@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.
Files changed (130) hide show
  1. package/README.md +2 -6
  2. package/package.json +3 -48
  3. package/dist/accounts.d.ts +0 -9
  4. package/dist/accounts.d.ts.map +0 -1
  5. package/dist/accounts.js +0 -20
  6. package/dist/apply.d.ts +0 -26
  7. package/dist/apply.d.ts.map +0 -1
  8. package/dist/apply.js +0 -73
  9. package/dist/audit.d.ts +0 -3
  10. package/dist/audit.d.ts.map +0 -1
  11. package/dist/audit.js +0 -123
  12. package/dist/billing-gateway.d.ts +0 -158
  13. package/dist/billing-gateway.d.ts.map +0 -1
  14. package/dist/billing-gateway.js +0 -23
  15. package/dist/billing.d.ts +0 -130
  16. package/dist/billing.d.ts.map +0 -1
  17. package/dist/billing.js +0 -128
  18. package/dist/calls.d.ts +0 -61
  19. package/dist/calls.d.ts.map +0 -1
  20. package/dist/calls.js +0 -172
  21. package/dist/catalog.d.ts +0 -54
  22. package/dist/catalog.d.ts.map +0 -1
  23. package/dist/catalog.js +0 -182
  24. package/dist/credit.d.ts +0 -16
  25. package/dist/credit.d.ts.map +0 -1
  26. package/dist/credit.js +0 -18
  27. package/dist/credits.d.ts +0 -38
  28. package/dist/credits.d.ts.map +0 -1
  29. package/dist/credits.js +0 -138
  30. package/dist/customer.d.ts +0 -25
  31. package/dist/customer.d.ts.map +0 -1
  32. package/dist/customer.js +0 -88
  33. package/dist/describe.d.ts +0 -4
  34. package/dist/describe.d.ts.map +0 -1
  35. package/dist/describe.js +0 -56
  36. package/dist/duplicates.d.ts +0 -12
  37. package/dist/duplicates.d.ts.map +0 -1
  38. package/dist/duplicates.js +0 -24
  39. package/dist/fake-billing.d.ts +0 -72
  40. package/dist/fake-billing.d.ts.map +0 -1
  41. package/dist/fake-billing.js +0 -290
  42. package/dist/gateway.d.ts +0 -108
  43. package/dist/gateway.d.ts.map +0 -1
  44. package/dist/gateway.js +0 -196
  45. package/dist/index.d.ts +0 -15
  46. package/dist/index.d.ts.map +0 -1
  47. package/dist/index.js +0 -6
  48. package/dist/job-input.d.ts +0 -6
  49. package/dist/job-input.d.ts.map +0 -1
  50. package/dist/job-input.js +0 -20
  51. package/dist/jobs.d.ts +0 -16
  52. package/dist/jobs.d.ts.map +0 -1
  53. package/dist/jobs.js +0 -189
  54. package/dist/keys.d.ts +0 -10
  55. package/dist/keys.d.ts.map +0 -1
  56. package/dist/keys.js +0 -30
  57. package/dist/kinds.d.ts +0 -11
  58. package/dist/kinds.d.ts.map +0 -1
  59. package/dist/kinds.js +0 -4
  60. package/dist/models.d.ts +0 -71
  61. package/dist/models.d.ts.map +0 -1
  62. package/dist/models.js +0 -41
  63. package/dist/plugin.d.ts +0 -41
  64. package/dist/plugin.d.ts.map +0 -1
  65. package/dist/plugin.js +0 -229
  66. package/dist/portal.d.ts +0 -23
  67. package/dist/portal.d.ts.map +0 -1
  68. package/dist/portal.js +0 -66
  69. package/dist/product.d.ts +0 -57
  70. package/dist/product.d.ts.map +0 -1
  71. package/dist/product.js +0 -113
  72. package/dist/running.d.ts +0 -61
  73. package/dist/running.d.ts.map +0 -1
  74. package/dist/running.js +0 -35
  75. package/dist/sdk-billing.d.ts +0 -8
  76. package/dist/sdk-billing.d.ts.map +0 -1
  77. package/dist/sdk-billing.js +0 -200
  78. package/dist/sdk-common.d.ts +0 -13
  79. package/dist/sdk-common.d.ts.map +0 -1
  80. package/dist/sdk-common.js +0 -41
  81. package/dist/sdk-customer.d.ts +0 -9
  82. package/dist/sdk-customer.d.ts.map +0 -1
  83. package/dist/sdk-customer.js +0 -149
  84. package/dist/sdk-invoices.d.ts +0 -10
  85. package/dist/sdk-invoices.d.ts.map +0 -1
  86. package/dist/sdk-invoices.js +0 -53
  87. package/dist/sdk-recovery.d.ts +0 -5
  88. package/dist/sdk-recovery.d.ts.map +0 -1
  89. package/dist/sdk-recovery.js +0 -81
  90. package/dist/sync.d.ts +0 -8
  91. package/dist/sync.d.ts.map +0 -1
  92. package/dist/sync.js +0 -196
  93. package/dist/testing.d.ts +0 -24
  94. package/dist/testing.d.ts.map +0 -1
  95. package/dist/testing.js +0 -100
  96. package/dist/webhook.d.ts +0 -4
  97. package/dist/webhook.d.ts.map +0 -1
  98. package/dist/webhook.js +0 -73
  99. package/src/accounts.ts +0 -30
  100. package/src/apply.ts +0 -99
  101. package/src/audit.ts +0 -171
  102. package/src/billing-gateway.ts +0 -188
  103. package/src/billing.ts +0 -361
  104. package/src/calls.ts +0 -280
  105. package/src/catalog.ts +0 -327
  106. package/src/credit.ts +0 -36
  107. package/src/credits.ts +0 -206
  108. package/src/customer.ts +0 -113
  109. package/src/describe.ts +0 -76
  110. package/src/duplicates.ts +0 -45
  111. package/src/fake-billing.ts +0 -388
  112. package/src/gateway.ts +0 -333
  113. package/src/index.ts +0 -35
  114. package/src/job-input.ts +0 -24
  115. package/src/jobs.ts +0 -230
  116. package/src/keys.ts +0 -40
  117. package/src/kinds.ts +0 -15
  118. package/src/models.ts +0 -107
  119. package/src/plugin.ts +0 -307
  120. package/src/portal.ts +0 -95
  121. package/src/product.ts +0 -203
  122. package/src/running.ts +0 -104
  123. package/src/sdk-billing.ts +0 -220
  124. package/src/sdk-common.ts +0 -57
  125. package/src/sdk-customer.ts +0 -203
  126. package/src/sdk-invoices.ts +0 -81
  127. package/src/sdk-recovery.ts +0 -93
  128. package/src/sync.ts +0 -246
  129. package/src/testing.ts +0 -135
  130. package/src/webhook.ts +0 -100
