v1: Telegram-бот КЗБухгалтер — учёт доходов/расходов, авто-дорога 1000 ₸, отчёты за период

This commit is contained in:
Galym 2026-11-20 07:00:21 +00:00
parent b3534432fd
commit eb1621d2a3
6 changed files with 341 additions and 0 deletions

5
.gitignore vendored Normal file
View File

@ -0,0 +1,5 @@
.env
node_modules/
data.json
.vibe42-run.log
.vibe42-run.pid

145
bot.js Normal file
View File

@ -0,0 +1,145 @@
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)");

10
package-lock.json generated Normal file
View File

@ -0,0 +1,10 @@
{
"name": "moy-buhgalter",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "moy-buhgalter"
}
}
}

8
package.json Normal file
View File

@ -0,0 +1,8 @@
{
"name": "moy-buhgalter",
"private": true,
"type": "commonjs",
"scripts": {
"start": "node --env-file=.env bot.js"
}
}

100
report.js Normal file
View File

@ -0,0 +1,100 @@
const store = require("./storage");
const fmt = (n) => n.toLocaleString("ru-RU") + " ₸";
const fmtDate = (d) =>
d.toLocaleDateString("ru-RU", { day: "2-digit", month: "2-digit", year: "numeric" });
function startMessage() {
return [
"Привет! Я — твой личный бухгалтер 👨‍💼",
"",
"Как записывать операции:",
"• +сумма — доход (например, +50000 зарплата)",
"• -сумма или сумма — расход (например, -2500 кафе)",
"Всё, что после цифры, — категория/комментарий.",
"",
"Каждый день я автоматически списываю 1 000 ₸ на дорогу.",
"",
"Команды:",
"/balance — текущий остаток",
"/month — итог за текущий месяц",
"/report ГГГГ-Месяц — отчёт за месяц",
"/report ПЕРИОД (см. справку) — отчёт за произвольный период",
"/help — справка"
].join("\n");
}
function helpMessage() {
return [
"Справка",
"",
"Операции:",
"• +50000 зарплата — доход",
"• -2500 кафе — расход",
"• 50000 зарплата — доход (без знака тоже работает)",
"",
"Команды:",
"/balance — остаток на сегодня",
"/month — доход/расход за этот месяц",
"/report 2026-06 — отчёт за июнь 2026",
"/report 2026-01-01..2026-06-30 — за период",
"/reset — стереть все записи (осторожно!)",
"/help — эта справка"
].join("\n");
}
function balanceMessage(userId) {
const bal = store.getBalance(userId);
const sign = bal >= 0 ? "" : "-";
return `💰 Остаток: ${sign}${fmt(Math.abs(bal))}`;
}
function monthMessage(userId) {
const now = new Date();
const s = store.getMonthlySummary(userId, now.getFullYear(), now.getMonth() + 1);
const monthName = now.toLocaleDateString("ru-RU", { month: "long", year: "numeric" });
return [
"📊 Итог за " + monthName,
"Доход: " + fmt(s.income),
"Расход: " + fmt(s.expense),
"Итого: " + fmt(s.net)
].join("\n");
}
function reportMessage(userId, from, to) {
const s = store.getPeriodSummary(userId, from, to);
const lines = [
"📈 Отчёт: " + fmtDate(from) + " — " + fmtDate(to),
"",
"Доход: " + fmt(s.income),
"Расход: " + fmt(s.expense),
"Итого: " + fmt(s.net),
"",
"По категориям:"
];
const cats = Object.entries(s.byCat).sort((a, b) => {
const aV = a[1].expense + a[1].income;
const bV = b[1].expense + b[1].income;
return bV - aV;
});
if (!cats.length) {
lines.push("За период записей нет.");
} else {
for (const [cat, v] of cats) {
const parts = [];
if (v.income) parts.push("доход " + fmt(v.income));
if (v.expense) parts.push("расход " + fmt(v.expense));
lines.push("• " + cat + " — " + parts.join(", "));
}
}
return lines.join("\n");
}
module.exports = {
startMessage,
helpMessage,
balanceMessage,
monthMessage,
reportMessage,
fmt
};

73
storage.js Normal file
View File

@ -0,0 +1,73 @@
const fs = require("fs");
const path = require("path");
const FILE = path.join(__dirname, "data.json");
function read() {
try {
return JSON.parse(fs.readFileSync(FILE, "utf8"));
} catch (_) {
return { entries: [] };
}
}
function write(data) {
data.updatedAt = new Date().toISOString();
fs.writeFileSync(FILE, JSON.stringify(data, null, 2));
}
function addEntry({ userId, type, amount, note, auto }) {
const data = read();
const entry = {
id: Date.now() + "_" + Math.random().toString(36).slice(2, 7),
userId,
type, // "income" | "expense"
amount: Math.round(amount),
note: String(note || "").trim(),
isAuto: !!auto,
createdAt: new Date().toISOString()
};
data.entries.push(entry);
write(data);
return entry;
}
function getEntries(userId) {
return read().entries.filter((e) => e.userId === userId);
}
function getBalance(userId) {
const list = getEntries(userId);
return list.reduce((bal, e) => (e.type === "income" ? bal + e.amount : bal - e.amount), 0);
}
function getMonthlySummary(userId, year, month) {
const list = getEntries(userId).filter((e) => {
const d = new Date(e.createdAt);
return d.getFullYear() === year && d.getMonth() + 1 === month;
});
const income = list.filter((e) => e.type === "income").reduce((s, e) => s + e.amount, 0);
const expense = list.filter((e) => e.type === "expense").reduce((s, e) => s + e.amount, 0);
return { income, expense, net: income - expense };
}
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;
});
const income = list.filter((e) => e.type === "income").reduce((s, e) => s + e.amount, 0);
const expense = list.filter((e) => e.type === "expense").reduce((s, e) => s + e.amount, 0);
const byCat = {};
for (const e of list) {
const cat = e.note || "Без категории";
byCat[cat] = byCat[cat] || { income: 0, expense: 0 };
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 };
}
module.exports = { addEntry, getEntries, getBalance, getMonthlySummary, getPeriodSummary, read, write };