@umohpyro/better-auth-nuvion 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +141 -3
- package/dist/client.cjs +33 -0
- package/dist/client.d.cts +12 -0
- package/dist/client.d.ts +12 -0
- package/dist/client.js +8 -0
- package/dist/engine.cjs +343 -0
- package/dist/engine.d.cts +151 -0
- package/dist/engine.d.ts +151 -0
- package/dist/engine.js +308 -0
- package/dist/index.cjs +741 -0
- package/dist/index.d.cts +470 -0
- package/dist/index.d.ts +470 -0
- package/dist/index.js +706 -0
- package/dist/types-BWF8YNYE.d.cts +108 -0
- package/dist/types-BWF8YNYE.d.ts +108 -0
- package/package.json +60 -6
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,741 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/index.ts
|
|
31
|
+
var src_exports = {};
|
|
32
|
+
__export(src_exports, {
|
|
33
|
+
nuvion: () => nuvion
|
|
34
|
+
});
|
|
35
|
+
module.exports = __toCommonJS(src_exports);
|
|
36
|
+
var import_api = require("better-auth/api");
|
|
37
|
+
var z = __toESM(require("zod"), 1);
|
|
38
|
+
|
|
39
|
+
// src/engine/fees.ts
|
|
40
|
+
var isInt = (n2) => Number.isSafeInteger(n2) && n2 >= 0;
|
|
41
|
+
function validateRule(r) {
|
|
42
|
+
if (!isInt(r.flatMinor)) throw new RangeError("flatMinor must be a non-negative integer");
|
|
43
|
+
if (!Number.isInteger(r.bps) || r.bps < 0 || r.bps > 1e4) throw new RangeError("bps must be an integer 0..10000");
|
|
44
|
+
for (const k of ["minMinor", "capMinor"]) {
|
|
45
|
+
if (r[k] !== void 0 && !isInt(r[k])) throw new RangeError(`${k} must be a non-negative integer`);
|
|
46
|
+
}
|
|
47
|
+
if (r.minMinor !== void 0 && r.capMinor !== void 0 && r.minMinor > r.capMinor) {
|
|
48
|
+
throw new RangeError("minMinor must be <= capMinor");
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
function computeFee(amountMinor, r) {
|
|
52
|
+
if (!isInt(amountMinor)) throw new RangeError("amount must be a non-negative integer");
|
|
53
|
+
if (!r) return 0;
|
|
54
|
+
validateRule(r);
|
|
55
|
+
let fee = r.flatMinor + Number(BigInt(amountMinor) * BigInt(r.bps) / 10000n);
|
|
56
|
+
if (r.minMinor !== void 0) fee = Math.max(fee, r.minMinor);
|
|
57
|
+
if (r.capMinor !== void 0) fee = Math.min(fee, r.capMinor);
|
|
58
|
+
return Math.min(fee, amountMinor);
|
|
59
|
+
}
|
|
60
|
+
function quote(baseMinor, chain) {
|
|
61
|
+
if (!isInt(baseMinor) || baseMinor === 0) throw new RangeError("base must be a positive integer");
|
|
62
|
+
if (chain.length < 1) throw new RangeError("empty chain");
|
|
63
|
+
const leafRule = chain.length > 1 ? chain[0].rule : void 0;
|
|
64
|
+
let charged = baseMinor;
|
|
65
|
+
if (leafRule?.bearer === "payer") charged = baseMinor + computeFee(baseMinor, leafRule);
|
|
66
|
+
const legs = [];
|
|
67
|
+
let inflow = charged;
|
|
68
|
+
for (let i = 0; i < chain.length - 1; i++) {
|
|
69
|
+
const node = chain[i];
|
|
70
|
+
let fee;
|
|
71
|
+
if (i === 0 && leafRule?.bearer === "payer") fee = charged - baseMinor;
|
|
72
|
+
else fee = computeFee(inflow, node.rule);
|
|
73
|
+
legs.push({ organizationId: node.organizationId, amountMinor: inflow - fee });
|
|
74
|
+
inflow = fee;
|
|
75
|
+
}
|
|
76
|
+
legs.push({ organizationId: chain[chain.length - 1].organizationId, amountMinor: inflow });
|
|
77
|
+
const sum = legs.reduce((s, l) => s + l.amountMinor, 0);
|
|
78
|
+
if (sum !== charged) throw new Error(`split invariant broken: ${sum} !== ${charged}`);
|
|
79
|
+
return { baseMinor, chargedMinor: charged, legs };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// src/engine/hierarchy.ts
|
|
83
|
+
var MAX_DEPTH = 3;
|
|
84
|
+
async function chainOf(organizationId, parentOf) {
|
|
85
|
+
const chain = [];
|
|
86
|
+
const seen = /* @__PURE__ */ new Set();
|
|
87
|
+
let cur = organizationId;
|
|
88
|
+
while (cur) {
|
|
89
|
+
if (seen.has(cur)) throw new Error(`cycle detected at ${cur}`);
|
|
90
|
+
seen.add(cur);
|
|
91
|
+
chain.push(cur);
|
|
92
|
+
if (chain.length > MAX_DEPTH) throw new Error(`hierarchy deeper than ${MAX_DEPTH}`);
|
|
93
|
+
cur = await parentOf(cur);
|
|
94
|
+
}
|
|
95
|
+
return chain;
|
|
96
|
+
}
|
|
97
|
+
async function assertValidParent(orgId, parentId, parentOf, childrenOf) {
|
|
98
|
+
if (parentId === null) return;
|
|
99
|
+
if (parentId === orgId) throw new Error("an organization cannot be its own parent");
|
|
100
|
+
const up = await chainOf(parentId, parentOf);
|
|
101
|
+
if (up.includes(orgId)) throw new Error("cycle: parent is a descendant of the organization");
|
|
102
|
+
const below = await subtreeHeight(orgId, childrenOf);
|
|
103
|
+
if (up.length + below > MAX_DEPTH) throw new Error(`hierarchy would exceed depth ${MAX_DEPTH}`);
|
|
104
|
+
}
|
|
105
|
+
async function subtreeHeight(id, childrenOf, guard = 0) {
|
|
106
|
+
if (guard > MAX_DEPTH + 1) return MAX_DEPTH + 1;
|
|
107
|
+
const kids = await childrenOf(id);
|
|
108
|
+
let h = 0;
|
|
109
|
+
for (const k of kids) h = Math.max(h, await subtreeHeight(k, childrenOf, guard + 1));
|
|
110
|
+
return 1 + h;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// src/engine/types.ts
|
|
114
|
+
var ProviderError = class extends Error {
|
|
115
|
+
kind;
|
|
116
|
+
constructor(kind, message) {
|
|
117
|
+
super(message);
|
|
118
|
+
this.kind = kind;
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
// src/engine/service.ts
|
|
123
|
+
var uid = () => crypto.randomUUID();
|
|
124
|
+
var SplitService = class {
|
|
125
|
+
store;
|
|
126
|
+
provider;
|
|
127
|
+
constructor(store, provider) {
|
|
128
|
+
this.store = store;
|
|
129
|
+
this.provider = provider;
|
|
130
|
+
}
|
|
131
|
+
/** Quote + persist a payment and open a hosted checkout for the (possibly grossed-up) charged amount. */
|
|
132
|
+
async createPayment(a) {
|
|
133
|
+
const q = await this.quoteFor(a.organizationId, a.baseMinor);
|
|
134
|
+
const id = uid();
|
|
135
|
+
const reference = `pay_${id}`;
|
|
136
|
+
const payment2 = {
|
|
137
|
+
id,
|
|
138
|
+
organizationId: a.organizationId,
|
|
139
|
+
reference,
|
|
140
|
+
baseMinor: a.baseMinor,
|
|
141
|
+
chargedMinor: q.chargedMinor,
|
|
142
|
+
currency: a.currency,
|
|
143
|
+
status: "pending",
|
|
144
|
+
createdAt: Date.now()
|
|
145
|
+
};
|
|
146
|
+
await this.store.insertPayment(payment2);
|
|
147
|
+
const s = await this.provider.createCheckout({
|
|
148
|
+
organizationId: a.organizationId,
|
|
149
|
+
amountMinor: q.chargedMinor,
|
|
150
|
+
currency: a.currency,
|
|
151
|
+
reference,
|
|
152
|
+
narration: reference,
|
|
153
|
+
redirectUrl: a.redirectUrl
|
|
154
|
+
});
|
|
155
|
+
payment2.providerSessionId = s.sessionId;
|
|
156
|
+
return { payment: payment2, checkoutUrl: s.checkoutUrl, quote: q };
|
|
157
|
+
}
|
|
158
|
+
async quoteFor(organizationId, baseMinor) {
|
|
159
|
+
const ids = await chainOf(organizationId, (o) => this.store.parentOf(o));
|
|
160
|
+
const chain = await Promise.all(ids.map(async (id) => ({ organizationId: id, rule: await this.store.getRule(id) })));
|
|
161
|
+
return quote(baseMinor, chain);
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* inflows.completed. Idempotent on eventId AND on payment status (a redelivery with a new event id is still a no-op).
|
|
165
|
+
* Funds landed in the leaf's account; legs move each beneficiary's share out of it.
|
|
166
|
+
*/
|
|
167
|
+
async onInflowCompleted(e) {
|
|
168
|
+
if (!await this.store.claimEvent(e.eventId)) return { status: "duplicate-event" };
|
|
169
|
+
const p = await this.store.findPaymentByReference(e.reference);
|
|
170
|
+
if (!p) return { status: "unknown-payment" };
|
|
171
|
+
if (e.amountMinor !== p.chargedMinor || e.currency !== p.currency) {
|
|
172
|
+
return { status: "amount-mismatch", paymentId: p.id };
|
|
173
|
+
}
|
|
174
|
+
if (!await this.store.transitionPayment(p.id, ["pending"], "received")) {
|
|
175
|
+
return { status: "already-processed", paymentId: p.id };
|
|
176
|
+
}
|
|
177
|
+
const q = await this.quoteFor(p.organizationId, p.baseMinor);
|
|
178
|
+
if (q.chargedMinor !== p.chargedMinor) throw new Error("fee rules changed between checkout and settlement; manual review");
|
|
179
|
+
const legs = q.legs.filter((l, i) => i > 0 && l.amountMinor > 0).map((l) => ({
|
|
180
|
+
id: uid(),
|
|
181
|
+
paymentId: p.id,
|
|
182
|
+
kind: "split",
|
|
183
|
+
fromOrganizationId: p.organizationId,
|
|
184
|
+
toOrganizationId: l.organizationId,
|
|
185
|
+
amountMinor: l.amountMinor,
|
|
186
|
+
state: "pending",
|
|
187
|
+
attempt: 0
|
|
188
|
+
}));
|
|
189
|
+
await this.store.insertLegs(legs);
|
|
190
|
+
const r = await this.executeLegs(p.id);
|
|
191
|
+
return { status: "processed", paymentId: p.id, ...r };
|
|
192
|
+
}
|
|
193
|
+
/** Run every runnable leg once. Retry = call again. Sent/completed legs are never re-issued. */
|
|
194
|
+
async executeLegs(paymentId) {
|
|
195
|
+
const p = await this.store.getPayment(paymentId);
|
|
196
|
+
if (!p) throw new Error("payment not found");
|
|
197
|
+
await this.store.transitionPayment(paymentId, ["received", "partial"], "splitting");
|
|
198
|
+
for (const leg2 of await this.store.legsOf(paymentId)) {
|
|
199
|
+
if (leg2.state !== "pending" && leg2.state !== "failed") continue;
|
|
200
|
+
const attempt = leg2.state === "failed" ? leg2.attempt + 1 : leg2.attempt;
|
|
201
|
+
try {
|
|
202
|
+
const r = await this.provider.transfer({
|
|
203
|
+
fromOrganizationId: leg2.fromOrganizationId,
|
|
204
|
+
toOrganizationId: leg2.toOrganizationId,
|
|
205
|
+
amountMinor: leg2.amountMinor,
|
|
206
|
+
currency: p.currency,
|
|
207
|
+
reference: `${leg2.id}-a${attempt}`,
|
|
208
|
+
narration: `${leg2.kind} ${p.reference}`
|
|
209
|
+
});
|
|
210
|
+
await this.store.updateLeg(leg2.id, { state: "sent", attempt, providerRef: r.providerRef, error: null });
|
|
211
|
+
} catch (err) {
|
|
212
|
+
if (!(err instanceof ProviderError)) throw err;
|
|
213
|
+
if (err.kind === "rejected") await this.store.updateLeg(leg2.id, { state: "failed", attempt, error: err.message });
|
|
214
|
+
else if (err.kind === "duplicate") await this.store.updateLeg(leg2.id, { state: "sent", attempt, error: "duplicate-reference" });
|
|
215
|
+
else await this.store.updateLeg(leg2.id, { state: "pending", attempt, error: err.message });
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
return this.refreshStatus(paymentId);
|
|
219
|
+
}
|
|
220
|
+
/** outflows.completed / outflows.failed for a leg, matched by our reference `${legId}-a${attempt}`. */
|
|
221
|
+
async onTransferEvent(e) {
|
|
222
|
+
if (!await this.store.claimEvent(e.eventId)) return { status: "duplicate-event" };
|
|
223
|
+
const m = /^(.+)-a(\d+)$/.exec(e.reference);
|
|
224
|
+
const leg2 = m && await this.store.getLeg(m[1]);
|
|
225
|
+
if (!m || !leg2) return { status: "unknown-leg" };
|
|
226
|
+
if (Number(m[2]) !== leg2.attempt) return { status: "stale-attempt" };
|
|
227
|
+
if (leg2.state === "completed" || leg2.state === "cancelled") return { status: "already-processed" };
|
|
228
|
+
await this.store.updateLeg(leg2.id, e.ok ? { state: "completed", error: null } : { state: "failed", error: "provider reported failure" });
|
|
229
|
+
await this.refreshStatus(leg2.paymentId);
|
|
230
|
+
return { status: "processed" };
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Refund after split (outflows.refunded). Money already left the leaf account, so the payer refund is only
|
|
234
|
+
* fundable if beneficiaries give their shares back: cancel unsent legs, add one reversal leg per moved leg.
|
|
235
|
+
*/
|
|
236
|
+
async onRefund(paymentId) {
|
|
237
|
+
const p = await this.store.getPayment(paymentId);
|
|
238
|
+
if (!p) throw new Error("payment not found");
|
|
239
|
+
if (!await this.store.transitionPayment(paymentId, ["pending", "received", "splitting", "partial", "settled"], "refund_partial")) {
|
|
240
|
+
return { status: "already-refunded" };
|
|
241
|
+
}
|
|
242
|
+
const reversals = [];
|
|
243
|
+
for (const leg2 of await this.store.legsOf(paymentId)) {
|
|
244
|
+
if (leg2.kind !== "split") continue;
|
|
245
|
+
if (leg2.state === "pending" || leg2.state === "failed") await this.store.updateLeg(leg2.id, { state: "cancelled" });
|
|
246
|
+
else
|
|
247
|
+
reversals.push({
|
|
248
|
+
id: uid(),
|
|
249
|
+
paymentId,
|
|
250
|
+
kind: "reversal",
|
|
251
|
+
fromOrganizationId: leg2.toOrganizationId,
|
|
252
|
+
toOrganizationId: leg2.fromOrganizationId,
|
|
253
|
+
amountMinor: leg2.amountMinor,
|
|
254
|
+
state: "pending",
|
|
255
|
+
attempt: 0
|
|
256
|
+
});
|
|
257
|
+
}
|
|
258
|
+
await this.store.insertLegs(reversals);
|
|
259
|
+
return { status: "refund-started", reversals: reversals.length, ...await this.executeLegs(paymentId) };
|
|
260
|
+
}
|
|
261
|
+
async refreshStatus(paymentId) {
|
|
262
|
+
const p = await this.store.getPayment(paymentId);
|
|
263
|
+
const live = (await this.store.legsOf(paymentId)).filter((l) => l.state !== "cancelled");
|
|
264
|
+
const done = live.every((l) => l.state === "completed");
|
|
265
|
+
let next = p.status;
|
|
266
|
+
if (p.status === "refund_partial") {
|
|
267
|
+
if (done) {
|
|
268
|
+
await this.store.transitionPayment(paymentId, ["refund_partial"], "refunded");
|
|
269
|
+
next = "refunded";
|
|
270
|
+
}
|
|
271
|
+
} else if (live.length > 0 && done) {
|
|
272
|
+
await this.store.transitionPayment(paymentId, ["splitting", "partial", "received"], "settled");
|
|
273
|
+
next = "settled";
|
|
274
|
+
} else if (live.length === 0) {
|
|
275
|
+
await this.store.transitionPayment(paymentId, ["splitting"], "settled");
|
|
276
|
+
next = "settled";
|
|
277
|
+
} else if (live.some((l) => l.state === "failed")) {
|
|
278
|
+
await this.store.transitionPayment(paymentId, ["splitting"], "partial");
|
|
279
|
+
next = "partial";
|
|
280
|
+
}
|
|
281
|
+
return { paymentStatus: next, legs: await this.store.legsOf(paymentId) };
|
|
282
|
+
}
|
|
283
|
+
};
|
|
284
|
+
|
|
285
|
+
// src/provider/index.ts
|
|
286
|
+
var import_node_crypto = require("crypto");
|
|
287
|
+
var DEFAULT_PROFILE = {
|
|
288
|
+
email: "book-transfers@counterparty.invalid",
|
|
289
|
+
relationship: "supplier",
|
|
290
|
+
address: { line1: "Not provided", city: "Not provided", country: "GB" }
|
|
291
|
+
};
|
|
292
|
+
var NuvionProvider = class {
|
|
293
|
+
baseUrl;
|
|
294
|
+
apiKey;
|
|
295
|
+
f;
|
|
296
|
+
dir;
|
|
297
|
+
profile;
|
|
298
|
+
constructor(cfg, dir) {
|
|
299
|
+
if (!cfg.apiKey) throw new Error("NUVION_API_KEY is required");
|
|
300
|
+
this.baseUrl = (cfg.baseUrl ?? "https://api.nuvion.dev").replace(/\/$/, "");
|
|
301
|
+
this.apiKey = cfg.apiKey;
|
|
302
|
+
this.f = cfg.fetch ?? fetch;
|
|
303
|
+
this.dir = dir;
|
|
304
|
+
this.profile = { ...DEFAULT_PROFILE, ...cfg.counterparty, address: { ...DEFAULT_PROFILE.address, ...cfg.counterparty?.address } };
|
|
305
|
+
}
|
|
306
|
+
async createCheckout(r) {
|
|
307
|
+
const b = await this.dir.binding(r.organizationId);
|
|
308
|
+
const res = await this.call("POST", "/funding-sessions", {
|
|
309
|
+
amount: r.amountMinor,
|
|
310
|
+
currency: r.currency,
|
|
311
|
+
account_id: b.accountId,
|
|
312
|
+
entity_id: b.entityId,
|
|
313
|
+
// required when acting on a child entity
|
|
314
|
+
unique_reference: r.reference,
|
|
315
|
+
narration: r.narration,
|
|
316
|
+
redirect_url: r.redirectUrl,
|
|
317
|
+
// HTTPS, required for open-banking
|
|
318
|
+
funding_type: "open-banking"
|
|
319
|
+
});
|
|
320
|
+
if (!res.ok) throw classify(res.status, res.body);
|
|
321
|
+
const d = res.body.data;
|
|
322
|
+
return { sessionId: String(d.id), checkoutUrl: String(d.checkout_url) };
|
|
323
|
+
}
|
|
324
|
+
async transfer(t) {
|
|
325
|
+
const src = await this.dir.binding(t.fromOrganizationId);
|
|
326
|
+
const dest = await this.ensureDestination(t.fromOrganizationId, t.toOrganizationId);
|
|
327
|
+
let res;
|
|
328
|
+
try {
|
|
329
|
+
res = await this.call("POST", "/transfers", {
|
|
330
|
+
entity_id: src.entityId,
|
|
331
|
+
account_id: src.accountId,
|
|
332
|
+
counterparty_id: dest.counterpartyId,
|
|
333
|
+
payment_detail_id: dest.paymentDetailId,
|
|
334
|
+
amount: t.amountMinor,
|
|
335
|
+
currency: t.currency,
|
|
336
|
+
payment_type: "book-transfer",
|
|
337
|
+
narration: t.narration.slice(0, 255),
|
|
338
|
+
unique_reference: t.reference
|
|
339
|
+
// <= 100 chars; doubles as our idempotency key
|
|
340
|
+
});
|
|
341
|
+
} catch (e) {
|
|
342
|
+
throw new ProviderError("ambiguous", `network error: ${e.name}`);
|
|
343
|
+
}
|
|
344
|
+
if (!res.ok) throw classify(res.status, res.body);
|
|
345
|
+
return { providerRef: String(res.body.data.id) };
|
|
346
|
+
}
|
|
347
|
+
/**
|
|
348
|
+
* The counterparty + book-transfer payment detail for from -> to, created on first use. Needs both organizations bound to
|
|
349
|
+
* different Nuvion accounts. Counterparties are created on the sending entity, so the same call also works for the reverse
|
|
350
|
+
* pair (a refund reversal). A failure after the counterparty is created but before its payment detail leaves an unused
|
|
351
|
+
* counterparty in Nuvion; the retry creates a new one.
|
|
352
|
+
*/
|
|
353
|
+
async ensureDestination(fromOrganizationId, toOrganizationId) {
|
|
354
|
+
const have = await this.dir.destination(fromOrganizationId, toOrganizationId);
|
|
355
|
+
if (have) return have;
|
|
356
|
+
const src = await this.dir.binding(fromOrganizationId);
|
|
357
|
+
const dst = await this.dir.binding(toOrganizationId);
|
|
358
|
+
if (src.accountId === dst.accountId) throw new ProviderError("rejected", "the paying and receiving organizations use the same Nuvion account; bind each organization to its own account");
|
|
359
|
+
const name = await this.dir.orgName(toOrganizationId);
|
|
360
|
+
const acct = await this.must("GET", `/accounts/${dst.accountId}?entity_id=${encodeURIComponent(dst.entityId)}`);
|
|
361
|
+
const account = acct.data?.account ?? acct.data;
|
|
362
|
+
if (!account?.nuvion_ban) throw new ProviderError("rejected", "the receiving Nuvion account has no account number (nuvion_ban)");
|
|
363
|
+
const cp = await this.must("POST", "/counterparties", {
|
|
364
|
+
type: "business",
|
|
365
|
+
entity_id: src.entityId,
|
|
366
|
+
nickname: name.slice(0, 100),
|
|
367
|
+
profile: { legal_name: name, relationship: this.profile.relationship, email: this.profile.email, registered_address: this.profile.address }
|
|
368
|
+
});
|
|
369
|
+
const pd = await this.must("POST", "/payment-details", {
|
|
370
|
+
payment_method: "book-transfer",
|
|
371
|
+
currency: account.currency,
|
|
372
|
+
account_holder_name: name,
|
|
373
|
+
counterparty_id: cp.data.id,
|
|
374
|
+
entity_id: src.entityId,
|
|
375
|
+
account_number: account.nuvion_ban
|
|
376
|
+
});
|
|
377
|
+
const d = { counterpartyId: String(cp.data.id), paymentDetailId: String(pd.data.id) };
|
|
378
|
+
await this.dir.saveDestination(fromOrganizationId, toOrganizationId, d);
|
|
379
|
+
return d;
|
|
380
|
+
}
|
|
381
|
+
/** A call that must succeed: network failures are ambiguous, non-2xx responses are classified. */
|
|
382
|
+
async must(method, path, body) {
|
|
383
|
+
let res;
|
|
384
|
+
try {
|
|
385
|
+
res = await this.call(method, path, body);
|
|
386
|
+
} catch (e) {
|
|
387
|
+
throw new ProviderError("ambiguous", `network error: ${e.name}`);
|
|
388
|
+
}
|
|
389
|
+
if (!res.ok) throw classify(res.status, res.body);
|
|
390
|
+
return res.body;
|
|
391
|
+
}
|
|
392
|
+
async getFundingSession(id, entityId) {
|
|
393
|
+
const res = await this.call("GET", `/funding-sessions/${id}?entity_id=${encodeURIComponent(entityId)}`);
|
|
394
|
+
if (!res.ok) throw classify(res.status, res.body);
|
|
395
|
+
return res.body.data;
|
|
396
|
+
}
|
|
397
|
+
async call(method, path, body) {
|
|
398
|
+
const r = await this.f(this.baseUrl + path, {
|
|
399
|
+
method,
|
|
400
|
+
headers: { Authorization: `Bearer ${this.apiKey}`, "Content-Type": "application/json" },
|
|
401
|
+
body: body === void 0 ? void 0 : JSON.stringify(body)
|
|
402
|
+
});
|
|
403
|
+
let json = {};
|
|
404
|
+
try {
|
|
405
|
+
json = await r.json();
|
|
406
|
+
} catch {
|
|
407
|
+
}
|
|
408
|
+
return { ok: r.ok, status: r.status, body: json };
|
|
409
|
+
}
|
|
410
|
+
};
|
|
411
|
+
function classify(status, body) {
|
|
412
|
+
const msg = `nuvion ${status} ${body?.type ?? ""}`.trim();
|
|
413
|
+
if (status === 409) return new ProviderError("duplicate", msg);
|
|
414
|
+
if (status >= 500 || status === 429 || status === 408) return new ProviderError("ambiguous", msg);
|
|
415
|
+
return new ProviderError("rejected", msg);
|
|
416
|
+
}
|
|
417
|
+
function verifyWebhook(rawBody, headers, secret, opts = {}) {
|
|
418
|
+
const ts = headers.get("x-nuvion-event-timestamp");
|
|
419
|
+
const sig = headers.get("x-nuvion-event-signature");
|
|
420
|
+
if (!ts || !sig || !secret) return false;
|
|
421
|
+
const expected = (0, import_node_crypto.createHmac)("sha256", secret).update(`${ts}.${rawBody}`).digest("hex");
|
|
422
|
+
const a = Buffer.from(expected);
|
|
423
|
+
const b = Buffer.from(sig);
|
|
424
|
+
if (a.length !== b.length || !(0, import_node_crypto.timingSafeEqual)(a, b)) return false;
|
|
425
|
+
if (opts.toleranceMs !== void 0) {
|
|
426
|
+
const t = Date.parse(ts);
|
|
427
|
+
if (Number.isNaN(t) || Math.abs((opts.now ?? Date.now()) - t) > opts.toleranceMs) return false;
|
|
428
|
+
}
|
|
429
|
+
return true;
|
|
430
|
+
}
|
|
431
|
+
function parseEvent(eventId, body) {
|
|
432
|
+
const d = body?.data ?? {};
|
|
433
|
+
switch (body?.event) {
|
|
434
|
+
case "inflows.completed":
|
|
435
|
+
return { kind: "inflow.completed", eventId, reference: String(d.unique_reference), narration: String(d.narration ?? ""), amountMinor: d.amount, currency: d.currency, entityId: String(d.entity_id) };
|
|
436
|
+
case "outflows.completed":
|
|
437
|
+
return { kind: "outflow.completed", eventId, reference: String(d.unique_reference) };
|
|
438
|
+
case "outflows.failed":
|
|
439
|
+
case "outflows.cancelled":
|
|
440
|
+
return { kind: "outflow.failed", eventId, reference: String(d.unique_reference) };
|
|
441
|
+
case "outflows.refunded":
|
|
442
|
+
return { kind: "refunded", eventId, reference: String(d.unique_reference) };
|
|
443
|
+
default:
|
|
444
|
+
return { kind: "ignored", eventId };
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
// src/store.ts
|
|
449
|
+
var n = (v) => v === null || v === void 0 ? v : Number(v);
|
|
450
|
+
var payment = (p) => ({ ...p, baseMinor: n(p.baseMinor), chargedMinor: n(p.chargedMinor), createdAt: n(p.createdAt) });
|
|
451
|
+
var leg = (l) => ({ ...l, amountMinor: n(l.amountMinor), attempt: n(l.attempt), providerRef: l.providerRef ?? void 0, error: l.error ?? void 0 });
|
|
452
|
+
var eq = (field, value) => ({ field, value });
|
|
453
|
+
var AuthStore = class {
|
|
454
|
+
db;
|
|
455
|
+
constructor(db) {
|
|
456
|
+
this.db = db;
|
|
457
|
+
}
|
|
458
|
+
async getRule(orgId) {
|
|
459
|
+
const r = await this.db.findOne({ model: "nuvionFeeRule", where: [eq("organizationId", orgId)] });
|
|
460
|
+
return r ? { organizationId: r.organizationId, flatMinor: n(r.flatMinor), bps: n(r.bps), minMinor: n(r.minMinor) ?? void 0, capMinor: n(r.capMinor) ?? void 0, bearer: r.bearer } : void 0;
|
|
461
|
+
}
|
|
462
|
+
async parentOf(orgId) {
|
|
463
|
+
const o = await this.db.findOne({ model: "organization", where: [eq("id", orgId)] });
|
|
464
|
+
return o?.parentOrganizationId ?? null;
|
|
465
|
+
}
|
|
466
|
+
async childrenOf(orgId) {
|
|
467
|
+
return (await this.db.findMany({ model: "organization", where: [eq("parentOrganizationId", orgId)] })).map((o) => o.id);
|
|
468
|
+
}
|
|
469
|
+
async insertPayment(p) {
|
|
470
|
+
await this.db.create({ model: "nuvionPayment", data: p, forceAllowId: true });
|
|
471
|
+
}
|
|
472
|
+
async getPayment(id) {
|
|
473
|
+
const r = await this.db.findOne({ model: "nuvionPayment", where: [eq("id", id)] });
|
|
474
|
+
return r ? payment(r) : void 0;
|
|
475
|
+
}
|
|
476
|
+
async findPaymentByReference(ref) {
|
|
477
|
+
const r = await this.db.findOne({ model: "nuvionPayment", where: [eq("reference", ref)] });
|
|
478
|
+
return r ? payment(r) : void 0;
|
|
479
|
+
}
|
|
480
|
+
async transitionPayment(id, from, to) {
|
|
481
|
+
const row = await this.db.update({
|
|
482
|
+
model: "nuvionPayment",
|
|
483
|
+
where: [eq("id", id), { field: "status", operator: "in", value: from }],
|
|
484
|
+
update: { status: to }
|
|
485
|
+
});
|
|
486
|
+
return row !== null && row !== void 0;
|
|
487
|
+
}
|
|
488
|
+
async claimEvent(eventId) {
|
|
489
|
+
try {
|
|
490
|
+
await this.db.create({ model: "nuvionEvent", data: { eventId, receivedAt: Date.now() } });
|
|
491
|
+
return true;
|
|
492
|
+
} catch {
|
|
493
|
+
return false;
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
async insertLegs(legs) {
|
|
497
|
+
for (const l of legs) await this.db.create({ model: "nuvionLeg", data: l, forceAllowId: true });
|
|
498
|
+
}
|
|
499
|
+
async getLeg(id) {
|
|
500
|
+
const r = await this.db.findOne({ model: "nuvionLeg", where: [eq("id", id)] });
|
|
501
|
+
return r ? leg(r) : void 0;
|
|
502
|
+
}
|
|
503
|
+
async legsOf(paymentId) {
|
|
504
|
+
return (await this.db.findMany({ model: "nuvionLeg", where: [eq("paymentId", paymentId)] })).map(leg);
|
|
505
|
+
}
|
|
506
|
+
async updateLeg(id, patch) {
|
|
507
|
+
await this.db.update({ model: "nuvionLeg", where: [eq("id", id)], update: patch });
|
|
508
|
+
}
|
|
509
|
+
};
|
|
510
|
+
|
|
511
|
+
// src/index.ts
|
|
512
|
+
var num = { type: "number", required: true, bigint: true };
|
|
513
|
+
var str = { type: "string", required: true };
|
|
514
|
+
var optNum = { type: "number", required: false, bigint: true };
|
|
515
|
+
var idx = { ...{ type: "string", required: true }, index: true };
|
|
516
|
+
async function assertOrgAdmin(db, userId, organizationId) {
|
|
517
|
+
const m = await db.findOne({ model: "member", where: [{ field: "organizationId", value: organizationId }, { field: "userId", value: userId }] });
|
|
518
|
+
if (!m || !["owner", "admin"].includes(String(m.role))) throw new import_api.APIError("FORBIDDEN", { message: "owner/admin of the organization required" });
|
|
519
|
+
}
|
|
520
|
+
var nuvion = (opts) => {
|
|
521
|
+
const build = (db) => {
|
|
522
|
+
const store = new AuthStore(db);
|
|
523
|
+
const dir = {
|
|
524
|
+
async binding(organizationId) {
|
|
525
|
+
const b = await db.findOne({ model: "nuvionBinding", where: [{ field: "organizationId", value: organizationId }] });
|
|
526
|
+
if (!b) throw new Error(`organization ${organizationId} is not bound to a Nuvion entity`);
|
|
527
|
+
return { entityId: b.entityId, accountId: b.accountId };
|
|
528
|
+
},
|
|
529
|
+
async destination(from, to) {
|
|
530
|
+
const d = await db.findOne({ model: "nuvionDestination", where: [{ field: "fromOrganizationId", value: from }, { field: "toOrganizationId", value: to }] });
|
|
531
|
+
return d ? { counterpartyId: d.counterpartyId, paymentDetailId: d.paymentDetailId } : null;
|
|
532
|
+
},
|
|
533
|
+
async saveDestination(from, to, d) {
|
|
534
|
+
await db.create({ model: "nuvionDestination", data: { fromOrganizationId: from, toOrganizationId: to, counterpartyId: d.counterpartyId, paymentDetailId: d.paymentDetailId } });
|
|
535
|
+
},
|
|
536
|
+
async orgName(organizationId) {
|
|
537
|
+
const o = await db.findOne({ model: "organization", where: [{ field: "id", value: organizationId }] });
|
|
538
|
+
return String(o?.name ?? organizationId);
|
|
539
|
+
}
|
|
540
|
+
};
|
|
541
|
+
const provider = new NuvionProvider({ apiKey: opts.apiKey, baseUrl: opts.baseUrl, fetch: opts.fetch, counterparty: opts.counterparty }, dir);
|
|
542
|
+
return { store, provider, svc: new SplitService(store, provider) };
|
|
543
|
+
};
|
|
544
|
+
return {
|
|
545
|
+
id: "nuvion",
|
|
546
|
+
schema: {
|
|
547
|
+
// Extends the organization plugin's table with the hierarchy pointer.
|
|
548
|
+
organization: { fields: { parentOrganizationId: { type: "string", required: false, input: false } } },
|
|
549
|
+
nuvionBinding: { fields: { organizationId: { ...str, unique: true }, entityId: str, accountId: str } },
|
|
550
|
+
nuvionDestination: { fields: { fromOrganizationId: idx, toOrganizationId: str, counterpartyId: str, paymentDetailId: str } },
|
|
551
|
+
nuvionFeeRule: { fields: { organizationId: { ...str, unique: true }, flatMinor: num, bps: num, minMinor: optNum, capMinor: optNum, bearer: str } },
|
|
552
|
+
nuvionPayment: {
|
|
553
|
+
fields: {
|
|
554
|
+
organizationId: idx,
|
|
555
|
+
reference: { ...str, unique: true },
|
|
556
|
+
providerSessionId: { type: "string", required: false },
|
|
557
|
+
baseMinor: num,
|
|
558
|
+
chargedMinor: num,
|
|
559
|
+
currency: str,
|
|
560
|
+
status: str,
|
|
561
|
+
createdAt: num
|
|
562
|
+
}
|
|
563
|
+
},
|
|
564
|
+
nuvionLeg: {
|
|
565
|
+
fields: {
|
|
566
|
+
paymentId: idx,
|
|
567
|
+
kind: str,
|
|
568
|
+
fromOrganizationId: str,
|
|
569
|
+
toOrganizationId: str,
|
|
570
|
+
amountMinor: num,
|
|
571
|
+
state: str,
|
|
572
|
+
attempt: { type: "number", required: true },
|
|
573
|
+
providerRef: { type: "string", required: false },
|
|
574
|
+
error: { type: "string", required: false }
|
|
575
|
+
}
|
|
576
|
+
},
|
|
577
|
+
nuvionEvent: { fields: { eventId: { ...str, unique: true }, receivedAt: num } }
|
|
578
|
+
},
|
|
579
|
+
// Webhook is handled in onRequest, not as an endpoint: the endpoint layer parses (consumes) the body before the
|
|
580
|
+
// handler runs, and the HMAC must be computed over the exact raw bytes. Public by design: auth = signature.
|
|
581
|
+
async onRequest(request, ctx) {
|
|
582
|
+
if (request.method !== "POST" || !new URL(request.url).pathname.endsWith("/nuvion/webhook")) return;
|
|
583
|
+
const json = (status, body) => ({ response: Response.json(body, { status }) });
|
|
584
|
+
const raw = await request.text();
|
|
585
|
+
if (!verifyWebhook(raw, request.headers, opts.webhookSecret, { toleranceMs: opts.webhookToleranceMs })) return json(401, { error: "invalid signature" });
|
|
586
|
+
const eventId = request.headers.get("x-nuvion-event-id");
|
|
587
|
+
if (!eventId) return json(400, { error: "missing event id" });
|
|
588
|
+
const { svc, store } = build(ctx.adapter);
|
|
589
|
+
const ev = parseEvent(eventId, JSON.parse(raw));
|
|
590
|
+
switch (ev.kind) {
|
|
591
|
+
case "inflow.completed": {
|
|
592
|
+
const p = await store.findPaymentByReference(ev.reference) ?? await store.findPaymentByReference(ev.narration);
|
|
593
|
+
if (!p) return json(200, { status: "unknown-payment" });
|
|
594
|
+
return json(200, await svc.onInflowCompleted({ ...ev, reference: p.reference }));
|
|
595
|
+
}
|
|
596
|
+
case "outflow.completed":
|
|
597
|
+
return json(200, await svc.onTransferEvent({ eventId, reference: ev.reference, ok: true }));
|
|
598
|
+
case "outflow.failed":
|
|
599
|
+
return json(200, await svc.onTransferEvent({ eventId, reference: ev.reference, ok: false }));
|
|
600
|
+
case "refunded":
|
|
601
|
+
return json(200, { status: "refund-needs-payment-mapping" });
|
|
602
|
+
// open question, see README
|
|
603
|
+
default:
|
|
604
|
+
return json(200, { status: "ignored" });
|
|
605
|
+
}
|
|
606
|
+
},
|
|
607
|
+
endpoints: {
|
|
608
|
+
setParent: (0, import_api.createAuthEndpoint)(
|
|
609
|
+
"/nuvion/organization/parent",
|
|
610
|
+
{ method: "POST", use: [import_api.sessionMiddleware], body: z.object({ organizationId: z.string(), parentOrganizationId: z.string().nullable() }) },
|
|
611
|
+
async (ctx) => {
|
|
612
|
+
const db = ctx.context.adapter;
|
|
613
|
+
const { store } = build(db);
|
|
614
|
+
await assertOrgAdmin(db, ctx.context.session.user.id, ctx.body.organizationId);
|
|
615
|
+
if (ctx.body.parentOrganizationId) await assertOrgAdmin(db, ctx.context.session.user.id, ctx.body.parentOrganizationId);
|
|
616
|
+
try {
|
|
617
|
+
await assertValidParent(ctx.body.organizationId, ctx.body.parentOrganizationId, (id) => store.parentOf(id), (id) => store.childrenOf(id));
|
|
618
|
+
} catch (e) {
|
|
619
|
+
throw new import_api.APIError("BAD_REQUEST", { message: e.message });
|
|
620
|
+
}
|
|
621
|
+
await db.update({ model: "organization", where: [{ field: "id", value: ctx.body.organizationId }], update: { parentOrganizationId: ctx.body.parentOrganizationId } });
|
|
622
|
+
return ctx.json({ ok: true });
|
|
623
|
+
}
|
|
624
|
+
),
|
|
625
|
+
bindEntity: (0, import_api.createAuthEndpoint)(
|
|
626
|
+
"/nuvion/organization/bind",
|
|
627
|
+
{ method: "POST", use: [import_api.sessionMiddleware], body: z.object({ organizationId: z.string(), entityId: z.string(), accountId: z.string() }) },
|
|
628
|
+
async (ctx) => {
|
|
629
|
+
const db = ctx.context.adapter;
|
|
630
|
+
await assertOrgAdmin(db, ctx.context.session.user.id, ctx.body.organizationId);
|
|
631
|
+
await db.create({ model: "nuvionBinding", data: ctx.body });
|
|
632
|
+
return ctx.json({ ok: true });
|
|
633
|
+
}
|
|
634
|
+
),
|
|
635
|
+
/**
|
|
636
|
+
* Create the book-transfer counterparties for an organization's splits (it -> each ancestor) now, instead of on the first
|
|
637
|
+
* transfer, so a missing or shared Nuvion account shows up here and not as a failed leg. Safe to call again: pairs that
|
|
638
|
+
* already exist are reused. Refund reversals (ancestor -> it) are created when a refund first needs them.
|
|
639
|
+
*/
|
|
640
|
+
provisionDestinations: (0, import_api.createAuthEndpoint)(
|
|
641
|
+
"/nuvion/organization/destinations",
|
|
642
|
+
{ method: "POST", use: [import_api.sessionMiddleware], body: z.object({ organizationId: z.string() }) },
|
|
643
|
+
async (ctx) => {
|
|
644
|
+
const db = ctx.context.adapter;
|
|
645
|
+
const { store, provider } = build(db);
|
|
646
|
+
await assertOrgAdmin(db, ctx.context.session.user.id, ctx.body.organizationId);
|
|
647
|
+
const results = [];
|
|
648
|
+
for (let to = await store.parentOf(ctx.body.organizationId); to; to = await store.parentOf(to)) {
|
|
649
|
+
try {
|
|
650
|
+
await provider.ensureDestination(ctx.body.organizationId, to);
|
|
651
|
+
results.push({ toOrganizationId: to, status: "ready" });
|
|
652
|
+
} catch (e) {
|
|
653
|
+
results.push({ toOrganizationId: to, status: "error", message: e.message });
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
return ctx.json({ results });
|
|
657
|
+
}
|
|
658
|
+
),
|
|
659
|
+
/** The PARENT's admin sets what the parent takes from a child's payments. */
|
|
660
|
+
setFeeRule: (0, import_api.createAuthEndpoint)(
|
|
661
|
+
"/nuvion/fee-rule",
|
|
662
|
+
{
|
|
663
|
+
method: "POST",
|
|
664
|
+
use: [import_api.sessionMiddleware],
|
|
665
|
+
body: z.object({
|
|
666
|
+
organizationId: z.string(),
|
|
667
|
+
flatMinor: z.number().int().min(0).default(0),
|
|
668
|
+
bps: z.number().int().min(0).max(1e4).default(0),
|
|
669
|
+
minMinor: z.number().int().min(0).optional(),
|
|
670
|
+
capMinor: z.number().int().min(0).optional(),
|
|
671
|
+
bearer: z.enum(["payer", "merchant"]).default("merchant")
|
|
672
|
+
})
|
|
673
|
+
},
|
|
674
|
+
async (ctx) => {
|
|
675
|
+
const db = ctx.context.adapter;
|
|
676
|
+
const { store } = build(db);
|
|
677
|
+
const parent = await store.parentOf(ctx.body.organizationId);
|
|
678
|
+
if (!parent) throw new import_api.APIError("BAD_REQUEST", { message: "root organizations have no fee rule" });
|
|
679
|
+
await assertOrgAdmin(db, ctx.context.session.user.id, parent);
|
|
680
|
+
const rule = ctx.body;
|
|
681
|
+
try {
|
|
682
|
+
validateRule(rule);
|
|
683
|
+
} catch (e) {
|
|
684
|
+
throw new import_api.APIError("BAD_REQUEST", { message: e.message });
|
|
685
|
+
}
|
|
686
|
+
const where = [{ field: "organizationId", value: rule.organizationId }];
|
|
687
|
+
const data = { ...rule, minMinor: rule.minMinor ?? null, capMinor: rule.capMinor ?? null };
|
|
688
|
+
if (await db.findOne({ model: "nuvionFeeRule", where })) await db.update({ model: "nuvionFeeRule", where, update: data });
|
|
689
|
+
else await db.create({ model: "nuvionFeeRule", data });
|
|
690
|
+
return ctx.json({ ok: true });
|
|
691
|
+
}
|
|
692
|
+
),
|
|
693
|
+
createPayment: (0, import_api.createAuthEndpoint)(
|
|
694
|
+
"/nuvion/payments",
|
|
695
|
+
{ method: "POST", use: [import_api.sessionMiddleware], body: z.object({ organizationId: z.string(), amountMinor: z.number().int().positive(), currency: z.string().length(3), redirectUrl: z.string().url() }) },
|
|
696
|
+
async (ctx) => {
|
|
697
|
+
const db = ctx.context.adapter;
|
|
698
|
+
await assertOrgAdmin(db, ctx.context.session.user.id, ctx.body.organizationId);
|
|
699
|
+
const { svc } = build(db);
|
|
700
|
+
const r = await svc.createPayment({ ...ctx.body, baseMinor: ctx.body.amountMinor });
|
|
701
|
+
return ctx.json({ paymentId: r.payment.id, checkoutUrl: r.checkoutUrl, chargedMinor: r.payment.chargedMinor, legs: r.quote.legs });
|
|
702
|
+
}
|
|
703
|
+
),
|
|
704
|
+
/** Retry stuck legs (partial failure). Call from a cron or an admin action. */
|
|
705
|
+
retryLegs: (0, import_api.createAuthEndpoint)(
|
|
706
|
+
"/nuvion/payments/retry",
|
|
707
|
+
{ method: "POST", use: [import_api.sessionMiddleware], body: z.object({ paymentId: z.string() }) },
|
|
708
|
+
async (ctx) => {
|
|
709
|
+
const db = ctx.context.adapter;
|
|
710
|
+
const { svc, store } = build(db);
|
|
711
|
+
const p = await store.getPayment(ctx.body.paymentId);
|
|
712
|
+
if (!p) throw new import_api.APIError("NOT_FOUND", { message: "payment not found" });
|
|
713
|
+
await assertOrgAdmin(db, ctx.context.session.user.id, p.organizationId);
|
|
714
|
+
return ctx.json(await svc.executeLegs(p.id));
|
|
715
|
+
}
|
|
716
|
+
),
|
|
717
|
+
/**
|
|
718
|
+
* Start a refund: unsent legs are cancelled and every moved leg gets a reversal leg (beneficiary -> payer-side org),
|
|
719
|
+
* so the merchant account is made whole. Paying the customer back is outside the plugin: Nuvion documents no refund
|
|
720
|
+
* API for funding-session inflows. Each (beneficiary -> origin) pair needs a counterparty, like the forward legs.
|
|
721
|
+
*/
|
|
722
|
+
refundPayment: (0, import_api.createAuthEndpoint)(
|
|
723
|
+
"/nuvion/payments/refund",
|
|
724
|
+
{ method: "POST", use: [import_api.sessionMiddleware], body: z.object({ paymentId: z.string() }) },
|
|
725
|
+
async (ctx) => {
|
|
726
|
+
const db = ctx.context.adapter;
|
|
727
|
+
const { svc, store } = build(db);
|
|
728
|
+
const p = await store.getPayment(ctx.body.paymentId);
|
|
729
|
+
if (!p) throw new import_api.APIError("NOT_FOUND", { message: "payment not found" });
|
|
730
|
+
await assertOrgAdmin(db, ctx.context.session.user.id, p.organizationId);
|
|
731
|
+
if (p.status === "pending") throw new import_api.APIError("BAD_REQUEST", { message: "payment has not been paid yet" });
|
|
732
|
+
return ctx.json(await svc.onRefund(p.id));
|
|
733
|
+
}
|
|
734
|
+
)
|
|
735
|
+
}
|
|
736
|
+
};
|
|
737
|
+
};
|
|
738
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
739
|
+
0 && (module.exports = {
|
|
740
|
+
nuvion
|
|
741
|
+
});
|