@happyvertical/smrt-sales 0.40.19 → 0.40.21

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.
@@ -1,3 +1,3 @@
1
- import "./chunks/__smrt-register__-ck7DyZQk.js";
1
+ import "./chunks/__smrt-register__-BG5Ze6GV.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-BAsJWmKg.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 };
package/dist/crm.js CHANGED
@@ -1,3 +1,3 @@
1
- import "./chunks/__smrt-register__-ck7DyZQk.js";
1
+ import "./chunks/__smrt-register__-BG5Ze6GV.js";
2
2
  import { S as Lead, _ as SalesActivityCollection, a as LeadCollection, b as PipelineStage, c as DEFAULT_PIPELINE_STAGES, d as PIPELINE_STATUSES, f as SALES_ACTIVITY_KINDS, g as OpportunityCollection, h as PipelineDefinition, i as OpportunityConversion, l as LEAD_STATUSES, m as SALES_REPRESENTATIVE_STATUSES, n as SalesRepresentative, o as PipelineDefinitionCollection, p as SALES_ACTIVITY_SUBJECT_KINDS, r as OpportunityConversionCollection, s as DEFAULT_PIPELINE_KEY, t as SalesRepresentativeCollection, u as OPPORTUNITY_STATUSES, v as SalesActivity, x as Opportunity, y as PipelineStageCollection } from "./chunks/crm-DwEz7E2r.js";
3
3
  export { DEFAULT_PIPELINE_KEY, DEFAULT_PIPELINE_STAGES, LEAD_STATUSES, Lead, LeadCollection, OPPORTUNITY_STATUSES, Opportunity, OpportunityCollection, OpportunityConversion, OpportunityConversionCollection, PIPELINE_STATUSES, PipelineDefinition, PipelineDefinitionCollection, PipelineStage, PipelineStageCollection, SALES_ACTIVITY_KINDS, SALES_ACTIVITY_SUBJECT_KINDS, SALES_REPRESENTATIVE_STATUSES, SalesActivity, SalesActivityCollection, SalesRepresentative, SalesRepresentativeCollection };
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import "./chunks/__smrt-register__-ck7DyZQk.js";
1
+ import "./chunks/__smrt-register__-BG5Ze6GV.js";
2
2
  import { a as AgreementExecutionEvent, c as AGREEMENT_EXECUTION_STATUSES, d as sanitizeSignerIntent, i as AgreementExecutionEventCollection, l as coerceAgreementDate, n as ExecutedAgreementCollection, o as AgreementExecutionCollection, r as ExecutedAgreement, s as AgreementExecution, t as AgreementExecutionService, u as sanitizeSignerEvidence } from "./chunks/agreements-DbzW1Pcq.js";
3
3
  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-BAsJWmKg.js";
4
4
  import { S as Lead, _ as SalesActivityCollection, a as LeadCollection, b as PipelineStage, c as DEFAULT_PIPELINE_STAGES, d as PIPELINE_STATUSES, f as SALES_ACTIVITY_KINDS, g as OpportunityCollection, h as PipelineDefinition, i as OpportunityConversion, l as LEAD_STATUSES, m as SALES_REPRESENTATIVE_STATUSES, n as SalesRepresentative, o as PipelineDefinitionCollection, p as SALES_ACTIVITY_SUBJECT_KINDS, r as OpportunityConversionCollection, s as DEFAULT_PIPELINE_KEY, t as SalesRepresentativeCollection, u as OPPORTUNITY_STATUSES, v as SalesActivity, x as Opportunity, y as PipelineStageCollection } from "./chunks/crm-DwEz7E2r.js";
5
- import { A as ReferralClickOperation, B as ATTRIBUTION_RESOLUTION_MODES, C as ReferralTouchCollection, D as ReferralCollection, E as assertHttpTargetUrl, F as validateAttributionPolicyTerms, G as REFERRAL_STATUSES, H as REFERRAL_AGREEMENT_STATUSES, I as ATTRIBUTION_CONFLICT_BEHAVIORS, J as AttributionExceptionCollection, K as REFERRAL_TOUCH_KINDS, L as ATTRIBUTION_CREDIT_MODES, M as ReferralAgreement, N as AttributionPolicyCollection, O as Referral, P as AttributionPolicy, R as ATTRIBUTION_EXCEPTION_STATUSES, S as generateReferralCode, T as ReferralLink, U as REFERRAL_LINK_STATUSES, V as REFERRAL_AGREEMENT_APPROVAL_MODES, W as REFERRAL_PROGRAM_STATUSES, Y as AttributionException, _ as REFERRAL_CODE_ALPHABET, a as ReferralAgreementExecutionService, b as ReferralClickValidationError, c as ReferrerCollection, d as ReferralTermSnapshot, f as ReferralProgramCollection, g as MAX_REFERRAL_CLICK_IDEMPOTENCY_KEY_BYTES, h as MAX_CODE_GENERATION_ATTEMPTS, i as REFERRAL_AGREEMENT_SOURCE_KIND, j as ReferralAgreementCollection, k as ReferralClickOperationCollection, l as Referrer, m as DEFAULT_REFERRAL_CLICK_EVIDENCE_MAX_BYTES, n as REFERRAL_TERMS_SNAPSHOT_KIND, o as AttributionService, p as ReferralProgram, q as REFERRER_STATUSES, r as ReferralCommissionService, s as QualifiedReferralOverrideError, t as ReferralQualificationService, u as ReferralTermSnapshotCollection, v as REFERRAL_CODE_LENGTH, w as ReferralTouch, x as ReferralLinkCollection, y as ReferralClickReplayConflictError, z as ATTRIBUTION_POLICY_STATUSES } from "./chunks/referrals-CeS9N5PI.js";
5
+ import { A as ReferralClickOperation, B as ATTRIBUTION_RESOLUTION_MODES, C as ReferralTouchCollection, D as ReferralCollection, E as assertHttpTargetUrl, F as validateAttributionPolicyTerms, G as REFERRAL_STATUSES, H as REFERRAL_AGREEMENT_STATUSES, I as ATTRIBUTION_CONFLICT_BEHAVIORS, J as AttributionExceptionCollection, K as REFERRAL_TOUCH_KINDS, L as ATTRIBUTION_CREDIT_MODES, M as ReferralAgreement, N as AttributionPolicyCollection, O as Referral, P as AttributionPolicy, R as ATTRIBUTION_EXCEPTION_STATUSES, S as generateReferralCode, T as ReferralLink, U as REFERRAL_LINK_STATUSES, V as REFERRAL_AGREEMENT_APPROVAL_MODES, W as REFERRAL_PROGRAM_STATUSES, Y as AttributionException, _ as REFERRAL_CODE_ALPHABET, a as ReferralAgreementExecutionService, b as ReferralClickValidationError, c as ReferrerCollection, d as ReferralTermSnapshot, f as ReferralProgramCollection, g as MAX_REFERRAL_CLICK_IDEMPOTENCY_KEY_BYTES, h as MAX_CODE_GENERATION_ATTEMPTS, i as REFERRAL_AGREEMENT_SOURCE_KIND, j as ReferralAgreementCollection, k as ReferralClickOperationCollection, l as Referrer, m as DEFAULT_REFERRAL_CLICK_EVIDENCE_MAX_BYTES, n as REFERRAL_TERMS_SNAPSHOT_KIND, o as AttributionService, p as ReferralProgram, q as REFERRER_STATUSES, r as ReferralCommissionService, s as QualifiedReferralOverrideError, t as ReferralQualificationService, u as ReferralTermSnapshotCollection, v as REFERRAL_CODE_LENGTH, w as ReferralTouch, x as ReferralLinkCollection, y as ReferralClickReplayConflictError, z as ATTRIBUTION_POLICY_STATUSES } from "./chunks/referrals-BzTlbjJH.js";
6
6
  export { ADJUSTMENT_SETTLEABLE_COMMISSION_STATUSES, AGREEMENT_EXECUTION_STATUSES, ATTRIBUTION_CONFLICT_BEHAVIORS, ATTRIBUTION_CREDIT_MODES, ATTRIBUTION_EXCEPTION_STATUSES, ATTRIBUTION_POLICY_STATUSES, ATTRIBUTION_RESOLUTION_MODES, AgreementExecution, AgreementExecutionCollection, AgreementExecutionEvent, AgreementExecutionEventCollection, AgreementExecutionService, AttributionException, AttributionExceptionCollection, AttributionPolicy, AttributionPolicyCollection, AttributionService, 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, DEFAULT_PIPELINE_KEY, DEFAULT_PIPELINE_STAGES, DEFAULT_REFERRAL_CLICK_EVIDENCE_MAX_BYTES, EARNER_SOURCE_ATTRIBUTION_STATUSES, EARNER_STATUSES, EARNING_EVENT_KINDS, Earner, EarnerAttributionService, EarnerCollection, EarnerSourceAttribution, EarnerSourceAttributionCollection, EarningEvent, EarningEventCollection, ExecutedAgreement, ExecutedAgreementCollection, LEAD_STATUSES, Lead, LeadCollection, MAX_CODE_GENERATION_ATTEMPTS, MAX_REFERRAL_CLICK_IDEMPOTENCY_KEY_BYTES, OPPORTUNITY_STATUSES, Opportunity, OpportunityCollection, OpportunityConversion, OpportunityConversionCollection, PAYOUT_METHODS, PIPELINE_STATUSES, PipelineDefinition, PipelineDefinitionCollection, PipelineStage, PipelineStageCollection, QualifiedReferralOverrideError, REFERRAL_AGREEMENT_APPROVAL_MODES, REFERRAL_AGREEMENT_SOURCE_KIND, REFERRAL_AGREEMENT_STATUSES, REFERRAL_CODE_ALPHABET, REFERRAL_CODE_LENGTH, REFERRAL_LINK_STATUSES, REFERRAL_PROGRAM_STATUSES, REFERRAL_STATUSES, REFERRAL_TERMS_SNAPSHOT_KIND, REFERRAL_TOUCH_KINDS, REFERRER_STATUSES, Referral, ReferralAgreement, ReferralAgreementCollection, ReferralAgreementExecutionService, ReferralClickOperation, ReferralClickOperationCollection, ReferralClickReplayConflictError, ReferralClickValidationError, ReferralCollection, ReferralCommissionService, ReferralLink, ReferralLinkCollection, ReferralProgram, ReferralProgramCollection, ReferralQualificationService, ReferralTermSnapshot, ReferralTermSnapshotCollection, ReferralTouch, ReferralTouchCollection, Referrer, ReferrerCollection, SALES_ACTIVITY_KINDS, SALES_ACTIVITY_SUBJECT_KINDS, SALES_REPRESENTATIVE_STATUSES, SalesActivity, SalesActivityCollection, SalesRepresentative, SalesRepresentativeCollection, amountToCents, assertHttpTargetUrl, calculateCommissionAmountCents, centsToAmount, coerceAgreementDate, generateReferralCode, roundCents, sanitizeSignerEvidence, sanitizeSignerIntent, validateAttributionPolicyTerms, validateCommissionPlanComponents };
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "version": "1.0.0",
3
- "timestamp": 1784615560182,
3
+ "timestamp": 1785008682722,
4
4
  "packageName": "@happyvertical/smrt-sales",
5
- "packageVersion": "0.40.19",
5
+ "packageVersion": "0.40.21",
6
6
  "objects": {
7
7
  "@happyvertical/smrt-sales:AgreementExecutionCollection": {
8
8
  "name": "agreementexecutioncollection",
@@ -1,4 +1,5 @@
1
1
  import { SmrtCollection } from '@happyvertical/smrt-core';
2
+ import { DatabaseInterface } from '@happyvertical/sql';
2
3
  import { ReferralLink } from '../models/ReferralLink.js';
3
4
  import { ReferralTouch } from '../models/ReferralTouch.js';
4
5
  /** Length of generated share codes. */
@@ -39,6 +40,12 @@ export type RecordClickRefusal = 'unknown_code' | 'link_disabled';
39
40
  * and `touch` are both set and `refused` is absent. On refusal `touch` is
40
41
  * `null`, `refused` names the reason, and `link` carries the (disabled) link
41
42
  * for `'link_disabled'` / `null` for `'unknown_code'`.
43
+ *
44
+ * When the click self-transacted (pool-bound collection, no
45
+ * {@link RecordClickInput.transaction}), models are re-read on the
46
+ * collection's database after commit. When the click participated in a
47
+ * caller transaction, models are bound to that transaction — current while
48
+ * it is open; carry ids across the commit boundary for long-lived use.
42
49
  */
43
50
  export interface RecordClickResult {
44
51
  link: ReferralLink | null;
@@ -82,6 +89,26 @@ export interface RecordClickInput {
82
89
  */
83
90
  subjectKind?: string;
84
91
  subjectId?: string;
92
+ /**
93
+ * Caller-owned open transaction this click should participate in: the
94
+ * database view your `db.transaction(async (tx) => …)` callback received,
95
+ * or a still-active `beginTransaction()` handle. When provided, every
96
+ * read and write of this click runs on it and Sales opens NO transaction
97
+ * of its own — atomicity, rollback, and locking belong to the caller's
98
+ * transaction, and the click sees the caller's uncommitted rows (a link
99
+ * created earlier in the same transaction resolves normally).
100
+ *
101
+ * Passing a pool-level database here is refused with a typed
102
+ * `'invalid_transaction'` {@link ReferralClickValidationError} — running
103
+ * the click's writes outside a transaction would abandon the atomicity
104
+ * guarantee, silently.
105
+ *
106
+ * Result models are bound to this transaction: they are current while it
107
+ * is open, but hold its connection afterwards — carry ids across the
108
+ * commit boundary and re-fetch on a pool-bound collection for long-lived
109
+ * use.
110
+ */
111
+ transaction?: DatabaseInterface;
85
112
  }
86
113
  export type ReferralClickReplayMismatchField = 'idempotencyKey' | 'tenantId' | 'code' | 'linkId' | 'targetUrl' | 'referrerId' | 'programId' | 'subjectKind' | 'subjectId' | 'occurredAt' | 'evidence' | 'intent';
87
114
  /** Typed fail-closed result for a replay key reused with another click. */
@@ -91,7 +118,7 @@ export declare class ReferralClickReplayConflictError extends Error {
91
118
  readonly code: "REFERRAL_CLICK_REPLAY_CONFLICT";
92
119
  constructor(idempotencyKey: string, mismatches: readonly ReferralClickReplayMismatchField[]);
93
120
  }
94
- export type ReferralClickValidationReason = 'invalid_idempotency_key' | 'invalid_occurred_at' | 'invalid_evidence' | 'invalid_max_evidence_bytes' | 'evidence_too_large' | 'transaction_unavailable' | 'operation_link_missing' | 'operation_touch_missing' | 'link_update_conflict';
121
+ export type ReferralClickValidationReason = 'invalid_idempotency_key' | 'invalid_occurred_at' | 'invalid_evidence' | 'invalid_max_evidence_bytes' | 'evidence_too_large' | 'transaction_unavailable' | 'invalid_transaction' | 'operation_link_missing' | 'operation_touch_missing' | 'link_update_conflict';
95
122
  /** Actionable validation/integrity error raised without a partial click. */
96
123
  export declare class ReferralClickValidationError extends Error {
97
124
  readonly reason: ReferralClickValidationReason;
@@ -126,6 +153,23 @@ export declare class ReferralLinkCollection extends SmrtCollection<ReferralLink>
126
153
  * returns the original touch without another increment; changed immutable
127
154
  * intent raises {@link ReferralClickReplayConflictError}.
128
155
  *
156
+ * Transactions: by default (collection bound to a pool-level database)
157
+ * the click opens and commits its own transaction, and the returned
158
+ * models are re-read on the collection's database after commit. To record
159
+ * a click inside YOUR transaction — required whenever your transaction
160
+ * holds locks the click needs (above all the `referral_links` row it
161
+ * increments) or created the link it resolves — either pass the
162
+ * transaction database as {@link RecordClickInput.transaction} or call
163
+ * `recordClick` on a collection bound to it
164
+ * (`ReferralLinkCollection.create({ db: tx, _reuseInitializedDb: true,
165
+ * _deferRuntimeInitialization: true })`). Both participate in the caller
166
+ * transaction instead of nesting (a nested adapter `transaction()` takes
167
+ * an independent pooled connection: it deadlocks undetectably on locks
168
+ * your transaction holds and cannot see your uncommitted rows —
169
+ * happyvertical/sdk#1108) and return models bound to it: commit/rollback
170
+ * and durability belong to you, and refusals/replays reflect your
171
+ * transaction's view.
172
+ *
129
173
  * Evidence is canonicalized, Sales-owned `code`/`linkId`/`targetUrl` fields
130
174
  * are applied, and the UTF-8 bytes of that exact persisted JSON are checked
131
175
  * before any write. The default bound is
@@ -138,6 +182,17 @@ export declare class ReferralLinkCollection extends SmrtCollection<ReferralLink>
138
182
  * returned, nothing is written).
139
183
  */
140
184
  recordClick(input: RecordClickInput): Promise<RecordClickResult>;
185
+ /**
186
+ * Bind the click's working collections to one transaction database. The
187
+ * transaction is the same initialized database on a pinned connection, so
188
+ * the lightweight-binding flags are requested (mirrors
189
+ * `CommissionPayoutService.txOptions`). Note `SmrtCollection.create()`
190
+ * currently forwards only whitelisted options — the two internal flags
191
+ * are dropped there today, and it is the same-URL system-table cache that
192
+ * keeps bootstrap DDL out of the transaction in practice; the flags make
193
+ * the intent explicit and take effect when core forwards them.
194
+ */
195
+ private static createClickCollections;
141
196
  /** Rebind public result models to the caller's database after commit. */
142
197
  private rehydrateRecordClickResult;
143
198
  private recordClickInTransaction;
@@ -1 +1 @@
1
- {"version":3,"file":"ReferralLinkCollection.d.ts","sourceRoot":"","sources":["../../../src/referrals/collections/ReferralLinkCollection.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAGH,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAE1D,OAAO,EAAuB,YAAY,EAAE,MAAM,2BAA2B,CAAC;AAC9E,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAIhE,uCAAuC;AACvC,eAAO,MAAM,oBAAoB,KAAK,CAAC;AAEvC,mEAAmE;AACnE,eAAO,MAAM,sBAAsB,yCAAyC,CAAC;AAE7E,oFAAoF;AACpF,eAAO,MAAM,4BAA4B,IAAI,CAAC;AAE9C,8EAA8E;AAC9E,eAAO,MAAM,yCAAyC,OAAO,CAAC;AAE9D,0DAA0D;AAC1D,eAAO,MAAM,wCAAwC,MAAM,CAAC;AAE5D;;;;GAIG;AACH,wBAAgB,oBAAoB,IAAI,MAAM,CAe7C;AAED,qEAAqE;AACrE,MAAM,WAAW,uBAAuB;IACtC,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB;;;;;OAKG;IACH,YAAY,CAAC,EAAE,MAAM,MAAM,CAAC;CAC7B;AAED,wEAAwE;AACxE,MAAM,MAAM,kBAAkB,GAAG,cAAc,GAAG,eAAe,CAAC;AAElE;;;;;GAKG;AACH,MAAM,WAAW,iBAAiB;IAChC,IAAI,EAAE,YAAY,GAAG,IAAI,CAAC;IAC1B,KAAK,EAAE,aAAa,GAAG,IAAI,CAAC;IAC5B,OAAO,CAAC,EAAE,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c,CAAC,YAAY,CAAC;IACtE,MAAM,CAAC,QAAQ,CAAC,UAAU,sBAAgB;IAE1C,8CAA8C;IACxC,cAAc,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,EAAE,CAAC;IAOjE;;;OAGG;IACG,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC;IAU5D;;;;;;;;;OASG;IACG,oBAAoB,CACxB,KAAK,EAAE,uBAAuB,GAC7B,OAAO,CAAC,YAAY,CAAC;IA+BxB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAkCG;IACG,WAAW,CAAC,KAAK,EAAE,gBAAgB,GAAG,OAAO,CAAC,iBAAiB,CAAC;IAuCtE;;;;;;;;;OASG;mBACkB,sBAAsB;IAe3C,yEAAyE;YAC3D,0BAA0B;YA6B1B,wBAAwB;YAqGxB,WAAW;CAuD1B;AAoRD,eAAe,sBAAsB,CAAC"}
package/dist/referrals.js CHANGED
@@ -1,3 +1,3 @@
1
- import "./chunks/__smrt-register__-ck7DyZQk.js";
2
- import { A as ReferralClickOperation, B as ATTRIBUTION_RESOLUTION_MODES, C as ReferralTouchCollection, D as ReferralCollection, E as assertHttpTargetUrl, F as validateAttributionPolicyTerms, G as REFERRAL_STATUSES, H as REFERRAL_AGREEMENT_STATUSES, I as ATTRIBUTION_CONFLICT_BEHAVIORS, J as AttributionExceptionCollection, K as REFERRAL_TOUCH_KINDS, L as ATTRIBUTION_CREDIT_MODES, M as ReferralAgreement, N as AttributionPolicyCollection, O as Referral, P as AttributionPolicy, R as ATTRIBUTION_EXCEPTION_STATUSES, S as generateReferralCode, T as ReferralLink, U as REFERRAL_LINK_STATUSES, V as REFERRAL_AGREEMENT_APPROVAL_MODES, W as REFERRAL_PROGRAM_STATUSES, Y as AttributionException, _ as REFERRAL_CODE_ALPHABET, a as ReferralAgreementExecutionService, b as ReferralClickValidationError, c as ReferrerCollection, d as ReferralTermSnapshot, f as ReferralProgramCollection, g as MAX_REFERRAL_CLICK_IDEMPOTENCY_KEY_BYTES, h as MAX_CODE_GENERATION_ATTEMPTS, i as REFERRAL_AGREEMENT_SOURCE_KIND, j as ReferralAgreementCollection, k as ReferralClickOperationCollection, l as Referrer, m as DEFAULT_REFERRAL_CLICK_EVIDENCE_MAX_BYTES, n as REFERRAL_TERMS_SNAPSHOT_KIND, o as AttributionService, p as ReferralProgram, q as REFERRER_STATUSES, r as ReferralCommissionService, s as QualifiedReferralOverrideError, t as ReferralQualificationService, u as ReferralTermSnapshotCollection, v as REFERRAL_CODE_LENGTH, w as ReferralTouch, x as ReferralLinkCollection, y as ReferralClickReplayConflictError, z as ATTRIBUTION_POLICY_STATUSES } from "./chunks/referrals-CeS9N5PI.js";
1
+ import "./chunks/__smrt-register__-BG5Ze6GV.js";
2
+ import { A as ReferralClickOperation, B as ATTRIBUTION_RESOLUTION_MODES, C as ReferralTouchCollection, D as ReferralCollection, E as assertHttpTargetUrl, F as validateAttributionPolicyTerms, G as REFERRAL_STATUSES, H as REFERRAL_AGREEMENT_STATUSES, I as ATTRIBUTION_CONFLICT_BEHAVIORS, J as AttributionExceptionCollection, K as REFERRAL_TOUCH_KINDS, L as ATTRIBUTION_CREDIT_MODES, M as ReferralAgreement, N as AttributionPolicyCollection, O as Referral, P as AttributionPolicy, R as ATTRIBUTION_EXCEPTION_STATUSES, S as generateReferralCode, T as ReferralLink, U as REFERRAL_LINK_STATUSES, V as REFERRAL_AGREEMENT_APPROVAL_MODES, W as REFERRAL_PROGRAM_STATUSES, Y as AttributionException, _ as REFERRAL_CODE_ALPHABET, a as ReferralAgreementExecutionService, b as ReferralClickValidationError, c as ReferrerCollection, d as ReferralTermSnapshot, f as ReferralProgramCollection, g as MAX_REFERRAL_CLICK_IDEMPOTENCY_KEY_BYTES, h as MAX_CODE_GENERATION_ATTEMPTS, i as REFERRAL_AGREEMENT_SOURCE_KIND, j as ReferralAgreementCollection, k as ReferralClickOperationCollection, l as Referrer, m as DEFAULT_REFERRAL_CLICK_EVIDENCE_MAX_BYTES, n as REFERRAL_TERMS_SNAPSHOT_KIND, o as AttributionService, p as ReferralProgram, q as REFERRER_STATUSES, r as ReferralCommissionService, s as QualifiedReferralOverrideError, t as ReferralQualificationService, u as ReferralTermSnapshotCollection, v as REFERRAL_CODE_LENGTH, w as ReferralTouch, x as ReferralLinkCollection, y as ReferralClickReplayConflictError, z as ATTRIBUTION_POLICY_STATUSES } from "./chunks/referrals-BzTlbjJH.js";
3
3
  export { ATTRIBUTION_CONFLICT_BEHAVIORS, ATTRIBUTION_CREDIT_MODES, ATTRIBUTION_EXCEPTION_STATUSES, ATTRIBUTION_POLICY_STATUSES, ATTRIBUTION_RESOLUTION_MODES, AttributionException, AttributionExceptionCollection, AttributionPolicy, AttributionPolicyCollection, AttributionService, DEFAULT_REFERRAL_CLICK_EVIDENCE_MAX_BYTES, MAX_CODE_GENERATION_ATTEMPTS, MAX_REFERRAL_CLICK_IDEMPOTENCY_KEY_BYTES, QualifiedReferralOverrideError, REFERRAL_AGREEMENT_APPROVAL_MODES, REFERRAL_AGREEMENT_SOURCE_KIND, REFERRAL_AGREEMENT_STATUSES, REFERRAL_CODE_ALPHABET, REFERRAL_CODE_LENGTH, REFERRAL_LINK_STATUSES, REFERRAL_PROGRAM_STATUSES, REFERRAL_STATUSES, REFERRAL_TERMS_SNAPSHOT_KIND, REFERRAL_TOUCH_KINDS, REFERRER_STATUSES, Referral, ReferralAgreement, ReferralAgreementCollection, ReferralAgreementExecutionService, ReferralClickOperation, ReferralClickOperationCollection, ReferralClickReplayConflictError, ReferralClickValidationError, ReferralCollection, ReferralCommissionService, ReferralLink, ReferralLinkCollection, ReferralProgram, ReferralProgramCollection, ReferralQualificationService, ReferralTermSnapshot, ReferralTermSnapshotCollection, ReferralTouch, ReferralTouchCollection, Referrer, ReferrerCollection, assertHttpTargetUrl, generateReferralCode, validateAttributionPolicyTerms };
@@ -1,14 +1,14 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "generatedAt": "2026-07-21T06:32:46.044Z",
3
+ "generatedAt": "2026-07-25T19:44:48.832Z",
4
4
  "packageName": "@happyvertical/smrt-sales",
5
- "packageVersion": "0.40.19",
5
+ "packageVersion": "0.40.21",
6
6
  "sourceManifestPath": "dist/manifest.json",
7
7
  "agentDocPath": "AGENTS.md",
8
8
  "sourceHashes": {
9
- "manifest": "65906168521e6341449232b6b3b6927bd156f81c5851fa355cfcb141843e4011",
10
- "packageJson": "0c352421ede1e0fb91df01e540b578d1165b4fa82b9e997ff4b1ce7ab6cd22d1",
11
- "agents": "47a9913b5dbbf97618b5ca604b256783e5ef8debc5c25acaeec37792d165f37c"
9
+ "manifest": "c4d33b334d89af82b4d3d4e1b57e63600da8d02c4092a0c5ad52ec5134a03c7d",
10
+ "packageJson": "557ab6d5840b6c8bf58b3c931f3244de5de626dc692528cfa0dc560d201a7eb7",
11
+ "agents": "8c585ed0f1f10a5ce4923b618345be68608189a8af38ec207bda6340f8eff446"
12
12
  },
13
13
  "exports": [
14
14
  ".",
@@ -6632,5 +6632,5 @@
6632
6632
  "polymorphicAssociations": 0,
6633
6633
  "uuidColumns": 136
6634
6634
  },
6635
- "agentDoc": "# @happyvertical/smrt-sales\n\nModular sales: provider-neutral agreement execution, CRM, referral intake, a neutral commissions financial core, and reusable Svelte surfaces. One installable package with distinct subpath exports:\n\n- `@happyvertical/smrt-sales/agreements`\n- `@happyvertical/smrt-sales/crm`\n- `@happyvertical/smrt-sales/referrals`\n- `@happyvertical/smrt-sales/commissions`\n- `@happyvertical/smrt-sales/svelte`\n\nThe root export re-exports every TS module. `agreements` depends on the provider-neutral `@happyvertical/signatures` contract and `smrt-assets`; provider credentials stay in the injected SDK adapter/secret store. `referrals` binds its versioned terms to `agreements`.\n\n## Validation\n\nRun `pnpm --filter @happyvertical/smrt-sales test` and `pnpm --filter @happyvertical/smrt-sales typecheck` for package changes. PostgreSQL-sensitive changes must also run `pnpm --filter @happyvertical/smrt-sales test:postgres`; the command uses the repository's disposable PostgreSQL harness and is registered in the PostgreSQL CI shard.\n\n## Roles vs. money\n\nReferrers and Sales Representatives are **distinct roles** and stay that way. Both connect to money through one neutral financial account:\n\n- **Earner** (commissions): payout identity — method, threshold, currency, status. Referenced by every Commission and CommissionPayout.\n- **SalesRepresentative** (crm) and **Referrer** (referrals): role models, each holding `profileId` (cross-package string ref to smrt-profiles) and `earnerId`.\n\n## Modules\n\n### agreements — verified execution evidence\n\n- **AgreementExecution**: private required-tenant orchestration state keyed by `(tenant_id, idempotency_key)`, with a collision-checked provider request/status, an expiring create-operation lease, source version/hash/size/Asset, intended signer identity/auth method, cancellation/expiry, reconciliation, exact staged artifact metadata, and secret-store references only.\n- **AgreementExecutionEvent**: private append-only evidence for verified webhooks and operator/provider operations. Provider events are deduped by tenant/provider replay key; explicit occurrence/first-receipt timestamps and the exact payload/hash are retained, while signature headers are never stored. A later receipt time for the same verified provider event is an idempotent replay. Stale, regressive, or conflicting terminal events are audited without regressing lifecycle state or creating executed evidence.\n- **ExecutedAgreement**: immutable read-only source version plus signed-document and audit-trail Asset ids/hashes/sizes/filenames/media types, completed signer evidence, acceptance/effective dates, and supersession reference. Amendments create new records.\n- **AgreementExecutionService**: accepts an SDK `SignatureProvider` and shared `AssetRuntimeLike`; enforces ambient tenant equality, expiring remote-attempt fencing, create idempotency, verified webhook ingestion/replay, tenant-fenced lifecycle compare-and-set with monotonic provider-event ordering, partial audit/failure updates that cannot overwrite lifecycle state, cancellation/expiry/reconciliation, exact artifact hashing, and immutable finalization. An expired create lease may be reclaimed only when the provider advertises atomic idempotency; otherwise a create with no confirmed request id must be reconciled/adopted before retry.\n\n### commissions — neutral financial core\n\n- **Earner**: `profileId`, `status` (`pending|active|suspended`), `payoutMethod` (`bank_transfer|check|paypal|credit|other`), `payoutThresholdCents`, `payoutScheduleKey` (open string: `manual`, `monthly`, …), `currency`, `metadata`.\n- **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`.\n- **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`).\n- **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()`.\n- **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).\n- **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. Existing adjustment schemas and legacy direct creates remain unchanged. Earned/paid Commissions are never rewritten — adjustments append to them.\n- **Payable balance**: computed, not stored — `CommissionBalanceService` sums payable Commissions plus unsettled Adjustments per Earner/currency.\n- **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.\n- **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).\n- **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.\n\n### crm\n\n- **SalesRepresentative**: role model (`profileId`, `earnerId`, `status`).\n- **Lead**: identified prospect with owner assignment, generic acquisition source (`sourceKind`/`sourceId`), preserved `acquisitionContext` JSON, and audited merge (`mergedIntoId`; merges preserve activity + acquisition history on both sides).\n- **PipelineDefinition / PipelineStage**: configurable ordered stages with default `new → qualified → discovery → proposal → negotiation → closed_won | closed_lost` (seeded via `ensureDefaultPipeline()`); stages carry `probability` and `isWon`/`isLost` terminal flags.\n- **Opportunity**: qualified engagement — owner, pipeline + stage, `expectedValueCents`, `probability`, `expectedCloseAt`, outcome. Stage movement validated against the pipeline; terminal stages set `won|lost` status.\n- **SalesActivity**: activity/next-action trail for Leads and Opportunities (`subjectKind`/`subjectId`), also the audit trail for assignment, qualification, merges, and stage movement.\n- **OpportunityConversion**: idempotent conversion links (`targetKind`/`targetId` — client, project, contract, subscription, …) with a composite natural key. CRM never creates downstream records itself and never mutates referral or commission state.\n\n### referrals\n\n- **Referrer**: role model (`profileId`, `earnerId`, `status`).\n- **ReferralProgram**: program defaults — default commission plan key, default attribution policy key, eligibility defaults.\n- **AttributionPolicy**: versioned `(tenant_id, policy_key, version)` policy (per-tenant keys) — attribution `windowDays`, credit mode (`first_touch|last_touch|assigned|split`), split shares, self-referral/existing-client eligibility, eligible services/campaigns/regions, conflict behavior. Immutable once active; amendments bump `version`.\n- **ReferralLink**: shareable link/code per Referrer+Program. Codes are crypto-random and uniqueness-checked. `ReferralLinkCollection.recordClick()` transactionally creates one immutable touch plus one counter increment behind a caller replay key. Exact retries return the original touch; changed link/subject/time/evidence intent raises `ReferralClickReplayConflictError`. Replay comparison uses the immutable operation/touch snapshot, so later mutable link edits do not invalidate the retry; the result carries the current link and original touch evidence. The exact canonical persisted evidence JSON, after Sales overwrites `code`, `linkId`, and `targetUrl`, is bounded to 4096 UTF-8 bytes by default (`maxEvidenceBytes` customizes it).\n- **ReferralTouch**: immutable attribution evidence (`click|code_entry|manual_assignment|partner_entry`) with subject hints and evidence JSON.\n- **Referral**: the introduction — generic qualifying target (`targetKind`/`targetId`: lead, opportunity, client, project, subscription, …), resolved policy version, credit fraction (splits create sibling Referrals sharing `splitGroupId`), lifecycle `pending → attributed → qualified | disqualified | expired | under_review`.\n- **AttributionException**: conflict review queue. Conclusive policy resolves automatically; ambiguity creates an exception; overrides require a `resolutionReason` and are audited.\n- **ReferralAgreement**: versioned per-Referrer terms binding — pins `commissionPlanKey`/`planVersion`, effective dating, and an immutable `ExecutedAgreement` before activation. Amendments are fresh unsigned drafts and never inherit execution evidence.\n- **ReferralTermSnapshot**: immutable at qualification — freezes agreement/plan/policy version refs plus the calculation inputs needed to reproduce every later earning.\n- **Services**: `ReferralAgreementExecutionService` binds generated Referral Agreement versions to the generic execution service and activates/supersedes them transactionally with future-effective amendment support; `AttributionService`, `ReferralQualificationService`, and `ReferralCommissionService` retain their existing attribution/qualification/earning responsibilities.\n\n### svelte\n\nProps-driven presentational components (no data fetching, no model-class imports, Provider-free smrt-ui primitives, `--smrt-*` tokens only): CRM — `SalesDashboard`, `LeadList`, `OpportunityBoard`, `OpportunityDetail`; referrer portal — `ReferralLinkManager`, `ReferralStatusList`, `ReferrerEarningsSummary`, `CommissionBreakdown` (trace-explained amounts), `PayoutHistoryList`, `ExecutedAgreementsList`; operator — `AttributionConflictQueue` (award editor + required resolution reason), `PayoutBatchReview`, `CommissionExpenseSummary` (explicitly distinct from client invoices). Monetary props stay integer cents; `format.ts` converts at render. View-model prop types are exported interfaces (never inline intersected generics in `$props()`); pure helpers (dashboard math, award validation mirroring the service, payout action gating) are unit-tested while components are svelte-check-gated.\n\n## Currency\n\n**All monetary fields are integer cents** with `*Cents` suffixes; rates are decimal (`0`–`1`). Rounding happens once per calculation step via `roundCents()` (half-away-from-zero) and every Commission stores its `calculationTrace` so amounts are reproducible. Convert at display/commerce boundaries with `centsToAmount()`/`amountToCents()`.\n\n## Tenancy\n\nBusiness/domain models are generally `@TenantScoped({ mode: 'optional' })` with `@tenantId({ nullable: true })`. This deliberately departs from legacy smrt-affiliates (which was cross-tenant by design for ad networks): sales programs, earners, and payouts are tenant-owned, while `tenantId: null` remains available for intentional global/operator-level rows. Immutable tenant-bound execution evidence (`AgreementExecution`, `AgreementExecutionEvent`, `ExecutedAgreement`) and private orchestration fences (`CommissionAdjustmentOperation`) instead use required tenancy with a non-null owner; never weaken those rows to optional tenancy.\n\n## Cross-package references (plain strings)\n\n`profileId` → smrt-profiles Profile; `invoiceId` (CommissionPayout) → smrt-commerce Invoice; agreement artifacts → smrt-assets Asset ids. No static imports of unrelated sibling domain packages.\n\n## smrt-affiliates migration\n\n`@happyvertical/smrt-affiliates` is now a deprecated compatibility package that re-exports this package's commissions core under the legacy names (`Partner` → `Earner`, `Payout` → `CommissionPayout`, `Commission`, collections, enums) with `@deprecated` guidance and **no duplicate persistence model**. The data/API mapping lives in `packages/affiliates/MIGRATION.md`.\n\n## Gotchas\n\n- **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.\n- **Versioned terms are rows, not edits**: CommissionPlan / AttributionPolicy / ReferralAgreement amendments insert `version + 1`; active versions are save-guarded immutable.\n- **Idempotency is dedupeKey-based**: EarningEvent, Commission, and CommissionPayout carry natural keys (`conflictColumns`) — retried ingestion/settlement upserts instead of duplicating.\n- **Adjustments never rewrite**: correcting an earned/paid Commission means appending a CommissionAdjustment, not editing the Commission.\n- **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.\n- **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.\n- **CommissionPayout, not Payout**: avoids the pre-existing global table-name collision between commerce `Payout` and legacy affiliates `Payout` (`payouts`).\n- **Table names are global**: new models were named to avoid collisions across packages (`commission_payouts`, `sales_activities`, `attribution_policies`, …).\n- **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`.\n- **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.\n- **`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.\n- **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.\n- **`sweepClearing` treats `clearingEndsAt: null` as immediately sweepable** (no clearing configured ⇒ nothing to wait for).\n- **Agreement freeze scope**: activating a ReferralAgreement requires and freezes its execution/evidence refs along with its commercial terms. `effectiveTo` remains writable for explicit end-dating; signed bytes, hashes, signer evidence, and audit trail exist only on immutable ExecutedAgreement/Asset records.\n- **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.\n- **Attribution resolution is single-writer per (target, program)**: `resolve()` is idempotent against PERSISTED state, but two workers resolving the same target concurrently can both pass the existence check and create duplicate credit — the collection layer has no cross-row transaction (the same stance as payout batching, which relies on disjoint scopes for concurrency). Run intake resolution serially per target (it naturally is, in a request handler); duplicates are visible in the portal and correctable via `override()`.\n- **Click retries reuse one key**: pass the exact same non-empty, well-formed-Unicode `recordClick.idempotencyKey` (maximum 256 UTF-8 bytes) on transport/database retry. Omitting it remains source-compatible but creates and returns a one-shot UUID; it cannot deduplicate a later independent invocation. `maxEvidenceBytes` guards creation; changing it cannot turn an already-committed exact replay into failure. Replay validation is against the immutable operation/touch snapshot, not mutable current link fields: later link edits preserve exact replay, the result link is current, and the touch evidence is the original snapshot. The private optional-tenant `ReferralClickOperation` table is the serialization fence and must be included in schema migration. Never pre-bound caller evidence: Sales owns the authoritative final-envelope byte check.\n- **`ObjectRegistry.getConfig(X)` needs the class module imported** (decorator side effects) — manifest-only registration doesn't carry api/mcp/conflictColumns; tests asserting surface configs need a side-effect import of the module barrel.\n"
6635
+ "agentDoc": "# @happyvertical/smrt-sales\n\nModular sales: provider-neutral agreement execution, CRM, referral intake, a neutral commissions financial core, and reusable Svelte surfaces. One installable package with distinct subpath exports:\n\n- `@happyvertical/smrt-sales/agreements`\n- `@happyvertical/smrt-sales/crm`\n- `@happyvertical/smrt-sales/referrals`\n- `@happyvertical/smrt-sales/commissions`\n- `@happyvertical/smrt-sales/svelte`\n\nThe root export re-exports every TS module. `agreements` depends on the provider-neutral `@happyvertical/signatures` contract and `smrt-assets`; provider credentials stay in the injected SDK adapter/secret store. `referrals` binds its versioned terms to `agreements`.\n\n## Validation\n\nRun `pnpm --filter @happyvertical/smrt-sales test` and `pnpm --filter @happyvertical/smrt-sales typecheck` for package changes. PostgreSQL-sensitive changes must also run `pnpm --filter @happyvertical/smrt-sales test:postgres`; the command uses the repository's disposable PostgreSQL harness and is registered in the PostgreSQL CI shard.\n\n## Roles vs. money\n\nReferrers and Sales Representatives are **distinct roles** and stay that way. Both connect to money through one neutral financial account:\n\n- **Earner** (commissions): payout identity — method, threshold, currency, status. Referenced by every Commission and CommissionPayout.\n- **SalesRepresentative** (crm) and **Referrer** (referrals): role models, each holding `profileId` (cross-package string ref to smrt-profiles) and `earnerId`.\n\n## Modules\n\n### agreements — verified execution evidence\n\n- **AgreementExecution**: private required-tenant orchestration state keyed by `(tenant_id, idempotency_key)`, with a collision-checked provider request/status, an expiring create-operation lease, source version/hash/size/Asset, intended signer identity/auth method, cancellation/expiry, reconciliation, exact staged artifact metadata, and secret-store references only.\n- **AgreementExecutionEvent**: private append-only evidence for verified webhooks and operator/provider operations. Provider events are deduped by tenant/provider replay key; explicit occurrence/first-receipt timestamps and the exact payload/hash are retained, while signature headers are never stored. A later receipt time for the same verified provider event is an idempotent replay. Stale, regressive, or conflicting terminal events are audited without regressing lifecycle state or creating executed evidence.\n- **ExecutedAgreement**: immutable read-only source version plus signed-document and audit-trail Asset ids/hashes/sizes/filenames/media types, completed signer evidence, acceptance/effective dates, and supersession reference. Amendments create new records.\n- **AgreementExecutionService**: accepts an SDK `SignatureProvider` and shared `AssetRuntimeLike`; enforces ambient tenant equality, expiring remote-attempt fencing, create idempotency, verified webhook ingestion/replay, tenant-fenced lifecycle compare-and-set with monotonic provider-event ordering, partial audit/failure updates that cannot overwrite lifecycle state, cancellation/expiry/reconciliation, exact artifact hashing, and immutable finalization. An expired create lease may be reclaimed only when the provider advertises atomic idempotency; otherwise a create with no confirmed request id must be reconciled/adopted before retry.\n\n### commissions — neutral financial core\n\n- **Earner**: `profileId`, `status` (`pending|active|suspended`), `payoutMethod` (`bank_transfer|check|paypal|credit|other`), `payoutThresholdCents`, `payoutScheduleKey` (open string: `manual`, `monthly`, …), `currency`, `metadata`.\n- **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`.\n- **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`).\n- **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()`.\n- **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).\n- **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. Existing adjustment schemas and legacy direct creates remain unchanged. Earned/paid Commissions are never rewritten — adjustments append to them.\n- **Payable balance**: computed, not stored — `CommissionBalanceService` sums payable Commissions plus unsettled Adjustments per Earner/currency.\n- **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.\n- **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).\n- **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.\n\n### crm\n\n- **SalesRepresentative**: role model (`profileId`, `earnerId`, `status`).\n- **Lead**: identified prospect with owner assignment, generic acquisition source (`sourceKind`/`sourceId`), preserved `acquisitionContext` JSON, and audited merge (`mergedIntoId`; merges preserve activity + acquisition history on both sides).\n- **PipelineDefinition / PipelineStage**: configurable ordered stages with default `new → qualified → discovery → proposal → negotiation → closed_won | closed_lost` (seeded via `ensureDefaultPipeline()`); stages carry `probability` and `isWon`/`isLost` terminal flags.\n- **Opportunity**: qualified engagement — owner, pipeline + stage, `expectedValueCents`, `probability`, `expectedCloseAt`, outcome. Stage movement validated against the pipeline; terminal stages set `won|lost` status.\n- **SalesActivity**: activity/next-action trail for Leads and Opportunities (`subjectKind`/`subjectId`), also the audit trail for assignment, qualification, merges, and stage movement.\n- **OpportunityConversion**: idempotent conversion links (`targetKind`/`targetId` — client, project, contract, subscription, …) with a composite natural key. CRM never creates downstream records itself and never mutates referral or commission state.\n\n### referrals\n\n- **Referrer**: role model (`profileId`, `earnerId`, `status`).\n- **ReferralProgram**: program defaults — default commission plan key, default attribution policy key, eligibility defaults.\n- **AttributionPolicy**: versioned `(tenant_id, policy_key, version)` policy (per-tenant keys) — attribution `windowDays`, credit mode (`first_touch|last_touch|assigned|split`), split shares, self-referral/existing-client eligibility, eligible services/campaigns/regions, conflict behavior. Immutable once active; amendments bump `version`.\n- **ReferralLink**: shareable link/code per Referrer+Program. Codes are crypto-random and uniqueness-checked. `ReferralLinkCollection.recordClick()` transactionally creates one immutable touch plus one counter increment behind a caller replay key. Exact retries return the original touch; changed link/subject/time/evidence intent raises `ReferralClickReplayConflictError`. Replay comparison uses the immutable operation/touch snapshot, so later mutable link edits do not invalidate the retry; the result carries the current link and original touch evidence. The exact canonical persisted evidence JSON, after Sales overwrites `code`, `linkId`, and `targetUrl`, is bounded to 4096 UTF-8 bytes by default (`maxEvidenceBytes` customizes it). By default the click self-transacts and rehydrates results after commit; inside a caller's open transaction it must participate instead — pass the transaction database as `RecordClickInput.transaction`, or call it on a collection bound to that transaction, and the click joins the caller's atomicity with results bound to that transaction (#2083).\n- **ReferralTouch**: immutable attribution evidence (`click|code_entry|manual_assignment|partner_entry`) with subject hints and evidence JSON.\n- **Referral**: the introduction — generic qualifying target (`targetKind`/`targetId`: lead, opportunity, client, project, subscription, …), resolved policy version, credit fraction (splits create sibling Referrals sharing `splitGroupId`), lifecycle `pending → attributed → qualified | disqualified | expired | under_review`.\n- **AttributionException**: conflict review queue. Conclusive policy resolves automatically; ambiguity creates an exception; overrides require a `resolutionReason` and are audited.\n- **ReferralAgreement**: versioned per-Referrer terms binding — pins `commissionPlanKey`/`planVersion`, effective dating, and an immutable `ExecutedAgreement` before activation. Amendments are fresh unsigned drafts and never inherit execution evidence.\n- **ReferralTermSnapshot**: immutable at qualification — freezes agreement/plan/policy version refs plus the calculation inputs needed to reproduce every later earning.\n- **Services**: `ReferralAgreementExecutionService` binds generated Referral Agreement versions to the generic execution service and activates/supersedes them transactionally with future-effective amendment support; `AttributionService`, `ReferralQualificationService`, and `ReferralCommissionService` retain their existing attribution/qualification/earning responsibilities.\n\n### svelte\n\nProps-driven presentational components (no data fetching, no model-class imports, Provider-free smrt-ui primitives, `--smrt-*` tokens only): CRM — `SalesDashboard`, `LeadList`, `OpportunityBoard`, `OpportunityDetail`; referrer portal — `ReferralLinkManager`, `ReferralStatusList`, `ReferrerEarningsSummary`, `CommissionBreakdown` (trace-explained amounts), `PayoutHistoryList`, `ExecutedAgreementsList`; operator — `AttributionConflictQueue` (award editor + required resolution reason), `PayoutBatchReview`, `CommissionExpenseSummary` (explicitly distinct from client invoices). Monetary props stay integer cents; `format.ts` converts at render. View-model prop types are exported interfaces (never inline intersected generics in `$props()`); pure helpers (dashboard math, award validation mirroring the service, payout action gating) are unit-tested while components are svelte-check-gated.\n\n## Currency\n\n**All monetary fields are integer cents** with `*Cents` suffixes; rates are decimal (`0`–`1`). Rounding happens once per calculation step via `roundCents()` (half-away-from-zero) and every Commission stores its `calculationTrace` so amounts are reproducible. Convert at display/commerce boundaries with `centsToAmount()`/`amountToCents()`.\n\n## Tenancy\n\nBusiness/domain models are generally `@TenantScoped({ mode: 'optional' })` with `@tenantId({ nullable: true })`. This deliberately departs from legacy smrt-affiliates (which was cross-tenant by design for ad networks): sales programs, earners, and payouts are tenant-owned, while `tenantId: null` remains available for intentional global/operator-level rows. Immutable tenant-bound execution evidence (`AgreementExecution`, `AgreementExecutionEvent`, `ExecutedAgreement`) and private orchestration fences (`CommissionAdjustmentOperation`) instead use required tenancy with a non-null owner; never weaken those rows to optional tenancy.\n\n## Cross-package references (plain strings)\n\n`profileId` → smrt-profiles Profile; `invoiceId` (CommissionPayout) → smrt-commerce Invoice; agreement artifacts → smrt-assets Asset ids. No static imports of unrelated sibling domain packages.\n\n## smrt-affiliates migration\n\n`@happyvertical/smrt-affiliates` is now a deprecated compatibility package that re-exports this package's commissions core under the legacy names (`Partner` → `Earner`, `Payout` → `CommissionPayout`, `Commission`, collections, enums) with `@deprecated` guidance and **no duplicate persistence model**. The data/API mapping lives in `packages/affiliates/MIGRATION.md`.\n\n## Gotchas\n\n- **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.\n- **Versioned terms are rows, not edits**: CommissionPlan / AttributionPolicy / ReferralAgreement amendments insert `version + 1`; active versions are save-guarded immutable.\n- **Idempotency is dedupeKey-based**: EarningEvent, Commission, and CommissionPayout carry natural keys (`conflictColumns`) — retried ingestion/settlement upserts instead of duplicating.\n- **Adjustments never rewrite**: correcting an earned/paid Commission means appending a CommissionAdjustment, not editing the Commission.\n- **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.\n- **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.\n- **CommissionPayout, not Payout**: avoids the pre-existing global table-name collision between commerce `Payout` and legacy affiliates `Payout` (`payouts`).\n- **Table names are global**: new models were named to avoid collisions across packages (`commission_payouts`, `sales_activities`, `attribution_policies`, …).\n- **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`.\n- **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.\n- **`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.\n- **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.\n- **`sweepClearing` treats `clearingEndsAt: null` as immediately sweepable** (no clearing configured ⇒ nothing to wait for).\n- **Agreement freeze scope**: activating a ReferralAgreement requires and freezes its execution/evidence refs along with its commercial terms. `effectiveTo` remains writable for explicit end-dating; signed bytes, hashes, signer evidence, and audit trail exist only on immutable ExecutedAgreement/Asset records.\n- **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.\n- **Attribution resolution is single-writer per (target, program)**: `resolve()` is idempotent against PERSISTED state, but two workers resolving the same target concurrently can both pass the existence check and create duplicate credit — the collection layer has no cross-row transaction (the same stance as payout batching, which relies on disjoint scopes for concurrency). Run intake resolution serially per target (it naturally is, in a request handler); duplicates are visible in the portal and correctable via `override()`.\n- **recordClick inside your transaction participates, never nests**: a nested adapter `transaction()` takes an independent pooled connection (happyvertical/sdk#1108) — it deadlocks undetectably on locks the caller's transaction holds (PostgreSQL sees a promise-wait, not a lock-wait) and refuses caller-created uncommitted links as `unknown_code`. Pass the caller's transaction database as `RecordClickInput.transaction` or bind the collection to it (`{ db: tx, _reuseInitializedDb: true, _deferRuntimeInitialization: true }` — detected and honored automatically); a pool-level database passed as `transaction` is refused with typed reason `invalid_transaction`. Participating results are bound to the caller's transaction — carry ids across the commit boundary; the pool-bound default still self-transacts and rehydrates after commit.\n- **Click retries reuse one key**: pass the exact same non-empty, well-formed-Unicode `recordClick.idempotencyKey` (maximum 256 UTF-8 bytes) on transport/database retry. Omitting it remains source-compatible but creates and returns a one-shot UUID; it cannot deduplicate a later independent invocation. `maxEvidenceBytes` guards creation; changing it cannot turn an already-committed exact replay into failure. Replay validation is against the immutable operation/touch snapshot, not mutable current link fields: later link edits preserve exact replay, the result link is current, and the touch evidence is the original snapshot. The private optional-tenant `ReferralClickOperation` table is the serialization fence and must be included in schema migration. Never pre-bound caller evidence: Sales owns the authoritative final-envelope byte check.\n- **`ObjectRegistry.getConfig(X)` needs the class module imported** (decorator side effects) — manifest-only registration doesn't carry api/mcp/conflictColumns; tests asserting surface configs need a side-effect import of the module barrel.\n"
6636
6636
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@happyvertical/smrt-sales",
3
- "version": "0.40.19",
3
+ "version": "0.40.21",
4
4
  "description": "Modular sales for the SMRT framework: agreement execution, CRM, referral intake, neutral commissions, and reusable Svelte surfaces",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -42,10 +42,10 @@
42
42
  "dependencies": {
43
43
  "@happyvertical/signatures": "^0.80.2",
44
44
  "@happyvertical/sql": "^0.80.2",
45
- "@happyvertical/smrt-assets": "0.40.19",
46
- "@happyvertical/smrt-core": "0.40.19",
47
- "@happyvertical/smrt-ui": "0.40.19",
48
- "@happyvertical/smrt-tenancy": "0.40.19"
45
+ "@happyvertical/smrt-assets": "0.40.21",
46
+ "@happyvertical/smrt-tenancy": "0.40.21",
47
+ "@happyvertical/smrt-core": "0.40.21",
48
+ "@happyvertical/smrt-ui": "0.40.21"
49
49
  },
50
50
  "peerDependencies": {
51
51
  "svelte": "^5.56.4"
@@ -59,7 +59,7 @@
59
59
  "typescript": "5.9.3",
60
60
  "vite": "8.1.4",
61
61
  "vitest": "4.1.10",
62
- "@happyvertical/smrt-vitest": "0.40.19"
62
+ "@happyvertical/smrt-vitest": "0.40.21"
63
63
  },
64
64
  "smrtRawPrimitives": "strict",
65
65
  "keywords": [