const store = require("./storage"); const rates = require("./rates"); 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 кафе — расход", "• +100 usd перевод — доход в валюте (курс по /rate)", "Всё, что после цифры, — категория/комментарий.", "", "Каждый день я автоматически списываю 1 000 ₸ на дорогу.", "", "Команды:", "/balance — текущий остаток", "/month — итог за текущий месяц", "/report ГГГГ-Месяц — отчёт за месяц", "/by ГГГГ-Месяц категория — сколько ушло на категорию", "/forecast — прогноз на остаток", "/quick — быстрые кнопки", "/undo — отменить последнюю запись", "/remind ДД.ММ ТЕМА — напоминание", "/reminders — список напоминаний", "/chart — график месяца (PNG)", "/rate — показать/сменить курс валют", "/export — выгрузить всё в Excel", "/backup — выгрузить data.json", "/help — полная справка" ].join("\n"); } function helpMessage() { return [ "Справка", "", "Операции:", "• +50000 зарплата — доход", "• -2500 кафе — расход", "• +100 usd перевод — доход в валюте", "• +50 eur перевод — доход в евро", "(валюты: usd, eur — курс задаётся через /rate)", "", "Команды:", "/balance — остаток сегодня", "/month — доход/расход за этот месяц", "/report 2026-06 — отчёт за июнь 2026", "/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"); } 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"); } // Локальная функция парсинга периода (используется в /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, byCategoryMessage, forecastMessage, reminderMessage, rateInfo, rateUpdateMessage, chartMessage, undoMessage, exportInfo, quickButtons, fmt, fmtDate, parsePeriodArg: parsePeriodArgLocal };