@fantastic.dev/better-stripe 0.47.0 → 0.48.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 (90) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/README.md +1 -1
  3. package/dist/client/billing/historyPages.d.ts +22 -0
  4. package/dist/client/billing/historyPages.d.ts.map +1 -0
  5. package/dist/client/billing/historyPages.js +8 -0
  6. package/dist/client/billing/historyPages.js.map +1 -0
  7. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +10 -0
  8. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +21 -16
  10. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  11. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +42 -32
  12. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  13. package/dist/client/connect/payoutSyncTestHelpers.d.ts +5 -0
  14. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  15. package/dist/client/publicTypes.d.ts +1 -0
  16. package/dist/client/publicTypes.d.ts.map +1 -1
  17. package/dist/client/readContracts.d.ts +4 -0
  18. package/dist/client/readContracts.d.ts.map +1 -1
  19. package/dist/client/readContracts.js +8 -0
  20. package/dist/client/readContracts.js.map +1 -1
  21. package/dist/client/webhooks/handler.d.ts.map +1 -1
  22. package/dist/client/webhooks/handler.js +6 -3
  23. package/dist/client/webhooks/handler.js.map +1 -1
  24. package/dist/client/webhooks/processors.d.ts.map +1 -1
  25. package/dist/client/webhooks/processors.js +3 -65
  26. package/dist/client/webhooks/processors.js.map +1 -1
  27. package/dist/client/webhooks/refundDelivery.d.ts +5 -0
  28. package/dist/client/webhooks/refundDelivery.d.ts.map +1 -0
  29. package/dist/client/webhooks/refundDelivery.js +28 -0
  30. package/dist/client/webhooks/refundDelivery.js.map +1 -0
  31. package/dist/client/webhooks/refundRecovery.d.ts +5 -0
  32. package/dist/client/webhooks/refundRecovery.d.ts.map +1 -0
  33. package/dist/client/webhooks/refundRecovery.js +36 -0
  34. package/dist/client/webhooks/refundRecovery.js.map +1 -0
  35. package/dist/component/_generated/api.d.ts +4 -0
  36. package/dist/component/_generated/api.d.ts.map +1 -1
  37. package/dist/component/_generated/api.js.map +1 -1
  38. package/dist/component/_generated/component.d.ts +100 -0
  39. package/dist/component/_generated/component.d.ts.map +1 -1
  40. package/dist/component/balanceFunding/mutations.d.ts +16 -16
  41. package/dist/component/billing/schema.d.ts +5 -0
  42. package/dist/component/billing/schema.d.ts.map +1 -1
  43. package/dist/component/billing/schema.js +13 -0
  44. package/dist/component/billing/schema.js.map +1 -1
  45. package/dist/component/billingHistory/queries.d.ts +97 -0
  46. package/dist/component/billingHistory/queries.d.ts.map +1 -0
  47. package/dist/component/billingHistory/queries.js +65 -0
  48. package/dist/component/billingHistory/queries.js.map +1 -0
  49. package/dist/component/billingHistory/scope.d.ts +23 -0
  50. package/dist/component/billingHistory/scope.d.ts.map +1 -0
  51. package/dist/component/billingHistory/scope.js +54 -0
  52. package/dist/component/billingHistory/scope.js.map +1 -0
  53. package/dist/component/connect/validators.js +1 -1
  54. package/dist/component/connect/validators.js.map +1 -1
  55. package/dist/component/earnings/triggers.d.ts +10 -0
  56. package/dist/component/earnings/triggers.d.ts.map +1 -1
  57. package/dist/component/processingCostReconciliation/rollback.d.ts +1 -1
  58. package/dist/component/refundSync/mutations.d.ts +1 -1
  59. package/dist/component/refundSync/mutations.d.ts.map +1 -1
  60. package/dist/component/schema.d.ts +5 -0
  61. package/dist/react/workflows/PlanPricingEditor.js +2 -2
  62. package/dist/react/workflows/PlanPricingEditor.js.map +1 -1
  63. package/docs/billing-history.md +13 -0
  64. package/docs/react-workflows.md +6 -2
  65. package/docs/refund-context.md +42 -9
  66. package/docs/releasing.md +11 -0
  67. package/package.json +3 -2
  68. package/src/client/billing/historyPages.test.ts +58 -0
  69. package/src/client/billing/historyPages.ts +48 -0
  70. package/src/client/publicTypes.ts +7 -0
  71. package/src/client/readContracts.ts +16 -0
  72. package/src/client/webhooks/handler.ts +7 -3
  73. package/src/client/webhooks/processors.test.ts +9 -7
  74. package/src/client/webhooks/processors.ts +3 -88
  75. package/src/client/webhooks/refund-delivery.test.ts +512 -0
  76. package/src/client/webhooks/refundDelivery.ts +42 -0
  77. package/src/client/webhooks/refundRecovery.ts +52 -0
  78. package/src/client/webhooks.test.ts +35 -42
  79. package/src/component/_generated/api.ts +4 -0
  80. package/src/component/_generated/component.ts +128 -0
  81. package/src/component/billing/schema.ts +13 -0
  82. package/src/component/billingHistory/guards.test.ts +235 -0
  83. package/src/component/billingHistory/options.test.ts +35 -0
  84. package/src/component/billingHistory/pages.test.ts +74 -0
  85. package/src/component/billingHistory/queries.ts +88 -0
  86. package/src/component/billingHistory/scope.ts +77 -0
  87. package/src/component/connect/validators.ts +1 -1
  88. package/src/react/workflows/PlanPricingEditor.currency.test.tsx +1 -1
  89. package/src/react/workflows/PlanPricingEditor.tsx +2 -2
  90. package/src/react/workflows/PlanPricingEditor.zero.test.tsx +100 -0
