@happyvertical/smrt-sales 0.51.32 → 0.51.34

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 (91) hide show
  1. package/dist/agreements/collections/AgreementExecutionCollection.d.ts +1 -1
  2. package/dist/agreements/collections/AgreementExecutionEventCollection.d.ts +1 -1
  3. package/dist/agreements/collections/ExecutedAgreementCollection.d.ts +1 -1
  4. package/dist/agreements/models/AgreementExecution.d.ts +2 -1
  5. package/dist/agreements/models/AgreementExecutionEvent.d.ts +2 -1
  6. package/dist/agreements/models/ExecutedAgreement.d.ts +2 -1
  7. package/dist/agreements/services/AgreementExecutionService.d.ts +7 -6
  8. package/dist/agreements/types.d.ts +3 -2
  9. package/dist/agreements.d.ts +7 -0
  10. package/dist/agreements.js +1 -1
  11. package/dist/chunks/{__smrt-register__-D4oQpwQY.js → __smrt-register__-CJkQS7rB.js} +2 -2
  12. package/dist/chunks/{__smrt-register__-D4oQpwQY.js.map → __smrt-register__-CJkQS7rB.js.map} +1 -1
  13. package/dist/commissions/collections/CommissionAdjustmentCollection.d.ts +13 -0
  14. package/dist/commissions/collections/CommissionAdjustmentOperationCollection.d.ts +1 -0
  15. package/dist/commissions/collections/CommissionCollection.d.ts +12 -1
  16. package/dist/commissions/collections/CommissionPayoutCollection.d.ts +6 -1
  17. package/dist/commissions/collections/CommissionPlanCollection.d.ts +9 -1
  18. package/dist/commissions/collections/EarnerCollection.d.ts +5 -1
  19. package/dist/commissions/collections/EarnerSourceAttributionCollection.d.ts +10 -0
  20. package/dist/commissions/collections/EarningEventCollection.d.ts +5 -1
  21. package/dist/commissions/models/Commission.d.ts +27 -1
  22. package/dist/commissions/models/CommissionAdjustment.d.ts +19 -1
  23. package/dist/commissions/models/CommissionAdjustmentOperation.d.ts +2 -1
  24. package/dist/commissions/models/CommissionPayout.d.ts +35 -1
  25. package/dist/commissions/models/CommissionPlan.d.ts +19 -1
  26. package/dist/commissions/models/Earner.d.ts +13 -1
  27. package/dist/commissions/models/EarnerSourceAttribution.d.ts +60 -1
  28. package/dist/commissions/models/EarningEvent.d.ts +28 -1
  29. package/dist/commissions/services/CommissionAdjustmentService.d.ts +4 -3
  30. package/dist/commissions/services/CommissionBalanceService.d.ts +16 -2
  31. package/dist/commissions/services/CommissionCalculationService.d.ts +16 -4
  32. package/dist/commissions/services/CommissionPayoutService.d.ts +28 -3
  33. package/dist/commissions/services/CommissionSettlementService.d.ts +13 -2
  34. package/dist/commissions/services/EarnerAttributionService.d.ts +22 -4
  35. package/dist/commissions/types.d.ts +16 -1
  36. package/dist/commissions.d.ts +9 -0
  37. package/dist/commissions.js +1 -1
  38. package/dist/crm/collections/LeadCollection.d.ts +8 -3
  39. package/dist/crm/collections/OpportunityCollection.d.ts +6 -1
  40. package/dist/crm/collections/OpportunityConversionCollection.d.ts +6 -1
  41. package/dist/crm/collections/PipelineDefinitionCollection.d.ts +7 -2
  42. package/dist/crm/collections/PipelineStageCollection.d.ts +4 -0
  43. package/dist/crm/collections/SalesActivityCollection.d.ts +5 -1
  44. package/dist/crm/collections/SalesRepresentativeCollection.d.ts +4 -0
  45. package/dist/crm/models/Lead.d.ts +5 -1
  46. package/dist/crm/models/Opportunity.d.ts +5 -1
  47. package/dist/crm/models/OpportunityConversion.d.ts +5 -1
  48. package/dist/crm/models/PipelineDefinition.d.ts +5 -1
  49. package/dist/crm/models/PipelineStage.d.ts +5 -1
  50. package/dist/crm/models/SalesActivity.d.ts +5 -1
  51. package/dist/crm/models/SalesRepresentative.d.ts +5 -1
  52. package/dist/crm/services/LeadWorkflowService.d.ts +15 -5
  53. package/dist/crm/types.d.ts +16 -5
  54. package/dist/crm.d.ts +8 -0
  55. package/dist/crm.js +1 -1
  56. package/dist/index.d.ts +26 -0
  57. package/dist/index.js +1 -1
  58. package/dist/manifest.json +1 -1
  59. package/dist/referrals/collections/AttributionExceptionCollection.d.ts +5 -0
  60. package/dist/referrals/collections/AttributionPolicyCollection.d.ts +11 -1
  61. package/dist/referrals/collections/ReferralAgreementCollection.d.ts +11 -1
  62. package/dist/referrals/collections/ReferralClickOperationCollection.d.ts +1 -0
  63. package/dist/referrals/collections/ReferralCollection.d.ts +4 -0
  64. package/dist/referrals/collections/ReferralLinkCollection.d.ts +9 -2
  65. package/dist/referrals/collections/ReferralProgramCollection.d.ts +5 -1
  66. package/dist/referrals/collections/ReferralTermSnapshotCollection.d.ts +8 -0
  67. package/dist/referrals/collections/ReferralTouchCollection.d.ts +7 -0
  68. package/dist/referrals/collections/ReferrerCollection.d.ts +5 -1
  69. package/dist/referrals/models/AttributionException.d.ts +20 -1
  70. package/dist/referrals/models/AttributionPolicy.d.ts +20 -1
  71. package/dist/referrals/models/Referral.d.ts +25 -1
  72. package/dist/referrals/models/ReferralAgreement.d.ts +25 -1
  73. package/dist/referrals/models/ReferralClickOperation.d.ts +2 -1
  74. package/dist/referrals/models/ReferralLink.d.ts +5 -1
  75. package/dist/referrals/models/ReferralProgram.d.ts +5 -1
  76. package/dist/referrals/models/ReferralTermSnapshot.d.ts +22 -2
  77. package/dist/referrals/models/ReferralTouch.d.ts +20 -1
  78. package/dist/referrals/models/Referrer.d.ts +5 -1
  79. package/dist/referrals/services/AttributionService.d.ts +12 -4
  80. package/dist/referrals/services/ReferralAgreementExecutionService.d.ts +7 -6
  81. package/dist/referrals/services/ReferralCommissionService.d.ts +15 -2
  82. package/dist/referrals/services/ReferralQualificationService.d.ts +18 -3
  83. package/dist/referrals/types.d.ts +18 -1
  84. package/dist/referrals.d.ts +9 -0
  85. package/dist/referrals.js +1 -1
  86. package/dist/smrt-knowledge.json +4 -4
  87. package/dist/test-fixtures.d.ts +6 -0
  88. package/dist/test-fixtures.d.ts.map +1 -0
  89. package/dist/test-setup.d.ts +2 -0
  90. package/dist/test-setup.d.ts.map +1 -0
  91. package/package.json +7 -7
@@ -1 +1 @@
1
- {"version":3,"file":"__smrt-register__-D4oQpwQY.js","names":[],"sources":["../../src/__smrt-register__.ts"],"sourcesContent":["import { ObjectRegistry } from '@happyvertical/smrt-core';\n\nObjectRegistry.registerPackageManifest(\n new URL('./manifest.json', import.meta.url),\n);\n"],"mappings":""}
1
+ {"version":3,"file":"__smrt-register__-CJkQS7rB.js","names":[],"sources":["../../src/__smrt-register__.ts"],"sourcesContent":["import { ObjectRegistry } from '@happyvertical/smrt-core';\n\nObjectRegistry.registerPackageManifest(\n new URL('./manifest.json', import.meta.url),\n);\n"],"mappings":""}
@@ -1,3 +1,16 @@
1
+ /**
2
+ * CommissionAdjustmentCollection — collection manager for
3
+ * {@link CommissionAdjustment}.
4
+ *
5
+ * "Unsettled" means `payoutId` is empty (checked in memory so `''`/`NULL`
6
+ * storage differences don't matter). NOTE: the collection-level queries do
7
+ * NOT apply the parent-commission-status eligibility rule — that lives in
8
+ * `CommissionBalanceService` / `CommissionPayoutService`, which filter
9
+ * unsettled adjustments to those whose parent commission is
10
+ * earned/approved/payable/paid.
11
+ *
12
+ * @packageDocumentation
13
+ */
1
14
  import { SmrtCollection } from '@happyvertical/smrt-core';
2
15
  import { CommissionAdjustment } from '../models/CommissionAdjustment.js';
