@fantastic.dev/better-stripe 0.58.0 → 0.59.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 (198) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +1 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +238 -18
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +119 -9
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +238 -18
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +119 -9
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  11. package/dist/client/usage/allowanceClient.d.ts +1 -1
  12. package/dist/client/usage/client.d.ts +2 -2
  13. package/dist/client/usage/client.d.ts.map +1 -1
  14. package/dist/client/usage/client.js +2 -2
  15. package/dist/client/usage/client.js.map +1 -1
  16. package/dist/client/usage/correctionClient.d.ts +33 -0
  17. package/dist/client/usage/correctionClient.d.ts.map +1 -0
  18. package/dist/client/usage/correctionClient.js +27 -0
  19. package/dist/client/usage/correctionClient.js.map +1 -0
  20. package/dist/client/usage/correctionEligibility.d.ts +4 -0
  21. package/dist/client/usage/correctionEligibility.d.ts.map +1 -0
  22. package/dist/client/usage/correctionEligibility.js +7 -0
  23. package/dist/client/usage/correctionEligibility.js.map +1 -0
  24. package/dist/client/usage/correctionInvoice.d.ts +9 -0
  25. package/dist/client/usage/correctionInvoice.d.ts.map +1 -0
  26. package/dist/client/usage/correctionInvoice.js +218 -0
  27. package/dist/client/usage/correctionInvoice.js.map +1 -0
  28. package/dist/client/usage/correctionInvoiceProof.d.ts +29 -0
  29. package/dist/client/usage/correctionInvoiceProof.d.ts.map +1 -0
  30. package/dist/client/usage/correctionInvoiceProof.js +41 -0
  31. package/dist/client/usage/correctionInvoiceProof.js.map +1 -0
  32. package/dist/client/usage/correctionProofs.d.ts +36 -0
  33. package/dist/client/usage/correctionProofs.d.ts.map +1 -0
  34. package/dist/client/usage/correctionProofs.js +41 -0
  35. package/dist/client/usage/correctionProofs.js.map +1 -0
  36. package/dist/client/usage/correctionProvider.d.ts +6 -0
  37. package/dist/client/usage/correctionProvider.d.ts.map +1 -0
  38. package/dist/client/usage/correctionProvider.js +243 -0
  39. package/dist/client/usage/correctionProvider.js.map +1 -0
  40. package/dist/client/usage/correctionRead.d.ts +27 -0
  41. package/dist/client/usage/correctionRead.d.ts.map +1 -0
  42. package/dist/client/usage/correctionRead.js +36 -0
  43. package/dist/client/usage/correctionRead.js.map +1 -0
  44. package/dist/client/usage/correctionTerms.d.ts +64 -0
  45. package/dist/client/usage/correctionTerms.d.ts.map +1 -0
  46. package/dist/client/usage/correctionTerms.js +65 -0
  47. package/dist/client/usage/correctionTerms.js.map +1 -0
  48. package/dist/client/usage/correctionTransport.fixtures.d.ts +37 -0
  49. package/dist/client/usage/correctionTransport.fixtures.d.ts.map +1 -0
  50. package/dist/client/usage/correctionTransport.fixtures.js +322 -0
  51. package/dist/client/usage/correctionTransport.fixtures.js.map +1 -0
  52. package/dist/client/usage/creditClient.d.ts +1 -1
  53. package/dist/client/usage/index.d.ts +2 -0
  54. package/dist/client/usage/index.d.ts.map +1 -1
  55. package/dist/client/usage/observationClient.d.ts +20 -0
  56. package/dist/client/usage/observationClient.d.ts.map +1 -1
  57. package/dist/client/usage/observationClient.js +20 -6
  58. package/dist/client/usage/observationClient.js.map +1 -1
  59. package/dist/client/usage/records.d.ts +1 -1
  60. package/dist/client/usage/records.d.ts.map +1 -1
  61. package/dist/client/usage/records.js.map +1 -1
  62. package/dist/client/usage/summary.d.ts +3 -0
  63. package/dist/client/usage/summary.d.ts.map +1 -1
  64. package/dist/client/usage/summary.js +9 -4
  65. package/dist/client/usage/summary.js.map +1 -1
  66. package/dist/client/usageExports.d.ts +2 -0
  67. package/dist/client/usageExports.d.ts.map +1 -1
  68. package/dist/component/_generated/api.d.ts +12 -0
  69. package/dist/component/_generated/api.d.ts.map +1 -1
  70. package/dist/component/_generated/api.js.map +1 -1
  71. package/dist/component/_generated/component.d.ts +255 -14
  72. package/dist/component/_generated/component.d.ts.map +1 -1
  73. package/dist/component/accountClosure/mutations.d.ts.map +1 -1
  74. package/dist/component/accountClosure/mutations.js +13 -0
  75. package/dist/component/accountClosure/mutations.js.map +1 -1
  76. package/dist/component/balanceFunding/mutations.d.ts +27 -27
  77. package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
  78. package/dist/component/earnings/triggers.d.ts +212 -26
  79. package/dist/component/earnings/triggers.d.ts.map +1 -1
  80. package/dist/component/schema.d.ts +119 -9
  81. package/dist/component/schema.js +4 -0
  82. package/dist/component/schema.js.map +1 -1
  83. package/dist/component/usage/queries.d.ts +2 -2
  84. package/dist/component/usage/schema.d.ts +18 -13
  85. package/dist/component/usage/schema.d.ts.map +1 -1
  86. package/dist/component/usage/schema.js +2 -1
  87. package/dist/component/usage/schema.js.map +1 -1
  88. package/dist/component/usageAllowance/queries.d.ts +1 -1
  89. package/dist/component/usageAllowance/queries.d.ts.map +1 -1
  90. package/dist/component/usageAllowance/queries.js +10 -1
  91. package/dist/component/usageAllowance/queries.js.map +1 -1
  92. package/dist/component/usageAllowance/schema.d.ts +5 -5
  93. package/dist/component/usageAllowance/schema.d.ts.map +1 -1
  94. package/dist/component/usageAllowance/schema.js +1 -1
  95. package/dist/component/usageAllowance/schema.js.map +1 -1
  96. package/dist/component/usageCorrections/accounting.d.ts +5 -0
  97. package/dist/component/usageCorrections/accounting.d.ts.map +1 -0
  98. package/dist/component/usageCorrections/accounting.js +55 -0
  99. package/dist/component/usageCorrections/accounting.js.map +1 -0
  100. package/dist/component/usageCorrections/cancellation.d.ts +6 -0
  101. package/dist/component/usageCorrections/cancellation.d.ts.map +1 -0
  102. package/dist/component/usageCorrections/cancellation.js +29 -0
  103. package/dist/component/usageCorrections/cancellation.js.map +1 -0
  104. package/dist/component/usageCorrections/helpers.d.ts +60 -0
  105. package/dist/component/usageCorrections/helpers.d.ts.map +1 -0
  106. package/dist/component/usageCorrections/helpers.js +52 -0
  107. package/dist/component/usageCorrections/helpers.js.map +1 -0
  108. package/dist/component/usageCorrections/invoice.d.ts +38 -0
  109. package/dist/component/usageCorrections/invoice.d.ts.map +1 -0
  110. package/dist/component/usageCorrections/invoice.js +82 -0
  111. package/dist/component/usageCorrections/invoice.js.map +1 -0
  112. package/dist/component/usageCorrections/mutations.d.ts +121 -0
  113. package/dist/component/usageCorrections/mutations.d.ts.map +1 -0
  114. package/dist/component/usageCorrections/mutations.js +256 -0
  115. package/dist/component/usageCorrections/mutations.js.map +1 -0
  116. package/dist/component/usageCorrections/queries.d.ts +115 -0
  117. package/dist/component/usageCorrections/queries.d.ts.map +1 -0
  118. package/dist/component/usageCorrections/queries.js +84 -0
  119. package/dist/component/usageCorrections/queries.js.map +1 -0
  120. package/dist/component/usageCorrections/schema.d.ts +248 -0
  121. package/dist/component/usageCorrections/schema.d.ts.map +1 -0
  122. package/dist/component/usageCorrections/schema.js +74 -0
  123. package/dist/component/usageCorrections/schema.js.map +1 -0
  124. package/dist/component/usageCredits/queries.d.ts +1 -1
  125. package/dist/component/usageCredits/queries.d.ts.map +1 -1
  126. package/dist/component/usageCredits/queries.js +6 -0
  127. package/dist/component/usageCredits/queries.js.map +1 -1
  128. package/dist/component/usageCredits/schema.d.ts +5 -5
  129. package/dist/component/usageCredits/schema.d.ts.map +1 -1
  130. package/dist/component/usageCredits/schema.js +1 -1
  131. package/dist/component/usageCredits/schema.js.map +1 -1
  132. package/dist/component/usageDelivery/fields.d.ts +2 -2
  133. package/dist/component/usageDelivery/fields.d.ts.map +1 -1
  134. package/dist/component/usageDelivery/fields.js +1 -1
  135. package/dist/component/usageDelivery/fields.js.map +1 -1
  136. package/dist/component/usageDelivery/helpers.d.ts +7 -6
  137. package/dist/component/usageDelivery/helpers.d.ts.map +1 -1
  138. package/dist/component/usageDelivery/mutations.d.ts +6 -6
  139. package/dist/component/usageDelivery/mutations.d.ts.map +1 -1
  140. package/dist/component/usageDelivery/mutations.js +9 -1
  141. package/dist/component/usageDelivery/mutations.js.map +1 -1
  142. package/dist/component/usageDelivery/queries.d.ts +8 -6
  143. package/dist/component/usageDelivery/queries.d.ts.map +1 -1
  144. package/dist/component/usageDelivery/schema.d.ts +4 -4
  145. package/dist/component/usageDelivery/steps.d.ts +2 -2
  146. package/dist/component/usageDelivery/steps.js +1 -1
  147. package/dist/component/usageDelivery/steps.js.map +1 -1
  148. package/dist/component/usageObservations/queries.d.ts.map +1 -1
  149. package/dist/component/usageObservations/queries.js +4 -2
  150. package/dist/component/usageObservations/queries.js.map +1 -1
  151. package/dist/component/usageSubscriptions/retirement.d.ts.map +1 -1
  152. package/dist/component/usageSubscriptions/retirement.js +24 -2
  153. package/dist/component/usageSubscriptions/retirement.js.map +1 -1
  154. package/docs/README.md +2 -0
  155. package/docs/usage-corrections.md +249 -0
  156. package/docs/usage-limits.md +1 -1
  157. package/package.json +2 -1
  158. package/src/client/usage/client.ts +2 -2
  159. package/src/client/usage/correctionClient.test.ts +153 -0
  160. package/src/client/usage/correctionClient.ts +62 -0
  161. package/src/client/usage/correctionCredits.test.ts +156 -0
  162. package/src/client/usage/correctionEligibility.ts +14 -0
  163. package/src/client/usage/correctionInvoice.test.ts +127 -0
  164. package/src/client/usage/correctionInvoice.ts +269 -0
  165. package/src/client/usage/correctionInvoiceProof.ts +40 -0
  166. package/src/client/usage/correctionProofs.ts +40 -0
  167. package/src/client/usage/correctionProvider.ts +326 -0
  168. package/src/client/usage/correctionRead.ts +73 -0
  169. package/src/client/usage/correctionRecovery.test.ts +113 -0
  170. package/src/client/usage/correctionTerms.ts +98 -0
  171. package/src/client/usage/correctionTransport.fixtures.ts +372 -0
  172. package/src/client/usage/index.ts +11 -0
  173. package/src/client/usage/observationClient.ts +20 -6
  174. package/src/client/usage/records.ts +7 -1
  175. package/src/client/usage/summary.ts +12 -4
  176. package/src/client/usageExports.ts +11 -0
  177. package/src/component/_generated/api.ts +12 -0
  178. package/src/component/_generated/component.ts +330 -2
  179. package/src/component/accountClosure/mutations.ts +17 -0
  180. package/src/component/schema.ts +8 -0
  181. package/src/component/usage/schema.ts +2 -0
  182. package/src/component/usageAllowance/queries.ts +8 -1
  183. package/src/component/usageAllowance/schema.ts +1 -0
  184. package/src/component/usageCorrections/accounting.ts +79 -0
  185. package/src/component/usageCorrections/cancellation.ts +32 -0
  186. package/src/component/usageCorrections/corrections.test.ts +389 -0
  187. package/src/component/usageCorrections/helpers.ts +57 -0
  188. package/src/component/usageCorrections/invoice.ts +103 -0
  189. package/src/component/usageCorrections/mutations.ts +278 -0
  190. package/src/component/usageCorrections/queries.ts +94 -0
  191. package/src/component/usageCorrections/schema.ts +90 -0
  192. package/src/component/usageCredits/queries.ts +4 -0
  193. package/src/component/usageCredits/schema.ts +1 -0
  194. package/src/component/usageDelivery/fields.ts +1 -0
  195. package/src/component/usageDelivery/mutations.ts +8 -3
  196. package/src/component/usageDelivery/steps.ts +1 -1
  197. package/src/component/usageObservations/queries.ts +5 -2
  198. package/src/component/usageSubscriptions/retirement.ts +31 -2
