Open-source personal finance manager. Self-hosted, privacy-first.
align transaction list with dashboard accounting mode
Tássio Noronha417fbee43fb8
diff --git a/backend/app/api/admin.py b/backend/app/api/admin.pyindex a9393947..b6f6c934 100644--- a/backend/app/api/admin.py+++ b/backend/app/api/admin.py@@ -3,7 +3,7 @@ import uuidfrom fastapi import APIRouter, Depends, HTTPException, Query, Request, statusfrom sqlalchemy.ext.asyncio import AsyncSession-from app.core.auth import UserManager, current_superuser, get_user_manager+from app.core.auth import UserManager, current_active_user, current_superuser, get_user_managerfrom app.core.database import get_async_sessionfrom app.models.user import Userfrom app.schemas.admin import (@@ -137,6 +137,15 @@ async def registration_status(return {"enabled": enabled}[email protected]("/accounting-mode")+async def accounting_mode(+ session: AsyncSession = Depends(get_async_session),+ _user: User = Depends(current_active_user),+):+ mode = await admin_service.get_credit_card_accounting_mode(session)+ return {"mode": mode}++async def check_registration_enabled(request: Request,session: AsyncSession = Depends(get_async_session),diff --git a/backend/app/api/transactions.py b/backend/app/api/transactions.pyindex eeb82617..88d630ec 100644--- a/backend/app/api/transactions.py+++ b/backend/app/api/transactions.py@@ -14,6 +14,7 @@ from app.core.database import get_async_sessionfrom app.models.user import Userfrom app.schemas.transaction import BulkCategorizeRequest, LinkTransferRequest, TransactionCreate, TransactionRead, TransactionUpdate, TransferCreate, TransferReadfrom app.services import transaction_service+from app.services.admin_service import get_credit_card_accounting_moderouter = APIRouter(prefix="/api/transactions", tags=["transactions"])@@ -63,6 +64,7 @@ async def list_transactions(session: AsyncSession = Depends(get_async_session),user: User = Depends(current_active_user),):+ accounting_mode = await get_credit_card_accounting_mode(session)transactions, total = await transaction_service.get_transactions(session, user.id,account_ids=_merge_id_filters(account_id, account_ids),@@ -70,6 +72,7 @@ async def list_transactions(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,+ accounting_mode=accounting_mode,)primary_currency = user.primary_currencyitems = [_tag_fx_fallback(TransactionRead.model_validate(tx, from_attributes=True), primary_currency) for tx in transactions]@@ -91,12 +94,14 @@ async def export_transactions(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,)output = io.StringIO()diff --git a/backend/app/services/transaction_service.py b/backend/app/services/transaction_service.pyindex b239054b..1a734121 100644--- a/backend/app/services/transaction_service.py+++ b/backend/app/services/transaction_service.py@@ -61,7 +61,13 @@ async def get_transactions(exclude_transfers: bool = False,account_ids: Optional[list[uuid.UUID]] = None,category_ids: Optional[list[uuid.UUID]] = None,+ accounting_mode: Optional[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.+ date_col = (+ Transaction.effective_date if accounting_mode == "accrual" else Transaction.date+ )# Base query: user's own transactions (manual or via account)base_query = (select(Transaction)@@ -103,9 +109,9 @@ async def get_transactions(if txn_type:base_query = base_query.where(Transaction.type == txn_type)if from_date:- base_query = base_query.where(Transaction.date >= from_date)+ base_query = base_query.where(date_col >= from_date)if to_date:- base_query = base_query.where(Transaction.date <= to_date)+ base_query = base_query.where(date_col <= to_date)if search:term = f"%{search}%"base_query = base_query.where(@@ -122,7 +128,7 @@ async def get_transactions(total = await session.scalar(count_query)# Apply ordering (and pagination unless skipped)- query = base_query.order_by(Transaction.date.desc(), Transaction.created_at.desc())+ query = base_query.order_by(date_col.desc(), Transaction.created_at.desc())if not skip_pagination:query = query.offset((page - 1) * limit).limit(limit)diff --git a/backend/tests/test_transaction_service.py b/backend/tests/test_transaction_service.pyindex 41396f17..789330d3 100644--- a/backend/tests/test_transaction_service.py+++ b/backend/tests/test_transaction_service.py@@ -292,6 +292,61 @@ async def test_get_transactions_filter_by_date_range(session: AsyncSession, testassert "Jan" not in descs+async def test_get_transactions_date_filter_respects_accounting_mode(+ session: AsyncSession, test_user, txn_account+):+ # CC purchase on Mar 25 that bills on Apr 15 (effective_date shifted).+ cc_purchase = Transaction(+ id=uuid.uuid4(),+ user_id=test_user.id,+ account_id=txn_account.id,+ description="CC purchase",+ amount=Decimal("50"),+ date=date(2025, 3, 25),+ effective_date=date(2025, 4, 15),+ type="debit",+ source="manual",+ created_at=datetime.now(timezone.utc),+ )+ # Regular tx that sits on its own date in both modes.+ regular = Transaction(+ id=uuid.uuid4(),+ user_id=test_user.id,+ account_id=txn_account.id,+ description="Regular",+ amount=Decimal("20"),+ date=date(2025, 4, 5),+ effective_date=date(2025, 4, 5),+ type="debit",+ source="manual",+ created_at=datetime.now(timezone.utc),+ )+ session.add_all([cc_purchase, regular])+ await session.commit()++ april_window = dict(from_date=date(2025, 4, 1), to_date=date(2025, 4, 30))+ march_window = dict(from_date=date(2025, 3, 1), to_date=date(2025, 3, 31))++ # Cash mode (default): the CC purchase lives in March, regular in April.+ cash_april, _ = await get_transactions(session, test_user.id, **april_window)+ assert {t.description for t in cash_april} == {"Regular"}++ cash_march, _ = await get_transactions(session, test_user.id, **march_window)+ assert {t.description for t in cash_march} == {"CC purchase"}++ # Accrual mode: both buckets shift to the bill-due month.+ accrual_april, _ = await get_transactions(+ session, test_user.id, accounting_mode="accrual", **april_window+ )+ assert {t.description for t in accrual_april} == {"CC purchase", "Regular"}++ accrual_march, _ = await get_transactions(+ session, test_user.id, accounting_mode="accrual", **march_window+ )+ assert {t.description for t in accrual_march} == set()++@pytest.mark.asyncioasync def test_get_transactions_filter_by_search(session: AsyncSession, test_user, txn_account):txn = Transaction(diff --git a/frontend/src/components/transaction-drill-down.tsx b/frontend/src/components/transaction-drill-down.tsxindex abb24dad..f1d1d359 100644--- a/frontend/src/components/transaction-drill-down.tsx+++ b/frontend/src/components/transaction-drill-down.tsx@@ -1,8 +1,8 @@import { useEffect, useRef, useMemo } from 'react'import { useTranslation } from 'react-i18next'import { useQuery } from '@tanstack/react-query'-import { transactions as transactionsApi, dashboard } from '@/lib/api'-import { AlertTriangle, Paperclip, X } from 'lucide-react'+import { transactions as transactionsApi, dashboard, admin } from '@/lib/api'+import { AlertTriangle, Info, Paperclip, X } from 'lucide-react'import { CategoryIcon } from '@/components/category-icon'import { useAuth } from '@/contexts/auth-context'import { usePrivacyMode } from '@/hooks/use-privacy-mode'@@ -79,6 +79,13 @@ export function TransactionDrillDown({enabled: !!filter && !!monthParam,})+ const { data: accountingModeData } = useQuery({+ queryKey: ['admin', 'accounting-mode'],+ queryFn: () => admin.accountingMode(),+ staleTime: 5 * 60 * 1000,+ })+ const isAccrual = accountingModeData?.mode === 'accrual'+// Merge real + projected transactions, filtering projected by drill-down criteriaconst displayItems = useMemo((): DisplayItem[] => {const items: DisplayItem[] = []@@ -158,12 +165,18 @@ export function TransactionDrillDown({}}, [filter, onClose])+ // Sum in user's primary currency. For foreign-currency rows we need+ // amount_primary; if it's missing we can't convert, so skip the row+ // instead of adding a raw foreign amount as if it were primary. This+ // matches how get_summary computes monthly_*_primary on the backend.const absTotal = displayItems.reduce((sum, item) => {- // Use amount_primary for foreign currency transactions, fall back to amount- const effectiveAmount = (item.currency !== userCurrency && item.amountPrimary != null)- ? item.amountPrimary- : item.amount- return sum + Math.abs(effectiveAmount)+ if (item.currency === userCurrency) {+ return sum + Math.abs(item.amount)+ }+ if (item.amountPrimary != null) {+ return sum + Math.abs(item.amountPrimary)+ }+ return sum}, 0)return (@@ -195,6 +208,13 @@ export function TransactionDrillDown({</button></div>+ {isAccrual && filter?.from && (+ <div className="flex items-start gap-2 px-5 py-2.5 bg-muted/40 border-b border-border text-[11px] text-muted-foreground shrink-0">+ <Info size={12} className="mt-0.5 shrink-0" />+ <span>{t('dashboard.accrualNote')}</span>+ </div>+ )}+{/* Transaction list */}<div className="flex-1 overflow-auto">{isLoading ? (diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 4efffc24..ce4e25d2 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -683,6 +683,10 @@ export const admin = {const { data } = await api.get('/admin/registration-status')return data},+ accountingMode: async (): Promise<{ mode: 'cash' | 'accrual' }> => {+ const { data } = await api.get('/admin/accounting-mode')+ return data+ },}// Global search (powers the command palette)diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex 26f7ce6f..cf5872a2 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -126,6 +126,7 @@"drillDownTotal": "{{count}} transactions · {{total}}","drillDownEmpty": "No transactions found","drillDownClose": "Close",+ "accrualNote": "Credit-card transactions are grouped by bill due date (accrual mode).","savingsRate": "Savings Rate","spendingProjection": "At this pace, you'll spend {{amount}} by month end","uncategorizedCta": "{{count}} transactions need categorizing",diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex fe0ee81d..56d6add8 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -126,6 +126,7 @@"drillDownTotal": "{{count}} transações · {{total}}","drillDownEmpty": "Nenhuma transação encontrada","drillDownClose": "Fechar",+ "accrualNote": "Transações de cartão de crédito são agrupadas pela data de vencimento da fatura (modo competência).","savingsRate": "Taxa de Economia","spendingProjection": "Nesse ritmo, você gastará {{amount}} até o fim do mês","uncategorizedCta": "{{count}} transações precisam ser categorizadas",diff --git a/frontend/src/pages/transactions.tsx b/frontend/src/pages/transactions.tsxindex 27a5e581..dfd491f2 100644--- a/frontend/src/pages/transactions.tsx+++ b/frontend/src/pages/transactions.tsx@@ -2,7 +2,7 @@ import { useState, useMemo, useEffect, useRef } from 'react'import { useSearchParams } from 'react-router-dom'import { useTranslation } from 'react-i18next'import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'-import { transactions, categories as categoriesApi, accounts as accountsApi, recurring, payees as payeesApi } from '@/lib/api'+import { transactions, categories as categoriesApi, accounts as accountsApi, recurring, payees as payeesApi, admin } from '@/lib/api'import { toast } from 'sonner'import { Button } from '@/components/ui/button'import {@@ -14,7 +14,7 @@ import {TableRow,} from '@/components/ui/table'import { Skeleton } from '@/components/ui/skeleton'-import { AlertTriangle, ArrowLeftRight, Check, Download, HelpCircle, Paperclip, X } from 'lucide-react'+import { AlertTriangle, ArrowLeftRight, Check, Download, HelpCircle, Info, Paperclip, X } from 'lucide-react'import type { Transaction } from '@/types'import { PageHeader } from '@/components/page-header'import { CategoryIcon } from '@/components/category-icon'@@ -153,6 +153,13 @@ export default function TransactionsPage() {queryFn: recurring.list,})+ const { data: accountingModeData } = useQuery({+ queryKey: ['admin', 'accounting-mode'],+ queryFn: () => admin.accountingMode(),+ staleTime: 5 * 60 * 1000,+ })+ const isAccrual = accountingModeData?.mode === 'accrual'+const createMutation = useMutation({mutationFn: async (payload: { tx: Partial<Transaction>; recurringData?: { frequency: string; end_date?: string }; pendingFiles?: File[] }) => {const created = await transactions.create(payload.tx)@@ -428,6 +435,12 @@ export default function TransactionsPage() {</button></div>)}+ {isAccrual && (filterFrom || filterTo) && (+ <div className="mb-4 flex items-start gap-2 rounded-lg border border-border bg-muted/40 px-3 py-2 text-[11px] text-muted-foreground">+ <Info size={12} className="mt-0.5 shrink-0" />+ <span>{t('dashboard.accrualNote')}</span>+ </div>+ )}{/* Table */}<div className="bg-card rounded-xl border border-border shadow-sm overflow-hidden mb-4">