@happyvertical/smrt-sales 0.39.13 → 0.39.14
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.
- package/AGENTS.md +7 -2
- package/dist/chunks/__smrt-register__-B2OBLeaC.js +6 -0
- package/dist/chunks/{__smrt-register__-Xl8ZSA-J.js.map → __smrt-register__-B2OBLeaC.js.map} +1 -1
- package/dist/chunks/{commissions-CgEyZZpd.js → commissions-DbB_Zd17.js} +1004 -61
- package/dist/chunks/commissions-DbB_Zd17.js.map +1 -0
- package/dist/chunks/{referrals-tb6Jb_eU.js → referrals-DTnPVdFk.js} +2 -2
- package/dist/chunks/{referrals-tb6Jb_eU.js.map → referrals-DTnPVdFk.js.map} +1 -1
- package/dist/commissions/collections/CommissionAdjustmentCollection.d.ts +6 -0
- package/dist/commissions/collections/CommissionAdjustmentCollection.d.ts.map +1 -1
- package/dist/commissions/collections/CommissionCollection.d.ts +7 -0
- package/dist/commissions/collections/CommissionCollection.d.ts.map +1 -1
- package/dist/commissions/collections/CommissionPayoutCollection.d.ts +13 -0
- package/dist/commissions/collections/CommissionPayoutCollection.d.ts.map +1 -1
- package/dist/commissions/collections/EarnerSourceAttributionCollection.d.ts +17 -0
- package/dist/commissions/collections/EarnerSourceAttributionCollection.d.ts.map +1 -0
- package/dist/commissions/collections/index.d.ts +1 -0
- package/dist/commissions/collections/index.d.ts.map +1 -1
- package/dist/commissions/models/CommissionPayout.d.ts +27 -0
- package/dist/commissions/models/CommissionPayout.d.ts.map +1 -1
- package/dist/commissions/models/EarnerSourceAttribution.d.ts +51 -0
- package/dist/commissions/models/EarnerSourceAttribution.d.ts.map +1 -0
- package/dist/commissions/models/index.d.ts +1 -0
- package/dist/commissions/models/index.d.ts.map +1 -1
- package/dist/commissions/services/CommissionPayoutService.d.ts +283 -1
- package/dist/commissions/services/CommissionPayoutService.d.ts.map +1 -1
- package/dist/commissions/services/EarnerAttributionService.d.ts +121 -0
- package/dist/commissions/services/EarnerAttributionService.d.ts.map +1 -0
- package/dist/commissions/services/index.d.ts +2 -1
- package/dist/commissions/services/index.d.ts.map +1 -1
- package/dist/commissions/types.d.ts +24 -2
- package/dist/commissions/types.d.ts.map +1 -1
- package/dist/commissions.js +3 -3
- package/dist/crm.js +1 -1
- package/dist/index.js +4 -4
- package/dist/manifest.json +516 -48
- package/dist/referrals.js +2 -2
- package/dist/smrt-knowledge.json +264 -8
- package/dist/svelte/__tests__/types.test.js +19 -0
- package/dist/svelte/components/PayoutBatchReview.svelte +52 -5
- package/dist/svelte/components/PayoutBatchReview.svelte.d.ts +5 -0
- package/dist/svelte/components/PayoutBatchReview.svelte.d.ts.map +1 -1
- package/dist/svelte/types.d.ts +5 -2
- package/dist/svelte/types.d.ts.map +1 -1
- package/dist/svelte/types.js +11 -5
- package/package.json +6 -6
- package/dist/chunks/__smrt-register__-Xl8ZSA-J.js +0 -6
- package/dist/chunks/commissions-CgEyZZpd.js.map +0 -1
package/AGENTS.md
CHANGED
|
@@ -25,12 +25,15 @@ Referrers and Sales Representatives are **distinct roles** and stay that way. Bo
|
|
|
25
25
|
### commissions — neutral financial core
|
|
26
26
|
|
|
27
27
|
- **Earner**: `profileId`, `status` (`pending|active|suspended`), `payoutMethod` (`bank_transfer|check|paypal|credit|other`), `payoutThresholdCents`, `payoutScheduleKey` (open string: `manual`, `monthly`, …), `currency`, `metadata`.
|
|
28
|
-
- **
|
|
28
|
+
- **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`.
|
|
29
|
+
- **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`).
|
|
29
30
|
- **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()`.
|
|
30
31
|
- **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).
|
|
31
32
|
- **CommissionAdjustment**: append-only corrections (`refund|credit|chargeback|dispute|correction`), signed `amountCents`, required `reason`, immutable once created. Earned/paid Commissions are never rewritten — adjustments append to them.
|
|
32
33
|
- **Payable balance**: computed, not stored — `CommissionBalanceService` sums payable Commissions plus unsettled Adjustments per Earner/currency.
|
|
33
|
-
- **CommissionPayout**: settlement batch per Earner. `pending → approved → processing → completed | failed` (`resetFromFailed()` is the only exit from failed);
|
|
34
|
+
- **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}`) — 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.
|
|
35
|
+
- **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).
|
|
36
|
+
- **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), totals are 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 resolve as one `transitioned` + `already_applied` echoes; `expectedStatus` adds optimistic-concurrency strictness. Memberless batch artifacts cannot pass the source-authorized door (`membership_empty`) — they stay operator-level.
|
|
34
37
|
|
|
35
38
|
### crm
|
|
36
39
|
|
|
@@ -84,6 +87,8 @@ Every model is `@TenantScoped({ mode: 'optional' })` with `@tenantId({ nullable:
|
|
|
84
87
|
- **Table names are global**: new models were named to avoid collisions across packages (`commission_payouts`, `sales_activities`, `attribution_policies`, …).
|
|
85
88
|
- **Svelte module is svelte-check-gated**: no runtime component tests; `typecheck` runs `svelte-check` via `scripts/svelte-check-a11y.mjs`. Ship raw `.svelte` via `svelte-package`.
|
|
86
89
|
- **Model transition methods don't save**: `markEarned()/approve()/markPayable()/markPaid()` (Commission) and the payout transitions mutate + stamp timestamps only — callers save; the settlement/payout services do both.
|
|
90
|
+
- **`reject()` alone strands rows**: the model method only flips status — always reject through `transitionPayoutForSource`, which releases the batch's membership in the same transaction; stamped rows on a rejected payout would be unsettleable forever.
|
|
91
|
+
- **The payout source stamp is derived data, never authorization**: `sourceKind`/`sourceId` on CommissionPayout index the history listing; both the listing and the lifecycle service re-verify actual membership and fail closed when the stamp cannot be proven.
|
|
87
92
|
- **`sweepClearing` treats `clearingEndsAt: null` as immediately sweepable** (no clearing configured ⇒ nothing to wait for).
|
|
88
93
|
- **Agreement freeze scope**: activating a ReferralAgreement freezes referrer/program/version/plan refs/clearingDays/approvalMode/effectiveFrom; `effectiveTo` (end-dating) and the evidence fields (`contractRef`, artifact url/hash, `acceptanceEvidence`) stay writable — e-signature completes downstream.
|
|
89
94
|
- **Circular FK pair by design**: `Referral.snapshotId ↔ ReferralTermSnapshot.referralId`. Fine on SQLite (and no cross-table DDL constraints are emitted for these string FKs); keep an eye on strict-DDL environments.
|