Skip to content

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

refactor(backend): fix typing across the backend (models, services, APIs, migrations) (#502)

Pedro Magalhãesd4cc95073e19
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index c5a8c26a..c1ffa905 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -61,6 +61,10 @@ jobs:
if: steps.backend-changes.outputs.run_backend == 'true'
run: ruff check .
+ - name: Type check with ty
+ if: steps.backend-changes.outputs.run_backend == 'true'
+ run: ty check .
+
- name: Run tests with coverage
if: steps.backend-changes.outputs.run_backend == 'true'
run: |
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
new file mode 100644
index 00000000..883cb56f
--- /dev/null
+++ b/.pre-commit-config.yaml
@@ -0,0 +1,31 @@
+# Runs the same backend checks as CI, before you push. Optional.
+#
+# cd backend && pip install -e ".[dev]" # installs ruff + ty
+# prek install # or: pip install pre-commit && pre-commit install
+#
+# Run by hand: prek run --all-files
+#
+# The hooks call the ruff and ty from backend/.[dev], so they always match the
+# versions CI uses. If ty reports errors CI doesn't, your venv is behind
+# pyproject.toml — re-run the install above.
+
+repos:
+ - repo: local
+ hooks:
+ - id: ruff
+ name: ruff (backend)
+ entry: bash -c 'cd backend && ruff check .'
+ language: system
+ types: [python]
+ files: ^backend/
+ pass_filenames: false
+
+ - id: ty
+ name: ty (backend)
+ entry: bash -c 'cd backend && ty check .'
+ language: system
+ types: [python]
+ files: ^backend/
+ # Type errors propagate: editing b.py can break a.py, so check the
+ # whole project rather than just the staged files.
+ pass_filenames: false
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 442d97d8..0bfd4aa6 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -59,6 +59,22 @@ The same applies to issues. An issue produced by pointing a model at the reposit
5. Commit with a clear message (see below)
6. Push your branch and open a Pull Request
+Optional but recommended, so you catch lint and type errors before CI does:
+
+```bash
+prek install # once, from the repo root
+# or, if you prefer the Python original:
+pip install pre-commit && pre-commit install
+```
+
+This runs `ruff check` and `ty check` on the backend whenever you commit a
+`backend/*.py` file. Both read their config from `backend/pyproject.toml`, so
+local and CI stay in sync.
+
+[prek](https://github.com/j178/prek) is a drop-in replacement for pre-commit:
+same `.pre-commit-config.yaml`, but a single binary with no Python bootstrap.
+Either works.
+
## Commit Messages
Use clear, descriptive commit messages:
@@ -79,6 +95,10 @@ pytest
# Backend tests with coverage
pytest --cov=app --cov-report=term-missing
+# Backend lint + type check (same commands CI runs)
+ruff check .
+ty check .
+
# Frontend lint
cd frontend && npm run lint
diff --git a/backend/alembic/versions/022_goals.py b/backend/alembic/versions/022_goals.py
index e7a4a8da..df3baf19 100644
--- a/backend/alembic/versions/022_goals.py
+++ b/backend/alembic/versions/022_goals.py
@@ -9,6 +9,7 @@ from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
+from sqlalchemy.dialects import postgresql
revision: str = "022"
down_revision: Union[str, None] = "021"
@@ -19,8 +20,8 @@ depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
op.create_table(
"goals",
- sa.Column("id", sa.dialects.postgresql.UUID(as_uuid=True), primary_key=True),
- sa.Column("user_id", sa.dialects.postgresql.UUID(as_uuid=True), sa.ForeignKey("users.id"), nullable=False),
+ sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True),
+ sa.Column("user_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("users.id"), nullable=False),
sa.Column("name", sa.String(255), nullable=False),
sa.Column("target_amount", sa.Numeric(precision=15, scale=2), nullable=False),
sa.Column("current_amount", sa.Numeric(precision=15, scale=2), nullable=False, server_default="0"),
@@ -29,7 +30,7 @@ def upgrade() -> None:
sa.Column("current_amount_primary", sa.Numeric(precision=15, scale=2), nullable=True),
sa.Column("target_date", sa.Date(), nullable=True),
sa.Column("tracking_type", sa.String(20), nullable=False, server_default="manual"),
- sa.Column("account_id", sa.dialects.postgresql.UUID(as_uuid=True), sa.ForeignKey("accounts.id"), nullable=True),
+ sa.Column("account_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("accounts.id"), nullable=True),
sa.Column("status", sa.String(20), nullable=False, server_default="active"),
sa.Column("icon", sa.String(50), nullable=True),
sa.Column("color", sa.String(7), nullable=True),
diff --git a/backend/alembic/versions/029_backfill_opening_balance_for_connected_accounts.py b/backend/alembic/versions/029_backfill_opening_balance_for_connected_accounts.py
index c14e01ec..1e679fc9 100644
--- a/backend/alembic/versions/029_backfill_opening_balance_for_connected_accounts.py
+++ b/backend/alembic/versions/029_backfill_opening_balance_for_connected_accounts.py
@@ -81,6 +81,8 @@ def upgrade() -> None:
),
{"acc_id": acc_id, "acc_currency": currency},
).fetchone()
+ if row is None:
+ continue
tx_sum = Decimal(str(row[0] or 0))
oldest_date = row[1]
diff --git a/backend/alembic/versions/052_add_workspaces.py b/backend/alembic/versions/052_add_workspaces.py
index d16eee9a..36f109af 100644
--- a/backend/alembic/versions/052_add_workspaces.py
+++ b/backend/alembic/versions/052_add_workspaces.py
@@ -25,6 +25,7 @@ visibility filtering — the query layer pivots to `workspace_id`.
from alembic import op
import sqlalchemy as sa
+from sqlalchemy.dialects import postgresql
revision = "052"
@@ -60,12 +61,12 @@ def upgrade() -> None:
# 1. workspaces
op.create_table(
"workspaces",
- sa.Column("id", sa.dialects.postgresql.UUID(as_uuid=True), primary_key=True),
+ sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True),
sa.Column("name", sa.String(100), nullable=False),
sa.Column("kind", sa.String(30), nullable=False, server_default="personal"),
sa.Column(
"created_by_user_id",
- sa.dialects.postgresql.UUID(as_uuid=True),
+ postgresql.UUID(as_uuid=True),
sa.ForeignKey("users.id", ondelete="SET NULL"),
nullable=True,
),
@@ -81,23 +82,23 @@ def upgrade() -> None:
# 2. workspace_members
op.create_table(
"workspace_members",
- sa.Column("id", sa.dialects.postgresql.UUID(as_uuid=True), primary_key=True),
+ sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True),
sa.Column(
"workspace_id",
- sa.dialects.postgresql.UUID(as_uuid=True),
+ postgresql.UUID(as_uuid=True),
sa.ForeignKey("workspaces.id", ondelete="CASCADE"),
nullable=False,
),
sa.Column(
"user_id",
- sa.dialects.postgresql.UUID(as_uuid=True),
+ postgresql.UUID(as_uuid=True),
sa.ForeignKey("users.id", ondelete="CASCADE"),
nullable=False,
),
sa.Column("role", sa.String(20), nullable=False, server_default="owner"),
sa.Column(
"invited_by_user_id",
- sa.dialects.postgresql.UUID(as_uuid=True),
+ postgresql.UUID(as_uuid=True),
sa.ForeignKey("users.id", ondelete="SET NULL"),
nullable=True,
),
@@ -147,7 +148,7 @@ def upgrade() -> None:
tbl,
sa.Column(
"workspace_id",
- sa.dialects.postgresql.UUID(as_uuid=True),
+ postgresql.UUID(as_uuid=True),
sa.ForeignKey("workspaces.id", ondelete="CASCADE"),
nullable=True,
),
@@ -179,7 +180,7 @@ def upgrade() -> None:
"asset_values",
sa.Column(
"workspace_id",
- sa.dialects.postgresql.UUID(as_uuid=True),
+ postgresql.UUID(as_uuid=True),
sa.ForeignKey("workspaces.id", ondelete="CASCADE"),
nullable=True,
),
@@ -196,7 +197,7 @@ def upgrade() -> None:
"group_members",
sa.Column(
"workspace_id",
- sa.dialects.postgresql.UUID(as_uuid=True),
+ postgresql.UUID(as_uuid=True),
sa.ForeignKey("workspaces.id", ondelete="CASCADE"),
nullable=True,
),
@@ -213,7 +214,7 @@ def upgrade() -> None:
"group_settlements",
sa.Column(
"workspace_id",
- sa.dialects.postgresql.UUID(as_uuid=True),
+ postgresql.UUID(as_uuid=True),
sa.ForeignKey("workspaces.id", ondelete="CASCADE"),
nullable=True,
),
@@ -230,7 +231,7 @@ def upgrade() -> None:
"transaction_splits",
sa.Column(
"workspace_id",
- sa.dialects.postgresql.UUID(as_uuid=True),
+ postgresql.UUID(as_uuid=True),
sa.ForeignKey("workspaces.id", ondelete="CASCADE"),
nullable=True,
),
@@ -257,7 +258,7 @@ def upgrade() -> None:
"payee_mapping",
sa.Column(
"workspace_id",
- sa.dialects.postgresql.UUID(as_uuid=True),
+ postgresql.UUID(as_uuid=True),
sa.ForeignKey("workspaces.id", ondelete="CASCADE"),
nullable=True,
),
diff --git a/backend/alembic/versions/053_workspace_managed_by.py b/backend/alembic/versions/053_workspace_managed_by.py
index dbfc7a04..62a5b66d 100644
--- a/backend/alembic/versions/053_workspace_managed_by.py
+++ b/backend/alembic/versions/053_workspace_managed_by.py
@@ -14,6 +14,7 @@ work across several distinct sets of books).
from alembic import op
import sqlalchemy as sa
+from sqlalchemy.dialects import postgresql
revision = "053"
@@ -27,7 +28,7 @@ def upgrade() -> None:
"workspaces",
sa.Column(
"managed_by_user_id",
- sa.dialects.postgresql.UUID(as_uuid=True),
+ postgresql.UUID(as_uuid=True),
sa.ForeignKey("users.id", ondelete="SET NULL"),
nullable=True,
),
diff --git a/backend/alembic/versions/054_agents_workspace_id.py b/backend/alembic/versions/054_agents_workspace_id.py
index 4d317971..1bf9a6f7 100644
--- a/backend/alembic/versions/054_agents_workspace_id.py
+++ b/backend/alembic/versions/054_agents_workspace_id.py
@@ -16,6 +16,7 @@ and indexed.
from alembic import op
import sqlalchemy as sa
+from sqlalchemy.dialects import postgresql
revision = "054"
@@ -30,7 +31,7 @@ def upgrade() -> None:
table,
sa.Column(
"workspace_id",
- sa.dialects.postgresql.UUID(as_uuid=True),
+ postgresql.UUID(as_uuid=True),
sa.ForeignKey("workspaces.id", ondelete="CASCADE"),
nullable=True,
),
diff --git a/backend/app/agents/models/agent.py b/backend/app/agents/models/agent.py
index 40203598..e027417c 100644
--- a/backend/app/agents/models/agent.py
+++ b/backend/app/agents/models/agent.py
@@ -1,6 +1,6 @@
import uuid
from datetime import datetime
-from typing import Optional
+from typing import TYPE_CHECKING, Optional, cast
from sqlalchemy import JSON, Boolean, DateTime, Float, ForeignKey, Integer, String, Text
from sqlalchemy.dialects.postgresql import UUID
@@ -9,6 +9,10 @@ from sqlalchemy.sql import func
from app.core.database import Base
+if TYPE_CHECKING:
+ from app.agents.models.conversation import Conversation
+ from app.agents.models.knowledge import KnowledgeDoc
+
class Agent(Base):
__tablename__ = "agents"
@@ -61,8 +65,12 @@ class Agent(Base):
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
tools: Mapped[list["AgentTool"]] = relationship(back_populates="agent", cascade="all, delete-orphan")
- conversations: Mapped[list["Conversation"]] = relationship(back_populates="agent", cascade="all, delete-orphan") # noqa: F821
- knowledge_docs: Mapped[list["KnowledgeDoc"]] = relationship(back_populates="agent", cascade="all, delete-orphan") # noqa: F821
+ conversations: Mapped[list["Conversation"]] = relationship(back_populates="agent", cascade="all, delete-orphan")
+ knowledge_docs: Mapped[list["KnowledgeDoc"]] = relationship(back_populates="agent", cascade="all, delete-orphan")
+
+ # Virtual attributes populated by agent_service queries (not DB columns).
+ conversation_count = cast(int, 0)
+ knowledge_count = cast(int, 0)
class AgentTool(Base):
diff --git a/backend/app/agents/models/conversation.py b/backend/app/agents/models/conversation.py
index c2eff16f..ce4dd9ae 100644
--- a/backend/app/agents/models/conversation.py
+++ b/backend/app/agents/models/conversation.py
@@ -1,6 +1,6 @@
import uuid
from datetime import datetime
-from typing import Optional
+from typing import TYPE_CHECKING, Optional
from sqlalchemy import JSON, DateTime, ForeignKey, Index, Integer, String, Text
from sqlalchemy.dialects.postgresql import UUID
@@ -9,6 +9,9 @@ from sqlalchemy.sql import func
from app.core.database import Base
+if TYPE_CHECKING:
+ from app.agents.models.agent import Agent
+
class Conversation(Base):
__tablename__ = "agent_conversations"
@@ -28,7 +31,7 @@ class Conversation(Base):
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
- agent: Mapped["Agent"] = relationship(back_populates="conversations") # noqa: F821
+ agent: Mapped["Agent"] = relationship(back_populates="conversations")
messages: Mapped[list["Message"]] = relationship(
back_populates="conversation",
cascade="all, delete-orphan",
diff --git a/backend/app/agents/models/knowledge.py b/backend/app/agents/models/knowledge.py
index 9d24952f..7e460bd7 100644
--- a/backend/app/agents/models/knowledge.py
+++ b/backend/app/agents/models/knowledge.py
@@ -1,6 +1,6 @@
import uuid
from datetime import datetime
-from typing import Optional
+from typing import TYPE_CHECKING, Optional
from pgvector.sqlalchemy import Vector
from sqlalchemy import Boolean, DateTime, ForeignKey, Index, Integer, String, Text
@@ -11,6 +11,9 @@ from sqlalchemy.sql import func
from app.agents.config import get_agent_settings
from app.core.database import Base
+if TYPE_CHECKING:
+ from app.agents.models.agent import Agent
+
_EMBED_DIM = get_agent_settings().embedding_dim
@@ -37,7 +40,7 @@ class KnowledgeDoc(Base):
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
- agent: Mapped["Agent"] = relationship(back_populates="knowledge_docs") # noqa: F821
+ agent: Mapped["Agent"] = relationship(back_populates="knowledge_docs")
chunks: Mapped[list["KnowledgeChunk"]] = relationship(back_populates="doc", cascade="all, delete-orphan")
diff --git a/backend/app/agents/providers/base.py b/backend/app/agents/providers/base.py
index 9a627eb4..a2d8fec3 100644
--- a/backend/app/agents/providers/base.py
+++ b/backend/app/agents/providers/base.py
@@ -107,11 +107,11 @@ class LLMProvider(ABC):
def __init__(self, *, api_key: str = "", base_url: Optional[str] = None, model: Optional[str] = None):
self.api_key = api_key
- self.base_url = base_url
+ self.base_url: str = base_url or ""
self.default_model = model
@abstractmethod
- async def chat_stream(
+ def chat_stream(
self,
messages: list[ChatMessage],
*,
diff --git a/backend/app/agents/runtime/executor.py b/backend/app/agents/runtime/executor.py
index e87c1821..418e6438 100644
--- a/backend/app/agents/runtime/executor.py
+++ b/backend/app/agents/runtime/executor.py
@@ -22,7 +22,7 @@ import os
import time
import uuid
from dataclasses import dataclass
-from typing import Any, AsyncIterator, Literal, Optional
+from typing import Any, AsyncIterator, Literal, Optional, cast
from sqlalchemy.ext.asyncio import AsyncSession
@@ -37,6 +37,7 @@ from app.agents.providers.base import (
LLMNotSupportedError,
LLMRateLimitError,
LLMUnavailableError,
+ Role,
ToolCall,
)
from app.agents.providers.registry import build_provider
@@ -393,7 +394,7 @@ class AgentExecutor:
tr = m.tool_result or {}
content = tr.get("text") or _safe_json(tr.get("data"))
messages.append(ChatMessage(
- role=m.role, # type: ignore[arg-type]
+ role=cast(Role, m.role),
content=content,
tool_calls=tcs,
tool_call_id=tool_call_id,
diff --git a/backend/app/agents/services/agent_service.py b/backend/app/agents/services/agent_service.py
index 3560e765..09e79913 100644
--- a/backend/app/agents/services/agent_service.py
+++ b/backend/app/agents/services/agent_service.py
@@ -28,18 +28,24 @@ async def list_agents(
if rows:
ids = [a.id for a in rows]
conv_counts = dict(
- (await session.execute(
- select(Conversation.agent_id, func.count(Conversation.id))
- .where(Conversation.agent_id.in_(ids))
- .group_by(Conversation.agent_id)
- )).all()
+ (r[0], r[1])
+ for r in (
+ await session.execute(
+ select(Conversation.agent_id, func.count(Conversation.id))
+ .where(Conversation.agent_id.in_(ids))
+ .group_by(Conversation.agent_id)
+ )
+ ).all()
)
kb_counts = dict(
- (await session.execute(
- select(KnowledgeDoc.agent_id, func.count(KnowledgeDoc.id))
- .where(KnowledgeDoc.agent_id.in_(ids))
- .group_by(KnowledgeDoc.agent_id)
- )).all()
+ (r[0], r[1])
+ for r in (
+ await session.execute(
+ select(KnowledgeDoc.agent_id, func.count(KnowledgeDoc.id))
+ .where(KnowledgeDoc.agent_id.in_(ids))
+ .group_by(KnowledgeDoc.agent_id)
+ )
+ ).all()
)
# Stash on the model instances; pydantic AgentRead reads them.
for a in rows:
diff --git a/backend/app/api/export.py b/backend/app/api/export.py
index 0025d27f..d3f7cd9d 100644
--- a/backend/app/api/export.py
+++ b/backend/app/api/export.py
@@ -1,7 +1,7 @@
import io
import json
import zipfile
-from datetime import date, datetime
+from datetime import date, datetime, timezone
from decimal import Decimal
from uuid import UUID
@@ -92,7 +92,7 @@ async def backup(
zf.writestr(f"{name}.json", json.dumps(serialized, indent=2, ensure_ascii=False))
metadata = {
- "export_date": datetime.utcnow().isoformat(),
+ "export_date": datetime.now(timezone.utc).isoformat(),
"format_version": "1.0",
"workspace_id": str(ws_id),
"workspace_name": ctx.workspace.name,
diff --git a/backend/app/api/rules.py b/backend/app/api/rules.py
index c0c68580..1cb58d65 100644
--- a/backend/app/api/rules.py
+++ b/backend/app/api/rules.py
@@ -143,7 +143,7 @@ async def update_rule(
if not current_rule:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Rule not found")
if data.apply_to_existing is None:
- should_apply = _rule_match_definition_changed(current_rule, data)
+ should_apply = _rule_match_definition_changed(RuleRead.model_validate(current_rule), data)
else:
should_apply = data.apply_to_existing
diff --git a/backend/app/api/transactions.py b/backend/app/api/transactions.py
index 850f9319..7601da51 100644
--- a/backend/app/api/transactions.py
+++ b/backend/app/api/transactions.py
@@ -293,6 +293,10 @@ async def create_transfer(
debit_full = await transaction_service.get_transaction(session, debit_tx.id, ctx.workspace.id)
credit_full = await transaction_service.get_transaction(session, credit_tx.id, ctx.workspace.id)
primary_currency = ctx.user.primary_currency
+
+ if debit_tx.transfer_pair_id is None:
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="transfer_pair cannot be null")
+
return TransferRead(
debit=_tag_fx_fallback(TransactionRead.model_validate(debit_full, from_attributes=True), primary_currency),
credit=_tag_fx_fallback(TransactionRead.model_validate(credit_full, from_attributes=True), primary_currency),
@@ -316,6 +320,10 @@ async def link_transfer(
debit_full = await transaction_service.get_transaction(session, debit_tx.id, ctx.workspace.id)
credit_full = await transaction_service.get_transaction(session, credit_tx.id, ctx.workspace.id)
primary_currency = ctx.user.primary_currency
+
+ if debit_tx.transfer_pair_id is None:
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="transfer_pair cannot be null")
+
return TransferRead(
debit=_tag_fx_fallback(TransactionRead.model_validate(debit_full, from_attributes=True), primary_currency),
credit=_tag_fx_fallback(TransactionRead.model_validate(credit_full, from_attributes=True), primary_currency),
@@ -341,6 +349,10 @@ async def create_counterpart(
debit_full = await transaction_service.get_transaction(session, debit_tx.id, ctx.workspace.id)
credit_full = await transaction_service.get_transaction(session, credit_tx.id, ctx.workspace.id)
primary_currency = ctx.user.primary_currency
+
+ if debit_tx.transfer_pair_id is None:
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="transfer_pair cannot be null")
+
return TransferRead(
debit=_tag_fx_fallback(TransactionRead.model_validate(debit_full, from_attributes=True), primary_currency),
credit=_tag_fx_fallback(TransactionRead.model_validate(credit_full, from_attributes=True), primary_currency),
diff --git a/backend/app/api/workspaces.py b/backend/app/api/workspaces.py
index 1c76c19c..57ad20cf 100644
--- a/backend/app/api/workspaces.py
+++ b/backend/app/api/workspaces.py
@@ -271,7 +271,11 @@ async def change_member_role(
session, workspace_id, member_user_id, body.role
)
await session.commit()
+
target = await session.get(User, member_user_id)
+ if target is None:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Could not find user")
+
return MemberRead(
id=member.id,
user_id=target.id,
diff --git a/backend/app/core/auth.py b/backend/app/core/auth.py
index 59a02ec5..3bd3397f 100644
--- a/backend/app/core/auth.py
+++ b/backend/app/core/auth.py
@@ -24,6 +24,7 @@ async def get_user_db(session: AsyncSession = Depends(get_async_session)):
class UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):
+ user_db: SQLAlchemyUserDatabase
reset_password_token_secret = settings.secret_key
verification_token_secret = settings.secret_key
diff --git a/backend/app/core/database.py b/backend/app/core/database.py
index 25c591ff..2ff468af 100644
--- a/backend/app/core/database.py
+++ b/backend/app/core/database.py
@@ -1,3 +1,5 @@
+from collections.abc import AsyncIterator
+
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker
from sqlalchemy.orm import DeclarativeBase
@@ -13,6 +15,6 @@ class Base(DeclarativeBase):
pass
-async def get_async_session() -> AsyncSession:
+async def get_async_session() -> AsyncIterator[AsyncSession]:
async with async_session_maker() as session:
yield session
diff --git a/backend/app/models/asset_transaction.py b/backend/app/models/asset_transaction.py
index 191549c1..086bdddd 100644
--- a/backend/app/models/asset_transaction.py
+++ b/backend/app/models/asset_transaction.py
@@ -1,5 +1,5 @@
import uuid
-from datetime import date, datetime
+from datetime import date as _date, datetime
from decimal import Decimal
from typing import TYPE_CHECKING, Optional
@@ -36,7 +36,7 @@ class AssetTransaction(Base):
quantity: Mapped[Decimal] = mapped_column(Numeric(precision=18, scale=6))
price: Mapped[Decimal] = mapped_column(Numeric(precision=18, scale=6)) # per-share, asset currency
fee: Mapped[Decimal] = mapped_column(Numeric(precision=15, scale=2), default=Decimal("0"))
- date: Mapped[date] = mapped_column(Date, index=True)
+ date: Mapped[_date] = mapped_column(Date, index=True)
source: Mapped[str] = mapped_column(String(20), default="manual") # manual, import, pluggy
external_id: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
notes: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
diff --git a/backend/app/models/asset_value.py b/backend/app/models/asset_value.py
index 9388f097..67928fd4 100644
--- a/backend/app/models/asset_value.py
+++ b/backend/app/models/asset_value.py
@@ -1,5 +1,5 @@
import uuid
-from datetime import date
+from datetime import date as _date
from decimal import Decimal
from typing import Optional
@@ -26,7 +26,7 @@ class AssetValue(Base):
# backdated trades didn't update the baked `amount`). Null for manual/growth
# assets, where `amount` is the value directly.
price: Mapped[Optional[Decimal]] = mapped_column(Numeric(precision=18, scale=6), nullable=True)
- date: Mapped[date] = mapped_column(Date)
+ date: Mapped[_date] = mapped_column(Date)
source: Mapped[str] = mapped_column(String(20), default="manual") # manual, rule, sync
asset: Mapped["Asset"] = relationship(back_populates="values")
diff --git a/backend/app/models/fx_rate.py b/backend/app/models/fx_rate.py
index bc29f917..69ea067a 100644
--- a/backend/app/models/fx_rate.py
+++ b/backend/app/models/fx_rate.py
@@ -1,5 +1,5 @@
import uuid
-from datetime import date, datetime, timezone
+from datetime import date as _date, datetime, timezone
from decimal import Decimal
from sqlalchemy import Date, DateTime, Index, Numeric, String, UniqueConstraint
@@ -19,7 +19,7 @@ class FxRate(Base):
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
base_currency: Mapped[str] = mapped_column(String(3)) # Always "USD" for OER
quote_currency: Mapped[str] = mapped_column(String(3))
- date: Mapped[date] = mapped_column(Date)
+ date: Mapped[_date] = mapped_column(Date)
rate: Mapped[Decimal] = mapped_column(Numeric(precision=20, scale=10))
source: Mapped[str] = mapped_column(String(50))
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc))
diff --git a/backend/app/models/group.py b/backend/app/models/group.py
index 1dd487cf..a2818006 100644
--- a/backend/app/models/group.py
+++ b/backend/app/models/group.py
@@ -1,6 +1,6 @@
import uuid
from datetime import datetime, timezone
-from typing import TYPE_CHECKING, Optional
+from typing import TYPE_CHECKING, Optional, cast
from sqlalchemy import Boolean, DateTime, ForeignKey, String
from sqlalchemy.dialects.postgresql import UUID
@@ -57,6 +57,9 @@ class Group(Base):
back_populates="group", cascade="all, delete-orphan"
)
+ # Per-request transient flag set by group_service._tag_owner.
+ is_owner = cast(bool, False)
+
class GroupMember(Base):
__tablename__ = "group_members"
diff --git a/backend/app/models/payee.py b/backend/app/models/payee.py
index 31ca7842..6c97658e 100644
--- a/backend/app/models/payee.py
+++ b/backend/app/models/payee.py
@@ -1,6 +1,6 @@
import uuid
from datetime import datetime, timezone
-from typing import TYPE_CHECKING, Optional
+from typing import TYPE_CHECKING, Optional, cast
from sqlalchemy import Boolean, DateTime, ForeignKey, String
from sqlalchemy.dialects.postgresql import UUID
@@ -27,6 +27,9 @@ class Payee(Base):
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))
+ # Dynamically set by payee_service; not a DB column
+ transaction_count = cast(int, 0)
+
user: Mapped["User"] = relationship()
transactions: Mapped[list["Transaction"]] = relationship(back_populates="payee_entity")
diff --git a/backend/app/models/transaction.py b/backend/app/models/transaction.py
index 457e2079..396d38d0 100644
--- a/backend/app/models/transaction.py
+++ b/backend/app/models/transaction.py
@@ -1,7 +1,7 @@
import uuid
from datetime import date as _date, datetime, timezone
from decimal import Decimal
-from typing import TYPE_CHECKING, Optional
+from typing import TYPE_CHECKING, Optional, cast
from sqlalchemy import Boolean, Date, DateTime, ForeignKey, JSON, Numeric, SmallInteger, String, event
from sqlalchemy.dialects.postgresql import UUID
@@ -107,18 +107,26 @@ class Transaction(Base):
back_populates="transaction", cascade="all, delete-orphan"
)
+ # Populated dynamically by the service (not DB columns).
+ is_shared: bool = False
+ viewer_share = cast(Optional[Decimal], None)
+ group_id = cast(Optional[uuid.UUID], None)
+ parent_owner_name = cast(Optional[str], None)
+ attachment_count: int = 0
+ payee_name = cast(Optional[str], None)
+
# Safety net: `effective_date` is NOT NULL. For non-CC transactions it always
# equals `date`, so if a call site (or test) forgets to set it, fall back
# silently. CC-aware service code still calls `apply_effective_date` explicitly
# so that cycle-based due dates are stored when the account has the metadata.
@event.listens_for(Transaction, "before_insert")
-def _default_effective_date(mapper, connection, target): # type: ignore
+def _default_effective_date(mapper, connection, target):
if target.effective_date is None:
target.effective_date = target.date
@event.listens_for(Transaction, "before_update")
-def _default_effective_date_on_update(mapper, connection, target): # type: ignore
+def _default_effective_date_on_update(mapper, connection, target):
if target.effective_date is None:
target.effective_date = target.date
diff --git a/backend/app/models/user.py b/backend/app/models/user.py
index 6664706c..1483f634 100644
--- a/backend/app/models/user.py
+++ b/backend/app/models/user.py
@@ -1,3 +1,4 @@
+import uuid
from typing import TYPE_CHECKING, Optional
from fastapi_users.db import SQLAlchemyBaseUserTableUUID
@@ -19,6 +20,19 @@ class User(SQLAlchemyBaseUserTableUUID, Base):
UniqueConstraint("oidc_issuer", "oidc_subject", name="uq_users_oidc_identity"),
)
+ if TYPE_CHECKING:
+ # fastapi-users declares its inherited columns as plain types (e.g.
+ # `email: str`) under its own TYPE_CHECKING branch, so `ty` can't see
+ # them as SQLAlchemy `Mapped` attributes (`.ilike()`, `.in_()`, ...).
+ # Re-annotate them here so type checkers treat them as real mapped
+ # columns everywhere.
+ id: Mapped[uuid.UUID]
+ email: Mapped[str]
+ hashed_password: Mapped[str]
+ is_active: Mapped[bool]
+ is_superuser: Mapped[bool]
+ is_verified: Mapped[bool]
+
preferences: Mapped[Optional[dict]] = mapped_column(
JSON,
default=lambda: {
diff --git a/backend/app/providers/base.py b/backend/app/providers/base.py
index a0eb3486..8406dd33 100644
--- a/backend/app/providers/base.py
+++ b/backend/app/providers/base.py
@@ -326,7 +326,7 @@ class BankProvider(ABC):
"""Refresh access token if needed."""
...
- async def trigger_refresh(self, credentials: dict) -> RefreshOutcome:
+ async def trigger_refresh(self, credentials: dict | None) -> RefreshOutcome:
"""Ask the provider to pull fresh data from the underlying institution.
Some aggregator providers cache the bank's data on their own side and
diff --git a/backend/app/providers/pluggy.py b/backend/app/providers/pluggy.py
index e6269519..75b5f31b 100644
--- a/backend/app/providers/pluggy.py
+++ b/backend/app/providers/pluggy.py
@@ -530,7 +530,7 @@ class PluggyProvider(BankProvider):
# Pluggy manages API keys at the provider level, not per-connection
return credentials
- async def trigger_refresh(self, credentials: dict) -> RefreshOutcome:
+ async def trigger_refresh(self, credentials: dict | None) -> RefreshOutcome:
"""Trigger ``PATCH /items/{id}`` and poll the item until it leaves
the ``UPDATING`` state.
diff --git a/backend/app/providers/simplefin.py b/backend/app/providers/simplefin.py
index c274e443..9fa11671 100644
--- a/backend/app/providers/simplefin.py
+++ b/backend/app/providers/simplefin.py
@@ -369,7 +369,7 @@ class SimpleFinProvider(BankProvider):
accounts: list[AccountData] = []
for raw in payload.get("accounts") or []:
balance = _to_decimal(raw.get("balance")) or Decimal("0")
- currency = _iso_currency(raw.get("currency"), "USD")
+ currency = _iso_currency(raw.get("currency"), "USD") or "USD"
account_id = str(raw.get("id") or "")
if not account_id:
continue
@@ -487,13 +487,13 @@ class SimpleFinProvider(BankProvider):
HoldingData(
external_id=holding_id,
name=raw.get("description") or raw.get("symbol") or holding_id,
- currency=_iso_currency(raw.get("currency"), acc_currency),
+ currency=_iso_currency(raw.get("currency"), acc_currency) or acc_currency,
ticker=_ticker(raw.get("symbol")),
current_value=market_value,
quantity=_to_decimal(raw.get("shares")),
- unit_price=_to_decimal(raw.get("market_value")) / _to_decimal(
- raw.get("shares")
- ) if _to_decimal(raw.get("shares")) else None,
+ unit_price=market_value / shares
+ if (shares := _to_decimal(raw.get("shares")))
+ else None,
purchase_price=_to_decimal(raw.get("purchase_price")),
purchase_date=_epoch_to_date(raw.get("created")),
isin=raw.get("isin"),
diff --git a/backend/app/services/account_service.py b/backend/app/services/account_service.py
index a036cb7c..d60be6b7 100644
--- a/backend/app/services/account_service.py
+++ b/backend/app/services/account_service.py
@@ -3,7 +3,7 @@ from datetime import date as _Date, datetime, timedelta, timezone
from decimal import Decimal
from typing import Optional
-from sqlalchemy import case, func, select, or_
+from sqlalchemy import case, delete, func, select, or_, update
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import contains_eager
@@ -553,20 +553,20 @@ async def delete_account(session: AsyncSession, account_id: uuid.UUID, workspace
# The transaction rows themselves cascade-delete via Account.transactions
# when session.delete(account) flushes below.
await session.execute(
- Transaction.__table__.update()
+ update(Transaction)
.where(Transaction.account_id == account_id)
.values(import_id=None)
)
await session.execute(
- ImportLog.__table__.delete().where(ImportLog.account_id == account_id)
+ delete(ImportLog).where(ImportLog.account_id == account_id)
)
await session.execute(
- RecurringTransaction.__table__.delete().where(
+ delete(RecurringTransaction).where(
RecurringTransaction.account_id == account_id
)
)
await session.execute(
- Goal.__table__.update()
+ update(Goal)
.where(Goal.account_id == account_id)
.values(account_id=None)
)
@@ -666,7 +666,7 @@ async def get_account_summary(
),
)
)
- current_balance = float(balance_result.scalar())
+ current_balance = float(balance_result.scalar() or 0)
# Connected CC: provider balance is positive for debt → negate.
# Manual CC: transaction math already gives negative for debt.
diff --git a/backend/app/services/asset_service.py b/backend/app/services/asset_service.py
index f898c88c..35baf55e 100644
--- a/backend/app/services/asset_service.py
+++ b/backend/app/services/asset_service.py
@@ -2,7 +2,7 @@ import logging
import uuid
from datetime import date, datetime, timezone, timedelta
from decimal import Decimal
-from typing import Optional
+from typing import Any, Optional, cast
from fastapi import HTTPException, status
from sqlalchemy import select, func, desc
@@ -23,6 +23,9 @@ from app.services.fx_rate_service import convert, stamp_primary_amount
logger = logging.getLogger(__name__)
+ValueRecord = tuple[date, Decimal, Optional[Decimal]] # (date, amount, price_per_share)
+TxRecord = tuple[date, str, Decimal, Optional[Decimal]] # (date, kind, quantity, price_per_share)
+
def _next_due_date(last_date: date, frequency: str) -> date:
"""Calculate the next due date based on frequency."""
@@ -196,8 +199,8 @@ async def _get_value_as_of(
def build_market_value_series(
- value_rows: list[tuple[date, Decimal, Optional[Decimal]]],
- txs: list[tuple[date, str, Decimal, Optional[Decimal]]],
+ value_rows: list[ValueRecord],
+ txs: list[TxRecord],
) -> list[tuple[date, float]]:
"""Rebuild a market-priced holding's value series from the ledger.
@@ -246,7 +249,7 @@ def build_market_value_series(
qty += tx_delta.get(d, Decimal("0"))
held = qty if qty > 0 else Decimal("0")
- amount, price = value_by_date.get(d, (None, None))
+ amount, price = value_by_date.get(d, (0.0, None))
if price is not None:
last_price = price # a recorded market price always wins
seen_market = True
@@ -261,7 +264,7 @@ def build_market_value_series(
elif last_price is not None:
out.append((d, float(last_price * held)))
else:
- out.append((d, float(amount) if amount is not None else 0.0))
+ out.append((d, float(amount)))
return out
@@ -291,13 +294,13 @@ async def _load_asset_native_values(
q = q.where(AssetValue.date <= up_to_date)
rows = (await session.execute(q)).all()
- raw: dict[str, list[tuple[date, Decimal, Optional[Decimal]]]] = {str(a.id): [] for a in assets}
+ raw: dict[str, list[ValueRecord]] = {str(a.id): [] for a in assets}
for aid, d, amt, price in rows:
raw[str(aid)].append((d, amt, price))
# Bulk-load the ledger for market-priced holdings (one query).
market_ids = [a.id for a in assets if a.valuation_method == "market_price"]
- txs_by_aid: dict[str, list[tuple[date, str, Decimal]]] = {}
+ txs_by_aid: dict[str, list[TxRecord]] = {}
if market_ids:
tq = select(
AssetTransaction.asset_id, AssetTransaction.date,
@@ -814,7 +817,7 @@ async def get_portfolio_trend(
values_map = await _load_asset_native_values(session, active_assets)
- asset_meta = []
+ asset_meta: list[dict[str, Any]] = []
asset_currency: dict[str, str] = {}
sell_date_by_aid: dict[str, date] = {}
all_dates: set[date] = set()
@@ -901,7 +904,7 @@ async def get_portfolio_trend(
# The header total matches the last row's _total — both use the same
# per-display-date conversion so no second conversion is needed.
- total = trend[-1]["_total"] if trend else 0.0
+ total: float = cast(float, trend[-1]["_total"]) if trend else 0.0
return {"assets": asset_meta, "trend": trend, "total": round(total, 2)}
diff --git a/backend/app/services/asset_transaction_service.py b/backend/app/services/asset_transaction_service.py
index f48b2629..afa30f93 100644
--- a/backend/app/services/asset_transaction_service.py
+++ b/backend/app/services/asset_transaction_service.py
@@ -307,10 +307,16 @@ async def update_transaction(
)
_raise_if_oversell(others + [edited])
+ # Resolve the asset before mutating the row: bailing out after the
+ # setattr loop would leave the edits pending in the session, so a later
+ # commit in the same request would persist an update we reported failed.
+ asset = await _load_asset(session, tx.asset_id, workspace_id)
+ if asset is None:
+ return None
+
for key, value in fields.items():
setattr(tx, key, value)
_validate(tx.kind, _d(tx.quantity), _d(tx.price))
- asset = await _load_asset(session, tx.asset_id, workspace_id)
await session.flush()
await recompute_and_cache(session, asset)
await session.commit()
@@ -329,6 +335,8 @@ async def delete_transaction(
if tx is None:
return None
asset = await _load_asset(session, tx.asset_id, workspace_id)
+ if asset is None:
+ return None
await session.delete(tx)
await session.flush()
await recompute_and_cache(session, asset)
@@ -401,7 +409,10 @@ async def buy_into_holding(
await session.flush()
await recompute_and_cache(session, asset)
await session.commit()
- return await asset_service.get_asset(session, asset.id, workspace_id)
+ result = await asset_service.get_asset(session, asset.id, workspace_id)
+ if result is None:
+ raise RuntimeError("Asset disappeared after ledger transaction")
+ return result
def _type_from_quote(quote_type: Optional[str]) -> str:
diff --git a/backend/app/services/category_group_service.py b/backend/app/services/category_group_service.py
index b437239e..03e7ffc1 100644
--- a/backend/app/services/category_group_service.py
+++ b/backend/app/services/category_group_service.py
@@ -44,7 +44,7 @@ CATEGORY_TO_GROUP = {
def _resolve_group_name(key: str, lang: str) -> str:
entry = DEFAULT_GROUPS_I18N.get(key, {})
- return entry.get(lang, entry.get("en", key))
+ return str(entry.get(lang, entry.get("en", key)))
async def create_default_groups(
@@ -100,7 +100,10 @@ async def create_group(
group = CategoryGroup(user_id=user_id, workspace_id=workspace_id, **data.model_dump())
session.add(group)
await session.commit()
- return await get_group(session, group.id, workspace_id)
+ created = await get_group(session, group.id, workspace_id)
+ if created is None:
+ raise RuntimeError("Failed to reload created category group")
+ return created
async def update_group(
diff --git a/backend/app/services/connection_service.py b/backend/app/services/connection_service.py
index db6feac1..7932bf34 100644
--- a/backend/app/services/connection_service.py
+++ b/backend/app/services/connection_service.py
@@ -1138,6 +1138,8 @@ async def sync_connection(
connection = await get_connection(session, connection_id, workspace_id)
if not connection:
raise ValueError("Connection not found")
+ if not connection.credentials:
+ raise ValueError("Credentials not found")
conn_settings = connection.settings or {}
payee_source = conn_settings.get("payee_source", "auto")
@@ -1524,8 +1526,11 @@ async def sync_connection(
conn = await session.get(BankConnection, connection_id)
if conn and conn.status != "expired":
conn.status = "active"
+ # The row can vanish if the connection was deleted mid-sync. Fall back
+ # to the one we already hold rather than raising: re-raising here would
+ # escape as a 500, which is exactly what this handler exists to avoid.
refreshed = await session.get(BankConnection, connection_id)
- return refreshed, 0
+ return refreshed or connection, 0
except Exception:
# Mark connection as errored so UI shows reconnect banner
await session.rollback()
diff --git a/backend/app/services/goal_service.py b/backend/app/services/goal_service.py
index ac0797c1..a2870966 100644
--- a/backend/app/services/goal_service.py
+++ b/backend/app/services/goal_service.py
@@ -50,7 +50,10 @@ async def _linked_name(session: AsyncSession, model: type, item_id: uuid.UUID |
return None
if isinstance(item, Account):
return get_account_name(item)
- return item.name
+ # Callers pass Asset / AssetGroup, both of which have `.name`. Stay
+ # tolerant rather than raising: a goal whose link we can't name should
+ # render without one, not 500 the whole goals list.
+ return getattr(item, "name", None)
async def _resolve_current_amount(
diff --git a/backend/app/services/group_service.py b/backend/app/services/group_service.py
index 2e7c9e07..8f3707b5 100644
--- a/backend/app/services/group_service.py
+++ b/backend/app/services/group_service.py
@@ -23,7 +23,7 @@ def _tag_owner(group: Group, user_id: uuid.UUID) -> Group:
workspace it lives in — `Group.user_id` retains creator semantics
even after the workspace migration.
"""
- group.is_owner = group.user_id == user_id # type: ignore[attr-defined]
+ group.is_owner = group.user_id == user_id
if getattr(group, "members", None):
for m in group.members:
_tag_member_self(m, user_id, group.user_id)
diff --git a/backend/app/services/import_service.py b/backend/app/services/import_service.py
index 77d085eb..482af357 100644
--- a/backend/app/services/import_service.py
+++ b/backend/app/services/import_service.py
@@ -11,8 +11,6 @@ from ofxparse import OfxParser
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
-from types import SimpleNamespace
-
from app.core.config import get_settings
from app.models.account import Account
from app.models.category import Category
@@ -582,7 +580,7 @@ async def enrich_with_category_suggestions(
return transactions
for txn in transactions:
- proxy = SimpleNamespace(
+ proxy: Transaction = Transaction(
description=txn.description,
amount=txn.amount,
date=txn.date,
diff --git a/backend/app/services/payee_service.py b/backend/app/services/payee_service.py
index c6c4f665..270fc9b5 100644
--- a/backend/app/services/payee_service.py
+++ b/backend/app/services/payee_service.py
@@ -1,9 +1,9 @@
import uuid
from datetime import date
from decimal import Decimal
-from typing import Optional
+from typing import Optional, cast
-from sqlalchemy import case, select, func, update, delete
+from sqlalchemy import CursorResult, case, select, func, update, delete
from sqlalchemy.ext.asyncio import AsyncSession
from app.models.payee import Payee, PayeeMapping
@@ -208,7 +208,7 @@ async def bulk_delete_payees(session: AsyncSession, workspace_id: uuid.UUID, pay
)
await session.commit()
- return result.rowcount
+ return cast(CursorResult, result).rowcount
async def merge_payees(
@@ -237,7 +237,7 @@ async def merge_payees(
.where(Transaction.payee_id.in_(source_ids))
.values(payee_id=target_id)
)
- reassigned = result.rowcount
+ reassigned = cast(CursorResult, result).rowcount
# Update mappings: point source mappings to target
for source_id in source_ids:
@@ -297,7 +297,7 @@ async def get_payee_summary(
else_=Decimal("0"),
)
), Decimal("0")).label("total_received"),
- func.count(Transaction.id).label("count"),
+ func.count(Transaction.id).label("tx_count"),
func.max(Transaction.date).label("last_date"),
)
.where(
@@ -327,12 +327,12 @@ async def get_payee_summary(
)
most_common_category = cat.scalar_one_or_none()
- payee.transaction_count = row.count
+ payee.transaction_count = row.tx_count
return {
"payee": payee,
"total_spent": row.total_spent,
"total_received": row.total_received,
- "transaction_count": row.count,
+ "transaction_count": row.tx_count,
"most_common_category": most_common_category,
"last_transaction_date": row.last_date,
}
diff --git a/backend/app/services/rule_service.py b/backend/app/services/rule_service.py
index b9494152..f9839a8b 100644
--- a/backend/app/services/rule_service.py
+++ b/backend/app/services/rule_service.py
@@ -1,6 +1,6 @@
# backend/app/services/rule_service.py
import uuid
-from typing import Optional
+from typing import Any, Optional, cast
from sqlalchemy import delete, select
from sqlalchemy.ext.asyncio import AsyncSession
@@ -118,7 +118,7 @@ UNIVERSAL_RULES = [
]
# ─── Country-specific rule packs (optional, not auto-applied) ───
-RULE_PACKS = {
+RULE_PACKS: dict[str, dict[str, Any]] = {
"BR": {
"name": "Brazil",
"flag": "\U0001F1E7\U0001F1F7",
@@ -778,7 +778,9 @@ async def install_rule_pack(
pack_code = str(user_id_or_pack_code)
else:
workspace_id = workspace_id_or_user_id
- user_id = user_id_or_pack_code
+ # Narrowed by the branch: `pack_code` being set means the caller used
+ # the workspace-scoped signature, so this argument is the user id.
+ user_id = cast(uuid.UUID, user_id_or_pack_code)
pack = RULE_PACKS.get(pack_code)
if not pack:
@@ -1023,9 +1025,9 @@ async def update_rule(
if update_data["name"] in existing_names:
raise DuplicateRuleError(f"A rule named '{update_data['name']}' already exists")
- if "conditions" in update_data and update_data["conditions"] is not None:
+ if data.conditions is not None:
update_data["conditions"] = [c.model_dump() for c in data.conditions]
- if "actions" in update_data and update_data["actions"] is not None:
+ if data.actions is not None:
update_data["actions"] = [a.model_dump() for a in data.actions]
await _validate_rule_definition(
diff --git a/backend/app/services/split_service.py b/backend/app/services/split_service.py
index 519ac6a9..99962c5d 100644
--- a/backend/app/services/split_service.py
+++ b/backend/app/services/split_service.py
@@ -63,7 +63,7 @@ def _materialize(
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"))
+ pct_sum = sum((s.share_pct or Decimal("0") for s in payload.splits), Decimal("0"))
if pct_sum != Decimal("100"):
raise ValueError("Split percentages must sum to 100")
@@ -73,11 +73,8 @@ def _materialize(
# 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)
- ]
+ amounts.append(_quantize(total * (s.share_pct or Decimal("0")) / 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}")
@@ -92,9 +89,7 @@ async def _validate_members(
(owner OR linked member). Returns that group's id."""
# A group is visible if the user owns it or is linked as a member.
linked_group_ids = (
- select(GroupMember.group_id)
- .where(GroupMember.linked_user_id == user_id)
- .distinct()
+ select(GroupMember.group_id).where(GroupMember.linked_user_id == user_id).distinct()
)
result = await session.execute(
select(GroupMember, Group)
@@ -132,9 +127,7 @@ async def replace_splits(
# 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
- )
+ delete(TransactionSplit).where(TransactionSplit.transaction_id == transaction.id)
)
if not payload.splits:
diff --git a/backend/app/services/transaction_calendar_service.py b/backend/app/services/transaction_calendar_service.py
index 8d1fd237..8be40336 100644
--- a/backend/app/services/transaction_calendar_service.py
+++ b/backend/app/services/transaction_calendar_service.py
@@ -1,7 +1,7 @@
import uuid
from datetime import date, timedelta
from decimal import Decimal
-from typing import Optional
+from typing import Literal, Optional, cast
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
@@ -56,7 +56,9 @@ async def get_transaction_calendar(
requested_account_ids = account_ids
if requested_account_ids is not None and len(requested_account_ids) == 0:
- return _empty_calendar(month_start, grid_start, grid_end, primary_currency, requested_account_ids)
+ return _empty_calendar(
+ month_start, grid_start, grid_end, primary_currency, requested_account_ids
+ )
days = {
d: TransactionCalendarDay(
@@ -94,7 +96,9 @@ async def get_transaction_calendar(
session, tx.amount, tx.currency, primary_currency, tx.amount_primary
)
- is_transfer = bool(tx.transfer_pair_id) or bool(tx.category and tx.category.treat_as_transfer)
+ is_transfer = bool(tx.transfer_pair_id) or bool(
+ tx.category and tx.category.treat_as_transfer
+ )
ignored = bool(tx.is_ignored or (tx.category and tx.category.is_ignored))
if not ignored:
if is_transfer or tx.source == "transfer":
@@ -261,7 +265,11 @@ async def _signed_balance_delta_primary(
primary_currency: str,
) -> float:
account_currency = tx.account.currency if tx.account else tx.currency
- effective = tx.amount if tx.currency == account_currency else Decimal(str(tx.amount_primary or tx.amount))
+ effective = (
+ tx.amount
+ if tx.currency == account_currency
+ else Decimal(str(tx.amount_primary or tx.amount))
+ )
amount = abs(Decimal(str(effective)))
if account_currency != primary_currency:
amount, _ = await fx_convert(session, amount, account_currency, primary_currency)
@@ -269,7 +277,9 @@ async def _signed_balance_delta_primary(
return float(signed)
-def _actual_item(tx: Transaction, amount_primary: float, is_transfer: bool, ignored: bool) -> TransactionCalendarItem:
+def _actual_item(
+ tx: Transaction, amount_primary: float, is_transfer: bool, ignored: bool
+) -> TransactionCalendarItem:
category = tx.category
account = tx.account
return TransactionCalendarItem(
@@ -280,7 +290,7 @@ def _actual_item(tx: Transaction, amount_primary: float, is_transfer: bool, igno
amount=float(tx.amount),
amount_primary=amount_primary,
currency=tx.currency,
- type=tx.type,
+ type=cast(Literal["debit", "credit"], tx.type),
account_id=tx.account_id,
account_name=account.display_name or account.name if account else None,
category_id=tx.category_id,
@@ -353,7 +363,7 @@ async def _project_recurring_items(
amount=float(rec.amount),
amount_primary=amount_primary,
currency=rec.currency,
- type=rec.type,
+ type=cast(Literal["debit", "credit"], rec.type),
account_id=rec.account_id,
account_name=account.display_name or account.name if account else None,
category_id=rec.category_id,
diff --git a/backend/app/services/transaction_service.py b/backend/app/services/transaction_service.py
index e570db6b..1e46ea06 100644
--- a/backend/app/services/transaction_service.py
+++ b/backend/app/services/transaction_service.py
@@ -2,9 +2,9 @@ import re
import uuid
from datetime import date
from decimal import Decimal
-from typing import Optional
+from typing import Optional, cast
-from sqlalchemy import select, func, or_, not_, update
+from sqlalchemy import CursorResult, select, func, or_, not_, update
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload
@@ -131,7 +131,7 @@ async def get_transactions(
# point of the override (issue #92, LucasFidelis suggestion). Shared
# with the dashboard/report/budget aggregations so a transaction lands
# in the same month everywhere (issue #232).
- date_col = reporting_date_col(accounting_mode)
+ date_col = reporting_date_col(accounting_mode or "cash")
# Group-scope visibility: when the caller filters by a group they
# have access to (owner or linked member), bypass the user-owns-it
@@ -143,7 +143,7 @@ async def get_transactions(
accessible = await get_group_visible(session, group_id, workspace_id, user_id)
if accessible is None:
- return [], 0
+ return [], 0, None
use_group_scope = True
# CC bill-view date column: when the caller asks "what's in this bill?"
@@ -446,7 +446,7 @@ async def get_transactions(
# order by purchase date so the in-cycle list matches the bank's own
# statement ordering regardless of accounting mode.
default_order_col = bill_view_date_col if in_bill_view else date_col
- sort_columns: dict[str, object] = {
+ sort_columns = {
# `date` is the cycle/accrual-aware column the UI lists use so its
# ordering matches the cash-flow & dashboard views.
"date": default_order_col,
@@ -491,7 +491,7 @@ async def get_transactions(
.where(TransactionAttachment.transaction_id.in_(tx_ids))
.group_by(TransactionAttachment.transaction_id)
)
- counts = dict(count_rows.all())
+ counts = {row[0]: row[1] for row in count_rows.all()}
for tx in transactions:
tx.attachment_count = counts.get(tx.id, 0)
tx.payee_name = tx.payee_entity.name if tx.payee_entity else None
@@ -915,7 +915,7 @@ async def get_transfer_candidates(
.where(TransactionAttachment.transaction_id.in_(tx_ids))
.group_by(TransactionAttachment.transaction_id)
)
- counts = dict(count_rows.all())
+ counts = {row[0]: row[1] for row in count_rows.all()}
for tx in candidates:
tx.attachment_count = counts.get(tx.id, 0)
tx.payee_name = tx.payee_entity.name if tx.payee_entity else None
@@ -1290,7 +1290,7 @@ async def bulk_update_category(
.values(category_id=category_id)
)
await session.commit()
- return result.rowcount
+ return cast(CursorResult, result).rowcount
_TAG_CHAR_CLASS = r"[\wÀ-ž-]"
diff --git a/backend/mcp_server/tools/_helpers.py b/backend/mcp_server/tools/_helpers.py
index 58f07490..dd070518 100644
--- a/backend/mcp_server/tools/_helpers.py
+++ b/backend/mcp_server/tools/_helpers.py
@@ -32,9 +32,12 @@ def parse_uuid(v: Any) -> Optional[uuid.UUID]:
def parse_uuid_list(v: Any) -> Optional[list[uuid.UUID]]:
if v is None:
return None
- if isinstance(v, (list, tuple)):
- return [parse_uuid(x) for x in v if x] or None
- return [parse_uuid(v)]
+ values = v if isinstance(v, (list, tuple)) else [v]
+ return [
+ u
+ for x in values
+ if (u := parse_uuid(x)) is not None
+ ] or None
def num(x: Any) -> Optional[float]:
diff --git a/backend/mcp_server/tools/accounts.py b/backend/mcp_server/tools/accounts.py
index c244582e..43281b73 100644
--- a/backend/mcp_server/tools/accounts.py
+++ b/backend/mcp_server/tools/accounts.py
@@ -76,9 +76,13 @@ async def get_account_summary(
to_date: str | None = None,
) -> dict[str, Any]:
ws_id = await resolve_workspace_id(session, ctx)
+ account_uuid = parse_uuid(account_id)
+ if account_uuid is None:
+ return dict(error="account not found")
+
summary = await account_service.get_account_summary(
session,
- parse_uuid(account_id),
+ account_uuid,
ws_id,
date_from=parse_date(from_date),
date_to=parse_date(to_date),
diff --git a/backend/mcp_server/tools/aggregate.py b/backend/mcp_server/tools/aggregate.py
index 312712b3..33c94eae 100644
--- a/backend/mcp_server/tools/aggregate.py
+++ b/backend/mcp_server/tools/aggregate.py
@@ -141,7 +141,7 @@ async def aggregate(
q = q.group_by(bucket_id).order_by(value_expr.desc().nulls_last()).limit(int(limit))
- rows = (await session.execute(q)).all()
+ rows = (await session.execute(q)).mappings().all()
label_map: dict[Any, str] = {}
if label_q is not None:
for cid, cname in (await session.execute(label_q)).all():
@@ -149,10 +149,10 @@ async def aggregate(
items = [
{
- "bucket": str(r.bucket) if r.bucket is not None else None,
- "label": label_map.get(r.bucket),
- "value": num(r.value),
- "count": int(r.count or 0),
+ "bucket": str(r["bucket"]) if r["bucket"] is not None else None,
+ "label": label_map.get(r["bucket"]),
+ "value": num(r["value"]),
+ "count": int(r.get("count", 0)),
}
for r in rows
]
diff --git a/backend/mcp_server/tools/groups.py b/backend/mcp_server/tools/groups.py
index 606a2aff..a85b0cdd 100644
--- a/backend/mcp_server/tools/groups.py
+++ b/backend/mcp_server/tools/groups.py
@@ -96,6 +96,10 @@ async def get_group_balances(
group_id: str,
) -> dict[str, Any]:
gid = parse_uuid(group_id)
+ if gid is None:
+ return dict(error="group not found or not visible to this user")
+
+
ws_id = await resolve_workspace_id(session, ctx)
result = await balance_service.compute_balances(session, gid, ws_id, ctx.user_id)
if result is None:
@@ -156,6 +160,9 @@ async def list_group_settlements(
group_id: str,
) -> dict[str, Any]:
gid = parse_uuid(group_id)
+ if gid is None:
+ return dict(error="group not found or not visible to this user")
+
ws_id = await resolve_workspace_id(session, ctx)
rows = await settlement_service.list_settlements(session, gid, ws_id, ctx.user_id)
if rows is None:
diff --git a/backend/mcp_server/tools/lifecycle.py b/backend/mcp_server/tools/lifecycle.py
index 0489f7e8..aa323594 100644
--- a/backend/mcp_server/tools/lifecycle.py
+++ b/backend/mcp_server/tools/lifecycle.py
@@ -44,7 +44,7 @@ async def list_recurring_transactions(
"interval": getattr(r, "interval", None),
"next_occurrence": r.next_occurrence.isoformat() if getattr(r, "next_occurrence", None) else None,
"start_date": r.start_date.isoformat() if getattr(r, "start_date", None) else None,
- "end_date": r.end_date.isoformat() if getattr(r, "end_date", None) else None,
+ "end_date": r.end_date.isoformat() if r.end_date else None,
"is_active": bool(getattr(r, "is_active", True)),
"category_id": str(r.category_id) if getattr(r, "category_id", None) else None,
"account_id": str(r.account_id) if getattr(r, "account_id", None) else None,
diff --git a/backend/mcp_server/tools/payees.py b/backend/mcp_server/tools/payees.py
index 9a67a6d7..36691bd0 100644
--- a/backend/mcp_server/tools/payees.py
+++ b/backend/mcp_server/tools/payees.py
@@ -27,7 +27,6 @@ async def list_payees(
{
"id": str(p.id),
"name": p.name,
- "default_category_id": str(p.default_category_id) if getattr(p, "default_category_id", None) else None,
}
for p in payees
]
diff --git a/backend/mcp_server/tools/proposals.py b/backend/mcp_server/tools/proposals.py
index f6c337f1..b21260fa 100644
--- a/backend/mcp_server/tools/proposals.py
+++ b/backend/mcp_server/tools/proposals.py
@@ -12,6 +12,7 @@ the preview as usual; a follow-up call with `apply=true` performs the
write directly. Internal callers never set `apply`, so behavior is
unchanged for Securo's own UI.
"""
+
from __future__ import annotations
from datetime import date
@@ -46,7 +47,13 @@ from app.services import (
)
from mcp_server.auth import CallContext
from mcp_server.registry import tool
-from mcp_server.tools._helpers import num, parse_date, parse_uuid, parse_uuid_list, resolve_workspace_id
+from mcp_server.tools._helpers import (
+ num,
+ parse_date,
+ parse_uuid,
+ parse_uuid_list,
+ resolve_workspace_id,
+)
# Repeated in EVERY propose_* tool description. The LLM reads these when
@@ -86,14 +93,19 @@ def _can_apply(ctx: CallContext, apply: bool) -> bool:
@tool(
name="propose_categorize",
- description=_PROPOSAL_PREFACE + (
+ description=_PROPOSAL_PREFACE
+ + (
"Build a preview for re-categorizing one or more transactions. "
"Returns a summary of what would change and the resolved category."
),
parameters={
"type": "object",
"properties": {
- "transaction_ids": {"type": "array", "items": {"type": "string", "format": "uuid"}, "minItems": 1},
+ "transaction_ids": {
+ "type": "array",
+ "items": {"type": "string", "format": "uuid"},
+ "minItems": 1,
+ },
"category_id": {"type": "string", "format": "uuid"},
"apply": _APPLY_FIELD,
},
@@ -113,20 +125,35 @@ async def propose_categorize(
) -> dict[str, Any]:
ws_id = await resolve_workspace_id(session, ctx)
cat_id = parse_uuid(category_id)
- cat = (await session.execute(
- select(Category).where(Category.id == cat_id, Category.workspace_id == ws_id)
- )).scalar_one_or_none()
+ cat = (
+ await session.execute(
+ select(Category).where(Category.id == cat_id, Category.workspace_id == ws_id)
+ )
+ ).scalar_one_or_none()
if cat is None:
return {"error": "category not found"}
tx_ids = parse_uuid_list(transaction_ids) or []
- txs = (await session.execute(
- select(Transaction).where(Transaction.id.in_(tx_ids), Transaction.workspace_id == ws_id)
- )).scalars().all()
+ txs = (
+ (
+ await session.execute(
+ select(Transaction).where(
+ Transaction.id.in_(tx_ids), Transaction.workspace_id == ws_id
+ )
+ )
+ )
+ .scalars()
+ .all()
+ )
affected = [
- {"id": str(t.id), "description": t.description, "amount": num(t.amount), "currency": t.currency,
- "current_category_id": str(t.category_id) if t.category_id else None}
+ {
+ "id": str(t.id),
+ "description": t.description,
+ "amount": num(t.amount),
+ "currency": t.currency,
+ "current_category_id": str(t.category_id) if t.category_id else None,
+ }
for t in txs
]
preview = {
@@ -141,8 +168,9 @@ async def propose_categorize(
if _can_apply(ctx, apply):
if not affected:
return {**preview, "error": "no matching transactions to update"}
+ tx_uuids = [u for a in affected if (u := parse_uuid(a["id"])) is not None]
updated = await transaction_service.bulk_update_category(
- session, ws_id, [parse_uuid(a["id"]) for a in affected], cat.id
+ session, ws_id, tx_uuids, cat.id
)
return {**preview, "applied": True, "updated_count": updated}
@@ -151,7 +179,8 @@ async def propose_categorize(
@tool(
name="propose_create_category",
- description=_PROPOSAL_PREFACE + (
+ description=_PROPOSAL_PREFACE
+ + (
"Preview the creation of a new category. Returns the proposed shape "
"and any name collision detected."
),
@@ -181,12 +210,14 @@ async def propose_create_category(
apply: bool = False,
) -> dict[str, Any]:
ws_id = await resolve_workspace_id(session, ctx)
- existing = (await session.execute(
- select(Category.id, Category.name).where(
- Category.workspace_id == ws_id,
- Category.name.ilike(name.strip()),
+ existing = (
+ await session.execute(
+ select(Category.id, Category.name).where(
+ Category.workspace_id == ws_id,
+ Category.name.ilike(name.strip()),
+ )
)
- )).first()
+ ).first()
preview = {
"kind": "create_category",
"proposed": {
@@ -220,7 +251,8 @@ async def propose_create_category(
@tool(
name="propose_create_budget",
- description=_PROPOSAL_PREFACE + (
+ description=_PROPOSAL_PREFACE
+ + (
"Preview a budget creation for a category and month. Returns the "
"proposal plus any existing budget for the same category/month. "
"STRICT: if the user mentions a category that does NOT match an "
@@ -260,9 +292,11 @@ async def propose_create_budget(
cat_id = parse_uuid(category_id)
target_month = (parse_date(month) or date.today()).replace(day=1)
- cat = (await session.execute(
- select(Category).where(Category.id == cat_id, Category.workspace_id == ws_id)
- )).scalar_one_or_none()
+ cat = (
+ await session.execute(
+ select(Category).where(Category.id == cat_id, Category.workspace_id == ws_id)
+ )
+ ).scalar_one_or_none()
if cat is None:
return {"error": "category not found"}
@@ -298,7 +332,8 @@ async def propose_create_budget(
@tool(
name="propose_create_transaction",
- description=_PROPOSAL_PREFACE + (
+ description=_PROPOSAL_PREFACE
+ + (
"Build a preview for adding a one-off transaction (e.g. 'add a "
"R$50 lunch today'). Validates the account/category exist; "
"leaves currency to the account's default when not provided.\n\n"
@@ -314,14 +349,26 @@ async def propose_create_budget(
"type": "object",
"properties": {
"description": {"type": "string", "minLength": 1, "maxLength": 500},
- "amount": {"type": "number", "exclusiveMinimum": 0, "description": "Absolute value, always positive — direction comes from `type`"},
- "type": {"type": "string", "enum": ["debit", "credit"], "description": "debit = expense, credit = income"},
+ "amount": {
+ "type": "number",
+ "exclusiveMinimum": 0,
+ "description": "Absolute value, always positive — direction comes from `type`",
+ },
+ "type": {
+ "type": "string",
+ "enum": ["debit", "credit"],
+ "description": "debit = expense, credit = income",
+ },
"account_id": {"type": "string", "format": "uuid"},
"category_id": {"type": "string", "format": "uuid"},
"date": {"type": "string", "format": "date", "description": "Defaults to today"},
"currency": {"type": "string", "description": "Defaults to the account's currency"},
"notes": {"type": "string"},
- "group_id": {"type": "string", "format": "uuid", "description": "Optional: attach to an expense-sharing group"},
+ "group_id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Optional: attach to an expense-sharing group",
+ },
"splits": {
"type": "object",
"description": "Required when `group_id` is set. Defines how the amount is split among group members.",
@@ -334,8 +381,14 @@ async def propose_create_budget(
"type": "object",
"properties": {
"member_id": {"type": "string", "format": "uuid"},
- "share_amount": {"type": "number", "description": "Required for share_type='exact' (sum must equal `amount`)"},
- "share_pct": {"type": "number", "description": "Required for share_type='percent' (must sum to 100)"},
+ "share_amount": {
+ "type": "number",
+ "description": "Required for share_type='exact' (sum must equal `amount`)",
+ },
+ "share_pct": {
+ "type": "number",
+ "description": "Required for share_type='percent' (must sum to 100)",
+ },
},
"required": ["member_id"],
"additionalProperties": False,
@@ -371,17 +424,23 @@ async def propose_create_transaction(
) -> dict[str, Any]:
ws_id = await resolve_workspace_id(session, ctx)
acc_id = parse_uuid(account_id)
- acc = (await session.execute(
- select(Account).where(Account.id == acc_id, Account.workspace_id == ws_id)
- )).scalar_one_or_none()
+ acc = (
+ await session.execute(
+ select(Account).where(Account.id == acc_id, Account.workspace_id == ws_id)
+ )
+ ).scalar_one_or_none()
if acc is None:
return {"error": "account not found"}
cat = None
if category_id:
- cat = (await session.execute(
- select(Category).where(Category.id == parse_uuid(category_id), Category.workspace_id == ws_id)
- )).scalar_one_or_none()
+ cat = (
+ await session.execute(
+ select(Category).where(
+ Category.id == parse_uuid(category_id), Category.workspace_id == ws_id
+ )
+ )
+ ).scalar_one_or_none()
if cat is None:
return {"error": "category not found"}
@@ -395,9 +454,11 @@ async def propose_create_transaction(
# Group ownership stays user-scoped (Splitwise authorship check) —
# the user_id column on `groups` represents the owner, not a
# tenant filter.
- group = (await session.execute(
- select(Group).where(Group.id == gid, Group.user_id == ctx.user_id)
- )).scalar_one_or_none()
+ group = (
+ await session.execute(
+ select(Group).where(Group.id == gid, Group.user_id == ctx.user_id)
+ )
+ ).scalar_one_or_none()
if group is None:
return {"error": "group not found"}
group_name = group.name
@@ -409,9 +470,17 @@ async def propose_create_transaction(
if not members_in:
return {"error": "splits.members must not be empty"}
member_ids = [parse_uuid(m["member_id"]) for m in members_in]
- rows = (await session.execute(
- select(GroupMember).where(GroupMember.id.in_(member_ids), GroupMember.group_id == gid)
- )).scalars().all()
+ rows = (
+ (
+ await session.execute(
+ select(GroupMember).where(
+ GroupMember.id.in_(member_ids), GroupMember.group_id == gid
+ )
+ )
+ )
+ .scalars()
+ .all()
+ )
if len(rows) != len(set(member_ids)):
return {"error": "one or more members do not belong to the given group"}
name_by_id = {m.id: m.name for m in rows}
@@ -455,12 +524,14 @@ async def propose_create_transaction(
else:
share = round(amt * float(m.get("share_pct") or 0) / 100.0, 2)
running += share
- splits_preview.append({
- "member_id": str(m["member_id"]),
- "member_name": name_by_id.get(parse_uuid(m["member_id"]), "?"),
- "share_amount": share,
- "share_pct": float(m.get("share_pct") or 0),
- })
+ splits_preview.append(
+ {
+ "member_id": str(m["member_id"]),
+ "member_name": name_by_id.get(parse_uuid(m["member_id"]), "?"),
+ "share_amount": share,
+ "share_pct": float(m.get("share_pct") or 0),
+ }
+ )
target_date = parse_date(date) or _today()
proposed: dict[str, Any] = {
@@ -476,6 +547,7 @@ async def propose_create_transaction(
"notes": (notes or None),
}
if splits_preview is not None:
+ assert splits is not None
proposed["group_id"] = group_id
proposed["group_name"] = group_name
proposed["splits"] = {
@@ -497,11 +569,16 @@ async def propose_create_transaction(
share_type=splits["share_type"],
splits=[
TransactionSplitInput(
- group_member_id=parse_uuid(m["member_id"]),
- share_amount=Decimal(str(m["share_amount"])) if m.get("share_amount") is not None else None,
- share_pct=Decimal(str(m["share_pct"])) if m.get("share_pct") is not None else None,
+ group_member_id=mid,
+ share_amount=Decimal(str(m["share_amount"]))
+ if m.get("share_amount") is not None
+ else None,
+ share_pct=Decimal(str(m["share_pct"]))
+ if m.get("share_pct") is not None
+ else None,
)
for m in splits["members"]
+ if (mid := parse_uuid(m["member_id"])) is not None
],
)
try:
@@ -530,7 +607,8 @@ async def propose_create_transaction(
@tool(
name="propose_create_recurring_transaction",
- description=_PROPOSAL_PREFACE + (
+ description=_PROPOSAL_PREFACE
+ + (
"Build a preview for adding a recurring transaction / subscription "
"(e.g. 'Netflix R$55 every month on the 10th'). Frequency is one "
"of weekly/monthly/quarterly/yearly. For monthly or quarterly use "
@@ -576,16 +654,24 @@ async def propose_create_recurring_transaction(
if frequency in ("monthly", "quarterly") and not day_of_month:
return {"error": "day_of_month is required for monthly or quarterly frequency"}
ws_id = await resolve_workspace_id(session, ctx)
- acc = (await session.execute(
- select(Account).where(Account.id == parse_uuid(account_id), Account.workspace_id == ws_id)
- )).scalar_one_or_none()
+ acc = (
+ await session.execute(
+ select(Account).where(
+ Account.id == parse_uuid(account_id), Account.workspace_id == ws_id
+ )
+ )
+ ).scalar_one_or_none()
if acc is None:
return {"error": "account not found"}
cat = None
if category_id:
- cat = (await session.execute(
- select(Category).where(Category.id == parse_uuid(category_id), Category.workspace_id == ws_id)
- )).scalar_one_or_none()
+ cat = (
+ await session.execute(
+ select(Category).where(
+ Category.id == parse_uuid(category_id), Category.workspace_id == ws_id
+ )
+ )
+ ).scalar_one_or_none()
if cat is None:
return {"error": "category not found"}
@@ -636,7 +722,8 @@ async def propose_create_recurring_transaction(
@tool(
name="propose_update_recurring_transaction",
- description=_PROPOSAL_PREFACE + (
+ description=_PROPOSAL_PREFACE
+ + (
"Build a preview for editing an existing recurring transaction "
"(e.g. 'update my salary to R$8,000', 'change Netflix to R$60'). "
"Pass the recurring_id and only the fields you want to change. "
@@ -678,19 +765,25 @@ async def propose_update_recurring_transaction(
) -> dict[str, Any]:
ws_id = await resolve_workspace_id(session, ctx)
rid = parse_uuid(recurring_id)
- rt = (await session.execute(
- select(RecurringTransaction).where(
- RecurringTransaction.id == rid, RecurringTransaction.workspace_id == ws_id
+ rt = (
+ await session.execute(
+ select(RecurringTransaction).where(
+ RecurringTransaction.id == rid, RecurringTransaction.workspace_id == ws_id
+ )
)
- )).scalar_one_or_none()
+ ).scalar_one_or_none()
if rt is None:
return {"error": "recurring transaction not found"}
cat = None
if category_id:
- cat = (await session.execute(
- select(Category).where(Category.id == parse_uuid(category_id), Category.workspace_id == ws_id)
- )).scalar_one_or_none()
+ cat = (
+ await session.execute(
+ select(Category).where(
+ Category.id == parse_uuid(category_id), Category.workspace_id == ws_id
+ )
+ )
+ ).scalar_one_or_none()
if cat is None:
return {"error": "category not found"}
@@ -704,7 +797,8 @@ async def propose_update_recurring_transaction(
if day_of_month is not None:
changes["day_of_month"] = int(day_of_month)
if end_date is not None:
- changes["end_date"] = parse_date(end_date).isoformat() if end_date else None
+ parsed_end = parse_date(end_date)
+ changes["end_date"] = parsed_end.isoformat() if parsed_end else None
if cat is not None:
changes["category_id"] = str(cat.id)
if is_active is not None:
@@ -739,7 +833,9 @@ async def propose_update_recurring_transaction(
if "day_of_month" in changes:
update_data["day_of_month"] = changes["day_of_month"]
if "end_date" in changes:
- update_data["end_date"] = parse_date(changes["end_date"]) if changes["end_date"] else None
+ update_data["end_date"] = (
+ parse_date(changes["end_date"]) if changes["end_date"] else None
+ )
if "category_id" in changes:
update_data["category_id"] = parse_uuid(changes["category_id"])
if "is_active" in changes:
@@ -756,7 +852,8 @@ async def propose_update_recurring_transaction(
@tool(
name="propose_cancel_recurring_transaction",
- description=_PROPOSAL_PREFACE + (
+ description=_PROPOSAL_PREFACE
+ + (
"Build a preview for cancelling a recurring transaction (e.g. "
"'cancel that subscription'). Two modes: 'deactivate' keeps the "
"history but stops future occurrences (recommended); 'delete' "
@@ -784,12 +881,14 @@ async def propose_cancel_recurring_transaction(
apply: bool = False,
) -> dict[str, Any]:
ws_id = await resolve_workspace_id(session, ctx)
- rt = (await session.execute(
- select(RecurringTransaction).where(
- RecurringTransaction.id == parse_uuid(recurring_id),
- RecurringTransaction.workspace_id == ws_id,
+ rt = (
+ await session.execute(
+ select(RecurringTransaction).where(
+ RecurringTransaction.id == parse_uuid(recurring_id),
+ RecurringTransaction.workspace_id == ws_id,
+ )
)
- )).scalar_one_or_none()
+ ).scalar_one_or_none()
if rt is None:
return {"error": "recurring transaction not found"}
@@ -833,7 +932,8 @@ async def propose_cancel_recurring_transaction(
@tool(
name="propose_create_goal",
- description=_PROPOSAL_PREFACE + (
+ description=_PROPOSAL_PREFACE
+ + (
"Build a preview for creating a savings/financial goal (e.g. "
"'set a R$10k goal for travel')."
),
@@ -844,7 +944,11 @@ async def propose_cancel_recurring_transaction(
"target_amount": {"type": "number", "exclusiveMinimum": 0},
"currency": {"type": "string", "description": "Defaults to user's primary currency"},
"deadline": {"type": "string", "format": "date"},
- "initial_amount": {"type": "number", "minimum": 0, "description": "How much you've already saved"},
+ "initial_amount": {
+ "type": "number",
+ "minimum": 0,
+ "description": "How much you've already saved",
+ },
"icon": {"type": "string"},
"color": {"type": "string", "pattern": "^#[0-9a-fA-F]{6}$"},
"apply": _APPLY_FIELD,
@@ -908,19 +1012,24 @@ async def propose_create_goal(
def _today():
from datetime import date as _d
+
return _d.today()
@tool(
name="propose_create_payee_rule",
- description=_PROPOSAL_PREFACE + (
+ description=_PROPOSAL_PREFACE
+ + (
"Preview a rule that auto-categorizes future transactions matching "
"a description pattern. Returns the proposed rule shape."
),
parameters={
"type": "object",
"properties": {
- "match_pattern": {"type": "string", "description": "Substring to match in transaction description (case-insensitive)"},
+ "match_pattern": {
+ "type": "string",
+ "description": "Substring to match in transaction description (case-insensitive)",
+ },
"category_id": {"type": "string", "format": "uuid"},
"apply": _APPLY_FIELD,
},
@@ -940,9 +1049,11 @@ async def propose_create_payee_rule(
) -> dict[str, Any]:
ws_id = await resolve_workspace_id(session, ctx)
cat_id = parse_uuid(category_id)
- cat = (await session.execute(
- select(Category).where(Category.id == cat_id, Category.workspace_id == ws_id)
- )).scalar_one_or_none()
+ cat = (
+ await session.execute(
+ select(Category).where(Category.id == cat_id, Category.workspace_id == ws_id)
+ )
+ ).scalar_one_or_none()
if cat is None:
return {"error": "category not found"}
diff --git a/backend/mcp_server/tools/transactions.py b/backend/mcp_server/tools/transactions.py
index 860a4a50..05c6983a 100644
--- a/backend/mcp_server/tools/transactions.py
+++ b/backend/mcp_server/tools/transactions.py
@@ -201,11 +201,11 @@ async def list_transactions(
"type": t.type,
"status": getattr(t, "status", None),
"category_id": str(t.category_id) if t.category_id else None,
- "category_name": t.category.name if getattr(t, "category", None) else None,
+ "category_name": t.category.name if t.category else None,
"account_id": str(t.account_id) if t.account_id else None,
"account_name": t.account.name if getattr(t, "account", None) else None,
"payee_id": str(t.payee_id) if getattr(t, "payee_id", None) else None,
- "payee_name": t.payee_entity.name if getattr(t, "payee_entity", None) else None,
+ "payee_name": t.payee_entity.name if t.payee_entity else None,
"tags": getattr(t, "tags", None),
"is_transfer": bool(getattr(t, "transfer_pair_id", None)),
"notes": getattr(t, "notes", None),
diff --git a/backend/pyproject.toml b/backend/pyproject.toml
index ce95752f..9ba99bb1 100644
--- a/backend/pyproject.toml
+++ b/backend/pyproject.toml
@@ -46,6 +46,11 @@ dev = [
# historical alembic/ migration import blocks. Bump deliberately (with the
# accompanying reformat) rather than letting CI float to a newer release.
"ruff>=0.1.0,<0.16",
+ # Pinned exactly, for the same reason as ruff above: ty is pre-1.0 and each
+ # 0.0.x release can add new checks, so letting it float would turn a green
+ # CI red on an unrelated PR. Bump deliberately, together with whatever
+ # annotations the new release asks for.
+ "ty==0.0.66",
]
[tool.setuptools.packages.find]
@@ -72,6 +77,11 @@ omit = [
"app/providers/market_price.py",
]
+[tool.ty.environment]
+# Match ruff's target-version: check against the oldest Python we support, so a
+# 3.12+-only construct is caught here rather than by a self-hoster on 3.11.
+python-version = "3.11"
+
[tool.ruff]
line-length = 100
target-version = "py311"
diff --git a/backend/scripts/seed_perf.py b/backend/scripts/seed_perf.py
index f67503c3..30185e83 100644
--- a/backend/scripts/seed_perf.py
+++ b/backend/scripts/seed_perf.py
@@ -25,6 +25,7 @@ import sys
import uuid
from datetime import date, timedelta
from decimal import Decimal
+from typing import NotRequired, TypedDict
# Allow running from repo root or backend root
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
@@ -115,7 +116,17 @@ ASSET_GROUP_TEMPLATES = [
{"name": "Collectibles", "icon": "gem", "color": "#a855f7"},
]
-ASSET_TEMPLATES = [
+class AssetTemplate(TypedDict):
+ name: str
+ type: str
+ currency: str
+ purchase: Decimal
+ base: Decimal
+ daily_pct: Decimal
+ group: NotRequired[str]
+
+
+ASSET_TEMPLATES: list[AssetTemplate] = [
{"name": "Primary Residence", "type": "real_estate", "currency": "USD", "purchase": Decimal("450000"), "base": Decimal("520000"), "daily_pct": Decimal("0.00110"), "group": "Real Estate"},
{"name": "Investment Property", "type": "real_estate", "currency": "USD", "purchase": Decimal("280000"), "base": Decimal("310000"), "daily_pct": Decimal("0.00082"), "group": "Real Estate"},
{"name": "Tesla Model 3", "type": "vehicle", "currency": "USD", "purchase": Decimal("45000"), "base": Decimal("28000"), "daily_pct": Decimal("-0.00219")},
@@ -206,6 +217,8 @@ async def seed(
user = await manager.create(UserCreate(email=email, password=password))
except UserAlreadyExists:
user = await session.scalar(select(User).where(User.email == email))
+ if user is None:
+ raise RuntimeError(f"Failed to create or look up user {email}")
await session.commit()
print(f" Created {user.id}")
else:
diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py
index 38d5bcc1..3dbb4bde 100644
--- a/backend/tests/conftest.py
+++ b/backend/tests/conftest.py
@@ -35,7 +35,7 @@ class _VectorJSON(sqlalchemy.types.JSON):
return literal(0.5)
-_pgv.Vector = _VectorJSON # type: ignore[attr-defined]
+setattr(_pgv, "Vector", _VectorJSON)
# ---------------------------------------------------------------------------
import pytest # noqa: E402
@@ -227,7 +227,7 @@ async def auth_token(client: AsyncClient, test_user: User) -> str:
@pytest_asyncio.fixture
-def auth_headers(auth_token: str) -> dict:
+async def auth_headers(auth_token: str) -> dict:
"""Auth headers for authenticated requests."""
return {"Authorization": f"Bearer {auth_token}"}
@@ -271,7 +271,7 @@ async def admin_auth_token(client: AsyncClient, test_superuser: User) -> str:
@pytest_asyncio.fixture
-def admin_auth_headers(admin_auth_token: str) -> dict:
+async def admin_auth_headers(admin_auth_token: str) -> dict:
"""Auth headers for admin requests."""
return {"Authorization": f"Bearer {admin_auth_token}"}
diff --git a/backend/tests/test_account_service.py b/backend/tests/test_account_service.py
index 8672fabd..3d1fcbc6 100644
--- a/backend/tests/test_account_service.py
+++ b/backend/tests/test_account_service.py
@@ -575,6 +575,8 @@ async def test_close_bank_connected_keeps_link(session: AsyncSession, test_user,
connection_id=test_connection.id, external_id="ext-close",
)
closed = await close_account(session, account.id, test_workspace.id)
+
+ assert closed is not None
assert closed.connection_id == test_connection.id
assert closed.is_closed is True
diff --git a/backend/tests/test_admin_service.py b/backend/tests/test_admin_service.py
index 5745afc2..ac8e0a1d 100644
--- a/backend/tests/test_admin_service.py
+++ b/backend/tests/test_admin_service.py
@@ -212,6 +212,8 @@ async def test_update_user_email(session: AsyncSession, clean_db):
target = await _make_user(session, "[email protected]")
data = AdminUserUpdate(email="[email protected]")
result = await update_user(session, target.id, data, admin.id)
+
+ assert result is not None
assert result.email == "[email protected]"
@@ -230,6 +232,7 @@ async def test_update_user_password(session: AsyncSession, clean_db):
old_hash = target.hashed_password
data = AdminUserUpdate(password="newpassword123")
result = await update_user(session, target.id, data, admin.id)
+
assert result is not None
# Password should have changed
assert result.hashed_password != old_hash
@@ -241,6 +244,9 @@ async def test_update_user_preferences(session: AsyncSession, clean_db):
new_prefs = {"language": "pt-BR", "currency_display": "BRL"}
data = AdminUserUpdate(preferences=new_prefs)
result = await update_user(session, target.id, data, admin.id)
+
+ assert result is not None
+ assert result.preferences is not None
assert result.preferences["language"] == "pt-BR"
@@ -270,6 +276,8 @@ async def test_update_user_is_active_and_superuser(session: AsyncSession, clean_
target = await _make_user(session, "[email protected]")
data = AdminUserUpdate(is_active=False, is_superuser=True)
result = await update_user(session, target.id, data, admin.id)
+
+ assert result is not None
assert result.is_active is False
assert result.is_superuser is True
diff --git a/backend/tests/test_agents_connection_service.py b/backend/tests/test_agents_connection_service.py
index 3c809baf..234a6347 100644
--- a/backend/tests/test_agents_connection_service.py
+++ b/backend/tests/test_agents_connection_service.py
@@ -61,9 +61,13 @@ async def test_default_is_unique_per_user(session, test_user):
)
# Re-fetch a — its default flag should be cleared.
refreshed_a = await cs.get_connection(session, a.id, test_user.id)
+
+ assert refreshed_a is not None
await session.refresh(refreshed_a)
assert refreshed_a.is_default is False
refreshed_b = await cs.get_connection(session, b.id, test_user.id)
+
+ assert refreshed_b is not None
await session.refresh(refreshed_b)
assert refreshed_b.is_default is True
@@ -90,6 +94,8 @@ async def test_update_connection_handles_partial_and_default_swap(session, test_
# a should be demoted.
refreshed_a = await cs.get_connection(session, a.id, test_user.id)
+
+ assert refreshed_a is not None
await session.refresh(refreshed_a)
assert refreshed_a.is_default is False
@@ -110,9 +116,11 @@ async def test_update_connection_can_clear_api_key(session, test_user):
conn = await cs.create_connection(
session, test_user.id, name="x", kind="openai", api_key="sk-old",
)
+
assert conn.api_key_encrypted is not None
out = await cs.update_connection(session, conn.id, test_user.id, api_key="")
+ assert out is not None
assert out.api_key_encrypted is None
diff --git a/backend/tests/test_agents_connections.py b/backend/tests/test_agents_connections.py
index 63f8d019..658d7994 100644
--- a/backend/tests/test_agents_connections.py
+++ b/backend/tests/test_agents_connections.py
@@ -87,6 +87,8 @@ async def test_only_one_default_per_user(session: AsyncSession, test_user: User)
)
# Re-fetch a — should no longer be default.
a_after = await connection_service.get_connection(session, a.id, test_user.id)
+
+ assert a_after is not None
assert a_after.is_default is False
assert b.is_default is True
@@ -101,6 +103,8 @@ async def test_update_keeps_existing_key_when_api_key_omitted(session: AsyncSess
updated = await connection_service.update_connection(
session, conn.id, test_user.id, name="renamed",
)
+
+ assert updated is not None
assert updated.api_key_encrypted == enc_before
assert decrypt(updated.api_key_encrypted) == "sk-original"
@@ -112,6 +116,8 @@ async def test_update_clears_key_with_empty_string(session: AsyncSession, test_u
updated = await connection_service.update_connection(
session, conn.id, test_user.id, api_key="",
)
+
+ assert updated is not None
assert updated.api_key_encrypted is None
diff --git a/backend/tests/test_agents_conversation_service.py b/backend/tests/test_agents_conversation_service.py
index 4744d766..d6e10651 100644
--- a/backend/tests/test_agents_conversation_service.py
+++ b/backend/tests/test_agents_conversation_service.py
@@ -103,12 +103,16 @@ async def test_update_title_if_empty_only_writes_when_blank(session, test_user,
# First call: title is None → should fill in.
await svc.update_title_if_empty(session, conv.id, "Auto generated")
refreshed = await svc.get_conversation(session, conv.id, test_workspace.id)
+
+ assert refreshed is not None
await session.refresh(refreshed)
assert refreshed.title == "Auto generated"
# Second call: title already set → should NOT overwrite.
await svc.update_title_if_empty(session, conv.id, "Different title")
refreshed = await svc.get_conversation(session, conv.id, test_workspace.id)
+
+ assert refreshed is not None
await session.refresh(refreshed)
assert refreshed.title == "Auto generated"
@@ -126,7 +130,9 @@ async def test_update_title_truncates_to_200_chars(session, test_user, test_work
)
long_title = "x" * 500
out = await svc.update_title(session, conv.id, test_workspace.id,long_title)
+
assert out is not None
+ assert out.title is not None
assert len(out.title) == 200
diff --git a/backend/tests/test_agents_ingest.py b/backend/tests/test_agents_ingest.py
index e2be9572..494c7ef9 100644
--- a/backend/tests/test_agents_ingest.py
+++ b/backend/tests/test_agents_ingest.py
@@ -63,6 +63,8 @@ async def test_do_ingest_happy_path_writes_chunks_and_marks_ready(
assert result == {"ok": True, "chunks": 2}
refreshed = await knowledge_service.get_doc(session, doc.id, test_user.id)
+
+ assert refreshed is not None
# The session_maker inside _do_ingest commits — we need a fresh read.
await session.refresh(refreshed)
assert refreshed.status == "ready"
@@ -97,6 +99,8 @@ async def test_do_ingest_marks_failed_when_storage_unreadable(
assert result == {"ok": False, "reason": "read failed"}
refreshed = await knowledge_service.get_doc(session, doc.id, test_user.id)
+
+ assert refreshed is not None
await session.refresh(refreshed)
assert refreshed.status == "failed"
assert "read failed" in (refreshed.error or "")
@@ -123,6 +127,8 @@ async def test_do_ingest_marks_failed_when_no_extractable_text(
assert result == {"ok": False, "reason": "no text"}
refreshed = await knowledge_service.get_doc(session, doc.id, test_user.id)
+
+ assert refreshed is not None
await session.refresh(refreshed)
assert refreshed.status == "failed"
assert "no extractable text" in (refreshed.error or "")
@@ -155,6 +161,8 @@ async def test_do_ingest_marks_failed_when_embedding_fails(
assert result == {"ok": False, "reason": "embed failed"}
refreshed = await knowledge_service.get_doc(session, doc.id, test_user.id)
+
+ assert refreshed is not None
await session.refresh(refreshed)
assert refreshed.status == "failed"
assert "embed failed" in (refreshed.error or "")
diff --git a/backend/tests/test_agents_jwt.py b/backend/tests/test_agents_jwt.py
index e47a1302..b755b9b6 100644
--- a/backend/tests/test_agents_jwt.py
+++ b/backend/tests/test_agents_jwt.py
@@ -6,16 +6,26 @@ Both sides share AGENTS_MCP_JWT_SECRET. We test that:
- Expired tokens are rejected.
- Missing audience / issuer is rejected.
"""
+
import time
import uuid
import pytest
from jose import jwt
+from starlette.requests import Request
from app.agents.config import get_agent_settings
from app.agents.mcp.auth import JWT_ALGO, JWT_AUDIENCE, JWT_ISSUER, mint_token
+def _req(headers: list[tuple[bytes, bytes]]) -> Request:
+ return Request(scope={"type": "http", "headers": headers})
+
+
+def _req_bearer(token: str) -> Request:
+ return _req([(b"authorization", f"Bearer {token}".encode())])
+
+
def test_mint_then_verify_roundtrip():
from mcp_server.auth import verify_request
@@ -24,11 +34,7 @@ def test_mint_then_verify_roundtrip():
agent_id = uuid.uuid4()
token = mint_token(user_id=user_id, conversation_id=conv_id, agent_id=agent_id)
- # Stub Request just enough for verify_request — it only reads the header.
- class _Req:
- headers = {"authorization": f"Bearer {token}"}
-
- ctx = verify_request(_Req()) # type: ignore[arg-type]
+ ctx = verify_request(_req_bearer(token))
assert ctx.user_id == user_id
assert ctx.conversation_id == conv_id
assert ctx.agent_id == agent_id
@@ -38,11 +44,8 @@ def test_missing_authorization_rejected():
from fastapi import HTTPException
from mcp_server.auth import verify_request
- class _Req:
- headers: dict[str, str] = {}
-
with pytest.raises(HTTPException) as exc:
- verify_request(_Req()) # type: ignore[arg-type]
+ _ = verify_request(_req([]))
assert exc.value.status_code == 401
@@ -63,11 +66,8 @@ def test_wrong_secret_rejected():
algorithm=JWT_ALGO,
)
- class _Req:
- headers = {"authorization": f"Bearer {bogus}"}
-
with pytest.raises(HTTPException) as exc:
- verify_request(_Req()) # type: ignore[arg-type]
+ _ = verify_request(_req_bearer(bogus))
assert exc.value.status_code == 401
@@ -89,11 +89,8 @@ def test_expired_token_rejected():
algorithm=JWT_ALGO,
)
- class _Req:
- headers = {"authorization": f"Bearer {expired}"}
-
with pytest.raises(HTTPException) as exc:
- verify_request(_Req()) # type: ignore[arg-type]
+ _ = verify_request(_req_bearer(expired))
assert exc.value.status_code == 401
@@ -105,11 +102,8 @@ def test_short_ttl_respected():
token = mint_token(user_id=uuid.uuid4(), ttl_seconds=1)
time.sleep(2.1)
- class _Req:
- headers = {"authorization": f"Bearer {token}"}
-
with pytest.raises(HTTPException):
- verify_request(_Req()) # type: ignore[arg-type]
+ _ = verify_request(_req_bearer(token))
def test_optional_conv_id_is_truly_optional():
@@ -117,10 +111,7 @@ def test_optional_conv_id_is_truly_optional():
token = mint_token(user_id=uuid.uuid4())
- class _Req:
- headers = {"authorization": f"Bearer {token}"}
-
- ctx = verify_request(_Req()) # type: ignore[arg-type]
+ ctx = verify_request(_req_bearer(token))
assert ctx.conversation_id is None
assert ctx.agent_id is None
@@ -130,10 +121,7 @@ def test_external_token_round_trip():
token = mint_token(user_id=uuid.uuid4(), external=True)
- class _Req:
- headers = {"authorization": f"Bearer {token}"}
-
- ctx = verify_request(_Req()) # type: ignore[arg-type]
+ ctx = verify_request(_req_bearer(token))
assert ctx.external is True
@@ -142,8 +130,5 @@ def test_default_token_has_no_external_flag():
token = mint_token(user_id=uuid.uuid4())
- class _Req:
- headers = {"authorization": f"Bearer {token}"}
-
- ctx = verify_request(_Req()) # type: ignore[arg-type]
+ ctx = verify_request(_req_bearer(token))
assert ctx.external is False
diff --git a/backend/tests/test_agents_knowledge_service.py b/backend/tests/test_agents_knowledge_service.py
index f7963a17..c99837c1 100644
--- a/backend/tests/test_agents_knowledge_service.py
+++ b/backend/tests/test_agents_knowledge_service.py
@@ -81,6 +81,8 @@ async def test_upload_doc_sanitizes_disk_filename(session, test_agent, test_user
mime="text/plain",
payload=b"x",
)
+
+ assert doc.storage_path is not None
assert "../" not in doc.storage_path.split("/", 5)[-1] # no traversal in stored basename
assert os.path.dirname(doc.storage_path) == os.path.abspath(os.path.dirname(doc.storage_path))
@@ -128,6 +130,8 @@ async def test_delete_doc_removes_row_and_file(session, test_agent, test_user):
filename="delete-me.txt", mime="text/plain", payload=b"hi",
)
path = doc.storage_path
+
+ assert path is not None
assert os.path.exists(path)
ok = await knowledge_service.delete_doc(session, doc.id, test_user.id)
assert ok is True
@@ -143,6 +147,8 @@ async def test_delete_doc_swallows_missing_file_on_disk(session, test_agent, tes
session, agent_id=test_agent.id, user_id=test_user.id,
filename="ghost.txt", mime="text/plain", payload=b"x",
)
+
+ assert doc.storage_path is not None
os.remove(doc.storage_path)
assert await knowledge_service.delete_doc(session, doc.id, test_user.id) is True
@@ -176,11 +182,15 @@ async def test_mark_status_ready_clears_prior_error(session, test_agent, test_us
# Initial failure → error message stored.
await knowledge_service.mark_status(session, doc.id, status="failed", error="embed failed: 500")
refreshed = await knowledge_service.get_doc(session, doc.id, test_user.id)
+
+ assert refreshed is not None
assert refreshed.status == "failed"
assert "embed failed" in (refreshed.error or "")
# Subsequent success → status flips AND prior error cleared.
await knowledge_service.mark_status(session, doc.id, status="ready", chunk_count=4)
refreshed = await knowledge_service.get_doc(session, doc.id, test_user.id)
+
+ assert refreshed is not None
assert refreshed.status == "ready"
assert refreshed.error is None
assert refreshed.chunk_count == 4
@@ -195,6 +205,8 @@ async def test_mark_status_failed_preserves_prior_status_metadata(session, test_
await knowledge_service.mark_status(session, doc.id, status="processing")
await knowledge_service.mark_status(session, doc.id, status="failed", error="parse failed")
refreshed = await knowledge_service.get_doc(session, doc.id, test_user.id)
+
+ assert refreshed is not None
assert refreshed.status == "failed"
assert "parse failed" in (refreshed.error or "")
diff --git a/backend/tests/test_agents_mcp_client.py b/backend/tests/test_agents_mcp_client.py
index 41ad80b9..219cedf4 100644
--- a/backend/tests/test_agents_mcp_client.py
+++ b/backend/tests/test_agents_mcp_client.py
@@ -46,7 +46,7 @@ class _FakeAsyncClient:
pass
queue: list[_FakeResponse] = []
- calls: list[tuple[str, dict, dict]] = []
+ calls: list[tuple[str, dict | None, dict | None]] = []
async def __aenter__(self):
return self
@@ -143,6 +143,8 @@ async def test_list_tools_parses_securo_extras_and_defaults_schema():
assert by_name["create_payee"].parameters == {"type": "object", "properties": {}}
# Bearer header is propagated.
_, _, headers = _FakeAsyncClient.calls[0]
+
+ assert headers is not None
assert headers["Authorization"] == "Bearer fake"
@@ -237,7 +239,7 @@ def test_to_provider_tools_namespaces_and_filters():
filtered = MCPRegistry.to_provider_tools(handles, allowed={("securo", "list_accounts")})
assert [t.name for t in filtered] == ["securo__list_accounts"]
# Defaults a missing parameters schema to an empty object schema.
- handle_no_schema = ToolHandle(server="x", name="y", description="d", parameters=None) # type: ignore[arg-type]
+ handle_no_schema = ToolHandle(server="x", name="y", description="d", parameters={})
out = MCPRegistry.to_provider_tools([handle_no_schema], allowed=None)
assert out[0].parameters == {"type": "object", "properties": {}}
diff --git a/backend/tests/test_agents_mcp_tools.py b/backend/tests/test_agents_mcp_tools.py
index 2409be09..1f447dd9 100644
--- a/backend/tests/test_agents_mcp_tools.py
+++ b/backend/tests/test_agents_mcp_tools.py
@@ -21,7 +21,7 @@ pytestmark = pytest.mark.asyncio
@pytest_asyncio.fixture
-def ctx(test_user) -> CallContext:
+async def ctx(test_user) -> CallContext:
return CallContext(user_id=test_user.id, conversation_id=uuid.uuid4())
diff --git a/backend/tests/test_agents_providers.py b/backend/tests/test_agents_providers.py
index c772a373..72442d20 100644
--- a/backend/tests/test_agents_providers.py
+++ b/backend/tests/test_agents_providers.py
@@ -178,7 +178,7 @@ async def test_openai_parser_handles_index_keyed_tool_call_chunks():
def stream(self, *_a, **_kw): return _StreamResp()
p = OpenAIProvider(api_key="x", base_url="http://lmstudio:1234")
- chunks = []
+ chunks: list[ChatChunk] = []
with patch("httpx.AsyncClient", return_value=_Client()):
async for c in p.chat_stream([ChatMessage(role="user", content="hi")], model="m"):
chunks.append(c)
@@ -188,7 +188,11 @@ async def test_openai_parser_handles_index_keyed_tool_call_chunks():
assert starts[0].tool_name == "propose_categorize"
assert starts[0].tool_call_id == "call_abc"
- arg_deltas = [c.args_delta for c in chunks if c.type == "tool_call_args_delta"]
+ arg_deltas = [
+ c.args_delta for c in chunks
+ if c.type == "tool_call_args_delta"
+ and c.args_delta is not None
+ ]
assert "".join(arg_deltas) == '{"transaction_ids":["abc"],"category_id":"def"}'
ends = [c for c in chunks if c.type == "tool_call_end"]
diff --git a/backend/tests/test_agents_providers_streaming.py b/backend/tests/test_agents_providers_streaming.py
index 0bb9ef42..352073c7 100644
--- a/backend/tests/test_agents_providers_streaming.py
+++ b/backend/tests/test_agents_providers_streaming.py
@@ -229,7 +229,7 @@ async def test_anthropic_chat_stream_parses_text_block_sequence():
text = "".join(c.text or "" for c in chunks if c.type == "text_delta")
assert text == "Hi!"
- assert any(c.type == "usage" and c.usage.output_tokens == 2 for c in chunks)
+ assert any(c.type == "usage" and c.usage is not None and c.usage.output_tokens == 2 for c in chunks)
assert any(c.type == "finish" and c.finish_reason == "end_turn" for c in chunks)
diff --git a/backend/tests/test_asset_service.py b/backend/tests/test_asset_service.py
index 1c6619ee..52421511 100644
--- a/backend/tests/test_asset_service.py
+++ b/backend/tests/test_asset_service.py
@@ -13,6 +13,8 @@ from app.models.user import User
from app.schemas.asset import AssetCreate, AssetUpdate, AssetValueCreate
from app.services import asset_service
from app.services.asset_service import (
+ TxRecord,
+ ValueRecord,
_compute_current_value,
_generate_growth_values,
_next_due_date,
@@ -23,12 +25,12 @@ from app.services.asset_service import (
def test_build_market_value_series_reflects_quantity_over_time():
"""A backdated buy steps the value up from its date, not just today."""
- rows = [
+ rows: list[ValueRecord] = [
(date(2026, 5, 12), Decimal("9286"), Decimal("46.43")),
(date(2026, 5, 17), Decimal("9094"), Decimal("45.47")),
(date(2026, 6, 11), Decimal("8330"), Decimal("41.65")),
]
- txs = [
+ txs: list[TxRecord] = [
(date(2025, 12, 1), "buy", Decimal("200"), Decimal("40")),
(date(2026, 5, 15), "buy", Decimal("50"), Decimal("46")), # backdated, between value points
]
@@ -44,12 +46,12 @@ def test_build_market_value_series_reflects_quantity_over_time():
def test_build_market_value_series_handles_sell_and_missing_price():
- rows = [
+ rows: list[ValueRecord] = [
(date(2026, 1, 1), Decimal("1000"), Decimal("10")), # 100 units
(date(2026, 2, 1), Decimal("0"), Decimal("12")), # after selling 40 → 60 units
(date(2026, 3, 1), Decimal("777"), None), # no price → fall back to amount
]
- txs = [
+ txs: list[TxRecord] = [
(date(2026, 1, 1), "buy", Decimal("100"), Decimal("10")),
(date(2026, 1, 20), "sell", Decimal("40"), Decimal("11")),
]
@@ -67,8 +69,8 @@ def test_build_market_value_series_backdated_trades_predating_prices():
dates), so every backdated buy must still produce a dated point — otherwise
the chart collapses them onto one anchor and draws a single interpolation.
"""
- rows = [(date(2026, 6, 15), Decimal("5335.56"), Decimal("296.42"))]
- txs = [
+ rows: list[ValueRecord] = [(date(2026, 6, 15), Decimal("5335.56"), Decimal("296.42"))]
+ txs: list[TxRecord] = [
(date(2021, 1, 15), "buy", Decimal("10"), Decimal("50")),
(date(2022, 2, 2), "buy", Decimal("5"), Decimal("80")),
(date(2022, 4, 11), "buy", Decimal("3"), Decimal("120")),
@@ -83,7 +85,7 @@ def test_build_market_value_series_backdated_trades_predating_prices():
def test_build_market_value_series_no_ledger_keeps_amounts():
"""A holding with no transactions must not be zeroed — keep stored amounts."""
- rows = [
+ rows: list[ValueRecord] = [
(date(2026, 1, 1), Decimal("500"), Decimal("5")),
(date(2026, 2, 1), Decimal("600"), Decimal("6")),
]
@@ -815,6 +817,7 @@ async def test_update_asset_purchase_price(session: AsyncSession, test_user: Use
created = await asset_service.create_asset(session, test_workspace.id, test_user.id, data)
update_data = AssetUpdate(purchase_price=Decimal("2000"))
updated = await asset_service.update_asset(session, created.id, test_workspace.id, test_user.id, update_data)
+ assert updated is not None
assert updated.purchase_price == 2000.0
diff --git a/backend/tests/test_asset_transaction_service.py b/backend/tests/test_asset_transaction_service.py
index 3d667eea..6665fcee 100644
--- a/backend/tests/test_asset_transaction_service.py
+++ b/backend/tests/test_asset_transaction_service.py
@@ -154,8 +154,12 @@ async def test_add_buys_sets_units_average_and_cost_basis(session, test_workspac
AssetTransactionCreate(kind="buy", quantity=Decimal("5"), price=Decimal("26"), date=date(2026, 2, 1)),
)
# avg = (200 + 130) / 15 = 22.00
+ assert read is not None
assert read.units == 15
+
+ assert read.average_price is not None
assert round(read.average_price, 2) == 22.00
+ assert read.total_invested is not None
assert round(read.total_invested, 2) == 330.00
assert read.transaction_count == 2
@@ -170,8 +174,11 @@ async def test_sell_records_realized_gain(session, test_workspace, market_asset)
session, market_asset.id, test_workspace.id,
AssetTransactionCreate(kind="sell", quantity=Decimal("4"), price=Decimal("30"), date=date(2026, 3, 1)),
)
+ assert read is not None
assert read.units == 6
+ assert read.average_price is not None
assert round(read.average_price, 2) == 20.00 # average unchanged by sell
+ assert read.realized_gain is not None
assert round(read.realized_gain, 2) == 40.00 # (30 - 20) * 4
@@ -182,7 +189,9 @@ async def test_delete_transaction_recomputes(session, test_workspace, market_ass
AssetTransactionCreate(kind="buy", quantity=Decimal("10"), price=Decimal("20"), date=date(2026, 1, 1)),
)
txs = await asset_transaction_service.list_asset_transactions(session, market_asset.id, test_workspace.id)
+ assert txs is not None
read = await asset_transaction_service.delete_transaction(session, txs[0].id, test_workspace.id)
+ assert read is not None
assert read.units == 0
assert read.average_price is None
@@ -194,10 +203,13 @@ async def test_update_transaction_recomputes(session, test_workspace, market_ass
AssetTransactionCreate(kind="buy", quantity=Decimal("10"), price=Decimal("20"), date=date(2026, 1, 1)),
)
txs = await asset_transaction_service.list_asset_transactions(session, market_asset.id, test_workspace.id)
+ assert txs is not None
read = await asset_transaction_service.update_transaction(
session, txs[0].id, test_workspace.id, AssetTransactionUpdate(quantity=Decimal("20")),
)
+ assert read is not None
assert read.units == 20
+ assert read.average_price is not None
assert round(read.average_price, 2) == 20.00
@@ -217,6 +229,7 @@ async def test_oversell_is_rejected(session, test_workspace, market_asset):
assert exc.value.status_code == 422
# The rejected sell must not have changed the position.
txs = await asset_transaction_service.list_asset_transactions(session, market_asset.id, test_workspace.id)
+ assert txs is not None
assert len(txs) == 1
@@ -230,6 +243,7 @@ async def test_sell_exact_holding_is_allowed(session, test_workspace, market_ass
session, market_asset.id, test_workspace.id,
AssetTransactionCreate(kind="sell", quantity=Decimal("10"), price=Decimal("30"), date=date(2026, 2, 1)),
)
+ assert read is not None
assert read.units == 0
@@ -255,9 +269,11 @@ async def test_full_exit_marks_sold(session, test_workspace, market_asset):
session, market_asset.id, test_workspace.id,
AssetTransactionCreate(kind="sell", quantity=Decimal("10"), price=Decimal("30"), date=date(2026, 6, 1)),
)
+ assert read is not None
assert read.units == 0
assert read.average_price is None
assert read.sell_date == date(2026, 6, 1) # drops out of the active portfolio
+ assert read.realized_gain is not None
assert round(read.realized_gain, 2) == 100.00
@@ -275,10 +291,13 @@ async def test_rebuy_after_full_exit_resets_position(session, test_workspace, ma
session, market_asset.id, test_workspace.id,
AssetTransactionCreate(kind="buy", quantity=Decimal("5"), price=Decimal("40"), date=date(2026, 3, 1)),
)
+ assert read is not None
assert read.units == 5
+ assert read.average_price is not None
assert round(read.average_price, 2) == 40.00
assert read.sell_date is None # re-entered → no longer "sold"
# Realized gain from the earlier round-trip is retained.
+ assert read.realized_gain is not None
assert round(read.realized_gain, 2) == 100.00
@@ -297,7 +316,9 @@ async def test_multiple_sells_accumulate_realized_gain(session, test_workspace,
AssetTransactionCreate(kind="sell", quantity=Decimal("2"), price=Decimal("25"), date=date(2026, 3, 1)),
)
# (30-20)*3 + (25-20)*2 = 30 + 10 = 40
+ assert read is not None
assert read.units == 5
+ assert read.realized_gain is not None
assert round(read.realized_gain, 2) == 40.00
@@ -348,7 +369,9 @@ async def test_buy_into_holding_consolidates_by_ticker(session, test_workspace,
)
# Same logical holding — not two assets.
assert first.id == second.id
+ assert second is not None
assert second.units == 20
+ assert second.average_price is not None
assert round(second.average_price, 2) == 60.00
all_vale = (
diff --git a/backend/tests/test_balance_service.py b/backend/tests/test_balance_service.py
index 84009479..6a5f0140 100644
--- a/backend/tests/test_balance_service.py
+++ b/backend/tests/test_balance_service.py
@@ -151,6 +151,7 @@ async def test_settlement_reduces_balance(
balances = await balance_service.compute_balances(
session, group.id, test_workspace.id, test_user.id
)
+ assert balances is not None
by_member = {ln["member_id"]: ln["amount"] for ln in balances["lines"]}
assert by_member[friend.id] == Decimal("15.00")
@@ -184,6 +185,7 @@ async def test_self_loan_increases_balance_owed(
balances = await balance_service.compute_balances(
session, group.id, test_workspace.id, test_user.id
)
+ assert balances is not None
by_member = {ln["member_id"]: ln["amount"] for ln in balances["lines"]}
assert by_member[friend.id] == Decimal("50.00")
@@ -219,6 +221,7 @@ async def test_balances_segregated_by_currency(
balances = await balance_service.compute_balances(
session, group.id, test_workspace.id, test_user.id
)
+ assert balances is not None
by_currency = {
ln["currency"]: ln["amount"]
for ln in balances["lines"]
@@ -272,6 +275,7 @@ async def test_balance_line_dropped_when_settlement_zeroes_out_split(
balances = await balance_service.compute_balances(
session, group.id, test_workspace.id, test_user.id
)
+ assert balances is not None
friend_lines = [ln for ln in balances["lines"] if ln["member_id"] == friend.id]
assert friend_lines == []
@@ -322,6 +326,7 @@ async def test_cross_member_settlements_are_ignored_in_owner_ledger(
balances = await balance_service.compute_balances(
session, group.id, test_workspace.id, test_user.id
)
+ assert balances is not None
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")
@@ -344,6 +349,8 @@ async def test_no_self_member_means_only_split_totals(
b = await group_service.create_member(
session, group.id, test_workspace.id, GroupMemberCreate(name="B")
)
+ assert a is not None
+ assert b is not None
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(
@@ -363,6 +370,7 @@ async def test_no_self_member_means_only_split_totals(
balances = await balance_service.compute_balances(
session, group.id, test_workspace.id, test_user.id
)
+ assert balances is not None
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_connection_service.py b/backend/tests/test_connection_service.py
index 24350731..834aecfe 100644
--- a/backend/tests/test_connection_service.py
+++ b/backend/tests/test_connection_service.py
@@ -235,6 +235,7 @@ async def test_update_settings_new(session: AsyncSession, test_user, test_worksp
session, conn.id, test_workspace.id, {"payee_source": "merchant"},
)
assert updated is not None
+ assert updated.settings is not None
assert updated.settings["payee_source"] == "merchant"
@@ -250,6 +251,7 @@ async def test_update_settings_preserves_existing(session: AsyncSession, test_us
session, conn.id, test_workspace.id, {"import_pending": False},
)
assert updated is not None
+ assert updated.settings is not None
assert updated.settings["payee_source"] == "auto"
assert updated.settings["import_pending"] is False
@@ -266,6 +268,7 @@ async def test_update_settings_sync_assets(session: AsyncSession, test_user, tes
session, conn.id, test_workspace.id, {"sync_assets": False},
)
assert updated is not None
+ assert updated.settings is not None
assert updated.settings["payee_source"] == "auto"
assert updated.settings["import_pending"] is True
assert updated.settings["sync_assets"] is False
@@ -301,6 +304,8 @@ async def test_oauth_callback_respects_initial_asset_sync_opt_out(
sync_assets=False,
)
+ assert connection is not None
+ assert connection.settings is not None
assert connection.settings["sync_assets"] is False
mock_provider.get_holdings.assert_not_awaited()
assets = (await session.execute(select(Asset))).scalars().all()
@@ -346,6 +351,8 @@ async def test_oauth_callback_respects_state_asset_sync_opt_out(
state="stored-state",
)
+ assert connection is not None
+ assert connection.settings is not None
assert connection.settings["sync_assets"] is False
assert connection.settings["flow_params"] == {
"country": "BR",
@@ -440,6 +447,7 @@ async def test_update_settings_ignores_none(session: AsyncSession, test_user, te
session, conn.id, test_workspace.id, {"payee_source": None},
)
assert updated is not None
+ assert updated.settings is not None
assert updated.settings["payee_source"] == "auto"
@@ -838,6 +846,7 @@ async def test_sync_connection_user_action_marks_error(
await sync_connection(session, conn.id, test_workspace.id, test_user.id)
refreshed = await session.get(BankConnection, conn.id)
+ assert refreshed is not None
assert refreshed.status == "error"
@@ -1610,6 +1619,7 @@ async def test_sync_creates_synthetic_transactions_for_finance_charges(
assert r.date == date(2026, 4, 15)
assert r.effective_date == date(2026, 4, 15)
assert r.type == "debit"
+ assert r.external_id is not None
assert r.external_id.startswith("bill_charge:bill-fc-1:")
@@ -1831,6 +1841,7 @@ async def test_sync_removes_orphaned_finance_charges_on_resync(
)
)).scalars().all()
assert len(rows) == 1
+ assert rows[0].external_id is not None
assert "fc-keep" in rows[0].external_id
diff --git a/backend/tests/test_credit_card_accounting_mode.py b/backend/tests/test_credit_card_accounting_mode.py
index c2315884..c283954d 100644
--- a/backend/tests/test_credit_card_accounting_mode.py
+++ b/backend/tests/test_credit_card_accounting_mode.py
@@ -1425,6 +1425,8 @@ class TestEffectiveBillDateFiltersList:
date_from=date(2026, 3, 17), date_to=date(2026, 4, 16),
bill_id=bill.id,
)
+
+ assert summary is not None
assert summary["monthly_income"] == 80.0
@pytest.mark.asyncio
@@ -1482,6 +1484,8 @@ class TestEffectiveBillDateFiltersList:
bill_id=bill.id,
)
# 44.90 (charge) - 44.90 (refund) + 32.50 (other) = 32.50
+
+ assert summary is not None
assert summary["monthly_expenses"] == 32.50
@pytest.mark.asyncio
@@ -1520,6 +1524,8 @@ class TestEffectiveBillDateFiltersList:
session, checking.id, test_workspace.id,
date_from=date(2026, 4, 1), date_to=date(2026, 4, 30),
)
+
+ assert summary is not None
assert summary["monthly_expenses"] == 50.0
assert summary["monthly_income"] == 3000.0
@@ -1603,6 +1609,8 @@ class TestEffectiveBillDateFiltersList:
bill_id=bill.id,
)
# Manual 50 counted, pending 99 excluded
+
+ assert summary is not None
assert summary["monthly_expenses"] == 50.0
@pytest.mark.asyncio
@@ -1715,6 +1723,8 @@ class TestEffectiveBillDateFiltersList:
date_from=date(2026, 4, 17), date_to=date(2026, 5, 16),
bill_id=may.id,
)
+
+ assert summary is not None
assert summary["monthly_expenses"] == 105.0
@pytest.mark.asyncio
@@ -1759,4 +1769,6 @@ class TestEffectiveBillDateFiltersList:
date_from=date(2026, 4, 12), date_to=date(2026, 5, 11),
unbilled_only=True,
)
+
+ assert summary is not None
assert summary["monthly_expenses"] == 59.90
diff --git a/backend/tests/test_group_service.py b/backend/tests/test_group_service.py
index b8458763..40b80ab2 100644
--- a/backend/tests/test_group_service.py
+++ b/backend/tests/test_group_service.py
@@ -98,6 +98,8 @@ async def test_create_member_and_unique_name(
test_workspace.id,
GroupMemberCreate(name="Alice", is_self=True),
)
+
+ assert member is not None
assert member.name == "Alice"
assert member.is_self is True
@@ -115,18 +117,24 @@ async def test_only_one_self_member_allowed(
session, test_workspace.id, test_user.id, GroupCreate(name="G")
)
m1 = await group_service.create_member(
- session, group.id, test_workspace.id, GroupMemberCreate(name="Me", is_self=True)
+ session, group.id, test_workspace.id, GroupMemberCreate(name="Me", is_self=True)
)
+
+ assert m1 is not None
m2 = await group_service.create_member(
session,
group.id,
test_workspace.id,
GroupMemberCreate(name="Also Me", is_self=True),
)
+
+ assert m2 is not None
# m1 should have been demoted automatically.
refreshed = await group_service.list_members(
session, group.id, test_workspace.id, test_user.id
)
+
+ assert refreshed is not None
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
@@ -142,10 +150,13 @@ async def test_update_member_promotes_to_self_demotes_others(
m1 = await group_service.create_member(
session, group.id, test_workspace.id, GroupMemberCreate(name="A", is_self=True)
)
+ assert m1 is not None
m2 = await group_service.create_member(
session, group.id, test_workspace.id, GroupMemberCreate(name="B")
)
+ assert m2 is not None
+
await group_service.update_member(
session,
group.id,
@@ -156,6 +167,8 @@ async def test_update_member_promotes_to_self_demotes_others(
refreshed = await group_service.list_members(
session, group.id, test_workspace.id, test_user.id
)
+
+ assert refreshed is not None
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
diff --git a/backend/tests/test_group_service_coverage.py b/backend/tests/test_group_service_coverage.py
index c4e8eb65..0627d3ab 100644
--- a/backend/tests/test_group_service_coverage.py
+++ b/backend/tests/test_group_service_coverage.py
@@ -98,8 +98,10 @@ async def test_update_member_resolves_email_link(session: AsyncSession, test_use
session, test_workspace.id, test_user.id, GroupCreate(name="G")
)
m = await group_service.create_member(
- session, group.id, test_workspace.id, GroupMemberCreate(name="Friend")
+ session, group.id, test_workspace.id, GroupMemberCreate(name="Friend")
)
+
+ assert m is not None
assert m.linked_user_id is None
updated = await group_service.update_member(
@@ -119,8 +121,10 @@ async def test_update_member_name_clash(session: AsyncSession, test_user, test_w
session, group.id, test_workspace.id, GroupMemberCreate(name="Alice")
)
bob = await group_service.create_member(
- session, group.id, test_workspace.id, GroupMemberCreate(name="Bob")
+ session, group.id, test_workspace.id, GroupMemberCreate(name="Bob")
)
+
+ assert bob is not None
with pytest.raises(ValueError, match="already exists"):
await group_service.update_member(
session, group.id, bob.id, test_workspace.id,
@@ -155,8 +159,10 @@ async def test_delete_member(session: AsyncSession, test_user, test_workspace):
session, test_workspace.id, test_user.id, GroupCreate(name="G")
)
m = await group_service.create_member(
- session, group.id, test_workspace.id, GroupMemberCreate(name="Temp")
+ session, group.id, test_workspace.id, GroupMemberCreate(name="Temp")
)
+
+ assert m is not None
assert await group_service.delete_member(session, group.id, m.id, test_workspace.id) is True
# Now gone.
assert await group_service.delete_member(session, group.id, m.id, test_workspace.id) is False
@@ -180,9 +186,11 @@ async def test_delete_member_integrity_error_translated(session: AsyncSession, t
session, test_workspace.id, test_user.id, GroupCreate(name="G")
)
member = await group_service.create_member(
- session, group.id, test_workspace.id, GroupMemberCreate(name="Alice")
+ session, group.id, test_workspace.id, GroupMemberCreate(name="Alice")
)
+ assert member is not None
+
async def _boom():
raise IntegrityError("DELETE", {}, Exception("FK RESTRICT"))
@@ -209,7 +217,7 @@ async def test_get_group_visible_cross_workspace(session: AsyncSession, test_use
session, group.id, other_ws.id, other.id
)
assert visible is not None
- assert visible.is_owner is False # type: ignore[attr-defined]
+ assert visible.is_owner is False
# And via list_groups too.
listed = await group_service.list_groups(session, other_ws.id, other.id)
@@ -224,6 +232,7 @@ async def test_list_transactions(session: AsyncSession, test_user, test_workspac
member = await group_service.create_member(
session, group.id, test_workspace.id, GroupMemberCreate(name="Alice")
)
+ assert member is not None
tx = Transaction(
id=uuid.uuid4(),
user_id=test_user.id,
@@ -341,6 +350,10 @@ async def test_create_member_self_demotes_prior_self(session: AsyncSession, test
members = await group_service.list_members(
session, group.id, test_workspace.id, test_user.id
)
+
+ assert m1 is not None
+ assert m2 is not None
+ assert members is not None
by_id = {m.id: m for m in members}
assert by_id[m1.id].is_self is False
assert by_id[m2.id].is_self is True
@@ -357,12 +370,16 @@ async def test_update_member_promote_self_demotes_existing(session: AsyncSession
m2 = await group_service.create_member(
session, group.id, test_workspace.id, GroupMemberCreate(name="B")
)
+
+ assert m1 is not None
+ assert m2 is not None
await group_service.update_member(
session, group.id, m2.id, test_workspace.id, GroupMemberUpdate(is_self=True)
)
members = await group_service.list_members(
session, group.id, test_workspace.id, test_user.id
)
+ assert members is not None
by_id = {m.id: m for m in members}
assert by_id[m1.id].is_self is False
assert by_id[m2.id].is_self is True
diff --git a/backend/tests/test_group_visibility.py b/backend/tests/test_group_visibility.py
index 1eb7bba5..8a8b4b7a 100644
--- a/backend/tests/test_group_visibility.py
+++ b/backend/tests/test_group_visibility.py
@@ -61,6 +61,8 @@ async def test_email_auto_resolves_to_linked_user(
test_workspace.id,
GroupMemberCreate(name="Friend", email="[email protected]"),
)
+
+ assert member is not None
assert member.linked_user_id == other.id
@@ -77,6 +79,8 @@ async def test_email_unknown_creates_shadow(
test_workspace.id,
GroupMemberCreate(name="Stranger", email="[email protected]"),
)
+
+ assert member is not None
assert member.linked_user_id is None
assert member.email == "[email protected]"
@@ -232,6 +236,9 @@ async def test_linked_member_can_settle_own_debt(
GroupMemberCreate(name="A", email="[email protected]"),
)
+ assert self_m is not None
+ assert a is not None
+
settlement = await settlement_service.create_settlement(
session,
group.id,
@@ -265,9 +272,12 @@ async def test_linked_member_cannot_settle_someone_elses_debt(
GroupMemberCreate(name="A", email="[email protected]"),
)
b = await group_service.create_member(
- session, group.id, test_workspace.id, GroupMemberCreate(name="B")
+ session, group.id, test_workspace.id, GroupMemberCreate(name="B")
)
+ assert a is not None
+ assert b is not None
+
with pytest.raises(PermissionError):
await settlement_service.create_settlement(
session,
diff --git a/backend/tests/test_new_rules_api.py b/backend/tests/test_new_rules_api.py
index 2570ebba..5da02c5e 100644
--- a/backend/tests/test_new_rules_api.py
+++ b/backend/tests/test_new_rules_api.py
@@ -109,6 +109,8 @@ async def test_create_rule_does_not_overwrite_existing_category(
items = (await client.get("/api/transactions", headers=auth_headers)).json()["items"]
ifood = {t["description"]: t for t in items}.get("IFOOD RESTAURANTE")
+
+ assert ifood is not None
assert ifood["category_id"] == original
@@ -133,6 +135,8 @@ async def test_create_rule_can_overwrite_existing_category_when_requested(
items = (await client.get("/api/transactions", headers=auth_headers)).json()["items"]
ifood = {t["description"]: t for t in items}.get("IFOOD RESTAURANTE")
+
+ assert ifood is not None
assert ifood["category_id"] != original
assert ifood["category_id"] == other
@@ -309,6 +313,8 @@ async def test_update_rule_can_overwrite_existing_category_when_requested(
items = (await client.get("/api/transactions", headers=auth_headers)).json()["items"]
ifood = {t["description"]: t for t in items}.get("IFOOD RESTAURANTE")
+
+ assert ifood is not None
assert ifood["category_id"] != original
assert ifood["category_id"] == other
@@ -409,6 +415,8 @@ async def test_apply_all_resets_before_reapply(
by_desc = {t["description"]: t for t in items}
uber = by_desc.get("UBER TRIP")
+
+ assert uber is not None
assert uber["category_id"] == str(test_categories[1].id)
diff --git a/backend/tests/test_payee_service.py b/backend/tests/test_payee_service.py
index f8ac9820..62b41f13 100644
--- a/backend/tests/test_payee_service.py
+++ b/backend/tests/test_payee_service.py
@@ -55,7 +55,7 @@ async def test_create_payee(session: AsyncSession, test_user, test_workspace):
assert payee.name == "Starbucks"
assert payee.type == "merchant"
assert payee.is_favorite is False
- assert payee.transaction_count == 0
+ assert payee.transaction_count == 0 # type: ignore[attr-defined]
assert payee.user_id == test_user.id
@@ -139,8 +139,8 @@ async def test_get_payees_with_transaction_counts(session: AsyncSession, test_us
payees = await get_payees(session, test_workspace.id)
payees_by_name = {p.name: p for p in payees}
- assert payees_by_name["Payee A"].transaction_count == 2
- assert payees_by_name["Payee B"].transaction_count == 1
+ assert payees_by_name["Payee A"].transaction_count == 2 # type: ignore[attr-defined]
+ assert payees_by_name["Payee B"].transaction_count == 1 # type: ignore[attr-defined]
@pytest.mark.asyncio
@@ -175,8 +175,8 @@ async def test_get_payees_includes_zero_transaction_payees(session: AsyncSession
assert orphan.id in ids
payees_by_id = {p.id: p for p in payees}
- assert payees_by_id[active.id].transaction_count == 1
- assert payees_by_id[orphan.id].transaction_count == 0
+ assert payees_by_id[active.id].transaction_count == 1 # type: ignore[attr-defined]
+ assert payees_by_id[orphan.id].transaction_count == 0 # type: ignore[attr-defined]
# ---------------------------------------------------------------------------
diff --git a/backend/tests/test_providers.py b/backend/tests/test_providers.py
index f87f6fe7..b75af290 100644
--- a/backend/tests/test_providers.py
+++ b/backend/tests/test_providers.py
@@ -1,3 +1,6 @@
+from datetime import date
+from typing import Optional
+
import pytest
from unittest.mock import patch
@@ -10,6 +13,7 @@ from app.providers import (
_PROVIDERS,
)
from app.providers.base import BankProvider
+from app.core.config import Settings
class FakeProvider(BankProvider):
@@ -21,7 +25,12 @@ class FakeProvider(BankProvider):
def flow_type(self) -> str:
return "widget"
- def get_oauth_url(self, redirect_uri: str, state: str) -> str:
+ async def get_oauth_url(
+ self,
+ redirect_uri: str,
+ state: str,
+ flow_params: Optional[dict] = None,
+ ) -> str:
return "https://fake.example.com"
async def handle_oauth_callback(self, code: str):
@@ -30,7 +39,13 @@ class FakeProvider(BankProvider):
async def get_accounts(self, credentials: dict):
return []
- async def get_transactions(self, credentials, account_id, since, **kw):
+ async def get_transactions(
+ self,
+ credentials: dict,
+ account_external_id: str,
+ since: Optional[date] = None,
+ payee_source: str = "auto",
+ ) -> list:
return []
async def refresh_credentials(self, credentials: dict) -> dict:
@@ -106,15 +121,12 @@ class TestOAuthRedirectDefaults:
parse (containers/podman-compose#1064).
"""
- def _settings(self, **overrides):
- from app.core.config import Settings
-
- defaults = {
- "frontend_url": "http://localhost:3000",
- "pluggy_oauth_redirect_uri": "",
- "enable_banking_oauth_redirect_uri": "",
- }
- return Settings(**{**defaults, **overrides})
+ def _settings(self, **overrides) -> Settings:
+ return Settings(
+ frontend_url="http://localhost:3000",
+ pluggy_oauth_redirect_uri="",
+ enable_banking_oauth_redirect_uri="",
+ ).model_copy(update=overrides)
def test_default_derives_from_frontend_url(self):
from app.providers.base import default_oauth_redirect_uri
diff --git a/backend/tests/test_providers_pluggy_bills.py b/backend/tests/test_providers_pluggy_bills.py
index c7f697e6..7b2bc344 100644
--- a/backend/tests/test_providers_pluggy_bills.py
+++ b/backend/tests/test_providers_pluggy_bills.py
@@ -338,7 +338,7 @@ async def test_default_get_bills_returns_empty_list():
def name(self) -> str:
return "stub"
- def get_oauth_url(self, redirect_uri, state):
+ async def get_oauth_url(self, redirect_uri: str, state: str, flow_params: dict | None = None) -> str:
return ""
async def handle_oauth_callback(self, code):
diff --git a/backend/tests/test_providers_pluggy_trigger_refresh.py b/backend/tests/test_providers_pluggy_trigger_refresh.py
index c7de17ec..2d531aa6 100644
--- a/backend/tests/test_providers_pluggy_trigger_refresh.py
+++ b/backend/tests/test_providers_pluggy_trigger_refresh.py
@@ -35,10 +35,10 @@ def _client_with(patch_resp: MagicMock, get_responses: list[MagicMock]) -> Magic
async def _run(client: MagicMock) -> str:
provider = PluggyProvider()
- with patch.object(
- PluggyProvider, "_headers", new=AsyncMock(return_value={"X-API-KEY": "k"})
- ), patch("app.providers.pluggy.httpx.AsyncClient", return_value=client), patch(
- "app.providers.pluggy.asyncio.sleep", new=AsyncMock(return_value=None)
+ with (
+ patch.object(PluggyProvider, "_headers", new=AsyncMock(return_value={"X-API-KEY": "k"})),
+ patch("app.providers.pluggy.httpx.AsyncClient", return_value=client),
+ patch("app.providers.pluggy.asyncio.sleep", new=AsyncMock(return_value=None)),
):
return await provider.trigger_refresh({"item_id": "item-1"})
@@ -62,7 +62,6 @@ async def test_refresh_missing_item_id_skipped():
"""Connections without an item_id (non-Pluggy, malformed) skip refresh."""
provider = PluggyProvider()
assert await provider.trigger_refresh({}) == "skipped"
- assert await provider.trigger_refresh(None) == "skipped" # type: ignore[arg-type]
@pytest.mark.asyncio
@@ -161,9 +160,10 @@ async def test_refresh_patch_http_error_returns_failed():
client.__aenter__ = AsyncMock(return_value=client)
client.__aexit__ = AsyncMock(return_value=None)
provider = PluggyProvider()
- with patch.object(
- PluggyProvider, "_headers", new=AsyncMock(return_value={"X-API-KEY": "k"})
- ), patch("app.providers.pluggy.httpx.AsyncClient", return_value=client):
+ with (
+ patch.object(PluggyProvider, "_headers", new=AsyncMock(return_value={"X-API-KEY": "k"})),
+ patch("app.providers.pluggy.httpx.AsyncClient", return_value=client),
+ ):
assert await provider.trigger_refresh({"item_id": "item-1"}) == "failed"
@@ -185,11 +185,12 @@ async def test_refresh_poll_eventually_times_out():
except StopIteration:
return 999.0
- with patch.object(
- PluggyProvider, "_headers", new=AsyncMock(return_value={"X-API-KEY": "k"})
- ), patch("app.providers.pluggy.httpx.AsyncClient", return_value=client), patch(
- "app.providers.pluggy.asyncio.sleep", new=AsyncMock(return_value=None)
- ), patch("app.providers.pluggy.time.monotonic", side_effect=fake_monotonic):
+ with (
+ patch.object(PluggyProvider, "_headers", new=AsyncMock(return_value={"X-API-KEY": "k"})),
+ patch("app.providers.pluggy.httpx.AsyncClient", return_value=client),
+ patch("app.providers.pluggy.asyncio.sleep", new=AsyncMock(return_value=None)),
+ patch("app.providers.pluggy.time.monotonic", side_effect=fake_monotonic),
+ ):
assert await provider.trigger_refresh({"item_id": "item-1"}) == "failed"
diff --git a/backend/tests/test_providers_simplefin.py b/backend/tests/test_providers_simplefin.py
index 2e8916bd..2837c90b 100644
--- a/backend/tests/test_providers_simplefin.py
+++ b/backend/tests/test_providers_simplefin.py
@@ -502,6 +502,7 @@ def test_build_transaction_non_iso_currency_is_none():
assert txn.currency is None
# A real ISO code still passes through, normalized.
ok = SimpleFinProvider._build_transaction({**raw, "currency": "eur"}, "description")
+ assert ok is not None
assert ok.currency == "EUR"
diff --git a/backend/tests/test_report_service_coverage.py b/backend/tests/test_report_service_coverage.py
index 2b2c9cb9..a49b0a8a 100644
--- a/backend/tests/test_report_service_coverage.py
+++ b/backend/tests/test_report_service_coverage.py
@@ -713,6 +713,8 @@ async def test_cash_flow_baseline_amount_primary_used(session, test_user, test_w
session, test_workspace.id, test_user.id, months=2, interval="daily", baseline=True
)
assert report.meta.baseline_active is True
+
+ assert report.meta.baseline_lookback_days is not None
assert report.meta.baseline_lookback_days > 0
diff --git a/backend/tests/test_rule_engine.py b/backend/tests/test_rule_engine.py
index a201ed23..5bacbef6 100644
--- a/backend/tests/test_rule_engine.py
+++ b/backend/tests/test_rule_engine.py
@@ -1,14 +1,14 @@
# backend/tests/test_rule_engine.py
-import types
import uuid
from decimal import Decimal
from datetime import date
+from app.models import Transaction
from app.services.rule_engine import evaluate_conditions, apply_rule_actions
-def make_tx(**kwargs) -> types.SimpleNamespace:
+def make_tx(**kwargs) -> Transaction:
defaults = dict(
id=uuid.uuid4(),
user_id=uuid.uuid4(),
@@ -24,11 +24,12 @@ def make_tx(**kwargs) -> types.SimpleNamespace:
notes=None,
)
defaults.update(kwargs)
- return types.SimpleNamespace(**defaults)
+ return Transaction(**defaults)
# --- evaluate_conditions tests ---
+
def test_contains_match():
conditions = [{"field": "description", "op": "contains", "value": "UBER"}]
tx = make_tx(description="UBER TRIP")
@@ -160,7 +161,7 @@ def test_and_partial_match():
def test_or_one_match():
conditions = [
{"field": "description", "op": "contains", "value": "IFOOD"}, # fails
- {"field": "description", "op": "contains", "value": "UBER"}, # passes
+ {"field": "description", "op": "contains", "value": "UBER"}, # passes
]
tx = make_tx(description="UBER TRIP")
assert evaluate_conditions("or", conditions, tx) is True
@@ -168,6 +169,7 @@ def test_or_one_match():
# --- apply_rule_actions tests ---
+
def test_set_category():
cat_id = uuid.uuid4()
actions = [{"op": "set_category", "value": str(cat_id)}]
@@ -203,6 +205,8 @@ def test_append_notes_accumulates():
tx = make_tx(notes=None)
apply_rule_actions(actions1, tx, category_already_set=False)
apply_rule_actions(actions2, tx, category_already_set=False)
+
+ assert tx.notes is not None
assert "#work" in tx.notes
assert "#small" in tx.notes
@@ -211,6 +215,8 @@ def test_append_notes_no_duplicate():
actions = [{"op": "append_notes", "value": "#work"}]
tx = make_tx(notes="#work")
apply_rule_actions(actions, tx, category_already_set=False)
+
+ assert tx.notes is not None
assert tx.notes.count("#work") == 1
@@ -223,6 +229,7 @@ def test_ignore_action_sets_flag():
# --- Edge-case: evaluate_conditions ---
+
def test_not_equals():
conditions = [{"field": "type", "op": "not_equals", "value": "credit"}]
tx = make_tx(type="debit")
@@ -333,6 +340,7 @@ def test_invalid_regex_returns_false():
# --- Edge-case: apply_rule_actions ---
+
def test_invalid_uuid_set_category_skips():
actions = [{"op": "set_category", "value": "not-a-uuid"}]
tx = make_tx()
diff --git a/backend/tests/test_rule_service.py b/backend/tests/test_rule_service.py
index 9966cb46..8a548139 100644
--- a/backend/tests/test_rule_service.py
+++ b/backend/tests/test_rule_service.py
@@ -582,7 +582,7 @@ async def test_create_default_rules(session: AsyncSession, test_user, test_works
async def test_install_rule_pack_br(session: AsyncSession, test_user, test_workspace):
await create_default_categories(session, test_user.id, lang="pt-BR")
- result = await install_rule_pack(session, test_user.id, "BR", lang="pt-BR")
+ result = await install_rule_pack(session, test_workspace.id, test_user.id, "BR", lang="pt-BR")
assert len(result.rules) > 0
assert result.unresolved == 0
@@ -594,8 +594,8 @@ async def test_install_rule_pack_br(session: AsyncSession, test_user, test_works
async def test_install_rule_pack_skips_duplicates(session: AsyncSession, test_user, test_workspace):
await create_default_categories(session, test_user.id, lang="pt-BR")
- first = await install_rule_pack(session, test_user.id, "BR", lang="pt-BR")
- second = await install_rule_pack(session, test_user.id, "BR", lang="pt-BR")
+ first = await install_rule_pack(session, test_workspace.id, test_user.id, "BR", lang="pt-BR")
+ second = await install_rule_pack(session, test_workspace.id, test_user.id, "BR", lang="pt-BR")
assert len(first.rules) > 0
# All rules already installed — distinct from "couldn't install" because
@@ -612,7 +612,7 @@ async def test_install_rule_pack_works_across_languages(session: AsyncSession, t
# still resolve the category by internal key.
await create_default_categories(session, test_user.id, lang="en")
- result = await install_rule_pack(session, test_user.id, "BR", lang="pt-BR")
+ result = await install_rule_pack(session, test_workspace.id, test_user.id, "BR", lang="pt-BR")
# Every BR rule's set_category action should have resolved to a real
# English category UUID, so the pack installs in full.
@@ -629,7 +629,7 @@ async def test_install_rule_pack_reports_unresolved_when_categories_missing(
# write any rules. The result must surface this so the frontend can
# tell the user "missing categories" instead of the misleading
# "pack already installed" toast.
- result = await install_rule_pack(session, test_user.id, "BR", lang="pt-BR")
+ result = await install_rule_pack(session, test_workspace.id, test_user.id, "BR", lang="pt-BR")
assert len(result.rules) == 0
assert result.unresolved == len(RULE_PACKS["BR"]["rules"])
@@ -644,6 +644,7 @@ async def test_install_rule_pack_creates_missing_categories_when_opted_in(
# then install the full rule set.
result = await install_rule_pack(
session,
+ test_workspace.id,
test_user.id,
"BR",
lang="pt-BR",
@@ -657,7 +658,7 @@ async def test_install_rule_pack_creates_missing_categories_when_opted_in(
@pytest.mark.asyncio
async def test_install_rule_pack_unknown_returns_empty(session: AsyncSession, test_user, test_workspace):
- result = await install_rule_pack(session, test_user.id, "ZZ")
+ result = await install_rule_pack(session, test_workspace.id, test_user.id, "ZZ")
assert result.rules == []
assert result.unresolved == 0
@@ -669,7 +670,7 @@ async def test_get_installed_packs(session: AsyncSession, test_user, test_worksp
packs_before = await get_installed_packs(session, test_user.id)
assert packs_before["BR"] is False
- await install_rule_pack(session, test_user.id, "BR", lang="pt-BR")
+ await install_rule_pack(session, test_workspace.id, test_user.id, "BR", lang="pt-BR")
packs_after = await get_installed_packs(session, test_user.id)
assert packs_after["BR"] is True
diff --git a/backend/tests/test_settlement_service.py b/backend/tests/test_settlement_service.py
index 91282135..56daca7d 100644
--- a/backend/tests/test_settlement_service.py
+++ b/backend/tests/test_settlement_service.py
@@ -143,6 +143,7 @@ async def test_settlement_update_keeps_invariants(
date=date.today(),
),
)
+ assert s is not None
updated = await settlement_service.update_settlement(
session,
@@ -152,6 +153,8 @@ async def test_settlement_update_keeps_invariants(
test_user.id,
GroupSettlementUpdate(amount=Decimal("12.00"), notes="adjusted"),
)
+
+ assert updated is not None
assert updated.amount == Decimal("12.00")
assert updated.notes == "adjusted"
@@ -227,6 +230,9 @@ async def test_receiver_credit_created_when_to_member_is_linked_with_account(
GroupMemberCreate(name="Bob", linked_user_id=receiver.id),
)
+ assert me is not None
+ assert bob is not None
+
s = await settlement_service.create_settlement(
session,
group.id,
@@ -271,9 +277,12 @@ async def test_receiver_credit_skipped_when_to_member_is_shadow(
GroupMemberCreate(name="Me", is_self=True),
)
shadow = await group_service.create_member(
- session, group.id, test_workspace.id, GroupMemberCreate(name="Shadow")
+ session, group.id, test_workspace.id, GroupMemberCreate(name="Shadow")
)
+ assert me is not None
+ assert shadow is not None
+
s = await settlement_service.create_settlement(
session,
group.id,
@@ -321,6 +330,9 @@ async def test_receiver_credit_skipped_when_linked_user_has_no_cash_account(
GroupMemberCreate(name="Bob", linked_user_id=receiver.id),
)
+ assert me is not None
+ assert bob is not None
+
s = await settlement_service.create_settlement(
session,
group.id,
@@ -357,9 +369,12 @@ async def test_receiver_credit_lands_on_owner_when_self_member_unlinked(
GroupMemberCreate(name="Me", is_self=True),
)
friend = await group_service.create_member(
- session, group.id, test_workspace.id, GroupMemberCreate(name="Friend")
+ session, group.id, test_workspace.id, GroupMemberCreate(name="Friend")
)
+ assert owner_self is not None
+ assert friend is not None
+
# 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.
diff --git a/backend/tests/test_settlement_service_coverage.py b/backend/tests/test_settlement_service_coverage.py
index c00ff5ad..599255cb 100644
--- a/backend/tests/test_settlement_service_coverage.py
+++ b/backend/tests/test_settlement_service_coverage.py
@@ -198,6 +198,9 @@ async def test_create_settlement_receiver_self_member_owner_fallback(session: As
friend = await group_service.create_member(
session, group.id, test_workspace.id, GroupMemberCreate(name="Friend")
)
+ assert owner_self is not None
+
+ assert friend is not None
s = await settlement_service.create_settlement(
session, group.id, test_workspace.id, test_user.id,
GroupSettlementCreate(
@@ -205,9 +208,12 @@ async def test_create_settlement_receiver_self_member_owner_fallback(session: As
amount=Decimal("8.00"), currency="USD", date=date.today(),
),
)
+
assert s is not None
+
assert s.receiver_transaction_id is not None
rx = await session.get(Transaction, s.receiver_transaction_id)
+ assert rx is not None
assert rx.account_id == owner_account.id
assert rx.type == "credit"
@@ -238,10 +244,13 @@ async def test_update_settlement_change_only_from_member(session: AsyncSession,
amount=Decimal("10.00"), currency="USD", date=date.today(),
),
)
+
+ assert s is not None
updated = await settlement_service.update_settlement(
session, group.id, s.id, test_workspace.id, test_user.id,
GroupSettlementUpdate(from_member_id=c.id),
)
+
assert updated is not None
assert updated.from_member_id == c.id
@@ -278,11 +287,14 @@ async def test_update_settlement_revalidates_members_and_transaction(session: As
amount=Decimal("10.00"), currency="USD", date=date.today(),
),
)
+
+ assert s is not None
# Change to_member to Carol and link the transaction.
updated = await settlement_service.update_settlement(
session, group.id, s.id, test_workspace.id, test_user.id,
GroupSettlementUpdate(to_member_id=c.id, transaction_id=tx.id),
)
+
assert updated is not None
assert updated.to_member_id == c.id
assert updated.transaction_id == tx.id
@@ -298,6 +310,8 @@ async def test_update_settlement_invalid_member(session: AsyncSession, test_user
amount=Decimal("10.00"), currency="USD", date=date.today(),
),
)
+
+ assert s is not None
with pytest.raises(ValueError, match="must belong to the group"):
await settlement_service.update_settlement(
session, group.id, s.id, test_workspace.id, test_user.id,
@@ -315,6 +329,8 @@ async def test_delete_settlement(session: AsyncSession, test_user, test_workspac
amount=Decimal("10.00"), currency="USD", date=date.today(),
),
)
+
+ assert s is not None
assert await settlement_service.delete_settlement(
session, group.id, s.id, test_workspace.id, test_user.id
) is True
@@ -360,6 +376,10 @@ async def test_settlement_permission_for_linked_member(session: AsyncSession, te
GroupMemberCreate(name="Payer", linked_user_id=payer_user.id),
)
+ assert me is not None
+
+ assert payer is not None
+
# The linked payer can record a payment where they are the from_member.
s = await settlement_service.create_settlement(
session, group.id, payer_ws.id, payer_user.id,
@@ -368,6 +388,7 @@ async def test_settlement_permission_for_linked_member(session: AsyncSession, te
amount=Decimal("3.00"), currency="USD", date=date.today(),
),
)
+
assert s is not None
# But NOT one where someone else is the from_member.
@@ -409,6 +430,10 @@ async def test_update_settlement_permission_denied(session: AsyncSession, test_u
session, group.id, test_workspace.id,
GroupMemberCreate(name="Intruder", linked_user_id=intruder.id),
)
+
+ assert a is not None
+
+ assert b is not None
# Owner creates a settlement from a -> b.
s = await settlement_service.create_settlement(
session, group.id, test_workspace.id, test_user.id,
@@ -417,6 +442,8 @@ async def test_update_settlement_permission_denied(session: AsyncSession, test_u
amount=Decimal("10.00"), currency="USD", date=date.today(),
),
)
+
+ assert s is not None
# Intruder (linked to b, not the from_member) can't edit it.
with pytest.raises(PermissionError, match="settlements you created"):
await settlement_service.update_settlement(
diff --git a/backend/tests/test_share_only_model.py b/backend/tests/test_share_only_model.py
index f2054409..93b0e354 100644
--- a/backend/tests/test_share_only_model.py
+++ b/backend/tests/test_share_only_model.py
@@ -540,6 +540,8 @@ async def test_balance_line_default_currency_passthrough(
balances = await balance_service.compute_balances(
session, members[0].group_id, test_workspace.id, test_user.id
)
+
+ assert balances is not None
line = balances["lines"][0]
assert Decimal(str(line["amount"])) == Decimal(str(line["amount_in_default_currency"]))
diff --git a/backend/tests/test_sync_holdings.py b/backend/tests/test_sync_holdings.py
index 17d0653c..5679aa54 100644
--- a/backend/tests/test_sync_holdings.py
+++ b/backend/tests/test_sync_holdings.py
@@ -6,6 +6,7 @@ bearing and must never be overwritten. These tests pin the full matrix:
new/existing × active/withdrawn, same-day vs next-day re-syncs,
historical seeding idempotency, and sparse-field merging.
"""
+
from __future__ import annotations
import uuid
@@ -53,7 +54,9 @@ class _MockProvider(BankProvider):
def name(self) -> str:
return "mock"
- def get_oauth_url(self, redirect_uri: str, state: str) -> str: # pragma: no cover
+ async def get_oauth_url(
+ self, redirect_uri: str, state: str, flow_params=None
+ ) -> str: # pragma: no cover
return "http://mock"
async def handle_oauth_callback(self, code: str) -> ConnectionData: # pragma: no cover
@@ -62,7 +65,9 @@ class _MockProvider(BankProvider):
async def get_accounts(self, credentials: dict) -> list[AccountData]: # pragma: no cover
return []
- async def get_transactions(self, credentials: dict, account_external_id: str, since=None, payee_source: str = "auto") -> list[TransactionData]: # pragma: no cover
+ async def get_transactions(
+ self, credentials: dict, account_external_id: str, since=None, payee_source: str = "auto"
+ ) -> list[TransactionData]: # pragma: no cover
return []
async def refresh_credentials(self, credentials: dict) -> dict: # pragma: no cover
@@ -157,6 +162,7 @@ async def test_new_active_holding_creates_asset_wallet_and_today_value(
_holding(current_value=Decimal("1234.56"), purchase_date=today - timedelta(days=10)),
]
+ assert mock_connection.credentials is not None
await _sync_holdings(session, test_user.id, mock_connection, mock_connection.credentials)
await session.commit()
@@ -192,6 +198,7 @@ async def test_new_withdrawn_holding_is_skipped_entirely(
_holding(external_id="dead-1", current_value=Decimal("0"), is_withdrawn=True),
]
+ assert mock_connection.credentials is not None
await _sync_holdings(session, test_user.id, mock_connection, mock_connection.credentials)
await session.commit()
@@ -209,6 +216,8 @@ async def test_withdrawn_existing_asset_gets_sell_date(
# First sync: active.
_MockProvider._holdings = [_holding(external_id="h-1", current_value=Decimal("500"))]
+
+ assert mock_connection.credentials is not None
await _sync_holdings(session, test_user.id, mock_connection, mock_connection.credentials)
await session.commit()
[asset] = await _assets_for(session, test_user)
@@ -220,6 +229,8 @@ async def test_withdrawn_existing_asset_gets_sell_date(
_MockProvider._holdings = [
_holding(external_id="h-1", current_value=Decimal("0"), is_withdrawn=True)
]
+
+ assert mock_connection.credentials is not None
await _sync_holdings(session, test_user.id, mock_connection, mock_connection.credentials)
await session.commit()
await session.refresh(asset)
@@ -256,6 +267,8 @@ async def test_withdrawn_existing_does_not_overwrite_user_sell_date(
_MockProvider._holdings = [
_holding(external_id="h-1", current_value=Decimal("0"), is_withdrawn=True)
]
+
+ assert mock_connection.credentials is not None
await _sync_holdings(session, test_user.id, mock_connection, mock_connection.credentials)
await session.commit()
await session.refresh(asset)
@@ -286,9 +299,9 @@ async def test_user_sold_active_on_provider_stops_value_updates(
session.add(asset)
await session.commit()
- _MockProvider._holdings = [
- _holding(external_id="h-1", current_value=Decimal("999.99"))
- ]
+ _MockProvider._holdings = [_holding(external_id="h-1", current_value=Decimal("999.99"))]
+
+ assert mock_connection.credentials is not None
await _sync_holdings(session, test_user.id, mock_connection, mock_connection.credentials)
await session.commit()
await session.refresh(asset)
@@ -305,11 +318,15 @@ async def test_same_day_resync_updates_asset_value_in_place(
"""Running sync twice in one day must not duplicate the day's AssetValue —
the second pass updates the amount in the existing row."""
_MockProvider._holdings = [_holding(external_id="h-1", current_value=Decimal("100"))]
+
+ assert mock_connection.credentials is not None
await _sync_holdings(session, test_user.id, mock_connection, mock_connection.credentials)
await session.commit()
[asset] = await _assets_for(session, test_user)
_MockProvider._holdings = [_holding(external_id="h-1", current_value=Decimal("110"))]
+
+ assert mock_connection.credentials is not None
await _sync_holdings(session, test_user.id, mock_connection, mock_connection.credentials)
await session.commit()
@@ -336,6 +353,8 @@ async def test_sparse_fields_are_preserved_on_later_sync(
purchase_date=date.today() - timedelta(days=100),
)
]
+
+ assert mock_connection.credentials is not None
await _sync_holdings(session, test_user.id, mock_connection, mock_connection.credentials)
await session.commit()
[asset] = await _assets_for(session, test_user)
@@ -351,6 +370,8 @@ async def test_sparse_fields_are_preserved_on_later_sync(
purchase_date=None,
)
]
+
+ assert mock_connection.credentials is not None
await _sync_holdings(session, test_user.id, mock_connection, mock_connection.credentials)
await session.commit()
await session.refresh(asset)
@@ -374,6 +395,8 @@ async def test_historical_seed_is_idempotent(
purchase_date=purchase,
)
]
+
+ assert mock_connection.credentials is not None
for _ in range(3):
await _sync_holdings(session, test_user.id, mock_connection, mock_connection.credentials)
await session.commit()
@@ -420,6 +443,8 @@ async def test_historical_seed_respects_prior_manual_value(
purchase_date=purchase,
)
]
+
+ assert mock_connection.credentials is not None
await _sync_holdings(session, test_user.id, mock_connection, mock_connection.credentials)
await session.commit()
@@ -440,11 +465,15 @@ async def test_disappeared_holding_gets_archived(
_holding(external_id="h-1", current_value=Decimal("500")),
_holding(external_id="h-2", current_value=Decimal("200")),
]
+
+ assert mock_connection.credentials is not None
await _sync_holdings(session, test_user.id, mock_connection, mock_connection.credentials)
await session.commit()
# Only h-1 comes back on the next sync. h-2 must be archived.
_MockProvider._holdings = [_holding(external_id="h-1", current_value=Decimal("510"))]
+
+ assert mock_connection.credentials is not None
await _sync_holdings(session, test_user.id, mock_connection, mock_connection.credentials)
await session.commit()
@@ -459,11 +488,15 @@ async def test_returned_holding_is_unarchived_after_reconnect(
):
"""A holding archived on unlink should become active again when reconnected."""
_MockProvider._holdings = [_holding(external_id="h-1", current_value=Decimal("500"))]
+
+ assert mock_connection.credentials is not None
await _sync_holdings(session, test_user.id, mock_connection, mock_connection.credentials)
await session.commit()
# Next sync does not include h-1 -> archived.
_MockProvider._holdings = []
+
+ assert mock_connection.credentials is not None
await _sync_holdings(session, test_user.id, mock_connection, mock_connection.credentials)
await session.commit()
@@ -489,6 +522,8 @@ async def test_returned_holding_is_unarchived_after_reconnect(
# Later sync includes h-1 again -> should unarchive.
_MockProvider._holdings = [_holding(external_id="h-1", current_value=Decimal("525"))]
+
+ assert reconnected.credentials is not None
await _sync_holdings(session, test_user.id, reconnected, reconnected.credentials)
await session.commit()
@@ -502,6 +537,8 @@ async def test_user_archived_holding_stays_archived_on_same_connection_sync(
):
"""Sync must not override a user archive decision on the same connection."""
_MockProvider._holdings = [_holding(external_id="h-1", current_value=Decimal("500"))]
+
+ assert mock_connection.credentials is not None
await _sync_holdings(session, test_user.id, mock_connection, mock_connection.credentials)
await session.commit()
@@ -510,6 +547,8 @@ async def test_user_archived_holding_stays_archived_on_same_connection_sync(
await session.commit()
_MockProvider._holdings = [_holding(external_id="h-1", current_value=Decimal("510"))]
+
+ assert mock_connection.credentials is not None
await _sync_holdings(session, test_user.id, mock_connection, mock_connection.credentials)
await session.commit()
@@ -524,6 +563,8 @@ async def test_user_moved_asset_to_custom_wallet_not_overridden(
"""If the user moves a synced asset to a custom wallet, later syncs must
not drag it back to the provider's default wallet."""
_MockProvider._holdings = [_holding(external_id="h-1", current_value=Decimal("500"))]
+
+ assert mock_connection.credentials is not None
await _sync_holdings(session, test_user.id, mock_connection, mock_connection.credentials)
await session.commit()
[asset] = await _assets_for(session, test_user)
@@ -545,6 +586,8 @@ async def test_user_moved_asset_to_custom_wallet_not_overridden(
await session.commit()
_MockProvider._holdings = [_holding(external_id="h-1", current_value=Decimal("520"))]
+
+ assert mock_connection.credentials is not None
await _sync_holdings(session, test_user.id, mock_connection, mock_connection.credentials)
await session.commit()
await session.refresh(asset)
@@ -560,6 +603,8 @@ async def test_provider_error_is_swallowed_without_side_effects(
"""/investments errors must not crash the account/transaction sync that
just succeeded — silent failure here is intentional."""
_MockProvider._raise = RuntimeError("provider 500")
+
+ assert mock_connection.credentials is not None
await _sync_holdings(session, test_user.id, mock_connection, mock_connection.credentials)
# No assets, no exception.
assert await _assets_for(session, test_user) == []
@@ -583,12 +628,12 @@ async def test_next_day_sync_appends_new_asset_value(
currency="BRL",
)
session.add(asset)
- session.add(
- AssetValue(asset_id=asset.id, amount=Decimal("100"), date=yesterday, source="sync")
- )
+ session.add(AssetValue(asset_id=asset.id, amount=Decimal("100"), date=yesterday, source="sync"))
await session.commit()
_MockProvider._holdings = [_holding(external_id="h-1", current_value=Decimal("105"))]
+
+ assert mock_connection.credentials is not None
await _sync_holdings(session, test_user.id, mock_connection, mock_connection.credentials)
await session.commit()
diff --git a/backend/tests/test_tesouro_direto_assets.py b/backend/tests/test_tesouro_direto_assets.py
index c233778f..adef23d6 100644
--- a/backend/tests/test_tesouro_direto_assets.py
+++ b/backend/tests/test_tesouro_direto_assets.py
@@ -81,6 +81,8 @@ async def test_create_tesouro_market_price_asset_reuses_market_ledger(
assert created.transaction_count == 1
db_asset = await session.get(Asset, created.id)
+
+ assert db_asset is not None
assert db_asset.external_metadata is None
@@ -109,6 +111,8 @@ async def test_refresh_all_market_prices_updates_tesouro_symbol_through_market_p
assert summary == {"refreshed": 1, "skipped": 0, "rate_limited": 0}
assert refresh_provider.bulk_calls == 1
db_asset = await session.get(Asset, created.id)
+
+ assert db_asset is not None
assert db_asset.last_price == Decimal("15200.000000")
values = (
await session.execute(
diff --git a/backend/tests/test_transaction_service.py b/backend/tests/test_transaction_service.py
index 5e36c030..6c0b18e8 100644
--- a/backend/tests/test_transaction_service.py
+++ b/backend/tests/test_transaction_service.py
@@ -1,6 +1,7 @@
import uuid
from datetime import date, datetime, timezone
from decimal import Decimal
+from typing import TypedDict
import pytest
import pytest_asyncio
@@ -26,6 +27,11 @@ from app.services.transaction_service import (
)
+class _TxFilter(TypedDict, total=False):
+ from_date: date
+ to_date: date
+
+
@pytest_asyncio.fixture
async def txn_account(session: AsyncSession, test_user) -> Account:
account = Account(
@@ -194,7 +200,9 @@ async def test_create_transaction_invalid_account(session: AsyncSession, test_us
@pytest.mark.asyncio
-async def test_get_transactions_pagination(session: AsyncSession, test_user, test_workspace, txn_account):
+async def test_get_transactions_pagination(
+ session: AsyncSession, test_user, test_workspace, txn_account
+):
# Create 5 transactions
for i in range(5):
txn = Transaction(
@@ -211,7 +219,9 @@ async def test_get_transactions_pagination(session: AsyncSession, test_user, tes
session.add(txn)
await session.commit()
- page1, total, _ = await get_transactions(session, test_workspace.id, test_user.id, limit=2, page=1)
+ page1, total, _ = await get_transactions(
+ session, test_workspace.id, test_user.id, limit=2, page=1
+ )
assert total >= 5
assert len(page1) == 2
@@ -225,7 +235,9 @@ async def test_get_transactions_pagination(session: AsyncSession, test_user, tes
@pytest.mark.asyncio
-async def test_get_transactions_filter_by_account(session: AsyncSession, test_user, test_workspace, txn_account):
+async def test_get_transactions_filter_by_account(
+ session: AsyncSession, test_user, test_workspace, txn_account
+):
other_account = Account(
id=uuid.uuid4(),
user_id=test_user.id,
@@ -262,7 +274,9 @@ async def test_get_transactions_filter_by_account(session: AsyncSession, test_us
session.add_all([txn1, txn2])
await session.commit()
- results, _, _ = await get_transactions(session, test_workspace.id, test_user.id, account_id=txn_account.id)
+ results, _, _ = await get_transactions(
+ session, test_workspace.id, test_user.id, account_id=txn_account.id
+ )
descs = {t.description for t in results}
assert "In main" in descs
assert "In other" not in descs
@@ -299,14 +313,18 @@ async def test_get_transactions_filter_by_category(
session.add_all([txn1, txn2])
await session.commit()
- results, _, _ = await get_transactions(session, test_workspace.id, test_user.id, category_id=test_categories[0].id)
+ results, _, _ = await get_transactions(
+ session, test_workspace.id, test_user.id, category_id=test_categories[0].id
+ )
descs = {t.description for t in results}
assert "Cat A" in descs
assert "Cat B" not in descs
@pytest.mark.asyncio
-async def test_get_transactions_filter_by_date_range(session: AsyncSession, test_user, test_workspace, txn_account):
+async def test_get_transactions_filter_by_date_range(
+ session: AsyncSession, test_user, test_workspace, txn_account
+):
txn_jan = Transaction(
id=uuid.uuid4(),
user_id=test_user.id,
@@ -334,7 +352,8 @@ async def test_get_transactions_filter_by_date_range(session: AsyncSession, test
results, _, _ = await get_transactions(
session,
- test_workspace.id, test_user.id,
+ test_workspace.id,
+ test_user.id,
from_date=date(2025, 3, 1),
to_date=date(2025, 3, 31),
)
@@ -376,14 +395,18 @@ async def test_get_transactions_date_filter_respects_accounting_mode(
session.add_all([cc_purchase, regular])
await session.commit()
- april_window = dict(from_date=date(2025, 4, 1), to_date=date(2025, 4, 30))
- march_window = dict(from_date=date(2025, 3, 1), to_date=date(2025, 3, 31))
+ april_window: _TxFilter = dict(from_date=date(2025, 4, 1), to_date=date(2025, 4, 30))
+ march_window: _TxFilter = dict(from_date=date(2025, 3, 1), to_date=date(2025, 3, 31))
# Cash mode (default): the CC purchase lives in March, regular in April.
- cash_april, _, _ = await get_transactions(session, test_workspace.id, test_user.id, **april_window)
+ cash_april, _, _ = await get_transactions(
+ session, test_workspace.id, test_user.id, **april_window
+ )
assert {t.description for t in cash_april} == {"Regular"}
- cash_march, _, _ = await get_transactions(session, test_workspace.id, test_user.id, **march_window)
+ cash_march, _, _ = await get_transactions(
+ session, test_workspace.id, test_user.id, **march_window
+ )
assert {t.description for t in cash_march} == {"CC purchase"}
# Accrual mode: both buckets shift to the bill-due month.
@@ -399,7 +422,9 @@ async def test_get_transactions_date_filter_respects_accounting_mode(
@pytest.mark.asyncio
-async def test_get_transactions_filter_by_search(session: AsyncSession, test_user, test_workspace, txn_account):
+async def test_get_transactions_filter_by_search(
+ session: AsyncSession, test_user, test_workspace, txn_account
+):
txn = Transaction(
id=uuid.uuid4(),
user_id=test_user.id,
@@ -414,13 +439,17 @@ async def test_get_transactions_filter_by_search(session: AsyncSession, test_use
session.add(txn)
await session.commit()
- results, _, _ = await get_transactions(session, test_workspace.id, test_user.id, search="netflix")
+ results, _, _ = await get_transactions(
+ session, test_workspace.id, test_user.id, search="netflix"
+ )
descs = {t.description for t in results}
assert "NETFLIX SUBSCRIPTION" in descs
@pytest.mark.asyncio
-async def test_get_transactions_filter_by_type(session: AsyncSession, test_user, test_workspace, txn_account):
+async def test_get_transactions_filter_by_type(
+ session: AsyncSession, test_user, test_workspace, txn_account
+):
txn_debit = Transaction(
id=uuid.uuid4(),
user_id=test_user.id,
@@ -446,7 +475,9 @@ async def test_get_transactions_filter_by_type(session: AsyncSession, test_user,
session.add_all([txn_debit, txn_credit])
await session.commit()
- results, _, _ = await get_transactions(session, test_workspace.id, test_user.id, txn_type="credit")
+ results, _, _ = await get_transactions(
+ session, test_workspace.id, test_user.id, txn_type="credit"
+ )
types = {t.type for t in results}
assert "credit" in types
assert all(t.type == "credit" for t in results)
@@ -503,7 +534,8 @@ async def test_update_transaction(session: AsyncSession, test_user, test_workspa
updated = await update_transaction(
session,
txn.id,
- test_workspace.id, test_user.id,
+ test_workspace.id,
+ test_user.id,
TransactionUpdate(description="New", amount=Decimal("99")),
)
assert updated is not None
@@ -549,7 +581,9 @@ async def test_delete_transaction_not_found(session: AsyncSession, test_user, te
@pytest.mark.asyncio
-async def test_toggle_ignore_transaction(session: AsyncSession, test_user, test_workspace, txn_account):
+async def test_toggle_ignore_transaction(
+ session: AsyncSession, test_user, test_workspace, txn_account
+):
txn = Transaction(
id=uuid.uuid4(),
user_id=test_user.id,
@@ -576,7 +610,9 @@ async def test_toggle_ignore_transaction(session: AsyncSession, test_user, test_
@pytest.mark.asyncio
-async def test_toggle_ignore_transaction_not_found(session: AsyncSession, test_user, test_workspace):
+async def test_toggle_ignore_transaction_not_found(
+ session: AsyncSession, test_user, test_workspace
+):
assert await toggle_ignore_transaction(session, uuid.uuid4(), test_workspace.id) is None
@@ -586,7 +622,9 @@ async def test_toggle_ignore_transaction_not_found(session: AsyncSession, test_u
@pytest.mark.asyncio
-async def test_bulk_update_category(session: AsyncSession, test_user, test_workspace, test_categories, txn_account):
+async def test_bulk_update_category(
+ session: AsyncSession, test_user, test_workspace, test_categories, txn_account
+):
txns = []
for i in range(3):
txn = Transaction(
@@ -646,9 +684,14 @@ async def test_bulk_update_category_clear(
def test_apply_fx_override_both():
txn = Transaction(
- id=uuid.uuid4(), user_id=uuid.uuid4(), account_id=uuid.uuid4(),
- description="T", amount=Decimal("100"), date=date.today(),
- type="debit", source="manual",
+ id=uuid.uuid4(),
+ user_id=uuid.uuid4(),
+ account_id=uuid.uuid4(),
+ description="T",
+ amount=Decimal("100"),
+ date=date.today(),
+ type="debit",
+ source="manual",
)
_apply_fx_override(txn, 100, amount_primary=500.0, fx_rate_used=5.0)
assert txn.amount_primary == Decimal("500.0")
@@ -657,9 +700,14 @@ def test_apply_fx_override_both():
def test_apply_fx_override_only_amount_primary():
txn = Transaction(
- id=uuid.uuid4(), user_id=uuid.uuid4(), account_id=uuid.uuid4(),
- description="T", amount=Decimal("100"), date=date.today(),
- type="debit", source="manual",
+ id=uuid.uuid4(),
+ user_id=uuid.uuid4(),
+ account_id=uuid.uuid4(),
+ description="T",
+ amount=Decimal("100"),
+ date=date.today(),
+ type="debit",
+ source="manual",
)
_apply_fx_override(txn, 100, amount_primary=250.0)
assert txn.amount_primary == Decimal("250.0")
@@ -668,9 +716,14 @@ def test_apply_fx_override_only_amount_primary():
def test_apply_fx_override_only_fx_rate():
txn = Transaction(
- id=uuid.uuid4(), user_id=uuid.uuid4(), account_id=uuid.uuid4(),
- description="T", amount=Decimal("100"), date=date.today(),
- type="debit", source="manual",
+ id=uuid.uuid4(),
+ user_id=uuid.uuid4(),
+ account_id=uuid.uuid4(),
+ description="T",
+ amount=Decimal("100"),
+ date=date.today(),
+ type="debit",
+ source="manual",
)
_apply_fx_override(txn, 100, fx_rate_used=3.0)
assert txn.fx_rate_used == Decimal("3.0")
@@ -679,9 +732,14 @@ def test_apply_fx_override_only_fx_rate():
def test_apply_fx_override_zero_amount():
txn = Transaction(
- id=uuid.uuid4(), user_id=uuid.uuid4(), account_id=uuid.uuid4(),
- description="T", amount=Decimal("0"), date=date.today(),
- type="debit", source="manual",
+ id=uuid.uuid4(),
+ user_id=uuid.uuid4(),
+ account_id=uuid.uuid4(),
+ description="T",
+ amount=Decimal("0"),
+ date=date.today(),
+ type="debit",
+ source="manual",
)
_apply_fx_override(txn, 0, amount_primary=0.0)
assert txn.amount_primary == Decimal("0.0")
@@ -694,11 +752,17 @@ def test_apply_fx_override_zero_amount():
@pytest.mark.asyncio
-async def test_create_transaction_with_fx_override(session: AsyncSession, test_user, test_workspace, txn_account):
+async def test_create_transaction_with_fx_override(
+ session: AsyncSession, test_user, test_workspace, txn_account
+):
data = TransactionCreate(
- account_id=txn_account.id, description="USD Purchase",
- amount=Decimal("100"), date=date.today(), type="debit",
- amount_primary=Decimal("500"), fx_rate_used=Decimal("5"),
+ account_id=txn_account.id,
+ description="USD Purchase",
+ amount=Decimal("100"),
+ date=date.today(),
+ type="debit",
+ amount_primary=Decimal("500"),
+ fx_rate_used=Decimal("5"),
)
txn = await create_transaction(session, test_workspace.id, test_user.id, data)
assert txn.amount_primary == Decimal("500")
@@ -713,8 +777,12 @@ async def test_create_transaction_with_fx_override(session: AsyncSession, test_u
@pytest_asyncio.fixture
async def txn_account_usd(session: AsyncSession, test_user) -> Account:
acct = Account(
- id=uuid.uuid4(), user_id=test_user.id, name="USD Acct",
- type="checking", balance=Decimal("5000"), currency="USD",
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ name="USD Acct",
+ type="checking",
+ balance=Decimal("5000"),
+ currency="USD",
)
session.add(acct)
await session.commit()
@@ -723,17 +791,26 @@ async def txn_account_usd(session: AsyncSession, test_user) -> Account:
@pytest.mark.asyncio
-async def test_create_transfer_same_currency(session: AsyncSession, test_user, test_workspace, txn_account):
+async def test_create_transfer_same_currency(
+ session: AsyncSession, test_user, test_workspace, txn_account
+):
acct2 = Account(
- id=uuid.uuid4(), user_id=test_user.id, name="Savings",
- type="savings", balance=Decimal("0"), currency="BRL",
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ name="Savings",
+ type="savings",
+ balance=Decimal("0"),
+ currency="BRL",
)
session.add(acct2)
await session.commit()
data = TransferCreate(
- from_account_id=txn_account.id, to_account_id=acct2.id,
- description="Transfer", amount=Decimal("1000"), date=date.today(),
+ from_account_id=txn_account.id,
+ to_account_id=acct2.id,
+ description="Transfer",
+ amount=Decimal("1000"),
+ date=date.today(),
)
debit_tx, credit_tx = await create_transfer(session, test_workspace.id, test_user.id, data)
assert debit_tx.type == "debit"
@@ -743,20 +820,30 @@ async def test_create_transfer_same_currency(session: AsyncSession, test_user, t
@pytest.mark.asyncio
-async def test_create_transfer_same_account(session: AsyncSession, test_user, test_workspace, txn_account):
+async def test_create_transfer_same_account(
+ session: AsyncSession, test_user, test_workspace, txn_account
+):
data = TransferCreate(
- from_account_id=txn_account.id, to_account_id=txn_account.id,
- description="Self", amount=Decimal("100"), date=date.today(),
+ from_account_id=txn_account.id,
+ to_account_id=txn_account.id,
+ description="Self",
+ amount=Decimal("100"),
+ date=date.today(),
)
with pytest.raises(ValueError, match="same account"):
await create_transfer(session, test_workspace.id, test_user.id, data)
@pytest.mark.asyncio
-async def test_create_transfer_cross_currency(session: AsyncSession, test_user, test_workspace, txn_account, txn_account_usd):
+async def test_create_transfer_cross_currency(
+ session: AsyncSession, test_user, test_workspace, txn_account, txn_account_usd
+):
data = TransferCreate(
- from_account_id=txn_account.id, to_account_id=txn_account_usd.id,
- description="Cross-currency", amount=Decimal("500"), date=date.today(),
+ from_account_id=txn_account.id,
+ to_account_id=txn_account_usd.id,
+ description="Cross-currency",
+ amount=Decimal("500"),
+ date=date.today(),
fx_rate=Decimal("0.2"),
)
debit_tx, credit_tx = await create_transfer(session, test_workspace.id, test_user.id, data)
@@ -766,10 +853,15 @@ async def test_create_transfer_cross_currency(session: AsyncSession, test_user,
@pytest.mark.asyncio
-async def test_create_transfer_cross_currency_auto_fx(session: AsyncSession, test_user, test_workspace, txn_account, txn_account_usd):
+async def test_create_transfer_cross_currency_auto_fx(
+ session: AsyncSession, test_user, test_workspace, txn_account, txn_account_usd
+):
data = TransferCreate(
- from_account_id=txn_account.id, to_account_id=txn_account_usd.id,
- description="Auto FX", amount=Decimal("500"), date=date.today(),
+ from_account_id=txn_account.id,
+ to_account_id=txn_account_usd.id,
+ description="Auto FX",
+ amount=Decimal("500"),
+ date=date.today(),
)
debit_tx, credit_tx = await create_transfer(session, test_workspace.id, test_user.id, data)
assert debit_tx.type == "debit"
@@ -777,20 +869,30 @@ async def test_create_transfer_cross_currency_auto_fx(session: AsyncSession, tes
@pytest.mark.asyncio
-async def test_create_transfer_invalid_from_account(session: AsyncSession, test_user, test_workspace, txn_account):
+async def test_create_transfer_invalid_from_account(
+ session: AsyncSession, test_user, test_workspace, txn_account
+):
data = TransferCreate(
- from_account_id=uuid.uuid4(), to_account_id=txn_account.id,
- description="Bad from", amount=Decimal("100"), date=date.today(),
+ from_account_id=uuid.uuid4(),
+ to_account_id=txn_account.id,
+ description="Bad from",
+ amount=Decimal("100"),
+ date=date.today(),
)
with pytest.raises(ValueError, match="Source account not found"):
await create_transfer(session, test_workspace.id, test_user.id, data)
@pytest.mark.asyncio
-async def test_create_transfer_invalid_to_account(session: AsyncSession, test_user, test_workspace, txn_account):
+async def test_create_transfer_invalid_to_account(
+ session: AsyncSession, test_user, test_workspace, txn_account
+):
data = TransferCreate(
- from_account_id=txn_account.id, to_account_id=uuid.uuid4(),
- description="Bad to", amount=Decimal("100"), date=date.today(),
+ from_account_id=txn_account.id,
+ to_account_id=uuid.uuid4(),
+ description="Bad to",
+ amount=Decimal("100"),
+ date=date.today(),
)
with pytest.raises(ValueError, match="Destination account not found"):
await create_transfer(session, test_workspace.id, test_user.id, data)
@@ -802,71 +904,148 @@ async def test_create_transfer_invalid_to_account(session: AsyncSession, test_us
@pytest.mark.asyncio
-async def test_get_transactions_uncategorized(session: AsyncSession, test_user, test_workspace, txn_account, test_categories):
- await create_transaction(session, test_workspace.id, test_user.id, TransactionCreate(
- account_id=txn_account.id, description="Uncategorized",
- amount=Decimal("50"), date=date.today(), type="debit",
- ))
- await create_transaction(session, test_workspace.id, test_user.id, TransactionCreate(
- account_id=txn_account.id, description="Categorized",
- amount=Decimal("50"), date=date.today(), type="debit",
- category_id=test_categories[0].id,
- ))
- txns, _, _ = await get_transactions(session, test_workspace.id, test_user.id, uncategorized=True)
+async def test_get_transactions_uncategorized(
+ session: AsyncSession, test_user, test_workspace, txn_account, test_categories
+):
+ await create_transaction(
+ session,
+ test_workspace.id,
+ test_user.id,
+ TransactionCreate(
+ account_id=txn_account.id,
+ description="Uncategorized",
+ amount=Decimal("50"),
+ date=date.today(),
+ type="debit",
+ ),
+ )
+ await create_transaction(
+ session,
+ test_workspace.id,
+ test_user.id,
+ TransactionCreate(
+ account_id=txn_account.id,
+ description="Categorized",
+ amount=Decimal("50"),
+ date=date.today(),
+ type="debit",
+ category_id=test_categories[0].id,
+ ),
+ )
+ txns, _, _ = await get_transactions(
+ session, test_workspace.id, test_user.id, uncategorized=True
+ )
descs = [t.description for t in txns]
assert "Uncategorized" in descs
assert "Categorized" not in descs
@pytest.mark.asyncio
-async def test_get_transactions_date_filter(session: AsyncSession, test_user, test_workspace, txn_account):
+async def test_get_transactions_date_filter(
+ session: AsyncSession, test_user, test_workspace, txn_account
+):
from datetime import timedelta
+
today = date.today()
yesterday = today - timedelta(days=1)
- await create_transaction(session, test_workspace.id, test_user.id, TransactionCreate(
- account_id=txn_account.id, description="Today",
- amount=Decimal("10"), date=today, type="debit",
- ))
- await create_transaction(session, test_workspace.id, test_user.id, TransactionCreate(
- account_id=txn_account.id, description="Yesterday",
- amount=Decimal("10"), date=yesterday, type="debit",
- ))
- txns, _, _ = await get_transactions(session, test_workspace.id, test_user.id, from_date=today, to_date=today)
+ await create_transaction(
+ session,
+ test_workspace.id,
+ test_user.id,
+ TransactionCreate(
+ account_id=txn_account.id,
+ description="Today",
+ amount=Decimal("10"),
+ date=today,
+ type="debit",
+ ),
+ )
+ await create_transaction(
+ session,
+ test_workspace.id,
+ test_user.id,
+ TransactionCreate(
+ account_id=txn_account.id,
+ description="Yesterday",
+ amount=Decimal("10"),
+ date=yesterday,
+ type="debit",
+ ),
+ )
+ txns, _, _ = await get_transactions(
+ session, test_workspace.id, test_user.id, from_date=today, to_date=today
+ )
descs = [t.description for t in txns]
assert "Today" in descs
assert "Yesterday" not in descs
@pytest.mark.asyncio
-async def test_get_transactions_exclude_transfers(session: AsyncSession, test_user, test_workspace, txn_account):
+async def test_get_transactions_exclude_transfers(
+ session: AsyncSession, test_user, test_workspace, txn_account
+):
acct2 = Account(
- id=uuid.uuid4(), user_id=test_user.id, name="Sav",
- type="savings", balance=Decimal("0"), currency="BRL",
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ name="Sav",
+ type="savings",
+ balance=Decimal("0"),
+ currency="BRL",
)
session.add(acct2)
await session.commit()
- await create_transfer(session, test_workspace.id, test_user.id, TransferCreate(
- from_account_id=txn_account.id, to_account_id=acct2.id,
- description="Xfer", amount=Decimal("100"), date=date.today(),
- ))
- await create_transaction(session, test_workspace.id, test_user.id, TransactionCreate(
- account_id=txn_account.id, description="Regular",
- amount=Decimal("50"), date=date.today(), type="debit",
- ))
- txns, _, _ = await get_transactions(session, test_workspace.id, test_user.id, exclude_transfers=True)
+ await create_transfer(
+ session,
+ test_workspace.id,
+ test_user.id,
+ TransferCreate(
+ from_account_id=txn_account.id,
+ to_account_id=acct2.id,
+ description="Xfer",
+ amount=Decimal("100"),
+ date=date.today(),
+ ),
+ )
+ await create_transaction(
+ session,
+ test_workspace.id,
+ test_user.id,
+ TransactionCreate(
+ account_id=txn_account.id,
+ description="Regular",
+ amount=Decimal("50"),
+ date=date.today(),
+ type="debit",
+ ),
+ )
+ txns, _, _ = await get_transactions(
+ session, test_workspace.id, test_user.id, exclude_transfers=True
+ )
descs = [t.description for t in txns]
assert "Regular" in descs
@pytest.mark.asyncio
-async def test_get_transactions_skip_pagination(session: AsyncSession, test_user, test_workspace, txn_account):
+async def test_get_transactions_skip_pagination(
+ session: AsyncSession, test_user, test_workspace, txn_account
+):
for i in range(5):
- await create_transaction(session, test_workspace.id, test_user.id, TransactionCreate(
- account_id=txn_account.id, description=f"Txn{i}",
- amount=Decimal("10"), date=date.today(), type="debit",
- ))
- txns, total, _ = await get_transactions(session, test_workspace.id, test_user.id, skip_pagination=True, limit=2)
+ await create_transaction(
+ session,
+ test_workspace.id,
+ test_user.id,
+ TransactionCreate(
+ account_id=txn_account.id,
+ description=f"Txn{i}",
+ amount=Decimal("10"),
+ date=date.today(),
+ type="debit",
+ ),
+ )
+ txns, total, _ = await get_transactions(
+ session, test_workspace.id, test_user.id, skip_pagination=True, limit=2
+ )
assert len(txns) == total
@@ -876,45 +1055,87 @@ async def test_get_transactions_skip_pagination(session: AsyncSession, test_user
@pytest.mark.asyncio
-async def test_update_transaction_fx_override(session: AsyncSession, test_user, test_workspace, txn_account):
- txn = await create_transaction(session, test_workspace.id, test_user.id, TransactionCreate(
- account_id=txn_account.id, description="FX Test",
- amount=Decimal("100"), date=date.today(), type="debit",
- ))
+async def test_update_transaction_fx_override(
+ session: AsyncSession, test_user, test_workspace, txn_account
+):
+ txn = await create_transaction(
+ session,
+ test_workspace.id,
+ test_user.id,
+ TransactionCreate(
+ account_id=txn_account.id,
+ description="FX Test",
+ amount=Decimal("100"),
+ date=date.today(),
+ type="debit",
+ ),
+ )
data = TransactionUpdate(amount_primary=Decimal("500"), fx_rate_used=Decimal("5"))
updated = await update_transaction(session, txn.id, test_workspace.id, test_user.id, data)
+
+ assert updated is not None
assert updated.amount_primary == Decimal("500")
@pytest.mark.asyncio
-async def test_update_transaction_restamp_on_amount_change(session: AsyncSession, test_user, test_workspace, txn_account):
- txn = await create_transaction(session, test_workspace.id, test_user.id, TransactionCreate(
- account_id=txn_account.id, description="Restamp",
- amount=Decimal("100"), date=date.today(), type="debit",
- ))
+async def test_update_transaction_restamp_on_amount_change(
+ session: AsyncSession, test_user, test_workspace, txn_account
+):
+ txn = await create_transaction(
+ session,
+ test_workspace.id,
+ test_user.id,
+ TransactionCreate(
+ account_id=txn_account.id,
+ description="Restamp",
+ amount=Decimal("100"),
+ date=date.today(),
+ type="debit",
+ ),
+ )
data = TransactionUpdate(amount=Decimal("200"))
updated = await update_transaction(session, txn.id, test_workspace.id, test_user.id, data)
+
+ assert updated is not None
assert updated.amount == Decimal("200")
@pytest.mark.asyncio
-async def test_update_transfer_cascades(session: AsyncSession, test_user, test_workspace, txn_account):
+async def test_update_transfer_cascades(
+ session: AsyncSession, test_user, test_workspace, txn_account
+):
acct2 = Account(
- id=uuid.uuid4(), user_id=test_user.id, name="CascSav",
- type="savings", balance=Decimal("0"), currency="BRL",
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ name="CascSav",
+ type="savings",
+ balance=Decimal("0"),
+ currency="BRL",
)
session.add(acct2)
await session.commit()
- debit_tx, credit_tx = await create_transfer(session, test_workspace.id, test_user.id, TransferCreate(
- from_account_id=txn_account.id, to_account_id=acct2.id,
- description="Cascade Xfer", amount=Decimal("200"), date=date.today(),
- ))
+ debit_tx, credit_tx = await create_transfer(
+ session,
+ test_workspace.id,
+ test_user.id,
+ TransferCreate(
+ from_account_id=txn_account.id,
+ to_account_id=acct2.id,
+ description="Cascade Xfer",
+ amount=Decimal("200"),
+ date=date.today(),
+ ),
+ )
data = TransactionUpdate(description="Updated Xfer")
updated = await update_transaction(session, debit_tx.id, test_workspace.id, test_user.id, data)
+
+ assert updated is not None
assert updated.description == "Updated Xfer"
paired = await get_transaction(session, credit_tx.id, test_workspace.id)
+
+ assert paired is not None
assert paired.description == "Updated Xfer"
@@ -924,18 +1145,32 @@ async def test_update_transfer_cascades(session: AsyncSession, test_user, test_w
@pytest.mark.asyncio
-async def test_delete_transfer_cascades(session: AsyncSession, test_user, test_workspace, txn_account):
+async def test_delete_transfer_cascades(
+ session: AsyncSession, test_user, test_workspace, txn_account
+):
acct2 = Account(
- id=uuid.uuid4(), user_id=test_user.id, name="DelSav",
- type="savings", balance=Decimal("0"), currency="BRL",
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ name="DelSav",
+ type="savings",
+ balance=Decimal("0"),
+ currency="BRL",
)
session.add(acct2)
await session.commit()
- debit_tx, credit_tx = await create_transfer(session, test_workspace.id, test_user.id, TransferCreate(
- from_account_id=txn_account.id, to_account_id=acct2.id,
- description="Del Xfer", amount=Decimal("300"), date=date.today(),
- ))
+ debit_tx, credit_tx = await create_transfer(
+ session,
+ test_workspace.id,
+ test_user.id,
+ TransferCreate(
+ from_account_id=txn_account.id,
+ to_account_id=acct2.id,
+ description="Del Xfer",
+ amount=Decimal("300"),
+ date=date.today(),
+ ),
+ )
assert await delete_transaction(session, debit_tx.id, test_workspace.id) is True
assert await get_transaction(session, credit_tx.id, test_workspace.id) is None
@@ -950,19 +1185,34 @@ async def test_update_transaction_changes_account(
session: AsyncSession, test_user, test_workspace, txn_account
):
other_account = Account(
- id=uuid.uuid4(), user_id=test_user.id, name="OtherAcc",
- type="checking", balance=Decimal("0"), currency="BRL",
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ name="OtherAcc",
+ type="checking",
+ balance=Decimal("0"),
+ currency="BRL",
)
session.add(other_account)
await session.commit()
- txn = await create_transaction(session, test_workspace.id, test_user.id, TransactionCreate(
- account_id=txn_account.id, description="Move me",
- amount=Decimal("42"), date=date.today(), type="debit",
- ))
+ txn = await create_transaction(
+ session,
+ test_workspace.id,
+ test_user.id,
+ TransactionCreate(
+ account_id=txn_account.id,
+ description="Move me",
+ amount=Decimal("42"),
+ date=date.today(),
+ type="debit",
+ ),
+ )
updated = await update_transaction(
- session, txn.id, test_workspace.id, test_user.id,
+ session,
+ txn.id,
+ test_workspace.id,
+ test_user.id,
TransactionUpdate(account_id=other_account.id),
)
assert updated is not None
@@ -970,6 +1220,8 @@ async def test_update_transaction_changes_account(
# Re-fetch to make sure the change was committed, not just set in memory.
reloaded = await get_transaction(session, txn.id, test_workspace.id)
+
+ assert reloaded is not None
assert reloaded.account_id == other_account.id
@@ -986,27 +1238,45 @@ async def test_update_transaction_rejects_foreign_account(
id=uuid.uuid4(),
hashed_password=_bcrypt.hashpw(b"x", _bcrypt.gensalt()).decode(),
- is_active=True, is_superuser=False, is_verified=True,
+ is_active=True,
+ is_superuser=False,
+ is_verified=True,
)
session.add(other_user)
await session.commit()
other_ws = await create_personal_workspace_for_user(session, other_user)
await session.commit()
foreign_account = Account(
- id=uuid.uuid4(), user_id=other_user.id, workspace_id=other_ws.id, name="ForeignAcc",
- type="checking", balance=Decimal("0"), currency="BRL",
+ id=uuid.uuid4(),
+ user_id=other_user.id,
+ workspace_id=other_ws.id,
+ name="ForeignAcc",
+ type="checking",
+ balance=Decimal("0"),
+ currency="BRL",
)
session.add(foreign_account)
await session.commit()
- txn = await create_transaction(session, test_workspace.id, test_user.id, TransactionCreate(
- account_id=txn_account.id, description="Stay put",
- amount=Decimal("10"), date=date.today(), type="debit",
- ))
+ txn = await create_transaction(
+ session,
+ test_workspace.id,
+ test_user.id,
+ TransactionCreate(
+ account_id=txn_account.id,
+ description="Stay put",
+ amount=Decimal("10"),
+ date=date.today(),
+ type="debit",
+ ),
+ )
with pytest.raises(ValueError, match="Account not found"):
await update_transaction(
- session, txn.id, test_workspace.id, test_user.id,
+ session,
+ txn.id,
+ test_workspace.id,
+ test_user.id,
TransactionUpdate(account_id=foreign_account.id),
)
@@ -1016,22 +1286,37 @@ async def test_update_transfer_rejects_collapsing_accounts(
session: AsyncSession, test_user, test_workspace, txn_account
):
acct2 = Account(
- id=uuid.uuid4(), user_id=test_user.id, name="XferSav",
- type="savings", balance=Decimal("0"), currency="BRL",
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ name="XferSav",
+ type="savings",
+ balance=Decimal("0"),
+ currency="BRL",
)
session.add(acct2)
await session.commit()
- debit_tx, credit_tx = await create_transfer(session, test_workspace.id, test_user.id, TransferCreate(
- from_account_id=txn_account.id, to_account_id=acct2.id,
- description="Xfer", amount=Decimal("100"), date=date.today(),
- ))
+ debit_tx, credit_tx = await create_transfer(
+ session,
+ test_workspace.id,
+ test_user.id,
+ TransferCreate(
+ from_account_id=txn_account.id,
+ to_account_id=acct2.id,
+ description="Xfer",
+ amount=Decimal("100"),
+ date=date.today(),
+ ),
+ )
# Moving the debit side to acct2 would put both legs of the transfer
# in the same account, which is invalid.
with pytest.raises(ValueError, match="same account"):
await update_transaction(
- session, debit_tx.id, test_workspace.id, test_user.id,
+ session,
+ debit_tx.id,
+ test_workspace.id,
+ test_user.id,
TransactionUpdate(account_id=acct2.id),
)
@@ -1048,9 +1333,15 @@ async def test_get_transactions_filters_tags_with_exact_match(
"""Filtering by `#test` must NOT match `#test2` — exact tag boundaries."""
txns = [
Transaction(
- id=uuid.uuid4(), user_id=test_user.id, account_id=txn_account.id,
- description=desc, amount=Decimal("10"), date=date(2026, 1, day),
- type="debit", source="manual", notes=notes,
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ account_id=txn_account.id,
+ description=desc,
+ amount=Decimal("10"),
+ date=date(2026, 1, day),
+ type="debit",
+ source="manual",
+ notes=notes,
created_at=datetime.now(timezone.utc),
)
for day, desc, notes in [
@@ -1080,9 +1371,15 @@ async def test_get_transactions_filters_multiple_tags_with_or(
of the requested tags — issue #88."""
txns = [
Transaction(
- id=uuid.uuid4(), user_id=test_user.id, account_id=txn_account.id,
- description=desc, amount=Decimal("10"), date=date(2026, 1, day),
- type="debit", source="manual", notes=notes,
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ account_id=txn_account.id,
+ description=desc,
+ amount=Decimal("10"),
+ date=date(2026, 1, day),
+ type="debit",
+ source="manual",
+ notes=notes,
created_at=datetime.now(timezone.utc),
)
for day, desc, notes in [
@@ -1107,29 +1404,45 @@ async def test_bulk_add_tags_appends_to_each_transaction(
):
"""bulk_add_tags must add the given tags to each tx, skipping duplicates."""
t1 = Transaction(
- id=uuid.uuid4(), user_id=test_user.id, account_id=txn_account.id,
- description="A", amount=Decimal("10"), date=date.today(),
- type="debit", source="manual", notes=None,
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ account_id=txn_account.id,
+ description="A",
+ amount=Decimal("10"),
+ date=date.today(),
+ type="debit",
+ source="manual",
+ notes=None,
created_at=datetime.now(timezone.utc),
)
t2 = Transaction(
- id=uuid.uuid4(), user_id=test_user.id, account_id=txn_account.id,
- description="B", amount=Decimal("10"), date=date.today(),
- type="debit", source="manual", notes="existing #work note",
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ account_id=txn_account.id,
+ description="B",
+ amount=Decimal("10"),
+ date=date.today(),
+ type="debit",
+ source="manual",
+ notes="existing #work note",
created_at=datetime.now(timezone.utc),
)
t3 = Transaction(
- id=uuid.uuid4(), user_id=test_user.id, account_id=txn_account.id,
- description="C", amount=Decimal("10"), date=date.today(),
- type="debit", source="manual", notes="#groceries already here",
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ account_id=txn_account.id,
+ description="C",
+ amount=Decimal("10"),
+ date=date.today(),
+ type="debit",
+ source="manual",
+ notes="#groceries already here",
created_at=datetime.now(timezone.utc),
)
session.add_all([t1, t2, t3])
await session.commit()
- touched = await bulk_add_tags(
- session, test_workspace.id, [t1.id, t2.id, t3.id], ["#groceries"]
- )
+ touched = await bulk_add_tags(session, test_workspace.id, [t1.id, t2.id, t3.id], ["#groceries"])
assert touched == 2 # t3 already has it
await session.refresh(t1)
@@ -1146,23 +1459,33 @@ async def test_bulk_remove_tags_clears_only_exact_matches(
):
"""Removing `#test` must NOT touch `#test2` — exact match boundary."""
t1 = Transaction(
- id=uuid.uuid4(), user_id=test_user.id, account_id=txn_account.id,
- description="A", amount=Decimal("10"), date=date.today(),
- type="debit", source="manual", notes="#test #keep",
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ account_id=txn_account.id,
+ description="A",
+ amount=Decimal("10"),
+ date=date.today(),
+ type="debit",
+ source="manual",
+ notes="#test #keep",
created_at=datetime.now(timezone.utc),
)
t2 = Transaction(
- id=uuid.uuid4(), user_id=test_user.id, account_id=txn_account.id,
- description="B", amount=Decimal("10"), date=date.today(),
- type="debit", source="manual", notes="#test2 untouched",
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ account_id=txn_account.id,
+ description="B",
+ amount=Decimal("10"),
+ date=date.today(),
+ type="debit",
+ source="manual",
+ notes="#test2 untouched",
created_at=datetime.now(timezone.utc),
)
session.add_all([t1, t2])
await session.commit()
- touched = await bulk_remove_tags(
- session, test_workspace.id, [t1.id, t2.id], ["#test"]
- )
+ touched = await bulk_remove_tags(session, test_workspace.id, [t1.id, t2.id], ["#test"])
assert touched == 1
await session.refresh(t1)
diff --git a/backend/tests/test_transaction_service_coverage.py b/backend/tests/test_transaction_service_coverage.py
index 4a4459c0..e70a9225 100644
--- a/backend/tests/test_transaction_service_coverage.py
+++ b/backend/tests/test_transaction_service_coverage.py
@@ -14,6 +14,7 @@ import pytest
import pytest_asyncio
from sqlalchemy.ext.asyncio import AsyncSession
+from app.models import User, Workspace
from app.models.account import Account
from app.models.credit_card_bill import CreditCardBill
from app.models.group import Group, GroupMember
@@ -80,7 +81,7 @@ async def acct_usd(session: AsyncSession, test_user) -> Account:
@pytest_asyncio.fixture
-async def cc_account(session: AsyncSession, test_user) -> Account:
+async def cc_account(session: AsyncSession, test_user: User) -> Account:
account = Account(
id=uuid.uuid4(),
user_id=test_user.id,
@@ -97,7 +98,7 @@ async def cc_account(session: AsyncSession, test_user) -> Account:
return account
-async def _mk_txn(session, test_user, account, **kw) -> Transaction:
+async def _mk_txn(session: AsyncSession, test_user: User, account: Account, **kw) -> Transaction:
defaults = dict(
id=uuid.uuid4(),
user_id=test_user.id,
@@ -117,7 +118,7 @@ async def _mk_txn(session, test_user, account, **kw) -> Transaction:
return txn
-async def _mk_group(session, test_user, test_workspace, with_self=True, n_members=2):
+async def _mk_group(session: AsyncSession, test_user: User, test_workspace: Workspace, with_self=True, n_members=2):
group = Group(
id=uuid.uuid4(),
user_id=test_user.id,
@@ -247,6 +248,8 @@ async def test_get_transactions_summary_excludes_ignored(session, test_user, tes
_, _, summary = await get_transactions(
session, test_workspace.id, test_user.id, include_summary=True
)
+
+ assert summary is not None
assert summary["expense"] == Decimal("100")
# The ignored row leaves income/expense but surfaces in `excluded` (#242).
assert summary["excluded"] == Decimal("999")
@@ -280,6 +283,8 @@ async def test_get_transactions_summary_excludes_ignored_category(
_, _, summary = await get_transactions(
session, test_workspace.id, test_user.id, include_summary=True
)
+
+ assert summary is not None
assert summary["expense"] == Decimal("100")
assert summary["excluded"] == Decimal("999")
@@ -315,6 +320,8 @@ async def test_get_transactions_summary_excludes_transfers_and_treat_as_transfer
_, _, summary = await get_transactions(
session, test_workspace.id, test_user.id, include_summary=True
)
+
+ assert summary is not None
assert summary["income"] == Decimal("2000")
assert summary["expense"] == Decimal("800")
assert summary["net"] == Decimal("1200")
@@ -323,7 +330,7 @@ async def test_get_transactions_summary_excludes_transfers_and_treat_as_transfer
async def test_get_transactions_user_pnl_only_returns_only_dashboard_reportable_rows(
- session, test_user, test_workspace, acct
+ session: AsyncSession, test_user: User, test_workspace: Workspace, acct
):
from app.models.category import Category
@@ -363,6 +370,8 @@ async def test_get_transactions_user_pnl_only_returns_only_dashboard_reportable_
assert {tx.description for tx in rows} == {"Salary", "Rent"}
assert total == 2
+
+ assert summary is not None
assert summary["income"] == Decimal("1000")
assert summary["expense"] == Decimal("300")
assert summary["excluded"] == Decimal("0")
@@ -397,7 +406,7 @@ async def test_get_transactions_sorting(session, test_user, test_workspace, acct
# ---------------------------------------------------------------------------
-async def test_get_transactions_group_scope(session, test_user, test_workspace, acct):
+async def test_get_transactions_group_scope(session: AsyncSession, test_user: User, test_workspace: Workspace, acct):
group, members = await _mk_group(session, test_user, test_workspace)
txn = await _mk_txn(session, test_user, acct, description="Shared dinner", amount=Decimal("100"))
# Split among the two non-self members
@@ -417,7 +426,7 @@ async def test_get_transactions_group_scope(session, test_user, test_workspace,
assert total == 1
-async def test_get_transactions_group_scope_not_visible(session, test_user, test_workspace, acct):
+async def test_get_transactions_group_scope_not_visible(session: AsyncSession, test_user: User, test_workspace: Workspace, acct):
# A random group id the user cannot see returns the early-out tuple.
result = await get_transactions(
session, test_workspace.id, test_user.id, group_id=uuid.uuid4()
@@ -427,7 +436,7 @@ async def test_get_transactions_group_scope_not_visible(session, test_user, test
assert result[1] == 0
-async def test_get_transactions_owner_share_tagging(session, test_user, test_workspace, acct):
+async def test_get_transactions_owner_share_tagging(session: AsyncSession, test_user: User, test_workspace: Workspace, acct):
"""Owner with a self-split should get group_id and viewer_share tagged."""
group, members = await _mk_group(session, test_user, test_workspace)
txn = await _mk_txn(session, test_user, acct, description="With self share", amount=Decimal("90"))
@@ -444,6 +453,8 @@ async def test_get_transactions_owner_share_tagging(session, test_user, test_wor
res, _, _ = await get_transactions(session, test_workspace.id, test_user.id)
tagged = next(t for t in res if t.description == "With self share")
+
+ assert tagged is not None
assert tagged.group_id == group.id
assert tagged.is_shared is False
assert tagged.viewer_share == Decimal("45.00")
@@ -679,6 +690,8 @@ async def test_update_transaction_with_splits(session, test_user, test_workspace
session, txn.id, test_workspace.id, test_user.id,
TransactionUpdate(splits=payload),
)
+
+ assert updated is not None
assert len(updated.splits) == 2
@@ -706,8 +719,12 @@ async def test_update_transfer_cascades_amount_cross_currency(session, test_user
session, debit.id, test_workspace.id, test_user.id,
TransactionUpdate(amount=Decimal("1000")),
)
+
+ assert updated is not None
assert updated.amount == Decimal("1000")
paired = await get_transaction(session, credit.id, test_workspace.id)
+
+ assert paired is not None
# The cross-currency cascade branch ran: paired amount was re-converted
# (rate is 1:1 in tests since no FX rate is seeded, so it tracks 1000).
assert paired.amount == Decimal("1000")
@@ -729,6 +746,8 @@ async def test_update_transfer_cascade_category(session, test_user, test_workspa
TransactionUpdate(category_id=test_categories[0].id, apply_to_transfer_pair=True),
)
paired = await get_transaction(session, credit.id, test_workspace.id)
+
+ assert paired is not None
assert paired.category_id == test_categories[0].id
@@ -748,6 +767,8 @@ async def test_update_transaction_effective_bill_date_links_bill(session, test_u
session, txn.id, test_workspace.id, test_user.id,
TransactionUpdate(effective_bill_date=date(2025, 4, 20)),
)
+
+ assert updated is not None
assert updated.bill_id == bill.id
assert updated.effective_date == date(2025, 4, 20)
@@ -761,6 +782,8 @@ async def test_update_transaction_effective_bill_date_no_match(session, test_use
session, txn.id, test_workspace.id, test_user.id,
TransactionUpdate(effective_bill_date=date(2099, 1, 1)),
)
+
+ assert updated is not None
assert updated.bill_id is None
assert updated.effective_date == date(2099, 1, 1)
@@ -783,6 +806,7 @@ async def test_update_transaction_clear_bill_override_recovers_pluggy(session, t
session, txn.id, test_workspace.id, test_user.id,
TransactionUpdate(effective_bill_date=None),
)
+ assert updated is not None
assert updated.bill_id == bill.id
@@ -796,6 +820,7 @@ async def test_update_transaction_clear_bill_override_no_raw(session, test_user,
session, txn.id, test_workspace.id, test_user.id,
TransactionUpdate(effective_bill_date=None),
)
+ assert updated is not None
assert updated.bill_id is None