Open-source personal finance manager. Self-hosted, privacy-first.
feat: global search and transaction filters (#61)
Tássio Noronha48453538361d
diff --git a/backend/app/api/search.py b/backend/app/api/search.pynew file mode 100644index 00000000..064532fb--- /dev/null+++ b/backend/app/api/search.py@@ -0,0 +1,30 @@+from fastapi import APIRouter, Depends, Query+from sqlalchemy.ext.asyncio import AsyncSession++from app.core.auth import current_active_user+from app.core.database import get_async_session+from app.models.user import User+from app.services import search_service++router = APIRouter(prefix="/api/search", tags=["search"])+++async def global_search(+ q: str = Query("", min_length=0, max_length=100),+ limit: int = Query(5, ge=1, le=20),+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ """Global search across transactions, accounts, payees, categories, goals and assets.++ Used by the command palette (Cmd/Ctrl+K). Returns a flat list of+ typed hits limited to ``limit`` results per entity type.+ """+ hits = await search_service.search_all(+ session=session,+ user_id=user.id,+ query=q,+ per_type_limit=limit,+ )+ return {"query": q, "results": hits}diff --git a/backend/app/api/transactions.py b/backend/app/api/transactions.pyindex 83fb0b83..630b4fb9 100644--- a/backend/app/api/transactions.py+++ b/backend/app/api/transactions.py@@ -2,7 +2,7 @@ import csvimport ioimport uuidfrom datetime import date-from typing import Optional+from typing import List, Optionalfrom fastapi import APIRouter, Depends, HTTPException, Query, statusfrom fastapi.responses import StreamingResponse@@ -32,10 +32,24 @@ class PaginatedTransactions(BaseModel):limit: int+def _merge_id_filters(+ single: Optional[uuid.UUID], many: Optional[List[uuid.UUID]]+) -> Optional[List[uuid.UUID]]:+ """Combine the legacy single-id query param with the new list param."""+ ids: list[uuid.UUID] = []+ if many:+ ids.extend(many)+ if single and single not in ids:+ ids.append(single)+ return ids or None++@router.get("", response_model=PaginatedTransactions)async def list_transactions(account_id: Optional[uuid.UUID] = Query(None),+ account_ids: Optional[List[uuid.UUID]] = Query(None),category_id: Optional[uuid.UUID] = Query(None),+ category_ids: Optional[List[uuid.UUID]] = Query(None),payee_id: Optional[uuid.UUID] = Query(None),from_date: Optional[date] = Query(None, alias="from"),to_date: Optional[date] = Query(None, alias="to"),@@ -50,9 +64,12 @@ async def list_transactions(user: User = Depends(current_active_user),):transactions, total = await transaction_service.get_transactions(- session, user.id, account_id, category_id, payee_id, from_date, to_date, page, limit,- include_opening_balance, search=q, uncategorized=uncategorized, txn_type=type,- exclude_transfers=exclude_transfers,+ session, user.id,+ account_ids=_merge_id_filters(account_id, account_ids),+ category_ids=_merge_id_filters(category_id, category_ids),+ payee_id=payee_id, from_date=from_date, to_date=to_date, page=page, limit=limit,+ include_opening_balance=include_opening_balance, search=q, uncategorized=uncategorized,+ txn_type=type, exclude_transfers=exclude_transfers,)primary_currency = user.primary_currencyitems = [_tag_fx_fallback(TransactionRead.model_validate(tx, from_attributes=True), primary_currency) for tx in transactions]@@ -62,7 +79,9 @@ async def list_transactions(@router.get("/export")async def export_transactions(account_id: Optional[uuid.UUID] = Query(None),+ account_ids: Optional[List[uuid.UUID]] = Query(None),category_id: Optional[uuid.UUID] = Query(None),+ category_ids: Optional[List[uuid.UUID]] = Query(None),payee_id: Optional[uuid.UUID] = Query(None),from_date: Optional[date] = Query(None, alias="from"),to_date: Optional[date] = Query(None, alias="to"),@@ -73,7 +92,10 @@ async def export_transactions(user: User = Depends(current_active_user),):transactions, _ = await transaction_service.get_transactions(- session, user.id, account_id, category_id, payee_id, from_date, to_date,+ session, user.id,+ account_ids=_merge_id_filters(account_id, account_ids),+ category_ids=_merge_id_filters(category_id, category_ids),+ payee_id=payee_id, from_date=from_date, to_date=to_date,search=q, uncategorized=uncategorized, txn_type=type, skip_pagination=True,)diff --git a/backend/app/main.py b/backend/app/main.pyindex e1d7da48..c08cd948 100644--- a/backend/app/main.py+++ b/backend/app/main.py@@ -18,6 +18,7 @@ from app.api.recurring_transactions import router as recurring_routerfrom app.api.rules import router as rules_routerfrom app.api.assets import router as assets_routerfrom app.api.reports import router as reports_router+from app.api.search import router as search_routerfrom app.api.setup import router as setup_routerfrom app.api.currencies import router as currencies_routerfrom app.api.export import router as export_router@@ -113,6 +114,7 @@ app.include_router(goals_router)app.include_router(assets_router)app.include_router(dashboard_router)app.include_router(reports_router)+app.include_router(search_router)app.include_router(setup_router)app.include_router(currencies_router)app.include_router(fx_rates_router)diff --git a/backend/app/services/search_service.py b/backend/app/services/search_service.pynew file mode 100644index 00000000..6999f1cf--- /dev/null+++ b/backend/app/services/search_service.py@@ -0,0 +1,237 @@+"""Global search across the user's financial entities.++Implements lightweight case-insensitive ILIKE matching across transactions,+accounts, payees, categories, goals and assets. Designed to power the+command palette (Cmd/Ctrl+K) on the frontend. Kept intentionally simple —+no full-text indexes required — but fast enough for tens of thousands of+rows thanks to per-entity LIMITs and trigger-word scoping.+"""++from __future__ import annotations++import uuid+from dataclasses import dataclass+from decimal import Decimal+from typing import Any, Literal, Optional++from sqlalchemy import or_, select+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.account import Account+from app.models.asset import Asset+from app.models.category import Category+from app.models.goal import Goal+from app.models.payee import Payee+from app.models.transaction import Transaction+++EntityType = Literal[+ "transaction",+ "account",+ "payee",+ "category",+ "goal",+ "asset",+]+++@dataclass+class SearchHit:+ type: EntityType+ id: str+ label: str+ subtitle: Optional[str] = None+ amount: Optional[Decimal] = None+ currency: Optional[str] = None+ date: Optional[str] = None+ icon: Optional[str] = None+ color: Optional[str] = None+ meta: Optional[dict[str, Any]] = None++ def to_dict(self) -> dict[str, Any]:+ return {+ "type": self.type,+ "id": self.id,+ "label": self.label,+ "subtitle": self.subtitle,+ "amount": float(self.amount) if self.amount is not None else None,+ "currency": self.currency,+ "date": self.date,+ "icon": self.icon,+ "color": self.color,+ "meta": self.meta or {},+ }+++def _like(term: str) -> str:+ # Escape SQL LIKE wildcards the user typed, then wrap.+ escaped = term.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")+ return f"%{escaped}%"+++async def search_all(+ session: AsyncSession,+ user_id: uuid.UUID,+ query: str,+ per_type_limit: int = 5,+) -> list[dict[str, Any]]:+ """Search across all entity types for the given user.++ Returns a flat list of hits ordered by entity type, newest first within+ each group. Matching is case-insensitive ILIKE on the most useful string+ columns per model.+ """+ term = (query or "").strip()+ if len(term) < 1:+ return []++ pattern = _like(term)+ hits: list[SearchHit] = []++ # -- Transactions -------------------------------------------------------+ tx_result = await session.execute(+ select(Transaction)+ .where(+ Transaction.user_id == user_id,+ or_(+ Transaction.description.ilike(pattern, escape="\\"),+ Transaction.payee.ilike(pattern, escape="\\"),+ Transaction.notes.ilike(pattern, escape="\\"),+ ),+ )+ .order_by(Transaction.date.desc(), Transaction.created_at.desc())+ .limit(per_type_limit)+ )+ for tx in tx_result.scalars().all():+ hits.append(+ SearchHit(+ type="transaction",+ id=str(tx.id),+ label=tx.description,+ subtitle=tx.payee,+ amount=tx.amount,+ currency=tx.currency,+ date=tx.date.isoformat() if tx.date else None,+ meta={+ "account_id": str(tx.account_id),+ "category_id": str(tx.category_id) if tx.category_id else None,+ "tx_type": tx.type,+ },+ )+ )++ # -- Accounts -----------------------------------------------------------+ acc_result = await session.execute(+ select(Account)+ .where(+ Account.user_id == user_id,+ Account.name.ilike(pattern, escape="\\"),+ )+ .order_by(Account.is_closed.asc(), Account.name.asc())+ .limit(per_type_limit)+ )+ for acc in acc_result.scalars().all():+ hits.append(+ SearchHit(+ type="account",+ id=str(acc.id),+ label=acc.name,+ subtitle=acc.type,+ amount=acc.balance,+ currency=acc.currency,+ meta={"is_closed": acc.is_closed},+ )+ )++ # -- Payees -------------------------------------------------------------+ payee_result = await session.execute(+ select(Payee)+ .where(+ Payee.user_id == user_id,+ or_(+ Payee.name.ilike(pattern, escape="\\"),+ Payee.notes.ilike(pattern, escape="\\"),+ ),+ )+ .order_by(Payee.is_favorite.desc(), Payee.name.asc())+ .limit(per_type_limit)+ )+ for payee in payee_result.scalars().all():+ hits.append(+ SearchHit(+ type="payee",+ id=str(payee.id),+ label=payee.name,+ subtitle=payee.type,+ meta={"is_favorite": payee.is_favorite},+ )+ )++ # -- Categories ---------------------------------------------------------+ cat_result = await session.execute(+ select(Category)+ .where(+ Category.user_id == user_id,+ Category.name.ilike(pattern, escape="\\"),+ )+ .order_by(Category.name.asc())+ .limit(per_type_limit)+ )+ for cat in cat_result.scalars().all():+ hits.append(+ SearchHit(+ type="category",+ id=str(cat.id),+ label=cat.name,+ icon=cat.icon,+ color=cat.color,+ )+ )++ # -- Goals --------------------------------------------------------------+ goal_result = await session.execute(+ select(Goal)+ .where(+ Goal.user_id == user_id,+ Goal.name.ilike(pattern, escape="\\"),+ )+ .order_by(Goal.position.asc(), Goal.name.asc())+ .limit(per_type_limit)+ )+ for goal in goal_result.scalars().all():+ hits.append(+ SearchHit(+ type="goal",+ id=str(goal.id),+ label=goal.name,+ subtitle=goal.status,+ amount=goal.target_amount,+ currency=goal.currency,+ icon=goal.icon,+ color=goal.color,+ )+ )++ # -- Assets -------------------------------------------------------------+ asset_result = await session.execute(+ select(Asset)+ .where(+ Asset.user_id == user_id,+ Asset.name.ilike(pattern, escape="\\"),+ )+ .order_by(Asset.is_archived.asc(), Asset.position.asc(), Asset.name.asc())+ .limit(per_type_limit)+ )+ for asset in asset_result.scalars().all():+ hits.append(+ SearchHit(+ type="asset",+ id=str(asset.id),+ label=asset.name,+ subtitle=asset.type,+ currency=asset.currency,+ meta={"is_archived": asset.is_archived},+ )+ )++ return [hit.to_dict() for hit in hits]diff --git a/backend/app/services/transaction_service.py b/backend/app/services/transaction_service.pyindex c6ffade8..8085c9fa 100644--- a/backend/app/services/transaction_service.py+++ b/backend/app/services/transaction_service.py@@ -58,6 +58,8 @@ async def get_transactions(txn_type: Optional[str] = None,skip_pagination: bool = False,exclude_transfers: bool = False,+ account_ids: Optional[list[uuid.UUID]] = None,+ category_ids: Optional[list[uuid.UUID]] = None,) -> tuple[list[Transaction], int]:# Base query: user's own transactions (manual or via account)base_query = (@@ -79,9 +81,14 @@ async def get_transactions(base_query = base_query.where(Transaction.source != "opening_balance")# Apply filters- if account_id:+ # Multi-id filters take precedence over single-id filters.+ if account_ids:+ base_query = base_query.where(Transaction.account_id.in_(account_ids))+ elif account_id:base_query = base_query.where(Transaction.account_id == account_id)- if category_id:+ if category_ids:+ base_query = base_query.where(Transaction.category_id.in_(category_ids))+ elif category_id:base_query = base_query.where(Transaction.category_id == category_id)if payee_id:base_query = base_query.where(Transaction.payee_id == payee_id)diff --git a/backend/tests/test_search_api.py b/backend/tests/test_search_api.pynew file mode 100644index 00000000..ebe8d8fc--- /dev/null+++ b/backend/tests/test_search_api.py@@ -0,0 +1,212 @@+"""Tests for the global search endpoint powering the command palette."""++import uuid+from datetime import date, datetime, timezone+from decimal import Decimal++import pytest+from httpx import AsyncClient+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.account import Account+from app.models.asset import Asset+from app.models.category import Category+from app.models.goal import Goal+from app.models.payee import Payee+from app.models.transaction import Transaction+from app.models.user import User+++async def _seed(session: AsyncSession, user: User) -> None:+ account = Account(+ id=uuid.uuid4(),+ user_id=user.id,+ name="Nubank Checking",+ type="checking",+ balance=Decimal("1234.56"),+ currency="BRL",+ )+ session.add(account)++ payee = Payee(+ id=uuid.uuid4(),+ user_id=user.id,+ name="Padaria Boulangerie",+ type="merchant",+ created_at=datetime.now(timezone.utc),+ )+ session.add(payee)++ category = Category(+ id=uuid.uuid4(),+ user_id=user.id,+ name="Groceries",+ icon="shopping-cart",+ color="#10B981",+ )+ session.add(category)+ await session.flush()++ session.add(+ Transaction(+ id=uuid.uuid4(),+ user_id=user.id,+ account_id=account.id,+ description="Coffee at Padaria",+ amount=Decimal("4.50"),+ date=date.today(),+ type="debit",+ source="manual",+ payee_id=payee.id,+ payee="Padaria Boulangerie",+ currency="BRL",+ created_at=datetime.now(timezone.utc),+ )+ )++ session.add(+ Goal(+ id=uuid.uuid4(),+ user_id=user.id,+ name="Trip to Lisbon",+ target_amount=Decimal("5000"),+ current_amount=Decimal("1000"),+ currency="EUR",+ status="active",+ )+ )++ session.add(+ Asset(+ id=uuid.uuid4(),+ user_id=user.id,+ name="Peugeot 208",+ type="vehicle",+ currency="EUR",+ )+ )++ await session.commit()+++async def test_search_returns_all_entity_types(+ client: AsyncClient, auth_headers: dict, session: AsyncSession, test_user: User+) -> None:+ await _seed(session, test_user)++ resp = await client.get("/api/search?q=a", headers=auth_headers)+ assert resp.status_code == 200+ data = resp.json()+ assert "results" in data+ types = {hit["type"] for hit in data["results"]}+ # The seeded fixtures should match multiple entity types on the letter "a"+ assert "transaction" in types or "payee" in types or "account" in types+++async def test_search_matches_transaction_description(+ client: AsyncClient, auth_headers: dict, session: AsyncSession, test_user: User+) -> None:+ await _seed(session, test_user)++ resp = await client.get("/api/search?q=coffee", headers=auth_headers)+ assert resp.status_code == 200+ hits = resp.json()["results"]+ tx_hits = [h for h in hits if h["type"] == "transaction"]+ assert any("Coffee" in h["label"] for h in tx_hits)+++async def test_search_matches_payee(+ client: AsyncClient, auth_headers: dict, session: AsyncSession, test_user: User+) -> None:+ await _seed(session, test_user)++ resp = await client.get("/api/search?q=boulang", headers=auth_headers)+ assert resp.status_code == 200+ hits = resp.json()["results"]+ payee_hits = [h for h in hits if h["type"] == "payee"]+ assert len(payee_hits) == 1+ assert payee_hits[0]["label"] == "Padaria Boulangerie"+++async def test_search_matches_account(+ client: AsyncClient, auth_headers: dict, session: AsyncSession, test_user: User+) -> None:+ await _seed(session, test_user)++ resp = await client.get("/api/search?q=nubank", headers=auth_headers)+ assert resp.status_code == 200+ hits = resp.json()["results"]+ acc_hits = [h for h in hits if h["type"] == "account"]+ assert len(acc_hits) == 1+ assert acc_hits[0]["label"] == "Nubank Checking"+++async def test_search_matches_goal_and_asset(+ client: AsyncClient, auth_headers: dict, session: AsyncSession, test_user: User+) -> None:+ await _seed(session, test_user)++ resp = await client.get("/api/search?q=lisbon", headers=auth_headers)+ assert resp.status_code == 200+ assert any(h["type"] == "goal" for h in resp.json()["results"])++ resp = await client.get("/api/search?q=peugeot", headers=auth_headers)+ assert resp.status_code == 200+ assert any(h["type"] == "asset" for h in resp.json()["results"])+++async def test_search_empty_query_returns_empty(+ client: AsyncClient, auth_headers: dict+) -> None:+ resp = await client.get("/api/search?q=", headers=auth_headers)+ assert resp.status_code == 200+ assert resp.json()["results"] == []+++async def test_search_respects_user_scope(+ client: AsyncClient, auth_headers: dict, session: AsyncSession, test_user: User+) -> None:+ # Create an account owned by a different user — should NOT appear in results.+ other_user_id = uuid.uuid4()+ other_account = Account(+ id=uuid.uuid4(),+ user_id=other_user_id,+ name="Other User Secret Account",+ type="checking",+ balance=Decimal("0"),+ currency="USD",+ )+ session.add(other_account)+ await session.commit()++ resp = await client.get("/api/search?q=secret", headers=auth_headers)+ assert resp.status_code == 200+ assert resp.json()["results"] == []+++async def test_search_escapes_like_wildcards(+ client: AsyncClient, auth_headers: dict, session: AsyncSession, test_user: User+) -> None:+ # A literal % should not be treated as a wildcard.+ payee = Payee(+ id=uuid.uuid4(),+ user_id=test_user.id,+ name="Discount 50% Store",+ type="merchant",+ created_at=datetime.now(timezone.utc),+ )+ session.add(payee)+ await session.commit()++ resp = await client.get("/api/search?q=50%25", headers=auth_headers)+ assert resp.status_code == 200+ payee_hits = [h for h in resp.json()["results"] if h["type"] == "payee"]+ assert any("50%" in h["label"] for h in payee_hits)diff --git a/backend/tests/test_transactions_api.py b/backend/tests/test_transactions_api.pyindex c83aa8aa..8e13c683 100644--- a/backend/tests/test_transactions_api.py+++ b/backend/tests/test_transactions_api.py@@ -67,6 +67,173 @@ async def test_list_transactions_filter_by_category(assert data["total"] == 1 # only IFOOD+async def test_list_transactions_filter_by_category_ids_multi(+ client: AsyncClient, auth_headers, test_transactions: list[Transaction],+ test_categories: list[Category],+):+ """Passing multiple ``category_ids`` should return the union of matches."""+ alimentacao = test_categories[0].id # IFOOD+ transporte = test_categories[1].id # UBER+ response = await client.get(+ f"/api/transactions?category_ids={alimentacao}&category_ids={transporte}",+ headers=auth_headers,+ )+ assert response.status_code == 200+ data = response.json()+ assert data["total"] == 2+ descriptions = {item["description"] for item in data["items"]}+ assert descriptions == {"UBER TRIP", "IFOOD RESTAURANTE"}+++async def test_list_transactions_filter_by_category_ids_single_element(+ client: AsyncClient, auth_headers, test_transactions: list[Transaction],+ test_categories: list[Category],+):+ """A one-element ``category_ids`` list should behave like the legacy single filter."""+ cat_id = test_categories[0].id # Alimentação+ response = await client.get(+ f"/api/transactions?category_ids={cat_id}", headers=auth_headers+ )+ assert response.status_code == 200+ data = response.json()+ assert data["total"] == 1+ assert data["items"][0]["description"] == "IFOOD RESTAURANTE"+++async def test_list_transactions_merge_category_id_and_category_ids(+ client: AsyncClient, auth_headers, test_transactions: list[Transaction],+ test_categories: list[Category],+):+ """When both the legacy ``category_id`` and the new ``category_ids`` are sent,+ results should be the union of both."""+ alimentacao = test_categories[0].id+ transporte = test_categories[1].id+ response = await client.get(+ f"/api/transactions?category_id={alimentacao}&category_ids={transporte}",+ headers=auth_headers,+ )+ assert response.status_code == 200+ data = response.json()+ assert data["total"] == 2+ descriptions = {item["description"] for item in data["items"]}+ assert descriptions == {"UBER TRIP", "IFOOD RESTAURANTE"}+++async def test_list_transactions_filter_by_category_ids_no_match(+ client: AsyncClient, auth_headers, test_transactions: list[Transaction],+):+ """A non-existent ``category_ids`` filter should return zero rows, not leak other txns."""+ ghost_id = uuid.uuid4()+ response = await client.get(+ f"/api/transactions?category_ids={ghost_id}", headers=auth_headers+ )+ assert response.status_code == 200+ data = response.json()+ assert data["total"] == 0+ assert data["items"] == []+++async def test_list_transactions_filter_by_account_ids_multi(+ client: AsyncClient,+ auth_headers,+ session: AsyncSession,+ test_user: User,+ test_account: Account,+ test_transactions: list[Transaction],+):+ """Passing multiple ``account_ids`` should include transactions from every account."""+ # Create a second account under the same user with one transaction.+ second_account = Account(+ id=uuid.uuid4(),+ user_id=test_user.id,+ connection_id=None,+ external_id="acc-ext-second",+ name="Poupança",+ type="savings",+ balance=Decimal("500.00"),+ currency="BRL",+ )+ session.add(second_account)+ await session.flush()+ extra_txn = Transaction(+ id=uuid.uuid4(),+ user_id=test_user.id,+ account_id=second_account.id,+ category_id=None,+ description="APORTE POUPANCA",+ amount=Decimal("100.00"),+ date=date.today(),+ type="credit",+ source="manual",+ created_at=datetime.now(timezone.utc),+ )+ session.add(extra_txn)+ await session.commit()++ response = await client.get(+ f"/api/transactions?account_ids={test_account.id}&account_ids={second_account.id}",+ headers=auth_headers,+ )+ assert response.status_code == 200+ data = response.json()+ # 5 from test_account + 1 from second_account+ assert data["total"] == 6+ account_ids_in_response = {item["account_id"] for item in data["items"]}+ assert str(test_account.id) in account_ids_in_response+ assert str(second_account.id) in account_ids_in_response+++async def test_list_transactions_filter_by_account_ids_isolates_other_accounts(+ client: AsyncClient,+ auth_headers,+ session: AsyncSession,+ test_user: User,+ test_account: Account,+ test_transactions: list[Transaction],+):+ """``account_ids`` should exclude txns from accounts not in the list."""+ second_account = Account(+ id=uuid.uuid4(),+ user_id=test_user.id,+ connection_id=None,+ external_id="acc-ext-isolated",+ name="Isolada",+ type="savings",+ balance=Decimal("0"),+ currency="BRL",+ )+ session.add(second_account)+ await session.flush()+ isolated_txn = Transaction(+ id=uuid.uuid4(),+ user_id=test_user.id,+ account_id=second_account.id,+ category_id=None,+ description="ISOLATED TXN",+ amount=Decimal("10.00"),+ date=date.today(),+ type="debit",+ source="manual",+ created_at=datetime.now(timezone.utc),+ )+ session.add(isolated_txn)+ await session.commit()++ response = await client.get(+ f"/api/transactions?account_ids={second_account.id}", headers=auth_headers+ )+ assert response.status_code == 200+ data = response.json()+ assert data["total"] == 1+ assert data["items"][0]["description"] == "ISOLATED TXN"++@pytest.mark.asyncioasync def test_list_transactions_filter_by_date(client: AsyncClient, auth_headers, test_transactions: list[Transaction]diff --git a/frontend/package-lock.json b/frontend/package-lock.jsonindex c9d00dc8..2178dc66 100644--- a/frontend/package-lock.json+++ b/frontend/package-lock.json@@ -13,6 +13,7 @@"axios": "^1.13.5","class-variance-authority": "^0.7.1","clsx": "^2.1.1",+ "cmdk": "^1.1.1","date-fns": "^4.1.0","i18next": "^25.8.13","i18next-browser-languagedetector": "^8.2.1",@@ -5355,6 +5356,22 @@"node": ">=6"}},+ "node_modules/cmdk": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/cmdk/-/cmdk-1.1.1.tgz",+ "integrity": "sha512-Vsv7kFaXm+ptHDMZ7izaRsP70GgrW9NBNGswt9OZaVBLlE0SNpDq8eu/VGXyF9r7M0azK3Wy7OlYXsuyYLFzHg==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-compose-refs": "^1.1.1",+ "@radix-ui/react-dialog": "^1.1.6",+ "@radix-ui/react-id": "^1.1.0",+ "@radix-ui/react-primitive": "^2.0.2"+ },+ "peerDependencies": {+ "react": "^18 || ^19 || ^19.0.0-rc",+ "react-dom": "^18 || ^19 || ^19.0.0-rc"+ }+ },"node_modules/code-block-writer": {"version": "13.0.3","resolved": "https://registry.npmjs.org/code-block-writer/-/code-block-writer-13.0.3.tgz",diff --git a/frontend/package.json b/frontend/package.jsonindex 2b1ad796..9342cdaf 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -16,6 +16,7 @@"axios": "^1.13.5","class-variance-authority": "^0.7.1","clsx": "^2.1.1",+ "cmdk": "^1.1.1","date-fns": "^4.1.0","i18next": "^25.8.13","i18next-browser-languagedetector": "^8.2.1",diff --git a/frontend/src/components/app-layout.tsx b/frontend/src/components/app-layout.tsxindex 7611ec52..71fb5822 100644--- a/frontend/src/components/app-layout.tsx+++ b/frontend/src/components/app-layout.tsx@@ -14,7 +14,12 @@ import {DropdownMenu,DropdownMenuContent,DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuPortal,DropdownMenuSeparator,+ DropdownMenuSub,+ DropdownMenuSubContent,+ DropdownMenuSubTrigger,DropdownMenuTrigger,} from '@/components/ui/dropdown-menu'import { cn } from '@/lib/utils'@@ -39,7 +44,9 @@ import {BarChart3,Sun,Moon,+ Languages,KeyRound,+ Check,HardDriveDownload,Shield,ShieldCheck,@@ -47,6 +54,9 @@ import {import { usePrivacyMode } from '@/hooks/use-privacy-mode'import { ChangePasswordDialog } from '@/components/change-password-dialog'import { TwoFactorSetup } from '@/components/two-factor-setup'+import { CommandPalette } from '@/components/command-palette'+import { useCommandPaletteHotkey } from '@/hooks/use-command-palette-hotkey'+import { Search } from 'lucide-react'type NavItem =| { type: 'link'; key: string; path: string; icon: React.ElementType }@@ -89,6 +99,9 @@ export function AppLayout() {const [changePasswordOpen, setChangePasswordOpen] = useState(false)const [twoFactorOpen, setTwoFactorOpen] = useState(false)const [backingUp, setBackingUp] = useState(false)+ const [paletteOpen, setPaletteOpen] = useState(false)+ useCommandPaletteHotkey(setPaletteOpen)+ const isMac = typeof navigator !== 'undefined' && /Mac|iPhone|iPad|iPod/.test(navigator.platform)const showTour = user && !user.preferences?.onboarding_completed && !localStorage.getItem('onboarding_completed')@@ -105,6 +118,12 @@ export function AppLayout() {const userInitial = user?.email?.charAt(0).toUpperCase() ?? '?'const currentLang = i18n.language+ const resolvedTheme = theme === 'system' ? undefined : theme+ const isDark = resolvedTheme+ ? resolvedTheme === 'dark'+ : typeof window !== 'undefined' &&+ window.matchMedia?.('(prefers-color-scheme: dark)').matches+ const toggleTheme = () => setTheme(isDark ? 'light' : 'dark')const { data: accountsList } = useQuery({queryKey: ['accounts'],@@ -132,6 +151,14 @@ export function AppLayout() {<span className="font-bold text-sidebar-foreground">{t('app.name')}</span></div><div className="ml-auto flex items-center gap-2">+ <button+ onClick={() => setPaletteOpen(true)}+ className="text-sidebar-muted hover:text-sidebar-foreground transition-colors p-1"+ title={t('cmdk.triggerAria')}+ aria-label={t('cmdk.triggerAria')}+ >+ <Search size={18} />+ </button><buttononClick={togglePrivacyMode}className="text-sidebar-muted hover:text-sidebar-foreground transition-colors p-1"@@ -139,6 +166,14 @@ export function AppLayout() {>{privacyMode ? <EyeOff size={18} /> : <Eye size={18} />}</button>+ <button+ onClick={toggleTheme}+ className="text-sidebar-muted hover:text-sidebar-foreground transition-colors p-1"+ title={isDark ? t('settings.themeLight') : t('settings.themeDark')}+ aria-label={isDark ? t('settings.themeLight') : t('settings.themeDark')}+ >+ {isDark ? <Sun size={18} /> : <Moon size={18} />}+ </button><UserMenu userInitial={userInitial} logout={logout} onChangePassword={() => setChangePasswordOpen(true)} onTwoFactor={() => setTwoFactorOpen(true)} backingUp={backingUp} onBackup={async () => {setBackingUp(true)try {@@ -175,12 +210,43 @@ export function AppLayout() {<ShellLogo size={24} className="text-primary shrink-0" /><span className="font-bold text-lg text-sidebar-foreground tracking-tight">{t('app.name')}</span></div>+ <div className="flex items-center gap-0.5">+ <button+ onClick={togglePrivacyMode}+ className="text-sidebar-muted hover:text-sidebar-foreground transition-colors p-1 rounded-md hover:bg-sidebar-accent"+ title={privacyMode ? t('privacy.show') : t('privacy.hide')}+ aria-label={privacyMode ? t('privacy.show') : t('privacy.hide')}+ >+ {privacyMode ? <EyeOff size={16} /> : <Eye size={16} />}+ </button>+ <button+ onClick={toggleTheme}+ className="text-sidebar-muted hover:text-sidebar-foreground transition-colors p-1 rounded-md hover:bg-sidebar-accent"+ title={isDark ? t('settings.themeLight') : t('settings.themeDark')}+ aria-label={isDark ? t('settings.themeLight') : t('settings.themeDark')}+ >+ {isDark ? <Sun size={16} /> : <Moon size={16} />}+ </button>+ </div>+ </div>++ {/* Command palette trigger */}+ <div className="px-3 pt-3"><button- onClick={togglePrivacyMode}- className="text-sidebar-muted hover:text-sidebar-foreground transition-colors p-1 rounded-md hover:bg-sidebar-accent"- title={privacyMode ? t('privacy.show') : t('privacy.hide')}+ type="button"+ onClick={() => setPaletteOpen(true)}+ className={cn(+ 'group flex w-full items-center gap-2 rounded-lg border border-sidebar-border/80 bg-sidebar-accent/40 px-3 py-2',+ 'text-[12.5px] text-sidebar-muted transition-all',+ 'hover:bg-sidebar-accent hover:text-sidebar-foreground hover:border-sidebar-border'+ )}+ aria-label={t('cmdk.triggerAria')}>- {privacyMode ? <EyeOff size={16} /> : <Eye size={16} />}+ <Search size={13} className="shrink-0" />+ <span className="flex-1 text-left">{t('cmdk.triggerLabel')}</span>+ <kbd className="hidden lg:inline-flex h-[17px] items-center rounded border border-sidebar-border bg-sidebar px-1 font-mono text-[9.5px] font-semibold text-sidebar-muted/80">+ {isMac ? '⌘' : 'Ctrl'} K+ </kbd></button></div>@@ -295,62 +361,6 @@ export function AppLayout() {<div className="flex-1" />- {/* Language & Theme toggles */}- <div className="group/toggles px-3 pb-2 border-b border-sidebar-border">- <div className="flex items-center justify-between gap-2 px-1 py-2">- {/* Language toggle */}- <div className="flex items-center gap-1">- <button- onClick={() => i18n.changeLanguage('pt-BR')}- className={cn(- 'px-2 py-1 rounded text-[11px] font-semibold transition-all duration-300',- currentLang === 'pt-BR'- ? 'bg-primary/15 text-primary group-hover/toggles:bg-primary/25'- : 'text-sidebar-muted/40 group-hover/toggles:text-sidebar-muted group-hover/toggles:hover:text-sidebar-foreground'- )}- >- PT- </button>- <button- onClick={() => i18n.changeLanguage('en')}- className={cn(- 'px-2 py-1 rounded text-[11px] font-semibold transition-all duration-300',- currentLang === 'en'- ? 'bg-primary/15 text-primary group-hover/toggles:bg-primary/25'- : 'text-sidebar-muted/40 group-hover/toggles:text-sidebar-muted group-hover/toggles:hover:text-sidebar-foreground'- )}- >- EN- </button>- </div>- {/* Theme toggle */}- <div className="flex items-center gap-1">- <button- onClick={() => setTheme('light')}- className={cn(- 'p-1.5 rounded transition-all duration-300',- theme === 'light'- ? 'bg-primary/15 text-primary group-hover/toggles:bg-primary/25'- : 'text-sidebar-muted/40 group-hover/toggles:text-sidebar-muted group-hover/toggles:hover:text-sidebar-foreground'- )}- >- <Sun size={14} />- </button>- <button- onClick={() => setTheme('dark')}- className={cn(- 'p-1.5 rounded transition-all duration-300',- theme === 'dark'- ? 'bg-primary/15 text-primary group-hover/toggles:bg-primary/25'- : 'text-sidebar-muted/40 group-hover/toggles:text-sidebar-muted group-hover/toggles:hover:text-sidebar-foreground'- )}- >- <Moon size={14} />- </button>- </div>- </div>- </div>-{/* User section */}<div className="p-3"><DropdownMenu>@@ -409,6 +419,40 @@ export function AppLayout() {<HardDriveDownload size={14} />{backingUp ? t('backup.downloading') : t('backup.button')}</DropdownMenuItem>+ <DropdownMenuSub>+ <DropdownMenuSubTrigger className="flex items-center gap-2">+ <Languages size={14} />+ <span className="flex-1">{t('setup.language')}</span>+ <span className="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">+ {currentLang === 'pt-BR' ? 'PT' : 'EN'}+ </span>+ </DropdownMenuSubTrigger>+ <DropdownMenuPortal>+ <DropdownMenuSubContent className="w-40">+ <DropdownMenuLabel className="px-2 py-1 text-[10.5px] font-semibold uppercase tracking-[0.08em] text-muted-foreground/70">+ {t('setup.language')}+ </DropdownMenuLabel>+ <DropdownMenuItem+ onClick={() => i18n.changeLanguage('pt-BR')}+ className="flex items-center gap-2"+ >+ <span className="flex-1">Português</span>+ {currentLang === 'pt-BR' && (+ <Check size={13} className="text-primary" />+ )}+ </DropdownMenuItem>+ <DropdownMenuItem+ onClick={() => i18n.changeLanguage('en')}+ className="flex items-center gap-2"+ >+ <span className="flex-1">English</span>+ {currentLang === 'en' && (+ <Check size={13} className="text-primary" />+ )}+ </DropdownMenuItem>+ </DropdownMenuSubContent>+ </DropdownMenuPortal>+ </DropdownMenuSub><DropdownMenuSeparator /><DropdownMenuItemonClick={logout}@@ -433,13 +477,15 @@ export function AppLayout() {{showTour && <OnboardingTour onComplete={handleTourComplete} />}<ChangePasswordDialog open={changePasswordOpen} onClose={() => setChangePasswordOpen(false)} /><TwoFactorSetup open={twoFactorOpen} onClose={() => setTwoFactorOpen(false)} />+ <CommandPalette open={paletteOpen} onOpenChange={setPaletteOpen} /></div>)}function UserMenu({ userInitial, logout, onChangePassword, onTwoFactor, onBackup, backingUp, dark, isAdmin }: { userInitial: string; logout: () => void; onChangePassword: () => void; onTwoFactor: () => void; onBackup: () => void; backingUp: boolean; dark?: boolean; isAdmin?: boolean }) {- const { t } = useTranslation()+ const { t, i18n } = useTranslation()const nav = useNavigate()+ const currentLang = i18n.languagereturn (<DropdownMenu><DropdownMenuTrigger asChild>@@ -473,6 +519,40 @@ function UserMenu({ userInitial, logout, onChangePassword, onTwoFactor, onBackup<HardDriveDownload size={14} />{backingUp ? t('backup.downloading') : t('backup.button')}</DropdownMenuItem>+ <DropdownMenuSub>+ <DropdownMenuSubTrigger className="flex items-center gap-2">+ <Languages size={14} />+ <span className="flex-1">{t('setup.language')}</span>+ <span className="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">+ {currentLang === 'pt-BR' ? 'PT' : 'EN'}+ </span>+ </DropdownMenuSubTrigger>+ <DropdownMenuPortal>+ <DropdownMenuSubContent className="w-40">+ <DropdownMenuLabel className="px-2 py-1 text-[10.5px] font-semibold uppercase tracking-[0.08em] text-muted-foreground/70">+ {t('setup.language')}+ </DropdownMenuLabel>+ <DropdownMenuItem+ onClick={() => i18n.changeLanguage('pt-BR')}+ className="flex items-center gap-2"+ >+ <span className="flex-1">Português</span>+ {currentLang === 'pt-BR' && (+ <Check size={13} className="text-primary" />+ )}+ </DropdownMenuItem>+ <DropdownMenuItem+ onClick={() => i18n.changeLanguage('en')}+ className="flex items-center gap-2"+ >+ <span className="flex-1">English</span>+ {currentLang === 'en' && (+ <Check size={13} className="text-primary" />+ )}+ </DropdownMenuItem>+ </DropdownMenuSubContent>+ </DropdownMenuPortal>+ </DropdownMenuSub><DropdownMenuSeparator /><DropdownMenuItem onClick={logout} className="text-rose-600 focus:text-rose-600">{t('auth.logout')}diff --git a/frontend/src/components/command-palette.tsx b/frontend/src/components/command-palette.tsxnew file mode 100644index 00000000..8289bcb1--- /dev/null+++ b/frontend/src/components/command-palette.tsx@@ -0,0 +1,778 @@+import { useEffect, useMemo, useRef, useState, useCallback, useSyncExternalStore } from 'react'+import { Command } from 'cmdk'+import { Dialog as DialogPrimitive } from 'radix-ui'+import { useNavigate } from 'react-router-dom'+import { useTranslation } from 'react-i18next'+import { useQuery } from '@tanstack/react-query'+import {+ Search,+ CornerDownLeft,+ LayoutDashboard,+ ArrowLeftRight,+ Building2,+ Upload,+ SlidersHorizontal,+ Tag,+ PiggyBank,+ Target,+ Repeat,+ Landmark,+ Users,+ BarChart3,+ Plus,+ Receipt,+ CircleDollarSign,+ Wallet,+ Flame,+ FileSpreadsheet,+ History,+ ArrowUpRight,+ Zap,+ Compass,+} from 'lucide-react'++import { search as searchApi, type SearchHit, type SearchHitType } from '@/lib/api'+import { cn } from '@/lib/utils'++// ---------------------------------------------------------------------------+// Static actions & navigation registry+// ---------------------------------------------------------------------------++type StaticItem = {+ id: string+ labelKey: string+ icon: React.ElementType+ path?: string+ onSelect?: (nav: (to: string) => void) => void+ keywords?: string[]+}++const NAV_ITEMS: StaticItem[] = [+ { id: 'nav-dashboard', labelKey: 'nav.dashboard', icon: LayoutDashboard, path: '/', keywords: ['home', 'inicio', 'início'] },+ { id: 'nav-transactions', labelKey: 'nav.transactions', icon: ArrowLeftRight, path: '/transactions', keywords: ['tx', 'transacoes', 'transações'] },+ { id: 'nav-accounts', labelKey: 'nav.accounts', icon: Building2, path: '/accounts', keywords: ['contas'] },+ { id: 'nav-import', labelKey: 'nav.import', icon: Upload, path: '/import', keywords: ['csv', 'ofx', 'importar'] },+ { id: 'nav-reports', labelKey: 'nav.reports', icon: BarChart3, path: '/reports', keywords: ['relatorios', 'relatórios', 'charts'] },+ { id: 'nav-assets', labelKey: 'nav.assets', icon: Landmark, path: '/assets', keywords: ['patrimonio', 'patrimônio'] },+ { id: 'nav-budgets', labelKey: 'nav.budgets', icon: PiggyBank, path: '/budgets', keywords: ['orcamentos', 'orçamentos'] },+ { id: 'nav-goals', labelKey: 'nav.goals', icon: Target, path: '/goals', keywords: ['metas'] },+ { id: 'nav-recurring', labelKey: 'nav.recurring', icon: Repeat, path: '/recurring', keywords: ['recorrentes'] },+ { id: 'nav-categories', labelKey: 'nav.categories', icon: Tag, path: '/categories', keywords: ['categorias'] },+ { id: 'nav-payees', labelKey: 'nav.payees', icon: Users, path: '/payees', keywords: ['beneficiarios', 'beneficiários'] },+ { id: 'nav-rules', labelKey: 'nav.rules', icon: SlidersHorizontal, path: '/rules', keywords: ['regras'] },+]++const QUICK_ACTIONS: StaticItem[] = [+ {+ id: 'action-new-transaction',+ labelKey: 'cmdk.actions.newTransaction',+ icon: Plus,+ onSelect: (nav) => nav('/transactions?new=1'),+ keywords: ['new', 'add', 'create', 'nova', 'adicionar'],+ },+ {+ id: 'action-import',+ labelKey: 'cmdk.actions.importFile',+ icon: FileSpreadsheet,+ onSelect: (nav) => nav('/import'),+ keywords: ['upload', 'csv', 'ofx', 'qif'],+ },+ {+ id: 'action-new-budget',+ labelKey: 'cmdk.actions.newBudget',+ icon: PiggyBank,+ onSelect: (nav) => nav('/budgets?new=1'),+ keywords: ['budget', 'orcamento'],+ },+ {+ id: 'action-new-goal',+ labelKey: 'cmdk.actions.newGoal',+ icon: Target,+ onSelect: (nav) => nav('/goals?new=1'),+ keywords: ['goal', 'meta', 'target'],+ },+ {+ id: 'action-reports',+ labelKey: 'cmdk.actions.openReports',+ icon: BarChart3,+ onSelect: (nav) => nav('/reports'),+ },+]++// ---------------------------------------------------------------------------+// Entity type → icon + accent color+// ---------------------------------------------------------------------------++const ENTITY_META: Record<SearchHitType, { icon: React.ElementType; tintClass: string; bgClass: string; labelKey: string; pathFor: (hit: SearchHit) => string }> = {+ transaction: {+ icon: Receipt,+ tintClass: 'text-indigo-500 dark:text-indigo-300',+ bgClass: 'bg-indigo-500/10',+ labelKey: 'cmdk.groups.transactions',+ pathFor: (hit) => {+ const params = new URLSearchParams()+ if (hit.label) params.set('q', hit.label)+ params.set('highlight', hit.id)+ return `/transactions?${params.toString()}`+ },+ },+ account: {+ icon: Wallet,+ tintClass: 'text-emerald-500 dark:text-emerald-300',+ bgClass: 'bg-emerald-500/10',+ labelKey: 'cmdk.groups.accounts',+ pathFor: (hit) => `/accounts/${hit.id}`,+ },+ payee: {+ icon: Users,+ tintClass: 'text-sky-500 dark:text-sky-300',+ bgClass: 'bg-sky-500/10',+ labelKey: 'cmdk.groups.payees',+ pathFor: (hit) => `/transactions?payee_id=${hit.id}`,+ },+ category: {+ icon: Tag,+ tintClass: 'text-fuchsia-500 dark:text-fuchsia-300',+ bgClass: 'bg-fuchsia-500/10',+ labelKey: 'cmdk.groups.categories',+ pathFor: (hit) => `/transactions?category_id=${hit.id}`,+ },+ goal: {+ icon: Target,+ tintClass: 'text-amber-500 dark:text-amber-300',+ bgClass: 'bg-amber-500/10',+ labelKey: 'cmdk.groups.goals',+ pathFor: () => '/goals',+ },+ asset: {+ icon: Landmark,+ tintClass: 'text-rose-500 dark:text-rose-300',+ bgClass: 'bg-rose-500/10',+ labelKey: 'cmdk.groups.assets',+ pathFor: () => '/assets',+ },+}++// ---------------------------------------------------------------------------+// Recent items (localStorage)+// ---------------------------------------------------------------------------++type RecentItem = {+ id: string+ label: string+ path: string+ icon: string // lucide name, stored as string; resolved via fallback icon+ sublabel?: string | null+}++const RECENT_KEY = 'securo.cmdk.recent'+const RECENT_MAX = 5++function loadRecents(): RecentItem[] {+ try {+ const raw = localStorage.getItem(RECENT_KEY)+ if (!raw) return []+ const parsed = JSON.parse(raw)+ if (!Array.isArray(parsed)) return []+ return parsed.slice(0, RECENT_MAX)+ } catch {+ return []+ }+}++// Tiny external store so we can read `localStorage` recents through+// useSyncExternalStore and avoid setState-in-effect lint warnings.+type Listener = () => void+const recentListeners = new Set<Listener>()+let recentSnapshot: RecentItem[] = loadRecents()++function subscribeRecents(listener: Listener) {+ recentListeners.add(listener)+ return () => {+ recentListeners.delete(listener)+ }+}++function getRecentSnapshot(): RecentItem[] {+ return recentSnapshot+}++function saveRecent(item: RecentItem) {+ const existing = recentSnapshot.filter((r) => r.id !== item.id)+ const next = [item, ...existing].slice(0, RECENT_MAX)+ recentSnapshot = next+ try {+ localStorage.setItem(RECENT_KEY, JSON.stringify(next))+ } catch {+ // ignore+ }+ recentListeners.forEach((l) => l())+}++// ---------------------------------------------------------------------------+// Amount formatting helper+// ---------------------------------------------------------------------------++function formatHitAmount(amount: number | null, currency: string | null, locale: string): string | null {+ if (amount === null || amount === undefined) return null+ try {+ return new Intl.NumberFormat(locale, {+ style: 'currency',+ currency: currency ?? 'USD',+ maximumFractionDigits: 2,+ }).format(amount)+ } catch {+ return `${amount}`+ }+}++function formatHitDate(iso: string | null, locale: string): string | null {+ if (!iso) return null+ try {+ const d = new Date(iso)+ return new Intl.DateTimeFormat(locale, { month: 'short', day: 'numeric' }).format(d)+ } catch {+ return iso+ }+}++// Accent- and case-insensitive substring match so that typing "regras"+// matches "Regras", "orcamento" matches "Orçamentos", etc.+function normalizeText(s: string): string {+ return s.toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '')+}++function matchesQuery(query: string, haystacks: Array<string | undefined>): boolean {+ const q = normalizeText(query.trim())+ if (!q) return true+ return haystacks.some((h) => (h ? normalizeText(h).includes(q) : false))+}++// ---------------------------------------------------------------------------+// The palette+// ---------------------------------------------------------------------------++export interface CommandPaletteProps {+ open: boolean+ onOpenChange: (open: boolean) => void+}++export function CommandPalette({ open, onOpenChange }: CommandPaletteProps) {+ const { t, i18n } = useTranslation()+ const navigate = useNavigate()+ const [query, setQuery] = useState('')+ const [debounced, setDebounced] = useState('')+ const recents = useSyncExternalStore(subscribeRecents, getRecentSnapshot, getRecentSnapshot)+ const inputRef = useRef<HTMLInputElement>(null)+ const locale = i18n.language === 'en' ? 'en-US' : i18n.language++ // Focus the input whenever the palette opens. The cmdk Command is re-keyed+ // on `open` so results and selection reset automatically. We reset our own+ // query/debounced state in the close handler instead of here to avoid+ // calling setState inside an effect.+ useEffect(() => {+ if (open) {+ const id = setTimeout(() => inputRef.current?.focus(), 10)+ return () => clearTimeout(id)+ }+ }, [open])++ const handleOpenChange = useCallback(+ (next: boolean) => {+ if (!next) {+ setQuery('')+ setDebounced('')+ }+ onOpenChange(next)+ },+ [onOpenChange]+ )++ // Debounce query → debounced (150ms)+ useEffect(() => {+ const id = setTimeout(() => setDebounced(query), 150)+ return () => clearTimeout(id)+ }, [query])++ const { data: searchResults = [], isFetching } = useQuery({+ queryKey: ['search', debounced],+ queryFn: () => searchApi.query(debounced, 5),+ enabled: open && debounced.trim().length > 0,+ staleTime: 30_000,+ })++ // Group hits by entity type+ const grouped = useMemo(() => {+ const groups = new Map<SearchHitType, SearchHit[]>()+ for (const hit of searchResults) {+ const arr = groups.get(hit.type) ?? []+ arr.push(hit)+ groups.set(hit.type, arr)+ }+ return groups+ }, [searchResults])++ // Client-side filtered nav + quick actions so typing "regras" or "nova"+ // narrows the in-app items alongside the backend entity search.+ const filteredNavItems = useMemo(() => {+ if (debounced.trim().length === 0) return NAV_ITEMS+ return NAV_ITEMS.filter((n) =>+ matchesQuery(debounced, [t(n.labelKey), n.path, ...(n.keywords ?? [])])+ )+ }, [debounced, t])++ const filteredQuickActions = useMemo(() => {+ if (debounced.trim().length === 0) return QUICK_ACTIONS+ return QUICK_ACTIONS.filter((a) =>+ matchesQuery(debounced, [t(a.labelKey), ...(a.keywords ?? [])])+ )+ }, [debounced, t])++ const runAndClose = useCallback(+ (item: { id: string; label: string; path: string; iconName: string; sublabel?: string | null }) => {+ saveRecent({+ id: item.id,+ label: item.label,+ path: item.path,+ icon: item.iconName,+ sublabel: item.sublabel,+ })+ handleOpenChange(false)+ // Slight delay so dialog closes before navigation animation+ setTimeout(() => navigate(item.path), 0)+ },+ [navigate, handleOpenChange]+ )++ const showEmptyHome = debounced.trim().length === 0+ const hasAnyResults = searchResults.length > 0+ const hasAnyLocalMatch =+ filteredNavItems.length > 0 || filteredQuickActions.length > 0+ const showEmptyState = !showEmptyHome && !hasAnyResults && !hasAnyLocalMatch++ return (+ <DialogPrimitive.Root open={open} onOpenChange={handleOpenChange}>+ <DialogPrimitive.Portal>+ <DialogPrimitive.Overlay+ className={cn(+ 'fixed inset-0 z-50 backdrop-blur-[3px] bg-background/40',+ 'data-[state=open]:animate-in data-[state=closed]:animate-out',+ 'data-[state=open]:fade-in-0 data-[state=closed]:fade-out-0'+ )}+ />+ <DialogPrimitive.Content+ className={cn(+ 'fixed left-1/2 top-[22%] z-50 w-[92vw] max-w-[640px] -translate-x-1/2',+ 'data-[state=open]:animate-in data-[state=closed]:animate-out',+ 'data-[state=open]:fade-in-0 data-[state=closed]:fade-out-0',+ 'data-[state=open]:zoom-in-95 data-[state=closed]:zoom-out-95',+ 'data-[state=open]:slide-in-from-top-4 data-[state=closed]:slide-out-to-top-4',+ 'duration-150 outline-none'+ )}+ >+ <DialogPrimitive.Title className="sr-only">{t('cmdk.title')}</DialogPrimitive.Title>+ <DialogPrimitive.Description className="sr-only">{t('cmdk.description')}</DialogPrimitive.Description>++ <Command+ key={open ? 'open' : 'closed'}+ shouldFilter={false}+ className={cn(+ 'relative overflow-hidden rounded-2xl border border-border/80 bg-card',+ 'shadow-[0_30px_80px_-20px_rgba(15,23,42,0.35)] dark:shadow-[0_30px_80px_-20px_rgba(0,0,0,0.8)]',+ 'ring-1 ring-black/[0.02] dark:ring-white/[0.04]'+ )}+ >+ {/* Decorative gradient rim */}+ <div+ aria-hidden+ className="pointer-events-none absolute inset-x-0 top-0 h-px bg-gradient-to-r from-transparent via-primary/40 to-transparent"+ />++ {/* Input row */}+ <div className="flex items-center gap-3 border-b border-border/60 px-4 py-3.5">+ <Search size={17} className="shrink-0 text-muted-foreground" />+ <Command.Input+ ref={inputRef}+ value={query}+ onValueChange={setQuery}+ placeholder={t('cmdk.placeholder')}+ className={cn(+ 'flex-1 bg-transparent text-[14.5px] text-foreground outline-none',+ 'placeholder:text-muted-foreground/70',+ 'caret-primary'+ )}+ />+ {isFetching && debounced && (+ <div className="h-3 w-3 shrink-0 animate-spin rounded-full border border-muted-foreground/30 border-t-primary" />+ )}+ <kbd className="hidden sm:inline-flex h-5 items-center rounded border border-border/80 bg-muted/60 px-1.5 font-mono text-[10px] font-medium text-muted-foreground">+ ESC+ </kbd>+ </div>++ {/* Scrollable results area */}+ <Command.List+ className={cn(+ 'max-h-[min(480px,60vh)] overflow-y-auto overscroll-contain px-2 py-2',+ 'scrollbar-thin'+ )}+ >+ {/* HOME (no query): recents → quick actions → navigation */}+ {showEmptyHome ? (+ <>+ {recents.length > 0 && (+ <Group+ icon={<History size={11} />}+ labelKey="cmdk.groups.recent"+ >+ {recents.map((r) => (+ <Command.Item+ key={`recent-${r.id}`}+ value={`recent ${r.label}`}+ onSelect={() =>+ runAndClose({+ id: r.id,+ label: r.label,+ path: r.path,+ iconName: r.icon,+ sublabel: r.sublabel,+ })+ }+ className={itemClasses()}+ >+ <ItemIcon tintClass="text-muted-foreground" bgClass="bg-muted/60">+ <Compass size={14} />+ </ItemIcon>+ <div className="min-w-0 flex-1">+ <div className="truncate text-[13.5px] text-foreground">{r.label}</div>+ {r.sublabel && (+ <div className="truncate text-[11.5px] text-muted-foreground">{r.sublabel}</div>+ )}+ </div>+ <ArrowUpRight size={13} className="text-muted-foreground/50 group-data-[selected=true]:text-primary" />+ </Command.Item>+ ))}+ </Group>+ )}++ {filteredQuickActions.length > 0 && (+ <Group icon={<Zap size={11} />} labelKey="cmdk.groups.quickActions">+ {filteredQuickActions.map((a) => {+ const Icon = a.icon+ return (+ <Command.Item+ key={a.id}+ value={`action ${t(a.labelKey)} ${(a.keywords ?? []).join(' ')}`}+ onSelect={() => {+ if (a.onSelect) {+ handleOpenChange(false)+ setTimeout(() => a.onSelect!(navigate), 0)+ }+ }}+ className={itemClasses()}+ >+ <ItemIcon tintClass="text-primary" bgClass="bg-primary/10">+ <Icon size={14} />+ </ItemIcon>+ <div className="min-w-0 flex-1">+ <div className="truncate text-[13.5px] text-foreground">{t(a.labelKey)}</div>+ </div>+ <CornerDownLeft size={12} className="text-muted-foreground/40 group-data-[selected=true]:text-primary" />+ </Command.Item>+ )+ })}+ </Group>+ )}++ {filteredNavItems.length > 0 && (+ <Group icon={<Compass size={11} />} labelKey="cmdk.groups.navigation">+ {filteredNavItems.map((n) => {+ const Icon = n.icon+ return (+ <Command.Item+ key={n.id}+ value={`nav ${t(n.labelKey)} ${(n.keywords ?? []).join(' ')}`}+ onSelect={() =>+ runAndClose({+ id: n.id,+ label: t(n.labelKey),+ path: n.path!,+ iconName: 'compass',+ })+ }+ className={itemClasses()}+ >+ <ItemIcon tintClass="text-muted-foreground" bgClass="bg-muted/60">+ <Icon size={14} />+ </ItemIcon>+ <div className="min-w-0 flex-1">+ <div className="truncate text-[13.5px] text-foreground">{t(n.labelKey)}</div>+ <div className="truncate text-[11px] text-muted-foreground/80">{n.path}</div>+ </div>+ </Command.Item>+ )+ })}+ </Group>+ )}+ </>+ ) : (+ /* SEARCH (query active): entities FIRST, then actions, then nav */+ <>+ {showEmptyState && !isFetching && (+ <Command.Empty className="px-3 py-10 text-center">+ <div className="mx-auto mb-3 flex h-10 w-10 items-center justify-center rounded-full bg-muted/60">+ <Flame size={15} className="text-muted-foreground" />+ </div>+ <p className="text-[13px] font-medium text-foreground">+ {t('cmdk.empty.title', { query: debounced })}+ </p>+ <p className="mt-1 text-[12px] text-muted-foreground">{t('cmdk.empty.hint')}</p>+ </Command.Empty>+ )}++ {/* Entity results — highest priority when searching */}+ {(['transaction', 'account', 'payee', 'category', 'goal', 'asset'] as SearchHitType[]).map((type) => {+ const items = grouped.get(type) ?? []+ if (items.length === 0) return null+ const meta = ENTITY_META[type]+ const GroupIcon = meta.icon+ return (+ <Group+ key={type}+ icon={<GroupIcon size={11} />}+ labelKey={meta.labelKey}+ >+ {items.map((hit) => {+ const amount = formatHitAmount(hit.amount, hit.currency, locale)+ const dateLabel = formatHitDate(hit.date, locale)+ const isPositive = (hit.amount ?? 0) > 0 && hit.type === 'transaction' && (hit.meta?.tx_type === 'credit' || hit.amount! > 0)+ const isNegative = hit.type === 'transaction' && hit.amount !== null && (hit.meta?.tx_type === 'debit' || hit.amount! < 0)+ return (+ <Command.Item+ key={`${hit.type}-${hit.id}`}+ value={`${hit.type} ${hit.label} ${hit.subtitle ?? ''}`}+ onSelect={() =>+ runAndClose({+ id: `${hit.type}-${hit.id}`,+ label: hit.label,+ path: meta.pathFor(hit),+ iconName: hit.type,+ sublabel: hit.subtitle,+ })+ }+ className={itemClasses()}+ >+ <ItemIcon tintClass={meta.tintClass} bgClass={meta.bgClass} style={hit.color ? { backgroundColor: `${hit.color}1A`, color: hit.color } : undefined}>+ <GroupIcon size={14} />+ </ItemIcon>+ <div className="min-w-0 flex-1">+ <div className="truncate text-[13.5px] text-foreground">{hit.label}</div>+ {hit.subtitle && (+ <div className="truncate text-[11.5px] text-muted-foreground/90">+ {hit.subtitle}+ {dateLabel && <span className="mx-1.5 text-muted-foreground/40">•</span>}+ {dateLabel}+ </div>+ )}+ </div>+ {amount && (+ <div+ className={cn(+ 'shrink-0 tabular-nums text-[12.5px] font-medium',+ isNegative && 'text-rose-500 dark:text-rose-400',+ isPositive && 'text-emerald-500 dark:text-emerald-400',+ !isNegative && !isPositive && 'text-muted-foreground'+ )}+ >+ {amount}+ </div>+ )}+ </Command.Item>+ )+ })}+ </Group>+ )+ })}++ {/* Quick actions — lower priority fallback while searching */}+ {filteredQuickActions.length > 0 && (+ <Group icon={<Zap size={11} />} labelKey="cmdk.groups.quickActions">+ {filteredQuickActions.map((a) => {+ const Icon = a.icon+ return (+ <Command.Item+ key={a.id}+ value={`action ${t(a.labelKey)} ${(a.keywords ?? []).join(' ')}`}+ onSelect={() => {+ if (a.onSelect) {+ handleOpenChange(false)+ setTimeout(() => a.onSelect!(navigate), 0)+ }+ }}+ className={itemClasses()}+ >+ <ItemIcon tintClass="text-primary" bgClass="bg-primary/10">+ <Icon size={14} />+ </ItemIcon>+ <div className="min-w-0 flex-1">+ <div className="truncate text-[13.5px] text-foreground">{t(a.labelKey)}</div>+ </div>+ <CornerDownLeft size={12} className="text-muted-foreground/40 group-data-[selected=true]:text-primary" />+ </Command.Item>+ )+ })}+ </Group>+ )}++ {/* Navigation — lowest priority fallback while searching */}+ {filteredNavItems.length > 0 && (+ <Group icon={<Compass size={11} />} labelKey="cmdk.groups.navigation">+ {filteredNavItems.map((n) => {+ const Icon = n.icon+ return (+ <Command.Item+ key={n.id}+ value={`nav ${t(n.labelKey)} ${(n.keywords ?? []).join(' ')}`}+ onSelect={() =>+ runAndClose({+ id: n.id,+ label: t(n.labelKey),+ path: n.path!,+ iconName: 'compass',+ })+ }+ className={itemClasses()}+ >+ <ItemIcon tintClass="text-muted-foreground" bgClass="bg-muted/60">+ <Icon size={14} />+ </ItemIcon>+ <div className="min-w-0 flex-1">+ <div className="truncate text-[13.5px] text-foreground">{t(n.labelKey)}</div>+ <div className="truncate text-[11px] text-muted-foreground/80">{n.path}</div>+ </div>+ </Command.Item>+ )+ })}+ </Group>+ )}+ </>+ )}+ </Command.List>++ {/* Footer */}+ <div className="flex items-center justify-between gap-4 border-t border-border/60 bg-muted/30 px-4 py-2">+ <div className="flex items-center gap-1.5 text-[10.5px] text-muted-foreground">+ <CircleDollarSign size={11} className="text-primary" />+ <span className="font-semibold tracking-tight text-foreground/90">Securo</span>+ <span className="text-muted-foreground/50">/</span>+ <span>{t('cmdk.footer.tagline')}</span>+ </div>+ <div className="flex items-center gap-3 text-[10px] text-muted-foreground">+ <KbdHint>+ <Kbd>↑</Kbd>+ <Kbd>↓</Kbd>+ <span>{t('cmdk.footer.navigate')}</span>+ </KbdHint>+ <KbdHint>+ <Kbd>+ <CornerDownLeft size={9} />+ </Kbd>+ <span>{t('cmdk.footer.open')}</span>+ </KbdHint>+ <KbdHint>+ <Kbd>esc</Kbd>+ <span>{t('cmdk.footer.close')}</span>+ </KbdHint>+ </div>+ </div>+ </Command>+ </DialogPrimitive.Content>+ </DialogPrimitive.Portal>+ </DialogPrimitive.Root>+ )+}++// ---------------------------------------------------------------------------+// Subcomponents+// ---------------------------------------------------------------------------++function Group({+ icon,+ labelKey,+ children,+}: {+ icon: React.ReactNode+ labelKey: string+ children: React.ReactNode+}) {+ const { t } = useTranslation()+ return (+ <Command.Group+ heading={+ <div className="flex items-center gap-1.5 px-3 pt-3 pb-1.5">+ <span className="text-muted-foreground/60">{icon}</span>+ <span className="text-[10px] font-semibold uppercase tracking-[0.12em] text-muted-foreground/70">+ {t(labelKey)}+ </span>+ </div>+ }+ className="mb-1"+ >+ {children}+ </Command.Group>+ )+}++function itemClasses() {+ return cn(+ 'group flex cursor-pointer items-center gap-3 rounded-lg px-3 py-2 text-sm',+ 'transition-colors',+ 'data-[selected=true]:bg-primary/[0.08] data-[selected=true]:text-foreground',+ 'data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50',+ 'hover:bg-muted/40'+ )+}++function ItemIcon({+ tintClass,+ bgClass,+ style,+ children,+}: {+ tintClass: string+ bgClass: string+ style?: React.CSSProperties+ children: React.ReactNode+}) {+ return (+ <div+ className={cn(+ 'flex h-7 w-7 shrink-0 items-center justify-center rounded-md',+ bgClass,+ tintClass+ )}+ style={style}+ >+ {children}+ </div>+ )+}++function KbdHint({ children }: { children: React.ReactNode }) {+ return <div className="flex items-center gap-1">{children}</div>+}++function Kbd({ children }: { children: React.ReactNode }) {+ return (+ <kbd+ className={cn(+ 'inline-flex h-[17px] min-w-[17px] items-center justify-center rounded border border-border/80',+ 'bg-background px-1 font-mono text-[9.5px] font-medium text-muted-foreground/90',+ 'shadow-[0_1px_0_rgba(0,0,0,0.05)]'+ )}+ >+ {children}+ </kbd>+ )+}+diff --git a/frontend/src/components/transactions-filter-bar.tsx b/frontend/src/components/transactions-filter-bar.tsxnew file mode 100644index 00000000..6fac9ebc--- /dev/null+++ b/frontend/src/components/transactions-filter-bar.tsx@@ -0,0 +1,850 @@+import { useMemo, useRef, useState } from 'react'+import { useTranslation } from 'react-i18next'+import { format, startOfMonth, startOfYear, subDays } from 'date-fns'+import {+ Calendar as CalendarIcon,+ Check,+ ChevronRight,+ ListFilter,+ Search,+ Store,+ Tag,+ Wallet,+ X,+} from 'lucide-react'+import { ptBR, enUS } from 'date-fns/locale'++import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuGroup,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuPortal,+ DropdownMenuSeparator,+ DropdownMenuSub,+ DropdownMenuSubContent,+ DropdownMenuSubTrigger,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu'+import {+ Popover,+ PopoverAnchor,+ PopoverContent,+} from '@/components/ui/popover'+import { Calendar } from '@/components/ui/calendar'+import { Input } from '@/components/ui/input'+import { Button } from '@/components/ui/button'+import { cn } from '@/lib/utils'+import type { Account, Category, Payee } from '@/types'++interface TransactionsFilterBarProps {+ searchInput: string+ onSearchChange: (value: string) => void+ filterAccountIds: string[]+ onAccountIdsChange: (value: string[]) => void+ filterCategoryIds: string[]+ onCategoryIdsChange: (value: string[]) => void+ filterUncategorized: boolean+ onUncategorizedChange: (value: boolean) => void+ filterPayee: string+ onPayeeChange: (value: string) => void+ filterFrom: string+ filterTo: string+ onDateRangeChange: (from: string, to: string) => void+ onClearAll: () => void+ accounts: Account[]+ categories: Category[]+ payees: Payee[]+}++function toISODate(d: Date): string {+ return format(d, 'yyyy-MM-dd')+}++function toggleInArray(arr: string[], id: string): string[] {+ return arr.includes(id) ? arr.filter((x) => x !== id) : [...arr, id]+}++export function TransactionsFilterBar({+ searchInput,+ onSearchChange,+ filterAccountIds,+ onAccountIdsChange,+ filterCategoryIds,+ onCategoryIdsChange,+ filterUncategorized,+ onUncategorizedChange,+ filterPayee,+ onPayeeChange,+ filterFrom,+ filterTo,+ onDateRangeChange,+ onClearAll,+ accounts,+ categories,+ payees,+}: TransactionsFilterBarProps) {+ const { t, i18n } = useTranslation()+ const locale = i18n.language === 'en' ? 'en-US' : i18n.language+ const dateFnsLocale = i18n.language === 'pt-BR' ? ptBR : enUS+ const [menuOpen, setMenuOpen] = useState(false)+ const [accountSubOpen, setAccountSubOpen] = useState(false)+ const [categorySubOpen, setCategorySubOpen] = useState(false)+ const keepAccountSubOpenRef = useRef(false)+ const keepCategorySubOpenRef = useRef(false)+ const [dateCustomOpen, setDateCustomOpen] = useState(false)+ const [draftFrom, setDraftFrom] = useState<string>(filterFrom)+ const [draftTo, setDraftTo] = useState<string>(filterTo)+ const searchRef = useRef<HTMLInputElement>(null)++ // When a CheckRow is clicked inside a submenu, Radix tries to close the submenu+ // even if we preventDefault in onSelect. We intercept the close request so the+ // submenu stays open and users can toggle several rows in a row.+ const handleAccountSubOpenChange = (open: boolean) => {+ if (!open && keepAccountSubOpenRef.current) {+ keepAccountSubOpenRef.current = false+ return+ }+ setAccountSubOpen(open)+ }+ const handleCategorySubOpenChange = (open: boolean) => {+ if (!open && keepCategorySubOpenRef.current) {+ keepCategorySubOpenRef.current = false+ return+ }+ setCategorySubOpen(open)+ }+ // When the root menu closes, make sure submenus close too so a fresh open starts clean.+ const handleMenuOpenChange = (open: boolean) => {+ setMenuOpen(open)+ if (!open) {+ setAccountSubOpen(false)+ setCategorySubOpen(false)+ keepAccountSubOpenRef.current = false+ keepCategorySubOpenRef.current = false+ }+ }++ const accountById = useMemo(() => {+ const map = new Map<string, Account>()+ accounts.forEach((a) => map.set(a.id, a))+ return map+ }, [accounts])++ const categoryById = useMemo(() => {+ const map = new Map<string, Category>()+ categories.forEach((c) => map.set(c.id, c))+ return map+ }, [categories])++ const selectedPayee = useMemo(+ () => payees.find((p) => p.id === filterPayee),+ [payees, filterPayee],+ )++ const hasAnyFilter =+ filterAccountIds.length > 0 ||+ filterCategoryIds.length > 0 ||+ filterUncategorized ||+ !!filterPayee ||+ !!filterFrom ||+ !!filterTo ||+ searchInput.trim().length > 0++ const dateLabel = useMemo(() => {+ if (!filterFrom && !filterTo) return null+ const fmt = (iso: string) =>+ new Date(iso + 'T00:00:00').toLocaleDateString(locale, {+ day: '2-digit',+ month: 'short',+ })+ if (filterFrom && filterTo) return `${fmt(filterFrom)} — ${fmt(filterTo)}`+ if (filterFrom) return `≥ ${fmt(filterFrom)}`+ return `≤ ${fmt(filterTo)}`+ }, [filterFrom, filterTo, locale])++ const datePresets = useMemo(() => {+ const today = new Date()+ return [+ {+ key: 'today',+ label: t('transactions.filtersBar.datePresets.today'),+ from: toISODate(today),+ to: toISODate(today),+ },+ {+ key: 'last7',+ label: t('transactions.filtersBar.datePresets.last7'),+ from: toISODate(subDays(today, 6)),+ to: toISODate(today),+ },+ {+ key: 'last30',+ label: t('transactions.filtersBar.datePresets.last30'),+ from: toISODate(subDays(today, 29)),+ to: toISODate(today),+ },+ {+ key: 'thisMonth',+ label: t('transactions.filtersBar.datePresets.thisMonth'),+ from: toISODate(startOfMonth(today)),+ to: toISODate(today),+ },+ {+ key: 'last90',+ label: t('transactions.filtersBar.datePresets.last90'),+ from: toISODate(subDays(today, 89)),+ to: toISODate(today),+ },+ {+ key: 'thisYear',+ label: t('transactions.filtersBar.datePresets.thisYear'),+ from: toISODate(startOfYear(today)),+ to: toISODate(today),+ },+ ]+ }, [t])++ const openCustomRange = () => {+ setDraftFrom(filterFrom)+ setDraftTo(filterTo)+ setMenuOpen(false)+ // Wait for the dropdown to finish closing before showing the popover+ // so focus and portal state settle correctly.+ setTimeout(() => setDateCustomOpen(true), 80)+ }++ const accountSummary =+ filterAccountIds.length > 1+ ? t('transactions.filtersBar.nSelected', { count: filterAccountIds.length })+ : filterAccountIds.length === 1+ ? (accountById.get(filterAccountIds[0])?.name ?? '')+ : ''++ const categorySummary = (() => {+ const total = filterCategoryIds.length + (filterUncategorized ? 1 : 0)+ if (total > 1)+ return t('transactions.filtersBar.nSelected', { count: total })+ if (filterUncategorized) return t('transactions.uncategorized')+ if (filterCategoryIds.length === 1)+ return categoryById.get(filterCategoryIds[0])?.name ?? ''+ return ''+ })()++ return (+ <div className="mb-4">+ <Popover open={dateCustomOpen} onOpenChange={setDateCustomOpen}>+ <PopoverAnchor asChild>+ <div+ className={cn(+ 'group/filterbar rounded-xl border border-border bg-card shadow-sm transition-colors',+ 'focus-within:border-primary/40 focus-within:ring-[3px] focus-within:ring-primary/10',+ )}+ >+ {/* Top row: search input + controls */}+ <div className="flex items-center gap-1.5 px-2 py-1.5">+ {/* Search input */}+ <div className="relative flex min-w-0 flex-1 items-center">+ <Search+ size={15}+ className="pointer-events-none absolute left-2.5 text-muted-foreground/70"+ />+ <Input+ ref={searchRef}+ type="text"+ placeholder={t('transactions.searchPlaceholder')}+ value={searchInput}+ onChange={(e) => onSearchChange(e.target.value)}+ className="h-9 w-full border-0 bg-transparent pl-8 pr-2 text-[13.5px] shadow-none focus-visible:ring-0 focus-visible:border-transparent"+ />+ </div>++ {/* Right-side controls */}+ <div className="ml-auto flex shrink-0 items-center gap-1 pl-1">+ {hasAnyFilter && (+ <button+ type="button"+ onClick={onClearAll}+ className="hidden h-7 items-center rounded-md px-2 text-[11.5px] font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground md:inline-flex"+ >+ {t('transactions.clearFilters')}+ </button>+ )}++ <DropdownMenu open={menuOpen} onOpenChange={handleMenuOpenChange}>+ <DropdownMenuTrigger asChild>+ <button+ type="button"+ aria-label={t('transactions.filtersBar.filters')}+ className={cn(+ 'inline-flex h-8 items-center gap-1.5 rounded-md border border-border/80 bg-background px-2.5 text-[12px] font-medium text-muted-foreground transition-colors',+ 'hover:bg-muted hover:text-foreground',+ menuOpen && 'bg-muted text-foreground',+ hasAnyFilter && 'border-primary/30 text-primary hover:text-primary',+ )}+ >+ <ListFilter size={13} />+ <span className="hidden sm:inline">+ {t('transactions.filtersBar.filters')}+ </span>+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent+ align="end"+ sideOffset={6}+ className="w-[240px] p-1"+ >+ <DropdownMenuLabel className="px-2 py-1 text-[10.5px] font-semibold uppercase tracking-[0.08em] text-muted-foreground/70">+ {t('transactions.filtersBar.filterBy')}+ </DropdownMenuLabel>+ <DropdownMenuGroup>+ {/* Account submenu (multi) */}+ <DropdownMenuSub+ open={accountSubOpen}+ onOpenChange={handleAccountSubOpenChange}+ >+ <DropdownMenuSubTrigger className="gap-2 text-[13px]">+ <Wallet size={14} className="text-muted-foreground" />+ <span className="flex-1">{t('transactions.account')}</span>+ {accountSummary && (+ <span className="max-w-[90px] truncate text-[11px] text-muted-foreground">+ {accountSummary}+ </span>+ )}+ </DropdownMenuSubTrigger>+ <DropdownMenuPortal>+ <DropdownMenuSubContent+ sideOffset={8}+ className="max-h-[320px] w-[240px] overflow-y-auto p-1"+ >+ {accounts.length === 0 ? (+ <div className="px-2 py-3 text-center text-[12px] text-muted-foreground">+ {t('transactions.filtersBar.noOptions')}+ </div>+ ) : (+ accounts.map((a) => (+ <CheckRow+ key={a.id}+ checked={filterAccountIds.includes(a.id)}+ onToggle={() => {+ keepAccountSubOpenRef.current = true+ onAccountIdsChange(+ toggleInArray(filterAccountIds, a.id),+ )+ }}+ label={a.name}+ sublabel={a.currency}+ />+ ))+ )}+ {filterAccountIds.length > 0 && (+ <>+ <div className="my-1 h-px bg-border/60" />+ <DropdownMenuItem+ onSelect={(e) => {+ e.preventDefault()+ keepAccountSubOpenRef.current = true+ onAccountIdsChange([])+ }}+ className="gap-2 rounded-sm px-2 py-1.5 text-[12px] text-muted-foreground"+ >+ <X size={12} />+ {t('transactions.filtersBar.clearSelection')}+ </DropdownMenuItem>+ </>+ )}+ </DropdownMenuSubContent>+ </DropdownMenuPortal>+ </DropdownMenuSub>++ {/* Category submenu (multi) */}+ <DropdownMenuSub+ open={categorySubOpen}+ onOpenChange={handleCategorySubOpenChange}+ >+ <DropdownMenuSubTrigger className="gap-2 text-[13px]">+ <Tag size={14} className="text-muted-foreground" />+ <span className="flex-1">{t('transactions.category')}</span>+ {categorySummary && (+ <span className="max-w-[90px] truncate text-[11px] text-muted-foreground">+ {categorySummary}+ </span>+ )}+ </DropdownMenuSubTrigger>+ <DropdownMenuPortal>+ <DropdownMenuSubContent+ sideOffset={8}+ className="max-h-[320px] w-[240px] overflow-y-auto p-1"+ >+ <CheckRow+ checked={filterUncategorized}+ onToggle={() => {+ keepCategorySubOpenRef.current = true+ onUncategorizedChange(!filterUncategorized)+ }}+ label={t('transactions.uncategorized')}+ italic+ />+ <div className="my-1 h-px bg-border/60" />+ {categories.length === 0 ? (+ <div className="px-2 py-3 text-center text-[12px] text-muted-foreground">+ {t('transactions.filtersBar.noOptions')}+ </div>+ ) : (+ categories.map((c) => (+ <CheckRow+ key={c.id}+ checked={filterCategoryIds.includes(c.id)}+ onToggle={() => {+ keepCategorySubOpenRef.current = true+ onCategoryIdsChange(+ toggleInArray(filterCategoryIds, c.id),+ )+ }}+ label={c.name}+ swatchColor={c.color ?? undefined}+ />+ ))+ )}+ {(filterCategoryIds.length > 0 || filterUncategorized) && (+ <>+ <div className="my-1 h-px bg-border/60" />+ <DropdownMenuItem+ onSelect={(e) => {+ e.preventDefault()+ keepCategorySubOpenRef.current = true+ onCategoryIdsChange([])+ onUncategorizedChange(false)+ }}+ className="gap-2 rounded-sm px-2 py-1.5 text-[12px] text-muted-foreground"+ >+ <X size={12} />+ {t('transactions.filtersBar.clearSelection')}+ </DropdownMenuItem>+ </>+ )}+ </DropdownMenuSubContent>+ </DropdownMenuPortal>+ </DropdownMenuSub>++ {/* Payee submenu (single) */}+ <DropdownMenuSub>+ <DropdownMenuSubTrigger className="gap-2 text-[13px]">+ <Store size={14} className="text-muted-foreground" />+ <span className="flex-1">{t('payees.payee')}</span>+ {selectedPayee && (+ <span className="max-w-[90px] truncate text-[11px] text-muted-foreground">+ {selectedPayee.name}+ </span>+ )}+ </DropdownMenuSubTrigger>+ <DropdownMenuPortal>+ <DropdownMenuSubContent+ sideOffset={8}+ className="max-h-[320px] w-[240px] overflow-y-auto p-1"+ >+ <DropdownMenuItem+ onSelect={() => onPayeeChange('')}+ className={cn(+ 'gap-2 rounded-sm px-2 py-1.5 text-[13px]',+ !filterPayee && 'bg-primary/5',+ )}+ >+ <span className="size-2.5 shrink-0" />+ <span className="min-w-0 flex-1 truncate text-left">+ {t('transactions.all')}+ </span>+ {!filterPayee && <Check size={13} className="text-primary" />}+ </DropdownMenuItem>+ <div className="my-1 h-px bg-border/60" />+ {payees.length === 0 ? (+ <div className="px-2 py-3 text-center text-[12px] text-muted-foreground">+ {t('transactions.filtersBar.noOptions')}+ </div>+ ) : (+ payees.map((p) => (+ <DropdownMenuItem+ key={p.id}+ onSelect={() => onPayeeChange(p.id)}+ className={cn(+ 'gap-2 rounded-sm px-2 py-1.5 text-[13px]',+ filterPayee === p.id && 'bg-primary/5',+ )}+ >+ <span className="size-2.5 shrink-0" />+ <span className="min-w-0 flex-1 truncate text-left">+ {p.name}+ </span>+ {filterPayee === p.id && (+ <Check size={13} className="text-primary" />+ )}+ </DropdownMenuItem>+ ))+ )}+ </DropdownMenuSubContent>+ </DropdownMenuPortal>+ </DropdownMenuSub>++ {/* Date range submenu with presets */}+ <DropdownMenuSub>+ <DropdownMenuSubTrigger className="gap-2 text-[13px]">+ <CalendarIcon size={14} className="text-muted-foreground" />+ <span className="flex-1">+ {t('transactions.filtersBar.date')}+ </span>+ {dateLabel && (+ <span className="max-w-[90px] truncate text-[11px] text-muted-foreground">+ {dateLabel}+ </span>+ )}+ </DropdownMenuSubTrigger>+ <DropdownMenuPortal>+ <DropdownMenuSubContent+ sideOffset={8}+ className="w-[220px] p-1"+ >+ <DropdownMenuItem+ onSelect={() => onDateRangeChange('', '')}+ className={cn(+ 'gap-2 rounded-sm px-2 py-1.5 text-[13px]',+ !filterFrom && !filterTo && 'bg-primary/5',+ )}+ >+ <span className="size-2.5 shrink-0" />+ <span className="min-w-0 flex-1 truncate text-left">+ {t('transactions.all')}+ </span>+ {!filterFrom && !filterTo && (+ <Check size={13} className="text-primary" />+ )}+ </DropdownMenuItem>+ <div className="my-1 h-px bg-border/60" />+ {datePresets.map((preset) => {+ const active =+ filterFrom === preset.from && filterTo === preset.to+ return (+ <DropdownMenuItem+ key={preset.key}+ onSelect={() =>+ onDateRangeChange(preset.from, preset.to)+ }+ className={cn(+ 'gap-2 rounded-sm px-2 py-1.5 text-[13px]',+ active && 'bg-primary/5',+ )}+ >+ <span className="size-2.5 shrink-0" />+ <span className="min-w-0 flex-1 truncate text-left">+ {preset.label}+ </span>+ {active && <Check size={13} className="text-primary" />}+ </DropdownMenuItem>+ )+ })}+ <div className="my-1 h-px bg-border/60" />+ <DropdownMenuItem+ onSelect={openCustomRange}+ className="justify-between rounded-sm px-2 py-1.5 text-[13px]"+ >+ <span>{t('transactions.filtersBar.customRange')}</span>+ <ChevronRight+ size={13}+ className="text-muted-foreground/60"+ />+ </DropdownMenuItem>+ </DropdownMenuSubContent>+ </DropdownMenuPortal>+ </DropdownMenuSub>+ </DropdownMenuGroup>++ {hasAnyFilter && (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ onSelect={() => {+ onClearAll()+ setMenuOpen(false)+ }}+ className="gap-2 rounded-sm px-2 py-1.5 text-[12.5px] text-muted-foreground"+ >+ <X size={13} />+ {t('transactions.clearFilters')}+ </DropdownMenuItem>+ </>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ </div>++ {/* Bottom row: active filter chips (only when any are set) */}+ {(filterAccountIds.length > 0 ||+ filterCategoryIds.length > 0 ||+ filterUncategorized ||+ !!selectedPayee ||+ !!dateLabel) && (+ <div className="flex flex-wrap items-center gap-1 border-t border-border/60 px-2 py-1.5">+ {filterAccountIds.map((id) => {+ const account = accountById.get(id)+ if (!account) return null+ return (+ <FilterChip+ key={`acc-${id}`}+ icon={<Wallet size={12} />}+ label={t('transactions.account')}+ value={account.name}+ onRemove={() =>+ onAccountIdsChange(filterAccountIds.filter((x) => x !== id))+ }+ />+ )+ })}+ {filterCategoryIds.map((id) => {+ const cat = categoryById.get(id)+ if (!cat) return null+ return (+ <FilterChip+ key={`cat-${id}`}+ icon={<Tag size={12} />}+ label={t('transactions.category')}+ value={cat.name}+ tint={cat.color ?? undefined}+ onRemove={() =>+ onCategoryIdsChange(+ filterCategoryIds.filter((x) => x !== id),+ )+ }+ />+ )+ })}+ {filterUncategorized && (+ <FilterChip+ icon={<Tag size={12} />}+ label={t('transactions.category')}+ value={t('transactions.uncategorized')}+ onRemove={() => onUncategorizedChange(false)}+ />+ )}+ {selectedPayee && (+ <FilterChip+ icon={<Store size={12} />}+ label={t('payees.payee')}+ value={selectedPayee.name}+ onRemove={() => onPayeeChange('')}+ />+ )}+ {dateLabel && (+ <FilterChip+ icon={<CalendarIcon size={12} />}+ label={t('transactions.filtersBar.date')}+ value={dateLabel}+ onRemove={() => onDateRangeChange('', '')}+ />+ )}+ </div>+ )}+ </div>++ </PopoverAnchor>+ {/* Custom range popover — anchored to the filter bar above */}+ <PopoverContent+ align="end"+ sideOffset={8}+ className="w-auto p-0"+ onOpenAutoFocus={(e) => e.preventDefault()}+ >+ <div className="border-b border-border/70 px-4 py-3">+ <p className="text-[11px] font-semibold uppercase tracking-[0.08em] text-muted-foreground">+ {t('transactions.filtersBar.customRange')}+ </p>+ <p className="mt-0.5 text-[11px] text-muted-foreground/70">+ {draftFrom || draftTo+ ? formatRange(draftFrom, draftTo, locale)+ : t('transactions.filtersBar.pickRange')}+ </p>+ </div>+ <div className="flex flex-col gap-4 p-3 sm:flex-row sm:gap-0">+ <div className="sm:border-r sm:border-border/60 sm:pr-2">+ <p className="px-2 pb-1 text-[10.5px] font-semibold uppercase tracking-[0.08em] text-muted-foreground/80">+ {t('transactions.filtersBar.fromLabel')}+ </p>+ <Calendar+ selected={draftFrom ? new Date(draftFrom + 'T00:00:00') : undefined}+ defaultMonth={+ draftFrom ? new Date(draftFrom + 'T00:00:00') : new Date()+ }+ locale={dateFnsLocale}+ onSelect={(d) => setDraftFrom(d ? toISODate(d) : '')}+ />+ </div>+ <div className="sm:pl-2">+ <p className="px-2 pb-1 text-[10.5px] font-semibold uppercase tracking-[0.08em] text-muted-foreground/80">+ {t('transactions.filtersBar.toLabel')}+ </p>+ <Calendar+ selected={draftTo ? new Date(draftTo + 'T00:00:00') : undefined}+ defaultMonth={+ draftTo+ ? new Date(draftTo + 'T00:00:00')+ : draftFrom+ ? new Date(draftFrom + 'T00:00:00')+ : new Date()+ }+ locale={dateFnsLocale}+ onSelect={(d) => setDraftTo(d ? toISODate(d) : '')}+ />+ </div>+ </div>+ <div className="flex items-center justify-between gap-2 border-t border-border/70 px-3 py-2">+ <button+ type="button"+ onClick={() => {+ setDraftFrom('')+ setDraftTo('')+ }}+ className="text-[12px] font-medium text-muted-foreground transition-colors hover:text-foreground"+ >+ {t('transactions.filtersBar.reset')}+ </button>+ <div className="flex items-center gap-2">+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={() => setDateCustomOpen(false)}+ >+ {t('transactions.filtersBar.cancel')}+ </Button>+ <Button+ type="button"+ size="sm"+ disabled={!draftFrom && !draftTo}+ onClick={() => {+ // Normalize: if user only picked one of the two, mirror it.+ const from = draftFrom || draftTo+ const to = draftTo || draftFrom+ if (from && to && from > to) {+ onDateRangeChange(to, from)+ } else {+ onDateRangeChange(from, to)+ }+ setDateCustomOpen(false)+ }}+ >+ {t('transactions.filtersBar.apply')}+ </Button>+ </div>+ </div>+ </PopoverContent>+ </Popover>+ </div>+ )+}++function formatRange(from: string, to: string, locale: string): string {+ const fmt = (iso: string) =>+ new Date(iso + 'T00:00:00').toLocaleDateString(locale, {+ day: '2-digit',+ month: 'short',+ year: 'numeric',+ })+ if (from && to) return `${fmt(from)} — ${fmt(to)}`+ if (from) return `≥ ${fmt(from)}`+ return `≤ ${fmt(to)}`+}++interface FilterChipProps {+ icon: React.ReactNode+ label: string+ value: string+ tint?: string+ onRemove: () => void+}++function FilterChip({ icon, label, value, tint, onRemove }: FilterChipProps) {+ return (+ <button+ type="button"+ onClick={onRemove}+ className="group inline-flex h-7 shrink-0 items-center gap-1.5 rounded-full border border-border/80 bg-muted/50 pl-2 pr-1.5 text-[11.5px] text-foreground transition-colors hover:border-destructive/40 hover:bg-destructive/5"+ style={tint ? { borderColor: `${tint}55`, backgroundColor: `${tint}12` } : undefined}+ >+ <span+ className="flex items-center text-muted-foreground group-hover:text-destructive"+ style={tint ? { color: tint } : undefined}+ >+ {icon}+ </span>+ <span className="text-muted-foreground">{label}:</span>+ <span className="max-w-[140px] truncate font-medium text-foreground">+ {value}+ </span>+ <span className="ml-0.5 inline-flex h-4 w-4 items-center justify-center rounded-full text-muted-foreground/70 group-hover:text-destructive">+ <X size={11} />+ </span>+ </button>+ )+}++interface CheckRowProps {+ checked: boolean+ onToggle: () => void+ label: string+ sublabel?: string+ swatchColor?: string+ italic?: boolean+}++function CheckRow({+ checked,+ onToggle,+ label,+ sublabel,+ swatchColor,+ italic,+}: CheckRowProps) {+ return (+ <DropdownMenuItem+ onSelect={(e) => {+ // Keep the menu open so users can select multiple options.+ e.preventDefault()+ onToggle()+ }}+ className={cn(+ 'gap-2 rounded-sm px-2 py-1.5 text-[13px]',+ checked && 'bg-primary/5 data-[highlighted]:bg-primary/10',+ )}+ >+ <span+ className={cn(+ 'flex size-[14px] shrink-0 items-center justify-center rounded-[4px] border transition-colors',+ checked+ ? 'border-primary bg-primary text-primary-foreground'+ : 'border-border/80 bg-background',+ )}+ >+ {checked && <Check size={10} strokeWidth={3} />}+ </span>+ {swatchColor ? (+ <span+ className="size-2.5 shrink-0 rounded-full border border-black/5"+ style={{ backgroundColor: swatchColor }}+ />+ ) : null}+ <span+ className={cn(+ 'min-w-0 flex-1 truncate text-left',+ italic && 'italic text-muted-foreground',+ )}+ >+ {label}+ </span>+ {sublabel && (+ <span className="text-[10.5px] uppercase tracking-wide text-muted-foreground/70">+ {sublabel}+ </span>+ )}+ </DropdownMenuItem>+ )+}diff --git a/frontend/src/hooks/use-command-palette-hotkey.ts b/frontend/src/hooks/use-command-palette-hotkey.tsnew file mode 100644index 00000000..72b33518--- /dev/null+++ b/frontend/src/hooks/use-command-palette-hotkey.ts@@ -0,0 +1,22 @@+import { useEffect } from 'react'++/**+ * Registers a global Cmd/Ctrl+K listener that toggles the command palette.+ * Lives in its own file so the palette module can stay a pure component+ * export (keeps React Fast Refresh happy).+ */+export function useCommandPaletteHotkey(+ setOpen: (open: boolean | ((prev: boolean) => boolean)) => void+) {+ useEffect(() => {+ const handler = (e: KeyboardEvent) => {+ const isMod = e.metaKey || e.ctrlKey+ if (isMod && (e.key === 'k' || e.key === 'K')) {+ e.preventDefault()+ setOpen((prev) => !prev)+ }+ }+ document.addEventListener('keydown', handler)+ return () => document.removeEventListener('keydown', handler)+ }, [setOpen])+}diff --git a/frontend/src/index.css b/frontend/src/index.cssindex 5401ed66..1e8ae8db 100644--- a/frontend/src/index.css+++ b/frontend/src/index.css@@ -130,3 +130,22 @@letter-spacing: -0.035em;}}++@keyframes securo-highlight-flash {+ 0% {+ background-color: color-mix(in srgb, var(--primary) 22%, transparent);+ box-shadow: inset 3px 0 0 var(--primary);+ }+ 60% {+ background-color: color-mix(in srgb, var(--primary) 14%, transparent);+ box-shadow: inset 3px 0 0 var(--primary);+ }+ 100% {+ background-color: transparent;+ box-shadow: inset 3px 0 0 transparent;+ }+}++.securo-highlight-flash {+ animation: securo-highlight-flash 2.4s ease-out;+}diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 20565a12..5ea84970 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -232,7 +232,9 @@ export const accounts = {export const transactions = {list: async (params?: {account_id?: string+ account_ids?: string[]category_id?: string+ category_ids?: string[]payee_id?: stringuncategorized?: booleantype?: string@@ -244,7 +246,10 @@ export const transactions = {include_opening_balance?: booleanexclude_transfers?: boolean}): Promise<PaginatedResponse<Transaction>> => {- const { data } = await api.get('/transactions', { params })+ const { data } = await api.get('/transactions', {+ params,+ paramsSerializer: { indexes: null },+ })return data},get: async (id: string): Promise<Transaction> => {@@ -302,14 +307,20 @@ export const transactions = {},export: async (params?: {account_id?: string+ account_ids?: string[]category_id?: string+ category_ids?: string[]uncategorized?: booleantype?: stringfrom?: stringto?: stringq?: string}): Promise<void> => {- const { data } = await api.get('/transactions/export', { params, responseType: 'blob' })+ const { data } = await api.get('/transactions/export', {+ params,+ responseType: 'blob',+ paramsSerializer: { indexes: null },+ })const blob = new Blob([data], { type: 'text/csv;charset=utf-8;' })const url = URL.createObjectURL(blob)const a = document.createElement('a')@@ -652,4 +663,34 @@ export const admin = {},}+// Global search (powers the command palette)+export type SearchHitType =+ | 'transaction'+ | 'account'+ | 'payee'+ | 'category'+ | 'goal'+ | 'asset'++export interface SearchHit {+ type: SearchHitType+ id: string+ label: string+ subtitle: string | null+ amount: number | null+ currency: string | null+ date: string | null+ icon: string | null+ color: string | null+ meta: Record<string, unknown>+}++export const search = {+ query: async (q: string, limit = 5): Promise<SearchHit[]> => {+ if (!q.trim()) return []+ const { data } = await api.get('/search', { params: { q, limit } })+ return data.results as SearchHit[]+ },+}+export default apidiff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex 7c0bb74d..9705ac8e 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -2,6 +2,41 @@"app": {"name": "Securo"},+ "cmdk": {+ "title": "Command palette",+ "description": "Search transactions, accounts, categories and more.",+ "triggerLabel": "Search everything…",+ "triggerAria": "Open command palette",+ "placeholder": "What are you looking for?",+ "groups": {+ "recent": "Recent",+ "quickActions": "Quick actions",+ "navigation": "Go to",+ "transactions": "Transactions",+ "accounts": "Accounts",+ "payees": "Payees",+ "categories": "Categories",+ "goals": "Goals",+ "assets": "Assets"+ },+ "actions": {+ "newTransaction": "New transaction",+ "importFile": "Import CSV / OFX / QIF",+ "newBudget": "New budget",+ "newGoal": "New goal",+ "openReports": "Open reports"+ },+ "empty": {+ "title": "No results for \"{{query}}\"",+ "hint": "Try a different keyword, a payee name, or an amount."+ },+ "footer": {+ "tagline": "own your finances",+ "navigate": "navigate",+ "open": "open",+ "close": "close"+ }+ },"nav": {"dashboard": "Dashboard","transactions": "Transactions",@@ -179,7 +214,30 @@"transferDescription": "Description","transferNotes": "Notes","transferInfo": "This is a transfer — changes to description, date, and notes will apply to both sides",- "transferTooltip": "Transfers are excluded from report and dashboard totals"+ "transferTooltip": "Transfers are excluded from report and dashboard totals",+ "filtersBar": {+ "filters": "Filters",+ "filterBy": "Filter by",+ "date": "Date",+ "customRange": "Custom range…",+ "pickRange": "Pick a start and end date",+ "noOptions": "Nothing here yet",+ "nSelected": "{{count}} selected",+ "clearSelection": "Clear selection",+ "fromLabel": "From",+ "toLabel": "To",+ "reset": "Reset",+ "cancel": "Cancel",+ "apply": "Apply",+ "datePresets": {+ "today": "Today",+ "last7": "Last 7 days",+ "last30": "Last 30 days",+ "thisMonth": "This month",+ "last90": "Last 90 days",+ "thisYear": "This year"+ }+ }},"accounts": {"title": "Accounts",diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex 4f175077..a827ab18 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -2,6 +2,41 @@"app": {"name": "Securo"},+ "cmdk": {+ "title": "Paleta de comandos",+ "description": "Busque transações, contas, categorias e muito mais.",+ "triggerLabel": "Buscar em tudo…",+ "triggerAria": "Abrir paleta de comandos",+ "placeholder": "O que você está procurando?",+ "groups": {+ "recent": "Recentes",+ "quickActions": "Ações rápidas",+ "navigation": "Ir para",+ "transactions": "Transações",+ "accounts": "Contas",+ "payees": "Beneficiários",+ "categories": "Categorias",+ "goals": "Metas",+ "assets": "Patrimônio"+ },+ "actions": {+ "newTransaction": "Nova transação",+ "importFile": "Importar CSV / OFX / QIF",+ "newBudget": "Novo orçamento",+ "newGoal": "Nova meta",+ "openReports": "Abrir relatórios"+ },+ "empty": {+ "title": "Nenhum resultado para \"{{query}}\"",+ "hint": "Tente outra palavra, um beneficiário, ou um valor."+ },+ "footer": {+ "tagline": "controle total das suas finanças",+ "navigate": "navegar",+ "open": "abrir",+ "close": "fechar"+ }+ },"nav": {"dashboard": "Painel","transactions": "Transações",@@ -179,7 +214,30 @@"transferDescription": "Descrição","transferNotes": "Notas","transferInfo": "Esta é uma transferência — alterações na descrição, data e notas serão aplicadas em ambos os lados",- "transferTooltip": "Transferências são excluídas dos totais de relatórios e dashboard"+ "transferTooltip": "Transferências são excluídas dos totais de relatórios e dashboard",+ "filtersBar": {+ "filters": "Filtros",+ "filterBy": "Filtrar por",+ "date": "Data",+ "customRange": "Período personalizado…",+ "pickRange": "Escolha uma data inicial e final",+ "noOptions": "Nada por aqui ainda",+ "nSelected": "{{count}} selecionados",+ "clearSelection": "Limpar seleção",+ "fromLabel": "De",+ "toLabel": "Até",+ "reset": "Redefinir",+ "cancel": "Cancelar",+ "apply": "Aplicar",+ "datePresets": {+ "today": "Hoje",+ "last7": "Últimos 7 dias",+ "last30": "Últimos 30 dias",+ "thisMonth": "Este mês",+ "last90": "Últimos 90 dias",+ "thisYear": "Este ano"+ }+ }},"accounts": {"title": "Contas",diff --git a/frontend/src/pages/transactions.tsx b/frontend/src/pages/transactions.tsxindex 9a7f42c9..735947ab 100644--- a/frontend/src/pages/transactions.tsx+++ b/frontend/src/pages/transactions.tsx@@ -13,15 +13,14 @@ import {TableHeader,TableRow,} from '@/components/ui/table'-import { Input } from '@/components/ui/input'import { Skeleton } from '@/components/ui/skeleton'-import { AlertTriangle, ArrowLeftRight, Check, Download, HelpCircle, Paperclip, Search, X } from 'lucide-react'+import { AlertTriangle, ArrowLeftRight, Check, Download, HelpCircle, Paperclip, X } from 'lucide-react'import type { Transaction } from '@/types'import { PageHeader } from '@/components/page-header'import { CategoryIcon } from '@/components/category-icon'import { TransactionDialog, extractApiError } from '@/components/transaction-dialog'import { TransferDialog } from '@/components/transfer-dialog'-import { DatePickerInput } from '@/components/ui/date-picker-input'+import { TransactionsFilterBar } from '@/components/transactions-filter-bar'import { usePrivacyMode } from '@/hooks/use-privacy-mode'import { useAuth } from '@/contexts/auth-context'@@ -44,12 +43,16 @@ export default function TransactionsPage() {const userCurrency = user?.preferences?.currency_display ?? 'USD'const queryClient = useQueryClient()const [page, setPage] = useState(1)- const [filterAccount, setFilterAccount] = useState<string>('')- const [filterCategory, setFilterCategory] = useState<string>('')+ const [filterAccountIds, setFilterAccountIds] = useState<string[]>([])+ const [filterCategoryIds, setFilterCategoryIds] = useState<string[]>(() => {+ const initial = searchParams.get('category_id')+ return initial ? [initial] : []+ })+ const [filterUncategorized, setFilterUncategorized] = useState<boolean>(false)const [filterFrom, setFilterFrom] = useState<string>('')const [filterTo, setFilterTo] = useState<string>('')- const [searchInput, setSearchInput] = useState('')- const [searchQuery, setSearchQuery] = useState('')+ const [searchInput, setSearchInput] = useState(() => searchParams.get('q') ?? '')+ const [searchQuery, setSearchQuery] = useState(() => searchParams.get('q') ?? '')const [dialogOpen, setDialogOpen] = useState(false)const [editingTx, setEditingTx] = useState<Transaction | null>(null)const [filterPayee, setFilterPayee] = useState<string>(searchParams.get('payee_id') ?? '')@@ -59,6 +62,22 @@ export default function TransactionsPage() {const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())const [bulkCategory, setBulkCategory] = useState<string>('')const debounceRef = useRef<ReturnType<typeof setTimeout>>(null)+ const highlightId = searchParams.get('highlight')+ const highlightedRowRef = useRef<HTMLTableRowElement | null>(null)++ // Sync state from URL when navigating (e.g. from the command palette) while+ // the page is already mounted. Typing in the search box does not touch the+ // URL, so this effect only fires on genuine navigation events.+ useEffect(() => {+ const nextQ = searchParams.get('q') ?? ''+ setSearchInput(nextQ)+ setSearchQuery(nextQ)+ setFilterPayee(searchParams.get('payee_id') ?? '')+ const nextCategory = searchParams.get('category_id')+ setFilterCategoryIds(nextCategory ? [nextCategory] : [])+ setFilterUncategorized(false)+ setPage(1)+ }, [searchParams])useEffect(() => {if (debounceRef.current) clearTimeout(debounceRef.current)@@ -73,18 +92,39 @@ export default function TransactionsPage() {useEffect(() => {setSelectedIds(new Set())setBulkCategory('')- }, [page, filterAccount, filterCategory, filterPayee, filterFrom, filterTo, searchQuery])+ }, [page, filterAccountIds, filterCategoryIds, filterUncategorized, filterPayee, filterFrom, filterTo, searchQuery])++ // Scroll to and flash a highlighted row after navigation (e.g. opened via+ // the command palette). Re-runs whenever highlightId or the current data+ // set changes so that when results finish loading we animate the row.+ useEffect(() => {+ if (!highlightId) return+ const el = highlightedRowRef.current+ if (!el) return+ const raf = requestAnimationFrame(() => {+ el.scrollIntoView({ behavior: 'smooth', block: 'center' })+ el.classList.add('securo-highlight-flash')+ })+ const timer = setTimeout(() => {+ el.classList.remove('securo-highlight-flash')+ }, 2500)+ return () => {+ cancelAnimationFrame(raf)+ clearTimeout(timer)+ el.classList.remove('securo-highlight-flash')+ }+ }, [highlightId, searchQuery, filterPayee, filterCategoryIds, page])const { data, isLoading } = useQuery({- queryKey: ['transactions', page, filterAccount, filterCategory, filterPayee, filterFrom, filterTo, searchQuery],+ queryKey: ['transactions', page, filterAccountIds, filterCategoryIds, filterUncategorized, filterPayee, filterFrom, filterTo, searchQuery],queryFn: () =>transactions.list({page,limit: 20,- account_id: filterAccount || undefined,- category_id: filterCategory === '__uncategorized__' ? undefined : (filterCategory || undefined),+ account_ids: filterAccountIds.length > 0 ? filterAccountIds : undefined,+ category_ids: filterCategoryIds.length > 0 ? filterCategoryIds : undefined,payee_id: filterPayee || undefined,- uncategorized: filterCategory === '__uncategorized__' ? true : undefined,+ uncategorized: filterUncategorized ? true : undefined,from: filterFrom || undefined,to: filterTo || undefined,q: searchQuery || undefined,@@ -256,9 +296,9 @@ export default function TransactionsPage() {setExporting(true)try {await transactions.export({- account_id: filterAccount || undefined,- category_id: filterCategory === '__uncategorized__' ? undefined : (filterCategory || undefined),- uncategorized: filterCategory === '__uncategorized__' ? true : undefined,+ account_ids: filterAccountIds.length > 0 ? filterAccountIds : undefined,+ category_ids: filterCategoryIds.length > 0 ? filterCategoryIds : undefined,+ uncategorized: filterUncategorized ? true : undefined,from: filterFrom || undefined,to: filterTo || undefined,q: searchQuery || undefined,@@ -286,92 +326,46 @@ export default function TransactionsPage() {/>{/* Filters */}- <div className="bg-card rounded-xl border border-border shadow-sm p-3 md:p-4 mb-4">- <div className="flex flex-col gap-2 md:flex-row md:flex-wrap md:items-end md:gap-3">- <div className="relative w-full md:w-auto">- <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" size={16} />- <Input- type="text"- placeholder={t('transactions.searchPlaceholder')}- value={searchInput}- onChange={(e) => setSearchInput(e.target.value)}- className="pl-9 w-full md:w-[240px] h-[38px] text-sm"- />- </div>- <div className="grid grid-cols-2 gap-2 md:flex md:gap-3">- <select- className="border border-border rounded-lg px-3 py-2 text-sm bg-card text-foreground focus:outline-none focus-visible:ring-ring/30 focus-visible:ring-[2px] min-w-0"- value={filterAccount}- onChange={(e) => { setFilterAccount(e.target.value); setPage(1) }}- >- <option value="">{t('transactions.account')}: {t('transactions.all')}</option>- {accountsList?.map((acc) => (- <option key={acc.id} value={acc.id}>{acc.name}</option>- ))}- </select>- <select- className="border border-border rounded-lg px-3 py-2 text-sm bg-card text-foreground focus:outline-none focus-visible:ring-ring/30 focus-visible:ring-[2px] min-w-0"- value={filterCategory}- onChange={(e) => { setFilterCategory(e.target.value); setPage(1) }}- >- <option value="">{t('transactions.category')}: {t('transactions.all')}</option>- <option value="__uncategorized__">{t('transactions.uncategorized')}</option>- {categoriesList?.map((cat) => (- <option key={cat.id} value={cat.id}>{cat.name}</option>- ))}- </select>- <select- className="border border-border rounded-lg px-3 py-2 text-sm bg-card text-foreground focus:outline-none focus-visible:ring-ring/30 focus-visible:ring-[2px] min-w-0"- value={filterPayee}- onChange={(e) => { setFilterPayee(e.target.value); setPage(1) }}- >- <option value="">{t('payees.payee')}: {t('transactions.all')}</option>- {payeesList?.map((p) => (- <option key={p.id} value={p.id}>{p.name}</option>- ))}- </select>- </div>- <div className="grid grid-cols-2 gap-2 md:flex md:gap-3">- <div className="flex items-center gap-2">- <label className="hidden md:inline text-sm text-muted-foreground">{t('transactions.from')}</label>- <DatePickerInput- value={filterFrom}- onChange={(v) => { setFilterFrom(v); setPage(1) }}- placeholder={t('transactions.from')}- />- </div>- <div className="flex items-center gap-2">- <label className="hidden md:inline text-sm text-muted-foreground">{t('transactions.to')}</label>- <DatePickerInput- value={filterTo}- onChange={(v) => { setFilterTo(v); setPage(1) }}- placeholder={t('transactions.to')}- />- </div>- </div>- {(filterFrom || filterTo || filterAccount || filterCategory || filterPayee || searchInput) && (- <Button- variant="ghost"- size="sm"- className="text-muted-foreground hover:text-foreground"- onClick={() => { setFilterFrom(''); setFilterTo(''); setFilterAccount(''); setFilterCategory(''); setFilterPayee(''); setSearchInput(''); setSearchQuery(''); setPage(1) }}- >- {t('transactions.clearFilters')}- </Button>- )}- {tagFilter && (- <div className="flex items-center gap-1.5 px-3 py-1.5 bg-primary/5 border border-primary/10 rounded-lg text-xs text-primary font-medium">- <span>{tagFilter}</span>- <button- onClick={() => setTagFilter(null)}- className="text-primary/60 hover:text-primary ml-0.5"- >- <X size={12} />- </button>- </div>- )}+ <TransactionsFilterBar+ searchInput={searchInput}+ onSearchChange={(v) => setSearchInput(v)}+ filterAccountIds={filterAccountIds}+ onAccountIdsChange={(v) => { setFilterAccountIds(v); setPage(1) }}+ filterCategoryIds={filterCategoryIds}+ onCategoryIdsChange={(v) => { setFilterCategoryIds(v); setPage(1) }}+ filterUncategorized={filterUncategorized}+ onUncategorizedChange={(v) => { setFilterUncategorized(v); setPage(1) }}+ filterPayee={filterPayee}+ onPayeeChange={(v) => { setFilterPayee(v); setPage(1) }}+ filterFrom={filterFrom}+ filterTo={filterTo}+ onDateRangeChange={(from, to) => { setFilterFrom(from); setFilterTo(to); setPage(1) }}+ onClearAll={() => {+ setFilterFrom('')+ setFilterTo('')+ setFilterAccountIds([])+ setFilterCategoryIds([])+ setFilterUncategorized(false)+ setFilterPayee('')+ setSearchInput('')+ setSearchQuery('')+ setPage(1)+ }}+ accounts={accountsList ?? []}+ categories={categoriesList ?? []}+ payees={payeesList ?? []}+ />+ {tagFilter && (+ <div className="mb-4 inline-flex items-center gap-1.5 rounded-full border border-primary/15 bg-primary/5 px-3 py-1 text-xs font-medium text-primary">+ <span>{tagFilter}</span>+ <button+ onClick={() => setTagFilter(null)}+ className="ml-0.5 text-primary/60 hover:text-primary"+ >+ <X size={12} />+ </button></div>- </div>+ )}{/* Table */}<div className="bg-card rounded-xl border border-border shadow-sm overflow-hidden mb-4">@@ -404,6 +398,7 @@ export default function TransactionsPage() {{filteredItems.map((tx) => (<TableRowkey={tx.id}+ ref={tx.id === highlightId ? highlightedRowRef : undefined}className={`cursor-pointer hover:bg-muted border-b border-border last:border-0 ${selectedIds.has(tx.id) ? 'bg-primary/5' : ''}`}onClick={() => { setEditingTx(tx); setDialogOpen(true) }}>