@fantastic.dev/better-stripe 0.42.0 → 0.44.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 (127) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/README.md +11 -4
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +1022 -0
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +511 -0
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +1054 -32
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +527 -16
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  11. package/dist/client/costRecovery-invoices.d.ts +3 -2
  12. package/dist/client/costRecovery-invoices.d.ts.map +1 -1
  13. package/dist/client/costRecovery-invoices.js +10 -5
  14. package/dist/client/costRecovery-invoices.js.map +1 -1
  15. package/dist/client/costRecovery.d.ts +4 -2
  16. package/dist/client/costRecovery.d.ts.map +1 -1
  17. package/dist/client/costRecovery.js +2 -2
  18. package/dist/client/costRecovery.js.map +1 -1
  19. package/dist/client/processingCostReconciliation/client.d.ts +14 -0
  20. package/dist/client/processingCostReconciliation/client.d.ts.map +1 -0
  21. package/dist/client/processingCostReconciliation/client.js +35 -0
  22. package/dist/client/processingCostReconciliation/client.js.map +1 -0
  23. package/dist/client/processingCostReconciliation/contracts.d.ts +172 -0
  24. package/dist/client/processingCostReconciliation/contracts.d.ts.map +1 -0
  25. package/dist/client/processingCostReconciliation/contracts.js +55 -0
  26. package/dist/client/processingCostReconciliation/contracts.js.map +1 -0
  27. package/dist/client/processingCostReconciliation/invoiceFunding.d.ts +15 -0
  28. package/dist/client/processingCostReconciliation/invoiceFunding.d.ts.map +1 -0
  29. package/dist/client/processingCostReconciliation/invoiceFunding.js +195 -0
  30. package/dist/client/processingCostReconciliation/invoiceFunding.js.map +1 -0
  31. package/dist/client/processingCostReconciliation/provider.d.ts +9 -0
  32. package/dist/client/processingCostReconciliation/provider.d.ts.map +1 -0
  33. package/dist/client/processingCostReconciliation/provider.js +148 -0
  34. package/dist/client/processingCostReconciliation/provider.js.map +1 -0
  35. package/dist/client/settlement/processingCostHistory.d.ts +12 -0
  36. package/dist/client/settlement/processingCostHistory.d.ts.map +1 -0
  37. package/dist/client/settlement/processingCostHistory.js +20 -0
  38. package/dist/client/settlement/processingCostHistory.js.map +1 -0
  39. package/dist/client/settlement/processingCosts.d.ts +3 -0
  40. package/dist/client/settlement/processingCosts.d.ts.map +1 -1
  41. package/dist/client/settlement/processingCosts.js +27 -7
  42. package/dist/client/settlement/processingCosts.js.map +1 -1
  43. package/dist/component/_generated/api.d.ts +18 -0
  44. package/dist/component/_generated/api.d.ts.map +1 -1
  45. package/dist/component/_generated/api.js.map +1 -1
  46. package/dist/component/_generated/component.d.ts +515 -0
  47. package/dist/component/_generated/component.d.ts.map +1 -1
  48. package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
  49. package/dist/component/balanceFunding/mutations.d.ts +16 -16
  50. package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
  51. package/dist/component/balanceFunding/workflowValidators.d.ts +16 -16
  52. package/dist/component/earnings/triggers.d.ts +318 -16
  53. package/dist/component/earnings/triggers.d.ts.map +1 -1
  54. package/dist/component/payoutRelease/queries.d.ts +2 -2
  55. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  56. package/dist/component/processingCostReconciliation/adoption.d.ts +29 -0
  57. package/dist/component/processingCostReconciliation/adoption.d.ts.map +1 -0
  58. package/dist/component/processingCostReconciliation/adoption.js +58 -0
  59. package/dist/component/processingCostReconciliation/adoption.js.map +1 -0
  60. package/dist/component/processingCostReconciliation/bridge.d.ts +45 -0
  61. package/dist/component/processingCostReconciliation/bridge.d.ts.map +1 -0
  62. package/dist/component/processingCostReconciliation/bridge.js +41 -0
  63. package/dist/component/processingCostReconciliation/bridge.js.map +1 -0
  64. package/dist/component/processingCostReconciliation/helpers.d.ts +327 -0
  65. package/dist/component/processingCostReconciliation/helpers.d.ts.map +1 -0
  66. package/dist/component/processingCostReconciliation/helpers.js +39 -0
  67. package/dist/component/processingCostReconciliation/helpers.js.map +1 -0
  68. package/dist/component/processingCostReconciliation/mutations.d.ts +303 -0
  69. package/dist/component/processingCostReconciliation/mutations.d.ts.map +1 -0
  70. package/dist/component/processingCostReconciliation/mutations.js +121 -0
  71. package/dist/component/processingCostReconciliation/mutations.js.map +1 -0
  72. package/dist/component/processingCostReconciliation/queries.d.ts +422 -0
  73. package/dist/component/processingCostReconciliation/queries.d.ts.map +1 -0
  74. package/dist/component/processingCostReconciliation/queries.js +19 -0
  75. package/dist/component/processingCostReconciliation/queries.js.map +1 -0
  76. package/dist/component/processingCostReconciliation/rollback.d.ts +21 -0
  77. package/dist/component/processingCostReconciliation/rollback.d.ts.map +1 -0
  78. package/dist/component/processingCostReconciliation/rollback.js +54 -0
  79. package/dist/component/processingCostReconciliation/rollback.js.map +1 -0
  80. package/dist/component/processingCostReconciliation/schema.d.ts +2460 -0
  81. package/dist/component/processingCostReconciliation/schema.d.ts.map +1 -0
  82. package/dist/component/processingCostReconciliation/schema.js +137 -0
  83. package/dist/component/processingCostReconciliation/schema.js.map +1 -0
  84. package/dist/component/processingCostReconciliation/steps.d.ts +306 -0
  85. package/dist/component/processingCostReconciliation/steps.d.ts.map +1 -0
  86. package/dist/component/processingCostReconciliation/steps.js +149 -0
  87. package/dist/component/processingCostReconciliation/steps.js.map +1 -0
  88. package/dist/component/processingCostReconciliation/validation.d.ts +13 -0
  89. package/dist/component/processingCostReconciliation/validation.d.ts.map +1 -0
  90. package/dist/component/processingCostReconciliation/validation.js +61 -0
  91. package/dist/component/processingCostReconciliation/validation.js.map +1 -0
  92. package/dist/component/processingCostReconciliation/workflow.d.ts +105 -0
  93. package/dist/component/processingCostReconciliation/workflow.d.ts.map +1 -0
  94. package/dist/component/processingCostReconciliation/workflow.js +33 -0
  95. package/dist/component/processingCostReconciliation/workflow.js.map +1 -0
  96. package/dist/component/schema.d.ts +511 -0
  97. package/dist/component/schema.js +2 -0
  98. package/dist/component/schema.js.map +1 -1
  99. package/docs/react-workflows.md +16 -8
  100. package/package.json +1 -1
  101. package/src/client/costRecovery-invoices.ts +19 -4
  102. package/src/client/costRecovery.ts +4 -2
  103. package/src/client/processingCostReconciliation/client.ts +75 -0
  104. package/src/client/processingCostReconciliation/contracts.ts +176 -0
  105. package/src/client/processingCostReconciliation/invoiceFunding.ts +270 -0
  106. package/src/client/processingCostReconciliation/invoiceProvider.test.ts +353 -0
  107. package/src/client/processingCostReconciliation/provider.test.ts +324 -0
  108. package/src/client/processingCostReconciliation/provider.ts +178 -0
  109. package/src/client/settlement/processingCostHistory.ts +31 -0
  110. package/src/client/settlement/processingCosts.ts +50 -15
  111. package/src/component/_generated/api.ts +18 -0
  112. package/src/component/_generated/component.ts +570 -0
  113. package/src/component/processingCostReconciliation/adoption.test.ts +206 -0
  114. package/src/component/processingCostReconciliation/adoption.ts +77 -0
  115. package/src/component/processingCostReconciliation/bridge.ts +50 -0
  116. package/src/component/processingCostReconciliation/helpers.ts +55 -0
  117. package/src/component/processingCostReconciliation/invoice.test.ts +152 -0
  118. package/src/component/processingCostReconciliation/mutations.ts +148 -0
  119. package/src/component/processingCostReconciliation/queries.ts +18 -0
  120. package/src/component/processingCostReconciliation/rollback.ts +72 -0
  121. package/src/component/processingCostReconciliation/schema.ts +191 -0
  122. package/src/component/processingCostReconciliation/state.test.ts +407 -0
  123. package/src/component/processingCostReconciliation/steps.ts +168 -0
  124. package/src/component/processingCostReconciliation/validation.ts +79 -0
  125. package/src/component/processingCostReconciliation/workflow.test.ts +329 -0
  126. package/src/component/processingCostReconciliation/workflow.ts +50 -0
  127. package/src/component/schema.ts +2 -0
@@ -1,3 +1,7 @@
1
+ import {
2
+ boundedCostHistory,
3
+ type ProcessingCostHistoryBounds,
4
+ } from "./settlement/processingCostHistory.js";
1
5
  import { singleInvoiceFunding } from "./paymentSource/funding.js";
2
6
  import { getProcessingCostContext } from "./settlement/processingCosts.js";
3
7
  import type Stripe from "stripe";
@@ -22,6 +26,7 @@ export function attachRecoveryInvoice(
22
26
  bind: BindInvoiceItem,
23
27
  create?: true,
24
28
  maxItems?: number,
29
+ historyBounds?: ProcessingCostHistoryBounds,
25
30
  ): Promise<InvoiceReceipt>;
26
31
  export function attachRecoveryInvoice(
27
32
  stripe: Stripe,
@@ -30,6 +35,7 @@ export function attachRecoveryInvoice(
30
35
  bind: BindInvoiceItem,
31
36
  create: false,
32
37
  maxItems?: number,
38
+ historyBounds?: ProcessingCostHistoryBounds,
33
39
  ): Promise<
34
40
  | InvoiceReceipt
35
41
  | (Omit<InvoiceReceipt, "invoiceItemId"> & { invoiceItemId: null })
@@ -43,6 +49,7 @@ export async function attachRecoveryInvoice(
43
49
  bind: (invoiceItemId: string) => Promise<RecoveryGroup>,
44
50
  create = true,
45
51
  maxItems = Number.POSITIVE_INFINITY,
52
+ historyBounds?: ProcessingCostHistoryBounds,
46
53
  ) {
47
54
  if (
48
55
  !group ||
@@ -70,10 +77,18 @@ export async function attachRecoveryInvoice(
70
77
  throw new Error("Recovery invoice currency does not match.");
71
78
  let found: Stripe.InvoiceItem | undefined;
72
79
  let inspected = 0;
73
- for await (const item of stripe.invoiceItems.list({
74
- invoice: invoice.id,
75
- limit: 100,
76
- })) {
80
+ const itemRows = historyBounds
81
+ ? await boundedCostHistory(
82
+ (cursor, limit) =>
83
+ stripe.invoiceItems.list({
84
+ invoice: invoice.id,
85
+ limit,
86
+ ...(cursor ? { starting_after: cursor } : {}),
87
+ }),
88
+ historyBounds,
89
+ )
90
+ : stripe.invoiceItems.list({ invoice: invoice.id, limit: 100 });
91
+ for await (const item of itemRows) {
77
92
  if (++inspected > maxItems)
78
93
  throw new Error("Recovery invoice history exceeded its item bound.");
79
94
  if (item.metadata?.[marker] !== group._id) continue;
@@ -1,4 +1,6 @@
1
- import { RecoveryWorkflowClient } from "./recoveryWorkflow/client.js";
1
+ export type { ProcessingCostProviderOptions } from "./processingCostReconciliation/provider.js";
2
+ import { ProcessingCostReconciliationClient } from "./processingCostReconciliation/client.js";
3
+ export type * from "./processingCostReconciliation/contracts.js";
2
4
  export type * from "./recoveryWorkflow/contracts.js";
3
5
  export type { RecoveryProviderOptions } from "./recoveryWorkflow/provider.js";
4
6
  import type Stripe from "stripe";
@@ -99,7 +101,7 @@ export type RecoveryPreparationResult =
99
101
  retryable: false;
100
102
  };
101
103
  /** Host authorizes policy and scope. Provider methods verify invoice outcomes. */
102
- export class CostRecoveryClient extends RecoveryWorkflowClient {
104
+ export class CostRecoveryClient extends ProcessingCostReconciliationClient {
103
105
  constructor(
104
106
  protected readonly component: Component,
105
107
  private readonly provider?: () => Stripe,
@@ -0,0 +1,75 @@
1
+ import {
2
+ observeProcessingCostProvider,
3
+ type ProcessingCostProviderOptions,
4
+ } from "./provider.js";
5
+ import type { ProcessingCostProviderRequest } from "./contracts.js";
6
+ import { createFunctionHandle } from "convex/server";
7
+ import { RecoveryWorkflowClient } from "../recoveryWorkflow/client.js";
8
+ import type { RunCtx } from "../helpers.js";
9
+ import { runMutationOrThrow } from "../helpers.js";
10
+ import { componentRef } from "../webhooks/helpers.js";
11
+ import { processingCostRef } from "./contracts.js";
12
+ import type {
13
+ ProcessingCostOperationRef,
14
+ ProcessingCostOperationStatus,
15
+ ProcessingCostStartOptions,
16
+ ProcessingCostStartResult,
17
+ } from "./contracts.js";
18
+ export abstract class ProcessingCostReconciliationClient extends RecoveryWorkflowClient {
19
+ /** Host authorizes the original source, scope, liability policy and both expected revisions. */
20
+ async startProcessingCostReconciliation(
21
+ ctx: RunCtx,
22
+ options: ProcessingCostStartOptions,
23
+ ): Promise<ProcessingCostStartResult> {
24
+ const { provider, projection, importHook, ...args } = options;
25
+ return (await runMutationOrThrow(
26
+ ctx,
27
+ componentRef(
28
+ this.component,
29
+ "processingCostReconciliation/mutations/start",
30
+ ),
31
+ {
32
+ ...args,
33
+ provider: await createFunctionHandle(provider),
34
+ ...(projection
35
+ ? { projection: await createFunctionHandle(projection) }
36
+ : {}),
37
+ ...(importHook
38
+ ? { importHook: await createFunctionHandle(importHook) }
39
+ : {}),
40
+ maxAttempts: options.maxAttempts ?? 3,
41
+ retryDelayMs: options.retryDelayMs ?? 1000,
42
+ },
43
+ )) as ProcessingCostStartResult;
44
+ }
45
+ getProcessingCostReconciliation(
46
+ ctx: RunCtx,
47
+ op: ProcessingCostOperationRef,
48
+ ): Promise<ProcessingCostOperationStatus> {
49
+ return ctx.runQuery(
50
+ componentRef(this.component, "processingCostReconciliation/queries/get"),
51
+ processingCostRef(op),
52
+ ) as Promise<ProcessingCostOperationStatus>;
53
+ }
54
+ resumeProcessingCostReconciliation(
55
+ ctx: RunCtx,
56
+ op: ProcessingCostOperationRef,
57
+ ): Promise<ProcessingCostOperationStatus> {
58
+ return runMutationOrThrow(
59
+ ctx,
60
+ componentRef(
61
+ this.component,
62
+ "processingCostReconciliation/mutations/resume",
63
+ ),
64
+ processingCostRef(op),
65
+ ) as Promise<ProcessingCostOperationStatus>;
66
+ }
67
+ /** Registered internal host action only. Supply the secret at execution, never in workflow arguments. */
68
+ observeProcessingCosts(
69
+ ctx: RunCtx,
70
+ request: ProcessingCostProviderRequest,
71
+ options: ProcessingCostProviderOptions,
72
+ ) {
73
+ return observeProcessingCostProvider(this.component, ctx, request, options);
74
+ }
75
+ }
@@ -0,0 +1,176 @@
1
+ import { z } from "zod";
2
+ import type { FunctionReference } from "convex/server";
3
+ import type {
4
+ FinancialOutcome,
5
+ FinancialUnavailable,
6
+ } from "../financialOutcomes/contracts.js";
7
+ import { financialUnavailableSchema } from "../financialOutcomes/contracts.js";
8
+ import type { RecoveryClaim, RecoveryScope } from "../costRecovery.js";
9
+ import type {
10
+ ProcessingCostDeficit,
11
+ ProcessingCostDeficitOptions,
12
+ } from "../processingCostDeficit/index.js";
13
+ const id = z.string().min(1).max(200);
14
+ const units = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
15
+ export const costObservationSchema = z
16
+ .object({
17
+ paymentIntentId: id,
18
+ sourceChargeId: id,
19
+ currency: z.string().regex(/^[a-z]{3}$/),
20
+ gross: units.min(1),
21
+ originalProcessingFee: units,
22
+ processingFee: units,
23
+ disputeFees: units,
24
+ principalReturned: units,
25
+ provenance: z
26
+ .object({
27
+ invoiceId: id,
28
+ invoicePaymentId: id,
29
+ customerAccountId: id,
30
+ subscriptionId: id.optional(),
31
+ stripePriceId: id.optional(),
32
+ stripeProductId: id.optional(),
33
+ recoveryInvoiceItemId: id.optional(),
34
+ })
35
+ .strict(),
36
+ })
37
+ .strict()
38
+ .refine((o) => o.principalReturned <= o.gross);
39
+ export type ProcessingCostObservation = z.infer<typeof costObservationSchema>;
40
+ export type ProcessingCostSource =
41
+ | {
42
+ kind: "sale";
43
+ paymentIntentId: string;
44
+ gross: number;
45
+ customerAccountId: string;
46
+ invoiceId?: string;
47
+ subscriptionId?: string;
48
+ stripeAccountId?: string;
49
+ stripePriceId?: string;
50
+ stripeProductId?: string;
51
+ }
52
+ | {
53
+ kind: "invoice_recovery";
54
+ paymentIntentId: string;
55
+ gross: number;
56
+ groupKey: string;
57
+ };
58
+ export type ProcessingCostPolicy = Pick<
59
+ ProcessingCostDeficitOptions,
60
+ "sellingFee" | "liability" | "rounding"
61
+ >;
62
+ export type ProcessingCostOperationRef = RecoveryScope & {
63
+ operationId: string;
64
+ version: number;
65
+ };
66
+ export type ProcessingCostReconciliationResult = {
67
+ claim: RecoveryClaim;
68
+ rollbackClaim?: RecoveryClaim;
69
+ deficit: ProcessingCostDeficit;
70
+ observation: ProcessingCostObservation;
71
+ };
72
+ export type ProcessingCostCompleted = ProcessingCostOperationRef & {
73
+ status: "completed";
74
+ result: ProcessingCostReconciliationResult;
75
+ };
76
+ export type ProcessingCostOperationStatus = ProcessingCostOperationRef &
77
+ (
78
+ | { status: "queued" | "running" }
79
+ | { status: "completed"; result: ProcessingCostReconciliationResult }
80
+ | FinancialUnavailable
81
+ );
82
+ export type ProcessingCostProviderRequest = ProcessingCostOperationRef & {
83
+ providerApiVersion: string;
84
+ definitionVersion: number;
85
+ };
86
+ export type ProcessingCostProviderReceipt = ProcessingCostProviderRequest & {
87
+ outcome: FinancialOutcome<ProcessingCostObservation>;
88
+ };
89
+ export type ProcessingCostImportRequest = ProcessingCostOperationRef & {
90
+ claimKey: string;
91
+ expectedRevision: number;
92
+ sourceChargeId: string;
93
+ sourceGross: number;
94
+ sourceProcessingFee: number;
95
+ };
96
+ export type ProcessingCostOpeningSnapshot = {
97
+ operationKey: string;
98
+ amountDue: number;
99
+ collectedAmount: number;
100
+ revision: number;
101
+ };
102
+ export type ProcessingCostStartOptions = RecoveryScope & {
103
+ claimKey: string;
104
+ requestKey: string;
105
+ expectedRevision: number;
106
+ source: ProcessingCostSource;
107
+ policy: ProcessingCostPolicy;
108
+ rollback?: { groupKey: string; expectedRevision: number };
109
+ provider: FunctionReference<
110
+ "action",
111
+ "internal",
112
+ ProcessingCostProviderRequest,
113
+ ProcessingCostProviderReceipt
114
+ >;
115
+ projection?: FunctionReference<
116
+ "mutation",
117
+ "internal",
118
+ ProcessingCostCompleted,
119
+ unknown
120
+ >;
121
+ importHook?: FunctionReference<
122
+ "mutation",
123
+ "internal",
124
+ ProcessingCostImportRequest,
125
+ ProcessingCostOpeningSnapshot | null
126
+ >;
127
+ providerApiVersion: string;
128
+ definitionVersion: 1;
129
+ maxAttempts?: number;
130
+ retryDelayMs?: number;
131
+ };
132
+ export type ProcessingCostStartResult =
133
+ ProcessingCostOperationStatus | FinancialUnavailable;
134
+ export type ProcessingCostSnapshot = Pick<
135
+ ProcessingCostStartOptions,
136
+ | "accountId"
137
+ | "scopeKey"
138
+ | "currency"
139
+ | "source"
140
+ | "policy"
141
+ | "rollback"
142
+ | "providerApiVersion"
143
+ | "definitionVersion"
144
+ > & {
145
+ version: number;
146
+ status: string;
147
+ result?: ProcessingCostReconciliationResult;
148
+ };
149
+ export const providerReceiptSchema = z
150
+ .object({
151
+ accountId: id,
152
+ scopeKey: id,
153
+ currency: z.string().regex(/^[a-z]{3}$/),
154
+ operationId: id,
155
+ version: z.number().int().min(1),
156
+ providerApiVersion: id,
157
+ definitionVersion: z.number().int().min(1),
158
+ outcome: z.union([
159
+ z
160
+ .object({ status: z.literal("ready"), value: costObservationSchema })
161
+ .strict(),
162
+ financialUnavailableSchema,
163
+ ]),
164
+ })
165
+ .strict();
166
+ export function processingCostRef(
167
+ op: ProcessingCostOperationRef,
168
+ ): ProcessingCostOperationRef {
169
+ return {
170
+ accountId: op.accountId,
171
+ scopeKey: op.scopeKey,
172
+ currency: op.currency,
173
+ operationId: op.operationId,
174
+ version: op.version,
175
+ };
176
+ }
@@ -0,0 +1,270 @@
1
+ import type Stripe from "stripe";
2
+ import type { Component, RunCtx } from "../helpers.js";
3
+ import { componentRef } from "../webhooks/helpers.js";
4
+ import type { RecoveryGroup } from "../costRecovery.js";
5
+ import { attachRecoveryInvoice } from "../costRecovery-invoices.js";
6
+ import { singleInvoiceFunding } from "../paymentSource/funding.js";
7
+ import { saleAmountFailure } from "../paymentSource/economics.js";
8
+ import { boundedCostHistory } from "../settlement/processingCostHistory.js";
9
+ import {
10
+ getProcessingCostContext,
11
+ type ProcessingCostContext,
12
+ } from "../settlement/processingCosts.js";
13
+ import { processingCostOutcome } from "../financialOutcomes/adapters.js";
14
+ import type { FinancialOutcome } from "../financialOutcomes/contracts.js";
15
+ import type {
16
+ ProcessingCostObservation,
17
+ ProcessingCostSnapshot,
18
+ } from "./contracts.js";
19
+ const bounds = { maxPages: 5, maxItems: 500 };
20
+ const identity = () =>
21
+ ({
22
+ status: "conflict",
23
+ reason: "identity_changed",
24
+ retryable: false,
25
+ }) as const;
26
+ const unsupported = () =>
27
+ ({
28
+ status: "rejected",
29
+ reason: "unsupported_source",
30
+ retryable: false,
31
+ }) as const;
32
+ const incomplete = () =>
33
+ ({
34
+ status: "unknown",
35
+ reason: "history_incomplete",
36
+ retryable: false,
37
+ }) as const;
38
+ const id = (value: string | { id: string } | null | undefined) =>
39
+ typeof value === "string" ? value : value?.id;
40
+ const integer = (n: unknown) =>
41
+ typeof n === "number" && Number.isSafeInteger(n) && n >= 0;
42
+ type VerifiedFunding = {
43
+ cost: Extract<ProcessingCostContext, { status: "ready" }>;
44
+ provenance: ProcessingCostObservation["provenance"];
45
+ };
46
+ function validRow(row: Stripe.InvoicePayment, invoice: Stripe.Invoice) {
47
+ return (
48
+ row.object === "invoice_payment" &&
49
+ ["paid", "open", "canceled"].includes(row.status) &&
50
+ row.currency === invoice.currency &&
51
+ row.livemode === invoice.livemode &&
52
+ !!id(row.invoice) &&
53
+ !!row.payment &&
54
+ typeof row.payment.type === "string"
55
+ );
56
+ }
57
+ /** A collected recovery item has funding provenance, not an invented original price. All provider IO is read-only. */
58
+ export async function readCollectedInvoiceFunding(
59
+ stripe: Stripe,
60
+ component: Component,
61
+ ctx: RunCtx,
62
+ op: ProcessingCostSnapshot,
63
+ ): Promise<FinancialOutcome<VerifiedFunding>> {
64
+ if (
65
+ op.source.kind !== "invoice_recovery" ||
66
+ !op.rollback ||
67
+ op.rollback.groupKey !== op.source.groupKey
68
+ )
69
+ return identity();
70
+ const group = (await ctx.runQuery(
71
+ componentRef(component, "costRecovery/queries/group"),
72
+ { groupKey: op.source.groupKey },
73
+ )) as RecoveryGroup | null;
74
+ if (
75
+ !group ||
76
+ group.accountId !== op.accountId ||
77
+ group.scopeKey !== op.scopeKey ||
78
+ group.currency !== op.currency ||
79
+ group.sourceKind !== "invoice" ||
80
+ !group.invoiceItemId
81
+ )
82
+ return identity();
83
+ if (group.status !== "collected")
84
+ return { status: "not_ready", reason: "provider_pending", retryable: true };
85
+ const invoice = await stripe.invoices.retrieve(group.sourceId);
86
+ if (
87
+ invoice.object !== "invoice" ||
88
+ invoice.id !== group.sourceId ||
89
+ invoice.customer_account !== group.accountId ||
90
+ typeof invoice.livemode !== "boolean"
91
+ )
92
+ return identity();
93
+ if (invoice.currency !== op.currency)
94
+ return {
95
+ status: "rejected",
96
+ reason: "currency_mismatch",
97
+ retryable: false,
98
+ };
99
+ if (
100
+ invoice.status !== "paid" ||
101
+ ![invoice.amount_paid, invoice.amount_due, invoice.total].every(
102
+ (n) => integer(n) && n === op.source.gross,
103
+ ) ||
104
+ invoice.amount_remaining !== 0 ||
105
+ invoice.amount_overpaid !== 0
106
+ )
107
+ return unsupported();
108
+ await attachRecoveryInvoice(
109
+ stripe,
110
+ group,
111
+ {
112
+ accountId: op.accountId,
113
+ scopeKey: op.scopeKey,
114
+ currency: op.currency,
115
+ groupKey: group.groupKey,
116
+ },
117
+ async () => {
118
+ throw new Error("Collected recovery item must already be bound.");
119
+ },
120
+ false,
121
+ 500,
122
+ bounds,
123
+ );
124
+ const forward = await boundedCostHistory(
125
+ (cursor, limit) =>
126
+ stripe.invoicePayments.list({
127
+ invoice: invoice.id,
128
+ limit,
129
+ ...(cursor ? { starting_after: cursor } : {}),
130
+ }),
131
+ bounds,
132
+ );
133
+ if (forward.some((row) => !validRow(row, invoice))) return incomplete();
134
+ if (forward.some((row) => id(row.invoice) !== invoice.id)) return identity();
135
+ const funded = singleInvoiceFunding(forward, invoice.amount_paid);
136
+ if (
137
+ !funded ||
138
+ !integer(funded.amount_paid) ||
139
+ funded.amount_requested !== op.source.gross
140
+ )
141
+ return unsupported();
142
+ if (id(funded.payment.payment_intent) !== op.source.paymentIntentId)
143
+ return identity();
144
+ const paymentIntentId = op.source.paymentIntentId;
145
+ const inverse = await boundedCostHistory(
146
+ (cursor, limit) =>
147
+ stripe.invoicePayments.list({
148
+ payment: { type: "payment_intent", payment_intent: paymentIntentId },
149
+ limit,
150
+ ...(cursor ? { starting_after: cursor } : {}),
151
+ }),
152
+ bounds,
153
+ );
154
+ if (inverse.some((row) => !validRow(row, invoice))) return incomplete();
155
+ if (
156
+ inverse.some(
157
+ (row) =>
158
+ row.payment.type !== "payment_intent" ||
159
+ id(row.payment.payment_intent) !== paymentIntentId,
160
+ )
161
+ )
162
+ return identity();
163
+ const unique = singleInvoiceFunding(inverse, op.source.gross);
164
+ if (!unique || unique.amount_requested !== op.source.gross)
165
+ return unsupported();
166
+ if (unique.id !== funded.id || id(unique.invoice) !== invoice.id)
167
+ return identity();
168
+ const payment = await stripe.paymentIntents.retrieve(paymentIntentId, {
169
+ expand: ["latest_charge.balance_transaction"],
170
+ });
171
+ if (
172
+ payment.object !== "payment_intent" ||
173
+ payment.id !== paymentIntentId ||
174
+ payment.customer_account !== group.accountId ||
175
+ payment.livemode !== invoice.livemode
176
+ )
177
+ return identity();
178
+ if (payment.status === "processing")
179
+ return { status: "not_ready", reason: "provider_pending", retryable: true };
180
+ if (payment.status !== "succeeded")
181
+ return {
182
+ status: "rejected",
183
+ reason: "payment_not_payable",
184
+ retryable: false,
185
+ };
186
+ if (
187
+ payment.amount !== op.source.gross ||
188
+ payment.amount_received !== op.source.gross ||
189
+ payment.currency !== op.currency
190
+ )
191
+ return identity();
192
+ const charge = payment.latest_charge;
193
+ if (!charge || typeof charge === "string")
194
+ return { status: "not_ready", reason: "provider_pending", retryable: true };
195
+ if (
196
+ charge.object !== "charge" ||
197
+ !charge.id ||
198
+ id(charge.payment_intent) !== payment.id ||
199
+ charge.livemode !== payment.livemode
200
+ )
201
+ return identity();
202
+ if (
203
+ !charge.paid ||
204
+ !charge.captured ||
205
+ charge.status !== "succeeded" ||
206
+ charge.amount_captured !== op.source.gross
207
+ )
208
+ return unsupported();
209
+ if (!charge.balance_transaction)
210
+ return { status: "not_ready", reason: "fee_pending", retryable: true };
211
+ const balance =
212
+ typeof charge.balance_transaction === "string"
213
+ ? await stripe.balanceTransactions.retrieve(charge.balance_transaction)
214
+ : charge.balance_transaction;
215
+ if (
216
+ (typeof charge.balance_transaction === "string" &&
217
+ balance.id !== charge.balance_transaction) ||
218
+ balance.object !== "balance_transaction" ||
219
+ !balance.id ||
220
+ id(balance.source) !== charge.id
221
+ )
222
+ return identity();
223
+ const invalid = saleAmountFailure(payment, charge, balance);
224
+ if (invalid === "currency")
225
+ return {
226
+ status: "rejected",
227
+ reason: "currency_mismatch",
228
+ retryable: false,
229
+ };
230
+ if (
231
+ invalid ||
232
+ !integer(balance.amount) ||
233
+ !integer(balance.net) ||
234
+ balance.amount !== op.source.gross ||
235
+ balance.amount - balance.fee !== balance.net
236
+ )
237
+ return unsupported();
238
+ const cost = await getProcessingCostContext(stripe, {
239
+ paymentIntentId,
240
+ historyBounds: bounds,
241
+ });
242
+ if (cost.status !== "ready") return processingCostOutcome(cost);
243
+ if (
244
+ cost.paymentIntentId !== payment.id ||
245
+ cost.chargeId !== charge.id ||
246
+ cost.gross !== op.source.gross ||
247
+ cost.currency !== op.currency ||
248
+ cost.processingFee !== balance.fee
249
+ )
250
+ return identity();
251
+ if (
252
+ group.invoiceFunding &&
253
+ (group.invoiceFunding.sourceChargeId !== cost.chargeId ||
254
+ group.invoiceFunding.sourceGross !== cost.gross ||
255
+ group.invoiceFunding.sourceProcessingFee !== cost.processingFee)
256
+ )
257
+ return identity();
258
+ return {
259
+ status: "ready",
260
+ value: {
261
+ cost,
262
+ provenance: {
263
+ invoiceId: invoice.id,
264
+ invoicePaymentId: funded.id,
265
+ customerAccountId: group.accountId,
266
+ recoveryInvoiceItemId: group.invoiceItemId,
267
+ },
268
+ },
269
+ };
270
+ }