Open-source personal finance manager. Self-hosted, privacy-first.
feat: tag system overhaul on exact match (#88) (#108)
Tássio Noronha75d2649f1036
diff --git a/.gitignore b/.gitignoreindex c1ad6614..7747a789 100644--- a/.gitignore+++ b/.gitignore@@ -4,3 +4,4 @@.playwright-mcp/.claudedocs/plans/+tmp/diff --git a/backend/app/api/transactions.py b/backend/app/api/transactions.pyindex 88d630ec..757d121f 100644--- a/backend/app/api/transactions.py+++ b/backend/app/api/transactions.py@@ -12,7 +12,7 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom app.core.auth import current_active_userfrom app.core.database import get_async_sessionfrom app.models.user import User-from app.schemas.transaction import BulkCategorizeRequest, LinkTransferRequest, TransactionCreate, TransactionRead, TransactionUpdate, TransferCreate, TransferRead+from app.schemas.transaction import BulkCategorizeRequest, BulkTagsRequest, LinkTransferRequest, TransactionCreate, TransactionRead, TransactionUpdate, TransferCreate, TransferReadfrom app.services import transaction_servicefrom app.services.admin_service import get_credit_card_accounting_mode@@ -61,6 +61,7 @@ async def list_transactions(limit: int = Query(50, ge=1, le=500),include_opening_balance: bool = Query(False),exclude_transfers: bool = Query(False),+ tags: Optional[List[str]] = Query(None),session: AsyncSession = Depends(get_async_session),user: User = Depends(current_active_user),):@@ -73,6 +74,7 @@ async def list_transactions(include_opening_balance=include_opening_balance, search=q, uncategorized=uncategorized,txn_type=type, exclude_transfers=exclude_transfers,accounting_mode=accounting_mode,+ tags=tags,)primary_currency = user.primary_currencyitems = [_tag_fx_fallback(TransactionRead.model_validate(tx, from_attributes=True), primary_currency) for tx in transactions]@@ -91,6 +93,7 @@ async def export_transactions(q: Optional[str] = Query(None),uncategorized: bool = Query(False),type: Optional[str] = Query(None),+ tags: Optional[List[str]] = Query(None),session: AsyncSession = Depends(get_async_session),user: User = Depends(current_active_user),):@@ -102,6 +105,7 @@ async def export_transactions(payee_id=payee_id, from_date=from_date, to_date=to_date,search=q, uncategorized=uncategorized, txn_type=type, skip_pagination=True,accounting_mode=accounting_mode,+ tags=tags,)output = io.StringIO()@@ -147,6 +151,30 @@ async def bulk_categorize(return {"updated": count}[email protected]("/bulk-add-tags")+async def bulk_add_tags(+ data: BulkTagsRequest,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ count = await transaction_service.bulk_add_tags(+ session, user.id, data.transaction_ids, data.tags+ )+ return {"updated": count}++[email protected]("/bulk-remove-tags")+async def bulk_remove_tags(+ data: BulkTagsRequest,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ count = await transaction_service.bulk_remove_tags(+ session, user.id, data.transaction_ids, data.tags+ )+ return {"updated": count}++@router.post("/transfer", response_model=TransferRead, status_code=status.HTTP_201_CREATED)async def create_transfer(data: TransferCreate,diff --git a/backend/app/schemas/transaction.py b/backend/app/schemas/transaction.pyindex 6ab04cfd..27782f8a 100644--- a/backend/app/schemas/transaction.py+++ b/backend/app/schemas/transaction.py@@ -88,6 +88,11 @@ class LinkTransferRequest(BaseModel):transaction_ids: list[uuid.UUID]+class BulkTagsRequest(BaseModel):+ transaction_ids: list[uuid.UUID]+ tags: list[str]++class TransferRead(BaseModel):debit: TransactionReadcredit: TransactionReaddiff --git a/backend/app/services/transaction_service.py b/backend/app/services/transaction_service.pyindex 1a734121..e659c578 100644--- a/backend/app/services/transaction_service.py+++ b/backend/app/services/transaction_service.py@@ -1,3 +1,4 @@+import reimport uuidfrom datetime import datefrom typing import Optional@@ -62,6 +63,7 @@ async def get_transactions(account_ids: Optional[list[uuid.UUID]] = None,category_ids: Optional[list[uuid.UUID]] = None,accounting_mode: Optional[str] = None,+ tags: Optional[list[str]] = None,) -> tuple[list[Transaction], int]:# In "accrual" mode, bucket/order by effective_date so list filters# line up with the cash-flow view used by the dashboard and reports.@@ -122,6 +124,22 @@ async def get_transactions(Payee.name.ilike(term),))+ if tags:+ # Exact tag match using portable ILIKE patterns so `#test` never+ # matches `#test2`. Multiple tags are OR-combined (union) — a row+ # matches if it carries ANY of the requested tags. The four boundary+ # variants cover position at start / middle / end / standalone+ # (issue #88).+ clauses = []+ for raw_tag in tags:+ tag = raw_tag if raw_tag.startswith("#") else f"#{raw_tag}"+ clauses.extend([+ Transaction.notes == tag,+ Transaction.notes.ilike(f"{tag} %"),+ Transaction.notes.ilike(f"% {tag}"),+ Transaction.notes.ilike(f"% {tag} %"),+ ])+ base_query = base_query.where(or_(*clauses))# Get total countcount_query = select(func.count()).select_from(base_query.subquery())@@ -596,6 +614,97 @@ async def bulk_update_category(return result.rowcount+_TAG_CHAR_CLASS = r"[\wÀ-ž-]"+++def _normalize_tag(tag: str) -> str:+ """Return the tag in canonical `#foo` form."""+ return tag if tag.startswith("#") else f"#{tag}"+++def _parse_hashtags(notes: Optional[str]) -> list[str]:+ if not notes:+ return []+ return re.findall(rf"#{_TAG_CHAR_CLASS}+", notes)+++async def bulk_add_tags(+ session: AsyncSession,+ user_id: uuid.UUID,+ transaction_ids: list[uuid.UUID],+ tags: list[str],+) -> int:+ """Append the given tags to each transaction's `notes`, skipping tags+ that are already present. Returns the number of rows modified (issue #88)."""+ if not transaction_ids or not tags:+ return 0++ normalized_tags = [_normalize_tag(t.strip()) for t in tags if t and t.strip()]+ if not normalized_tags:+ return 0++ result = await session.execute(+ select(Transaction).where(+ Transaction.id.in_(transaction_ids),+ Transaction.user_id == user_id,+ )+ )+ touched = 0+ for tx in result.scalars().all():+ existing = set(_parse_hashtags(tx.notes))+ to_add = [t for t in normalized_tags if t not in existing]+ if not to_add:+ continue+ new_notes = (tx.notes.rstrip() + " " if tx.notes else "") + " ".join(to_add)+ tx.notes = new_notes.strip()+ touched += 1++ await session.commit()+ return touched+++async def bulk_remove_tags(+ session: AsyncSession,+ user_id: uuid.UUID,+ transaction_ids: list[uuid.UUID],+ tags: list[str],+) -> int:+ if not transaction_ids or not tags:+ return 0++ normalized_tags = [_normalize_tag(t.strip()) for t in tags if t and t.strip()]+ if not normalized_tags:+ return 0++ result = await session.execute(+ select(Transaction).where(+ Transaction.id.in_(transaction_ids),+ Transaction.user_id == user_id,+ )+ )+ touched = 0+ for tx in result.scalars().all():+ if not tx.notes:+ continue+ original = tx.notes+ updated = original+ for tag in normalized_tags:+ pattern = (+ r"(?:(?<=^)|(?<=[^\wÀ-ž-]))"+ + re.escape(tag)+ + r"(?=$|[^\wÀ-ž-])"+ )+ updated = re.sub(pattern, "", updated)+ # Collapse consecutive whitespace left behind by removed tags.+ updated = re.sub(r"\s{2,}", " ", updated).strip()+ if updated != original:+ tx.notes = updated or None+ touched += 1++ await session.commit()+ return touched++async def delete_transaction(session: AsyncSession, transaction_id: uuid.UUID, user_id: uuid.UUID) -> bool:diff --git a/backend/tests/test_transaction_service.py b/backend/tests/test_transaction_service.pyindex 789330d3..adf0ea01 100644--- a/backend/tests/test_transaction_service.py+++ b/backend/tests/test_transaction_service.py@@ -12,6 +12,8 @@ from app.models.transaction import Transactionfrom app.schemas.transaction import TransactionCreate, TransactionUpdate, TransferCreatefrom app.services.transaction_service import (_apply_fx_override,+ bulk_add_tags,+ bulk_remove_tags,bulk_update_category,create_transaction,create_transfer,@@ -945,3 +947,138 @@ async def test_update_transfer_rejects_collapsing_accounts(session, debit_tx.id, test_user.id,TransactionUpdate(account_id=acct2.id),)+++# ---------------------------------------------------------------------------+# Tag filtering and bulk tag operations (issue #88)+# ---------------------------------------------------------------------------+++async def test_get_transactions_filters_tags_with_exact_match(+ session: AsyncSession, test_user, txn_account+):+ """Filtering by `#test` must NOT match `#test2` — exact tag boundaries."""+ txns = [+ Transaction(+ id=uuid.uuid4(), user_id=test_user.id, account_id=txn_account.id,+ description=desc, amount=Decimal("10"), date=date(2026, 1, day),+ type="debit", source="manual", notes=notes,+ created_at=datetime.now(timezone.utc),+ )+ for day, desc, notes in [+ (1, "A", "spent on lunch #test"),+ (2, "B", "#test2 work meal"),+ (3, "C", "#TEST uppercase variant"),+ (4, "D", "no tag here"),+ (5, "E", "#test #hey both"),+ ]+ ]+ session.add_all(txns)+ await session.commit()++ matches, total = await get_transactions(+ session, test_user.id, tags=["#test"]+ )+ descriptions = {tx.description for tx in matches}+ assert descriptions == {"A", "C", "E"}+ assert total == 3+++async def test_get_transactions_filters_multiple_tags_with_or(+ session: AsyncSession, test_user, txn_account+):+ """Multiple `tags` are OR-combined: a row matches if it carries ANY+ of the requested tags — issue #88."""+ txns = [+ Transaction(+ id=uuid.uuid4(), user_id=test_user.id, account_id=txn_account.id,+ description=desc, amount=Decimal("10"), date=date(2026, 1, day),+ type="debit", source="manual", notes=notes,+ created_at=datetime.now(timezone.utc),+ )+ for day, desc, notes in [+ (1, "A", "#test only"),+ (2, "B", "#hey only"),+ (3, "C", "#test and #hey together"),+ (4, "D", "#unrelated"),+ ]+ ]+ session.add_all(txns)+ await session.commit()++ matches, _ = await get_transactions(+ session, test_user.id, tags=["#test", "#hey"]+ )+ assert {tx.description for tx in matches} == {"A", "B", "C"}+++async def test_bulk_add_tags_appends_to_each_transaction(+ session: AsyncSession, test_user, txn_account+):+ """bulk_add_tags must add the given tags to each tx, skipping duplicates."""+ t1 = Transaction(+ id=uuid.uuid4(), user_id=test_user.id, account_id=txn_account.id,+ description="A", amount=Decimal("10"), date=date.today(),+ type="debit", source="manual", notes=None,+ created_at=datetime.now(timezone.utc),+ )+ t2 = Transaction(+ id=uuid.uuid4(), user_id=test_user.id, account_id=txn_account.id,+ description="B", amount=Decimal("10"), date=date.today(),+ type="debit", source="manual", notes="existing #work note",+ created_at=datetime.now(timezone.utc),+ )+ t3 = Transaction(+ id=uuid.uuid4(), user_id=test_user.id, account_id=txn_account.id,+ description="C", amount=Decimal("10"), date=date.today(),+ type="debit", source="manual", notes="#groceries already here",+ created_at=datetime.now(timezone.utc),+ )+ session.add_all([t1, t2, t3])+ await session.commit()++ touched = await bulk_add_tags(+ session, test_user.id, [t1.id, t2.id, t3.id], ["#groceries"]+ )+ assert touched == 2 # t3 already has it++ await session.refresh(t1)+ await session.refresh(t2)+ await session.refresh(t3)+ assert t1.notes == "#groceries"+ assert t2.notes == "existing #work note #groceries"+ assert t3.notes == "#groceries already here"+++async def test_bulk_remove_tags_clears_only_exact_matches(+ session: AsyncSession, test_user, txn_account+):+ """Removing `#test` must NOT touch `#test2` — exact match boundary."""+ t1 = Transaction(+ id=uuid.uuid4(), user_id=test_user.id, account_id=txn_account.id,+ description="A", amount=Decimal("10"), date=date.today(),+ type="debit", source="manual", notes="#test #keep",+ created_at=datetime.now(timezone.utc),+ )+ t2 = Transaction(+ id=uuid.uuid4(), user_id=test_user.id, account_id=txn_account.id,+ description="B", amount=Decimal("10"), date=date.today(),+ type="debit", source="manual", notes="#test2 untouched",+ created_at=datetime.now(timezone.utc),+ )+ session.add_all([t1, t2])+ await session.commit()++ touched = await bulk_remove_tags(+ session, test_user.id, [t1.id, t2.id], ["#test"]+ )+ assert touched == 1++ await session.refresh(t1)+ await session.refresh(t2)+ assert t1.notes == "#keep"+ assert t2.notes == "#test2 untouched"diff --git a/frontend/src/components/transactions-filter-bar.tsx b/frontend/src/components/transactions-filter-bar.tsxindex edfd020d..b8c5659c 100644--- a/frontend/src/components/transactions-filter-bar.tsx+++ b/frontend/src/components/transactions-filter-bar.tsx@@ -34,7 +34,6 @@ import {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'@@ -42,6 +41,7 @@ import type { Account, Category, Payee } from '@/types'interface TransactionsFilterBarProps {searchInput: stringonSearchChange: (value: string) => void+ onSearchSubmit?: (value: string) => voidfilterAccountIds: string[]onAccountIdsChange: (value: string[]) => voidfilterCategoryIds: string[]@@ -70,6 +70,7 @@ function toggleInArray(arr: string[], id: string): string[] {export function TransactionsFilterBar({searchInput,onSearchChange,+ onSearchSubmit,filterAccountIds,onAccountIdsChange,filterCategoryIds,@@ -245,21 +246,15 @@ export function TransactionsFilterBar({>{/* 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>+ {/* Search input — splits committed `#tag` tokens into inline chips,+ keeping free text as plain typing. Comma or space commits a token. */}+ <SearchWithTagChips+ inputRef={searchRef}+ value={searchInput}+ placeholder={t('transactions.searchPlaceholder')}+ onChange={onSearchChange}+ onSubmit={onSearchSubmit}+ />{/* Right-side controls */}<div className="ml-auto flex shrink-0 items-center gap-1 pl-1">@@ -849,3 +844,133 @@ function CheckRow({</DropdownMenuItem>)}+++// Search input with inline `#tag` chips. Free text is a normal input;+// `#`-prefixed words become purple chips when committed via comma, space+// (when token starts with `#`), or Enter, and immediately apply as filters.+function SearchWithTagChips({+ inputRef,+ value,+ placeholder,+ onChange,+ onSubmit,+}: {+ inputRef: React.RefObject<HTMLInputElement | null>+ value: string+ placeholder?: string+ onChange: (value: string) => void+ onSubmit?: (value: string) => void+}) {+ // Split into leading `#tag` chips (terminated by whitespace) + free text.+ // We only treat a `#tag` as a chip when it has a trailing whitespace —+ // otherwise the user is still typing it.+ const [chips, freeText] = (() => {+ const parts: string[] = []+ let rest = value+ while (true) {+ const m = rest.match(/^(#\S+)\s+/)+ if (!m) break+ parts.push(m[1])+ rest = rest.slice(m[0].length)+ }+ return [parts, rest] as const+ })()++ const rebuild = (nextChips: string[], nextFreeText: string): string => {+ const head = nextChips.length ? nextChips.join(' ') + ' ' : ''+ return head + nextFreeText+ }++ const removeChipAt = (index: number) => {+ const next = [...chips]+ next.splice(index, 1)+ onChange(rebuild(next, freeText))+ inputRef.current?.focus()+ }++ const commitTrailingTagInFreeText = (text: string): { newChips: string[]; rest: string } | null => {+ // Match a `#tag` that ends the string (just typed before comma/space/Enter).+ const m = text.match(/^(.*?)(\s|^)(#\S+)$/)+ if (!m) return null+ const before = (m[1] + m[2]).trimEnd()+ const tag = m[3]+ const newChips = [...chips, tag]+ return { newChips, rest: before }+ }++ return (+ <div+ className="relative flex min-w-0 flex-1 flex-wrap items-center gap-1 px-2.5 py-1 min-h-9 cursor-text"+ onClick={() => inputRef.current?.focus()}+ >+ <Search size={15} className="pointer-events-none shrink-0 text-muted-foreground/70" />+ {chips.map((tag, i) => (+ <span+ key={`${tag}-${i}`}+ className="inline-flex items-center gap-1 rounded-full border border-primary/15 bg-primary/5 px-2 py-0.5 text-[11.5px] font-medium text-primary"+ >+ {tag}+ <button+ type="button"+ tabIndex={-1}+ onClick={(e) => {+ e.stopPropagation()+ removeChipAt(i)+ }}+ className="text-primary/60 hover:text-primary"+ >+ <X size={10} />+ </button>+ </span>+ ))}+ <input+ ref={inputRef}+ type="text"+ placeholder={chips.length === 0 ? placeholder : undefined}+ value={freeText}+ onChange={(e) => {+ const next = e.target.value+ // Comma right after a `#tag` token commits it. Other commas stay+ // as literal characters in the free-text search.+ if (next.endsWith(',')) {+ const beforeComma = next.slice(0, -1)+ const result = commitTrailingTagInFreeText(beforeComma)+ if (result) {+ const submitValue = rebuild(result.newChips, result.rest)+ if (onSubmit) onSubmit(submitValue)+ else onChange(submitValue)+ return+ }+ }+ onChange(rebuild(chips, next))+ }}+ onKeyDown={(e) => {+ if (e.key === 'Enter' && onSubmit) {+ e.preventDefault()+ // Promote a still-being-typed `#tag` at the end to a chip too.+ const result = commitTrailingTagInFreeText(freeText)+ const submitValue = result+ ? rebuild(result.newChips, result.rest)+ : rebuild(chips, freeText)+ onSubmit(submitValue)+ } else if (e.key === 'Backspace' && freeText === '' && chips.length > 0) {+ e.preventDefault()+ removeChipAt(chips.length - 1)+ } else if (e.key === ' ') {+ // Space after a `#tag` commits it; space inside free text is+ // a normal whitespace.+ const result = commitTrailingTagInFreeText(freeText)+ if (result) {+ e.preventDefault()+ const submitValue = rebuild(result.newChips, result.rest)+ if (onSubmit) onSubmit(submitValue)+ else onChange(submitValue)+ }+ }+ }}+ className="min-w-[80px] flex-1 border-0 bg-transparent text-[13.5px] outline-none placeholder:text-muted-foreground"+ />+ </div>+ )+}diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex a2c0b13a..01748489 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -257,6 +257,7 @@ export const transactions = {limit?: numberinclude_opening_balance?: booleanexclude_transfers?: boolean+ tags?: string[]}): Promise<PaginatedResponse<Transaction>> => {const { data } = await api.get('/transactions', {params,@@ -298,6 +299,20 @@ export const transactions = {})return data},+ bulkAddTags: async (transactionIds: string[], tags: string[]): Promise<{ updated: number }> => {+ const { data } = await api.patch('/transactions/bulk-add-tags', {+ transaction_ids: transactionIds,+ tags,+ })+ return data+ },+ bulkRemoveTags: async (transactionIds: string[], tags: string[]): Promise<{ updated: number }> => {+ const { data } = await api.patch('/transactions/bulk-remove-tags', {+ transaction_ids: transactionIds,+ tags,+ })+ return data+ },linkTransfer: async (transactionIds: string[]): Promise<{ debit: Transaction; credit: Transaction; transfer_pair_id: string }> => {const { data } = await api.post('/transactions/link-transfer', {transaction_ids: transactionIds,diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex ca32e3fd..7a9b656d 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -179,7 +179,7 @@"exportError": "Failed to export transactions","syncedInfo": "Bank-synced transaction — only category and notes can be edited","uncategorized": "Uncategorized",- "selected": "{{count}} selected",+ "selected": "selected","bulkCategorize": "Apply","bulkSuccess": "{{count}} transactions categorized","selectCategory": "Select category...",diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex 417084dd..d2993af5 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -179,7 +179,7 @@"exportError": "Erro ao exportar transações","syncedInfo": "Transação sincronizada — apenas categoria e notas podem ser editadas","uncategorized": "Sem categoria",- "selected": "{{count}} selecionadas",+ "selected": "selecionadas","bulkCategorize": "Aplicar","bulkSuccess": "{{count}} transações categorizadas","selectCategory": "Selecionar categoria...",diff --git a/frontend/src/pages/transactions.tsx b/frontend/src/pages/transactions.tsxindex 83aa2299..02ab80aa 100644--- a/frontend/src/pages/transactions.tsx+++ b/frontend/src/pages/transactions.tsx@@ -61,12 +61,27 @@ export default function TransactionsPage() {const [formResetKey, setFormResetKey] = useState(0)const [duplicateDraft, setDuplicateDraft] = useState<Partial<Transaction> | null>(null)const [filterPayee, setFilterPayee] = useState<string>(searchParams.get('payee_id') ?? '')- const [tagFilter, setTagFilter] = useState<string | null>(null)+ const [tagFilters, setTagFilters] = useState<string[]>([])++ const addTagFilter = (tag: string) => {+ const normalized = tag.startsWith('#') ? tag : `#${tag}`+ setTagFilters(prev => (prev.includes(normalized) ? prev : [...prev, normalized]))+ setPage(1)+ }+ const removeTagFilter = (tag: string) => {+ setTagFilters(prev => prev.filter(t => t !== tag))+ setPage(1)+ }+ const clearTagFilters = () => {+ setTagFilters([])+ setPage(1)+ }const [exporting, setExporting] = useState(false)const [transferDialogOpen, setTransferDialogOpen] = useState(false)const [linkTransferDialogOpen, setLinkTransferDialogOpen] = useState(false)const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())const [bulkCategory, setBulkCategory] = useState<string>('')+ const [bulkTagInput, setBulkTagInput] = useState<string>('')const debounceRef = useRef<ReturnType<typeof setTimeout>>(null)const highlightId = searchParams.get('highlight')const highlightedRowRef = useRef<HTMLTableRowElement | null>(null)@@ -122,7 +137,7 @@ export default function TransactionsPage() {}, [highlightId, searchQuery, filterPayee, filterCategoryIds, page])const { data, isLoading } = useQuery({- queryKey: ['transactions', page, filterAccountIds, filterCategoryIds, filterUncategorized, filterPayee, filterFrom, filterTo, searchQuery],+ queryKey: ['transactions', page, filterAccountIds, filterCategoryIds, filterUncategorized, filterPayee, filterFrom, filterTo, searchQuery, tagFilters],queryFn: () =>transactions.list({page,@@ -134,6 +149,7 @@ export default function TransactionsPage() {from: filterFrom || undefined,to: filterTo || undefined,q: searchQuery || undefined,+ tags: tagFilters.length > 0 ? tagFilters : undefined,}),})@@ -250,6 +266,20 @@ export default function TransactionsPage() {},})+ const bulkAddTagsMutation = useMutation({+ mutationFn: ({ ids, tags }: { ids: string[]; tags: string[] }) =>+ transactions.bulkAddTags(ids, tags),+ onSuccess: (result) => {+ invalidateAfterTxMutation()+ setSelectedIds(new Set())+ setBulkTagInput('')+ toast.success(t('transactions.bulkSuccess', { count: result.updated }))+ },+ onError: (error) => {+ toast.error(extractApiError(error))+ },+ })+const linkTransferMutation = useMutation({mutationFn: (ids: [string, string]) => transactions.linkTransfer(ids),onSuccess: () => {@@ -306,12 +336,9 @@ export default function TransactionsPage() {})}- const filteredItems = useMemo(() => {- if (!tagFilter || !data?.items) return data?.items ?? []- return data.items.filter(tx =>- tx.notes?.includes(tagFilter)- )- }, [data?.items, tagFilter])+ // Tag filtering is now applied server-side, so the visible list and the+ // page count both reflect the same filtered total — issue #88.+ const filteredItems = data?.items ?? []const toggleSelectAll = () => {if (!filteredItems.length) return@@ -406,6 +433,19 @@ export default function TransactionsPage() {<TransactionsFilterBarsearchInput={searchInput}onSearchChange={(v) => setSearchInput(v)}+ onSearchSubmit={(value) => {+ const trimmed = value.trim()+ // Tokenize submitted text. `#`-tokens become live tag filter+ // chips below the search bar (filtering applies immediately, no+ // Enter required). Non-`#` text remains as the free-text search+ // query (issue #88).+ const tokens = trimmed.split(/\s+/).filter(Boolean)+ const tags = tokens.filter(t => t.startsWith('#'))+ const text = tokens.filter(t => !t.startsWith('#')).join(' ')+ tags.forEach(addTagFilter)+ setSearchInput(text)+ setSearchQuery(text)+ }}filterAccountIds={filterAccountIds}onAccountIdsChange={(v) => { setFilterAccountIds(v); setPage(1) }}filterCategoryIds={filterCategoryIds}@@ -426,21 +466,30 @@ export default function TransactionsPage() {setFilterPayee('')setSearchInput('')setSearchQuery('')+ clearTagFilters()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>+ {tagFilters.length > 0 && (+ <div className="mb-4 flex flex-wrap items-center gap-1.5">+ {tagFilters.map(tag => (+ <span+ key={tag}+ className="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>{tag}</span>+ <button+ onClick={() => removeTagFilter(tag)}+ className="ml-0.5 text-primary/60 hover:text-primary"+ aria-label={`Remove ${tag} filter`}+ >+ <X size={12} />+ </button>+ </span>+ ))}</div>)}{isAccrual && (filterFrom || filterTo) && (@@ -540,7 +589,7 @@ export default function TransactionsPage() {<spankey={tag}className="inline-block text-[11px] font-medium bg-primary/5 text-primary border border-primary/10 px-1.5 py-0 rounded-full leading-5 cursor-pointer hover:bg-primary/10 transition-colors"- onClick={(e) => { e.stopPropagation(); setTagFilter(tag) }}+ onClick={(e) => { e.stopPropagation(); addTagFilter(tag) }}>{tag}</span>@@ -622,49 +671,93 @@ export default function TransactionsPage() {<divclassName={`fixed bottom-0 left-0 right-0 z-50 transition-transform duration-200 ease-out ${selectedIds.size > 0 ? 'translate-y-0' : 'translate-y-full'}`}>- <div className="mx-auto max-w-2xl px-3 md:px-4 pb-4 md:pb-6">- <div className="flex flex-wrap items-center gap-2 md:gap-3 bg-card border border-border shadow-lg rounded-xl px-3 md:px-5 py-2.5 md:py-3">- <span className="text-xs md:text-sm font-medium text-foreground whitespace-nowrap">- {t('transactions.selected', { count: selectedIds.size })}- </span>+ <div className="mx-auto max-w-5xl px-3 md:px-4 pb-4 md:pb-6">+ <div className="flex items-stretch gap-1.5 bg-card border border-border shadow-xl rounded-2xl p-2">+ {/* Selection count */}+ <div className="flex items-center gap-2 pl-3 pr-4 text-sm font-medium text-foreground whitespace-nowrap">+ <span className="inline-flex items-center justify-center size-6 rounded-full bg-primary/10 text-primary text-xs font-semibold">+ {selectedIds.size}+ </span>+ <span className="hidden sm:inline">{t('transactions.selected')}</span>+ </div>++ <div className="w-px bg-border/60 self-stretch" />++ {/* Categorize — fires on selection, no separate Apply button */}<select- className="border border-border rounded-lg px-2 md:px-3 py-1.5 text-xs md:text-sm bg-card text-foreground focus:outline-none focus-visible:ring-ring/30 focus-visible:ring-[2px] flex-1 min-w-0"+ className="rounded-lg px-3 py-2 text-sm bg-transparent text-foreground hover:bg-muted/60 focus:outline-none focus-visible:bg-muted/60 cursor-pointer w-44 md:w-56"value={bulkCategory}- onChange={(e) => setBulkCategory(e.target.value)}+ onChange={(e) => {+ const next = e.target.value+ setBulkCategory(next)+ if (next) {+ bulkCategorizeMutation.mutate({ ids: Array.from(selectedIds), categoryId: next })+ }+ }}+ disabled={bulkCategorizeMutation.isPending}><option value="">{t('transactions.selectCategory')}</option>{categoriesList?.map((cat) => (<option key={cat.id} value={cat.id}>{cat.name}</option>))}</select>++ <div className="w-px bg-border/60 self-stretch" />++ {/* Add tags inline */}+ <div className="flex items-center gap-1 px-1">+ <input+ type="text"+ value={bulkTagInput}+ onChange={(e) => setBulkTagInput(e.target.value)}+ placeholder={t('transactions.addTagsPlaceholder', '#tag…')}+ className="rounded-lg px-2.5 py-2 text-sm bg-transparent text-foreground placeholder:text-muted-foreground/70 focus:outline-none focus:bg-muted/60 w-28 md:w-40"+ onKeyDown={(e) => {+ if (e.key === 'Enter' && bulkTagInput.trim()) {+ e.preventDefault()+ const tagList = bulkTagInput.trim().split(/[\s,]+/).filter(Boolean)+ bulkAddTagsMutation.mutate({ ids: Array.from(selectedIds), tags: tagList })+ }+ }}+ />+ <Button+ size="sm"+ variant="ghost"+ disabled={!bulkTagInput.trim() || bulkAddTagsMutation.isPending}+ onClick={() => {+ const tagList = bulkTagInput.trim().split(/[\s,]+/).filter(Boolean)+ if (tagList.length === 0) return+ bulkAddTagsMutation.mutate({ ids: Array.from(selectedIds), tags: tagList })+ }}+ className="h-8 w-8 px-0 shrink-0"+ title={t('transactions.bulkAddTags', 'Add tags')}+ >+ <Check size={15} />+ </Button>+ </div>++ <div className="w-px bg-border/60 self-stretch" />++ {/* Link transfer */}<Buttonsize="sm"- disabled={!bulkCategory || bulkCategorizeMutation.isPending}- onClick={() => {- bulkCategorizeMutation.mutate({- ids: Array.from(selectedIds),- categoryId: bulkCategory || null,- })- }}- className="shrink-0"- >- <Check size={14} className="mr-1" />- {t('transactions.bulkCategorize')}- </Button>- <Button- size="sm"- variant="outline"+ variant="ghost"disabled={!canOpenLinkDialog}- title={linkDisabledTooltip}+ title={linkDisabledTooltip ?? t('transactions.linkAsTransfer')}onClick={() => setLinkTransferDialogOpen(true)}- className="shrink-0"+ className="h-8 px-3 shrink-0 text-sm">- <ArrowLeftRight size={14} className="mr-1" />- {t('transactions.linkAsTransfer')}+ <ArrowLeftRight size={15} className="mr-1.5" />+ <span className="hidden lg:inline">{t('transactions.linkAsTransfer')}</span></Button>++ <div className="ml-auto" />++ {/* Close */}<button- onClick={() => { setSelectedIds(new Set()); setBulkCategory('') }}- className="text-muted-foreground hover:text-foreground p-1 shrink-0"+ onClick={() => { setSelectedIds(new Set()); setBulkCategory(''); setBulkTagInput('') }}+ className="text-muted-foreground hover:text-foreground p-2 shrink-0 self-center rounded-lg hover:bg-muted/60"+ title={t('common.close', 'Close')}><X size={16} /></button>