61 lines
2.7 KiB
JavaScript
61 lines
2.7 KiB
JavaScript
#!/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';
|
|
|
|
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')) {
|
|
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' });
|
|
}
|
|
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 send(e.status, 'application/json', await e.text());
|
|
}
|
|
const period = url.searchParams.get('period');
|
|
const q = period ? `?period=${encodeURIComponent(period)}` : '';
|
|
if (req.method === 'GET' && url.pathname === '/export/quickbooks.iif') {
|
|
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') {
|
|
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`);
|
|
});
|