Open-source personal finance manager. Self-hosted, privacy-first.
Add cash-flow transaction calendar view (#401)
Romulo Gatto66ef522804d9
diff --git a/backend/app/api/transactions.py b/backend/app/api/transactions.pyindex a38f9b8e..55b78f5f 100644--- a/backend/app/api/transactions.py+++ b/backend/app/api/transactions.py@@ -16,8 +16,10 @@ from app.core.workspace_context import (current_writable_workspace,)from app.schemas.transaction import BulkAddToGroupRequest, BulkCategorizeRequest, BulkTagsRequest, CreateCounterpartRequest, LinkTransferRequest, TransactionCreate, TransactionRead, TransactionUpdate, TransferCreate, TransferRead+from app.schemas.transaction_calendar import TransactionCalendarResponsefrom app.services import transaction_servicefrom app.services.admin_service import get_credit_card_accounting_mode+from app.services.transaction_calendar_service import get_transaction_calendarrouter = APIRouter(prefix="/api/transactions", tags=["transactions"])@@ -133,6 +135,23 @@ async def list_transactions(return PaginatedTransactions(items=items, total=total, page=page, limit=limit, summary=summary_out)[email protected]("/calendar", response_model=TransactionCalendarResponse)+async def transaction_calendar(+ month: Optional[date] = Query(None),+ account_id: Optional[uuid.UUID] = Query(None),+ account_ids: Optional[List[uuid.UUID]] = Query(None),+ ctx: WorkspaceContext = Depends(current_workspace),+ session: AsyncSession = Depends(get_async_session),+):+ return await get_transaction_calendar(+ session,+ ctx.workspace.id,+ ctx.user_id,+ month,+ account_ids=_merge_id_filters(account_id, account_ids),+ )++@router.get("/export")async def export_transactions(account_id: Optional[uuid.UUID] = Query(None),diff --git a/backend/app/schemas/transaction_calendar.py b/backend/app/schemas/transaction_calendar.pynew file mode 100644index 00000000..97510e48--- /dev/null+++ b/backend/app/schemas/transaction_calendar.py@@ -0,0 +1,50 @@+import uuid+from datetime import date+from typing import Literal, Optional++from pydantic import BaseModel, Field+++class TransactionCalendarItem(BaseModel):+ kind: Literal["actual", "projected"]+ id: Optional[uuid.UUID] = None+ recurring_id: Optional[uuid.UUID] = None+ date: date+ description: str+ amount: float+ amount_primary: Optional[float] = None+ currency: str+ type: Literal["debit", "credit"]+ account_id: Optional[uuid.UUID] = None+ account_name: Optional[str] = None+ category_id: Optional[uuid.UUID] = None+ category_name: Optional[str] = None+ category_icon: Optional[str] = None+ category_color: Optional[str] = None+ status: Optional[str] = None+ source: Optional[str] = None+ transfer_pair_id: Optional[uuid.UUID] = None+ is_transfer: bool = False+ is_ignored: bool = False+++class TransactionCalendarDay(BaseModel):+ date: date+ in_month: bool+ ending_balance: float+ income: float = 0.0+ expense: float = 0.0+ transfer_net: float = 0.0+ actual_count: int = 0+ projected_count: int = 0+ has_income: bool = False+ has_expense: bool = False+ has_transfer: bool = False+ items: list[TransactionCalendarItem] = Field(default_factory=list)+++class TransactionCalendarResponse(BaseModel):+ month: str+ currency: str+ account_ids: list[uuid.UUID] | None = None+ days: list[TransactionCalendarDay]diff --git a/backend/app/services/dashboard_service.py b/backend/app/services/dashboard_service.pyindex 5f1e534a..b7d598e8 100644--- a/backend/app/services/dashboard_service.py+++ b/backend/app/services/dashboard_service.py@@ -929,21 +929,22 @@ async def _balance_at(already know the workspace's primary currency."""totals = await _total_balance_by_currency(session, workspace_id, cutoff, account_ids)-- # If all same currency, just sum- if len(totals) <= 1:- return sum(totals.values())+ if not totals:+ return 0.0primary_currency = primary_currency_hint or get_settings().default_currencytotal = 0.0for currency, amount in totals.items():+ if currency == primary_currency:+ total += amount+ continueconverted, _ = await convert(session, Decimal(str(amount)), currency, primary_currency)total += float(converted)return total-async def _daily_deltas(+async def _daily_balance_deltas_by_date(session: AsyncSession,workspace_id: uuid.UUID,start: date,@@ -951,12 +952,14 @@ async def _daily_deltas(*,primary_currency_hint: Optional[str] = None,account_ids: Optional[list[uuid.UUID]] = None,-) -> dict[int, float]:- """Get daily balance deltas for a date range [start, end).+) -> dict[date, float]:+ """Get daily balance deltas for a date range [start, end), keyed by date.+Computes per-account in native currency (using amount_primary only for- foreign txs within an account), grouped by day and account currency,- then converts each currency to primary. This is consistent with _balance_at."""- # Use amount_primary only when tx currency differs from account currency+ foreign txs within an account), grouped by date and account currency,+ then converts each currency to primary. This is consistent with+ ``_balance_at`` and avoids per-transaction FX conversion loops.+ """effective = case((Transaction.currency == Account.currency, Transaction.amount),else_=func.coalesce(Transaction.amount_primary, Transaction.amount),@@ -967,7 +970,7 @@ async def _daily_deltas()result = await session.execute(select(- func.extract("day", Transaction.date).label("day"),+ Transaction.date,Account.currency,func.sum(signed),)@@ -985,30 +988,41 @@ async def _daily_deltas(),*( [Transaction.account_id.in_(account_ids)] if account_ids is not None else [] ),)- .group_by("day", Account.currency)+ .group_by(Transaction.date, Account.currency))- rows = result.all()- # Check if all same currency — skip conversion- currencies_seen = {row[1] for row in rows}- if len(currencies_seen) <= 1:- return {int(row[0]): float(row[2] or 0) for row in rows}-- # Multiple currencies: convert each to primaryprimary_currency = primary_currency_hint or get_settings().default_currency-- deltas: dict[int, float] = {}- for row in rows:- day = int(row[0])- currency = row[1]- amount = float(row[2] or 0)+ deltas: dict[date, float] = {}+ for tx_date, currency, raw_amount in result.all():+ amount = raw_amount or 0if currency != primary_currency:converted, _ = await convert(session, Decimal(str(amount)), currency, primary_currency)- amount = float(converted)- deltas[day] = deltas.get(day, 0) + amount+ amount = converted+ deltas[tx_date] = deltas.get(tx_date, 0.0) + float(amount)return deltas+async def _daily_deltas(+ session: AsyncSession,+ workspace_id: uuid.UUID,+ start: date,+ end: date,+ *,+ primary_currency_hint: Optional[str] = None,+ account_ids: Optional[list[uuid.UUID]] = None,+) -> dict[int, float]:+ """Get daily balance deltas for a date range [start, end), keyed by day-of-month."""+ by_date = await _daily_balance_deltas_by_date(+ session,+ workspace_id,+ start,+ end,+ primary_currency_hint=primary_currency_hint,+ account_ids=account_ids,+ )+ return {tx_date.day: amount for tx_date, amount in by_date.items()}++async def get_balance_history(session: AsyncSession,workspace_id: uuid.UUID,diff --git a/backend/app/services/transaction_calendar_service.py b/backend/app/services/transaction_calendar_service.pynew file mode 100644index 00000000..239b5e47--- /dev/null+++ b/backend/app/services/transaction_calendar_service.py@@ -0,0 +1,349 @@+import uuid+from datetime import date, timedelta+from decimal import Decimal+from typing import Optional++from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession+from sqlalchemy.orm import selectinload++from app.core.config import get_settings+from app.models.account import Account+from app.models.category import Category+from app.models.recurring_transaction import RecurringTransaction+from app.models.transaction import Transaction+from app.models.user import User+from app.schemas.transaction_calendar import (+ TransactionCalendarDay,+ TransactionCalendarItem,+ TransactionCalendarResponse,+)+from app.services.dashboard_service import _balance_at, _daily_balance_deltas_by_date+from app.services.fx_rate_service import convert as fx_convert+from app.services.recurring_transaction_service import get_occurrences_in_range+++async def get_transaction_calendar(+ session: AsyncSession,+ workspace_id: uuid.UUID,+ user_id: uuid.UUID,+ month: Optional[date] = None,+ account_ids: Optional[list[uuid.UUID]] = None,+) -> TransactionCalendarResponse:+ """Build a read-only month-grid transaction calendar.++ The calendar shows posted/manual transactions plus virtual recurring+ occurrences. Virtual rows are never persisted; they only affect the daily+ projected ending balance returned by this read endpoint.+ """+ if month is None:+ month = date.today().replace(day=1)+ month_start = month.replace(day=1)+ if month_start.month == 12:+ month_end = month_start.replace(year=month_start.year + 1, month=1)+ else:+ month_end = month_start.replace(month=month_start.month + 1)++ # Sunday-start grid to match the existing mock/reference. The response+ # includes spillover days so frontend layout does not need to make extra+ # balance queries for previous/next month cells.+ grid_start = month_start - timedelta(days=(month_start.weekday() + 1) % 7)+ last_month_day = month_end - timedelta(days=1)+ grid_end = last_month_day + timedelta(days=6 - ((last_month_day.weekday() + 1) % 7) + 1)++ user = await session.get(User, user_id)+ primary_currency = user.primary_currency if user else get_settings().default_currency++ requested_account_ids = account_ids+ if requested_account_ids is not None and len(requested_account_ids) == 0:+ return _empty_calendar(month_start, grid_start, grid_end, primary_currency, requested_account_ids)++ days = {+ d: TransactionCalendarDay(+ date=d,+ in_month=month_start <= d < month_end,+ ending_balance=0.0,+ )+ for d in _date_range(grid_start, grid_end)+ }++ start_balance = await _balance_at(+ session,+ workspace_id,+ grid_start - timedelta(days=1),+ primary_currency_hint=primary_currency,+ account_ids=requested_account_ids,+ )++ actual_rows = await _load_actual_transactions(+ session, workspace_id, grid_start, grid_end, requested_account_ids+ )+ balance_deltas = await _daily_balance_deltas_by_date(+ session,+ workspace_id,+ grid_start,+ grid_end,+ primary_currency_hint=primary_currency,+ account_ids=requested_account_ids,+ )+ for tx in actual_rows:+ if tx.date not in days:+ continue+ day = days[tx.date]+ amount_primary = await _positive_primary_amount(+ session, tx.amount, tx.currency, primary_currency, tx.amount_primary+ )++ is_transfer = bool(tx.transfer_pair_id) or bool(tx.category and tx.category.treat_as_transfer)+ ignored = bool(tx.is_ignored or (tx.category and tx.category.is_ignored))+ if not ignored:+ if is_transfer or tx.source == "transfer":+ day.transfer_net += await _signed_balance_delta_primary(session, tx, primary_currency)+ day.has_transfer = True+ elif tx.source != "opening_balance":+ if tx.type == "credit":+ day.income += amount_primary+ day.has_income = True+ else:+ day.expense += amount_primary+ day.has_expense = True++ day.actual_count += 1+ day.items.append(_actual_item(tx, amount_primary, is_transfer, ignored))++ projected_items, projected_deltas = await _project_recurring_items(+ session,+ workspace_id,+ primary_currency,+ grid_start,+ grid_end,+ requested_account_ids,+ )+ for item, signed_delta in projected_items:+ day = days[item.date]+ amount_primary = abs(signed_delta)+ if item.is_transfer:+ day.transfer_net += signed_delta+ day.has_transfer = True+ elif item.type == "credit":+ day.income += amount_primary+ day.has_income = True+ else:+ day.expense += amount_primary+ day.has_expense = True+ day.projected_count += 1+ day.items.append(item)++ for delta_date, delta in projected_deltas.items():+ balance_deltas[delta_date] = balance_deltas.get(delta_date, 0.0) + delta++ running = start_balance+ response_days: list[TransactionCalendarDay] = []+ for d in _date_range(grid_start, grid_end):+ running += balance_deltas.get(d, 0.0)+ day = days[d]+ day.ending_balance = round(running, 2)+ day.income = round(day.income, 2)+ day.expense = round(day.expense, 2)+ day.transfer_net = round(day.transfer_net, 2)+ day.items.sort(key=lambda item: (item.kind != "actual", item.type, item.description.lower()))+ response_days.append(day)++ return TransactionCalendarResponse(+ month=month_start.strftime("%Y-%m"),+ currency=primary_currency,+ account_ids=requested_account_ids,+ days=response_days,+ )+++def _empty_calendar(+ month_start: date,+ grid_start: date,+ grid_end: date,+ primary_currency: str,+ account_ids: list[uuid.UUID],+) -> TransactionCalendarResponse:+ return TransactionCalendarResponse(+ month=month_start.strftime("%Y-%m"),+ currency=primary_currency,+ account_ids=account_ids,+ days=[+ TransactionCalendarDay(+ date=d,+ in_month=month_start <= d < _next_month(month_start),+ ending_balance=0.0,+ )+ for d in _date_range(grid_start, grid_end)+ ],+ )+++def _next_month(month_start: date) -> date:+ if month_start.month == 12:+ return month_start.replace(year=month_start.year + 1, month=1)+ return month_start.replace(month=month_start.month + 1)+++def _date_range(start: date, end: date):+ current = start+ while current < end:+ yield current+ current += timedelta(days=1)+++async def _load_actual_transactions(+ session: AsyncSession,+ workspace_id: uuid.UUID,+ start: date,+ end: date,+ account_ids: Optional[list[uuid.UUID]],+) -> list[Transaction]:+ stmt = (+ select(Transaction)+ .join(Account, Transaction.account_id == Account.id)+ .outerjoin(Category, Transaction.category_id == Category.id)+ .where(+ Transaction.workspace_id == workspace_id,+ Account.is_closed == False,+ Transaction.date >= start,+ Transaction.date < end,+ )+ .options(+ selectinload(Transaction.account),+ selectinload(Transaction.category),+ selectinload(Transaction.payee_entity),+ )+ .order_by(Transaction.date.asc(), Transaction.created_at.asc())+ )+ if account_ids is not None:+ stmt = stmt.where(Transaction.account_id.in_(account_ids))+ result = await session.execute(stmt)+ return list(result.scalars().all())+++async def _positive_primary_amount(+ session: AsyncSession,+ amount: Decimal,+ currency: str,+ primary_currency: str,+ stamped_primary: Decimal | float | None = None,+) -> float:+ if currency == primary_currency:+ return float(abs(amount))+ if stamped_primary is not None:+ return float(abs(Decimal(str(stamped_primary))))+ converted, _ = await fx_convert(session, abs(amount), currency, primary_currency)+ return float(converted)+++async def _signed_balance_delta_primary(+ session: AsyncSession,+ tx: Transaction,+ primary_currency: str,+) -> float:+ account_currency = tx.account.currency if tx.account else tx.currency+ effective = tx.amount if tx.currency == account_currency else Decimal(str(tx.amount_primary or tx.amount))+ amount = abs(Decimal(str(effective)))+ if account_currency != primary_currency:+ amount, _ = await fx_convert(session, amount, account_currency, primary_currency)+ signed = amount if tx.type == "credit" else -amount+ return float(signed)+++def _actual_item(tx: Transaction, amount_primary: float, is_transfer: bool, ignored: bool) -> TransactionCalendarItem:+ category = tx.category+ account = tx.account+ return TransactionCalendarItem(+ kind="actual",+ id=tx.id,+ date=tx.date,+ description=tx.description,+ amount=float(tx.amount),+ amount_primary=amount_primary,+ currency=tx.currency,+ type=tx.type,+ account_id=tx.account_id,+ account_name=account.display_name or account.name if account else None,+ category_id=tx.category_id,+ category_name=category.name if category else None,+ category_icon=category.icon if category else None,+ category_color=category.color if category else None,+ status=tx.status,+ source=tx.source,+ transfer_pair_id=tx.transfer_pair_id,+ is_transfer=is_transfer,+ is_ignored=ignored,+ )+++async def _project_recurring_items(+ session: AsyncSession,+ workspace_id: uuid.UUID,+ primary_currency: str,+ start: date,+ end: date,+ account_ids: Optional[list[uuid.UUID]],+) -> tuple[list[tuple[TransactionCalendarItem, float]], dict[date, float]]:+ stmt = (+ select(RecurringTransaction)+ .join(Account, RecurringTransaction.account_id == Account.id)+ .outerjoin(Category, RecurringTransaction.category_id == Category.id)+ .where(+ RecurringTransaction.workspace_id == workspace_id,+ RecurringTransaction.is_active == True,+ RecurringTransaction.start_date < end,+ Account.is_closed == False,+ )+ .options(+ selectinload(RecurringTransaction.account),+ selectinload(RecurringTransaction.category),+ )+ )+ if account_ids is not None:+ stmt = stmt.where(RecurringTransaction.account_id.in_(account_ids))+ result = await session.execute(stmt)+ recurring_rows = list(result.scalars().all())++ items: list[tuple[TransactionCalendarItem, float]] = []+ deltas: dict[date, float] = {}+ for rec in recurring_rows:+ if rec.account_id is None:+ continue+ occurrences = get_occurrences_in_range(+ start=rec.next_occurrence,+ frequency=rec.frequency,+ end_date=rec.end_date,+ range_start=start,+ range_end=end,+ intended_day=rec.day_of_month or rec.start_date.day,+ )+ category = rec.category+ account = rec.account+ amount_primary = await _positive_primary_amount(+ session, rec.amount, rec.currency, primary_currency, rec.amount_primary+ )+ signed_delta = amount_primary if rec.type == "credit" else -amount_primary+ is_transfer = bool(category and category.treat_as_transfer)+ for occ_date in occurrences:+ item = TransactionCalendarItem(+ kind="projected",+ recurring_id=rec.id,+ date=occ_date,+ description=rec.description,+ amount=float(rec.amount),+ amount_primary=amount_primary,+ currency=rec.currency,+ type=rec.type,+ account_id=rec.account_id,+ account_name=account.display_name or account.name if account else None,+ category_id=rec.category_id,+ category_name=category.name if category else None,+ category_icon=category.icon if category else None,+ category_color=category.color if category else None,+ source="recurring",+ is_transfer=is_transfer,+ )+ items.append((item, signed_delta))+ deltas[occ_date] = deltas.get(occ_date, 0.0) + signed_delta+ return items, deltasdiff --git a/backend/tests/test_transaction_calendar_service.py b/backend/tests/test_transaction_calendar_service.pynew file mode 100644index 00000000..57cd4f43--- /dev/null+++ b/backend/tests/test_transaction_calendar_service.py@@ -0,0 +1,246 @@+import uuid+from datetime import date+from decimal import Decimal++import pytest+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.account import Account+from app.models.category import Category+from app.models.fx_rate import FxRate+from app.models.recurring_transaction import RecurringTransaction+from app.models.transaction import Transaction+from app.services.transaction_calendar_service import get_transaction_calendar+++async def test_transaction_calendar_combines_actual_projected_and_balances(+ session: AsyncSession, test_user, test_workspace+):+ account = Account(+ id=uuid.uuid4(),+ user_id=test_user.id,+ workspace_id=test_workspace.id,+ name="Person",+ type="checking",+ balance=Decimal("0"),+ currency="BRL",+ )+ category = Category(+ id=uuid.uuid4(),+ user_id=test_user.id,+ workspace_id=test_workspace.id,+ name="Bills",+ icon="receipt",+ color="#f97316",+ )+ session.add_all([account, category])+ await session.flush()++ salary = Transaction(+ id=uuid.uuid4(),+ user_id=test_user.id,+ workspace_id=test_workspace.id,+ account_id=account.id,+ category_id=category.id,+ description="Salary",+ amount=Decimal("1000"),+ currency="BRL",+ date=date(2026, 7, 2),+ type="credit",+ source="manual",+ )+ groceries = Transaction(+ id=uuid.uuid4(),+ user_id=test_user.id,+ workspace_id=test_workspace.id,+ account_id=account.id,+ category_id=category.id,+ description="Groceries",+ amount=Decimal("200"),+ currency="BRL",+ date=date(2026, 7, 5),+ type="debit",+ source="manual",+ )+ rent = RecurringTransaction(+ id=uuid.uuid4(),+ user_id=test_user.id,+ workspace_id=test_workspace.id,+ account_id=account.id,+ category_id=category.id,+ description="Rent",+ amount=Decimal("300"),+ currency="BRL",+ type="debit",+ frequency="monthly",+ start_date=date(2026, 7, 10),+ next_occurrence=date(2026, 7, 10),+ )+ session.add_all([salary, groceries, rent])+ await session.commit()++ calendar = await get_transaction_calendar(+ session, test_workspace.id, test_user.id, month=date(2026, 7, 1)+ )++ assert calendar.month == "2026-07"+ assert calendar.currency == "BRL"+ assert calendar.days[0].date == date(2026, 6, 28)+ assert calendar.days[-1].date == date(2026, 8, 1)++ july_2 = next(day for day in calendar.days if day.date == date(2026, 7, 2))+ assert july_2.income == 1000.0+ assert july_2.ending_balance == 1000.0+ assert july_2.actual_count == 1+ assert july_2.items[0].kind == "actual"++ july_5 = next(day for day in calendar.days if day.date == date(2026, 7, 5))+ assert july_5.expense == 200.0+ assert july_5.ending_balance == 800.0++ july_10 = next(day for day in calendar.days if day.date == date(2026, 7, 10))+ assert july_10.projected_count == 1+ assert july_10.expense == 300.0+ assert july_10.ending_balance == 500.0+ assert july_10.items[0].kind == "projected"+ assert july_10.items[0].recurring_id == rent.id+++async def test_transaction_calendar_respects_account_filter(+ session: AsyncSession, test_user, test_workspace+):+ kept = Account(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ name="Kept", type="checking", balance=Decimal("0"), currency="BRL",+ )+ other = Account(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ name="Other", type="checking", balance=Decimal("0"), currency="BRL",+ )+ session.add_all([kept, other])+ await session.flush()+ session.add_all([+ Transaction(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ account_id=kept.id, description="Kept income", amount=Decimal("100"),+ currency="BRL", date=date(2026, 7, 3), type="credit", source="manual",+ ),+ Transaction(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ account_id=other.id, description="Other income", amount=Decimal("999"),+ currency="BRL", date=date(2026, 7, 3), type="credit", source="manual",+ ),+ ])+ await session.commit()++ calendar = await get_transaction_calendar(+ session,+ test_workspace.id,+ test_user.id,+ month=date(2026, 7, 1),+ account_ids=[kept.id],+ )++ july_3 = next(day for day in calendar.days if day.date == date(2026, 7, 3))+ assert july_3.income == 100.0+ assert july_3.ending_balance == 100.0+ assert [item.description for item in july_3.items] == ["Kept income"]+++async def test_transaction_calendar_single_foreign_account_uses_primary_currency_balance(+ session: AsyncSession, test_user, test_workspace+):+ account = Account(+ id=uuid.uuid4(),+ user_id=test_user.id,+ workspace_id=test_workspace.id,+ name="USD checking",+ type="checking",+ balance=Decimal("0"),+ currency="USD",+ )+ session.add_all([+ account,+ FxRate(+ base_currency="USD",+ quote_currency="BRL",+ date=date.today(),+ rate=Decimal("5"),+ source="test",+ ),+ ])+ await session.flush()+ session.add_all([+ Transaction(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ account_id=account.id, description="Starting cash", amount=Decimal("100"),+ currency="USD", date=date(2026, 6, 20), type="credit", source="opening_balance",+ ),+ Transaction(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ account_id=account.id, description="Coffee", amount=Decimal("10"),+ currency="USD", date=date(2026, 7, 2), type="debit", source="manual",+ ),+ ])+ await session.commit()++ calendar = await get_transaction_calendar(+ session,+ test_workspace.id,+ test_user.id,+ month=date(2026, 7, 1),+ account_ids=[account.id],+ )++ assert calendar.currency == "BRL"+ july_1 = next(day for day in calendar.days if day.date == date(2026, 7, 1))+ assert july_1.ending_balance == 500.0+ july_2 = next(day for day in calendar.days if day.date == date(2026, 7, 2))+ assert july_2.expense == 50.0+ assert july_2.ending_balance == 450.0+++async def test_transaction_calendar_skips_closed_account_recurring_projections(+ session: AsyncSession, test_user, test_workspace+):+ closed_account = Account(+ id=uuid.uuid4(),+ user_id=test_user.id,+ workspace_id=test_workspace.id,+ name="Closed",+ type="checking",+ balance=Decimal("0"),+ currency="BRL",+ is_closed=True,+ )+ session.add(closed_account)+ await session.flush()+ session.add(+ RecurringTransaction(+ id=uuid.uuid4(),+ user_id=test_user.id,+ workspace_id=test_workspace.id,+ account_id=closed_account.id,+ description="Old subscription",+ amount=Decimal("25"),+ currency="BRL",+ type="debit",+ frequency="monthly",+ start_date=date(2026, 7, 10),+ next_occurrence=date(2026, 7, 10),+ )+ )+ await session.commit()++ calendar = await get_transaction_calendar(+ session, test_workspace.id, test_user.id, month=date(2026, 7, 1)+ )++ july_10 = next(day for day in calendar.days if day.date == date(2026, 7, 10))+ assert july_10.projected_count == 0+ assert july_10.items == []+ assert july_10.ending_balance == 0.0diff --git a/docker-compose.yml b/docker-compose.ymlindex 565410be..eba2ea29 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -21,7 +21,10 @@ x-backend-env: &backend-envENABLE_BANKING_APP_ID: ${ENABLE_BANKING_APP_ID:-}ENABLE_BANKING_PRIVATE_KEY_FILE: ${ENABLE_BANKING_PRIVATE_KEY_FILE:-/app/secrets/enable_banking_private.pem}ENABLE_BANKING_API_URL: ${ENABLE_BANKING_API_URL:-https://api.enablebanking.com}- ENABLE_BANKING_OAUTH_REDIRECT_URI: ${ENABLE_BANKING_OAUTH_REDIRECT_URI:-http://localhost:${FRONTEND_PORT:-3000}/oauth/callback}+ # Compose does not support nested interpolation inside ${VAR:-default}.+ # Keep this default parseable; override ENABLE_BANKING_OAUTH_REDIRECT_URI+ # explicitly when testing Enable Banking with a non-default redirect URL.+ ENABLE_BANKING_OAUTH_REDIRECT_URI: ${ENABLE_BANKING_OAUTH_REDIRECT_URI:-http://localhost:3000/oauth/callback}SIMPLEFIN_ENABLED: ${SIMPLEFIN_ENABLED:-false}SIMPLEFIN_API_URL: ${SIMPLEFIN_API_URL:-https://beta-bridge.simplefin.org}OIDC_ENABLED: ${OIDC_ENABLED:-false}diff --git a/docs/transaction-calendar/calendar-all-accounts-dark.png b/docs/transaction-calendar/calendar-all-accounts-dark.pngnew file mode 100644index 00000000..0c36f748Binary files /dev/null and b/docs/transaction-calendar/calendar-all-accounts-dark.png differdiff --git a/docs/transaction-calendar/calendar-single-account-light.png b/docs/transaction-calendar/calendar-single-account-light.pngnew file mode 100644index 00000000..d612cc58Binary files /dev/null and b/docs/transaction-calendar/calendar-single-account-light.png differdiff --git a/frontend/src/components/category-icon.tsx b/frontend/src/components/category-icon.tsxindex 07dd65da..ebeb08b3 100644--- a/frontend/src/components/category-icon.tsx+++ b/frontend/src/components/category-icon.tsx@@ -3,6 +3,7 @@ import { CircleHelp } from 'lucide-react'import { cn } from '@/lib/utils'const SIZES = {+ xs: { box: 'w-4 h-4 rounded', icon: 10 },sm: { box: 'w-6 h-6 rounded-md', icon: 14 },md: { box: 'w-8 h-8 rounded-lg', icon: 16 },lg: { box: 'w-10 h-10 rounded-xl', icon: 20 },diff --git a/frontend/src/components/transaction-calendar-view.tsx b/frontend/src/components/transaction-calendar-view.tsxnew file mode 100644index 00000000..07d7ea96--- /dev/null+++ b/frontend/src/components/transaction-calendar-view.tsx@@ -0,0 +1,733 @@+import { useEffect, useMemo, useState } from 'react'+import type { ReactNode } from 'react'+import { useTranslation } from 'react-i18next'+import { ArrowLeftRight, CalendarDays, CircleDot } from 'lucide-react'+import type { TransactionCalendarDay, TransactionCalendarItem, TransactionCalendarResponse } from '@/types'+import { Skeleton } from '@/components/ui/skeleton'+import { CategoryIcon } from '@/components/category-icon'+import { cn } from '@/lib/utils'++function parseLocalDate(value: string) {+ return new Date(`${value}T00:00:00`)+}++function formatCurrency(value: number, currency = 'USD', locale = 'en-US') {+ return new Intl.NumberFormat(locale, { style: 'currency', currency }).format(value)+}++function compactCurrency(value: number, currency = 'USD', locale = 'en-US') {+ return new Intl.NumberFormat(locale, {+ style: 'currency',+ currency,+ notation: 'compact',+ maximumFractionDigits: 1,+ }).format(value)+}++function signedAmount(item: TransactionCalendarItem) {+ return item.type === 'credit' ? Math.abs(item.amount) : -Math.abs(item.amount)+}++function displayDayNumber(date: string) {+ return parseLocalDate(date).getDate()+}++function todayIso() {+ return new Date().toISOString().split('T')[0]+}++// A busy day can hold dozens of rows, and only three fit. Showing the biggest movers+// makes those three worth reading; showing an arbitrary three did not.+function itemSize(item: TransactionCalendarItem) {+ return Math.abs(item.amount_primary ?? item.amount)+}++function topItemsBySize(items: TransactionCalendarItem[], limit: number) {+ return [...items].sort((a, b) => itemSize(b) - itemSize(a)).slice(0, limit)+}++type CalendarMarkerTone = 'income' | 'expense' | 'transfer' | 'projected'+type CalendarDensity = 'compact' | 'detailed'+const CALENDAR_DENSITY_STORAGE_KEY = 'securo.transactionCalendar.density'++function readCalendarDensity(): CalendarDensity {+ if (typeof window === 'undefined') return 'compact'+ return window.localStorage.getItem(CALENDAR_DENSITY_STORAGE_KEY) === 'detailed' ? 'detailed' : 'compact'+}++export function TransactionCalendarView({+ calendar,+ isLoading,+ locale,+ dateLocale,+ mask,+ selectedDate,+ onSelectedDateChange,+ onOpenTransaction,+}: {+ calendar?: TransactionCalendarResponse+ isLoading: boolean+ locale: string+ dateLocale: string+ mask: (value: string) => string+ selectedDate: string+ onSelectedDateChange: (date: string) => void+ onOpenTransaction: (id: string) => void+}) {+ const [density, setDensity] = useState<CalendarDensity>(readCalendarDensity)++ useEffect(() => {+ window.localStorage.setItem(CALENDAR_DENSITY_STORAGE_KEY, density)+ }, [density])++ useEffect(() => {+ if (!calendar?.days.length) return+ if (selectedDate && calendar.days.some((day) => day.date === selectedDate)) return+ const today = todayIso()+ const inCalendarToday = calendar.days.find((day) => day.date === today)+ const firstInMonth = calendar.days.find((day) => day.in_month)+ onSelectedDateChange((inCalendarToday ?? firstInMonth ?? calendar.days[0]).date)+ }, [calendar, onSelectedDateChange, selectedDate])++ const selectedDay = calendar?.days.find((day) => day.date === selectedDate)+ const weekDays = useMemo(+ () => Array.from({ length: 7 }, (_, index) => {+ const date = new Date(Date.UTC(2024, 0, 7 + index)) // Sunday-start reference week+ return date.toLocaleDateString(dateLocale, { weekday: 'short' })+ }),+ [dateLocale],+ )++ if (isLoading) {+ return (+ <div className="bg-card rounded-xl border border-border shadow-sm overflow-hidden mb-4">+ <div className="p-4 border-b border-border flex items-center justify-between">+ <Skeleton className="h-6 w-44" />+ <Skeleton className="h-8 w-32" />+ </div>+ <div className="grid grid-cols-7">+ {Array.from({ length: 35 }).map((_, index) => (+ <div key={index} className="min-h-32 border-r border-b border-border p-3">+ <Skeleton className="h-4 w-8 mb-4" />+ <Skeleton className="h-4 w-24" />+ </div>+ ))}+ </div>+ </div>+ )+ }++ if (!calendar) return null++ return (+ <div className="mb-4 flex flex-col gap-4 md:flex-row md:items-start">+ <section className="min-w-0 flex-1 bg-card rounded-xl border border-border shadow-sm overflow-hidden">+ <div className="flex flex-wrap items-center justify-between gap-3 px-4 py-3 border-b border-border sm:px-5">+ <CalendarLegend />+ <CalendarDensityToggle value={density} onChange={setDensity} />+ </div>++ <BalanceTrend+ days={calendar.days.filter((day) => day.in_month)}+ currency={calendar.currency}+ locale={locale}+ mask={mask}+ selectedDate={selectedDate}+ onSelectDate={onSelectedDateChange}+ />++ <div className="hidden md:grid grid-cols-7 border-b border-border bg-muted/30">+ {weekDays.map((day) => (+ <div key={day} className="px-3 py-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground">+ {day}+ </div>+ ))}+ </div>++ <div className="hidden md:grid grid-cols-7">+ {calendar.days.map((day) => (+ <DayCell+ key={day.date}+ day={day}+ selected={day.date === selectedDate}+ today={day.date === todayIso()}+ currency={calendar.currency}+ locale={locale}+ mask={mask}+ density={density}+ onSelect={() => onSelectedDateChange(day.date)}+ />+ ))}+ </div>++ <div className="md:hidden divide-y divide-border">+ {calendar.days.filter((day) => day.in_month).map((day) => (+ <MobileDayRow+ key={day.date}+ day={day}+ selected={day.date === selectedDate}+ currency={calendar.currency}+ locale={locale}+ dateLocale={dateLocale}+ mask={mask}+ density={density}+ onSelect={() => onSelectedDateChange(day.date)}+ />+ ))}+ </div>+ </section>++ <SelectedDayPanel+ day={selectedDay}+ currency={calendar.currency}+ locale={locale}+ dateLocale={dateLocale}+ mask={mask}+ onOpenTransaction={onOpenTransaction}+ />+ </div>+ )+}++// The grid tells you what happened on a day. It cannot show the shape of the month,+// which is the actual question: when does the balance fall, and does it cross zero.+// Reading 31 separate numbers to answer that is the thing this strip removes.+function BalanceTrend({+ days,+ currency,+ locale,+ mask,+ selectedDate,+ onSelectDate,+}: {+ days: TransactionCalendarDay[]+ currency: string+ locale: string+ mask: (value: string) => string+ selectedDate: string+ onSelectDate: (date: string) => void+}) {+ const { t } = useTranslation()+ const W = 1000+ const H = 120++ const geometry = useMemo(() => {+ if (days.length < 2) return null+ const values = days.map((day) => day.ending_balance)+ const rawMin = Math.min(...values, 0)+ const rawMax = Math.max(...values, 0)+ const pad = (rawMax - rawMin) * 0.12 || Math.abs(rawMax || 1) * 0.12+ const min = rawMin - pad+ const max = rawMax + pad+ const span = max - min || 1+ const x = (i: number) => (i / (days.length - 1)) * W+ const y = (v: number) => H - ((v - min) / span) * H+ const points = days.map((day, i) => ({ x: x(i), y: y(day.ending_balance), day }))+ const line = points.map((p, i) => `${i === 0 ? 'M' : 'L'}${p.x.toFixed(2)},${p.y.toFixed(2)}`).join(' ')+ const zeroY = y(0)+ // Close the area on the zero line rather than the bottom edge. Clipped above zero it+ // paints the surplus green; clipped below it paints only the actual shortfall red.+ const area = `${line} L${W},${zeroY.toFixed(2)} L0,${zeroY.toFixed(2)} Z`+ return { points, line, area, zeroY }+ }, [days])++ if (!geometry) return null+ const { points, line, area, zeroY } = geometry+ const selectedPoint = points.find((p) => p.day.date === selectedDate)++ return (+ <div className="hidden border-b border-border px-4 pb-3 pt-2 sm:px-5 md:block">+ <p className="mb-1 text-[11px] font-semibold uppercase tracking-wide text-muted-foreground">+ {t('transactions.calendarBalanceTrend')}+ </p>+ <svg+ viewBox={`0 0 ${W} ${H}`}+ preserveAspectRatio="none"+ className="h-16 w-full overflow-visible"+ role="img"+ aria-label={t('transactions.calendarBalanceTrend')}+ >+ <defs>+ <linearGradient id="cal-trend-fill" x1="0" y1="0" x2="0" y2="1">+ <stop offset="0%" stopColor="rgb(16 185 129)" stopOpacity="0.28" />+ <stop offset="100%" stopColor="rgb(16 185 129)" stopOpacity="0.02" />+ </linearGradient>+ <clipPath id="cal-trend-positive">+ <rect x="0" y="0" width={W} height={Math.max(0, zeroY)} />+ </clipPath>+ {/* Only the stretch that actually dips under zero reads red. */}+ <clipPath id="cal-trend-negative">+ <rect x="0" y={zeroY} width={W} height={Math.max(0, H - zeroY)} />+ </clipPath>+ </defs>++ <path d={area} fill="url(#cal-trend-fill)" clipPath="url(#cal-trend-positive)" />+ <path d={area} fill="rgb(244 63 94)" fillOpacity="0.25" clipPath="url(#cal-trend-negative)" />++ <line+ x1="0"+ x2={W}+ y1={zeroY}+ y2={zeroY}+ stroke="currentColor"+ strokeWidth="1"+ strokeDasharray="4 4"+ vectorEffect="non-scaling-stroke"+ className="text-rose-400/70"+ />+ <path+ d={line}+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinejoin="round"+ strokeLinecap="round"+ vectorEffect="non-scaling-stroke"+ className="text-emerald-600 dark:text-emerald-400"+ />++ {selectedPoint && (+ <>+ <line+ x1={selectedPoint.x}+ x2={selectedPoint.x}+ y1="0"+ y2={H}+ stroke="currentColor"+ strokeWidth="1"+ vectorEffect="non-scaling-stroke"+ className="text-primary/40"+ />+ <circle+ cx={selectedPoint.x}+ cy={selectedPoint.y}+ r="4"+ vectorEffect="non-scaling-stroke"+ className="fill-background stroke-primary"+ strokeWidth="2"+ />+ </>+ )}++ {/* Invisible hit targets: the strip doubles as a way to pick a day. */}+ {points.map((p, i) => (+ <rect+ key={p.day.date}+ x={i === 0 ? 0 : p.x - W / (points.length - 1) / 2}+ y="0"+ width={W / (points.length - 1)}+ height={H}+ fill="transparent"+ className="cursor-pointer"+ onClick={() => onSelectDate(p.day.date)}+ >+ <title>{`${displayDayNumber(p.day.date)} · ${mask(formatCurrency(p.day.ending_balance, currency, locale))}`}</title>+ </rect>+ ))}+ </svg>+ </div>+ )+}++function CalendarLegend() {+ const { t } = useTranslation()+ return (+ <div className="flex flex-wrap items-center gap-2 text-[11px] text-muted-foreground">+ <span className="font-semibold uppercase tracking-wide">{t('transactions.calendarLegend')}</span>+ <LegendItem tone="income" label={t('transactions.summaryIncome')} />+ <LegendItem tone="expense" label={t('transactions.summaryExpenses')} />+ <LegendItem tone="transfer" label={t('transactions.transfer')}>+ <ArrowLeftRight size={9} />+ </LegendItem>+ <LegendItem tone="projected" label={t('transactions.calendarProjected')}>+ <CalendarDays size={9} />+ </LegendItem>+ </div>+ )+}++function CalendarDensityToggle({ value, onChange }: { value: CalendarDensity; onChange: (value: CalendarDensity) => void }) {+ const { t } = useTranslation()+ const options: Array<{ value: CalendarDensity; label: string }> = [+ { value: 'compact', label: t('transactions.calendarCompact') },+ { value: 'detailed', label: t('transactions.calendarDetailed') },+ ]+ return (+ <div className="inline-flex items-center gap-1 rounded-lg border border-border bg-muted/30 p-0.5 text-xs" aria-label={t('transactions.calendarDensity')}>+ {options.map((option) => (+ <button+ key={option.value}+ type="button"+ onClick={() => onChange(option.value)}+ className={cn(+ 'rounded-md px-2.5 py-1 font-semibold text-muted-foreground transition-colors hover:text-foreground focus:outline-none focus:ring-2 focus:ring-primary/40',+ value === option.value && 'bg-card text-foreground shadow-sm dark:bg-background',+ )}+ aria-pressed={value === option.value}+ >+ {option.label}+ </button>+ ))}+ </div>+ )+}++function LegendItem({ tone, label, children }: { tone: CalendarMarkerTone; label: string; children?: ReactNode }) {+ return (+ <span className="inline-flex items-center gap-1 whitespace-nowrap">+ <BadgeDot tone={tone} label={label}>{children}</BadgeDot>+ <span>{label}</span>+ </span>+ )+}++function DayCell({+ day,+ selected,+ today,+ currency,+ locale,+ mask,+ density,+ onSelect,+}: {+ day: TransactionCalendarDay+ selected: boolean+ today: boolean+ currency: string+ locale: string+ mask: (value: string) => string+ density: CalendarDensity+ onSelect: () => void+}) {+ const { t } = useTranslation()+ const isLowBalance = day.ending_balance < 0+ const detailed = density === 'detailed'+ const previewItems = detailed ? topItemsBySize(day.items, 3) : []+ const moreCount = detailed ? Math.max(0, day.items.length - previewItems.length) : 0+ return (+ <div+ role="button"+ tabIndex={0}+ onClick={onSelect}+ onKeyDown={(event) => {+ if (event.key === 'Enter' || event.key === ' ') {+ event.preventDefault()+ onSelect()+ }+ }}+ className={cn(+ 'border-r border-b border-border p-3 text-left transition-colors hover:bg-muted/30 focus:outline-none focus:ring-2 focus:ring-primary/40',+ detailed ? 'min-h-44' : 'min-h-24',+ !day.in_month && 'bg-muted/20 text-muted-foreground',+ day.in_month && isLowBalance && 'bg-rose-50/60 dark:bg-rose-950/20',+ // Selection is a ring, not a fill, on low-balance days: tinting the cell+ // would hide the negative-balance warning exactly when the user opens it.+ selected && 'z-10 ring-2 ring-primary/70',+ selected && !isLowBalance && 'bg-primary/5 dark:bg-primary/10',+ )}+ >+ <div className="flex items-center justify-between gap-1">+ <span className={cn(+ 'inline-flex size-6 shrink-0 items-center justify-center rounded-full text-sm font-bold tabular-nums',+ today && 'bg-primary text-primary-foreground',+ !today && day.in_month && 'text-foreground',+ !today && !day.in_month && 'text-muted-foreground',+ )}>+ {displayDayNumber(day.date)}+ </span>+ {/* Shown in both densities. The rows below only list the top few items, so on a+ busy day the badges are the only thing reporting the income, transfer or+ projection buried in the "+N more". */}+ <CalendarBadges day={day} />+ </div>++ {/* The balance is plain text on an ordinary day. Almost every day repeats+ yesterday's number, so making all of them loud buries the days that matter.+ Negative days keep the pill; the day it first turns negative is called out+ in words above the grid rather than with an icon nobody can decode. */}+ <div className="mt-3 flex items-center gap-1">+ <p+ title={mask(formatCurrency(day.ending_balance, currency, locale))}+ className={cn(+ 'whitespace-nowrap text-sm tabular-nums',+ isLowBalance+ ? 'rounded-full border border-rose-300 bg-rose-100 px-1.5 py-0.5 font-bold text-rose-700 dark:border-rose-500/50 dark:bg-rose-500/15 dark:text-rose-300'+ : 'font-semibold text-muted-foreground',+ )}+ >+ {mask(compactCurrency(day.ending_balance, currency, locale))}+ </p>+ </div>++ {detailed && previewItems.length > 0 && (+ <div className="mt-3 space-y-1.5 pr-1">+ {previewItems.map((item) => (+ <DayPreviewRow+ key={`${item.kind}-${item.id ?? item.recurring_id}-${item.date}`}+ item={item}+ locale={locale}+ mask={mask}+ />+ ))}+ {moreCount > 0 && (+ <p className="truncate text-[11px] font-semibold text-muted-foreground">+ {t('transactions.calendarMoreItems', { count: moreCount })}+ </p>+ )}+ </div>+ )}+ </div>+ )+}++// The row is only ~70px wide, which truncated descriptions to two or three characters.+// That carried no meaning and starved the amount, so the row now shows the category icon+// and the amount only. The description stays available on hover and in the selected-day+// panel. Projected items get a dashed border to read as not yet settled.+function DayPreviewRow({ item, locale, mask }: { item: TransactionCalendarItem; locale: string; mask: (value: string) => string }) {+ const amount = signedAmount(item)+ const label = [item.description, item.category_name].filter(Boolean).join(' · ')+ return (+ <div+ title={label}+ className={cn(+ 'flex items-center gap-1.5 rounded-md px-1.5 py-1 text-[11px] shadow-sm',+ item.kind === 'projected'+ ? 'border border-dashed border-violet-400/70 bg-violet-500/5 dark:border-violet-400/50'+ : 'bg-background/45 dark:bg-background/25',+ )}+ >+ <CategoryIcon icon={item.category_icon ?? undefined} color={item.category_color ?? undefined} size="xs" />+ <span className={cn('min-w-0 flex-1 truncate text-right font-bold tabular-nums', amount >= 0 ? 'text-emerald-600 dark:text-emerald-400' : 'text-rose-600 dark:text-rose-400')}>+ {mask(`${amount >= 0 ? '+' : '−'}${compactCurrency(Math.abs(item.amount), item.currency, locale)}`)}+ </span>+ </div>+ )+}++// Markers stay on one line beside the day number. A cell header is ~100px wide and the+// date takes 28px, so the four badges are sized to fit the remainder rather than wrap+// onto a second row, which used to push the balance chip down.+function CalendarBadges({ day }: { day: TransactionCalendarDay }) {+ const { t } = useTranslation()+ return (+ <div className="flex shrink-0 items-center gap-0.5">+ {day.has_income && <BadgeDot tone="income" label={t('transactions.summaryIncome')} />}+ {day.has_expense && <BadgeDot tone="expense" label={t('transactions.summaryExpenses')} />}+ {day.has_transfer && (+ <BadgeDot tone="transfer" label={t('transactions.transfer')}>+ <ArrowLeftRight size={9} />+ </BadgeDot>+ )}+ {day.projected_count > 0 && (+ <BadgeDot tone="projected" label={t('transactions.calendarProjected')}>+ <CalendarDays size={9} />+ </BadgeDot>+ )}+ </div>+ )+}++function BadgeDot({+ tone,+ label,+ children,+}: {+ tone: CalendarMarkerTone+ label: string+ children?: ReactNode+}) {+ return (+ <span+ title={label}+ aria-label={label}+ className={cn(+ 'inline-flex size-3.5 shrink-0 items-center justify-center rounded border bg-background/80 shadow-sm',+ tone === 'income' && 'border-emerald-500/40 text-emerald-600 dark:text-emerald-400',+ tone === 'expense' && 'border-rose-500/40 text-rose-600 dark:text-rose-400',+ tone === 'transfer' && 'border-sky-500/40 text-sky-600 dark:text-sky-400',+ tone === 'projected' && 'border-violet-500/40 text-violet-600 dark:text-violet-300',+ )}+ >+ {children ?? <CircleDot size={9} />}+ </span>+ )+}++function MobileDayRow({+ day,+ selected,+ currency,+ locale,+ dateLocale,+ mask,+ density,+ onSelect,+}: {+ day: TransactionCalendarDay+ selected: boolean+ currency: string+ locale: string+ dateLocale: string+ mask: (value: string) => string+ density: CalendarDensity+ onSelect: () => void+}) {+ const { t } = useTranslation()+ const isLowBalance = day.ending_balance < 0+ const previewItems = density === 'detailed' ? day.items.slice(0, 3) : []+ const moreCount = density === 'detailed' ? Math.max(0, day.items.length - previewItems.length) : 0+ return (+ <button+ type="button"+ onClick={onSelect}+ className={cn(+ 'w-full px-4 py-3 text-left transition-colors hover:bg-muted/30',+ isLowBalance && 'bg-rose-50/75 dark:bg-rose-950/25',+ selected && 'bg-primary/5 dark:bg-primary/10',+ )}+ >+ <div className="flex items-center justify-between gap-3">+ <div>+ <p className="text-sm font-semibold text-foreground">+ {parseLocalDate(day.date).toLocaleDateString(dateLocale, { weekday: 'short', day: 'numeric', month: 'short' })}+ </p>+ <p className="text-xs text-muted-foreground">+ {t('transactions.calendarItemCount', { count: day.actual_count + day.projected_count })}+ </p>+ </div>+ <div className="text-right">+ <p className={cn('text-sm font-bold tabular-nums', day.ending_balance < 0 ? 'text-rose-600 dark:text-rose-400' : 'text-emerald-600 dark:text-emerald-400')}>+ {mask(formatCurrency(day.ending_balance, currency, locale))}+ </p>+ <CalendarBadges day={day} />+ </div>+ </div>+ {previewItems.length > 0 && (+ <div className="mt-2 space-y-1.5">+ {previewItems.map((item) => (+ <DayPreviewRow+ key={`${item.kind}-${item.id ?? item.recurring_id}-${item.date}`}+ item={item}+ locale={locale}+ mask={mask}+ />+ ))}+ {moreCount > 0 && (+ <p className="truncate text-[11px] font-semibold text-muted-foreground">+ {t('transactions.calendarMoreItems', { count: moreCount })}+ </p>+ )}+ </div>+ )}+ </button>+ )+}++function SelectedDayPanel({+ day,+ currency,+ locale,+ dateLocale,+ mask,+ onOpenTransaction,+}: {+ day?: TransactionCalendarDay+ currency: string+ locale: string+ dateLocale: string+ mask: (value: string) => string+ onOpenTransaction: (id: string) => void+}) {+ const { t } = useTranslation()+ if (!day) return null+ return (+ <aside className="bg-card rounded-xl border border-border shadow-sm overflow-hidden md:sticky md:top-4 md:max-h-[calc(100vh-7rem)] md:w-[320px] md:shrink-0 md:self-start md:flex md:flex-col lg:w-[340px]">+ <div className="px-4 py-4 border-b border-border">+ <div className="flex items-end justify-between gap-3">+ <div className="min-w-0">+ <p className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">{t('transactions.calendarSelectedDay')}</p>+ <h3 className="truncate text-lg font-bold text-foreground">+ {parseLocalDate(day.date).toLocaleDateString(dateLocale, { weekday: 'long', day: 'numeric', month: 'long' })}+ </h3>+ </div>+ <p+ title={mask(formatCurrency(day.ending_balance, currency, locale))}+ className={cn(+ 'shrink-0 text-right text-lg font-bold tabular-nums',+ day.ending_balance < 0 ? 'text-rose-600 dark:text-rose-400' : 'text-emerald-600 dark:text-emerald-400',+ )}+ >+ {mask(formatCurrency(day.ending_balance, currency, locale))}+ </p>+ </div>+ </div>++ <div className="min-h-0 divide-y divide-border overflow-y-auto md:flex-1">+ {day.items.length === 0 ? (+ <p className="px-4 py-8 text-sm text-muted-foreground text-center">{t('transactions.calendarNoItems')}</p>+ ) : (+ day.items.map((item) => (+ <CalendarItemRow+ key={`${item.kind}-${item.id ?? item.recurring_id}-${item.date}`}+ item={item}+ locale={locale}+ mask={mask}+ onOpenTransaction={onOpenTransaction}+ />+ ))+ )}+ </div>+ </aside>+ )+}++function CalendarItemRow({+ item,+ locale,+ mask,+ onOpenTransaction,+}: {+ item: TransactionCalendarItem+ locale: string+ mask: (value: string) => string+ onOpenTransaction: (id: string) => void+}) {+ const { t } = useTranslation()+ const amount = signedAmount(item)+ const interactive = item.kind === 'actual' && !!item.id+ return (+ <button+ type="button"+ disabled={!interactive}+ onClick={() => { if (item.id) onOpenTransaction(item.id) }}+ className={cn(+ 'w-full px-4 py-3 text-left flex items-center gap-3',+ interactive ? 'hover:bg-muted/50 transition-colors' : 'cursor-default',+ )}+ >+ <CategoryIcon icon={item.category_icon ?? undefined} color={item.category_color ?? undefined} size="md" />+ <div className="min-w-0 flex-1">+ <div className="flex items-center gap-2 min-w-0">+ <p className="text-sm font-semibold text-foreground truncate">{item.description}</p>+ {item.kind === 'projected' && (+ <span className="shrink-0 rounded-full border border-violet-500/20 bg-violet-500/10 px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-violet-700 dark:text-violet-300">+ {t('transactions.calendarProjected')}+ </span>+ )}+ {item.is_transfer && (+ <span className="shrink-0 text-sky-600 dark:text-sky-400"><ArrowLeftRight size={13} /></span>+ )}+ </div>+ <p className="text-xs text-muted-foreground truncate">+ {item.account_name ?? t('transactions.account')}+ {item.category_name ? ` · ${item.category_name}` : ''}+ </p>+ </div>+ <p className={cn('text-sm font-bold tabular-nums', amount >= 0 ? 'text-emerald-600 dark:text-emerald-400' : 'text-rose-600 dark:text-rose-400')}>+ {mask(`${amount >= 0 ? '+' : '−'}${formatCurrency(Math.abs(item.amount), item.currency, locale)}`)}+ </p>+ </button>+ )+}diff --git a/frontend/src/components/transactions-filter-bar.tsx b/frontend/src/components/transactions-filter-bar.tsxindex faa2e14c..68e7f263 100644--- a/frontend/src/components/transactions-filter-bar.tsx+++ b/frontend/src/components/transactions-filter-bar.tsx@@ -54,6 +54,7 @@ interface TransactionsFilterBarProps {onSearchSubmit?: (value: string) => voidfilterAccountIds: string[]onAccountIdsChange: (value: string[]) => void+ accountSelectionMode?: 'multiple' | 'single'filterCategoryIds: string[]onCategoryIdsChange: (value: string[]) => voidfilterUncategorized: boolean@@ -88,6 +89,7 @@ export function TransactionsFilterBar({onSearchSubmit,filterAccountIds,onAccountIdsChange,+ accountSelectionMode = 'multiple',filterCategoryIds,onCategoryIdsChange,filterUncategorized,@@ -432,7 +434,7 @@ export function TransactionsFilterBar({{t('transactions.filtersBar.filterBy')}</DropdownMenuLabel><DropdownMenuGroup>- {/* Account submenu (multi) */}+ {/* Account submenu: calendar mode is all-or-one; list mode stays multi-select. */}<DropdownMenuSubopen={accountSubOpen}onOpenChange={handleAccountSubOpenChange}@@ -451,10 +453,55 @@ export function TransactionsFilterBar({sideOffset={8}className="max-h-[320px] w-[240px] overflow-y-auto p-1">+ {accountSelectionMode === 'single' && (+ <>+ <DropdownMenuItem+ onSelect={() => {+ onAccountIdsChange([])+ }}+ className={cn(+ 'gap-2 rounded-sm px-2 py-1.5 text-[13px]',+ filterAccountIds.length === 0 && 'bg-primary/5',+ )}+ >+ <span className="min-w-0 flex-1 truncate text-left">+ {t('transactions.all')}+ </span>+ {filterAccountIds.length === 0 && <Check size={13} className="text-primary" />}+ </DropdownMenuItem>+ <div className="my-1 h-px bg-border/60" />+ </>+ )}{accounts.length === 0 ? (<div className="px-2 py-3 text-center text-[12px] text-muted-foreground">{t('transactions.filtersBar.noOptions')}</div>+ ) : accountSelectionMode === 'single' ? (+ accounts.map((a) => {+ const checked = filterAccountIds[0] === a.id+ return (+ <DropdownMenuItem+ key={a.id}+ onSelect={() => {+ onAccountIdsChange(checked ? [] : [a.id])+ }}+ className={cn(+ 'gap-2 rounded-sm px-2 py-1.5 text-[13px]',+ checked && 'bg-primary/5',+ )}+ >+ <span className="min-w-0 flex-1 truncate text-left">+ {getAccountName(a)}+ </span>+ {a.currency && (+ <span className="text-[10.5px] uppercase tracking-wide text-muted-foreground/70">+ {a.currency}+ </span>+ )}+ {checked && <Check size={13} className="text-primary" />}+ </DropdownMenuItem>+ )+ })) : (accounts.map((a) => (<DropdownMenuCheckboxItem@@ -480,7 +527,7 @@ export function TransactionsFilterBar({</DropdownMenuCheckboxItem>)))}- {filterAccountIds.length > 0 && (+ {accountSelectionMode === 'multiple' && filterAccountIds.length > 0 && (<><div className="my-1 h-px bg-border/60" /><DropdownMenuItemdiff --git a/frontend/src/components/transactions-page-actions.tsx b/frontend/src/components/transactions-page-actions.tsxindex 6419e14d..84ef30fe 100644--- a/frontend/src/components/transactions-page-actions.tsx+++ b/frontend/src/components/transactions-page-actions.tsx@@ -20,6 +20,7 @@ type MonthStepperConfig = {export type TransactionsPageActionsProps = {month: MonthStepperConfig+ viewToggle?: ReactNodecolumnPicker: ReactNodeexportLabel: stringexporting: boolean@@ -42,6 +43,7 @@ function DesktopSecondaryActions(props: TransactionsPageActionsProps) {const { t } = useTranslation()return (<div className="hidden sm:contents">+ {props.viewToggle}{props.columnPicker}<Button variant="outline" disabled={props.exporting} onClick={props.onExport}><Download size={16} className="mr-1.5" />{props.exportLabel}diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex afbbf186..257fcb71 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -20,6 +20,7 @@ import type {PayeeSummary,RecurringTransaction,ProjectedTransaction,+ TransactionCalendarResponse,Budget,BudgetVsActual,Rule,@@ -452,6 +453,17 @@ export const transactions = {})return data},+ calendar: async (params?: {+ month?: string+ account_id?: string+ account_ids?: string[]+ }): Promise<TransactionCalendarResponse> => {+ const { data } = await api.get('/transactions/calendar', {+ params,+ paramsSerializer: { indexes: null },+ })+ return data+ },get: async (id: string): Promise<Transaction> => {const { data } = await api.get(`/transactions/${id}`)return datadiff --git a/frontend/src/locales/de.json b/frontend/src/locales/de.jsonindex 5349d504..d2e83da7 100644--- a/frontend/src/locales/de.json+++ b/frontend/src/locales/de.json@@ -489,7 +489,28 @@"last90": "Letzte 90 Tage","thisYear": "Dieses Jahr"}- }+ },+ "listView": "Liste",+ "calendarView": "Kalender",+ "calendar": "Kalender",+ "calendarOneAccount": "1 Konto",+ "calendarAccountCount": "{{count}} Konten",+ "calendarAllAccounts": "Alle Konten",+ "calendarEndBalance": "Endsaldo",+ "calendarItemCount": "{{count}} Eintrag",+ "calendarItemCount_plural": "{{count}} Einträge",+ "calendarProjectedCount": "{{count}} geplant",+ "calendarProjected": "Geplant",+ "calendarBalanceTrend": "Saldoverlauf",+ "calendarLegend": "Legende",+ "calendarDensity": "Ansicht",+ "calendarCompact": "Kompakt",+ "calendarDetailed": "Detailliert",+ "calendarMoreItems": "+{{count}} weitere",+ "calendarAddIncome": "Einnahme hinzufügen",+ "calendarAddExpense": "Ausgabe hinzufügen",+ "calendarSelectedDay": "Ausgewählter Tag",+ "calendarNoItems": "Keine Transaktionen an diesem Tag"},"accounts": {"title": "Konten",diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex e69757e7..abab65c6 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -489,7 +489,28 @@"last90": "Last 90 days","thisYear": "This year"}- }+ },+ "listView": "List",+ "calendarView": "Calendar",+ "calendar": "Calendar",+ "calendarOneAccount": "1 account",+ "calendarAccountCount": "{{count}} accounts",+ "calendarAllAccounts": "All accounts",+ "calendarEndBalance": "End balance",+ "calendarItemCount": "{{count}} item",+ "calendarItemCount_plural": "{{count}} items",+ "calendarProjectedCount": "{{count}} projected",+ "calendarProjected": "Projected",+ "calendarBalanceTrend": "Balance trend",+ "calendarLegend": "Legend",+ "calendarDensity": "View",+ "calendarCompact": "Compact",+ "calendarDetailed": "Detailed",+ "calendarMoreItems": "+{{count}} more",+ "calendarAddIncome": "Add income",+ "calendarAddExpense": "Add expense",+ "calendarSelectedDay": "Selected day",+ "calendarNoItems": "No transactions on this day"},"accounts": {"title": "Accounts",diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.jsonindex 40d6aa61..bd79cf44 100644--- a/frontend/src/locales/es.json+++ b/frontend/src/locales/es.json@@ -489,7 +489,28 @@"bulkAddTags": "Añadir etiquetas","bulkRemoveTags": "Eliminar etiquetas","addTagsPlaceholder": "#etiqueta…",- "clearOverride": "Borrar anulación"+ "clearOverride": "Borrar anulación",+ "listView": "Lista",+ "calendarView": "Calendario",+ "calendar": "Calendario",+ "calendarOneAccount": "1 cuenta",+ "calendarAccountCount": "{{count}} cuentas",+ "calendarAllAccounts": "Todas las cuentas",+ "calendarEndBalance": "Saldo final",+ "calendarItemCount": "{{count}} elemento",+ "calendarItemCount_plural": "{{count}} elementos",+ "calendarProjectedCount": "{{count}} previsto",+ "calendarProjected": "Previsto",+ "calendarBalanceTrend": "Tendencia del saldo",+ "calendarLegend": "Leyenda",+ "calendarDensity": "Vista",+ "calendarCompact": "Compacta",+ "calendarDetailed": "Detallada",+ "calendarMoreItems": "+{{count}} más",+ "calendarAddIncome": "Añadir ingreso",+ "calendarAddExpense": "Añadir gasto",+ "calendarSelectedDay": "Día seleccionado",+ "calendarNoItems": "No hay transacciones en este día"},"accounts": {"title": "Cuentas",diff --git a/frontend/src/locales/fr.json b/frontend/src/locales/fr.jsonindex 9653c4db..b5c0c2a0 100644--- a/frontend/src/locales/fr.json+++ b/frontend/src/locales/fr.json@@ -489,7 +489,28 @@"last90": "90 derniers jours","thisYear": "Cette année"}- }+ },+ "listView": "Liste",+ "calendarView": "Calendrier",+ "calendar": "Calendrier",+ "calendarOneAccount": "1 compte",+ "calendarAccountCount": "{{count}} comptes",+ "calendarAllAccounts": "Tous les comptes",+ "calendarEndBalance": "Solde final",+ "calendarItemCount": "{{count}} élément",+ "calendarItemCount_plural": "{{count}} éléments",+ "calendarProjectedCount": "{{count}} prévu(s)",+ "calendarProjected": "Prévu",+ "calendarBalanceTrend": "Évolution du solde",+ "calendarLegend": "Légende",+ "calendarDensity": "Affichage",+ "calendarCompact": "Compact",+ "calendarDetailed": "Détaillé",+ "calendarMoreItems": "+{{count}} de plus",+ "calendarAddIncome": "Ajouter un revenu",+ "calendarAddExpense": "Ajouter une dépense",+ "calendarSelectedDay": "Jour sélectionné",+ "calendarNoItems": "Aucune transaction ce jour-là"},"accounts": {"title": "Comptes",diff --git a/frontend/src/locales/it.json b/frontend/src/locales/it.jsonindex f51f0e34..5758aeea 100644--- a/frontend/src/locales/it.json+++ b/frontend/src/locales/it.json@@ -489,7 +489,28 @@"bulkAddTags": "Aggiungi tag","bulkRemoveTags": "Rimuovi tag","addTagsPlaceholder": "#tag…",- "clearOverride": "Rimuovi override"+ "clearOverride": "Rimuovi override",+ "listView": "Lista",+ "calendarView": "Calendario",+ "calendar": "Calendario",+ "calendarOneAccount": "1 conto",+ "calendarAccountCount": "{{count}} conti",+ "calendarAllAccounts": "Tutti i conti",+ "calendarEndBalance": "Saldo finale",+ "calendarItemCount": "{{count}} elemento",+ "calendarItemCount_plural": "{{count}} elementi",+ "calendarProjectedCount": "{{count}} previsto",+ "calendarProjected": "Previsto",+ "calendarBalanceTrend": "Andamento del saldo",+ "calendarLegend": "Legenda",+ "calendarDensity": "Vista",+ "calendarCompact": "Compatta",+ "calendarDetailed": "Dettagliata",+ "calendarMoreItems": "+{{count}} altri",+ "calendarAddIncome": "Aggiungi entrata",+ "calendarAddExpense": "Aggiungi spesa",+ "calendarSelectedDay": "Giorno selezionato",+ "calendarNoItems": "Nessuna transazione in questo giorno"},"accounts": {"title": "Conti",diff --git a/frontend/src/locales/pl.json b/frontend/src/locales/pl.jsonindex 5f918ccd..63b462ff 100644--- a/frontend/src/locales/pl.json+++ b/frontend/src/locales/pl.json@@ -516,7 +516,28 @@"bulkAddTags": "Dodaj tagi","bulkRemoveTags": "Usuń tagi","addTagsPlaceholder": "#tag…",- "clearOverride": "Wyczyść nadpisanie"+ "clearOverride": "Wyczyść nadpisanie",+ "listView": "Lista",+ "calendarView": "Kalendarz",+ "calendar": "Kalendarz",+ "calendarOneAccount": "1 konto",+ "calendarAccountCount": "{{count}} konta",+ "calendarAllAccounts": "Wszystkie konta",+ "calendarEndBalance": "Saldo końcowe",+ "calendarItemCount": "{{count}} pozycja",+ "calendarItemCount_plural": "{{count}} pozycje",+ "calendarProjectedCount": "{{count}} planowane",+ "calendarProjected": "Planowane",+ "calendarBalanceTrend": "Trend salda",+ "calendarLegend": "Legenda",+ "calendarDensity": "Widok",+ "calendarCompact": "Kompaktowy",+ "calendarDetailed": "Szczegółowy",+ "calendarMoreItems": "+{{count}} więcej",+ "calendarAddIncome": "Dodaj przychód",+ "calendarAddExpense": "Dodaj wydatek",+ "calendarSelectedDay": "Wybrany dzień",+ "calendarNoItems": "Brak transakcji w tym dniu"},"accounts": {"title": "Konta",diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex 41ce8e26..3c6ef925 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -489,7 +489,28 @@"bulkAddTags": "Adicionar tags","bulkRemoveTags": "Remover tags","addTagsPlaceholder": "#tag…",- "clearOverride": "Limpar substituição"+ "clearOverride": "Limpar substituição",+ "listView": "Lista",+ "calendarView": "Calendário",+ "calendar": "Calendário",+ "calendarOneAccount": "1 conta",+ "calendarAccountCount": "{{count}} contas",+ "calendarAllAccounts": "Todas as contas",+ "calendarEndBalance": "Saldo final",+ "calendarItemCount": "{{count}} item",+ "calendarItemCount_plural": "{{count}} itens",+ "calendarProjectedCount": "{{count}} previsto(s)",+ "calendarProjected": "Previsto",+ "calendarBalanceTrend": "Tendência do saldo",+ "calendarLegend": "Legenda",+ "calendarDensity": "Visualização",+ "calendarCompact": "Compacto",+ "calendarDetailed": "Detalhado",+ "calendarMoreItems": "+{{count}} mais",+ "calendarAddIncome": "Adicionar receita",+ "calendarAddExpense": "Adicionar despesa",+ "calendarSelectedDay": "Dia selecionado",+ "calendarNoItems": "Nenhuma transação neste dia"},"accounts": {"title": "Contas",diff --git a/frontend/src/locales/pt-PT.json b/frontend/src/locales/pt-PT.jsonindex ceac8a90..53676b2e 100644--- a/frontend/src/locales/pt-PT.json+++ b/frontend/src/locales/pt-PT.json@@ -486,6 +486,27 @@"thisYear": "Este ano"}},+ "listView": "Lista",+ "calendarView": "Calendário",+ "calendar": "Calendário",+ "calendarOneAccount": "1 conta",+ "calendarAccountCount": "{{count}} contas",+ "calendarAllAccounts": "Todas as contas",+ "calendarEndBalance": "Saldo final",+ "calendarItemCount": "{{count}} item",+ "calendarItemCount_plural": "{{count}} itens",+ "calendarProjectedCount": "{{count}} previsto(s)",+ "calendarProjected": "Previsto",+ "calendarBalanceTrend": "Tendência do saldo",+ "calendarLegend": "Legenda",+ "calendarDensity": "Visualização",+ "calendarCompact": "Compacto",+ "calendarDetailed": "Detalhado",+ "calendarMoreItems": "+{{count}} mais",+ "calendarAddIncome": "Adicionar receita",+ "calendarAddExpense": "Adicionar despesa",+ "calendarSelectedDay": "Dia selecionado",+ "calendarNoItems": "Nenhuma transação neste dia","bulkAddTags": "Adicionar tags","bulkRemoveTags": "Remover tags","addTagsPlaceholder": "#tag…",diff --git a/frontend/src/locales/ru.json b/frontend/src/locales/ru.jsonindex 60934834..0fc9a36a 100644--- a/frontend/src/locales/ru.json+++ b/frontend/src/locales/ru.json@@ -489,7 +489,28 @@"last90": "Последние 90 дней","thisYear": "Этот год"}- }+ },+ "listView": "Список",+ "calendarView": "Календарь",+ "calendar": "Календарь",+ "calendarOneAccount": "1 счет",+ "calendarAccountCount": "{{count}} счетов",+ "calendarAllAccounts": "Все счета",+ "calendarEndBalance": "Итоговый баланс",+ "calendarItemCount": "{{count}} запись",+ "calendarItemCount_plural": "{{count}} записей",+ "calendarProjectedCount": "{{count}} запланировано",+ "calendarProjected": "Запланировано",+ "calendarBalanceTrend": "Динамика баланса",+ "calendarLegend": "Легенда",+ "calendarDensity": "Вид",+ "calendarCompact": "Компактно",+ "calendarDetailed": "Подробно",+ "calendarMoreItems": "ещё +{{count}}",+ "calendarAddIncome": "Добавить доход",+ "calendarAddExpense": "Добавить расход",+ "calendarSelectedDay": "Выбранный день",+ "calendarNoItems": "В этот день транзакций нет"},"accounts": {"title": "Счета",diff --git a/frontend/src/locales/uk.json b/frontend/src/locales/uk.jsonindex fa62235b..7508d930 100644--- a/frontend/src/locales/uk.json+++ b/frontend/src/locales/uk.json@@ -489,7 +489,28 @@"last90": "Останні 90 днів","thisYear": "Цей рік"}- }+ },+ "listView": "Список",+ "calendarView": "Календар",+ "calendar": "Календар",+ "calendarOneAccount": "1 рахунок",+ "calendarAccountCount": "{{count}} рахунків",+ "calendarAllAccounts": "Усі рахунки",+ "calendarEndBalance": "Кінцевий баланс",+ "calendarItemCount": "{{count}} запис",+ "calendarItemCount_plural": "{{count}} записи",+ "calendarProjectedCount": "{{count}} заплановано",+ "calendarProjected": "Заплановано",+ "calendarBalanceTrend": "Динаміка балансу",+ "calendarLegend": "Легенда",+ "calendarDensity": "Вигляд",+ "calendarCompact": "Компактно",+ "calendarDetailed": "Детально",+ "calendarMoreItems": "ще +{{count}}",+ "calendarAddIncome": "Додати дохід",+ "calendarAddExpense": "Додати витрату",+ "calendarSelectedDay": "Вибраний день",+ "calendarNoItems": "Немає транзакцій у цей день"},"accounts": {"title": "Рахунки",diff --git a/frontend/src/pages/transactions.tsx b/frontend/src/pages/transactions.tsxindex adff571e..40a0232d 100644--- a/frontend/src/pages/transactions.tsx+++ b/frontend/src/pages/transactions.tsx@@ -34,7 +34,7 @@ import {TableRow,} from '@/components/ui/table'import { Skeleton } from '@/components/ui/skeleton'-import { AlertTriangle, ArrowLeftRight, ArrowUp, ArrowDown, Check, HelpCircle, Info, Paperclip, Users, X, EyeClosed, SlidersHorizontal } from 'lucide-react'+import { AlertTriangle, ArrowLeftRight, ArrowUp, ArrowDown, CalendarDays, Check, HelpCircle, Info, List, Paperclip, Users, X, EyeClosed, SlidersHorizontal } from 'lucide-react'import type { Transaction, Rule } from '@/types'import { RuleDialog, type RuleDialogInitialData } from '@/components/rule-dialog'import { PageHeader } from '@/components/page-header'@@ -50,6 +50,7 @@ import { TransferDialog } from '@/components/transfer-dialog'import { LinkTransferDialog } from '@/components/link-transfer-dialog'import { BulkAddToGroupDialog, type BulkAddToGroupSubmission } from '@/components/bulk-add-to-group-dialog'import { TransactionsFilterBar } from '@/components/transactions-filter-bar'+import { TransactionCalendarView } from '@/components/transaction-calendar-view'import { usePrivacyMode } from '@/hooks/use-privacy-mode'import { useAuth } from '@/contexts/auth-context'import { useWorkspace } from '@/contexts/workspace-context'@@ -95,7 +96,10 @@ export default function TransactionsPage() {return 20}})- const [filterAccountIds, setFilterAccountIds] = useState<string[]>([])+ const [filterAccountIds, setFilterAccountIds] = useState<string[]>(() => {+ const initial = searchParams.get('account_id')+ return initial ? initial.split(',') : []+ })const [filterCategoryIds, setFilterCategoryIds] = useState<string[]>(() => {const initial = searchParams.get('category_id')return initial ? [initial] : []@@ -131,6 +135,10 @@ export default function TransactionsPage() {useState<PendingTransferCategoryUpdate | null>(null)const [formResetKey, setFormResetKey] = useState(0)const [duplicateDraft, setDuplicateDraft] = useState<Partial<Transaction> | null>(null)+ const [viewMode, setViewMode] = useState<'list' | 'calendar'>(() => (+ searchParams.get('view') === 'calendar' ? 'calendar' : 'list'+ ))+ const [calendarSelectedDate, setCalendarSelectedDate] = useState<string>(() => searchParams.get('day') ?? '')const [filterPayee, setFilterPayee] = useState<string>(searchParams.get('payee_id') ?? '')const [filterGroupId, setFilterGroupId] = useState<string>(searchParams.get('group_id') ?? '')const [filterType, setFilterType] = useState<string>(searchParams.get('type') ?? '')@@ -202,6 +210,8 @@ export default function TransactionsPage() {prevSearchRef.current = searchconst nextQ = searchParams.get('q') ?? ''+ setViewMode(searchParams.get('view') === 'calendar' ? 'calendar' : 'list')+ setCalendarSelectedDate(searchParams.get('day') ?? '')setSearchInput(nextQ)setSearchQuery(nextQ)const tags = searchParams.get('tags');@@ -237,6 +247,8 @@ export default function TransactionsPage() {const params = new URLSearchParams([['q', searchQuery],+ ['view', viewMode === 'calendar' ? 'calendar' : ''],+ ['day', viewMode === 'calendar' ? calendarSelectedDate : ''],['tags', tagFilters.join(',')],['payee_id', filterPayee],['group_id', filterGroupId],@@ -258,6 +270,8 @@ export default function TransactionsPage() {);}, [searchQuery,+ viewMode,+ calendarSelectedDate,tagFilters,filterPayee,filterGroupId,@@ -287,6 +301,15 @@ export default function TransactionsPage() {setBulkCategory('')}, [page, filterAccountIds, filterCategoryIds, filterUncategorized, filterPayee, filterType, filterFrom, filterTo, filterMinAmount, filterMaxAmount, searchQuery])+ useEffect(() => {+ if (viewMode === 'calendar') {+ setFilterAccountIds((prev) => prev.length > 1 ? [] : prev)+ setSelectedIds(new Set())+ setLastSelectedId(null)+ setBulkCategory('')+ }+ }, [viewMode, filterAccountIds.length])+// Reset bulk category when selection changes so the same category can be re-applieduseEffect(() => {setBulkCategory('')@@ -348,6 +371,17 @@ export default function TransactionsPage() {}),})+ const calendarMonth = steppedMonth+ const calendarAccountIds = filterAccountIds.length === 1 ? filterAccountIds : []+ const { data: calendarData, isLoading: calendarLoading } = useQuery({+ queryKey: ['transactions', 'calendar', calendarMonth, calendarAccountIds],+ enabled: viewMode === 'calendar',+ queryFn: () => transactions.calendar({+ month: `${calendarMonth}-01`,+ account_ids: calendarAccountIds.length === 1 ? calendarAccountIds : undefined,+ }),+ })+// Publish the active filters + result count to the global chat panel.// The agent uses this so "what about THIS list?" / "soma essas" /// "categorize these" resolve against the filtered view, not the user's@@ -789,6 +823,17 @@ export default function TransactionsPage() {setDialogOpen(true)}+ const handleOpenCalendarTransaction = async (id: string) => {+ try {+ const tx = await transactions.get(id)+ setEditingTx(tx)+ setDuplicateDraft(null)+ setDialogOpen(true)+ } catch {+ toast.error(t('common.error'))+ }+ }+const handleExport = async () => {setExporting(true)try {@@ -1155,7 +1200,32 @@ export default function TransactionsPage() {prevLabel: t('transactions.monthPrevious'),nextLabel: t('transactions.monthNext'),}}- columnPicker={<TransactionsColumnPicker state={grid} />}+ viewToggle={+ <div className="inline-flex rounded-lg border border-border bg-card p-0.5">+ <Button+ variant={viewMode === 'list' ? 'secondary' : 'ghost'}+ size="sm"+ className="h-8 gap-1.5 px-2.5"+ onClick={() => setViewMode('list')}+ >+ <List size={14} />+ {t('transactions.listView')}+ </Button>+ <Button+ variant={viewMode === 'calendar' ? 'secondary' : 'ghost'}+ size="sm"+ className="h-8 gap-1.5 px-2.5"+ onClick={() => {+ if (filterAccountIds.length > 1) setFilterAccountIds([])+ setViewMode('calendar')+ }}+ >+ <CalendarDays size={14} />+ {t('transactions.calendarView')}+ </Button>+ </div>+ }+ columnPicker={viewMode === 'list' ? <TransactionsColumnPicker state={grid} /> : null}exportLabel={exportLabel}exporting={exporting}onExport={handleExport}@@ -1184,7 +1254,8 @@ export default function TransactionsPage() {setSearchQuery(text)}}filterAccountIds={filterAccountIds}- onAccountIdsChange={(v) => { setFilterAccountIds(v); setPage(1) }}+ onAccountIdsChange={(v) => { setFilterAccountIds(viewMode === 'calendar' ? v.slice(0, 1) : v); setPage(1) }}+ accountSelectionMode={viewMode === 'calendar' ? 'single' : 'multiple'}filterCategoryIds={filterCategoryIds}onCategoryIdsChange={(v) => { setFilterCategoryIds(v); setPage(1) }}filterUncategorized={filterUncategorized}@@ -1263,7 +1334,21 @@ export default function TransactionsPage() {</div>)}+ {viewMode === 'calendar' && (+ <TransactionCalendarView+ calendar={calendarData}+ isLoading={calendarLoading}+ locale={locale}+ dateLocale={dateLocale}+ mask={mask}+ selectedDate={calendarSelectedDate}+ onSelectedDateChange={setCalendarSelectedDate}+ onOpenTransaction={handleOpenCalendarTransaction}+ />+ )}+{/* Table */}+ {viewMode === 'list' && (<div className="bg-card rounded-xl border border-border shadow-sm overflow-hidden mb-4">{isLoading ? (<div className="p-6 space-y-3">@@ -1382,9 +1467,10 @@ export default function TransactionsPage() {</div>)}</div>+ )}{/* Pagination */}- {data && data.total > 10 && (+ {viewMode === 'list' && data && data.total > 10 && (<div className={`flex flex-col sm:flex-row items-center justify-between gap-4 py-4 ${selectedIds.size > 0 ? 'pb-20' : ''}`}><div className="hidden sm:block w-32" />{totalPages > 1 ? (@@ -1441,14 +1527,12 @@ export default function TransactionsPage() {</div></div>)}-{/* Bulk Action Bar — aligned with the main content area: clears thefixed sidebar on lg+ and matches the page's max-w-7xl + p-6 wrapperso the bar visually sits over the transactions list, not thefull viewport. */}- <div- className={`fixed bottom-0 left-0 right-0 lg:left-60 z-50 transition-transform duration-200 ease-out ${selectedIds.size > 0 ? 'translate-y-0' : 'translate-y-full'}`}- >+ {viewMode === 'list' && selectedIds.size > 0 && (+ <div className="fixed bottom-0 left-0 right-0 lg:left-60 z-50"><div className="mx-auto max-w-7xl px-3 md:px-6 pb-4 md:pb-6"><div className="flex items-stretch gap-1.5 bg-card border border-border shadow-xl rounded-2xl p-2"><MobileBulkSelectionActions@@ -1640,6 +1724,7 @@ export default function TransactionsPage() {</div></div></div>+ )}{/* Bulk Add-to-Group Dialog */}<BulkAddToGroupDialogdiff --git a/frontend/src/types/index.ts b/frontend/src/types/index.tsindex 2726548b..cb8521fa 100644--- a/frontend/src/types/index.ts+++ b/frontend/src/types/index.ts@@ -455,6 +455,51 @@ export interface ProjectedTransaction {category_color: string | null}+export interface TransactionCalendarItem {+ kind: 'actual' | 'projected'+ id: string | null+ recurring_id: string | null+ date: string+ description: string+ amount: number+ amount_primary: number | null+ currency: string+ type: 'debit' | 'credit'+ account_id: string | null+ account_name: string | null+ category_id: string | null+ category_name: string | null+ category_icon: string | null+ category_color: string | null+ status: string | null+ source: string | null+ transfer_pair_id: string | null+ is_transfer: boolean+ is_ignored: boolean+}++export interface TransactionCalendarDay {+ date: string+ in_month: boolean+ ending_balance: number+ income: number+ expense: number+ transfer_net: number+ actual_count: number+ projected_count: number+ has_income: boolean+ has_expense: boolean+ has_transfer: boolean+ items: TransactionCalendarItem[]+}++export interface TransactionCalendarResponse {+ month: string+ currency: string+ account_ids: string[] | null+ days: TransactionCalendarDay[]+}+export interface DashboardSummary {total_balance: Record<string, number>total_balance_primary: number