@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/service.js CHANGED
@@ -1,361 +1,490 @@
1
- import { BillingError as e, BillingService as t, EntitlementExceeded as n } from "./types.js";
2
- import { captureProviderAccount as r, sameProviderAccount as i } from "./providerIdentity.js";
3
- import { evaluateEntitlement as a } from "./entitlement.js";
4
- import { assertInvoiceSnapshot as o, invoiceSnapshotError as s } from "./invoiceSnapshot.js";
5
- import { captureInvoiceHistoryInput as c, captureInvoiceHistoryPage as l, historyError as u } from "./invoiceHistory.js";
6
- import { DUNNING_LOCK_STEP_ID as d, defaultDunningEmail as f, dueSteps as p, episodeKeyOf as m, evaluateBillingEntitlement as h, resolveDunningConfig as g } from "./dunning.js";
7
- import { isLive as _, memoryStores as v } from "./stores.js";
8
- import { Effect as y, Layer as b, Schedule as x } from "effect";
9
- import { createLogger as S } from "@voltro/logger";
1
+ import { captureSubscriptionObservation as e, observeSubscriptionProvider as t, subscriptionReadbackHolds as n } from "./subscriptionObservation.js";
2
+ import { billingRequestStale as r } from "./subscriptionWriteStore.js";
3
+ import { evaluateEntitlement as i } from "./entitlement.js";
4
+ import { assertInvoiceSnapshot as a, invoiceSnapshotError as o } from "./invoiceSnapshot.js";
5
+ import { captureProviderAccount as s, sameProviderAccount as c } from "./providerIdentity.js";
6
+ import { captureInvoiceHistoryInput as l, captureInvoiceHistoryPage as u, historyError as d } from "./invoiceHistory.js";
7
+ import { isLive as f, memoryStores as p } from "./stores.js";
8
+ import { makeHistoricalUsageInvoicer as m } from "./historicalUsage.js";
9
+ import { DUNNING_LOCK_STEP_ID as h, defaultDunningEmail as g, dueSteps as _, episodeKeyOf as v, evaluateBillingEntitlement as y, resolveDunningConfig as b } from "./dunning.js";
10
+ import { BillingClosurePending as ee, BillingError as x, BillingService as S, EntitlementExceeded as te } from "./types.js";
11
+ import { Effect as C, Fiber as ne, Layer as w, Schedule as T } from "effect";
12
+ import { createLogger as E } from "@voltro/logger";
10
13
  // src/service.ts
