commit 8d19233faea19219f1e00dac363da56393e9e13e Author: George Lambert Date: Fri Sep 11 18:03:00 2026 -0400 Initial import of zappier-customer-service from zapier monorepo 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..99d9f1f --- /dev/null +++ b/README.md @@ -0,0 +1,23 @@ +# 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 | +| `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..72f97b6 --- /dev/null +++ b/public/index.html @@ -0,0 +1,144 @@ + + + + + + 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/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..28b99ba --- /dev/null +++ b/src/server.js @@ -0,0 +1,80 @@ +#!/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'; + +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')) { + 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', 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 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/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'); + } +});