@fantastic.dev/better-stripe 0.59.0 → 0.60.0

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 (124) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +3 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +650 -44
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +309 -6
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +618 -12
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +325 -22
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  11. package/dist/client/index.d.ts +4 -0
  12. package/dist/client/index.d.ts.map +1 -1
  13. package/dist/client/paymentSource/resolver.d.ts +12 -1
  14. package/dist/client/paymentSource/resolver.d.ts.map +1 -1
  15. package/dist/client/paymentSource/resolver.fixtures.d.ts +220 -0
  16. package/dist/client/paymentSource/resolver.fixtures.d.ts.map +1 -0
  17. package/dist/client/paymentSource/resolver.fixtures.js +189 -0
  18. package/dist/client/paymentSource/resolver.fixtures.js.map +1 -0
  19. package/dist/client/paymentSource/resolver.js +28 -3
  20. package/dist/client/paymentSource/resolver.js.map +1 -1
  21. package/dist/client/settlement/execution.d.ts +25 -0
  22. package/dist/client/settlement/execution.d.ts.map +1 -1
  23. package/dist/client/settlement/execution.js +2 -0
  24. package/dist/client/settlement/execution.js.map +1 -1
  25. package/dist/client/usage/catalogPrices.d.ts +1 -1
  26. package/dist/client/usage/catalogPrices.d.ts.map +1 -1
  27. package/dist/client/usage/catalogPrices.js +4 -4
  28. package/dist/client/usage/catalogPrices.js.map +1 -1
  29. package/dist/client/usage/client.d.ts +2 -2
  30. package/dist/client/usage/client.js +2 -2
  31. package/dist/client/usage/creditRevenue.d.ts +22 -0
  32. package/dist/client/usage/creditRevenue.d.ts.map +1 -0
  33. package/dist/client/usage/creditRevenue.js +118 -0
  34. package/dist/client/usage/creditRevenue.js.map +1 -0
  35. package/dist/client/usage/creditSettlement.d.ts +29 -0
  36. package/dist/client/usage/creditSettlement.d.ts.map +1 -0
  37. package/dist/client/usage/creditSettlement.fixtures.d.ts +215 -0
  38. package/dist/client/usage/creditSettlement.fixtures.d.ts.map +1 -0
  39. package/dist/client/usage/creditSettlement.fixtures.js +59 -0
  40. package/dist/client/usage/creditSettlement.fixtures.js.map +1 -0
  41. package/dist/client/usage/creditSettlement.js +70 -0
  42. package/dist/client/usage/creditSettlement.js.map +1 -0
  43. package/dist/client/usage/creditTransport.fixtures.d.ts +7 -1
  44. package/dist/client/usage/creditTransport.fixtures.d.ts.map +1 -1
  45. package/dist/client/usage/creditTransport.fixtures.js +25 -4
  46. package/dist/client/usage/creditTransport.fixtures.js.map +1 -1
  47. package/dist/client/usage/index.d.ts +4 -0
  48. package/dist/client/usage/index.d.ts.map +1 -1
  49. package/dist/client/usage/invoiceSale.d.ts +22 -0
  50. package/dist/client/usage/invoiceSale.d.ts.map +1 -0
  51. package/dist/client/usage/invoiceSale.fixtures.d.ts +285 -0
  52. package/dist/client/usage/invoiceSale.fixtures.d.ts.map +1 -0
  53. package/dist/client/usage/invoiceSale.fixtures.js +104 -0
  54. package/dist/client/usage/invoiceSale.fixtures.js.map +1 -0
  55. package/dist/client/usage/invoiceSale.js +117 -0
  56. package/dist/client/usage/invoiceSale.js.map +1 -0
  57. package/dist/client/usage/observationClient.d.ts +2 -2
  58. package/dist/client/usage/observationClient.d.ts.map +1 -1
  59. package/dist/client/usage/settlement.d.ts +32 -0
  60. package/dist/client/usage/settlement.d.ts.map +1 -0
  61. package/dist/client/usage/settlement.js +60 -0
  62. package/dist/client/usage/settlement.js.map +1 -0
  63. package/dist/client/usage/settlementClient.d.ts +51 -0
  64. package/dist/client/usage/settlementClient.d.ts.map +1 -0
  65. package/dist/client/usage/settlementClient.js +35 -0
  66. package/dist/client/usage/settlementClient.js.map +1 -0
  67. package/dist/component/_generated/component.d.ts +125 -0
  68. package/dist/component/_generated/component.d.ts.map +1 -1
  69. package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
  70. package/dist/component/balanceFunding/mutations.d.ts +27 -27
  71. package/dist/component/earnings/triggers.d.ts +156 -6
  72. package/dist/component/earnings/triggers.d.ts.map +1 -1
  73. package/dist/component/financialObservations/settlementHelpers.d.ts.map +1 -1
  74. package/dist/component/financialObservations/settlementHelpers.js +2 -0
  75. package/dist/component/financialObservations/settlementHelpers.js.map +1 -1
  76. package/dist/component/recoveryWorkflow/helpers.d.ts +25 -0
  77. package/dist/component/recoveryWorkflow/helpers.d.ts.map +1 -1
  78. package/dist/component/recoveryWorkflow/mutations.d.ts +25 -0
  79. package/dist/component/recoveryWorkflow/mutations.d.ts.map +1 -1
  80. package/dist/component/recoveryWorkflow/queries.d.ts +50 -0
  81. package/dist/component/recoveryWorkflow/queries.d.ts.map +1 -1
  82. package/dist/component/recoveryWorkflow/schema.d.ts +566 -10
  83. package/dist/component/recoveryWorkflow/schema.d.ts.map +1 -1
  84. package/dist/component/schema.d.ts +309 -6
  85. package/dist/component/settlement/mutations.d.ts +50 -0
  86. package/dist/component/settlement/mutations.d.ts.map +1 -1
  87. package/dist/component/settlement/mutations.js +8 -1
  88. package/dist/component/settlement/mutations.js.map +1 -1
  89. package/dist/component/settlement/queries.d.ts +25 -0
  90. package/dist/component/settlement/queries.d.ts.map +1 -1
  91. package/dist/component/settlement/schema.d.ts +128 -1
  92. package/dist/component/settlement/schema.d.ts.map +1 -1
  93. package/dist/component/settlement/schema.js +22 -0
  94. package/dist/component/settlement/schema.js.map +1 -1
  95. package/docs/README.md +2 -0
  96. package/docs/settlement.md +4 -0
  97. package/docs/usage-settlement.md +162 -0
  98. package/package.json +2 -1
  99. package/src/client/index.ts +9 -0
  100. package/src/client/paymentSource/resolver.fixtures.ts +216 -0
  101. package/src/client/paymentSource/resolver.test.ts +11 -207
  102. package/src/client/paymentSource/resolver.ts +54 -2
  103. package/src/client/settlement/execution.ts +24 -0
  104. package/src/client/usage/catalogPrices.ts +4 -2
  105. package/src/client/usage/client.ts +2 -2
  106. package/src/client/usage/creditRevenue.test.ts +105 -0
  107. package/src/client/usage/creditRevenue.ts +163 -0
  108. package/src/client/usage/creditSettlement.fixtures.ts +70 -0
  109. package/src/client/usage/creditSettlement.test.ts +66 -0
  110. package/src/client/usage/creditSettlement.ts +94 -0
  111. package/src/client/usage/creditSettlementRecovery.test.ts +173 -0
  112. package/src/client/usage/creditTransport.fixtures.ts +29 -4
  113. package/src/client/usage/index.ts +9 -0
  114. package/src/client/usage/invoiceSale.fixtures.ts +103 -0
  115. package/src/client/usage/invoiceSale.test.ts +184 -0
  116. package/src/client/usage/invoiceSale.ts +155 -0
  117. package/src/client/usage/settlement.test.ts +179 -0
  118. package/src/client/usage/settlement.ts +81 -0
  119. package/src/client/usage/settlementClient.ts +84 -0
  120. package/src/component/_generated/component.ts +110 -0
  121. package/src/component/financialObservations/settlementHelpers.ts +2 -0
  122. package/src/component/settlement/mutations.ts +10 -1
  123. package/src/component/settlement/schema.ts +26 -0
  124. package/src/component/settlement/settlement-claims.test.ts +54 -0
@@ -0,0 +1,81 @@
1
+ import { getUsageInvoiceSale } from "./invoiceSale.js";
2
+ import { allocateSale } from "../settlement/allocation.js";
3
+ import { selectCommissionInvoice } from "../settlement/commissions.js";
4
+ import {
5
+ executeResolvedTransfers,
6
+ type ResolvedSettlement,
7
+ } from "../settlement/execution.js";
8
+ import { componentRef } from "../webhooks/helpers.js";
9
+ import type Stripe from "stripe";
10
+ import type { Component, RunCtx } from "../helpers.js";
11
+ import type { SaleAllocationOptions } from "../settlement/allocation.js";
12
+ import type { CommissionTerm } from "../settlement/commissions.js";
13
+ import type { UsageInvoiceSaleOptions } from "./invoiceSale.js";
14
+ export type UsageInvoiceSettlementOptions = UsageInvoiceSaleOptions & {
15
+ policy: Omit<SaleAllocationOptions, "gross" | "processingFee"> & {
16
+ commissionTerm?: CommissionTerm;
17
+ };
18
+ };
19
+ export async function settleUsageInvoice(
20
+ stripe: Stripe,
21
+ component: Component,
22
+ ctx: RunCtx,
23
+ input: UsageInvoiceSettlementOptions,
24
+ ) {
25
+ const sale = await getUsageInvoiceSale(stripe, input);
26
+ if (sale.status !== "ready") return sale;
27
+ const source = sale.value;
28
+ const prior = (await ctx.runQuery(
29
+ componentRef(component, "settlement/queries/getSettlementAllocation"),
30
+ { sourceChargeId: source.chargeId },
31
+ )) as ResolvedSettlement | null;
32
+ if (
33
+ prior &&
34
+ (prior.gross !== source.gross ||
35
+ prior.processingFee !== source.processingFee ||
36
+ prior.currency !== source.currency)
37
+ )
38
+ throw new Error(
39
+ "Retained allocation conflicts with verified invoice proceeds",
40
+ );
41
+ let affiliate = input.policy.affiliate;
42
+ if (affiliate) {
43
+ const commission = await selectCommissionInvoice(stripe, component, ctx, {
44
+ subscriptionId: input.subscription.subscriptionId,
45
+ invoiceId: source.invoiceId,
46
+ affiliateAccountId: affiliate.destinationAccountId,
47
+ term: input.policy.commissionTerm ?? "forever",
48
+ });
49
+ if (commission.status !== "ready") return commission;
50
+ if (!commission.eligible) affiliate = undefined;
51
+ }
52
+ const allocation = allocateSale({
53
+ ...input.policy,
54
+ affiliate,
55
+ gross: source.gross,
56
+ processingFee: source.processingFee,
57
+ });
58
+ return executeResolvedTransfers(stripe, component, ctx, {
59
+ sourceChargeId: source.chargeId,
60
+ paymentIntentId: source.paymentIntentId,
61
+ sourceInvoiceId: source.invoiceId,
62
+ usageSource: {
63
+ stripeAccountId: input.scope.stripeAccountId,
64
+ customerAccount: source.customerAccountId,
65
+ livemode: source.livemode,
66
+ meterId: source.meterId,
67
+ stripePriceId: source.stripePriceId,
68
+ stripeProductId: source.stripeProductId,
69
+ subscriptionId: input.subscription.subscriptionId,
70
+ subscriptionItemId: source.subscriptionItemId,
71
+ invoicePaymentId: source.invoicePaymentId,
72
+ period: source.period,
73
+ model: source.model,
74
+ },
75
+ gross: source.gross,
76
+ currency: source.currency,
77
+ processingFee: source.processingFee,
78
+ platformNet: allocation.platformNet,
79
+ transfers: allocation.transfers,
80
+ });
81
+ }
@@ -0,0 +1,84 @@
1
+ import {
2
+ settleCreditPurchase,
3
+ type UsageCreditSettlementOptions,
4
+ } from "./creditSettlement.js";
5
+ import Stripe from "stripe";
6
+ import type { RunCtx } from "../helpers.js";
7
+ import type { StripeApiVersion } from "../stripe-types.js";
8
+ import { UsageCorrectionClient } from "./correctionClient.js";
9
+ import {
10
+ getUsageInvoiceSale,
11
+ type UsageInvoiceSaleOptions,
12
+ } from "./invoiceSale.js";
13
+ import {
14
+ settleUsageInvoice,
15
+ type UsageInvoiceSettlementOptions,
16
+ } from "./settlement.js";
17
+ import { getCreditPurchaseRevenue } from "./creditRevenue.js";
18
+ import {
19
+ creditBinding,
20
+ creditPurchaseTerms,
21
+ type UsageCreditPurchaseOptions,
22
+ } from "./creditTerms.js";
23
+ import { observationOptions } from "./observationTypes.js";
24
+ import type { UsageDeliveryProviderOptions } from "./deliveryProvider.js";
25
+ function provider(version: string, options: UsageDeliveryProviderOptions) {
26
+ if (!options.stripeSecretKey)
27
+ throw new Error("Native usage settlement credentials unavailable");
28
+ return new Stripe(options.stripeSecretKey, {
29
+ apiVersion: version as StripeApiVersion,
30
+ maxNetworkRetries: 0,
31
+ timeout: 15000,
32
+ ...(options.httpClient ? { httpClient: options.httpClient } : {}),
33
+ });
34
+ }
35
+ /** Trusted host authorizes original seller/product and recipient policies before any settlement. */
36
+ export class UsageSettlementClient extends UsageCorrectionClient {
37
+ async getInvoiceSale(
38
+ _ctx: RunCtx,
39
+ input: UsageInvoiceSaleOptions,
40
+ options: UsageDeliveryProviderOptions,
41
+ ) {
42
+ return getUsageInvoiceSale(
43
+ provider(observationOptions(input).binding.apiVersion, options),
44
+ input,
45
+ );
46
+ }
47
+ async settleInvoice(
48
+ ctx: RunCtx,
49
+ input: UsageInvoiceSettlementOptions,
50
+ options: UsageDeliveryProviderOptions,
51
+ ) {
52
+ return settleUsageInvoice(
53
+ provider(observationOptions(input).binding.apiVersion, options),
54
+ this.component,
55
+ ctx,
56
+ input,
57
+ );
58
+ }
59
+ async getCreditPurchaseRevenue(
60
+ ctx: RunCtx,
61
+ input: UsageCreditPurchaseOptions,
62
+ options: UsageDeliveryProviderOptions,
63
+ ) {
64
+ return getCreditPurchaseRevenue(
65
+ provider(creditPurchaseTerms(input).binding.apiVersion, options),
66
+ this.component,
67
+ ctx,
68
+ input,
69
+ );
70
+ }
71
+ async settleCreditPurchase(
72
+ ctx: RunCtx,
73
+ input: UsageCreditSettlementOptions,
74
+ options: UsageDeliveryProviderOptions,
75
+ ) {
76
+ const { policy: _policy, ...purchase } = input;
77
+ return settleCreditPurchase(
78
+ provider(creditBinding(purchase).binding.apiVersion, options),
79
+ this.component,
80
+ ctx,
81
+ input,
82
+ );
83
+ }
84
+ }
@@ -7715,6 +7715,15 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
7715
7715
  accountId: string;
