v2: добавлены /undo /quick /forecast /remind /rate /by /chart /export /backup, дневная сводка в 21:00, мультивалюта (условно)
This commit is contained in:
parent
eb1621d2a3
commit
fbacb77293
2
.gitignore
vendored
2
.gitignore
vendored
@ -1,5 +1,7 @@
|
||||
.env
|
||||
node_modules/
|
||||
data.json
|
||||
rates.json
|
||||
exports/
|
||||
.vibe42-run.log
|
||||
.vibe42-run.pid
|
||||
|
||||
301
bot.js
301
bot.js
@ -1,14 +1,31 @@
|
||||
const { Bot } = require("grammy");
|
||||
const store = require("./storage");
|
||||
const rep = require("./report");
|
||||
const rates = require("./rates");
|
||||
const exp = require("./export");
|
||||
const chartlib = require("./chart");
|
||||
|
||||
const DAILY_TRANSPORT = parseInt(process.env.DAILY_TRANSPORT || "1000", 10);
|
||||
const TZ_OFFSET_MIN = 5 * 60; // Астана UTC+5
|
||||
let dailyDigestScheduled = false;
|
||||
|
||||
const bot = new Bot(process.env.BOT_TOKEN);
|
||||
|
||||
// Парсинг операции: "+50000 зарплата", "-2500 кафе", "50000 зарплата"
|
||||
// Парсинг операции: +50000 зарплата / -2500 кафе / +100 usd перевод
|
||||
function parseEntry(text) {
|
||||
const t = String(text || "").trim();
|
||||
const m = t.match(/^([+-]?)\s*(\d[\d\s\u00a0.,]*)\s*(.*)$/);
|
||||
// Сначала пробуем валюту: +100 usd перевод
|
||||
const cur = t.match(/^([+-]?)(\d[\d\s\u00a0.,]*)\s*(usd|eur)\b\s*(.*)$/i);
|
||||
if (cur) {
|
||||
const [, sign, num, curr, note] = cur;
|
||||
const raw = parseFloat(String(num).replace(/[\s\u00a0]/g, "").replace(",", "."));
|
||||
if (!isFinite(raw) || raw <= 0) return null;
|
||||
const kzt = rates.convert(raw, curr);
|
||||
if (kzt == null) return { error: "currency_unknown", cur: curr };
|
||||
const type = sign === "-" ? "expense" : "income";
|
||||
return { type, amount: kzt, note: (String(note).trim() || curr.toUpperCase()) + " (→₸)" };
|
||||
}
|
||||
const m = t.match(/^([+-]?)(\d[\d\s\u00a0.,]*)\s*(.*)$/);
|
||||
if (!m) return null;
|
||||
const [, sign, num, note] = m;
|
||||
const amount = parseFloat(String(num).replace(/[\s\u00a0]/g, "").replace(",", "."));
|
||||
@ -17,26 +34,17 @@ function parseEntry(text) {
|
||||
return { type, amount, note: String(note).trim() };
|
||||
}
|
||||
|
||||
// Запись ежедневной дороги (только 1 раз на пользователя в день)
|
||||
async function ensureDailyTransport(userId) {
|
||||
const tzOffset = 5 * 60; // Астана UTC+5
|
||||
const localNow = new Date(Date.now() + tzOffset * 60000 + new Date().getTimezoneOffset() * 60000);
|
||||
const year = localNow.getUTCFullYear();
|
||||
const month = localNow.getUTCMonth() + 1;
|
||||
const day = localNow.getUTCDate();
|
||||
const key = year + "-" + month + "-" + day;
|
||||
function todayKey() {
|
||||
const d = new Date(Date.now() + TZ_OFFSET_MIN * 60000 + new Date().getTimezoneOffset() * 60000);
|
||||
return d.getUTCFullYear() + "-" + (d.getUTCMonth() + 1) + "-" + d.getUTCDate();
|
||||
}
|
||||
|
||||
async function ensureDailyTransport(userId) {
|
||||
const data = store.read();
|
||||
const marked = data.lastTransport || {};
|
||||
const key = todayKey();
|
||||
if (marked[userId] === key) return false;
|
||||
|
||||
store.addEntry({
|
||||
userId,
|
||||
type: "expense",
|
||||
amount: DAILY_TRANSPORT,
|
||||
note: "Дорога",
|
||||
auto: true
|
||||
});
|
||||
store.addEntry({ userId, type: "expense", amount: DAILY_TRANSPORT, note: "Дорога", auto: true });
|
||||
data.lastTransport = data.lastTransport || {};
|
||||
data.lastTransport[userId] = key;
|
||||
store.write(data);
|
||||
@ -44,41 +52,38 @@ async function ensureDailyTransport(userId) {
|
||||
}
|
||||
|
||||
function parseReportArg(raw) {
|
||||
return rep.parsePeriodArg(raw);
|
||||
}
|
||||
|
||||
function parseRateArg(raw) {
|
||||
const s = (raw || "").trim();
|
||||
if (!s) return null;
|
||||
const out = {};
|
||||
const mUsd = s.match(/usd\s*=\s*(\d+(?:\.\d+)?)/i);
|
||||
const mEur = s.match(/eur\s*=\s*(\d+(?:\.\d+)?)/i);
|
||||
if (mUsd) out.usd = Math.round(parseFloat(mUsd[1]));
|
||||
if (mEur) out.eur = Math.round(parseFloat(mEur[1]));
|
||||
return out;
|
||||
}
|
||||
|
||||
// YYYY-MM
|
||||
let m = s.match(/^(\d{4})-(\d{1,2})$/);
|
||||
if (m) {
|
||||
const y = +m[1], mo = +m[2];
|
||||
if (mo < 1 || mo > 12) return null;
|
||||
const from = new Date(Date.UTC(y, mo - 1, 1));
|
||||
const to = new Date(Date.UTC(y, mo, 1, 23, 59, 59, 999));
|
||||
return { from, to };
|
||||
}
|
||||
function parseRemindArg(raw) {
|
||||
const s = (raw || "").trim();
|
||||
const m = s.match(/^(\d{1,2})\.(\d{1,2})(?:[./](\d{2,4}))?\s+(.*)$/);
|
||||
if (!m) return null;
|
||||
const [, mm, dd, yy, ...rest] = m;
|
||||
const txt = rest.join(" ");
|
||||
if (!txt) return null;
|
||||
let year = +yy;
|
||||
if (year < 100) year += 2000;
|
||||
if (!year) return null;
|
||||
const month = +mm, day = +dd;
|
||||
if (month < 1 || month > 12 || day < 1 || day > 31) return null;
|
||||
const at = new Date(Date.UTC(year, month - 1, day, 9, 0, 0));
|
||||
return { at: at.toISOString(), text: txt };
|
||||
}
|
||||
|
||||
// YYYY-MM-DD..YYYY-MM-DD
|
||||
m = s.match(/^(\d{4})-(\d{1,2})-(\d{1,2})\s*\.\.\s*(\d{4})-(\d{1,2})-(\d{1,2})$/);
|
||||
if (m) {
|
||||
const [, y1, m1, d1, y2, m2, d2] = m.map(Number);
|
||||
const from = new Date(Date.UTC(y1, m1 - 1, d1));
|
||||
const to = new Date(Date.UTC(y2, m2 - 1, d2, 23, 59, 59, 999));
|
||||
if (from > to) return null;
|
||||
return { from, to };
|
||||
}
|
||||
|
||||
// MM.DD..MM.DD (текущий год)
|
||||
const y = new Date().getFullYear();
|
||||
m = s.match(/^(\d{1,2})\.(\d{1,2})\s*\.\.\s*(\d{1,2})\.(\d{1,2})$/);
|
||||
if (m) {
|
||||
const [, m1, d1, m2, d2] = m.map(Number);
|
||||
const from = new Date(Date.UTC(y, m1 - 1, d1));
|
||||
const to = new Date(Date.UTC(y, m2 - 1, d2, 23, 59, 59, 999));
|
||||
if (from > to) return null;
|
||||
return { from, to };
|
||||
}
|
||||
|
||||
return null;
|
||||
// (График вынесен в chart.js, здесь только хелпер)
|
||||
function drawBarChart(bars) {
|
||||
return chartlib.drawBarChart(bars, "Доходы и расходы — по дням");
|
||||
}
|
||||
|
||||
bot.command("start", (ctx) => ctx.reply(rep.startMessage()));
|
||||
@ -108,6 +113,132 @@ bot.command("report", async (ctx) => {
|
||||
ctx.reply(rep.reportMessage(userId, r.from, r.to));
|
||||
});
|
||||
|
||||
bot.command("by", async (ctx) => {
|
||||
const userId = ctx.from.id;
|
||||
const parts = (ctx.message.text || "").split(/\s+/).slice(1);
|
||||
if (parts.length < 2) {
|
||||
ctx.reply("Формат: /by 2026-06 кафе (или /by 01.06..01.07 кафе)");
|
||||
return;
|
||||
}
|
||||
// Период — пока 2 токена (MM.DD..DD.MM), категория — остальное
|
||||
const period = parts[0];
|
||||
const cat = parts.slice(1).join(" ");
|
||||
ctx.reply(rep.byCategoryMessage(userId, period, cat));
|
||||
});
|
||||
|
||||
bot.command("forecast", async (ctx) => {
|
||||
const userId = ctx.from.id;
|
||||
await ensureDailyTransport(userId);
|
||||
ctx.reply(rep.forecastMessage(userId));
|
||||
});
|
||||
|
||||
bot.command("quick", async (ctx) => {
|
||||
ctx.reply("Выбери, что записать:", {
|
||||
reply_markup: {
|
||||
inline_keyboard: rep.quickButtons().map((b) => [{ text: b.text, callback_data: b.data }])
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
bot.on("callback_query", async (ctx) => {
|
||||
const userId = ctx.from.id;
|
||||
await ensureDailyTransport(userId);
|
||||
const data = ctx.callbackQuery.data;
|
||||
const parsed = parseEntry(data);
|
||||
if (!parsed || parsed.error) {
|
||||
ctx.editMessageText("Не разобрал. Попробуй /help");
|
||||
return;
|
||||
}
|
||||
store.addEntry({ userId, ...parsed, auto: false });
|
||||
const bal = store.getBalance(userId);
|
||||
const sign = bal >= 0 ? "" : "-";
|
||||
ctx.editMessageText(
|
||||
`✅ ${parsed.type === "income" ? "Доход" : "Расход"}: ${parsed.note}\nСумма: ${rep.fmt(parsed.amount)}\nОстаток: ${sign}${rep.fmt(Math.abs(bal))}`
|
||||
);
|
||||
});
|
||||
|
||||
bot.command("undo", async (ctx) => {
|
||||
const userId = ctx.from.id;
|
||||
await ensureDailyTransport(userId);
|
||||
ctx.reply(rep.undoMessage(userId));
|
||||
});
|
||||
|
||||
bot.command("remind", async (ctx) => {
|
||||
const userId = ctx.from.id;
|
||||
const arg = (ctx.message.text || "").split(/\s/).slice(1).join(" ");
|
||||
const r = parseRemindArg(arg);
|
||||
if (!r) {
|
||||
ctx.reply("Формат: /remind 25.12 коммуналка (или /remind 25.12.2026 коммуналка)");
|
||||
return;
|
||||
}
|
||||
store.addReminder(userId, r.at, r.text);
|
||||
const d = new Date(r.at);
|
||||
ctx.reply(`📌 Напоминание: ${d.toLocaleDateString("ru-RU")} ${d.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" })} — ${r.text}`);
|
||||
});
|
||||
|
||||
bot.command("reminders", async (ctx) => {
|
||||
const userId = ctx.from.id;
|
||||
ctx.reply(rep.reminderMessage(userId));
|
||||
});
|
||||
|
||||
bot.command("rate", async (ctx) => {
|
||||
const arg = (ctx.message.text || "").split(/\s/).slice(1).join(" ");
|
||||
const upd = parseRateArg(arg);
|
||||
if (upd.usd && upd.eur) {
|
||||
ctx.reply(rep.rateUpdateMessage(upd.usd, upd.eur));
|
||||
return;
|
||||
}
|
||||
if (upd.usd || upd.eur) {
|
||||
const r = rates.readRates();
|
||||
const nUsd = upd.usd || r.usd;
|
||||
const nEur = upd.eur || r.eur;
|
||||
ctx.reply(rep.rateUpdateMessage(nUsd, nEur));
|
||||
return;
|
||||
}
|
||||
ctx.reply("Текущий курс:\n" + rep.rateInfo() + "\n\nОбновить: /rate usd=530 eur=570");
|
||||
});
|
||||
|
||||
bot.command("chart", async (ctx) => {
|
||||
const userId = ctx.from.id;
|
||||
const info = rep.chartMessage(userId);
|
||||
if (!info.ok) {
|
||||
ctx.reply("Не получилось построить график.");
|
||||
return;
|
||||
}
|
||||
const svg = chartlib.drawBarChart(info.bars, "Доходы и расходы — по дням");
|
||||
ctx.replyWithDocument(
|
||||
{ source: Buffer.from(svg) },
|
||||
{ filename: "chart.svg", caption: `📊 ${info.month} — график доходов и расходов (SVG-график)` }
|
||||
);
|
||||
});
|
||||
|
||||
bot.command("export", async (ctx) => {
|
||||
const userId = ctx.from.id;
|
||||
const arg = (ctx.message.text || "").split(/\s/).slice(1).join(" ");
|
||||
let from = null, to = null;
|
||||
if (arg) {
|
||||
const r = parseReportArg(arg);
|
||||
if (r) { from = r.from; to = r.to; }
|
||||
}
|
||||
const list = rep.exportInfo(userId, from, to);
|
||||
const buf = await exp.exportXlsx(userId, list);
|
||||
const file = await exp.saveTemp(userId, buf, "export");
|
||||
const fname = from && to
|
||||
? `export_${from.toISOString().slice(0, 10)}_${to.toISOString().slice(0, 10)}.xlsx`
|
||||
: `export_${new Date().toISOString().slice(0, 10)}.xlsx`;
|
||||
ctx.replyWithDocument({ source: file }, { filename: fname, caption: `Операций: ${list.length}` });
|
||||
});
|
||||
|
||||
bot.command("backup", async (ctx) => {
|
||||
const data = store.read();
|
||||
const buf = Buffer.from(JSON.stringify(data, null, 2));
|
||||
const file = await exp.saveTemp(ctx.from.id, buf, "backup");
|
||||
ctx.replyWithDocument(
|
||||
{ source: file },
|
||||
{ filename: "backup_" + new Date().toISOString().slice(0, 10) + ".json", caption: "Полный бэкап всех записей." }
|
||||
);
|
||||
});
|
||||
|
||||
bot.command("reset", async (ctx) => {
|
||||
const userId = ctx.from.id;
|
||||
const data = store.read();
|
||||
@ -119,17 +250,18 @@ bot.command("reset", async (ctx) => {
|
||||
bot.on("message:text", async (ctx) => {
|
||||
const userId = ctx.from.id;
|
||||
const text = ctx.message.text;
|
||||
|
||||
// Пропускаем команды (они уже обработаны выше)
|
||||
if (text.startsWith("/")) return;
|
||||
|
||||
// Авто-дорога при любом контакте
|
||||
const transportAdded = await ensureDailyTransport(userId);
|
||||
const note = transportAdded ? "\n(сегодня списано " + rep.fmt(DAILY_TRANSPORT) + " на дорогу)" : "";
|
||||
|
||||
const entry = parseEntry(text);
|
||||
if (!entry) {
|
||||
ctx.reply("Не разобрал. Попробуй так:\n+50000 зарплата\n-2500 кафе или просто /help" + note);
|
||||
ctx.reply("Не разобрал. Попробуй так:\n+50000 зарплата\n-2500 кафе\n+100 usd перевод или /help" + note);
|
||||
return;
|
||||
}
|
||||
if (entry.error === "currency_unknown") {
|
||||
ctx.reply(`Валюта «${entry.cur}» не поддерживается. Пока есть usd и eur. Курсы: /rate`);
|
||||
return;
|
||||
}
|
||||
|
||||
@ -137,9 +269,62 @@ bot.on("message:text", async (ctx) => {
|
||||
const bal = store.getBalance(userId);
|
||||
const sign = bal >= 0 ? "" : "-";
|
||||
const label = entry.type === "income" ? "✅ Доход записан" : "💸 Расход записан";
|
||||
ctx.reply(label + "\n" + entry.note + " — " + rep.fmt(entry.amount) +
|
||||
"\nОстаток: " + sign + rep.fmt(Math.abs(bal)) + note);
|
||||
ctx.reply(
|
||||
label + "\n" + (entry.note || "—") + " — " + rep.fmt(entry.amount) +
|
||||
"\nОстаток: " + sign + rep.fmt(Math.abs(bal)) + note
|
||||
);
|
||||
});
|
||||
|
||||
bot.start();
|
||||
console.log("Бот КЗБухгалтер запущен (long-polling)");
|
||||
// Фоновые задачи: напоминания + дневная сводка (раз в час)
|
||||
async function tick() {
|
||||
try {
|
||||
const now = new Date();
|
||||
|
||||
// Напоминания
|
||||
let due = [];
|
||||
const data = store.read();
|
||||
for (const userId of Object.keys(data.lastTransport || {})) {
|
||||
due = due.concat(store.getDueReminders(userId, now));
|
||||
}
|
||||
for (const r of due) {
|
||||
try {
|
||||
await bot.api.sendMessage(r.userId, "⏰ Напоминание: " + r.text);
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
// Дневная сводка в 21:00 (локальное Астаны, UTC+5)
|
||||
const localH = (now.getUTCHours() + 5) % 24;
|
||||
if (localH === 21) {
|
||||
const key = "digest_" + todayKey();
|
||||
const d2 = store.read();
|
||||
const marked = d2.lastDigest || {};
|
||||
if (!marked[key]) {
|
||||
for (const userId of Object.keys(d2.lastTransport || {})) {
|
||||
const s = store.getPeriodSummary(userId, new Date(Date.now() - 86400000), now);
|
||||
const bal = store.getBalance(userId);
|
||||
const sign = bal >= 0 ? "" : "-";
|
||||
try {
|
||||
await bot.api.sendMessage(userId,
|
||||
`📊 Дневная сводка\nДоход: ${rep.fmt(s.income)}\nРасход: ${rep.fmt(s.expense)}\nОстаток: ${sign}${rep.fmt(Math.abs(bal))}`
|
||||
);
|
||||
} catch (_) {}
|
||||
}
|
||||
d2.lastDigest = d2.lastDigest || {};
|
||||
d2.lastDigest[key] = true;
|
||||
store.write(d2);
|
||||
}
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
function scheduleDigest() {
|
||||
if (dailyDigestScheduled) return;
|
||||
dailyDigestScheduled = true;
|
||||
setInterval(tick, 60 * 60 * 1000);
|
||||
setTimeout(tick, 5 * 60 * 1000);
|
||||
}
|
||||
|
||||
bot.start({ onStart: (me) => {
|
||||
console.log("Бот @" + me.username + " запущен (long-polling)");
|
||||
scheduleDigest();
|
||||
}});
|
||||
|
||||
61
chart.js
Normal file
61
chart.js
Normal file
@ -0,0 +1,61 @@
|
||||
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 };
|
||||
43
export.js
Normal file
43
export.js
Normal file
@ -0,0 +1,43 @@
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const ExcelJS = require("exceljs");
|
||||
|
||||
function exportXlsx(userId, entries) {
|
||||
const wb = new ExcelJS.Workbook();
|
||||
const ws = wb.addWorksheet("Операции");
|
||||
ws.columns = [
|
||||
{ header: "Дата", key: "date", width: 18 },
|
||||
{ header: "Время", key: "time", width: 8 },
|
||||
{ header: "Тип", key: "type", width: 12 },
|
||||
{ header: "Сумма", key: "amount", width: 14 },
|
||||
{ header: "Категория", key: "note", width: 30 },
|
||||
{ header: "Остаток", key: "balance", width: 16 }
|
||||
];
|
||||
let bal = 0;
|
||||
for (const e of entries) {
|
||||
if (e.type === "income") bal += e.amount;
|
||||
else bal -= e.amount;
|
||||
const d = new Date(e.createdAt);
|
||||
ws.addRow({
|
||||
date: d.toLocaleDateString("ru-RU"),
|
||||
time: d.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" }),
|
||||
type: e.type === "income" ? "Доход" : "Расход",
|
||||
amount: e.amount,
|
||||
note: e.note || "",
|
||||
balance: bal
|
||||
});
|
||||
}
|
||||
return wb.xlsx
|
||||
.writeBuffer()
|
||||
.then((buf) => Buffer.from(buf));
|
||||
}
|
||||
|
||||
async function saveTemp(userId, buf, name) {
|
||||
const dir = path.join(__dirname, "exports");
|
||||
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
|
||||
const file = path.join(dir, `export_${userId}_${Date.now()}.xlsx`);
|
||||
await fs.promises.writeFile(file, buf);
|
||||
return file;
|
||||
}
|
||||
|
||||
module.exports = { exportXlsx, saveTemp };
|
||||
2525
package-lock.json
generated
2525
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@ -4,5 +4,8 @@
|
||||
"type": "commonjs",
|
||||
"scripts": {
|
||||
"start": "node --env-file=.env bot.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"exceljs": "^4.4.0"
|
||||
}
|
||||
}
|
||||
|
||||
35
rates.js
Normal file
35
rates.js
Normal file
@ -0,0 +1,35 @@
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
// Курс валют: 1 USD/EUR в KZT (запись вручную, обновляется при /rate)
|
||||
const RATES_FILE = path.join(__dirname, "rates.json");
|
||||
|
||||
function defaultRates() {
|
||||
return { usd: 540, eur: 580, updated: null };
|
||||
}
|
||||
function readRates() {
|
||||
try {
|
||||
return { ...defaultRates(), ...JSON.parse(fs.readFileSync(RATES_FILE, "utf8")) };
|
||||
} catch (_) {
|
||||
return defaultRates();
|
||||
}
|
||||
}
|
||||
function writeRates(r) {
|
||||
fs.writeFileSync(RATES_FILE, JSON.stringify(r, null, 2));
|
||||
}
|
||||
function convert(amount, from) {
|
||||
const r = readRates();
|
||||
if (!from) return Math.round(amount);
|
||||
const f = String(from).toLowerCase();
|
||||
if (f === "kzt") return Math.round(amount);
|
||||
const rate = r[f];
|
||||
if (!rate) return null;
|
||||
return Math.round(amount * rate);
|
||||
}
|
||||
function fmtRate() {
|
||||
const r = readRates();
|
||||
const d = r.updated ? new Date(r.updated).toLocaleDateString("ru-RU") : "не обновлён";
|
||||
return `Курс (от 0${d}): USD=${r.usd} ₸, EUR=${r.eur} ₸`;
|
||||
}
|
||||
|
||||
module.exports = { readRates, writeRates, convert, fmtRate };
|
||||
187
report.js
187
report.js
@ -1,4 +1,5 @@
|
||||
const store = require("./storage");
|
||||
const rates = require("./rates");
|
||||
|
||||
const fmt = (n) => n.toLocaleString("ru-RU") + " ₸";
|
||||
const fmtDate = (d) =>
|
||||
@ -9,8 +10,9 @@ function startMessage() {
|
||||
"Привет! Я — твой личный бухгалтер 👨💼",
|
||||
"",
|
||||
"Как записывать операции:",
|
||||
"• +сумма — доход (например, +50000 зарплата)",
|
||||
"• -сумма или сумма — расход (например, -2500 кафе)",
|
||||
"• +50000 зарплата — доход",
|
||||
"• -2500 кафе — расход",
|
||||
"• +100 usd перевод — доход в валюте (курс по /rate)",
|
||||
"Всё, что после цифры, — категория/комментарий.",
|
||||
"",
|
||||
"Каждый день я автоматически списываю 1 000 ₸ на дорогу.",
|
||||
@ -19,8 +21,17 @@ function startMessage() {
|
||||
"/balance — текущий остаток",
|
||||
"/month — итог за текущий месяц",
|
||||
"/report ГГГГ-Месяц — отчёт за месяц",
|
||||
"/report ПЕРИОД (см. справку) — отчёт за произвольный период",
|
||||
"/help — справка"
|
||||
"/by ГГГГ-Месяц категория — сколько ушло на категорию",
|
||||
"/forecast — прогноз на остаток",
|
||||
"/quick — быстрые кнопки",
|
||||
"/undo — отменить последнюю запись",
|
||||
"/remind ДД.ММ ТЕМА — напоминание",
|
||||
"/reminders — список напоминаний",
|
||||
"/chart — график месяца (PNG)",
|
||||
"/rate — показать/сменить курс валют",
|
||||
"/export — выгрузить всё в Excel",
|
||||
"/backup — выгрузить data.json",
|
||||
"/help — полная справка"
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
@ -31,14 +42,28 @@ function helpMessage() {
|
||||
"Операции:",
|
||||
"• +50000 зарплата — доход",
|
||||
"• -2500 кафе — расход",
|
||||
"• 50000 зарплата — доход (без знака тоже работает)",
|
||||
"• +100 usd перевод — доход в валюте",
|
||||
"• +50 eur перевод — доход в евро",
|
||||
"(валюты: usd, eur — курс задаётся через /rate)",
|
||||
"",
|
||||
"Команды:",
|
||||
"/balance — остаток на сегодня",
|
||||
"/balance — остаток сегодня",
|
||||
"/month — доход/расход за этот месяц",
|
||||
"/report 2026-06 — отчёт за июнь 2026",
|
||||
"/report 2026-01-01..2026-06-30 — за период",
|
||||
"/reset — стереть все записи (осторожно!)",
|
||||
"/report 2026-01-01..2026-06-30 — за произвольный период",
|
||||
"/report 01.06..01.07 — за период в текущем году",
|
||||
"/by 2026-06 кафе — сколько на «кафе» за июнь",
|
||||
"/forecast — прогноз остатка до конца месяца",
|
||||
"/quick — быстрые кнопки (Ящик/Заправка/Кафе)",
|
||||
"/undo — отменить последнюю запись",
|
||||
"/remind 20.12 коммуналка — напоминание",
|
||||
"/reminders — моё напоминание",
|
||||
"/chart — PNG-график за месяц",
|
||||
"/rate usd=530 eur=570 — обновить курсы",
|
||||
"/rate — показать текущий курс и дату",
|
||||
"/export или /export 2026-11 — выгрузка Excel",
|
||||
"/backup — выгрузить data.json (JSON-файл)",
|
||||
"/reset — стереть все записи",
|
||||
"/help — эта справка"
|
||||
].join("\n");
|
||||
}
|
||||
@ -90,11 +115,155 @@ function reportMessage(userId, from, to) {
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
// Локальная функция парсинга периода (используется в /report, /by, /export)
|
||||
function parsePeriodArgLocal(raw) {
|
||||
const s = (raw || "").trim();
|
||||
if (!s) return null;
|
||||
let m = s.match(/^(\d{4})-(\d{1,2})$/);
|
||||
if (m) {
|
||||
const y = +m[1], mo = +m[2];
|
||||
if (mo < 1 || mo > 12) return null;
|
||||
return { from: new Date(Date.UTC(y, mo - 1, 1)), to: new Date(Date.UTC(y, mo, 1, 23, 59, 59, 999)) };
|
||||
}
|
||||
m = s.match(/^(\d{4})-(\d{1,2})-(\d{1,2})\s*\.\.\s*(\d{4})-(\d{1,2})-(\d{1,2})$/);
|
||||
if (m) {
|
||||
const [, y1, m1, d1, y2, m2, d2] = m.map(Number);
|
||||
const from = new Date(Date.UTC(y1, m1 - 1, d1));
|
||||
const to = new Date(Date.UTC(y2, m2 - 1, d2, 23, 59, 59, 999));
|
||||
if (from > to) return null;
|
||||
return { from, to };
|
||||
}
|
||||
const y = new Date().getFullYear();
|
||||
m = s.match(/^(\d{1,2})\.(\d{1,2})\s*\.\.\s*(\d{1,2})\.(\d{1,2})$/);
|
||||
if (m) {
|
||||
const [, m1, d1, m2, d2] = m.map(Number);
|
||||
const from = new Date(Date.UTC(y, m1 - 1, d1));
|
||||
const to = new Date(Date.UTC(y, m2 - 1, d2, 23, 59, 59, 999));
|
||||
if (from > to) return null;
|
||||
return { from, to };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function byCategoryMessage(userId, period, catName) {
|
||||
const r = parsePeriodArgLocal(period);
|
||||
if (!r) return "Не разобрал период. Попробуй: /by 2026-06 кафе или /by 01.01..31.12 кафе";
|
||||
const s = store.getPeriodSummary(userId, r.from, r.to);
|
||||
const c = s.byCat[catName] || { income: 0, expense: 0 };
|
||||
const total = c.income + c.expense;
|
||||
if (!total) return `За период «${fmtDate(r.from)} — ${fmtDate(r.to)}» по категории «${catName}» записей нет.`;
|
||||
return [
|
||||
`По категории «${catName}» за ${fmtDate(r.from)} — ${fmtDate(r.to)}:`,
|
||||
c.income ? "Доход: " + fmt(c.income) : "Доход: —",
|
||||
c.expense ? "Расход: " + fmt(c.expense) : "Расход: —",
|
||||
"Всего: " + fmt(total)
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
function forecastMessage(userId) {
|
||||
const now = new Date();
|
||||
const startOfMonth = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));
|
||||
const endOfMonth = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1, 0, 0, 0, -1));
|
||||
// Последние 14 дней — для среднего расхода
|
||||
const last14 = new Date(Date.now() - 14 * 86400000);
|
||||
const s14 = store.getPeriodSummary(userId, last14, endOfMonth);
|
||||
const perDay = s14.expense / 14;
|
||||
const curMonth = store.getMonthlySummary(userId, now.getUTCFullYear(), now.getUTCMonth() + 1);
|
||||
const bal = store.getBalance(userId);
|
||||
const daysLeft = Math.ceil((endOfMonth - now) / 86400000);
|
||||
const projected = bal - perDay * daysLeft;
|
||||
const sign = projected >= 0 ? "" : "-";
|
||||
return [
|
||||
"🔮 Прогноз",
|
||||
"Средний расход за последние 14 дней: " + fmt(perDay),
|
||||
"Остаток: " + fmt(bal),
|
||||
"До конца месяца: " + daysLeft + " дней",
|
||||
"Прогноз остатка к концу месяца: " + sign + fmt(Math.abs(projected))
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
function reminderMessage(userId) {
|
||||
const list = store.listReminders(userId);
|
||||
if (!list.length) return "Напоминаний нет. Добавь: /remind 25.12 коммуналка";
|
||||
const lines = ["📌 Напоминания:"];
|
||||
for (const r of list) {
|
||||
const d = new Date(r.at);
|
||||
lines.push(`• ${d.toLocaleDateString("ru-RU")} ${d.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" })} — ${r.text}`);
|
||||
}
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
function rateInfo() {
|
||||
return rates.fmtRate();
|
||||
}
|
||||
|
||||
function rateUpdateMessage(usd, eur) {
|
||||
rates.writeRates({ usd, eur, updated: new Date().toISOString() });
|
||||
return `✅ Курсы обновлены:\nUSD = ${usd} ₸\nEUR = ${eur} ₸\n\nЗаписи в валюте будут конвертироваться по новому курсу.`;
|
||||
}
|
||||
|
||||
function chartMessage(userId) {
|
||||
const now = new Date();
|
||||
const s = store.getPeriodSummary(userId, new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)), new Date(Date.now()));
|
||||
const days = Object.keys(s.byDay).sort();
|
||||
const bars = days.map((d) => {
|
||||
const v = s.byDay[d];
|
||||
const inc = v.income;
|
||||
const exp = v.expense;
|
||||
return {
|
||||
date: new Date(d).toLocaleDateString("ru-RU", { day: "2-digit", month: "2-digit" }),
|
||||
income: inc,
|
||||
expense: exp
|
||||
};
|
||||
});
|
||||
return { ok: true, month: now.toLocaleDateString("ru-RU", { month: "long", year: "numeric" }), bars };
|
||||
}
|
||||
|
||||
function undoMessage(userId) {
|
||||
const entries = store.getEntries(userId);
|
||||
if (!entries.length) return "Нечего отменять — записей нет.";
|
||||
const last = entries[entries.length - 1];
|
||||
store.removeById(userId, last.id);
|
||||
const bal = store.getBalance(userId);
|
||||
const sign = bal >= 0 ? "" : "-";
|
||||
return `✅ Отменено: ${last.note || "—"} (${last.type === "income" ? "доход" : "расход"}) ${fmt(last.amount)}\nОстаток: ${sign}${fmt(Math.abs(bal))}`;
|
||||
}
|
||||
|
||||
function exportInfo(userId, from, to) {
|
||||
const list = store.getEntries(userId).filter((e) => {
|
||||
const d = new Date(e.createdAt);
|
||||
return (!from || d >= from) && (!to || d <= to);
|
||||
});
|
||||
return list;
|
||||
}
|
||||
|
||||
function quickButtons() {
|
||||
return [
|
||||
{ text: "Ящик (4 000 ₸)", data: "-4000 ящик" },
|
||||
{ text: "Транспорт (1 000 ₸)", data: "-1000 транспорт" },
|
||||
{ text: "Кафе (5 000 ₸)", data: "-5000 кафе" },
|
||||
{ text: "Заправка (5 000 ₸)", data: "-5000 заправка" },
|
||||
{ text: "Зарплата (250 000 ₸)", data: "+250000 зарплата" },
|
||||
{ text: "Фриланс (100 000 ₸)", data: "+100000 фриланс" }
|
||||
];
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
startMessage,
|
||||
helpMessage,
|
||||
balanceMessage,
|
||||
monthMessage,
|
||||
reportMessage,
|
||||
fmt
|
||||
byCategoryMessage,
|
||||
forecastMessage,
|
||||
reminderMessage,
|
||||
rateInfo,
|
||||
rateUpdateMessage,
|
||||
chartMessage,
|
||||
undoMessage,
|
||||
exportInfo,
|
||||
quickButtons,
|
||||
fmt,
|
||||
fmtDate,
|
||||
parsePeriodArg: parsePeriodArgLocal
|
||||
};
|
||||
|
||||
92
storage.js
92
storage.js
@ -7,7 +7,7 @@ function read() {
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(FILE, "utf8"));
|
||||
} catch (_) {
|
||||
return { entries: [] };
|
||||
return { entries: [], lastTransport: {}, reminders: [] };
|
||||
}
|
||||
}
|
||||
|
||||
@ -21,10 +21,10 @@ function addEntry({ userId, type, amount, note, auto }) {
|
||||
const entry = {
|
||||
id: Date.now() + "_" + Math.random().toString(36).slice(2, 7),
|
||||
userId,
|
||||
type, // "income" | "expense"
|
||||
type,
|
||||
amount: Math.round(amount),
|
||||
note: String(note || "").trim(),
|
||||
isAuto: !!auto,
|
||||
auto: !!auto,
|
||||
createdAt: new Date().toISOString()
|
||||
};
|
||||
data.entries.push(entry);
|
||||
@ -33,12 +33,35 @@ function addEntry({ userId, type, amount, note, auto }) {
|
||||
}
|
||||
|
||||
function getEntries(userId) {
|
||||
return read().entries.filter((e) => e.userId === userId);
|
||||
return read()
|
||||
.entries.filter((e) => e.userId === userId)
|
||||
.sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt));
|
||||
}
|
||||
|
||||
function removeById(userId, id) {
|
||||
const data = read();
|
||||
const before = data.entries.length;
|
||||
data.entries = data.entries.filter((e) => !(e.userId === userId && e.id === id));
|
||||
write(data);
|
||||
return data.entries.length < before;
|
||||
}
|
||||
|
||||
function updateById(userId, id, patch) {
|
||||
const data = read();
|
||||
const e = data.entries.find((x) => x.userId === userId && x.id === id);
|
||||
if (!e) return false;
|
||||
if (typeof patch.amount === "number") e.amount = Math.round(patch.amount);
|
||||
if (typeof patch.note === "string") e.note = patch.note.trim();
|
||||
if (typeof patch.type === "string" && (patch.type === "income" || patch.type === "expense")) {
|
||||
e.type = patch.type;
|
||||
}
|
||||
write(data);
|
||||
return true;
|
||||
}
|
||||
|
||||
function getBalance(userId) {
|
||||
const list = getEntries(userId);
|
||||
return list.reduce((bal, e) => (e.type === "income" ? bal + e.amount : bal - e.amount), 0);
|
||||
return getEntries(userId).reduce((bal, e) =>
|
||||
e.type === "income" ? bal + e.amount : bal - e.amount, 0);
|
||||
}
|
||||
|
||||
function getMonthlySummary(userId, year, month) {
|
||||
@ -52,7 +75,6 @@ function getMonthlySummary(userId, year, month) {
|
||||
}
|
||||
|
||||
function getPeriodSummary(userId, from, to) {
|
||||
// from/to — Date
|
||||
const list = getEntries(userId).filter((e) => {
|
||||
const d = new Date(e.createdAt);
|
||||
return d >= from && d <= to;
|
||||
@ -67,7 +89,59 @@ function getPeriodSummary(userId, from, to) {
|
||||
if (e.type === "income") byCat[cat].income += e.amount;
|
||||
else byCat[cat].expense += e.amount;
|
||||
}
|
||||
return { income, expense, net: income - expense, byCat, count: list.length };
|
||||
|
||||
// Динамика по дням внутри периода
|
||||
const byDay = {};
|
||||
for (const e of list) {
|
||||
const d = new Date(e.createdAt);
|
||||
const key = d.toISOString().slice(0, 10);
|
||||
byDay[key] = byDay[key] || { income: 0, expense: 0 };
|
||||
if (e.type === "income") byDay[key].income += e.amount;
|
||||
else byDay[key].expense += e.amount;
|
||||
}
|
||||
|
||||
return { income, expense, net: income - expense, byCat, byDay, count: list.length };
|
||||
}
|
||||
|
||||
module.exports = { addEntry, getEntries, getBalance, getMonthlySummary, getPeriodSummary, read, write };
|
||||
function addReminder(userId, dateISO, text) {
|
||||
const data = read();
|
||||
data.reminders.push({
|
||||
id: Date.now() + "_" + Math.random().toString(36).slice(2, 7),
|
||||
userId,
|
||||
at: dateISO,
|
||||
text: String(text || "").trim(),
|
||||
done: false
|
||||
});
|
||||
write(data);
|
||||
}
|
||||
|
||||
function getDueReminders(userId, now) {
|
||||
const data = read();
|
||||
const due = data.reminders.filter(
|
||||
(r) => r.userId === userId && !r.done && new Date(r.at) <= now
|
||||
);
|
||||
for (const r of due) r.done = true;
|
||||
if (due.length) write(data);
|
||||
return due;
|
||||
}
|
||||
|
||||
function listReminders(userId) {
|
||||
return read()
|
||||
.reminders.filter((r) => r.userId === userId && !r.done)
|
||||
.sort((a, b) => new Date(a.at) - new Date(b.at));
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
read,
|
||||
write,
|
||||
addEntry,
|
||||
getEntries,
|
||||
removeById,
|
||||
updateById,
|
||||
getBalance,
|
||||
getMonthlySummary,
|
||||
getPeriodSummary,
|
||||
addReminder,
|
||||
getDueReminders,
|
||||
listReminders
|
||||
};
|
||||
|
||||
99
tests/smoke.js
Normal file
99
tests/smoke.js
Normal file
@ -0,0 +1,99 @@
|
||||
const assert = require("assert");
|
||||
const path = require("path");
|
||||
const fs = require("fs");
|
||||
|
||||
const ROOT = path.join(__dirname, "..");
|
||||
const testFile = path.join(ROOT, "test_data.json");
|
||||
if (fs.existsSync(testFile)) fs.unlinkSync(testFile);
|
||||
|
||||
// Хак: patch storage.js на время теста через Module._load
|
||||
const origLoad = require("module")._load;
|
||||
require("module")._load = function (request, parent, isMain) {
|
||||
if (request === "./storage" && parent && parent.filename === require.resolve(path.join(ROOT, "report.js"))) {
|
||||
return require(path.join(ROOT, "storage_test.js"));
|
||||
}
|
||||
return origLoad.apply(this, arguments);
|
||||
};
|
||||
|
||||
const storageSrc = fs.readFileSync(path.join(ROOT, "storage.js"), "utf8");
|
||||
const patched = storageSrc.replace(
|
||||
'path.join(__dirname, "data.json")',
|
||||
'path.join(__dirname, "test_data.json")'
|
||||
);
|
||||
fs.writeFileSync(path.join(ROOT, "storage_test.js"), patched);
|
||||
|
||||
const origLoadRef = require(path.join(ROOT, "storage_test.js"));
|
||||
const store = origLoadRef;
|
||||
const rep = require(path.join(ROOT, "report.js"));
|
||||
const rates = require(path.join(ROOT, "rates.js"));
|
||||
|
||||
// 1. addEntry + getBalance
|
||||
store.addEntry({ userId: "u1", type: "income", amount: 50000, note: "зарплата" });
|
||||
let e2 = store.addEntry({ userId: "u1", type: "expense", amount: 1000, note: "Дорога", auto: true });
|
||||
store.addEntry({ userId: "u1", type: "expense", amount: 4000, note: "ящик" });
|
||||
store.addEntry({ userId: "u2", type: "income", amount: 999, note: "чужой" });
|
||||
assert.equal(store.getBalance("u1"), 45000, "balance u1 = 45000");
|
||||
assert.equal(store.getBalance("u2"), 999, "balance u2");
|
||||
assert.equal(store.getEntries("u1").length, 3, "entries u1 = 3");
|
||||
|
||||
// 2. removeById
|
||||
const entries = store.getEntries("u1");
|
||||
const e3 = entries.find((e) => e.note === "ящик");
|
||||
assert(store.removeById("u1", e3.id), "removeById works");
|
||||
assert.equal(store.getBalance("u1"), 49000, "balance after remove = 49000");
|
||||
|
||||
// 3. updateById
|
||||
assert(store.updateById("u1", e2.id, { amount: 2000, note: "Дорога×2" }), "updateById works");
|
||||
assert.equal(store.getBalance("u1"), 48000, "balance after update = 48000");
|
||||
|
||||
// 4. Monthly summary
|
||||
const now = new Date();
|
||||
const m = store.getMonthlySummary("u1", now.getFullYear(), now.getMonth() + 1);
|
||||
assert.equal(m.income, 50000, "month income = 50000");
|
||||
assert.equal(m.expense, 2000, "month expense = 2000");
|
||||
assert.equal(m.net, 48000, "month net = 48000");
|
||||
|
||||
// 5. Period summary
|
||||
const p = store.getPeriodSummary("u1", new Date(Date.now() - 86400000), new Date());
|
||||
assert.equal(p.income, 50000, "period income = 50000");
|
||||
assert.equal(p.expense, 2000, "period expense = 2000");
|
||||
assert(p.byCat["Дорога×2"], "byCat has Дорога×2");
|
||||
assert(p.byDay && Object.keys(p.byDay).length >= 1, "byDay filled");
|
||||
|
||||
// 6. Reminders
|
||||
store.addReminder("u1", new Date(Date.now() - 60000).toISOString(), "communal");
|
||||
const due = store.getDueReminders("u1", new Date());
|
||||
assert.equal(due.length, 1, "reminder due");
|
||||
assert.equal(due[0].text, "communal");
|
||||
|
||||
// 7. Rates
|
||||
assert.equal(rates.convert(10, "usd"), 10 * rates.readRates().usd, "convert usd");
|
||||
assert.equal(rates.convert(10, "eur"), 10 * rates.readRates().eur, "convert eur");
|
||||
assert.equal(rates.convert(10, "kzt"), 10, "convert kzt");
|
||||
|
||||
// 8. Report messages
|
||||
const balMsg = rep.balanceMessage("u1");
|
||||
assert(balMsg.includes("₸"), "balance has ₸: " + balMsg);
|
||||
assert(balMsg.replace(/\s/g, "").includes("48000"), "balance = 48000: " + balMsg);
|
||||
|
||||
const byMsg = rep.byCategoryMessage("u1", now.getFullYear() + "-" + (now.getMonth() + 1), "Дорога×2");
|
||||
assert(byMsg.includes("Дорога×2"), "by-category finds Дорога×2: " + byMsg);
|
||||
|
||||
// 9. Quick buttons
|
||||
const q = rep.quickButtons();
|
||||
assert.equal(q.length, 6, "6 quick buttons");
|
||||
assert(q[0].data === "-4000 ящик", "quick 0 = ящик");
|
||||
|
||||
// 10. Undo
|
||||
const before = store.getBalance("u1");
|
||||
store.addEntry({ userId: "u1", type: "expense", amount: 500, note: "тест" });
|
||||
assert.equal(store.getBalance("u1"), before - 500, "balance after add for undo");
|
||||
const undoMsg = rep.undoMessage("u1");
|
||||
assert(undoMsg.includes("Отменено"), "undo message: " + undoMsg);
|
||||
assert.equal(store.getBalance("u1"), before, "balance restored after undo");
|
||||
|
||||
console.log("✅ Все 10 групп тестов прошли");
|
||||
|
||||
// Очистка
|
||||
fs.unlinkSync(testFile);
|
||||
fs.unlinkSync(path.join(ROOT, "storage_test.js"));
|
||||
Loading…
Reference in New Issue
Block a user