@voltro/plugin-billing 0.89.1 → 0.90.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +1835 -0
- package/README.md +0 -435
- package/dist/catalog.js +175 -76
- package/dist/custodyInventory.js +101 -65
- package/dist/dunning.js +14 -6
- package/dist/eventDelivery.js +14 -5
- package/dist/historicalUsage.js +94 -0
- package/dist/index.d.ts +773 -67
- package/dist/index.js +340 -219
- package/dist/invoiceHistoryJournal.js +115 -90
- package/dist/invoiceHistoryProgress.js +49 -25
- package/dist/invoiceHistoryWork.js +162 -160
- package/dist/invoicePaymentEpoch.js +145 -0
- package/dist/invoicePaymentObservation.js +64 -0
- package/dist/invoiceSnapshot.js +52 -42
- package/dist/invoiceStore.js +122 -88
- package/dist/paidInvoiceCoverage.js +84 -0
- package/dist/plans.js +15 -2
- package/dist/providers.js +124 -67
- package/dist/provision.js +84 -73
- package/dist/rpc.d.ts +53 -13
- package/dist/rpc.js +141 -78
- package/dist/service.js +1159 -673
- package/dist/stores.js +231 -139
- package/dist/stripeInvoicePayments.js +129 -0
- package/dist/stripeInvoiceSnapshot.js +59 -40
- package/dist/stripeProvider.js +542 -173
- package/dist/subscriptionObservation.js +93 -0
- package/dist/subscriptionWriteStore.js +325 -0
- package/dist/table.js +75 -66
- package/dist/types.d.ts +415 -27
- package/dist/types.js +21 -4
- package/dist/web/index.d.ts +93 -3
- package/dist/web/index.js +76 -33
- package/dist/web/writeRequest.js +65 -0
- package/package.json +8 -8
package/dist/service.js
CHANGED
|
@@ -1,213 +1,335 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import { assertInvoiceSnapshot as
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
1
|
+
import { BillingClosurePending as e, BillingError as t, BillingService as n, EntitlementExceeded as r } from "./types.js";
|
|
2
|
+
import { billingRequestStale as i } from "./subscriptionWriteStore.js";
|
|
3
|
+
import { DUNNING_LOCK_STEP_ID as a, defaultDunningEmail as o, dueSteps as s, episodeKeyOf as c, evaluateBillingEntitlement as l, resolveDunningConfig as u } from "./dunning.js";
|
|
4
|
+
import { assertInvoiceSnapshot as d, invoiceSnapshotError as f } from "./invoiceSnapshot.js";
|
|
5
|
+
import { captureProviderAccount as p, sameProviderAccount as m } from "./providerIdentity.js";
|
|
6
|
+
import { captureInvoiceHistoryInput as h, captureInvoiceHistoryPage as g, historyError as _ } from "./invoiceHistory.js";
|
|
7
|
+
import { captureSubscriptionObservation as v, observeSubscriptionProvider as y, subscriptionReadbackHolds as b } from "./subscriptionObservation.js";
|
|
8
|
+
import { evaluateEntitlement as ee } from "./entitlement.js";
|
|
9
|
+
import { isLive as x, memoryStores as S } from "./stores.js";
|
|
10
|
+
import { makeHistoricalUsageInvoicer as te } from "./historicalUsage.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
|
|
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
|
-
]),
|
|
16
|
-
schedule:
|
|
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 ?? S() }), M = (e, t) => e.pipe(C.retry({
|
|
22
|
+
schedule: T.recurs(Math.max(0, t - 1)),
|
|
17
23
|
while: (e) => e.transient
|
|
18
|
-
})),
|
|
19
|
-
let { provider:
|
|
20
|
-
|
|
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 = (n) => {
|
|
25
|
+
let { provider: S, plans: w } = n, T = n.attempts ?? 3, E = n.checkout, k = n.now ?? (() => /* @__PURE__ */ new Date()), A = n.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, r, i) => C.gen(function* () {
|
|
28
|
+
if (e.length === 0) return yield* C.fail(new t({
|
|
21
29
|
source: "billing",
|
|
22
30
|
message: "no tenant on this call",
|
|
23
31
|
transient: !1
|
|
24
32
|
}));
|
|
25
|
-
if (r !== "cancel" && (yield*
|
|
33
|
+
if (r !== "cancel" && (yield* P.stores.closures.getAccount(e)) !== null) return yield* C.fail(new t({
|
|
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 (
|
|
31
|
-
let
|
|
32
|
-
if (
|
|
38
|
+
if (r !== "cancel" && (yield* P.stores.subscriptionWrites.assertOpen(e)), n.admit !== void 0 && (yield* n.admit(e, r)), yield* R(e), i !== void 0) {
|
|
39
|
+
let t = yield* P.stores.customers.getByTenant(e);
|
|
40
|
+
if (t === null || t.providerCustomerId !== i) return yield* C.fail(f("Checkout customer custody changed before dispatch or private URL replay."));
|
|
33
41
|
}
|
|
34
|
-
}),
|
|
35
|
-
let r = (
|
|
42
|
+
}), ue = n.redirectOrigins?.map((e) => new URL(e).origin), de = (e, n) => {
|
|
43
|
+
let r = (e) => C.fail(new t({
|
|
36
44
|
source: "billing",
|
|
37
|
-
message: `${n} ${
|
|
45
|
+
message: `${n} ${e}`,
|
|
38
46
|
transient: !1
|
|
39
47
|
})), i;
|
|
40
48
|
try {
|
|
41
|
-
i = new URL(
|
|
49
|
+
i = new URL(e);
|
|
42
50
|
} catch {
|
|
43
51
|
return r("is not an absolute URL");
|
|
44
52
|
}
|
|
45
|
-
return i.protocol !== "https:" && i.protocol !== "http:" ? r("must be an http(s) URL") :
|
|
46
|
-
},
|
|
47
|
-
if (
|
|
48
|
-
let e =
|
|
49
|
-
return e === void 0 ?
|
|
53
|
+
return i.protocol !== "https:" && i.protocol !== "http:" ? r("must be an http(s) URL") : ue !== void 0 && !ue.includes(i.origin) ? r(`must point at one of the configured redirect origins, not ${i.origin}`) : C.void;
|
|
54
|
+
}, P = se(n.stores), F = n.dunning ?? u(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(f("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:
|
|
53
|
-
account:
|
|
60
|
+
provider: S.name,
|
|
61
|
+
account: p(e)
|
|
54
62
|
});
|
|
55
|
-
if (
|
|
56
|
-
return
|
|
63
|
+
if (I !== void 0 && !m(I.account, t.account)) throw f("The provider account changed during observation.");
|
|
64
|
+
return I ??= t, I;
|
|
57
65
|
},
|
|
58
|
-
catch: () =>
|
|
66
|
+
catch: () => f("A fixed provider account/mode is required.")
|
|
59
67
|
})));
|
|
60
|
-
},
|
|
61
|
-
let n = yield*
|
|
62
|
-
if (r === void 0) return yield*
|
|
63
|
-
if ((yield*
|
|
64
|
-
let i = yield*
|
|
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(f("Positive provider customer evidence is required."));
|
|
71
|
+
if ((yield* P.stores.customers.getByTenant(e)) === null && (yield* P.stores.subscriptions.listByTenant(e)).some((e) => x(e.status))) return yield* C.fail(f("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
|
-
}),
|
|
68
|
-
return yield*
|
|
75
|
+
}), T);
|
|
76
|
+
return yield* P.stores.customers.bind({
|
|
69
77
|
...n,
|
|
70
78
|
tenantId: e,
|
|
71
79
|
providerCustomerId: t
|
|
72
80
|
}, i);
|
|
73
|
-
}),
|
|
74
|
-
if (
|
|
75
|
-
let r = yield*
|
|
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(f("The retained subscription has no qualified billing account.")) : C.succeed(l(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 (n.resolveEntitlementLimit !== void 0) {
|
|
83
|
+
let r = yield* n.resolveEntitlementLimit(e, t);
|
|
76
84
|
if (r !== null) return r;
|
|
77
85
|
}
|
|
78
|
-
let r = yield*
|
|
79
|
-
return
|
|
80
|
-
}),
|
|
81
|
-
let r = yield*
|
|
82
|
-
return
|
|
83
|
-
}),
|
|
84
|
-
let i = yield*
|
|
85
|
-
if (!Number.isFinite(i) ||
|
|
86
|
-
let a =
|
|
87
|
-
yield*
|
|
88
|
-
let o = yield*
|
|
89
|
-
if (!o.allowed) return yield*
|
|
86
|
+
let r = yield* he(e);
|
|
87
|
+
return w.entitlementLimit(r, t);
|
|
88
|
+
}), ve = (e, t, n) => C.gen(function* () {
|
|
89
|
+
let r = yield* _e(e, t), i = yield* P.stores.usage.used(e, t, j(k()));
|
|
90
|
+
return ee(t, r, i, n);
|
|
91
|
+
}), ye = (e, t, n) => C.gen(function* () {
|
|
92
|
+
let i = yield* _e(e, t);
|
|
93
|
+
if (!Number.isFinite(i) || n <= 0) return;
|
|
94
|
+
let a = j(k());
|
|
95
|
+
yield* pe(e);
|
|
96
|
+
let o = yield* P.stores.usage.consume(e, t, a, n, i);
|
|
97
|
+
if (!o.allowed) return yield* C.fail(new r({
|
|
90
98
|
entitlement: t,
|
|
91
99
|
limit: o.limit,
|
|
92
100
|
used: o.used,
|
|
93
|
-
cost:
|
|
101
|
+
cost: n
|
|
94
102
|
}));
|
|
95
|
-
}),
|
|
103
|
+
}), be = (e, n, r) => ce.test(n) ? Number.isFinite(r) ? r <= 0 ? C.void : pe(e).pipe(C.andThen(P.stores.usage.increment(e, n, j(k()), r)), C.asVoid) : C.fail(new t({
|
|
96
104
|
source: "billing",
|
|
97
105
|
message: `usage quantity must be a finite number, got ${r}`,
|
|
98
106
|
transient: !1
|
|
99
|
-
})) :
|
|
107
|
+
})) : C.fail(new t({
|
|
100
108
|
source: "billing",
|
|
101
|
-
message:
|
|
109
|
+
message: le,
|
|
102
110
|
transient: !1
|
|
103
|
-
})),
|
|
104
|
-
if (!
|
|
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 t({
|
|
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 (
|
|
117
|
+
if (e.occurredAt.getTime() > k().getTime()) return yield* C.fail(new t({
|
|
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(
|
|
115
|
-
if ((yield*
|
|
116
|
-
yield*
|
|
117
|
-
...
|
|
122
|
+
let n = new Date(e.occurredAt);
|
|
123
|
+
if ((yield* P.stores.customers.accountForTenant(e.tenantId)) === null) return yield* C.fail(f("Usage occurrence requires its already recorded original billing account."));
|
|
124
|
+
yield* P.stores.usage.recordEvent({
|
|
125
|
+
...e,
|
|
118
126
|
occurredAt: n,
|
|
119
|
-
period:
|
|
127
|
+
period: j(n)
|
|
120
128
|
});
|
|
121
|
-
}), V = () => new
|
|
129
|
+
}), V = () => new t({
|
|
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
|
-
}),
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
133
|
+
}), Se = (e) => P.stores.closures.getAccount(e).pipe(C.map((e) => e?.usageSealed === 1)), Ce = te({
|
|
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 && x(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 t({
|
|
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, n, r) => C.gen(function* () {
|
|
157
|
+
if (n + 1 >= 8) return yield* C.fail(new t({
|
|
158
|
+
source: "billing",
|
|
159
|
+
message: "Usage flush lost its dispatch claim repeatedly to concurrent flushes. Retry the flush.",
|
|
160
|
+
transient: !0
|
|
161
|
+
}));
|
|
162
|
+
let i = (yield* P.stores.usage.pending()).find((t) => t.tenantId === e.tenantId && t.entitlementKey === e.entitlementKey && t.period === e.period);
|
|
163
|
+
i !== void 0 && (yield* r(i, n + 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 n = yield* P.stores.usage.pending(), r = ke();
|
|
224
|
+
for (let i of n) {
|
|
225
|
+
if (e !== void 0 && i.tenantId !== e) continue;
|
|
226
|
+
let n = i.used - i.reportedToProvider;
|
|
131
227
|
if (n <= 0) continue;
|
|
132
|
-
if (
|
|
133
|
-
if (
|
|
134
|
-
|
|
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
|
-
}));
|
|
228
|
+
if (yield* Se(i.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: i.tenantId }));
|
|
142
231
|
continue;
|
|
143
232
|
}
|
|
144
|
-
if (
|
|
145
|
-
if (
|
|
146
|
-
|
|
233
|
+
if (i.period !== j(k())) {
|
|
234
|
+
if (e !== void 0) {
|
|
235
|
+
yield* je(i, r);
|
|
236
|
+
continue;
|
|
237
|
+
}
|
|
238
|
+
yield* je(i, r).pipe(C.catch((e) => C.logWarning("billing usage of a closed month retained").pipe(C.annotateLogs({
|
|
239
|
+
tenantId: i.tenantId,
|
|
240
|
+
key: i.entitlementKey,
|
|
241
|
+
period: i.period,
|
|
242
|
+
reason: e.message
|
|
243
|
+
}))));
|
|
147
244
|
continue;
|
|
148
245
|
}
|
|
149
|
-
let
|
|
150
|
-
if (
|
|
151
|
-
if (
|
|
246
|
+
let a = yield* P.stores.customers.getByTenant(i.tenantId);
|
|
247
|
+
if (a === null && S.usageRequiresCustomer === !0) {
|
|
248
|
+
if (e !== void 0) return yield* C.fail(new t({
|
|
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*
|
|
157
|
-
tenantId:
|
|
158
|
-
key:
|
|
253
|
+
yield* C.logWarning("billing usage not flushed: no provider customer linked").pipe(C.annotateLogs({
|
|
254
|
+
tenantId: i.tenantId,
|
|
255
|
+
key: i.entitlementKey,
|
|
159
256
|
pending: n
|
|
160
257
|
}));
|
|
161
|
-
} else yield*
|
|
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(i, a?.providerCustomerId);
|
|
171
259
|
}
|
|
172
|
-
}),
|
|
260
|
+
}), Ne = () => Me(), U = (e) => C.fail(new t({
|
|
173
261
|
source: "billing",
|
|
174
|
-
message: `tenant '${
|
|
262
|
+
message: `tenant '${e}' already has a paying subscription — change its plan instead of checking out again`,
|
|
175
263
|
transient: !1
|
|
176
|
-
})),
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
264
|
+
})), W = (e, t, n) => C.gen(function* () {
|
|
265
|
+
if (!(yield* R(e))) return yield* C.fail(f("A qualified billing account is required before subscription writes."));
|
|
266
|
+
let r = P.stores, i = yield* L(), a = yield* C.try({
|
|
267
|
+
try: () => y({
|
|
268
|
+
tenantId: e,
|
|
269
|
+
provider: S.name,
|
|
270
|
+
account: i.account,
|
|
271
|
+
snapshot: t,
|
|
272
|
+
expectedPriceId: t.plan === null ? null : w.priceIdFor(t.plan),
|
|
273
|
+
expectedCurrency: w.currencyFor(t.plan ?? "free"),
|
|
274
|
+
observedAt: k()
|
|
275
|
+
}),
|
|
276
|
+
catch: () => f("The current provider subscription binding could not be captured.")
|
|
277
|
+
});
|
|
278
|
+
if (a !== null) {
|
|
279
|
+
let t = yield* r.customers.getByProviderCustomerId(a.providerCustomerId, i);
|
|
280
|
+
if (t === null || t.tenantId !== e || P.stores !== r) return yield* C.fail(f("The provider subscription has no matching native customer custody."));
|
|
281
|
+
}
|
|
282
|
+
if (t.status === "canceled" && t.plan === null) return yield* oe(C.gen(function* () {
|
|
283
|
+
let n = (yield* r.subscriptions.listByTenant(e)).filter((e) => e.provider === S.name && e.providerSubscriptionId === t.providerSubscriptionId);
|
|
284
|
+
if (n.length > 1) return yield* C.fail(f("The current subscription identity is ambiguous."));
|
|
285
|
+
n[0] !== void 0 && (yield* r.subscriptions.patchBySubscription(e, t.providerSubscriptionId, { status: "canceled" }, n[0].statusEventAt));
|
|
286
|
+
}));
|
|
287
|
+
if (yield* r.subscriptions.upsert({
|
|
288
|
+
tenantId: e,
|
|
289
|
+
provider: S.name,
|
|
290
|
+
providerSubscriptionId: t.providerSubscriptionId,
|
|
291
|
+
plan: t.plan ?? "free",
|
|
292
|
+
status: t.status,
|
|
293
|
+
quantity: t.quantity,
|
|
294
|
+
currentPeriodStart: t.currentPeriodStart,
|
|
295
|
+
currentPeriodEnd: t.currentPeriodEnd,
|
|
296
|
+
cancelAt: t.cancelAt,
|
|
297
|
+
pastDueSince: null,
|
|
298
|
+
statusEventAt: n,
|
|
299
|
+
providerObservation: a
|
|
300
|
+
}), a !== null) {
|
|
301
|
+
let i = (yield* r.subscriptions.listByTenant(e)).filter((e) => e.provider === S.name && e.providerSubscriptionId === t.providerSubscriptionId);
|
|
302
|
+
yield* C.try({
|
|
303
|
+
try: () => {
|
|
304
|
+
if (P.stores !== r || !b(i, a, n)) throw Error("unconfirmed");
|
|
305
|
+
},
|
|
306
|
+
catch: () => f("The provider subscription observation was not read back exactly.", !0)
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
}), Pe = (e) => C.gen(function* () {
|
|
310
|
+
let { tenantId: n, plan: r, successUrl: i, cancelUrl: a } = e, o = e.authorize ?? (() => C.void), s = w.priceIdFor(r), c = e.quantity ?? w.minimumSeatsFor(r), l = (e) => C.fail(new t({
|
|
190
311
|
source: "billing",
|
|
191
|
-
message:
|
|
312
|
+
message: e,
|
|
192
313
|
transient: !1
|
|
193
314
|
}));
|
|
194
|
-
if (
|
|
195
|
-
if (!Number.isSafeInteger(
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
315
|
+
if (s === null) return yield* l("The selected plan has no provider checkout price.");
|
|
316
|
+
if (!Number.isSafeInteger(c) || c < 1) return yield* l("Seat quantity must be a positive integer.");
|
|
317
|
+
if (c < w.minimumSeatsFor(r)) return yield* l("The plan price already covers more seats than requested.");
|
|
318
|
+
yield* N(n, "checkout"), yield* o(), yield* de(i, "successUrl"), yield* de(a, "cancelUrl");
|
|
319
|
+
let u = yield* P.stores.subscriptions.getByTenant(n);
|
|
320
|
+
if (u !== null && ae.has(u.status)) return yield* U(n);
|
|
321
|
+
let d = [...new Set(w.meteredPriceIdsFor(r))].sort(), f = E?.adjustableQuantity === void 0 ? void 0 : {
|
|
322
|
+
min: E.adjustableQuantity.min,
|
|
323
|
+
max: E.adjustableQuantity.max
|
|
324
|
+
}, p = E?.trialDays, m = yield* C.tryPromise({
|
|
203
325
|
try: async () => {
|
|
204
326
|
let e = new TextEncoder().encode(JSON.stringify([
|
|
205
327
|
n,
|
|
206
|
-
|
|
328
|
+
S.name,
|
|
207
329
|
r,
|
|
208
|
-
|
|
330
|
+
s,
|
|
209
331
|
d,
|
|
210
|
-
|
|
332
|
+
c,
|
|
211
333
|
i,
|
|
212
334
|
a,
|
|
213
335
|
f ?? null,
|
|
@@ -215,152 +337,159 @@ var C = S({ scope: "@voltro/plugin-billing" }), w = 3, T = /* @__PURE__ */ new S
|
|
|
215
337
|
])), t = await globalThis.crypto.subtle.digest("SHA-256", e);
|
|
216
338
|
return [...new Uint8Array(t)].map((e) => e.toString(16).padStart(2, "0")).join("");
|
|
217
339
|
},
|
|
218
|
-
catch: () => new
|
|
340
|
+
catch: () => new t({
|
|
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*
|
|
226
|
-
let e = new Date(
|
|
347
|
+
yield* N(n, "checkout"), yield* o(), yield* fe(n);
|
|
348
|
+
let e = new Date(k());
|
|
227
349
|
if (!Number.isFinite(e.getTime())) return yield* l("The checkout clock could not be confirmed.");
|
|
228
|
-
let t = yield*
|
|
350
|
+
let t = yield* P.stores.checkouts.reserve({
|
|
229
351
|
tenantId: n,
|
|
230
|
-
provider:
|
|
352
|
+
provider: S.name,
|
|
231
353
|
requestDigest: m,
|
|
232
354
|
plan: r,
|
|
233
|
-
quantity:
|
|
355
|
+
quantity: c,
|
|
234
356
|
createdAt: e,
|
|
235
357
|
expiresAt: /* @__PURE__ */ new Date(Math.floor((e.getTime() + 36e5) / 1e3) * 1e3)
|
|
236
358
|
});
|
|
237
|
-
if (t.provider !==
|
|
359
|
+
if (t.provider !== S.name) return yield* l("The checkout provider changed. Its previous operation needs reconciliation.");
|
|
238
360
|
let u = t.providerCustomerId, h = yield* z(n);
|
|
239
|
-
if (h !== null && (h.provider !==
|
|
361
|
+
if (h !== null && (h.provider !== S.name || u !== null && h.providerCustomerId !== u)) return yield* l("The checkout customer binding changed. Its operation needs reconciliation.");
|
|
240
362
|
if (t.requestDigest === m && u === null) {
|
|
241
|
-
yield*
|
|
242
|
-
let e = yield*
|
|
363
|
+
yield* N(n, "checkout"), yield* o(), u = h?.providerCustomerId ?? (yield* M(o().pipe(C.andThen(N(n, "checkout")), C.andThen(S.ensureCustomer({ tenantId: n }))), T));
|
|
364
|
+
let e = yield* P.stores.checkouts.patch(t.id, { providerCustomerId: u });
|
|
243
365
|
if (e.active !== 1 || e.providerCustomerId !== u) return yield* l("Checkout ownership changed during customer resolution.");
|
|
244
366
|
let r = yield* z(n);
|
|
245
|
-
if (r !== null && (r.provider !==
|
|
246
|
-
yield*
|
|
367
|
+
if (r !== null && (r.provider !== S.name || r.providerCustomerId !== u)) return yield* l("The current customer binding requires reconciliation.");
|
|
368
|
+
yield* o(), r === null && (yield* B(n, u));
|
|
247
369
|
}
|
|
248
370
|
if (u !== null) {
|
|
249
371
|
let e = yield* z(n);
|
|
250
372
|
if (e === null) yield* B(n, u);
|
|
251
373
|
else if (e.providerCustomerId !== u) return yield* l("Checkout customer custody differs from the retained operation.");
|
|
252
374
|
}
|
|
253
|
-
let g = yield*
|
|
375
|
+
let g = yield* M(S.findCheckoutSession({
|
|
254
376
|
tenantId: n,
|
|
255
377
|
operationId: t.id,
|
|
256
378
|
...u === null ? {} : { providerCustomerId: u }
|
|
257
|
-
}),
|
|
379
|
+
}), T), _ = g.receipt;
|
|
258
380
|
if (_ !== null) {
|
|
259
381
|
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*
|
|
261
|
-
yield*
|
|
382
|
+
if (u === null && (u = _.providerCustomerId, yield* P.stores.checkouts.patch(t.id, { providerCustomerId: u })), _.status === "expired") {
|
|
383
|
+
yield* P.stores.checkouts.patch(t.id, {
|
|
262
384
|
phase: "expired",
|
|
263
385
|
providerSessionId: _.id
|
|
264
386
|
});
|
|
265
387
|
continue;
|
|
266
388
|
}
|
|
267
389
|
if (_.status === "complete") {
|
|
268
|
-
if (yield*
|
|
390
|
+
if (yield* P.stores.checkouts.patch(t.id, {
|
|
269
391
|
phase: "completed",
|
|
270
392
|
providerSessionId: _.id
|
|
271
393
|
}), _.providerSubscriptionId === null) return yield* l("Completed checkout settlement is not yet confirmed.");
|
|
272
|
-
if ((yield*
|
|
273
|
-
yield*
|
|
394
|
+
if ((yield* M(S.fetchSubscription(_.providerSubscriptionId), T))?.status === "canceled") {
|
|
395
|
+
yield* P.stores.checkouts.patch(t.id, { phase: "retired" });
|
|
274
396
|
continue;
|
|
275
397
|
}
|
|
276
|
-
return yield*
|
|
398
|
+
return yield* U(n);
|
|
277
399
|
}
|
|
278
|
-
let e = yield*
|
|
400
|
+
let e = yield* P.stores.checkouts.patch(t.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*
|
|
404
|
+
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* N(n, "checkout", u ?? void 0), { url: _.url }) : yield* l("Another checkout is still open for this organization.");
|
|
283
405
|
}
|
|
284
406
|
if (g.observedAt !== null && g.observedAt.getTime() > t.expiresAt.getTime()) {
|
|
285
|
-
yield*
|
|
407
|
+
yield* P.stores.checkouts.patch(t.id, { phase: "expired" });
|
|
286
408
|
continue;
|
|
287
409
|
}
|
|
288
410
|
if (t.requestDigest !== m) return yield* l("An earlier checkout request is unresolved. Check its current state first.");
|
|
289
|
-
if (u === null ||
|
|
290
|
-
let
|
|
291
|
-
if (
|
|
292
|
-
for (let e of
|
|
293
|
-
return yield*
|
|
411
|
+
if (u === null || k().getTime() >= t.expiresAt.getTime()) return yield* l("The earlier checkout needs provider deadline/receipt reconciliation.");
|
|
412
|
+
let v = (yield* M(S.listSubscriptions({ providerCustomerId: u }), T)).filter((e) => ae.has(e.status));
|
|
413
|
+
if (v.length > 0) {
|
|
414
|
+
for (let e of v) yield* W(n, e, k());
|
|
415
|
+
return yield* U(n);
|
|
294
416
|
}
|
|
295
|
-
let
|
|
296
|
-
if (
|
|
297
|
-
yield*
|
|
417
|
+
let y = yield* P.stores.checkouts.patch(t.id, { phase: "creating" });
|
|
418
|
+
if (y.active !== 1 || y.phase === "completed") return yield* l("Checkout state changed before provider dispatch.");
|
|
419
|
+
yield* N(n, "checkout", u ?? void 0), yield* o(), yield* M(o().pipe(C.andThen(N(n, "checkout", u ?? void 0)), C.andThen(S.expireOpenCheckouts({
|
|
298
420
|
providerCustomerId: u,
|
|
299
421
|
exceptOperationId: t.id
|
|
300
|
-
}))),
|
|
301
|
-
let
|
|
422
|
+
}))), T), yield* N(n, "checkout", u ?? void 0), yield* o();
|
|
423
|
+
let b = yield* M(o().pipe(C.andThen(N(n, "checkout", u ?? void 0)), C.andThen(S.createCheckoutSession({
|
|
302
424
|
tenantId: n,
|
|
303
|
-
priceId:
|
|
425
|
+
priceId: s,
|
|
304
426
|
meteredPriceIds: d,
|
|
305
427
|
successUrl: i,
|
|
306
428
|
cancelUrl: a,
|
|
307
|
-
quantity:
|
|
429
|
+
quantity: c,
|
|
308
430
|
providerCustomerId: u,
|
|
309
431
|
idempotencyKey: t.id,
|
|
310
432
|
expiresAt: t.expiresAt,
|
|
311
433
|
...f === void 0 ? {} : { adjustableQuantity: f },
|
|
312
434
|
...p === void 0 ? {} : { trialDays: p }
|
|
313
|
-
}))),
|
|
314
|
-
if (
|
|
315
|
-
if (
|
|
316
|
-
yield*
|
|
435
|
+
}))), T);
|
|
436
|
+
if (b.operationId !== t.id || b.tenantId !== n || b.providerCustomerId !== u || b.expiresAt.getTime() !== t.expiresAt.getTime() || !b.id) return yield* l("Checkout creation returned an inconsistent provider receipt.");
|
|
437
|
+
if (b.status === "expired") {
|
|
438
|
+
yield* P.stores.checkouts.patch(t.id, {
|
|
317
439
|
phase: "expired",
|
|
318
|
-
providerSessionId:
|
|
440
|
+
providerSessionId: b.id
|
|
319
441
|
});
|
|
320
442
|
continue;
|
|
321
443
|
}
|
|
322
|
-
if (
|
|
444
|
+
if (b.status === "complete") return yield* P.stores.checkouts.patch(t.id, {
|
|
323
445
|
phase: "completed",
|
|
324
|
-
providerSessionId:
|
|
325
|
-
}), yield*
|
|
326
|
-
if (
|
|
327
|
-
let
|
|
446
|
+
providerSessionId: b.id
|
|
447
|
+
}), yield* U(n);
|
|
448
|
+
if (b.url === null) return yield* l("Checkout creation returned no confirmed URL.");
|
|
449
|
+
let ee = yield* P.stores.checkouts.patch(t.id, {
|
|
328
450
|
phase: "ready",
|
|
329
|
-
providerSessionId:
|
|
451
|
+
providerSessionId: b.id
|
|
330
452
|
});
|
|
331
|
-
return
|
|
453
|
+
return ee.active !== 1 || ee.phase !== "ready" ? yield* l("Checkout state changed before its URL could be returned.") : (yield* N(n, "checkout", u ?? void 0), { url: b.url });
|
|
332
454
|
}
|
|
333
455
|
return yield* l("Checkout operations changed concurrently. Check current billing state before retrying.");
|
|
334
|
-
}),
|
|
335
|
-
yield*
|
|
336
|
-
let r = yield* z(
|
|
337
|
-
return r === null ? yield*
|
|
456
|
+
}), Fe = (e, n) => C.gen(function* () {
|
|
457
|
+
yield* N(e, "portal"), yield* de(n, "returnUrl");
|
|
458
|
+
let r = yield* z(e);
|
|
459
|
+
return r === null ? yield* C.fail(new t({
|
|
338
460
|
source: "billing",
|
|
339
|
-
message: `no provider customer linked for tenant '${
|
|
461
|
+
message: `no provider customer linked for tenant '${e}'`,
|
|
340
462
|
transient: !1
|
|
341
|
-
})) : yield*
|
|
342
|
-
tenantId:
|
|
463
|
+
})) : yield* M(S.createPortalSession({
|
|
464
|
+
tenantId: e,
|
|
343
465
|
providerCustomerId: r.providerCustomerId,
|
|
344
466
|
returnUrl: n
|
|
345
|
-
}),
|
|
346
|
-
}),
|
|
347
|
-
if (
|
|
348
|
-
let t = yield*
|
|
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 (
|
|
473
|
+
if (S.customerEmail === void 0) return null;
|
|
352
474
|
let t = yield* z(e);
|
|
353
|
-
return t === null ? null : yield*
|
|
354
|
-
}),
|
|
355
|
-
let
|
|
356
|
-
return
|
|
357
|
-
|
|
358
|
-
|
|
475
|
+
return t === null ? null : yield* S.customerEmail(t.providerCustomerId);
|
|
476
|
+
}), Le = (e) => {
|
|
477
|
+
let n = F.portalReturnUrl;
|
|
478
|
+
return n === void 0 ? C.succeed(null) : C.try({
|
|
479
|
+
try: () => typeof n == "string" ? n : n(e),
|
|
480
|
+
catch: (e) => new t({
|
|
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))), s = yield* Le(e.tenantId), c = t.lockedSince !== null, l = o({
|
|
359
488
|
stepId: n,
|
|
360
|
-
locked:
|
|
489
|
+
locked: c,
|
|
361
490
|
graceEndsAt: i,
|
|
362
|
-
portalUrl:
|
|
363
|
-
}),
|
|
491
|
+
portalUrl: s
|
|
492
|
+
}), u = {
|
|
364
493
|
stepId: n,
|
|
365
494
|
tenantId: e.tenantId,
|
|
366
495
|
to: a,
|
|
@@ -368,82 +497,89 @@ var C = S({ scope: "@voltro/plugin-billing" }), w = 3, T = /* @__PURE__ */ new S
|
|
|
368
497
|
status: e.status,
|
|
369
498
|
pastDueSince: r,
|
|
370
499
|
graceEndsAt: i,
|
|
371
|
-
locked:
|
|
372
|
-
lockout:
|
|
373
|
-
portalUrl:
|
|
374
|
-
...
|
|
500
|
+
locked: c,
|
|
501
|
+
lockout: F.lockout,
|
|
502
|
+
portalUrl: s,
|
|
503
|
+
...l
|
|
375
504
|
};
|
|
376
|
-
|
|
505
|
+
D.info("billing dunning notice", {
|
|
377
506
|
tenant: e.tenantId,
|
|
378
507
|
step: n,
|
|
379
|
-
locked:
|
|
508
|
+
locked: c,
|
|
380
509
|
graceEndsAt: i.toISOString(),
|
|
381
|
-
delivered:
|
|
510
|
+
delivered: F.notify !== void 0 && a !== null
|
|
382
511
|
});
|
|
383
|
-
let
|
|
384
|
-
|
|
385
|
-
|
|
512
|
+
let d = F.notify;
|
|
513
|
+
d !== void 0 && (yield* d(u).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
|
-
}),
|
|
392
|
-
yield*
|
|
393
|
-
|
|
394
|
-
|
|
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))))
|
|
400
|
-
if (
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
527
|
+
}), null))));
|
|
528
|
+
if (P.stores !== t) return yield* C.fail(f("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
|
-
}),
|
|
428
|
-
let
|
|
429
|
-
|
|
430
|
-
|
|
552
|
+
}), G = (e) => C.gen(function* () {
|
|
553
|
+
let t = P.stores;
|
|
554
|
+
if (yield* R(e), P.stores !== t) return yield* C.fail(f("Billing storage changed during observation.", !0));
|
|
555
|
+
let n = yield* oe(ze(e, t));
|
|
556
|
+
if (n === null) return l(null, F, k(), e);
|
|
557
|
+
let r = l(n, F, k(), e);
|
|
558
|
+
if (!F.enabled || n.status !== "pastDue" || n.pastDueSince === null) return r;
|
|
559
|
+
let i = n.pastDueSince, o = c(i), u = r.graceEndsAt ?? i, d = s(F.steps, i, k()).map((e) => e.id);
|
|
560
|
+
r.lockedSince !== null && d.push(a);
|
|
561
|
+
for (let t of d) (yield* P.stores.dunningNotices.claim(e, o, t, k())) && (yield* Re(n, r, t, i, u));
|
|
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
|
-
}),
|
|
437
|
-
if (!
|
|
438
|
-
if (e._tag === "invoicePaymentFailed") return
|
|
439
|
-
if (e._tag !== "invoicePaid" && e._tag !== "subscriptionUpserted") return
|
|
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
|
|
442
|
-
},
|
|
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
|
|
580
|
+
case "subscriptionUpserted": return P.stores.subscriptions.upsert({
|
|
445
581
|
tenantId: e.tenantId,
|
|
446
|
-
provider:
|
|
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
|
|
458
|
-
case "customerLinked": return B(e.tenantId, e.providerCustomerId).pipe(
|
|
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
|
-
},
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
596
|
+
}, He = (e) => C.gen(function* () {
|
|
597
|
+
let t = yield* C.try({
|
|
598
|
+
try: () => {
|
|
599
|
+
let t = p(e);
|
|
600
|
+
if (![e.providerCustomerId, e.providerEventId].every((e) => typeof e == "string" && e.length > 0 && e.length <= 191 && e.trim() === e && e.isWellFormed())) throw f("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: () => f("The verified payment correction identity is invalid.")
|
|
608
|
+
}), n = P.stores, r = yield* L();
|
|
609
|
+
if (!m(t, r.account)) return yield* C.fail(f("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(f("Retained native customer custody is required before payment correction."));
|
|
612
|
+
if (P.stores !== n) return yield* C.fail(f("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), o = yield* n.customers.getByProviderCustomerId(t.providerCustomerId, r), s = yield* L();
|
|
620
|
+
return P.stores !== n || !m(s.account, t) || o === null || o.id !== i.id || o.tenantId !== i.tenantId ? yield* C.fail(f("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(f("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*
|
|
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" ?
|
|
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(f("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
|
|
639
|
+
return C.gen(function* () {
|
|
479
640
|
let e = t.providerCustomerId;
|
|
480
|
-
if (typeof e != "string" || e.length === 0 || e.trim() !== e) return yield*
|
|
481
|
-
let n = yield*
|
|
482
|
-
if (n === null) return yield*
|
|
483
|
-
if (n.provider !==
|
|
641
|
+
if (typeof e != "string" || e.length === 0 || e.trim() !== e) return yield* C.fail(f("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(f("The invoice customer must be linked before reconciliation.", !0));
|
|
644
|
+
if (n.provider !== S.name) return yield* C.fail(f("The invoice customer belongs to a different provider."));
|
|
484
645
|
let r = n.tenantId;
|
|
485
|
-
yield*
|
|
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*
|
|
494
|
-
return n.retiredAt === null && a?.id === n.id && (yield*
|
|
654
|
+
}, a = yield* P.stores.customers.getByTenant(r);
|
|
655
|
+
return n.retiredAt === null && a?.id === n.id && (yield* K(i)), i;
|
|
656
|
+
});
|
|
657
|
+
}, q = (e, n, r) => C.gen(function* () {
|
|
658
|
+
let i = P.stores;
|
|
659
|
+
if (S.supportsNativeSubscriptionWrites !== !0) return yield* C.fail(new t({
|
|
660
|
+
source: "billing",
|
|
661
|
+
message: "This provider does not support native single-dispatch subscription operations.",
|
|
662
|
+
transient: !1
|
|
663
|
+
}));
|
|
664
|
+
let a = null;
|
|
665
|
+
yield* r(), yield* N(e, n);
|
|
666
|
+
let o = yield* i.subscriptions.getByTenant(e), s = yield* z(e), c = S.fetchSubscriptionSnapshot?.bind(S), l = () => new t({
|
|
667
|
+
source: "billing",
|
|
668
|
+
message: "The current owned subscription must be reconciled before this change can be confirmed.",
|
|
669
|
+
transient: !0
|
|
495
670
|
});
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
671
|
+
if (o === null || s === null || c === void 0 || o.tenantId !== e || o.provider !== S.name || s.provider !== S.name) return yield* C.fail(l());
|
|
672
|
+
let u = () => C.gen(function* () {
|
|
673
|
+
if (yield* r(), P.stores !== i || (yield* i.closures.getAccount(e)) !== null) return yield* C.fail(l());
|
|
674
|
+
yield* N(e, n, s.providerCustomerId);
|
|
675
|
+
let t = yield* i.customers.getByTenant(e), a = yield* i.subscriptions.getByTenant(e);
|
|
676
|
+
if (P.stores !== i || t === null || t.id !== s.id || t.provider !== s.provider || t.providerCustomerId !== s.providerCustomerId || !m(t.account, s.account) || a === null || a.provider !== o.provider || a.providerSubscriptionId !== o.providerSubscriptionId) return yield* C.fail(l());
|
|
677
|
+
yield* r();
|
|
678
|
+
}), d = (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(), f = () => C.gen(function* () {
|
|
679
|
+
yield* u();
|
|
680
|
+
let t = yield* X(o.providerSubscriptionId, s), n = yield* C.try({
|
|
681
|
+
try: () => {
|
|
682
|
+
let n = (e) => e === null || e instanceof Date && Number.isFinite(e.getTime()), r = t?.plan == null ? null : w.priceIdFor(t.plan);
|
|
683
|
+
if (t === null || t.providerSubscriptionId !== o.providerSubscriptionId || t.providerCustomerId !== s.providerCustomerId || t.tenantId !== null && t.tenantId !== e || t.plan === null || !w.has(t.plan) || !Number.isSafeInteger(t.quantity) || t.quantity < 1 || !Array.isArray(t.priceIds) || t.priceIds.some((e) => typeof e != "string" || e.length === 0) || r !== null && !t.priceIds.includes(r) || ![
|
|
684
|
+
"active",
|
|
685
|
+
"trialing",
|
|
686
|
+
"pastDue",
|
|
687
|
+
"incomplete",
|
|
688
|
+
"canceled"
|
|
689
|
+
].includes(t.status) || !n(t.currentPeriodStart) || !n(t.currentPeriodEnd) || !n(t.cancelAt) || t.currentPeriodStart !== null && t.currentPeriodEnd !== null && t.currentPeriodStart.getTime() > t.currentPeriodEnd.getTime()) throw l();
|
|
690
|
+
let i = k();
|
|
691
|
+
if (!(i instanceof Date) || !Number.isFinite(i.getTime())) throw l();
|
|
692
|
+
return a = {
|
|
693
|
+
...t,
|
|
694
|
+
priceIds: [...t.priceIds],
|
|
695
|
+
providerObservedAt: t.providerObservedAt instanceof Date ? new Date(t.providerObservedAt.getTime()) : null
|
|
696
|
+
}, {
|
|
697
|
+
tenantId: e,
|
|
698
|
+
provider: S.name,
|
|
699
|
+
providerSubscriptionId: o.providerSubscriptionId,
|
|
700
|
+
plan: t.plan,
|
|
701
|
+
status: t.status,
|
|
702
|
+
quantity: t.quantity,
|
|
703
|
+
currentPeriodStart: t.currentPeriodStart === null ? null : new Date(t.currentPeriodStart.getTime()),
|
|
704
|
+
currentPeriodEnd: t.currentPeriodEnd === null ? null : new Date(t.currentPeriodEnd.getTime()),
|
|
705
|
+
cancelAt: t.cancelAt === null ? null : new Date(t.cancelAt.getTime()),
|
|
706
|
+
providerObservation: y({
|
|
707
|
+
tenantId: e,
|
|
708
|
+
provider: S.name,
|
|
709
|
+
account: s.account,
|
|
710
|
+
snapshot: t,
|
|
711
|
+
expectedPriceId: r,
|
|
712
|
+
expectedCurrency: w.currencyFor(t.plan),
|
|
713
|
+
observedAt: i
|
|
714
|
+
}),
|
|
715
|
+
pastDueSince: o.pastDueSince,
|
|
716
|
+
statusEventAt: new Date(i.getTime())
|
|
717
|
+
};
|
|
718
|
+
},
|
|
719
|
+
catch: l
|
|
720
|
+
});
|
|
721
|
+
yield* u();
|
|
722
|
+
let r = yield* i.subscriptions.getByTenant(e);
|
|
723
|
+
yield* i.subscriptions.upsert(n);
|
|
724
|
+
let c = n.status === "pastDue" ? r?.status === "pastDue" && r.pastDueSince !== null ? r.pastDueSince : n.statusEventAt : null;
|
|
725
|
+
yield* i.subscriptions.patchBySubscription(e, n.providerSubscriptionId, { pastDueSince: c }, n.statusEventAt);
|
|
726
|
+
let f = yield* i.subscriptions.getByTenant(e);
|
|
727
|
+
return f === null || f.providerSubscriptionId !== n.providerSubscriptionId || f.plan !== n.plan || f.status !== n.status || f.quantity !== n.quantity || !d(f.currentPeriodStart, n.currentPeriodStart) || !d(f.currentPeriodEnd, n.currentPeriodEnd) || !d(f.cancelAt, n.cancelAt) ? yield* C.fail(l()) : (yield* u(), yield* C.try({
|
|
728
|
+
try: () => {
|
|
729
|
+
if (JSON.stringify(v(f.providerObservation, f)) !== JSON.stringify(v(n.providerObservation, n))) throw l();
|
|
730
|
+
},
|
|
731
|
+
catch: l
|
|
732
|
+
}), yield* Z([Q(e, n, n.statusEventAt ?? k())]), yield* u(), f);
|
|
733
|
+
}), p = () => oe(f());
|
|
734
|
+
return {
|
|
735
|
+
sub: yield* p(),
|
|
736
|
+
customer: s,
|
|
737
|
+
stores: i,
|
|
738
|
+
check: u,
|
|
739
|
+
observe: p,
|
|
740
|
+
sameDate: d,
|
|
741
|
+
refuse: l,
|
|
742
|
+
getObservation: () => a
|
|
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, n, r, a) => C.gen(function* () {
|
|
748
|
+
if (n === void 0 || !/^[A-Za-z0-9_-]{8,128}$/.test(n)) return yield* C.fail(new t({
|
|
500
749
|
source: "billing",
|
|
501
|
-
message:
|
|
750
|
+
message: "A durable requestId is required. Keep it unchanged when checking or retrying this operation.",
|
|
502
751
|
transient: !1
|
|
503
752
|
}));
|
|
504
|
-
let
|
|
505
|
-
|
|
753
|
+
let o = e.getObservation(), s = {
|
|
754
|
+
...r,
|
|
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: r.kind === "cancel" ? null : o?.providerPlanItemId ?? null,
|
|
761
|
+
expectedPriceId: r.kind === "cancel" ? null : w.priceIdFor(e.sub.plan)
|
|
762
|
+
};
|
|
763
|
+
if (r.kind !== "cancel" && (s.itemId === null || s.expectedPriceId === null)) return yield* C.fail(e.refuse());
|
|
764
|
+
let c = e.stores.subscriptionWrites, l = yield* c.reserve(e.sub.tenantId, n, s), u = null;
|
|
765
|
+
if (l.phase === "prepared" || l.phase === "claimed") {
|
|
766
|
+
if (!x(e.sub.status)) return yield* C.fail(e.refuse());
|
|
767
|
+
yield* e.check();
|
|
768
|
+
let t = globalThis.crypto.randomUUID();
|
|
769
|
+
if (l = yield* c.claim(l.id, t), l.phase === "claimed" && l.claimId === t) {
|
|
770
|
+
let n = l;
|
|
771
|
+
yield* a({
|
|
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(c.dispatch(n.id, t))),
|
|
777
|
+
notDispatched: () => c.notDispatched(n.id, t),
|
|
778
|
+
rejected: (e) => c.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
|
+
u = e;
|
|
782
|
+
})));
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
let d = yield* e.observe(), f = e.getObservation();
|
|
786
|
+
f?.writeOperationId === l.id && (yield* We(e, l.id, f));
|
|
787
|
+
let p = yield* c.getRequest(e.sub.tenantId, n);
|
|
788
|
+
if (p === null || p.id !== l.id) return yield* C.fail(e.refuse());
|
|
789
|
+
if (p.phase === "acknowledged") yield* c.complete(p.id);
|
|
790
|
+
else if (p.phase === "withdrawn" || p.phase === "rejected") return yield* C.fail(u ?? i(n, p.phase));
|
|
791
|
+
else if (p.phase !== "completed") return yield* C.fail(u ?? e.refuse());
|
|
792
|
+
return yield* e.check(), d;
|
|
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, n, r = () => C.void, i) => C.gen(function* () {
|
|
829
|
+
let a = n.plan === void 0 ? void 0 : w.priceIdFor(n.plan);
|
|
830
|
+
if (n.plan !== void 0 && (!w.has(n.plan) || a === null) || n.quantity !== void 0 && (!Number.isSafeInteger(n.quantity) || n.quantity < 1)) return yield* C.fail(new t({
|
|
506
831
|
source: "billing",
|
|
507
|
-
message:
|
|
832
|
+
message: "Choose a self-service plan and a positive safe whole seat quantity.",
|
|
508
833
|
transient: !1
|
|
509
834
|
}));
|
|
510
|
-
|
|
835
|
+
let o = yield* q(e, "change", r);
|
|
836
|
+
if (n.quantity !== void 0 && n.quantity < w.minimumSeatsFor(n.plan ?? o.sub.plan)) return yield* C.fail(new t({
|
|
511
837
|
source: "billing",
|
|
512
|
-
message:
|
|
838
|
+
message: "The plan price already covers more seats than requested.",
|
|
513
839
|
transient: !1
|
|
514
840
|
}));
|
|
515
|
-
let
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
841
|
+
let s = yield* Ge(o, i, {
|
|
842
|
+
kind: "change",
|
|
843
|
+
plan: n.plan ?? null,
|
|
844
|
+
priceId: a ?? null,
|
|
845
|
+
quantity: n.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
|
-
})
|
|
521
|
-
return
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
tenantId: t,
|
|
528
|
-
plan: i,
|
|
529
|
-
quantity: o.quantity,
|
|
530
|
-
prorationMinor: o.prorationMinor,
|
|
531
|
-
currency: o.currency
|
|
853
|
+
}));
|
|
854
|
+
return {
|
|
855
|
+
tenantId: e,
|
|
856
|
+
plan: s.plan,
|
|
857
|
+
quantity: s.quantity,
|
|
858
|
+
prorationMinor: null,
|
|
859
|
+
currency: w.currencyFor(s.plan)
|
|
532
860
|
};
|
|
533
|
-
}),
|
|
534
|
-
let r = yield*
|
|
535
|
-
if (r === null) return yield*
|
|
861
|
+
}), Xe = (e, n) => C.gen(function* () {
|
|
862
|
+
let r = yield* P.stores.subscriptions.getByTenant(e);
|
|
863
|
+
if (r === null) return yield* C.fail(new t({
|
|
864
|
+
source: "billing",
|
|
865
|
+
message: `no subscription for tenant '${e}' to preview`,
|
|
866
|
+
transient: !1
|
|
867
|
+
}));
|
|
868
|
+
let i = n.plan ?? r.plan, a = n.plan === void 0 ? void 0 : w.priceIdFor(i);
|
|
869
|
+
if (!w.has(i) || a === null || n.quantity !== void 0 && (!Number.isSafeInteger(n.quantity) || n.quantity < 1)) return yield* C.fail(new t({
|
|
870
|
+
source: "billing",
|
|
871
|
+
message: "Choose a self-service plan and a positive safe whole seat quantity.",
|
|
872
|
+
transient: !1
|
|
873
|
+
}));
|
|
874
|
+
if (n.quantity !== void 0 && n.quantity < w.minimumSeatsFor(i)) return yield* C.fail(new t({
|
|
536
875
|
source: "billing",
|
|
537
|
-
message:
|
|
876
|
+
message: "The plan price already covers more seats than requested.",
|
|
538
877
|
transient: !1
|
|
539
878
|
}));
|
|
540
|
-
let
|
|
879
|
+
let o = yield* M(S.previewSubscriptionChange({
|
|
541
880
|
providerSubscriptionId: r.providerSubscriptionId,
|
|
542
|
-
...
|
|
881
|
+
...a === void 0 ? {} : { priceId: a },
|
|
882
|
+
...Je(n.plan ?? null),
|
|
543
883
|
...n.quantity === void 0 ? {} : { quantity: n.quantity },
|
|
544
884
|
proration: "prorate"
|
|
545
|
-
}),
|
|
546
|
-
return {
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
885
|
+
}), T);
|
|
886
|
+
return o.plan !== i || !w.has(o.plan) || n.quantity !== void 0 && o.quantity !== n.quantity || !Number.isSafeInteger(o.quantity) || o.quantity < 1 || !Number.isSafeInteger(o.prorationMinor) || o.currency !== w.currencyFor(o.plan) ? yield* C.fail(new t({
|
|
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: o.plan,
|
|
893
|
+
quantity: o.quantity,
|
|
894
|
+
prorationMinor: o.prorationMinor,
|
|
895
|
+
currency: o.currency
|
|
552
896
|
};
|
|
553
|
-
}),
|
|
897
|
+
}), Ze = (e) => C.gen(function* () {
|
|
554
898
|
let t = yield* z(e);
|
|
555
|
-
return t === null ? [] : yield*
|
|
556
|
-
}),
|
|
557
|
-
let
|
|
558
|
-
if (
|
|
559
|
-
if (
|
|
560
|
-
let
|
|
561
|
-
if (
|
|
562
|
-
let
|
|
563
|
-
if (!
|
|
564
|
-
let
|
|
565
|
-
providerCustomerId:
|
|
899
|
+
return t === null ? [] : yield* M(S.listInvoices({ providerCustomerId: t.providerCustomerId }), T);
|
|
900
|
+
}), Qe = (e, n, r = P.stores) => C.gen(function* () {
|
|
901
|
+
let i = S.fetchInvoiceSnapshot?.bind(S), a = S.fetchAccountIdentity?.bind(S);
|
|
902
|
+
if (i === void 0 || a === void 0) return yield* C.fail(f("Complete account-owned invoice evidence is unsupported."));
|
|
903
|
+
if (P.stores !== r) return yield* C.fail(f("Billing stores changed before invoice observation.", !0));
|
|
904
|
+
let o = yield* L();
|
|
905
|
+
if (o.provider !== e.provider || !m(o.account, e.account)) return yield* C.fail(f("The invoice account differs from retained custody."));
|
|
906
|
+
let s = yield* a();
|
|
907
|
+
if (!m(s, e.account)) return yield* C.fail(f("The provider account changed before invoice observation."));
|
|
908
|
+
let c = yield* M(i({
|
|
909
|
+
providerCustomerId: e.providerCustomerId,
|
|
566
910
|
providerInvoiceId: n
|
|
567
|
-
}),
|
|
568
|
-
yield*
|
|
911
|
+
}), T);
|
|
912
|
+
yield* C.try({
|
|
569
913
|
try: () => {
|
|
570
|
-
if (
|
|
914
|
+
if (d(c), c.providerInvoiceId !== n || c.providerCustomerId !== e.providerCustomerId || c.livemode !== e.account.livemode) throw f("The invoice does not match retained account/customer custody.");
|
|
571
915
|
},
|
|
572
|
-
catch: (
|
|
916
|
+
catch: (e) => e instanceof t ? e : f("The provider invoice could not be confirmed.")
|
|
573
917
|
});
|
|
574
|
-
let
|
|
575
|
-
return
|
|
576
|
-
}),
|
|
577
|
-
let
|
|
578
|
-
if (!
|
|
579
|
-
let
|
|
918
|
+
let l = yield* a(), u = yield* r.customers.getByProviderCustomerId(e.providerCustomerId, o);
|
|
919
|
+
return P.stores !== r || !m(l, e.account) || u === null || u.id !== e.id || u.tenantId !== e.tenantId ? yield* C.fail(f("Invoice account/customer custody changed during observation.", !0)) : c;
|
|
920
|
+
}), J = (e, n, r) => C.gen(function* () {
|
|
921
|
+
let i = P.stores;
|
|
922
|
+
if (!e || e.trim() !== e) return yield* C.fail(_("Exact tenant/customer identities are required."));
|
|
923
|
+
let a = yield* C.try({
|
|
580
924
|
try: () => {
|
|
581
|
-
let e =
|
|
582
|
-
...
|
|
925
|
+
let e = r?.cursor, t = e === void 0 ? void 0 : Object.freeze({
|
|
926
|
+
...p(e),
|
|
583
927
|
providerCustomerId: e.providerCustomerId,
|
|
584
928
|
afterInvoiceId: e.afterInvoiceId
|
|
585
|
-
}), n =
|
|
929
|
+
}), n = r?.limit;
|
|
586
930
|
return Object.freeze({
|
|
587
931
|
...t === void 0 ? {} : { cursor: t },
|
|
588
932
|
...n === void 0 ? {} : { limit: n }
|
|
589
933
|
});
|
|
590
934
|
},
|
|
591
|
-
catch: (
|
|
592
|
-
}),
|
|
593
|
-
try: () =>
|
|
594
|
-
account:
|
|
935
|
+
catch: (e) => e instanceof t ? e : _()
|
|
936
|
+
}), o = yield* L(), s = yield* C.try({
|
|
937
|
+
try: () => h({
|
|
938
|
+
account: o.account,
|
|
595
939
|
providerCustomerId: n,
|
|
596
|
-
...
|
|
940
|
+
...a
|
|
597
941
|
}),
|
|
598
|
-
catch: (
|
|
599
|
-
}),
|
|
600
|
-
if (
|
|
601
|
-
let
|
|
602
|
-
if (
|
|
603
|
-
let
|
|
604
|
-
if (!
|
|
605
|
-
let
|
|
606
|
-
try: () =>
|
|
607
|
-
catch: (
|
|
608
|
-
}),
|
|
609
|
-
return
|
|
610
|
-
}),
|
|
611
|
-
if (!e || e.trim() !== e || !t || t.trim() !== t) return yield*
|
|
942
|
+
catch: (e) => e instanceof t ? e : _()
|
|
943
|
+
}), c = yield* i.customers.getByProviderCustomerId(s.providerCustomerId, o);
|
|
944
|
+
if (c === null || c.tenantId !== e || c.provider !== S.name) return yield* C.fail(_("Positive current or retained customer custody is required."));
|
|
945
|
+
let l = S.listInvoiceHistory?.bind(S), u = S.fetchAccountIdentity?.bind(S);
|
|
946
|
+
if (l === void 0 || u === void 0) return yield* C.fail(_("Complete account-owned invoice history is unsupported."));
|
|
947
|
+
let d = yield* u();
|
|
948
|
+
if (!m(d, c.account)) return yield* C.fail(_("The provider account differs before invoice history access."));
|
|
949
|
+
let f = yield* M(l(s), T), v = yield* C.try({
|
|
950
|
+
try: () => g(s, f),
|
|
951
|
+
catch: (e) => e instanceof t ? e : _()
|
|
952
|
+
}), y = yield* u(), b = yield* i.customers.getByProviderCustomerId(s.providerCustomerId, o);
|
|
953
|
+
return P.stores !== i || !m(y, c.account) || b === null || b.id !== c.id || b.tenantId !== e ? yield* C.fail(_("Invoice history account/customer custody changed during observation.", !0)) : v;
|
|
954
|
+
}), $e = (e, t) => C.gen(function* () {
|
|
955
|
+
if (!e || e.trim() !== e || !t || t.trim() !== t) return yield* C.fail(f("Exact tenant/invoice identities are required."));
|
|
612
956
|
let n = yield* z(e);
|
|
613
|
-
return n === null ? yield*
|
|
614
|
-
}),
|
|
615
|
-
let r =
|
|
616
|
-
if (!e || e.trim() !== e || !t || t.trim() !== t) return yield*
|
|
617
|
-
let i = yield*
|
|
957
|
+
return n === null ? yield* C.fail(f("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(f("Exact tenant/invoice identities are required."));
|
|
961
|
+
let i = yield* L();
|
|
618
962
|
for (let a = 0; a < 3; a++) {
|
|
619
|
-
if (
|
|
963
|
+
if (P.stores !== r) return yield* C.fail(f("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*
|
|
965
|
+
if (a === null || a.tenantId !== e) return yield* C.fail(f("Positive current or retained customer custody is required.", !0));
|
|
622
966
|
let o = 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*
|
|
629
|
-
if (
|
|
630
|
-
if (!(yield* r.invoices.complete(o, c, l))) continue;
|
|
972
|
+
}), s = yield* r.invoices.capturePaymentEpoch(o), c = yield* r.invoices.get(o), l = yield* Qe(a, t, r);
|
|
973
|
+
if (P.stores !== r) return yield* C.fail(f("Billing stores changed before native invoice persistence.", !0));
|
|
974
|
+
if (!(yield* r.invoices.complete(o, c, l, s))) continue;
|
|
631
975
|
let u = yield* r.invoices.get(o);
|
|
632
|
-
return u === null || u.revision <= (c?.revision ?? 0) ? yield*
|
|
976
|
+
return u === null || u.revision <= (c?.revision ?? 0) ? yield* C.fail(f("Invoice persistence could not be confirmed.", !0)) : u;
|
|
633
977
|
}
|
|
634
|
-
return yield*
|
|
635
|
-
}),
|
|
978
|
+
return yield* C.fail(f("Concurrent invoice observation requires retry.", !0));
|
|
979
|
+
}), et = (e, n, r, i = () => C.void, a) => C.gen(function* () {
|
|
636
980
|
if (n === "free") {
|
|
637
|
-
let
|
|
981
|
+
let t = yield* tt(e, i, a);
|
|
638
982
|
return {
|
|
639
|
-
tenantId:
|
|
640
|
-
plan:
|
|
641
|
-
quantity:
|
|
642
|
-
prorationMinor:
|
|
643
|
-
currency:
|
|
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
|
|
990
|
+
return w.has(n) && w.priceIdFor(n) === null ? yield* C.fail(new t({
|
|
647
991
|
source: "billing",
|
|
648
992
|
message: `plan '${n}' has no provider price — it is not a self-serve plan`,
|
|
649
993
|
transient: !1
|
|
650
|
-
})) : yield*
|
|
651
|
-
}),
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
providerSubscriptionId:
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
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: n }, i, a);
|
|
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 = (n) => C.gen(function* () {
|
|
1016
|
+
yield* R(n), yield* fe(n);
|
|
1017
|
+
let r = () => new t({
|
|
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 (
|
|
685
|
-
yield*
|
|
686
|
-
let
|
|
687
|
-
if (
|
|
688
|
-
let
|
|
689
|
-
|
|
690
|
-
for (let e of
|
|
691
|
-
let
|
|
692
|
-
if (
|
|
693
|
-
let e = yield*
|
|
694
|
-
tenantId:
|
|
695
|
-
operationId:
|
|
696
|
-
...
|
|
697
|
-
}),
|
|
698
|
-
if (
|
|
699
|
-
if (e.observedAt === null || !Number.isFinite(e.observedAt.getTime()) || e.observedAt.getTime() <
|
|
700
|
-
yield*
|
|
1022
|
+
if (n.length === 0) return yield* C.fail(r());
|
|
1023
|
+
yield* Ke(n), yield* P.stores.subscriptionWrites.seal(n), yield* P.stores.closures.reserveAccount(n, S.name, k());
|
|
1024
|
+
let i = yield* z(n), a = yield* P.stores.checkouts.getActive(n);
|
|
1025
|
+
if (i !== null && i.provider !== S.name || a !== null && a.provider !== S.name || i !== null && a?.providerCustomerId !== null && a?.providerCustomerId !== void 0 && i.providerCustomerId !== a.providerCustomerId) return yield* C.fail(r());
|
|
1026
|
+
let o = /* @__PURE__ */ new Set();
|
|
1027
|
+
i !== null && o.add(i.providerCustomerId), a?.providerCustomerId && o.add(a.providerCustomerId);
|
|
1028
|
+
for (let e of o) yield* M(S.expireOpenCheckouts({ providerCustomerId: e }), T);
|
|
1029
|
+
let s = null;
|
|
1030
|
+
if (a !== null) {
|
|
1031
|
+
let e = yield* M(S.findCheckoutSession({
|
|
1032
|
+
tenantId: n,
|
|
1033
|
+
operationId: a.id,
|
|
1034
|
+
...a.providerCustomerId === null ? {} : { providerCustomerId: a.providerCustomerId }
|
|
1035
|
+
}), T), t = e.receipt;
|
|
1036
|
+
if (t === null) {
|
|
1037
|
+
if (e.observedAt === null || !Number.isFinite(e.observedAt.getTime()) || e.observedAt.getTime() < a.expiresAt.getTime()) return yield* C.fail(r());
|
|
1038
|
+
yield* P.stores.checkouts.patch(a.id, { phase: "expired" });
|
|
701
1039
|
} else {
|
|
702
|
-
if (
|
|
703
|
-
if (
|
|
704
|
-
providerCustomerId:
|
|
705
|
-
providerSessionId:
|
|
706
|
-
}),
|
|
707
|
-
if (
|
|
1040
|
+
if (t.operationId !== a.id || t.tenantId !== n || !t.id || t.providerCustomerId === null || t.expiresAt.getTime() !== a.expiresAt.getTime() || a.providerCustomerId !== null && t.providerCustomerId !== a.providerCustomerId || a.providerSessionId !== null && t.id !== a.providerSessionId) return yield* C.fail(r());
|
|
1041
|
+
if (o.add(t.providerCustomerId), yield* P.stores.checkouts.patch(a.id, {
|
|
1042
|
+
providerCustomerId: t.providerCustomerId,
|
|
1043
|
+
providerSessionId: t.id
|
|
1044
|
+
}), t.status === "open") return yield* M(S.expireOpenCheckouts({ providerCustomerId: t.providerCustomerId }), T), yield* C.fail(r());
|
|
1045
|
+
if (t.status === "expired") yield* P.stores.checkouts.patch(a.id, { phase: "expired" });
|
|
708
1046
|
else {
|
|
709
|
-
if (
|
|
710
|
-
|
|
1047
|
+
if (t.providerSubscriptionId === null) return yield* C.fail(r());
|
|
1048
|
+
s = t.providerSubscriptionId, yield* P.stores.checkouts.patch(a.id, { phase: "completed" });
|
|
711
1049
|
}
|
|
712
1050
|
}
|
|
713
1051
|
}
|
|
714
|
-
yield*
|
|
715
|
-
let
|
|
716
|
-
if (
|
|
717
|
-
let
|
|
718
|
-
|
|
719
|
-
for (let e of
|
|
720
|
-
let t = yield*
|
|
721
|
-
for (let e of t)
|
|
1052
|
+
yield* Me(n), yield* P.stores.closures.sealUsage(n);
|
|
1053
|
+
let c = yield* P.stores.usage.pending();
|
|
1054
|
+
if (S.supportsMeteredUsage && c.some((e) => e.tenantId === n && e.used > e.reportedToProvider)) return yield* C.fail(V());
|
|
1055
|
+
let l = yield* P.stores.subscriptions.listByTenant(n), u = new Set(l.filter((e) => x(e.status)).map((e) => e.providerSubscriptionId));
|
|
1056
|
+
s !== null && u.add(s);
|
|
1057
|
+
for (let e of o) {
|
|
1058
|
+
let t = yield* M(S.listSubscriptions({ providerCustomerId: e }), T);
|
|
1059
|
+
for (let e of t) u.add(e.providerSubscriptionId);
|
|
722
1060
|
}
|
|
723
|
-
let
|
|
724
|
-
for (let e of
|
|
725
|
-
let
|
|
726
|
-
if (
|
|
727
|
-
|
|
1061
|
+
let d = [], f = /* @__PURE__ */ new Set(), p = !1;
|
|
1062
|
+
for (let e of u) {
|
|
1063
|
+
let t = yield* M(S.fetchSubscription(e), T);
|
|
1064
|
+
if (t === null) {
|
|
1065
|
+
p = !0;
|
|
728
1066
|
continue;
|
|
729
1067
|
}
|
|
730
|
-
let i =
|
|
731
|
-
if (
|
|
732
|
-
let
|
|
733
|
-
if (
|
|
734
|
-
let
|
|
735
|
-
|
|
736
|
-
tenantId:
|
|
737
|
-
provider:
|
|
1068
|
+
let i = t;
|
|
1069
|
+
if (t.status !== "canceled") {
|
|
1070
|
+
let t = yield* P.stores.closures.getSubscription(n, e);
|
|
1071
|
+
if (t === null) {
|
|
1072
|
+
let r = yield* M(S.prepareSubscriptionClose(e), T);
|
|
1073
|
+
t = yield* P.stores.closures.reserveSubscription({
|
|
1074
|
+
tenantId: n,
|
|
1075
|
+
provider: S.name,
|
|
738
1076
|
providerSubscriptionId: e,
|
|
739
|
-
cancelAt:
|
|
740
|
-
createdAt:
|
|
1077
|
+
cancelAt: r.cancelAt,
|
|
1078
|
+
createdAt: k()
|
|
741
1079
|
});
|
|
742
1080
|
}
|
|
743
|
-
if (
|
|
744
|
-
i = yield*
|
|
1081
|
+
if (t.provider !== S.name || t.providerSubscriptionId !== e || t.cancelAt === null) return yield* C.fail(r());
|
|
1082
|
+
i = yield* M(S.cancelSubscription({
|
|
745
1083
|
providerSubscriptionId: e,
|
|
746
1084
|
mode: "close",
|
|
747
1085
|
closeOperation: {
|
|
748
|
-
id:
|
|
749
|
-
cancelAt:
|
|
1086
|
+
id: t.id,
|
|
1087
|
+
cancelAt: t.cancelAt
|
|
750
1088
|
}
|
|
751
|
-
}),
|
|
1089
|
+
}), T);
|
|
752
1090
|
}
|
|
753
|
-
yield*
|
|
1091
|
+
yield* W(n, {
|
|
754
1092
|
...i,
|
|
755
1093
|
providerSubscriptionId: e
|
|
756
|
-
},
|
|
1094
|
+
}, k()), i.status === "canceled" ? d.push(e) : f.add(e);
|
|
757
1095
|
}
|
|
758
|
-
for (let e of
|
|
759
|
-
if (
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
1096
|
+
for (let e of o) (yield* M(S.listSubscriptions({ providerCustomerId: e }), T)).some((e) => e.status !== "canceled" && !f.has(e.providerSubscriptionId)) && (p = !0);
|
|
1097
|
+
if (p) return yield* C.fail(r());
|
|
1098
|
+
if (f.size > 0) return yield* C.fail(new e({
|
|
1099
|
+
tenantId: n,
|
|
1100
|
+
reason: "cancellation-settling",
|
|
1101
|
+
providerInvoiceIds: [],
|
|
1102
|
+
message: "Billing closure is pending provider confirmation: subscriptions end after the meter settlement window."
|
|
1103
|
+
}));
|
|
1104
|
+
let m = yield* P.stores.usage.pending();
|
|
1105
|
+
if (S.supportsMeteredUsage && m.some((e) => e.tenantId === n && e.used > e.reportedToProvider)) return yield* C.fail(V());
|
|
1106
|
+
a !== null && s !== null && (yield* P.stores.checkouts.patch(a.id, { phase: "retired" }));
|
|
1107
|
+
let h = /* @__PURE__ */ new Set([...d, ...l.filter((e) => e.provider === S.name).map((e) => e.providerSubscriptionId)]), g = yield* it(n, [...h], i, r);
|
|
1108
|
+
return D.info("billing account closed", {
|
|
1109
|
+
tenant: n,
|
|
1110
|
+
canceled: d.length,
|
|
1111
|
+
finalInvoices: g.length
|
|
764
1112
|
}), {
|
|
1113
|
+
tenantId: n,
|
|
1114
|
+
canceled: d,
|
|
1115
|
+
finalInvoices: g
|
|
1116
|
+
};
|
|
1117
|
+
}), it = (t, n, r, i) => C.gen(function* () {
|
|
1118
|
+
let a = /* @__PURE__ */ new Set();
|
|
1119
|
+
for (let e of n) {
|
|
1120
|
+
let t = yield* X(e, r ?? void 0);
|
|
1121
|
+
if (t.status !== "canceled") return yield* C.fail(i());
|
|
1122
|
+
t.providerLatestInvoiceId && a.add(t.providerLatestInvoiceId);
|
|
1123
|
+
}
|
|
1124
|
+
if (a.size === 0) return [];
|
|
1125
|
+
if (r === null) return yield* C.fail(i());
|
|
1126
|
+
let o = (n, r) => new e({
|
|
765
1127
|
tenantId: t,
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
1128
|
+
reason: n,
|
|
1129
|
+
providerInvoiceIds: [...r],
|
|
1130
|
+
message: n === "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
|
+
}), s = yield* J(t, r.providerCustomerId, { limit: 100 }), c = [];
|
|
1132
|
+
for (let e of a) {
|
|
1133
|
+
let t = s.invoices.find((t) => t.providerInvoiceId === e);
|
|
1134
|
+
if (t === void 0) return yield* C.fail(i());
|
|
1135
|
+
t.status === "draft" && c.push(e);
|
|
1136
|
+
}
|
|
1137
|
+
if (c.length > 0) return yield* C.fail(o("final-invoice-draft", c));
|
|
1138
|
+
let l = [], u = [];
|
|
1139
|
+
for (let e of a) {
|
|
1140
|
+
let n = (yield* Y(t, e, r.providerCustomerId)).snapshot.status;
|
|
1141
|
+
n === "open" ? u.push(e) : l.push({
|
|
1142
|
+
providerInvoiceId: e,
|
|
1143
|
+
status: n
|
|
1144
|
+
});
|
|
1145
|
+
}
|
|
1146
|
+
return u.length > 0 ? yield* C.fail(o("final-invoice-open", u)) : l;
|
|
1147
|
+
}), at = (e) => C.gen(function* () {
|
|
1148
|
+
return (yield* P.stores.closures.getAccount(e)) === null ? n.isTenantClosed === void 0 ? !1 : yield* n.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) =>
|
|
774
|
-
let
|
|
775
|
-
if (
|
|
776
|
-
let
|
|
777
|
-
if (
|
|
778
|
-
let a = yield*
|
|
779
|
-
if (!
|
|
780
|
-
let o =
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
1152
|
+
}), !1)))), X = (e, t) => C.gen(function* () {
|
|
1153
|
+
let n = S.fetchSubscriptionSnapshot;
|
|
1154
|
+
if (n === void 0) return yield* C.fail(f("Customer-qualified subscription observations are required."));
|
|
1155
|
+
let r = yield* L(), i = S.fetchAccountIdentity;
|
|
1156
|
+
if (i === void 0) return yield* C.fail(f("Provider account observations are required."));
|
|
1157
|
+
let a = yield* i();
|
|
1158
|
+
if (!m(a, r.account)) return yield* C.fail(f("The provider account changed before subscription observation."));
|
|
1159
|
+
let o = P.stores, s = t === void 0 ? null : yield* o.customers.getByProviderCustomerId(t.providerCustomerId, r);
|
|
1160
|
+
if (t !== void 0 && (s === null || s.id !== t.id || s.tenantId !== t.tenantId)) return yield* C.fail(f("Native subscription customer custody changed."));
|
|
1161
|
+
let c = t === void 0 ? null : yield* o.invoices.capturePaymentEpoch({
|
|
1162
|
+
tenantId: t.tenantId,
|
|
1163
|
+
provider: r.provider,
|
|
1164
|
+
...r.account,
|
|
1165
|
+
providerCustomerId: t.providerCustomerId
|
|
1166
|
+
}), l = yield* M(n(e), T), u = yield* i();
|
|
1167
|
+
return !m(u, r.account) || l === null || l.providerSubscriptionId !== e || l.providerCustomerId === null || t !== void 0 && l.providerCustomerId !== t.providerCustomerId || P.stores !== o ? yield* C.fail(f("A complete subscription observation in the retained provider account is required.")) : {
|
|
1168
|
+
...l,
|
|
1169
|
+
providerAccount: p(r.account),
|
|
1170
|
+
paymentEpoch: c
|
|
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 o = yield* X(a.providerSubscriptionId, e);
|
|
1180
|
+
if (P.stores !== n) return yield* C.fail(f("Billing stores changed during current subscription refresh.", !0));
|
|
1181
|
+
if (yield* r()) return [];
|
|
1182
|
+
let s = k();
|
|
1183
|
+
yield* W(e.tenantId, o, s);
|
|
1184
|
+
let c = Q(e.tenantId, o, s);
|
|
1185
|
+
return yield* K(c), [c];
|
|
1186
|
+
}), ct = (e, n) => C.gen(function* () {
|
|
1187
|
+
let r = k(), i = yield* P.stores.customers.getByProviderCustomerId(e, yield* L());
|
|
784
1188
|
if (i !== null && i.retiredAt !== null) {
|
|
785
|
-
let
|
|
786
|
-
for (let n of yield*
|
|
787
|
-
let a = yield* X(n.providerSubscriptionId);
|
|
788
|
-
if (a.providerCustomerId !==
|
|
789
|
-
if (a.status !== "canceled") return yield*
|
|
790
|
-
let o = yield*
|
|
791
|
-
if (o === null || o.id !== i.id || o.tenantId !== i.tenantId || o.retiredAt === null) return yield*
|
|
792
|
-
yield*
|
|
1189
|
+
let t = [];
|
|
1190
|
+
for (let n of yield* P.stores.subscriptions.listByTenant(i.tenantId)) {
|
|
1191
|
+
let a = yield* X(n.providerSubscriptionId, i);
|
|
1192
|
+
if (a.providerCustomerId !== e) continue;
|
|
1193
|
+
if (a.status !== "canceled") return yield* C.fail(f("A retired customer still has an unsettled provider subscription."));
|
|
1194
|
+
let o = yield* P.stores.customers.getByProviderCustomerId(e, yield* L());
|
|
1195
|
+
if (o === null || o.id !== i.id || o.tenantId !== i.tenantId || o.retiredAt === null) return yield* C.fail(f("Retired customer custody changed during reconciliation."));
|
|
1196
|
+
yield* W(i.tenantId, a, r), t.push(Q(i.tenantId, a, r));
|
|
793
1197
|
}
|
|
794
|
-
for (let
|
|
1198
|
+
for (let e of t) yield* K(e);
|
|
795
1199
|
return {
|
|
796
1200
|
tenantId: i.tenantId,
|
|
797
|
-
events:
|
|
1201
|
+
events: t
|
|
798
1202
|
};
|
|
799
1203
|
}
|
|
800
|
-
let a = yield*
|
|
801
|
-
if (a.some((
|
|
1204
|
+
let a = yield* M(S.listSubscriptions({ providerCustomerId: e }), T);
|
|
1205
|
+
if (a.some((t) => t.providerCustomerId !== e)) return yield* C.fail(f("The subscription listing names another customer."));
|
|
802
1206
|
let o = i?.tenantId ?? n ?? a.find((e) => e.tenantId !== null)?.tenantId ?? null;
|
|
803
|
-
if (o === null) return
|
|
1207
|
+
if (o === 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
|
|
808
|
-
if (i !== null && i.provider !==
|
|
1211
|
+
let s = [], c = yield* z(o);
|
|
1212
|
+
if (i !== null && i.provider !== S.name || c !== null && (c.provider !== S.name || c.providerCustomerId !== e)) return yield* C.fail(new t({
|
|
809
1213
|
source: "billing.syncCustomer",
|
|
810
1214
|
message: "Customer discovery cannot replace existing native billing custody.",
|
|
811
1215
|
transient: !1
|
|
812
1216
|
}));
|
|
813
1217
|
if (i === null) {
|
|
814
|
-
if (yield*
|
|
815
|
-
yield* B(o,
|
|
1218
|
+
if (yield* at(o)) return yield* C.fail(f("Closed tenant customer custody requires reconciliation."));
|
|
1219
|
+
yield* B(o, e), s.push({
|
|
816
1220
|
_tag: "customerLinked",
|
|
817
1221
|
tenantId: o,
|
|
818
|
-
providerCustomerId:
|
|
1222
|
+
providerCustomerId: e,
|
|
819
1223
|
occurredAt: r
|
|
820
1224
|
});
|
|
821
1225
|
}
|
|
822
|
-
a.some((e) =>
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
1226
|
+
a.some((e) => O.has(e.status) && e.cancelAt === null) && (yield* ot(o)) && (D.error("billing sync: a closed tenant still has a paying subscription — closing it", { tenant: o }), yield* rt(o).pipe(C.catchTag("BillingClosurePending", (e) => C.fail(new t({
|
|
1227
|
+
source: "billing",
|
|
1228
|
+
message: e.message,
|
|
1229
|
+
transient: !0
|
|
1230
|
+
})))), a = yield* M(S.listSubscriptions({ providerCustomerId: e }), T));
|
|
1231
|
+
let l = yield* P.stores.customers.getByProviderCustomerId(e, yield* L());
|
|
1232
|
+
if (l === null || l.tenantId !== o) return yield* C.fail(f("Current native customer custody is required."));
|
|
1233
|
+
for (let t of a) {
|
|
1234
|
+
let n = yield* X(t.providerSubscriptionId, l);
|
|
1235
|
+
if (n.providerCustomerId !== e) return yield* C.fail(f("The current subscription belongs to another customer."));
|
|
1236
|
+
if (yield* W(o, n, r), s.push(Q(o, n, r)), n.plan !== null && O.has(n.status)) {
|
|
1237
|
+
let e = w.meteredPriceIdsFor(n.plan).filter((e) => !n.priceIds.includes(e));
|
|
1238
|
+
e.length > 0 && (yield* M(S.addSubscriptionPrices({
|
|
1239
|
+
providerSubscriptionId: n.providerSubscriptionId,
|
|
1240
|
+
priceIds: e
|
|
1241
|
+
}), T));
|
|
1242
|
+
}
|
|
829
1243
|
}
|
|
830
1244
|
let u = new Set(a.map((e) => e.providerSubscriptionId));
|
|
831
|
-
for (let
|
|
832
|
-
if (!
|
|
833
|
-
let n = yield* X(
|
|
834
|
-
if (n.providerCustomerId !==
|
|
835
|
-
yield*
|
|
1245
|
+
for (let t of yield* P.stores.subscriptions.listByTenant(o)) {
|
|
1246
|
+
if (!x(t.status) || u.has(t.providerSubscriptionId)) continue;
|
|
1247
|
+
let n = yield* X(t.providerSubscriptionId, l);
|
|
1248
|
+
if (n.providerCustomerId !== e) return yield* C.fail(f("The subscription belongs to another customer."));
|
|
1249
|
+
yield* W(o, n, r), s.push(Q(o, n, r));
|
|
836
1250
|
}
|
|
837
|
-
for (let e of
|
|
1251
|
+
for (let e of s) yield* K(e);
|
|
838
1252
|
return {
|
|
839
1253
|
tenantId: o,
|
|
840
|
-
events:
|
|
1254
|
+
events: s
|
|
841
1255
|
};
|
|
842
|
-
}),
|
|
843
|
-
let
|
|
844
|
-
return
|
|
845
|
-
|
|
1256
|
+
}), Z = (e) => C.forEach(e, (e) => {
|
|
1257
|
+
let t = n.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 }),
|
|
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*
|
|
854
|
-
yield*
|
|
1268
|
+
let n = yield* ct(t.providerCustomerId, e);
|
|
1269
|
+
yield* Z(n.events);
|
|
855
1270
|
}
|
|
856
|
-
return yield*
|
|
857
|
-
}),
|
|
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
|
-
},
|
|
874
|
-
let 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 ?
|
|
1291
|
+
return t === void 0 ? ot(e).pipe(C.tap((t) => C.sync(() => {
|
|
877
1292
|
l.set(e, t);
|
|
878
|
-
}))) :
|
|
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*
|
|
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,
|
|
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++,
|
|
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)),
|
|
902
|
-
|
|
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*
|
|
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
|
-
|
|
913
|
-
let h = yield*
|
|
914
|
-
|
|
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 &&
|
|
917
|
-
let e =
|
|
918
|
-
e.length > 0 && (yield*
|
|
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
|
-
}),
|
|
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*
|
|
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*
|
|
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*
|
|
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 >=
|
|
947
|
-
if (g)
|
|
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:
|
|
1368
|
+
provider: S.name
|
|
951
1369
|
});
|
|
952
|
-
else for (let t of h) yield*
|
|
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 _)
|
|
959
|
-
let
|
|
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
|
|
970
|
-
checked:
|
|
971
|
-
corrected:
|
|
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:
|
|
976
|
-
}), yield*
|
|
977
|
-
}),
|
|
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*
|
|
983
|
-
let r =
|
|
984
|
-
if (a === null || a.tenantId !== e || a.provider !==
|
|
985
|
-
let o = yield* r.historyWork.claim(a, n,
|
|
1400
|
+
].every((e) => typeof e == "string" && e.length > 0 && e.length <= 191 && e.trim() === e && e.isWellFormed())) return yield* C.fail(_("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(_("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, () =>
|
|
991
|
-
return yield*
|
|
992
|
-
if (
|
|
993
|
-
let n = yield*
|
|
994
|
-
if (
|
|
995
|
-
let i = yield* r.historyWork.observed(a, s, n,
|
|
996
|
-
return i === null || i.state !== "observed" && i.state !== "deferred" ? yield*
|
|
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(_("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(_("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(_("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(
|
|
1001
|
-
return yield* r.historyWork.failed(a, s,
|
|
1002
|
-
})),
|
|
1003
|
-
})
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
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(_("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(_("Billing stores changed during the invoice-history pass.", !0));
|
|
1423
|
+
if (S.listInvoiceHistory === void 0 || S.fetchInvoiceSnapshot === void 0) return yield* C.fail(_("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
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
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*
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
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 t ? e : _("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(f("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(f("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 n = S.fetchPrices;
|
|
1533
|
+
if (n === void 0) return yield* C.fail(new t({
|
|
1534
|
+
source: "billing",
|
|
1535
|
+
message: `Billing provider "${S.name}" cannot read prices.`,
|
|
1536
|
+
transient: !1
|
|
1537
|
+
}));
|
|
1538
|
+
let r = Date.now(), i = [...new Set(e)], a = i.filter((e) => {
|
|
1539
|
+
let t = _t.get(e);
|
|
1540
|
+
return t === void 0 || r - t.at > 6e4;
|
|
1541
|
+
}), o = a.filter((e) => !$.has(e)), s = [];
|
|
1542
|
+
if (o.length > 0) {
|
|
1543
|
+
let e = { fiber: null };
|
|
1544
|
+
for (let t of o) $.set(t, e);
|
|
1545
|
+
let t = yield* C.forkDetach(n(o).pipe(C.tap((e) => C.sync(() => {
|
|
1546
|
+
for (let t of o) _t.set(t, {
|
|
1547
|
+
at: r,
|
|
1548
|
+
price: e.find((e) => e.id === t) ?? null
|
|
1072
1549
|
});
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1550
|
+
})), C.asVoid, C.ensuring(C.sync(() => {
|
|
1551
|
+
for (let t of o) $.get(t) === e && $.delete(t);
|
|
1552
|
+
}))));
|
|
1553
|
+
e.fiber = t, s.push(t);
|
|
1554
|
+
}
|
|
1555
|
+
for (let e of a) {
|
|
1556
|
+
let t = $.get(e)?.fiber;
|
|
1557
|
+
t != null && !s.includes(t) && s.push(t);
|
|
1558
|
+
}
|
|
1559
|
+
return yield* C.forEach(s, (e) => ne.join(e), { discard: !0 }), i.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:
|
|
1598
|
+
holder: P
|
|
1113
1599
|
};
|
|
1114
|
-
},
|
|
1115
|
-
export { k as USAGE_KEY,
|
|
1600
|
+
}, ue = (e) => w.succeed(n, 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 };
|