Initial import of zappier-accounting-export from zapier monorepo
This commit is contained in:
commit
184d72ef96
9 changed files with 383 additions and 0 deletions
35
src/iam-gate.js
Normal file
35
src/iam-gate.js
Normal file
|
|
@ -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;
|
||||
}
|
||||
37
src/names.js
Normal file
37
src/names.js
Normal file
|
|
@ -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;
|
||||
}
|
||||
17
src/nats-billing.js
Normal file
17
src/nats-billing.js
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
export const SUBJECTS = { STATEMENT_GET: 'verae.billing.statement.get' };
|
||||
|
||||
export async function billingRequest(subject, payload) {
|
||||
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-accounting-export' });
|
||||
const sc = StringCodec();
|
||||
const m = await nc.request(subject, sc.encode(JSON.stringify(payload)), { timeout: 2000 });
|
||||
const out = JSON.parse(sc.decode(m.data) || '{}');
|
||||
await nc.close();
|
||||
return out;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
72
src/server.js
Normal file
72
src/server.js
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
#!/usr/bin/env node
|
||||
/** Accounting department: QuickBooks IIF + CSV from zappier-edge invoices. */
|
||||
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 PORT = Number(process.env.PORT || 3013);
|
||||
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(/\/$/, '');
|
||||
const PUBLIC = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'public');
|
||||
|
||||
async function edge(pathname) {
|
||||
const r = await fetch(`${EDGE}${pathname}`, { headers: { 'x-admin-key': KEY } });
|
||||
return r;
|
||||
}
|
||||
|
||||
const server = http.createServer(async (req, res) => {
|
||||
const url = new URL(req.url || '/', `http://127.0.0.1:${PORT}`);
|
||||
const send = (code, type, body) => {
|
||||
res.writeHead(code, { 'content-type': type });
|
||||
res.end(body);
|
||||
};
|
||||
const json = (code, obj) => send(code, 'application/json', JSON.stringify(obj));
|
||||
try {
|
||||
if (req.method === 'GET' && (url.pathname === '/' || url.pathname === '/index.html')) {
|
||||
if (!(await denyOrRedirect(req, res, json, { permission: 'accounting.review', html: true }))) return;
|
||||
return send(200, 'text/html; charset=utf-8', fs.readFileSync(path.join(PUBLIC, 'index.html')));
|
||||
}
|
||||
if (req.method === 'GET' && url.pathname === '/health') {
|
||||
return json(200, { ok: true, role: 'zappier-accounting-export' });
|
||||
}
|
||||
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: 'accounting.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)}`);
|
||||
const body = await e.json().catch(() => ({}));
|
||||
return json(e.status, await withCustomerName(body, id, EDGE, KEY));
|
||||
}
|
||||
const period = url.searchParams.get('period');
|
||||
const q = period ? `?period=${encodeURIComponent(period)}` : '';
|
||||
if (req.method === 'GET' && url.pathname === '/export/quickbooks.iif') {
|
||||
if (!(await denyOrRedirect(req, res, json, { permission: 'accounting.export' }))) return;
|
||||
const r = await edge(`/admin/api/exports/quickbooks.iif${q}`);
|
||||
return send(r.status, 'text/plain', await r.text());
|
||||
}
|
||||
if (req.method === 'GET' && url.pathname === '/export/accounting.csv') {
|
||||
if (!(await denyOrRedirect(req, res, json, { permission: 'accounting.export' }))) return;
|
||||
const r = await edge(`/admin/api/exports/accounting.csv${q}`);
|
||||
return send(r.status, 'text/csv', await r.text());
|
||||
}
|
||||
json(404, { error: 'not found' });
|
||||
} catch (err) {
|
||||
json(502, { error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
server.listen(PORT, '0.0.0.0', () => {
|
||||
process.stdout.write(`zappier-accounting-export http://127.0.0.1:${PORT}/\n`);
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue