@voltro/plugin-billing 0.89.2 → 0.91.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.
Files changed (40) hide show
  1. package/CHANGELOG.md +1943 -0
  2. package/README.md +0 -435
  3. package/THIRD-PARTY-NOTICES.md +22 -646
  4. package/dist/catalog.js +169 -70
  5. package/dist/custodyInventory.js +101 -65
  6. package/dist/dunning.js +14 -6
  7. package/dist/eventDelivery.js +14 -5
  8. package/dist/historicalUsage.js +94 -0
  9. package/dist/index.d.ts +777 -68
  10. package/dist/index.js +354 -233
  11. package/dist/invoiceHistoryJournal.js +204 -179
  12. package/dist/invoiceHistoryProgress.js +130 -106
  13. package/dist/invoiceHistoryWork.js +188 -186
  14. package/dist/invoicePaymentEpoch.js +145 -0
  15. package/dist/invoicePaymentObservation.js +64 -0
  16. package/dist/invoiceSnapshot.js +56 -46
  17. package/dist/invoiceStore.js +124 -90
  18. package/dist/paidInvoiceCoverage.js +84 -0
  19. package/dist/plans.js +15 -2
  20. package/dist/providers.js +149 -92
  21. package/dist/provision.js +84 -73
  22. package/dist/rpc.d.ts +53 -13
  23. package/dist/rpc.js +141 -78
  24. package/dist/service.js +1208 -722
  25. package/dist/stores.js +240 -148
  26. package/dist/stripeIdentity.js +17 -17
  27. package/dist/stripeInvoiceHistory.js +21 -21
  28. package/dist/stripeInvoicePayments.js +129 -0
  29. package/dist/stripeInvoiceSnapshot.js +65 -46
  30. package/dist/stripeProvider.js +570 -201
  31. package/dist/stripeRest.js +10 -10
  32. package/dist/subscriptionObservation.js +93 -0
  33. package/dist/subscriptionWriteStore.js +325 -0
  34. package/dist/table.js +75 -66
  35. package/dist/types.d.ts +415 -27
  36. package/dist/types.js +21 -4
  37. package/dist/web/index.d.ts +93 -3
  38. package/dist/web/index.js +76 -33
  39. package/dist/web/writeRequest.js +65 -0
  40. package/package.json +9 -9
package/dist/stores.js CHANGED
@@ -1,60 +1,77 @@
1
- import { BillingError as e } from "./types.js";
2
- import { dataStoreCustomerStore as t } from "./customerStore.js";
1
+ import { captureSubscriptionObservation as e } from "./subscriptionObservation.js";
2
+ import { dataStoreSubscriptionWriteStore as t } from "./subscriptionWriteStore.js";
3
3
  import { dataStoreInvoiceHistoryJournal as n } from "./invoiceHistoryJournal.js";
4
- import { dataStoreInvoiceStore as r } from "./invoiceStore.js";
4
+ import { dataStoreInvoiceHistoryProgressStore as r } from "./invoiceHistoryProgress.js";
5
5
  import { dataStoreInvoiceHistoryWorkStore as i } from "./invoiceHistoryWork.js";
6
- import { dataStoreInvoiceHistoryProgressStore as a } from "./invoiceHistoryProgress.js";
7
- import { recordDataStoreUsageEvent as o } from "./usageEvents.js";
8
- import { dataStoreCheckoutOperationStore as s } from "./checkoutStore.js";
9
- import { dataStoreBillingCloseStore as c } from "./closeStore.js";
10
- import { dataStoreDunningNoticeStore as l } from "./dunning.js";
6
+ import { dataStoreCustomerStore as a } from "./customerStore.js";
7
+ import { dataStoreInvoiceStore as o } from "./invoiceStore.js";
8
+ import { recordDataStoreUsageEvent as s } from "./usageEvents.js";
9
+ import { dataStoreCheckoutOperationStore as c } from "./checkoutStore.js";
10
+ import { dataStoreBillingCloseStore as l } from "./closeStore.js";
11
11
  import { BILLING_SUBSCRIPTIONS_TABLE as u, BILLING_USAGE_TABLE as d, billingTables as f } from "./table.js";
12
- import { Effect as p } from "effect";
13
- import { _voltroIdempotencyTable as m, and as h, ensureTableRegistered as g, eq as _ } from "@voltro/database";
14
- import { InMemoryDataStore as v } from "@voltro/runtime";
15
- import { createLogger as y } from "@voltro/logger";
12
+ import { dataStoreDunningNoticeStore as p } from "./dunning.js";
13
+ import { BillingError as m } from "./types.js";
14
+ import { Effect as h } from "effect";
15
+ import { _voltroIdempotencyTable as g, and as _, ensureTableRegistered as v, eq as y, lt as b } from "@voltro/database";
16
+ import { InMemoryDataStore as x } from "@voltro/runtime";
17
+ import { createLogger as S } from "@voltro/logger";
16
18
  // src/stores.ts
