From 6a166a93d605d1dcc17c768d557b89afdcbf7615 Mon Sep 17 00:00:00 2001 From: George Lambert Date: Fri, 11 Sep 2026 18:27:02 -0400 Subject: [PATCH] Initial import of zappier-customer-service from zapier monorepo --- .gitignore | 2 + README.md | 24 +++++++ package-lock.json | 46 +++++++++++++ package.json | 14 ++++ public/index.html | 157 ++++++++++++++++++++++++++++++++++++++++++++ src/names.js | 37 +++++++++++ src/nats-billing.js | 44 +++++++++++++ src/server.js | 106 ++++++++++++++++++++++++++++++ src/staff-page.js | 16 +++++ test/health.test.js | 62 +++++++++++++++++ 10 files changed, 508 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 public/index.html create mode 100644 src/names.js create mode 100644 src/nats-billing.js create mode 100644 src/server.js create mode 100644 src/staff-page.js create mode 100644 test/health.test.js diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..dd950c9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +data/ +node_modules/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..68f97da --- /dev/null +++ b/README.md @@ -0,0 +1,24 @@ +# zappier-customer-service + +Department API for **customer-service credit additions** and **review** of credits, balances, usage, and payments. Internally uses **NATS** `verae.billing.*` (account-balance). HTTP fallback to account-balance then zappier-edge. + +**Forgejo:** https://git.georgelambert.org/marchon/zappier-customer-service +**Catalog:** https://zapier.georgelambert.org/packages/zappier-customer-service/README.pdf +**Plugs into:** zappier-edge admin (`x-admin-key`) at `ZAPPIER_ADMIN_URL` (default `http://127.0.0.1:3000`). + +```bash +PORT=3011 ZAPPIER_ADMIN_URL=http://127.0.0.1:3000 node src/server.js +curl -X POST http://127.0.0.1:3011/credits -H 'content-type: application/json' \ + -d '{"customerId":"cust_1","cents":500,"reason":"goodwill","agent":"cs-anna"}' +``` + +| Route | Job | +|-------|-----| +| `GET /` | Staff review UI (typeahead names). `STAFF_AUTH=1` redirects to `verae-staff-session`. | +| `GET /customers` | `{ customers }` from zappier-edge | +| `GET /health` | `{ ok, role }` | +| `POST /credits` | Add/subtract prepaid cents (NATS `balance.adjust`) | +| `GET /credits?customerId=` | Ledger | +| `GET /review/:customerId` | Full statement (balance, credits, usage, payments) | + +Talks to NATS `verae.billing.*` internally. Never talks to Zapier cloud. diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..d0b6619 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,46 @@ +{ + "name": "zappier-customer-service", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "zappier-customer-service", + "version": "0.1.0", + "dependencies": { + "nats": "^2.28.2" + } + }, + "node_modules/nats": { + "version": "2.29.3", + "resolved": "https://registry.npmjs.org/nats/-/nats-2.29.3.tgz", + "integrity": "sha512-tOQCRCwC74DgBTk4pWZ9V45sk4d7peoE2njVprMRCBXrhJ5q5cYM7i6W+Uvw2qUrcfOSnuisrX7bEx3b3Wx4QA==", + "deprecated": "Package moved. Use @nats-io/transport-node from https://github.com/nats-io/nats.js", + "license": "Apache-2.0", + "dependencies": { + "nkeys.js": "1.1.0" + }, + "engines": { + "node": ">= 14.0.0" + } + }, + "node_modules/nkeys.js": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/nkeys.js/-/nkeys.js-1.1.0.tgz", + "integrity": "sha512-tB/a0shZL5UZWSwsoeyqfTszONTt4k2YS0tuQioMOD180+MbombYVgzDUYHlx+gejYK6rgf08n/2Df99WY0Sxg==", + "license": "Apache-2.0", + "dependencies": { + "tweetnacl": "1.0.3" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/tweetnacl": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz", + "integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==", + "license": "Unlicense" + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..c7e23b9 --- /dev/null +++ b/package.json @@ -0,0 +1,14 @@ +{ + "name": "zappier-customer-service", + "version": "0.1.0", + "private": true, + "type": "module", + "description": "Customer-service credits and notes; writes prepaid balances on zappier-edge", + "scripts": { + "start": "node src/server.js", + "test": "node --test test/*.test.js" + }, + "dependencies": { + "nats": "^2.28.2" + } +} diff --git a/public/index.html b/public/index.html new file mode 100644 index 0000000..2ab96f9 --- /dev/null +++ b/public/index.html @@ -0,0 +1,157 @@ + + + + + + Customer service — account review + + + + + +
+
staff · customer service
+

