@ultimabase/stripe 0.0.0-first.0 → 0.0.0-stage
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 +2 -6
- package/package.json +3 -48
- package/dist/accounts.d.ts +0 -9
- package/dist/accounts.d.ts.map +0 -1
- package/dist/accounts.js +0 -20
- package/dist/apply.d.ts +0 -26
- package/dist/apply.d.ts.map +0 -1
- package/dist/apply.js +0 -73
- package/dist/audit.d.ts +0 -3
- package/dist/audit.d.ts.map +0 -1
- package/dist/audit.js +0 -123
- package/dist/billing-gateway.d.ts +0 -158
- package/dist/billing-gateway.d.ts.map +0 -1
- package/dist/billing-gateway.js +0 -23
- package/dist/billing.d.ts +0 -130
- package/dist/billing.d.ts.map +0 -1
- package/dist/billing.js +0 -128
- package/dist/calls.d.ts +0 -61
- package/dist/calls.d.ts.map +0 -1
- package/dist/calls.js +0 -172
- package/dist/catalog.d.ts +0 -54
- package/dist/catalog.d.ts.map +0 -1
- package/dist/catalog.js +0 -182
- package/dist/credit.d.ts +0 -16
- package/dist/credit.d.ts.map +0 -1
- package/dist/credit.js +0 -18
- package/dist/credits.d.ts +0 -38
- package/dist/credits.d.ts.map +0 -1
- package/dist/credits.js +0 -138
- package/dist/customer.d.ts +0 -25
- package/dist/customer.d.ts.map +0 -1
- package/dist/customer.js +0 -88
- package/dist/describe.d.ts +0 -4
- package/dist/describe.d.ts.map +0 -1
- package/dist/describe.js +0 -56
- package/dist/duplicates.d.ts +0 -12
- package/dist/duplicates.d.ts.map +0 -1
- package/dist/duplicates.js +0 -24
- package/dist/fake-billing.d.ts +0 -72
- package/dist/fake-billing.d.ts.map +0 -1
- package/dist/fake-billing.js +0 -290
- package/dist/gateway.d.ts +0 -108
- package/dist/gateway.d.ts.map +0 -1
- package/dist/gateway.js +0 -196
- package/dist/index.d.ts +0 -15
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js +0 -6
- package/dist/job-input.d.ts +0 -6
- package/dist/job-input.d.ts.map +0 -1
- package/dist/job-input.js +0 -20
- package/dist/jobs.d.ts +0 -16
- package/dist/jobs.d.ts.map +0 -1
- package/dist/jobs.js +0 -189
- package/dist/keys.d.ts +0 -10
- package/dist/keys.d.ts.map +0 -1
- package/dist/keys.js +0 -30
- package/dist/kinds.d.ts +0 -11
- package/dist/kinds.d.ts.map +0 -1
- package/dist/kinds.js +0 -4
- package/dist/models.d.ts +0 -71
- package/dist/models.d.ts.map +0 -1
- package/dist/models.js +0 -41
- package/dist/plugin.d.ts +0 -41
- package/dist/plugin.d.ts.map +0 -1
- package/dist/plugin.js +0 -229
- package/dist/portal.d.ts +0 -23
- package/dist/portal.d.ts.map +0 -1
- package/dist/portal.js +0 -66
- package/dist/product.d.ts +0 -57
- package/dist/product.d.ts.map +0 -1
- package/dist/product.js +0 -113
- package/dist/running.d.ts +0 -61
- package/dist/running.d.ts.map +0 -1
- package/dist/running.js +0 -35
- package/dist/sdk-billing.d.ts +0 -8
- package/dist/sdk-billing.d.ts.map +0 -1
- package/dist/sdk-billing.js +0 -200
- package/dist/sdk-common.d.ts +0 -13
- package/dist/sdk-common.d.ts.map +0 -1
- package/dist/sdk-common.js +0 -41
- package/dist/sdk-customer.d.ts +0 -9
- package/dist/sdk-customer.d.ts.map +0 -1
- package/dist/sdk-customer.js +0 -149
- package/dist/sdk-invoices.d.ts +0 -10
- package/dist/sdk-invoices.d.ts.map +0 -1
- package/dist/sdk-invoices.js +0 -53
- package/dist/sdk-recovery.d.ts +0 -5
- package/dist/sdk-recovery.d.ts.map +0 -1
- package/dist/sdk-recovery.js +0 -81
- package/dist/sync.d.ts +0 -8
- package/dist/sync.d.ts.map +0 -1
- package/dist/sync.js +0 -196
- package/dist/testing.d.ts +0 -24
- package/dist/testing.d.ts.map +0 -1
- package/dist/testing.js +0 -100
- package/dist/webhook.d.ts +0 -4
- package/dist/webhook.d.ts.map +0 -1
- package/dist/webhook.js +0 -73
- package/src/accounts.ts +0 -30
- package/src/apply.ts +0 -99
- package/src/audit.ts +0 -171
- package/src/billing-gateway.ts +0 -188
- package/src/billing.ts +0 -361
- package/src/calls.ts +0 -280
- package/src/catalog.ts +0 -327
- package/src/credit.ts +0 -36
- package/src/credits.ts +0 -206
- package/src/customer.ts +0 -113
- package/src/describe.ts +0 -76
- package/src/duplicates.ts +0 -45
- package/src/fake-billing.ts +0 -388
- package/src/gateway.ts +0 -333
- package/src/index.ts +0 -35
- package/src/job-input.ts +0 -24
- package/src/jobs.ts +0 -230
- package/src/keys.ts +0 -40
- package/src/kinds.ts +0 -15
- package/src/models.ts +0 -107
- package/src/plugin.ts +0 -307
- package/src/portal.ts +0 -95
- package/src/product.ts +0 -203
- package/src/running.ts +0 -104
- package/src/sdk-billing.ts +0 -220
- package/src/sdk-common.ts +0 -57
- package/src/sdk-customer.ts +0 -203
- package/src/sdk-invoices.ts +0 -81
- package/src/sdk-recovery.ts +0 -93
- package/src/sync.ts +0 -246
- package/src/testing.ts +0 -135
- package/src/webhook.ts +0 -100
package/src/billing.ts
DELETED
|
@@ -1,361 +0,0 @@
|
|
|
1
|
-
// `defineSubscription`, `definePurchase`, `defineBalance` and
|
|
2
|
-
// `defineCreditHistory` (D-373, D-377): the application's own models of what
|
|
3
|
-
// a payer bought and of its credits, which only the plugin writes. Each is an ordinary model with the plugin first in its `use`.
|
|
4
|
-
import type {
|
|
5
|
-
Field,
|
|
6
|
-
FieldShapes,
|
|
7
|
-
IndexShape,
|
|
8
|
-
ModelFields,
|
|
9
|
-
ModelIndexes,
|
|
10
|
-
ModelOf,
|
|
11
|
-
ModelUse,
|
|
12
|
-
One,
|
|
13
|
-
PluginTypes,
|
|
14
|
-
ScalarOptions,
|
|
15
|
-
} from 'ultimabase'
|
|
16
|
-
import { defineModel, Refused } from 'ultimabase'
|
|
17
|
-
import { knownKeys } from 'ultimabase/internal'
|
|
18
|
-
import type { FieldBuilders } from 'ultimabase'
|
|
19
|
-
import { billingModels, type Kind } from './kinds.ts'
|
|
20
|
-
import type { Stripe } from './plugin.ts'
|
|
21
|
-
import { stripeUse } from './plugin.ts'
|
|
22
|
-
import type { Every } from './product.ts'
|
|
23
|
-
|
|
24
|
-
type Uses = readonly ModelUse<string, PluginTypes>[]
|
|
25
|
-
/** A billing model's `use`: the plugin first, then the developer's. */
|
|
26
|
-
export type WithStripe<U extends Uses> = readonly [
|
|
27
|
-
ModelUse<'stripe', Stripe>,
|
|
28
|
-
...U,
|
|
29
|
-
]
|
|
30
|
-
|
|
31
|
-
type Text = Field<string, ScalarOptions<string>>
|
|
32
|
-
type Int = Field<number, { readonly integer: true }>
|
|
33
|
-
type Moment = Field<Date, ScalarOptions<Date>>
|
|
34
|
-
type Optional<V> = Field<V | null, { readonly optional: true }>
|
|
35
|
-
type StripeId = Field<string, { readonly unique: true }>
|
|
36
|
-
type PayerOf<P> = One<P, { readonly onDelete: 'cascade' }>
|
|
37
|
-
type OneOf<V extends string> = Field<V, ScalarOptions<string>>
|
|
38
|
-
|
|
39
|
-
/** Stripe's statuses of a subscription. */
|
|
40
|
-
export type SubscriptionStatus =
|
|
41
|
-
| 'incomplete'
|
|
42
|
-
| 'incomplete_expired'
|
|
43
|
-
| 'trialing'
|
|
44
|
-
| 'active'
|
|
45
|
-
| 'past_due'
|
|
46
|
-
| 'canceled'
|
|
47
|
-
| 'unpaid'
|
|
48
|
-
| 'paused'
|
|
49
|
-
const statuses: readonly SubscriptionStatus[] = [
|
|
50
|
-
'incomplete',
|
|
51
|
-
'incomplete_expired',
|
|
52
|
-
'trialing',
|
|
53
|
-
'active',
|
|
54
|
-
'past_due',
|
|
55
|
-
'canceled',
|
|
56
|
-
'unpaid',
|
|
57
|
-
'paused',
|
|
58
|
-
]
|
|
59
|
-
const intervals: readonly Every[] = ['day', 'week', 'month', 'year']
|
|
60
|
-
|
|
61
|
-
/** The fields `defineSubscription` adds; `P` is the payer's thunk. */
|
|
62
|
-
export type SubscriptionFields<P> = {
|
|
63
|
-
readonly payer: PayerOf<P>
|
|
64
|
-
readonly stripeId: StripeId
|
|
65
|
-
/** The product's key and the price's name (D-372). */
|
|
66
|
-
readonly product: Text
|
|
67
|
-
readonly price: Text
|
|
68
|
-
readonly status: OneOf<SubscriptionStatus>
|
|
69
|
-
readonly quantity: Int
|
|
70
|
-
/**
|
|
71
|
-
* What one period costs, times the quantity, before discounts and taxes,
|
|
72
|
-
* in the currency's smallest unit: the price the payer subscribed at.
|
|
73
|
-
*/
|
|
74
|
-
readonly amount: Int
|
|
75
|
-
/** The price's interval: every `everyCount` `every`. */
|
|
76
|
-
readonly every: OneOf<Every>
|
|
77
|
-
readonly everyCount: Int
|
|
78
|
-
readonly currentPeriodEnd: Moment
|
|
79
|
-
readonly cancelAt: Optional<Date>
|
|
80
|
-
readonly canceledAt: Optional<Date>
|
|
81
|
-
readonly trialEnd: Optional<Date>
|
|
82
|
-
readonly startedAt: Moment
|
|
83
|
-
/** A change that waits for the period's end (D-373 point 8). */
|
|
84
|
-
readonly scheduledProduct: Optional<string>
|
|
85
|
-
readonly scheduledPrice: Optional<string>
|
|
86
|
-
readonly scheduledAt: Optional<Date>
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
/** The fields `definePurchase` adds. */
|
|
90
|
-
export type PurchaseFields<P> = {
|
|
91
|
-
readonly payer: PayerOf<P>
|
|
92
|
-
readonly stripeId: StripeId
|
|
93
|
-
readonly product: Text
|
|
94
|
-
readonly quantity: Int
|
|
95
|
-
/** In the currency's smallest unit. */
|
|
96
|
-
readonly amount: Int
|
|
97
|
-
readonly refunded: Int
|
|
98
|
-
readonly status: OneOf<'paid' | 'refunded'>
|
|
99
|
-
readonly paidAt: Moment
|
|
100
|
-
/** Stripe's receipt page. */
|
|
101
|
-
readonly receiptUrl: Optional<string>
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
/** The fields `defineBalance` adds. */
|
|
105
|
-
export type BalanceFields<P> = {
|
|
106
|
-
readonly owner: PayerOf<P>
|
|
107
|
-
/** The credit's key (D-372). */
|
|
108
|
-
readonly credit: Text
|
|
109
|
-
/** Never below zero. */
|
|
110
|
-
readonly amount: Int
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
/** The fields `defineCreditHistory` adds: one move of credits (D-377). */
|
|
114
|
-
export type CreditHistoryFields<P> = {
|
|
115
|
-
readonly owner: PayerOf<P>
|
|
116
|
-
readonly credit: Text
|
|
117
|
-
/** Positive when given, negative when spent or taken back. */
|
|
118
|
-
readonly change: Int
|
|
119
|
-
/** `purchase`, `subscription`, `refund`, or the application's own. */
|
|
120
|
-
readonly reason: Text
|
|
121
|
-
/** The Stripe payment or invoice that moved it. */
|
|
122
|
-
readonly payment: Optional<string>
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
type Definition<N, F, U extends Uses, X, A> = {
|
|
126
|
-
readonly name: N
|
|
127
|
-
/** The stored table's or collection's name (D-63). */
|
|
128
|
-
readonly dbName?: string
|
|
129
|
-
readonly use?: U
|
|
130
|
-
readonly indexes?: ModelIndexes<X, F & A, WithStripe<U>>
|
|
131
|
-
}
|
|
132
|
-
type Own<F, U extends Uses> = { readonly fields: ModelFields<F, WithStripe<U>> }
|
|
133
|
-
|
|
134
|
-
const added = (
|
|
135
|
-
f: FieldBuilders<never>,
|
|
136
|
-
kind: Kind,
|
|
137
|
-
payer: () => object,
|
|
138
|
-
): object => {
|
|
139
|
-
const ref = f.one(payer, { onDelete: 'cascade' })
|
|
140
|
-
const optional = { optional: true } as const
|
|
141
|
-
if (kind === 'subscription') {
|
|
142
|
-
return {
|
|
143
|
-
payer: ref,
|
|
144
|
-
stripeId: f.string({ unique: true }),
|
|
145
|
-
product: f.string(),
|
|
146
|
-
price: f.string(),
|
|
147
|
-
status: f.enumOf(statuses),
|
|
148
|
-
quantity: f.number({ integer: true }),
|
|
149
|
-
amount: f.number({ integer: true }),
|
|
150
|
-
every: f.enumOf(intervals),
|
|
151
|
-
everyCount: f.number({ integer: true }),
|
|
152
|
-
currentPeriodEnd: f.dateTime(),
|
|
153
|
-
cancelAt: f.dateTime(optional),
|
|
154
|
-
canceledAt: f.dateTime(optional),
|
|
155
|
-
trialEnd: f.dateTime(optional),
|
|
156
|
-
startedAt: f.dateTime(),
|
|
157
|
-
scheduledProduct: f.string(optional),
|
|
158
|
-
scheduledPrice: f.string(optional),
|
|
159
|
-
scheduledAt: f.dateTime(optional),
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
if (kind === 'purchase') {
|
|
163
|
-
return {
|
|
164
|
-
payer: ref,
|
|
165
|
-
stripeId: f.string({ unique: true }),
|
|
166
|
-
product: f.string(),
|
|
167
|
-
quantity: f.number({ integer: true }),
|
|
168
|
-
amount: f.number({ integer: true }),
|
|
169
|
-
refunded: f.number({ integer: true }),
|
|
170
|
-
status: f.enumOf(['paid', 'refunded']),
|
|
171
|
-
paidAt: f.dateTime(),
|
|
172
|
-
receiptUrl: f.string(optional),
|
|
173
|
-
}
|
|
174
|
-
}
|
|
175
|
-
if (kind === 'history') {
|
|
176
|
-
return {
|
|
177
|
-
owner: ref,
|
|
178
|
-
credit: f.string(),
|
|
179
|
-
change: f.number({ integer: true }),
|
|
180
|
-
reason: f.string(),
|
|
181
|
-
payment: f.string(optional),
|
|
182
|
-
}
|
|
183
|
-
}
|
|
184
|
-
return {
|
|
185
|
-
owner: ref,
|
|
186
|
-
credit: f.string(),
|
|
187
|
-
amount: f.number({ integer: true }),
|
|
188
|
-
}
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
/** The indexes the plugin's queries need. */
|
|
192
|
-
const indexesOf = (kind: Kind): readonly IndexShape[] => {
|
|
193
|
-
if (kind === 'balance') return [{ fields: ['owner', 'credit'], unique: true }]
|
|
194
|
-
// A payment gives its credits once: its moves are looked up by it.
|
|
195
|
-
if (kind === 'history') return [{ fields: ['payment'] }]
|
|
196
|
-
return []
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
// The kernel checks the model the thunk returns.
|
|
200
|
-
const isThunk = (value: unknown): value is () => object =>
|
|
201
|
-
typeof value === 'function'
|
|
202
|
-
|
|
203
|
-
const entries = {
|
|
204
|
-
subscription: ['defineSubscription', 'payer'],
|
|
205
|
-
purchase: ['definePurchase', 'payer'],
|
|
206
|
-
balance: ['defineBalance', 'owner'],
|
|
207
|
-
history: ['defineCreditHistory', 'owner'],
|
|
208
|
-
} as const
|
|
209
|
-
|
|
210
|
-
type Loose = {
|
|
211
|
-
readonly name: string
|
|
212
|
-
readonly dbName?: string
|
|
213
|
-
readonly use?: Uses
|
|
214
|
-
readonly fields?: Function
|
|
215
|
-
readonly indexes?: readonly IndexShape[]
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
/** Builds a billing model of `kind` from the developer's definition. */
|
|
219
|
-
function billingModel(kind: Kind, definition: Loose): object {
|
|
220
|
-
const [entry, key] = entries[kind]
|
|
221
|
-
const { name, fields } = definition
|
|
222
|
-
const keys = ['name', 'dbName', key, 'use', 'fields', 'indexes']
|
|
223
|
-
knownKeys(name, definition, keys, 'access, hooks and plugin options')
|
|
224
|
-
const payer: unknown = Reflect.get(definition, key)
|
|
225
|
-
if (!isThunk(payer)) {
|
|
226
|
-
throw new Refused(`${entry}(${name}): ${key} is () => its model.`)
|
|
227
|
-
}
|
|
228
|
-
const target = payer
|
|
229
|
-
const model: object = defineModel<
|
|
230
|
-
string,
|
|
231
|
-
FieldShapes,
|
|
232
|
-
Uses,
|
|
233
|
-
readonly IndexShape[]
|
|
234
|
-
>({
|
|
235
|
-
name,
|
|
236
|
-
...(definition.dbName === undefined ? {} : { dbName: definition.dbName }),
|
|
237
|
-
use: [stripeUse(), ...(definition.use ?? [])],
|
|
238
|
-
fields: (f) => {
|
|
239
|
-
const own: unknown =
|
|
240
|
-
fields === undefined ? {} : Reflect.apply(fields, undefined, [f])
|
|
241
|
-
if (typeof own !== 'object' || own === null) {
|
|
242
|
-
throw new Refused(`${entry}(${name}): fields returns an object.`)
|
|
243
|
-
}
|
|
244
|
-
const adds = added(f, kind, target)
|
|
245
|
-
const taken = Object.keys(adds).find((field) => Object.hasOwn(own, field))
|
|
246
|
-
if (taken !== undefined) {
|
|
247
|
-
throw new Refused(
|
|
248
|
-
`${entry}(${name}): ${taken} is a field ${entry} adds.`,
|
|
249
|
-
)
|
|
250
|
-
}
|
|
251
|
-
return { ...own, ...adds }
|
|
252
|
-
},
|
|
253
|
-
indexes: [...indexesOf(kind), ...(definition.indexes ?? [])],
|
|
254
|
-
})
|
|
255
|
-
billingModels.set(model, { kind, payer: target })
|
|
256
|
-
return model
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
/** The application's subscriptions, with its own fields (D-373). */
|
|
260
|
-
export function defineSubscription<
|
|
261
|
-
const N extends string,
|
|
262
|
-
const P extends () => object,
|
|
263
|
-
const F extends FieldShapes,
|
|
264
|
-
const U extends Uses = [],
|
|
265
|
-
const X extends readonly IndexShape[] = [],
|
|
266
|
-
>(
|
|
267
|
-
definition: Definition<N, F, U, X, SubscriptionFields<P>> &
|
|
268
|
-
Own<F, U> & { readonly payer: P },
|
|
269
|
-
): ModelOf<N, F & SubscriptionFields<P>, WithStripe<U>, X>
|
|
270
|
-
/** The application's subscriptions (D-373). */
|
|
271
|
-
export function defineSubscription<
|
|
272
|
-
const N extends string,
|
|
273
|
-
const P extends () => object,
|
|
274
|
-
const U extends Uses = [],
|
|
275
|
-
const X extends readonly IndexShape[] = [],
|
|
276
|
-
>(
|
|
277
|
-
definition: Definition<N, {}, U, X, SubscriptionFields<P>> & {
|
|
278
|
-
readonly payer: P
|
|
279
|
-
},
|
|
280
|
-
): ModelOf<N, SubscriptionFields<P>, WithStripe<U>, X>
|
|
281
|
-
export function defineSubscription(definition: Loose): object {
|
|
282
|
-
return billingModel('subscription', definition)
|
|
283
|
-
}
|
|
284
|
-
|
|
285
|
-
/** The application's one-time purchases, with its own fields (D-373). */
|
|
286
|
-
export function definePurchase<
|
|
287
|
-
const N extends string,
|
|
288
|
-
const P extends () => object,
|
|
289
|
-
const F extends FieldShapes,
|
|
290
|
-
const U extends Uses = [],
|
|
291
|
-
const X extends readonly IndexShape[] = [],
|
|
292
|
-
>(
|
|
293
|
-
definition: Definition<N, F, U, X, PurchaseFields<P>> &
|
|
294
|
-
Own<F, U> & { readonly payer: P },
|
|
295
|
-
): ModelOf<N, F & PurchaseFields<P>, WithStripe<U>, X>
|
|
296
|
-
/** The application's one-time purchases (D-373). */
|
|
297
|
-
export function definePurchase<
|
|
298
|
-
const N extends string,
|
|
299
|
-
const P extends () => object,
|
|
300
|
-
const U extends Uses = [],
|
|
301
|
-
const X extends readonly IndexShape[] = [],
|
|
302
|
-
>(
|
|
303
|
-
definition: Definition<N, {}, U, X, PurchaseFields<P>> & {
|
|
304
|
-
readonly payer: P
|
|
305
|
-
},
|
|
306
|
-
): ModelOf<N, PurchaseFields<P>, WithStripe<U>, X>
|
|
307
|
-
export function definePurchase(definition: Loose): object {
|
|
308
|
-
return billingModel('purchase', definition)
|
|
309
|
-
}
|
|
310
|
-
|
|
311
|
-
/** The application's credit balances, with its own fields (D-374). */
|
|
312
|
-
export function defineBalance<
|
|
313
|
-
const N extends string,
|
|
314
|
-
const P extends () => object,
|
|
315
|
-
const F extends FieldShapes,
|
|
316
|
-
const U extends Uses = [],
|
|
317
|
-
const X extends readonly IndexShape[] = [],
|
|
318
|
-
>(
|
|
319
|
-
definition: Definition<N, F, U, X, BalanceFields<P>> &
|
|
320
|
-
Own<F, U> & { readonly owner: P },
|
|
321
|
-
): ModelOf<N, F & BalanceFields<P>, WithStripe<U>, X>
|
|
322
|
-
/** The application's credit balances (D-374). */
|
|
323
|
-
export function defineBalance<
|
|
324
|
-
const N extends string,
|
|
325
|
-
const P extends () => object,
|
|
326
|
-
const U extends Uses = [],
|
|
327
|
-
const X extends readonly IndexShape[] = [],
|
|
328
|
-
>(
|
|
329
|
-
definition: Definition<N, {}, U, X, BalanceFields<P>> & {
|
|
330
|
-
readonly owner: P
|
|
331
|
-
},
|
|
332
|
-
): ModelOf<N, BalanceFields<P>, WithStripe<U>, X>
|
|
333
|
-
export function defineBalance(definition: Loose): object {
|
|
334
|
-
return billingModel('balance', definition)
|
|
335
|
-
}
|
|
336
|
-
|
|
337
|
-
/** The application's history of credits, with its own fields (D-377). */
|
|
338
|
-
export function defineCreditHistory<
|
|
339
|
-
const N extends string,
|
|
340
|
-
const P extends () => object,
|
|
341
|
-
const F extends FieldShapes,
|
|
342
|
-
const U extends Uses = [],
|
|
343
|
-
const X extends readonly IndexShape[] = [],
|
|
344
|
-
>(
|
|
345
|
-
definition: Definition<N, F, U, X, CreditHistoryFields<P>> &
|
|
346
|
-
Own<F, U> & { readonly owner: P },
|
|
347
|
-
): ModelOf<N, F & CreditHistoryFields<P>, WithStripe<U>, X>
|
|
348
|
-
/** The application's history of credits: each move, given or spent (D-377). */
|
|
349
|
-
export function defineCreditHistory<
|
|
350
|
-
const N extends string,
|
|
351
|
-
const P extends () => object,
|
|
352
|
-
const U extends Uses = [],
|
|
353
|
-
const X extends readonly IndexShape[] = [],
|
|
354
|
-
>(
|
|
355
|
-
definition: Definition<N, {}, U, X, CreditHistoryFields<P>> & {
|
|
356
|
-
readonly owner: P
|
|
357
|
-
},
|
|
358
|
-
): ModelOf<N, CreditHistoryFields<P>, WithStripe<U>, X>
|
|
359
|
-
export function defineCreditHistory(definition: Loose): object {
|
|
360
|
-
return billingModel('history', definition)
|
|
361
|
-
}
|
package/src/calls.ts
DELETED
|
@@ -1,280 +0,0 @@
|
|
|
1
|
-
// `stripe.checkout`, `stripe.portal` and `stripe.syncCheckout` (D-371 point
|
|
2
|
-
// 3, D-373 points 7 and 8): the server calls an application's functions make.
|
|
3
|
-
// Each runs under the payer's customer lock and expires the Checkouts the
|
|
4
|
-
// payer left open, so two tabs cannot both pay.
|
|
5
|
-
import { PublicError, Refused } from 'ultimabase'
|
|
6
|
-
import type { Gateway } from './accounts.ts'
|
|
7
|
-
import type { PortalFlow } from './billing-gateway.ts'
|
|
8
|
-
import { liveStatuses, Missing } from './billing-gateway.ts'
|
|
9
|
-
import type { Customer } from './customer.ts'
|
|
10
|
-
import {
|
|
11
|
-
customerRow,
|
|
12
|
-
ensureCustomer,
|
|
13
|
-
locked,
|
|
14
|
-
payerRow,
|
|
15
|
-
renewed,
|
|
16
|
-
} from './customer.ts'
|
|
17
|
-
import { M, StripeCustomer } from './models.ts'
|
|
18
|
-
import type { Product, SubscriptionProduct } from './product.ts'
|
|
19
|
-
import type { Billing, Row, Running } from './running.ts'
|
|
20
|
-
import { runningOf, stripeOf } from './running.ts'
|
|
21
|
-
import { grant, spend } from './credits.ts'
|
|
22
|
-
import { syncCustomer } from './sync.ts'
|
|
23
|
-
|
|
24
|
-
type Payer = { readonly id: string }
|
|
25
|
-
/** A product's price names: `'monthly' | 'yearly'`. */
|
|
26
|
-
type PriceOf<P> = P extends SubscriptionProduct<string, infer N> ? N : never
|
|
27
|
-
|
|
28
|
-
/** What `stripe.checkout` takes (D-373 point 7). */
|
|
29
|
-
export interface CheckoutArgs<P extends Product = Product> {
|
|
30
|
-
/** The payer's row, as `{ id }`. */
|
|
31
|
-
readonly payer: Payer
|
|
32
|
-
readonly product: P
|
|
33
|
-
/** One of a subscription product's prices; its only one by default. */
|
|
34
|
-
readonly price?: PriceOf<P>
|
|
35
|
-
/** 1 by default. */
|
|
36
|
-
readonly quantity?: number
|
|
37
|
-
readonly trialDays?: number
|
|
38
|
-
/** Whether the payer must accept the portal's `termsUrl`. */
|
|
39
|
-
readonly terms?: boolean
|
|
40
|
-
readonly promotionCodes?: boolean
|
|
41
|
-
/** Where Stripe sends the payer back; `{CHECKOUT_SESSION_ID}` is replaced. */
|
|
42
|
-
readonly successUrl: string
|
|
43
|
-
readonly cancelUrl: string
|
|
44
|
-
readonly metadata?: Readonly<Record<string, string>>
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
/** What `stripe.portal` takes (D-373 point 8). */
|
|
48
|
-
export interface PortalArgs<
|
|
49
|
-
P extends SubscriptionProduct = SubscriptionProduct,
|
|
50
|
-
> {
|
|
51
|
-
readonly payer: Payer
|
|
52
|
-
/** The portal option's `returnUrl` by default. */
|
|
53
|
-
readonly returnUrl?: string
|
|
54
|
-
/** Opens the confirmation of a move to another product or price. */
|
|
55
|
-
readonly change?: {
|
|
56
|
-
readonly product: P
|
|
57
|
-
readonly price: PriceOf<P>
|
|
58
|
-
/** The subscription row's id, when the payer has several live ones. */
|
|
59
|
-
readonly subscription?: string
|
|
60
|
-
}
|
|
61
|
-
/** Opens the confirmation of a cancellation. */
|
|
62
|
-
readonly cancel?: { readonly subscription?: string }
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
/** The catalog's product, or a bug: a product the plugin was not given. */
|
|
66
|
-
function catalogued(running: Running, product: Product): Product {
|
|
67
|
-
if (running.products.get(product.key) === product) return product
|
|
68
|
-
throw new Error(`${product.key} is not in stripePlugin's products.`)
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
/** The price's lookup key (D-372 point 3). */
|
|
72
|
-
function lookupKey(product: Product, price: string | undefined): string {
|
|
73
|
-
if (!('prices' in product)) return product.key
|
|
74
|
-
const names = Object.keys(product.prices)
|
|
75
|
-
const [only] = names
|
|
76
|
-
const name = price ?? (names.length === 1 ? only : undefined)
|
|
77
|
-
if (name === undefined || !names.includes(name)) {
|
|
78
|
-
throw new TypeError(`${product.key}'s price is one of ${names.join(', ')}.`)
|
|
79
|
-
}
|
|
80
|
-
return `${product.key}.${name}`
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
/** The model naming the payers of a product: who the customer is for. */
|
|
84
|
-
function billingOf(running: Running, product: Product): Billing {
|
|
85
|
-
const billing =
|
|
86
|
-
'prices' in product
|
|
87
|
-
? running.subscription
|
|
88
|
-
: (running.purchase ?? running.balance)
|
|
89
|
-
if (billing !== undefined) return billing
|
|
90
|
-
throw new Error(
|
|
91
|
-
`${product.key} needs a model definePurchase returned, to record its payments.`,
|
|
92
|
-
)
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
/**
|
|
96
|
-
* Runs `run` with the payer's customer at Stripe, under its lock, after
|
|
97
|
-
* expiring its open Checkouts; a customer deleted at Stripe is created again.
|
|
98
|
-
*/
|
|
99
|
-
async function withCustomer<R>(
|
|
100
|
-
billing: Billing,
|
|
101
|
-
payer: Payer,
|
|
102
|
-
run: (gateway: Gateway, customerId: string, row: Customer) => Promise<R>,
|
|
103
|
-
): Promise<R> {
|
|
104
|
-
const { gateway } = stripeOf('stripe')
|
|
105
|
-
const read = await payerRow(billing.payer, payer.id)
|
|
106
|
-
const held = await customerRow(billing.payer.name, payer.id)
|
|
107
|
-
const done = await locked(held.id, async (row) => {
|
|
108
|
-
const attempt = async (current: Customer): Promise<R> => {
|
|
109
|
-
const { row: saved, stripeId } = await ensureCustomer(current, read)
|
|
110
|
-
try {
|
|
111
|
-
await gateway.expireCheckouts(stripeId)
|
|
112
|
-
return await run(gateway, stripeId, saved)
|
|
113
|
-
} catch (error) {
|
|
114
|
-
if (!(error instanceof Missing) || current !== row) throw error
|
|
115
|
-
return attempt(await renewed(saved))
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
return { value: await attempt(row) }
|
|
119
|
-
})
|
|
120
|
-
if (done === undefined) throw new Error('The payer’s customer was closed.')
|
|
121
|
-
return done.value
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
const checkPositive = (name: string, value: number | undefined): void => {
|
|
125
|
-
if (value !== undefined && (!Number.isSafeInteger(value) || value < 1)) {
|
|
126
|
-
throw new TypeError(`stripe.checkout: ${name} is a positive integer.`)
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
/** Opens a Checkout for the payer and returns its URL. */
|
|
131
|
-
export async function checkout<const P extends Product>(
|
|
132
|
-
args: CheckoutArgs<P>,
|
|
133
|
-
): Promise<string> {
|
|
134
|
-
const running = runningOf('stripe.checkout')
|
|
135
|
-
stripeOf('stripe.checkout')
|
|
136
|
-
const product = catalogued(running, args.product)
|
|
137
|
-
const key = lookupKey(product, args.price)
|
|
138
|
-
checkPositive('quantity', args.quantity)
|
|
139
|
-
checkPositive('trialDays', args.trialDays)
|
|
140
|
-
const subscribing = 'prices' in product
|
|
141
|
-
return withCustomer(
|
|
142
|
-
billingOf(running, product),
|
|
143
|
-
args.payer,
|
|
144
|
-
async (gateway, customerId) => {
|
|
145
|
-
if (subscribing && running.oneSubscription) {
|
|
146
|
-
const { subscriptions } = await gateway.readCustomer(customerId)
|
|
147
|
-
if (subscriptions.some(({ status }) => liveStatuses.includes(status))) {
|
|
148
|
-
throw new PublicError(
|
|
149
|
-
'ALREADY_SUBSCRIBED',
|
|
150
|
-
'The payer already has a subscription.',
|
|
151
|
-
)
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
return gateway.openCheckout({
|
|
155
|
-
customerId,
|
|
156
|
-
reference: args.payer.id,
|
|
157
|
-
mode: subscribing ? 'subscription' : 'payment',
|
|
158
|
-
product: product.key,
|
|
159
|
-
lookupKey: key,
|
|
160
|
-
quantity: args.quantity ?? 1,
|
|
161
|
-
trialDays: subscribing ? (args.trialDays ?? null) : null,
|
|
162
|
-
terms: args.terms ?? false,
|
|
163
|
-
promotionCodes: args.promotionCodes ?? false,
|
|
164
|
-
successUrl: args.successUrl,
|
|
165
|
-
cancelUrl: args.cancelUrl,
|
|
166
|
-
metadata: args.metadata ?? {},
|
|
167
|
-
})
|
|
168
|
-
},
|
|
169
|
-
)
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
/**
|
|
173
|
-
* The payer's subscription a deep link is about, or `NOT_SUBSCRIBED`; the
|
|
174
|
-
* code names one with `option` when the payer has several.
|
|
175
|
-
*/
|
|
176
|
-
async function subscriptionOf(
|
|
177
|
-
model: Billing,
|
|
178
|
-
payer: Payer,
|
|
179
|
-
id: string | undefined,
|
|
180
|
-
option: string,
|
|
181
|
-
): Promise<Row> {
|
|
182
|
-
const where = {
|
|
183
|
-
payer: { is: { id: payer.id } },
|
|
184
|
-
status: { in: liveStatuses },
|
|
185
|
-
...(id === undefined ? {} : { id }),
|
|
186
|
-
}
|
|
187
|
-
const live = await model.queries.findMany({ where, take: 2 }, M)
|
|
188
|
-
const [one, other] = live
|
|
189
|
-
if (one === undefined) {
|
|
190
|
-
throw new PublicError('NOT_SUBSCRIBED', 'The payer has no subscription.')
|
|
191
|
-
}
|
|
192
|
-
if (other !== undefined) {
|
|
193
|
-
throw new Refused(
|
|
194
|
-
`stripe.portal: the payer has several live subscriptions; name the one with ${option}, a ${model.name} row’s id.`,
|
|
195
|
-
)
|
|
196
|
-
}
|
|
197
|
-
return one
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
/** The portal's flow for the arguments. */
|
|
201
|
-
async function flowOf(
|
|
202
|
-
running: Running,
|
|
203
|
-
model: Billing,
|
|
204
|
-
args: PortalArgs,
|
|
205
|
-
): Promise<PortalFlow> {
|
|
206
|
-
const { change, cancel } = args
|
|
207
|
-
if (change !== undefined && cancel !== undefined) {
|
|
208
|
-
throw new TypeError('stripe.portal takes change or cancel, not both.')
|
|
209
|
-
}
|
|
210
|
-
if (change !== undefined) {
|
|
211
|
-
const product = catalogued(running, change.product)
|
|
212
|
-
const lookup = lookupKey(product, change.price)
|
|
213
|
-
const row = await subscriptionOf(
|
|
214
|
-
model,
|
|
215
|
-
args.payer,
|
|
216
|
-
change.subscription,
|
|
217
|
-
'change.subscription',
|
|
218
|
-
)
|
|
219
|
-
const subscriptionId = String(row['stripeId'])
|
|
220
|
-
return { kind: 'change', subscriptionId, lookupKey: lookup }
|
|
221
|
-
}
|
|
222
|
-
if (cancel !== undefined) {
|
|
223
|
-
const row = await subscriptionOf(
|
|
224
|
-
model,
|
|
225
|
-
args.payer,
|
|
226
|
-
cancel.subscription,
|
|
227
|
-
'cancel.subscription',
|
|
228
|
-
)
|
|
229
|
-
return { kind: 'cancel', subscriptionId: String(row['stripeId']) }
|
|
230
|
-
}
|
|
231
|
-
return { kind: 'home' }
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
/** Opens the payer's customer portal, or one change's confirmation. */
|
|
235
|
-
export async function portal<const P extends SubscriptionProduct>(
|
|
236
|
-
args: PortalArgs<P>,
|
|
237
|
-
): Promise<string> {
|
|
238
|
-
const running = runningOf('stripe.portal')
|
|
239
|
-
const { gateway } = stripeOf('stripe.portal')
|
|
240
|
-
const model = running.subscription
|
|
241
|
-
if (model === undefined) {
|
|
242
|
-
throw new Error('stripe.portal needs a model defineSubscription returned.')
|
|
243
|
-
}
|
|
244
|
-
const flow = await flowOf(running, model, args)
|
|
245
|
-
running.portal ??= (await gateway.readCatalog()).portal?.id ?? null
|
|
246
|
-
const configuration = running.portal
|
|
247
|
-
const returnUrl = args.returnUrl ?? running.catalog.portal.returnUrl
|
|
248
|
-
return withCustomer(model, args.payer, async (_, customerId) =>
|
|
249
|
-
gateway.openPortal({ customerId, configuration, returnUrl, flow }),
|
|
250
|
-
)
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
/**
|
|
254
|
-
* Syncs the payer's Checkout `sessionId` when the client comes back, without
|
|
255
|
-
* waiting for the webhook; `NOT_FOUND` for another payer's.
|
|
256
|
-
*/
|
|
257
|
-
export async function syncCheckout(
|
|
258
|
-
sessionId: string,
|
|
259
|
-
payer: Payer,
|
|
260
|
-
): Promise<void> {
|
|
261
|
-
const { gateway } = stripeOf('stripe.syncCheckout')
|
|
262
|
-
const customerId = await gateway.checkoutCustomer(sessionId)
|
|
263
|
-
const row =
|
|
264
|
-
customerId === null
|
|
265
|
-
? null
|
|
266
|
-
: await StripeCustomer.findUnique({ where: { stripeId: customerId } }, M)
|
|
267
|
-
if (row === null || row.payer !== payer.id) {
|
|
268
|
-
throw new PublicError('NOT_FOUND', 'No Checkout of the payer matches.')
|
|
269
|
-
}
|
|
270
|
-
await syncCustomer(row.id)
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
/** The running plugin, from the application's functions (D-371 point 3). */
|
|
274
|
-
export const stripe: {
|
|
275
|
-
readonly checkout: typeof checkout
|
|
276
|
-
readonly portal: typeof portal
|
|
277
|
-
readonly syncCheckout: typeof syncCheckout
|
|
278
|
-
readonly grant: typeof grant
|
|
279
|
-
readonly spend: typeof spend
|
|
280
|
-
} = { checkout, portal, syncCheckout, grant, spend }
|