@happyvertical/smrt-sales 0.60.12 → 0.60.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/AGENTS.md +1 -0
  2. package/README.md +10 -0
  3. package/agents/referrals.md +28 -1
  4. package/dist/agreements.js +1 -1
  5. package/dist/chunks/{__smrt-register__-DU-LsJ2Z.js → __smrt-register__-Djs_txHu.js} +2 -2
  6. package/dist/chunks/{__smrt-register__-DU-LsJ2Z.js.map → __smrt-register__-Djs_txHu.js.map} +1 -1
  7. package/dist/chunks/{referrals-DQaEehr8.js → referrals-STQ8kdIv.js} +674 -174
  8. package/dist/chunks/referrals-STQ8kdIv.js.map +1 -0
  9. package/dist/commissions.js +1 -1
  10. package/dist/crm.js +1 -1
  11. package/dist/index.js +3 -3
  12. package/dist/manifest.json +530 -2
  13. package/dist/referrals/collections/AttributionExceptionCollection.d.ts +1 -1
  14. package/dist/referrals/collections/AttributionExceptionCollection.d.ts.map +1 -1
  15. package/dist/referrals/collections/ReferrerIdentifierCollection.d.ts +20 -0
  16. package/dist/referrals/collections/ReferrerIdentifierCollection.d.ts.map +1 -0
  17. package/dist/referrals/index.d.ts +3 -0
  18. package/dist/referrals/index.d.ts.map +1 -1
  19. package/dist/referrals/models/AttributionException.d.ts +4 -3
  20. package/dist/referrals/models/AttributionException.d.ts.map +1 -1
  21. package/dist/referrals/models/ReferralTouch.d.ts +4 -3
  22. package/dist/referrals/models/ReferralTouch.d.ts.map +1 -1
  23. package/dist/referrals/models/ReferrerIdentifier.d.ts +24 -0
  24. package/dist/referrals/models/ReferrerIdentifier.d.ts.map +1 -0
  25. package/dist/referrals/nomination-identity.d.ts +3 -0
  26. package/dist/referrals/nomination-identity.d.ts.map +1 -0
  27. package/dist/referrals/services/AttributionService.d.ts +5 -3
  28. package/dist/referrals/services/AttributionService.d.ts.map +1 -1
  29. package/dist/referrals/services/ReferralAgreementExecutionService.d.ts +1 -1
  30. package/dist/referrals/services/ReferralAgreementExecutionService.d.ts.map +1 -1
  31. package/dist/referrals/services/ReferralNominationResolver.d.ts +55 -0
  32. package/dist/referrals/services/ReferralNominationResolver.d.ts.map +1 -0
  33. package/dist/referrals/types.d.ts +21 -2
  34. package/dist/referrals/types.d.ts.map +1 -1
  35. package/dist/referrals.js +3 -3
  36. package/dist/smrt-knowledge.json +285 -11
  37. package/dist/smrt-knowledge.okf.md +6 -2
  38. package/package.json +8 -8
  39. package/dist/chunks/referrals-DQaEehr8.js.map +0 -1
@@ -3,17 +3,17 @@
3
3
  "sensitiveFieldsExcluded": true,
4
4
  "generatedAt": "1970-01-01T00:00:00.000Z",
5
5
  "packageName": "@happyvertical/smrt-sales",
6
- "packageVersion": "0.60.12",
6
+ "packageVersion": "0.60.14",
7
7
  "sourceManifestPath": "dist/manifest.json",
8
8
  "agentDocPath": "AGENTS.md",
9
9
  "sourceHashes": {
10
- "manifest": "bc70c4e75d430e023e95cb13996018aac50c8af06821307cf9ff4530246002bc",
11
- "packageJson": "ad7d64849c257645f7502af8d94d28142c8959d9c9945921e9756ce20113d7de",
12
- "agents": "50157c8c1d2f3ef2d03dcb583ff0ade2048d497456ce2b9395d4721ee2e63bd2",
10
+ "manifest": "77613d03be0b9873904aa7a855f26d813ccd06c16dbc86b09bad87fe322595ae",
11
+ "packageJson": "8c8e097cbb80e65ab5fcb20fcfcba8695a1d8ecab93a421526d0bd67f57a208e",
12
+ "agents": "114b0bf794d90cbcff545b52947341d24802cbe4782ccf9003592120bb6f1103",
13
13
  "moduleDoc:agents/agreements.md": "86609271b56633c1b6a3d9b1905a200cad1cb15de54adb8ca9f1200f6af8b9ce",
14
14
  "moduleDoc:agents/commissions.md": "476439bdc831649302441f53394d9dada0910d15602850ab496a41ad8183c3b0",
15
15
  "moduleDoc:agents/crm.md": "074eff9e3ca7ae6d86e65a1d29ac7b9b555b719b3801918678b15df7538f99e0",
16
- "moduleDoc:agents/referrals.md": "ef48c88e63155e3d08b9003f4643bc66ebb1942f1fb713252dc042ddcaad38e5",
16
+ "moduleDoc:agents/referrals.md": "167327a5cb33f5fe9a867c3a57fbbd5bfb2d6f8ac2ad3b0242c5458ebfc8a2d5",
17
17
  "moduleDoc:agents/svelte.md": "75e26f56185b5c2ce3895d9969522405131efcee4af4f5aaa66232a26fb27c8b"
18
18
  },