7716
7716
  allocation?: {
7717
7717
  adjustmentAmount?: number;
7718
+ creditSource?: {
7719
+ creditGrantId: string;
7720
+ customerAccount: string;
7721
+ livemode: boolean;
7722
+ purchaseId: string;
7723
+ stripeAccountId: string;
7724
+ stripePriceId: string;
7725
+ stripeProductId: string;
7726
+ };
7718
7727
  currency: string;
7719
7728
  gross: number;
7720
7729
  paymentId?: string;
@@ -7728,6 +7737,19 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
7728
7737
  destinationAccountId: string;
7729
7738
  role: "store" | "affiliate" | "other";
7730
7739
  }>;
7740
+ usageSource?: {
7741
+ customerAccount: string;
7742
+ invoicePaymentId: string;
7743
+ livemode: boolean;
7744
+ meterId: string;
7745
+ model: "pay_as_you_go" | "included_overage";
7746
+ period: { end: number; start: number };
7747
+ stripeAccountId: string;
7748
+ stripePriceId: string;
7749
+ stripeProductId: string;
7750
+ subscriptionId: string;
7751
+ subscriptionItemId: string;
7752
+ };
7731
7753
  };
7732
7754
  completion?: string;
7733
7755
  currency: string;
@@ -7820,6 +7842,15 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
7820
7842
  activePhase?: "execute" | "reconcile";