@@ -0,0 +1,127 @@
1
+ import { afterEach, expect, it, vi } from "vitest";
2
+ import type { RunCtx } from "../helpers.js";
3
+ import { setupCorrection } from "./correctionTransport.fixtures.js";
4
+ afterEach(() => vi.useRealTimers());
5
+ async function partial() {
6
+ const f = await setupCorrection();
7
+ await f.f.t.action((ctx) =>
8
+ f.client.usage.requestCorrection(
9
+ ctx as RunCtx,
10
+ { ...f.correction, quantity: "2" },
11
+ f.options,
12
+ ),
13
+ );
14
+ const input = {
15
+ scope: f.correction.scope,
16
+ eventId: f.correction.eventId,
17
+ correctionId: f.correction.correctionId,
18
+ invoiceId: "in_usage",
19
+ creditNoteId: "cn_fix",
20
+ amount: 4,
21
+ };
22
+ return { ...f, input };
23
+ }
24
+ it("verifies the original paid invoice, invoice payment, charge and succeeded refund before recording cash adjustment provenance", async () => {
25
+ const { f, client, options, state, input } = await partial();
26
+ state.paidAdjustment = true;
27
+ expect(
28
+ await f.t.action((ctx) =>
29
+ client.usage.observeInvoiceCorrection(ctx as RunCtx, input, options),
30
+ ),
31
+ ).toMatchObject({
32
+ state: "confirmed",
33
+ creditNoteId: "cn_fix",
34
+ refundId: "re_fix",
35
+ restoredQuantity: "0",
36
+ resolution: "invoice_credit",
37
+ cashCollection: "none",
38
+ invoiceAdjustment: {
39
+ amount: 4,
40
+ currency: "usd",
41
+ postPaymentAmount: 4,
42
+ paymentIntentId: "pi_invoice",
43
+ chargeId: "ch_invoice",
44
+ refundId: "re_fix",
45
+ },
46
+ });
47
+ });
48
+ it("holds foreign, incomplete, pending-refund and wrong-line native credit evidence", async () => {
49
+ for (const invalid of [
50
+ "foreignNote",
51
+ "truncatedNote",
52
+ "foreignLine",
53
+ "pendingRefund",
54
+ ] as const) {
55
+ const { f, client, options, state, input } = await partial();
56
+ if (invalid === "pendingRefund") {
57
+ state.paidAdjustment = true;
58
+ state.refundSucceeded = false;
59
+ } else state[invalid] = true;
60
+ expect(
61
+ await f.t.action((ctx) =>
62
+ client.usage.observeInvoiceCorrection(ctx as RunCtx, input, options),
63
+ ),
64
+ ).toMatchObject({ status: "held" });
65
+ }
66
+ });
67
+ it("does not claim the same native credit note for a second correction operation", async () => {
68
+ const { f, client, options, correction, input } = await partial();
69
+ await f.t.action((ctx) =>
70
+ client.usage.observeInvoiceCorrection(ctx as RunCtx, input, options),
71
+ );
72
+ await f.t.action((ctx) =>
73
+ client.usage.requestCorrection(
74
+ ctx as RunCtx,
75
+ { ...correction, correctionId: "fix2", quantity: "1" },
76
+ options,
77
+ ),
78
+ );
79
+ await expect(
80
+ f.t.action((ctx) =>
81
+ client.usage.observeInvoiceCorrection(
82
+ ctx as RunCtx,
83
+ { ...input, correctionId: "fix2" },
84
+ options,
85
+ ),
86
+ ),
87
+ ).rejects.toThrow(/already claimed/i);
88
+ });
89
+ it("records a verified pre-payment credit-note void without refunding cash or restoring valid usage", async () => {
90
+ const { f, client, options, state, input } = await partial();
91
+ await f.t.action((ctx) =>
92
+ client.usage.observeInvoiceCorrection(ctx as RunCtx, input, options),
93
+ );
94
+ state.voidedNote = true;
95
+ expect(
96
+ await f.t.action((ctx) =>
97
+ client.usage.observeInvoiceCorrection(ctx as RunCtx, input, options),
98
+ ),
99
+ ).toMatchObject({
100
+ state: "confirmed",
101
+ nativeCreditNoteStatus: "void",
102
+ reason: "native_invoice_credit_voided",
103
+ cashConsequence: "none",
104
+ restoredQuantity: "0",
105
+ });
106
+ });
107
+
108
+ it("rejects unsafe native payment and charge amounts instead of normalizing a refund proof", async () => {
109
+ const { f, client, options, state, input } = await partial();
110
+ state.paidAdjustment = true;
111
+ state.invalidCash = true;
112
+ expect(
113
+ await f.t.action((ctx) =>
114
+ client.usage.observeInvoiceCorrection(ctx as RunCtx, input, options),
115
+ ),
116
+ ).toMatchObject({ status: "held" });
117
+ });
118
+
119
+ it("does not treat missing native tax and page evidence as a known empty financial history", async () => {
120
+ const { f, client, options, state, input } = await partial();
121
+ state.missingEvidence = true;
122
+ expect(
123
+ await f.t.action((ctx) =>
124
+ client.usage.observeInvoiceCorrection(ctx as RunCtx, input, options),
125
+ ),
126
+ ).toMatchObject({ status: "held" });
127
+ });
@@ -0,0 +1,269 @@
1
+ import Stripe from "stripe";
2
+ import type { Component, RunCtx } from "../helpers.js";
3
+ import { runMutationOrThrow } from "../helpers.js";
4
+ import { componentRef } from "../webhooks/helpers.js";
5
+ import type { Doc } from "../../component/_generated/dataModel.js";
6
+ import type { PreparedUsageRecord } from "./records.js";
7
+ import type { UsageDeliveryProviderOptions } from "./deliveryProvider.js";
8
+ import type { StripeApiVersion } from "../stripe-types.js";
9
+ import { verifyRealm } from "./catalogTypes.js";
10
+ import { subscriptionSnapshot } from "../../component/usage/helpers.js";
11
+ import {
12
+ invoiceCorrectionOptions,
13
+ correctionView,
14
+ type UsageInvoiceCorrectionOptions,
15
+ } from "./correctionTerms.js";
16
+ import { invoiceCorrectionProof } from "./correctionInvoiceProof.js";
17
+ import {
18
+ referenceId,
19
+ paymentReference,
20
+ } from "../billing/invoicePaymentShared.js";
21
+ const requireProof = (valid: unknown) => {
22
+ if (!valid)
23
+ throw new Error("Native invoice correction requires reconciliation");
24
+ };
25
+ /** Read-only provider adoption. The operator creates notes/refunds through existing authorized billing workflows. */
26
+ export async function observeInvoiceCorrection(
27
+ component: Component,
28
+ ctx: RunCtx,
29
+ input: UsageInvoiceCorrectionOptions,
30
+ options: UsageDeliveryProviderOptions,
31
+ ) {
32
+ const opts = invoiceCorrectionOptions.parse(input);
33
+ const row = (await ctx.runQuery(
34
+ componentRef(component, "usageCorrections/queries/get"),
35
+ {
36
+ scope: opts.scope,
37
+ eventId: opts.eventId,
38
+ correctionId: opts.correctionId,
39
+ },
40
+ )) as Doc<"usageCorrections"> | null;
41
+ if (!row) throw new Error("Usage correction unavailable");
42
+ if (row.adjustmentJson) {
43
+ const pinned = invoiceCorrectionProof.parse(JSON.parse(row.adjustmentJson));
44
+ if (
45
+ pinned.creditNoteId !== opts.creditNoteId ||
46
+ pinned.invoiceId !== opts.invoiceId ||
47
+ pinned.amount !== opts.amount
48
+ )
49
+ throw new Error("Invoice adjustment replay conflict");
50
+ }
51
+ const record = JSON.parse(row.recordJson) as PreparedUsageRecord,
52
+ sub = subscriptionSnapshot(row.subscriptionJson);
53
+ if (!options.stripeSecretKey || record.binding.plan.model === "prepaid")
54
+ return {
55
+ status: "held" as const,
56
+ reason:
57
+ record.binding.plan.model === "prepaid"
58
+ ? "prepaid_credit_reconciliation_required"
59
+ : "provider_unavailable",
60
+ };
61
+ const stripe = new Stripe(options.stripeSecretKey, {
62
+ apiVersion: record.binding.apiVersion as StripeApiVersion,
63
+ maxNetworkRetries: 0,
64
+ timeout: 15000,
65
+ ...(options.httpClient ? { httpClient: options.httpClient } : {}),
66
+ });
67
+ let proof: ReturnType<typeof invoiceCorrectionProof.parse>;
68
+ try {
69
+ await verifyRealm(stripe, {
70
+ stripeAccountId: record.scope.stripeAccountId,
71
+ livemode: record.scope.livemode,
72
+ });
73
+ const [note, invoice, customer] = await Promise.all([
74
+ stripe.creditNotes.retrieve(opts.creditNoteId),
75
+ stripe.invoices.retrieve(opts.invoiceId),
76
+ stripe.customers.retrieve(record.scope.customerAccount),
77
+ ]);
78
+ requireProof(
79
+ !customer.deleted &&
80
+ customer.id === record.binding.stripeCustomerId &&
81
+ customer.customer_account === record.scope.customerAccount &&
82
+ customer.livemode === record.scope.livemode,
83
+ );
84
+ requireProof(
85
+ note.id === opts.creditNoteId &&
86
+ note.object === "credit_note" &&
87
+ note.livemode === record.scope.livemode &&
88
+ note.customer_account === record.scope.customerAccount &&
89
+ referenceId(note.customer) === record.binding.stripeCustomerId &&
90
+ referenceId(note.invoice) === opts.invoiceId &&
91
+ (note.status === "issued" ||
92
+ (note.status === "void" &&
93
+ row.adjustmentJson &&
94
+ note.pre_payment_amount === note.amount &&
95
+ note.post_payment_amount === 0)) &&
96
+ note.currency === record.binding.plan.rate.currency &&
97
+ note.amount === opts.amount &&
98
+ note.total === note.amount &&
99
+ note.subtotal === note.amount &&
100
+ note.discount_amount === 0 &&
101
+ note.amount_shipping === 0 &&
102
+ Array.isArray(note.total_taxes) &&
103
+ note.total_taxes.length === 0 &&
104
+ note.customer_balance_transaction === null &&
105
+ (note.out_of_band_amount === null || note.out_of_band_amount === 0) &&
106
+ Array.isArray(note.pretax_credit_amounts) &&
107
+ note.pretax_credit_amounts.length === 0 &&
108
+ note.lines.has_more === false &&
109
+ note.lines.data.length === 1 &&
110
+ note.amount === note.pre_payment_amount + note.post_payment_amount,
111
+ );
112
+ requireProof(
113
+ invoice.id === opts.invoiceId &&
114
+ invoice.livemode === record.scope.livemode &&
115
+ invoice.customer_account === record.scope.customerAccount &&
116
+ referenceId(invoice.customer) === record.binding.stripeCustomerId &&
117
+ invoice.currency === record.binding.plan.rate.currency &&
118
+ ["open", "paid"].includes(invoice.status ?? "") &&
119
+ referenceId(invoice.parent?.subscription_details?.subscription) ===
120
+ sub.subscriptionId &&
121
+ invoice.lines.has_more === false,
122
+ );
123
+ const noteLine = note.lines.data[0],
124
+ line = invoice.lines.data.find(
125
+ (line) => line.id === noteLine.invoice_line_item,
126
+ );
127
+ requireProof(
128
+ noteLine.type === "invoice_line_item" &&
129
+ noteLine.livemode === record.scope.livemode &&
130
+ noteLine.amount === opts.amount &&
131
+ noteLine.discount_amount === 0 &&
132
+ (noteLine.taxes === null ||
133
+ (Array.isArray(noteLine.taxes) && noteLine.taxes.length === 0)) &&
134
+ Array.isArray(noteLine.pretax_credit_amounts) &&
135
+ noteLine.pretax_credit_amounts.length === 0 &&
136
+ line &&
137
+ line.currency === record.binding.plan.rate.currency &&
138
+ line.amount >= opts.amount &&
139
+ line.pricing?.price_details?.price === record.binding.stripePriceId &&
140
+ line.parent?.subscription_item_details?.subscription_item ===
141
+ sub.subscriptionItemId &&
142
+ !line.parent?.subscription_item_details?.proration &&
143
+ line.period.start === sub.period.start &&
144
+ line.period.end === sub.period.end &&
145
+ Array.isArray(line.pretax_credit_amounts) &&
146
+ line.pretax_credit_amounts.length === 0,
147
+ );
148
+ let paymentIntentId: string | null = null,
149
+ chargeId: string | null = null,
150
+ refundId: string | null = null;
151
+ if (note.post_payment_amount > 0) {
152
+ requireProof(
153
+ note.refunds.length === 1 &&
154
+ note.refunds[0].type === "refund" &&
155
+ note.refunds[0].amount_refunded === note.post_payment_amount,
156
+ );
157
+ refundId = referenceId(note.refunds[0].refund) ?? null;
158
+ requireProof(refundId);
159
+ const refund = await stripe.refunds.retrieve(refundId!);
160
+ paymentIntentId = referenceId(refund.payment_intent) ?? null;
161
+ chargeId = referenceId(refund.charge) ?? null;
162
+ requireProof(
163
+ refund.id === refundId &&
164
+ refund.status === "succeeded" &&
165
+ refund.amount === note.post_payment_amount &&
166
+ refund.currency === note.currency &&
167
+ paymentIntentId &&
168
+ chargeId,
169
+ );
170
+ const [payment, charge, payments] = await Promise.all([
171
+ stripe.paymentIntents.retrieve(paymentIntentId!),
172
+ stripe.charges.retrieve(chargeId!),
173
+ stripe.invoicePayments.list({
174
+ invoice: invoice.id,
175
+ status: "paid",
176
+ limit: 100,
177
+ }),
178
+ ]);
179
+ const references = payments.data.map(paymentReference);
180
+ requireProof(
181
+ payments.has_more === false &&
182
+ references.some(
183
+ ({ invoicePayment: p }) =>
184
+ referenceId(p.invoice) === invoice.id &&
185
+ p.status === "paid" &&
186
+ p.currency === note.currency &&
187
+ p.amount_paid !== null &&
188
+ p.amount_paid >= refund.amount &&
189
+ p.payment.type === "payment_intent" &&
190
+ referenceId(p.payment.payment_intent) === paymentIntentId,
191
+ ),
192
+ );
193
+ requireProof(
194
+ [
195
+ refund.amount,
196
+ payment.amount,
197
+ payment.amount_received,
198
+ charge.amount,
199
+ charge.amount_captured,
200
+ charge.amount_refunded,
201
+ ].every((value) => Number.isSafeInteger(value) && value >= 0),
202
+ );
203
+ requireProof(
204
+ refund.object === "refund" &&
205
+ payment.object === "payment_intent" &&
206
+ charge.object === "charge" &&
207
+ charge.amount_captured === payment.amount_received &&
208
+ charge.amount_captured <= charge.amount &&
209
+ charge.amount_captured <= payment.amount &&
210
+ (!payment.customer ||
211
+ referenceId(payment.customer) ===
212
+ record.binding.stripeCustomerId) &&
213
+ referenceId(charge.customer) === referenceId(payment.customer),
214
+ );
215
+ requireProof(
216
+ payment.id === paymentIntentId &&
217
+ payment.livemode === record.scope.livemode &&
218
+ payment.customer_account === record.scope.customerAccount &&
219
+ payment.status === "succeeded" &&
220
+ payment.currency === note.currency &&
221
+ referenceId(payment.latest_charge) === chargeId &&
222
+ payment.amount_received >= refund.amount &&
223
+ charge.id === chargeId &&
224
+ charge.payment_intent === paymentIntentId &&
225
+ charge.livemode === record.scope.livemode &&
226
+ charge.currency === note.currency &&
227
+ charge.paid &&
228
+ charge.captured &&
229
+ charge.status === "succeeded" &&
230
+ !charge.disputed &&
231
+ charge.amount_captured >= refund.amount &&
232
+ charge.amount_refunded >= refund.amount &&
233
+ charge.amount_refunded <= charge.amount_captured,
234
+ );
235
+ } else requireProof(note.refunds.length === 0);
236
+ proof = invoiceCorrectionProof.parse({
237
+ creditNoteStatus: note.status,
238
+ stripeAccountId: record.scope.stripeAccountId,
239
+ customerAccount: record.scope.customerAccount,
240
+ livemode: record.scope.livemode,
241
+ stripeCustomerId: record.binding.stripeCustomerId,
242
+ subscriptionId: sub.subscriptionId,
243
+ subscriptionItemId: sub.subscriptionItemId,
244
+ stripePriceId: record.binding.stripePriceId,
245
+ period: sub.period,
246
+ creditNoteId: note.id,
247
+ invoiceId: invoice.id,
248
+ invoiceLineId: line!.id,
249
+ currency: note.currency,
250
+ amount: note.amount,
251
+ prePaymentAmount: note.pre_payment_amount,
252
+ postPaymentAmount: note.post_payment_amount,
253
+ paymentIntentId,
254
+ chargeId,
255
+ refundId,
256
+ });
257
+ } catch {
258
+ return {
259
+ status: "held" as const,
260
+ reason: "native_invoice_adjustment_unverified",
261
+ };
262
+ }
263
+ const saved = (await runMutationOrThrow(
264
+ ctx,
265
+ componentRef(component, "usageCorrections/mutations/adopt"),
266
+ { key: row.key, proofJson: JSON.stringify(proof) },
267
+ )) as Doc<"usageCorrections">;
268
+ return correctionView(saved);
269
+ }
@@ -0,0 +1,40 @@
1
+ import { z } from "zod";
2
+ export const invoiceCorrectionProof = z.strictObject({
3
+ creditNoteStatus: z.enum(["issued", "void"]),
4
+ stripeAccountId: z.string(),
5
+ livemode: z.boolean(),
6
+ customerAccount: z.string(),
7
+ stripeCustomerId: z.string(),
8
+ subscriptionId: z.string(),
9
+ subscriptionItemId: z.string(),
10
+ stripePriceId: z.string(),
11
+ period: z.strictObject({ start: z.number().int(), end: z.number().int() }),
12
+ creditNoteId: z
13
+ .string()
14
+ .regex(/^cn_[a-zA-Z0-9]+$/)
15
+ .max(100),
16
+ invoiceId: z
17
+ .string()
18
+ .regex(/^in_[a-zA-Z0-9]+$/)
19
+ .max(100),
20
+ invoiceLineId: z.string().max(100),
21
+ currency: z.string().regex(/^[a-z]{3}$/),
22
+ amount: z.number().int().positive().max(99999999),
23
+ prePaymentAmount: z.number().int().nonnegative(),
24
+ postPaymentAmount: z.number().int().nonnegative(),
25
+ paymentIntentId: z
26
+ .string()
27
+ .regex(/^pi_[a-zA-Z0-9]+$/)
28
+ .max(100)
29
+ .nullable(),
30
+ chargeId: z
31
+ .string()
32
+ .regex(/^ch_[a-zA-Z0-9]+$/)
33
+ .max(100)
34
+ .nullable(),
35
+ refundId: z
36
+ .string()
37
+ .regex(/^re_[a-zA-Z0-9]+$/)
38
+ .max(100)
39
+ .nullable(),
40
+ });
@@ -0,0 +1,40 @@
1
+ import { z } from "zod";
2
+ export const correctionOutcome = z.union([
3
+ z.strictObject({
4
+ status: z.enum(["pending", "complete"]),
5
+ eventName: z.string().min(1).max(100),
6
+ identifier: z.string().min(1).max(100),
7
+ livemode: z.boolean(),
8
+ nativeAdjustmentId: z.string().min(1).max(100).nullable(),
9
+ creditBackingVerified: z.boolean(),
10
+ billingSafe: z.boolean().default(false),
11
+ invoiceId: z
12
+ .string()
13
+ .regex(/^in_[a-zA-Z0-9]+$/)
14
+ .max(100)
15
+ .optional(),
16
+ }),
17
+ z.strictObject({
18
+ status: z.literal("local_complete"),
19
+ creditBackingVerified: z.literal(true),
20
+ }),
21
+ z.strictObject({
22
+ status: z.enum(["held", "invoice_adjustment_required", "unsupported"]),
23
+ reason: z.enum([
24
+ "native_cancellation_expired",
25
+ "original_delivery_unresolved",
26
+ "provider_unavailable",
27
+ "provider_outcome_unknown",
28
+ "billing_period_closed",
29
+ "native_invoice_finalized",
30
+ "native_invoice_history_incomplete",
31
+ "credit_backing_requires_reconciliation",
32
+ "native_cancellation_rejected",
33
+ ]),
34
+ invoiceId: z
35
+ .string()
36
+ .regex(/^in_[a-zA-Z0-9]+$/)
37
+ .max(100)
38
+ .optional(),
39
+ }),
40
+ ]);