@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.
@@ -0,0 +1,64 @@
1
+ import { Schema as e } from "effect";
2
+ // src/invoicePaymentObservation.ts
3
+ var t = e.Number.check(e.makeFilter((e) => Number.isSafeInteger(e) && e >= 0)), n = e.Number.check(e.makeFilter((e) => Number.isSafeInteger(e))), r = e.NonEmptyString, i = e.Struct({
4
+ providerRefundId: r,
5
+ amountMinor: t,
6
+ currency: e.String,
7
+ status: e.NullOr(e.String)
8
+ }), a = e.Struct({
9
+ providerChargeId: r,
10
+ providerPaymentIntentId: e.NullOr(r),
11
+ providerCustomerId: r,
12
+ paymentIntentStatus: e.NullOr(e.String),
13
+ paymentIntentReceivedMinor: e.NullOr(t),
14
+ livemode: e.Boolean,
15
+ currency: e.String,
16
+ amountMinor: t,
17
+ capturedMinor: t,
18
+ refundedMinor: t,
19
+ paid: e.Boolean,
20
+ captured: e.Boolean,
21
+ disputed: e.Boolean,
22
+ refunds: e.Array(i)
23
+ }), o = e.Struct({
24
+ protocol: e.Literal("voltro.invoice-payments.v1"),
25
+ providerInvoiceId: r,
26
+ providerCustomerId: r,
27
+ livemode: e.Boolean,
28
+ currency: e.String,
29
+ prePaymentCreditNotesMinor: t,
30
+ postPaymentCreditNotesMinor: t,
31
+ invoiceTotalMinor: e.optionalKey(e.NullOr(n)),
32
+ startingBalanceMinor: e.optionalKey(e.NullOr(n)),
33
+ endingBalanceMinor: e.optionalKey(e.NullOr(n)),
34
+ observedAt: e.DateFromString,
35
+ payments: e.Array(e.Struct({
36
+ providerInvoicePaymentId: r,
37
+ sourceType: r,
38
+ sourceId: e.NullOr(r),
39
+ status: e.Literals([
40
+ "open",
41
+ "paid",
42
+ "canceled"
43
+ ]),
44
+ amountPaidMinor: e.NullOr(t),
45
+ paidAt: e.NullOr(e.DateFromString),
46
+ cash: e.NullOr(a)
47
+ }))
48
+ }), s = (t) => {
49
+ if (!e.is(o)(t) || t.payments.length > 1e4 || !/^[a-z]{3}$/.test(t.currency) || !Number.isSafeInteger(t.observedAt.getTime())) throw c();
50
+ let n = /* @__PURE__ */ new Set();
51
+ for (let e of t.payments) {
52
+ if (n.has(e.providerInvoicePaymentId) || e.status === "paid" && (e.amountPaidMinor === null || e.paidAt === null) || e.paidAt !== null && !Number.isSafeInteger(e.paidAt.getTime())) throw c();
53
+ n.add(e.providerInvoicePaymentId);
54
+ let r = e.cash;
55
+ if (r === null) continue;
56
+ if (r.providerCustomerId !== t.providerCustomerId || r.livemode !== t.livemode || r.currency !== t.currency || r.capturedMinor > r.amountMinor || r.refundedMinor > r.capturedMinor || r.refunds.length > 1e4 || e.sourceType === "payment_intent" && (r.providerPaymentIntentId !== e.sourceId || r.paymentIntentStatus === null || r.paymentIntentReceivedMinor === null) || e.sourceType === "charge" && (r.providerChargeId !== e.sourceId || r.providerPaymentIntentId !== null || r.paymentIntentStatus !== null || r.paymentIntentReceivedMinor !== null) || !["charge", "payment_intent"].includes(e.sourceType)) throw c();
57
+ let i = /* @__PURE__ */ new Set();
58
+ for (let e of r.refunds) {
59
+ if (i.has(e.providerRefundId) || e.currency !== t.currency) throw c();
60
+ i.add(e.providerRefundId);
61
+ }
62
+ }
63
+ }, c = () => /* @__PURE__ */ TypeError("Complete invoice payment observations require exact identities, amounts and source ownership.");
64
+ export { o as InvoicePaymentObservationSchema, s as assertInvoicePaymentObservation };
@@ -1,65 +1,75 @@
1
1
  import { BillingError as e } from "./types.js";
2
- import { Schema as t } from "effect";
2
+ import { InvoicePaymentObservationSchema as t, assertInvoicePaymentObservation as n } from "./invoicePaymentObservation.js";
3
+ import { Schema as r } from "effect";
3
4
  // src/invoiceSnapshot.ts
