@fantastic.dev/better-stripe 0.45.2 → 0.46.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 (87) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +1 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +46 -0
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +23 -0
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +46 -0
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +23 -0
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  11. package/dist/client/connect/refundSync.d.ts +32 -0
  12. package/dist/client/connect/refundSync.d.ts.map +1 -0
  13. package/dist/client/connect/refundSync.js +61 -0
  14. package/dist/client/connect/refundSync.js.map +1 -0
  15. package/dist/client/connect/refundSyncValidation.d.ts +16 -0
  16. package/dist/client/connect/refundSyncValidation.d.ts.map +1 -0
  17. package/dist/client/connect/refundSyncValidation.js +87 -0
  18. package/dist/client/connect/refundSyncValidation.js.map +1 -0
  19. package/dist/client/index.d.ts +30 -0
  20. package/dist/client/index.d.ts.map +1 -1
  21. package/dist/client/index.js +5 -0
  22. package/dist/client/index.js.map +1 -1
  23. package/dist/component/_generated/api.d.ts +12 -0
  24. package/dist/component/_generated/api.d.ts.map +1 -1
  25. package/dist/component/_generated/api.js.map +1 -1
  26. package/dist/component/_generated/component.d.ts +67 -0
  27. package/dist/component/_generated/component.d.ts.map +1 -1
  28. package/dist/component/connect/mutations.d.ts.map +1 -1
  29. package/dist/component/connect/mutations.js +2 -53
  30. package/dist/component/connect/mutations.js.map +1 -1
  31. package/dist/component/connect/refundWrites.d.ts +6 -0
  32. package/dist/component/connect/refundWrites.d.ts.map +1 -0
  33. package/dist/component/connect/refundWrites.js +56 -0
  34. package/dist/component/connect/refundWrites.js.map +1 -0
  35. package/dist/component/earnings/triggers.d.ts +46 -0
  36. package/dist/component/earnings/triggers.d.ts.map +1 -1
  37. package/dist/component/processingCostReconciliation/rollback.d.ts +1 -1
  38. package/dist/component/refundHistory/originalSeller.d.ts +1 -1
  39. package/dist/component/refundHistory/originalSeller.d.ts.map +1 -1
  40. package/dist/component/refundHistory/originalSeller.js.map +1 -1
  41. package/dist/component/refundSync/helpers.d.ts +43 -0
  42. package/dist/component/refundSync/helpers.d.ts.map +1 -0
  43. package/dist/component/refundSync/helpers.js +71 -0
  44. package/dist/component/refundSync/helpers.js.map +1 -0
  45. package/dist/component/refundSync/mutations.d.ts +56 -0
  46. package/dist/component/refundSync/mutations.d.ts.map +1 -0
  47. package/dist/component/refundSync/mutations.js +113 -0
  48. package/dist/component/refundSync/mutations.js.map +1 -0
  49. package/dist/component/refundSync/queries.d.ts +12 -0
  50. package/dist/component/refundSync/queries.d.ts.map +1 -0
  51. package/dist/component/refundSync/queries.js +10 -0
  52. package/dist/component/refundSync/queries.js.map +1 -0
  53. package/dist/component/refundSync/routing.d.ts +8 -0
  54. package/dist/component/refundSync/routing.d.ts.map +1 -0
  55. package/dist/component/refundSync/routing.js +42 -0
  56. package/dist/component/refundSync/routing.js.map +1 -0
  57. package/dist/component/refundSync/schema.d.ts +25 -0
  58. package/dist/component/refundSync/schema.d.ts.map +1 -0
  59. package/dist/component/refundSync/schema.js +15 -0
  60. package/dist/component/refundSync/schema.js.map +1 -0
  61. package/dist/component/refundSync/validators.d.ts +164 -0
  62. package/dist/component/refundSync/validators.d.ts.map +1 -0
  63. package/dist/component/refundSync/validators.js +32 -0
  64. package/dist/component/refundSync/validators.js.map +1 -0
  65. package/dist/component/schema.d.ts +23 -0
  66. package/dist/component/schema.js +2 -0
  67. package/dist/component/schema.js.map +1 -1
  68. package/docs/refund-context.md +54 -0
  69. package/package.json +1 -1
  70. package/src/client/connect/refundSync.test.ts +239 -0
  71. package/src/client/connect/refundSync.transport.test.ts +396 -0
  72. package/src/client/connect/refundSync.ts +125 -0
  73. package/src/client/connect/refundSyncValidation.ts +120 -0
  74. package/src/client/index.ts +19 -0
  75. package/src/component/_generated/api.ts +12 -0
  76. package/src/component/_generated/component.ts +100 -0
  77. package/src/component/connect/mutations.ts +2 -67
  78. package/src/component/connect/refundWrites.ts +76 -0
  79. package/src/component/refundHistory/originalSeller.ts +4 -1
  80. package/src/component/refundSync/helpers.ts +99 -0
  81. package/src/component/refundSync/mutations.ts +131 -0
  82. package/src/component/refundSync/queries.ts +10 -0
  83. package/src/component/refundSync/refund-sync.test.ts +255 -0
  84. package/src/component/refundSync/routing.ts +55 -0
  85. package/src/component/refundSync/schema.ts +19 -0
  86. package/src/component/refundSync/validators.ts +35 -0
  87. package/src/component/schema.ts +2 -0
