@fantastic.dev/better-stripe 0.55.0 → 0.56.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 (212) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +3 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +216 -38
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +92 -3
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +216 -38
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +92 -3
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  11. package/dist/client/index.d.ts +4 -0
  12. package/dist/client/index.d.ts.map +1 -1
  13. package/dist/client/index.js +1 -0
  14. package/dist/client/index.js.map +1 -1
  15. package/dist/client/usage/catalogPrices.d.ts +2 -0
  16. package/dist/client/usage/catalogPrices.d.ts.map +1 -1
  17. package/dist/client/usage/catalogPrices.js +15 -0
  18. package/dist/client/usage/catalogPrices.js.map +1 -1
  19. package/dist/client/usage/client.d.ts +2 -2
  20. package/dist/client/usage/client.d.ts.map +1 -1
  21. package/dist/client/usage/client.js +2 -2
  22. package/dist/client/usage/client.js.map +1 -1
  23. package/dist/client/usage/deliveryProvider.d.ts.map +1 -1
  24. package/dist/client/usage/deliveryProvider.js +26 -1
  25. package/dist/client/usage/deliveryProvider.js.map +1 -1
  26. package/dist/client/usage/index.d.ts +4 -0
  27. package/dist/client/usage/index.d.ts.map +1 -1
  28. package/dist/client/usage/index.js +1 -0
  29. package/dist/client/usage/index.js.map +1 -1
  30. package/dist/client/usage/subscription.fixtures.d.ts +118 -0
  31. package/dist/client/usage/subscription.fixtures.d.ts.map +1 -0
  32. package/dist/client/usage/subscription.fixtures.js +84 -0
  33. package/dist/client/usage/subscription.fixtures.js.map +1 -0
  34. package/dist/client/usage/subscriptionAbandonment.d.ts +8 -0
  35. package/dist/client/usage/subscriptionAbandonment.d.ts.map +1 -0
  36. package/dist/client/usage/subscriptionAbandonment.js +82 -0
  37. package/dist/client/usage/subscriptionAbandonment.js.map +1 -0
  38. package/dist/client/usage/subscriptionCancellation.d.ts +9 -0
  39. package/dist/client/usage/subscriptionCancellation.d.ts.map +1 -0
  40. package/dist/client/usage/subscriptionCancellation.js +39 -0
  41. package/dist/client/usage/subscriptionCancellation.js.map +1 -0
  42. package/dist/client/usage/subscriptionCheckout.d.ts +52 -0
  43. package/dist/client/usage/subscriptionCheckout.d.ts.map +1 -0
  44. package/dist/client/usage/subscriptionCheckout.js +94 -0
  45. package/dist/client/usage/subscriptionCheckout.js.map +1 -0
  46. package/dist/client/usage/subscriptionClient.d.ts +267 -0
  47. package/dist/client/usage/subscriptionClient.d.ts.map +1 -0
  48. package/dist/client/usage/subscriptionClient.js +93 -0
  49. package/dist/client/usage/subscriptionClient.js.map +1 -0
  50. package/dist/client/usage/subscriptionErrors.d.ts +5 -0
  51. package/dist/client/usage/subscriptionErrors.d.ts.map +1 -0
  52. package/dist/client/usage/subscriptionErrors.js +9 -0
  53. package/dist/client/usage/subscriptionErrors.js.map +1 -0
  54. package/dist/client/usage/subscriptionInvoiceSchema.d.ts +203 -0
  55. package/dist/client/usage/subscriptionInvoiceSchema.d.ts.map +1 -0
  56. package/dist/client/usage/subscriptionInvoiceSchema.js +108 -0
  57. package/dist/client/usage/subscriptionInvoiceSchema.js.map +1 -0
  58. package/dist/client/usage/subscriptionLifecycle.d.ts +80 -0
  59. package/dist/client/usage/subscriptionLifecycle.d.ts.map +1 -0
  60. package/dist/client/usage/subscriptionLifecycle.js +87 -0
  61. package/dist/client/usage/subscriptionLifecycle.js.map +1 -0
  62. package/dist/client/usage/subscriptionProvider.d.ts +111 -0
  63. package/dist/client/usage/subscriptionProvider.d.ts.map +1 -0
  64. package/dist/client/usage/subscriptionProvider.js +147 -0
  65. package/dist/client/usage/subscriptionProvider.js.map +1 -0
  66. package/dist/client/usage/subscriptionTerms.d.ts +161 -0
  67. package/dist/client/usage/subscriptionTerms.d.ts.map +1 -0
  68. package/dist/client/usage/subscriptionTerms.js +242 -0
  69. package/dist/client/usage/subscriptionTerms.js.map +1 -0
  70. package/dist/client/usage/subscriptionTransport.fixtures.d.ts +25 -0
  71. package/dist/client/usage/subscriptionTransport.fixtures.d.ts.map +1 -0
  72. package/dist/client/usage/subscriptionTransport.fixtures.js +203 -0
  73. package/dist/client/usage/subscriptionTransport.fixtures.js.map +1 -0
  74. package/dist/client/webhooks/processors.d.ts.map +1 -1
  75. package/dist/client/webhooks/processors.js +2 -0
  76. package/dist/client/webhooks/processors.js.map +1 -1
  77. package/dist/client/webhooks/usageSubscriptions.d.ts +5 -0
  78. package/dist/client/webhooks/usageSubscriptions.d.ts.map +1 -0
  79. package/dist/client/webhooks/usageSubscriptions.js +54 -0
  80. package/dist/client/webhooks/usageSubscriptions.js.map +1 -0
  81. package/dist/component/_generated/api.d.ts +14 -0
  82. package/dist/component/_generated/api.d.ts.map +1 -1
  83. package/dist/component/_generated/api.js.map +1 -1
  84. package/dist/component/_generated/component.d.ts +160 -5
  85. package/dist/component/_generated/component.d.ts.map +1 -1
  86. package/dist/component/accountClosure/mutations.d.ts.map +1 -1
  87. package/dist/component/accountClosure/mutations.js +10 -0
  88. package/dist/component/accountClosure/mutations.js.map +1 -1
  89. package/dist/component/balanceFunding/preparationHandlers.d.ts +8 -8
  90. package/dist/component/balanceFunding/workflowValidators.d.ts +16 -16
  91. package/dist/component/earnings/triggers.d.ts +192 -4
  92. package/dist/component/earnings/triggers.d.ts.map +1 -1
  93. package/dist/component/payoutRelease/queries.d.ts +2 -2
  94. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  95. package/dist/component/schema.d.ts +92 -3
  96. package/dist/component/schema.js +5 -0
  97. package/dist/component/schema.js.map +1 -1
  98. package/dist/component/usage/mutations.d.ts.map +1 -1
  99. package/dist/component/usage/mutations.js +5 -0
  100. package/dist/component/usage/mutations.js.map +1 -1
  101. package/dist/component/usage/queries.d.ts +2 -0
  102. package/dist/component/usage/queries.d.ts.map +1 -1
  103. package/dist/component/usage/schema.d.ts +14 -7
  104. package/dist/component/usage/schema.d.ts.map +1 -1
  105. package/dist/component/usage/schema.js +5 -1
  106. package/dist/component/usage/schema.js.map +1 -1
  107. package/dist/component/usageDelivery/fields.d.ts +3 -2
  108. package/dist/component/usageDelivery/fields.d.ts.map +1 -1
  109. package/dist/component/usageDelivery/fields.js +2 -1
  110. package/dist/component/usageDelivery/fields.js.map +1 -1
  111. package/dist/component/usageDelivery/helpers.d.ts +4 -3
  112. package/dist/component/usageDelivery/helpers.d.ts.map +1 -1
  113. package/dist/component/usageDelivery/mutations.d.ts +3 -3
  114. package/dist/component/usageDelivery/queries.d.ts +17 -3
  115. package/dist/component/usageDelivery/queries.d.ts.map +1 -1
  116. package/dist/component/usageDelivery/queries.js +20 -3
  117. package/dist/component/usageDelivery/queries.js.map +1 -1
  118. package/dist/component/usageDelivery/schema.d.ts +2 -2
  119. package/dist/component/usageDelivery/steps.d.ts +1 -1
  120. package/dist/component/usageDelivery/steps.d.ts.map +1 -1
  121. package/dist/component/usageDelivery/steps.js +12 -1
  122. package/dist/component/usageDelivery/steps.js.map +1 -1
  123. package/dist/component/usageSubscriptions/abandonment.d.ts +4 -0
  124. package/dist/component/usageSubscriptions/abandonment.d.ts.map +1 -0
  125. package/dist/component/usageSubscriptions/abandonment.js +59 -0
  126. package/dist/component/usageSubscriptions/abandonment.js.map +1 -0
  127. package/dist/component/usageSubscriptions/acceptance.d.ts +11 -0
  128. package/dist/component/usageSubscriptions/acceptance.d.ts.map +1 -0
  129. package/dist/component/usageSubscriptions/acceptance.js +38 -0
  130. package/dist/component/usageSubscriptions/acceptance.js.map +1 -0
  131. package/dist/component/usageSubscriptions/helpers.d.ts +39 -0
  132. package/dist/component/usageSubscriptions/helpers.d.ts.map +1 -0
  133. package/dist/component/usageSubscriptions/helpers.js +28 -0
  134. package/dist/component/usageSubscriptions/helpers.js.map +1 -0
  135. package/dist/component/usageSubscriptions/history.d.ts +46 -0
  136. package/dist/component/usageSubscriptions/history.d.ts.map +1 -0
  137. package/dist/component/usageSubscriptions/history.js +46 -0
  138. package/dist/component/usageSubscriptions/history.js.map +1 -0
  139. package/dist/component/usageSubscriptions/mutations.d.ts +64 -0
  140. package/dist/component/usageSubscriptions/mutations.d.ts.map +1 -0
  141. package/dist/component/usageSubscriptions/mutations.js +252 -0
  142. package/dist/component/usageSubscriptions/mutations.js.map +1 -0
  143. package/dist/component/usageSubscriptions/queries.d.ts +81 -0
  144. package/dist/component/usageSubscriptions/queries.d.ts.map +1 -0
  145. package/dist/component/usageSubscriptions/queries.js +70 -0
  146. package/dist/component/usageSubscriptions/queries.js.map +1 -0
  147. package/dist/component/usageSubscriptions/retirement.d.ts +4 -0
  148. package/dist/component/usageSubscriptions/retirement.d.ts.map +1 -0
  149. package/dist/component/usageSubscriptions/retirement.js +80 -0
  150. package/dist/component/usageSubscriptions/retirement.js.map +1 -0
  151. package/dist/component/usageSubscriptions/schema.d.ts +191 -0
  152. package/dist/component/usageSubscriptions/schema.d.ts.map +1 -0
  153. package/dist/component/usageSubscriptions/schema.js +69 -0
  154. package/dist/component/usageSubscriptions/schema.js.map +1 -0
  155. package/dist/test.d.ts +6 -0
  156. package/dist/test.d.ts.map +1 -0
  157. package/dist/test.js +15 -0
  158. package/dist/test.js.map +1 -0
  159. package/docs/README.md +2 -0
  160. package/docs/evidence/native-metering/clock-finalization-run.json +129 -0
  161. package/docs/evidence/native-metering/clock-lag-run.json +111 -0
  162. package/docs/evidence/native-metering/paid-run.json +107 -0
  163. package/docs/evidence/native-metering/promotional-run.json +103 -0
  164. package/docs/metered-usage.md +14 -0
  165. package/docs/metering-setup.md +5 -1
  166. package/docs/usage-subscriptions.md +278 -0
  167. package/package.json +4 -2
  168. package/src/client/index.ts +8 -0
  169. package/src/client/usage/catalogPrices.ts +21 -0
  170. package/src/client/usage/client.ts +2 -2
  171. package/src/client/usage/deliveryProvider.test.ts +70 -1
  172. package/src/client/usage/deliveryProvider.ts +43 -2
  173. package/src/client/usage/index.ts +9 -0
  174. package/src/client/usage/subscription.fixtures.ts +84 -0
  175. package/src/client/usage/subscriptionAbandonment.test.ts +124 -0
  176. package/src/client/usage/subscriptionAbandonment.ts +116 -0
  177. package/src/client/usage/subscriptionCancellation.ts +90 -0
  178. package/src/client/usage/subscriptionCheckout.test.ts +31 -0
  179. package/src/client/usage/subscriptionCheckout.ts +152 -0
  180. package/src/client/usage/subscriptionClient.test.ts +316 -0
  181. package/src/client/usage/subscriptionClient.ts +204 -0
  182. package/src/client/usage/subscriptionErrors.ts +14 -0
  183. package/src/client/usage/subscriptionInvoiceSchema.ts +116 -0
  184. package/src/client/usage/subscriptionLifecycle.ts +165 -0
  185. package/src/client/usage/subscriptionProvider.test.ts +48 -0
  186. package/src/client/usage/subscriptionProvider.ts +247 -0
  187. package/src/client/usage/subscriptionTerms.test.ts +158 -0
  188. package/src/client/usage/subscriptionTerms.ts +294 -0
  189. package/src/client/usage/subscriptionTransport.fixtures.ts +241 -0
  190. package/src/client/webhooks/processors.ts +2 -0
  191. package/src/client/webhooks/usageSubscriptions.test.ts +162 -0
  192. package/src/client/webhooks/usageSubscriptions.ts +81 -0
  193. package/src/component/_generated/api.ts +14 -0
  194. package/src/component/_generated/component.ts +200 -0
  195. package/src/component/accountClosure/mutations.ts +12 -0
  196. package/src/component/schema.ts +10 -0
  197. package/src/component/usage/mutations.ts +5 -0
  198. package/src/component/usage/schema.ts +5 -1
  199. package/src/component/usageDelivery/fields.ts +2 -0
  200. package/src/component/usageDelivery/queries.ts +30 -3
  201. package/src/component/usageDelivery/steps.ts +22 -1
  202. package/src/component/usageSubscriptions/abandonment.ts +80 -0
  203. package/src/component/usageSubscriptions/acceptance.test.ts +122 -0
  204. package/src/component/usageSubscriptions/acceptance.ts +66 -0
  205. package/src/component/usageSubscriptions/helpers.ts +33 -0
  206. package/src/component/usageSubscriptions/history.test.ts +69 -0
  207. package/src/component/usageSubscriptions/history.ts +68 -0
  208. package/src/component/usageSubscriptions/mutations.test.ts +205 -0
  209. package/src/component/usageSubscriptions/mutations.ts +275 -0
  210. package/src/component/usageSubscriptions/queries.ts +78 -0
  211. package/src/component/usageSubscriptions/retirement.ts +105 -0
  212. package/src/component/usageSubscriptions/schema.ts +73 -0
@@ -0,0 +1,122 @@
1
+ import { convexTest } from "convex-test";
2
+ import { makeFunctionReference } from "convex/server";
3
+ import { afterEach, expect, it, vi } from "vitest";
4
+ import { schema, modules } from "../../test.js";
5
+ import {
6
+ request,
7
+ nativeSubscription,
8
+ } from "../../client/usage/subscription.fixtures.js";
9
+ const prepare = makeFunctionReference<"mutation">(
10
+ "usageSubscriptions/mutations:prepare",
11
+ ),
12
+ save = makeFunctionReference<"mutation">("usageSubscriptions/mutations:save"),
13
+ record = makeFunctionReference<"mutation">("usage/mutations:record");
14
+ afterEach(() => vi.useRealTimers());
15
+ it("rejects new managed usage at closeout while retaining immutable replays", async () => {
16
+ vi.useFakeTimers();
17
+ vi.setSystemTime(700000);
18
+ const t = convexTest(schema, modules);
19
+ const intent = await t.mutation(prepare, {
20
+ termsJson: JSON.stringify(request),
21
+ method: "direct",
22
+ });
23
+ await t.mutation(save, {
24
+ key: intent.key,
25
+ nativeJson: JSON.stringify(nativeSubscription()),
26
+ startedAt: Date.now(),
27
+ });
28
+ const input = {
29
+ ...request.meters[0],
30
+ sourceEventId: "one",
31
+ quantity: "1",
32
+ occurredAt: 700,
33
+ };
34
+ const sub = {
35
+ subscriptionId: "sub_calls",
36
+ subscriptionItemId: "si_calls",
37
+ stripePriceId: "price_calls",
38
+ period: { start: 600, end: 1200 },
39
+ interval: "month",
40
+ };
41
+ const args = {
42
+ inputJson: JSON.stringify(input),
43
+ subscriptionJson: JSON.stringify(sub),
44
+ };
45
+ const receipt = await t.mutation(record, args);
46
+ vi.setSystemTime(1150000);
47
+ expect(await t.mutation(record, args)).toEqual(receipt);
48
+ await expect(
49
+ t.mutation(record, {
50
+ ...args,
51
+ inputJson: JSON.stringify({
52
+ ...input,
53
+ sourceEventId: "late",
54
+ occurredAt: 1100,
55
+ }),
56
+ }),
57
+ ).rejects.toThrow(/closing|closed/i);
58
+ });
59
+
60
+ it("keeps enrollment reserved until native cancellation/finalization and all local sends are resolved", async () => {
61
+ vi.useFakeTimers();
62
+ vi.setSystemTime(700000);
63
+ const t = convexTest(schema, modules),
64
+ intent = await t.mutation(prepare, {
65
+ termsJson: JSON.stringify(request),
66
+ method: "direct",
67
+ });
68
+ const native = nativeSubscription();
69
+ await t.mutation(save, {
70
+ key: intent.key,
71
+ nativeJson: JSON.stringify(native),
72
+ startedAt: Date.now(),
73
+ });
74
+ const retire = makeFunctionReference<"mutation">(
75
+ "usageSubscriptions/mutations:retire",
76
+ );
77
+ const proof = {
78
+ invoiceId: "in_closeout",
79
+ stripeAccountId: "acct_platform",
80
+ customerAccount: "acct_buyer",
81
+ stripeCustomerId: "cus_buyer",
82
+ livemode: false,
83
+ subscriptionId: "sub_calls",
84
+ status: "open",
85
+ finalizedAt: 1300,
86
+ billingReason: "subscription_cycle",
87
+ periodEnd: 1200,
88
+ };
89
+ await expect(
90
+ t.mutation(retire, { key: intent.key, proofJson: JSON.stringify(proof) }),
91
+ ).rejects.toThrow();
92
+ native.status = "canceled";
93
+ vi.setSystemTime(1400000);
94
+ await t.mutation(save, {
95
+ key: intent.key,
96
+ nativeJson: JSON.stringify(native),
97
+ startedAt: Date.now(),
98
+ });
99
+ await expect(
100
+ t.mutation(retire, {
101
+ key: intent.key,
102
+ proofJson: JSON.stringify({
103
+ ...proof,
104
+ billingReason: "subscription_create",
105
+ }),
106
+ }),
107
+ ).rejects.toThrow();
108
+ await t.mutation(retire, {
109
+ key: intent.key,
110
+ proofJson: JSON.stringify(proof),
111
+ });
112
+ const next = structuredClone(request);
113
+ next.requestId = "next";
114
+ next.meters[0].binding.stripePriceId = "price_next";
115
+ next.meters[0].binding.plan.version = "v2";
116
+ expect(
117
+ await t.mutation(prepare, {
118
+ termsJson: JSON.stringify(next),
119
+ method: "direct",
120
+ }),
121
+ ).toHaveProperty("key");
122
+ });
@@ -0,0 +1,66 @@
1
+ import { convexToJson } from "convex/values";
2
+ import type { QueryCtx } from "../_generated/server.js";
3
+ import type { PreparedUsageRecord } from "../../client/usage/records.js";
4
+ import type { UsageSubscriptionBinding } from "../../client/usage/boundaries.js";
5
+ import type { UsageSubscriptionView } from "../../client/usage/subscriptionTerms.js";
6
+ /** Managed v1 closes new acceptance/sends 60 seconds before the native period. */
7
+ export async function managedBillingPolicy(
8
+ ctx: QueryCtx,
9
+ record: PreparedUsageRecord,
10
+ subscription: UsageSubscriptionBinding,
11
+ ): Promise<{
12
+ cutoff: number;
13
+ collection: UsageSubscriptionView["collection"] | null;
14
+ } | null> {
15
+ const candidates = await ctx.db
16
+ .query("usageSubscriptionIntents")
17
+ .withIndex("by_provider", (q) =>
18
+ q.eq("providerId", subscription.subscriptionId),
19
+ )
20
+ .take(3);
21
+ const matched = candidates.filter((intent) => {
22
+ const scope = JSON.parse(intent.scopeKey);
23
+ return (
24
+ scope.stripeAccountId === record.scope.stripeAccountId &&
25
+ scope.livemode === record.scope.livemode &&
26
+ scope.customerAccount === record.scope.customerAccount
27
+ );
28
+ });
29
+ if (!matched.length)
30
+ return candidates.length >= 3 ? { cutoff: 0, collection: null } : null;
31
+ if (
32
+ matched.length !== 1 ||
33
+ !matched[0].viewJson ||
34
+ matched[0].retiredAt !== undefined
35
+ )
36
+ return { cutoff: 0, collection: null };
37
+ const view = JSON.parse(matched[0].viewJson) as UsageSubscriptionView;
38
+ const original = view.bindings.find(
39
+ (item) =>
40
+ item.scope.meterId === record.scope.meterId &&
41
+ item.subscription.subscriptionItemId === subscription.subscriptionItemId,
42
+ );
43
+ if (
44
+ !view.collection ||
45
+ !original ||
46
+ view.status !== "active" ||
47
+ JSON.stringify(convexToJson(original.scope)) !==
48
+ JSON.stringify(convexToJson(record.scope)) ||
49
+ JSON.stringify(convexToJson(original.binding)) !==
50
+ JSON.stringify(convexToJson(record.binding)) ||
51
+ JSON.stringify(convexToJson(original.subscription)) !==
52
+ JSON.stringify(convexToJson(subscription))
53
+ )
54
+ return { cutoff: 0, collection: null };
55
+ return { cutoff: subscription.period.end - 60, collection: view.collection };
56
+ }
57
+
58
+ export async function managedBillingCutoff(
59
+ ctx: QueryCtx,
60
+ record: PreparedUsageRecord,
61
+ subscription: UsageSubscriptionBinding,
62
+ ): Promise<number | null> {
63
+ return (
64
+ (await managedBillingPolicy(ctx, record, subscription))?.cutoff ?? null
65
+ );
66
+ }
@@ -0,0 +1,33 @@
1
+ import { convexToJson } from "convex/values";
2
+ import { canonicalFingerprint } from "../operationEvidence/canonical.js";
3
+ import {
4
+ subscriptionScope,
5
+ subscriptionScopeSchema,
6
+ subscriptionTerms,
7
+ } from "../../client/usage/subscriptionTerms.js";
8
+ export function jsonTerms(json: string) {
9
+ if (new TextEncoder().encode(json).length > 32768)
10
+ throw new Error("Subscription terms exceed size limit");
11
+ const terms = subscriptionTerms(JSON.parse(json));
12
+ return {
13
+ terms,
14
+ termsJson: JSON.stringify(convexToJson(terms)),
15
+ scopeKey: JSON.stringify(subscriptionScope(terms)),
16
+ };
17
+ }
18
+ export async function intentKey(scope: unknown, requestId: string) {
19
+ if (!requestId || requestId.length > 100)
20
+ throw new Error("Invalid subscription request identity");
21
+ return canonicalFingerprint([
22
+ subscriptionScopeSchema.parse(scope),
23
+ requestId,
24
+ ]);
25
+ }
26
+ export function observationStart(startedAt: number) {
27
+ if (
28
+ !Number.isSafeInteger(startedAt) ||
29
+ startedAt < 0 ||
30
+ startedAt > Date.now() + 300000
31
+ )
32
+ throw new Error("Invalid subscription observation time");
33
+ }
@@ -0,0 +1,69 @@
1
+ import { convexTest } from "convex-test";
2
+ import { makeFunctionReference } from "convex/server";
3
+ import { expect, it } from "vitest";
4
+ import { schema, modules } from "../../test.js";
5
+ import {
6
+ request,
7
+ nativeSubscription,
8
+ } from "../../client/usage/subscription.fixtures.js";
9
+ const prepare = makeFunctionReference<"mutation">(
10
+ "usageSubscriptions/mutations:prepare",
11
+ ),
12
+ save = makeFunctionReference<"mutation">("usageSubscriptions/mutations:save"),
13
+ history = makeFunctionReference<"query">(
14
+ "usageSubscriptions/queries:history",
15
+ ),
16
+ get = makeFunctionReference<"query">("usageSubscriptions/queries:get");
17
+ it("retains original and renewed snapshots, deduplicates replay and keeps newer projections", async () => {
18
+ const t = convexTest(schema, modules),
19
+ now = Date.now();
20
+ const intent = await t.mutation(prepare, {
21
+ termsJson: JSON.stringify(request),
22
+ method: "direct",
23
+ });
24
+ const first = nativeSubscription(),
25
+ renewed = nativeSubscription();
26
+ renewed.items.data.forEach((item) => {
27
+ item.current_period_start = 1200;
28
+ item.current_period_end = 1800;
29
+ });
30
+ await t.mutation(save, {
31
+ key: intent.key,
32
+ nativeJson: JSON.stringify(renewed),
33
+ startedAt: now,
34
+ });
35
+ await t.mutation(save, {
36
+ key: intent.key,
37
+ nativeJson: JSON.stringify(first),
38
+ startedAt: now - 1,
39
+ });
40
+ await t.mutation(save, {
41
+ key: intent.key,
42
+ nativeJson: JSON.stringify(first),
43
+ startedAt: now - 1,
44
+ });
45
+ const scope = {
46
+ stripeAccountId: "acct_platform",
47
+ customerAccount: "acct_buyer",
48
+ livemode: false,
49
+ };
50
+ const projection = await t.query(get, { scope, requestId: "signup1" });
51
+ expect(
52
+ JSON.parse(projection.viewJson).bindings[0].subscription.period.start,
53
+ ).toBe(1200);
54
+ const page = await t.query(history, {
55
+ scope,
56
+ requestId: "signup1",
57
+ kind: "subscription",
58
+ paginationOpts: { numItems: 10, cursor: null },
59
+ });
60
+ expect(page.page).toHaveLength(2);
61
+ await expect(
62
+ t.query(history, {
63
+ scope: { ...scope, customerAccount: "acct_other" },
64
+ requestId: "signup1",
65
+ kind: "subscription",
66
+ paginationOpts: { numItems: 10, cursor: null },
67
+ }),
68
+ ).rejects.toThrow();
69
+ });
@@ -0,0 +1,68 @@
1
+ import type { MutationCtx } from "../_generated/server.js";
2
+ import type { Doc } from "../_generated/dataModel.js";
3
+ import { canonicalFingerprint } from "../operationEvidence/canonical.js";
4
+ import { jsonTerms } from "./helpers.js";
5
+ import { subscriptionView } from "../../client/usage/subscriptionTerms.js";
6
+ export async function appendSnapshot(
7
+ ctx: MutationCtx,
8
+ intent: Doc<"usageSubscriptionIntents">,
9
+ kind: "subscription" | "invoice" | "retirement",
10
+ resourceId: string,
11
+ value: import("convex/values").Value,
12
+ startedAt: number,
13
+ ) {
14
+ const fingerprint = await canonicalFingerprint([
15
+ intent.key,
16
+ kind,
17
+ resourceId,
18
+ value,
19
+ ]);
20
+ const prior = await ctx.db
21
+ .query("usageSubscriptionHistory")
22
+ .withIndex("by_fingerprint", (q) => q.eq("fingerprint", fingerprint))
23
+ .unique();
24
+ if (prior) return;
25
+ if ((intent.historyCount ?? 0) >= 100000)
26
+ throw new Error("Managed subscription history quota exhausted");
27
+ await ctx.db.insert("usageSubscriptionHistory", {
28
+ intentKey: intent.key,
29
+ kind,
30
+ resourceId,
31
+ fingerprint,
32
+ observationJson: JSON.stringify(value),
33
+ startedAt,
34
+ });
35
+ await ctx.db.patch("usageSubscriptionIntents", intent._id, {
36
+ historyCount: (intent.historyCount ?? 0) + 1,
37
+ });
38
+ }
39
+ export async function saveView(
40
+ ctx: MutationCtx,
41
+ intent: Doc<"usageSubscriptionIntents">,
42
+ nativeJson: string,
43
+ startedAt: number,
44
+ ) {
45
+ if (new TextEncoder().encode(nativeJson).length > 65536)
46
+ throw new Error("Subscription observation exceeds size limit");
47
+ const view = subscriptionView(
48
+ JSON.parse(nativeJson),
49
+ jsonTerms(intent.termsJson).terms,
50
+ );
51
+ if (intent.providerId && intent.providerId !== view.subscriptionId)
52
+ throw new Error("Native subscription identity conflict");
53
+ await appendSnapshot(
54
+ ctx,
55
+ intent,
56
+ "subscription",
57
+ view.subscriptionId,
58
+ view,
59
+ startedAt,
60
+ );
61
+ if ((intent.startedAt ?? -1) <= startedAt)
62
+ await ctx.db.patch("usageSubscriptionIntents", intent._id, {
63
+ providerId: view.subscriptionId,
64
+ viewJson: JSON.stringify(view),
65
+ startedAt,
66
+ });
67
+ return view;
68
+ }
@@ -0,0 +1,205 @@
1
+ import { convexTest } from "convex-test";
2
+ import { makeFunctionReference } from "convex/server";
3
+ import { expect, it } from "vitest";
4
+ import { schema, modules } from "../../test.js";
5
+ const prepare = makeFunctionReference<"mutation">(
6
+ "usageSubscriptions/mutations:prepare",
7
+ );
8
+ const get = makeFunctionReference<"query">("usageSubscriptions/queries:get");
9
+ const terms = {
10
+ requestId: "signup1",
11
+ fixedPriceIds: [],
12
+ collection: { method: "send_invoice", daysUntilDue: 30 },
13
+ meters: [
14
+ {
15
+ scope: {
16
+ stripeAccountId: "acct_platform",
17
+ customerAccount: "acct_buyer",
18
+ meterId: "mtr_calls",
19
+ livemode: false,
20
+ },
21
+ binding: {
22
+ stripeCustomerId: "cus_buyer",
23
+ stripePriceId: "price_calls",
24
+ eventName: "calls",
25
+ plan: {
26
+ key: "calls",
27
+ version: "v1",
28
+ model: "pay_as_you_go",
29
+ unit: { name: "call", precision: 0 },
30
+ rate: { currency: "usd", unitAmountDecimal: "2" },
31
+ },
32
+ },
33
+ },
34
+ ],
35
+ };
36
+ it("atomically reserves native customer/meter enrollment and conflicts on changed replay", async () => {
37
+ const t = convexTest(schema, modules);
38
+ const first = await t.mutation(prepare, {
39
+ termsJson: JSON.stringify(terms),
40
+ method: "direct",
41
+ });
42
+ const replay = await t.mutation(prepare, {
43
+ termsJson: JSON.stringify(terms),
44
+ method: "direct",
45
+ });
46
+ expect(replay.key).toBe(first.key);
47
+ await expect(
48
+ t.mutation(prepare, {
49
+ termsJson: JSON.stringify({ ...terms, requestId: "other" }),
50
+ method: "direct",
51
+ }),
52
+ ).rejects.toThrow(/enrollment/i);
53
+ await expect(
54
+ t.mutation(prepare, {
55
+ termsJson: JSON.stringify({ ...terms, fixedPriceIds: ["price_base"] }),
56
+ method: "direct",
57
+ }),
58
+ ).rejects.toThrow(/conflict/i);
59
+ const scope = {
60
+ stripeAccountId: "acct_platform",
61
+ customerAccount: "acct_buyer",
62
+ livemode: false,
63
+ };
64
+ expect(await t.query(get, { scope, requestId: "signup1" })).toMatchObject({
65
+ key: first.key,
66
+ });
67
+ expect(
68
+ await t.query(get, {
69
+ scope: { ...scope, customerAccount: "acct_other" },
70
+ requestId: "signup1",
71
+ }),
72
+ ).toBeNull();
73
+ });
74
+ it("keeps realm and mode independent while payer aliases cannot duplicate native billing", async () => {
75
+ const t = convexTest(schema, modules);
76
+ await t.mutation(prepare, {
77
+ termsJson: JSON.stringify(terms),
78
+ method: "direct",
79
+ });
80
+ const alias = structuredClone(terms);
81
+ alias.meters[0].scope.customerAccount = "acct_alias";
82
+ await expect(
83
+ t.mutation(prepare, { termsJson: JSON.stringify(alias), method: "direct" }),
84
+ ).rejects.toThrow(/enrollment/i);
85
+ const live = structuredClone(terms);
86
+ live.meters[0].scope.livemode = true;
87
+ expect(
88
+ await t.mutation(prepare, {
89
+ termsJson: JSON.stringify(live),
90
+ method: "direct",
91
+ }),
92
+ ).toHaveProperty("key");
93
+ });
94
+
95
+ it("serializes period-end cancellation commands and rejects changed command replays", async () => {
96
+ const t = convexTest(schema, modules);
97
+ const row = await t.mutation(prepare, {
98
+ termsJson: JSON.stringify(terms),
99
+ method: "direct",
100
+ });
101
+ await t.run(async (ctx) => {
102
+ const doc = await ctx.db
103
+ .query("usageSubscriptionIntents")
104
+ .withIndex("by_key", (q) => q.eq("key", row.key))
105
+ .unique();
106
+ await ctx.db.patch("usageSubscriptionIntents", doc!._id, {
107
+ providerId: "sub_calls",
108
+ });
109
+ });
110
+ const command = makeFunctionReference<"mutation">(
111
+ "usageSubscriptions/mutations:prepareCancellation",
112
+ );
113
+ const args = {
114
+ key: row.key,
115
+ operationId: "cancel1",
116
+ cancelAtPeriodEnd: true,
117
+ };
118
+ const first = await t.mutation(command, args);
119
+ expect((await t.mutation(command, args)).key).toBe(first.key);
120
+ await expect(
121
+ t.mutation(command, { ...args, cancelAtPeriodEnd: false }),
122
+ ).rejects.toThrow(/conflict/i);
123
+ await expect(
124
+ t.mutation(command, {
125
+ ...args,
126
+ operationId: "reactivate2",
127
+ cancelAtPeriodEnd: false,
128
+ }),
129
+ ).rejects.toThrow(/pending/i);
130
+ });
131
+
132
+ const close = makeFunctionReference<"mutation">(
133
+ "accountClosure/mutations:prepare",
134
+ );
135
+ it("blocks payer and billing-realm closure while an enrollment owns usage locks, including closure retries", async () => {
136
+ const t = convexTest(schema, modules);
137
+ await t.mutation(prepare, {
138
+ termsJson: JSON.stringify(terms),
139
+ method: "direct",
140
+ });
141
+ for (const stripeAccountId of ["acct_buyer", "acct_platform"]) {
142
+ await expect(t.mutation(close, { stripeAccountId })).rejects.toThrow(
143
+ /managed usage/i,
144
+ );
145
+ await t.run(async (ctx) => {
146
+ await ctx.db.insert("accountClosures", {
147
+ stripeAccountId,
148
+ state: "pending",
149
+ });
150
+ });
151
+ await expect(t.mutation(close, { stripeAccountId })).rejects.toThrow(
152
+ /managed usage/i,
153
+ );
154
+ }
155
+ });
156
+
157
+ it("blocks new and replayed signup after payer or realm closure preparation", async () => {
158
+ for (const stripeAccountId of ["acct_buyer", "acct_platform"]) {
159
+ for (const state of ["pending", "closed"] as const) {
160
+ const t = convexTest(schema, modules);
161
+ await t.run(async (ctx) => {
162
+ await ctx.db.insert("accountClosures", { stripeAccountId, state });
163
+ });
164
+ await expect(
165
+ t.mutation(prepare, {
166
+ termsJson: JSON.stringify(terms),
167
+ method: "direct",
168
+ }),
169
+ ).rejects.toThrow(/account closure/i);
170
+ }
171
+ }
172
+ const t = convexTest(schema, modules);
173
+ await t.mutation(prepare, {
174
+ termsJson: JSON.stringify(terms),
175
+ method: "direct",
176
+ });
177
+ await t.run(async (ctx) => {
178
+ await ctx.db.insert("accountClosures", {
179
+ stripeAccountId: "acct_buyer",
180
+ state: "pending",
181
+ });
182
+ });
183
+ await expect(
184
+ t.mutation(prepare, { termsJson: JSON.stringify(terms), method: "direct" }),
185
+ ).rejects.toThrow(/account closure/i);
186
+ });
187
+
188
+ it("allows closure after retirement releases enrollment locks and keeps unrelated accounts independent", async () => {
189
+ const t = convexTest(schema, modules);
190
+ await t.mutation(prepare, {
191
+ termsJson: JSON.stringify(terms),
192
+ method: "direct",
193
+ });
194
+ expect(
195
+ await t.mutation(close, { stripeAccountId: "acct_unrelated" }),
196
+ ).toHaveProperty("closure");
197
+ await t.run(async (ctx) => {
198
+ for (const lock of await ctx.db.query("usageSubscriptionLocks").collect()) {
199
+ await ctx.db.delete("usageSubscriptionLocks", lock._id);
200
+ }
201
+ });
202
+ expect(
203
+ await t.mutation(close, { stripeAccountId: "acct_buyer" }),
204
+ ).toHaveProperty("closure");
205
+ });