11
- var C = S({ scope: "@voltro/plugin-billing" }), w = 3, T = /* @__PURE__ */ new Set([
14
+ var D = E({ scope: "@voltro/plugin-billing" }), re = 3, ie = 9e5, O = /* @__PURE__ */ new Set([
12
15
  "active",
13
16
  "trialing",
14
17
  "pastDue"
15
- ]), E = /* @__PURE__ */ new Set([...T, "incomplete"]), D = (e = /* @__PURE__ */ new Date()) => `${e.getUTCFullYear()}-${String(e.getUTCMonth() + 1).padStart(2, "0")}`, ee = (e) => ({ stores: e ?? v() }), O = (e, t) => e.pipe(y.retry({
16
- schedule: x.recurs(Math.max(0, t - 1)),
18
+ ]), ae = /* @__PURE__ */ new Set([...O, "incomplete"]), k = 6e4, A = 4, oe = (e) => e.pipe(C.retry({
19
+ schedule: T.recurs(A),
20
+ while: (e) => e.source === "subscriptionStore" && e.transient
21
+ })), j = (e = /* @__PURE__ */ new Date()) => `${e.getUTCFullYear()}-${String(e.getUTCMonth() + 1).padStart(2, "0")}`, se = (e) => ({ stores: e ?? p() }), M = (e, t) => e.pipe(C.retry({
22
+ schedule: T.recurs(Math.max(0, t - 1)),
17
23
  while: (e) => e.transient
18
- })), k = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,99}$/, te = "usage key must be 1–100 characters of A–Z, a–z, 0–9, \"_\", \".\", \":\" or \"-\", starting with a letter or digit", A = (t) => {
19
- let { provider: v, plans: b } = t, x = t.attempts ?? 3, S = t.checkout, A = t.now ?? (() => /* @__PURE__ */ new Date()), j = (n, r, i) => y.gen(function* () {
20
- if (n.length === 0) return yield* y.fail(new e({
24
+ })), ce = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,99}$/, le = "usage key must be 1–100 characters of A–Z, a–z, 0–9, \"_\", \".\", \":\" or \"-\", starting with a letter or digit", N = (p) => {
25
+ let { provider: S, plans: w } = p, T = p.attempts ?? 3, E = p.checkout, k = p.now ?? (() => /* @__PURE__ */ new Date()), A = p.invoiceHistoryHeadRescanMs ?? ie;
26
+ if (!Number.isSafeInteger(A) || A < 1e3 || A > 864e5) throw TypeError("Invoice-history head rescans require a whole interval from one second through one day");
27
+ let N = (e, t, n) => C.gen(function* () {
28
+ if (e.length === 0) return yield* C.fail(new x({
21
29
  source: "billing",
22
30
  message: "no tenant on this call",
23
31
  transient: !1
24
32
  }));
25
- if (r !== "cancel" && (yield* N.stores.closures.getAccount(n)) !== null) return yield* y.fail(new e({
33
+ if (t !== "cancel" && (yield* P.stores.closures.getAccount(e)) !== null) return yield* C.fail(new x({
26
34
  source: "billing",
27
35
  message: "This billing account is closing. New paid actions are unavailable.",
28
36
  transient: !1
29
37
  }));
30
- if (t.admit !== void 0 && (yield* t.admit(n, r)), yield* L(n), i !== void 0) {
31
- let e = yield* N.stores.customers.getByTenant(n);
32
- if (e === null || e.providerCustomerId !== i) return yield* y.fail(s("Checkout customer custody changed before dispatch or private URL replay."));
38
+ if (t !== "cancel" && (yield* P.stores.subscriptionWrites.assertOpen(e)), p.admit !== void 0 && (yield* p.admit(e, t)), yield* R(e), n !== void 0) {
39
+ let t = yield* P.stores.customers.getByTenant(e);
40
+ if (t === null || t.providerCustomerId !== n) return yield* C.fail(o("Checkout customer custody changed before dispatch or private URL replay."));
33
41
  }
34
- }), ne = t.redirectOrigins?.map((e) => new URL(e).origin), M = (t, n) => {
35
- let r = (t) => y.fail(new e({
42
+ }), ue = p.redirectOrigins?.map((e) => new URL(e).origin), de = (e, t) => {
43
+ let n = (e) => C.fail(new x({
36
44
  source: "billing",
37
- message: `${n} ${t}`,
45
+ message: `${t} ${e}`,
38
46
  transient: !1
39
- })), i;
47
+ })), r;
40
48
  try {
41
- i = new URL(t);
49
+ r = new URL(e);
42
50
  } catch {
43
- return r("is not an absolute URL");
51
+ return n("is not an absolute URL");
44
52
  }
45
- return i.protocol !== "https:" && i.protocol !== "http:" ? r("must be an http(s) URL") : ne !== void 0 && !ne.includes(i.origin) ? r(`must point at one of the configured redirect origins, not ${i.origin}`) : y.void;
46
- }, N = ee(t.stores), P = t.dunning ?? g(void 0, {}), F, I = () => {
47
- if (F !== void 0) return y.succeed(F);
48
- let e = v.fetchAccountIdentity?.bind(v);
49
- return e === void 0 ? y.fail(s("Account-qualified billing is unsupported by this provider.")) : e().pipe(y.flatMap((e) => y.try({
53
+ return r.protocol !== "https:" && r.protocol !== "http:" ? n("must be an http(s) URL") : ue !== void 0 && !ue.includes(r.origin) ? n(`must point at one of the configured redirect origins, not ${r.origin}`) : C.void;
54
+ }, P = se(p.stores), F = p.dunning ?? b(void 0, {}), I, L = () => {
55
+ if (I !== void 0) return C.succeed(I);
56
+ let e = S.fetchAccountIdentity?.bind(S);
57
+ return e === void 0 ? C.fail(o("Account-qualified billing is unsupported by this provider.")) : e().pipe(C.flatMap((e) => C.try({
50
58
  try: () => {
51
59
  let t = Object.freeze({
52
- provider: v.name,
53
- account: r(e)
60
+ provider: S.name,
61
+ account: s(e)
54
62
  });
55
- if (F !== void 0 && !i(F.account, t.account)) throw s("The provider account changed during observation.");
56
- return F ??= t, F;
63
+ if (I !== void 0 && !c(I.account, t.account)) throw o("The provider account changed during observation.");
64
+ return I ??= t, I;
57
65
  },
58
- catch: () => s("A fixed provider account/mode is required.")
66
+ catch: () => o("A fixed provider account/mode is required.")
59
67
  })));
60
- }, L = (e) => I().pipe(y.flatMap((t) => N.stores.customers.assertAccount(e, t))), R = (e) => I().pipe(y.flatMap((t) => N.stores.customers.reserveAccount(e, t))), re = (e) => N.stores.customers.accountForTenant(e).pipe(y.flatMap((t) => t === null ? R(e) : y.void)), z = (e) => L(e).pipe(y.andThen(N.stores.customers.getByTenant(e))), B = (e, t) => y.gen(function* () {
61
- let n = yield* I(), r = v.fetchCustomerSnapshot?.bind(v);
62
- if (r === void 0) return yield* y.fail(s("Positive provider customer evidence is required."));
63
- if ((yield* N.stores.customers.getByTenant(e)) === null && (yield* N.stores.subscriptions.listByTenant(e)).some((e) => _(e.status))) return yield* y.fail(s("A previous live subscription must be reconciled before customer relinking."));
64
- let i = yield* O(r({
68
+ }, R = (e) => L().pipe(C.flatMap((t) => P.stores.customers.assertAccount(e, t))), fe = (e) => L().pipe(C.flatMap((t) => P.stores.customers.reserveAccount(e, t))), pe = (e) => P.stores.customers.accountForTenant(e).pipe(C.flatMap((t) => t === null ? fe(e) : C.void)), z = (e) => R(e).pipe(C.andThen(P.stores.customers.getByTenant(e))), B = (e, t) => C.gen(function* () {
69
+ let n = yield* L(), r = S.fetchCustomerSnapshot?.bind(S);
70
+ if (r === void 0) return yield* C.fail(o("Positive provider customer evidence is required."));
71
+ if ((yield* P.stores.customers.getByTenant(e)) === null && (yield* P.stores.subscriptions.listByTenant(e)).some((e) => f(e.status))) return yield* C.fail(o("A previous live subscription must be reconciled before customer relinking."));
72
+ let i = yield* M(r({
65
73
  account: n.account,
66
74
  providerCustomerId: t
67
- }), x);
68
- return yield* N.stores.customers.bind({
75
+ }), T);
76
+ return yield* P.stores.customers.bind({
69
77
  ...n,
70
78
  tenantId: e,
71
79
  providerCustomerId: t
72
80
  }, i);
73
- }), ie = (e) => N.stores.subscriptions.getByTenant(e).pipe(y.flatMap((t) => N.stores.customers.accountForTenant(e).pipe(y.flatMap((n) => t !== null && n === null ? y.fail(s("The retained subscription has no qualified billing account.")) : y.succeed(h(t, P, A(), e)))))), ae = (e) => ie(e).pipe(y.map((e) => e.plan)), oe = (e) => N.stores.subscriptions.getByTenant(e), se = (e, n) => y.gen(function* () {
74
- if (t.resolveEntitlementLimit !== void 0) {
75
- let r = yield* t.resolveEntitlementLimit(e, n);
76
- if (r !== null) return r;
81
+ }), me = (e) => P.stores.subscriptions.getByTenant(e).pipe(C.flatMap((t) => P.stores.customers.accountForTenant(e).pipe(C.flatMap((n) => t !== null && n === null ? C.fail(o("The retained subscription has no qualified billing account.")) : C.succeed(y(t, F, k(), e)))))), he = (e) => me(e).pipe(C.map((e) => e.plan)), ge = (e) => P.stores.subscriptions.getByTenant(e), _e = (e, t) => C.gen(function* () {
82
+ if (p.resolveEntitlementLimit !== void 0) {
83
+ let n = yield* p.resolveEntitlementLimit(e, t);
84
+ if (n !== null) return n;
77
85
  }
78
- let r = yield* ae(e);
79
- return b.entitlementLimit(r, n);
80
- }), ce = (e, t, n) => y.gen(function* () {
81
- let r = yield* se(e, t), i = yield* N.stores.usage.used(e, t, D(A()));
82
- return a(t, r, i, n);
83
- }), le = (e, t, r) => y.gen(function* () {
84
- let i = yield* se(e, t);
85
- if (!Number.isFinite(i) || r <= 0) return;
86
- let a = D(A());
87
- yield* re(e);
88
- let o = yield* N.stores.usage.consume(e, t, a, r, i);
89
- if (!o.allowed) return yield* y.fail(new n({
86
+ let n = yield* he(e);
87
+ return w.entitlementLimit(n, t);
88
+ }), ve = (e, t, n) => C.gen(function* () {
89
+ let r = yield* _e(e, t), a = yield* P.stores.usage.used(e, t, j(k()));
90
+ return i(t, r, a, n);
91
+ }), ye = (e, t, n) => C.gen(function* () {
92
+ let r = yield* _e(e, t);
93
+ if (!Number.isFinite(r) || n <= 0) return;
94
+ let i = j(k());
95
+ yield* pe(e);
96
+ let a = yield* P.stores.usage.consume(e, t, i, n, r);
97
+ if (!a.allowed) return yield* C.fail(new te({
90
98
  entitlement: t,
91
- limit: o.limit,
92
- used: o.used,
93
- cost: r
99
+ limit: a.limit,
100
+ used: a.used,
101
+ cost: n
94
102
  }));
95
- }), ue = (t, n, r) => k.test(n) ? Number.isFinite(r) ? r <= 0 ? y.void : re(t).pipe(y.andThen(N.stores.usage.increment(t, n, D(A()), r)), y.asVoid) : y.fail(new e({
103
+ }), be = (e, t, n) => ce.test(t) ? Number.isFinite(n) ? n <= 0 ? C.void : pe(e).pipe(C.andThen(P.stores.usage.increment(e, t, j(k()), n)), C.asVoid) : C.fail(new x({
96
104
  source: "billing",
97
- message: `usage quantity must be a finite number, got ${r}`,
105
+ message: `usage quantity must be a finite number, got ${n}`,
98
106
  transient: !1
99
- })) : y.fail(new e({
107
+ })) : C.fail(new x({
100
108
  source: "billing",
101
- message: te,
109
+ message: le,
102
110
  transient: !1
103
- })), de = (t) => y.gen(function* () {
104
- if (!k.test(t.entitlementKey) || !(t.occurredAt instanceof Date) || !Number.isFinite(t.occurredAt.getTime()) || t.occurredAt.getTime() < 0 || !Number.isFinite(A().getTime())) return yield* y.fail(new e({
111
+ })), xe = (e) => C.gen(function* () {
112
+ if (!ce.test(e.entitlementKey) || !(e.occurredAt instanceof Date) || !Number.isFinite(e.occurredAt.getTime()) || e.occurredAt.getTime() < 0 || !Number.isFinite(k().getTime())) return yield* C.fail(new x({
105
113
  source: "usageEvent",
106
114
  message: "Usage event requires a valid meter key and a completed occurrence timestamp.",
107
115
  transient: !1
108
116
  }));
109
- if (t.occurredAt.getTime() > A().getTime()) return yield* y.fail(new e({
117
+ if (e.occurredAt.getTime() > k().getTime()) return yield* C.fail(new x({
110
118
  source: "usageEvent",
111
119
  message: "Usage completion is ahead of this replica clock. Retry the same event after its completion time.",
112
120
  transient: !0
113
121
  }));
114
- let n = new Date(t.occurredAt);
115
- if ((yield* N.stores.customers.accountForTenant(t.tenantId)) === null) return yield* y.fail(s("Usage occurrence requires its already recorded original billing account."));
116
- yield* N.stores.usage.recordEvent({
117
- ...t,
118
- occurredAt: n,
119
- period: D(n)
122
+ let t = new Date(e.occurredAt);
123
+ if ((yield* P.stores.customers.accountForTenant(e.tenantId)) === null) return yield* C.fail(o("Usage occurrence requires its already recorded original billing account."));
124
+ yield* P.stores.usage.recordEvent({
125
+ ...e,
126
+ occurredAt: t,
127
+ period: j(t)
120
128
  });
121
- }), V = () => new e({
129
+ }), V = () => new x({
122
130
  source: "billing",
123
131
  message: "Usage arrived after final billing dispatch was sealed. Financial reconciliation is required before account deletion.",
124
132
  transient: !1
125
- }), H = (e) => N.stores.closures.getAccount(e).pipe(y.map((e) => e?.usageSealed === 1)), U = (t) => y.gen(function* () {
126
- if (!v.supportsMeteredUsage) return;
127
- let n = yield* N.stores.usage.pending();
128
- for (let r of n) {
129
- if (t !== void 0 && r.tenantId !== t) continue;
130
- let n = r.used - r.reportedToProvider;
131
- if (n <= 0) continue;
132
- if (r.period !== D(A())) {
133
- if (t !== void 0) return yield* y.fail(new e({
134
- source: "billing",
135
- message: "Historical usage requires original-period financial reconciliation before account deletion.",
136
- transient: !1
137
- }));
138
- yield* y.logWarning("historical billing usage retained for original-period reconciliation").pipe(y.annotateLogs({
139
- tenantId: r.tenantId,
140
- period: r.period
141
- }));
133
+ }), Se = (e) => P.stores.closures.getAccount(e).pipe(C.map((e) => e?.usageSealed === 1)), Ce = m({
134
+ provider: S,
135
+ now: k,
136
+ customerOf: (e) => z(e).pipe(C.map((e) => e?.providerCustomerId ?? null)),
137
+ liveSubscriptionOf: (e) => P.stores.subscriptions.getByTenant(e).pipe(C.map((e) => e !== null && f(e.status) ? e.providerSubscriptionId : null)),
138
+ sealed: Se
139
+ }), we = (e, t) => P.stores.usage.markReported(e.tenantId, e.entitlementKey, e.period, t), H = (e) => new x({
140
+ source: "billing",
141
+ message: e,
142
+ transient: !1
143
+ }), Te = (e, t, n, r) => M(C.gen(function* () {
144
+ if (yield* Se(e.tenantId)) return yield* C.fail(V());
145
+ yield* S.reportUsage({
146
+ tenantId: e.tenantId,
147
+ entitlementKey: e.entitlementKey,
148
+ quantity: r - n,
149
+ idempotencyKey: `${e.tenantId}:${e.entitlementKey}:${e.period}:${r}`,
150
+ ...t === void 0 ? {} : { providerCustomerId: t }
151
+ });
152
+ }), T).pipe(C.andThen(we(e, r))), Ee = (e, t, n, r) => P.stores.usage.claimDispatch(e.tenantId, e.entitlementKey, e.period, t, {
153
+ expected: n,
154
+ from: r,
155
+ through: e.used
156
+ }), De = (e, t, n) => C.gen(function* () {
157
+ if (t + 1 >= 8) return yield* C.fail(new x({
158
+ source: "billing",
159
+ message: "Usage flush lost its dispatch claim repeatedly to concurrent flushes. Retry the flush.",
160
+ transient: !0
161
+ }));
162
+ let r = (yield* P.stores.usage.pending()).find((t) => t.tenantId === e.tenantId && t.entitlementKey === e.entitlementKey && t.period === e.period);
163
+ r !== void 0 && (yield* n(r, t + 1));
164
+ }), Oe = (e, t, n = 0) => C.gen(function* () {
165
+ let r = e.reportedToProvider;
166
+ if (e.meterDispatchedThrough > r && (yield* Te(e, t, r, e.meterDispatchedThrough), r = e.meterDispatchedThrough), !(e.used <= r)) {
167
+ if (!(yield* Ee(e, "meter", e.meterDispatchedThrough, r))) return yield* De(e, n, (e, n) => Oe(e, t, n));
168
+ yield* Te(e, t, r, e.used);
169
+ }
170
+ }), ke = () => {
171
+ let e;
172
+ return C.gen(function* () {
173
+ if (e !== void 0) return e;
174
+ let t = S.fetchPriceMeters;
175
+ if (t === void 0 || S.fetchPriceVersions === void 0 || S.ensureInvoiceItem === void 0) return yield* C.fail(H(`Billing provider "${S.name}" cannot invoice historical usage.`));
176
+ let n = [...new Set(w.planIds().flatMap((e) => w.meteredPriceIdsFor(e)))];
177
+ return e = n.length === 0 ? [] : yield* M(t(n), T), e;
178
+ });
179
+ }, Ae = (e, t) => C.gen(function* () {
180
+ let n = [...new Set((yield* t).filter((t) => t.meterEventName === e.entitlementKey).map((e) => e.priceId))];
181
+ if (n.length === 1) return n[0];
182
+ if (n.length === 0) return yield* C.fail(H(`No configured metered price bills usage "${e.entitlementKey}"; list its price in a plan's meteredPriceIds.`));
183
+ let r = new Set((yield* P.stores.subscriptions.listByTenant(e.tenantId)).flatMap((e) => w.meteredPriceIdsFor(e.plan))), i = n.filter((e) => r.has(e));
184
+ return i.length === 1 ? i[0] : yield* C.fail(H(`Usage "${e.entitlementKey}" is billed by more than one configured metered price and the tenant's plan does not decide which.`));
185
+ }), je = (e, t, n = 0) => C.gen(function* () {
186
+ let r = /^([0-9]{4})-(0[1-9]|1[0-2])$/.exec(e.period);
187
+ if (r === null) return yield* C.fail(H(`Usage period "${e.period}" is not a calendar month.`));
188
+ let i = Number(r[1]), a = Number(r[2]), o = {
189
+ start: new Date(Date.UTC(i, a - 1, 1)),
190
+ end: new Date(Date.UTC(i, a, 1))
191
+ }, s = e.reportedToProvider;
192
+ e.meterDispatchedThrough > s && (s = e.meterDispatchedThrough, yield* we(e, s));
193
+ let c = (n, r) => C.gen(function* () {
194
+ let i = yield* Ae(e, t), a = yield* C.tryPromise({
195
+ try: async () => {
196
+ let t = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify([
197
+ e.tenantId,
198
+ e.entitlementKey,
199
+ e.period,
200
+ n,
201
+ r
202
+ ])));
203
+ return [...new Uint8Array(t)].map((e) => e.toString(16).padStart(2, "0")).join("");
204
+ },
205
+ catch: () => H("Usage interval identity could not be established.")
206
+ });
207
+ yield* M(Ce({
208
+ tenantId: e.tenantId,
209
+ priceId: i,
210
+ period: o,
211
+ fromUnits: n,
212
+ toUnits: r,
213
+ idempotencyKey: `voltro-usage:${a}`,
214
+ description: `${e.entitlementKey}, ${e.period}`
215
+ }), T), yield* we(e, r);
216
+ });
217
+ if (e.invoiceDispatchedThrough > s && (yield* c(s, e.invoiceDispatchedThrough), s = e.invoiceDispatchedThrough), !(e.used <= s)) {
218
+ if (!(yield* Ee(e, "invoice", e.invoiceDispatchedThrough, s))) return yield* De(e, n, (e, n) => je(e, t, n));
219
+ yield* c(s, e.used);
220
+ }
221
+ }), Me = (e) => C.gen(function* () {
222
+ if (!S.supportsMeteredUsage) return;
223
+ let t = yield* P.stores.usage.pending(), n = ke();
224
+ for (let r of t) {
225
+ if (e !== void 0 && r.tenantId !== e) continue;
226
+ let t = r.used - r.reportedToProvider;
227
+ if (t <= 0) continue;
228
+ if (yield* Se(r.tenantId)) {
229
+ if (e !== void 0) return yield* C.fail(V());
230
+ yield* C.logWarning("billing usage retained: final dispatch is sealed").pipe(C.annotateLogs({ tenantId: r.tenantId }));
142
231
  continue;
143
232
  }
144
- if (yield* H(r.tenantId)) {
145
- if (t !== void 0) return yield* y.fail(V());
146
- yield* y.logWarning("billing usage retained: final dispatch is sealed").pipe(y.annotateLogs({ tenantId: r.tenantId }));
233
+ if (r.period !== j(k())) {
234
+ if (e !== void 0) {
235
+ yield* je(r, n);
236
+ continue;
237
+ }
238
+ yield* je(r, n).pipe(C.catch((e) => C.logWarning("billing usage of a closed month retained").pipe(C.annotateLogs({
239
+ tenantId: r.tenantId,
240
+ key: r.entitlementKey,
241
+ period: r.period,
242
+ reason: e.message
243
+ }))));
147
244
  continue;
148
245
  }
149
- let i = yield* N.stores.customers.getByTenant(r.tenantId);
150
- if (i === null && v.usageRequiresCustomer === !0) {
151
- if (t !== void 0) return yield* y.fail(new e({
246
+ let i = yield* P.stores.customers.getByTenant(r.tenantId);
247
+ if (i === null && S.usageRequiresCustomer === !0) {
248
+ if (e !== void 0) return yield* C.fail(new x({
152
249
  source: "billing",
153
250
  message: "Final usage requires a confirmed provider customer before account closure.",
154
251
  transient: !0
155
252
  }));
156
- yield* y.logWarning("billing usage not flushed: no provider customer linked").pipe(y.annotateLogs({
253
+ yield* C.logWarning("billing usage not flushed: no provider customer linked").pipe(C.annotateLogs({
157
254
  tenantId: r.tenantId,
158
255
  key: r.entitlementKey,
159
- pending: n
256
+ pending: t
160
257
  }));
161
- } else yield* O(y.gen(function* () {
162
- if (yield* H(r.tenantId)) return yield* y.fail(V());
163
- yield* v.reportUsage({
164
- tenantId: r.tenantId,
165
- entitlementKey: r.entitlementKey,
166
- quantity: n,
167
- idempotencyKey: `${r.tenantId}:${r.entitlementKey}:${r.period}:${r.used}`,
168
- ...i === null ? {} : { providerCustomerId: i.providerCustomerId }
169
- });
170
- }), x), yield* N.stores.usage.markReported(r.tenantId, r.entitlementKey, r.period, r.used);
258
+ } else yield* Oe(r, i?.providerCustomerId);
171
259
  }
172
- }), fe = () => U(), W = (t) => y.fail(new e({
260
+ }), Ne = () => Me(), U = (e) => C.fail(new x({
173
261
  source: "billing",
174
- message: `tenant '${t}' already has a paying subscription — change its plan instead of checking out again`,
262
+ message: `tenant '${e}' already has a paying subscription — change its plan instead of checking out again`,
175
263
  transient: !1
176
- })), G = (e, t, n) => L(e).pipe(y.flatMap((r) => r ? t.status === "canceled" ? N.stores.subscriptions.markCanceled(t.providerSubscriptionId) : N.stores.subscriptions.upsert({
177
- tenantId: e,
178
- provider: v.name,
179
- providerSubscriptionId: t.providerSubscriptionId,
180
- plan: t.plan ?? "free",
181
- status: t.status,
182
- quantity: t.quantity,
183
- currentPeriodStart: t.currentPeriodStart,
184
- currentPeriodEnd: t.currentPeriodEnd,
185
- cancelAt: t.cancelAt,
186
- pastDueSince: null,
187
- statusEventAt: n
188
- }) : y.fail(s("A qualified billing account is required before subscription writes.")))), pe = (t) => y.gen(function* () {
189
- let { tenantId: n, plan: r, successUrl: i, cancelUrl: a } = t, o = t.quantity ?? 1, s = t.authorize ?? (() => y.void), c = b.priceIdFor(r), l = (t) => y.fail(new e({
264
+ })), W = (e, r, i) => C.gen(function* () {
265
+ if (!(yield* R(e))) return yield* C.fail(o("A qualified billing account is required before subscription writes."));
266
+ let a = P.stores, s = yield* L(), c = yield* C.try({
267
+ try: () => t({
268
+ tenantId: e,
269
+ provider: S.name,
270
+ account: s.account,
271
+ snapshot: r,
272
+ expectedPriceId: r.plan === null ? null : w.priceIdFor(r.plan),
273
+ expectedCurrency: w.currencyFor(r.plan ?? "free"),
274
+ observedAt: k()
275
+ }),
276
+ catch: () => o("The current provider subscription binding could not be captured.")
277
+ });
278
+ if (c !== null) {
279
+ let t = yield* a.customers.getByProviderCustomerId(c.providerCustomerId, s);
280
+ if (t === null || t.tenantId !== e || P.stores !== a) return yield* C.fail(o("The provider subscription has no matching native customer custody."));
281
+ }
282
+ if (r.status === "canceled" && r.plan === null) return yield* oe(C.gen(function* () {
283
+ let t = (yield* a.subscriptions.listByTenant(e)).filter((e) => e.provider === S.name && e.providerSubscriptionId === r.providerSubscriptionId);
284
+ if (t.length > 1) return yield* C.fail(o("The current subscription identity is ambiguous."));
285
+ t[0] !== void 0 && (yield* a.subscriptions.patchBySubscription(e, r.providerSubscriptionId, { status: "canceled" }, t[0].statusEventAt));
286
+ }));
287
+ if (yield* a.subscriptions.upsert({
288
+ tenantId: e,
289
+ provider: S.name,
290
+ providerSubscriptionId: r.providerSubscriptionId,
291
+ plan: r.plan ?? "free",
292
+ status: r.status,
293
+ quantity: r.quantity,
294
+ currentPeriodStart: r.currentPeriodStart,
295
+ currentPeriodEnd: r.currentPeriodEnd,
296
+ cancelAt: r.cancelAt,
297
+ pastDueSince: null,
298
+ statusEventAt: i,
299
+ providerObservation: c
300
+ }), c !== null) {
301
+ let t = (yield* a.subscriptions.listByTenant(e)).filter((e) => e.provider === S.name && e.providerSubscriptionId === r.providerSubscriptionId);
302
+ yield* C.try({
303
+ try: () => {
304
+ if (P.stores !== a || !n(t, c, i)) throw Error("unconfirmed");
305
+ },
306
+ catch: () => o("The provider subscription observation was not read back exactly.", !0)
307
+ });
308
+ }
309
+ }), Pe = (e) => C.gen(function* () {
310
+ let { tenantId: t, plan: n, successUrl: r, cancelUrl: i } = e, a = e.authorize ?? (() => C.void), o = w.priceIdFor(n), s = e.quantity ?? w.minimumSeatsFor(n), c = (e) => C.fail(new x({
190
311
  source: "billing",
191
- message: t,
312
+ message: e,
192
313
  transient: !1
193
314
  }));
194
- if (c === null) return yield* l("The selected plan has no provider checkout price.");
195
- if (!Number.isSafeInteger(o) || o < 1) return yield* l("Seat quantity must be a positive integer.");
196
- yield* j(n, "checkout"), yield* s(), yield* M(i, "successUrl"), yield* M(a, "cancelUrl");
197
- let u = yield* N.stores.subscriptions.getByTenant(n);
198
- if (u !== null && E.has(u.status)) return yield* W(n);
199
- let d = [...new Set(b.meteredPriceIdsFor(r))].sort(), f = S?.adjustableQuantity === void 0 ? void 0 : {
200
- min: S.adjustableQuantity.min,
201
- max: S.adjustableQuantity.max
202
- }, p = S?.trialDays, m = yield* y.tryPromise({
315
+ if (o === null) return yield* c("The selected plan has no provider checkout price.");
316
+ if (!Number.isSafeInteger(s) || s < 1) return yield* c("Seat quantity must be a positive integer.");
317
+ if (s < w.minimumSeatsFor(n)) return yield* c("The plan price already covers more seats than requested.");
318
+ yield* N(t, "checkout"), yield* a(), yield* de(r, "successUrl"), yield* de(i, "cancelUrl");
319
+ let l = yield* P.stores.subscriptions.getByTenant(t);
320
+ if (l !== null && ae.has(l.status)) return yield* U(t);
321
+ let u = [...new Set(w.meteredPriceIdsFor(n))].sort(), d = E?.adjustableQuantity === void 0 ? void 0 : {
322
+ min: E.adjustableQuantity.min,
323
+ max: E.adjustableQuantity.max
324
+ }, f = E?.trialDays, p = yield* C.tryPromise({
203
325
  try: async () => {
204
326
  let e = new TextEncoder().encode(JSON.stringify([
327
+ t,
328
+ S.name,
205
329
  n,
206
- v.name,
207
- r,
208
- c,
209
- d,
210
330
  o,
331
+ u,
332
+ s,
333
+ r,
211
334
  i,
212
- a,
213
- f ?? null,
214
- p ?? null
215
- ])), t = await globalThis.crypto.subtle.digest("SHA-256", e);
216
- return [...new Uint8Array(t)].map((e) => e.toString(16).padStart(2, "0")).join("");
335
+ d ?? null,
336
+ f ?? null
337
+ ])), a = await globalThis.crypto.subtle.digest("SHA-256", e);
338
+ return [...new Uint8Array(a)].map((e) => e.toString(16).padStart(2, "0")).join("");
217
339
  },
218
- catch: () => new e({
340
+ catch: () => new x({
219
341
  source: "billing",
220
342
  message: "Checkout request identity could not be established.",
221
343
  transient: !1
222
344
  })
223
345
  });
224
346
  for (let e = 0; e < 4; e++) {
225
- yield* j(n, "checkout"), yield* s(), yield* R(n);
226
- let e = new Date(A());
227
- if (!Number.isFinite(e.getTime())) return yield* l("The checkout clock could not be confirmed.");
228
- let t = yield* N.stores.checkouts.reserve({
229
- tenantId: n,
230
- provider: v.name,
231
- requestDigest: m,
232
- plan: r,
233
- quantity: o,
347
+ yield* N(t, "checkout"), yield* a(), yield* fe(t);
348
+ let e = new Date(k());
349
+ if (!Number.isFinite(e.getTime())) return yield* c("The checkout clock could not be confirmed.");
350
+ let l = yield* P.stores.checkouts.reserve({
351
+ tenantId: t,
352
+ provider: S.name,
353
+ requestDigest: p,
354
+ plan: n,
355
+ quantity: s,
234
356
  createdAt: e,
235
357
  expiresAt: /* @__PURE__ */ new Date(Math.floor((e.getTime() + 36e5) / 1e3) * 1e3)
236
358
  });
237
- if (t.provider !== v.name) return yield* l("The checkout provider changed. Its previous operation needs reconciliation.");
238
- let u = t.providerCustomerId, h = yield* z(n);
239
- if (h !== null && (h.provider !== v.name || u !== null && h.providerCustomerId !== u)) return yield* l("The checkout customer binding changed. Its operation needs reconciliation.");
240
- if (t.requestDigest === m && u === null) {
241
- yield* j(n, "checkout"), yield* s(), u = h?.providerCustomerId ?? (yield* O(s().pipe(y.andThen(j(n, "checkout")), y.andThen(v.ensureCustomer({ tenantId: n }))), x));
242
- let e = yield* N.stores.checkouts.patch(t.id, { providerCustomerId: u });
243
- if (e.active !== 1 || e.providerCustomerId !== u) return yield* l("Checkout ownership changed during customer resolution.");
244
- let r = yield* z(n);
245
- if (r !== null && (r.provider !== v.name || r.providerCustomerId !== u)) return yield* l("The current customer binding requires reconciliation.");
246
- yield* s(), r === null && (yield* B(n, u));
359
+ if (l.provider !== S.name) return yield* c("The checkout provider changed. Its previous operation needs reconciliation.");
360
+ let m = l.providerCustomerId, h = yield* z(t);
361
+ if (h !== null && (h.provider !== S.name || m !== null && h.providerCustomerId !== m)) return yield* c("The checkout customer binding changed. Its operation needs reconciliation.");
362
+ if (l.requestDigest === p && m === null) {
363
+ yield* N(t, "checkout"), yield* a(), m = h?.providerCustomerId ?? (yield* M(a().pipe(C.andThen(N(t, "checkout")), C.andThen(S.ensureCustomer({ tenantId: t }))), T));
364
+ let e = yield* P.stores.checkouts.patch(l.id, { providerCustomerId: m });
365
+ if (e.active !== 1 || e.providerCustomerId !== m) return yield* c("Checkout ownership changed during customer resolution.");
366
+ let n = yield* z(t);
367
+ if (n !== null && (n.provider !== S.name || n.providerCustomerId !== m)) return yield* c("The current customer binding requires reconciliation.");
368
+ yield* a(), n === null && (yield* B(t, m));
247
369
  }
248
- if (u !== null) {
249
- let e = yield* z(n);
250
- if (e === null) yield* B(n, u);
251
- else if (e.providerCustomerId !== u) return yield* l("Checkout customer custody differs from the retained operation.");
370
+ if (m !== null) {
371
+ let e = yield* z(t);
372
+ if (e === null) yield* B(t, m);
373
+ else if (e.providerCustomerId !== m) return yield* c("Checkout customer custody differs from the retained operation.");
252
374
  }
253
- let g = yield* O(v.findCheckoutSession({
254
- tenantId: n,
255
- operationId: t.id,
256
- ...u === null ? {} : { providerCustomerId: u }
257
- }), x), _ = g.receipt;
375
+ let g = yield* M(S.findCheckoutSession({
376
+ tenantId: t,
377
+ operationId: l.id,
378
+ ...m === null ? {} : { providerCustomerId: m }
379
+ }), T), _ = g.receipt;
258
380
  if (_ !== null) {
259
- if (_.operationId !== t.id || _.tenantId !== n || _.providerCustomerId === null || u !== null && _.providerCustomerId !== u || _.expiresAt.getTime() !== t.expiresAt.getTime() || _.id === "") return yield* l("The provider checkout receipt does not match its retained operation.");
260
- if (u === null && (u = _.providerCustomerId, yield* N.stores.checkouts.patch(t.id, { providerCustomerId: u })), _.status === "expired") {
261
- yield* N.stores.checkouts.patch(t.id, {
381
+ if (_.operationId !== l.id || _.tenantId !== t || _.providerCustomerId === null || m !== null && _.providerCustomerId !== m || _.expiresAt.getTime() !== l.expiresAt.getTime() || _.id === "") return yield* c("The provider checkout receipt does not match its retained operation.");
382
+ if (m === null && (m = _.providerCustomerId, yield* P.stores.checkouts.patch(l.id, { providerCustomerId: m })), _.status === "expired") {
383
+ yield* P.stores.checkouts.patch(l.id, {
262
384
  phase: "expired",
263
385
  providerSessionId: _.id
264
386
  });
265
387
  continue;
266
388
  }
267
389
  if (_.status === "complete") {
268
- if (yield* N.stores.checkouts.patch(t.id, {
390
+ if (yield* P.stores.checkouts.patch(l.id, {
269
391
  phase: "completed",
270
392
  providerSessionId: _.id
271
- }), _.providerSubscriptionId === null) return yield* l("Completed checkout settlement is not yet confirmed.");
272
- if ((yield* O(v.fetchSubscription(_.providerSubscriptionId), x))?.status === "canceled") {
273
- yield* N.stores.checkouts.patch(t.id, { phase: "retired" });
393
+ }), _.providerSubscriptionId === null) return yield* c("Completed checkout settlement is not yet confirmed.");
394
+ if ((yield* M(S.fetchSubscription(_.providerSubscriptionId), T))?.status === "canceled") {
395
+ yield* P.stores.checkouts.patch(l.id, { phase: "retired" });
274
396
  continue;
275
397
  }
276
- return yield* W(n);
398
+ return yield* U(t);
277
399
  }
278
- let e = yield* N.stores.checkouts.patch(t.id, {
400
+ let e = yield* P.stores.checkouts.patch(l.id, {
279
401
  phase: "ready",
280
402
  providerSessionId: _.id
281
403
  });
282
- return t.requestDigest === m ? _.url === null || g.observedAt !== null && g.observedAt.getTime() >= _.expiresAt.getTime() ? yield* l("The current checkout URL could not be confirmed.") : e.active !== 1 || e.phase !== "ready" ? yield* l("Checkout state changed before its URL could be returned.") : (yield* j(n, "checkout", u ?? void 0), { url: _.url }) : yield* l("Another checkout is still open for this organization.");
404
+ return l.requestDigest === p ? _.url === null || g.observedAt !== null && g.observedAt.getTime() >= _.expiresAt.getTime() ? yield* c("The current checkout URL could not be confirmed.") : e.active !== 1 || e.phase !== "ready" ? yield* c("Checkout state changed before its URL could be returned.") : (yield* N(t, "checkout", m ?? void 0), { url: _.url }) : yield* c("Another checkout is still open for this organization.");
283
405
  }
284
- if (g.observedAt !== null && g.observedAt.getTime() > t.expiresAt.getTime()) {
285
- yield* N.stores.checkouts.patch(t.id, { phase: "expired" });
406
+ if (g.observedAt !== null && g.observedAt.getTime() > l.expiresAt.getTime()) {
407
+ yield* P.stores.checkouts.patch(l.id, { phase: "expired" });
286
408
  continue;
287
409
  }
288
- if (t.requestDigest !== m) return yield* l("An earlier checkout request is unresolved. Check its current state first.");
289
- if (u === null || A().getTime() >= t.expiresAt.getTime()) return yield* l("The earlier checkout needs provider deadline/receipt reconciliation.");
290
- let b = (yield* O(v.listSubscriptions({ providerCustomerId: u }), x)).filter((e) => E.has(e.status));
291
- if (b.length > 0) {
292
- for (let e of b) yield* G(n, e, A());
293
- return yield* W(n);
410
+ if (l.requestDigest !== p) return yield* c("An earlier checkout request is unresolved. Check its current state first.");
411
+ if (m === null || k().getTime() >= l.expiresAt.getTime()) return yield* c("The earlier checkout needs provider deadline/receipt reconciliation.");
412
+ let v = (yield* M(S.listSubscriptions({ providerCustomerId: m }), T)).filter((e) => ae.has(e.status));
413
+ if (v.length > 0) {
414
+ for (let e of v) yield* W(t, e, k());
415
+ return yield* U(t);
294
416
  }
295
- let S = yield* N.stores.checkouts.patch(t.id, { phase: "creating" });
296
- if (S.active !== 1 || S.phase === "completed") return yield* l("Checkout state changed before provider dispatch.");
297
- yield* j(n, "checkout", u ?? void 0), yield* s(), yield* O(s().pipe(y.andThen(j(n, "checkout", u ?? void 0)), y.andThen(v.expireOpenCheckouts({
298
- providerCustomerId: u,
299
- exceptOperationId: t.id
300
- }))), x), yield* j(n, "checkout", u ?? void 0), yield* s();
301
- let C = yield* O(s().pipe(y.andThen(j(n, "checkout", u ?? void 0)), y.andThen(v.createCheckoutSession({
302
- tenantId: n,
303
- priceId: c,
304
- meteredPriceIds: d,
305
- successUrl: i,
306
- cancelUrl: a,
307
- quantity: o,
308
- providerCustomerId: u,
309
- idempotencyKey: t.id,
310
- expiresAt: t.expiresAt,
311
- ...f === void 0 ? {} : { adjustableQuantity: f },
312
- ...p === void 0 ? {} : { trialDays: p }
313
- }))), x);
314
- if (C.operationId !== t.id || C.tenantId !== n || C.providerCustomerId !== u || C.expiresAt.getTime() !== t.expiresAt.getTime() || !C.id) return yield* l("Checkout creation returned an inconsistent provider receipt.");
315
- if (C.status === "expired") {
316
- yield* N.stores.checkouts.patch(t.id, {
417
+ let y = yield* P.stores.checkouts.patch(l.id, { phase: "creating" });
418
+ if (y.active !== 1 || y.phase === "completed") return yield* c("Checkout state changed before provider dispatch.");
419
+ yield* N(t, "checkout", m ?? void 0), yield* a(), yield* M(a().pipe(C.andThen(N(t, "checkout", m ?? void 0)), C.andThen(S.expireOpenCheckouts({
420
+ providerCustomerId: m,
421
+ exceptOperationId: l.id
422
+ }))), T), yield* N(t, "checkout", m ?? void 0), yield* a();
423
+ let b = yield* M(a().pipe(C.andThen(N(t, "checkout", m ?? void 0)), C.andThen(S.createCheckoutSession({
424
+ tenantId: t,
425
+ priceId: o,
426
+ meteredPriceIds: u,
427
+ successUrl: r,
428
+ cancelUrl: i,
429
+ quantity: s,
430
+ providerCustomerId: m,
431
+ idempotencyKey: l.id,
432
+ expiresAt: l.expiresAt,
433
+ ...d === void 0 ? {} : { adjustableQuantity: d },
434
+ ...f === void 0 ? {} : { trialDays: f }
435
+ }))), T);
436
+ if (b.operationId !== l.id || b.tenantId !== t || b.providerCustomerId !== m || b.expiresAt.getTime() !== l.expiresAt.getTime() || !b.id) return yield* c("Checkout creation returned an inconsistent provider receipt.");
437
+ if (b.status === "expired") {
438
+ yield* P.stores.checkouts.patch(l.id, {
317
439
  phase: "expired",
318
- providerSessionId: C.id
440
+ providerSessionId: b.id
319
441
  });
320
442
  continue;
321
443
  }
322
- if (C.status === "complete") return yield* N.stores.checkouts.patch(t.id, {
444
+ if (b.status === "complete") return yield* P.stores.checkouts.patch(l.id, {
323
445
  phase: "completed",
324
- providerSessionId: C.id
325
- }), yield* W(n);
326
- if (C.url === null) return yield* l("Checkout creation returned no confirmed URL.");
327
- let w = yield* N.stores.checkouts.patch(t.id, {
446
+ providerSessionId: b.id
447
+ }), yield* U(t);
448
+ if (b.url === null) return yield* c("Checkout creation returned no confirmed URL.");
449
+ let ee = yield* P.stores.checkouts.patch(l.id, {
328
450
  phase: "ready",
329
- providerSessionId: C.id
451
+ providerSessionId: b.id
330
452
  });
331
- return w.active !== 1 || w.phase !== "ready" ? yield* l("Checkout state changed before its URL could be returned.") : (yield* j(n, "checkout", u ?? void 0), { url: C.url });
453
+ return ee.active !== 1 || ee.phase !== "ready" ? yield* c("Checkout state changed before its URL could be returned.") : (yield* N(t, "checkout", m ?? void 0), { url: b.url });
332
454
  }
333
- return yield* l("Checkout operations changed concurrently. Check current billing state before retrying.");
334
- }), me = (t, n) => y.gen(function* () {
335
- yield* j(t, "portal"), yield* M(n, "returnUrl");
336
- let r = yield* z(t);
337
- return r === null ? yield* y.fail(new e({
455
+ return yield* c("Checkout operations changed concurrently. Check current billing state before retrying.");
456
+ }), Fe = (e, t) => C.gen(function* () {
457
+ yield* N(e, "portal"), yield* de(t, "returnUrl");
458
+ let n = yield* z(e);
459
+ return n === null ? yield* C.fail(new x({
338
460
  source: "billing",
339
- message: `no provider customer linked for tenant '${t}'`,
461
+ message: `no provider customer linked for tenant '${e}'`,
340
462
  transient: !1
341
- })) : yield* O(v.createPortalSession({
342
- tenantId: t,
343
- providerCustomerId: r.providerCustomerId,
344
- returnUrl: n
345
- }), x);
346
- }), he = (e) => y.gen(function* () {
347
- if (P.resolveRecipient !== void 0) {
348
- let t = yield* P.resolveRecipient(e);
463
+ })) : yield* M(S.createPortalSession({
464
+ tenantId: e,
465
+ providerCustomerId: n.providerCustomerId,
466
+ returnUrl: t
467
+ }), T);
468
+ }), Ie = (e) => C.gen(function* () {
469
+ if (F.resolveRecipient !== void 0) {
470
+ let t = yield* F.resolveRecipient(e);
349
471
  if (t !== null) return t;
350
472
  }
351
- if (v.customerEmail === void 0) return null;
473
+ if (S.customerEmail === void 0) return null;
352
474
  let t = yield* z(e);
353
- return t === null ? null : yield* v.customerEmail(t.providerCustomerId);
354
- }), ge = (e) => {
355
- let t = P.portalReturnUrl;
356
- return t === void 0 ? y.succeed(null) : me(e, t).pipe(y.map((e) => e.url), y.catch(() => y.succeed(null)));
357
- }, _e = (e, t, n, r, i) => y.gen(function* () {
358
- let a = yield* he(e.tenantId).pipe(y.catch(() => y.succeed(null))), o = yield* ge(e.tenantId), s = t.lockedSince !== null, c = f({
475
+ return t === null ? null : yield* S.customerEmail(t.providerCustomerId);
476
+ }), Le = (e) => {
477
+ let t = F.portalReturnUrl;
478
+ return t === void 0 ? C.succeed(null) : C.try({
479
+ try: () => typeof t == "string" ? t : t(e),
480
+ catch: (e) => new x({
481
+ source: "dunning",
482
+ message: String(e?.message ?? e),
483
+ transient: !1
484
+ })
485
+ }).pipe(C.flatMap((t) => Fe(e, t)), C.map((e) => e.url), C.catch(() => C.succeed(null)));
486
+ }, Re = (e, t, n, r, i) => C.gen(function* () {
487
+ let a = yield* Ie(e.tenantId).pipe(C.catch(() => C.succeed(null))), o = yield* Le(e.tenantId), s = t.lockedSince !== null, c = g({
359
488
  stepId: n,
360
489
  locked: s,
361
490
  graceEndsAt: i,
@@ -369,81 +498,88 @@ var C = S({ scope: "@voltro/plugin-billing" }), w = 3, T = /* @__PURE__ */ new S
369
498
  pastDueSince: r,
370
499
  graceEndsAt: i,
371
500
  locked: s,
372
- lockout: P.lockout,
501
+ lockout: F.lockout,
373
502
  portalUrl: o,
374
503
  ...c
375
504
  };
376
- C.info("billing dunning notice", {
505
+ D.info("billing dunning notice", {
377
506
  tenant: e.tenantId,
378
507
  step: n,
379
508
  locked: s,
380
509
  graceEndsAt: i.toISOString(),
381
- delivered: P.notify !== void 0 && a !== null
510
+ delivered: F.notify !== void 0 && a !== null
382
511
  });
383
- let u = P.notify;
384
- u !== void 0 && (yield* u(l).pipe(y.catchCause((t) => y.sync(() => {
385
- C.warn("billing dunning notify failed", {
512
+ let u = F.notify;
513
+ u !== void 0 && (yield* u(l).pipe(C.catchCause((t) => C.sync(() => {
514
+ D.warn("billing dunning notify failed", {
386
515
  tenant: e.tenantId,
387
516
  step: n,
388
517
  cause: String(t)
389
518
  });
390
519
  }))));
391
- }), K = (e) => y.gen(function* () {
392
- yield* L(e);
393
- let t = yield* N.stores.subscriptions.getByTenant(e);
394
- if (t === null) return h(null, P, A(), e);
395
- let n = yield* v.fetchSubscription(t.providerSubscriptionId).pipe(y.catch((t) => y.sync(() => (C.warn("billing dunning reconcile: provider unreachable, not escalating", {
520
+ }), ze = (e, t) => C.gen(function* () {
521
+ let n = yield* t.subscriptions.getByTenant(e);
522
+ if (n === null) return null;
523
+ let r = yield* S.fetchSubscription(n.providerSubscriptionId).pipe(C.catch((t) => C.sync(() => (D.warn("billing dunning reconcile: provider unreachable, not escalating", {
396
524
  tenant: e,
397
525
  source: t.source,
398
526
  message: t.message
399
- }), null)))), r = t;
400
- if (n !== null) {
401
- let i = A(), a = n.status === "pastDue" ? t.status === "pastDue" && t.pastDueSince !== null ? t.pastDueSince : i : null;
402
- yield* N.stores.subscriptions.patchByTenant(e, {
403
- status: n.status,
404
- ...n.plan === null ? {} : { plan: n.plan },
405
- quantity: n.quantity,
406
- currentPeriodStart: n.currentPeriodStart,
407
- currentPeriodEnd: n.currentPeriodEnd,
408
- pastDueSince: a,
409
- statusEventAt: i
410
- }), r = {
411
- ...t,
412
- status: n.status,
413
- plan: n.plan ?? t.plan,
414
- quantity: n.quantity,
415
- currentPeriodStart: n.currentPeriodStart,
416
- currentPeriodEnd: n.currentPeriodEnd,
417
- pastDueSince: a,
418
- statusEventAt: i
527
+ }), null))));
528
+ if (P.stores !== t) return yield* C.fail(o("Billing storage changed during observation.", !0));
529
+ let i = n;
530
+ if (r !== null) {
531
+ let a = k(), o = r.status === "pastDue" ? n.status === "pastDue" && n.pastDueSince !== null ? n.pastDueSince : a : null;
532
+ yield* t.subscriptions.patchBySubscription(e, n.providerSubscriptionId, {
533
+ status: r.status,
534
+ ...r.plan === null ? {} : { plan: r.plan },
535
+ quantity: r.quantity,
536
+ currentPeriodStart: r.currentPeriodStart,
537
+ currentPeriodEnd: r.currentPeriodEnd,
538
+ pastDueSince: o,
539
+ statusEventAt: a
540
+ }, n.statusEventAt), i = {
541
+ ...n,
542
+ status: r.status,
543
+ plan: r.plan ?? n.plan,
544
+ quantity: r.quantity,
545
+ currentPeriodStart: r.currentPeriodStart,
546
+ currentPeriodEnd: r.currentPeriodEnd,
547
+ pastDueSince: o,
548
+ statusEventAt: a
419
549
  };
420
550
  }
421
- let i = h(r, P, A(), e);
422
- if (!P.enabled || r.status !== "pastDue" || r.pastDueSince === null) return i;
423
- let a = r.pastDueSince, o = m(a), s = i.graceEndsAt ?? a, c = p(P.steps, a, A()).map((e) => e.id);
424
- i.lockedSince !== null && c.push(d);
425
- for (let t of c) (yield* N.stores.dunningNotices.claim(e, o, t, A())) && (yield* _e(r, i, t, a, s));
426
551
  return i;
427
- }), ve = () => y.gen(function* () {
428
- let e = yield* N.stores.subscriptions.listByStatus("pastDue"), t = 0;
429
- for (let n of e) yield* K(n.tenantId).pipe(y.catch((e) => y.sync(() => {
430
- C.warn("billing dunning sweep: tenant failed", {
552
+ }), G = (e) => C.gen(function* () {
553
+ let t = P.stores;
554
+ if (yield* R(e), P.stores !== t) return yield* C.fail(o("Billing storage changed during observation.", !0));
555
+ let n = yield* oe(ze(e, t));
556
+ if (n === null) return y(null, F, k(), e);
557
+ let r = y(n, F, k(), e);
558
+ if (!F.enabled || n.status !== "pastDue" || n.pastDueSince === null) return r;
559
+ let i = n.pastDueSince, a = v(i), s = r.graceEndsAt ?? i, c = _(F.steps, i, k()).map((e) => e.id);
560
+ r.lockedSince !== null && c.push(h);
561
+ for (let t of c) (yield* P.stores.dunningNotices.claim(e, a, t, k())) && (yield* Re(n, r, t, i, s));
562
+ return r;
563
+ }), Be = () => C.gen(function* () {
564
+ let e = yield* P.stores.subscriptions.listByStatus("pastDue"), t = 0;
565
+ for (let n of e) yield* G(n.tenantId).pipe(C.catch((e) => C.sync(() => {
566
+ D.warn("billing dunning sweep: tenant failed", {
431
567
  tenant: n.tenantId,
432
568
  message: e.message
433
569
  });
434
570
  }))), t += 1;
435
571
  return t;
436
- }), q = (e) => {
437
- if (!P.enabled) return y.void;
438
- if (e._tag === "invoicePaymentFailed") return K(e.tenantId).pipe(y.asVoid);
439
- if (e._tag !== "invoicePaid" && e._tag !== "subscriptionUpserted") return y.void;
572
+ }), K = (e) => {
573
+ if (!F.enabled) return C.void;
574
+ if (e._tag === "invoicePaymentFailed") return G(e.tenantId).pipe(C.asVoid);
575
+ if (e._tag !== "invoicePaid" && e._tag !== "subscriptionUpserted") return C.void;
440
576
  let t = e.tenantId;
441
- return N.stores.subscriptions.getByTenant(t).pipe(y.flatMap((e) => e !== null && (e.status === "pastDue" || e.pastDueSince !== null) ? K(t).pipe(y.asVoid) : y.void));
442
- }, ye = (e) => {
577
+ return P.stores.subscriptions.getByTenant(t).pipe(C.flatMap((e) => e !== null && (e.status === "pastDue" || e.pastDueSince !== null) ? G(t).pipe(C.asVoid) : C.void));
578
+ }, Ve = (e) => {
443
579
  switch (e._tag) {
444
- case "subscriptionUpserted": return N.stores.subscriptions.upsert({
580
+ case "subscriptionUpserted": return P.stores.subscriptions.upsert({
445
581
  tenantId: e.tenantId,
446
- provider: v.name,
582
+ provider: S.name,
447
583
  providerSubscriptionId: e.providerSubscriptionId,
448
584
  plan: e.plan,
449
585
  status: e.status,
@@ -454,35 +590,60 @@ var C = S({ scope: "@voltro/plugin-billing" }), w = 3, T = /* @__PURE__ */ new S
454
590
  pastDueSince: null,
455
591
  statusEventAt: e.occurredAt
456
592
  });
457
- case "subscriptionCanceled": return N.stores.subscriptions.markCanceled(e.providerSubscriptionId);
458
- case "customerLinked": return B(e.tenantId, e.providerCustomerId).pipe(y.asVoid);
593
+ case "subscriptionCanceled": return P.stores.subscriptions.markCanceled(e.providerSubscriptionId);
594
+ case "customerLinked": return B(e.tenantId, e.providerCustomerId).pipe(C.asVoid);
459
595
  }
460
- }, be = (e) => {
461
- if (e._tag === "customerUnlinked") return y.gen(function* () {
462
- let t = yield* I(), n = v.fetchCustomerSnapshot?.bind(v);
463
- if (n === void 0) return yield* y.fail(s("Positive customer deletion evidence is required."));
596
+ }, He = (e) => C.gen(function* () {
597
+ let t = yield* C.try({
598
+ try: () => {
599
+ let t = s(e);
600
+ if (![e.providerCustomerId, e.providerEventId].every((e) => typeof e == "string" && e.length > 0 && e.length <= 191 && e.trim() === e && e.isWellFormed())) throw o("Exact verified customer and correction identities are required.");
601
+ return Object.freeze({
602
+ ...t,
603
+ providerCustomerId: e.providerCustomerId,
604
+ providerEventId: e.providerEventId
605
+ });
606
+ },
607
+ catch: () => o("The verified payment correction identity is invalid.")
608
+ }), n = P.stores, r = yield* L();
609
+ if (!c(t, r.account)) return yield* C.fail(o("The correction belongs to another provider account or mode."));
610
+ let i = yield* n.customers.getByProviderCustomerId(t.providerCustomerId, r);
611
+ if (i === null || i.provider !== S.name) return yield* C.fail(o("Retained native customer custody is required before payment correction."));
612
+ if (P.stores !== n) return yield* C.fail(o("Billing stores changed before payment correction.", !0));
613
+ yield* n.invoices.invalidatePayments({
614
+ tenantId: i.tenantId,
615
+ provider: r.provider,
616
+ ...r.account,
617
+ providerCustomerId: i.providerCustomerId
618
+ }, t.providerEventId);
619
+ let a = yield* st(i), l = yield* n.customers.getByProviderCustomerId(t.providerCustomerId, r), u = yield* L();
620
+ return P.stores !== n || !c(u.account, t) || l === null || l.id !== i.id || l.tenantId !== i.tenantId ? yield* C.fail(o("Native customer or provider custody changed during payment correction.", !0)) : a;
621
+ }), Ue = (e) => {
622
+ if (e._tag === "customerUnlinked") return C.gen(function* () {
623
+ let t = yield* L(), n = S.fetchCustomerSnapshot?.bind(S);
624
+ if (n === void 0) return yield* C.fail(o("Positive customer deletion evidence is required."));
464
625
  let r = yield* n({
465
626
  account: t.account,
466
627
  providerCustomerId: e.providerCustomerId
467
- }), i = yield* N.stores.customers.retire(t, r);
628
+ }), i = yield* P.stores.customers.retire(t, r);
468
629
  return {
469
630
  ...e,
470
631
  tenantId: i?.tenantId ?? null
471
632
  };
472
633
  });
473
- if (e._tag !== "invoicePaid" && e._tag !== "invoicePaymentFailed") return (e._tag === "customerLinked" ? y.void : z(e.tenantId).pipe(y.flatMap((e) => e === null ? y.fail(s("A qualified current customer is required before subscription events.")) : y.void))).pipe(y.andThen(ye(e)), y.andThen(q(e)), y.as(e));
634
+ if (e._tag !== "invoicePaid" && e._tag !== "invoicePaymentFailed") return (e._tag === "customerLinked" ? C.void : z(e.tenantId).pipe(C.flatMap((e) => e === null ? C.fail(o("A qualified current customer is required before subscription events.")) : C.void))).pipe(C.andThen(Ve(e)), C.andThen(K(e)), C.as(e));
474
635
  let t = {
475
636
  ...e,
476
637
  occurredAt: e.occurredAt === null ? null : new Date(e.occurredAt)
477
638
  };
478
- return y.gen(function* () {
639
+ return C.gen(function* () {
479
640
  let e = t.providerCustomerId;
480
- if (typeof e != "string" || e.length === 0 || e.trim() !== e) return yield* y.fail(s("An exact provider customer identity is required."));
481
- let n = yield* N.stores.customers.getByProviderCustomerId(e, yield* I());
482
- if (n === null) return yield* y.fail(s("The invoice customer must be linked before reconciliation.", !0));
483
- if (n.provider !== v.name) return yield* y.fail(s("The invoice customer belongs to a different provider."));
641
+ if (typeof e != "string" || e.length === 0 || e.trim() !== e) return yield* C.fail(o("An exact provider customer identity is required."));
642
+ let n = yield* P.stores.customers.getByProviderCustomerId(e, yield* L());
643
+ if (n === null) return yield* C.fail(o("The invoice customer must be linked before reconciliation.", !0));
644
+ if (n.provider !== S.name) return yield* C.fail(o("The invoice customer belongs to a different provider."));
484
645
  let r = n.tenantId;
485
- yield* J(r, t.providerInvoiceId, e);
646
+ yield* Y(r, t.providerInvoiceId, e);
486
647
  let i = {
487
648
  _tag: t._tag,
488
649
  tenantId: r,
@@ -490,371 +651,625 @@ var C = S({ scope: "@voltro/plugin-billing" }), w = 3, T = /* @__PURE__ */ new S
490
651
  amountMinor: t.amountMinor,
491
652
  currency: t.currency,
492
653
  occurredAt: t.occurredAt
493
- }, a = yield* N.stores.customers.getByTenant(r);
494
- return n.retiredAt === null && a?.id === n.id && (yield* q(i)), i;
654
+ }, a = yield* P.stores.customers.getByTenant(r);
655
+ return n.retiredAt === null && a?.id === n.id && (yield* K(i)), i;
495
656
  });
496
- }, xe = (t, n) => y.gen(function* () {
497
- yield* j(t, "change"), yield* Z(t);
498
- let r = yield* N.stores.subscriptions.getByTenant(t);
499
- if (r === null) return yield* y.fail(new e({
657
+ }, q = (n, r, i) => C.gen(function* () {
658
+ let a = P.stores;
659
+ if (S.supportsNativeSubscriptionWrites !== !0) return yield* C.fail(new x({
500
660
  source: "billing",
501
- message: `no subscription for tenant '${t}' to change`,
661
+ message: "This provider does not support native single-dispatch subscription operations.",
502
662
  transient: !1
503
663
  }));
504
- let i = n.plan ?? r.plan, a = n.quantity ?? r.quantity;
505
- if (n.plan !== void 0 && !b.has(i)) return yield* y.fail(new e({
664
+ let o = null;
665
+ yield* i(), yield* N(n, r);
666
+ let s = yield* a.subscriptions.getByTenant(n), l = yield* z(n), u = S.fetchSubscriptionSnapshot?.bind(S), d = () => new x({
506
667
  source: "billing",
507
- message: `unknown plan '${i}' — not in the plan registry`,
668
+ message: "The current owned subscription must be reconciled before this change can be confirmed.",
669
+ transient: !0
670
+ });
671
+ if (s === null || l === null || u === void 0 || s.tenantId !== n || s.provider !== S.name || l.provider !== S.name) return yield* C.fail(d());
672
+ let f = () => C.gen(function* () {
673
+ if (yield* i(), P.stores !== a || (yield* a.closures.getAccount(n)) !== null) return yield* C.fail(d());
674
+ yield* N(n, r, l.providerCustomerId);
675
+ let e = yield* a.customers.getByTenant(n), t = yield* a.subscriptions.getByTenant(n);
676
+ if (P.stores !== a || e === null || e.id !== l.id || e.provider !== l.provider || e.providerCustomerId !== l.providerCustomerId || !c(e.account, l.account) || t === null || t.provider !== s.provider || t.providerSubscriptionId !== s.providerSubscriptionId) return yield* C.fail(d());
677
+ yield* i();
678
+ }), p = (e, t) => e === null || t === null ? e === t : e instanceof Date && t instanceof Date && Number.isFinite(e.getTime()) && Number.isFinite(t.getTime()) && e.getTime() === t.getTime(), m = () => C.gen(function* () {
679
+ yield* f();
680
+ let r = yield* X(s.providerSubscriptionId, l), i = yield* C.try({
681
+ try: () => {
682
+ let e = (e) => e === null || e instanceof Date && Number.isFinite(e.getTime()), i = r?.plan == null ? null : w.priceIdFor(r.plan);
683
+ if (r === null || r.providerSubscriptionId !== s.providerSubscriptionId || r.providerCustomerId !== l.providerCustomerId || r.tenantId !== null && r.tenantId !== n || r.plan === null || !w.has(r.plan) || !Number.isSafeInteger(r.quantity) || r.quantity < 1 || !Array.isArray(r.priceIds) || r.priceIds.some((e) => typeof e != "string" || e.length === 0) || i !== null && !r.priceIds.includes(i) || ![
684
+ "active",
685
+ "trialing",
686
+ "pastDue",
687
+ "incomplete",
688
+ "canceled"
689
+ ].includes(r.status) || !e(r.currentPeriodStart) || !e(r.currentPeriodEnd) || !e(r.cancelAt) || r.currentPeriodStart !== null && r.currentPeriodEnd !== null && r.currentPeriodStart.getTime() > r.currentPeriodEnd.getTime()) throw d();
690
+ let a = k();
691
+ if (!(a instanceof Date) || !Number.isFinite(a.getTime())) throw d();
692
+ return o = {
693
+ ...r,
694
+ priceIds: [...r.priceIds],
695
+ providerObservedAt: r.providerObservedAt instanceof Date ? new Date(r.providerObservedAt.getTime()) : null
696
+ }, {
697
+ tenantId: n,
698
+ provider: S.name,
699
+ providerSubscriptionId: s.providerSubscriptionId,
700
+ plan: r.plan,
701
+ status: r.status,
702
+ quantity: r.quantity,
703
+ currentPeriodStart: r.currentPeriodStart === null ? null : new Date(r.currentPeriodStart.getTime()),
704
+ currentPeriodEnd: r.currentPeriodEnd === null ? null : new Date(r.currentPeriodEnd.getTime()),
705
+ cancelAt: r.cancelAt === null ? null : new Date(r.cancelAt.getTime()),
706
+ providerObservation: t({
707
+ tenantId: n,
708
+ provider: S.name,
709
+ account: l.account,
710
+ snapshot: r,
711
+ expectedPriceId: i,
712
+ expectedCurrency: w.currencyFor(r.plan),
713
+ observedAt: a
714
+ }),
715
+ pastDueSince: s.pastDueSince,
716
+ statusEventAt: new Date(a.getTime())
717
+ };
718
+ },
719
+ catch: d
720
+ });
721
+ yield* f();
722
+ let c = yield* a.subscriptions.getByTenant(n);
723
+ yield* a.subscriptions.upsert(i);
724
+ let u = i.status === "pastDue" ? c?.status === "pastDue" && c.pastDueSince !== null ? c.pastDueSince : i.statusEventAt : null;
725
+ yield* a.subscriptions.patchBySubscription(n, i.providerSubscriptionId, { pastDueSince: u }, i.statusEventAt);
726
+ let m = yield* a.subscriptions.getByTenant(n);
727
+ return m === null || m.providerSubscriptionId !== i.providerSubscriptionId || m.plan !== i.plan || m.status !== i.status || m.quantity !== i.quantity || !p(m.currentPeriodStart, i.currentPeriodStart) || !p(m.currentPeriodEnd, i.currentPeriodEnd) || !p(m.cancelAt, i.cancelAt) ? yield* C.fail(d()) : (yield* f(), yield* C.try({
728
+ try: () => {
729
+ if (JSON.stringify(e(m.providerObservation, m)) !== JSON.stringify(e(i.providerObservation, i))) throw d();
730
+ },
731
+ catch: d
732
+ }), yield* Z([Q(n, i, i.statusEventAt ?? k())]), yield* f(), m);
733
+ }), h = () => oe(m());
734
+ return {
735
+ sub: yield* h(),
736
+ customer: l,
737
+ stores: a,
738
+ check: f,
739
+ observe: h,
740
+ sameDate: p,
741
+ refuse: d,
742
+ getObservation: () => o
743
+ };
744
+ }), We = (e, t, n) => C.gen(function* () {
745
+ if (yield* e.check(), n.providerSubscriptionId !== e.sub.providerSubscriptionId || n.providerCustomerId !== e.customer.providerCustomerId || n.tenantId !== null && n.tenantId !== e.sub.tenantId || n.writeOperationId !== t || !(n.providerObservedAt instanceof Date) || !Number.isFinite(n.providerObservedAt.getTime())) return yield* C.fail(e.refuse());
746
+ yield* e.stores.subscriptionWrites.acknowledge(t, n.providerObservedAt);
747
+ }), Ge = (e, t, n, i) => C.gen(function* () {
748
+ if (t === void 0 || !/^[A-Za-z0-9_-]{8,128}$/.test(t)) return yield* C.fail(new x({
749
+ source: "billing",
750
+ message: "A durable requestId is required. Keep it unchanged when checking or retrying this operation.",
751
+ transient: !1
752
+ }));
753
+ let a = e.getObservation(), o = {
754
+ ...n,
755
+ provider: S.name,
756
+ providerAccountId: e.customer.account.providerAccountId,
757
+ livemode: e.customer.account.livemode,
758
+ customerId: e.customer.providerCustomerId,
759
+ subscriptionId: e.sub.providerSubscriptionId,
760
+ itemId: n.kind === "cancel" ? null : a?.providerPlanItemId ?? null,
761
+ expectedPriceId: n.kind === "cancel" ? null : w.priceIdFor(e.sub.plan)
762
+ };
763
+ if (n.kind !== "cancel" && (o.itemId === null || o.expectedPriceId === null)) return yield* C.fail(e.refuse());
764
+ let s = e.stores.subscriptionWrites, c = yield* s.reserve(e.sub.tenantId, t, o), l = null;
765
+ if (c.phase === "prepared" || c.phase === "claimed") {
766
+ if (!f(e.sub.status)) return yield* C.fail(e.refuse());
767
+ yield* e.check();
768
+ let t = globalThis.crypto.randomUUID();
769
+ if (c = yield* s.claim(c.id, t), c.phase === "claimed" && c.claimId === t) {
770
+ let n = c;
771
+ yield* i({
772
+ id: n.id,
773
+ itemId: n.intent.itemId,
774
+ plan: n.intent.plan,
775
+ expectedPriceId: n.intent.expectedPriceId,
776
+ beforeDispatch: () => e.check().pipe(C.andThen(s.dispatch(n.id, t))),
777
+ notDispatched: () => s.notDispatched(n.id, t),
778
+ rejected: (e) => s.reject(n.id, t, e).pipe(C.asVoid),
779
+ applied: (t) => We(e, n.id, t)
780
+ }, n.intent).pipe(C.catch((e) => C.sync(() => {
781
+ l = e;
782
+ })));
783
+ }
784
+ }
785
+ let u = yield* e.observe(), d = e.getObservation();
786
+ d?.writeOperationId === c.id && (yield* We(e, c.id, d));
787
+ let p = yield* s.getRequest(e.sub.tenantId, t);
788
+ if (p === null || p.id !== c.id) return yield* C.fail(e.refuse());
789
+ if (p.phase === "acknowledged") yield* s.complete(p.id);
790
+ else if (p.phase === "withdrawn" || p.phase === "rejected") return yield* C.fail(l ?? r(t, p.phase));
791
+ else if (p.phase !== "completed") return yield* C.fail(l ?? e.refuse());
792
+ return yield* e.check(), u;
793
+ }), Ke = (e, t = () => C.void) => C.gen(function* () {
794
+ let n = yield* P.stores.subscriptionWrites.getActive(e);
795
+ if (n === null) return "none";
796
+ if (n.phase === "prepared" || n.phase === "claimed") return yield* P.stores.subscriptionWrites.withdraw(n.id, {
797
+ phase: n.phase,
798
+ claimId: n.claimId
799
+ }), "withdrawn";
800
+ let r = yield* q(e, "cancel", t), i = r.getObservation();
801
+ if (n.intent.provider !== S.name || n.intent.subscriptionId !== r.sub.providerSubscriptionId || n.intent.customerId !== r.customer.providerCustomerId || n.intent.providerAccountId !== r.customer.account.providerAccountId || n.intent.livemode !== r.customer.account.livemode) return yield* C.fail(r.refuse());
802
+ if (n.phase !== "acknowledged") {
803
+ if (i?.writeOperationId !== n.id) return yield* C.fail(r.refuse());
804
+ yield* We(r, n.id, i);
805
+ }
806
+ return yield* r.stores.subscriptionWrites.complete(n.id), "completed";
807
+ }), qe = (e) => C.gen(function* () {
808
+ let t = e?.limit ?? 25, n = e?.afterTenantId ?? null, r = yield* P.stores.subscriptionWrites.listActive(t, n), i = {
809
+ examined: r.length,
810
+ completed: 0,
811
+ withdrawn: 0,
812
+ pending: 0
813
+ };
814
+ for (let e of r) {
815
+ let t = yield* Ke(e).pipe(C.catch(() => C.succeed("pending")));
816
+ t !== "none" && i[t]++;
817
+ }
818
+ return {
819
+ ...i,
820
+ nextAfter: r.length < t ? null : r.at(-1) ?? null
821
+ };
822
+ }), Je = (e) => {
823
+ let t = [...new Set(w.planIds().flatMap((e) => w.meteredPriceIdsFor(e)))];
824
+ return e === null || t.length === 0 ? {} : {
825
+ meteredPriceIds: [...new Set(w.meteredPriceIdsFor(e))],
826
+ replacesMeteredPriceIds: t
827
+ };
828
+ }, Ye = (e, t, n = () => C.void, r) => C.gen(function* () {
829
+ let i = t.plan === void 0 ? void 0 : w.priceIdFor(t.plan);
830
+ if (t.plan !== void 0 && (!w.has(t.plan) || i === null) || t.quantity !== void 0 && (!Number.isSafeInteger(t.quantity) || t.quantity < 1)) return yield* C.fail(new x({
831
+ source: "billing",
832
+ message: "Choose a self-service plan and a positive safe whole seat quantity.",
508
833
  transient: !1
509
834
  }));
510
- if (!Number.isInteger(a) || a <= 0) return yield* y.fail(new e({
835
+ let a = yield* q(e, "change", n);
836
+ if (t.quantity !== void 0 && t.quantity < w.minimumSeatsFor(t.plan ?? a.sub.plan)) return yield* C.fail(new x({
511
837
  source: "billing",
512
- message: `seat quantity must be a positive integer, got ${a}`,
838
+ message: "The plan price already covers more seats than requested.",
513
839
  transient: !1
514
840
  }));
515
- let o = yield* O(v.updateSubscription({
516
- providerSubscriptionId: r.providerSubscriptionId,
517
- ...n.plan === void 0 ? {} : { priceId: b.priceIdFor(i) ?? i },
518
- ...n.quantity === void 0 ? {} : { quantity: a },
841
+ let o = yield* Ge(a, r, {
842
+ kind: "change",
843
+ plan: t.plan ?? null,
844
+ priceId: i ?? null,
845
+ quantity: t.quantity ?? null
846
+ }, (e, t) => S.updateSubscription({
847
+ providerSubscriptionId: t.subscriptionId,
848
+ operation: e,
849
+ ...t.priceId === null ? {} : { priceId: t.priceId },
850
+ ...Je(t.plan),
851
+ ...t.quantity === null ? {} : { quantity: t.quantity },
519
852
  proration: "prorate"
520
- }), x);
521
- return yield* N.stores.subscriptions.patchByTenant(t, {
522
- ...n.plan === void 0 ? {} : { plan: i },
523
- quantity: o.quantity,
524
- ...o.currentPeriodStart === null ? {} : { currentPeriodStart: o.currentPeriodStart },
525
- ...o.currentPeriodEnd === null ? {} : { currentPeriodEnd: o.currentPeriodEnd }
526
- }), {
527
- tenantId: t,
528
- plan: i,
853
+ }));
854
+ return {
855
+ tenantId: e,
856
+ plan: o.plan,
529
857
  quantity: o.quantity,
530
- prorationMinor: o.prorationMinor,
531
- currency: o.currency
858
+ prorationMinor: null,
859
+ currency: w.currencyFor(o.plan)
532
860
  };
533
- }), Se = (t, n) => y.gen(function* () {
534
- let r = yield* N.stores.subscriptions.getByTenant(t);
535
- if (r === null) return yield* y.fail(new e({
861
+ }), Xe = (e, t) => C.gen(function* () {
862
+ let n = yield* P.stores.subscriptions.getByTenant(e);
863
+ if (n === null) return yield* C.fail(new x({
536
864
  source: "billing",
537
- message: `no subscription for tenant '${t}' to preview`,
865
+ message: `no subscription for tenant '${e}' to preview`,
538
866
  transient: !1
539
867
  }));
540
- let i = n.plan ?? r.plan, a = yield* O(v.previewSubscriptionChange({
541
- providerSubscriptionId: r.providerSubscriptionId,
542
- ...n.plan === void 0 ? {} : { priceId: b.priceIdFor(i) ?? i },
543
- ...n.quantity === void 0 ? {} : { quantity: n.quantity },
868
+ let r = t.plan ?? n.plan, i = t.plan === void 0 ? void 0 : w.priceIdFor(r);
869
+ if (!w.has(r) || i === null || t.quantity !== void 0 && (!Number.isSafeInteger(t.quantity) || t.quantity < 1)) return yield* C.fail(new x({
870
+ source: "billing",
871
+ message: "Choose a self-service plan and a positive safe whole seat quantity.",
872
+ transient: !1
873
+ }));
874
+ if (t.quantity !== void 0 && t.quantity < w.minimumSeatsFor(r)) return yield* C.fail(new x({
875
+ source: "billing",
876
+ message: "The plan price already covers more seats than requested.",
877
+ transient: !1
878
+ }));
879
+ let a = yield* M(S.previewSubscriptionChange({
880
+ providerSubscriptionId: n.providerSubscriptionId,
881
+ ...i === void 0 ? {} : { priceId: i },
882
+ ...Je(t.plan ?? null),
883
+ ...t.quantity === void 0 ? {} : { quantity: t.quantity },
544
884
  proration: "prorate"
545
- }), x);
546
- return {
547
- tenantId: t,
548
- plan: i,
885
+ }), T);
886
+ return a.plan !== r || !w.has(a.plan) || t.quantity !== void 0 && a.quantity !== t.quantity || !Number.isSafeInteger(a.quantity) || a.quantity < 1 || !Number.isSafeInteger(a.prorationMinor) || a.currency !== w.currencyFor(a.plan) ? yield* C.fail(new x({
887
+ source: "billing",
888
+ message: "The provider preview could not be confirmed. Refresh billing before retrying.",
889
+ transient: !0
890
+ })) : {
891
+ tenantId: e,
892
+ plan: a.plan,
549
893
  quantity: a.quantity,
550
894
  prorationMinor: a.prorationMinor,
551
895
  currency: a.currency
552
896
  };
553
- }), Ce = (e) => y.gen(function* () {
897
+ }), Ze = (e) => C.gen(function* () {
554
898
  let t = yield* z(e);
555
- return t === null ? [] : yield* O(v.listInvoices({ providerCustomerId: t.providerCustomerId }), x);
556
- }), we = (t, n, r = N.stores) => y.gen(function* () {
557
- let a = v.fetchInvoiceSnapshot?.bind(v), c = v.fetchAccountIdentity?.bind(v);
558
- if (a === void 0 || c === void 0) return yield* y.fail(s("Complete account-owned invoice evidence is unsupported."));
559
- if (N.stores !== r) return yield* y.fail(s("Billing stores changed before invoice observation.", !0));
560
- let l = yield* I();
561
- if (l.provider !== t.provider || !i(l.account, t.account)) return yield* y.fail(s("The invoice account differs from retained custody."));
562
- let u = yield* c();
563
- if (!i(u, t.account)) return yield* y.fail(s("The provider account changed before invoice observation."));
564
- let d = yield* O(a({
565
- providerCustomerId: t.providerCustomerId,
566
- providerInvoiceId: n
567
- }), x);
568
- yield* y.try({
899
+ return t === null ? [] : yield* M(S.listInvoices({ providerCustomerId: t.providerCustomerId }), T);
900
+ }), Qe = (e, t, n = P.stores) => C.gen(function* () {
901
+ let r = S.fetchInvoiceSnapshot?.bind(S), i = S.fetchAccountIdentity?.bind(S);
902
+ if (r === void 0 || i === void 0) return yield* C.fail(o("Complete account-owned invoice evidence is unsupported."));
903
+ if (P.stores !== n) return yield* C.fail(o("Billing stores changed before invoice observation.", !0));
904
+ let s = yield* L();
905
+ if (s.provider !== e.provider || !c(s.account, e.account)) return yield* C.fail(o("The invoice account differs from retained custody."));
906
+ let l = yield* i();
907
+ if (!c(l, e.account)) return yield* C.fail(o("The provider account changed before invoice observation."));
908
+ let u = yield* M(r({
909
+ providerCustomerId: e.providerCustomerId,
910
+ providerInvoiceId: t
911
+ }), T);
912
+ yield* C.try({
569
913
  try: () => {
570
- if (o(d), d.providerInvoiceId !== n || d.providerCustomerId !== t.providerCustomerId || d.livemode !== t.account.livemode) throw s("The invoice does not match retained account/customer custody.");
914
+ if (a(u), u.providerInvoiceId !== t || u.providerCustomerId !== e.providerCustomerId || u.livemode !== e.account.livemode) throw o("The invoice does not match retained account/customer custody.");
571
915
  },
572
- catch: (t) => t instanceof e ? t : s("The provider invoice could not be confirmed.")
916
+ catch: (e) => e instanceof x ? e : o("The provider invoice could not be confirmed.")
573
917
  });
574
- let f = yield* c(), p = yield* r.customers.getByProviderCustomerId(t.providerCustomerId, l);
575
- return N.stores !== r || !i(f, t.account) || p === null || p.id !== t.id || p.tenantId !== t.tenantId ? yield* y.fail(s("Invoice account/customer custody changed during observation.", !0)) : d;
576
- }), Te = (t, n, a) => y.gen(function* () {
577
- let o = N.stores;
578
- if (!t || t.trim() !== t) return yield* y.fail(u("Exact tenant/customer identities are required."));
579
- let s = yield* y.try({
918
+ let d = yield* i(), f = yield* n.customers.getByProviderCustomerId(e.providerCustomerId, s);
919
+ return P.stores !== n || !c(d, e.account) || f === null || f.id !== e.id || f.tenantId !== e.tenantId ? yield* C.fail(o("Invoice account/customer custody changed during observation.", !0)) : u;
920
+ }), J = (e, t, n) => C.gen(function* () {
921
+ let r = P.stores;
922
+ if (!e || e.trim() !== e) return yield* C.fail(d("Exact tenant/customer identities are required."));
923
+ let i = yield* C.try({
580
924
  try: () => {
581
- let e = a?.cursor, t = e === void 0 ? void 0 : Object.freeze({
582
- ...r(e),
925
+ let e = n?.cursor, t = e === void 0 ? void 0 : Object.freeze({
926
+ ...s(e),
583
927
  providerCustomerId: e.providerCustomerId,
584
928
  afterInvoiceId: e.afterInvoiceId
585
- }), n = a?.limit;
929
+ }), r = n?.limit;
586
930
  return Object.freeze({
587
931
  ...t === void 0 ? {} : { cursor: t },
588
- ...n === void 0 ? {} : { limit: n }
932
+ ...r === void 0 ? {} : { limit: r }
589
933
  });
590
934
  },
591
- catch: (t) => t instanceof e ? t : u()
592
- }), d = yield* I(), f = yield* y.try({
593
- try: () => c({
594
- account: d.account,
595
- providerCustomerId: n,
596
- ...s
935
+ catch: (e) => e instanceof x ? e : d()
936
+ }), a = yield* L(), o = yield* C.try({
937
+ try: () => l({
938
+ account: a.account,
939
+ providerCustomerId: t,
940
+ ...i
597
941
  }),
598
- catch: (t) => t instanceof e ? t : u()
599
- }), p = yield* o.customers.getByProviderCustomerId(f.providerCustomerId, d);
600
- if (p === null || p.tenantId !== t || p.provider !== v.name) return yield* y.fail(u("Positive current or retained customer custody is required."));
601
- let m = v.listInvoiceHistory?.bind(v), h = v.fetchAccountIdentity?.bind(v);
602
- if (m === void 0 || h === void 0) return yield* y.fail(u("Complete account-owned invoice history is unsupported."));
603
- let g = yield* h();
604
- if (!i(g, p.account)) return yield* y.fail(u("The provider account differs before invoice history access."));
605
- let _ = yield* O(m(f), x), b = yield* y.try({
606
- try: () => l(f, _),
607
- catch: (t) => t instanceof e ? t : u()
608
- }), S = yield* h(), C = yield* o.customers.getByProviderCustomerId(f.providerCustomerId, d);
609
- return N.stores !== o || !i(S, p.account) || C === null || C.id !== p.id || C.tenantId !== t ? yield* y.fail(u("Invoice history account/customer custody changed during observation.", !0)) : b;
610
- }), Ee = (e, t) => y.gen(function* () {
611
- if (!e || e.trim() !== e || !t || t.trim() !== t) return yield* y.fail(s("Exact tenant/invoice identities are required."));
942
+ catch: (e) => e instanceof x ? e : d()
943
+ }), f = yield* r.customers.getByProviderCustomerId(o.providerCustomerId, a);
944
+ if (f === null || f.tenantId !== e || f.provider !== S.name) return yield* C.fail(d("Positive current or retained customer custody is required."));
945
+ let p = S.listInvoiceHistory?.bind(S), m = S.fetchAccountIdentity?.bind(S);
946
+ if (p === void 0 || m === void 0) return yield* C.fail(d("Complete account-owned invoice history is unsupported."));
947
+ let h = yield* m();
948
+ if (!c(h, f.account)) return yield* C.fail(d("The provider account differs before invoice history access."));
949
+ let g = yield* M(p(o), T), _ = yield* C.try({
950
+ try: () => u(o, g),
951
+ catch: (e) => e instanceof x ? e : d()
952
+ }), v = yield* m(), y = yield* r.customers.getByProviderCustomerId(o.providerCustomerId, a);
953
+ return P.stores !== r || !c(v, f.account) || y === null || y.id !== f.id || y.tenantId !== e ? yield* C.fail(d("Invoice history account/customer custody changed during observation.", !0)) : _;
954
+ }), $e = (e, t) => C.gen(function* () {
955
+ if (!e || e.trim() !== e || !t || t.trim() !== t) return yield* C.fail(o("Exact tenant/invoice identities are required."));
612
956
  let n = yield* z(e);
613
- return n === null ? yield* y.fail(s("A qualified current customer is required.")) : yield* we(n, t);
614
- }), J = (e, t, n) => y.gen(function* () {
615
- let r = N.stores;
616
- if (!e || e.trim() !== e || !t || t.trim() !== t) return yield* y.fail(s("Exact tenant/invoice identities are required."));
617
- let i = yield* I();
957
+ return n === null ? yield* C.fail(o("A qualified current customer is required.")) : yield* Qe(n, t);
958
+ }), Y = (e, t, n) => C.gen(function* () {
959
+ let r = P.stores;
960
+ if (!e || e.trim() !== e || !t || t.trim() !== t) return yield* C.fail(o("Exact tenant/invoice identities are required."));
961
+ let i = yield* L();
618
962
  for (let a = 0; a < 3; a++) {
619
- if (N.stores !== r) return yield* y.fail(s("Billing stores changed during invoice reconciliation.", !0));
963
+ if (P.stores !== r) return yield* C.fail(o("Billing stores changed during invoice reconciliation.", !0));
620
964
  let a = n === void 0 ? yield* z(e) : yield* r.customers.getByProviderCustomerId(n, i);
621
- if (a === null || a.tenantId !== e) return yield* y.fail(s("Positive current or retained customer custody is required.", !0));
622
- let o = Object.freeze({
965
+ if (a === null || a.tenantId !== e) return yield* C.fail(o("Positive current or retained customer custody is required.", !0));
966
+ let s = Object.freeze({
623
967
  tenantId: e,
624
968
  provider: i.provider,
625
969
  ...i.account,
626
970
  providerCustomerId: a.providerCustomerId,
627
971
  providerInvoiceId: t
628
- }), c = yield* r.invoices.get(o), l = yield* we(a, t, r);
629
- if (N.stores !== r) return yield* y.fail(s("Billing stores changed before native invoice persistence.", !0));
630
- if (!(yield* r.invoices.complete(o, c, l))) continue;
631
- let u = yield* r.invoices.get(o);
632
- return u === null || u.revision <= (c?.revision ?? 0) ? yield* y.fail(s("Invoice persistence could not be confirmed.", !0)) : u;
972
+ }), c = yield* r.invoices.capturePaymentEpoch(s), l = yield* r.invoices.get(s), u = yield* Qe(a, t, r);
973
+ if (P.stores !== r) return yield* C.fail(o("Billing stores changed before native invoice persistence.", !0));
974
+ if (!(yield* r.invoices.complete(s, l, u, c))) continue;
975
+ let d = yield* r.invoices.get(s);
976
+ return d === null || d.revision <= (l?.revision ?? 0) ? yield* C.fail(o("Invoice persistence could not be confirmed.", !0)) : d;
633
977
  }
634
- return yield* y.fail(s("Concurrent invoice observation requires retry.", !0));
635
- }), De = (t, n) => y.gen(function* () {
636
- if (n === "free") {
637
- let e = yield* Ae(t);
978
+ return yield* C.fail(o("Concurrent invoice observation requires retry.", !0));
979
+ }), et = (e, t, n, r = () => C.void, i) => C.gen(function* () {
980
+ if (t === "free") {
981
+ let t = yield* tt(e, r, i);
638
982
  return {
639
- tenantId: t,
640
- plan: e.plan,
641
- quantity: e.quantity,
642
- prorationMinor: 0,
643
- currency: b.currencyFor(e.plan)
983
+ tenantId: e,
984
+ plan: t.plan,
985
+ quantity: t.quantity,
986
+ prorationMinor: null,
987
+ currency: w.currencyFor(t.plan)
644
988
  };
645
989
  }
646
- return b.has(n) && b.priceIdFor(n) === null ? yield* y.fail(new e({
990
+ return w.has(t) && w.priceIdFor(t) === null ? yield* C.fail(new x({
647
991
  source: "billing",
648
- message: `plan '${n}' has no provider price — it is not a self-serve plan`,
992
+ message: `plan '${t}' has no provider price — it is not a self-serve plan`,
649
993
  transient: !1
650
- })) : yield* xe(t, { plan: n });
651
- }), Oe = (t, n) => N.stores.subscriptions.getByTenant(t).pipe(y.flatMap((r) => r !== null && _(r.status) ? y.succeed(r) : y.fail(new e({
652
- source: "billing",
653
- message: `no live subscription for tenant '${t}' to ${n}`,
654
- transient: !1
655
- })))), ke = (e, t) => y.gen(function* () {
656
- let n = A();
657
- return yield* G(e.tenantId, {
658
- ...t,
659
- providerSubscriptionId: e.providerSubscriptionId
660
- }, n), {
661
- ...e,
662
- ...t,
663
- plan: t.plan ?? e.plan,
664
- statusEventAt: n
665
- };
666
- }), Ae = (e) => y.gen(function* () {
667
- yield* j(e, "cancel"), yield* Z(e);
668
- let t = yield* Oe(e, "cancel"), n = yield* O(v.cancelSubscription({
669
- providerSubscriptionId: t.providerSubscriptionId,
670
- mode: "periodEnd"
671
- }), x);
672
- return yield* ke(t, n);
673
- }), je = (e) => y.gen(function* () {
674
- yield* j(e, "resume"), yield* Z(e);
675
- let t = yield* Oe(e, "resume"), n = yield* O(v.resumeSubscription(t.providerSubscriptionId), x);
676
- return yield* ke(t, n);
677
- }), Y = (t) => y.gen(function* () {
678
- yield* L(t), yield* R(t);
679
- let n = () => new e({
994
+ })) : yield* Ye(e, { plan: t }, r, i);
995
+ }), tt = (e, t = () => C.void, n) => C.gen(function* () {
996
+ let r = yield* q(e, "cancel", t);
997
+ return yield* Ge(r, n, {
998
+ kind: "cancel",
999
+ plan: null,
1000
+ priceId: null,
1001
+ quantity: null
1002
+ }, (e, t) => S.cancelSubscription({
1003
+ providerSubscriptionId: t.subscriptionId,
1004
+ mode: "periodEnd",
1005
+ operation: e
1006
+ }));
1007
+ }), nt = (e, t = () => C.void, n) => C.gen(function* () {
1008
+ let r = yield* q(e, "resume", t);
1009
+ return yield* Ge(r, n, {
1010
+ kind: "resume",
1011
+ plan: null,
1012
+ priceId: null,
1013
+ quantity: null
1014
+ }, (e, t) => S.resumeSubscription(t.subscriptionId, e));
1015
+ }), rt = (e) => C.gen(function* () {
1016
+ yield* R(e), yield* fe(e);
1017
+ let t = () => new x({
680
1018
  source: "billing",
681
1019
  message: "Billing closure is pending provider confirmation. Retry reconciliation before completing account deletion.",
682
1020
  transient: !0
683
1021
  });
684
- if (t.length === 0) return yield* y.fail(n());
685
- yield* N.stores.closures.reserveAccount(t, v.name, A());
686
- let r = yield* z(t), i = yield* N.stores.checkouts.getActive(t);
687
- if (r !== null && r.provider !== v.name || i !== null && i.provider !== v.name || r !== null && i?.providerCustomerId !== null && i?.providerCustomerId !== void 0 && r.providerCustomerId !== i.providerCustomerId) return yield* y.fail(n());
688
- let a = /* @__PURE__ */ new Set();
689
- r !== null && a.add(r.providerCustomerId), i?.providerCustomerId && a.add(i.providerCustomerId);
690
- for (let e of a) yield* O(v.expireOpenCheckouts({ providerCustomerId: e }), x);
691
- let o = null;
692
- if (i !== null) {
693
- let e = yield* O(v.findCheckoutSession({
694
- tenantId: t,
695
- operationId: i.id,
696
- ...i.providerCustomerId === null ? {} : { providerCustomerId: i.providerCustomerId }
697
- }), x), r = e.receipt;
698
- if (r === null) {
699
- if (e.observedAt === null || !Number.isFinite(e.observedAt.getTime()) || e.observedAt.getTime() < i.expiresAt.getTime()) return yield* y.fail(n());
700
- yield* N.stores.checkouts.patch(i.id, { phase: "expired" });
1022
+ if (e.length === 0) return yield* C.fail(t());
1023
+ yield* Ke(e), yield* P.stores.subscriptionWrites.seal(e), yield* P.stores.closures.reserveAccount(e, S.name, k());
1024
+ let n = yield* z(e), r = yield* P.stores.checkouts.getActive(e);
1025
+ if (n !== null && n.provider !== S.name || r !== null && r.provider !== S.name || n !== null && r?.providerCustomerId !== null && r?.providerCustomerId !== void 0 && n.providerCustomerId !== r.providerCustomerId) return yield* C.fail(t());
1026
+ let i = /* @__PURE__ */ new Set();
1027
+ n !== null && i.add(n.providerCustomerId), r?.providerCustomerId && i.add(r.providerCustomerId);
1028
+ for (let e of i) yield* M(S.expireOpenCheckouts({ providerCustomerId: e }), T);
1029
+ let a = null;
1030
+ if (r !== null) {
1031
+ let n = yield* M(S.findCheckoutSession({
1032
+ tenantId: e,
1033
+ operationId: r.id,
1034
+ ...r.providerCustomerId === null ? {} : { providerCustomerId: r.providerCustomerId }
1035
+ }), T), o = n.receipt;
1036
+ if (o === null) {
1037
+ if (n.observedAt === null || !Number.isFinite(n.observedAt.getTime()) || n.observedAt.getTime() < r.expiresAt.getTime()) return yield* C.fail(t());
1038
+ yield* P.stores.checkouts.patch(r.id, { phase: "expired" });
701
1039
  } else {
702
- if (r.operationId !== i.id || r.tenantId !== t || !r.id || r.providerCustomerId === null || r.expiresAt.getTime() !== i.expiresAt.getTime() || i.providerCustomerId !== null && r.providerCustomerId !== i.providerCustomerId || i.providerSessionId !== null && r.id !== i.providerSessionId) return yield* y.fail(n());
703
- if (a.add(r.providerCustomerId), yield* N.stores.checkouts.patch(i.id, {
704
- providerCustomerId: r.providerCustomerId,
705
- providerSessionId: r.id
706
- }), r.status === "open") return yield* O(v.expireOpenCheckouts({ providerCustomerId: r.providerCustomerId }), x), yield* y.fail(n());
707
- if (r.status === "expired") yield* N.stores.checkouts.patch(i.id, { phase: "expired" });
1040
+ if (o.operationId !== r.id || o.tenantId !== e || !o.id || o.providerCustomerId === null || o.expiresAt.getTime() !== r.expiresAt.getTime() || r.providerCustomerId !== null && o.providerCustomerId !== r.providerCustomerId || r.providerSessionId !== null && o.id !== r.providerSessionId) return yield* C.fail(t());
1041
+ if (i.add(o.providerCustomerId), yield* P.stores.checkouts.patch(r.id, {
1042
+ providerCustomerId: o.providerCustomerId,
1043
+ providerSessionId: o.id
1044
+ }), o.status === "open") return yield* M(S.expireOpenCheckouts({ providerCustomerId: o.providerCustomerId }), T), yield* C.fail(t());
1045
+ if (o.status === "expired") yield* P.stores.checkouts.patch(r.id, { phase: "expired" });
708
1046
  else {
709
- if (r.providerSubscriptionId === null) return yield* y.fail(n());
710
- o = r.providerSubscriptionId, yield* N.stores.checkouts.patch(i.id, { phase: "completed" });
1047
+ if (o.providerSubscriptionId === null) return yield* C.fail(t());
1048
+ a = o.providerSubscriptionId, yield* P.stores.checkouts.patch(r.id, { phase: "completed" });
711
1049
  }
712
1050
  }
713
1051
  }
714
- yield* U(t), yield* N.stores.closures.sealUsage(t);
715
- let s = yield* N.stores.usage.pending();
716
- if (v.supportsMeteredUsage && s.some((e) => e.tenantId === t && e.used > e.reportedToProvider)) return yield* y.fail(V());
717
- let c = yield* N.stores.subscriptions.listByTenant(t), l = new Set(c.filter((e) => _(e.status)).map((e) => e.providerSubscriptionId));
718
- o !== null && l.add(o);
719
- for (let e of a) {
720
- let t = yield* O(v.listSubscriptions({ providerCustomerId: e }), x);
721
- for (let e of t) l.add(e.providerSubscriptionId);
1052
+ yield* Me(e), yield* P.stores.closures.sealUsage(e);
1053
+ let o = yield* P.stores.usage.pending();
1054
+ if (S.supportsMeteredUsage && o.some((t) => t.tenantId === e && t.used > t.reportedToProvider)) return yield* C.fail(V());
1055
+ let s = yield* P.stores.subscriptions.listByTenant(e), c = new Set(s.filter((e) => f(e.status)).map((e) => e.providerSubscriptionId));
1056
+ a !== null && c.add(a);
1057
+ for (let e of i) {
1058
+ let t = yield* M(S.listSubscriptions({ providerCustomerId: e }), T);
1059
+ for (let e of t) c.add(e.providerSubscriptionId);
722
1060
  }
723
- let u = [], d = !1;
724
- for (let e of l) {
725
- let r = yield* O(v.fetchSubscription(e), x);
1061
+ let l = [], u = /* @__PURE__ */ new Set(), d = !1;
1062
+ for (let n of c) {
1063
+ let r = yield* M(S.fetchSubscription(n), T);
726
1064
  if (r === null) {
727
1065
  d = !0;
728
1066
  continue;
729
1067
  }
730
1068
  let i = r;
731
1069
  if (r.status !== "canceled") {
732
- let r = yield* N.stores.closures.getSubscription(t, e);
1070
+ let r = yield* P.stores.closures.getSubscription(e, n);
733
1071
  if (r === null) {
734
- let n = yield* O(v.prepareSubscriptionClose(e), x);
735
- r = yield* N.stores.closures.reserveSubscription({
736
- tenantId: t,
737
- provider: v.name,
738
- providerSubscriptionId: e,
739
- cancelAt: n.cancelAt,
740
- createdAt: A()
1072
+ let t = yield* M(S.prepareSubscriptionClose(n), T);
1073
+ r = yield* P.stores.closures.reserveSubscription({
1074
+ tenantId: e,
1075
+ provider: S.name,
1076
+ providerSubscriptionId: n,
1077
+ cancelAt: t.cancelAt,
1078
+ createdAt: k()
741
1079
  });
742
1080
  }
743
- if (r.provider !== v.name || r.providerSubscriptionId !== e || r.cancelAt === null) return yield* y.fail(n());
744
- i = yield* O(v.cancelSubscription({
745
- providerSubscriptionId: e,
1081
+ if (r.provider !== S.name || r.providerSubscriptionId !== n || r.cancelAt === null) return yield* C.fail(t());
1082
+ i = yield* M(S.cancelSubscription({
1083
+ providerSubscriptionId: n,
746
1084
  mode: "close",
747
1085
  closeOperation: {
748
1086
  id: r.id,
749
1087
  cancelAt: r.cancelAt
750
1088
  }
751
- }), x);
1089
+ }), T);
752
1090
  }
753
- yield* G(t, {
1091
+ yield* W(e, {
754
1092
  ...i,
755
- providerSubscriptionId: e
756
- }, A()), i.status === "canceled" ? u.push(e) : d = !0;
1093
+ providerSubscriptionId: n
1094
+ }, k()), i.status === "canceled" ? l.push(n) : u.add(n);
757
1095
  }
758
- for (let e of a) (yield* O(v.listSubscriptions({ providerCustomerId: e }), x)).some((e) => e.status !== "canceled") && (d = !0);
759
- if (d) return yield* y.fail(n());
760
- let f = yield* N.stores.usage.pending();
761
- return v.supportsMeteredUsage && f.some((e) => e.tenantId === t && e.used > e.reportedToProvider) ? yield* y.fail(V()) : (i !== null && o !== null && (yield* N.stores.checkouts.patch(i.id, { phase: "retired" })), C.info("billing account closed", {
762
- tenant: t,
763
- canceled: u.length
1096
+ for (let e of i) (yield* M(S.listSubscriptions({ providerCustomerId: e }), T)).some((e) => e.status !== "canceled" && !u.has(e.providerSubscriptionId)) && (d = !0);
1097
+ if (d) return yield* C.fail(t());
1098
+ if (u.size > 0) return yield* C.fail(new ee({
1099
+ tenantId: e,
1100
+ reason: "cancellation-settling",
1101
+ providerInvoiceIds: [],
1102
+ message: "Billing closure is pending provider confirmation: subscriptions end after the meter settlement window."
1103
+ }));
1104
+ let p = yield* P.stores.usage.pending();
1105
+ if (S.supportsMeteredUsage && p.some((t) => t.tenantId === e && t.used > t.reportedToProvider)) return yield* C.fail(V());
1106
+ r !== null && a !== null && (yield* P.stores.checkouts.patch(r.id, { phase: "retired" }));
1107
+ let m = /* @__PURE__ */ new Set([...l, ...s.filter((e) => e.provider === S.name).map((e) => e.providerSubscriptionId)]), h = yield* it(e, [...m], n, t);
1108
+ return D.info("billing account closed", {
1109
+ tenant: e,
1110
+ canceled: l.length,
1111
+ finalInvoices: h.length
764
1112
  }), {
765
- tenantId: t,
766
- canceled: u
767
- });
768
- }), Me = (e) => y.gen(function* () {
769
- return (yield* N.stores.closures.getAccount(e)) === null ? t.isTenantClosed === void 0 ? !1 : yield* t.isTenantClosed(e) : !0;
770
- }), Ne = (e) => Me(e).pipe(y.catch((t) => y.sync(() => (C.warn("billing: could not tell whether a tenant is closed — leaving it", {
1113
+ tenantId: e,
1114
+ canceled: l,
1115
+ finalInvoices: h
1116
+ };
1117
+ }), it = (e, t, n, r) => C.gen(function* () {
1118
+ let i = /* @__PURE__ */ new Set();
1119
+ for (let e of t) {
1120
+ let t = yield* X(e, n ?? void 0);
1121
+ if (t.status !== "canceled") return yield* C.fail(r());
1122
+ t.providerLatestInvoiceId && i.add(t.providerLatestInvoiceId);
1123
+ }
1124
+ if (i.size === 0) return [];
1125
+ if (n === null) return yield* C.fail(r());
1126
+ let a = (t, n) => new ee({
1127
+ tenantId: e,
1128
+ reason: t,
1129
+ providerInvoiceIds: [...n],
1130
+ message: t === "final-invoice-draft" ? "Billing closure waits for the provider to finalize the final invoice." : "Billing closure waits until the final invoice is paid, uncollectible or void."
1131
+ }), o = yield* J(e, n.providerCustomerId, { limit: 100 }), s = [];
1132
+ for (let e of i) {
1133
+ let t = o.invoices.find((t) => t.providerInvoiceId === e);
1134
+ if (t === void 0) return yield* C.fail(r());
1135
+ t.status === "draft" && s.push(e);
1136
+ }
1137
+ if (s.length > 0) return yield* C.fail(a("final-invoice-draft", s));
1138
+ let c = [], l = [];
1139
+ for (let t of i) {
1140
+ let r = (yield* Y(e, t, n.providerCustomerId)).snapshot.status;
1141
+ r === "open" ? l.push(t) : c.push({
1142
+ providerInvoiceId: t,
1143
+ status: r
1144
+ });
1145
+ }
1146
+ return l.length > 0 ? yield* C.fail(a("final-invoice-open", l)) : c;
1147
+ }), at = (e) => C.gen(function* () {
1148
+ return (yield* P.stores.closures.getAccount(e)) === null ? p.isTenantClosed === void 0 ? !1 : yield* p.isTenantClosed(e) : !0;
1149
+ }), ot = (e) => at(e).pipe(C.catch((t) => C.sync(() => (D.warn("billing: could not tell whether a tenant is closed — leaving it", {
771
1150
  tenant: e,
772
1151
  message: t.message
773
- }), !1)))), X = (e) => y.gen(function* () {
774
- let t = v.fetchSubscriptionSnapshot;
775
- if (t === void 0) return yield* y.fail(s("Customer-qualified subscription observations are required."));
776
- let n = yield* I(), r = v.fetchAccountIdentity;
777
- if (r === void 0) return yield* y.fail(s("Provider account observations are required."));
778
- let a = yield* r();
779
- if (!i(a, n.account)) return yield* y.fail(s("The provider account changed before subscription observation."));
780
- let o = yield* O(t(e), x), c = yield* r();
781
- return !i(c, n.account) || o === null || o.providerSubscriptionId !== e || o.providerCustomerId === null ? yield* y.fail(s("A complete subscription observation in the retained provider account is required.")) : o;
782
- }), Pe = (t, n) => y.gen(function* () {
783
- let r = A(), i = yield* N.stores.customers.getByProviderCustomerId(t, yield* I());
784
- if (i !== null && i.retiredAt !== null) {
785
- let e = [];
786
- for (let n of yield* N.stores.subscriptions.listByTenant(i.tenantId)) {
787
- let a = yield* X(n.providerSubscriptionId);
788
- if (a.providerCustomerId !== t) continue;
789
- if (a.status !== "canceled") return yield* y.fail(s("A retired customer still has an unsettled provider subscription."));
790
- let o = yield* N.stores.customers.getByProviderCustomerId(t, yield* I());
791
- if (o === null || o.id !== i.id || o.tenantId !== i.tenantId || o.retiredAt === null) return yield* y.fail(s("Retired customer custody changed during reconciliation."));
792
- yield* G(i.tenantId, a, r), e.push(Q(i.tenantId, a, r));
1152
+ }), !1)))), X = (e, t) => C.gen(function* () {
1153
+ let n = S.fetchSubscriptionSnapshot;
1154
+ if (n === void 0) return yield* C.fail(o("Customer-qualified subscription observations are required."));
1155
+ let r = yield* L(), i = S.fetchAccountIdentity;
1156
+ if (i === void 0) return yield* C.fail(o("Provider account observations are required."));
1157
+ let a = yield* i();
1158
+ if (!c(a, r.account)) return yield* C.fail(o("The provider account changed before subscription observation."));
1159
+ let l = P.stores, u = t === void 0 ? null : yield* l.customers.getByProviderCustomerId(t.providerCustomerId, r);
1160
+ if (t !== void 0 && (u === null || u.id !== t.id || u.tenantId !== t.tenantId)) return yield* C.fail(o("Native subscription customer custody changed."));
1161
+ let d = t === void 0 ? null : yield* l.invoices.capturePaymentEpoch({
1162
+ tenantId: t.tenantId,
1163
+ provider: r.provider,
1164
+ ...r.account,
1165
+ providerCustomerId: t.providerCustomerId
1166
+ }), f = yield* M(n(e), T), p = yield* i();
1167
+ return !c(p, r.account) || f === null || f.providerSubscriptionId !== e || f.providerCustomerId === null || t !== void 0 && f.providerCustomerId !== t.providerCustomerId || P.stores !== l ? yield* C.fail(o("A complete subscription observation in the retained provider account is required.")) : {
1168
+ ...f,
1169
+ providerAccount: s(r.account),
1170
+ paymentEpoch: d
1171
+ };
1172
+ }), st = (e, t = !1) => C.gen(function* () {
1173
+ let n = P.stores, r = () => t ? n.closures.getAccount(e.tenantId).pipe(C.map((e) => e !== null)) : C.succeed(!1);
1174
+ if (yield* r()) return [];
1175
+ let i = yield* n.customers.getByTenant(e.tenantId);
1176
+ if (i === null || i.id !== e.id) return [];
1177
+ let a = yield* n.subscriptions.getByTenant(e.tenantId);
1178
+ if (a === null || a.provider !== S.name) return [];
1179
+ let s = yield* X(a.providerSubscriptionId, e);
1180
+ if (P.stores !== n) return yield* C.fail(o("Billing stores changed during current subscription refresh.", !0));
1181
+ if (yield* r()) return [];
1182
+ let c = k();
1183
+ yield* W(e.tenantId, s, c);
1184
+ let l = Q(e.tenantId, s, c);
1185
+ return yield* K(l), [l];
1186
+ }), ct = (e, t) => C.gen(function* () {
1187
+ let n = k(), r = yield* P.stores.customers.getByProviderCustomerId(e, yield* L());
1188
+ if (r !== null && r.retiredAt !== null) {
1189
+ let t = [];
1190
+ for (let i of yield* P.stores.subscriptions.listByTenant(r.tenantId)) {
1191
+ let a = yield* X(i.providerSubscriptionId, r);
1192
+ if (a.providerCustomerId !== e) continue;
1193
+ if (a.status !== "canceled") return yield* C.fail(o("A retired customer still has an unsettled provider subscription."));
1194
+ let s = yield* P.stores.customers.getByProviderCustomerId(e, yield* L());
1195
+ if (s === null || s.id !== r.id || s.tenantId !== r.tenantId || s.retiredAt === null) return yield* C.fail(o("Retired customer custody changed during reconciliation."));
1196
+ yield* W(r.tenantId, a, n), t.push(Q(r.tenantId, a, n));
793
1197
  }
794
- for (let t of e) yield* q(t);
1198
+ for (let e of t) yield* K(e);
795
1199
  return {
796
- tenantId: i.tenantId,
797
- events: e
1200
+ tenantId: r.tenantId,
1201
+ events: t
798
1202
  };
799
1203
  }
800
- let a = yield* O(v.listSubscriptions({ providerCustomerId: t }), x);
801
- if (a.some((e) => e.providerCustomerId !== t)) return yield* y.fail(s("The subscription listing names another customer."));
802
- let o = i?.tenantId ?? n ?? a.find((e) => e.tenantId !== null)?.tenantId ?? null;
803
- if (o === null) return C.warn("billing sync: customer names no tenant — nothing to attribute it to", { customer: t }), {
1204
+ let i = yield* M(S.listSubscriptions({ providerCustomerId: e }), T);
1205
+ if (i.some((t) => t.providerCustomerId !== e)) return yield* C.fail(o("The subscription listing names another customer."));
1206
+ let a = r?.tenantId ?? t ?? i.find((e) => e.tenantId !== null)?.tenantId ?? null;
1207
+ if (a === null) return D.warn("billing sync: customer names no tenant — nothing to attribute it to", { customer: e }), {
804
1208
  tenantId: null,
805
1209
  events: []
806
1210
  };
807
- let c = [], l = yield* z(o);
808
- if (i !== null && i.provider !== v.name || l !== null && (l.provider !== v.name || l.providerCustomerId !== t)) return yield* y.fail(new e({
1211
+ let s = [], c = yield* z(a);
1212
+ if (r !== null && r.provider !== S.name || c !== null && (c.provider !== S.name || c.providerCustomerId !== e)) return yield* C.fail(new x({
809
1213
  source: "billing.syncCustomer",
810
1214
  message: "Customer discovery cannot replace existing native billing custody.",
811
1215
  transient: !1
812
1216
  }));
813
- if (i === null) {
814
- if (yield* Me(o)) return yield* y.fail(s("Closed tenant customer custody requires reconciliation."));
815
- yield* B(o, t), c.push({
1217
+ if (r === null) {
1218
+ if (yield* at(a)) return yield* C.fail(o("Closed tenant customer custody requires reconciliation."));
1219
+ yield* B(a, e), s.push({
816
1220
  _tag: "customerLinked",
817
- tenantId: o,
818
- providerCustomerId: t,
819
- occurredAt: r
1221
+ tenantId: a,
1222
+ providerCustomerId: e,
1223
+ occurredAt: n
820
1224
  });
821
1225
  }
822
- a.some((e) => T.has(e.status) && e.cancelAt === null) && (yield* Ne(o)) && (C.error("billing sync: a closed tenant still has a paying subscription — closing it", { tenant: o }), yield* Y(o), a = yield* O(v.listSubscriptions({ providerCustomerId: t }), x));
823
- for (let e of a) if (yield* G(o, e, r), c.push(Q(o, e, r)), e.plan !== null && T.has(e.status)) {
824
- let t = b.meteredPriceIdsFor(e.plan).filter((t) => !e.priceIds.includes(t));
825
- t.length > 0 && (yield* O(v.addSubscriptionPrices({
826
- providerSubscriptionId: e.providerSubscriptionId,
827
- priceIds: t
828
- }), x));
1226
+ i.some((e) => O.has(e.status) && e.cancelAt === null) && (yield* ot(a)) && (D.error("billing sync: a closed tenant still has a paying subscription — closing it", { tenant: a }), yield* rt(a).pipe(C.catchTag("BillingClosurePending", (e) => C.fail(new x({
1227
+ source: "billing",
1228
+ message: e.message,
1229
+ transient: !0
1230
+ })))), i = yield* M(S.listSubscriptions({ providerCustomerId: e }), T));
1231
+ let l = yield* P.stores.customers.getByProviderCustomerId(e, yield* L());
1232
+ if (l === null || l.tenantId !== a) return yield* C.fail(o("Current native customer custody is required."));
1233
+ for (let t of i) {
1234
+ let r = yield* X(t.providerSubscriptionId, l);
1235
+ if (r.providerCustomerId !== e) return yield* C.fail(o("The current subscription belongs to another customer."));
1236
+ if (yield* W(a, r, n), s.push(Q(a, r, n)), r.plan !== null && O.has(r.status)) {
1237
+ let e = w.meteredPriceIdsFor(r.plan).filter((e) => !r.priceIds.includes(e));
1238
+ e.length > 0 && (yield* M(S.addSubscriptionPrices({
1239
+ providerSubscriptionId: r.providerSubscriptionId,
1240
+ priceIds: e
1241
+ }), T));
1242
+ }
829
1243
  }
830
- let u = new Set(a.map((e) => e.providerSubscriptionId));
831
- for (let e of yield* N.stores.subscriptions.listByTenant(o)) {
832
- if (!_(e.status) || u.has(e.providerSubscriptionId)) continue;
833
- let n = yield* X(e.providerSubscriptionId);
834
- if (n.providerCustomerId !== t) return yield* y.fail(s("The subscription belongs to another customer."));
835
- yield* G(o, n, r), c.push(Q(o, n, r));
1244
+ let u = new Set(i.map((e) => e.providerSubscriptionId));
1245
+ for (let t of yield* P.stores.subscriptions.listByTenant(a)) {
1246
+ if (!f(t.status) || u.has(t.providerSubscriptionId)) continue;
1247
+ let r = yield* X(t.providerSubscriptionId, l);
1248
+ if (r.providerCustomerId !== e) return yield* C.fail(o("The subscription belongs to another customer."));
1249
+ yield* W(a, r, n), s.push(Q(a, r, n));
836
1250
  }
837
- for (let e of c) yield* q(e);
1251
+ for (let e of s) yield* K(e);
838
1252
  return {
839
- tenantId: o,
840
- events: c
1253
+ tenantId: a,
1254
+ events: s
841
1255
  };
842
- }), Fe = (e) => y.forEach(e, (e) => {
843
- let n = t.onEvent?.[e._tag];
844
- return n === void 0 ? y.void : n(e).pipe(y.catchCause((t) => y.sync(() => {
845
- C.error("billing: onEvent failed for a correction — the next sync of this tenant retries it", {
1256
+ }), Z = (e) => C.forEach(e, (e) => {
1257
+ let t = p.onEvent?.[e._tag];
1258
+ return t === void 0 ? C.void : t(e).pipe(C.catchCause((t) => C.sync(() => {
1259
+ D.error("billing: onEvent failed for a correction — the next sync of this tenant retries it", {
846
1260
  event: e._tag,
847
1261
  cause: String(t)
848
1262
  });
849
1263
  })));
850
- }, { discard: !0 }), Z = (e) => y.gen(function* () {
1264
+ }, { discard: !0 }), lt = (e) => C.gen(function* () {
1265
+ yield* Ke(e);
851
1266
  let t = yield* z(e);
852
1267
  if (t !== null) {
853
- let n = yield* Pe(t.providerCustomerId, e);
854
- yield* Fe(n.events);
1268
+ let n = yield* ct(t.providerCustomerId, e);
1269
+ yield* Z(n.events);
855
1270
  }
856
- return yield* N.stores.subscriptions.getByTenant(e);
857
- }), Ie = (e, t) => e !== void 0 && e.status === t.status && e.plan === (t.plan ?? "free") && e.quantity === t.quantity && (e.cancelAt?.getTime() ?? null) === (t.cancelAt?.getTime() ?? null), Q = (e, t, n) => t.status === "canceled" ? {
1271
+ return yield* P.stores.subscriptions.getByTenant(e);
1272
+ }), ut = (e, t) => e !== void 0 && e.status === t.status && e.plan === (t.plan ?? "free") && e.quantity === t.quantity && (e.cancelAt?.getTime() ?? null) === (t.cancelAt?.getTime() ?? null), Q = (e, t, n) => t.status === "canceled" ? {
858
1273
  _tag: "subscriptionCanceled",
859
1274
  tenantId: e,
860
1275
  providerSubscriptionId: t.providerSubscriptionId,
@@ -870,24 +1285,24 @@ var C = S({ scope: "@voltro/plugin-billing" }), w = 3, T = /* @__PURE__ */ new S
870
1285
  currentPeriodEnd: t.currentPeriodEnd,
871
1286
  cancelAt: t.cancelAt,
872
1287
  occurredAt: n
873
- }, Le = () => y.gen(function* () {
874
- let e = A(), t = yield* O(v.listSubscriptions({}), x), n = yield* N.stores.customers.list(yield* I()), r = new Map(n.map((e) => [e.providerCustomerId, e.tenantId])), i = /* @__PURE__ */ new Set(), a = /* @__PURE__ */ new Map(), o = /* @__PURE__ */ new Set(), s = [], c = /* @__PURE__ */ new Set(), l = /* @__PURE__ */ new Map(), u = 0, d = 0, f = (e) => {
1288
+ }, dt = () => C.gen(function* () {
1289
+ let e = k(), t = yield* M(S.listSubscriptions({}), T), n = yield* P.stores.customers.list(yield* L()), r = new Map(n.map((e) => [e.providerCustomerId, e.tenantId])), i = /* @__PURE__ */ new Set(), a = /* @__PURE__ */ new Map(), o = /* @__PURE__ */ new Set(), s = [], c = /* @__PURE__ */ new Set(), l = /* @__PURE__ */ new Map(), u = 0, d = 0, f = (e) => {
875
1290
  let t = l.get(e);
876
- return t === void 0 ? Ne(e).pipe(y.tap((t) => y.sync(() => {
1291
+ return t === void 0 ? ot(e).pipe(C.tap((t) => C.sync(() => {
877
1292
  l.set(e, t);
878
- }))) : y.succeed(t);
1293
+ }))) : C.succeed(t);
879
1294
  };
880
1295
  for (let n of t) {
881
1296
  o.add(n.providerSubscriptionId);
882
1297
  let t = null;
883
- n.providerCustomerId !== null && (t = yield* N.stores.customers.getByProviderCustomerId(n.providerCustomerId, yield* I()));
1298
+ n.providerCustomerId !== null && (t = yield* P.stores.customers.getByProviderCustomerId(n.providerCustomerId, yield* L()));
884
1299
  let l = t === null ? null : t.tenantId, p = n.providerCustomerId === null ? null : r.get(n.providerCustomerId) ?? null, m = l === null ? p === null ? n.tenantId : p : l;
885
1300
  if (m === null) {
886
- u += 1, C.warn("billing reconcile: provider subscription names no tenant", { subscription: n.providerSubscriptionId });
1301
+ u += 1, D.warn("billing reconcile: provider subscription names no tenant", { subscription: n.providerSubscriptionId });
887
1302
  continue;
888
1303
  }
889
1304
  if (t !== null && t.retiredAt !== null) {
890
- u++, C.warn("billing reconcile: retired customer subscriptions require financial reconciliation", {
1305
+ u++, D.warn("billing reconcile: retired customer subscriptions require financial reconciliation", {
891
1306
  tenant: t.tenantId,
892
1307
  customer: t.providerCustomerId
893
1308
  });
@@ -898,27 +1313,30 @@ var C = S({ scope: "@voltro/plugin-billing" }), w = 3, T = /* @__PURE__ */ new S
898
1313
  tenantId: m,
899
1314
  providerCustomerId: n.providerCustomerId,
900
1315
  occurredAt: e
901
- }), i.add(m)), T.has(n.status) && n.cancelAt === null && !c.has(m) && (yield* f(m))) {
902
- C.error("billing reconcile: a closed tenant still has a paying subscription — closing it", {
1316
+ }), i.add(m)), O.has(n.status) && n.cancelAt === null && !c.has(m) && (yield* f(m))) {
1317
+ D.error("billing reconcile: a closed tenant still has a paying subscription — closing it", {
903
1318
  tenant: m,
904
1319
  subscription: n.providerSubscriptionId
905
- }), (yield* Y(m).pipe(y.map(() => !0), y.catch((e) => y.sync(() => (C.error("billing reconcile: closing a closed tenant failed — retried next run", {
1320
+ }), (yield* rt(m).pipe(C.map(() => !0), C.catchTag("BillingClosurePending", (e) => C.sync(() => (D.info("billing reconcile: closing a closed tenant is pending provider settlement", {
1321
+ tenant: m,
1322
+ reason: e.reason
1323
+ }), !1))), C.catch((e) => C.sync(() => (D.error("billing reconcile: closing a closed tenant failed — retried next run", {
906
1324
  tenant: m,
907
1325
  message: e.message
908
1326
  }), !1))))) && c.add(m), i.add(m);
909
1327
  continue;
910
1328
  }
911
1329
  if (c.has(m)) continue;
912
- T.has(n.status) && a.set(m, (a.get(m) ?? 0) + 1);
913
- let h = yield* N.stores.subscriptions.listByTenant(m);
914
- Ie(h.find((e) => e.providerSubscriptionId === n.providerSubscriptionId), n) || (yield* G(m, n, e), s.push(Q(m, n, e)), i.add(m));
1330
+ O.has(n.status) && a.set(m, (a.get(m) ?? 0) + 1);
1331
+ let h = yield* P.stores.subscriptions.listByTenant(m);
1332
+ ut(h.find((e) => e.providerSubscriptionId === n.providerSubscriptionId), n) || (yield* W(m, n, e), s.push(Q(m, n, e)), i.add(m));
915
1333
  let g = n.plan;
916
- if (g !== null && T.has(n.status)) {
917
- let e = b.meteredPriceIdsFor(g).filter((e) => !n.priceIds.includes(e));
918
- e.length > 0 && (yield* O(v.addSubscriptionPrices({
1334
+ if (g !== null && O.has(n.status)) {
1335
+ let e = w.meteredPriceIdsFor(g).filter((e) => !n.priceIds.includes(e));
1336
+ e.length > 0 && (yield* M(S.addSubscriptionPrices({
919
1337
  providerSubscriptionId: n.providerSubscriptionId,
920
1338
  priceIds: e
921
- }), x), d += 1);
1339
+ }), T), d += 1);
922
1340
  }
923
1341
  }
924
1342
  let p = 0, m = [];
@@ -927,12 +1345,12 @@ var C = S({ scope: "@voltro/plugin-billing" }), w = 3, T = /* @__PURE__ */ new S
927
1345
  "trialing",
928
1346
  "pastDue",
929
1347
  "incomplete"
930
- ]) m.push(...yield* N.stores.subscriptions.listByStatus(e));
1348
+ ]) m.push(...yield* P.stores.subscriptions.listByStatus(e));
931
1349
  let h = [];
932
1350
  for (let t of m) {
933
1351
  if (o.has(t.providerSubscriptionId)) continue;
934
1352
  p += 1;
935
- let n = yield* O(v.fetchSubscription(t.providerSubscriptionId), x);
1353
+ let n = yield* M(S.fetchSubscription(t.providerSubscriptionId), T);
936
1354
  if (n === null) {
937
1355
  h.push(t);
938
1356
  continue;
@@ -941,22 +1359,22 @@ var C = S({ scope: "@voltro/plugin-billing" }), w = 3, T = /* @__PURE__ */ new S
941
1359
  ...n,
942
1360
  providerSubscriptionId: t.providerSubscriptionId
943
1361
  };
944
- yield* G(t.tenantId, r, e), s.push(Q(t.tenantId, r, e)), i.add(t.tenantId);
1362
+ yield* W(t.tenantId, r, e), s.push(Q(t.tenantId, r, e)), i.add(t.tenantId);
945
1363
  }
946
- let g = h.length >= w && h.length * 2 >= m.length;
947
- if (g) C.error("billing reconcile: the provider knows none of these live subscriptions — wrong account or provider? Nothing was canceled", {
1364
+ let g = h.length >= re && h.length * 2 >= m.length;
1365
+ if (g) D.error("billing reconcile: the provider knows none of these live subscriptions — wrong account or provider? Nothing was canceled", {
948
1366
  unknown: h.length,
949
1367
  live: m.length,
950
- provider: v.name
1368
+ provider: S.name
951
1369
  });
952
- else for (let t of h) yield* N.stores.subscriptions.markCanceled(t.providerSubscriptionId), s.push(Q(t.tenantId, {
1370
+ else for (let t of h) yield* P.stores.subscriptions.markCanceled(t.providerSubscriptionId), s.push(Q(t.tenantId, {
953
1371
  ...t,
954
1372
  status: "canceled",
955
1373
  providerSubscriptionId: t.providerSubscriptionId
956
1374
  }, e)), i.add(t.tenantId);
957
1375
  let _ = [...a].filter(([, e]) => e > 1).map(([e]) => e);
958
- for (let e of _) C.error("billing reconcile: tenant has more than one paying subscription — billed twice, resolve by hand", { tenant: e });
959
- let S = {
1376
+ for (let e of _) D.error("billing reconcile: tenant has more than one paying subscription — billed twice, resolve by hand", { tenant: e });
1377
+ let v = {
960
1378
  checked: t.length + p,
961
1379
  corrected: [...i],
962
1380
  duplicates: _,
@@ -966,150 +1384,218 @@ var C = S({ scope: "@voltro/plugin-billing" }), w = 3, T = /* @__PURE__ */ new S
966
1384
  refusedUnknown: g ? h.length : 0,
967
1385
  events: s
968
1386
  };
969
- return C.info("billing reconcile from provider", {
970
- checked: S.checked,
971
- corrected: S.corrected.length,
1387
+ return D.info("billing reconcile from provider", {
1388
+ checked: v.checked,
1389
+ corrected: v.corrected.length,
972
1390
  duplicates: _.length,
973
1391
  unattributed: u,
974
1392
  meteredItemsRestored: d,
975
- closedTenants: S.closedTenants.length
976
- }), yield* Fe(s), S;
977
- }), Re = (e, t) => xe(e, { quantity: t }), $ = (e, t, n) => y.gen(function* () {
1393
+ closedTenants: v.closedTenants.length
1394
+ }), yield* Z(s), v;
1395
+ }), ft = (e, t, n, r = () => C.void, i) => Ye(e, { quantity: t }, r, i), pt = (e, t, n) => C.gen(function* () {
978
1396
  if (![
979
1397
  e,
980
1398
  t,
981
1399
  n
982
- ].every((e) => typeof e == "string" && e.length > 0 && e.length <= 191 && e.trim() === e && e.isWellFormed())) return yield* y.fail(u("Exact owned invoice reference identities are required."));
983
- let r = N.stores, i = yield* I(), a = yield* r.customers.getByProviderCustomerId(t, i);
984
- if (a === null || a.tenantId !== e || a.provider !== v.name) return yield* y.fail(u("Positive current or retained customer custody is required."));
985
- let o = yield* r.historyWork.claim(a, n, A());
1400
+ ].every((e) => typeof e == "string" && e.length > 0 && e.length <= 191 && e.trim() === e && e.isWellFormed())) return yield* C.fail(d("Exact owned invoice reference identities are required."));
1401
+ let r = P.stores, i = yield* L(), a = yield* r.customers.getByProviderCustomerId(t, i);
1402
+ if (a === null || a.tenantId !== e || a.provider !== S.name) return yield* C.fail(d("Positive current or retained customer custody is required."));
1403
+ let o = yield* r.historyWork.claim(a, n, k());
986
1404
  if (o.kind !== "claimed") return {
987
1405
  kind: o.kind,
988
1406
  work: o.work
989
1407
  };
990
- let s = o.attempt, c = r.historyWork.hold(s, () => A().getTime());
991
- return yield* y.gen(function* () {
992
- if (N.stores !== r) return yield* y.fail(u("Billing stores changed before invoice reference dispatch.", !0));
993
- let n = yield* J(e, o.work.providerInvoiceId, t).pipe(y.timeout("5 minutes"));
994
- if (N.stores !== r) return yield* y.fail(u("Billing stores changed during invoice reference observation.", !0));
995
- let i = yield* r.historyWork.observed(a, s, n, A());
996
- return i === null || i.state !== "observed" && i.state !== "deferred" ? yield* y.fail(u("Invoice reference acknowledgement no longer owns its attempt.", !0)) : {
1408
+ let s = o.attempt, c = r.historyWork.hold(s, () => k().getTime());
1409
+ return yield* C.gen(function* () {
1410
+ if (P.stores !== r) return yield* C.fail(d("Billing stores changed before invoice reference dispatch.", !0));
1411
+ let n = yield* Y(e, o.work.providerInvoiceId, t).pipe(C.timeout("5 minutes"));
1412
+ if (P.stores !== r) return yield* C.fail(d("Billing stores changed during invoice reference observation.", !0));
1413
+ let i = yield* r.historyWork.observed(a, s, n, k());
1414
+ return i === null || i.state !== "observed" && i.state !== "deferred" ? yield* C.fail(d("Invoice reference acknowledgement no longer owns its attempt.", !0)) : {
997
1415
  kind: i.state === "observed" ? "observed" : "deferred",
998
1416
  work: i
999
1417
  };
1000
- }).pipe(y.catch(() => y.gen(function* () {
1001
- return yield* r.historyWork.failed(a, s, A()), yield* y.fail(u("The invoice reference remains unconfirmed and retryable.", !0));
1002
- })), y.ensuring(y.sync(c)));
1003
- });
1004
- return {
1005
- service: {
1006
- subscription: oe,
1007
- plan: ae,
1008
- entitlementStatus: ie,
1009
- reconcileDunning: K,
1010
- dunningSweep: ve,
1011
- checkEntitlement: ce,
1012
- consumeEntitlement: le,
1013
- reportUsage: ue,
1014
- reportUsageEvent: de,
1015
- flushUsage: fe,
1016
- startCheckout: pe,
1017
- portalUrl: me,
1018
- applyEvent: be,
1019
- changePlan: De,
1020
- changeSeats: Re,
1021
- previewChange: Se,
1022
- invoices: Ce,
1023
- invoiceSnapshot: Ee,
1024
- invoiceHistory: Te,
1025
- reconcileInvoice: J,
1026
- processInvoiceHistoryReference: $,
1027
- reconcileInvoiceHistory: () => y.gen(function* () {
1028
- let e = N.stores, t = () => N.stores === e ? y.void : y.fail(u("Billing stores changed during the invoice-history pass.", !0));
1029
- if (v.listInvoiceHistory === void 0 || v.fetchInvoiceSnapshot === void 0) return yield* y.fail(u("Complete account-owned invoice history and observations are required."));
1030
- let n = yield* I(), r = yield* e.historyProgress.account(n, A());
1418
+ }).pipe(C.catch(() => C.gen(function* () {
1419
+ return yield* r.historyWork.failed(a, s, k()), yield* C.fail(d("The invoice reference remains unconfirmed and retryable.", !0));
1420
+ })), C.ensuring(C.sync(c)));
1421
+ }), mt = () => C.gen(function* () {
1422
+ let e = P.stores, t = () => P.stores === e ? C.void : C.fail(d("Billing stores changed during the invoice-history pass.", !0));
1423
+ if (S.listInvoiceHistory === void 0 || S.fetchInvoiceSnapshot === void 0) return yield* C.fail(d("Complete account-owned invoice history and observations are required."));
1424
+ let n = yield* L(), r = yield* e.historyProgress.account(n, k());
1425
+ yield* t();
1426
+ let i = yield* e.customers.inventory(n, {
1427
+ ...r.afterCustodyId === null ? {} : { afterCustodyId: r.afterCustodyId },
1428
+ limit: 1
1429
+ }), a = r.cycleEndCustodyId, o = i.customers.find((e) => a === null || e.id <= a);
1430
+ if (o === void 0) return yield* t(), {
1431
+ kind: (r.afterCustodyId === null ? r : yield* e.historyProgress.advanceAccount(r, null, k())) === null ? "contended" : "idle",
1432
+ customerCustodyId: null,
1433
+ admittedPages: 0,
1434
+ observed: 0,
1435
+ deferred: 0,
1436
+ busy: 0,
1437
+ unconfirmed: 0
1438
+ };
1439
+ let s = yield* C.gen(function* () {
1440
+ yield* t();
1441
+ let n = yield* st(o, !0);
1442
+ (yield* e.closures.getAccount(o.tenantId)) === null && (yield* Z(n)), yield* t();
1443
+ let r = yield* e.historyProgress.customer(o, k()), i = yield* e.historyJournal.begin(o), a = 0, s = i.headCheckedAt?.getTime() ?? null, c = k().getTime();
1444
+ if (i.exhausted && (s === null || c - s >= A || s - c > A)) {
1031
1445
  yield* t();
1032
- let i = yield* e.customers.inventory(n, {
1033
- ...r.afterCustodyId === null ? {} : { afterCustodyId: r.afterCustodyId },
1034
- limit: 1
1035
- }), a = i.customers[0];
1036
- if (a === void 0) return yield* t(), {
1037
- kind: (r.afterCustodyId === null ? r : yield* e.historyProgress.advanceAccount(r, null, A())) === null ? "contended" : "idle",
1038
- customerCustodyId: null,
1039
- admittedPages: 0,
1040
- observed: 0,
1041
- deferred: 0,
1042
- busy: 0,
1043
- unconfirmed: 0
1044
- };
1045
- let o = yield* y.gen(function* () {
1446
+ let n = yield* J(o.tenantId, o.providerCustomerId, { limit: 100 });
1447
+ yield* t();
1448
+ let r = yield* e.historyJournal.scanHead(i, n);
1449
+ r === null ? i = yield* e.historyJournal.begin(o) : (r.pageOrdinal > i.pageOrdinal && (a = 1), i = r);
1450
+ } else if (!i.exhausted) {
1451
+ yield* t();
1452
+ let n = yield* J(o.tenantId, o.providerCustomerId, {
1453
+ limit: 100,
1454
+ ...i.cursor === null ? {} : { cursor: i.cursor }
1455
+ });
1456
+ yield* t();
1457
+ let r = yield* e.historyJournal.commitPage(i, n);
1458
+ r === null ? i = yield* e.historyJournal.begin(o) : (i = r, a = 1);
1459
+ }
1460
+ let l = { ...r.cursors }, u = 0, d = 0, f = 0, p = 0;
1461
+ for (let n of [
1462
+ "observed",
1463
+ "unprepared",
1464
+ "ready",
1465
+ "working"
1466
+ ]) {
1467
+ yield* t();
1468
+ let a = r.walkId === i.id ? l[n] : null, s = yield* e.historyWork.pending(o, n, k(), {
1469
+ limit: 1,
1470
+ ...a === null ? {} : { cursor: {
1471
+ lane: n,
1472
+ walkId: i.id,
1473
+ afterId: a
1474
+ } }
1475
+ });
1476
+ for (let e of s.entries) {
1046
1477
  yield* t();
1047
- let n = yield* e.historyProgress.customer(a, A()), r = yield* e.historyJournal.begin(a), i = 0;
1048
- if (!r.exhausted) {
1049
- yield* t();
1050
- let n = yield* Te(a.tenantId, a.providerCustomerId, {
1051
- limit: 100,
1052
- ...r.cursor === null ? {} : { cursor: r.cursor }
1053
- });
1054
- yield* t();
1055
- let o = yield* e.historyJournal.commitPage(r, n);
1056
- o === null ? r = yield* e.historyJournal.begin(a) : (r = o, i = 1);
1057
- }
1058
- let o = { ...n.cursors }, s = 0, c = 0, l = 0, u = 0;
1059
- for (let i of [
1060
- "unprepared",
1061
- "ready",
1062
- "working"
1063
- ]) {
1064
- yield* t();
1065
- let d = n.walkId === r.id ? o[i] : null, f = yield* e.historyWork.pending(a, i, A(), {
1066
- limit: 1,
1067
- ...d === null ? {} : { cursor: {
1068
- lane: i,
1069
- walkId: r.id,
1070
- afterId: d
1071
- } }
1478
+ let n = yield* pt(o.tenantId, o.providerCustomerId, e.reference.id).pipe(C.catch(() => C.succeed(null)));
1479
+ n === null ? p++ : n.kind === "observed" ? u++ : n.kind === "deferred" ? d++ : f++;
1480
+ }
1481
+ l[n] = s.nextCursor?.afterId ?? null;
1482
+ }
1483
+ yield* t();
1484
+ let m = yield* e.historyProgress.advanceCustomer(r, {
1485
+ walkId: i.id,
1486
+ cursors: l
1487
+ }, k());
1488
+ return {
1489
+ admittedPages: a,
1490
+ observed: u,
1491
+ deferred: d,
1492
+ busy: f + +(m === null),
1493
+ unconfirmed: p
1494
+ };
1495
+ }).pipe(C.catch(() => C.succeed({
1496
+ admittedPages: 0,
1497
+ observed: 0,
1498
+ deferred: 0,
1499
+ busy: 0,
1500
+ unconfirmed: 1
1501
+ })));
1502
+ yield* t();
1503
+ let c = i.nextCustodyId === null || a !== null && o.id >= a;
1504
+ return {
1505
+ kind: (yield* e.historyProgress.advanceAccount(r, c ? null : i.nextCustodyId, k())) === null ? "contended" : "advanced",
1506
+ customerCustodyId: o.id,
1507
+ ...s
1508
+ };
1509
+ }).pipe(C.timeout("2 minutes"), C.mapError((e) => e instanceof x ? e : d("The bounded invoice-history pass timed out and remains retryable.", !0))), ht = (e, t) => C.gen(function* () {
1510
+ let n = P.stores;
1511
+ yield* R(e);
1512
+ let r = yield* n.subscriptionWrites.getRequest(e, t), i = yield* L();
1513
+ return P.stores !== n || r !== null && (r.intent.provider !== S.name || r.intent.providerAccountId !== i.account.providerAccountId || r.intent.livemode !== i.account.livemode) ? yield* C.fail(o("Original billing operation custody requires reconciliation.")) : { phase: r?.phase ?? "not-found" };
1514
+ }), gt = (e) => C.gen(function* () {
1515
+ let t = P.stores;
1516
+ yield* R(e);
1517
+ let n = yield* t.subscriptionWrites.getActive(e), r = yield* L();
1518
+ if (P.stores !== t || n !== null && (n.intent.provider !== S.name || n.intent.providerAccountId !== r.account.providerAccountId || n.intent.livemode !== r.account.livemode)) return yield* C.fail(o("Original billing operation custody requires reconciliation."));
1519
+ if (n === null) return null;
1520
+ let i = n.phase;
1521
+ return i !== "prepared" && i !== "claimed" && i !== "dispatched" && i !== "acknowledged" ? null : {
1522
+ requestId: n.requestId,
1523
+ kind: n.intent.kind,
1524
+ plan: n.intent.plan,
1525
+ quantity: n.intent.quantity,
1526
+ phase: i
1527
+ };
1528
+ }), _t = /* @__PURE__ */ new Map(), $ = /* @__PURE__ */ new Map();
1529
+ return {
1530
+ service: {
1531
+ prices: (e) => C.gen(function* () {
1532
+ let t = S.fetchPrices;
1533
+ if (t === void 0) return yield* C.fail(new x({
1534
+ source: "billing",
1535
+ message: `Billing provider "${S.name}" cannot read prices.`,
1536
+ transient: !1
1537
+ }));
1538
+ let n = Date.now(), r = [...new Set(e)], i = r.filter((e) => {
1539
+ let t = _t.get(e);
1540
+ return t === void 0 || n - t.at > 6e4;
1541
+ }), a = i.filter((e) => !$.has(e)), o = [];
1542
+ if (a.length > 0) {
1543
+ let e = { fiber: null };
1544
+ for (let t of a) $.set(t, e);
1545
+ let r = yield* C.forkDetach(t(a).pipe(C.tap((e) => C.sync(() => {
1546
+ for (let t of a) _t.set(t, {
1547
+ at: n,
1548
+ price: e.find((e) => e.id === t) ?? null
1072
1549
  });
1073
- for (let e of f.entries) {
1074
- yield* t();
1075
- let n = yield* $(a.tenantId, a.providerCustomerId, e.reference.id).pipe(y.catch(() => y.succeed(null)));
1076
- n === null ? u++ : n.kind === "observed" ? s++ : n.kind === "deferred" ? c++ : l++;
1077
- }
1078
- o[i] = f.nextCursor?.afterId ?? null;
1079
- }
1080
- yield* t();
1081
- let d = yield* e.historyProgress.advanceCustomer(n, {
1082
- walkId: r.id,
1083
- cursors: o
1084
- }, A());
1085
- return {
1086
- admittedPages: i,
1087
- observed: s,
1088
- deferred: c,
1089
- busy: l + +(d === null),
1090
- unconfirmed: u
1091
- };
1092
- }).pipe(y.catch(() => y.succeed({
1093
- admittedPages: 0,
1094
- observed: 0,
1095
- deferred: 0,
1096
- busy: 0,
1097
- unconfirmed: 1
1098
- })));
1099
- return yield* t(), {
1100
- kind: (yield* e.historyProgress.advanceAccount(r, i.nextCustodyId, A())) === null ? "contended" : "advanced",
1101
- customerCustodyId: a.id,
1102
- ...o
1103
- };
1104
- }).pipe(y.timeout("2 minutes"), y.mapError((t) => t instanceof e ? t : u("The bounded invoice-history pass timed out and remains retryable.", !0))),
1105
- cancelSubscription: Ae,
1106
- resumeSubscription: je,
1107
- closeAccount: Y,
1108
- reconcileFromProvider: Le,
1109
- syncCustomer: Pe,
1110
- syncTenant: Z
1550
+ })), C.asVoid, C.ensuring(C.sync(() => {
1551
+ for (let t of a) $.get(t) === e && $.delete(t);
1552
+ }))));
1553
+ e.fiber = r, o.push(r);
1554
+ }
1555
+ for (let e of i) {
1556
+ let t = $.get(e)?.fiber;
1557
+ t != null && !o.includes(t) && o.push(t);
1558
+ }
1559
+ return yield* C.forEach(o, (e) => ne.join(e), { discard: !0 }), r.flatMap((e) => {
1560
+ let t = _t.get(e)?.price;
1561
+ return t ? [t] : [];
1562
+ });
1563
+ }),
1564
+ subscription: ge,
1565
+ subscriptionWriteStatus: ht,
1566
+ pendingSubscriptionWrite: gt,
1567
+ recoverSubscriptionWrites: qe,
1568
+ plan: he,
1569
+ entitlementStatus: me,
1570
+ reconcileDunning: G,
1571
+ dunningSweep: Be,
1572
+ checkEntitlement: ve,
1573
+ consumeEntitlement: ye,
1574
+ reportUsage: be,
1575
+ reportUsageEvent: xe,
1576
+ invoiceHistoricalUsage: Ce,
1577
+ flushUsage: Ne,
1578
+ startCheckout: Pe,
1579
+ portalUrl: Fe,
1580
+ applyEvent: Ue,
1581
+ changePlan: et,
1582
+ changeSeats: ft,
1583
+ previewChange: Xe,
1584
+ invoices: Ze,
1585
+ invoiceSnapshot: $e,
1586
+ invoiceHistory: J,
1587
+ reconcileInvoice: Y,
1588
+ reconcilePaymentCorrection: He,
1589
+ processInvoiceHistoryReference: pt,
1590
+ reconcileInvoiceHistory: mt,
1591
+ cancelSubscription: tt,
1592
+ resumeSubscription: nt,
1593
+ closeAccount: rt,
1594
+ reconcileFromProvider: dt,
1595
+ syncCustomer: ct,
1596
+ syncTenant: lt
1111
1597
  },
1112
- holder: N
1598
+ holder: P
1113
1599
  };
1114
- }, j = (e) => b.succeed(t, e);
1115
- export { k as USAGE_KEY, te as USAGE_KEY_RULE, j as billingServiceLayer, A as buildBillingService, ee as makeStoreHolder, D as periodKey };
1600
+ }, ue = (e) => w.succeed(S, e);
1601
+ export { k as PRICE_CACHE_TTL_MS, ce as USAGE_KEY, le as USAGE_KEY_RULE, ue as billingServiceLayer, N as buildBillingService, se as makeStoreHolder, j as periodKey };