@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.
- package/README.md +7 -0
- package/dist/accounts.d.ts +9 -0
- package/dist/accounts.d.ts.map +1 -0
- package/dist/accounts.js +20 -0
- package/dist/apply.d.ts +26 -0
- package/dist/apply.d.ts.map +1 -0
- package/dist/apply.js +73 -0
- package/dist/audit.d.ts +3 -0
- package/dist/audit.d.ts.map +1 -0
- package/dist/audit.js +123 -0
- package/dist/billing-gateway.d.ts +158 -0
- package/dist/billing-gateway.d.ts.map +1 -0
- package/dist/billing-gateway.js +23 -0
- package/dist/billing.d.ts +130 -0
- package/dist/billing.d.ts.map +1 -0
- package/dist/billing.js +128 -0
- package/dist/calls.d.ts +61 -0
- package/dist/calls.d.ts.map +1 -0
- package/dist/calls.js +172 -0
- package/dist/catalog.d.ts +54 -0
- package/dist/catalog.d.ts.map +1 -0
- package/dist/catalog.js +182 -0
- package/dist/credit.d.ts +16 -0
- package/dist/credit.d.ts.map +1 -0
- package/dist/credit.js +18 -0
- package/dist/credits.d.ts +38 -0
- package/dist/credits.d.ts.map +1 -0
- package/dist/credits.js +138 -0
- package/dist/customer.d.ts +25 -0
- package/dist/customer.d.ts.map +1 -0
- package/dist/customer.js +88 -0
- package/dist/describe.d.ts +4 -0
- package/dist/describe.d.ts.map +1 -0
- package/dist/describe.js +56 -0
- package/dist/duplicates.d.ts +12 -0
- package/dist/duplicates.d.ts.map +1 -0
- package/dist/duplicates.js +24 -0
- package/dist/fake-billing.d.ts +72 -0
- package/dist/fake-billing.d.ts.map +1 -0
- package/dist/fake-billing.js +290 -0
- package/dist/gateway.d.ts +108 -0
- package/dist/gateway.d.ts.map +1 -0
- package/dist/gateway.js +196 -0
- package/dist/index.d.ts +15 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +6 -0
- package/dist/job-input.d.ts +6 -0
- package/dist/job-input.d.ts.map +1 -0
- package/dist/job-input.js +20 -0
- package/dist/jobs.d.ts +16 -0
- package/dist/jobs.d.ts.map +1 -0
- package/dist/jobs.js +189 -0
- package/dist/keys.d.ts +10 -0
- package/dist/keys.d.ts.map +1 -0
- package/dist/keys.js +30 -0
- package/dist/kinds.d.ts +11 -0
- package/dist/kinds.d.ts.map +1 -0
- package/dist/kinds.js +4 -0
- package/dist/models.d.ts +71 -0
- package/dist/models.d.ts.map +1 -0
- package/dist/models.js +41 -0
- package/dist/plugin.d.ts +41 -0
- package/dist/plugin.d.ts.map +1 -0
- package/dist/plugin.js +229 -0
- package/dist/portal.d.ts +23 -0
- package/dist/portal.d.ts.map +1 -0
- package/dist/portal.js +66 -0
- package/dist/product.d.ts +57 -0
- package/dist/product.d.ts.map +1 -0
- package/dist/product.js +113 -0
- package/dist/running.d.ts +61 -0
- package/dist/running.d.ts.map +1 -0
- package/dist/running.js +35 -0
- package/dist/sdk-billing.d.ts +8 -0
- package/dist/sdk-billing.d.ts.map +1 -0
- package/dist/sdk-billing.js +200 -0
- package/dist/sdk-common.d.ts +13 -0
- package/dist/sdk-common.d.ts.map +1 -0
- package/dist/sdk-common.js +41 -0
- package/dist/sdk-customer.d.ts +9 -0
- package/dist/sdk-customer.d.ts.map +1 -0
- package/dist/sdk-customer.js +149 -0
- package/dist/sdk-invoices.d.ts +10 -0
- package/dist/sdk-invoices.d.ts.map +1 -0
- package/dist/sdk-invoices.js +53 -0
- package/dist/sdk-recovery.d.ts +5 -0
- package/dist/sdk-recovery.d.ts.map +1 -0
- package/dist/sdk-recovery.js +81 -0
- package/dist/sync.d.ts +8 -0
- package/dist/sync.d.ts.map +1 -0
- package/dist/sync.js +196 -0
- package/dist/testing.d.ts +24 -0
- package/dist/testing.d.ts.map +1 -0
- package/dist/testing.js +100 -0
- package/dist/webhook.d.ts +4 -0
- package/dist/webhook.d.ts.map +1 -0
- package/dist/webhook.js +73 -0
- package/package.json +51 -0
- package/src/accounts.ts +30 -0
- package/src/apply.ts +99 -0
- package/src/audit.ts +171 -0
- package/src/billing-gateway.ts +188 -0
- package/src/billing.ts +361 -0
- package/src/calls.ts +280 -0
- package/src/catalog.ts +327 -0
- package/src/credit.ts +36 -0
- package/src/credits.ts +206 -0
- package/src/customer.ts +113 -0
- package/src/describe.ts +76 -0
- package/src/duplicates.ts +45 -0
- package/src/fake-billing.ts +388 -0
- package/src/gateway.ts +333 -0
- package/src/index.ts +35 -0
- package/src/job-input.ts +24 -0
- package/src/jobs.ts +230 -0
- package/src/keys.ts +40 -0
- package/src/kinds.ts +15 -0
- package/src/models.ts +107 -0
- package/src/plugin.ts +307 -0
- package/src/portal.ts +95 -0
- package/src/product.ts +203 -0
- package/src/running.ts +104 -0
- package/src/sdk-billing.ts +220 -0
- package/src/sdk-common.ts +57 -0
- package/src/sdk-customer.ts +203 -0
- package/src/sdk-invoices.ts +81 -0
- package/src/sdk-recovery.ts +93 -0
- package/src/sync.ts +246 -0
- package/src/testing.ts +135 -0
- package/src/webhook.ts +100 -0
package/src/catalog.ts
ADDED
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
// The catalog at Stripe, written from the products declared in code (D-372).
|
|
2
|
+
// A product is found by its `metadata.key`, a price by its lookup key:
|
|
3
|
+
// `<product>.<price>`, or the product's key for a one-time price. The plan
|
|
4
|
+
// lists the changes from what Stripe holds; applying them never deletes: a
|
|
5
|
+
// product left out is archived, and a price whose billing changed is
|
|
6
|
+
// replaced by a new one, which takes its lookup key over.
|
|
7
|
+
import { Refused } from 'ultimabase'
|
|
8
|
+
import {
|
|
9
|
+
type CatalogState,
|
|
10
|
+
type PortalProduct,
|
|
11
|
+
type ProductWrite,
|
|
12
|
+
type Recurring,
|
|
13
|
+
type StripeGateway,
|
|
14
|
+
type StripePrice,
|
|
15
|
+
type StripeProduct,
|
|
16
|
+
managedBy,
|
|
17
|
+
} from './gateway.ts'
|
|
18
|
+
import { type PortalOptions, portalSettings, samePortal } from './portal.ts'
|
|
19
|
+
import type { Every, Product } from './product.ts'
|
|
20
|
+
|
|
21
|
+
/** What an application sells, and how its payers manage it. */
|
|
22
|
+
export interface Catalog {
|
|
23
|
+
/** Every price's currency, in lowercase: `eur`. */
|
|
24
|
+
readonly currency: string
|
|
25
|
+
/** Whether the amounts include the taxes. */
|
|
26
|
+
readonly taxBehavior: 'inclusive' | 'exclusive'
|
|
27
|
+
readonly products: readonly Product[]
|
|
28
|
+
readonly portal: PortalOptions
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** A price as the catalog wants it. */
|
|
32
|
+
export interface WantedPrice {
|
|
33
|
+
/** Its product's key. */
|
|
34
|
+
readonly product: string
|
|
35
|
+
readonly lookupKey: string
|
|
36
|
+
readonly amount: number
|
|
37
|
+
/** `null` for a one-time price. */
|
|
38
|
+
readonly recurring: Recurring<Every> | null
|
|
39
|
+
readonly metadata: Readonly<Record<string, string>>
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** One change to the catalog. */
|
|
43
|
+
export type CatalogStep =
|
|
44
|
+
| { readonly kind: 'createProduct'; readonly product: ProductWrite }
|
|
45
|
+
| {
|
|
46
|
+
readonly kind: 'updateProduct'
|
|
47
|
+
readonly product: ProductWrite
|
|
48
|
+
readonly was: StripeProduct
|
|
49
|
+
}
|
|
50
|
+
| { readonly kind: 'archiveProduct'; readonly was: StripeProduct }
|
|
51
|
+
| {
|
|
52
|
+
readonly kind: 'createPrice'
|
|
53
|
+
readonly price: WantedPrice
|
|
54
|
+
/** The price whose lookup key it takes over, archived after. */
|
|
55
|
+
readonly replaces: StripePrice | null
|
|
56
|
+
}
|
|
57
|
+
| {
|
|
58
|
+
readonly kind: 'updatePrice'
|
|
59
|
+
readonly price: WantedPrice
|
|
60
|
+
readonly was: StripePrice
|
|
61
|
+
}
|
|
62
|
+
| { readonly kind: 'archivePrice'; readonly was: StripePrice }
|
|
63
|
+
| { readonly kind: 'savePortal'; readonly id: string | null }
|
|
64
|
+
|
|
65
|
+
const productWrite = (product: Product): ProductWrite => ({
|
|
66
|
+
key: product.key,
|
|
67
|
+
name: product.name,
|
|
68
|
+
taxCode: product.taxCode ?? null,
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
/** The prices of the catalog's products, in their order. */
|
|
72
|
+
const wantedPrices = (products: readonly Product[]): WantedPrice[] =>
|
|
73
|
+
products.flatMap((product): WantedPrice[] =>
|
|
74
|
+
'prices' in product
|
|
75
|
+
? Object.entries(product.prices).map(([name, price]) => ({
|
|
76
|
+
product: product.key,
|
|
77
|
+
lookupKey: `${product.key}.${name}`,
|
|
78
|
+
amount: price.amount,
|
|
79
|
+
recurring: { every: price.every, count: price.everyCount ?? 1 },
|
|
80
|
+
metadata: { managedBy, product: product.key, price: name },
|
|
81
|
+
}))
|
|
82
|
+
: [
|
|
83
|
+
{
|
|
84
|
+
product: product.key,
|
|
85
|
+
lookupKey: product.key,
|
|
86
|
+
amount: product.price.amount,
|
|
87
|
+
recurring: null,
|
|
88
|
+
metadata: { managedBy, product: product.key },
|
|
89
|
+
},
|
|
90
|
+
],
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
/** The product of each key: its active one first, else an archived one. */
|
|
94
|
+
const productsOf = (
|
|
95
|
+
products: readonly Product[],
|
|
96
|
+
held: readonly StripeProduct[],
|
|
97
|
+
): Map<string, StripeProduct> =>
|
|
98
|
+
new Map(
|
|
99
|
+
products.flatMap(({ key }) => {
|
|
100
|
+
const ofKey = held.filter((product) => product.key === key)
|
|
101
|
+
const product = ofKey.find(({ active }) => active) ?? ofKey.at(0)
|
|
102
|
+
return product === undefined ? [] : [[key, product] as const]
|
|
103
|
+
}),
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
const sameRecurring = (
|
|
107
|
+
held: Recurring | null,
|
|
108
|
+
wanted: Recurring | null,
|
|
109
|
+
): boolean =>
|
|
110
|
+
held === null || wanted === null
|
|
111
|
+
? held === wanted
|
|
112
|
+
: held.every === wanted.every && held.count === wanted.count
|
|
113
|
+
|
|
114
|
+
/** Whether `held` bills as `price`: what Stripe never changes of a price. */
|
|
115
|
+
const billsAs = (
|
|
116
|
+
catalog: Catalog,
|
|
117
|
+
held: StripePrice,
|
|
118
|
+
price: WantedPrice,
|
|
119
|
+
productId: string | undefined,
|
|
120
|
+
): boolean =>
|
|
121
|
+
held.productId === productId &&
|
|
122
|
+
held.amount === price.amount &&
|
|
123
|
+
held.currency === catalog.currency &&
|
|
124
|
+
sameRecurring(held.recurring, price.recurring) &&
|
|
125
|
+
held.taxBehavior === catalog.taxBehavior
|
|
126
|
+
|
|
127
|
+
/** Whether `held` carries `price`'s nickname and metadata. */
|
|
128
|
+
const describedAs = (held: StripePrice, price: WantedPrice): boolean =>
|
|
129
|
+
held.nickname === price.lookupKey &&
|
|
130
|
+
// Stripe merges metadata: a key someone added stays, and is let be.
|
|
131
|
+
Object.entries(price.metadata).every(
|
|
132
|
+
([key, value]) => held.metadata[key] === value,
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
const productIs = (held: StripeProduct, product: ProductWrite): boolean =>
|
|
136
|
+
held.active && held.name === product.name && held.taxCode === product.taxCode
|
|
137
|
+
|
|
138
|
+
/** The active price of each lookup key. */
|
|
139
|
+
const activePrices = (
|
|
140
|
+
prices: readonly StripePrice[],
|
|
141
|
+
): Map<string, StripePrice> =>
|
|
142
|
+
new Map(
|
|
143
|
+
prices.flatMap((price) =>
|
|
144
|
+
price.active && price.lookupKey !== null
|
|
145
|
+
? [[price.lookupKey, price] as const]
|
|
146
|
+
: [],
|
|
147
|
+
),
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
/** The id `ids` holds for `key`, which the steps before have written. */
|
|
151
|
+
const idOf = (ids: ReadonlyMap<string, string>, key: string): string => {
|
|
152
|
+
const id = ids.get(key)
|
|
153
|
+
if (id === undefined) throw new Error(`The catalog has no id for ${key}.`)
|
|
154
|
+
return id
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** The portal's products: the subscriptions, with their prices' ids. */
|
|
158
|
+
const portalProducts = (
|
|
159
|
+
products: readonly Product[],
|
|
160
|
+
productIds: ReadonlyMap<string, string>,
|
|
161
|
+
priceIds: ReadonlyMap<string, string>,
|
|
162
|
+
): PortalProduct[] =>
|
|
163
|
+
products.flatMap((product) =>
|
|
164
|
+
'prices' in product
|
|
165
|
+
? [
|
|
166
|
+
{
|
|
167
|
+
productId: idOf(productIds, product.key),
|
|
168
|
+
priceIds: Object.keys(product.prices).map((name) =>
|
|
169
|
+
idOf(priceIds, `${product.key}.${name}`),
|
|
170
|
+
),
|
|
171
|
+
},
|
|
172
|
+
]
|
|
173
|
+
: [],
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
/** The id of each key's product. */
|
|
177
|
+
const productIdsOf = (
|
|
178
|
+
products: readonly Product[],
|
|
179
|
+
held: readonly StripeProduct[],
|
|
180
|
+
): Map<string, string> =>
|
|
181
|
+
new Map(
|
|
182
|
+
[...productsOf(products, held)].map(([key, { id }]) => [key, id] as const),
|
|
183
|
+
)
|
|
184
|
+
|
|
185
|
+
/** The changes that bring `state` to `catalog`, in order. */
|
|
186
|
+
export const planCatalog = (
|
|
187
|
+
catalog: Catalog,
|
|
188
|
+
state: CatalogState,
|
|
189
|
+
): CatalogStep[] => {
|
|
190
|
+
const steps: CatalogStep[] = []
|
|
191
|
+
const kept = productsOf(catalog.products, state.products)
|
|
192
|
+
for (const product of catalog.products.map(productWrite)) {
|
|
193
|
+
const was = kept.get(product.key)
|
|
194
|
+
if (was === undefined) steps.push({ kind: 'createProduct', product })
|
|
195
|
+
else if (!productIs(was, product)) {
|
|
196
|
+
steps.push({ kind: 'updateProduct', product, was })
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
const active = activePrices(state.prices)
|
|
200
|
+
const unchanged = new Map<string, string>()
|
|
201
|
+
const wanted = wantedPrices(catalog.products)
|
|
202
|
+
for (const price of wanted) {
|
|
203
|
+
const was = active.get(price.lookupKey)
|
|
204
|
+
if (was !== undefined && was.metadata['managedBy'] !== managedBy) {
|
|
205
|
+
throw new Refused(
|
|
206
|
+
`The price ${was.id} holds the lookup key ${price.lookupKey} but was not written by the catalog: archive it, or remove its lookup key, in the Stripe Dashboard.`,
|
|
207
|
+
)
|
|
208
|
+
}
|
|
209
|
+
if (was === undefined) {
|
|
210
|
+
steps.push({ kind: 'createPrice', price, replaces: null })
|
|
211
|
+
} else if (!billsAs(catalog, was, price, kept.get(price.product)?.id)) {
|
|
212
|
+
// A price's billing never changes: a new one takes the key over.
|
|
213
|
+
steps.push({ kind: 'createPrice', price, replaces: was })
|
|
214
|
+
} else {
|
|
215
|
+
unchanged.set(price.lookupKey, was.id)
|
|
216
|
+
if (!describedAs(was, price)) {
|
|
217
|
+
steps.push({ kind: 'updatePrice', price, was })
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
const lookupKeys = new Set(wanted.map(({ lookupKey }) => lookupKey))
|
|
222
|
+
for (const price of state.prices) {
|
|
223
|
+
if (
|
|
224
|
+
price.active &&
|
|
225
|
+
price.metadata['managedBy'] === managedBy &&
|
|
226
|
+
(price.lookupKey === null || !lookupKeys.has(price.lookupKey))
|
|
227
|
+
) {
|
|
228
|
+
steps.push({ kind: 'archivePrice', was: price })
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
// A product left out, or a key's second product.
|
|
232
|
+
const keptIds = new Set([...kept.values()].map(({ id }) => id))
|
|
233
|
+
for (const product of state.products) {
|
|
234
|
+
if (product.active && !keptIds.has(product.id)) {
|
|
235
|
+
steps.push({ kind: 'archiveProduct', was: product })
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
// A new subscription price changes the portal's list.
|
|
239
|
+
const moved = steps.some(
|
|
240
|
+
(step) => step.kind === 'createPrice' && step.price.recurring !== null,
|
|
241
|
+
)
|
|
242
|
+
if (
|
|
243
|
+
moved ||
|
|
244
|
+
state.portal === null ||
|
|
245
|
+
!samePortal(
|
|
246
|
+
state.portal.settings,
|
|
247
|
+
portalSettings(
|
|
248
|
+
catalog.portal,
|
|
249
|
+
portalProducts(
|
|
250
|
+
catalog.products,
|
|
251
|
+
productIdsOf(catalog.products, state.products),
|
|
252
|
+
unchanged,
|
|
253
|
+
),
|
|
254
|
+
),
|
|
255
|
+
)
|
|
256
|
+
) {
|
|
257
|
+
steps.push({ kind: 'savePortal', id: state.portal?.id ?? null })
|
|
258
|
+
}
|
|
259
|
+
return steps
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** Applies `steps`, planned from `state`, through `gateway`. */
|
|
263
|
+
export const applyCatalog = async (
|
|
264
|
+
catalog: Catalog,
|
|
265
|
+
gateway: StripeGateway,
|
|
266
|
+
state: CatalogState,
|
|
267
|
+
steps: readonly CatalogStep[],
|
|
268
|
+
): Promise<void> => {
|
|
269
|
+
const productIds = productIdsOf(catalog.products, state.products)
|
|
270
|
+
const priceIds = new Map(
|
|
271
|
+
[...activePrices(state.prices)].map(([key, { id }]) => [key, id] as const),
|
|
272
|
+
)
|
|
273
|
+
for (const step of steps) {
|
|
274
|
+
switch (step.kind) {
|
|
275
|
+
case 'createProduct':
|
|
276
|
+
productIds.set(
|
|
277
|
+
step.product.key,
|
|
278
|
+
await gateway.createProduct(step.product),
|
|
279
|
+
)
|
|
280
|
+
break
|
|
281
|
+
case 'updateProduct':
|
|
282
|
+
await gateway.updateProduct(step.was.id, step.product)
|
|
283
|
+
break
|
|
284
|
+
case 'archiveProduct':
|
|
285
|
+
await gateway.archiveProduct(step.was.id)
|
|
286
|
+
break
|
|
287
|
+
case 'createPrice': {
|
|
288
|
+
const { price } = step
|
|
289
|
+
const id = await gateway.createPrice({
|
|
290
|
+
productId: idOf(productIds, price.product),
|
|
291
|
+
lookupKey: price.lookupKey,
|
|
292
|
+
amount: price.amount,
|
|
293
|
+
currency: catalog.currency,
|
|
294
|
+
recurring: price.recurring,
|
|
295
|
+
taxBehavior: catalog.taxBehavior,
|
|
296
|
+
nickname: price.lookupKey,
|
|
297
|
+
metadata: price.metadata,
|
|
298
|
+
})
|
|
299
|
+
priceIds.set(price.lookupKey, id)
|
|
300
|
+
// After its successor: a payer never finds no price.
|
|
301
|
+
if (step.replaces !== null) {
|
|
302
|
+
await gateway.archivePrice(step.replaces.id)
|
|
303
|
+
}
|
|
304
|
+
break
|
|
305
|
+
}
|
|
306
|
+
case 'updatePrice':
|
|
307
|
+
await gateway.updatePrice(step.was.id, {
|
|
308
|
+
nickname: step.price.lookupKey,
|
|
309
|
+
metadata: step.price.metadata,
|
|
310
|
+
})
|
|
311
|
+
break
|
|
312
|
+
case 'archivePrice':
|
|
313
|
+
await gateway.archivePrice(step.was.id)
|
|
314
|
+
break
|
|
315
|
+
case 'savePortal': {
|
|
316
|
+
await gateway.savePortal(
|
|
317
|
+
step.id,
|
|
318
|
+
portalSettings(
|
|
319
|
+
catalog.portal,
|
|
320
|
+
portalProducts(catalog.products, productIds, priceIds),
|
|
321
|
+
),
|
|
322
|
+
)
|
|
323
|
+
break
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
}
|
package/src/credit.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// `defineCredit` (D-372): a kind of credit, as blue gems. It is a function:
|
|
2
|
+
// `blueGems(500)` is 500 of them, a value a product gives and, later, the
|
|
3
|
+
// application spends.
|
|
4
|
+
import { Refused } from 'ultimabase'
|
|
5
|
+
import { checkKey, ownKeys } from './keys.ts'
|
|
6
|
+
|
|
7
|
+
/** An amount of one credit: what a product gives. */
|
|
8
|
+
export interface CreditAmount<K extends string = string> {
|
|
9
|
+
readonly credit: K
|
|
10
|
+
readonly amount: number
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** A kind of credit: called with an amount, it gives that many of it. */
|
|
14
|
+
export interface Credit<K extends string = string> {
|
|
15
|
+
(amount: number): CreditAmount<K>
|
|
16
|
+
/** The credit's name in the application, never changed. */
|
|
17
|
+
readonly key: K
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Declares a kind of credit (D-372). */
|
|
21
|
+
export function defineCredit<const K extends string>(definition: {
|
|
22
|
+
readonly key: K
|
|
23
|
+
}): Credit<K> {
|
|
24
|
+
ownKeys('defineCredit', definition, ['key'])
|
|
25
|
+
const { key } = definition
|
|
26
|
+
checkKey('defineCredit', key)
|
|
27
|
+
const credit = (amount: number): CreditAmount<K> => {
|
|
28
|
+
if (!Number.isSafeInteger(amount) || amount <= 0) {
|
|
29
|
+
throw new Refused(
|
|
30
|
+
`${key}(${String(amount)}): an amount is a positive integer.`,
|
|
31
|
+
)
|
|
32
|
+
}
|
|
33
|
+
return Object.freeze({ credit: key, amount })
|
|
34
|
+
}
|
|
35
|
+
return Object.assign(credit, { key })
|
|
36
|
+
}
|
package/src/credits.ts
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
// Credits (D-374, D-377): a paid purchase or subscription invoice adds what
|
|
2
|
+
// it gives, once; a full refund or a lost dispute takes it back, down to
|
|
3
|
+
// zero; the application grants and spends them in its own transaction. Each
|
|
4
|
+
// move is written to the application's credit history.
|
|
5
|
+
import { PublicError, transaction } from 'ultimabase'
|
|
6
|
+
import type { CreditAmount } from './credit.ts'
|
|
7
|
+
import { M } from './models.ts'
|
|
8
|
+
import type { Billing, Row } from './running.ts'
|
|
9
|
+
import { runningOf } from './running.ts'
|
|
10
|
+
|
|
11
|
+
type Owner = { readonly id: string }
|
|
12
|
+
|
|
13
|
+
/** A paid payment or invoice, as its credits read it. */
|
|
14
|
+
export interface Paid {
|
|
15
|
+
readonly id: string
|
|
16
|
+
readonly amount: number
|
|
17
|
+
readonly refunded: number
|
|
18
|
+
readonly disputeLost: boolean
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Whether a full refund or a lost dispute takes its credits back. */
|
|
22
|
+
export const lost = (paid: Paid): boolean =>
|
|
23
|
+
// A free invoice, after a full coupon, is never refunded.
|
|
24
|
+
paid.disputeLost || (paid.amount > 0 && paid.refunded >= paid.amount)
|
|
25
|
+
|
|
26
|
+
/** Each credit's total, `times` over, in the order first named. */
|
|
27
|
+
export function totals(
|
|
28
|
+
credits: readonly CreditAmount[],
|
|
29
|
+
times = 1,
|
|
30
|
+
sums: Map<string, number> = new Map(),
|
|
31
|
+
): Map<string, number> {
|
|
32
|
+
for (const { credit, amount } of credits) {
|
|
33
|
+
sums.set(credit, (sums.get(credit) ?? 0) + amount * times)
|
|
34
|
+
}
|
|
35
|
+
return sums
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const listOf = (
|
|
39
|
+
credits: CreditAmount | readonly CreditAmount[],
|
|
40
|
+
): readonly CreditAmount[] => ('credit' in credits ? [credits] : credits)
|
|
41
|
+
|
|
42
|
+
/** The owner's balances of `credits`, their rows locked by the update. */
|
|
43
|
+
async function lockedBalances(
|
|
44
|
+
balance: Billing,
|
|
45
|
+
owner: string,
|
|
46
|
+
credits: readonly string[],
|
|
47
|
+
): Promise<Map<string, Row>> {
|
|
48
|
+
const where = { owner: { is: { id: owner } }, credit: { in: credits } }
|
|
49
|
+
const data = { amount: { increment: 0 } }
|
|
50
|
+
const rows = await balance.queries.updateManyAndReturn({ where, data }, M)
|
|
51
|
+
return new Map(rows.map((row) => [String(row['credit']), row]))
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const amountOf = (row: Row | undefined): number =>
|
|
55
|
+
typeof row?.['amount'] === 'number' ? row['amount'] : 0
|
|
56
|
+
|
|
57
|
+
/** The balance and history models, which come together (D-377 point 2). */
|
|
58
|
+
function creditModels(name: string): {
|
|
59
|
+
readonly balance: Billing
|
|
60
|
+
readonly history: Billing
|
|
61
|
+
} {
|
|
62
|
+
const { balance, history } = runningOf(name)
|
|
63
|
+
if (balance === undefined || history === undefined) {
|
|
64
|
+
throw new Error(`${name} needs a model defineBalance returned.`)
|
|
65
|
+
}
|
|
66
|
+
return { balance, history }
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Adds to the owner's balance of `credit`, creating it at the first move. */
|
|
70
|
+
async function add(
|
|
71
|
+
balance: Billing,
|
|
72
|
+
owner: string,
|
|
73
|
+
credit: string,
|
|
74
|
+
amount: number,
|
|
75
|
+
): Promise<void> {
|
|
76
|
+
await balance.queries.upsert(
|
|
77
|
+
{
|
|
78
|
+
where: { owner, credit },
|
|
79
|
+
create: { owner: { connect: { id: owner } }, credit, amount },
|
|
80
|
+
update: { amount: { increment: amount } },
|
|
81
|
+
},
|
|
82
|
+
M,
|
|
83
|
+
)
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
async function entry(
|
|
87
|
+
history: Billing,
|
|
88
|
+
owner: string,
|
|
89
|
+
move: { credit: string; change: number; reason: string },
|
|
90
|
+
payment: string | null = null,
|
|
91
|
+
): Promise<void> {
|
|
92
|
+
const data = { owner: { connect: { id: owner } }, ...move, payment }
|
|
93
|
+
await history.queries.create({ data }, M)
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Adds to each of the owner's balances without a payment, in the caller's
|
|
98
|
+
* transaction when it has one (D-377 point 1).
|
|
99
|
+
*/
|
|
100
|
+
export async function grant(
|
|
101
|
+
owner: Owner,
|
|
102
|
+
credits: CreditAmount | readonly CreditAmount[],
|
|
103
|
+
options: { readonly reason: string },
|
|
104
|
+
): Promise<void> {
|
|
105
|
+
const { balance, history } = creditModels('stripe.grant')
|
|
106
|
+
const sums = totals(listOf(credits))
|
|
107
|
+
await transaction(async () => {
|
|
108
|
+
for (const [credit, amount] of sums) {
|
|
109
|
+
await add(balance, owner.id, credit, amount)
|
|
110
|
+
const move = { credit, change: amount, reason: options.reason }
|
|
111
|
+
await entry(history, owner.id, move)
|
|
112
|
+
}
|
|
113
|
+
})
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Lowers each of the owner's balances, in the caller's transaction when it
|
|
118
|
+
* has one; `NOT_ENOUGH_CREDITS` when one would fall below zero, with
|
|
119
|
+
* nothing changed (D-374 point 2).
|
|
120
|
+
*/
|
|
121
|
+
export async function spend(
|
|
122
|
+
owner: Owner,
|
|
123
|
+
credits: CreditAmount | readonly CreditAmount[],
|
|
124
|
+
options: { readonly reason: string },
|
|
125
|
+
): Promise<void> {
|
|
126
|
+
const { balance, history } = creditModels('stripe.spend')
|
|
127
|
+
const sums = totals(listOf(credits))
|
|
128
|
+
await transaction(async () => {
|
|
129
|
+
const held = await lockedBalances(balance, owner.id, [...sums.keys()])
|
|
130
|
+
const spent = [...sums].map(([credit, needed]) => {
|
|
131
|
+
const row = held.get(credit)
|
|
132
|
+
const left = amountOf(row)
|
|
133
|
+
if (row === undefined || left < needed) {
|
|
134
|
+
throw new PublicError('NOT_ENOUGH_CREDITS', `Not enough ${credit}.`, {
|
|
135
|
+
details: { credit, balance: left, needed },
|
|
136
|
+
})
|
|
137
|
+
}
|
|
138
|
+
return { id: row.id, credit, needed }
|
|
139
|
+
})
|
|
140
|
+
for (const { id, credit, needed } of spent) {
|
|
141
|
+
const data = { amount: { decrement: needed } }
|
|
142
|
+
await balance.queries.update({ where: { id }, data }, M)
|
|
143
|
+
const move = { credit, change: -needed, reason: options.reason }
|
|
144
|
+
await entry(history, owner.id, move)
|
|
145
|
+
}
|
|
146
|
+
})
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** What the history shows a payment gave, by credit, and whether it was taken back. */
|
|
150
|
+
async function movesOf(
|
|
151
|
+
history: Billing,
|
|
152
|
+
payment: string,
|
|
153
|
+
): Promise<{ readonly given: Map<string, number>; readonly taken: boolean }> {
|
|
154
|
+
const rows = await history.queries.findMany({ where: { payment } }, M)
|
|
155
|
+
const given = new Map<string, number>()
|
|
156
|
+
for (const row of rows) {
|
|
157
|
+
if (row['reason'] === 'refund' || typeof row['change'] !== 'number')
|
|
158
|
+
continue
|
|
159
|
+
const credit = String(row['credit'])
|
|
160
|
+
given.set(credit, (given.get(credit) ?? 0) + row['change'])
|
|
161
|
+
}
|
|
162
|
+
return { given, taken: rows.some((row) => row['reason'] === 'refund') }
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Gives the credits `sums` a paid payment or invoice gives, once, and takes
|
|
167
|
+
* back what it gave after a full refund or a lost dispute, once, down to
|
|
168
|
+
* zero (D-374, D-377 point 4).
|
|
169
|
+
*/
|
|
170
|
+
export async function settleCredits(
|
|
171
|
+
owner: string,
|
|
172
|
+
paid: Paid,
|
|
173
|
+
sums: ReadonlyMap<string, number>,
|
|
174
|
+
reason: 'purchase' | 'subscription',
|
|
175
|
+
): Promise<void> {
|
|
176
|
+
const { balance, history, logger } = runningOf('stripe')
|
|
177
|
+
if (balance === undefined || history === undefined) return
|
|
178
|
+
const moves = await movesOf(history, paid.id)
|
|
179
|
+
let given = moves.given
|
|
180
|
+
if (given.size === 0 && !moves.taken) {
|
|
181
|
+
for (const [credit, amount] of sums) {
|
|
182
|
+
await add(balance, owner, credit, amount)
|
|
183
|
+
await entry(history, owner, { credit, change: amount, reason }, paid.id)
|
|
184
|
+
}
|
|
185
|
+
given = new Map(sums)
|
|
186
|
+
}
|
|
187
|
+
if (!lost(paid) || moves.taken || given.size === 0) return
|
|
188
|
+
const held = await lockedBalances(balance, owner, [...given.keys()])
|
|
189
|
+
for (const [credit, amount] of given) {
|
|
190
|
+
const row = held.get(credit)
|
|
191
|
+
const taken = Math.min(amount, amountOf(row))
|
|
192
|
+
if (taken < amount) {
|
|
193
|
+
const details = { owner, credit, payment: paid.id }
|
|
194
|
+
logger.warn(
|
|
195
|
+
{ ...details, spent: amount - taken },
|
|
196
|
+
`${credit} of a refunded payment were already spent: they stay spent.`,
|
|
197
|
+
)
|
|
198
|
+
}
|
|
199
|
+
if (row !== undefined && taken > 0) {
|
|
200
|
+
const data = { amount: { decrement: taken } }
|
|
201
|
+
await balance.queries.update({ where: { id: row.id }, data }, M)
|
|
202
|
+
}
|
|
203
|
+
const move = { credit, change: -taken, reason: 'refund' }
|
|
204
|
+
await entry(history, owner, move, paid.id)
|
|
205
|
+
}
|
|
206
|
+
}
|
package/src/customer.ts
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
// A payer's Stripe customer (D-373 point 3): one row per payer in
|
|
2
|
+
// `StripeCustomer`, whose update is the lock every write about the payer
|
|
3
|
+
// takes, and one customer at Stripe, created once.
|
|
4
|
+
import type { RecordOf } from 'ultimabase'
|
|
5
|
+
import { PublicError, transaction } from 'ultimabase'
|
|
6
|
+
import type { CustomerProfile } from './billing-gateway.ts'
|
|
7
|
+
import { Missing } from './billing-gateway.ts'
|
|
8
|
+
import { M, StripeCustomer } from './models.ts'
|
|
9
|
+
import type { Billing, Row } from './running.ts'
|
|
10
|
+
import { runningOf, stripeOf } from './running.ts'
|
|
11
|
+
|
|
12
|
+
export type Customer = RecordOf<typeof StripeCustomer>
|
|
13
|
+
|
|
14
|
+
/** The payer's row of `model`, read as Master, or `NOT_FOUND`. */
|
|
15
|
+
export async function payerRow(
|
|
16
|
+
payer: Billing['payer'],
|
|
17
|
+
id: string,
|
|
18
|
+
): Promise<Row> {
|
|
19
|
+
const row = await payer.queries.findUnique({ where: { id } }, M)
|
|
20
|
+
if (row !== null) return row
|
|
21
|
+
throw new PublicError('NOT_FOUND', `No ${payer.name} matches payer.`, {
|
|
22
|
+
details: { model: payer.name },
|
|
23
|
+
})
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** The payer's customer row, created on its first use. */
|
|
27
|
+
export async function customerRow(
|
|
28
|
+
model: string,
|
|
29
|
+
payer: string,
|
|
30
|
+
): Promise<Customer> {
|
|
31
|
+
const where = { model, payer }
|
|
32
|
+
const held = await StripeCustomer.findUnique({ where }, M)
|
|
33
|
+
if (held !== null) return held
|
|
34
|
+
try {
|
|
35
|
+
return await StripeCustomer.create({ data: where }, M)
|
|
36
|
+
} catch (error) {
|
|
37
|
+
// Another call created it first.
|
|
38
|
+
if (!(error instanceof PublicError && error.code === 'UNIQUE_VIOLATION')) {
|
|
39
|
+
throw error
|
|
40
|
+
}
|
|
41
|
+
return StripeCustomer.findUniqueOrThrow({ where }, M)
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Runs `run` in a transaction holding the customer's row, so one write
|
|
47
|
+
* about a payer runs at a time; `undefined` when the row is gone.
|
|
48
|
+
*/
|
|
49
|
+
export async function locked<R>(
|
|
50
|
+
id: string,
|
|
51
|
+
run: (row: Customer) => Promise<R>,
|
|
52
|
+
): Promise<R | undefined> {
|
|
53
|
+
return transaction(async () => {
|
|
54
|
+
const data = { lockedAt: new Date() }
|
|
55
|
+
const [row] = await StripeCustomer.updateManyAndReturn(
|
|
56
|
+
{ where: { id }, data },
|
|
57
|
+
M,
|
|
58
|
+
)
|
|
59
|
+
return row === undefined ? undefined : run(row)
|
|
60
|
+
})
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** What Stripe shows of the payer, from the `customer` option. */
|
|
64
|
+
function profileOf(payer: Row): CustomerProfile {
|
|
65
|
+
const { customer } = runningOf('stripe')
|
|
66
|
+
const given: unknown =
|
|
67
|
+
customer === undefined ? {} : Reflect.apply(customer, undefined, [payer])
|
|
68
|
+
const read = (key: string): string | null => {
|
|
69
|
+
const value: unknown =
|
|
70
|
+
typeof given === 'object' && given !== null
|
|
71
|
+
? Reflect.get(given, key)
|
|
72
|
+
: undefined
|
|
73
|
+
return typeof value === 'string' ? value : null
|
|
74
|
+
}
|
|
75
|
+
return { email: read('email'), name: read('name'), locale: read('locale') }
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** A new row for the payer of `row`, whose customer Stripe deleted. */
|
|
79
|
+
export async function renewed(row: Customer): Promise<Customer> {
|
|
80
|
+
await StripeCustomer.delete({ where: { id: row.id } }, M)
|
|
81
|
+
const data = { model: row.model, payer: row.payer }
|
|
82
|
+
return StripeCustomer.create({ data }, M)
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* The payer's customer at Stripe, under its lock: created once, with an
|
|
87
|
+
* idempotency key, and given the payer's profile when it changed. A customer
|
|
88
|
+
* deleted at Stripe gives the payer a new row, so a new key.
|
|
89
|
+
*/
|
|
90
|
+
export async function ensureCustomer(
|
|
91
|
+
row: Customer,
|
|
92
|
+
payer: Row,
|
|
93
|
+
): Promise<{ readonly row: Customer; readonly stripeId: string }> {
|
|
94
|
+
const { gateway } = stripeOf('stripe')
|
|
95
|
+
const profile = profileOf(payer)
|
|
96
|
+
const json = JSON.stringify(profile)
|
|
97
|
+
if (row.stripeId !== null) {
|
|
98
|
+
if (row.profile === json) return { row, stripeId: row.stripeId }
|
|
99
|
+
try {
|
|
100
|
+
await gateway.updateCustomer(row.stripeId, profile)
|
|
101
|
+
} catch (error) {
|
|
102
|
+
if (!(error instanceof Missing)) throw error
|
|
103
|
+
return ensureCustomer(await renewed(row), payer)
|
|
104
|
+
}
|
|
105
|
+
const data = { profile: json }
|
|
106
|
+
await StripeCustomer.update({ where: { id: row.id }, data }, M)
|
|
107
|
+
return { row, stripeId: row.stripeId }
|
|
108
|
+
}
|
|
109
|
+
const stripeId = await gateway.createCustomer(profile, `customer-${row.id}`)
|
|
110
|
+
const data = { stripeId, profile: json }
|
|
111
|
+
await StripeCustomer.update({ where: { id: row.id }, data }, M)
|
|
112
|
+
return { row, stripeId }
|
|
113
|
+
}
|