@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/describe.ts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
// A catalog step in a line, as `applyStripeCatalog` prints its plan.
|
|
2
|
+
import type { CatalogStep } from './catalog.ts'
|
|
3
|
+
import type { Recurring, StripePrice } from './gateway.ts'
|
|
4
|
+
|
|
5
|
+
/** An amount in the currency's smallest unit, as `9.90 EUR`. */
|
|
6
|
+
const formatAmount = (amount: number, currency: string): string => {
|
|
7
|
+
const digits = Number(
|
|
8
|
+
new Intl.NumberFormat('en', {
|
|
9
|
+
style: 'currency',
|
|
10
|
+
currency,
|
|
11
|
+
}).resolvedOptions().maximumFractionDigits,
|
|
12
|
+
)
|
|
13
|
+
return `${(amount / 10 ** digits).toFixed(digits)} ${currency.toUpperCase()}`
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const often = (recurring: Recurring | null): string =>
|
|
17
|
+
recurring === null
|
|
18
|
+
? 'once'
|
|
19
|
+
: recurring.count === 1
|
|
20
|
+
? `every ${recurring.every}`
|
|
21
|
+
: `every ${String(recurring.count)} ${recurring.every}s`
|
|
22
|
+
|
|
23
|
+
const billing = (
|
|
24
|
+
amount: number | null,
|
|
25
|
+
currency: string,
|
|
26
|
+
recurring: Recurring | null,
|
|
27
|
+
): string =>
|
|
28
|
+
`${amount === null ? 'no amount' : formatAmount(amount, currency)} ${often(recurring)}`
|
|
29
|
+
|
|
30
|
+
const priceName = (price: StripePrice): string =>
|
|
31
|
+
price.lookupKey === null ? price.id : `${price.lookupKey} (${price.id})`
|
|
32
|
+
|
|
33
|
+
/** What an update changes of a product. */
|
|
34
|
+
const productChanges = (
|
|
35
|
+
step: Extract<CatalogStep, { readonly kind: 'updateProduct' }>,
|
|
36
|
+
): string => {
|
|
37
|
+
const { product, was } = step
|
|
38
|
+
return [
|
|
39
|
+
...(was.active ? [] : ['restore it']),
|
|
40
|
+
...(was.name === product.name
|
|
41
|
+
? []
|
|
42
|
+
: [`rename it from "${was.name}" to "${product.name}"`]),
|
|
43
|
+
...(was.taxCode === product.taxCode
|
|
44
|
+
? []
|
|
45
|
+
: [`set its tax code to ${product.taxCode ?? 'none'}`]),
|
|
46
|
+
].join(', ')
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The step in a line. */
|
|
50
|
+
export const describeStep = (step: CatalogStep, currency: string): string => {
|
|
51
|
+
if (step.kind === 'createProduct') {
|
|
52
|
+
return `create the product ${step.product.key}: "${step.product.name}"`
|
|
53
|
+
}
|
|
54
|
+
if (step.kind === 'updateProduct') {
|
|
55
|
+
return `update the product ${step.product.key}: ${productChanges(step)}`
|
|
56
|
+
}
|
|
57
|
+
if (step.kind === 'archiveProduct') {
|
|
58
|
+
return `archive the product "${step.was.name}" (${step.was.id})`
|
|
59
|
+
}
|
|
60
|
+
if (step.kind === 'createPrice') {
|
|
61
|
+
const { price, replaces } = step
|
|
62
|
+
const line = `create the price ${price.lookupKey}: ${billing(price.amount, currency, price.recurring)}`
|
|
63
|
+
return replaces === null
|
|
64
|
+
? line
|
|
65
|
+
: `${line}, replacing ${replaces.id} (${billing(replaces.amount, replaces.currency, replaces.recurring)})`
|
|
66
|
+
}
|
|
67
|
+
if (step.kind === 'updatePrice') {
|
|
68
|
+
return `update the nickname and metadata of the price ${priceName(step.was)}`
|
|
69
|
+
}
|
|
70
|
+
if (step.kind === 'archivePrice') {
|
|
71
|
+
return `archive the price ${priceName(step.was)}`
|
|
72
|
+
}
|
|
73
|
+
return step.id === null
|
|
74
|
+
? 'create the customer portal configuration'
|
|
75
|
+
: `update the customer portal configuration ${step.id}`
|
|
76
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// A payer's second subscription, with `oneSubscription` (D-373 point 6): a
|
|
2
|
+
// sync finds it, and a job ends it at once and refunds it. Its events then
|
|
3
|
+
// sync the payer again.
|
|
4
|
+
import type { Job } from '@ultimabase/jobs'
|
|
5
|
+
import { defineJob } from '@ultimabase/jobs'
|
|
6
|
+
import type { StripeSubscription } from './billing-gateway.ts'
|
|
7
|
+
import { liveStatuses } from './billing-gateway.ts'
|
|
8
|
+
import { strings } from './job-input.ts'
|
|
9
|
+
import { stripeOf } from './running.ts'
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* The live subscriptions beyond the first: the oldest stays. One still
|
|
13
|
+
* `incomplete` is not paid, and Stripe expires it within a day.
|
|
14
|
+
*/
|
|
15
|
+
export const duplicatesOf = (
|
|
16
|
+
subscriptions: readonly StripeSubscription[],
|
|
17
|
+
): readonly StripeSubscription[] =>
|
|
18
|
+
subscriptions
|
|
19
|
+
.filter(({ status }) => liveStatuses.includes(status))
|
|
20
|
+
.toSorted(
|
|
21
|
+
(one, other) =>
|
|
22
|
+
one.startedAt.getTime() - other.startedAt.getTime() ||
|
|
23
|
+
one.id.localeCompare(other.id),
|
|
24
|
+
)
|
|
25
|
+
.slice(1)
|
|
26
|
+
|
|
27
|
+
/** Ends a second subscription at once and refunds it: the payer paid twice. */
|
|
28
|
+
export const duplicateJob: Job<
|
|
29
|
+
'stripe.duplicate',
|
|
30
|
+
{ readonly subscription: string }
|
|
31
|
+
> = defineJob({
|
|
32
|
+
name: 'stripe.duplicate',
|
|
33
|
+
input: strings('subscription'),
|
|
34
|
+
// Each sync until it ends finds it again: one run at a time.
|
|
35
|
+
key: ({ subscription }) => subscription,
|
|
36
|
+
run: async ({ input, logger }) => {
|
|
37
|
+
await stripeOf('stripe.duplicate').gateway.cancelAndRefund(
|
|
38
|
+
input.subscription,
|
|
39
|
+
)
|
|
40
|
+
logger.error(
|
|
41
|
+
input,
|
|
42
|
+
'A payer’s second subscription was canceled and refunded.',
|
|
43
|
+
)
|
|
44
|
+
},
|
|
45
|
+
})
|
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
// The fake account's payers (D-371 point 8): customers, Checkouts a test
|
|
2
|
+
// pays, subscriptions and payments, and the thin events each change sends
|
|
3
|
+
// to the webhook, signed as Stripe signs them.
|
|
4
|
+
import { Stripe } from 'stripe'
|
|
5
|
+
import type {
|
|
6
|
+
BillingGateway,
|
|
7
|
+
CheckoutWrite,
|
|
8
|
+
RecoveryGateway,
|
|
9
|
+
CustomerProfile,
|
|
10
|
+
PortalWrite,
|
|
11
|
+
StripeInvoice,
|
|
12
|
+
StripePayment,
|
|
13
|
+
StripeSubscription,
|
|
14
|
+
} from './billing-gateway.ts'
|
|
15
|
+
import { Missing } from './billing-gateway.ts'
|
|
16
|
+
import type { StripePrice } from './gateway.ts'
|
|
17
|
+
|
|
18
|
+
/** A customer of the fake account. */
|
|
19
|
+
export interface FakeCustomer {
|
|
20
|
+
readonly id: string
|
|
21
|
+
readonly profile: CustomerProfile
|
|
22
|
+
readonly deleted: boolean
|
|
23
|
+
/** Its default card: the one a renewal charges (D-380). */
|
|
24
|
+
readonly card: string | null
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** A Checkout of the fake account. */
|
|
28
|
+
export interface FakeCheckout extends CheckoutWrite {
|
|
29
|
+
readonly id: string
|
|
30
|
+
readonly url: string
|
|
31
|
+
readonly status: 'open' | 'complete' | 'expired'
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** What the fake account holds of its payers, and what a test does at Stripe. */
|
|
35
|
+
export interface FakeBilling {
|
|
36
|
+
readonly webhookSecret: string
|
|
37
|
+
readonly customers: Map<string, FakeCustomer>
|
|
38
|
+
readonly checkouts: Map<string, FakeCheckout>
|
|
39
|
+
readonly subscriptions: Map<string, StripeSubscription>
|
|
40
|
+
readonly payments: Map<string, StripePayment>
|
|
41
|
+
/** The paid invoices of subscriptions, each period's. */
|
|
42
|
+
readonly invoices: Map<string, StripeInvoice>
|
|
43
|
+
/** Each portal session opened, in order. */
|
|
44
|
+
readonly portalSessions: PortalWrite[]
|
|
45
|
+
/** The subscriptions whose latest payment the plugin refunded. */
|
|
46
|
+
readonly subscriptionRefunds: Set<string>
|
|
47
|
+
/**
|
|
48
|
+
* Pays an open Checkout, by its URL, as its payer would; gives its id.
|
|
49
|
+
* `free`: a promotion code took the whole price, and Stripe makes no
|
|
50
|
+
* payment for a purchase.
|
|
51
|
+
*/
|
|
52
|
+
readonly pay: (url: string, options?: { readonly free?: boolean }) => string
|
|
53
|
+
/** Changes a subscription, as the portal or a renewal would. */
|
|
54
|
+
readonly update: (
|
|
55
|
+
id: string,
|
|
56
|
+
changes: Partial<Omit<StripeSubscription, 'id'>>,
|
|
57
|
+
) => void
|
|
58
|
+
/** Pays a subscription's next period, as Stripe renews it; gives its invoice. */
|
|
59
|
+
readonly renew: (id: string) => string
|
|
60
|
+
/** Refunds a payment or an invoice, all of it by default. */
|
|
61
|
+
readonly refund: (id: string, amount?: number) => void
|
|
62
|
+
readonly loseDispute: (id: string) => void
|
|
63
|
+
/** Deletes a customer, as the dashboard would. */
|
|
64
|
+
readonly deleteCustomer: (id: string) => void
|
|
65
|
+
/** Posts each event sent since the last call to the application at `url`. */
|
|
66
|
+
readonly deliver: (url: string, path?: string) => Promise<void>
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** A thin event's body, as Stripe sends it to an event destination. */
|
|
70
|
+
export const thinEvent = (event: {
|
|
71
|
+
readonly id?: string
|
|
72
|
+
/** Its v1 type: `customer.subscription.updated`. */
|
|
73
|
+
readonly type: string
|
|
74
|
+
/** Its related object: `{ id: 'sub_1', type: 'subscription' }`. */
|
|
75
|
+
readonly object: { readonly id: string; readonly type: string }
|
|
76
|
+
readonly livemode?: boolean
|
|
77
|
+
}): string =>
|
|
78
|
+
JSON.stringify({
|
|
79
|
+
id: event.id ?? `evt_${crypto.randomUUID().replaceAll('-', '')}`,
|
|
80
|
+
object: 'v2.core.event',
|
|
81
|
+
type: `v1.${event.type}`,
|
|
82
|
+
livemode: event.livemode ?? false,
|
|
83
|
+
created: new Date().toISOString(),
|
|
84
|
+
related_object: { ...event.object, url: `/v1/${event.object.id}` },
|
|
85
|
+
})
|
|
86
|
+
|
|
87
|
+
/** Posts `payload` to the webhook of the application at `url`, signed. */
|
|
88
|
+
export const postEvent = async (
|
|
89
|
+
url: string,
|
|
90
|
+
payload: string,
|
|
91
|
+
options: { readonly secret: string; readonly path?: string | undefined },
|
|
92
|
+
): Promise<Response> =>
|
|
93
|
+
fetch(`${url}${options.path ?? '/webhooks/stripe'}`, {
|
|
94
|
+
method: 'POST',
|
|
95
|
+
headers: {
|
|
96
|
+
'content-type': 'application/json',
|
|
97
|
+
'stripe-signature': Stripe.webhooks.generateTestHeaderString({
|
|
98
|
+
payload,
|
|
99
|
+
secret: options.secret,
|
|
100
|
+
}),
|
|
101
|
+
},
|
|
102
|
+
body: payload,
|
|
103
|
+
})
|
|
104
|
+
|
|
105
|
+
const found = <T>(map: ReadonlyMap<string, T>, id: string): T => {
|
|
106
|
+
const record = map.get(id)
|
|
107
|
+
if (record === undefined) throw new Missing(id)
|
|
108
|
+
return record
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const day = 24 * 60 * 60 * 1000
|
|
112
|
+
const days: Readonly<Record<string, number>> = {
|
|
113
|
+
day: 1,
|
|
114
|
+
week: 7,
|
|
115
|
+
month: 30,
|
|
116
|
+
year: 365,
|
|
117
|
+
}
|
|
118
|
+
const periodOf = ({ every, everyCount }: StripeSubscription): number =>
|
|
119
|
+
(days[every] ?? 30) * everyCount * day
|
|
120
|
+
|
|
121
|
+
/** The fake's billing, over its catalog's prices. */
|
|
122
|
+
export function fakeBilling(
|
|
123
|
+
prices: ReadonlyMap<string, StripePrice>,
|
|
124
|
+
newId: (prefix: string) => string,
|
|
125
|
+
): {
|
|
126
|
+
readonly gateway: BillingGateway & RecoveryGateway
|
|
127
|
+
readonly fake: FakeBilling
|
|
128
|
+
} {
|
|
129
|
+
const customers = new Map<string, FakeCustomer>()
|
|
130
|
+
const keys = new Map<string, string>()
|
|
131
|
+
const checkouts = new Map<string, FakeCheckout>()
|
|
132
|
+
const subscriptions = new Map<string, StripeSubscription>()
|
|
133
|
+
const payments = new Map<string, StripePayment>()
|
|
134
|
+
const invoices = new Map<string, StripeInvoice>()
|
|
135
|
+
const portalSessions: PortalWrite[] = []
|
|
136
|
+
const subscriptionRefunds = new Set<string>()
|
|
137
|
+
const sent: string[] = []
|
|
138
|
+
/** Each event's object and time, which Stripe lists for 30 days. */
|
|
139
|
+
const listed: { readonly id: string; readonly type: string; at: Date }[] = []
|
|
140
|
+
const send = (type: string, id: string, object: string) => {
|
|
141
|
+
sent.push(thinEvent({ type, object: { id, type: object } }))
|
|
142
|
+
listed.push({ id, type: object, at: new Date() })
|
|
143
|
+
}
|
|
144
|
+
const ownerOf = (type: string, id: string): string | null => {
|
|
145
|
+
const maps: Record<string, ReadonlyMap<string, { customerId: string }>> = {
|
|
146
|
+
'checkout.session': checkouts,
|
|
147
|
+
subscription: subscriptions,
|
|
148
|
+
payment_intent: payments,
|
|
149
|
+
invoice: invoices,
|
|
150
|
+
}
|
|
151
|
+
if (type === 'customer') return customers.has(id) ? id : null
|
|
152
|
+
return maps[type]?.get(id)?.customerId ?? null
|
|
153
|
+
}
|
|
154
|
+
const priceOf = (lookupKey: string): StripePrice => {
|
|
155
|
+
const held = [...prices.values()].find(
|
|
156
|
+
(one) => one.active && one.lookupKey === lookupKey,
|
|
157
|
+
)
|
|
158
|
+
if (held === undefined) throw new Error(`No price is ${lookupKey}.`)
|
|
159
|
+
return held
|
|
160
|
+
}
|
|
161
|
+
const live = (id: string): FakeCustomer => {
|
|
162
|
+
const customer = found(customers, id)
|
|
163
|
+
if (customer.deleted) throw new Missing(id)
|
|
164
|
+
return customer
|
|
165
|
+
}
|
|
166
|
+
/** Bills a subscription's period, which ends at `end`. */
|
|
167
|
+
const bill = (subscription: StripeSubscription, end: Date): string => {
|
|
168
|
+
const id = newId('in')
|
|
169
|
+
const { product, price, quantity, amount, customerId } = subscription
|
|
170
|
+
const periods = [{ product, price, quantity, end }]
|
|
171
|
+
const refunds = { refunded: 0, disputeLost: false }
|
|
172
|
+
invoices.set(id, { id, customerId, periods, amount, ...refunds })
|
|
173
|
+
send('invoice.paid', id, 'invoice')
|
|
174
|
+
return id
|
|
175
|
+
}
|
|
176
|
+
const subscribe = (checkout: FakeCheckout, price: StripePrice): string => {
|
|
177
|
+
const id = newId('sub')
|
|
178
|
+
const now = Date.now()
|
|
179
|
+
const { every = 'month', count = 1 } = price.recurring ?? {}
|
|
180
|
+
const trialEnd =
|
|
181
|
+
checkout.trialDays === null
|
|
182
|
+
? null
|
|
183
|
+
: new Date(now + checkout.trialDays * day)
|
|
184
|
+
const [product = '', name = ''] = checkout.lookupKey.split('.')
|
|
185
|
+
subscriptions.set(id, {
|
|
186
|
+
id,
|
|
187
|
+
customerId: checkout.customerId,
|
|
188
|
+
product,
|
|
189
|
+
price: name,
|
|
190
|
+
status: trialEnd === null ? 'active' : 'trialing',
|
|
191
|
+
quantity: checkout.quantity,
|
|
192
|
+
amount: (price.amount ?? 0) * checkout.quantity,
|
|
193
|
+
every,
|
|
194
|
+
everyCount: count,
|
|
195
|
+
currentPeriodEnd:
|
|
196
|
+
trialEnd ?? new Date(now + (days[every] ?? 30) * count * day),
|
|
197
|
+
cancelAt: null,
|
|
198
|
+
canceledAt: null,
|
|
199
|
+
trialEnd,
|
|
200
|
+
startedAt: new Date(now),
|
|
201
|
+
scheduled: null,
|
|
202
|
+
card: newId('pm'),
|
|
203
|
+
})
|
|
204
|
+
send('customer.subscription.created', id, 'subscription')
|
|
205
|
+
const created = found(subscriptions, id)
|
|
206
|
+
if (trialEnd === null) bill(created, created.currentPeriodEnd)
|
|
207
|
+
return id
|
|
208
|
+
}
|
|
209
|
+
const charge = (
|
|
210
|
+
checkout: FakeCheckout,
|
|
211
|
+
price: StripePrice,
|
|
212
|
+
free: boolean,
|
|
213
|
+
): string => {
|
|
214
|
+
// A free Checkout stands for its payment, which Stripe does not make.
|
|
215
|
+
const id = free ? checkout.id : newId('pi')
|
|
216
|
+
payments.set(id, {
|
|
217
|
+
id,
|
|
218
|
+
customerId: checkout.customerId,
|
|
219
|
+
product: checkout.product,
|
|
220
|
+
quantity: checkout.quantity,
|
|
221
|
+
amount: free ? 0 : (price.amount ?? 0) * checkout.quantity,
|
|
222
|
+
refunded: 0,
|
|
223
|
+
disputeLost: false,
|
|
224
|
+
paidAt: new Date(),
|
|
225
|
+
receiptUrl: free ? null : `https://pay.stripe.test/receipts/${id}`,
|
|
226
|
+
})
|
|
227
|
+
if (!free) send('payment_intent.succeeded', id, 'payment_intent')
|
|
228
|
+
return id
|
|
229
|
+
}
|
|
230
|
+
const gateway: BillingGateway & RecoveryGateway = {
|
|
231
|
+
createCustomer: async (profile, idempotencyKey) => {
|
|
232
|
+
const held = keys.get(idempotencyKey)
|
|
233
|
+
if (held !== undefined) return held
|
|
234
|
+
const id = newId('cus')
|
|
235
|
+
customers.set(id, { id, profile, deleted: false, card: null })
|
|
236
|
+
keys.set(idempotencyKey, id)
|
|
237
|
+
return id
|
|
238
|
+
},
|
|
239
|
+
updateCustomer: async (id, profile) => {
|
|
240
|
+
customers.set(id, { ...live(id), profile })
|
|
241
|
+
},
|
|
242
|
+
deleteCustomer: async (id) => {
|
|
243
|
+
fake.deleteCustomer(id)
|
|
244
|
+
},
|
|
245
|
+
readCustomer: async (id, options) => {
|
|
246
|
+
const customer = customers.get(id)
|
|
247
|
+
if (customer === undefined || customer.deleted) {
|
|
248
|
+
return { deleted: true, subscriptions: [], payments: [], invoices: [] }
|
|
249
|
+
}
|
|
250
|
+
const own = <T extends { readonly customerId: string }>(
|
|
251
|
+
map: ReadonlyMap<string, T>,
|
|
252
|
+
) => [...map.values()].filter((one) => one.customerId === id)
|
|
253
|
+
return {
|
|
254
|
+
deleted: false,
|
|
255
|
+
subscriptions: own(subscriptions),
|
|
256
|
+
// Stripe lists a free Checkout only when asked to.
|
|
257
|
+
payments: own(payments).filter(
|
|
258
|
+
(one) => options?.free === true || !one.id.startsWith('cs_'),
|
|
259
|
+
),
|
|
260
|
+
invoices: options?.invoices === true ? own(invoices) : [],
|
|
261
|
+
}
|
|
262
|
+
},
|
|
263
|
+
customerOf: async (type, id) => ownerOf(type, id),
|
|
264
|
+
openCheckout: async (checkout) => {
|
|
265
|
+
live(checkout.customerId)
|
|
266
|
+
priceOf(checkout.lookupKey)
|
|
267
|
+
const id = newId('cs')
|
|
268
|
+
const url = `https://checkout.stripe.test/${id}`
|
|
269
|
+
checkouts.set(id, { ...checkout, id, url, status: 'open' })
|
|
270
|
+
return url
|
|
271
|
+
},
|
|
272
|
+
expireCheckouts: async (customerId) => {
|
|
273
|
+
live(customerId)
|
|
274
|
+
for (const checkout of checkouts.values()) {
|
|
275
|
+
if (checkout.customerId === customerId && checkout.status === 'open') {
|
|
276
|
+
checkouts.set(checkout.id, { ...checkout, status: 'expired' })
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
},
|
|
280
|
+
checkoutCustomer: async (id) => checkouts.get(id)?.customerId ?? null,
|
|
281
|
+
openPortal: async (portal) => {
|
|
282
|
+
live(portal.customerId)
|
|
283
|
+
portalSessions.push(portal)
|
|
284
|
+
return `https://billing.stripe.test/${newId('bps')}`
|
|
285
|
+
},
|
|
286
|
+
moveCard: async ({ id, customerId, card }) => {
|
|
287
|
+
customers.set(customerId, { ...live(customerId), card })
|
|
288
|
+
fake.update(id, { card: null })
|
|
289
|
+
},
|
|
290
|
+
cancelAndRefund: async (id) => {
|
|
291
|
+
const held = found(subscriptions, id)
|
|
292
|
+
if (held.status !== 'canceled') {
|
|
293
|
+
const ended = { status: 'canceled', canceledAt: new Date() }
|
|
294
|
+
subscriptions.set(id, { ...held, ...ended })
|
|
295
|
+
send('customer.subscription.deleted', id, 'subscription')
|
|
296
|
+
}
|
|
297
|
+
subscriptionRefunds.add(id)
|
|
298
|
+
},
|
|
299
|
+
changedSince: async (since) => {
|
|
300
|
+
const changed = new Map<string, Date>()
|
|
301
|
+
for (const { id, type, at } of listed) {
|
|
302
|
+
const customer = ownerOf(type, id)
|
|
303
|
+
if (customer !== null && at > since) changed.set(customer, at)
|
|
304
|
+
}
|
|
305
|
+
return changed
|
|
306
|
+
},
|
|
307
|
+
}
|
|
308
|
+
const fake: FakeBilling = {
|
|
309
|
+
webhookSecret: `whsec_fake_${crypto.randomUUID()}`,
|
|
310
|
+
customers,
|
|
311
|
+
checkouts,
|
|
312
|
+
subscriptions,
|
|
313
|
+
payments,
|
|
314
|
+
invoices,
|
|
315
|
+
portalSessions,
|
|
316
|
+
subscriptionRefunds,
|
|
317
|
+
pay: (url, options) => {
|
|
318
|
+
const checkout = [...checkouts.values()].find((one) => one.url === url)
|
|
319
|
+
if (checkout?.status !== 'open') throw new Error(`${url} is not open.`)
|
|
320
|
+
const price = priceOf(checkout.lookupKey)
|
|
321
|
+
checkouts.set(checkout.id, { ...checkout, status: 'complete' })
|
|
322
|
+
const id =
|
|
323
|
+
checkout.mode === 'subscription'
|
|
324
|
+
? subscribe(checkout, price)
|
|
325
|
+
: charge(checkout, price, options?.free ?? false)
|
|
326
|
+
send('checkout.session.completed', checkout.id, 'checkout.session')
|
|
327
|
+
return id
|
|
328
|
+
},
|
|
329
|
+
update: (id, changes) => {
|
|
330
|
+
subscriptions.set(id, { ...found(subscriptions, id), ...changes })
|
|
331
|
+
send('customer.subscription.updated', id, 'subscription')
|
|
332
|
+
},
|
|
333
|
+
renew: (id) => {
|
|
334
|
+
const held = found(subscriptions, id)
|
|
335
|
+
const start = Math.max(held.currentPeriodEnd.getTime(), Date.now())
|
|
336
|
+
const end = new Date(start + periodOf(held))
|
|
337
|
+
const renewed = { ...held, status: 'active', currentPeriodEnd: end }
|
|
338
|
+
subscriptions.set(id, renewed)
|
|
339
|
+
send('customer.subscription.updated', id, 'subscription')
|
|
340
|
+
return bill(renewed, end)
|
|
341
|
+
},
|
|
342
|
+
refund: (id, amount) => {
|
|
343
|
+
const map: Map<string, StripePayment | StripeInvoice> = invoices.has(id)
|
|
344
|
+
? invoices
|
|
345
|
+
: payments
|
|
346
|
+
const paid = found(map, id)
|
|
347
|
+
const refunded = paid.refunded + (amount ?? paid.amount)
|
|
348
|
+
map.set(id, { ...paid, refunded })
|
|
349
|
+
send(
|
|
350
|
+
'charge.refunded',
|
|
351
|
+
id,
|
|
352
|
+
invoices.has(id) ? 'invoice' : 'payment_intent',
|
|
353
|
+
)
|
|
354
|
+
},
|
|
355
|
+
loseDispute: (id) => {
|
|
356
|
+
const map: Map<string, StripePayment | StripeInvoice> = invoices.has(id)
|
|
357
|
+
? invoices
|
|
358
|
+
: payments
|
|
359
|
+
map.set(id, { ...found(map, id), disputeLost: true })
|
|
360
|
+
send(
|
|
361
|
+
'charge.dispute.closed',
|
|
362
|
+
id,
|
|
363
|
+
invoices.has(id) ? 'invoice' : 'payment_intent',
|
|
364
|
+
)
|
|
365
|
+
},
|
|
366
|
+
deleteCustomer: (id) => {
|
|
367
|
+
const customer = customers.get(id)
|
|
368
|
+
if (customer === undefined || customer.deleted) return
|
|
369
|
+
customers.set(id, { ...customer, deleted: true })
|
|
370
|
+
for (const one of subscriptions.values()) {
|
|
371
|
+
if (one.customerId === id && one.status !== 'canceled') {
|
|
372
|
+
subscriptions.set(one.id, { ...one, status: 'canceled' })
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
send('customer.deleted', id, 'customer')
|
|
376
|
+
},
|
|
377
|
+
deliver: async (url, path) => {
|
|
378
|
+
for (const payload of sent.splice(0)) {
|
|
379
|
+
const secret = fake.webhookSecret
|
|
380
|
+
const response = await postEvent(url, payload, { secret, path })
|
|
381
|
+
if (!response.ok) {
|
|
382
|
+
throw new Error(`The webhook answered ${String(response.status)}.`)
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
},
|
|
386
|
+
}
|
|
387
|
+
return { gateway, fake }
|
|
388
|
+
}
|