4
- var n = (t, n = !1) => new e({
5
+ var i = (t, n = !1) => new e({
5
6
  source: "invoiceSnapshot",
6
7
  message: t,
7
8
  transient: n
8
- }), r = (e) => typeof e == "string" && e.length > 0 && e.trim() === e, i = (e) => e === null || r(e), a = (e) => e instanceof Date && Number.isSafeInteger(e.getTime()), o = (e) => Number.isSafeInteger(e) && e >= 0, s = t.Struct({
9
- providerInvoiceId: t.String,
10
- providerCustomerId: t.String,
11
- providerSubscriptionId: t.NullOr(t.String),
12
- providerRevisionId: t.NullOr(t.String),
13
- status: t.Literals([
9
+ }), a = (e) => typeof e == "string" && e.length > 0 && e.trim() === e, o = (e) => e === null || a(e), s = (e) => e instanceof Date && Number.isSafeInteger(e.getTime()), c = (e) => Number.isSafeInteger(e) && e >= 0, l = r.Struct({
10
+ paymentObservation: r.optionalKey(r.NullOr(t)),
11
+ providerInvoiceId: r.String,
12
+ providerCustomerId: r.String,
13
+ providerSubscriptionId: r.NullOr(r.String),
14
+ providerRevisionId: r.NullOr(r.String),
15
+ status: r.Literals([
14
16
  "open",
15
17
  "paid",
16
18
  "uncollectible",
17
19
  "void"
18
20
  ]),
19
- livemode: t.Boolean,
20
- currency: t.String,
21
- amountDueMinor: t.Number,
22
- amountPaidMinor: t.Number,
23
- amountRemainingMinor: t.Number,
24
- finalizedAt: t.DateFromString,
25
- paidAt: t.NullOr(t.DateFromString),
26
- observedAt: t.DateFromString,
27
- lines: t.Array(t.Struct({
28
- providerLineId: t.String,
29
- providerSubscriptionId: t.NullOr(t.String),
30
- providerSubscriptionItemId: t.NullOr(t.String),
31
- providerPriceId: t.NullOr(t.String),
32
- amountMinor: t.Number,
33
- currency: t.String,
34
- quantityDecimal: t.NullOr(t.String),
35
- periodStart: t.DateFromString,
36
- periodEnd: t.DateFromString,
37
- proration: t.NullOr(t.Boolean)
21
+ livemode: r.Boolean,
22
+ currency: r.String,
23
+ amountDueMinor: r.Number,
24
+ amountPaidMinor: r.Number,
25
+ amountRemainingMinor: r.Number,
26
+ finalizedAt: r.DateFromString,
27
+ paidAt: r.NullOr(r.DateFromString),
28
+ observedAt: r.DateFromString,
29
+ lines: r.Array(r.Struct({
30
+ providerLineId: r.String,
31
+ providerSubscriptionId: r.NullOr(r.String),
32
+ providerSubscriptionItemId: r.NullOr(r.String),
33
+ providerPriceId: r.NullOr(r.String),
34
+ amountMinor: r.Number,
35
+ currency: r.String,
36
+ quantityDecimal: r.NullOr(r.String),
37
+ periodStart: r.DateFromString,
38
+ periodEnd: r.DateFromString,
39
+ proration: r.NullOr(r.Boolean)
38
40
  }))
39
- }), c = t.Struct({
40
- protocol: t.Literal("voltro.invoice-observation.v1"),
41
- snapshot: s
42
- }), l = (e) => (d(e), t.encodeUnknownSync(c)({
41
+ }), u = r.Struct({
42
+ protocol: r.Literal("voltro.invoice-observation.v1"),
43
+ snapshot: l
44
+ }), d = (e) => (p(e), r.encodeUnknownSync(u)({
43
45
  protocol: "voltro.invoice-observation.v1",
44
46
  snapshot: e
45
- })), u = (e) => {
47
+ })), f = (e) => {
46
48
  try {
47
- let n = t.decodeUnknownSync(c)(e).snapshot;
48
- return d(n), n;
49
+ let t = r.decodeUnknownSync(u)(e).snapshot, n = {
50
+ ...t,
51
+ paymentObservation: t.paymentObservation ?? null
52
+ };
53
+ return p(n), n;
49
54
  } catch {
50
- throw n("The stored complete invoice observation could not be confirmed.");
55
+ throw i("The stored complete invoice observation could not be confirmed.");
51
56
  }
52
- }, d = (e) => {
53
- if (!r(e.providerInvoiceId) || !r(e.providerCustomerId) || !i(e.providerSubscriptionId) || !i(e.providerRevisionId) || ![
57
+ }, p = (e) => {
58
+ if (!a(e.providerInvoiceId) || !a(e.providerCustomerId) || !o(e.providerSubscriptionId) || !o(e.providerRevisionId) || ![
54
59
  "open",
55
60
  "paid",
56
61
  "uncollectible",
57
62
  "void"
58
- ].includes(e.status) || typeof e.livemode != "boolean" || !/^[a-z]{3}$/.test(e.currency) || !o(e.amountDueMinor) || !o(e.amountPaidMinor) || !o(e.amountRemainingMinor) || !a(e.finalizedAt) || !a(e.observedAt) || e.paidAt !== null && (!a(e.paidAt) || e.paidAt < e.finalizedAt) || e.status === "paid" && e.paidAt === null || !Array.isArray(e.lines) || e.lines.length > 1e4) throw n("A complete finalized invoice observation is required.");
63
+ ].includes(e.status) || typeof e.livemode != "boolean" || !/^[a-z]{3}$/.test(e.currency) || !c(e.amountDueMinor) || !c(e.amountPaidMinor) || !c(e.amountRemainingMinor) || !s(e.finalizedAt) || !s(e.observedAt) || e.paidAt !== null && (!s(e.paidAt) || e.paidAt < e.finalizedAt) || e.status === "paid" && e.paidAt === null || !Array.isArray(e.lines) || e.lines.length > 1e4) throw i("A complete finalized invoice observation is required.");
64
+ if (e.paymentObservation !== null) try {
65
+ if (n(e.paymentObservation), e.paymentObservation.providerInvoiceId !== e.providerInvoiceId || e.paymentObservation.providerCustomerId !== e.providerCustomerId || e.paymentObservation.currency !== e.currency || e.paymentObservation.livemode !== e.livemode) throw TypeError("Invoice payment identity mismatch.");
66
+ } catch {
67
+ throw i("Invoice payment observations must match the complete invoice ownership.");
68
+ }
59
69
  let t = /* @__PURE__ */ new Set();
60
- for (let o of e.lines) {
61
- if (!r(o.providerLineId) || t.has(o.providerLineId) || !i(o.providerSubscriptionId) || !i(o.providerSubscriptionItemId) || !i(o.providerPriceId) || !Number.isSafeInteger(o.amountMinor) || o.currency !== e.currency || o.quantityDecimal !== null && (typeof o.quantityDecimal != "string" || !/^\d+(?:\.\d{1,12})?$/.test(o.quantityDecimal)) || !a(o.periodStart) || !a(o.periodEnd) || o.periodEnd < o.periodStart || o.proration !== null && typeof o.proration != "boolean") throw n("Invoice lines must retain exact identities, money and periods.");
62
- t.add(o.providerLineId);
70
+ for (let n of e.lines) {
71
+ if (!a(n.providerLineId) || t.has(n.providerLineId) || !o(n.providerSubscriptionId) || !o(n.providerSubscriptionItemId) || !o(n.providerPriceId) || !Number.isSafeInteger(n.amountMinor) || n.currency !== e.currency || n.quantityDecimal !== null && (typeof n.quantityDecimal != "string" || !/^\d+(?:\.\d{1,12})?$/.test(n.quantityDecimal)) || !s(n.periodStart) || !s(n.periodEnd) || n.periodEnd < n.periodStart || n.proration !== null && typeof n.proration != "boolean") throw i("Invoice lines must retain exact identities, money and periods.");
72
+ t.add(n.providerLineId);
63
73
  }
64
74
  };
65
- export { d as assertInvoiceSnapshot, u as decodeInvoiceSnapshot, l as encodeInvoiceSnapshot, n as invoiceSnapshotError };
75
+ export { p as assertInvoiceSnapshot, f as decodeInvoiceSnapshot, d as encodeInvoiceSnapshot, i as invoiceSnapshotError };
@@ -1,48 +1,58 @@
1
1
  import { BillingError as e } from "./types.js";
2
- import { decodeInvoiceSnapshot as t, encodeInvoiceSnapshot as n, invoiceSnapshotError as r } from "./invoiceSnapshot.js";
3
- import { Effect as i } from "effect";
4
- import { and as a, eq as o, id as s, integer as c, json as l, table as u, text as d, timestamp as f } from "@voltro/database";
2
+ import { captureInvoicePaymentEpoch as t, currentInvoicePaymentEpoch as n, invalidateInvoicePayments as r, withInvoicePaymentEpoch as i } from "./invoicePaymentEpoch.js";
3
+ import { decodeInvoiceSnapshot as a, encodeInvoiceSnapshot as o, invoiceSnapshotError as s } from "./invoiceSnapshot.js";
4
+ import { Effect as c } from "effect";
5
+ import { and as l, eq as u, id as d, integer as f, json as p, table as m, text as h, timestamp as g } from "@voltro/database";
6
+ import "@voltro/runtime";
5
7
  // src/invoiceStore.ts
6
- var p = "_voltro_billing_account_invoices", m = u("_voltro_billing_invoice_observations", {
7
- id: s({ prefix: "binvobs" }),
8
- tenantId: d(),
9
- provider: d(),
10
- providerInvoiceId: d(),
11
- providerCustomerId: d(),
12
- identityKey: d().maxLength(64),
13
- revision: c(),
14
- providerSnapshot: l().serverOnly(),
15
- createdAt: f()
16
- }).index("byBillingInvoiceObservationTenant", ["tenantId"]).unique("byBillingInvoiceObservationIdentity", ["identityKey"]), h = u(p, {
17
- id: s({ prefix: "binvobs" }),
18
- tenantId: d(),
19
- provider: d(),
20
- providerAccountId: d().maxLength(191),
21
- livemode: c(),
22
- providerInvoiceId: d(),
23
- providerCustomerId: d(),
24
- identityKey: d().maxLength(64),
25
- revision: c(),
26
- providerSnapshot: l().serverOnly(),
27
- createdAt: f()
28
- }).index("byBillingAccountInvoiceTenant", ["tenantId"]).unique("byBillingAccountInvoiceIdentity", ["identityKey"]), g = 2147483647, _ = (e) => typeof e == "string" && e.length > 0 && e.trim() === e, v = (e, t) => ({
29
- table: p,
8
+ var _ = "_voltro_billing_account_invoices", v = m("_voltro_billing_invoice_observations", {
9
+ id: d({ prefix: "binvobs" }),
10
+ tenantId: h(),
11
+ provider: h(),
12
+ providerInvoiceId: h(),
13
+ providerCustomerId: h(),
14
+ identityKey: h().maxLength(64),
15
+ revision: f(),
16
+ providerSnapshot: p().serverOnly(),
17
+ createdAt: g()
18
+ }).index("byBillingInvoiceObservationTenant", ["tenantId"]).unique("byBillingInvoiceObservationIdentity", ["identityKey"]), y = m(_, {
19
+ id: d({ prefix: "binvobs" }),
20
+ tenantId: h(),
21
+ provider: h(),
22
+ providerAccountId: h().maxLength(191),
23
+ livemode: f(),
24
+ providerInvoiceId: h(),
25
+ providerCustomerId: h(),
26
+ identityKey: h().maxLength(64),
27
+ revision: f(),
28
+ providerSnapshot: p().serverOnly(),
29
+ paymentHeadId: h().nullable().serverOnly(),
30
+ paymentEpoch: f().nullable().serverOnly(),
31
+ createdAt: g()
32
+ }).index("byBillingAccountInvoiceTenant", ["tenantId"]).index("byBillingInvoicePaymentCustomer", [
33
+ "provider",
34
+ "providerAccountId",
35
+ "livemode",
36
+ "providerCustomerId",
37
+ "paymentEpoch"
38
+ ]).unique("byBillingAccountInvoiceIdentity", ["identityKey"]), b = 2147483647, x = (e) => typeof e == "string" && e.length > 0 && e.trim() === e, S = (e, t) => ({
39
+ table: _,
30
40
  predicate: e,
31
41
  order: [],
32
42
  take: t,
33
43
  skip: void 0,
34
44
  projection: void 0
35
- }), y = (t) => i.tryPromise({
45
+ }), C = (t) => c.tryPromise({
36
46
  try: t,
37
- catch: (t) => t instanceof e ? t : r("The native invoice observation could not be persisted or read.", !0)
38
- }), b = (e) => {
47
+ catch: (t) => t instanceof e ? t : s("The native invoice observation could not be persisted or read.", !0)
48
+ }), w = (e) => {
39
49
  if (![
40
50
  e.tenantId,
41
51
  e.provider,
42
52
  e.providerAccountId,
43
53
  e.providerCustomerId,
44
54
  e.providerInvoiceId
45
- ].every(_) || typeof e.livemode != "boolean") throw r("A valid customer-bound invoice identity is required.");
55
+ ].every(x) || typeof e.livemode != "boolean") throw s("A valid customer-bound invoice identity is required.");
46
56
  return Object.freeze({
47
57
  tenantId: e.tenantId,
48
58
  provider: e.provider,
@@ -51,7 +61,7 @@ var p = "_voltro_billing_account_invoices", m = u("_voltro_billing_invoice_obser
51
61
  providerCustomerId: e.providerCustomerId,
52
62
  providerInvoiceId: e.providerInvoiceId
53
63
  });
54
- }, x = async (e) => {
64
+ }, T = async (e) => {
55
65
  let t = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify([
56
66
  "voltro.account-invoice-observation.v1",
57
67
  e.provider,
@@ -60,73 +70,97 @@ var p = "_voltro_billing_account_invoices", m = u("_voltro_billing_invoice_obser
60
70
  e.providerInvoiceId
61
71
  ])));
62
72
  return [...new Uint8Array(t)].map((e) => e.toString(16).padStart(2, "0")).join("");
63
- }, S = (e, t) => e.tenantId === t.tenantId && e.provider === t.provider && e.providerAccountId === t.providerAccountId && e.livemode === t.livemode && e.providerCustomerId === t.providerCustomerId && e.providerInvoiceId === t.providerInvoiceId, C = (e, t) => {
64
- if (!S(e, t)) throw r("The invoice is bound to a different tenant or billing customer.");
65
- }, w = (e) => {
66
- let n = e.tenantId, i = e.provider, a = e.providerInvoiceId, o = e.providerAccountId, s = e.livemode, c = e.providerCustomerId, l = e.identityKey, u = e.revision, d = e.id;
67
- if (!_(n) || !_(i) || !_(a) || !_(c) || !_(d) || !_(o) || s !== 0 && s !== 1 || typeof l != "string" || !/^[0-9a-f]{64}$/.test(l) || typeof u != "number" || !Number.isInteger(u) || u < 1 || u > g) throw r("The native invoice observation identity is invalid.");
68
- let f = t(e.providerSnapshot);
69
- if (f.providerCustomerId !== c || f.providerInvoiceId !== a || f.livemode !== (s === 1)) throw r("The stored observation has a different customer or invoice.");
73
+ }, E = (e, t) => e.tenantId === t.tenantId && e.provider === t.provider && e.providerAccountId === t.providerAccountId && e.livemode === t.livemode && e.providerCustomerId === t.providerCustomerId && e.providerInvoiceId === t.providerInvoiceId, D = (e, t) => {
74
+ if (!E(e, t)) throw s("The invoice is bound to a different tenant or billing customer.");
75
+ }, O = (e) => {
76
+ let n = e.tenantId, r = e.provider, i = e.providerInvoiceId, o = e.providerAccountId, c = e.livemode, l = e.providerCustomerId, u = e.identityKey, d = e.revision, f = e.id;
77
+ if (!x(n) || !x(r) || !x(i) || !x(l) || !x(f) || !x(o) || c !== 0 && c !== 1 || typeof u != "string" || !/^[0-9a-f]{64}$/.test(u) || typeof d != "number" || !Number.isInteger(d) || d < 1 || d > b) throw s("The native invoice observation identity is invalid.");
78
+ let p = a(e.providerSnapshot);
79
+ if (p.providerCustomerId !== l || p.providerInvoiceId !== i || p.livemode !== (c === 1)) throw s("The stored observation has a different customer or invoice.");
80
+ let m = e.paymentHeadId == null && e.paymentEpoch == null ? null : t({
81
+ headId: e.paymentHeadId,
82
+ epoch: e.paymentEpoch
83
+ });
70
84
  return {
71
- id: d,
85
+ id: f,
72
86
  tenantId: n,
73
- provider: i,
87
+ provider: r,
74
88
  providerAccountId: o,
75
- livemode: s === 1,
76
- providerInvoiceId: a,
77
- providerCustomerId: c,
78
- identityKey: l,
79
- revision: u,
80
- snapshot: f
89
+ livemode: c === 1,
90
+ providerInvoiceId: i,
91
+ providerCustomerId: l,
92
+ identityKey: u,
93
+ revision: d,
94
+ snapshot: p,
95
+ paymentEpoch: m
81
96
  };
82
- }, T = (e, t, i) => {
83
- let a = b(e), o = t === null ? null : Object.freeze({
97
+ }, k = (e, t, n) => {
98
+ let r = w(e), i = t === null ? null : Object.freeze({
84
99
  ...t,
85
- ...b(t)
100
+ ...w(t)
86
101
  });
87
- if (o !== null && (C(o, a), !_(o.id) || !/^[0-9a-f]{64}$/.test(o.identityKey) || !Number.isInteger(o.revision) || o.revision < 1 || o.revision >= g)) throw r("The expected native invoice revision is invalid or exhausted.");
88
- if (i.providerInvoiceId !== a.providerInvoiceId || i.providerCustomerId !== a.providerCustomerId || i.livemode !== a.livemode) throw r("The complete invoice must match the confirmed customer binding.");
102
+ if (i !== null && (D(i, r), !x(i.id) || !/^[0-9a-f]{64}$/.test(i.identityKey) || !Number.isInteger(i.revision) || i.revision < 1 || i.revision >= b)) throw s("The expected native invoice revision is invalid or exhausted.");
103
+ if (n.providerInvoiceId !== r.providerInvoiceId || n.providerCustomerId !== r.providerCustomerId || n.livemode !== r.livemode) throw s("The complete invoice must match the confirmed customer binding.");
89
104
  return {
90
- owner: a,
91
- previous: o,
92
- providerSnapshot: n(i)
105
+ owner: r,
106
+ previous: i,
107
+ providerSnapshot: structuredClone(o(n))
93
108
  };
94
- }, E = (e) => {
95
- let t = async (t) => {
96
- let n = await e.query(v(o("identityKey", t), 2));
97
- if (n.length > 1) throw r("The native invoice identity is not unique.");
98
- let i = n[0] ? w(n[0]) : null;
99
- if (i !== null && (i.identityKey !== t || await x(i) !== t)) throw r("The native invoice identity digest could not be confirmed.");
100
- return i;
109
+ }, A = (e) => {
110
+ let a = async (t, n = e, r = !1) => {
111
+ let i = S(u("identityKey", t), 2), a = await n.query(r ? {
112
+ ...i,
113
+ lock: "update"
114
+ } : i);
115
+ if (a.length > 1) throw s("The native invoice identity is not unique.");
116
+ let o = a[0] ? O(a[0]) : null;
117
+ if (o !== null && (o.identityKey !== t || await T(o) !== t)) throw s("The native invoice identity digest could not be confirmed.");
118
+ return o;
101
119
  };
102
120
  return {
103
- get: (e) => y(async () => {
104
- let n = b(e), r = await t(await x(n));
105
- return r !== null && C(r, n), r;
121
+ capturePaymentEpoch: (t) => C(() => i(e, t, !0, async (e, t) => t)),
122
+ currentPaymentEpoch: (t, r) => C(() => n(e, t, r?.forUpdate === !0)),
123
+ invalidatePayments: (t, n) => C(() => r(e, t, n)),
124
+ get: (t, n) => C(async () => {
125
+ let r = w(t), i = await a(await T(r), e, n?.forUpdate === !0);
126
+ return i !== null && D(i, r), i;
106
127
  }),
107
- complete: (n, i, s) => y(async () => {
108
- let { owner: c, previous: l, providerSnapshot: u } = T(n, i, s), d = await x(c);
109
- if (l === null) {
110
- let n = "binvobs_" + globalThis.crypto.randomUUID();
111
- await e.insertIgnore(p, {
112
- id: n,
113
- ...c,
114
- livemode: +!!c.livemode,
115
- identityKey: d,
116
- revision: 1,
117
- providerSnapshot: u,
118
- createdAt: /* @__PURE__ */ new Date()
119
- }, { conflictColumns: ["identityKey"] });
120
- let i = await t(d);
121
- if (i === null) throw r("The persisted invoice observation could not be confirmed.", !0);
122
- return C(i, c), i.id === n;
123
- }
124
- if (d !== l.identityKey) throw r("The expected invoice identity digest is invalid.");
125
- return await e.updateMany(p, {
126
- providerSnapshot: u,
127
- revision: l.revision + 1
128
- }, { where: a(o("id", l.id), o("identityKey", d), o("revision", l.revision), o("tenantId", c.tenantId), o("provider", c.provider), o("providerAccountId", c.providerAccountId), o("livemode", +!!c.livemode), o("providerCustomerId", c.providerCustomerId), o("providerInvoiceId", c.providerInvoiceId)) }) === 1;
128
+ complete: (n, r, o, c) => C(async () => {
129
+ let { owner: d, previous: f, providerSnapshot: p } = k(n, r, o), m = t(c), h = await T(d);
130
+ return i(e, d, !1, async (e, t) => {
131
+ if (t.headId !== m.headId || t.epoch !== m.epoch) return !1;
132
+ if (f === null) {
133
+ let t = "binvobs_" + globalThis.crypto.randomUUID();
134
+ await e.insertIgnore(_, {
135
+ id: t,
136
+ ...d,
137
+ livemode: +!!d.livemode,
138
+ identityKey: h,
139
+ revision: 1,
140
+ providerSnapshot: p,
141
+ paymentHeadId: m.headId,
142
+ paymentEpoch: m.epoch,
143
+ createdAt: /* @__PURE__ */ new Date()
144
+ }, { conflictColumns: ["identityKey"] });
145
+ let n = await a(h, e, !0);
146
+ if (n === null) throw s("The persisted invoice observation could not be confirmed.", !0);
147
+ return D(n, d), n.id === t && (j(n, m, p), !0);
148
+ }
149
+ if (h !== f.identityKey) throw s("The expected invoice identity digest is invalid.");
150
+ if (await e.updateMany("_voltro_billing_account_invoices", {
151
+ providerSnapshot: p,
152
+ revision: f.revision + 1,
153
+ paymentHeadId: m.headId,
154
+ paymentEpoch: m.epoch
155
+ }, { where: l(u("id", f.id), u("identityKey", h), u("revision", f.revision), u("tenantId", d.tenantId), u("provider", d.provider), u("providerAccountId", d.providerAccountId), u("livemode", +!!d.livemode), u("providerCustomerId", d.providerCustomerId), u("providerInvoiceId", d.providerInvoiceId)) }) !== 1) return !1;
156
+ let n = await a(h, e, !0);
157
+ if (!n || n.id !== f.id || n.revision !== f.revision + 1) throw s("The updated invoice revision could not be read back.", !0);
158
+ return D(n, d), j(n, m, p), !0;
159
+ });
129
160
  })
130
161
  };
162
+ }, j = (e, t, n) => {
163
+ let r = e.paymentEpoch;
164
+ if (r === null || r.headId !== t.headId || r.epoch !== t.epoch || JSON.stringify(o(e.snapshot)) !== JSON.stringify(n)) throw s("Invoice payment generation or exact observation could not be read back.", !0);
131
165
  };
132
- export { p as BILLING_INVOICE_OBSERVATIONS_TABLE, h as billingInvoiceObservationsTable, m as billingRetainedInvoiceObservationsTable, E as dataStoreInvoiceStore };
166
+ export { _ as BILLING_INVOICE_OBSERVATIONS_TABLE, y as billingInvoiceObservationsTable, v as billingRetainedInvoiceObservationsTable, A as dataStoreInvoiceStore };
@@ -0,0 +1,84 @@
1
+ import { BillingError as e } from "./types.js";
2
+ import { dataStoreInvoiceStore as t } from "./invoiceStore.js";
3
+ import { dataStoreCustomerStore as n } from "./customerStore.js";
4
+ import { BILLING_SUBSCRIPTIONS_TABLE as r } from "./table.js";
5
+ import { captureSubscriptionObservation as i } from "./subscriptionObservation.js";
6
+ import { Effect as a } from "effect";
7
+ import { and as o, eq as s } from "@voltro/database";
8
+ // src/paidInvoiceCoverage.ts
9
+ var c = () => new e({
10
+ source: "paidInvoiceCoverage",
11
+ message: "Current native paid invoice coverage requires reconciliation.",
12
+ transient: !0
13
+ }), l = (e) => {
14
+ let t = e.paymentObservation;
15
+ if (e.status !== "paid" || e.paidAt === null || t === null || e.amountDueMinor <= 0 || e.amountRemainingMinor !== 0 || e.amountPaidMinor < e.amountDueMinor || t.prePaymentCreditNotesMinor !== 0 || t.postPaymentCreditNotesMinor !== 0 || typeof t.invoiceTotalMinor != "number" || typeof t.startingBalanceMinor != "number" || typeof t.endingBalanceMinor != "number" || t.invoiceTotalMinor <= 0 || e.amountDueMinor < t.invoiceTotalMinor || t.startingBalanceMinor < 0 || t.endingBalanceMinor < 0 || e.lines.some((e) => e.amountMinor < 0)) return !1;
16
+ let n = 0n, r = /* @__PURE__ */ new Map();
17
+ for (let e of t.payments) {
18
+ if (e.status !== "paid") continue;
19
+ let t = e.cash;
20
+ if (t === null || e.amountPaidMinor === null || e.paidAt === null || !t.paid || !t.captured || t.disputed || t.refundedMinor !== 0 || t.refunds.some((e) => e.status !== "failed" && e.status !== "canceled") || t.providerPaymentIntentId !== null && t.paymentIntentStatus !== "succeeded") return !1;
21
+ let i = BigInt(e.amountPaidMinor), a = BigInt(t.capturedMinor), o = r.get(t.providerChargeId);
22
+ if (o !== void 0 && o.captured !== a) return !1;
23
+ let s = (o?.allocated ?? 0n) + i;
24
+ if (s > a) return !1;
25
+ r.set(t.providerChargeId, {
26
+ allocated: s,
27
+ captured: a
28
+ }), n += i;
29
+ }
30
+ return n >= BigInt(e.amountDueMinor) && n === BigInt(e.amountPaidMinor);
31
+ }, u = async (e, u, d) => {
32
+ if (!(d instanceof Date) || !Number.isSafeInteger(d.getTime()) || d.getTime() < 0) throw c();
33
+ let f = i(u.providerObservation, u);
34
+ if (f === null) return null;
35
+ let p = await e.query({
36
+ table: r,
37
+ predicate: o(s("tenantId", u.tenantId), s("provider", u.provider), s("providerSubscriptionId", u.providerSubscriptionId)),
38
+ order: [],
39
+ take: 2,
40
+ skip: void 0,
41
+ projection: void 0,
42
+ lock: "update"
43
+ }), m = p[0];
44
+ if (p.length !== 1 || m === void 0) throw c();
45
+ let h = (e) => e == null ? null : e instanceof Date ? e : new Date(String(e)), g = i(m.providerObservation, {
46
+ tenantId: String(m.tenantId),
47
+ provider: String(m.provider),
48
+ providerSubscriptionId: String(m.providerSubscriptionId),
49
+ plan: String(m.plan),
50
+ status: String(m.status),
51
+ quantity: Number(m.quantity),
52
+ currentPeriodStart: h(m.currentPeriodStart),
53
+ currentPeriodEnd: h(m.currentPeriodEnd),
54
+ cancelAt: h(m.cancelAt)
55
+ });
56
+ if (g === null || JSON.stringify(g) !== JSON.stringify(f) || Date.parse(f.observedAt) > d.getTime()) throw c();
57
+ let _ = {
58
+ providerAccountId: f.providerAccountId,
59
+ livemode: f.livemode
60
+ }, v = n(e), y = await a.runPromise(v.accountForTenant(u.tenantId));
61
+ if (y === null || y.provider !== u.provider || y.account.providerAccountId !== _.providerAccountId || y.account.livemode !== _.livemode) throw c();
62
+ let b = {
63
+ provider: u.provider,
64
+ account: _
65
+ }, x = await a.runPromise(v.getByProviderCustomerId(f.providerCustomerId, b));
66
+ if (x === null || x.tenantId !== u.tenantId || x.provider !== u.provider) throw c();
67
+ let S = {
68
+ tenantId: u.tenantId,
69
+ provider: u.provider,
70
+ ..._,
71
+ providerCustomerId: f.providerCustomerId
72
+ }, C = t(e), w = await a.runPromise(C.currentPaymentEpoch(S, { forUpdate: !0 }));
73
+ if (w === null || f.paymentHeadId !== w.headId || f.paymentEpoch !== w.epoch) return null;
74
+ let T = await a.runPromise(C.get({
75
+ ...S,
76
+ providerInvoiceId: f.providerLatestInvoiceId
77
+ }, { forUpdate: !0 }));
78
+ if (T === null || T.paymentEpoch?.headId !== w.headId || T.paymentEpoch.epoch !== w.epoch) return null;
79
+ let E = T.snapshot;
80
+ if (E.providerSubscriptionId !== u.providerSubscriptionId || E.currency !== f.currency || E.observedAt.getTime() > d.getTime() || !l(E)) return null;
81
+ for (let e of E.lines) if (!(e.providerSubscriptionId !== u.providerSubscriptionId || e.providerSubscriptionItemId !== f.providerSubscriptionItemId || e.providerPriceId !== f.providerPriceId || e.currency !== f.currency || e.proration !== !1 || e.amountMinor <= 0 || e.quantityDecimal === null || e.quantityDecimal.length > 64 || !/^[1-9][0-9]*(?:\.0+)?$/.test(e.quantityDecimal) || BigInt(e.quantityDecimal.split(".")[0]) !== BigInt(f.quantity) || e.periodStart.getTime() > d.getTime() || e.periodStart.getTime() !== Date.parse(f.currentPeriodStart) || e.periodEnd.getTime() !== Date.parse(f.currentPeriodEnd))) return new Date(e.periodEnd.getTime());
82
+ return null;
83
+ };
84
+ export { u as paidInvoiceCoverageInTransaction };
package/dist/plans.js CHANGED
@@ -1,8 +1,15 @@
1
1
  import { DEFAULT_PLAN as e } from "./types.js";
2
2
  // src/plans.ts
3
3
  var t = (e) => e === void 0 ? 0 : e === "unlimited" ? Infinity : e, n = (e) => {
4
- let n = /* @__PURE__ */ new Map();
5
- for (let [t, r] of Object.entries(e)) r.priceId !== void 0 && n.set(r.priceId, t);
4
+ let n = /* @__PURE__ */ new Map(), r = /* @__PURE__ */ new Map();
5
+ for (let [t, i] of Object.entries(e)) if (i.priceId !== void 0 && n.set(i.priceId, t), i.seatPriceId !== void 0 || i.includedSeats !== void 0) {
6
+ if (i.priceId === void 0 || i.seatPriceId === void 0 || i.includedSeats === void 0 || !Number.isSafeInteger(i.includedSeats) || i.includedSeats < 1 || i.seatPriceId === i.priceId) throw TypeError(`billingPlugin: plan '${t}' needs priceId, seatPriceId and a positive whole includedSeats together.`);
7
+ r.set(t, {
8
+ includedSeats: i.includedSeats,
9
+ seatPriceId: i.seatPriceId
10
+ });
11
+ }
12
+ for (let [e, t] of r) if (n.has(t.seatPriceId)) throw TypeError(`billingPlugin: plan '${e}' seatPriceId is another plan's priceId.`);
6
13
  return {
7
14
  has: (t) => Object.prototype.hasOwnProperty.call(e, t),
8
15
  entitlementLimit: (n, r) => {
@@ -11,6 +18,12 @@ var t = (e) => e === void 0 ? 0 : e === "unlimited" ? Infinity : e, n = (e) => {
11
18
  },
12
19
  planForPriceId: (e) => n.get(e) ?? null,
13
20
  priceIdFor: (t) => e[t]?.priceId ?? null,
21
+ seatPricingFor: (e) => r.get(e) ?? null,
22
+ seatPricingForPriceId: (e) => {
23
+ let t = n.get(e);
24
+ return t === void 0 ? null : r.get(t) ?? null;
25
+ },
26
+ minimumSeatsFor: (e) => r.get(e)?.includedSeats ?? 1,
14
27
  meteredPriceIdsFor: (t) => e[t]?.meteredPriceIds ?? [],
15
28
  unitAmountFor: (t) => {
16
29
  let n = e[t]?.unitAmountMinor;