@happyvertical/smrt-sales 0.57.45 → 0.57.47

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 (33) hide show
  1. package/AGENTS.md +1 -1
  2. package/agents/commissions.md +3 -3
  3. package/dist/agreements.js +1 -1
  4. package/dist/chunks/__smrt-register__-D1H7oo6b.js +6 -0
  5. package/dist/chunks/__smrt-register__-D1H7oo6b.js.map +1 -0
  6. package/dist/chunks/{commissions-B1WnBKsn.js → commissions-DbhfPQbi.js} +78 -36
  7. package/dist/chunks/commissions-DbhfPQbi.js.map +1 -0
  8. package/dist/chunks/{referrals-DE0tKm5G.js → referrals-DQaEehr8.js} +2 -2
  9. package/dist/chunks/{referrals-DE0tKm5G.js.map → referrals-DQaEehr8.js.map} +1 -1
  10. package/dist/commissions/collections/CommissionCollection.d.ts +8 -2
  11. package/dist/commissions/collections/CommissionCollection.d.ts.map +1 -1
  12. package/dist/commissions/collections/CommissionPayoutCollection.d.ts +8 -2
  13. package/dist/commissions/collections/CommissionPayoutCollection.d.ts.map +1 -1
  14. package/dist/commissions/collections/EarningEventCollection.d.ts +12 -5
  15. package/dist/commissions/collections/EarningEventCollection.d.ts.map +1 -1
  16. package/dist/commissions/models/Commission.d.ts.map +1 -1
  17. package/dist/commissions/models/CommissionPayout.d.ts.map +1 -1
  18. package/dist/commissions/models/EarningEvent.d.ts +5 -5
  19. package/dist/commissions/models/EarningEvent.d.ts.map +1 -1
  20. package/dist/commissions/replay-owner.d.ts +35 -0
  21. package/dist/commissions/replay-owner.d.ts.map +1 -0
  22. package/dist/commissions/services/CommissionCalculationService.d.ts.map +1 -1
  23. package/dist/commissions/services/CommissionPayoutService.d.ts.map +1 -1
  24. package/dist/commissions.js +2 -2
  25. package/dist/crm.js +1 -1
  26. package/dist/index.js +3 -3
  27. package/dist/manifest.json +225 -13
  28. package/dist/referrals.js +2 -2
  29. package/dist/smrt-knowledge.json +16 -10
  30. package/package.json +8 -8
  31. package/dist/chunks/__smrt-register__-CyAtSSJB.js +0 -6
  32. package/dist/chunks/__smrt-register__-CyAtSSJB.js.map +0 -1
  33. package/dist/chunks/commissions-B1WnBKsn.js.map +0 -1
@@ -1,5 +1,5 @@
1
1
  import { SmrtCollection, SmrtObject, crossPackageRef, field, foreignKey, smrt } from "@happyvertical/smrt-core";
2
- import { TenantContextError, TenantScoped, assertTenantReadAllowed, getCurrentTenant, requireTenantId, tenantId } from "@happyvertical/smrt-tenancy";
2
+ import { TenantContextError, TenantIsolationError, TenantScoped, assertTenantReadAllowed, getCurrentTenant, requireTenantId, tenantId } from "@happyvertical/smrt-tenancy";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import { isDeepStrictEqual } from "node:util";
5
5
  //#region src/commissions/models/CommissionAdjustment.ts
@@ -281,6 +281,34 @@ var CommissionAdjustmentOperationCollection = class extends SmrtCollection {
281
281
  }
282
282
  };
283
283
  //#endregion