7821
7843
  allocation?: {
7822
7844
  adjustmentAmount?: number;
7845
+ creditSource?: {
7846
+ creditGrantId: string;
7847
+ customerAccount: string;
7848
+ livemode: boolean;
7849
+ purchaseId: string;
7850
+ stripeAccountId: string;
7851
+ stripePriceId: string;
7852
+ stripeProductId: string;
7853
+ };
7823
7854
  currency: string;
7824
7855
  gross: number;
7825
7856
  paymentId?: string;
@@ -7833,6 +7864,19 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
7833
7864
  destinationAccountId: string;
7834
7865
  role: "store" | "affiliate" | "other";
7835
7866
  }>;
7867
+ usageSource?: {
7868
+ customerAccount: string;
7869
+ invoicePaymentId: string;
7870
+ livemode: boolean;
7871
+ meterId: string;
7872
+ model: "pay_as_you_go" | "included_overage";
7873
+ period: { end: number; start: number };
7874
+ stripeAccountId: string;
7875
+ stripePriceId: string;
7876
+ stripeProductId: string;
7877
+ subscriptionId: string;
7878
+ subscriptionItemId: string;
7879
+ };
7836
7880
  };
7837
7881
  cancelRequested: boolean;
7838
7882
  completion?: string;
@@ -8132,6 +8176,15 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
8132
8176
  "internal",
