Compare commits
No commits in common. "main" and "feat/b2b-custom-candle-requests" have entirely different histories.
main
...
feat/b2b-c
|
|
@ -23,16 +23,15 @@ steps:
|
|||
- name: Deploy
|
||||
image: appleboy/drone-ssh
|
||||
settings:
|
||||
host: manicandles-backend.midastix.com
|
||||
host: api.midastix.com
|
||||
username: manicandle-backend
|
||||
key:
|
||||
from_secret: server_ssh_pkey
|
||||
port: 22
|
||||
command_timeout: 3m
|
||||
script:
|
||||
- set -e
|
||||
- echo "Deploying manicandle-backend"
|
||||
- sudo -n /opt/deployable/manicandle-backend/docker/deploy.sh
|
||||
- sudo /opt/deployable/manicandle-backend/docker/deploy.sh
|
||||
- echo "Deployment completed"
|
||||
when:
|
||||
branch:
|
||||
|
|
|
|||
|
|
@ -14,10 +14,5 @@ RECOVERY_TTL_MINUTES=15
|
|||
# RECOVERY_URL=https://shop.example.com/reset
|
||||
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.
|
||||
# SWAGGER_ENABLED=true
|
||||
|
|
|
|||
|
|
@ -7,47 +7,27 @@ on:
|
|||
jobs:
|
||||
quality:
|
||||
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:
|
||||
postgres:
|
||||
image: postgres:17
|
||||
env:
|
||||
POSTGRES_USER: mani
|
||||
POSTGRES_PASSWORD: ${{ secrets.CI_POSTGRES_PASSWORD }}
|
||||
POSTGRES_PASSWORD: ci_only_password
|
||||
POSTGRES_DB: mani_ci
|
||||
options: >-
|
||||
--health-cmd "pg_isready -U mani -d mani_ci"
|
||||
--health-interval 5s --health-timeout 5s --health-retries 10
|
||||
env:
|
||||
DATABASE_URL: postgresql://mani:${{ secrets.CI_POSTGRES_PASSWORD }}@postgres:5432/mani_ci
|
||||
TEST_DATABASE_URL: postgresql://mani:${{ secrets.CI_POSTGRES_PASSWORD }}@postgres:5432/mani_ci
|
||||
DATABASE_URL: postgresql://mani:ci_only_password@postgres:5432/mani_ci
|
||||
TEST_DATABASE_URL: postgresql://mani:ci_only_password@postgres:5432/mani_ci
|
||||
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: Generate Prisma client
|
||||
run: pnpm db:generate
|
||||
- name: Validate native migration upgrade and schema drift
|
||||
run: node scripts/verify-migrations.mjs
|
||||
- name: Require native concurrency tests without skips
|
||||
run: pnpm test:native
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '24'
|
||||
- run: npm install --global pnpm@11.19.0
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: pnpm security:audit
|
||||
- run: pnpm db:generate
|
||||
- run: node scripts/verify-migrations.mjs
|
||||
- run: pnpm check
|
||||
|
|
|
|||
32
README.md
32
README.md
|
|
@ -68,35 +68,3 @@ B2B partner purchase orders: see [Phase 3G API guide](docs/b2b-partner-orders-ap
|
|||
B2B partner partial payments: see [Phase 3H API guide](docs/b2b-partner-payments-api.md).
|
||||
|
||||
B2B custom candle requests and staff review: see [Phase 3I API guide](docs/b2b-custom-candles-api.md).
|
||||
|
||||
B2B partner reports: see [Phase 3J API guide](docs/b2b-partner-reporting-api.md).
|
||||
|
||||
Private wishlists: see [Phase 4A API guide](docs/wishlist-api.md).
|
||||
|
||||
Verified product reviews and moderation: see [Phase 4B API guide](docs/product-reviews-api.md).
|
||||
|
||||
Seasonal campaigns and scheduled collection discovery: see [Phase 4C API guide](docs/seasonal-campaigns-api.md).
|
||||
|
||||
Campaign-linked collection discounts: see [Phase 4D API guide](docs/campaign-discounts-api.md).
|
||||
|
||||
Private idle cart recovery: see [Phase 4E API guide](docs/cart-recovery-api.md).
|
||||
|
||||
Explicit messaging consent and eligibility: see [Phase 4F API guide](docs/messaging-consent-api.md).
|
||||
|
||||
Blog drafts, publication and SEO metadata: see [Phase 4G API guide](docs/blog-publishing-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).
|
||||
|
||||
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).
|
||||
|
|
|
|||
|
|
@ -1,30 +0,0 @@
|
|||
# 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.
|
||||
|
|
@ -1,23 +0,0 @@
|
|||
# B2B partner reporting (Phase 3J)
|
||||
|
||||
`GET /api/v1/b2b/accounts/:id/report` requires a bearer session and the dedicated `b2b.report.read` permission. The account must belong to the caller's organization; missing or out-of-scope accounts return 404. A report is available even when an account has no orders or is not verified, so staff can inspect its history.
|
||||
|
||||
The response contains `accountId` and a `currencies` array sorted by currency code. Each currency contains:
|
||||
|
||||
| Field | Meaning |
|
||||
| ------------------------- | --------------------------------------------------------- |
|
||||
| `orderCount` | All partner orders, including cancelled orders |
|
||||
| `activeOrderCount` | Orders without cancellation |
|
||||
| `cancelledOrderCount` | Orders with a recorded cancellation |
|
||||
| `unpaidOrderCount` | Active orders with no unreversed receipts |
|
||||
| `partiallyPaidOrderCount` | Active orders paid above zero but below merchandise total |
|
||||
| `paidOrderCount` | Active orders with merchandise fully paid |
|
||||
| `merchandiseTotal` | Total merchandise value of active orders |
|
||||
| `paidTotal` | Unreversed receipts against active orders |
|
||||
| `outstandingTotal` | Active merchandise value minus unreversed receipts |
|
||||
|
||||
All amounts are exact decimal strings with two fractional digits. Different currencies are never combined or converted. Each order contributes once regardless of how many receipts it has. Reversals restore outstanding balances; cancelled orders retain their counts but contribute no financial totals. An account with no orders returns `{ "accountId": "<uuid>", "currencies": [] }`.
|
||||
|
||||
Reports cover all recorded history. A repeatable-read transaction provides a consistent account lookup and aggregate. Reads create no audit events and change no order/payment records. This is a merchandise-balance report; it does not establish credit utilization, overdue status, tax, shipping, refunds, gateway settlement, or accounting receivables.
|
||||
|
||||
The permission migration grants access to existing system Owner roles. Custom roles need an explicit RBAC grant. No schema, provider, or configuration change is required beyond deploying the append-only permission migration. Removing a custom role's report permission disables access; financial records remain intact.
|
||||
|
|
@ -1,30 +0,0 @@
|
|||
# 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.
|
||||
|
|
@ -1,28 +0,0 @@
|
|||
# Blog publishing and SEO metadata (Phase 4G)
|
||||
|
||||
Staff create and edit organization-scoped blog articles, explicitly publish reviewed draft versions, and withdraw content with a reason. Revisions to a published article remain private working text until publication replaces the public snapshot at its existing slug. This is the next provider-independent growth milestone while Instagram, Etsy and WhatsApp integrations remain deferred.
|
||||
|
||||
| Method | Route | Access |
|
||||
| ------ | ----------------------------------------------- | ----------------------------------------------------------------------------------- |
|
||||
| GET | `/api/v1/blog-articles` | `blog.read`; paginated staff records, optional `state` filter. |
|
||||
| GET | `/api/v1/blog-articles/:id` | `blog.read`; working text and latest publication metadata/snapshot. |
|
||||
| POST | `/api/v1/blog-articles` | `blog.manage`; create a draft. |
|
||||
| PATCH | `/api/v1/blog-articles/:id` | `blog.manage`; edit working text at its current version. |
|
||||
| POST | `/api/v1/blog-articles/:id/publication` | `blog.publish`; publish `{ "version": 0 }`. |
|
||||
| POST | `/api/v1/blog-articles/:id/withdrawal` | `blog.publish`; withdraw with `{ "reason": "Editorial correction needed" }`. |
|
||||
| GET | `/api/v1/storefront/:organizationId/blog` | Public, shared storefront rate limit; published article summaries and SEO metadata. |
|
||||
| GET | `/api/v1/storefront/:organizationId/blog/:slug` | Public, shared storefront rate limit; latest published text and SEO metadata. |
|
||||
|
||||
Create with `slug`, `title`, `summary`, `body`, and a UUID `idempotencyKey`. Slugs use the existing lowercase, hyphen-separated catalog convention and are permanent within an organization. Title is single-line plain text up to 160 characters, summary up to 500, and body multiline plain text up to 20,000. All are required and trimmed. HTML, angle brackets, and unsafe control characters are rejected; body line breaks and tabs are supported. PATCH accepts the current `version` and at least one of title/summary/body. Identity, slug, scope, lifecycle metadata, and public snapshot are never client-editable.
|
||||
|
||||
Creation retries with the same key and normalized input return the same article; changed input returns `IDEMPOTENCY_CONFLICT` (409). Duplicate organization/slug returns `RECORD_CONFLICT` (409). Successful edits increment version and record `blog.updated`. Publishing checks the reviewed version, copies title/summary/body into the public snapshot, records publication version/time/staff, increments the working version, and audits `blog.published`. Repeating the **latest** successful publication version makes no new changes or audit record. Older publication commands after republishing return `BLOG_CHANGED` (409). An exact latest-publication retry after further draft edits leaves those edits unpublished. Editors do not require publication permission to save private changes.
|
||||
|
||||
Public responses expose only slug, published title/summary, publication date, and `seo: { title, description }` derived from that snapshot. Detail adds published `body`; list omits body and uses existing limit/offset pagination. Draft content, staff identities, internal scope, keys, hashes, and version counters are absent. Draft, withdrawn, and foreign-organization detail requests return `BLOG_NOT_FOUND` (404). Staff reads are separately permission-gated, and all writes recheck live session and permission inside the existing organization lock.
|
||||
|
||||
Withdrawal is terminal, immediate, and reasoned; it does not erase the last public snapshot or audit evidence. Repeating the same reason is safe; a different reason, edit, or publication after withdrawal returns `BLOG_STATE_CONFLICT` (409). The slug remains reserved. Public routing no longer exposes withdrawn records. Replace an irreversibly withdrawn article with a new slug when needed.
|
||||
|
||||
The frontend must render body as text, preserving paragraphs, and escape all text used in HTML metadata. This API supplies content and metadata; it does not render pages, generate HTML/Markdown, invent a canonical domain, submit a sitemap, or guarantee search indexing/ranking. Frontend canonical links, sitemap/robots integration, rich text, media and structured data are separate delivery work.
|
||||
|
||||
Deploy the additive table/type migration before the application. Existing system Owners gain `blog.read`, `blog.manage`, and `blog.publish`; custom roles require explicit grants. Scoped staff foreign keys, unique slugs/creation keys, native revision/transition guards, and exact snapshot checks protect persistence. Deletes and withdrawn-record rewrites are rejected. Prior migrations remain unchanged. Older code ignores this table; preserve article rows and audit events on rollback.
|
||||
|
||||
The latest public snapshot is retained, while the audit trail records editorial actions without storing old article bodies. Full revision history and restoration can be added when editorial rollback is required. Verification covers unpublished/draft privacy, live text separation, republication, metadata projection, independent permissions, scoped access, plain-text/size validation, stale and concurrent commands, creation retries, reasoned withdrawal, native snapshot/delete guards, and migration drift. Native multi-connection concurrency verification remains dependent on the existing PostgreSQL CI setup.
|
||||
|
|
@ -1,17 +0,0 @@
|
|||
# Campaign discounts (Phase 4D)
|
||||
|
||||
Campaign offers reuse existing coupons and exact checkout money rules. A campaign can have one coupon, created while the campaign is a draft. Coupon terms and association are immutable; the existing coupon status endpoint can pause/resume the code. Configure the campaign window first, then its coupon, then publish the updated campaign version.
|
||||
|
||||
`POST /api/v1/coupons` accepts the existing fixed/percentage coupon body plus optional `campaignId` and `campaignVersion`. Both must be supplied together. Linking requires `coupons.manage` and `campaigns.manage`, a draft in the caller's organization, and its current version. The coupon's start/end must fit inside the campaign window. Successful creation increments campaign version atomically, preventing publication of an offer not seen in the staff member's last read. Existing unlinked coupon requests retain their behavior.
|
||||
|
||||
Draft edits must keep the campaign window around its linked coupon. Terms cannot be replaced by another code in this milestone; create a new campaign/code for a different offer. The code remains the coupon creation identity; duplicate code or campaign association returns a conflict. No existing applied migration is edited.
|
||||
|
||||
Public campaign responses gain an optional `offer` with code, currency, kind, fixed amount/percentage basis points, minimum subtotal, and coupon start/end dates. It appears only when both the campaign and coupon are active and within their windows. Usage limits and per-customer eligibility remain authoritative at checkout; published terms do not promise a reservation or remaining use. Internal coupon IDs and usage counts are not public.
|
||||
|
||||
Customers continue submitting one `couponCode` to the existing checkout endpoint. A linked code additionally requires an active published campaign and a current collection. Only cart variants belonging to that collection contribute to the discount base and minimum-spend test. Other cart lines keep their full price. Percentage rounding and fixed-amount caps use the existing minor-unit arithmetic. No matching lines, draft/future/ended/cancelled campaigns, wrong currency, disabled/expired coupons, and exhausted limits fail before order/stock/cart writes.
|
||||
|
||||
New campaign-coupon order snapshots also retain campaign ID/slug, collection ID, campaign/coupon windows, eligible variant IDs, and exact eligible subtotal. These facts are frozen alongside coupon/price snapshots. Retrying a successful checkout returns its original order even after campaign cancellation or coupon disablement. New attempts use current eligibility. Order cancellation/expiry retain the existing usage-release behavior. Payment enablement, tax, shipping and gateway behavior do not change.
|
||||
|
||||
Acceptance: collection-only discounts in mixed carts; exact fixed/percentage amounts; scoped binding and version checks; window compatibility; public offer privacy; campaign/coupon cancellation gates; coupon quotas; checkout rollback/idempotency; immutable linkage and order evidence; unchanged generic coupons.
|
||||
|
||||
Deploy the additive migration before the application. Existing coupons receive a null campaign link and remain generic. New scoped foreign keys/unique constraints prevent cross-organization or duplicate binding; native guards freeze linked coupon terms and prevent invalid linked campaign rescheduling. Rollback to older code requires disabling campaign-linked coupons first so an older checkout cannot treat them as generic coupons. Preserve rows, order snapshots and audit history. No new dependencies or provider accounts are required.
|
||||
|
|
@ -1,23 +0,0 @@
|
|||
# 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.
|
||||
|
|
@ -1,20 +0,0 @@
|
|||
# Private cart recovery (Phase 4E)
|
||||
|
||||
Authenticated customers can resume their persisted cart after at least 24 hours without a successful cart edit, recovery, or checkout. Cart reads and failed commands do not refresh activity. A cart must contain at least one line and have a known activity timestamp. This milestone provides in-app recovery; outbound reminders require the later consent-aware messaging milestone.
|
||||
|
||||
All routes use the caller's live active session and own organization/user scope. No staff permission, user ID parameter, public token, customer directory, or new provider is involved. Existing access rate limits apply.
|
||||
|
||||
| Method | Route | Behavior |
|
||||
| ------ | ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| GET | `/api/v1/cart/recovery` | Returns `version`, nullable `lastActivityAt`, `recoverable`, and current lines; does not create a cart or change activity. |
|
||||
| POST | `/api/v1/cart/recovery` | Strict body `{ "version": 1 }`; resumes the eligible cart at its current version. Returns 201 with the next `version` and `removedVariantIds`. |
|
||||
|
||||
Each preview line contains `variantId`, `quantity`, `available`, and `variant`. Available variants expose current name, SKU, decimal price, currency, and product name. Inactive variants and unpublished products return `available: false, variant: null`; their private catalog details are redacted. The response contains no user profile or contact details.
|
||||
|
||||
The customer explicitly confirms removal of unavailable lines when posting recovery. Resumption rechecks catalog availability, preserves all available quantities, removes unavailable lines atomically, refreshes activity, increments the cart version once, and appends `cart.recovered` to the audit trail. A competing edit, checkout, or recovery is serialized by the existing organization lock. Stale versions return `CART_CHANGED` (409); empty, undated, or recently active carts return `CART_NOT_RECOVERABLE` (409). Invalid bodies return 400; missing/inactive sessions are rejected by the existing access guard. A lost successful response is resolved by reading the new version, rather than blindly retrying the old command.
|
||||
|
||||
Availability means currently active and published merchandise, not a stock reservation. Recovery neither freezes prices nor copies coupons from earlier orders. Checkout remains authoritative for current prices, currency consistency, campaign/coupon eligibility, stock, and immutable order snapshots. Customers can edit the recovered cart with the existing versioned cart endpoints.
|
||||
|
||||
Deploy the additive nullable `last_activity_at` migration before the application. Existing carts retain all lines but have unknown historical activity; they become eligible only after a new successful cart edit followed by 24 idle hours. This avoids inventing old activity timestamps. No historical migrations are edited. Older code ignores the new column; if rolling back and later re-enabling recovery, clear timestamps for carts that may have been edited by the older code before enabling recovery again. Preserve cart lines, orders, and audit history.
|
||||
|
||||
Acceptance covers the exact 24-hour boundary, empty/unknown/future activity, current prices, read-only activity semantics, customer and organization isolation, schema validation, stale and concurrent commands, audit uniqueness, inactive/unpublished redaction and removal, and edit/checkout reset. Native PostgreSQL concurrency checks remain subject to the project's existing CI database setup.
|
||||
|
|
@ -1,26 +0,0 @@
|
|||
# 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,13 +25,3 @@ 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.
|
||||
|
||||
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,25 +0,0 @@
|
|||
# Live customer segmentation (Phase 4H)
|
||||
|
||||
Staff can inspect three fixed, live segments based on current commerce records. Accounts must be active and belong to the caller's organization. Membership contains only account IDs, not names, contacts, addresses, purchase evidence, or cart/wishlist contents. Accounts with staff roles are included if they have the same qualifying commerce activity; the current identity model has no separate customer-only account type.
|
||||
|
||||
| Segment key | Definition |
|
||||
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `WISHLIST_INTEREST` | At least one saved wishlist variant is currently active and its product published. Multiple saved items count the account once. |
|
||||
| `RECOVERABLE_CART` | A nonempty cart has a known activity timestamp at least 24 hours old, using the same cutoff as private cart recovery. Empty/undated/recently edited carts are excluded. Catalog/stock eligibility remains authoritative at recovery and checkout. |
|
||||
| `VERIFIED_BUYER` | At least one unrevoked external purchase verification exists under the verified-review evidence workflow. Pending-payment orders and cancelled orders do not establish completed purchase evidence. |
|
||||
|
||||
`GET /api/v1/customer-segments` requires `segments.read` and returns `asOf` plus a `segments` array of `{ key, description, total }`. The groups can overlap; their counts should not be summed to infer unique customers. No account without the qualifying evidence is included merely because it is active.
|
||||
|
||||
`GET /api/v1/customer-segments/:segment/members` requires `segments.read` and returns `{ segment, asOf, total, members: [{ userId }] }`. Members are distinct and ordered by UUID ascending. `limit` defaults to 25 with a maximum of 100, and `offset` defaults to zero with a maximum of 10,000. `total` is the complete filtered count, not the size of this page. Unknown segment keys, invalid pagination, scope overrides, and extra query fields return 400. Missing sessions return 401; missing permission returns 403.
|
||||
|
||||
Both routes optionally accept `channel=EMAIL&purpose=PROMOTIONS` (also `WHATSAPP` and `CART_RECOVERY`). Supply both fields together. This intersects the segment with the latest explicit grant for that channel and purpose; absent consent and later withdrawal exclude the account. A grant for another channel/purpose does not qualify, and replaying an old grant after withdrawal does not restore membership. Consent-filtered reads additionally require the caller's **live** `messaging.read` permission, preventing consent disclosure through a segment-only role.
|
||||
|
||||
Inactive accounts, unavailable wishlist merchandise, cart edits/clearing, and purchase-evidence revocation affect the next read immediately. Reads recheck the staff session and permissions inside the existing organization-locked transaction. One server time is used across each response's segment checks; total and page use the same query predicate. Source API writes share the lock. Different requests/pages are live evaluations and can change between reads; `asOf` is an evaluation timestamp, not a persistent audience snapshot or paging token.
|
||||
|
||||
All SQL values are bound parameters. Fixed predicate fragments use scoped joins and `EXISTS`, so multiple qualifying source records do not duplicate accounts. Queries use the existing user, wishlist, cart, verification, and consent indexes. No materialized audience, copied contact list, custom rule DSL, saved segment, scheduler, CSV export, or provider delivery is introduced. Keep live reads until measured dataset size and query latency justify cached/materialized audiences.
|
||||
|
||||
These are staff analysis and planning APIs, not permission to deliver messages. Future adapters must recheck live consent, recipient status/contact ownership, channel policy, campaign/cart eligibility and suppressions at dispatch and retries. A filtered preview can become stale after withdrawal. Existing transactional notifications and customer preferences are unchanged.
|
||||
|
||||
Deploy the additive permission migration before the application. Existing system Owners gain `segments.read`; custom roles remain explicit. There are no new audience tables or schema changes. Existing migrations and source evidence remain unchanged. Older code ignores the new permission; rollback preserves all commerce records and consent history. Existing native PostgreSQL CI requirements continue to apply.
|
||||
|
||||
Verification covers deduplication, live catalog/account changes, shared recovery timing and empty/undated carts, revoked purchase evidence, unpaid-order exclusion, newest consent and stale-grant replay, channel/purpose isolation, separate permissions, organization isolation, strict inputs, pagination, private projections, migration drift, and prior recovery regressions.
|
||||
|
|
@ -1,32 +0,0 @@
|
|||
# Moderated community discussions (Phase 5A)
|
||||
|
||||
Active accounts can submit immutable discussion threads and flat replies. Everything begins pending and stays private until an independent staff moderator approves it. Customers explicitly choose the public display alias; the application never substitutes their account name or contact details. Submission and moderation history remain append-only.
|
||||
|
||||
| Method | Route | Access |
|
||||
| ------ | ------------------------------------------------------ | --------------------------------------------------------------------------------- |
|
||||
| POST | `/api/v1/forum/threads` | Active session; create a pending thread. |
|
||||
| POST | `/api/v1/forum/threads/:id/replies` | Active session; create a pending reply under an available approved thread. |
|
||||
| GET | `/api/v1/forum/posts` | Active session; own submissions and moderation status, paginated. |
|
||||
| GET | `/api/v1/forum-moderation` | `forum.read`; scoped queue/history with optional `status` and `threadId` filters. |
|
||||
| POST | `/api/v1/forum-moderation/:id/decision` | `forum.moderate`; approve, reject, or hide with an immutable reason. |
|
||||
| GET | `/api/v1/storefront/:organizationId/forum` | Public; available approved threads. |
|
||||
| GET | `/api/v1/storefront/:organizationId/forum/:id` | Public; one available approved thread. |
|
||||
| GET | `/api/v1/storefront/:organizationId/forum/:id/replies` | Public; available approved replies under that thread. |
|
||||
|
||||
Thread input is `{ "title": "Candle care question", "displayName": "Candle fan", "body": "How do I care for my candle?", "idempotencyKey": "<uuid>" }`. Replies omit `title`; reply targets must be root threads, not other replies. Title is 3–160 single-line characters, alias 1–80, and body 10–5,000 with line breaks/tabs supported. All text is trimmed, bounded plain text; HTML and unsafe control characters are rejected. Identity, organization, timestamps, and moderation metadata are never client-editable. Frontends must render/escape content as text.
|
||||
|
||||
Each account may have at most 20 pending posts across threads/replies in its organization. Existing authentication and request rate limits also apply. Moderation releases pending capacity; approved posts do not consume that quota. Submission retries with the same account/key and normalized input return the existing post/current status without another audit event. Changed input, including a different parent thread, returns `IDEMPOTENCY_CONFLICT` (409). Exact reply retries remain readable by their author even if the parent later becomes unavailable, without creating or publishing content.
|
||||
|
||||
Own responses contain only post ID, thread ID, alias, title/body, submission date, and `moderationStatus`. Staff queue/decision responses additionally provide author ID, current account status, and moderation records/notes. `forum.read` and `forum.moderate` are separate permissions; self-moderation returns `FORUM_SELF_MODERATION` (403) even for Owners. Existing system Owners gain both permissions; custom roles remain explicit.
|
||||
|
||||
Moderation input is `{ "decision": "APPROVED", "note": "Content checked by staff", "idempotencyKey": "<uuid>" }`, with note 3–1,000 characters. Pending posts can receive one approval or rejection; only approved posts can subsequently be hidden. Rejection and hiding are terminal. Invalid transitions return `FORUM_MODERATION_STATE` (409); inactive authors cannot be approved (`FORUM_AUTHOR_INACTIVE`, 409). Approval of a reply also requires a currently available root thread. Exact latest or historical decision-key retries return the current record without repeating decisions or audits; changed commands return `IDEMPOTENCY_CONFLICT` (409).
|
||||
|
||||
Public queries require approval, no hiding event, and an active author. Replies additionally require the parent thread to meet those conditions. Hiding a root therefore removes it and every reply from public discovery without rewriting reply evidence. Public responses expose only IDs/parent IDs, chosen alias, title/body and submission date; account IDs, profile/contact information, staff notes, decision history, hashes and keys are absent. Missing, private, unavailable, reply-as-thread, and foreign-scope roots return `FORUM_NOT_FOUND` (404). All public routes use the existing shared storefront rate limit and pagination (default 25, maximum 100; offset maximum 10,000).
|
||||
|
||||
Writes recheck live account/permission inside the existing organization lock. Native guards serialize pending quotas, require scoped approved root targets, reject self-moderation, enforce decision sequence/transitions, and freeze both submissions and decisions. Audit actions are `forum.submitted`, `forum.approved`, `forum.rejected`, and `forum.hidden`. Publishing or hiding occurs through evidence append, with no mutable status flag to bypass moderation.
|
||||
|
||||
Deploy the additive enum/tables/permission migration before the application. Composite user/parent/post foreign keys enforce organization scope. Existing migrations and commerce records are untouched. Older code ignores the new tables; preserve submission, moderation, and audit history on rollback. Shared multiline validation preserves blog behavior.
|
||||
|
||||
This milestone provides moderated flat discussions, not editing/deletion, nested replies, categories, attachments, voting, reporting/appeals, moderator restoration, realtime chat, outbound notifications, or a forum frontend. Immutable posts avoid edits bypassing review; customers can submit corrected text under a fresh key. Additional community delivery work can follow actual usage and policy decisions.
|
||||
|
||||
Verification covers private pending submissions, independent moderation, public alias projection, separately moderated replies, parent hiding/inactive authors, scoped access, replay conflicts, immutable native records, pending quotas, competing decisions, strict text/shape validation, schema drift, and prior blog validation. Multi-connection native PostgreSQL CI remains subject to the existing test setup.
|
||||
|
|
@ -1,27 +1,26 @@
|
|||
# Phase 1B: identity and access API
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
## Endpoints
|
||||
|
||||
| Method | Path | Permission | Request / result |
|
||||
| ------ | ---------------------- | ------------------ | ------------------------------------------------------------------------------------------------ |
|
||||
| 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 |
|
||||
| POST | /auth/logout | Authenticated | Revoke current session; 204 |
|
||||
| POST | /auth/logout-all | Authenticated | Revoke all current user sessions; 204 |
|
||||
| POST | /auth/recovery/request | Public; throttled | organizationId, email → generic 202; 503 if SMTP is unconfigured |
|
||||
| POST | /auth/recovery/reset | Public; throttled | token, password → 204; token expires and can be consumed once |
|
||||
| GET | /users | users.read | Paginated safe user records |
|
||||
| POST | /users | users.create | name, email, password → PENDING account |
|
||||
| PATCH | /users/:id/status | users.approve | status: ACTIVE or SUSPENDED |
|
||||
| PATCH | /users/:id/roles | users.roles.assign | roleIds: UUID array; replaces assignments |
|
||||
| GET | /roles/permissions | roles.read | Current permission catalogue |
|
||||
| GET | /roles | roles.read | Paginated roles |
|
||||
| POST | /roles | roles.manage | name, permissions |
|
||||
| PATCH | /roles/:id | roles.manage | Complete replacement of name and permissions |
|
||||
| GET | /audit-events | audit.read | Paginated append-only organization audit history |
|
||||
| Method | Path | Permission | Request / result |
|
||||
| ------ | ---------------------- | ------------------ | ------------------------------------------------------------------- |
|
||||
| POST | /auth/login | Public; throttled | organizationId, email, password → accessToken, tokenType, expiresAt |
|
||||
| GET | /auth/me | Authenticated | userId, organizationId, sessionId, effective permissions |
|
||||
| POST | /auth/logout | Authenticated | Revoke current session; 204 |
|
||||
| POST | /auth/logout-all | Authenticated | Revoke all current user sessions; 204 |
|
||||
| POST | /auth/recovery/request | Public; throttled | organizationId, email → generic 202; 503 if SMTP is unconfigured |
|
||||
| POST | /auth/recovery/reset | Public; throttled | token, password → 204; token expires and can be consumed once |
|
||||
| GET | /users | users.read | Paginated safe user records |
|
||||
| POST | /users | users.create | name, email, password → PENDING account |
|
||||
| PATCH | /users/:id/status | users.approve | status: ACTIVE or SUSPENDED |
|
||||
| PATCH | /users/:id/roles | users.roles.assign | roleIds: UUID array; replaces assignments |
|
||||
| GET | /roles/permissions | roles.read | Current permission catalogue |
|
||||
| GET | /roles | roles.read | Paginated roles |
|
||||
| POST | /roles | roles.manage | name, permissions |
|
||||
| PATCH | /roles/:id | roles.manage | Complete replacement of name and permissions |
|
||||
| GET | /audit-events | audit.read | Paginated append-only organization audit history |
|
||||
|
||||
List queries accept `limit` (1–100, default 25) and `offset` (0–10000, default 0). Unknown fields, malformed UUIDs, duplicate role assignments/permissions and unknown permissions are rejected. Errors use Nest's JSON error contract: 400 invalid input, 401 unauthenticated, 403 denied, 404 missing/out-of-scope target, 409 duplicate record, 429 throttled, 503 unavailable.
|
||||
|
||||
|
|
@ -37,7 +36,7 @@ Example login:
|
|||
|
||||
## Access rules
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
|
|
|
|||
|
|
@ -1,26 +0,0 @@
|
|||
# Consent-aware messaging (Phase 4F)
|
||||
|
||||
Customers explicitly choose optional promotions and cart recovery reminders for email and WhatsApp independently. All four preferences default to off. Preferences are self-service; staff can check eligibility but cannot grant consent on a customer's behalf. The existing order outbox and account-recovery mail retain their separate transactional contracts.
|
||||
|
||||
| Method | Route | Access and result |
|
||||
| ------ | ------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------- |
|
||||
| GET | `/api/v1/messaging/preferences` | Own active session; current notice texts and four current channel/purpose preferences. |
|
||||
| POST | `/api/v1/messaging/preferences` | Own active session; append a versioned grant or withdrawal and return its receipt plus the current preference. |
|
||||
| GET | `/api/v1/messaging/preferences/history` | Own active session; immutable receipts, newest first, with existing `limit`/`offset` pagination. |
|
||||
| GET | `/api/v1/messaging/eligibility/:userId?channel=EMAIL&purpose=PROMOTIONS` | `messaging.read`; scoped recipient's current preference and eligibility. |
|
||||
|
||||
To grant, send `{ "channel": "EMAIL", "purpose": "PROMOTIONS", "granted": true, "version": 0, "noticeVersion": "2026-10-07", "idempotencyKey": "<uuid>" }`. Supported channels are `EMAIL` and `WHATSAPP`; supported purposes are `PROMOTIONS` and `CART_RECOVERY`. The UI must show the returned notice for the selected purpose and channel before submitting a customer's affirmative choice. Never preselect opt-in or infer consent from an order, login, wishlist, cart activity, review, or business verification.
|
||||
|
||||
To withdraw, send the same channel/purpose with `granted: false`, the current `version`, and a fresh `idempotencyKey`, omitting `noticeVersion`. Withdrawal requires no notice agreement. Bodies are strict: no target user, contact data, arbitrary purpose, or client timestamp is accepted. All successful decisions, including repeated choices with new keys, append the next revision and a `messaging.consent.recorded` audit event atomically. Timestamps come from the server/database; notice versions and decision receipts are retained as evidence.
|
||||
|
||||
Each channel/purpose has its own version starting at zero. Stale writes return `CONSENT_CHANGED` (409). Reusing a key with changed input returns `IDEMPOTENCY_CONFLICT` (409). Exact retries return the original immutable `decision` and the **live** `current` preference, so replaying an old grant after withdrawal cannot revive consent or imply current eligibility. Receipt/history responses omit user profile, contact details, internal organization/user scope, hashes, and idempotency keys.
|
||||
|
||||
Staff eligibility returns `channel`, `purpose`, `granted`, `version`, and `eligible`. Eligibility requires a current grant and an active recipient in the staff member's organization. Missing/foreign recipients return `MESSAGING_RECIPIENT_NOT_FOUND` (404), unauthorized staff return 403, and inactive customer sessions cannot change preferences. The additive migration grants `messaging.read` to existing system Owners; custom roles remain explicit.
|
||||
|
||||
The shared `messagingEligibility` function reads the latest decision and live recipient status. A staff preview is not a delivery authorization: future adapters must recheck this gate inside the existing serialized dispatch transaction, including retries, and also validate recipient contact ownership, provider/channel policy, suppression and content eligibility. Consent withdrawal must suppress unsent optional messages. Recovery messages additionally need a currently recoverable cart; promotions need current campaign eligibility. Consent alone does not prove a verified email or WhatsApp destination.
|
||||
|
||||
This milestone stores preferences and exposes the reusable eligibility gate. It sends no messages and adds no provider credentials, contact directory, campaign audience export, guest unsubscribe tokens, templates, scheduler, or promotional outbox. Those belong with enabled provider delivery; existing transactional notifications are not converted into promotional messages.
|
||||
|
||||
Deploy the new table and permission migration before the application. Existing accounts remain opted out with no inferred decisions. Composite user/organization foreign keys enforce scope; native checks validate terms, a serialized insert guard enforces consecutive revisions, and update/delete triggers protect immutable evidence. No historical migration is changed. Older application code ignores the table; preserve decisions and audit evidence on rollback, and keep optional delivery disabled until it uses the consent gate.
|
||||
|
||||
Verification covers default-off and purpose/channel isolation, explicit notice requirements, strict schemas, withdrawal without agreement, stale/conflicting retries, old-grant replay, scoped permission checks, inactive recipients, competing revisions, privacy-preserving history, immutable database records, and migration drift. Multi-connection PostgreSQL verification remains dependent on the project's existing native CI setup.
|
||||
|
|
@ -1,28 +0,0 @@
|
|||
# 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.
|
||||
|
|
@ -1,56 +0,0 @@
|
|||
# Verified product reviews (Phase 4B)
|
||||
|
||||
Purchase eligibility uses **manual staff verification of external completed-purchase evidence**, as selected for this milestone. It does not infer a purchase from a pending checkout, reserve stock, change order status, or claim gateway/delivery verification. Public reviews identify the method as `MANUAL`.
|
||||
|
||||
| Method | Path under `/api/v1` | Access |
|
||||
| ------ | --------------------------------------------------------- | -------------------------------------------------------------------- |
|
||||
| GET | `/reviews/eligibility` | Active user; own eligible verification IDs/variant IDs/dates |
|
||||
| GET | `/reviews` | Active user; own submissions and computed moderation status |
|
||||
| POST | `/reviews` | Active user; submit against own active verification |
|
||||
| GET | `/review-verifications` | `reviews.verify`; optional `userId`, `variantId` filters |
|
||||
| POST | `/review-verifications` | `reviews.verify`; record checked external purchase evidence |
|
||||
| POST | `/review-verifications/:id/revoke` | `reviews.verify`; permanently revoke incorrect evidence |
|
||||
| GET | `/review-moderation` | `reviews.read`; optional `variantId`, `status` filters |
|
||||
| POST | `/review-moderation/:id/decision` | `reviews.moderate`; approve/reject, or hide an approved review |
|
||||
| GET | `/storefront/:organizationId/products/:productId/reviews` | Public, shared storefront rate limit; approved verified reviews only |
|
||||
|
||||
All list endpoints use `limit` (1–100, default 25) and `offset` (0–10,000, default 0). Private resources are scoped to the authenticated organization; customers cannot read another user's eligibility or submissions. Unknown input fields are rejected.
|
||||
|
||||
Staff first check external evidence for the specific active customer and variant, then submit:
|
||||
|
||||
```json
|
||||
{
|
||||
"userId": "b92c23e5-794d-47e7-a7f4-428b84543fa1",
|
||||
"variantId": "983a3a76-b3b7-4a63-9796-1393a63c2e0b",
|
||||
"reference": "EXTERNAL-RECEIPT-123",
|
||||
"note": "Receipt and completed purchase checked",
|
||||
"idempotencyKey": "10fc5585-34a6-4ead-b5ce-d83418eb50df"
|
||||
}
|
||||
```
|
||||
|
||||
The verifier must differ from the customer. References are exact, trimmed identifiers (3–100 characters), unique per organization and variant, so one receipt may cover different variants but cannot be reassigned to multiple customers for the same variant. Notes require 3–1,000 characters. Historical variants can receive verification records, but new reviews require an active variant and published product.
|
||||
|
||||
Customer submission example:
|
||||
|
||||
```json
|
||||
{
|
||||
"verificationId": "62386f2a-4a74-4de2-93cc-ab60490c33e2",
|
||||
"rating": 5,
|
||||
"displayName": "Candle customer",
|
||||
"title": "Lovely fragrance",
|
||||
"body": "The candle burns evenly and smells wonderful.",
|
||||
"idempotencyKey": "4aeec80a-4a4b-4d72-9b44-b385b2d06147"
|
||||
}
|
||||
```
|
||||
|
||||
Rating is an integer 1–5. Display name is an explicit public alias of 1–80 characters, title 3–160, body 10–2,000. Text is trimmed, plain single-line text. The API publishes the supplied alias rather than the user's private account name or email. One immutable submission is allowed per customer/organization/variant, even with repeated purchases. Editing, replacement after rejection, and customer withdrawal are outside this milestone; staff can hide approved content.
|
||||
|
||||
Moderation body: `{ "decision": "APPROVED", "note": "Content checked", "idempotencyKey": "<uuid>" }`. `REJECTED` is also allowed for a pending submission. A different staff member must moderate the customer's review. An approved review may receive one `HIDDEN` decision; hidden/rejected content cannot be republished. Notes require 3–1,000 characters. Revoked purchase evidence prevents approval. Moderation history is immutable and ordered; status is computed as `PENDING`, `APPROVED`, `REJECTED`, or `HIDDEN`.
|
||||
|
||||
Revocation body: `{ "reason": "Evidence was invalidated", "idempotencyKey": "<uuid>" }`, with a 3–1,000-character reason. Revoking evidence blocks new submissions and immediately excludes any associated review from public results. It does not rewrite moderation history. Customers' own review responses expose `purchaseVerified: false` after revocation.
|
||||
|
||||
Public responses include only review ID, variant ID, rating, explicit display name, title, body, creation date, `verifiedPurchase: true`, and `verificationMethod: "MANUAL"`. No customer/account identifiers, evidence references, staff notes, hashes, or moderation history are exposed. Public publication additionally requires a currently published product and active variant. Missing/private products return 404; a published product with no eligible reviews returns an empty array.
|
||||
|
||||
Each write uses a UUID idempotency key. Verification/revocation/moderation namespaces are separately organization-scoped; submissions are customer/organization-scoped. Identical retries return the current record; changed content returns a specific 409 replay conflict. Retries do not duplicate audit events. Self-verification/moderation and missing permissions return 403; scoped misses return 404; duplicate submissions, revoked eligibility, and invalid transitions return 409.
|
||||
|
||||
Deploy the append-only migration before the application. It adds four tables, scoped foreign keys, unique constraints, rating/text checks, immutable-record guards, and moderation/verification transition guards. Existing system Owner roles receive `reviews.verify`, `reviews.read`, and `reviews.moderate`; custom roles need explicit grants. Evidence references and notes are available only through the verification permission. Moderation queues expose the customer ID and decision history but omit evidence references and notes. Existing checkout/payment/provider behavior remains unchanged.
|
||||
|
|
@ -1,42 +0,0 @@
|
|||
# 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.
|
||||
|
|
@ -48,36 +48,14 @@ Business verification, price lists, MOQ, quotations, credit policies, samples, b
|
|||
- 3H (implemented): manual, partial external receipt records for partner orders with exact merchandise-balance checks, idempotent reversals, and cancellation protection. Gateway collection, refunds, tax, shipping, and credit utilization remain separate milestones.
|
||||
- 3I (implemented): verified-account custom candle specifications with immutable request capture, independent one-time staff review, scoped permissions, and idempotent retries. Quotation, artwork approval, BOM, and production linkage remain separate milestones.
|
||||
|
||||
- 3J (implemented): read-only partner order and payment summaries by currency, with exact outstanding merchandise balances, reversal/cancellation handling, and dedicated report permissions. Credit utilization, overdue receivables, and accounting remain separate milestones.
|
||||
|
||||
## Phase 4: Growth channels
|
||||
|
||||
Wishlist, verified reviews/moderation, seasonal campaigns, discounts, cart recovery, consent-aware messaging, Instagram, Etsy, WhatsApp, blogs/SEO and segmentation.
|
||||
|
||||
- 4A (implemented): private user wishlists with published-variant eligibility, duplicate-safe saves, repeatable removal, paginated current catalog views, unavailable-item redaction, and a per-user quota. Public sharing, guest lists, cart conversion, and notifications remain separate milestones.
|
||||
- 4B (implemented): customer reviews gated by independent staff verification of external purchase evidence, immutable submissions, independent approval/rejection/hiding, evidence revocation, and a privacy-preserving public feed. Automated checkout/payment verification, review revisions, and rating analytics remain separate milestones.
|
||||
- 4C (implemented): organization-scoped seasonal campaign drafts, versioned editing/publication, immutable published terms, reasoned cancellation, and time-windowed public collection discovery. Campaign discounts, media assets, outbound messaging, and channel integrations remain separate milestones.
|
||||
- 4D (implemented): draft-bound campaign coupons, version-aware offer publication, public offer terms, and collection-only fixed/percentage checkout discounts with exact eligible-subtotal snapshots. Generic coupons retain their behavior; payment enablement, media assets and messaging remain separate milestones.
|
||||
- 4E (implemented): private discovery and versioned resumption of carts idle for 24 hours, current catalog previews, unavailable-item redaction/removal, and audited activity tracking. Outbound recovery reminders remain dependent on consent-aware messaging and provider enablement.
|
||||
- 4F (consent and eligibility implemented; live delivery deferred): explicit, independent email/WhatsApp opt-in and withdrawal for promotions/cart reminders, immutable versioned evidence, private history, and scoped live eligibility checks. Provider delivery, verified channel destinations, suppression-aware dispatch and unsubscribe links remain separate milestones.
|
||||
- 4G (backend implemented): versioned blog drafts, separate publication permission, stable-slug public snapshots, private revisions, reasoned withdrawal, and public SEO metadata. Frontend pages, sitemap/canonical integration, rich text/media and historical revision restoration remain separate milestones; live channel integrations remain deferred.
|
||||
- 4H (implemented): live staff segmentation for wishlist interest, recoverable carts and externally verified buyers, with deduplicated scoped account IDs/counts and optional separately permissioned current-consent filtering. Saved/custom rules, materialized audiences, exports and provider dispatch remain separate milestones.
|
||||
|
||||
## Phase 5: Community and optimization
|
||||
|
||||
Moderated forums, advanced analytics, forecasts, accounting adapters, profitability and workflow automation. SaaS tenancy/billing requires a separate architecture decision before implementation; an organization table alone does not provide tenant isolation.
|
||||
|
||||
- 5A (backend implemented): immutable discussion threads and flat replies, independent append-only approval/rejection/hiding, private author history, public alias-only discovery, parent visibility gates, and pending-submission quotas. Forum UI, editing/appeals, media, realtime features and notifications remain separate milestones.
|
||||
- 5B (implemented): bounded UTC daily checkout activity and frozen variant-demand analytics, current-state/currency separation, exact snapshot values, scoped reporting permissions, and UTC application sessions. Paid/fulfilled revenue, financial recognition, forecasts, cross-channel analytics and dashboard UI remain separate milestones.
|
||||
- 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
|
||||
|
||||
Small cohesive files; no duplicated business rules; unit tests for success, failure and boundaries; HTTP/integration tests where behavior crosses boundaries; schema migration and upgrade validation when persistence changes; documented API and permission contract; passing checks; focused Conventional Commit; reviewed pull request. Do not mark an entire phase complete until its end-to-end acceptance criteria pass.
|
||||
|
|
|
|||
|
|
@ -1,32 +0,0 @@
|
|||
# Seasonal campaigns (Phase 4C)
|
||||
|
||||
Seasonal campaigns promote existing catalog collections during an explicit time window. They contain public title/summary copy and a collection link. Collection membership remains live; checkout prices and coupon eligibility continue to use the existing commerce rules.
|
||||
|
||||
| Method | Path under `/api/v1` | Access |
|
||||
| ------ | --------------------------------------------- | --------------------------------------------------------------------- |
|
||||
| GET | `/campaigns` | `campaigns.read`; optional persisted `state` filter |
|
||||
| GET | `/campaigns/:id` | `campaigns.read`; scoped campaign and live status |
|
||||
| POST | `/campaigns` | `campaigns.manage`; create draft with a reusable UUID idempotency key |
|
||||
| PATCH | `/campaigns/:id` | `campaigns.manage`; edit draft with its current version |
|
||||
| POST | `/campaigns/:id/publication` | `campaigns.manage`; publish/schedule the specified draft version |
|
||||
| POST | `/campaigns/:id/cancellation` | `campaigns.manage`; cancel with a reason |
|
||||
| GET | `/storefront/:organizationId/campaigns` | Public; active campaigns only |
|
||||
| GET | `/storefront/:organizationId/campaigns/:slug` | Public; active campaign by slug |
|
||||
|
||||
Lists use the existing `limit` (1–100, default 25) and `offset` (0–10,000, default 0) contract. Staff resources are organization-scoped. Public routes share the existing storefront rate limit.
|
||||
|
||||
Create body: `slug` (existing collection slug format, at most 100 characters), `title` (1–160), `summary` (0–500; default empty), `collectionId` (UUID), `startsAt`, `endsAt`, and `idempotencyKey` (UUID). Times must be ISO timestamps with a timezone/UTC offset and are normalized to UTC milliseconds; end must be after start at that precision. Unknown fields and HTML/control characters in copy are rejected.
|
||||
|
||||
PATCH takes the current integer `version` plus one or more of `title`, `summary`, `collectionId`, `startsAt`, or `endsAt`. Slug and original creation identity are fixed. A stale version returns 409; callers should refetch after an ambiguous timeout before deciding whether to retry. A patch that changes no values leaves version and audit history unchanged. Actual changes increment version.
|
||||
|
||||
Persisted `state` is `DRAFT`, `PUBLISHED`, or `CANCELLED`. Staff responses also include computed `status`: `DRAFT`, `SCHEDULED`, `ACTIVE`, `ENDED`, or `CANCELLED`. Status describes the lifecycle/time window; public visibility additionally requires an eligible collection. Active visibility uses `startsAt <= now < endsAt`; it requires no scheduler, worker, or cron job. Publication requires an unexpired end time and a collection in the caller's organization containing at least one published product with an active variant.
|
||||
|
||||
Publication body is `{ "version": 0 }`, using the draft version just read. A stale version returns 409. Published campaign terms cannot be edited. Repeating the original publication version returns its current representation without another audit event; a different version conflicts. Cancelled campaigns cannot be published. Cancellation body is `{ "reason": "Campaign withdrawn" }` (3–500 characters). Cancellation applies to drafts and published campaigns; repeating the same reason returns the current record, while a conflicting reason returns 409. Cancellation metadata is immutable. No hard-delete endpoint exists.
|
||||
|
||||
Public responses include only campaign ID, slug, title, summary, UTC start/end, and collection ID/name/slug. Drafts, future, expired, and cancelled campaigns are absent. Changing a linked group to a category or removing all eligible products also hides the campaign. An inactive or unknown public slug returns 404. Public collection links can use the existing storefront product list with `groupId`.
|
||||
|
||||
Creation keys are organization-scoped and retained with the campaign. Identical retries return the current representation; different original content using the same key returns 409. Unique slugs are organization-scoped. All actual writes record audit events within the existing transaction/organization lock. Inputs derive organization and staff identity from the bearer session.
|
||||
|
||||
Acceptance: private drafts; exact start/end boundaries; versioned edits; immutable published terms; repeatable publication/cancellation; scoped permissions/collections; dynamic collection suppression; public-field allowlist; preserved checkout behavior. Verify with `pnpm check` and `pnpm db:test`, plus focused Jest campaign tests. Implementation lives in `src/campaigns`, tests in `test`, and the additive migration in `prisma/migrations`.
|
||||
|
||||
Deploy the migration before the application. It adds one campaign table, scoped foreign keys, unique/index/time constraints, and lifecycle guards, and grants `campaigns.read`/`campaigns.manage` to existing system Owner roles. Custom roles require explicit grants. Rollback can redeploy the previous application while retaining the new table and audit history. This milestone provides collection discovery; campaign discounts, media assets, outbound messaging, and channel integrations are separate work.
|
||||
|
|
@ -1,17 +0,0 @@
|
|||
# Private wishlists (Phase 4A)
|
||||
|
||||
Endpoints under `/api/v1/wishlist` require an active bearer session. Like private addresses and carts, they need no staff permission. Ownership comes exclusively from the session; there is no staff endpoint for another user's wishlist and caller-supplied ownership fields are rejected.
|
||||
|
||||
| Method | Path | Purpose |
|
||||
| ------ | ------------- | ---------------------------------------------------------------------------------- |
|
||||
| GET | `/` | List own saved variants; `limit` defaults to 25 (1–100), `offset` to 0 (0–10,000) |
|
||||
| PUT | `/:variantId` | Save a published, active variant in the current organization; send no body or `{}` |
|
||||
| DELETE | `/:variantId` | Remove own saved variant; returns 204, including when already absent |
|
||||
|
||||
Each list/save response item contains `id`, `variantId`, `savedAt`, `available`, and `variant`. Available items include current variant name, SKU, exact two-decimal price, currency, and product ID/name/slug. Prices are live catalog prices, not frozen checkout prices. `available` means published and active; it does not indicate warehouse stock or reserve inventory.
|
||||
|
||||
Unpublished, archived, or inactive saved variants remain in the list with `available: false` and `variant: null`. This prevents leaking private catalog details while allowing removal. Repeating PUT for an existing saved item returns its current representation, even if it has become unavailable. A new save of an unavailable, missing, or out-of-organization variant returns 404 (`WISHLIST_ITEM_UNAVAILABLE`).
|
||||
|
||||
A user may save at most 100 variants. A new item at the limit returns 409 (`WISHLIST_LIMIT`); existing-item retries remain valid. List ordering is newest saved first, with ID as a stable tie-breaker. PUT retries keep the same ID and timestamp. After deletion, a later save creates a new item. Concurrent API mutations use the existing transaction/organization lock; a database unique constraint also prevents duplicate user/organization/variant entries.
|
||||
|
||||
Save/remove actions produce one audit event per actual change. There are no public shares, guest wishlists, notifications, cart conversion, or inventory effects in this milestone. Composite database foreign keys enforce user and variant organization scope. Deploy the append-only migration before the application; existing records and permissions are unchanged.
|
||||
|
|
@ -19,13 +19,10 @@
|
|||
"db:validate": "prisma validate",
|
||||
"db:migrate": "prisma migrate dev",
|
||||
"db:deploy": "prisma migrate deploy",
|
||||
"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",
|
||||
"check": "pnpm migrations:check && pnpm format:check && pnpm db:validate && pnpm typecheck && pnpm test:coverage && pnpm build",
|
||||
"start:watch": "node --watch dist/main.js",
|
||||
"db:status": "prisma migrate status",
|
||||
"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:seed-local": "node dist/cli/local-admin.js seed",
|
||||
"db:test": "node scripts/test-migrations.mjs",
|
||||
|
|
@ -41,10 +38,10 @@
|
|||
"@prisma/client": "^7.0.0",
|
||||
"dotenv": "^17.0.0",
|
||||
"helmet": "^8.0.0",
|
||||
"nodemailer": "^10.6.1",
|
||||
"nodemailer": "^10.0.2",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"rxjs": "^7.8.2",
|
||||
"zod": "^4.6.7"
|
||||
"zod": "^4.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@electric-sql/pglite": "^0.5.8",
|
||||
|
|
|
|||
|
|
@ -6,12 +6,10 @@ settings:
|
|||
|
||||
overrides:
|
||||
'@prisma/config>deepmerge-ts': 8.0.0
|
||||
'@prisma/config>effect': 3.22.5
|
||||
prisma>mysql2: 3.23.1
|
||||
'@nestjs/platform-express>multer': 2.5.0
|
||||
'@nestjs/platform-express>multer': 2.4.0
|
||||
'@nestjs/swagger>js-yaml': 5.4.1
|
||||
ajv>fast-uri: 3.1.9
|
||||
express>proxy-addr: 2.0.8
|
||||
ajv>fast-uri: 3.1.8
|
||||
|
||||
importers:
|
||||
|
||||
|
|
@ -42,8 +40,8 @@ importers:
|
|||
specifier: ^8.0.0
|
||||
version: 8.3.0
|
||||
nodemailer:
|
||||
specifier: ^10.6.1
|
||||
version: 10.6.1
|
||||
specifier: ^10.0.2
|
||||
version: 10.0.11
|
||||
reflect-metadata:
|
||||
specifier: ^0.2.2
|
||||
version: 0.2.2
|
||||
|
|
@ -51,8 +49,8 @@ importers:
|
|||
specifier: ^7.8.2
|
||||
version: 7.8.2
|
||||
zod:
|
||||
specifier: ^4.6.7
|
||||
version: 4.6.7
|
||||
specifier: ^4.0.0
|
||||
version: 4.5.4
|
||||
devDependencies:
|
||||
'@electric-sql/pglite':
|
||||
specifier: ^0.5.8
|
||||
|
|
@ -1341,8 +1339,8 @@ packages:
|
|||
better-result@2.10.0:
|
||||
resolution: {integrity: sha512-oQhh0y1qo2/ZKdAAEvHZAqKKiHOFU5k/bW96fE2ScgQOVkJRiHwB+nOS1SgFsYqRlxMDWvefXi9Q3px7QvgNDw==}
|
||||
|
||||
body-parser@2.4.0:
|
||||
resolution: {integrity: sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ==}
|
||||
body-parser@2.3.0:
|
||||
resolution: {integrity: sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==}
|
||||
engines: {node: '>=18'}
|
||||
|
||||
brace-expansion@2.1.4:
|
||||
|
|
@ -1612,8 +1610,8 @@ packages:
|
|||
ee-first@1.1.1:
|
||||
resolution: {integrity: sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==}
|
||||
|
||||
effect@3.22.5:
|
||||
resolution: {integrity: sha512-AdIU4llI19BzhJ4xUBZix7kS8oiYSlCsJ61j3UM3UyJw9ecDrsrrweDFm/Ku1nHbJWMLoynK+1Me4it3Zkmjpw==}
|
||||
effect@3.20.0:
|
||||
resolution: {integrity: sha512-qMLfDJscrNG8p/aw+IkT9W7fgj50Z4wG5bLBy0Txsxz8iUHjDIkOgO3SV0WZfnQbNG2VJYb0b+rDLMrhM4+Krw==}
|
||||
|
||||
electron-to-chromium@1.5.422:
|
||||
resolution: {integrity: sha512-UvA/32XqrLDdZSn7Jllo1AYNcWji/G0d5M0GTViE7KoGBiMunw3a34Sb2KO4ZZyrSEhqsxFoVhWWJshdyfKqJA==}
|
||||
|
|
@ -1728,8 +1726,8 @@ packages:
|
|||
fast-safe-stringify@2.1.1:
|
||||
resolution: {integrity: sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==}
|
||||
|
||||
fast-uri@3.1.9:
|
||||
resolution: {integrity: sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==}
|
||||
fast-uri@3.1.8:
|
||||
resolution: {integrity: sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg==}
|
||||
|
||||
fb-watchman@2.0.2:
|
||||
resolution: {integrity: sha512-p5161BqbuCaSnB8jIbzQHOlpgsPmK5rJVDfDKO91Axs5NC1uu3HRQm6wt9cd9/+GtQQIO53JdGXXoyDpTAsgYA==}
|
||||
|
|
@ -2221,8 +2219,8 @@ packages:
|
|||
ms@2.1.3:
|
||||
resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}
|
||||
|
||||
multer@2.5.0:
|
||||
resolution: {integrity: sha512-BsqOzYGVq49JcW2IzoSAxeKYRevb+dGGPPWleOR8Lrlk4igwxu1/9pwSXlByhCb7MVZDrNJFC0IBP5/O5nLYRw==}
|
||||
multer@2.4.0:
|
||||
resolution: {integrity: sha512-7dqa0ZcFfzbefdTuIkzOSMvZWC0J7FLqBOjJUZvDCXShIURWKxAyTT1wHhnE5q19c7jOJf43IYYKjBmZVZmvhg==}
|
||||
engines: {node: '>= 10.16.0'}
|
||||
|
||||
mysql2@3.23.1:
|
||||
|
|
@ -2260,8 +2258,8 @@ packages:
|
|||
resolution: {integrity: sha512-YHs7BmmcsdAI5Ozuf8JZo6PT0mv2GIWC9vMfvUC3dp65M8hn7Ux8CPL+2oBI7juNuj9d0ndhTcznq2ODBps9cQ==}
|
||||
engines: {node: '>=18'}
|
||||
|
||||
nodemailer@10.6.1:
|
||||
resolution: {integrity: sha512-d7kfFfS/tR4Aca+SBvRaQ+MXKNv7d2JiRe5TxaRcFT/kYMh4GGPnW9aKksTIEvyEbA7d/7HYWE4YPDEHxzJj/g==}
|
||||
nodemailer@10.0.11:
|
||||
resolution: {integrity: sha512-/c4P7U7aGpiNu2Rl08q525q2zECkUpSaf2zQPgIStCcAjHAkkQQKwD4sTyi3l91mGcLQrKzL1syXPHymo+Ogtw==}
|
||||
engines: {node: '>=20.0.0'}
|
||||
|
||||
normalize-path@3.0.0:
|
||||
|
|
@ -2451,8 +2449,8 @@ packages:
|
|||
proper-lockfile@4.1.2:
|
||||
resolution: {integrity: sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA==}
|
||||
|
||||
proxy-addr@2.0.8:
|
||||
resolution: {integrity: sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==}
|
||||
proxy-addr@2.0.7:
|
||||
resolution: {integrity: sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==}
|
||||
engines: {node: '>= 0.10'}
|
||||
|
||||
pure-rand@6.1.0:
|
||||
|
|
@ -2461,8 +2459,8 @@ packages:
|
|||
pure-rand@7.0.1:
|
||||
resolution: {integrity: sha512-oTUZM/NAZS8p7ANR3SHh30kXB+zK2r2BPcEn/awJIbOvq82WoMN4p62AWWp3Hhw50G0xMsw1mhIBLqHw64EcNQ==}
|
||||
|
||||
qs@6.17.1:
|
||||
resolution: {integrity: sha512-jd3COkaKVgGUW+ZHyEHCG9bH7RoaaiWuMgzsIBjUMVjLAaWGWpoUAVwljVvBHxRu/2qEHnadLGZrkutYUBPQJA==}
|
||||
qs@6.16.0:
|
||||
resolution: {integrity: sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA==}
|
||||
engines: {node: '>=0.6'}
|
||||
|
||||
range-parser@1.3.0:
|
||||
|
|
@ -2850,8 +2848,8 @@ packages:
|
|||
zeptomatch@2.1.0:
|
||||
resolution: {integrity: sha512-KiGErG2J0G82LSpniV0CtIzjlJ10E04j02VOudJsPyPwNZgGnRKQy7I1R7GMyg/QswnE4l7ohSGrQbQbjXPPDA==}
|
||||
|
||||
zod@4.6.7:
|
||||
resolution: {integrity: sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==}
|
||||
zod@4.5.4:
|
||||
resolution: {integrity: sha512-sC95tT5iHHH9gtpj6A81kh+NEaRAUFN+qlUPDUbRfOMvNf5QCBqsb3WgvnpVtK5Y+4UfA6KqufotuTvMGiTlsA==}
|
||||
|
||||
snapshots:
|
||||
|
||||
|
|
@ -3455,7 +3453,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)
|
||||
cors: 2.8.6
|
||||
express: 5.2.1(supports-color@8.1.1)
|
||||
multer: 2.5.0
|
||||
multer: 2.4.0
|
||||
path-to-regexp: 8.4.2
|
||||
tslib: 2.8.1
|
||||
transitivePeerDependencies:
|
||||
|
|
@ -3570,7 +3568,7 @@ snapshots:
|
|||
dependencies:
|
||||
c12: 3.3.4
|
||||
deepmerge-ts: 8.0.0
|
||||
effect: 3.22.5
|
||||
effect: 3.20.0
|
||||
empathic: 2.0.0
|
||||
transitivePeerDependencies:
|
||||
- magicast
|
||||
|
|
@ -4042,7 +4040,7 @@ snapshots:
|
|||
ajv@8.20.0:
|
||||
dependencies:
|
||||
fast-deep-equal: 3.1.3
|
||||
fast-uri: 3.1.9
|
||||
fast-uri: 3.1.8
|
||||
json-schema-traverse: 1.0.0
|
||||
require-from-string: 2.0.2
|
||||
|
||||
|
|
@ -4141,7 +4139,7 @@ snapshots:
|
|||
|
||||
better-result@2.10.0: {}
|
||||
|
||||
body-parser@2.4.0(supports-color@8.1.1):
|
||||
body-parser@2.3.0(supports-color@8.1.1):
|
||||
dependencies:
|
||||
bytes: 3.1.2
|
||||
content-type: 2.1.0
|
||||
|
|
@ -4149,7 +4147,7 @@ snapshots:
|
|||
http-errors: 2.0.1
|
||||
iconv-lite: 0.7.3
|
||||
on-finished: 2.4.1
|
||||
qs: 6.17.1
|
||||
qs: 6.16.0
|
||||
raw-body: 3.0.2
|
||||
type-is: 2.1.0
|
||||
transitivePeerDependencies:
|
||||
|
|
@ -4381,7 +4379,7 @@ snapshots:
|
|||
|
||||
ee-first@1.1.1: {}
|
||||
|
||||
effect@3.22.5:
|
||||
effect@3.20.0:
|
||||
dependencies:
|
||||
'@standard-schema/spec': 1.1.0
|
||||
fast-check: 3.23.2
|
||||
|
|
@ -4489,7 +4487,7 @@ snapshots:
|
|||
express@5.2.1(supports-color@8.1.1):
|
||||
dependencies:
|
||||
accepts: 2.0.0
|
||||
body-parser: 2.4.0(supports-color@8.1.1)
|
||||
body-parser: 2.3.0(supports-color@8.1.1)
|
||||
content-disposition: 1.1.0
|
||||
content-type: 1.0.5
|
||||
cookie: 0.7.2
|
||||
|
|
@ -4507,8 +4505,8 @@ snapshots:
|
|||
on-finished: 2.4.1
|
||||
once: 1.4.0
|
||||
parseurl: 1.3.3
|
||||
proxy-addr: 2.0.8
|
||||
qs: 6.17.1
|
||||
proxy-addr: 2.0.7
|
||||
qs: 6.16.0
|
||||
range-parser: 1.3.0
|
||||
router: 2.2.0(supports-color@8.1.1)
|
||||
send: 1.2.1(supports-color@8.1.1)
|
||||
|
|
@ -4537,7 +4535,7 @@ snapshots:
|
|||
|
||||
fast-safe-stringify@2.1.1: {}
|
||||
|
||||
fast-uri@3.1.9: {}
|
||||
fast-uri@3.1.8: {}
|
||||
|
||||
fb-watchman@2.0.2:
|
||||
dependencies:
|
||||
|
|
@ -5175,7 +5173,7 @@ snapshots:
|
|||
|
||||
ms@2.1.3: {}
|
||||
|
||||
multer@2.5.0:
|
||||
multer@2.4.0:
|
||||
dependencies:
|
||||
append-field: 1.0.0
|
||||
busboy: 1.6.0
|
||||
|
|
@ -5213,7 +5211,7 @@ snapshots:
|
|||
|
||||
node-releases@2.0.54: {}
|
||||
|
||||
nodemailer@10.6.1: {}
|
||||
nodemailer@10.0.11: {}
|
||||
|
||||
normalize-path@3.0.0: {}
|
||||
|
||||
|
|
@ -5384,7 +5382,7 @@ snapshots:
|
|||
retry: 0.12.0
|
||||
signal-exit: 3.0.7
|
||||
|
||||
proxy-addr@2.0.8:
|
||||
proxy-addr@2.0.7:
|
||||
dependencies:
|
||||
forwarded: 0.2.0
|
||||
ipaddr.js: 1.9.1
|
||||
|
|
@ -5393,7 +5391,7 @@ snapshots:
|
|||
|
||||
pure-rand@7.0.1: {}
|
||||
|
||||
qs@6.17.1:
|
||||
qs@6.16.0:
|
||||
dependencies:
|
||||
es-define-property: 1.0.1
|
||||
side-channel: 1.1.1
|
||||
|
|
@ -5601,7 +5599,7 @@ snapshots:
|
|||
formidable: 3.5.4
|
||||
methods: 1.1.2
|
||||
mime: 2.6.0
|
||||
qs: 6.17.1
|
||||
qs: 6.16.0
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
|
|
@ -5793,4 +5791,4 @@ snapshots:
|
|||
grammex: 3.1.13
|
||||
graphmatch: 1.1.1
|
||||
|
||||
zod@4.6.7: {}
|
||||
zod@4.5.4: {}
|
||||
|
|
|
|||
|
|
@ -7,9 +7,7 @@ allowBuilds:
|
|||
unrs-resolver: true
|
||||
overrides:
|
||||
'@prisma/config>deepmerge-ts': 8.0.0
|
||||
'@prisma/config>effect': 3.22.5
|
||||
'prisma>mysql2': 3.23.1
|
||||
'@nestjs/platform-express>multer': 2.5.0
|
||||
'@nestjs/platform-express>multer': 2.4.0
|
||||
'@nestjs/swagger>js-yaml': 5.4.1
|
||||
'ajv>fast-uri': 3.1.9
|
||||
'express>proxy-addr': 2.0.8
|
||||
'ajv>fast-uri': 3.1.8
|
||||
|
|
|
|||
|
|
@ -1,35 +0,0 @@
|
|||
enum BlogState {
|
||||
DRAFT
|
||||
PUBLISHED
|
||||
WITHDRAWN
|
||||
}
|
||||
model BlogArticle {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
organizationId String @map("organization_id") @db.Uuid
|
||||
createdById String @map("created_by_id") @db.Uuid
|
||||
slug String @db.VarChar(100)
|
||||
title String @db.VarChar(160)
|
||||
summary String @db.VarChar(500)
|
||||
body String
|
||||
state BlogState @default(DRAFT)
|
||||
version Int @default(0)
|
||||
publishedContent Json? @map("published_content")
|
||||
publicationVersion Int? @map("publication_version")
|
||||
publishedAt DateTime? @map("published_at") @db.Timestamptz(3)
|
||||
publishedById String? @map("published_by_id") @db.Uuid
|
||||
withdrawnAt DateTime? @map("withdrawn_at") @db.Timestamptz(3)
|
||||
withdrawnById String? @map("withdrawn_by_id") @db.Uuid
|
||||
withdrawalReason String? @map("withdrawal_reason") @db.VarChar(500)
|
||||
idempotencyKey String @map("idempotency_key") @db.Uuid
|
||||
requestHash String @map("request_hash") @db.Char(64)
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
|
||||
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz(3)
|
||||
createdBy User @relation("BlogCreator", fields: [createdById, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
publishedBy User? @relation("BlogPublisher", fields: [publishedById, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
withdrawnBy User? @relation("BlogWithdrawer", fields: [withdrawnById, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
@@unique([organizationId, slug])
|
||||
@@unique([organizationId, idempotencyKey])
|
||||
@@index([organizationId, state, publishedAt, id])
|
||||
@@index([organizationId, createdAt, id])
|
||||
@@map("blog_articles")
|
||||
}
|
||||
|
|
@ -1,39 +0,0 @@
|
|||
enum CampaignState {
|
||||
DRAFT
|
||||
PUBLISHED
|
||||
CANCELLED
|
||||
}
|
||||
|
||||
model SeasonalCampaign {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
organizationId String @map("organization_id") @db.Uuid
|
||||
collectionId String @map("collection_id") @db.Uuid
|
||||
createdById String @map("created_by_id") @db.Uuid
|
||||
slug String @db.VarChar(100)
|
||||
title String @db.VarChar(160)
|
||||
summary String @default("") @db.VarChar(500)
|
||||
startsAt DateTime @map("starts_at") @db.Timestamptz(3)
|
||||
endsAt DateTime @map("ends_at") @db.Timestamptz(3)
|
||||
state CampaignState @default(DRAFT)
|
||||
version Int @default(0)
|
||||
idempotencyKey String @map("idempotency_key") @db.Uuid
|
||||
requestHash String @map("request_hash") @db.Char(64)
|
||||
publishedById String? @map("published_by_id") @db.Uuid
|
||||
publishedAt DateTime? @map("published_at") @db.Timestamptz(3)
|
||||
cancelledById String? @map("cancelled_by_id") @db.Uuid
|
||||
cancelledAt DateTime? @map("cancelled_at") @db.Timestamptz(3)
|
||||
cancellationReason String? @map("cancellation_reason") @db.VarChar(500)
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
|
||||
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz(3)
|
||||
collection CatalogGroup @relation(fields: [collectionId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
createdBy User @relation("CampaignCreator", fields: [createdById, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
publishedBy User? @relation("CampaignPublisher", fields: [publishedById, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
cancelledBy User? @relation("CampaignCanceller", fields: [cancelledById, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
coupon Coupon?
|
||||
@@unique([id, organizationId])
|
||||
@@unique([organizationId, slug])
|
||||
@@unique([organizationId, idempotencyKey])
|
||||
@@index([organizationId, state, startsAt, endsAt, id])
|
||||
@@index([organizationId, createdAt, id])
|
||||
@@map("seasonal_campaigns")
|
||||
}
|
||||
|
|
@ -19,7 +19,6 @@ model Product {
|
|||
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
|
||||
variants ProductVariant[]
|
||||
groups ProductGroup[]
|
||||
images ProductImage[]
|
||||
@@unique([organizationId, slug])
|
||||
@@unique([id, organizationId])
|
||||
@@index([organizationId, status, createdAt, id])
|
||||
|
|
@ -37,9 +36,6 @@ model ProductVariant {
|
|||
active Boolean @default(true)
|
||||
stockItems StockItem[]
|
||||
cartLines CartLine[]
|
||||
wishlistItems WishlistItem[]
|
||||
reviewVerifications ReviewPurchaseVerification[]
|
||||
reviews ProductReview[]
|
||||
orderLines OrderLine[]
|
||||
boms ProductBom[]
|
||||
b2bPriceListItems B2bPriceListItem[]
|
||||
|
|
@ -53,7 +49,6 @@ model ProductVariant {
|
|||
@@map("product_variants")
|
||||
}
|
||||
model CatalogGroup {
|
||||
seasonalCampaigns SeasonalCampaign[]
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
organizationId String @map("organization_id") @db.Uuid
|
||||
name String @db.VarChar(100)
|
||||
|
|
|
|||
|
|
@ -11,7 +11,6 @@ model Cart {
|
|||
organizationId String @map("organization_id") @db.Uuid
|
||||
userId String @map("user_id") @db.Uuid
|
||||
version Int @default(0)
|
||||
lastActivityAt DateTime? @map("last_activity_at") @db.Timestamptz(3)
|
||||
user User @relation(fields: [userId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
lines CartLine[]
|
||||
@@unique([userId, organizationId])
|
||||
|
|
@ -32,7 +31,6 @@ model CartLine {
|
|||
model Coupon {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
organizationId String @map("organization_id") @db.Uuid
|
||||
campaignId String? @unique @map("campaign_id") @db.Uuid
|
||||
code String @db.VarChar(40)
|
||||
kind CouponKind
|
||||
currency String @db.Char(3)
|
||||
|
|
@ -46,8 +44,6 @@ model Coupon {
|
|||
active Boolean @default(true)
|
||||
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
|
||||
orders Order[]
|
||||
campaign SeasonalCampaign? @relation(fields: [campaignId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
@@unique([campaignId, organizationId])
|
||||
@@unique([organizationId, code])
|
||||
@@unique([id, organizationId])
|
||||
@@map("coupons")
|
||||
|
|
@ -77,8 +73,6 @@ model Order {
|
|||
@@unique([userId, organizationId, idempotencyKey])
|
||||
@@unique([id, organizationId])
|
||||
@@index([organizationId, userId, createdAt, id])
|
||||
@@index([organizationId, createdAt, id])
|
||||
@@index([organizationId, status, expiresAt, id])
|
||||
@@unique([id, userId, organizationId])
|
||||
@@index([couponId, status, expiresAt])
|
||||
@@map("orders")
|
||||
|
|
|
|||
|
|
@ -1,43 +0,0 @@
|
|||
enum ForumDecisionKind {
|
||||
APPROVED
|
||||
REJECTED
|
||||
HIDDEN
|
||||
}
|
||||
model ForumPost {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
organizationId String @map("organization_id") @db.Uuid
|
||||
userId String @map("user_id") @db.Uuid
|
||||
threadId String? @map("thread_id") @db.Uuid
|
||||
displayName String @map("display_name") @db.VarChar(80)
|
||||
title String? @db.VarChar(160)
|
||||
body String @db.VarChar(5000)
|
||||
idempotencyKey String @map("idempotency_key") @db.Uuid
|
||||
requestHash String @map("request_hash") @db.Char(64)
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
|
||||
user User @relation(fields: [userId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
thread ForumPost? @relation("ForumReplies", fields: [threadId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
replies ForumPost[] @relation("ForumReplies")
|
||||
events ForumModeration[]
|
||||
@@unique([id, organizationId])
|
||||
@@unique([userId, organizationId, idempotencyKey])
|
||||
@@index([organizationId, threadId, createdAt, id])
|
||||
@@index([organizationId, userId, createdAt, id])
|
||||
@@map("forum_posts")
|
||||
}
|
||||
model ForumModeration {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
organizationId String @map("organization_id") @db.Uuid
|
||||
postId String @map("post_id") @db.Uuid
|
||||
actorId String @map("actor_id") @db.Uuid
|
||||
sequence Int
|
||||
kind ForumDecisionKind
|
||||
note String @db.VarChar(1000)
|
||||
idempotencyKey String @map("idempotency_key") @db.Uuid
|
||||
requestHash String @map("request_hash") @db.Char(64)
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
|
||||
post ForumPost @relation(fields: [postId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
actor User @relation(fields: [actorId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
@@unique([postId, sequence])
|
||||
@@unique([organizationId, idempotencyKey])
|
||||
@@map("forum_moderation")
|
||||
}
|
||||
|
|
@ -1,18 +0,0 @@
|
|||
model MessagingConsentDecision {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
organizationId String @map("organization_id") @db.Uuid
|
||||
userId String @map("user_id") @db.Uuid
|
||||
channel String @db.VarChar(20)
|
||||
purpose String @db.VarChar(20)
|
||||
granted Boolean
|
||||
version Int
|
||||
noticeVersion String? @map("notice_version") @db.VarChar(40)
|
||||
idempotencyKey String @map("idempotency_key") @db.Uuid
|
||||
requestHash String @map("request_hash") @db.Char(64)
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
|
||||
user User @relation(fields: [userId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
@@unique([userId, organizationId, channel, purpose, version])
|
||||
@@unique([userId, organizationId, idempotencyKey])
|
||||
@@index([userId, organizationId, createdAt, id])
|
||||
@@map("messaging_consent_decisions")
|
||||
}
|
||||
|
|
@ -41,21 +41,5 @@
|
|||
"20261003000100_b2b_artwork_approvals": "1359390fc3692bdc2dea8a4cc12223d97c7c15b0cdd2181b082b5e5acbe33677",
|
||||
"20261003151400_b2b_partner_orders": "ffbba39ed98a16c122b0756a97d721adde9268904f9a7d9770407f341ef848ba",
|
||||
"20261003183000_b2b_partner_payments": "bc43c5a713c62aa201affa2f2595156a2fc68882774504cdf12ac4cf0f641452",
|
||||
"20261004003000_b2b_custom_candle_requests": "ab78d0a7e214ab226e042f29b42e961ddbae3a3e338fd65983d5aa87e2c736ac",
|
||||
"20261004010000_b2b_partner_reporting": "44086ecc27278b9499fbcf5fa97ed754f056fcf49f6b155e1ed377527616dc89",
|
||||
"20261005120000_private_wishlists": "8ded2f27a4e08ea6af3e5ae92f15b832cea66156a7489f28e178d3df6404f5e4",
|
||||
"20261005160000_verified_product_reviews": "1f71f6d49622c48a37c88f2eb7740174cbc9aea7d0027f6fc27d81301d87c757",
|
||||
"20261006120000_seasonal_campaigns": "4f81582f91a8d3cb30bf49051281ca05c862b794925c0643a7237d1a1efb6f40",
|
||||
"20261006160000_campaign_discounts": "99485a5b252f01057dfa6300c567c79586555a76cec5c2dc0d9c3fef9fc61017",
|
||||
"20261007120000_cart_recovery": "a415f3b458c55bf37a95f8d2f3b31dfc7ae4427f04aabc9f0910f1201caa6d31",
|
||||
"20261007130000_messaging_consent": "b4fd5b1cf6a7cd17083a4b5fbef815ec1ebc25ba7538c6de18c05e16212155dd",
|
||||
"20261007140000_blog_publishing": "92e8d98a8e89f3eda28b6cf5c3b45125a325e5d8e852f1e5a0a3cf5d7eff65a4",
|
||||
"20261007150000_customer_segments": "bcafd50bc12dc44b7ee532ba4ca23da0b12eb3f0e89ad4b168789a22e110969a",
|
||||
"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"
|
||||
"20261004003000_b2b_custom_candle_requests": "ab78d0a7e214ab226e042f29b42e961ddbae3a3e338fd65983d5aa87e2c736ac"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,2 +0,0 @@
|
|||
UPDATE roles SET permissions = ARRAY(SELECT DISTINCT unnest(permissions || ARRAY['b2b.report.read']))
|
||||
WHERE is_system = true AND name = 'Owner';
|
||||
|
|
@ -1,22 +0,0 @@
|
|||
-- CreateTable
|
||||
CREATE TABLE "wishlist_items" (
|
||||
"id" UUID NOT NULL,
|
||||
"organization_id" UUID NOT NULL,
|
||||
"user_id" UUID NOT NULL,
|
||||
"variant_id" UUID NOT NULL,
|
||||
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "wishlist_items_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "wishlist_items_user_id_organization_id_created_at_id_idx" ON "wishlist_items"("user_id", "organization_id", "created_at", "id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "wishlist_items_user_id_organization_id_variant_id_key" ON "wishlist_items"("user_id", "organization_id", "variant_id");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "wishlist_items" ADD CONSTRAINT "wishlist_items_user_id_organization_id_fkey" FOREIGN KEY ("user_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "wishlist_items" ADD CONSTRAINT "wishlist_items_variant_id_organization_id_fkey" FOREIGN KEY ("variant_id", "organization_id") REFERENCES "product_variants"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
|
@ -1,216 +0,0 @@
|
|||
-- CreateEnum
|
||||
CREATE TYPE "ReviewModerationKind" AS ENUM ('APPROVED', 'REJECTED', 'HIDDEN');
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "review_purchase_verifications" (
|
||||
"id" UUID NOT NULL,
|
||||
"organization_id" UUID NOT NULL,
|
||||
"user_id" UUID NOT NULL,
|
||||
"variant_id" UUID NOT NULL,
|
||||
"actor_id" UUID NOT NULL,
|
||||
"reference" VARCHAR(100) NOT NULL,
|
||||
"note" VARCHAR(1000) NOT NULL,
|
||||
"idempotency_key" UUID NOT NULL,
|
||||
"request_hash" CHAR(64) NOT NULL,
|
||||
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "review_purchase_verifications_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "review_purchase_revocations" (
|
||||
"verification_id" UUID NOT NULL,
|
||||
"organization_id" UUID NOT NULL,
|
||||
"actor_id" UUID NOT NULL,
|
||||
"reason" VARCHAR(1000) NOT NULL,
|
||||
"idempotency_key" UUID NOT NULL,
|
||||
"request_hash" CHAR(64) NOT NULL,
|
||||
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "review_purchase_revocations_pkey" PRIMARY KEY ("verification_id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "product_reviews" (
|
||||
"id" UUID NOT NULL,
|
||||
"organization_id" UUID NOT NULL,
|
||||
"user_id" UUID NOT NULL,
|
||||
"variant_id" UUID NOT NULL,
|
||||
"verification_id" UUID NOT NULL,
|
||||
"rating" INTEGER NOT NULL,
|
||||
"display_name" VARCHAR(80) NOT NULL,
|
||||
"title" VARCHAR(160) NOT NULL,
|
||||
"body" VARCHAR(2000) NOT NULL,
|
||||
"idempotency_key" UUID NOT NULL,
|
||||
"request_hash" CHAR(64) NOT NULL,
|
||||
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "product_reviews_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "product_review_moderation" (
|
||||
"id" UUID NOT NULL,
|
||||
"organization_id" UUID NOT NULL,
|
||||
"review_id" UUID NOT NULL,
|
||||
"actor_id" UUID NOT NULL,
|
||||
"sequence" INTEGER NOT NULL,
|
||||
"kind" "ReviewModerationKind" NOT NULL,
|
||||
"note" VARCHAR(1000) NOT NULL,
|
||||
"idempotency_key" UUID NOT NULL,
|
||||
"request_hash" CHAR(64) NOT NULL,
|
||||
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "product_review_moderation_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "review_purchase_verifications_organization_id_user_id_creat_idx" ON "review_purchase_verifications"("organization_id", "user_id", "created_at", "id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "review_purchase_verifications_id_user_id_variant_id_organiz_key" ON "review_purchase_verifications"("id", "user_id", "variant_id", "organization_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "review_purchase_verifications_id_organization_id_key" ON "review_purchase_verifications"("id", "organization_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "review_purchase_verifications_organization_id_idempotency_k_key" ON "review_purchase_verifications"("organization_id", "idempotency_key");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "review_purchase_verifications_organization_id_reference_var_key" ON "review_purchase_verifications"("organization_id", "reference", "variant_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "review_purchase_revocations_verification_id_organization_id_key" ON "review_purchase_revocations"("verification_id", "organization_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "review_purchase_revocations_organization_id_idempotency_key_key" ON "review_purchase_revocations"("organization_id", "idempotency_key");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "product_reviews_verification_id_key" ON "product_reviews"("verification_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "product_reviews_organization_id_user_id_created_at_id_idx" ON "product_reviews"("organization_id", "user_id", "created_at", "id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "product_reviews_id_organization_id_key" ON "product_reviews"("id", "organization_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "product_reviews_verification_id_user_id_variant_id_organiza_key" ON "product_reviews"("verification_id", "user_id", "variant_id", "organization_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "product_reviews_user_id_organization_id_variant_id_key" ON "product_reviews"("user_id", "organization_id", "variant_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "product_reviews_user_id_organization_id_idempotency_key_key" ON "product_reviews"("user_id", "organization_id", "idempotency_key");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "product_review_moderation_review_id_sequence_key" ON "product_review_moderation"("review_id", "sequence");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "product_review_moderation_organization_id_idempotency_key_key" ON "product_review_moderation"("organization_id", "idempotency_key");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "review_purchase_verifications" ADD CONSTRAINT "review_purchase_verifications_user_id_organization_id_fkey" FOREIGN KEY ("user_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "review_purchase_verifications" ADD CONSTRAINT "review_purchase_verifications_actor_id_organization_id_fkey" FOREIGN KEY ("actor_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "review_purchase_verifications" ADD CONSTRAINT "review_purchase_verifications_variant_id_organization_id_fkey" FOREIGN KEY ("variant_id", "organization_id") REFERENCES "product_variants"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "review_purchase_revocations" ADD CONSTRAINT "review_purchase_revocations_verification_id_organization_i_fkey" FOREIGN KEY ("verification_id", "organization_id") REFERENCES "review_purchase_verifications"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "review_purchase_revocations" ADD CONSTRAINT "review_purchase_revocations_actor_id_organization_id_fkey" FOREIGN KEY ("actor_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "product_reviews" ADD CONSTRAINT "product_reviews_verification_id_user_id_variant_id_organiz_fkey" FOREIGN KEY ("verification_id", "user_id", "variant_id", "organization_id") REFERENCES "review_purchase_verifications"("id", "user_id", "variant_id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "product_reviews" ADD CONSTRAINT "product_reviews_variant_id_organization_id_fkey" FOREIGN KEY ("variant_id", "organization_id") REFERENCES "product_variants"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "product_review_moderation" ADD CONSTRAINT "product_review_moderation_review_id_organization_id_fkey" FOREIGN KEY ("review_id", "organization_id") REFERENCES "product_reviews"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "product_review_moderation" ADD CONSTRAINT "product_review_moderation_actor_id_organization_id_fkey" FOREIGN KEY ("actor_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
CREATE INDEX "product_reviews_organization_id_variant_id_created_at_id_idx" ON product_reviews(organization_id, variant_id, created_at, id);
|
||||
CREATE INDEX "product_reviews_organization_id_created_at_id_idx" ON product_reviews(organization_id, created_at, id);
|
||||
|
||||
ALTER TABLE review_purchase_verifications
|
||||
ADD CONSTRAINT review_verification_reference CHECK (char_length(btrim(reference)) >= 3),
|
||||
ADD CONSTRAINT review_verification_note CHECK (char_length(btrim(note)) >= 3),
|
||||
ADD CONSTRAINT review_verification_hash CHECK (request_hash ~ '^[a-f0-9]{64}$'),
|
||||
ADD CONSTRAINT review_verification_independent CHECK (actor_id <> user_id);
|
||||
ALTER TABLE review_purchase_revocations
|
||||
ADD CONSTRAINT review_revocation_reason CHECK (char_length(btrim(reason)) >= 3),
|
||||
ADD CONSTRAINT review_revocation_hash CHECK (request_hash ~ '^[a-f0-9]{64}$');
|
||||
ALTER TABLE product_reviews
|
||||
ADD CONSTRAINT product_review_rating CHECK (rating BETWEEN 1 AND 5),
|
||||
ADD CONSTRAINT product_review_text CHECK (char_length(btrim(display_name)) >= 1 AND char_length(btrim(title)) >= 3 AND char_length(btrim(body)) >= 10),
|
||||
ADD CONSTRAINT product_review_hash CHECK (request_hash ~ '^[a-f0-9]{64}$');
|
||||
ALTER TABLE product_review_moderation
|
||||
ADD CONSTRAINT review_moderation_sequence CHECK (sequence BETWEEN 1 AND 2),
|
||||
ADD CONSTRAINT review_moderation_note CHECK (char_length(btrim(note)) >= 3),
|
||||
ADD CONSTRAINT review_moderation_hash CHECK (request_hash ~ '^[a-f0-9]{64}$');
|
||||
|
||||
CREATE FUNCTION reject_review_record_mutation() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN RAISE EXCEPTION 'Review evidence, submissions and moderation history are immutable'; END;
|
||||
$$;
|
||||
CREATE TRIGGER review_verifications_immutable BEFORE UPDATE OR DELETE ON review_purchase_verifications
|
||||
FOR EACH ROW EXECUTE FUNCTION reject_review_record_mutation();
|
||||
CREATE TRIGGER review_revocations_immutable BEFORE UPDATE OR DELETE ON review_purchase_revocations
|
||||
FOR EACH ROW EXECUTE FUNCTION reject_review_record_mutation();
|
||||
CREATE TRIGGER product_reviews_immutable BEFORE UPDATE OR DELETE ON product_reviews
|
||||
FOR EACH ROW EXECUTE FUNCTION reject_review_record_mutation();
|
||||
CREATE TRIGGER review_moderation_immutable BEFORE UPDATE OR DELETE ON product_review_moderation
|
||||
FOR EACH ROW EXECUTE FUNCTION reject_review_record_mutation();
|
||||
|
||||
CREATE FUNCTION guard_review_submission() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
PERFORM id FROM review_purchase_verifications
|
||||
WHERE id = NEW.verification_id AND organization_id = NEW.organization_id
|
||||
AND user_id = NEW.user_id AND variant_id = NEW.variant_id FOR UPDATE;
|
||||
IF NOT FOUND OR EXISTS (SELECT 1 FROM review_purchase_revocations WHERE verification_id = NEW.verification_id)
|
||||
THEN RAISE EXCEPTION 'Review requires an active matching purchase verification'; END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
CREATE TRIGGER product_reviews_eligibility BEFORE INSERT ON product_reviews
|
||||
FOR EACH ROW EXECUTE FUNCTION guard_review_submission();
|
||||
|
||||
CREATE FUNCTION lock_review_revocation() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
PERFORM id FROM review_purchase_verifications
|
||||
WHERE id = NEW.verification_id AND organization_id = NEW.organization_id FOR UPDATE;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
CREATE TRIGGER review_revocation_lock BEFORE INSERT ON review_purchase_revocations
|
||||
FOR EACH ROW EXECUTE FUNCTION lock_review_revocation();
|
||||
|
||||
CREATE FUNCTION guard_review_moderation() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
DECLARE review product_reviews%ROWTYPE; last_kind "ReviewModerationKind";
|
||||
BEGIN
|
||||
SELECT * INTO review FROM product_reviews WHERE id = NEW.review_id AND organization_id = NEW.organization_id FOR UPDATE;
|
||||
IF review.id IS NULL OR review.user_id = NEW.actor_id THEN RAISE EXCEPTION 'Review requires an independent moderator'; END IF;
|
||||
PERFORM id FROM review_purchase_verifications WHERE id = review.verification_id FOR UPDATE;
|
||||
SELECT kind INTO last_kind FROM product_review_moderation WHERE review_id = NEW.review_id ORDER BY sequence DESC LIMIT 1;
|
||||
IF NEW.kind = 'HIDDEN' THEN
|
||||
IF NEW.sequence <> 2 OR last_kind IS DISTINCT FROM 'APPROVED'::"ReviewModerationKind"
|
||||
THEN RAISE EXCEPTION 'Only approved reviews can be hidden'; END IF;
|
||||
ELSE
|
||||
IF NEW.sequence <> 1 OR last_kind IS NOT NULL THEN RAISE EXCEPTION 'Review already decided'; END IF;
|
||||
IF NEW.kind = 'APPROVED' AND EXISTS (SELECT 1 FROM review_purchase_revocations WHERE verification_id = review.verification_id)
|
||||
THEN RAISE EXCEPTION 'Revoked purchase verification cannot be approved'; END IF;
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
CREATE TRIGGER review_moderation_transition BEFORE INSERT ON product_review_moderation
|
||||
FOR EACH ROW EXECUTE FUNCTION guard_review_moderation();
|
||||
|
||||
UPDATE roles SET permissions = ARRAY(SELECT DISTINCT unnest(permissions || ARRAY['reviews.verify', 'reviews.read', 'reviews.moderate']))
|
||||
WHERE is_system = true AND name = 'Owner';
|
||||
|
|
@ -1,104 +0,0 @@
|
|||
-- CreateEnum
|
||||
CREATE TYPE "CampaignState" AS ENUM ('DRAFT', 'PUBLISHED', 'CANCELLED');
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "seasonal_campaigns" (
|
||||
"id" UUID NOT NULL,
|
||||
"organization_id" UUID NOT NULL,
|
||||
"collection_id" UUID NOT NULL,
|
||||
"created_by_id" UUID NOT NULL,
|
||||
"slug" VARCHAR(100) NOT NULL,
|
||||
"title" VARCHAR(160) NOT NULL,
|
||||
"summary" VARCHAR(500) NOT NULL DEFAULT '',
|
||||
"starts_at" TIMESTAMPTZ(3) NOT NULL,
|
||||
"ends_at" TIMESTAMPTZ(3) NOT NULL,
|
||||
"state" "CampaignState" NOT NULL DEFAULT 'DRAFT',
|
||||
"version" INTEGER NOT NULL DEFAULT 0,
|
||||
"idempotency_key" UUID NOT NULL,
|
||||
"request_hash" CHAR(64) NOT NULL,
|
||||
"published_by_id" UUID,
|
||||
"published_at" TIMESTAMPTZ(3),
|
||||
"cancelled_by_id" UUID,
|
||||
"cancelled_at" TIMESTAMPTZ(3),
|
||||
"cancellation_reason" VARCHAR(500),
|
||||
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMPTZ(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "seasonal_campaigns_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "seasonal_campaigns_organization_id_state_starts_at_ends_at__idx" ON "seasonal_campaigns"("organization_id", "state", "starts_at", "ends_at", "id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "seasonal_campaigns_organization_id_created_at_id_idx" ON "seasonal_campaigns"("organization_id", "created_at", "id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "seasonal_campaigns_organization_id_slug_key" ON "seasonal_campaigns"("organization_id", "slug");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "seasonal_campaigns_organization_id_idempotency_key_key" ON "seasonal_campaigns"("organization_id", "idempotency_key");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "seasonal_campaigns" ADD CONSTRAINT "seasonal_campaigns_collection_id_organization_id_fkey" FOREIGN KEY ("collection_id", "organization_id") REFERENCES "catalog_groups"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "seasonal_campaigns" ADD CONSTRAINT "seasonal_campaigns_created_by_id_organization_id_fkey" FOREIGN KEY ("created_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "seasonal_campaigns" ADD CONSTRAINT "seasonal_campaigns_published_by_id_organization_id_fkey" FOREIGN KEY ("published_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "seasonal_campaigns" ADD CONSTRAINT "seasonal_campaigns_cancelled_by_id_organization_id_fkey" FOREIGN KEY ("cancelled_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
ALTER TABLE seasonal_campaigns
|
||||
ADD CONSTRAINT campaign_window CHECK (ends_at > starts_at),
|
||||
ADD CONSTRAINT campaign_version CHECK (version >= 0),
|
||||
ADD CONSTRAINT campaign_slug CHECK (slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$'),
|
||||
ADD CONSTRAINT campaign_title CHECK (char_length(btrim(title)) >= 1),
|
||||
ADD CONSTRAINT campaign_hash CHECK (request_hash ~ '^[a-f0-9]{64}$'),
|
||||
ADD CONSTRAINT campaign_publication_fields CHECK ((published_at IS NULL) = (published_by_id IS NULL)),
|
||||
ADD CONSTRAINT campaign_cancellation_fields CHECK (
|
||||
(state <> 'CANCELLED' AND cancelled_at IS NULL AND cancelled_by_id IS NULL AND cancellation_reason IS NULL)
|
||||
OR (state = 'CANCELLED' AND cancelled_at IS NOT NULL AND cancelled_by_id IS NOT NULL AND cancellation_reason IS NOT NULL AND char_length(btrim(cancellation_reason)) >= 3)),
|
||||
ADD CONSTRAINT campaign_state_fields CHECK (
|
||||
(state = 'DRAFT' AND published_at IS NULL)
|
||||
OR (state = 'PUBLISHED' AND published_at IS NOT NULL)
|
||||
OR state = 'CANCELLED');
|
||||
|
||||
CREATE FUNCTION guard_seasonal_campaign() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF TG_OP = 'DELETE' THEN RAISE EXCEPTION 'Campaigns cannot be deleted'; END IF;
|
||||
IF TG_OP = 'INSERT' THEN
|
||||
IF NEW.state <> 'DRAFT' OR NEW.version <> 0 THEN RAISE EXCEPTION 'Campaigns must start as drafts'; END IF;
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
IF (NEW.id, NEW.organization_id, NEW.created_by_id, NEW.slug, NEW.idempotency_key, NEW.request_hash, NEW.created_at)
|
||||
IS DISTINCT FROM (OLD.id, OLD.organization_id, OLD.created_by_id, OLD.slug, OLD.idempotency_key, OLD.request_hash, OLD.created_at)
|
||||
THEN RAISE EXCEPTION 'Campaign identity is immutable'; END IF;
|
||||
IF OLD.state = 'CANCELLED' THEN RAISE EXCEPTION 'Cancelled campaigns are immutable'; END IF;
|
||||
IF NEW.version <> OLD.version + 1 THEN RAISE EXCEPTION 'Campaign update requires next version'; END IF;
|
||||
IF OLD.state <> 'DRAFT' OR NEW.state <> 'DRAFT' THEN
|
||||
IF (NEW.title, NEW.summary, NEW.collection_id, NEW.starts_at, NEW.ends_at)
|
||||
IS DISTINCT FROM (OLD.title, OLD.summary, OLD.collection_id, OLD.starts_at, OLD.ends_at)
|
||||
THEN RAISE EXCEPTION 'Published campaign terms are immutable'; END IF;
|
||||
END IF;
|
||||
IF OLD.state = 'DRAFT' AND NEW.state = 'DRAFT' THEN RETURN NEW; END IF;
|
||||
IF OLD.state = 'DRAFT' AND NEW.state = 'PUBLISHED' THEN
|
||||
IF NEW.published_at IS NULL OR NEW.published_by_id IS NULL OR NEW.ends_at <= NEW.published_at
|
||||
THEN RAISE EXCEPTION 'Publication requires unexpired terms and staff metadata'; END IF;
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
IF NEW.state = 'CANCELLED' THEN
|
||||
IF (NEW.published_at, NEW.published_by_id) IS DISTINCT FROM (OLD.published_at, OLD.published_by_id)
|
||||
THEN RAISE EXCEPTION 'Publication metadata is immutable'; END IF;
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
RAISE EXCEPTION 'Invalid campaign transition';
|
||||
END;
|
||||
$$;
|
||||
CREATE TRIGGER seasonal_campaigns_guard BEFORE INSERT OR UPDATE OR DELETE ON seasonal_campaigns
|
||||
FOR EACH ROW EXECUTE FUNCTION guard_seasonal_campaign();
|
||||
|
||||
UPDATE roles SET permissions = ARRAY(SELECT DISTINCT unnest(permissions || ARRAY['campaigns.read', 'campaigns.manage']))
|
||||
WHERE is_system = true AND name = 'Owner';
|
||||
|
|
@ -1,52 +0,0 @@
|
|||
-- AlterTable
|
||||
ALTER TABLE "coupons" ADD COLUMN "campaign_id" UUID;
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "seasonal_campaigns_id_organization_id_key" ON "seasonal_campaigns"("id", "organization_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "coupons_campaign_id_key" ON "coupons"("campaign_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "coupons_campaign_id_organization_id_key" ON "coupons"("campaign_id", "organization_id");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "coupons" ADD CONSTRAINT "coupons_campaign_id_organization_id_fkey" FOREIGN KEY ("campaign_id", "organization_id") REFERENCES "seasonal_campaigns"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
CREATE FUNCTION guard_campaign_coupon() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
DECLARE campaign seasonal_campaigns%ROWTYPE;
|
||||
BEGIN
|
||||
IF TG_OP = 'DELETE' THEN
|
||||
IF OLD.campaign_id IS NOT NULL THEN RAISE EXCEPTION 'Campaign coupon association is immutable'; END IF;
|
||||
RETURN OLD;
|
||||
END IF;
|
||||
IF NEW.campaign_id IS NULL THEN RETURN NEW; END IF;
|
||||
SELECT * INTO campaign FROM seasonal_campaigns
|
||||
WHERE id = NEW.campaign_id AND organization_id = NEW.organization_id FOR UPDATE;
|
||||
IF campaign.id IS NULL OR campaign.state <> 'DRAFT' THEN RAISE EXCEPTION 'Coupon requires an organization-scoped draft campaign'; END IF;
|
||||
IF NEW.starts_at < campaign.starts_at OR NEW.ends_at > campaign.ends_at
|
||||
THEN RAISE EXCEPTION 'Coupon dates must fit campaign window'; END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
CREATE TRIGGER coupons_campaign_guard BEFORE INSERT OR DELETE ON coupons
|
||||
FOR EACH ROW EXECUTE FUNCTION guard_campaign_coupon();
|
||||
|
||||
CREATE FUNCTION bump_campaign_coupon_version() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
UPDATE seasonal_campaigns SET version = version + 1, updated_at = CURRENT_TIMESTAMP WHERE id = NEW.campaign_id;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
CREATE TRIGGER coupons_campaign_version AFTER INSERT ON coupons
|
||||
FOR EACH ROW WHEN (NEW.campaign_id IS NOT NULL) EXECUTE FUNCTION bump_campaign_coupon_version();
|
||||
|
||||
CREATE FUNCTION check_campaign_coupon_window() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF EXISTS (SELECT 1 FROM coupons WHERE campaign_id = NEW.id AND (starts_at < NEW.starts_at OR ends_at > NEW.ends_at))
|
||||
THEN RAISE EXCEPTION 'Campaign window must contain its coupon window'; END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
CREATE TRIGGER seasonal_campaigns_coupon_window BEFORE UPDATE ON seasonal_campaigns
|
||||
FOR EACH ROW EXECUTE FUNCTION check_campaign_coupon_window();
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
-- Historical carts have unknown activity; reads must not invent abandonment times.
|
||||
ALTER TABLE "carts" ADD COLUMN "last_activity_at" TIMESTAMPTZ(3);
|
||||
|
|
@ -1,40 +0,0 @@
|
|||
CREATE TABLE "messaging_consent_decisions" (
|
||||
"id" UUID NOT NULL,
|
||||
"organization_id" UUID NOT NULL,
|
||||
"user_id" UUID NOT NULL,
|
||||
"channel" VARCHAR(20) NOT NULL,
|
||||
"purpose" VARCHAR(20) NOT NULL,
|
||||
"granted" BOOLEAN NOT NULL,
|
||||
"version" INTEGER NOT NULL,
|
||||
"notice_version" VARCHAR(40),
|
||||
"idempotency_key" UUID NOT NULL,
|
||||
"request_hash" CHAR(64) NOT NULL,
|
||||
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "messaging_consent_decisions_pkey" PRIMARY KEY ("id"),
|
||||
CONSTRAINT "messaging_consent_decisions_user_id_organization_id_fkey" FOREIGN KEY ("user_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE,
|
||||
CONSTRAINT "messaging_consent_terms" CHECK (
|
||||
channel IN ('EMAIL', 'WHATSAPP') AND purpose IN ('PROMOTIONS', 'CART_RECOVERY') AND version > 0
|
||||
AND ((granted AND notice_version = '2026-10-07' AND notice_version IS NOT NULL) OR (NOT granted AND notice_version IS NULL))
|
||||
AND request_hash ~ '^[a-f0-9]{64}$'
|
||||
)
|
||||
);
|
||||
CREATE UNIQUE INDEX "messaging_consent_decisions_user_id_organization_id_channel_key" ON "messaging_consent_decisions"("user_id", "organization_id", "channel", "purpose", "version");
|
||||
CREATE UNIQUE INDEX "messaging_consent_decisions_user_id_organization_id_idempot_key" ON "messaging_consent_decisions"("user_id", "organization_id", "idempotency_key");
|
||||
CREATE INDEX "messaging_consent_decisions_user_id_organization_id_created_idx" ON "messaging_consent_decisions"("user_id", "organization_id", "created_at", "id");
|
||||
|
||||
CREATE FUNCTION guard_messaging_consent() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
DECLARE previous_version integer;
|
||||
BEGIN
|
||||
IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Messaging consent decisions are immutable'; END IF;
|
||||
PERFORM id FROM organizations WHERE id = NEW.organization_id FOR UPDATE;
|
||||
SELECT COALESCE(MAX(version), 0) INTO previous_version FROM messaging_consent_decisions
|
||||
WHERE organization_id = NEW.organization_id AND user_id = NEW.user_id AND channel = NEW.channel AND purpose = NEW.purpose;
|
||||
IF NEW.version::bigint <> previous_version::bigint + 1 THEN RAISE EXCEPTION 'Consent requires next version'; END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
CREATE TRIGGER messaging_consent_guard BEFORE INSERT OR UPDATE OR DELETE ON messaging_consent_decisions
|
||||
FOR EACH ROW EXECUTE FUNCTION guard_messaging_consent();
|
||||
|
||||
UPDATE roles SET permissions = ARRAY(SELECT DISTINCT unnest(permissions || ARRAY['messaging.read']))
|
||||
WHERE is_system = true AND name = 'Owner';
|
||||
|
|
@ -1,62 +0,0 @@
|
|||
CREATE TYPE "BlogState" AS ENUM ('DRAFT', 'PUBLISHED', 'WITHDRAWN');
|
||||
CREATE TABLE "blog_articles" (
|
||||
"id" UUID NOT NULL, "organization_id" UUID NOT NULL, "created_by_id" UUID NOT NULL,
|
||||
"slug" VARCHAR(100) NOT NULL, "title" VARCHAR(160) NOT NULL, "summary" VARCHAR(500) NOT NULL, "body" TEXT NOT NULL,
|
||||
"state" "BlogState" NOT NULL DEFAULT 'DRAFT', "version" INTEGER NOT NULL DEFAULT 0,
|
||||
"published_content" JSONB, "publication_version" INTEGER, "published_at" TIMESTAMPTZ(3), "published_by_id" UUID,
|
||||
"withdrawn_at" TIMESTAMPTZ(3), "withdrawn_by_id" UUID, "withdrawal_reason" VARCHAR(500),
|
||||
"idempotency_key" UUID NOT NULL, "request_hash" CHAR(64) NOT NULL,
|
||||
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, "updated_at" TIMESTAMPTZ(3) NOT NULL,
|
||||
CONSTRAINT "blog_articles_pkey" PRIMARY KEY ("id"),
|
||||
CONSTRAINT "blog_articles_created_by_id_organization_id_fkey" FOREIGN KEY ("created_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE,
|
||||
CONSTRAINT "blog_articles_published_by_id_organization_id_fkey" FOREIGN KEY ("published_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE,
|
||||
CONSTRAINT "blog_articles_withdrawn_by_id_organization_id_fkey" FOREIGN KEY ("withdrawn_by_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE,
|
||||
CONSTRAINT "blog_article_terms" CHECK (version >= 0 AND char_length(title) >= 1 AND char_length(summary) >= 1 AND char_length(body) BETWEEN 1 AND 20000 AND slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' AND request_hash ~ '^[a-f0-9]{64}$'),
|
||||
CONSTRAINT "blog_publication_metadata" CHECK (
|
||||
(published_content IS NULL AND publication_version IS NULL AND published_at IS NULL AND published_by_id IS NULL)
|
||||
OR (published_content IS NOT NULL AND jsonb_typeof(published_content) = 'object' AND publication_version IS NOT NULL AND publication_version >= 0 AND publication_version < version AND published_at IS NOT NULL AND published_by_id IS NOT NULL)
|
||||
),
|
||||
CONSTRAINT "blog_state_metadata" CHECK (
|
||||
(state = 'DRAFT' AND published_content IS NULL OR state = 'PUBLISHED' AND published_content IS NOT NULL OR state = 'WITHDRAWN')
|
||||
AND ((state = 'WITHDRAWN' AND withdrawn_at IS NOT NULL AND withdrawn_by_id IS NOT NULL AND withdrawal_reason IS NOT NULL AND char_length(withdrawal_reason) >= 3)
|
||||
OR (state <> 'WITHDRAWN' AND withdrawn_at IS NULL AND withdrawn_by_id IS NULL AND withdrawal_reason IS NULL))
|
||||
)
|
||||
);
|
||||
CREATE UNIQUE INDEX "blog_articles_organization_id_slug_key" ON "blog_articles"("organization_id", "slug");
|
||||
CREATE UNIQUE INDEX "blog_articles_organization_id_idempotency_key_key" ON "blog_articles"("organization_id", "idempotency_key");
|
||||
CREATE INDEX "blog_articles_organization_id_state_published_at_id_idx" ON "blog_articles"("organization_id", "state", "published_at", "id");
|
||||
CREATE INDEX "blog_articles_organization_id_created_at_id_idx" ON "blog_articles"("organization_id", "created_at", "id");
|
||||
|
||||
CREATE FUNCTION guard_blog_article() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF TG_OP = 'DELETE' THEN RAISE EXCEPTION 'Blog articles cannot be deleted'; END IF;
|
||||
IF TG_OP = 'INSERT' THEN
|
||||
IF NEW.state <> 'DRAFT' OR NEW.version <> 0 THEN RAISE EXCEPTION 'Articles must begin as drafts'; END IF;
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
IF OLD.state = 'WITHDRAWN' THEN RAISE EXCEPTION 'Withdrawn articles are immutable'; END IF;
|
||||
IF (NEW.id, NEW.organization_id, NEW.created_by_id, NEW.slug, NEW.idempotency_key, NEW.request_hash, NEW.created_at)
|
||||
IS DISTINCT FROM (OLD.id, OLD.organization_id, OLD.created_by_id, OLD.slug, OLD.idempotency_key, OLD.request_hash, OLD.created_at)
|
||||
THEN RAISE EXCEPTION 'Article identity is immutable'; END IF;
|
||||
IF NEW.version::bigint <> OLD.version::bigint + 1 THEN RAISE EXCEPTION 'Article requires next version'; END IF;
|
||||
IF NEW.state = 'WITHDRAWN' THEN
|
||||
IF (NEW.title, NEW.summary, NEW.body, NEW.published_content, NEW.publication_version, NEW.published_at, NEW.published_by_id)
|
||||
IS DISTINCT FROM (OLD.title, OLD.summary, OLD.body, OLD.published_content, OLD.publication_version, OLD.published_at, OLD.published_by_id)
|
||||
THEN RAISE EXCEPTION 'Withdrawal cannot rewrite content'; END IF;
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
IF (NEW.published_content, NEW.publication_version, NEW.published_at, NEW.published_by_id)
|
||||
IS DISTINCT FROM (OLD.published_content, OLD.publication_version, OLD.published_at, OLD.published_by_id) THEN
|
||||
IF NEW.state <> 'PUBLISHED' OR NEW.publication_version IS DISTINCT FROM OLD.version
|
||||
OR NEW.published_content IS DISTINCT FROM jsonb_build_object('title', OLD.title, 'summary', OLD.summary, 'body', OLD.body)
|
||||
OR (NEW.title, NEW.summary, NEW.body) IS DISTINCT FROM (OLD.title, OLD.summary, OLD.body)
|
||||
THEN RAISE EXCEPTION 'Publication requires the reviewed draft snapshot'; END IF;
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
IF NEW.state <> OLD.state THEN RAISE EXCEPTION 'Invalid article transition'; END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
CREATE TRIGGER blog_articles_guard BEFORE INSERT OR UPDATE OR DELETE ON blog_articles FOR EACH ROW EXECUTE FUNCTION guard_blog_article();
|
||||
UPDATE roles SET permissions = ARRAY(SELECT DISTINCT unnest(permissions || ARRAY['blog.read', 'blog.manage', 'blog.publish']))
|
||||
WHERE is_system = true AND name = 'Owner';
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
-- Audiences are derived from current source records, not persisted member copies.
|
||||
UPDATE roles SET permissions = ARRAY(SELECT DISTINCT unnest(permissions || ARRAY['segments.read']))
|
||||
WHERE is_system = true AND name = 'Owner';
|
||||
|
|
@ -1,85 +0,0 @@
|
|||
CREATE TYPE "ForumDecisionKind" AS ENUM ('APPROVED', 'REJECTED', 'HIDDEN');
|
||||
CREATE TABLE "forum_posts" (
|
||||
"id" UUID NOT NULL, "organization_id" UUID NOT NULL, "user_id" UUID NOT NULL, "thread_id" UUID,
|
||||
"display_name" VARCHAR(80) NOT NULL, "title" VARCHAR(160), "body" VARCHAR(5000) NOT NULL,
|
||||
"idempotency_key" UUID NOT NULL, "request_hash" CHAR(64) NOT NULL,
|
||||
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "forum_posts_pkey" PRIMARY KEY ("id"),
|
||||
CONSTRAINT "forum_posts_user_id_organization_id_fkey" FOREIGN KEY ("user_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE,
|
||||
CONSTRAINT "forum_post_content" CHECK (char_length(btrim(display_name)) >= 1 AND char_length(btrim(body)) >= 10 AND request_hash ~ '^[a-f0-9]{64}$'),
|
||||
CONSTRAINT "forum_post_kind" CHECK ((thread_id IS NULL AND title IS NOT NULL AND char_length(btrim(title)) >= 3) OR (thread_id IS NOT NULL AND title IS NULL AND thread_id <> id))
|
||||
);
|
||||
CREATE UNIQUE INDEX "forum_posts_id_organization_id_key" ON "forum_posts"("id", "organization_id");
|
||||
CREATE UNIQUE INDEX "forum_posts_user_id_organization_id_idempotency_key_key" ON "forum_posts"("user_id", "organization_id", "idempotency_key");
|
||||
CREATE INDEX "forum_posts_organization_id_thread_id_created_at_id_idx" ON "forum_posts"("organization_id", "thread_id", "created_at", "id");
|
||||
CREATE INDEX "forum_posts_organization_id_user_id_created_at_id_idx" ON "forum_posts"("organization_id", "user_id", "created_at", "id");
|
||||
ALTER TABLE forum_posts ADD CONSTRAINT "forum_posts_thread_id_organization_id_fkey" FOREIGN KEY ("thread_id", "organization_id") REFERENCES "forum_posts"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
CREATE TABLE "forum_moderation" (
|
||||
"id" UUID NOT NULL, "organization_id" UUID NOT NULL, "post_id" UUID NOT NULL, "actor_id" UUID NOT NULL,
|
||||
"sequence" INTEGER NOT NULL, "kind" "ForumDecisionKind" NOT NULL, "note" VARCHAR(1000) NOT NULL,
|
||||
"idempotency_key" UUID NOT NULL, "request_hash" CHAR(64) NOT NULL,
|
||||
"created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "forum_moderation_pkey" PRIMARY KEY ("id"),
|
||||
CONSTRAINT "forum_moderation_post_id_organization_id_fkey" FOREIGN KEY ("post_id", "organization_id") REFERENCES "forum_posts"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE,
|
||||
CONSTRAINT "forum_moderation_actor_id_organization_id_fkey" FOREIGN KEY ("actor_id", "organization_id") REFERENCES "users"("id", "organization_id") ON DELETE RESTRICT ON UPDATE CASCADE,
|
||||
CONSTRAINT "forum_moderation_terms" CHECK (sequence BETWEEN 1 AND 2 AND char_length(btrim(note)) >= 3 AND request_hash ~ '^[a-f0-9]{64}$')
|
||||
);
|
||||
CREATE UNIQUE INDEX "forum_moderation_post_id_sequence_key" ON "forum_moderation"("post_id", "sequence");
|
||||
CREATE UNIQUE INDEX "forum_moderation_organization_id_idempotency_key_key" ON "forum_moderation"("organization_id", "idempotency_key");
|
||||
CREATE FUNCTION reject_forum_mutation() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN RAISE EXCEPTION 'Forum submissions and moderation history are immutable'; END;
|
||||
$$;
|
||||
CREATE TRIGGER forum_posts_immutable BEFORE UPDATE OR DELETE ON forum_posts FOR EACH ROW EXECUTE FUNCTION reject_forum_mutation();
|
||||
CREATE TRIGGER forum_moderation_immutable BEFORE UPDATE OR DELETE ON forum_moderation FOR EACH ROW EXECUTE FUNCTION reject_forum_mutation();
|
||||
|
||||
CREATE FUNCTION guard_forum_submission() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
DECLARE parent forum_posts%ROWTYPE;
|
||||
BEGIN
|
||||
PERFORM id FROM organizations WHERE id = NEW.organization_id FOR UPDATE;
|
||||
IF NOT EXISTS (SELECT 1 FROM users WHERE id = NEW.user_id AND organization_id = NEW.organization_id AND status = 'ACTIVE')
|
||||
THEN RAISE EXCEPTION 'Forum submission requires an active author'; END IF;
|
||||
IF (SELECT COUNT(*) FROM forum_posts p WHERE p.user_id = NEW.user_id AND p.organization_id = NEW.organization_id
|
||||
AND NOT EXISTS (SELECT 1 FROM forum_moderation m WHERE m.post_id = p.id)) >= 20
|
||||
THEN RAISE EXCEPTION 'Forum pending submission limit reached'; END IF;
|
||||
IF NEW.thread_id IS NOT NULL THEN
|
||||
SELECT * INTO parent FROM forum_posts WHERE id = NEW.thread_id AND organization_id = NEW.organization_id FOR UPDATE;
|
||||
IF parent.id IS NULL OR parent.thread_id IS NOT NULL
|
||||
OR NOT EXISTS (SELECT 1 FROM users WHERE id = parent.user_id AND status = 'ACTIVE')
|
||||
OR NOT EXISTS (SELECT 1 FROM forum_moderation WHERE post_id = parent.id AND kind = 'APPROVED')
|
||||
OR EXISTS (SELECT 1 FROM forum_moderation WHERE post_id = parent.id AND kind = 'HIDDEN')
|
||||
THEN RAISE EXCEPTION 'Reply requires an available approved thread'; END IF;
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
CREATE TRIGGER forum_posts_eligibility BEFORE INSERT ON forum_posts FOR EACH ROW EXECUTE FUNCTION guard_forum_submission();
|
||||
|
||||
CREATE FUNCTION guard_forum_moderation() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
DECLARE target forum_posts%ROWTYPE; parent forum_posts%ROWTYPE; last_kind "ForumDecisionKind";
|
||||
BEGIN
|
||||
PERFORM id FROM organizations WHERE id = NEW.organization_id FOR UPDATE;
|
||||
SELECT * INTO target FROM forum_posts WHERE id = NEW.post_id AND organization_id = NEW.organization_id FOR UPDATE;
|
||||
IF target.id IS NULL OR target.user_id = NEW.actor_id THEN RAISE EXCEPTION 'Forum post requires an independent moderator'; END IF;
|
||||
SELECT kind INTO last_kind FROM forum_moderation WHERE post_id = target.id ORDER BY sequence DESC LIMIT 1;
|
||||
IF NEW.kind = 'HIDDEN' THEN
|
||||
IF NEW.sequence <> 2 OR last_kind IS DISTINCT FROM 'APPROVED'::"ForumDecisionKind"
|
||||
THEN RAISE EXCEPTION 'Only approved posts can be hidden'; END IF;
|
||||
ELSE
|
||||
IF NEW.sequence <> 1 OR last_kind IS NOT NULL THEN RAISE EXCEPTION 'Post already decided'; END IF;
|
||||
IF NEW.kind = 'APPROVED' THEN
|
||||
IF NOT EXISTS (SELECT 1 FROM users WHERE id = target.user_id AND status = 'ACTIVE') THEN RAISE EXCEPTION 'Inactive author cannot be approved'; END IF;
|
||||
IF target.thread_id IS NOT NULL THEN
|
||||
SELECT * INTO parent FROM forum_posts WHERE id = target.thread_id FOR UPDATE;
|
||||
IF NOT EXISTS (SELECT 1 FROM users WHERE id = parent.user_id AND status = 'ACTIVE')
|
||||
OR NOT EXISTS (SELECT 1 FROM forum_moderation WHERE post_id = parent.id AND kind = 'APPROVED')
|
||||
OR EXISTS (SELECT 1 FROM forum_moderation WHERE post_id = parent.id AND kind = 'HIDDEN')
|
||||
THEN RAISE EXCEPTION 'Reply approval requires an available thread'; END IF;
|
||||
END IF;
|
||||
END IF;
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
CREATE TRIGGER forum_moderation_transition BEFORE INSERT ON forum_moderation FOR EACH ROW EXECUTE FUNCTION guard_forum_moderation();
|
||||
UPDATE roles SET permissions = ARRAY(SELECT DISTINCT unnest(permissions || ARRAY['forum.read', 'forum.moderate']))
|
||||
WHERE is_system = true AND name = 'Owner';
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
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';
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
UPDATE roles SET permissions = ARRAY(SELECT DISTINCT unnest(permissions || ARRAY['forecasts.read']))
|
||||
WHERE is_system = true AND name = 'Owner';
|
||||
|
|
@ -1,8 +0,0 @@
|
|||
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';
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
UPDATE roles SET permissions = ARRAY(SELECT DISTINCT unnest(permissions || ARRAY['profitability.read']))
|
||||
WHERE is_system = true AND name = 'Owner';
|
||||
|
|
@ -1,24 +0,0 @@
|
|||
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';
|
||||
|
|
@ -1,9 +0,0 @@
|
|||
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,7 +86,6 @@ model B2bPartnerPayment {
|
|||
@@unique([organizationId, reference])
|
||||
@@index([organizationId, orderId, createdAt, id])
|
||||
@@map("b2b_partner_payments")
|
||||
@@index([organizationId, createdAt, id], map: "partner_payments_accounting_idx")
|
||||
}
|
||||
|
||||
model B2bPartnerPaymentReversal {
|
||||
|
|
@ -103,5 +102,4 @@ model B2bPartnerPaymentReversal {
|
|||
@@unique([paymentId, organizationId])
|
||||
@@unique([organizationId, idempotencyKey])
|
||||
@@map("b2b_partner_payment_reversals")
|
||||
@@index([organizationId, createdAt, paymentId], map: "partner_payment_reversals_accounting_idx")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -224,7 +224,6 @@ model SupplierInvoice {
|
|||
@@unique([id, organizationId])
|
||||
@@index([organizationId, purchaseOrderId, createdAt, id], map: "supplier_invoices_order_created_idx")
|
||||
@@map("supplier_invoices")
|
||||
@@index([organizationId, createdAt, id], map: "supplier_invoices_accounting_idx")
|
||||
}
|
||||
|
||||
model SupplierInvoiceLine {
|
||||
|
|
@ -254,7 +253,6 @@ model SupplierInvoiceVoid {
|
|||
voidedBy User @relation(fields: [voidedById, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
@@unique([invoiceId, organizationId])
|
||||
@@map("supplier_invoice_voids")
|
||||
@@index([organizationId, createdAt, invoiceId], map: "supplier_invoice_voids_accounting_idx")
|
||||
}
|
||||
|
||||
model SupplierPayment {
|
||||
|
|
@ -279,7 +277,6 @@ model SupplierPayment {
|
|||
@@unique([id, organizationId])
|
||||
@@index([organizationId, invoiceId, createdAt, id], map: "supplier_payments_invoice_created_idx")
|
||||
@@map("supplier_payments")
|
||||
@@index([organizationId, createdAt, id], map: "supplier_payments_accounting_idx")
|
||||
}
|
||||
|
||||
model SupplierPaymentReversal {
|
||||
|
|
@ -293,5 +290,4 @@ model SupplierPaymentReversal {
|
|||
reversedBy User @relation(fields: [reversedById, organizationId], references: [id, organizationId], onDelete: Restrict, map: "supplier_payment_reversal_actor_scope_fkey")
|
||||
@@unique([paymentId, organizationId])
|
||||
@@map("supplier_payment_reversals")
|
||||
@@index([organizationId, createdAt, paymentId], map: "supplier_payment_reversals_accounting_idx")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,13 +0,0 @@
|
|||
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")
|
||||
}
|
||||
|
|
@ -1,88 +0,0 @@
|
|||
enum ReviewModerationKind {
|
||||
APPROVED
|
||||
REJECTED
|
||||
HIDDEN
|
||||
}
|
||||
|
||||
model ReviewPurchaseVerification {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
organizationId String @map("organization_id") @db.Uuid
|
||||
userId String @map("user_id") @db.Uuid
|
||||
variantId String @map("variant_id") @db.Uuid
|
||||
actorId String @map("actor_id") @db.Uuid
|
||||
reference String @db.VarChar(100)
|
||||
note String @db.VarChar(1000)
|
||||
idempotencyKey String @map("idempotency_key") @db.Uuid
|
||||
requestHash String @map("request_hash") @db.Char(64)
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
|
||||
user User @relation("ReviewBuyer", fields: [userId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
actor User @relation("ReviewVerifier", fields: [actorId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
variant ProductVariant @relation(fields: [variantId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
revocation ReviewPurchaseRevocation?
|
||||
review ProductReview?
|
||||
@@unique([id, userId, variantId, organizationId])
|
||||
@@unique([id, organizationId])
|
||||
@@unique([organizationId, idempotencyKey])
|
||||
@@unique([organizationId, reference, variantId])
|
||||
@@index([organizationId, userId, createdAt, id])
|
||||
@@map("review_purchase_verifications")
|
||||
}
|
||||
|
||||
model ReviewPurchaseRevocation {
|
||||
verificationId String @id @map("verification_id") @db.Uuid
|
||||
organizationId String @map("organization_id") @db.Uuid
|
||||
actorId String @map("actor_id") @db.Uuid
|
||||
reason String @db.VarChar(1000)
|
||||
idempotencyKey String @map("idempotency_key") @db.Uuid
|
||||
requestHash String @map("request_hash") @db.Char(64)
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
|
||||
verification ReviewPurchaseVerification @relation(fields: [verificationId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
actor User @relation(fields: [actorId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
@@unique([verificationId, organizationId])
|
||||
@@unique([organizationId, idempotencyKey])
|
||||
@@map("review_purchase_revocations")
|
||||
}
|
||||
|
||||
model ProductReview {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
organizationId String @map("organization_id") @db.Uuid
|
||||
userId String @map("user_id") @db.Uuid
|
||||
variantId String @map("variant_id") @db.Uuid
|
||||
verificationId String @unique @map("verification_id") @db.Uuid
|
||||
rating Int
|
||||
displayName String @map("display_name") @db.VarChar(80)
|
||||
title String @db.VarChar(160)
|
||||
body String @db.VarChar(2000)
|
||||
idempotencyKey String @map("idempotency_key") @db.Uuid
|
||||
requestHash String @map("request_hash") @db.Char(64)
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
|
||||
verification ReviewPurchaseVerification @relation(fields: [verificationId, userId, variantId, organizationId], references: [id, userId, variantId, organizationId], onDelete: Restrict)
|
||||
variant ProductVariant @relation(fields: [variantId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
events ProductReviewModeration[]
|
||||
@@unique([id, organizationId])
|
||||
@@unique([verificationId, userId, variantId, organizationId])
|
||||
@@unique([userId, organizationId, variantId])
|
||||
@@unique([userId, organizationId, idempotencyKey])
|
||||
@@index([organizationId, userId, createdAt, id])
|
||||
@@index([organizationId, variantId, createdAt, id])
|
||||
@@index([organizationId, createdAt, id])
|
||||
@@map("product_reviews")
|
||||
}
|
||||
|
||||
model ProductReviewModeration {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
organizationId String @map("organization_id") @db.Uuid
|
||||
reviewId String @map("review_id") @db.Uuid
|
||||
actorId String @map("actor_id") @db.Uuid
|
||||
sequence Int
|
||||
kind ReviewModerationKind
|
||||
note String @db.VarChar(1000)
|
||||
idempotencyKey String @map("idempotency_key") @db.Uuid
|
||||
requestHash String @map("request_hash") @db.Char(64)
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
|
||||
review ProductReview @relation(fields: [reviewId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
actor User @relation(fields: [actorId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
@@unique([reviewId, sequence])
|
||||
@@unique([organizationId, idempotencyKey])
|
||||
@@map("product_review_moderation")
|
||||
}
|
||||
|
|
@ -89,21 +89,6 @@ model User {
|
|||
sessions Session[]
|
||||
recoveryTokens RecoveryToken[]
|
||||
addresses Address[]
|
||||
wishlistItems WishlistItem[]
|
||||
messagingConsents MessagingConsentDecision[]
|
||||
blogsCreated BlogArticle[] @relation("BlogCreator")
|
||||
blogsPublished BlogArticle[] @relation("BlogPublisher")
|
||||
blogsWithdrawn BlogArticle[] @relation("BlogWithdrawer")
|
||||
forumPosts ForumPost[]
|
||||
forumDecisions ForumModeration[]
|
||||
expiryRuns OrderExpiryRun[]
|
||||
reviewPurchases ReviewPurchaseVerification[] @relation("ReviewBuyer")
|
||||
reviewVerifications ReviewPurchaseVerification[] @relation("ReviewVerifier")
|
||||
reviewRevocations ReviewPurchaseRevocation[]
|
||||
reviewModerations ProductReviewModeration[]
|
||||
campaignsCreated SeasonalCampaign[] @relation("CampaignCreator")
|
||||
campaignsPublished SeasonalCampaign[] @relation("CampaignPublisher")
|
||||
campaignsCancelled SeasonalCampaign[] @relation("CampaignCanceller")
|
||||
purchaseOrders PurchaseOrder[]
|
||||
goodsReceipts GoodsReceipt[]
|
||||
receiptInspections ReceiptInspection[]
|
||||
|
|
|
|||
|
|
@ -1,12 +0,0 @@
|
|||
model WishlistItem {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
organizationId String @map("organization_id") @db.Uuid
|
||||
userId String @map("user_id") @db.Uuid
|
||||
variantId String @map("variant_id") @db.Uuid
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
|
||||
user User @relation(fields: [userId, organizationId], references: [id, organizationId], onDelete: Cascade)
|
||||
variant ProductVariant @relation(fields: [variantId, organizationId], references: [id, organizationId], onDelete: Restrict)
|
||||
@@unique([userId, organizationId, variantId])
|
||||
@@index([userId, organizationId, createdAt, id])
|
||||
@@map("wishlist_items")
|
||||
}
|
||||
|
|
@ -1,15 +0,0 @@
|
|||
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")
|
||||
}
|
||||
|
|
@ -1,83 +0,0 @@
|
|||
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;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,55 +0,0 @@
|
|||
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/);
|
||||
}
|
||||
});
|
||||
|
|
@ -1,16 +0,0 @@
|
|||
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);
|
||||
});
|
||||
|
|
@ -1,21 +0,0 @@
|
|||
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);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,10 +0,0 @@
|
|||
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 {}
|
||||
|
|
@ -1,53 +0,0 @@
|
|||
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');
|
||||
}
|
||||
|
|
@ -1,57 +0,0 @@
|
|||
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}`;
|
||||
}
|
||||
|
|
@ -1,30 +0,0 @@
|
|||
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>;
|
||||
|
|
@ -1,73 +0,0 @@
|
|||
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,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,53 +0,0 @@
|
|||
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}`;
|
||||
}
|
||||
|
|
@ -1,33 +0,0 @@
|
|||
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);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,12 +0,0 @@
|
|||
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 {}
|
||||
|
|
@ -1,40 +0,0 @@
|
|||
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>;
|
||||
|
|
@ -1,91 +0,0 @@
|
|||
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,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,18 +0,0 @@
|
|||
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();
|
||||
}
|
||||
|
|
@ -1,21 +0,0 @@
|
|||
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}`;
|
||||
}
|
||||
|
|
@ -1,16 +0,0 @@
|
|||
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>;
|
||||
|
|
@ -1,65 +0,0 @@
|
|||
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,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,24 +0,0 @@
|
|||
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);
|
||||
}
|
||||
}
|
||||
|
|
@ -11,29 +11,9 @@ import { EnvironmentModule } from './config/environment.module';
|
|||
import { IdentityModule } from './identity/identity.module';
|
||||
import { HealthModule } from './health/health.module';
|
||||
import { B2bModule } from './b2b/b2b.module';
|
||||
import { WishlistModule } from './wishlist/wishlist.module';
|
||||
import { ReviewsModule } from './reviews/reviews.module';
|
||||
import { CampaignsModule } from './campaigns/campaigns.module';
|
||||
import { MessagingModule } from './messaging/messaging.module';
|
||||
import { BlogModule } from './blog/blog.module';
|
||||
import { SegmentsModule } from './segments/segments.module';
|
||||
import { ForumModule } from './forum/forum.module';
|
||||
import { AnalyticsModule } from './analytics/analytics.module';
|
||||
import { AccountingModule } from './accounting/accounting.module';
|
||||
import { WorkflowsModule } from './workflows/workflows.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
WorkflowsModule,
|
||||
AccountingModule,
|
||||
AnalyticsModule,
|
||||
ForumModule,
|
||||
SegmentsModule,
|
||||
BlogModule,
|
||||
MessagingModule,
|
||||
CampaignsModule,
|
||||
ReviewsModule,
|
||||
WishlistModule,
|
||||
EnvironmentModule,
|
||||
HealthModule,
|
||||
IdentityModule,
|
||||
|
|
|
|||
|
|
@ -1,6 +1,4 @@
|
|||
import { CustomCandlesController } from './custom-candles.controller';
|
||||
import { PartnerReportsController } from './partner-reports.controller';
|
||||
import { PartnerReportStore } from './partner-report.store';
|
||||
import { CustomCandleStore } from './custom-candle.store';
|
||||
import { CustomCandleReviewStore } from './custom-candle-review.store';
|
||||
import { Module } from '@nestjs/common';
|
||||
|
|
@ -38,7 +36,6 @@ import { PartnerPaymentWriteStore } from './partner-payment-write.store';
|
|||
@Module({
|
||||
imports: [DatabaseModule, IdentityModule],
|
||||
controllers: [
|
||||
PartnerReportsController,
|
||||
CustomCandlesController,
|
||||
BusinessController,
|
||||
PriceListsController,
|
||||
|
|
@ -52,7 +49,6 @@ import { PartnerPaymentWriteStore } from './partner-payment-write.store';
|
|||
PartnerPaymentsController,
|
||||
],
|
||||
providers: [
|
||||
PartnerReportStore,
|
||||
CustomCandleStore,
|
||||
CustomCandleReviewStore,
|
||||
BusinessStore,
|
||||
|
|
|
|||
|
|
@ -1,76 +0,0 @@
|
|||
import { Injectable } from '@nestjs/common';
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
import { Prisma } from '../generated/prisma/client';
|
||||
import type { Principal } from '../identity/identity.types';
|
||||
import { requireBusinessAccount } from './price-list.helpers';
|
||||
|
||||
type CurrencyReport = {
|
||||
currency: string;
|
||||
orderCount: number;
|
||||
activeOrderCount: number;
|
||||
cancelledOrderCount: number;
|
||||
unpaidOrderCount: number;
|
||||
partiallyPaidOrderCount: number;
|
||||
paidOrderCount: number;
|
||||
merchandiseTotal: string;
|
||||
paidTotal: string;
|
||||
outstandingTotal: string;
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class PartnerReportStore {
|
||||
constructor(private readonly db: DatabaseService) {}
|
||||
|
||||
report(actor: Principal, accountId: string) {
|
||||
return this.db.$transaction(
|
||||
async (tx) => {
|
||||
await requireBusinessAccount(tx, actor.organizationId, accountId);
|
||||
const currencies = await tx.$queryRaw<CurrencyReport[]>`
|
||||
WITH order_balances AS (
|
||||
SELECT o.currency, o.merchandise_total, c.order_id IS NOT NULL AS cancelled,
|
||||
COALESCE(p.paid_total, 0) AS paid_total
|
||||
FROM b2b_partner_orders o
|
||||
LEFT JOIN b2b_partner_order_cancellations c
|
||||
ON c.order_id = o.id AND c.organization_id = o.organization_id
|
||||
LEFT JOIN (
|
||||
SELECT p.order_id, p.organization_id, SUM(p.amount) AS paid_total
|
||||
FROM b2b_partner_payments p
|
||||
JOIN b2b_partner_orders target
|
||||
ON target.id = p.order_id AND target.organization_id = p.organization_id
|
||||
LEFT JOIN b2b_partner_payment_reversals r
|
||||
ON r.payment_id = p.id AND r.organization_id = p.organization_id
|
||||
WHERE p.organization_id = ${actor.organizationId}::uuid
|
||||
AND target.account_id = ${accountId}::uuid AND r.payment_id IS NULL
|
||||
GROUP BY p.order_id, p.organization_id
|
||||
) p ON p.order_id = o.id AND p.organization_id = o.organization_id
|
||||
WHERE o.organization_id = ${actor.organizationId}::uuid AND o.account_id = ${accountId}::uuid
|
||||
)
|
||||
SELECT currency, COUNT(*)::int AS "orderCount",
|
||||
COUNT(*) FILTER (WHERE NOT cancelled)::int AS "activeOrderCount",
|
||||
COUNT(*) FILTER (WHERE cancelled)::int AS "cancelledOrderCount",
|
||||
COUNT(*) FILTER (WHERE NOT cancelled AND paid_total = 0)::int AS "unpaidOrderCount",
|
||||
COUNT(*) FILTER (WHERE NOT cancelled AND paid_total > 0 AND paid_total < merchandise_total)::int AS "partiallyPaidOrderCount",
|
||||
COUNT(*) FILTER (WHERE NOT cancelled AND paid_total = merchandise_total)::int AS "paidOrderCount",
|
||||
COALESCE(SUM(merchandise_total) FILTER (WHERE NOT cancelled), 0)::text AS "merchandiseTotal",
|
||||
COALESCE(SUM(paid_total) FILTER (WHERE NOT cancelled), 0)::text AS "paidTotal",
|
||||
COALESCE(SUM(merchandise_total - paid_total) FILTER (WHERE NOT cancelled), 0)::text AS "outstandingTotal"
|
||||
FROM order_balances GROUP BY currency ORDER BY currency
|
||||
`;
|
||||
return {
|
||||
accountId,
|
||||
currencies: currencies.map((row) => ({
|
||||
...row,
|
||||
merchandiseTotal: new Prisma.Decimal(row.merchandiseTotal).toFixed(
|
||||
2,
|
||||
),
|
||||
paidTotal: new Prisma.Decimal(row.paidTotal).toFixed(2),
|
||||
outstandingTotal: new Prisma.Decimal(row.outstandingTotal).toFixed(
|
||||
2,
|
||||
),
|
||||
})),
|
||||
};
|
||||
},
|
||||
{ isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,21 +0,0 @@
|
|||
import { Controller, Get, Param, ParseUUIDPipe } from '@nestjs/common';
|
||||
import {
|
||||
CurrentPrincipal,
|
||||
RequirePermission,
|
||||
} from '../identity/access.decorator';
|
||||
import type { Principal } from '../identity/identity.types';
|
||||
import { PartnerReportStore } from './partner-report.store';
|
||||
|
||||
@Controller('b2b/accounts')
|
||||
export class PartnerReportsController {
|
||||
constructor(private readonly reports: PartnerReportStore) {}
|
||||
|
||||
@Get(':id/report')
|
||||
@RequirePermission('b2b.report.read')
|
||||
report(
|
||||
@CurrentPrincipal() actor: Principal,
|
||||
@Param('id', ParseUUIDPipe) id: string,
|
||||
) {
|
||||
return this.reports.report(actor, id);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,72 +0,0 @@
|
|||
import { Injectable } from '@nestjs/common';
|
||||
import { AccessStore } from '../identity/access.store';
|
||||
import type { Principal } from '../identity/identity.types';
|
||||
import { assertReplay, commandHash } from '../common/idempotency';
|
||||
import { recordAudit } from '../identity/audit';
|
||||
import { AppError } from '../common/errors/app-error';
|
||||
import { requireArticle, nextBlogVersion } from './blog-lookup';
|
||||
import type { BlogCreateInput, BlogPatchInput } from './blog.schemas';
|
||||
|
||||
@Injectable()
|
||||
export class BlogDraftStore {
|
||||
constructor(private readonly access: AccessStore) {}
|
||||
create(actor: Principal, input: BlogCreateInput) {
|
||||
const requestHash = commandHash(
|
||||
input.slug,
|
||||
input.title,
|
||||
input.summary,
|
||||
input.body,
|
||||
);
|
||||
return this.access.mutate(actor, 'blog.manage', async (tx) => {
|
||||
const previous = await tx.blogArticle.findUnique({
|
||||
where: {
|
||||
organizationId_idempotencyKey: {
|
||||
organizationId: actor.organizationId,
|
||||
idempotencyKey: input.idempotencyKey,
|
||||
},
|
||||
},
|
||||
});
|
||||
if (previous) {
|
||||
assertReplay(previous.requestHash, requestHash);
|
||||
return previous;
|
||||
}
|
||||
const article = await tx.blogArticle.create({
|
||||
data: {
|
||||
...input,
|
||||
organizationId: actor.organizationId,
|
||||
createdById: actor.userId,
|
||||
requestHash,
|
||||
},
|
||||
});
|
||||
await recordAudit(
|
||||
tx,
|
||||
actor.organizationId,
|
||||
actor.userId,
|
||||
'blog.created',
|
||||
article.id,
|
||||
);
|
||||
return article;
|
||||
});
|
||||
}
|
||||
edit(actor: Principal, id: string, input: BlogPatchInput) {
|
||||
return this.access.mutate(actor, 'blog.manage', async (tx) => {
|
||||
const article = await requireArticle(tx, actor.organizationId, id);
|
||||
if (article.state === 'WITHDRAWN')
|
||||
throw new AppError('BLOG_STATE_CONFLICT');
|
||||
if (article.version !== input.version) throw new AppError('BLOG_CHANGED');
|
||||
const { version, ...fields } = input;
|
||||
const updated = await tx.blogArticle.update({
|
||||
where: { id },
|
||||
data: { ...fields, version: nextBlogVersion(version) },
|
||||
});
|
||||
await recordAudit(
|
||||
tx,
|
||||
actor.organizationId,
|
||||
actor.userId,
|
||||
'blog.updated',
|
||||
id,
|
||||
);
|
||||
return updated;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -1,17 +0,0 @@
|
|||
import type { Prisma } from '../generated/prisma/client';
|
||||
import { AppError } from '../common/errors/app-error';
|
||||
export async function requireArticle(
|
||||
tx: Prisma.TransactionClient,
|
||||
organizationId: string,
|
||||
id: string,
|
||||
) {
|
||||
const article = await tx.blogArticle.findFirst({
|
||||
where: { id, organizationId },
|
||||
});
|
||||
if (!article) throw new AppError('BLOG_NOT_FOUND');
|
||||
return article;
|
||||
}
|
||||
export function nextBlogVersion(version: number) {
|
||||
if (version >= 2147483647) throw new AppError('BLOG_CHANGED');
|
||||
return version + 1;
|
||||
}
|
||||
|
|
@ -1,72 +0,0 @@
|
|||
import { Injectable } from '@nestjs/common';
|
||||
import { AccessStore } from '../identity/access.store';
|
||||
import type { Principal } from '../identity/identity.types';
|
||||
import { recordAudit } from '../identity/audit';
|
||||
import { AppError } from '../common/errors/app-error';
|
||||
import { requireArticle, nextBlogVersion } from './blog-lookup';
|
||||
|
||||
@Injectable()
|
||||
export class BlogPublicationStore {
|
||||
constructor(private readonly access: AccessStore) {}
|
||||
publish(actor: Principal, id: string, version: number) {
|
||||
return this.access.mutate(actor, 'blog.publish', async (tx) => {
|
||||
const article = await requireArticle(tx, actor.organizationId, id);
|
||||
if (article.state === 'WITHDRAWN')
|
||||
throw new AppError('BLOG_STATE_CONFLICT');
|
||||
if (article.publicationVersion === version) return article;
|
||||
if (article.version !== version) throw new AppError('BLOG_CHANGED');
|
||||
// ponytail: retain the latest public snapshot; add revision history when editorial rollback is needed.
|
||||
const updated = await tx.blogArticle.update({
|
||||
where: { id },
|
||||
data: {
|
||||
state: 'PUBLISHED',
|
||||
publishedContent: {
|
||||
title: article.title,
|
||||
summary: article.summary,
|
||||
body: article.body,
|
||||
},
|
||||
publicationVersion: version,
|
||||
publishedAt: new Date(),
|
||||
publishedById: actor.userId,
|
||||
version: nextBlogVersion(version),
|
||||
},
|
||||
});
|
||||
await recordAudit(
|
||||
tx,
|
||||
actor.organizationId,
|
||||
actor.userId,
|
||||
'blog.published',
|
||||
id,
|
||||
);
|
||||
return updated;
|
||||
});
|
||||
}
|
||||
withdraw(actor: Principal, id: string, reason: string) {
|
||||
return this.access.mutate(actor, 'blog.publish', async (tx) => {
|
||||
const article = await requireArticle(tx, actor.organizationId, id);
|
||||
if (article.state === 'WITHDRAWN') {
|
||||
if (article.withdrawalReason !== reason)
|
||||
throw new AppError('BLOG_STATE_CONFLICT');
|
||||
return article;
|
||||
}
|
||||
const updated = await tx.blogArticle.update({
|
||||
where: { id },
|
||||
data: {
|
||||
state: 'WITHDRAWN',
|
||||
withdrawalReason: reason,
|
||||
withdrawnAt: new Date(),
|
||||
withdrawnById: actor.userId,
|
||||
version: nextBlogVersion(article.version),
|
||||
},
|
||||
});
|
||||
await recordAudit(
|
||||
tx,
|
||||
actor.organizationId,
|
||||
actor.userId,
|
||||
'blog.withdrawn',
|
||||
id,
|
||||
);
|
||||
return updated;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -1,68 +0,0 @@
|
|||
import { Injectable } from '@nestjs/common';
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
import type { Principal } from '../identity/identity.types';
|
||||
import type { PageInput } from '../identity/identity.schemas';
|
||||
import type { Prisma } from '../generated/prisma/client';
|
||||
import { AppError } from '../common/errors/app-error';
|
||||
import { requireArticle } from './blog-lookup';
|
||||
import type { BlogQuery } from './blog.schemas';
|
||||
|
||||
const publicSelect = { slug: true, publishedContent: true, publishedAt: true };
|
||||
function publicView(
|
||||
article: {
|
||||
slug: string;
|
||||
publishedContent: Prisma.JsonValue | null;
|
||||
publishedAt: Date | null;
|
||||
},
|
||||
detail: boolean,
|
||||
) {
|
||||
const content = article.publishedContent as {
|
||||
title: string;
|
||||
summary: string;
|
||||
body: string;
|
||||
};
|
||||
return {
|
||||
slug: article.slug,
|
||||
title: content.title,
|
||||
summary: content.summary,
|
||||
...(detail ? { body: content.body } : {}),
|
||||
publishedAt: article.publishedAt,
|
||||
seo: { title: content.title, description: content.summary },
|
||||
};
|
||||
}
|
||||
@Injectable()
|
||||
export class BlogReadStore {
|
||||
constructor(private readonly db: DatabaseService) {}
|
||||
list(actor: Principal, page: BlogQuery) {
|
||||
return this.db.blogArticle.findMany({
|
||||
where: {
|
||||
organizationId: actor.organizationId,
|
||||
...(page.state ? { state: page.state } : {}),
|
||||
},
|
||||
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
|
||||
skip: page.offset,
|
||||
take: page.limit,
|
||||
});
|
||||
}
|
||||
get(actor: Principal, id: string) {
|
||||
return requireArticle(this.db, actor.organizationId, id);
|
||||
}
|
||||
async publicList(organizationId: string, page: PageInput) {
|
||||
const articles = await this.db.blogArticle.findMany({
|
||||
where: { organizationId, state: 'PUBLISHED' },
|
||||
select: publicSelect,
|
||||
orderBy: [{ publishedAt: 'desc' }, { id: 'asc' }],
|
||||
skip: page.offset,
|
||||
take: page.limit,
|
||||
});
|
||||
return articles.map((article) => publicView(article, false));
|
||||
}
|
||||
async publicGet(organizationId: string, slug: string) {
|
||||
const article = await this.db.blogArticle.findFirst({
|
||||
where: { organizationId, slug, state: 'PUBLISHED' },
|
||||
select: publicSelect,
|
||||
});
|
||||
if (!article) throw new AppError('BLOG_NOT_FOUND');
|
||||
return publicView(article, true);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,88 +0,0 @@
|
|||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
Param,
|
||||
ParseUUIDPipe,
|
||||
Patch,
|
||||
Post,
|
||||
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 { BlogDraftStore } from './blog-draft.store';
|
||||
import { BlogReadStore } from './blog-read.store';
|
||||
import { BlogPublicationStore } from './blog-publication.store';
|
||||
import {
|
||||
blogCreateSchema,
|
||||
blogPatchSchema,
|
||||
blogPublicationSchema,
|
||||
blogWithdrawalSchema,
|
||||
blogQuerySchema,
|
||||
type BlogCreateInput,
|
||||
type BlogPatchInput,
|
||||
type BlogQuery,
|
||||
} from './blog.schemas';
|
||||
@Controller('blog-articles')
|
||||
export class BlogController {
|
||||
constructor(
|
||||
private readonly drafts: BlogDraftStore,
|
||||
private readonly articles: BlogReadStore,
|
||||
private readonly publication: BlogPublicationStore,
|
||||
) {}
|
||||
@Get()
|
||||
@RequirePermission('blog.read')
|
||||
list(
|
||||
@CurrentPrincipal() actor: Principal,
|
||||
@Query(new SchemaPipe(blogQuerySchema)) query: BlogQuery,
|
||||
) {
|
||||
return this.articles.list(actor, query);
|
||||
}
|
||||
@Get(':id')
|
||||
@RequirePermission('blog.read')
|
||||
get(
|
||||
@CurrentPrincipal() actor: Principal,
|
||||
@Param('id', ParseUUIDPipe) id: string,
|
||||
) {
|
||||
return this.articles.get(actor, id);
|
||||
}
|
||||
@Post()
|
||||
@RequirePermission('blog.manage')
|
||||
create(
|
||||
@CurrentPrincipal() actor: Principal,
|
||||
@Body(new SchemaPipe(blogCreateSchema)) input: BlogCreateInput,
|
||||
) {
|
||||
return this.drafts.create(actor, input);
|
||||
}
|
||||
@Patch(':id')
|
||||
@RequirePermission('blog.manage')
|
||||
edit(
|
||||
@CurrentPrincipal() actor: Principal,
|
||||
@Param('id', ParseUUIDPipe) id: string,
|
||||
@Body(new SchemaPipe(blogPatchSchema)) input: BlogPatchInput,
|
||||
) {
|
||||
return this.drafts.edit(actor, id, input);
|
||||
}
|
||||
@Post(':id/publication')
|
||||
@RequirePermission('blog.publish')
|
||||
publish(
|
||||
@CurrentPrincipal() actor: Principal,
|
||||
@Param('id', ParseUUIDPipe) id: string,
|
||||
@Body(new SchemaPipe(blogPublicationSchema)) input: { version: number },
|
||||
) {
|
||||
return this.publication.publish(actor, id, input.version);
|
||||
}
|
||||
@Post(':id/withdrawal')
|
||||
@RequirePermission('blog.publish')
|
||||
withdraw(
|
||||
@CurrentPrincipal() actor: Principal,
|
||||
@Param('id', ParseUUIDPipe) id: string,
|
||||
@Body(new SchemaPipe(blogWithdrawalSchema)) input: { reason: string },
|
||||
) {
|
||||
return this.publication.withdraw(actor, id, input.reason);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,20 +0,0 @@
|
|||
import { Module } from '@nestjs/common';
|
||||
import { DatabaseModule } from '../database/database.module';
|
||||
import { IdentityModule } from '../identity/identity.module';
|
||||
import { BlogController } from './blog.controller';
|
||||
import { PublicBlogController } from './public-blog.controller';
|
||||
import { BlogDraftStore } from './blog-draft.store';
|
||||
import { BlogReadStore } from './blog-read.store';
|
||||
import { BlogPublicationStore } from './blog-publication.store';
|
||||
import { StorefrontGuard } from '../catalog/storefront.guard';
|
||||
@Module({
|
||||
imports: [DatabaseModule, IdentityModule],
|
||||
controllers: [BlogController, PublicBlogController],
|
||||
providers: [
|
||||
BlogDraftStore,
|
||||
BlogReadStore,
|
||||
BlogPublicationStore,
|
||||
StorefrontGuard,
|
||||
],
|
||||
})
|
||||
export class BlogModule {}
|
||||
|
|
@ -1,31 +0,0 @@
|
|||
import { z } from 'zod';
|
||||
import { text, multilineText } from '../common/input';
|
||||
import { groupSchema } from '../catalog/catalog.schemas';
|
||||
import { pageSchema } from '../identity/identity.schemas';
|
||||
export const blogSlugSchema = groupSchema.shape.slug;
|
||||
const fields = {
|
||||
title: text(160),
|
||||
summary: text(500),
|
||||
body: multilineText(20000),
|
||||
};
|
||||
const version = z.number().int().min(0).max(2147483646);
|
||||
export const blogCreateSchema = z
|
||||
.object({ ...fields, slug: blogSlugSchema, idempotencyKey: z.uuid() })
|
||||
.strict();
|
||||
export const blogPatchSchema = z
|
||||
.object(fields)
|
||||
.partial()
|
||||
.extend({ version })
|
||||
.strict()
|
||||
.refine(
|
||||
(input) => Object.keys(input).some((key) => key !== 'version'),
|
||||
'Provide a field to edit',
|
||||
);
|
||||
export const blogPublicationSchema = z.object({ version }).strict();
|
||||
export const blogWithdrawalSchema = z.object({ reason: text(500, 3) }).strict();
|
||||
export const blogQuerySchema = pageSchema
|
||||
.extend({ state: z.enum(['DRAFT', 'PUBLISHED', 'WITHDRAWN']).optional() })
|
||||
.strict();
|
||||
export type BlogCreateInput = z.infer<typeof blogCreateSchema>;
|
||||
export type BlogPatchInput = z.infer<typeof blogPatchSchema>;
|
||||
export type BlogQuery = z.infer<typeof blogQuerySchema>;
|
||||
|
|
@ -1,34 +0,0 @@
|
|||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Param,
|
||||
ParseUUIDPipe,
|
||||
Query,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { Public } from '../identity/access.decorator';
|
||||
import { StorefrontGuard } from '../catalog/storefront.guard';
|
||||
import { SchemaPipe } from '../common/validation.pipe';
|
||||
import { pageSchema, type PageInput } from '../identity/identity.schemas';
|
||||
import { blogSlugSchema } from './blog.schemas';
|
||||
import { BlogReadStore } from './blog-read.store';
|
||||
@Public()
|
||||
@UseGuards(StorefrontGuard)
|
||||
@Controller('storefront/:organizationId/blog')
|
||||
export class PublicBlogController {
|
||||
constructor(private readonly articles: BlogReadStore) {}
|
||||
@Get()
|
||||
list(
|
||||
@Param('organizationId', ParseUUIDPipe) organizationId: string,
|
||||
@Query(new SchemaPipe(pageSchema)) page: PageInput,
|
||||
) {
|
||||
return this.articles.publicList(organizationId, page);
|
||||
}
|
||||
@Get(':slug')
|
||||
get(
|
||||
@Param('organizationId', ParseUUIDPipe) organizationId: string,
|
||||
@Param('slug', new SchemaPipe(blogSlugSchema)) slug: string,
|
||||
) {
|
||||
return this.articles.publicGet(organizationId, slug);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,129 +0,0 @@
|
|||
import { Injectable } from '@nestjs/common';
|
||||
import { AccessStore } from '../identity/access.store';
|
||||
import { AppError } from '../common/errors/app-error';
|
||||
import { commandHash } from '../common/idempotency';
|
||||
import { recordAudit } from '../identity/audit';
|
||||
import type { Principal } from '../identity/identity.types';
|
||||
import {
|
||||
campaignInclude,
|
||||
nextCampaignVersion,
|
||||
requireCampaign,
|
||||
requireCampaignCollection,
|
||||
} from './campaign-lookup';
|
||||
import { campaignStatus } from './campaign-policy';
|
||||
import { assertCampaignCouponWindow } from '../coupons/campaign-coupon-policy';
|
||||
import type {
|
||||
CampaignCreateInput,
|
||||
CampaignPatchInput,
|
||||
} from './campaign.schemas';
|
||||
|
||||
@Injectable()
|
||||
export class CampaignDraftStore {
|
||||
constructor(private readonly access: AccessStore) {}
|
||||
|
||||
create(actor: Principal, input: CampaignCreateInput) {
|
||||
const hash = commandHash(
|
||||
input.slug,
|
||||
input.title,
|
||||
input.summary,
|
||||
input.collectionId,
|
||||
input.startsAt.toISOString(),
|
||||
input.endsAt.toISOString(),
|
||||
);
|
||||
return this.access.mutate(actor, 'campaigns.manage', async (tx) => {
|
||||
const replay = await tx.seasonalCampaign.findUnique({
|
||||
where: {
|
||||
organizationId_idempotencyKey: {
|
||||
organizationId: actor.organizationId,
|
||||
idempotencyKey: input.idempotencyKey,
|
||||
},
|
||||
},
|
||||
include: campaignInclude,
|
||||
});
|
||||
if (replay) {
|
||||
if (replay.requestHash !== hash)
|
||||
throw new AppError('CAMPAIGN_REPLAY_CONFLICT');
|
||||
return { ...replay, status: campaignStatus(replay) };
|
||||
}
|
||||
await requireCampaignCollection(
|
||||
tx,
|
||||
actor.organizationId,
|
||||
input.collectionId,
|
||||
);
|
||||
if (
|
||||
await tx.seasonalCampaign.findUnique({
|
||||
where: {
|
||||
organizationId_slug: {
|
||||
organizationId: actor.organizationId,
|
||||
slug: input.slug,
|
||||
},
|
||||
},
|
||||
})
|
||||
)
|
||||
throw new AppError('CAMPAIGN_SLUG_EXISTS');
|
||||
const campaign = await tx.seasonalCampaign.create({
|
||||
data: {
|
||||
...input,
|
||||
organizationId: actor.organizationId,
|
||||
createdById: actor.userId,
|
||||
requestHash: hash,
|
||||
},
|
||||
include: campaignInclude,
|
||||
});
|
||||
await recordAudit(
|
||||
tx,
|
||||
actor.organizationId,
|
||||
actor.userId,
|
||||
'campaign.created',
|
||||
campaign.id,
|
||||
);
|
||||
return { ...campaign, status: campaignStatus(campaign) };
|
||||
});
|
||||
}
|
||||
|
||||
edit(actor: Principal, id: string, input: CampaignPatchInput) {
|
||||
return this.access.mutate(actor, 'campaigns.manage', async (tx) => {
|
||||
const campaign = await requireCampaign(tx, actor.organizationId, id);
|
||||
if (campaign.state !== 'DRAFT')
|
||||
throw new AppError('CAMPAIGN_STATE_CONFLICT');
|
||||
if (campaign.version !== input.version)
|
||||
throw new AppError('CAMPAIGN_CHANGED');
|
||||
const values = {
|
||||
title: input.title ?? campaign.title,
|
||||
summary: input.summary ?? campaign.summary,
|
||||
collectionId: input.collectionId ?? campaign.collectionId,
|
||||
startsAt: input.startsAt ?? campaign.startsAt,
|
||||
endsAt: input.endsAt ?? campaign.endsAt,
|
||||
};
|
||||
if (values.endsAt <= values.startsAt)
|
||||
throw new AppError('CAMPAIGN_INVALID_WINDOW');
|
||||
if (campaign.coupon) assertCampaignCouponWindow(values, campaign.coupon);
|
||||
await requireCampaignCollection(
|
||||
tx,
|
||||
actor.organizationId,
|
||||
values.collectionId,
|
||||
);
|
||||
if (
|
||||
values.title === campaign.title &&
|
||||
values.summary === campaign.summary &&
|
||||
values.collectionId === campaign.collectionId &&
|
||||
values.startsAt.getTime() === campaign.startsAt.getTime() &&
|
||||
values.endsAt.getTime() === campaign.endsAt.getTime()
|
||||
)
|
||||
return { ...campaign, status: campaignStatus(campaign) };
|
||||
const updated = await tx.seasonalCampaign.update({
|
||||
where: { id },
|
||||
data: { ...values, version: nextCampaignVersion(campaign.version) },
|
||||
include: campaignInclude,
|
||||
});
|
||||
await recordAudit(
|
||||
tx,
|
||||
actor.organizationId,
|
||||
actor.userId,
|
||||
'campaign.updated',
|
||||
id,
|
||||
);
|
||||
return { ...updated, status: campaignStatus(updated) };
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -1,92 +0,0 @@
|
|||
import { Injectable } from '@nestjs/common';
|
||||
import { AccessStore } from '../identity/access.store';
|
||||
import { AppError } from '../common/errors/app-error';
|
||||
import { recordAudit } from '../identity/audit';
|
||||
import type { Principal } from '../identity/identity.types';
|
||||
import {
|
||||
campaignInclude,
|
||||
eligibleCampaignCollection,
|
||||
nextCampaignVersion,
|
||||
requireCampaign,
|
||||
} from './campaign-lookup';
|
||||
import { campaignStatus } from './campaign-policy';
|
||||
|
||||
@Injectable()
|
||||
export class CampaignLifecycleStore {
|
||||
constructor(private readonly access: AccessStore) {}
|
||||
|
||||
publish(actor: Principal, id: string, version: number) {
|
||||
return this.access.mutate(actor, 'campaigns.manage', async (tx) => {
|
||||
const campaign = await requireCampaign(tx, actor.organizationId, id);
|
||||
if (campaign.state === 'PUBLISHED') {
|
||||
if (campaign.version !== version + 1)
|
||||
throw new AppError('CAMPAIGN_CHANGED');
|
||||
return { ...campaign, status: campaignStatus(campaign) };
|
||||
}
|
||||
if (campaign.state !== 'DRAFT')
|
||||
throw new AppError('CAMPAIGN_STATE_CONFLICT');
|
||||
if (campaign.version !== version) throw new AppError('CAMPAIGN_CHANGED');
|
||||
if (
|
||||
!(await tx.catalogGroup.findFirst({
|
||||
where: {
|
||||
...eligibleCampaignCollection,
|
||||
id: campaign.collectionId,
|
||||
organizationId: actor.organizationId,
|
||||
},
|
||||
select: { id: true },
|
||||
}))
|
||||
)
|
||||
throw new AppError('CAMPAIGN_COLLECTION_EMPTY');
|
||||
const now = new Date();
|
||||
if (campaign.endsAt <= now) throw new AppError('CAMPAIGN_EXPIRED');
|
||||
const published = await tx.seasonalCampaign.update({
|
||||
where: { id },
|
||||
data: {
|
||||
state: 'PUBLISHED',
|
||||
publishedAt: now,
|
||||
publishedById: actor.userId,
|
||||
version: nextCampaignVersion(campaign.version),
|
||||
},
|
||||
include: campaignInclude,
|
||||
});
|
||||
await recordAudit(
|
||||
tx,
|
||||
actor.organizationId,
|
||||
actor.userId,
|
||||
'campaign.published',
|
||||
id,
|
||||
);
|
||||
return { ...published, status: campaignStatus(published) };
|
||||
});
|
||||
}
|
||||
|
||||
cancel(actor: Principal, id: string, reason: string) {
|
||||
return this.access.mutate(actor, 'campaigns.manage', async (tx) => {
|
||||
const campaign = await requireCampaign(tx, actor.organizationId, id);
|
||||
if (campaign.state === 'CANCELLED') {
|
||||
if (campaign.cancellationReason !== reason)
|
||||
throw new AppError('CAMPAIGN_CANCELLATION_CONFLICT');
|
||||
return { ...campaign, status: campaignStatus(campaign) };
|
||||
}
|
||||
const cancelled = await tx.seasonalCampaign.update({
|
||||
where: { id },
|
||||
data: {
|
||||
state: 'CANCELLED',
|
||||
cancelledAt: new Date(),
|
||||
cancelledById: actor.userId,
|
||||
cancellationReason: reason,
|
||||
version: nextCampaignVersion(campaign.version),
|
||||
},
|
||||
include: campaignInclude,
|
||||
});
|
||||
await recordAudit(
|
||||
tx,
|
||||
actor.organizationId,
|
||||
actor.userId,
|
||||
'campaign.cancelled',
|
||||
id,
|
||||
);
|
||||
return { ...cancelled, status: campaignStatus(cancelled) };
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -1,45 +0,0 @@
|
|||
import { AppError } from '../common/errors/app-error';
|
||||
import type { DatabaseService } from '../database/database.service';
|
||||
import type { Prisma } from '../generated/prisma/client';
|
||||
import { campaignCouponSelect } from '../coupons/campaign-coupon-policy';
|
||||
|
||||
type Db = DatabaseService | Prisma.TransactionClient;
|
||||
export const campaignInclude = {
|
||||
collection: { select: { id: true, name: true, slug: true } },
|
||||
coupon: { select: campaignCouponSelect },
|
||||
} as const;
|
||||
export const eligibleCampaignCollection: Prisma.CatalogGroupWhereInput = {
|
||||
kind: 'COLLECTION',
|
||||
products: {
|
||||
some: {
|
||||
product: { status: 'PUBLISHED', variants: { some: { active: true } } },
|
||||
},
|
||||
},
|
||||
};
|
||||
export async function requireCampaign(
|
||||
db: Db,
|
||||
organizationId: string,
|
||||
id: string,
|
||||
) {
|
||||
const campaign = await db.seasonalCampaign.findFirst({
|
||||
where: { id, organizationId },
|
||||
include: campaignInclude,
|
||||
});
|
||||
if (!campaign) throw new AppError('CAMPAIGN_NOT_FOUND');
|
||||
return campaign;
|
||||
}
|
||||
export async function requireCampaignCollection(
|
||||
db: Db,
|
||||
organizationId: string,
|
||||
id: string,
|
||||
) {
|
||||
const collection = await db.catalogGroup.findFirst({
|
||||
where: { id, organizationId, kind: 'COLLECTION' },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!collection) throw new AppError('CAMPAIGN_COLLECTION_NOT_FOUND');
|
||||
}
|
||||
export function nextCampaignVersion(version: number) {
|
||||
if (version >= 2147483647) throw new AppError('CAMPAIGN_VERSION_LIMIT');
|
||||
return version + 1;
|
||||
}
|
||||
|
|
@ -1,58 +0,0 @@
|
|||
import type { CampaignCouponOffer } from '../coupons/campaign-coupon-policy';
|
||||
|
||||
type CampaignTime = {
|
||||
state: 'DRAFT' | 'PUBLISHED' | 'CANCELLED';
|
||||
startsAt: Date;
|
||||
endsAt: Date;
|
||||
};
|
||||
|
||||
export function campaignStatus(campaign: CampaignTime, now = new Date()) {
|
||||
if (campaign.state !== 'PUBLISHED') return campaign.state;
|
||||
if (now < campaign.startsAt) return 'SCHEDULED';
|
||||
return now >= campaign.endsAt ? 'ENDED' : 'ACTIVE';
|
||||
}
|
||||
|
||||
export function publicCampaignView(
|
||||
campaign: CampaignTime & {
|
||||
id: string;
|
||||
slug: string;
|
||||
title: string;
|
||||
summary: string;
|
||||
collection: { id: string; name: string; slug: string };
|
||||
coupon?: CampaignCouponOffer | null;
|
||||
},
|
||||
now = new Date(),
|
||||
) {
|
||||
const coupon = campaign.coupon;
|
||||
const offer =
|
||||
coupon &&
|
||||
coupon.active &&
|
||||
campaignStatus(campaign, now) === 'ACTIVE' &&
|
||||
coupon.startsAt <= now &&
|
||||
coupon.endsAt > now
|
||||
? {
|
||||
code: coupon.code,
|
||||
currency: coupon.currency,
|
||||
kind: coupon.kind,
|
||||
amount: coupon.amount?.toFixed(2) ?? null,
|
||||
percentBps: coupon.percentBps,
|
||||
minimumSubtotal: coupon.minimumSubtotal.toFixed(2),
|
||||
startsAt: coupon.startsAt,
|
||||
endsAt: coupon.endsAt,
|
||||
}
|
||||
: null;
|
||||
return {
|
||||
id: campaign.id,
|
||||
slug: campaign.slug,
|
||||
title: campaign.title,
|
||||
summary: campaign.summary,
|
||||
startsAt: campaign.startsAt,
|
||||
endsAt: campaign.endsAt,
|
||||
collection: {
|
||||
id: campaign.collection.id,
|
||||
name: campaign.collection.name,
|
||||
slug: campaign.collection.slug,
|
||||
},
|
||||
...(offer ? { offer } : {}),
|
||||
};
|
||||
}
|
||||
|
|
@ -1,70 +0,0 @@
|
|||
import { Injectable } from '@nestjs/common';
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
import type { Principal } from '../identity/identity.types';
|
||||
import { campaignStatus, publicCampaignView } from './campaign-policy';
|
||||
import {
|
||||
campaignInclude,
|
||||
eligibleCampaignCollection,
|
||||
requireCampaign,
|
||||
} from './campaign-lookup';
|
||||
import { AppError } from '../common/errors/app-error';
|
||||
import type { PageInput } from '../identity/identity.schemas';
|
||||
import type { Prisma } from '../generated/prisma/client';
|
||||
import type { CampaignQuery } from './campaign.schemas';
|
||||
|
||||
@Injectable()
|
||||
export class CampaignReadStore {
|
||||
constructor(private readonly db: DatabaseService) {}
|
||||
private publicWhere(
|
||||
organizationId: string,
|
||||
now: Date,
|
||||
): Prisma.SeasonalCampaignWhereInput {
|
||||
return {
|
||||
organizationId,
|
||||
state: 'PUBLISHED',
|
||||
startsAt: { lte: now },
|
||||
endsAt: { gt: now },
|
||||
collection: eligibleCampaignCollection,
|
||||
};
|
||||
}
|
||||
async publicList(organizationId: string, page: PageInput, now = new Date()) {
|
||||
const campaigns = await this.db.seasonalCampaign.findMany({
|
||||
where: this.publicWhere(organizationId, now),
|
||||
include: campaignInclude,
|
||||
orderBy: [{ startsAt: 'desc' }, { id: 'asc' }],
|
||||
take: page.limit,
|
||||
skip: page.offset,
|
||||
});
|
||||
return campaigns.map((campaign) => publicCampaignView(campaign, now));
|
||||
}
|
||||
async publicGet(organizationId: string, slug: string) {
|
||||
const now = new Date();
|
||||
const campaign = await this.db.seasonalCampaign.findFirst({
|
||||
where: { ...this.publicWhere(organizationId, now), slug },
|
||||
include: campaignInclude,
|
||||
});
|
||||
if (!campaign) throw new AppError('CAMPAIGN_NOT_FOUND');
|
||||
return publicCampaignView(campaign, now);
|
||||
}
|
||||
async list(actor: Principal, query: CampaignQuery) {
|
||||
const campaigns = await this.db.seasonalCampaign.findMany({
|
||||
where: {
|
||||
organizationId: actor.organizationId,
|
||||
...(query.state ? { state: query.state } : {}),
|
||||
},
|
||||
include: campaignInclude,
|
||||
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
|
||||
take: query.limit,
|
||||
skip: query.offset,
|
||||
});
|
||||
const now = new Date();
|
||||
return campaigns.map((campaign) => ({
|
||||
...campaign,
|
||||
status: campaignStatus(campaign, now),
|
||||
}));
|
||||
}
|
||||
async get(actor: Principal, id: string) {
|
||||
const campaign = await requireCampaign(this.db, actor.organizationId, id);
|
||||
return { ...campaign, status: campaignStatus(campaign) };
|
||||
}
|
||||
}
|
||||
|
|
@ -1,50 +0,0 @@
|
|||
import { z } from 'zod';
|
||||
import { text } from '../common/input';
|
||||
import { groupSchema } from '../catalog/catalog.schemas';
|
||||
import { pageSchema } from '../identity/identity.schemas';
|
||||
|
||||
const timestamp = z.iso
|
||||
.datetime({ offset: true })
|
||||
.transform((value) => new Date(value));
|
||||
const fields = {
|
||||
title: text(160),
|
||||
summary: text(500, 0),
|
||||
collectionId: z.uuid(),
|
||||
startsAt: timestamp,
|
||||
endsAt: timestamp,
|
||||
};
|
||||
const version = z.number().int().min(0).max(2147483647);
|
||||
export const campaignCreateSchema = z
|
||||
.object({
|
||||
...fields,
|
||||
summary: fields.summary.default(''),
|
||||
slug: groupSchema.shape.slug,
|
||||
idempotencyKey: z.uuid(),
|
||||
})
|
||||
.strict()
|
||||
.refine((value) => value.endsAt > value.startsAt, {
|
||||
message: 'End must follow start',
|
||||
path: ['endsAt'],
|
||||
});
|
||||
export const campaignPatchSchema = z
|
||||
.object(fields)
|
||||
.partial()
|
||||
.extend({
|
||||
version,
|
||||
})
|
||||
.strict()
|
||||
.refine(
|
||||
(value) => Object.keys(value).some((key) => key !== 'version'),
|
||||
'Provide at least one field',
|
||||
);
|
||||
export const campaignPublicationSchema = z.object({ version }).strict();
|
||||
export const campaignCancellationSchema = z
|
||||
.object({ reason: text(500, 3) })
|
||||
.strict();
|
||||
export const campaignQuerySchema = pageSchema
|
||||
.extend({ state: z.enum(['DRAFT', 'PUBLISHED', 'CANCELLED']).optional() })
|
||||
.strict();
|
||||
export const campaignSlugSchema = groupSchema.shape.slug;
|
||||
export type CampaignCreateInput = z.infer<typeof campaignCreateSchema>;
|
||||
export type CampaignPatchInput = z.infer<typeof campaignPatchSchema>;
|
||||
export type CampaignQuery = z.infer<typeof campaignQuerySchema>;
|
||||
|
|
@ -1,92 +0,0 @@
|
|||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
Param,
|
||||
ParseUUIDPipe,
|
||||
Patch,
|
||||
Post,
|
||||
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 { CampaignDraftStore } from './campaign-draft.store';
|
||||
import { CampaignReadStore } from './campaign-read.store';
|
||||
import { CampaignLifecycleStore } from './campaign-lifecycle.store';
|
||||
import {
|
||||
campaignPublicationSchema,
|
||||
campaignCancellationSchema,
|
||||
} from './campaign.schemas';
|
||||
import {
|
||||
campaignCreateSchema,
|
||||
campaignPatchSchema,
|
||||
campaignQuerySchema,
|
||||
type CampaignCreateInput,
|
||||
type CampaignPatchInput,
|
||||
type CampaignQuery,
|
||||
} from './campaign.schemas';
|
||||
|
||||
@Controller('campaigns')
|
||||
export class CampaignsController {
|
||||
constructor(
|
||||
private readonly drafts: CampaignDraftStore,
|
||||
private readonly campaigns: CampaignReadStore,
|
||||
private readonly lifecycle: CampaignLifecycleStore,
|
||||
) {}
|
||||
@Get()
|
||||
@RequirePermission('campaigns.read')
|
||||
list(
|
||||
@CurrentPrincipal() actor: Principal,
|
||||
@Query(new SchemaPipe(campaignQuerySchema)) query: CampaignQuery,
|
||||
) {
|
||||
return this.campaigns.list(actor, query);
|
||||
}
|
||||
@Post(':id/publication')
|
||||
@RequirePermission('campaigns.manage')
|
||||
publish(
|
||||
@CurrentPrincipal() actor: Principal,
|
||||
@Param('id', ParseUUIDPipe) id: string,
|
||||
@Body(new SchemaPipe(campaignPublicationSchema))
|
||||
input: { version: number },
|
||||
) {
|
||||
return this.lifecycle.publish(actor, id, input.version);
|
||||
}
|
||||
@Post(':id/cancellation')
|
||||
@RequirePermission('campaigns.manage')
|
||||
cancel(
|
||||
@CurrentPrincipal() actor: Principal,
|
||||
@Param('id', ParseUUIDPipe) id: string,
|
||||
@Body(new SchemaPipe(campaignCancellationSchema)) input: { reason: string },
|
||||
) {
|
||||
return this.lifecycle.cancel(actor, id, input.reason);
|
||||
}
|
||||
@Get(':id')
|
||||
@RequirePermission('campaigns.read')
|
||||
get(
|
||||
@CurrentPrincipal() actor: Principal,
|
||||
@Param('id', ParseUUIDPipe) id: string,
|
||||
) {
|
||||
return this.campaigns.get(actor, id);
|
||||
}
|
||||
@Post()
|
||||
@RequirePermission('campaigns.manage')
|
||||
create(
|
||||
@CurrentPrincipal() actor: Principal,
|
||||
@Body(new SchemaPipe(campaignCreateSchema)) input: CampaignCreateInput,
|
||||
) {
|
||||
return this.drafts.create(actor, input);
|
||||
}
|
||||
@Patch(':id')
|
||||
@RequirePermission('campaigns.manage')
|
||||
edit(
|
||||
@CurrentPrincipal() actor: Principal,
|
||||
@Param('id', ParseUUIDPipe) id: string,
|
||||
@Body(new SchemaPipe(campaignPatchSchema)) input: CampaignPatchInput,
|
||||
) {
|
||||
return this.drafts.edit(actor, id, input);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,21 +0,0 @@
|
|||
import { Module } from '@nestjs/common';
|
||||
import { DatabaseModule } from '../database/database.module';
|
||||
import { IdentityModule } from '../identity/identity.module';
|
||||
import { CampaignsController } from './campaigns.controller';
|
||||
import { CampaignDraftStore } from './campaign-draft.store';
|
||||
import { CampaignReadStore } from './campaign-read.store';
|
||||
import { CampaignLifecycleStore } from './campaign-lifecycle.store';
|
||||
import { PublicCampaignsController } from './public-campaigns.controller';
|
||||
import { StorefrontGuard } from '../catalog/storefront.guard';
|
||||
|
||||
@Module({
|
||||
imports: [DatabaseModule, IdentityModule],
|
||||
controllers: [CampaignsController, PublicCampaignsController],
|
||||
providers: [
|
||||
CampaignDraftStore,
|
||||
CampaignReadStore,
|
||||
CampaignLifecycleStore,
|
||||
StorefrontGuard,
|
||||
],
|
||||
})
|
||||
export class CampaignsModule {}
|
||||
|
|
@ -1,35 +0,0 @@
|
|||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Param,
|
||||
ParseUUIDPipe,
|
||||
Query,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { Public } from '../identity/access.decorator';
|
||||
import { StorefrontGuard } from '../catalog/storefront.guard';
|
||||
import { pageSchema, type PageInput } from '../identity/identity.schemas';
|
||||
import { SchemaPipe } from '../common/validation.pipe';
|
||||
import { CampaignReadStore } from './campaign-read.store';
|
||||
import { campaignSlugSchema } from './campaign.schemas';
|
||||
|
||||
@Public()
|
||||
@UseGuards(StorefrontGuard)
|
||||
@Controller('storefront/:organizationId/campaigns')
|
||||
export class PublicCampaignsController {
|
||||
constructor(private readonly campaigns: CampaignReadStore) {}
|
||||
@Get()
|
||||
list(
|
||||
@Param('organizationId', ParseUUIDPipe) organizationId: string,
|
||||
@Query(new SchemaPipe(pageSchema)) page: PageInput,
|
||||
) {
|
||||
return this.campaigns.publicList(organizationId, page);
|
||||
}
|
||||
@Get(':slug')
|
||||
get(
|
||||
@Param('organizationId', ParseUUIDPipe) organizationId: string,
|
||||
@Param('slug', new SchemaPipe(campaignSlugSchema)) slug: string,
|
||||
) {
|
||||
return this.campaigns.publicGet(organizationId, slug);
|
||||
}
|
||||
}
|
||||
|
|
@ -9,11 +9,6 @@ import { ProductsController } from './products.controller';
|
|||
import { GroupsController } from './groups.controller';
|
||||
import { StorefrontController } from './storefront.controller';
|
||||
import { StorefrontGuard } from './storefront.guard';
|
||||
import { ProductImageStore } from './product-image.store';
|
||||
import {
|
||||
ProductImagesController,
|
||||
StorefrontImagesController,
|
||||
} from './product-images.controller';
|
||||
|
||||
@Module({
|
||||
imports: [DatabaseModule, IdentityModule],
|
||||
|
|
@ -23,14 +18,7 @@ import {
|
|||
GroupStore,
|
||||
StorefrontStore,
|
||||
StorefrontGuard,
|
||||
ProductImageStore,
|
||||
],
|
||||
controllers: [
|
||||
ProductsController,
|
||||
GroupsController,
|
||||
StorefrontController,
|
||||
ProductImagesController,
|
||||
StorefrontImagesController,
|
||||
],
|
||||
controllers: [ProductsController, GroupsController, StorefrontController],
|
||||
})
|
||||
export class CatalogModule {}
|
||||
|
|
|
|||
|
|
@ -1,38 +0,0 @@
|
|||
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),
|
||||
};
|
||||
}
|
||||
|
|
@ -1,87 +0,0 @@
|
|||
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;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,86 +0,0 @@
|
|||
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));
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue