Add NATS account-balance SoT and statement review for customers, CS, and sales
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:
George Lambert 2026-09-11 15:35:37 -04:00
parent a1a5b957fd
commit ac38676645
135 changed files with 3078 additions and 130 deletions

View file

@ -0,0 +1,20 @@
export const SUBJECTS = {
STATEMENT_GET: 'verae.billing.statement.get',
BALANCE_ADJUST: 'verae.billing.balance.adjust',
};
export async function billingRequest(subject, payload) {
const url = process.env.NATS_URL;
if (!url) return null;
try {
const { connect, StringCodec } = await import('nats');
const nc = await connect({ servers: url.split(','), name: 'zappier-customer-service' });
const sc = StringCodec();
const m = await nc.request(subject, sc.encode(JSON.stringify(payload)), { timeout: 2000 });
const out = JSON.parse(sc.decode(m.data) || '{}');
await nc.close();
return out;
} catch {
return null;
}
}

View file

@ -1,41 +1,27 @@
#!/usr/bin/env node
/**
* Customer-service department API: goodwill credits, CS notes.
* Source of truth for balances remains zappier-edge admin.
* CS HTTP front door. Internally prefers NATS account-balance, then HTTP.
*/
import http from 'node:http';
import fs from 'node:fs';
import http from 'node:http';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { SUBJECTS, billingRequest } from './nats-billing.js';
const PUBLIC = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'public');
const PORT = Number(process.env.PORT || 3011);
const BOOKS = (process.env.ACCOUNT_BALANCE_URL || 'http://127.0.0.1:3010').replace(/\/$/, '');
const EDGE = (process.env.ZAPPIER_ADMIN_URL || 'http://127.0.0.1:3000').replace(/\/$/, '');
const KEY = process.env.ZAPPIER_ADMIN_KEY || 'admin-dev-key';
const STORE = process.env.CS_STORE || path.join(process.cwd(), 'data', 'credits.json');
function load() {
try {
return JSON.parse(fs.readFileSync(STORE, 'utf8'));
} catch {
return { credits: [] };
}
}
function save(data) {
fs.mkdirSync(path.dirname(STORE), { recursive: true });
fs.writeFileSync(STORE, JSON.stringify(data, null, 2));
}
async function edge(pathname, { method = 'GET', body } = {}) {
const r = await fetch(`${EDGE}${pathname}`, {
method,
headers: { 'content-type': 'application/json', 'x-admin-key': KEY },
body: body ? JSON.stringify(body) : undefined,
});
const text = await r.text();
try {
return { status: r.status, body: JSON.parse(text) };
} catch {
return { status: r.status, body: text };
}
async function statement(customerId) {
const nats = await billingRequest(SUBJECTS.STATEMENT_GET, { customerId });
if (nats) return { status: 200, body: { ...nats, source: 'nats' } };
const r = await fetch(`${BOOKS}/statement/${customerId}`);
if (r.ok) return { status: r.status, body: { ...(await r.json()), source: 'account-balance' } };
const e = await fetch(`${EDGE}/admin/api/statement/${customerId}`, { headers: { 'x-admin-key': KEY } });
return { status: e.status, body: { ...(await e.json().catch(() => ({}))), source: 'edge' } };
}
const server = http.createServer(async (req, res) => {
@ -45,22 +31,43 @@ const server = http.createServer(async (req, res) => {
res.end(JSON.stringify(obj));
};
try {
if (req.method === 'GET' && (url.pathname === '/' || url.pathname === '/index.html')) {
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
res.end(fs.readFileSync(path.join(PUBLIC, 'index.html')));
return;
}
if (req.method === 'GET' && url.pathname === '/health') {
return json(200, { ok: true, role: 'zappier-customer-service' });
return json(200, { ok: true, role: 'zappier-customer-service', nats: Boolean(process.env.NATS_URL) });
}
const review = url.pathname.match(/^\/review\/([^/]+)$/);
if (req.method === 'GET' && review) {
const out = await statement(review[1]);
return json(out.status, out.body);
}
if (req.method === 'POST' && url.pathname === '/credits') {
const chunks = [];
for await (const c of req) chunks.push(c);
const payload = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
const forwarded = await edge('/admin/api/credits', { method: 'POST', body: payload });
const data = load();
data.credits.unshift({ ...payload, at: new Date().toISOString(), edge: forwarded.status });
save(data);
return json(forwarded.status, forwarded.body);
const nats = await billingRequest(SUBJECTS.BALANCE_ADJUST, { ...payload, kind: 'credit' });
if (nats) return json(200, { ...nats, source: 'nats' });
const r = await fetch(`${BOOKS}/adjust`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(payload),
});
const body = await r.json().catch(() => ({}));
await fetch(`${EDGE}/admin/api/credits`, {
method: 'POST',
headers: { 'content-type': 'application/json', 'x-admin-key': KEY },
body: JSON.stringify(payload),
}).catch(() => {});
return json(r.status, body);
}
if (req.method === 'GET' && url.pathname === '/credits') {
const forwarded = await edge(`/admin/api/credits${url.search}`);
return json(forwarded.status, forwarded.body);
const id = url.searchParams.get('customerId');
if (!id) return json(400, { error: 'customerId required' });
const out = await statement(id);
return json(out.status, { credits: out.body.credits || [] });
}
json(404, { error: 'not found' });
} catch (err) {
@ -69,5 +76,5 @@ const server = http.createServer(async (req, res) => {
});
server.listen(PORT, '0.0.0.0', () => {
process.stdout.write(`zappier-customer-service http://127.0.0.1:${PORT}/\n`);
process.stdout.write(`zappier-customer-service http://0.0.0.0:${PORT}/\n`);
});