@ultimabase/stripe 0.0.0-first.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 (130) hide show
  1. package/README.md +7 -0
  2. package/dist/accounts.d.ts +9 -0
  3. package/dist/accounts.d.ts.map +1 -0
  4. package/dist/accounts.js +20 -0
  5. package/dist/apply.d.ts +26 -0
  6. package/dist/apply.d.ts.map +1 -0
  7. package/dist/apply.js +73 -0
  8. package/dist/audit.d.ts +3 -0
  9. package/dist/audit.d.ts.map +1 -0
  10. package/dist/audit.js +123 -0
  11. package/dist/billing-gateway.d.ts +158 -0
  12. package/dist/billing-gateway.d.ts.map +1 -0
  13. package/dist/billing-gateway.js +23 -0
  14. package/dist/billing.d.ts +130 -0
  15. package/dist/billing.d.ts.map +1 -0
  16. package/dist/billing.js +128 -0
  17. package/dist/calls.d.ts +61 -0
  18. package/dist/calls.d.ts.map +1 -0
  19. package/dist/calls.js +172 -0
  20. package/dist/catalog.d.ts +54 -0
  21. package/dist/catalog.d.ts.map +1 -0
  22. package/dist/catalog.js +182 -0
  23. package/dist/credit.d.ts +16 -0
  24. package/dist/credit.d.ts.map +1 -0
  25. package/dist/credit.js +18 -0
  26. package/dist/credits.d.ts +38 -0
  27. package/dist/credits.d.ts.map +1 -0
  28. package/dist/credits.js +138 -0
  29. package/dist/customer.d.ts +25 -0
  30. package/dist/customer.d.ts.map +1 -0
  31. package/dist/customer.js +88 -0
  32. package/dist/describe.d.ts +4 -0
  33. package/dist/describe.d.ts.map +1 -0
  34. package/dist/describe.js +56 -0
  35. package/dist/duplicates.d.ts +12 -0
  36. package/dist/duplicates.d.ts.map +1 -0
  37. package/dist/duplicates.js +24 -0
  38. package/dist/fake-billing.d.ts +72 -0
  39. package/dist/fake-billing.d.ts.map +1 -0
  40. package/dist/fake-billing.js +290 -0
  41. package/dist/gateway.d.ts +108 -0
  42. package/dist/gateway.d.ts.map +1 -0
  43. package/dist/gateway.js +196 -0
  44. package/dist/index.d.ts +15 -0
  45. package/dist/index.d.ts.map +1 -0
  46. package/dist/index.js +6 -0
  47. package/dist/job-input.d.ts +6 -0
  48. package/dist/job-input.d.ts.map +1 -0
  49. package/dist/job-input.js +20 -0
  50. package/dist/jobs.d.ts +16 -0
  51. package/dist/jobs.d.ts.map +1 -0
  52. package/dist/jobs.js +189 -0
  53. package/dist/keys.d.ts +10 -0
  54. package/dist/keys.d.ts.map +1 -0
  55. package/dist/keys.js +30 -0
  56. package/dist/kinds.d.ts +11 -0
  57. package/dist/kinds.d.ts.map +1 -0
  58. package/dist/kinds.js +4 -0
  59. package/dist/models.d.ts +71 -0
  60. package/dist/models.d.ts.map +1 -0
  61. package/dist/models.js +41 -0
  62. package/dist/plugin.d.ts +41 -0
  63. package/dist/plugin.d.ts.map +1 -0
  64. package/dist/plugin.js +229 -0
  65. package/dist/portal.d.ts +23 -0
  66. package/dist/portal.d.ts.map +1 -0
  67. package/dist/portal.js +66 -0
  68. package/dist/product.d.ts +57 -0
  69. package/dist/product.d.ts.map +1 -0
  70. package/dist/product.js +113 -0
  71. package/dist/running.d.ts +61 -0
  72. package/dist/running.d.ts.map +1 -0
  73. package/dist/running.js +35 -0
  74. package/dist/sdk-billing.d.ts +8 -0
  75. package/dist/sdk-billing.d.ts.map +1 -0
  76. package/dist/sdk-billing.js +200 -0
  77. package/dist/sdk-common.d.ts +13 -0
  78. package/dist/sdk-common.d.ts.map +1 -0
  79. package/dist/sdk-common.js +41 -0
  80. package/dist/sdk-customer.d.ts +9 -0
  81. package/dist/sdk-customer.d.ts.map +1 -0
  82. package/dist/sdk-customer.js +149 -0
  83. package/dist/sdk-invoices.d.ts +10 -0
  84. package/dist/sdk-invoices.d.ts.map +1 -0
  85. package/dist/sdk-invoices.js +53 -0
  86. package/dist/sdk-recovery.d.ts +5 -0
  87. package/dist/sdk-recovery.d.ts.map +1 -0
  88. package/dist/sdk-recovery.js +81 -0
  89. package/dist/sync.d.ts +8 -0
  90. package/dist/sync.d.ts.map +1 -0
  91. package/dist/sync.js +196 -0
  92. package/dist/testing.d.ts +24 -0
  93. package/dist/testing.d.ts.map +1 -0
  94. package/dist/testing.js +100 -0
  95. package/dist/webhook.d.ts +4 -0
  96. package/dist/webhook.d.ts.map +1 -0
  97. package/dist/webhook.js +73 -0
  98. package/package.json +51 -0
  99. package/src/accounts.ts +30 -0
  100. package/src/apply.ts +99 -0
  101. package/src/audit.ts +171 -0
  102. package/src/billing-gateway.ts +188 -0
  103. package/src/billing.ts +361 -0
  104. package/src/calls.ts +280 -0
  105. package/src/catalog.ts +327 -0
  106. package/src/credit.ts +36 -0
  107. package/src/credits.ts +206 -0
  108. package/src/customer.ts +113 -0
  109. package/src/describe.ts +76 -0
  110. package/src/duplicates.ts +45 -0
  111. package/src/fake-billing.ts +388 -0
  112. package/src/gateway.ts +333 -0
  113. package/src/index.ts +35 -0
  114. package/src/job-input.ts +24 -0
  115. package/src/jobs.ts +230 -0
  116. package/src/keys.ts +40 -0
  117. package/src/kinds.ts +15 -0
  118. package/src/models.ts +107 -0
  119. package/src/plugin.ts +307 -0
  120. package/src/portal.ts +95 -0
  121. package/src/product.ts +203 -0
  122. package/src/running.ts +104 -0
  123. package/src/sdk-billing.ts +220 -0
  124. package/src/sdk-common.ts +57 -0
  125. package/src/sdk-customer.ts +203 -0
  126. package/src/sdk-invoices.ts +81 -0
  127. package/src/sdk-recovery.ts +93 -0
  128. package/src/sync.ts +246 -0
  129. package/src/testing.ts +135 -0
  130. package/src/webhook.ts +100 -0
