From 32ef7e966be3442fbc92e3aa5224def553a7a3aa Mon Sep 17 00:00:00 2001 From: George Lambert Date: Fri, 11 Sep 2026 18:38:17 -0400 Subject: [PATCH] Initial import of zappier-sales-pricing from zapier monorepo --- README.md | 19 ++++++ package-lock.json | 46 +++++++++++++ package.json | 14 ++++ public/index.html | 153 ++++++++++++++++++++++++++++++++++++++++++++ src/iam-gate.js | 35 ++++++++++ src/names.js | 37 +++++++++++ src/nats-billing.js | 36 +++++++++++ src/server.js | 85 ++++++++++++++++++++++++ test/health.test.js | 58 +++++++++++++++++ 9 files changed, 483 insertions(+) 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/iam-gate.js create mode 100644 src/names.js create mode 100644 src/nats-billing.js create mode 100644 src/server.js create mode 100644 test/health.test.js diff --git a/README.md b/README.md new file mode 100644 index 0000000..b3092e8 --- /dev/null +++ b/README.md @@ -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"}' +``` diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..68d2b5f --- /dev/null +++ b/package-lock.json @@ -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" + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..813317e --- /dev/null +++ b/package.json @@ -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" + } +} diff --git a/public/index.html b/public/index.html new file mode 100644 index 0000000..52e2d82 --- /dev/null +++ b/public/index.html @@ -0,0 +1,153 @@ + + + + + + Sales — customer review + + + + + +
+
staff · sales
+

Sales

+

Review a customer’s balance, credits, usage, and payments. Open a quote with names and dollar amounts — not a JSON dump.

+
+
+
+
+
+ + + +
+ + +
+
+
+
+ + + diff --git a/src/iam-gate.js b/src/iam-gate.js new file mode 100644 index 0000000..c5e6144 --- /dev/null +++ b/src/iam-gate.js @@ -0,0 +1,35 @@ +export function iamBase() { + return (process.env.STAFF_IAM_URL || '').replace(/\/$/, ''); +} + +export async function iamCheck(req, permission) { + const base = iamBase(); + if (!base) { + if (process.env.STAFF_AUTH === '1') { + const login = (process.env.STAFF_SESSION_URL || 'http://127.0.0.1:3027').replace(/\/$/, ''); + const r = await fetch(`${login}/check`, { headers: { cookie: req.headers.cookie || '' } }).catch(() => null); + return { ok: Boolean(r && r.ok) }; + } + return { ok: true, skipped: true }; + } + const q = permission ? `?permission=${encodeURIComponent(permission)}` : ''; + const r = await fetch(`${base}/check${q}`, { + headers: { cookie: req.headers.cookie || '', authorization: req.headers.authorization || '' }, + }).catch(() => null); + if (!r) return { ok: false, status: 502 }; + const body = await r.json().catch(() => ({})); + return { ok: r.ok, status: r.status, ...body }; +} + +export async function denyOrRedirect(req, res, json, { permission, html }) { + const out = await iamCheck(req, permission); + if (out.ok) return true; + const login = iamBase() || (process.env.STAFF_SESSION_URL || 'http://127.0.0.1:3028').replace(/\/$/, ''); + if (html) { + res.writeHead(302, { location: `${login}/login?next=${encodeURIComponent('http://' + (req.headers.host || '127.0.0.1') + '/')}` }); + res.end(); + return false; + } + json(out.status === 403 ? 403 : 401, { error: out.reason || 'unauthorized', permission }); + return false; +} 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..17e7a52 --- /dev/null +++ b/src/nats-billing.js @@ -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; + } +} diff --git a/src/server.js b/src/server.js new file mode 100644 index 0000000..ff85574 --- /dev/null +++ b/src/server.js @@ -0,0 +1,85 @@ +#!/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'; +import { listCustomers, withCustomerName } from './names.js'; +import { denyOrRedirect } from './iam-gate.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')) { + if (!(await denyOrRedirect(req, res, json, { permission: 'sales.review', html: true }))) return; + 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' }); + } + 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) { + if (!(await denyOrRedirect(req, res, json, { permission: 'sales.review' }))) return; + const id = decodeURIComponent(review[1]); + const nats = await billingRequest(SUBJECTS.STATEMENT_GET, { customerId: id }); + if (nats) return json(200, await withCustomerName({ ...nats, source: 'nats' }, id, EDGE, KEY)); + const r = await fetch(`${BOOKS}/statement/${encodeURIComponent(id)}`); + if (r.ok) return json(200, await withCustomerName({ ...(await r.json()), source: 'account-balance' }, id, EDGE, KEY)); + const e = await edge(`/admin/api/statement/${encodeURIComponent(id)}`); + return json(e.status, await withCustomerName(e.body, id, EDGE, KEY)); + } + const quote = url.pathname.match(/^\/quotes\/([^/]+)$/); + if (req.method === 'GET' && quote) { + if (!(await denyOrRedirect(req, res, json, { permission: 'sales.quote' }))) return; + 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`); +}); diff --git a/test/health.test.js b/test/health.test.js new file mode 100644 index 0000000..0533933 --- /dev/null +++ b/test/health.test.js @@ -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'); + } +});