@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
package/dist/catalog.js DELETED
@@ -1,182 +0,0 @@
1
- // The catalog at Stripe, written from the products declared in code (D-372).
2
- // A product is found by its `metadata.key`, a price by its lookup key:
3
- // `<product>.<price>`, or the product's key for a one-time price. The plan
4
- // lists the changes from what Stripe holds; applying them never deletes: a
5
- // product left out is archived, and a price whose billing changed is
6
- // replaced by a new one, which takes its lookup key over.
7
- import { Refused } from 'ultimabase';
8
- import { managedBy, } from './gateway.js';
9
- import { portalSettings, samePortal } from './portal.js';
10
- const productWrite = (product) => ({
11
- key: product.key,
12
- name: product.name,
13
- taxCode: product.taxCode ?? null,
14
- });
15
- /** The prices of the catalog's products, in their order. */
16
- const wantedPrices = (products) => products.flatMap((product) => 'prices' in product
17
- ? Object.entries(product.prices).map(([name, price]) => ({
18
- product: product.key,
19
- lookupKey: `${product.key}.${name}`,
20
- amount: price.amount,
21
- recurring: { every: price.every, count: price.everyCount ?? 1 },
22
- metadata: { managedBy, product: product.key, price: name },
23
- }))
24
- : [
25
- {
26
- product: product.key,
27
- lookupKey: product.key,
28
- amount: product.price.amount,
29
- recurring: null,
30
- metadata: { managedBy, product: product.key },
31
- },
32
- ]);
33
- /** The product of each key: its active one first, else an archived one. */
34
- const productsOf = (products, held) => new Map(products.flatMap(({ key }) => {
35
- const ofKey = held.filter((product) => product.key === key);
36
- const product = ofKey.find(({ active }) => active) ?? ofKey.at(0);
37
- return product === undefined ? [] : [[key, product]];
38
- }));
39
- const sameRecurring = (held, wanted) => held === null || wanted === null
40
- ? held === wanted
41
- : held.every === wanted.every && held.count === wanted.count;
42
- /** Whether `held` bills as `price`: what Stripe never changes of a price. */
43
- const billsAs = (catalog, held, price, productId) => held.productId === productId &&
44
- held.amount === price.amount &&
45
- held.currency === catalog.currency &&
46
- sameRecurring(held.recurring, price.recurring) &&
47
- held.taxBehavior === catalog.taxBehavior;
48
- /** Whether `held` carries `price`'s nickname and metadata. */
49
- const describedAs = (held, price) => held.nickname === price.lookupKey &&
50
- // Stripe merges metadata: a key someone added stays, and is let be.
51
- Object.entries(price.metadata).every(([key, value]) => held.metadata[key] === value);
52
- const productIs = (held, product) => held.active && held.name === product.name && held.taxCode === product.taxCode;
53
- /** The active price of each lookup key. */
54
- const activePrices = (prices) => new Map(prices.flatMap((price) => price.active && price.lookupKey !== null
55
- ? [[price.lookupKey, price]]
56
- : []));
57
- /** The id `ids` holds for `key`, which the steps before have written. */
58
- const idOf = (ids, key) => {
59
- const id = ids.get(key);
60
- if (id === undefined)
61
- throw new Error(`The catalog has no id for ${key}.`);
62
- return id;
63
- };
64
- /** The portal's products: the subscriptions, with their prices' ids. */
65
- const portalProducts = (products, productIds, priceIds) => products.flatMap((product) => 'prices' in product
66
- ? [
67
- {
68
- productId: idOf(productIds, product.key),
69
- priceIds: Object.keys(product.prices).map((name) => idOf(priceIds, `${product.key}.${name}`)),
70
- },
71
- ]
72
- : []);
73
- /** The id of each key's product. */
74
- const productIdsOf = (products, held) => new Map([...productsOf(products, held)].map(([key, { id }]) => [key, id]));
75
- /** The changes that bring `state` to `catalog`, in order. */
76
- export const planCatalog = (catalog, state) => {
77
- const steps = [];
78
- const kept = productsOf(catalog.products, state.products);
79
- for (const product of catalog.products.map(productWrite)) {
80
- const was = kept.get(product.key);
81
- if (was === undefined)
82
- steps.push({ kind: 'createProduct', product });
83
- else if (!productIs(was, product)) {
84
- steps.push({ kind: 'updateProduct', product, was });
85
- }
86
- }
87
- const active = activePrices(state.prices);
88
- const unchanged = new Map();
89
- const wanted = wantedPrices(catalog.products);
90
- for (const price of wanted) {
91
- const was = active.get(price.lookupKey);
92
- if (was !== undefined && was.metadata['managedBy'] !== managedBy) {
93
- throw new Refused(`The price ${was.id} holds the lookup key ${price.lookupKey} but was not written by the catalog: archive it, or remove its lookup key, in the Stripe Dashboard.`);
94
- }
95
- if (was === undefined) {
96
- steps.push({ kind: 'createPrice', price, replaces: null });
97
- }
98
- else if (!billsAs(catalog, was, price, kept.get(price.product)?.id)) {
99
- // A price's billing never changes: a new one takes the key over.
100
- steps.push({ kind: 'createPrice', price, replaces: was });
101
- }
102
- else {
103
- unchanged.set(price.lookupKey, was.id);
104
- if (!describedAs(was, price)) {
105
- steps.push({ kind: 'updatePrice', price, was });
106
- }
107
- }
108
- }
109
- const lookupKeys = new Set(wanted.map(({ lookupKey }) => lookupKey));
110
- for (const price of state.prices) {
111
- if (price.active &&
112
- price.metadata['managedBy'] === managedBy &&
113
- (price.lookupKey === null || !lookupKeys.has(price.lookupKey))) {
114
- steps.push({ kind: 'archivePrice', was: price });
115
- }
116
- }
117
- // A product left out, or a key's second product.
118
- const keptIds = new Set([...kept.values()].map(({ id }) => id));
119
- for (const product of state.products) {
120
- if (product.active && !keptIds.has(product.id)) {
121
- steps.push({ kind: 'archiveProduct', was: product });
122
- }
123
- }
124
- // A new subscription price changes the portal's list.
125
- const moved = steps.some((step) => step.kind === 'createPrice' && step.price.recurring !== null);
126
- if (moved ||
127
- state.portal === null ||
128
- !samePortal(state.portal.settings, portalSettings(catalog.portal, portalProducts(catalog.products, productIdsOf(catalog.products, state.products), unchanged)))) {
129
- steps.push({ kind: 'savePortal', id: state.portal?.id ?? null });
130
- }
131
- return steps;
132
- };
133
- /** Applies `steps`, planned from `state`, through `gateway`. */
134
- export const applyCatalog = async (catalog, gateway, state, steps) => {
135
- const productIds = productIdsOf(catalog.products, state.products);
136
- const priceIds = new Map([...activePrices(state.prices)].map(([key, { id }]) => [key, id]));
137
- for (const step of steps) {
138
- switch (step.kind) {
139
- case 'createProduct':
140
- productIds.set(step.product.key, await gateway.createProduct(step.product));
141
- break;
142
- case 'updateProduct':
143
- await gateway.updateProduct(step.was.id, step.product);
144
- break;
145
- case 'archiveProduct':
146
- await gateway.archiveProduct(step.was.id);
147
- break;
148
- case 'createPrice': {
149
- const { price } = step;
150
- const id = await gateway.createPrice({
151
- productId: idOf(productIds, price.product),
152
- lookupKey: price.lookupKey,
153
- amount: price.amount,
154
- currency: catalog.currency,
155
- recurring: price.recurring,
156
- taxBehavior: catalog.taxBehavior,
157
- nickname: price.lookupKey,
158
- metadata: price.metadata,
159
- });
160
- priceIds.set(price.lookupKey, id);
161
- // After its successor: a payer never finds no price.
162
- if (step.replaces !== null) {
163
- await gateway.archivePrice(step.replaces.id);
164
- }
165
- break;
166
- }
167
- case 'updatePrice':
168
- await gateway.updatePrice(step.was.id, {
169
- nickname: step.price.lookupKey,
170
- metadata: step.price.metadata,
171
- });
172
- break;
173
- case 'archivePrice':
174
- await gateway.archivePrice(step.was.id);
175
- break;
176
- case 'savePortal': {
177
- await gateway.savePortal(step.id, portalSettings(catalog.portal, portalProducts(catalog.products, productIds, priceIds)));
178
- break;
179
- }
180
- }
181
- }
182
- };
package/dist/credit.d.ts DELETED
@@ -1,16 +0,0 @@
1
- /** An amount of one credit: what a product gives. */
2
- export interface CreditAmount<K extends string = string> {
3
- readonly credit: K;
4
- readonly amount: number;
5
- }
6
- /** A kind of credit: called with an amount, it gives that many of it. */
7
- export interface Credit<K extends string = string> {
8
- (amount: number): CreditAmount<K>;
9
- /** The credit's name in the application, never changed. */
10
- readonly key: K;
11
- }
12
- /** Declares a kind of credit (D-372). */
13
- export declare function defineCredit<const K extends string>(definition: {
14
- readonly key: K;
15
- }): Credit<K>;
16
- //# sourceMappingURL=credit.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"credit.d.ts","sourceRoot":"","sources":["../src/credit.ts"],"names":[],"mappings":"AAMA,qDAAqD;AACrD,MAAM,WAAW,YAAY,CAAC,CAAC,SAAS,MAAM,GAAG,MAAM;IACtD,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAA;IAClB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;CACvB;AAED,yEAAyE;AACzE,MAAM,WAAW,MAAM,CAAC,CAAC,SAAS,MAAM,GAAG,MAAM;IAChD,CAAC,MAAM,EAAE,MAAM,GAAG,YAAY,CAAC,CAAC,CAAC,CAAA;IACjC,2DAA2D;IAC3D,QAAQ,CAAC,GAAG,EAAE,CAAC,CAAA;CACf;AAED,yCAAyC;AACzC,wBAAgB,YAAY,CAAC,KAAK,CAAC,CAAC,SAAS,MAAM,EAAE,UAAU,EAAE;IAChE,QAAQ,CAAC,GAAG,EAAE,CAAC,CAAA;CACf,GAAG,MAAM,CAAC,CAAC,CAAC,CAaZ"}
package/dist/credit.js DELETED
@@ -1,18 +0,0 @@
1
- // `defineCredit` (D-372): a kind of credit, as blue gems. It is a function:
2
- // `blueGems(500)` is 500 of them, a value a product gives and, later, the
3
- // application spends.
4
- import { Refused } from 'ultimabase';
5
- import { checkKey, ownKeys } from './keys.js';
6
- /** Declares a kind of credit (D-372). */
7
- export function defineCredit(definition) {
8
- ownKeys('defineCredit', definition, ['key']);
9
- const { key } = definition;
10
- checkKey('defineCredit', key);
11
- const credit = (amount) => {
12
- if (!Number.isSafeInteger(amount) || amount <= 0) {
13
- throw new Refused(`${key}(${String(amount)}): an amount is a positive integer.`);
14
- }
15
- return Object.freeze({ credit: key, amount });
16
- };
17
- return Object.assign(credit, { key });
18
- }
package/dist/credits.d.ts DELETED
@@ -1,38 +0,0 @@
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
@@ -1 +0,0 @@
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 DELETED
@@ -1,138 +0,0 @@
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
- }
@@ -1,25 +0,0 @@
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
@@ -1 +0,0 @@
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 DELETED
@@ -1,88 +0,0 @@
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
- }
@@ -1,4 +0,0 @@
1
- import type { CatalogStep } from './catalog.ts';
2
- /** The step in a line. */
3
- export declare const describeStep: (step: CatalogStep, currency: string) => string;
4
- //# sourceMappingURL=describe.d.ts.map
@@ -1 +0,0 @@
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 DELETED
@@ -1,56 +0,0 @@
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
- };
@@ -1,12 +0,0 @@
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
@@ -1 +0,0 @@
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"}
@@ -1,24 +0,0 @@
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
- });