Open-source personal finance manager. Self-hosted, privacy-first.
feat: configure application timezone in admin settings (#909)
Fredson Barreto481c1a2ac456
diff --git a/backend/app/agents/services/context_service.py b/backend/app/agents/services/context_service.pyindex e5ca08db..0a3f2ceb 100644--- a/backend/app/agents/services/context_service.py+++ b/backend/app/agents/services/context_service.py@@ -10,12 +10,12 @@ Goals:from __future__ import annotationsimport uuid-from datetime import datetime, timezonefrom decimal import Decimalfrom typing import Optionalfrom sqlalchemy.ext.asyncio import AsyncSession+from app.core.app_clock import app_timezone, app_todayfrom app.models.user import User@@ -56,9 +56,8 @@ async def build_context_primer(prefs = getattr(user, "preferences", None) or {}primary_currency = prefs.get("currency_display") or "USD"language = prefs.get("language") or "en"- timezone_label = prefs.get("timezone") or "UTC"-- today_utc = datetime.now(timezone.utc).date().isoformat()+ timezone_label = str(app_timezone())+ today = app_today().isoformat()lines: list[str] = []lines.append("# Context for this conversation")@@ -68,7 +67,7 @@ async def build_context_primer(lines.append(f"- Primary currency: {primary_currency}")lines.append(f"- Preferred language: {language}")lines.append(f"- Timezone: {timezone_label}")- lines.append(f"- Today is {today_utc} (UTC)")+ lines.append(f"- Today is {today} ({timezone_label})")lines.append("")rows: list[dict] = []diff --git a/backend/app/api/admin.py b/backend/app/api/admin.pyindex 09f076f3..a1301980 100644--- a/backend/app/api/admin.py+++ b/backend/app/api/admin.py@@ -1,5 +1,6 @@import uuidimport re+from zoneinfo import ZoneInfo, ZoneInfoNotFoundError, available_timezonesfrom fastapi import APIRouter, Depends, HTTPException, Query, Request, statusfrom sqlalchemy.ext.asyncio import AsyncSession@@ -7,6 +8,7 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom app.core.auth import UserManager, current_active_user, current_superuser, get_user_managerfrom app.core.auth_policy import require_local_auth_enabledfrom app.core.database import get_async_session+from app.core.app_clock import app_timezonefrom app.models.user import Userfrom app.schemas.admin import (AdminUserCreate,@@ -15,6 +17,7 @@ from app.schemas.admin import (AdminUserUpdate,AppSettingRead,AppSettingUpdate,+ TimezoneSettingRead,)from app.services import admin_service@@ -28,6 +31,7 @@ ALLOWED_SETTINGS = {"theme_color_dark","number_format","date_format",+ "timezone",}@@ -133,6 +137,11 @@ async def update_setting(status_code=status.HTTP_400_BAD_REQUEST,detail=f"Setting '{key}' is not configurable",)+ if key == "timezone":+ try:+ ZoneInfo(data.value)+ except (ZoneInfoNotFoundError, ValueError):+ raise HTTPException(status_code=400, detail="Invalid IANA timezone")SETTING_VALIDATORS = {"registration_enabled": {"true", "false"},"credit_card_accounting_mode": {"cash", "accrual"},@@ -158,6 +167,17 @@ async def update_setting(return AppSettingRead.model_validate(setting)[email protected]("/timezone", response_model=TimezoneSettingRead)+async def timezone_setting(+ _session: AsyncSession = Depends(get_async_session),+ _user: User = Depends(current_superuser),+):+ return TimezoneSettingRead(+ timezone=str(app_timezone()),+ available=sorted(available_timezones()),+ )++@router.get("/registration-status")async def registration_status(session: AsyncSession = Depends(get_async_session),diff --git a/backend/app/api/export.py b/backend/app/api/export.pyindex 4ffee63c..53a3341a 100644--- a/backend/app/api/export.py+++ b/backend/app/api/export.py@@ -7,6 +7,7 @@ from fastapi.responses import StreamingResponsefrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession+from app.core.app_clock import app_todayfrom app.core.database import get_async_sessionfrom app.core.workspace_context import WorkspaceContext, current_workspacefrom app.models.account import Account@@ -91,7 +92,7 @@ async def _collect(ctx: WorkspaceContext, session: AsyncSession) -> dict[str, obdef _as_download(archive: bytes) -> StreamingResponse:- today = date.today().isoformat()+ today = app_today().isoformat()return StreamingResponse(iter([archive]),media_type="application/zip",diff --git a/backend/app/api/fx_rates.py b/backend/app/api/fx_rates.pyindex 8173c5dc..9bf1fdc2 100644--- a/backend/app/api/fx_rates.py+++ b/backend/app/api/fx_rates.py@@ -1,9 +1,8 @@-from datetime import date-from fastapi import APIRouter, Dependsfrom sqlalchemy import select, funcfrom sqlalchemy.ext.asyncio import AsyncSession+from app.core.app_clock import app_todayfrom app.core.auth import current_active_userfrom app.core.config import get_settingsfrom app.core.database import get_async_session@@ -20,8 +19,9 @@ async def refresh_rates(user: User = Depends(current_active_user),):"""Trigger immediate FX rate sync."""- count = await sync_rates(session, date.today())- return {"synced": True, "rates_count": count, "date": date.today().isoformat()}+ today = app_today()+ count = await sync_rates(session, today)+ return {"synced": True, "rates_count": count, "date": today.isoformat()}@router.get("/status")diff --git a/backend/app/api/transactions.py b/backend/app/api/transactions.pyindex 0530506c..4a209d25 100644--- a/backend/app/api/transactions.py+++ b/backend/app/api/transactions.py@@ -9,6 +9,7 @@ from fastapi.responses import StreamingResponsefrom pydantic import BaseModelfrom sqlalchemy.ext.asyncio import AsyncSession+from app.core.app_clock import app_todayfrom app.core.database import get_async_sessionfrom app.core.workspace_context import (WorkspaceContext,@@ -250,7 +251,7 @@ async def export_transactions(])output.seek(0)- today = date.today().isoformat()+ today = app_today().isoformat()return StreamingResponse(iter([output.getvalue()]),media_type="text/csv",diff --git a/backend/app/cli.py b/backend/app/cli.pyindex 652bd933..0d845f3d 100644--- a/backend/app/cli.py+++ b/backend/app/cli.py@@ -11,10 +11,11 @@ from app.models.user import Userasync def generate_recurring() -> None:"""Generate pending recurring transactions for all users."""+ from app.core.app_clock import use_timezonefrom app.models.user import User as UserModelfrom app.services import recurring_transaction_service- async with async_session_maker() as session:+ async with async_session_maker() as session, use_timezone(session):result = await session.execute(select(UserModel))users = result.scalars().all()total = 0diff --git a/backend/app/core/app_clock.py b/backend/app/core/app_clock.pynew file mode 100644index 00000000..d051fd4b--- /dev/null+++ b/backend/app/core/app_clock.py@@ -0,0 +1,71 @@+"""Application calendar dates; persisted timestamps continue to use UTC."""++import logging+from contextlib import asynccontextmanager, contextmanager+from contextvars import ContextVar+from datetime import date, datetime+from os import getenv+from zoneinfo import ZoneInfo, ZoneInfoNotFoundError++import tzlocal+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++logger = logging.getLogger(__name__)+_timezone: ContextVar[ZoneInfo | None] = ContextVar("app_timezone", default=None)+++def environment_timezone() -> ZoneInfo:+ """Resolve the deployment timezone, falling back safely to UTC."""+ name = getenv("TZ")+ if name:+ try:+ return ZoneInfo(name)+ except (ZoneInfoNotFoundError, ValueError):+ logger.warning("TZ environment value is unavailable; using system timezone")++ try:+ return tzlocal.get_localzone()+ except (OSError, ZoneInfoNotFoundError, ValueError):+ logger.warning("System timezone is unavailable; using UTC")+ return ZoneInfo("UTC")+++async def get_timezone(session: AsyncSession) -> ZoneInfo:+ """Resolve the saved application timezone without caching database state."""+ from app.models.app_settings import AppSetting++ name = await session.scalar(select(AppSetting.value).where(AppSetting.key == "timezone"))+ if name:+ try:+ return ZoneInfo(name)+ except (ZoneInfoNotFoundError, ValueError):+ logger.warning("Saved application timezone is unavailable; using environment timezone")+ return environment_timezone()+++def app_timezone() -> ZoneInfo:+ """Return the timezone captured for this operation, or the process fallback."""+ return _timezone.get() or environment_timezone()+++def app_today() -> date:+ """Return today's calendar date in the application timezone."""+ return datetime.now(app_timezone()).date()+++@contextmanager+def use_resolved_timezone(timezone: ZoneInfo):+ """Carry an already resolved timezone across one operation."""+ token = _timezone.set(timezone)+ try:+ yield+ finally:+ _timezone.reset(token)+++@asynccontextmanager+async def use_timezone(session: AsyncSession):+ """Resolve and snapshot the timezone for one database-backed operation."""+ with use_resolved_timezone(await get_timezone(session)):+ yielddiff --git a/backend/app/core/database.py b/backend/app/core/database.pyindex 2ff468af..cdb96478 100644--- a/backend/app/core/database.py+++ b/backend/app/core/database.py@@ -16,5 +16,8 @@ class Base(DeclarativeBase):async def get_async_session() -> AsyncIterator[AsyncSession]:+ from app.core.app_clock import use_timezone+async with async_session_maker() as session:- yield session+ async with use_timezone(session):+ yield sessiondiff --git a/backend/app/main.py b/backend/app/main.pyindex 3b27dc90..e0666ee4 100644--- a/backend/app/main.py+++ b/backend/app/main.py@@ -69,6 +69,7 @@ async def _warm_tesouro_cache() -> None:returnfrom sqlalchemy import select+ from app.core.app_clock import get_timezone, use_resolved_timezonefrom app.core.database import async_session_makerfrom app.models.workspace import Workspace@@ -76,13 +77,15 @@ async def _warm_tesouro_cache() -> None:has_brl = await session.scalar(select(Workspace.id).where(Workspace.default_currency == "BRL").limit(1))- if not has_brl:- return+ if not has_brl:+ return+ operation_timezone = await get_timezone(session)from app.providers.tesouro_direto import get_tesouro_direto_provider- await get_tesouro_direto_provider().get_available_bonds()- logger.info("Startup: warmed Tesouro Direto price cache")+ with use_resolved_timezone(operation_timezone):+ await get_tesouro_direto_provider().get_available_bonds()+ logger.info("Startup: warmed Tesouro Direto price cache")except Exception:logger.exception("Startup: Tesouro Direto cache warm failed")diff --git a/backend/app/providers/enable_banking.py b/backend/app/providers/enable_banking.pyindex 18267f44..4220aefe 100644--- a/backend/app/providers/enable_banking.py+++ b/backend/app/providers/enable_banking.py@@ -563,7 +563,11 @@ class EnableBankingProvider(BankProvider):payee_source: str = "auto",) -> list[TransactionData]:_ = self._session_id(credentials) # surface expired credentials early- today = date.today()+ # Enable Banking reads date_to as an inclusive UTC calendar day, so the+ # window ends on the UTC date regardless of the application calendar;+ # otherwise an application west of UTC would stop short of the day's+ # newest transactions until its own date caught up.+ today = datetime.now(timezone.utc).date()if since is not None:return await self._fetch_transactions(account_external_id, since, today, payee_sourcediff --git a/backend/app/providers/simplefin.py b/backend/app/providers/simplefin.pyindex 21e66002..2d59da6c 100644--- a/backend/app/providers/simplefin.py+++ b/backend/app/providers/simplefin.py@@ -462,7 +462,9 @@ class SimpleFinProvider(BankProvider):since: Optional[date] = None,payee_source: str = "auto",) -> list[TransactionData]:- end_date = date.today()+ # SimpleFIN request windows are epoch-based and use UTC boundaries,+ # independent of Securo's configurable application calendar.+ end_date = datetime.now(timezone.utc).date()if since is None:start_date = end_date - timedelta(days=SIMPLEFIN_INITIAL_HISTORY_DAYS)else:diff --git a/backend/app/providers/tesouro_direto.py b/backend/app/providers/tesouro_direto.pyindex adf65c4b..8e4d077c 100644--- a/backend/app/providers/tesouro_direto.py+++ b/backend/app/providers/tesouro_direto.py@@ -13,6 +13,8 @@ from decimal import Decimal, InvalidOperationfrom typing import Optionalimport requests+from app.core.app_clock import app_today+TESOURO_DIRETO_CSV_URL = ("https://www.tesourotransparente.gov.br/ckan/dataset/""df56aa42-484a-4a59-8184-7676580c81e3/resource/"@@ -125,7 +127,7 @@ class TesouroDiretoProvider:async def get_available_bonds(self) -> list[TesouroDiretoQuote]:# Only bonds still open for investment — the CSV also lists long-matured# series that nobody should be adding as a current holding.- today = date.today()+ today = app_today()bonds = [q for q in await self._latest_quotes() if q.maturity_date >= today]return sorted(bonds, key=lambda q: (q.title_type, q.maturity_date))diff --git a/backend/app/schemas/admin.py b/backend/app/schemas/admin.pyindex 5231bcba..965d09c6 100644--- a/backend/app/schemas/admin.py+++ b/backend/app/schemas/admin.py@@ -44,3 +44,8 @@ class AppSettingRead(BaseModel):class AppSettingUpdate(BaseModel):value: str+++class TimezoneSettingRead(BaseModel):+ timezone: str+ available: list[str]diff --git a/backend/app/services/_query_filters.py b/backend/app/services/_query_filters.pyindex 842d3025..707b38fb 100644--- a/backend/app/services/_query_filters.py+++ b/backend/app/services/_query_filters.py@@ -11,6 +11,7 @@ from typing import Optionalfrom sqlalchemy import and_, case, func, or_, selectfrom sqlalchemy.ext.asyncio import AsyncSession+from app.core.app_clock import app_todayfrom app.models.account import Accountfrom app.models.category import Categoryfrom app.models.transaction import Transaction@@ -312,7 +313,7 @@ async def owner_split_offset_pnl(Transaction.source != "opening_balance",date_col >= month_start,date_col < month_end,- date_col <= date.today(),+ date_col <= app_today(),Transaction.status == "posted",counts_as_user_pnl(),)@@ -392,7 +393,7 @@ async def owner_split_offset_by_category(Transaction.source != "opening_balance",date_col >= month_start,date_col < month_end,- date_col <= date.today(),+ date_col <= app_today(),Transaction.status == "posted",counts_as_user_pnl(),)@@ -476,7 +477,7 @@ async def viewer_shared_pnl(Transaction.source != "opening_balance",date_col >= month_start,date_col < month_end,- date_col <= date.today(),+ date_col <= app_today(),Transaction.status == "posted",counts_as_pnl(),)@@ -555,7 +556,7 @@ async def viewer_shared_spending_by_category(Transaction.source != "opening_balance",date_col >= month_start,date_col < month_end,- date_col <= date.today(),+ date_col <= app_today(),Transaction.status == "posted",counts_as_pnl(),)diff --git a/backend/app/services/account_service.py b/backend/app/services/account_service.pyindex c67ab560..ffad2149 100644--- a/backend/app/services/account_service.py+++ b/backend/app/services/account_service.py@@ -7,6 +7,7 @@ from sqlalchemy import case, delete, func, select, or_, updatefrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlalchemy.orm import contains_eager+from app.core.app_clock import app_todayfrom app.models.account import Accountfrom app.models.bank_connection import BankConnectionfrom app.models.credit_card_bill import CreditCardBill@@ -50,7 +51,7 @@ def _opening_balance_values(account_type: str, balance: Decimal) -> tuple[Decimaasync def get_accounts(session: AsyncSession, workspace_id: uuid.UUID, include_closed: bool = False) -> list[dict]:- today = _Date.today()+ today = app_today()# Subquery: compute current_balance per account from transactions in one pass# Use amount_primary only when tx currency differs from account currency# (converts foreign txs to account's reporting currency)@@ -286,7 +287,7 @@ async def create_account(description="Saldo inicial",amount=amount,currency=data.currency,- date=data.balance_date or _Date.today(),+ date=data.balance_date or app_today(),type=opening_type,source="opening_balance",)@@ -413,7 +414,7 @@ async def update_account(description="Saldo inicial",amount=amount,currency=account.currency,- date=balance_date or _Date.today(),+ date=balance_date or app_today(),type=opening_type,source="opening_balance",)@@ -475,7 +476,7 @@ async def sync_opening_balance_for_connected_account(# are projections and must not change the synthetic opening transaction;# otherwise a later-dated row can shift the opening balance even though it# is not part of the provider's current balance yet.- balance_cutoff = _Date.today()+ balance_cutoff = app_today()# For connected CC accounts the stored balance is positive debt and the UI# displays it negated (account_service.serialize_account). The sum of signed@@ -541,7 +542,7 @@ async def sync_opening_balance_for_connected_account())oldest_date = oldest_result.scalar()- opening_date = (oldest_date - timedelta(days=1)) if oldest_date else _Date.today()+ opening_date = (oldest_date - timedelta(days=1)) if oldest_date else app_today()# Sign convention matches the rest of the codebase: credit = +, debit = -# regardless of account type. A positive offset needs a credit to raise the@@ -677,7 +678,7 @@ async def get_account_summary(if not account:return None- today = _Date.today()+ today = app_today()if not date_from:date_from = today.replace(day=1)if not date_to:@@ -1013,7 +1014,7 @@ async def _account_balance_at(.outerjoin(Category, Transaction.category_id == Category.id).where(Transaction.account_id == account_id,- Transaction.date <= min(cutoff, _Date.today()),+ Transaction.date <= min(cutoff, app_today()),Transaction.status == "posted",Transaction.is_ignored == False,or_(@@ -1047,7 +1048,7 @@ async def _account_daily_balance_series(Transaction.account_id == account_id,Transaction.date >= date_from,Transaction.date <= date_to,- Transaction.date <= _Date.today(),+ Transaction.date <= app_today(),Transaction.status == "posted",Transaction.is_ignored == False,or_(@@ -1079,7 +1080,7 @@ async def get_account_balance_history(if not account:return None- today = _Date.today()+ today = app_today()if not date_from:date_from = today.replace(day=1)if not date_to:diff --git a/backend/app/services/asset_service.py b/backend/app/services/asset_service.pyindex 79e89ad7..575c16dc 100644--- a/backend/app/services/asset_service.py+++ b/backend/app/services/asset_service.py@@ -9,6 +9,7 @@ from sqlalchemy import select, func, descfrom sqlalchemy.exc import IntegrityErrorfrom sqlalchemy.ext.asyncio import AsyncSession+from app.core.app_clock import app_todayfrom app.models.asset import Assetfrom app.models.asset_transaction import AssetTransactionfrom app.models.asset_value import AssetValue@@ -79,7 +80,7 @@ def _generate_growth_values(When growth_start_date is set, growth iteration begins from that date — notfrom base_date — so the asset accrues no growth for the gap betweenpurchase and the configured growth start."""- today = date.today()+ today = app_today()if growth_start_date and today < growth_start_date:return []@@ -528,7 +529,7 @@ async def create_asset(asset_id=asset.id,amount=initial_amount,price=Decimal(str(quote.price)),- date=date.today(),+ date=app_today(),source="sync",))@@ -539,13 +540,13 @@ async def create_asset(value = AssetValue(asset_id=asset.id,amount=data.current_value,- date=date.today(),+ date=app_today(),source="manual",)session.add(value)elif data.valuation_method == "growth_rule" and data.purchase_price is not None:# Seed the initial value from purchase price- base_date = data.purchase_date or data.growth_start_date or date.today()+ base_date = data.purchase_date or data.growth_start_date or app_today()seed = AssetValue(asset_id=asset.id,amount=data.purchase_price,@@ -592,7 +593,7 @@ async def create_asset(quantity=Decimal(str(data.units)),price=buy_price,fee=Decimal("0"),- date=data.purchase_date or date.today(),+ date=data.purchase_date or app_today(),source="manual",))@@ -681,7 +682,7 @@ async def update_asset()# Regenerate from purchase_priceif asset.purchase_price and asset.growth_type and asset.growth_rate and asset.growth_frequency:- base_date = asset.purchase_date or asset.growth_start_date or date.today()+ base_date = asset.purchase_date or asset.growth_start_date or app_today()backfill = _generate_growth_values(asset_id=asset.id,base_amount=float(asset.purchase_price),@@ -1055,7 +1056,7 @@ async def _apply_price_to_asset(if not asset.units or asset.units <= 0:return- today = value_date or date.today()+ today = value_date or app_today()new_amount = new_price * Decimal(str(asset.units))existing = await session.execute(select(AssetValue)diff --git a/backend/app/services/budget_service.py b/backend/app/services/budget_service.pyindex ad556fad..c1360a1a 100644--- a/backend/app/services/budget_service.py+++ b/backend/app/services/budget_service.py@@ -6,6 +6,7 @@ from typing import Optionalfrom sqlalchemy import select, func, and_from sqlalchemy.ext.asyncio import AsyncSession+from app.core.app_clock import app_todayfrom app.models.budget import Budgetfrom app.models.category import Categoryfrom app.models.category_group import CategoryGroup@@ -229,7 +230,7 @@ async def get_budget_vs_actual(month: Optional[date] = None,) -> list[BudgetVsActual]:if not month:- month = date.today().replace(day=1)+ month = app_today().replace(day=1)month_start = month.replace(day=1)if month.month == 12:@@ -277,7 +278,7 @@ async def get_budget_vs_actual(report_date >= month_start,report_date < month_end,Transaction.category_id.isnot(None),- report_date <= date.today(),+ report_date <= app_today(),Transaction.status == "posted",counts_as_user_pnl(),)@@ -363,7 +364,7 @@ async def get_budget_vs_actual(report_date >= prev_month_start,report_date < prev_month_end,Transaction.category_id.isnot(None),- report_date <= date.today(),+ report_date <= app_today(),Transaction.status == "posted",counts_as_user_pnl(),)diff --git a/backend/app/services/connection_service.py b/backend/app/services/connection_service.pyindex efd0c6f4..a3e40963 100644--- a/backend/app/services/connection_service.py+++ b/backend/app/services/connection_service.py@@ -11,6 +11,7 @@ from sqlalchemy.exc import IntegrityErrorfrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlalchemy.orm import selectinload+from app.core.app_clock import app_todayfrom app.core.config import get_settingsfrom app.models.asset import Assetfrom app.models.asset_group import AssetGroup@@ -278,7 +279,7 @@ async def _sync_holdings(returnsource = connection.provider- today = date.today()+ today = app_today()# Find-or-create the wallet(s) that own this connection's holdings. A# holding carrying its owning account (SimpleFIN — issue #345) gets onediff --git a/backend/app/services/credit_card_service.py b/backend/app/services/credit_card_service.pyindex f965bbea..821d45ef 100644--- a/backend/app/services/credit_card_service.py+++ b/backend/app/services/credit_card_service.py@@ -3,6 +3,8 @@ from datetime import datefrom decimal import Decimalfrom typing import Optional+from app.core.app_clock import app_today+def _clamp_day(year: int, month: int, day: int) -> date:last_day = calendar.monthrange(year, month)[1]@@ -29,7 +31,7 @@ def get_cycle_dates(occurrence of payment_due_day, and the close is the most recent occurrence ofstatement_close_day on or before that due date. This guarantees close <= due."""if reference is None:- reference = date.today()+ reference = app_today()next_due = _next_day_occurrence(payment_due_day, reference) if payment_due_day else Nonediff --git a/backend/app/services/dashboard_service.py b/backend/app/services/dashboard_service.pyindex dcc6eb8f..f3538b76 100644--- a/backend/app/services/dashboard_service.py+++ b/backend/app/services/dashboard_service.py@@ -7,6 +7,7 @@ from sqlalchemy import select, func, case, or_from sqlalchemy.ext.asyncio import AsyncSessionfrom sqlalchemy.orm import selectinload+from app.core.app_clock import app_todayfrom app.core.config import get_settingsfrom app.models.account import Accountfrom app.models.bank_connection import BankConnection@@ -167,7 +168,7 @@ async def _get_forecast_transactions(if account_ids is not None and len(account_ids) == 0:return []- today = date.today()+ today = app_today()bucket_date = range_date_col if range_date_col is not None else Transaction.datestmt = (select(Transaction)@@ -218,10 +219,10 @@ async def get_summary(asset_group_ids: Optional[list[uuid.UUID]] = None,) -> DashboardSummary:if not month:- month = date.today().replace(day=1)+ month = app_today().replace(day=1)month_start, month_end = _month_range(month)- today = date.today()+ today = app_today()# Collection filter (issue #105): show the *raw* P&L/balances of the# collection's accounts, plus the assets in its wallets (asset_group_ids);@@ -718,10 +719,10 @@ async def get_spending_by_category(account_ids: Optional[list[uuid.UUID]] = None,) -> list[SpendingByCategory]:if not month:- month = date.today().replace(day=1)+ month = app_today().replace(day=1)month_start, month_end = _month_range(month)- today = date.today()+ today = app_today()filtered = account_ids is not Noneacct_filter = [Transaction.account_id.in_(account_ids)] if filtered else []@@ -935,7 +936,7 @@ async def get_monthly_trend() -> list[MonthlyTrend]:filtered = account_ids is not Noneacct_filter = [Transaction.account_id.in_(account_ids)] if filtered else []- today = date.today()+ today = app_today()accounting_mode = await get_credit_card_accounting_mode(session)report_date = reporting_date_col(accounting_mode)month_label = func.to_char(report_date, 'YYYY-MM').label('month')@@ -1075,7 +1076,7 @@ async def get_projected_transactions(range_start, range_end = from_date, to_date + timedelta(days=1)else:if not month:- month = date.today().replace(day=1)+ month = app_today().replace(day=1)range_start, range_end = _month_range(month)# Get user's primary currency for live conversion@@ -1266,7 +1267,7 @@ async def _account_balance_at(current cutoff: their provider balance is returned verbatim so it keepsmatching the bank app. Forecast callers add pending/future rows separately."""- today = date.today()+ today = app_today()balance_cutoff = min(cutoff, today)if account.connection_id:# Start from the provider's authoritative current balance@@ -1350,7 +1351,7 @@ async def _total_balance_by_currency(if not accounts:return {}- today = date.today()+ today = app_today()balance_cutoff = min(cutoff, today)connected = [account for account in accounts if account.connection_id]manual = [account for account in accounts if not account.connection_id]@@ -1513,7 +1514,7 @@ async def _daily_balance_deltas_by_date(Account.is_closed == False,Transaction.date >= start,Transaction.date < end,- Transaction.date <= date.today(),+ Transaction.date <= app_today(),Transaction.is_ignored == False,*status_filter,or_(@@ -1567,13 +1568,13 @@ async def get_balance_history(account_ids: Optional[list[uuid.UUID]] = None,) -> BalanceHistory:if not month:- month = date.today().replace(day=1)+ month = app_today().replace(day=1)month_start, month_end = _month_range(month)prev_month_start = (month_start - timedelta(days=1)).replace(day=1)prev_month_end = month_start- today = date.today()+ today = app_today()is_current = month_start.year == today.year and month_start.month == today.monthdays_in_month = (month_end - month_start).dayscutoff_day = today.day if is_current else days_in_monthdiff --git a/backend/app/services/fx_rate_service.py b/backend/app/services/fx_rate_service.pyindex 758b59fb..3aa9d975 100644--- a/backend/app/services/fx_rate_service.py+++ b/backend/app/services/fx_rate_service.py@@ -8,6 +8,7 @@ from sqlalchemy import select, descfrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlalchemy.dialects.postgresql import insert as pg_insert+from app.core.app_clock import app_todayfrom app.core.config import get_settingsfrom app.models.fx_rate import FxRatefrom app.models.user import User@@ -27,14 +28,14 @@ async def sync_rates(Idempotent — existing rates for the same date are updated.Returns the number of rates synced."""- requested_target = target_date or date.today()+ requested_target = target_date or app_today()# Providers cannot return a historical rate for a date that has not# happened yet. Treat a future request as a request for today's latest# published rate and store it under today's date.- target = min(requested_target, date.today())+ target = min(requested_target, app_today())supported = set(get_settings().supported_currencies.split(","))- if target == date.today():+ if target == app_today():rates = await _provider.fetch_latest()else:rates = await _provider.fetch_historical(target)@@ -82,11 +83,11 @@ async def _resolve_rate(if from_currency == to_currency:return Decimal("1")- requested_target = target_date or date.today()+ requested_target = target_date or app_today()# A future transaction must use the latest real rate, never query a# not-yet-existing historical snapshot. Looking up against today also# lets the closest-rate fallback select the last cached business day.- target = min(requested_target, date.today())+ target = min(requested_target, app_today())# Step 1: Try exact dateusd_to_source = await _get_exact_date_rate(session, from_currency, target)@@ -143,7 +144,7 @@ async def get_rate(if rate is None:logger.warning("No FX rate found for %s -> %s on %s, returning 1",- from_currency, to_currency, target_date or date.today(),+ from_currency, to_currency, target_date or app_today(),)return Decimal("1")return ratediff --git a/backend/app/services/goal_service.py b/backend/app/services/goal_service.pyindex a2870966..e1c7eb03 100644--- a/backend/app/services/goal_service.py+++ b/backend/app/services/goal_service.py@@ -6,6 +6,7 @@ from typing import Optionalfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession+from app.core.app_clock import app_todayfrom app.core.config import get_settingsfrom app.models.account import Accountfrom app.models.asset import Asset@@ -71,7 +72,7 @@ async def _resolve_current_amount(account = await session.get(Account, goal.account_id)if account:# Use dashboard's balance logic so manual accounts are computed correctly- bal = Decimal(str(await _account_balance_at(session, account, date.today())))+ bal = Decimal(str(await _account_balance_at(session, account, app_today())))return await _convert_amount(session, bal, account.currency, goal_currency)return goal.current_amountelif goal.tracking_type == "asset" and goal.asset_id:@@ -94,7 +95,7 @@ async def _resolve_current_amount(# Reuse dashboard's account query and balance logic so manual accounts# (whose balance is computed from transactions) are handled correctly.accounts = await _get_open_accounts(session, workspace_id)- today = date.today()+ today = app_today()total = Decimal("0")for acc in accounts:bal = Decimal(str(await _account_balance_at(session, acc, today)))@@ -147,7 +148,7 @@ def _compute_monthly_contribution() -> Optional[float]:if not target_date:return None- today = date.today()+ today = app_today()if today >= target_date:return 0.0remaining = target - current@@ -168,7 +169,7 @@ def _compute_on_track(return Noneif current >= target:return "achieved"- today = date.today()+ today = app_today()if today > target_date:return "overdue"diff --git a/backend/app/services/invoice_service.py b/backend/app/services/invoice_service.pyindex 2bcdb070..37d627a4 100644--- a/backend/app/services/invoice_service.py+++ b/backend/app/services/invoice_service.py@@ -23,6 +23,7 @@ from sqlalchemy.exc import IntegrityErrorfrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlalchemy.orm import selectinload+from app.core.app_clock import app_timezone, app_todayfrom app.fiscal.registry import TaxIdKind, normalise_and_validatefrom app.models.invoice import (MANUAL_METHOD,@@ -242,14 +243,14 @@ def derive_state(invoice: Invoice, today: Optional[_date] = None) -> DerivedStatif remaining <= ZERO:return "paid"- reference = today or datetime.now(timezone.utc).date()+ reference = today or app_today()if invoice.due_date and invoice.due_date < reference:return "overdue"return "partial" if allocated_total(invoice) > ZERO else "open"def days_overdue(invoice: Invoice, today: Optional[_date] = None) -> int:- reference = today or datetime.now(timezone.utc).date()+ reference = today or app_today()if derive_state(invoice, reference) != "overdue":return 0return (reference - invoice.due_date).days@@ -441,7 +442,7 @@ async def aging_summary(is not money anybody owes. Voided and uncollectible invoices areexcluded for the same reason, one decision later."""- reference = today or datetime.now(timezone.utc).date()+ reference = today or app_today()result = await session.execute(_base_query(direction).where(Invoice.workspace_id == workspace_id,@@ -484,9 +485,13 @@ async def aging_summary(# which is why both are stored.month_start = reference.replace(day=1)received_this_month = ZERO+ reporting_timezone = app_timezone()for invoice in invoices:for allocation in invoice.allocations:- allocated_on = allocation.allocated_at.date()+ allocated_at = allocation.allocated_at+ if allocated_at.tzinfo is None:+ allocated_at = allocated_at.replace(tzinfo=timezone.utc)+ allocated_on = allocated_at.astimezone(reporting_timezone).date()if month_start <= allocated_on <= reference:received_this_month += allocation.amount@@ -598,7 +603,7 @@ async def create_invoice("An imported document must say where it came from",)- issue_date = data.get("issue_date") or datetime.now(timezone.utc).date()+ issue_date = data.get("issue_date") or app_today()due_date = data.get("due_date")if due_date is None:due_date = issue_date + timedelta(days=settings.default_payment_terms_days)diff --git a/backend/app/services/reconciliation_service.py b/backend/app/services/reconciliation_service.pyindex 7fced06f..79d469fe 100644--- a/backend/app/services/reconciliation_service.py+++ b/backend/app/services/reconciliation_service.py@@ -38,7 +38,7 @@ of their own, and this module simply runs what comes back.from __future__ import annotationsimport uuid-from datetime import date, timedelta+from datetime import timedeltafrom decimal import Decimalfrom typing import Optional@@ -46,6 +46,7 @@ from sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlalchemy.orm import selectinload+from app.core.app_clock import app_todayfrom app.models.invoice import Invoice, InvoiceAllocationfrom app.models.recurring_transaction import RecurringTransactionfrom app.models.transaction import Transaction@@ -174,7 +175,7 @@ async def _open_invoices(selectinload(Invoice.payee),))- today = date.today()+ today = app_today()return [invoicefor invoice in result.unique().scalars().all()@@ -450,7 +451,7 @@ async def match_for_invoice(session, invoice.workspace_id, NODE)wanted = set(policy.get("scope", {}).get("candidate_states", []))- if invoice_service.derive_state(invoice, date.today()) not in wanted:+ if invoice_service.derive_state(invoice, app_today()) not in wanted:return Nonepolicy["strategies"] = [diff --git a/backend/app/services/recurring_transaction_service.py b/backend/app/services/recurring_transaction_service.pyindex c74e8d28..d3354f5b 100644--- a/backend/app/services/recurring_transaction_service.py+++ b/backend/app/services/recurring_transaction_service.py@@ -6,6 +6,7 @@ from typing import Optionalfrom sqlalchemy import and_, or_, selectfrom sqlalchemy.ext.asyncio import AsyncSession+from app.core.app_clock import app_todayfrom app.models.account import Accountfrom app.models.bank_connection import BankConnectionfrom app.models.recurring_transaction import RecurringTransaction@@ -270,7 +271,7 @@ async def generate_pending(If up_to is None, defaults to today. This allows the dashboard to pre-generatetransactions for future months when the user navigates ahead.Returns the count of transactions generated."""- cutoff = up_to or date.today()+ cutoff = up_to or app_today()result = await session.execute(select(RecurringTransaction)diff --git a/backend/app/services/report_service.py b/backend/app/services/report_service.pyindex 925174a8..9e18b78d 100644--- a/backend/app/services/report_service.py+++ b/backend/app/services/report_service.py@@ -7,6 +7,7 @@ from typing import Optionalfrom sqlalchemy import String, select, desc, func, casefrom sqlalchemy.ext.asyncio import AsyncSession+from app.core.app_clock import app_todayfrom app.core.config import get_settingsfrom app.models.account import Accountfrom app.models.asset import Asset@@ -311,7 +312,7 @@ async def get_net_worth_report(# A wallet-only collection (wallets, no accounts) still filters.if asset_group_ids is not None and account_ids is None:account_ids = []- real_today = date.today()+ real_today = app_today()axis_end = end_date or real_todaystart = _report_start_date(axis_end, months, period, financial_year_start_month=financial_year_start_month,@@ -437,7 +438,7 @@ async def get_income_expenses_report("""Build income/expenses; explicit custom windows include actuals only."""filtered = account_ids is not Noneacct_filter = [Transaction.account_id.in_(account_ids)] if filtered else []- real_today = date.today()+ real_today = app_today()axis_end = end_date or real_todaystart = _report_start_date(axis_end,@@ -1346,7 +1347,7 @@ async def get_cash_flow_report(from app.services.fx_rate_service import get_rateacct_filter = [Transaction.account_id.in_(account_ids)] if account_ids is not None else []- today = date.today()+ today = app_today()end = _add_months(today, months)chart_start = _add_months(today, -_PAST_HISTORY_MONTHS)diff --git a/backend/app/services/transaction_calendar_service.py b/backend/app/services/transaction_calendar_service.pyindex 959515eb..982673de 100644--- a/backend/app/services/transaction_calendar_service.py+++ b/backend/app/services/transaction_calendar_service.py@@ -7,6 +7,7 @@ from sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlalchemy.orm import selectinload+from app.core.app_clock import app_todayfrom app.core.config import get_settingsfrom app.models.account import Accountfrom app.models.category import Category@@ -44,7 +45,7 @@ async def get_transaction_calendar(projected ending balance returned by this read endpoint."""if month is None:- month = date.today().replace(day=1)+ month = app_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)@@ -88,9 +89,9 @@ async def get_transaction_calendar(# A future calendar month starts after today's current balance. Carry real# forecast rows that fall in the gap into the projected seed, just like# virtual recurring occurrences are carried below.- if grid_start > date.today():+ if grid_start > app_today():before_grid_rows = await _get_forecast_transactions(- session, workspace_id, date.today() + timedelta(days=1), grid_start,+ session, workspace_id, app_today() + timedelta(days=1), grid_start,requested_account_ids,)for tx in before_grid_rows:@@ -296,7 +297,7 @@ async def _load_actual_transactions(Account.is_closed == False,Transaction.date >= start,Transaction.date < end,- Transaction.date <= date.today(),+ Transaction.date <= app_today(),Transaction.status == "posted",).options(diff --git a/backend/app/tasks/asset_tasks.py b/backend/app/tasks/asset_tasks.pyindex 38086e8a..f61b774a 100644--- a/backend/app/tasks/asset_tasks.py+++ b/backend/app/tasks/asset_tasks.py@@ -6,6 +6,7 @@ from decimal import Decimalfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker+from app.core.app_clock import app_today, get_timezone, use_resolved_timezone, use_timezonefrom app.worker import celery_appfrom app.core.config import get_settingsfrom app.models.asset import Asset@@ -45,10 +46,10 @@ async def _apply_growth_rules() -> int:"""Apply growth rules for all assets that have valuation_method='growth_rule'."""engine, session_maker = _make_session_maker()try:- today = date.today()total = 0async with session_maker() as session:+ operation_timezone = await get_timezone(session)result = await session.execute(select(Asset).where(Asset.valuation_method == "growth_rule",@@ -61,64 +62,66 @@ async def _apply_growth_rules() -> int:)assets = list(result.scalars().all())- for asset in assets:- try:- async with session_maker() as session:- # Get latest value- val_result = await session.execute(- select(AssetValue)- .where(AssetValue.asset_id == asset.id)- .order_by(AssetValue.date.desc(), AssetValue.id.desc())- .limit(1)- )- latest = val_result.scalar_one_or_none()- if not latest:- continue-- # Check if growth should start- if asset.growth_start_date and today < asset.growth_start_date:- continue-- # Generate all missed periods in a loop- current_date = latest.date- current_amount = float(latest.amount)- created = 0-- while True:- next_due = _next_due_date(current_date, asset.growth_frequency)- if next_due > today:- break-- if asset.growth_type == "percentage":- current_amount = current_amount * (1 + float(asset.growth_rate) / 100)- elif asset.growth_type == "absolute":- current_amount = current_amount + float(asset.growth_rate)- else:- break-- new_value = AssetValue(- asset_id=asset.id,- amount=Decimal(str(round(current_amount, 6))),- date=next_due,- source="rule",+ with use_resolved_timezone(operation_timezone):+ today = app_today()+ for asset in assets:+ try:+ async with session_maker() as session:+ # Get latest value+ val_result = await session.execute(+ select(AssetValue)+ .where(AssetValue.asset_id == asset.id)+ .order_by(AssetValue.date.desc(), AssetValue.id.desc())+ .limit(1))- session.add(new_value)- current_date = next_due- created += 1-- # Safety limit to avoid infinite loops- if created >= 1000:- break-- if created > 0:- await session.commit()- total += created- logger.info(- "Growth rule applied for asset %s: %d values created, latest=%.2f",- asset.id, created, current_amount,- )- except Exception:- logger.exception("Failed to apply growth rule for asset %s", asset.id)+ latest = val_result.scalar_one_or_none()+ if not latest:+ continue++ # Check if growth should start+ if asset.growth_start_date and today < asset.growth_start_date:+ continue++ # Generate all missed periods in a loop+ current_date = latest.date+ current_amount = float(latest.amount)+ created = 0++ while True:+ next_due = _next_due_date(current_date, asset.growth_frequency)+ if next_due > today:+ break++ if asset.growth_type == "percentage":+ current_amount = current_amount * (1 + float(asset.growth_rate) / 100)+ elif asset.growth_type == "absolute":+ current_amount = current_amount + float(asset.growth_rate)+ else:+ break++ new_value = AssetValue(+ asset_id=asset.id,+ amount=Decimal(str(round(current_amount, 6))),+ date=next_due,+ source="rule",+ )+ session.add(new_value)+ current_date = next_due+ created += 1++ # Safety limit to avoid infinite loops+ if created >= 1000:+ break++ if created > 0:+ await session.commit()+ total += created+ logger.info(+ "Growth rule applied for asset %s: %d values created, latest=%.2f",+ asset.id, created, current_amount,+ )+ except Exception:+ logger.exception("Failed to apply growth rule for asset %s", asset.id)finally:await engine.dispose()@@ -141,7 +144,7 @@ async def _refresh_market_prices() -> dict[str, int]:"""engine, session_maker = _make_session_maker()try:- async with session_maker() as session:+ async with session_maker() as session, use_timezone(session):return await refresh_all_market_prices(session)finally:await engine.dispose()diff --git a/backend/app/tasks/fx_backfill_tasks.py b/backend/app/tasks/fx_backfill_tasks.pyindex 8ecb8656..527a6c72 100644--- a/backend/app/tasks/fx_backfill_tasks.py+++ b/backend/app/tasks/fx_backfill_tasks.py@@ -6,6 +6,7 @@ from decimal import Decimalfrom sqlalchemy import select, or_from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker+from app.core.app_clock import use_timezonefrom app.worker import celery_appfrom app.core.config import get_settingsfrom app.models.transaction import Transaction@@ -36,7 +37,7 @@ async def _backfill_primary_amounts() -> dict:try:stats = {"transactions": 0, "recurring": 0, "assets": 0, "rates_synced": 0}- async with session_maker() as session:+ async with session_maker() as session, use_timezone(session):# 1. Get all users up front so we can tell cross-currency rows apart.users_result = await session.execute(select(User))settings = get_settings()diff --git a/backend/app/tasks/fx_rate_tasks.py b/backend/app/tasks/fx_rate_tasks.pyindex 50537ac9..c03628c5 100644--- a/backend/app/tasks/fx_rate_tasks.py+++ b/backend/app/tasks/fx_rate_tasks.py@@ -3,6 +3,7 @@ import loggingfrom sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker+from app.core.app_clock import use_timezonefrom app.worker import celery_appfrom app.core.config import get_settings@@ -22,7 +23,7 @@ async def _sync_fx_rates() -> int:engine, session_maker = _make_session_maker()try:- async with session_maker() as session:+ async with session_maker() as session, use_timezone(session):count = await sync_rates(session)return countfinally:@@ -39,24 +40,24 @@ async def _restamp_recurring_fx() -> int:engine, session_maker = _make_session_maker()try:- async with session_maker() as session:+ async with session_maker() as session, use_timezone(session):users = (await session.execute(select(User))).scalars().all()- count = 0- for user in users:- primary = user.primary_currency- result = await session.execute(- select(RecurringTransaction).where(- RecurringTransaction.user_id == user.id,- RecurringTransaction.is_active == True,- RecurringTransaction.currency != primary,- )- )- for rec in result.scalars().all():- await stamp_primary_amount(- session, user.id, rec, date_field="start_date",+ count = 0+ for user in users:+ primary = user.primary_currency+ result = await session.execute(+ select(RecurringTransaction).where(+ RecurringTransaction.user_id == user.id,+ RecurringTransaction.is_active == True,+ RecurringTransaction.currency != primary,+ ))- count += 1- await session.commit()+ for rec in result.scalars().all():+ await stamp_primary_amount(+ session, user.id, rec, date_field="start_date",+ )+ count += 1+ await session.commit()finally:await engine.dispose()return count@@ -85,7 +86,7 @@ async def _restamp_fallback_transactions() -> int:settings = get_settings()engine, session_maker = _make_session_maker()try:- async with session_maker() as session:+ async with session_maker() as session, use_timezone(session):users = {u.id: u.primary_currencyfor u in (await session.execute(select(User))).scalars().all()diff --git a/backend/app/tasks/recurring_tasks.py b/backend/app/tasks/recurring_tasks.pyindex e88497be..99d5c39a 100644--- a/backend/app/tasks/recurring_tasks.py+++ b/backend/app/tasks/recurring_tasks.py@@ -4,6 +4,7 @@ import loggingfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker+from app.core.app_clock import get_timezone, use_resolved_timezonefrom app.worker import celery_appfrom app.core.config import get_settingsfrom app.models.user import User@@ -26,18 +27,20 @@ async def _generate_all() -> int:total = 0async with session_maker() as session:+ operation_timezone = await get_timezone(session)result = await session.execute(select(User.id))user_ids = [row[0] for row in result.all()]- for user_id in user_ids:- try:- async with session_maker() as session:- count = await recurring_transaction_service.generate_pending(session, user_id)- if count:- logger.info("Generated %d recurring transactions for user %s", count, user_id)- total += count- except Exception:- logger.exception("Failed to generate recurring transactions for user %s", user_id)+ with use_resolved_timezone(operation_timezone):+ for user_id in user_ids:+ try:+ async with session_maker() as session:+ count = await recurring_transaction_service.generate_pending(session, user_id)+ if count:+ logger.info("Generated %d recurring transactions for user %s", count, user_id)+ total += count+ except Exception:+ logger.exception("Failed to generate recurring transactions for user %s", user_id)finally:await engine.dispose()diff --git a/backend/app/tasks/sync_tasks.py b/backend/app/tasks/sync_tasks.pyindex 96a4ca8e..01d0d8b3 100644--- a/backend/app/tasks/sync_tasks.py+++ b/backend/app/tasks/sync_tasks.py@@ -6,6 +6,7 @@ from datetime import datetime, timezone, timedeltafrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine+from app.core.app_clock import get_timezone, use_resolved_timezone, use_timezonefrom app.worker import celery_appfrom app.core.config import get_settingsfrom app.models.bank_connection import BankConnection@@ -45,6 +46,7 @@ async def _sync_all() -> int:synced = 0async with session_maker() as session:+ operation_timezone = await get_timezone(session)result = await session.execute(select(BankConnection.id,@@ -65,24 +67,25 @@ async def _sync_all() -> int:cutoff.isoformat(),)- for conn_id, user_id, last_sync, settings in connections:- try:- logger.info("Syncing connection %s (last_sync=%s)", conn_id, last_sync)- await _sync_one(- session_maker,- conn_id,- user_id,- trigger_provider_refresh=_should_trigger_provider_refresh(- settings, datetime.now(timezone.utc)- ),- )- synced += 1- except ProviderNotConfiguredError as exc:- # Actionable one-liner instead of a buried traceback: this- # means THIS process is missing the provider's configuration.- logger.error("Skipping connection %s: %s", conn_id, exc)- except Exception:- logger.exception("Background sync failed for connection %s", conn_id)+ with use_resolved_timezone(operation_timezone):+ for conn_id, user_id, last_sync, settings in connections:+ try:+ logger.info("Syncing connection %s (last_sync=%s)", conn_id, last_sync)+ await _sync_one(+ session_maker,+ conn_id,+ user_id,+ trigger_provider_refresh=_should_trigger_provider_refresh(+ settings, datetime.now(timezone.utc)+ ),+ )+ synced += 1+ except ProviderNotConfiguredError as exc:+ # Actionable one-liner instead of a buried traceback: this+ # means THIS process is missing the provider's configuration.+ logger.error("Skipping connection %s: %s", conn_id, exc)+ except Exception:+ logger.exception("Background sync failed for connection %s", conn_id)return syncedfinally:@@ -135,7 +138,7 @@ def sync_single_connection(connection_id: str, user_id: str) -> dict:async def _sync_one_celery(connection_id: str, user_id: str) -> None:engine, session_maker = _make_session_maker()try:- async with session_maker() as session:+ async with session_maker() as session, use_timezone(session):conn_uuid = uuid.UUID(connection_id)workspace_id = await session.scalar(select(BankConnection.workspace_id).where(BankConnection.id == conn_uuid)diff --git a/backend/mcp_server/registry.py b/backend/mcp_server/registry.pyindex 1c4c8bd0..ccdcfe81 100644--- a/backend/mcp_server/registry.py+++ b/backend/mcp_server/registry.py@@ -79,4 +79,7 @@ async def call_tool(spec = REGISTRY.get(name)if spec is None:raise KeyError(f"unknown tool: {name}")- return await spec.handler(session=session, ctx=ctx, **(arguments or {}))+ from app.core.app_clock import use_timezone++ async with use_timezone(session):+ return await spec.handler(session=session, ctx=ctx, **(arguments or {}))diff --git a/backend/mcp_server/tools/budgets.py b/backend/mcp_server/tools/budgets.pyindex 036266d0..851a2db2 100644--- a/backend/mcp_server/tools/budgets.py+++ b/backend/mcp_server/tools/budgets.py@@ -1,10 +1,10 @@from __future__ import annotations-from datetime import datefrom typing import Anyfrom sqlalchemy.ext.asyncio import AsyncSession+from app.core.app_clock import app_todayfrom app.services import budget_servicefrom mcp_server.auth import CallContextfrom mcp_server.registry import tool@@ -32,7 +32,7 @@ async def get_budget_vs_actual(ctx: CallContext,month: str | None = None,) -> dict[str, Any]:- target = parse_date(month) or date.today().replace(day=1)+ target = parse_date(month) or app_today().replace(day=1)ws_id = await resolve_workspace_id(session, ctx)rows = await budget_service.get_budget_vs_actual(session, ws_id, ctx.user_id, month=target)items = []diff --git a/backend/mcp_server/tools/proposals.py b/backend/mcp_server/tools/proposals.pyindex f0b548fa..6327e919 100644--- a/backend/mcp_server/tools/proposals.py+++ b/backend/mcp_server/tools/proposals.py@@ -15,13 +15,13 @@ unchanged for Securo's own UI.from __future__ import annotations-from datetime import datefrom decimal import Decimalfrom typing import Anyfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession+from app.core.app_clock import app_todayfrom app.models.account import Accountfrom app.models.category import Categoryfrom app.models.group import Group, GroupMember@@ -291,7 +291,7 @@ async def propose_create_budget() -> dict[str, Any]:ws_id = await resolve_workspace_id(session, ctx)cat_id = parse_uuid(category_id)- target_month = (parse_date(month) or date.today()).replace(day=1)+ target_month = (parse_date(month) or app_today()).replace(day=1)cat = (await session.execute(diff --git a/backend/mcp_server/tools/reports.py b/backend/mcp_server/tools/reports.pyindex b00bfcbb..ecc6cd9f 100644--- a/backend/mcp_server/tools/reports.py+++ b/backend/mcp_server/tools/reports.py@@ -1,10 +1,10 @@from __future__ import annotations-from datetime import datefrom typing import Anyfrom sqlalchemy.ext.asyncio import AsyncSession+from app.core.app_clock import app_todayfrom app.services import dashboard_service, report_servicefrom mcp_server.auth import CallContextfrom mcp_server.registry import tool@@ -125,7 +125,7 @@ async def get_dashboard_snapshot(ctx: CallContext,month: str | None = None,) -> dict[str, Any]:- target = parse_date(month) or date.today().replace(day=1)+ target = parse_date(month) or app_today().replace(day=1)ws_id = await resolve_workspace_id(session, ctx)summary = await dashboard_service.get_summary(session, ws_id, ctx.user_id, month=target)if hasattr(summary, "model_dump"):diff --git a/backend/pyproject.toml b/backend/pyproject.tomlindex a299b1b8..80e02b09 100644--- a/backend/pyproject.toml+++ b/backend/pyproject.toml@@ -46,6 +46,8 @@ dependencies = [# agents feature pay zero cost (the package is installed but never# imported)."fastembed>=0.4.0",+ # Resolve the host's IANA timezone when no app setting or TZ override exists.+ "tzlocal>=5.0.0",][project.optional-dependencies]diff --git a/backend/tests/conftest.py b/backend/tests/conftest.pyindex c890bf11..13920fce 100644--- a/backend/tests/conftest.py+++ b/backend/tests/conftest.py@@ -174,8 +174,11 @@ def _fast_password_hashes():async def override_get_async_session() -> AsyncGenerator[AsyncSession, None]:+ from app.core.app_clock import use_timezone+async with TestSessionLocal() as session:- yield session+ async with use_timezone(session):+ yield session# Override the dependencydiff --git a/backend/tests/test_app_timezone.py b/backend/tests/test_app_timezone.pynew file mode 100644index 00000000..60068497--- /dev/null+++ b/backend/tests/test_app_timezone.py@@ -0,0 +1,291 @@+from datetime import date, datetime, timezone+from unittest.mock import patch+from zoneinfo import ZoneInfo++import pytest++from app.models.app_settings import AppSetting+++class FixedDatetime(datetime):+ @classmethod+ def now(cls, tz=None):+ return datetime(2026, 5, 19, 1, 0, tzinfo=timezone.utc).astimezone(tz)+++async def test_saved_timezone_takes_effect_for_new_operations(session, clean_db):+ from app.core.app_clock import app_today, use_timezone++ setting = AppSetting(key="timezone", value="America/Sao_Paulo")+ session.add(setting)+ await session.commit()++ with patch("app.core.app_clock.datetime", FixedDatetime):+ async with use_timezone(session):+ assert app_today().isoformat() == "2026-05-18"++ setting.value = "Asia/Tokyo"+ await session.commit()+ assert app_today().isoformat() == "2026-05-18"++ async with use_timezone(session):+ assert app_today().isoformat() == "2026-05-19"+++async def test_tz_environment_falls_back_to_system_timezone(session, clean_db, monkeypatch):+ from app.core.app_clock import app_today, use_timezone++ monkeypatch.setenv("TZ", "Unavailable/Zone")+ with (+ patch("tzlocal.get_localzone", return_value=ZoneInfo("America/Bahia")),+ patch("app.core.app_clock.datetime", FixedDatetime),+ ):+ async with use_timezone(session):+ assert app_today().isoformat() == "2026-05-18"+++async def test_invalid_saved_timezone_keeps_repair_endpoint_available(+ client, admin_auth_headers, session, monkeypatch, caplog+):+ monkeypatch.setenv("TZ", "America/Sao_Paulo")+ session.add(AppSetting(key="timezone", value="Unavailable/Zone"))+ await session.commit()++ response = await client.get("/api/setup/status")+ assert response.status_code == 200++ response = await client.get("/api/admin/timezone", headers=admin_auth_headers)+ assert response.status_code == 200+ assert response.json()["timezone"] == "America/Sao_Paulo"+ assert "Saved application timezone is unavailable" in caplog.text++ response = await client.patch(+ "/api/admin/settings/timezone",+ headers=admin_auth_headers,+ json={"value": "UTC"},+ )+ assert response.status_code == 200+++async def test_admin_can_set_timezone_and_invalid_names_are_rejected(+ client, admin_auth_headers+):+ response = await client.patch(+ "/api/admin/settings/timezone",+ headers=admin_auth_headers,+ json={"value": "America/Sao_Paulo"},+ )+ assert response.status_code == 200++ response = await client.get("/api/admin/timezone", headers=admin_auth_headers)+ assert response.status_code == 200+ assert response.json()["timezone"] == "America/Sao_Paulo"+ assert "Europe/London" in response.json()["available"]++ for value in ("Invalid/Timezone", "../UTC", ""):+ response = await client.patch(+ "/api/admin/settings/timezone",+ headers=admin_auth_headers,+ json={"value": value},+ )+ assert response.status_code == 400+++async def test_context_primer_uses_application_timezone(session, test_user):+ from app.agents.services.context_service import build_context_primer+ from app.core.app_clock import use_timezone++ setting = AppSetting(key="timezone", value="America/Sao_Paulo")+ session.add(setting)+ await session.commit()++ with patch("app.core.app_clock.datetime", FixedDatetime):+ async with use_timezone(session):+ primer = await build_context_primer(session, test_user)++ assert "Today is 2026-05-18 (America/Sao_Paulo)" in primer+ assert "Timezone: America/Sao_Paulo" in primer+++async def test_account_service_uses_application_day_for_dates_and_balances(+ session, test_user, test_workspace, monkeypatch+):+ from decimal import Decimal++ from sqlalchemy import select++ from app.core.app_clock import use_timezone+ from app.models.transaction import Transaction+ from app.schemas.account import AccountCreate+ from app.services.account_service import create_account, get_accounts++ monkeypatch.setenv("TZ", "UTC")+ session.add(AppSetting(key="timezone", value="America/Sao_Paulo"))+ await session.commit()++ with patch("app.core.app_clock.datetime", FixedDatetime):+ async with use_timezone(session):+ account = await create_account(+ session,+ test_workspace.id,+ test_user.id,+ AccountCreate(+ name="Local calendar account",+ type="checking",+ balance=Decimal("100.00"),+ currency="BRL",+ ),+ )+ opening = await session.scalar(+ select(Transaction).where(+ Transaction.account_id == account.id,+ Transaction.source == "opening_balance",+ )+ )+ assert opening is not None+ assert opening.date == date(2026, 5, 18)++ session.add(+ Transaction(+ user_id=test_user.id,+ workspace_id=test_workspace.id,+ account_id=account.id,+ description="Tomorrow locally",+ amount=Decimal("50.00"),+ currency="BRL",+ date=date(2026, 5, 19),+ type="credit",+ source="manual",+ )+ )+ await session.commit()+ [serialized] = await get_accounts(session, test_workspace.id)++ assert serialized["current_balance"] == 100.0+++async def test_recurring_generation_waits_until_the_local_due_date(+ session, test_user, test_workspace, test_account, monkeypatch+):+ from app.core.app_clock import use_timezone+ from app.schemas.recurring_transaction import RecurringTransactionCreate+ from app.services.recurring_transaction_service import (+ create_recurring_transaction,+ generate_pending,+ )++ monkeypatch.setenv("TZ", "UTC")+ await create_recurring_transaction(+ session,+ test_workspace.id,+ test_user.id,+ RecurringTransactionCreate(+ description="Local due date",+ amount=10,+ type="debit",+ frequency="monthly",+ start_date=date(2026, 5, 19),+ account_id=test_account.id,+ auto_generate=True,+ ),+ )+ setting = AppSetting(key="timezone", value="America/Sao_Paulo")+ session.add(setting)+ await session.commit()++ with patch("app.core.app_clock.datetime", FixedDatetime):+ async with use_timezone(session):+ assert await generate_pending(session, test_user.id) == 0++ setting.value = "UTC"+ await session.commit()+ async with use_timezone(session):+ assert await generate_pending(session, test_user.id) == 1+++async def test_recurring_fx_worker_uses_local_day_through_commit(+ session, test_user, test_workspace, monkeypatch+):+ from decimal import Decimal+ from types import SimpleNamespace+ from unittest.mock import AsyncMock++ from sqlalchemy.ext.asyncio import async_sessionmaker++ from app.models.fx_rate import FxRate+ from app.models.recurring_transaction import RecurringTransaction+ from app.tasks.fx_rate_tasks import _restamp_recurring_fx++ monkeypatch.setenv("TZ", "UTC")+ test_user.preferences = {"currency_display": "USD"}+ session.add(AppSetting(key="timezone", value="America/Sao_Paulo"))+ for day, rate in ((18, 5), (19, 10)):+ session.add(+ FxRate(+ base_currency="USD",+ quote_currency="BRL",+ date=date(2026, 5, day),+ rate=rate,+ source="test",+ )+ )+ recurring = RecurringTransaction(+ user_id=test_user.id,+ workspace_id=test_workspace.id,+ description="Local FX",+ amount=100,+ currency="BRL",+ type="debit",+ frequency="monthly",+ start_date=date(2026, 5, 19),+ next_occurrence=date(2026, 5, 19),+ )+ session.add(recurring)+ await session.commit()+ maker = async_sessionmaker(session.bind, expire_on_commit=False)++ with (+ patch("app.core.app_clock.datetime", FixedDatetime),+ patch(+ "app.tasks.fx_rate_tasks._make_session_maker",+ return_value=(SimpleNamespace(dispose=AsyncMock()), maker),+ ),+ ):+ assert await _restamp_recurring_fx() == 1++ await session.refresh(recurring)+ assert recurring.amount_primary == Decimal("20.00")+ assert recurring.fx_rate_used == Decimal("0.2")+++async def test_mcp_defaults_use_application_month(session, test_user, test_workspace):+ from mcp_server.auth import CallContext+ from mcp_server.registry import call_tool+ import mcp_server.tools # noqa: F401++ class MonthBoundary(datetime):+ @classmethod+ def now(cls, tz=None):+ return datetime(2026, 6, 1, 1, 0, tzinfo=timezone.utc).astimezone(tz)++ session.add(AppSetting(key="timezone", value="America/Sao_Paulo"))+ await session.commit()++ with patch("app.core.app_clock.datetime", MonthBoundary):+ result = await call_tool(+ session,+ CallContext(user_id=test_user.id, workspace_id=test_workspace.id),+ "get_budget_vs_actual",+ {},+ )++ assert result["month"] == "2026-05-01"diff --git a/backend/tests/test_dashboard_service_coverage.py b/backend/tests/test_dashboard_service_coverage.pyindex ef0fe6b9..9379c9c0 100644--- a/backend/tests/test_dashboard_service_coverage.py+++ b/backend/tests/test_dashboard_service_coverage.py@@ -40,13 +40,9 @@ from app.services.dashboard_service import (@pytest.fixturedef projection_today(monkeypatch):"""Keep current-month projection cases away from the last day of a month."""- class ProjectionDate(date):- @classmethod- def today(cls):- return cls(2026, 1, 15)-- monkeypatch.setattr("app.services.dashboard_service.date", ProjectionDate)- return ProjectionDate.today()+ today = date(2026, 1, 15)+ monkeypatch.setattr("app.services.dashboard_service.app_today", lambda: today)+ return todayasync def _seed_fx(session, today=None):diff --git a/backend/tests/test_goal_service_coverage.py b/backend/tests/test_goal_service_coverage.pyindex d1c0d1c6..b0e42dcc 100644--- a/backend/tests/test_goal_service_coverage.py+++ b/backend/tests/test_goal_service_coverage.py@@ -157,8 +157,7 @@ def test_monthly_contribution_normal():def test_monthly_contribution_months_clamped_to_one():# Target date in the same calendar month but a later day -> months == 0,# clamped to 1 (line 111). today < target_date so we don't hit the past branch.- with patch("app.services.goal_service.date", wraps=date) as clock:- clock.today.return_value = date(2026, 1, 15)+ with patch("app.services.goal_service.app_today", return_value=date(2026, 1, 15)):val = _compute_monthly_contribution(Decimal("0"), Decimal("500"), date(2026, 1, 28))assert val == 500.0 # remaining / 1 monthdiff --git a/backend/tests/test_invoice_service.py b/backend/tests/test_invoice_service.pyindex b69cf374..884ef354 100644--- a/backend/tests/test_invoice_service.py+++ b/backend/tests/test_invoice_service.py@@ -8,11 +8,13 @@ allocation table really is N:N — the claim the whole schema rests on.import uuidfrom datetime import date, datetime, timedelta, timezonefrom decimal import Decimal+from zoneinfo import ZoneInfoimport pytestimport pytest_asynciofrom sqlalchemy.ext.asyncio import AsyncSession+from app.core.app_clock import use_resolved_timezonefrom app.models.account import Accountfrom app.models.invoice import Invoice, InvoiceAllocationfrom app.models.transaction import Transaction@@ -398,6 +400,20 @@ class TestAgingBuckets:assert summary["outstanding"] == Decimal("500.00")assert live.id in {i.id for i in summary["upcoming"]}+ async def test_received_this_month_uses_the_application_timezone(+ self, session: AsyncSession, workspace, test_user, credit+ ):+ invoice = await create(session, workspace, test_user)+ allocated = await svc.allocate(session, invoice, credit.id, Decimal("100.00"))+ allocated.allocated_at = datetime(2026, 9, 1, 1, tzinfo=timezone.utc)+ await session.commit()++ with use_resolved_timezone(ZoneInfo("America/Bahia")):+ summary = await svc.aging_summary(session, workspace.id, date(2026, 9, 1))++ # 01:00 UTC is still August 31 in Bahia, so it is not September cash.+ assert summary["received_this_month"] == Decimal("0.00")+@pytest.mark.asyncioclass TestCompetenceDate:diff --git a/backend/tests/test_invoices_api.py b/backend/tests/test_invoices_api.pyindex 15da2d6e..d5658d18 100644--- a/backend/tests/test_invoices_api.py+++ b/backend/tests/test_invoices_api.py@@ -10,7 +10,7 @@ Two things these tests exist to pin down, beyond the usual CRUD:UI does, computed from allocations and the due date."""import uuid-from datetime import date, datetime, timedelta, timezone+from datetime import date, timedeltafrom decimal import Decimalfrom unittest.mock import patch@@ -27,9 +27,9 @@ from app.models.transaction import Transaction@pytest.fixturedef invoice_today():"""Pin the service clock so UTC/local midnight cannot change expectations."""- with patch("app.services.invoice_service.datetime", wraps=datetime) as clock:- clock.now.return_value = datetime(2026, 1, 15, tzinfo=timezone.utc)- yield clock.now.return_value.date()+ today = date(2026, 1, 15)+ with patch("app.services.invoice_service.app_today", return_value=today):+ yield today@pytest_asyncio.fixturediff --git a/backend/tests/test_reports_postgres.py b/backend/tests/test_reports_postgres.pyindex b6dcb6ef..dd7d6658 100644--- a/backend/tests/test_reports_postgres.py+++ b/backend/tests/test_reports_postgres.py@@ -243,12 +243,8 @@ async def test_aggregate_by_month(session, test_user, test_transactions):async def test_monthly_report_follows_mode(session, test_user, test_account, monkeypatch):- class ReportDate(date):- @classmethod- def today(cls):- return cls(2026, 2, 1)-- monkeypatch.setattr(report_service, "date", ReportDate)+ # The service asks the application clock for today, so that is what is pinned.+ monkeypatch.setattr(report_service, "app_today", lambda: date(2026, 2, 1))test_account.type = "credit_card"for when, effective, amount in [(date(2025, 12, 30), date(2026, 1, 16), Decimal("120")),diff --git a/backend/uv.lock b/backend/uv.lockindex 6d48a923..242df981 100644--- a/backend/uv.lock+++ b/backend/uv.lock@@ -2565,6 +2565,7 @@ dependencies = [{ name = "redis", extra = ["hiredis"] },{ name = "reportlab" },{ name = "sqlalchemy" },+ { name = "tzlocal" },{ name = "uvicorn", extra = ["standard"] },{ name = "webauthn" },{ name = "yfinance" },@@ -2614,6 +2615,7 @@ requires-dist = [{ name = "ruff", marker = "extra == 'dev'", specifier = ">=0.16.4,<0.17" },{ name = "sqlalchemy", specifier = ">=2.0.0" },{ name = "ty", marker = "extra == 'dev'", specifier = "==0.0.82" },+ { name = "tzlocal", specifier = ">=5.0.0" },{ name = "uvicorn", extras = ["standard"], specifier = ">=0.27.0" },{ name = "webauthn", specifier = ">=2.8.0" },{ name = "yfinance", specifier = ">=1.3.0" },diff --git a/frontend/src/components/timezone-select.test.tsx b/frontend/src/components/timezone-select.test.tsxnew file mode 100644index 00000000..2f084ffb--- /dev/null+++ b/frontend/src/components/timezone-select.test.tsx@@ -0,0 +1,88 @@+import { useState } from 'react'+import { screen, within } from '@testing-library/react'+import { describe, expect, it, vi } from 'vitest'++import { renderWithProviders } from '@/test/utils'++import { timezoneCityLabel, timezoneOffsetLabel } from '@/lib/timezone-utils'++import { TimezoneSelect } from './timezone-select'++const options = ['America/Sao_Paulo', 'America/New_York', 'Asia/Tokyo', 'Europe/Paris', 'UTC']++function renderSelect(initial = '', emptyOption?: string) {+ const onChange = vi.fn()+ function Harness() {+ const [value, setValue] = useState(initial)+ return (+ <TimezoneSelect+ id="tz"+ value={value}+ onChange={(v) => { setValue(v); onChange(v) }}+ options={options}+ emptyOption={emptyOption}+ />+ )+ }+ return { ...renderWithProviders(<Harness />), onChange }+}++describe('timezone labels', () => {+ it('reads the city out of the IANA name', () => {+ expect(timezoneCityLabel('America/Sao_Paulo')).toBe('Sao Paulo')+ expect(timezoneCityLabel('America/Argentina/Buenos_Aires')).toBe('Argentina/Buenos Aires')+ expect(timezoneCityLabel('UTC')).toBe('UTC')+ })++ it('gives the current offset, or nothing for a name the runtime does not know', () => {+ const winter = new Date('2026-01-15T12:00:00Z')+ expect(timezoneOffsetLabel('America/Sao_Paulo', winter)).toBe('GMT-3')+ expect(timezoneOffsetLabel('Asia/Kolkata', winter)).toBe('GMT+5:30')+ expect(timezoneOffsetLabel('UTC', winter)).toBe('GMT')+ expect(timezoneOffsetLabel('Mars/Olympus_Mons', winter)).toBeNull()+ })+})++describe('TimezoneSelect', () => {+ it('finds a zone by city, by IANA name or by offset', async () => {+ const { user, onChange } = renderSelect()+ await user.click(screen.getByRole('combobox'))+ const search = screen.getByPlaceholderText('Search timezone...')++ await user.type(search, 'sao paulo')+ expect(screen.getAllByRole('option')).toHaveLength(1)+ await user.clear(search)+ await user.type(search, 'asia/to')+ expect(screen.getAllByRole('option')).toHaveLength(1)+ await user.clear(search)+ await user.type(search, 'gmt-3')+ expect(screen.getAllByRole('option').map((o) => o.textContent)).toEqual([+ expect.stringContaining('America/Sao_Paulo'),+ ])++ await user.click(screen.getByRole('option', { name: /America\/Sao_Paulo/ }))+ expect(onChange).toHaveBeenCalledWith('America/Sao_Paulo')+ expect(screen.getByRole('combobox')).toHaveTextContent('America/Sao_Paulo')+ })++ it('groups zones by region', async () => {+ const { user } = renderSelect('Asia/Tokyo')+ await user.click(screen.getByRole('combobox'))+ const list = screen.getByRole('listbox')+ expect(within(list).getByText('America')).toBeInTheDocument()+ expect(within(list).getByText('Europe')).toBeInTheDocument()+ // UTC has no region, so it is listed without a heading, after the regions.+ const texts = within(list).getAllByRole('option').map((o) => o.textContent ?? '')+ expect(texts[texts.length - 1]).toContain('UTC')+ })++ it('offers the empty choice first when one is given', async () => {+ const { user, onChange } = renderSelect('Asia/Tokyo', 'Server default (UTC)')+ await user.click(screen.getByRole('combobox'))+ const [first] = screen.getAllByRole('option')+ expect(first).toHaveTextContent('Server default (UTC)')+ await user.click(first)+ expect(onChange).toHaveBeenCalledWith('')+ expect(screen.getByRole('combobox')).toHaveTextContent('Server default (UTC)')+ })+})diff --git a/frontend/src/components/timezone-select.tsx b/frontend/src/components/timezone-select.tsxnew file mode 100644index 00000000..b6577b50--- /dev/null+++ b/frontend/src/components/timezone-select.tsx@@ -0,0 +1,170 @@+import { useMemo, useState } from 'react'+import { useTranslation } from 'react-i18next'+import { CheckIcon, ChevronDownIcon } from 'lucide-react'++import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'+import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from '@/components/ui/command'+import { timezoneCityLabel, timezoneOffsetLabel, timezoneRegion } from '@/lib/timezone-utils'+import { cn, normalizeText } from '@/lib/utils'++interface TimezoneSelectProps {+ value: string+ onChange: (value: string) => void+ /** IANA names, as the server lists them. */+ options: string[]+ /**+ * An extra first choice carrying the empty value, for "follow the default"+ * pickers. Its label is shown on the trigger when nothing is chosen.+ */+ emptyOption?: string+ id?: string+ disabled?: boolean+ className?: string+ 'aria-describedby'?: string+}++/**+ * A searchable timezone picker, grouped by region the way the category+ * picker groups by category group. Typing "sao paulo", "America/Sao" or+ * "gmt-3" all find America/Sao_Paulo; the flat 600-row dropdown it replaces+ * asked the user to scroll.+ */+export function TimezoneSelect({+ value,+ onChange,+ options,+ emptyOption,+ id,+ disabled = false,+ className,+ 'aria-describedby': describedBy,+}: TimezoneSelectProps) {+ const { t } = useTranslation()+ const [open, setOpen] = useState(false)+ const [search, setSearch] = useState('')++ const groups = useMemo(() => {+ const byRegion = new Map<string, string[]>()+ for (const name of options) {+ const region = timezoneRegion(name)+ byRegion.set(region, [...(byRegion.get(region) ?? []), name])+ }+ // Regions in alphabetical order; the few names without a region (UTC,+ // GMT and the legacy aliases) close the list.+ return [...byRegion.entries()]+ .sort(([a], [b]) => (a === '' ? 1 : b === '' ? -1 : a.localeCompare(b)))+ .map(([region, names]) => ({ region, names: [...names].sort() }))+ }, [options])++ // Offsets are computed once per open, not once per keystroke.+ const offsets = useMemo(() => {+ if (!open) return new Map<string, string | null>()+ const now = new Date()+ return new Map(options.map((name) => [name, timezoneOffsetLabel(name, now)]))+ }, [open, options])++ function handleOpenChange(next: boolean) {+ setOpen(next)+ if (!next) setSearch('')+ }++ function choose(next: string) {+ onChange(next)+ handleOpenChange(false)+ }++ const selectedOffset = value ? timezoneOffsetLabel(value) : null++ return (+ <Popover open={open} onOpenChange={handleOpenChange}>+ <PopoverTrigger asChild>+ <button+ type="button"+ id={id}+ role="combobox"+ aria-expanded={open}+ aria-describedby={describedBy}+ disabled={disabled}+ className={cn(+ 'flex w-full items-center justify-between gap-2 rounded-md border border-input bg-card px-3 py-2 text-sm text-left shadow-xs transition-[color,box-shadow] outline-hidden focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 dark:bg-input/30 dark:hover:bg-input/50 h-9 cursor-pointer',+ className,+ )}+ >+ <span className="flex items-center gap-2 min-w-0 truncate">+ {value ? (+ <>+ <span className="truncate">{value}</span>+ {selectedOffset && (+ <span className="shrink-0 text-xs tabular-nums text-muted-foreground">{selectedOffset}</span>+ )}+ </>+ ) : (+ <span className={cn('truncate', emptyOption ? 'italic text-muted-foreground' : 'text-muted-foreground')}>+ {emptyOption ?? t('common.selectTimezone')}+ </span>+ )}+ </span>+ <ChevronDownIcon className="size-4 shrink-0 opacity-50" />+ </button>+ </PopoverTrigger>+ <PopoverContent+ align="start"+ className="w-[var(--radix-popover-trigger-width)] min-w-72 p-0 overflow-hidden"+ >+ <Command+ filter={(itemValue, query) => (normalizeText(itemValue).includes(normalizeText(query)) ? 1 : 0)}+ >+ <CommandInput+ placeholder={t('common.searchTimezone')}+ value={search}+ onValueChange={setSearch}+ />+ <CommandList>+ <CommandEmpty>{t('common.noTimezoneFound')}</CommandEmpty>+ {emptyOption && (+ <CommandGroup>+ <CommandItem+ value={`default ${emptyOption}`}+ onSelect={() => choose('')}+ className="italic text-muted-foreground cursor-pointer"+ >+ <span className="flex-1 truncate">{emptyOption}</span>+ {value === '' && <CheckIcon className="size-4 shrink-0" />}+ </CommandItem>+ </CommandGroup>+ )}+ {groups.map(({ region, names }) => (+ <CommandGroup key={region || 'other'}>+ {region && (+ <div className="px-2 py-1 text-[10.5px] font-semibold uppercase tracking-[0.08em] text-muted-foreground/70">+ {region}+ </div>+ )}+ {names.map((name) => {+ const offset = offsets.get(name)+ return (+ <CommandItem+ key={name}+ value={`${name} ${timezoneCityLabel(name)} ${offset ?? ''}`}+ onSelect={() => choose(name)}+ className="cursor-pointer"+ >+ <span className="flex items-baseline gap-2 min-w-0 truncate flex-1">+ <span className="truncate">{timezoneCityLabel(name)}</span>+ <span className="truncate text-xs text-muted-foreground">{name}</span>+ </span>+ {offset && (+ <span className="shrink-0 text-xs tabular-nums text-muted-foreground">{offset}</span>+ )}+ {value === name && <CheckIcon className="size-4 shrink-0" />}+ </CommandItem>+ )+ })}+ </CommandGroup>+ ))}+ </CommandList>+ </Command>+ </PopoverContent>+ </Popover>+ )+}diff --git a/frontend/src/components/timezone-settings.test.tsx b/frontend/src/components/timezone-settings.test.tsxnew file mode 100644index 00000000..9f1c8cca--- /dev/null+++ b/frontend/src/components/timezone-settings.test.tsx@@ -0,0 +1,85 @@+import { QueryClient } from '@tanstack/react-query'+import { screen, waitFor } from '@testing-library/react'+import { beforeEach, expect, it, vi } from 'vitest'++import { admin } from '@/lib/api'+import { renderWithProviders } from '@/test/utils'++import { TimezoneSettings } from './timezone-settings'++vi.mock('@/lib/api', () => ({ admin: { timezone: vi.fn(), updateSetting: vi.fn() } }))++const settings = { timezone: 'UTC', available: ['UTC', 'America/Sao_Paulo'] }++beforeEach(() => {+ vi.clearAllMocks()+ vi.mocked(admin.timezone).mockResolvedValue(settings)+ vi.mocked(admin.updateSetting).mockResolvedValue({ key: 'timezone', value: 'America/Sao_Paulo' })+})++it('lets administrators retry a failed timezone load', async () => {+ vi.mocked(admin.timezone).mockRejectedValueOnce(new Error('Offline'))++ const { user } = renderWithProviders(<TimezoneSettings />)++ await screen.findByRole('alert')+ await user.click(screen.getByRole('button', { name: 'Retry' }))+ expect(await screen.findByLabelText('Application timezone')).toHaveTextContent('UTC')+})++it('refreshes date-sensitive data without invalidating unrelated settings', async () => {+ // First load, then the refetch after saving reports the saved zone.+ vi.mocked(admin.timezone)+ .mockResolvedValueOnce(settings)+ .mockResolvedValue({ ...settings, timezone: 'America/Sao_Paulo' })+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: Infinity } } })+ const affected = [+ ['accounts'],+ ['transactions'],+ ['recurring'],+ ['dashboard'],+ ['reports'],+ ['budgets'],+ ['goals'],+ ['assets'],+ ['asset-values'],+ ['asset-trend'],+ ['portfolio-trend'],+ ['fx-rates'],+ ['invoice', 'invoice-id'],+ ['invoices'],+ ['invoice-summary'],+ ['invoice-facets'],+ ['invoice-document', 'invoice-id'],+ ['reconciliation-suggestions'],+ ['drill-down'],+ ]+ const unrelated = [+ ['admin', 'users'],+ ['admin', 'number-format'],+ ['categories'],+ ['connections', 'providers'],+ ]+ for (const key of [...affected, ...unrelated]) queryClient.setQueryData(key, [])++ const { user } = renderWithProviders(<TimezoneSettings />, { queryClient })+ const select = await screen.findByLabelText('Application timezone')+ expect(select).toHaveAccessibleDescription(/Calendar dates/)+ await user.click(select)+ await user.type(screen.getByPlaceholderText('Search timezone...'), 'sao paulo')+ await user.click(screen.getByRole('option', { name: /America\/Sao_Paulo/ }))+ await user.click(screen.getByRole('button', { name: 'Save' }))++ await waitFor(() => expect(admin.updateSetting).toHaveBeenCalledWith('timezone', 'America/Sao_Paulo'))+ // The field showed the draft before Save was pressed, so that alone proves+ // nothing. Only a finished save clears the draft (Save goes back to+ // disabled) and only the refetch keeps the field on the saved zone.+ await waitFor(() => expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled())+ await waitFor(() => expect(admin.timezone).toHaveBeenCalledTimes(2))+ expect(select).toHaveTextContent('America/Sao_Paulo')+ await waitFor(() => {+ for (const key of affected) expect(queryClient.getQueryState(key)?.isInvalidated).toBe(true)+ })+ for (const key of unrelated) expect(queryClient.getQueryState(key)?.isInvalidated).toBe(false)+ queryClient.clear()+})diff --git a/frontend/src/components/timezone-settings.tsx b/frontend/src/components/timezone-settings.tsxnew file mode 100644index 00000000..fe1349a4--- /dev/null+++ b/frontend/src/components/timezone-settings.tsx@@ -0,0 +1,110 @@+import { useState } from 'react'+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { CalendarClock } from 'lucide-react'+import { useTranslation } from 'react-i18next'+import { toast } from 'sonner'++import { Button } from '@/components/ui/button'+import { Label } from '@/components/ui/label'+import { TimezoneSelect } from '@/components/timezone-select'+import { admin } from '@/lib/api'++const calendarQueryKeys = new Set([+ 'accounts',+ 'transactions',+ 'recurring',+ 'dashboard',+ 'reports',+ 'budgets',+ 'goals',+ 'assets',+ 'asset-values',+ 'asset-trend',+ 'portfolio-trend',+ 'fx-rates',+ 'invoice',+ 'invoices',+ 'invoice-summary',+ 'invoice-facets',+ 'invoice-document',+ 'reconciliation-suggestions',+ 'drill-down',+])++export function TimezoneSettings() {+ const { t } = useTranslation()+ const queryClient = useQueryClient()+ const [draft, setDraft] = useState<string>()+ const timezoneQuery = useQuery({+ queryKey: ['admin', 'timezone'],+ queryFn: admin.timezone,+ })+ const saveTimezone = useMutation({+ mutationFn: (timezone: string) => admin.updateSetting('timezone', timezone),+ onSuccess: (_setting, timezone) => {+ queryClient.setQueryData<{ timezone: string; available: string[] }>(+ ['admin', 'timezone'],+ (current) => current ? { ...current, timezone } : current,+ )+ setDraft(undefined)+ void queryClient.invalidateQueries({ queryKey: ['admin', 'timezone'] })+ void queryClient.invalidateQueries({+ predicate: ({ queryKey }) => calendarQueryKeys.has(String(queryKey[0])),+ })+ toast.success(t('admin.settings.updated'))+ },+ onError: () => toast.error(t('common.error')),+ })++ const currentTimezone = timezoneQuery.data?.timezone+ const selectedTimezone = draft ?? currentTimezone++ return (+ <section className="mb-8 rounded-xl border border-border/60 bg-card overflow-hidden">+ <div className="px-5 py-4 border-b border-border/40">+ <div className="flex items-center gap-2 mb-0.5">+ <CalendarClock size={15} className="text-muted-foreground" />+ <h2 className="text-sm font-semibold text-foreground">+ {t('admin.settings.timezoneTitle')}+ </h2>+ </div>+ </div>+ <div className="p-5 space-y-3">+ <div className="space-y-1">+ <Label htmlFor="application-timezone">{t('admin.settings.timezone')}</Label>+ <p id="application-timezone-help" className="text-sm text-muted-foreground">+ {t('admin.settings.timezoneHelp')}+ </p>+ </div>+ {timezoneQuery.isError ? (+ <div role="alert" className="flex flex-wrap items-center gap-3 text-sm text-destructive">+ <span>{t('common.error')}</span>+ <Button variant="outline" size="sm" onClick={() => timezoneQuery.refetch()}>+ {t('common.retry')}+ </Button>+ </div>+ ) : !timezoneQuery.data ? (+ <p role="status" className="text-sm text-muted-foreground">{t('common.loading')}</p>+ ) : (+ <div className="flex flex-wrap items-center gap-3">+ <TimezoneSelect+ id="application-timezone"+ aria-describedby="application-timezone-help"+ className="h-10 w-80 max-w-full"+ disabled={saveTimezone.isPending}+ value={selectedTimezone ?? ''}+ onChange={setDraft}+ options={timezoneQuery.data.available}+ />+ <Button+ disabled={saveTimezone.isPending || !draft || draft === currentTimezone}+ onClick={() => draft && saveTimezone.mutate(draft)}+ >+ {saveTimezone.isPending ? t('common.loading') : t('common.save')}+ </Button>+ </div>+ )}+ </div>+ </section>+ )+}diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 4339f400..67970077 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -1541,6 +1541,10 @@ export const admin = {const { data } = await api.patch(`/admin/settings/${key}`, { value })return data},+ timezone: async (): Promise<{ timezone: string; available: string[] }> => {+ const { data } = await api.get('/admin/timezone')+ return data+ },registrationStatus: async (): Promise<{ enabled: boolean }> => {const { data } = await api.get('/admin/registration-status')return datadiff --git a/frontend/src/lib/timezone-utils.ts b/frontend/src/lib/timezone-utils.tsnew file mode 100644index 00000000..28d13ca5--- /dev/null+++ b/frontend/src/lib/timezone-utils.ts@@ -0,0 +1,24 @@+/** "GMT-3", "GMT+5:30" or "GMT" for a zone right now, or null when unknown. */+export function timezoneOffsetLabel(name: string, at = new Date()): string | null {+ try {+ const part = new Intl.DateTimeFormat('en-US', { timeZone: name, timeZoneName: 'shortOffset' })+ .formatToParts(at)+ .find((p) => p.type === 'timeZoneName')+ // Runtimes disagree on the zero offset ("GMT" vs "GMT+0"); show one form.+ return part ? part.value.replace(/^GMT[+-]0$/, 'GMT') : null+ } catch {+ return null+ }+}++/** "America/Sao_Paulo" reads as "Sao Paulo" under the "America" heading. */+export function timezoneCityLabel(name: string): string {+ const slash = name.indexOf('/')+ return (slash < 0 ? name : name.slice(slash + 1)).replace(/_/g, ' ')+}++/** The part before the first slash, or an empty string for UTC-style names. */+export function timezoneRegion(name: string): string {+ const slash = name.indexOf('/')+ return slash < 0 ? '' : name.slice(0, slash)+}diff --git a/frontend/src/locales/de.json b/frontend/src/locales/de.jsonindex d4d561b7..3fb7071b 100644--- a/frontend/src/locales/de.json+++ b/frontend/src/locales/de.json@@ -1944,6 +1944,9 @@"anyCountry": "Anderswo"},"common": {+ "selectTimezone": "Zeitzone wählen",+ "searchTimezone": "Zeitzone suchen...",+ "noTimezoneFound": "Keine Zeitzone gefunden.","createNamed": "„{{name}}“ erstellen","view": "Ansehen","add": "Hinzufügen",@@ -2210,6 +2213,9 @@"dateFormatMdyDesc": "Monat zuerst, z.B. 06/04/2026.","dateFormatYmd": "Jahr / Monat / Tag","dateFormatYmdDesc": "ISO-Reihenfolge, z.B. 2026-06-04.",+ "timezoneTitle": "Datum und Uhrzeit",+ "timezone": "Anwendungszeitzone",+ "timezoneHelp": "Kalenderdaten, wiederkehrende Transaktionen, geplante Aufgaben und der KI-Kontext verwenden diese Zeitzone. Änderungen gelten für neue Anfragen und Aufgaben.","updated": "Einstellung aktualisiert"}},diff --git a/frontend/src/locales/el.json b/frontend/src/locales/el.jsonindex dbea9332..255e1896 100644--- a/frontend/src/locales/el.json+++ b/frontend/src/locales/el.json@@ -1943,6 +1943,9 @@"anyCountry": "Οπουδήποτε αλλού"},"common": {+ "selectTimezone": "Επιλογή ζώνης ώρας",+ "searchTimezone": "Αναζήτηση ζώνης ώρας...",+ "noTimezoneFound": "Δεν βρέθηκε ζώνη ώρας.","createNamed": "Δημιουργία «{{name}}»","view": "Προβολή","add": "Προσθήκη",@@ -2209,6 +2212,9 @@"dateFormatMdyDesc": "Πρώτα ο μήνας, π.χ. 06/04/2026.","dateFormatYmd": "Έτος / Μήνας / Ημέρα","dateFormatYmdDesc": "Σειρά κατά ISO, π.χ. 2026-06-04.",+ "timezoneTitle": "Ημερομηνία και ώρα",+ "timezone": "Ζώνη ώρας εφαρμογής",+ "timezoneHelp": "Οι ημερομηνίες, οι επαναλαμβανόμενες συναλλαγές, οι προγραμματισμένες εργασίες και το πλαίσιο της τεχνητής νοημοσύνης χρησιμοποιούν αυτή τη ζώνη ώρας. Οι αλλαγές ισχύουν για νέα αιτήματα και εργασίες.","updated": "Η ρύθμιση ενημερώθηκε"}},diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex 83b422f7..6f766190 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -1943,6 +1943,9 @@"anyCountry": "Anywhere else"},"common": {+ "selectTimezone": "Select timezone",+ "searchTimezone": "Search timezone...",+ "noTimezoneFound": "No timezone found.","createNamed": "Create \"{{name}}\"","view": "View","add": "Add",@@ -2209,6 +2212,9 @@"dateFormatMdyDesc": "Month first, e.g. 06/04/2026.","dateFormatYmd": "Year / Month / Day","dateFormatYmdDesc": "ISO order, e.g. 2026-06-04.",+ "timezoneTitle": "Date and time",+ "timezone": "Application timezone",+ "timezoneHelp": "Calendar dates, recurring transactions, scheduled work and AI context use this timezone. Changes apply to new requests and jobs.","updated": "Setting updated"}},diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.jsonindex 43357281..f0001e61 100644--- a/frontend/src/locales/es.json+++ b/frontend/src/locales/es.json@@ -1944,6 +1944,9 @@"anyCountry": "Cualquier otro lugar"},"common": {+ "selectTimezone": "Seleccionar zona horaria",+ "searchTimezone": "Buscar zona horaria...",+ "noTimezoneFound": "No se encontró ninguna zona horaria.","createNamed": "Crear \"{{name}}\"","view": "Ver","add": "Añadir",@@ -2210,6 +2213,9 @@"dateFormatMdyDesc": "Mes primero, p. ej. 06/04/2026.","dateFormatYmd": "Año / Mes / Día","dateFormatYmdDesc": "Orden ISO, p. ej. 2026-06-04.",+ "timezoneTitle": "Fecha y hora",+ "timezone": "Zona horaria de la aplicación",+ "timezoneHelp": "Las fechas, las transacciones recurrentes, las tareas programadas y el contexto de IA utilizan esta zona horaria. Los cambios se aplican a las nuevas solicitudes y tareas.","updated": "Configuración actualizada"}},diff --git a/frontend/src/locales/fr.json b/frontend/src/locales/fr.jsonindex 23aaca49..08947e07 100644--- a/frontend/src/locales/fr.json+++ b/frontend/src/locales/fr.json@@ -1944,6 +1944,9 @@"anyCountry": "Ailleurs"},"common": {+ "selectTimezone": "Choisir un fuseau horaire",+ "searchTimezone": "Rechercher un fuseau horaire...",+ "noTimezoneFound": "Aucun fuseau horaire trouvé.","createNamed": "Créer « {{name}} »","view": "Voir","add": "Ajouter",@@ -2210,6 +2213,9 @@"dateFormatMdyDesc": "Mois en premier, ex. 06/04/2026.","dateFormatYmd": "Année / Mois / Jour","dateFormatYmdDesc": "Ordre ISO, ex. 2026-06-04.",+ "timezoneTitle": "Date et heure",+ "timezone": "Fuseau horaire de l’application",+ "timezoneHelp": "Les dates, les transactions récurrentes, les tâches planifiées et le contexte de l’IA utilisent ce fuseau horaire. Les changements s’appliquent aux nouvelles requêtes et tâches.","updated": "Paramètre mis à jour"}},diff --git a/frontend/src/locales/hi.json b/frontend/src/locales/hi.jsonindex b11bb4e5..e3c0e998 100644--- a/frontend/src/locales/hi.json+++ b/frontend/src/locales/hi.json@@ -1943,6 +1943,9 @@"anyCountry": "और कहीं भी"},"common": {+ "selectTimezone": "समय क्षेत्र चुनें",+ "searchTimezone": "समय क्षेत्र खोजें...",+ "noTimezoneFound": "कोई समय क्षेत्र नहीं मिला।","createNamed": "\"{{name}}\" बनाएं","view": "देखें","add": "जोड़ें",@@ -2209,6 +2212,9 @@"dateFormatMdyDesc": "महीना पहले, जैसे 06/04/2026।","dateFormatYmd": "वर्ष / महीना / दिन","dateFormatYmdDesc": "ISO क्रम, जैसे 2026-06-04।",+ "timezoneTitle": "दिनांक और समय",+ "timezone": "ऐप्लिकेशन का समय क्षेत्र",+ "timezoneHelp": "तिथियाँ, आवर्ती लेनदेन, निर्धारित कार्य और AI संदर्भ इस समय क्षेत्र का उपयोग करते हैं। बदलाव नए अनुरोधों और कार्यों पर लागू होते हैं।","updated": "सेटिंग अपडेट हुई"}},diff --git a/frontend/src/locales/it.json b/frontend/src/locales/it.jsonindex 5d422de1..dd8ac410 100644--- a/frontend/src/locales/it.json+++ b/frontend/src/locales/it.json@@ -1944,6 +1944,9 @@"anyCountry": "Qualsiasi altro luogo"},"common": {+ "selectTimezone": "Seleziona fuso orario",+ "searchTimezone": "Cerca fuso orario...",+ "noTimezoneFound": "Nessun fuso orario trovato.","createNamed": "Crea \"{{name}}\"","view": "Visualizza","add": "Aggiungi",@@ -2210,6 +2213,9 @@"dateFormatMdyDesc": "Mese prima, es. 06/04/2026.","dateFormatYmd": "Anno / Mese / Giorno","dateFormatYmdDesc": "Ordine ISO, es. 2026-06-04.",+ "timezoneTitle": "Data e ora",+ "timezone": "Fuso orario dell’applicazione",+ "timezoneHelp": "Le date, le transazioni ricorrenti, le attività pianificate e il contesto IA usano questo fuso orario. Le modifiche si applicano alle nuove richieste e attività.","updated": "Impostazione aggiornata"}},diff --git a/frontend/src/locales/ja.json b/frontend/src/locales/ja.jsonindex d17561f4..e672a3c7 100644--- a/frontend/src/locales/ja.json+++ b/frontend/src/locales/ja.json@@ -1943,6 +1943,9 @@"anyCountry": "その他すべての国"},"common": {+ "selectTimezone": "タイムゾーンを選択",+ "searchTimezone": "タイムゾーンを検索...",+ "noTimezoneFound": "タイムゾーンが見つかりません。","createNamed": "「{{name}}」を作成","view": "表示","add": "追加",@@ -2209,6 +2212,9 @@"dateFormatMdyDesc": "月が先。例: 06/04/2026。","dateFormatYmd": "年 / 月 / 日","dateFormatYmdDesc": "ISO順。例: 2026-06-04。",+ "timezoneTitle": "日付と時刻",+ "timezone": "アプリケーションのタイムゾーン",+ "timezoneHelp": "日付、定期取引、スケジュールされたタスク、AIのコンテキストにこのタイムゾーンを使用します。変更は新しいリクエストとジョブに適用されます。","updated": "設定を更新しました"}},diff --git a/frontend/src/locales/nl.json b/frontend/src/locales/nl.jsonindex 46e6b977..234efca2 100644--- a/frontend/src/locales/nl.json+++ b/frontend/src/locales/nl.json@@ -1945,6 +1945,9 @@"anyCountry": "Ergens anders"},"common": {+ "selectTimezone": "Tijdzone kiezen",+ "searchTimezone": "Tijdzone zoeken...",+ "noTimezoneFound": "Geen tijdzone gevonden.","createNamed": "\"{{name}}\" aanmaken","view": "Bekijk","add": "Toevoegen",@@ -2211,6 +2214,9 @@"dateFormatMdyDesc": "Maand eerst, b.v. 06/04/2026.","dateFormatYmd": "Jaar / Maand / Dag","dateFormatYmdDesc": "ISO-volgorde, b.v. 04-06-2026.",+ "timezoneTitle": "Datum en tijd",+ "timezone": "Tijdzone van de applicatie",+ "timezoneHelp": "Datums, terugkerende transacties, geplande taken en de AI-context gebruiken deze tijdzone. Wijzigingen gelden voor nieuwe verzoeken en taken.","updated": "Instelling bijgewerkt"}},diff --git a/frontend/src/locales/pl.json b/frontend/src/locales/pl.jsonindex d1964f87..901ea061 100644--- a/frontend/src/locales/pl.json+++ b/frontend/src/locales/pl.json@@ -2034,6 +2034,9 @@"anyCountry": "Gdziekolwiek indziej"},"common": {+ "selectTimezone": "Wybierz strefę czasową",+ "searchTimezone": "Szukaj strefy czasowej...",+ "noTimezoneFound": "Nie znaleziono strefy czasowej.","createNamed": "Utwórz „{{name}}”","view": "Zobacz","add": "Dodaj",@@ -2309,6 +2312,9 @@"dateFormatMdyDesc": "Najpierw miesiąc, np. 06/04/2026.","dateFormatYmd": "Rok / Miesiąc / Dzień","dateFormatYmdDesc": "Kolejność ISO, np. 2026-06-04.",+ "timezoneTitle": "Data i godzina",+ "timezone": "Strefa czasowa aplikacji",+ "timezoneHelp": "Daty, transakcje cykliczne, zaplanowane zadania i kontekst AI korzystają z tej strefy czasowej. Zmiany dotyczą nowych żądań i zadań.","updated": "Zaktualizowano ustawienie"}},diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex 3a06d637..f57ed4c0 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -1944,6 +1944,9 @@"anyCountry": "Qualquer outro lugar"},"common": {+ "selectTimezone": "Selecionar fuso horário",+ "searchTimezone": "Buscar fuso horário...",+ "noTimezoneFound": "Nenhum fuso horário encontrado.","createNamed": "Criar \"{{name}}\"","view": "Ver","add": "Adicionar",@@ -2210,6 +2213,9 @@"dateFormatMdyDesc": "Mês primeiro, ex.: 06/04/2026.","dateFormatYmd": "Ano / Mês / Dia","dateFormatYmdDesc": "Ordem ISO, ex.: 2026-06-04.",+ "timezoneTitle": "Data e hora",+ "timezone": "Fuso horário do aplicativo",+ "timezoneHelp": "Datas, transações recorrentes, tarefas agendadas e o contexto da IA usam este fuso horário. As alterações valem para novas solicitações e tarefas.","updated": "Configuração atualizada"}},diff --git a/frontend/src/locales/pt-PT.json b/frontend/src/locales/pt-PT.jsonindex 0776f0b3..5527863f 100644--- a/frontend/src/locales/pt-PT.json+++ b/frontend/src/locales/pt-PT.json@@ -1944,6 +1944,9 @@"anyCountry": "Qualquer outro lugar"},"common": {+ "selectTimezone": "Selecionar fuso horário",+ "searchTimezone": "Procurar fuso horário...",+ "noTimezoneFound": "Nenhum fuso horário encontrado.","createNamed": "Criar \"{{name}}\"","view": "Ver","add": "Adicionar",@@ -2210,6 +2213,9 @@"dateFormatMdyDesc": "Mês primeiro, ex.: 06/04/2026.","dateFormatYmd": "Ano / Mês / Dia","dateFormatYmdDesc": "Ordem ISO, ex.: 2026-06-04.",+ "timezoneTitle": "Data e hora",+ "timezone": "Fuso horário da aplicação",+ "timezoneHelp": "Datas, transações recorrentes, tarefas agendadas e o contexto da IA usam este fuso horário. As alterações aplicam-se a novos pedidos e tarefas.","updated": "Configuração atualizada"}},diff --git a/frontend/src/locales/ru.json b/frontend/src/locales/ru.jsonindex 4491b158..1c2e0a96 100644--- a/frontend/src/locales/ru.json+++ b/frontend/src/locales/ru.json@@ -1956,6 +1956,9 @@"anyCountry": "Где-либо ещё"},"common": {+ "selectTimezone": "Выберите часовой пояс",+ "searchTimezone": "Поиск часового пояса...",+ "noTimezoneFound": "Часовой пояс не найден.","createNamed": "Создать «{{name}}»","view": "Просмотр","add": "Добавить",@@ -2222,6 +2225,9 @@"dateFormatMdyDesc": "Сначала месяц, например 06.04.2026.","dateFormatYmd": "Год / Месяц / День","dateFormatYmdDesc": "ISO-порядок, например 2026-06-04.",+ "timezoneTitle": "Дата и время",+ "timezone": "Часовой пояс приложения",+ "timezoneHelp": "Даты, регулярные транзакции, запланированные задачи и контекст ИИ используют этот часовой пояс. Изменения применяются к новым запросам и задачам.","updated": "Настройка обновлена"}},diff --git a/frontend/src/locales/sk.json b/frontend/src/locales/sk.jsonindex 113aad61..29087b9c 100644--- a/frontend/src/locales/sk.json+++ b/frontend/src/locales/sk.json@@ -2063,6 +2063,9 @@"anyCountry": "Kdekoľvek inde"},"common": {+ "selectTimezone": "Vyberte časové pásmo",+ "searchTimezone": "Hľadať časové pásmo...",+ "noTimezoneFound": "Nenašlo sa žiadne časové pásmo.","createNamed": "Vytvoriť „{{name}}“","view": "Zobraziť","add": "Pridať",@@ -2341,6 +2344,9 @@"dateFormatMdyDesc": "Najprv mesiac, napr. 06/04/2026.","dateFormatYmd": "Rok / Mesiac / Deň","dateFormatYmdDesc": "Poradie ISO, napr. 2026-06-04.",+ "timezoneTitle": "Dátum a čas",+ "timezone": "Časové pásmo aplikácie",+ "timezoneHelp": "Dátumy, opakované transakcie, naplánované úlohy a kontext AI používajú toto časové pásmo. Zmeny platia pre nové požiadavky a úlohy.","updated": "Nastavenie aktualizované"}},diff --git a/frontend/src/locales/uk.json b/frontend/src/locales/uk.jsonindex e5ab7d9b..c9d50722 100644--- a/frontend/src/locales/uk.json+++ b/frontend/src/locales/uk.json@@ -1956,6 +1956,9 @@"anyCountry": "Будь-де інде"},"common": {+ "selectTimezone": "Виберіть часовий пояс",+ "searchTimezone": "Пошук часового поясу...",+ "noTimezoneFound": "Часовий пояс не знайдено.","createNamed": "Створити «{{name}}»","view": "Переглянути","add": "Додати",@@ -2222,6 +2225,9 @@"dateFormatMdyDesc": "Спочатку місяць, наприклад 06.04.2026.","dateFormatYmd": "Рік / Місяць / День","dateFormatYmdDesc": "ISO-порядок, наприклад 2026-06-04.",+ "timezoneTitle": "Дата й час",+ "timezone": "Часовий пояс застосунку",+ "timezoneHelp": "Дати, регулярні транзакції, заплановані завдання та контекст ШІ використовують цей часовий пояс. Зміни застосовуються до нових запитів і завдань.","updated": "Налаштування оновлено"}},diff --git a/frontend/src/pages/admin/settings.tsx b/frontend/src/pages/admin/settings.tsxindex c4fe8450..355e4121 100644--- a/frontend/src/pages/admin/settings.tsx+++ b/frontend/src/pages/admin/settings.tsx@@ -29,6 +29,7 @@ import {SelectValue,} from '@/components/ui/select'import { PageHeader } from '@/components/page-header'+import { TimezoneSettings } from '@/components/timezone-settings'import { setThemeBasedOnSystem } from '@/lib/theme-utils'import { useLocalAuthEnabled } from '@/hooks/use-local-auth'import { Search, Plus, Trash2, Shield, ShieldOff, UserCog, Users, Scale, Tag, Palette, Save, Hash, CalendarDays } from 'lucide-react'@@ -369,6 +370,8 @@ export default function AdminSettingsPage() {)}</div>+ <TimezoneSettings />+{/* Theme and Customization Section */}<div className="grid grid-cols-1 gap-6 mb-8"><div className="rounded-xl border border-border/60 bg-card overflow-hidden">