@happyvertical/smrt-sales 0.57.46 → 0.57.47

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/AGENTS.md +1 -1
  2. package/agents/commissions.md +3 -3
  3. package/dist/agreements.js +1 -1
  4. package/dist/chunks/__smrt-register__-D1H7oo6b.js +6 -0
  5. package/dist/chunks/__smrt-register__-D1H7oo6b.js.map +1 -0
  6. package/dist/chunks/{commissions-B1WnBKsn.js → commissions-DbhfPQbi.js} +78 -36
  7. package/dist/chunks/commissions-DbhfPQbi.js.map +1 -0
  8. package/dist/chunks/{referrals-DE0tKm5G.js → referrals-DQaEehr8.js} +2 -2
  9. package/dist/chunks/{referrals-DE0tKm5G.js.map → referrals-DQaEehr8.js.map} +1 -1
  10. package/dist/commissions/collections/CommissionCollection.d.ts +8 -2
  11. package/dist/commissions/collections/CommissionCollection.d.ts.map +1 -1
  12. package/dist/commissions/collections/CommissionPayoutCollection.d.ts +8 -2
  13. package/dist/commissions/collections/CommissionPayoutCollection.d.ts.map +1 -1
  14. package/dist/commissions/collections/EarningEventCollection.d.ts +12 -5
  15. package/dist/commissions/collections/EarningEventCollection.d.ts.map +1 -1
  16. package/dist/commissions/models/Commission.d.ts.map +1 -1
  17. package/dist/commissions/models/CommissionPayout.d.ts.map +1 -1
  18. package/dist/commissions/models/EarningEvent.d.ts +5 -5
  19. package/dist/commissions/models/EarningEvent.d.ts.map +1 -1
  20. package/dist/commissions/replay-owner.d.ts +35 -0
  21. package/dist/commissions/replay-owner.d.ts.map +1 -0
  22. package/dist/commissions/services/CommissionCalculationService.d.ts.map +1 -1
  23. package/dist/commissions/services/CommissionPayoutService.d.ts.map +1 -1
  24. package/dist/commissions.js +2 -2
  25. package/dist/crm.js +1 -1
  26. package/dist/index.js +3 -3
  27. package/dist/manifest.json +225 -13
  28. package/dist/referrals.js +2 -2
  29. package/dist/smrt-knowledge.json +16 -10
  30. package/package.json +8 -8
  31. package/dist/chunks/__smrt-register__-DpLLYukX.js +0 -6
  32. package/dist/chunks/__smrt-register__-DpLLYukX.js.map +0 -1
  33. package/dist/chunks/commissions-B1WnBKsn.js.map +0 -1
package/AGENTS.md CHANGED
@@ -55,7 +55,7 @@ Business/domain models are generally `@TenantScoped({ mode: 'optional' })` with
55
55
  - **Cents vs. rates**: `*Cents` fields are INTEGER (`= 0` defaults); `rate`/`probability`/`shareFraction` are DECIMAL (`= 0.0` defaults). Don't mix the two conventions on one field.
56
56
  - **Optional same-package foreign keys use null**: execution, supersession, earning-event, and payout references that are absent persist as `null`, never `''`; their physical database constraints remain enabled when a real id is present.
57
57
  - **Versioned terms are rows, not edits**: CommissionPlan / AttributionPolicy / ReferralAgreement amendments insert `version + 1`; active versions are save-guarded immutable.
