@voltro/plugin-billing 0.89.2 → 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.
@@ -1,43 +1,43 @@
1
1
  import { BillingError as e } from "./types.js";
2
- import { captureProviderAccount as t, exactProviderIdentifier as n, sameProviderAccount as r } from "./providerIdentity.js";
3
- import { BILLING_INVOICE_HISTORY_REFERENCES_TABLE as i, invoiceHistoryJournalInTransaction as a } from "./invoiceHistoryJournal.js";
4
- import { dataStoreInvoiceStore as o } from "./invoiceStore.js";
2
+ import { dataStoreInvoiceStore as t } from "./invoiceStore.js";
3
+ import { captureProviderAccount as n, exactProviderIdentifier as r, sameProviderAccount as i } from "./providerIdentity.js";
4
+ import { BILLING_INVOICE_HISTORY_REFERENCES_TABLE as a, invoiceHistoryJournalInTransaction as o } from "./invoiceHistoryJournal.js";
5
5
  import { Effect as s, Schema as c } from "effect";
6
- import { DEFAULT_IN_FLIGHT_LEASE_MS as l, beginIdempotent as u, finishIdempotent as d, holdIdempotentClaim as f, prepareIdempotentInput as p, systemSubject as m } from "@voltro/protocol";
7
- import { and as h, eq as g, gt as _, id as v, inSet as y, integer as b, lte as x, notInSubquery as S, table as C, text as w, timestamp as T } from "@voltro/database";
8
- import { dataStoreIdempotencyStore as E } from "@voltro/runtime";
6
+ import { and as l, eq as u, gt as d, id as f, inSet as p, integer as m, lte as h, notInSubquery as g, table as _, text as v, timestamp as y } from "@voltro/database";
7
+ import { dataStoreIdempotencyStore as b } from "@voltro/runtime";
8
+ import { DEFAULT_IN_FLIGHT_LEASE_MS as x, beginIdempotent as S, finishIdempotent as C, holdIdempotentClaim as w, prepareIdempotentInput as T, systemSubject as E } from "@voltro/protocol";
9
9
  // src/invoiceHistoryWork.ts