284
+ //#region src/commissions/replay-owner.ts
285
+ var same = (a, b) => a.toLowerCase() === b.toLowerCase();
286
+ function resolveReplayOwner(tenantId, label) {
287
+ const context = getCurrentTenant()?.tenantId;
288
+ const owner = tenantId || context || null;
289
+ if (owner && context && !same(owner, context)) throw new TenantIsolationError(`Tenant isolation violation in ${label}: context tenant is '${context}' but the replay key belongs to '${owner}'`, {
290
+ tenantId: context,
291
+ attemptedTenantId: owner
292
+ });
293
+ return owner;
294
+ }
295
+ async function findByReplayKey(collection, column, value, owner) {
296
+ return (await collection.query(owner ? `SELECT * FROM ${collection.tableName} WHERE ${column} = ? AND tenant_id = ? ORDER BY created_at, id` : `SELECT * FROM ${collection.tableName} WHERE ${column} = ? AND tenant_id IS NULL ORDER BY created_at, id`, owner ? [value, owner] : [value], { allowRawOnTenantScoped: true })).find((row) => {
297
+ const tenant = row.tenantId;
298
+ return owner ? !!tenant && same(String(tenant), owner) : !tenant;
299
+ }) ?? null;
300
+ }
301
+ function assertWritableInContext(rowTenantId, label) {
302
+ const context = getCurrentTenant()?.tenantId;
303
+ if (context && rowTenantId && !same(rowTenantId, context)) throw new TenantIsolationError(`Tenant isolation violation in ${label}: context tenant '${context}' cannot write a row of tenant '${rowTenantId}'`, {
304
+ tenantId: context,
305
+ attemptedTenantId: rowTenantId
306
+ });
307
+ }
308
+ function rowOwner(rowTenantId) {
309
+ return rowTenantId || getCurrentTenant()?.tenantId || null;
310
+ }
311
+ //#endregion
284
312
  //#region src/commissions/models/Commission.ts
285
313
  var __defProp$5 = Object.defineProperty;
286
314
  var __getOwnPropDesc$5 = Object.getOwnPropertyDescriptor;
