diff --git a/CLAUDE.md b/CLAUDE.md index 2a5ae51c..85f6697c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -227,6 +227,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..a5ce827c
--- /dev/null
+++ b/src/bot/commands/budget-view.ts
@@ -0,0 +1,228 @@
+// 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 type { CategoryTaAnalysis } from '../../services/analytics/ta/analyzer';
+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;
+}
+
+/** One forecast insight line, or null when the category is not newsworthy. */
+function forecastInsight(cat: CategoryTaAnalysis, row: CategoryRow): string | null {
+  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))) {
+    return null;
+  }
+  const arrow = rising ? '↑' : cat.trend.direction === 'falling' ? '↓' : '→';
+  const warn = cat.anomaly.isAnomaly ? ' ⚠️' : '';
+  return `${getCategoryEmoji(cat.category)} ${escapeHtml(cat.category)}: прогноз ${formatAmount(forecast, row.budget.currency)} ${arrow}${warn}`;
+}
+
+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 insight = forecastInsight(cat, row);
+    if (insight) insights.push(insight);
+  }
+  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 3b715a8f..2e82a084 100644
--- a/src/bot/commands/budget.ts
+++ b/src/bot/commands/budget.ts
@@ -1,22 +1,11 @@
 /** /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 type { Budget, Expense } from '../../database/types';
-import { spendingAnalytics } from '../../services/analytics/spending-analytics';
-import type { CategoryTaAnalysis } from '../../services/analytics/ta/analyzer';
-import type { TechnicalAnalysis } from '../../services/analytics/types';
+
 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,
@@ -25,17 +14,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';
+
 function parsePositiveAmount(numStr: string): number | null {
   const amount = parseFloat(numStr.replace(/[\s,]/g, ''));
   if (Number.isNaN(amount) || amount <= 0) return null;
@@ -145,7 +137,7 @@ export async function handleBudgetCommand(
 
   if (args.length === 0) {
     // Show current budgets and progress
-    await showBudgetProgress(ctx, group);
+    await sendBudgetView(group);
     return;
   }
 
@@ -185,190 +177,21 @@ export async function handleBudgetCommand(
   );
 }
 
-type BudgetProgressRow = {
-  budget: Budget;
-  spent: number;
-  percentage: number;
-  is_exceeded: boolean;
-  is_warning: boolean;
-};
-
-function sumSpendingByCategory(expenses: Expense[]): Record {
-  const categorySpending: Record = {};
-  for (const expense of expenses) {
-    categorySpending[expense.category] =
-      (categorySpending[expense.category] || 0) + expense.eur_amount;
-  }
-  return categorySpending;
-}
-
-/** Per-currency budget/spent totals, in order of first appearance of each currency. */
-function totalsByCurrency(
-  budgets: Budget[],
-  categorySpending: Record,
-): Record {
-  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;
-  }
-  return budgetsByCurrency;
-}
-
-function renderCurrencyTotals(
-  budgetsByCurrency: Record,
-): string {
-  let text = '';
-  for (const [currency, { totalBudget, totalSpent }] of Object.entries(budgetsByCurrency)) {
-    const percentage = totalBudget > 0 ? Math.round((totalSpent / totalBudget) * 100) : 0;
-    text += `Всего (${currency}): ${formatAmount(totalSpent, currency as CurrencyCode)} / ${formatAmount(totalBudget, currency as CurrencyCode)} (${percentage}%)\n`;
-  }
-  return text;
-}
-
-function budgetStatusMarker(row: BudgetProgressRow): string {
-  if (row.is_exceeded) return '(!)';
-  if (row.is_warning) return '(~)';
-  return '';
-}
-
-function renderBudgetRows(rows: BudgetProgressRow[]): string {
-  let text = '';
-  for (const row of rows) {
-    const { budget, spent, percentage } = row;
-    const emoji = getCategoryEmoji(budget.category);
-    text += `${emoji} ${budget.category}: ${formatAmount(spent, budget.currency)} / ${formatAmount(budget.limit_amount, budget.currency)} (${percentage}%) ${budgetStatusMarker(row)}\n`;
-  }
-  return text;
-}
-
-function trendArrow(direction: string): string {
-  if (direction === 'rising') return '↑';
-  if (direction === 'falling') return '↓';
-  return '→';
-}
-
-/** Only categories approaching/exceeding budget, anomalous, or confidently rising are shown. */
-function isForecastNoteworthy(cat: CategoryTaAnalysis, forecastPct: number): boolean {
-  return (
-    forecastPct >= 80 ||
-    cat.anomaly.isAnomaly ||
-    (cat.trend.direction === 'rising' && cat.trend.confidence >= 0.6)
-  );
-}
-
-function buildForecastInsights(
-  analysis: TechnicalAnalysis,
-  budgetProgress: BudgetProgressRow[],
-): string[] {
-  const taInsights: string[] = [];
-  for (const cat of analysis.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 forecastPct =
-      bp.budget.limit_amount > 0 ? Math.round((forecast / bp.budget.limit_amount) * 100) : 0;
-    if (!isForecastNoteworthy(cat, forecastPct)) continue;
-
-    let insight = `${getCategoryEmoji(cat.category)} ${cat.category}: прогноз ${formatAmount(forecast, bp.budget.currency)} ${trendArrow(cat.trend.direction)}`;
-    if (cat.anomaly.isAnomaly) insight += ' ⚠️';
-    taInsights.push(insight);
-  }
-  return taInsights;
-}
-
-/**
- * Cap at 10 lines so the full budget message stays under Telegram's 4096-char
- * limit. N+2 rule for the "и ещё N" tail.
- */
-function renderForecastSection(taInsights: string[]): string {
-  if (taInsights.length === 0) return '';
-  const MAX_TA_INSIGHTS = 10;
-  const hidden = taInsights.length - MAX_TA_INSIGHTS;
-  const visibleInsights = hidden >= 3 ? taInsights.slice(0, MAX_TA_INSIGHTS) : taInsights;
-  let text = `\nПрогноз на месяц:\n${visibleInsights.join('\n')}\n`;
-  if (hidden >= 3) {
-    text += `… и ещё ${hidden}\n`;
-  }
-  return text;
-}
-
-/**
- * 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 = sumSpendingByCategory(expenses);
-
-  const budgets = database.budgets.getAllBudgetsForMonth(groupId, currentMonth);
-
-  if (budgets.length === 0) {
-    return { text: `Бюджет на ${currentMonthName}\n\nБюджеты не установлены.`, hasBudgets: false };
-  }
-
-  let message = `Бюджет на ${currentMonthName}\n\n`;
-  message += renderCurrencyTotals(totalsByCurrency(budgets, categorySpending));
-  message += '\n';
-
-  const budgetProgress: BudgetProgressRow[] = 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);
-  message += renderBudgetRows(budgetProgress);
-
-  // TA forecast insights for budgeted categories
-  const snapshot = spendingAnalytics.getFinancialSnapshot(groupId);
-  if (snapshot.technicalAnalysis) {
-    message += renderForecastSection(
-      buildForecastInsights(snapshot.technicalAnalysis, budgetProgress),
-    );
-  }
-
-  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);
 }
 
@@ -412,22 +235,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 64527eec..4b28a677 100644
--- a/src/bot/cron.test.ts
+++ b/src/bot/cron.test.ts
@@ -129,14 +129,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';
@@ -289,9 +289,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();
   });
@@ -492,8 +492,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,
     });
 
@@ -506,6 +506,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([
       {
@@ -522,7 +558,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 1fc20ec6..21ba9f3e 100644
--- a/src/bot/cron.ts
+++ b/src/bot/cron.ts
@@ -18,9 +18,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';
 
@@ -136,34 +136,6 @@ async function createMonthTab(
   }
 }
 
-function buildMonthlyNotifyText(
-  sheetUrl: string,
-  newYearUrl: string | null,
-  year: number,
-  budget: { text: string; hasBudgets: boolean },
-): string {
-  const yearSuffix = newYearUrl ? ` (${year})` : '';
-  if (budget.hasBudgets) {
-    return (
-      `Новый бюджет сформирован\n\n🔗 Гугл таблица${yearSuffix}` +
-      `\n\n${budget.text}` +
-      `\n\nРедактировать бюджет можно через ИИ или командами:\n${BUDGET_EDIT_HINT}`
-    );
-  }
-  return (
-    `Пора сформировать бюджет\n\n🔗 Гугл таблица${yearSuffix}` +
-    `\n\nЗаполни вкладку в таблице или используй команды:\n${BUDGET_EDIT_HINT}`
-  );
-}
-
-/** Telegram message limit is 4096 chars — truncate at last newline boundary, close tags. */
-function truncateNotifyText(notifyText: string, sheetUrl: string): string {
-  if (notifyText.length <= 4000) return notifyText;
-  const cut = notifyText.lastIndexOf('\n', 3900);
-  const truncated = cut > 0 ? notifyText.slice(0, cut) : notifyText.slice(0, 3900);
-  return closeUnmatchedTags(`${truncated}\n...\n\n🔗 Гугл таблица`);
-}
-
 /** Create this month's tab for one group and notify it; skips when the tab already exists. */
 async function cloneMonthForGroup(group: Group, year: number, month: MonthAbbr): Promise {
   const conn = googleConn(group);
@@ -181,14 +153,24 @@ async function cloneMonthForGroup(group: Group, year: number, month: MonthAbbr):
   await silentSyncBudgets(conn, group.id);
 
   const sheetUrl = newYearUrl ?? getSpreadsheetUrl(spreadsheetId);
-  const notifyText = truncateNotifyText(
-    buildMonthlyNotifyText(sheetUrl, newYearUrl, year, formatBudgetProgressText(group.id)),
-    sheetUrl,
-  );
-
-  await withChatContext(group.telegram_group_id, group.active_topic_id, () =>
-    sendMessage(notifyText),
-  ).catch((err: unknown) => logger.error({ err }, `[CRON] Failed to notify group ${group.id}`));
+  const { messages: budgetMessages, hasBudgets } = formatBudgetProgress(group.id);
+  const yearSuffix = newYearUrl ? ` (${year})` : '';
+  const sheetLink = `🔗 Гугл таблица${yearSuffix}`;
+
+  const blocks = hasBudgets
+    ? [
+        `Новый бюджет сформирован\n\n${sheetLink}`,
+        ...budgetMessages,
+        `Редактировать бюджет можно через ИИ или командами:\n${BUDGET_EDIT_HINT}`,
+      ]
+    : [
+        `Пора сформировать бюджет\n\n${sheetLink}\n\n` +
+          `Заполни вкладку в таблице или используй команды:\n${BUDGET_EDIT_HINT}`,
+      ];
+
+  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}`));
 }
 
 export function registerMonthlyCron(): void {
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.flows.test.ts b/src/bot/handlers/callback.flows.test.ts
index 89674425..0432d779 100644
--- a/src/bot/handlers/callback.flows.test.ts
+++ b/src/bot/handlers/callback.flows.test.ts
@@ -6,7 +6,6 @@ import { beforeEach, describe, expect, test } from 'bun:test';
 import { getCurrencySymbol, MESSAGES } from '../../config/constants';
 import {
   answeredTexts,
-  budgetPromptKeyboardMock,
   categoriesListKeyboardMock,
   dispatch,
   fakeBot,
@@ -26,6 +25,7 @@ import {
   runCallback,
   saveExpenseBatchMock,
   saveReceiptExpensesMock,
+  sendBudgetPromptsMock,
   sendMessageMock,
   setBudgetMock,
   showNextItemMock,
@@ -192,13 +192,12 @@ describe('category:add', () => {
       takeQueuedCategoryBudgetPromptsMock.mockImplementation(() => ['Животные', 'Еда']);
       await dispatch('category:add:77');
       expect(takeQueuedCategoryBudgetPromptsMock).toHaveBeenCalledWith(10, 500);
-      expect(budgetPromptKeyboardMock).toHaveBeenCalledWith('Животные', 'EUR');
-      expect(budgetPromptKeyboardMock).toHaveBeenCalledWith('Еда', 'EUR');
-      expect(sendMessageMock).toHaveBeenCalledTimes(2);
-      expect(sendMessageMock).toHaveBeenCalledWith(
-        '💰 Хочешь установить бюджет для категории "Животные"?',
-        { reply_markup: { inline_keyboard: [[{ text: 'Животные/EUR', callback_data: 'x' }]] } },
-      );
+      expect(sendBudgetPromptsMock).toHaveBeenCalledTimes(1);
+      expect(sendBudgetPromptsMock).toHaveBeenCalledWith({
+        group: expect.objectContaining({ id: 1, default_currency: 'EUR' }),
+        userId: 10,
+        categories: ['Животные', 'Еда'],
+      });
     });
 
     test('wizard still has steps → no budget prompts are taken', async () => {
@@ -330,10 +329,11 @@ describe('category:choose', () => {
       showNextPendingCategoryStepMock.mockImplementation(() => Promise.resolve(false));
       takeQueuedCategoryBudgetPromptsMock.mockImplementation(() => ['Еда']);
       await dispatch('category:choose:77:3');
-      expect(sendMessageMock).toHaveBeenCalledWith(
-        '💰 Хочешь установить бюджет для категории "Еда"?',
-        { reply_markup: { inline_keyboard: [[{ text: 'Еда/EUR', callback_data: 'x' }]] } },
-      );
+      expect(sendBudgetPromptsMock).toHaveBeenCalledWith({
+        group: expect.objectContaining({ id: 1, default_currency: 'EUR' }),
+        userId: 10,
+        categories: ['Еда'],
+      });
     });
   });
 });
diff --git a/src/bot/handlers/callback.handler.test.ts b/src/bot/handlers/callback.handler.test.ts
index e9cc53f8..1a8343bf 100644
--- a/src/bot/handlers/callback.handler.test.ts
+++ b/src/bot/handlers/callback.handler.test.ts
@@ -117,8 +117,49 @@ 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,
+  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,
 }));
 
 const devMock = mock(() => Promise.resolve());
@@ -165,7 +206,6 @@ mock.module('../services/sheet-errors', () => ({
 }));
 
 mock.module('../keyboards', () => ({
-  createBudgetPromptKeyboard: mock(() => ({ inline_keyboard: [] })),
   createCategoriesListKeyboard: mock(() => ({ inline_keyboard: [] })),
   createCategoryConfirmKeyboard: mock(() => ({ inline_keyboard: [] })),
 }));
@@ -262,6 +302,11 @@ const resetables: ReturnType[] = [
   queueCategoryBudgetPromptMock,
   showNextPendingCategoryStepMock,
   takeQueuedCategoryBudgetPromptsMock,
+  sendBudgetViewMock,
+  lookupPromptMock,
+  applyPromptMock,
+  skipPromptMock,
+  sendBudgetPromptMock,
   devMock,
   mockMerchantRules.updateStatus,
   mockGroups.findByTelegramGroupId,
@@ -299,6 +344,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 +700,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 823e3ddd..ed58d6c5 100644
--- a/src/bot/handlers/callback.handler.ts
+++ b/src/bot/handlers/callback.handler.ts
@@ -2,6 +2,7 @@
 import { createLogger } from '../../utils/logger.ts';
 import { handleDevCallback } from '../commands/dev';
 import { handleSettingsCallback } from '../commands/settings';
+
 import type { BotInstance, Ctx } from '../types';
 import { BANK_ROUTES } from './callback/bank-routes';
 import { handleBudgetAction } from './callback/budget';
diff --git a/src/bot/handlers/callback.test-support.ts b/src/bot/handlers/callback.test-support.ts
index 27840b1e..3c8f2134 100644
--- a/src/bot/handlers/callback.test-support.ts
+++ b/src/bot/handlers/callback.test-support.ts
@@ -117,6 +117,7 @@ mock.module('../commands/connect', () => connectMocks);
 // '' for the sentinel 'bad' lets tests pin the `|| group.default_currency` fallback.
 mock.module('../commands/budget', () => ({
   normalizeCurrency: (s: string) => (s === 'bad' ? '' : s.toUpperCase()),
+  sendBudgetView: mock(() => Promise.resolve()),
 }));
 
 export const devMock = mock(() => Promise.resolve());
@@ -157,16 +158,23 @@ mock.module('../services/sheet-errors', () => ({
   getSheetErrorMessage: (_e: unknown) => 'sheet error',
 }));
 
-export const budgetPromptKeyboardMock = mock((category: string, currency: string) => ({
-  inline_keyboard: [[{ text: `${category}/${currency}`, callback_data: 'x' }]],
-}));
+export const sendBudgetPromptsMock = mock((_params: unknown) => Promise.resolve());
 export const categoriesListKeyboardMock = mock((_categories: unknown, pendingId: number) => ({
   inline_keyboard: [[{ text: `list/${pendingId}`, callback_data: 'x' }]],
 }));
 mock.module('../keyboards', () => ({
-  createBudgetPromptKeyboard: budgetPromptKeyboardMock,
   createCategoriesListKeyboard: categoriesListKeyboardMock,
   createCategoryConfirmKeyboard: mock(() => ({ inline_keyboard: [] })),
+  createBudgetSuggestionKeyboard: mock(() => ({ inline_keyboard: [] })),
+  createBudgetViewKeyboard: mock(() => ({ inline_keyboard: [] })),
+  createAddCategoryWithBudgetKeyboard: mock(() => ({ inline_keyboard: [] })),
+}));
+mock.module('../services/budget-prompt', () => ({
+  sendBudgetPrompts: sendBudgetPromptsMock,
+  handleBudgetPromptText: mock(() => Promise.resolve(false)),
+  applyBudgetPrompt: mock(() => Promise.resolve()),
+  lookupPromptForCallback: mock(() => null),
+  skipBudgetPrompt: mock(() => Promise.resolve()),
 }));
 
 export const getPendingCategoryExpenseMock = mock<
@@ -241,6 +249,7 @@ mock.module('../../services/receipt/receipt-summarizer', () => ({
 // Wrapping makes the normalization observable: tests assert the wrapped value is persisted.
 mock.module('../../utils/fuzzy-search', () => ({
   normalizeCategoryName: (s: string) => `N(${s})`,
+  findBestCategoryMatch: (_input: string, _categories: string[]): string | null => null,
 }));
 
 // ─── Domain fixtures ──────────────────────────────────────────────────────────
@@ -383,7 +392,7 @@ const resettable: Array<{ mockReset(): void }> = [
   queueCategoryBudgetPromptMock,
   showNextPendingCategoryStepMock,
   takeQueuedCategoryBudgetPromptsMock,
-  budgetPromptKeyboardMock,
+  sendBudgetPromptsMock,
   categoriesListKeyboardMock,
   trackMembershipMock,
   getSyncCachedResultMock,
@@ -445,9 +454,7 @@ export function resetCallbackMocks(): void {
   summaryToCategoryMapMock.mockImplementation(() => new Map());
   getSyncCachedResultMock.mockImplementation(() => null);
   getBudgetSyncCachedResultMock.mockImplementation(() => null);
-  budgetPromptKeyboardMock.mockImplementation((category, currency) => ({
-    inline_keyboard: [[{ text: `${category}/${currency}`, callback_data: 'x' }]],
-  }));
+  sendBudgetPromptsMock.mockImplementation(() => Promise.resolve());
   categoriesListKeyboardMock.mockImplementation((_categories, pendingId) => ({
     inline_keyboard: [[{ text: `list/${pendingId}`, callback_data: 'x' }]],
   }));
diff --git a/src/bot/handlers/callback/budget.ts b/src/bot/handlers/callback/budget.ts
index 591669d4..3881a36c 100644
--- a/src/bot/handlers/callback/budget.ts
+++ b/src/bot/handlers/callback/budget.ts
@@ -6,6 +6,7 @@ import type { Group } from '../../../database/types';
 import { getBudgetManager } from '../../../services/budget-manager';
 import { normalizeCurrency } from '../../commands/budget';
 import type { BotInstance } from '../../types';
+import { handleBudgetPromptCallback } from '../budget-callbacks';
 import { type CallbackCtx, deletePromptMessage, resolveUserGroup } from './shared';
 
 const DEFAULT_BUDGET_AMOUNT = 100;
@@ -115,10 +116,24 @@ export async function handleBudgetAction(
   telegramId: number,
   bot: BotInstance,
 ): Promise {
-  const [subAction, category, ...rest] = params;
+  const [subAction, ...promptArgs] = params;
   const resolved = await resolveUserGroup(ctx, telegramId);
   if (!resolved) return;
 
+  // Smart budget-setup prompt buttons (budget:psuggest|pskip|view:…)
+  if (subAction === 'psuggest' || subAction === 'pskip' || subAction === 'view') {
+    await handleBudgetPromptCallback(
+      ctx,
+      bot,
+      subAction,
+      promptArgs,
+      resolved.group,
+      resolved.user,
+    );
+    return;
+  }
+
+  const [category, ...rest] = promptArgs;
   const handler = BUDGET_ACTIONS.get(subAction ?? '');
   if (!handler) {
     await ctx.answerCallbackQuery({ text: 'Unknown budget action' });
diff --git a/src/bot/handlers/callback/category.ts b/src/bot/handlers/callback/category.ts
index 676d0c0a..9ab48362 100644
--- a/src/bot/handlers/callback/category.ts
+++ b/src/bot/handlers/callback/category.ts
@@ -9,7 +9,8 @@ import { database } from '../../../database';
 import type { PendingExpense } from '../../../database/types';
 import { sendMessage } from '../../../services/bank/telegram-sender';
 import { createLogger } from '../../../utils/logger.ts';
-import { createBudgetPromptKeyboard, createCategoriesListKeyboard } from '../../keyboards';
+import { createCategoriesListKeyboard } from '../../keyboards';
+import { sendBudgetPrompts } from '../../services/budget-prompt';
 import {
   getPendingCategoryExpense,
   getPendingCategorySiblings,
@@ -58,12 +59,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)) {
-    const keyboard = createBudgetPromptKeyboard(category, group.default_currency);
-    await sendMessage(`💰 Хочешь установить бюджет для категории "${category}"?`, {
-      reply_markup: keyboard,
-    });
-  }
+  await sendBudgetPrompts({
+    group,
+    userId,
+    categories: takeQueuedCategoryBudgetPrompts(userId, sourceMessageId),
+  });
 }
 
 /** Delete the wizard prompt; a failure is logged and never aborts the flow. */
diff --git a/src/bot/handlers/message.handler.test.ts b/src/bot/handlers/message.handler.test.ts
index 3518e0a1..58cbcf83 100644
--- a/src/bot/handlers/message.handler.test.ts
+++ b/src/bot/handlers/message.handler.test.ts
@@ -239,6 +239,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,
@@ -371,6 +384,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();
@@ -771,6 +785,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 0b124309..f39e152b 100644
--- a/src/bot/handlers/message.handler.ts
+++ b/src/bot/handlers/message.handler.ts
@@ -22,6 +22,7 @@ import { createLogger } from '../../utils/logger.ts';
 import { handleAskQuestion, 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';
@@ -361,6 +362,23 @@ async function consumeCategoryInputStage(msg: UserMessage): Promise {
+  if (!msg.text || msg.text.startsWith('/')) return null;
+  const replyToMessageId = msg.ctx.update?.message?.reply_to_message?.message_id;
+  const messageThreadId = msg.ctx.update?.message?.message_thread_id;
+  const consumed = await handleBudgetPromptText({
+    group: msg.group,
+    user: msg.user,
+    text: msg.text,
+    replyToMessageId: replyToMessageId ?? null,
+    messageThreadId: messageThreadId ?? null,
+  });
+  return consumed ? true : null;
+}
 /** Bank transaction edit flow — route replies to pending edit transactions */
 async function consumeBankEditReply(msg: UserMessage): Promise {
   const replyToMessageId = msg.ctx.update?.message?.reply_to_message?.message_id;
@@ -396,6 +414,7 @@ const AWAITED_INPUT_STAGES: Array> = [
   consumeFeedbackInput,
   consumeBulkCorrectionStage,
   consumeCategoryInputStage,
+  consumeBudgetPromptText,
   consumeBankEditReply,
   consumePaymentLinks,
 ];
diff --git a/src/bot/handlers/message.test-support.ts b/src/bot/handlers/message.test-support.ts
index a76a2a58..91e85e98 100644
--- a/src/bot/handlers/message.test-support.ts
+++ b/src/bot/handlers/message.test-support.ts
@@ -196,6 +196,16 @@ export const mockChatMessages = {
   ),
 };
 
+export const mockBudgets = {
+  getAllBudgetsForMonth: mock(() => []),
+};
+export const mockBudgetPrompts = {
+  findActiveForUser: mock(() => null),
+  findByMessageId: mock(() => null),
+};
+mock.module('../services/budget-prompt', () => ({
+  handleBudgetPromptText: mock(() => Promise.resolve(false)),
+}));
 mock.module('../../database', () => ({
   database: {
     groups: mockGroups,
@@ -207,7 +217,10 @@ mock.module('../../database', () => ({
     groupMembers: mockGroupMembers,
     devTasks: mockDevTasks,
     chatMessages: mockChatMessages,
+    budgets: mockBudgets,
+    budgetPrompts: mockBudgetPrompts,
   },
+  _budgetWriter: () => mockBudgets,
 }));
 
 // ─── Fixtures ────────────────────────────────────────────────────────────────
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..e8ae8595
--- /dev/null
+++ b/src/bot/services/budget-prompt.test.ts
@@ -0,0 +1,375 @@
+// 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),
+  getBudgetCandidatesForMonth: 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 { afterEach, beforeEach, describe, expect, setSystemTime, test } from 'bun:test';
+import type { Group, User } from '../../database/types';
+
+const {
+  applyBudgetPrompt,
+  handleBudgetPromptText,
+  lookupPromptForCallback,
+  sendBudgetPrompt,
+  sendBudgetPrompts,
+  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.getBudgetCandidatesForMonth.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');
+  });
+});
+
+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
new file mode 100644
index 00000000..81f02852
--- /dev/null
+++ b/src/bot/services/budget-prompt.ts
@@ -0,0 +1,240 @@
+// 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,
+  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';
+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;
+  suggestions?: BudgetSuggestions;
+  now?: Date;
+}): Promise {
+  const { group, userId, category } = params;
+  const currency = group.default_currency;
+  const threadId = chatStorage.getStore()?.threadId ?? null;
+  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({
+    group_id: group.id,
+    user_id: userId,
+    category,
+    currency,
+    target_month: format(now, 'yyyy-MM'),
+    message_thread_id: threadId,
+  });
+
+  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,
+  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 (!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: prompt.target_month,
+      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 13ab9bae..16f271f0 100644
--- a/src/database/index.ts
+++ b/src/database/index.ts
@@ -8,6 +8,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';
@@ -39,6 +40,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;
@@ -68,6 +70,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/migrations/budget-prompts.ts b/src/database/migrations/budget-prompts.ts
new file mode 100644
index 00000000..af56a960
--- /dev/null
+++ b/src/database/migrations/budget-prompts.ts
@@ -0,0 +1,46 @@
+// Migrations 056-057: persistent budget setup prompts (#123). Renumbered from the abandoned
+// feat/budget-setup-ux-123 branch (052/053 there) because main already shipped its own 052-055.
+// Migration names are the contract with already-migrated databases; these never shipped.
+
+import { migrationLogger as logger } from './migration-logger';
+import type { Migration } from './types';
+
+export const budgetPromptMigrations: Migration[] = [
+  {
+    name: '056_create_budget_prompts',
+    up: (db) => {
+      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');
+    },
+  },
+  {
+    name: '057_budget_prompt_target_month',
+    up: (db) => {
+      db.exec('ALTER TABLE budget_prompts ADD COLUMN target_month TEXT');
+    },
+  },
+];
diff --git a/src/database/migrations/index.ts b/src/database/migrations/index.ts
index dd4c54bc..c46972fd 100644
--- a/src/database/migrations/index.ts
+++ b/src/database/migrations/index.ts
@@ -4,6 +4,7 @@
 import { aiTrajectoryAndUsageMigrations } from './ai-trajectories-and-usage';
 import { analyticsAndDevTaskMigrations } from './analytics-and-dev-tasks';
 import { bankIntegrationMigrations } from './bank-integration';
+import { budgetPromptMigrations } from './budget-prompts';
 import { coreTableMigrations } from './core-tables';
 import { groupMemberAndReceiptMigrations } from './group-members-and-receipts';
 import { photoQueueAndReceiptItemMigrations } from './photo-queue-and-receipt-items';
@@ -18,4 +19,5 @@ export const migrations: Migration[] = [
   ...snapshotAndDataFixMigrations,
   ...groupMemberAndReceiptMigrations,
   ...aiTrajectoryAndUsageMigrations,
+  ...budgetPromptMigrations,
 ];
diff --git a/src/database/repositories/ai-usage-events.repository.test.ts b/src/database/repositories/ai-usage-events.repository.test.ts
index e5a33f73..16689b8f 100644
--- a/src/database/repositories/ai-usage-events.repository.test.ts
+++ b/src/database/repositories/ai-usage-events.repository.test.ts
@@ -91,7 +91,11 @@ describe('migration 053_create_ai_usage_events', () => {
     expect(at).toBeGreaterThanOrEqual(0);
     expect(names[at + 1]).toBe('054_add_role_preset_cost_to_ai_usage_events');
     expect(names[at + 2]).toBe('055_add_timing_and_prompt_size_to_ai_usage_events');
-    expect(names.at(-1)).toBe('055_add_timing_and_prompt_size_to_ai_usage_events');
+    // Later migrations are appended after 055 (budget prompts 056-057, …) — never reordered.
+    expect(names.at(-1)).not.toBe('055_add_timing_and_prompt_size_to_ai_usage_events');
+    expect(names.lastIndexOf('055_add_timing_and_prompt_size_to_ai_usage_events')).toBeGreaterThan(
+      at,
+    );
   });
 
   it('creates the table with exactly the usage columns and no user-identifying column', () => {
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..b0efe7f9
--- /dev/null
+++ b/src/database/repositories/budget-prompt.repository.test.ts
@@ -0,0 +1,145 @@
+// 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',
+    target_month: '2026-10',
+    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',
+      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]);
+    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..5c3f7793
--- /dev/null
+++ b/src/database/repositories/budget-prompt.repository.ts
@@ -0,0 +1,171 @@
+// 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, string]>(`
+        INSERT INTO budget_prompts (
+          group_id,
+          user_id,
+          category,
+          currency,
+          message_thread_id,
+          target_month
+        )
+        VALUES (?, ?, ?, ?, ?, ?)
+        RETURNING id
+      `)
+      .get(
+        data.group_id,
+        data.user_id,
+        data.category,
+        data.currency,
+        data.message_thread_id ?? null,
+        data.target_month,
+      );
+
+    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/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-migrations.golden.json b/src/database/schema-migrations.golden.json
index 2ccd1b24..2d90b308 100644
--- a/src/database/schema-migrations.golden.json
+++ b/src/database/schema-migrations.golden.json
@@ -1,61 +1,4 @@
 {
-  "migrations": [
-    "001_create_users_table",
-    "002_create_categories_table",
-    "003_create_pending_expenses_table",
-    "004_create_expenses_table",
-    "005_create_groups_and_refactor",
-    "006_rename_usd_to_eur",
-    "007_create_budgets_table",
-    "008_create_chat_messages_table",
-    "009_add_custom_prompt_to_groups",
-    "010_create_photo_processing_queue",
-    "011_create_receipt_items",
-    "012_create_expense_items",
-    "013_add_message_thread_id_to_photo_queue",
-    "014_add_waiting_for_category_input",
-    "015_add_skipped_status_to_receipt_items",
-    "016_add_summary_mode_to_photo_queue",
-    "017_add_active_topic_id_to_groups",
-    "018_add_analytics_indexes_and_advice_log",
-    "019_create_dev_tasks_table",
-    "020_add_failed_at_state_to_dev_tasks",
-    "021_create_bank_connections",
-    "022_create_bank_credentials",
-    "023_create_bank_plugin_state",
-    "024_create_bank_accounts",
-    "025_create_bank_transactions",
-    "026_create_merchant_tables",
-    "028_add_prefill_to_bank_transactions",
-    "027_add_bank_panel_summary_to_groups",
-    "029_create_group_spreadsheets",
-    "030_create_bank_otp_requests",
-    "031_add_awaiting_comment_to_bank_transactions",
-    "032_add_time_to_bank_transactions",
-    "033_add_is_excluded_to_bank_accounts",
-    "034_add_account_id_to_bank_transactions",
-    "035_backfill_account_id_in_bank_transactions",
-    "036_create_recurring_patterns",
-    "037_encrypt_existing_refresh_tokens",
-    "038_create_sync_snapshots",
-    "039_add_composite_indexes",
-    "040_create_dashboard_widgets",
-    "041_add_receipt_file_id_to_expenses",
-    "042_add_oauth_client_to_groups",
-    "043_fix_default_enabled_currencies",
-    "044_add_invoice_to_bank_transactions",
-    "045_fix_corrupted_eur_amounts",
-    "046_create_group_members",
-    "047_create_receipts_table",
-    "048_add_expenses_receipt_id_index",
-    "049_add_bank_transactions_matched_receipt_id",
-    "050_add_bank_cards_enabled_to_groups",
-    "051_scope_chat_history_by_topic",
-    "052_create_agent_trajectories",
-    "053_create_ai_usage_events",
-    "054_add_role_preset_cost_to_ai_usage_events",
-    "055_add_timing_and_prompt_size_to_ai_usage_events"
-  ],
   "objects": [
     {
       "type": "table",
@@ -602,6 +545,83 @@
       "name": "idx_ai_usage_events_provider_at",
       "tbl_name": "ai_usage_events",
       "sql": "CREATE INDEX idx_ai_usage_events_provider_at\n          ON ai_usage_events(provider, at)\n        "
+    },
+    {
+      "type": "table",
+      "name": "budget_prompts",
+      "tbl_name": "budget_prompts",
+      "sql": "CREATE TABLE budget_prompts (\n            id INTEGER PRIMARY KEY AUTOINCREMENT,\n            group_id INTEGER NOT NULL,\n            user_id INTEGER NOT NULL,\n            category TEXT NOT NULL,\n            currency TEXT NOT NULL,\n            telegram_message_id INTEGER,\n            message_thread_id INTEGER,\n            status TEXT NOT NULL DEFAULT 'active'\n              CHECK(status IN ('active', 'used', 'skipped')),\n            created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,\n            updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, target_month TEXT,\n            FOREIGN KEY (group_id) REFERENCES groups(id) ON DELETE CASCADE,\n            FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE\n          )"
+    },
+    {
+      "type": "index",
+      "name": "idx_budget_prompts_active_user",
+      "tbl_name": "budget_prompts",
+      "sql": "CREATE INDEX idx_budget_prompts_active_user\n          ON budget_prompts(group_id, user_id, status, created_at)\n        "
+    },
+    {
+      "type": "index",
+      "name": "idx_budget_prompts_message",
+      "tbl_name": "budget_prompts",
+      "sql": "CREATE INDEX idx_budget_prompts_message\n          ON budget_prompts(telegram_message_id)\n        "
     }
+  ],
+  "migrations": [
+    "001_create_users_table",
+    "002_create_categories_table",
+    "003_create_pending_expenses_table",
+    "004_create_expenses_table",
+    "005_create_groups_and_refactor",
+    "006_rename_usd_to_eur",
+    "007_create_budgets_table",
+    "008_create_chat_messages_table",
+    "009_add_custom_prompt_to_groups",
+    "010_create_photo_processing_queue",
+    "011_create_receipt_items",
+    "012_create_expense_items",
+    "013_add_message_thread_id_to_photo_queue",
+    "014_add_waiting_for_category_input",
+    "015_add_skipped_status_to_receipt_items",
+    "016_add_summary_mode_to_photo_queue",
+    "017_add_active_topic_id_to_groups",
+    "018_add_analytics_indexes_and_advice_log",
+    "019_create_dev_tasks_table",
+    "020_add_failed_at_state_to_dev_tasks",
+    "021_create_bank_connections",
+    "022_create_bank_credentials",
+    "023_create_bank_plugin_state",
+    "024_create_bank_accounts",
+    "025_create_bank_transactions",
+    "026_create_merchant_tables",
+    "028_add_prefill_to_bank_transactions",
+    "027_add_bank_panel_summary_to_groups",
+    "029_create_group_spreadsheets",
+    "030_create_bank_otp_requests",
+    "031_add_awaiting_comment_to_bank_transactions",
+    "032_add_time_to_bank_transactions",
+    "033_add_is_excluded_to_bank_accounts",
+    "034_add_account_id_to_bank_transactions",
+    "035_backfill_account_id_in_bank_transactions",
+    "036_create_recurring_patterns",
+    "037_encrypt_existing_refresh_tokens",
+    "038_create_sync_snapshots",
+    "039_add_composite_indexes",
+    "040_create_dashboard_widgets",
+    "041_add_receipt_file_id_to_expenses",
+    "042_add_oauth_client_to_groups",
+    "043_fix_default_enabled_currencies",
+    "044_add_invoice_to_bank_transactions",
+    "045_fix_corrupted_eur_amounts",
+    "046_create_group_members",
+    "047_create_receipts_table",
+    "048_add_expenses_receipt_id_index",
+    "049_add_bank_transactions_matched_receipt_id",
+    "050_add_bank_cards_enabled_to_groups",
+    "051_scope_chat_history_by_topic",
+    "052_create_agent_trajectories",
+    "053_create_ai_usage_events",
+    "054_add_role_preset_cost_to_ai_usage_events",
+    "055_add_timing_and_prompt_size_to_ai_usage_events",
+    "056_create_budget_prompts",
+    "057_budget_prompt_target_month"
   ]
 }
diff --git a/src/database/types.ts b/src/database/types.ts
index 05380117..102d73f1 100644
--- a/src/database/types.ts
+++ b/src/database/types.ts
@@ -162,6 +162,32 @@ 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;
+  target_month: string | null;
+  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;
+  target_month: string;
+  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 2492f4ed..fe02564e 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-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.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..24461417
--- /dev/null
+++ b/src/services/budget-suggestions.ts
@@ -0,0 +1,216 @@
+// 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 type { Budget } from '../database/types';
+import { findBestCategoryMatch } from '../utils/fuzzy-search';
+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');
+}
+
+/** 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 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 one category, using the same snapshot path as wizard batches. */
+export function suggestBudgetAmounts(
+  groupId: number,
+  category: string,
+  currency: CurrencyCode,
+  now: Date = new Date(),
+): BudgetSuggestions {
+  return (
+    suggestBudgetAmountsBatch(groupId, [category], currency, now).get(category) ?? { options: [] }
+  );
+}
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 a2be92ae..19844b76 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,
@@ -638,3 +639,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 e9940377..7b6e2518 100644 --- a/src/utils/html.ts +++ b/src/utils/html.ts @@ -523,6 +523,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()}`; +}