10
- var D = "_voltro_billing_invoice_history_work", O = C(D, {
11
- id: v({ prefix: "bihwork" }),
12
- tenantId: w().maxLength(191),
13
- provider: w().maxLength(64),
14
- providerAccountId: w().maxLength(191),
15
- livemode: b(),
16
- providerCustomerId: w().maxLength(191),
17
- custodyId: w().maxLength(191),
18
- walkId: w().maxLength(191),
19
- referenceId: w().maxLength(191),
20
- providerInvoiceId: w().maxLength(191),
21
- revision: b(),
22
- attempt: b(),
23
- executions: b(),
24
- state: w().maxLength(32),
25
- activeClaimId: w().maxLength(191).nullable(),
26
- nextAttemptAt: T(),
27
- lastOutcome: w().maxLength(32),
28
- observationId: w().maxLength(191).nullable(),
29
- observationRevision: b().nullable(),
30
- updatedAt: T()
10
+ var D = "_voltro_billing_invoice_history_work", O = _(D, {
11
+ id: f({ prefix: "bihwork" }),
12
+ tenantId: v().maxLength(191),
13
+ provider: v().maxLength(64),
14
+ providerAccountId: v().maxLength(191),
15
+ livemode: m(),
16
+ providerCustomerId: v().maxLength(191),
17
+ custodyId: v().maxLength(191),
18
+ walkId: v().maxLength(191),
19
+ referenceId: v().maxLength(191),
20
+ providerInvoiceId: v().maxLength(191),
21
+ revision: m(),
22
+ attempt: m(),
23
+ executions: m(),
24
+ state: v().maxLength(32),
25
+ activeClaimId: v().maxLength(191).nullable(),
26
+ nextAttemptAt: y(),
27
+ lastOutcome: v().maxLength(32),
28
+ observationId: v().maxLength(191).nullable(),
29
+ observationRevision: m().nullable(),
30
+ updatedAt: y()
31
31
  }).unique("byBillingInvoiceHistoryWorkReference", ["referenceId"]).index("byBillingInvoiceHistoryWorkDue", [
32
32
  "walkId",
33
33
  "state",
34
34
  "nextAttemptAt"
35
- ]).index("byBillingInvoiceHistoryWorkTenant", ["tenantId"]), k = 2147483647, A = 6e4, j = 864e5, M = m("billing.invoice-history-work", []), N = (t = "Invoice reference work remains unconfirmed and requires reconciliation.", n = !0) => new e({
35
+ ]).index("byBillingInvoiceHistoryWorkTenant", ["tenantId"]), k = 2147483647, A = 6e4, j = 864e5, M = E("billing.invoice-history-work", []), N = (t = "Invoice reference work remains unconfirmed and requires reconciliation.", n = !0) => new e({
36
36
  source: "invoiceHistoryWork",
37
37
  message: t,
38
38
  transient: n
39
39
  }), P = (e, t = 191) => {
40
- if (!n(e) || e.length > t || !e.isWellFormed()) throw N();
40
+ if (!r(e) || e.length > t || !e.isWellFormed()) throw N();
41
41
  return e;
42
42
  }, F = (e, t = 0) => {
43
43
  if (typeof e != "number" || !Number.isInteger(e) || e < t || e > k) throw N();
@@ -51,7 +51,7 @@ var D = "_voltro_billing_invoice_history_work", O = C(D, {
51
51
  catch: (t) => t instanceof e ? t : N()
52
52
  }), z = (e, t = !1) => ({
53
53
  table: D,
54
- predicate: g("referenceId", e),
54
+ predicate: u("referenceId", e),
55
55
  order: [],
56
56
  take: 2,
57
57
  skip: void 0,
@@ -73,27 +73,27 @@ var D = "_voltro_billing_invoice_history_work", O = C(D, {
73
73
  ...e.account,
74
74
  providerCustomerId: e.providerCustomerId,
75
75
  providerInvoiceId: e.providerInvoiceId
76
- }), H = (e, n) => {
76
+ }), H = (e, t) => {
77
77
  if (e.livemode !== 0 && e.livemode !== 1) throw N();
78
- let i = t({
78
+ let r = n({
79
79
  providerAccountId: P(e.providerAccountId),
80
80
  livemode: e.livemode === 1
81
81
  });
82
- if (e.tenantId !== n.tenantId || e.provider !== n.provider || e.providerCustomerId !== n.providerCustomerId || e.custodyId !== n.custodyId || e.walkId !== n.walkId || e.referenceId !== n.id || e.providerInvoiceId !== n.providerInvoiceId || !r(i, n.account)) throw N();
82
+ if (e.tenantId !== t.tenantId || e.provider !== t.provider || e.providerCustomerId !== t.providerCustomerId || e.custodyId !== t.custodyId || e.walkId !== t.walkId || e.referenceId !== t.id || e.providerInvoiceId !== t.providerInvoiceId || !i(r, t.account)) throw N();
83
83
  let a = e.state, o = e.lastOutcome, s = e.activeClaimId;
84
84
  if (a !== "queued" && a !== "working" && a !== "retry" && a !== "deferred" && a !== "observed" || o !== "unconfirmed" && o !== "open" && o !== "observed") throw N();
85
85
  let c = e.observationId === null ? null : P(e.observationId), l = e.observationRevision === null ? null : F(e.observationRevision, 1);
86
86
  if (c === null != (l === null) || a === "working" != (s !== null) || (a === "observed" || a === "deferred") && c === null || a === "observed" && o !== "observed" || a === "deferred" && o !== "open") throw N();
87
87
  let u = {
88
88
  id: P(e.id),
89
- tenantId: n.tenantId,
90
- provider: n.provider,
91
- account: i,
92
- providerCustomerId: n.providerCustomerId,
93
- custodyId: n.custodyId,
94
- walkId: n.walkId,
95
- referenceId: n.id,
96
- providerInvoiceId: n.providerInvoiceId,
89
+ tenantId: t.tenantId,
90
+ provider: t.provider,
91
+ account: r,
92
+ providerCustomerId: t.providerCustomerId,
93
+ custodyId: t.custodyId,
94
+ walkId: t.walkId,
95
+ referenceId: t.id,
96
+ providerInvoiceId: t.providerInvoiceId,
97
97
  revision: F(e.revision, 1),
98
98
  attempt: F(e.attempt),
99
99
  executions: F(e.executions),
@@ -107,7 +107,7 @@ var D = "_voltro_billing_invoice_history_work", O = C(D, {
107
107
  };
108
108
  if (a === "working" && (u.attempt === 0 || u.executions === 0)) throw N();
109
109
  return u;
110
- }, U = (e) => "billing.invoice-history-work.v1:" + e.walkId, W = (e, t) => e.id + ":" + t, G = async (e, t) => (await p(c.Unknown, [
110
+ }, U = (e) => "billing.invoice-history-work.v1:" + e.walkId, W = (e, t) => e.id + ":" + t, G = async (e, t) => (await T(c.Unknown, [
111
111
  e.id,
112
112
  e.tenantId,
113
113
  e.provider,
@@ -131,22 +131,27 @@ var D = "_voltro_billing_invoice_history_work", O = C(D, {
131
131
  work: Object.freeze(t),
132
132
  claim: n
133
133
  });
134
- }, q = (e) => {
135
- let t = E(e), n = async (e, t, n) => {
136
- let r = await s.runPromise(a(e).reference(t, n));
134
+ }, q = async (e, n) => {
135
+ let r = t(e), i = V(n), a = await s.runPromise(r.currentPaymentEpoch(i, { forUpdate: !0 }));
136
+ if (a === null) return null;
137
+ let o = await s.runPromise(r.get(i, { forUpdate: !0 }));
138
+ return o?.paymentEpoch?.headId === a.headId && o.paymentEpoch.epoch === a.epoch ? o : null;
139
+ }, J = (e) => {
140
+ let t = b(e), n = async (e, t, n) => {
141
+ let r = await s.runPromise(o(e).reference(t, n));
137
142
  if (r === null) throw N("The original owned invoice history reference is missing.", !1);
138
143
  return r;
139
144
  }, r = async (e, t, n = !1) => {
140
145
  let r = await e.query(z(t.id, n));
141
146
  if (r.length > 1) throw N();
142
147
  return r[0] ? H(r[0], t) : null;
143
- }, c = async (e, t, n, i, a) => {
148
+ }, i = async (e, t, n, i, a) => {
144
149
  if (n.revision >= k) throw N("The invoice reference work revision is exhausted.", !1);
145
150
  if (await e.updateMany("_voltro_billing_invoice_history_work", {
146
151
  ...i,
147
152
  revision: n.revision + 1,
148
153
  updatedAt: a
149
- }, { where: h(g("id", n.id), g("referenceId", t.id), g("revision", n.revision), g("custodyId", t.custodyId), g("walkId", t.walkId)) }) !== 1) throw N();
154
+ }, { where: l(u("id", n.id), u("referenceId", t.id), u("revision", n.revision), u("custodyId", t.custodyId), u("walkId", t.walkId)) }) !== 1) throw N();
150
155
  let o = await r(e, t, !0);
151
156
  if (o === null || o.id !== n.id || o.revision !== n.revision + 1 || o.updatedAt.getTime() !== a.getTime()) throw N();
152
157
  for (let [e, t] of Object.entries(i)) {
@@ -154,101 +159,98 @@ var D = "_voltro_billing_invoice_history_work", O = C(D, {
154
159
  if (t instanceof Date ? !(n instanceof Date) || n.getTime() !== t.getTime() : n !== t) throw N("The invoice work acknowledgement was not read back exactly.");
155
160
  }
156
161
  return o;
157
- }, p = async (e, t, n) => {
162
+ }, c = async (e, t, n) => {
158
163
  let i = await r(e, t, !0), a = n.work;
159
164
  return i === null || i.id !== a.id || i.referenceId !== a.referenceId || i.state !== "working" || i.attempt !== a.attempt || i.activeClaimId !== n.claim.id || n.claim.inputHash !== await G(i, i.attempt) ? null : i;
160
165
  };
161
166
  return {
162
- pending: (t, r, o, c) => R(async () => {
163
- let l = structuredClone(t), u = I(o), d = c?.limit ?? 25;
167
+ pending: (t, r, i, c) => R(async () => {
168
+ let f = structuredClone(t), m = I(i), _ = c?.limit ?? 25;
164
169
  if (![
165
170
  "unprepared",
166
171
  "ready",
167
- "working"
168
- ].includes(r) || !Number.isInteger(d) || d < 1 || d > 100) throw N();
169
- let f = c?.cursor === void 0 ? null : {
172
+ "working",
173
+ "observed"
174
+ ].includes(r) || !Number.isInteger(_) || _ < 1 || _ > 100) throw N();
175
+ let v = c?.cursor === void 0 ? null : {
170
176
  lane: c.cursor.lane,
171
177
  walkId: P(c.cursor.walkId),
172
178
  afterId: P(c.cursor.afterId)
173
179
  };
174
- if (f !== null && f.lane !== r) throw N("Invoice work cursors belong to one selection lane.", !1);
180
+ if (v !== null && v.lane !== r) throw N("Invoice work cursors belong to one selection lane.", !1);
175
181
  return e.transactional(async (e) => {
176
- let t = a(e), o = await s.runPromise(t.read(l));
177
- if (o === null) throw N("No retained owned invoice history walk exists.");
178
- let c = await s.runPromise(t.begin(l));
179
- if (c.id !== o.id || f !== null && f.walkId !== c.id) throw N("Invoice work cursor differs from the retained walk.", !1);
180
- let p = h(g("tenantId", c.tenantId), g("provider", c.provider), g("providerAccountId", c.account.providerAccountId), g("livemode", +!!c.account.livemode), g("providerCustomerId", c.providerCustomerId), g("custodyId", c.custodyId), g("walkId", c.id)), m = r === "unprepared", v = m ? i : D;
181
- if (f !== null) {
182
+ let t = o(e), i = await s.runPromise(t.read(f));
183
+ if (i === null) throw N("No retained owned invoice history walk exists.");
184
+ let c = await s.runPromise(t.begin(f));
185
+ if (c.id !== i.id || v !== null && v.walkId !== c.id) throw N("Invoice work cursor differs from the retained walk.", !1);
186
+ let y = l(u("tenantId", c.tenantId), u("provider", c.provider), u("providerAccountId", c.account.providerAccountId), u("livemode", +!!c.account.livemode), u("providerCustomerId", c.providerCustomerId), u("custodyId", c.custodyId), u("walkId", c.id)), b = r === "unprepared", x = r === "working" ? ["working"] : r === "observed" ? ["observed"] : [
187
+ "queued",
188
+ "retry",
189
+ "deferred"
190
+ ], S = b ? a : D;
191
+ if (v !== null) {
182
192
  let t = await e.query({
183
- ...z(f.afterId),
184
- table: v,
185
- predicate: h(p, g("id", f.afterId))
193
+ ...z(v.afterId),
194
+ table: S,
195
+ predicate: l(y, u("id", v.afterId))
186
196
  });
187
- if (t.length !== 1 || t[0]?.id !== f.afterId) throw N("Invoice work cursor is no longer retained.", !0);
188
- let r = await n(e, l, m ? f.afterId : P(t[0]?.referenceId));
189
- m || H(t[0], r);
197
+ if (t.length !== 1 || t[0]?.id !== v.afterId) throw N("Invoice work cursor is no longer retained.", !0);
198
+ let r = await n(e, f, b ? v.afterId : P(t[0]?.referenceId));
199
+ b || H(t[0], r);
190
200
  }
191
- let b = [p];
192
- f !== null && b.push(_("id", f.afterId)), m ? b.push(x("pageOrdinal", c.pageOrdinal), S("id", {
201
+ let C = [y];
202
+ v !== null && C.push(d("id", v.afterId)), b ? C.push(h("pageOrdinal", c.pageOrdinal), g("id", {
193
203
  ...z(c.id),
194
- predicate: p,
204
+ predicate: y,
195
205
  projection: ["referenceId"],
196
206
  take: void 0
197
- })) : b.push(x("nextAttemptAt", u), r === "working" ? g("state", "working") : y("state", [
198
- "queued",
199
- "retry",
200
- "deferred"
201
- ]));
202
- let C = await e.query({
207
+ })) : C.push(h("nextAttemptAt", m), p("state", x));
208
+ let w = await e.query({
203
209
  ...z(c.id),
204
- table: v,
205
- predicate: h(...b),
210
+ table: S,
211
+ predicate: l(...C),
206
212
  order: [{
207
213
  column: "id",
208
214
  direction: "asc"
209
215
  }],
210
- take: d + 1
216
+ take: _ + 1
211
217
  });
212
- if (C.length > d + 1) throw N();
213
- let w = await s.runPromise(t.referencesByIds(l, C.map((e) => P(m ? e.id : e.referenceId))));
214
- if (m && C.length > 0 && (await e.query({
218
+ if (w.length > _ + 1) throw N();
219
+ let T = await s.runPromise(t.referencesByIds(f, w.map((e) => P(b ? e.id : e.referenceId))));
220
+ if (b && w.length > 0 && (await e.query({
215
221
  ...z(c.id),
216
- predicate: y("referenceId", w.map((e) => e.id)),
222
+ predicate: p("referenceId", T.map((e) => e.id)),
217
223
  take: 1
218
224
  })).length > 0) throw N("An unprepared invoice reference already has native work.", !0);
219
- let T = f?.afterId ?? null, E = [];
220
- for (let [e, t] of C.entries()) {
225
+ let E = v?.afterId ?? null, O = [];
226
+ for (let [e, t] of w.entries()) {
221
227
  let n = P(t.id);
222
- if (T !== null && n <= T) throw N("Invoice work selection is not strictly ordered.");
223
- T = n;
224
- let i = w[e];
225
- if (i === void 0 || i.walkId !== c.id || i.pageOrdinal > c.pageOrdinal) throw N();
226
- let a = m ? null : H(t, i);
227
- if (a !== null && (a.id !== n || a.nextAttemptAt.getTime() > u.getTime() || (r === "working" ? a.state !== "working" : ![
228
- "queued",
229
- "retry",
230
- "deferred"
231
- ].includes(a.state)))) throw N("Invoice work changed while selecting its lane.", !0);
232
- E.push({
233
- reference: i,
234
- work: a
228
+ if (E !== null && n <= E) throw N("Invoice work selection is not strictly ordered.");
229
+ E = n;
230
+ let r = T[e];
231
+ if (r === void 0 || r.walkId !== c.id || r.pageOrdinal > c.pageOrdinal) throw N();
232
+ let i = b ? null : H(t, r);
233
+ if (i !== null && (i.id !== n || i.nextAttemptAt.getTime() > m.getTime() || !x.includes(i.state))) throw N("Invoice work changed while selecting its lane.", !0);
234
+ O.push({
235
+ reference: r,
236
+ work: i
235
237
  });
236
238
  }
237
239
  return {
238
- entries: E.slice(0, d),
239
- nextCursor: C.length > d ? {
240
+ entries: O.slice(0, _),
241
+ nextCursor: w.length > _ ? {
240
242
  lane: r,
241
243
  walkId: c.id,
242
- afterId: P(C[d - 1]?.id)
244
+ afterId: P(w[_ - 1]?.id)
243
245
  } : null,
244
246
  walkRevision: c.revision
245
247
  };
246
248
  });
247
249
  }),
248
- claim: (t, i, a) => R(async () => {
249
- let d = structuredClone(t), f = P(i), p = I(a);
250
+ claim: (t, a, o) => R(async () => {
251
+ let s = structuredClone(t), c = P(a), l = I(o);
250
252
  return e.transactional(async (e) => {
251
- let t = await n(e, d, f);
253
+ let t = await n(e, s, c);
252
254
  await e.insertIgnore(D, {
253
255
  id: "bihwork_" + globalThis.crypto.randomUUID(),
254
256
  ...B(t),
@@ -257,106 +259,106 @@ var D = "_voltro_billing_invoice_history_work", O = C(D, {
257
259
  executions: 0,
258
260
  state: "queued",
259
261
  activeClaimId: null,
260
- nextAttemptAt: p,
262
+ nextAttemptAt: l,
261
263
  lastOutcome: "unconfirmed",
262
264
  observationId: null,
263
265
  observationRevision: null,
264
- updatedAt: p
266
+ updatedAt: l
265
267
  }, { conflictColumns: ["referenceId"] });
266
- let i = await r(e, t, !0);
267
- if (i === null) throw N();
268
- if (i.state === "observed") {
269
- let n = await s.runPromise(o(e).get(V(t)));
270
- if (n !== null && n.id === i.observationId && n.revision >= i.observationRevision && n.snapshot.status !== "open") return {
268
+ let a = await r(e, t, !0);
269
+ if (a === null) throw N();
270
+ if (a.state === "observed") {
271
+ let n = await q(e, t);
272
+ if (n !== null && n.id === a.observationId && n.revision >= a.observationRevision && n.snapshot.status !== "open") return {
271
273
  kind: "observed",
272
- work: i
274
+ work: a
273
275
  };
274
- i = await c(e, t, i, {
276
+ a = await i(e, t, a, {
275
277
  state: "queued",
276
278
  activeClaimId: null,
277
279
  lastOutcome: "unconfirmed",
278
- nextAttemptAt: p
279
- }, p);
280
+ nextAttemptAt: l
281
+ }, l);
280
282
  }
281
- if (i.state !== "working" && i.nextAttemptAt.getTime() > p.getTime()) return {
283
+ if (a.state !== "working" && a.nextAttemptAt.getTime() > l.getTime()) return {
282
284
  kind: "busy",
283
- work: i
285
+ work: a
284
286
  };
285
- let a = i.state === "working" ? i.attempt : i.attempt + 1;
286
- if (a > k || i.executions >= k) throw N("The invoice reference attempt counter is exhausted.", !1);
287
- let m = await G(i, a), h = await u(E(e), U(i), W(i, a), m, j, p.getTime());
288
- if (h.kind === "replay") return i = await c(e, t, i, {
289
- attempt: a,
287
+ let o = a.state === "working" ? a.attempt : a.attempt + 1;
288
+ if (o > k || a.executions >= k) throw N("The invoice reference attempt counter is exhausted.", !1);
289
+ let u = await G(a, o), d = await S(b(e), U(a), W(a, o), u, j, l.getTime());
290
+ if (d.kind === "replay") return a = await i(e, t, a, {
291
+ attempt: o,
290
292
  state: "queued",
291
293
  activeClaimId: null,
292
- nextAttemptAt: p,
294
+ nextAttemptAt: l,
293
295
  lastOutcome: "unconfirmed"
294
- }, p), {
296
+ }, l), {
295
297
  kind: "busy",
296
- work: i
298
+ work: a
297
299
  };
298
- if (h.kind === "conflict") return {
300
+ if (d.kind === "conflict") return {
299
301
  kind: "busy",
300
- work: i
302
+ work: a
301
303
  };
302
- if (h.kind !== "fresh") throw N("The retained invoice attempt has a different input binding.", !1);
303
- return i = await c(e, t, i, {
304
- attempt: a,
305
- executions: i.executions + 1,
304
+ if (d.kind !== "fresh") throw N("The retained invoice attempt has a different input binding.", !1);
305
+ return a = await i(e, t, a, {
306
+ attempt: o,
307
+ executions: a.executions + 1,
306
308
  state: "working",
307
- activeClaimId: h.claim.id,
308
- nextAttemptAt: L(p, l),
309
+ activeClaimId: d.claim.id,
310
+ nextAttemptAt: L(l, x),
309
311
  lastOutcome: "unconfirmed"
310
- }, p), {
312
+ }, l), {
311
313
  kind: "claimed",
312
- work: i,
314
+ work: a,
313
315
  attempt: Object.freeze({
314
- work: i,
315
- claim: h.claim
316
+ work: a,
317
+ claim: d.claim
316
318
  })
317
319
  };
318
320
  });
319
321
  }),
320
- observed: (t, r, i, a) => R(async () => {
321
- let l = structuredClone(t), u = K(r), f = I(a), m = P(i.id), h = F(i.revision, 1);
322
+ observed: (t, r, a, o) => R(async () => {
323
+ let s = structuredClone(t), l = K(r), u = I(o), d = P(a.id), f = F(a.revision, 1);
322
324
  return e.transactional(async (e) => {
323
- let t = await n(e, l, u.work.referenceId), r = await p(e, t, u);
325
+ let t = await n(e, s, l.work.referenceId), r = await c(e, t, l);
324
326
  if (r === null) return null;
325
- let i = await s.runPromise(o(e).get(V(t)));
326
- if (i === null || i.id !== m || i.revision < h) throw N("The qualified native invoice observation is missing or older than the offered acknowledgement.");
327
- let a = i.snapshot.status === "open";
328
- return await d(E(e), u.claim, {
329
- status: a ? 202 : 204,
327
+ let a = await q(e, t);
328
+ if (a === null || a.id !== d || a.revision < f) throw N("The qualified native invoice observation is missing or older than the offered acknowledgement.");
329
+ let o = a.snapshot.status === "open";
330
+ return await C(b(e), l.claim, {
331
+ status: o ? 202 : 204,
330
332
  body: null
331
- }, f.getTime()) ? c(e, t, r, {
332
- state: a ? "deferred" : "observed",
333
+ }, u.getTime()) ? i(e, t, r, {
334
+ state: o ? "deferred" : "observed",
333
335
  activeClaimId: null,
334
- observationId: i.id,
335
- observationRevision: i.revision,
336
- lastOutcome: a ? "open" : "observed",
337
- nextAttemptAt: a ? L(f, A) : f
338
- }, f) : null;
336
+ observationId: a.id,
337
+ observationRevision: a.revision,
338
+ lastOutcome: o ? "open" : "observed",
339
+ nextAttemptAt: o ? L(u, A) : u
340
+ }, u) : null;
339
341
  });
340
342
  }),
341
- failed: (t, r, i) => R(async () => {
342
- let a = structuredClone(t), o = K(r), s = I(i);
343
+ failed: (t, r, a) => R(async () => {
344
+ let o = structuredClone(t), s = K(r), l = I(a);
343
345
  return e.transactional(async (e) => {
344
- let t = await n(e, a, o.work.referenceId), r = await p(e, t, o);
345
- return r === null || !await d(E(e), o.claim, {
346
+ let t = await n(e, o, s.work.referenceId), r = await c(e, t, s);
347
+ return r === null || !await C(b(e), s.claim, {
346
348
  status: 503,
347
349
  body: null
348
- }, s.getTime()) ? null : c(e, t, r, {
350
+ }, l.getTime()) ? null : i(e, t, r, {
349
351
  state: "retry",
350
352
  activeClaimId: null,
351
353
  lastOutcome: "unconfirmed",
352
- nextAttemptAt: L(s, A)
353
- }, s);
354
+ nextAttemptAt: L(l, A)
355
+ }, l);
354
356
  });
355
357
  }),
356
358
  hold: (e, n) => {
357
359
  let r = K(e);
358
- return f(t, r.claim, l, n);
360
+ return w(t, r.claim, x, n);
359
361
  }
360
362
  };
361
363
  };
362
- export { D as BILLING_INVOICE_HISTORY_WORK_TABLE, O as billingInvoiceHistoryWorkTable, q as dataStoreInvoiceHistoryWorkStore };
364
+ export { D as BILLING_INVOICE_HISTORY_WORK_TABLE, O as billingInvoiceHistoryWorkTable, J as dataStoreInvoiceHistoryWorkStore };
@@ -0,0 +1,145 @@
1
+ import { BillingError as e } from "./types.js";
2
+ import { and as t, eq as n, gt as r, id as i, integer as a, isNotNull as o, neq as s, or as c, table as l, text as u, timestamp as d } from "@voltro/database";
3
+ // src/invoicePaymentEpoch.ts
4
+ var f = "_voltro_billing_invoice_payment_heads", p = "_voltro_billing_invoice_payment_corrections", m = "_voltro_billing_account_invoices", h = "voltro.invoice-payment-epoch.v1", g = 2147483647, _ = l(f, {
5
+ id: i({ prefix: "bipe" }),
6
+ protocol: u(),
7
+ tenantId: u(),
8
+ provider: u(),
9
+ providerAccountId: u().maxLength(191),
10
+ livemode: a(),
11
+ providerCustomerId: u().maxLength(191),
12
+ identityKey: u().maxLength(64),
13
+ epoch: a(),
14
+ createdAt: d(),
15
+ updatedAt: d()
16
+ }).unique("billingInvoicePaymentHeadIdentity", ["identityKey"]).index("billingInvoicePaymentHeadTenant", ["tenantId"]), v = l(p, {
17
+ id: i({ prefix: "bipc" }),
18
+ scopeKey: u().maxLength(64),
19
+ headId: u(),
20
+ providerEventId: u().maxLength(191),
21
+ epoch: a(),
22
+ createdAt: d()
23
+ }).unique("billingInvoicePaymentCorrectionIdentity", ["scopeKey", "providerEventId"]).unique("billingInvoicePaymentCorrectionEpoch", ["scopeKey", "epoch"]), y = (t = "Original invoice payment custody requires reconciliation.", n = !1) => new e({
24
+ source: "invoicePaymentEpoch",
25
+ message: t,
26
+ transient: n
27
+ }), b = (e) => typeof e == "string" && e.length > 0 && e.trim() === e, x = (e) => typeof e == "number" && Number.isInteger(e) && e >= 0 && e <= 2147483647, S = (e) => {
28
+ if (![
29
+ e.tenantId,
30
+ e.provider,
31
+ e.providerAccountId,
32
+ e.providerCustomerId
33
+ ].every(b) || e.providerAccountId.length > 191 || e.providerCustomerId.length > 191 || typeof e.livemode != "boolean") throw y();
34
+ return Object.freeze({
35
+ tenantId: e.tenantId,
36
+ provider: e.provider,
37
+ providerAccountId: e.providerAccountId,
38
+ livemode: e.livemode,
39
+ providerCustomerId: e.providerCustomerId
40
+ });
41
+ }, C = (e) => {
42
+ if (!b(e.headId) || !x(e.epoch)) throw y();
43
+ return Object.freeze({
44
+ headId: e.headId,
45
+ epoch: e.epoch
46
+ });
47
+ }, w = async (e) => {
48
+ let t = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify([
49
+ h,
50
+ e.provider,
51
+ e.providerAccountId,
52
+ e.livemode,
53
+ e.providerCustomerId
54
+ ])));
55
+ return [...new Uint8Array(t)].map((e) => e.toString(16).padStart(2, "0")).join("");
56
+ }, T = (e, t, n = !1) => ({
57
+ table: e,
58
+ predicate: t,
59
+ ...n ? { lock: "update" } : {},
60
+ order: [],
61
+ take: 2,
62
+ skip: void 0,
63
+ projection: void 0
64
+ }), E = async (e, i, a, l) => {
65
+ let u = await e.query(T(f, n("identityKey", a), l));
66
+ if (u.length > 1) throw y();
67
+ let d = u[0];
68
+ if (!d) return null;
69
+ if (!b(d.id) || d.protocol !== h || d.identityKey !== a || d.tenantId !== i.tenantId || d.provider !== i.provider || d.providerAccountId !== i.providerAccountId || d.livemode !== +!!i.livemode || d.providerCustomerId !== i.providerCustomerId || !x(d.epoch)) throw y();
70
+ let g = d.id, _ = d.epoch, v = await e.query({
71
+ ...T(p, t(n("scopeKey", a), c(s("headId", g), r("epoch", _))), l),
72
+ projection: ["id"]
73
+ }), S = await e.query({
74
+ ...T(m, t(n("provider", i.provider), n("providerAccountId", i.providerAccountId), n("livemode", +!!i.livemode), n("providerCustomerId", i.providerCustomerId), c(t(o("paymentHeadId"), s("paymentHeadId", g)), r("paymentEpoch", _))), l),
75
+ projection: ["id"]
76
+ });
77
+ if (v.length || S.length) throw y();
78
+ if (_ > 0) {
79
+ let r = await e.query(T(p, t(n("scopeKey", a), n("epoch", _)), l));
80
+ if (r.length !== 1 || r[0]?.headId !== g || !b(r[0]?.providerEventId)) throw y();
81
+ }
82
+ return {
83
+ headId: g,
84
+ epoch: _
85
+ };
86
+ }, D = async (e, t, n = !1) => {
87
+ let r = S(t);
88
+ return E(e, r, await w(r), n);
89
+ }, O = async (e, r, i, a) => {
90
+ let s = S(r), l = await w(s);
91
+ return e.transactional(async (e) => {
92
+ let r = await E(e, s, l, !0);
93
+ if (r === null) {
94
+ if (!i) throw y();
95
+ let a = await e.query({
96
+ ...T(m, t(n("provider", s.provider), n("providerAccountId", s.providerAccountId), n("livemode", +!!s.livemode), n("providerCustomerId", s.providerCustomerId), c(o("paymentHeadId"), o("paymentEpoch"))), !0),
97
+ projection: ["id"]
98
+ }), u = await e.query({
99
+ ...T(p, n("scopeKey", l), !0),
100
+ projection: ["id"]
101
+ });
102
+ if (a.length || u.length) throw y();
103
+ let d = /* @__PURE__ */ new Date();
104
+ if (await e.insertIgnore(f, {
105
+ id: "bipe_" + globalThis.crypto.randomUUID(),
106
+ protocol: h,
107
+ ...s,
108
+ livemode: +!!s.livemode,
109
+ identityKey: l,
110
+ epoch: 0,
111
+ createdAt: d,
112
+ updatedAt: d
113
+ }, { conflictColumns: ["identityKey"] }), r = await E(e, s, l, !0), r === null) throw y("Invoice payment custody could not be retained.", !0);
114
+ }
115
+ return a(e, r, l);
116
+ });
117
+ }, k = async (e, r, i) => {
118
+ if (!b(i) || i.length > 191) throw y();
119
+ return O(e, r, !0, async (e, a, o) => {
120
+ let s = t(n("scopeKey", o), n("providerEventId", i)), c = await e.query(T(p, s, !0));
121
+ if (c.length > 1) throw y();
122
+ if (c[0]) {
123
+ let e = c[0];
124
+ if (e.headId !== a.headId || !x(e.epoch) || e.epoch < 1 || e.epoch > a.epoch) throw y();
125
+ return a;
126
+ }
127
+ if (a.epoch === 2147483647) throw y("Invoice payment correction generation is exhausted.");
128
+ let l = a.epoch + 1, u = /* @__PURE__ */ new Date(), d = "bipc_" + globalThis.crypto.randomUUID();
129
+ if (await e.insert(p, {
130
+ id: d,
131
+ scopeKey: o,
132
+ headId: a.headId,
133
+ providerEventId: i,
134
+ epoch: l,
135
+ createdAt: u
136
+ }), !await e.update(f, a.headId, {
137
+ epoch: l,
138
+ updatedAt: u
139
+ })) throw y("Invoice payment correction was not retained.", !0);
140
+ let m = await E(e, S(r), o, !0), h = await e.query(T(p, s, !0));
141
+ if (!m || m.headId !== a.headId || m.epoch !== l || h.length !== 1 || h[0]?.id !== d || h[0]?.headId !== a.headId || h[0]?.epoch !== l) throw y("Invoice payment correction could not be read back.", !0);
142
+ return m;
143
+ });
144
+ };
145
+ export { g as MAX_INVOICE_PAYMENT_EPOCH, v as billingInvoicePaymentCorrectionsTable, _ as billingInvoicePaymentHeadsTable, C as captureInvoicePaymentEpoch, S as captureInvoicePaymentOwner, D as currentInvoicePaymentEpoch, k as invalidateInvoicePayments, O as withInvoicePaymentEpoch };