@fantastic.dev/better-stripe 0.45.2 → 0.47.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 (107) hide show
  1. package/CHANGELOG.md +36 -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 +39 -16
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +78 -32
  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 +54 -1
  20. package/dist/client/index.d.ts.map +1 -1
  21. package/dist/client/index.js +10 -3
  22. package/dist/client/index.js.map +1 -1
  23. package/dist/client/types/triggers.d.ts +3 -2
  24. package/dist/client/types/triggers.d.ts.map +1 -1
  25. package/dist/client/webhooks/helpers.d.ts.map +1 -1
  26. package/dist/client/webhooks/helpers.js +1 -0
  27. package/dist/client/webhooks/helpers.js.map +1 -1
  28. package/dist/client/webhooks/refundReconciliation.d.ts +10 -0
  29. package/dist/client/webhooks/refundReconciliation.d.ts.map +1 -0
  30. package/dist/client/webhooks/refundReconciliation.js +41 -0
  31. package/dist/client/webhooks/refundReconciliation.js.map +1 -0
  32. package/dist/client/webhooks/refundReconciliationValidators.d.ts +68 -0
  33. package/dist/client/webhooks/refundReconciliationValidators.d.ts.map +1 -0
  34. package/dist/client/webhooks/refundReconciliationValidators.js +11 -0
  35. package/dist/client/webhooks/refundReconciliationValidators.js.map +1 -0
  36. package/dist/component/_generated/api.d.ts +12 -0
  37. package/dist/component/_generated/api.d.ts.map +1 -1
  38. package/dist/component/_generated/api.js.map +1 -1
  39. package/dist/component/_generated/component.d.ts +67 -0
  40. package/dist/component/_generated/component.d.ts.map +1 -1
  41. package/dist/component/balanceFunding/mutations.d.ts +27 -27
  42. package/dist/component/balanceFunding/workflowValidators.d.ts +16 -16
  43. package/dist/component/connect/mutations.d.ts.map +1 -1
  44. package/dist/component/connect/mutations.js +2 -53
  45. package/dist/component/connect/mutations.js.map +1 -1
  46. package/dist/component/connect/refundWrites.d.ts +6 -0
  47. package/dist/component/connect/refundWrites.d.ts.map +1 -0
  48. package/dist/component/connect/refundWrites.js +56 -0
  49. package/dist/component/connect/refundWrites.js.map +1 -0
  50. package/dist/component/earnings/triggers.d.ts +46 -0
  51. package/dist/component/earnings/triggers.d.ts.map +1 -1
  52. package/dist/component/processingCostReconciliation/rollback.d.ts +1 -1
  53. package/dist/component/refundHistory/originalSeller.d.ts +1 -1
  54. package/dist/component/refundHistory/originalSeller.d.ts.map +1 -1
  55. package/dist/component/refundHistory/originalSeller.js.map +1 -1
  56. package/dist/component/refundSync/helpers.d.ts +43 -0
  57. package/dist/component/refundSync/helpers.d.ts.map +1 -0
  58. package/dist/component/refundSync/helpers.js +71 -0
  59. package/dist/component/refundSync/helpers.js.map +1 -0
  60. package/dist/component/refundSync/mutations.d.ts +56 -0
  61. package/dist/component/refundSync/mutations.d.ts.map +1 -0
  62. package/dist/component/refundSync/mutations.js +113 -0
  63. package/dist/component/refundSync/mutations.js.map +1 -0
  64. package/dist/component/refundSync/queries.d.ts +12 -0
  65. package/dist/component/refundSync/queries.d.ts.map +1 -0
  66. package/dist/component/refundSync/queries.js +10 -0
  67. package/dist/component/refundSync/queries.js.map +1 -0
  68. package/dist/component/refundSync/routing.d.ts +8 -0
  69. package/dist/component/refundSync/routing.d.ts.map +1 -0
  70. package/dist/component/refundSync/routing.js +42 -0
  71. package/dist/component/refundSync/routing.js.map +1 -0
  72. package/dist/component/refundSync/schema.d.ts +25 -0
  73. package/dist/component/refundSync/schema.d.ts.map +1 -0
  74. package/dist/component/refundSync/schema.js +15 -0
  75. package/dist/component/refundSync/schema.js.map +1 -0
  76. package/dist/component/refundSync/validators.d.ts +164 -0
  77. package/dist/component/refundSync/validators.d.ts.map +1 -0
  78. package/dist/component/refundSync/validators.js +32 -0
  79. package/dist/component/refundSync/validators.js.map +1 -0
  80. package/dist/component/schema.d.ts +23 -0
  81. package/dist/component/schema.js +2 -0
  82. package/dist/component/schema.js.map +1 -1
  83. package/docs/refund-context.md +82 -0
  84. package/package.json +1 -1
  85. package/src/client/connect/refundSync.test.ts +239 -0
  86. package/src/client/connect/refundSync.transport.test.ts +396 -0
  87. package/src/client/connect/refundSync.ts +125 -0
  88. package/src/client/connect/refundSyncValidation.ts +120 -0
  89. package/src/client/index.ts +34 -6
  90. package/src/client/types/triggers.ts +3 -1
  91. package/src/client/webhooks/helpers.ts +1 -0
  92. package/src/client/webhooks/refund-reconciliation.test.ts +320 -0
  93. package/src/client/webhooks/refundReconciliation.ts +80 -0
  94. package/src/client/webhooks/refundReconciliationValidators.ts +15 -0
  95. package/src/component/_generated/api.ts +12 -0
  96. package/src/component/_generated/component.ts +100 -0
  97. package/src/component/connect/mutations.ts +2 -67
  98. package/src/component/connect/refundWrites.ts +76 -0
  99. package/src/component/refundHistory/originalSeller.ts +4 -1
  100. package/src/component/refundSync/helpers.ts +99 -0
  101. package/src/component/refundSync/mutations.ts +131 -0
  102. package/src/component/refundSync/queries.ts +10 -0
  103. package/src/component/refundSync/refund-sync.test.ts +255 -0
  104. package/src/component/refundSync/routing.ts +55 -0
  105. package/src/component/refundSync/schema.ts +19 -0
  106. package/src/component/refundSync/validators.ts +35 -0
  107. package/src/component/schema.ts +2 -0
