moy-buhgalter/chart.js

62 lines
2.9 KiB
JavaScript

const fs = require("fs");
const path = require("path");
// Генерация SVG-графика (встроенная, без sharp/canvas)
function drawBarChart(bars, monthName) {
const W = 600, H = 400;
const pad = { top: 50, right: 20, bottom: 70, left: 70 };
const cw = W - pad.left - pad.right;
const ch = H - pad.top - pad.bottom;
const maxY = Math.max(1, ...bars.map((b) => Math.max(b.income, b.expense)));
const niceMax = Math.ceil(maxY / 10000) * 10000 || 10000;
const n = bars.length;
const groupW = cw / n;
const barW = Math.min(28, groupW * 0.35);
const out = [];
out.push(`<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}">`);
out.push(`<rect width="${W}" height="${H}" fill="#0c0a09"/>`);
out.push(`<text x="${pad.left}" y="30" fill="#faf9f5" font-family="Inter,Arial" font-size="18" font-weight="600">${monthName}</text>`);
for (let i = 0; i <= 4; i++) {
const val = (niceMax / 4) * i;
const y = pad.top + ch - (ch * val) / niceMax;
out.push(`<line x1="${pad.left}" y1="${y}" x2="${W - pad.right}" y2="${y}" stroke="#2a2622" stroke-width="1"/>`);
out.push(`<text x="${pad.left - 8}" y="${y + 4}" fill="#a8a29e" font-size="11" font-family="Inter,Arial" text-anchor="end">${Math.round(val / 1000)}k</text>`);
}
bars.forEach((b, i) => {
const cx = pad.left + groupW * i + groupW / 2;
const hInc = (ch * b.income) / niceMax;
const hExp = (ch * b.expense) / niceMax;
out.push(`<rect x="${cx - barW - 2}" y="${pad.top + ch - hInc}" width="${barW}" height="${hInc}" fill="#3ba6f1" rx="3"/>`);
out.push(`<rect x="${cx + 2}" y="${pad.top + ch - hExp}" width="${barW}" height="${hExp}" fill="#f2695c" rx="3"/>`);
out.push(`<text x="${cx}" y="${pad.top + ch + 18}" fill="#a8a29e" font-size="11" font-family="Inter,Arial" text-anchor="middle">${b.date}</text>`);
});
out.push(`<rect x="${pad.left}" y="${H - 26}" width="12" height="12" fill="#3ba6f1" rx="2"/>`);
out.push(`<text x="${pad.left + 18}" y="${H - 16}" fill="#d9d4cd" font-size="12" font-family="Inter,Arial">Доход</text>`);
out.push(`<rect x="${pad.left + 110}" y="${H - 26}" width="12" height="12" fill="#f2695c" rx="2"/>`);
out.push(`<text x="${pad.left + 128}" y="${H - 16}" fill="#d9d4cd" font-size="12" font-family="Inter,Arial">Расход</text>`);
out.push(`</svg>`);
return out.join("\n");
}
function barsForMonth(userId, getPeriodSummary, now) {
const from = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));
const to = new Date(now.getTime());
const s = getPeriodSummary(userId, from, to);
const days = Object.keys(s.byDay || {}).sort();
return days.map((d) => {
const v = s.byDay[d];
return {
date: new Date(d).toLocaleDateString("ru-RU", { day: "2-digit", month: "2-digit" }),
income: v.income,
expense: v.expense
};
});
}
module.exports = { drawBarChart, barsForMonth };