8133
8177
  {
8134
8178
  adjustmentAmount?: number;
8179
+ creditSource?: {
8180
+ creditGrantId: string;
8181
+ customerAccount: string;
8182
+ livemode: boolean;
8183
+ purchaseId: string;
8184
+ stripeAccountId: string;
8185
+ stripePriceId: string;
8186
+ stripeProductId: string;
8187
+ };
8135
8188
  currency: string;
8136
8189
  gross: number;
8137
8190
  paymentId?: string;
@@ -8145,11 +8198,33 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
8145
8198
  destinationAccountId: string;
8146
8199
  role: "store" | "affiliate" | "other";
8147
8200
  }>;
8201
+ usageSource?: {
8202
+ customerAccount: string;
8203
+ invoicePaymentId: string;
8204
+ livemode: boolean;
8205
+ meterId: string;
8206
+ model: "pay_as_you_go" | "included_overage";
8207
+ period: { end: number; start: number };
8208
+ stripeAccountId: string;
8209
+ stripePriceId: string;
8210
+ stripeProductId: string;
8211
+ subscriptionId: string;
8212
+ subscriptionItemId: string;
8213
+ };
8148
8214
  },
8149
8215
  {
8150
8216
  _creationTime: number;
8151
8217
  _id: string;
8152
8218
  adjustmentAmount?: number;
8219
+ creditSource?: {
8220
+ creditGrantId: string;
8221
+ customerAccount: string;
8222
+ livemode: boolean;
8223
+ purchaseId: string;
8224
+ stripeAccountId: string;
8225
+ stripePriceId: string;
8226
+ stripeProductId: string;
8227
+ };
8153
8228
  currency: string;
8154
8229
  gross: number;
8155
8230
  paymentId?: string;
@@ -8163,6 +8238,19 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
8163
8238
  destinationAccountId: string;
8164
8239
  role: "store" | "affiliate" | "other";
8165
8240
  }>;