@@ -0,0 +1,125 @@
1
+ import type Stripe from "stripe";
2
+ import type { Infer } from "convex/values";
3
+ import type { Component, RunCtx } from "../helpers.js";
4
+ import { runMutationOrThrow } from "../helpers.js";
5
+ import { componentRef } from "../webhooks/helpers.js";
6
+ import { validateIdentity } from "../../component/refundSync/helpers.js";
7
+ import type {
8
+ result,
9
+ routingResult,
10
+ } from "../../component/refundSync/validators.js";
11
+ import {
12
+ refundApiContext,
13
+ refundSnapshot,
14
+ refundChargeMerchant,
15
+ type RefundSyncScope,
16
+ } from "./refundSyncValidation.js";
17
+
18
+ export type RefundSyncOptions = {
19
+ stripeRefundId: string;
20
+ scope: RefundSyncScope;
21
+ };
22
+ export type RefundSyncResult = Infer<typeof result>;
23
+ export type PreparedRefundSync = Awaited<ReturnType<typeof prepareRefundSync>>;
24
+
25
+ async function markUnknown(
26
+ component: Component,
27
+ ctx: RunCtx,
28
+ observation: {
29
+ stripeRefundId: string;
30
+ apiContext: string;
31
+ generation: number;
32
+ },
33
+ ) {
34
+ await runMutationOrThrow(
35
+ ctx,
36
+ componentRef(component, "refundSync/mutations/markUnknown"),
37
+ observation,
38
+ );
39
+ }
40
+
41
+ /** Internal preparation for a future transactional host callback; no refund write yet. */
42
+ export async function prepareRefundSync(
43
+ stripe: Stripe,
44
+ component: Component,
45
+ ctx: RunCtx,
46
+ opts: RefundSyncOptions,
47
+ ) {
48
+ const identity = {
49
+ stripeRefundId: opts?.stripeRefundId,
50
+ apiContext: refundApiContext(opts?.scope),
51
+ };
52
+ validateIdentity(identity);
53
+ if (!ctx.runMutation || !ctx.runQuery)
54
+ throw new Error(
55
+ "Refund synchronization requires runMutation and runQuery.",
56
+ );
57
+ const generation = (await runMutationOrThrow(
58
+ ctx,
59
+ componentRef(component, "refundSync/mutations/begin"),
60
+ identity,
61
+ )) as number;
62
+ try {
63
+ const request =
64
+ identity.apiContext === "platform"
65
+ ? {}
66
+ : { stripeAccount: identity.apiContext };
67
+ const refund = refundSnapshot(
68
+ await stripe.refunds.retrieve(identity.stripeRefundId, {}, request),
69
+ identity.stripeRefundId,
70
+ );
71
+ const routing = (await ctx.runQuery(
72
+ componentRef(component, "refundSync/queries/routing"),
73
+ {
74
+ stripeRefundId: refund.stripeRefundId,
75
+ stripePaymentIntentId: refund.stripePaymentIntentId,
76
+ stripeChargeId: refund.stripeChargeId,
77
+ currency: refund.currency,
78
+ },
79
+ )) as Infer<typeof routingResult>;
80
+ if (routing.status === "held")
81
+ throw new Error(
82
+ "Original refund merchant proof is ambiguous or contradictory.",
83
+ );
84
+ const accountId =
85
+ routing.merchantAccount ??
86
+ (routing.requiresChargeProof
87
+ ? refundChargeMerchant(
88
+ await stripe.charges.retrieve(refund.stripeChargeId, {}, request),
89
+ refund,
90
+ )
91
+ : undefined);
92
+ return {
93
+ ...identity,
94
+ generation,
95
+ refund: { ...refund, ...(accountId === undefined ? {} : { accountId }) },
96
+ };
97
+ } catch (error) {
98
+ await markUnknown(component, ctx, { ...identity, generation });
99
+ throw error;
100
+ }
101
+ }
102
+
103
+ /** Host-authorized provider read plus generation-qualified, atomic existing refund synchronization. */
104
+ export async function syncRefundFromStripe(
105
+ stripe: Stripe,
106
+ component: Component,
107
+ ctx: RunCtx,
108
+ opts: RefundSyncOptions,
109
+ ): Promise<RefundSyncResult> {
110
+ const observation = await prepareRefundSync(stripe, component, ctx, opts);
111
+ try {
112
+ return (await runMutationOrThrow(
113
+ ctx,
114
+ componentRef(component, "refundSync/mutations/finish"),
115
+ observation,
116
+ )) as RefundSyncResult;
117
+ } catch (error) {
118
+ await markUnknown(component, ctx, {
119
+ stripeRefundId: observation.stripeRefundId,
120
+ apiContext: observation.apiContext,
121
+ generation: observation.generation,
122
+ });
123
+ throw error;
124
+ }
125
+ }
@@ -0,0 +1,120 @@
1
+ import type Stripe from "stripe";
2
+ import type { Infer } from "convex/values";
3
+ import type { snapshot } from "../../component/refundSync/validators.js";
4
+ import { validateSnapshot } from "../../component/refundSync/helpers.js";
5
+
6
+ export type RefundSyncScope =
7
+ { type: "platform" } | { type: "connected"; accountId: string };
8
+
9
+ /** The host authorizes this API namespace; metadata never selects it. */
10
+ export function refundApiContext(scope: RefundSyncScope) {
11
+ if (scope?.type === "platform" && Object.keys(scope).length === 1)
12
+ return "platform";
13
+ if (
14
+ scope?.type === "connected" &&
15
+ Object.keys(scope).length === 2 &&
16
+ typeof scope.accountId === "string" &&
17
+ /^acct_[A-Za-z0-9_]{1,250}$/.test(scope.accountId)
18
+ )
19
+ return scope.accountId;
20
+ throw new Error("Refund synchronization scope must be explicit.");
21
+ }
22
+
23
+ function originalId(
24
+ value: string | { id: string; object: string } | null,
25
+ kind: "charge" | "payment_intent",
26
+ ) {
27
+ if (typeof value === "string") return value;
28
+ if (value && value.object === kind && typeof value.id === "string")
29
+ return value.id;
30
+ throw new Error("Provider refund original payment identity is unavailable.");
31
+ }
32
+
33
+ function refundReason(
34
+ value: Stripe.Refund.Reason | null,
35
+ ): Infer<typeof snapshot>["reason"] {
36
+ switch (value) {
37
+ case null:
38
+ return undefined;
39
+ case "duplicate":
40
+ return "duplicate";
41
+ case "fraudulent":
42
+ return "fraudulent";
43
+ case "requested_by_customer":
44
+ return "requested_by_customer";
45
+ case "expired_uncaptured_charge":
46
+ return "expired_uncaptured_charge";
47
+ default:
48
+ throw new Error("Provider refund reason is invalid.");
49
+ }
50
+ }
51
+
52
+ /** A current provider observation can legitimately move back to requires_action. */
53
+ export function refundSnapshot(
54
+ r: Stripe.Refund,
55
+ stripeRefundId: string,
56
+ ): Infer<typeof snapshot> {
57
+ if (!r || r.object !== "refund" || r.id !== stripeRefundId)
58
+ throw new Error("Provider refund identity does not match.");
59
+ if (
60
+ !["pending", "requires_action", "succeeded", "failed", "canceled"].includes(
61
+ r.status ?? "",
62
+ )
63
+ )
64
+ throw new Error("Provider refund status is unavailable.");
65
+ const reason = refundReason(r.reason);
66
+ if (r.failure_reason != null && typeof r.failure_reason !== "string")
67
+ throw new Error("Provider refund failure detail is invalid.");
68
+ const metadata = r.metadata === null ? {} : r.metadata;
69
+ if (
70
+ !metadata ||
71
+ typeof metadata !== "object" ||
72
+ Array.isArray(metadata) ||
73
+ Object.values(metadata).some((value) => typeof value !== "string")
74
+ )
75
+ throw new Error("Provider refund metadata is invalid.");
76
+ const row: Infer<typeof snapshot> = {
77
+ stripeRefundId: r.id,
78
+ stripePaymentIntentId: originalId(r.payment_intent, "payment_intent"),
79
+ stripeChargeId: originalId(r.charge, "charge"),
80
+ amount: r.amount,
81
+ currency: r.currency,
82
+ status: r.status as Infer<typeof snapshot>["status"],
83
+ ...(reason === undefined ? {} : { reason }),
84
+ ...(r.failure_reason == null ? {} : { failureReason: r.failure_reason }),
85
+ metadata,
86
+ };
87
+ validateSnapshot(row);
88
+ return row;
89
+ }
90
+
91
+ /** The charge's original destination is independent of the caller's API namespace. */
92
+ export function refundChargeMerchant(
93
+ charge: Stripe.Charge,
94
+ row: Infer<typeof snapshot>,
95
+ ) {
96
+ if (
97
+ !charge ||
98
+ charge.object !== "charge" ||
99
+ charge.id !== row.stripeChargeId ||
100
+ originalId(charge.payment_intent, "payment_intent") !==
101
+ row.stripePaymentIntentId ||
102
+ charge.currency !== row.currency ||
103
+ !Number.isSafeInteger(charge.amount) ||
104
+ charge.amount < row.amount
105
+ )
106
+ throw new Error("Original refund charge proof does not match.");
107
+ const destination = charge.transfer_data?.destination;
108
+ const account =
109
+ typeof destination === "string"
110
+ ? destination
111
+ : destination?.object === "account"
112
+ ? destination.id
113
+ : undefined;
114
+ if (
115
+ typeof account !== "string" ||
116
+ !/^acct_[A-Za-z0-9_]{1,250}$/.test(account)
117
+ )
118
+ throw new Error("Original refund merchant cannot be qualified.");
119
+ return account;
120
+ }
@@ -1,3 +1,9 @@
1
+ import * as refundSyncImpl from "./connect/refundSync.js";
2
+ export type {
3
+ RefundSyncOptions,
4
+ RefundSyncResult,
5
+ } from "./connect/refundSync.js";
6
+ export type { RefundSyncScope } from "./connect/refundSyncValidation.js";
1
7
  import * as personalAccountMappingImpl from "./core/personalAccountMapping.js";
