@fantastic.dev/better-stripe 0.45.1 → 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 (99) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/MIGRATION.md +6 -4
  3. package/README.md +8 -6
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +46 -0
  5. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +23 -0
  7. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +46 -0
  9. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts +23 -0
  11. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  12. package/dist/client/connect/refundSync.d.ts +32 -0
  13. package/dist/client/connect/refundSync.d.ts.map +1 -0
  14. package/dist/client/connect/refundSync.js +61 -0
  15. package/dist/client/connect/refundSync.js.map +1 -0
  16. package/dist/client/connect/refundSyncValidation.d.ts +16 -0
  17. package/dist/client/connect/refundSyncValidation.d.ts.map +1 -0
  18. package/dist/client/connect/refundSyncValidation.js +87 -0
  19. package/dist/client/connect/refundSyncValidation.js.map +1 -0
  20. package/dist/client/index.d.ts +30 -0
  21. package/dist/client/index.d.ts.map +1 -1
  22. package/dist/client/index.js +5 -0
  23. package/dist/client/index.js.map +1 -1
  24. package/dist/component/_generated/api.d.ts +12 -0
  25. package/dist/component/_generated/api.d.ts.map +1 -1
  26. package/dist/component/_generated/api.js.map +1 -1
  27. package/dist/component/_generated/component.d.ts +67 -0
  28. package/dist/component/_generated/component.d.ts.map +1 -1
  29. package/dist/component/connect/mutations.d.ts.map +1 -1
  30. package/dist/component/connect/mutations.js +2 -53
  31. package/dist/component/connect/mutations.js.map +1 -1
  32. package/dist/component/connect/refundWrites.d.ts +6 -0
  33. package/dist/component/connect/refundWrites.d.ts.map +1 -0
  34. package/dist/component/connect/refundWrites.js +56 -0
  35. package/dist/component/connect/refundWrites.js.map +1 -0
  36. package/dist/component/earnings/triggers.d.ts +46 -0
  37. package/dist/component/earnings/triggers.d.ts.map +1 -1
  38. package/dist/component/processingCostReconciliation/rollback.d.ts +1 -1
  39. package/dist/component/refundHistory/originalSeller.d.ts +1 -1
  40. package/dist/component/refundHistory/originalSeller.d.ts.map +1 -1
  41. package/dist/component/refundHistory/originalSeller.js.map +1 -1
  42. package/dist/component/refundSync/helpers.d.ts +43 -0
  43. package/dist/component/refundSync/helpers.d.ts.map +1 -0
  44. package/dist/component/refundSync/helpers.js +71 -0
  45. package/dist/component/refundSync/helpers.js.map +1 -0
  46. package/dist/component/refundSync/mutations.d.ts +56 -0
  47. package/dist/component/refundSync/mutations.d.ts.map +1 -0
  48. package/dist/component/refundSync/mutations.js +113 -0
  49. package/dist/component/refundSync/mutations.js.map +1 -0
  50. package/dist/component/refundSync/queries.d.ts +12 -0
  51. package/dist/component/refundSync/queries.d.ts.map +1 -0
  52. package/dist/component/refundSync/queries.js +10 -0
  53. package/dist/component/refundSync/queries.js.map +1 -0
  54. package/dist/component/refundSync/routing.d.ts +8 -0
  55. package/dist/component/refundSync/routing.d.ts.map +1 -0
  56. package/dist/component/refundSync/routing.js +42 -0
  57. package/dist/component/refundSync/routing.js.map +1 -0
  58. package/dist/component/refundSync/schema.d.ts +25 -0
  59. package/dist/component/refundSync/schema.d.ts.map +1 -0
  60. package/dist/component/refundSync/schema.js +15 -0
  61. package/dist/component/refundSync/schema.js.map +1 -0
  62. package/dist/component/refundSync/validators.d.ts +164 -0
  63. package/dist/component/refundSync/validators.d.ts.map +1 -0
  64. package/dist/component/refundSync/validators.js +32 -0
  65. package/dist/component/refundSync/validators.js.map +1 -0
  66. package/dist/component/schema.d.ts +23 -0
  67. package/dist/component/schema.js +2 -0
  68. package/dist/component/schema.js.map +1 -1
  69. package/docs/affiliate-clawbacks.md +3 -3
  70. package/docs/architecture/component-extraction.md +415 -0
  71. package/docs/architecture/durable-execution.md +200 -0
  72. package/docs/architecture/recovery-workflow.md +69 -0
  73. package/docs/balance-funding-state.md +114 -0
  74. package/docs/balance-funding-workflow.md +53 -0
  75. package/docs/example-balance-funding-cutover.md +94 -0
  76. package/docs/example-recovery-cutover.md +21 -0
  77. package/docs/processing-cost-reconciliation.md +23 -0
  78. package/docs/refund-context.md +54 -0
  79. package/docs/release-handoff.md +196 -0
  80. package/docs/releasing.md +41 -0
  81. package/package.json +12 -2
  82. package/src/client/connect/refundSync.test.ts +239 -0
  83. package/src/client/connect/refundSync.transport.test.ts +396 -0
  84. package/src/client/connect/refundSync.ts +125 -0
  85. package/src/client/connect/refundSyncValidation.ts +120 -0
  86. package/src/client/index.ts +19 -0
  87. package/src/component/_generated/api.ts +12 -0
  88. package/src/component/_generated/component.ts +100 -0
  89. package/src/component/connect/mutations.ts +2 -67
  90. package/src/component/connect/refundWrites.ts +76 -0
  91. package/src/component/refundHistory/originalSeller.ts +4 -1
  92. package/src/component/refundSync/helpers.ts +99 -0
  93. package/src/component/refundSync/mutations.ts +131 -0
  94. package/src/component/refundSync/queries.ts +10 -0
  95. package/src/component/refundSync/refund-sync.test.ts +255 -0
  96. package/src/component/refundSync/routing.ts +55 -0
  97. package/src/component/refundSync/schema.ts +19 -0
  98. package/src/component/refundSync/validators.ts +35 -0
  99. package/src/component/schema.ts +2 -0
@@ -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
+ }
@@ -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
+ });