8241
+ usageSource?: {
8242
+ customerAccount: string;
8243
+ invoicePaymentId: string;
8244
+ livemode: boolean;
8245
+ meterId: string;
8246
+ model: "pay_as_you_go" | "included_overage";
8247
+ period: { end: number; start: number };
8248
+ stripeAccountId: string;
8249
+ stripePriceId: string;
8250
+ stripeProductId: string;
8251
+ subscriptionId: string;
8252
+ subscriptionItemId: string;
8253
+ };
8166
8254
  },
8167
8255
  Name
8168
8256
  >;
@@ -8188,6 +8276,15 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
8188
8276
  _creationTime: number;
8189
8277
  _id: string;
8190
8278
  adjustmentAmount?: number;
8279
+ creditSource?: {
8280
+ creditGrantId: string;
8281
+ customerAccount: string;
8282
+ livemode: boolean;
8283
+ purchaseId: string;
8284
+ stripeAccountId: string;
8285
+ stripePriceId: string;
8286
+ stripeProductId: string;
8287
+ };
8191
8288
  currency: string;
8192
8289
  gross: number;
8193
8290
  paymentId?: string;
@@ -8201,6 +8298,19 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
8201
8298
  destinationAccountId: string;
8202
8299
  role: "store" | "affiliate" | "other";
8203
8300
  }>;
8301
+ usageSource?: {
8302
+ customerAccount: string;
8303
+ invoicePaymentId: string;
8304
+ livemode: boolean;
8305
+ meterId: string;
8306
+ model: "pay_as_you_go" | "included_overage";
8307
+ period: { end: number; start: number };
8308
+ stripeAccountId: string;
8309
+ stripePriceId: string;
8310
+ stripeProductId: string;
8311
+ subscriptionId: string;
8312
+ subscriptionItemId: string;
8313
+ };
8204
8314
  } | null,
8205
8315
  Name
8206
8316
  >;