19
19
  "exports": [
@@ -7966,7 +7966,8 @@
7966
7966
  "params": [
7967
7967
  "targetKind: string",
7968
7968
  "targetId: string",
7969
- "programId: string"
7969
+ "programId: string",
7970
+ "tenantId?: string | null"
7970
7971
  ],
7971
7972
  "returns": "Promise<AttributionException | null>"
7972
7973
  }
@@ -8768,6 +8769,44 @@
8768
8769
  "tags": [],
8769
8770
  "risks": []
8770
8771
  },
8772
+ {
8773
+ "name": "ReferrerIdentifierCollection",
8774
+ "qualifiedName": "@happyvertical/smrt-sales:ReferrerIdentifierCollection",
8775
+ "collection": "referreridentifiers",
8776
+ "tableName": "referrer_identifiers",
8777
+ "packageName": "@happyvertical/smrt-sales",
8778
+ "extends": "SmrtCollection",
8779
+ "fields": [],
8780
+ "relationships": [],
8781
+ "methods": [
8782
+ "register"
8783
+ ],
8784
+ "methodSignatures": [
8785
+ {
8786
+ "name": "register",
8787
+ "async": true,
8788
+ "params": [
8789
+ "input: RegisterReferrerIdentifierInput"
8790
+ ],
8791
+ "returns": "Promise<ReferrerIdentifier>"
8792
+ }
8793
+ ],
8794
+ "surfaces": [],
8795
+ "withheldSurfaces": [
8796
+ {
8797
+ "kind": "api",
8798
+ "operation": "register",
8799
+ "code": "not-included",
8800
+ "reason": "not listed in api.include",
8801
+ "objectName": "@happyvertical/smrt-sales:ReferrerIdentifierCollection"
8802
+ }
8803
+ ],
8804
+ "relationshipFeatures": [
8805
+ "uuidColumns"
8806
+ ],
8807
+ "tags": [],
8808
+ "risks": []
8809
+ },
8771
8810
  {
8772
8811
  "name": "AttributionException",
8773
8812
  "qualifiedName": "@happyvertical/smrt-sales:AttributionException",
@@ -11720,6 +11759,213 @@
11720
11759
  ],
11721
11760
  "tags": [],
11722
11761
  "risks": []
