From 5fbd154c9544c99fdf596be2f5f72fecea3e4c68 Mon Sep 17 00:00:00 2001 From: Alex Ultra Date: Fri, 2 Oct 2026 11:37:47 +0200 Subject: [PATCH 1/4] feat(budget): add explainable setup prompts and compact overview (#123) --- CLAUDE.md | 6 + src/bot/commands/budget-progress.test.ts | 176 ---------- src/bot/commands/budget-view.test.ts | 209 ++++++++++++ src/bot/commands/budget-view.ts | 222 +++++++++++++ src/bot/commands/budget.test.ts | 39 ++- src/bot/commands/budget.ts | 180 ++--------- src/bot/cron.test.ts | 56 +++- src/bot/cron.ts | 63 ++-- src/bot/handlers/budget-callbacks.ts | 111 +++++++ src/bot/handlers/callback.handler.test.ts | 179 ++++++++++- src/bot/handlers/callback.handler.ts | 17 +- src/bot/handlers/message.handler.test.ts | 74 +++++ src/bot/handlers/message.handler.ts | 16 +- src/bot/keyboards.test.ts | 61 ++-- src/bot/keyboards.ts | 32 +- src/bot/services/budget-prompt.test.ts | 302 ++++++++++++++++++ src/bot/services/budget-prompt.ts | 200 ++++++++++++ src/database/index.ts | 3 + .../budget-prompt.repository.test.ts | 132 ++++++++ .../repositories/budget-prompt.repository.ts | 169 ++++++++++ src/database/schema.ts | 31 ++ src/database/types.ts | 24 ++ .../expense-flow.integration.test.ts | 2 + src/services/budget-suggestions.test.ts | 137 ++++++++ src/services/budget-suggestions.ts | 186 +++++++++++ .../currency/budget-amount-parser.test.ts | 41 +++ src/services/currency/budget-amount-parser.ts | 52 +++ src/test-utils/db.ts | 1 + src/test-utils/mocks/database.ts | 1 + src/utils/html.test.ts | 25 ++ src/utils/html.ts | 24 ++ src/utils/ru-date.test.ts | 16 + src/utils/ru-date.ts | 21 ++ 33 files changed, 2375 insertions(+), 433 deletions(-) delete mode 100644 src/bot/commands/budget-progress.test.ts create mode 100644 src/bot/commands/budget-view.test.ts create mode 100644 src/bot/commands/budget-view.ts create mode 100644 src/bot/handlers/budget-callbacks.ts create mode 100644 src/bot/services/budget-prompt.test.ts create mode 100644 src/bot/services/budget-prompt.ts create mode 100644 src/database/repositories/budget-prompt.repository.test.ts create mode 100644 src/database/repositories/budget-prompt.repository.ts create mode 100644 src/services/budget-suggestions.test.ts create mode 100644 src/services/budget-suggestions.ts create mode 100644 src/services/currency/budget-amount-parser.test.ts create mode 100644 src/services/currency/budget-amount-parser.ts create mode 100644 src/utils/ru-date.test.ts create mode 100644 src/utils/ru-date.ts diff --git a/CLAUDE.md b/CLAUDE.md index decd78cb..2aff0bba 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -166,6 +166,12 @@ Bot uses callback queries (inline keyboards) and message handlers to manage mult - **OAuth setup:** currency selection → additional currencies → spreadsheet creation - **New category confirmation:** detect new category → ask user to confirm/skip → save - **Budget management:** create/view/edit budgets via inline keyboards +- **Budget setup prompt:** persistent `budget_prompts` rows (scoped by group/user/topic) with data-driven + suggestions; answered by a button (`budget:psuggest::`, `budget:pskip:`), + a strict plain amount when exactly one prompt is active, or a reply to the prompt message when several are. + Logic: [src/bot/services/budget-prompt.ts](src/bot/services/budget-prompt.ts), suggestions: + [src/services/budget-suggestions.ts](src/services/budget-suggestions.ts), `/budget` rich view: + [src/bot/commands/budget-view.ts](src/bot/commands/budget-view.ts) **Key files:** diff --git a/src/bot/commands/budget-progress.test.ts b/src/bot/commands/budget-progress.test.ts deleted file mode 100644 index 6e33f484..00000000 --- a/src/bot/commands/budget-progress.test.ts +++ /dev/null @@ -1,176 +0,0 @@ -// Tests for formatBudgetProgressText — budget progress formatting for /budget and cron - -import { mock } from 'bun:test'; -import type { CurrencyCode } from '../../config/constants'; -import { createMockLogger } from '../../test-utils/mocks/logger'; - -// ── Mock database ── - -const mockExpenses = { - findByDateRange: mock( - ( - _groupId: number, - _from: string, - _to: string, - ): Array<{ category: string; eur_amount: number }> => [], - ), -}; - -const mockBudgets = { - getAllBudgetsForMonth: mock( - ( - _groupId: number, - _month: string, - ): Array<{ - category: string; - limit_amount: number; - currency: CurrencyCode; - }> => [], - ), -}; - -mock.module('../../database', () => ({ - database: { - expenses: mockExpenses, - budgets: mockBudgets, - }, -})); - -mock.module('../../services/currency/converter', () => ({ - convertCurrency: mock((amount: number) => amount), - formatAmount: mock((amount: number, currency: string) => `${amount} ${currency}`), -})); - -const logMock = createMockLogger(); -mock.module('../../utils/logger', () => ({ - createLogger: () => logMock, - logger: logMock, -})); - -mock.module('../../services/analytics/spending-analytics', () => ({ - spendingAnalytics: { - getFinancialSnapshot: () => ({ technicalAnalysis: null }), - }, -})); - -// ── Import after mocks ── - -import { beforeEach, describe, expect, it } from 'bun:test'; -import { formatBudgetProgressText } from './budget'; - -beforeEach(() => { - mockExpenses.findByDateRange.mockReset(); - mockExpenses.findByDateRange.mockReturnValue([]); - mockBudgets.getAllBudgetsForMonth.mockReset(); - mockBudgets.getAllBudgetsForMonth.mockReturnValue([]); -}); - -describe('formatBudgetProgressText', () => { - it('returns hasBudgets=false when no budgets exist', () => { - const result = formatBudgetProgressText(1); - - expect(result.hasBudgets).toBe(false); - expect(result.text).toContain('Бюджеты не установлены'); - }); - - it('includes month name in header', () => { - const result = formatBudgetProgressText(1); - - // Should contain "Бюджет на " - expect(result.text).toMatch(/Бюджет на /); - }); - - it('returns hasBudgets=true when budgets exist', () => { - mockBudgets.getAllBudgetsForMonth.mockReturnValue([ - { category: 'Food', limit_amount: 500, currency: 'EUR' as CurrencyCode }, - ]); - - const result = formatBudgetProgressText(1); - - expect(result.hasBudgets).toBe(true); - expect(result.text).toContain('Food'); - expect(result.text).toContain('500'); - }); - - it('shows 0% when no expenses match budget category', () => { - mockBudgets.getAllBudgetsForMonth.mockReturnValue([ - { category: 'Food', limit_amount: 1000, currency: 'EUR' as CurrencyCode }, - ]); - - const result = formatBudgetProgressText(1); - - expect(result.text).toContain('(0%)'); - }); - - it('calculates correct percentage from expenses', () => { - mockBudgets.getAllBudgetsForMonth.mockReturnValue([ - { category: 'Food', limit_amount: 1000, currency: 'EUR' as CurrencyCode }, - ]); - mockExpenses.findByDateRange.mockReturnValue([{ category: 'Food', eur_amount: 500 }]); - - const result = formatBudgetProgressText(1); - - expect(result.text).toContain('(50%)'); - }); - - it('shows (!) for exceeded budgets', () => { - mockBudgets.getAllBudgetsForMonth.mockReturnValue([ - { category: 'Food', limit_amount: 100, currency: 'EUR' as CurrencyCode }, - ]); - mockExpenses.findByDateRange.mockReturnValue([{ category: 'Food', eur_amount: 150 }]); - - const result = formatBudgetProgressText(1); - - expect(result.text).toContain('(!)'); - }); - - it('shows (~) for warning budgets (>=90%)', () => { - mockBudgets.getAllBudgetsForMonth.mockReturnValue([ - { category: 'Food', limit_amount: 100, currency: 'EUR' as CurrencyCode }, - ]); - mockExpenses.findByDateRange.mockReturnValue([{ category: 'Food', eur_amount: 95 }]); - - const result = formatBudgetProgressText(1); - - expect(result.text).toContain('(~)'); - }); - - it('shows total per currency', () => { - mockBudgets.getAllBudgetsForMonth.mockReturnValue([ - { category: 'Food', limit_amount: 500, currency: 'EUR' as CurrencyCode }, - { category: 'Transport', limit_amount: 200, currency: 'EUR' as CurrencyCode }, - ]); - - const result = formatBudgetProgressText(1); - - expect(result.text).toContain('Всего (EUR)'); - }); - - it('sorts budgets by percentage descending', () => { - mockBudgets.getAllBudgetsForMonth.mockReturnValue([ - { category: 'Low', limit_amount: 1000, currency: 'EUR' as CurrencyCode }, - { category: 'High', limit_amount: 100, currency: 'EUR' as CurrencyCode }, - ]); - mockExpenses.findByDateRange.mockReturnValue([ - { category: 'Low', eur_amount: 100 }, - { category: 'High', eur_amount: 90 }, - ]); - - const result = formatBudgetProgressText(1); - - const highIdx = result.text.indexOf('High'); - const lowIdx = result.text.indexOf('Low'); - expect(highIdx).toBeLessThan(lowIdx); - }); - - it('does not log errors on happy path', () => { - mockBudgets.getAllBudgetsForMonth.mockReturnValue([ - { category: 'Food', limit_amount: 500, currency: 'EUR' as CurrencyCode }, - ]); - - formatBudgetProgressText(1); - - expect(logMock.error).not.toHaveBeenCalled(); - expect(logMock.warn).not.toHaveBeenCalled(); - }); -}); diff --git a/src/bot/commands/budget-view.test.ts b/src/bot/commands/budget-view.test.ts new file mode 100644 index 00000000..8af5a3e3 --- /dev/null +++ b/src/bot/commands/budget-view.test.ts @@ -0,0 +1,209 @@ +// Tests for the rich-text /budget view: Russian month, aligned
 table, totals, markers, 4096 split
+
+import { mock } from 'bun:test';
+import type { CurrencyCode } from '../../config/constants';
+import { createMockLogger } from '../../test-utils/mocks/logger';
+
+interface BudgetStub {
+  category: string;
+  limit_amount: number;
+  currency: CurrencyCode;
+}
+
+const mockExpenses = {
+  getCategoryTotals: mock(
+    (
+      _groupId: number,
+      _from: string,
+      _to: string,
+    ): Array<{ category: string; total: number }> => [],
+  ),
+};
+const mockBudgets = {
+  getAllBudgetsForMonth: mock((_groupId: number, _month: string): BudgetStub[] => []),
+};
+const mockGroups = {
+  findById: mock((_id: number) => ({ id: 1, default_currency: 'EUR' as CurrencyCode })),
+};
+
+mock.module('../../database', () => ({
+  database: { expenses: mockExpenses, budgets: mockBudgets, groups: mockGroups },
+}));
+
+const logMock = createMockLogger();
+mock.module('../../utils/logger', () => ({ createLogger: () => logMock, logger: logMock }));
+
+const snapshotMock = mock((_groupId: number): { technicalAnalysis: unknown } => ({
+  technicalAnalysis: null,
+}));
+mock.module('../../services/analytics/spending-analytics', () => ({
+  spendingAnalytics: { getFinancialSnapshot: snapshotMock },
+}));
+
+import { beforeEach, describe, expect, it } from 'bun:test';
+import { formatBudgetProgress } from './budget-view';
+
+const OCTOBER = new Date('2026-10-15T12:00:00Z');
+
+function budget(category: string, limit: number, currency: CurrencyCode = 'EUR'): BudgetStub {
+  return { category, limit_amount: limit, currency };
+}
+
+function render(now: Date = OCTOBER): { messages: string[]; hasBudgets: boolean } {
+  return formatBudgetProgress(1, now);
+}
+
+function allText(): string {
+  return render().messages.join('\n');
+}
+
+function tableRows(text: string): string[] {
+  return text
+    .split('\n')
+    .map((line) => line.replace(/<\/?pre>/g, ''))
+    .filter((line) => line.includes(' / ') && /[🟢🟡🔴]/u.test(line));
+}
+
+beforeEach(() => {
+  mockExpenses.getCategoryTotals.mockReset();
+  mockExpenses.getCategoryTotals.mockReturnValue([]);
+  mockBudgets.getAllBudgetsForMonth.mockReset();
+  mockBudgets.getAllBudgetsForMonth.mockReturnValue([]);
+  snapshotMock.mockReset();
+  snapshotMock.mockReturnValue({ technicalAnalysis: null });
+  logMock.error.mockClear();
+  logMock.warn.mockClear();
+});
+
+describe('formatBudgetProgress', () => {
+  it('reports no budgets with the localized month', () => {
+    const result = render();
+    expect(result.hasBudgets).toBe(false);
+    expect(result.messages.join('\n')).toContain('Бюджеты не установлены');
+    expect(result.messages.join('\n')).toContain('октябрь 2026');
+  });
+
+  it('uses Russian month names, not English ones', () => {
+    mockBudgets.getAllBudgetsForMonth.mockReturnValue([budget('Food', 500)]);
+    const september = formatBudgetProgress(1, new Date('2026-09-02T12:00:00Z')).messages.join('\n');
+    expect(september).toContain('сентябрь 2026');
+    expect(september).not.toContain('September');
+    expect(allText()).toContain('');
+  });
+
+  it('renders categories inside an HTML 
 table with matching tags', () => {
+    mockBudgets.getAllBudgetsForMonth.mockReturnValue([budget('Food', 500), budget('Rent', 900)]);
+    const text = allText();
+    expect(text.match(/
/g)?.length).toBe(text.match(/<\/pre>/g)?.length);
+    expect(text).toContain('
');
+    expect(tableRows(text)).toHaveLength(2);
+  });
+
+  it('aligns the amount separator across rows', () => {
+    mockBudgets.getAllBudgetsForMonth.mockReturnValue([
+      budget('Food', 500),
+      budget('Transportation costs', 1200),
+      budget('Hi', 50),
+    ]);
+    mockExpenses.getCategoryTotals.mockReturnValue([{ category: 'Food', total: 77 }]);
+    const rows = tableRows(allText());
+    const positions = rows.map((row) => row.indexOf(' / '));
+    expect(rows).toHaveLength(3);
+    expect(new Set(positions).size).toBe(1);
+  });
+
+  it('escapes HTML in category names', () => {
+    mockBudgets.getAllBudgetsForMonth.mockReturnValue([budget('R&D ', 100)]);
+    const text = allText();
+    expect(text).toContain('R&D <b>');
+    expect(text).not.toContain('R&D ');
+  });
+
+  it('shows per-currency totals plus a combined line for mixed currencies', () => {
+    mockBudgets.getAllBudgetsForMonth.mockReturnValue([
+      budget('Food', 500, 'EUR'),
+      budget('Taxi', 20000, 'RSD'),
+    ]);
+    const text = allText();
+    expect(text).toContain('Итого EUR');
+    expect(text).toContain('Итого RSD');
+    expect(text).toContain('Всего');
+  });
+
+  it('does not add a combined line for a single currency', () => {
+    mockBudgets.getAllBudgetsForMonth.mockReturnValue([budget('Food', 500), budget('Rent', 900)]);
+    const text = allText();
+    expect(text).toContain('Итого EUR');
+    expect(text).not.toContain('Всего');
+  });
+
+  it('orders rows by usage percentage, highest first', () => {
+    mockBudgets.getAllBudgetsForMonth.mockReturnValue([budget('Low', 1000), budget('High', 100)]);
+    mockExpenses.getCategoryTotals.mockReturnValue([
+      { category: 'Low', total: 100 },
+      { category: 'High', total: 90 },
+    ]);
+    const text = allText();
+    expect(text.indexOf('High')).toBeLessThan(text.indexOf('Low'));
+  });
+
+  it('marks under-limit, warning and exceeded budgets differently', () => {
+    mockBudgets.getAllBudgetsForMonth.mockReturnValue([
+      budget('Calm', 100),
+      budget('Warn', 100),
+      budget('Over', 100),
+    ]);
+    mockExpenses.getCategoryTotals.mockReturnValue([
+      { category: 'Calm', total: 10 },
+      { category: 'Warn', total: 95 },
+      { category: 'Over', total: 150 },
+    ]);
+    const rows = tableRows(allText());
+    expect(rows.find((r) => r.includes('Calm'))).toContain('🟢');
+    expect(rows.find((r) => r.includes('Warn'))).toContain('🟡');
+    expect(rows.find((r) => r.includes('Over'))).toContain('🔴');
+  });
+
+  it('shows 0% when nothing was spent', () => {
+    mockBudgets.getAllBudgetsForMonth.mockReturnValue([budget('Food', 1000)]);
+    expect(allText()).toContain('0%');
+  });
+
+  it('adds forecast insights for categories heading over budget', () => {
+    mockBudgets.getAllBudgetsForMonth.mockReturnValue([budget('Food', 100)]);
+    snapshotMock.mockReturnValue({
+      technicalAnalysis: {
+        categories: [
+          {
+            category: 'Food',
+            forecasts: { ensemble: 150 },
+            trend: { direction: 'rising', confidence: 0.9 },
+            anomaly: { isAnomaly: false },
+          },
+        ],
+      },
+    });
+    expect(allText()).toContain('Прогноз');
+  });
+
+  it('splits long output into valid messages under 4096 characters', () => {
+    const many = Array.from({ length: 220 }, (_, i) =>
+      budget(`Category <${i}> with a very long name & more`, 100 + i),
+    );
+    mockBudgets.getAllBudgetsForMonth.mockReturnValue(many);
+    const result = render();
+    expect(result.messages.length).toBeGreaterThan(1);
+    for (const message of result.messages) {
+      expect(message.length).toBeLessThanOrEqual(4096);
+      expect(message.match(/
/g)?.length ?? 0).toBe(message.match(/<\/pre>/g)?.length ?? 0);
+    }
+    expect(result.messages.join('\n')).toContain('Category <219>');
+  });
+
+  it('does not log errors on the happy path', () => {
+    mockBudgets.getAllBudgetsForMonth.mockReturnValue([budget('Food', 500)]);
+    render();
+    expect(logMock.error).not.toHaveBeenCalled();
+    expect(logMock.warn).not.toHaveBeenCalled();
+  });
+});
diff --git a/src/bot/commands/budget-view.ts b/src/bot/commands/budget-view.ts
new file mode 100644
index 00000000..263a0d1c
--- /dev/null
+++ b/src/bot/commands/budget-view.ts
@@ -0,0 +1,222 @@
+// Rich Telegram HTML budget overview: aligned 
 table, RU month name, safe 4096-char chunking
+
+import { endOfMonth, format, startOfMonth } from 'date-fns';
+import { getCategoryEmoji } from '../../config/category-emojis';
+import { BASE_CURRENCY, type CurrencyCode } from '../../config/constants';
+import { database } from '../../database';
+import { computeBudgetProgress } from '../../database/repositories/budget.repository';
+import type { Budget } from '../../database/types';
+import { spendingAnalytics } from '../../services/analytics/spending-analytics';
+import { convertCurrency, formatAmount } from '../../services/currency/converter';
+import { escapeHtml, packHtmlBlocks } from '../../utils/html';
+import { formatMonthYearRu } from '../../utils/ru-date';
+
+const TABLE_CHUNK_LIMIT = 3500;
+const MAX_NAME_WIDTH = 16;
+const MAX_FORECAST_LINES = 10;
+
+interface CategoryRow {
+  budget: Budget;
+  spent: number;
+  percentage: number;
+  isExceeded: boolean;
+  isWarning: boolean;
+}
+
+interface CurrencyTotal {
+  spent: number;
+  limit: number;
+}
+
+function percent(spent: number, limit: number): number {
+  return limit > 0 ? Math.round((spent / limit) * 100) : 0;
+}
+
+function marker(row: CategoryRow): string {
+  if (row.isExceeded) return '🔴';
+  return row.isWarning ? '🟡' : '🟢';
+}
+
+function truncateName(name: string): string {
+  const chars = Array.from(name);
+  return chars.length > MAX_NAME_WIDTH ? `${chars.slice(0, MAX_NAME_WIDTH - 1).join('')}…` : name;
+}
+
+function padCell(cell: string, width: number, align: 'left' | 'right'): string {
+  // Pad by code points: String#padEnd counts UTF-16 units, which misaligns emoji cells.
+  const gap = ' '.repeat(Math.max(0, width - Array.from(cell).length));
+  return align === 'right' ? `${gap}${cell}` : `${cell}${gap}`;
+}
+
+/** Pad every column to its widest cell so rows line up in a monospace 
. */
+function alignColumns(rows: string[][], align: Array<'left' | 'right'>): string[] {
+  const widths = (rows[0] ?? []).map((_, col) =>
+    Math.max(...rows.map((row) => Array.from(row[col] ?? '').length)),
+  );
+  return rows.map((row) =>
+    row.map((cell, col) => padCell(cell, widths[col] ?? 0, align[col] ?? 'left')).join(' '),
+  );
+}
+
+function wrapPre(lines: string[]): string {
+  return `
${lines.map(escapeHtml).join('\n')}
`; +} + +function loadRows(groupId: number, budgets: Budget[], now: Date): CategoryRow[] { + const totals = database.expenses.getCategoryTotals( + groupId, + format(startOfMonth(now), 'yyyy-MM-dd'), + format(endOfMonth(now), 'yyyy-MM-dd'), + ); + const spentEur = new Map(totals.map((row) => [row.category, row.total])); + const rows = budgets.map((budget) => { + const spent = convertCurrency( + spentEur.get(budget.category) ?? 0, + BASE_CURRENCY, + budget.currency, + ); + const progress = computeBudgetProgress(budget, spent); + return { + budget, + spent, + percentage: progress.percentage, + isExceeded: progress.is_exceeded, + isWarning: progress.is_warning, + }; + }); + return rows.sort( + (a, b) => b.percentage - a.percentage || a.budget.category.localeCompare(b.budget.category), + ); +} + +function sumByCurrency(rows: CategoryRow[]): Map { + const totals = new Map(); + for (const { budget, spent } of rows) { + const total = totals.get(budget.currency) ?? { spent: 0, limit: 0 }; + total.spent += spent; + total.limit += budget.limit_amount; + totals.set(budget.currency, total); + } + return totals; +} + +function totalsBlock(groupId: number, rows: CategoryRow[]): string { + const totals = sumByCurrency(rows); + const cells = [...totals].map(([currency, { spent, limit }]) => [ + `Итого ${currency}`, + formatAmount(spent, currency), + '/', + formatAmount(limit, currency), + `${percent(spent, limit)}%`, + ]); + if (totals.size > 1) { + const display = database.groups.findById(groupId)?.default_currency ?? BASE_CURRENCY; + const all = [...totals].reduce( + (sum, [currency, t]) => ({ + spent: sum.spent + convertCurrency(t.spent, currency, display), + limit: sum.limit + convertCurrency(t.limit, currency, display), + }), + { spent: 0, limit: 0 }, + ); + cells.push([ + `Всего ≈ ${display}`, + formatAmount(all.spent, display), + '/', + formatAmount(all.limit, display), + `${percent(all.spent, all.limit)}%`, + ]); + } + return wrapPre(alignColumns(cells, ['left', 'right', 'left', 'right', 'right'])); +} + +/** Table rows packed into
 blocks that each stay well under the Telegram limit. */
+function tableBlocks(rows: CategoryRow[]): string[] {
+  const cells = rows.map((row) => [
+    `${marker(row)} ${truncateName(row.budget.category)}`,
+    formatAmount(row.spent, row.budget.currency),
+    '/',
+    formatAmount(row.budget.limit_amount, row.budget.currency),
+    `${row.percentage}%`,
+  ]);
+  // Marker emoji + space prefix are identical in width for every row, so pad names only.
+  const lines = alignColumns(cells, ['left', 'right', 'left', 'right', 'right']);
+  const blocks: string[] = [];
+  let chunk: string[] = [];
+  let size = 0;
+  for (const line of lines) {
+    const lineSize = escapeHtml(line).length + 1;
+    if (chunk.length > 0 && size + lineSize > TABLE_CHUNK_LIMIT) {
+      blocks.push(wrapPre(chunk));
+      chunk = [];
+      size = 0;
+    }
+    chunk.push(line);
+    size += lineSize;
+  }
+  if (chunk.length > 0) blocks.push(wrapPre(chunk));
+  return blocks;
+}
+
+function forecastBlock(groupId: number, rows: CategoryRow[]): string | null {
+  const analysis = spendingAnalytics.getFinancialSnapshot(groupId).technicalAnalysis;
+  if (!analysis) return null;
+  const insights: string[] = [];
+  for (const cat of analysis.categories) {
+    const row = rows.find((r) => r.budget.category === cat.category);
+    if (!row) continue;
+    const forecast = Math.round(
+      convertCurrency(cat.forecasts.ensemble, BASE_CURRENCY, row.budget.currency),
+    );
+    const forecastPct = percent(forecast, row.budget.limit_amount);
+    const rising = cat.trend.direction === 'rising';
+    if (forecastPct >= 80 || cat.anomaly.isAnomaly || (rising && cat.trend.confidence >= 0.6)) {
+      const arrow = rising ? '↑' : cat.trend.direction === 'falling' ? '↓' : '→';
+      const warn = cat.anomaly.isAnomaly ? ' ⚠️' : '';
+      insights.push(
+        `${getCategoryEmoji(cat.category)} ${escapeHtml(cat.category)}: прогноз ${formatAmount(forecast, row.budget.currency)} ${arrow}${warn}`,
+      );
+    }
+  }
+  if (insights.length === 0) return null;
+  // N+2 rule: never hide fewer than 3 lines behind "и ещё N".
+  const hidden = insights.length - MAX_FORECAST_LINES;
+  const visible = hidden >= 3 ? insights.slice(0, MAX_FORECAST_LINES) : insights;
+  const tail = hidden >= 3 ? `\n… и ещё ${hidden}` : '';
+  return `Прогноз на месяц\n${visible.join('\n')}${tail}`;
+}
+
+/** Build the budget overview as one or more Telegram HTML messages. */
+export function formatBudgetProgress(
+  groupId: number,
+  now: Date = new Date(),
+): { messages: string[]; hasBudgets: boolean } {
+  const title = `📊 Бюджет на ${formatMonthYearRu(now)}`;
+  const budgets = database.budgets.getAllBudgetsForMonth(groupId, format(now, 'yyyy-MM'));
+  if (budgets.length === 0) {
+    return { messages: [`${title}\n\nБюджеты не установлены.`], hasBudgets: false };
+  }
+
+  const rows = loadRows(groupId, budgets, now);
+  const legend = '🟢 в рамках · 🟡 от 90% · 🔴 превышен';
+  const blocks = [`${title}\n${legend}`, totalsBlock(groupId, rows), ...tableBlocks(rows)];
+  const forecast = forecastBlock(groupId, rows);
+  if (forecast) blocks.push(forecast);
+  return { messages: packHtmlBlocks(blocks), hasBudgets: true };
+}
+
+/** Confirmation text after a budget was written (used by /budget set and the prompt flow). */
+export function formatBudgetSetMessage(params: {
+  category: string;
+  amount: number;
+  currency: CurrencyCode;
+  sheetsSynced: boolean;
+  sheetsConnected: boolean;
+}): string {
+  const { category, amount, currency, sheetsSynced, sheetsConnected } = params;
+  const summary = `Бюджет установлен: ${getCategoryEmoji(category)} ${escapeHtml(category)} = ${formatAmount(amount, currency)}`;
+  if (sheetsSynced) return summary;
+  if (sheetsConnected) {
+    return `${summary}\n\nНе удалось записать в Google Sheets. Используй /budget sync позже.`;
+  }
+  return `${summary}\n\nПодключи Google Sheets (/connect) чтобы синхронизировать бюджеты.`;
+}
diff --git a/src/bot/commands/budget.test.ts b/src/bot/commands/budget.test.ts
index 50717320..dcdfe1f8 100644
--- a/src/bot/commands/budget.test.ts
+++ b/src/bot/commands/budget.test.ts
@@ -17,15 +17,19 @@ mock.module('../../utils/logger.ts', () => ({
 // ── Database ──────────────────────────────────────────────────────────────
 
 const mockExpenses = {
-  findByDateRange: mock(
+  getCategoryTotals: mock(
     (
       _groupId: number,
       _from: string,
       _to: string,
-    ): Array<{ category: string; eur_amount: number }> => [],
+    ): Array<{ category: string; total: number }> => [],
   ),
 };
 
+const mockGroups = {
+  findById: mock((_id: number) => ({ id: 1, default_currency: 'EUR' as CurrencyCode })),
+};
+
 const mockBudgets = {
   getAllBudgetsForMonth: mock(
     (
@@ -50,6 +54,7 @@ mock.module('../../database', () => ({
     expenses: mockExpenses,
     budgets: mockBudgets,
     categories: mockCategories,
+    groups: mockGroups,
   },
 }));
 
@@ -119,7 +124,7 @@ mock.module('../services/budget-sync', () => ({
   silentSyncBudgets: silentSyncBudgetsMock,
 }));
 
-// ── Analytics (used by formatBudgetProgressText — we stub to avoid noise) ─
+// ── Analytics (used by the budget view formatter — we stub to avoid noise) ─
 
 mock.module('../../services/analytics/spending-analytics', () => ({
   spendingAnalytics: {
@@ -184,7 +189,7 @@ beforeEach(() => {
   budgetManagerMock.delete.mockReset().mockResolvedValue({ deleted: true, sheetsSynced: true });
   budgetManagerMock.importFromSheet.mockReset().mockReturnValue({});
 
-  mockExpenses.findByDateRange.mockReset().mockReturnValue([]);
+  mockExpenses.getCategoryTotals.mockReset().mockReturnValue([]);
   mockBudgets.getAllBudgetsForMonth.mockReset().mockReturnValue([]);
   mockCategories.exists.mockReset().mockReturnValue(true);
   mockCategories.create.mockReset();
@@ -216,13 +221,14 @@ describe('/budget list view', () => {
     mockBudgets.getAllBudgetsForMonth.mockReturnValue([
       { category: 'Food', limit_amount: 500, currency: 'EUR' as CurrencyCode },
     ]);
-    mockExpenses.findByDateRange.mockReturnValue([{ category: 'Food', eur_amount: 250 }]);
+    mockExpenses.getCategoryTotals.mockReturnValue([{ category: 'Food', total: 250 }]);
 
     await handleBudgetCommand(fakeCtx('/budget'), fakeGroup());
 
     const msg = sendMessageMock.mock.calls.at(-1)?.[0] as string;
     expect(msg).toContain('Food');
-    expect(msg).toContain('(50%)');
+    expect(msg).toContain('50%');
+    expect(msg).toContain('
');
     expect(logMock.error).not.toHaveBeenCalled();
   });
 
@@ -255,6 +261,27 @@ describe('/budget set', () => {
     expect(msg).toContain('Food');
   });
 
+  test('success confirmation carries the "show budget" action', async () => {
+    await handleBudgetCommand(fakeCtx('/budget set Food 500'), fakeGroup());
+
+    const options = sendMessageMock.mock.calls.at(-1)?.[1] as {
+      reply_markup: { toJSON: () => { inline_keyboard: Array> } };
+    };
+    const data = options.reply_markup
+      .toJSON()
+      .inline_keyboard.flat()
+      .map((b) => b.callback_data);
+    expect(data).toContain('budget:view');
+  });
+
+  test('escapes the category name in the confirmation', async () => {
+    await handleBudgetCommand(fakeCtx('/budget set R&D 500'), fakeGroup());
+
+    const msg = sendMessageMock.mock.calls.at(-1)?.[0] as string;
+    expect(msg).toContain('R&');
+    expect(msg).not.toContain('R&d');
+  });
+
   test('parses RSD via suffix ("500 RSD") when group default is EUR', async () => {
     await handleBudgetCommand(fakeCtx('/budget set Транспорт 500 RSD'), fakeGroup());
 
diff --git a/src/bot/commands/budget.ts b/src/bot/commands/budget.ts
index b0f3a0e8..040cab86 100644
--- a/src/bot/commands/budget.ts
+++ b/src/bot/commands/budget.ts
@@ -1,19 +1,10 @@
 /** /budget command handler — create, view, and edit spending budgets per category */
-import { endOfMonth, format, startOfMonth } from 'date-fns';
+import { format } from 'date-fns';
 import { InlineKeyboard } from 'gramio';
-import { getCategoryEmoji } from '../../config/category-emojis';
-import {
-  BASE_CURRENCY,
-  CURRENCY_ALIASES,
-  type CurrencyCode,
-  getCurrencySymbol,
-} from '../../config/constants';
+import { CURRENCY_ALIASES, type CurrencyCode, getCurrencySymbol } from '../../config/constants';
 import { database } from '../../database';
-import { computeBudgetProgress } from '../../database/repositories/budget.repository';
-import { spendingAnalytics } from '../../services/analytics/spending-analytics';
 import { sendMessage } from '../../services/bank/telegram-sender';
 import { getBudgetManager } from '../../services/budget-manager';
-import { convertCurrency, formatAmount } from '../../services/currency/converter';
 import { monthAbbrFromDate } from '../../services/google/month-abbr';
 import {
   createEmptyMonthTab,
@@ -22,17 +13,20 @@ import {
   readMonthBudget,
 } from '../../services/google/sheets';
 import { normalizeCategoryName } from '../../utils/fuzzy-search';
-import { truncateForTelegram } from '../../utils/html';
 import { createLogger } from '../../utils/logger.ts';
 import { buildMiniAppUrl } from '../../utils/miniapp-url';
 import type { GoogleConnectedGroup } from '../guards';
-import { createAddCategoryWithBudgetKeyboard } from '../keyboards';
+import { createAddCategoryWithBudgetKeyboard, createBudgetViewKeyboard } from '../keyboards';
 import { silentSyncBudgets } from '../services/budget-sync';
 import type { Ctx } from '../types';
 import { maybeSmartAdvice } from './ask';
+import { formatBudgetProgress, formatBudgetSetMessage } from './budget-view';
 
 const logger = createLogger('budget');
 
+const NO_BUDGET_HINT =
+  'Используй:\n• /budget set <Категория> <Сумма>\n• /budget sync — синхронизировать с Google Sheets';
+
 /**
  * Parse budget amount with optional currency
  * Supports: 500, 500$, $500, 500 EUR, 500 евро, etc.
@@ -138,7 +132,7 @@ export async function handleBudgetCommand(
 
   if (args.length === 0) {
     // Show current budgets and progress
-    await showBudgetProgress(ctx, group);
+    await sendBudgetView(group);
     return;
   }
 
@@ -178,131 +172,21 @@ export async function handleBudgetCommand(
   );
 }
 
-/**
- * Format budget progress text for a group (reusable by cron and /budget command)
- */
-export function formatBudgetProgressText(groupId: number): { text: string; hasBudgets: boolean } {
-  const now = new Date();
-  const currentMonth = format(now, 'yyyy-MM');
-  const currentMonthName = format(now, 'LLLL yyyy');
-
-  const currentMonthStart = format(startOfMonth(now), 'yyyy-MM-dd');
-  const currentMonthEnd = format(endOfMonth(now), 'yyyy-MM-dd');
-  const expenses = database.expenses.findByDateRange(groupId, currentMonthStart, currentMonthEnd);
-
-  const categorySpending: Record = {};
-  for (const expense of expenses) {
-    categorySpending[expense.category] =
-      (categorySpending[expense.category] || 0) + expense.eur_amount;
-  }
-
-  const budgets = database.budgets.getAllBudgetsForMonth(groupId, currentMonth);
-
-  if (budgets.length === 0) {
-    return { text: `Бюджет на ${currentMonthName}\n\nБюджеты не установлены.`, hasBudgets: false };
-  }
-
-  const budgetsByCurrency: Record =
-    {} as Record;
-
-  for (const budget of budgets) {
-    const currency = budget.currency;
-    if (!budgetsByCurrency[currency]) {
-      budgetsByCurrency[currency] = { totalBudget: 0, totalSpent: 0 };
-    }
-    const spentEur = categorySpending[budget.category] || 0;
-    const spentInCurrency = convertCurrency(spentEur, BASE_CURRENCY, currency);
-    budgetsByCurrency[currency].totalBudget += budget.limit_amount;
-    budgetsByCurrency[currency].totalSpent += spentInCurrency;
-  }
-
-  let message = `Бюджет на ${currentMonthName}\n\n`;
-
-  for (const [currency, { totalBudget, totalSpent }] of Object.entries(budgetsByCurrency)) {
-    const percentage = totalBudget > 0 ? Math.round((totalSpent / totalBudget) * 100) : 0;
-    message += `Всего (${currency}): ${formatAmount(totalSpent, currency as CurrencyCode)} / ${formatAmount(totalBudget, currency as CurrencyCode)} (${percentage}%)\n`;
-  }
-  message += '\n';
-
-  const budgetProgress = budgets.map((budget) => {
-    const spentEur = categorySpending[budget.category] || 0;
-    const spent = convertCurrency(spentEur, BASE_CURRENCY, budget.currency);
-    const progress = computeBudgetProgress(budget, spent);
-    return { budget, spent, ...progress };
-  });
-
-  budgetProgress.sort((a, b) => b.percentage - a.percentage);
-
-  for (const { budget, spent, percentage, is_exceeded, is_warning } of budgetProgress) {
-    const emoji = getCategoryEmoji(budget.category);
-    const status = is_exceeded ? '(!)' : is_warning ? '(~)' : '';
-    message += `${emoji} ${budget.category}: ${formatAmount(spent, budget.currency)} / ${formatAmount(budget.limit_amount, budget.currency)} (${percentage}%) ${status}\n`;
-  }
-
-  // Add TA forecast insights for budgeted categories — cap at 10 lines so the
-  // full budget message stays under Telegram's 4096-char limit. N+2 rule for
-  // the "и ещё N" tail.
-  const snapshot = spendingAnalytics.getFinancialSnapshot(groupId);
-  if (snapshot.technicalAnalysis) {
-    const taInsights: string[] = [];
-    for (const cat of snapshot.technicalAnalysis.categories) {
-      const bp = budgetProgress.find((b) => b.budget.category === cat.category);
-      if (!bp) continue;
-
-      const forecast = Math.round(
-        convertCurrency(cat.forecasts.ensemble, BASE_CURRENCY, bp.budget.currency),
-      );
-      const trendLabel =
-        cat.trend.direction === 'rising' ? '↑' : cat.trend.direction === 'falling' ? '↓' : '→';
-      const forecastPct =
-        bp.budget.limit_amount > 0 ? Math.round((forecast / bp.budget.limit_amount) * 100) : 0;
-
-      // Only show insights for categories approaching or exceeding budget
-      if (
-        forecastPct >= 80 ||
-        cat.anomaly.isAnomaly ||
-        (cat.trend.direction === 'rising' && cat.trend.confidence >= 0.6)
-      ) {
-        let insight = `${getCategoryEmoji(cat.category)} ${cat.category}: прогноз ${formatAmount(forecast, bp.budget.currency)} ${trendLabel}`;
-        if (cat.anomaly.isAnomaly) insight += ' ⚠️';
-        taInsights.push(insight);
-      }
-    }
-    if (taInsights.length > 0) {
-      const MAX_TA_INSIGHTS = 10;
-      const hidden = taInsights.length - MAX_TA_INSIGHTS;
-      const visibleInsights = hidden >= 3 ? taInsights.slice(0, MAX_TA_INSIGHTS) : taInsights;
-      message += `\nПрогноз на месяц:\n${visibleInsights.join('\n')}\n`;
-      if (hidden >= 3) {
-        message += `… и ещё ${hidden}\n`;
-      }
-    }
-  }
-
-  return { text: truncateForTelegram(message.trim()), hasBudgets: true };
-}
-
-async function showBudgetProgress(ctx: Ctx['Command'], group: GoogleConnectedGroup): Promise {
-  void ctx;
-
+/** Send the rich budget overview — shared by /budget and the "show budget" button. */
+export async function sendBudgetView(group: {
+  id: number;
+  telegram_group_id: number;
+}): Promise {
+  const { messages, hasBudgets } = formatBudgetProgress(group.id);
   const miniAppUrl = buildMiniAppUrl('dashboard', group.telegram_group_id);
   const keyboard = miniAppUrl ? new InlineKeyboard().url('📊 Дашборд', miniAppUrl) : undefined;
 
-  const { text, hasBudgets } = formatBudgetProgressText(group.id);
-
-  if (!hasBudgets) {
-    await sendMessage(
-      `${text}\n\n` +
-        `Используй:\n` +
-        `• /budget set <Категория> <Сумма>\n` +
-        `• /budget sync — синхронизировать с Google Sheets`,
-      keyboard ? { reply_markup: keyboard } : {},
-    );
-    await maybeSmartAdvice(group.id);
-    return;
+  const lastIndex = messages.length - 1;
+  for (const [index, message] of messages.entries()) {
+    const isLast = index === lastIndex;
+    const text = isLast && !hasBudgets ? `${message}\n\n${NO_BUDGET_HINT}` : message;
+    await sendMessage(text, isLast && keyboard ? { reply_markup: keyboard } : {});
   }
-
-  await sendMessage(text, keyboard ? { reply_markup: keyboard } : {});
   await maybeSmartAdvice(group.id);
 }
 
@@ -346,22 +230,16 @@ async function setBudget(
     currency,
   });
 
-  const emoji = getCategoryEmoji(normalizedCategory);
-  if (!result.sheetsSynced && group.google_refresh_token) {
-    await sendMessage(
-      `Бюджет установлен: ${emoji} ${normalizedCategory} = ${formatAmount(amount, currency)}\n\n` +
-        'Не удалось записать в Google Sheets. Используй /budget sync позже.',
-    );
-  } else if (!result.sheetsSynced) {
-    await sendMessage(
-      `Бюджет установлен: ${emoji} ${normalizedCategory} = ${formatAmount(amount, currency)}\n\n` +
-        'Подключи Google Sheets (/connect) чтобы синхронизировать бюджеты.',
-    );
-  } else {
-    await sendMessage(
-      `Бюджет установлен: ${emoji} ${normalizedCategory} = ${formatAmount(amount, currency)}`,
-    );
-  }
+  await sendMessage(
+    formatBudgetSetMessage({
+      category: normalizedCategory,
+      amount,
+      currency,
+      sheetsSynced: result.sheetsSynced,
+      sheetsConnected: Boolean(group.google_refresh_token),
+    }),
+    { reply_markup: createBudgetViewKeyboard() },
+  );
 
   await maybeSmartAdvice(group.id);
 }
diff --git a/src/bot/cron.test.ts b/src/bot/cron.test.ts
index c6ee9813..4a3b6b99 100644
--- a/src/bot/cron.test.ts
+++ b/src/bot/cron.test.ts
@@ -125,14 +125,14 @@ mock.module('./commands/sync', () => ({
   importExpensesFromSheet: importExpensesFromSheetMock,
 }));
 
-const formatBudgetProgressTextMock = mock(
-  (_groupId: number): { text: string; hasBudgets: boolean } => ({
-    text: 'Бюджет на April 2026\n\nБюджеты не установлены.',
+const formatBudgetProgressMock = mock(
+  (_groupId: number): { messages: string[]; hasBudgets: boolean } => ({
+    messages: ['Бюджет на апрель 2026\n\nБюджеты не установлены.'],
     hasBudgets: false,
   }),
 );
-mock.module('./commands/budget', () => ({
-  formatBudgetProgressText: formatBudgetProgressTextMock,
+mock.module('./commands/budget-view', () => ({
+  formatBudgetProgress: formatBudgetProgressMock,
 }));
 
 import { afterEach, beforeEach, describe, expect, it, spyOn } from 'bun:test';
@@ -284,9 +284,9 @@ describe('registerMonthlyCron', () => {
     createExpenseSpreadsheetMock.mockReset().mockResolvedValue({ spreadsheetId: 'new-sheet-id' });
     silentSyncBudgetsMock.mockReset().mockResolvedValue(0);
     sendMessageMock.mockReset().mockResolvedValue(null);
-    formatBudgetProgressTextMock
+    formatBudgetProgressMock
       .mockReset()
-      .mockReturnValue({ text: 'Бюджет на April 2026', hasBudgets: false });
+      .mockReturnValue({ messages: ['Бюджет на апрель 2026'], hasBudgets: false });
     logMock.error.mockReset();
     logMock.warn.mockReset();
   });
@@ -487,8 +487,8 @@ describe('registerMonthlyCron', () => {
     ]);
     mockGroupSpreadsheets.getByYear.mockReturnValue('sid-current');
     monthTabExistsMock.mockResolvedValueOnce(false).mockResolvedValueOnce(true);
-    formatBudgetProgressTextMock.mockReturnValue({
-      text: 'Food: 50/100',
+    formatBudgetProgressMock.mockReturnValue({
+      messages: ['Food: 50/100'],
       hasBudgets: true,
     });
 
@@ -501,6 +501,42 @@ describe('registerMonthlyCron', () => {
     expect(text).toContain('Food: 50/100');
   });
 
+  it('sends a long budget overview as several valid messages under the Telegram limit', async () => {
+    mockGroupsRepo.findAll.mockReturnValue([
+      {
+        id: 1,
+        telegram_group_id: -100,
+        google_refresh_token: 'tok',
+        default_currency: 'EUR',
+        enabled_currencies: ['EUR'],
+        active_topic_id: null,
+      },
+    ]);
+    mockGroupSpreadsheets.listAll.mockReturnValue([
+      { year: new Date().getFullYear(), spreadsheetId: 'sid-current' },
+    ]);
+    mockGroupSpreadsheets.getByYear.mockReturnValue('sid-current');
+    monthTabExistsMock.mockResolvedValueOnce(false).mockResolvedValueOnce(true);
+    const bigBlock = `
${'row\n'.repeat(900)}
`; + formatBudgetProgressMock.mockReturnValue({ + messages: [bigBlock, bigBlock], + hasBudgets: true, + }); + + registerMonthlyCron(); + const cb = cronSpy.mock.calls[0]?.[1] as () => Promise; + await cb(); + + const texts = sendMessageMock.mock.calls.map((call) => call[0] as string); + expect(texts.length).toBeGreaterThanOrEqual(2); + for (const text of texts) { + expect(text.length).toBeLessThanOrEqual(4096); + expect(text.match(/
/g)?.length ?? 0).toBe(text.match(/<\/pre>/g)?.length ?? 0);
+    }
+    expect(texts[0]).toContain('Новый бюджет сформирован');
+    expect(texts.at(-1)).toContain('/budget sync');
+  });
+
   it('uses "Пора сформировать бюджет" wording when group has no budgets', async () => {
     mockGroupsRepo.findAll.mockReturnValue([
       {
@@ -517,7 +553,7 @@ describe('registerMonthlyCron', () => {
     ]);
     mockGroupSpreadsheets.getByYear.mockReturnValue('sid-current');
     monthTabExistsMock.mockResolvedValueOnce(false).mockResolvedValueOnce(true);
-    formatBudgetProgressTextMock.mockReturnValue({ text: '', hasBudgets: false });
+    formatBudgetProgressMock.mockReturnValue({ messages: [], hasBudgets: false });
 
     registerMonthlyCron();
     const cb = cronSpy.mock.calls[0]?.[1] as () => Promise;
diff --git a/src/bot/cron.ts b/src/bot/cron.ts
index ba393387..c673fc5f 100644
--- a/src/bot/cron.ts
+++ b/src/bot/cron.ts
@@ -15,9 +15,9 @@ import {
   monthTabExists,
   sortExpensesTab,
 } from '../services/google/sheets';
-import { closeUnmatchedTags } from '../utils/html';
+import { packHtmlBlocks } from '../utils/html';
 import { createLogger } from '../utils/logger.ts';
-import { formatBudgetProgressText } from './commands/budget';
+import { formatBudgetProgress } from './commands/budget-view';
 import { importExpensesFromSheet } from './commands/sync';
 import { silentSyncBudgets } from './services/budget-sync';
 
@@ -130,43 +130,28 @@ export function registerMonthlyCron(): void {
         await silentSyncBudgets(conn, group.id);
 
         const sheetUrl = newYearUrl ?? getSpreadsheetUrl(spreadsheetId);
-        const { text: budgetText, hasBudgets } = formatBudgetProgressText(group.id);
-
-        let notifyText: string;
-
-        if (hasBudgets) {
-          notifyText = `Новый бюджет сформирован\n\n🔗 Гугл таблица`;
-          if (newYearUrl) {
-            notifyText += ` (${year})`;
-          }
-          notifyText += `\n\n${budgetText}`;
-          notifyText +=
-            '\n\nРедактировать бюджет можно через ИИ или командами:\n' +
-            '/budget set Категория Сумма\n' +
-            '/budget sync';
-        } else {
-          notifyText = `Пора сформировать бюджет\n\n🔗 Гугл таблица`;
-          if (newYearUrl) {
-            notifyText += ` (${year})`;
-          }
-          notifyText +=
-            '\n\nЗаполни вкладку в таблице или используй команды:\n' +
-            '/budget set Категория Сумма\n' +
-            '/budget sync';
-        }
-
-        // Telegram message limit is 4096 chars — truncate at last newline boundary, close tags
-        if (notifyText.length > 4000) {
-          const cut = notifyText.lastIndexOf('\n', 3900);
-          const truncated = cut > 0 ? notifyText.slice(0, cut) : notifyText.slice(0, 3900);
-          notifyText = closeUnmatchedTags(
-            `${truncated}\n...\n\n🔗 Гугл таблица`,
-          );
-        }
-
-        await withChatContext(group.telegram_group_id, group.active_topic_id, () =>
-          sendMessage(notifyText),
-        ).catch((err: unknown) =>
+        const { messages: budgetMessages, hasBudgets } = formatBudgetProgress(group.id);
+        const yearSuffix = newYearUrl ? ` (${year})` : '';
+        const sheetLink = `🔗 Гугл таблица${yearSuffix}`;
+
+        const blocks = hasBudgets
+          ? [
+              `Новый бюджет сформирован\n\n${sheetLink}`,
+              ...budgetMessages,
+              'Редактировать бюджет можно через ИИ или командами:\n' +
+                '/budget set Категория Сумма\n' +
+                '/budget sync',
+            ]
+          : [
+              `Пора сформировать бюджет\n\n${sheetLink}\n\n` +
+                'Заполни вкладку в таблице или используй команды:\n' +
+                '/budget set Категория Сумма\n' +
+                '/budget sync',
+            ];
+
+        await withChatContext(group.telegram_group_id, group.active_topic_id, async () => {
+          for (const message of packHtmlBlocks(blocks)) await sendMessage(message);
+        }).catch((err: unknown) =>
           logger.error({ err }, `[CRON] Failed to notify group ${group.id}`),
         );
       } catch (err) {
diff --git a/src/bot/handlers/budget-callbacks.ts b/src/bot/handlers/budget-callbacks.ts
new file mode 100644
index 00000000..63eef6c7
--- /dev/null
+++ b/src/bot/handlers/budget-callbacks.ts
@@ -0,0 +1,111 @@
+// Callback handlers for the smart budget prompt buttons: suggested amount, skip, show budget
+
+import type { Group, User } from '../../database/types';
+import { formatAmount } from '../../services/currency/converter';
+import { sendBudgetView } from '../commands/budget';
+import {
+  applyBudgetPrompt,
+  lookupPromptForCallback,
+  skipBudgetPrompt,
+} from '../services/budget-prompt';
+import type { BotInstance, Ctx } from '../types';
+
+export type BudgetPromptAction = 'psuggest' | 'pskip' | 'view';
+
+const STALE_TEXT = 'Запрос устарел или уже обработан';
+const FOREIGN_TEXT = 'Этот запрос создан другим участником';
+
+async function removeButtonMessage(ctx: Ctx['CallbackQuery'], bot: BotInstance): Promise {
+  const chatId = ctx.message?.chat?.id;
+  const messageId = ctx.message?.id;
+  if (chatId && messageId) {
+    await bot.api.deleteMessage({ chat_id: chatId, message_id: messageId });
+  }
+}
+
+function parsePositiveInt(raw: string | undefined): number | null {
+  const value = Number.parseInt(raw ?? '', 10);
+  return Number.isInteger(value) && value > 0 ? value : null;
+}
+
+async function handleSuggestion(
+  ctx: Ctx['CallbackQuery'],
+  bot: BotInstance,
+  args: string[],
+  group: Group,
+  user: User,
+): Promise {
+  const promptId = parsePositiveInt(args[0]);
+  const amount = parsePositiveInt(args[1]);
+  if (promptId === null || amount === null) {
+    await ctx.answerCallbackQuery({ text: STALE_TEXT });
+    return;
+  }
+
+  const lookup = lookupPromptForCallback(promptId, group.id, user.id);
+  if (!lookup.ok) {
+    await ctx.answerCallbackQuery({ text: lookup.reason === 'stale' ? STALE_TEXT : FOREIGN_TEXT });
+    return;
+  }
+
+  const { prompt } = lookup;
+  const result = await applyBudgetPrompt(prompt, amount, prompt.currency);
+  if (result === 'already_handled') {
+    await ctx.answerCallbackQuery({ text: STALE_TEXT });
+    return;
+  }
+  if (result === 'failed') {
+    await ctx.answerCallbackQuery({ text: '❌ Не удалось установить бюджет' });
+    return;
+  }
+  await ctx.answerCallbackQuery({
+    text: `✅ Бюджет установлен: ${formatAmount(amount, prompt.currency)}`,
+  });
+  await removeButtonMessage(ctx, bot);
+}
+
+async function handleSkip(
+  ctx: Ctx['CallbackQuery'],
+  bot: BotInstance,
+  args: string[],
+  group: Group,
+  user: User,
+): Promise {
+  const promptId = parsePositiveInt(args[0]);
+  const lookup = promptId === null ? null : lookupPromptForCallback(promptId, group.id, user.id);
+  if (!lookup?.ok) {
+    await ctx.answerCallbackQuery({
+      text: lookup?.reason === 'foreign' ? FOREIGN_TEXT : STALE_TEXT,
+    });
+    return;
+  }
+  if (!skipBudgetPrompt(lookup.prompt)) {
+    await ctx.answerCallbackQuery({ text: STALE_TEXT });
+    return;
+  }
+  await ctx.answerCallbackQuery({ text: '⏭️ Пропущено' });
+  await removeButtonMessage(ctx, bot);
+}
+
+/** Route budget:psuggest / budget:pskip / budget:view. `args` excludes the sub-action. */
+export async function handleBudgetPromptCallback(
+  ctx: Ctx['CallbackQuery'],
+  bot: BotInstance,
+  action: BudgetPromptAction,
+  args: string[],
+  group: Group,
+  user: User,
+): Promise {
+  switch (action) {
+    case 'psuggest':
+      await handleSuggestion(ctx, bot, args, group, user);
+      return;
+    case 'pskip':
+      await handleSkip(ctx, bot, args, group, user);
+      return;
+    case 'view':
+      await ctx.answerCallbackQuery();
+      await sendBudgetView(group);
+      return;
+  }
+}
diff --git a/src/bot/handlers/callback.handler.test.ts b/src/bot/handlers/callback.handler.test.ts
index e9cc53f8..a18a56d0 100644
--- a/src/bot/handlers/callback.handler.test.ts
+++ b/src/bot/handlers/callback.handler.test.ts
@@ -117,8 +117,45 @@ const connectMocks = {
 };
 mock.module('../commands/connect', () => connectMocks);
 
+const sendBudgetViewMock = mock((_group: unknown) => Promise.resolve());
 mock.module('../commands/budget', () => ({
   normalizeCurrency: (s: string) => s.toUpperCase(),
+  sendBudgetView: sendBudgetViewMock,
+}));
+
+// ─── Smart budget prompt service ──────────────────────────────────────────────
+interface PromptStub {
+  id: number;
+  group_id: number;
+  user_id: number;
+  category: string;
+  currency: 'EUR';
+}
+const promptStub: PromptStub = {
+  id: 5,
+  group_id: 1,
+  user_id: 10,
+  category: 'Food',
+  currency: 'EUR',
+};
+type LookupResult = { ok: true; prompt: PromptStub } | { ok: false; reason: 'stale' | 'foreign' };
+const lookupPromptMock = mock(
+  (_id: number, _groupId: number, _userId: number): LookupResult => ({
+    ok: true,
+    prompt: promptStub,
+  }),
+);
+const applyPromptMock = mock(
+  (_prompt: PromptStub, _amount: number, _currency: string): Promise =>
+    Promise.resolve('applied'),
+);
+const skipPromptMock = mock((_prompt: PromptStub) => true);
+const sendBudgetPromptMock = mock((_params: unknown) => Promise.resolve());
+mock.module('../services/budget-prompt', () => ({
+  sendBudgetPrompt: sendBudgetPromptMock,
+  lookupPromptForCallback: lookupPromptMock,
+  applyBudgetPrompt: applyPromptMock,
+  skipBudgetPrompt: skipPromptMock,
 }));
 
 const devMock = mock(() => Promise.resolve());
@@ -165,7 +202,6 @@ mock.module('../services/sheet-errors', () => ({
 }));
 
 mock.module('../keyboards', () => ({
-  createBudgetPromptKeyboard: mock(() => ({ inline_keyboard: [] })),
   createCategoriesListKeyboard: mock(() => ({ inline_keyboard: [] })),
   createCategoryConfirmKeyboard: mock(() => ({ inline_keyboard: [] })),
 }));
@@ -262,6 +298,11 @@ const resetables: ReturnType[] = [
   queueCategoryBudgetPromptMock,
   showNextPendingCategoryStepMock,
   takeQueuedCategoryBudgetPromptsMock,
+  sendBudgetViewMock,
+  lookupPromptMock,
+  applyPromptMock,
+  skipPromptMock,
+  sendBudgetPromptMock,
   devMock,
   mockMerchantRules.updateStatus,
   mockGroups.findByTelegramGroupId,
@@ -299,6 +340,9 @@ afterEach(() => {
   showNextPendingCategoryStepMock.mockResolvedValue(true);
   takeQueuedCategoryBudgetPromptsMock.mockReturnValue([]);
   saveExpenseBatchMock.mockResolvedValue(undefined);
+  lookupPromptMock.mockImplementation(() => ({ ok: true, prompt: promptStub }));
+  applyPromptMock.mockImplementation(() => Promise.resolve('applied'));
+  skipPromptMock.mockImplementation(() => true);
 });
 
 // ─────────────────────────────────────────────────────────────────────────────
@@ -652,6 +696,139 @@ describe('handleCallbackQuery — routing table', () => {
         }),
       );
     });
+
+    describe('smart budget prompt buttons', () => {
+      test('budget:psuggest applies the amount to the prompt found by numeric id', async () => {
+        const ctx = fakeCallbackCtx('budget:psuggest:5:150');
+        const bot = fakeBot();
+        await handleCallbackQuery(ctx as never, bot as never);
+
+        expect(lookupPromptMock).toHaveBeenCalledWith(5, 1, 10);
+        expect(applyPromptMock).toHaveBeenCalledWith(promptStub, 150, 'EUR');
+        expect(ctx.answerCallbackQuery).toHaveBeenCalledWith(
+          expect.objectContaining({ text: expect.stringContaining('Бюджет установлен') }),
+        );
+        expect(bot.api.deleteMessage).toHaveBeenCalledTimes(1);
+      });
+
+      test('a stale prompt id does not mutate anything', async () => {
+        lookupPromptMock.mockReturnValueOnce({ ok: false, reason: 'stale' });
+        const ctx = fakeCallbackCtx('budget:psuggest:5:150');
+        const bot = fakeBot();
+        await handleCallbackQuery(ctx as never, bot as never);
+
+        expect(applyPromptMock).not.toHaveBeenCalled();
+        expect(setBudgetMock).not.toHaveBeenCalled();
+        expect(bot.api.deleteMessage).not.toHaveBeenCalled();
+        expect(ctx.answerCallbackQuery).toHaveBeenCalledWith(
+          expect.objectContaining({ text: expect.stringContaining('устарел') }),
+        );
+      });
+
+      test('a prompt owned by another member is rejected', async () => {
+        lookupPromptMock.mockReturnValueOnce({ ok: false, reason: 'foreign' });
+        const ctx = fakeCallbackCtx('budget:psuggest:5:150');
+        await handleCallbackQuery(ctx as never, fakeBot() as never);
+
+        expect(applyPromptMock).not.toHaveBeenCalled();
+        expect(ctx.answerCallbackQuery).toHaveBeenCalledWith(
+          expect.objectContaining({ text: expect.stringContaining('другим участником') }),
+        );
+      });
+
+      test('an already handled prompt (double tap) keeps the message and reports stale', async () => {
+        applyPromptMock.mockResolvedValueOnce('already_handled');
+        const ctx = fakeCallbackCtx('budget:psuggest:5:150');
+        const bot = fakeBot();
+        await handleCallbackQuery(ctx as never, bot as never);
+
+        expect(bot.api.deleteMessage).not.toHaveBeenCalled();
+        expect(ctx.answerCallbackQuery).toHaveBeenCalledWith(
+          expect.objectContaining({ text: expect.stringContaining('уже обработан') }),
+        );
+      });
+
+      test('a failed budget write is reported and the message stays', async () => {
+        applyPromptMock.mockResolvedValueOnce('failed');
+        const ctx = fakeCallbackCtx('budget:psuggest:5:150');
+        const bot = fakeBot();
+        await handleCallbackQuery(ctx as never, bot as never);
+
+        expect(bot.api.deleteMessage).not.toHaveBeenCalled();
+        expect(ctx.answerCallbackQuery).toHaveBeenCalledWith(
+          expect.objectContaining({ text: expect.stringContaining('Не удалось') }),
+        );
+      });
+
+      test.each([
+        'budget:psuggest:abc:150',
+        'budget:psuggest:5:0',
+        'budget:psuggest:5',
+      ])('malformed "%s" is treated as stale', async (data) => {
+        const ctx = fakeCallbackCtx(data);
+        await handleCallbackQuery(ctx as never, fakeBot() as never);
+        expect(applyPromptMock).not.toHaveBeenCalled();
+        expect(lookupPromptMock).not.toHaveBeenCalled();
+        expect(ctx.answerCallbackQuery).toHaveBeenCalledTimes(1);
+      });
+
+      test('budget:pskip retires the prompt and removes the message', async () => {
+        const ctx = fakeCallbackCtx('budget:pskip:5');
+        const bot = fakeBot();
+        await handleCallbackQuery(ctx as never, bot as never);
+
+        expect(skipPromptMock).toHaveBeenCalledWith(promptStub);
+        expect(setBudgetMock).not.toHaveBeenCalled();
+        expect(bot.api.deleteMessage).toHaveBeenCalledTimes(1);
+      });
+
+      test('budget:pskip on a stale prompt does nothing', async () => {
+        lookupPromptMock.mockReturnValueOnce({ ok: false, reason: 'stale' });
+        const ctx = fakeCallbackCtx('budget:pskip:5');
+        const bot = fakeBot();
+        await handleCallbackQuery(ctx as never, bot as never);
+
+        expect(skipPromptMock).not.toHaveBeenCalled();
+        expect(bot.api.deleteMessage).not.toHaveBeenCalled();
+      });
+
+      test('budget:view answers the button and sends the shared budget view', async () => {
+        const ctx = fakeCallbackCtx('budget:view');
+        await handleCallbackQuery(ctx as never, fakeBot() as never);
+
+        expect(ctx.answerCallbackQuery).toHaveBeenCalledTimes(1);
+        expect(sendBudgetViewMock).toHaveBeenCalledTimes(1);
+        expect(sendBudgetViewMock.mock.calls[0]?.[0]).toMatchObject({ id: 1 });
+      });
+
+      test('finishing the category wizard sends one persistent prompt per queued category', async () => {
+        const pending = {
+          id: 77,
+          user_id: 10,
+          message_id: 500,
+          parsed_amount: 100,
+          parsed_currency: 'EUR' as const,
+          detected_category: 'Животные',
+          comment: '',
+          status: 'pending_category' as const,
+          created_at: '2026-10-01 00:00:00',
+        };
+        getPendingCategoryExpenseMock.mockReturnValue(pending);
+        getPendingCategorySiblingsMock.mockReturnValue([pending]);
+        mockCategories.exists.mockReturnValue(false);
+        showNextPendingCategoryStepMock.mockResolvedValue(false);
+        takeQueuedCategoryBudgetPromptsMock.mockReturnValue(['Животные', 'Еда']);
+
+        await handleCallbackQuery(fakeCallbackCtx('category:add:77') as never, fakeBot() as never);
+
+        expect(sendBudgetPromptMock).toHaveBeenCalledTimes(2);
+        expect(sendBudgetPromptMock.mock.calls[0]?.[0]).toMatchObject({
+          userId: 10,
+          category: 'Животные',
+        });
+        expect(sendBudgetPromptMock.mock.calls[1]?.[0]).toMatchObject({ category: 'Еда' });
+      });
+    });
   });
 
   describe('receipt_item / receipt routing', () => {
diff --git a/src/bot/handlers/callback.handler.ts b/src/bot/handlers/callback.handler.ts
index edebc795..fd1e3ad5 100644
--- a/src/bot/handlers/callback.handler.ts
+++ b/src/bot/handlers/callback.handler.ts
@@ -43,7 +43,8 @@ import { handleDevCallback } from '../commands/dev';
 import { handleDisconnectCancel, handleDisconnectConfirm } from '../commands/disconnect';
 import { cancelPendingFeedback } from '../commands/feedback';
 import { handleSettingsCallback } from '../commands/settings';
-import { createBudgetPromptKeyboard, createCategoriesListKeyboard } from '../keyboards';
+import { createCategoriesListKeyboard } from '../keyboards';
+import { sendBudgetPrompt } from '../services/budget-prompt';
 import {
   getPendingCategoryExpense,
   getPendingCategorySiblings,
@@ -54,6 +55,7 @@ import {
 import { saveExpenseBatch, saveReceiptExpenses } from '../services/expense-saver';
 import { getSheetErrorMessage } from '../services/sheet-errors';
 import type { BotInstance, Ctx } from '../types';
+import { handleBudgetPromptCallback } from './budget-callbacks';
 import { trackMembership } from './message.handler';
 
 const logger = createLogger('callback.handler');
@@ -526,10 +528,7 @@ async function advanceCategoryWizard(
   // Category confirmation is complete. Only now surface deferred budget actions,
   // so the user never has several different actionable wizard messages at once.
   for (const category of takeQueuedCategoryBudgetPrompts(userId, sourceMessageId)) {
-    const keyboard = createBudgetPromptKeyboard(category, group.default_currency);
-    await sendMessage(`💰 Хочешь установить бюджет для категории "${category}"?`, {
-      reply_markup: keyboard,
-    });
+    await sendBudgetPrompt({ group, userId, category });
   }
 }
 
@@ -777,9 +776,15 @@ async function handleBudgetAction(
     return;
   }
 
-  const { group } = result;
+  const { group, user } = result;
 
   switch (subAction) {
+    case 'psuggest':
+    case 'pskip':
+    case 'view':
+      await handleBudgetPromptCallback(ctx, bot, subAction, params.slice(1), group, user);
+      break;
+
     case 'set': {
       // Set budget for category
       const amountStr = rest[0];
diff --git a/src/bot/handlers/message.handler.test.ts b/src/bot/handlers/message.handler.test.ts
index 076819b7..2f2ddc3d 100644
--- a/src/bot/handlers/message.handler.test.ts
+++ b/src/bot/handlers/message.handler.test.ts
@@ -237,6 +237,19 @@ mock.module('../../database', () => ({
   },
 }));
 
+const handleBudgetPromptTextMock = mock(
+  (_input: {
+    group: Group;
+    user: User;
+    text: string;
+    replyToMessageId: number | null;
+    messageThreadId: number | null;
+  }) => Promise.resolve(false),
+);
+mock.module('../services/budget-prompt', () => ({
+  handleBudgetPromptText: handleBudgetPromptTextMock,
+}));
+
 const showNextPendingCategoryStepMock = mock(() => Promise.resolve(true));
 mock.module('../services/category-wizard', () => ({
   showNextPendingCategoryStep: showNextPendingCategoryStepMock,
@@ -366,6 +379,7 @@ function resetAllMocks(): void {
   mockGroupMembers.upsert.mockReset();
   mockChatMessages.create.mockReset().mockImplementation(() => ({ id: 1 }));
   showNextPendingCategoryStepMock.mockReset().mockResolvedValue(true);
+  handleBudgetPromptTextMock.mockReset().mockResolvedValue(false);
   mockChatMessages.pruneOldMessagesIfNeeded.mockReset().mockReturnValue(0);
 
   logMock.error.mockClear();
@@ -766,6 +780,66 @@ describe('handleExpenseMessage — routing to other flows', () => {
   });
 });
 
+describe('handleExpenseMessage — budget prompt answers', () => {
+  beforeEach(() => {
+    resetAllMocks();
+    mockGroups.findByTelegramGroupId.mockReturnValue(makeGroup());
+    mockCategories.exists.mockReturnValue(true);
+  });
+
+  test('a consumed budget answer short-circuits expense parsing and bank edit replies', async () => {
+    handleBudgetPromptTextMock.mockResolvedValue(true);
+    const ctx = fakeMessageCtx('150', { replyToMessageId: 777, threadId: 12 });
+
+    const handled = await handleExpenseMessage(ctx, fakeBot());
+
+    expect(handled).toBe(true);
+    expect(handleBudgetPromptTextMock).toHaveBeenCalledTimes(1);
+    expect(handleBudgetPromptTextMock.mock.calls[0]?.[0]).toMatchObject({
+      text: '150',
+      replyToMessageId: 777,
+      messageThreadId: 12,
+      group: { id: 1 },
+      user: { id: 1 },
+    });
+    expect(handleBankEditReplyMock).not.toHaveBeenCalled();
+    expect(mockPendingExpenses.create).not.toHaveBeenCalled();
+    expect(saveExpenseBatchMock).not.toHaveBeenCalled();
+  });
+
+  test('plain messages pass null reply and topic ids', async () => {
+    await handleExpenseMessage(fakeMessageCtx('150'), fakeBot());
+    expect(handleBudgetPromptTextMock.mock.calls[0]?.[0]).toMatchObject({
+      replyToMessageId: null,
+      messageThreadId: null,
+    });
+  });
+
+  test('an unconsumed message continues to the normal expense flow', async () => {
+    handleBudgetPromptTextMock.mockResolvedValue(false);
+    const handled = await handleExpenseMessage(fakeMessageCtx('100 EUR groceries'), fakeBot());
+
+    expect(handled).toBe(true);
+    expect(saveExpenseBatchMock).toHaveBeenCalledTimes(1);
+  });
+
+  test('slash commands never reach the budget prompt handler', async () => {
+    await handleExpenseMessage(fakeMessageCtx('/budget'), fakeBot());
+    expect(handleBudgetPromptTextMock).not.toHaveBeenCalled();
+  });
+
+  test('the budget prompt is consulted before the bank edit reply flow', async () => {
+    handleBankEditReplyMock.mockResolvedValue(true);
+    handleBudgetPromptTextMock.mockResolvedValue(false);
+    await handleExpenseMessage(
+      fakeMessageCtx('Кафе — latte', { replyToMessageId: 555 }),
+      fakeBot(),
+    );
+    expect(handleBudgetPromptTextMock).toHaveBeenCalledTimes(1);
+    expect(handleBankEditReplyMock).toHaveBeenCalledTimes(1);
+  });
+});
+
 describe('handleExpenseMessage — multi-line batch', () => {
   beforeEach(() => {
     resetAllMocks();
diff --git a/src/bot/handlers/message.handler.ts b/src/bot/handlers/message.handler.ts
index 22f271dd..ed23ac22 100644
--- a/src/bot/handlers/message.handler.ts
+++ b/src/bot/handlers/message.handler.ts
@@ -18,6 +18,7 @@ import { createLogger } from '../../utils/logger.ts';
 import { maybeSmartAdvice } from '../commands/ask';
 import { consumePendingDesignEdit, getPipelineInstance } from '../commands/dev';
 import { consumePendingFeedback, submitFeedback } from '../commands/feedback';
+import { handleBudgetPromptText } from '../services/budget-prompt';
 import { showNextPendingCategoryStep } from '../services/category-wizard';
 import { saveExpenseBatch, saveReceiptExpenses } from '../services/expense-saver';
 import { getSheetErrorMessage } from '../services/sheet-errors';
@@ -259,8 +260,21 @@ export async function handleExpenseMessage(
     return true;
   }
 
-  // Bank transaction edit flow — route replies to pending edit transactions
   const replyToMessageId = ctx.update?.message?.reply_to_message?.message_id;
+
+  // Budget prompt answer — only a strict plain amount, or a reply to a prompt message
+  if (text && !text.startsWith('/')) {
+    const consumed = await handleBudgetPromptText({
+      group,
+      user,
+      text,
+      replyToMessageId: replyToMessageId ?? null,
+      messageThreadId: messageThreadId ?? null,
+    });
+    if (consumed) return true;
+  }
+
+  // Bank transaction edit flow — route replies to pending edit transactions
   if (replyToMessageId && text) {
     const { handleBankEditReply } = await import('../commands/bank');
     const handled = await handleBankEditReply(ctx, telegramGroupId, text, replyToMessageId);
diff --git a/src/bot/keyboards.test.ts b/src/bot/keyboards.test.ts
index 3606d3cf..1d5ad651 100644
--- a/src/bot/keyboards.test.ts
+++ b/src/bot/keyboards.test.ts
@@ -3,7 +3,8 @@ import { describe, expect, it } from 'bun:test';
 import type { InlineKeyboard } from 'gramio';
 import {
   createAddCategoryWithBudgetKeyboard,
-  createBudgetPromptKeyboard,
+  createBudgetSuggestionKeyboard,
+  createBudgetViewKeyboard,
   createBulkEditKeyboard,
   createCategoriesListKeyboard,
   createCategoryConfirmKeyboard,
@@ -199,48 +200,48 @@ describe('createConfirmKeyboard', () => {
   });
 });
 
-describe('createBudgetPromptKeyboard', () => {
-  it('has set budget and skip buttons', () => {
-    const kb = createBudgetPromptKeyboard('Food');
+describe('createBudgetSuggestionKeyboard', () => {
+  it('has one button per suggested amount carrying the numeric prompt id', () => {
+    const kb = createBudgetSuggestionKeyboard(42, [100, 250], 'EUR');
     const data = allButtons(kb).map((b) => b.callback_data);
-    expect(data.some((d) => d?.startsWith('budget:set:'))).toBe(true);
-    expect(data.some((d) => d?.startsWith('budget:skip:'))).toBe(true);
+    expect(data).toContain('budget:psuggest:42:100');
+    expect(data).toContain('budget:psuggest:42:250');
   });
 
-  it('callback_data includes category name', () => {
-    const kb = createBudgetPromptKeyboard('Transport');
+  it('always has a skip button bound to the prompt id', () => {
+    const kb = createBudgetSuggestionKeyboard(42, [], 'EUR');
     const data = allButtons(kb).map((b) => b.callback_data);
-    expect(data.some((d) => d?.includes('Transport'))).toBe(true);
+    expect(data).toEqual(['budget:pskip:42']);
   });
 
-  it('EUR currency shows € symbol in button text', () => {
-    const kb = createBudgetPromptKeyboard('Food', 'EUR');
-    const texts = allButtons(kb).map((b) => b.text);
-    expect(texts.some((t) => t.includes('€'))).toBe(true);
+  it('never puts the category name into callback data', () => {
+    const kb = createBudgetSuggestionKeyboard(7, [300], 'EUR');
+    for (const button of allButtons(kb)) {
+      expect(button.callback_data).toMatch(/^budget:p(suggest|skip):\d+(:\d+)?$/);
+    }
   });
 
-  it('USD currency shows $ symbol in button text', () => {
-    const kb = createBudgetPromptKeyboard('Food', 'USD');
-    const texts = allButtons(kb).map((b) => b.text);
+  it('shows amounts with the currency symbol', () => {
+    const texts = allButtons(createBudgetSuggestionKeyboard(1, [100], 'USD')).map((b) => b.text);
     expect(texts.some((t) => t.includes('$'))).toBe(true);
+    const rsd = allButtons(createBudgetSuggestionKeyboard(1, [100], 'RSD')).map((b) => b.text);
+    expect(rsd.some((t) => t.includes('RSD'))).toBe(true);
   });
 
-  it('RUB currency shows ₽ symbol in button text', () => {
-    const kb = createBudgetPromptKeyboard('Food', 'RUB');
-    const texts = allButtons(kb).map((b) => b.text);
-    expect(texts.some((t) => t.includes('₽'))).toBe(true);
-  });
-
-  it('unknown currency falls back to currency code in button text', () => {
-    const kb = createBudgetPromptKeyboard('Food', 'RSD');
-    const texts = allButtons(kb).map((b) => b.text);
-    expect(texts.some((t) => t.includes('RSD'))).toBe(true);
+  it('keeps every callback_data within Telegram 64-byte limit', () => {
+    const kb = createBudgetSuggestionKeyboard(2147483647, [999999999999], 'EUR');
+    for (const button of allButtons(kb)) {
+      expect(Buffer.byteLength(button.callback_data ?? '')).toBeLessThanOrEqual(64);
+    }
   });
+});
 
-  it('default currency is EUR when not specified', () => {
-    const kb = createBudgetPromptKeyboard('Food');
-    const texts = allButtons(kb).map((b) => b.text);
-    expect(texts.some((t) => t.includes('€'))).toBe(true);
+describe('createBudgetViewKeyboard', () => {
+  it('has a single show-budget button', () => {
+    const buttons = allButtons(createBudgetViewKeyboard());
+    expect(buttons).toHaveLength(1);
+    expect(buttons[0]?.text).toBe('📊 Показать бюджет');
+    expect(buttons[0]?.callback_data).toBe('budget:view');
   });
 });
 
diff --git a/src/bot/keyboards.ts b/src/bot/keyboards.ts
index c690937a..0ad9f6d2 100644
--- a/src/bot/keyboards.ts
+++ b/src/bot/keyboards.ts
@@ -6,6 +6,7 @@ import {
   KEYBOARD_TEXTS,
   SUPPORTED_CURRENCIES,
 } from '../config/constants';
+import { formatAmount } from '../services/currency/converter';
 
 /**
  * Create currency set selection keyboard (Step 1)
@@ -178,27 +179,32 @@ export function createConfirmKeyboard(action: string): InlineKeyboard {
 }
 
 /**
- * Create budget setup prompt keyboard
+ * Create budget setup prompt keyboard: one button per suggested amount plus skip.
+ * Callbacks carry the numeric prompt id only, so a stale button can never touch another prompt.
  */
-export function createBudgetPromptKeyboard(
-  category: string,
-  defaultCurrency: string = BASE_CURRENCY,
+export function createBudgetSuggestionKeyboard(
+  promptId: number,
+  amounts: number[],
+  currency: string = BASE_CURRENCY,
 ): InlineKeyboard {
   const keyboard = new InlineKeyboard();
 
-  const currencySymbol = getCurrencySymbol(defaultCurrency);
-
-  keyboard
-    .text(
-      `💰 Установить бюджет ${currencySymbol}100`,
-      `budget:set:${category}:100:${defaultCurrency}`,
-    )
-    .row()
-    .text('⏭️ Пропустить', `budget:skip:${category}`);
+  if (amounts.length > 0) {
+    for (const amount of amounts) {
+      keyboard.text(formatAmount(amount, currency), `budget:psuggest:${promptId}:${amount}`);
+    }
+    keyboard.row();
+  }
+  keyboard.text('⏭️ Пропустить', `budget:pskip:${promptId}`);
 
   return keyboard;
 }
 
+/** "Show budget" action attached to every successful budget-set confirmation. */
+export function createBudgetViewKeyboard(): InlineKeyboard {
+  return new InlineKeyboard().text('📊 Показать бюджет', 'budget:view');
+}
+
 /**
  * Create keyboard for adding new category with budget
  */
diff --git a/src/bot/services/budget-prompt.test.ts b/src/bot/services/budget-prompt.test.ts
new file mode 100644
index 00000000..ca5fb33d
--- /dev/null
+++ b/src/bot/services/budget-prompt.test.ts
@@ -0,0 +1,302 @@
+// Tests for the persistent budget prompt service: sending, plain input, reply disambiguation, claiming
+
+import { mock } from 'bun:test';
+// ── Real in-memory persistence for prompts, stubs for everything else ──
+import { BudgetPromptRepository } from '../../database/repositories/budget-prompt.repository';
+import { GroupRepository } from '../../database/repositories/group.repository';
+import { UserRepository } from '../../database/repositories/user.repository';
+import { createTestDb } from '../../test-utils/db';
+import { createMockLogger } from '../../test-utils/mocks/logger';
+
+const db = createTestDb();
+const prompts = new BudgetPromptRepository(db);
+const groupRepo = new GroupRepository(db);
+const userRepo = new UserRepository(db);
+
+const groupsStub = { findById: mock((_id: number) => ({ id: 1, google_refresh_token: 'tok' })) };
+const budgetsStub = {
+  getBudgetForMonth: mock(() => null),
+  getAllBudgetsForMonth: mock((): unknown[] => []),
+};
+const expensesStub = {
+  getMonthlyHistoryByCategory: mock((): unknown[] => []),
+};
+
+mock.module('../../database', () => ({
+  database: {
+    budgetPrompts: prompts,
+    groups: groupsStub,
+    budgets: budgetsStub,
+    expenses: expensesStub,
+  },
+}));
+
+const logMock = createMockLogger();
+mock.module('../../utils/logger.ts', () => ({ createLogger: () => logMock, logger: logMock }));
+
+let nextMessageId = 1000;
+const sendMessageMock = mock(
+  (_text: string, _options?: { reply_markup?: unknown }): Promise<{ message_id: number } | null> =>
+    Promise.resolve({ message_id: nextMessageId++ }),
+);
+mock.module('../../services/bank/telegram-sender', () => ({ sendMessage: sendMessageMock }));
+
+const setBudgetMock = mock(
+  (_params: {
+    groupId: number;
+    category: string;
+    month: string;
+    amount: number;
+    currency: string;
+  }) => Promise.resolve({ sheetsSynced: true }),
+);
+mock.module('../../services/budget-manager', () => ({
+  getBudgetManager: () => ({ set: setBudgetMock }),
+}));
+
+import { beforeEach, describe, expect, test } from 'bun:test';
+import type { Group, User } from '../../database/types';
+
+const {
+  applyBudgetPrompt,
+  handleBudgetPromptText,
+  lookupPromptForCallback,
+  sendBudgetPrompt,
+  skipBudgetPrompt,
+} = await import('./budget-prompt');
+
+let group: Group;
+let user: User;
+let otherUser: User;
+
+function keyboardData(options: { reply_markup?: unknown } | undefined): string[] {
+  const json = (
+    options?.reply_markup as { toJSON: () => { inline_keyboard: unknown[][] } }
+  ).toJSON();
+  return (json.inline_keyboard.flat() as Array<{ callback_data?: string }>).map(
+    (b) => b.callback_data ?? '',
+  );
+}
+
+async function openPrompt(category: string, forUser: User = user): Promise {
+  await sendBudgetPrompt({ group, userId: forUser.id, category });
+  const all = prompts.findActiveForUser(group.id, forUser.id, null);
+  const created = all.find((p) => p.category === category);
+  if (!created) throw new Error('prompt was not created');
+  return created.id;
+}
+
+function input(
+  text: string,
+  extra: { reply?: number | null; thread?: number | null; who?: User } = {},
+) {
+  return {
+    group,
+    user: extra.who ?? user,
+    text,
+    replyToMessageId: extra.reply ?? null,
+    messageThreadId: extra.thread ?? null,
+  };
+}
+
+beforeEach(() => {
+  db.exec('DELETE FROM budget_prompts; DELETE FROM users; DELETE FROM groups;');
+  group = { ...groupRepo.create({ telegram_group_id: -100500 }), default_currency: 'EUR' };
+  user = userRepo.create({ telegram_id: 1, group_id: group.id });
+  otherUser = userRepo.create({ telegram_id: 2, group_id: group.id });
+  nextMessageId = 1000;
+  sendMessageMock.mockClear();
+  setBudgetMock.mockClear();
+  setBudgetMock.mockImplementation(() => Promise.resolve({ sheetsSynced: true }));
+  budgetsStub.getBudgetForMonth.mockReturnValue(null);
+  budgetsStub.getAllBudgetsForMonth.mockReturnValue([]);
+  expensesStub.getMonthlyHistoryByCategory.mockReturnValue([]);
+  logMock.error.mockClear();
+  logMock.warn.mockClear();
+});
+
+describe('sendBudgetPrompt', () => {
+  test('persists the prompt, binds the sent message id and uses its numeric id in callbacks', async () => {
+    expensesStub.getMonthlyHistoryByCategory.mockReturnValue([
+      { category: 'Food', month: '2026-09', monthly_total: 200, tx_count: 4 },
+    ]);
+    await sendBudgetPrompt({ group, userId: user.id, category: 'Food' });
+
+    const [created] = prompts.findActiveForUser(group.id, user.id, null);
+    expect(created?.telegram_message_id).toBe(1000);
+    const [text, options] = sendMessageMock.mock.calls[0] ?? [];
+    expect(text).toContain('Food');
+    expect(text).toContain('траты в прошлом месяце');
+    expect(keyboardData(options)).toContain(`budget:psuggest:${created?.id}:200`);
+    expect(keyboardData(options)).toContain(`budget:pskip:${created?.id}`);
+  });
+
+  test('without any history it offers no amounts and does not claim a recommendation', async () => {
+    await sendBudgetPrompt({ group, userId: user.id, category: 'Gym' });
+    const [text, options] = sendMessageMock.mock.calls[0] ?? [];
+    expect(text).toContain('нет данных');
+    expect(text).not.toContain('Варианты по данным');
+    expect(keyboardData(options).filter((d) => d.startsWith('budget:psuggest'))).toEqual([]);
+  });
+
+  test('escapes the category in HTML', async () => {
+    await sendBudgetPrompt({ group, userId: user.id, category: 'R&D ' });
+    expect(sendMessageMock.mock.calls[0]?.[0]).toContain('R&D <i>');
+  });
+
+  test('a repeated prompt for the same category retires the old one', async () => {
+    const first = await openPrompt('Food');
+    const second = await openPrompt('Food');
+    expect(prompts.findById(first)?.status).toBe('skipped');
+    expect(prompts.findById(second)?.status).toBe('active');
+  });
+
+  test('a failed send leaves no active prompt behind', async () => {
+    sendMessageMock.mockResolvedValueOnce(null);
+    await sendBudgetPrompt({ group, userId: user.id, category: 'Food' });
+    expect(prompts.findActiveForUser(group.id, user.id, null)).toEqual([]);
+  });
+});
+
+describe('handleBudgetPromptText', () => {
+  test('one active prompt: a plain amount sets that category', async () => {
+    const id = await openPrompt('Food');
+    sendMessageMock.mockClear();
+
+    expect(await handleBudgetPromptText(input('150'))).toBe(true);
+
+    expect(setBudgetMock).toHaveBeenCalledTimes(1);
+    expect(setBudgetMock.mock.calls[0]?.[0]).toMatchObject({
+      groupId: group.id,
+      category: 'Food',
+      amount: 150,
+      currency: 'EUR',
+    });
+    expect(prompts.findById(id)?.status).toBe('used');
+    const [text, options] = sendMessageMock.mock.calls[0] ?? [];
+    expect(text).toContain('Бюджет установлен');
+    expect(keyboardData(options)).toContain('budget:view');
+  });
+
+  test('an explicit currency overrides the prompt currency', async () => {
+    await openPrompt('Food');
+    await handleBudgetPromptText(input('1 500 RSD'));
+    expect(setBudgetMock.mock.calls[0]?.[0]).toMatchObject({ amount: 1500, currency: 'RSD' });
+  });
+
+  test('prose is never intercepted', async () => {
+    await openPrompt('Food');
+    expect(await handleBudgetPromptText(input('поставь бюджет на еду 150'))).toBe(false);
+    expect(await handleBudgetPromptText(input('150 кофе'))).toBe(false);
+    expect(setBudgetMock).not.toHaveBeenCalled();
+  });
+
+  test('several active prompts: a plain amount is NOT applied and a hint is sent', async () => {
+    const food = await openPrompt('Food');
+    const rent = await openPrompt('Rent');
+    sendMessageMock.mockClear();
+
+    expect(await handleBudgetPromptText(input('150'))).toBe(true);
+
+    expect(setBudgetMock).not.toHaveBeenCalled();
+    expect(prompts.findById(food)?.status).toBe('active');
+    expect(prompts.findById(rent)?.status).toBe('active');
+    const text = sendMessageMock.mock.calls[0]?.[0] ?? '';
+    expect(text).toContain('Food');
+    expect(text).toContain('Rent');
+    expect(text).toContain('реплаем');
+  });
+
+  test('several active prompts: replying to one prompt selects exactly that category', async () => {
+    await openPrompt('Food');
+    const rentId = await openPrompt('Rent');
+    const rentMessage = prompts.findById(rentId)?.telegram_message_id ?? -1;
+
+    expect(await handleBudgetPromptText(input('900', { reply: rentMessage }))).toBe(true);
+
+    expect(setBudgetMock).toHaveBeenCalledTimes(1);
+    expect(setBudgetMock.mock.calls[0]?.[0]).toMatchObject({ category: 'Rent', amount: 900 });
+    expect(prompts.findById(rentId)?.status).toBe('used');
+    expect(prompts.findActiveForUser(group.id, user.id, null).map((p) => p.category)).toEqual([
+      'Food',
+    ]);
+  });
+
+  test('a reply to an unrelated message is left for normal handling even with one prompt', async () => {
+    await openPrompt('Food');
+    expect(await handleBudgetPromptText(input('150', { reply: 424242 }))).toBe(false);
+    expect(setBudgetMock).not.toHaveBeenCalled();
+  });
+
+  test('no active prompts: nothing is intercepted', async () => {
+    expect(await handleBudgetPromptText(input('150'))).toBe(false);
+  });
+
+  test('prompts of another user or another topic are invisible', async () => {
+    await openPrompt('Food', otherUser);
+    expect(await handleBudgetPromptText(input('150'))).toBe(false);
+    await openPrompt('Rent');
+    expect(await handleBudgetPromptText(input('150', { thread: 9 }))).toBe(false);
+    expect(setBudgetMock).not.toHaveBeenCalled();
+  });
+
+  test('a failing budget write reopens the prompt and tells the user', async () => {
+    const id = await openPrompt('Food');
+    setBudgetMock.mockRejectedValueOnce(new Error('db down'));
+    sendMessageMock.mockClear();
+
+    expect(await handleBudgetPromptText(input('150'))).toBe(true);
+
+    expect(prompts.findById(id)?.status).toBe('active');
+    expect(logMock.error).toHaveBeenCalled();
+    expect(sendMessageMock.mock.calls[0]?.[0]).toContain('Не удалось');
+  });
+});
+
+describe('prompt lookup, apply and skip', () => {
+  test('lookup accepts the owner and rejects stale and foreign prompts', async () => {
+    const id = await openPrompt('Food');
+    expect(lookupPromptForCallback(id, group.id, user.id).ok).toBe(true);
+    expect(lookupPromptForCallback(id, group.id, otherUser.id)).toEqual({
+      ok: false,
+      reason: 'foreign',
+    });
+    expect(lookupPromptForCallback(id + 99, group.id, user.id)).toEqual({
+      ok: false,
+      reason: 'stale',
+    });
+    expect(lookupPromptForCallback(id, group.id + 1, user.id)).toEqual({
+      ok: false,
+      reason: 'stale',
+    });
+  });
+
+  test('a used prompt is stale and cannot be applied twice', async () => {
+    const id = await openPrompt('Food');
+    const lookup = lookupPromptForCallback(id, group.id, user.id);
+    if (!lookup.ok) throw new Error('expected prompt');
+
+    expect(await applyBudgetPrompt(lookup.prompt, 100, 'EUR')).toBe('applied');
+    expect(await applyBudgetPrompt(lookup.prompt, 200, 'EUR')).toBe('already_handled');
+    expect(setBudgetMock).toHaveBeenCalledTimes(1);
+    expect(lookupPromptForCallback(id, group.id, user.id)).toEqual({ ok: false, reason: 'stale' });
+  });
+
+  test('a stale button for an old prompt does not touch the newer prompt of the category', async () => {
+    const oldId = await openPrompt('Food');
+    const newId = await openPrompt('Food');
+    expect(lookupPromptForCallback(oldId, group.id, user.id).ok).toBe(false);
+    expect(lookupPromptForCallback(newId, group.id, user.id).ok).toBe(true);
+    expect(setBudgetMock).not.toHaveBeenCalled();
+  });
+
+  test('skip retires the prompt without writing a budget', async () => {
+    const id = await openPrompt('Food');
+    const lookup = lookupPromptForCallback(id, group.id, user.id);
+    if (!lookup.ok) throw new Error('expected prompt');
+    expect(skipBudgetPrompt(lookup.prompt)).toBe(true);
+    expect(skipBudgetPrompt(lookup.prompt)).toBe(false);
+    expect(setBudgetMock).not.toHaveBeenCalled();
+    expect(prompts.findById(id)?.status).toBe('skipped');
+  });
+});
diff --git a/src/bot/services/budget-prompt.ts b/src/bot/services/budget-prompt.ts
new file mode 100644
index 00000000..13b55c5f
--- /dev/null
+++ b/src/bot/services/budget-prompt.ts
@@ -0,0 +1,200 @@
+// Persistent smart budget prompts: send with suggestions, apply by button or typed amount/reply
+
+import { format } from 'date-fns';
+import type { CurrencyCode } from '../../config/constants';
+import { database } from '../../database';
+import type { BudgetPrompt, Group, User } from '../../database/types';
+import { sendMessage } from '../../services/bank/telegram-sender';
+import { getBudgetManager } from '../../services/budget-manager';
+import { type BudgetSuggestions, suggestBudgetAmounts } from '../../services/budget-suggestions';
+import { parseBudgetInputAmount } from '../../services/currency/budget-amount-parser';
+import { formatAmount } from '../../services/currency/converter';
+import { chatStorage } from '../../utils/chat-context';
+import { escapeHtml } from '../../utils/html';
+import { createLogger } from '../../utils/logger.ts';
+import { formatMonthYearRu } from '../../utils/ru-date';
+import { formatBudgetSetMessage } from '../commands/budget-view';
+import { createBudgetSuggestionKeyboard, createBudgetViewKeyboard } from '../keyboards';
+
+const logger = createLogger('budget-prompt');
+
+const INPUT_HINT =
+  'Выбери вариант кнопкой или напиши свою сумму сообщением, например 150 или 150 EUR. ' +
+  'Если открыто несколько запросов — ответь реплаем на нужное сообщение.';
+
+export type PromptLookup =
+  | { ok: true; prompt: BudgetPrompt }
+  | { ok: false; reason: 'stale' | 'foreign' };
+
+export type ApplyResult = 'applied' | 'already_handled' | 'failed';
+
+export interface PromptTextInput {
+  group: Group;
+  user: User;
+  text: string;
+  replyToMessageId: number | null;
+  messageThreadId: number | null;
+}
+
+function formatPromptText(
+  category: string,
+  suggestions: BudgetSuggestions,
+  currency: CurrencyCode,
+  now: Date,
+): string {
+  const title = `💰 Бюджет для категории ${escapeHtml(category)} на ${formatMonthYearRu(now)}`;
+  if (suggestions.options.length === 0) {
+    return (
+      `${title}\n\nПока нет данных, чтобы предложить сумму: по этой категории нет ни бюджетов, ` +
+      'ни расходов за прошлые месяцы. Напиши лимит сообщением, например 150 или 150 EUR, или пропусти.'
+    );
+  }
+  const lines = suggestions.options.map(
+    (option) => `• ${formatAmount(option.amount, currency)} — ${option.reason}`,
+  );
+  return `${title}\n\nВарианты по данным:\n${lines.join('\n')}\n\n${INPUT_HINT}`;
+}
+
+/** Create a persistent prompt for a category and send it with data-driven suggestions. */
+export async function sendBudgetPrompt(params: {
+  group: Group;
+  userId: number;
+  category: string;
+}): Promise {
+  const { group, userId, category } = params;
+  const currency = group.default_currency;
+  const threadId = chatStorage.getStore()?.threadId ?? null;
+  const now = new Date();
+
+  database.budgetPrompts.supersedeActive(group.id, userId, category, threadId);
+  const prompt = database.budgetPrompts.create({
+    group_id: group.id,
+    user_id: userId,
+    category,
+    currency,
+    message_thread_id: threadId,
+  });
+
+  const suggestions = suggestBudgetAmounts(group.id, category, currency, now);
+  const keyboard = createBudgetSuggestionKeyboard(
+    prompt.id,
+    suggestions.options.map((option) => option.amount),
+    currency,
+  );
+  const sent = await sendMessage(formatPromptText(category, suggestions, currency, now), {
+    reply_markup: keyboard,
+  });
+
+  if (sent) {
+    database.budgetPrompts.bindMessage(prompt.id, sent.message_id);
+    return;
+  }
+  // The user never saw it, so it must not capture their next plain amount.
+  database.budgetPrompts.finish(prompt.id, 'skipped');
+}
+
+/** Resolve a button's prompt id for the pressing user; stale/foreign prompts are rejected. */
+export function lookupPromptForCallback(
+  promptId: number,
+  groupId: number,
+  userId: number,
+): PromptLookup {
+  const prompt = database.budgetPrompts.findActiveById(promptId);
+  if (!prompt || prompt.group_id !== groupId) return { ok: false, reason: 'stale' };
+  if (prompt.user_id !== userId) return { ok: false, reason: 'foreign' };
+  return { ok: true, prompt };
+}
+
+/** Atomically claim the prompt, write the budget through BudgetManager, confirm in chat. */
+export async function applyBudgetPrompt(
+  prompt: BudgetPrompt,
+  amount: number,
+  currency: CurrencyCode,
+): Promise {
+  if (!database.budgetPrompts.finish(prompt.id, 'used')) return 'already_handled';
+
+  try {
+    const result = await getBudgetManager().set({
+      groupId: prompt.group_id,
+      category: prompt.category,
+      month: format(new Date(), 'yyyy-MM'),
+      amount,
+      currency,
+    });
+    const group = database.groups.findById(prompt.group_id);
+    await sendMessage(
+      formatBudgetSetMessage({
+        category: prompt.category,
+        amount,
+        currency,
+        sheetsSynced: result.sheetsSynced,
+        sheetsConnected: Boolean(group?.google_refresh_token),
+      }),
+      { reply_markup: createBudgetViewKeyboard() },
+    );
+    return 'applied';
+  } catch (err) {
+    logger.error({ err, promptId: prompt.id }, '[BUDGET-PROMPT] Failed to set budget');
+    database.budgetPrompts.reopen(prompt.id);
+    return 'failed';
+  }
+}
+
+/** Retire the prompt without touching budgets. False when it was already handled. */
+export function skipBudgetPrompt(prompt: BudgetPrompt): boolean {
+  return database.budgetPrompts.finish(prompt.id, 'skipped');
+}
+
+type TextTarget =
+  | { kind: 'prompt'; prompt: BudgetPrompt }
+  | { kind: 'ambiguous'; prompts: BudgetPrompt[] }
+  | { kind: 'none' };
+
+function resolveTextTarget(input: PromptTextInput): TextTarget {
+  const { group, user, replyToMessageId, messageThreadId } = input;
+  if (replyToMessageId !== null) {
+    // A reply is an explicit address: it either names a prompt or the text is not for us.
+    const prompt = database.budgetPrompts.findActiveByMessage(
+      group.id,
+      user.id,
+      replyToMessageId,
+      messageThreadId,
+    );
+    return prompt ? { kind: 'prompt', prompt } : { kind: 'none' };
+  }
+  const prompts = database.budgetPrompts.findActiveForUser(group.id, user.id, messageThreadId);
+  const [only] = prompts;
+  if (!only) return { kind: 'none' };
+  return prompts.length === 1 ? { kind: 'prompt', prompt: only } : { kind: 'ambiguous', prompts };
+}
+
+async function sendAmbiguityHint(prompts: BudgetPrompt[]): Promise {
+  const names = prompts.map((prompt) => `«${escapeHtml(prompt.category)}»`).join(', ');
+  await sendMessage(
+    `У тебя открыто несколько запросов бюджета: ${names}. ` +
+      'Ответь реплаем на сообщение с нужной категорией, чтобы я не перепутал.',
+  );
+}
+
+/**
+ * Handle a plain amount or a reply to a prompt. Returns true when the message was consumed.
+ * Only a strict amount ("150", "150 eur", "1 500 RSD") is ever intercepted.
+ */
+export async function handleBudgetPromptText(input: PromptTextInput): Promise {
+  const parsed = parseBudgetInputAmount(input.text);
+  if (!parsed) return false;
+
+  const target = resolveTextTarget(input);
+  if (target.kind === 'none') return false;
+  if (target.kind === 'ambiguous') {
+    await sendAmbiguityHint(target.prompts);
+    return true;
+  }
+
+  const { prompt } = target;
+  const result = await applyBudgetPrompt(prompt, parsed.amount, parsed.currency ?? prompt.currency);
+  if (result === 'failed') {
+    await sendMessage('Не удалось установить бюджет. Попробуй ещё раз или используй /budget set.');
+  }
+  return true;
+}
diff --git a/src/database/index.ts b/src/database/index.ts
index 3f1038f9..dcf1f12c 100644
--- a/src/database/index.ts
+++ b/src/database/index.ts
@@ -6,6 +6,7 @@ import { BankConnectionsRepository } from './repositories/bank-connections.repos
 import { BankCredentialsRepository } from './repositories/bank-credentials.repository';
 import { BankTransactionsRepository } from './repositories/bank-transactions.repository';
 import { type BudgetReadRepository, BudgetRepository } from './repositories/budget.repository';
+import { BudgetPromptRepository } from './repositories/budget-prompt.repository';
 import { CategoryRepository } from './repositories/category.repository';
 import { ChatMessageRepository } from './repositories/chat-message.repository';
 import { DevTaskRepository } from './repositories/dev-task.repository';
@@ -37,6 +38,7 @@ export class DatabaseService {
   public pendingExpenses: PendingExpenseRepository;
   public expenses: ExpenseRepository;
   public budgets: BudgetReadRepository;
+  public budgetPrompts: BudgetPromptRepository;
   private _budgetWriter: BudgetRepository;
   public chatMessages: ChatMessageRepository;
   public photoQueue: PhotoQueueRepository;
@@ -64,6 +66,7 @@ export class DatabaseService {
     this.expenses = new ExpenseRepository(this.db);
     this._budgetWriter = new BudgetRepository(this.db);
     this.budgets = this._budgetWriter;
+    this.budgetPrompts = new BudgetPromptRepository(this.db);
     _budgetWriterRef = this._budgetWriter;
     this.chatMessages = new ChatMessageRepository(this.db);
     this.photoQueue = new PhotoQueueRepository(this.db);
diff --git a/src/database/repositories/budget-prompt.repository.test.ts b/src/database/repositories/budget-prompt.repository.test.ts
new file mode 100644
index 00000000..92518e90
--- /dev/null
+++ b/src/database/repositories/budget-prompt.repository.test.ts
@@ -0,0 +1,132 @@
+// Tests for BudgetPromptRepository — persistence, group/user/topic scoping, status transitions
+
+import type { Database } from 'bun:sqlite';
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { clearTestDb, createTestDb } from '../../test-utils/db';
+import { BudgetPromptRepository } from './budget-prompt.repository';
+import { GroupRepository } from './group.repository';
+import { UserRepository } from './user.repository';
+
+let db: Database;
+let repo: BudgetPromptRepository;
+let groupId: number;
+let otherGroupId: number;
+let userId: number;
+let otherUserId: number;
+
+beforeAll(() => {
+  db = createTestDb();
+  repo = new BudgetPromptRepository(db);
+});
+
+afterAll(() => {
+  db.close();
+});
+
+beforeEach(() => {
+  clearTestDb(db);
+  const groups = new GroupRepository(db);
+  const users = new UserRepository(db);
+  groupId = groups.create({ telegram_group_id: -1001 }).id;
+  otherGroupId = groups.create({ telegram_group_id: -1002 }).id;
+  userId = users.create({ telegram_id: 1, group_id: groupId }).id;
+  otherUserId = users.create({ telegram_id: 2, group_id: groupId }).id;
+});
+
+function createPrompt(overrides: { category?: string; thread?: number | null } = {}) {
+  return repo.create({
+    group_id: groupId,
+    user_id: userId,
+    category: overrides.category ?? 'Food',
+    currency: 'EUR',
+    message_thread_id: overrides.thread ?? null,
+  });
+}
+
+describe('BudgetPromptRepository', () => {
+  test('create persists an active prompt without a message id', () => {
+    const prompt = createPrompt();
+    expect(prompt.id).toBeGreaterThan(0);
+    expect(prompt.status).toBe('active');
+    expect(prompt.telegram_message_id).toBeNull();
+    expect(prompt.category).toBe('Food');
+  });
+
+  test('bindMessage stores the Telegram message id', () => {
+    const prompt = createPrompt();
+    repo.bindMessage(prompt.id, 555);
+    expect(repo.findById(prompt.id)?.telegram_message_id).toBe(555);
+  });
+
+  test('findActiveForUser is scoped by group, user and topic', () => {
+    const general = createPrompt({ category: 'A' });
+    const topic = createPrompt({ category: 'B', thread: 7 });
+    repo.create({ group_id: otherGroupId, user_id: userId, category: 'C', currency: 'EUR' });
+    repo.create({ group_id: groupId, user_id: otherUserId, category: 'D', currency: 'EUR' });
+
+    expect(repo.findActiveForUser(groupId, userId, null).map((p) => p.id)).toEqual([general.id]);
+    expect(repo.findActiveForUser(groupId, userId, 7).map((p) => p.id)).toEqual([topic.id]);
+    expect(repo.findActiveForUser(groupId, userId, 8)).toEqual([]);
+  });
+
+  test('findActiveByMessage matches only the bound message', () => {
+    const first = createPrompt({ category: 'A' });
+    const second = createPrompt({ category: 'B' });
+    repo.bindMessage(first.id, 10);
+    repo.bindMessage(second.id, 11);
+
+    expect(repo.findActiveByMessage(groupId, userId, 11, null)?.id).toBe(second.id);
+    expect(repo.findActiveByMessage(groupId, userId, 99, null)).toBeNull();
+    expect(repo.findActiveByMessage(groupId, otherUserId, 11, null)).toBeNull();
+    expect(repo.findActiveByMessage(groupId, userId, 11, 7)).toBeNull();
+  });
+
+  test('finish moves the prompt out of the active set exactly once', () => {
+    const prompt = createPrompt();
+    expect(repo.finish(prompt.id, 'used')).toBe(true);
+    expect(repo.finish(prompt.id, 'skipped')).toBe(false);
+    expect(repo.findById(prompt.id)?.status).toBe('used');
+    expect(repo.findActiveForUser(groupId, userId, null)).toEqual([]);
+  });
+
+  test('findActiveById ignores finished prompts', () => {
+    const prompt = createPrompt();
+    expect(repo.findActiveById(prompt.id)?.id).toBe(prompt.id);
+    repo.finish(prompt.id, 'skipped');
+    expect(repo.findActiveById(prompt.id)).toBeNull();
+  });
+
+  test('expired prompts are not active', () => {
+    const prompt = createPrompt();
+    db.query("UPDATE budget_prompts SET created_at = datetime('now', '-8 days') WHERE id = ?").run(
+      prompt.id,
+    );
+    expect(repo.findActiveForUser(groupId, userId, null)).toEqual([]);
+    expect(repo.findActiveById(prompt.id)).toBeNull();
+  });
+
+  test('reopen restores a finished prompt', () => {
+    const prompt = createPrompt();
+    repo.finish(prompt.id, 'used');
+    repo.reopen(prompt.id);
+    expect(repo.findById(prompt.id)?.status).toBe('active');
+  });
+
+  test('supersedeActive skips older active prompts for the same category and scope', () => {
+    const old = createPrompt({ category: 'Food' });
+    const otherCategory = createPrompt({ category: 'Rent' });
+    const otherTopic = createPrompt({ category: 'Food', thread: 3 });
+
+    repo.supersedeActive(groupId, userId, 'Food', null);
+
+    expect(repo.findById(old.id)?.status).toBe('skipped');
+    expect(repo.findById(otherCategory.id)?.status).toBe('active');
+    expect(repo.findById(otherTopic.id)?.status).toBe('active');
+  });
+
+  test('prompts are removed with their group', () => {
+    createPrompt();
+    db.query('DELETE FROM groups WHERE id = ?').run(groupId);
+    expect(db.query('SELECT COUNT(*) as c FROM budget_prompts').get()).toEqual({ c: 0 });
+  });
+});
diff --git a/src/database/repositories/budget-prompt.repository.ts b/src/database/repositories/budget-prompt.repository.ts
new file mode 100644
index 00000000..1df9469b
--- /dev/null
+++ b/src/database/repositories/budget-prompt.repository.ts
@@ -0,0 +1,169 @@
+// Persistent budget-setup prompts (group/user/topic scoped) for the button and text/reply flows
+import type { Database } from 'bun:sqlite';
+import type { BudgetPrompt, BudgetPromptStatus, CreateBudgetPromptData } from '../types';
+
+export class BudgetPromptRepository {
+  constructor(private db: Database) {}
+
+  create(data: CreateBudgetPromptData): BudgetPrompt {
+    const result = this.db
+      .query<{ id: number }, [number, number, string, string, number | null]>(`
+        INSERT INTO budget_prompts (
+          group_id,
+          user_id,
+          category,
+          currency,
+          message_thread_id
+        )
+        VALUES (?, ?, ?, ?, ?)
+        RETURNING id
+      `)
+      .get(
+        data.group_id,
+        data.user_id,
+        data.category,
+        data.currency,
+        data.message_thread_id ?? null,
+      );
+
+    if (!result) throw new Error('Failed to create budget prompt');
+    const prompt = this.findById(result.id);
+    if (!prompt) throw new Error('Failed to read created budget prompt');
+    return prompt;
+  }
+
+  findById(id: number): BudgetPrompt | null {
+    return (
+      this.db.query('SELECT * FROM budget_prompts WHERE id = ?').get(id) ??
+      null
+    );
+  }
+
+  bindMessage(id: number, telegramMessageId: number): void {
+    this.db
+      .query(
+        `UPDATE budget_prompts
+         SET telegram_message_id = ?, updated_at = CURRENT_TIMESTAMP
+         WHERE id = ?`,
+      )
+      .run(telegramMessageId, id);
+  }
+
+  findActiveForUser(
+    groupId: number,
+    userId: number,
+    messageThreadId: number | null,
+  ): BudgetPrompt[] {
+    if (messageThreadId === null) {
+      return this.db
+        .query(`
+          SELECT * FROM budget_prompts
+          WHERE group_id = ? AND user_id = ?
+            AND status = 'active'
+            AND message_thread_id IS NULL
+            AND created_at >= datetime('now', '-7 days')
+          ORDER BY id ASC
+        `)
+        .all(groupId, userId);
+    }
+    return this.db
+      .query(`
+        SELECT * FROM budget_prompts
+        WHERE group_id = ? AND user_id = ?
+          AND status = 'active'
+          AND message_thread_id = ?
+          AND created_at >= datetime('now', '-7 days')
+        ORDER BY id ASC
+      `)
+      .all(groupId, userId, messageThreadId);
+  }
+
+  findActiveByMessage(
+    groupId: number,
+    userId: number,
+    telegramMessageId: number,
+    messageThreadId: number | null,
+  ): BudgetPrompt | null {
+    const threadClause =
+      messageThreadId === null ? 'message_thread_id IS NULL' : 'message_thread_id = ?';
+    const sql = `
+      SELECT * FROM budget_prompts
+      WHERE group_id = ? AND user_id = ?
+        AND telegram_message_id = ?
+        AND status = 'active'
+        AND ${threadClause}
+        AND created_at >= datetime('now', '-7 days')
+      ORDER BY id DESC
+      LIMIT 1
+    `;
+    if (messageThreadId === null) {
+      return (
+        this.db
+          .query(sql)
+          .get(groupId, userId, telegramMessageId) ?? null
+      );
+    }
+    return (
+      this.db
+        .query(sql)
+        .get(groupId, userId, telegramMessageId, messageThreadId) ?? null
+    );
+  }
+
+  /** Active, non-expired prompt by id — used by button callbacks. */
+  findActiveById(id: number): BudgetPrompt | null {
+    return (
+      this.db
+        .query(`
+          SELECT * FROM budget_prompts
+          WHERE id = ? AND status = 'active'
+            AND created_at >= datetime('now', '-7 days')
+        `)
+        .get(id) ?? null
+    );
+  }
+
+  /**
+   * Atomically leave the active state. Returns false when the prompt was already
+   * finished, so concurrent button presses cannot both apply it.
+   */
+  finish(id: number, status: Exclude): boolean {
+    const result = this.db
+      .query(
+        `UPDATE budget_prompts
+         SET status = ?, updated_at = CURRENT_TIMESTAMP
+         WHERE id = ? AND status = 'active'`,
+      )
+      .run(status, id);
+    return result.changes > 0;
+  }
+
+  /** Put a claimed prompt back (the budget write that followed the claim failed). */
+  reopen(id: number): void {
+    this.db
+      .query(
+        `UPDATE budget_prompts
+         SET status = 'active', updated_at = CURRENT_TIMESTAMP
+         WHERE id = ?`,
+      )
+      .run(id);
+  }
+
+  /** Retire older active prompts for the same category in the same group/user/topic scope. */
+  supersedeActive(
+    groupId: number,
+    userId: number,
+    category: string,
+    messageThreadId: number | null,
+  ): void {
+    this.db
+      .query(
+        `UPDATE budget_prompts
+         SET status = 'skipped', updated_at = CURRENT_TIMESTAMP
+         WHERE group_id = ? AND user_id = ? AND category = ?
+           AND status = 'active'
+           AND message_thread_id IS ?`,
+      )
+      .run(groupId, userId, category, messageThreadId);
+  }
+}
diff --git a/src/database/schema.ts b/src/database/schema.ts
index a8fdb124..bbaa874c 100644
--- a/src/database/schema.ts
+++ b/src/database/schema.ts
@@ -1402,6 +1402,37 @@ export function runMigrations(db: Database): void {
         logger.info('✓ Scoped chat history by Telegram topic');
       },
     },
+    {
+      name: '052_create_budget_prompts',
+      up: () => {
+        db.exec(`
+          CREATE TABLE IF NOT EXISTS budget_prompts (
+            id INTEGER PRIMARY KEY AUTOINCREMENT,
+            group_id INTEGER NOT NULL,
+            user_id INTEGER NOT NULL,
+            category TEXT NOT NULL,
+            currency TEXT NOT NULL,
+            telegram_message_id INTEGER,
+            message_thread_id INTEGER,
+            status TEXT NOT NULL DEFAULT 'active'
+              CHECK(status IN ('active', 'used', 'skipped')),
+            created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
+            updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
+            FOREIGN KEY (group_id) REFERENCES groups(id) ON DELETE CASCADE,
+            FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
+          );
+        `);
+        db.exec(`
+          CREATE INDEX IF NOT EXISTS idx_budget_prompts_active_user
+          ON budget_prompts(group_id, user_id, status, created_at)
+        `);
+        db.exec(`
+          CREATE INDEX IF NOT EXISTS idx_budget_prompts_message
+          ON budget_prompts(telegram_message_id)
+        `);
+        logger.info('✓ Added persistent budget setup prompts');
+      },
+    },
   ];
 
   // Check and run migrations
diff --git a/src/database/types.ts b/src/database/types.ts
index 05380117..8ab63203 100644
--- a/src/database/types.ts
+++ b/src/database/types.ts
@@ -162,6 +162,30 @@ export interface CreateBudgetData {
   currency?: CurrencyCode;
 }
 
+export type BudgetPromptStatus = 'active' | 'used' | 'skipped';
+
+/** Persistent Telegram prompt used while setting a budget. */
+export interface BudgetPrompt {
+  id: number;
+  group_id: number;
+  user_id: number;
+  category: string;
+  currency: CurrencyCode;
+  telegram_message_id: number | null;
+  message_thread_id: number | null;
+  status: BudgetPromptStatus;
+  created_at: string;
+  updated_at: string;
+}
+
+export interface CreateBudgetPromptData {
+  group_id: number;
+  user_id: number;
+  category: string;
+  currency: CurrencyCode;
+  message_thread_id?: number | null;
+}
+
 /**
  * Budget progress (for analytics and display)
  */
diff --git a/src/integration/expense-flow.integration.test.ts b/src/integration/expense-flow.integration.test.ts
index 2159fa0c..a7c337d9 100644
--- a/src/integration/expense-flow.integration.test.ts
+++ b/src/integration/expense-flow.integration.test.ts
@@ -61,6 +61,8 @@ mock.module('../services/google/sheets', () => ({
   }),
   isRateLimitError: () => false,
   withSheetsRetry: async (fn: () => Promise) => fn(),
+  // imported (never called) by budget-manager, which message.handler now reaches via budget-prompt
+  writeMonthBudgetRow: async () => true,
 }));
 
 mock.module('../services/google/oauth', () => ({
diff --git a/src/services/budget-suggestions.test.ts b/src/services/budget-suggestions.test.ts
new file mode 100644
index 00000000..2fcd75d4
--- /dev/null
+++ b/src/services/budget-suggestions.test.ts
@@ -0,0 +1,137 @@
+// Tests for budget amount suggestions — previous plan, spending history, group distribution, no data
+
+import { mock } from 'bun:test';
+import { createMockLogger } from '../test-utils/mocks/logger';
+
+const logMock = createMockLogger();
+mock.module('../utils/logger', () => ({ createLogger: () => logMock, logger: logMock }));
+
+import { describe, expect, test } from 'bun:test';
+import { buildBudgetSuggestions, roundToNiceAmount } from './budget-suggestions';
+
+const base = {
+  currency: 'EUR' as const,
+  previousBudget: null,
+  currentBudget: null,
+  monthlySpendEur: [] as number[],
+  otherBudgets: [] as Array<{ amount: number; currency: 'EUR' | 'USD' | 'RSD' }>,
+};
+
+describe('roundToNiceAmount', () => {
+  test.each([
+    [237, 240],
+    [1234, 1200],
+    [99, 99],
+    [8.4, 8],
+    [0.2, 1],
+    [45678, 46000],
+  ])('%p -> %p', (input, expected) => {
+    expect(roundToNiceAmount(input)).toBe(expected);
+  });
+});
+
+describe('buildBudgetSuggestions', () => {
+  test('no history at all: no options and no data-driven claim', () => {
+    const result = buildBudgetSuggestions(base);
+    expect(result.options).toEqual([]);
+  });
+
+  test('previous month budget is offered first with its reason', () => {
+    const result = buildBudgetSuggestions({
+      ...base,
+      previousBudget: { amount: 300, currency: 'EUR' },
+    });
+    expect(result.options[0]).toMatchObject({ amount: 300, kind: 'previous_budget' });
+    expect(result.options[0]?.reason).toContain('прошлого месяца');
+  });
+
+  test('spending history gives last-month and average options', () => {
+    const result = buildBudgetSuggestions({ ...base, monthlySpendEur: [100, 200, 300] });
+    const kinds = result.options.map((o) => o.kind);
+    expect(kinds).toContain('last_month_spend');
+    expect(kinds).toContain('average_spend');
+    expect(result.options.find((o) => o.kind === 'last_month_spend')?.amount).toBe(300);
+    expect(result.options.find((o) => o.kind === 'average_spend')?.amount).toBe(200);
+    expect(result.options.find((o) => o.kind === 'average_spend')?.reason).toContain('3');
+  });
+
+  test('single month of spending does not produce an average', () => {
+    const result = buildBudgetSuggestions({ ...base, monthlySpendEur: [120] });
+    expect(result.options.map((o) => o.kind)).toEqual(['last_month_spend']);
+  });
+
+  test('current plan is offered when the budget already exists this month', () => {
+    const result = buildBudgetSuggestions({
+      ...base,
+      currentBudget: { amount: 250, currency: 'EUR' },
+    });
+    expect(result.options[0]).toMatchObject({ amount: 250, kind: 'current_plan' });
+  });
+
+  test('group distribution is the fallback when the category has no history', () => {
+    const result = buildBudgetSuggestions({
+      ...base,
+      otherBudgets: [
+        { amount: 100, currency: 'EUR' },
+        { amount: 300, currency: 'EUR' },
+        { amount: 500, currency: 'EUR' },
+      ],
+    });
+    expect(result.options.map((o) => o.kind)).toContain('group_median');
+    expect(result.options.find((o) => o.kind === 'group_median')?.amount).toBe(300);
+    expect(result.options.find((o) => o.kind === 'group_median')?.reason).toContain(
+      'других категорий',
+    );
+  });
+
+  test('group distribution is NOT used when the category has its own history', () => {
+    const result = buildBudgetSuggestions({
+      ...base,
+      monthlySpendEur: [100, 120],
+      otherBudgets: [{ amount: 999, currency: 'EUR' }],
+    });
+    expect(result.options.map((o) => o.kind)).not.toContain('group_median');
+  });
+
+  test('duplicate amounts are collapsed and options are capped at three', () => {
+    const result = buildBudgetSuggestions({
+      ...base,
+      previousBudget: { amount: 200, currency: 'EUR' },
+      currentBudget: { amount: 200, currency: 'EUR' },
+      monthlySpendEur: [150, 200, 260, 310],
+    });
+    const amounts = result.options.map((o) => o.amount);
+    expect(new Set(amounts).size).toBe(amounts.length);
+    expect(amounts.length).toBeLessThanOrEqual(3);
+  });
+
+  test('converts EUR spending and foreign budgets into the prompt currency', () => {
+    const result = buildBudgetSuggestions({
+      ...base,
+      currency: 'RSD',
+      monthlySpendEur: [10, 10],
+      previousBudget: { amount: 50, currency: 'EUR' },
+    });
+    // 1 EUR is worth ~117 RSD, so amounts must be far above the raw EUR numbers
+    expect(result.options.every((o) => o.amount > 500)).toBe(true);
+  });
+
+  test('every option has an integer amount of at least 1', () => {
+    const result = buildBudgetSuggestions({ ...base, monthlySpendEur: [0.3, 0.4] });
+    for (const option of result.options) {
+      expect(Number.isInteger(option.amount)).toBe(true);
+      expect(option.amount).toBeGreaterThanOrEqual(1);
+    }
+  });
+});
+
+// Input history omits months without spending, so explanations must not imply consecutive months.
+test('spending explanations identify observed months rather than the previous calendar month', () => {
+  const result = buildBudgetSuggestions({ ...base, monthlySpendEur: [100, 300] });
+  expect(result.options.find((option) => option.kind === 'last_month_spend')?.reason).toBe(
+    'последний месяц с расходами',
+  );
+  expect(result.options.find((option) => option.kind === 'average_spend')?.reason).toBe(
+    'средние траты за 2 мес. с расходами',
+  );
+});
diff --git a/src/services/budget-suggestions.ts b/src/services/budget-suggestions.ts
new file mode 100644
index 00000000..0ab33cc9
--- /dev/null
+++ b/src/services/budget-suggestions.ts
@@ -0,0 +1,186 @@
+// Builds explainable suggested budget amounts from plans, spending history and group budgets
+
+import { addMonths, format, startOfMonth } from 'date-fns';
+import { BASE_CURRENCY, type CurrencyCode } from '../config/constants';
+import { database } from '../database';
+import { convertCurrency } from './currency/converter';
+
+export type BudgetSuggestionKind =
+  | 'previous_budget'
+  | 'current_plan'
+  | 'last_month_spend'
+  | 'average_spend'
+  | 'group_median'
+  | 'group_average';
+
+export interface BudgetSuggestion {
+  /** Whole units of the prompt currency — also used verbatim in callback data. */
+  amount: number;
+  kind: BudgetSuggestionKind;
+  /** Short Russian explanation shown next to the amount. */
+  reason: string;
+}
+
+interface MoneyAmount {
+  amount: number;
+  currency: CurrencyCode;
+}
+
+export interface SuggestionInputs {
+  currency: CurrencyCode;
+  previousBudget: MoneyAmount | null;
+  currentBudget: MoneyAmount | null;
+  /** EUR totals of the category for recent full months with spending, oldest first. */
+  monthlySpendEur: number[];
+  /** This month's budgets of the group's other categories. */
+  otherBudgets: MoneyAmount[];
+}
+
+export interface BudgetSuggestions {
+  options: BudgetSuggestion[];
+}
+
+const MAX_OPTIONS = 3;
+const HISTORY_MONTHS = 3;
+
+/** Round to two significant digits so suggestions look like plans, not statistics. */
+export function roundToNiceAmount(value: number): number {
+  if (value < 10) return Math.max(1, Math.round(value));
+  const step = 10 ** (Math.floor(Math.log10(value)) - 1);
+  return Math.max(1, Math.round(value / step) * step);
+}
+
+function toCurrency(money: MoneyAmount, target: CurrencyCode): number {
+  return convertCurrency(money.amount, money.currency, target);
+}
+
+function median(values: number[]): number {
+  const sorted = [...values].sort((a, b) => a - b);
+  const mid = Math.floor(sorted.length / 2);
+  const upper = sorted[mid] ?? 0;
+  return sorted.length % 2 === 1 ? upper : ((sorted[mid - 1] ?? upper) + upper) / 2;
+}
+
+function planSuggestions(input: SuggestionInputs): BudgetSuggestion[] {
+  const result: BudgetSuggestion[] = [];
+  if (input.currentBudget) {
+    result.push({
+      amount: roundToNiceAmount(toCurrency(input.currentBudget, input.currency)),
+      kind: 'current_plan',
+      reason: 'текущий бюджет на этот месяц',
+    });
+  }
+  if (input.previousBudget) {
+    result.push({
+      amount: roundToNiceAmount(toCurrency(input.previousBudget, input.currency)),
+      kind: 'previous_budget',
+      reason: 'бюджет прошлого месяца',
+    });
+  }
+  return result;
+}
+
+function spendingSuggestions(input: SuggestionInputs): BudgetSuggestion[] {
+  const spend = input.monthlySpendEur;
+  const last = spend[spend.length - 1];
+  if (last === undefined) return [];
+  const inCurrency = (eur: number) =>
+    roundToNiceAmount(convertCurrency(eur, BASE_CURRENCY, input.currency));
+  const result: BudgetSuggestion[] = [];
+  if (spend.length >= 2) {
+    const average = spend.reduce((sum, value) => sum + value, 0) / spend.length;
+    result.push({
+      amount: inCurrency(average),
+      kind: 'average_spend',
+      reason: `средние траты за ${spend.length} мес. с расходами`,
+    });
+  }
+  result.push({
+    amount: inCurrency(last),
+    kind: 'last_month_spend',
+    reason: 'последний месяц с расходами',
+  });
+  return result;
+}
+
+function groupSuggestions(input: SuggestionInputs): BudgetSuggestion[] {
+  if (input.otherBudgets.length === 0) return [];
+  const amounts = input.otherBudgets.map((budget) => toCurrency(budget, input.currency));
+  const average = amounts.reduce((sum, value) => sum + value, 0) / amounts.length;
+  const reason = `бюджеты других категорий (${amounts.length})`;
+  const result: BudgetSuggestion[] = [
+    {
+      amount: roundToNiceAmount(median(amounts)),
+      kind: 'group_median',
+      reason: `медиана: ${reason}`,
+    },
+  ];
+  if (amounts.length >= 3) {
+    result.push({
+      amount: roundToNiceAmount(average),
+      kind: 'group_average',
+      reason: `среднее: ${reason}`,
+    });
+  }
+  return result;
+}
+
+/** Pure suggestion logic: no DB access, deterministic for the given inputs. */
+export function buildBudgetSuggestions(input: SuggestionInputs): BudgetSuggestions {
+  const own = [...planSuggestions(input), ...spendingSuggestions(input)];
+  // The group distribution only stands in when the category itself has no data.
+  const candidates = own.length > 0 ? own : groupSuggestions(input);
+
+  const options: BudgetSuggestion[] = [];
+  for (const candidate of candidates) {
+    if (options.some((option) => option.amount === candidate.amount)) continue;
+    options.push(candidate);
+    if (options.length === MAX_OPTIONS) break;
+  }
+  return { options };
+}
+
+function monthKey(date: Date): string {
+  return format(date, 'yyyy-MM');
+}
+
+function collectMonthlySpendEur(groupId: number, category: string, now: Date): number[] {
+  const currentStart = startOfMonth(now);
+  const from = format(addMonths(currentStart, -HISTORY_MONTHS), 'yyyy-MM-dd');
+  const to = format(currentStart, 'yyyy-MM-dd');
+  const wanted = category.toLowerCase();
+  return database.expenses
+    .getMonthlyHistoryByCategory(groupId, from, to)
+    .filter((row) => row.category.toLowerCase() === wanted && row.monthly_total > 0)
+    .sort((a, b) => a.month.localeCompare(b.month))
+    .map((row) => row.monthly_total);
+}
+
+/** Gather the real data for a category and build suggestions from it. */
+export function suggestBudgetAmounts(
+  groupId: number,
+  category: string,
+  currency: CurrencyCode,
+  now: Date = new Date(),
+): BudgetSuggestions {
+  const thisMonth = monthKey(now);
+  const previous = database.budgets.getBudgetForMonth(
+    groupId,
+    category,
+    monthKey(addMonths(startOfMonth(now), -1)),
+  );
+  const current = database.budgets.getBudgetForMonth(groupId, category, thisMonth);
+  const others = database.budgets
+    .getAllBudgetsForMonth(groupId, thisMonth)
+    .filter((budget) => budget.category.toLowerCase() !== category.toLowerCase());
+
+  return buildBudgetSuggestions({
+    currency,
+    previousBudget: previous
+      ? { amount: previous.limit_amount, currency: previous.currency }
+      : null,
+    currentBudget: current ? { amount: current.limit_amount, currency: current.currency } : null,
+    monthlySpendEur: collectMonthlySpendEur(groupId, category, now),
+    otherBudgets: others.map((b) => ({ amount: b.limit_amount, currency: b.currency })),
+  });
+}
diff --git a/src/services/currency/budget-amount-parser.test.ts b/src/services/currency/budget-amount-parser.test.ts
new file mode 100644
index 00000000..7ae4f03f
--- /dev/null
+++ b/src/services/currency/budget-amount-parser.test.ts
@@ -0,0 +1,41 @@
+// Tests for the strict plain-amount parser used by the budget prompt text/reply flow
+
+import { describe, expect, test } from 'bun:test';
+import type { CurrencyCode } from '../../config/constants';
+import { parseBudgetInputAmount } from './budget-amount-parser';
+
+describe('parseBudgetInputAmount', () => {
+  test.each<[string, number, CurrencyCode | null]>([
+    ['150', 150, null],
+    ['150 eur', 150, 'EUR'],
+    ['150 EUR', 150, 'EUR'],
+    ['1 500 RSD', 1500, 'RSD'],
+    ['1500.50', 1500.5, null],
+    ['1500,5', 1500.5, null],
+    ['$150', 150, 'USD'],
+    ['150$', 150, 'USD'],
+    ['€ 99', 99, 'EUR'],
+    ['2000 руб', 2000, 'RUB'],
+    ['  150  ', 150, null],
+  ])('accepts %p', (input, amount, currency) => {
+    expect(parseBudgetInputAmount(input)).toEqual({ amount, currency });
+  });
+
+  test.each([
+    '',
+    'hello',
+    '150 food',
+    '150 еда продукты',
+    'budget 150',
+    '0',
+    '-5',
+    '150 eur usd',
+    '$150 eur',
+    '12abc',
+    '1.2.3',
+    '99999999999999',
+    '150\n200',
+  ])('rejects %p', (input) => {
+    expect(parseBudgetInputAmount(input)).toBeNull();
+  });
+});
diff --git a/src/services/currency/budget-amount-parser.ts b/src/services/currency/budget-amount-parser.ts
new file mode 100644
index 00000000..9c31f75f
--- /dev/null
+++ b/src/services/currency/budget-amount-parser.ts
@@ -0,0 +1,52 @@
+// Strict parser for a lone budget amount ("150", "150 eur", "1 500 RSD", "$150") typed by the user
+
+import { CURRENCY_ALIASES, type CurrencyCode } from '../../config/constants';
+
+export interface ParsedBudgetAmount {
+  amount: number;
+  /** null when the user did not name a currency — caller falls back to the prompt currency. */
+  currency: CurrencyCode | null;
+}
+
+const MAX_AMOUNT = 1_000_000_000_000;
+const NUMBER = String.raw`(\d{1,3}(?:[  ]\d{3})+(?:[.,]\d{1,2})?|\d+(?:[.,]\d{1,2})?)`;
+const PREFIX_FORM = new RegExp(String.raw`^([$€£₽¥])\s*${NUMBER}$`);
+const SUFFIX_FORM = new RegExp(String.raw`^${NUMBER}\s*([$€£₽¥]|[\p{L}]+)?$`, 'u');
+
+function toCurrency(token: string | undefined): CurrencyCode | null | undefined {
+  if (!token) return null;
+  const code = CURRENCY_ALIASES[token.toLowerCase()];
+  // undefined = unknown word, so the whole input is prose, not an amount
+  return code ? (code as CurrencyCode) : undefined;
+}
+
+function toAmount(raw: string): number | null {
+  const normalized = raw.replace(/[  ]/g, '').replace(',', '.');
+  const amount = Number.parseFloat(normalized);
+  if (!Number.isFinite(amount) || amount <= 0 || amount >= MAX_AMOUNT) return null;
+  return amount;
+}
+
+/**
+ * Parse text that consists ONLY of an amount with an optional currency.
+ * Anything else (extra words, unknown currency words, several numbers) returns null so that
+ * ordinary expense lines and prose are never swallowed by a budget prompt.
+ */
+export function parseBudgetInputAmount(text: string): ParsedBudgetAmount | null {
+  const trimmed = text.trim();
+  if (!trimmed || trimmed.includes('\n')) return null;
+
+  const prefix = PREFIX_FORM.exec(trimmed);
+  if (prefix) {
+    const amount = toAmount(prefix[2] ?? '');
+    const currency = toCurrency(prefix[1]);
+    return amount !== null && currency ? { amount, currency } : null;
+  }
+
+  const suffix = SUFFIX_FORM.exec(trimmed);
+  if (!suffix) return null;
+  const amount = toAmount(suffix[1] ?? '');
+  const currency = toCurrency(suffix[2]);
+  if (amount === null || currency === undefined) return null;
+  return { amount, currency };
+}
diff --git a/src/test-utils/db.ts b/src/test-utils/db.ts
index 4d4c091e..986b5cb0 100644
--- a/src/test-utils/db.ts
+++ b/src/test-utils/db.ts
@@ -34,6 +34,7 @@ export function clearTestDb(db: Database): void {
     DELETE FROM dev_tasks;
     DELETE FROM expenses;
     DELETE FROM receipts;
+    DELETE FROM budget_prompts;
     DELETE FROM budgets;
     DELETE FROM categories;
     DELETE FROM pending_expenses;
diff --git a/src/test-utils/mocks/database.ts b/src/test-utils/mocks/database.ts
index 3fb054a1..01c124d1 100644
--- a/src/test-utils/mocks/database.ts
+++ b/src/test-utils/mocks/database.ts
@@ -29,6 +29,7 @@ export function mockDatabase(
     'categories',
     'pendingExpenses',
     'budgets',
+    'budgetPrompts',
     'chatMessages',
     'adviceLog',
     'bankConnections',
diff --git a/src/utils/html.test.ts b/src/utils/html.test.ts
index d1cd5ac5..e05ab6df 100644
--- a/src/utils/html.test.ts
+++ b/src/utils/html.test.ts
@@ -5,6 +5,7 @@ import {
   escapeHtml,
   escapeMarkdown,
   escapeMarkdownV2,
+  packHtmlBlocks,
   processThinkTags,
   sanitizeHtmlForTelegram,
   stripAllHtml,
@@ -404,3 +405,27 @@ describe('truncateForTelegram', () => {
     expect(truncateForTelegram('short', 100)).toBe('short');
   });
 });
+
+// ── packHtmlBlocks ──────────────────────────────────────────────────
+
+describe('packHtmlBlocks', () => {
+  test('joins small blocks into one message with a blank line', () => {
+    expect(packHtmlBlocks(['a', 'b'])).toEqual(['a\n\nb']);
+  });
+
+  test('starts a new message instead of splitting a block', () => {
+    const blocks = ['
aaaa
', '
bbbb
', '
cccc
']; + const result = packHtmlBlocks(blocks, 35); + expect(result).toEqual(['
aaaa
\n\n
bbbb
', '
cccc
']); + }); + + test('truncates a single oversized block and closes its tags', () => { + const [only] = packHtmlBlocks([`${'x'.repeat(200)}`], 100); + expect(only?.length).toBeLessThan(120); + expect(only).toContain('
'); + }); + + test('returns no messages for no blocks', () => { + expect(packHtmlBlocks([])).toEqual([]); + }); +}); diff --git a/src/utils/html.ts b/src/utils/html.ts index fdea9335..f105e202 100644 --- a/src/utils/html.ts +++ b/src/utils/html.ts @@ -166,6 +166,30 @@ export function truncateForTelegram( return `${closeUnmatchedTags(sliced)}${marker}`; } +/** + * Greedily pack self-contained HTML blocks into messages of at most `maxLength` characters, + * separated by a blank line. Blocks are never split, so tags stay balanced; a single block + * longer than the limit is truncated with its open tags closed. + */ +export function packHtmlBlocks( + blocks: string[], + maxLength: number = TELEGRAM_MAX_MESSAGE_LENGTH, +): string[] { + const messages: string[] = []; + let current = ''; + for (const block of blocks) { + const joined = current ? `${current}\n\n${block}` : block; + if (current && joined.length > maxLength) { + messages.push(current); + current = block; + } else { + current = joined; + } + } + if (current) messages.push(current); + return messages.map((message) => truncateForTelegram(message, maxLength)); +} + /** * Strip ALL HTML tags and decode entities back to plain text. */ diff --git a/src/utils/ru-date.test.ts b/src/utils/ru-date.test.ts new file mode 100644 index 00000000..52ec660a --- /dev/null +++ b/src/utils/ru-date.test.ts @@ -0,0 +1,16 @@ +// Tests for Russian month formatting + +import { describe, expect, test } from 'bun:test'; +import { formatMonthYearRu } from './ru-date'; + +describe('formatMonthYearRu', () => { + test('formats every month in nominative case', () => { + const names = Array.from({ length: 12 }, (_, month) => + formatMonthYearRu(new Date(2026, month, 15)), + ); + expect(names[0]).toBe('январь 2026'); + expect(names[8]).toBe('сентябрь 2026'); + expect(names[11]).toBe('декабрь 2026'); + expect(new Set(names).size).toBe(12); + }); +}); diff --git a/src/utils/ru-date.ts b/src/utils/ru-date.ts new file mode 100644 index 00000000..99c48fbf --- /dev/null +++ b/src/utils/ru-date.ts @@ -0,0 +1,21 @@ +// Russian month names for user-facing text (Intl/ICU locale data is not guaranteed in the runtime) + +const MONTHS_RU = [ + 'январь', + 'февраль', + 'март', + 'апрель', + 'май', + 'июнь', + 'июль', + 'август', + 'сентябрь', + 'октябрь', + 'ноябрь', + 'декабрь', +] as const; + +/** "октябрь 2026" — nominative month name plus year. */ +export function formatMonthYearRu(date: Date): string { + return `${MONTHS_RU[date.getMonth()]} ${date.getFullYear()}`; +} From f1027dfe5d35a9b7ea00600408a40b0d29678fc7 Mon Sep 17 00:00:00 2001 From: Alex Ultra Date: Fri, 2 Oct 2026 14:18:29 +0200 Subject: [PATCH 2/4] fix(budget): retain prompt month and share suggestion snapshots --- src/bot/handlers/callback.handler.test.ts | 4 + src/bot/handlers/callback.handler.ts | 10 ++- src/bot/services/budget-prompt.test.ts | 81 ++++++++++++++++- src/bot/services/budget-prompt.ts | 72 +++++++++++---- .../budget-prompt.repository.test.ts | 17 +++- .../repositories/budget-prompt.repository.ts | 8 +- .../repositories/budget.repository.ts | 12 ++- src/database/schema.ts | 6 ++ src/database/types.ts | 2 + src/services/budget-suggestions-batch.test.ts | 50 +++++++++++ src/services/budget-suggestions.ts | 88 +++++++++++++------ 11 files changed, 289 insertions(+), 61 deletions(-) create mode 100644 src/services/budget-suggestions-batch.test.ts diff --git a/src/bot/handlers/callback.handler.test.ts b/src/bot/handlers/callback.handler.test.ts index a18a56d0..1a8343bf 100644 --- a/src/bot/handlers/callback.handler.test.ts +++ b/src/bot/handlers/callback.handler.test.ts @@ -153,6 +153,10 @@ const skipPromptMock = mock((_prompt: PromptStub) => true); const sendBudgetPromptMock = mock((_params: unknown) => Promise.resolve()); mock.module('../services/budget-prompt', () => ({ sendBudgetPrompt: sendBudgetPromptMock, + sendBudgetPrompts: async (params: { group: unknown; userId: number; categories: string[] }) => { + for (const category of params.categories) + await sendBudgetPromptMock({ group: params.group, userId: params.userId, category }); + }, lookupPromptForCallback: lookupPromptMock, applyBudgetPrompt: applyPromptMock, skipBudgetPrompt: skipPromptMock, diff --git a/src/bot/handlers/callback.handler.ts b/src/bot/handlers/callback.handler.ts index fd1e3ad5..cc52bd34 100644 --- a/src/bot/handlers/callback.handler.ts +++ b/src/bot/handlers/callback.handler.ts @@ -44,7 +44,7 @@ import { handleDisconnectCancel, handleDisconnectConfirm } from '../commands/dis import { cancelPendingFeedback } from '../commands/feedback'; import { handleSettingsCallback } from '../commands/settings'; import { createCategoriesListKeyboard } from '../keyboards'; -import { sendBudgetPrompt } from '../services/budget-prompt'; +import { sendBudgetPrompts } from '../services/budget-prompt'; import { getPendingCategoryExpense, getPendingCategorySiblings, @@ -527,9 +527,11 @@ async function advanceCategoryWizard( // Category confirmation is complete. Only now surface deferred budget actions, // so the user never has several different actionable wizard messages at once. - for (const category of takeQueuedCategoryBudgetPrompts(userId, sourceMessageId)) { - await sendBudgetPrompt({ group, userId, category }); - } + await sendBudgetPrompts({ + group, + userId, + categories: takeQueuedCategoryBudgetPrompts(userId, sourceMessageId), + }); } /** diff --git a/src/bot/services/budget-prompt.test.ts b/src/bot/services/budget-prompt.test.ts index ca5fb33d..e8ae8595 100644 --- a/src/bot/services/budget-prompt.test.ts +++ b/src/bot/services/budget-prompt.test.ts @@ -16,7 +16,7 @@ const userRepo = new UserRepository(db); const groupsStub = { findById: mock((_id: number) => ({ id: 1, google_refresh_token: 'tok' })) }; const budgetsStub = { getBudgetForMonth: mock(() => null), - getAllBudgetsForMonth: mock((): unknown[] => []), + getBudgetCandidatesForMonth: mock((): unknown[] => []), }; const expensesStub = { getMonthlyHistoryByCategory: mock((): unknown[] => []), @@ -54,7 +54,7 @@ mock.module('../../services/budget-manager', () => ({ getBudgetManager: () => ({ set: setBudgetMock }), })); -import { beforeEach, describe, expect, test } from 'bun:test'; +import { afterEach, beforeEach, describe, expect, setSystemTime, test } from 'bun:test'; import type { Group, User } from '../../database/types'; const { @@ -62,6 +62,7 @@ const { handleBudgetPromptText, lookupPromptForCallback, sendBudgetPrompt, + sendBudgetPrompts, skipBudgetPrompt, } = await import('./budget-prompt'); @@ -109,7 +110,7 @@ beforeEach(() => { setBudgetMock.mockClear(); setBudgetMock.mockImplementation(() => Promise.resolve({ sheetsSynced: true })); budgetsStub.getBudgetForMonth.mockReturnValue(null); - budgetsStub.getAllBudgetsForMonth.mockReturnValue([]); + budgetsStub.getBudgetCandidatesForMonth.mockReturnValue([]); expensesStub.getMonthlyHistoryByCategory.mockReturnValue([]); logMock.error.mockClear(); logMock.warn.mockClear(); @@ -126,7 +127,7 @@ describe('sendBudgetPrompt', () => { expect(created?.telegram_message_id).toBe(1000); const [text, options] = sendMessageMock.mock.calls[0] ?? []; expect(text).toContain('Food'); - expect(text).toContain('траты в прошлом месяце'); + expect(text).toContain('последний месяц с расходами'); expect(keyboardData(options)).toContain(`budget:psuggest:${created?.id}:200`); expect(keyboardData(options)).toContain(`budget:pskip:${created?.id}`); }); @@ -300,3 +301,75 @@ describe('prompt lookup, apply and skip', () => { expect(prompts.findById(id)?.status).toBe('skipped'); }); }); + +afterEach(() => setSystemTime()); + +test('a September prompt answered in October still writes September', async () => { + setSystemTime(new Date(2026, 8, 30, 23, 59)); + const id = await openPrompt('Food'); + expect(sendMessageMock.mock.calls[0]?.[0]).toContain('сентябрь 2026'); + setSystemTime(new Date(2026, 9, 1, 0, 1)); + const prompt = prompts.findById(id); + if (!prompt) throw new Error('missing synthetic prompt'); + await applyBudgetPrompt(prompt, 150, 'EUR'); + expect(setBudgetMock.mock.calls[0]?.[0].month).toBe('2026-09'); +}); + +test('a failed suggestion read does not leave an invisible prompt', async () => { + expensesStub.getMonthlyHistoryByCategory.mockImplementationOnce(() => { + throw new Error('synthetic read failure'); + }); + await expect(sendBudgetPrompt({ group, userId: user.id, category: 'Food' })).rejects.toThrow( + 'synthetic read failure', + ); + expect(prompts.findActiveForUser(group.id, user.id, null)).toEqual([]); + expect(await handleBudgetPromptText(input('150'))).toBe(false); + expect(setBudgetMock).not.toHaveBeenCalled(); +}); + +test('a category batch reads shared history and both budget months only once', async () => { + expensesStub.getMonthlyHistoryByCategory.mockClear(); + budgetsStub.getBudgetCandidatesForMonth.mockClear(); + expensesStub.getMonthlyHistoryByCategory.mockReturnValue([ + { category: 'Food', month: '2026-09', monthly_total: 200, tx_count: 4 }, + { category: 'Gym', month: '2026-09', monthly_total: 70, tx_count: 1 }, + ]); + await sendBudgetPrompts({ group, userId: user.id, categories: ['Food', 'Gym'] }); + expect(expensesStub.getMonthlyHistoryByCategory).toHaveBeenCalledTimes(1); + expect(budgetsStub.getBudgetCandidatesForMonth).toHaveBeenCalledTimes(2); + expect(sendMessageMock).toHaveBeenCalledTimes(2); + expect(sendMessageMock.mock.calls[0]?.[0]).toContain('200.00'); + expect(sendMessageMock.mock.calls[1]?.[0]).toContain('70.00'); +}); + +test('a rejected send leaves no invisible active prompt', async () => { + sendMessageMock.mockRejectedValueOnce(new Error('synthetic send failure')); + await expect(sendBudgetPrompt({ group, userId: user.id, category: 'Food' })).rejects.toThrow( + 'synthetic send failure', + ); + expect(prompts.findActiveForUser(group.id, user.id, null)).toEqual([]); +}); + +test('legacy prompts without a recorded month never guess a financial target', async () => { + const id = await openPrompt('Food'); + db.query('UPDATE budget_prompts SET target_month = NULL WHERE id = ?').run(id); + const prompt = prompts.findById(id); + if (!prompt) throw new Error('missing synthetic prompt'); + expect(await applyBudgetPrompt(prompt, 150, 'EUR')).toBe('failed'); + expect(setBudgetMock).not.toHaveBeenCalled(); + expect(prompts.findById(id)?.status).toBe('skipped'); +}); + +test('batch suggestions retain previous and current category budget sources', async () => { + budgetsStub.getBudgetCandidatesForMonth + .mockReturnValueOnce([ + { category: 'FOOD', limit_amount: 180, currency: 'EUR' }, + { category: 'Gym', limit_amount: 70, currency: 'EUR' }, + ]) + .mockReturnValueOnce([{ category: 'Food', limit_amount: 120, currency: 'EUR' }]); + await sendBudgetPrompts({ group, userId: user.id, categories: ['Food', 'Gym'] }); + const text = sendMessageMock.mock.calls[0]?.[0]; + expect(text).toContain('120.00'); + expect(text).toContain('180.00'); + expect(sendMessageMock.mock.calls[1]?.[0]).toContain('70.00'); +}); diff --git a/src/bot/services/budget-prompt.ts b/src/bot/services/budget-prompt.ts index 13b55c5f..81f02852 100644 --- a/src/bot/services/budget-prompt.ts +++ b/src/bot/services/budget-prompt.ts @@ -6,7 +6,11 @@ import { database } from '../../database'; import type { BudgetPrompt, Group, User } from '../../database/types'; import { sendMessage } from '../../services/bank/telegram-sender'; import { getBudgetManager } from '../../services/budget-manager'; -import { type BudgetSuggestions, suggestBudgetAmounts } from '../../services/budget-suggestions'; +import { + type BudgetSuggestions, + suggestBudgetAmounts, + suggestBudgetAmountsBatch, +} from '../../services/budget-suggestions'; import { parseBudgetInputAmount } from '../../services/currency/budget-amount-parser'; import { formatAmount } from '../../services/currency/converter'; import { chatStorage } from '../../utils/chat-context'; @@ -60,11 +64,14 @@ export async function sendBudgetPrompt(params: { group: Group; userId: number; category: string; + suggestions?: BudgetSuggestions; + now?: Date; }): Promise { const { group, userId, category } = params; const currency = group.default_currency; const threadId = chatStorage.getStore()?.threadId ?? null; - const now = new Date(); + const now = params.now ?? new Date(); + const suggestions = params.suggestions ?? suggestBudgetAmounts(group.id, category, currency, now); database.budgetPrompts.supersedeActive(group.id, userId, category, threadId); const prompt = database.budgetPrompts.create({ @@ -72,27 +79,55 @@ export async function sendBudgetPrompt(params: { user_id: userId, category, currency, + target_month: format(now, 'yyyy-MM'), message_thread_id: threadId, }); - const suggestions = suggestBudgetAmounts(group.id, category, currency, now); - const keyboard = createBudgetSuggestionKeyboard( - prompt.id, - suggestions.options.map((option) => option.amount), - currency, - ); - const sent = await sendMessage(formatPromptText(category, suggestions, currency, now), { - reply_markup: keyboard, - }); - - if (sent) { - database.budgetPrompts.bindMessage(prompt.id, sent.message_id); - return; + try { + const keyboard = createBudgetSuggestionKeyboard( + prompt.id, + suggestions.options.map((option) => option.amount), + currency, + ); + const sent = await sendMessage(formatPromptText(category, suggestions, currency, now), { + reply_markup: keyboard, + }); + if (sent) { + database.budgetPrompts.bindMessage(prompt.id, sent.message_id); + return; + } + } catch (error) { + database.budgetPrompts.finish(prompt.id, 'skipped'); + throw error; } // The user never saw it, so it must not capture their next plain amount. database.budgetPrompts.finish(prompt.id, 'skipped'); } +/** Share one history/budget snapshot across the categories completed by a wizard. */ +export async function sendBudgetPrompts(params: { + group: Group; + userId: number; + categories: string[]; +}): Promise { + const now = new Date(); + const suggestions = suggestBudgetAmountsBatch( + params.group.id, + params.categories, + params.group.default_currency, + now, + ); + for (const category of params.categories) { + await sendBudgetPrompt({ + group: params.group, + userId: params.userId, + category, + now, + suggestions: suggestions.get(category) ?? { options: [] }, + }); + } +} + /** Resolve a button's prompt id for the pressing user; stale/foreign prompts are rejected. */ export function lookupPromptForCallback( promptId: number, @@ -111,13 +146,18 @@ export async function applyBudgetPrompt( amount: number, currency: CurrencyCode, ): Promise { + if (!prompt.target_month) { + // Legacy prompts did not record the displayed month; never guess the budget's target. + database.budgetPrompts.finish(prompt.id, 'skipped'); + return 'failed'; + } if (!database.budgetPrompts.finish(prompt.id, 'used')) return 'already_handled'; try { const result = await getBudgetManager().set({ groupId: prompt.group_id, category: prompt.category, - month: format(new Date(), 'yyyy-MM'), + month: prompt.target_month, amount, currency, }); diff --git a/src/database/repositories/budget-prompt.repository.test.ts b/src/database/repositories/budget-prompt.repository.test.ts index 92518e90..b0efe7f9 100644 --- a/src/database/repositories/budget-prompt.repository.test.ts +++ b/src/database/repositories/budget-prompt.repository.test.ts @@ -38,6 +38,7 @@ function createPrompt(overrides: { category?: string; thread?: number | null } = group_id: groupId, user_id: userId, category: overrides.category ?? 'Food', + target_month: '2026-10', currency: 'EUR', message_thread_id: overrides.thread ?? null, }); @@ -61,8 +62,20 @@ describe('BudgetPromptRepository', () => { test('findActiveForUser is scoped by group, user and topic', () => { const general = createPrompt({ category: 'A' }); const topic = createPrompt({ category: 'B', thread: 7 }); - repo.create({ group_id: otherGroupId, user_id: userId, category: 'C', currency: 'EUR' }); - repo.create({ group_id: groupId, user_id: otherUserId, category: 'D', currency: 'EUR' }); + repo.create({ + group_id: otherGroupId, + user_id: userId, + category: 'C', + target_month: '2026-10', + currency: 'EUR', + }); + repo.create({ + group_id: groupId, + user_id: otherUserId, + category: 'D', + target_month: '2026-10', + currency: 'EUR', + }); expect(repo.findActiveForUser(groupId, userId, null).map((p) => p.id)).toEqual([general.id]); expect(repo.findActiveForUser(groupId, userId, 7).map((p) => p.id)).toEqual([topic.id]); diff --git a/src/database/repositories/budget-prompt.repository.ts b/src/database/repositories/budget-prompt.repository.ts index 1df9469b..5c3f7793 100644 --- a/src/database/repositories/budget-prompt.repository.ts +++ b/src/database/repositories/budget-prompt.repository.ts @@ -7,15 +7,16 @@ export class BudgetPromptRepository { create(data: CreateBudgetPromptData): BudgetPrompt { const result = this.db - .query<{ id: number }, [number, number, string, string, number | null]>(` + .query<{ id: number }, [number, number, string, string, number | null, string]>(` INSERT INTO budget_prompts ( group_id, user_id, category, currency, - message_thread_id + message_thread_id, + target_month ) - VALUES (?, ?, ?, ?, ?) + VALUES (?, ?, ?, ?, ?, ?) RETURNING id `) .get( @@ -24,6 +25,7 @@ export class BudgetPromptRepository { data.category, data.currency, data.message_thread_id ?? null, + data.target_month, ); if (!result) throw new Error('Failed to create budget prompt'); diff --git a/src/database/repositories/budget.repository.ts b/src/database/repositories/budget.repository.ts index efbc9c37..d133b08a 100644 --- a/src/database/repositories/budget.repository.ts +++ b/src/database/repositories/budget.repository.ts @@ -35,6 +35,7 @@ export interface BudgetReadRepository { findByGroupCategoryMonth(groupId: number, category: string, month: string): Budget | null; getBudgetForMonth(groupId: number, category: string, month: string): Budget | null; getAllBudgetsForMonth(groupId: number, month: string): Budget[]; + getBudgetCandidatesForMonth(groupId: number, month: string): Budget[]; findByGroupId(groupId: number): Budget[]; getBudgetProgress( groupId: number, @@ -92,9 +93,7 @@ export class BudgetRepository implements BudgetReadRepository { * Uses full fuzzy matching pipeline (exact → case → trim → phonetic → Levenshtein) * to handle typos, case differences, and minor spelling variations. */ findByGroupCategoryMonth(groupId: number, category: string, month: string): Budget | null { - const rows = this.db - .query('SELECT * FROM budgets WHERE group_id = ? AND month = ?') - .all(groupId, month); + const rows = this.getBudgetCandidatesForMonth(groupId, month); if (rows.length === 0) return null; @@ -110,6 +109,13 @@ export class BudgetRepository implements BudgetReadRepository { return this.findByGroupCategoryMonth(groupId, category, month); } + /** Preserve the existing candidate order used by the first-match fuzzy resolver. */ + getBudgetCandidatesForMonth(groupId: number, month: string): Budget[] { + return this.db + .query('SELECT * FROM budgets WHERE group_id = ? AND month = ?') + .all(groupId, month); + } + /** Get all budgets for exact month — no inheritance loop */ getAllBudgetsForMonth(groupId: number, month: string): Budget[] { return this.db diff --git a/src/database/schema.ts b/src/database/schema.ts index bbaa874c..c5f589c1 100644 --- a/src/database/schema.ts +++ b/src/database/schema.ts @@ -1433,6 +1433,12 @@ export function runMigrations(db: Database): void { logger.info('✓ Added persistent budget setup prompts'); }, }, + { + name: '053_budget_prompt_target_month', + up: () => { + db.exec('ALTER TABLE budget_prompts ADD COLUMN target_month TEXT'); + }, + }, ]; // Check and run migrations diff --git a/src/database/types.ts b/src/database/types.ts index 8ab63203..102d73f1 100644 --- a/src/database/types.ts +++ b/src/database/types.ts @@ -171,6 +171,7 @@ export interface BudgetPrompt { user_id: number; category: string; currency: CurrencyCode; + target_month: string | null; telegram_message_id: number | null; message_thread_id: number | null; status: BudgetPromptStatus; @@ -183,6 +184,7 @@ export interface CreateBudgetPromptData { user_id: number; category: string; currency: CurrencyCode; + target_month: string; message_thread_id?: number | null; } diff --git a/src/services/budget-suggestions-batch.test.ts b/src/services/budget-suggestions-batch.test.ts new file mode 100644 index 00000000..94383b18 --- /dev/null +++ b/src/services/budget-suggestions-batch.test.ts @@ -0,0 +1,50 @@ +// Shared budget snapshots must preserve repository matching and chronological spending semantics. +import { expect, mock, test } from 'bun:test'; +import { BudgetRepository } from '../database/repositories/budget.repository'; +import { GroupRepository } from '../database/repositories/group.repository'; +import { createTestDb } from '../test-utils/db'; + +const db = createTestDb(); +const budgets = new BudgetRepository(db); +const history = mock( + () => [] as { category: string; month: string; monthly_total: number; tx_count: number }[], +); +mock.module('../database', () => ({ + database: { budgets, expenses: { getMonthlyHistoryByCategory: history } }, +})); +const { suggestBudgetAmountsBatch } = await import('./budget-suggestions'); + +test('batch suggestions preserve ambiguous prefix choice from the repository', () => { + const group = new GroupRepository(db).create({ telegram_group_id: -746123 }); + budgets.setBudget({ + group_id: group.id, + category: 'Food', + month: '2026-09', + limit_amount: 120, + currency: 'EUR', + }); + budgets.setBudget({ + group_id: group.id, + category: 'Foo', + month: '2026-09', + limit_amount: 240, + currency: 'EUR', + }); + const original = budgets.getBudgetForMonth(group.id, 'Fo', '2026-09'); + expect(original?.category).toBe('Food'); + const suggestion = suggestBudgetAmountsBatch(group.id, ['Fo'], 'EUR', new Date(2026, 9, 2)).get( + 'Fo', + ); + expect(suggestion?.options[0]?.amount).toBe(original?.limit_amount); +}); + +test('case-folded history remains chronological without sorting unrelated categories', () => { + history.mockReturnValue([ + { category: 'FOOD', month: '2026-09', monthly_total: 300, tx_count: 1 }, + { category: 'Food', month: '2026-08', monthly_total: 100, tx_count: 1 }, + { category: 'Unrelated', month: '2026-09', monthly_total: 999, tx_count: 1 }, + ]); + const result = suggestBudgetAmountsBatch(-1, ['Food'], 'EUR', new Date(2026, 9, 2)).get('Food'); + expect(result?.options.find((option) => option.kind === 'last_month_spend')?.amount).toBe(300); + expect(result?.options.some((option) => option.amount === 200)).toBe(true); +}); diff --git a/src/services/budget-suggestions.ts b/src/services/budget-suggestions.ts index 0ab33cc9..24461417 100644 --- a/src/services/budget-suggestions.ts +++ b/src/services/budget-suggestions.ts @@ -3,6 +3,8 @@ import { addMonths, format, startOfMonth } from 'date-fns'; import { BASE_CURRENCY, type CurrencyCode } from '../config/constants'; import { database } from '../database'; +import type { Budget } from '../database/types'; +import { findBestCategoryMatch } from '../utils/fuzzy-search'; import { convertCurrency } from './currency/converter'; export type BudgetSuggestionKind = @@ -144,43 +146,71 @@ function monthKey(date: Date): string { return format(date, 'yyyy-MM'); } -function collectMonthlySpendEur(groupId: number, category: string, now: Date): number[] { +/** Gather shared history/current and previous budgets once for a wizard's category batch. */ +export function suggestBudgetAmountsBatch( + groupId: number, + categories: string[], + currency: CurrencyCode, + now: Date = new Date(), +): Map { + const result = new Map(); + if (categories.length === 0) return result; const currentStart = startOfMonth(now); - const from = format(addMonths(currentStart, -HISTORY_MONTHS), 'yyyy-MM-dd'); - const to = format(currentStart, 'yyyy-MM-dd'); - const wanted = category.toLowerCase(); - return database.expenses - .getMonthlyHistoryByCategory(groupId, from, to) - .filter((row) => row.category.toLowerCase() === wanted && row.monthly_total > 0) - .sort((a, b) => a.month.localeCompare(b.month)) - .map((row) => row.monthly_total); + const current = database.budgets.getBudgetCandidatesForMonth(groupId, monthKey(now)); + const previous = database.budgets.getBudgetCandidatesForMonth( + groupId, + monthKey(addMonths(currentStart, -1)), + ); + const history = database.expenses.getMonthlyHistoryByCategory( + groupId, + format(addMonths(currentStart, -HISTORY_MONTHS), 'yyyy-MM-dd'), + format(currentStart, 'yyyy-MM-dd'), + ); + const wanted = new Set(categories.map((category) => category.toLowerCase())); + const spend = new Map(); + for (const row of history) { + if (row.monthly_total <= 0) continue; + const key = row.category.toLowerCase(); + if (!wanted.has(key)) continue; + const amounts = spend.get(key) ?? []; + amounts.push({ month: row.month, amount: row.monthly_total }); + spend.set(key, amounts); + } + const matchingBudget = (budgets: Budget[], category: string): MoneyAmount | null => { + const match = findBestCategoryMatch( + category, + budgets.map((budget) => budget.category), + ); + const budget = budgets.find((row) => row.category === match); + return budget ? { amount: budget.limit_amount, currency: budget.currency } : null; + }; + for (const category of categories) { + result.set( + category, + buildBudgetSuggestions({ + currency, + previousBudget: matchingBudget(previous, category), + currentBudget: matchingBudget(current, category), + monthlySpendEur: (spend.get(category.toLowerCase()) ?? []) + .sort((a, b) => a.month.localeCompare(b.month)) + .map((row) => row.amount), + otherBudgets: current + .filter((row) => row.category.toLowerCase() !== category.toLowerCase()) + .map((row) => ({ amount: row.limit_amount, currency: row.currency })), + }), + ); + } + return result; } -/** Gather the real data for a category and build suggestions from it. */ +/** Gather the real data for one category, using the same snapshot path as wizard batches. */ export function suggestBudgetAmounts( groupId: number, category: string, currency: CurrencyCode, now: Date = new Date(), ): BudgetSuggestions { - const thisMonth = monthKey(now); - const previous = database.budgets.getBudgetForMonth( - groupId, - category, - monthKey(addMonths(startOfMonth(now), -1)), + return ( + suggestBudgetAmountsBatch(groupId, [category], currency, now).get(category) ?? { options: [] } ); - const current = database.budgets.getBudgetForMonth(groupId, category, thisMonth); - const others = database.budgets - .getAllBudgetsForMonth(groupId, thisMonth) - .filter((budget) => budget.category.toLowerCase() !== category.toLowerCase()); - - return buildBudgetSuggestions({ - currency, - previousBudget: previous - ? { amount: previous.limit_amount, currency: previous.currency } - : null, - currentBudget: current ? { amount: current.limit_amount, currency: current.currency } : null, - monthlySpendEur: collectMonthlySpendEur(groupId, category, now), - otherBudgets: others.map((b) => ({ amount: b.limit_amount, currency: b.currency })), - }); } From 33511b074bd78437a88b65d9ac264f7a72d69650 Mon Sep 17 00:00:00 2001 From: Alex Ultra Date: Fri, 2 Oct 2026 11:49:05 +0200 Subject: [PATCH 3/4] fix(routing): exclude budget intent from expense fastpath (#121) --- src/bot/handlers/message.handler.test.ts | 118 +++++++++++++++++- src/bot/handlers/message.handler.ts | 18 ++- src/bot/index.ts | 7 +- .../expense-flow.integration.test.ts | 39 +++++- 4 files changed, 173 insertions(+), 9 deletions(-) diff --git a/src/bot/handlers/message.handler.test.ts b/src/bot/handlers/message.handler.test.ts index 076819b7..3518e0a1 100644 --- a/src/bot/handlers/message.handler.test.ts +++ b/src/bot/handlers/message.handler.test.ts @@ -115,8 +115,10 @@ mock.module('../services/expense-saver', () => ({ // ── ask (maybeSmartAdvice is fire-and-forget advice hook) ── const maybeSmartAdviceMock = mock(() => Promise.resolve()); +const handleAskQuestionMock = mock(() => Promise.resolve()); mock.module('../commands/ask', () => ({ maybeSmartAdvice: maybeSmartAdviceMock, + handleAskQuestion: handleAskQuestionMock, })); // ── dev pipeline — never trigger in these tests ── @@ -243,7 +245,9 @@ mock.module('../services/category-wizard', () => ({ })); // Dynamic-import target — must come AFTER all mock.module calls. -const { handleExpenseMessage, buildBudgetAlertStatus } = await import('./message.handler'); +const { handleExpenseMessage, buildBudgetAlertStatus, routeTextMessage } = await import( + './message.handler' +); // ─── Fixtures ──────────────────────────────────────────────────────────────── @@ -336,6 +340,7 @@ function resetAllMocks(): void { saveExpenseBatchMock.mockReset().mockResolvedValue(); saveReceiptExpensesMock.mockReset().mockResolvedValue(); maybeSmartAdviceMock.mockReset().mockResolvedValue(); + handleAskQuestionMock.mockReset().mockResolvedValue(); isAwaitingCustomCurrencyMock.mockReset().mockReturnValue(false); handleCustomCurrencyInputMock.mockReset().mockResolvedValue(true); handleWizardInputMock.mockReset().mockResolvedValue(false); @@ -791,3 +796,114 @@ describe('handleExpenseMessage — multi-line batch', () => { expect(summaryCall).toBeDefined(); }); }); + +// Budget language is intent, even if every line otherwise matches expense syntax. +describe('budget routing safety regression', () => { + beforeEach(() => { + resetAllMocks(); + mockGroups.findByTelegramGroupId.mockReturnValue(makeGroup()); + mockCategories.exists.mockReturnValue(true); + }); + + test.each([ + 'бюджет', + 'БЮДЖЕТ', + 'бюджета', + 'бюджету', + 'бюджетом', + 'бюджете', + 'бюджеты', + 'бюджетов', + 'бюджетами', + 'бюджетный', + 'budget', + 'BuDgEt', + 'BUDGETS', + ])('refuses all expense writes when %s appears in a parseable line', async (word) => { + const handled = await handleExpenseMessage( + fakeMessageCtx(`10 EUR еда\n20 EUR ${word}`), + fakeBot(), + ); + expect(handled).toBe(false); + expect(mockPendingExpenses.create).not.toHaveBeenCalled(); + expect(saveExpenseBatchMock).not.toHaveBeenCalled(); + expect(sendMessageMock).not.toHaveBeenCalled(); + }); + + test.each([ + 'Составь план\n€450 — квартира', + '€450 — квартира\nУточни остаток', + '\n\n', + '10 EUR еда\nБЮДЖЕТ\n20 EUR дом', + ])('keeps the entire mixed message out of expense writes: %s', async (text) => { + expect(await handleExpenseMessage(fakeMessageCtx(text), fakeBot())).toBe(false); + expect(mockPendingExpenses.create).not.toHaveBeenCalled(); + expect(saveExpenseBatchMock).not.toHaveBeenCalled(); + }); + + test('euro prefix, em dash and blank lines remain valid for pure expenses', async () => { + expect( + await handleExpenseMessage(fakeMessageCtx('\n€450 — квартира\n\n€600 — еда\n'), fakeBot()), + ).toBe(true); + expect(mockPendingExpenses.create).toHaveBeenCalledTimes(2); + expect(saveExpenseBatchMock).toHaveBeenCalledTimes(1); + }); +}); + +describe('production text route forwards budget intent intact', () => { + beforeEach(() => { + resetAllMocks(); + mockGroups.findByTelegramGroupId.mockReturnValue(makeGroup({ active_topic_id: 77 })); + mockCategories.exists.mockReturnValue(true); + }); + + test('exact October plan reaches AI once with original context and zero expense writes', async () => { + const text = `Сформируй бюджет на грядущий октябрь + +€450 — квартира +€600 — еда +€300 — коммуналка +€200 — животные +€200 — машина +€700 — Лена +€700 — Алекс +€100 — развлечения +€620 — подписки +€100 — дом + +Другие категории убери (перечили), сумма должна быть 6000€`; + const ctx = fakeMessageCtx(text, { isForum: true, threadId: 77 }); + const bot = fakeBot(); + await routeTextMessage(ctx, bot, true); + expect(handleAskQuestionMock).toHaveBeenCalledTimes(1); + expect(handleAskQuestionMock).toHaveBeenCalledWith(ctx, text, bot); + expect(mockPendingExpenses.create).not.toHaveBeenCalled(); + expect(saveExpenseBatchMock).not.toHaveBeenCalled(); + expect(saveReceiptExpensesMock).not.toHaveBeenCalled(); + expect(sendMessageMock).not.toHaveBeenCalled(); + }); + + test.each([ + '100 EUR БЮДЖЕТА', + 'Вводный текст\n€450 — квартира', + '€450 — квартира\nЗавершающий текст', + ])('declined fastpath calls AI rather than dropping input: %s', async (text) => { + const ctx = fakeMessageCtx(text, { threadId: 77 }); + const bot = fakeBot(); + await routeTextMessage(ctx, bot, true); + expect(handleAskQuestionMock).toHaveBeenCalledTimes(1); + expect(handleAskQuestionMock).toHaveBeenCalledWith(ctx, text, bot); + expect(mockPendingExpenses.create).not.toHaveBeenCalled(); + }); + + test('pure expenses are saved without invoking AI', async () => { + await routeTextMessage( + fakeMessageCtx('€450 — квартира\n\n€600 — еда', { threadId: 77 }), + fakeBot(), + true, + ); + expect(mockPendingExpenses.create).toHaveBeenCalledTimes(2); + expect(saveExpenseBatchMock).toHaveBeenCalledTimes(1); + expect(handleAskQuestionMock).not.toHaveBeenCalled(); + }); +}); diff --git a/src/bot/handlers/message.handler.ts b/src/bot/handlers/message.handler.ts index 615254a7..0b124309 100644 --- a/src/bot/handlers/message.handler.ts +++ b/src/bot/handlers/message.handler.ts @@ -19,7 +19,7 @@ import { getErrorMessage } from '../../utils/error'; import { findBestCategoryMatchAsync } from '../../utils/fuzzy-search'; import { escapeHtml } from '../../utils/html'; import { createLogger } from '../../utils/logger.ts'; -import { maybeSmartAdvice } from '../commands/ask'; +import { handleAskQuestion, maybeSmartAdvice } from '../commands/ask'; import { consumePendingDesignEdit, getPipelineInstance } from '../commands/dev'; import { consumePendingFeedback, submitFeedback } from '../commands/feedback'; import { showNextPendingCategoryStep } from '../services/category-wizard'; @@ -421,6 +421,10 @@ function parseStrictLines( logger.info(`[MSG] Processing ${lines.length} line(s)`); + if (/(?:^|[^\p{L}])(?:бюджет|budget)\p{L}*(?=$|[^\p{L}])/iu.test(text)) { + logger.info('[MSG] Budget intent — routing the whole message to AI'); + return null; + } const parsedLines = lines.map((line) => parseExpenseMessage(line, defaultCurrency)); if (parsedLines.length === 0 || parsedLines.some((parsed) => !validateParsedExpense(parsed))) { logger.info('[MSG] Mixed/non-canonical message — routing the whole message to AI'); @@ -984,3 +988,15 @@ export function buildBudgetAlertStatus( isWarning: progress.is_warning, }; } + +/** Preserve the full message and context when direct expense entry declines it. */ +export async function routeTextMessage( + ctx: Ctx['Message'], + bot: BotInstance, + allowDirectAI: boolean, +): Promise { + const expenseHandled = await handleExpenseMessage(ctx, bot); + if (!expenseHandled && allowDirectAI && ctx.text) { + await handleAskQuestion(ctx, ctx.text, bot); + } +} diff --git a/src/bot/index.ts b/src/bot/index.ts index e2dc5db6..41ddcf7d 100644 --- a/src/bot/index.ts +++ b/src/bot/index.ts @@ -38,7 +38,7 @@ import { } from './cron'; import { requireAdmin, requireGoogle, requireGroup } from './guards'; import { handleCallbackQuery } from './handlers/callback.handler'; -import { handleExpenseMessage } from './handlers/message.handler'; +import { routeTextMessage } from './handlers/message.handler'; import { handlePhotoMessage } from './handlers/photo.handler'; import { rateLimitOnResponseError, rateLimitPreRequest } from './rate-limit.hook'; import { sanitizeOutgoingMessages } from './sanitize-outgoing.hook'; @@ -196,10 +196,7 @@ export function createBot(): Bot { // Deterministic expense input is handled locally; everything else may fall through // to AI, which stores its own exact current-turn history row before reading context. - const expenseHandled = await handleExpenseMessage(ctx, bot); - if (!expenseHandled && allowDirectAI) { - await handleAskQuestion(ctx, text, bot); - } + await routeTextMessage(ctx, bot, allowDirectAI); }); // Global error handler — catches unhandled errors in bot middleware/handlers diff --git a/src/integration/expense-flow.integration.test.ts b/src/integration/expense-flow.integration.test.ts index 2159fa0c..2492f4ed 100644 --- a/src/integration/expense-flow.integration.test.ts +++ b/src/integration/expense-flow.integration.test.ts @@ -83,7 +83,11 @@ mock.module('../utils/fuzzy-search', () => ({ normalizeCategoryName: (s: string) => s, })); -mock.module('../bot/commands/ask', () => ({ maybeSmartAdvice: async () => {} })); +const handleAskQuestionMock = mock(async (..._args: unknown[]) => {}); +mock.module('../bot/commands/ask', () => ({ + maybeSmartAdvice: async () => {}, + handleAskQuestion: handleAskQuestionMock, +})); mock.module('../bot/commands/dev', () => ({ consumePendingDesignEdit: () => null, getPipelineInstance: () => null, @@ -162,7 +166,7 @@ mock.module('../database', () => ({ // ── Dynamic imports AFTER all mocks ────────────────────────────────────── -const { handleExpenseMessage } = await import('../bot/handlers/message.handler'); +const { handleExpenseMessage, routeTextMessage } = await import('../bot/handlers/message.handler'); // ── Fixtures ───────────────────────────────────────────────────────────── @@ -183,6 +187,7 @@ afterAll(() => { beforeEach(() => { clearTestDb(db); + handleAskQuestionMock.mockClear(); sentMessages.length = 0; sendMessageMock.mockClear(); appendExpenseRowsMock.mockReset(); @@ -336,3 +341,33 @@ describe('expense-flow integration', () => { expect(appendExpenseRowsMock).not.toHaveBeenCalled(); }); }); + +test('exact October budget replay reaches AI with zero real expense or pending rows', async () => { + seedGroupAndUser(); + const text = `Сформируй бюджет на грядущий октябрь + +€450 — квартира +€600 — еда +€300 — коммуналка +€200 — животные +€200 — машина +€700 — Лена +€700 — Алекс +€100 — развлечения +€620 — подписки +€100 — дом + +Другие категории убери (перечили), сумма должна быть 6000€`; + const ctx = fakeCtx(text); + const bot = fakeBot(); + await routeTextMessage(ctx, bot, true); + expect(handleAskQuestionMock).toHaveBeenCalledTimes(1); + expect(handleAskQuestionMock).toHaveBeenCalledWith(ctx, text, bot); + expect(db.query<{ n: number }, []>('SELECT COUNT(*) AS n FROM expenses').get()?.n).toBe(0); + expect(db.query<{ n: number }, []>('SELECT COUNT(*) AS n FROM pending_expenses').get()?.n).toBe( + 0, + ); + expect(appendExpenseRowsMock).not.toHaveBeenCalled(); + expect(sentMessages).toEqual([]); + expect(logMock.error).not.toHaveBeenCalled(); +}); From 9c740cbe8ae157ecce028584efd00b68eb861e2c Mon Sep 17 00:00:00 2001 From: Alex Ultra Date: Fri, 2 Oct 2026 11:49:05 +0200 Subject: [PATCH 4/4] fix(routing): exclude budget intent from expense fastpath (#121) --- src/bot/handlers/message.handler.test.ts | 118 +++++++++++++++++- src/bot/handlers/message.handler.ts | 18 ++- src/bot/handlers/message.test-support.ts | 3 + src/bot/index.ts | 7 +- .../expense-flow.integration.test.ts | 39 +++++- 5 files changed, 176 insertions(+), 9 deletions(-) diff --git a/src/bot/handlers/message.handler.test.ts b/src/bot/handlers/message.handler.test.ts index 076819b7..3518e0a1 100644 --- a/src/bot/handlers/message.handler.test.ts +++ b/src/bot/handlers/message.handler.test.ts @@ -115,8 +115,10 @@ mock.module('../services/expense-saver', () => ({ // ── ask (maybeSmartAdvice is fire-and-forget advice hook) ── const maybeSmartAdviceMock = mock(() => Promise.resolve()); +const handleAskQuestionMock = mock(() => Promise.resolve()); mock.module('../commands/ask', () => ({ maybeSmartAdvice: maybeSmartAdviceMock, + handleAskQuestion: handleAskQuestionMock, })); // ── dev pipeline — never trigger in these tests ── @@ -243,7 +245,9 @@ mock.module('../services/category-wizard', () => ({ })); // Dynamic-import target — must come AFTER all mock.module calls. -const { handleExpenseMessage, buildBudgetAlertStatus } = await import('./message.handler'); +const { handleExpenseMessage, buildBudgetAlertStatus, routeTextMessage } = await import( + './message.handler' +); // ─── Fixtures ──────────────────────────────────────────────────────────────── @@ -336,6 +340,7 @@ function resetAllMocks(): void { saveExpenseBatchMock.mockReset().mockResolvedValue(); saveReceiptExpensesMock.mockReset().mockResolvedValue(); maybeSmartAdviceMock.mockReset().mockResolvedValue(); + handleAskQuestionMock.mockReset().mockResolvedValue(); isAwaitingCustomCurrencyMock.mockReset().mockReturnValue(false); handleCustomCurrencyInputMock.mockReset().mockResolvedValue(true); handleWizardInputMock.mockReset().mockResolvedValue(false); @@ -791,3 +796,114 @@ describe('handleExpenseMessage — multi-line batch', () => { expect(summaryCall).toBeDefined(); }); }); + +// Budget language is intent, even if every line otherwise matches expense syntax. +describe('budget routing safety regression', () => { + beforeEach(() => { + resetAllMocks(); + mockGroups.findByTelegramGroupId.mockReturnValue(makeGroup()); + mockCategories.exists.mockReturnValue(true); + }); + + test.each([ + 'бюджет', + 'БЮДЖЕТ', + 'бюджета', + 'бюджету', + 'бюджетом', + 'бюджете', + 'бюджеты', + 'бюджетов', + 'бюджетами', + 'бюджетный', + 'budget', + 'BuDgEt', + 'BUDGETS', + ])('refuses all expense writes when %s appears in a parseable line', async (word) => { + const handled = await handleExpenseMessage( + fakeMessageCtx(`10 EUR еда\n20 EUR ${word}`), + fakeBot(), + ); + expect(handled).toBe(false); + expect(mockPendingExpenses.create).not.toHaveBeenCalled(); + expect(saveExpenseBatchMock).not.toHaveBeenCalled(); + expect(sendMessageMock).not.toHaveBeenCalled(); + }); + + test.each([ + 'Составь план\n€450 — квартира', + '€450 — квартира\nУточни остаток', + '\n\n', + '10 EUR еда\nБЮДЖЕТ\n20 EUR дом', + ])('keeps the entire mixed message out of expense writes: %s', async (text) => { + expect(await handleExpenseMessage(fakeMessageCtx(text), fakeBot())).toBe(false); + expect(mockPendingExpenses.create).not.toHaveBeenCalled(); + expect(saveExpenseBatchMock).not.toHaveBeenCalled(); + }); + + test('euro prefix, em dash and blank lines remain valid for pure expenses', async () => { + expect( + await handleExpenseMessage(fakeMessageCtx('\n€450 — квартира\n\n€600 — еда\n'), fakeBot()), + ).toBe(true); + expect(mockPendingExpenses.create).toHaveBeenCalledTimes(2); + expect(saveExpenseBatchMock).toHaveBeenCalledTimes(1); + }); +}); + +describe('production text route forwards budget intent intact', () => { + beforeEach(() => { + resetAllMocks(); + mockGroups.findByTelegramGroupId.mockReturnValue(makeGroup({ active_topic_id: 77 })); + mockCategories.exists.mockReturnValue(true); + }); + + test('exact October plan reaches AI once with original context and zero expense writes', async () => { + const text = `Сформируй бюджет на грядущий октябрь + +€450 — квартира +€600 — еда +€300 — коммуналка +€200 — животные +€200 — машина +€700 — Лена +€700 — Алекс +€100 — развлечения +€620 — подписки +€100 — дом + +Другие категории убери (перечили), сумма должна быть 6000€`; + const ctx = fakeMessageCtx(text, { isForum: true, threadId: 77 }); + const bot = fakeBot(); + await routeTextMessage(ctx, bot, true); + expect(handleAskQuestionMock).toHaveBeenCalledTimes(1); + expect(handleAskQuestionMock).toHaveBeenCalledWith(ctx, text, bot); + expect(mockPendingExpenses.create).not.toHaveBeenCalled(); + expect(saveExpenseBatchMock).not.toHaveBeenCalled(); + expect(saveReceiptExpensesMock).not.toHaveBeenCalled(); + expect(sendMessageMock).not.toHaveBeenCalled(); + }); + + test.each([ + '100 EUR БЮДЖЕТА', + 'Вводный текст\n€450 — квартира', + '€450 — квартира\nЗавершающий текст', + ])('declined fastpath calls AI rather than dropping input: %s', async (text) => { + const ctx = fakeMessageCtx(text, { threadId: 77 }); + const bot = fakeBot(); + await routeTextMessage(ctx, bot, true); + expect(handleAskQuestionMock).toHaveBeenCalledTimes(1); + expect(handleAskQuestionMock).toHaveBeenCalledWith(ctx, text, bot); + expect(mockPendingExpenses.create).not.toHaveBeenCalled(); + }); + + test('pure expenses are saved without invoking AI', async () => { + await routeTextMessage( + fakeMessageCtx('€450 — квартира\n\n€600 — еда', { threadId: 77 }), + fakeBot(), + true, + ); + expect(mockPendingExpenses.create).toHaveBeenCalledTimes(2); + expect(saveExpenseBatchMock).toHaveBeenCalledTimes(1); + expect(handleAskQuestionMock).not.toHaveBeenCalled(); + }); +}); diff --git a/src/bot/handlers/message.handler.ts b/src/bot/handlers/message.handler.ts index 615254a7..0b124309 100644 --- a/src/bot/handlers/message.handler.ts +++ b/src/bot/handlers/message.handler.ts @@ -19,7 +19,7 @@ import { getErrorMessage } from '../../utils/error'; import { findBestCategoryMatchAsync } from '../../utils/fuzzy-search'; import { escapeHtml } from '../../utils/html'; import { createLogger } from '../../utils/logger.ts'; -import { maybeSmartAdvice } from '../commands/ask'; +import { handleAskQuestion, maybeSmartAdvice } from '../commands/ask'; import { consumePendingDesignEdit, getPipelineInstance } from '../commands/dev'; import { consumePendingFeedback, submitFeedback } from '../commands/feedback'; import { showNextPendingCategoryStep } from '../services/category-wizard'; @@ -421,6 +421,10 @@ function parseStrictLines( logger.info(`[MSG] Processing ${lines.length} line(s)`); + if (/(?:^|[^\p{L}])(?:бюджет|budget)\p{L}*(?=$|[^\p{L}])/iu.test(text)) { + logger.info('[MSG] Budget intent — routing the whole message to AI'); + return null; + } const parsedLines = lines.map((line) => parseExpenseMessage(line, defaultCurrency)); if (parsedLines.length === 0 || parsedLines.some((parsed) => !validateParsedExpense(parsed))) { logger.info('[MSG] Mixed/non-canonical message — routing the whole message to AI'); @@ -984,3 +988,15 @@ export function buildBudgetAlertStatus( isWarning: progress.is_warning, }; } + +/** Preserve the full message and context when direct expense entry declines it. */ +export async function routeTextMessage( + ctx: Ctx['Message'], + bot: BotInstance, + allowDirectAI: boolean, +): Promise { + const expenseHandled = await handleExpenseMessage(ctx, bot); + if (!expenseHandled && allowDirectAI && ctx.text) { + await handleAskQuestion(ctx, ctx.text, bot); + } +} diff --git a/src/bot/handlers/message.test-support.ts b/src/bot/handlers/message.test-support.ts index 6a76a9a1..a76a2a58 100644 --- a/src/bot/handlers/message.test-support.ts +++ b/src/bot/handlers/message.test-support.ts @@ -48,8 +48,10 @@ mock.module('../services/expense-saver', () => ({ // ── ask ── export const maybeSmartAdviceMock = mock((_groupId: number) => Promise.resolve()); +export const handleAskQuestionMock = mock((_ctx: unknown, _text: string) => Promise.resolve()); mock.module('../commands/ask', () => ({ maybeSmartAdvice: maybeSmartAdviceMock, + handleAskQuestion: handleAskQuestionMock, })); // ── dev pipeline ── @@ -312,6 +314,7 @@ export function resetAllMocks(): void { saveExpenseBatchMock.mockReset().mockResolvedValue(); saveReceiptExpensesMock.mockReset().mockResolvedValue(); maybeSmartAdviceMock.mockReset().mockResolvedValue(); + handleAskQuestionMock.mockReset().mockResolvedValue(); consumePendingDesignEditMock.mockReset().mockReturnValue(null); getPipelineInstanceMock.mockReset().mockReturnValue(null); consumePendingFeedbackMock.mockReset().mockReturnValue(null); diff --git a/src/bot/index.ts b/src/bot/index.ts index e2dc5db6..41ddcf7d 100644 --- a/src/bot/index.ts +++ b/src/bot/index.ts @@ -38,7 +38,7 @@ import { } from './cron'; import { requireAdmin, requireGoogle, requireGroup } from './guards'; import { handleCallbackQuery } from './handlers/callback.handler'; -import { handleExpenseMessage } from './handlers/message.handler'; +import { routeTextMessage } from './handlers/message.handler'; import { handlePhotoMessage } from './handlers/photo.handler'; import { rateLimitOnResponseError, rateLimitPreRequest } from './rate-limit.hook'; import { sanitizeOutgoingMessages } from './sanitize-outgoing.hook'; @@ -196,10 +196,7 @@ export function createBot(): Bot { // Deterministic expense input is handled locally; everything else may fall through // to AI, which stores its own exact current-turn history row before reading context. - const expenseHandled = await handleExpenseMessage(ctx, bot); - if (!expenseHandled && allowDirectAI) { - await handleAskQuestion(ctx, text, bot); - } + await routeTextMessage(ctx, bot, allowDirectAI); }); // Global error handler — catches unhandled errors in bot middleware/handlers diff --git a/src/integration/expense-flow.integration.test.ts b/src/integration/expense-flow.integration.test.ts index 2159fa0c..2492f4ed 100644 --- a/src/integration/expense-flow.integration.test.ts +++ b/src/integration/expense-flow.integration.test.ts @@ -83,7 +83,11 @@ mock.module('../utils/fuzzy-search', () => ({ normalizeCategoryName: (s: string) => s, })); -mock.module('../bot/commands/ask', () => ({ maybeSmartAdvice: async () => {} })); +const handleAskQuestionMock = mock(async (..._args: unknown[]) => {}); +mock.module('../bot/commands/ask', () => ({ + maybeSmartAdvice: async () => {}, + handleAskQuestion: handleAskQuestionMock, +})); mock.module('../bot/commands/dev', () => ({ consumePendingDesignEdit: () => null, getPipelineInstance: () => null, @@ -162,7 +166,7 @@ mock.module('../database', () => ({ // ── Dynamic imports AFTER all mocks ────────────────────────────────────── -const { handleExpenseMessage } = await import('../bot/handlers/message.handler'); +const { handleExpenseMessage, routeTextMessage } = await import('../bot/handlers/message.handler'); // ── Fixtures ───────────────────────────────────────────────────────────── @@ -183,6 +187,7 @@ afterAll(() => { beforeEach(() => { clearTestDb(db); + handleAskQuestionMock.mockClear(); sentMessages.length = 0; sendMessageMock.mockClear(); appendExpenseRowsMock.mockReset(); @@ -336,3 +341,33 @@ describe('expense-flow integration', () => { expect(appendExpenseRowsMock).not.toHaveBeenCalled(); }); }); + +test('exact October budget replay reaches AI with zero real expense or pending rows', async () => { + seedGroupAndUser(); + const text = `Сформируй бюджет на грядущий октябрь + +€450 — квартира +€600 — еда +€300 — коммуналка +€200 — животные +€200 — машина +€700 — Лена +€700 — Алекс +€100 — развлечения +€620 — подписки +€100 — дом + +Другие категории убери (перечили), сумма должна быть 6000€`; + const ctx = fakeCtx(text); + const bot = fakeBot(); + await routeTextMessage(ctx, bot, true); + expect(handleAskQuestionMock).toHaveBeenCalledTimes(1); + expect(handleAskQuestionMock).toHaveBeenCalledWith(ctx, text, bot); + expect(db.query<{ n: number }, []>('SELECT COUNT(*) AS n FROM expenses').get()?.n).toBe(0); + expect(db.query<{ n: number }, []>('SELECT COUNT(*) AS n FROM pending_expenses').get()?.n).toBe( + 0, + ); + expect(appendExpenseRowsMock).not.toHaveBeenCalled(); + expect(sentMessages).toEqual([]); + expect(logMock.error).not.toHaveBeenCalled(); +});