3
16
  export declare class CommissionAdjustmentCollection extends SmrtCollection<CommissionAdjustment> {
@@ -1,3 +1,4 @@
1
+ /** Database serialization primitive for adjustment operation UUIDs. */
1
2
  import { SmrtCollection } from '@happyvertical/smrt-core';
2
3
  import { CommissionAdjustmentOperation } from '../models/CommissionAdjustmentOperation.js';
3
4
  export interface ClaimCommissionAdjustmentOperationInput {
@@ -1,6 +1,17 @@
1
+ /**
2
+ * CommissionCollection — collection manager for {@link Commission}.
3
+ *
4
+ * "Unsettled" throughout means `payoutId` is empty — the row has not been
5
+ * gathered into a {@link CommissionPayout} batch yet. The emptiness check is
6
+ * applied in memory (`!c.payoutId`) rather than as a `WHERE payout_id = ''`
7
+ * filter so the semantics hold whether an adapter stores the empty
8
+ * reference as `''` or `NULL`.
9
+ *
10
+ * @packageDocumentation
11
+ */
1
12
  import { SmrtCollection } from '@happyvertical/smrt-core';
2
13
  import { Commission } from '../models/Commission.js';
3
- import { CommissionStatus } from '../types.js';
14
+ import type { CommissionStatus } from '../types.js';
4
15
  export declare class CommissionCollection extends SmrtCollection<Commission> {
5
16
  static readonly _itemClass: typeof Commission;
6
17
  /** All commissions for an earner, newest first. */
@@ -1,6 +1,11 @@
1
+ /**
2
+ * CommissionPayoutCollection — collection manager for
3
+ * {@link CommissionPayout}.
4
+ * @packageDocumentation
5
+ */
1
6
  import { SmrtCollection } from '@happyvertical/smrt-core';
2
7
  import { CommissionPayout } from '../models/CommissionPayout.js';
3
- import { CommissionPayoutStatus } from '../types.js';
8
+ import type { CommissionPayoutStatus } from '../types.js';
4
9
  export declare class CommissionPayoutCollection extends SmrtCollection<CommissionPayout> {
5
10
  static readonly _itemClass: typeof CommissionPayout;
6
11
  /** All payout batches for an earner, newest first. */
@@ -1,6 +1,14 @@
1
+ /**
2
+ * CommissionPlanCollection — collection manager for {@link CommissionPlan}.
3
+ *
4
+ * Plans are versioned rows: amendments insert `(planKey, maxVersion + 1)`
5
+ * drafts via {@link createAmendment}; existing versions are never rewritten.
6
+ *
7
+ * @packageDocumentation
8
+ */
1
9
  import { SmrtCollection } from '@happyvertical/smrt-core';
2
10
  import { CommissionPlan } from '../models/CommissionPlan.js';
3
- import { CommissionPlanComponent, CommissionPlanStatus } from '../types.js';
11
+ import type { CommissionPlanComponent, CommissionPlanStatus } from '../types.js';
4
12
  /**
5
13
  * Fields an amendment may change relative to the version it copies.
6
14
  * `planKey` is fixed (it identifies the plan), `version` is computed, and
@@ -1,6 +1,10 @@
1
+ /**
2
+ * EarnerCollection — collection manager for {@link Earner}.
3
+ * @packageDocumentation
4
+ */
1
5
  import { SmrtCollection } from '@happyvertical/smrt-core';
2
6
  import { Earner } from '../models/Earner.js';
3
- import { EarnerStatus } from '../types.js';
7
+ import type { EarnerStatus } from '../types.js';
4
8
  export declare class EarnerCollection extends SmrtCollection<Earner> {
5
9
  static readonly _itemClass: typeof Earner;
6
10
  /** Earners linked to a smrt-profiles Profile. */
@@ -1,3 +1,13 @@
1
+ /**
2
+ * EarnerSourceAttributionCollection — collection manager for
3
+ * {@link EarnerSourceAttribution}.
4
+ *
5
+ * The queries here are the indexed primitives; the earner-resolving lookups
6
+ * (single + batched, active-earner filtered, ambiguity fail-closed) live on
7
+ * `EarnerAttributionService`.
8
+ *
9
+ * @packageDocumentation
10
+ */
1
11
  import { SmrtCollection } from '@happyvertical/smrt-core';
2
12
  import { EarnerSourceAttribution } from '../models/EarnerSourceAttribution.js';
3
13
  export declare class EarnerSourceAttributionCollection extends SmrtCollection<EarnerSourceAttribution> {
@@ -1,6 +1,10 @@
1
+ /**
2
+ * EarningEventCollection — collection manager for {@link EarningEvent}.
3
+ * @packageDocumentation
4
+ */
1
5
  import { SmrtCollection } from '@happyvertical/smrt-core';
2
6
  import { EarningEvent } from '../models/EarningEvent.js';
3
- import { EarningEventOptions } from '../types.js';
7
+ import type { EarningEventOptions } from '../types.js';
4
8
  export declare class EarningEventCollection extends SmrtCollection<EarningEvent> {
5
9
  static readonly _itemClass: typeof EarningEvent;
6
10
  /** Look up an event by its idempotency natural key. */
@@ -1,5 +1,31 @@
1
+ /**
2
+ * Commission — one earning record for one earner, one plan component, one
3
+ * earning-event occurrence.
4
+ *
5
+ * Amounts are integer cents; `rate`/`shareFraction` are decimals in 0–1.
6
+ * Every row stores snapshot references (`planKey`/`planVersion` plus a
7
+ * generic polymorphic `termsSnapshotKind`/`termsSnapshotId` — the referrals
8
+ * module points the latter at its ReferralTermSnapshot) and a JSON
9
+ * `calculationTrace` sufficient to reproduce `amountCents`, so earnings stay
10
+ * auditable after plans are superseded.
11
+ *
12
+ * Lifecycle is a STRICT forward chain — `pending → earned → approved →
13
+ * payable → paid` — enforced at save time against the AUTHORITATIVE prior
14
+ * persisted status (re-read from the database, commerce pattern), so neither
15
+ * raw mass-assignment nor a `create({ id, _skipLoad: true })` upsert can skip
16
+ * steps or roll back. Use the transition methods ({@link markEarned} /
17
+ * {@link approve} / {@link markPayable} / {@link markPaid}); they mutate and
18
+ * stamp timestamps but DO NOT save — the caller saves (one explicit
19
+ * persistence point per mutation, matching commerce's markSent/markConfirmed
20
+ * convention).
21
+ *
22
+ * Commissions are audit rows: the generated surface has no update or delete.
23
+ * Corrections append {@link CommissionAdjustment} rows instead of editing.
24
+ *
25
+ * @packageDocumentation
26
+ */
1
27
  import { SmrtObject } from '@happyvertical/smrt-core';
2
- import { CommissionBasis, CommissionCalculationTrace, CommissionOptions, CommissionStatus } from '../types.js';
28
+ import type { CommissionBasis, CommissionCalculationTrace, CommissionOptions, CommissionStatus } from '../types.js';
3
29
  export declare class Commission extends SmrtObject {
4
30
  /** Tenant ID for multi-tenant isolation (nullable → global rows). */
5
31
  tenantId: string | null;
@@ -1,5 +1,23 @@
1
+ /**
2
+ * CommissionAdjustment — append-only correction against a Commission.
3
+ *
4
+ * Earned/paid Commissions are NEVER rewritten. A refund, credit,
5
+ * chargeback, dispute outcome, or manual correction appends one of these
6
+ * rows instead. `amountCents` is SIGNED — negative amounts claw earnings
7
+ * back; positive amounts credit extra.
8
+ *
9
+ * Immutability contract: once persisted, an adjustment's substance
10
+ * (`commissionId`, `earnerId`, `adjustmentKind`, `amountCents`, `currency`,
11
+ * `reason`, `createdByProfileId`, `metadata`, `tenantId`) is frozen — the
12
+ * save-time guard rejects any change via a WeakMap snapshot compare (the
13
+ * commerce LicenseSale pattern). The ONLY post-create mutation allowed is
14
+ * stamping/clearing `payoutId` when a settlement batch picks the row up.
15
+ * A wrong adjustment is corrected by appending a counter-adjustment.
16
+ *
17
+ * @packageDocumentation
18
+ */
1
19
  import { SmrtObject } from '@happyvertical/smrt-core';
2
- import { CommissionAdjustmentKind, CommissionAdjustmentOptions } from '../types.js';
20
+ import type { CommissionAdjustmentKind, CommissionAdjustmentOptions } from '../types.js';
3
21
  export declare class CommissionAdjustment extends SmrtObject {
4
22
  /** Tenant ID for multi-tenant isolation (nullable → global rows). */
5
23
  tenantId: string | null;
@@ -1,4 +1,5 @@
1
- import { SmrtObject, SmrtObjectOptions } from '@happyvertical/smrt-core';
1
+ /** Persisted serialization fence for idempotent CommissionAdjustment writes. */
2
+ import { SmrtObject, type SmrtObjectOptions } from '@happyvertical/smrt-core';
2
3
  interface CommissionAdjustmentOperationOptions extends SmrtObjectOptions {
3
4
  tenantId?: string;
4
5
  adjustmentId?: string;
@@ -1,5 +1,39 @@
1
+ /**
2
+ * CommissionPayout — settlement batch for one earner in one currency.
3
+ *
4
+ * A payout gathers an earner's payable unsettled Commissions plus the
5
+ * unsettled Adjustments of eligible commissions, stamps `payoutId` on those
6
+ * EXACT rows, and records the totals it settled
7
+ * (`totalAmountCents = commissionTotalCents + adjustmentTotalCents` —
8
+ * enforced at save time). Batches are minted by
9
+ * `CommissionPayoutService.createPayoutBatch`, idempotently via the
10
+ * `idempotencyKey` natural key.
11
+ *
12
+ * The model is named CommissionPayout (table `commission_payouts`) to avoid
13
+ * the global table-name collision with commerce `Payout` / legacy affiliates
14
+ * `Payout` (`payouts`).
15
+ *
16
+ * Generated surface is FULLY read-only — list/get on api, mcp, AND cli.
17
+ * Commerce Payout precedent ("a payout has no safe generated write"): the
18
+ * status drives an outgoing remittance and the totals are the integrity
19
+ * core, so the only legitimate writes are the service's creation path and
20
+ * the guarded transition helpers below. The CLI is an independently
21
+ * configured write surface — `cli: true` would regenerate the exact
22
+ * create/update vector closed on api/mcp, so it is locked to list/get too.
23
+ *
24
+ * Lifecycle: `pending → approved → processing → completed | failed`, with
25
+ * `failed` reachable from approved/processing and resettable to `pending`
26
+ * only via {@link resetFromFailed}, and `rejected` the terminal
27
+ * operator-decline exit from pending/approved (see {@link reject} — the
28
+ * membership release lives in
29
+ * `CommissionPayoutService.transitionPayoutForSource`). Transition helpers
30
+ * mutate and stamp but DO NOT save — the caller saves (same convention as
31
+ * Commission).
32
+ *
33
+ * @packageDocumentation
34
+ */
1
35
  import { SmrtObject } from '@happyvertical/smrt-core';
2
- import { CommissionPayoutOptions, CommissionPayoutStatus, PayoutMethod } from '../types.js';
36
+ import type { CommissionPayoutOptions, CommissionPayoutStatus, PayoutMethod } from '../types.js';
3
37
  export declare class CommissionPayout extends SmrtObject {
4
38
  /** Tenant ID for multi-tenant isolation (nullable → global payouts). */
5
39
  tenantId: string | null;
@@ -1,5 +1,23 @@
1
+ /**
2
+ * CommissionPlan — versioned commission calculation terms.
3
+ *
4
+ * A plan is identified by its `(planKey, version)` natural key. Versions are
5
+ * ROWS, not edits: amending a plan inserts a `version + 1` draft (see
6
+ * `CommissionPlanCollection.createAmendment`) and the prior version is never
7
+ * rewritten. Once a row has been saved with status `active`, its calculation
8
+ * identity (`components`, `currency`, `planKey`, `version`, `effectiveFrom`)
9
+ * is frozen — re-saving with any of them changed throws (same
10
+ * WeakMap-serialize pattern as commerce's `LicenseSale` rights snapshot).
11
+ * Status transitions remain allowed on frozen rows.
12
+ *
13
+ * Generated write surface is deliberately narrow: `create` only (drafts),
14
+ * NO generated update route — amendments are new rows, and status moves go
15
+ * through the guarded transition methods / legal save-time edges.
16
+ *
17
+ * @packageDocumentation
18
+ */
1
19
  import { SmrtObject } from '@happyvertical/smrt-core';
2
- import { CommissionPlanComponent, CommissionPlanOptions, CommissionPlanStatus } from '../types.js';
20
+ import { type CommissionPlanComponent, type CommissionPlanOptions, type CommissionPlanStatus } from '../types.js';
3
21
  /**
4
22
  * Validate a components array. Throws a descriptive error on the first
5
23
  * violation. Exported for reuse by the calculation service's input guards
@@ -1,5 +1,17 @@
1
+ /**
2
+ * Earner — neutral financial payout account.
3
+ *
4
+ * Replaces the financial half of legacy smrt-affiliates' `Partner`: it holds
5
+ * everything money-related about a party that earns commissions (payout
6
+ * method, threshold, schedule, currency, status) and NOTHING role-related.
7
+ * Role models (a CRM `SalesRepresentative`, a referrals `Referrer`, or any
8
+ * application-defined role) each hold their own `earnerId` pointing here, so
9
+ * one person acting in several roles still settles through a single account.
10
+ *
11
+ * @packageDocumentation
12
+ */
1
13
  import { SmrtObject } from '@happyvertical/smrt-core';
2
- import { EarnerOptions, EarnerStatus, PayoutMethod } from '../types.js';
14
+ import type { EarnerOptions, EarnerStatus, PayoutMethod } from '../types.js';
3
15
  export declare class Earner extends SmrtObject {
4
16
  /**
5
17
  * Tenant ID for multi-tenant isolation. Nullable so global/operator-level
@@ -1,5 +1,64 @@
1
+ /**
2
+ * EarnerSourceAttribution — indexed external attribution mapping for an
3
+ * {@link Earner}.
4
+ *
5
+ * Maps a generic external key `(sourceKind, sourceId)` — an ad-network
6
+ * property, a marketplace storefront, a partner account, any
7
+ * application-defined attribution surface — to the Earner credited for it.
8
+ * High-volume ingestion resolves earners through the indexed lookups on
9
+ * `EarnerSourceAttributionCollection` / `EarnerAttributionService` instead of
10
+ * scanning every active earner's JSON metadata.
11
+ *
12
+ * The kind space is the CONSUMER's to define. It may — but need not —
13
+ * coincide with the `(sourceKind, sourceId)` earning-source pairs recorded on
14
+ * EarningEvents and Commissions: an application can attribute earners by
15
+ * property while its earning events carry the network as their source.
16
+ *
17
+ * ## Uniqueness and tenancy
18
+ *
19
+ * Natural key `(tenant_id, source_kind, source_id)` (`conflictColumns`): one
20
+ * mapping per external key per tenant. A `create` for an existing key
21
+ * UPSERTS — it re-points the mapping to the new `earnerId` (idempotent
22
+ * registration; use `EarnerAttributionService.registerAttribution` to observe
23
+ * whether a call created or re-pointed). The adapters' null-aware upsert
24
+ * dedups NULL-tenant (global) keys too, but the unique INDEX itself treats
25
+ * NULLs as distinct, so duplicate global rows can still arrive outside the
26
+ * model layer (raw-SQL imports, pre-null-aware data) — the lookups treat
27
+ * more than one ACTIVE row for a key as ambiguous and fail closed instead
28
+ * of picking one.
29
+ *
30
+ * With an active tenant context, lookups resolve within that tenant only
31
+ * (global rows are invisible). Without tenant context (`optional` mode)
32
+ * lookups see every row, so operator-level resolution across tenants can
33
+ * surface an ambiguity that per-tenant resolution would not — tenant-scoped
34
+ * applications should resolve inside `withTenant()`.
35
+ *
36
+ * ## Migrating metadata-based associations
37
+ *
38
+ * Consumers that previously stashed the association in `Earner.metadata`
39
+ * migrate with a one-time loop — `registerAttribution` is the idempotent
40
+ * backfill primitive (re-running the loop upserts, never duplicates):
41
+ *
42
+ * ```typescript
43
+ * const service = await EarnerAttributionService.create({ db });
44
+ * for (const earner of await earners.list({})) {
45
+ * const propertyIds = (earner.getMetadata().propertyIds ?? []) as string[];
46
+ * for (const propertyId of propertyIds) {
47
+ * await service.registerAttribution({
48
+ * earnerId: earner.id!,
49
+ * sourceKind: 'ad_network_property',
50
+ * sourceId: propertyId,
51
+ * tenantId: earner.tenantId,
52
+ * });
53
+ * }
54
+ * }
55
+ * // Verify via resolveActiveEarnersBySources(), then drop the metadata key.
56
+ * ```
57
+ *
58
+ * @packageDocumentation
59
+ */
1
60
  import { SmrtObject } from '@happyvertical/smrt-core';
2
- import { EarnerSourceAttributionOptions, EarnerSourceAttributionStatus } from '../types.js';
61
+ import type { EarnerSourceAttributionOptions, EarnerSourceAttributionStatus } from '../types.js';
3
62
  export declare class EarnerSourceAttribution extends SmrtObject {
4
63
  /** Tenant ID for multi-tenant isolation (nullable → global mappings). */
5
64
  tenantId: string | null;
@@ -1,5 +1,32 @@
1
+ /**
2
+ * EarningEvent — immutable commercial-event evidence.
3
+ *
4
+ * An EarningEvent records that something commission-worthy happened: a
5
+ * conversion, an agreement execution, an invoice payment, collected revenue,
6
+ * recognized margin, a milestone — or any application-defined kind
7
+ * (`eventKind` is an open string; see `EARNING_EVENT_KINDS` for the
8
+ * recommended vocabulary). The source is a generic `(sourceKind, sourceId)`
9
+ * string pair — this module never assumes advertising, Referral, Lead, or
10
+ * Opportunity semantics.
11
+ *
12
+ * Immutability contract: events are evidence. The generated surface exposes
13
+ * `create`/`list`/`get` only (no update, no delete), and application code
14
+ * must treat persisted rows as append-only — commissions reference an
15
+ * event's amounts in their calculation traces, so rewriting an event would
16
+ * silently orphan the audit trail. Corrections are modelled as NEW events
17
+ * (e.g. a `refund`-kind event) or as `CommissionAdjustment` rows.
18
+ *
19
+ * Idempotent ingestion: `dedupeKey` is the natural key
20
+ * (`conflictColumns: ['dedupe_key']`). Callers embed tenant and source
21
+ * identity in the key — e.g.
22
+ * `` `${tenantId}:${sourceKind}:${sourceId}:${eventKind}:${occurrence}` `` —
23
+ * so a retried ingest resolves to the existing row (see
24
+ * `EarningEventCollection.getOrCreateByDedupeKey`).
25
+ *
26
+ * @packageDocumentation
27
+ */
1
28
  import { SmrtObject } from '@happyvertical/smrt-core';
2
- import { EarningEventOptions } from '../types.js';
29
+ import type { EarningEventOptions } from '../types.js';
3
30
  export declare class EarningEvent extends SmrtObject {
4
31
  /** Tenant ID for multi-tenant isolation (nullable → global events). */
5
32
  tenantId: string | null;
@@ -1,6 +1,7 @@
1
- import { SmrtClassOptions } from '@happyvertical/smrt-core';
2
- import { CommissionAdjustment } from '../models/CommissionAdjustment.js';
3
- import { CommissionAdjustmentKind } from '../types.js';
1
+ /** Tenant-safe, idempotent creation of immutable commission adjustments. */
2
+ import type { SmrtClassOptions } from '@happyvertical/smrt-core';
3
+ import type { CommissionAdjustment } from '../models/CommissionAdjustment.js';
4
+ import { type CommissionAdjustmentKind } from '../types.js';
4
5
  /** One immutable operator correction intent. */
5
6
  export interface CreateCommissionAdjustmentInput {
6
7
  /** Stable caller-supplied UUID; retries MUST reuse it. */
@@ -1,7 +1,21 @@
1
- import { SmrtClassOptions } from '@happyvertical/smrt-core';
1
+ /**
2
+ * CommissionBalanceService — computed (never stored) per-earner balances.
3
+ *
4
+ * `payableCents` is the sum of unsettled `payable` commissions;
5
+ * `unsettledAdjustmentCents` is the signed sum of unsettled adjustments
6
+ * whose parent commission is earned/approved/payable/paid (adjustments
7
+ * against still-`pending` commissions wait for the earning to clear);
8
+ * `netPayableCents = payableCents + unsettledAdjustmentCents` and can go
9
+ * NEGATIVE when clawbacks against already-paid commissions exceed what is
10
+ * currently payable. The pending/earned/approved breakdowns feed portal
11
+ * views.
12
+ *
13
+ * @packageDocumentation
14
+ */
15
+ import type { SmrtClassOptions } from '@happyvertical/smrt-core';
2
16
  import { CommissionAdjustmentCollection } from '../collections/CommissionAdjustmentCollection.js';
3
17
  import { CommissionCollection } from '../collections/CommissionCollection.js';
4
- import { EarnerBalance } from '../types.js';
18
+ import { type EarnerBalance } from '../types.js';
5
19
  export declare class CommissionBalanceService {
6
20
  private readonly commissions;
7
21
  private readonly adjustments;
@@ -1,9 +1,21 @@
1
- import { SmrtClassOptions } from '@happyvertical/smrt-core';
1
+ /**
2
+ * CommissionCalculationService — turns one {@link EarningEvent} into
3
+ * Commission rows for one earner, driven by a set of plan components.
4
+ *
5
+ * The service deliberately takes COMPONENTS (plus `planKey`/`planVersion`
6
+ * snapshot refs), not a live plan: callers that calculate from frozen terms
7
+ * — e.g. the referrals module's term snapshots — pass the components they
8
+ * froze, so a later plan amendment can never leak into an already-agreed
9
+ * calculation.
10
+ *
11
+ * @packageDocumentation
12
+ */
13
+ import type { SmrtClassOptions } from '@happyvertical/smrt-core';
2
14
  import { CommissionCollection } from '../collections/CommissionCollection.js';
3
15
  import { EarnerCollection } from '../collections/EarnerCollection.js';
4
- import { Commission } from '../models/Commission.js';
5
- import { EarningEvent } from '../models/EarningEvent.js';
6
- import { CommissionPlanComponent } from '../types.js';
16
+ import type { Commission } from '../models/Commission.js';
17
+ import type { EarningEvent } from '../models/EarningEvent.js';
18
+ import type { CommissionPlanComponent } from '../types.js';
7
19
  /** Input for {@link CommissionCalculationService.calculateForEvent}. */
8
20
  export interface CommissionCalculationInput {
9
21
  /** The (persisted) earning event to calculate from. */
@@ -1,10 +1,35 @@
1
- import { SmrtClassOptions } from '@happyvertical/smrt-core';
1
+ /**
2
+ * CommissionPayoutService — mints and drives {@link CommissionPayout}
3
+ * settlement batches.
4
+ *
5
+ * The service is the ONLY sanctioned creation path for payouts (their
6
+ * generated surface is fully read-only): it gathers the exact payable
7
+ * unsettled Commissions and eligible unsettled Adjustments, refuses
8
+ * below-threshold / non-positive batches, stamps `payoutId` on the exact
9
+ * gathered rows, and later flips the batch's commissions to `paid` when the
10
+ * payout completes.
11
+ *
12
+ * Batch creation is deliberately non-transactional (conditional claims +
13
+ * disjoint scopes — see {@link createPayoutBatch}). Two surfaces layered on
14
+ * top serve per-source consumers:
15
+ *
16
+ * - {@link getSourcePayoutHistory} — the source-scoped, paginated,
17
+ * membership-verified payout history (#1985), indexed by the derived
18
+ * single-source stamp each batch/repair pass maintains.
19
+ * - {@link transitionPayoutForSource} — atomic source-authorized lifecycle
20
+ * transitions (#1987): payout row locked, membership re-verified and
21
+ * totals recomputed under the lock, transition + member writes committed
22
+ * together on the same transaction database.
23
+ *
24
+ * @packageDocumentation
25
+ */
26
+ import type { SmrtClassOptions } from '@happyvertical/smrt-core';
2
27
  import { CommissionAdjustmentCollection } from '../collections/CommissionAdjustmentCollection.js';
3
28
  import { CommissionCollection } from '../collections/CommissionCollection.js';
4
29
  import { CommissionPayoutCollection } from '../collections/CommissionPayoutCollection.js';
5
30
  import { EarnerCollection } from '../collections/EarnerCollection.js';
6
- import { CommissionPayout } from '../models/CommissionPayout.js';
7
- import { CommissionPayoutStatus, PayoutMethod } from '../types.js';
31
+ import type { CommissionPayout } from '../models/CommissionPayout.js';
32
+ import { type CommissionPayoutStatus, type PayoutMethod } from '../types.js';
8
33
  /** Collaborators for {@link CommissionPayoutService}. */
9
34
  export interface CommissionPayoutServiceDeps {
10
35
  earners: EarnerCollection;
@@ -1,6 +1,17 @@
1
- import { SmrtClassOptions } from '@happyvertical/smrt-core';
1
+ /**
2
+ * CommissionSettlementService — advances Commissions along the strict
3
+ * `pending → earned → approved → payable` chain (the final `payable → paid`
4
+ * step belongs to `CommissionPayoutService.completePayout`, which flips a
5
+ * batch's rows when the money actually moves).
6
+ *
7
+ * All methods persist the rows they advance (transition method + save per
8
+ * row) and return the updated instances.
9
+ *
10
+ * @packageDocumentation
11
+ */
12
+ import type { SmrtClassOptions } from '@happyvertical/smrt-core';
2
13
  import { CommissionCollection } from '../collections/CommissionCollection.js';
3
- import { Commission } from '../models/Commission.js';
14
+ import type { Commission } from '../models/Commission.js';
4
15
  export declare class CommissionSettlementService {
5
16
  private readonly commissions;
6
17
  constructor(commissions: CommissionCollection);
@@ -1,9 +1,27 @@
1
- import { SmrtClassOptions } from '@happyvertical/smrt-core';
1
+ /**
2
+ * EarnerAttributionService — registration and indexed resolution of
3
+ * {@link EarnerSourceAttribution} mappings.
4
+ *
5
+ * High-volume ingestion (e.g. billing events that must credit an earner per
6
+ * ad-network property) resolves earners here: one indexed attribution query
7
+ * plus one earner load per call, bounded by the REQUESTED keys — never a
8
+ * scan of all active earners. Resolution is fail-closed: a key that cannot
9
+ * be proven to map to exactly one active mapping and one active earner
10
+ * resolves to nothing, with a typed reason.
11
+ *
12
+ * Registration is the idempotent write path (and the documented
13
+ * metadata-migration backfill primitive — see the model doc): re-registering
14
+ * a key updates the existing mapping in place and reports the displaced
15
+ * earner instead of silently duplicating.
16
+ *
17
+ * @packageDocumentation
18
+ */
19
+ import type { SmrtClassOptions } from '@happyvertical/smrt-core';
2
20
  import { EarnerCollection } from '../collections/EarnerCollection.js';
3
21
  import { EarnerSourceAttributionCollection } from '../collections/EarnerSourceAttributionCollection.js';
4
- import { Earner } from '../models/Earner.js';
5
- import { EarnerSourceAttribution } from '../models/EarnerSourceAttribution.js';
6
- import { EarnerSourceAttributionStatus } from '../types.js';
22
+ import type { Earner } from '../models/Earner.js';
23
+ import type { EarnerSourceAttribution } from '../models/EarnerSourceAttribution.js';
24
+ import type { EarnerSourceAttributionStatus } from '../types.js';
7
25
  /** Collaborators for {@link EarnerAttributionService}. */
8
26
  export interface EarnerAttributionServiceDeps {
9
27
  earners: EarnerCollection;
@@ -1,4 +1,19 @@
1
- import { SmrtObjectOptions } from '@happyvertical/smrt-core';
1
+ /**
2
+ * Shared types for the neutral commissions financial core.
3
+ *
4
+ * Statuses are string-literal unions derived from `as const` arrays (no TS
5
+ * enums) so downstream code can iterate the legal values and the types stay
6
+ * erasable. All monetary fields across the module are integer cents with a
7
+ * `*Cents` suffix; rates/fractions are decimals in the range 0–1.
8
+ *
9
+ * This module is the neutral financial core of `@happyvertical/smrt-sales`:
10
+ * it never imports from the `crm` or `referrals` modules and never assumes
11
+ * advertising, Referral, Lead, or Opportunity semantics. Earning sources are
12
+ * generic `(sourceKind, sourceId)` string pairs.
13
+ *
14
+ * @packageDocumentation
15
+ */
16
+ import type { SmrtObjectOptions } from '@happyvertical/smrt-core';
2
17
  /** Lifecycle of an {@link Earner} payout account. */
3
18
  export declare const EARNER_STATUSES: readonly ["pending", "active", "suspended"];
4
19
  export type EarnerStatus = (typeof EARNER_STATUSES)[number];
@@ -1,2 +1,11 @@
1
+ /**
2
+ * Subpath entry: `@happyvertical/smrt-sales/commissions`.
3
+ *
4
+ * Neutral commission financial core: Earners, versioned Commission Plans,
5
+ * earning events, Commissions, append-only adjustments, payable balances,
6
+ * and CommissionPayout batches. Commission sources are extensible and never
7
+ * assume advertising, Referral, Lead, or Opportunity semantics.
8
+ */
9
+ import './__smrt-register__.js';
1
10
  export * from './commissions/index.js';
2
11
  //# sourceMappingURL=commissions.d.ts.map
@@ -1,3 +1,3 @@
1
- import "./chunks/__smrt-register__-D4oQpwQY.js";
1
+ import "./chunks/__smrt-register__-CJkQS7rB.js";
2
2
  import { A as EARNING_EVENT_KINDS, C as COMMISSION_ADJUSTMENT_KINDS, D as COMMISSION_STATUSES, E as COMMISSION_PLAN_STATUSES, F as Commission, I as CommissionAdjustmentOperationCollection, L as CommissionAdjustmentOperation, M as CommissionPayoutCollection, N as CommissionPayout, O as EARNER_SOURCE_ATTRIBUTION_STATUSES, P as CommissionCollection, R as CommissionAdjustmentCollection, S as ADJUSTMENT_SETTLEABLE_COMMISSION_STATUSES, T as COMMISSION_PAYOUT_STATUSES, _ as EarnerCollection, a as CommissionBalanceService, b as CommissionPlan, c as CommissionAdjustmentValidationError, d as centsToAmount, f as roundCents, g as EarnerSourceAttribution, h as EarnerSourceAttributionCollection, i as CommissionCalculationService, j as PAYOUT_METHODS, k as EARNER_STATUSES, l as amountToCents, m as EarningEvent, n as CommissionSettlementService, o as CommissionAdjustmentReplayConflictError, p as EarningEventCollection, r as CommissionPayoutService, s as CommissionAdjustmentService, t as EarnerAttributionService, u as calculateCommissionAmountCents, v as Earner, w as COMMISSION_BASES, x as validateCommissionPlanComponents, y as CommissionPlanCollection, z as CommissionAdjustment } from "./chunks/commissions-BlJpPXFC.js";
3
3
  export { ADJUSTMENT_SETTLEABLE_COMMISSION_STATUSES, COMMISSION_ADJUSTMENT_KINDS, COMMISSION_BASES, COMMISSION_PAYOUT_STATUSES, COMMISSION_PLAN_STATUSES, COMMISSION_STATUSES, Commission, CommissionAdjustment, CommissionAdjustmentCollection, CommissionAdjustmentOperation, CommissionAdjustmentOperationCollection, CommissionAdjustmentReplayConflictError, CommissionAdjustmentService, CommissionAdjustmentValidationError, CommissionBalanceService, CommissionCalculationService, CommissionCollection, CommissionPayout, CommissionPayoutCollection, CommissionPayoutService, CommissionPlan, CommissionPlanCollection, CommissionSettlementService, EARNER_SOURCE_ATTRIBUTION_STATUSES, EARNER_STATUSES, EARNING_EVENT_KINDS, Earner, EarnerAttributionService, EarnerCollection, EarnerSourceAttribution, EarnerSourceAttributionCollection, EarningEvent, EarningEventCollection, PAYOUT_METHODS, amountToCents, calculateCommissionAmountCents, centsToAmount, roundCents, validateCommissionPlanComponents };
@@ -1,8 +1,13 @@
1
+ /**
2
+ * LeadCollection — collection manager for Lead, including qualification into
3
+ * opportunities, audited duplicate merges, and merge-aware history reads.
4
+ * @packageDocumentation
5
+ */
1
6
  import { SmrtCollection } from '@happyvertical/smrt-core';
2
7
  import { Lead } from '../models/Lead.js';
3
- import { Opportunity } from '../models/Opportunity.js';
4
- import { SalesActivity } from '../models/SalesActivity.js';
5
- import { LeadStatus, MergeLeadsParams, MergeLeadsResult, QualifyLeadParams } from '../types.js';
8
+ import type { Opportunity } from '../models/Opportunity.js';
9
+ import type { SalesActivity } from '../models/SalesActivity.js';
10
+ import type { LeadStatus, MergeLeadsParams, MergeLeadsResult, QualifyLeadParams } from '../types.js';
6
11
  export declare class LeadCollection extends SmrtCollection<Lead> {
7
12
  static readonly _itemClass: typeof Lead;
8
13
  private opportunityCollectionPromise;
@@ -1,6 +1,11 @@
1
+ /**
2
+ * OpportunityCollection — collection manager for Opportunity, including
3
+ * validated, audited stage movement.
4
+ * @packageDocumentation
5
+ */
1
6
  import { SmrtCollection } from '@happyvertical/smrt-core';
2
7
  import { Opportunity } from '../models/Opportunity.js';
3
- import { MoveToStageParams } from '../types.js';
8
+ import type { MoveToStageParams } from '../types.js';
4
9
  export declare class OpportunityCollection extends SmrtCollection<Opportunity> {
5
10
  static readonly _itemClass: typeof Opportunity;
6
11
  private stageCollectionPromise;
@@ -1,6 +1,11 @@
1
+ /**
2
+ * OpportunityConversionCollection — collection manager for
3
+ * OpportunityConversion, including the idempotent recorder.
4
+ * @packageDocumentation
5
+ */
1
6
  import { SmrtCollection } from '@happyvertical/smrt-core';
2
7
  import { OpportunityConversion } from '../models/OpportunityConversion.js';
3
- import { RecordConversionParams, RecordConversionResult } from '../types.js';
8
+ import type { RecordConversionParams, RecordConversionResult } from '../types.js';
4
9
  export declare class OpportunityConversionCollection extends SmrtCollection<OpportunityConversion> {
5
10
  static readonly _itemClass: typeof OpportunityConversion;
6
11
  private opportunityCollectionPromise;