@@ -81,6 +81,8 @@ export async function settlementFingerprint(row: Doc<"settlementAllocations">) {
81
81
  sourceChargeId: row.sourceChargeId,
82
82
  paymentIntentId: row.paymentIntentId,
83
83
  sourceInvoiceId: row.sourceInvoiceId,
84
+ ...(row.usageSource ? { usageSource: row.usageSource } : {}),
85
+ ...(row.creditSource ? { creditSource: row.creditSource } : {}),
84
86
  gross: row.gross,
85
87
  currency: row.currency,
86
88
  processingFee: row.processingFee,
@@ -1,3 +1,4 @@
1
+ import { canonicalFingerprint } from "../operationEvidence/canonical.js";
1
2
  import { observeSettlementAllocation } from "../financialObservations/settlement.js";
2
3
  import { paginator } from "convex-helpers/server/pagination";
3
4
  import schema from "../schema.js";
@@ -16,6 +17,10 @@ export const reserveSettlementAllocation = mutation({
16
17
  args: allocationFields,
17
18
  returns: doc,
18
19
  handler: async (ctx, args) => {
20
+ if (args.usageSource && args.creditSource)
21
+ throw new Error(
22
+ "Settlement cannot combine invoice and credit purchase sources",
23
+ );
19
24
  const existing = await ctx.db
20
25
  .query("settlementAllocations")
21
26
  .withIndex("by_source_charge", (q) =>
@@ -26,7 +31,11 @@ export const reserveSettlementAllocation = mutation({
26
31
  if (
27
32
  existing.currency !== args.currency ||
28
33
  existing.paymentIntentId !== args.paymentIntentId ||
29
- existing.sourceInvoiceId !== args.sourceInvoiceId
34
+ existing.sourceInvoiceId !== args.sourceInvoiceId ||
35
+ (await canonicalFingerprint(existing.usageSource ?? null)) !==
36
+ (await canonicalFingerprint(args.usageSource ?? null)) ||
37
+ (await canonicalFingerprint(existing.creditSource ?? null)) !==
38
+ (await canonicalFingerprint(args.creditSource ?? null))
30
39
  )
31
40
  throw new Error("Settlement source identity cannot change.");
32
41
  await observeSettlementAllocation(ctx, existing);
@@ -9,6 +9,32 @@ export const allocationFields = {
9
9
  sourceChargeId: v.string(),
10
10
  paymentIntentId: v.optional(v.string()),
11
11
  sourceInvoiceId: v.optional(v.string()),
12
+ usageSource: v.optional(
13
+ v.object({
14
+ stripeAccountId: v.string(),
15
+ customerAccount: v.string(),
16
+ livemode: v.boolean(),
17
+ meterId: v.string(),
18
+ stripePriceId: v.string(),
19
+ stripeProductId: v.string(),
20
+ subscriptionId: v.string(),
21
+ subscriptionItemId: v.string(),
22
+ invoicePaymentId: v.string(),
23
+ period: v.object({ start: v.number(), end: v.number() }),
24
+ model: v.union(v.literal("pay_as_you_go"), v.literal("included_overage")),
25
+ }),
26
+ ),
27
+ creditSource: v.optional(
28
+ v.object({
29
+ stripeAccountId: v.string(),
30
+ customerAccount: v.string(),
31
+ livemode: v.boolean(),
32
+ purchaseId: v.string(),
33
+ creditGrantId: v.string(),
34
+ stripePriceId: v.string(),
35
+ stripeProductId: v.string(),
36
+ }),
37
+ ),
12
38
  gross: v.number(),
13
39
  currency: v.string(),
14
40
  processingFee: v.number(),
@@ -74,3 +74,57 @@ it("persists the term, identity and earliest invoice despite replay and term cha
74
74
  }),
75
75
  ).rejects.toThrow();
76
76
  });
77
+
78
+ it("pins original native metering provenance and refuses replay against another meter or invoice payment", async () => {
79
+ const t = convexTest(schema, modules);
80
+ const opts = {
81
+ sourceChargeId: "ch_meter",
82
+ paymentIntentId: "pi_meter",
83
+ sourceInvoiceId: "in_meter",
84
+ gross: 100,
85
+ currency: "usd",
86
+ processingFee: 3,
87
+ platformNet: 7,
88
+ transfers: [
89
+ {
90
+ destinationAccountId: "acct_seller",
91
+ amount: 90,
92
+ role: "store" as const,
93
+ },
94
+ ],
95
+ usageSource: {
96
+ stripeAccountId: "acct_platform",
97
+ customerAccount: "acct_buyer",
98
+ livemode: false,
99
+ meterId: "mtr_calls",
100
+ stripePriceId: "price_calls",
101
+ stripeProductId: "prod_calls",
102
+ subscriptionId: "sub_calls",
103
+ subscriptionItemId: "si_calls",
104
+ invoicePaymentId: "inpay_meter",
105
+ period: { start: 600, end: 1200 },
106
+ model: "pay_as_you_go" as const,
107
+ },
108
+ };
109
+ const first = await t.mutation(
110
+ api.settlement.mutations.reserveSettlementAllocation,
111
+ opts,
112
+ );
113
+ expect(first).toMatchObject({ usageSource: opts.usageSource });
114
+ for (const changed of [
115
+ { meterId: "mtr_other" },
116
+ { invoicePaymentId: "inpay_other" },
117
+ ])
118
+ await expect(
119
+ t.mutation(api.settlement.mutations.reserveSettlementAllocation, {
120
+ ...opts,
121
+ usageSource: { ...opts.usageSource, ...changed },
122
+ }),
123
+ ).rejects.toThrow(/source identity/i);
124
+ await expect(
125
+ t.mutation(api.settlement.mutations.reserveSettlementAllocation, {
126
+ ...opts,
127
+ usageSource: undefined,
128
+ }),
129
+ ).rejects.toThrow(/source identity/i);
130
+ });