@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/models.ts
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
// The plugin's own models (D-110, D-371 point 6), which no application
|
|
2
|
+
// exposes: a payer's Stripe customer, the events received, and how far the
|
|
3
|
+
// hourly job read them.
|
|
4
|
+
import type { Field, ModelOf, ScalarOptions } from 'ultimabase'
|
|
5
|
+
import { defineModel, master } from 'ultimabase'
|
|
6
|
+
|
|
7
|
+
export const M: { readonly as: typeof master } = { as: master }
|
|
8
|
+
|
|
9
|
+
type Text = Field<string, ScalarOptions<string>>
|
|
10
|
+
type Optional<V> = Field<V | null, { readonly optional: true }>
|
|
11
|
+
type Counter = Field<
|
|
12
|
+
number,
|
|
13
|
+
{ readonly integer: true; readonly default: number }
|
|
14
|
+
>
|
|
15
|
+
|
|
16
|
+
type CustomerFields = {
|
|
17
|
+
/** The payer's model, `User`, and its row's id (D-373 point 3). */
|
|
18
|
+
readonly model: Text
|
|
19
|
+
readonly payer: Text
|
|
20
|
+
/** Set once Stripe created it. */
|
|
21
|
+
readonly stripeId: Field<
|
|
22
|
+
string | null,
|
|
23
|
+
{ readonly optional: true; readonly unique: true }
|
|
24
|
+
>
|
|
25
|
+
/** When the last sync written began to read Stripe. */
|
|
26
|
+
readonly syncedAt: Optional<Date>
|
|
27
|
+
/** The syncs begun, and the number of the last one written. */
|
|
28
|
+
readonly syncsBegun: Counter
|
|
29
|
+
readonly syncWritten: Counter
|
|
30
|
+
/** When a subscription renews, ends or changes: the hourly job syncs it. */
|
|
31
|
+
readonly renewsAt: Optional<Date>
|
|
32
|
+
/** Written to take the customer's lock. */
|
|
33
|
+
readonly lockedAt: Optional<Date>
|
|
34
|
+
/** The profile Stripe holds, as JSON. */
|
|
35
|
+
readonly profile: Optional<string>
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
type CustomerIndexes = readonly [
|
|
39
|
+
{ readonly fields: readonly ['model', 'payer']; readonly unique: true },
|
|
40
|
+
{ readonly fields: readonly ['renewsAt'] },
|
|
41
|
+
]
|
|
42
|
+
|
|
43
|
+
/** One per payer (D-373 point 3). */
|
|
44
|
+
export const StripeCustomer: ModelOf<
|
|
45
|
+
'StripeCustomer',
|
|
46
|
+
CustomerFields,
|
|
47
|
+
[],
|
|
48
|
+
CustomerIndexes
|
|
49
|
+
> = defineModel({
|
|
50
|
+
name: 'StripeCustomer',
|
|
51
|
+
fields: (f) => ({
|
|
52
|
+
model: f.string(),
|
|
53
|
+
payer: f.string(),
|
|
54
|
+
stripeId: f.string({ optional: true, unique: true }),
|
|
55
|
+
syncedAt: f.dateTime({ optional: true }),
|
|
56
|
+
syncsBegun: f.number({ integer: true, default: 0 }),
|
|
57
|
+
syncWritten: f.number({ integer: true, default: 0 }),
|
|
58
|
+
renewsAt: f.dateTime({ optional: true }),
|
|
59
|
+
lockedAt: f.dateTime({ optional: true }),
|
|
60
|
+
profile: f.string({ optional: true }),
|
|
61
|
+
}),
|
|
62
|
+
indexes: [
|
|
63
|
+
{ fields: ['model', 'payer'], unique: true },
|
|
64
|
+
{ fields: ['renewsAt'] },
|
|
65
|
+
],
|
|
66
|
+
})
|
|
67
|
+
|
|
68
|
+
type EventFields = {
|
|
69
|
+
readonly stripeId: Field<string, { readonly unique: true }>
|
|
70
|
+
/** `checkout.session.completed`: its v1 type. */
|
|
71
|
+
readonly type: Text
|
|
72
|
+
/** Its related object: `subscription` and its id. */
|
|
73
|
+
readonly objectType: Text
|
|
74
|
+
readonly objectId: Text
|
|
75
|
+
readonly processedAt: Optional<Date>
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Each event received, once (D-371 point 4). */
|
|
79
|
+
export const StripeEvent: ModelOf<'StripeEvent', EventFields, []> = defineModel(
|
|
80
|
+
{
|
|
81
|
+
name: 'StripeEvent',
|
|
82
|
+
fields: (f) => ({
|
|
83
|
+
stripeId: f.string({ unique: true }),
|
|
84
|
+
type: f.string(),
|
|
85
|
+
objectType: f.string(),
|
|
86
|
+
objectId: f.string(),
|
|
87
|
+
processedAt: f.dateTime({ optional: true }),
|
|
88
|
+
}),
|
|
89
|
+
indexes: [{ fields: ['processedAt'] }],
|
|
90
|
+
},
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
type ScanFields = {
|
|
94
|
+
/** `events`: the one scan. */
|
|
95
|
+
readonly name: Field<string, { readonly unique: true }>
|
|
96
|
+
/** Stripe's events up to this time were read. */
|
|
97
|
+
readonly until: Field<Date, ScalarOptions<Date>>
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** How far the hourly job read Stripe's events (D-375). */
|
|
101
|
+
export const StripeScan: ModelOf<'StripeScan', ScanFields, []> = defineModel({
|
|
102
|
+
name: 'StripeScan',
|
|
103
|
+
fields: (f) => ({
|
|
104
|
+
name: f.string({ unique: true }),
|
|
105
|
+
until: f.dateTime(),
|
|
106
|
+
}),
|
|
107
|
+
})
|
package/src/plugin.ts
ADDED
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
// `stripePlugin(options)` (D-371): the webhook, the jobs, the billing
|
|
2
|
+
// models' hooks, and at start the checks of D-372 point 5 and the catalog
|
|
3
|
+
// compared with Stripe, applied in development with a test key.
|
|
4
|
+
import type { Http } from '@ultimabase/http'
|
|
5
|
+
import { httpPlugin } from '@ultimabase/http'
|
|
6
|
+
import type { Jobs } from '@ultimabase/jobs'
|
|
7
|
+
import { jobsPlugin } from '@ultimabase/jobs'
|
|
8
|
+
import type {
|
|
9
|
+
Caller,
|
|
10
|
+
ExposedModel,
|
|
11
|
+
Logger,
|
|
12
|
+
PluginOf,
|
|
13
|
+
PluginTypes,
|
|
14
|
+
UseOf,
|
|
15
|
+
} from 'ultimabase'
|
|
16
|
+
import { definePlugin, isMaster, PublicError, Refused } from 'ultimabase'
|
|
17
|
+
import manifest from '../package.json' with { type: 'json' }
|
|
18
|
+
import { gatewayOf } from './accounts.ts'
|
|
19
|
+
import { catalogOf } from './apply.ts'
|
|
20
|
+
import type { CustomerProfile } from './billing-gateway.ts'
|
|
21
|
+
import type { Catalog } from './catalog.ts'
|
|
22
|
+
import { applyCatalog, planCatalog } from './catalog.ts'
|
|
23
|
+
import { describeStep } from './describe.ts'
|
|
24
|
+
import { stripeClient } from './gateway.ts'
|
|
25
|
+
import { closeJob, stripeJobs } from './jobs.ts'
|
|
26
|
+
import { ownKeys } from './keys.ts'
|
|
27
|
+
import type { Kind } from './kinds.ts'
|
|
28
|
+
import { billingModels } from './kinds.ts'
|
|
29
|
+
import { M, StripeCustomer, StripeEvent, StripeScan } from './models.ts'
|
|
30
|
+
import type { PortalOptions } from './portal.ts'
|
|
31
|
+
import type { Product } from './product.ts'
|
|
32
|
+
import type { Billing, Running } from './running.ts'
|
|
33
|
+
import { rowsOf, runningOf, useRunning } from './running.ts'
|
|
34
|
+
import { webhookRoutes } from './webhook.ts'
|
|
35
|
+
|
|
36
|
+
/** What `stripePlugin` takes (D-371 point 2). */
|
|
37
|
+
export interface StripeOptions {
|
|
38
|
+
/** `undefined`: the application starts, and payments are unavailable. */
|
|
39
|
+
readonly keys:
|
|
40
|
+
{ readonly secret: string; readonly webhook: string } | undefined
|
|
41
|
+
/** Every price's currency, in lowercase: `eur`. */
|
|
42
|
+
readonly currency: string
|
|
43
|
+
/** `'inclusive'`, by default, when the amounts include the taxes. */
|
|
44
|
+
readonly taxBehavior?: 'inclusive' | 'exclusive'
|
|
45
|
+
readonly products: readonly Product[]
|
|
46
|
+
readonly portal: PortalOptions
|
|
47
|
+
/**
|
|
48
|
+
* What Stripe shows of a payer, from its row: type the parameter with the
|
|
49
|
+
* payer's record, `(user: UserRecord) => ({ email: user.email })`.
|
|
50
|
+
*/
|
|
51
|
+
readonly customer?: (payer: never) => CustomerProfile
|
|
52
|
+
/** `/webhooks/stripe` by default. */
|
|
53
|
+
readonly webhookPath?: string
|
|
54
|
+
/** One live subscription per payer (D-373 point 6). */
|
|
55
|
+
readonly oneSubscription?: boolean
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** The Stripe plugin's types (D-57). */
|
|
59
|
+
export interface Stripe extends PluginTypes {
|
|
60
|
+
readonly name: 'stripe'
|
|
61
|
+
readonly appOptions: StripeOptions
|
|
62
|
+
readonly requires: Http | Jobs
|
|
63
|
+
readonly errors:
|
|
64
|
+
| 'PAYMENT_UNAVAILABLE'
|
|
65
|
+
| 'ALREADY_SUBSCRIBED'
|
|
66
|
+
| 'NOT_SUBSCRIBED'
|
|
67
|
+
| 'NOT_ENOUGH_CREDITS'
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const entry = 'stripePlugin'
|
|
71
|
+
const optionKeys = [
|
|
72
|
+
'keys',
|
|
73
|
+
'currency',
|
|
74
|
+
'taxBehavior',
|
|
75
|
+
'products',
|
|
76
|
+
'portal',
|
|
77
|
+
'customer',
|
|
78
|
+
'webhookPath',
|
|
79
|
+
'oneSubscription',
|
|
80
|
+
]
|
|
81
|
+
const names = {
|
|
82
|
+
subscription: 'defineSubscription',
|
|
83
|
+
purchase: 'definePurchase',
|
|
84
|
+
balance: 'defineBalance',
|
|
85
|
+
history: 'defineCreditHistory',
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** The keys, refused when one of them is unset. */
|
|
89
|
+
function keysOf(keys: unknown): StripeOptions['keys'] {
|
|
90
|
+
if (keys === undefined) return undefined
|
|
91
|
+
ownKeys(`${entry}'s keys`, keys, ['secret', 'webhook'])
|
|
92
|
+
const secret: unknown = Reflect.get(keys, 'secret')
|
|
93
|
+
const webhook: unknown = Reflect.get(keys, 'webhook')
|
|
94
|
+
if (typeof secret !== 'string' || !secret.startsWith('sk_')) {
|
|
95
|
+
throw new Refused(`${entry}: keys.secret is the secret key, sk_….`)
|
|
96
|
+
}
|
|
97
|
+
if (typeof webhook !== 'string' || !webhook.startsWith('whsec_')) {
|
|
98
|
+
throw new Refused(`${entry}: keys.webhook is the signing secret, whsec_….`)
|
|
99
|
+
}
|
|
100
|
+
return { secret, webhook }
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** The one model of `kind` among the application's, with its payer's. */
|
|
104
|
+
function billingOf(
|
|
105
|
+
models: readonly ExposedModel[],
|
|
106
|
+
kind: Kind,
|
|
107
|
+
): Billing | undefined {
|
|
108
|
+
const own = models.flatMap((model) => {
|
|
109
|
+
const declared = billingModels.get(model.queries)
|
|
110
|
+
return declared?.kind === kind ? [{ model, declared }] : []
|
|
111
|
+
})
|
|
112
|
+
const [first, second] = own
|
|
113
|
+
if (second !== undefined) {
|
|
114
|
+
throw new Refused(
|
|
115
|
+
`models lists two models ${names[kind]} returned: an application has one.`,
|
|
116
|
+
)
|
|
117
|
+
}
|
|
118
|
+
if (first === undefined) return undefined
|
|
119
|
+
const target = first.declared.payer()
|
|
120
|
+
const payer = models.find(({ queries }) => queries === target)
|
|
121
|
+
const name = first.model.schema.name
|
|
122
|
+
// The kernel refuses a relation to a model the application lacks.
|
|
123
|
+
if (payer === undefined) throw new TypeError(`${name}'s payer is unknown.`)
|
|
124
|
+
return {
|
|
125
|
+
name,
|
|
126
|
+
queries: rowsOf(first.model.queries),
|
|
127
|
+
payer: { name: payer.schema.name, queries: rowsOf(payer.queries) },
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
type Models = Pick<Running, 'subscription' | 'purchase' | 'balance' | 'history'>
|
|
132
|
+
|
|
133
|
+
/** Whether a product gives credits, by its price or with each of its prices. */
|
|
134
|
+
const givesCredits = (product: Product): boolean =>
|
|
135
|
+
'prices' in product
|
|
136
|
+
? Object.values(product.prices).some(({ gives = [] }) => gives.length > 0)
|
|
137
|
+
: product.gives.length > 0
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Refuses a product no model records, and credits without their history
|
|
141
|
+
* (D-372 point 5, D-374 point 1, D-377 point 2).
|
|
142
|
+
*/
|
|
143
|
+
function checkModels(products: readonly Product[], models: Models): void {
|
|
144
|
+
const { subscription, purchase, balance, history } = models
|
|
145
|
+
for (const other of [purchase, history]) {
|
|
146
|
+
if (other && balance && other.payer.name !== balance.payer.name) {
|
|
147
|
+
throw new Refused(
|
|
148
|
+
`${balance.name}'s owner and ${other.name}'s ${other === purchase ? 'payer' : 'owner'} are one model.`,
|
|
149
|
+
)
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
if (balance && !history) {
|
|
153
|
+
throw new Refused(
|
|
154
|
+
`${balance.name} needs its history: declare it with defineCreditHistory.`,
|
|
155
|
+
)
|
|
156
|
+
}
|
|
157
|
+
for (const product of products) {
|
|
158
|
+
if ('prices' in product && subscription === undefined) {
|
|
159
|
+
throw new Refused(
|
|
160
|
+
`${product.key} is a subscription: declare its model with defineSubscription.`,
|
|
161
|
+
)
|
|
162
|
+
}
|
|
163
|
+
if (givesCredits(product) && !balance) {
|
|
164
|
+
throw new Refused(
|
|
165
|
+
`${product.key} gives credits: declare their model with defineBalance.`,
|
|
166
|
+
)
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Compares the catalog with Stripe: applied with `NODE_ENV=development` and
|
|
173
|
+
* a test key, otherwise each difference is logged (D-372 point 4).
|
|
174
|
+
*/
|
|
175
|
+
async function compare(running: Running, logger: Logger): Promise<void> {
|
|
176
|
+
const { stripe, catalog } = running
|
|
177
|
+
if (stripe === undefined) return
|
|
178
|
+
const { gateway, live } = stripe
|
|
179
|
+
try {
|
|
180
|
+
const state = await gateway.readCatalog()
|
|
181
|
+
const steps = planCatalog(catalog, state)
|
|
182
|
+
if (steps.length === 0) return
|
|
183
|
+
const changes = steps.map((step) => describeStep(step, catalog.currency))
|
|
184
|
+
if (process.env['NODE_ENV'] !== 'development' || live) {
|
|
185
|
+
logger.warn(
|
|
186
|
+
{ changes },
|
|
187
|
+
'The Stripe catalog differs from the code: apply it with applyStripeCatalog.',
|
|
188
|
+
)
|
|
189
|
+
return
|
|
190
|
+
}
|
|
191
|
+
for (const change of changes) logger.info(`Stripe catalog: ${change}`)
|
|
192
|
+
await applyCatalog(catalog, gateway, state, steps)
|
|
193
|
+
} catch (error) {
|
|
194
|
+
logger.warn({ err: error }, 'The Stripe catalog could not be compared.')
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** Refuses a write to a billing model, and logs it (D-373 point 4). */
|
|
199
|
+
function refuse(caller: Caller, name: string, operation: string): never {
|
|
200
|
+
const details = { model: name, operation }
|
|
201
|
+
const callerId = caller.kind === 'user' ? caller.user.id : null
|
|
202
|
+
const message = `${name} ${operation} refused.`
|
|
203
|
+
runningOf(entry).logger.warn({ ...details, callerId }, message)
|
|
204
|
+
throw new PublicError('ACCESS_DENIED', message, { details })
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
type Facts = { readonly caller: Caller; readonly name: string }
|
|
208
|
+
|
|
209
|
+
/** Only Master, so the plugin, creates or updates a billing model. */
|
|
210
|
+
const masterOnly =
|
|
211
|
+
(operation: 'create' | 'update') =>
|
|
212
|
+
({ caller, name }: Facts): void => {
|
|
213
|
+
if (!isMaster(caller)) refuse(caller, name, operation)
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* A billing row goes with its payer, whoever deletes the payer (D-373 point
|
|
218
|
+
* 3), and alone only by Master; then its customer is closed. The hook runs
|
|
219
|
+
* in the delete's transaction after its one write: a payer still stored
|
|
220
|
+
* means the row went alone, and the refusal rolls the delete back.
|
|
221
|
+
*/
|
|
222
|
+
async function deleted(facts: Facts & { readonly record: object }) {
|
|
223
|
+
const { caller, name, record } = facts
|
|
224
|
+
const running = runningOf(entry)
|
|
225
|
+
const { subscription, purchase, balance, history } = running
|
|
226
|
+
const billing = [subscription, purchase, balance, history]
|
|
227
|
+
const model = billing.find((one) => one?.name === name)
|
|
228
|
+
// The row holds its payer as `{ id }`.
|
|
229
|
+
const ref: unknown =
|
|
230
|
+
Reflect.get(record, 'payer') ?? Reflect.get(record, 'owner')
|
|
231
|
+
const payer: unknown = Reflect.get(Object(ref), 'id')
|
|
232
|
+
if (model === undefined || typeof payer !== 'string') return
|
|
233
|
+
if (!isMaster(caller)) {
|
|
234
|
+
const where = { id: payer }
|
|
235
|
+
const kept = await model.payer.queries.findUnique({ where }, M)
|
|
236
|
+
if (kept !== null) refuse(caller, name, 'delete')
|
|
237
|
+
}
|
|
238
|
+
if (running.stripe === undefined) return
|
|
239
|
+
await closeJob.enqueue({ model: model.payer.name, payer })
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
const definition = definePlugin<Stripe>({
|
|
243
|
+
name: 'stripe',
|
|
244
|
+
manifest,
|
|
245
|
+
requires: { http: httpPlugin, jobs: jobsPlugin },
|
|
246
|
+
models: [StripeCustomer, StripeEvent, StripeScan],
|
|
247
|
+
api: ({ plugins, options }) => {
|
|
248
|
+
const { webhookPath = '/webhooks/stripe' } = options
|
|
249
|
+
if (typeof webhookPath !== 'string' || !webhookPath.startsWith('/')) {
|
|
250
|
+
throw new Refused(`${entry}: webhookPath is a path, as /webhooks/stripe.`)
|
|
251
|
+
}
|
|
252
|
+
plugins.http.mount(webhookRoutes(webhookPath))
|
|
253
|
+
plugins.jobs.add(stripeJobs)
|
|
254
|
+
},
|
|
255
|
+
hooks: {
|
|
256
|
+
beforeCreate: masterOnly('create'),
|
|
257
|
+
beforeUpdate: masterOnly('update'),
|
|
258
|
+
afterDelete: deleted,
|
|
259
|
+
},
|
|
260
|
+
start: async ({ options, models, logger }) => {
|
|
261
|
+
ownKeys(entry, options, optionKeys)
|
|
262
|
+
const keys = keysOf(options.keys)
|
|
263
|
+
const catalog: Catalog = catalogOf(entry, options)
|
|
264
|
+
const { customer, oneSubscription = false } = options
|
|
265
|
+
if (customer !== undefined && typeof customer !== 'function') {
|
|
266
|
+
throw new Refused(`${entry}: customer is (payer) => its profile.`)
|
|
267
|
+
}
|
|
268
|
+
if (typeof oneSubscription !== 'boolean') {
|
|
269
|
+
throw new Refused(`${entry}: oneSubscription is true or false.`)
|
|
270
|
+
}
|
|
271
|
+
const billing = {
|
|
272
|
+
subscription: billingOf(models, 'subscription'),
|
|
273
|
+
purchase: billingOf(models, 'purchase'),
|
|
274
|
+
balance: billingOf(models, 'balance'),
|
|
275
|
+
history: billingOf(models, 'history'),
|
|
276
|
+
}
|
|
277
|
+
checkModels(catalog.products, billing)
|
|
278
|
+
const running: Running = {
|
|
279
|
+
stripe:
|
|
280
|
+
keys === undefined
|
|
281
|
+
? undefined
|
|
282
|
+
: {
|
|
283
|
+
gateway: gatewayOf(keys.secret),
|
|
284
|
+
client: stripeClient(keys.secret),
|
|
285
|
+
webhook: keys.webhook,
|
|
286
|
+
live: keys.secret.includes('_live_'),
|
|
287
|
+
},
|
|
288
|
+
catalog,
|
|
289
|
+
products: new Map(catalog.products.map((one) => [one.key, one])),
|
|
290
|
+
customer,
|
|
291
|
+
oneSubscription,
|
|
292
|
+
...billing,
|
|
293
|
+
logger,
|
|
294
|
+
portal: undefined,
|
|
295
|
+
}
|
|
296
|
+
useRunning(running)
|
|
297
|
+
await compare(running, logger)
|
|
298
|
+
},
|
|
299
|
+
stop: () => {
|
|
300
|
+
useRunning(undefined)
|
|
301
|
+
},
|
|
302
|
+
})
|
|
303
|
+
|
|
304
|
+
/** Payments on Stripe's hosted pages; it requires `httpPlugin` and `jobsPlugin`. */
|
|
305
|
+
export const stripePlugin: PluginOf<Stripe> = definition.plugin
|
|
306
|
+
/** The plugin's entry in a billing model's `use`, which `define*` adds. */
|
|
307
|
+
export const stripeUse: UseOf<Stripe> = definition.use
|
package/src/portal.ts
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
// The customer portal's options (D-373 point 8), in Stripe's words: how a
|
|
2
|
+
// change of plan bills, which changes wait for the period's end, what a
|
|
3
|
+
// change during a trial does, and how a cancellation ends.
|
|
4
|
+
import { Refused } from 'ultimabase'
|
|
5
|
+
import type { PortalProduct, PortalSettings } from './gateway.ts'
|
|
6
|
+
import { ownKeys } from './keys.ts'
|
|
7
|
+
|
|
8
|
+
/** How the customer portal lets a payer change plan and cancel. */
|
|
9
|
+
export interface PortalOptions {
|
|
10
|
+
/** Where the portal's return link leads. */
|
|
11
|
+
readonly returnUrl: string
|
|
12
|
+
readonly termsUrl?: string
|
|
13
|
+
readonly privacyUrl?: string
|
|
14
|
+
/** `'invoiceNow'` charges a dearer plan's difference at once. */
|
|
15
|
+
readonly upgrades?: 'invoiceNow' | 'nextInvoice'
|
|
16
|
+
/** `'atPeriodEnd'` starts a cheaper or shorter plan at the period's end. */
|
|
17
|
+
readonly downgrades?: 'atPeriodEnd' | 'now'
|
|
18
|
+
/** `'endTrial'` ends a trial on a change, and charges the new plan. */
|
|
19
|
+
readonly trialChange?: 'endTrial' | 'keepTrial'
|
|
20
|
+
/** `'atPeriodEnd'` ends a canceled subscription at its period's end. */
|
|
21
|
+
readonly cancel?: 'atPeriodEnd' | 'now'
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Each option's values, in Stripe's words; the first is the default. */
|
|
25
|
+
const choices = {
|
|
26
|
+
upgrades: { invoiceNow: 'always_invoice', nextInvoice: 'create_prorations' },
|
|
27
|
+
downgrades: { atPeriodEnd: true, now: false },
|
|
28
|
+
trialChange: { endTrial: 'end_trial', keepTrial: 'continue_trial' },
|
|
29
|
+
cancel: { atPeriodEnd: 'at_period_end', now: 'immediately' },
|
|
30
|
+
} as const
|
|
31
|
+
const urls = ['returnUrl', 'termsUrl', 'privacyUrl'] as const
|
|
32
|
+
|
|
33
|
+
/** Refuses portal options Stripe would refuse, naming the option. */
|
|
34
|
+
export function checkPortal(portal: unknown): asserts portal is PortalOptions {
|
|
35
|
+
ownKeys('portal', portal, [...urls, ...Object.keys(choices)])
|
|
36
|
+
for (const name of urls) {
|
|
37
|
+
const url: unknown = Reflect.get(portal, name)
|
|
38
|
+
if (url === undefined && name !== 'returnUrl') continue
|
|
39
|
+
if (typeof url !== 'string' || !URL.canParse(url)) {
|
|
40
|
+
throw new Refused(`portal: ${name} is an absolute URL.`)
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
for (const [name, values] of Object.entries(choices)) {
|
|
44
|
+
const value: unknown = Reflect.get(portal, name)
|
|
45
|
+
if (value === undefined) continue
|
|
46
|
+
if (typeof value !== 'string' || !Object.hasOwn(values, value)) {
|
|
47
|
+
throw new Refused(
|
|
48
|
+
`portal: ${name} is ${Object.keys(values)
|
|
49
|
+
.map((one) => `'${one}'`)
|
|
50
|
+
.join(' or ')}.`,
|
|
51
|
+
)
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** The portal's settings, letting a subscription move to `products`. */
|
|
57
|
+
export const portalSettings = (
|
|
58
|
+
portal: PortalOptions,
|
|
59
|
+
products: readonly PortalProduct[] | null,
|
|
60
|
+
): PortalSettings => ({
|
|
61
|
+
returnUrl: portal.returnUrl,
|
|
62
|
+
termsUrl: portal.termsUrl ?? null,
|
|
63
|
+
privacyUrl: portal.privacyUrl ?? null,
|
|
64
|
+
prorationBehavior: choices.upgrades[portal.upgrades ?? 'invoiceNow'],
|
|
65
|
+
// A cheaper plan, or a shorter interval, waits for the period's end.
|
|
66
|
+
scheduleAtPeriodEnd: choices.downgrades[portal.downgrades ?? 'atPeriodEnd']
|
|
67
|
+
? ['decreasing_item_amount', 'shortening_interval']
|
|
68
|
+
: [],
|
|
69
|
+
trialUpdate: choices.trialChange[portal.trialChange ?? 'endTrial'],
|
|
70
|
+
cancelMode: choices.cancel[portal.cancel ?? 'atPeriodEnd'],
|
|
71
|
+
products,
|
|
72
|
+
active: true,
|
|
73
|
+
})
|
|
74
|
+
|
|
75
|
+
/** The settings in a string, whatever the order of their lists. */
|
|
76
|
+
const sorted = (settings: PortalSettings): string =>
|
|
77
|
+
JSON.stringify([
|
|
78
|
+
settings.returnUrl,
|
|
79
|
+
settings.termsUrl,
|
|
80
|
+
settings.privacyUrl,
|
|
81
|
+
settings.prorationBehavior,
|
|
82
|
+
settings.scheduleAtPeriodEnd.toSorted(),
|
|
83
|
+
settings.trialUpdate,
|
|
84
|
+
settings.cancelMode,
|
|
85
|
+
settings.active,
|
|
86
|
+
settings.products
|
|
87
|
+
?.map(({ productId, priceIds }) => [productId, priceIds.toSorted()])
|
|
88
|
+
.toSorted(([a], [b]) => String(a).localeCompare(String(b))),
|
|
89
|
+
])
|
|
90
|
+
|
|
91
|
+
/** Whether two settings are the same, whatever the order of their lists. */
|
|
92
|
+
export const samePortal = (
|
|
93
|
+
one: PortalSettings,
|
|
94
|
+
other: PortalSettings,
|
|
95
|
+
): boolean => sorted(one) === sorted(other)
|