Initial import of zappier-sales-pricing from zapier monorepo
This commit is contained in:
commit
ad0fe8e202
7 changed files with 305 additions and 0 deletions
19
README.md
Normal file
19
README.md
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
# zappier-sales-pricing
|
||||
|
||||
Sales-department API for **per-customer pricing** (tier + `multiplierOverride`). zappier-edge remains the rate-card store.
|
||||
|
||||
**Forgejo:** https://git.georgelambert.org/marchon/zappier-sales-pricing
|
||||
**Catalog:** https://zapier.georgelambert.org/packages/zappier-sales-pricing/README.pdf
|
||||
|
||||
Internal reviews use NATS `verae.billing.statement.get` (account-balance).
|
||||
|
||||
Staff UI: http://127.0.0.1:3012/ — review credits, balances, usage, payments.
|
||||
|
||||
```bash
|
||||
PORT=3012 NATS_URL=nats://127.0.0.1:4222 node src/server.js
|
||||
curl http://127.0.0.1:3012/review/cust_2
|
||||
curl http://127.0.0.1:3012/quotes/cust_2
|
||||
curl -X PUT http://127.0.0.1:3012/customers/cust_2/pricing \
|
||||
-H 'content-type: application/json' \
|
||||
-d '{"multiplierOverride":0.4,"tierId":"business"}'
|
||||
```
|
||||
46
package-lock.json
generated
Normal file
46
package-lock.json
generated
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
{
|
||||
"name": "zappier-sales-pricing",
|
||||
"version": "0.1.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "zappier-sales-pricing",
|
||||
"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-sales-pricing",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "Sales-department per-customer pricing; writes multiplier/tier on zappier-edge",
|
||||
"scripts": {
|
||||
"start": "node src/server.js",
|
||||
"test": "node --test test/*.test.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"nats": "^2.28.2"
|
||||
}
|
||||
}
|
||||
56
public/index.html
Normal file
56
public/index.html
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Sales — customer 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>Sales</h1>
|
||||
<p class="muted">Review customer credits, balances, usage, and payments (NATS account-balance). Pricing writes still go to zappier-edge.</p>
|
||||
<div class="card">
|
||||
<label>Customer id</label>
|
||||
<input id="id" value="cust_2" />
|
||||
<button onclick="review()">Review</button>
|
||||
<button onclick="quote()">Quote</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 quote() {
|
||||
const id = document.getElementById('id').value.trim();
|
||||
const q = await (await fetch('/quotes/' + encodeURIComponent(id))).json();
|
||||
document.getElementById('out').innerHTML = `<pre>${JSON.stringify(q, null, 2)}</pre>`;
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
36
src/nats-billing.js
Normal file
36
src/nats-billing.js
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
export const SUBJECTS = { STATEMENT_GET: 'verae.billing.statement.get' };
|
||||
const PLANE = 'staff';
|
||||
|
||||
async function authz(subject) {
|
||||
const http = process.env.AUTHZ_URL;
|
||||
if (!http) return { allow: true, subject };
|
||||
const r = await fetch(`${http.replace(/\/$/, '')}/check`, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ plane: PLANE, subject }),
|
||||
});
|
||||
return r.json();
|
||||
}
|
||||
|
||||
export async function billingRequest(subject, payload) {
|
||||
const decision = await authz(subject);
|
||||
if (decision && decision.allow === false) {
|
||||
const err = new Error(decision.reason || 'denied');
|
||||
err.status = 403;
|
||||
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-sales-pricing' });
|
||||
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;
|
||||
}
|
||||
}
|
||||
76
src/server.js
Normal file
76
src/server.js
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
#!/usr/bin/env node
|
||||
/** Sales department: per-customer multiplier / tier. Writes through zappier-edge. */
|
||||
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 || 3012);
|
||||
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 BOOKS = (process.env.ACCOUNT_BALANCE_URL || 'http://127.0.0.1:3010').replace(/\/$/, '');
|
||||
|
||||
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 };
|
||||
}
|
||||
}
|
||||
|
||||
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-sales-pricing' });
|
||||
}
|
||||
const review = url.pathname.match(/^\/review\/([^/]+)$/);
|
||||
if (req.method === 'GET' && review) {
|
||||
const nats = await billingRequest(SUBJECTS.STATEMENT_GET, { customerId: review[1] });
|
||||
if (nats) return json(200, { ...nats, source: 'nats' });
|
||||
const r = await fetch(`${BOOKS}/statement/${review[1]}`);
|
||||
if (r.ok) return json(200, { ...(await r.json()), source: 'account-balance' });
|
||||
const e = await edge(`/admin/api/statement/${review[1]}`);
|
||||
return json(e.status, e.body);
|
||||
}
|
||||
const quote = url.pathname.match(/^\/quotes\/([^/]+)$/);
|
||||
if (req.method === 'GET' && quote) {
|
||||
const forwarded = await edge(`/admin/api/sales/quote/${quote[1]}`);
|
||||
return json(forwarded.status, forwarded.body);
|
||||
}
|
||||
const price = url.pathname.match(/^\/customers\/([^/]+)\/pricing$/);
|
||||
if (req.method === 'PUT' && price) {
|
||||
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/customers/${price[1]}`, { method: 'PUT', body: payload });
|
||||
return json(forwarded.status, forwarded.body);
|
||||
}
|
||||
json(404, { error: 'not found' });
|
||||
} catch (err) {
|
||||
json(err.status === 403 ? 403 : 502, { error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
server.listen(PORT, '0.0.0.0', () => {
|
||||
process.stdout.write(`zappier-sales-pricing http://127.0.0.1:${PORT}/\n`);
|
||||
});
|
||||
58
test/health.test.js
Normal file
58
test/health.test.js
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
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.join(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
|
||||
test('sales-pricing health', async () => {
|
||||
const port = 18012;
|
||||
const child = spawn(process.execPath, ['src/server.js'], {
|
||||
cwd: 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`);
|
||||
assert.equal((await r.json()).role, 'zappier-sales-pricing');
|
||||
const home = await fetch(`http://127.0.0.1:${port}/`);
|
||||
assert.equal(home.status, 200);
|
||||
} finally {
|
||||
child.kill('SIGTERM');
|
||||
}
|
||||
});
|
||||
|
||||
test('sales review via account-balance HTTP', async () => {
|
||||
const booksPort = 18016;
|
||||
const salesPort = 18017;
|
||||
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 sales = spawn(process.execPath, ['src/server.js'], {
|
||||
cwd: root,
|
||||
env: {
|
||||
...process.env,
|
||||
PORT: String(salesPort),
|
||||
ACCOUNT_BALANCE_URL: `http://127.0.0.1:${booksPort}`,
|
||||
},
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
});
|
||||
await new Promise((r) => setTimeout(r, 500));
|
||||
try {
|
||||
await fetch(`http://127.0.0.1:${booksPort}/adjust`, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ customerId: 'c-sales', cents: 300, reason: 'promo', agent: 'sales' }),
|
||||
});
|
||||
const st = await (await fetch(`http://127.0.0.1:${salesPort}/review/c-sales`)).json();
|
||||
assert.equal(st.prepaidCents, 300);
|
||||
assert.equal(st.source, 'account-balance');
|
||||
} finally {
|
||||
sales.kill('SIGTERM');
|
||||
books.kill('SIGTERM');
|
||||
}
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue