@fantastic.dev/better-stripe 0.41.0 → 0.43.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 (209) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +1 -1
  3. package/dist/client/balanceFundingWorkflow/client.d.ts +172 -0
  4. package/dist/client/balanceFundingWorkflow/client.d.ts.map +1 -0
  5. package/dist/client/balanceFundingWorkflow/client.js +289 -0
  6. package/dist/client/balanceFundingWorkflow/client.js.map +1 -0
  7. package/dist/client/billing/balanceFunding.d.ts +5 -0
  8. package/dist/client/billing/balanceFunding.d.ts.map +1 -1
  9. package/dist/client/billing/balanceFunding.js +30 -0
  10. package/dist/client/billing/balanceFunding.js.map +1 -1
  11. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +1388 -2
  12. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  13. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +710 -17
  14. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  15. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +1420 -34
  16. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  17. package/dist/client/connect/payoutSyncTestHelpers.d.ts +694 -1
  18. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  19. package/dist/client/costRecovery-invoices.d.ts +3 -2
  20. package/dist/client/costRecovery-invoices.d.ts.map +1 -1
  21. package/dist/client/costRecovery-invoices.js +10 -5
  22. package/dist/client/costRecovery-invoices.js.map +1 -1
  23. package/dist/client/costRecovery.d.ts +4 -2
  24. package/dist/client/costRecovery.d.ts.map +1 -1
  25. package/dist/client/costRecovery.js +2 -2
  26. package/dist/client/costRecovery.js.map +1 -1
  27. package/dist/client/index.d.ts +3 -0
  28. package/dist/client/index.d.ts.map +1 -1
  29. package/dist/client/index.js +4 -0
  30. package/dist/client/index.js.map +1 -1
  31. package/dist/client/processingCostReconciliation/client.d.ts +14 -0
  32. package/dist/client/processingCostReconciliation/client.d.ts.map +1 -0
  33. package/dist/client/processingCostReconciliation/client.js +35 -0
  34. package/dist/client/processingCostReconciliation/client.js.map +1 -0
  35. package/dist/client/processingCostReconciliation/contracts.d.ts +172 -0
  36. package/dist/client/processingCostReconciliation/contracts.d.ts.map +1 -0
  37. package/dist/client/processingCostReconciliation/contracts.js +55 -0
  38. package/dist/client/processingCostReconciliation/contracts.js.map +1 -0
  39. package/dist/client/processingCostReconciliation/invoiceFunding.d.ts +15 -0
  40. package/dist/client/processingCostReconciliation/invoiceFunding.d.ts.map +1 -0
  41. package/dist/client/processingCostReconciliation/invoiceFunding.js +195 -0
  42. package/dist/client/processingCostReconciliation/invoiceFunding.js.map +1 -0
  43. package/dist/client/processingCostReconciliation/provider.d.ts +9 -0
  44. package/dist/client/processingCostReconciliation/provider.d.ts.map +1 -0
  45. package/dist/client/processingCostReconciliation/provider.js +148 -0
  46. package/dist/client/processingCostReconciliation/provider.js.map +1 -0
  47. package/dist/client/settlement/processingCostHistory.d.ts +12 -0
  48. package/dist/client/settlement/processingCostHistory.d.ts.map +1 -0
  49. package/dist/client/settlement/processingCostHistory.js +20 -0
  50. package/dist/client/settlement/processingCostHistory.js.map +1 -0
  51. package/dist/client/settlement/processingCosts.d.ts +3 -0
  52. package/dist/client/settlement/processingCosts.d.ts.map +1 -1
  53. package/dist/client/settlement/processingCosts.js +27 -7
  54. package/dist/client/settlement/processingCosts.js.map +1 -1
  55. package/dist/component/_generated/api.d.ts +36 -0
  56. package/dist/component/_generated/api.d.ts.map +1 -1
  57. package/dist/component/_generated/api.js.map +1 -1
  58. package/dist/component/_generated/component.d.ts +988 -0
  59. package/dist/component/_generated/component.d.ts.map +1 -1
  60. package/dist/component/balanceFunding/helpers.d.ts +42 -0
  61. package/dist/component/balanceFunding/helpers.d.ts.map +1 -1
  62. package/dist/component/balanceFunding/internal/actions.d.ts +39 -0
  63. package/dist/component/balanceFunding/internal/actions.d.ts.map +1 -0
  64. package/dist/component/balanceFunding/internal/actions.js +80 -0
  65. package/dist/component/balanceFunding/internal/actions.js.map +1 -0
  66. package/dist/component/balanceFunding/internal/mutations.d.ts +55 -0
  67. package/dist/component/balanceFunding/internal/mutations.d.ts.map +1 -0
  68. package/dist/component/balanceFunding/internal/mutations.js +54 -0
  69. package/dist/component/balanceFunding/internal/mutations.js.map +1 -0
  70. package/dist/component/balanceFunding/internal/queries.d.ts +116 -0
  71. package/dist/component/balanceFunding/internal/queries.d.ts.map +1 -0
  72. package/dist/component/balanceFunding/internal/queries.js +35 -0
  73. package/dist/component/balanceFunding/internal/queries.js.map +1 -0
  74. package/dist/component/balanceFunding/internal/workflow.d.ts +10 -0
  75. package/dist/component/balanceFunding/internal/workflow.d.ts.map +1 -0
  76. package/dist/component/balanceFunding/internal/workflow.js +31 -0
  77. package/dist/component/balanceFunding/internal/workflow.js.map +1 -0
  78. package/dist/component/balanceFunding/lifecycleHandlers.d.ts +126 -0
  79. package/dist/component/balanceFunding/lifecycleHandlers.d.ts.map +1 -1
  80. package/dist/component/balanceFunding/mutations.d.ts +419 -16
  81. package/dist/component/balanceFunding/mutations.d.ts.map +1 -1
  82. package/dist/component/balanceFunding/mutations.js +24 -0
  83. package/dist/component/balanceFunding/mutations.js.map +1 -1
  84. package/dist/component/balanceFunding/preparationHandlers.d.ts +42 -0
  85. package/dist/component/balanceFunding/preparationHandlers.d.ts.map +1 -1
  86. package/dist/component/balanceFunding/queries.d.ts +78 -0
  87. package/dist/component/balanceFunding/queries.d.ts.map +1 -1
  88. package/dist/component/balanceFunding/queries.js +35 -0
  89. package/dist/component/balanceFunding/queries.js.map +1 -1
  90. package/dist/component/balanceFunding/receipt.d.ts +5 -0
  91. package/dist/component/balanceFunding/receipt.d.ts.map +1 -0
  92. package/dist/component/balanceFunding/receipt.js +37 -0
  93. package/dist/component/balanceFunding/receipt.js.map +1 -0
  94. package/dist/component/balanceFunding/schema.d.ts +506 -2
  95. package/dist/component/balanceFunding/schema.d.ts.map +1 -1
  96. package/dist/component/balanceFunding/schema.js +2 -0
  97. package/dist/component/balanceFunding/schema.js.map +1 -1
  98. package/dist/component/balanceFunding/stateHandlers.d.ts +42 -0
  99. package/dist/component/balanceFunding/stateHandlers.d.ts.map +1 -1
  100. package/dist/component/balanceFunding/workflowControl.d.ts +19 -0
  101. package/dist/component/balanceFunding/workflowControl.d.ts.map +1 -0
  102. package/dist/component/balanceFunding/workflowControl.js +149 -0
  103. package/dist/component/balanceFunding/workflowControl.js.map +1 -0
  104. package/dist/component/balanceFunding/workflowSchema.d.ts +356 -0
  105. package/dist/component/balanceFunding/workflowSchema.d.ts.map +1 -0
  106. package/dist/component/balanceFunding/workflowSchema.js +48 -0
  107. package/dist/component/balanceFunding/workflowSchema.js.map +1 -0
  108. package/dist/component/balanceFunding/workflowState.d.ts +157 -0
  109. package/dist/component/balanceFunding/workflowState.d.ts.map +1 -0
  110. package/dist/component/balanceFunding/workflowState.js +194 -0
  111. package/dist/component/balanceFunding/workflowState.js.map +1 -0
  112. package/dist/component/balanceFunding/workflowValidators.d.ts +306 -0
  113. package/dist/component/balanceFunding/workflowValidators.d.ts.map +1 -0
  114. package/dist/component/balanceFunding/workflowValidators.js +27 -0
  115. package/dist/component/balanceFunding/workflowValidators.js.map +1 -0
  116. package/dist/component/earnings/triggers.d.ts +388 -2
  117. package/dist/component/earnings/triggers.d.ts.map +1 -1
  118. package/dist/component/payoutRelease/queries.d.ts +2 -2
  119. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  120. package/dist/component/processingCostReconciliation/adoption.d.ts +29 -0
  121. package/dist/component/processingCostReconciliation/adoption.d.ts.map +1 -0
  122. package/dist/component/processingCostReconciliation/adoption.js +58 -0
  123. package/dist/component/processingCostReconciliation/adoption.js.map +1 -0
  124. package/dist/component/processingCostReconciliation/bridge.d.ts +45 -0
  125. package/dist/component/processingCostReconciliation/bridge.d.ts.map +1 -0
  126. package/dist/component/processingCostReconciliation/bridge.js +41 -0
  127. package/dist/component/processingCostReconciliation/bridge.js.map +1 -0
  128. package/dist/component/processingCostReconciliation/helpers.d.ts +327 -0
  129. package/dist/component/processingCostReconciliation/helpers.d.ts.map +1 -0
  130. package/dist/component/processingCostReconciliation/helpers.js +39 -0
  131. package/dist/component/processingCostReconciliation/helpers.js.map +1 -0
  132. package/dist/component/processingCostReconciliation/mutations.d.ts +303 -0
  133. package/dist/component/processingCostReconciliation/mutations.d.ts.map +1 -0
  134. package/dist/component/processingCostReconciliation/mutations.js +121 -0
  135. package/dist/component/processingCostReconciliation/mutations.js.map +1 -0
  136. package/dist/component/processingCostReconciliation/queries.d.ts +422 -0
  137. package/dist/component/processingCostReconciliation/queries.d.ts.map +1 -0
  138. package/dist/component/processingCostReconciliation/queries.js +19 -0
  139. package/dist/component/processingCostReconciliation/queries.js.map +1 -0
  140. package/dist/component/processingCostReconciliation/rollback.d.ts +21 -0
  141. package/dist/component/processingCostReconciliation/rollback.d.ts.map +1 -0
  142. package/dist/component/processingCostReconciliation/rollback.js +54 -0
  143. package/dist/component/processingCostReconciliation/rollback.js.map +1 -0
  144. package/dist/component/processingCostReconciliation/schema.d.ts +2460 -0
  145. package/dist/component/processingCostReconciliation/schema.d.ts.map +1 -0
  146. package/dist/component/processingCostReconciliation/schema.js +137 -0
  147. package/dist/component/processingCostReconciliation/schema.js.map +1 -0
  148. package/dist/component/processingCostReconciliation/steps.d.ts +306 -0
  149. package/dist/component/processingCostReconciliation/steps.d.ts.map +1 -0
  150. package/dist/component/processingCostReconciliation/steps.js +149 -0
  151. package/dist/component/processingCostReconciliation/steps.js.map +1 -0
  152. package/dist/component/processingCostReconciliation/validation.d.ts +13 -0
  153. package/dist/component/processingCostReconciliation/validation.d.ts.map +1 -0
  154. package/dist/component/processingCostReconciliation/validation.js +61 -0
  155. package/dist/component/processingCostReconciliation/validation.js.map +1 -0
  156. package/dist/component/processingCostReconciliation/workflow.d.ts +105 -0
  157. package/dist/component/processingCostReconciliation/workflow.d.ts.map +1 -0
  158. package/dist/component/processingCostReconciliation/workflow.js +33 -0
  159. package/dist/component/processingCostReconciliation/workflow.js.map +1 -0
  160. package/dist/component/schema.d.ts +694 -1
  161. package/dist/component/schema.js +2 -0
  162. package/dist/component/schema.js.map +1 -1
  163. package/package.json +1 -1
  164. package/src/client/balanceFundingWorkflow/capture.test.ts +144 -0
  165. package/src/client/balanceFundingWorkflow/client.ts +419 -0
  166. package/src/client/billing/balanceFunding.ts +50 -0
  167. package/src/client/costRecovery-invoices.ts +19 -4
  168. package/src/client/costRecovery.ts +4 -2
  169. package/src/client/index.ts +15 -0
  170. package/src/client/processingCostReconciliation/client.ts +75 -0
  171. package/src/client/processingCostReconciliation/contracts.ts +176 -0
  172. package/src/client/processingCostReconciliation/invoiceFunding.ts +270 -0
  173. package/src/client/processingCostReconciliation/invoiceProvider.test.ts +353 -0
  174. package/src/client/processingCostReconciliation/provider.test.ts +324 -0
  175. package/src/client/processingCostReconciliation/provider.ts +178 -0
  176. package/src/client/settlement/processingCostHistory.ts +31 -0
  177. package/src/client/settlement/processingCosts.ts +50 -15
  178. package/src/component/_generated/api.ts +36 -0
  179. package/src/component/_generated/component.ts +1094 -0
  180. package/src/component/balanceFunding/internal/actions.ts +107 -0
  181. package/src/component/balanceFunding/internal/mutations.ts +66 -0
  182. package/src/component/balanceFunding/internal/queries.ts +34 -0
  183. package/src/component/balanceFunding/internal/workflow.ts +49 -0
  184. package/src/component/balanceFunding/mutations.ts +34 -0
  185. package/src/component/balanceFunding/queries.ts +38 -0
  186. package/src/component/balanceFunding/receipt.ts +48 -0
  187. package/src/component/balanceFunding/schema.ts +2 -0
  188. package/src/component/balanceFunding/scopeLookup.test.ts +94 -0
  189. package/src/component/balanceFunding/workflow.fixtures.ts +366 -0
  190. package/src/component/balanceFunding/workflow.test.ts +552 -0
  191. package/src/component/balanceFunding/workflowControl.ts +198 -0
  192. package/src/component/balanceFunding/workflowSchema.ts +78 -0
  193. package/src/component/balanceFunding/workflowState.ts +285 -0
  194. package/src/component/balanceFunding/workflowValidators.ts +40 -0
  195. package/src/component/processingCostReconciliation/adoption.test.ts +206 -0
  196. package/src/component/processingCostReconciliation/adoption.ts +77 -0
  197. package/src/component/processingCostReconciliation/bridge.ts +50 -0
  198. package/src/component/processingCostReconciliation/helpers.ts +55 -0
  199. package/src/component/processingCostReconciliation/invoice.test.ts +152 -0
  200. package/src/component/processingCostReconciliation/mutations.ts +148 -0
  201. package/src/component/processingCostReconciliation/queries.ts +18 -0
  202. package/src/component/processingCostReconciliation/rollback.ts +72 -0
  203. package/src/component/processingCostReconciliation/schema.ts +191 -0
  204. package/src/component/processingCostReconciliation/state.test.ts +407 -0
  205. package/src/component/processingCostReconciliation/steps.ts +168 -0
  206. package/src/component/processingCostReconciliation/validation.ts +79 -0
  207. package/src/component/processingCostReconciliation/workflow.test.ts +329 -0
  208. package/src/component/processingCostReconciliation/workflow.ts +50 -0
  209. package/src/component/schema.ts +2 -0
@@ -0,0 +1,168 @@
1
+ import { v } from "convex/values";
2
+ import { anyApi } from "convex/server";
3
+ import { checkRollback } from "./rollback.js";
4
+ import { adopt } from "./adoption.js";
5
+ import type { FunctionHandle } from "convex/server";
6
+ import { observationFailure } from "./validation.js";
7
+ import { internalMutation } from "../_generated/server.js";
8
+ import { observation, refFields, safeStatus, failure } from "./schema.js";
9
+ import {
10
+ read,
11
+ status,
12
+ conflict,
13
+ setFailure,
14
+ reference as referenceFor,
15
+ } from "./helpers.js";
16
+ import { recordClaim, rollbackClaim } from "../costRecovery/claims.js";
17
+ import { calculateProcessingCostDeficit } from "../../client/processingCostDeficit/index.js";
18
+ export const apply = internalMutation({
19
+ args: { ...refFields, observation },
20
+ returns: safeStatus,
21
+ handler: async (ctx, args) => {
22
+ const op = await read(ctx, args);
23
+ if (
24
+ op.result ||
25
+ (op.failure &&
26
+ op.failure.status !== "not_ready" &&
27
+ op.failure.status !== "unknown")
28
+ )
29
+ return status(op);
30
+ let claim = await ctx.db
31
+ .query("recoveryClaims")
32
+ .withIndex("by_key", (q) => q.eq("claimKey", op.claimKey))
33
+ .unique();
34
+ const o = args.observation;
35
+ if (
36
+ claim &&
37
+ (claim.accountId !== op.accountId ||
38
+ claim.scopeKey !== op.scopeKey ||
39
+ claim.currency !== op.currency ||
40
+ claim.sourceChargeId !== o.sourceChargeId ||
41
+ claim.sourceGross !== o.gross ||
42
+ claim.sourceProcessingFee !== o.originalProcessingFee)
43
+ )
44
+ return setFailure(ctx, op, conflict("identity_changed"));
45
+ if ((claim?.revision ?? -1) !== op.expectedRevision) {
46
+ const failure = conflict("revision_changed");
47
+ await ctx.db.patch("processingCostReconciliationOperations", op._id, {
48
+ status: "conflict",
49
+ failure,
50
+ });
51
+ return { ...referenceFor(op), ...failure };
52
+ }
53
+ if (
54
+ o.paymentIntentId !== op.source.paymentIntentId ||
55
+ o.gross !== op.source.gross ||
56
+ o.currency !== op.currency
57
+ )
58
+ throw new Error("Processing-cost source identity does not match.");
59
+ const rollbackCheck = await checkRollback(ctx, op, o);
60
+ if (rollbackCheck.status !== "ready")
61
+ return setFailure(ctx, op, rollbackCheck);
62
+ const original = await ctx.db
63
+ .query("processingCostReconciliationOperations")
64
+ .withIndex("by_claim_status", (q) =>
65
+ q.eq("claimKey", op.claimKey).eq("status", "completed"),
66
+ )
67
+ .order("asc")
68
+ .first();
69
+ const invalid = observationFailure(op, o, original);
70
+ if (invalid) return setFailure(ctx, op, invalid);
71
+ const deficit = calculateProcessingCostDeficit({
72
+ currency: o.currency,
73
+ gross: o.gross,
74
+ ...op.policy,
75
+ processingFee: o.processingFee,
76
+ principalReturned: o.principalReturned,
77
+ disputeFees: o.disputeFees,
78
+ });
79
+ if (!claim && op.importHook) {
80
+ claim = await adopt(ctx, op, o);
81
+ if ((await checkRollback(ctx, op, o)).status !== "ready")
82
+ throw new Error("Processing-cost import changed the rollback state.");
83
+ }
84
+ if (rollbackCheck.bindFunding && op.rollback)
85
+ await ctx.runMutation(anyApi.costRecovery.mutations.bindInvoiceFunding, {
86
+ groupKey: op.rollback.groupKey,
87
+ sourceChargeId: o.sourceChargeId,
88
+ sourceGross: o.gross,
89
+ sourceProcessingFee: o.originalProcessingFee,
90
+ });
91
+ const stored = await recordClaim(ctx, {
92
+ accountId: op.accountId,
93
+ scopeKey: op.scopeKey,
94
+ currency: op.currency,
95
+ claimKey: op.claimKey,
96
+ sourceChargeId: o.sourceChargeId,
97
+ sourceGross: o.gross,
98
+ sourceProcessingFee: o.originalProcessingFee,
99
+ amountDue: deficit.amountDue,
100
+ revision: (claim?.revision ?? -1) + 1,
101
+ });
102
+ const rolledBack = op.rollback
103
+ ? await rollbackClaim(ctx, {
104
+ groupKey: op.rollback.groupKey,
105
+ returnedPrincipal: o.principalReturned,
106
+ revision: op.rollback.expectedRevision + 1,
107
+ })
108
+ : undefined;
109
+ const result = {
110
+ claim: stored,
111
+ ...(rolledBack ? { rollbackClaim: rolledBack } : {}),
112
+ deficit,
113
+ observation: o,
114
+ };
115
+ const completed = {
116
+ ...referenceFor(op),
117
+ status: "completed" as const,
118
+ result,
119
+ };
120
+ if (op.projection) {
121
+ try {
122
+ await ctx.runMutation(
123
+ op.projection as FunctionHandle<"mutation">,
124
+ completed,
125
+ );
126
+ } catch {
127
+ throw new Error("Processing-cost projection failed.");
128
+ }
129
+ }
130
+ await ctx.db.patch("processingCostReconciliationOperations", op._id, {
131
+ status: "completed",
132
+ result,
133
+ failure: undefined,
134
+ });
135
+ return completed;
136
+ },
137
+ });
138
+ export const begin = internalMutation({
139
+ args: refFields,
140
+ returns: v.null(),
141
+ handler: async (ctx, args) => {
142
+ const op = await read(ctx, args);
143
+ if (
144
+ !op.result &&
145
+ (!op.failure ||
146
+ op.failure.status === "not_ready" ||
147
+ op.failure.status === "unknown")
148
+ )
149
+ await ctx.db.patch("processingCostReconciliationOperations", op._id, {
150
+ status: "running",
151
+ failure: undefined,
152
+ });
153
+ return null;
154
+ },
155
+ });
156
+ export const unavailable = internalMutation({
157
+ args: { ...refFields, outcome: failure },
158
+ returns: safeStatus,
159
+ handler: async (ctx, args) => {
160
+ const op = await read(ctx, args);
161
+ if (
162
+ op.result ||
163
+ (op.failure && ["conflict", "rejected"].includes(op.failure.status))
164
+ )
165
+ return status(op);
166
+ return setFailure(ctx, op, args.outcome);
167
+ },
168
+ });
@@ -0,0 +1,79 @@
1
+ import type { Infer } from "convex/values";
2
+ import type { Doc } from "../_generated/dataModel.js";
3
+ import { observation } from "./schema.js";
4
+ import { same } from "../recoveryWorkflow/helpers.js";
5
+ import { conflict } from "./helpers.js";
6
+ const identifier = (value: unknown) =>
7
+ typeof value === "string" && value.trim().length > 0 && value.length <= 200;
8
+ export function observationFailure(
9
+ op: Doc<"processingCostReconciliationOperations">,
10
+ o: Infer<typeof observation>,
11
+ original: Doc<"processingCostReconciliationOperations"> | null,
12
+ ) {
13
+ if (
14
+ [
15
+ o.gross,
16
+ o.originalProcessingFee,
17
+ o.processingFee,
18
+ o.disputeFees,
19
+ o.principalReturned,
20
+ ].some((n) => !Number.isSafeInteger(n) || n < 0) ||
21
+ o.gross === 0 ||
22
+ o.principalReturned > o.gross ||
23
+ !identifier(o.sourceChargeId) ||
24
+ !identifier(o.provenance.invoiceId) ||
25
+ !identifier(o.provenance.invoicePaymentId) ||
26
+ !identifier(o.provenance.customerAccountId)
27
+ )
28
+ return {
29
+ status: "rejected",
30
+ reason: "unsupported_source",
31
+ retryable: false,
32
+ } as const;
33
+ if (
34
+ o.paymentIntentId !== op.source.paymentIntentId ||
35
+ o.gross !== op.source.gross ||
36
+ o.currency !== op.currency
37
+ )
38
+ return conflict("identity_changed");
39
+ if (op.source.kind === "sale") {
40
+ if (o.provenance.recoveryInvoiceItemId !== undefined)
41
+ return conflict("identity_changed");
42
+ if (
43
+ !identifier(o.provenance.stripePriceId) ||
44
+ !identifier(o.provenance.stripeProductId)
45
+ )
46
+ return {
47
+ status: "rejected",
48
+ reason: "unsupported_source",
49
+ retryable: false,
50
+ } as const;
51
+ if (
52
+ o.provenance.customerAccountId !== op.source.customerAccountId ||
53
+ (op.source.invoiceId !== undefined &&
54
+ o.provenance.invoiceId !== op.source.invoiceId) ||
55
+ (op.source.subscriptionId !== undefined &&
56
+ o.provenance.subscriptionId !== op.source.subscriptionId) ||
57
+ (op.source.stripePriceId !== undefined &&
58
+ o.provenance.stripePriceId !== op.source.stripePriceId) ||
59
+ (op.source.stripeProductId !== undefined &&
60
+ o.provenance.stripeProductId !== op.source.stripeProductId)
61
+ )
62
+ return conflict("identity_changed");
63
+ } else if (
64
+ o.provenance.stripePriceId !== undefined ||
65
+ o.provenance.stripeProductId !== undefined
66
+ )
67
+ return conflict("identity_changed");
68
+ if (
69
+ original &&
70
+ (original.policy.sellingFee !== op.policy.sellingFee ||
71
+ original.source.kind !== op.source.kind ||
72
+ (original.source.kind === "sale" &&
73
+ op.source.kind === "sale" &&
74
+ original.source.stripeAccountId !== op.source.stripeAccountId) ||
75
+ !same(original.result?.observation.provenance, o.provenance))
76
+ )
77
+ return conflict("identity_changed");
78
+ return null;
79
+ }
@@ -0,0 +1,329 @@
1
+ import { convexTest } from "convex-test";
2
+ import workflowTest from "@convex-dev/workflow/test";
3
+ import {
4
+ anyApi,
5
+ componentsGeneric,
6
+ defineSchema,
7
+ defineTable,
8
+ internalActionGeneric,
9
+ internalMutationGeneric,
10
+ internalQueryGeneric,
11
+ type FunctionReference,
12
+ } from "convex/server";
13
+ import { v } from "convex/values";
14
+ import { afterEach, beforeEach, expect, it, vi } from "vitest";
15
+ import { CostRecoveryClient } from "../../client/costRecovery.js";
16
+ import type { Component } from "../../client/helpers.js";
17
+ import { executionWorkflow } from "../durableExecution/runtime.js";
18
+ import { schema, modules } from "../../test.js";
19
+ const nested = componentsGeneric();
20
+ const scope = { accountId: "acct_seller", scopeKey: "store", currency: "usd" };
21
+ const observation = {
22
+ paymentIntentId: "pi_a",
23
+ sourceChargeId: "ch_a",
24
+ currency: "usd",
25
+ gross: 1000,
26
+ originalProcessingFee: 30,
27
+ processingFee: 30,
28
+ disputeFees: 0,
29
+ principalReturned: 1000,
30
+ provenance: {
31
+ invoiceId: "in_a",
32
+ invoicePaymentId: "inpay_a",
33
+ customerAccountId: "acct_buyer",
34
+ stripePriceId: "price_original",
35
+ stripeProductId: "prod_original",
36
+ },
37
+ };
38
+ const client = () =>
39
+ new CostRecoveryClient(nested.betterStripe as unknown as Component);
40
+ let calls = 0,
41
+ projectionFailures = 0;
42
+ let outcome: unknown;
43
+ let providerGate: Promise<void> | null;
44
+ const host = {
45
+ start: internalMutationGeneric({
46
+ args: {},
47
+ returns: v.any(),
48
+ handler: (ctx) =>
49
+ client().startProcessingCostReconciliation(ctx, {
50
+ ...scope,
51
+ claimKey: "cost:pi_a",
52
+ requestKey: "workflow-refund",
53
+ expectedRevision: -1,
54
+ source: {
55
+ kind: "sale",
56
+ paymentIntentId: "pi_a",
57
+ gross: 1000,
58
+ customerAccountId: "acct_buyer",
59
+ invoiceId: "in_a",
60
+ },
61
+ policy: {
62
+ sellingFee: 100,
63
+ liability: { processingCosts: "uncovered", disputeCosts: "all" },
64
+ rounding: "nearest",
65
+ },
66
+ provider: anyApi.host.provider as FunctionReference<
67
+ "action",
68
+ "internal"
69
+ >,
70
+ projection: anyApi.host.project as FunctionReference<
71
+ "mutation",
72
+ "internal"
73
+ >,
74
+ providerApiVersion: "2026-09-30.endive",
75
+ definitionVersion: 1,
76
+ maxAttempts: 2,
77
+ retryDelayMs: 1,
78
+ }),
79
+ }),
80
+ provider: internalActionGeneric({
81
+ args: {
82
+ ...Object.fromEntries(Object.keys(scope).map((k) => [k, v.string()])),
83
+ operationId: v.string(),
84
+ version: v.number(),
85
+ providerApiVersion: v.string(),
86
+ definitionVersion: v.number(),
87
+ },
88
+ returns: v.any(),
89
+ handler: async (_ctx, args) => {
90
+ calls++;
91
+ if (providerGate) await providerGate;
92
+ if (outcome instanceof Error) throw outcome;
93
+ return { ...args, outcome };
94
+ },
95
+ }),
96
+ project: internalMutationGeneric({
97
+ args: {
98
+ ...Object.fromEntries(Object.keys(scope).map((k) => [k, v.string()])),
99
+ operationId: v.string(),
100
+ version: v.number(),
101
+ status: v.literal("completed"),
102
+ result: v.any(),
103
+ },
104
+ returns: v.null(),
105
+ handler: async (ctx, args) => {
106
+ if (projectionFailures-- > 0) throw new Error("private database detail");
107
+ await ctx.db.insert("reports", {
108
+ operationId: args.operationId,
109
+ revision: args.result.claim.revision,
110
+ });
111
+ return null;
112
+ },
113
+ }),
114
+ resume: internalMutationGeneric({
115
+ args: { operationId: v.string(), version: v.number() },
116
+ returns: v.any(),
117
+ handler: (ctx, args) =>
118
+ client().resumeProcessingCostReconciliation(ctx, { ...scope, ...args }),
119
+ }),
120
+ freshClaim: internalMutationGeneric({
121
+ args: {},
122
+ returns: v.any(),
123
+ handler: (ctx) =>
124
+ client().recordClaim(ctx, {
125
+ ...scope,
126
+ claimKey: "cost:pi_a",
127
+ sourceChargeId: "ch_a",
128
+ sourceGross: 1000,
129
+ sourceProcessingFee: 30,
130
+ amountDue: 15,
131
+ revision: 0,
132
+ }),
133
+ }),
134
+ };
135
+ async function fixture() {
136
+ const t = convexTest(
137
+ defineSchema({
138
+ reports: defineTable({ operationId: v.string(), revision: v.number() }),
139
+ }),
140
+ { "./_generated/api.ts": async () => ({}), "./host.ts": async () => host },
141
+ );
142
+ t.registerComponent("betterStripe", schema, {
143
+ ...modules,
144
+ "./component/fixture.ts": async () => ({
145
+ history: internalQueryGeneric({
146
+ args: {},
147
+ returns: v.any(),
148
+ handler: async (ctx) => {
149
+ const op = (await ctx.db
150
+ .query("processingCostReconciliationOperations")
151
+ .first())!;
152
+ return executionWorkflow.listSteps(ctx, op.workflowId!, {
153
+ paginationOpts: { cursor: null, numItems: 100 },
154
+ });
155
+ },
156
+ }),
157
+ }),
158
+ });
159
+ workflowTest.register(t, "betterStripe/workflow");
160
+ return t;
161
+ }
162
+ const ref = (op: { operationId: string; version: number }) => ({
163
+ ...scope,
164
+ operationId: op.operationId,
165
+ version: op.version,
166
+ });
167
+ beforeEach(() => {
168
+ vi.useFakeTimers();
169
+ calls = 0;
170
+ projectionFailures = 0;
171
+ providerGate = null;
172
+ outcome = { status: "ready", value: observation };
173
+ });
174
+ afterEach(() => vi.useRealTimers());
175
+ it("runs through the public SDK and real nested Workflow once", async () => {
176
+ const t = await fixture();
177
+ const op = await t.mutation(anyApi.host.start, {});
178
+ expect((await t.mutation(anyApi.host.start, {})).operationId).toBe(
179
+ op.operationId,
180
+ );
181
+ await t.finishAllScheduledFunctions(vi.runAllTimers);
182
+ expect(
183
+ await t.query(
184
+ nested.betterStripe.processingCostReconciliation.queries.get,
185
+ ref(op),
186
+ ),
187
+ ).toMatchObject({
188
+ status: "completed",
189
+ result: { claim: { revision: 0, amountDue: 30 } },
190
+ });
191
+ expect(calls).toBe(1);
192
+ expect(await t.run((ctx) => ctx.db.query("reports").collect())).toHaveLength(
193
+ 1,
194
+ );
195
+ });
196
+ it("restarts failed database projection using the saved provider observation", async () => {
197
+ const t = await fixture();
198
+ projectionFailures = 1;
199
+ const op = await t.mutation(anyApi.host.start, {});
200
+ await t.finishAllScheduledFunctions(vi.runAllTimers);
201
+ expect(
202
+ await t.query(nested.betterStripe.costRecovery.queries.claim, {
203
+ claimKey: "cost:pi_a",
204
+ }),
205
+ ).toBeNull();
206
+ expect(calls).toBe(1);
207
+ await t.mutation(anyApi.host.resume, {
208
+ operationId: op.operationId,
209
+ version: op.version,
210
+ });
211
+ await t.finishAllScheduledFunctions(vi.runAllTimers);
212
+ expect(calls).toBe(1);
213
+ expect(
214
+ await t.query(
215
+ nested.betterStripe.processingCostReconciliation.queries.get,
216
+ ref(op),
217
+ ),
218
+ ).toMatchObject({ status: "completed" });
219
+ });
220
+ it("a racing authoritative claim revision wins before a stale provider observation commits", async () => {
221
+ let release!: () => void;
222
+ providerGate = new Promise<void>((resolve) => {
223
+ release = resolve;
224
+ });
225
+ const t = await fixture();
226
+ const op = await t.mutation(anyApi.host.start, {});
227
+ const drain = t.finishAllScheduledFunctions(vi.runAllTimers);
228
+ await vi.waitFor(() => expect(calls).toBe(1));
229
+ await t.mutation(anyApi.host.freshClaim, {});
230
+ release();
231
+ await drain;
232
+ expect(
233
+ await t.query(
234
+ nested.betterStripe.processingCostReconciliation.queries.get,
235
+ ref(op),
236
+ ),
237
+ ).toMatchObject({ status: "conflict", reason: "revision_changed" });
238
+ expect(
239
+ await t.query(nested.betterStripe.costRecovery.queries.claim, {
240
+ claimKey: "cost:pi_a",
241
+ }),
242
+ ).toMatchObject({ revision: 0, amountDue: 15 });
243
+ expect(await t.run((ctx) => ctx.db.query("reports").collect())).toEqual([]);
244
+ });
245
+
246
+ it.each([
247
+ new Error("sk_test_PRIVATE accidental provider body"),
248
+ {
249
+ status: "ready",
250
+ value: { ...observation, privateMetadata: "sk_test_PRIVATE" },
251
+ },
252
+ ])(
253
+ "holds unknown observations without journaling provider details and explicitly resumes",
254
+ async (unsafe) => {
255
+ const t = await fixture();
256
+ outcome = unsafe;
257
+ const op = await t.mutation(anyApi.host.start, {});
258
+ await t.finishAllScheduledFunctions(vi.runAllTimers);
259
+ expect(calls).toBe(1);
260
+ expect(
261
+ await t.query(
262
+ nested.betterStripe.processingCostReconciliation.queries.get,
263
+ ref(op),
264
+ ),
265
+ ).toMatchObject({
266
+ status: "unknown",
267
+ reason: "provider_outcome_unknown",
268
+ retryable: false,
269
+ });
270
+ expect(
271
+ await t.query(nested.betterStripe.costRecovery.queries.claim, {
272
+ claimKey: "cost:pi_a",
273
+ }),
274
+ ).toBeNull();
275
+ const journal = JSON.stringify(
276
+ await t.query(nested.betterStripe.fixture.history, {}),
277
+ );
278
+ expect(journal).not.toContain("sk_test_PRIVATE");
279
+ expect(journal).not.toContain("accidental provider body");
280
+ expect(journal).not.toContain("privateMetadata");
281
+ outcome = { status: "ready", value: observation };
282
+ await t.mutation(anyApi.host.resume, {
283
+ operationId: op.operationId,
284
+ version: op.version,
285
+ });
286
+ await t.finishAllScheduledFunctions(vi.runAllTimers);
287
+ expect(calls).toBe(2);
288
+ expect(
289
+ await t.query(
290
+ nested.betterStripe.processingCostReconciliation.queries.get,
291
+ ref(op),
292
+ ),
293
+ ).toMatchObject({
294
+ status: "completed",
295
+ result: { claim: { revision: 0, amountDue: 30 } },
296
+ });
297
+ },
298
+ );
299
+ it("bounds known pending retries without creating a zero-cost claim", async () => {
300
+ const t = await fixture();
301
+ outcome = { status: "not_ready", reason: "fee_pending", retryable: true };
302
+ const op = await t.mutation(anyApi.host.start, {});
303
+ await t.finishAllScheduledFunctions(vi.runAllTimers);
304
+ expect(calls).toBe(2);
305
+ expect(
306
+ await t.query(
307
+ nested.betterStripe.processingCostReconciliation.queries.get,
308
+ ref(op),
309
+ ),
310
+ ).toMatchObject({ status: "not_ready", reason: "fee_pending" });
311
+ expect(
312
+ await t.query(nested.betterStripe.costRecovery.queries.claim, {
313
+ claimKey: "cost:pi_a",
314
+ }),
315
+ ).toBeNull();
316
+ outcome = { status: "ready", value: observation };
317
+ await t.mutation(anyApi.host.resume, {
318
+ operationId: op.operationId,
319
+ version: op.version,
320
+ });
321
+ await t.finishAllScheduledFunctions(vi.runAllTimers);
322
+ expect(calls).toBe(3);
323
+ expect(
324
+ await t.query(
325
+ nested.betterStripe.processingCostReconciliation.queries.get,
326
+ ref(op),
327
+ ),
328
+ ).toMatchObject({ status: "completed", result: { claim: { revision: 0 } } });
329
+ });
@@ -0,0 +1,50 @@
1
+ import { anyApi } from "convex/server";
2
+ import type { Infer } from "convex/values";
3
+ import { executionWorkflow } from "../durableExecution/runtime.js";
4
+ import { refFields, safeStatus } from "./schema.js";
5
+ import { financialRetryDecision } from "../../client/financialOutcomes/retry.js";
6
+ export const run = executionWorkflow
7
+ .define({ args: refFields, returns: safeStatus })
8
+ .handler(async (step, args): Promise<Infer<typeof safeStatus>> => {
9
+ const op = await step.runQuery(
10
+ anyApi.processingCostReconciliation.queries.saved,
11
+ args,
12
+ );
13
+ for (let attempt = 0; attempt < op.maxAttempts; attempt++) {
14
+ const observed = await step.runAction(
15
+ anyApi.processingCostReconciliation.bridge.invoke,
16
+ args,
17
+ { name: `observe-${attempt}`, retry: false },
18
+ );
19
+ const state =
20
+ observed.status === "ready"
21
+ ? await step.runMutation(
22
+ anyApi.processingCostReconciliation.steps.apply,
23
+ { ...args, observation: observed.value },
24
+ { name: "apply" },
25
+ )
26
+ : await step.runMutation(
27
+ anyApi.processingCostReconciliation.steps.unavailable,
28
+ { ...args, outcome: observed },
29
+ );
30
+ if (!["not_ready", "unknown"].includes(state.status)) return state;
31
+ if (state.status !== "not_ready" && state.status !== "unknown")
32
+ return state;
33
+ const decision = financialRetryDecision(
34
+ {
35
+ status: state.status,
36
+ reason: state.reason,
37
+ retryable: state.retryable,
38
+ },
39
+ attempt,
40
+ {
41
+ maxRetries: op.maxAttempts - 1,
42
+ initialDelayMs: op.retryDelayMs,
43
+ maxDelayMs: op.retryDelayMs,
44
+ },
45
+ );
46
+ if (decision.status === "stop") return state;
47
+ await step.sleep(decision.delayMs);
48
+ }
49
+ throw new Error("Processing-cost observation budget exhausted.");
50
+ });
@@ -1,3 +1,4 @@
1
+ import { operationsTable as processingCostReconciliationOperations } from "./processingCostReconciliation/schema.js";
1
2
  import {
2
3
  operationsTable as recoveryWorkflowOperations,
3
4
  requestsTable as recoveryWorkflowRequests,
@@ -87,6 +88,7 @@ import { pricesTable, productsTable } from "./products/schema";
87
88
  import { webhookEventsTable } from "./webhooks/schema";
88
89
 
89
90
  export default defineSchema({
91
+ processingCostReconciliationOperations,
90
92
  recoveryWorkflowOperations,
91
93
  recoveryWorkflowRequests,
92
94
  balanceFundingPreparations,