11762
+ },
11763
+ {
11764
+ "name": "ReferrerIdentifier",
11765
+ "qualifiedName": "@happyvertical/smrt-sales:ReferrerIdentifier",
11766
+ "collection": "referreridentifiers",
11767
+ "description": "A tenant's verified spelling, code, address, or other alias for a referrer.",
11768
+ "tableName": "referrer_identifiers",
11769
+ "packageName": "@happyvertical/smrt-sales",
11770
+ "extends": "SmrtObject",
11771
+ "fields": [
11772
+ {
11773
+ "name": "tenantId",
11774
+ "type": "text",
11775
+ "required": false,
11776
+ "columnType": "UUID"
11777
+ },
11778
+ {
11779
+ "name": "referrerId",
11780
+ "type": "foreignKey",
11781
+ "required": true,
11782
+ "related": "Referrer",
11783
+ "columnType": "UUID"
11784
+ },
11785
+ {
11786
+ "name": "programId",
11787
+ "type": "foreignKey",
11788
+ "required": false,
11789
+ "related": "ReferralProgram",
11790
+ "columnType": "UUID"
11791
+ },
11792
+ {
11793
+ "name": "kind",
11794
+ "type": "text",
11795
+ "required": true,
11796
+ "columnType": "TEXT",
11797
+ "default": ""
11798
+ },
11799
+ {
11800
+ "name": "value",
11801
+ "type": "text",
11802
+ "required": true,
11803
+ "columnType": "TEXT",
11804
+ "default": ""
11805
+ },
11806
+ {
11807
+ "name": "normalizedValue",
11808
+ "type": "text",
11809
+ "required": true,
11810
+ "columnType": "TEXT",
11811
+ "default": ""
11812
+ },
11813
+ {
11814
+ "name": "status",
11815
+ "type": "text",
11816
+ "required": false,
11817
+ "columnType": "TEXT",
11818
+ "default": "active"
11819
+ },
11820
+ {
11821
+ "name": "metadata",
11822
+ "type": "text",
11823
+ "required": false,
11824
+ "columnType": "TEXT",
11825
+ "default": "{}"
11826
+ }
11827
+ ],
11828
+ "relationships": [
11829
+ {
11830
+ "name": "referrerId",
11831
+ "type": "foreignKey",
11832
+ "required": true,
11833
+ "related": "Referrer",
11834
+ "columnType": "UUID"
11835
+ },
11836
+ {
11837
+ "name": "programId",
11838
+ "type": "foreignKey",
11839
+ "required": false,
11840
+ "related": "ReferralProgram",
11841
+ "columnType": "UUID"
11842
+ }
11843
+ ],
11844
+ "methods": [
11845
+ "delete",
11846
+ "disable",
11847
+ "getMetadata",
11848
+ "isActive",
11849
+ "save",
11850
+ "setMetadata"
11851
+ ],
11852
+ "methodSignatures": [
11853
+ {
11854
+ "name": "delete",
11855
+ "async": true,
11856
+ "returns": "Promise<void>"
11857
+ },
11858
+ {
11859
+ "name": "disable",
11860
+ "returns": "void"
11861
+ },
11862
+ {
11863
+ "name": "getMetadata",
11864
+ "returns": "Record<string, unknown>"
11865
+ },
11866
+ {
11867
+ "name": "isActive",
11868
+ "returns": "boolean"
11869
+ },
11870
+ {
11871
+ "name": "save",
11872
+ "async": true,
11873
+ "params": [
11874
+ "options?: SmrtSaveOptions"
11875
+ ],
11876
+ "returns": "Promise<this>"
11877
+ },
11878
+ {
11879
+ "name": "setMetadata",
11880
+ "params": [
11881
+ "metadata: Record<string, unknown>"
11882
+ ],
11883
+ "returns": "void"
11884
+ }
11885
+ ],
11886
+ "tenant": {
11887
+ "scoped": true,
11888
+ "mode": "optional",
11889
+ "field": "tenantId"
11890
+ },
11891
+ "conflictColumns": [
11892
+ "tenant_id",
11893
+ "kind",
11894
+ "normalized_value"
11895
+ ],
11896
+ "surfaces": [
11897
+ {
11898
+ "kind": "api",
11899
+ "name": "referreridentifiers.list",
11900
+ "operation": "list",
11901
+ "objectName": "@happyvertical/smrt-sales:ReferrerIdentifier",
11902
+ "path": "/referreridentifiers",
11903
+ "method": "GET"
11904
+ },
11905
+ {
11906
+ "kind": "api",
11907
+ "name": "referreridentifiers.get",
11908
+ "operation": "get",
11909
+ "objectName": "@happyvertical/smrt-sales:ReferrerIdentifier",
11910
+ "path": "/referreridentifiers/[id]",
11911
+ "method": "GET"
11912
+ },
11913
+ {
11914
+ "kind": "mcp",
11915
+ "name": "referreridentifier_list",
11916
+ "operation": "list",
11917
+ "objectName": "@happyvertical/smrt-sales:ReferrerIdentifier"
11918
+ },
11919
+ {
11920
+ "kind": "mcp",
11921
+ "name": "referreridentifier_get",
11922
+ "operation": "get",
11923
+ "objectName": "@happyvertical/smrt-sales:ReferrerIdentifier"
11924
+ }
11925
+ ],
11926
+ "withheldSurfaces": [
11927
+ {
11928
+ "kind": "api",
11929
+ "operation": "disable",
11930
+ "code": "not-included",
11931
+ "reason": "not listed in api.include",
11932
+ "objectName": "@happyvertical/smrt-sales:ReferrerIdentifier"
11933
+ },
11934
+ {
11935
+ "kind": "api",
11936
+ "operation": "getMetadata",
11937
+ "code": "not-included",
11938
+ "reason": "not listed in api.include",
11939
+ "objectName": "@happyvertical/smrt-sales:ReferrerIdentifier"
11940
+ },
11941
+ {
11942
+ "kind": "api",
11943
+ "operation": "isActive",
11944
+ "code": "not-included",
11945
+ "reason": "not listed in api.include",
11946
+ "objectName": "@happyvertical/smrt-sales:ReferrerIdentifier"
11947
+ },
11948
+ {
11949
+ "kind": "api",
11950
+ "operation": "save",
11951
+ "code": "lifecycle-method",
11952
+ "reason": "`save` is a framework lifecycle method, not a distinct operation",
11953
+ "objectName": "@happyvertical/smrt-sales:ReferrerIdentifier"
11954
+ },
11955
+ {
11956
+ "kind": "api",
11957
+ "operation": "setMetadata",
11958
+ "code": "not-included",
11959
+ "reason": "not listed in api.include",
11960
+ "objectName": "@happyvertical/smrt-sales:ReferrerIdentifier"
11961
+ }
11962
+ ],
11963
+ "relationshipFeatures": [
11964
+ "foreignKey",
11965
+ "uuidColumns"
11966
+ ],
11967
+ "tags": [],
11968
+ "risks": []
11723
11969
  }
