Initial import of zappier-customer-service from zapier monorepo

This commit is contained in:
George Lambert 2026-09-11 19:09:47 -04:00
commit 8adae77807
11 changed files with 547 additions and 0 deletions

104
src/server.js Normal file
View file

@ -0,0 +1,104 @@
#!/usr/bin/env node
/**
* CS HTTP front door. Internally prefers NATS account-balance, then 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';
import { listCustomers, withCustomerName } from './names.js';
import { staffPageHtml } from './staff-page.js';
import { denyOrRedirect } from './iam-gate.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';
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) => {
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 === '/' || url.pathname === '/index.html')) {
if (!(await denyOrRedirect(req, res, json, { permission: 'cs.review', html: true }))) return;
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
res.end(
await staffPageHtml(
{
title: 'Customer service',
kicker: 'staff · customer service',
lede: 'Look up a customer by name. Review prepaid balance, credits, usage, and payments. Credit amounts are in dollars.',
},
path.join(PUBLIC, 'index.html'),
),
);
return;
}
if (req.method === 'GET' && url.pathname === '/health') {
return json(200, { ok: true, role: 'zappier-customer-service', nats: Boolean(process.env.NATS_URL) });
}
if (req.method === 'GET' && url.pathname === '/customers') {
if (!(await denyOrRedirect(req, res, json, { permission: 'cs.review' }))) return;
return json(200, { customers: await listCustomers(EDGE, KEY) });
}
const review = url.pathname.match(/^\/review\/([^/]+)$/);
if (req.method === 'GET' && review) {
if (!(await denyOrRedirect(req, res, json, { permission: 'cs.review' }))) return;
const id = decodeURIComponent(review[1]);
const out = await statement(id);
out.body = await withCustomerName(out.body, id, EDGE, KEY);
return json(out.status, out.body);
}
if (req.method === 'POST' && url.pathname === '/credits') {
const who = await denyOrRedirect(req, res, json, { permission: 'cs.credit' });
if (!who) return;
const chunks = [];
for await (const c of req) chunks.push(c);
const payload = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
if (who.user?.username) payload.agent = who.user.username;
const nats = await billingRequest(SUBJECTS.BALANCE_ADJUST, { ...payload, kind: 'credit', principal: payload.agent });
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') {
if (!(await denyOrRedirect(req, res, json, { permission: 'cs.review' }))) return;
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) {
json(err.status === 403 ? 403 : 502, { error: err.message, ...(err.decision || {}) });
}
});
server.listen(PORT, '0.0.0.0', () => {
process.stdout.write(`zappier-customer-service http://0.0.0.0:${PORT}/\n`);
});