@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
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import type { CreditAmount } from './credit.ts';
|
|
2
|
+
type Owner = {
|
|
3
|
+
readonly id: string;
|
|
4
|
+
};
|
|
5
|
+
/** A paid payment or invoice, as its credits read it. */
|
|
6
|
+
export interface Paid {
|
|
7
|
+
readonly id: string;
|
|
8
|
+
readonly amount: number;
|
|
9
|
+
readonly refunded: number;
|
|
10
|
+
readonly disputeLost: boolean;
|
|
11
|
+
}
|
|
12
|
+
/** Whether a full refund or a lost dispute takes its credits back. */
|
|
13
|
+
export declare const lost: (paid: Paid) => boolean;
|
|
14
|
+
/** Each credit's total, `times` over, in the order first named. */
|
|
15
|
+
export declare function totals(credits: readonly CreditAmount[], times?: number, sums?: Map<string, number>): Map<string, number>;
|
|
16
|
+
/**
|
|
17
|
+
* Adds to each of the owner's balances without a payment, in the caller's
|
|
18
|
+
* transaction when it has one (D-377 point 1).
|
|
19
|
+
*/
|
|
20
|
+
export declare function grant(owner: Owner, credits: CreditAmount | readonly CreditAmount[], options: {
|
|
21
|
+
readonly reason: string;
|
|
22
|
+
}): Promise<void>;
|
|
23
|
+
/**
|
|
24
|
+
* Lowers each of the owner's balances, in the caller's transaction when it
|
|
25
|
+
* has one; `NOT_ENOUGH_CREDITS` when one would fall below zero, with
|
|
26
|
+
* nothing changed (D-374 point 2).
|
|
27
|
+
*/
|
|
28
|
+
export declare function spend(owner: Owner, credits: CreditAmount | readonly CreditAmount[], options: {
|
|
29
|
+
readonly reason: string;
|
|
30
|
+
}): Promise<void>;
|
|
31
|
+
/**
|
|
32
|
+
* Gives the credits `sums` a paid payment or invoice gives, once, and takes
|
|
33
|
+
* back what it gave after a full refund or a lost dispute, once, down to
|
|
34
|
+
* zero (D-374, D-377 point 4).
|
|
35
|
+
*/
|
|
36
|
+
export declare function settleCredits(owner: string, paid: Paid, sums: ReadonlyMap<string, number>, reason: 'purchase' | 'subscription'): Promise<void>;
|
|
37
|
+
export {};
|
|
38
|
+
//# sourceMappingURL=credits.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"credits.d.ts","sourceRoot":"","sources":["../src/credits.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAA;AAK/C,KAAK,KAAK,GAAG;IAAE,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAA;CAAE,CAAA;AAEpC,yDAAyD;AACzD,MAAM,WAAW,IAAI;IACpB,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAA;IACnB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;IACvB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAA;IACzB,QAAQ,CAAC,WAAW,EAAE,OAAO,CAAA;CAC7B;AAED,sEAAsE;AACtE,eAAO,MAAM,IAAI,SAAU,IAAI,KAAG,OAEoC,CAAA;AAEtE,mEAAmE;AACnE,wBAAgB,MAAM,CACrB,OAAO,EAAE,SAAS,YAAY,EAAE,EAChC,KAAK,SAAI,EACT,IAAI,GAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAa,GACnC,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAKrB;AA4DD;;;GAGG;AACH,wBAAsB,KAAK,CAC1B,KAAK,EAAE,KAAK,EACZ,OAAO,EAAE,YAAY,GAAG,SAAS,YAAY,EAAE,EAC/C,OAAO,EAAE;IAAE,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GAClC,OAAO,CAAC,IAAI,CAAC,CAUf;AAED;;;;GAIG;AACH,wBAAsB,KAAK,CAC1B,KAAK,EAAE,KAAK,EACZ,OAAO,EAAE,YAAY,GAAG,SAAS,YAAY,EAAE,EAC/C,OAAO,EAAE;IAAE,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GAClC,OAAO,CAAC,IAAI,CAAC,CAsBf;AAkBD;;;;GAIG;AACH,wBAAsB,aAAa,CAClC,KAAK,EAAE,MAAM,EACb,IAAI,EAAE,IAAI,EACV,IAAI,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,EACjC,MAAM,EAAE,UAAU,GAAG,cAAc,GACjC,OAAO,CAAC,IAAI,CAAC,CA+Bf"}
|
package/dist/credits.js
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
// Credits (D-374, D-377): a paid purchase or subscription invoice adds what
|
|
2
|
+
// it gives, once; a full refund or a lost dispute takes it back, down to
|
|
3
|
+
// zero; the application grants and spends them in its own transaction. Each
|
|
4
|
+
// move is written to the application's credit history.
|
|
5
|
+
import { PublicError, transaction } from 'ultimabase';
|
|
6
|
+
import { M } from './models.js';
|
|
7
|
+
import { runningOf } from './running.js';
|
|
8
|
+
/** Whether a full refund or a lost dispute takes its credits back. */
|
|
9
|
+
export const lost = (paid) =>
|
|
10
|
+
// A free invoice, after a full coupon, is never refunded.
|
|
11
|
+
paid.disputeLost || (paid.amount > 0 && paid.refunded >= paid.amount);
|
|
12
|
+
/** Each credit's total, `times` over, in the order first named. */
|
|
13
|
+
export function totals(credits, times = 1, sums = new Map()) {
|
|
14
|
+
for (const { credit, amount } of credits) {
|
|
15
|
+
sums.set(credit, (sums.get(credit) ?? 0) + amount * times);
|
|
16
|
+
}
|
|
17
|
+
return sums;
|
|
18
|
+
}
|
|
19
|
+
const listOf = (credits) => ('credit' in credits ? [credits] : credits);
|
|
20
|
+
/** The owner's balances of `credits`, their rows locked by the update. */
|
|
21
|
+
async function lockedBalances(balance, owner, credits) {
|
|
22
|
+
const where = { owner: { is: { id: owner } }, credit: { in: credits } };
|
|
23
|
+
const data = { amount: { increment: 0 } };
|
|
24
|
+
const rows = await balance.queries.updateManyAndReturn({ where, data }, M);
|
|
25
|
+
return new Map(rows.map((row) => [String(row['credit']), row]));
|
|
26
|
+
}
|
|
27
|
+
const amountOf = (row) => typeof row?.['amount'] === 'number' ? row['amount'] : 0;
|
|
28
|
+
/** The balance and history models, which come together (D-377 point 2). */
|
|
29
|
+
function creditModels(name) {
|
|
30
|
+
const { balance, history } = runningOf(name);
|
|
31
|
+
if (balance === undefined || history === undefined) {
|
|
32
|
+
throw new Error(`${name} needs a model defineBalance returned.`);
|
|
33
|
+
}
|
|
34
|
+
return { balance, history };
|
|
35
|
+
}
|
|
36
|
+
/** Adds to the owner's balance of `credit`, creating it at the first move. */
|
|
37
|
+
async function add(balance, owner, credit, amount) {
|
|
38
|
+
await balance.queries.upsert({
|
|
39
|
+
where: { owner, credit },
|
|
40
|
+
create: { owner: { connect: { id: owner } }, credit, amount },
|
|
41
|
+
update: { amount: { increment: amount } },
|
|
42
|
+
}, M);
|
|
43
|
+
}
|
|
44
|
+
async function entry(history, owner, move, payment = null) {
|
|
45
|
+
const data = { owner: { connect: { id: owner } }, ...move, payment };
|
|
46
|
+
await history.queries.create({ data }, M);
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Adds to each of the owner's balances without a payment, in the caller's
|
|
50
|
+
* transaction when it has one (D-377 point 1).
|
|
51
|
+
*/
|
|
52
|
+
export async function grant(owner, credits, options) {
|
|
53
|
+
const { balance, history } = creditModels('stripe.grant');
|
|
54
|
+
const sums = totals(listOf(credits));
|
|
55
|
+
await transaction(async () => {
|
|
56
|
+
for (const [credit, amount] of sums) {
|
|
57
|
+
await add(balance, owner.id, credit, amount);
|
|
58
|
+
const move = { credit, change: amount, reason: options.reason };
|
|
59
|
+
await entry(history, owner.id, move);
|
|
60
|
+
}
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Lowers each of the owner's balances, in the caller's transaction when it
|
|
65
|
+
* has one; `NOT_ENOUGH_CREDITS` when one would fall below zero, with
|
|
66
|
+
* nothing changed (D-374 point 2).
|
|
67
|
+
*/
|
|
68
|
+
export async function spend(owner, credits, options) {
|
|
69
|
+
const { balance, history } = creditModels('stripe.spend');
|
|
70
|
+
const sums = totals(listOf(credits));
|
|
71
|
+
await transaction(async () => {
|
|
72
|
+
const held = await lockedBalances(balance, owner.id, [...sums.keys()]);
|
|
73
|
+
const spent = [...sums].map(([credit, needed]) => {
|
|
74
|
+
const row = held.get(credit);
|
|
75
|
+
const left = amountOf(row);
|
|
76
|
+
if (row === undefined || left < needed) {
|
|
77
|
+
throw new PublicError('NOT_ENOUGH_CREDITS', `Not enough ${credit}.`, {
|
|
78
|
+
details: { credit, balance: left, needed },
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
return { id: row.id, credit, needed };
|
|
82
|
+
});
|
|
83
|
+
for (const { id, credit, needed } of spent) {
|
|
84
|
+
const data = { amount: { decrement: needed } };
|
|
85
|
+
await balance.queries.update({ where: { id }, data }, M);
|
|
86
|
+
const move = { credit, change: -needed, reason: options.reason };
|
|
87
|
+
await entry(history, owner.id, move);
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
/** What the history shows a payment gave, by credit, and whether it was taken back. */
|
|
92
|
+
async function movesOf(history, payment) {
|
|
93
|
+
const rows = await history.queries.findMany({ where: { payment } }, M);
|
|
94
|
+
const given = new Map();
|
|
95
|
+
for (const row of rows) {
|
|
96
|
+
if (row['reason'] === 'refund' || typeof row['change'] !== 'number')
|
|
97
|
+
continue;
|
|
98
|
+
const credit = String(row['credit']);
|
|
99
|
+
given.set(credit, (given.get(credit) ?? 0) + row['change']);
|
|
100
|
+
}
|
|
101
|
+
return { given, taken: rows.some((row) => row['reason'] === 'refund') };
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Gives the credits `sums` a paid payment or invoice gives, once, and takes
|
|
105
|
+
* back what it gave after a full refund or a lost dispute, once, down to
|
|
106
|
+
* zero (D-374, D-377 point 4).
|
|
107
|
+
*/
|
|
108
|
+
export async function settleCredits(owner, paid, sums, reason) {
|
|
109
|
+
const { balance, history, logger } = runningOf('stripe');
|
|
110
|
+
if (balance === undefined || history === undefined)
|
|
111
|
+
return;
|
|
112
|
+
const moves = await movesOf(history, paid.id);
|
|
113
|
+
let given = moves.given;
|
|
114
|
+
if (given.size === 0 && !moves.taken) {
|
|
115
|
+
for (const [credit, amount] of sums) {
|
|
116
|
+
await add(balance, owner, credit, amount);
|
|
117
|
+
await entry(history, owner, { credit, change: amount, reason }, paid.id);
|
|
118
|
+
}
|
|
119
|
+
given = new Map(sums);
|
|
120
|
+
}
|
|
121
|
+
if (!lost(paid) || moves.taken || given.size === 0)
|
|
122
|
+
return;
|
|
123
|
+
const held = await lockedBalances(balance, owner, [...given.keys()]);
|
|
124
|
+
for (const [credit, amount] of given) {
|
|
125
|
+
const row = held.get(credit);
|
|
126
|
+
const taken = Math.min(amount, amountOf(row));
|
|
127
|
+
if (taken < amount) {
|
|
128
|
+
const details = { owner, credit, payment: paid.id };
|
|
129
|
+
logger.warn({ ...details, spent: amount - taken }, `${credit} of a refunded payment were already spent: they stay spent.`);
|
|
130
|
+
}
|
|
131
|
+
if (row !== undefined && taken > 0) {
|
|
132
|
+
const data = { amount: { decrement: taken } };
|
|
133
|
+
await balance.queries.update({ where: { id: row.id }, data }, M);
|
|
134
|
+
}
|
|
135
|
+
const move = { credit, change: -taken, reason: 'refund' };
|
|
136
|
+
await entry(history, owner, move, paid.id);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { RecordOf } from 'ultimabase';
|
|
2
|
+
import { StripeCustomer } from './models.ts';
|
|
3
|
+
import type { Billing, Row } from './running.ts';
|
|
4
|
+
export type Customer = RecordOf<typeof StripeCustomer>;
|
|
5
|
+
/** The payer's row of `model`, read as Master, or `NOT_FOUND`. */
|
|
6
|
+
export declare function payerRow(payer: Billing['payer'], id: string): Promise<Row>;
|
|
7
|
+
/** The payer's customer row, created on its first use. */
|
|
8
|
+
export declare function customerRow(model: string, payer: string): Promise<Customer>;
|
|
9
|
+
/**
|
|
10
|
+
* Runs `run` in a transaction holding the customer's row, so one write
|
|
11
|
+
* about a payer runs at a time; `undefined` when the row is gone.
|
|
12
|
+
*/
|
|
13
|
+
export declare function locked<R>(id: string, run: (row: Customer) => Promise<R>): Promise<R | undefined>;
|
|
14
|
+
/** A new row for the payer of `row`, whose customer Stripe deleted. */
|
|
15
|
+
export declare function renewed(row: Customer): Promise<Customer>;
|
|
16
|
+
/**
|
|
17
|
+
* The payer's customer at Stripe, under its lock: created once, with an
|
|
18
|
+
* idempotency key, and given the payer's profile when it changed. A customer
|
|
19
|
+
* deleted at Stripe gives the payer a new row, so a new key.
|
|
20
|
+
*/
|
|
21
|
+
export declare function ensureCustomer(row: Customer, payer: Row): Promise<{
|
|
22
|
+
readonly row: Customer;
|
|
23
|
+
readonly stripeId: string;
|
|
24
|
+
}>;
|
|
25
|
+
//# sourceMappingURL=customer.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"customer.d.ts","sourceRoot":"","sources":["../src/customer.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAA;AAI1C,OAAO,EAAK,cAAc,EAAE,MAAM,aAAa,CAAA;AAC/C,OAAO,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,cAAc,CAAA;AAGhD,MAAM,MAAM,QAAQ,GAAG,QAAQ,CAAC,OAAO,cAAc,CAAC,CAAA;AAEtD,kEAAkE;AAClE,wBAAsB,QAAQ,CAC7B,KAAK,EAAE,OAAO,CAAC,OAAO,CAAC,EACvB,EAAE,EAAE,MAAM,GACR,OAAO,CAAC,GAAG,CAAC,CAMd;AAED,0DAA0D;AAC1D,wBAAsB,WAAW,CAChC,KAAK,EAAE,MAAM,EACb,KAAK,EAAE,MAAM,GACX,OAAO,CAAC,QAAQ,CAAC,CAanB;AAED;;;GAGG;AACH,wBAAsB,MAAM,CAAC,CAAC,EAC7B,EAAE,EAAE,MAAM,EACV,GAAG,EAAE,CAAC,GAAG,EAAE,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,GAChC,OAAO,CAAC,CAAC,GAAG,SAAS,CAAC,CASxB;AAiBD,uEAAuE;AACvE,wBAAsB,OAAO,CAAC,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC,CAI9D;AAED;;;;GAIG;AACH,wBAAsB,cAAc,CACnC,GAAG,EAAE,QAAQ,EACb,KAAK,EAAE,GAAG,GACR,OAAO,CAAC;IAAE,QAAQ,CAAC,GAAG,EAAE,QAAQ,CAAC;IAAC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,CAAC,CAoBhE"}
|
package/dist/customer.js
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { PublicError, transaction } from 'ultimabase';
|
|
2
|
+
import { Missing } from './billing-gateway.js';
|
|
3
|
+
import { M, StripeCustomer } from './models.js';
|
|
4
|
+
import { runningOf, stripeOf } from './running.js';
|
|
5
|
+
/** The payer's row of `model`, read as Master, or `NOT_FOUND`. */
|
|
6
|
+
export async function payerRow(payer, id) {
|
|
7
|
+
const row = await payer.queries.findUnique({ where: { id } }, M);
|
|
8
|
+
if (row !== null)
|
|
9
|
+
return row;
|
|
10
|
+
throw new PublicError('NOT_FOUND', `No ${payer.name} matches payer.`, {
|
|
11
|
+
details: { model: payer.name },
|
|
12
|
+
});
|
|
13
|
+
}
|
|
14
|
+
/** The payer's customer row, created on its first use. */
|
|
15
|
+
export async function customerRow(model, payer) {
|
|
16
|
+
const where = { model, payer };
|
|
17
|
+
const held = await StripeCustomer.findUnique({ where }, M);
|
|
18
|
+
if (held !== null)
|
|
19
|
+
return held;
|
|
20
|
+
try {
|
|
21
|
+
return await StripeCustomer.create({ data: where }, M);
|
|
22
|
+
}
|
|
23
|
+
catch (error) {
|
|
24
|
+
// Another call created it first.
|
|
25
|
+
if (!(error instanceof PublicError && error.code === 'UNIQUE_VIOLATION')) {
|
|
26
|
+
throw error;
|
|
27
|
+
}
|
|
28
|
+
return StripeCustomer.findUniqueOrThrow({ where }, M);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Runs `run` in a transaction holding the customer's row, so one write
|
|
33
|
+
* about a payer runs at a time; `undefined` when the row is gone.
|
|
34
|
+
*/
|
|
35
|
+
export async function locked(id, run) {
|
|
36
|
+
return transaction(async () => {
|
|
37
|
+
const data = { lockedAt: new Date() };
|
|
38
|
+
const [row] = await StripeCustomer.updateManyAndReturn({ where: { id }, data }, M);
|
|
39
|
+
return row === undefined ? undefined : run(row);
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
/** What Stripe shows of the payer, from the `customer` option. */
|
|
43
|
+
function profileOf(payer) {
|
|
44
|
+
const { customer } = runningOf('stripe');
|
|
45
|
+
const given = customer === undefined ? {} : Reflect.apply(customer, undefined, [payer]);
|
|
46
|
+
const read = (key) => {
|
|
47
|
+
const value = typeof given === 'object' && given !== null
|
|
48
|
+
? Reflect.get(given, key)
|
|
49
|
+
: undefined;
|
|
50
|
+
return typeof value === 'string' ? value : null;
|
|
51
|
+
};
|
|
52
|
+
return { email: read('email'), name: read('name'), locale: read('locale') };
|
|
53
|
+
}
|
|
54
|
+
/** A new row for the payer of `row`, whose customer Stripe deleted. */
|
|
55
|
+
export async function renewed(row) {
|
|
56
|
+
await StripeCustomer.delete({ where: { id: row.id } }, M);
|
|
57
|
+
const data = { model: row.model, payer: row.payer };
|
|
58
|
+
return StripeCustomer.create({ data }, M);
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* The payer's customer at Stripe, under its lock: created once, with an
|
|
62
|
+
* idempotency key, and given the payer's profile when it changed. A customer
|
|
63
|
+
* deleted at Stripe gives the payer a new row, so a new key.
|
|
64
|
+
*/
|
|
65
|
+
export async function ensureCustomer(row, payer) {
|
|
66
|
+
const { gateway } = stripeOf('stripe');
|
|
67
|
+
const profile = profileOf(payer);
|
|
68
|
+
const json = JSON.stringify(profile);
|
|
69
|
+
if (row.stripeId !== null) {
|
|
70
|
+
if (row.profile === json)
|
|
71
|
+
return { row, stripeId: row.stripeId };
|
|
72
|
+
try {
|
|
73
|
+
await gateway.updateCustomer(row.stripeId, profile);
|
|
74
|
+
}
|
|
75
|
+
catch (error) {
|
|
76
|
+
if (!(error instanceof Missing))
|
|
77
|
+
throw error;
|
|
78
|
+
return ensureCustomer(await renewed(row), payer);
|
|
79
|
+
}
|
|
80
|
+
const data = { profile: json };
|
|
81
|
+
await StripeCustomer.update({ where: { id: row.id }, data }, M);
|
|
82
|
+
return { row, stripeId: row.stripeId };
|
|
83
|
+
}
|
|
84
|
+
const stripeId = await gateway.createCustomer(profile, `customer-${row.id}`);
|
|
85
|
+
const data = { stripeId, profile: json };
|
|
86
|
+
await StripeCustomer.update({ where: { id: row.id }, data }, M);
|
|
87
|
+
return { row, stripeId };
|
|
88
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"describe.d.ts","sourceRoot":"","sources":["../src/describe.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAA;AA+C/C,0BAA0B;AAC1B,eAAO,MAAM,YAAY,SAAU,WAAW,YAAY,MAAM,KAAG,MA0BlE,CAAA"}
|
package/dist/describe.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/** An amount in the currency's smallest unit, as `9.90 EUR`. */
|
|
2
|
+
const formatAmount = (amount, currency) => {
|
|
3
|
+
const digits = Number(new Intl.NumberFormat('en', {
|
|
4
|
+
style: 'currency',
|
|
5
|
+
currency,
|
|
6
|
+
}).resolvedOptions().maximumFractionDigits);
|
|
7
|
+
return `${(amount / 10 ** digits).toFixed(digits)} ${currency.toUpperCase()}`;
|
|
8
|
+
};
|
|
9
|
+
const often = (recurring) => recurring === null
|
|
10
|
+
? 'once'
|
|
11
|
+
: recurring.count === 1
|
|
12
|
+
? `every ${recurring.every}`
|
|
13
|
+
: `every ${String(recurring.count)} ${recurring.every}s`;
|
|
14
|
+
const billing = (amount, currency, recurring) => `${amount === null ? 'no amount' : formatAmount(amount, currency)} ${often(recurring)}`;
|
|
15
|
+
const priceName = (price) => price.lookupKey === null ? price.id : `${price.lookupKey} (${price.id})`;
|
|
16
|
+
/** What an update changes of a product. */
|
|
17
|
+
const productChanges = (step) => {
|
|
18
|
+
const { product, was } = step;
|
|
19
|
+
return [
|
|
20
|
+
...(was.active ? [] : ['restore it']),
|
|
21
|
+
...(was.name === product.name
|
|
22
|
+
? []
|
|
23
|
+
: [`rename it from "${was.name}" to "${product.name}"`]),
|
|
24
|
+
...(was.taxCode === product.taxCode
|
|
25
|
+
? []
|
|
26
|
+
: [`set its tax code to ${product.taxCode ?? 'none'}`]),
|
|
27
|
+
].join(', ');
|
|
28
|
+
};
|
|
29
|
+
/** The step in a line. */
|
|
30
|
+
export const describeStep = (step, currency) => {
|
|
31
|
+
if (step.kind === 'createProduct') {
|
|
32
|
+
return `create the product ${step.product.key}: "${step.product.name}"`;
|
|
33
|
+
}
|
|
34
|
+
if (step.kind === 'updateProduct') {
|
|
35
|
+
return `update the product ${step.product.key}: ${productChanges(step)}`;
|
|
36
|
+
}
|
|
37
|
+
if (step.kind === 'archiveProduct') {
|
|
38
|
+
return `archive the product "${step.was.name}" (${step.was.id})`;
|
|
39
|
+
}
|
|
40
|
+
if (step.kind === 'createPrice') {
|
|
41
|
+
const { price, replaces } = step;
|
|
42
|
+
const line = `create the price ${price.lookupKey}: ${billing(price.amount, currency, price.recurring)}`;
|
|
43
|
+
return replaces === null
|
|
44
|
+
? line
|
|
45
|
+
: `${line}, replacing ${replaces.id} (${billing(replaces.amount, replaces.currency, replaces.recurring)})`;
|
|
46
|
+
}
|
|
47
|
+
if (step.kind === 'updatePrice') {
|
|
48
|
+
return `update the nickname and metadata of the price ${priceName(step.was)}`;
|
|
49
|
+
}
|
|
50
|
+
if (step.kind === 'archivePrice') {
|
|
51
|
+
return `archive the price ${priceName(step.was)}`;
|
|
52
|
+
}
|
|
53
|
+
return step.id === null
|
|
54
|
+
? 'create the customer portal configuration'
|
|
55
|
+
: `update the customer portal configuration ${step.id}`;
|
|
56
|
+
};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { Job } from '@ultimabase/jobs';
|
|
2
|
+
import type { StripeSubscription } from './billing-gateway.ts';
|
|
3
|
+
/**
|
|
4
|
+
* The live subscriptions beyond the first: the oldest stays. One still
|
|
5
|
+
* `incomplete` is not paid, and Stripe expires it within a day.
|
|
6
|
+
*/
|
|
7
|
+
export declare const duplicatesOf: (subscriptions: readonly StripeSubscription[]) => readonly StripeSubscription[];
|
|
8
|
+
/** Ends a second subscription at once and refunds it: the payer paid twice. */
|
|
9
|
+
export declare const duplicateJob: Job<'stripe.duplicate', {
|
|
10
|
+
readonly subscription: string;
|
|
11
|
+
}>;
|
|
12
|
+
//# sourceMappingURL=duplicates.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"duplicates.d.ts","sourceRoot":"","sources":["../src/duplicates.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,kBAAkB,CAAA;AAE3C,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAA;AAK9D;;;GAGG;AACH,eAAO,MAAM,YAAY,kBACT,SAAS,kBAAkB,EAAE,KAC1C,SAAS,kBAAkB,EAQnB,CAAA;AAEX,+EAA+E;AAC/E,eAAO,MAAM,YAAY,EAAE,GAAG,CAC7B,kBAAkB,EAClB;IAAE,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAA;CAAE,CAehC,CAAA"}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { defineJob } from '@ultimabase/jobs';
|
|
2
|
+
import { liveStatuses } from './billing-gateway.js';
|
|
3
|
+
import { strings } from './job-input.js';
|
|
4
|
+
import { stripeOf } from './running.js';
|
|
5
|
+
/**
|
|
6
|
+
* The live subscriptions beyond the first: the oldest stays. One still
|
|
7
|
+
* `incomplete` is not paid, and Stripe expires it within a day.
|
|
8
|
+
*/
|
|
9
|
+
export const duplicatesOf = (subscriptions) => subscriptions
|
|
10
|
+
.filter(({ status }) => liveStatuses.includes(status))
|
|
11
|
+
.toSorted((one, other) => one.startedAt.getTime() - other.startedAt.getTime() ||
|
|
12
|
+
one.id.localeCompare(other.id))
|
|
13
|
+
.slice(1);
|
|
14
|
+
/** Ends a second subscription at once and refunds it: the payer paid twice. */
|
|
15
|
+
export const duplicateJob = defineJob({
|
|
16
|
+
name: 'stripe.duplicate',
|
|
17
|
+
input: strings('subscription'),
|
|
18
|
+
// Each sync until it ends finds it again: one run at a time.
|
|
19
|
+
key: ({ subscription }) => subscription,
|
|
20
|
+
run: async ({ input, logger }) => {
|
|
21
|
+
await stripeOf('stripe.duplicate').gateway.cancelAndRefund(input.subscription);
|
|
22
|
+
logger.error(input, 'A payer’s second subscription was canceled and refunded.');
|
|
23
|
+
},
|
|
24
|
+
});
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import type { BillingGateway, CheckoutWrite, RecoveryGateway, CustomerProfile, PortalWrite, StripeInvoice, StripePayment, StripeSubscription } from './billing-gateway.ts';
|
|
2
|
+
import type { StripePrice } from './gateway.ts';
|
|
3
|
+
/** A customer of the fake account. */
|
|
4
|
+
export interface FakeCustomer {
|
|
5
|
+
readonly id: string;
|
|
6
|
+
readonly profile: CustomerProfile;
|
|
7
|
+
readonly deleted: boolean;
|
|
8
|
+
/** Its default card: the one a renewal charges (D-380). */
|
|
9
|
+
readonly card: string | null;
|
|
10
|
+
}
|
|
11
|
+
/** A Checkout of the fake account. */
|
|
12
|
+
export interface FakeCheckout extends CheckoutWrite {
|
|
13
|
+
readonly id: string;
|
|
14
|
+
readonly url: string;
|
|
15
|
+
readonly status: 'open' | 'complete' | 'expired';
|
|
16
|
+
}
|
|
17
|
+
/** What the fake account holds of its payers, and what a test does at Stripe. */
|
|
18
|
+
export interface FakeBilling {
|
|
19
|
+
readonly webhookSecret: string;
|
|
20
|
+
readonly customers: Map<string, FakeCustomer>;
|
|
21
|
+
readonly checkouts: Map<string, FakeCheckout>;
|
|
22
|
+
readonly subscriptions: Map<string, StripeSubscription>;
|
|
23
|
+
readonly payments: Map<string, StripePayment>;
|
|
24
|
+
/** The paid invoices of subscriptions, each period's. */
|
|
25
|
+
readonly invoices: Map<string, StripeInvoice>;
|
|
26
|
+
/** Each portal session opened, in order. */
|
|
27
|
+
readonly portalSessions: PortalWrite[];
|
|
28
|
+
/** The subscriptions whose latest payment the plugin refunded. */
|
|
29
|
+
readonly subscriptionRefunds: Set<string>;
|
|
30
|
+
/**
|
|
31
|
+
* Pays an open Checkout, by its URL, as its payer would; gives its id.
|
|
32
|
+
* `free`: a promotion code took the whole price, and Stripe makes no
|
|
33
|
+
* payment for a purchase.
|
|
34
|
+
*/
|
|
35
|
+
readonly pay: (url: string, options?: {
|
|
36
|
+
readonly free?: boolean;
|
|
37
|
+
}) => string;
|
|
38
|
+
/** Changes a subscription, as the portal or a renewal would. */
|
|
39
|
+
readonly update: (id: string, changes: Partial<Omit<StripeSubscription, 'id'>>) => void;
|
|
40
|
+
/** Pays a subscription's next period, as Stripe renews it; gives its invoice. */
|
|
41
|
+
readonly renew: (id: string) => string;
|
|
42
|
+
/** Refunds a payment or an invoice, all of it by default. */
|
|
43
|
+
readonly refund: (id: string, amount?: number) => void;
|
|
44
|
+
readonly loseDispute: (id: string) => void;
|
|
45
|
+
/** Deletes a customer, as the dashboard would. */
|
|
46
|
+
readonly deleteCustomer: (id: string) => void;
|
|
47
|
+
/** Posts each event sent since the last call to the application at `url`. */
|
|
48
|
+
readonly deliver: (url: string, path?: string) => Promise<void>;
|
|
49
|
+
}
|
|
50
|
+
/** A thin event's body, as Stripe sends it to an event destination. */
|
|
51
|
+
export declare const thinEvent: (event: {
|
|
52
|
+
readonly id?: string;
|
|
53
|
+
/** Its v1 type: `customer.subscription.updated`. */
|
|
54
|
+
readonly type: string;
|
|
55
|
+
/** Its related object: `{ id: 'sub_1', type: 'subscription' }`. */
|
|
56
|
+
readonly object: {
|
|
57
|
+
readonly id: string;
|
|
58
|
+
readonly type: string;
|
|
59
|
+
};
|
|
60
|
+
readonly livemode?: boolean;
|
|
61
|
+
}) => string;
|
|
62
|
+
/** Posts `payload` to the webhook of the application at `url`, signed. */
|
|
63
|
+
export declare const postEvent: (url: string, payload: string, options: {
|
|
64
|
+
readonly secret: string;
|
|
65
|
+
readonly path?: string | undefined;
|
|
66
|
+
}) => Promise<Response>;
|
|
67
|
+
/** The fake's billing, over its catalog's prices. */
|
|
68
|
+
export declare function fakeBilling(prices: ReadonlyMap<string, StripePrice>, newId: (prefix: string) => string): {
|
|
69
|
+
readonly gateway: BillingGateway & RecoveryGateway;
|
|
70
|
+
readonly fake: FakeBilling;
|
|
71
|
+
};
|
|
72
|
+
//# sourceMappingURL=fake-billing.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fake-billing.d.ts","sourceRoot":"","sources":["../src/fake-billing.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EACX,cAAc,EACd,aAAa,EACb,eAAe,EACf,eAAe,EACf,WAAW,EACX,aAAa,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