331 lines
12 KiB
JavaScript
331 lines
12 KiB
JavaScript
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 кафе / +100 usd перевод
|
||
function parseEntry(text) {
|
||
const t = String(text || "").trim();
|
||
// Сначала пробуем валюту: +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(",", "."));
|
||
if (!isFinite(amount) || amount <= 0) return null;
|
||
const type = sign === "-" ? "expense" : "income";
|
||
return { type, amount, note: String(note).trim() };
|
||
}
|
||
|
||
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 });
|
||
data.lastTransport = data.lastTransport || {};
|
||
data.lastTransport[userId] = key;
|
||
store.write(data);
|
||
return true;
|
||
}
|
||
|
||
function parseReportArg(raw) {
|
||
return rep.parsePeriodArg(raw);
|
||
}
|
||
|
||
function parseRateArg(raw) {
|
||
const s = (raw || "").trim();
|
||
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;
|
||
}
|
||
|
||
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 };
|
||
}
|
||
|
||
// (График вынесен в chart.js, здесь только хелпер)
|
||
function drawBarChart(bars) {
|
||
return chartlib.drawBarChart(bars, "Доходы и расходы — по дням");
|
||
}
|
||
|
||
bot.command("start", (ctx) => ctx.reply(rep.startMessage()));
|
||
bot.command("help", (ctx) => ctx.reply(rep.helpMessage()));
|
||
|
||
bot.command("balance", async (ctx) => {
|
||
const userId = ctx.from.id;
|
||
await ensureDailyTransport(userId);
|
||
ctx.reply(rep.balanceMessage(userId));
|
||
});
|
||
|
||
bot.command("month", async (ctx) => {
|
||
const userId = ctx.from.id;
|
||
await ensureDailyTransport(userId);
|
||
ctx.reply(rep.monthMessage(userId));
|
||
});
|
||
|
||
bot.command("report", async (ctx) => {
|
||
const userId = ctx.from.id;
|
||
await ensureDailyTransport(userId);
|
||
const arg = (ctx.message.text || "").split(/\s/).slice(1).join(" ");
|
||
const r = parseReportArg(arg);
|
||
if (!r) {
|
||
ctx.reply("Укажи период, например:\n/report 2026-06\n/report 2026-01-01..2026-06-30\n/report 01.06..01.07");
|
||
return;
|
||
}
|
||
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();
|
||
data.entries = data.entries.filter((e) => e.userId !== userId);
|
||
store.write(data);
|
||
ctx.reply("✅ Все ваши записи удалены.");
|
||
});
|
||
|
||
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 кафе\n+100 usd перевод или /help" + note);
|
||
return;
|
||
}
|
||
if (entry.error === "currency_unknown") {
|
||
ctx.reply(`Валюта «${entry.cur}» не поддерживается. Пока есть usd и eur. Курсы: /rate`);
|
||
return;
|
||
}
|
||
|
||
store.addEntry({ userId, ...entry, auto: false });
|
||
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
|
||
);
|
||
});
|
||
|
||
// Фоновые задачи: напоминания + дневная сводка (раз в час)
|
||
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();
|
||
}});
|