@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/audit.ts ADDED
@@ -0,0 +1,171 @@
1
+ // The daily audit (D-379): it logs a balance that is not the sum of its
2
+ // history, and a payment Stripe took with no purchase. It never writes.
3
+ import type { RecurringJob } from '@ultimabase/jobs'
4
+ import { defineJob } from '@ultimabase/jobs'
5
+ import type { Logger } from 'ultimabase'
6
+ import { transaction } from 'ultimabase'
7
+ import type { BillingGateway, RecoveryGateway } from './billing-gateway.ts'
8
+ import { M, StripeCustomer } from './models.ts'
9
+ import type { Billing, Running } from './running.ts'
10
+ import { runningOf } from './running.ts'
11
+
12
+ const hour = 60 * 60 * 1000
13
+ /** The owners, or the customers, read at once. */
14
+ const page = 500
15
+ /** The oldest payment read: two runs overlap, so a skipped one loses none. */
16
+ const oldest = 48 * hour
17
+ /** The newest payment read: the hourly reconciliation heals it first. */
18
+ const newest = 2 * hour
19
+
20
+ const idOf = (value: unknown): string | undefined => {
21
+ const id: unknown =
22
+ typeof value === 'object' && value !== null
23
+ ? Reflect.get(value, 'id')
24
+ : undefined
25
+ return typeof id === 'string' ? id : undefined
26
+ }
27
+
28
+ const numberOf = (value: unknown): number =>
29
+ typeof value === 'number' ? value : 0
30
+
31
+ type Sum = { owner: string; credit: string; sum: number }
32
+ type Row = Readonly<Record<string, unknown>>
33
+
34
+ /** Each owner's sums, by `owner credit`, from rows or groups. */
35
+ function sums(rows: readonly Row[], read: (row: Row) => number) {
36
+ const found = new Map<string, Sum>()
37
+ for (const row of rows) {
38
+ const owner = idOf(row.owner)
39
+ const { credit } = row
40
+ if (owner === undefined || typeof credit !== 'string') continue
41
+ found.set(`${owner} ${credit}`, { owner, credit, sum: read(row) })
42
+ }
43
+ return found
44
+ }
45
+
46
+ /** Logs each balance of these owners that is not the sum of its history. */
47
+ async function auditOwners(
48
+ balance: Billing,
49
+ history: Billing,
50
+ ids: readonly string[],
51
+ logger: Logger,
52
+ ): Promise<void> {
53
+ const where = { owner: { is: { id: { in: ids } } } }
54
+ const [balances, moves] = await transaction(
55
+ async () =>
56
+ [
57
+ await balance.queries.findMany(
58
+ {
59
+ where,
60
+ select: {
61
+ owner: { select: { id: true } },
62
+ credit: true,
63
+ amount: true,
64
+ },
65
+ },
66
+ M,
67
+ ),
68
+ await history.queries.groupBy(
69
+ { by: ['owner', 'credit'], where, _sum: { change: true } },
70
+ M,
71
+ ),
72
+ ] as const,
73
+ { isolation: 'serializable' },
74
+ )
75
+ const held = sums(balances, (row) => numberOf(row.amount))
76
+ const summed = sums(moves, (row) =>
77
+ numberOf(Reflect.get(Object(row['_sum']), 'change')),
78
+ )
79
+ for (const key of new Set([...held.keys(), ...summed.keys()])) {
80
+ const one = held.get(key) ?? summed.get(key)
81
+ const amount = held.get(key)?.sum ?? 0
82
+ const sum = summed.get(key)?.sum ?? 0
83
+ if (one === undefined || amount === sum) continue
84
+ const { owner, credit } = one
85
+ logger.error(
86
+ { owner, credit, balance: amount, history: sum },
87
+ 'A balance is not the sum of its history.',
88
+ )
89
+ }
90
+ }
91
+
92
+ /** Each balance is the sum of its history (D-379 point 2). */
93
+ async function auditBalances(running: Running, logger: Logger): Promise<void> {
94
+ const { balance, history } = running
95
+ if (balance === undefined || history === undefined) return
96
+ let cursor: string | undefined
97
+ for (;;) {
98
+ const owners = await balance.payer.queries.findMany(
99
+ {
100
+ select: { id: true },
101
+ orderBy: { id: 'asc' },
102
+ take: page,
103
+ ...(cursor === undefined ? {} : { cursor: { id: cursor }, skip: 1 }),
104
+ },
105
+ M,
106
+ )
107
+ const ids = owners.map(({ id }) => id)
108
+ if (ids.length > 0) await auditOwners(balance, history, ids, logger)
109
+ cursor = ids.at(-1)
110
+ if (ids.length < page) return
111
+ }
112
+ }
113
+
114
+ /** Each payment Stripe took has its purchase (D-379 point 3). */
115
+ async function auditPayments(
116
+ gateway: BillingGateway & RecoveryGateway,
117
+ purchase: Billing,
118
+ running: Running,
119
+ logger: Logger,
120
+ ): Promise<void> {
121
+ const now = Date.now()
122
+ const changed = await gateway.changedSince(new Date(now - oldest))
123
+ const ids = [...changed.keys()]
124
+ for (let at = 0; at < ids.length; at += page) {
125
+ const stripeId = { in: ids.slice(at, at + page) }
126
+ const where = { stripeId, model: purchase.payer.name }
127
+ for (const row of await StripeCustomer.findMany({ where }, M)) {
128
+ if (row.stripeId === null) continue
129
+ const { payments } = await gateway.readCustomer(row.stripeId)
130
+ const paid = payments.filter(({ product, paidAt }) => {
131
+ const age = now - paidAt.getTime()
132
+ return (
133
+ product !== null &&
134
+ running.products.has(product) &&
135
+ age >= newest &&
136
+ age <= oldest
137
+ )
138
+ })
139
+ if (paid.length === 0) continue
140
+ const kept = await purchase.queries.findMany(
141
+ { where: { stripeId: { in: paid.map(({ id }) => id) } } },
142
+ M,
143
+ )
144
+ const known = new Set(kept.map((one) => one.stripeId))
145
+ for (const { id, customerId, paidAt } of paid) {
146
+ if (known.has(id)) continue
147
+ logger.error(
148
+ { payment: id, customer: customerId, paidAt: paidAt.toISOString() },
149
+ 'A paid payment has no purchase.',
150
+ )
151
+ }
152
+ }
153
+ }
154
+ }
155
+
156
+ /** Every day: the ledger's balances, then Stripe's payments (D-379). */
157
+ async function audit(logger: Logger): Promise<void> {
158
+ const running = runningOf('stripe.audit')
159
+ await auditBalances(running, logger)
160
+ // Last, so that an unreachable Stripe leaves the ledger audited.
161
+ const { stripe, purchase } = running
162
+ if (stripe !== undefined && purchase !== undefined) {
163
+ await auditPayments(stripe.gateway, purchase, running, logger)
164
+ }
165
+ }
166
+
167
+ export const auditJob: RecurringJob<'stripe.audit'> = defineJob({
168
+ name: 'stripe.audit',
169
+ every: 24 * hour,
170
+ run: ({ logger }) => audit(logger),
171
+ })
@@ -0,0 +1,188 @@
1
+ // What the plugin asks Stripe of its payers: customers, Checkouts, the
2
+ // portal, and what a customer holds. `sdkBilling` reaches Stripe; the fake
3
+ // of `@ultimabase/stripe/testing` answers in memory.
4
+ import { PublicError } from 'ultimabase'
5
+
6
+ /** What Stripe shows of a payer (D-371). */
7
+ export interface CustomerProfile {
8
+ readonly email?: string | null
9
+ readonly name?: string | null
10
+ /** Checkout's and the portal's language: `fr`. */
11
+ readonly locale?: string | null
12
+ }
13
+
14
+ /** A product key and a price name, from a price's metadata. */
15
+ export interface PriceKeys {
16
+ readonly product: string | null
17
+ readonly price: string | null
18
+ }
19
+
20
+ /** A subscription, as the plugin reads it. */
21
+ export interface StripeSubscription extends PriceKeys {
22
+ readonly id: string
23
+ readonly customerId: string
24
+ readonly status: string
25
+ readonly quantity: number
26
+ /** One period's price times the quantity, before discounts and taxes. */
27
+ readonly amount: number
28
+ readonly every: string
29
+ readonly everyCount: number
30
+ readonly currentPeriodEnd: Date
31
+ readonly cancelAt: Date | null
32
+ readonly canceledAt: Date | null
33
+ readonly trialEnd: Date | null
34
+ readonly startedAt: Date
35
+ /** A change waiting for the period's end. */
36
+ readonly scheduled: (PriceKeys & { readonly at: Date }) | null
37
+ /** The card its Checkout left on it, moved to its customer (D-380). */
38
+ readonly card: string | null
39
+ }
40
+
41
+ /** Stripe's statuses of a subscription that still gives access. */
42
+ export const liveStatuses: readonly string[] = [
43
+ 'active',
44
+ 'trialing',
45
+ 'past_due',
46
+ 'unpaid',
47
+ 'paused',
48
+ ]
49
+
50
+ /** A one-time payment of a catalog product. */
51
+ export interface StripePayment {
52
+ readonly id: string
53
+ readonly customerId: string
54
+ readonly product: string | null
55
+ /** How many of the product were paid: what it gives, so many times. */
56
+ readonly quantity: number
57
+ readonly amount: number
58
+ readonly refunded: number
59
+ /** Whether a dispute of it was lost. */
60
+ readonly disputeLost: boolean
61
+ readonly paidAt: Date
62
+ readonly receiptUrl: string | null
63
+ }
64
+
65
+ /** A paid invoice of a subscription (D-377 point 4). */
66
+ export interface StripeInvoice {
67
+ readonly id: string
68
+ readonly customerId: string
69
+ /** Its lines that bill a whole period above zero: no proration, no trial. */
70
+ readonly periods: readonly (PriceKeys & {
71
+ readonly quantity: number
72
+ /** When the period it bills ends. */
73
+ readonly end: Date
74
+ })[]
75
+ readonly amount: number
76
+ readonly refunded: number
77
+ readonly disputeLost: boolean
78
+ }
79
+
80
+ /** What a customer holds. */
81
+ export interface CustomerState {
82
+ /** Deleted, or never found. */
83
+ readonly deleted: boolean
84
+ readonly subscriptions: readonly StripeSubscription[]
85
+ readonly payments: readonly StripePayment[]
86
+ readonly invoices: readonly StripeInvoice[]
87
+ }
88
+
89
+ /** A Checkout the plugin opens. */
90
+ export interface CheckoutWrite {
91
+ readonly customerId: string
92
+ /** Its `client_reference_id`: the payer's id. */
93
+ readonly reference: string
94
+ readonly mode: 'subscription' | 'payment'
95
+ readonly product: string
96
+ readonly lookupKey: string
97
+ readonly quantity: number
98
+ readonly trialDays: number | null
99
+ readonly terms: boolean
100
+ readonly promotionCodes: boolean
101
+ readonly successUrl: string
102
+ readonly cancelUrl: string
103
+ readonly metadata: Readonly<Record<string, string>>
104
+ }
105
+
106
+ /** The portal's page a session opens on. */
107
+ export type PortalFlow =
108
+ | { readonly kind: 'home' }
109
+ | {
110
+ readonly kind: 'change'
111
+ readonly subscriptionId: string
112
+ readonly lookupKey: string
113
+ }
114
+ | { readonly kind: 'cancel'; readonly subscriptionId: string }
115
+
116
+ /** A portal session the plugin opens. */
117
+ export interface PortalWrite {
118
+ readonly customerId: string
119
+ /** The managed configuration, or `null` for the account's default. */
120
+ readonly configuration: string | null
121
+ readonly returnUrl: string
122
+ readonly flow: PortalFlow
123
+ }
124
+
125
+ /** What the plugin asks Stripe of its payers. */
126
+ export interface BillingGateway {
127
+ /** Creates a customer; the same key gives the same one. */
128
+ readonly createCustomer: (
129
+ profile: CustomerProfile,
130
+ idempotencyKey: string,
131
+ ) => Promise<string>
132
+ readonly updateCustomer: (
133
+ id: string,
134
+ profile: CustomerProfile,
135
+ ) => Promise<void>
136
+ /** Deletes a customer, which ends its subscriptions; a missing one is gone. */
137
+ readonly deleteCustomer: (id: string) => Promise<void>
138
+ /**
139
+ * What a customer holds; if asked, of the last 400 days, its paid
140
+ * invoices and its Checkouts a full discount made free.
141
+ */
142
+ readonly readCustomer: (
143
+ id: string,
144
+ options?: { readonly invoices?: boolean; readonly free?: boolean },
145
+ ) => Promise<CustomerState>
146
+ /** The customer an event's object belongs to, if any. */
147
+ readonly customerOf: (type: string, id: string) => Promise<string | null>
148
+ /** Opens a Checkout; returns its URL. */
149
+ readonly openCheckout: (checkout: CheckoutWrite) => Promise<string>
150
+ /** Expires the customer's open Checkouts. */
151
+ readonly expireCheckouts: (customerId: string) => Promise<void>
152
+ /** A Checkout's customer, or `null` for an unknown id. */
153
+ readonly checkoutCustomer: (id: string) => Promise<string | null>
154
+ /** Opens a portal session; returns its URL. */
155
+ readonly openPortal: (portal: PortalWrite) => Promise<string>
156
+ /** Makes a subscription's card its customer's, then clears its own (D-380). */
157
+ readonly moveCard: (
158
+ one: Pick<StripeSubscription, 'id' | 'customerId'> & { card: string },
159
+ ) => Promise<void>
160
+ }
161
+
162
+ /** What the plugin asks Stripe to set right what went wrong (D-375). */
163
+ export interface RecoveryGateway {
164
+ /**
165
+ * Ends a subscription at once, unless it ended, and refunds its latest
166
+ * payment; done again, it changes nothing.
167
+ */
168
+ readonly cancelAndRefund: (id: string) => Promise<void>
169
+ /**
170
+ * The customers whose objects Stripe's events changed after `since`, with
171
+ * the time of each one's last event.
172
+ */
173
+ readonly changedSince: (since: Date) => Promise<ReadonlyMap<string, Date>>
174
+ }
175
+
176
+ /** An object Stripe does not hold, or no longer does. */
177
+ export class Missing extends Error {
178
+ constructor(id: string) {
179
+ super(`Stripe holds no ${id}.`)
180
+ this.name = 'Missing'
181
+ }
182
+ }
183
+
184
+ /** `PAYMENT_UNAVAILABLE` (D-371): Stripe cannot be reached, or no key is set. */
185
+ export const unavailable = (cause?: unknown): PublicError =>
186
+ new PublicError('PAYMENT_UNAVAILABLE', 'Payments are unavailable.', {
187
+ cause,
188
+ })