@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
@@ -1,23 +1,23 @@
1
1
  import { D as CommissionPayout, G as Commission, O as Earner, W as CommissionCollection, i as CommissionCalculationService, v as CommissionPlanCollection } from "./commissions-DbhfPQbi.js";
2
- import { SmrtCollection, SmrtObject, SmrtRecipe, crossPackageRef, field, foreignKey, smrt } from "@happyvertical/smrt-core";
3
- import { TenantScoped, requireTenantId, tenantId } from "@happyvertical/smrt-tenancy";
2
+ import { SmrtCollection, SmrtObject, SmrtRecipe, crossPackageRef, field, foreignKey, isUniqueViolationError, smrt } from "@happyvertical/smrt-core";
3
+ import { TenantScoped, getTenantId, requireTenantId, tenantId, withTenant } from "@happyvertical/smrt-tenancy";
4
4
  import { createHash, randomBytes, randomUUID } from "node:crypto";
5
5
  //#region src/referrals/models/AttributionException.ts
6
- var __defProp$9 = Object.defineProperty;
7
- var __getOwnPropDesc$9 = Object.getOwnPropertyDescriptor;
8
- var __defNormalProp$9 = (obj, key, value) => key in obj ? __defProp$9(obj, key, {
6
+ var __defProp$10 = Object.defineProperty;
7
+ var __getOwnPropDesc$10 = Object.getOwnPropertyDescriptor;
8
+ var __defNormalProp$10 = (obj, key, value) => key in obj ? __defProp$10(obj, key, {
9
9
  enumerable: true,
10
10
  configurable: true,
11
11
  writable: true,
12
12
  value
13
13
  }) : obj[key] = value;
14
- var __decorateClass$9 = (decorators, target, key, kind) => {
15
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$9(target, key) : target;
14
+ var __decorateClass$10 = (decorators, target, key, kind) => {
15
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$10(target, key) : target;
16
16
  for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
17
- if (kind && result) __defProp$9(target, key, result);
17
+ if (kind && result) __defProp$10(target, key, result);
18
18
  return result;
19
19
  };
20
- var __publicField$9 = (obj, key, value) => __defNormalProp$9(obj, typeof key !== "symbol" ? key + "" : key, value);
20
+ var __publicField$10 = (obj, key, value) => __defNormalProp$10(obj, typeof key !== "symbol" ? key + "" : key, value);
21
21
  var AttributionException = class extends SmrtObject {
22
22
  tenantId = null;
23
23
  targetKind = "";
@@ -28,9 +28,10 @@ var AttributionException = class extends SmrtObject {
28
28
  /**
29
29
  * Why the exception was raised — recommended vocabulary: `'tie'`
30
30
  * (exact-timestamp tie between distinct referrers),
31
- * `'competing_touches'` (competing manual assignments), and
32
- * `'policy_review'` (`conflictBehavior: 'review'` with multiple
33
- * referrers). Open string.
31
+ * `'competing_touches'` (competing manual assignments or nominations),
32
+ * `'policy_review'` (`conflictBehavior: 'review'` with multiple referrers),
33
+ * and `'nomination_unresolved'` (no confident, unique nomination match).
34
+ * Open string.
34
35
  */
35
36
  conflictReason = "";
36
37
  /**
@@ -153,13 +154,13 @@ var AttributionException = class extends SmrtObject {
153
154
  return null;
154
155
  }
155
156
  };
156
- __publicField$9(AttributionException, "__smrtPackage__", "@happyvertical/smrt-sales");
157
- __decorateClass$9([tenantId({ nullable: true })], AttributionException.prototype, "tenantId", 2);
158
- __decorateClass$9([field({ required: true })], AttributionException.prototype, "targetKind", 2);
159
- __decorateClass$9([field({ required: true })], AttributionException.prototype, "targetId", 2);
160
- __decorateClass$9([foreignKey("ReferralProgram")], AttributionException.prototype, "programId", 2);
161
- __decorateClass$9([crossPackageRef("@happyvertical/smrt-profiles:Profile")], AttributionException.prototype, "resolvedByProfileId", 2);
162
- AttributionException = __decorateClass$9([TenantScoped({ mode: "optional" }), smrt({
157
+ __publicField$10(AttributionException, "__smrtPackage__", "@happyvertical/smrt-sales");
158
+ __decorateClass$10([tenantId({ nullable: true })], AttributionException.prototype, "tenantId", 2);
159
+ __decorateClass$10([field({ required: true })], AttributionException.prototype, "targetKind", 2);
160
+ __decorateClass$10([field({ required: true })], AttributionException.prototype, "targetId", 2);
161
+ __decorateClass$10([foreignKey("ReferralProgram")], AttributionException.prototype, "programId", 2);
162
+ __decorateClass$10([crossPackageRef("@happyvertical/smrt-profiles:Profile")], AttributionException.prototype, "resolvedByProfileId", 2);
163
+ AttributionException = __decorateClass$10([TenantScoped({ mode: "optional" }), smrt({
163
164
  api: { include: ["list", "get"] },
164
165
  mcp: { include: ["list", "get"] },
165
166
  cli: false
@@ -180,13 +181,14 @@ var AttributionExceptionCollection = class extends SmrtCollection {
180
181
  * `AttributionService.resolve()` returns this instead of minting a
181
182
  * duplicate when a conflict is already parked for review.
182
183
  */
183
- async findOpenByTarget(targetKind, targetId, programId) {
184
+ async findOpenByTarget(targetKind, targetId, programId, tenantId) {
184
185
  return (await this.list({
185
186
  where: {
186
187
  targetKind,
187
188
  targetId,
188
189
  programId,
189
- status: "open"
190
+ status: "open",
191
+ ...tenantId !== void 0 && { tenantId }
190
192
  },
191
193
  orderBy: "created_at ASC",
192
194
  limit: 1
@@ -234,7 +236,8 @@ var REFERRAL_TOUCH_KINDS = [
234
236
  "click",
235
237
  "code_entry",
236
238
  "manual_assignment",
237
- "partner_entry"
239
+ "partner_entry",
240
+ "nomination"
238
241
  ];
239
242
  var REFERRAL_STATUSES = [
240
243
  "pending",
@@ -255,21 +258,21 @@ var REFERRAL_AGREEMENT_STATUSES = [
255
258
  var REFERRAL_AGREEMENT_APPROVAL_MODES = ["manual", "auto"];
256
259
  //#endregion
257
260
  //#region src/referrals/models/AttributionPolicy.ts
258
- var __defProp$8 = Object.defineProperty;
259
- var __getOwnPropDesc$8 = Object.getOwnPropertyDescriptor;
260
- var __defNormalProp$8 = (obj, key, value) => key in obj ? __defProp$8(obj, key, {
261
+ var __defProp$9 = Object.defineProperty;
262
+ var __getOwnPropDesc$9 = Object.getOwnPropertyDescriptor;
263
+ var __defNormalProp$9 = (obj, key, value) => key in obj ? __defProp$9(obj, key, {
261
264
  enumerable: true,
262
265
  configurable: true,
263
266
  writable: true,
264
267
  value
265
268
  }) : obj[key] = value;
266
- var __decorateClass$8 = (decorators, target, key, kind) => {
267
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$8(target, key) : target;
269
+ var __decorateClass$9 = (decorators, target, key, kind) => {
270
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$9(target, key) : target;
268
271
  for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
269
- if (kind && result) __defProp$8(target, key, result);
272
+ if (kind && result) __defProp$9(target, key, result);
270
273
  return result;
271
274
  };
272
- var __publicField$8 = (obj, key, value) => __defNormalProp$8(obj, typeof key !== "symbol" ? key + "" : key, value);
275
+ var __publicField$9 = (obj, key, value) => __defNormalProp$9(obj, typeof key !== "symbol" ? key + "" : key, value);
273
276
  var POLICY_STATUS_TRANSITIONS = {
274
277
  draft: ["active", "retired"],
275
278
  active: ["superseded", "retired"],
@@ -534,10 +537,10 @@ var AttributionPolicy = class extends SmrtObject {
534
537
  return null;
535
538
  }
536
539
  };
537
- __publicField$8(AttributionPolicy, "__smrtPackage__", "@happyvertical/smrt-sales");
538
- __decorateClass$8([tenantId({ nullable: true })], AttributionPolicy.prototype, "tenantId", 2);
539
- __decorateClass$8([field({ required: true })], AttributionPolicy.prototype, "policyKey", 2);
540
- AttributionPolicy = __decorateClass$8([TenantScoped({ mode: "optional" }), smrt({
540
+ __publicField$9(AttributionPolicy, "__smrtPackage__", "@happyvertical/smrt-sales");
541
+ __decorateClass$9([tenantId({ nullable: true })], AttributionPolicy.prototype, "tenantId", 2);
542
+ __decorateClass$9([field({ required: true })], AttributionPolicy.prototype, "policyKey", 2);
543
+ AttributionPolicy = __decorateClass$9([TenantScoped({ mode: "optional" }), smrt({
541
544
  conflictColumns: [
542
545
  "tenant_id",
543
546
  "policy_key",
@@ -621,21 +624,21 @@ var AttributionPolicyCollection = class extends SmrtCollection {
621
624
  };
622
625
  //#endregion
623
626
  //#region src/referrals/models/ReferralAgreement.ts
624
- var __defProp$7 = Object.defineProperty;
625
- var __getOwnPropDesc$7 = Object.getOwnPropertyDescriptor;
626
- var __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$7(obj, key, {
627
+ var __defProp$8 = Object.defineProperty;
628
+ var __getOwnPropDesc$8 = Object.getOwnPropertyDescriptor;
629
+ var __defNormalProp$8 = (obj, key, value) => key in obj ? __defProp$8(obj, key, {
627
630
  enumerable: true,
628
631
  configurable: true,
629
632
  writable: true,
630
633
  value
631
634
  }) : obj[key] = value;
632
- var __decorateClass$7 = (decorators, target, key, kind) => {
633
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$7(target, key) : target;
635
+ var __decorateClass$8 = (decorators, target, key, kind) => {
636
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$8(target, key) : target;
634
637
  for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
635
- if (kind && result) __defProp$7(target, key, result);
638
+ if (kind && result) __defProp$8(target, key, result);
636
639
  return result;
637
640
  };
638
- var __publicField$7 = (obj, key, value) => __defNormalProp$7(obj, typeof key !== "symbol" ? key + "" : key, value);
641
+ var __publicField$8 = (obj, key, value) => __defNormalProp$8(obj, typeof key !== "symbol" ? key + "" : key, value);
639
642
  var AGREEMENT_STATUS_TRANSITIONS = {
640
643
  draft: ["active", "terminated"],
641
644
  active: ["superseded", "terminated"],
@@ -870,13 +873,13 @@ var ReferralAgreement = class extends SmrtObject {
870
873
  return null;
871
874
  }
872
875
  };
873
- __publicField$7(ReferralAgreement, "__smrtPackage__", "@happyvertical/smrt-sales");
874
- __decorateClass$7([tenantId({ nullable: true })], ReferralAgreement.prototype, "tenantId", 2);
875
- __decorateClass$7([foreignKey("Referrer", { required: true })], ReferralAgreement.prototype, "referrerId", 2);
876
- __decorateClass$7([foreignKey("ReferralProgram", { required: true })], ReferralAgreement.prototype, "programId", 2);
877
- __decorateClass$7([foreignKey("AgreementExecution")], ReferralAgreement.prototype, "executionId", 2);
878
- __decorateClass$7([foreignKey("ExecutedAgreement")], ReferralAgreement.prototype, "executedAgreementId", 2);
879
- ReferralAgreement = __decorateClass$7([TenantScoped({ mode: "optional" }), smrt({
876
+ __publicField$8(ReferralAgreement, "__smrtPackage__", "@happyvertical/smrt-sales");
877
+ __decorateClass$8([tenantId({ nullable: true })], ReferralAgreement.prototype, "tenantId", 2);
878
+ __decorateClass$8([foreignKey("Referrer", { required: true })], ReferralAgreement.prototype, "referrerId", 2);
879
+ __decorateClass$8([foreignKey("ReferralProgram", { required: true })], ReferralAgreement.prototype, "programId", 2);
880
+ __decorateClass$8([foreignKey("AgreementExecution")], ReferralAgreement.prototype, "executionId", 2);
881
+ __decorateClass$8([foreignKey("ExecutedAgreement")], ReferralAgreement.prototype, "executedAgreementId", 2);
882
+ ReferralAgreement = __decorateClass$8([TenantScoped({ mode: "optional" }), smrt({
880
883
  conflictColumns: [
881
884
  "referrer_id",
882
885
  "program_id",
@@ -955,21 +958,21 @@ var ReferralAgreementCollection = class extends SmrtCollection {
955
958
  };
956
959
  //#endregion
957
960
  //#region src/referrals/models/ReferralClickOperation.ts
958
- var __defProp$6 = Object.defineProperty;
959
- var __getOwnPropDesc$6 = Object.getOwnPropertyDescriptor;
960
- var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, {
961
+ var __defProp$7 = Object.defineProperty;
962
+ var __getOwnPropDesc$7 = Object.getOwnPropertyDescriptor;
963
+ var __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$7(obj, key, {
961
964
  enumerable: true,
962
965
  configurable: true,
963
966
  writable: true,
964
967
  value
965
968
  }) : obj[key] = value;
966
- var __decorateClass$6 = (decorators, target, key, kind) => {
967
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$6(target, key) : target;
969
+ var __decorateClass$7 = (decorators, target, key, kind) => {
970
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$7(target, key) : target;
968
971
  for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
969
- if (kind && result) __defProp$6(target, key, result);
972
+ if (kind && result) __defProp$7(target, key, result);
970
973
  return result;
971
974
  };
972
- var __publicField$6 = (obj, key, value) => __defNormalProp$6(obj, typeof key !== "symbol" ? key + "" : key, value);
975
+ var __publicField$7 = (obj, key, value) => __defNormalProp$7(obj, typeof key !== "symbol" ? key + "" : key, value);
973
976
  var ReferralClickOperation = class extends SmrtObject {
974
977
  tenantId = null;
975
978
  keyHash;
@@ -996,37 +999,37 @@ var ReferralClickOperation = class extends SmrtObject {
996
999
  return this;
997
1000
  }
998
1001
  };
999
- __publicField$6(ReferralClickOperation, "__smrtPackage__", "@happyvertical/smrt-sales");
1000
- __decorateClass$6([tenantId({ nullable: true })], ReferralClickOperation.prototype, "tenantId", 2);
1001
- __decorateClass$6([field({
1002
+ __publicField$7(ReferralClickOperation, "__smrtPackage__", "@happyvertical/smrt-sales");
1003
+ __decorateClass$7([tenantId({ nullable: true })], ReferralClickOperation.prototype, "tenantId", 2);
1004
+ __decorateClass$7([field({
1002
1005
  required: true,
1003
1006
  readonly: true
1004
1007
  })], ReferralClickOperation.prototype, "keyHash", 2);
1005
- __decorateClass$6([field({
1008
+ __decorateClass$7([field({
1006
1009
  sqlType: "UUID",
1007
1010
  required: true,
1008
1011
  readonly: true,
1009
1012
  indexed: true
1010
1013
  })], ReferralClickOperation.prototype, "linkId", 2);
1011
- __decorateClass$6([field({
1014
+ __decorateClass$7([field({
1012
1015
  sqlType: "UUID",
1013
1016
  required: true,
1014
1017
  readonly: true,
1015
1018
  indexed: true
1016
1019
  })], ReferralClickOperation.prototype, "touchId", 2);
1017
- __decorateClass$6([field({
1020
+ __decorateClass$7([field({
1018
1021
  required: true,
1019
1022
  readonly: true
1020
1023
  })], ReferralClickOperation.prototype, "intentHash", 2);
1021
- __decorateClass$6([field({
1024
+ __decorateClass$7([field({
1022
1025
  required: true,
1023
1026
  readonly: true
1024
1027
  })], ReferralClickOperation.prototype, "callerEvidenceHash", 2);
1025
- __decorateClass$6([field({
1028
+ __decorateClass$7([field({
1026
1029
  required: true,
1027
1030
  readonly: true
1028
1031
  })], ReferralClickOperation.prototype, "requestedOccurredAt", 2);
1029
- ReferralClickOperation = __decorateClass$6([TenantScoped({ mode: "optional" }), smrt({
1032
+ ReferralClickOperation = __decorateClass$7([TenantScoped({ mode: "optional" }), smrt({
1030
1033
  api: false,
1031
1034
  mcp: false,
1032
1035
  cli: false
@@ -1070,21 +1073,21 @@ var ReferralClickOperationCollection = class extends SmrtCollection {
1070
1073
  };
1071
1074
  //#endregion
1072
1075
  //#region src/referrals/models/Referral.ts
1073
- var __defProp$5 = Object.defineProperty;
1074
- var __getOwnPropDesc$5 = Object.getOwnPropertyDescriptor;
1075
- var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, {
1076
+ var __defProp$6 = Object.defineProperty;
1077
+ var __getOwnPropDesc$6 = Object.getOwnPropertyDescriptor;
1078
+ var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, {
1076
1079
  enumerable: true,
1077
1080
  configurable: true,
1078
1081
  writable: true,
1079
1082
  value
1080
1083
  }) : obj[key] = value;
1081
- var __decorateClass$5 = (decorators, target, key, kind) => {
1082
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$5(target, key) : target;
1084
+ var __decorateClass$6 = (decorators, target, key, kind) => {
1085
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$6(target, key) : target;
1083
1086
  for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
1084
- if (kind && result) __defProp$5(target, key, result);
1087
+ if (kind && result) __defProp$6(target, key, result);
1085
1088
  return result;
1086
1089
  };
1087
- var __publicField$5 = (obj, key, value) => __defNormalProp$5(obj, typeof key !== "symbol" ? key + "" : key, value);
1090
+ var __publicField$6 = (obj, key, value) => __defNormalProp$6(obj, typeof key !== "symbol" ? key + "" : key, value);
1088
1091
  var REFERRAL_STATUS_TRANSITIONS = {
1089
1092
  pending: [
1090
1093
  "attributed",
@@ -1285,13 +1288,13 @@ var Referral = class extends SmrtObject {
1285
1288
  return null;
1286
1289
  }
1287
1290
  };
1288
- __publicField$5(Referral, "__smrtPackage__", "@happyvertical/smrt-sales");
1289
- __decorateClass$5([tenantId({ nullable: true })], Referral.prototype, "tenantId", 2);
1290
- __decorateClass$5([field({ description: "The affiliate who sent this person." }), foreignKey("Referrer", { required: true })], Referral.prototype, "referrerId", 2);
1291
- __decorateClass$5([field({ description: "The program this referral counts towards." }), foreignKey("ReferralProgram", { required: true })], Referral.prototype, "programId", 2);
1292
- __decorateClass$5([field({ description: "Whether the referral is waiting, has led to a sale or has lapsed." })], Referral.prototype, "status", 2);
1293
- __decorateClass$5([foreignKey("ReferralTouch")], Referral.prototype, "primaryTouchId", 2);
1294
- Referral = __decorateClass$5([TenantScoped({ mode: "optional" }), smrt({
1291
+ __publicField$6(Referral, "__smrtPackage__", "@happyvertical/smrt-sales");
1292
+ __decorateClass$6([tenantId({ nullable: true })], Referral.prototype, "tenantId", 2);
1293
+ __decorateClass$6([field({ description: "The affiliate who sent this person." }), foreignKey("Referrer", { required: true })], Referral.prototype, "referrerId", 2);
1294
+ __decorateClass$6([field({ description: "The program this referral counts towards." }), foreignKey("ReferralProgram", { required: true })], Referral.prototype, "programId", 2);
1295
+ __decorateClass$6([field({ description: "Whether the referral is waiting, has led to a sale or has lapsed." })], Referral.prototype, "status", 2);
1296
+ __decorateClass$6([foreignKey("ReferralTouch")], Referral.prototype, "primaryTouchId", 2);
1297
+ Referral = __decorateClass$6([TenantScoped({ mode: "optional" }), smrt({
1295
1298
  api: { include: [
1296
1299
  "list",
1297
1300
  "get",
@@ -1361,21 +1364,21 @@ var ReferralCollection = class extends SmrtCollection {
1361
1364
  };
1362
1365
  //#endregion
1363
1366
  //#region src/referrals/models/ReferralLink.ts
1364
- var __defProp$4 = Object.defineProperty;
1365
- var __getOwnPropDesc$4 = Object.getOwnPropertyDescriptor;
1366
- var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, {
1367
+ var __defProp$5 = Object.defineProperty;
1368
+ var __getOwnPropDesc$5 = Object.getOwnPropertyDescriptor;
1369
+ var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, {
1367
1370
  enumerable: true,
1368
1371
  configurable: true,
1369
1372
  writable: true,
1370
1373
  value
1371
1374
  }) : obj[key] = value;
1372
- var __decorateClass$4 = (decorators, target, key, kind) => {
1373
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$4(target, key) : target;
1375
+ var __decorateClass$5 = (decorators, target, key, kind) => {
1376
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$5(target, key) : target;
1374
1377
  for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
1375
- if (kind && result) __defProp$4(target, key, result);
1378
+ if (kind && result) __defProp$5(target, key, result);
1376
1379
  return result;
1377
1380
  };
1378
- var __publicField$4 = (obj, key, value) => __defNormalProp$4(obj, typeof key !== "symbol" ? key + "" : key, value);
1381
+ var __publicField$5 = (obj, key, value) => __defNormalProp$5(obj, typeof key !== "symbol" ? key + "" : key, value);
1379
1382
  function assertHttpTargetUrl(targetUrl) {
1380
1383
  let parsed;
1381
1384
  try {
@@ -1459,12 +1462,12 @@ var ReferralLink = class extends SmrtObject {
1459
1462
  return await super.save(options);
1460
1463
  }
1461
1464
  };
1462
- __publicField$4(ReferralLink, "__smrtPackage__", "@happyvertical/smrt-sales");
1463
- __decorateClass$4([tenantId({ nullable: true })], ReferralLink.prototype, "tenantId", 2);
1464
- __decorateClass$4([foreignKey("Referrer", { required: true })], ReferralLink.prototype, "referrerId", 2);
1465
- __decorateClass$4([foreignKey("ReferralProgram", { required: true })], ReferralLink.prototype, "programId", 2);
1466
- __decorateClass$4([field({ required: true })], ReferralLink.prototype, "code", 2);
1467
- ReferralLink = __decorateClass$4([TenantScoped({ mode: "optional" }), smrt({
1465
+ __publicField$5(ReferralLink, "__smrtPackage__", "@happyvertical/smrt-sales");
1466
+ __decorateClass$5([tenantId({ nullable: true })], ReferralLink.prototype, "tenantId", 2);
1467
+ __decorateClass$5([foreignKey("Referrer", { required: true })], ReferralLink.prototype, "referrerId", 2);
1468
+ __decorateClass$5([foreignKey("ReferralProgram", { required: true })], ReferralLink.prototype, "programId", 2);
1469
+ __decorateClass$5([field({ required: true })], ReferralLink.prototype, "code", 2);
1470
+ ReferralLink = __decorateClass$5([TenantScoped({ mode: "optional" }), smrt({
1468
1471
  conflictColumns: ["code"],
1469
1472
  api: { include: [
1470
1473
  "list",
@@ -1481,21 +1484,21 @@ ReferralLink = __decorateClass$4([TenantScoped({ mode: "optional" }), smrt({
1481
1484
  })], ReferralLink);
1482
1485
  //#endregion
1483
1486
  //#region src/referrals/models/ReferralTouch.ts
1484
- var __defProp$3 = Object.defineProperty;
1485
- var __getOwnPropDesc$3 = Object.getOwnPropertyDescriptor;
1486
- var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, {
1487
+ var __defProp$4 = Object.defineProperty;
1488
+ var __getOwnPropDesc$4 = Object.getOwnPropertyDescriptor;
1489
+ var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, {
1487
1490
  enumerable: true,
1488
1491
  configurable: true,
1489
1492
  writable: true,
1490
1493
  value
1491
1494
  }) : obj[key] = value;
1492
- var __decorateClass$3 = (decorators, target, key, kind) => {
1493
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$3(target, key) : target;
1495
+ var __decorateClass$4 = (decorators, target, key, kind) => {
1496
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$4(target, key) : target;
1494
1497
  for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
1495
- if (kind && result) __defProp$3(target, key, result);
1498
+ if (kind && result) __defProp$4(target, key, result);
1496
1499
  return result;
1497
1500
  };
1498
- var __publicField$3 = (obj, key, value) => __defNormalProp$3(obj, typeof key !== "symbol" ? key + "" : key, value);
1501
+ var __publicField$4 = (obj, key, value) => __defNormalProp$4(obj, typeof key !== "symbol" ? key + "" : key, value);
1499
1502
  var ReferralTouch = class extends SmrtObject {
1500
1503
  tenantId = null;
1501
1504
  linkId = "";
@@ -1517,7 +1520,8 @@ var ReferralTouch = class extends SmrtObject {
1517
1520
  occurredAt = /* @__PURE__ */ new Date();
1518
1521
  /**
1519
1522
  * Evidence payload as a JSON object string (the code/link/url for clicks,
1520
- * actor + reason for manual assignments, …). Use
1523
+ * actor + reason for manual assignments, `ReferralNominationEvidence` for
1524
+ * matched nominations, …). Use
1521
1525
  * {@link getEvidence}/{@link setEvidence}.
1522
1526
  */
1523
1527
  evidence = "{}";
@@ -1587,12 +1591,12 @@ var ReferralTouch = class extends SmrtObject {
1587
1591
  return null;
1588
1592
  }
1589
1593
  };
1590
- __publicField$3(ReferralTouch, "__smrtPackage__", "@happyvertical/smrt-sales");
1591
- __decorateClass$3([tenantId({ nullable: true })], ReferralTouch.prototype, "tenantId", 2);
1592
- __decorateClass$3([foreignKey("ReferralLink")], ReferralTouch.prototype, "linkId", 2);
1593
- __decorateClass$3([foreignKey("Referrer", { required: true })], ReferralTouch.prototype, "referrerId", 2);
1594
- __decorateClass$3([foreignKey("ReferralProgram")], ReferralTouch.prototype, "programId", 2);
1595
- ReferralTouch = __decorateClass$3([TenantScoped({ mode: "optional" }), smrt({
1594
+ __publicField$4(ReferralTouch, "__smrtPackage__", "@happyvertical/smrt-sales");
1595
+ __decorateClass$4([tenantId({ nullable: true })], ReferralTouch.prototype, "tenantId", 2);
1596
+ __decorateClass$4([foreignKey("ReferralLink")], ReferralTouch.prototype, "linkId", 2);
1597
+ __decorateClass$4([foreignKey("Referrer", { required: true })], ReferralTouch.prototype, "referrerId", 2);
1598
+ __decorateClass$4([foreignKey("ReferralProgram")], ReferralTouch.prototype, "programId", 2);
1599
+ ReferralTouch = __decorateClass$4([TenantScoped({ mode: "optional" }), smrt({
1596
1600
  api: { include: [
1597
1601
  "create",
1598
1602
  "list",
@@ -2066,21 +2070,21 @@ function isPlainObject(value) {
2066
2070
  }
2067
2071
  //#endregion
2068
2072
  //#region src/referrals/models/ReferralProgram.ts
2069
- var __defProp$2 = Object.defineProperty;
2070
- var __getOwnPropDesc$2 = Object.getOwnPropertyDescriptor;
2071
- var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, {
2073
+ var __defProp$3 = Object.defineProperty;
2074
+ var __getOwnPropDesc$3 = Object.getOwnPropertyDescriptor;
2075
+ var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, {
2072
2076
  enumerable: true,
2073
2077
  configurable: true,
2074
2078
  writable: true,
2075
2079
  value
2076
2080
  }) : obj[key] = value;
2077
- var __decorateClass$2 = (decorators, target, key, kind) => {
2078
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$2(target, key) : target;
2081
+ var __decorateClass$3 = (decorators, target, key, kind) => {
2082
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$3(target, key) : target;
2079
2083
  for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
2080
- if (kind && result) __defProp$2(target, key, result);
2084
+ if (kind && result) __defProp$3(target, key, result);
2081
2085
  return result;
2082
2086
  };
2083
- var __publicField$2 = (obj, key, value) => __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
2087
+ var __publicField$3 = (obj, key, value) => __defNormalProp$3(obj, typeof key !== "symbol" ? key + "" : key, value);
2084
2088
  var ReferralProgram = class extends SmrtObject {
2085
2089
  tenantId = null;
2086
2090
  key = "";
@@ -2130,15 +2134,15 @@ var ReferralProgram = class extends SmrtObject {
2130
2134
  this.metadata = JSON.stringify(metadata);
2131
2135
  }
2132
2136
  };
2133
- __publicField$2(ReferralProgram, "__smrtPackage__", "@happyvertical/smrt-sales");
2134
- __decorateClass$2([tenantId({ nullable: true })], ReferralProgram.prototype, "tenantId", 2);
2135
- __decorateClass$2([field({
2137
+ __publicField$3(ReferralProgram, "__smrtPackage__", "@happyvertical/smrt-sales");
2138
+ __decorateClass$3([tenantId({ nullable: true })], ReferralProgram.prototype, "tenantId", 2);
2139
+ __decorateClass$3([field({
2136
2140
  required: true,
2137
2141
  description: "A short name for the program, used in links and reports."
2138
2142
  })], ReferralProgram.prototype, "key", 2);
2139
- __decorateClass$2([field({ description: "What you call this program." })], ReferralProgram.prototype, "name", 2);
2140
- __decorateClass$2([field({ description: "Whether the program is in draft, running or finished." })], ReferralProgram.prototype, "status", 2);
2141
- ReferralProgram = __decorateClass$2([TenantScoped({ mode: "optional" }), smrt({
2143
+ __decorateClass$3([field({ description: "What you call this program." })], ReferralProgram.prototype, "name", 2);
2144
+ __decorateClass$3([field({ description: "Whether the program is in draft, running or finished." })], ReferralProgram.prototype, "status", 2);
2145
+ ReferralProgram = __decorateClass$3([TenantScoped({ mode: "optional" }), smrt({
2142
2146
  conflictColumns: ["tenant_id", "key"],
2143
2147
  api: { include: [
2144
2148
  "list",
@@ -2178,21 +2182,21 @@ var ReferralProgramCollection = class extends SmrtCollection {
2178
2182
  };
2179
2183
  //#endregion
2180
2184
  //#region src/referrals/models/ReferralTermSnapshot.ts
2181
- var __defProp$1 = Object.defineProperty;
2182
- var __getOwnPropDesc$1 = Object.getOwnPropertyDescriptor;
2183
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, {
2185
+ var __defProp$2 = Object.defineProperty;
2186
+ var __getOwnPropDesc$2 = Object.getOwnPropertyDescriptor;
2187
+ var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, {
2184
2188
  enumerable: true,
2185
2189
  configurable: true,
2186
2190
  writable: true,
2187
2191
  value
2188
2192
  }) : obj[key] = value;
2189
- var __decorateClass$1 = (decorators, target, key, kind) => {
2190
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$1(target, key) : target;
2193
+ var __decorateClass$2 = (decorators, target, key, kind) => {
2194
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$2(target, key) : target;
2191
2195
  for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
2192
- if (kind && result) __defProp$1(target, key, result);
2196
+ if (kind && result) __defProp$2(target, key, result);
2193
2197
  return result;
2194
2198
  };
2195
- var __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
2199
+ var __publicField$2 = (obj, key, value) => __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
2196
2200
  var persistedSnapshotState = /* @__PURE__ */ new WeakMap();
2197
2201
  var ReferralTermSnapshot = class extends SmrtObject {
2198
2202
  tenantId = null;
@@ -2307,10 +2311,10 @@ var ReferralTermSnapshot = class extends SmrtObject {
2307
2311
  });
2308
2312
  }
2309
2313
  };
2310
- __publicField$1(ReferralTermSnapshot, "__smrtPackage__", "@happyvertical/smrt-sales");
2311
- __decorateClass$1([tenantId({ nullable: true })], ReferralTermSnapshot.prototype, "tenantId", 2);
2312
- __decorateClass$1([foreignKey("Referral", { required: true })], ReferralTermSnapshot.prototype, "referralId", 2);
2313
- ReferralTermSnapshot = __decorateClass$1([TenantScoped({ mode: "optional" }), smrt({
2314
+ __publicField$2(ReferralTermSnapshot, "__smrtPackage__", "@happyvertical/smrt-sales");
2315
+ __decorateClass$2([tenantId({ nullable: true })], ReferralTermSnapshot.prototype, "tenantId", 2);
2316
+ __decorateClass$2([foreignKey("Referral", { required: true })], ReferralTermSnapshot.prototype, "referralId", 2);
2317
+ ReferralTermSnapshot = __decorateClass$2([TenantScoped({ mode: "optional" }), smrt({
2314
2318
  api: { include: ["list", "get"] },
2315
2319
  mcp: { include: ["list", "get"] },
2316
2320
  cli: false
@@ -2333,21 +2337,21 @@ var ReferralTermSnapshotCollection = class extends SmrtCollection {
2333
2337
  };
2334
2338
  //#endregion
2335
2339
  //#region src/referrals/models/Referrer.ts
2336
- var __defProp = Object.defineProperty;
2337
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
2338
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, {
2340
+ var __defProp$1 = Object.defineProperty;
2341
+ var __getOwnPropDesc$1 = Object.getOwnPropertyDescriptor;
2342
+ var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, {
2339
2343
  enumerable: true,
2340
2344
  configurable: true,
2341
2345
  writable: true,
2342
2346
  value
2343
2347
  }) : obj[key] = value;
2344
- var __decorateClass = (decorators, target, key, kind) => {
2345
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
2348
+ var __decorateClass$1 = (decorators, target, key, kind) => {
2349
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$1(target, key) : target;
2346
2350
  for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
2347
- if (kind && result) __defProp(target, key, result);
2351
+ if (kind && result) __defProp$1(target, key, result);
2348
2352
  return result;
2349
2353
  };
2350
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
2354
+ var __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
2351
2355
  var Referrer = class extends SmrtObject {
2352
2356
  tenantId = null;
2353
2357
  profileId = "";
@@ -2393,13 +2397,13 @@ var Referrer = class extends SmrtObject {
2393
2397
  this.metadata = JSON.stringify(metadata);
2394
2398
  }
2395
2399
  };
2396
- __publicField(Referrer, "__smrtPackage__", "@happyvertical/smrt-sales");
2397
- __decorateClass([tenantId({ nullable: true })], Referrer.prototype, "tenantId", 2);
2398
- __decorateClass([crossPackageRef("@happyvertical/smrt-profiles:Profile")], Referrer.prototype, "profileId", 2);
2399
- __decorateClass([foreignKey("Earner")], Referrer.prototype, "earnerId", 2);
2400
- __decorateClass([field({ description: "The name you know this affiliate by." })], Referrer.prototype, "displayName", 2);
2401
- __decorateClass([field({ description: "Whether this affiliate is approved to send you referrals." })], Referrer.prototype, "status", 2);
2402
- Referrer = __decorateClass([TenantScoped({ mode: "optional" }), smrt({
2400
+ __publicField$1(Referrer, "__smrtPackage__", "@happyvertical/smrt-sales");
2401
+ __decorateClass$1([tenantId({ nullable: true })], Referrer.prototype, "tenantId", 2);
2402
+ __decorateClass$1([crossPackageRef("@happyvertical/smrt-profiles:Profile")], Referrer.prototype, "profileId", 2);
2403
+ __decorateClass$1([foreignKey("Earner")], Referrer.prototype, "earnerId", 2);
2404
+ __decorateClass$1([field({ description: "The name you know this affiliate by." })], Referrer.prototype, "displayName", 2);
2405
+ __decorateClass$1([field({ description: "Whether this affiliate is approved to send you referrals." })], Referrer.prototype, "status", 2);
2406
+ Referrer = __decorateClass$1([TenantScoped({ mode: "optional" }), smrt({
2403
2407
  api: { include: [
2404
2408
  "list",
2405
2409
  "get",
@@ -2440,6 +2444,162 @@ var ReferrerCollection = class extends SmrtCollection {
2440
2444
  }
2441
2445
  };
2442
2446
  //#endregion
2447
+ //#region src/referrals/nomination-identity.ts
2448
+ function normalizeIdentifier(value) {
2449
+ return value.normalize("NFKC").trim().toLowerCase().replace(/\s+/gu, " ");
2450
+ }
2451
+ function nominationUuid(parts) {
2452
+ const hash = createHash("sha256").update(JSON.stringify(parts)).digest("hex");
2453
+ return `${hash.slice(0, 8)}-${hash.slice(8, 12)}-8${hash.slice(13, 16)}-a${hash.slice(17, 20)}-${hash.slice(20, 32)}`;
2454
+ }
2455
+ //#endregion
2456
+ //#region src/referrals/models/ReferrerIdentifier.ts
2457
+ var __defProp = Object.defineProperty;
2458
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
2459
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, {
2460
+ enumerable: true,
2461
+ configurable: true,
2462
+ writable: true,
2463
+ value
2464
+ }) : obj[key] = value;
2465
+ var __decorateClass = (decorators, target, key, kind) => {
2466
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
2467
+ for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
2468
+ if (kind && result) __defProp(target, key, result);
2469
+ return result;
2470
+ };
2471
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
2472
+ var ReferrerIdentifier = class extends SmrtObject {
2473
+ tenantId = null;
2474
+ referrerId = "";
2475
+ programId = null;
2476
+ kind = "";
2477
+ value = "";
2478
+ normalizedValue = "";
2479
+ status = "active";
2480
+ metadata = "{}";
2481
+ constructor(options = {}) {
2482
+ super(options);
2483
+ if (options.tenantId !== void 0) this.tenantId = options.tenantId;
2484
+ if (options.referrerId !== void 0) this.referrerId = options.referrerId;
2485
+ if (options.programId !== void 0) this.programId = options.programId;
2486
+ if (options.kind !== void 0) this.kind = options.kind;
2487
+ if (options.value !== void 0) this.value = options.value;
2488
+ if (options.status !== void 0) this.status = options.status;
2489
+ if (options.metadata !== void 0) this.metadata = options.metadata;
2490
+ }
2491
+ isActive() {
2492
+ return this.status === "active";
2493
+ }
2494
+ disable() {
2495
+ this.status = "disabled";
2496
+ }
2497
+ getMetadata() {
2498
+ try {
2499
+ const parsed = JSON.parse(this.metadata);
2500
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
2501
+ } catch {
2502
+ return {};
2503
+ }
2504
+ }
2505
+ setMetadata(metadata) {
2506
+ this.metadata = JSON.stringify(metadata);
2507
+ }
2508
+ async save(options) {
2509
+ const contextTenantId = getTenantId();
2510
+ this.tenantId ??= contextTenantId ?? null;
2511
+ if (contextTenantId && this.tenantId !== contextTenantId) throw new Error("ReferrerIdentifier belongs to a different tenant");
2512
+ this.kind = normalizeIdentifier(this.kind);
2513
+ this.normalizedValue = normalizeIdentifier(this.value);
2514
+ if (!this.kind || !this.normalizedValue || !this.referrerId || !["active", "disabled"].includes(this.status)) throw new Error("ReferrerIdentifier requires a referrer, kind, value, and valid status");
2515
+ if (this.isPersisted) {
2516
+ const stored = await this.db.get(this.tableName, { id: this.id });
2517
+ if (!stored || (stored.tenant_id ?? null) !== this.tenantId || stored.referrer_id !== this.referrerId || (stored.program_id ?? null) !== this.programId || stored.kind !== this.kind || stored.value !== this.value || stored.normalized_value !== this.normalizedValue || stored.metadata !== this.metadata || stored.status === "disabled" && this.status !== "disabled") throw new Error("ReferrerIdentifier is append-only and may only be disabled");
2518
+ } else {
2519
+ this.id = nominationUuid([
2520
+ "referrer-identifier",
2521
+ this.tenantId,
2522
+ this.kind,
2523
+ this.normalizedValue
2524
+ ]);
2525
+ this.requireInsertOnSave();
2526
+ }
2527
+ return await super.save(options);
2528
+ }
2529
+ async delete() {
2530
+ throw new Error("ReferrerIdentifier is append-only and may only be disabled");
2531
+ }
2532
+ };
2533
+ __publicField(ReferrerIdentifier, "__smrtPackage__", "@happyvertical/smrt-sales");
2534
+ __decorateClass([tenantId({ nullable: true })], ReferrerIdentifier.prototype, "tenantId", 2);
2535
+ __decorateClass([foreignKey("Referrer", { required: true })], ReferrerIdentifier.prototype, "referrerId", 2);
2536
+ __decorateClass([foreignKey("ReferralProgram")], ReferrerIdentifier.prototype, "programId", 2);
2537
+ __decorateClass([field({ required: true })], ReferrerIdentifier.prototype, "kind", 2);
2538
+ __decorateClass([field({ required: true })], ReferrerIdentifier.prototype, "value", 2);
2539
+ __decorateClass([field({ required: true })], ReferrerIdentifier.prototype, "normalizedValue", 2);
2540
+ ReferrerIdentifier = __decorateClass([TenantScoped({ mode: "optional" }), smrt({
2541
+ conflictColumns: [
2542
+ "tenant_id",
2543
+ "kind",
2544
+ "normalized_value"
2545
+ ],
2546
+ sensitive: true,
2547
+ api: { include: ["list", "get"] },
2548
+ mcp: { include: ["list", "get"] },
2549
+ cli: false
2550
+ })], ReferrerIdentifier);
2551
+ //#endregion
2552
+ //#region src/referrals/collections/ReferrerIdentifierCollection.ts
2553
+ var ReferrerIdentifierConflictError = class extends Error {
2554
+ constructor(cause) {
2555
+ super("ReferrerIdentifier is already registered in this tenant", { cause });
2556
+ this.name = "ReferrerIdentifierConflictError";
2557
+ }
2558
+ };
2559
+ var ReferrerIdentifierCollection = class extends SmrtCollection {
2560
+ static _itemClass = ReferrerIdentifier;
2561
+ /** Register an alias in the caller's executor and tenant lane. */
2562
+ async register(input) {
2563
+ const contextTenantId = getTenantId();
2564
+ if (contextTenantId && contextTenantId !== input.tenantId) throw new Error("ReferrerIdentifier registration tenant mismatch");
2565
+ const options = {
2566
+ db: this.db,
2567
+ _reuseInitializedDb: true,
2568
+ _deferRuntimeInitialization: true
2569
+ };
2570
+ const referrer = await (await ReferrerCollection.create(options)).get({ id: input.referrerId });
2571
+ if (!referrer || referrer.tenantId !== input.tenantId) throw new Error("ReferrerIdentifier requires a referrer in the same tenant");
2572
+ if (input.programId) {
2573
+ const program = await (await ReferralProgramCollection.create(options)).get({ id: input.programId });
2574
+ if (!program || program.tenantId !== input.tenantId) throw new Error("ReferrerIdentifier requires a program in the same tenant");
2575
+ }
2576
+ const programId = input.programId ?? null;
2577
+ const kind = normalizeIdentifier(input.kind);
2578
+ const existing = await this.findOne({ where: {
2579
+ tenantId: input.tenantId,
2580
+ kind,
2581
+ normalizedValue: normalizeIdentifier(input.value)
2582
+ } });
2583
+ if (existing) {
2584
+ if (existing.isActive() && existing.referrerId === input.referrerId && existing.programId === programId) return existing;
2585
+ throw new ReferrerIdentifierConflictError();
2586
+ }
2587
+ try {
2588
+ return await this.create({
2589
+ tenantId: input.tenantId,
2590
+ referrerId: input.referrerId,
2591
+ programId,
2592
+ kind,
2593
+ value: input.value,
2594
+ metadata: JSON.stringify(input.metadata ?? {})
2595
+ });
2596
+ } catch (error) {
2597
+ if (isUniqueViolationError(error)) throw new ReferrerIdentifierConflictError(error);
2598
+ throw error;
2599
+ }
2600
+ }
2601
+ };
2602
+ //#endregion
2443
2603
  //#region src/referrals/recipes.ts
2444
2604
  var AffiliatesReferralsRecipe = class extends SmrtRecipe {
2445
2605
  static id = "affiliates.referrals";
@@ -2639,7 +2799,7 @@ var AffiliatesReferralsRecipe = class extends SmrtRecipe {
2639
2799
  };
2640
2800
  //#endregion
2641
2801
  //#region src/referrals/services/AttributionService.ts
2642
- var MS_PER_DAY = 1440 * 60 * 1e3;
2802
+ var MS_PER_DAY$1 = 1440 * 60 * 1e3;
2643
2803
  var QualifiedReferralOverrideError = class extends Error {
2644
2804
  constructor(referralIds) {
2645
2805
  super(`AttributionService.override: target already has qualified referral(s) [${referralIds.join(", ")}] \u2014 qualified credit is governed by term snapshots and commission adjustments downstream, not re-attribution.`);
@@ -2683,12 +2843,12 @@ var AttributionService = class AttributionService {
2683
2843
  * them. Nothing left → `refused: 'no_eligible_touches'`.
2684
2844
  * 5. **Conflicts** — `conflictBehavior: 'review'` with more than one
2685
2845
  * distinct eligible referrer, exact-timestamp ties between distinct
2686
- * referrers in `first_touch`/`last_touch`, or competing manual
2687
- * assignments in `assigned` mode → an OPEN AttributionException
2846
+ * referrers in `first_touch`/`last_touch`, or competing assignments or nominations
2847
+ * for different referrers in `assigned` mode → an OPEN AttributionException
2688
2848
  * carrying the candidates; NO referral rows.
2689
2849
  * 6. **Credit** — otherwise the mode elects the winner(s):
2690
2850
  * `first_touch`/`last_touch` (earliest/latest), `assigned` (most
2691
- * recent manual assignment; assignments beat clicks by definition),
2851
+ * recent assignment-grade touch, either a manual assignment or nomination),
2692
2852
  * or `split` (every distinct eligible referrer, equal fractions
2693
2853
  * rounded to 4 dp with the remainder on the last, one shared
2694
2854
  * `splitGroupId`). Referrals are created `pending → attributed` with
@@ -2697,17 +2857,9 @@ var AttributionService = class AttributionService {
2697
2857
  */
2698
2858
  async resolve(input) {
2699
2859
  const now = input.now ?? /* @__PURE__ */ new Date();
2700
- const existing = (await this.deps.referrals.findByTarget(input.targetKind, input.targetId)).filter((referral) => referral.programId === input.programId && (referral.status === "attributed" || referral.status === "qualified"));
2701
- if (existing.length > 0) return {
2702
- referrals: existing,
2703
- exception: null
2704
- };
2705
- const openException = await this.deps.exceptions.findOpenByTarget(input.targetKind, input.targetId, input.programId);
2706
- if (openException) return {
2707
- referrals: [],
2708
- exception: openException
2709
- };
2710
2860
  const program = await this.requireProgram(input.programId);
2861
+ const existing = await this.findExistingResolution(input, program.tenantId);
2862
+ if (existing) return existing;
2711
2863
  const policy = await this.resolvePolicy(program, input.policyKey, now);
2712
2864
  if (!policy) return {
2713
2865
  referrals: [],
@@ -2719,7 +2871,7 @@ var AttributionService = class AttributionService {
2719
2871
  exception: null,
2720
2872
  refused: "existing_client_ineligible"
2721
2873
  };
2722
- const eligible = await this.gatherEligibleTouches(input, policy, now);
2874
+ const eligible = await this.gatherEligibleTouches(input, program.tenantId, policy, now);
2723
2875
  if (eligible.length === 0) return {
2724
2876
  referrals: [],
2725
2877
  exception: null,
@@ -2769,7 +2921,7 @@ var AttributionService = class AttributionService {
2769
2921
  };
2770
2922
  }
2771
2923
  case "assigned": {
2772
- const assignments = eligible.filter((touch) => touch.kind === "manual_assignment");
2924
+ const assignments = eligible.filter((touch) => touch.kind === "manual_assignment" || touch.kind === "nomination");
2773
2925
  if (assignments.length === 0) return {
2774
2926
  referrals: [],
2775
2927
  exception: null,
@@ -2874,8 +3026,12 @@ var AttributionService = class AttributionService {
2874
3026
  const exception = await this.deps.exceptions.get({ id: input.exceptionId });
2875
3027
  if (!exception) throw new Error(`AttributionService.resolveException: exception '${input.exceptionId}' not found`);
2876
3028
  if (!exception.isOpen()) throw new Error(`AttributionService.resolveException: exception '${input.exceptionId}' is already resolved`);
2877
- const policyPin = await this.resolvePolicyPin(exception);
2878
3029
  const candidates = exception.getCandidates();
3030
+ if (exception.conflictReason === "nomination_unresolved" || candidates.some((candidate) => candidate.kind === "nomination")) for (const { referrerId } of input.awards) {
3031
+ const referrer = await this.deps.referrers.get({ id: referrerId });
3032
+ if (!referrer?.isActive() || referrer.tenantId !== exception.tenantId) throw new Error("Nomination awards require active referrers in the same tenant");
3033
+ }
3034
+ const policyPin = await this.resolvePolicyPin(exception);
2879
3035
  const splitGroupId = input.awards.length > 1 ? randomUUID() : "";
2880
3036
  const referrals = [];
2881
3037
  for (const award of input.awards) {
@@ -2998,6 +3154,20 @@ var AttributionService = class AttributionService {
2998
3154
  exception
2999
3155
  };
3000
3156
  }
3157
+ /** Return already attributed credit or an open review for this target and tenant. */
3158
+ async findExistingResolution(input, tenantId) {
3159
+ const existing = (await this.deps.referrals.findByTarget(input.targetKind, input.targetId)).filter((referral) => referral.programId === input.programId && referral.tenantId === tenantId && (referral.status === "attributed" || referral.status === "qualified"));
3160
+ if (existing.length > 0) return {
3161
+ referrals: existing,
3162
+ exception: null
3163
+ };
3164
+ const openException = await this.deps.exceptions.findOpenByTarget(input.targetKind, input.targetId, input.programId, tenantId);
3165
+ if (openException) return {
3166
+ referrals: [],
3167
+ exception: openException
3168
+ };
3169
+ return null;
3170
+ }
3001
3171
  async requireProgram(programId) {
3002
3172
  const program = await this.deps.programs.get({ id: programId });
3003
3173
  if (!program) throw new Error(`AttributionService: program '${programId}' not found`);
@@ -3019,25 +3189,29 @@ var AttributionService = class AttributionService {
3019
3189
  * to `occurredAt` within `[now - windowDays, now]`, and to referrers that
3020
3190
  * pass the self-referral gate. Sorted by `occurredAt` ascending.
3021
3191
  */
3022
- async gatherEligibleTouches(input, policy, now) {
3192
+ async gatherEligibleTouches(input, tenantId, policy, now) {
3023
3193
  const byId = /* @__PURE__ */ new Map();
3024
3194
  if (input.subjectKind && input.subjectId) for (const touch of await this.deps.touches.findBySubject(input.subjectKind, input.subjectId)) byId.set(touch.id ?? "", touch);
3025
3195
  for (const touch of await this.deps.touches.findBySubject(input.targetKind, input.targetId)) byId.set(touch.id ?? "", touch);
3026
- const windowStart = now.getTime() - policy.windowDays * MS_PER_DAY;
3196
+ const windowStart = now.getTime() - policy.windowDays * MS_PER_DAY$1;
3027
3197
  const inWindow = [...byId.values()].filter((touch) => {
3028
- if (touch.programId !== input.programId) return false;
3198
+ if (touch.programId !== input.programId || touch.tenantId !== tenantId) return false;
3029
3199
  const at = touch.occurredAt.getTime();
3030
3200
  return at >= windowStart && at <= now.getTime();
3031
3201
  });
3032
- let eligible = inWindow;
3033
- if (!policy.allowSelfReferral && input.subjectProfileId) {
3034
- const referrerProfiles = /* @__PURE__ */ new Map();
3035
- for (const touch of inWindow) {
3036
- if (referrerProfiles.has(touch.referrerId)) continue;
3037
- const referrer = await this.deps.referrers.get({ id: touch.referrerId });
3038
- referrerProfiles.set(touch.referrerId, referrer?.profileId ?? "");
3202
+ const eligible = [];
3203
+ const referrers = /* @__PURE__ */ new Map();
3204
+ const checkSelfReferral = !policy.allowSelfReferral && !!input.subjectProfileId;
3205
+ for (const touch of inWindow) {
3206
+ if (touch.kind !== "nomination" && !checkSelfReferral) {
3207
+ eligible.push(touch);
3208
+ continue;
3039
3209
  }
3040
- eligible = inWindow.filter((touch) => referrerProfiles.get(touch.referrerId) !== input.subjectProfileId);
3210
+ if (!referrers.has(touch.referrerId)) referrers.set(touch.referrerId, await this.deps.referrers.get({ id: touch.referrerId }));
3211
+ const referrer = referrers.get(touch.referrerId);
3212
+ if (touch.kind === "nomination" && (!referrer?.isActive() || referrer.tenantId !== tenantId)) continue;
3213
+ if (checkSelfReferral && referrer?.profileId === input.subjectProfileId) continue;
3214
+ eligible.push(touch);
3041
3215
  }
3042
3216
  return eligible.sort((a, b) => a.occurredAt.getTime() - b.occurredAt.getTime());
3043
3217
  }
@@ -3152,7 +3326,7 @@ var AttributionService = class AttributionService {
3152
3326
  status: "pending"
3153
3327
  });
3154
3328
  referral.markAttributed(params.now);
3155
- referral.expiresAt = pin.windowDays !== null ? new Date(params.now.getTime() + pin.windowDays * MS_PER_DAY) : null;
3329
+ referral.expiresAt = pin.windowDays !== null ? new Date(params.now.getTime() + pin.windowDays * MS_PER_DAY$1) : null;
3156
3330
  await referral.save();
3157
3331
  return referral;
3158
3332
  }
@@ -3204,6 +3378,8 @@ var ReferralAgreementExecutionService = class {
3204
3378
  now;
3205
3379
  async requestSignature(input) {
3206
3380
  this.assertTenant(input.tenantId);
3381
+ const { executionService } = this.deps;
3382
+ if (!executionService) throw new Error("Requesting a signature requires an AgreementExecutionService");
3207
3383
  const agreement = await this.requireAgreement(input.agreementId);
3208
3384
  this.assertAgreementTenant(agreement, input.tenantId);
3209
3385
  if (!agreement.id || agreement.status !== "draft") throw new Error("Only a persisted draft ReferralAgreement can be sent");
@@ -3212,7 +3388,7 @@ var ReferralAgreementExecutionService = class {
3212
3388
  const idempotencyKey = `${input.tenantId}:${REFERRAL_AGREEMENT_SOURCE_KIND}:${agreement.id}:v${agreement.version}`;
3213
3389
  let result;
3214
3390
  try {
3215
- result = await this.deps.executionService.createExecution({
3391
+ result = await executionService.createExecution({
3216
3392
  tenantId: input.tenantId,
3217
3393
  idempotencyKey,
3218
3394
  sourceKind: REFERRAL_AGREEMENT_SOURCE_KIND,
@@ -3458,6 +3634,330 @@ var ReferralCommissionService = class ReferralCommissionService {
3458
3634
  }
3459
3635
  };
3460
3636
  //#endregion
3637
+ //#region src/referrals/services/ReferralNominationResolver.ts
3638
+ var EMAIL = /[\p{L}\p{N}.!#$%&'*+/=?^_`{|}~-]+@[\p{L}\p{N}-]+(?:\.[\p{L}\p{N}-]+)+/gu;
3639
+ var CODE = new RegExp(`^[a-z0-9]{10}$`, "u");
3640
+ var MIN_NAME_SCORE = .85;
3641
+ var MIN_NAME_MARGIN = .12;
3642
+ var MAX_NOMINATION_BYTES = 1024;
3643
+ var MS_PER_DAY = 1440 * 60 * 1e3;
3644
+ var ReferralNominationResolver = class ReferralNominationResolver {
3645
+ constructor(touches, referrals, exceptions, policies, programs, referrers, links, identifiers) {
3646
+ this.touches = touches;
3647
+ this.referrals = referrals;
3648
+ this.exceptions = exceptions;
3649
+ this.policies = policies;
3650
+ this.programs = programs;
3651
+ this.referrers = referrers;
3652
+ this.links = links;
3653
+ this.identifiers = identifiers;
3654
+ this.attribution = new AttributionService({
3655
+ touches,
3656
+ referrals,
3657
+ exceptions,
3658
+ policies,
3659
+ programs,
3660
+ referrers
3661
+ });
3662
+ }
3663
+ touches;
3664
+ referrals;
3665
+ exceptions;
3666
+ policies;
3667
+ programs;
3668
+ referrers;
3669
+ links;
3670
+ identifiers;
3671
+ attribution;
3672
+ static async create(options = {}) {
3673
+ const touches = await ReferralTouchCollection.create(options);
3674
+ const shared = {
3675
+ ...options,
3676
+ db: touches.db,
3677
+ _reuseInitializedDb: true,
3678
+ _deferRuntimeInitialization: true
3679
+ };
3680
+ return new ReferralNominationResolver(touches, await ReferralCollection.create(shared), await AttributionExceptionCollection.create(shared), await AttributionPolicyCollection.create(shared), await ReferralProgramCollection.create(shared), await ReferrerCollection.create(shared), await ReferralLinkCollection.create(shared), await ReferrerIdentifierCollection.create(shared));
3681
+ }
3682
+ /** Record immutable evidence for a confidently matched prospect at intake. */
3683
+ async recordNomination(input) {
3684
+ return await inTenant(input.tenantId, async () => {
3685
+ if (!(await this.requireProgram(input)).isActive()) return null;
3686
+ const tags = parseNomination(input);
3687
+ const occurredAt = input.occurredAt ?? input.now ?? /* @__PURE__ */ new Date();
3688
+ return (await this.recordMatch(input, tags, occurredAt)).touch;
3689
+ });
3690
+ }
3691
+ /**
3692
+ * Apply the program's policy to a prospect's nomination and existing touches.
3693
+ * Like AttributionService, use a caller transaction and serialize writes
3694
+ * per target and program when multiple workers can qualify the same target.
3695
+ */
3696
+ async resolve(input) {
3697
+ assertTenantLane(input.tenantId);
3698
+ const program = await this.requireProgram(input);
3699
+ const existing = await this.attribution.findExistingResolution(input, input.tenantId);
3700
+ if (existing) return existing;
3701
+ if (!program.isActive()) return {
3702
+ referrals: [],
3703
+ exception: null,
3704
+ refused: "no_eligible_touches"
3705
+ };
3706
+ const now = input.now ?? /* @__PURE__ */ new Date();
3707
+ const policy = await this.policies.latestActiveByKey(program.defaultAttributionPolicyKey, now, input.tenantId);
3708
+ if (!program.defaultAttributionPolicyKey || !policy) return {
3709
+ referrals: [],
3710
+ exception: null,
3711
+ refused: "no_active_policy"
3712
+ };
3713
+ if (input.isExistingClient && !policy.allowExistingClients) return {
3714
+ referrals: [],
3715
+ exception: null,
3716
+ refused: "existing_client_ineligible"
3717
+ };
3718
+ const tags = parseNomination(input);
3719
+ const occurredAt = input.occurredAt ?? now;
3720
+ if (occurredAt > now || occurredAt.getTime() < now.getTime() - policy.windowDays * MS_PER_DAY) return await this.attribution.resolve({
3721
+ ...input,
3722
+ now
3723
+ });
3724
+ const { touch, candidates } = await this.recordMatch(input, tags, occurredAt);
3725
+ if (touch) return await this.attribution.resolve({
3726
+ ...input,
3727
+ now
3728
+ });
3729
+ return {
3730
+ referrals: [],
3731
+ exception: await this.exceptions.create({
3732
+ tenantId: input.tenantId,
3733
+ programId: input.programId,
3734
+ targetKind: input.targetKind,
3735
+ targetId: input.targetId,
3736
+ status: "open",
3737
+ conflictReason: "nomination_unresolved",
3738
+ candidates: JSON.stringify(candidates.map((referrerId) => ({
3739
+ touchId: "",
3740
+ referrerId,
3741
+ kind: "nomination",
3742
+ occurredAt: occurredAt.toISOString()
3743
+ }))),
3744
+ metadata: JSON.stringify({
3745
+ ...nominationInputs(input),
3746
+ subjectKind: input.subjectKind,
3747
+ subjectId: input.subjectId,
3748
+ policyKey: policy.policyKey,
3749
+ policyVersion: policy.version,
3750
+ windowDays: policy.windowDays
3751
+ })
3752
+ })
3753
+ };
3754
+ }
3755
+ /**
3756
+ * Remember a verified alias for a referrer awarded credit through
3757
+ * AttributionService.resolveException. May join the same host transaction.
3758
+ */
3759
+ async registerResolvedIdentifier(input) {
3760
+ return await inTenant(input.tenantId, async () => {
3761
+ const exception = await this.exceptions.get({ id: input.exceptionId });
3762
+ if (!exception || exception.tenantId !== input.tenantId || exception.status !== "resolved" || exception.conflictReason !== "nomination_unresolved") throw new Error("A resolved nomination exception in the same tenant is required");
3763
+ for (const id of exception.getResolvedReferralIds()) {
3764
+ const referral = await this.referrals.get({ id });
3765
+ if (referral?.tenantId === input.tenantId && referral.referrerId === input.referrerId && referral.programId === exception.programId) return await this.identifiers.register({
3766
+ ...input,
3767
+ programId: exception.programId,
3768
+ metadata: {
3769
+ nominationExceptionId: exception.id,
3770
+ confirmedByProfileId: exception.resolvedByProfileId
3771
+ }
3772
+ });
3773
+ }
3774
+ throw new Error("The referrer did not receive credit from this nomination exception");
3775
+ });
3776
+ }
3777
+ async requireProgram(input) {
3778
+ const program = await this.programs.get({ id: input.programId });
3779
+ if (!program || program.tenantId !== input.tenantId) throw new Error("Referral nomination requires a program in the same tenant");
3780
+ return program;
3781
+ }
3782
+ async recordMatch(input, tags, occurredAt) {
3783
+ const id = nominationUuid([
3784
+ "referral-nomination",
3785
+ input.tenantId,
3786
+ input.programId,
3787
+ input.subjectKind,
3788
+ input.subjectId,
3789
+ tags.text,
3790
+ normalizeIdentifier(input.nominationEmail ?? ""),
3791
+ normalizeIdentifier(input.nominationCode ?? "")
3792
+ ]);
3793
+ const stored = await this.touches.get({ id });
3794
+ if (stored) {
3795
+ if (stored.tenantId !== input.tenantId || stored.programId !== input.programId || stored.kind !== "nomination" || stored.subjectKind !== input.subjectKind || stored.subjectId !== input.subjectId) throw new Error("Referral nomination touch identity is already in use");
3796
+ return {
3797
+ touch: stored,
3798
+ candidates: []
3799
+ };
3800
+ }
3801
+ const { match, candidates } = await this.findMatch(input, tags);
3802
+ if (!match) return {
3803
+ touch: null,
3804
+ candidates
3805
+ };
3806
+ const evidence = {
3807
+ ...nominationInputs(input),
3808
+ matchedBy: match.matchedBy,
3809
+ matchedIdentifierId: match.matchedIdentifierId
3810
+ };
3811
+ return {
3812
+ touch: await this.touches.create({
3813
+ id,
3814
+ _insertOnly: true,
3815
+ tenantId: input.tenantId,
3816
+ programId: input.programId,
3817
+ referrerId: match.referrerId,
3818
+ ...match.linkId && {
3819
+ linkId: match.linkId,
3820
+ code: match.code
3821
+ },
3822
+ kind: "nomination",
3823
+ subjectKind: input.subjectKind,
3824
+ subjectId: input.subjectId,
3825
+ occurredAt,
3826
+ evidence: JSON.stringify(evidence)
3827
+ }),
3828
+ candidates: []
3829
+ };
3830
+ }
3831
+ async findMatch(input, tags) {
3832
+ const matches = /* @__PURE__ */ new Map();
3833
+ const active = await this.referrers.list({ where: {
3834
+ tenantId: input.tenantId,
3835
+ status: "active"
3836
+ } });
3837
+ const activeIds = new Set(active.map((referrer) => referrer.id));
3838
+ const aliases = [
3839
+ ...tags.emails.map((value) => ({
3840
+ kind: "email",
3841
+ value
3842
+ })),
3843
+ ...tags.codes.map((value) => ({
3844
+ kind: "code",
3845
+ value
3846
+ })),
3847
+ ...[.../* @__PURE__ */ new Set([tags.text, tags.name])].map((value) => ({
3848
+ kind: "name",
3849
+ value
3850
+ })),
3851
+ ...tags.text.startsWith("@") ? [{
3852
+ kind: "handle",
3853
+ value: tags.text
3854
+ }] : []
3855
+ ];
3856
+ for (const { kind, value } of aliases) {
3857
+ if (!value) continue;
3858
+ const identifiers = await this.identifiers.list({ where: {
3859
+ tenantId: input.tenantId,
3860
+ kind,
3861
+ normalizedValue: value,
3862
+ status: "active"
3863
+ } });
3864
+ for (const alias of identifiers) if ((alias.programId === null || alias.programId === input.programId) && activeIds.has(alias.referrerId)) matches.set(alias.referrerId, {
3865
+ referrerId: alias.referrerId,
3866
+ matchedBy: "identifier",
3867
+ matchedIdentifierId: alias.id ?? void 0
3868
+ });
3869
+ }
3870
+ for (const code of tags.codes) {
3871
+ const link = await this.links.findByCode(code);
3872
+ if (link?.tenantId === input.tenantId && link.programId === input.programId && link.isActive() && activeIds.has(link.referrerId) && !matches.has(link.referrerId)) matches.set(link.referrerId, {
3873
+ referrerId: link.referrerId,
3874
+ matchedBy: "link_code",
3875
+ linkId: link.id ?? void 0,
3876
+ code
3877
+ });
3878
+ }
3879
+ if (matches.size > 0) {
3880
+ const exact = [...matches.values()];
3881
+ return {
3882
+ match: exact.length === 1 ? exact[0] : void 0,
3883
+ candidates: [...matches.keys()].sort()
3884
+ };
3885
+ }
3886
+ return matchName(active, tags.name);
3887
+ }
3888
+ };
3889
+ function nominationInputs(input) {
3890
+ return {
3891
+ nominationText: input.nominationText,
3892
+ nominationEmail: input.nominationEmail,
3893
+ nominationCode: input.nominationCode,
3894
+ actorProfileId: input.actorProfileId
3895
+ };
3896
+ }
3897
+ async function inTenant(tenantId, run) {
3898
+ const activeTenant = assertTenantLane(tenantId);
3899
+ return tenantId && !activeTenant ? await withTenant({ tenantId }, run) : await run();
3900
+ }
3901
+ function assertTenantLane(tenantId) {
3902
+ const activeTenant = getTenantId();
3903
+ if (activeTenant && activeTenant !== tenantId) throw new Error("Referral nomination tenant mismatch");
3904
+ return activeTenant;
3905
+ }
3906
+ function parseNomination(input) {
3907
+ const text = normalizeIdentifier(input.nominationText);
3908
+ const email = normalizeIdentifier(input.nominationEmail ?? "");
3909
+ const code = normalizeIdentifier(input.nominationCode ?? "");
3910
+ if (input.occurredAt && !Number.isFinite(input.occurredAt.getTime()) || input.now && !Number.isFinite(input.now.getTime()) || !input.subjectKind.trim() || !input.subjectId.trim() || !(text || email || code) || Buffer.byteLength(input.nominationText + (input.nominationEmail ?? "") + (input.nominationCode ?? "")) > MAX_NOMINATION_BYTES) throw new Error("Referral nomination requires a subject and at most 1024 bytes of non-empty nomination input");
3911
+ const words = text.replace(EMAIL, " ").match(/[\p{L}\p{N}]+/gu) ?? [];
3912
+ return {
3913
+ text,
3914
+ emails: [...new Set([email, ...text.match(EMAIL) ?? []].filter(Boolean))],
3915
+ codes: [...new Set([code, ...words.filter((word) => CODE.test(word))].filter(Boolean))],
3916
+ name: words.filter((word) => (word !== code || text === code) && !(CODE.test(word) && /\d/u.test(word))).join(" ")
3917
+ };
3918
+ }
3919
+ function matchName(referrers, name) {
3920
+ const words = nameWords(name);
3921
+ if (words.length === 0) return { candidates: [] };
3922
+ const ranked = referrers.flatMap((referrer) => referrer.id ? [{
3923
+ referrerId: referrer.id,
3924
+ score: scoreName(words, nameWords(referrer.displayName))
3925
+ }] : []).sort((a, b) => b.score - a.score || a.referrerId.localeCompare(b.referrerId));
3926
+ const best = ranked[0];
3927
+ if (!best || best.score < MIN_NAME_SCORE) return { candidates: [] };
3928
+ const contenders = ranked.filter(({ score }) => best.score - score < MIN_NAME_MARGIN);
3929
+ return {
3930
+ match: contenders.length === 1 ? {
3931
+ referrerId: best.referrerId,
3932
+ matchedBy: "fuzzy_name"
3933
+ } : void 0,
3934
+ candidates: contenders.map(({ referrerId }) => referrerId)
3935
+ };
3936
+ }
3937
+ function nameWords(value) {
3938
+ return normalizeIdentifier(value).normalize("NFKD").replace(/\p{M}/gu, "").match(/[\p{L}\p{N}]+/gu) ?? [];
3939
+ }
3940
+ function scoreName(nomination, name) {
3941
+ if (name.length === 0 || name.length > nomination.length) return 0;
3942
+ const expected = name.join(" ");
3943
+ let best = 0;
3944
+ for (let i = 0; i <= nomination.length - name.length; i += 1) {
3945
+ const candidate = nomination.slice(i, i + name.length).join(" ");
3946
+ const score = 1 - editDistance(candidate, expected) / Math.max(candidate.length, expected.length);
3947
+ best = Math.max(best, score);
3948
+ }
3949
+ return best;
3950
+ }
3951
+ function editDistance(a, b) {
3952
+ let row = Array.from({ length: b.length + 1 }, (_, index) => index);
3953
+ for (let i = 0; i < a.length; i += 1) {
3954
+ const next = [i + 1];
3955
+ for (let j = 0; j < b.length; j += 1) next.push(Math.min(next[j] + 1, row[j + 1] + 1, row[j] + Number(a[i] !== b[j])));
3956
+ row = next;
3957
+ }
3958
+ return row[b.length];
3959
+ }
3960
+ //#endregion
3461
3961
  //#region src/referrals/services/ReferralQualificationService.ts
3462
3962
  var ReferralQualificationService = class ReferralQualificationService {
3463
3963
  constructor(deps) {
@@ -3694,6 +4194,6 @@ var ReferralQualificationService = class ReferralQualificationService {
3694
4194
  }
3695
4195
  };
3696
4196
  //#endregion
3697
- export { ReferralClickOperationCollection as A, ATTRIBUTION_POLICY_STATUSES as B, generateReferralCode as C, assertHttpTargetUrl as D, ReferralLink as E, AttributionPolicy as F, REFERRAL_PROGRAM_STATUSES as G, REFERRAL_AGREEMENT_APPROVAL_MODES as H, validateAttributionPolicyTerms as I, REFERRER_STATUSES as J, REFERRAL_STATUSES as K, ATTRIBUTION_CONFLICT_BEHAVIORS as L, ReferralAgreementCollection as M, ReferralAgreement as N, ReferralCollection as O, AttributionPolicyCollection as P, ATTRIBUTION_CREDIT_MODES as R, ReferralLinkCollection as S, ReferralTouch as T, REFERRAL_AGREEMENT_STATUSES as U, ATTRIBUTION_RESOLUTION_MODES as V, REFERRAL_LINK_STATUSES as W, AttributionException as X, AttributionExceptionCollection as Y, MAX_REFERRAL_CLICK_IDEMPOTENCY_KEY_BYTES as _, ReferralAgreementExecutionService as a, ReferralClickReplayConflictError as b, AffiliatesReferralsRecipe as c, ReferralTermSnapshotCollection as d, ReferralTermSnapshot as f, MAX_CODE_GENERATION_ATTEMPTS as g, DEFAULT_REFERRAL_CLICK_EVIDENCE_MAX_BYTES as h, REFERRAL_AGREEMENT_SOURCE_KIND as i, ReferralClickOperation as j, Referral as k, ReferrerCollection as l, ReferralProgram as m, REFERRAL_TERMS_SNAPSHOT_KIND as n, AttributionService as o, ReferralProgramCollection as p, REFERRAL_TOUCH_KINDS as q, ReferralCommissionService as r, QualifiedReferralOverrideError as s, ReferralQualificationService as t, Referrer as u, REFERRAL_CODE_ALPHABET as v, ReferralTouchCollection as w, ReferralClickValidationError as x, REFERRAL_CODE_LENGTH as y, ATTRIBUTION_EXCEPTION_STATUSES as z };
4197
+ export { AttributionExceptionCollection as $, ReferralLink as A, validateAttributionPolicyTerms as B, REFERRAL_CODE_LENGTH as C, generateReferralCode as D, ReferralLinkCollection as E, ReferralClickOperation as F, ATTRIBUTION_RESOLUTION_MODES as G, ATTRIBUTION_CREDIT_MODES as H, ReferralAgreementCollection as I, REFERRAL_LINK_STATUSES as J, REFERRAL_AGREEMENT_APPROVAL_MODES as K, ReferralAgreement as L, ReferralCollection as M, Referral as N, ReferralTouchCollection as O, ReferralClickOperationCollection as P, REFERRER_STATUSES as Q, AttributionPolicyCollection as R, REFERRAL_CODE_ALPHABET as S, ReferralClickValidationError as T, ATTRIBUTION_EXCEPTION_STATUSES as U, ATTRIBUTION_CONFLICT_BEHAVIORS as V, ATTRIBUTION_POLICY_STATUSES as W, REFERRAL_STATUSES as X, REFERRAL_PROGRAM_STATUSES as Y, REFERRAL_TOUCH_KINDS as Z, ReferralProgramCollection as _, REFERRAL_AGREEMENT_SOURCE_KIND as a, MAX_CODE_GENERATION_ATTEMPTS as b, QualifiedReferralOverrideError as c, ReferrerIdentifierConflictError as d, AttributionException as et, ReferrerIdentifier as f, ReferralTermSnapshot as g, ReferralTermSnapshotCollection as h, ReferralCommissionService as i, assertHttpTargetUrl as j, ReferralTouch as k, AffiliatesReferralsRecipe as l, Referrer as m, ReferralNominationResolver as n, ReferralAgreementExecutionService as o, ReferrerCollection as p, REFERRAL_AGREEMENT_STATUSES as q, REFERRAL_TERMS_SNAPSHOT_KIND as r, AttributionService as s, ReferralQualificationService as t, ReferrerIdentifierCollection as u, ReferralProgram as v, ReferralClickReplayConflictError as w, MAX_REFERRAL_CLICK_IDEMPOTENCY_KEY_BYTES as x, DEFAULT_REFERRAL_CLICK_EVIDENCE_MAX_BYTES as y, AttributionPolicy as z };
3698
4198
 
3699
- //# sourceMappingURL=referrals-DQaEehr8.js.map
4199
+ //# sourceMappingURL=referrals-STQ8kdIv.js.map