Initial import of zappier-customer-service from zapier monorepo
This commit is contained in:
commit
ed618e1679
8 changed files with 338 additions and 0 deletions
2
.gitignore
vendored
Normal file
2
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
data/
|
||||
node_modules/
|
||||
23
README.md
Normal file
23
README.md
Normal file
|
|
@ -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.
|
||||
46
package-lock.json
generated
Normal file
46
package-lock.json
generated
Normal file
|
|
@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
14
package.json
Normal file
14
package.json
Normal file
|
|
@ -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"
|
||||
}
|
||||
}
|
||||
67
public/index.html
Normal file
67
public/index.html
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Customer service — account review</title>
|
||||
<style>
|
||||
body { font-family: -apple-system, sans-serif; margin: 2rem; max-width: 960px; color: #171a26; }
|
||||
h1 { font-size: 1.3rem; }
|
||||
label { font-size: 0.8rem; font-weight: 600; display: block; margin-top: 0.6rem; }
|
||||
input { padding: 0.4rem 0.55rem; }
|
||||
button { margin-top: 0.8rem; padding: 0.4rem 0.8rem; }
|
||||
table { border-collapse: collapse; width: 100%; margin-top: 0.6rem; }
|
||||
th, td { border-bottom: 1px solid #e5e7f0; padding: 0.4rem 0.5rem; text-align: left; font-size: 0.88rem; }
|
||||
.muted { color: #6b7186; }
|
||||
.card { border: 1px solid #e5e7f0; border-radius: 10px; padding: 1rem; margin: 1rem 0; }
|
||||
.stat { font-size: 1.4rem; font-weight: 800; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Customer service</h1>
|
||||
<p class="muted">Review prepaid balance, credits, usage, and payments. Credits go to account-balance over NATS.</p>
|
||||
<div class="card">
|
||||
<label>Customer id</label>
|
||||
<input id="id" value="cust_1" />
|
||||
<button onclick="review()">Review</button>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h3>Add credit</h3>
|
||||
<label>Cents</label><input id="cents" type="number" value="500" />
|
||||
<label>Reason</label><input id="reason" value="goodwill" />
|
||||
<label>Agent</label><input id="agent" value="cs" />
|
||||
<button onclick="credit()">Apply credit</button>
|
||||
</div>
|
||||
<div id="out"></div>
|
||||
<script>
|
||||
const fmt = (c) => (c < 0 ? '-$' : '$') + (Math.abs(c || 0) / 100).toFixed(2);
|
||||
const rows = (list, cols) =>
|
||||
(list || [])
|
||||
.map((r) => '<tr>' + cols.map((c) => `<td>${r[c] ?? ''}</td>`).join('') + '</tr>')
|
||||
.join('') || '<tr><td colspan="8" class="muted">none</td></tr>';
|
||||
async function review() {
|
||||
const id = document.getElementById('id').value.trim();
|
||||
const st = await (await fetch('/review/' + encodeURIComponent(id))).json();
|
||||
document.getElementById('out').innerHTML = `
|
||||
<div class="card"><div class="muted">Prepaid</div><div class="stat">${fmt(st.prepaidCents)}</div>
|
||||
<p class="muted">source ${st.source || 'unknown'}</p></div>
|
||||
<div class="card"><h3>Credits</h3><table><thead><tr><th>cents</th><th>reason</th><th>agent</th><th>at</th></tr></thead>
|
||||
<tbody>${rows(st.credits, ['cents','reason','agent','at'])}</tbody></table></div>
|
||||
<div class="card"><h3>Usage</h3><table><thead><tr><th>endpoint</th><th>cents</th><th>at</th></tr></thead>
|
||||
<tbody>${rows(st.usage, ['endpointId','cents','at'])}</tbody></table></div>
|
||||
<div class="card"><h3>Payments</h3><table><thead><tr><th>cents</th><th>kind</th><th>reason</th><th>at</th></tr></thead>
|
||||
<tbody>${rows(st.payments, ['cents','kind','reason','at'])}</tbody></table></div>`;
|
||||
}
|
||||
async function credit() {
|
||||
const body = {
|
||||
customerId: document.getElementById('id').value.trim(),
|
||||
cents: Number(document.getElementById('cents').value),
|
||||
reason: document.getElementById('reason').value,
|
||||
agent: document.getElementById('agent').value,
|
||||
};
|
||||
await fetch('/credits', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
|
||||
await review();
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
44
src/nats-billing.js
Normal file
44
src/nats-billing.js
Normal file
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
80
src/server.js
Normal file
80
src/server.js
Normal file
|
|
@ -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`);
|
||||
});
|
||||
62
test/health.test.js
Normal file
62
test/health.test.js
Normal file
|
|
@ -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');
|
||||
}
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue