Skip to content

Open-source personal finance manager. Self-hosted, privacy-first.

feat(budgets): suggest budget limits from previous months (#1295)

Tássio Noronhab4d1937896dd
diff --git a/backend/app/api/budgets.py b/backend/app/api/budgets.py
index 89bb87c5..8567dbc2 100644
--- a/backend/app/api/budgets.py
+++ b/backend/app/api/budgets.py
@@ -11,7 +11,14 @@ from app.core.workspace_context import (
current_workspace,
current_writable_workspace,
)
-from app.schemas.budget import BudgetCreate, BudgetRead, BudgetUpdate, BudgetVsActual
+from app.schemas.budget import (
+ BudgetBatchCreate,
+ BudgetCreate,
+ BudgetRead,
+ BudgetSuggestionResponse,
+ BudgetUpdate,
+ BudgetVsActual,
+)
from app.services import budget_service
router = APIRouter(prefix="/api/budgets", tags=["budgets"])
@@ -38,6 +45,34 @@ async def create_budget(
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
+ "/batch", response_model=list[BudgetRead], status_code=status.HTTP_201_CREATED
+)
+async def create_budgets_batch(
+ data: BudgetBatchCreate,
+ ctx: WorkspaceContext = Depends(current_writable_workspace),
+ session: AsyncSession = Depends(get_async_session),
+):
+ try:
+ return await budget_service.create_budgets_batch(
+ session, ctx.workspace.id, ctx.user_id, data
+ )
+ except ValueError as e:
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
+
+
[email protected]("/suggestions", response_model=BudgetSuggestionResponse)
+async def budget_suggestions(
+ month: Optional[date] = Query(None),
+ months: int = Query(3, ge=1, le=24),
+ ctx: WorkspaceContext = Depends(current_workspace),
+ session: AsyncSession = Depends(get_async_session),
+):
+ return await budget_service.get_budget_suggestions(
+ session, ctx.workspace.id, ctx.user_id, month, months
+ )
+
+
@router.patch("/{budget_id}", response_model=BudgetRead)
async def update_budget(
budget_id: uuid.UUID,
diff --git a/backend/app/schemas/budget.py b/backend/app/schemas/budget.py
index a3dfdc60..1397703c 100644
--- a/backend/app/schemas/budget.py
+++ b/backend/app/schemas/budget.py
@@ -3,7 +3,7 @@ from datetime import date as _Date
from decimal import Decimal
from typing import Optional
-from pydantic import BaseModel, ConfigDict
+from pydantic import BaseModel, ConfigDict, Field
class BudgetCreate(BaseModel):
@@ -43,3 +43,34 @@ class BudgetVsActual(BaseModel):
projected_prev_month_amount: Decimal = Decimal("0")
percentage_used: Optional[float] = None
is_recurring: bool = False
+
+
+class BudgetSuggestion(BaseModel):
+ category_id: uuid.UUID
+ category_name: str
+ category_icon: str
+ category_color: str
+ group_id: Optional[uuid.UUID] = None
+ group_name: Optional[str] = None
+ suggested_amount: Decimal
+ total_spent: Decimal
+ months_with_data: int
+ existing_budget: bool = False
+
+
+class BudgetSuggestionResponse(BaseModel):
+ month: _Date
+ months_requested: int
+ months_analyzed: int
+ suggestions: list[BudgetSuggestion]
+
+
+class BudgetBatchItem(BaseModel):
+ category_id: uuid.UUID
+ amount: Decimal = Field(gt=0)
+
+
+class BudgetBatchCreate(BaseModel):
+ month: _Date
+ is_recurring: bool = False
+ items: list[BudgetBatchItem] = Field(min_length=1, max_length=200)
diff --git a/backend/app/services/budget_service.py b/backend/app/services/budget_service.py
index 2e874909..b06a33d2 100644
--- a/backend/app/services/budget_service.py
+++ b/backend/app/services/budget_service.py
@@ -1,9 +1,10 @@
import uuid
from datetime import date
-from decimal import Decimal
+from decimal import Decimal, ROUND_HALF_UP
from typing import Optional
from sqlalchemy import select, func, and_, case
+from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.app_clock import app_today
@@ -12,7 +13,14 @@ from app.models.category import Category
from app.models.category_group import CategoryGroup
from app.models.transaction import Transaction
from app.models.user import User
-from app.schemas.budget import BudgetCreate, BudgetUpdate, BudgetVsActual
+from app.schemas.budget import (
+ BudgetBatchCreate,
+ BudgetCreate,
+ BudgetSuggestion,
+ BudgetSuggestionResponse,
+ BudgetUpdate,
+ BudgetVsActual,
+)
from app.services._query_filters import (
counts_as_user_pnl,
owner_split_offset_by_category,
@@ -484,3 +492,230 @@ async def get_budget_vs_actual(
))
return sorted(comparisons, key=lambda x: float(x.actual_amount), reverse=True)
+
+
+def _add_months(d: date, n: int) -> date:
+ """First day of the month n months after d (n may be negative)."""
+ index = d.year * 12 + d.month - 1 + n
+ return date(index // 12, index % 12 + 1, 1)
+
+
+async def get_budget_suggestions(
+ session: AsyncSession,
+ workspace_id: uuid.UUID,
+ user_id: uuid.UUID,
+ month: Optional[date] = None,
+ months: int = 3,
+) -> BudgetSuggestionResponse:
+ """Suggest budget amounts from average spending over recent months.
+
+ The window covers the ``months`` calendar months immediately before
+ ``month`` (the target month, default: current). Any month that is not
+ fully in the past yet is excluded so a partial month never skews the
+ average. The suggested amount is the net spending of the window
+ divided by the number of analyzed months, using the same base as the
+ budget vs. actual comparison (posted PnL transactions, credit card
+ accounting mode, split offsets, shared workspace shares, primary
+ currency).
+ """
+ if not month:
+ month = app_today().replace(day=1)
+ target = month.replace(day=1)
+ months = max(1, min(int(months), 24))
+ today = app_today()
+
+ analyzed = [
+ _add_months(target, -offset)
+ for offset in range(1, months + 1)
+ if _add_months(_add_months(target, -offset), 1) <= today
+ ]
+ if not analyzed:
+ return BudgetSuggestionResponse(
+ month=target, months_requested=months, months_analyzed=0, suggestions=[]
+ )
+
+ window_start = min(analyzed)
+ window_end = _add_months(max(analyzed), 1)
+
+ user = await session.get(User, user_id)
+ primary_currency = user.primary_currency if user else get_settings().default_currency
+ accounting_mode = await get_credit_card_accounting_mode(session)
+ report_date = reporting_date_col(accounting_mode)
+
+ cats_result = await session.execute(
+ select(Category, CategoryGroup)
+ .outerjoin(CategoryGroup, Category.group_id == CategoryGroup.id)
+ .where(Category.workspace_id == workspace_id)
+ )
+ all_categories = cats_result.all()
+
+ net_expr = case(
+ (Transaction.type == "debit", _primary_amount_expr()),
+ (Transaction.type == "credit", -_primary_amount_expr()),
+ else_=0,
+ )
+ window_filters = (
+ Transaction.workspace_id == workspace_id,
+ report_date >= window_start,
+ report_date < window_end,
+ report_date <= today,
+ Transaction.category_id.isnot(None),
+ Transaction.status == "posted",
+ counts_as_user_pnl(),
+ )
+
+ spending_result = await session.execute(
+ select(Transaction.category_id, func.sum(net_expr))
+ .where(*window_filters)
+ .group_by(Transaction.category_id)
+ )
+ total_by_cat: dict[str, Decimal] = {}
+ for cat_uuid, net in spending_result.all():
+ net = net or Decimal("0")
+ if net != 0:
+ total_by_cat[str(cat_uuid)] = net
+
+ # Net per category and day in SQL, rolled up to months in Python (SQLite
+ # and Postgres do not share a portable month-truncation function). The
+ # "has spending" check runs on the month total, so a debit and an equal
+ # refund later in the same month leave that month without data.
+ daily_result = await session.execute(
+ select(Transaction.category_id, report_date, func.sum(net_expr))
+ .where(*window_filters)
+ .group_by(Transaction.category_id, report_date)
+ )
+ monthly_net: dict[tuple[str, date], Decimal] = {}
+ for cat_uuid, d, net in daily_result.all():
+ key = (str(cat_uuid), d.replace(day=1))
+ monthly_net[key] = monthly_net.get(key, Decimal("0")) + (net or Decimal("0"))
+ months_with_data: dict[str, set] = {}
+ for (cat_id, month_start), net in monthly_net.items():
+ if net > 0:
+ months_with_data.setdefault(cat_id, set()).add(month_start)
+
+ own_offset = await owner_split_offset_by_category(
+ session,
+ user_id,
+ window_start,
+ window_end,
+ use_effective_date=accounting_mode == "accrual",
+ primary_currency=primary_currency,
+ workspace_id=workspace_id,
+ )
+ for cat_uuid, total in own_offset.items():
+ if cat_uuid is None:
+ continue
+ cat_id = str(cat_uuid)
+ if cat_id in total_by_cat:
+ total_by_cat[cat_id] -= Decimal(str(total))
+ if total_by_cat[cat_id] <= 0:
+ total_by_cat.pop(cat_id)
+
+ from app.services._query_filters import viewer_shared_spending_by_category
+
+ shared_by_cat = await viewer_shared_spending_by_category(
+ session,
+ user_id,
+ window_start,
+ window_end,
+ use_effective_date=accounting_mode == "accrual",
+ primary_currency=primary_currency,
+ )
+ for cat_uuid, total in shared_by_cat.items():
+ if cat_uuid is None:
+ continue
+ cat_id = str(cat_uuid)
+ total_by_cat[cat_id] = total_by_cat.get(cat_id, Decimal("0")) + Decimal(str(total))
+
+ budget_map = await _build_budget_map(session, workspace_id, target)
+ divisor = Decimal(len(analyzed))
+
+ suggestions = []
+ for category, group in all_categories:
+ cat_id = str(category.id)
+ total = total_by_cat.get(cat_id)
+ if total is None or total <= 0:
+ continue
+ suggested = (total / divisor).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
+ if suggested <= 0:
+ continue
+ suggestions.append(BudgetSuggestion(
+ category_id=category.id,
+ category_name=category.name,
+ category_icon=category.icon,
+ category_color=category.color,
+ group_id=group.id if group else None,
+ group_name=group.name if group else None,
+ suggested_amount=suggested,
+ total_spent=total,
+ months_with_data=len(months_with_data.get(cat_id, set())),
+ ))
+
+ suggestions.sort(key=lambda s: s.suggested_amount, reverse=True)
+ for s in suggestions:
+ s.existing_budget = str(s.category_id) in budget_map
+
+ return BudgetSuggestionResponse(
+ month=target,
+ months_requested=months,
+ months_analyzed=len(analyzed),
+ suggestions=suggestions,
+ )
+
+
+async def create_budgets_batch(
+ session: AsyncSession,
+ workspace_id: uuid.UUID,
+ user_id: uuid.UUID,
+ data: BudgetBatchCreate,
+) -> list[Budget]:
+ """Create several budgets in one transaction.
+
+ Fails atomically: if any item conflicts with the
+ (user, category, month, is_recurring) unique constraint nothing is
+ written.
+ """
+ month = data.month.replace(day=1)
+ seen: set[uuid.UUID] = set()
+ budgets: list[Budget] = []
+ for item in data.items:
+ if item.category_id in seen:
+ continue
+ seen.add(item.category_id)
+ budgets.append(
+ Budget(
+ user_id=user_id,
+ workspace_id=workspace_id,
+ category_id=item.category_id,
+ amount=item.amount,
+ month=month,
+ is_recurring=data.is_recurring,
+ )
+ )
+ if not budgets:
+ raise ValueError("No budgets to create")
+
+ known = set(
+ (
+ await session.execute(
+ select(Category.id).where(
+ Category.workspace_id == workspace_id,
+ Category.id.in_(seen),
+ )
+ )
+ ).scalars()
+ )
+ if known != seen:
+ raise ValueError("Category not found")
+
+ session.add_all(budgets)
+ try:
+ await session.commit()
+ except IntegrityError:
+ await session.rollback()
+ raise ValueError(
+ "A budget for one of these categories already exists for this month"
+ )
+ for budget in budgets:
+ await session.refresh(budget)
+ return budgets
diff --git a/backend/tests/api_contract/baseline.json b/backend/tests/api_contract/baseline.json
index 709efc87..52c9e201 100644
--- a/backend/tests/api_contract/baseline.json
+++ b/backend/tests/api_contract/baseline.json
@@ -85,6 +85,7 @@
"GET /api/auth/passkeys": 401,
"GET /api/budgets": 401,
"GET /api/budgets/comparison": 401,
+ "GET /api/budgets/suggestions": 401,
"GET /api/categories": 401,
"GET /api/categories/{category_id}/rule-usage": 401,
"GET /api/categories/{category_id}/usage": 401,
@@ -254,6 +255,7 @@
"POST /api/auth/register": 201,
"POST /api/auth/reset-password": 400,
"POST /api/budgets": 401,
+ "POST /api/budgets/batch": 401,
"POST /api/categories": 401,
"POST /api/category-groups": 401,
"POST /api/collections": 401,
@@ -353,6 +355,7 @@
"POST /api/auth/register": 422,
"POST /api/auth/reset-password": 422,
"POST /api/budgets": 422,
+ "POST /api/budgets/batch": 422,
"POST /api/categories": 422,
"POST /api/category-groups": 422,
"POST /api/collections": 422,
@@ -476,6 +479,7 @@
"GET /api/auth/passkeys": 200,
"GET /api/budgets": 200,
"GET /api/budgets/comparison": 200,
+ "GET /api/budgets/suggestions": 200,
"GET /api/categories": 200,
"GET /api/categories/{category_id}/rule-usage": 200,
"GET /api/categories/{category_id}/usage": 200,
@@ -643,6 +647,7 @@
"POST /api/auth/register": 201,
"POST /api/auth/reset-password": 400,
"POST /api/budgets": 201,
+ "POST /api/budgets/batch": 201,
"POST /api/categories": 201,
"POST /api/category-groups": 201,
"POST /api/collections": 201,
@@ -989,6 +994,7 @@
"POST /api/auth/register": 201,
"POST /api/auth/reset-password": 400,
"POST /api/budgets": 403,
+ "POST /api/budgets/batch": 403,
"POST /api/categories": 403,
"POST /api/category-groups": 403,
"POST /api/collections": 403,
diff --git a/backend/tests/api_contract/cases.py b/backend/tests/api_contract/cases.py
index 5755c4d6..7a877835 100644
--- a/backend/tests/api_contract/cases.py
+++ b/backend/tests/api_contract/cases.py
@@ -66,6 +66,10 @@ BODY_OVERRIDES: dict[tuple[str, str], Callable[[dict], Any]] = {
("POST", "/api/budgets"): lambda w: {
"category_id": w["second_category_id"], "amount": 300, "month": "2026-05-01",
},
+ ("POST", "/api/budgets/batch"): lambda w: {
+ "month": "2026-05-01",
+ "items": [{"category_id": w["second_category_id"], "amount": 300}],
+ },
("POST", "/api/payees/merge"): lambda w: {
"source_ids": [w["second_payee_id"]], "target_id": w["payee_id"],
},
diff --git a/backend/tests/test_budget_suggestions.py b/backend/tests/test_budget_suggestions.py
new file mode 100644
index 00000000..6cab35fb
--- /dev/null
+++ b/backend/tests/test_budget_suggestions.py
@@ -0,0 +1,503 @@
+"""Tests for budget suggestions (issue #430).
+
+Suggestions average the net PnL spending of the N calendar months
+immediately before the target month, excluding any month that is not fully
+in the past. Batch creation writes several budgets atomically.
+"""
+import uuid
+from datetime import date, datetime, timezone
+from decimal import Decimal
+
+import pytest
+from pydantic import ValidationError
+from sqlalchemy import func, select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.core.app_clock import app_today
+from app.models.account import Account
+from app.models.budget import Budget
+from app.models.transaction import Transaction
+from app.schemas.budget import (
+ BudgetBatchCreate,
+ BudgetBatchItem,
+ BudgetCreate,
+)
+from app.services.budget_service import (
+ _add_months,
+ create_budgets_batch,
+ get_budget_suggestions,
+)
+
+
+# ---------------------------------------------------------------------------
+# helpers
+# ---------------------------------------------------------------------------
+
+
+async def _make_account(session: AsyncSession, test_user, name: str) -> Account:
+ account = Account(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ name=name,
+ type="checking",
+ balance=Decimal("5000"),
+ currency="BRL",
+ )
+ session.add(account)
+ await session.commit()
+ await session.refresh(account)
+ return account
+
+
+def _txn(test_user, account, category, amount, day, kind="debit", pair_id=None):
+ return Transaction(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ account_id=account.id,
+ category_id=category.id,
+ description="SUGGEST TEST",
+ amount=Decimal(str(amount)),
+ date=day,
+ type=kind,
+ source="manual",
+ transfer_pair_id=pair_id,
+ created_at=datetime.now(timezone.utc),
+ )
+
+
+async def _suggest(session, test_user, test_workspace, month, months=3):
+ return await get_budget_suggestions(
+ session, test_workspace.id, test_user.id, month, months
+ )
+
+
+def _by_cat(response, cat_id):
+ return [s for s in response.suggestions if s.category_id == cat_id]
+
+
+# ---------------------------------------------------------------------------
+# _add_months
+# ---------------------------------------------------------------------------
+
+
+def test_add_months_wraps_years():
+ assert _add_months(date(2025, 3, 10), -2) == date(2025, 1, 1)
+ assert _add_months(date(2025, 1, 15), -1) == date(2024, 12, 1)
+ assert _add_months(date(2024, 12, 1), 2) == date(2025, 2, 1)
+
+
+# ---------------------------------------------------------------------------
+# get_budget_suggestions
+# ---------------------------------------------------------------------------
+
+
+async def test_months_with_data_nets_the_whole_month(
+ session: AsyncSession, test_user, test_workspace, test_categories
+):
+ """A debit and an equal refund in the same month leave no data for it."""
+ account = await _make_account(session, test_user, "SugAccMonthNet")
+ cat_food = test_categories[0]
+ session.add_all([
+ _txn(test_user, account, cat_food, 100, date(2025, 4, 1)),
+ _txn(test_user, account, cat_food, 100, date(2025, 4, 5), kind="credit"),
+ _txn(test_user, account, cat_food, 300, date(2025, 5, 8)),
+ ])
+ await session.commit()
+
+ resp = await _suggest(session, test_user, test_workspace, date(2025, 6, 1), months=3)
+
+ food = _by_cat(resp, cat_food.id)
+ assert len(food) == 1
+ assert food[0].total_spent == Decimal("300")
+ assert food[0].months_with_data == 1
+
+
+async def test_suggestions_average_over_window(
+ session: AsyncSession, test_user, test_workspace, test_categories
+):
+ account = await _make_account(session, test_user, "SugAcc1")
+ cat_food, cat_transit, _ = test_categories
+
+ txns = [
+ # food: 100 + 200 + 300 over the 3 window months -> 600 / 3 = 200.00
+ _txn(test_user, account, cat_food, 100, date(2025, 3, 10)),
+ _txn(test_user, account, cat_food, 200, date(2025, 4, 12)),
+ _txn(test_user, account, cat_food, 300, date(2025, 5, 8)),
+ # transit: single month of spend -> 150 / 3 = 50.00
+ _txn(test_user, account, cat_transit, 150, date(2025, 4, 5)),
+ ]
+ session.add_all(txns)
+ await session.commit()
+
+ resp = await _suggest(session, test_user, test_workspace, date(2025, 6, 1), months=3)
+
+ assert resp.month == date(2025, 6, 1)
+ assert resp.months_requested == 3
+ assert resp.months_analyzed == 3
+
+ food = _by_cat(resp, cat_food.id)
+ assert len(food) == 1
+ assert food[0].suggested_amount == Decimal("200.00")
+ assert food[0].total_spent == Decimal("600")
+ assert food[0].months_with_data == 3
+
+ transit = _by_cat(resp, cat_transit.id)
+ assert len(transit) == 1
+ assert transit[0].suggested_amount == Decimal("50.00")
+ assert transit[0].months_with_data == 1
+
+ # Highest suggested amount first
+ assert resp.suggestions[0].category_id == cat_food.id
+
+
+async def test_suggestions_credit_income_not_suggested(
+ session: AsyncSession, test_user, test_workspace, test_categories
+):
+ account = await _make_account(session, test_user, "SugAcc2")
+ cat_income = test_categories[2]
+
+ session.add(_txn(test_user, account, cat_income, 5000, date(2025, 4, 30), kind="credit"))
+ await session.commit()
+
+ resp = await _suggest(session, test_user, test_workspace, date(2025, 6, 1), months=3)
+ assert _by_cat(resp, cat_income.id) == []
+
+
+async def test_suggestions_refunds_reduce_average(
+ session: AsyncSession, test_user, test_workspace, test_categories
+):
+ account = await _make_account(session, test_user, "SugAcc3")
+ cat_food = test_categories[0]
+
+ txns = [
+ _txn(test_user, account, cat_food, 200, date(2025, 3, 10)),
+ _txn(test_user, account, cat_food, 50, date(2025, 4, 10), kind="credit"),
+ ]
+ session.add_all(txns)
+ await session.commit()
+
+ resp = await _suggest(session, test_user, test_workspace, date(2025, 6, 1), months=3)
+ food = _by_cat(resp, cat_food.id)
+ assert len(food) == 1
+ assert food[0].total_spent == Decimal("150")
+ assert food[0].suggested_amount == Decimal("50.00")
+
+
+async def test_suggestions_excludes_transfers(
+ session: AsyncSession, test_user, test_workspace, test_categories
+):
+ account = await _make_account(session, test_user, "SugAcc4")
+ cat_transit = test_categories[1]
+ pair_id = uuid.uuid4()
+
+ txns = [
+ _txn(test_user, account, cat_transit, 200, date(2025, 4, 5), pair_id=pair_id),
+ _txn(test_user, account, cat_transit, 200, date(2025, 4, 5), kind="credit", pair_id=pair_id),
+ ]
+ session.add_all(txns)
+ await session.commit()
+
+ resp = await _suggest(session, test_user, test_workspace, date(2025, 6, 1), months=3)
+ assert resp.months_analyzed == 3
+ assert resp.suggestions == []
+
+
+async def test_suggestions_excludes_partial_current_month(
+ session: AsyncSession, test_user, test_workspace, test_categories
+):
+ today = app_today()
+ current_month = today.replace(day=1)
+ target = _add_months(current_month, 1) # next month
+ cat_food = test_categories[0]
+ account = await _make_account(session, test_user, "SugAcc5")
+
+ txns = [
+ # Inside the window: current month minus 2
+ _txn(test_user, account, cat_food, 100, _add_months(current_month, -2).replace(day=15)),
+ # The current month is still running and must not skew the average
+ _txn(test_user, account, cat_food, 300, today),
+ ]
+ session.add_all(txns)
+ await session.commit()
+
+ resp = await _suggest(session, test_user, test_workspace, target, months=3)
+ assert resp.months_requested == 3
+ assert resp.months_analyzed == 2
+
+ food = _by_cat(resp, cat_food.id)
+ assert len(food) == 1
+ assert food[0].total_spent == Decimal("100")
+ assert food[0].suggested_amount == Decimal("50.00")
+ assert food[0].months_with_data == 1
+
+
+async def test_suggestions_marks_existing_budget(
+ session: AsyncSession, test_user, test_workspace, test_categories
+):
+ today = app_today()
+ target = today.replace(day=1)
+ cat_food, cat_transit, _ = test_categories
+ account = await _make_account(session, test_user, "SugAcc6")
+
+ txns = [
+ _txn(test_user, account, cat_food, 100, _add_months(target, -2).replace(day=10)),
+ _txn(test_user, account, cat_food, 200, _add_months(target, -1).replace(day=10)),
+ _txn(test_user, account, cat_transit, 90, _add_months(target, -3).replace(day=10)),
+ ]
+ session.add_all(txns)
+ await session.commit()
+
+ from app.services.budget_service import create_budget
+
+ await create_budget(
+ session,
+ test_workspace.id,
+ test_user.id,
+ BudgetCreate(category_id=cat_food.id, amount=Decimal("150"), month=target),
+ )
+
+ resp = await _suggest(session, test_user, test_workspace, target, months=3)
+
+ food = _by_cat(resp, cat_food.id)
+ assert len(food) == 1
+ assert food[0].suggested_amount == Decimal("100.00")
+ assert food[0].existing_budget is True
+
+ transit = _by_cat(resp, cat_transit.id)
+ assert len(transit) == 1
+ assert transit[0].existing_budget is False
+
+
+async def test_suggestions_empty_without_history(
+ session: AsyncSession, test_user, test_workspace, test_categories
+):
+ resp = await _suggest(session, test_user, test_workspace, date(2025, 6, 1), months=3)
+ assert resp.months_analyzed == 3
+ assert resp.suggestions == []
+
+
+async def test_suggestions_window_entirely_in_future(
+ session: AsyncSession, test_user, test_workspace, test_categories
+):
+ today = app_today()
+ target = _add_months(today.replace(day=1), 6)
+ resp = await _suggest(session, test_user, test_workspace, target, months=1)
+ assert resp.months_analyzed == 0
+ assert resp.suggestions == []
+
+
+# ---------------------------------------------------------------------------
+# create_budgets_batch
+# ---------------------------------------------------------------------------
+
+
+async def test_batch_creates_multiple(
+ session: AsyncSession, test_user, test_workspace, test_categories
+):
+ data = BudgetBatchCreate(
+ month=date(2026, 11, 15), # mid-month should normalize to day 1
+ items=[
+ BudgetBatchItem(category_id=test_categories[0].id, amount=Decimal("100.50")),
+ BudgetBatchItem(category_id=test_categories[1].id, amount=Decimal("200")),
+ ],
+ )
+ budgets = await create_budgets_batch(session, test_workspace.id, test_user.id, data)
+
+ assert len(budgets) == 2
+ assert all(b.month == date(2026, 11, 1) for b in budgets)
+ assert all(b.is_recurring is False for b in budgets)
+
+
+async def test_batch_recurring_flag(
+ session: AsyncSession, test_user, test_workspace, test_categories
+):
+ data = BudgetBatchCreate(
+ month=date(2026, 11, 1),
+ is_recurring=True,
+ items=[BudgetBatchItem(category_id=test_categories[0].id, amount=Decimal("50"))],
+ )
+ budgets = await create_budgets_batch(session, test_workspace.id, test_user.id, data)
+ assert budgets[0].is_recurring is True
+
+
+async def test_batch_dedupes_repeated_category(
+ session: AsyncSession, test_user, test_workspace, test_categories
+):
+ data = BudgetBatchCreate(
+ month=date(2026, 11, 1),
+ items=[
+ BudgetBatchItem(category_id=test_categories[0].id, amount=Decimal("100")),
+ BudgetBatchItem(category_id=test_categories[0].id, amount=Decimal("200")),
+ ],
+ )
+ budgets = await create_budgets_batch(session, test_workspace.id, test_user.id, data)
+ assert len(budgets) == 1
+
+
+def test_batch_item_rejects_non_positive_amount():
+ with pytest.raises(ValidationError):
+ BudgetBatchItem(category_id=uuid.uuid4(), amount=Decimal("0"))
+ with pytest.raises(ValidationError):
+ BudgetBatchItem(category_id=uuid.uuid4(), amount=Decimal("-5"))
+
+
+def test_batch_rejects_empty_items():
+ with pytest.raises(ValidationError):
+ BudgetBatchCreate(month=date(2026, 11, 1), items=[])
+
+
+async def test_batch_atomic_on_conflict(
+ session: AsyncSession, test_user, test_workspace, test_categories
+):
+ from app.services.budget_service import create_budget
+
+ await create_budget(
+ session,
+ test_workspace.id,
+ test_user.id,
+ BudgetCreate(category_id=test_categories[0].id, amount=Decimal("1"), month=date(2026, 11, 1)),
+ )
+
+ data = BudgetBatchCreate(
+ month=date(2026, 11, 1),
+ items=[
+ BudgetBatchItem(category_id=test_categories[0].id, amount=Decimal("100")),
+ BudgetBatchItem(category_id=test_categories[1].id, amount=Decimal("200")),
+ ],
+ )
+ with pytest.raises(ValueError):
+ await create_budgets_batch(session, test_workspace.id, test_user.id, data)
+
+ # Nothing was written: only the pre-existing budget remains for that month
+ count = (
+ await session.execute(
+ select(func.count(Budget.id)).where(Budget.month == date(2026, 11, 1))
+ )
+ ).scalar_one()
+ assert count == 1
+
+
+async def test_batch_rejects_category_outside_workspace(
+ session: AsyncSession, test_user, test_workspace, test_categories
+):
+ data = BudgetBatchCreate(
+ month=date(2026, 11, 1),
+ items=[
+ BudgetBatchItem(category_id=test_categories[0].id, amount=Decimal("100")),
+ BudgetBatchItem(category_id=uuid.uuid4(), amount=Decimal("200")),
+ ],
+ )
+ with pytest.raises(ValueError, match="Category not found"):
+ await create_budgets_batch(session, test_workspace.id, test_user.id, data)
+
+ count = (
+ await session.execute(
+ select(func.count(Budget.id)).where(Budget.month == date(2026, 11, 1))
+ )
+ ).scalar_one()
+ assert count == 0
+
+
+# ---------------------------------------------------------------------------
+# API
+# ---------------------------------------------------------------------------
+
+
+async def test_api_suggestions(client, auth_headers, session, test_user, test_workspace, test_categories):
+ account = await _make_account(session, test_user, "SugApiAcc")
+ cat_food = test_categories[0]
+ session.add(_txn(test_user, account, cat_food, 300, date(2025, 5, 20)))
+ await session.commit()
+
+ response = await client.get(
+ "/api/budgets/suggestions?month=2025-06-01&months=3",
+ headers=auth_headers,
+ )
+ assert response.status_code == 200
+ body = response.json()
+ assert body["month"] == "2025-06-01"
+ assert body["months_analyzed"] == 3
+ assert len(body["suggestions"]) == 1
+ assert body["suggestions"][0]["suggested_amount"] == "100.00"
+ assert body["suggestions"][0]["existing_budget"] is False
+
+
+async def test_api_batch_creates(client, auth_headers, test_categories):
+ response = await client.post(
+ "/api/budgets/batch",
+ json={
+ "month": "2026-12-10",
+ "items": [
+ {"category_id": str(test_categories[0].id), "amount": "100.00"},
+ {"category_id": str(test_categories[1].id), "amount": "75"},
+ ],
+ },
+ headers=auth_headers,
+ )
+ assert response.status_code == 201
+ data = response.json()
+ assert len(data) == 2
+ assert all(b["month"] == "2026-12-01" for b in data)
+
+ listing = await client.get("/api/budgets?month=2026-12-01", headers=auth_headers)
+ assert listing.status_code == 200
+ assert len(listing.json()) == 2
+
+
+async def test_api_batch_conflict(client, auth_headers, test_categories):
+ existing = await client.post(
+ "/api/budgets",
+ json={
+ "category_id": str(test_categories[0].id),
+ "amount": 1,
+ "month": "2026-12-01",
+ },
+ headers=auth_headers,
+ )
+ assert existing.status_code == 201
+
+ response = await client.post(
+ "/api/budgets/batch",
+ json={
+ "month": "2026-12-01",
+ "items": [
+ {"category_id": str(test_categories[0].id), "amount": "100.00"},
+ {"category_id": str(test_categories[1].id), "amount": "200"},
+ ],
+ },
+ headers=auth_headers,
+ )
+ assert response.status_code == 400
+
+ listing = await client.get("/api/budgets?month=2026-12-01", headers=auth_headers)
+ assert len(listing.json()) == 1
+
+
+async def test_api_batch_rejects_bad_amount(client, auth_headers, test_categories):
+ response = await client.post(
+ "/api/budgets/batch",
+ json={
+ "month": "2026-12-01",
+ "items": [{"category_id": str(test_categories[0].id), "amount": 0}],
+ },
+ headers=auth_headers,
+ )
+ assert response.status_code == 422
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index eef29b8e..6624d25c 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -53,6 +53,7 @@ import type {
TransactionCalendarResponse,
Budget,
BudgetVsActual,
+ BudgetSuggestionResponse,
Rule,
RuleAction,
RuleConditionNode,
@@ -1293,6 +1294,18 @@ export const budgets = {
const { data } = await api.get('/budgets/comparison', { params: { month } })
return data
},
+ suggestions: async (month: string, months: number): Promise<BudgetSuggestionResponse> => {
+ const { data } = await api.get('/budgets/suggestions', { params: { month, months } })
+ return data
+ },
+ createBatch: async (payload: {
+ month: string
+ is_recurring: boolean
+ items: { category_id: string; amount: number }[]
+ }): Promise<Budget[]> => {
+ const { data } = await api.post('/budgets/batch', payload)
+ return data
+ },
}
// Goals
diff --git a/frontend/src/locales/cs.json b/frontend/src/locales/cs.json
index 2f0713ba..520dbc1c 100644
--- a/frontend/src/locales/cs.json
+++ b/frontend/src/locales/cs.json
@@ -1451,7 +1451,17 @@
"confirmDeleteDescription": "Rozpočet pro „{{name}}“ bude trvale smazán. Stávající transakce to neovlivní. Tuto akci nelze vrátit.",
"confirmDeleteRecurringDescription": "Opakovaný rozpočet pro „{{name}}“ bude trvale smazán. Tato definice se už nebude vztahovat na další měsíce. Stávající transakce to neovlivní. Tuto akci nelze vrátit.",
"repeatEveryMonth": "Opakovat každý měsíc",
- "recurringLabel": "Opakovaný"
+ "recurringLabel": "Opakovaný",
+ "suggest": "Navrhnout z historie",
+ "suggestTitle": "Navrhnout rozpočty",
+ "suggestDescription": "Navržené limity podle vašeho průměrného měsíčního vydání za posledních {{months}} měsíců.",
+ "suggestPeriod": "Období",
+ "suggestMonths": "měsíců",
+ "suggestSpent": "Vydáno za období: {{amount}}",
+ "suggestCreate": "Vytvořit rozpočty",
+ "suggestCreated": "Vytvořeno {{count}} rozpočtů",
+ "suggestEmpty": "Ve vybraném období není historie výdajů.",
+ "suggestError": "Návrhy se nepodařilo načíst. Zkuste to znovu za chvíli."
},
"goals": {
"title": "Cíle",
diff --git a/frontend/src/locales/de.json b/frontend/src/locales/de.json
index 5faf1cb1..4fce3dca 100644
--- a/frontend/src/locales/de.json
+++ b/frontend/src/locales/de.json
@@ -1368,7 +1368,17 @@
"confirmDeleteDescription": "Das Budget für \"{{name}}\" wird dauerhaft gelöscht. Bestehende Transaktionen bleiben unverändert. Diese Aktion kann nicht rückgängig gemacht werden.",
"confirmDeleteRecurringDescription": "Das wiederkehrende Budget für \"{{name}}\" wird dauerhaft gelöscht. Diese Definition gilt nicht mehr für zukünftige Monate. Bestehende Transaktionen bleiben unverändert. Diese Aktion kann nicht rückgängig gemacht werden.",
"repeatEveryMonth": "Jeden Monat wiederholen",
- "recurringLabel": "Wiederkehrend"
+ "recurringLabel": "Wiederkehrend",
+ "suggest": "Aus Verlauf vorschlagen",
+ "suggestTitle": "Budgets vorschlagen",
+ "suggestDescription": "Vorgeschlagene Limits auf Basis deines durchschnittlichen monatlichen Verbrauchs der letzten {{months}} Monate.",
+ "suggestPeriod": "Zeitraum",
+ "suggestMonths": "Monate",
+ "suggestSpent": "Ausgegeben im Zeitraum: {{amount}}",
+ "suggestCreate": "Budgets erstellen",
+ "suggestCreated": "{{count}} Budgets erstellt",
+ "suggestEmpty": "Keine Ausgaben im gewählten Zeitraum, aus denen vorgeschlagen werden kann.",
+ "suggestError": "Vorschläge konnten nicht geladen werden. Versuche es gleich noch einmal."
},
"goals": {
"title": "Ziele",
diff --git a/frontend/src/locales/el.json b/frontend/src/locales/el.json
index ea2023f2..7868e8f3 100644
--- a/frontend/src/locales/el.json
+++ b/frontend/src/locales/el.json
@@ -1367,7 +1367,17 @@
"confirmDeleteDescription": "Ο προϋπολογισμός για \"{{name}}\" θα διαγραφεί οριστικά. Οι υπάρχουσες συναλλαγές δεν επηρεάζονται. Αυτή η ενέργεια δεν μπορεί να αναιρεθεί.",
"confirmDeleteRecurringDescription": "Ο επαναλαμβανόμενος προϋπολογισμός για \"{{name}}\" θα διαγραφεί οριστικά. Αυτός ο ορισμός δεν θα ισχύει πλέον για επόμενους μήνες. Οι υπάρχουσες συναλλαγές δεν επηρεάζονται. Αυτή η ενέργεια δεν μπορεί να αναιρεθεί.",
"repeatEveryMonth": "Επανάληψη κάθε μήνα",
- "recurringLabel": "Επαναλαμβανόμενος"
+ "recurringLabel": "Επαναλαμβανόμενος",
+ "suggest": "Προτάσεις από το ιστορικό",
+ "suggestTitle": "Προτάσεις προϋπολογισμών",
+ "suggestDescription": "Προτεινόμενα όρια με βάση το μέσο μηνιαίο κόστος σας των τελευταίων {{months}} μηνών.",
+ "suggestPeriod": "Περίοδος",
+ "suggestMonths": "μήνες",
+ "suggestSpent": "Ξόδαψε {{amount}} στην περίοδο",
+ "suggestCreate": "Δημιουργία προϋπολογισμών",
+ "suggestCreated": "Δημιουργήθηκαν {{count}} προϋπολογισμοί",
+ "suggestEmpty": "Δεν υπάρχει ιστορικό εξόδων για την επιλεγμένη περίοδο.",
+ "suggestError": "Δεν ήταν δυνατή η φόρτωση των προτάσεων. Δοκιμάστε ξανά σε λίγο."
},
"goals": {
"title": "Στόχοι",
diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.json
index 251b9309..58d4a044 100644
--- a/frontend/src/locales/en.json
+++ b/frontend/src/locales/en.json
@@ -1367,7 +1367,17 @@
"confirmDeleteDescription": "The budget for \"{{name}}\" will be permanently deleted. Existing transactions are not affected. This action cannot be undone.",
"confirmDeleteRecurringDescription": "The recurring budget for \"{{name}}\" will be permanently deleted. This definition will no longer apply to later months. Existing transactions are not affected. This action cannot be undone.",
"repeatEveryMonth": "Repeat every month",
- "recurringLabel": "Recurring"
+ "recurringLabel": "Recurring",
+ "suggest": "Suggest from history",
+ "suggestTitle": "Suggest budgets",
+ "suggestDescription": "Proposed limits based on your average monthly spending over the last {{months}} months.",
+ "suggestPeriod": "Period",
+ "suggestMonths": "months",
+ "suggestSpent": "Spent {{amount}} in the period",
+ "suggestCreate": "Create budgets",
+ "suggestCreated": "Created {{count}} budgets",
+ "suggestEmpty": "No spending history in the selected period to suggest from.",
+ "suggestError": "Could not load suggestions. Try again in a moment."
},
"goals": {
"title": "Goals",
diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.json
index 529df9f7..a8a55b9a 100644
--- a/frontend/src/locales/es.json
+++ b/frontend/src/locales/es.json
@@ -1371,7 +1371,17 @@
"confirmDeleteDescription": "El presupuesto para \"{{name}}\" se eliminará permanentemente. Las transacciones existentes no se ven afectadas. Esta acción no se puede deshacer.",
"confirmDeleteRecurringDescription": "El presupuesto recurrente para \"{{name}}\" se eliminará permanentemente. Esta definición dejará de aplicarse en los meses posteriores. Las transacciones existentes no se ven afectadas. Esta acción no se puede deshacer.",
"repeatEveryMonth": "Repetir cada mes",
- "recurringLabel": "Recurrente"
+ "recurringLabel": "Recurrente",
+ "suggest": "Sugerir desde el historial",
+ "suggestTitle": "Sugerir presupuestos",
+ "suggestDescription": "Límites propuestos según tu gasto mensual medio de los últimos {{months}} meses.",
+ "suggestPeriod": "Período",
+ "suggestMonths": "meses",
+ "suggestSpent": "Gastado {{amount}} en el período",
+ "suggestCreate": "Crear presupuestos",
+ "suggestCreated": "Se crearon {{count}} presupuestos",
+ "suggestEmpty": "Sin historial de gastos en el período seleccionado que sugerir.",
+ "suggestError": "No se pudieron cargar las sugerencias. Inténtalo de nuevo en un momento."
},
"goals": {
"title": "Objetivos",
diff --git a/frontend/src/locales/fr.json b/frontend/src/locales/fr.json
index 4d8622b8..2c0a8676 100644
--- a/frontend/src/locales/fr.json
+++ b/frontend/src/locales/fr.json
@@ -1371,7 +1371,17 @@
"confirmDeleteDescription": "Le budget pour « {{name}} » sera définitivement supprimé. Les transactions existantes ne sont pas affectées. Cette action est irréversible.",
"confirmDeleteRecurringDescription": "Le budget récurrent pour « {{name}} » sera définitivement supprimé. Cette définition ne s'appliquera plus aux mois suivants. Les transactions existantes ne sont pas affectées. Cette action est irréversible.",
"repeatEveryMonth": "Répéter chaque mois",
- "recurringLabel": "Récurrent"
+ "recurringLabel": "Récurrent",
+ "suggest": "Suggérer depuis l'historique",
+ "suggestTitle": "Suggérer des budgets",
+ "suggestDescription": "Limites proposées sur la base de vos dépenses moyennes mensuelles des {{months}} derniers mois.",
+ "suggestPeriod": "Période",
+ "suggestMonths": "mois",
+ "suggestSpent": "Dépensé {{amount}} sur la période",
+ "suggestCreate": "Créer les budgets",
+ "suggestCreated": "{{count}} budgets créés",
+ "suggestEmpty": "Aucun historique de dépenses sur la période sélectionnée pour suggérer.",
+ "suggestError": "Impossible de charger les suggestions. Réessayez dans un instant."
},
"goals": {
"title": "Objectifs",
diff --git a/frontend/src/locales/hi.json b/frontend/src/locales/hi.json
index 0d9f0c28..fdeb2b5c 100644
--- a/frontend/src/locales/hi.json
+++ b/frontend/src/locales/hi.json
@@ -1367,7 +1367,17 @@
"confirmDeleteDescription": "\"{{name}}\" का बजट स्थायी रूप से हट जाएगा। मौजूदा लेन-देन पर कोई असर नहीं पड़ता। यह कार्रवाई पूर्ववत नहीं की जा सकती।",
"confirmDeleteRecurringDescription": "\"{{name}}\" का आवर्ती बजट स्थायी रूप से हट जाएगा। यह परिभाषा आगे के महीनों पर लागू नहीं होगी। मौजूदा लेन-देन पर कोई असर नहीं पड़ता। यह कार्रवाई पूर्ववत नहीं की जा सकती।",
"repeatEveryMonth": "हर महीने दोहराएँ",
- "recurringLabel": "आवर्ती"
+ "recurringLabel": "आवर्ती",
+ "suggest": "इतिहास से सुझाएँ",
+ "suggestTitle": "बजट सुझाएँ",
+ "suggestDescription": "पिछले {{months}} महीनों की आपकी औसत मासिक खर्च के आधार पर प्रस्तावित सीमाएँ।",
+ "suggestPeriod": "अवधि",
+ "suggestMonths": "महीने",
+ "suggestSpent": "अवधि में खर्च: {{amount}}",
+ "suggestCreate": "बजट बनाएँ",
+ "suggestCreated": "{{count}} बजट बनाए गए",
+ "suggestEmpty": "चुनी गई अवधि में खर्च का कोई इतिहास नहीं है।",
+ "suggestError": "सुझाव लोड नहीं हो सके। थोड़ी देर बाद फिर से कोशिश करें।"
},
"goals": {
"title": "लक्ष्य",
diff --git a/frontend/src/locales/hu.json b/frontend/src/locales/hu.json
index 0cf81bb7..7e543ed5 100644
--- a/frontend/src/locales/hu.json
+++ b/frontend/src/locales/hu.json
@@ -1367,7 +1367,17 @@
"confirmDeleteDescription": "A(z) „{{name}}” költségkerete véglegesen törlődik. A meglévő tranzakciókat ez nem érinti. Ez a művelet nem vonható vissza.",
"confirmDeleteRecurringDescription": "A(z) „{{name}}” ismétlődő költségkerete véglegesen törlődik. Ez a beállítás a későbbi hónapokra sem vonatkozik majd. A meglévő tranzakciókat ez nem érinti. Ez a művelet nem vonható vissza.",
"repeatEveryMonth": "Ismétlés minden hónapban",
- "recurringLabel": "Ismétlődő"
+ "recurringLabel": "Ismétlődő",
+ "suggest": "Javaslat a múltból",
+ "suggestTitle": "Költségkeretek javaslása",
+ "suggestDescription": "Javasolt limitek az elmúlt {{months}} hónap átlagos havi kiadásaid alapján.",
+ "suggestPeriod": "Időtartam",
+ "suggestMonths": "hó",
+ "suggestSpent": "Kiadás az időszakban: {{amount}}",
+ "suggestCreate": "Költségkeretek létrehozása",
+ "suggestCreated": "{{count}} költségkeret létrehozva",
+ "suggestEmpty": "Nincs kiadási előzmény a kiválasztott időszakban.",
+ "suggestError": "Nem sikerült betölteni a javaslatokat. Próbáld újra egy kicsit később."
},
"goals": {
"title": "Célok",
diff --git a/frontend/src/locales/it.json b/frontend/src/locales/it.json
index 1d2945a5..9d93e738 100644
--- a/frontend/src/locales/it.json
+++ b/frontend/src/locales/it.json
@@ -1371,7 +1371,17 @@
"confirmDeleteDescription": "Il budget per \"{{name}}\" verrà eliminato definitivamente. Le transazioni esistenti non sono interessate. Questa azione non può essere annullata.",
"confirmDeleteRecurringDescription": "Il budget ricorrente per \"{{name}}\" verrà eliminato definitivamente. Questa definizione non si applicherà più ai mesi successivi. Le transazioni esistenti non sono interessate. Questa azione non può essere annullata.",
"repeatEveryMonth": "Ripeti ogni mese",
- "recurringLabel": "Ricorrente"
+ "recurringLabel": "Ricorrente",
+ "suggest": "Suggerisci dalla cronologia",
+ "suggestTitle": "Suggerisci budget",
+ "suggestDescription": "Limiti proposti in base alla tua spesa media mensile degli ultimi {{months}} mesi.",
+ "suggestPeriod": "Periodo",
+ "suggestMonths": "mesi",
+ "suggestSpent": "Speso {{amount}} nel periodo",
+ "suggestCreate": "Crea budget",
+ "suggestCreated": "Creati {{count}} budget",
+ "suggestEmpty": "Nessuna cronologia di spesa nel periodo selezionato.",
+ "suggestError": "Impossibile caricare i suggerimenti. Riprova tra poco."
},
"goals": {
"title": "Obiettivi",
diff --git a/frontend/src/locales/ja.json b/frontend/src/locales/ja.json
index e60d407d..b9015120 100644
--- a/frontend/src/locales/ja.json
+++ b/frontend/src/locales/ja.json
@@ -1367,7 +1367,17 @@
"confirmDeleteDescription": "「{{name}}」の予算を完全に削除します。既存の取引には影響しません。この操作は取り消せません。",
"confirmDeleteRecurringDescription": "「{{name}}」の定期的な予算を完全に削除します。この定義は以降の月には適用されなくなります。既存の取引には影響しません。この操作は取り消せません。",
"repeatEveryMonth": "毎月繰り返す",
- "recurringLabel": "定期的"
+ "recurringLabel": "定期的",
+ "suggest": "履歴から提案",
+ "suggestTitle": "予算を提案",
+ "suggestDescription": "過去{{months}}ヶ月の平均月次支出に基づく、提案される上限額です。",
+ "suggestPeriod": "期間",
+ "suggestMonths": "ヶ月",
+ "suggestSpent": "期間内の支出: {{amount}}",
+ "suggestCreate": "予算を作成",
+ "suggestCreated": "{{count}}件の予算を作成しました",
+ "suggestEmpty": "選択した期間に支出の履歴がありません。",
+ "suggestError": "候補を読み込めませんでした。しばらくしてからもう一度お試しください。"
},
"goals": {
"title": "目標",
diff --git a/frontend/src/locales/nl.json b/frontend/src/locales/nl.json
index 2e561f23..97625ed7 100644
--- a/frontend/src/locales/nl.json
+++ b/frontend/src/locales/nl.json
@@ -1369,7 +1369,17 @@
"recurringLabel": "Terugkerend",
"confirmDeleteTitle": "Budget verwijderen?",
"confirmDeleteDescription": "Het budget voor \"{{name}}\" wordt permanent verwijderd. Bestaande transacties worden niet beïnvloed. Deze actie kan niet ongedaan worden gemaakt.",
- "confirmDeleteRecurringDescription": "Het terugkerende budget voor \"{{name}}\" wordt permanent verwijderd. Deze definitie geldt niet meer voor latere maanden. Bestaande transacties worden niet beïnvloed. Deze actie kan niet ongedaan worden gemaakt."
+ "confirmDeleteRecurringDescription": "Het terugkerende budget voor \"{{name}}\" wordt permanent verwijderd. Deze definitie geldt niet meer voor latere maanden. Bestaande transacties worden niet beïnvloed. Deze actie kan niet ongedaan worden gemaakt.",
+ "suggest": "Suggereer uit geschiedenis",
+ "suggestTitle": "Budgetten suggereren",
+ "suggestDescription": "Voorgestelde limieten op basis van je gemiddelde maandelijkse uitgaven van de laatste {{months}} maanden.",
+ "suggestPeriod": "Periode",
+ "suggestMonths": "maanden",
+ "suggestSpent": "Besteed in de periode: {{amount}}",
+ "suggestCreate": "Budgetten aanmaken",
+ "suggestCreated": "{{count}} budgetten aangemaakt",
+ "suggestEmpty": "Geen uitgavenhistoriek in de geselecteerde periode.",
+ "suggestError": "Suggesties konden niet worden geladen. Probeer het zo opnieuw."
},
"goals": {
"title": "Doelen",
diff --git a/frontend/src/locales/pl.json b/frontend/src/locales/pl.json
index ed41523c..58cea0a3 100644
--- a/frontend/src/locales/pl.json
+++ b/frontend/src/locales/pl.json
@@ -1420,7 +1420,17 @@
"confirmDeleteDescription": "Budżet dla „{{name}}” zostanie trwale usunięty. Istniejące transakcje nie zostaną zmienione. Tej operacji nie można cofnąć.",
"confirmDeleteRecurringDescription": "Cykliczny budżet dla „{{name}}” zostanie trwale usunięty. Ta definicja nie będzie już stosowana w kolejnych miesiącach. Istniejące transakcje nie zostaną zmienione. Tej operacji nie można cofnąć.",
"repeatEveryMonth": "Powtarzaj co miesiąc",
- "recurringLabel": "Cykliczny"
+ "recurringLabel": "Cykliczny",
+ "suggest": "Sugeruj z historii",
+ "suggestTitle": "Sugeruj budżety",
+ "suggestDescription": "Proponowane limity na podstawie średnich miesięcznych wydatków z ostatnich {{months}} miesięcy.",
+ "suggestPeriod": "Okres",
+ "suggestMonths": "mies.",
+ "suggestSpent": "Wydatki w okresie: {{amount}}",
+ "suggestCreate": "Utwórz budżety",
+ "suggestCreated": "Utworzono {{count}} budżetów",
+ "suggestEmpty": "Brak historii wydatków w wybranym okresie.",
+ "suggestError": "Nie udało się wczytać sugestii. Spróbuj ponownie za chwilę."
},
"goals": {
"title": "Cele",
diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.json
index 896c2413..792aeb89 100644
--- a/frontend/src/locales/pt-BR.json
+++ b/frontend/src/locales/pt-BR.json
@@ -1371,7 +1371,17 @@
"confirmDeleteDescription": "O orçamento para \"{{name}}\" será excluído permanentemente. As transações existentes não são afetadas. Esta ação não pode ser desfeita.",
"confirmDeleteRecurringDescription": "O orçamento recorrente para \"{{name}}\" será excluído permanentemente. Esta definição não será mais aplicada nos meses seguintes. As transações existentes não são afetadas. Esta ação não pode ser desfeita.",
"repeatEveryMonth": "Repetir todo mês",
- "recurringLabel": "Recorrente"
+ "recurringLabel": "Recorrente",
+ "suggest": "Sugerir pelo histórico",
+ "suggestTitle": "Sugerir orçamentos",
+ "suggestDescription": "Limites propostos com base na sua média de gastos mensais nos últimos {{months}} meses.",
+ "suggestPeriod": "Período",
+ "suggestMonths": "meses",
+ "suggestSpent": "Gasto de {{amount}} no período",
+ "suggestCreate": "Criar orçamentos",
+ "suggestCreated": "{{count}} orçamentos criados",
+ "suggestEmpty": "Sem histórico de gastos no período selecionado para sugerir.",
+ "suggestError": "Não foi possível carregar as sugestões. Tente novamente em instantes."
},
"goals": {
"title": "Metas",
diff --git a/frontend/src/locales/pt-PT.json b/frontend/src/locales/pt-PT.json
index fc48ebb0..591f1674 100644
--- a/frontend/src/locales/pt-PT.json
+++ b/frontend/src/locales/pt-PT.json
@@ -1371,7 +1371,17 @@
"confirmDeleteDescription": "O orçamento para \"{{name}}\" será eliminado permanentemente. As transações existentes não são afetadas. Esta ação não pode ser desfeita.",
"confirmDeleteRecurringDescription": "O orçamento recorrente para \"{{name}}\" será eliminado permanentemente. Esta definição deixará de se aplicar aos meses seguintes. As transações existentes não são afetadas. Esta ação não pode ser desfeita.",
"repeatEveryMonth": "Repetir todo mês",
- "recurringLabel": "Recorrente"
+ "recurringLabel": "Recorrente",
+ "suggest": "Sugerir pelo histórico",
+ "suggestTitle": "Sugerir orçamentos",
+ "suggestDescription": "Limites propostos com base na sua média de gastos mensais nos últimos {{months}} meses.",
+ "suggestPeriod": "Período",
+ "suggestMonths": "meses",
+ "suggestSpent": "Gasto de {{amount}} no período",
+ "suggestCreate": "Criar orçamentos",
+ "suggestCreated": "{{count}} orçamentos criados",
+ "suggestEmpty": "Sem histórico de gastos no período selecionado para sugerir.",
+ "suggestError": "Não foi possível carregar as sugestões. Tente novamente dentro de momentos."
},
"goals": {
"title": "Objetivos",
diff --git a/frontend/src/locales/ru.json b/frontend/src/locales/ru.json
index b8158de8..91f7a517 100644
--- a/frontend/src/locales/ru.json
+++ b/frontend/src/locales/ru.json
@@ -1384,7 +1384,17 @@
"confirmDeleteDescription": "Бюджет для «{{name}}» будет удалён навсегда. Существующие транзакции не будут затронуты. Это действие нельзя отменить.",
"confirmDeleteRecurringDescription": "Регулярный бюджет для «{{name}}» будет удалён навсегда. Это определение больше не будет применяться в последующих месяцах. Существующие транзакции не будут затронуты. Это действие нельзя отменить.",
"repeatEveryMonth": "Повторять каждый месяц",
- "recurringLabel": "Регулярный"
+ "recurringLabel": "Регулярный",
+ "suggest": "Предложить из истории",
+ "suggestTitle": "Предложить бюджеты",
+ "suggestDescription": "Рекомендуемые лимиты на основе средних месячных расходов за последние {{months}} месяцев.",
+ "suggestPeriod": "Период",
+ "suggestMonths": "мес.",
+ "suggestSpent": "Потрачено за период: {{amount}}",
+ "suggestCreate": "Создать бюджеты",
+ "suggestCreated": "Создано бюджетов: {{count}}",
+ "suggestEmpty": "Нет истории расходов за выбранный период.",
+ "suggestError": "Не удалось загрузить предложения. Попробуйте ещё раз чуть позже."
},
"goals": {
"title": "Цели",
diff --git a/frontend/src/locales/sk.json b/frontend/src/locales/sk.json
index 85e69441..9a5b1108 100644
--- a/frontend/src/locales/sk.json
+++ b/frontend/src/locales/sk.json
@@ -1435,7 +1435,17 @@
"confirmDeleteDescription": "Rozpočet pre „{{name}}“ bude natrvalo vymazaný. Existujúce transakcie to neovplyvní. Túto akciu nie je možné vrátiť späť.",
"confirmDeleteRecurringDescription": "Opakovaný rozpočet pre „{{name}}“ bude natrvalo vymazaný. Táto definícia sa už nebude vzťahovať na ďalšie mesiace. Existujúce transakcie to neovplyvní. Túto akciu nie je možné vrátiť späť.",
"repeatEveryMonth": "Opakovať každý mesiac",
- "recurringLabel": "Opakovaný"
+ "recurringLabel": "Opakovaný",
+ "suggest": "Navrhnúť z histórie",
+ "suggestTitle": "Navrhnúť rozpočty",
+ "suggestDescription": "Navrhnuté limity na základe vášho priemerného mesačného výdavku za posledné {{months}} mesiace.",
+ "suggestPeriod": "Obdobie",
+ "suggestMonths": "mesiacov",
+ "suggestSpent": "Vynaložené za obdobie: {{amount}}",
+ "suggestCreate": "Vytvoriť rozpočty",
+ "suggestCreated": "Vytvorené {{count}} rozpočtov",
+ "suggestEmpty": "Vo vybranom období nie je história výdavkov.",
+ "suggestError": "Návrhy sa nepodarilo načítať. Skúste to znova o chvíľu."
},
"goals": {
"title": "Ciele",
diff --git a/frontend/src/locales/uk.json b/frontend/src/locales/uk.json
index c80b1ab5..8c95b898 100644
--- a/frontend/src/locales/uk.json
+++ b/frontend/src/locales/uk.json
@@ -1384,7 +1384,17 @@
"confirmDeleteDescription": "Бюджет для «{{name}}» буде видалено назавжди. Наявні транзакції не будуть порушені. Цю дію не можна скасувати.",
"confirmDeleteRecurringDescription": "Регулярний бюджет для «{{name}}» буде видалено назавжди. Це визначення більше не застосовуватиметься в наступних місяцях. Наявні транзакції не будуть порушені. Цю дію не можна скасувати.",
"repeatEveryMonth": "Повторювати щомісяця",
- "recurringLabel": "Регулярний"
+ "recurringLabel": "Регулярний",
+ "suggest": "Запропонувати з історії",
+ "suggestTitle": "Запропонувати бюджети",
+ "suggestDescription": "Рекомендовані ліміти на основі середніх місячних витрат за останні {{months}} місяців.",
+ "suggestPeriod": "Період",
+ "suggestMonths": "міс.",
+ "suggestSpent": "Потрачено за період: {{amount}}",
+ "suggestCreate": "Створити бюджети",
+ "suggestCreated": "Створено бюджетів: {{count}}",
+ "suggestEmpty": "Немає історії витрат за обраний період.",
+ "suggestError": "Не вдалося завантажити пропозиції. Спробуйте ще раз трохи згодом."
},
"goals": {
"title": "Цілі",
diff --git a/frontend/src/pages/budgets.test.tsx b/frontend/src/pages/budgets.test.tsx
new file mode 100644
index 00000000..f86dcef0
--- /dev/null
+++ b/frontend/src/pages/budgets.test.tsx
@@ -0,0 +1,207 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { screen, waitFor, within } from '@testing-library/react'
+import { format } from 'date-fns'
+
+import BudgetsPage from '@/pages/budgets'
+import { renderWithProviders, t } from '@/test/utils'
+
+const api = vi.hoisted(() => ({
+ budgets: {
+ list: vi.fn(),
+ create: vi.fn(),
+ update: vi.fn(),
+ delete: vi.fn(),
+ comparison: vi.fn(),
+ suggestions: vi.fn(),
+ createBatch: vi.fn(),
+ },
+ categories: {
+ list: vi.fn(),
+ listIncludingHidden: vi.fn(),
+ },
+ categoryGroups: {
+ list: vi.fn(),
+ },
+}))
+
+vi.mock('@/lib/api', () => ({
+ budgets: api.budgets,
+ categories: api.categories,
+ categoryGroups: api.categoryGroups,
+}))
+
+vi.mock('@/hooks/use-display-locale', () => ({
+ useDisplayLocale: () => 'en-US',
+ useDateLocale: () => 'en-US',
+}))
+
+vi.mock('@/contexts/auth-context', () => ({
+ useAuth: () => ({ user: { preferences: { currency_display: 'USD' } } }),
+}))
+
+vi.mock('@/contexts/workspace-context', () => ({
+ useWorkspace: () => ({ canWrite: true }),
+}))
+
+vi.mock('@/hooks/use-privacy-mode', () => ({
+ usePrivacyMode: () => ({ mask: (value: string) => value }),
+}))
+
+const categories = [
+ {
+ id: 'cat-groceries', user_id: 'user-1', group_id: null, name: 'Groceries',
+ icon: '', color: '#34d399', is_system: false, is_hidden: false,
+ treat_as_transfer: false, is_ignored: false,
+ },
+ {
+ id: 'cat-utilities', user_id: 'user-1', group_id: null, name: 'Utilities',
+ icon: '', color: '#f59e0b', is_system: false, is_hidden: false,
+ treat_as_transfer: false, is_ignored: false,
+ },
+]
+
+function suggestion(partial: Record<string, unknown>) {
+ return {
+ category_id: 'cat-groceries',
+ category_name: 'Groceries',
+ category_icon: '',
+ category_color: '#34d399',
+ group_id: null,
+ group_name: null,
+ suggested_amount: '120.50',
+ total_spent: '361.50',
+ months_with_data: 3,
+ existing_budget: false,
+ ...partial,
+ }
+}
+
+function mockSuggestions(suggestions: unknown[]) {
+ api.budgets.suggestions.mockResolvedValue({
+ month: '2026-10-01', months_requested: 3, months_analyzed: 3, suggestions,
+ })
+}
+
+const expectedMonth = `${format(new Date(), 'yyyy-MM')}-01`
+
+describe('BudgetsPage suggestions', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ api.budgets.list.mockResolvedValue([])
+ api.categories.list.mockResolvedValue(categories)
+ api.categories.listIncludingHidden.mockResolvedValue(categories)
+ api.categoryGroups.list.mockResolvedValue([])
+ })
+
+ it('offers the suggest button next to the add button', async () => {
+ renderWithProviders(<BudgetsPage />, { route: '/budgets' })
+
+ expect(await screen.findByRole('button', { name: t('budgets.suggest') })).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: t('budgets.add') })).toBeInTheDocument()
+ })
+
+ it('lists only categories without a budget and creates them in one batch', async () => {
+ mockSuggestions([
+ suggestion({}),
+ suggestion({
+ category_id: 'cat-utilities',
+ category_name: 'Utilities',
+ suggested_amount: '80.00',
+ total_spent: '240.00',
+ existing_budget: true,
+ }),
+ ])
+ api.budgets.createBatch.mockResolvedValue([{ id: 'b1', user_id: 'user-1', category_id: 'cat-groceries', amount: 120.5, month: expectedMonth, is_recurring: false }])
+ const { user } = renderWithProviders(<BudgetsPage />, { route: '/budgets' })
+
+ await user.click(await screen.findByRole('button', { name: t('budgets.suggest') }))
+ const dialog = await screen.findByRole('dialog')
+
+ expect(within(dialog).getByText('Groceries')).toBeInTheDocument()
+ expect(within(dialog).queryByText('Utilities')).not.toBeInTheDocument()
+ expect(within(dialog).getByDisplayValue('120.50')).toBeInTheDocument()
+ expect(api.budgets.suggestions).toHaveBeenCalledWith(expectedMonth, 3)
+
+ await user.click(within(dialog).getByRole('button', { name: t('budgets.suggestCreate') }))
+
+ await waitFor(() => {
+ expect(api.budgets.createBatch).toHaveBeenCalledWith({
+ month: expectedMonth,
+ is_recurring: false,
+ items: [{ category_id: 'cat-groceries', amount: 120.5 }],
+ })
+ })
+ await waitFor(() => expect(api.budgets.list.mock.calls.length).toBeGreaterThanOrEqual(2))
+ })
+
+ it('shows the empty message when every category already has a budget', async () => {
+ mockSuggestions([suggestion({ existing_budget: true })])
+ const { user } = renderWithProviders(<BudgetsPage />, { route: '/budgets' })
+
+ await user.click(await screen.findByRole('button', { name: t('budgets.suggest') }))
+ const dialog = await screen.findByRole('dialog')
+
+ expect(within(dialog).getByText(t('budgets.suggestEmpty'))).toBeInTheDocument()
+ expect(within(dialog).getByRole('button', { name: t('budgets.suggestCreate') })).toBeDisabled()
+ })
+
+ it('shows an error, not the empty message, when suggestions fail to load', async () => {
+ api.budgets.suggestions.mockRejectedValue(new Error('server error'))
+ const { user } = renderWithProviders(<BudgetsPage />, { route: '/budgets' })
+
+ await user.click(await screen.findByRole('button', { name: t('budgets.suggest') }))
+ const dialog = await screen.findByRole('dialog')
+
+ expect(await within(dialog).findByText(t('budgets.suggestError'))).toBeInTheDocument()
+ expect(within(dialog).queryByText(t('budgets.suggestEmpty'))).not.toBeInTheDocument()
+ expect(within(dialog).getByRole('button', { name: t('budgets.suggestCreate') })).toBeDisabled()
+ })
+
+ it('only sends checked rows with a positive amount', async () => {
+ mockSuggestions([
+ suggestion({}),
+ suggestion({
+ category_id: 'cat-utilities',
+ category_name: 'Utilities',
+ suggested_amount: '80.00',
+ total_spent: '240.00',
+ }),
+ ])
+ api.budgets.createBatch.mockResolvedValue([{ id: 'b1', user_id: 'user-1', category_id: 'cat-utilities', amount: 80, month: expectedMonth, is_recurring: false }])
+ const { user } = renderWithProviders(<BudgetsPage />, { route: '/budgets' })
+
+ await user.click(await screen.findByRole('button', { name: t('budgets.suggest') }))
+ const dialog = await screen.findByRole('dialog')
+
+ await user.click(within(dialog).getByRole('checkbox', { name: 'Groceries' }))
+ await user.click(within(dialog).getByRole('button', { name: t('budgets.suggestCreate') }))
+
+ await waitFor(() => {
+ expect(api.budgets.createBatch).toHaveBeenCalledWith({
+ month: expectedMonth,
+ is_recurring: false,
+ items: [{ category_id: 'cat-utilities', amount: 80 }],
+ })
+ })
+ })
+
+ it('marks the created budgets as recurring when the repeat checkbox is on', async () => {
+ mockSuggestions([suggestion({})])
+ api.budgets.createBatch.mockResolvedValue([{ id: 'b1', user_id: 'user-1', category_id: 'cat-groceries', amount: 120.5, month: expectedMonth, is_recurring: true }])
+ const { user } = renderWithProviders(<BudgetsPage />, { route: '/budgets' })
+
+ await user.click(await screen.findByRole('button', { name: t('budgets.suggest') }))
+ const dialog = await screen.findByRole('dialog')
+
+ await user.click(within(dialog).getByRole('checkbox', { name: t('budgets.repeatEveryMonth') }))
+ await user.click(within(dialog).getByRole('button', { name: t('budgets.suggestCreate') }))
+
+ await waitFor(() => {
+ expect(api.budgets.createBatch).toHaveBeenCalledWith({
+ month: expectedMonth,
+ is_recurring: true,
+ items: [{ category_id: 'cat-groceries', amount: 120.5 }],
+ })
+ })
+ })
+})
diff --git a/frontend/src/pages/budgets.tsx b/frontend/src/pages/budgets.tsx
index cdb6fe80..d17c2272 100644
--- a/frontend/src/pages/budgets.tsx
+++ b/frontend/src/pages/budgets.tsx
@@ -17,8 +17,8 @@ import {
DialogTitle,
DialogFooter,
} from '@/components/ui/dialog'
-import type { Budget } from '@/types'
-import { Pencil, Trash2, Plus, Repeat, CalendarIcon } from 'lucide-react'
+import type { Budget, BudgetSuggestion } from '@/types'
+import { Pencil, Trash2, Plus, Repeat, CalendarIcon, Sparkles } from 'lucide-react'
import { format } from 'date-fns'
import { Popover, PopoverTrigger, PopoverContent } from '@/components/ui/popover'
import { MonthPicker } from '@/components/ui/monthpicker'
@@ -69,6 +69,10 @@ export default function BudgetsPage() {
const [dialogOpen, setDialogOpen] = useState(false)
const [editing, setEditing] = useState<Budget | null>(null)
const [deletingBudget, setDeletingBudget] = useState<Budget | null>(null)
+ const [suggestOpen, setSuggestOpen] = useState(false)
+ const [suggestMonths, setSuggestMonths] = useState(3)
+ const [suggestRecurring, setSuggestRecurring] = useState(false)
+ const [suggestEdits, setSuggestEdits] = useState<Record<string, { checked: boolean; amount: string }>>({})
const { data: budgetsList } = useQuery({
queryKey: ['budgets', selectedMonth],
@@ -92,6 +96,43 @@ export default function BudgetsPage() {
queryFn: groupsApi.list,
})
+ const { data: suggestionData, isPending: suggestionsPending, isError: suggestionsError } = useQuery({
+ queryKey: ['budgets', 'suggestions', monthParam, suggestMonths],
+ queryFn: () => budgetsApi.suggestions(monthParam, suggestMonths),
+ enabled: suggestOpen,
+ })
+
+ // Rows default to the fetched suggestions; user edits layer on top.
+ // Edits are reset when the dialog opens or the period changes.
+ const rowFor = (s: BudgetSuggestion) =>
+ suggestEdits[s.category_id] ?? { checked: !s.existing_budget, amount: s.suggested_amount }
+
+ const suggestable = (suggestionData?.suggestions ?? []).filter((s) => !s.existing_budget)
+ const batchItems = suggestable.filter((s) => {
+ const row = rowFor(s)
+ return row.checked && parseFloat(row.amount) > 0
+ })
+
+ const batchMutation = useMutation({
+ mutationFn: () =>
+ budgetsApi.createBatch({
+ month: monthParam,
+ is_recurring: suggestRecurring,
+ items: batchItems.map((s) => ({
+ category_id: s.category_id,
+ amount: parseFloat(rowFor(s).amount),
+ })),
+ }),
+ onSuccess: (created) => {
+ queryClient.invalidateQueries({ queryKey: ['budgets'] })
+ setSuggestOpen(false)
+ toast.success(t('budgets.suggestCreated', { count: created.length }))
+ },
+ onError: (err: unknown) => {
+ toast.error(extractApiError(err, t('common.error')))
+ },
+ })
+
const createMutation = useMutation({
mutationFn: (data: { category_id: string; amount: number; month: string; is_recurring?: boolean }) =>
budgetsApi.create(data),
@@ -197,9 +238,14 @@ export default function BudgetsPage() {
title={t('budgets.title')}
action={
canWrite ? (
- <Button size="sm" className="gap-1.5 h-8" onClick={() => { setEditing(null); setDialogOpen(true) }}>
- <Plus size={13} /> {t('budgets.add')}
- </Button>
+ <div className="flex items-center gap-2">
+ <Button size="sm" variant="outline" className="gap-1.5 h-8" onClick={() => { setSuggestEdits({}); setSuggestOpen(true) }}>
+ <Sparkles size={13} /> {t('budgets.suggest')}
+ </Button>
+ <Button size="sm" className="gap-1.5 h-8" onClick={() => { setEditing(null); setDialogOpen(true) }}>
+ <Plus size={13} /> {t('budgets.add')}
+ </Button>
+ </div>
) : undefined
}
/>
@@ -335,6 +381,101 @@ export default function BudgetsPage() {
</DialogContent>
</Dialog>
+ <Dialog open={suggestOpen} onOpenChange={(open) => { setSuggestOpen(open); if (!open) setSuggestEdits({}) }}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>{t('budgets.suggestTitle')}</DialogTitle>
+ </DialogHeader>
+ <div className="space-y-4">
+ <div className="flex items-center gap-4">
+ <div className="space-y-1">
+ <Label>{t('budgets.suggestPeriod')}</Label>
+ <select
+ value={suggestMonths}
+ onChange={(e) => { setSuggestMonths(Number(e.target.value)); setSuggestEdits({}) }}
+ className="w-full border border-border rounded-lg px-3 py-2 text-sm bg-card text-foreground focus:outline-none focus:ring-2 focus:ring-primary"
+ >
+ <option value={3}>3 {t('budgets.suggestMonths')}</option>
+ <option value={6}>6 {t('budgets.suggestMonths')}</option>
+ <option value={12}>12 {t('budgets.suggestMonths')}</option>
+ </select>
+ </div>
+ <label className="flex items-center gap-2 cursor-pointer mt-5">
+ <input
+ type="checkbox"
+ checked={suggestRecurring}
+ onChange={(e) => setSuggestRecurring(e.target.checked)}
+ className="rounded border-border"
+ />
+ <span className="text-sm text-foreground">{t('budgets.repeatEveryMonth')}</span>
+ </label>
+ </div>
+ <p className="text-sm text-muted-foreground">
+ {t('budgets.suggestDescription', { months: suggestMonths })}
+ </p>
+ {suggestionsPending ? (
+ <p className="text-sm text-muted-foreground text-center py-8">{t('common.loading')}</p>
+ ) : suggestionsError ? (
+ <p role="alert" className="text-sm text-destructive text-center py-8">{t('budgets.suggestError')}</p>
+ ) : suggestable.length === 0 ? (
+ <p className="text-sm text-muted-foreground text-center py-8">{t('budgets.suggestEmpty')}</p>
+ ) : (
+ <div className="max-h-72 overflow-y-auto rounded-lg border border-border">
+ {suggestable.map((s) => {
+ const row = rowFor(s)
+ return (
+ <div key={s.category_id} className="flex items-center gap-3 border-b border-border last:border-0 px-3 py-2">
+ <input
+ type="checkbox"
+ checked={row.checked}
+ onChange={(e) =>
+ setSuggestEdits((prev) => ({
+ ...prev,
+ [s.category_id]: { ...rowFor(s), checked: e.target.checked },
+ }))
+ }
+ className="rounded border-border"
+ aria-label={s.category_name}
+ />
+ <span className="flex-1 text-sm font-medium text-foreground truncate">{s.category_name}</span>
+ <span className="text-xs text-muted-foreground tabular-nums whitespace-nowrap">
+ {t('budgets.suggestSpent', { amount: formatCurrency(Number(s.total_spent), userCurrency, locale) })}
+ </span>
+ <Input
+ type="number"
+ step="0.01"
+ min="0"
+ value={row.amount}
+ onChange={(e) =>
+ setSuggestEdits((prev) => ({
+ ...prev,
+ [s.category_id]: { ...rowFor(s), amount: e.target.value },
+ }))
+ }
+ className="w-24 h-8"
+ aria-label={`${s.category_name} ${t('budgets.amount')}`}
+ />
+ </div>
+ )
+ })}
+ </div>
+ )}
+ </div>
+ <DialogFooter>
+ <Button type="button" variant="outline" onClick={() => setSuggestOpen(false)}>
+ {t('common.cancel')}
+ </Button>
+ <Button
+ type="button"
+ disabled={batchMutation.isPending || batchItems.length === 0}
+ onClick={() => batchMutation.mutate()}
+ >
+ {t('budgets.suggestCreate')}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+
<DeleteConfirmationDialog
open={!!deletingBudget}
title={t('budgets.confirmDeleteTitle')}
diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts
index 87fe501b..4d7de4de 100644
--- a/frontend/src/types/index.ts
+++ b/frontend/src/types/index.ts
@@ -850,6 +850,26 @@ export interface BudgetVsActual {
is_recurring: boolean
}
+export interface BudgetSuggestion {
+ category_id: string
+ category_name: string
+ category_icon: string
+ category_color: string
+ group_id: string | null
+ group_name: string | null
+ suggested_amount: string
+ total_spent: string
+ months_with_data: number
+ existing_budget: boolean
+}
+
+export interface BudgetSuggestionResponse {
+ month: string
+ months_requested: number
+ months_analyzed: number
+ suggestions: BudgetSuggestion[]
+}
+
export interface Asset {
id: string
user_id: string