@@ -509,6 +537,7 @@ var Commission = class extends SmrtObject {
509
537
  * persisted row may only advance one legal step.
510
538
  */
511
539
  async save(options) {
540
+ assertWritableInContext(this.tenantId, "Commission.save");
512
541
  const prior = await this.resolvePriorStatus();
513
542
  this.assertStatusTransition(prior);
514
543
  await this.assertDedupeKeyNotTaken();
@@ -527,7 +556,8 @@ var Commission = class extends SmrtObject {
527
556
  async assertDedupeKeyNotTaken() {
528
557
  if (!this.dedupeKey) return;
529
558
  try {
530
- const res = await this.db.query(`SELECT CAST(id AS VARCHAR) AS id FROM ${this.tableName} WHERE dedupe_key = $1`, this.dedupeKey);
559
+ const owner = rowOwner(this.tenantId);
560
+ const res = owner ? await this.db.query(`SELECT CAST(id AS VARCHAR) AS id FROM ${this.tableName} WHERE dedupe_key = $1 AND tenant_id = $2`, this.dedupeKey, owner) : await this.db.query(`SELECT CAST(id AS VARCHAR) AS id FROM ${this.tableName} WHERE dedupe_key = $1 AND tenant_id IS NULL`, this.dedupeKey);
531
561
  if ((Array.isArray(res) ? res : res.rows ?? []).find((row) => row.id !== this.id)) throw new Error(`Commission (dedupeKey '${this.dedupeKey}'): a commission with this dedupe key already exists \u2014 commissions are immutable audit rows; corrections append CommissionAdjustments.`);
532
562
  } catch (error) {
533
563
  if (error instanceof Error && error.message.includes("immutable")) throw error;
@@ -568,7 +598,7 @@ __decorateClass$5([field({
568
598
  description: "A reference that stops the same commission being recorded twice."
569
599
  })], Commission.prototype, "dedupeKey", 2);
570
600
  Commission = __decorateClass$5([TenantScoped({ mode: "optional" }), smrt({
571
- conflictColumns: ["dedupe_key"],
601
+ conflictColumns: ["tenant_id", "dedupe_key"],
572
602
  api: { include: [
573
603
  "list",
574
604
  "get",
@@ -602,13 +632,15 @@ var CommissionCollection = class extends SmrtCollection {
602
632
  orderBy: "created_at DESC"
603
633
  });
604
634
  }
605
- /** Look up a commission by its idempotency natural key. */
606
- async findByDedupeKey(dedupeKey) {
635
+ /**
636
+ * Look up a commission by its idempotency natural key within one owner
637
+ * (#3305 D1): `options.tenantId` (the event's tenant, for background
638
+ * calculation), else the active context; neither → global rows only.
639
+ */
640
+ async findByDedupeKey(dedupeKey, options = {}) {
607
641
  if (!dedupeKey) return null;
608
- return (await this.list({
609
- where: { dedupeKey },
610
- limit: 1
611
- }))[0] ?? null;
642
+ const owner = resolveReplayOwner(options.tenantId, "CommissionCollection.findByDedupeKey");
643
+ return findByReplayKey(this, "dedupe_key", dedupeKey, owner);
612
644
  }
613
645
  /**
614
646
  * Payable commissions for an earner+currency that no payout batch has
@@ -1208,6 +1240,7 @@ ${memo}` : memo;
1208
1240
  * was set.
1209
1241
  */
1210
1242
  async save(options) {
1243
+ assertWritableInContext(this.tenantId, "CommissionPayout.save");
1211
1244
  this.validateTotals();
1212
1245
  await this.assertRoutingUnchanged();
1213
1246
  const prior = await this.resolvePriorStatus();
@@ -1243,7 +1276,8 @@ ${memo}` : memo;
1243
1276
  }
1244
1277
  /** Authoritative read also closes blind-id and natural-key upsert doors. */
1245
1278
  async assertRoutingUnchanged() {
1246
- const { rows } = await this.db.query(`SELECT CAST(id AS VARCHAR) AS id, payout_method, payout_destination FROM ${this.tableName} WHERE id = ? OR idempotency_key = ?`, this.id ?? null, this.idempotencyKey || null);
1279
+ const owner = rowOwner(this.tenantId);
1280
+ const { rows } = owner ? await this.db.query(`SELECT CAST(id AS VARCHAR) AS id, payout_method, payout_destination FROM ${this.tableName} WHERE id = ? OR (idempotency_key = ? AND tenant_id = ?)`, this.id ?? null, this.idempotencyKey || null, owner) : await this.db.query(`SELECT CAST(id AS VARCHAR) AS id, payout_method, payout_destination FROM ${this.tableName} WHERE id = ? OR (idempotency_key = ? AND tenant_id IS NULL)`, this.id ?? null, this.idempotencyKey || null);
1247
1281
  for (const row of rows) {
1248
1282
  if (row.id !== this.id) throw new Error("CommissionPayout: existing batch routing is immutable; reuse its idempotency key through the payout service");
1249
1283
  const priorDestination = String(row.payout_destination ?? "{}");
@@ -1300,7 +1334,7 @@ __decorateClass$3([field({
1300
1334
  })], CommissionPayout.prototype, "idempotencyKey", 2);
1301
1335
  __decorateClass$3([field({ indexed: true })], CommissionPayout.prototype, "sourceId", 2);
1302
1336
  CommissionPayout = __decorateClass$3([TenantScoped({ mode: "optional" }), smrt({
1303
- conflictColumns: ["idempotency_key"],
1337
+ conflictColumns: ["tenant_id", "idempotency_key"],
1304
1338
  api: { include: ["list", "get"] },
1305
1339
  mcp: { include: ["list", "get"] },
1306
1340
  cli: { include: ["list", "get"] }
@@ -1330,13 +1364,15 @@ var CommissionPayoutCollection = class extends SmrtCollection {
1330
1364
  orderBy: "created_at DESC"
1331
1365
  });
1332
1366
  }
1333
- /** Look up a payout by its idempotency natural key. */
1334
- async findByIdempotencyKey(idempotencyKey) {
1367
+ /**
1368
+ * Look up a payout by its idempotency natural key within one owner
1369
+ * (#3305 D1): `options.tenantId` (the earner's tenant, for background
1370
+ * settlement), else the active context; neither → global payouts only.
1371
+ */
1372
+ async findByIdempotencyKey(idempotencyKey, options = {}) {
1335
1373
  if (!idempotencyKey) return null;
1336
- return (await this.list({
1337
- where: { idempotencyKey },
1338
- limit: 1
1339
- }))[0] ?? null;
1374
+ const owner = resolveReplayOwner(options.tenantId, "CommissionPayoutCollection.findByIdempotencyKey");
1375
+ return findByReplayKey(this, "idempotency_key", idempotencyKey, owner);
1340
1376
  }
1341
1377
  /**
1342
1378
  * One page of payouts carrying the derived single-source stamp for
@@ -2606,12 +2642,16 @@ var EarningEvent = class extends SmrtObject {
2606
2642
  * finds first and never upserts.
2607
2643
  */
2608
2644
  async save(options) {
2645
+ assertWritableInContext(this.tenantId, "EarningEvent.save");
2609
2646
  const captured = persistedEventState.get(this);
2610
2647
  if (captured !== void 0) {
2611
2648
  if (captured !== this.serializeState()) throw new Error(`EarningEvent ${this.id ?? "<new>"}: earning events are immutable evidence \u2014 record a correcting event (or a CommissionAdjustment downstream) instead of editing this row.`);
2612
2649
  } else if (this.id && await this.isSaved()) throw new Error(`EarningEvent ${this.id}: refusing to overwrite an existing event row from a non-hydrated instance \u2014 earning events are immutable evidence.`);
2613
2650
  else if (this.dedupeKey) try {
2614
- const row = await this.db.get(this.tableName, { dedupe_key: this.dedupeKey });
2651
+ const row = await this.db.get(this.tableName, {
2652
+ tenant_id: rowOwner(this.tenantId),
2653
+ dedupe_key: this.dedupeKey
2654
+ });
2615
2655
  if (row && row.id !== this.id) throw new Error(`EarningEvent (dedupeKey '${this.dedupeKey}'): an event with this dedupe key already exists \u2014 earning events are immutable evidence, and the natural-key upsert would rotate the existing row's id (orphaning commissions that reference it). Use EarningEventCollection.getOrCreateByDedupeKey() for idempotent ingestion, or record a new event under its own dedupe key.`);
2616
2656
  } catch (error) {
2617
2657
  if (error instanceof Error && error.message.includes("immutable evidence")) throw error;
@@ -2693,7 +2733,7 @@ __decorateClass([field({
2693
2733
  })], EarningEvent.prototype, "marginCents", 2);
2694
2734
  __decorateClass([field({ required: true })], EarningEvent.prototype, "dedupeKey", 2);
2695
2735
  EarningEvent = __decorateClass([TenantScoped({ mode: "optional" }), smrt({
2696
- conflictColumns: ["dedupe_key"],
2736
+ conflictColumns: ["tenant_id", "dedupe_key"],
2697
2737
  api: { include: [
2698
2738
  "create",
2699
2739
  "list",
@@ -2706,27 +2746,31 @@ EarningEvent = __decorateClass([TenantScoped({ mode: "optional" }), smrt({
2706
2746
  //#region src/commissions/collections/EarningEventCollection.ts
2707
2747
  var EarningEventCollection = class extends SmrtCollection {
2708
2748
  static _itemClass = EarningEvent;
2709
- /** Look up an event by its idempotency natural key. */
2710
- async findByDedupeKey(dedupeKey) {
2749
+ /**
2750
+ * Look up an event by its idempotency natural key within one owner
2751
+ * (#3305 D1): `options.tenantId`, else the active context; neither →
2752
+ * global events only. Never returns another tenant's event.
2753
+ */
2754
+ async findByDedupeKey(dedupeKey, options = {}) {
2711
2755
  if (!dedupeKey) return null;
2712
- return (await this.list({
2713
- where: { dedupeKey },
2714
- limit: 1
2715
- }))[0] ?? null;
2756
+ const owner = resolveReplayOwner(options.tenantId, "EarningEventCollection.findByDedupeKey");
2757
+ return findByReplayKey(this, "dedupe_key", dedupeKey, owner);
2716
2758
  }
2717
2759
  /**
2718
2760
  * Idempotent ingestion: if an event with `options.dedupeKey` already
2719
2761
  * exists, return it untouched (`created: false`) — evidence is immutable,
2720
2762
  * so a replay never updates the stored row. Otherwise create the event.
2721
2763
  *
2722
- * `dedupeKey` is required — callers embed tenant/source identity in it
2723
- * (e.g. `` `${tenantId}:${sourceKind}:${sourceId}:${eventKind}` ``);
2724
- * an empty key would silently disable idempotency, so it throws instead.
2764
+ * `dedupeKey` is required and unique per tenant (#3305 D1); an empty key
2765
+ * would silently disable idempotency, so it throws instead. The replay
2766
+ * lookup and the create share one owner (`options.tenantId`, else the
2767
+ * context), so a retry finds what it filed and never another tenant's.
2725
2768
  */
2726
2769
  async getOrCreateByDedupeKey(options) {
2727
2770
  const dedupeKey = options.dedupeKey ?? "";
2728
2771
  if (!dedupeKey) throw new Error("EarningEventCollection.getOrCreateByDedupeKey requires a dedupeKey");
2729
- const existing = await this.findByDedupeKey(dedupeKey);
2772
+ const tenantId = resolveReplayOwner(options.tenantId, "EarningEventCollection.getOrCreateByDedupeKey");
2773
+ const existing = await this.findByDedupeKey(dedupeKey, { tenantId });
2730
2774
  if (existing) return {
2731
2775
  event: existing,
2732
2776
  created: false
@@ -2735,6 +2779,7 @@ var EarningEventCollection = class extends SmrtCollection {
2735
2779
  return {
2736
2780
  event: await this.create({
2737
2781
  ...rest,
2782
+ tenantId,
2738
2783
  ...occurredAt !== void 0 ? { occurredAt: new Date(occurredAt) } : {}
2739
2784
  }),
2740
2785
  created: true
@@ -3200,7 +3245,7 @@ var CommissionCalculationService = class CommissionCalculationService {
3200
3245
  }
3201
3246
  const occurrenceIndex = occurrenceCount;
3202
3247
  const dedupeKey = `${event.dedupeKey}:${termsRef}:${component.key}:${input.earnerId}:${occurrenceIndex}`;
3203
- const priorByKey = await this.commissions.findByDedupeKey(dedupeKey);
3248
+ const priorByKey = await this.commissions.findByDedupeKey(dedupeKey, { tenantId: event.tenantId });
3204
3249
  if (priorByKey) {
3205
3250
  existing.push(priorByKey);
3206
3251
  continue;
@@ -3244,10 +3289,7 @@ var CommissionCalculationService = class CommissionCalculationService {
3244
3289
  });
3245
3290
  } catch (error) {
3246
3291
  if (error instanceof Error && error.message.includes("immutable audit rows")) {
3247
- const winner = await this.commissions.list({
3248
- where: { dedupeKey },
3249
- limit: 1
3250
- });
3292
+ const winner = [await this.commissions.findByDedupeKey(dedupeKey, { tenantId: event.tenantId })].filter((row) => row !== null);
3251
3293
  if (winner[0]) {
3252
3294
  existing.push(winner[0]);
3253
3295
  continue;
@@ -3347,7 +3389,7 @@ var CommissionPayoutService = class CommissionPayoutService {
3347
3389
  sourceKind: input.sourceKind,
3348
3390
  sourceId: input.sourceId
3349
3391
  } : void 0);
3350
- const existingPayout = await this.deps.payouts.findByIdempotencyKey(idempotencyKey);
3392
+ const existingPayout = await this.deps.payouts.findByIdempotencyKey(idempotencyKey, { tenantId: earner.tenantId });
3351
3393
  if (existingPayout) {
3352
3394
  if (existingPayout.isPending() && !await this.membershipConsistent(existingPayout)) return {
3353
3395
  ...await this.claimAndReconcile(existingPayout, input),
@@ -4399,4 +4441,4 @@ var EarnerAttributionService = class EarnerAttributionService {
4399
4441
  //#endregion
4400
4442
  export { ADJUSTMENT_SETTLEABLE_COMMISSION_STATUSES as A, PAYOUT_METHODS as B, calculateWaterfallWithPools as C, CommissionPayout as D, CommissionPayoutCollection as E, COMMISSION_STATUSES as F, Commission as G, WATERFALL_POOL_RESIDUAL_RULES as H, EARNER_KINDS as I, CommissionAdjustmentCollection as J, CommissionAdjustmentOperationCollection as K, EARNER_SOURCE_ATTRIBUTION_STATUSES as L, COMMISSION_BASES as M, COMMISSION_PAYOUT_STATUSES as N, Earner as O, COMMISSION_PLAN_STATUSES as P, EARNER_STATUSES as R, calculateWaterfall as S, validateWaterfallPlan as T, WATERFALL_POOL_ZERO_WEIGHT_RULES as U, PAYOUT_METHODS_REQUIRING_DESTINATION as V, CommissionCollection as W, CommissionAdjustment as Y, EarnerCollection as _, CommissionBalanceService as a, validateCommissionPlanComponents as b, CommissionAdjustmentValidationError as c, centsToAmount as d, roundCents as f, EarnerSourceAttribution as g, EarnerSourceAttributionCollection as h, CommissionCalculationService as i, COMMISSION_ADJUSTMENT_KINDS as j, validatePayoutDestination as k, amountToCents as l, EarningEvent as m, CommissionSettlementService as n, CommissionAdjustmentReplayConflictError as o, EarningEventCollection as p, CommissionAdjustmentOperation as q, CommissionPayoutService as r, CommissionAdjustmentService as s, EarnerAttributionService as t, calculateCommissionAmountCents as u, CommissionPlanCollection as v, prepareWaterfallPools as w, WaterfallRecipientResolverRegistry as x, CommissionPlan as y, EARNING_EVENT_KINDS as z };
4401
4443
 
4402
- //# sourceMappingURL=commissions-B1WnBKsn.js.map
4444
+ //# sourceMappingURL=commissions-DbhfPQbi.js.map