@voltro/plugin-billing 0.85.0 → 0.86.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.
@@ -0,0 +1,209 @@
1
+ import { BillingError as e, DEFAULT_PLAN as t } from "./types.js";
2
+ import { Effect as n } from "effect";
3
+ import { and as r, eq as i, id as a, table as o, text as s, timestamp as c } from "@voltro/database";
4
+ //#region src/dunning.ts
5
+ var l = "_voltro_billing_dunning_notices", u = o(l, {
6
+ id: a({ prefix: "bdun" }),
7
+ tenantId: s().maxLength(191),
8
+ episode: s().maxLength(32),
9
+ stepId: s().maxLength(64),
10
+ sentAt: c()
11
+ }).unique("byBillingDunningNotice", [
12
+ "tenantId",
13
+ "episode",
14
+ "stepId"
15
+ ]), d = "locked", f = [
16
+ {
17
+ id: "payment-failed",
18
+ afterHours: 0
19
+ },
20
+ {
21
+ id: "reminder",
22
+ afterHours: 72
23
+ },
24
+ {
25
+ id: "final-warning",
26
+ afterHours: 144
27
+ }
28
+ ], p = 168, m = "hard", h = (e, t, n) => {
29
+ if (e === void 0 || e.trim() === "") return t;
30
+ let r = Number(e);
31
+ if (!Number.isFinite(r) || r < 0) throw Error(`billingPlugin: ${n} must be a non-negative number, got '${e}'`);
32
+ return r;
33
+ }, g = (e, t) => {
34
+ let n = t.VOLTRO_BILLING_DUNNING;
35
+ if (n !== void 0 && n !== "" && n !== "on" && n !== "off") throw Error(`billingPlugin: VOLTRO_BILLING_DUNNING must be 'on' or 'off', got '${n}'`);
36
+ let r = n === "off" ? !1 : n === "on" ? !0 : e?.enabled ?? !0, i = t.VOLTRO_BILLING_LOCKOUT;
37
+ if (i !== void 0 && i !== "" && i !== "hard" && i !== "soft") throw Error(`billingPlugin: VOLTRO_BILLING_LOCKOUT must be 'hard' or 'soft', got '${i}'`);
38
+ let a = i === "hard" || i === "soft" ? i : e?.lockout ?? "hard", o = h(t.VOLTRO_BILLING_GRACE_HOURS, e?.graceHours ?? 168, "VOLTRO_BILLING_GRACE_HOURS"), s = e?.steps ?? f, c = t.VOLTRO_BILLING_DUNNING_STEP_HOURS, l = s;
39
+ if (c !== void 0 && c.trim() !== "") {
40
+ let e = c.split(",").map((e) => e.trim());
41
+ if (e.length !== s.length) throw Error(`billingPlugin: VOLTRO_BILLING_DUNNING_STEP_HOURS lists ${e.length} value(s) but the sequence declares ${s.length} step(s) (${s.map((e) => e.id).join(", ")})`);
42
+ l = s.map((t, n) => ({
43
+ id: t.id,
44
+ afterHours: h(e[n], t.afterHours, "VOLTRO_BILLING_DUNNING_STEP_HOURS")
45
+ }));
46
+ }
47
+ let u = /* @__PURE__ */ new Set();
48
+ for (let e of l) {
49
+ if (e.id === "locked") throw Error(`billingPlugin: '${d}' is the reserved lockout step id`);
50
+ if (u.has(e.id)) throw Error(`billingPlugin: duplicate dunning step id '${e.id}'`);
51
+ u.add(e.id);
52
+ }
53
+ return {
54
+ enabled: r,
55
+ graceHours: o,
56
+ lockout: a,
57
+ steps: [...l].sort((e, t) => e.afterHours - t.afterHours),
58
+ ...e?.notify === void 0 ? {} : { notify: e.notify },
59
+ ...e?.resolveRecipient === void 0 ? {} : { resolveRecipient: e.resolveRecipient },
60
+ ...e?.portalReturnUrl === void 0 ? {} : { portalReturnUrl: e.portalReturnUrl }
61
+ };
62
+ }, _ = 36e5, v = (e) => String(e.getTime()), y = (e, t) => new Date(e.getTime() + t * _), b = (e, t, n) => {
63
+ let r = (n.getTime() - t.getTime()) / _;
64
+ return e.filter((e) => r >= e.afterHours);
65
+ }, x = (e, n, r, i) => {
66
+ let a = {
67
+ tenantId: e?.tenantId ?? i ?? "",
68
+ lockout: n.lockout
69
+ };
70
+ if (e === null) return {
71
+ ...a,
72
+ plan: t,
73
+ billedPlan: t,
74
+ status: "none",
75
+ entitled: !0,
76
+ inGrace: !1,
77
+ graceEndsAt: null,
78
+ lockedSince: null
79
+ };
80
+ if (e.status === "active" || e.status === "trialing") return {
81
+ ...a,
82
+ plan: e.plan,
83
+ billedPlan: e.plan,
84
+ status: e.status,
85
+ entitled: !0,
86
+ inGrace: !1,
87
+ graceEndsAt: null,
88
+ lockedSince: null
89
+ };
90
+ if (e.status === "pastDue") {
91
+ if (!n.enabled) return {
92
+ ...a,
93
+ plan: t,
94
+ billedPlan: e.plan,
95
+ status: e.status,
96
+ entitled: !0,
97
+ inGrace: !1,
98
+ graceEndsAt: null,
99
+ lockedSince: null
100
+ };
101
+ if (e.pastDueSince === null) return {
102
+ ...a,
103
+ plan: e.plan,
104
+ billedPlan: e.plan,
105
+ status: e.status,
106
+ entitled: !0,
107
+ inGrace: !0,
108
+ graceEndsAt: null,
109
+ lockedSince: null
110
+ };
111
+ let i = y(e.pastDueSince, n.graceHours), o = r.getTime() >= i.getTime();
112
+ return {
113
+ ...a,
114
+ plan: o && n.lockout === "hard" ? t : e.plan,
115
+ billedPlan: e.plan,
116
+ status: e.status,
117
+ entitled: !o,
118
+ inGrace: !o,
119
+ graceEndsAt: i,
120
+ lockedSince: o ? i : null
121
+ };
122
+ }
123
+ return {
124
+ ...a,
125
+ plan: t,
126
+ billedPlan: e.plan,
127
+ status: e.status,
128
+ entitled: !0,
129
+ inGrace: !1,
130
+ graceEndsAt: null,
131
+ lockedSince: null
132
+ };
133
+ }, S = (e) => e.toISOString().slice(0, 10), C = (e) => {
134
+ let t = e.portalUrl, n = t === null ? "<p>Please update your payment method in the billing settings.</p>" : `<p><a href="${t}">Update your payment method</a></p>`, r = t === null ? "Please update your payment method in the billing settings." : `Update your payment method: ${t}`;
135
+ if (e.locked) return {
136
+ subject: "Your subscription has been suspended",
137
+ html: `<p>We were unable to collect payment, and your subscription is now suspended.</p>${n}`,
138
+ text: `We were unable to collect payment, and your subscription is now suspended.\n\n${r}`
139
+ };
140
+ let i = S(e.graceEndsAt), a = e.stepId === "payment-failed" ? "Your last payment could not be collected." : "Your payment is still outstanding.";
141
+ return {
142
+ subject: "Action needed: your payment could not be collected",
143
+ html: `<p>${a} Your subscription stays active until ${i}.</p>${n}`,
144
+ text: `${a} Your subscription stays active until ${i}.\n\n${r}`
145
+ };
146
+ }, w = (e) => (t) => t.to === null ? n.void : e.send({
147
+ to: t.to,
148
+ subject: t.subject,
149
+ html: t.html,
150
+ text: t.text
151
+ }).pipe(n.asVoid), T = (e, t, n) => `${e}\u0000${t}\u0000${n}`, E = () => {
152
+ let e = /* @__PURE__ */ new Map();
153
+ return {
154
+ claim: (t, r, i, a) => n.sync(() => {
155
+ let n = T(t, r, i);
156
+ return !e.has(n) && (e.set(n, {
157
+ tenantId: t,
158
+ episode: r,
159
+ stepId: i,
160
+ sentAt: a
161
+ }), !0);
162
+ }),
163
+ sentSteps: (t, r) => n.sync(() => [...e.values()].filter((e) => e.tenantId === t && e.episode === r))
164
+ };
165
+ }, D = () => `bdun_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`, O = (t) => ({
166
+ claim: (r, i, a, o) => n.tryPromise({
167
+ try: async () => {
168
+ let e = D(), n = await t.insertIgnore(l, {
169
+ id: e,
170
+ tenantId: r,
171
+ episode: i,
172
+ stepId: a,
173
+ sentAt: o
174
+ }, { conflictColumns: [
175
+ "tenantId",
176
+ "episode",
177
+ "stepId"
178
+ ] });
179
+ return String(n.id) === e;
180
+ },
181
+ catch: (t) => new e({
182
+ source: "dunningNoticeStore",
183
+ message: String(t?.message ?? t),
184
+ transient: !0
185
+ })
186
+ }),
187
+ sentSteps: (a, o) => n.tryPromise({
188
+ try: async () => (await t.query({
189
+ table: l,
190
+ predicate: r(i("tenantId", a), i("episode", o)),
191
+ order: [],
192
+ take: void 0,
193
+ skip: void 0,
194
+ projection: void 0
195
+ })).map((e) => ({
196
+ tenantId: String(e.tenantId),
197
+ episode: String(e.episode),
198
+ stepId: String(e.stepId),
199
+ sentAt: e.sentAt == null ? null : new Date(e.sentAt)
200
+ })),
201
+ catch: (t) => new e({
202
+ source: "dunningNoticeStore",
203
+ message: String(t?.message ?? t),
204
+ transient: !0
205
+ })
206
+ })
207
+ });
208
+ //#endregion
209
+ export { l as BILLING_DUNNING_NOTICES_TABLE, f as DEFAULT_DUNNING_STEPS, p as DEFAULT_GRACE_HOURS, m as DEFAULT_LOCKOUT, d as DUNNING_LOCK_STEP_ID, u as billingDunningNoticesTable, O as dataStoreDunningNoticeStore, C as defaultDunningEmail, b as dueSteps, w as dunningMailNotifier, v as episodeKeyOf, x as evaluateBillingEntitlement, y as graceEndOf, E as memoryDunningNoticeStore, g as resolveDunningConfig };
@@ -0,0 +1,41 @@
1
+ import { BillingService as e, EntitlementExceeded as t, SubscriptionLocked as n } from "./types.js";
2
+ import { Effect as r } from "effect";
3
+ //#region src/entitlement.ts
4
+ var i = (e, t, n, r) => ({
5
+ allowed: !Number.isFinite(t) || r <= 0 || n + r <= t,
6
+ entitlement: e,
7
+ limit: t,
8
+ used: n,
9
+ cost: r
10
+ }), a = (e) => e.tenantId, o = (n, i, o) => r.gen(function* () {
11
+ let s = a(n.request.subject);
12
+ if (s === null) return o <= 0 ? void 0 : yield* r.fail(new t({
13
+ entitlement: i,
14
+ limit: 0,
15
+ used: 0,
16
+ cost: o
17
+ }));
18
+ yield* (yield* e).consumeEntitlement(s, i, o);
19
+ }), s = (t) => r.gen(function* () {
20
+ let i = a(t.request.subject);
21
+ if (i === null) return;
22
+ let o = yield* (yield* e).entitlementStatus(i);
23
+ if (!o.entitled) return yield* r.fail(new n({
24
+ tenantId: i,
25
+ status: o.status,
26
+ lockedSince: (o.lockedSince ?? /* @__PURE__ */ new Date()).toISOString(),
27
+ lockout: o.lockout
28
+ }));
29
+ }), c = (e, n) => (i, a) => {
30
+ let o = e[a.tag];
31
+ if (o === void 0) return i;
32
+ let s = o.cost ?? 1, c = a.subject.tenantId;
33
+ return c === null ? s <= 0 ? i : r.fail(new t({
34
+ entitlement: o.entitlement,
35
+ limit: 0,
36
+ used: 0,
37
+ cost: s
38
+ })) : r.flatMap(n.consumeEntitlement(c, o.entitlement, s), () => i);
39
+ };
40
+ //#endregion
41
+ export { c as buildEnforceInterceptor, i as evaluateEntitlement, s as requireEntitled, o as requireEntitlement };
@@ -0,0 +1,20 @@
1
+ import { id as e, table as t, text as n, timestamp as r } from "@voltro/database";
2
+ //#region src/flushClaim.ts
3
+ var i = "_voltro_billing_flush_claims", a = t(i, {
4
+ id: e({ scheme: "numeric" }),
5
+ windowKey: n(),
6
+ claimedBy: n(),
7
+ claimedAt: r().default("now")
8
+ }).unique("billingFlushClaimWindow", ["windowKey"]), o = (e, t) => `billing-flush:${Math.floor(e / Math.max(1, t))}`, s = async (e, t, n, r) => {
9
+ try {
10
+ return (await e.insertIgnore(i, {
11
+ windowKey: t,
12
+ claimedBy: n,
13
+ claimedAt: new Date(r)
14
+ }, { conflictColumns: ["windowKey"] })).claimedBy === n;
15
+ } catch {
16
+ return !0;
17
+ }
18
+ };
19
+ //#endregion
20
+ export { i as BILLING_FLUSH_CLAIMS_TABLE, a as billingFlushClaimsTable, s as claimFlushWindow, o as flushWindowKey };