Customer service

+

Look up a customer by name or id. Review prepaid balance, credits, usage, and payments. Credit amounts are in dollars.

+
+
+
+
+
+ + + +
+ +
+
+
+

Apply credit

+
+
+ + +
+
+ + +
+
+ + +
+ +
+

Credits write to account-balance. The customer sees dollars, not cents.

+
+
+
+ + + diff --git a/src/names.js b/src/names.js new file mode 100644 index 0000000..ff1e72f --- /dev/null +++ b/src/names.js @@ -0,0 +1,37 @@ +/** Join ledger ids to zappier-edge customer display names. */ +export async function listCustomers(edge, key) { + try { + const r = await fetch(`${edge.replace(/\/$/, '')}/admin/api/customers`, { + headers: { 'x-admin-key': key }, + }); + const body = await r.json(); + return (body.customers || []).map(({ passwordHash, apiKey, totpSecret, ...rest }) => rest); + } catch { + return []; + } +} + +export async function withCustomerName(st, idOrName, edge, key) { + const out = { ...(st || {}) }; + if (out.name && out.customerId) return out; + try { + const r = await fetch(`${edge.replace(/\/$/, '')}/admin/api/customers`, { + headers: { 'x-admin-key': key }, + }); + const { customers } = await r.json(); + const want = String(idOrName || out.customerId || '').toLowerCase(); + const c = (customers || []).find( + (x) => + x.id === idOrName || + x.id === out.customerId || + String(x.name || '').toLowerCase() === want, + ); + if (c) { + out.name = c.name; + out.customerId = c.id; + } + } catch { + /* edge optional */ + } + return out; +} diff --git a/src/nats-billing.js b/src/nats-billing.js new file mode 100644 index 0000000..2a9d87d --- /dev/null +++ b/src/nats-billing.js @@ -0,0 +1,44 @@ +export const SUBJECTS = { + STATEMENT_GET: 'verae.billing.statement.get', + BALANCE_ADJUST: 'verae.billing.balance.adjust', + AUTHZ_CHECK: 'verae.access.authz.check', +}; +const PLANE = 'staff'; + +async function authz(subject, payload) { + const http = process.env.AUTHZ_URL; + if (!http && !process.env.NATS_URL) return { allow: true, subject }; + if (http) { + const r = await fetch(`${http.replace(/\/$/, '')}/check`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ plane: PLANE, subject, kind: payload?.kind, payload, principal: payload?.agent }), + }); + return r.json(); + } + return { allow: true, subject }; +} + +export async function billingRequest(subject, payload) { + const decision = await authz(subject, payload); + if (decision && decision.allow === false) { + const err = new Error(decision.reason || 'denied'); + err.status = 403; + err.decision = decision; + throw err; + } + 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, plane: PLANE })), { timeout: 2000 }); + const out = JSON.parse(sc.decode(m.data) || '{}'); + await nc.close(); + return out; + } catch (err) { + if (err.status === 403) throw err; + return null; + } +} diff --git a/src/server.js b/src/server.js new file mode 100644 index 0000000..8f069fa --- /dev/null +++ b/src/server.js @@ -0,0 +1,106 @@ +#!/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'; + +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 (process.env.STAFF_AUTH === '1') { + const login = (process.env.STAFF_SESSION_URL || 'http://127.0.0.1:3027').replace(/\/$/, ''); + const chk = await fetch(`${login}/check`, { headers: { cookie: req.headers.cookie || '' } }).catch(() => null); + if (!chk || !chk.ok) { + const next = `http://${req.headers.host || '127.0.0.1'}/`; + res.writeHead(302, { location: `${login}/login?next=${encodeURIComponent(next)}` }); + res.end(); + 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') { + return json(200, { customers: await listCustomers(EDGE, KEY) }); + } + const review = url.pathname.match(/^\/review\/([^/]+)$/); + if (req.method === 'GET' && review) { + 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 chunks = []; + for await (const c of req) chunks.push(c); + const payload = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}'); + 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 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`); +}); diff --git a/src/staff-page.js b/src/staff-page.js new file mode 100644 index 0000000..88ec449 --- /dev/null +++ b/src/staff-page.js @@ -0,0 +1,16 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { pathToFileURL } from 'node:url'; + +export async function staffPageHtml(opts, fallbackPath) { + const sibling = path.join(path.dirname(fallbackPath), '..', '..', 'verae-staff-ui', 'src', 'load.js'); + try { + if (fs.existsSync(sibling)) { + const { loadReviewHtml } = await import(pathToFileURL(sibling).href); + return loadReviewHtml(opts, fallbackPath); + } + } catch { + /* standalone clone */ + } + return fs.readFileSync(fallbackPath, 'utf8'); +} diff --git a/test/health.test.js b/test/health.test.js new file mode 100644 index 0000000..876eb6b --- /dev/null +++ b/test/health.test.js @@ -0,0 +1,62 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { spawn } from 'node:child_process'; +import { fileURLToPath } from 'node:url'; +import path from 'node:path'; + +const root = path.dirname(fileURLToPath(new URL('.', import.meta.url))); + +test('customer-service health', async () => { + const port = 18011; + const child = spawn(process.execPath, ['src/server.js'], { + cwd: path.join(root), + env: { ...process.env, PORT: String(port) }, + stdio: ['ignore', 'pipe', 'pipe'], + }); + await new Promise((r) => setTimeout(r, 400)); + try { + const r = await fetch(`http://127.0.0.1:${port}/health`); + const body = await r.json(); + assert.equal(body.role, 'zappier-customer-service'); + const home = await fetch(`http://127.0.0.1:${port}/`); + assert.equal(home.status, 200); + assert.match(await home.text(), /Customer service/); + } finally { + child.kill('SIGTERM'); + } +}); + +test('customer-service review via account-balance HTTP', async () => { + const booksPort = 18014; + const csPort = 18015; + const books = spawn(process.execPath, ['src/server.js'], { + cwd: path.join(root, '..', 'zappier-account-balance'), + env: { ...process.env, PORT: String(booksPort) }, + stdio: ['ignore', 'pipe', 'pipe'], + }); + const cs = spawn(process.execPath, ['src/server.js'], { + cwd: path.join(root), + env: { + ...process.env, + PORT: String(csPort), + ACCOUNT_BALANCE_URL: `http://127.0.0.1:${booksPort}`, + }, + stdio: ['ignore', 'pipe', 'pipe'], + }); + await new Promise((r) => setTimeout(r, 500)); + try { + const add = await fetch(`http://127.0.0.1:${csPort}/credits`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ customerId: 'c-review', cents: 700, reason: 'goodwill', agent: 'cs' }), + }); + assert.equal(add.status, 200); + const st = await (await fetch(`http://127.0.0.1:${csPort}/review/c-review`)).json(); + assert.equal(st.prepaidCents, 700); + assert.equal(st.source, 'account-balance'); + assert.equal(st.credits[0].reason, 'goodwill'); + } finally { + cs.kill('SIGTERM'); + books.kill('SIGTERM'); + } +});