Add NATS account-balance SoT and statement review for customers, CS, and sales
Some checks are pending
offline / test (push) Waiting to run
Some checks are pending
offline / test (push) Waiting to run
Internal billing now uses verae.billing.* request-reply and pubs. zappier-account-balance tracks prepaid, credits, usage, and payments. Portal, admin, CS, and sales all review the same statement. Independent Forgejo repos stay split via push-module-repos.
This commit is contained in:
parent
a1a5b957fd
commit
ac38676645
135 changed files with 3078 additions and 130 deletions
89
packages/zappier-account-balance/src/books.js
Normal file
89
packages/zappier-account-balance/src/books.js
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
/**
|
||||
* Source of truth for prepaid balances, CS credits, usage, and payments.
|
||||
*/
|
||||
export class AccountBooks {
|
||||
constructor() {
|
||||
/** @type {Record<string, number>} */
|
||||
this.prepaid = {};
|
||||
this.credits = [];
|
||||
this.usage = [];
|
||||
this.payments = [];
|
||||
}
|
||||
|
||||
prepaidCents(customerId) {
|
||||
return this.prepaid[customerId] ?? 0;
|
||||
}
|
||||
|
||||
adjust({ customerId, cents, reason, agent, kind = 'credit' }) {
|
||||
const delta = Math.trunc(Number(cents) || 0);
|
||||
const next = this.prepaidCents(customerId) + delta;
|
||||
this.prepaid[customerId] = next;
|
||||
const row = {
|
||||
id: `adj_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 6)}`,
|
||||
customerId,
|
||||
cents: delta,
|
||||
reason: reason || kind,
|
||||
agent: agent || 'system',
|
||||
kind,
|
||||
at: new Date().toISOString(),
|
||||
prepaidCents: next,
|
||||
};
|
||||
if (kind === 'payment' || kind === 'reload') this.payments.unshift(row);
|
||||
else this.credits.unshift(row);
|
||||
return row;
|
||||
}
|
||||
|
||||
recordUsage(entry) {
|
||||
const cents = Number(entry.cents) || 0;
|
||||
const customerId = entry.customerId;
|
||||
const next = this.prepaidCents(customerId) - cents;
|
||||
this.prepaid[customerId] = next;
|
||||
const row = {
|
||||
customerId,
|
||||
endpointId: entry.endpointId || 'unknown',
|
||||
cents,
|
||||
at: entry.at || new Date().toISOString(),
|
||||
prepaidCents: next,
|
||||
};
|
||||
this.usage.unshift(row);
|
||||
return row;
|
||||
}
|
||||
|
||||
recordPayment(entry) {
|
||||
return this.adjust({
|
||||
customerId: entry.customerId,
|
||||
cents: Number(entry.cents) || 0,
|
||||
reason: entry.reason || 'payment',
|
||||
agent: entry.agent || 'payments',
|
||||
kind: 'payment',
|
||||
});
|
||||
}
|
||||
|
||||
statement(customerId) {
|
||||
const match = (rows) => rows.filter((r) => r.customerId === customerId).slice(0, 100);
|
||||
return {
|
||||
customerId,
|
||||
prepaidCents: this.prepaidCents(customerId),
|
||||
credits: match(this.credits),
|
||||
usage: match(this.usage),
|
||||
payments: match(this.payments),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export function handle(subject, payload, books) {
|
||||
const p = payload || {};
|
||||
if (subject.endsWith('balance.get') || subject.endsWith('statement.get')) {
|
||||
return books.statement(p.customerId);
|
||||
}
|
||||
if (subject.endsWith('balance.adjust') || subject.endsWith('credit.applied')) {
|
||||
return books.adjust(p);
|
||||
}
|
||||
if (subject.endsWith('usage.recorded')) {
|
||||
return books.recordUsage(p);
|
||||
}
|
||||
if (subject.endsWith('payment.recorded')) {
|
||||
return books.recordPayment(p);
|
||||
}
|
||||
throw new Error(`unknown billing subject ${subject}`);
|
||||
}
|
||||
92
packages/zappier-account-balance/src/server.js
Normal file
92
packages/zappier-account-balance/src/server.js
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
#!/usr/bin/env node
|
||||
import http from 'node:http';
|
||||
import { AccountBooks, handle } from './books.js';
|
||||
import { SUBJECTS } from './subjects.js';
|
||||
|
||||
const PORT = Number(process.env.PORT || process.env.FLEET_HEALTH_PORT || 3010);
|
||||
const BIND = process.env.FLEET_HEALTH_BIND || '0.0.0.0';
|
||||
const books = new AccountBooks();
|
||||
let natsOk = false;
|
||||
|
||||
async function startNats() {
|
||||
const url = process.env.NATS_URL;
|
||||
if (!url) return;
|
||||
const { connect, StringCodec } = await import('nats');
|
||||
const nc = await connect({ servers: url.split(','), name: 'zappier-account-balance' });
|
||||
const sc = StringCodec();
|
||||
const reply = async (sub, fn) => {
|
||||
for await (const m of sub) {
|
||||
let payload = {};
|
||||
try {
|
||||
payload = JSON.parse(sc.decode(m.data) || '{}');
|
||||
} catch {
|
||||
payload = {};
|
||||
}
|
||||
const out = fn(payload);
|
||||
if (m.reply) m.respond(sc.encode(JSON.stringify(out)));
|
||||
}
|
||||
};
|
||||
reply(nc.subscribe(SUBJECTS.STATEMENT_GET, { queue: SUBJECTS.QUEUE }), (p) =>
|
||||
handle(SUBJECTS.STATEMENT_GET, p, books),
|
||||
);
|
||||
reply(nc.subscribe(SUBJECTS.BALANCE_GET, { queue: SUBJECTS.QUEUE }), (p) =>
|
||||
handle(SUBJECTS.BALANCE_GET, p, books),
|
||||
);
|
||||
reply(nc.subscribe(SUBJECTS.BALANCE_ADJUST, { queue: SUBJECTS.QUEUE }), (p) =>
|
||||
handle(SUBJECTS.BALANCE_ADJUST, p, books),
|
||||
);
|
||||
(async () => {
|
||||
for await (const m of nc.subscribe(SUBJECTS.USAGE_RECORDED)) {
|
||||
handle(SUBJECTS.USAGE_RECORDED, JSON.parse(sc.decode(m.data) || '{}'), books);
|
||||
}
|
||||
})();
|
||||
// payment.recorded / credit.applied are fan-out events. Prepaid mutations
|
||||
// go through balance.adjust so publishers can both pub and request-reply.
|
||||
natsOk = true;
|
||||
process.stdout.write(`account-balance nats ${url}\n`);
|
||||
}
|
||||
|
||||
function readBody(req) {
|
||||
return new Promise((resolve) => {
|
||||
const chunks = [];
|
||||
req.on('data', (c) => chunks.push(c));
|
||||
req.on('end', () => {
|
||||
try {
|
||||
resolve(JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}'));
|
||||
} catch {
|
||||
resolve({});
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
const server = http.createServer(async (req, res) => {
|
||||
const url = new URL(req.url || '/', `http://127.0.0.1:${PORT}`);
|
||||
const json = (code, obj) => {
|
||||
res.writeHead(code, { 'content-type': 'application/json' });
|
||||
res.end(JSON.stringify(obj));
|
||||
};
|
||||
try {
|
||||
if (req.method === 'GET' && url.pathname === '/health') {
|
||||
return json(200, { ok: true, role: 'zappier-account-balance', nats: natsOk, subjects: SUBJECTS });
|
||||
}
|
||||
const st = url.pathname.match(/^\/statement\/([^/]+)$/);
|
||||
if (req.method === 'GET' && st) {
|
||||
return json(200, books.statement(st[1]));
|
||||
}
|
||||
if (req.method === 'POST' && url.pathname === '/adjust') {
|
||||
const body = await readBody(req);
|
||||
return json(200, books.adjust(body));
|
||||
}
|
||||
json(404, { error: 'not found' });
|
||||
} catch (err) {
|
||||
json(500, { error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
server.listen(PORT, BIND, () => {
|
||||
process.stdout.write(`zappier-account-balance http://${BIND}:${PORT}/\n`);
|
||||
});
|
||||
startNats().catch((err) => {
|
||||
process.stderr.write(`nats optional: ${err.message}\n`);
|
||||
});
|
||||
10
packages/zappier-account-balance/src/subjects.js
Normal file
10
packages/zappier-account-balance/src/subjects.js
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
/** Internal billing bus. Zapier cloud never subscribes. */
|
||||
export const SUBJECTS = {
|
||||
BALANCE_GET: 'verae.billing.balance.get',
|
||||
BALANCE_ADJUST: 'verae.billing.balance.adjust',
|
||||
STATEMENT_GET: 'verae.billing.statement.get',
|
||||
USAGE_RECORDED: 'verae.billing.usage.recorded',
|
||||
PAYMENT_RECORDED: 'verae.billing.payment.recorded',
|
||||
CREDIT_APPLIED: 'verae.billing.credit.applied',
|
||||
QUEUE: 'account-balance',
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue