Skip to content

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

fix: compute group totals from aggregates, not the recent list (#1287)

Iván Trejob4e0118317e9
diff --git a/backend/app/api/groups.py b/backend/app/api/groups.py
index 7312725b..90f28f6b 100644
--- a/backend/app/api/groups.py
+++ b/backend/app/api/groups.py
@@ -17,6 +17,7 @@ from app.schemas.group import (
GroupMemberRead,
GroupMemberUpdate,
GroupRead,
+ GroupSummary,
GroupUpdate,
)
from app.schemas.group_settlement import (
@@ -25,7 +26,12 @@ from app.schemas.group_settlement import (
GroupSettlementUpdate,
)
from app.schemas.transaction import TransactionRead
-from app.services import balance_service, group_service, settlement_service
+from app.services import (
+ balance_service,
+ group_service,
+ group_summary_service,
+ settlement_service,
+)
router = APIRouter(prefix="/api/groups", tags=["groups"])
@@ -192,6 +198,25 @@ async def list_group_transactions(
return txs
[email protected]("/{group_id}/summary", response_model=GroupSummary)
+async def get_summary(
+ group_id: uuid.UUID,
+ ctx: WorkspaceContext = Depends(current_workspace),
+ session: AsyncSession = Depends(get_async_session),
+):
+ """Spending aggregates for the whole group.
+
+ Separate from /transactions, which is a capped recent-activity list:
+ totals have to see every split, not the last page of them.
+ """
+ summary = await group_summary_service.compute_summary(
+ session, group_id, ctx.workspace.id, ctx.user_id
+ )
+ if summary is None:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Group not found")
+ return summary
+
+
@router.get("/{group_id}/balances", response_model=GroupBalances)
async def get_balances(
group_id: uuid.UUID,
diff --git a/backend/app/schemas/group.py b/backend/app/schemas/group.py
index e9194394..664f62d2 100644
--- a/backend/app/schemas/group.py
+++ b/backend/app/schemas/group.py
@@ -85,3 +85,25 @@ class GroupBalances(BaseModel):
self_member_id: Optional[uuid.UUID] = None
default_currency: str
lines: list[GroupBalanceLine] = []
+
+
+class GroupSummaryMonth(BaseModel):
+ # "YYYY-MM"; the client formats it for display.
+ month: str
+ total: Decimal
+
+
+class GroupSummaryCategory(BaseModel):
+ # Null for transactions with no category.
+ category_id: Optional[uuid.UUID] = None
+ name: Optional[str] = None
+ color: Optional[str] = None
+ total: Decimal
+
+
+class GroupSummary(BaseModel):
+ group_id: uuid.UUID
+ default_currency: str
+ total_moved: Decimal
+ months: list[GroupSummaryMonth] = []
+ categories: list[GroupSummaryCategory] = []
diff --git a/backend/app/services/group_summary_service.py b/backend/app/services/group_summary_service.py
new file mode 100644
index 00000000..16e012bb
--- /dev/null
+++ b/backend/app/services/group_summary_service.py
@@ -0,0 +1,105 @@
+"""Group spending aggregates.
+
+The group page shows three figures that describe the group as a whole:
+how much has moved through it, how that splits by month, and how it
+splits by category. They are computed here, in SQL, for the same reason
+balances are: the recent-transactions list is capped at 20 rows, so
+deriving totals from it describes the last few weeks while claiming to
+describe the group.
+
+Amounts follow the convention the rest of the group page already uses —
+``amount_primary`` when the sync stored one, the native ``amount``
+otherwise.
+"""
+
+import uuid
+from decimal import Decimal
+from typing import Optional
+
+from sqlalchemy import String, cast, func, select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models.category import Category
+from app.models.group import GroupMember
+from app.models.transaction import Transaction
+from app.models.transaction_split import TransactionSplit
+
+
+def _amount_expr():
+ return func.coalesce(Transaction.amount_primary, Transaction.amount)
+
+
+def _group_transactions(group_id: uuid.UUID):
+ """Transactions carrying a split for any member of this group."""
+ member_ids = select(GroupMember.id).where(GroupMember.group_id == group_id)
+ return (
+ select(TransactionSplit.transaction_id)
+ .where(TransactionSplit.group_member_id.in_(member_ids))
+ .distinct()
+ )
+
+
+async def compute_summary(
+ session: AsyncSession,
+ group_id: uuid.UUID,
+ workspace_id: uuid.UUID,
+ user_id: uuid.UUID,
+) -> Optional[dict]:
+ # Same visibility rule as balances: workspace members plus
+ # cross-workspace linked members all see the same totals.
+ from app.services.group_service import get_group_visible
+
+ group = await get_group_visible(session, group_id, workspace_id, user_id)
+ if not group:
+ return None
+
+ tx_ids = _group_transactions(group_id)
+ amount = _amount_expr()
+
+ # "YYYY-MM" without to_char: the date renders as YYYY-MM-DD on both
+ # PostgreSQL and the SQLite the test suite runs on, so the bucket
+ # works everywhere instead of 500ing on one of them.
+ month_label = func.substr(cast(Transaction.date, String), 1, 7).label("month")
+ months_result = await session.execute(
+ select(month_label, func.sum(amount))
+ .where(Transaction.id.in_(tx_ids))
+ .group_by(month_label)
+ .order_by(month_label)
+ )
+ months = [{"month": row[0], "total": row[1] or 0} for row in months_result.all()]
+ # The headline figure is the same row set, bucketed differently —
+ # summing the buckets keeps the two from ever disagreeing.
+ total = sum((m["total"] for m in months), Decimal("0"))
+
+ # Spending only — credits coming back into the group aren't spend,
+ # which is the rule the stacked bar already applied client-side.
+ categories_result = await session.execute(
+ select(
+ Category.id,
+ Category.name,
+ Category.color,
+ func.sum(amount),
+ )
+ .select_from(Transaction)
+ .outerjoin(Category, Transaction.category_id == Category.id)
+ .where(Transaction.id.in_(tx_ids), Transaction.type == "debit")
+ .group_by(Category.id, Category.name, Category.color)
+ .order_by(func.sum(amount).desc())
+ )
+ categories = [
+ {
+ "category_id": row[0],
+ "name": row[1],
+ "color": row[2],
+ "total": row[3] or 0,
+ }
+ for row in categories_result.all()
+ ]
+
+ return {
+ "group_id": group_id,
+ "default_currency": group.default_currency,
+ "total_moved": total,
+ "months": months,
+ "categories": categories,
+ }
diff --git a/backend/tests/api_contract/baseline.json b/backend/tests/api_contract/baseline.json
index 245c3dec..709efc87 100644
--- a/backend/tests/api_contract/baseline.json
+++ b/backend/tests/api_contract/baseline.json
@@ -113,6 +113,7 @@
"GET /api/groups/{group_id}/balances": 401,
"GET /api/groups/{group_id}/members": 401,
"GET /api/groups/{group_id}/settlements": 401,
+ "GET /api/groups/{group_id}/summary": 401,
"GET /api/groups/{group_id}/transactions": 401,
"GET /api/health": 200,
"GET /api/import-logs": 401,
@@ -502,6 +503,7 @@
"GET /api/groups/{group_id}/balances": 200,
"GET /api/groups/{group_id}/members": 200,
"GET /api/groups/{group_id}/settlements": 200,
+ "GET /api/groups/{group_id}/summary": 200,
"GET /api/groups/{group_id}/transactions": 200,
"GET /api/health": 200,
"GET /api/import-logs": 200,
@@ -773,6 +775,7 @@
"GET /api/groups/{group_id}/balances": 404,
"GET /api/groups/{group_id}/members": 404,
"GET /api/groups/{group_id}/settlements": 404,
+ "GET /api/groups/{group_id}/summary": 404,
"GET /api/groups/{group_id}/transactions": 404,
"GET /api/invoice-schedules/{schedule_id}": 404,
"GET /api/invoice-schedules/{schedule_id}/invoices": 404,
diff --git a/backend/tests/test_group_summary.py b/backend/tests/test_group_summary.py
new file mode 100644
index 00000000..c6f8aabf
--- /dev/null
+++ b/backend/tests/test_group_summary.py
@@ -0,0 +1,139 @@
+"""Group spending aggregates: they must cover every split, not a page of them."""
+import uuid
+from datetime import date
+from decimal import Decimal
+
+import pytest
+from httpx import AsyncClient
+
+from app.models.transaction import Transaction
+from app.models.transaction_split import TransactionSplit
+
+pytestmark = pytest.mark.asyncio
+
+
+async def _group_with_member(client: AsyncClient, auth_headers: dict):
+ resp = await client.post(
+ "/api/groups",
+ headers=auth_headers,
+ json={"name": "Flat", "kind": "social", "default_currency": "USD"},
+ )
+ assert resp.status_code == 201, resp.text
+ group = resp.json()
+ resp = await client.post(
+ f"/api/groups/{group['id']}/members", headers=auth_headers, json={"name": "Alice"}
+ )
+ assert resp.status_code == 201, resp.text
+ return group, resp.json()
+
+
+async def test_summary_covers_every_split_not_just_the_recent_page(
+ client, auth_headers, session, test_user, test_workspace, test_account, test_categories
+):
+ """Thirty debits of 10.00 across three months.
+
+ A summary derived from the recent-transactions list would report 200.00
+ over a single month, because that list stops at 20 rows.
+ """
+ group, member = await _group_with_member(client, auth_headers)
+
+ for i in range(30):
+ month = 1 + i // 10 # ten in each of January, February, March
+ txn = Transaction(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ workspace_id=test_workspace.id,
+ account_id=test_account.id,
+ category_id=test_categories[0].id,
+ description=f"Shared {i}",
+ amount=Decimal("10.00"),
+ date=date(2026, month, 1 + i % 10),
+ type="debit",
+ source="manual",
+ )
+ session.add(txn)
+ session.add(
+ TransactionSplit(
+ id=uuid.uuid4(),
+ transaction_id=txn.id,
+ group_member_id=uuid.UUID(member["id"]),
+ workspace_id=test_workspace.id,
+ share_amount=Decimal("5.00"),
+ share_type="exact",
+ )
+ )
+ await session.commit()
+
+ resp = await client.get(f"/api/groups/{group['id']}/summary", headers=auth_headers)
+ assert resp.status_code == 200, resp.text
+ body = resp.json()
+
+ assert Decimal(body["total_moved"]) == Decimal("300.00")
+ assert [m["month"] for m in body["months"]] == ["2026-01", "2026-02", "2026-03"]
+ assert all(Decimal(m["total"]) == Decimal("100.00") for m in body["months"])
+ assert len(body["categories"]) == 1
+ assert Decimal(body["categories"][0]["total"]) == Decimal("300.00")
+
+ # The list it used to be derived from is still capped.
+ resp = await client.get(f"/api/groups/{group['id']}/transactions", headers=auth_headers)
+ assert len(resp.json()) == 20
+
+
+async def test_summary_counts_debits_only_in_the_category_split(
+ client, auth_headers, session, test_user, test_workspace, test_account, test_categories
+):
+ """Money coming back isn't spend: it lifts the total, not the breakdown."""
+ group, member = await _group_with_member(client, auth_headers)
+
+ for amount, kind in ((Decimal("40.00"), "debit"), (Decimal("10.00"), "credit")):
+ txn = Transaction(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ workspace_id=test_workspace.id,
+ account_id=test_account.id,
+ category_id=test_categories[0].id,
+ description=kind,
+ amount=amount,
+ date=date(2026, 5, 4),
+ type=kind,
+ source="manual",
+ )
+ session.add(txn)
+ session.add(
+ TransactionSplit(
+ id=uuid.uuid4(),
+ transaction_id=txn.id,
+ group_member_id=uuid.UUID(member["id"]),
+ workspace_id=test_workspace.id,
+ share_amount=amount / 2,
+ share_type="exact",
+ )
+ )
+ await session.commit()
+
+ body = (await client.get(
+ f"/api/groups/{group['id']}/summary", headers=auth_headers
+ )).json()
+ assert Decimal(body["total_moved"]) == Decimal("50.00")
+ assert Decimal(body["categories"][0]["total"]) == Decimal("40.00")
+
+
+async def test_summary_empty_group(client, auth_headers, test_user):
+ resp = await client.post(
+ "/api/groups",
+ headers=auth_headers,
+ json={"name": "Empty", "kind": "social", "default_currency": "EUR"},
+ )
+ group = resp.json()
+ body = (await client.get(
+ f"/api/groups/{group['id']}/summary", headers=auth_headers
+ )).json()
+ assert Decimal(body["total_moved"]) == Decimal("0")
+ assert body["months"] == []
+ assert body["categories"] == []
+ assert body["default_currency"] == "EUR"
+
+
+async def test_summary_unknown_group_is_404(client, auth_headers, test_user):
+ resp = await client.get(f"/api/groups/{uuid.uuid4()}/summary", headers=auth_headers)
+ assert resp.status_code == 404
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 7437e731..eef29b8e 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -91,6 +91,7 @@ import type {
GroupMember,
GroupSettlement,
GroupBalances,
+ GroupSummary,
TransactionSplitsInput,
TransactionEditPayload,
InstallmentSeriesInput,
@@ -1029,6 +1030,10 @@ export const groups = {
const { data } = await api.get(`/groups/${groupId}/balances`)
return data
},
+ summary: async (groupId: string): Promise<GroupSummary> => {
+ const { data } = await api.get(`/groups/${groupId}/summary`)
+ return data
+ },
transactions: async (groupId: string, limit = 20): Promise<Transaction[]> => {
const { data } = await api.get(`/groups/${groupId}/transactions`, {
params: { limit },
diff --git a/frontend/src/pages/group-detail.tsx b/frontend/src/pages/group-detail.tsx
index a333e18f..0c003de1 100644
--- a/frontend/src/pages/group-detail.tsx
+++ b/frontend/src/pages/group-detail.tsx
@@ -194,12 +194,22 @@ export default function GroupDetailPage() {
enabled: !!groupId,
})
+ // The recent-activity list stays capped — it feeds the "Recent
+ // transactions" card and nothing else.
const { data: groupTxs } = useQuery({
queryKey: ['groups', groupId, 'transactions'],
queryFn: () => groupsApi.transactions(groupId, 20),
enabled: !!groupId,
})
+ // Totals come from the server so they describe the whole group rather
+ // than whatever happens to be on the first page of the list.
+ const { data: summary, isError: summaryFailed } = useQuery({
+ queryKey: ['groups', groupId, 'summary'],
+ queryFn: () => groupsApi.summary(groupId),
+ enabled: !!groupId,
+ })
+
// ── Member management ────────────────────────────────────────
const [memberDialogOpen, setMemberDialogOpen] = useState(false)
const [editingMember, setEditingMember] = useState<GroupMember | null>(null)
@@ -411,17 +421,12 @@ export default function GroupDetailPage() {
// ── KPIs ─────────────────────────────────────────────────────
const groupCurrency = group?.default_currency ?? 'USD'
- // Sum cross-currency rows in the group's primary terms — using
- // amount_primary when available, otherwise the native amount. Without
- // this, EUR rows would silently add as USD (a €100 hotel would count
- // as $100, throwing off the KPI vs. spending-by-category breakdown).
- const totalMoved = useMemo(() => {
- if (!groupTxs) return 0
- return groupTxs.reduce(
- (sum, tx) => sum + Number(tx.amount_primary ?? tx.amount),
- 0,
- )
- }, [groupTxs])
+ // One flag for everything the summary feeds. Without it the KPI reads
+ // 0 while the request is still in flight, and a failed background
+ // refetch leaves TanStack's cached data in place — so the KPI would say
+ // "—" while the charts below kept drawing the stale numbers.
+ const summaryReady = !!summary && !summaryFailed
+ const totalMoved = Number(summary?.total_moved ?? 0)
// KPIs roll up across currencies using each line's
// amount_in_default_currency (FX-converted server-side). Filtering by
@@ -503,43 +508,26 @@ export default function GroupDetailPage() {
}, [balances, isOwner, viewerMember, ownerMember, memberNameById, locale])
const monthlyData = useMemo(() => {
- if (!groupTxs || groupTxs.length === 0) return []
- const byMonth = new Map<string, number>()
- for (const tx of groupTxs) {
- const m = tx.date.slice(0, 7)
- byMonth.set(m, (byMonth.get(m) ?? 0) + Number(tx.amount_primary ?? tx.amount))
- }
- return Array.from(byMonth.entries())
- .sort(([a], [b]) => a.localeCompare(b))
- .map(([month, total]) => ({
- month: new Date(month + '-01').toLocaleString(dateLocale, { month: 'short' }),
- total: Number(total.toFixed(2)),
- }))
- }, [groupTxs, dateLocale])
+ if (!summary) return []
+ return summary.months.map(({ month, total }) => ({
+ // Local date from the parts: new Date('2026-03-01') is UTC midnight,
+ // which lands in February for anyone west of Greenwich.
+ month: new Date(Number(month.slice(0, 4)), Number(month.slice(5, 7)) - 1, 1)
+ .toLocaleString(dateLocale, { month: 'short' }),
+ total: Number(Number(total).toFixed(2)),
+ }))
+ }, [summary, dateLocale])
- // Group spending broken down by category — for the stacked horizontal
- // bar. We sum debits only (income/credits aren't "spending"). When a
- // tx has amount_primary we use that so cross-currency rows are
- // comparable; otherwise fall back to the native amount, which is fine
- // for single-currency groups.
+ // Shape the server's per-category totals for the stacked bar.
const categoryBreakdown = useMemo(() => {
- if (!groupTxs || groupTxs.length === 0) return [] as { id: string; name: string; color: string; total: number }[]
- const map = new Map<string, { id: string; name: string; color: string; total: number }>()
- for (const tx of groupTxs) {
- if (tx.type !== 'debit') continue
- const id = tx.category?.id ?? 'uncategorized'
- const name = tx.category?.name ?? t('splitGroups.uncategorized')
- const color = tx.category?.color ?? '#6B7280'
- const value = Number(tx.amount_primary ?? tx.amount)
- const existing = map.get(id)
- if (existing) {
- existing.total += value
- } else {
- map.set(id, { id, name, color, total: value })
- }
- }
- return Array.from(map.values()).sort((a, b) => b.total - a.total)
- }, [groupTxs, t])
+ if (!summary) return [] as { id: string; name: string; color: string; total: number }[]
+ return summary.categories.map((c) => ({
+ id: c.category_id ?? 'uncategorized',
+ name: c.name ?? t('splitGroups.uncategorized'),
+ color: c.color ?? '#6B7280',
+ total: Number(c.total),
+ }))
+ }, [summary, t])
const categoryBreakdownTotal = useMemo(
() => categoryBreakdown.reduce((s, c) => s + c.total, 0),
@@ -583,7 +571,7 @@ export default function GroupDetailPage() {
<div className="grid grid-cols-1 sm:grid-cols-3 gap-3 sm:gap-4">
<KpiCard
label={t('splitGroups.kpiTotalMoved')}
- value={formatCurrency(totalMoved, groupCurrency, locale)}
+ value={summaryReady ? formatCurrency(totalMoved, groupCurrency, locale) : '—'}
icon={Wallet}
/>
<KpiCard
@@ -603,7 +591,7 @@ export default function GroupDetailPage() {
</div>
{/* Spending trend (compact) */}
- {monthlyData.length > 1 && (
+ {summaryReady && monthlyData.length > 1 && (
<SectionCard>
<SectionHeader
title={t('splitGroups.spendingTrend')}
@@ -637,7 +625,7 @@ export default function GroupDetailPage() {
{/* Category distribution — single horizontal stacked bar split
by category, with a legend showing absolute and % per slice. */}
- {categoryBreakdownTotal > 0 && (
+ {summaryReady && categoryBreakdownTotal > 0 && (
<SectionCard>
<SectionHeader
title={t('splitGroups.byCategory')}
diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts
index 65317a09..87fe501b 100644
--- a/frontend/src/types/index.ts
+++ b/frontend/src/types/index.ts
@@ -459,6 +459,28 @@ export interface GroupBalances {
lines: GroupBalanceLine[]
}
+export interface GroupSummaryMonth {
+ /** "YYYY-MM" — the client formats it for display. */
+ month: string
+ total: number
+}
+
+export interface GroupSummaryCategory {
+ /** Null for transactions with no category. */
+ category_id: string | null
+ name: string | null
+ color: string | null
+ total: number
+}
+
+export interface GroupSummary {
+ group_id: string
+ default_currency: string
+ total_moved: number
+ months: GroupSummaryMonth[]
+ categories: GroupSummaryCategory[]
+}
+
/** A fiscal document belonging to a payee. `kind` mirrors the backend's
* closed TaxIdKind; the value arrives normalised. */
export interface PayeeTaxId {