@@ -1,203 +0,0 @@
1
- // What a customer holds at Stripe, read for its sync: its subscriptions,
2
- // the one-time payments the plugin opened, its Checkouts a full discount
3
- // made free, and its subscriptions' paid invoices.
4
- import type { Stripe } from 'stripe'
5
- import type {
6
- CustomerState,
7
- StripePayment,
8
- StripeSubscription,
9
- } from './billing-gateway.ts'
10
- import { managedBy } from './gateway.ts'
11
- import { all, dateOf, keysOf, maybeDate, refOf } from './sdk-common.ts'
12
- import { invoicesOf } from './sdk-invoices.ts'
13
-
14
- /** A subscription's next phase, when its schedule holds one. */
15
- async function scheduledOf(
16
- client: Stripe,
17
- schedule: Stripe.Subscription['schedule'],
18
- ): Promise<StripeSubscription['scheduled']> {
19
- if (schedule === null || typeof schedule === 'string') return null
20
- const now = Date.now() / 1000
21
- const next = schedule.phases.find(({ start_date }) => start_date > now)
22
- const item = next?.items[0]
23
- if (next === undefined || item === undefined) return null
24
- const price =
25
- typeof item.price === 'string'
26
- ? await client.prices.retrieve(item.price)
27
- : item.price
28
- return { ...keysOf(price), at: dateOf(next.start_date) }
29
- }
30
-
31
- async function subscriptionOf(
32
- client: Stripe,
33
- subscription: Stripe.Subscription,
34
- ): Promise<StripeSubscription> {
35
- const item = subscription.items.data[0]
36
- const quantity = item?.quantity ?? 1
37
- const recurring = item?.price.recurring
38
- const cancelAt =
39
- subscription.cancel_at ??
40
- (subscription.cancel_at_period_end
41
- ? (item?.current_period_end ?? null)
42
- : null)
43
- return {
44
- id: subscription.id,
45
- customerId: refOf(subscription.customer) ?? '',
46
- ...(item === undefined
47
- ? { product: null, price: null }
48
- : keysOf(item.price)),
49
- status: subscription.status,
50
- quantity,
51
- amount: (item?.price.unit_amount ?? 0) * quantity,
52
- every: recurring?.interval ?? 'month',
53
- everyCount: recurring?.interval_count ?? 1,
54
- currentPeriodEnd: dateOf(
55
- item?.current_period_end ?? subscription.start_date,
56
- ),
57
- cancelAt: maybeDate(cancelAt),
58
- canceledAt: maybeDate(subscription.canceled_at),
59
- trialEnd: maybeDate(subscription.trial_end),
60
- startedAt: dateOf(subscription.start_date),
61
- scheduled: await scheduledOf(client, subscription.schedule),
62
- card:
63
- subscription.metadata['managedBy'] === managedBy
64
- ? refOf(subscription.default_payment_method)
65
- : null,
66
- }
67
- }
68
-
69
- /** The quantity a Checkout wrote to its payment, one when it wrote none. */
70
- const quantityOf = (value: string | undefined): number => {
71
- const quantity = Number(value)
72
- return Number.isSafeInteger(quantity) && quantity > 0 ? quantity : 1
73
- }
74
-
75
- async function paymentOf(
76
- client: Stripe,
77
- intent: Stripe.PaymentIntent,
78
- ): Promise<StripePayment> {
79
- const charge =
80
- intent.latest_charge === null || typeof intent.latest_charge === 'string'
81
- ? null
82
- : intent.latest_charge
83
- const disputes =
84
- charge?.disputed === true
85
- ? await all(client.disputes.list({ payment_intent: intent.id }))
86
- : []
87
- return {
88
- id: intent.id,
89
- customerId: refOf(intent.customer) ?? '',
90
- product: intent.metadata['product'] ?? null,
91
- quantity: quantityOf(intent.metadata['quantity']),
92
- amount: intent.amount_received,
93
- refunded: charge?.amount_refunded ?? 0,
94
- disputeLost: disputes.some(({ status }) => status === 'lost'),
95
- paidAt: dateOf(intent.created),
96
- receiptUrl: charge?.receipt_url ?? null,
97
- }
98
- }
99
-
100
- /**
101
- * A Checkout of the plugin's that a full discount made free: Stripe makes
102
- * no payment for it, so it stands for one.
103
- */
104
- const freeOf = (session: Stripe.Checkout.Session): StripePayment => ({
105
- id: session.id,
106
- customerId: refOf(session.customer) ?? '',
107
- product: session.metadata?.['product'] ?? null,
108
- quantity: quantityOf(session.metadata?.['quantity']),
109
- amount: 0,
110
- refunded: 0,
111
- disputeLost: false,
112
- paidAt: dateOf(session.created),
113
- receiptUrl: null,
114
- })
115
-
116
- const isFree = (session: Stripe.Checkout.Session): boolean =>
117
- session.mode === 'payment' &&
118
- session.payment_intent === null &&
119
- session.metadata?.['managedBy'] === managedBy
120
-
121
- export const gone: CustomerState = {
122
- deleted: true,
123
- subscriptions: [],
124
- payments: [],
125
- invoices: [],
126
- }
127
-
128
- const day = 24 * 60 * 60
129
-
130
- /** What a customer holds; its invoices and free Checkouts, if asked. */
131
- export async function stateOf(
132
- client: Stripe,
133
- id: string,
134
- asked: { readonly invoices: boolean; readonly free: boolean },
135
- ): Promise<CustomerState> {
136
- const customer = await client.customers.retrieve(id)
137
- if (customer.deleted === true) return gone
138
- // A refund comes within the year; a paid period, within its own.
139
- const created = { gte: Math.floor(Date.now() / 1000) - 400 * day }
140
- const [subscriptions, intents, invoices, sessions] = await Promise.all([
141
- all(
142
- client.subscriptions.list({
143
- customer: id,
144
- status: 'all',
145
- limit: 100,
146
- expand: ['data.schedule'],
147
- }),
148
- ),
149
- all(
150
- client.paymentIntents.list({
151
- customer: id,
152
- limit: 100,
153
- expand: ['data.latest_charge'],
154
- }),
155
- ),
156
- asked.invoices
157
- ? all(
158
- client.invoices.list({
159
- customer: id,
160
- status: 'paid',
161
- created,
162
- limit: 100,
163
- expand: ['data.payments'],
164
- }),
165
- )
166
- : [],
167
- asked.free
168
- ? all(
169
- client.checkout.sessions.list({
170
- customer: id,
171
- status: 'complete',
172
- created,
173
- limit: 100,
174
- }),
175
- )
176
- : [],
177
- ])
178
- const succeeded = intents.filter(({ status }) => status === 'succeeded')
179
- const paid = await Promise.all(
180
- succeeded.map(async (one) => paymentOf(client, one)),
181
- )
182
- // The plugin's one-time payments; the others paid invoices.
183
- const opened = new Set(
184
- succeeded
185
- .filter(({ metadata }) => metadata['managedBy'] === managedBy)
186
- .map(({ id: intent }) => intent),
187
- )
188
- return {
189
- deleted: false,
190
- subscriptions: await Promise.all(
191
- subscriptions.map(async (one) => subscriptionOf(client, one)),
192
- ),
193
- payments: [
194
- ...paid.filter((one) => opened.has(one.id)),
195
- ...sessions.filter(isFree).map(freeOf),
196
- ],
197
- invoices: await invoicesOf(
198
- client,
199
- invoices,
200
- new Map(paid.map((one) => [one.id, one])),
201
- ),
202
- }
203
- }
@@ -1,81 +0,0 @@
1
- // A subscription's paid invoices, as their credits read them (D-377 point
2
- // 4): the lines that bill a whole period above zero, and what was refunded
3
- // or lost to a dispute of the payments that paid them.
4
- import type { Stripe } from 'stripe'
5
- import type {
6
- PriceKeys,
7
- StripeInvoice,
8
- StripePayment,
9
- } from './billing-gateway.ts'
10
- import { all, dateOf, keysOf, refOf } from './sdk-common.ts'
11
-
12
- type Period = StripeInvoice['periods'][number]
13
- type Keys = (price: string | Stripe.Price) => Promise<PriceKeys>
14
-
15
- /** A price's keys, each price read once. */
16
- function priceKeys(client: Stripe): Keys {
17
- const read = new Map<string, Promise<PriceKeys>>()
18
- return async (price) => {
19
- if (typeof price !== 'string') return keysOf(price)
20
- const held = read.get(price) ?? client.prices.retrieve(price).then(keysOf)
21
- read.set(price, held)
22
- return held
23
- }
24
- }
25
-
26
- /** Whether a line bills a whole period above zero: no proration, no trial. */
27
- const billsPeriod = (line: Stripe.InvoiceLineItem): boolean =>
28
- line.amount > 0 && line.parent?.subscription_item_details?.proration === false
29
-
30
- async function periodsOf(
31
- client: Stripe,
32
- invoice: Stripe.Invoice,
33
- keys: Keys,
34
- ): Promise<Period[]> {
35
- const lines =
36
- invoice.lines.has_more && invoice.id !== undefined
37
- ? await all(client.invoices.listLineItems(invoice.id, { limit: 100 }))
38
- : invoice.lines.data
39
- return Promise.all(
40
- lines.filter(billsPeriod).flatMap((line) => {
41
- const price = line.pricing?.price_details?.price
42
- if (price === undefined) return []
43
- const quantity = line.quantity ?? 1
44
- const end = dateOf(line.period.end)
45
- return [keys(price).then((held) => ({ ...held, quantity, end }))]
46
- }),
47
- )
48
- }
49
-
50
- /**
51
- * The paid invoices, with the periods they bill and the refunds and
52
- * disputes of the payments that paid them, from the customer's `payments`
53
- * by id. An invoice whose periods ended is kept: its refund takes back what
54
- * it gave.
55
- */
56
- export async function invoicesOf(
57
- client: Stripe,
58
- invoices: readonly Stripe.Invoice[],
59
- payments: ReadonlyMap<string, StripePayment>,
60
- ): Promise<StripeInvoice[]> {
61
- const keys = priceKeys(client)
62
- return Promise.all(
63
- invoices.map(async (invoice) => {
64
- const paidBy = (invoice.payments?.data ?? [])
65
- .filter(({ status }) => status === 'paid')
66
- .flatMap(({ payment }) => {
67
- const intent = refOf(payment.payment_intent ?? null)
68
- const held = intent === null ? undefined : payments.get(intent)
69
- return held === undefined ? [] : [held]
70
- })
71
- return {
72
- id: invoice.id ?? '',
73
- customerId: refOf(invoice.customer) ?? '',
74
- periods: await periodsOf(client, invoice, keys),
75
- amount: invoice.amount_paid,
76
- refunded: paidBy.reduce((sum, one) => sum + one.refunded, 0),
77
- disputeLost: paidBy.some(({ disputeLost }) => disputeLost),
78
- }
79
- }),
80
- )
81
- }
@@ -1,93 +0,0 @@
1
- // What the plugin asks Stripe's API to set right what went wrong (D-375):
2
- // a payer's second subscription ended and refunded, and the customers that
3
- // Stripe's events changed, for the hourly job to find what a lost webhook
4
- // missed.
5
- import { Stripe } from 'stripe'
6
- import type { RecoveryGateway } from './billing-gateway.ts'
7
- import { ownerOf } from './sdk-billing.ts'
8
- import { all, guarded, refOf } from './sdk-common.ts'
9
-
10
- /** The statuses Stripe no longer changes. */
11
- const ended = new Set(['canceled', 'incomplete_expired'])
12
-
13
- /** Whether Stripe refused a refund the payment no longer needs. */
14
- const refundedAlready = (error: unknown): boolean =>
15
- error instanceof Stripe.errors.StripeInvalidRequestError &&
16
- (error.code === 'charge_already_refunded' || error.code === 'charge_disputed')
17
-
18
- async function cancelAndRefund(client: Stripe, id: string): Promise<void> {
19
- const subscription = await client.subscriptions.retrieve(id)
20
- if (!ended.has(subscription.status)) {
21
- await client.subscriptions.cancel(id, { prorate: false })
22
- }
23
- const invoice = refOf(subscription.latest_invoice)
24
- if (invoice === null) return
25
- const paid = await all(
26
- client.invoicePayments.list({ invoice, status: 'paid', limit: 100 }),
27
- )
28
- for (const { payment } of paid) {
29
- const intent = refOf(payment.payment_intent ?? null)
30
- const charge = refOf(payment.charge ?? null)
31
- const target =
32
- intent === null
33
- ? charge === null
34
- ? undefined
35
- : { charge }
36
- : { payment_intent: intent }
37
- if (target === undefined) continue
38
- try {
39
- // The key makes a retried job refund once.
40
- await client.refunds.create(target, {
41
- idempotencyKey: `refund-${intent ?? charge ?? ''}`,
42
- })
43
- } catch (error) {
44
- if (!refundedAlready(error)) throw error
45
- }
46
- }
47
- }
48
-
49
- /** The customer an event's object belongs to, from the event alone. */
50
- async function ownerOfEvent(
51
- client: Stripe,
52
- event: Stripe.Event,
53
- ): Promise<string | null> {
54
- const object: unknown = event.data.object
55
- const kind: unknown = Reflect.get(Object(object), 'object')
56
- const id: unknown = Reflect.get(Object(object), 'id')
57
- if (kind === 'customer' && typeof id === 'string') return id
58
- const customer: unknown = Reflect.get(Object(object), 'customer')
59
- if (typeof customer === 'string') return customer
60
- const nested: unknown = Reflect.get(Object(customer), 'id')
61
- if (typeof nested === 'string') return nested
62
- // A dispute names its charge only.
63
- if (kind === 'dispute' && typeof id === 'string') {
64
- return refOf(await ownerOf(client, 'dispute', id))
65
- }
66
- return null
67
- }
68
-
69
- async function changedSince(
70
- client: Stripe,
71
- since: Date,
72
- ): Promise<ReadonlyMap<string, Date>> {
73
- const changed = new Map<string, Date>()
74
- const created = { gt: Math.floor(since.getTime() / 1000) }
75
- // Stripe lists its events for 30 days, the newest first.
76
- for await (const event of client.events.list({ created, limit: 100 })) {
77
- const customer = await ownerOfEvent(client, event)
78
- const at = new Date(event.created * 1000)
79
- const known = customer === null ? undefined : changed.get(customer)
80
- if (customer !== null && (known === undefined || known < at)) {
81
- changed.set(customer, at)
82
- }
83
- }
84
- return changed
85
- }
86
-
87
- /** The recovery gateway over Stripe's API. */
88
- export const sdkRecovery = (client: Stripe): RecoveryGateway => ({
89
- cancelAndRefund: async (id) =>
90
- guarded(id, async () => cancelAndRefund(client, id)),
91
- changedSince: async (since) =>
92
- guarded('events', async () => changedSince(client, since)),
93
- })
package/src/sync.ts DELETED
@@ -1,246 +0,0 @@
1
- // A payer's sync (D-371 point 4, D-375): what Stripe holds now is written
2
- // to the application's subscription and purchase rows, so events out of
3
- // order or lost leave nothing stale. Stripe is read outside any transaction;
4
- // the write takes the customer's lock.
5
- import { transaction } from 'ultimabase'
6
- import type {
7
- CustomerState,
8
- StripeInvoice,
9
- StripePayment,
10
- StripeSubscription,
11
- } from './billing-gateway.ts'
12
- import { liveStatuses } from './billing-gateway.ts'
13
- import { lost, settleCredits, totals } from './credits.ts'
14
- import type { Customer } from './customer.ts'
15
- import { duplicateJob, duplicatesOf } from './duplicates.ts'
16
- import { M, StripeCustomer } from './models.ts'
17
- import type { Billing, Row, Running } from './running.ts'
18
- import { runningOf, stripeOf } from './running.ts'
19
-
20
- /** The model when its payer is the customer's, else nothing to write. */
21
- const ownModel = (model: Billing | undefined, row: Customer) =>
22
- model?.payer.name === row.model ? model : undefined
23
-
24
- const connect = (id: string) => ({ connect: { id } })
25
-
26
- /** Whether the row holds each value already. */
27
- const holds = (row: Row, values: Readonly<Record<string, unknown>>) =>
28
- Object.entries(values).every(([field, value]) => {
29
- const held = row[field]
30
- return value instanceof Date && held instanceof Date
31
- ? value.getTime() === held.getTime()
32
- : held === value
33
- })
34
-
35
- /**
36
- * Creates the row of `stripeId`, or updates it when one of its values
37
- * changed: a sync that finds it unchanged writes nothing, so the model's
38
- * hooks run on a change only. The customer's lock is held.
39
- */
40
- async function save(
41
- model: Billing,
42
- stripeId: string,
43
- create: object,
44
- values: Readonly<Record<string, unknown>>,
45
- ): Promise<void> {
46
- const row = await model.queries.findUnique({ where: { stripeId } }, M)
47
- if (row === null) {
48
- const data = { ...create, ...values, stripeId }
49
- await model.queries.create({ data }, M)
50
- } else if (!holds(row, values)) {
51
- await model.queries.update({ where: { id: row.id }, data: values }, M)
52
- }
53
- }
54
-
55
- async function writeSubscription(
56
- model: Billing,
57
- row: Customer,
58
- one: StripeSubscription,
59
- ): Promise<void> {
60
- if (one.product === null || one.price === null) return
61
- const values = {
62
- product: one.product,
63
- price: one.price,
64
- status: one.status,
65
- quantity: one.quantity,
66
- amount: one.amount,
67
- every: one.every,
68
- everyCount: one.everyCount,
69
- currentPeriodEnd: one.currentPeriodEnd,
70
- cancelAt: one.cancelAt,
71
- canceledAt: one.canceledAt,
72
- trialEnd: one.trialEnd,
73
- startedAt: one.startedAt,
74
- scheduledProduct: one.scheduled?.product ?? null,
75
- scheduledPrice: one.scheduled?.price ?? null,
76
- scheduledAt: one.scheduled?.at ?? null,
77
- }
78
- await save(model, one.id, { payer: connect(row.payer) }, values)
79
- }
80
-
81
- async function writePayment(
82
- running: Running,
83
- row: Customer,
84
- payment: StripePayment,
85
- ): Promise<void> {
86
- const product =
87
- payment.product === null ? undefined : running.products.get(payment.product)
88
- if (product === undefined) return
89
- const purchase = ownModel(running.purchase, row)
90
- if (purchase !== undefined) {
91
- const refunded = payment.disputeLost ? payment.amount : payment.refunded
92
- const values = {
93
- amount: payment.amount,
94
- refunded,
95
- // A free purchase, after a full discount, is paid, not refunded.
96
- status: lost(payment) ? 'refunded' : 'paid',
97
- receiptUrl: payment.receiptUrl,
98
- }
99
- const create = {
100
- product: product.key,
101
- quantity: payment.quantity,
102
- paidAt: payment.paidAt,
103
- payer: connect(row.payer),
104
- }
105
- await save(purchase, payment.id, create, values)
106
- }
107
- if (!('prices' in product) && ownModel(running.balance, row) !== undefined) {
108
- const sums = totals(product.gives, payment.quantity)
109
- await settleCredits(row.payer, payment, sums, 'purchase')
110
- }
111
- }
112
-
113
- /**
114
- * Gives what the invoice's periods give, for the periods not ended yet: a
115
- * `gives` added later pays nothing for the past (D-377 point 4).
116
- */
117
- async function writeInvoice(
118
- running: Running,
119
- row: Customer,
120
- invoice: StripeInvoice,
121
- readAt: Date,
122
- ): Promise<void> {
123
- const sums = new Map<string, number>()
124
- for (const { product: key, price, quantity, end } of invoice.periods) {
125
- const product = key === null ? undefined : running.products.get(key)
126
- if (end <= readAt || price === null || !product || !('prices' in product)) {
127
- continue
128
- }
129
- totals(product.prices[price]?.gives ?? [], quantity, sums)
130
- }
131
- if (sums.size === 0 && !lost(invoice)) return
132
- await settleCredits(row.payer, invoice, sums, 'subscription')
133
- }
134
-
135
- /** Whether a recurring price gives credits: then the sync reads invoices. */
136
- const readsInvoices = ({ products, balance }: Running): boolean =>
137
- balance !== undefined &&
138
- [...products.values()].some(
139
- (product) =>
140
- 'prices' in product &&
141
- Object.values(product.prices).some(({ gives }) => gives !== undefined),
142
- )
143
-
144
- /** The next time one of the live subscriptions changes by itself. */
145
- function renewsAt(state: CustomerState): Date | null {
146
- const times = state.subscriptions
147
- .filter(({ status }) => liveStatuses.includes(status))
148
- .flatMap((one) => [
149
- one.currentPeriodEnd,
150
- one.cancelAt,
151
- one.trialEnd,
152
- one.scheduled?.at ?? null,
153
- ])
154
- .filter((time) => time !== null)
155
- .map((time) => time.getTime())
156
- return times.length === 0 ? null : new Date(Math.min(...times))
157
- }
158
-
159
- /** Ends the live rows of a customer Stripe deleted, and forgets it. */
160
- async function forget(running: Running, row: Customer): Promise<void> {
161
- const subscription = ownModel(running.subscription, row)
162
- if (subscription !== undefined) {
163
- const where = {
164
- payer: { is: { id: row.payer } },
165
- status: { in: liveStatuses },
166
- }
167
- const data = { status: 'canceled', canceledAt: new Date() }
168
- await subscription.queries.updateManyAndReturn({ where, data }, M)
169
- }
170
- await StripeCustomer.delete({ where: { id: row.id } }, M)
171
- }
172
-
173
- /** Writes what was read of the customer, under its lock. */
174
- async function write(
175
- running: Running,
176
- row: Customer,
177
- state: CustomerState,
178
- readAt: Date,
179
- ) {
180
- if (state.deleted) {
181
- await forget(running, row)
182
- return
183
- }
184
- const subscription = ownModel(running.subscription, row)
185
- if (subscription !== undefined) {
186
- for (const one of state.subscriptions) {
187
- await writeSubscription(subscription, row, one)
188
- }
189
- }
190
- for (const payment of state.payments) {
191
- await writePayment(running, row, payment)
192
- }
193
- if (ownModel(running.balance, row) !== undefined) {
194
- for (const invoice of state.invoices) {
195
- await writeInvoice(running, row, invoice, readAt)
196
- }
197
- }
198
- // Enqueued with the write: a sync that writes nothing read older.
199
- if (running.oneSubscription) {
200
- for (const { id } of duplicatesOf(state.subscriptions)) {
201
- await duplicateJob.enqueue({ subscription: id })
202
- }
203
- }
204
- }
205
-
206
- /**
207
- * Writes what Stripe holds of the customer of row `id`. The sync takes the
208
- * next number of the customer's syncs, reads Stripe, then writes only when
209
- * no sync begun after it wrote first. A change at Stripe sends an event
210
- * whose sync begins after it, so no sync begun before overwrites it.
211
- */
212
- export async function syncCustomer(id: string): Promise<void> {
213
- const running = runningOf('stripe.sync')
214
- const { gateway } = stripeOf('stripe.sync')
215
- const [begun] = await StripeCustomer.updateManyAndReturn(
216
- { where: { id }, data: { syncsBegun: { increment: 1 } } },
217
- M,
218
- )
219
- const stripeId = begun?.stripeId ?? null
220
- if (begun === undefined || stripeId === null) return
221
- const readAt = new Date()
222
- const invoices = readsInvoices(running)
223
- // Only a catalog that sells once has Checkouts a discount made free.
224
- const free = [...running.products.values()].some((one) => !('prices' in one))
225
- const state = await gateway.readCustomer(stripeId, { invoices, free })
226
- await transaction(async () => {
227
- const number = begun.syncsBegun
228
- const data = {
229
- syncWritten: number,
230
- syncedAt: readAt,
231
- renewsAt: renewsAt(state),
232
- }
233
- // The customer's lock, taken by the write.
234
- const [row] = await StripeCustomer.updateManyAndReturn(
235
- { where: { id, stripeId, syncWritten: { lt: number } }, data },
236
- M,
237
- )
238
- if (row !== undefined) await write(running, row, state, readAt)
239
- })
240
- // Outside the lock, as any call to Stripe (D-380).
241
- for (const one of state.subscriptions) {
242
- if (one.card !== null && liveStatuses.includes(one.status)) {
243
- await gateway.moveCard({ ...one, card: one.card })
244
- }
245
- }
246
- }