@@ -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
+ }
@@ -0,0 +1,131 @@
1
+ import { v } from "convex/values";
2
+ import { mutation } from "../earnings/triggers.js";
3
+ import { writeRefund } from "../connect/refundWrites.js";
4
+ import {
5
+ claimByRefund,
6
+ refundById,
7
+ validateIdentity,
8
+ validateSnapshot,
9
+ assertOriginal,
10
+ fingerprint,
11
+ } from "./helpers.js";
12
+ import { refundRouting } from "./routing.js";
13
+ import { identity, prepared, result } from "./validators.js";
14
+
15
+ /** Failed first reads cannot permanently claim an unverified provider API namespace. */
16
+ export const begin = mutation({
17
+ args: identity,
18
+ returns: v.number(),
19
+ handler: async (ctx, args) => {
20
+ validateIdentity(args);
21
+ const claim = await claimByRefund(ctx, args.stripeRefundId);
22
+ await refundById(ctx, args.stripeRefundId);
23
+ if (
24
+ claim?.acceptedContext !== undefined &&
25
+ claim.acceptedContext !== args.apiContext
26
+ )
27
+ throw new Error("Accepted refund API context does not match.");
28
+ const generation = (claim?.generation ?? 0) + 1;
29
+ if (!Number.isSafeInteger(generation) || generation <= 0)
30
+ throw new Error("Refund synchronization generation exhausted.");
31
+ const fields = {
32
+ generation,
33
+ requestedContext: args.apiContext,
34
+ status: "pending" as const,
35
+ startedAt: Date.now(),
36
+ };
37
+ if (claim) await ctx.db.patch("refundSyncClaims", claim._id, fields);
38
+ else
39
+ await ctx.db.insert("refundSyncClaims", {
40
+ stripeRefundId: args.stripeRefundId,
41
+ ...fields,
42
+ });
43
+ return generation;
44
+ },
45
+ });
46
+
47
+ /** Accept the qualified observation and unchanged financial writer atomically. */
48
+ export const finish = mutation({
49
+ args: prepared,
50
+ returns: result,
51
+ handler: async (ctx, args) => {
52
+ validateIdentity(args);
53
+ if (!Number.isSafeInteger(args.generation) || args.generation <= 0)
54
+ throw new Error("Invalid refund synchronization generation.");
55
+ const claim = await claimByRefund(ctx, args.stripeRefundId);
56
+ if (!claim) throw new Error("Refund synchronization claim is missing.");
57
+ if (claim.generation !== args.generation)
58
+ return { status: "superseded" as const, generation: args.generation };
59
+ if (
60
+ claim.requestedContext !== args.apiContext ||
61
+ (claim.acceptedContext !== undefined &&
62
+ claim.acceptedContext !== args.apiContext)
63
+ )
64
+ throw new Error("Refund synchronization API context does not match.");
65
+ validateSnapshot(args.refund);
66
+ if (args.refund.stripeRefundId !== args.stripeRefundId)
67
+ throw new Error("Refund synchronization identity does not match.");
68
+ const routing = await refundRouting(ctx, args.refund);
69
+ if (
70
+ routing.status === "held" ||
71
+ (routing.merchantAccount !== null &&
72
+ routing.merchantAccount !== args.refund.accountId) ||
73
+ (routing.requiresChargeProof && args.refund.accountId === undefined)
74
+ )
75
+ throw new Error(
76
+ "Original refund merchant is unavailable or contradictory.",
77
+ );
78
+ const existing = await refundById(ctx, args.stripeRefundId);
79
+ assertOriginal(existing, args.refund);
80
+ const nextFingerprint = await fingerprint(args.refund);
81
+ const changed =
82
+ !existing || (await fingerprint(existing)) !== nextFingerprint;
83
+ if (claim.status === "accepted") {
84
+ if (claim.acceptedFingerprint !== nextFingerprint || changed || !existing)
85
+ throw new Error(
86
+ "Accepted refund observation changed outside its generation.",
87
+ );
88
+ return {
89
+ status: "accepted" as const,
90
+ generation: args.generation,
91
+ changed: false,
92
+ refund: existing,
93
+ };
94
+ }
95
+ await writeRefund(ctx, {
96
+ ...args.refund,
97
+ reason: args.refund.reason,
98
+ failureReason: args.refund.failureReason,
99
+ });
100
+ const refund = await refundById(ctx, args.stripeRefundId);
101
+ if (!refund) throw new Error("Accepted refund was not persisted.");
102
+ await ctx.db.patch("refundSyncClaims", claim._id, {
103
+ status: "accepted",
104
+ acceptedContext: args.apiContext,
105
+ acceptedGeneration: args.generation,
106
+ acceptedAt: Date.now(),
107
+ acceptedFingerprint: nextFingerprint,
108
+ });
109
+ return {
110
+ status: "accepted" as const,
111
+ generation: args.generation,
112
+ changed,
113
+ refund,
114
+ };
115
+ },
116
+ });
117
+ export const markUnknown = mutation({
118
+ args: { ...identity, generation: v.number() },
119
+ returns: v.null(),
120
+ handler: async (ctx, args) => {
121
+ validateIdentity(args);
122
+ const claim = await claimByRefund(ctx, args.stripeRefundId);
123
+ if (
124
+ claim?.generation === args.generation &&
125
+ claim.requestedContext === args.apiContext &&
126
+ claim.status === "pending"
127
+ )
128
+ await ctx.db.patch("refundSyncClaims", claim._id, { status: "unknown" });
129
+ return null;
130
+ },
131
+ });
@@ -0,0 +1,10 @@
1
+ import { query } from "../_generated/server.js";
2
+ import { routingInput, routingResult } from "./validators.js";
3
+ import { refundRouting } from "./routing.js";
4
+
5
+ /** Trusted-host routing proof only; this does not establish seller dispatch authority. */
6
+ export const routing = query({
7
+ args: routingInput,
8
+ returns: routingResult,
9
+ handler: refundRouting,
10
+ });
@@ -0,0 +1,255 @@
1
+ // @vitest-environment edge-runtime
2
+ import { convexTest } from "convex-test";
3
+ import { makeFunctionReference } from "convex/server";
4
+ import { expect, it, vi } from "vitest";
5
+ import { schema, modules } from "../../test.js";
6
+ import { api } from "../_generated/api.js";
7
+
8
+ const identity = { stripeRefundId: "re_original", apiContext: "platform" };
9
+ const refund = {
10
+ stripeRefundId: "re_original",
11
+ stripePaymentIntentId: "pi_original",
12
+ stripeChargeId: "ch_original",
13
+ amount: 250,
14
+ currency: "usd",
15
+ status: "succeeded" as const,
16
+ metadata: { betterStripeRefundCommand: "original-command" },
17
+ };
18
+ const operation = (name: string) =>
19
+ makeFunctionReference<"mutation">(`refundSync/mutations:${name}`);
20
+ async function fixture() {
21
+ const t = convexTest(schema, modules);
22
+ const generation = await t.mutation(operation("begin"), identity);
23
+ return { t, args: { ...identity, generation, refund } };
24
+ }
25
+
26
+ it("replays the same committed generation without changing observed time or its row", async () => {
27
+ vi.useFakeTimers();
28
+ try {
29
+ vi.setSystemTime(1000);
30
+ const { t, args } = await fixture();
31
+ await t.mutation(operation("finish"), args);
32
+ const first = await t.run((ctx) => ctx.db.query("refunds").unique());
33
+ vi.setSystemTime(2000);
34
+ expect(await t.mutation(operation("finish"), args)).toMatchObject({
35
+ status: "accepted",
36
+ changed: false,
37
+ });
38
+ expect(await t.run((ctx) => ctx.db.query("refunds").unique())).toEqual(
39
+ first,
40
+ );
41
+ expect(
42
+ await t.run((ctx) => ctx.db.query("refundSyncClaims").unique()),
43
+ ).toMatchObject({ acceptedAt: 1000, status: "accepted" });
44
+ await expect(
45
+ t.mutation(operation("finish"), {
46
+ ...args,
47
+ refund: { ...refund, status: "pending" },
48
+ }),
49
+ ).rejects.toThrow("Accepted refund observation changed");
50
+ } finally {
51
+ vi.useRealTimers();
52
+ }
53
+ });
54
+
55
+ it("rejects original money and payment identity changes atomically", async () => {
56
+ const { t, args } = await fixture();
57
+ await t.mutation(operation("finish"), args);
58
+ const before = await t.run((ctx) => ctx.db.query("refunds").unique());
59
+ for (const patch of [
60
+ { amount: 251 },
61
+ { currency: "jpy" },
62
+ { stripePaymentIntentId: "pi_foreign" },
63
+ { stripeChargeId: "ch_foreign" },
64
+ ]) {
65
+ const generation = await t.mutation(operation("begin"), identity);
66
+ await expect(
67
+ t.mutation(operation("finish"), {
68
+ ...args,
69
+ generation,
70
+ refund: { ...refund, ...patch },
71
+ }),
72
+ ).rejects.toThrow("Original refund identity");
73
+ expect(await t.run((ctx) => ctx.db.query("refunds").unique())).toEqual(
74
+ before,
75
+ );
76
+ }
77
+ });
78
+
79
+ it("preserves first command normalization and permanently latches changed or removed keys", async () => {
80
+ const { t, args } = await fixture();
81
+ await t.run((ctx) =>
82
+ ctx.db.insert("refunds", {
83
+ ...refund,
84
+ metadata: { betterStripeRefundCommand: "first-original-key" },
85
+ }),
86
+ );
87
+ await t.mutation(operation("finish"), args);
88
+ expect(await t.run((ctx) => ctx.db.query("refunds").unique())).toMatchObject({
89
+ refundCommandKey: "first-original-key",
90
+ refundCommandConflict: true,
91
+ refundCommandNormalizationVersion: 1,
92
+ });
93
+ const observed = (await t.run((ctx) => ctx.db.query("refunds").unique()))!
94
+ .refundCommandObservedAt;
95
+ const generation = await t.mutation(operation("begin"), identity);
96
+ await t.mutation(operation("finish"), {
97
+ ...args,
98
+ generation,
99
+ refund: { ...refund, metadata: {} },
100
+ });
101
+ expect(await t.run((ctx) => ctx.db.query("refunds").unique())).toMatchObject({
102
+ refundCommandKey: "first-original-key",
103
+ refundCommandConflict: true,
104
+ refundCommandObservedAt: observed,
105
+ });
106
+ });
107
+
108
+ it("keeps omitted legacy metadata distinct from an explicit replacement", async () => {
109
+ const t = convexTest(schema, modules);
110
+ await t.mutation(api.connect.mutations.upsertRefund, refund);
111
+ const { metadata: _metadata, ...partial } = refund;
112
+ await t.mutation(api.connect.mutations.upsertRefund, {
113
+ ...partial,
114
+ status: "pending",
115
+ });
116
+ expect(await t.run((ctx) => ctx.db.query("refunds").unique())).toMatchObject({
117
+ refundCommandKey: "original-command",
118
+ refundCommandConflict: false,
119
+ });
120
+ await t.mutation(api.connect.mutations.upsertRefund, {
121
+ ...refund,
122
+ metadata: {},
123
+ });
124
+ expect(await t.run((ctx) => ctx.db.query("refunds").unique())).toMatchObject({
125
+ refundCommandConflict: true,
126
+ });
127
+ });
128
+
129
+ it("retains all 1005 failed/canceled rows while summing only the complete live refund contribution", async () => {
130
+ const { t, args } = await fixture();
131
+ await t.run(async (ctx) => {
132
+ for (let i = 0; i < 1005; i++)
133
+ await ctx.db.insert("refunds", {
134
+ ...refund,
135
+ stripeRefundId: `re_excluded_${i}`,
136
+ amount: 10000,
137
+ status: i % 2 === 0 ? "failed" : "canceled",
138
+ });
139
+ await ctx.db.insert("payments", {
140
+ stripePaymentIntentId: "pi_original",
141
+ userId: "buyer",
142
+ amount: 1000,
143
+ currency: "usd",
144
+ status: "succeeded",
145
+ });
146
+ for (const [status, amount] of [
147
+ ["pending", 50],
148
+ ["requires_action", 100],
149
+ ["succeeded", 200],
150
+ ] as const)
151
+ await ctx.db.insert("refunds", {
152
+ ...refund,
153
+ stripeRefundId: `re_live_${status}`,
154
+ status,
155
+ amount,
156
+ });
157
+ });
158
+ await t.mutation(operation("finish"), args);
159
+ expect(await t.run((ctx) => ctx.db.query("payments").unique())).toMatchObject(
160
+ { refundedAmount: 600, refundStatus: "partially_refunded" },
161
+ );
162
+ expect(await t.run((ctx) => ctx.db.query("refunds").collect())).toHaveLength(
163
+ 1009,
164
+ );
165
+ const generation = await t.mutation(operation("begin"), identity);
166
+ await t.mutation(operation("finish"), {
167
+ ...args,
168
+ generation,
169
+ refund: { ...refund, status: "canceled" },
170
+ });
171
+ expect(await t.run((ctx) => ctx.db.query("payments").unique())).toMatchObject(
172
+ { refundedAmount: 350, refundStatus: "partially_refunded" },
173
+ );
174
+ // The legacy entry point still uses exactly the same full cumulative writer.
175
+ await t.mutation(api.connect.mutations.upsertRefund, {
176
+ ...refund,
177
+ stripeRefundId: "re_final",
178
+ amount: 650,
179
+ });
180
+ expect(await t.run((ctx) => ctx.db.query("payments").unique())).toMatchObject(
181
+ { refundedAmount: 1000, refundStatus: "fully_refunded" },
182
+ );
183
+ });
184
+
185
+ it("holds a new refund whose provider currency contradicts the registered original payment", async () => {
186
+ const { t, args } = await fixture();
187
+ await t.run((ctx) =>
188
+ ctx.db.insert("payments", {
189
+ stripePaymentIntentId: "pi_original",
190
+ userId: "buyer",
191
+ amount: 1000,
192
+ currency: "usd",
193
+ status: "succeeded",
194
+ }),
195
+ );
196
+ await expect(
197
+ t.mutation(operation("finish"), {
198
+ ...args,
199
+ refund: { ...refund, currency: "jpy" },
200
+ }),
201
+ ).rejects.toThrow("Original refund merchant");
202
+ expect(await t.run((ctx) => ctx.db.query("refunds").collect())).toEqual([]);
203
+ expect(
204
+ await t.run((ctx) => ctx.db.query("payments").unique()),
205
+ ).not.toHaveProperty("refundedAmount");
206
+ });
207
+
208
+ it("rejects duplicate refund identities or claim rows before mutating either projection", async () => {
209
+ const t = convexTest(schema, modules);
210
+ await t.run(async (ctx) => {
211
+ await ctx.db.insert("refunds", refund);
212
+ await ctx.db.insert("refunds", refund);
213
+ });
214
+ await expect(t.mutation(operation("begin"), identity)).rejects.toThrow(
215
+ "Refund identity is ambiguous",
216
+ );
217
+ expect(
218
+ await t.run((ctx) => ctx.db.query("refundSyncClaims").collect()),
219
+ ).toEqual([]);
220
+ const s = convexTest(schema, modules);
221
+ await s.run(async (ctx) => {
222
+ for (let i = 0; i < 2; i++)
223
+ await ctx.db.insert("refundSyncClaims", {
224
+ stripeRefundId: identity.stripeRefundId,
225
+ requestedContext: "platform",
226
+ generation: 1,
227
+ status: "pending",
228
+ startedAt: 0,
229
+ });
230
+ });
231
+ await expect(s.mutation(operation("begin"), identity)).rejects.toThrow(
232
+ "Refund synchronization is ambiguous",
233
+ );
234
+ expect(
235
+ await s.run((ctx) => ctx.db.query("refundSyncClaims").collect()),
236
+ ).toHaveLength(2);
237
+ });
238
+
239
+ it("holds duplicate original payment identities before the cumulative writer selects a row", async () => {
240
+ const { t, args } = await fixture();
241
+ await t.run(async (ctx) => {
242
+ for (const userId of ["buyer", "foreign"])
243
+ await ctx.db.insert("payments", {
244
+ stripePaymentIntentId: "pi_original",
245
+ userId,
246
+ amount: 1000,
247
+ currency: "usd",
248
+ status: "succeeded",
249
+ });
250
+ });
251
+ await expect(t.mutation(operation("finish"), args)).rejects.toThrow(
252
+ "Original refund merchant",
253
+ );
254
+ expect(await t.run((ctx) => ctx.db.query("refunds").collect())).toEqual([]);
255
+ });