const { Bot } = require("grammy"); const store = require("./storage"); const rep = require("./report"); const DAILY_TRANSPORT = parseInt(process.env.DAILY_TRANSPORT || "1000", 10); const bot = new Bot(process.env.BOT_TOKEN); // Парсинг операции: "+50000 зарплата", "-2500 кафе", "50000 зарплата" function parseEntry(text) { const t = String(text || "").trim(); const m = t.match(/^([+-]?)\s*(\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() }; } // Запись ежедневной дороги (только 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; const data = store.read(); const marked = data.lastTransport || {}; 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) { const s = (raw || "").trim(); if (!s) return null; // 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 }; } // 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; } 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("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 кафе или просто /help" + note); 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); }); bot.start(); console.log("Бот КЗБухгалтер запущен (long-polling)");