11724
11970
  ],
11725
11971
  "surfaces": [
@@ -13990,18 +14236,46 @@
13990
14236
  "name": "referrer_create",
13991
14237
  "operation": "create",
13992
14238
  "objectName": "@happyvertical/smrt-sales:Referrer"
14239
+ },
14240
+ {
14241
+ "kind": "api",
14242
+ "name": "referreridentifiers.list",
14243
+ "operation": "list",
14244
+ "objectName": "@happyvertical/smrt-sales:ReferrerIdentifier",
14245
+ "path": "/referreridentifiers",
14246
+ "method": "GET"
14247
+ },
14248
+ {
14249
+ "kind": "api",
14250
+ "name": "referreridentifiers.get",
14251
+ "operation": "get",
14252
+ "objectName": "@happyvertical/smrt-sales:ReferrerIdentifier",
14253
+ "path": "/referreridentifiers/[id]",
14254
+ "method": "GET"
14255
+ },
14256
+ {
14257
+ "kind": "mcp",
14258
+ "name": "referreridentifier_list",
14259
+ "operation": "list",
14260
+ "objectName": "@happyvertical/smrt-sales:ReferrerIdentifier"
14261
+ },
14262
+ {
14263
+ "kind": "mcp",
14264
+ "name": "referreridentifier_get",
14265
+ "operation": "get",
14266
+ "objectName": "@happyvertical/smrt-sales:ReferrerIdentifier"
13993
14267
  }
13994
14268
  ],
13995
14269
  "prompts": [],
13996
14270
  "relationshipsV2": {
13997
- "foreignKeyFields": 37,
14271
+ "foreignKeyFields": 39,
13998
14272
  "crossPackageRefFields": 14,
13999
14273
  "junctionCollections": 0,
14000
14274
  "hierarchicalObjects": 0,
14001
14275
  "polymorphicAssociations": 0,
14002
- "uuidColumns": 232
14276
+ "uuidColumns": 240
14003
14277
  },
14004
- "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\nPer-module semantics live in sibling module docs — read the one for the module\nyou are editing. This file keeps what holds in every module.\n\n| Module | Scope | Module doc |\n|---|---|---|\n| `agreements` | verified execution evidence — private orchestration state, append-only provider events, immutable executed agreements, and the provider-neutral execution service | [agents/agreements.md](agents/agreements.md) |\n| `commissions` | the neutral financial core — earners, versioned plans, earning events, commissions, adjustments, balances, and payout settlement | [agents/commissions.md](agents/commissions.md) |\n| `crm` | leads, configurable pipelines, opportunities, tenant-safe Lead follow-up, activity trail, and idempotent conversion links | [agents/crm.md](agents/crm.md) |\n| `referrals` | referrers, programs, versioned attribution policies, links/touches, referrals, exception review, and term snapshots | [agents/referrals.md](agents/referrals.md) |\n| `svelte` | props-driven presentational surfaces for CRM, the referrer portal, and operator review | [agents/svelte.md](agents/svelte.md) |\n\n## Currency\n\n**All monetary fields are integer cents** with `*Cents` suffixes; that scale is a Sales contract, not an implicit framework currency rule. Fresh PostgreSQL/DuckDB INTEGER columns are BIGINT, while JavaScript hydration rejects values outside the safe-integer range. 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- **Optional same-package foreign keys use null**: execution, supersession, earning-event, and payout references that are absent persist as `null`, never `''`; their physical database constraints remain enabled when a real id is present.\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, per tenant (#3305 D1)**: EarningEvent, Commission, and CommissionPayout are keyed `(tenant_id, dedupe_key|idempotency_key)`. Replay lookups (`findByDedupeKey`/`getOrCreateByDedupeKey`/`findByIdempotencyKey`) and the raw save guards resolve one owner (explicit `tenantId`, else context; neither → global rows); calculation/settlement pass the event's/earner's tenant because they run without a context; a foreign owner under a context fails closed, super-admin bypass included. Rollout: `db:migrate` adds the tenant-led uniques and drops the superseded ones in a writer-drained window; recovery is forward-only once tenants share a key.\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 validation includes interaction contracts**: intake and inbox components have runtime component tests; `typecheck` also runs `svelte-check` via `scripts/svelte-check-a11y.mjs`. Ship raw `.svelte` via `svelte-package`.\n- **Lead workflows stay generic**: call `LeadWorkflowService` for tenant-safe intake, audited follow-up, qualification, nonterminal Opportunity stage movement, and terminal closure with optional conversion links. Optional intake `profileId` is stored and fingerprinted but remains host-authorized. The service delegates CRM lifecycles to their owning collections; hosts supply authorization and create downstream records. `LeadCreateForm`, `LeadList`, and `LeadDetail` are props/callback only. See [agents/crm.md](agents/crm.md) for dedupe, retry, and inbox contracts.\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\n- **Governed sales use the owned service factory**: `SalesGovernanceService`\n accepts allowlisted PostgreSQL connection configuration only, owns its\n adapter and transaction executors, and guards private state/model writes.\n DuckDB support remains blocked on SDK #1452; SQLite is also rejected until\n same-process BUSY recovery is proven. Quote issue/sign always recheck\n current seller, host policy/inventory and exact finance approval; see\n [agents/crm.md](agents/crm.md#governed-sellers-quotes-and-canonical-advertiser-registration).\n\n- **Recipe `affiliates.referrals`** (`src/referrals/recipes.ts`, help in `src/referrals/referrals.recipe.md`): the affiliate feature for catalog hosts (referrers, programs, referrals, commissions, payouts). It lives here because `@happyvertical/smrt-affiliates` is a model-less shim and a recipe needs models of its own package. Fields it shows carry `@field({ description })` in plain words.\n",
14278
+ "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\nPer-module semantics live in sibling module docs — read the one for the module\nyou are editing. This file keeps what holds in every module.\n\n| Module | Scope | Module doc |\n|---|---|---|\n| `agreements` | verified execution evidence — private orchestration state, append-only provider events, immutable executed agreements, and the provider-neutral execution service | [agents/agreements.md](agents/agreements.md) |\n| `commissions` | the neutral financial core — earners, versioned plans, earning events, commissions, adjustments, balances, and payout settlement | [agents/commissions.md](agents/commissions.md) |\n| `crm` | leads, configurable pipelines, opportunities, tenant-safe Lead follow-up, activity trail, and idempotent conversion links | [agents/crm.md](agents/crm.md) |\n| `referrals` | referrers, programs, versioned attribution policies, links/touches, referrals, exception review, and term snapshots | [agents/referrals.md](agents/referrals.md) |\n| `svelte` | props-driven presentational surfaces for CRM, the referrer portal, and operator review | [agents/svelte.md](agents/svelte.md) |\n\n## Currency\n\n**All monetary fields are integer cents** with `*Cents` suffixes; that scale is a Sales contract, not an implicit framework currency rule. Fresh PostgreSQL/DuckDB INTEGER columns are BIGINT, while JavaScript hydration rejects values outside the safe-integer range. 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- **Optional same-package foreign keys use null**: execution, supersession, earning-event, and payout references that are absent persist as `null`, never `''`; their physical database constraints remain enabled when a real id is present.\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, per tenant (#3305 D1)**: EarningEvent, Commission, and CommissionPayout are keyed `(tenant_id, dedupe_key|idempotency_key)`. Replay lookups (`findByDedupeKey`/`getOrCreateByDedupeKey`/`findByIdempotencyKey`) and the raw save guards resolve one owner (explicit `tenantId`, else context; neither → global rows); calculation/settlement pass the event's/earner's tenant because they run without a context; a foreign owner under a context fails closed, super-admin bypass included. Rollout: `db:migrate` adds the tenant-led uniques and drops the superseded ones in a writer-drained window; recovery is forward-only once tenants share a key.\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 validation includes interaction contracts**: intake and inbox components have runtime component tests; `typecheck` also runs `svelte-check` via `scripts/svelte-check-a11y.mjs`. Ship raw `.svelte` via `svelte-package`.\n- **Lead workflows stay generic**: call `LeadWorkflowService` for tenant-safe intake, audited follow-up, qualification, nonterminal Opportunity stage movement, and terminal closure with optional conversion links. Optional intake `profileId` is stored and fingerprinted but remains host-authorized. The service delegates CRM lifecycles to their owning collections; hosts supply authorization and create downstream records. `LeadCreateForm`, `LeadList`, and `LeadDetail` are props/callback only. See [agents/crm.md](agents/crm.md) for dedupe, retry, and inbox contracts.\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- **Nomination matches stay in one tenant lane**: register verified aliases through `ReferrerIdentifierCollection.register()`. Unresolved nominations go into the exception queue when the target is known. Bind the resolver to the intake or attribution executor and serialize qualification per target and program.\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\n- **Governed sales use the owned service factory**: `SalesGovernanceService`\n accepts allowlisted PostgreSQL connection configuration only, owns its\n adapter and transaction executors, and guards private state/model writes.\n DuckDB support remains blocked on SDK #1452; SQLite is also rejected until\n same-process BUSY recovery is proven. Quote issue/sign always recheck\n current seller, host policy/inventory and exact finance approval; see\n [agents/crm.md](agents/crm.md#governed-sellers-quotes-and-canonical-advertiser-registration).\n\n- **Recipe `affiliates.referrals`** (`src/referrals/recipes.ts`, help in `src/referrals/referrals.recipe.md`): the affiliate feature for catalog hosts (referrers, programs, referrals, commissions, payouts). It lives here because `@happyvertical/smrt-affiliates` is a model-less shim and a recipe needs models of its own package. Fields it shows carry `@field({ description })` in plain words.\n",
14005
14279
  "moduleDocs": [
14006
14280
  {
14007
14281
  "path": "agents/agreements.md",
@@ -14021,7 +14295,7 @@
14021
14295
  {
14022
14296
  "path": "agents/referrals.md",
14023
14297
  "module": "referrals",
14024
- "content": "# smrt-sales/referrals\n\nPer-module semantics for `@happyvertical/smrt-sales/referrals`. Package orientation, the\ncross-module invariants (currency, tenancy, cross-package refs, roles vs.\nmoney), and the Gotchas that apply before editing anything live in\n[../AGENTS.md](../AGENTS.md) — read that first.\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- **Plan compatibility**: qualification and requalification accept only v1 component plans. A pinned or latest-active v2 waterfall plan returns `unsupported_plan_engine` before snapshot/referral writes; existing snapshots remain valid and unchanged. Bind compatible component terms and retry to recover. Engine changes under a plan key never implicitly migrate referrals.\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"
14298
+ "content": "# smrt-sales/referrals\n\nPer-module semantics for `@happyvertical/smrt-sales/referrals`. Package orientation, the\ncross-module invariants (currency, tenancy, cross-package refs, roles vs.\nmoney), and the Gotchas that apply before editing anything live in\n[../AGENTS.md](../AGENTS.md) — read that first.\n\n- **Referrer**: role model (`profileId`, `earnerId`, `status`).\n- **ReferrerIdentifier**: append-only alias per tenant, kind, and normalized value. Optional program limits where it matches. Disable an obsolete alias to preserve its audit history and reservation. Register through `ReferrerIdentifierCollection.register()`, which derives the normalized value, checks same-lane ownership, and returns the existing active alias when the owner and program match.\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|nomination`) 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- **Plan compatibility**: qualification and requalification accept only v1 component plans. A pinned or latest-active v2 waterfall plan returns `unsupported_plan_engine` before snapshot/referral writes; existing snapshots remain valid and unchanged. Bind compatible component terms and retry to recover. Engine changes under a plan key never implicitly migrate referrals.\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\n## Prospect nominations\n\nHosts can call `ReferralNominationResolver.recordNomination()` during intake and\n`resolve()` when an attribution target exists. Supply the same subject and\nnomination inputs, using the original intake time when known. Exact registered\nemail, code, name, or handle and active program link codes take precedence over\ndisplay-name scoring. The fallback compares name-sized word spans and requires\na score of at least 0.85 and a lead of at least 0.12 over the runner-up.\nCandidates must be active in the program's tenant lane.\n\nA match records an immutable, deterministic touch with the original nomination\nand match provenance. In `assigned` mode both manual assignments and matched\nnominations can earn credit. Competing assignment-grade touches for distinct\nreferrers go to review. The program's current policy governs credit, and\nqualification still requires the usual versioned agreement and plan.\n\nWithout a unique confident match, resolution creates one open\n`nomination_unresolved` exception for the target and program with the original\ninputs and policy pin. Candidate entries in this exception have an empty\n`touchId`. Operators award credit using `AttributionService.resolveException()`.\nThey can then call `registerResolvedIdentifier()` to remember a verified alias\nfor a referrer who received credit. Run both operations in the caller's\ntransaction when registration and resolution must commit together. The host\nauthorizes both operations and serializes attribution per target and program.\n"
14025
14299
  },
14026
14300
  {
14027
14301
  "path": "agents/svelte.md",
@@ -14391,7 +14665,7 @@
14391
14665
  }
14392
14666
  },
14393
14667
  "help": {
14394
- "markdown": "## Overview\n\nAffiliates lets partners and customers send people your way and earn a reward\nwhen it leads to a sale. You set up a program that says what a referral earns,\nsign up the people who will refer, record each person they send, and see what\neach affiliate has earned and what has been paid out.\n\n## Tasks\n\n### Sign up an affiliate\n\n1. Open the list of affiliates and choose **New**.\n2. Type their **{field:Referrer.displayName}**.\n3. Save. They stay pending until you approve them by setting the **{field:Referrer.status}**.\n\n### Set up a program\n\n1. Open the programs and choose **New**.\n2. Give the program a **{field:ReferralProgram.name}** your affiliates will understand.\n3. Set the **{field:ReferralProgram.status}** to active when you are ready to start.\n4. Save.\n\n### Record a referral\n\n1. Open the referrals and choose **New**.\n2. Pick the **{field:Referral.referrerId}** who sent the person and the **{field:Referral.programId}** it belongs to.\n3. Save. The referral stays pending until it leads to a sale.\n\n### Check what an affiliate has earned\n\n1. Open the commissions and find the affiliate.\n2. Read the **{field:Commission.amountCents}** and the **{field:Commission.status}** of each one.\n3. A commission moves from pending to approved, then payable, then paid as it is worked through.\n\n### Check a payout\n\nPayouts are made by the commission payout service, not by hand in the app. You\ncan see what has been paid.\n\n1. Open the payouts.\n2. Read the **{field:CommissionPayout.earnerId}**, the **{field:CommissionPayout.totalAmountCents}** and the **{field:CommissionPayout.status}**.\n3. A payout is waiting, approved, being sent, then completed. It shows failed or rejected if the money did not go out.\n",
14668
+ "markdown": "## Overview\n\nAffiliates lets partners and customers send people your way and earn a reward\nwhen it leads to a sale. You set up a program that says what a referral earns,\nsign up the people who will refer, record each person they send, and see what\neach affiliate has earned and what has been paid out.\n\n## Tasks\n\n### Sign up an affiliate\n\n1. Open the list of affiliates and choose **New**.\n2. Type their **{field:Referrer.displayName}**.\n3. Save. They stay pending until you approve them by setting the **{field:Referrer.status}**.\n\n### Set up a program\n\n1. Open the programs and choose **New**.\n2. Give the program a **{field:ReferralProgram.name}** your affiliates will understand.\n3. Set the **{field:ReferralProgram.status}** to active when you are ready to start.\n4. Save.\n\n### Record a referral\n\n1. Open the referrals and choose **New**.\n2. Pick the **{field:Referral.referrerId}** who sent the person and the **{field:Referral.programId}** it belongs to.\n3. Save. The referral stays pending until it leads to a sale.\n\n### Check what an affiliate has earned\n\n1. Open the commissions and find the affiliate.\n2. Read the **{field:Commission.amountCents}** and the **{field:Commission.status}** of each one.\n3. A commission moves from pending to earned, approved, payable, and paid as it is worked through.\n\n### Check a payout\n\nPayouts are made by the commission payout service, not by hand in the app. You\ncan see what has been paid.\n\n1. Open the payouts.\n2. Read the **{field:CommissionPayout.earnerId}**, the **{field:CommissionPayout.totalAmountCents}** and the **{field:CommissionPayout.status}**.\n3. A payout is waiting, approved, being sent, then completed. It shows failed or rejected if the money did not go out.\n",
14395
14669
  "fieldRefs": [
14396
14670
  "Commission.amountCents",
14397
14671
  "Commission.status",
@@ -5,10 +5,10 @@ description: "Modular sales for the SMRT framework: agreement execution, CRM, re
5
5
  status: "stable"
6
6
  generated:
7
7
  by: "smrt/scripts/generate-knowledge-okf.ts"
8
- at: "2026-11-05T15:48:19Z"
8
+ at: "2026-11-06T21:34:17Z"
9
9
  audience: "internal"
10
10
  evidence_level: "source-inspected"
11
- source_revision: "sha256:0629891e27cc57a6a5419797a7b005dcf71629583bdba36ad5e4b65ad595cc3a"
11
+ source_revision: "sha256:d4873ba74d72d43a63b08a775750f76af40ed6994383f23cd3e92cc9115f0dca"
12
12
  sources:
13
13
  - id: "manifest"
14
14
  resource: "https://github.com/happyvertical/smrt/blob/main/packages/sales/package.json"
@@ -130,6 +130,8 @@ sources:
130
130
  - `ReferralTouchCollection` (collection `referraltouches`, extends `SmrtCollection`)
131
131
  - `Referrer` (collection `referrers`, extends `SmrtObject`)
132
132
  - `ReferrerCollection` (collection `referrers`, extends `SmrtCollection`)
133
+ - `ReferrerIdentifier` (collection `referreridentifiers`, extends `SmrtObject`)
134
+ - `ReferrerIdentifierCollection` (collection `referreridentifiers`, extends `SmrtCollection`)
133
135
  - `SalesActivity` (collection `salesactivities`, extends `SmrtObject`)
134
136
  - `SalesActivityCollection` (collection `salesactivities`, extends `SmrtCollection`)
135
137
  - `SalesGovernanceEvent` (collection `salesgovernanceevents`, extends `SmrtObject`)
@@ -192,6 +194,8 @@ sources:
192
194
  - `referrer_create`: create on `@happyvertical/smrt-sales:Referrer`
193
195
  - `referrer_get`: get on `@happyvertical/smrt-sales:Referrer`
194
196
  - `referrer_list`: list on `@happyvertical/smrt-sales:Referrer`
197
+ - `referreridentifier_get`: get on `@happyvertical/smrt-sales:ReferrerIdentifier`
198
+ - `referreridentifier_list`: list on `@happyvertical/smrt-sales:ReferrerIdentifier`
195
199
  - `salesactivity_create`: create on `@happyvertical/smrt-sales:SalesActivity`
196
200
  - `salesactivity_list`: list on `@happyvertical/smrt-sales:SalesActivity`
197
201
  - `salesrepresentative_get`: get on `@happyvertical/smrt-sales:SalesRepresentative`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@happyvertical/smrt-sales",
3
- "version": "0.60.12",
3
+ "version": "0.60.14",
4
4
  "smrtJsdoc": "strict",
5
5
  "description": "Modular sales for the SMRT framework: agreement execution, CRM, referral intake, neutral commissions, and reusable Svelte surfaces",
6
6
  "type": "module",
@@ -42,18 +42,18 @@
42
42
  "./manifest.json": "./dist/manifest.json"
43
43
  },
44
44
  "dependencies": {
45
- "@happyvertical/signatures": "^0.111.5",
46
- "@happyvertical/smrt-assets": "0.60.12",
47
- "@happyvertical/smrt-core": "0.60.12",
48
- "@happyvertical/smrt-tenancy": "0.60.12",
49
- "@happyvertical/smrt-ui": "0.60.12",
50
- "@happyvertical/sql": "^0.111.5"
45
+ "@happyvertical/signatures": "^0.111.6",
46
+ "@happyvertical/smrt-assets": "0.60.14",
47
+ "@happyvertical/smrt-core": "0.60.14",
48
+ "@happyvertical/smrt-tenancy": "0.60.14",
49
+ "@happyvertical/smrt-ui": "0.60.14",
50
+ "@happyvertical/sql": "^0.111.6"
51
51
  },
52
52
  "peerDependencies": {
53
53
  "svelte": "^5.57.0"
54
54
  },
55
55
  "devDependencies": {
56
- "@happyvertical/smrt-vitest": "0.60.12",
56
+ "@happyvertical/smrt-vitest": "0.60.14",
57
57
  "@sveltejs/package": "^2.5.8",
58
58
  "@sveltejs/vite-plugin-svelte": "^7.3.0",
59
59
  "@types/node": "24.13.6",