Open-source personal finance manager. Self-hosted, privacy-first.
feature: splitting transactions (#95) (#140)
Tássio Noronha987631315f50
diff --git a/.gitignore b/.gitignoreindex 99e88210..2a4f527e 100644--- a/.gitignore+++ b/.gitignore@@ -5,6 +5,7 @@.claudedocs/plans/tmp/+docker-compose.override.yml# Ignore local configuration files-.vscode/\ No newline at end of file+.vscode/diff --git a/backend/alembic/versions/044_split_transactions.py b/backend/alembic/versions/044_split_transactions.pynew file mode 100644index 00000000..5c67af42--- /dev/null+++ b/backend/alembic/versions/044_split_transactions.py@@ -0,0 +1,240 @@+"""split transactions: groups, members, splits, settlements++Adds the schema for splitting a transaction across multiple participants+(roommates, travel groups, cost centers, projects, clients). Independent+from the account ledger — the transaction keeps the full amount on the+owner's account; splits track the social/allocation debt separately.++Tables:+- groups: a bag of participants. `kind` makes the same table serve B2C+ social groups and B2B cost-center/project/client allocations without+ schema changes.+- group_members: participants. `linked_user_id` is nullable so shadow+ members (no Securo account) work from day one.+- transaction_splits: per-member share of a transaction. `share_amount`+ is always materialized in the transaction's currency; `share_type` is+ metadata for round-trip editing.+- group_settlements: payback / chargeback records, optionally linked to+ a real transaction when cash actually moves.++`groups.user_id` is the single owner today and will become workspace_id+when multi-user workspaces land — the FK shape is identical, so the+migration cost is just a column rename + backfill.++Revision ID: 044+Revises: 043+Create Date: 2026-04-28+"""++from typing import Sequence, Union++import sqlalchemy as sa+from alembic import op+from sqlalchemy.dialects.postgresql import UUID++revision: str = "044"+down_revision: Union[str, None] = "043"+branch_labels: Union[str, Sequence[str], None] = None+depends_on: Union[str, Sequence[str], None] = None+++def upgrade() -> None:+ op.create_table(+ "groups",+ sa.Column("id", UUID(as_uuid=True), primary_key=True),+ sa.Column(+ "user_id",+ UUID(as_uuid=True),+ sa.ForeignKey("users.id", ondelete="CASCADE"),+ nullable=False,+ ),+ sa.Column("name", sa.String(100), nullable=False),+ # social | cost_center | project | client | other. Drives UI labels+ # and (later) settlement workflows; the data model is identical.+ sa.Column("kind", sa.String(20), server_default="social", nullable=False),+ sa.Column("default_currency", sa.String(3), server_default="USD", nullable=False),+ sa.Column("icon", sa.String(50), server_default="users", nullable=False),+ sa.Column("color", sa.String(7), server_default="#6B7280", nullable=False),+ sa.Column(+ "is_archived", sa.Boolean, server_default=sa.text("false"), nullable=False+ ),+ sa.Column("notes", sa.String(1000), nullable=True),+ sa.Column(+ "created_at",+ sa.DateTime(timezone=True),+ server_default=sa.func.now(),+ nullable=False,+ ),+ )+ op.create_index("ix_groups_user_id", "groups", ["user_id"])+ op.create_unique_constraint("uq_groups_user_id_name", "groups", ["user_id", "name"])++ op.create_table(+ "group_members",+ sa.Column("id", UUID(as_uuid=True), primary_key=True),+ sa.Column(+ "group_id",+ UUID(as_uuid=True),+ sa.ForeignKey("groups.id", ondelete="CASCADE"),+ nullable=False,+ ),+ sa.Column("name", sa.String(100), nullable=False),+ # Optional link to a real Securo user. SET NULL on delete so the+ # shadow record (and its history) survives if the linked account+ # is removed.+ sa.Column(+ "linked_user_id",+ UUID(as_uuid=True),+ sa.ForeignKey("users.id", ondelete="SET NULL"),+ nullable=True,+ ),+ sa.Column("email", sa.String(255), nullable=True),+ sa.Column(+ "is_self",+ sa.Boolean,+ server_default=sa.text("false"),+ nullable=False,+ ),+ sa.Column(+ "created_at",+ sa.DateTime(timezone=True),+ server_default=sa.func.now(),+ nullable=False,+ ),+ )+ op.create_index("ix_group_members_group_id", "group_members", ["group_id"])+ op.create_index(+ "ix_group_members_linked_user_id", "group_members", ["linked_user_id"]+ )+ op.create_unique_constraint(+ "uq_group_members_group_id_name", "group_members", ["group_id", "name"]+ )++ op.create_table(+ "transaction_splits",+ sa.Column("id", UUID(as_uuid=True), primary_key=True),+ sa.Column(+ "transaction_id",+ UUID(as_uuid=True),+ sa.ForeignKey("transactions.id", ondelete="CASCADE"),+ nullable=False,+ ),+ # RESTRICT: a member with active splits cannot be removed from+ # the group without first reassigning or deleting those splits.+ # Group-level CASCADE still works when no splits exist; otherwise+ # the user is forced to clean up first (UI-driven).+ sa.Column(+ "group_member_id",+ UUID(as_uuid=True),+ sa.ForeignKey("group_members.id", ondelete="RESTRICT"),+ nullable=False,+ ),+ # Always materialized in the parent transaction's currency. The+ # rounding residual is assigned to the last share at write time+ # so the sum is exact.+ sa.Column("share_amount", sa.Numeric(precision=15, scale=2), nullable=False),+ # equal | exact | percent — metadata only; share_amount is the+ # source of truth.+ sa.Column("share_type", sa.String(10), server_default="exact", nullable=False),+ # Preserved only for share_type='percent' so an edit round-trips+ # without re-deriving.+ sa.Column("share_pct", sa.Numeric(precision=5, scale=2), nullable=True),+ sa.Column("notes", sa.String(500), nullable=True),+ sa.Column(+ "created_at",+ sa.DateTime(timezone=True),+ server_default=sa.func.now(),+ nullable=False,+ ),+ )+ op.create_index(+ "ix_transaction_splits_transaction_id",+ "transaction_splits",+ ["transaction_id"],+ )+ op.create_index(+ "ix_transaction_splits_group_member_id",+ "transaction_splits",+ ["group_member_id"],+ )+ op.create_unique_constraint(+ "uq_transaction_splits_tx_member",+ "transaction_splits",+ ["transaction_id", "group_member_id"],+ )++ op.create_table(+ "group_settlements",+ sa.Column("id", UUID(as_uuid=True), primary_key=True),+ sa.Column(+ "group_id",+ UUID(as_uuid=True),+ sa.ForeignKey("groups.id", ondelete="CASCADE"),+ nullable=False,+ ),+ sa.Column(+ "from_member_id",+ UUID(as_uuid=True),+ sa.ForeignKey("group_members.id", ondelete="RESTRICT"),+ nullable=False,+ ),+ sa.Column(+ "to_member_id",+ UUID(as_uuid=True),+ sa.ForeignKey("group_members.id", ondelete="RESTRICT"),+ nullable=False,+ ),+ sa.Column("amount", sa.Numeric(precision=15, scale=2), nullable=False),+ sa.Column("currency", sa.String(3), nullable=False),+ sa.Column("date", sa.Date, nullable=False),+ # Optional pointer to a real bank transaction so the cash side+ # reconciles against the account ledger. SET NULL: settlement+ # record survives if the linked tx is later deleted.+ sa.Column(+ "transaction_id",+ UUID(as_uuid=True),+ sa.ForeignKey("transactions.id", ondelete="SET NULL"),+ nullable=True,+ ),+ sa.Column("notes", sa.String(1000), nullable=True),+ sa.Column(+ "created_at",+ sa.DateTime(timezone=True),+ server_default=sa.func.now(),+ nullable=False,+ ),+ )+ op.create_index("ix_group_settlements_group_id", "group_settlements", ["group_id"])+ op.create_index(+ "ix_group_settlements_transaction_id",+ "group_settlements",+ ["transaction_id"],+ )+++def downgrade() -> None:+ op.drop_index("ix_group_settlements_transaction_id", table_name="group_settlements")+ op.drop_index("ix_group_settlements_group_id", table_name="group_settlements")+ op.drop_table("group_settlements")++ op.drop_constraint(+ "uq_transaction_splits_tx_member", "transaction_splits", type_="unique"+ )+ op.drop_index(+ "ix_transaction_splits_group_member_id", table_name="transaction_splits"+ )+ op.drop_index(+ "ix_transaction_splits_transaction_id", table_name="transaction_splits"+ )+ op.drop_table("transaction_splits")++ op.drop_constraint(+ "uq_group_members_group_id_name", "group_members", type_="unique"+ )+ op.drop_index("ix_group_members_linked_user_id", table_name="group_members")+ op.drop_index("ix_group_members_group_id", table_name="group_members")+ op.drop_table("group_members")++ op.drop_constraint("uq_groups_user_id_name", "groups", type_="unique")+ op.drop_index("ix_groups_user_id", table_name="groups")+ op.drop_table("groups")diff --git a/backend/alembic/versions/045_settlement_receiver_tx.py b/backend/alembic/versions/045_settlement_receiver_tx.pynew file mode 100644index 00000000..422283ea--- /dev/null+++ b/backend/alembic/versions/045_settlement_receiver_tx.py@@ -0,0 +1,48 @@+"""group_settlements.receiver_transaction_id — receiver-side credit link++Settlements that involve a Securo-linked receiver now mirror the+payer's debit with a corresponding credit on the receiver's account.+This column points to that auto-created credit. Nullable: settlements+where the receiver is a shadow member (no linked user) or has no+suitable account stay payer-only.++Revision ID: 045+Revises: 044+Create Date: 2026-04-29+"""++from typing import Sequence, Union++import sqlalchemy as sa+from alembic import op+from sqlalchemy.dialects.postgresql import UUID++revision: str = "045"+down_revision: Union[str, None] = "044"+branch_labels: Union[str, Sequence[str], None] = None+depends_on: Union[str, Sequence[str], None] = None+++def upgrade() -> None:+ op.add_column(+ "group_settlements",+ sa.Column(+ "receiver_transaction_id",+ UUID(as_uuid=True),+ sa.ForeignKey("transactions.id", ondelete="SET NULL"),+ nullable=True,+ ),+ )+ op.create_index(+ "ix_group_settlements_receiver_transaction_id",+ "group_settlements",+ ["receiver_transaction_id"],+ )+++def downgrade() -> None:+ op.drop_index(+ "ix_group_settlements_receiver_transaction_id",+ table_name="group_settlements",+ )+ op.drop_column("group_settlements", "receiver_transaction_id")diff --git a/backend/app/api/groups.py b/backend/app/api/groups.pynew file mode 100644index 00000000..f3821951--- /dev/null+++ b/backend/app/api/groups.py@@ -0,0 +1,265 @@+import uuid++from fastapi import APIRouter, Depends, HTTPException, Query, status+from sqlalchemy.ext.asyncio import AsyncSession++from app.core.auth import current_active_user+from app.core.database import get_async_session+from app.models.user import User+from app.schemas.group import (+ GroupBalances,+ GroupCreate,+ GroupMemberCreate,+ GroupMemberRead,+ GroupMemberUpdate,+ GroupRead,+ GroupUpdate,+)+from app.schemas.group_settlement import (+ GroupSettlementCreate,+ GroupSettlementRead,+ GroupSettlementUpdate,+)+from app.schemas.transaction import TransactionRead+from app.services import balance_service, group_service, settlement_service++router = APIRouter(prefix="/api/groups", tags=["groups"])++[email protected]("", response_model=list[GroupRead])+async def list_groups(+ include_archived: bool = Query(False),+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ return await group_service.list_groups(session, user.id, include_archived=include_archived)++[email protected]("", response_model=GroupRead, status_code=status.HTTP_201_CREATED)+async def create_group(+ data: GroupCreate,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ try:+ return await group_service.create_group(session, user.id, data)+ except ValueError as e:+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))++[email protected]("/{group_id}", response_model=GroupRead)+async def get_group(+ group_id: uuid.UUID,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ # Read endpoint — visible to the owner and to any linked member,+ # so a person added to someone else's group can see the shared view.+ group = await group_service.get_group_visible(session, group_id, user.id)+ if not group:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Group not found")+ return group++[email protected]("/{group_id}", response_model=GroupRead)+async def update_group(+ group_id: uuid.UUID,+ data: GroupUpdate,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ try:+ group = await group_service.update_group(session, group_id, user.id, data)+ except ValueError as e:+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))+ if not group:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Group not found")+ return group++[email protected]("/{group_id}", status_code=status.HTTP_204_NO_CONTENT)+async def delete_group(+ group_id: uuid.UUID,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ try:+ deleted = await group_service.delete_group(session, group_id, user.id)+ except ValueError as e:+ raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e))+ if not deleted:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Group not found")++[email protected]("/{group_id}/members", response_model=list[GroupMemberRead])+async def list_members(+ group_id: uuid.UUID,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ members = await group_service.list_members(session, group_id, user.id)+ if members is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Group not found")+ return members+++ "/{group_id}/members",+ response_model=GroupMemberRead,+ status_code=status.HTTP_201_CREATED,+)+async def create_member(+ group_id: uuid.UUID,+ data: GroupMemberCreate,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ try:+ member = await group_service.create_member(session, group_id, user.id, data)+ except ValueError as e:+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))+ if member is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Group not found")+ return member++[email protected]("/{group_id}/members/{member_id}", response_model=GroupMemberRead)+async def update_member(+ group_id: uuid.UUID,+ member_id: uuid.UUID,+ data: GroupMemberUpdate,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ try:+ member = await group_service.update_member(session, group_id, member_id, user.id, data)+ except ValueError as e:+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))+ if member is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Member not found")+ return member+++ "/{group_id}/members/{member_id}", status_code=status.HTTP_204_NO_CONTENT+)+async def delete_member(+ group_id: uuid.UUID,+ member_id: uuid.UUID,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ try:+ deleted = await group_service.delete_member(session, group_id, member_id, user.id)+ except ValueError as e:+ raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e))+ if not deleted:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Member not found")++[email protected]("/{group_id}/transactions", response_model=list[TransactionRead])+async def list_group_transactions(+ group_id: uuid.UUID,+ limit: int = 20,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ txs = await group_service.list_transactions(session, group_id, user.id, limit=limit)+ if txs is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Group not found")+ return txs++[email protected]("/{group_id}/balances", response_model=GroupBalances)+async def get_balances(+ group_id: uuid.UUID,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ balances = await balance_service.compute_balances(session, group_id, user.id)+ if balances is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Group not found")+ return balances++[email protected]("/{group_id}/settlements", response_model=list[GroupSettlementRead])+async def list_settlements(+ group_id: uuid.UUID,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ settlements = await settlement_service.list_settlements(session, group_id, user.id)+ if settlements is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Group not found")+ return settlements+++ "/{group_id}/settlements",+ response_model=GroupSettlementRead,+ status_code=status.HTTP_201_CREATED,+)+async def create_settlement(+ group_id: uuid.UUID,+ data: GroupSettlementCreate,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ try:+ settlement = await settlement_service.create_settlement(+ session, group_id, user.id, data+ )+ except PermissionError as e:+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(e))+ except ValueError as e:+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))+ if settlement is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Group not found")+ return settlement+++ "/{group_id}/settlements/{settlement_id}", response_model=GroupSettlementRead+)+async def update_settlement(+ group_id: uuid.UUID,+ settlement_id: uuid.UUID,+ data: GroupSettlementUpdate,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ try:+ settlement = await settlement_service.update_settlement(+ session, group_id, settlement_id, user.id, data+ )+ except PermissionError as e:+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(e))+ except ValueError as e:+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))+ if settlement is None:+ raise HTTPException(+ status_code=status.HTTP_404_NOT_FOUND, detail="Settlement not found"+ )+ return settlement+++ "/{group_id}/settlements/{settlement_id}",+ status_code=status.HTTP_204_NO_CONTENT,+)+async def delete_settlement(+ group_id: uuid.UUID,+ settlement_id: uuid.UUID,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ try:+ deleted = await settlement_service.delete_settlement(+ session, group_id, settlement_id, user.id+ )+ except PermissionError as e:+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(e))+ if not deleted:+ raise HTTPException(+ status_code=status.HTTP_404_NOT_FOUND, detail="Settlement not found"+ )diff --git a/backend/app/api/transactions.py b/backend/app/api/transactions.pyindex 36735679..34c4c69b 100644--- a/backend/app/api/transactions.py+++ b/backend/app/api/transactions.py@@ -55,6 +55,7 @@ async def list_transactions(from_date: Optional[date] = Query(None, alias="from"),to_date: Optional[date] = Query(None, alias="to"),bill_id: Optional[uuid.UUID] = Query(None, description="Filter by credit-card bill (issue #92); takes precedence over from/to"),+ group_id: Optional[uuid.UUID] = Query(None, description="Filter to transactions split through this group; widens visibility for linked members"),unbilled_only: bool = Query(False, description="Cycle-math fallback only: exclude txs already linked to any bill (used for in-progress CC cycles)"),q: Optional[str] = Query(None),uncategorized: bool = Query(False),@@ -78,6 +79,7 @@ async def list_transactions(accounting_mode=accounting_mode,tags=tags,bill_id=bill_id,+ group_id=group_id,unbilled_only=unbilled_only,)primary_currency = user.primary_currencydiff --git a/backend/app/api/user_lookup.py b/backend/app/api/user_lookup.pynew file mode 100644index 00000000..c43352da--- /dev/null+++ b/backend/app/api/user_lookup.py@@ -0,0 +1,62 @@+"""User lookup for group invites.++Two modes:+- ``/lookup`` — exact-match by email, used to validate a typed address+ before creating a member.+- ``/directory`` — flat list of all users on the instance, used to power+ the "pick an existing user" dropdown when adding a member.++The directory endpoint exposes every user's email to any authenticated+caller. That is acceptable for self-hosted, single-tenant deployments+(everyone on the instance trusts each other). It will need to be scoped+to "users in the same organization" once multi-tenancy lands; flag this+when introducing org boundaries.+"""++import uuid++from fastapi import APIRouter, Depends, HTTPException, Query, status+from pydantic import BaseModel, ConfigDict, EmailStr+from sqlalchemy import func, select+from sqlalchemy.ext.asyncio import AsyncSession++from app.core.auth import current_active_user+from app.core.database import get_async_session+from app.models.user import User++router = APIRouter(prefix="/api/users", tags=["users"])+++class UserLookupResult(BaseModel):+ id: uuid.UUID+ email: EmailStr++ model_config = ConfigDict(from_attributes=True)++[email protected]("/lookup", response_model=UserLookupResult)+async def lookup_user_by_email(+ email: EmailStr = Query(..., description="Exact email to look up"),+ session: AsyncSession = Depends(get_async_session),+ _: User = Depends(current_active_user),+):+ result = await session.execute(+ select(User).where(func.lower(User.email) == email.lower())+ )+ user = result.scalar_one_or_none()+ if user is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")+ return user++[email protected]("/directory", response_model=list[UserLookupResult])+async def list_users_directory(+ session: AsyncSession = Depends(get_async_session),+ _: User = Depends(current_active_user),+):+ """List every user on the instance — for the member-picker dropdown.++ Single-tenant assumption: scope to org once multi-tenancy lands.+ """+ result = await session.execute(select(User).order_by(User.email))+ return list(result.scalars().all())diff --git a/backend/app/main.py b/backend/app/main.pyindex 5db46b0f..471479c5 100644--- a/backend/app/main.py+++ b/backend/app/main.py@@ -7,6 +7,7 @@ from fastapi.middleware.cors import CORSMiddlewarefrom app.api.accounts import router as accounts_routerfrom app.api.budgets import router as budgets_routerfrom app.api.goals import router as goals_router+from app.api.groups import router as groups_routerfrom app.api.categories import router as categories_routerfrom app.api.category_groups import router as category_groups_routerfrom app.api.connections import router as connections_router@@ -29,6 +30,7 @@ from app.api.payees import router as payees_routerfrom app.api.settings import router as settings_routerfrom app.api.transactions import router as transactions_routerfrom app.api.two_factor import router as two_factor_router+from app.api.user_lookup import router as user_lookup_routerfrom app.api.admin import router as admin_router, check_registration_enabledfrom app.core.auth import fastapi_usersfrom app.core.config import get_settings@@ -94,6 +96,10 @@ app.include_router(tags=["auth"],dependencies=[Depends(password_reset_rate_limit)],)+# user_lookup must precede the fastapi-users router below so the+# `/api/users/lookup` path isn't captured by the catch-all `/{id}`+# route fastapi-users mounts.+app.include_router(user_lookup_router)app.include_router(fastapi_users.get_users_router(UserRead, UserUpdate),prefix="/api/users",@@ -112,6 +118,7 @@ app.include_router(connections_router)app.include_router(recurring_router)app.include_router(budgets_router)app.include_router(goals_router)+app.include_router(groups_router)app.include_router(assets_router)app.include_router(asset_groups_router)app.include_router(dashboard_router)diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.pyindex 57e50539..39ed9c75 100644--- a/backend/app/models/__init__.py+++ b/backend/app/models/__init__.py@@ -17,6 +17,9 @@ from app.models.payee import Payee, PayeeMappingfrom app.models.app_settings import AppSettingfrom app.models.goal import Goalfrom app.models.credit_card_bill import CreditCardBill+from app.models.group import Group, GroupMember+from app.models.transaction_split import TransactionSplit+from app.models.group_settlement import GroupSettlement__all__ = ["User",@@ -39,4 +42,8 @@ __all__ = ["AppSetting","Goal","CreditCardBill",+ "Group",+ "GroupMember",+ "TransactionSplit",+ "GroupSettlement",]diff --git a/backend/app/models/group.py b/backend/app/models/group.pynew file mode 100644index 00000000..763d3ef1--- /dev/null+++ b/backend/app/models/group.py@@ -0,0 +1,82 @@+import uuid+from datetime import datetime, timezone+from typing import TYPE_CHECKING, Optional++from sqlalchemy import Boolean, DateTime, ForeignKey, String+from sqlalchemy.dialects.postgresql import UUID+from sqlalchemy.orm import Mapped, mapped_column, relationship++from app.core.database import Base++if TYPE_CHECKING:+ from app.models.group_settlement import GroupSettlement+ from app.models.transaction_split import TransactionSplit+ from app.models.user import User+++# Allowed values for Group.kind. The data model is identical across+# kinds; this is metadata that drives UI labels and (later) settlement+# workflows. Keeps the same table B2C-friendly (social) and B2B-ready+# (cost_center / project / client) without a schema change.+GROUP_KINDS = ("social", "cost_center", "project", "client", "other")++# Allowed values for TransactionSplit.share_type — kept here so models+# importing Group don't pull from the splits module.+SHARE_TYPES = ("equal", "exact", "percent")+++class Group(Base):+ __tablename__ = "groups"++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ # Single owner today; will become workspace_id when multi-user+ # workspaces land. Service code never assumes+ # transaction.user_id == group.user_id — always join through this FK.+ user_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE")+ )+ name: Mapped[str] = mapped_column(String(100))+ kind: Mapped[str] = mapped_column(String(20), default="social", server_default="social")+ default_currency: Mapped[str] = mapped_column(String(3), default="USD", server_default="USD")+ icon: Mapped[str] = mapped_column(String(50), default="users", server_default="users")+ color: Mapped[str] = mapped_column(String(7), default="#6B7280", server_default="#6B7280")+ is_archived: Mapped[bool] = mapped_column(Boolean, default=False, server_default="false")+ notes: Mapped[Optional[str]] = mapped_column(String(1000), nullable=True)+ created_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)+ )++ user: Mapped["User"] = relationship()+ members: Mapped[list["GroupMember"]] = relationship(+ back_populates="group", cascade="all, delete-orphan"+ )+ settlements: Mapped[list["GroupSettlement"]] = relationship(+ back_populates="group", cascade="all, delete-orphan"+ )+++class GroupMember(Base):+ __tablename__ = "group_members"++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ group_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("groups.id", ondelete="CASCADE")+ )+ name: Mapped[str] = mapped_column(String(100))+ # Nullable so shadow members (non-Securo people) work from day one.+ # SET NULL on delete preserves the shadow record + its history if+ # the linked account is removed.+ linked_user_id: Mapped[Optional[uuid.UUID]] = mapped_column(+ UUID(as_uuid=True), ForeignKey("users.id", ondelete="SET NULL"), nullable=True+ )+ email: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)+ # Marks the member that represents the group owner ("me"). Used to+ # compute "you owe / owes you" balances without scanning user_id on+ # every read.+ is_self: Mapped[bool] = mapped_column(Boolean, default=False, server_default="false")+ created_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)+ )++ group: Mapped["Group"] = relationship(back_populates="members")+ splits: Mapped[list["TransactionSplit"]] = relationship(back_populates="member")diff --git a/backend/app/models/group_settlement.py b/backend/app/models/group_settlement.pynew file mode 100644index 00000000..646a0e2d--- /dev/null+++ b/backend/app/models/group_settlement.py@@ -0,0 +1,60 @@+import uuid+from datetime import date as _date, datetime, timezone+from decimal import Decimal+from typing import TYPE_CHECKING, Optional++from sqlalchemy import Date, DateTime, ForeignKey, Numeric, String+from sqlalchemy.dialects.postgresql import UUID+from sqlalchemy.orm import Mapped, mapped_column, relationship++from app.core.database import Base++if TYPE_CHECKING:+ from app.models.group import Group, GroupMember+ from app.models.transaction import Transaction+++class GroupSettlement(Base):+ __tablename__ = "group_settlements"++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ group_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("groups.id", ondelete="CASCADE")+ )+ from_member_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("group_members.id", ondelete="RESTRICT")+ )+ to_member_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("group_members.id", ondelete="RESTRICT")+ )+ amount: Mapped[Decimal] = mapped_column(Numeric(precision=15, scale=2))+ currency: Mapped[str] = mapped_column(String(3))+ date: Mapped[_date] = mapped_column(Date)+ # Optional link to a real bank transaction so the cash side+ # reconciles against the account ledger. SET NULL on delete: the+ # settlement record survives if the linked tx is later removed.+ transaction_id: Mapped[Optional[uuid.UUID]] = mapped_column(+ UUID(as_uuid=True),+ ForeignKey("transactions.id", ondelete="SET NULL"),+ nullable=True,+ )+ # Receiver-side mirror: when the to_member is a linked Securo user+ # with at least one checking/savings account, the settlement also+ # creates a credit on their account. This column points to it.+ receiver_transaction_id: Mapped[Optional[uuid.UUID]] = mapped_column(+ UUID(as_uuid=True),+ ForeignKey("transactions.id", ondelete="SET NULL"),+ nullable=True,+ )+ notes: Mapped[Optional[str]] = mapped_column(String(1000), nullable=True)+ created_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)+ )++ group: Mapped["Group"] = relationship(back_populates="settlements")+ from_member: Mapped["GroupMember"] = relationship(foreign_keys=[from_member_id])+ to_member: Mapped["GroupMember"] = relationship(foreign_keys=[to_member_id])+ transaction: Mapped[Optional["Transaction"]] = relationship(foreign_keys=[transaction_id])+ receiver_transaction: Mapped[Optional["Transaction"]] = relationship(+ foreign_keys=[receiver_transaction_id]+ )diff --git a/backend/app/models/transaction.py b/backend/app/models/transaction.pyindex 404d48d9..899fb724 100644--- a/backend/app/models/transaction.py+++ b/backend/app/models/transaction.py@@ -16,6 +16,7 @@ if TYPE_CHECKING:from app.models.import_log import ImportLogfrom app.models.payee import Payeefrom app.models.transaction_attachment import TransactionAttachment+ from app.models.transaction_split import TransactionSplitclass Transaction(Base):@@ -82,6 +83,9 @@ class Transaction(Base):attachments: Mapped[list["TransactionAttachment"]] = relationship(back_populates="transaction", cascade="all, delete-orphan")+ splits: Mapped[list["TransactionSplit"]] = relationship(+ back_populates="transaction", cascade="all, delete-orphan"+ )# Safety net: `effective_date` is NOT NULL. For non-CC transactions it alwaysdiff --git a/backend/app/models/transaction_split.py b/backend/app/models/transaction_split.pynew file mode 100644index 00000000..2f7c5311--- /dev/null+++ b/backend/app/models/transaction_split.py@@ -0,0 +1,46 @@+import uuid+from datetime import datetime, timezone+from decimal import Decimal+from typing import TYPE_CHECKING, Optional++from sqlalchemy import DateTime, ForeignKey, Numeric, String+from sqlalchemy.dialects.postgresql import UUID+from sqlalchemy.orm import Mapped, mapped_column, relationship++from app.core.database import Base++if TYPE_CHECKING:+ from app.models.group import GroupMember+ from app.models.transaction import Transaction+++class TransactionSplit(Base):+ __tablename__ = "transaction_splits"++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ transaction_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("transactions.id", ondelete="CASCADE")+ )+ # RESTRICT: removing a member with active splits requires reassigning+ # or deleting those splits first. Group-level CASCADE still works+ # when no splits exist.+ group_member_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("group_members.id", ondelete="RESTRICT")+ )+ # Always materialized in the parent transaction's currency. The+ # service layer assigns the rounding residual to the last share so+ # the sum is exact.+ share_amount: Mapped[Decimal] = mapped_column(Numeric(precision=15, scale=2))+ share_type: Mapped[str] = mapped_column(String(10), default="exact", server_default="exact")+ # Preserved only for share_type='percent' so the value round-trips+ # through edit. Otherwise null.+ share_pct: Mapped[Optional[Decimal]] = mapped_column(+ Numeric(precision=5, scale=2), nullable=True+ )+ notes: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)+ created_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)+ )++ transaction: Mapped["Transaction"] = relationship(back_populates="splits")+ member: Mapped["GroupMember"] = relationship(back_populates="splits")diff --git a/backend/app/schemas/dashboard.py b/backend/app/schemas/dashboard.pyindex 2df21432..3c83e910 100644--- a/backend/app/schemas/dashboard.py+++ b/backend/app/schemas/dashboard.py@@ -17,6 +17,12 @@ class DashboardSummary(BaseModel):assets_value: dict[str, float] = {} # currency -> total asset valueassets_value_primary: float = 0.0primary_currency: str = "USD"+ # Net pending balance from group splits (in primary currency).+ # Negative = the user is a net debtor (others paid for them, debt+ # owed). Positive = the user is a net creditor (paid for others,+ # waiting to be paid back). Computed from group balance lines so+ # it already accounts for any partial settlements.+ pending_shares_net: float = 0.0class SpendingByCategory(BaseModel):diff --git a/backend/app/schemas/group.py b/backend/app/schemas/group.pynew file mode 100644index 00000000..e9194394--- /dev/null+++ b/backend/app/schemas/group.py@@ -0,0 +1,87 @@+import uuid+from datetime import datetime+from decimal import Decimal+from typing import Literal, Optional++from pydantic import BaseModel, ConfigDict, EmailStr, Field++GroupKind = Literal["social", "cost_center", "project", "client", "other"]+++class GroupBase(BaseModel):+ name: str = Field(min_length=1, max_length=100)+ kind: GroupKind = "social"+ default_currency: str = Field(default="USD", min_length=3, max_length=3)+ icon: str = "users"+ color: str = "#6B7280"+ notes: Optional[str] = None+++class GroupCreate(GroupBase):+ pass+++class GroupUpdate(BaseModel):+ name: Optional[str] = Field(default=None, min_length=1, max_length=100)+ kind: Optional[GroupKind] = None+ default_currency: Optional[str] = Field(default=None, min_length=3, max_length=3)+ icon: Optional[str] = None+ color: Optional[str] = None+ notes: Optional[str] = None+ is_archived: Optional[bool] = None+++class GroupMemberBase(BaseModel):+ name: str = Field(min_length=1, max_length=100)+ linked_user_id: Optional[uuid.UUID] = None+ email: Optional[EmailStr] = None+ is_self: bool = False+++class GroupMemberCreate(GroupMemberBase):+ pass+++class GroupMemberUpdate(BaseModel):+ name: Optional[str] = Field(default=None, min_length=1, max_length=100)+ linked_user_id: Optional[uuid.UUID] = None+ email: Optional[EmailStr] = None+ is_self: Optional[bool] = None+++class GroupMemberRead(GroupMemberBase):+ id: uuid.UUID+ group_id: uuid.UUID+ created_at: datetime++ model_config = ConfigDict(from_attributes=True)+++class GroupRead(GroupBase):+ id: uuid.UUID+ user_id: uuid.UUID+ is_archived: bool+ # Derived per-request: True if the requester is the group owner.+ # Linked members get False — the frontend uses this to hide edit UI.+ is_owner: bool = True+ created_at: datetime+ members: list[GroupMemberRead] = []++ model_config = ConfigDict(from_attributes=True)+++class GroupBalanceLine(BaseModel):+ member_id: uuid.UUID+ currency: str+ # Positive = member owes the group owner. Negative = owner owes member.+ amount: Decimal+ # Same value FX-converted to the group's default currency, so the+ # frontend can roll up cross-currency lines into a single KPI.+ amount_in_default_currency: Decimal+++class GroupBalances(BaseModel):+ group_id: uuid.UUID+ self_member_id: Optional[uuid.UUID] = None+ default_currency: str+ lines: list[GroupBalanceLine] = []diff --git a/backend/app/schemas/group_settlement.py b/backend/app/schemas/group_settlement.pynew file mode 100644index 00000000..cb66b81e--- /dev/null+++ b/backend/app/schemas/group_settlement.py@@ -0,0 +1,50 @@+import uuid+from datetime import date as _Date, datetime+from decimal import Decimal+from typing import Optional++from pydantic import BaseModel, ConfigDict, Field, model_validator+++class GroupSettlementBase(BaseModel):+ from_member_id: uuid.UUID+ to_member_id: uuid.UUID+ amount: Decimal = Field(gt=0)+ currency: str = Field(min_length=3, max_length=3)+ date: _Date+ transaction_id: Optional[uuid.UUID] = None+ notes: Optional[str] = None++ @model_validator(mode="after")+ def _distinct_members(self):+ if self.from_member_id == self.to_member_id:+ raise ValueError("from_member_id and to_member_id must differ")+ return self+++class GroupSettlementCreate(GroupSettlementBase):+ # When provided, also creates a debit transaction on this account+ # for the settlement amount and links it via `transaction_id`. The+ # account must belong to the requesting user, and the user must be+ # the `from_member` (the payer). Mutually exclusive with passing+ # `transaction_id` directly.+ account_id: Optional[uuid.UUID] = None+ description: Optional[str] = None+++class GroupSettlementUpdate(BaseModel):+ from_member_id: Optional[uuid.UUID] = None+ to_member_id: Optional[uuid.UUID] = None+ amount: Optional[Decimal] = Field(default=None, gt=0)+ currency: Optional[str] = Field(default=None, min_length=3, max_length=3)+ date: Optional[_Date] = None+ transaction_id: Optional[uuid.UUID] = None+ notes: Optional[str] = None+++class GroupSettlementRead(GroupSettlementBase):+ id: uuid.UUID+ group_id: uuid.UUID+ created_at: datetime++ model_config = ConfigDict(from_attributes=True)diff --git a/backend/app/schemas/transaction.py b/backend/app/schemas/transaction.pyindex 84911899..01d29478 100644--- a/backend/app/schemas/transaction.py+++ b/backend/app/schemas/transaction.py@@ -6,6 +6,10 @@ from typing import Optionalfrom pydantic import BaseModel, ConfigDictfrom app.schemas.category import CategoryRead+from app.schemas.transaction_split import (+ TransactionSplitRead,+ TransactionSplitsInput,+)class TransactionBase(BaseModel):@@ -28,6 +32,7 @@ class TransactionCreate(TransactionBase):amount_primary: Optional[Decimal] = Nonefx_rate_used: Optional[Decimal] = Noneeffective_bill_date: Optional[_Date] = None+ splits: Optional[TransactionSplitsInput] = Noneclass TransactionUpdate(BaseModel):@@ -46,6 +51,9 @@ class TransactionUpdate(BaseModel):# CC bucketing override (issue #92). Empty string / explicit null clears# it back to auto. Only meaningful for credit-card accounts.effective_bill_date: Optional[_Date] = None+ # When provided, replaces the transaction's splits wholesale. Pass+ # an object with an empty `splits` list to clear them.+ splits: Optional[TransactionSplitsInput] = Noneclass TransactionRead(TransactionBase):@@ -72,6 +80,18 @@ class TransactionRead(TransactionBase):installment_purchase_date: Optional[_Date] = Nonebill_id: Optional[uuid.UUID] = Noneeffective_bill_date: Optional[_Date] = None+ splits: list[TransactionSplitRead] = []+ # Shared-transaction view fields. Set per-request when the viewer+ # is a linked member of one of this transaction's splits but not+ # its owner. The viewer sees their share amount instead of the+ # parent's full amount, with a back-link to the originating group.+ is_shared: bool = False+ viewer_share: Optional[Decimal] = None+ group_id: Optional[uuid.UUID] = None+ # Display name of the parent's owner — derived from the group's+ # is_self member at request time. Helps the UI show who paid+ # instead of a generic "shared" badge.+ parent_owner_name: Optional[str] = Nonemodel_config = ConfigDict(from_attributes=True)diff --git a/backend/app/schemas/transaction_split.py b/backend/app/schemas/transaction_split.pynew file mode 100644index 00000000..a0c0a0e3--- /dev/null+++ b/backend/app/schemas/transaction_split.py@@ -0,0 +1,39 @@+import uuid+from datetime import datetime+from decimal import Decimal+from typing import Literal, Optional++from pydantic import BaseModel, ConfigDict++ShareType = Literal["equal", "exact", "percent"]+++class TransactionSplitInput(BaseModel):+ """One row in a splits payload. Required fields depend on share_type:+ equal -> only group_member_id; exact -> + share_amount; percent ->+ + share_pct."""++ group_member_id: uuid.UUID+ share_amount: Optional[Decimal] = None+ share_pct: Optional[Decimal] = None+ notes: Optional[str] = None+++class TransactionSplitsInput(BaseModel):+ """Whole splits payload attached to a transaction."""++ share_type: ShareType+ splits: list[TransactionSplitInput]+++class TransactionSplitRead(BaseModel):+ id: uuid.UUID+ transaction_id: uuid.UUID+ group_member_id: uuid.UUID+ share_amount: Decimal+ share_type: str+ share_pct: Optional[Decimal] = None+ notes: Optional[str] = None+ created_at: datetime++ model_config = ConfigDict(from_attributes=True)diff --git a/backend/app/services/_query_filters.py b/backend/app/services/_query_filters.pyindex cc8b2c0b..254eefb9 100644--- a/backend/app/services/_query_filters.py+++ b/backend/app/services/_query_filters.py@@ -4,7 +4,12 @@ Centralizes the "what counts as real income/expense" definition so everyaggregation site agrees. Changes to the rule (e.g. adding a new exclusionsignal) only need to be made here."""-from sqlalchemy import and_, or_, select+import uuid+from datetime import date+from typing import Optional++from sqlalchemy import and_, case, func, or_, select+from sqlalchemy.ext.asyncio import AsyncSessionfrom app.models.category import Categoryfrom app.models.transaction import Transaction@@ -25,6 +30,13 @@ def counts_as_pnl():"""return and_(Transaction.transfer_pair_id.is_(None),+ # Settlement *debits* are repayments of debts that were already+ # booked as an expense via the share. Counting them would+ # double-count. Settlement *credits*, however, represent the+ # receiver actually getting the cash back — they offset the+ # over-recorded expense from when the receiver paid the full+ # parent transaction. So we keep credits, drop debits.+ ~and_(Transaction.source == "settlement", Transaction.type == "debit"),or_(Transaction.category_id.is_(None),Transaction.category_id.not_in(@@ -32,3 +44,303 @@ def counts_as_pnl():),),)+++def counts_as_user_pnl():+ """SQL filter for *user-level* P/L (dashboard, reports, budgets).++ Stricter than `counts_as_pnl`: also drops settlement *credits*. Under+ the share-only model an owner's expense for a split tx is just their+ share, so the corresponding settlement credits would double-count.+ Per-account stats still use `counts_as_pnl` because account ledgers+ track real cash through the account, not user P/L.+ """+ return and_(+ counts_as_pnl(),+ Transaction.source != "settlement",+ )+++async def owner_split_offset_pnl(+ session: AsyncSession,+ user_id: uuid.UUID,+ month_start: date,+ month_end: date,+ use_effective_date: bool = False,+ primary_currency: Optional[str] = None,+) -> tuple[float, float]:+ """Return (income_offset, expense_offset) — the totals to *subtract*+ from the owner's full-amount aggregations so only their own share+ remains. We sum every split share that belongs to a non-owner+ member; subtracting that from the parent's full amount leaves the+ owner's share."""+ from app.models.group import Group, GroupMember+ from app.models.transaction_split import TransactionSplit++ # The user's own member entries: linked_user_id matches OR is_self=true+ # in a group they own. The first form covers groups they're invited to;+ # the second covers their own groups (where is_self=true marks the owner).+ viewer_member_ids = (+ select(GroupMember.id)+ .outerjoin(Group, Group.id == GroupMember.group_id)+ .where(+ or_(+ GroupMember.linked_user_id == user_id,+ and_(GroupMember.is_self == True, Group.user_id == user_id),+ )+ )+ )+ date_col = Transaction.effective_date if use_effective_date else Transaction.date++ result = await session.execute(+ select(+ Transaction.currency,+ func.sum(+ case(+ (Transaction.type == "credit", TransactionSplit.share_amount),+ else_=0,+ )+ ),+ func.sum(+ case(+ (Transaction.type == "debit", TransactionSplit.share_amount),+ else_=0,+ )+ ),+ )+ .join(Transaction, TransactionSplit.transaction_id == Transaction.id)+ .where(+ Transaction.user_id == user_id,+ TransactionSplit.group_member_id.notin_(viewer_member_ids),+ Transaction.source != "opening_balance",+ date_col >= month_start,+ date_col < month_end,+ counts_as_user_pnl(),+ )+ .group_by(Transaction.currency)+ )++ if primary_currency is None:+ income_total = 0.0+ expense_total = 0.0+ for row in result.all():+ income_total += float(row[1] or 0)+ expense_total += float(row[2] or 0)+ return income_total, expense_total++ from decimal import Decimal as _Decimal++ from app.services.fx_rate_service import convert as _convert++ income_total = 0.0+ expense_total = 0.0+ for row in result.all():+ cur, inc_raw, exp_raw = row[0], row[1] or 0, row[2] or 0+ if inc_raw:+ inc_pri, _ = await _convert(session, _Decimal(str(inc_raw)), cur, primary_currency)+ income_total += float(inc_pri)+ if exp_raw:+ exp_pri, _ = await _convert(session, _Decimal(str(exp_raw)), cur, primary_currency)+ expense_total += float(exp_pri)+ return income_total, expense_total+++async def owner_split_offset_by_category(+ session: AsyncSession,+ user_id: uuid.UUID,+ month_start: date,+ month_end: date,+ use_effective_date: bool = False,+ primary_currency: Optional[str] = None,+) -> dict:+ """Per-category, sum of non-owner shares on owner-side debit splits —+ subtract from full owner debits to get the owner's category share."""+ from app.models.group import Group, GroupMember+ from app.models.transaction_split import TransactionSplit++ viewer_member_ids = (+ select(GroupMember.id)+ .outerjoin(Group, Group.id == GroupMember.group_id)+ .where(+ or_(+ GroupMember.linked_user_id == user_id,+ and_(GroupMember.is_self == True, Group.user_id == user_id),+ )+ )+ )+ date_col = Transaction.effective_date if use_effective_date else Transaction.date++ result = await session.execute(+ select(+ Transaction.category_id,+ Transaction.currency,+ func.sum(TransactionSplit.share_amount),+ )+ .join(Transaction, TransactionSplit.transaction_id == Transaction.id)+ .where(+ Transaction.user_id == user_id,+ Transaction.type == "debit",+ TransactionSplit.group_member_id.notin_(viewer_member_ids),+ Transaction.source != "opening_balance",+ date_col >= month_start,+ date_col < month_end,+ counts_as_user_pnl(),+ )+ .group_by(Transaction.category_id, Transaction.currency)+ )++ out: dict = {}+ if primary_currency is None:+ for cat_id, _cur, total in result.all():+ out[cat_id] = out.get(cat_id, 0.0) + float(total or 0)+ return out++ from decimal import Decimal as _Decimal++ from app.services.fx_rate_service import convert as _convert++ for cat_id, cur, total in result.all():+ if not total:+ continue+ converted, _ = await _convert(session, _Decimal(str(total)), cur, primary_currency)+ out[cat_id] = out.get(cat_id, 0.0) + float(converted)+ return out+++async def viewer_shared_pnl(+ session: AsyncSession,+ user_id: uuid.UUID,+ month_start: date,+ month_end: date,+ use_effective_date: bool = False,+ primary_currency: Optional[str] = None,+) -> tuple[float, float]:+ """Return (income, expense) totals contributed by transactions the+ viewer doesn't own but participates in via a group split.++ Concert tickets paid by a friend show up as the viewer's share in+ their own spending picture — without inflating account balances.++ When `primary_currency` is given, mixed-currency shares are+ converted to that currency via the FX service. Otherwise, sums+ are taken in raw nominal terms (only safe when all shares are+ same-currency, e.g., during single-currency tests).+ """+ from app.models.group import GroupMember+ from app.models.transaction_split import TransactionSplit++ member_ids = select(GroupMember.id).where(GroupMember.linked_user_id == user_id)+ date_col = Transaction.effective_date if use_effective_date else Transaction.date++ result = await session.execute(+ select(+ Transaction.currency,+ func.sum(+ case(+ (Transaction.type == "credit", TransactionSplit.share_amount),+ else_=0,+ )+ ),+ func.sum(+ case(+ (Transaction.type == "debit", TransactionSplit.share_amount),+ else_=0,+ )+ ),+ )+ .join(Transaction, TransactionSplit.transaction_id == Transaction.id)+ .where(+ TransactionSplit.group_member_id.in_(member_ids),+ # Avoid double-counting if the viewer also owns the parent.+ Transaction.user_id != user_id,+ Transaction.source != "opening_balance",+ date_col >= month_start,+ date_col < month_end,+ counts_as_pnl(),+ )+ .group_by(Transaction.currency)+ )++ if primary_currency is None:+ # Backward-compatible nominal sum (caller is responsible for+ # currency homogeneity). Acceptable when only one currency is+ # in play.+ income_total = 0.0+ expense_total = 0.0+ for row in result.all():+ income_total += float(row[1] or 0)+ expense_total += float(row[2] or 0)+ return income_total, expense_total++ # FX-aware: convert each currency bucket to primary.+ from decimal import Decimal as _Decimal++ from app.services.fx_rate_service import convert as _convert++ income_total = 0.0+ expense_total = 0.0+ for row in result.all():+ cur, inc_raw, exp_raw = row[0], row[1] or 0, row[2] or 0+ if inc_raw:+ inc_pri, _ = await _convert(session, _Decimal(str(inc_raw)), cur, primary_currency)+ income_total += float(inc_pri)+ if exp_raw:+ exp_pri, _ = await _convert(session, _Decimal(str(exp_raw)), cur, primary_currency)+ expense_total += float(exp_pri)+ return income_total, expense_total+++async def viewer_shared_spending_by_category(+ session: AsyncSession,+ user_id: uuid.UUID,+ month_start: date,+ month_end: date,+ use_effective_date: bool = False,+ primary_currency: Optional[str] = None,+) -> dict:+ """Return {category_id (uuid|None): total_share_expense_float} for+ transactions where the viewer participates via a group split.++ With `primary_currency`, totals are FX-converted; otherwise raw+ nominal sums (single-currency only)."""+ from app.models.group import GroupMember+ from app.models.transaction_split import TransactionSplit++ member_ids = select(GroupMember.id).where(GroupMember.linked_user_id == user_id)+ date_col = Transaction.effective_date if use_effective_date else Transaction.date++ result = await session.execute(+ select(+ Transaction.category_id,+ Transaction.currency,+ func.sum(TransactionSplit.share_amount),+ )+ .join(Transaction, TransactionSplit.transaction_id == Transaction.id)+ .where(+ TransactionSplit.group_member_id.in_(member_ids),+ Transaction.user_id != user_id,+ Transaction.type == "debit",+ Transaction.source != "opening_balance",+ date_col >= month_start,+ date_col < month_end,+ counts_as_pnl(),+ )+ .group_by(Transaction.category_id, Transaction.currency)+ )++ out: dict = {}+ if primary_currency is None:+ for cat_id, _cur, total in result.all():+ out[cat_id] = out.get(cat_id, 0.0) + float(total or 0)+ return out++ from decimal import Decimal as _Decimal++ from app.services.fx_rate_service import convert as _convert++ for cat_id, cur, total in result.all():+ if not total:+ continue+ converted, _ = await _convert(session, _Decimal(str(total)), cur, primary_currency)+ out[cat_id] = out.get(cat_id, 0.0) + float(converted)+ return outdiff --git a/backend/app/services/balance_service.py b/backend/app/services/balance_service.pynew file mode 100644index 00000000..3a3e3496--- /dev/null+++ b/backend/app/services/balance_service.py@@ -0,0 +1,114 @@+"""Group balance computation.++The model assumes the group owner is the implicit payer of every+transaction with splits — i.e. the `is_self` member of the group is the+one whose bank account holds the parent transaction.++For each non-self member M, we compute, per currency:+ + sum of M's split shares on owner-paid transactions (M owes self)+ + settlements where from=self, to=M (self lent to M)+ - settlements where from=M, to=self (M paid self back)++A positive value means M owes the owner; negative means the owner owes M.+Mixed currencies are kept as separate lines — no FX conversion in v1.+"""++import uuid+from collections import defaultdict+from decimal import Decimal+from typing import Optional++from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.group import GroupMember+from app.models.group_settlement import GroupSettlement+from app.models.transaction import Transaction+from app.models.transaction_split import TransactionSplit+++async def compute_balances(+ session: AsyncSession, group_id: uuid.UUID, user_id: uuid.UUID+) -> Optional[dict]:+ # Visible to the owner AND any linked member — they all need to+ # see the same who-owes-whom view.+ from app.services.group_service import get_group_visible++ group = await get_group_visible(session, group_id, user_id)+ if not group:+ return None++ members_result = await session.execute(+ select(GroupMember).where(GroupMember.group_id == group_id)+ )+ members = list(members_result.scalars().all())+ self_member = next((m for m in members if m.is_self), None)++ # member_id -> currency -> Decimal+ totals: dict[uuid.UUID, dict[str, Decimal]] = defaultdict(+ lambda: defaultdict(lambda: Decimal("0"))+ )++ # Splits — each non-self member's share of an owner-paid transaction+ # is what they owe the self member.+ splits_result = await session.execute(+ select(TransactionSplit, Transaction.currency)+ .join(Transaction, TransactionSplit.transaction_id == Transaction.id)+ .join(GroupMember, TransactionSplit.group_member_id == GroupMember.id)+ .where(GroupMember.group_id == group_id)+ )+ for split, currency in splits_result.all():+ if self_member is not None and split.group_member_id == self_member.id:+ continue+ totals[split.group_member_id][currency] += Decimal(str(split.share_amount))++ # Settlements — adjust the pairwise balance with the self member.+ if self_member is not None:+ settlements_result = await session.execute(+ select(GroupSettlement).where(GroupSettlement.group_id == group_id)+ )+ for s in settlements_result.scalars().all():+ amount = Decimal(str(s.amount))+ if s.from_member_id == self_member.id:+ # Self lent to the other party — increases what they owe.+ totals[s.to_member_id][s.currency] += amount+ elif s.to_member_id == self_member.id:+ # Other party paid self back — reduces what they owe.+ totals[s.from_member_id][s.currency] -= amount+ # Cross-member settlements (neither side is self) don't affect+ # the owner's balance ledger and are ignored here.++ # FX-convert each line to the group's default currency so the+ # frontend can roll cross-currency lines up into a single KPI+ # without doing FX itself. Lines stay in their native currency too.+ from app.services.fx_rate_service import convert as _fx_convert++ default_currency = group.default_currency++ lines = []+ for member_id, by_currency in totals.items():+ for currency, amount in by_currency.items():+ if amount == 0:+ continue+ if currency == default_currency:+ amount_in_default = amount+ else:+ converted, _ = await _fx_convert(+ session, amount, currency, default_currency+ )+ amount_in_default = converted+ lines.append(+ {+ "member_id": member_id,+ "currency": currency,+ "amount": amount,+ "amount_in_default_currency": amount_in_default,+ }+ )++ return {+ "group_id": group_id,+ "self_member_id": self_member.id if self_member else None,+ "default_currency": default_currency,+ "lines": lines,+ }diff --git a/backend/app/services/budget_service.py b/backend/app/services/budget_service.pyindex 832e873e..fe2dd4ad 100644--- a/backend/app/services/budget_service.py+++ b/backend/app/services/budget_service.py@@ -12,7 +12,10 @@ from app.models.category_group import CategoryGroupfrom app.models.transaction import Transactionfrom app.models.user import Userfrom app.schemas.budget import BudgetCreate, BudgetUpdate, BudgetVsActual-from app.services._query_filters import counts_as_pnl+from app.services._query_filters import (+ counts_as_user_pnl,+ owner_split_offset_by_category,+)from app.services.admin_service import get_credit_card_accounting_modefrom app.services.dashboard_service import _get_recurring_projectionsfrom app.services.fx_rate_service import convert@@ -263,7 +266,7 @@ async def get_budget_vs_actual(report_date >= month_start,report_date < month_end,Transaction.category_id.isnot(None),- counts_as_pnl(),+ counts_as_user_pnl(),).group_by(Transaction.category_id))@@ -271,6 +274,38 @@ async def get_budget_vs_actual(for row in spending_result.all():spending_map[str(row[0])] = abs(row[1] or Decimal("0"))+ # Subtract non-owner shares of own splits — only the user's share counts.+ own_offset = await owner_split_offset_by_category(+ session, user_id, month_start, month_end,+ use_effective_date=accounting_mode == "accrual",+ primary_currency=primary_currency,+ )+ for cat_uuid, total in own_offset.items():+ if cat_uuid is None:+ continue+ cat_id = str(cat_uuid)+ if cat_id in spending_map:+ spending_map[cat_id] -= Decimal(str(total))+ if spending_map[cat_id] <= 0:+ spending_map.pop(cat_id)++ # Layer in the user's share from group splits — concert tickets+ # paid by a friend are still the user's expense in the budget+ # picture for the matching category. FX-convert per currency to+ # match the rest of the budget (everything else is in primary).+ from app.services._query_filters import viewer_shared_spending_by_category++ shared_by_cat = await viewer_shared_spending_by_category(+ session, user_id, month_start, month_end,+ use_effective_date=accounting_mode == "accrual",+ primary_currency=primary_currency,+ )+ for cat_uuid, total in shared_by_cat.items():+ if cat_uuid is None:+ continue+ cat_id = str(cat_uuid)+ spending_map[cat_id] = spending_map.get(cat_id, Decimal("0")) + Decimal(str(total))+# Add projected recurring transactions for this month (converted to primary currency)projections = await _get_recurring_projections(session, user_id, month_start, month_end)for proj in projections:@@ -295,7 +330,7 @@ async def get_budget_vs_actual(report_date >= prev_month_start,report_date < prev_month_end,Transaction.category_id.isnot(None),- counts_as_pnl(),+ counts_as_user_pnl(),).group_by(Transaction.category_id))@@ -303,6 +338,33 @@ async def get_budget_vs_actual(for row in prev_spending_result.all():prev_spending_map[str(row[0])] = abs(row[1] or Decimal("0"))+ prev_own_offset = await owner_split_offset_by_category(+ session, user_id, prev_month_start, prev_month_end,+ use_effective_date=accounting_mode == "accrual",+ primary_currency=primary_currency,+ )+ for cat_uuid, total in prev_own_offset.items():+ if cat_uuid is None:+ continue+ cat_id = str(cat_uuid)+ if cat_id in prev_spending_map:+ prev_spending_map[cat_id] -= Decimal(str(total))+ if prev_spending_map[cat_id] <= 0:+ prev_spending_map.pop(cat_id)++ # Same shared-share layer for the previous month so the trend+ # comparison is apples-to-apples.+ prev_shared_by_cat = await viewer_shared_spending_by_category(+ session, user_id, prev_month_start, prev_month_end,+ use_effective_date=accounting_mode == "accrual",+ primary_currency=primary_currency,+ )+ for cat_uuid, total in prev_shared_by_cat.items():+ if cat_uuid is None:+ continue+ cat_id = str(cat_uuid)+ prev_spending_map[cat_id] = prev_spending_map.get(cat_id, Decimal("0")) + Decimal(str(total))+# Add projected recurring transactions for previous month (converted to primary currency)prev_projections = await _get_recurring_projections(session, user_id, prev_month_start, prev_month_end)for proj in prev_projections:diff --git a/backend/app/services/dashboard_service.py b/backend/app/services/dashboard_service.pyindex 3ab89673..bd49822f 100644--- a/backend/app/services/dashboard_service.py+++ b/backend/app/services/dashboard_service.py@@ -13,7 +13,13 @@ from app.models.transaction import Transactionfrom app.models.category import Categoryfrom app.models.recurring_transaction import RecurringTransactionfrom app.schemas.dashboard import DashboardSummary, SpendingByCategory, MonthlyTrend, ProjectedTransaction, DailyBalance, BalanceHistory-from app.services._query_filters import counts_as_pnl+from app.services._query_filters import (+ counts_as_user_pnl,+ owner_split_offset_by_category,+ owner_split_offset_pnl,+ viewer_shared_pnl,+ viewer_shared_spending_by_category,+)from app.services.admin_service import get_credit_card_accounting_modefrom app.services.recurring_transaction_service import get_occurrences_in_rangefrom app.services.asset_service import get_total_asset_value@@ -112,8 +118,9 @@ async def get_summary(total_balance[proj["currency"]] = total_balance.get(proj["currency"], 0.0) + signed# Monthly income and expenses — exclude opening_balance so initial deposits- # don't inflate the month's income figure. counts_as_pnl() also skips- # paired transfers and transfer-like categories (e.g. Investimentos).+ # don't inflate the month's income figure. counts_as_user_pnl() skips+ # paired transfers, transfer-like categories AND settlement movements+ # (whose offset is already in the owner's share, see share-only model).monthly_result = await session.execute(select(func.sum(case((Transaction.type == "credit", Transaction.amount), else_=0)),@@ -126,13 +133,30 @@ async def get_summary(report_date >= month_start,report_date < month_end,Transaction.source != "opening_balance",- counts_as_pnl(),+ counts_as_user_pnl(),))monthly_row = monthly_result.one()monthly_income = float(monthly_row[0] or 0)monthly_expenses = float(monthly_row[1] or 0)+ # Subtract non-owner shares of the user's own split txs — they paid+ # for the others, so those amounts aren't their actual cost.+ own_offset_inc, own_offset_exp = await owner_split_offset_pnl(+ session, user_id, month_start, month_end, use_effective_date=False+ )+ monthly_income -= own_offset_inc+ monthly_expenses -= own_offset_exp++ # Add the viewer's share from group splits where they're a linked+ # member but not the owner. Their concert ticket paid by a friend+ # is a real expense in their P/L picture.+ shared_income, shared_expenses = await viewer_shared_pnl(+ session, user_id, month_start, month_end, use_effective_date=False+ )+ monthly_income += shared_income+ monthly_expenses += shared_expenses+# Save real-only totals before adding projections (used for primary init)real_monthly_income = monthly_incomereal_monthly_expenses = monthly_expenses@@ -157,6 +181,10 @@ async def get_summary(Transaction.user_id == user_id,Transaction.category_id.is_(None),Transaction.source != "opening_balance",+ # Settlement-sourced rows are auto-generated movements (paying+ # back / receiving back a group debt). They aren't expenses or+ # income that need a category, so exclude them.+ Transaction.source != "settlement",Transaction.transfer_pair_id.is_(None),]pending_categorization = await session.scalar(@@ -206,7 +234,7 @@ async def get_summary(report_date >= month_start,report_date < month_end,Transaction.source != "opening_balance",- counts_as_pnl(),+ counts_as_user_pnl(),Transaction.amount_primary.isnot(None),))@@ -215,6 +243,71 @@ async def get_summary(monthly_income_primary = float(primary_row[0] or 0)monthly_expenses_primary = abs(float(primary_row[1] or 0))+ # Apply share-only offset in primary currency (FX-converted).+ own_offset_inc_pri, own_offset_exp_pri = await owner_split_offset_pnl(+ session,+ user_id,+ month_start,+ month_end,+ use_effective_date=False,+ primary_currency=primary_currency,+ )+ monthly_income_primary -= own_offset_inc_pri+ monthly_expenses_primary -= own_offset_exp_pri++ # Add the viewer's shared shares to primary totals too. The shares+ # are stored in the parent transaction's currency, so we convert+ # each currency bucket separately rather than re-using shared_income+ # / shared_expenses (which were summed without conversion).+ from app.models.group import GroupMember+ from app.models.transaction_split import TransactionSplit++ viewer_member_ids = select(GroupMember.id).where(+ GroupMember.linked_user_id == user_id+ )+ shared_currency_rows = await session.execute(+ select(+ Transaction.currency,+ func.sum(+ case(+ (Transaction.type == "credit", TransactionSplit.share_amount),+ else_=0,+ )+ ),+ func.sum(+ case(+ (Transaction.type == "debit", TransactionSplit.share_amount),+ else_=0,+ )+ ),+ )+ .select_from(TransactionSplit)+ .join(Transaction, TransactionSplit.transaction_id == Transaction.id)+ .where(+ TransactionSplit.group_member_id.in_(viewer_member_ids),+ Transaction.user_id != user_id,+ Transaction.source != "opening_balance",+ report_date >= month_start,+ report_date < month_end,+ counts_as_user_pnl(),+ )+ .group_by(Transaction.currency)+ )+ for row in shared_currency_rows.all():+ cur = row[0]+ in_credit = float(row[1] or 0)+ in_debit = float(row[2] or 0)+ if in_credit:+ credit_pri, _ = await convert(+ session, Decimal(str(in_credit)), cur, primary_currency+ )+ monthly_income_primary += float(credit_pri)+ if in_debit:+ debit_pri, _ = await convert(+ session, Decimal(str(in_debit)), cur, primary_currency+ )+ monthly_expenses_primary += abs(float(debit_pri))+# Add recurring projections to primary totals (convert each)for proj in projections:proj_converted, _ = await convert(@@ -232,6 +325,13 @@ async def get_summary(converted, _ = await convert(session, Decimal(str(amount)), currency, primary_currency)assets_value_primary += float(converted)+ # Aggregate the user's net pending balance across all groups they+ # participate in. We reuse the group balance computation so partial+ # settlements are already netted out.+ pending_shares_net = await _compute_pending_shares_net(+ session, user_id, primary_currency+ )+return DashboardSummary(total_balance=total_balance,total_balance_primary=round(total_balance_primary, 2),@@ -246,9 +346,66 @@ async def get_summary(assets_value=assets_value,assets_value_primary=round(assets_value_primary, 2),primary_currency=primary_currency,+ pending_shares_net=round(pending_shares_net, 2),)+async def _compute_pending_shares_net(+ session: AsyncSession, user_id: uuid.UUID, primary_currency: str+) -> float:+ """Sum, in primary currency, the user's net position across every+ group they belong to.++ For each group:+ - Owner: sum of (positive lines) - sum of (abs negative lines).+ Positive net = others owe them; negative = they owe.+ - Linked member: their own line. Positive line = they owe the+ owner; we flip the sign so the dashboard shows it as negative+ (net liability).+ """+ from app.models.group import Group, GroupMember+ from app.services.balance_service import compute_balances++ # All groups the user can see (owned + linked-as-member).+ owned_q = await session.execute(+ select(Group.id).where(Group.user_id == user_id)+ )+ owned_ids = {row[0] for row in owned_q.all()}+ linked_q = await session.execute(+ select(GroupMember.group_id, GroupMember.id).where(+ GroupMember.linked_user_id == user_id+ )+ )+ linked_rows = list(linked_q.all())+ linked_ids = {row.group_id for row in linked_rows}+ member_id_for_group = {row.group_id: row.id for row in linked_rows}++ total_primary = 0.0+ for gid in owned_ids | linked_ids:+ balances = await compute_balances(session, gid, user_id)+ if not balances:+ continue+ for line in balances["lines"]:+ line_amount = float(line["amount"])+ currency = line["currency"]+ if gid in owned_ids:+ # Positive = member owes the owner (an asset).+ # Negative = owner owes the member (a liability).+ signed = line_amount+ else:+ # Linked-member view: only the line about *us* matters+ # to our personal net. Flip the sign — `compute_balances`+ # frames it from the owner's perspective.+ if line["member_id"] != member_id_for_group[gid]:+ continue+ signed = -line_amount+ converted, _ = await convert(+ session, Decimal(str(signed)), currency, primary_currency+ )+ total_primary += float(converted)+ return total_primary++async def get_spending_by_category(session: AsyncSession, user_id: uuid.UUID, month: Optional[date] = None) -> list[SpendingByCategory]:@@ -259,6 +416,7 @@ async def get_spending_by_category(user = await session.get(User, user_id)accounting_mode = await get_credit_card_accounting_mode(session)+ primary_currency = user.primary_currency if user else get_settings().default_currencyreport_date = (Transaction.effective_date if accounting_mode == "accrual" else Transaction.date)@@ -282,7 +440,7 @@ async def get_spending_by_category(Transaction.type == "debit",report_date >= month_start,report_date < month_end,- counts_as_pnl(),+ counts_as_user_pnl(),).group_by(Category.id, Category.name, Category.icon, Category.color).order_by(func.sum(_primary_amount_expr()).desc())@@ -299,9 +457,65 @@ async def get_spending_by_category("total": abs(float(row[4] or 0)),}+ # Subtract non-owner shares per category — owner-side splits should+ # contribute only the owner's share, not the full amount.+ owner_offset = await owner_split_offset_by_category(+ session,+ user_id,+ month_start,+ month_end,+ use_effective_date=accounting_mode == "accrual",+ primary_currency=primary_currency,+ )+ for cat_uuid, offset_total in owner_offset.items():+ cat_id = str(cat_uuid) if cat_uuid else None+ if cat_id in spending_map:+ spending_map[cat_id]["total"] -= offset_total+ if spending_map[cat_id]["total"] <= 0:+ spending_map.pop(cat_id)++ # Add shared shares — the viewer's portion of group-split debits+ # they participate in but don't own. The category comes from the+ # parent transaction.+ shared_by_cat = await viewer_shared_spending_by_category(+ session, user_id, month_start, month_end,+ use_effective_date=accounting_mode == "accrual",+ primary_currency=primary_currency,+ )+ if shared_by_cat:+ cat_meta_cache: dict[str, dict] = {}+ for cat_uuid, share_total in shared_by_cat.items():+ cat_id = str(cat_uuid) if cat_uuid else None+ if cat_id and cat_id not in cat_meta_cache and cat_id not in spending_map:+ meta_row = (+ await session.execute(+ select(Category.name, Category.icon, Category.color).where(+ Category.id == cat_uuid+ )+ )+ ).one_or_none()+ if meta_row:+ cat_meta_cache[cat_id] = {+ "name": meta_row[0],+ "icon": meta_row[1],+ "color": meta_row[2],+ }+ if cat_id in spending_map:+ spending_map[cat_id]["total"] += share_total+ else:+ meta = cat_meta_cache.get(+ cat_id,+ {"name": "Sem categoria", "icon": "circle-help", "color": "#6B7280"},+ )+ spending_map[cat_id] = {+ "name": meta["name"],+ "icon": meta["icon"],+ "color": meta["color"],+ "total": share_total,+ }+# Add virtual recurring projections (debit only), converted to primary currencyprojections = await _get_recurring_projections(session, user_id, month_start, month_end)- primary_currency = user.primary_currency if user else get_settings().default_currency# We need category info for recurring projections — fetch categoriescat_cache: dict[str, dict] = {}for proj in projections:@@ -373,22 +587,50 @@ async def get_monthly_trend(Transaction.user_id == user_id,Account.is_closed == False,Transaction.source != "opening_balance",- counts_as_pnl(),+ counts_as_user_pnl(),).group_by(month_label).order_by(month_label.desc()).limit(months))- trends = []+ user = await session.get(User, user_id)+ primary_currency = user.primary_currency if user else get_settings().default_currency++ trends_raw: list[tuple[str, float, float]] = []for row in result.all():- trends.append(MonthlyTrend(- month=row[0],- income=float(row[1] or 0),- expenses=abs(float(row[2] or 0)),- ))+ trends_raw.append((row[0], float(row[1] or 0), abs(float(row[2] or 0))))++ # Subtract owner non-owner-share offsets per month, and add the+ # viewer's shares of others' splits.+ adjusted: list[MonthlyTrend] = []+ for month_str, income, expenses in trends_raw:+ year, mnum = month_str.split("-")+ m_start = date(int(year), int(mnum), 1)+ m_end = (+ date(int(year), int(mnum) + 1, 1)+ if int(mnum) < 12+ else date(int(year) + 1, 1, 1)+ )+ own_inc, own_exp = await owner_split_offset_pnl(+ session, user_id, m_start, m_end,+ use_effective_date=accounting_mode == "accrual",+ primary_currency=primary_currency,+ )+ shared_inc, shared_exp = await viewer_shared_pnl(+ session, user_id, m_start, m_end,+ use_effective_date=accounting_mode == "accrual",+ primary_currency=primary_currency,+ )+ adjusted.append(+ MonthlyTrend(+ month=month_str,+ income=max(0.0, income - own_inc + shared_inc),+ expenses=max(0.0, expenses - own_exp + shared_exp),+ )+ )- return list(reversed(trends))+ return list(reversed(adjusted))async def get_projected_transactions(diff --git a/backend/app/services/group_service.py b/backend/app/services/group_service.pynew file mode 100644index 00000000..ad16f1b9--- /dev/null+++ b/backend/app/services/group_service.py@@ -0,0 +1,361 @@+import uuid+from typing import Optional++from sqlalchemy import func, or_, select+from sqlalchemy.exc import IntegrityError+from sqlalchemy.ext.asyncio import AsyncSession+from sqlalchemy.orm import selectinload++from app.models.group import Group, GroupMember+from app.models.user import User+from app.schemas.group import (+ GroupCreate,+ GroupMemberCreate,+ GroupMemberUpdate,+ GroupUpdate,+)+++def _tag_owner(group: Group, user_id: uuid.UUID) -> Group:+ """Set a transient `is_owner` flag for the response layer.++ Pydantic's from_attributes picks this up — the schema treats+ `is_owner` as derived per-request, not stored on the model.+ """+ group.is_owner = group.user_id == user_id # type: ignore[attr-defined]+ return group+++async def _resolve_member_email(+ session: AsyncSession, email: Optional[str]+) -> Optional[uuid.UUID]:+ """If `email` matches an existing Securo user, return their id.+ Otherwise return None — the member is created as a shadow row."""+ if not email:+ return None+ result = await session.execute(+ select(User.id).where(func.lower(User.email) == email.strip().lower())+ )+ return result.scalar_one_or_none()+++def _visible_predicate(user_id: uuid.UUID):+ """Group is visible if the user is the owner OR linked as a member.+ Implemented as a subquery so the filter survives joins/options."""+ member_groups = (+ select(GroupMember.group_id)+ .where(GroupMember.linked_user_id == user_id)+ .distinct()+ )+ return or_(Group.user_id == user_id, Group.id.in_(member_groups))+++async def list_groups(+ session: AsyncSession, user_id: uuid.UUID, include_archived: bool = False+) -> list[Group]:+ query = (+ select(Group)+ .where(_visible_predicate(user_id))+ .options(selectinload(Group.members))+ .order_by(Group.created_at.desc())+ )+ if not include_archived:+ query = query.where(Group.is_archived.is_(False))+ result = await session.execute(query)+ return [_tag_owner(g, user_id) for g in result.scalars().all()]+++async def get_group(+ session: AsyncSession, group_id: uuid.UUID, user_id: uuid.UUID+) -> Optional[Group]:+ """Returns the group if the user is the owner. Used by edit paths+ that need to enforce ownership."""+ result = await session.execute(+ select(Group)+ .where(Group.id == group_id, Group.user_id == user_id)+ .options(selectinload(Group.members))+ )+ group = result.scalar_one_or_none()+ if group is not None:+ _tag_owner(group, user_id)+ return group+++async def get_group_visible(+ session: AsyncSession, group_id: uuid.UUID, user_id: uuid.UUID+) -> Optional[Group]:+ """Returns the group if the user is the owner OR a linked member.+ Use for read-only endpoints that should also serve members."""+ result = await session.execute(+ select(Group)+ .where(Group.id == group_id, _visible_predicate(user_id))+ .options(selectinload(Group.members))+ )+ group = result.scalar_one_or_none()+ if group is not None:+ _tag_owner(group, user_id)+ return group+++async def create_group(+ session: AsyncSession, user_id: uuid.UUID, data: GroupCreate+) -> Group:+ existing = await session.execute(+ select(Group).where(+ Group.user_id == user_id,+ func.lower(Group.name) == data.name.strip().lower(),+ )+ )+ if existing.scalar_one_or_none():+ raise ValueError("A group with this name already exists")++ group = Group(user_id=user_id, **data.model_dump())+ session.add(group)+ await session.flush()+ # Eager-load members so the response shape stays stable.+ await session.refresh(group, attribute_names=["members"])+ await session.commit()+ return _tag_owner(group, user_id)+++async def update_group(+ session: AsyncSession,+ group_id: uuid.UUID,+ user_id: uuid.UUID,+ data: GroupUpdate,+) -> Optional[Group]:+ group = await get_group(session, group_id, user_id)+ if not group:+ return None++ update_data = data.model_dump(exclude_unset=True)+ if "name" in update_data and update_data["name"]:+ clash = await session.execute(+ select(Group).where(+ Group.user_id == user_id,+ func.lower(Group.name) == update_data["name"].strip().lower(),+ Group.id != group_id,+ )+ )+ if clash.scalar_one_or_none():+ raise ValueError("A group with this name already exists")++ for key, value in update_data.items():+ setattr(group, key, value)++ await session.commit()+ await session.refresh(group, attribute_names=["members"])+ return _tag_owner(group, user_id)+++async def delete_group(+ session: AsyncSession, group_id: uuid.UUID, user_id: uuid.UUID+) -> bool:+ group = await get_group(session, group_id, user_id)+ if not group:+ return False+ try:+ await session.delete(group)+ await session.commit()+ except IntegrityError as e:+ # A member with active splits or settlements (RESTRICT FK)+ # blocks the cascade. Translate into a 409-friendly error.+ await session.rollback()+ raise ValueError(+ "Group has members referenced by transaction splits or settlements. "+ "Remove those first."+ ) from e+ return True+++async def list_members(+ session: AsyncSession, group_id: uuid.UUID, user_id: uuid.UUID+) -> Optional[list[GroupMember]]:+ # Skip the eager-loaded `Group.members` collection here — within a+ # long-lived session (notably tests) the identity map can hold a+ # stale snapshot after upstream mutations like `_clear_self_flag`.+ # A direct query always reflects the current row state.+ # Visible to owners AND linked members (read-only context).+ if not await get_group_visible(session, group_id, user_id):+ return None+ result = await session.execute(+ select(GroupMember)+ .where(GroupMember.group_id == group_id)+ .order_by(GroupMember.created_at)+ )+ return list(result.scalars().all())+++async def create_member(+ session: AsyncSession,+ group_id: uuid.UUID,+ user_id: uuid.UUID,+ data: GroupMemberCreate,+) -> Optional[GroupMember]:+ group = await get_group(session, group_id, user_id)+ if not group:+ return None++ clash = await session.execute(+ select(GroupMember).where(+ GroupMember.group_id == group_id,+ func.lower(GroupMember.name) == data.name.strip().lower(),+ )+ )+ if clash.scalar_one_or_none():+ raise ValueError("A member with this name already exists in this group")++ if data.is_self:+ # Only one self-member per group; demote any existing one.+ await _clear_self_flag(session, group_id)++ payload = data.model_dump()+ if payload.get("email") is not None:+ payload["email"] = str(payload["email"])+ # Auto-link to a real Securo user if the email matches one. The+ # caller can override by passing linked_user_id explicitly.+ if payload.get("linked_user_id") is None:+ payload["linked_user_id"] = await _resolve_member_email(session, payload.get("email"))+ member = GroupMember(group_id=group_id, **payload)+ session.add(member)+ await session.commit()+ await session.refresh(member)+ return member+++async def update_member(+ session: AsyncSession,+ group_id: uuid.UUID,+ member_id: uuid.UUID,+ user_id: uuid.UUID,+ data: GroupMemberUpdate,+) -> Optional[GroupMember]:+ group = await get_group(session, group_id, user_id)+ if not group:+ return None++ result = await session.execute(+ select(GroupMember).where(+ GroupMember.id == member_id, GroupMember.group_id == group_id+ )+ )+ member = result.scalar_one_or_none()+ if not member:+ return None++ update_data = data.model_dump(exclude_unset=True)+ if update_data.get("email") is not None:+ update_data["email"] = str(update_data["email"])+ if "name" in update_data and update_data["name"]:+ clash = await session.execute(+ select(GroupMember).where(+ GroupMember.group_id == group_id,+ func.lower(GroupMember.name) == update_data["name"].strip().lower(),+ GroupMember.id != member_id,+ )+ )+ if clash.scalar_one_or_none():+ raise ValueError("A member with this name already exists in this group")++ if update_data.get("is_self") is True:+ await _clear_self_flag(session, group_id, except_id=member_id)++ # Re-resolve the email link only when the caller is changing email+ # AND not explicitly overriding linked_user_id in the same request.+ if "email" in update_data and "linked_user_id" not in update_data:+ update_data["linked_user_id"] = await _resolve_member_email(+ session, update_data.get("email")+ )++ for key, value in update_data.items():+ setattr(member, key, value)++ await session.commit()+ await session.refresh(member)+ return member+++async def delete_member(+ session: AsyncSession,+ group_id: uuid.UUID,+ member_id: uuid.UUID,+ user_id: uuid.UUID,+) -> bool:+ group = await get_group(session, group_id, user_id)+ if not group:+ return False++ result = await session.execute(+ select(GroupMember).where(+ GroupMember.id == member_id, GroupMember.group_id == group_id+ )+ )+ member = result.scalar_one_or_none()+ if not member:+ return False++ try:+ await session.delete(member)+ await session.commit()+ except IntegrityError as e:+ await session.rollback()+ raise ValueError(+ "Member is referenced by transaction splits or settlements. "+ "Remove those first."+ ) from e+ return True+++async def list_transactions(+ session: AsyncSession,+ group_id: uuid.UUID,+ user_id: uuid.UUID,+ limit: int = 20,+) -> Optional[list]:+ """Return the most recent transactions whose splits reference any+ member of this group. Visible to owner + linked members."""+ from sqlalchemy.orm import selectinload as _sel++ from app.models.transaction import Transaction+ from app.models.transaction_split import TransactionSplit++ if not await get_group_visible(session, group_id, user_id):+ return None++ member_ids_subq = select(GroupMember.id).where(GroupMember.group_id == group_id)+ tx_ids_subq = (+ select(TransactionSplit.transaction_id)+ .where(TransactionSplit.group_member_id.in_(member_ids_subq))+ .distinct()+ )+ result = await session.execute(+ select(Transaction)+ .where(Transaction.id.in_(tx_ids_subq))+ .options(+ _sel(Transaction.category),+ _sel(Transaction.account),+ _sel(Transaction.payee_entity),+ _sel(Transaction.splits),+ )+ .order_by(Transaction.date.desc(), Transaction.created_at.desc())+ .limit(limit)+ )+ txs = list(result.scalars().all())+ # Hydrate fields the TransactionRead schema expects.+ for tx in txs:+ tx.attachment_count = 0+ tx.payee_name = tx.payee_entity.name if tx.payee_entity else None+ return txs+++async def _clear_self_flag(+ session: AsyncSession, group_id: uuid.UUID, except_id: Optional[uuid.UUID] = None+) -> None:+ query = select(GroupMember).where(+ GroupMember.group_id == group_id, GroupMember.is_self.is_(True)+ )+ if except_id is not None:+ query = query.where(GroupMember.id != except_id)+ result = await session.execute(query)+ for m in result.scalars().all():+ m.is_self = Falsediff --git a/backend/app/services/report_service.py b/backend/app/services/report_service.pyindex abf38903..d750957f 100644--- a/backend/app/services/report_service.py+++ b/backend/app/services/report_service.py@@ -13,7 +13,11 @@ from app.models.asset_value import AssetValuefrom app.models.transaction import Transactionfrom app.models.category import Categoryfrom app.models.user import User-from app.services._query_filters import counts_as_pnl+from app.services._query_filters import (+ counts_as_pnl,+ counts_as_user_pnl,+ owner_split_offset_by_category,+)from app.services.admin_service import get_credit_card_accounting_modefrom app.services.account_service import get_account_namefrom app.services.fx_rate_service import convert@@ -385,7 +389,7 @@ async def get_income_expenses_report(report_date >= start,report_date <= today,Transaction.source != "opening_balance",- counts_as_pnl(),+ counts_as_user_pnl(),).group_by(label_expr).order_by(label_expr)@@ -398,9 +402,134 @@ async def get_income_expenses_report(expenses = abs(float(row[2] or 0))data_map[row[0]] = (income, expenses)+ # Subtract non-owner shares of the user's own splits per period — the+ # user shouldn't be charged for the parts they're owed back.+ from sqlalchemy import or_ as _or_, and_ as _and_+ from app.models.group import Group as _Group_, GroupMember as _GroupMember_+ from app.models.transaction_split import TransactionSplit as _TS_+ from app.services.fx_rate_service import convert as fx_convert++ own_member_ids_sq = (+ select(_GroupMember_.id)+ .outerjoin(_Group_, _Group_.id == _GroupMember_.group_id)+ .where(+ _or_(+ _GroupMember_.linked_user_id == user_id,+ _and_(_GroupMember_.is_self == True, _Group_.user_id == user_id),+ )+ )+ )+ owner_offset_result = await session.execute(+ select(+ label_expr,+ Transaction.currency,+ func.sum(+ case(+ (Transaction.type == "credit", _TS_.share_amount),+ else_=0,+ )+ ),+ func.sum(+ case(+ (Transaction.type == "debit", _TS_.share_amount),+ else_=0,+ )+ ),+ )+ .select_from(_TS_)+ .join(Transaction, _TS_.transaction_id == Transaction.id)+ .where(+ Transaction.user_id == user_id,+ _TS_.group_member_id.notin_(own_member_ids_sq),+ report_date >= start,+ report_date <= today,+ Transaction.source != "opening_balance",+ counts_as_user_pnl(),+ )+ .group_by(label_expr, Transaction.currency)+ )+ for row in owner_offset_result.all():+ period, currency, raw_credit, raw_debit = row+ sub_inc = 0.0+ sub_exp = 0.0+ if raw_credit:+ inc_pri, _ = await fx_convert(+ session, Decimal(str(raw_credit)), currency, primary_currency+ )+ sub_inc = float(inc_pri)+ if raw_debit:+ exp_pri, _ = await fx_convert(+ session, Decimal(str(raw_debit)), currency, primary_currency+ )+ sub_exp = abs(float(exp_pri))+ existing_income, existing_expenses = data_map.get(period, (0.0, 0.0))+ data_map[period] = (+ max(0.0, existing_income - sub_inc),+ max(0.0, existing_expenses - sub_exp),+ )++ # Layer in the viewer's share from group splits — concert tickets+ # paid by a friend show up as the viewer's expense in their P/L+ # picture, just like in /transactions and the dashboard. Group by+ # currency so we can FX-convert each bucket to primary correctly.+ from app.models.group import GroupMember+ from app.models.transaction_split import TransactionSplit++ viewer_member_ids = select(GroupMember.id).where(+ GroupMember.linked_user_id == user_id+ )+ shared_result = await session.execute(+ select(+ label_expr,+ Transaction.currency,+ func.sum(+ case(+ (Transaction.type == "credit", TransactionSplit.share_amount),+ else_=0,+ )+ ),+ func.sum(+ case(+ (Transaction.type == "debit", TransactionSplit.share_amount),+ else_=0,+ )+ ),+ )+ .select_from(TransactionSplit)+ .join(Transaction, TransactionSplit.transaction_id == Transaction.id)+ .where(+ TransactionSplit.group_member_id.in_(viewer_member_ids),+ Transaction.user_id != user_id,+ report_date >= start,+ report_date <= today,+ Transaction.source != "opening_balance",+ counts_as_user_pnl(),+ )+ .group_by(label_expr, Transaction.currency)+ )+ from app.services.fx_rate_service import convert as fx_convert+ for row in shared_result.all():+ period, currency, raw_credit, raw_debit = row+ share_income_pri = 0.0+ share_expenses_pri = 0.0+ if raw_credit:+ inc_pri, _ = await fx_convert(+ session, Decimal(str(raw_credit)), currency, primary_currency+ )+ share_income_pri = float(inc_pri)+ if raw_debit:+ exp_pri, _ = await fx_convert(+ session, Decimal(str(raw_debit)), currency, primary_currency+ )+ share_expenses_pri = abs(float(exp_pri))+ existing_income, existing_expenses = data_map.get(period, (0.0, 0.0))+ data_map[period] = (+ existing_income + share_income_pri,+ existing_expenses + share_expenses_pri,+ )+# Add recurring projections for each month in the range (consistent with dashboard)from app.services.dashboard_service import _month_range, _get_recurring_projections- from app.services.fx_rate_service import convert as fx_convertcursor = startwhile cursor <= today:@@ -508,7 +637,7 @@ async def get_income_expenses_report(report_date >= start,report_date <= today,Transaction.source != "opening_balance",- counts_as_pnl(),+ counts_as_user_pnl(),).group_by(Category.id, Category.name, Category.color, Transaction.type))@@ -529,6 +658,22 @@ async def get_income_expenses_report("value": amount,}+ # Subtract non-owner shares of own splits from composition (debit only —+ # owner_split_offset_by_category is debit-only). Keeps the report's+ # composition consistent with summary totals under share-only model.+ full_range_offset = await owner_split_offset_by_category(+ session, user_id, start, today + timedelta(days=1),+ use_effective_date=accounting_mode == "accrual",+ primary_currency=primary_currency,+ )+ for cat_uuid, offset_total in full_range_offset.items():+ cat_key = str(cat_uuid) if cat_uuid else "uncategorized"+ comp_key = (cat_key, "expenses")+ if comp_key in comp_map:+ comp_map[comp_key]["value"] -= offset_total+ if comp_map[comp_key]["value"] <= 0:+ comp_map.pop(comp_key)+# Build per-category trend (sparklines) for the full date rangecat_trend_result = await session.execute(select(@@ -548,7 +693,7 @@ async def get_income_expenses_report(report_date >= start,report_date <= today,Transaction.source != "opening_balance",- counts_as_pnl(),+ counts_as_user_pnl(),).group_by(label_expr, Category.id, Category.name, Category.color, Transaction.type))@@ -575,6 +720,49 @@ async def get_income_expenses_report(cat_trend_map[map_key]["periods"].get(period_label, 0.0) + amount)+ # Subtract non-owner shares of own splits per (period, category) — keeps+ # the per-category trend consistent with the share-only summary.+ cat_offset_result = await session.execute(+ select(+ label_expr,+ Transaction.category_id,+ Transaction.currency,+ func.sum(_TS_.share_amount),+ )+ .select_from(_TS_)+ .join(Transaction, _TS_.transaction_id == Transaction.id)+ .where(+ Transaction.user_id == user_id,+ Transaction.type == "debit",+ _TS_.group_member_id.notin_(own_member_ids_sq),+ report_date >= start,+ report_date <= today,+ Transaction.source != "opening_balance",+ counts_as_user_pnl(),+ )+ .group_by(label_expr, Transaction.category_id, Transaction.currency)+ )+ for period_label, cat_id, currency, raw_total in cat_offset_result.all():+ if not raw_total:+ continue+ cat_key = str(cat_id) if cat_id else "uncategorized"+ offset_pri, _ = await fx_convert(+ session, Decimal(str(raw_total)), currency, primary_currency+ )+ offset = float(offset_pri)+ map_key = (cat_key, "expenses")+ if map_key not in cat_trend_map:+ continue+ cat_trend_map[map_key]["total"] = max(+ 0.0, cat_trend_map[map_key]["total"] - offset+ )+ cur_period = cat_trend_map[map_key]["periods"].get(period_label, 0.0)+ cat_trend_map[map_key]["periods"][period_label] = max(0.0, cur_period - offset)+ # Drop categories that fully zeroed out+ for key in list(cat_trend_map.keys()):+ if cat_trend_map[key]["total"] <= 0:+ cat_trend_map.pop(key)+# Add recurring projections to composition and category trendcat_cache: dict[str, dict] = {}cursor2 = startdiff --git a/backend/app/services/search_service.py b/backend/app/services/search_service.pyindex 6999f1cf..86d6df92 100644--- a/backend/app/services/search_service.py+++ b/backend/app/services/search_service.py@@ -89,10 +89,27 @@ async def search_all(hits: list[SearchHit] = []# -- Transactions -------------------------------------------------------+ # Search returns the user's own transactions PLUS transactions+ # they participate in via group splits — so "concert" finds the+ # parent that someone else paid for but is on the user's ledger.+ from app.models.group import GroupMember+ from app.models.transaction_split import TransactionSplit++ viewer_member_ids = select(GroupMember.id).where(+ GroupMember.linked_user_id == user_id+ )+ shared_tx_ids = (+ select(TransactionSplit.transaction_id)+ .where(TransactionSplit.group_member_id.in_(viewer_member_ids))+ .distinct()+ )tx_result = await session.execute(select(Transaction).where(- Transaction.user_id == user_id,+ or_(+ Transaction.user_id == user_id,+ Transaction.id.in_(shared_tx_ids),+ ),or_(Transaction.description.ilike(pattern, escape="\\"),Transaction.payee.ilike(pattern, escape="\\"),diff --git a/backend/app/services/settlement_service.py b/backend/app/services/settlement_service.pynew file mode 100644index 00000000..96e8ed81--- /dev/null+++ b/backend/app/services/settlement_service.py@@ -0,0 +1,391 @@+import uuid+from datetime import datetime, timezone+from typing import Optional++from sqlalchemy import or_, select+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.account import Account+from app.models.bank_connection import BankConnection+from app.models.group import Group, GroupMember+from app.models.group_settlement import GroupSettlement+from app.models.transaction import Transaction+from app.schemas.group_settlement import (+ GroupSettlementCreate,+ GroupSettlementUpdate,+)+++async def _ensure_group_owned(+ session: AsyncSession, group_id: uuid.UUID, user_id: uuid.UUID+) -> Optional[Group]:+ """Owner-only access — used when only the owner may proceed."""+ result = await session.execute(+ select(Group).where(Group.id == group_id, Group.user_id == user_id)+ )+ return result.scalar_one_or_none()+++async def _ensure_group_visible(+ session: AsyncSession, group_id: uuid.UUID, user_id: uuid.UUID+) -> Optional[Group]:+ """Visible to the owner OR any linked member — for read endpoints."""+ from app.services.group_service import get_group_visible++ return await get_group_visible(session, group_id, user_id)+++async def _user_member_id(+ session: AsyncSession, group_id: uuid.UUID, user_id: uuid.UUID+) -> Optional[uuid.UUID]:+ """If the user is a linked member of this group, return that member+ id. Owners may not have a linked member (they can still act via+ the owner check), so this can return None for them."""+ result = await session.execute(+ select(GroupMember.id).where(+ GroupMember.group_id == group_id,+ GroupMember.linked_user_id == user_id,+ )+ )+ return result.scalar_one_or_none()+++async def _can_settle_from(+ session: AsyncSession,+ group: Group,+ user_id: uuid.UUID,+ from_member_id: uuid.UUID,+) -> bool:+ """Permission check for creating/editing a settlement:+ - Group owner can do anything.+ - Linked member can only act when they are the `from_member`+ (i.e., they're recording a payment they themselves made)."""+ if group.user_id == user_id:+ return True+ linked = await _user_member_id(session, group.id, user_id)+ return linked is not None and linked == from_member_id+++async def _create_payment_transaction(+ session: AsyncSession,+ user_id: uuid.UUID,+ account_id: uuid.UUID,+ amount,+ currency: str,+ when,+ description: str,+) -> Transaction:+ """Create a debit transaction on the user's account representing a+ settlement payment. Validates account ownership."""+ account_result = await session.execute(+ select(Account)+ .outerjoin(BankConnection)+ .where(+ Account.id == account_id,+ or_(Account.user_id == user_id, BankConnection.user_id == user_id),+ )+ )+ account = account_result.scalar_one_or_none()+ if account is None:+ raise ValueError("Account not found")++ tx = Transaction(+ id=uuid.uuid4(),+ user_id=user_id,+ account_id=account.id,+ description=description,+ amount=amount,+ currency=currency,+ date=when,+ type="debit",+ # `settlement` is a special source that excludes the row from+ # spending reports — the underlying expense is already counted+ # via the share that produced the debt; this is the payback,+ # not a new expense.+ source="settlement",+ created_at=datetime.now(timezone.utc),+ )+ session.add(tx)+ await session.flush()+ # Stamp primary-currency amount so dashboard / report aggregations+ # that prefer amount_primary include this row.+ from app.services.fx_rate_service import stamp_primary_amount++ await stamp_primary_amount(session, user_id, tx)+ return tx+++async def _pick_default_account_for_user(+ session: AsyncSession, user_id: uuid.UUID+) -> Optional[Account]:+ """Return the user's first non-archived checking/savings account.+ Used as the auto-target for receiver-side settlement credits."""+ result = await session.execute(+ select(Account)+ .outerjoin(BankConnection)+ .where(+ or_(Account.user_id == user_id, BankConnection.user_id == user_id),+ Account.is_closed.is_(False),+ Account.type.in_(("checking", "savings")),+ )+ .order_by(Account.name)+ )+ return result.scalars().first()+++async def _create_receiver_credit(+ session: AsyncSession,+ receiver_user_id: uuid.UUID,+ amount,+ currency: str,+ when,+ description: str,+) -> Optional[Transaction]:+ """Mirror a settlement credit on the receiver's side.++ Picks the receiver's first checking/savings account. Returns None+ silently when the receiver has no suitable account — they can do+ it manually or the next time they reconcile from their bank sync.+ """+ account = await _pick_default_account_for_user(session, receiver_user_id)+ if account is None:+ return None+ tx = Transaction(+ id=uuid.uuid4(),+ user_id=receiver_user_id,+ account_id=account.id,+ description=description,+ amount=amount,+ currency=currency,+ date=when,+ type="credit",+ # Settlement credits ARE counted in P/L (income), unlike the+ # payer's debit which is excluded. See counts_as_pnl().+ source="settlement",+ created_at=datetime.now(timezone.utc),+ )+ session.add(tx)+ await session.flush()+ from app.services.fx_rate_service import stamp_primary_amount++ await stamp_primary_amount(session, receiver_user_id, tx)+ return tx+++async def _validate_members_in_group(+ session: AsyncSession, group_id: uuid.UUID, member_ids: list[uuid.UUID]+) -> None:+ result = await session.execute(+ select(GroupMember.id).where(+ GroupMember.group_id == group_id, GroupMember.id.in_(member_ids)+ )+ )+ found = {row[0] for row in result.all()}+ if found != set(member_ids):+ raise ValueError("Settlement members must belong to the group")+++async def _validate_transaction(+ session: AsyncSession,+ transaction_id: Optional[uuid.UUID],+ user_id: uuid.UUID,+) -> None:+ if transaction_id is None:+ return+ result = await session.execute(+ select(Transaction)+ .outerjoin(Account)+ .outerjoin(BankConnection)+ .where(+ Transaction.id == transaction_id,+ or_(+ Transaction.user_id == user_id,+ BankConnection.user_id == user_id,+ ),+ )+ )+ if result.scalar_one_or_none() is None:+ raise ValueError("Linked transaction not found")+++async def list_settlements(+ session: AsyncSession, group_id: uuid.UUID, user_id: uuid.UUID+) -> Optional[list[GroupSettlement]]:+ if not await _ensure_group_visible(session, group_id, user_id):+ return None+ result = await session.execute(+ select(GroupSettlement)+ .where(GroupSettlement.group_id == group_id)+ .order_by(GroupSettlement.date.desc(), GroupSettlement.created_at.desc())+ )+ return list(result.scalars().all())+++async def create_settlement(+ session: AsyncSession,+ group_id: uuid.UUID,+ user_id: uuid.UUID,+ data: GroupSettlementCreate,+) -> Optional[GroupSettlement]:+ group = await _ensure_group_visible(session, group_id, user_id)+ if not group:+ return None++ if not await _can_settle_from(session, group, user_id, data.from_member_id):+ # Linked members may only record payments they themselves made.+ raise PermissionError(+ "You can only record settlements where you are the payer"+ )++ await _validate_members_in_group(+ session, group_id, [data.from_member_id, data.to_member_id]+ )+ await _validate_transaction(session, data.transaction_id, user_id)++ payload = data.model_dump()+ account_id = payload.pop("account_id", None)+ description = payload.pop("description", None)++ # Resolve member metadata once — we need names for descriptions+ # and the to_member's linked_user_id for the receiver-side credit.+ members_q = await session.execute(+ select(+ GroupMember.id,+ GroupMember.name,+ GroupMember.linked_user_id,+ GroupMember.is_self,+ ).where(GroupMember.id.in_([data.from_member_id, data.to_member_id]))+ )+ member_meta = {row.id: row for row in members_q.all()}+ from_name = member_meta[data.from_member_id].name if data.from_member_id in member_meta else "—"+ to_meta = member_meta.get(data.to_member_id)+ to_name = to_meta.name if to_meta else "—"+ # Resolve the receiver's Securo user id. linked_user_id wins; fall+ # back to group.user_id when the receiver is the owner's+ # self-member (owners often don't bother linking themselves).+ receiver_user_id = None+ if to_meta is not None:+ receiver_user_id = to_meta.linked_user_id+ if receiver_user_id is None and to_meta.is_self:+ receiver_user_id = group.user_id++ # Optional integration with the real account ledger: create a debit+ # transaction on the payer's account and link it via transaction_id.+ if account_id is not None:+ if payload.get("transaction_id") is not None:+ raise ValueError(+ "Pass either account_id (to create a transaction) or "+ "transaction_id (to link an existing one), not both"+ )+ auto_desc = description or f"Acerto · {group.name} · {to_name}"+ tx = await _create_payment_transaction(+ session,+ user_id,+ account_id,+ data.amount,+ data.currency,+ data.date,+ auto_desc,+ )+ payload["transaction_id"] = tx.id++ # Receiver-side mirror credit: when the receiver maps to a Securo+ # user and has a checking/savings account, record the cash-in side+ # so their books reflect the actual money received.+ receiver_tx_id = None+ if receiver_user_id is not None:+ receiver_desc = description or f"Acerto · {group.name} · {from_name}"+ receiver_tx = await _create_receiver_credit(+ session,+ receiver_user_id,+ data.amount,+ data.currency,+ data.date,+ receiver_desc,+ )+ if receiver_tx is not None:+ receiver_tx_id = receiver_tx.id+ payload["receiver_transaction_id"] = receiver_tx_id++ settlement = GroupSettlement(group_id=group_id, **payload)+ session.add(settlement)+ await session.commit()+ await session.refresh(settlement)+ return settlement+++async def update_settlement(+ session: AsyncSession,+ group_id: uuid.UUID,+ settlement_id: uuid.UUID,+ user_id: uuid.UUID,+ data: GroupSettlementUpdate,+) -> Optional[GroupSettlement]:+ group = await _ensure_group_visible(session, group_id, user_id)+ if not group:+ return None++ result = await session.execute(+ select(GroupSettlement).where(+ GroupSettlement.id == settlement_id,+ GroupSettlement.group_id == group_id,+ )+ )+ settlement = result.scalar_one_or_none()+ if not settlement:+ return None++ # Caller must currently own the settlement (linked member of the+ # original from_member, or the group owner).+ if not await _can_settle_from(session, group, user_id, settlement.from_member_id):+ raise PermissionError("You can only edit settlements you created")++ update_data = data.model_dump(exclude_unset=True)++ new_from = update_data.get("from_member_id", settlement.from_member_id)+ new_to = update_data.get("to_member_id", settlement.to_member_id)+ if new_from == new_to:+ raise ValueError("from_member_id and to_member_id must differ")++ member_check: list[uuid.UUID] = []+ if "from_member_id" in update_data:+ member_check.append(update_data["from_member_id"])+ if "to_member_id" in update_data:+ member_check.append(update_data["to_member_id"])+ if member_check:+ await _validate_members_in_group(session, group_id, member_check)++ if "transaction_id" in update_data:+ await _validate_transaction(session, update_data["transaction_id"], user_id)++ for key, value in update_data.items():+ setattr(settlement, key, value)++ await session.commit()+ await session.refresh(settlement)+ return settlement+++async def delete_settlement(+ session: AsyncSession,+ group_id: uuid.UUID,+ settlement_id: uuid.UUID,+ user_id: uuid.UUID,+) -> bool:+ group = await _ensure_group_visible(session, group_id, user_id)+ if not group:+ return False+ result = await session.execute(+ select(GroupSettlement).where(+ GroupSettlement.id == settlement_id,+ GroupSettlement.group_id == group_id,+ )+ )+ settlement = result.scalar_one_or_none()+ if not settlement:+ return False+ if not await _can_settle_from(session, group, user_id, settlement.from_member_id):+ raise PermissionError("You can only delete settlements you created")+ await session.delete(settlement)+ await session.commit()+ return Truediff --git a/backend/app/services/split_service.py b/backend/app/services/split_service.pynew file mode 100644index 00000000..3395969b--- /dev/null+++ b/backend/app/services/split_service.py@@ -0,0 +1,147 @@+"""Materializing transaction splits.++Splits are always written as integer-cent amounts (Numeric(15,2)) in the+transaction's currency. Equal/percent inputs are materialized at write+time and the rounding residual is assigned to the last share so the sum+matches the parent amount exactly.+"""++import uuid+from decimal import ROUND_HALF_UP, Decimal+from typing import Optional++from sqlalchemy import delete, select+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.group import Group, GroupMember+from app.models.transaction import Transaction+from app.models.transaction_split import TransactionSplit+from app.schemas.transaction_split import (+ TransactionSplitsInput,+)++_CENT = Decimal("0.01")+++def _quantize(amount: Decimal) -> Decimal:+ return amount.quantize(_CENT, rounding=ROUND_HALF_UP)+++def _materialize(+ total: Decimal, payload: TransactionSplitsInput+) -> list[tuple[uuid.UUID, Decimal, Optional[Decimal]]]:+ """Resolve splits into [(member_id, share_amount, share_pct?)] tuples.++ `total` is treated as a positive value — the sign of a transaction+ (debit/credit) is independent of how it's distributed.+ """+ total = _quantize(Decimal(str(total)).copy_abs())+ n = len(payload.splits)+ if n == 0:+ raise ValueError("At least one split is required")++ if payload.share_type == "equal":+ per = _quantize(total / n)+ # Last share absorbs the rounding residual so the sum is exact.+ residual = total - (per * (n - 1))+ return [+ (s.group_member_id, residual if i == n - 1 else per, None)+ for i, s in enumerate(payload.splits)+ ]++ if payload.share_type == "exact":+ out: list[tuple[uuid.UUID, Decimal, Optional[Decimal]]] = []+ for s in payload.splits:+ if s.share_amount is None:+ raise ValueError("share_amount is required for share_type='exact'")+ out.append((s.group_member_id, _quantize(s.share_amount), None))+ if sum((a for _, a, _ in out), Decimal("0")) != total:+ raise ValueError("Split amounts must sum to the transaction amount")+ return out++ if payload.share_type == "percent":+ for s in payload.splits:+ if s.share_pct is None:+ raise ValueError("share_pct is required for share_type='percent'")+ pct_sum = sum((s.share_pct for s in payload.splits), Decimal("0"))+ if pct_sum != Decimal("100"):+ raise ValueError("Split percentages must sum to 100")++ amounts: list[Decimal] = []+ for i, s in enumerate(payload.splits):+ if i == n - 1:+ # Last share: residual so the sum is exact.+ amounts.append(total - sum(amounts, Decimal("0")))+ else:+ amounts.append(_quantize(total * s.share_pct / Decimal("100")))+ return [+ (s.group_member_id, amounts[i], s.share_pct)+ for i, s in enumerate(payload.splits)+ ]++ raise ValueError(f"Unknown share_type: {payload.share_type}")+++async def _validate_members(+ session: AsyncSession,+ member_ids: list[uuid.UUID],+ user_id: uuid.UUID,+) -> uuid.UUID:+ """Ensure all members belong to a single group owned by `user_id`.+ Returns that group's id."""+ result = await session.execute(+ select(GroupMember, Group)+ .join(Group, GroupMember.group_id == Group.id)+ .where(GroupMember.id.in_(member_ids), Group.user_id == user_id)+ )+ rows = result.all()+ if len(rows) != len(set(member_ids)):+ raise ValueError("One or more split members not found")+ group_ids = {g.id for _, g in rows}+ if len(group_ids) != 1:+ raise ValueError("All splits must reference members of the same group")+ return group_ids.pop()+++async def replace_splits(+ session: AsyncSession,+ transaction: Transaction,+ payload: Optional[TransactionSplitsInput],+ user_id: uuid.UUID,+) -> None:+ """Replace any existing splits on `transaction` with the given payload.++ Pass `payload=None` to leave splits untouched. Pass an empty+ `TransactionSplitsInput(splits=[])`-equivalent (handled upstream) to+ clear them.+ """+ if payload is None:+ return++ # Always start by clearing existing splits — replace semantics keep+ # the create/update paths trivially consistent.+ await session.execute(+ delete(TransactionSplit).where(+ TransactionSplit.transaction_id == transaction.id+ )+ )++ if not payload.splits:+ return++ member_ids = [s.group_member_id for s in payload.splits]+ if len(set(member_ids)) != len(member_ids):+ raise ValueError("Each member can appear at most once per transaction")++ await _validate_members(session, member_ids, user_id)++ for member_id, share_amount, share_pct in _materialize(transaction.amount, payload):+ session.add(+ TransactionSplit(+ transaction_id=transaction.id,+ group_member_id=member_id,+ share_amount=share_amount,+ share_type=payload.share_type,+ share_pct=share_pct,+ )+ )diff --git a/backend/app/services/transaction_service.py b/backend/app/services/transaction_service.pyindex 830a739d..230c0965 100644--- a/backend/app/services/transaction_service.py+++ b/backend/app/services/transaction_service.py@@ -13,6 +13,7 @@ from app.models.account import Accountfrom app.models.bank_connection import BankConnectionfrom app.models.payee import Payeefrom app.schemas.transaction import TransactionCreate, TransactionUpdate, TransferCreate+from app.services import split_servicefrom app.services.credit_card_service import apply_effective_datefrom app.services.rule_service import apply_rules_to_transactionfrom app.services.fx_rate_service import stamp_primary_amount, convert as fx_convert@@ -65,6 +66,7 @@ async def get_transactions(accounting_mode: Optional[str] = None,tags: Optional[list[str]] = None,bill_id: Optional[uuid.UUID] = None,+ group_id: Optional[uuid.UUID] = None,unbilled_only: bool = False,) -> tuple[list[Transaction], int]:# In "accrual" mode, bucket/order by effective_date so list filters@@ -76,6 +78,20 @@ async def get_transactions(Transaction.effective_bill_date,Transaction.effective_date if accounting_mode == "accrual" else Transaction.date,)++ # Group-scope visibility: when the caller filters by a group they+ # have access to (owner or linked member), bypass the user-owns-it+ # check and return that group's transactions instead. Lets a linked+ # member view the owner's transactions for shared groups.+ use_group_scope = False+ if group_id is not None:+ from app.services.group_service import get_group_visible++ accessible = await get_group_visible(session, group_id, user_id)+ if accessible is None:+ return [], 0+ use_group_scope = True+# CC bill-view date column: when the caller asks "what's in this bill?"# (bill_id passed, or in-progress cycle via unbilled_only), the answer# is bank-truth — the charges that fell in the cycle by purchase date —@@ -90,20 +106,56 @@ async def get_transactions()in_bill_view = bill_id is not None or unbilled_onlyfilter_date_col = bill_view_date_col if in_bill_view else date_col- # Base query: user's own transactions (manual or via account)+ # Base query: user's own transactions (manual or via account), or+ # group-scoped when `group_id` resolves to a visible group.base_query = (select(Transaction).outerjoin(Account).outerjoin(BankConnection).outerjoin(Payee, Transaction.payee_id == Payee.id)- .where(+ .options(+ selectinload(Transaction.category),+ selectinload(Transaction.account),+ selectinload(Transaction.payee_entity),+ selectinload(Transaction.splits),+ )+ )+ if use_group_scope:+ from app.models.group import GroupMember+ from app.models.transaction_split import TransactionSplit++ member_ids_subq = select(GroupMember.id).where(GroupMember.group_id == group_id)+ tx_ids_subq = (+ select(TransactionSplit.transaction_id)+ .where(TransactionSplit.group_member_id.in_(member_ids_subq))+ .distinct()+ )+ base_query = base_query.where(Transaction.id.in_(tx_ids_subq))+ else:+ # Default scope: own transactions PLUS transactions shared+ # with the user via group splits. Shared rows surface in the+ # viewer's ledger so their `Concert Tickets · share $90` shows+ # up alongside their own expenses; account-balance integrity+ # is preserved because the transaction's account_id still+ # belongs to the original owner.+ from app.models.group import GroupMember+ from app.models.transaction_split import TransactionSplit++ viewer_member_ids = select(GroupMember.id).where(+ GroupMember.linked_user_id == user_id+ )+ shared_tx_ids = (+ select(TransactionSplit.transaction_id)+ .where(TransactionSplit.group_member_id.in_(viewer_member_ids))+ .distinct()+ )+ base_query = base_query.where(or_(Transaction.user_id == user_id,BankConnection.user_id == user_id,+ Transaction.id.in_(shared_tx_ids),))- .options(selectinload(Transaction.category), selectinload(Transaction.account), selectinload(Transaction.payee_entity))- )# Exclude opening_balance transactions from the normal list unless explicitly requestedif not include_opening_balance:@@ -248,9 +300,141 @@ async def get_transactions(tx.attachment_count = counts.get(tx.id, 0)tx.payee_name = tx.payee_entity.name if tx.payee_entity else None+ # Tag shared rows with the viewer's share + the source group.+ # Owned rows stay as-is. We pre-compute the viewer's linked+ # member ids → group ids once, then look up each transaction's+ # split that targets one of those member ids.+ # Run for both default and group-scoped queries: when filtering+ # by `group_id`, a linked member sees the owner's transactions+ # and the frontend needs `is_shared` to lock them from edits.+ await _tag_shared_view(session, transactions, user_id)+return transactions, total or 0+async def _tag_shared_view(+ session: AsyncSession,+ transactions: list[Transaction],+ user_id: uuid.UUID,+) -> None:+ """Annotate transactions with split metadata for the viewer:++ - `is_shared`: true when the viewer doesn't own the parent but is a+ linked split member.+ - `viewer_share`: the viewer's share amount (only when shared).+ - `group_id`: the group the splits belong to. Set for both owner+ and linked-member views so the UI can show a group badge on+ either side.+ - `parent_owner_name`: friendly name of the parent owner; only+ meaningful for shared rows.++ Mutates the in-memory objects so Pydantic's from_attributes picks+ them up directly.+ """+ from app.models.group import GroupMember++ member_rows = await session.execute(+ select(GroupMember.id, GroupMember.group_id).where(+ GroupMember.linked_user_id == user_id+ )+ )+ member_to_group = {row.id: row.group_id for row in member_rows}++ # Map every split-member that appears in this batch → group, so we+ # can also tag owner-side transactions with their group. (The+ # viewer-linked map above only covers the viewer's own member ids.)+ all_split_member_ids: set[uuid.UUID] = set()+ for tx in transactions:+ for s in tx.splits or []:+ all_split_member_ids.add(s.group_member_id)+ split_member_to_group: dict[uuid.UUID, uuid.UUID] = {}+ if all_split_member_ids:+ rows = await session.execute(+ select(GroupMember.id, GroupMember.group_id).where(+ GroupMember.id.in_(all_split_member_ids)+ )+ )+ split_member_to_group = {row.id: row.group_id for row in rows}++ if not member_to_group and not split_member_to_group:+ for tx in transactions:+ tx.is_shared = False+ tx.viewer_share = None+ tx.group_id = None+ tx.parent_owner_name = None+ return++ # Per-group lookups: the `is_self` member represents the parent+ # owner / payer. We need this for ALL groups touching this batch,+ # not just the viewer-linked ones — owners need their own+ # self-member id to compute their share. Cached once per call.+ all_group_ids = set(member_to_group.values()) | set(split_member_to_group.values())+ self_member_rows = await session.execute(+ select(GroupMember.id, GroupMember.group_id, GroupMember.name).where(+ GroupMember.group_id.in_(all_group_ids),+ GroupMember.is_self.is_(True),+ )+ )+ self_member_id_by_group: dict[uuid.UUID, uuid.UUID] = {}+ owner_name_by_group: dict[uuid.UUID, str] = {}+ for row in self_member_rows:+ self_member_id_by_group[row.group_id] = row.id+ owner_name_by_group[row.group_id] = row.name++ for tx in transactions:+ if tx.user_id == user_id:+ # Owner of the parent — not "shared" but still tag the+ # group_id so the UI can show a group badge for owners.+ # Also populate viewer_share with the owner's *own* split+ # share when they participate (is_self member appears in the+ # splits): the UI surfaces "your share: $X" alongside the+ # full amount that hit the account.+ tx.is_shared = False+ tx.parent_owner_name = None+ owner_group_id: Optional[uuid.UUID] = None+ for s in tx.splits or []:+ gid = split_member_to_group.get(s.group_member_id)+ if gid is not None:+ owner_group_id = gid+ break+ tx.group_id = owner_group_id+ self_mid = (+ self_member_id_by_group.get(owner_group_id)+ if owner_group_id is not None+ else None+ )+ owner_split = (+ next(+ (s for s in tx.splits or [] if s.group_member_id == self_mid),+ None,+ )+ if self_mid is not None+ else None+ )+ tx.viewer_share = owner_split.share_amount if owner_split else None+ continue+ # The viewer doesn't own this; find their split share.+ match = next(+ (s for s in (tx.splits or []) if s.group_member_id in member_to_group),+ None,+ )+ if match is None:+ tx.is_shared = False+ tx.viewer_share = None+ tx.group_id = None+ tx.parent_owner_name = None+ else:+ tx.is_shared = True+ tx.viewer_share = match.share_amount+ tx.group_id = member_to_group[match.group_member_id]+ tx.parent_owner_name = owner_name_by_group.get(tx.group_id)+ # Hide attachment count on shared rows — Bob can see the+ # paperclip but the API would 403 the actual download+ # (attachment auth is owner-only). Avoid the dead-end UX+ # by not advertising files he can't open.+ tx.attachment_count = 0++async def get_transaction(session: AsyncSession, transaction_id: uuid.UUID, user_id: uuid.UUID) -> Optional[Transaction]:@@ -265,7 +449,11 @@ async def get_transaction(BankConnection.user_id == user_id,),)- .options(selectinload(Transaction.category), selectinload(Transaction.payee_entity))+ .options(+ selectinload(Transaction.category),+ selectinload(Transaction.payee_entity),+ selectinload(Transaction.splits),+ ))transaction = result.scalar_one_or_none()if transaction:@@ -328,8 +516,11 @@ async def create_transaction(else:await stamp_primary_amount(session, user_id, transaction)+ if data.splits is not None:+ await split_service.replace_splits(session, transaction, data.splits, user_id)+await session.commit()- await session.refresh(transaction, ["category"])+ await session.refresh(transaction, ["category", "splits"])return transaction@@ -477,6 +668,7 @@ async def get_transfer_candidates(selectinload(Transaction.category),selectinload(Transaction.account),selectinload(Transaction.payee_entity),+ selectinload(Transaction.splits),))candidates = list(result.scalars().all())@@ -631,6 +823,11 @@ async def update_transaction(update_data = data.model_dump(exclude_unset=True)apply_to_transfer_pair = update_data.pop("apply_to_transfer_pair", False)+ # Splits are processed separately after column updates land so the+ # service can validate against the new amount.+ splits_payload = data.splits if "splits" in update_data else None+ update_data.pop("splits", None)+# Verify the new account belongs to the user before touching the row.# When changing the account on one side of a transfer pair, refuse to# collide with the paired transaction's account (a transfer must have two@@ -723,8 +920,11 @@ async def update_transaction(paired_account = await session.get(Account, paired_tx.account_id)apply_effective_date(paired_tx, paired_account)+ if splits_payload is not None:+ await split_service.replace_splits(session, transaction, splits_payload, user_id)+await session.commit()- await session.refresh(transaction)+ await session.refresh(transaction, ["splits"])return transactiondiff --git a/backend/tests/conftest.py b/backend/tests/conftest.pyindex 134e0a26..55e10566 100644--- a/backend/tests/conftest.py+++ b/backend/tests/conftest.py@@ -25,6 +25,9 @@ from app.models.payee import Payee, PayeeMapping # noqa: F401from app.models.app_settings import AppSetting # noqa: F401from app.models.goal import Goal # noqa: F401from app.models.credit_card_bill import CreditCardBill # noqa: F401+from app.models.group import Group, GroupMember # noqa: F401+from app.models.transaction_split import TransactionSplit # noqa: F401+from app.models.group_settlement import GroupSettlement # noqa: F401# Use SQLite for tests — fast, no external dependencyTEST_DATABASE_URL = "sqlite+aiosqlite:///./test.db"diff --git a/backend/tests/test_balance_service.py b/backend/tests/test_balance_service.pynew file mode 100644index 00000000..d2842fd6--- /dev/null+++ b/backend/tests/test_balance_service.py@@ -0,0 +1,324 @@+import uuid+from datetime import date+from decimal import Decimal++import pytest+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.account import Account+from app.models.transaction import Transaction+from app.schemas.group import GroupCreate, GroupMemberCreate+from app.schemas.group_settlement import GroupSettlementCreate+from app.schemas.transaction_split import (+ TransactionSplitInput,+ TransactionSplitsInput,+)+from app.services import (+ balance_service,+ group_service,+ settlement_service,+ split_service,+)+++async def _make_account(session: AsyncSession, user_id) -> Account:+ account = Account(+ id=uuid.uuid4(),+ user_id=user_id,+ name="W",+ type="checking",+ balance=Decimal("0"),+ currency="USD",+ )+ session.add(account)+ await session.flush()+ return account+++async def _make_tx(session, user_id, account_id, amount, currency="USD") -> Transaction:+ tx = Transaction(+ id=uuid.uuid4(),+ user_id=user_id,+ account_id=account_id,+ description="t",+ amount=Decimal(amount),+ currency=currency,+ date=date.today(),+ type="debit",+ source="manual",+ )+ session.add(tx)+ await session.flush()+ return tx+++async def _setup(session, test_user, n_others=2):+ group = await group_service.create_group(+ session, test_user.id, GroupCreate(name="Trip")+ )+ self_member = await group_service.create_member(+ session, group.id, test_user.id, GroupMemberCreate(name="Me", is_self=True)+ )+ others = []+ for i in range(n_others):+ m = await group_service.create_member(+ session, group.id, test_user.id, GroupMemberCreate(name=f"Friend{i}")+ )+ others.append(m)+ return group, self_member, others+++async def test_balances_each_friend_owes_their_share(session: AsyncSession, test_user):+ group, self_m, friends = await _setup(session, test_user, n_others=3)+ account = await _make_account(session, test_user.id)+ tx = await _make_tx(session, test_user.id, account.id, "120.00")++ payload = TransactionSplitsInput(+ share_type="equal",+ splits=[+ TransactionSplitInput(group_member_id=self_m.id),+ *[TransactionSplitInput(group_member_id=f.id) for f in friends],+ ],+ )+ await split_service.replace_splits(session, tx, payload, test_user.id)+ await session.commit()++ balances = await balance_service.compute_balances(session, group.id, test_user.id)+ assert balances is not None+ by_member = {ln["member_id"]: ln["amount"] for ln in balances["lines"]}+ # Each friend owes 30.00, self balance line excluded.+ for f in friends:+ assert by_member[f.id] == Decimal("30.00")+ assert self_m.id not in by_member+++async def test_settlement_reduces_balance(session: AsyncSession, test_user):+ group, self_m, friends = await _setup(session, test_user, n_others=2)+ friend = friends[0]+ account = await _make_account(session, test_user.id)+ tx = await _make_tx(session, test_user.id, account.id, "100.00")++ await split_service.replace_splits(+ session,+ tx,+ TransactionSplitsInput(+ share_type="exact",+ splits=[+ TransactionSplitInput(+ group_member_id=self_m.id, share_amount=Decimal("60.00")+ ),+ TransactionSplitInput(+ group_member_id=friend.id, share_amount=Decimal("40.00")+ ),+ ],+ ),+ test_user.id,+ )+ # Friend pays back 25 of the 40 they owe.+ await settlement_service.create_settlement(+ session,+ group.id,+ test_user.id,+ GroupSettlementCreate(+ from_member_id=friend.id,+ to_member_id=self_m.id,+ amount=Decimal("25.00"),+ currency="USD",+ date=date.today(),+ ),+ )+ await session.commit()++ balances = await balance_service.compute_balances(session, group.id, test_user.id)+ by_member = {ln["member_id"]: ln["amount"] for ln in balances["lines"]}+ assert by_member[friend.id] == Decimal("15.00")+++async def test_self_loan_increases_balance_owed(session: AsyncSession, test_user):+ """Self lending money to a friend should make them owe more, even+ without an associated split (e.g. a direct cash advance)."""+ group, self_m, friends = await _setup(session, test_user, n_others=1)+ friend = friends[0]++ await settlement_service.create_settlement(+ session,+ group.id,+ test_user.id,+ GroupSettlementCreate(+ from_member_id=self_m.id,+ to_member_id=friend.id,+ amount=Decimal("50.00"),+ currency="USD",+ date=date.today(),+ ),+ )+ await session.commit()++ balances = await balance_service.compute_balances(session, group.id, test_user.id)+ by_member = {ln["member_id"]: ln["amount"] for ln in balances["lines"]}+ assert by_member[friend.id] == Decimal("50.00")+++async def test_balances_segregated_by_currency(session: AsyncSession, test_user):+ group, self_m, friends = await _setup(session, test_user, n_others=1)+ friend = friends[0]+ account = await _make_account(session, test_user.id)++ tx_usd = await _make_tx(session, test_user.id, account.id, "60.00", currency="USD")+ tx_eur = await _make_tx(session, test_user.id, account.id, "40.00", currency="EUR")++ for tx in (tx_usd, tx_eur):+ await split_service.replace_splits(+ session,+ tx,+ TransactionSplitsInput(+ share_type="equal",+ splits=[+ TransactionSplitInput(group_member_id=self_m.id),+ TransactionSplitInput(group_member_id=friend.id),+ ],+ ),+ test_user.id,+ )+ await session.commit()++ balances = await balance_service.compute_balances(session, group.id, test_user.id)+ by_currency = {ln["currency"]: ln["amount"] for ln in balances["lines"] if ln["member_id"] == friend.id}+ assert by_currency["USD"] == Decimal("30.00")+ assert by_currency["EUR"] == Decimal("20.00")+++async def test_balance_line_dropped_when_settlement_zeroes_out_split(+ session: AsyncSession, test_user+):+ """A friend who pays back exactly their share should drop off the+ balance ledger — no zero-amount line should be returned."""+ group, self_m, friends = await _setup(session, test_user, n_others=1)+ friend = friends[0]+ account = await _make_account(session, test_user.id)+ tx = await _make_tx(session, test_user.id, account.id, "40.00")++ await split_service.replace_splits(+ session,+ tx,+ TransactionSplitsInput(+ share_type="equal",+ splits=[+ TransactionSplitInput(group_member_id=self_m.id),+ TransactionSplitInput(group_member_id=friend.id),+ ],+ ),+ test_user.id,+ )+ # Friend owes 20; pays back exactly 20.+ await settlement_service.create_settlement(+ session,+ group.id,+ test_user.id,+ GroupSettlementCreate(+ from_member_id=friend.id,+ to_member_id=self_m.id,+ amount=Decimal("20.00"),+ currency="USD",+ date=date.today(),+ ),+ )+ await session.commit()++ balances = await balance_service.compute_balances(+ session, group.id, test_user.id+ )+ friend_lines = [ln for ln in balances["lines"] if ln["member_id"] == friend.id]+ assert friend_lines == []+++async def test_cross_member_settlements_are_ignored_in_owner_ledger(+ session: AsyncSession, test_user+):+ """Settlements between two non-self members don't affect the+ owner-ledger view (balance_service is owner-centric in v1)."""+ group, self_m, friends = await _setup(session, test_user, n_others=2)+ a, b = friends+ account = await _make_account(session, test_user.id)++ # Owner pays $30 split equally with A — A owes $15.+ tx = await _make_tx(session, test_user.id, account.id, "30.00")+ await split_service.replace_splits(+ session,+ tx,+ TransactionSplitsInput(+ share_type="equal",+ splits=[+ TransactionSplitInput(group_member_id=self_m.id),+ TransactionSplitInput(group_member_id=a.id),+ ],+ ),+ test_user.id,+ )+ # A "settles" with B — neither side is self. Should be a no-op for+ # the owner's balance ledger.+ await settlement_service.create_settlement(+ session,+ group.id,+ test_user.id,+ GroupSettlementCreate(+ from_member_id=a.id,+ to_member_id=b.id,+ amount=Decimal("100.00"),+ currency="USD",+ date=date.today(),+ ),+ )+ await session.commit()++ balances = await balance_service.compute_balances(+ session, group.id, test_user.id+ )+ by_member = {ln["member_id"]: ln["amount"] for ln in balances["lines"]}+ # A still owes their original $15 — not adjusted by the cross-member tx.+ assert by_member[a.id] == Decimal("15.00")+ # B has no obligation to the owner — no line.+ assert b.id not in by_member+++async def test_no_self_member_means_only_split_totals(+ session: AsyncSession, test_user+):+ """Without a self member, settlements can't be applied (cross-member+ settlements are out of scope for v1) — only split shares accumulate."""+ group = await group_service.create_group(+ session, test_user.id, GroupCreate(name="NoSelf")+ )+ a = await group_service.create_member(+ session, group.id, test_user.id, GroupMemberCreate(name="A")+ )+ b = await group_service.create_member(+ session, group.id, test_user.id, GroupMemberCreate(name="B")+ )+ account = await _make_account(session, test_user.id)+ tx = await _make_tx(session, test_user.id, account.id, "20.00")+ await split_service.replace_splits(+ session,+ tx,+ TransactionSplitsInput(+ share_type="equal",+ splits=[+ TransactionSplitInput(group_member_id=a.id),+ TransactionSplitInput(group_member_id=b.id),+ ],+ ),+ test_user.id,+ )+ await session.commit()++ balances = await balance_service.compute_balances(session, group.id, test_user.id)+ by_member = {ln["member_id"]: ln["amount"] for ln in balances["lines"]}+ assert by_member[a.id] == Decimal("10.00")+ assert by_member[b.id] == Decimal("10.00")diff --git a/backend/tests/test_group_service.py b/backend/tests/test_group_service.pynew file mode 100644index 00000000..1dd14ed3--- /dev/null+++ b/backend/tests/test_group_service.py@@ -0,0 +1,133 @@+import uuid++import pytest+from sqlalchemy.ext.asyncio import AsyncSession++from app.schemas.group import (+ GroupCreate,+ GroupMemberCreate,+ GroupMemberUpdate,+ GroupUpdate,+)+from app.services import group_service+++async def test_create_group_defaults(session: AsyncSession, test_user):+ group = await group_service.create_group(+ session, test_user.id, GroupCreate(name="Roommates")+ )+ assert group.name == "Roommates"+ assert group.kind == "social"+ assert group.default_currency == "USD"+ assert group.is_archived is False+ assert group.user_id == test_user.id+++async def test_create_group_b2b_kind(session: AsyncSession, test_user):+ group = await group_service.create_group(+ session,+ test_user.id,+ GroupCreate(name="Marketing", kind="cost_center", default_currency="EUR"),+ )+ assert group.kind == "cost_center"+ assert group.default_currency == "EUR"+++async def test_duplicate_group_name_rejected(session: AsyncSession, test_user):+ await group_service.create_group(session, test_user.id, GroupCreate(name="Trip"))+ with pytest.raises(ValueError, match="already exists"):+ await group_service.create_group(+ session, test_user.id, GroupCreate(name="Trip")+ )+++async def test_list_groups_excludes_archived_by_default(+ session: AsyncSession, test_user+):+ g1 = await group_service.create_group(session, test_user.id, GroupCreate(name="A"))+ await group_service.create_group(session, test_user.id, GroupCreate(name="B"))+ await group_service.update_group(+ session, g1.id, test_user.id, GroupUpdate(is_archived=True)+ )++ visible = await group_service.list_groups(session, test_user.id)+ assert {g.name for g in visible} == {"B"}++ all_groups = await group_service.list_groups(+ session, test_user.id, include_archived=True+ )+ assert {g.name for g in all_groups} == {"A", "B"}+++async def test_get_group_scoped_to_owner(session: AsyncSession, test_user):+ group = await group_service.create_group(session, test_user.id, GroupCreate(name="X"))+ other_user = uuid.uuid4()+ fetched = await group_service.get_group(session, group.id, other_user)+ assert fetched is None+++async def test_create_member_and_unique_name(session: AsyncSession, test_user):+ group = await group_service.create_group(session, test_user.id, GroupCreate(name="G"))+ member = await group_service.create_member(+ session, group.id, test_user.id, GroupMemberCreate(name="Alice", is_self=True)+ )+ assert member.name == "Alice"+ assert member.is_self is True++ with pytest.raises(ValueError, match="already exists"):+ await group_service.create_member(+ session, group.id, test_user.id, GroupMemberCreate(name="Alice")+ )+++async def test_only_one_self_member_allowed(session: AsyncSession, test_user):+ group = await group_service.create_group(session, test_user.id, GroupCreate(name="G"))+ m1 = await group_service.create_member(+ session, group.id, test_user.id, GroupMemberCreate(name="Me", is_self=True)+ )+ m2 = await group_service.create_member(+ session, group.id, test_user.id, GroupMemberCreate(name="Also Me", is_self=True)+ )+ # m1 should have been demoted automatically.+ refreshed = await group_service.list_members(session, group.id, test_user.id)+ by_id = {m.id: m for m in refreshed}+ assert by_id[m1.id].is_self is False+ assert by_id[m2.id].is_self is True+++async def test_update_member_promotes_to_self_demotes_others(+ session: AsyncSession, test_user+):+ group = await group_service.create_group(session, test_user.id, GroupCreate(name="G"))+ m1 = await group_service.create_member(+ session, group.id, test_user.id, GroupMemberCreate(name="A", is_self=True)+ )+ m2 = await group_service.create_member(+ session, group.id, test_user.id, GroupMemberCreate(name="B")+ )++ await group_service.update_member(+ session, group.id, m2.id, test_user.id, GroupMemberUpdate(is_self=True)+ )+ refreshed = await group_service.list_members(session, group.id, test_user.id)+ by_id = {m.id: m for m in refreshed}+ assert by_id[m1.id].is_self is False+ assert by_id[m2.id].is_self is True+++async def test_member_operations_isolated_per_owner(session: AsyncSession, test_user):+ group = await group_service.create_group(session, test_user.id, GroupCreate(name="G"))+ other = uuid.uuid4()+ result = await group_service.create_member(+ session, group.id, other, GroupMemberCreate(name="Bob")+ )+ assert result is None # group not visible to other userdiff --git a/backend/tests/test_group_visibility.py b/backend/tests/test_group_visibility.pynew file mode 100644index 00000000..5829c8a9--- /dev/null+++ b/backend/tests/test_group_visibility.py@@ -0,0 +1,246 @@+"""Cross-user visibility for groups: an owner can see/edit, a linked+member can see, others see nothing. Settlement and balance reads work+for linked members; writes are owner-only."""++import uuid+from datetime import date+from decimal import Decimal++import bcrypt+import pytest+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.user import User+from app.schemas.group import GroupCreate, GroupMemberCreate+from app.schemas.group_settlement import GroupSettlementCreate+from app.services import (+ balance_service,+ group_service,+ settlement_service,+)+++async def _make_user(session: AsyncSession, email: str) -> User:+ hashed = bcrypt.hashpw(b"pw", bcrypt.gensalt()).decode()+ user = User(+ id=uuid.uuid4(),+ email=email,+ hashed_password=hashed,+ is_active=True,+ is_superuser=False,+ is_verified=True,+ )+ session.add(user)+ await session.flush()+ return user+++async def test_email_auto_resolves_to_linked_user(session: AsyncSession, test_user):+ other = await _make_user(session, "[email protected]")+ group = await group_service.create_group(+ session, test_user.id, GroupCreate(name="Trip")+ )+ member = await group_service.create_member(+ session,+ group.id,+ test_user.id,+ GroupMemberCreate(name="Friend", email="[email protected]"),+ )+ assert member.linked_user_id == other.id+++async def test_email_unknown_creates_shadow(session: AsyncSession, test_user):+ group = await group_service.create_group(+ session, test_user.id, GroupCreate(name="Trip")+ )+ member = await group_service.create_member(+ session,+ group.id,+ test_user.id,+ GroupMemberCreate(name="Stranger", email="[email protected]"),+ )+ assert member.linked_user_id is None+ assert member.email == "[email protected]"+++async def test_linked_member_sees_group_in_list(session: AsyncSession, test_user):+ other = await _make_user(session, "[email protected]")+ group = await group_service.create_group(+ session, test_user.id, GroupCreate(name="Shared")+ )+ await group_service.create_member(+ session,+ group.id,+ test_user.id,+ GroupMemberCreate(name="Viewer", email="[email protected]"),+ )++ visible = await group_service.list_groups(session, other.id)+ assert {g.id for g in visible} == {group.id}+ # Linked member sees is_owner=False; the original owner sees True.+ assert visible[0].is_owner is False++ owners_view = await group_service.list_groups(session, test_user.id)+ assert owners_view[0].is_owner is True+++async def test_unrelated_user_does_not_see_group(session: AsyncSession, test_user):+ stranger = await _make_user(session, "[email protected]")+ await group_service.create_group(session, test_user.id, GroupCreate(name="Private"))++ visible = await group_service.list_groups(session, stranger.id)+ assert visible == []+++async def test_visible_get_works_for_linked_member(session: AsyncSession, test_user):+ other = await _make_user(session, "[email protected]")+ group = await group_service.create_group(+ session, test_user.id, GroupCreate(name="Shared")+ )+ await group_service.create_member(+ session,+ group.id,+ test_user.id,+ GroupMemberCreate(name="V", email="[email protected]"),+ )++ via_visible = await group_service.get_group_visible(session, group.id, other.id)+ assert via_visible is not None+ assert via_visible.is_owner is False++ # Owner-only get returns None for the linked member, ensuring that+ # edit paths reject non-owners cleanly.+ via_owned = await group_service.get_group(session, group.id, other.id)+ assert via_owned is None+++async def test_linked_member_cannot_modify_group(session: AsyncSession, test_user):+ other = await _make_user(session, "[email protected]")+ group = await group_service.create_group(+ session, test_user.id, GroupCreate(name="Shared")+ )+ await group_service.create_member(+ session,+ group.id,+ test_user.id,+ GroupMemberCreate(name="V", email="[email protected]"),+ )++ # Updates via the linked member's user_id resolve to None (no-op).+ from app.schemas.group import GroupUpdate++ updated = await group_service.update_group(+ session, group.id, other.id, GroupUpdate(name="Hijacked")+ )+ assert updated is None++ # Member-add by linked viewer also rejected.+ add = await group_service.create_member(+ session, group.id, other.id, GroupMemberCreate(name="Bob")+ )+ assert add is None+++async def test_linked_member_can_read_balances_and_settlements(+ session: AsyncSession, test_user+):+ other = await _make_user(session, "[email protected]")+ group = await group_service.create_group(+ session, test_user.id, GroupCreate(name="Shared")+ )+ await group_service.create_member(+ session,+ group.id,+ test_user.id,+ GroupMemberCreate(name="Me", is_self=True),+ )+ await group_service.create_member(+ session,+ group.id,+ test_user.id,+ GroupMemberCreate(name="V", email="[email protected]"),+ )++ balances = await balance_service.compute_balances(session, group.id, other.id)+ assert balances is not None+ assert balances["lines"] == []++ settlements = await settlement_service.list_settlements(session, group.id, other.id)+ assert settlements == []+++async def test_linked_member_can_settle_own_debt(+ session: AsyncSession, test_user+):+ """A linked member CAN record a settlement when they are the+ from_member (i.e., they're recording a payment they made)."""+ other = await _make_user(session, "[email protected]")+ group = await group_service.create_group(+ session, test_user.id, GroupCreate(name="Shared")+ )+ self_m = await group_service.create_member(+ session, group.id, test_user.id, GroupMemberCreate(name="Me", is_self=True)+ )+ a = await group_service.create_member(+ session,+ group.id,+ test_user.id,+ GroupMemberCreate(name="A", email="[email protected]"),+ )++ settlement = await settlement_service.create_settlement(+ session,+ group.id,+ other.id,+ GroupSettlementCreate(+ from_member_id=a.id, # the linked member themself+ to_member_id=self_m.id,+ amount=Decimal("5.00"),+ currency="USD",+ date=date.today(),+ ),+ )+ assert settlement is not None+ assert settlement.from_member_id == a.id+++async def test_linked_member_cannot_settle_someone_elses_debt(+ session: AsyncSession, test_user+):+ """A linked member CANNOT speak for another member."""+ other = await _make_user(session, "[email protected]")+ group = await group_service.create_group(+ session, test_user.id, GroupCreate(name="Shared")+ )+ a = await group_service.create_member(+ session,+ group.id,+ test_user.id,+ GroupMemberCreate(name="A", email="[email protected]"),+ )+ b = await group_service.create_member(+ session, group.id, test_user.id, GroupMemberCreate(name="B")+ )++ with pytest.raises(PermissionError):+ await settlement_service.create_settlement(+ session,+ group.id,+ other.id,+ GroupSettlementCreate(+ from_member_id=b.id, # NOT the linked member's own id+ to_member_id=a.id,+ amount=Decimal("5.00"),+ currency="USD",+ date=date.today(),+ ),+ )diff --git a/backend/tests/test_groups_api.py b/backend/tests/test_groups_api.pynew file mode 100644index 00000000..c3d0008d--- /dev/null+++ b/backend/tests/test_groups_api.py@@ -0,0 +1,148 @@+import pytest+from httpx import AsyncClient+++async def _create_group(client: AsyncClient, auth_headers: dict, **overrides) -> dict:+ payload = {"name": "Roommates", "kind": "social", "default_currency": "USD"}+ payload.update(overrides)+ resp = await client.post("/api/groups", headers=auth_headers, json=payload)+ assert resp.status_code == 201, resp.text+ return resp.json()+++async def _add_member(client, auth_headers, group_id, **fields) -> dict:+ payload = {"name": "Alice"}+ payload.update(fields)+ resp = await client.post(+ f"/api/groups/{group_id}/members", headers=auth_headers, json=payload+ )+ assert resp.status_code == 201, resp.text+ return resp.json()+++async def test_create_list_get_group(client: AsyncClient, auth_headers, test_user):+ group = await _create_group(client, auth_headers, name="My Group")++ resp = await client.get("/api/groups", headers=auth_headers)+ assert resp.status_code == 200+ body = resp.json()+ assert any(g["id"] == group["id"] for g in body)++ resp = await client.get(f"/api/groups/{group['id']}", headers=auth_headers)+ assert resp.status_code == 200+ detail = resp.json()+ assert detail["name"] == "My Group"+ assert detail["members"] == []+++async def test_duplicate_group_name_returns_400(client, auth_headers, test_user):+ await _create_group(client, auth_headers, name="Same")+ resp = await client.post(+ "/api/groups",+ headers=auth_headers,+ json={"name": "Same", "kind": "social", "default_currency": "USD"},+ )+ assert resp.status_code == 400+++async def test_kind_validation_rejects_unknown(client, auth_headers, test_user):+ resp = await client.post(+ "/api/groups",+ headers=auth_headers,+ json={"name": "X", "kind": "made_up", "default_currency": "USD"},+ )+ # Pydantic validation error -> 422+ assert resp.status_code == 422+++async def test_member_lifecycle(client, auth_headers, test_user):+ group = await _create_group(client, auth_headers, name="L")++ member = await _add_member(client, auth_headers, group["id"], name="Alice", is_self=True)+ assert member["is_self"] is True++ resp = await client.patch(+ f"/api/groups/{group['id']}/members/{member['id']}",+ headers=auth_headers,+ json={"name": "Alicia"},+ )+ assert resp.status_code == 200+ assert resp.json()["name"] == "Alicia"++ resp = await client.delete(+ f"/api/groups/{group['id']}/members/{member['id']}", headers=auth_headers+ )+ assert resp.status_code == 204+++async def test_balances_endpoint_empty_group(client, auth_headers, test_user):+ group = await _create_group(client, auth_headers, name="EB")+ resp = await client.get(f"/api/groups/{group['id']}/balances", headers=auth_headers)+ assert resp.status_code == 200+ body = resp.json()+ assert body["lines"] == []+ assert body["self_member_id"] is None+++async def test_settlement_endpoints(client, auth_headers, test_user):+ group = await _create_group(client, auth_headers, name="Sett")+ a = await _add_member(client, auth_headers, group["id"], name="A")+ b = await _add_member(client, auth_headers, group["id"], name="B")++ resp = await client.post(+ f"/api/groups/{group['id']}/settlements",+ headers=auth_headers,+ json={+ "from_member_id": a["id"],+ "to_member_id": b["id"],+ "amount": "12.34",+ "currency": "USD",+ "date": "2026-04-28",+ },+ )+ assert resp.status_code == 201, resp.text+ settlement = resp.json()++ resp = await client.get(+ f"/api/groups/{group['id']}/settlements", headers=auth_headers+ )+ assert resp.status_code == 200+ assert any(s["id"] == settlement["id"] for s in resp.json())++ resp = await client.delete(+ f"/api/groups/{group['id']}/settlements/{settlement['id']}",+ headers=auth_headers,+ )+ assert resp.status_code == 204+++async def test_unauthorized_without_token(client):+ resp = await client.get("/api/groups")+ assert resp.status_code == 401+++async def test_settlement_distinct_from_to_validation(client, auth_headers, test_user):+ group = await _create_group(client, auth_headers, name="Distinct")+ a = await _add_member(client, auth_headers, group["id"], name="A")++ resp = await client.post(+ f"/api/groups/{group['id']}/settlements",+ headers=auth_headers,+ json={+ "from_member_id": a["id"],+ "to_member_id": a["id"],+ "amount": "5.00",+ "currency": "USD",+ "date": "2026-04-28",+ },+ )+ # Pydantic validator -> 422+ assert resp.status_code == 422diff --git a/backend/tests/test_settlement_service.py b/backend/tests/test_settlement_service.pynew file mode 100644index 00000000..ea2b81cb--- /dev/null+++ b/backend/tests/test_settlement_service.py@@ -0,0 +1,348 @@+import uuid+from datetime import date+from decimal import Decimal++import bcrypt as _bcrypt+import pytest+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.account import Account+from app.models.transaction import Transaction+from app.models.user import User+from app.schemas.group import GroupCreate, GroupMemberCreate+from app.schemas.group_settlement import (+ GroupSettlementCreate,+ GroupSettlementUpdate,+)+from app.services import group_service, settlement_service+++async def _setup_group(session, user_id):+ group = await group_service.create_group(+ session, user_id, GroupCreate(name=f"S-{uuid.uuid4().hex[:6]}")+ )+ a = await group_service.create_member(+ session, group.id, user_id, GroupMemberCreate(name="Alice")+ )+ b = await group_service.create_member(+ session, group.id, user_id, GroupMemberCreate(name="Bob")+ )+ return group, a, b+++async def _make_user(session, email):+ hashed = _bcrypt.hashpw(b"x", _bcrypt.gensalt()).decode()+ user = User(+ id=uuid.uuid4(),+ email=email,+ hashed_password=hashed,+ is_active=True,+ is_superuser=False,+ is_verified=True,+ preferences={"currency_display": "USD"},+ )+ session.add(user)+ await session.flush()+ return user+++async def _make_account(session, user_id, account_type="checking"):+ account = Account(+ id=uuid.uuid4(),+ user_id=user_id,+ name=f"Acc-{uuid.uuid4().hex[:4]}",+ type=account_type,+ balance=Decimal("0"),+ currency="USD",+ )+ session.add(account)+ await session.flush()+ return account+++async def test_create_settlement_happy_path(session: AsyncSession, test_user):+ group, a, b = await _setup_group(session, test_user.id)+ s = await settlement_service.create_settlement(+ session,+ group.id,+ test_user.id,+ GroupSettlementCreate(+ from_member_id=a.id,+ to_member_id=b.id,+ amount=Decimal("12.50"),+ currency="USD",+ date=date.today(),+ ),+ )+ assert s is not None+ assert s.amount == Decimal("12.50")+ assert s.currency == "USD"+++async def test_settlement_members_must_belong_to_group(+ session: AsyncSession, test_user+):+ group, a, _b = await _setup_group(session, test_user.id)+ other_group, _x, y = await _setup_group(session, test_user.id)++ with pytest.raises(ValueError, match="must belong to the group"):+ await settlement_service.create_settlement(+ session,+ group.id,+ test_user.id,+ GroupSettlementCreate(+ from_member_id=a.id,+ to_member_id=y.id, # belongs to other_group+ amount=Decimal("5.00"),+ currency="USD",+ date=date.today(),+ ),+ )+++async def test_settlement_from_to_must_differ_at_creation(+ session: AsyncSession, test_user+):+ group, a, _b = await _setup_group(session, test_user.id)+ # Pydantic-level validation rejects from == to before service runs.+ with pytest.raises(ValueError, match="must differ"):+ GroupSettlementCreate(+ from_member_id=a.id,+ to_member_id=a.id,+ amount=Decimal("5.00"),+ currency="USD",+ date=date.today(),+ )+++async def test_settlement_update_keeps_invariants(session: AsyncSession, test_user):+ group, a, b = await _setup_group(session, test_user.id)+ s = await settlement_service.create_settlement(+ session,+ group.id,+ test_user.id,+ GroupSettlementCreate(+ from_member_id=a.id,+ to_member_id=b.id,+ amount=Decimal("10.00"),+ currency="USD",+ date=date.today(),+ ),+ )++ updated = await settlement_service.update_settlement(+ session,+ group.id,+ s.id,+ test_user.id,+ GroupSettlementUpdate(amount=Decimal("12.00"), notes="adjusted"),+ )+ assert updated.amount == Decimal("12.00")+ assert updated.notes == "adjusted"++ # Updating to set both ends to the same member should fail.+ with pytest.raises(ValueError, match="must differ"):+ await settlement_service.update_settlement(+ session,+ group.id,+ s.id,+ test_user.id,+ GroupSettlementUpdate(to_member_id=a.id),+ )+++async def test_settlement_owner_isolation(session: AsyncSession, test_user):+ group, a, b = await _setup_group(session, test_user.id)+ other_user = uuid.uuid4()+ result = await settlement_service.create_settlement(+ session,+ group.id,+ other_user,+ GroupSettlementCreate(+ from_member_id=a.id,+ to_member_id=b.id,+ amount=Decimal("1.00"),+ currency="USD",+ date=date.today(),+ ),+ )+ assert result is None+++# ---------------------------------------------------------------------------+# receiver_transaction_id (migration 045): when a settlement is recorded,+# the receiver-side credit transaction should be created (and pinned via+# `receiver_transaction_id`) iff the receiver maps to a real Securo user+# AND that user has a checking/savings account to receive into.+# ---------------------------------------------------------------------------+++async def test_receiver_credit_created_when_to_member_is_linked_with_account(+ session: AsyncSession, test_user+):+ receiver = await _make_user(session, "[email protected]")+ receiver_account = await _make_account(session, receiver.id)+ payer_account = await _make_account(session, test_user.id)++ group = await group_service.create_group(+ session, test_user.id, GroupCreate(name="LinkedReceiver")+ )+ me = await group_service.create_member(+ session, group.id, test_user.id, GroupMemberCreate(name="Me", is_self=True)+ )+ bob = await group_service.create_member(+ session,+ group.id,+ test_user.id,+ GroupMemberCreate(name="Bob", linked_user_id=receiver.id),+ )++ s = await settlement_service.create_settlement(+ session,+ group.id,+ test_user.id,+ GroupSettlementCreate(+ from_member_id=me.id,+ to_member_id=bob.id,+ amount=Decimal("50.00"),+ currency="USD",+ date=date.today(),+ account_id=payer_account.id,+ ),+ )+ assert s is not None+ assert s.receiver_transaction_id is not None++ receiver_tx = await session.get(Transaction, s.receiver_transaction_id)+ assert receiver_tx is not None+ assert receiver_tx.user_id == receiver.id+ assert receiver_tx.account_id == receiver_account.id+ assert receiver_tx.type == "credit"+ assert receiver_tx.amount == Decimal("50.00")+ assert receiver_tx.currency == "USD"+ assert receiver_tx.source == "settlement"+++async def test_receiver_credit_skipped_when_to_member_is_shadow(+ session: AsyncSession, test_user+):+ """Shadow member (no linked_user_id, not is_self) — there's no real+ user on the receiving side, so no credit transaction is created."""+ payer_account = await _make_account(session, test_user.id)+ group = await group_service.create_group(+ session, test_user.id, GroupCreate(name="ShadowReceiver")+ )+ me = await group_service.create_member(+ session, group.id, test_user.id, GroupMemberCreate(name="Me", is_self=True)+ )+ shadow = await group_service.create_member(+ session, group.id, test_user.id, GroupMemberCreate(name="Shadow")+ )++ s = await settlement_service.create_settlement(+ session,+ group.id,+ test_user.id,+ GroupSettlementCreate(+ from_member_id=me.id,+ to_member_id=shadow.id,+ amount=Decimal("10.00"),+ currency="USD",+ date=date.today(),+ account_id=payer_account.id,+ ),+ )+ assert s is not None+ assert s.receiver_transaction_id is None+++async def test_receiver_credit_skipped_when_linked_user_has_no_cash_account(+ session: AsyncSession, test_user+):+ """Linked receiver, but their only account is a credit card (not+ checking/savings). The mirror credit can't be placed and is silently+ skipped — settlement is still recorded."""+ receiver = await _make_user(session, "[email protected]")+ await _make_account(session, receiver.id, account_type="credit_card")+ payer_account = await _make_account(session, test_user.id)++ group = await group_service.create_group(+ session, test_user.id, GroupCreate(name="CCOnly")+ )+ me = await group_service.create_member(+ session, group.id, test_user.id, GroupMemberCreate(name="Me", is_self=True)+ )+ bob = await group_service.create_member(+ session,+ group.id,+ test_user.id,+ GroupMemberCreate(name="Bob", linked_user_id=receiver.id),+ )++ s = await settlement_service.create_settlement(+ session,+ group.id,+ test_user.id,+ GroupSettlementCreate(+ from_member_id=me.id,+ to_member_id=bob.id,+ amount=Decimal("10.00"),+ currency="USD",+ date=date.today(),+ account_id=payer_account.id,+ ),+ )+ assert s is not None+ assert s.receiver_transaction_id is None+++async def test_receiver_credit_lands_on_owner_when_self_member_unlinked(+ session: AsyncSession, test_user+):+ """When the to_member is the owner's self-member with no+ linked_user_id, the service falls back to group.user_id — the+ credit lands on the owner's checking account."""+ owner_account = await _make_account(session, test_user.id)+ group = await group_service.create_group(+ session, test_user.id, GroupCreate(name="SelfFallback")+ )+ owner_self = await group_service.create_member(+ session, group.id, test_user.id, GroupMemberCreate(name="Me", is_self=True)+ )+ friend = await group_service.create_member(+ session, group.id, test_user.id, GroupMemberCreate(name="Friend")+ )++ # Friend pays the owner back. Caller is the owner (allowed to record+ # on any from_member). No account_id — friend is a shadow, no real+ # account to debit. Receiver fallback should still kick in.+ s = await settlement_service.create_settlement(+ session,+ group.id,+ test_user.id,+ GroupSettlementCreate(+ from_member_id=friend.id,+ to_member_id=owner_self.id,+ amount=Decimal("20.00"),+ currency="USD",+ date=date.today(),+ ),+ )+ assert s is not None+ assert s.receiver_transaction_id is not None++ receiver_tx = await session.get(Transaction, s.receiver_transaction_id)+ assert receiver_tx is not None+ assert receiver_tx.user_id == test_user.id+ assert receiver_tx.account_id == owner_account.id+ assert receiver_tx.type == "credit"+ assert receiver_tx.amount == Decimal("20.00")diff --git a/backend/tests/test_share_only_model.py b/backend/tests/test_share_only_model.pynew file mode 100644index 00000000..8bf9a62a--- /dev/null+++ b/backend/tests/test_share_only_model.py@@ -0,0 +1,613 @@+"""Conformity checks for the share-only P/L model.++Under this model, an owner-side split transaction contributes only the+*owner's share* to user-level P/L (dashboard summary, spending-by-+category, reports, budgets). The non-owner shares are reimbursable, not+real cost. Settlement credits are also dropped from P/L because the+share already captured the cost — counting the credit again would+double-book.++Account-level stats (per-account income/expenses, balance history) keep+full amounts because they track real cash through the account.++The tests here pin those guarantees end-to-end: split layout → service+output. Most run in single-currency USD; the cross-currency ones seed+USD↔EUR rates explicitly so SQLite has something to convert with.+"""++import uuid+from datetime import date, datetime, timezone+from decimal import Decimal++import pytest+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.account import Account+from app.models.fx_rate import FxRate+from app.models.transaction import Transaction+from app.schemas.group import GroupCreate, GroupMemberCreate+from app.schemas.group_settlement import GroupSettlementCreate+from app.schemas.transaction_split import (+ TransactionSplitInput,+ TransactionSplitsInput,+)+from app.services import (+ balance_service,+ budget_service,+ dashboard_service,+ group_service,+ settlement_service,+ split_service,+)+++# ──────────────────────────── helpers ─────────────────────────────+++async def _make_account(+ session: AsyncSession, user_id, currency: str = "USD"+) -> Account:+ account = Account(+ id=uuid.uuid4(),+ user_id=user_id,+ name="W",+ type="checking",+ balance=Decimal("0"),+ currency=currency,+ )+ session.add(account)+ await session.flush()+ return account+++async def _make_tx(+ session: AsyncSession,+ user_id,+ account_id,+ amount: str,+ currency: str = "USD",+ *,+ type_: str = "debit",+ category_id=None,+ when: date | None = None,+ description: str = "tx",+ source: str = "manual",+) -> Transaction:+ tx = Transaction(+ id=uuid.uuid4(),+ user_id=user_id,+ account_id=account_id,+ category_id=category_id,+ description=description,+ amount=Decimal(amount),+ currency=currency,+ date=when or date.today(),+ type=type_,+ source=source,+ amount_primary=Decimal(amount) if currency == "USD" else None,+ created_at=datetime.now(timezone.utc),+ )+ session.add(tx)+ await session.flush()+ return tx+++async def _setup_group(+ session: AsyncSession, user, *member_names: str, default_currency: str = "USD"+):+ group = await group_service.create_group(+ session,+ user.id,+ GroupCreate(name=f"G-{uuid.uuid4().hex[:6]}", default_currency=default_currency),+ )+ members = []+ for i, name in enumerate(member_names):+ m = await group_service.create_member(+ session,+ group.id,+ user.id,+ GroupMemberCreate(name=name, is_self=(i == 0)),+ )+ members.append(m)+ return group, members+++async def _force_user_currency(session: AsyncSession, user, code: str) -> None:+ """Pin the test_user's primary currency so dashboard math is predictable."""+ prefs = dict(user.preferences or {})+ prefs["currency_display"] = code+ user.preferences = prefs+ await session.commit()+ await session.refresh(user)+++def _month_window(d: date) -> tuple[date, date]:+ start = d.replace(day=1)+ if start.month == 12:+ end = start.replace(year=start.year + 1, month=1)+ else:+ end = start.replace(month=start.month + 1)+ return start, end+++# ─────────────── share-only model: dashboard summary ────────────────+++async def test_summary_owner_share_caps_expense(+ session: AsyncSession, test_user+):+ """Owner pays $150 split equally with two friends ($50 share). The+ dashboard should report a $50 expense, not $150."""+ await _force_user_currency(session, test_user, "USD")+ today = date.today()+ account = await _make_account(session, test_user.id)+ tx = await _make_tx(session, test_user.id, account.id, "150.00", when=today)+ _, members = await _setup_group(session, test_user, "Me", "A", "B")++ await split_service.replace_splits(+ session,+ tx,+ TransactionSplitsInput(+ share_type="equal",+ splits=[TransactionSplitInput(group_member_id=m.id) for m in members],+ ),+ test_user.id,+ )+ await session.commit()++ summary = await dashboard_service.get_summary(+ session, test_user.id, today.replace(day=1)+ )+ assert summary.monthly_expenses_primary == pytest.approx(50.0, abs=0.01)+ assert summary.monthly_income_primary == 0.0+++async def test_summary_owner_with_zero_share(session: AsyncSession, test_user):+ """Owner fronts a $150 expense entirely for two friends. They each+ have a $75 share; owner has no share. Expense should be $0."""+ await _force_user_currency(session, test_user, "USD")+ today = date.today()+ account = await _make_account(session, test_user.id)+ tx = await _make_tx(session, test_user.id, account.id, "150.00", when=today)+ _, members = await _setup_group(session, test_user, "Me", "A", "B")+ me, friend_a, friend_b = members++ await split_service.replace_splits(+ session,+ tx,+ TransactionSplitsInput(+ share_type="exact",+ splits=[+ TransactionSplitInput(+ group_member_id=friend_a.id, share_amount=Decimal("75.00")+ ),+ TransactionSplitInput(+ group_member_id=friend_b.id, share_amount=Decimal("75.00")+ ),+ ],+ ),+ test_user.id,+ )+ await session.commit()++ summary = await dashboard_service.get_summary(+ session, test_user.id, today.replace(day=1)+ )+ assert summary.monthly_expenses_primary == 0.0+++async def test_summary_no_split_full_amount_counts(+ session: AsyncSession, test_user+):+ """A regular non-split transaction must still count its full amount —+ the offset only applies when splits exist."""+ await _force_user_currency(session, test_user, "USD")+ today = date.today()+ account = await _make_account(session, test_user.id)+ await _make_tx(session, test_user.id, account.id, "80.00", when=today)+ await session.commit()++ summary = await dashboard_service.get_summary(+ session, test_user.id, today.replace(day=1)+ )+ assert summary.monthly_expenses_primary == pytest.approx(80.0, abs=0.01)+++async def test_summary_drops_settlement_credits_from_income(+ session: AsyncSession, test_user+):+ """Receiver-side settlement credits no longer count as income — the+ parent share already booked the expense, so the credit would+ double-count."""+ await _force_user_currency(session, test_user, "USD")+ today = date.today()+ account = await _make_account(session, test_user.id)+ tx = await _make_tx(session, test_user.id, account.id, "60.00", when=today)+ _, members = await _setup_group(session, test_user, "Me", "Friend")+ me, friend = members++ await split_service.replace_splits(+ session,+ tx,+ TransactionSplitsInput(+ share_type="equal",+ splits=[+ TransactionSplitInput(group_member_id=me.id),+ TransactionSplitInput(group_member_id=friend.id),+ ],+ ),+ test_user.id,+ )+ # Friend pays the owner $30 — both the payer-side debit and the+ # receiver-side credit get auto-stamped as source='settlement'.+ await settlement_service.create_settlement(+ session,+ members[0].group_id,+ test_user.id,+ GroupSettlementCreate(+ from_member_id=friend.id,+ to_member_id=me.id,+ amount=Decimal("30.00"),+ currency="USD",+ date=today,+ ),+ )++ summary = await dashboard_service.get_summary(+ session, test_user.id, today.replace(day=1)+ )+ # Owner's expense = $30 share. No income from the settlement credit.+ assert summary.monthly_expenses_primary == pytest.approx(30.0, abs=0.01)+ assert summary.monthly_income_primary == 0.0+++async def test_summary_settlement_debit_excluded_for_payer(+ session: AsyncSession, test_user+):+ """Linked-member side: paying back a debt is not an expense — the+ share already captured it."""+ await _force_user_currency(session, test_user, "USD")+ today = date.today()+ account = await _make_account(session, test_user.id)+ # Settlement-sourced debit on the user's account, by hand.+ await _make_tx(+ session,+ test_user.id,+ account.id,+ "30.00",+ when=today,+ source="settlement",+ )+ await session.commit()++ summary = await dashboard_service.get_summary(+ session, test_user.id, today.replace(day=1)+ )+ assert summary.monthly_expenses_primary == 0.0+++# ─────────────── share-only model: spending by category ─────────────+++async def test_spending_by_category_uses_owner_share(+ session: AsyncSession, test_user, test_categories+):+ """A categorized split contributes only the owner's share to its+ bucket. No share → category drops out."""+ await _force_user_currency(session, test_user, "USD")+ today = date.today()+ food = test_categories[0] # Alimentação+ account = await _make_account(session, test_user.id)++ # Brunch $50, owner share $25 → category should show $25+ brunch = await _make_tx(+ session,+ test_user.id,+ account.id,+ "50.00",+ category_id=food.id,+ description="Brunch",+ when=today,+ )+ _, members = await _setup_group(session, test_user, "Me", "Friend")+ me, friend = members+ await split_service.replace_splits(+ session,+ brunch,+ TransactionSplitsInput(+ share_type="exact",+ splits=[+ TransactionSplitInput(group_member_id=me.id, share_amount=Decimal("25.00")),+ TransactionSplitInput(group_member_id=friend.id, share_amount=Decimal("25.00")),+ ],+ ),+ test_user.id,+ )+ await session.commit()++ spending = await dashboard_service.get_spending_by_category(+ session, test_user.id, today.replace(day=1)+ )+ food_row = next(s for s in spending if s.category_name == "Alimentação")+ assert food_row.total == pytest.approx(25.0, abs=0.01)+++async def test_spending_by_category_drops_zero_share_category(+ session: AsyncSession, test_user, test_categories+):+ """A split where the owner has no share = category contributes $0+ and should not appear in the breakdown at all."""+ await _force_user_currency(session, test_user, "USD")+ today = date.today()+ food = test_categories[0]+ account = await _make_account(session, test_user.id)+ tx = await _make_tx(+ session,+ test_user.id,+ account.id,+ "100.00",+ category_id=food.id,+ when=today,+ )+ _, members = await _setup_group(session, test_user, "Me", "A")+ me, friend = members+ await split_service.replace_splits(+ session,+ tx,+ TransactionSplitsInput(+ share_type="exact",+ splits=[+ TransactionSplitInput(+ group_member_id=friend.id, share_amount=Decimal("100.00")+ ),+ ],+ ),+ test_user.id,+ )+ await session.commit()++ spending = await dashboard_service.get_spending_by_category(+ session, test_user.id, today.replace(day=1)+ )+ assert all(s.category_name != "Alimentação" for s in spending)+++# ─────────────── owner self-member detection ─────────────+++async def test_owner_self_member_recognized_without_link(+ session: AsyncSession, test_user+):+ """The owner's GroupMember has is_self=True but linked_user_id=NULL.+ The offset query must still recognize it as the owner's own share —+ otherwise the regression we hit before returns: the owner's share+ would be subtracted as if it were a non-owner share, blowing the+ expense down to $0."""+ await _force_user_currency(session, test_user, "USD")+ today = date.today()+ account = await _make_account(session, test_user.id)+ tx = await _make_tx(session, test_user.id, account.id, "90.00", when=today)+ _, members = await _setup_group(session, test_user, "Me", "Friend")+ me, friend = members+ # Sanity-check the schema invariant the bug exploited.+ assert me.is_self is True+ assert me.linked_user_id is None++ await split_service.replace_splits(+ session,+ tx,+ TransactionSplitsInput(+ share_type="equal",+ splits=[+ TransactionSplitInput(group_member_id=me.id),+ TransactionSplitInput(group_member_id=friend.id),+ ],+ ),+ test_user.id,+ )+ await session.commit()++ summary = await dashboard_service.get_summary(+ session, test_user.id, today.replace(day=1)+ )+ # Owner's $45 share survives; the previous bug would have returned 0.+ assert summary.monthly_expenses_primary == pytest.approx(45.0, abs=0.01)+++# ─────────────── balance lines: cross-currency rollup ─────────────+++async def _seed_eur_rate(session: AsyncSession, when: date) -> None:+ """Seed a USD→EUR rate so balance_service can FX-convert. Stored as+ base=USD,quote=EUR per the rate model convention."""+ session.add(+ FxRate(+ id=uuid.uuid4(),+ base_currency="USD",+ quote_currency="EUR",+ rate=Decimal("0.85"), # 1 USD = 0.85 EUR ⇒ €100 ≈ $117.65+ date=when,+ source="test",+ )+ )+ await session.commit()+++async def test_balance_line_includes_fx_converted_amount(+ session: AsyncSession, test_user+):+ """A EUR-denominated debt line on a USD-default group must surface+ `amount_in_default_currency` so the frontend can sum cross-currency+ balances into a single KPI without doing FX itself."""+ today = date.today()+ await _seed_eur_rate(session, today)+ account = await _make_account(session, test_user.id, currency="EUR")+ tx = await _make_tx(+ session, test_user.id, account.id, "100.00", currency="EUR", when=today+ )+ _, members = await _setup_group(+ session, test_user, "Me", "Friend", default_currency="USD"+ )+ me, friend = members++ await split_service.replace_splits(+ session,+ tx,+ TransactionSplitsInput(+ share_type="exact",+ splits=[+ TransactionSplitInput(+ group_member_id=friend.id, share_amount=Decimal("100.00")+ ),+ ],+ ),+ test_user.id,+ )+ await session.commit()++ balances = await balance_service.compute_balances(+ session, members[0].group_id, test_user.id+ )+ assert balances is not None+ assert balances["default_currency"] == "USD"+ assert len(balances["lines"]) == 1+ line = balances["lines"][0]+ assert line["currency"] == "EUR"+ assert Decimal(str(line["amount"])) == Decimal("100.00")+ # 100 EUR / 0.85 ≈ 117.65 USD+ assert Decimal(str(line["amount_in_default_currency"])) == pytest.approx(+ Decimal("117.65"), abs=Decimal("0.5")+ )+++async def test_balance_line_default_currency_passthrough(+ session: AsyncSession, test_user+):+ """Same-currency line: amount_in_default_currency should equal amount+ (no FX needed). Guards against accidental rounding."""+ today = date.today()+ account = await _make_account(session, test_user.id)+ tx = await _make_tx(session, test_user.id, account.id, "60.00", when=today)+ _, members = await _setup_group(session, test_user, "Me", "Friend")+ me, friend = members+ await split_service.replace_splits(+ session,+ tx,+ TransactionSplitsInput(+ share_type="exact",+ splits=[+ TransactionSplitInput(+ group_member_id=friend.id, share_amount=Decimal("60.00")+ ),+ ],+ ),+ test_user.id,+ )+ await session.commit()++ balances = await balance_service.compute_balances(+ session, members[0].group_id, test_user.id+ )+ line = balances["lines"][0]+ assert Decimal(str(line["amount"])) == Decimal(str(line["amount_in_default_currency"]))+++# ─────────────── share-only model: reports + budgets ─────────────+++async def test_owner_split_offset_pnl_helper(session: AsyncSession, test_user):+ """The income/expenses report uses Postgres `to_char`, so we can't+ exercise it under SQLite. Instead pin its underlying helper — the+ same one the dashboard uses — directly."""+ from app.services._query_filters import owner_split_offset_pnl++ await _force_user_currency(session, test_user, "USD")+ today = date.today()+ account = await _make_account(session, test_user.id)+ tx = await _make_tx(session, test_user.id, account.id, "120.00", when=today)+ _, members = await _setup_group(session, test_user, "Me", "A", "B", "C")++ await split_service.replace_splits(+ session,+ tx,+ TransactionSplitsInput(+ share_type="equal",+ splits=[TransactionSplitInput(group_member_id=m.id) for m in members],+ ),+ test_user.id,+ )+ await session.commit()++ month_start, month_end = _month_window(today)+ income_offset, expense_offset = await owner_split_offset_pnl(+ session, test_user.id, month_start, month_end, primary_currency="USD"+ )+ # Three friends each owe $30 → offset is $90; the owner's $30 share+ # is what survives in the dashboard math.+ assert income_offset == 0.0+ assert expense_offset == pytest.approx(90.0, abs=0.01)+++async def test_budget_actual_uses_share_only(+ session: AsyncSession, test_user, test_categories+):+ """Budget vs. actual: a category's "actual" spent should be the+ user's share, not the full amount fronted."""+ await _force_user_currency(session, test_user, "USD")+ today = date.today()+ food = test_categories[0]+ account = await _make_account(session, test_user.id)+ tx = await _make_tx(+ session,+ test_user.id,+ account.id,+ "60.00",+ category_id=food.id,+ when=today,+ )+ _, members = await _setup_group(session, test_user, "Me", "A", "B")+ me, *friends = members+ await split_service.replace_splits(+ session,+ tx,+ TransactionSplitsInput(+ share_type="equal",+ splits=[TransactionSplitInput(group_member_id=m.id) for m in members],+ ),+ test_user.id,+ )++ # Create a budget for the food category so it appears in the result.+ from app.models.budget import Budget++ session.add(+ Budget(+ id=uuid.uuid4(),+ user_id=test_user.id,+ category_id=food.id,+ amount=Decimal("100.00"),+ currency="USD",+ month=today.replace(day=1),+ is_recurring=True,+ )+ )+ await session.commit()++ rows = await budget_service.get_budget_vs_actual(+ session, test_user.id, today.replace(day=1)+ )+ food_row = next(r for r in rows if r.category_id == food.id)+ # Owner's share is $20 (60/3); the full $60 would be the bug.+ assert float(food_row.actual_amount) == pytest.approx(20.0, abs=0.01)diff --git a/backend/tests/test_shared_transactions_view.py b/backend/tests/test_shared_transactions_view.pynew file mode 100644index 00000000..d6abc9c8--- /dev/null+++ b/backend/tests/test_shared_transactions_view.py@@ -0,0 +1,315 @@+"""End-to-end tests for the 'shared transactions become first-class+in the linked member's ledger' design:++ - Shared rows show up in /api/transactions for the linked member.+ - The viewer sees their share, not the parent's full amount.+ - Settlement-created debits are excluded from spending reports.+ - Owner doesn't see duplicates (they own the parent).+"""++import pytest+from httpx import AsyncClient+++async def _register(client: AsyncClient, email: str, password: str) -> dict:+ resp = await client.post(+ "/api/auth/register",+ json={"email": email, "password": password},+ )+ assert resp.status_code in (200, 201), resp.text+ return resp.json()+++async def _login(client: AsyncClient, email: str, password: str) -> dict:+ resp = await client.post(+ "/api/auth/login",+ data={"username": email, "password": password},+ headers={"Content-Type": "application/x-www-form-urlencoded"},+ )+ assert resp.status_code == 200, resp.text+ return {"Authorization": f"Bearer {resp.json()['access_token']}"}+++async def _create_account(client, headers, name="Wallet"):+ resp = await client.post(+ "/api/accounts",+ headers=headers,+ json={"name": name, "type": "checking", "balance": 0, "currency": "USD"},+ )+ assert resp.status_code in (200, 201), resp.text+ return resp.json()+++async def _create_group_with_self_and_friend(+ client, owner_headers, friend_email+):+ g = (+ await client.post(+ "/api/groups",+ headers=owner_headers,+ json={"name": "Trip", "kind": "social", "default_currency": "USD"},+ )+ ).json()+ me = (+ await client.post(+ f"/api/groups/{g['id']}/members",+ headers=owner_headers,+ json={"name": "Me", "is_self": True},+ )+ ).json()+ friend = (+ await client.post(+ f"/api/groups/{g['id']}/members",+ headers=owner_headers,+ json={"name": "Friend", "email": friend_email},+ )+ ).json()+ return g, me, friend+++async def test_linked_member_sees_shared_transaction_in_their_list(+ client, auth_headers, test_user+):+ # Owner = the existing test_user.+ # Friend = a freshly registered user we'll link.+ friend_email = "[email protected]"+ await _register(client, friend_email, "friendpassword12")+ friend_headers = await _login(client, friend_email, "friendpassword12")++ account = await _create_account(client, auth_headers)+ group, me_member, friend_member = await _create_group_with_self_and_friend(+ client, auth_headers, friend_email+ )++ # Owner creates a $90 expense split equally with the friend.+ resp = await client.post(+ "/api/transactions",+ headers=auth_headers,+ json={+ "account_id": account["id"],+ "description": "Concert Tickets",+ "amount": 90,+ "date": "2026-04-28",+ "type": "debit",+ "currency": "USD",+ "splits": {+ "share_type": "equal",+ "splits": [+ {"group_member_id": me_member["id"]},+ {"group_member_id": friend_member["id"]},+ ],+ },+ },+ )+ assert resp.status_code == 201++ # Friend's list should now include the shared transaction with+ # viewer_share = 45 and is_shared = True.+ list_resp = await client.get("/api/transactions", headers=friend_headers)+ assert list_resp.status_code == 200+ items = list_resp.json()["items"]+ shared = [t for t in items if t.get("is_shared")]+ assert len(shared) == 1+ assert shared[0]["description"] == "Concert Tickets"+ assert float(shared[0]["viewer_share"]) == 45.0+ assert shared[0]["group_id"] == group["id"]+++async def test_owner_does_not_see_shared_duplicate(client, auth_headers, test_user):+ """Owners see their own transaction once, never tagged as shared."""+ friend_email = "[email protected]"+ await _register(client, friend_email, "friendpassword12")++ account = await _create_account(client, auth_headers)+ _, me, friend = await _create_group_with_self_and_friend(+ client, auth_headers, friend_email+ )++ await client.post(+ "/api/transactions",+ headers=auth_headers,+ json={+ "account_id": account["id"],+ "description": "Dinner",+ "amount": 60,+ "date": "2026-04-28",+ "type": "debit",+ "currency": "USD",+ "splits": {+ "share_type": "equal",+ "splits": [+ {"group_member_id": me["id"]},+ {"group_member_id": friend["id"]},+ ],+ },+ },+ )++ list_resp = await client.get("/api/transactions", headers=auth_headers)+ rows = list_resp.json()["items"]+ dinner_rows = [r for r in rows if r["description"] == "Dinner"]+ assert len(dinner_rows) == 1+ assert dinner_rows[0]["is_shared"] is False+ # viewer_share is also populated for the owner (= their own split+ # share), so the UI can render "your share" alongside the full+ # parent amount. is_shared stays False — no duplicate row.+ assert float(dinner_rows[0]["viewer_share"]) == 30.0+++async def test_owner_viewer_share_null_when_owner_not_in_splits(+ client, auth_headers, test_user+):+ """If the owner paid for others without including themselves in the+ split (e.g. covering a friend's expense), viewer_share stays None+ so the UI doesn't render a misleading 'your share: $0' line."""+ friend_email = "[email protected]"+ await _register(client, friend_email, "friendpassword12")++ account = await _create_account(client, auth_headers)+ _, _me, friend = await _create_group_with_self_and_friend(+ client, auth_headers, friend_email+ )++ await client.post(+ "/api/transactions",+ headers=auth_headers,+ json={+ "account_id": account["id"],+ "description": "Gift",+ "amount": 40,+ "date": "2026-04-28",+ "type": "debit",+ "currency": "USD",+ # Owner pays but only the friend is in the split (owner is+ # covering the friend's whole share — common gift / loan case).+ "splits": {+ "share_type": "equal",+ "splits": [{"group_member_id": friend["id"]}],+ },+ },+ )++ list_resp = await client.get("/api/transactions", headers=auth_headers)+ rows = list_resp.json()["items"]+ gift_rows = [r for r in rows if r["description"] == "Gift"]+ assert len(gift_rows) == 1+ assert gift_rows[0]["is_shared"] is False+ assert gift_rows[0]["viewer_share"] is None+++async def test_settlement_with_account_id_creates_settlement_source_tx(+ client, auth_headers, test_user+):+ """When the payer settles via account_id, the auto-created tx is+ tagged source='settlement' so reports don't double-count it."""+ friend_email = "[email protected]"+ await _register(client, friend_email, "friendpassword12")+ friend_headers = await _login(client, friend_email, "friendpassword12")++ account = await _create_account(client, auth_headers)+ group, me, friend = await _create_group_with_self_and_friend(+ client, auth_headers, friend_email+ )++ # Owner pays $100, splits equally — friend ends up owing $50.+ await client.post(+ "/api/transactions",+ headers=auth_headers,+ json={+ "account_id": account["id"],+ "description": "Show",+ "amount": 100,+ "date": "2026-04-28",+ "type": "debit",+ "currency": "USD",+ "splits": {+ "share_type": "equal",+ "splits": [+ {"group_member_id": me["id"]},+ {"group_member_id": friend["id"]},+ ],+ },+ },+ )++ # Friend creates their own account and settles their $50 debt with+ # the optional account_id flow → backend creates a debit tx in+ # their account, tagged source='settlement'.+ friend_account = await _create_account(client, friend_headers, name="Friend's wallet")+ settle_resp = await client.post(+ f"/api/groups/{group['id']}/settlements",+ headers=friend_headers,+ json={+ "from_member_id": friend["id"],+ "to_member_id": me["id"],+ "amount": "50.00",+ "currency": "USD",+ "date": "2026-04-29",+ "account_id": friend_account["id"],+ },+ )+ assert settle_resp.status_code == 201, settle_resp.text+ settlement = settle_resp.json()+ assert settlement["transaction_id"] is not None++ # Friend's transaction list now has TWO rows: the shared $50+ # share (Show) and the settlement debit ($50). Total spending+ # reports must NOT count both — settlement.source filters it out.+ list_resp = await client.get("/api/transactions", headers=friend_headers)+ rows = list_resp.json()["items"]+ settlement_rows = [r for r in rows if r["id"] == settlement["transaction_id"]]+ assert len(settlement_rows) == 1+ assert settlement_rows[0]["source"] == "settlement"++ # The shared row is still present with viewer_share = 50.+ shared_rows = [r for r in rows if r.get("is_shared")]+ assert len(shared_rows) == 1+ assert float(shared_rows[0]["viewer_share"]) == 50.0+++async def test_group_filter_still_works_for_linked_member(+ client, auth_headers, test_user+):+ """Sanity: the group_id filter on /transactions still scopes to+ the group's transactions for a linked member."""+ friend_email = "[email protected]"+ await _register(client, friend_email, "friendpassword12")+ friend_headers = await _login(client, friend_email, "friendpassword12")++ account = await _create_account(client, auth_headers)+ group, me, friend = await _create_group_with_self_and_friend(+ client, auth_headers, friend_email+ )+ await client.post(+ "/api/transactions",+ headers=auth_headers,+ json={+ "account_id": account["id"],+ "description": "Brunch",+ "amount": 40,+ "date": "2026-04-28",+ "type": "debit",+ "currency": "USD",+ "splits": {+ "share_type": "equal",+ "splits": [+ {"group_member_id": me["id"]},+ {"group_member_id": friend["id"]},+ ],+ },+ },+ )++ resp = await client.get(+ "/api/transactions",+ headers=friend_headers,+ params={"group_id": group["id"]},+ )+ assert resp.status_code == 200+ rows = resp.json()["items"]+ assert {r["description"] for r in rows} == {"Brunch"}diff --git a/backend/tests/test_split_service.py b/backend/tests/test_split_service.pynew file mode 100644index 00000000..a31c0943--- /dev/null+++ b/backend/tests/test_split_service.py@@ -0,0 +1,275 @@+import uuid+from decimal import Decimal++import pytest+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.account import Account+from app.models.transaction import Transaction+from app.models.transaction_split import TransactionSplit+from app.schemas.group import GroupCreate, GroupMemberCreate+from app.schemas.transaction_split import (+ TransactionSplitInput,+ TransactionSplitsInput,+)+from app.services import group_service, split_service+++async def _make_account(session: AsyncSession, user_id) -> Account:+ account = Account(+ id=uuid.uuid4(),+ user_id=user_id,+ name="Wallet",+ type="checking",+ balance=Decimal("1000.00"),+ currency="USD",+ )+ session.add(account)+ await session.flush()+ return account+++async def _make_tx(session: AsyncSession, user_id, account_id, amount: Decimal) -> Transaction:+ from datetime import date++ tx = Transaction(+ id=uuid.uuid4(),+ user_id=user_id,+ account_id=account_id,+ description="Test",+ amount=amount,+ currency="USD",+ date=date.today(),+ type="debit",+ source="manual",+ )+ session.add(tx)+ await session.flush()+ return tx+++async def _make_group_with_members(session, user_id, names):+ group = await group_service.create_group(+ session, user_id, GroupCreate(name=f"G-{uuid.uuid4().hex[:6]}")+ )+ members = []+ for n in names:+ m = await group_service.create_member(+ session, group.id, user_id, GroupMemberCreate(name=n)+ )+ members.append(m)+ return group, members+++async def _read_splits(session, transaction_id):+ rows = (+ await session.execute(+ select(TransactionSplit).where(+ TransactionSplit.transaction_id == transaction_id+ )+ )+ ).scalars().all()+ return list(rows)+++async def test_equal_split_three_ways_assigns_residual_to_last(+ session: AsyncSession, test_user+):+ account = await _make_account(session, test_user.id)+ tx = await _make_tx(session, test_user.id, account.id, Decimal("100.00"))+ _, members = await _make_group_with_members(session, test_user.id, ["A", "B", "C"])++ payload = TransactionSplitsInput(+ share_type="equal",+ splits=[TransactionSplitInput(group_member_id=m.id) for m in members],+ )+ await split_service.replace_splits(session, tx, payload, test_user.id)++ splits = await _read_splits(session, tx.id)+ by_member = {s.group_member_id: s.share_amount for s in splits}+ # 100 / 3 = 33.33 each, last share absorbs the residual to make 33.34+ assert by_member[members[0].id] == Decimal("33.33")+ assert by_member[members[1].id] == Decimal("33.33")+ assert by_member[members[2].id] == Decimal("33.34")+ assert sum(by_member.values()) == Decimal("100.00")+++async def test_percent_split_residual_on_last(session: AsyncSession, test_user):+ account = await _make_account(session, test_user.id)+ tx = await _make_tx(session, test_user.id, account.id, Decimal("100.00"))+ _, members = await _make_group_with_members(session, test_user.id, ["A", "B", "C"])++ payload = TransactionSplitsInput(+ share_type="percent",+ splits=[+ TransactionSplitInput(group_member_id=members[0].id, share_pct=Decimal("33.33")),+ TransactionSplitInput(group_member_id=members[1].id, share_pct=Decimal("33.33")),+ TransactionSplitInput(group_member_id=members[2].id, share_pct=Decimal("33.34")),+ ],+ )+ await split_service.replace_splits(session, tx, payload, test_user.id)++ splits = await _read_splits(session, tx.id)+ total = sum(s.share_amount for s in splits)+ assert total == Decimal("100.00")+ # share_pct preserved per row+ by_member = {s.group_member_id: s for s in splits}+ assert by_member[members[0].id].share_pct == Decimal("33.33")+ assert by_member[members[2].id].share_pct == Decimal("33.34")+++async def test_percent_must_sum_to_100(session: AsyncSession, test_user):+ account = await _make_account(session, test_user.id)+ tx = await _make_tx(session, test_user.id, account.id, Decimal("100.00"))+ _, members = await _make_group_with_members(session, test_user.id, ["A", "B"])++ payload = TransactionSplitsInput(+ share_type="percent",+ splits=[+ TransactionSplitInput(group_member_id=members[0].id, share_pct=Decimal("60")),+ TransactionSplitInput(group_member_id=members[1].id, share_pct=Decimal("30")),+ ],+ )+ with pytest.raises(ValueError, match="sum to 100"):+ await split_service.replace_splits(session, tx, payload, test_user.id)+++async def test_exact_amounts_must_sum_to_total(session: AsyncSession, test_user):+ account = await _make_account(session, test_user.id)+ tx = await _make_tx(session, test_user.id, account.id, Decimal("100.00"))+ _, members = await _make_group_with_members(session, test_user.id, ["A", "B"])++ payload = TransactionSplitsInput(+ share_type="exact",+ splits=[+ TransactionSplitInput(+ group_member_id=members[0].id, share_amount=Decimal("60.00")+ ),+ TransactionSplitInput(+ group_member_id=members[1].id, share_amount=Decimal("39.00")+ ),+ ],+ )+ with pytest.raises(ValueError, match="sum to the transaction amount"):+ await split_service.replace_splits(session, tx, payload, test_user.id)+++async def test_exact_amounts_credit_transaction_uses_absolute_total(+ session: AsyncSession, test_user+):+ """Income splits work the same as expense splits — sign-agnostic."""+ account = await _make_account(session, test_user.id)+ tx = await _make_tx(session, test_user.id, account.id, Decimal("200.00"))+ tx.type = "credit"+ _, members = await _make_group_with_members(session, test_user.id, ["A", "B"])++ payload = TransactionSplitsInput(+ share_type="exact",+ splits=[+ TransactionSplitInput(+ group_member_id=members[0].id, share_amount=Decimal("120.00")+ ),+ TransactionSplitInput(+ group_member_id=members[1].id, share_amount=Decimal("80.00")+ ),+ ],+ )+ await split_service.replace_splits(session, tx, payload, test_user.id)+ splits = await _read_splits(session, tx.id)+ assert sum(s.share_amount for s in splits) == Decimal("200.00")+++async def test_replace_splits_clears_previous(session: AsyncSession, test_user):+ account = await _make_account(session, test_user.id)+ tx = await _make_tx(session, test_user.id, account.id, Decimal("60.00"))+ _, members = await _make_group_with_members(session, test_user.id, ["A", "B", "C"])++ # First, equal split across 3+ await split_service.replace_splits(+ session,+ tx,+ TransactionSplitsInput(+ share_type="equal",+ splits=[TransactionSplitInput(group_member_id=m.id) for m in members],+ ),+ test_user.id,+ )+ assert len(await _read_splits(session, tx.id)) == 3++ # Then replace with 2-way exact+ await split_service.replace_splits(+ session,+ tx,+ TransactionSplitsInput(+ share_type="exact",+ splits=[+ TransactionSplitInput(+ group_member_id=members[0].id, share_amount=Decimal("20.00")+ ),+ TransactionSplitInput(+ group_member_id=members[1].id, share_amount=Decimal("40.00")+ ),+ ],+ ),+ test_user.id,+ )+ splits = await _read_splits(session, tx.id)+ assert len(splits) == 2+ assert sum(s.share_amount for s in splits) == Decimal("60.00")+++async def test_members_must_share_one_group(session: AsyncSession, test_user):+ account = await _make_account(session, test_user.id)+ tx = await _make_tx(session, test_user.id, account.id, Decimal("50.00"))+ _, members_a = await _make_group_with_members(session, test_user.id, ["A"])+ _, members_b = await _make_group_with_members(session, test_user.id, ["B"])++ payload = TransactionSplitsInput(+ share_type="equal",+ splits=[+ TransactionSplitInput(group_member_id=members_a[0].id),+ TransactionSplitInput(group_member_id=members_b[0].id),+ ],+ )+ with pytest.raises(ValueError, match="same group"):+ await split_service.replace_splits(session, tx, payload, test_user.id)+++async def test_members_must_belong_to_owner(session: AsyncSession, test_user):+ account = await _make_account(session, test_user.id)+ tx = await _make_tx(session, test_user.id, account.id, Decimal("50.00"))+ _, members = await _make_group_with_members(session, test_user.id, ["A"])++ other_user = uuid.uuid4()+ payload = TransactionSplitsInput(+ share_type="equal",+ splits=[TransactionSplitInput(group_member_id=members[0].id)],+ )+ with pytest.raises(ValueError, match="not found"):+ await split_service.replace_splits(session, tx, payload, other_user)+++async def test_no_duplicate_member_per_transaction(session: AsyncSession, test_user):+ account = await _make_account(session, test_user.id)+ tx = await _make_tx(session, test_user.id, account.id, Decimal("50.00"))+ _, members = await _make_group_with_members(session, test_user.id, ["A"])++ payload = TransactionSplitsInput(+ share_type="equal",+ splits=[+ TransactionSplitInput(group_member_id=members[0].id),+ TransactionSplitInput(group_member_id=members[0].id),+ ],+ )+ with pytest.raises(ValueError, match="at most once"):+ await split_service.replace_splits(session, tx, payload, test_user.id)diff --git a/backend/tests/test_transaction_splits_api.py b/backend/tests/test_transaction_splits_api.pynew file mode 100644index 00000000..ca6a1b42--- /dev/null+++ b/backend/tests/test_transaction_splits_api.py@@ -0,0 +1,309 @@+"""End-to-end-ish tests for transaction CRUD with splits attached."""++import pytest+from httpx import AsyncClient+++async def _create_account(client: AsyncClient, auth_headers, name="Wallet") -> dict:+ resp = await client.post(+ "/api/accounts",+ headers=auth_headers,+ json={+ "name": name,+ "type": "checking",+ "balance": 0,+ "currency": "USD",+ },+ )+ assert resp.status_code in (200, 201), resp.text+ return resp.json()+++async def _create_group_with_members(client, auth_headers, *names):+ g = (+ await client.post(+ "/api/groups",+ headers=auth_headers,+ json={"name": f"Trip-{names[0]}", "kind": "social", "default_currency": "USD"},+ )+ ).json()+ members = []+ for n in names:+ m = (+ await client.post(+ f"/api/groups/{g['id']}/members",+ headers=auth_headers,+ json={"name": n, "is_self": n == names[0]},+ )+ ).json()+ members.append(m)+ return g, members+++async def test_create_transaction_with_equal_split(client, auth_headers, test_user):+ account = await _create_account(client, auth_headers)+ _, members = await _create_group_with_members(client, auth_headers, "Me", "A", "B")++ resp = await client.post(+ "/api/transactions",+ headers=auth_headers,+ json={+ "account_id": account["id"],+ "description": "Dinner",+ "amount": 99,+ "date": "2026-04-28",+ "type": "debit",+ "currency": "USD",+ "splits": {+ "share_type": "equal",+ "splits": [{"group_member_id": m["id"]} for m in members],+ },+ },+ )+ assert resp.status_code == 201, resp.text+ body = resp.json()+ splits = body["splits"]+ assert len(splits) == 3+ total = sum(float(s["share_amount"]) for s in splits)+ assert abs(total - 99.0) < 0.01+++async def test_update_transaction_replaces_splits(client, auth_headers, test_user):+ account = await _create_account(client, auth_headers)+ _, members = await _create_group_with_members(client, auth_headers, "Me", "A", "B")++ create = await client.post(+ "/api/transactions",+ headers=auth_headers,+ json={+ "account_id": account["id"],+ "description": "X",+ "amount": 60,+ "date": "2026-04-28",+ "type": "debit",+ "currency": "USD",+ "splits": {+ "share_type": "equal",+ "splits": [{"group_member_id": m["id"]} for m in members],+ },+ },+ )+ tx_id = create.json()["id"]++ update = await client.patch(+ f"/api/transactions/{tx_id}",+ headers=auth_headers,+ json={+ "splits": {+ "share_type": "exact",+ "splits": [+ {"group_member_id": members[0]["id"], "share_amount": "20.00"},+ {"group_member_id": members[1]["id"], "share_amount": "40.00"},+ ],+ }+ },+ )+ assert update.status_code == 200, update.text+ splits = update.json()["splits"]+ assert len(splits) == 2+ by_member = {s["group_member_id"]: float(s["share_amount"]) for s in splits}+ assert by_member[members[0]["id"]] == 20.0+ assert by_member[members[1]["id"]] == 40.0+++async def test_split_validation_bubbles_400(client, auth_headers, test_user):+ account = await _create_account(client, auth_headers)+ _, members = await _create_group_with_members(client, auth_headers, "Me", "A")++ resp = await client.post(+ "/api/transactions",+ headers=auth_headers,+ json={+ "account_id": account["id"],+ "description": "Bad",+ "amount": 100,+ "date": "2026-04-28",+ "type": "debit",+ "currency": "USD",+ "splits": {+ "share_type": "exact",+ "splits": [+ {"group_member_id": members[0]["id"], "share_amount": "30.00"},+ {"group_member_id": members[1]["id"], "share_amount": "30.00"},+ ],+ },+ },+ )+ # ValueError from split_service -> 400 via FastAPI handler+ # (depends on the API layer's existing exception mapping; if it+ # surfaces as 500 that means the handler is missing — flag it).+ assert resp.status_code in (400, 422), resp.text+++async def test_create_rejects_percent_under_100(client, auth_headers, test_user):+ account = await _create_account(client, auth_headers)+ _, members = await _create_group_with_members(client, auth_headers, "Me", "A")++ resp = await client.post(+ "/api/transactions",+ headers=auth_headers,+ json={+ "account_id": account["id"],+ "description": "Bad-pct",+ "amount": 100,+ "date": "2026-04-28",+ "type": "debit",+ "currency": "USD",+ "splits": {+ "share_type": "percent",+ "splits": [+ {"group_member_id": members[0]["id"], "share_pct": "60"},+ {"group_member_id": members[1]["id"], "share_pct": "30"},+ ],+ },+ },+ )+ assert resp.status_code == 400, resp.text+ assert "100" in resp.json()["detail"]+++async def test_create_rejects_percent_over_100(client, auth_headers, test_user):+ account = await _create_account(client, auth_headers)+ _, members = await _create_group_with_members(client, auth_headers, "Me", "A")++ resp = await client.post(+ "/api/transactions",+ headers=auth_headers,+ json={+ "account_id": account["id"],+ "description": "Bad-pct-over",+ "amount": 100,+ "date": "2026-04-28",+ "type": "debit",+ "currency": "USD",+ "splits": {+ "share_type": "percent",+ "splits": [+ {"group_member_id": members[0]["id"], "share_pct": "60"},+ {"group_member_id": members[1]["id"], "share_pct": "50"},+ ],+ },+ },+ )+ assert resp.status_code == 400, resp.text+++async def test_create_rejects_exact_under_total(client, auth_headers, test_user):+ account = await _create_account(client, auth_headers)+ _, members = await _create_group_with_members(client, auth_headers, "Me", "A", "B")++ resp = await client.post(+ "/api/transactions",+ headers=auth_headers,+ json={+ "account_id": account["id"],+ "description": "Bad-exact",+ "amount": 90,+ "date": "2026-04-28",+ "type": "debit",+ "currency": "USD",+ "splits": {+ "share_type": "exact",+ "splits": [+ {"group_member_id": members[0]["id"], "share_amount": "30.00"},+ {"group_member_id": members[1]["id"], "share_amount": "30.00"},+ ],+ },+ },+ )+ assert resp.status_code == 400, resp.text+++async def test_update_rejects_invalid_splits_and_keeps_old(+ client, auth_headers, test_user+):+ """A failed split update must leave the transaction intact (no+ half-applied state) and keep the previous splits."""+ account = await _create_account(client, auth_headers)+ _, members = await _create_group_with_members(client, auth_headers, "Me", "A", "B")++ create = await client.post(+ "/api/transactions",+ headers=auth_headers,+ json={+ "account_id": account["id"],+ "description": "Initial",+ "amount": 90,+ "date": "2026-04-28",+ "type": "debit",+ "currency": "USD",+ "splits": {+ "share_type": "equal",+ "splits": [{"group_member_id": m["id"]} for m in members],+ },+ },+ )+ tx_id = create.json()["id"]+ original_splits = create.json()["splits"]++ bad = await client.patch(+ f"/api/transactions/{tx_id}",+ headers=auth_headers,+ json={+ "splits": {+ "share_type": "percent",+ "splits": [+ {"group_member_id": members[0]["id"], "share_pct": "20"},+ {"group_member_id": members[1]["id"], "share_pct": "30"},+ ],+ }+ },+ )+ assert bad.status_code == 400, bad.text++ after = await client.get(f"/api/transactions/{tx_id}", headers=auth_headers)+ assert after.status_code == 200+ assert len(after.json()["splits"]) == len(original_splits)+++async def test_balances_reflect_splits(client, auth_headers, test_user):+ account = await _create_account(client, auth_headers)+ group, members = await _create_group_with_members(client, auth_headers, "Me", "A", "B")+ me, a, b = members++ await client.post(+ "/api/transactions",+ headers=auth_headers,+ json={+ "account_id": account["id"],+ "description": "Drinks",+ "amount": 60,+ "date": "2026-04-28",+ "type": "debit",+ "currency": "USD",+ "splits": {+ "share_type": "equal",+ "splits": [+ {"group_member_id": me["id"]},+ {"group_member_id": a["id"]},+ {"group_member_id": b["id"]},+ ],+ },+ },+ )++ resp = await client.get(f"/api/groups/{group['id']}/balances", headers=auth_headers)+ assert resp.status_code == 200+ body = resp.json()+ by_member = {ln["member_id"]: float(ln["amount"]) for ln in body["lines"]}+ # 60 / 3 = 20 each non-self share+ assert by_member.get(a["id"]) == 20.0+ assert by_member.get(b["id"]) == 20.0diff --git a/backend/tests/test_user_lookup_api.py b/backend/tests/test_user_lookup_api.pynew file mode 100644index 00000000..1731d6fb--- /dev/null+++ b/backend/tests/test_user_lookup_api.py@@ -0,0 +1,42 @@+import pytest+++async def test_lookup_existing_user(client, auth_headers, test_user):+ resp = await client.get(+ "/api/users/lookup",+ params={"email": test_user.email},+ headers=auth_headers,+ )+ assert resp.status_code == 200+ body = resp.json()+ assert body["email"].lower() == test_user.email.lower()+ assert body["id"] == str(test_user.id)+++async def test_lookup_case_insensitive(client, auth_headers, test_user):+ resp = await client.get(+ "/api/users/lookup",+ params={"email": test_user.email.upper()},+ headers=auth_headers,+ )+ assert resp.status_code == 200+++async def test_lookup_missing_user(client, auth_headers, test_user):+ resp = await client.get(+ "/api/users/lookup",+ params={"email": "[email protected]"},+ headers=auth_headers,+ )+ assert resp.status_code == 404+++async def test_lookup_requires_auth(client):+ resp = await client.get(+ "/api/users/lookup", params={"email": "[email protected]"}+ )+ assert resp.status_code == 401diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex a02b0f1f..de39b638 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -24,6 +24,8 @@ const GoalsPage = lazy(() => import('@/pages/goals'))const AssetsPage = lazy(() => import('@/pages/assets'))const ReportsPage = lazy(() => import('@/pages/reports'))const PayeesPage = lazy(() => import('@/pages/payees'))+const GroupsPage = lazy(() => import('@/pages/groups'))+const GroupDetailPage = lazy(() => import('@/pages/group-detail'))const AdminSettingsPage = lazy(() => import('@/pages/admin/settings'))const queryClient = new QueryClient({@@ -74,6 +76,8 @@ function App() {<Route path="/assets" element={<AssetsPage />} /><Route path="/reports" element={<ReportsPage />} /><Route path="/payees" element={<PayeesPage />} />+ <Route path="/groups" element={<GroupsPage />} />+ <Route path="/groups/:id" element={<GroupDetailPage />} /><Route path="/admin" element={<AdminRoute><AdminSettingsPage /></AdminRoute>} /></Route></Routes>diff --git a/frontend/src/components/app-layout.tsx b/frontend/src/components/app-layout.tsxindex a93c574b..260c8bd7 100644--- a/frontend/src/components/app-layout.tsx+++ b/frontend/src/components/app-layout.tsx@@ -45,6 +45,7 @@ import {Repeat,Landmark,Users,+ Split,BarChart3,Sun,Moon,@@ -87,6 +88,7 @@ const navItems: NavItem[] = [{ type: 'link', key: 'recurring', path: '/recurring', icon: Repeat },{ type: 'link', key: 'categories', path: '/categories', icon: Tag },{ type: 'link', key: 'payees', path: '/payees', icon: Users },+ { type: 'link', key: 'splitGroups', path: '/groups', icon: Split },{ type: 'link', key: 'rules', path: '/rules', icon: SlidersHorizontal },]diff --git a/frontend/src/components/transaction-dialog.tsx b/frontend/src/components/transaction-dialog.tsxindex ba9de6ba..0088f4d2 100644--- a/frontend/src/components/transaction-dialog.tsx+++ b/frontend/src/components/transaction-dialog.tsx@@ -25,7 +25,8 @@ import {} from '@/components/ui/dropdown-menu'import { TransactionAttachments } from '@/components/transaction-attachments'import type { AttachmentPreview } from '@/components/transaction-attachments'-import type { Transaction, RecurringTransaction } from '@/types'+import { TransactionSplitsSection } from '@/components/transaction-splits-section'+import type { Transaction, RecurringTransaction, TransactionSplitsInput } from '@/types'import { toast } from 'sonner'export type SaveAction = 'save' | 'saveAndNew' | 'saveAndDuplicate'@@ -326,6 +327,24 @@ function TransactionForm({const [isRecurring, setIsRecurring] = useState(false)const [frequency, setFrequency] = useState<'monthly' | 'weekly' | 'yearly'>('monthly')const [endDate, setEndDate] = useState('')+ // Optional split-with-group payload. `null` = leave splits as-is on+ // update, or no splits on create. The dedicated section component+ // owns its own UI state and surfaces a normalized payload here.+ // Seeded from the transaction's existing splits so the edit dialog+ // round-trips them rather than appearing empty.+ const [splitsValid, setSplitsValid] = useState(true)+ const [splits, setSplits] = useState<TransactionSplitsInput | null>(() => {+ const existing = (seed as Transaction | null | undefined)?.splits+ if (!existing || existing.length === 0) return null+ return {+ share_type: (existing[0].share_type as TransactionSplitsInput['share_type']) ?? 'equal',+ splits: existing.map((s) => ({+ group_member_id: s.group_member_id,+ share_amount: s.share_amount,+ share_pct: s.share_pct,+ })),+ }+ })const isCreating = !transactionconst showConversion = currency !== userCurrency && !isSyncedconst [pendingFiles, setPendingFiles] = useState<File[]>([])@@ -442,12 +461,17 @@ function TransactionForm({const overridePayload: Partial<Transaction> = isCcSelected? { effective_bill_date: effectiveBillDate || null }: {}+ // Splits ride along on the same payload — the backend treats+ // `splits = null` as untouched and a present payload as full+ // replacement.+ const splitsPayload = splits ? { splits } : {}const txData = isSynced? {category_id: categoryId || null,payee_id: payeeId || null,notes: notes.trim() || null,...overridePayload,+ ...splitsPayload,} as Partial<Transaction>: {description,@@ -461,6 +485,7 @@ function TransactionForm({notes: notes.trim() || null,...fxFields,...overridePayload,+ ...splitsPayload,} as Partial<Transaction>const recurringData = isCreating && isRecurring? { frequency, end_date: endDate || undefined }@@ -709,6 +734,20 @@ function TransactionForm({)})()}+ {/* A settlement-sourced transaction *is* the movement clearing a+ group debt; splitting it would create circular accounting+ (the share would settle a debt that this debit is already+ settling). Hide the section entirely in that case. */}+ {transaction?.source !== 'settlement' && (+ <TransactionSplitsSection+ amount={parseFloat(amount) || 0}+ currency={currency}+ value={splits}+ onChange={setSplits}+ onValidityChange={setSplitsValid}+ />+ )}+{!isCreating && transaction ? (<TransactionAttachmentstransactionId={transaction.id}@@ -789,7 +828,7 @@ function TransactionForm({<div className="inline-flex"><Buttontype="submit"- disabled={loading}+ disabled={loading || !splitsValid}className="rounded-r-none">{loading ? t('common.loading') : t('common.save')}@@ -798,7 +837,7 @@ function TransactionForm({<DropdownMenuTrigger asChild><Buttontype="button"- disabled={loading}+ disabled={loading || !splitsValid}aria-label={t('transactions.moreSaveOptions')}className="rounded-l-none border-l border-l-primary-foreground/20 px-2 has-[>svg]:px-2">@@ -816,7 +855,7 @@ function TransactionForm({</DropdownMenu></div>) : (- <Button type="submit" disabled={loading}>+ <Button type="submit" disabled={loading || !splitsValid}>{loading ? t('common.loading') : t('common.save')}</Button>)}diff --git a/frontend/src/components/transaction-splits-section.tsx b/frontend/src/components/transaction-splits-section.tsxnew file mode 100644index 00000000..bfe01bfd--- /dev/null+++ b/frontend/src/components/transaction-splits-section.tsx@@ -0,0 +1,333 @@+import { useEffect, useMemo, useRef, useState } from 'react'+import { useTranslation } from 'react-i18next'+import { useQuery } from '@tanstack/react-query'+import { Users } from 'lucide-react'++import { groups as groupsApi } from '@/lib/api'+import { formatCurrency } from '@/lib/format'+import type { Group, ShareType, TransactionSplitsInput } from '@/types'+import { Input } from '@/components/ui/input'+import { Label } from '@/components/ui/label'++interface RowState {+ member_id: string+ selected: boolean+ amount: string+ percent: string+}++function buildRows(group: Group | null | undefined, current: TransactionSplitsInput | null): RowState[] {+ if (!group) return []+ // Pydantic serializes Decimal as a string, so values arriving from+ // the API may be either number or string. Coerce both shapes.+ const toNum = (v: unknown): number | null => {+ if (v == null) return null+ const n = typeof v === 'number' ? v : Number(v)+ return Number.isFinite(n) ? n : null+ }+ const byMember = new Map<string, { amount: number | null; pct: number | null }>()+ for (const split of current?.splits ?? []) {+ byMember.set(split.group_member_id, {+ amount: toNum(split.share_amount),+ pct: toNum(split.share_pct),+ })+ }+ return group.members.map((m) => {+ const existing = byMember.get(m.id)+ return {+ member_id: m.id,+ selected: !!existing,+ amount: existing?.amount != null ? existing.amount.toFixed(2) : '',+ percent: existing?.pct != null ? existing.pct.toString() : '',+ }+ })+}++export function TransactionSplitsSection({+ amount,+ currency,+ value,+ onChange,+ onValidityChange,+}: {+ amount: number+ currency: string+ value: TransactionSplitsInput | null+ onChange: (next: TransactionSplitsInput | null) => void+ onValidityChange?: (valid: boolean) => void+}) {+ const { t } = useTranslation()+ const [enabled, setEnabled] = useState(value !== null)+ const [groupId, setGroupId] = useState<string>('')+ const [shareType, setShareType] = useState<ShareType>(value?.share_type ?? 'equal')+ const [rows, setRows] = useState<RowState[]>([])+ // Snapshot of the initial value so row hydration survives the+ // first push-state-up cycle (which zeros the parent before the+ // group has finished loading).+ const seedRef = useRef<TransactionSplitsInput | null>(value)+ // Once rows have been hydrated for the seeded value, stop applying+ // it — further edits are user-driven.+ const hydratedRef = useRef(false)++ const { data: groups } = useQuery({+ queryKey: ['groups'],+ queryFn: () => groupsApi.list(false),+ })++ const { data: group } = useQuery({+ queryKey: ['groups', groupId],+ queryFn: () => groupsApi.get(groupId),+ enabled: !!groupId,+ })++ // Auto-pick the group when splits are enabled. If the parent seeded a+ // value (edit flow), look up which group the existing split members+ // belong to so the dialog opens on the right one. Otherwise fall back+ // to the first group.+ useEffect(() => {+ if (!enabled || groupId || !groups || groups.length === 0) return+ const seededIds = new Set((seedRef.current?.splits ?? []).map((s) => s.group_member_id))+ if (seededIds.size > 0) {+ const match = groups.find((g) => g.members.some((m) => seededIds.has(m.id)))+ if (match) {+ setGroupId(match.id)+ return+ }+ }+ setGroupId(groups[0].id)+ }, [enabled, groupId, groups])++ // Rebuild rows when the group changes. Use the seed snapshot the+ // first time so the parent's value can't have been zeroed out by+ // the push-state-up effect before the group finished loading.+ useEffect(() => {+ if (!group) return+ const source = hydratedRef.current ? null : seedRef.current+ setRows(buildRows(group, source))+ hydratedRef.current = true+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [group?.id])++ // Push state up whenever it changes meaningfully.+ useEffect(() => {+ if (!enabled) {+ onChange(null)+ return+ }+ const selected = rows.filter((r) => r.selected)+ if (selected.length === 0) {+ onChange(null)+ return+ }+ const splits = selected.map((r) => {+ if (shareType === 'exact') {+ return {+ group_member_id: r.member_id,+ share_amount: r.amount ? parseFloat(r.amount) : 0,+ }+ }+ if (shareType === 'percent') {+ return {+ group_member_id: r.member_id,+ share_pct: r.percent ? parseFloat(r.percent) : 0,+ }+ }+ return { group_member_id: r.member_id }+ })+ onChange({ share_type: shareType, splits })+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [enabled, shareType, rows])++ // Validation summary+ const total = useMemo(() => {+ if (!enabled) return null+ const selected = rows.filter((r) => r.selected)+ if (selected.length === 0) return null+ if (shareType === 'equal') {+ return amount+ }+ if (shareType === 'exact') {+ return selected.reduce((sum, r) => sum + (parseFloat(r.amount) || 0), 0)+ }+ return selected.reduce((sum, r) => sum + (parseFloat(r.percent) || 0), 0)+ }, [enabled, shareType, rows, amount])++ // True when the splits payload is acceptable for the backend. Equal mode+ // always materializes correctly; exact must sum to the parent amount;+ // percent must sum to exactly 100. Reported up so the parent dialog can+ // gate its save button instead of relying on a 400 round-trip.+ const isValid = useMemo(() => {+ if (!enabled) return true+ const selected = rows.filter((r) => r.selected)+ if (selected.length === 0) return false+ if (shareType === 'equal') return true+ if (shareType === 'exact') {+ const sum = selected.reduce((s, r) => s + (parseFloat(r.amount) || 0), 0)+ return Math.abs(sum - Math.abs(amount)) < 0.005+ }+ const pctSum = selected.reduce((s, r) => s + (parseFloat(r.percent) || 0), 0)+ return Math.abs(pctSum - 100) < 0.005+ }, [enabled, shareType, rows, amount])++ useEffect(() => {+ onValidityChange?.(isValid)+ }, [isValid, onValidityChange])++ const updateRow = (memberId: string, patch: Partial<RowState>) => {+ setRows((prev) => prev.map((r) => (r.member_id === memberId ? { ...r, ...patch } : r)))+ }++ return (+ <div className="space-y-3 pt-2 border-t border-border">+ <label className="text-sm font-medium inline-flex items-center gap-2 cursor-pointer">+ <input+ type="checkbox"+ checked={enabled}+ onChange={(e) => setEnabled(e.target.checked)}+ className="h-4 w-4 rounded border-border accent-primary"+ />+ <Users size={14} />+ {t('splitGroups.splitTransaction')}+ </label>++ {enabled && (+ <div className="space-y-3 pl-6">+ {!groups || groups.length === 0 ? (+ <p className="text-xs text-muted-foreground">+ {t('splitGroups.splitNoGroups')}+ </p>+ ) : (+ <>+ <div className="grid grid-cols-2 gap-3">+ <div className="space-y-1">+ <Label className="text-xs">{t('splitGroups.group')}</Label>+ <select+ className="w-full border border-border rounded-md px-2 py-1.5 text-sm bg-background"+ value={groupId}+ onChange={(e) => setGroupId(e.target.value)}+ >+ {groups.map((g) => (+ <option key={g.id} value={g.id}>+ {g.name}+ </option>+ ))}+ </select>+ </div>+ <div className="space-y-1">+ <Label className="text-xs">{t('splitGroups.shareType')}</Label>+ <select+ className="w-full border border-border rounded-md px-2 py-1.5 text-sm bg-background"+ value={shareType}+ onChange={(e) => setShareType(e.target.value as ShareType)}+ >+ <option value="equal">{t('splitGroups.shareEqual')}</option>+ <option value="exact">{t('splitGroups.shareExact')}</option>+ <option value="percent">{t('splitGroups.sharePercent')}</option>+ </select>+ </div>+ </div>++ {group && (+ <div className="space-y-2">+ {group.members.length === 0 ? (+ <p className="text-xs text-muted-foreground">{t('splitGroups.splitNoMembers')}</p>+ ) : (+ (() => {+ const selectedCount = rows.filter((r) => r.selected).length+ const absAmount = Math.abs(amount)+ return group.members.map((m) => {+ const row = rows.find((r) => r.member_id === m.id)+ if (!row) return null+ const computed: number | null = !row.selected+ ? null+ : shareType === 'equal'+ ? selectedCount > 0+ ? absAmount / selectedCount+ : null+ : shareType === 'percent'+ ? (parseFloat(row.percent) || 0) * absAmount / 100+ : null+ return (+ <div key={m.id} className="flex items-center gap-2">+ <input+ type="checkbox"+ checked={row.selected}+ onChange={(e) =>+ updateRow(m.id, { selected: e.target.checked })+ }+ className="h-4 w-4 rounded border-border accent-primary"+ />+ <span className="text-sm flex-1 min-w-0 truncate">+ {m.name}+ {m.is_self && (+ <span className="ml-1.5 text-xs text-primary">+ ({t('splitGroups.you')})+ </span>+ )}+ </span>+ {computed !== null && (+ <span className="text-xs text-muted-foreground tabular-nums">+ {formatCurrency(computed, currency)}+ </span>+ )}+ {shareType === 'exact' && row.selected && (+ <Input+ type="number"+ step="0.01"+ className="w-24 h-8 text-sm"+ value={row.amount}+ onChange={(e) => updateRow(m.id, { amount: e.target.value })}+ />+ )}+ {shareType === 'percent' && row.selected && (+ <div className="flex items-center gap-1">+ <Input+ type="number"+ step="0.01"+ className="w-20 h-8 text-sm"+ value={row.percent}+ onChange={(e) => updateRow(m.id, { percent: e.target.value })}+ />+ <span className="text-xs text-muted-foreground">%</span>+ </div>+ )}+ </div>+ )+ })+ })()+ )}+ </div>+ )}++ {total !== null && (+ <div className="text-xs text-muted-foreground">+ {shareType === 'percent' ? (+ <span className={total === 100 ? 'text-emerald-600' : 'text-amber-600'}>+ {t('splitGroups.percentSum', { total: total.toFixed(2) })}+ </span>+ ) : shareType === 'exact' ? (+ <span+ className={+ Math.abs(total - Math.abs(amount)) < 0.005+ ? 'text-emerald-600'+ : 'text-amber-600'+ }+ >+ {t('splitGroups.amountSum', {+ total: total.toFixed(2),+ target: Math.abs(amount).toFixed(2),+ currency,+ })}+ </span>+ ) : (+ <span>{t('splitGroups.equalHint')}</span>+ )}+ </div>+ )}+ </>+ )}+ </div>+ )}+ </div>+ )+}diff --git a/frontend/src/components/transactions-filter-bar.tsx b/frontend/src/components/transactions-filter-bar.tsxindex b8c5659c..7624bac1 100644--- a/frontend/src/components/transactions-filter-bar.tsx+++ b/frontend/src/components/transactions-filter-bar.tsx@@ -10,6 +10,7 @@ import {Search,Store,Tag,+ Users,Wallet,X,} from 'lucide-react'@@ -36,7 +37,7 @@ import {import { Calendar } from '@/components/ui/calendar'import { Button } from '@/components/ui/button'import { cn } from '@/lib/utils'-import type { Account, Category, Payee } from '@/types'+import type { Account, Category, Group, Payee } from '@/types'interface TransactionsFilterBarProps {searchInput: string@@ -50,6 +51,8 @@ interface TransactionsFilterBarProps {onUncategorizedChange: (value: boolean) => voidfilterPayee: stringonPayeeChange: (value: string) => void+ filterGroupId: string+ onGroupIdChange: (value: string) => voidfilterFrom: stringfilterTo: stringonDateRangeChange: (from: string, to: string) => void@@ -57,6 +60,7 @@ interface TransactionsFilterBarProps {accounts: Account[]categories: Category[]payees: Payee[]+ groups: Group[]}function toISODate(d: Date): string {@@ -79,6 +83,8 @@ export function TransactionsFilterBar({onUncategorizedChange,filterPayee,onPayeeChange,+ filterGroupId,+ onGroupIdChange,filterFrom,filterTo,onDateRangeChange,@@ -86,6 +92,7 @@ export function TransactionsFilterBar({accounts,categories,payees,+ groups,}: TransactionsFilterBarProps) {const { t, i18n } = useTranslation()const locale = i18n.language === 'en' ? 'en-US' : i18n.language@@ -145,11 +152,17 @@ export function TransactionsFilterBar({[payees, filterPayee],)+ const selectedGroup = useMemo(+ () => groups.find((g) => g.id === filterGroupId),+ [groups, filterGroupId],+ )+const hasAnyFilter =filterAccountIds.length > 0 ||filterCategoryIds.length > 0 ||filterUncategorized ||!!filterPayee ||+ !!filterGroupId ||!!filterFrom ||!!filterTo ||searchInput.trim().length > 0@@ -482,6 +495,64 @@ export function TransactionsFilterBar({</DropdownMenuPortal></DropdownMenuSub>+ {/* Group submenu (single) */}+ <DropdownMenuSub>+ <DropdownMenuSubTrigger className="gap-2 text-[13px]">+ <Users size={14} className="text-muted-foreground" />+ <span className="flex-1">{t('splitGroups.group')}</span>+ {selectedGroup && (+ <span className="max-w-[90px] truncate text-[11px] text-muted-foreground">+ {selectedGroup.name}+ </span>+ )}+ </DropdownMenuSubTrigger>+ <DropdownMenuPortal>+ <DropdownMenuSubContent+ sideOffset={8}+ className="max-h-[320px] w-[240px] overflow-y-auto p-1"+ >+ <DropdownMenuItem+ onSelect={() => onGroupIdChange('')}+ className={cn(+ 'gap-2 rounded-sm px-2 py-1.5 text-[13px]',+ !filterGroupId && 'bg-primary/5',+ )}+ >+ <span className="size-2.5 shrink-0" />+ <span className="min-w-0 flex-1 truncate text-left">+ {t('transactions.all')}+ </span>+ {!filterGroupId && <Check size={13} className="text-primary" />}+ </DropdownMenuItem>+ <div className="my-1 h-px bg-border/60" />+ {groups.length === 0 ? (+ <div className="px-2 py-3 text-center text-[12px] text-muted-foreground">+ {t('transactions.filtersBar.noOptions')}+ </div>+ ) : (+ groups.map((g) => (+ <DropdownMenuItem+ key={g.id}+ onSelect={() => onGroupIdChange(g.id)}+ className={cn(+ 'gap-2 rounded-sm px-2 py-1.5 text-[13px]',+ filterGroupId === g.id && 'bg-primary/5',+ )}+ >+ <span className="size-2.5 shrink-0" />+ <span className="min-w-0 flex-1 truncate text-left">+ {g.name}+ </span>+ {filterGroupId === g.id && (+ <Check size={13} className="text-primary" />+ )}+ </DropdownMenuItem>+ ))+ )}+ </DropdownMenuSubContent>+ </DropdownMenuPortal>+ </DropdownMenuSub>+{/* Date range submenu with presets */}<DropdownMenuSub><DropdownMenuSubTrigger className="gap-2 text-[13px]">diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 4b605d02..1635294e 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -34,6 +34,12 @@ import type {BalanceHistory,PaginatedResponse,ReportResponse,+ Group,+ GroupKind,+ GroupMember,+ GroupSettlement,+ GroupBalances,+ TransactionSplitsInput,} from '@/types'const api = axios.create({@@ -258,6 +264,7 @@ export const transactions = {from?: stringto?: stringbill_id?: string+ group_id?: stringunbilled_only?: booleanq?: stringpage?: number@@ -457,6 +464,132 @@ export const payees = {},}+// Groups (split transactions)+export interface GroupCreatePayload {+ name: string+ kind?: GroupKind+ default_currency?: string+ icon?: string+ color?: string+ notes?: string | null+}++export interface GroupMemberPayload {+ name: string+ linked_user_id?: string | null+ email?: string | null+ is_self?: boolean+}++export interface GroupSettlementPayload {+ from_member_id: string+ to_member_id: string+ amount: number+ currency: string+ date: string+ transaction_id?: string | null+ notes?: string | null+ // When provided, the backend creates a debit transaction on this+ // account and links it via transaction_id. Mutually exclusive with+ // passing transaction_id directly.+ account_id?: string | null+ description?: string | null+}++export const groups = {+ list: async (includeArchived = false): Promise<Group[]> => {+ const { data } = await api.get('/groups', { params: { include_archived: includeArchived } })+ return data+ },+ get: async (id: string): Promise<Group> => {+ const { data } = await api.get(`/groups/${id}`)+ return data+ },+ create: async (payload: GroupCreatePayload): Promise<Group> => {+ const { data } = await api.post('/groups', payload)+ return data+ },+ update: async (id: string, payload: Partial<GroupCreatePayload> & { is_archived?: boolean }): Promise<Group> => {+ const { data } = await api.patch(`/groups/${id}`, payload)+ return data+ },+ delete: async (id: string): Promise<void> => {+ await api.delete(`/groups/${id}`)+ },+ members: {+ list: async (groupId: string): Promise<GroupMember[]> => {+ const { data } = await api.get(`/groups/${groupId}/members`)+ return data+ },+ create: async (groupId: string, payload: GroupMemberPayload): Promise<GroupMember> => {+ const { data } = await api.post(`/groups/${groupId}/members`, payload)+ return data+ },+ update: async (groupId: string, memberId: string, payload: Partial<GroupMemberPayload>): Promise<GroupMember> => {+ const { data } = await api.patch(`/groups/${groupId}/members/${memberId}`, payload)+ return data+ },+ delete: async (groupId: string, memberId: string): Promise<void> => {+ await api.delete(`/groups/${groupId}/members/${memberId}`)+ },+ },+ settlements: {+ list: async (groupId: string): Promise<GroupSettlement[]> => {+ const { data } = await api.get(`/groups/${groupId}/settlements`)+ return data+ },+ create: async (groupId: string, payload: GroupSettlementPayload): Promise<GroupSettlement> => {+ const { data } = await api.post(`/groups/${groupId}/settlements`, payload)+ return data+ },+ update: async (groupId: string, settlementId: string, payload: Partial<GroupSettlementPayload>): Promise<GroupSettlement> => {+ const { data } = await api.patch(`/groups/${groupId}/settlements/${settlementId}`, payload)+ return data+ },+ delete: async (groupId: string, settlementId: string): Promise<void> => {+ await api.delete(`/groups/${groupId}/settlements/${settlementId}`)+ },+ },+ balances: async (groupId: string): Promise<GroupBalances> => {+ const { data } = await api.get(`/groups/${groupId}/balances`)+ return data+ },+ transactions: async (groupId: string, limit = 20): Promise<Transaction[]> => {+ const { data } = await api.get(`/groups/${groupId}/transactions`, {+ params: { limit },+ })+ return data+ },+}++// Helper re-export so transaction-creation forms have a typed entry point.+export type { TransactionSplitsInput }++// User lookup: exact-match resolution for linking group members to+// existing Securo users. Returns null on miss (404).+export interface UserLookupResult {+ id: string+ email: string+}++export const users = {+ lookupByEmail: async (email: string): Promise<UserLookupResult | null> => {+ try {+ const { data } = await api.get('/users/lookup', { params: { email } })+ return data+ } catch (err: unknown) {+ const status = (err as { response?: { status?: number } })?.response?.status+ if (status === 404) return null+ throw err+ }+ },+ directory: async (): Promise<UserLookupResult[]> => {+ const { data } = await api.get('/users/directory')+ return data+ },+}++// Categorization Rulesexport const rules = {list: async (): Promise<Rule[]> => {diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex 77884304..c30bb2cd 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -53,6 +53,7 @@"recurring": "Recurring","assets": "Assets","payees": "Payees",+ "splitGroups": "Groups","goals": "Goals","reports": "Reports","groupAnalysis": "Analysis",@@ -104,6 +105,11 @@"greetingAfternoon": "Good afternoon","greetingEvening": "Good evening","totalBalance": "Total Balance",+ "byCurrency": "By currency:",+ "totalBalanceTooltip": "The main figure sums all accounts converted to your preferred currency. The \"By currency\" line shows totals grouped by each account's native currency, unconverted — so the component in your preferred currency may not match the total (the rest comes from converting the other currencies). \"Net\" adjusts the total for what you owe or are owed in group splits.",+ "pendingSharesOwe": "Net {{net}} after group debts ({{owed}} pending)",+ "pendingSharesOwed": "Net {{net}} including {{owed}} owed to you",+ "pendingSharesTooltip": "Reflects what you owe / are owed across your groups, before any settlement.","monthlyIncome": "Monthly Income","monthlyExpenses": "Monthly Expenses","pendingCategorization": "Uncategorized",@@ -808,6 +814,7 @@"close": "Close","delete": "Delete","edit": "Edit",+ "back": "Back","loading": "Loading...","error": "Error","success": "Success",@@ -817,6 +824,112 @@"showLess": "Show less","showMore": "+{{count}} more"},+ "splitGroups": {+ "title": "Groups",+ "section": "Setup",+ "add": "Add group",+ "edit": "Edit group",+ "created": "Group created",+ "updated": "Group updated",+ "deleted": "Group deleted",+ "empty": "No groups yet",+ "emptyHint": "Create a group to split expenses with people, departments, or projects.",+ "name": "Name",+ "kindLabel": "Type",+ "kindHint": "Drives the labels and reports — pick the closest fit.",+ "defaultCurrency": "Default currency",+ "notes": "Notes",+ "archived": "Archived",+ "showArchived": "Show archived",+ "filter": {+ "active": "Active",+ "archived": "Archived",+ "all": "All"+ },+ "memberCount": "{{count}} members",+ "notFound": "Group not found",+ "members": "Members",+ "addMember": "Add member",+ "editMember": "Edit member",+ "memberAdded": "Member added",+ "memberUpdated": "Member updated",+ "memberDeleted": "Member removed",+ "noMembers": "No members yet",+ "you": "you",+ "memberName": "Name",+ "memberEmail": "Email",+ "memberEmailHint": "Optional — useful if you invite them as a Securo user later.",+ "linkedUser": "Linked Securo user",+ "linkedUserNone": "— Not linked (non-user) —",+ "linkedUserHint": "Pick an existing Securo user to link the member, or leave unlinked to add a non-user (e.g. someone who doesn't have an account yet).",+ "willLinkToUser": "Will link to existing Securo user {{email}}",+ "sharedWithYou": "Shared with you",+ "sharedRowBadge": "Shared · {{group}}",+ "sharedRowBadgeAuthor": "{{author}} · {{group}}",+ "ownerRowBadge": "{{group}}",+ "sharedRowTooltip": "Your share in a group split. Tap to open the group.",+ "sharedRowParent": "of {{total}} total",+ "ownerRowYourShare": "your share: {{share}}",+ "sharedShortBadge": "Shared",+ "sharedShortBadgeAuthor": "Paid by {{author}}",+ "kpiTotalMoved": "Total moved",+ "kpiOwedToYou": "Owed to you",+ "kpiOwedToYouAsMember": "Owed to you",+ "kpiYouOwe": "You owe",+ "spendingTrend": "Spending trend",+ "spendingTrendHint": "Group expenses by month",+ "byCategory": "Spending by category",+ "byCategoryHint": "How the group's expenses are distributed",+ "uncategorized": "Uncategorized",+ "recentTransactions": "Recent transactions",+ "recentTransactionsHint": "Transactions split through this group",+ "viewAllTransactions": "View all",+ "noTransactions": "No transactions split through this group yet",+ "splitWays": "split {{count}} ways",+ "isSelf": "This is me",+ "balances": "Balances",+ "balancesHint": "Who owes whom, computed from splits minus settlements.",+ "allSettled": "All settled.",+ "owesYou": "{{name}} owes you",+ "youOwe": "You owe {{name}}",+ "ownerOwesYou": "{{name}} owes you",+ "thirdPartyOwes": "{{name}} owes {{owner}}",+ "thirdPartyOwed": "{{owner}} owes {{name}}",+ "ownerBadge": "owner",+ "settleUp": "Settle up",+ "payNow": "Pay now",+ "affectAccount": "Also record as a transaction in my account",+ "selectAccount": "Select an account...",+ "affectAccountHint": "A debit will be created on your account for this amount and linked to the settlement.",+ "settled": "Settlement recorded",+ "settlements": "Settlements",+ "recordSettlement": "Record settlement",+ "noSettlements": "No settlements yet.",+ "from": "From",+ "to": "To",+ "selectMember": "Select a member...",+ "amount": "Amount",+ "currency": "Currency",+ "date": "Date",+ "splitTransaction": "Split this transaction",+ "splitNoGroups": "Create a group first to split a transaction.",+ "splitNoMembers": "Add members to the group first.",+ "group": "Group",+ "shareType": "Split by",+ "shareEqual": "Equal",+ "shareExact": "Exact amounts",+ "sharePercent": "Percentages",+ "percentSum": "Sum: {{total}}%",+ "amountSum": "Sum: {{total}} / {{target}} {{currency}}",+ "equalHint": "Each selected member gets an equal share.",+ "kind": {+ "social": "Social",+ "cost_center": "Cost center",+ "project": "Project",+ "client": "Client",+ "other": "Other"+ }+ },"privacy": {"hide": "Hide values","show": "Show values"diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex b41cc06c..90f4094e 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -53,6 +53,7 @@"recurring": "Recorrentes","assets": "Patrimônio","payees": "Beneficiários",+ "splitGroups": "Grupos","goals": "Metas","reports": "Relatórios","groupAnalysis": "Análise",@@ -104,6 +105,11 @@"greetingAfternoon": "Boa tarde","greetingEvening": "Boa noite","totalBalance": "Saldo Total",+ "byCurrency": "Por moeda:",+ "totalBalanceTooltip": "O valor principal soma todas as contas convertidas para sua moeda preferida. A linha \"Por moeda\" mostra os totais separados por moeda original, sem conversão — por isso a soma dos componentes na sua moeda preferida pode não bater com o total (o restante vem da conversão das outras moedas). \"Líquido\" ajusta o total pelo que você tem a receber ou pagar em divisões de grupo.",+ "pendingSharesOwe": "Líquido {{net}} após dívidas de grupo ({{owed}} pendente)",+ "pendingSharesOwed": "Líquido {{net}} incluindo {{owed}} a receber",+ "pendingSharesTooltip": "Reflete o que você deve ou vai receber em grupos, antes de qualquer acerto.","monthlyIncome": "Entradas do Mês","monthlyExpenses": "Saídas do Mês","pendingCategorization": "Sem Categoria",@@ -808,6 +814,7 @@"close": "Fechar","delete": "Excluir","edit": "Editar",+ "back": "Voltar","loading": "Carregando...","error": "Erro","success": "Sucesso",@@ -817,6 +824,112 @@"showLess": "Mostrar menos","showMore": "Mostrar +{{count}}"},+ "splitGroups": {+ "title": "Grupos",+ "section": "Configuração",+ "add": "Adicionar grupo",+ "edit": "Editar grupo",+ "created": "Grupo criado",+ "updated": "Grupo atualizado",+ "deleted": "Grupo excluído",+ "empty": "Nenhum grupo ainda",+ "emptyHint": "Crie um grupo para dividir despesas com pessoas, departamentos ou projetos.",+ "name": "Nome",+ "kindLabel": "Tipo",+ "kindHint": "Define os rótulos e relatórios — escolha o que mais se aproxima.",+ "defaultCurrency": "Moeda padrão",+ "notes": "Notas",+ "archived": "Arquivado",+ "showArchived": "Mostrar arquivados",+ "filter": {+ "active": "Ativos",+ "archived": "Arquivados",+ "all": "Todos"+ },+ "memberCount": "{{count}} membros",+ "notFound": "Grupo não encontrado",+ "members": "Membros",+ "addMember": "Adicionar membro",+ "editMember": "Editar membro",+ "memberAdded": "Membro adicionado",+ "memberUpdated": "Membro atualizado",+ "memberDeleted": "Membro removido",+ "noMembers": "Sem membros ainda",+ "you": "você",+ "memberName": "Nome",+ "memberEmail": "Email",+ "memberEmailHint": "Opcional — útil se você for convidá-lo como usuário do Securo depois.",+ "linkedUser": "Usuário vinculado",+ "linkedUserNone": "— Sem vínculo (não-usuário) —",+ "linkedUserHint": "Escolha um usuário do Securo para vincular, ou deixe sem vínculo para adicionar como não-usuário (ex.: alguém que ainda não tem conta).",+ "willLinkToUser": "Será vinculado ao usuário do Securo {{email}}",+ "sharedWithYou": "Compartilhado com você",+ "sharedRowBadge": "Compartilhada · {{group}}",+ "sharedRowBadgeAuthor": "{{author}} · {{group}}",+ "ownerRowBadge": "{{group}}",+ "sharedRowTooltip": "Sua parcela em uma divisão de grupo. Toque para abrir o grupo.",+ "sharedRowParent": "de {{total}} no total",+ "ownerRowYourShare": "sua parte: {{share}}",+ "sharedShortBadge": "Compartilhada",+ "sharedShortBadgeAuthor": "Pago por {{author}}",+ "kpiTotalMoved": "Total movimentado",+ "kpiOwedToYou": "A receber",+ "kpiOwedToYouAsMember": "Te devem",+ "kpiYouOwe": "A pagar",+ "spendingTrend": "Tendência de gastos",+ "spendingTrendHint": "Despesas do grupo por mês",+ "byCategory": "Gastos por categoria",+ "byCategoryHint": "Distribuição das despesas do grupo",+ "uncategorized": "Sem categoria",+ "recentTransactions": "Transações recentes",+ "recentTransactionsHint": "Transações divididas neste grupo",+ "viewAllTransactions": "Ver todas",+ "noTransactions": "Ainda não há transações divididas neste grupo",+ "splitWays": "dividida entre {{count}}",+ "isSelf": "Sou eu",+ "balances": "Saldos",+ "balancesHint": "Quem deve a quem, calculado a partir das divisões menos os acertos.",+ "allSettled": "Tudo quitado.",+ "owesYou": "{{name}} te deve",+ "youOwe": "Você deve para {{name}}",+ "ownerOwesYou": "{{name}} te deve",+ "thirdPartyOwes": "{{name}} deve para {{owner}}",+ "thirdPartyOwed": "{{owner}} deve para {{name}}",+ "ownerBadge": "dono",+ "settleUp": "Acertar",+ "payNow": "Pagar",+ "affectAccount": "Registrar também como transação na minha conta",+ "selectAccount": "Selecione uma conta...",+ "affectAccountHint": "Será criada uma saída na sua conta com esse valor, vinculada ao acerto.",+ "settled": "Acerto registrado",+ "settlements": "Acertos",+ "recordSettlement": "Registrar acerto",+ "noSettlements": "Sem acertos ainda.",+ "from": "De",+ "to": "Para",+ "selectMember": "Selecione um membro...",+ "amount": "Valor",+ "currency": "Moeda",+ "date": "Data",+ "splitTransaction": "Dividir esta transação",+ "splitNoGroups": "Crie um grupo antes de dividir uma transação.",+ "splitNoMembers": "Adicione membros ao grupo primeiro.",+ "group": "Grupo",+ "shareType": "Dividir por",+ "shareEqual": "Igual",+ "shareExact": "Valores manuais",+ "sharePercent": "Porcentagens",+ "percentSum": "Soma: {{total}}%",+ "amountSum": "Soma: {{total}} / {{target}} {{currency}}",+ "equalHint": "Cada membro selecionado recebe uma parcela igual.",+ "kind": {+ "social": "Social",+ "cost_center": "Centro de custo",+ "project": "Projeto",+ "client": "Cliente",+ "other": "Outro"+ }+ },"privacy": {"hide": "Ocultar valores","show": "Mostrar valores"diff --git a/frontend/src/pages/dashboard.tsx b/frontend/src/pages/dashboard.tsxindex 39f24e4a..d881b261 100644--- a/frontend/src/pages/dashboard.tsx+++ b/frontend/src/pages/dashboard.tsx@@ -4,7 +4,7 @@ import { useTranslation } from 'react-i18next'import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'import { format } from 'date-fns'import { ptBR, enUS } from 'date-fns/locale'-import { dashboard, transactions, budgets, categories as categoriesApi, accounts as accountsApi, goals as goalsApi } from '@/lib/api'+import { dashboard, transactions, budgets, categories as categoriesApi, accounts as accountsApi, goals as goalsApi, groups as groupsApi } from '@/lib/api'import { invalidateFinancialQueries } from '@/lib/invalidate-queries'import { Skeleton } from '@/components/ui/skeleton'import { Button } from '@/components/ui/button'@@ -27,8 +27,8 @@ import {Tooltip,ResponsiveContainer,} from 'recharts'-import { CheckCircle2, CalendarIcon, Paperclip, Target, ArrowUpDown } from 'lucide-react'-import { Link } from 'react-router-dom'+import { CheckCircle2, CalendarIcon, Paperclip, Target, ArrowUpDown, HelpCircle } from 'lucide-react'+import { Link, useNavigate } from 'react-router-dom'import { ICON_MAP } from '@/lib/category-icons'import { PageHeader } from '@/components/page-header'import { CategoryIcon } from '@/components/category-icon'@@ -70,6 +70,7 @@ function formatDate(dateStr: string, locale = 'pt-BR') {export default function DashboardPage() {const { t, i18n } = useTranslation()+ const navigate = useNavigate()const { mask, privacyMode, MASK } = usePrivacyMode()const { user } = useAuth()const userCurrency = user?.preferences?.currency_display ?? 'USD'@@ -126,6 +127,18 @@ export default function DashboardPage() {}),})+ // Resolve group_id → name for the badge on split transactions.+ const { data: allGroups } = useQuery({+ queryKey: ['groups', 'all'],+ queryFn: () => groupsApi.list(true),+ staleTime: 60_000,+ })+ const groupNameById = useMemo(() => {+ const map = new Map<string, string>()+ for (const g of allGroups ?? []) map.set(g.id, g.name)+ return map+ }, [allGroups])+const { data: projectedTxs, isLoading: projectedTxLoading } = useQuery({queryKey: ['dashboard', 'projected-transactions', selectedMonth],queryFn: () => dashboard.projectedTransactions(monthParam),@@ -279,18 +292,40 @@ export default function DashboardPage() {categoryColor: string | nullisProjected: booleanattachmentCount: number+ isShared: boolean+ parentTotal: number | null+ // Owner-side: this user's share of a split they own. Null when+ // they're not in the split, or when share == amount (would be a+ // redundant secondary line).+ ownerShare: number | null+ groupId: string | null+ parentOwnerName: string | null+ groupName: string | null}const TX_PER_PAGE = 10const allDisplayRows = useMemo(() => {const rows: DisplayRow[] = []for (const tx of currentMonthTxs?.items ?? []) {+ const isShared = !!tx.is_shared+ const displayAmount =+ isShared && tx.viewer_share != null ? Number(tx.viewer_share) : Number(tx.amount)+ const groupId = tx.group_id ?? null+ // Owner-side share: backend populates viewer_share for owners+ // who participate in their own split. Suppress when it equals+ // the parent amount (sole-member case = no useful info).+ const ownerShareRaw =+ !isShared && tx.viewer_share != null ? Number(tx.viewer_share) : null+ const ownerShare =+ ownerShareRaw != null && Math.abs(ownerShareRaw) !== Math.abs(Number(tx.amount))+ ? ownerShareRaw+ : nullrows.push({key: tx.id,description: tx.description,date: tx.date,type: tx.type,- amount: Number(tx.amount),+ amount: displayAmount,amountPrimary: tx.amount_primary != null ? Number(tx.amount_primary) : null,currency: tx.currency,categoryIcon: tx.category?.icon ?? null,@@ -298,6 +333,12 @@ export default function DashboardPage() {categoryColor: tx.category?.color ?? null,isProjected: false,attachmentCount: tx.attachment_count ?? 0,+ isShared,+ parentTotal: isShared ? Number(tx.amount) : null,+ ownerShare,+ groupId,+ parentOwnerName: isShared ? tx.parent_owner_name ?? null : null,+ groupName: groupId ? groupNameById.get(groupId) ?? null : null,})}for (const pt of projectedTxs ?? []) {@@ -314,11 +355,17 @@ export default function DashboardPage() {categoryColor: pt.category_color ?? null,isProjected: true,attachmentCount: 0,+ isShared: false,+ parentTotal: null,+ ownerShare: null,+ groupId: null,+ parentOwnerName: null,+ groupName: null,})}rows.sort((a, b) => txSortDesc ? b.date.localeCompare(a.date) : a.date.localeCompare(b.date))return rows- }, [currentMonthTxs, projectedTxs, txSortDesc])+ }, [currentMonthTxs, projectedTxs, txSortDesc, groupNameById])const txTotalPages = Math.ceil(allDisplayRows.length / TX_PER_PAGE)const pagedRows = allDisplayRows.slice((txPage - 1) * TX_PER_PAGE, txPage * TX_PER_PAGE)@@ -403,7 +450,12 @@ export default function DashboardPage() {<div className="flex flex-wrap gap-6">{/* Balance */}<div className="min-w-0">- <p className="text-xs font-medium text-muted-foreground mb-0.5">{t('dashboard.totalBalance')}</p>+ <p className="text-xs font-medium text-muted-foreground mb-0.5 flex items-center gap-1">+ {t('dashboard.totalBalance')}+ <span title={t('dashboard.totalBalanceTooltip')} className="inline-flex cursor-help">+ <HelpCircle className="h-3 w-3 text-muted-foreground/60" />+ </span>+ </p>{summaryLoading ? (<Skeleton className="h-7 w-24" />) : (@@ -413,7 +465,8 @@ export default function DashboardPage() {</p>{/* Per-currency breakdown when multiple currencies */}{summary?.total_balance && Object.keys(summary.total_balance).length > 1 && (- <div className="flex flex-wrap gap-x-2 mt-0.5">+ <div className="flex flex-wrap items-baseline gap-x-1.5 mt-0.5">+ <span className="text-[10px] text-muted-foreground/70">{t('dashboard.byCurrency')}</span>{Object.entries(summary.total_balance).map(([cur, val]) => (<span key={cur} className="text-[10px] text-muted-foreground tabular-nums">{mask(formatCurrency(val, cur, locale))}@@ -421,6 +474,27 @@ export default function DashboardPage() {))}</div>)}+ {/* Net of pending group shares — show only when+ meaningfully nonzero so users without groups+ see the same UI as before. */}+ {summary && Math.abs(summary.pending_shares_net) >= 0.01 && (+ <p+ className={`text-[10px] tabular-nums mt-0.5 ${+ summary.pending_shares_net < 0 ? 'text-rose-500' : 'text-emerald-600'+ }`}+ title={t('dashboard.pendingSharesTooltip')}+ >+ {summary.pending_shares_net < 0+ ? t('dashboard.pendingSharesOwe', {+ net: mask(formatCurrency(totalBalance + summary.pending_shares_net, primaryCurrency, locale)),+ owed: mask(formatCurrency(Math.abs(summary.pending_shares_net), primaryCurrency, locale)),+ })+ : t('dashboard.pendingSharesOwed', {+ net: mask(formatCurrency(totalBalance + summary.pending_shares_net, primaryCurrency, locale)),+ owed: mask(formatCurrency(summary.pending_shares_net, primaryCurrency, locale)),+ })}+ </p>+ )}</div>)}</div>@@ -856,9 +930,21 @@ export default function DashboardPage() {{pagedRows.map((row) => (<TableRowkey={row.key}- className={`border-b border-border last:border-0 ${!row.isProjected ? 'cursor-pointer hover:bg-muted' : ''}`}+ className={`border-b border-border last:border-0 ${+ row.isProjected+ ? ''+ : row.isShared+ ? 'cursor-pointer hover:bg-muted'+ : 'cursor-pointer hover:bg-muted'+ }`}onClick={() => {if (row.isProjected) return+ if (row.isShared) {+ // Shared rows belong to another user — open the+ // group instead of the (locked) edit dialog.+ if (row.groupId) navigate(`/groups/${row.groupId}`)+ return+ }const tx = currentMonthTxs?.items.find((t) => t.id === row.key)if (tx) { setEditingTx(tx); setDialogOpen(true) }}}@@ -869,6 +955,13 @@ export default function DashboardPage() {<div className="min-w-0"><div className="flex items-center gap-2"><p className="text-sm font-semibold text-foreground truncate">{row.description}</p>+ {row.groupId && (+ <span className="inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-semibold bg-violet-100 text-violet-700 dark:bg-violet-950/40 dark:text-violet-300 shrink-0 uppercase tracking-wide">+ {row.isShared && row.parentOwnerName+ ? t('splitGroups.sharedShortBadgeAuthor', { author: row.parentOwnerName })+ : row.groupName ?? t('splitGroups.sharedShortBadge')}+ </span>+ )}{row.isProjected && (<span className="inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-semibold bg-violet-100 text-violet-600 shrink-0">{t('transactions.recurringBadge')}@@ -886,7 +979,21 @@ export default function DashboardPage() {<span className={`text-sm font-semibold tabular-nums ${row.type === 'credit' ? 'text-emerald-600' : 'text-rose-500'}`}>{mask(`${row.type === 'credit' ? '+' : '-'}${formatCurrency(Math.abs(row.amount), row.currency, locale)}`)}</span>- {row.currency !== userCurrency && row.amountPrimary != null && (+ {row.isShared && row.parentTotal != null && (+ <span className="block text-[10px] text-muted-foreground tabular-nums">+ {t('splitGroups.sharedRowParent', {+ total: formatCurrency(Math.abs(row.parentTotal), row.currency, locale),+ })}+ </span>+ )}+ {!row.isShared && row.ownerShare != null && (+ <span className="block text-[10px] text-muted-foreground tabular-nums">+ {t('splitGroups.ownerRowYourShare', {+ share: formatCurrency(Math.abs(row.ownerShare), row.currency, locale),+ })}+ </span>+ )}+ {!row.isShared && row.currency !== userCurrency && row.amountPrimary != null && (<span className="block text-[10px] text-muted-foreground tabular-nums">{mask(formatCurrency(Math.abs(row.amountPrimary), userCurrency, locale))}</span>diff --git a/frontend/src/pages/group-detail.tsx b/frontend/src/pages/group-detail.tsxnew file mode 100644index 00000000..fcf537f8--- /dev/null+++ b/frontend/src/pages/group-detail.tsx@@ -0,0 +1,1181 @@+import { useMemo, useState } from 'react'+import { useTranslation } from 'react-i18next'+import { useNavigate, useParams } from 'react-router-dom'+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { toast } from 'sonner'+import {+ ArrowLeft,+ ArrowRight,+ ChevronDown,+ Link2,+ Receipt,+ TrendingDown,+ TrendingUp,+ Trash2,+ UserPlus,+ Wallet,+} from 'lucide-react'+import {+ Bar,+ BarChart,+ ResponsiveContainer,+ Tooltip,+ XAxis,+} from 'recharts'++import {+ groups as groupsApi,+ users as usersApi,+ accounts as accountsApi,+ type GroupMemberPayload,+ type GroupSettlementPayload,+} from '@/lib/api'+import { useAuth } from '@/contexts/auth-context'+import { Button } from '@/components/ui/button'+import { Input } from '@/components/ui/input'+import { Label } from '@/components/ui/label'+import { Skeleton } from '@/components/ui/skeleton'+import {+ Dialog,+ DialogContent,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog'+import { CategoryIcon } from '@/components/category-icon'+import { PageHeader } from '@/components/page-header'+import type { GroupMember, GroupSettlement } from '@/types'++function formatCurrency(value: number, currency = 'USD', locale = 'en-US') {+ return new Intl.NumberFormat(locale, { style: 'currency', currency }).format(value)+}++function SectionCard({ children }: { children: React.ReactNode }) {+ return (+ <div className="bg-card rounded-xl border border-border shadow-sm overflow-hidden">+ {children}+ </div>+ )+}++function SectionHeader({+ title,+ description,+ action,+}: {+ title: string+ description?: string+ action?: React.ReactNode+}) {+ return (+ <div className="px-4 sm:px-5 py-4 border-b border-border flex flex-wrap items-center justify-between gap-2">+ <div className="min-w-0">+ <p className="text-sm font-semibold text-foreground">{title}</p>+ {description && (+ <p className="text-xs text-muted-foreground mt-0.5">{description}</p>+ )}+ </div>+ {action}+ </div>+ )+}++interface KpiBreakdownItem {+ name: string+ amountText: string+}++function KpiCard({+ label,+ value,+ icon: Icon,+ tone,+ breakdown,+}: {+ label: string+ value: string+ icon: React.ComponentType<{ size?: number; className?: string }>+ tone?: 'positive' | 'negative' | 'neutral'+ breakdown?: KpiBreakdownItem[]+}) {+ const [open, setOpen] = useState(false)+ const toneClass =+ tone === 'positive'+ ? 'text-emerald-600'+ : tone === 'negative'+ ? 'text-rose-500'+ : 'text-foreground'+ const hasBreakdown = !!breakdown && breakdown.length > 0+ return (+ <div className="bg-card rounded-xl border border-border shadow-sm p-3 sm:p-4">+ <button+ type="button"+ className={`w-full text-left ${hasBreakdown ? 'cursor-pointer' : 'cursor-default'}`}+ onClick={() => hasBreakdown && setOpen((o) => !o)}+ disabled={!hasBreakdown}+ aria-expanded={open}+ >+ <div className="flex items-center justify-between">+ <p className="text-[10px] sm:text-xs font-medium text-muted-foreground uppercase tracking-wide">+ {label}+ </p>+ <div className="flex items-center gap-1 text-muted-foreground">+ {hasBreakdown && (+ <ChevronDown+ size={14}+ className={`transition-transform ${open ? 'rotate-180' : ''}`}+ />+ )}+ <Icon size={14} />+ </div>+ </div>+ <p className={`text-base sm:text-2xl font-bold tabular-nums mt-1 ${toneClass}`}>+ {value}+ </p>+ </button>+ {open && hasBreakdown && (+ <ul className="mt-2 pt-2 border-t border-border space-y-1 text-xs text-muted-foreground">+ {breakdown!.map((b, i) => (+ <li key={i} className="flex justify-between gap-2">+ <span className="truncate">{b.name}</span>+ <span className="tabular-nums whitespace-nowrap text-foreground">+ {b.amountText}+ </span>+ </li>+ ))}+ </ul>+ )}+ </div>+ )+}++export default function GroupDetailPage() {+ const { id } = useParams<{ id: string }>()+ const groupId = id ?? ''+ const { t, i18n } = useTranslation()+ const locale = i18n.language === 'en' ? 'en-US' : i18n.language+ const navigate = useNavigate()+ const queryClient = useQueryClient()+ const { user } = useAuth()++ const { data: group, isLoading: loadingGroup } = useQuery({+ queryKey: ['groups', groupId],+ queryFn: () => groupsApi.get(groupId),+ enabled: !!groupId,+ })++ // Linked members get a read-only view of the group.+ const isOwner = group?.is_owner ?? false+ // The member that represents the current viewer (when linked).+ const viewerMember = useMemo(+ () => group?.members.find((m) => user && m.linked_user_id === user.id),+ [group?.members, user],+ )+ // The "self" member is the owner-payer of the group's transactions.+ const ownerMember = useMemo(+ () => group?.members.find((m) => m.is_self),+ [group?.members],+ )++ const { data: balances } = useQuery({+ queryKey: ['groups', groupId, 'balances'],+ queryFn: () => groupsApi.balances(groupId),+ enabled: !!groupId,+ })++ const { data: settlements } = useQuery({+ queryKey: ['groups', groupId, 'settlements'],+ queryFn: () => groupsApi.settlements.list(groupId),+ enabled: !!groupId,+ })++ const { data: groupTxs } = useQuery({+ queryKey: ['groups', groupId, 'transactions'],+ queryFn: () => groupsApi.transactions(groupId, 20),+ enabled: !!groupId,+ })++ // ── Member management ────────────────────────────────────────+ const [memberDialogOpen, setMemberDialogOpen] = useState(false)+ const [editingMember, setEditingMember] = useState<GroupMember | null>(null)+ const [memberName, setMemberName] = useState('')+ const [memberEmail, setMemberEmail] = useState('')+ // The Securo user this member should be linked to (if any). When set,+ // name+email are derived from that user and the inputs are locked —+ // is_self is auto-inferred (true iff the linked user is the viewer).+ const [memberLinkedUserId, setMemberLinkedUserId] = useState<string | null>(null)++ const memberMutation = useMutation({+ mutationFn: (payload: GroupMemberPayload) =>+ editingMember+ ? groupsApi.members.update(groupId, editingMember.id, payload)+ : groupsApi.members.create(groupId, payload),+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: ['groups', groupId] })+ queryClient.invalidateQueries({ queryKey: ['groups', groupId, 'balances'] })+ setMemberDialogOpen(false)+ setEditingMember(null)+ toast.success(editingMember ? t('splitGroups.memberUpdated') : t('splitGroups.memberAdded'))+ },+ onError: (err: unknown) => {+ const detail =+ err && typeof err === 'object' && 'response' in err+ ? (err as { response?: { data?: { detail?: string } } }).response?.data?.detail+ : undefined+ toast.error(detail ?? t('common.error'))+ },+ })++ const deleteMemberMutation = useMutation({+ mutationFn: (memberId: string) => groupsApi.members.delete(groupId, memberId),+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: ['groups', groupId] })+ queryClient.invalidateQueries({ queryKey: ['groups', groupId, 'balances'] })+ setMemberDialogOpen(false)+ setEditingMember(null)+ toast.success(t('splitGroups.memberDeleted'))+ },+ onError: (err: unknown) => {+ const detail =+ err && typeof err === 'object' && 'response' in err+ ? (err as { response?: { data?: { detail?: string } } }).response?.data?.detail+ : undefined+ toast.error(detail ?? t('common.error'))+ },+ })++ const openCreateMember = () => {+ setEditingMember(null)+ setMemberName('')+ setMemberEmail('')+ setMemberLinkedUserId(null)+ setMemberDialogOpen(true)+ }++ const openEditMember = (member: GroupMember) => {+ setEditingMember(member)+ setMemberName(member.name)+ setMemberEmail(member.email ?? '')+ setMemberLinkedUserId(member.linked_user_id)+ setMemberDialogOpen(true)+ }++ const saveMember = () => {+ // is_self is derived: a linked-to-viewer member is always "you".+ // Unlinked members can still represent the viewer if explicitly the+ // first member of their own group (legacy data) — we preserve that+ // flag during edits via the existing record.+ const linkedToViewer =+ memberLinkedUserId !== null && memberLinkedUserId === user?.id+ const is_self = linkedToViewer || (!memberLinkedUserId && (editingMember?.is_self ?? false))+ memberMutation.mutate({+ name: memberName.trim(),+ email: memberEmail.trim() || null,+ is_self,+ })+ }++ // Directory of all Securo users on the instance — populates the+ // member-picker dropdown so the host can pick an existing account+ // rather than typing its email.+ const { data: userDirectory } = useQuery({+ queryKey: ['users', 'directory'],+ queryFn: () => usersApi.directory(),+ enabled: memberDialogOpen,+ staleTime: 60_000,+ })++ // Resolve a typed email to an existing Securo user, kept as a+ // fallback for the "I know their email but they aren't in my list+ // for some reason" path.+ const trimmedEmail = memberEmail.trim()+ const { data: lookupResult } = useQuery({+ queryKey: ['users', 'lookup', trimmedEmail.toLowerCase()],+ queryFn: () => usersApi.lookupByEmail(trimmedEmail),+ enabled: trimmedEmail.length >= 3 && trimmedEmail.includes('@'),+ staleTime: 60_000,+ retry: false,+ })++ // ── Settle-up ────────────────────────────────────────────────+ const [settleOpen, setSettleOpen] = useState(false)+ const [settleFrom, setSettleFrom] = useState('')+ const [settleTo, setSettleTo] = useState('')+ const [settleAmount, setSettleAmount] = useState('')+ const [settleDate, setSettleDate] = useState(new Date().toISOString().split('T')[0])+ const [settleNotes, setSettleNotes] = useState('')+ const [settleCurrency, setSettleCurrency] = useState('USD')+ const [settleAffectAccount, setSettleAffectAccount] = useState(false)+ const [settleAccountId, setSettleAccountId] = useState('')++ // Accounts of the requesting user — needed only when the optional+ // "create transaction" toggle is enabled.+ const { data: accountsList } = useQuery({+ queryKey: ['accounts'],+ queryFn: () => accountsApi.list(),+ enabled: settleOpen,+ })++ const settlementMutation = useMutation({+ mutationFn: (payload: GroupSettlementPayload) =>+ groupsApi.settlements.create(groupId, payload),+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: ['groups', groupId, 'settlements'] })+ queryClient.invalidateQueries({ queryKey: ['groups', groupId, 'balances'] })+ setSettleOpen(false)+ toast.success(t('splitGroups.settled'))+ },+ onError: (err: unknown) => {+ const detail =+ err && typeof err === 'object' && 'response' in err+ ? (err as { response?: { data?: { detail?: string } } }).response?.data?.detail+ : undefined+ toast.error(detail ?? t('common.error'))+ },+ })++ const deleteSettlementMutation = useMutation({+ mutationFn: (settlementId: string) =>+ groupsApi.settlements.delete(groupId, settlementId),+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: ['groups', groupId, 'settlements'] })+ queryClient.invalidateQueries({ queryKey: ['groups', groupId, 'balances'] })+ },+ })++ const openSettleUp = (+ from?: string,+ to?: string,+ amount?: number,+ currency?: string,+ ) => {+ setSettleFrom(from ?? '')+ setSettleTo(to ?? '')+ setSettleAmount(amount != null ? amount.toFixed(2) : '')+ setSettleDate(new Date().toISOString().split('T')[0])+ setSettleNotes('')+ // Use the line's currency when settling a specific debt, falling+ // back to the group's default for free-form settlements. This+ // matters when the same group has cross-currency debts.+ setSettleCurrency(currency ?? group?.default_currency ?? 'USD')+ setSettleAffectAccount(false)+ setSettleAccountId('')+ setSettleOpen(true)+ }++ const saveSettlement = () => {+ if (!settleFrom || !settleTo || !settleAmount) return+ const payload: GroupSettlementPayload = {+ from_member_id: settleFrom,+ to_member_id: settleTo,+ amount: parseFloat(settleAmount),+ currency: settleCurrency,+ date: settleDate,+ notes: settleNotes.trim() || null,+ }+ if (settleAffectAccount && settleAccountId) {+ payload.account_id = settleAccountId+ }+ settlementMutation.mutate(payload)+ }++ // Lookup helpers+ const memberById = useMemo(() => {+ const map = new Map<string, GroupMember>()+ for (const m of group?.members ?? []) map.set(m.id, m)+ return map+ }, [group?.members])++ const memberName_ = (memberId: string) => memberById.get(memberId)?.name ?? '—'++ // ── 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])++ // KPIs roll up across currencies using each line's+ // amount_in_default_currency (FX-converted server-side). Filtering by+ // a single currency would otherwise hide debts in another currency+ // — e.g. a EUR-only line wouldn't show up for a USD-default group.+ const owedToViewer = useMemo(() => {+ if (!balances) return 0+ if (isOwner) {+ return balances.lines+ .filter((l) => l.amount > 0)+ .reduce((s, l) => s + Number(l.amount_in_default_currency), 0)+ }+ if (!viewerMember) return 0+ return balances.lines+ .filter((l) => l.member_id === viewerMember.id && l.amount < 0)+ .reduce((s, l) => s + Math.abs(Number(l.amount_in_default_currency)), 0)+ }, [balances, isOwner, viewerMember])++ const viewerOwes = useMemo(() => {+ if (!balances) return 0+ if (isOwner) {+ return Math.abs(+ balances.lines+ .filter((l) => l.amount < 0)+ .reduce((s, l) => s + Number(l.amount_in_default_currency), 0),+ )+ }+ if (!viewerMember) return 0+ return balances.lines+ .filter((l) => l.member_id === viewerMember.id && l.amount > 0)+ .reduce((s, l) => s + Number(l.amount_in_default_currency), 0)+ }, [balances, isOwner, viewerMember])++ // Per-line breakdown for the two debt KPIs. Each row shows the other+ // party's name and the amount in its native currency — so a EUR line+ // stays "€100" instead of being lossy-rolled into the USD KPI total.+ const memberNameById = useMemo(() => {+ const map = new Map<string, string>()+ for (const m of group?.members ?? []) map.set(m.id, m.name)+ return map+ }, [group?.members])++ const owedToViewerBreakdown = useMemo<KpiBreakdownItem[]>(() => {+ if (!balances) return []+ if (isOwner) {+ return balances.lines+ .filter((l) => l.amount > 0)+ .map((l) => ({+ name: memberNameById.get(l.member_id) ?? '—',+ amountText: formatCurrency(Number(l.amount), l.currency, locale),+ }))+ }+ if (!viewerMember || !ownerMember) return []+ return balances.lines+ .filter((l) => l.member_id === viewerMember.id && l.amount < 0)+ .map((l) => ({+ name: ownerMember.name,+ amountText: formatCurrency(Math.abs(Number(l.amount)), l.currency, locale),+ }))+ }, [balances, isOwner, viewerMember, ownerMember, memberNameById, locale])++ const viewerOwesBreakdown = useMemo<KpiBreakdownItem[]>(() => {+ if (!balances) return []+ if (isOwner) {+ return balances.lines+ .filter((l) => l.amount < 0)+ .map((l) => ({+ name: memberNameById.get(l.member_id) ?? '—',+ amountText: formatCurrency(Math.abs(Number(l.amount)), l.currency, locale),+ }))+ }+ if (!viewerMember || !ownerMember) return []+ return balances.lines+ .filter((l) => l.member_id === viewerMember.id && l.amount > 0)+ .map((l) => ({+ name: ownerMember.name,+ amountText: formatCurrency(Number(l.amount), l.currency, locale),+ }))+ }, [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(locale, { month: 'short' }),+ total: Number(total.toFixed(2)),+ }))+ }, [groupTxs, locale])++ // 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.+ 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])++ const categoryBreakdownTotal = useMemo(+ () => categoryBreakdown.reduce((s, c) => s + c.total, 0),+ [categoryBreakdown],+ )++ if (loadingGroup) {+ return (+ <div className="space-y-4">+ <Skeleton className="h-12 w-64" />+ <Skeleton className="h-32 w-full" />+ <Skeleton className="h-32 w-full" />+ </div>+ )+ }+ if (!group) {+ return <div className="text-muted-foreground">{t('splitGroups.notFound')}</div>+ }++ return (+ <div className="space-y-4">+ <PageHeader+ section={t('splitGroups.section')}+ title={group.name}+ action={+ <div className="flex items-center gap-2">+ {!isOwner && (+ <span className="text-xs bg-muted text-muted-foreground px-2 py-1 rounded-full">+ {t('splitGroups.sharedWithYou')}+ </span>+ )}+ <Button variant="outline" onClick={() => navigate('/groups')}>+ <ArrowLeft size={14} className="mr-1" />+ {t('common.back')}+ </Button>+ </div>+ }+ />++ {/* KPI row */}+ <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)}+ icon={Wallet}+ />+ <KpiCard+ label={t(isOwner ? 'splitGroups.kpiOwedToYou' : 'splitGroups.kpiOwedToYouAsMember')}+ value={formatCurrency(owedToViewer, groupCurrency, locale)}+ icon={TrendingUp}+ tone={owedToViewer > 0 ? 'positive' : 'neutral'}+ breakdown={owedToViewerBreakdown}+ />+ <KpiCard+ label={t('splitGroups.kpiYouOwe')}+ value={formatCurrency(viewerOwes, groupCurrency, locale)}+ icon={TrendingDown}+ tone={viewerOwes > 0 ? 'negative' : 'neutral'}+ breakdown={viewerOwesBreakdown}+ />+ </div>++ {/* Spending trend (compact) */}+ {monthlyData.length > 1 && (+ <SectionCard>+ <SectionHeader+ title={t('splitGroups.spendingTrend')}+ description={t('splitGroups.spendingTrendHint')}+ />+ <div className="px-2 py-3">+ <ResponsiveContainer width="100%" height={120}>+ <BarChart data={monthlyData}>+ <XAxis+ dataKey="month"+ tick={{ fontSize: 11 }}+ axisLine={false}+ tickLine={false}+ />+ <Tooltip+ cursor={{ fill: 'var(--muted)' }}+ contentStyle={{+ fontSize: 12,+ borderRadius: 8,+ border: '1px solid var(--border)',+ background: 'var(--card)',+ }}+ formatter={(v) => formatCurrency(Number(v ?? 0), groupCurrency, locale)}+ />+ <Bar dataKey="total" fill={group.color} radius={[4, 4, 0, 0]} />+ </BarChart>+ </ResponsiveContainer>+ </div>+ </SectionCard>+ )}++ {/* Category distribution — single horizontal stacked bar split+ by category, with a legend showing absolute and % per slice. */}+ {categoryBreakdownTotal > 0 && (+ <SectionCard>+ <SectionHeader+ title={t('splitGroups.byCategory')}+ description={t('splitGroups.byCategoryHint')}+ />+ <div className="px-4 py-3 space-y-3">+ <div className="flex h-3 w-full overflow-hidden rounded-full bg-muted">+ {categoryBreakdown.map((c) => {+ const pct = (c.total / categoryBreakdownTotal) * 100+ return (+ <div+ key={c.id}+ style={{ width: `${pct}%`, backgroundColor: c.color }}+ title={`${c.name} · ${formatCurrency(c.total, groupCurrency, locale)} (${pct.toFixed(1)}%)`}+ />+ )+ })}+ </div>+ <ul className="grid grid-cols-1 sm:grid-cols-2 gap-x-4 gap-y-1 text-xs">+ {categoryBreakdown.map((c) => {+ const pct = (c.total / categoryBreakdownTotal) * 100+ return (+ <li key={c.id} className="flex items-center justify-between gap-2">+ <span className="flex items-center gap-2 min-w-0">+ <span+ className="h-2.5 w-2.5 rounded-full shrink-0"+ style={{ backgroundColor: c.color }}+ />+ <span className="truncate">{c.name}</span>+ </span>+ <span className="tabular-nums whitespace-nowrap text-muted-foreground">+ {formatCurrency(c.total, groupCurrency, locale)} · {pct.toFixed(0)}%+ </span>+ </li>+ )+ })}+ </ul>+ </div>+ </SectionCard>+ )}++ {/* 2×2 grid: members + balances on top, transactions + settlements below */}+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-3 sm:gap-4">+ {/* Members */}+ <SectionCard>+ <SectionHeader+ title={t('splitGroups.members')}+ action={+ isOwner ? (+ <Button size="sm" className="gap-1.5 h-8" onClick={openCreateMember}>+ <UserPlus size={13} />+ {t('splitGroups.addMember')}+ </Button>+ ) : undefined+ }+ />+ {group.members.length === 0 ? (+ <div className="text-center py-8 text-muted-foreground text-sm">+ {t('splitGroups.noMembers')}+ </div>+ ) : (+ <ul className="divide-y divide-border">+ {group.members.map((member) => (+ <li key={member.id} className="flex items-center justify-between px-4 py-3">+ <div>+ <div className="flex items-center gap-2">+ <span className="text-sm font-medium">{member.name}</span>+ {/* "(you)" only marks the actual viewer. is_self+ identifies the group owner/payer; for non-owner+ viewers we show that as "(owner)" instead so+ the badge isn't misleading. */}+ {viewerMember?.id === member.id ? (+ <span className="text-xs bg-primary/10 text-primary px-2 py-0.5 rounded-full">+ {t('splitGroups.you')}+ </span>+ ) : member.is_self && isOwner ? (+ <span className="text-xs bg-primary/10 text-primary px-2 py-0.5 rounded-full">+ {t('splitGroups.you')}+ </span>+ ) : member.is_self ? (+ <span className="text-xs bg-muted text-muted-foreground px-2 py-0.5 rounded-full">+ {t('splitGroups.ownerBadge')}+ </span>+ ) : null}+ </div>+ {member.email && (+ <p className="text-xs text-muted-foreground inline-flex items-center gap-1">+ {member.linked_user_id && <Link2 size={10} />}+ {member.email}+ </p>+ )}+ </div>+ {isOwner && (+ <Button variant="ghost" size="sm" onClick={() => openEditMember(member)}>+ {t('common.edit')}+ </Button>+ )}+ </li>+ ))}+ </ul>+ )}+ </SectionCard>++ {/* Balances */}+ <SectionCard>+ <SectionHeader+ title={t('splitGroups.balances')}+ description={t('splitGroups.balancesHint')}+ />+ {balances && balances.lines.length > 0 ? (+ <ul className="divide-y divide-border">+ {balances.lines.map((line, idx) => {+ const positive = line.amount > 0+ // Reframe the line per viewer:+ // - Owner sees "X owes you" / "you owe X" (their direct relationship).+ // - A linked member sees their own line as "you owe / owes you {owner}",+ // and other lines as "{name} owes / is owed by {owner}".+ const ownerName = ownerMember?.name ?? '—'+ const otherName = memberName_(line.member_id)+ const isViewerLine = viewerMember?.id === line.member_id+ const label = isOwner+ ? positive+ ? t('splitGroups.owesYou', { name: otherName })+ : t('splitGroups.youOwe', { name: otherName })+ : isViewerLine+ ? positive+ ? t('splitGroups.youOwe', { name: ownerName })+ : t('splitGroups.ownerOwesYou', { name: ownerName })+ : positive+ ? t('splitGroups.thirdPartyOwes', { name: otherName, owner: ownerName })+ : t('splitGroups.thirdPartyOwed', { name: otherName, owner: ownerName })+ return (+ <li+ key={`${line.member_id}-${line.currency}-${idx}`}+ className="flex items-center justify-between px-4 py-3"+ >+ <div className="text-sm">{label}</div>+ <div className="flex items-center gap-3">+ <span+ className={`text-sm font-semibold tabular-nums ${+ positive ? 'text-emerald-600' : 'text-rose-500'+ }`}+ >+ {formatCurrency(Math.abs(line.amount), line.currency, locale)}+ </span>+ {(() => {+ // Show "Acertar" if the viewer can act on this line:+ // - Owner can act on any line+ // - Linked member can only act on their own debt line+ // (positive amount = they owe the owner)+ const canActLinked = !isOwner && isViewerLine && positive+ if (!isOwner && !canActLinked) return null+ return (+ <Button+ variant="outline"+ size="sm"+ onClick={() => {+ if (!balances.self_member_id) return+ if (positive) {+ // Member owes the owner → from = member, to = owner+ openSettleUp(line.member_id, balances.self_member_id, Math.abs(line.amount), line.currency)+ } else {+ // Owner owes the member → from = owner, to = member+ openSettleUp(balances.self_member_id, line.member_id, Math.abs(line.amount), line.currency)+ }+ }}+ >+ {canActLinked ? t('splitGroups.payNow') : t('splitGroups.settleUp')}+ </Button>+ )+ })()}+ </div>+ </li>+ )+ })}+ </ul>+ ) : (+ <div className="text-center py-6 text-muted-foreground text-sm">+ {t('splitGroups.allSettled')}+ </div>+ )}+ </SectionCard>++ {/* Recent transactions */}+ <SectionCard>+ <SectionHeader+ title={t('splitGroups.recentTransactions')}+ description={t('splitGroups.recentTransactionsHint')}+ action={+ groupTxs && groupTxs.length > 0 ? (+ <Button+ variant="ghost"+ size="sm"+ className="gap-1 h-8 text-xs"+ onClick={() => navigate(`/transactions?group_id=${groupId}`)}+ >+ {t('splitGroups.viewAllTransactions')}+ <ArrowRight size={12} />+ </Button>+ ) : undefined+ }+ />+ {!groupTxs ? (+ <div className="p-4 space-y-2">+ <Skeleton className="h-10 w-full" />+ <Skeleton className="h-10 w-full" />+ </div>+ ) : groupTxs.length === 0 ? (+ <div className="text-center py-8 text-muted-foreground text-sm flex flex-col items-center gap-2">+ <Receipt size={20} className="opacity-50" />+ {t('splitGroups.noTransactions')}+ </div>+ ) : (+ <ul className="divide-y divide-border">+ {groupTxs.slice(0, 8).map((tx) => (+ <li+ key={tx.id}+ className="flex items-center gap-3 px-4 py-3 hover:bg-muted cursor-pointer transition-colors"+ onClick={() => navigate(`/transactions?group_id=${groupId}&highlight=${tx.id}`)}+ >+ <CategoryIcon+ icon={tx.category?.icon}+ color={tx.category?.color}+ size="md"+ />+ <div className="flex-1 min-w-0">+ <p className="text-sm font-medium text-foreground truncate">+ {tx.description}+ </p>+ <p className="text-xs text-muted-foreground">+ {new Date(tx.date + 'T00:00:00').toLocaleDateString(locale)}+ {tx.category?.name ? ` · ${tx.category.name}` : ''}+ {tx.splits && tx.splits.length > 0+ ? ` · ${t('splitGroups.splitWays', { count: tx.splits.length })}`+ : ''}+ </p>+ </div>+ <span+ className={`text-sm font-semibold tabular-nums ml-3 ${+ tx.type === 'debit' ? 'text-rose-500' : 'text-emerald-600'+ }`}+ >+ {formatCurrency(Number(tx.amount), tx.currency, locale)}+ </span>+ </li>+ ))}+ </ul>+ )}+ </SectionCard>++ {/* Settlements */}+ <SectionCard>+ <SectionHeader+ title={t('splitGroups.settlements')}+ action={+ isOwner ? (+ <Button+ size="sm"+ variant="outline"+ className="gap-1.5 h-8"+ onClick={() => openSettleUp()}+ >+ {t('splitGroups.recordSettlement')}+ </Button>+ ) : undefined+ }+ />+ {settlements && settlements.length > 0 ? (+ <ul className="divide-y divide-border">+ {settlements.map((s: GroupSettlement) => (+ <li key={s.id} className="flex items-center justify-between px-4 py-3">+ <div className="flex-1 min-w-0">+ <div className="text-sm flex items-center gap-1.5">+ <span className="font-medium">{memberName_(s.from_member_id)}</span>+ <ArrowRight size={12} className="text-muted-foreground" />+ <span className="font-medium">{memberName_(s.to_member_id)}</span>+ </div>+ <p className="text-xs text-muted-foreground mt-0.5">+ {new Date(s.date + 'T00:00:00').toLocaleDateString(locale)}+ {s.notes ? ` · ${s.notes}` : ''}+ </p>+ </div>+ <div className="flex items-center gap-3">+ <span className="text-sm font-semibold tabular-nums">+ {formatCurrency(s.amount, s.currency, locale)}+ </span>+ {isOwner && (+ <Button+ variant="ghost"+ size="sm"+ onClick={() => deleteSettlementMutation.mutate(s.id)}+ >+ <Trash2 size={14} />+ </Button>+ )}+ </div>+ </li>+ ))}+ </ul>+ ) : (+ <div className="text-center py-6 text-muted-foreground text-sm">+ {t('splitGroups.noSettlements')}+ </div>+ )}+ </SectionCard>+ </div>++ {/* Member dialog */}+ <Dialog open={memberDialogOpen} onOpenChange={setMemberDialogOpen}>+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle>+ {editingMember ? t('splitGroups.editMember') : t('splitGroups.addMember')}+ </DialogTitle>+ </DialogHeader>+ <div className="space-y-4">+ {/* Pick an existing Securo user, or leave as "non-user" to+ add someone without an account (the most common case for+ roommates/relatives who don't use the app yet). When a+ user is picked, name+email come from their account and+ the inputs are locked — switch back to "Sem vínculo" to+ edit them by hand. */}+ <div className="space-y-2">+ <Label>{t('splitGroups.linkedUser')}</Label>+ <select+ className="w-full border border-border rounded-md px-3 py-2 text-sm bg-background h-9 focus:outline-none focus-visible:ring-ring/30 focus-visible:ring-[2px]"+ value={memberLinkedUserId ?? ''}+ onChange={(e) => {+ const id = e.target.value || null+ setMemberLinkedUserId(id)+ if (id) {+ const picked = userDirectory?.find((u) => u.id === id)+ if (picked) {+ // Always reflect the currently picked user — the+ // inputs are locked, so the source of truth is+ // whatever account is selected here.+ setMemberEmail(picked.email)+ setMemberName(picked.email.split('@')[0])+ }+ }+ }}+ >+ <option value="">{t('splitGroups.linkedUserNone')}</option>+ {(userDirectory ?? []).map((u) => (+ <option key={u.id} value={u.id}>+ {u.email}+ {u.id === user?.id ? ` (${t('splitGroups.you')})` : ''}+ </option>+ ))}+ </select>+ <p className="text-xs text-muted-foreground">+ {t('splitGroups.linkedUserHint')}+ </p>+ </div>+ <div className="space-y-2">+ <Label>{t('splitGroups.memberName')}</Label>+ <Input+ value={memberName}+ onChange={(e) => setMemberName(e.target.value)}+ disabled={memberLinkedUserId !== null}+ />+ </div>+ <div className="space-y-2">+ <Label>{t('splitGroups.memberEmail')}</Label>+ <Input+ type="email"+ value={memberEmail}+ onChange={(e) => setMemberEmail(e.target.value)}+ disabled={memberLinkedUserId !== null}+ />+ {memberLinkedUserId !== null ? (+ <p className="text-xs text-emerald-600 inline-flex items-center gap-1">+ <Link2 size={11} />+ {t('splitGroups.willLinkToUser', { email: memberEmail })}+ </p>+ ) : lookupResult ? (+ <p className="text-xs text-emerald-600 inline-flex items-center gap-1">+ <Link2 size={11} />+ {t('splitGroups.willLinkToUser', { email: lookupResult.email })}+ </p>+ ) : (+ <p className="text-xs text-muted-foreground">+ {t('splitGroups.memberEmailHint')}+ </p>+ )}+ </div>+ </div>+ <DialogFooter className={editingMember ? 'flex justify-between sm:justify-between' : ''}>+ {editingMember && (+ <Button+ variant="destructive"+ onClick={() => deleteMemberMutation.mutate(editingMember.id)}+ disabled={deleteMemberMutation.isPending}+ >+ <Trash2 size={14} className="mr-1" />+ {t('common.delete')}+ </Button>+ )}+ <div className="flex gap-2">+ <Button variant="outline" onClick={() => setMemberDialogOpen(false)}>+ {t('common.cancel')}+ </Button>+ <Button+ onClick={saveMember}+ disabled={!memberName.trim() || memberMutation.isPending}+ >+ {t('common.save')}+ </Button>+ </div>+ </DialogFooter>+ </DialogContent>+ </Dialog>++ {/* Settle dialog */}+ <Dialog open={settleOpen} onOpenChange={setSettleOpen}>+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle>{t('splitGroups.recordSettlement')}</DialogTitle>+ </DialogHeader>+ {(() => {+ const myMemberId = viewerMember?.id ?? (isOwner ? ownerMember?.id : null)+ const viewerIsPayer = !!myMemberId && settleFrom === myMemberId+ return (+ <div className="space-y-4">+ <div className="space-y-2">+ <Label>{t('splitGroups.from')}</Label>+ <select+ className="w-full border border-border rounded-md px-3 py-2 text-sm bg-background"+ value={settleFrom}+ onChange={(e) => {+ setSettleFrom(e.target.value)+ // Reset the account-side toggle: it's only meaningful+ // when the viewer is the payer.+ setSettleAffectAccount(false)+ setSettleAccountId('')+ }}+ >+ <option value="">{t('splitGroups.selectMember')}</option>+ {group.members.map((m) => (+ <option key={m.id} value={m.id}>+ {m.name}+ </option>+ ))}+ </select>+ </div>+ <div className="space-y-2">+ <Label>{t('splitGroups.to')}</Label>+ <select+ className="w-full border border-border rounded-md px-3 py-2 text-sm bg-background"+ value={settleTo}+ onChange={(e) => setSettleTo(e.target.value)}+ >+ <option value="">{t('splitGroups.selectMember')}</option>+ {group.members.map((m) => (+ <option key={m.id} value={m.id}>+ {m.name}+ </option>+ ))}+ </select>+ </div>+ <div className="grid grid-cols-3 gap-3">+ <div className="space-y-2 col-span-2">+ <Label>{t('splitGroups.amount')}</Label>+ <Input+ type="number"+ step="0.01"+ value={settleAmount}+ onChange={(e) => setSettleAmount(e.target.value)}+ />+ </div>+ <div className="space-y-2">+ <Label>{t('splitGroups.currency')}</Label>+ <Input+ value={settleCurrency}+ maxLength={3}+ onChange={(e) => setSettleCurrency(e.target.value.toUpperCase())}+ />+ </div>+ </div>+ <div className="space-y-2">+ <Label>{t('splitGroups.date')}</Label>+ <Input+ type="date"+ value={settleDate}+ onChange={(e) => setSettleDate(e.target.value)}+ />+ </div>+ <div className="space-y-2">+ <Label>{t('splitGroups.notes')}</Label>+ <textarea+ className="w-full border border-input rounded-md px-3 py-2 text-sm bg-background resize-none"+ rows={2}+ value={settleNotes}+ onChange={(e) => setSettleNotes(e.target.value)}+ />+ </div>++ {/* Optional account integration — only relevant when the+ viewer is the *payer* of this settlement. In that case+ we can write a real debit to one of their accounts. The+ receiver's mirror credit is created automatically by the+ backend when the receiver is a Securo user, so we don't+ expose that path in the UI here. */}+ {viewerIsPayer && (+ <div className="space-y-2 pt-2 border-t border-border">+ <label className="text-sm font-medium inline-flex items-center gap-2 cursor-pointer">+ <input+ type="checkbox"+ checked={settleAffectAccount}+ onChange={(e) => setSettleAffectAccount(e.target.checked)}+ className="h-4 w-4 rounded border-border accent-primary"+ />+ {t('splitGroups.affectAccount')}+ </label>+ {settleAffectAccount && (+ <div className="space-y-1">+ <select+ className="w-full border border-border rounded-md px-3 py-2 text-sm bg-background"+ value={settleAccountId}+ onChange={(e) => setSettleAccountId(e.target.value)}+ >+ <option value="">{t('splitGroups.selectAccount')}</option>+ {(accountsList ?? []).map((a) => (+ <option key={a.id} value={a.id}>+ {a.display_name || a.name}+ </option>+ ))}+ </select>+ <p className="text-xs text-muted-foreground">+ {t('splitGroups.affectAccountHint')}+ </p>+ </div>+ )}+ </div>+ )}+ </div>+ )+ })()}+ <DialogFooter>+ <Button variant="outline" onClick={() => setSettleOpen(false)}>+ {t('common.cancel')}+ </Button>+ <Button+ onClick={saveSettlement}+ disabled={+ !settleFrom ||+ !settleTo ||+ settleFrom === settleTo ||+ !settleAmount ||+ (settleAffectAccount && !settleAccountId) ||+ settlementMutation.isPending+ }+ >+ {t('common.save')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </div>+ )+}diff --git a/frontend/src/pages/groups.tsx b/frontend/src/pages/groups.tsxnew file mode 100644index 00000000..633a156f--- /dev/null+++ b/frontend/src/pages/groups.tsx@@ -0,0 +1,327 @@+import { useState } from 'react'+import { useTranslation } from 'react-i18next'+import { useNavigate } from 'react-router-dom'+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { toast } from 'sonner'++import { groups as groupsApi, currencies as currenciesApi, type GroupCreatePayload } from '@/lib/api'+import { useAuth } from '@/contexts/auth-context'+import { Button } from '@/components/ui/button'+import { Input } from '@/components/ui/input'+import { Label } from '@/components/ui/label'+import { Skeleton } from '@/components/ui/skeleton'+import {+ Dialog,+ DialogContent,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog'+import { PageHeader } from '@/components/page-header'+import { Archive, ChevronRight, Trash2, Users } from 'lucide-react'+import type { Group, GroupKind } from '@/types'++type StatusFilter = 'active' | 'archived' | 'all'++const KIND_OPTIONS: { value: GroupKind; tKey: string }[] = [+ { value: 'social', tKey: 'splitGroups.kind.social' },+ { value: 'cost_center', tKey: 'splitGroups.kind.cost_center' },+ { value: 'project', tKey: 'splitGroups.kind.project' },+ { value: 'client', tKey: 'splitGroups.kind.client' },+ { value: 'other', tKey: 'splitGroups.kind.other' },+]++export default function GroupsPage() {+ const { t } = useTranslation()+ const navigate = useNavigate()+ const queryClient = useQueryClient()+ const { user } = useAuth()+ const userCurrency = user?.preferences?.currency_display ?? 'USD'+ const [statusFilter, setStatusFilter] = useState<StatusFilter>('active')+ const [dialogOpen, setDialogOpen] = useState(false)+ const [editing, setEditing] = useState<Group | null>(null)+ const includeArchived = statusFilter !== 'active'++ const [name, setName] = useState('')+ const [kind, setKind] = useState<GroupKind>('social')+ const [defaultCurrency, setDefaultCurrency] = useState(userCurrency)+ const [notes, setNotes] = useState('')++ const { data: supportedCurrencies } = useQuery({+ queryKey: ['currencies'],+ queryFn: currenciesApi.list,+ staleTime: Infinity,+ })++ const { data: list, isLoading } = useQuery({+ queryKey: ['groups', { includeArchived }],+ queryFn: () => groupsApi.list(includeArchived),+ })++ const createMutation = useMutation({+ mutationFn: (payload: GroupCreatePayload) => groupsApi.create(payload),+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: ['groups'] })+ setDialogOpen(false)+ toast.success(t('splitGroups.created'))+ },+ onError: () => toast.error(t('common.error')),+ })++ const updateMutation = useMutation({+ mutationFn: ({ id, payload }: { id: string; payload: Partial<GroupCreatePayload> & { is_archived?: boolean } }) =>+ groupsApi.update(id, payload),+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: ['groups'] })+ setDialogOpen(false)+ setEditing(null)+ toast.success(t('splitGroups.updated'))+ },+ onError: () => toast.error(t('common.error')),+ })++ const deleteMutation = useMutation({+ mutationFn: (id: string) => groupsApi.delete(id),+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: ['groups'] })+ setDialogOpen(false)+ setEditing(null)+ toast.success(t('splitGroups.deleted'))+ },+ onError: (err: unknown) => {+ const detail =+ err && typeof err === 'object' && 'response' in err+ ? (err as { response?: { data?: { detail?: string } } }).response?.data?.detail+ : undefined+ toast.error(detail ?? t('common.error'))+ },+ })++ const openCreate = () => {+ setEditing(null)+ setName('')+ setKind('social')+ setDefaultCurrency(userCurrency)+ setNotes('')+ setDialogOpen(true)+ }++ const openEdit = (group: Group) => {+ setEditing(group)+ setName(group.name)+ setKind(group.kind)+ setDefaultCurrency(group.default_currency)+ setNotes(group.notes ?? '')+ setDialogOpen(true)+ }++ const handleSave = () => {+ const payload: GroupCreatePayload = {+ name: name.trim(),+ kind,+ default_currency: defaultCurrency,+ notes: notes.trim() || null,+ }+ if (editing) {+ updateMutation.mutate({ id: editing.id, payload })+ } else {+ createMutation.mutate(payload)+ }+ }++ const visibleGroups = (list ?? []).filter((g) =>+ statusFilter === 'active'+ ? !g.is_archived+ : statusFilter === 'archived'+ ? g.is_archived+ : true,+ )++ return (+ <div>+ <PageHeader+ section={t('splitGroups.section')}+ title={t('splitGroups.title')}+ action={+ <Button onClick={openCreate}>+ {t('splitGroups.add')}</Button>+ }+ />++ {/* Status filter — pill buttons matching goals.tsx */}+ <div className="flex items-center gap-2 mb-4">+ {(['active', 'archived', 'all'] as StatusFilter[]).map((s) => (+ <button+ key={s}+ onClick={() => setStatusFilter(s)}+ className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${+ statusFilter === s+ ? 'bg-primary text-primary-foreground'+ : 'bg-muted text-muted-foreground hover:text-foreground'+ }`}+ >+ {t(`splitGroups.filter.${s}`)}+ </button>+ ))}+ </div>++ <div className="bg-card rounded-xl border border-border shadow-sm overflow-hidden mb-4">+ {isLoading ? (+ <div className="p-6 space-y-3">+ {Array.from({ length: 3 }).map((_, i) => (+ <Skeleton key={i} className="h-14 w-full" />+ ))}+ </div>+ ) : visibleGroups.length === 0 ? (+ <div className="text-center py-16 text-muted-foreground">+ <Users size={32} className="mx-auto mb-2 opacity-50" />+ <p>{t('splitGroups.empty')}</p>+ <p className="text-xs mt-1">{t('splitGroups.emptyHint')}</p>+ </div>+ ) : (+ <ul className="divide-y divide-border">+ {visibleGroups.map((group) => (+ <li+ key={group.id}+ className="flex items-center gap-3 px-4 py-3.5 hover:bg-muted cursor-pointer transition-colors"+ onClick={() => navigate(`/groups/${group.id}`)}+ >+ {/* Avatar circle — colored using the group's `color` field */}+ <div+ className="h-10 w-10 rounded-full flex items-center justify-center shrink-0"+ style={{ backgroundColor: `${group.color}22`, color: group.color }}+ aria-hidden+ >+ <Users size={18} />+ </div>+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2 flex-wrap">+ <span className="text-sm font-semibold text-foreground truncate">{group.name}</span>+ <span className="text-xs bg-muted text-muted-foreground px-2 py-0.5 rounded-full">+ {t(`splitGroups.kind.${group.kind}`)}+ </span>+ {group.is_archived && (+ <span className="text-xs bg-amber-100 text-amber-800 dark:bg-amber-950 dark:text-amber-200 px-2 py-0.5 rounded-full inline-flex items-center gap-1">+ <Archive size={10} />+ {t('splitGroups.archived')}+ </span>+ )}+ {!group.is_owner && (+ <span className="text-xs bg-muted text-muted-foreground px-2 py-0.5 rounded-full">+ {t('splitGroups.sharedWithYou')}+ </span>+ )}+ </div>+ <p className="text-xs text-muted-foreground mt-0.5">+ {t('splitGroups.memberCount', { count: group.members.length })} · {group.default_currency}+ </p>+ </div>+ {group.is_owner && (+ <Button+ variant="ghost"+ size="sm"+ onClick={(e) => {+ e.stopPropagation()+ openEdit(group)+ }}+ >+ {t('common.edit')}+ </Button>+ )}+ <ChevronRight size={16} className="text-muted-foreground shrink-0" />+ </li>+ ))}+ </ul>+ )}+ </div>++ <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle>{editing ? t('splitGroups.edit') : t('splitGroups.add')}</DialogTitle>+ </DialogHeader>+ <div className="space-y-4">+ <div className="space-y-2">+ <Label>{t('splitGroups.name')}</Label>+ <Input value={name} onChange={(e) => setName(e.target.value)} />+ </div>+ <div className="space-y-2">+ <Label>{t('splitGroups.kindLabel')}</Label>+ <select+ className="w-full border border-border rounded-md px-3 py-2 text-sm bg-background"+ value={kind}+ onChange={(e) => setKind(e.target.value as GroupKind)}+ >+ {KIND_OPTIONS.map((opt) => (+ <option key={opt.value} value={opt.value}>+ {t(opt.tKey)}+ </option>+ ))}+ </select>+ <p className="text-xs text-muted-foreground">{t('splitGroups.kindHint')}</p>+ </div>+ <div className="space-y-2">+ <Label>{t('splitGroups.defaultCurrency')}</Label>+ <select+ className="w-full border border-border rounded-md px-3 py-2 text-sm bg-background h-9 focus:outline-none focus-visible:ring-ring/30 focus-visible:ring-[2px]"+ value={defaultCurrency}+ onChange={(e) => setDefaultCurrency(e.target.value)}+ >+ {(supportedCurrencies ?? [{ code: defaultCurrency, symbol: defaultCurrency, name: defaultCurrency, flag: '' }]).map((c) => (+ <option key={c.code} value={c.code}>{c.flag} {c.name}</option>+ ))}+ </select>+ </div>+ <div className="space-y-2">+ <Label>{t('splitGroups.notes')}</Label>+ <textarea+ className="w-full border border-input rounded-md px-3 py-2 text-sm bg-background resize-none"+ rows={2}+ value={notes}+ onChange={(e) => setNotes(e.target.value)}+ />+ </div>+ {editing && (+ <label className="text-sm text-muted-foreground inline-flex items-center gap-2 cursor-pointer">+ <input+ type="checkbox"+ checked={editing.is_archived}+ onChange={(e) =>+ updateMutation.mutate({+ id: editing.id,+ payload: { is_archived: e.target.checked },+ })+ }+ className="h-4 w-4 rounded border-border accent-primary"+ />+ {t('splitGroups.archived')}+ </label>+ )}+ </div>+ <DialogFooter className={editing ? 'flex justify-between sm:justify-between' : ''}>+ {editing && (+ <Button+ variant="destructive"+ onClick={() => deleteMutation.mutate(editing.id)}+ disabled={deleteMutation.isPending}+ >+ <Trash2 size={14} className="mr-1" />+ {t('common.delete')}+ </Button>+ )}+ <div className="flex gap-2">+ <Button variant="outline" onClick={() => setDialogOpen(false)}>+ {t('common.cancel')}+ </Button>+ <Button+ onClick={handleSave}+ disabled={!name.trim() || createMutation.isPending || updateMutation.isPending}+ >+ {t('common.save')}+ </Button>+ </div>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </div>+ )+}diff --git a/frontend/src/pages/transactions.tsx b/frontend/src/pages/transactions.tsxindex e2892ede..537c21e2 100644--- a/frontend/src/pages/transactions.tsx+++ b/frontend/src/pages/transactions.tsx@@ -1,9 +1,9 @@import { useState, useMemo, useEffect, useRef } from 'react'import { getAccountName } from '@/lib/account-utils'-import { useSearchParams } from 'react-router-dom'+import { useNavigate, 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, admin } from '@/lib/api'+import { transactions, categories as categoriesApi, accounts as accountsApi, recurring, payees as payeesApi, admin, groups as groupsApi } from '@/lib/api'import { invalidateFinancialQueries } from '@/lib/invalidate-queries'import { toast } from 'sonner'import { Button } from '@/components/ui/button'@@ -56,6 +56,7 @@ function parseHashtags(notes: string | null): string[] {export default function TransactionsPage() {const { t, i18n } = useTranslation()const [searchParams] = useSearchParams()+ const navigate = useNavigate()const locale = i18n.language === 'en' ? 'en-US' : i18n.languageconst { mask } = usePrivacyMode()const { user } = useAuth()@@ -79,8 +80,29 @@ 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 [filterGroupId, setFilterGroupId] = useState<string>(searchParams.get('group_id') ?? '')const [tagFilters, setTagFilters] = useState<string[]>([])+ // When the page is opened with a `group_id`, fetch its name so the+ // active-filter chip is recognizable rather than a raw uuid.+ const { data: filterGroup } = useQuery({+ queryKey: ['groups', filterGroupId],+ queryFn: () => groupsApi.get(filterGroupId),+ enabled: !!filterGroupId,+ })++ // Used to resolve the group name on shared transaction rows.+ const { data: allGroups } = useQuery({+ queryKey: ['groups', 'all'],+ queryFn: () => groupsApi.list(true),+ staleTime: 60_000,+ })+ const groupNameById = useMemo(() => {+ const map = new Map<string, string>()+ for (const g of allGroups ?? []) map.set(g.id, g.name)+ return map+ }, [allGroups])+const addTagFilter = (tag: string) => {const normalized = tag.startsWith('#') ? tag : `#${tag}`setTagFilters(prev => (prev.includes(normalized) ? prev : [...prev, normalized]))@@ -114,6 +136,7 @@ export default function TransactionsPage() {const tags = searchParams.get('tags');setTagFilters(tags ? tags.split(',') : []);setFilterPayee(searchParams.get('payee_id') ?? '')+ setFilterGroupId(searchParams.get('group_id') ?? '')const categories = searchParams.get('category_id');setFilterCategoryIds(categories ? categories.split(',') : []);setFilterUncategorized(searchParams.get('uncategorized') === '1');@@ -132,6 +155,7 @@ export default function TransactionsPage() {['q', searchQuery],['tags', tagFilters.join(',')],['payee_id', filterPayee],+ ['group_id', filterGroupId],['category_id', filterCategoryIds.join(',')],['uncategorized', filterUncategorized ? '1' : ''],['account_id', filterAccountIds.join(',')],@@ -149,6 +173,7 @@ export default function TransactionsPage() {searchQuery,tagFilters,filterPayee,+ filterGroupId,filterCategoryIds,filterUncategorized,filterAccountIds,@@ -193,7 +218,7 @@ export default function TransactionsPage() {}, [highlightId, searchQuery, filterPayee, filterCategoryIds, page])const { data, isLoading } = useQuery({- queryKey: ['transactions', page, filterAccountIds, filterCategoryIds, filterUncategorized, filterPayee, filterFrom, filterTo, searchQuery, tagFilters],+ queryKey: ['transactions', page, filterAccountIds, filterCategoryIds, filterUncategorized, filterPayee, filterGroupId, filterFrom, filterTo, searchQuery, tagFilters],queryFn: () =>transactions.list({page,@@ -201,6 +226,7 @@ export default function TransactionsPage() {account_ids: filterAccountIds.length > 0 ? filterAccountIds : undefined,category_ids: filterCategoryIds.length > 0 ? filterCategoryIds : undefined,payee_id: filterPayee || undefined,+ group_id: filterGroupId || undefined,uncategorized: filterUncategorized ? true : undefined,from: filterFrom || undefined,to: filterTo || undefined,@@ -547,6 +573,8 @@ export default function TransactionsPage() {onUncategorizedChange={(v) => { setFilterUncategorized(v); setPage(1) }}filterPayee={filterPayee}onPayeeChange={(v) => { setFilterPayee(v); setPage(1) }}+ filterGroupId={filterGroupId}+ onGroupIdChange={(v) => { setFilterGroupId(v); setPage(1) }}filterFrom={filterFrom}filterTo={filterTo}onDateRangeChange={(from, to) => { setFilterFrom(from); setFilterTo(to); setPage(1) }}@@ -557,6 +585,7 @@ export default function TransactionsPage() {setFilterCategoryIds([])setFilterUncategorized(false)setFilterPayee('')+ setFilterGroupId('')setSearchInput('')setSearchQuery('')clearTagFilters()@@ -565,7 +594,22 @@ export default function TransactionsPage() {accounts={accountsList ?? []}categories={categoriesList ?? []}payees={payeesList ?? []}+ groups={allGroups ?? []}/>+ {filterGroupId && (+ <div className="mb-4 flex flex-wrap items-center gap-1.5">+ <span 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">+ {t('splitGroups.title')}: {filterGroup?.name ?? '…'}+ <button+ onClick={() => { setFilterGroupId(''); setPage(1) }}+ className="ml-0.5 text-primary/60 hover:text-primary"+ aria-label="Clear group filter"+ >+ ×+ </button>+ </span>+ </div>+ )}{tagFilters.length > 0 && (<div className="mb-4 flex flex-wrap items-center gap-1.5">{tagFilters.map(tag => (@@ -624,17 +668,32 @@ export default function TransactionsPage() {<TableRowkey={tx.id}ref={tx.id === highlightId ? highlightedRowRef : undefined}- className={`cursor-pointer hover:bg-muted border-b border-border last:border-0 ${selectedIds.has(tx.id) ? 'bg-primary/5' : ''}`}- onClick={() => { setEditingTx(tx); setDialogOpen(true) }}+ className={`hover:bg-muted border-b border-border last:border-0 ${+ selectedIds.has(tx.id) ? 'bg-primary/5' : ''+ } ${tx.is_shared ? 'cursor-default' : 'cursor-pointer'}`}+ onClick={() => {+ if (tx.is_shared) {+ // Owned by another user — view in the group context instead.+ if (tx.group_id) navigate(`/groups/${tx.group_id}`)+ return+ }+ setEditingTx(tx)+ setDialogOpen(true)+ }}><TableCell className="py-2.5 pl-4 pr-0 w-[40px]">- <input- type="checkbox"- checked={selectedIds.has(tx.id)}- onChange={() => toggleSelect(tx.id)}- onClick={(e) => e.stopPropagation()}- className="h-4 w-4 rounded border-border accent-primary cursor-pointer"- />+ {/* Bulk operations are scoped to user.id so they+ silently skip shared rows — hide the checkbox+ on those to avoid the dead-end UX. */}+ {!tx.is_shared && (+ <input+ type="checkbox"+ checked={selectedIds.has(tx.id)}+ onChange={() => toggleSelect(tx.id)}+ onClick={(e) => e.stopPropagation()}+ className="h-4 w-4 rounded border-border accent-primary cursor-pointer"+ />+ )}</TableCell><TableCell className="py-2.5 pl-2 max-w-0"><div className="flex items-center gap-2 md:gap-3">@@ -642,6 +701,21 @@ export default function TransactionsPage() {<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" />@@ -707,9 +781,48 @@ export default function TransactionsPage() {)}</TableCell><TableCell className="py-2.5 pr-3 md:pr-5 text-right">- <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(Number(tx.amount)), tx.currency, locale)}`)}- </span>+ {(() => {+ // 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 && (diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.tsindex ebc4cfff..dd5c8447 100644--- a/frontend/src/types/index.ts+++ b/frontend/src/types/index.ts@@ -154,6 +154,100 @@ export interface Transaction {// available, cycle math otherwise). Setting it forces the tx into the// bill whose due_date matches.effective_bill_date: string | null+ splits: TransactionSplit[]+ // Shared-transaction view fields. Set per-request when the viewer+ // is a linked split member but not the owner. Render `viewer_share`+ // as the amount and treat the row as read-only — editing belongs+ // to the parent's owner.+ is_shared?: boolean+ viewer_share?: number | null+ group_id?: string | null+ // Display name of the parent's owner (the person who actually paid).+ // Derived per-request from the group's `is_self` member.+ parent_owner_name?: string | null+}++export type ShareType = 'equal' | 'exact' | 'percent'++export interface TransactionSplit {+ id: string+ transaction_id: string+ group_member_id: string+ share_amount: number+ share_type: string+ share_pct: number | null+ notes: string | null+ created_at: string+}++export interface TransactionSplitInput {+ group_member_id: string+ share_amount?: number | null+ share_pct?: number | null+ notes?: string | null+}++export interface TransactionSplitsInput {+ share_type: ShareType+ splits: TransactionSplitInput[]+}++export type GroupKind = 'social' | 'cost_center' | 'project' | 'client' | 'other'++export interface Group {+ id: string+ user_id: string+ name: string+ kind: GroupKind+ default_currency: string+ icon: string+ color: string+ is_archived: boolean+ // Derived server-side per request. False = the current user is a+ // linked member, not the owner — UI should hide edit affordances.+ is_owner: boolean+ notes: string | null+ created_at: string+ members: GroupMember[]+}++export interface GroupMember {+ id: string+ group_id: string+ name: string+ linked_user_id: string | null+ email: string | null+ is_self: boolean+ created_at: string+}++export interface GroupSettlement {+ id: string+ group_id: string+ from_member_id: string+ to_member_id: string+ amount: number+ currency: string+ date: string+ transaction_id: string | null+ notes: string | null+ created_at: string+}++export interface GroupBalanceLine {+ member_id: string+ currency: string+ // Positive = member owes the owner. Negative = owner owes member.+ amount: number+ // FX-converted to the group's default currency for cross-currency rollups.+ amount_in_default_currency: number+}++export interface GroupBalances {+ group_id: string+ self_member_id: string | null+ default_currency: string+ lines: GroupBalanceLine[]}export interface Payee {@@ -258,6 +352,10 @@ export interface DashboardSummary {assets_value: Record<string, number>assets_value_primary: numberprimary_currency: string+ // Net pending balance from group splits in primary currency.+ // Negative = net liability, positive = net receivable. Already+ // accounts for partial settlements.+ pending_shares_net: number}export interface SpendingByCategory {