17
- var b = (e) => `${e}_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`, x = y({ scope: "@voltro/plugin-billing" }), S = (t, n) => p.tryPromise({
18
- try: t,
19
- catch: (t) => (x.warn("billing store operation failed", {
20
- source: n,
21
- detail: String(t?.message ?? t)
22
- }), new e({
23
- source: n,
24
- message: `${n} failed`,
19
+ var C = (e) => `${e}_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`, w = S({ scope: "@voltro/plugin-billing" }), T = (e, t) => h.tryPromise({
20
+ try: e,
21
+ catch: (e) => e instanceof m ? e : (w.warn("billing store operation failed", {
22
+ source: t,
23
+ detail: String(e?.message ?? e)
24
+ }), new m({
25
+ source: t,
26
+ message: `${t} failed`,
25
27
  transient: !0
26
28
  }))
27
- }), C = (e) => ({
29
+ }), E = () => new m({
30
+ source: "subscriptionStore",
31
+ message: "Subscription observation changed before exact patch.",
32
+ transient: !0
33
+ }), D = (e) => ({
28
34
  table: e.table,
29
35
  predicate: e.predicate,
30
36
  order: e.order ?? [],
31
37
  take: e.take,
32
38
  skip: void 0,
33
39
  projection: void 0
34
- }), w = (e) => e === "canceled", T = /* @__PURE__ */ new Set([
40
+ }), O = (e, t) => e === null || t === null ? e === t : Number.isFinite(e.getTime()) && Number.isFinite(t.getTime()) && e.getTime() === t.getTime(), k = (e) => e === "canceled", A = /* @__PURE__ */ new Set([
35
41
  "active",
36
42
  "trialing",
37
43
  "pastDue",
38
44
  "incomplete"
39
- ]), E = (e) => T.has(e), D = (e) => e.find((e) => E(e.status)) ?? e[0] ?? null, O = (e, t) => e === null ? !1 : t === null || t.getTime() < e.getTime(), k = (e) => ({
40
- tenantId: String(e.tenantId),
41
- provider: String(e.provider),
42
- providerSubscriptionId: String(e.providerSubscriptionId),
43
- plan: String(e.plan),
44
- status: String(e.status),
45
- quantity: e.quantity == null ? 1 : Number(e.quantity),
46
- currentPeriodStart: e.currentPeriodStart == null ? null : new Date(e.currentPeriodStart),
47
- currentPeriodEnd: e.currentPeriodEnd == null ? null : new Date(e.currentPeriodEnd),
48
- cancelAt: e.cancelAt == null ? null : new Date(e.cancelAt),
49
- pastDueSince: e.pastDueSince == null ? null : new Date(e.pastDueSince),
50
- statusEventAt: e.statusEventAt == null ? null : new Date(e.statusEventAt)
51
- }), A = async (e, t) => (await e.query(C({
52
- table: "_voltro_billing_subscriptions",
53
- predicate: _("providerSubscriptionId", t),
54
- take: 1
55
- })))[0] ?? null, j = async (e, t) => (await e.query(C({
45
+ ]), j = (e) => A.has(e), M = (e) => e.find((e) => j(e.status)) ?? e[0] ?? null, N = (e, t) => e === null ? !1 : t === null || t.getTime() < e.getTime(), P = (t, n) => {
46
+ try {
47
+ return e(t.providerObservation, {
48
+ ...t,
49
+ ...n
50
+ });
51
+ } catch {
52
+ return null;
53
+ }
54
+ }, F = (t) => {
55
+ let n = {
56
+ tenantId: String(t.tenantId),
57
+ provider: String(t.provider),
58
+ providerSubscriptionId: String(t.providerSubscriptionId),
59
+ plan: String(t.plan),
60
+ status: String(t.status),
61
+ quantity: t.quantity == null ? 1 : Number(t.quantity),
62
+ currentPeriodStart: t.currentPeriodStart == null ? null : new Date(t.currentPeriodStart),
63
+ currentPeriodEnd: t.currentPeriodEnd == null ? null : new Date(t.currentPeriodEnd),
64
+ cancelAt: t.cancelAt == null ? null : new Date(t.cancelAt),
65
+ pastDueSince: t.pastDueSince == null ? null : new Date(t.pastDueSince),
66
+ statusEventAt: t.statusEventAt == null ? null : new Date(t.statusEventAt)
67
+ };
68
+ return {
69
+ ...n,
70
+ providerObservation: e(t.providerObservation, n)
71
+ };
72
+ }, I = async (e, t) => (await e.query(D({
56
73
  table: u,
57
- predicate: _("tenantId", t),
74
+ predicate: y("tenantId", t),
58
75
  order: [{
59
76
  column: "updatedAt",
60
77
  direction: "desc"
@@ -62,105 +79,169 @@ var b = (e) => `${e}_${Math.random().toString(36).slice(2)}${Date.now().toString
62
79
  column: "id",
63
80
  direction: "desc"
64
81
  }]
65
- }))).map(k), M = (e) => ({
66
- upsert: (t) => S(async () => {
67
- let n = await A(e, t.providerSubscriptionId), r = /* @__PURE__ */ new Date();
68
- if (n) {
69
- if (O(n.statusEventAt == null ? null : new Date(n.statusEventAt), t.statusEventAt) || w(String(n.status)) && !w(t.status)) return;
70
- await e.update(u, String(n.id), {
71
- tenantId: t.tenantId,
72
- provider: t.provider,
73
- plan: t.plan,
74
- status: t.status,
75
- quantity: t.quantity,
76
- currentPeriodStart: t.currentPeriodStart,
77
- currentPeriodEnd: t.currentPeriodEnd,
78
- cancelAt: t.cancelAt,
79
- statusEventAt: t.statusEventAt,
80
- updatedAt: r
81
- });
82
- } else await e.insert(u, {
83
- id: b("bsub"),
84
- tenantId: t.tenantId,
85
- provider: t.provider,
86
- providerSubscriptionId: t.providerSubscriptionId,
87
- plan: t.plan,
88
- status: t.status,
89
- quantity: t.quantity,
90
- currentPeriodStart: t.currentPeriodStart,
91
- currentPeriodEnd: t.currentPeriodEnd,
92
- cancelAt: t.cancelAt,
82
+ }))).map(F), L = () => /* @__PURE__ */ Error("The subscription observation write is unconfirmed."), R = (e, t) => ({
83
+ tenantId: e.tenantId,
84
+ provider: e.provider,
85
+ plan: e.plan,
86
+ status: e.status,
87
+ quantity: e.quantity,
88
+ currentPeriodStart: e.currentPeriodStart,
89
+ currentPeriodEnd: e.currentPeriodEnd,
90
+ cancelAt: e.cancelAt,
91
+ statusEventAt: e.statusEventAt,
92
+ providerObservation: t
93
+ }), z = (e, t, n) => {
94
+ if (e === void 0) throw L();
95
+ let r;
96
+ try {
97
+ r = F(e);
98
+ } catch {
99
+ throw L();
100
+ }
101
+ if (r.providerSubscriptionId !== t.providerSubscriptionId || r.tenantId !== t.tenantId || r.provider !== t.provider || r.plan !== t.plan || r.status !== t.status || r.quantity !== t.quantity || !O(r.currentPeriodStart, t.currentPeriodStart) || !O(r.currentPeriodEnd, t.currentPeriodEnd) || !O(r.cancelAt, t.cancelAt) || !O(r.statusEventAt, t.statusEventAt) || JSON.stringify(r.providerObservation ?? null) !== JSON.stringify(n)) throw L();
102
+ }, B = (e) => ({
103
+ ...D({
104
+ table: u,
105
+ predicate: y("providerSubscriptionId", e)
106
+ }),
107
+ lock: "update"
108
+ }), V = async (e, t) => {
109
+ let n = await e.query(B(t));
110
+ if (n.length > 1) throw L();
111
+ return n[0] ?? null;
112
+ }, H = [
113
+ "plan",
114
+ "quantity",
115
+ "status",
116
+ "currentPeriodStart",
117
+ "currentPeriodEnd",
118
+ "pastDueSince",
119
+ "statusEventAt"
120
+ ], U = (e) => {
121
+ let t = {};
122
+ for (let n of H) e[n] !== void 0 && (t[n] = e[n]);
123
+ return t;
124
+ }, W = (e, t) => H.every((n) => {
125
+ let r = t[n];
126
+ if (r === void 0) return !0;
127
+ let i = e[n];
128
+ return r instanceof Date || i instanceof Date ? r instanceof Date && i instanceof Date && O(i, r) : i === r;
129
+ }), G = async (e, t, n, r) => {
130
+ let i = String(t.providerSubscriptionId);
131
+ if (await e.update("_voltro_billing_subscriptions", String(t.id), {
132
+ ...n,
133
+ updatedAt: /* @__PURE__ */ new Date()
134
+ }) === null) throw L();
135
+ let a = await e.query(B(i)), o = a[0];
136
+ if (a.length !== 1 || o === void 0 || o.id !== t.id || o.tenantId !== t.tenantId || o.providerSubscriptionId !== i) throw L();
137
+ let s;
138
+ try {
139
+ s = F(o);
140
+ } catch {
141
+ throw L();
142
+ }
143
+ if (!r(s)) throw L();
144
+ }, K = (e, t, n) => e.transactional(async (e) => {
145
+ let r = await V(e, t);
146
+ r !== null && await G(e, r, {
147
+ status: n,
148
+ providerObservation: r.status === n ? r.providerObservation ?? null : null
149
+ }, (e) => e.status === n);
150
+ }), q = (t) => ({
151
+ upsert: (n) => T(async () => {
152
+ let r = structuredClone(n), i = e(r.providerObservation, r), a = /* @__PURE__ */ new Date(), o = C("bsub"), s = await t.insertIgnoreWithOutcome(u, {
153
+ id: o,
154
+ providerSubscriptionId: r.providerSubscriptionId,
155
+ ...R(r, i),
93
156
  pastDueSince: null,
94
- statusEventAt: t.statusEventAt,
95
- createdAt: r,
96
- updatedAt: r
157
+ createdAt: a,
158
+ updatedAt: a
159
+ }, { conflictColumns: ["providerSubscriptionId"] });
160
+ if (s.outcome === "inserted") {
161
+ if (s.row.id !== o) throw L();
162
+ return z(s.row, r, i);
163
+ }
164
+ await t.transactional(async (e) => {
165
+ let t = B(r.providerSubscriptionId), n = await e.query(t), o = n[0];
166
+ if (n.length !== 1 || o === void 0) throw L();
167
+ if (o.tenantId !== r.tenantId || o.provider !== r.provider) throw new m({
168
+ source: "subscriptionStore",
169
+ message: "The provider subscription belongs to different native custody.",
170
+ transient: !1
171
+ });
172
+ if (N(o.statusEventAt == null ? null : new Date(o.statusEventAt), r.statusEventAt) || k(String(o.status)) && !k(r.status)) return;
173
+ if (await e.update("_voltro_billing_subscriptions", String(o.id), {
174
+ ...R(r, i),
175
+ updatedAt: a
176
+ }) === null) throw L();
177
+ let s = await e.query(t);
178
+ if (s.length !== 1 || s[0].id !== o.id) throw L();
179
+ z(s[0], r, i);
97
180
  });
98
181
  }, "subscriptionStore"),
99
- getByTenant: (t) => S(async () => D(await j(e, t)), "subscriptionStore"),
100
- listByTenant: (t) => S(() => j(e, t), "subscriptionStore"),
101
- listByStatus: (t) => S(async () => (await e.query(C({
182
+ getByTenant: (e) => T(async () => M(await I(t, e)), "subscriptionStore"),
183
+ listByTenant: (e) => T(() => I(t, e), "subscriptionStore"),
184
+ listByStatus: (e) => T(async () => (await t.query(D({
102
185
  table: u,
103
- predicate: _("status", t),
186
+ predicate: y("status", e),
104
187
  order: [{
105
188
  column: "updatedAt",
106
189
  direction: "asc"
107
190
  }]
108
- }))).map(k), "subscriptionStore"),
109
- markCanceled: (t) => S(async () => {
110
- let n = await A(e, t);
111
- n && await e.update(u, String(n.id), {
112
- status: "canceled",
113
- updatedAt: /* @__PURE__ */ new Date()
114
- });
115
- }, "subscriptionStore"),
116
- patchByTenant: (t, n) => S(async () => {
117
- let r = D(await j(e, t)), i = r === null ? null : await A(e, r.providerSubscriptionId);
118
- i && await e.update(u, String(i.id), {
119
- ...n.plan === void 0 ? {} : { plan: n.plan },
120
- ...n.quantity === void 0 ? {} : { quantity: n.quantity },
121
- ...n.status === void 0 ? {} : { status: n.status },
122
- ...n.currentPeriodStart === void 0 ? {} : { currentPeriodStart: n.currentPeriodStart },
123
- ...n.currentPeriodEnd === void 0 ? {} : { currentPeriodEnd: n.currentPeriodEnd },
124
- ...n.pastDueSince === void 0 ? {} : { pastDueSince: n.pastDueSince },
125
- ...n.statusEventAt === void 0 ? {} : { statusEventAt: n.statusEventAt },
126
- updatedAt: /* @__PURE__ */ new Date()
127
- });
128
- }, "subscriptionStore"),
129
- setStatus: (t, n) => S(async () => {
130
- let r = await A(e, t);
131
- r && await e.update(u, String(r.id), {
132
- status: n,
133
- updatedAt: /* @__PURE__ */ new Date()
134
- });
135
- }, "subscriptionStore")
136
- }), N = (e) => ({
191
+ }))).map(F), "subscriptionStore"),
192
+ markCanceled: (e) => T(() => K(t, e, "canceled"), "subscriptionStore"),
193
+ patchByTenant: (e, n) => T(() => t.transactional(async (t) => {
194
+ let r = M(await I(t, e));
195
+ if (r === null) return;
196
+ let i = await V(t, r.providerSubscriptionId);
197
+ if (i === null || i.tenantId !== e || M(await I(t, e))?.providerSubscriptionId !== r.providerSubscriptionId) throw L();
198
+ await G(t, i, {
199
+ ...U(n),
200
+ providerObservation: P(F(i), n)
201
+ }, (e) => W(e, n));
202
+ }), "subscriptionStore"),
203
+ patchBySubscription: (e, n, r, i) => T(() => t.transactional(async (t) => {
204
+ let a = await V(t, n), o = a === null ? null : F(a);
205
+ if (a === null || o === null || o.tenantId !== e || i !== void 0 && !O(o.statusEventAt, i) || k(o.status) && r.status !== void 0 && !k(r.status)) throw E();
206
+ await G(t, a, {
207
+ ...U(r),
208
+ providerObservation: P(o, r)
209
+ }, (t) => t.tenantId === e && W(t, r));
210
+ }), "subscriptionStore"),
211
+ setStatus: (e, n) => T(() => K(t, e, n), "subscriptionStore")
212
+ }), J = {
213
+ meter: "meterDispatchedThrough",
214
+ invoice: "invoiceDispatchedThrough"
215
+ }, Y = (e) => ({
137
216
  tenantId: String(e.tenantId),
138
217
  entitlementKey: String(e.entitlementKey),
139
218
  period: String(e.period),
140
219
  used: Number(e.used ?? 0),
141
- reportedToProvider: Number(e.reportedToProvider ?? 0)
142
- }), P = async (e, t, n, r) => (await e.query(C({
220
+ reportedToProvider: Number(e.reportedToProvider ?? 0),
221
+ meterDispatchedThrough: Number(e.meterDispatchedThrough ?? 0),
222
+ invoiceDispatchedThrough: Number(e.invoiceDispatchedThrough ?? 0)
223
+ }), X = async (e, t, n, r) => (await e.query(D({
143
224
  table: "_voltro_billing_usage",
144
- predicate: h(_("tenantId", t), _("entitlementKey", n), _("period", r)),
225
+ predicate: _(y("tenantId", t), y("entitlementKey", n), y("period", r)),
145
226
  take: 1
146
- })))[0] ?? null, F = (t) => ({
147
- recordEvent: (n) => o(t, n, async (t, n) => {
148
- let r = F(t), i = await p.runPromise(r.used(n.tenantId, n.entitlementKey, n.period));
149
- if (!Number.isSafeInteger(i + n.quantity)) throw new e({
227
+ })))[0] ?? null, Z = (e) => ({
228
+ recordEvent: (t) => s(e, t, async (e, t) => {
229
+ let n = Z(e), r = await h.runPromise(n.used(t.tenantId, t.entitlementKey, t.period));
230
+ if (!Number.isSafeInteger(r + t.quantity)) throw new m({
150
231
  source: "usageEvent",
151
232
  message: "Usage total exceeds exact integer storage.",
152
233
  transient: !1
153
234
  });
154
- return p.runPromise(r.increment(n.tenantId, n.entitlementKey, n.period, n.quantity));
235
+ return h.runPromise(n.increment(t.tenantId, t.entitlementKey, t.period, t.quantity));
155
236
  }),
156
- used: (e, n, r) => S(async () => {
157
- let i = await P(t, e, n, r);
237
+ used: (t, n, r) => T(async () => {
238
+ let i = await X(e, t, n, r);
158
239
  return i ? Number(i.used ?? 0) : 0;
159
240
  }, "usageStore"),
160
- consume: (e, n, r, i, a) => S(async () => {
241
+ consume: (t, n, r, i, a) => T(async () => {
161
242
  for (let o = 0; o < 32; o++) {
162
243
  o > 0 && await new Promise((e) => setTimeout(e, o));
163
- let s = await P(t, e, n, r), c = s ? Number(s.used ?? 0) : 0;
244
+ let s = await X(e, t, n, r), c = s ? Number(s.used ?? 0) : 0;
164
245
  if (c + i > a) return {
165
246
  allowed: !1,
166
247
  entitlement: n,
@@ -169,10 +250,10 @@ var b = (e) => `${e}_${Math.random().toString(36).slice(2)}${Date.now().toString
169
250
  cost: i
170
251
  };
171
252
  if (s) {
172
- if (await t.updateMany("_voltro_billing_usage", {
253
+ if (await e.updateMany("_voltro_billing_usage", {
173
254
  used: c + i,
174
255
  updatedAt: /* @__PURE__ */ new Date()
175
- }, { where: h(_("id", String(s.id)), _("used", c)) }) === 1) return {
256
+ }, { where: _(y("id", String(s.id)), y("used", c)) }) === 1) return {
176
257
  allowed: !0,
177
258
  entitlement: n,
178
259
  limit: a,
@@ -180,9 +261,9 @@ var b = (e) => `${e}_${Math.random().toString(36).slice(2)}${Date.now().toString
180
261
  cost: i
181
262
  };
182
263
  } else {
183
- let o = b("buse"), s = await t.insertIgnore(d, {
264
+ let o = C("buse"), s = await e.insertIgnore(d, {
184
265
  id: o,
185
- tenantId: e,
266
+ tenantId: t,
186
267
  entitlementKey: n,
187
268
  period: r,
188
269
  used: i,
@@ -202,22 +283,22 @@ var b = (e) => `${e}_${Math.random().toString(36).slice(2)}${Date.now().toString
202
283
  };
203
284
  }
204
285
  }
205
- throw Error(`billing usage consume: contention on (${e}, ${n}, ${r}) exceeded 32 attempts`);
286
+ throw Error(`billing usage consume: contention on (${t}, ${n}, ${r}) exceeded 32 attempts`);
206
287
  }, "usageStore"),
207
- increment: (e, n, r, i) => S(async () => {
288
+ increment: (t, n, r, i) => T(async () => {
208
289
  for (let a = 0; a < 32; a++) {
209
290
  a > 0 && await new Promise((e) => setTimeout(e, a));
210
- let o = await P(t, e, n, r);
291
+ let o = await X(e, t, n, r);
211
292
  if (o) {
212
- let e = Number(o.used ?? 0);
213
- if (await t.updateMany("_voltro_billing_usage", {
214
- used: e + i,
293
+ let t = Number(o.used ?? 0);
294
+ if (await e.updateMany("_voltro_billing_usage", {
295
+ used: t + i,
215
296
  updatedAt: /* @__PURE__ */ new Date()
216
- }, { where: h(_("id", String(o.id)), _("used", e)) }) === 1) return e + i;
297
+ }, { where: _(y("id", String(o.id)), y("used", t)) }) === 1) return t + i;
217
298
  } else {
218
- let a = b("buse"), o = await t.insertIgnore(d, {
299
+ let a = C("buse"), o = await e.insertIgnore(d, {
219
300
  id: a,
220
- tenantId: e,
301
+ tenantId: t,
221
302
  entitlementKey: n,
222
303
  period: r,
223
304
  used: i,
@@ -231,29 +312,40 @@ var b = (e) => `${e}_${Math.random().toString(36).slice(2)}${Date.now().toString
231
312
  if (String(o.id) === a) return i;
232
313
  }
233
314
  }
234
- throw Error(`billing usage increment: contention on (${e}, ${n}, ${r}) exceeded 32 attempts`);
315
+ throw Error(`billing usage increment: contention on (${t}, ${n}, ${r}) exceeded 32 attempts`);
235
316
  }, "usageStore"),
236
- pending: () => S(async () => (await t.query(C({ table: d }))).map(N).filter((e) => e.used > e.reportedToProvider), "usageStore"),
237
- markReported: (e, n, r, i) => S(async () => {
238
- let a = await P(t, e, n, r);
239
- a && await t.update(d, String(a.id), {
317
+ pending: () => T(async () => (await e.query(D({ table: d }))).map(Y).filter((e) => e.used > e.reportedToProvider), "usageStore"),
318
+ markReported: (t, n, r, i) => T(async () => {
319
+ let a = await X(e, t, n, r);
320
+ a && await e.updateMany(d, {
240
321
  reportedToProvider: i,
241
322
  updatedAt: /* @__PURE__ */ new Date()
242
- });
323
+ }, { where: _(y("id", String(a.id)), b("reportedToProvider", i)) });
324
+ }, "usageStore"),
325
+ claimDispatch: (t, n, r, i, { expected: a, from: o, through: s }) => T(async () => {
326
+ if (s <= o) return !1;
327
+ let c = await X(e, t, n, r);
328
+ if (!c) return !1;
329
+ let l = J[i];
330
+ return await e.updateMany(d, {
331
+ [l]: s,
332
+ updatedAt: /* @__PURE__ */ new Date()
333
+ }, { where: _(y("id", String(c.id)), y(l, a), y("reportedToProvider", o)) }) === 1;
243
334
  }, "usageStore")
244
- }), I = () => {
245
- for (let e of [...f(), m]) g(e);
246
- return L(new v());
247
- }, L = (e) => ({
248
- closures: c(e),
249
- checkouts: s(e),
250
- customers: t(e),
251
- subscriptions: M(e),
252
- invoices: r(e),
335
+ }), Q = () => {
336
+ for (let e of [...f(), g]) v(e);
337
+ return $(new x());
338
+ }, $ = (e) => ({
339
+ subscriptionWrites: t(e),
340
+ closures: l(e),
341
+ checkouts: c(e),
342
+ customers: a(e),
343
+ subscriptions: q(e),
344
+ invoices: o(e),
253
345
  historyJournal: n(e),
254
346
  historyWork: i(e),
255
- historyProgress: a(e),
256
- usage: F(e),
257
- dunningNotices: l(e)
347
+ historyProgress: r(e),
348
+ usage: Z(e),
349
+ dunningNotices: p(e)
258
350
  });
259
- export { L as dataStoreStores, M as dataStoreSubscriptionStore, F as dataStoreUsageStore, E as isLive, O as isStaleStatusEvent, w as isTerminal, I as memoryStores, D as selectCurrentSubscription };
351
+ export { $ as dataStoreStores, q as dataStoreSubscriptionStore, Z as dataStoreUsageStore, j as isLive, N as isStaleStatusEvent, k as isTerminal, Q as memoryStores, M as selectCurrentSubscription };
@@ -1,20 +1,20 @@
1
- import { captureProviderAccount as e, captureProviderCustomer as t, exactProviderIdentifier as n, providerIdentityError as r, sameProviderAccount as i } from "./providerIdentity.js";
2
- import { stripeCall as a } from "./stripeClient.js";
1
+ import { stripeCall as e } from "./stripeClient.js";
2
+ import { captureProviderAccount as t, captureProviderCustomer as n, exactProviderIdentifier as r, providerIdentityError as i, sameProviderAccount as a } from "./providerIdentity.js";
3
3
  import { Effect as o } from "effect";
4
4
  // src/stripeIdentity.ts
5
5
  var s = (e) => o.try({
6
6
  try: e,
7
- catch: () => r()
8
- }), c = (t) => o.gen(function* () {
9
- let i = yield* a("stripe.accounts.retrieve", () => t.accounts.retrieve(null)), o = yield* s(() => {
10
- if (!n(i.id)) throw r();
11
- return i.id;
12
- }), c = yield* a("stripe.balance.retrieve", () => t.balance.retrieve()), l = yield* s(() => e({
7
+ catch: () => i()
8
+ }), c = (n) => o.gen(function* () {
9
+ let a = yield* e("stripe.accounts.retrieve", () => n.accounts.retrieve(null)), o = yield* s(() => {
10
+ if (!r(a.id)) throw i();
11
+ return a.id;
12
+ }), c = yield* e("stripe.balance.retrieve", () => n.balance.retrieve()), l = yield* s(() => t({
13
13
  providerAccountId: o,
14
14
  livemode: c.livemode
15
- })), u = yield* a("stripe.accounts.retrieve", () => t.accounts.retrieve(null));
15
+ })), u = yield* e("stripe.accounts.retrieve", () => n.accounts.retrieve(null));
16
16
  return yield* s(() => {
17
- if (u.id !== o) throw r();
17
+ if (u.id !== o) throw i();
18
18
  return l;
19
19
  });
20
20
  }), l = (l, u) => {
@@ -27,23 +27,23 @@ var s = (e) => o.try({
27
27
  };
28
28
  return o.gen(function* () {
29
29
  let o = yield* s(() => {
30
- if (!n(d.providerCustomerId)) throw r();
30
+ if (!r(d.providerCustomerId)) throw i();
31
31
  return Object.freeze({
32
- account: e(d.account),
32
+ account: t(d.account),
33
33
  providerCustomerId: d.providerCustomerId
34
34
  });
35
35
  }), u = yield* c(l);
36
36
  yield* s(() => {
37
- if (!i(u, o.account)) throw r();
37
+ if (!a(u, o.account)) throw i();
38
38
  });
39
- let f = yield* a("stripe.customers.retrieve", () => l.customers.retrieve(o.providerCustomerId)), p = yield* s(() => {
39
+ let f = yield* e("stripe.customers.retrieve", () => l.customers.retrieve(o.providerCustomerId)), p = yield* s(() => {
40
40
  let e = f.deleted;
41
- if (e !== void 0 && typeof e != "boolean" || f.id !== o.providerCustomerId || f.deleted !== !0 && f.livemode !== o.account.livemode) throw r();
41
+ if (e !== void 0 && typeof e != "boolean" || f.id !== o.providerCustomerId || f.deleted !== !0 && f.livemode !== o.account.livemode) throw i();
42
42
  return f.deleted === !0;
43
43
  }), m = yield* c(l);
44
44
  return yield* s(() => {
45
- if (!i(m, o.account)) throw r();
46
- return t({
45
+ if (!a(m, o.account)) throw i();
46
+ return n({
47
47
  account: o.account,
48
48
  providerCustomerId: o.providerCustomerId,
49
49
  deleted: p,
@@ -1,29 +1,29 @@
1
- import { BillingError as e } from "./types.js";
2
- import { sameProviderAccount as t } from "./providerIdentity.js";
3
- import { captureInvoiceHistoryInput as n, captureInvoiceHistoryPage as r, historyError as i } from "./invoiceHistory.js";
4
- import { stripeCall as a } from "./stripeClient.js";
5
- import { stripeAccountIdentity as o } from "./stripeIdentity.js";
1
+ import { stripeCall as e } from "./stripeClient.js";
2
+ import { stripeAccountIdentity as t } from "./stripeIdentity.js";
3
+ import { sameProviderAccount as n } from "./providerIdentity.js";
4
+ import { captureInvoiceHistoryInput as r, captureInvoiceHistoryPage as i, historyError as a } from "./invoiceHistory.js";
5
+ import { BillingError as o } from "./types.js";
6
6
  import { Effect as s } from "effect";
7
7
  // src/stripeInvoiceHistory.ts
8
- var c = (e, c) => s.gen(function* () {
9
- let f = yield* d(() => n(c)), p = yield* o(e);
10
- if (!t(p, f.account)) return yield* s.fail(i("The provider account differs before invoice history access."));
8
+ var c = (o, c) => s.gen(function* () {
9
+ let f = yield* d(() => r(c)), p = yield* t(o);
10
+ if (!n(p, f.account)) return yield* s.fail(a("The provider account differs before invoice history access."));
11
11
  let m = f.cursor;
12
12
  if (m !== void 0) {
13
- let t = yield* a("stripe.invoices.retrieve", () => e.invoices.retrieve(m.afterInvoiceId));
13
+ let t = yield* e("stripe.invoices.retrieve", () => o.invoices.retrieve(m.afterInvoiceId));
14
14
  yield* d(() => {
15
- if (t.id !== f.cursor?.afterInvoiceId || l(t.customer) !== f.providerCustomerId || t.livemode !== f.account.livemode) throw i("The invoice cursor belongs to another customer/account.");
15
+ if (t.id !== f.cursor?.afterInvoiceId || l(t.customer) !== f.providerCustomerId || t.livemode !== f.account.livemode) throw a("The invoice cursor belongs to another customer/account.");
16
16
  });
17
17
  }
18
- let h = yield* a("stripe.invoices.list", () => e.invoices.list({
18
+ let h = yield* e("stripe.invoices.list", () => o.invoices.list({
19
19
  customer: f.providerCustomerId,
20
20
  limit: f.limit,
21
21
  ...f.cursor === void 0 ? {} : { starting_after: f.cursor.afterInvoiceId }
22
22
  })), g = yield* d(() => {
23
- if (!Array.isArray(h.data) || h.data.length > f.limit || typeof h.has_more != "boolean" || h.has_more && h.data.length === 0) throw i("The provider invoice page is incomplete.");
23
+ if (!Array.isArray(h.data) || h.data.length > f.limit || typeof h.has_more != "boolean" || h.has_more && h.data.length === 0) throw a("The provider invoice page is incomplete.");
24
24
  let e = h.data.map((e) => {
25
25
  let t = u(e.status);
26
- if (l(e.customer) !== f.providerCustomerId || e.livemode !== f.account.livemode || !Number.isSafeInteger(e.created) || !Number.isSafeInteger(e.created * 1e3)) throw i();
26
+ if (l(e.customer) !== f.providerCustomerId || e.livemode !== f.account.livemode || !Number.isSafeInteger(e.created) || !Number.isSafeInteger(e.created * 1e3)) throw a();
27
27
  return {
28
28
  providerInvoiceId: e.id,
29
29
  providerCustomerId: f.providerCustomerId,
@@ -36,8 +36,8 @@ var c = (e, c) => s.gen(function* () {
36
36
  pdfUrl: e.invoice_pdf ?? null
37
37
  };
38
38
  }), t = e[e.length - 1];
39
- if (h.has_more && t === void 0) throw i();
40
- return r(f, {
39
+ if (h.has_more && t === void 0) throw a();
40
+ return i(f, {
41
41
  account: f.account,
42
42
  providerCustomerId: f.providerCustomerId,
43
43
  invoices: e,
@@ -48,8 +48,8 @@ var c = (e, c) => s.gen(function* () {
48
48
  } : null,
49
49
  observedAt: /* @__PURE__ */ new Date()
50
50
  });
51
- }), _ = yield* o(e);
52
- return t(_, f.account) ? g : yield* s.fail(i("The provider account changed during invoice history access.", !0));
51
+ }), _ = yield* t(o);
52
+ return n(_, f.account) ? g : yield* s.fail(a("The provider account changed during invoice history access.", !0));
53
53
  }), l = (e) => typeof e == "string" ? e : e?.id ?? null, u = (e) => {
54
54
  switch (e) {
55
55
  case "draft": return "draft";
@@ -57,10 +57,10 @@ var c = (e, c) => s.gen(function* () {
57
57
  case "paid": return "paid";
58
58
  case "uncollectible": return "uncollectible";
59
59
  case "void": return "void";
60
- default: throw i("The invoice history status is unsupported.");
60
+ default: throw a("The invoice history status is unsupported.");
61
61
  }
62
- }, d = (t) => s.try({
63
- try: t,
64
- catch: (t) => t instanceof e ? t : i()
62
+ }, d = (e) => s.try({
63
+ try: e,
64
+ catch: (e) => e instanceof o ? e : a()
65
65
  });
66
66
  export { c as stripeInvoiceHistory };