@@ -0,0 +1,88 @@
1
+ import { paginator } from "convex-helpers/server/pagination";
2
+ import {
3
+ paginationOptsValidator,
4
+ paginationResultValidator,
5
+ } from "convex/server";
6
+ import { v } from "convex/values";
7
+ import { query } from "../_generated/server.js";
8
+ import schema from "../schema.js";
9
+ import {
10
+ checkoutSessionDocValidator,
11
+ checkoutSessionStatusValidator,
12
+ subscriptionDocValidator,
13
+ subscriptionStatusValidator,
14
+ } from "../billing/validators.js";
15
+ import { historyOptions, historyResult } from "./scope.js";
16
+
17
+ export const paginateSubscriptions = query({
18
+ args: {
19
+ userId: v.string(),
20
+ accountId: v.optional(v.string()),
21
+ status: v.optional(subscriptionStatusValidator),
22
+ paginationOpts: paginationOptsValidator,
23
+ },
24
+ returns: paginationResultValidator(subscriptionDocValidator),
25
+ handler: async (ctx, args) => {
26
+ const { userId, accountId, status } = args;
27
+ const scope = { kind: "subscriptions" as const, userId, accountId, status };
28
+ const options = historyOptions(scope, args.paginationOpts);
29
+ const rows = paginator(ctx.db, schema).query("subscriptions");
30
+ const scoped =
31
+ accountId !== undefined
32
+ ? status !== undefined
33
+ ? rows.withIndex("by_userId_and_accountId_and_status", (q) =>
34
+ q
35
+ .eq("userId", userId)
36
+ .eq("accountId", accountId)
37
+ .eq("status", status),
38
+ )
39
+ : rows.withIndex("by_userId_and_accountId", (q) =>
40
+ q.eq("userId", userId).eq("accountId", accountId),
41
+ )
42
+ : status !== undefined
43
+ ? rows.withIndex("by_userId_and_status", (q) =>
44
+ q.eq("userId", userId).eq("status", status),
45
+ )
46
+ : rows.withIndex("by_user_id", (q) => q.eq("userId", userId));
47
+ return historyResult(scope, await scoped.order("desc").paginate(options));
48
+ },
49
+ });
50
+
51
+ export const paginateCheckoutSessions = query({
52
+ args: {
53
+ userId: v.string(),
54
+ accountId: v.optional(v.string()),
55
+ status: v.optional(checkoutSessionStatusValidator),
56
+ paginationOpts: paginationOptsValidator,
57
+ },
58
+ returns: paginationResultValidator(checkoutSessionDocValidator),
59
+ handler: async (ctx, args) => {
60
+ const { userId, accountId, status } = args;
61
+ const scope = {
62
+ kind: "checkoutSessions" as const,
63
+ userId,
64
+ accountId,
65
+ status,
66
+ };
67
+ const options = historyOptions(scope, args.paginationOpts);
68
+ const rows = paginator(ctx.db, schema).query("checkoutSessions");
69
+ const scoped =
70
+ accountId !== undefined
71
+ ? status !== undefined
72
+ ? rows.withIndex("by_userId_and_accountId_and_status", (q) =>
73
+ q
74
+ .eq("userId", userId)
75
+ .eq("accountId", accountId)
76
+ .eq("status", status),
77
+ )
78
+ : rows.withIndex("by_userId_and_accountId", (q) =>
79
+ q.eq("userId", userId).eq("accountId", accountId),
80
+ )
81
+ : status !== undefined
82
+ ? rows.withIndex("by_user_status", (q) =>
83
+ q.eq("userId", userId).eq("status", status),
84
+ )
85
+ : rows.withIndex("by_user_id", (q) => q.eq("userId", userId));
86
+ return historyResult(scope, await scoped.order("desc").paginate(options));
87
+ },
88
+ });
@@ -0,0 +1,77 @@
1
+ import type { PaginationOptions, PaginationResult } from "convex/server";
2
+
3
+ export type HistoryScope = {
4
+ kind: "subscriptions" | "checkoutSessions";
5
+ userId: string;
6
+ accountId?: string;
7
+ status?: string;
8
+ };
9
+
10
+ function encoded(scope: HistoryScope, cursor: string) {
11
+ return btoa(
12
+ encodeURIComponent(JSON.stringify({ version: 1, scope, cursor })),
13
+ );
14
+ }
15
+
16
+ function decoded(scope: HistoryScope, cursor: string) {
17
+ try {
18
+ const value = JSON.parse(decodeURIComponent(atob(cursor)));
19
+ if (
20
+ value.version !== 1 ||
21
+ typeof value.cursor !== "string" ||
22
+ encoded(scope, value.cursor) !== cursor
23
+ )
24
+ throw new Error();
25
+ return value.cursor as string;
26
+ } catch {
27
+ throw new Error("Invalid billing history cursor or scope");
28
+ }
29
+ }
30
+
31
+ /** Context binding only; the trusted host must authorize every call. */
32
+ export function historyOptions(
33
+ scope: HistoryScope,
34
+ options: PaginationOptions,
35
+ ) {
36
+ if (
37
+ !isCanonical(scope.userId) ||
38
+ (scope.accountId !== undefined && !isCanonical(scope.accountId)) ||
39
+ !Number.isSafeInteger(options.numItems) ||
40
+ options.numItems < 1 ||
41
+ options.numItems > 100
42
+ )
43
+ throw new Error("Invalid billing history selector or page size");
44
+ return {
45
+ ...options,
46
+ cursor: options.cursor === null ? null : decoded(scope, options.cursor),
47
+ ...(options.endCursor !== undefined && options.endCursor !== null
48
+ ? { endCursor: decoded(scope, options.endCursor) }
49
+ : {}),
50
+ maximumRowsRead: ceiling(options.maximumRowsRead, 200),
51
+ maximumBytesRead: ceiling(options.maximumBytesRead, 1_000_000),
52
+ };
53
+ }
54
+
55
+ export function historyResult<T>(
56
+ scope: HistoryScope,
57
+ result: PaginationResult<T>,
58
+ ) {
59
+ return {
60
+ ...result,
61
+ continueCursor: encoded(scope, result.continueCursor),
62
+ ...(result.splitCursor
63
+ ? { splitCursor: encoded(scope, result.splitCursor) }
64
+ : {}),
65
+ };
66
+ }
67
+
68
+ function ceiling(requested: number | undefined, policy: number) {
69
+ if (requested === undefined) return policy;
70
+ if (!Number.isSafeInteger(requested) || requested < 1)
71
+ throw new Error("Invalid billing history read ceiling");
72
+ return Math.min(requested, policy);
73
+ }
74
+
75
+ function isCanonical(value: string) {
76
+ return value.length > 0 && value === value.trim() && !/\p{Cc}/u.test(value);
77
+ }
@@ -2,7 +2,7 @@ import { refundCommandFields } from "../refundHistory/commandFields.js";
2
2
  import { commissionExposureValidator } from "../settlement/clawbackSchema.js";