package/src/gateway.ts ADDED
@@ -0,0 +1,333 @@
1
+ // Stripe, behind the narrow gateway the plugin calls. `sdkGateway` reaches
2
+ // Stripe through its SDK; `@ultimabase/stripe/testing` holds a fake in
3
+ // memory, and no test of `yarn validate` reaches Stripe.
4
+ import { Stripe } from 'stripe'
5
+ import type { Every } from './product.ts'
6
+ import { all } from './sdk-common.ts'
7
+
8
+ /** How often a price bills: Stripe's `interval` and `interval_count`. */
9
+ export interface Recurring<E extends string = string> {
10
+ readonly every: E
11
+ readonly count: number
12
+ }
13
+
14
+ /** A product the catalog manages, as Stripe holds it. */
15
+ export interface StripeProduct {
16
+ readonly id: string
17
+ /** Its `metadata.key`. */
18
+ readonly key: string | null
19
+ readonly name: string
20
+ readonly active: boolean
21
+ readonly taxCode: string | null
22
+ }
23
+
24
+ /** A price, as Stripe holds it. */
25
+ export interface StripePrice {
26
+ readonly id: string
27
+ readonly productId: string
28
+ readonly lookupKey: string | null
29
+ readonly amount: number | null
30
+ readonly currency: string
31
+ /** `null` for a one-time price. */
32
+ readonly recurring: Recurring | null
33
+ readonly taxBehavior: string | null
34
+ readonly nickname: string | null
35
+ readonly active: boolean
36
+ readonly metadata: Readonly<Record<string, string>>
37
+ }
38
+
39
+ /** A product the portal lets a subscription move to, with its prices. */
40
+ export interface PortalProduct {
41
+ readonly productId: string
42
+ readonly priceIds: readonly string[]
43
+ }
44
+
45
+ /** The customer portal's configuration, as the catalog writes it. */
46
+ export interface PortalSettings {
47
+ readonly returnUrl: string | null
48
+ readonly termsUrl: string | null
49
+ readonly privacyUrl: string | null
50
+ /** `always_invoice` or `create_prorations`. */
51
+ readonly prorationBehavior: string
52
+ /** Whether a downgrade waits for the period's end. */
53
+ readonly scheduleAtPeriodEnd: readonly string[]
54
+ /** `end_trial` or `continue_trial`. */
55
+ readonly trialUpdate: string
56
+ /** `at_period_end` or `immediately`. */
57
+ readonly cancelMode: string
58
+ /** `null` when Stripe did not list them. */
59
+ readonly products: readonly PortalProduct[] | null
60
+ readonly active: boolean
61
+ }
62
+
63
+ /** What Stripe holds of the catalog. */
64
+ export interface CatalogState {
65
+ /** The managed products, archived ones included. */
66
+ readonly products: readonly StripeProduct[]
67
+ /** Every price, archived ones included. */
68
+ readonly prices: readonly StripePrice[]
69
+ /** The managed portal configuration, if one was saved. */
70
+ readonly portal: {
71
+ readonly id: string
72
+ readonly settings: PortalSettings
73
+ } | null
74
+ }
75
+
76
+ /** A product as the catalog writes it. */
77
+ export interface ProductWrite {
78
+ readonly key: string
79
+ readonly name: string
80
+ readonly taxCode: string | null
81
+ }
82
+
83
+ /** A price as the catalog writes it: Stripe never changes its billing. */
84
+ export interface PriceWrite {
85
+ readonly productId: string
86
+ readonly lookupKey: string
87
+ readonly amount: number
88
+ readonly currency: string
89
+ /** `null` for a one-time price. */
90
+ readonly recurring: Recurring<Every> | null
91
+ readonly taxBehavior: 'inclusive' | 'exclusive'
92
+ readonly nickname: string
93
+ readonly metadata: Readonly<Record<string, string>>
94
+ }
95
+
96
+ /** What the plugin asks Stripe. */
97
+ export interface StripeGateway {
98
+ /** The managed products, every price, and the managed portal. */
99
+ readonly readCatalog: () => Promise<CatalogState>
100
+ /** Creates a managed product; returns its id. */
101
+ readonly createProduct: (product: ProductWrite) => Promise<string>
102
+ /** Renames a product, sets its tax code, and makes it active. */
103
+ readonly updateProduct: (id: string, product: ProductWrite) => Promise<void>
104
+ readonly archiveProduct: (id: string) => Promise<void>
105
+ /** Creates a price, which takes its lookup key over; returns its id. */
106
+ readonly createPrice: (price: PriceWrite) => Promise<string>
107
+ /** Sets a price's nickname and metadata. */
108
+ readonly updatePrice: (
109
+ id: string,
110
+ price: Pick<PriceWrite, 'nickname' | 'metadata'>,
111
+ ) => Promise<void>
112
+ readonly archivePrice: (id: string) => Promise<void>
113
+ /** Creates the portal configuration, or updates `id`; returns its id. */
114
+ readonly savePortal: (
115
+ id: string | null,
116
+ settings: PortalSettings,
117
+ ) => Promise<string>
118
+ }
119
+
120
+ /** `metadata.managedBy` of what the catalog writes: nothing else is touched. */
121
+ export const managedBy = 'ultimabase'
122
+
123
+ /** The API version the plugin reads Stripe's objects with: the SDK's. */
124
+ const apiVersion = '2026-10-28.endive'
125
+
126
+ /** The Stripe client of a secret key. */
127
+ export const stripeClient = (secret: string): Stripe =>
128
+ new Stripe(secret, {
129
+ apiVersion,
130
+ maxNetworkRetries: 2,
131
+ // A request past 10 s fails, and its caller retries.
132
+ timeout: 10_000,
133
+ })
134
+
135
+ const idOf = (value: string | { readonly id: string }): string =>
136
+ typeof value === 'string' ? value : value.id
137
+
138
+ const priceOf = (price: Stripe.Price): StripePrice => ({
139
+ id: price.id,
140
+ productId: idOf(price.product),
141
+ lookupKey: price.lookup_key,
142
+ amount: price.unit_amount,
143
+ currency: price.currency,
144
+ recurring:
145
+ price.recurring === null
146
+ ? null
147
+ : {
148
+ every: price.recurring.interval,
149
+ count: price.recurring.interval_count,
150
+ },
151
+ taxBehavior: price.tax_behavior,
152
+ nickname: price.nickname,
153
+ active: price.active,
154
+ metadata: price.metadata,
155
+ })
156
+
157
+ const portalOf = (
158
+ portal: Stripe.BillingPortal.Configuration,
159
+ ): PortalSettings => {
160
+ const update = portal.features.subscription_update
161
+ return {
162
+ returnUrl: portal.default_return_url,
163
+ termsUrl: portal.business_profile.terms_of_service_url,
164
+ privacyUrl: portal.business_profile.privacy_policy_url,
165
+ prorationBehavior: update.proration_behavior,
166
+ scheduleAtPeriodEnd: update.schedule_at_period_end.conditions.map(
167
+ ({ type }) => type,
168
+ ),
169
+ trialUpdate: update.trial_update_behavior,
170
+ cancelMode: portal.features.subscription_cancel.mode,
171
+ products:
172
+ update.products?.map(({ product, prices }) => ({
173
+ productId: product,
174
+ priceIds: prices,
175
+ })) ?? null,
176
+ active: portal.active,
177
+ }
178
+ }
179
+
180
+ /** The configuration's parameters, from `settings`. */
181
+ export const portalParams = (
182
+ settings: PortalSettings,
183
+ ): Stripe.BillingPortal.ConfigurationCreateParams => {
184
+ const products = settings.products ?? []
185
+ return {
186
+ business_profile: {
187
+ ...(settings.termsUrl !== null && {
188
+ terms_of_service_url: settings.termsUrl,
189
+ }),
190
+ ...(settings.privacyUrl !== null && {
191
+ privacy_policy_url: settings.privacyUrl,
192
+ }),
193
+ },
194
+ ...(settings.returnUrl !== null && {
195
+ default_return_url: settings.returnUrl,
196
+ }),
197
+ features: {
198
+ subscription_update: {
199
+ // The portal refuses an update with no product to move to.
200
+ enabled: products.length > 0,
201
+ default_allowed_updates: ['price'],
202
+ products: products.map(({ productId, priceIds }) => ({
203
+ product: productId,
204
+ prices: [...priceIds],
205
+ })),
206
+ proration_behavior: settings.prorationBehavior,
207
+ trial_update_behavior: settings.trialUpdate,
208
+ schedule_at_period_end: {
209
+ conditions: settings.scheduleAtPeriodEnd.map((type) => ({ type })),
210
+ },
211
+ },
212
+ subscription_cancel: {
213
+ enabled: true,
214
+ mode: settings.cancelMode,
215
+ },
216
+ payment_method_update: { enabled: true },
217
+ invoice_history: { enabled: true },
218
+ },
219
+ metadata: { managedBy },
220
+ }
221
+ }
222
+
223
+ /** The gateway over Stripe's API. */
224
+ export const sdkGateway = (client: Stripe): StripeGateway => ({
225
+ readCatalog: async () => {
226
+ // Three lists, whatever the catalog's size.
227
+ const [products, prices, portals] = await Promise.all([
228
+ all(client.products.list({ limit: 100 })),
229
+ all(client.prices.list({ limit: 100 })),
230
+ all(
231
+ client.billingPortal.configurations.list({
232
+ limit: 100,
233
+ expand: ['data.features.subscription_update.products'],
234
+ }),
235
+ ),
236
+ ])
237
+ const portal = portals.find(
238
+ ({ metadata }) => metadata?.['managedBy'] === managedBy,
239
+ )
240
+ return {
241
+ products: products
242
+ .filter(({ metadata }) => metadata['managedBy'] === managedBy)
243
+ .map((product) => ({
244
+ id: product.id,
245
+ key: product.metadata['key'] ?? null,
246
+ name: product.name,
247
+ active: product.active,
248
+ taxCode:
249
+ product.tax_code === null || product.tax_code === undefined
250
+ ? null
251
+ : idOf(product.tax_code),
252
+ })),
253
+ prices: prices.map(priceOf),
254
+ portal:
255
+ portal === undefined
256
+ ? null
257
+ : { id: portal.id, settings: portalOf(portal) },
258
+ }
259
+ },
260
+ createProduct: async ({ key, name, taxCode }) => {
261
+ const created = await client.products.create({
262
+ name,
263
+ ...(taxCode !== null && { tax_code: taxCode }),
264
+ metadata: { managedBy, key },
265
+ })
266
+ return created.id
267
+ },
268
+ updateProduct: async (id, { key, name, taxCode }) => {
269
+ await client.products.update(id, {
270
+ name,
271
+ active: true,
272
+ // An empty string unsets it.
273
+ tax_code: taxCode ?? '',
274
+ metadata: { managedBy, key },
275
+ })
276
+ },
277
+ archiveProduct: async (id) => {
278
+ await client.products.update(id, { active: false })
279
+ },
280
+ createPrice: async (price) => {
281
+ const created = await client.prices.create({
282
+ product: price.productId,
283
+ currency: price.currency,
284
+ unit_amount: price.amount,
285
+ ...(price.recurring !== null && {
286
+ recurring: {
287
+ interval: price.recurring.every,
288
+ interval_count: price.recurring.count,
289
+ },
290
+ }),
291
+ tax_behavior: price.taxBehavior,
292
+ lookup_key: price.lookupKey,
293
+ transfer_lookup_key: true,
294
+ nickname: price.nickname,
295
+ metadata: { ...price.metadata },
296
+ })
297
+ return created.id
298
+ },
299
+ updatePrice: async (id, { nickname, metadata }) => {
300
+ await client.prices.update(id, { nickname, metadata: { ...metadata } })
301
+ },
302
+ archivePrice: async (id) => {
303
+ await client.prices.update(id, { active: false })
304
+ },
305
+ savePortal: async (id, settings) => {
306
+ const params = portalParams(settings)
307
+ if (id === null) {
308
+ return (await client.billingPortal.configurations.create(params)).id
309
+ }
310
+ // Stripe drops an empty list or an absent key, keeping the old value:
311
+ // an update clears a setting with an empty string.
312
+ const { subscription_update: update } = params.features
313
+ const conditions = update?.schedule_at_period_end?.conditions ?? []
314
+ await client.billingPortal.configurations.update(id, {
315
+ ...params,
316
+ business_profile: {
317
+ terms_of_service_url: settings.termsUrl ?? '',
318
+ privacy_policy_url: settings.privacyUrl ?? '',
319
+ },
320
+ features: {
321
+ ...params.features,
322
+ subscription_update: {
323
+ ...update,
324
+ schedule_at_period_end: {
325
+ conditions: conditions.length > 0 ? conditions : '',
326
+ },
327
+ },
328
+ },
329
+ active: true,
330
+ })
331
+ return id
332
+ },
333
+ })
package/src/index.ts ADDED
@@ -0,0 +1,35 @@
1
+ // @ultimabase/stripe (D-371): what an application sells, declared in code
2
+ // (D-372), sold on Stripe's hosted pages, and kept in the application's own
3
+ // models (D-373), credits included (D-374).
4
+ export type { StripeCatalogOptions } from './apply.ts'
5
+ export { applyStripeCatalog } from './apply.ts'
6
+ export type {
7
+ BalanceFields,
8
+ CreditHistoryFields,
9
+ PurchaseFields,
10
+ SubscriptionFields,
11
+ WithStripe,
12
+ } from './billing.ts'
13
+ export {
14
+ defineBalance,
15
+ defineCreditHistory,
16
+ definePurchase,
17
+ defineSubscription,
18
+ } from './billing.ts'
19
+ export type { CustomerProfile } from './billing-gateway.ts'
20
+ export type { CheckoutArgs, PortalArgs } from './calls.ts'
21
+ export { stripe } from './calls.ts'
22
+ export type { Credit, CreditAmount } from './credit.ts'
23
+ export { defineCredit } from './credit.ts'
24
+ export type { Stripe, StripeOptions } from './plugin.ts'
25
+ export { stripePlugin } from './plugin.ts'
26
+ export type { PortalOptions } from './portal.ts'
27
+ export type {
28
+ Every,
29
+ OneTimePrice,
30
+ OneTimeProduct,
31
+ Product,
32
+ RecurringPrice,
33
+ SubscriptionProduct,
34
+ } from './product.ts'
35
+ export { defineProduct } from './product.ts'
@@ -0,0 +1,24 @@
1
+ // The plugin's jobs' inputs, checked as `@ultimabase/jobs` asks.
2
+ import type { StandardSchema } from '@ultimabase/jobs'
3
+
4
+ /** A job's input: an object of the strings `keys` names. */
5
+ export function strings<const K extends string>(
6
+ ...keys: K[]
7
+ ): StandardSchema<{ readonly [P in K]: string }> {
8
+ const message = `An object of strings: ${keys.join(', ')}.`
9
+ return {
10
+ '~standard': {
11
+ version: 1,
12
+ vendor: 'ultimabase-stripe',
13
+ validate: (value: unknown) => {
14
+ const read: Record<string, string> = {}
15
+ for (const key of keys) {
16
+ const field: unknown = Reflect.get(Object(value), key)
17
+ if (typeof field !== 'string') return { issues: [{ message }] }
18
+ read[key] = field
19
+ }
20
+ return { value: read }
21
+ },
22
+ },
23
+ }
24
+ }
package/src/jobs.ts ADDED
@@ -0,0 +1,230 @@
1
+ // The plugin's jobs (D-371 point 5, D-375), named `stripe.*`: an event's
2
+ // sync, a customer's sync and close, a second subscription's refund, and the
3
+ // hourly reconciliation, which catches what a lost webhook or a failed job
4
+ // left behind.
5
+ import type { Job, RecurringJob } from '@ultimabase/jobs'
6
+ import { defineJob } from '@ultimabase/jobs'
7
+ import { auditJob } from './audit.ts'
8
+ import type { Customer } from './customer.ts'
9
+ import { locked } from './customer.ts'
10
+ import { strings } from './job-input.ts'
11
+ import type { RecoveryGateway } from './billing-gateway.ts'
12
+ import { duplicateJob } from './duplicates.ts'
13
+ import { M, StripeCustomer, StripeEvent, StripeScan } from './models.ts'
14
+ import type { Rows, Running } from './running.ts'
15
+ import { runningOf, stripeOf } from './running.ts'
16
+ import { syncCustomer } from './sync.ts'
17
+
18
+ const minute = 60 * 1000
19
+ const hour = 60 * minute
20
+ /**
21
+ * How long a processed event stays: longer than Stripe retries a delivery
22
+ * (3 days), so a late one is still stored once.
23
+ */
24
+ const keepEvents = 90 * 24 * hour
25
+ /** The customers the reconciliation reads at once. */
26
+ const page = 500
27
+ /** The events a first scan reads back. */
28
+ const firstScan = 24 * hour
29
+ /** How far a scan reads again before the last one's end: Stripe lists late. */
30
+ const overlap = 10 * minute
31
+ /**
32
+ * A sync that began this long after a customer's last event read it: the
33
+ * margin covers the clocks' gap.
34
+ */
35
+ const margin = minute
36
+
37
+ /** Syncs the customer a stored event is about, then marks it processed. */
38
+ export const eventJob: Job<'stripe.event', { readonly event: string }> =
39
+ defineJob({
40
+ name: 'stripe.event',
41
+ input: strings('event'),
42
+ key: ({ event }) => event,
43
+ run: async ({ input }) => {
44
+ const event = await StripeEvent.findUnique(
45
+ { where: { id: input.event } },
46
+ M,
47
+ )
48
+ if (event === null || event.processedAt !== null) return
49
+ const { gateway } = stripeOf('stripe.event')
50
+ const customerId = await gateway.customerOf(
51
+ event.objectType,
52
+ event.objectId,
53
+ )
54
+ const where = { stripeId: customerId }
55
+ const row =
56
+ customerId === null
57
+ ? null
58
+ : await StripeCustomer.findUnique({ where }, M)
59
+ // Synced here: the event stays waiting, so retried, until it is.
60
+ if (row !== null) await syncCustomer(row.id)
61
+ const data = { processedAt: new Date() }
62
+ await StripeEvent.update({ where: { id: event.id }, data }, M)
63
+ },
64
+ })
65
+
66
+ /** Syncs one customer, which the reconciliation found stale. */
67
+ const syncJob = defineJob({
68
+ name: 'stripe.sync',
69
+ input: strings('customer'),
70
+ key: ({ customer }) => customer,
71
+ run: async ({ input }) => {
72
+ await syncCustomer(input.customer)
73
+ },
74
+ })
75
+
76
+ /** The queries of each payer model, by name. */
77
+ const payersOf = (running: Running): ReadonlyMap<string, Rows> =>
78
+ new Map(
79
+ [running.subscription, running.purchase, running.balance].flatMap(
80
+ (billing) =>
81
+ billing === undefined
82
+ ? []
83
+ : [[billing.payer.name, billing.payer.queries] as const],
84
+ ),
85
+ )
86
+
87
+ /**
88
+ * Closes the customer of a deleted payer: Stripe deletes it, which ends its
89
+ * subscriptions, and its row goes. A payer still there keeps it.
90
+ */
91
+ export const closeJob: Job<
92
+ 'stripe.close',
93
+ { readonly model: string; readonly payer: string }
94
+ > = defineJob({
95
+ name: 'stripe.close',
96
+ input: strings('model', 'payer'),
97
+ key: ({ model, payer }) => `${model}:${payer}`,
98
+ run: async ({ input, logger }) => {
99
+ const running = runningOf('stripe.close')
100
+ const { gateway } = stripeOf('stripe.close')
101
+ const payers = payersOf(running).get(input.model)
102
+ if (payers === undefined) {
103
+ logger.warn(input, 'No billing model names this payer model.')
104
+ return
105
+ }
106
+ const where = { id: input.payer }
107
+ if ((await payers.findUnique({ where }, M)) !== null) return
108
+ const held = await StripeCustomer.findUnique({ where: input }, M)
109
+ if (held === null) return
110
+ await locked(held.id, async (row: Customer) => {
111
+ if (row.stripeId !== null) await gateway.deleteCustomer(row.stripeId)
112
+ await StripeCustomer.delete({ where: { id: row.id } }, M)
113
+ })
114
+ },
115
+ })
116
+
117
+ /** Whether a customer's payer is gone, by its model's queries. */
118
+ async function goneOf(
119
+ running: Running,
120
+ rows: readonly Customer[],
121
+ ): Promise<Set<string>> {
122
+ const payers = payersOf(running)
123
+ const gone = new Set<string>()
124
+ for (const [model, held] of Map.groupBy(rows, (row) => row.model)) {
125
+ const queries = payers.get(model)
126
+ if (queries === undefined) continue
127
+ const ids = held.map(({ payer }) => payer)
128
+ const args = { where: { id: { in: ids } }, select: { id: true } }
129
+ const found = new Set((await queries.findMany(args, M)).map((r) => r.id))
130
+ for (const row of held) if (!found.has(row.payer)) gone.add(row.id)
131
+ }
132
+ return gone
133
+ }
134
+
135
+ /** Whether the customer needs a sync: its period ended since the last one. */
136
+ const stale = (row: Customer, now: number): boolean =>
137
+ row.stripeId !== null &&
138
+ row.renewsAt !== null &&
139
+ row.renewsAt.getTime() <= now
140
+
141
+ /**
142
+ * Closes the customers of deleted payers, and syncs those whose period
143
+ * ended: a renewal whose events were lost. Pages by id from a cursor; a
144
+ * cursor row deleted meanwhile ends the scan, and the next hour reads on.
145
+ */
146
+ async function scanCustomers(running: Running, now: number): Promise<void> {
147
+ const gone: { readonly model: string; readonly payer: string }[] = []
148
+ for (let cursor: string | undefined; ;) {
149
+ const rows = await StripeCustomer.findMany(
150
+ {
151
+ orderBy: { id: 'asc' },
152
+ take: page,
153
+ ...(cursor === undefined ? {} : { cursor: { id: cursor }, skip: 1 }),
154
+ },
155
+ M,
156
+ )
157
+ const goneIds = await goneOf(running, rows)
158
+ for (const row of rows) {
159
+ if (goneIds.has(row.id)) gone.push(row)
160
+ else if (stale(row, now)) await syncJob.enqueue({ customer: row.id })
161
+ }
162
+ cursor = rows.at(-1)?.id
163
+ if (rows.length < page) break
164
+ }
165
+ // Closed once the scan ends, so that no close deletes its cursor row.
166
+ for (const { model, payer } of gone) await closeJob.enqueue({ model, payer })
167
+ }
168
+
169
+ /**
170
+ * Syncs the customers Stripe's events changed since the last scan and that
171
+ * no sync read since: what a lost webhook missed (D-375). Its cost follows
172
+ * the account's activity, not its number of customers.
173
+ */
174
+ async function scanEvents(
175
+ gateway: RecoveryGateway,
176
+ now: number,
177
+ ): Promise<void> {
178
+ const where = { name: 'events' }
179
+ const last = await StripeScan.findUnique({ where }, M)
180
+ const since = (last?.until.getTime() ?? now - firstScan) - overlap
181
+ const changed = await gateway.changedSince(new Date(since))
182
+ const ids = [...changed.keys()]
183
+ for (let at = 0; at < ids.length; at += page) {
184
+ const stripeId = { in: ids.slice(at, at + page) }
185
+ const rows = await StripeCustomer.findMany({ where: { stripeId } }, M)
186
+ for (const row of rows) {
187
+ const event = changed.get(row.stripeId ?? '')?.getTime() ?? now
188
+ if (row.syncedAt === null || row.syncedAt.getTime() < event + margin) {
189
+ await syncJob.enqueue({ customer: row.id })
190
+ }
191
+ }
192
+ }
193
+ const until = new Date(now)
194
+ await StripeScan.upsert(
195
+ { where, create: { ...where, until }, update: { until } },
196
+ M,
197
+ )
198
+ }
199
+
200
+ /**
201
+ * Every hour: closes the customers of deleted payers, syncs those past a
202
+ * renewal, enqueues the events still waiting, deletes the old processed
203
+ * ones, then syncs the customers whose events were lost.
204
+ */
205
+ async function reconcile(): Promise<void> {
206
+ const running = runningOf('stripe.reconcile')
207
+ if (running.stripe === undefined) return
208
+ const now = Date.now()
209
+ await scanCustomers(running, now)
210
+ const waiting = await StripeEvent.findMany(
211
+ { where: { processedAt: null }, select: { id: true } },
212
+ M,
213
+ )
214
+ for (const { id } of waiting) await eventJob.enqueue({ event: id })
215
+ const old = new Date(now - keepEvents)
216
+ await StripeEvent.deleteMany({ where: { processedAt: { lt: old } } }, M)
217
+ // Last, so that an unreachable Stripe leaves the rest done.
218
+ await scanEvents(running.stripe.gateway, now)
219
+ }
220
+
221
+ const reconcileJob: RecurringJob<'stripe.reconcile'> = defineJob({
222
+ name: 'stripe.reconcile',
223
+ every: hour,
224
+ run: reconcile,
225
+ })
226
+
227
+ /** The jobs the plugin adds (D-369). */
228
+ export const stripeJobs: readonly (
229
+ Job<string, never> | RecurringJob<string>
230
+ )[] = [eventJob, syncJob, closeJob, duplicateJob, reconcileJob, auditJob]
package/src/keys.ts ADDED
@@ -0,0 +1,40 @@
1
+ // The checks every catalog definition shares: its keys, and the names it
2
+ // gives. A product's key and a price's name make the price's lookup key,
3
+ // `<product>.<price>`, so neither holds a dot.
4
+ import { Refused } from 'ultimabase'
5
+
6
+ const named = /^[\w-]+$/u
7
+
8
+ /** Where a message points: `defineProduct(pro)`, or the entry alone. */
9
+ export const whereOf = (entry: string, definition: object): string => {
10
+ const key: unknown = Reflect.get(definition, 'key')
11
+ return typeof key === 'string' ? `${entry}(${key})` : entry
12
+ }
13
+
14
+ /**
15
+ * Refuses a definition that is not an object, or holds a key `keys` does
16
+ * not name: a misspelt option would be dropped unread (D-370).
17
+ */
18
+ export function ownKeys(
19
+ entry: string,
20
+ definition: unknown,
21
+ keys: readonly string[],
22
+ ): asserts definition is object {
23
+ if (typeof definition !== 'object' || definition === null) {
24
+ throw new Refused(`${entry} takes an object.`)
25
+ }
26
+ for (const key of Object.keys(definition)) {
27
+ if (!keys.includes(key)) {
28
+ throw new Refused(`${whereOf(entry, definition)} takes no ${key}.`)
29
+ }
30
+ }
31
+ }
32
+
33
+ /** Refuses a key or a price's name that is not letters, digits, - and _. */
34
+ export function checkKey(where: string, key: unknown): void {
35
+ if (typeof key !== 'string' || !named.test(key)) {
36
+ throw new Refused(
37
+ `${where}: ${JSON.stringify(key)} is not a key: letters, digits, - and _ only.`,
38
+ )
39
+ }
40
+ }
package/src/kinds.ts ADDED
@@ -0,0 +1,15 @@
1
+ // The models `defineSubscription`, `definePurchase`, `defineBalance` and
2
+ // `defineCreditHistory` returned, which the plugin finds among the application's at start.
3
+
4
+ /** The billing model kinds (D-373). */
5
+ export type Kind = 'subscription' | 'purchase' | 'balance' | 'history'
6
+
7
+ /** What a billing model was declared with. */
8
+ export interface Declared {
9
+ readonly kind: Kind
10
+ /** Its payer's or owner's model: `() => User`. */
11
+ readonly payer: () => object
12
+ }
13
+
14
+ /** Each billing model, by its queries. */
15
+ export const billingModels: WeakMap<object, Declared> = new WeakMap()