58
- - **Idempotency is dedupeKey-based**: EarningEvent, Commission, and CommissionPayout carry natural keys (`conflictColumns`) — retried ingestion/settlement upserts instead of duplicating.
58
+ - **Idempotency is dedupeKey-based, per tenant (#3305 D1)**: EarningEvent, Commission, and CommissionPayout are keyed `(tenant_id, dedupe_key|idempotency_key)`. Replay lookups (`findByDedupeKey`/`getOrCreateByDedupeKey`/`findByIdempotencyKey`) and the raw save guards resolve one owner (explicit `tenantId`, else context; neither → global rows); calculation/settlement pass the event's/earner's tenant because they run without a context; a foreign owner under a context fails closed, super-admin bypass included. Rollout: `db:migrate` adds the tenant-led uniques and drops the superseded ones in a writer-drained window; recovery is forward-only once tenants share a key.
59
59
  - **Adjustments never rewrite**: correcting an earned/paid Commission means appending a CommissionAdjustment, not editing the Commission.
60
60
  - **Adjustment retries use the service**: CommissionAdjustment has no public operation field and rejects an untyped `operationId` constructor option; ordinary legacy creates without one remain compatible. `CommissionAdjustmentService` transactionally claims the private operation fence with insert-on-conflict-no-op, creates the explicit mapped adjustment id only for the winner, then verifies the persisted intent; the same globally unique operation UUID cannot be reused by another tenant.
61
61
  - **Manifest objects must remain root-importable**: generated consumer registration imports every manifest-advertised model and collection from `@happyvertical/smrt-sales`. The `CommissionAdjustmentOperation` and `ReferralClickOperation` model/collection values are therefore root and owning-subpath exports for runtime loading, while their `api: false`, `mcp: false`, and `cli: false` decorators keep them off generated application surfaces. Publish-pack validation imports the actual CLI-generated register against the packed tarball.
@@ -9,11 +9,11 @@ money), and the Gotchas that apply before editing anything live in
9
9
  - **EarnerSourceAttribution** (#1986): indexed external attribution mapping `(sourceKind, sourceId) → earnerId` with `status` (`active|inactive`) — the queryable replacement for stashing associations in `Earner.metadata`. Natural key `(tenant_id, source_kind, source_id)` (one mapping per key per tenant; a re-`create` upserts/re-points; the adapters' null-aware upsert dedups NULL-tenant keys too, but duplicate global rows minted outside the model layer remain representable). The attribution kind space is consumer-defined and need not match earning-event source kinds. `EarnerAttributionService` is the public API: `registerAttribution` (idempotent; reports `created`/`previousEarnerId`; also the documented metadata-migration backfill primitive — loop earners, register each association, verify, drop the metadata key) and `resolveActiveEarnerBySource`/`resolveActiveEarnersBySources` (single/batched; 2 queries bounded by the REQUESTED ids, never a scan of active earners; fail-closed typed reasons `no_mapping|mapping_inactive|ambiguous_mapping|earner_not_found|earner_not_active` — more than one ACTIVE row for a key refuses rather than guessing). In tenant context mappings resolve within that tenant only; without context, lookups span all rows and cross-tenant duplicates surface as `ambiguous_mapping`.
10
10
  - **CommissionPlan**: versioned calculation terms. Natural key `(tenant_id, plan_key, version)` (per-tenant keys; the adapters' null-aware upsert dedups NULL-tenant keys through the model layer, though duplicate global rows minted via raw SQL remain representable); `status` (`draft|active|superseded|retired`); `effectiveFrom`. Components are a JSON-string array (`getComponents()`): each component has `key`, `trigger` (earning-event kind or `*`), `basis` (`fixed|gross|net|margin|custom`), `rate` or `fixedAmountCents`, `recurrence` (`one_time` or `recurring` with optional `maxOccurrences`/`windowMonths`). **Immutable once active** — amendments create a new row with `version + 1`; prior versions are never rewritten. `latestActiveByKey(key, at?)` resolves the highest active version **already in effect at `at`** — a future-dated amendment can be activated ahead of time without governing earlier qualifications (same rule on `AttributionPolicyCollection`).
11
11
  - **Waterfall pool steps** (#3834): a v2 step with `pool: { metric?, residual?, zeroWeight? }` splits its amount across the members of the pool its `recipient` descriptor resolves to (through the normal recipient registry). Membership comes from an injected `WaterfallPoolMembershipResolver`, weights from an injected `MetricProvider` (omitted `metric` ⇒ equal weights, no provider call). `calculateWaterfall` stays synchronous and never calls providers: `prepareWaterfallPools()` (async) resolves pools at the authoritative event and the result is passed as `pools`; `calculateWaterfallWithPools()` does both. Weights must be non-negative safe integers (hosts scale fractional metrics); members are canonicalized to `(kind, id)` order and duplicates, non-member metric rows, and repeated rows are refused; members the provider omits weigh zero. Allocation is exact BigInt `floor(amount × weight ÷ total)`; the residual goes to the remainder sink (default) or, with `residual: 'largest_remainder'`, one unit at a time by largest fractional remainder, then larger weight, then `kind`, then `id` (UTF-16 code-unit order). An empty pool, or an all-zero pool under the default `zeroWeight: 'remainder_sink'`, sends the whole step to the sink; `zeroWeight: 'equal'` splits equally instead. The trace freezes `frozenInputs.poolsByStep` (pool identity, metric, ISO period, members, weights) so replay never re-reads metrics; frozen and prepared snapshots must match their frozen recipient and the step's declared `metric` (`null` for equal weights), and a prepared snapshot (or `null` unresolved marker) must equal what the step's descriptor resolves to at calculation, so pools prepared for another plan are refused. Replay trusts the evidence it is given — like frozen `recipientByStep`, an internally consistent edit to stored evidence is undetectable without keyed integrity, so hosts store it immutably. Pool-free plans emit no `poolsByStep` key or step `pool` field, so their traces are unchanged. A pool step cannot be the application-fee offset recipient. Each member trace carries `shareFraction` for hosts that persist member allocations as Commissions under one `splitGroupId` (for example `${earningEventId}:${stepKey}`).
12
- - **EarningEvent**: immutable commercial-event evidence (`conversion`, `agreement_execution`, `invoice_payment`, `collected_revenue`, `recognized_margin`, or any extensible kind). Carries `sourceKind`/`sourceId` (generic earning source), `grossAmountCents`/`netAmountCents`/`marginCents`, `currency`, `occurredAt`, and a `dedupeKey` natural key for idempotent ingestion. No update/delete surface, plus a save-time immutability guard: hydrated edits, blind id overwrites, and fresh creates onto an existing dedupe key all throw (the upsert would rotate the row id and orphan referencing Commissions) — idempotent ingestion goes through `getOrCreateByDedupeKey()`.
13
- - **Commission**: one earning record per earner per plan component per event occurrence. Integer-cents amounts (`baseAmountCents`, `amountCents`), decimal `rate`, `basis`, snapshot references (`planKey`/`planVersion`, generic `termsSnapshotKind`/`termsSnapshotId`), a JSON `calculationTrace` sufficient to reproduce the amount, split support (`splitGroupId`, `shareFraction`), and a `dedupeKey` for idempotent creation. Lifecycle `pending → earned → approved → payable → paid`, enforced by a save-time transition guard with an authoritative prior-status re-read (commerce pattern).
12
+ - **EarningEvent**: immutable commercial-event evidence (`conversion`, `agreement_execution`, `invoice_payment`, `collected_revenue`, `recognized_margin`, or any extensible kind). Carries `sourceKind`/`sourceId` (generic earning source), `grossAmountCents`/`netAmountCents`/`marginCents`, `currency`, `occurredAt`, and a `dedupeKey` natural key for idempotent ingestion, unique per tenant (`(tenant_id, dedupe_key)`, #3305 D1; callers no longer need to embed the tenant). No update/delete surface, plus a save-time immutability guard: hydrated edits, blind id overwrites, and fresh creates onto an existing dedupe key all throw (the upsert would rotate the row id and orphan referencing Commissions) — idempotent ingestion goes through `getOrCreateByDedupeKey()`.
13
+ - **Commission**: one earning record per earner per plan component per event occurrence. Integer-cents amounts (`baseAmountCents`, `amountCents`), decimal `rate`, `basis`, snapshot references (`planKey`/`planVersion`, generic `termsSnapshotKind`/`termsSnapshotId`), a JSON `calculationTrace` sufficient to reproduce the amount, split support (`splitGroupId`, `shareFraction`), and a `dedupeKey` for idempotent creation, unique per tenant (#3305 D1); calculation looks it up in the event's tenant. Lifecycle `pending → earned → approved → payable → paid`, enforced by a save-time transition guard with an authoritative prior-status re-read (commerce pattern).
14
14
  - **CommissionAdjustment**: append-only corrections (`refund|credit|chargeback|dispute|correction`), signed `amountCents`, required `reason`, immutable once created. `CommissionAdjustmentService.createAdjustment()` is the tenant-required idempotent creation door: callers provide a stable operation UUID; the database creates exactly one row, exact retries return it, and changed tenant/commission/earner/kind/cents/currency/reason/operator/metadata fail with a typed replay conflict. Parent Commission plus denormalized tenant/Earner/currency and operator UUID are validated before insert. The financial row deliberately exposes no operation field. A private, required-tenant `CommissionAdjustmentOperation` table uses the globally unique operation UUID as its primary id, maps it to the adjustment UUID, and is inserted in the same transaction as the adjustment. Claims tolerate either primary-key or tenant/slug/context uniqueness arbitration without aborting the transaction; only the tenant-scoped operation UUID lookup and immutable intent comparison authorize a replay. Existing adjustment schemas and legacy direct creates remain unchanged. Earned/paid Commissions are never rewritten — adjustments append to them.
15
15
  - **Payable balance**: computed, not stored — `CommissionBalanceService` sums payable Commissions plus unsettled Adjustments per Earner/currency.
16
- - **CommissionPayout**: settlement batch per Earner. `pending → approved → processing → completed | failed` (`resetFromFailed()` is the only exit from failed), plus the terminal operator decline `rejected` reachable from pending/approved (#1987 — reject through `transitionPayoutForSource`, which also RELEASES the batch's membership so the rows settle through a future batch; `reject()` on the model mutates status only). Settles rows via the collections' **conditional `claimForPayout`** (model-layer get/save/re-read — tenancy- and dialect-safe; a row owned by another batch is never re-claimed) and stores totals recomputed from the VERIFIED claimed membership; idempotent via `idempotencyKey` natural key (default `${earnerId}:${currency}:${YYYY-MM-DD}`) — initial creation uses a strict insert so concurrent same-key creators cannot overwrite the first routing snapshot; the loser receives a unique-constraint error and can retry the same key. A clean replay touches nothing, while a pending payout whose totals disagree with its stamped rows (interrupted claim pass) is repaired on replay (the claim pass re-checks the payout is still pending first). Each batch/repair pass also derives the payout's **single-source stamp** (`sourceKind`/`sourceId`, indexed): set when every claimed commission — and every claimed adjustment through its parent commission — shares exactly one non-empty source; empty for mixed/unknown/empty membership. `completePayout` flips member commissions to `paid` BEFORE the terminal transition, so a mid-loop failure stays retryable. Enforces `totalAmountCents = commissionTotalCents + adjustmentTotalCents` at save; retains `paymentReference`/`providerRef`; optional `invoiceId` cross-package string ref to a commerce Invoice. Generated surface is read-only on ALL doors (api/mcp/cli `list`/`get`) — writes go through `CommissionPayoutService`. `createPayoutBatch` settles the whole earner+currency by default, or a **scoped** subset: pass `sourceKind`+`sourceId` to settle just one earning source (e.g. one ad network), or `commissionIds` for an explicit set (each validated payable+unsettled+earner+currency; requires its own `idempotencyKey`) — adjustments are narrowed to the same scope, and the default idempotency key folds the source in. Scoping is how concurrent per-source batches settle safely: batches scoped to different sources (or disjoint `commissionIds`) gather **disjoint** row sets and never contend. The collection layer has no cross-row transaction, so OVERLAPPING concurrent scopes (a source batch + the earner-wide batch, intersecting id sets, or a batch replay racing a lifecycle transition of the same payout) must be serialized by the caller — `claimForPayout` still won't double-own a row, but a shared commission and its adjustment could split across the two batches.
16
+ - **CommissionPayout**: settlement batch per Earner. `pending → approved → processing → completed | failed` (`resetFromFailed()` is the only exit from failed), plus the terminal operator decline `rejected` reachable from pending/approved (#1987 — reject through `transitionPayoutForSource`, which also RELEASES the batch's membership so the rows settle through a future batch; `reject()` on the model mutates status only). Settles rows via the collections' **conditional `claimForPayout`** (model-layer get/save/re-read — tenancy- and dialect-safe; a row owned by another batch is never re-claimed) and stores totals recomputed from the VERIFIED claimed membership; idempotent via the per-tenant `(tenant_id, idempotency_key)` natural key (#3305 D1; settlement looks it up in the earner's tenant; default `${earnerId}:${currency}:${YYYY-MM-DD}`) — initial creation uses a strict insert so concurrent same-key creators cannot overwrite the first routing snapshot; the loser receives a unique-constraint error and can retry the same key. A clean replay touches nothing, while a pending payout whose totals disagree with its stamped rows (interrupted claim pass) is repaired on replay (the claim pass re-checks the payout is still pending first). Each batch/repair pass also derives the payout's **single-source stamp** (`sourceKind`/`sourceId`, indexed): set when every claimed commission — and every claimed adjustment through its parent commission — shares exactly one non-empty source; empty for mixed/unknown/empty membership. `completePayout` flips member commissions to `paid` BEFORE the terminal transition, so a mid-loop failure stays retryable. Enforces `totalAmountCents = commissionTotalCents + adjustmentTotalCents` at save; retains `paymentReference`/`providerRef`; optional `invoiceId` cross-package string ref to a commerce Invoice. Generated surface is read-only on ALL doors (api/mcp/cli `list`/`get`) — writes go through `CommissionPayoutService`. `createPayoutBatch` settles the whole earner+currency by default, or a **scoped** subset: pass `sourceKind`+`sourceId` to settle just one earning source (e.g. one ad network), or `commissionIds` for an explicit set (each validated payable+unsettled+earner+currency; requires its own `idempotencyKey`) — adjustments are narrowed to the same scope, and the default idempotency key folds the source in. Scoping is how concurrent per-source batches settle safely: batches scoped to different sources (or disjoint `commissionIds`) gather **disjoint** row sets and never contend. The collection layer has no cross-row transaction, so OVERLAPPING concurrent scopes (a source batch + the earner-wide batch, intersecting id sets, or a batch replay racing a lifecycle transition of the same payout) must be serialized by the caller — `claimForPayout` still won't double-own a row, but a shared commission and its adjustment could split across the two batches.
17
17
  - **Payout destination snapshot** (#4148): `CommissionPayout.payoutDestination` stores the typed Earner descriptor captured at batch creation. Use `getPayoutDestination()` on the batch for execution/review, never live Earner routing. Method and destination are immutable from first persistence (pending included); idempotency replay/repair and failed-reset preserve them. Reject through the source transition service and create a new key to change routing. Existing Connect/crypto batches with an empty migrated snapshot cannot approve/process/complete; reject/recreate rather than infer historical routing. Manual methods retain `{}`. Generated list/get surfaces expose the snapshot; no provider transfer is implemented.
18
18
  - **Source-scoped payout history** (#1985): `CommissionPayoutService.getSourcePayoutHistory({ sourceKind, sourceId, limit?, offset? })` — one page of the payouts belonging to ONE earning source, newest first (`created_at DESC, id DESC`), offset contract (`nextOffset` advances by the scanned count; `null` when exhausted). Candidates come from the indexed stamp, so work is bounded by page size (a sparse source never scans the global history); each page is re-verified against actual membership in three batched queries (no per-payout N+1) — every member commission and every adjustment's parent must carry exactly the requested source and agree on earner/currency/tenant; unprovable rows (mixed-source, missing parents, memberless artifacts, released/rejected batches) are excluded fail-closed and reported in `excluded` with reasons. Adjustment-only payouts prove ownership through parent commissions and list normally. Payouts minted before the stamp existed are invisible until backfilled with `restampPayoutSource(payoutId)` (idempotent, any status).
19
19
  - **Source-authorized lifecycle transitions** (#1987): `CommissionPayoutService.transitionPayoutForSource({ payoutId, sourceKind, sourceId, action, expectedStatus?, paymentReference?, reason? })` — atomic alternative to load-verify-transition. Actions `approve | mark_processing | complete | fail | reject`. Everything runs on one transaction database: the payout row is locked (PostgreSQL `SELECT … FOR UPDATE`, replica-safe; single-connection engines serialize transitions per database in-process), membership is re-verified under the lock (every commission and every adjustment through its parent must carry exactly the requested source and matching earner/currency/tenant — else typed fail-closed refusals with no payout/member data), and only authorized calls receive status-derived `already_applied` or `status_conflict` outcomes. Totals are then recomputed under the lock (drift refuses the money-forward actions with `totals_drift`; repair = `createPayoutBatch` replay while pending; `fail`/`reject` proceed despite drift — reject IS the remedy), and the transition plus member writes commit or roll back together (`complete` flips members to paid in the same transaction; `reject` releases membership then declines). Outcomes: `transitioned`, `already_applied` (idempotent echo — terminal completion NEVER rewrites `paymentReference`/`providerRef`/`paidAt`), or `refused` with `{ reason, detail }`. Concurrent duplicate calls for actions that retain membership resolve as one `transitioned` + `already_applied` echoes; `reject` releases its membership evidence, so serialized replays fail `membership_empty` rather than expose rejected state. `expectedStatus` adds optimistic-concurrency strictness after authorization. Memberless batch artifacts cannot pass the source-authorized door (`membership_empty`) — they stay operator-level.
@@ -1,3 +1,3 @@
1
- import "./chunks/__smrt-register__-DpLLYukX.js";
1
+ import "./chunks/__smrt-register__-D1H7oo6b.js";
2
2
  import { a as AgreementExecutionEvent, c as AgreementCollection, d as serializeAgreementParty, f as AGREEMENT_EXECUTION_STATUSES, g as sanitizeSignerIntent, h as sanitizeSignerEvidence, i as AgreementExecutionEventCollection, l as Agreement, m as coerceAgreementDate, n as ExecutedAgreementCollection, o as AgreementExecutionCollection, p as AGREEMENT_STATUSES, r as ExecutedAgreement, s as AgreementExecution, t as AgreementExecutionService, u as parseAgreementParty } from "./chunks/agreements-C8rxIVGB.js";
3
3
  export { AGREEMENT_EXECUTION_STATUSES, AGREEMENT_STATUSES, Agreement, AgreementCollection, AgreementExecution, AgreementExecutionCollection, AgreementExecutionEvent, AgreementExecutionEventCollection, AgreementExecutionService, ExecutedAgreement, ExecutedAgreementCollection, coerceAgreementDate, parseAgreementParty, sanitizeSignerEvidence, sanitizeSignerIntent, serializeAgreementParty };