3
3
  import { type Infer, v } from "convex/values";
4
4
 
5
- import { feeRoutingFields, splitRecipientRoleValidator } from "../lib/fees";
5
+ import { feeRoutingFields, splitRecipientRoleValidator } from "../lib/fees.js";
6
6
 
7
7
  export const paymentStatusValidator = v.union(
8
8
  v.literal("succeeded"),
@@ -65,7 +65,7 @@ it.each([
65
65
  ["ugx", "1.01"],
66
66
  ["usd", "1.005"],
67
67
  ["usd", "90071992547409.92"],
68
- ["usd", "0"],
68
+ ["usd", "-1"],
69
69
  ["usd", "1e2"],
70
70
  ["ZZZ", "1"],
71
71
  ["bhd", "1"],
@@ -65,9 +65,9 @@ export function PlanPricingEditor({
65
65
  fields.monthlyPrice.trim(),
66
66
  currency,
67
67
  );
68
- if (monthlyAmount === null || monthlyAmount <= 0)
68
+ if (monthlyAmount === null)
69
69
  throw new Error(
70
- "Enter a positive monthly price in supported currency units.",
70
+ "Enter a nonnegative monthly price in supported currency units.",
71
71
  );
72
72
  const feeBasisPoints =
73
73
  fields.saleFee.trim() === ""
@@ -0,0 +1,100 @@
1
+ // @vitest-environment jsdom
2
+ import "@testing-library/jest-dom/vitest";
3
+ import { cleanup, render, screen } from "@testing-library/react";
4
+ import userEvent from "@testing-library/user-event";
5
+ import { afterEach, expect, it, vi } from "vitest";
6
+ import { parseChargeAmount } from "../../client/charge-currency.js";
7
+ import { PlanPricingEditor } from "./PlanPricingEditor.js";
8
+
9
+ afterEach(cleanup);
10
+ const plan = {
11
+ id: "original-plan",
12
+ name: "Original",
13
+ monthlyAmount: 0,
14
+ feeBasisPoints: null,
15
+ affiliateBasisPoints: 2500,
16
+ version: 7,
17
+ };
18
+
19
+ it.each([
20
+ ["jpy", "0", 0],
21
+ ["usd", "0.00", 0],
22
+ ["jpy", "100", 100],
23
+ ])(
24
+ "saves the exact original %s price %s through the native form",
25
+ async (currency, display, amount) => {
26
+ const onSave = vi.fn().mockResolvedValue(undefined);
27
+ render(
28
+ <PlanPricingEditor
29
+ plan={{ ...plan, currency, monthlyAmount: amount }}
30
+ onSave={onSave}
31
+ />,
32
+ );
33
+ expect(parseChargeAmount(display, currency)).toBe(amount);
34
+ expect(
35
+ screen.getByLabelText(`Monthly price (${currency.toUpperCase()})`),
36
+ ).toHaveValue(display);
37
+ await userEvent.click(screen.getByRole("button", { name: "Save pricing" }));
38
+ expect(onSave).toHaveBeenCalledExactlyOnceWith({
39
+ monthlyAmount: amount,
40
+ feeBasisPoints: null,
41
+ affiliateBasisPoints: 2500,
42
+ expectedVersion: 7,
43
+ });
44
+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();
45
+ expect(screen.getByRole("status")).toHaveTextContent("Pricing saved");
46
+ },
47
+ );
48
+
49
+ it.each(["jpy", "usd"])(
50
+ "saves edited zero %s through the render-prop controller with an explicit zero fee",
51
+ async (currency) => {
52
+ const onSave = vi.fn().mockResolvedValue(undefined);
53
+ render(
54
+ <PlanPricingEditor
55
+ plan={{ ...plan, currency, monthlyAmount: 100, feeBasisPoints: 0 }}
56
+ onSave={onSave}
57
+ >
58
+ {(state) => (
59
+ <>
60
+ <button onClick={() => state.setMonthlyPrice("0")}>Zero</button>
61
+ <button onClick={() => void state.save()}>Save</button>
62
+ <output>{state.monthlyPrice}</output>
63
+ {state.error && <p role="alert">{state.error}</p>}
64
+ </>
65
+ )}
66
+ </PlanPricingEditor>,
67
+ );
68
+ await userEvent.click(screen.getByRole("button", { name: "Zero" }));
69
+ expect(screen.getByRole("status")).toHaveTextContent("0");
70
+ await userEvent.click(screen.getByRole("button", { name: "Save" }));
71
+ expect(onSave).toHaveBeenCalledExactlyOnceWith({
72
+ monthlyAmount: 0,
73
+ feeBasisPoints: 0,
74
+ affiliateBasisPoints: 2500,
75
+ expectedVersion: 7,
76
+ });
77
+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();
78
+ },
79
+ );
80
+
81
+ it("retries zero with the original version after a failed save", async () => {
82
+ const onSave = vi
83
+ .fn()
84
+ .mockRejectedValueOnce(new Error("Retry"))
85
+ .mockResolvedValue(undefined);
86
+ render(
87
+ <PlanPricingEditor plan={{ ...plan, currency: "jpy" }} onSave={onSave} />,
88
+ );
89
+ await userEvent.click(screen.getByRole("button", { name: "Save pricing" }));
90
+ expect(screen.getByRole("alert")).toHaveTextContent("Retry");
91
+ await userEvent.click(screen.getByRole("button", { name: "Save pricing" }));
92
+ expect(onSave).toHaveBeenCalledTimes(2);
93
+ expect(onSave).toHaveBeenNthCalledWith(2, {
94
+ monthlyAmount: 0,
95
+ feeBasisPoints: null,
96
+ affiliateBasisPoints: 2500,
97
+ expectedVersion: 7,
98
+ });
99
+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();
100
+ });