Skip to content

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

feat: keep each workspace on its own timezone (#1010)

Tássio Noronhac36467c8049a
diff --git a/.env.example b/.env.example
index 02954f52..b551a0ee 100644
--- a/.env.example
+++ b/.env.example
@@ -67,6 +67,10 @@ ENABLE_BANKING_APP_ID=
## Optional: the name shown in the browser's passkey prompt.
# WEBAUTHN_RP_NAME=Securo
+# Timezone (optional). Calendar dates follow the timezone saved in Admin
+## Settings; without one, this variable, then the host timezone, then UTC.
+# TZ=America/Sao_Paulo
+
# Host ports (optional) — change these to avoid conflicts with other services
## Default values are set in docker-compose.yml and docker-compose.prod.yml.
## Example:
diff --git a/README.md b/README.md
index 22100294..81dd2370 100644
--- a/README.md
+++ b/README.md
@@ -180,6 +180,10 @@ OPENEXCHANGERATES_APP_ID=your-app-id
Rates are fetched on-demand when foreign-currency transactions are created. Without a key, cross-currency amounts default to a 1:1 fallback rate with a visual warning.
+## Timezone
+
+Balances, budgets, due dates and recurring transactions turn over at midnight in the application timezone. Set it once in Admin Settings → Date and time; a workspace that keeps its books somewhere else can pick its own timezone in Workspace settings. Without a saved value the application follows `TZ` from the environment, then the host timezone, then UTC, so an existing installation keeps behaving as before until someone changes it.
+
## AI Agents (Optional)
Self-hosted AI assistants over your Securo data — multi-provider (OpenAI, Anthropic, Ollama, OpenAI-compatible), tool-use via MCP, per-agent RAG knowledge base, ⌘J global chat panel.
diff --git a/backend/alembic/versions/093_workspace_timezone.py b/backend/alembic/versions/093_workspace_timezone.py
new file mode 100644
index 00000000..b2b0b8ab
--- /dev/null
+++ b/backend/alembic/versions/093_workspace_timezone.py
@@ -0,0 +1,30 @@
+"""letting a workspace keep its own calendar
+
+The application timezone decides which day "today" is for balances,
+budgets, due dates and recurring transactions. One installation can hold
+workspaces whose books are kept in different places, and a person who
+closes the month in Sao Paulo should not see it turn over at Tokyo's
+midnight because another workspace on the same server lives there.
+
+So a workspace can name its own timezone. The column is nullable and
+null means "follow the application timezone", which is exactly what
+every existing workspace did before this migration.
+"""
+import sqlalchemy as sa
+from alembic import op
+
+revision = "093"
+down_revision = "092"
+branch_labels = None
+depends_on = None
+
+
+def upgrade() -> None:
+ op.add_column(
+ "workspaces",
+ sa.Column("timezone", sa.String(length=64), nullable=True),
+ )
+
+
+def downgrade() -> None:
+ op.drop_column("workspaces", "timezone")
diff --git a/backend/app/api/admin.py b/backend/app/api/admin.py
index a1301980..218d2b7f 100644
--- a/backend/app/api/admin.py
+++ b/backend/app/api/admin.py
@@ -1,14 +1,20 @@
import uuid
import re
-from zoneinfo import ZoneInfo, ZoneInfoNotFoundError, available_timezones
-from fastapi import APIRouter, Depends, HTTPException, Query, Request, status
+from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response, status
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.auth import UserManager, current_active_user, current_superuser, get_user_manager
from app.core.auth_policy import require_local_auth_enabled
from app.core.database import get_async_session
-from app.core.app_clock import app_timezone
+from app.core.app_clock import (
+ app_timezone,
+ environment_timezone,
+ invalidate_timezone_cache,
+ is_valid_timezone,
+ saved_timezone_name,
+ timezone_names,
+)
from app.models.user import User
from app.schemas.admin import (
AdminUserCreate,
@@ -137,11 +143,8 @@ 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")
+ if key == "timezone" and not is_valid_timezone(data.value):
+ raise HTTPException(status_code=400, detail="Invalid IANA timezone")
SETTING_VALIDATORS = {
"registration_enabled": {"true", "false"},
"credit_card_accounting_mode": {"cash", "accrual"},
@@ -164,17 +167,39 @@ async def update_setting(
)
setting = await admin_service.set_app_setting(session, key, data.value)
+ if key == "timezone":
+ invalidate_timezone_cache()
return AppSettingRead.model_validate(setting)
[email protected]("/settings/{key}", status_code=status.HTTP_204_NO_CONTENT)
+async def delete_setting(
+ key: str,
+ session: AsyncSession = Depends(get_async_session),
+ _user: User = Depends(current_superuser),
+):
+ """Forget a saved setting so the application falls back to its default."""
+ if key not in ALLOWED_SETTINGS:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail=f"Setting '{key}' is not configurable",
+ )
+ await admin_service.delete_app_setting(session, key)
+ if key == "timezone":
+ invalidate_timezone_cache()
+ return Response(status_code=status.HTTP_204_NO_CONTENT)
+
+
@router.get("/timezone", response_model=TimezoneSettingRead)
async def timezone_setting(
- _session: AsyncSession = Depends(get_async_session),
+ session: AsyncSession = Depends(get_async_session),
_user: User = Depends(current_superuser),
):
return TimezoneSettingRead(
timezone=str(app_timezone()),
- available=sorted(available_timezones()),
+ saved=await saved_timezone_name(session),
+ fallback=str(environment_timezone()),
+ available=sorted(timezone_names()),
)
diff --git a/backend/app/api/timezones.py b/backend/app/api/timezones.py
new file mode 100644
index 00000000..77fd8ef2
--- /dev/null
+++ b/backend/app/api/timezones.py
@@ -0,0 +1,33 @@
+"""The timezones a signed-in person can pick from, and the one in force.
+
+Workspace settings need the list to offer a calendar of its own, and every
+client needs to know which day the server calls today; neither is an
+administrator's concern, so this lives outside the admin router.
+"""
+from fastapi import APIRouter, Depends
+from pydantic import BaseModel
+
+from app.core.app_clock import get_timezone, timezone_names
+from app.core.auth import current_active_user
+from app.core.database import get_async_session
+from app.models.user import User
+from sqlalchemy.ext.asyncio import AsyncSession
+
+router = APIRouter(prefix="/api/timezones", tags=["timezones"])
+
+
+class TimezonesRead(BaseModel):
+ #: The application timezone: what a workspace without its own follows.
+ default: str
+ available: list[str]
+
+
[email protected]("", response_model=TimezonesRead)
+async def list_timezones(
+ session: AsyncSession = Depends(get_async_session),
+ _user: User = Depends(current_active_user),
+):
+ return TimezonesRead(
+ default=str(await get_timezone(session)),
+ available=sorted(timezone_names()),
+ )
diff --git a/backend/app/api/workspaces.py b/backend/app/api/workspaces.py
index ed9f1f50..0af9abf3 100644
--- a/backend/app/api/workspaces.py
+++ b/backend/app/api/workspaces.py
@@ -12,6 +12,7 @@ from fastapi_users import schemas as fu_schemas
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
+from app.core.app_clock import is_valid_timezone
from app.core.auth import current_active_user, get_user_manager, UserManager
from app.core.auth_policy import local_auth_enabled, require_local_auth_enabled
from app.core.database import get_async_session
@@ -144,6 +145,9 @@ async def update_workspace(
if workspace is None:
raise HTTPException(status_code=404, detail="Workspace not found")
updates = body.model_dump(exclude_unset=True)
+ timezone = updates.get("timezone")
+ if timezone is not None and not is_valid_timezone(timezone):
+ raise HTTPException(status_code=400, detail="Invalid IANA timezone")
for key, value in updates.items():
setattr(workspace, key, value)
# Changing the workspace currency follows through to the acting
diff --git a/backend/app/cli.py b/backend/app/cli.py
index 0d845f3d..03409b3a 100644
--- a/backend/app/cli.py
+++ b/backend/app/cli.py
@@ -15,7 +15,7 @@ async def generate_recurring() -> None:
from app.models.user import User as UserModel
from app.services import recurring_transaction_service
- async with async_session_maker() as session, use_timezone(session):
+ async with async_session_maker() as session, use_timezone(session, fresh=True):
result = await session.execute(select(UserModel))
users = result.scalars().all()
total = 0
diff --git a/backend/app/core/app_clock.py b/backend/app/core/app_clock.py
index d051fd4b..fdf18137 100644
--- a/backend/app/core/app_clock.py
+++ b/backend/app/core/app_clock.py
@@ -1,11 +1,29 @@
-"""Application calendar dates; persisted timestamps continue to use UTC."""
+"""Calendar dates for the application; persisted timestamps stay in UTC.
+
+Resolution order for "today":
+
+1. The workspace's own timezone, when the operation runs inside a workspace
+ that set one.
+2. The application timezone saved by an administrator (``app_settings``).
+3. The ``TZ`` environment variable.
+4. The host timezone.
+5. UTC.
+
+Each request, MCP call, CLI run and background job snapshots the timezone
+it starts with, so one operation never mixes two calendars if a setting
+changes while it runs.
+"""
import logging
+import time
+import uuid
from contextlib import asynccontextmanager, contextmanager
from contextvars import ContextVar
from datetime import date, datetime
+from functools import lru_cache
from os import getenv
-from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
+from typing import Optional
+from zoneinfo import ZoneInfo, ZoneInfoNotFoundError, available_timezones
import tzlocal
from sqlalchemy import select
@@ -14,6 +32,38 @@ from sqlalchemy.ext.asyncio import AsyncSession
logger = logging.getLogger(__name__)
_timezone: ContextVar[ZoneInfo | None] = ContextVar("app_timezone", default=None)
+# The saved application timezone is read on every request. It changes a few
+# times in the life of an installation, so a short cache keeps that read off
+# the database while still letting a new value land within seconds; the admin
+# endpoint that writes it drops the cache immediately for its own process.
+_CACHE_TTL_SECONDS = 30.0
+_saved_cache: tuple[float, Optional[str]] | None = None
+
+
+# Files that live next to the zones on some hosts without naming one: the
+# host's own link, the POSIX rules file and tzdata's placeholder zone.
+_NOT_TIMEZONES = frozenset({"localtime", "posixrules", "Factory"})
+
+
+@lru_cache(maxsize=1)
+def timezone_names() -> frozenset[str]:
+ """Every IANA key this host can load, for validation and pickers."""
+ return frozenset(available_timezones()) - _NOT_TIMEZONES
+
+
+def is_valid_timezone(name: str) -> bool:
+ return name in timezone_names()
+
+
+def parse_timezone(name: Optional[str]) -> Optional[ZoneInfo]:
+ """Load a saved timezone name, or None when it is missing or unknown."""
+ if not name:
+ return None
+ try:
+ return ZoneInfo(name)
+ except (ZoneInfoNotFoundError, ValueError):
+ return None
+
def environment_timezone() -> ZoneInfo:
"""Resolve the deployment timezone, falling back safely to UTC."""
@@ -31,29 +81,80 @@ def environment_timezone() -> ZoneInfo:
return ZoneInfo("UTC")
-async def get_timezone(session: AsyncSession) -> ZoneInfo:
- """Resolve the saved application timezone without caching database state."""
+def invalidate_timezone_cache() -> None:
+ """Forget the cached application setting; the next read hits the database."""
+ global _saved_cache
+ _saved_cache = None
+
+
+async def saved_timezone_name(session: AsyncSession, *, fresh: bool = False) -> Optional[str]:
+ """The raw application timezone setting, valid or not, or None when unset.
+
+ ``fresh`` skips the cache. Requests can live with a value up to thirty
+ seconds old, but a job that writes dated rows must not: the process that
+ saved a new value only dropped its own cache, and a worker that captured
+ the old zone could still stamp the old day onto a recurring transaction.
+ """
+ global _saved_cache
+ now = time.monotonic()
+ if not fresh and _saved_cache is not None and _saved_cache[0] > now:
+ return _saved_cache[1]
+
from app.models.app_settings import AppSetting
name = await session.scalar(select(AppSetting.value).where(AppSetting.key == "timezone"))
+ _saved_cache = (now + _CACHE_TTL_SECONDS, name or None)
+ return name or None
+
+
+async def get_timezone(session: AsyncSession, *, fresh: bool = False) -> ZoneInfo:
+ """Resolve the application timezone: the saved setting, else the environment."""
+ name = await saved_timezone_name(session, fresh=fresh)
if name:
- try:
- return ZoneInfo(name)
- except (ZoneInfoNotFoundError, ValueError):
- logger.warning("Saved application timezone is unavailable; using environment timezone")
+ timezone = parse_timezone(name)
+ if timezone is not None:
+ return timezone
+ logger.warning("Saved application timezone is unavailable; using environment timezone")
return environment_timezone()
+async def get_workspace_timezone(session: AsyncSession, workspace_id: uuid.UUID) -> ZoneInfo:
+ """Resolve the timezone one workspace runs on.
+
+ A workspace with its own timezone uses it; any other workspace follows the
+ application timezone captured for the current operation.
+ """
+ from app.models.workspace import Workspace
+
+ name = await session.scalar(select(Workspace.timezone).where(Workspace.id == workspace_id))
+ return workspace_timezone(name)
+
+
+def workspace_timezone(name: Optional[str]) -> ZoneInfo:
+ """Pick between a workspace's saved timezone and the application one."""
+ timezone = parse_timezone(name)
+ if timezone is not None:
+ return timezone
+ if name:
+ logger.warning("Saved workspace timezone is unavailable; using application timezone")
+ return app_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 today's calendar date in the timezone of the current operation."""
return datetime.now(app_timezone()).date()
+def today_in(timezone: ZoneInfo) -> date:
+ """Return today's calendar date in a specific timezone."""
+ return datetime.now(timezone).date()
+
+
@contextmanager
def use_resolved_timezone(timezone: ZoneInfo):
"""Carry an already resolved timezone across one operation."""
@@ -65,7 +166,21 @@ def use_resolved_timezone(timezone: ZoneInfo):
@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)):
- yield
+async def use_timezone(
+ session: AsyncSession,
+ workspace_id: Optional[uuid.UUID] = None,
+ *,
+ fresh: bool = False,
+):
+ """Resolve and snapshot the timezone for one database-backed operation.
+
+ With a workspace, the snapshot is that workspace's timezone; without one,
+ the application timezone. Jobs pass ``fresh`` to read the saved setting
+ rather than a cached copy.
+ """
+ with use_resolved_timezone(await get_timezone(session, fresh=fresh)):
+ if workspace_id is None:
+ yield
+ return
+ with use_resolved_timezone(await get_workspace_timezone(session, workspace_id)):
+ yield
diff --git a/backend/app/core/workspace_context.py b/backend/app/core/workspace_context.py
index 4e98eae8..01265f25 100644
--- a/backend/app/core/workspace_context.py
+++ b/backend/app/core/workspace_context.py
@@ -11,12 +11,14 @@ viewer/editor/owner restrictions; routes that just read use any
membership.
"""
import uuid
+from collections.abc import AsyncIterator
from dataclasses import dataclass
from typing import Optional
from fastapi import Depends, Header, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
+from app.core.app_clock import use_resolved_timezone, workspace_timezone
from app.core.auth import current_active_user
from app.core.database import get_async_session
from app.models.user import User
@@ -70,8 +72,24 @@ async def current_workspace(
x_workspace_id: Optional[str] = Header(default=None, alias="X-Workspace-Id"),
user: User = Depends(current_active_user),
session: AsyncSession = Depends(get_async_session),
+) -> AsyncIterator[WorkspaceContext]:
+ """Dependency: resolve and validate the current workspace + membership.
+
+ The rest of the request then runs on the workspace's calendar: a
+ workspace with a timezone of its own keeps its books there, any other
+ follows the application timezone the session already captured.
+ """
+ ctx = await resolve_workspace(x_workspace_id, user, session)
+ with use_resolved_timezone(workspace_timezone(ctx.workspace.timezone)):
+ yield ctx
+
+
+async def resolve_workspace(
+ x_workspace_id: Optional[str],
+ user: User,
+ session: AsyncSession,
) -> WorkspaceContext:
- """Dependency: resolve and validate the current workspace + membership."""
+ """Resolve the workspace a request addresses, without side effects."""
if x_workspace_id:
try:
ws_uuid = uuid.UUID(x_workspace_id)
diff --git a/backend/app/main.py b/backend/app/main.py
index e0666ee4..de565e0b 100644
--- a/backend/app/main.py
+++ b/backend/app/main.py
@@ -40,6 +40,7 @@ from app.api.invoices import router as invoices_router
from app.api.public_invoices import router as public_invoices_router
from app.api.payees import router as payees_router
from app.api.settings import router as settings_router
+from app.api.timezones import router as timezones_router
from app.api.transactions import router as transactions_router
from app.api.two_factor import router as two_factor_router
from app.api.user_lookup import router as user_lookup_router
@@ -189,6 +190,7 @@ app.include_router(reports_router)
app.include_router(search_router)
app.include_router(setup_router)
app.include_router(currencies_router)
+app.include_router(timezones_router)
app.include_router(fx_rates_router)
app.include_router(export_router)
app.include_router(attachments_router)
diff --git a/backend/app/models/user.py b/backend/app/models/user.py
index 1483f634..ee6e3284 100644
--- a/backend/app/models/user.py
+++ b/backend/app/models/user.py
@@ -38,7 +38,6 @@ class User(SQLAlchemyBaseUserTableUUID, Base):
default=lambda: {
"language": "en",
"date_format": "MM/DD/YYYY",
- "timezone": "UTC",
"currency_display": "USD",
},
)
diff --git a/backend/app/models/workspace.py b/backend/app/models/workspace.py
index a684f37f..8281dda2 100644
--- a/backend/app/models/workspace.py
+++ b/backend/app/models/workspace.py
@@ -67,6 +67,10 @@ class Workspace(Base):
# `default_currency` etc. from here.
default_currency: Mapped[str] = mapped_column(String(3), default="USD", server_default="USD")
locale: Mapped[Optional[str]] = mapped_column(String(10), nullable=True)
+ # The calendar this workspace keeps its books in, as an IANA name. Null
+ # means "follow the application timezone", which is what every workspace
+ # did before the column existed. See `core.app_clock`.
+ timezone: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
# Where this workspace operates fiscally. Selects the jurisdiction pack
# that names and validates fiscal documents, and the axis any future
# threshold or tax date keys on.
diff --git a/backend/app/schemas/admin.py b/backend/app/schemas/admin.py
index 965d09c6..3fb1c4d9 100644
--- a/backend/app/schemas/admin.py
+++ b/backend/app/schemas/admin.py
@@ -47,5 +47,10 @@ class AppSettingUpdate(BaseModel):
class TimezoneSettingRead(BaseModel):
+ #: The timezone in use, after fallbacks.
timezone: str
+ #: What an administrator saved, valid or not; None when nothing is saved.
+ saved: Optional[str] = None
+ #: Where the application lands without a saved value (TZ, host, UTC).
+ fallback: str
available: list[str]
diff --git a/backend/app/schemas/user.py b/backend/app/schemas/user.py
index 619d78a3..3cc3bce2 100644
--- a/backend/app/schemas/user.py
+++ b/backend/app/schemas/user.py
@@ -8,7 +8,6 @@ from pydantic import BaseModel
class UserPreferences(BaseModel):
language: str = "en"
date_format: str = "MM/DD/YYYY"
- timezone: str = "UTC"
currency_display: str = "USD"
onboarding_completed: bool = False
diff --git a/backend/app/schemas/workspace.py b/backend/app/schemas/workspace.py
index 94dba025..1d64377e 100644
--- a/backend/app/schemas/workspace.py
+++ b/backend/app/schemas/workspace.py
@@ -16,6 +16,9 @@ class WorkspaceRead(BaseModel):
is_archived: bool
default_currency: str
locale: Optional[str] = None
+ # The workspace's own calendar, or None to follow the application
+ # timezone. See `core.app_clock`.
+ timezone: Optional[str] = None
# Where the workspace operates fiscally. Never the UI language: see
# `models.workspace.Workspace.tax_jurisdiction`.
tax_jurisdiction: Optional[str] = None
@@ -62,6 +65,9 @@ class WorkspaceUpdate(BaseModel):
color: Optional[str] = Field(default=None, max_length=7)
default_currency: Optional[str] = Field(default=None, min_length=3, max_length=3)
locale: Optional[str] = Field(default=None, max_length=10)
+ # An IANA name to keep this workspace's calendar in, or null to follow
+ # the application timezone again. Validated by the route.
+ timezone: Optional[str] = Field(default=None, max_length=64)
# Editable, unlike `kind`: a business relocates, and every workspace that
# existed before jurisdictions did needs a way to say where it files.
tax_jurisdiction: Optional[str] = Field(default=None, max_length=10)
diff --git a/backend/app/services/admin_service.py b/backend/app/services/admin_service.py
index 8ba5e5e8..1ea3dbae 100644
--- a/backend/app/services/admin_service.py
+++ b/backend/app/services/admin_service.py
@@ -224,6 +224,16 @@ async def get_app_setting(session: AsyncSession, key: str) -> Optional[AppSettin
return result.scalar_one_or_none()
+async def delete_app_setting(session: AsyncSession, key: str) -> bool:
+ """Remove a saved setting. Returns False when nothing was saved."""
+ setting = await get_app_setting(session, key)
+ if setting is None:
+ return False
+ await session.delete(setting)
+ await session.commit()
+ return True
+
+
async def set_app_setting(session: AsyncSession, key: str, value: str) -> AppSetting:
setting = await get_app_setting(session, key)
if setting:
diff --git a/backend/app/services/recurring_transaction_service.py b/backend/app/services/recurring_transaction_service.py
index d3354f5b..406dca53 100644
--- a/backend/app/services/recurring_transaction_service.py
+++ b/backend/app/services/recurring_transaction_service.py
@@ -6,7 +6,7 @@ from typing import Optional
from sqlalchemy import and_, or_, select
from sqlalchemy.ext.asyncio import AsyncSession
-from app.core.app_clock import app_today
+from app.core.app_clock import app_today, get_workspace_timezone, today_in
from app.models.account import Account
from app.models.bank_connection import BankConnection
from app.models.recurring_transaction import RecurringTransaction
@@ -271,7 +271,30 @@ async def generate_pending(
If up_to is None, defaults to today. This allows the dashboard to pre-generate
transactions for future months when the user navigates ahead.
Returns the count of transactions generated."""
- cutoff = up_to or app_today()
+ # A person's recurring rows may live in several workspaces, and each
+ # workspace keeps its own calendar, so "today" is resolved per workspace.
+ # The query is bounded by the latest of those days and the loop below
+ # applies each row's own cutoff.
+ cutoffs: dict[uuid.UUID, date] = {}
+ if up_to is None:
+ workspace_ids = (
+ await session.execute(
+ select(RecurringTransaction.workspace_id)
+ .where(
+ RecurringTransaction.user_id == user_id,
+ RecurringTransaction.is_active == True,
+ RecurringTransaction.auto_generate == True,
+ )
+ .distinct()
+ )
+ ).scalars().all()
+ for ws_id in workspace_ids:
+ cutoffs[ws_id] = today_in(await get_workspace_timezone(session, ws_id))
+ if not cutoffs:
+ return 0
+ latest_cutoff = max(cutoffs.values())
+ else:
+ latest_cutoff = up_to
result = await session.execute(
select(RecurringTransaction)
@@ -282,11 +305,11 @@ async def generate_pending(
or_(
and_(
RecurringTransaction.weekend_adjustment == "previous_friday",
- RecurringTransaction.next_occurrence <= cutoff + timedelta(days=2),
+ RecurringTransaction.next_occurrence <= latest_cutoff + timedelta(days=2),
),
and_(
RecurringTransaction.weekend_adjustment != "previous_friday",
- RecurringTransaction.next_occurrence <= cutoff,
+ RecurringTransaction.next_occurrence <= latest_cutoff,
),
),
)
@@ -300,6 +323,7 @@ async def generate_pending(
# constraint — the user should edit the recurring to fix it.
if recurring.account_id is None:
continue
+ cutoff = up_to or cutoffs.get(recurring.workspace_id) or app_today()
# Generate while the effective date is due. The nominal pointer remains
# authoritative and is the only date used for schedule advancement and
# end-date evaluation.
diff --git a/backend/app/tasks/asset_tasks.py b/backend/app/tasks/asset_tasks.py
index f61b774a..913c7a36 100644
--- a/backend/app/tasks/asset_tasks.py
+++ b/backend/app/tasks/asset_tasks.py
@@ -1,12 +1,19 @@
import asyncio
import logging
+import uuid
from datetime import date, timedelta
from decimal import Decimal
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker
-from app.core.app_clock import app_today, get_timezone, use_resolved_timezone, use_timezone
+from app.core.app_clock import (
+ get_timezone,
+ get_workspace_timezone,
+ today_in,
+ use_resolved_timezone,
+ use_timezone,
+)
from app.worker import celery_app
from app.core.config import get_settings
from app.models.asset import Asset
@@ -49,7 +56,7 @@ async def _apply_growth_rules() -> int:
total = 0
async with session_maker() as session:
- operation_timezone = await get_timezone(session)
+ operation_timezone = await get_timezone(session, fresh=True)
result = await session.execute(
select(Asset).where(
Asset.valuation_method == "growth_rule",
@@ -62,11 +69,18 @@ async def _apply_growth_rules() -> int:
)
assets = list(result.scalars().all())
+ # Each workspace keeps its own calendar, so "today" is resolved per
+ # workspace and remembered for the rest of this run.
+ todays: dict[uuid.UUID, date] = {}
with use_resolved_timezone(operation_timezone):
- today = app_today()
for asset in assets:
try:
async with session_maker() as session:
+ if asset.workspace_id not in todays:
+ todays[asset.workspace_id] = today_in(
+ await get_workspace_timezone(session, asset.workspace_id)
+ )
+ today = todays[asset.workspace_id]
# Get latest value
val_result = await session.execute(
select(AssetValue)
@@ -144,7 +158,7 @@ async def _refresh_market_prices() -> dict[str, int]:
"""
engine, session_maker = _make_session_maker()
try:
- async with session_maker() as session, use_timezone(session):
+ async with session_maker() as session, use_timezone(session, fresh=True):
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.py
index 527a6c72..e1c58225 100644
--- a/backend/app/tasks/fx_backfill_tasks.py
+++ b/backend/app/tasks/fx_backfill_tasks.py
@@ -37,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, use_timezone(session):
+ async with session_maker() as session, use_timezone(session, fresh=True):
# 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.py
index c03628c5..cd9af940 100644
--- a/backend/app/tasks/fx_rate_tasks.py
+++ b/backend/app/tasks/fx_rate_tasks.py
@@ -23,7 +23,7 @@ async def _sync_fx_rates() -> int:
engine, session_maker = _make_session_maker()
try:
- async with session_maker() as session, use_timezone(session):
+ async with session_maker() as session, use_timezone(session, fresh=True):
count = await sync_rates(session)
return count
finally:
@@ -40,7 +40,7 @@ async def _restamp_recurring_fx() -> int:
engine, session_maker = _make_session_maker()
try:
- async with session_maker() as session, use_timezone(session):
+ async with session_maker() as session, use_timezone(session, fresh=True):
users = (await session.execute(select(User))).scalars().all()
count = 0
for user in users:
@@ -86,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, use_timezone(session):
+ async with session_maker() as session, use_timezone(session, fresh=True):
users = {
u.id: u.primary_currency
for u in (await session.execute(select(User))).scalars().all()
diff --git a/backend/app/tasks/recurring_tasks.py b/backend/app/tasks/recurring_tasks.py
index 99d5c39a..9e86b5ff 100644
--- a/backend/app/tasks/recurring_tasks.py
+++ b/backend/app/tasks/recurring_tasks.py
@@ -27,7 +27,7 @@ async def _generate_all() -> int:
total = 0
async with session_maker() as session:
- operation_timezone = await get_timezone(session)
+ operation_timezone = await get_timezone(session, fresh=True)
result = await session.execute(select(User.id))
user_ids = [row[0] for row in result.all()]
diff --git a/backend/app/tasks/sync_tasks.py b/backend/app/tasks/sync_tasks.py
index 01d0d8b3..ef74fdff 100644
--- a/backend/app/tasks/sync_tasks.py
+++ b/backend/app/tasks/sync_tasks.py
@@ -6,7 +6,12 @@ from datetime import datetime, timezone, timedelta
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
-from app.core.app_clock import get_timezone, use_resolved_timezone, use_timezone
+from app.core.app_clock import (
+ get_timezone,
+ get_workspace_timezone,
+ use_resolved_timezone,
+ use_timezone,
+)
from app.worker import celery_app
from app.core.config import get_settings
from app.models.bank_connection import BankConnection
@@ -46,7 +51,7 @@ async def _sync_all() -> int:
synced = 0
async with session_maker() as session:
- operation_timezone = await get_timezone(session)
+ operation_timezone = await get_timezone(session, fresh=True)
result = await session.execute(
select(
BankConnection.id,
@@ -107,13 +112,14 @@ async def _sync_one(
if workspace_id is None:
logger.warning("Connection %s has no workspace; skipping sync", connection_id)
return
- await connection_service.sync_connection(
- session,
- connection_id,
- workspace_id,
- user_id,
- trigger_provider_refresh=trigger_provider_refresh,
- )
+ with use_resolved_timezone(await get_workspace_timezone(session, workspace_id)):
+ await connection_service.sync_connection(
+ session,
+ connection_id,
+ workspace_id,
+ user_id,
+ trigger_provider_refresh=trigger_provider_refresh,
+ )
@celery_app.task(name="app.tasks.sync_tasks.sync_all_connections")
@@ -138,7 +144,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, use_timezone(session):
+ async with session_maker() as session:
conn_uuid = uuid.UUID(connection_id)
workspace_id = await session.scalar(
select(BankConnection.workspace_id).where(BankConnection.id == conn_uuid)
@@ -146,8 +152,9 @@ async def _sync_one_celery(connection_id: str, user_id: str) -> None:
if workspace_id is None:
logger.warning("Connection %s has no workspace; skipping sync", connection_id)
return
- await connection_service.sync_connection(
- session, conn_uuid, workspace_id, uuid.UUID(user_id)
- )
+ async with use_timezone(session, workspace_id, fresh=True):
+ await connection_service.sync_connection(
+ session, conn_uuid, workspace_id, uuid.UUID(user_id)
+ )
finally:
await engine.dispose()
diff --git a/backend/mcp_server/registry.py b/backend/mcp_server/registry.py
index ccdcfe81..8918eb4e 100644
--- a/backend/mcp_server/registry.py
+++ b/backend/mcp_server/registry.py
@@ -80,6 +80,14 @@ async def call_tool(
if spec is None:
raise KeyError(f"unknown tool: {name}")
from app.core.app_clock import use_timezone
-
- async with use_timezone(session):
+ from mcp_server.tools._helpers import resolve_workspace_id
+
+ # A token minted before workspaces existed carries no `ws_id`; the tool
+ # resolves the default workspace itself, and a caller with none at all
+ # still gets the application timezone rather than an error here.
+ try:
+ workspace_id = await resolve_workspace_id(session, ctx)
+ except ValueError:
+ workspace_id = None
+ async with use_timezone(session, workspace_id):
return await spec.handler(session=session, ctx=ctx, **(arguments or {}))
diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py
index 13920fce..a5b86e03 100644
--- a/backend/tests/conftest.py
+++ b/backend/tests/conftest.py
@@ -599,6 +599,16 @@ async def test_user_with_2fa(session: AsyncSession, clean_db) -> User:
return user
[email protected](autouse=True)
+def _fresh_timezone_cache():
+ """One test's saved timezone must never leak into the next through the cache."""
+ from app.core.app_clock import invalidate_timezone_cache
+
+ invalidate_timezone_cache()
+ yield
+ invalidate_timezone_cache()
+
+
@pytest.fixture(autouse=True)
def _mock_redis():
"""Provide a no-op Redis mock so rate limiting never blocks tests."""
diff --git a/backend/tests/test_app_timezone.py b/backend/tests/test_app_timezone.py
index 60068497..9eb5bf6e 100644
--- a/backend/tests/test_app_timezone.py
+++ b/backend/tests/test_app_timezone.py
@@ -15,7 +15,7 @@ class FixedDatetime(datetime):
@pytest.mark.asyncio
async def test_saved_timezone_takes_effect_for_new_operations(session, clean_db):
- from app.core.app_clock import app_today, use_timezone
+ from app.core.app_clock import app_today, invalidate_timezone_cache, use_timezone
setting = AppSetting(key="timezone", value="America/Sao_Paulo")
session.add(setting)
@@ -27,12 +27,33 @@ async def test_saved_timezone_takes_effect_for_new_operations(session, clean_db)
setting.value = "Asia/Tokyo"
await session.commit()
+ # Writing straight to the table bypasses the admin endpoint, which
+ # is what drops the cache; do it by hand like a second process
+ # would see it after the cache expires.
+ invalidate_timezone_cache()
assert app_today().isoformat() == "2026-05-18"
async with use_timezone(session):
assert app_today().isoformat() == "2026-05-19"
+async def test_saved_timezone_is_cached_between_reads(session, clean_db):
+ from app.core.app_clock import get_timezone, invalidate_timezone_cache
+
+ setting = AppSetting(key="timezone", value="America/Sao_Paulo")
+ session.add(setting)
+ await session.commit()
+ assert str(await get_timezone(session)) == "America/Sao_Paulo"
+
+ setting.value = "Asia/Tokyo"
+ await session.commit()
+ assert str(await get_timezone(session)) == "America/Sao_Paulo"
+
+ invalidate_timezone_cache()
+ assert str(await get_timezone(session)) == "Asia/Tokyo"
+
+
@pytest.mark.asyncio
async def test_tz_environment_falls_back_to_system_timezone(session, clean_db, monkeypatch):
from app.core.app_clock import app_today, use_timezone
@@ -50,16 +71,24 @@ async def test_tz_environment_falls_back_to_system_timezone(session, clean_db, m
async def test_invalid_saved_timezone_keeps_repair_endpoint_available(
client, admin_auth_headers, session, monkeypatch, caplog
):
+ from app.core.app_clock import invalidate_timezone_cache
+
monkeypatch.setenv("TZ", "America/Sao_Paulo")
session.add(AppSetting(key="timezone", value="Unavailable/Zone"))
await session.commit()
+ invalidate_timezone_cache()
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"
+ body = response.json()
+ # The endpoint tells the administrator what is saved and what is in use,
+ # so a broken value is visible in the UI and not only in the logs.
+ assert body["timezone"] == "America/Sao_Paulo"
+ assert body["saved"] == "Unavailable/Zone"
+ assert body["fallback"] == "America/Sao_Paulo"
assert "Saved application timezone is unavailable" in caplog.text
response = await client.patch(
@@ -70,6 +99,186 @@ async def test_invalid_saved_timezone_keeps_repair_endpoint_available(
assert response.status_code == 200
+async def test_admin_can_forget_the_saved_timezone(client, admin_auth_headers, monkeypatch):
+ monkeypatch.setenv("TZ", "America/Sao_Paulo")
+ response = await client.patch(
+ "/api/admin/settings/timezone",
+ headers=admin_auth_headers,
+ json={"value": "Asia/Tokyo"},
+ )
+ assert response.status_code == 200
+ response = await client.get("/api/admin/timezone", headers=admin_auth_headers)
+ assert response.json()["saved"] == "Asia/Tokyo"
+ assert response.json()["timezone"] == "Asia/Tokyo"
+
+ response = await client.delete("/api/admin/settings/timezone", headers=admin_auth_headers)
+ assert response.status_code == 204
+ response = await client.get("/api/admin/timezone", headers=admin_auth_headers)
+ assert response.json()["saved"] is None
+ assert response.json()["timezone"] == "America/Sao_Paulo"
+
+ # Only configurable keys can be forgotten, and only by an administrator.
+ response = await client.delete("/api/admin/settings/secret_key", headers=admin_auth_headers)
+ assert response.status_code == 400
+
+
+async def test_names_that_are_files_but_not_timezones_are_rejected(client, admin_auth_headers):
+ # `ZoneInfo("localtime")` loads on many hosts, but it is not a timezone
+ # anyone should pick, and it would never round-trip through the picker.
+ for value in ("localtime", "posixrules", "Factory"):
+ response = await client.patch(
+ "/api/admin/settings/timezone",
+ headers=admin_auth_headers,
+ json={"value": value},
+ )
+ assert response.status_code == 400, value
+
+
+async def test_signed_in_members_can_list_timezones(client, auth_headers, monkeypatch):
+ monkeypatch.setenv("TZ", "America/Sao_Paulo")
+ response = await client.get("/api/timezones", headers=auth_headers)
+ assert response.status_code == 200
+ body = response.json()
+ assert body["default"] == "America/Sao_Paulo"
+ assert "Europe/London" in body["available"]
+ assert "localtime" not in body["available"]
+
+ response = await client.get("/api/timezones")
+ assert response.status_code == 401
+
+
+async def test_workspace_keeps_its_own_calendar(
+ client, auth_headers, session, test_workspace, monkeypatch
+):
+ monkeypatch.setenv("TZ", "America/Sao_Paulo")
+ headers = {**auth_headers, "X-Workspace-Id": str(test_workspace.id)}
+
+ with patch("app.core.app_clock.datetime", FixedDatetime):
+ response = await client.get("/api/dashboard/summary", headers=headers)
+ assert response.status_code == 200
+ assert response.json()["balance_date"] == "2026-05-18"
+
+ response = await client.patch(
+ f"/api/workspaces/{test_workspace.id}",
+ headers=auth_headers,
+ json={"timezone": "Asia/Tokyo"},
+ )
+ assert response.status_code == 200, response.text
+ assert response.json()["timezone"] == "Asia/Tokyo"
+
+ response = await client.get("/api/dashboard/summary", headers=headers)
+ assert response.json()["balance_date"] == "2026-05-19"
+
+ # Null puts the workspace back on the application timezone.
+ response = await client.patch(
+ f"/api/workspaces/{test_workspace.id}",
+ headers=auth_headers,
+ json={"timezone": None},
+ )
+ assert response.status_code == 200, response.text
+ assert response.json()["timezone"] is None
+ response = await client.get("/api/dashboard/summary", headers=headers)
+ assert response.json()["balance_date"] == "2026-05-18"
+
+ response = await client.patch(
+ f"/api/workspaces/{test_workspace.id}",
+ headers=auth_headers,
+ json={"timezone": "Mars/Olympus_Mons"},
+ )
+ assert response.status_code == 400
+
+
+async def test_recurring_generation_follows_each_workspace_calendar(
+ session, test_user, test_workspace, test_account, monkeypatch
+):
+ from decimal import Decimal
+
+ from app.core.app_clock import use_timezone
+ from app.models.account import Account
+ from app.schemas.recurring_transaction import RecurringTransactionCreate
+ from app.services.recurring_transaction_service import (
+ create_recurring_transaction,
+ generate_pending,
+ )
+ from app.services.workspace_service import create_workspace
+
+ monkeypatch.setenv("TZ", "America/Sao_Paulo")
+ tokyo = await create_workspace(
+ session, name="Tokyo books", creator=test_user, self_membership=True
+ )
+ tokyo.timezone = "Asia/Tokyo"
+ tokyo_account = Account(
+ user_id=test_user.id,
+ workspace_id=tokyo.id,
+ name="Tokyo checking",
+ type="checking",
+ balance=Decimal("0"),
+ currency="JPY",
+ )
+ session.add(tokyo_account)
+ await session.commit()
+
+ for workspace, account in ((test_workspace, test_account), (tokyo, tokyo_account)):
+ await create_recurring_transaction(
+ session,
+ workspace.id,
+ test_user.id,
+ RecurringTransactionCreate(
+ description=f"Due on the 19th in {workspace.name}",
+ amount=10,
+ type="debit",
+ frequency="monthly",
+ start_date=date(2026, 5, 19),
+ account_id=account.id,
+ auto_generate=True,
+ ),
+ )
+
+ # 01:00 UTC on May 19 is still May 18 in Sao Paulo and already May 19 in
+ # Tokyo: only the Tokyo workspace's row is due.
+ with patch("app.core.app_clock.datetime", FixedDatetime):
+ async with use_timezone(session):
+ assert await generate_pending(session, test_user.id) == 1
+
+ from sqlalchemy import select
+
+ from app.models.transaction import Transaction
+
+ generated = (await session.execute(select(Transaction.workspace_id))).scalars().all()
+ assert generated == [tokyo.id]
+
+
+async def test_mcp_calls_use_the_workspace_calendar(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"))
+ test_workspace.timezone = "Asia/Tokyo"
+ 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-06-01"
+
+
@pytest.mark.asyncio
async def test_admin_can_set_timezone_and_invalid_names_are_rejected(
client, admin_auth_headers
@@ -174,7 +383,7 @@ async def test_account_service_uses_application_day_for_dates_and_balances(
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.core.app_clock import invalidate_timezone_cache, use_timezone
from app.schemas.recurring_transaction import RecurringTransactionCreate
from app.services.recurring_transaction_service import (
create_recurring_transaction,
@@ -206,6 +415,7 @@ async def test_recurring_generation_waits_until_the_local_due_date(
setting.value = "UTC"
await session.commit()
+ invalidate_timezone_cache()
async with use_timezone(session):
assert await generate_pending(session, test_user.id) == 1
@@ -289,3 +499,58 @@ async def test_mcp_defaults_use_application_month(session, test_user, test_works
)
assert result["month"] == "2026-05-01"
+
+
+async def test_recurring_job_reads_the_saved_timezone_past_a_stale_cache(
+ session, test_user, test_workspace, test_account, monkeypatch
+):
+ """A worker that cached the old zone must not stamp the old day on rows.
+
+ The admin endpoint only drops the cache of the process that handled the
+ save, so the job reads the setting itself instead of trusting the cache.
+ """
+ from types import SimpleNamespace
+ from unittest.mock import AsyncMock
+
+ from sqlalchemy.ext.asyncio import async_sessionmaker
+
+ from app.core.app_clock import get_timezone
+ from app.schemas.recurring_transaction import RecurringTransactionCreate
+ from app.services.recurring_transaction_service import create_recurring_transaction
+ from app.tasks.recurring_tasks import _generate_all
+
+ monkeypatch.setenv("TZ", "UTC")
+ await create_recurring_transaction(
+ session,
+ test_workspace.id,
+ test_user.id,
+ RecurringTransactionCreate(
+ description="Due on the 19th",
+ 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()
+ # This process caches Sao Paulo, where May 19 has not started yet...
+ assert str(await get_timezone(session)) == "America/Sao_Paulo"
+ # ...then another process saves UTC, where it has.
+ setting.value = "UTC"
+ await session.commit()
+ assert str(await get_timezone(session)) == "America/Sao_Paulo"
+
+ maker = async_sessionmaker(session.bind, expire_on_commit=False)
+ with (
+ patch("app.core.app_clock.datetime", FixedDatetime),
+ patch(
+ "app.tasks.recurring_tasks._make_session_maker",
+ return_value=(SimpleNamespace(dispose=AsyncMock()), maker),
+ ),
+ ):
+ assert await _generate_all() == 1
diff --git a/backend/tests/test_write_permission_coverage.py b/backend/tests/test_write_permission_coverage.py
index c387bac5..e933fae0 100644
--- a/backend/tests/test_write_permission_coverage.py
+++ b/backend/tests/test_write_permission_coverage.py
@@ -61,6 +61,7 @@ ALLOWLIST: dict[tuple[str, str], str] = {
("PATCH", "/api/admin/users/{user_id}"): "superuser-gated instance administration",
("DELETE", "/api/admin/users/{user_id}"): "superuser-gated instance administration",
("PATCH", "/api/admin/settings/{key}"): "superuser-gated instance administration",
+ ("DELETE", "/api/admin/settings/{key}"): "superuser-gated instance administration",
# Workspace administration: uses its own, stricter owner floor via
# `require_membership(min_role="owner")` inside the handler. Converting
# these to the write gate would *widen* access, since editors can write.
diff --git a/frontend/src/components/timezone-settings.test.tsx b/frontend/src/components/timezone-settings.test.tsx
index 9f1c8cca..cc0c98c5 100644
--- a/frontend/src/components/timezone-settings.test.tsx
+++ b/frontend/src/components/timezone-settings.test.tsx
@@ -7,14 +7,22 @@ import { renderWithProviders } from '@/test/utils'
import { TimezoneSettings } from './timezone-settings'
-vi.mock('@/lib/api', () => ({ admin: { timezone: vi.fn(), updateSetting: vi.fn() } }))
+vi.mock('@/lib/api', () => ({
+ admin: { timezone: vi.fn(), updateSetting: vi.fn(), deleteSetting: vi.fn() },
+}))
-const settings = { timezone: 'UTC', available: ['UTC', 'America/Sao_Paulo'] }
+const settings = {
+ timezone: 'Etc/UTC',
+ saved: null,
+ fallback: 'Etc/UTC',
+ available: ['Etc/UTC', 'America/Sao_Paulo'],
+}
beforeEach(() => {
vi.clearAllMocks()
vi.mocked(admin.timezone).mockResolvedValue(settings)
vi.mocked(admin.updateSetting).mockResolvedValue({ key: 'timezone', value: 'America/Sao_Paulo' })
+ vi.mocked(admin.deleteSetting).mockResolvedValue(undefined)
})
it('lets administrators retry a failed timezone load', async () => {
@@ -24,14 +32,15 @@ it('lets administrators retry a failed timezone load', async () => {
await screen.findByRole('alert')
await user.click(screen.getByRole('button', { name: 'Retry' }))
- expect(await screen.findByLabelText('Application timezone')).toHaveTextContent('UTC')
+ // Nothing saved reads as the server default, named after where it lands.
+ expect(await screen.findByLabelText('Application timezone')).toHaveTextContent('Server default (Etc/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' })
+ .mockResolvedValue({ ...settings, timezone: 'America/Sao_Paulo', saved: 'America/Sao_Paulo' })
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: Infinity } } })
const affected = [
['accounts'],
@@ -52,6 +61,7 @@ it('refreshes date-sensitive data without invalidating unrelated settings', asyn
['invoice-facets'],
['invoice-document', 'invoice-id'],
['reconciliation-suggestions'],
+ ['timezones'],
['drill-down'],
]
const unrelated = [
@@ -83,3 +93,44 @@ it('refreshes date-sensitive data without invalidating unrelated settings', asyn
for (const key of unrelated) expect(queryClient.getQueryState(key)?.isInvalidated).toBe(false)
queryClient.clear()
})
+
+it('forgets the saved timezone when the server default is chosen', async () => {
+ // First load has a saved zone; the refetch after saving reports it gone.
+ vi.mocked(admin.timezone)
+ .mockResolvedValueOnce({ ...settings, timezone: 'America/Sao_Paulo', saved: 'America/Sao_Paulo' })
+ .mockResolvedValue(settings)
+
+ const { user } = renderWithProviders(<TimezoneSettings />)
+ const select = await screen.findByLabelText('Application timezone')
+ expect(select).toHaveTextContent('America/Sao_Paulo')
+
+ await user.click(select)
+ await user.click(screen.getByRole('option', { name: /Server default/ }))
+ await user.click(screen.getByRole('button', { name: 'Save' }))
+
+ await waitFor(() => expect(admin.deleteSetting).toHaveBeenCalledWith('timezone'))
+ expect(admin.updateSetting).not.toHaveBeenCalled()
+ await waitFor(() => expect(select).toHaveTextContent('Server default (Etc/UTC)'))
+})
+
+it('warns when the saved value is not a timezone the server knows', async () => {
+ vi.mocked(admin.timezone).mockResolvedValue({
+ ...settings,
+ timezone: 'Etc/UTC',
+ saved: 'Mars/Olympus_Mons',
+ })
+
+ const { user } = renderWithProviders(<TimezoneSettings />)
+
+ const warning = await screen.findByRole('alert')
+ expect(warning).toHaveTextContent('Mars/Olympus_Mons')
+ expect(warning).toHaveTextContent('Etc/UTC')
+ // The picker shows the broken value as it is, so choosing the server
+ // default is a real change that clears it.
+ const select = screen.getByLabelText('Application timezone')
+ expect(select).toHaveTextContent('Mars/Olympus_Mons')
+ await user.click(select)
+ await user.click(screen.getByRole('option', { name: /Server default/ }))
+ await user.click(screen.getByRole('button', { name: 'Save' }))
+ await waitFor(() => expect(admin.deleteSetting).toHaveBeenCalledWith('timezone'))
+})
diff --git a/frontend/src/components/timezone-settings.tsx b/frontend/src/components/timezone-settings.tsx
index fe1349a4..afaeef22 100644
--- a/frontend/src/components/timezone-settings.tsx
+++ b/frontend/src/components/timezone-settings.tsx
@@ -1,13 +1,13 @@
import { useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
-import { CalendarClock } from 'lucide-react'
+import { AlertTriangle, 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'
+import { admin, type TimezoneSetting } from '@/lib/api'
const calendarQueryKeys = new Set([
'accounts',
@@ -28,9 +28,13 @@ const calendarQueryKeys = new Set([
'invoice-facets',
'invoice-document',
'reconciliation-suggestions',
+ 'timezones',
'drill-down',
])
+/** The option that means "nothing saved, follow the server". */
+const SERVER_DEFAULT = ''
+
export function TimezoneSettings() {
const { t } = useTranslation()
const queryClient = useQueryClient()
@@ -40,11 +44,20 @@ export function TimezoneSettings() {
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,
+ mutationFn: async (timezone: string) => {
+ if (timezone === SERVER_DEFAULT) await admin.deleteSetting('timezone')
+ else await admin.updateSetting('timezone', timezone)
+ return timezone
+ },
+ onSuccess: (timezone) => {
+ queryClient.setQueryData<TimezoneSetting>(['admin', 'timezone'], (current) =>
+ current
+ ? {
+ ...current,
+ saved: timezone === SERVER_DEFAULT ? null : timezone,
+ timezone: timezone === SERVER_DEFAULT ? current.fallback : timezone,
+ }
+ : current,
)
setDraft(undefined)
void queryClient.invalidateQueries({ queryKey: ['admin', 'timezone'] })
@@ -56,8 +69,14 @@ export function TimezoneSettings() {
onError: () => toast.error(t('common.error')),
})
- const currentTimezone = timezoneQuery.data?.timezone
- const selectedTimezone = draft ?? currentTimezone
+ const setting = timezoneQuery.data
+ // A saved value the server cannot load is shown as what it is, so the
+ // administrator sees the problem here and not only in the logs, and
+ // picking anything else (the server default included) is a real change
+ // that clears it.
+ const savedIsBroken = !!setting?.saved && !setting.available.includes(setting.saved)
+ const currentChoice = setting?.saved ?? SERVER_DEFAULT
+ const selectedChoice = draft ?? currentChoice
return (
<section className="mb-8 rounded-xl border border-border/60 bg-card overflow-hidden">
@@ -83,26 +102,43 @@ export function TimezoneSettings() {
{t('common.retry')}
</Button>
</div>
- ) : !timezoneQuery.data ? (
+ ) : !setting ? (
<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>
+ <>
+ {savedIsBroken && (
+ <div
+ role="alert"
+ className="flex items-start gap-2 rounded-lg border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-sm text-amber-700 dark:text-amber-300"
+ >
+ <AlertTriangle size={15} className="mt-0.5 shrink-0" />
+ <span>
+ {t('admin.settings.timezoneSavedInvalid', {
+ value: setting.saved,
+ zone: setting.timezone,
+ })}
+ </span>
+ </div>
+ )}
+ <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={selectedChoice}
+ onChange={setDraft}
+ options={setting.available}
+ emptyOption={t('admin.settings.timezoneServerDefault', { zone: setting.fallback })}
+ />
+ <Button
+ disabled={saveTimezone.isPending || draft === undefined || draft === currentChoice}
+ onClick={() => draft !== undefined && saveTimezone.mutate(draft)}
+ >
+ {saveTimezone.isPending ? t('common.loading') : t('common.save')}
+ </Button>
+ </div>
+ </>
)}
</div>
</section>
diff --git a/frontend/src/components/transaction-calendar-view.tsx b/frontend/src/components/transaction-calendar-view.tsx
index 4ec98091..f31c2e92 100644
--- a/frontend/src/components/transaction-calendar-view.tsx
+++ b/frontend/src/components/transaction-calendar-view.tsx
@@ -9,7 +9,8 @@ import { CategoryIcon } from '@/components/category-icon'
import { ProjectedTransactionBadge } from '@/components/projected-transaction-badge'
import { getAccountName } from '@/lib/account-utils'
import { activityChartData, dayActivity, isCalendarItemInteractive } from '@/lib/calendar-activity'
-import { weekdayShortLabels } from '@/lib/date-utils'
+import { todayInTimezone, weekdayShortLabels } from '@/lib/date-utils'
+import { useEffectiveTimezone } from '@/hooks/use-timezone'
import { cn } from '@/lib/utils'
import { formatCurrency } from '@/lib/format'
import { shouldShowPendingBadge } from '@/lib/transaction-status'
@@ -35,10 +36,6 @@ function displayDayNumber(date: string) {
return parseLocalDate(date).getDate()
}
-function todayIso() {
- return new Date().toISOString().split('T')[0]
-}
-
// A busy day can hold dozens of rows, and only three fit. Showing the biggest movers
// makes those three worth reading; showing an arbitrary three did not.
function itemSize(item: TransactionCalendarItem) {
@@ -90,6 +87,10 @@ export function TransactionCalendarView({
}) {
const [density, setDensity] = useState<CalendarDensity>(readCalendarDensity)
const [metric, setMetric] = useState<CalendarMetric>(readCalendarMetric)
+ // The server decides which rows are actual and which are projected by its
+ // own idea of today, so the highlighted day has to be the same one.
+ const timeZone = useEffectiveTimezone()
+ const today = todayInTimezone(timeZone)
const accountById = useMemo(() => {
const map = new Map<string, Account>()
@@ -108,11 +109,10 @@ export function TransactionCalendarView({
useEffect(() => {
if (!calendar?.days.length) return
if (selectedDate && calendar.days.some((day) => day.date === selectedDate)) return
- const today = todayIso()
const inCalendarToday = calendar.days.find((day) => day.date === today)
const firstInMonth = calendar.days.find((day) => day.in_month)
onSelectedDateChange((inCalendarToday ?? firstInMonth ?? calendar.days[0]).date)
- }, [calendar, onSelectedDateChange, selectedDate])
+ }, [calendar, onSelectedDateChange, selectedDate, today])
const selectedDay = calendar?.days.find((day) => day.date === selectedDate)
const weekDays = useMemo(() => weekdayShortLabels(dateLocale), [dateLocale])
@@ -183,7 +183,7 @@ export function TransactionCalendarView({
key={day.date}
day={day}
selected={day.date === selectedDate}
- today={day.date === todayIso()}
+ today={day.date === today}
currency={calendar.currency}
locale={locale}
mask={mask}
diff --git a/frontend/src/hooks/use-timezone.ts b/frontend/src/hooks/use-timezone.ts
new file mode 100644
index 00000000..d4105085
--- /dev/null
+++ b/frontend/src/hooks/use-timezone.ts
@@ -0,0 +1,32 @@
+import { useContext } from 'react'
+import { useQuery } from '@tanstack/react-query'
+
+import { WorkspaceContext } from '@/contexts/workspace-context'
+import { timezones as timezonesApi } from '@/lib/api'
+
+/**
+ * The timezones a signed-in person can pick from, plus the application
+ * default a workspace follows when it has none of its own. The list never
+ * changes, but the default can be changed by an administrator in another
+ * browser, so it is refetched after a few minutes rather than kept for the
+ * whole session; saving it here invalidates the query straight away.
+ */
+export function useTimezones() {
+ return useQuery({
+ queryKey: ['timezones'],
+ queryFn: timezonesApi.list,
+ staleTime: 5 * 60 * 1000,
+ })
+}
+
+/**
+ * The timezone the server keeps the active workspace's books in, or undefined
+ * while that is still unknown. Read through the context object directly so a
+ * component rendered outside a WorkspaceProvider (previews, tests) degrades to
+ * "unknown" instead of throwing.
+ */
+export function useEffectiveTimezone(): string | undefined {
+ const workspace = useContext(WorkspaceContext)
+ const { data } = useTimezones()
+ return workspace?.current?.timezone ?? data?.default ?? undefined
+}
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 67970077..e8b3c9b0 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -155,7 +155,7 @@ export const workspaces = {
id: string,
payload: Partial<
Pick<Workspace, 'name' | 'icon' | 'color' | 'default_currency' | 'locale'>
- > & { tax_jurisdiction?: string | null },
+ > & { tax_jurisdiction?: string | null; timezone?: string | null },
): Promise<Workspace> => {
const { data } = await api.patch(`/workspaces/${id}`, payload)
return data
@@ -1513,6 +1513,23 @@ export const backup = {
}
// Admin
+export interface TimezoneSetting {
+ /** The timezone in use, after fallbacks. */
+ timezone: string
+ /** What an administrator saved, valid or not; null when nothing is saved. */
+ saved: string | null
+ /** Where the application lands without a saved value. */
+ fallback: string
+ available: string[]
+}
+
+export const timezones = {
+ list: async (): Promise<{ default: string; available: string[] }> => {
+ const { data } = await api.get('/timezones')
+ return data
+ },
+}
+
export const admin = {
listUsers: async (params?: { search?: string; page?: number; limit?: number }): Promise<AdminUserList> => {
const { data } = await api.get('/admin/users', { params })
@@ -1541,7 +1558,10 @@ export const admin = {
const { data } = await api.patch(`/admin/settings/${key}`, { value })
return data
},
- timezone: async (): Promise<{ timezone: string; available: string[] }> => {
+ deleteSetting: async (key: string): Promise<void> => {
+ await api.delete(`/admin/settings/${key}`)
+ },
+ timezone: async (): Promise<TimezoneSetting> => {
const { data } = await api.get('/admin/timezone')
return data
},
diff --git a/frontend/src/lib/date-utils.test.ts b/frontend/src/lib/date-utils.test.ts
index 4518b3df..1126e222 100644
--- a/frontend/src/lib/date-utils.test.ts
+++ b/frontend/src/lib/date-utils.test.ts
@@ -1,6 +1,21 @@
import { describe, expect, it } from 'vitest'
-import { localDateString, weekdayShortLabels } from './date-utils'
+import { localDateString, todayInTimezone, weekdayShortLabels } from './date-utils'
+
+describe('todayInTimezone', () => {
+ // 01:00 UTC on May 19 is still May 18 in Sao Paulo and already May 19 in Tokyo.
+ const instant = new Date('2026-05-19T01:00:00Z')
+
+ it('returns the calendar day of the given zone', () => {
+ expect(todayInTimezone('America/Sao_Paulo', instant)).toBe('2026-05-18')
+ expect(todayInTimezone('Asia/Tokyo', instant)).toBe('2026-05-19')
+ })
+
+ it('falls back to the browser day without a zone or with an unknown one', () => {
+ expect(todayInTimezone(undefined, instant)).toBe(localDateString(instant))
+ expect(todayInTimezone('Mars/Olympus_Mons', instant)).toBe(localDateString(instant))
+ })
+})
describe('localDateString', () => {
it('formats the browser-local calendar day', () => {
diff --git a/frontend/src/lib/date-utils.ts b/frontend/src/lib/date-utils.ts
index 3c27ecce..4369e080 100644
--- a/frontend/src/lib/date-utils.ts
+++ b/frontend/src/lib/date-utils.ts
@@ -4,6 +4,32 @@ export function localDateString(date = new Date()) {
return format(date, 'yyyy-MM-dd')
}
+// Today as the server sees it. The server keeps each workspace's books in a
+// timezone of its own, so "today" for a balance or a due date is that zone's
+// day, which is not always the browser's. Without a zone (still loading, or a
+// viewer with no workspace) the browser's day is the best guess available.
+// Assembled from the date parts rather than from a locale's string form, so
+// the result is yyyy-MM-dd on every Intl implementation.
+export function todayInTimezone(timeZone?: string | null, now = new Date()) {
+ if (!timeZone) return localDateString(now)
+ try {
+ const parts = new Intl.DateTimeFormat('en-US', {
+ timeZone,
+ year: 'numeric',
+ month: '2-digit',
+ day: '2-digit',
+ }).formatToParts(now)
+ const part = (type: string) => parts.find((p) => p.type === type)?.value
+ const year = part('year')
+ const month = part('month')
+ const day = part('day')
+ if (!year || !month || !day) return localDateString(now)
+ return `${year}-${month}-${day}`
+ } catch {
+ return localDateString(now)
+ }
+}
+
// Short weekday names for a Sunday-start calendar header. The reference week is
// anchored in UTC, so it has to be formatted in UTC as well — otherwise a viewer
// behind UTC reads each instant as the previous day and every label shifts one
diff --git a/frontend/src/locales/de.json b/frontend/src/locales/de.json
index 3fb7071b..e98bc50f 100644
--- a/frontend/src/locales/de.json
+++ b/frontend/src/locales/de.json
@@ -13,6 +13,9 @@
"locale": "Sprache",
"taxJurisdiction": "Steuerjurisdiktion",
"taxJurisdictionHint": "Bestimmt, welche steuerlichen Dokumente dieser Workspace anbietet. Unabhängig von der Sprache der Oberfläche.",
+ "timezone": "Zeitzone",
+ "timezoneDefault": "Anwendungsstandard ({{zone}})",
+ "timezoneHint": "Der Kalender, in dem dieser Workspace seine Bücher führt. Salden, Budgets und Fälligkeiten wechseln dort um Mitternacht.",
"members": "Mitglieder",
"addMember": "Mitglied hinzufügen",
"addMemberTitle": "Mitglied hinzufügen",
@@ -2216,6 +2219,8 @@
"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.",
+ "timezoneServerDefault": "Serverstandard ({{zone}})",
+ "timezoneSavedInvalid": "Der gespeicherte Wert {{value}} ist keine Zeitzone, die dieser Server kennt. Bis zur Änderung wird {{zone}} verwendet.",
"updated": "Einstellung aktualisiert"
}
},
diff --git a/frontend/src/locales/el.json b/frontend/src/locales/el.json
index 255e1896..bff2d9c9 100644
--- a/frontend/src/locales/el.json
+++ b/frontend/src/locales/el.json
@@ -13,6 +13,9 @@
"locale": "Γλώσσα",
"taxJurisdiction": "Φορολογική δικαιοδοσία",
"taxJurisdictionHint": "Καθορίζει ποια φορολογικά έγγραφα προσφέρονται σε αυτόν τον χώρο εργασίας. Ξεχωριστό από τη γλώσσα διεπαφής.",
+ "timezone": "Ζώνη ώρας",
+ "timezoneDefault": "Προεπιλογή εφαρμογής ({{zone}})",
+ "timezoneHint": "Το ημερολόγιο στο οποίο αυτός ο χώρος εργασίας τηρεί τα βιβλία του. Υπόλοιπα, προϋπολογισμοί και προθεσμίες αλλάζουν εκεί τα μεσάνυχτα.",
"members": "Μέλη",
"addMember": "Προσθήκη μέλους",
"addMemberTitle": "Προσθήκη μέλους",
@@ -2215,6 +2218,8 @@
"timezoneTitle": "Ημερομηνία και ώρα",
"timezone": "Ζώνη ώρας εφαρμογής",
"timezoneHelp": "Οι ημερομηνίες, οι επαναλαμβανόμενες συναλλαγές, οι προγραμματισμένες εργασίες και το πλαίσιο της τεχνητής νοημοσύνης χρησιμοποιούν αυτή τη ζώνη ώρας. Οι αλλαγές ισχύουν για νέα αιτήματα και εργασίες.",
+ "timezoneServerDefault": "Προεπιλογή διακομιστή ({{zone}})",
+ "timezoneSavedInvalid": "Η αποθηκευμένη τιμή {{value}} δεν είναι ζώνη ώρας που γνωρίζει αυτός ο διακομιστής. Μέχρι να αλλάξει χρησιμοποιείται η {{zone}}.",
"updated": "Η ρύθμιση ενημερώθηκε"
}
},
diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.json
index 6f766190..e4bef688 100644
--- a/frontend/src/locales/en.json
+++ b/frontend/src/locales/en.json
@@ -13,6 +13,9 @@
"locale": "Language",
"taxJurisdiction": "Tax jurisdiction",
"taxJurisdictionHint": "Decides which fiscal documents this workspace is offered. Separate from the interface language.",
+ "timezone": "Timezone",
+ "timezoneDefault": "Application default ({{zone}})",
+ "timezoneHint": "The calendar this workspace keeps its books in. Balances, budgets and due dates turn over at midnight there.",
"members": "Members",
"addMember": "Add member",
"addMemberTitle": "Add member",
@@ -2215,6 +2218,8 @@
"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.",
+ "timezoneServerDefault": "Server default ({{zone}})",
+ "timezoneSavedInvalid": "The saved value {{value}} is not a timezone this server knows. {{zone}} is in use until it is changed.",
"updated": "Setting updated"
}
},
diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.json
index f0001e61..4ae684a1 100644
--- a/frontend/src/locales/es.json
+++ b/frontend/src/locales/es.json
@@ -13,6 +13,9 @@
"locale": "Idioma",
"taxJurisdiction": "Jurisdicción fiscal",
"taxJurisdictionHint": "Determina qué documentos fiscales ofrece este espacio de trabajo. Independiente del idioma de la interfaz.",
+ "timezone": "Zona horaria",
+ "timezoneDefault": "Predeterminada de la aplicación ({{zone}})",
+ "timezoneHint": "El calendario en el que este workspace lleva sus cuentas. Saldos, presupuestos y vencimientos cambian a medianoche en esa zona.",
"members": "Miembros",
"addMember": "Añadir miembro",
"addMemberTitle": "Añadir miembro",
@@ -2216,6 +2219,8 @@
"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.",
+ "timezoneServerDefault": "Predeterminado del servidor ({{zone}})",
+ "timezoneSavedInvalid": "El valor guardado {{value}} no es una zona horaria que este servidor conozca. Se usa {{zone}} hasta que se cambie.",
"updated": "Configuración actualizada"
}
},
diff --git a/frontend/src/locales/fr.json b/frontend/src/locales/fr.json
index 08947e07..144bf325 100644
--- a/frontend/src/locales/fr.json
+++ b/frontend/src/locales/fr.json
@@ -13,6 +13,9 @@
"locale": "Langue",
"taxJurisdiction": "Juridiction fiscale",
"taxJurisdictionHint": "Détermine les documents fiscaux proposés dans cet espace de travail. Indépendant de la langue de l'interface.",
+ "timezone": "Fuseau horaire",
+ "timezoneDefault": "Valeur par défaut de l'application ({{zone}})",
+ "timezoneHint": "Le calendrier dans lequel ce workspace tient ses comptes. Soldes, budgets et échéances basculent à minuit dans ce fuseau.",
"members": "Membres",
"addMember": "Ajouter un membre",
"addMemberTitle": "Ajouter un membre",
@@ -2216,6 +2219,8 @@
"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.",
+ "timezoneServerDefault": "Valeur par défaut du serveur ({{zone}})",
+ "timezoneSavedInvalid": "La valeur enregistrée {{value}} n'est pas un fuseau horaire connu de ce serveur. {{zone}} est utilisé jusqu'à ce qu'elle soit modifiée.",
"updated": "Paramètre mis à jour"
}
},
diff --git a/frontend/src/locales/hi.json b/frontend/src/locales/hi.json
index e3c0e998..a1437204 100644
--- a/frontend/src/locales/hi.json
+++ b/frontend/src/locales/hi.json
@@ -13,6 +13,9 @@
"locale": "भाषा",
"taxJurisdiction": "कर अधिकार-क्षेत्र",
"taxJurisdictionHint": "तय करता है कि इस वर्कस्पेस को कौन-से वित्तीय दस्तावेज़ मिलते हैं। इंटरफ़ेस की भाषा से अलग।",
+ "timezone": "समय क्षेत्र",
+ "timezoneDefault": "एप्लिकेशन डिफ़ॉल्ट ({{zone}})",
+ "timezoneHint": "वह कैलेंडर जिसमें यह वर्कस्पेस अपने खाते रखता है। शेष राशि, बजट और देय तिथियाँ वहाँ आधी रात को बदलती हैं।",
"members": "सदस्य",
"addMember": "सदस्य जोड़ें",
"addMemberTitle": "सदस्य जोड़ें",
@@ -2215,6 +2218,8 @@
"timezoneTitle": "दिनांक और समय",
"timezone": "ऐप्लिकेशन का समय क्षेत्र",
"timezoneHelp": "तिथियाँ, आवर्ती लेनदेन, निर्धारित कार्य और AI संदर्भ इस समय क्षेत्र का उपयोग करते हैं। बदलाव नए अनुरोधों और कार्यों पर लागू होते हैं।",
+ "timezoneServerDefault": "सर्वर डिफ़ॉल्ट ({{zone}})",
+ "timezoneSavedInvalid": "सहेजा गया मान {{value}} ऐसा समय क्षेत्र नहीं है जिसे यह सर्वर जानता हो। बदले जाने तक {{zone}} उपयोग में है।",
"updated": "सेटिंग अपडेट हुई"
}
},
diff --git a/frontend/src/locales/it.json b/frontend/src/locales/it.json
index dd8ac410..1c6783b2 100644
--- a/frontend/src/locales/it.json
+++ b/frontend/src/locales/it.json
@@ -13,6 +13,9 @@
"locale": "Lingua",
"taxJurisdiction": "Giurisdizione fiscale",
"taxJurisdictionHint": "Determina quali documenti fiscali offre quest'area di lavoro. Indipendente dalla lingua dell'interfaccia.",
+ "timezone": "Fuso orario",
+ "timezoneDefault": "Predefinito dell'applicazione ({{zone}})",
+ "timezoneHint": "Il calendario in cui questo workspace tiene i conti. Saldi, budget e scadenze cambiano a mezzanotte in quel fuso.",
"members": "Membri",
"addMember": "Aggiungi membro",
"addMemberTitle": "Aggiungi membro",
@@ -2216,6 +2219,8 @@
"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à.",
+ "timezoneServerDefault": "Predefinito del server ({{zone}})",
+ "timezoneSavedInvalid": "Il valore salvato {{value}} non è un fuso orario noto a questo server. Viene usato {{zone}} finché non viene modificato.",
"updated": "Impostazione aggiornata"
}
},
diff --git a/frontend/src/locales/ja.json b/frontend/src/locales/ja.json
index e672a3c7..8a86a48f 100644
--- a/frontend/src/locales/ja.json
+++ b/frontend/src/locales/ja.json
@@ -13,6 +13,9 @@
"locale": "言語",
"taxJurisdiction": "税務管轄",
"taxJurisdictionHint": "このワークスペースで提供される会計書類を決定します。UIの言語とは別の設定です。",
+ "timezone": "タイムゾーン",
+ "timezoneDefault": "アプリケーションの既定 ({{zone}})",
+ "timezoneHint": "このワークスペースが帳簿を管理するカレンダーです。残高、予算、支払期日はこのタイムゾーンの深夜に切り替わります。",
"members": "メンバー",
"addMember": "メンバーを追加",
"addMemberTitle": "メンバーを追加",
@@ -2215,6 +2218,8 @@
"timezoneTitle": "日付と時刻",
"timezone": "アプリケーションのタイムゾーン",
"timezoneHelp": "日付、定期取引、スケジュールされたタスク、AIのコンテキストにこのタイムゾーンを使用します。変更は新しいリクエストとジョブに適用されます。",
+ "timezoneServerDefault": "サーバーの既定 ({{zone}})",
+ "timezoneSavedInvalid": "保存された値 {{value}} はこのサーバーが認識するタイムゾーンではありません。変更されるまで {{zone}} が使用されます。",
"updated": "設定を更新しました"
}
},
diff --git a/frontend/src/locales/nl.json b/frontend/src/locales/nl.json
index 234efca2..9d27aeb0 100644
--- a/frontend/src/locales/nl.json
+++ b/frontend/src/locales/nl.json
@@ -13,6 +13,9 @@
"locale": "Taal",
"taxJurisdiction": "Belastingjurisdictie",
"taxJurisdictionHint": "Bepaalt welke fiscale documenten deze workspace wordt aangeboden. Los van de interfacetaal.",
+ "timezone": "Tijdzone",
+ "timezoneDefault": "Standaard van de applicatie ({{zone}})",
+ "timezoneHint": "De kalender waarin deze workspace zijn boeken bijhoudt. Saldi, budgetten en vervaldata wisselen daar om middernacht.",
"members": "Leden",
"addMember": "Lid toevoegen",
"addMemberTitle": "Lid toevoegen",
@@ -2217,6 +2220,8 @@
"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.",
+ "timezoneServerDefault": "Serverstandaard ({{zone}})",
+ "timezoneSavedInvalid": "De opgeslagen waarde {{value}} is geen tijdzone die deze server kent. {{zone}} wordt gebruikt totdat dit wordt gewijzigd.",
"updated": "Instelling bijgewerkt"
}
},
diff --git a/frontend/src/locales/pl.json b/frontend/src/locales/pl.json
index 901ea061..95e05f2c 100644
--- a/frontend/src/locales/pl.json
+++ b/frontend/src/locales/pl.json
@@ -13,6 +13,9 @@
"locale": "Język",
"taxJurisdiction": "Jurysdykcja podatkowa",
"taxJurisdictionHint": "Decyduje, jakie dokumenty podatkowe oferuje ten obszar roboczy. Niezależnie od języka interfejsu.",
+ "timezone": "Strefa czasowa",
+ "timezoneDefault": "Domyślna aplikacji ({{zone}})",
+ "timezoneHint": "Kalendarz, w którym ten workspace prowadzi księgi. Salda, budżety i terminy zmieniają się tam o północy.",
"members": "Członkowie",
"addMember": "Dodaj członka",
"addMemberTitle": "Dodaj członka",
@@ -2315,6 +2318,8 @@
"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ń.",
+ "timezoneServerDefault": "Domyślna serwera ({{zone}})",
+ "timezoneSavedInvalid": "Zapisana wartość {{value}} nie jest strefą czasową znaną temu serwerowi. Do czasu zmiany używana jest {{zone}}.",
"updated": "Zaktualizowano ustawienie"
}
},
diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.json
index f57ed4c0..6acb691e 100644
--- a/frontend/src/locales/pt-BR.json
+++ b/frontend/src/locales/pt-BR.json
@@ -13,6 +13,9 @@
"locale": "Idioma",
"taxJurisdiction": "Jurisdição fiscal",
"taxJurisdictionHint": "Define quais documentos fiscais este workspace oferece. Independente do idioma da interface.",
+ "timezone": "Fuso horário",
+ "timezoneDefault": "Padrão do aplicativo ({{zone}})",
+ "timezoneHint": "O calendário em que este workspace mantém as contas. Saldos, orçamentos e vencimentos viram à meia-noite nesse fuso.",
"members": "Membros",
"addMember": "Adicionar membro",
"addMemberTitle": "Adicionar membro",
@@ -2216,6 +2219,8 @@
"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.",
+ "timezoneServerDefault": "Padrão do servidor ({{zone}})",
+ "timezoneSavedInvalid": "O valor salvo {{value}} não é um fuso horário que este servidor conhece. {{zone}} está em uso até que ele seja alterado.",
"updated": "Configuração atualizada"
}
},
diff --git a/frontend/src/locales/pt-PT.json b/frontend/src/locales/pt-PT.json
index 5527863f..1bff7e42 100644
--- a/frontend/src/locales/pt-PT.json
+++ b/frontend/src/locales/pt-PT.json
@@ -13,6 +13,9 @@
"locale": "Idioma",
"taxJurisdiction": "Jurisdição fiscal",
"taxJurisdictionHint": "Define quais documentos fiscais este espaço de trabalho oferece. Independente do idioma da interface.",
+ "timezone": "Fuso horário",
+ "timezoneDefault": "Predefinição da aplicação ({{zone}})",
+ "timezoneHint": "O calendário em que este workspace mantém as contas. Saldos, orçamentos e vencimentos mudam à meia-noite nesse fuso.",
"members": "Membros",
"addMember": "Adicionar membro",
"addMemberTitle": "Adicionar membro",
@@ -2216,6 +2219,8 @@
"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.",
+ "timezoneServerDefault": "Predefinição do servidor ({{zone}})",
+ "timezoneSavedInvalid": "O valor guardado {{value}} não é um fuso horário que este servidor conhece. {{zone}} está em uso até ser alterado.",
"updated": "Configuração atualizada"
}
},
diff --git a/frontend/src/locales/ru.json b/frontend/src/locales/ru.json
index 1c2e0a96..6894b9ff 100644
--- a/frontend/src/locales/ru.json
+++ b/frontend/src/locales/ru.json
@@ -13,6 +13,9 @@
"locale": "Язык",
"taxJurisdiction": "Налоговая юрисдикция",
"taxJurisdictionHint": "Определяет, какие налоговые документы предлагает это рабочее пространство. Не зависит от языка интерфейса.",
+ "timezone": "Часовой пояс",
+ "timezoneDefault": "По умолчанию в приложении ({{zone}})",
+ "timezoneHint": "Календарь, по которому этот workspace ведёт учёт. Балансы, бюджеты и сроки оплаты сменяются там в полночь.",
"members": "Участники",
"addMember": "Добавить участника",
"addMemberTitle": "Добавить участника",
@@ -2228,6 +2231,8 @@
"timezoneTitle": "Дата и время",
"timezone": "Часовой пояс приложения",
"timezoneHelp": "Даты, регулярные транзакции, запланированные задачи и контекст ИИ используют этот часовой пояс. Изменения применяются к новым запросам и задачам.",
+ "timezoneServerDefault": "По умолчанию на сервере ({{zone}})",
+ "timezoneSavedInvalid": "Сохранённое значение {{value}} не является часовым поясом, известным этому серверу. До изменения используется {{zone}}.",
"updated": "Настройка обновлена"
}
},
diff --git a/frontend/src/locales/sk.json b/frontend/src/locales/sk.json
index 29087b9c..c4deefe2 100644
--- a/frontend/src/locales/sk.json
+++ b/frontend/src/locales/sk.json
@@ -13,6 +13,9 @@
"locale": "Jazyk",
"taxJurisdiction": "Daňová jurisdikcia",
"taxJurisdictionHint": "Určuje, ktoré fiškálne dokumenty sa tomuto pracovnému priestoru ponúkajú. Nesúvisí s jazykom rozhrania.",
+ "timezone": "Časové pásmo",
+ "timezoneDefault": "Predvolené aplikácie ({{zone}})",
+ "timezoneHint": "Kalendár, v ktorom tento workspace vedie účty. Zostatky, rozpočty a splatnosti sa tam menia o polnoci.",
"members": "Členovia",
"addMember": "Pridať člena",
"addMemberTitle": "Pridať člena",
@@ -2347,6 +2350,8 @@
"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.",
+ "timezoneServerDefault": "Predvolené servera ({{zone}})",
+ "timezoneSavedInvalid": "Uložená hodnota {{value}} nie je časové pásmo, ktoré tento server pozná. Kým sa nezmení, používa sa {{zone}}.",
"updated": "Nastavenie aktualizované"
}
},
diff --git a/frontend/src/locales/uk.json b/frontend/src/locales/uk.json
index c9d50722..7ac384a7 100644
--- a/frontend/src/locales/uk.json
+++ b/frontend/src/locales/uk.json
@@ -13,6 +13,9 @@
"locale": "Мова",
"taxJurisdiction": "Податкова юрисдикція",
"taxJurisdictionHint": "Визначає, які податкові документи пропонує цей робочий простір. Не залежить від мови інтерфейсу.",
+ "timezone": "Часовий пояс",
+ "timezoneDefault": "Типово в застосунку ({{zone}})",
+ "timezoneHint": "Календар, за яким цей workspace веде облік. Баланси, бюджети та строки оплати змінюються там опівночі.",
"members": "Учасники",
"addMember": "Додати учасника",
"addMemberTitle": "Додати учасника",
@@ -2228,6 +2231,8 @@
"timezoneTitle": "Дата й час",
"timezone": "Часовий пояс застосунку",
"timezoneHelp": "Дати, регулярні транзакції, заплановані завдання та контекст ШІ використовують цей часовий пояс. Зміни застосовуються до нових запитів і завдань.",
+ "timezoneServerDefault": "Типово на сервері ({{zone}})",
+ "timezoneSavedInvalid": "Збережене значення {{value}} не є часовим поясом, відомим цьому серверу. До зміни використовується {{zone}}.",
"updated": "Налаштування оновлено"
}
},
diff --git a/frontend/src/pages/workspace-settings.tsx b/frontend/src/pages/workspace-settings.tsx
index 038857a3..45d102f7 100644
--- a/frontend/src/pages/workspace-settings.tsx
+++ b/frontend/src/pages/workspace-settings.tsx
@@ -5,6 +5,8 @@ import { useDateLocale } from '@/hooks/use-display-locale'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import { auth as authApi, currencies as currenciesApi, fiscal as fiscalApi, workspaces as workspacesApi } from '@/lib/api'
+import { useTimezones } from '@/hooks/use-timezone'
+import { TimezoneSelect } from '@/components/timezone-select'
import { useAuth } from '@/contexts/auth-context'
import { useWorkspace } from '@/contexts/workspace-context'
import { useLocalAuthEnabled } from '@/hooks/use-local-auth'
@@ -88,6 +90,7 @@ export default function WorkspaceSettingsPage() {
const [editCurrency, setEditCurrency] = useState('')
const [editLocale, setEditLocale] = useState('')
const [editJurisdiction, setEditJurisdiction] = useState('')
+ const [editTimezone, setEditTimezone] = useState('')
const [editIcon, setEditIcon] = useState(DEFAULT_WORKSPACE_ICON)
const [editColor, setEditColor] = useState(DEFAULT_WORKSPACE_COLOR)
const [inviteOpen, setInviteOpen] = useState(false)
@@ -97,7 +100,7 @@ export default function WorkspaceSettingsPage() {
const [removeTarget, setRemoveTarget] = useState<WorkspaceMember | null>(null)
const [archiveOpen, setArchiveOpen] = useState(false)
- const formKey = JSON.stringify([current?.id, current?.name, current?.default_currency, current?.locale, current?.tax_jurisdiction, current?.icon, current?.color])
+ const formKey = JSON.stringify([current?.id, current?.name, current?.default_currency, current?.locale, current?.tax_jurisdiction, current?.timezone, current?.icon, current?.color])
const [previousFormKey, setPreviousFormKey] = useState<string | null>(null)
if (formKey !== previousFormKey) {
setPreviousFormKey(formKey)
@@ -106,6 +109,7 @@ export default function WorkspaceSettingsPage() {
setEditCurrency(current.default_currency)
setEditLocale(current.locale ?? '')
setEditJurisdiction(current.tax_jurisdiction ?? '')
+ setEditTimezone(current.timezone ?? '')
setEditIcon(current.icon ?? DEFAULT_WORKSPACE_ICON)
setEditColor(current.color ?? DEFAULT_WORKSPACE_COLOR)
}
@@ -131,6 +135,10 @@ export default function WorkspaceSettingsPage() {
staleTime: Infinity,
})
+ // Every workspace can keep its own calendar; the default is what the
+ // application runs on when a workspace has none.
+ const { data: timezoneOptions } = useTimezones()
+
const localAuthEnabled = useLocalAuthEnabled()
// The server lists codes; the user reads names. Sorted by the name actually
@@ -157,6 +165,7 @@ export default function WorkspaceSettingsPage() {
default_currency: editCurrency,
locale: editLocale || (null as unknown as string),
tax_jurisdiction: editJurisdiction || null,
+ timezone: editTimezone || null,
icon: editIcon,
color: editColor,
})
@@ -403,7 +412,7 @@ export default function WorkspaceSettingsPage() {
</div>
{/* Region row — currency, language, and where the workspace files */}
- <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
+ <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-4">
<div className="space-y-1.5">
<Label htmlFor="ws-currency" className="text-[13px]">
{t('workspace.defaultCurrency')}
@@ -475,6 +484,23 @@ export default function WorkspaceSettingsPage() {
)}
</p>
</div>
+ <div className="space-y-1.5">
+ <Label htmlFor="ws-timezone" className="text-[13px]">
+ {t('workspace.timezone')}
+ </Label>
+ <TimezoneSelect
+ id="ws-timezone"
+ className="h-10 rounded-lg w-full"
+ value={editTimezone}
+ onChange={setEditTimezone}
+ options={timezoneOptions?.available ?? (editTimezone ? [editTimezone] : [])}
+ emptyOption={t('workspace.timezoneDefault', { zone: timezoneOptions?.default ?? 'UTC' })}
+ disabled={!canManage}
+ />
+ <p className="text-[11px] text-muted-foreground leading-relaxed">
+ {t('workspace.timezoneHint')}
+ </p>
+ </div>
</div>
</div>
</section>
diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts
index 38f49998..26884f4b 100644
--- a/frontend/src/types/index.ts
+++ b/frontend/src/types/index.ts
@@ -56,6 +56,9 @@ export interface Workspace {
is_archived: boolean
default_currency: string
locale: string | null
+ /** The calendar this workspace keeps its books in, or null to follow the
+ * application timezone. */
+ timezone: string | null
/** Where the workspace files. Selects the fiscal document pack; never the
* interface language. */
tax_jurisdiction: string | null
@@ -81,7 +84,6 @@ export interface WorkspaceMember {
export interface UserPreferences {
language?: string
date_format?: string
- timezone?: string
currency_display?: string
display_name?: string
onboarding_completed?: boolean