Open-source personal finance manager. Self-hosted, privacy-first.
feat: adding transactions grid (#161) (#171)
Tássio Noronhabe40c7b3350e
diff --git a/backend/app/api/transactions.py b/backend/app/api/transactions.pyindex bc271f67..b6cb3e5b 100644--- a/backend/app/api/transactions.py+++ b/backend/app/api/transactions.py@@ -65,6 +65,8 @@ async def list_transactions(include_opening_balance: bool = Query(False),exclude_transfers: bool = Query(False),tags: Optional[List[str]] = Query(None),+ sort_by: Optional[str] = Query(None, description="Column to sort by (date|amount|description|payee|category|account|type|status). Default: date desc."),+ sort_dir: str = Query("desc", regex="^(asc|desc)$"),session: AsyncSession = Depends(get_async_session),user: User = Depends(current_active_user),):@@ -81,6 +83,8 @@ async def list_transactions(bill_id=bill_id,group_id=group_id,unbilled_only=unbilled_only,+ sort_by=sort_by,+ sort_dir=sort_dir,)primary_currency = user.primary_currencyitems = [_tag_fx_fallback(TransactionRead.model_validate(tx, from_attributes=True), primary_currency) for tx in transactions]@@ -100,19 +104,30 @@ async def export_transactions(uncategorized: bool = Query(False),type: Optional[str] = Query(None),tags: Optional[List[str]] = Query(None),+ transaction_ids: Optional[List[uuid.UUID]] = Query(None, description="If set, exports exactly these rows (scoped to the user); other filters are ignored."),session: AsyncSession = Depends(get_async_session),user: User = Depends(current_active_user),):accounting_mode = await get_credit_card_accounting_mode(session)- transactions, _ = await transaction_service.get_transactions(- 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,- accounting_mode=accounting_mode,- tags=tags,- )+ if transaction_ids:+ # Selection-only export: bypass user-facing filters but keep the+ # service-level user/visibility scoping intact.+ transactions, _ = await transaction_service.get_transactions(+ session, user.id,+ skip_pagination=True,+ accounting_mode=accounting_mode,+ transaction_ids=transaction_ids,+ )+ else:+ transactions, _ = await transaction_service.get_transactions(+ 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,+ accounting_mode=accounting_mode,+ tags=tags,+ )output = io.StringIO()output.write("\ufeff") # UTF-8 BOM for Exceldiff --git a/backend/app/services/transaction_service.py b/backend/app/services/transaction_service.pyindex 621802e9..59625f18 100644--- a/backend/app/services/transaction_service.py+++ b/backend/app/services/transaction_service.py@@ -11,6 +11,7 @@ from app.models.transaction import Transactionfrom app.models.transaction_attachment import TransactionAttachmentfrom app.models.account import Accountfrom app.models.bank_connection import BankConnection+from app.models.category import Categoryfrom app.models.group import Group, GroupMemberfrom app.models.payee import Payeefrom app.schemas.transaction import TransactionCreate, TransactionUpdate, TransferCreate@@ -70,6 +71,9 @@ async def get_transactions(bill_id: Optional[uuid.UUID] = None,group_id: Optional[uuid.UUID] = None,unbilled_only: bool = False,+ sort_by: Optional[str] = None,+ sort_dir: str = "desc",+ transaction_ids: Optional[list[uuid.UUID]] = 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.@@ -115,6 +119,7 @@ async def get_transactions(.outerjoin(Account).outerjoin(BankConnection).outerjoin(Payee, Transaction.payee_id == Payee.id)+ .outerjoin(Category, Transaction.category_id == Category.id).options(selectinload(Transaction.category),selectinload(Transaction.account),@@ -122,6 +127,8 @@ async def get_transactions(selectinload(Transaction.splits),))+ if transaction_ids:+ base_query = base_query.where(Transaction.id.in_(transaction_ids))if use_group_scope:from app.models.group import GroupMemberfrom app.models.transaction_split import TransactionSplit@@ -309,8 +316,26 @@ async def get_transactions(# Apply ordering (and pagination unless skipped). Bill-view callers# order by purchase date so the in-cycle list matches the bank's own# statement ordering regardless of accounting mode.- order_col = bill_view_date_col if in_bill_view else date_col- query = base_query.order_by(order_col.desc(), Transaction.created_at.desc())+ default_order_col = bill_view_date_col if in_bill_view else date_col+ sort_columns: dict[str, object] = {+ "date": default_order_col,+ "amount": Transaction.amount,+ "description": Transaction.description,+ "payee": Payee.name,+ "category": Category.name,+ "account": Account.name,+ "type": Transaction.type,+ "status": Transaction.status,+ }+ chosen_col = sort_columns.get(sort_by) if sort_by else None+ if chosen_col is None:+ # Default: by date desc, with created_at as tiebreaker.+ query = base_query.order_by(default_order_col.desc(), Transaction.created_at.desc())+ else:+ direction = (chosen_col.asc() if sort_dir == "asc" else chosen_col.desc())+ # Always tie-break on date desc + created_at desc so equal values+ # stay in a sensible order (e.g. multiple txs with the same amount).+ query = base_query.order_by(direction, default_order_col.desc(), Transaction.created_at.desc())if not skip_pagination:query = query.offset((page - 1) * limit).limit(limit)diff --git a/frontend/src/components/transactions-column-picker.tsx b/frontend/src/components/transactions-column-picker.tsxnew file mode 100644index 00000000..a6b9c113--- /dev/null+++ b/frontend/src/components/transactions-column-picker.tsx@@ -0,0 +1,63 @@+import { useTranslation } from 'react-i18next'+import { Columns3 } from 'lucide-react'++import { Button } from '@/components/ui/button'+import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'++import { COLUMN_REGISTRY, type ColumnId, type TransactionsGridState } from './transactions-grid-columns'++interface Props {+ state: TransactionsGridState+}++export function TransactionsColumnPicker({ state }: Props) {+ const { t } = useTranslation()+ return (+ <Popover>+ <PopoverTrigger asChild>+ <Button variant="outline" title={t('transactions.columnsTooltip')}>+ <Columns3 size={16} className="mr-1.5" />+ {t('transactions.columns')}+ </Button>+ </PopoverTrigger>+ <PopoverContent align="end" className="w-56 p-2">+ <div className="px-2 py-1.5 text-xs font-medium text-muted-foreground">+ {t('transactions.columns')}+ </div>+ <ul className="max-h-72 overflow-y-auto">+ {COLUMN_REGISTRY.map(col => {+ const checked = state.isVisible(col.id)+ const disabled = !!col.alwaysOn+ return (+ <li key={col.id}>+ <label+ className={`flex items-center gap-2 rounded-md px-2 py-1.5 text-sm hover:bg-muted ${+ disabled ? 'opacity-60 cursor-not-allowed' : 'cursor-pointer'+ }`}+ >+ <input+ type="checkbox"+ checked={checked}+ disabled={disabled}+ onChange={() => state.toggleColumn(col.id as ColumnId)}+ className="h-4 w-4 rounded border-border accent-primary"+ />+ <span className="flex-1">{t(col.labelKey)}</span>+ </label>+ </li>+ )+ })}+ </ul>+ <div className="mt-1 border-t border-border pt-2">+ <button+ type="button"+ onClick={() => state.resetColumns()}+ className="w-full rounded-md px-2 py-1.5 text-left text-xs text-muted-foreground hover:bg-muted hover:text-foreground"+ >+ {t('transactions.resetColumns')}+ </button>+ </div>+ </PopoverContent>+ </Popover>+ )+}diff --git a/frontend/src/components/transactions-grid-columns.tsx b/frontend/src/components/transactions-grid-columns.tsxnew file mode 100644index 00000000..0405c7fb--- /dev/null+++ b/frontend/src/components/transactions-grid-columns.tsx@@ -0,0 +1,201 @@+import { useCallback, useEffect, useMemo, useState } from 'react'++// Column id <-> backend sort key. The id is used for visibility/order/width+// state and must stay stable across releases (it's persisted to localStorage).+// The sort key matches the backend's `sort_by` query param.+export type ColumnId =+ | 'date'+ | 'description'+ | 'category'+ | 'account'+ | 'amount'+ | 'payee'+ | 'notes'+ | 'tags'+ | 'attachments'+ | 'type'+ | 'status'++export type SortDir = 'asc' | 'desc'++export interface ColumnDef {+ id: ColumnId+ labelKey: string+ alwaysOn?: boolean+ defaultVisible: boolean+ sortable: boolean+ defaultWidth: number+ align: 'left' | 'right'+}++// Source of truth for the available columns. The picker iterates over this+// list in registry order; visible columns render in the order the user has+// chosen (persisted in localStorage), which defaults to registry order.+export const COLUMN_REGISTRY: ColumnDef[] = [+ { id: 'date', labelKey: 'transactions.colDate', defaultVisible: true, sortable: true, defaultWidth: 110, align: 'left' },+ { id: 'description', labelKey: 'transactions.colDescription', alwaysOn: true, defaultVisible: true, sortable: true, defaultWidth: 320, align: 'left' },+ { id: 'category', labelKey: 'transactions.colCategory', defaultVisible: true, sortable: true, defaultWidth: 180, align: 'left' },+ { id: 'account', labelKey: 'transactions.colAccount', defaultVisible: true, sortable: true, defaultWidth: 160, align: 'left' },+ { id: 'payee', labelKey: 'transactions.colPayee', defaultVisible: false, sortable: true, defaultWidth: 160, align: 'left' },+ { id: 'notes', labelKey: 'transactions.colNotes', defaultVisible: false, sortable: false, defaultWidth: 220, align: 'left' },+ { id: 'tags', labelKey: 'transactions.colTags', defaultVisible: false, sortable: false, defaultWidth: 180, align: 'left' },+ { id: 'attachments', labelKey: 'transactions.colAttachments', defaultVisible: false, sortable: false, defaultWidth: 70, align: 'right' },+ { id: 'type', labelKey: 'transactions.colType', defaultVisible: false, sortable: true, defaultWidth: 100, align: 'left' },+ { id: 'status', labelKey: 'transactions.colStatus', defaultVisible: false, sortable: true, defaultWidth: 100, align: 'left' },+ { id: 'amount', labelKey: 'transactions.colAmount', alwaysOn: true, defaultVisible: true, sortable: true, defaultWidth: 160, align: 'right' },+]++const COL_BY_ID: Record<ColumnId, ColumnDef> = Object.fromEntries(+ COLUMN_REGISTRY.map(c => [c.id, c]),+) as Record<ColumnId, ColumnDef>++export function getColumn(id: ColumnId): ColumnDef {+ return COL_BY_ID[id]+}++const STORAGE_KEY_ORDER = 'securo.transactions.columns.order'+const STORAGE_KEY_WIDTHS = 'securo.transactions.columns.widths'+const STORAGE_KEY_SORT = 'securo.transactions.sort'++function loadOrder(): ColumnId[] {+ try {+ const raw = localStorage.getItem(STORAGE_KEY_ORDER)+ if (!raw) return defaultVisibleOrder()+ const parsed = JSON.parse(raw)+ if (!Array.isArray(parsed)) return defaultVisibleOrder()+ // Drop unknown ids (registry shrank). Keep alwaysOn ids even if missing.+ const known = parsed.filter((id): id is ColumnId => id in COL_BY_ID)+ for (const c of COLUMN_REGISTRY) {+ if (c.alwaysOn && !known.includes(c.id)) known.push(c.id)+ }+ return known+ } catch {+ return defaultVisibleOrder()+ }+}++function defaultVisibleOrder(): ColumnId[] {+ return COLUMN_REGISTRY.filter(c => c.defaultVisible || c.alwaysOn).map(c => c.id)+}++function loadWidths(): Partial<Record<ColumnId, number>> {+ try {+ const raw = localStorage.getItem(STORAGE_KEY_WIDTHS)+ if (!raw) return {}+ const parsed = JSON.parse(raw)+ if (!parsed || typeof parsed !== 'object') return {}+ const out: Partial<Record<ColumnId, number>> = {}+ for (const [k, v] of Object.entries(parsed)) {+ if (k in COL_BY_ID && typeof v === 'number' && v > 40 && v < 800) {+ out[k as ColumnId] = v+ }+ }+ return out+ } catch {+ return {}+ }+}++function loadSort(): { by: ColumnId | null; dir: SortDir } {+ try {+ const raw = localStorage.getItem(STORAGE_KEY_SORT)+ if (!raw) return { by: null, dir: 'desc' }+ const parsed = JSON.parse(raw)+ const by = parsed?.by && parsed.by in COL_BY_ID ? (parsed.by as ColumnId) : null+ const dir: SortDir = parsed?.dir === 'asc' ? 'asc' : 'desc'+ return { by, dir }+ } catch {+ return { by: null, dir: 'desc' }+ }+}++export interface TransactionsGridState {+ visibleIds: ColumnId[]+ visibleColumns: ColumnDef[]+ isVisible: (id: ColumnId) => boolean+ toggleColumn: (id: ColumnId) => void+ resetColumns: () => void+ widthOf: (id: ColumnId) => number+ setWidth: (id: ColumnId, width: number) => void+ sortBy: ColumnId | null+ sortDir: SortDir+ toggleSort: (id: ColumnId) => void+ // Stringly-typed sort, ready for the API call. `null` when no explicit sort.+ apiSort: { sort_by?: string; sort_dir?: SortDir }+}++export function useTransactionsGridState(): TransactionsGridState {+ const [order, setOrder] = useState<ColumnId[]>(() => loadOrder())+ const [widths, setWidths] = useState<Partial<Record<ColumnId, number>>>(() => loadWidths())+ const [sort, setSort] = useState<{ by: ColumnId | null; dir: SortDir }>(() => loadSort())++ useEffect(() => {+ try { localStorage.setItem(STORAGE_KEY_ORDER, JSON.stringify(order)) } catch { /* quota / disabled */ }+ }, [order])+ useEffect(() => {+ try { localStorage.setItem(STORAGE_KEY_WIDTHS, JSON.stringify(widths)) } catch { /* quota / disabled */ }+ }, [widths])+ useEffect(() => {+ try { localStorage.setItem(STORAGE_KEY_SORT, JSON.stringify(sort)) } catch { /* quota / disabled */ }+ }, [sort])++ const visibleColumns = useMemo(() => order.map(id => COL_BY_ID[id]).filter(Boolean), [order])+ const visibleIds = useMemo(() => visibleColumns.map(c => c.id), [visibleColumns])+ const visibleSet = useMemo(() => new Set(visibleIds), [visibleIds])++ const isVisible = useCallback((id: ColumnId) => visibleSet.has(id), [visibleSet])++ const toggleColumn = useCallback((id: ColumnId) => {+ const def = COL_BY_ID[id]+ if (!def || def.alwaysOn) return+ setOrder(prev => {+ if (prev.includes(id)) return prev.filter(x => x !== id)+ // Re-insert at the position the registry suggests, so toggling on+ // a column twice doesn't drift it to the end.+ const registryOrder = COLUMN_REGISTRY.map(c => c.id)+ const next = [...prev, id]+ next.sort((a, b) => registryOrder.indexOf(a) - registryOrder.indexOf(b))+ return next+ })+ }, [])++ const resetColumns = useCallback(() => {+ setOrder(defaultVisibleOrder())+ setWidths({})+ }, [])++ const widthOf = useCallback((id: ColumnId) => widths[id] ?? COL_BY_ID[id]?.defaultWidth ?? 120, [widths])+ const setWidth = useCallback((id: ColumnId, width: number) => {+ const clamped = Math.max(60, Math.min(800, Math.round(width)))+ setWidths(prev => ({ ...prev, [id]: clamped }))+ }, [])++ const toggleSort = useCallback((id: ColumnId) => {+ const def = COL_BY_ID[id]+ if (!def || !def.sortable) return+ setSort(prev => {+ if (prev.by !== id) return { by: id, dir: 'desc' }+ if (prev.dir === 'desc') return { by: id, dir: 'asc' }+ return { by: null, dir: 'desc' }+ })+ }, [])++ const apiSort = useMemo(() => {+ if (!sort.by) return {}+ return { sort_by: sort.by, sort_dir: sort.dir }+ }, [sort])++ return {+ visibleIds,+ visibleColumns,+ isVisible,+ toggleColumn,+ resetColumns,+ widthOf,+ setWidth,+ sortBy: sort.by,+ sortDir: sort.dir,+ toggleSort,+ apiSort,+ }+}diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 384d1c3b..1e2140b4 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -272,6 +272,8 @@ export const transactions = {include_opening_balance?: booleanexclude_transfers?: booleantags?: string[]+ sort_by?: string+ sort_dir?: 'asc' | 'desc'}): Promise<PaginatedResponse<Transaction>> => {const { data } = await api.get('/transactions', {params,@@ -406,6 +408,7 @@ export const transactions = {from?: stringto?: stringq?: string+ transaction_ids?: string[]}): Promise<void> => {const { data } = await api.get('/transactions/export', {params,diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex afcf9115..08c407dd 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -184,9 +184,31 @@"searchPlaceholder": "Search transactions...","clearFilters": "Clear filters","exportCsv": "Export CSV",+ "exportSelected": "Export Selected ({{count}})","exporting": "Exporting...","exportSuccess": "Transactions exported successfully","exportError": "Failed to export transactions",+ "columns": "Columns",+ "columnsTooltip": "Show or hide columns",+ "resetColumns": "Reset to defaults",+ "colDate": "Date",+ "colDescription": "Description",+ "colCategory": "Category",+ "colAccount": "Account",+ "colAmount": "Amount",+ "colPayee": "Payee",+ "colNotes": "Notes",+ "colTags": "Tags",+ "colAttachments": "Files",+ "colType": "Type",+ "colStatus": "Status",+ "typeExpense": "Expense",+ "typeIncome": "Income",+ "statusPending": "Pending",+ "statusPosted": "Posted",+ "statusCleared": "Cleared",+ "sortAsc": "Sort ascending",+ "sortDesc": "Sort descending","syncedInfo": "Bank-synced transaction — only category and notes can be edited","uncategorized": "Uncategorized","selected": "selected",diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex f614b788..c7d2a8f8 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -184,9 +184,31 @@"searchPlaceholder": "Buscar transações...","clearFilters": "Limpar filtros","exportCsv": "Exportar CSV",+ "exportSelected": "Exportar Selecionadas ({{count}})","exporting": "Exportando...","exportSuccess": "Transações exportadas com sucesso","exportError": "Erro ao exportar transações",+ "columns": "Colunas",+ "columnsTooltip": "Mostrar ou ocultar colunas",+ "resetColumns": "Restaurar padrão",+ "colDate": "Data",+ "colDescription": "Descrição",+ "colCategory": "Categoria",+ "colAccount": "Conta",+ "colAmount": "Valor",+ "colPayee": "Beneficiário",+ "colNotes": "Notas",+ "colTags": "Tags",+ "colAttachments": "Arquivos",+ "colType": "Tipo",+ "colStatus": "Status",+ "typeExpense": "Despesa",+ "typeIncome": "Receita",+ "statusPending": "Pendente",+ "statusPosted": "Lançada",+ "statusCleared": "Compensada",+ "sortAsc": "Ordem crescente",+ "sortDesc": "Ordem decrescente","syncedInfo": "Transação sincronizada — apenas categoria e notas podem ser editadas","uncategorized": "Sem categoria","selected": "selecionadas",diff --git a/frontend/src/pages/transactions.tsx b/frontend/src/pages/transactions.tsxindex 8ab0e3b1..ed0aa9c7 100644--- a/frontend/src/pages/transactions.tsx+++ b/frontend/src/pages/transactions.tsx@@ -23,11 +23,13 @@ import {TableRow,} from '@/components/ui/table'import { Skeleton } from '@/components/ui/skeleton'-import { AlertTriangle, ArrowLeftRight, Check, Download, HelpCircle, Info, Paperclip, Users, X } from 'lucide-react'+import { AlertTriangle, ArrowLeftRight, ArrowUp, ArrowDown, Check, Download, HelpCircle, Info, Paperclip, Users, X } from 'lucide-react'import type { Transaction } from '@/types'import { PageHeader } from '@/components/page-header'import { CategoryIcon } from '@/components/category-icon'import { TransactionDialog, extractApiError, type SaveAction } from '@/components/transaction-dialog'+import { TransactionsColumnPicker } from '@/components/transactions-column-picker'+import { type ColumnDef, type ColumnId, useTransactionsGridState } from '@/components/transactions-grid-columns'import { TransferDialog } from '@/components/transfer-dialog'import { LinkTransferDialog } from '@/components/link-transfer-dialog'import { BulkAddToGroupDialog, type BulkAddToGroupSubmission } from '@/components/bulk-add-to-group-dialog'@@ -122,6 +124,7 @@ export default function TransactionsPage() {const [transferDialogOpen, setTransferDialogOpen] = useState(false)const [linkTransferDialogOpen, setLinkTransferDialogOpen] = useState(false)const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())+ const grid = useTransactionsGridState()const [bulkCategory, setBulkCategory] = useState<string>('')const [bulkAddToGroupOpen, setBulkAddToGroupOpen] = useState(false)const [bulkTagInput, setBulkTagInput] = useState<string>('')@@ -224,7 +227,7 @@ export default function TransactionsPage() {}, [highlightId, searchQuery, filterPayee, filterCategoryIds, page])const { data, isLoading } = useQuery({- queryKey: ['transactions', page, filterAccountIds, filterCategoryIds, filterUncategorized, filterPayee, filterGroupId, filterType, filterFrom, filterTo, searchQuery, tagFilters],+ queryKey: ['transactions', page, filterAccountIds, filterCategoryIds, filterUncategorized, filterPayee, filterGroupId, filterType, filterFrom, filterTo, searchQuery, tagFilters, grid.sortBy, grid.sortDir],queryFn: () =>transactions.list({page,@@ -239,6 +242,7 @@ export default function TransactionsPage() {to: filterTo || undefined,q: searchQuery || undefined,tags: tagFilters.length > 0 ? tagFilters : undefined,+ ...grid.apiSort,}),})@@ -534,6 +538,295 @@ export default function TransactionsPage() {updateMutation.mutate({ id: editingTx.id, ...data })}+ // Resize: track which column is being dragged so we can clear listeners+ // when the gesture ends. The width is committed to grid state on every+ // pointermove for live feedback (cheap — single React state update).+ const resizingRef = useRef<{ id: ColumnId; startX: number; startWidth: number } | null>(null)+ const startResize = (e: React.PointerEvent<HTMLSpanElement>, col: ColumnDef) => {+ e.preventDefault()+ e.stopPropagation()+ resizingRef.current = { id: col.id, startX: e.clientX, startWidth: grid.widthOf(col.id) }+ const onMove = (ev: PointerEvent) => {+ const r = resizingRef.current+ if (!r) return+ grid.setWidth(r.id, r.startWidth + (ev.clientX - r.startX))+ }+ const onUp = () => {+ resizingRef.current = null+ window.removeEventListener('pointermove', onMove)+ window.removeEventListener('pointerup', onUp)+ }+ window.addEventListener('pointermove', onMove)+ window.addEventListener('pointerup', onUp)+ }++ const renderHeaderCell = (col: ColumnDef) => {+ const isSorted = grid.sortBy === col.id+ const sortIndicator = isSorted ? (grid.sortDir === 'asc' ? <ArrowUp size={12} /> : <ArrowDown size={12} />) : null+ const alignClass = col.align === 'right' ? 'text-right' : 'text-left'+ const justify = col.align === 'right' ? 'justify-end' : 'justify-start'+ const cursorClass = col.sortable ? 'cursor-pointer select-none hover:text-foreground' : ''+ // Match the amount/attachments body cells' pr-5 so right-aligned+ // headers line up with their values (issue #161 polish).+ const padX = col.align === 'right' ? 'pr-5' : ''+ return (+ <TableHead+ key={col.id}+ style={{ width: grid.widthOf(col.id), minWidth: grid.widthOf(col.id) }}+ className={`relative text-xs font-medium text-muted-foreground py-3 ${alignClass} ${padX}`}+ onClick={() => { if (col.sortable) grid.toggleSort(col.id) }}+ >+ <div className={`flex items-center gap-1 ${justify} ${cursorClass}`}>+ <span className="truncate">{t(col.labelKey)}</span>+ {sortIndicator}+ </div>+ <span+ onPointerDown={(e) => startResize(e, col)}+ onClick={(e) => e.stopPropagation()}+ aria-hidden="true"+ className="absolute right-0 top-0 h-full w-2 -mr-1 cursor-col-resize select-none hover:bg-primary/40 active:bg-primary/60"+ />+ </TableHead>+ )+ }++ const stripHashtags = (notes: string) => notes.replace(/#[\wÀ-ž-]+/g, '').trim()++ const renderAmountCell = (tx: Transaction) => {+ const displayAmount = tx.is_shared && tx.viewer_share != null+ ? Number(tx.viewer_share)+ : Number(tx.amount)+ return (+ <>+ <span+ className={`text-xs md:text-sm font-bold tabular-nums ${+ tx.type === 'credit' ? 'text-emerald-600' : 'text-rose-500'+ }`}+ >+ {mask(+ `${tx.type === 'credit' ? '+' : '−'}${formatCurrency(+ Math.abs(displayAmount),+ tx.currency,+ locale,+ )}`,+ )}+ </span>+ {tx.is_shared && (+ <p className="text-[10px] text-muted-foreground tabular-nums">+ {t('splitGroups.sharedRowParent', {+ total: formatCurrency(Math.abs(Number(tx.amount)), tx.currency, locale),+ })}+ </p>+ )}+ {!tx.is_shared && tx.viewer_share != null+ && Math.abs(Number(tx.viewer_share)) !== Math.abs(Number(tx.amount)) && (+ <p className="text-[10px] text-muted-foreground tabular-nums">+ {t('splitGroups.ownerRowYourShare', {+ share: formatCurrency(Math.abs(Number(tx.viewer_share)), tx.currency, locale),+ })}+ </p>+ )}+ {tx.amount_primary != null && tx.currency !== userCurrency && (+ <div className="flex items-center justify-end gap-1">+ {tx.fx_fallback && (+ <span title={t('transactions.fxFallbackTooltip')}><AlertTriangle size={11} className="text-amber-500 shrink-0" /></span>+ )}+ <span className="text-[10px] text-muted-foreground tabular-nums">+ {mask(formatCurrency(Math.abs(tx.amount_primary), userCurrency, locale))}+ </span>+ </div>+ )}+ </>+ )+ }++ const renderDescriptionCell = (tx: Transaction) => {+ const showInlineDate = !grid.isVisible('date')+ const showInlineNotes = !grid.isVisible('notes')+ const showInlineTags = !grid.isVisible('tags')+ const noteText = tx.notes ? stripHashtags(tx.notes) : ''+ const noteTags = tx.notes ? parseHashtags(tx.notes) : []+ return (+ <div className="flex items-center gap-2 md:gap-3">+ <CategoryIcon icon={tx.category?.icon} color={tx.category?.color} size="lg" />+ <div className="min-w-0 flex-1">+ <div className="flex items-center gap-2">+ <p className="text-sm font-semibold text-foreground truncate">{tx.description}</p>+ {tx.group_id && (+ <span+ className="inline-flex items-center gap-1 text-[10px] font-semibold uppercase tracking-wide text-violet-700 bg-violet-50 border border-violet-200 dark:bg-violet-950/40 dark:text-violet-300 dark:border-violet-900 px-1.5 py-0.5 rounded-full"+ title={t('splitGroups.sharedRowTooltip')}+ >+ {tx.is_shared && tx.parent_owner_name+ ? t('splitGroups.sharedRowBadgeAuthor', {+ author: tx.parent_owner_name,+ group: groupNameById.get(tx.group_id) ?? '',+ })+ : t('splitGroups.ownerRowBadge', {+ group: groupNameById.get(tx.group_id) ?? '',+ })}+ </span>+ )}+ {!!tx.transfer_pair_id && (+ <span className="inline-flex items-center gap-1 text-[10px] font-semibold uppercase tracking-wide text-blue-600 bg-blue-50 border border-blue-200 px-1.5 py-0.5 rounded-full">+ <ArrowLeftRight className="h-3 w-3" />+ {t('transactions.transfer')}+ <span title={t('transactions.transferTooltip')}><HelpCircle className="h-3 w-3 text-blue-400" /></span>+ </span>+ )}+ {recurringList?.some(r => r.description === tx.description && r.type === tx.type) && (+ <span className="text-[10px] font-semibold uppercase tracking-wide text-primary bg-primary/5 border border-primary/10 px-1.5 py-0.5 rounded-full">+ {t('transactions.recurringBadge')}+ </span>+ )}+ {tx.installment_number != null && tx.total_installments != null && (+ <span+ className="inline-flex items-center text-[10px] font-bold tabular-nums text-amber-700 dark:text-amber-400 bg-amber-100 dark:bg-amber-500/20 border border-amber-200 dark:border-amber-500/30 px-1.5 py-0.5 rounded-full"+ title={tx.installment_total_amount != null+ ? t('transactions.installmentTooltip', { count: tx.total_installments, total: tx.installment_total_amount })+ : undefined}+ >+ {tx.installment_number}/{tx.total_installments}+ </span>+ )}+ {(tx.attachment_count ?? 0) > 0 && (+ <Paperclip size={12} className="text-muted-foreground shrink-0" />+ )}+ </div>+ {showInlineDate && (+ <p className="text-xs text-muted-foreground mt-0.5">{new Date(tx.date + 'T00:00:00').toLocaleDateString(locale)}</p>+ )}+ {(showInlineNotes || showInlineTags) && tx.notes && (+ <div className="mt-1 space-y-0.5">+ {showInlineNotes && noteText && (+ <p className="text-xs text-muted-foreground italic leading-snug">{noteText}</p>+ )}+ {showInlineTags && noteTags.length > 0 && (+ <div className="flex flex-wrap gap-1">+ {noteTags.map((tag) => (+ <span+ key={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(); addTagFilter(tag) }}+ >+ {tag}+ </span>+ ))}+ </div>+ )}+ </div>+ )}+ </div>+ </div>+ )+ }++ const renderBodyCell = (col: ColumnDef, tx: Transaction) => {+ const widthStyle = { width: grid.widthOf(col.id), minWidth: grid.widthOf(col.id) }+ const alignClass = col.align === 'right' ? 'text-right' : ''+ const baseClass = `py-2.5 ${alignClass}`+ switch (col.id) {+ case 'date':+ return (+ <TableCell key={col.id} style={widthStyle} className={`${baseClass} text-sm text-muted-foreground tabular-nums`}>+ {new Date(tx.date + 'T00:00:00').toLocaleDateString(locale)}+ </TableCell>+ )+ case 'description':+ return (+ <TableCell key={col.id} style={widthStyle} className={`${baseClass} pl-2 max-w-0`}>+ {renderDescriptionCell(tx)}+ </TableCell>+ )+ case 'category':+ return (+ <TableCell key={col.id} style={widthStyle} className={baseClass}>+ {tx.category ? (+ <span className="text-sm text-muted-foreground">{tx.category.name}</span>+ ) : (+ <span className="text-xs text-muted-foreground italic">{t('transactions.noCategory')}</span>+ )}+ </TableCell>+ )+ case 'account':+ return (+ <TableCell key={col.id} style={widthStyle} className={`${baseClass} text-sm text-muted-foreground`}>+ {getAccountName(accountsList?.find((a) => a.id === tx.account_id) ?? { name: '', display_name: null }) || (+ <span className="text-muted-foreground">—</span>+ )}+ </TableCell>+ )+ case 'amount':+ return (+ <TableCell key={col.id} style={widthStyle} className={`${baseClass} pr-5`}>+ {renderAmountCell(tx)}+ </TableCell>+ )+ case 'payee':+ return (+ <TableCell key={col.id} style={widthStyle} className={`${baseClass} text-sm text-muted-foreground`}>+ {tx.payee_name ?? tx.payee ?? <span className="text-muted-foreground">—</span>}+ </TableCell>+ )+ case 'notes': {+ const text = tx.notes ? stripHashtags(tx.notes) : ''+ return (+ <TableCell key={col.id} style={widthStyle} className={`${baseClass} text-xs text-muted-foreground italic max-w-0 truncate`}>+ {text || <span className="not-italic">—</span>}+ </TableCell>+ )+ }+ case 'tags': {+ const tags = tx.notes ? parseHashtags(tx.notes) : []+ return (+ <TableCell key={col.id} style={widthStyle} className={baseClass}>+ {tags.length === 0 ? (+ <span className="text-muted-foreground">—</span>+ ) : (+ <div className="flex flex-wrap gap-1">+ {tags.map((tag) => (+ <span+ key={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"+ onClick={(e) => { e.stopPropagation(); addTagFilter(tag) }}+ >+ {tag}+ </span>+ ))}+ </div>+ )}+ </TableCell>+ )+ }+ case 'attachments':+ return (+ <TableCell key={col.id} style={widthStyle} className={`${baseClass} pr-5 text-sm text-muted-foreground tabular-nums`}>+ {(tx.attachment_count ?? 0) > 0 ? (+ <span className="inline-flex items-center gap-1 justify-end w-full">+ <Paperclip size={12} />{tx.attachment_count}+ </span>+ ) : <span>—</span>}+ </TableCell>+ )+ case 'type':+ return (+ <TableCell key={col.id} style={widthStyle} className={`${baseClass} text-sm`}>+ <span className={tx.type === 'credit' ? 'text-emerald-600' : 'text-rose-500'}>+ {tx.type === 'credit' ? t('transactions.typeIncome') : t('transactions.typeExpense')}+ </span>+ </TableCell>+ )+ case 'status':+ return (+ <TableCell key={col.id} style={widthStyle} className={`${baseClass} text-sm text-muted-foreground capitalize`}>+ {tx.status === 'pending'+ ? t('transactions.statusPending')+ : t('transactions.statusPosted')}+ </TableCell>+ )+ }+ }+return (<div><PageHeader@@ -541,20 +834,29 @@ export default function TransactionsPage() {title={t('transactions.title')}action={<div className="flex items-center gap-2">+ <TransactionsColumnPicker state={grid} /><Buttonvariant="outline"disabled={exporting}onClick={async () => {setExporting(true)try {- await transactions.export({- 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,- })+ if (selectedIds.size > 0) {+ // Selection-only export bypasses other filters and+ // hits the backend's `transaction_ids` short-circuit.+ await transactions.export({+ transaction_ids: Array.from(selectedIds),+ })+ } else {+ await transactions.export({+ 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,+ })+ }toast.success(t('transactions.exportSuccess'))} catch {toast.error(t('transactions.exportError'))@@ -564,7 +866,11 @@ export default function TransactionsPage() {}}><Download size={16} className="mr-1.5" />- {exporting ? t('transactions.exporting') : t('transactions.exportCsv')}+ {exporting+ ? t('transactions.exporting')+ : selectedIds.size > 0+ ? t('transactions.exportSelected', { count: selectedIds.size })+ : t('transactions.exportCsv')}</Button><Button variant="outline" onClick={() => setTransferDialogOpen(true)}><ArrowLeftRight size={16} className="mr-1.5" />@@ -677,10 +983,11 @@ export default function TransactionsPage() {))}</div>) : (- <Table>+ <div className="overflow-x-auto">+ <Table style={{ tableLayout: 'fixed' }}><TableHeader><TableRow className="border-b border-border hover:bg-transparent">- <TableHead className="w-[40px] py-3 pl-4 pr-0">+ <TableHead style={{ width: 40, minWidth: 40 }} className="py-3 pl-4 pr-0"><inputtype="checkbox"checked={allSelected}@@ -689,10 +996,7 @@ export default function TransactionsPage() {className="h-4 w-4 rounded border-border accent-primary cursor-pointer"/></TableHead>- <TableHead className="text-xs font-medium text-muted-foreground py-3 pl-2">{t('transactions.description')}</TableHead>- <TableHead className="hidden md:table-cell text-xs font-medium text-muted-foreground py-3 w-[180px]">{t('transactions.category')}</TableHead>- <TableHead className="hidden lg:table-cell text-xs font-medium text-muted-foreground py-3 w-[160px]">{t('transactions.account')}</TableHead>- <TableHead className="text-xs font-medium text-muted-foreground py-3 pr-5 text-right w-[120px] md:w-[180px]">{t('transactions.amount')}</TableHead>+ {grid.visibleColumns.map(renderHeaderCell)}</TableRow></TableHeader><TableBody>@@ -713,7 +1017,7 @@ export default function TransactionsPage() {setDialogOpen(true)}}>- <TableCell className="py-2.5 pl-4 pr-0 w-[40px]">+ <TableCell style={{ width: 40, minWidth: 40 }} className="py-2.5 pl-4 pr-0">{/* Bulk operations are scoped to user.id so theysilently skip shared rows — hide the checkboxon those to avoid the dead-end UX. */}@@ -727,156 +1031,19 @@ export default function TransactionsPage() {/>)}</TableCell>- <TableCell className="py-2.5 pl-2 max-w-0">- <div className="flex items-center gap-2 md:gap-3">- <CategoryIcon icon={tx.category?.icon} color={tx.category?.color} size="lg" />- <div className="min-w-0 flex-1">- <div className="flex items-center gap-2">- <p className="text-sm font-semibold text-foreground truncate">{tx.description}</p>- {tx.group_id && (- <span- className="inline-flex items-center gap-1 text-[10px] font-semibold uppercase tracking-wide text-violet-700 bg-violet-50 border border-violet-200 dark:bg-violet-950/40 dark:text-violet-300 dark:border-violet-900 px-1.5 py-0.5 rounded-full"- title={t('splitGroups.sharedRowTooltip')}- >- {tx.is_shared && tx.parent_owner_name- ? t('splitGroups.sharedRowBadgeAuthor', {- author: tx.parent_owner_name,- group: groupNameById.get(tx.group_id) ?? '',- })- : t('splitGroups.ownerRowBadge', {- group: groupNameById.get(tx.group_id) ?? '',- })}- </span>- )}- {!!tx.transfer_pair_id && (- <span className="inline-flex items-center gap-1 text-[10px] font-semibold uppercase tracking-wide text-blue-600 bg-blue-50 border border-blue-200 px-1.5 py-0.5 rounded-full">- <ArrowLeftRight className="h-3 w-3" />- {t('transactions.transfer')}- <span title={t('transactions.transferTooltip')}><HelpCircle className="h-3 w-3 text-blue-400" /></span>- </span>- )}- {recurringList?.some(r => r.description === tx.description && r.type === tx.type) && (- <span className="text-[10px] font-semibold uppercase tracking-wide text-primary bg-primary/5 border border-primary/10 px-1.5 py-0.5 rounded-full">- {t('transactions.recurringBadge')}- </span>- )}- {tx.installment_number != null && tx.total_installments != null && (- <span- className="inline-flex items-center text-[10px] font-bold tabular-nums text-amber-700 dark:text-amber-400 bg-amber-100 dark:bg-amber-500/20 border border-amber-200 dark:border-amber-500/30 px-1.5 py-0.5 rounded-full"- title={tx.installment_total_amount != null- ? t('transactions.installmentTooltip', { count: tx.total_installments, total: tx.installment_total_amount })- : undefined}- >- {tx.installment_number}/{tx.total_installments}- </span>- )}- {(tx.attachment_count ?? 0) > 0 && (- <Paperclip size={12} className="text-muted-foreground shrink-0" />- )}- </div>- <p className="text-xs text-muted-foreground mt-0.5">{new Date(tx.date + 'T00:00:00').toLocaleDateString(locale)}</p>- {tx.notes && (- <div className="mt-1 space-y-0.5">- {tx.notes.replace(/#[\w\u00C0-\u017E-]+/g, '').trim() && (- <p className="text-xs text-muted-foreground italic leading-snug">- {tx.notes.replace(/#[\w\u00C0-\u017E-]+/g, '').trim()}- </p>- )}- {parseHashtags(tx.notes).length > 0 && (- <div className="flex flex-wrap gap-1">- {parseHashtags(tx.notes).map((tag) => (- <span- key={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(); addTagFilter(tag) }}- >- {tag}- </span>- ))}- </div>- )}- </div>- )}- </div>- </div>- </TableCell>- <TableCell className="hidden md:table-cell py-2.5">- {tx.category ? (- <span className="text-sm text-muted-foreground">{tx.category.name}</span>- ) : (- <span className="text-xs text-muted-foreground italic">{t('transactions.noCategory')}</span>- )}- </TableCell>- <TableCell className="hidden lg:table-cell py-2.5 text-sm text-muted-foreground">- {getAccountName(accountsList?.find((a) => a.id === tx.account_id) ?? { name: '', display_name: null }) || (- <span className="text-muted-foreground">—</span>- )}- </TableCell>- <TableCell className="py-2.5 pr-3 md:pr-5 text-right">- {(() => {- // For shared rows we show the viewer's share (the- // portion that's actually theirs in financial- // terms), with the parent's full amount on a small- // secondary line for context.- const displayAmount = tx.is_shared && tx.viewer_share != null- ? Number(tx.viewer_share)- : Number(tx.amount)- return (- <span- className={`text-xs md:text-sm font-bold tabular-nums ${- tx.type === 'credit' ? 'text-emerald-600' : 'text-rose-500'- }`}- >- {mask(- `${tx.type === 'credit' ? '+' : '−'}${formatCurrency(- Math.abs(displayAmount),- tx.currency,- locale,- )}`,- )}- </span>- )- })()}- {tx.is_shared && (- <p className="text-[10px] text-muted-foreground tabular-nums">- {t('splitGroups.sharedRowParent', {- total: formatCurrency(Math.abs(Number(tx.amount)), tx.currency, locale),- })}- </p>- )}- {/* Owner of a split: show your-share secondary line.- Skip when the owner is the sole member (share ==- amount) — would just duplicate the figure. */}- {!tx.is_shared && tx.viewer_share != null- && Math.abs(Number(tx.viewer_share)) !== Math.abs(Number(tx.amount)) && (- <p className="text-[10px] text-muted-foreground tabular-nums">- {t('splitGroups.ownerRowYourShare', {- share: formatCurrency(Math.abs(Number(tx.viewer_share)), tx.currency, locale),- })}- </p>- )}- {tx.amount_primary != null && tx.currency !== userCurrency && (- <div className="flex items-center justify-end gap-1">- {tx.fx_fallback && (- <span title={t('transactions.fxFallbackTooltip')}><AlertTriangle size={11} className="text-amber-500 shrink-0" /></span>- )}- <span className="text-[10px] text-muted-foreground tabular-nums">- {mask(formatCurrency(Math.abs(tx.amount_primary), userCurrency, locale))}- </span>- </div>- )}- </TableCell>+ {grid.visibleColumns.map(col => renderBodyCell(col, tx))}</TableRow>))}{filteredItems.length === 0 && (<TableRow>- <TableCell colSpan={5} className="text-center py-16 text-muted-foreground">+ <TableCell colSpan={grid.visibleColumns.length + 1} className="text-center py-16 text-muted-foreground">{t('transactions.noResults')}</TableCell></TableRow>)}</TableBody></Table>+ </div>)}</div>@@ -905,11 +1072,14 @@ export default function TransactionsPage() {</div>)}- {/* Bulk Action Bar */}+ {/* Bulk Action Bar — aligned with the main content area: clears the+ fixed sidebar on lg+ and matches the page's max-w-7xl + p-6 wrapper+ so the bar visually sits over the transactions list, not the+ full viewport. */}<div- className={`fixed bottom-0 left-0 right-0 z-50 transition-transform duration-200 ease-out ${selectedIds.size > 0 ? 'translate-y-0' : 'translate-y-full'}`}+ className={`fixed bottom-0 left-0 right-0 lg:left-60 z-50 transition-transform duration-200 ease-out ${selectedIds.size > 0 ? 'translate-y-0' : 'translate-y-full'}`}>- <div className="mx-auto max-w-6xl px-3 md:px-4 pb-4 md:pb-6">+ <div className="mx-auto max-w-7xl px-3 md:px-6 pb-4 md:pb-6"><div className="flex items-stretch gap-1.5 bg-card border border-border shadow-xl rounded-2xl p-2">{/* Selection count */}<div className="flex items-center gap-2 pl-3 pr-4 text-sm font-medium text-foreground whitespace-nowrap">