250 lines
8.2 KiB
JavaScript
250 lines
8.2 KiB
JavaScript
import express from 'express';
|
|
import Database from 'better-sqlite3';
|
|
import { v4 as uuidv4 } from 'uuid';
|
|
import puppeteer from 'puppeteer';
|
|
import fs from 'fs';
|
|
import path from 'path';
|
|
import { fileURLToPath } from 'url';
|
|
|
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
const app = express();
|
|
const PORT = process.env.PORT || 3000;
|
|
const API_KEY = process.env.API_KEY || 'crystal-secret-key';
|
|
|
|
// Initialize database
|
|
const dbPath = process.env.DB_PATH || '/data/crystal.db';
|
|
const db = new Database(dbPath);
|
|
|
|
// Create tables
|
|
db.exec(`
|
|
CREATE TABLE IF NOT EXISTS reports (
|
|
id TEXT PRIMARY KEY,
|
|
title TEXT NOT NULL,
|
|
report_type TEXT NOT NULL,
|
|
html_content TEXT NOT NULL,
|
|
summary TEXT,
|
|
created_at TEXT DEFAULT (datetime('now')),
|
|
period_start TEXT,
|
|
period_end TEXT
|
|
)
|
|
`);
|
|
|
|
app.use(express.json({ limit: '10mb' }));
|
|
app.use(express.static(path.join(__dirname, '../public')));
|
|
|
|
// Helper: Wrap content in layout
|
|
function renderPage(title, content, extra = '') {
|
|
return `<!DOCTYPE html>
|
|
<html lang="en">
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
<title>${title} - Phil Dashboard</title>
|
|
<link rel="stylesheet" href="/styles.css">
|
|
${extra}
|
|
</head>
|
|
<body>
|
|
<header>
|
|
<div class="container">
|
|
<h1>📋 Phil Dashboard</h1>
|
|
<nav>
|
|
<a href="/">Reports</a>
|
|
</nav>
|
|
</div>
|
|
</header>
|
|
<main class="container">
|
|
${content}
|
|
</main>
|
|
<footer>
|
|
<div class="container">
|
|
<p>Phil Bookkeeper • Regulatory Affairs Integration</p>
|
|
</div>
|
|
</footer>
|
|
</body>
|
|
</html>`;
|
|
}
|
|
|
|
// Dashboard - List all reports
|
|
app.get('/', (req, res) => {
|
|
const reports = db.prepare(`
|
|
SELECT id, title, report_type, summary, created_at, period_start, period_end
|
|
FROM reports ORDER BY created_at DESC
|
|
`).all();
|
|
|
|
const reportsList = reports.length === 0
|
|
? '<p class="empty">No reports yet. Ask Phil to generate one!</p>'
|
|
: reports.map(r => `
|
|
<div class="report-card">
|
|
<div class="report-header">
|
|
<span class="report-type">${r.report_type}</span>
|
|
<span class="report-date">${new Date(r.created_at).toLocaleDateString()}</span>
|
|
</div>
|
|
<h3><a href="/reports/${r.id}">${r.title}</a></h3>
|
|
${r.summary ? `<p class="summary">${r.summary}</p>` : ''}
|
|
${r.period_start ? `<p class="period">${r.period_start} to ${r.period_end || 'Present'}</p>` : ''}
|
|
<div class="report-actions">
|
|
<a href="/reports/${r.id}" class="btn">View</a>
|
|
<a href="/reports/${r.id}/pdf" class="btn btn-secondary">PDF</a>
|
|
<button onclick="deleteReport('${r.id}')" class="btn btn-danger">Delete</button>
|
|
</div>
|
|
</div>
|
|
`).join('');
|
|
|
|
const content = `
|
|
<h2>Regulatory Reports</h2>
|
|
<div class="reports-grid">
|
|
${reportsList}
|
|
</div>
|
|
<script>
|
|
async function deleteReport(id) {
|
|
if (!confirm('Delete this report?')) return;
|
|
const res = await fetch('/reports/' + id, { method: 'DELETE' });
|
|
if (res.ok) location.reload();
|
|
else alert('Failed to delete');
|
|
}
|
|
</script>
|
|
`;
|
|
|
|
res.send(renderPage('Dashboard', content));
|
|
});
|
|
|
|
// View single report
|
|
app.get('/reports/:id', (req, res) => {
|
|
const report = db.prepare('SELECT * FROM reports WHERE id = ?').get(req.params.id);
|
|
if (!report) return res.status(404).send(renderPage('Not Found', '<p>Report not found</p>'));
|
|
|
|
const content = `
|
|
<div class="report-view">
|
|
<div class="report-meta">
|
|
<span class="report-type">${report.report_type}</span>
|
|
<span class="report-date">Generated: ${new Date(report.created_at).toLocaleString()}</span>
|
|
${report.period_start ? `<span class="period">Period: ${report.period_start} to ${report.period_end || 'Present'}</span>` : ''}
|
|
</div>
|
|
<div class="report-toolbar">
|
|
<a href="/" class="btn btn-secondary">← Back</a>
|
|
<a href="/reports/${report.id}/pdf" class="btn">Download PDF</a>
|
|
<button onclick="deleteReport('${report.id}')" class="btn btn-danger">Delete</button>
|
|
</div>
|
|
<div class="report-content">
|
|
${report.html_content}
|
|
</div>
|
|
</div>
|
|
<script>
|
|
async function deleteReport(id) {
|
|
if (!confirm('Delete this report?')) return;
|
|
const res = await fetch('/reports/' + id, { method: 'DELETE' });
|
|
if (res.ok) location.href = '/';
|
|
else alert('Failed to delete');
|
|
}
|
|
</script>
|
|
`;
|
|
|
|
res.send(renderPage(report.title, content));
|
|
});
|
|
|
|
// Generate PDF
|
|
app.get('/reports/:id/pdf', async (req, res) => {
|
|
const report = db.prepare('SELECT * FROM reports WHERE id = ?').get(req.params.id);
|
|
if (!report) return res.status(404).send('Report not found');
|
|
|
|
try {
|
|
const browser = await puppeteer.launch({
|
|
headless: true,
|
|
args: ['--no-sandbox', '--disable-setuid-sandbox']
|
|
});
|
|
const page = await browser.newPage();
|
|
|
|
const html = `<!DOCTYPE html>
|
|
<html>
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<title>${report.title}</title>
|
|
<style>
|
|
body { font-family: 'Helvetica Neue', Arial, sans-serif; padding: 40px; color: #333; }
|
|
h1 { color: #2563eb; border-bottom: 2px solid #2563eb; padding-bottom: 10px; }
|
|
table { width: 100%; border-collapse: collapse; margin: 20px 0; }
|
|
th, td { padding: 12px; text-align: left; border-bottom: 1px solid #e5e7eb; }
|
|
th { background: #f9fafb; font-weight: 600; }
|
|
.amount { text-align: right; font-family: 'Courier New', monospace; }
|
|
.total { font-weight: bold; background: #f0f9ff; }
|
|
.negative { color: #dc2626; }
|
|
.positive { color: #16a34a; }
|
|
.meta { color: #6b7280; font-size: 14px; margin-bottom: 20px; }
|
|
.footer { margin-top: 40px; padding-top: 20px; border-top: 1px solid #e5e7eb; color: #9ca3af; font-size: 12px; }
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<h1>${report.title}</h1>
|
|
<div class="meta">
|
|
Generated: ${new Date(report.created_at).toLocaleString()}
|
|
${report.period_start ? ` • Period: ${report.period_start} to ${report.period_end || 'Present'}` : ''}
|
|
</div>
|
|
${report.html_content}
|
|
<div class="footer">
|
|
Generated by Phil Bookkeeper • Regulatory Affairs
|
|
</div>
|
|
</body>
|
|
</html>`;
|
|
|
|
await page.setContent(html, { waitUntil: 'networkidle0' });
|
|
const pdf = await page.pdf({
|
|
format: 'A4',
|
|
printBackground: true,
|
|
margin: { top: '20mm', bottom: '20mm', left: '15mm', right: '15mm' }
|
|
});
|
|
|
|
await browser.close();
|
|
|
|
const filename = `${report.title.replace(/[^a-z0-9]/gi, '-').toLowerCase()}.pdf`;
|
|
res.setHeader('Content-Type', 'application/pdf');
|
|
res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
|
|
res.send(pdf);
|
|
} catch (err) {
|
|
console.error('PDF generation error:', err);
|
|
res.status(500).send('Failed to generate PDF');
|
|
}
|
|
});
|
|
|
|
// Delete report
|
|
app.delete('/reports/:id', (req, res) => {
|
|
const result = db.prepare('DELETE FROM reports WHERE id = ?').run(req.params.id);
|
|
if (result.changes === 0) return res.status(404).json({ error: 'Not found' });
|
|
res.json({ success: true });
|
|
});
|
|
|
|
// API: Create report (for Phil)
|
|
app.post('/api/reports', (req, res) => {
|
|
const authHeader = req.headers.authorization;
|
|
if (authHeader !== `Bearer ${API_KEY}`) {
|
|
return res.status(401).json({ error: 'Unauthorized' });
|
|
}
|
|
|
|
const { title, report_type, html_content, summary, period_start, period_end } = req.body;
|
|
|
|
if (!title || !report_type || !html_content) {
|
|
return res.status(400).json({ error: 'Missing required fields: title, report_type, html_content' });
|
|
}
|
|
|
|
const id = uuidv4();
|
|
db.prepare(`
|
|
INSERT INTO reports (id, title, report_type, html_content, summary, period_start, period_end)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
`).run(id, title, report_type, html_content, summary || null, period_start || null, period_end || null);
|
|
|
|
const url = `${req.protocol}://${req.get('host')}/reports/${id}`;
|
|
res.json({ success: true, id, url });
|
|
});
|
|
|
|
// API: List reports (for Phil)
|
|
app.get('/api/reports', (req, res) => {
|
|
const reports = db.prepare(`
|
|
SELECT id, title, report_type, summary, created_at, period_start, period_end
|
|
FROM reports ORDER BY created_at DESC LIMIT 50
|
|
`).all();
|
|
res.json(reports);
|
|
});
|
|
|
|
app.listen(PORT, () => {
|
|
console.log(`Phil Dashboard running on port ${PORT}`);
|
|
});
|