2
8
  export type * from "./publicTypes.js";
3
9
  export * from "./financialOutcomes/index.js";
@@ -1190,6 +1196,19 @@ export class BetterStripe extends PaymentSourceClient {
1190
1196
  );
1191
1197
  }
1192
1198
 
1199
+ /** Host must authorize the explicit API scope; this never creates a refund. */
1200
+ async syncRefundFromStripe(
1201
+ ctx: RunCtx,
1202
+ opts: refundSyncImpl.RefundSyncOptions,
1203
+ ) {
1204
+ return refundSyncImpl.syncRefundFromStripe(
1205
+ this.stripe(),
1206
+ this.component,
1207
+ ctx,
1208
+ opts,
1209
+ );
1210
+ }
1211
+
1193
1212
  // REFUND METHODS
1194
1213
 
1195
1214
  /**
@@ -41,6 +41,7 @@ import type * as billing_validators from "../billing/validators.js";
41
41
  import type * as connect_mutations from "../connect/mutations.js";
42
42
  import type * as connect_payoutWrites from "../connect/payoutWrites.js";
43
43
  import type * as connect_queries from "../connect/queries.js";
44
+ import type * as connect_refundWrites from "../connect/refundWrites.js";
44
45
  import type * as connect_reversalClaims from "../connect/reversalClaims.js";
45
46
  import type * as connect_reversalDiagnostics from "../connect/reversalDiagnostics.js";
46
47
  import type * as connect_reversalReceipts from "../connect/reversalReceipts.js";
@@ -150,6 +151,11 @@ import type * as refundHistory_commandFields from "../refundHistory/commandField
150
151
  import type * as refundHistory_mutations from "../refundHistory/mutations.js";
151
152
  import type * as refundHistory_originalSeller from "../refundHistory/originalSeller.js";
152
153
  import type * as refundHistory_queries from "../refundHistory/queries.js";
154
+ import type * as refundSync_helpers from "../refundSync/helpers.js";
155
+ import type * as refundSync_mutations from "../refundSync/mutations.js";
156
+ import type * as refundSync_queries from "../refundSync/queries.js";
157
+ import type * as refundSync_routing from "../refundSync/routing.js";
158
+ import type * as refundSync_validators from "../refundSync/validators.js";
153
159
  import type * as settlement_clawbackSchema from "../settlement/clawbackSchema.js";
154
160
  import type * as settlement_clawbacks from "../settlement/clawbacks.js";
155
161
  import type * as settlement_mutations from "../settlement/mutations.js";
@@ -199,6 +205,7 @@ const fullApi: ApiFromModules<{
199
205
  "connect/mutations": typeof connect_mutations;
200
206
  "connect/payoutWrites": typeof connect_payoutWrites;
201
207
  "connect/queries": typeof connect_queries;
208
+ "connect/refundWrites": typeof connect_refundWrites;
202
209
  "connect/reversalClaims": typeof connect_reversalClaims;
203
210
  "connect/reversalDiagnostics": typeof connect_reversalDiagnostics;
204
211
  "connect/reversalReceipts": typeof connect_reversalReceipts;
@@ -308,6 +315,11 @@ const fullApi: ApiFromModules<{
308
315
  "refundHistory/mutations": typeof refundHistory_mutations;
309
316
  "refundHistory/originalSeller": typeof refundHistory_originalSeller;
310
317
  "refundHistory/queries": typeof refundHistory_queries;
318
+ "refundSync/helpers": typeof refundSync_helpers;
319
+ "refundSync/mutations": typeof refundSync_mutations;
320
+ "refundSync/queries": typeof refundSync_queries;
321
+ "refundSync/routing": typeof refundSync_routing;
322
+ "refundSync/validators": typeof refundSync_validators;
311
323
  "settlement/clawbackSchema": typeof settlement_clawbackSchema;
312
324
  "settlement/clawbacks": typeof settlement_clawbacks;
313
325
  "settlement/mutations": typeof settlement_mutations;
@@ -7857,6 +7857,106 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
7857
7857
  >;
7858
7858
  };
7859
7859
  };
7860
+ refundSync: {
7861
+ mutations: {
7862
+ begin: FunctionReference<
7863
+ "mutation",
7864
+ "internal",
7865
+ { apiContext: string; stripeRefundId: string },
7866
+ number,
7867
+ Name
7868
+ >;
7869
+ finish: FunctionReference<
7870
+ "mutation",
7871
+ "internal",
7872
+ {
7873
+ apiContext: string;
7874
+ generation: number;
7875
+ refund: {
7876
+ accountId?: string;
7877
+ amount: number;
7878
+ currency: string;
7879
+ failureReason?: string;
7880
+ metadata?: Record<string, string>;
7881
+ reason?:
7882
+ | "duplicate"
7883
+ | "fraudulent"
7884
+ | "requested_by_customer"
7885
+ | "expired_uncaptured_charge";
7886
+ status:
7887
+ | "pending"
7888
+ | "requires_action"
7889
+ | "succeeded"
7890
+ | "failed"
7891
+ | "canceled";
7892
+ stripeChargeId: string;
7893
+ stripePaymentIntentId: string;
7894
+ stripeRefundId: string;
7895
+ };
7896
+ stripeRefundId: string;
7897
+ },
7898
+ | {
7899
+ changed: boolean;
7900
+ generation: number;
7901
+ refund: {
7902
+ _creationTime: number;
7903
+ _id: string;
7904
+ accountId?: string;
7905
+ amount: number;
7906
+ currency: string;
7907
+ failureReason?: string;
7908
+ metadata?: any;
7909
+ reason?:
7910
+ | "duplicate"
7911
+ | "fraudulent"
7912
+ | "requested_by_customer"
7913
+ | "expired_uncaptured_charge";
7914
+ refundCommandConflict?: boolean;
7915
+ refundCommandKey?: string;
7916
+ refundCommandNormalizationVersion?: 1;
7917
+ refundCommandObservedAt?: number;
7918
+ status:
7919
+ | "pending"
7920
+ | "requires_action"
7921
+ | "succeeded"
7922
+ | "failed"
7923
+ | "canceled";
7924
+ stripeChargeId?: string;
7925
+ stripePaymentIntentId?: string;
7926
+ stripeRefundId: string;
7927
+ };
7928
+ status: "accepted";
7929
+ }
7930
+ | { generation: number; status: "superseded" },
7931
+ Name
7932
+ >;
7933
+ markUnknown: FunctionReference<
7934
+ "mutation",
7935
+ "internal",
7936
+ { apiContext: string; generation: number; stripeRefundId: string },
7937
+ null,
7938
+ Name
7939
+ >;
7940
+ };
7941
+ queries: {
7942
+ routing: FunctionReference<
7943
+ "query",
7944
+ "internal",
7945
+ {
7946
+ currency: string;
7947
+ stripeChargeId: string;
7948
+ stripePaymentIntentId: string;
7949
+ stripeRefundId: string;
7950
+ },
7951
+ {
7952
+ merchantAccount: string | null;
7953
+ requiresChargeProof: boolean;
7954
+ status: "known" | "unknown" | "held";
7955
+ },
7956
+ Name
7957
+ >;
7958
+ };
7959
+ };
7860
7960
  settlement: {
7861
7961
  mutations: {
7862
7962
  claimCommissionInvoice: FunctionReference<
@@ -1,4 +1,4 @@
1
- import { refundCommandBinding } from "../refundHistory/commandBinding.js";
1
+ import { writeRefund } from "./refundWrites.js";
2
2
  import {
3
3
  deferTransferFacts,
4
4
  synchronousTransferFactLimit,
@@ -137,72 +137,7 @@ export const upsertPayout = mutation({
137
137
  export const upsertRefund = mutation({
138
138
  args: refundFields,
139
139
  returns: v.null(),
140
- handler: async (ctx, args) => {
141
- const existing = await ctx.db
142
- .query("refunds")
143
- .withIndex("by_stripe_refund_id", (q) =>
144
- q.eq("stripeRefundId", args.stripeRefundId),
145
- )
146
- .first();
147
-
148
- const accountId =
149
- args.accountId ?? (await paymentSeller(ctx, args.stripePaymentIntentId));
150
- const record = {
151
- ...args,
152
- ...(accountId ? { accountId } : {}),
153
- ...refundCommandBinding(existing, args, Date.now()),
154
- };
155
- if (existing) {
156
- await ctx.db.patch("refunds", existing._id, record);
157
- } else {
158
- await ctx.db.insert("refunds", record);
159
- }
160
-
161
- // Denormalize cumulative refund state onto the linked `payments` row so
162
- // consumers can answer "is this payment whole?" in one read. Runs in the
163
- // same transaction as the refund upsert.
164
- const paymentIntentId = args.stripePaymentIntentId;
165
- if (paymentIntentId) {
166
- const payment = await ctx.db
167
- .query("payments")
168
- .withIndex("by_stripe_payment_intent_id", (q) =>
169
- q.eq("stripePaymentIntentId", paymentIntentId),
170
- )
171
- .first();
172
-
173
- if (payment) {
174
- // Bounded cardinality: a single payment intent can only be refunded
175
- // down to zero, so the number of refund rows per PI is inherently small.
176
- // eslint-disable-next-line @convex-dev/no-collect-in-query
177
- const refunds = await ctx.db
178
- .query("refunds")
179
- .withIndex("by_stripe_payment_intent_id", (q) =>
180
- q.eq("stripePaymentIntentId", paymentIntentId),
181
- )
182
- .collect();
183
-
184
- // Money is considered returned for any refund that isn't failed or
185
- // canceled (matches Stripe's Charge.amount_refunded semantics).
186
- const refundedAmount = refunds
187
- .filter((r) => r.status !== "failed" && r.status !== "canceled")
188
- .reduce((sum, r) => sum + r.amount, 0);
189
-
190
- const refundStatus =
191
- refundedAmount <= 0
192
- ? undefined
193
- : refundedAmount >= payment.amount
194
- ? ("fully_refunded" as const)
195
- : ("partially_refunded" as const);
196
-
197
- await ctx.db.patch("payments", payment._id, {
198
- refundedAmount,
199
- refundStatus,
200
- });
201
- }
202
- }
203
-
204
- return null;
205
- },
140
+ handler: writeRefund,
206
141
  });
207
142
 
208
143
  /**
@@ -0,0 +1,76 @@
1
+ import type { ObjectType } from "convex/values";
2
+ import type { MutationCtx } from "../_generated/server.js";
3
+ import { refundCommandBinding } from "../refundHistory/commandBinding.js";
4
+ import { paymentSeller } from "../lib/paymentSeller.js";
5
+ import { refundFields } from "./validators.js";
6
+
7
+ /** Existing refund write and denormalization, shared in the caller's transaction. */
8
+ export async function writeRefund(
9
+ ctx: MutationCtx,
10
+ args: ObjectType<typeof refundFields>,
11
+ ) {
12
+ const existing = await ctx.db
13
+ .query("refunds")
14
+ .withIndex("by_stripe_refund_id", (q) =>
15
+ q.eq("stripeRefundId", args.stripeRefundId),
16
+ )
17
+ .first();
18
+
19
+ const accountId =
20
+ args.accountId ?? (await paymentSeller(ctx, args.stripePaymentIntentId));
21
+ const record = {
22
+ ...args,
23
+ ...(accountId ? { accountId } : {}),
24
+ ...refundCommandBinding(existing, args, Date.now()),
25
+ };
26
+ if (existing) {
27
+ await ctx.db.patch("refunds", existing._id, record);
28
+ } else {
29
+ await ctx.db.insert("refunds", record);
30
+ }
31
+
32
+ // Denormalize cumulative refund state onto the linked `payments` row so
33
+ // consumers can answer "is this payment whole?" in one read. Runs in the
34
+ // same transaction as the refund upsert.
35
+ const paymentIntentId = args.stripePaymentIntentId;
36
+ if (paymentIntentId) {
37
+ const payment = await ctx.db
38
+ .query("payments")
39
+ .withIndex("by_stripe_payment_intent_id", (q) =>
40
+ q.eq("stripePaymentIntentId", paymentIntentId),
41
+ )
42
+ .first();
43
+
44
+ if (payment) {
45
+ // Preserve the complete legacy cumulative calculation. Failed/canceled
46
+ // history is not cardinality-bounded; native resource errors abort atomically.
47
+ // eslint-disable-next-line @convex-dev/no-collect-in-query
48
+ const refunds = await ctx.db
49
+ .query("refunds")
50
+ .withIndex("by_stripe_payment_intent_id", (q) =>
51
+ q.eq("stripePaymentIntentId", paymentIntentId),
52
+ )
53
+ .collect();
54
+
55
+ // Money is considered returned for any refund that isn't failed or
56
+ // canceled (matches Stripe's Charge.amount_refunded semantics).
57
+ const refundedAmount = refunds
58
+ .filter((r) => r.status !== "failed" && r.status !== "canceled")
59
+ .reduce((sum, r) => sum + r.amount, 0);
60
+
61
+ const refundStatus =
62
+ refundedAmount <= 0
63
+ ? undefined
64
+ : refundedAmount >= payment.amount
65
+ ? ("fully_refunded" as const)
66
+ : ("partially_refunded" as const);
67
+
68
+ await ctx.db.patch("payments", payment._id, {
69
+ refundedAmount,
70
+ refundStatus,
71
+ });
72
+ }
73
+ }
74
+
75
+ return null;
76
+ }
@@ -28,7 +28,10 @@ function seller(allocation: Doc<"settlementAllocations">): string | undefined {
28
28
  /** At most two exact-charge allocations; mutable payments never establish original ownership. */
29
29
  export async function originalRefundSeller(
30
30
  ctx: QueryCtx,
31
- scope: RefundCommandScope,
31
+ scope: Pick<
32
+ RefundCommandScope,
33
+ "stripeChargeId" | "stripePaymentIntentId" | "currency"
34
+ >,
32
35
  ): Promise<string | undefined> {
33
36
  const allocations = await ctx.db
34
37
  .query("settlementAllocations")
@@ -0,0 +1,99 @@
1
+ import type { Infer } from "convex/values";
2
+ import type { MutationCtx, QueryCtx } from "../_generated/server.js";
3
+ import type { Doc } from "../_generated/dataModel.js";
4
+ import { generateIdempotencyKey } from "../lib/idempotency.js";
5
+ import type { snapshot } from "./validators.js";
6
+
7
+ export function validateIdentity(input: {
8
+ stripeRefundId: string;
9
+ apiContext: string;
10
+ }) {
11
+ if (
12
+ typeof input.stripeRefundId !== "string" ||
13
+ typeof input.apiContext !== "string" ||
14
+ !/^re_[A-Za-z0-9_]{1,252}$/.test(input.stripeRefundId) ||
15
+ (input.apiContext !== "platform" &&
16
+ !/^acct_[A-Za-z0-9_]{1,250}$/.test(input.apiContext))
17
+ )
18
+ throw new Error("Invalid refund synchronization identity or API scope.");
19
+ }
20
+ export async function claimByRefund(
21
+ ctx: QueryCtx | MutationCtx,
22
+ stripeRefundId: string,
23
+ ) {
24
+ const rows = await ctx.db
25
+ .query("refundSyncClaims")
26
+ .withIndex("by_stripe_refund_id", (q) =>
27
+ q.eq("stripeRefundId", stripeRefundId),
28
+ )
29
+ .take(2);
30
+ if (rows.length > 1) throw new Error("Refund synchronization is ambiguous.");
31
+ return rows[0] ?? null;
32
+ }
33
+ export async function refundById(
34
+ ctx: QueryCtx | MutationCtx,
35
+ stripeRefundId: string,
36
+ ) {
37
+ const rows = await ctx.db
38
+ .query("refunds")
39
+ .withIndex("by_stripe_refund_id", (q) =>
40
+ q.eq("stripeRefundId", stripeRefundId),
41
+ )
42
+ .take(2);
43
+ if (rows.length > 1) throw new Error("Refund identity is ambiguous.");
44
+ return rows[0] ?? null;
45
+ }
46
+ export function validateSnapshot(row: Infer<typeof snapshot>) {
47
+ if (
48
+ typeof row.stripeRefundId !== "string" ||
49
+ typeof row.stripePaymentIntentId !== "string" ||
50
+ typeof row.stripeChargeId !== "string" ||
51
+ typeof row.currency !== "string" ||
52
+ !/^re_[A-Za-z0-9_]{1,252}$/.test(row.stripeRefundId) ||
53
+ !/^pi_[A-Za-z0-9_]{1,252}$/.test(row.stripePaymentIntentId) ||
54
+ !/^ch_[A-Za-z0-9_]{1,252}$/.test(row.stripeChargeId) ||
55
+ !Number.isSafeInteger(row.amount) ||
56
+ row.amount < 0 ||
57
+ !/^[a-z]{3}$/.test(row.currency) ||
58
+ (row.accountId !== undefined &&
59
+ !/^acct_[A-Za-z0-9_]{1,250}$/.test(row.accountId))
60
+ )
61
+ throw new Error("Invalid original refund snapshot.");
62
+ }
63
+ export function assertOriginal(
64
+ existing: Doc<"refunds"> | null,
65
+ row: Infer<typeof snapshot>,
66
+ ) {
67
+ if (
68
+ existing &&
69
+ (existing.amount !== row.amount ||
70
+ existing.currency !== row.currency ||
71
+ (existing.stripePaymentIntentId !== undefined &&
72
+ existing.stripePaymentIntentId !== row.stripePaymentIntentId) ||
73
+ (existing.stripeChargeId !== undefined &&
74
+ existing.stripeChargeId !== row.stripeChargeId) ||
75
+ (existing.accountId !== undefined &&
76
+ existing.accountId !== row.accountId))
77
+ )
78
+ throw new Error(
79
+ "Original refund identity, money or merchant does not match.",
80
+ );
81
+ }
82
+ export function fingerprint(row: Infer<typeof snapshot> | Doc<"refunds">) {
83
+ return generateIdempotencyKey("refund-sync", {
84
+ snapshot: [
85
+ row.stripeRefundId,
86
+ row.stripePaymentIntentId,
87
+ row.stripeChargeId,
88
+ row.accountId,
89
+ row.amount,
90
+ row.currency,
91
+ row.status,
92
+ row.reason,
93
+ row.failureReason,
94
+ Object.entries(row.metadata ?? {}).sort(([a], [b]) =>
95
+ a < b ? -1 : a > b ? 1 : 0,
96
+ ),
97
+ ],
98
+ });
99
+ }