Files
WYGIWYH/app/apps/api/views/accounts.py
T
Herculino Trotta 4754f7e022 feat(api): serve a native MCP server at /mcp
Off unless MCP_ENABLED=true. Runs inside the web app (stateless Streamable
HTTP, JSON responses), so no extra container or supervisord program.

- Tools run the REST views in-process as the caller, so permissions,
  sharing, validation and transaction rules stay the API's.
- 11 curated tools with compact output, plus search_api/call_api to reach
  every other API endpoint from the OpenAPI schema.
- OAuth protected-resource metadata (RFC 9728) and a WWW-Authenticate hint
  on 401s, so MCP clients find the existing OAuth server and DCR.
- GET /api/transactions/summary/: totals per currency and type, optionally
  grouped by category, tag, entity, account or month.

API changes found while testing it:

- Writes no longer need Django model permissions, which nothing granted;
  access now matches the web UI (signed-in user, scoped querysets, owner-only
  edits of shared objects). API tokens and OAuth apps can now write for
  regular users.
- Account group owner is read-only; it could be set to another user.
- Reject negative installment, recurring, DCA and exchange-rate amounts, a
  zero recurrence interval, and performance on non-investment accounts.
- Accounts can be archived; group_id/exchange_currency_id are optional;
  category accepts null; currency prefix/suffix keep their spaces.
- Transactions filter by tags and entities.
- OpenAPI: separate request schemas (COMPONENT_SPLIT_REQUEST) and real
  descriptions for the viewsets and DCA chart actions.
2026-11-15 16:29:06 -03:00

121 lines
4.4 KiB
Python

from drf_spectacular.utils import extend_schema, extend_schema_view
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.exceptions import ValidationError
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from apps.accounts.models import AccountGroup, Account, InvestmentClass
from apps.accounts.services import get_account_balance
from apps.api.permissions import SHARED_OBJECT_PERMISSIONS
from apps.api.serializers import (
AccountGroupSerializer,
InvestmentClassSerializer,
AccountSerializer,
AccountBalanceSerializer,
InvestmentPerformanceSerializer,
)
from apps.investments.services import get_holding_performance
class AccountGroupViewSet(viewsets.ModelViewSet):
"""Groups that organize accounts, e.g. by bank."""
permission_classes = SHARED_OBJECT_PERMISSIONS
queryset = AccountGroup.objects.all()
serializer_class = AccountGroupSerializer
filterset_fields = {
"name": ["exact", "icontains"],
"owner": ["exact"],
}
search_fields = ["name"]
ordering_fields = "__all__"
ordering = ["id"]
def get_queryset(self):
return AccountGroup.objects.all()
class InvestmentClassViewSet(viewsets.ModelViewSet):
"""Asset classes (e.g. stocks, fixed income) that group investment accounts,
each with a target share of the portfolio in percent."""
queryset = InvestmentClass.objects.all()
serializer_class = InvestmentClassSerializer
filterset_fields = {"name": ["exact", "icontains"]}
search_fields = ["name"]
ordering_fields = "__all__"
ordering = ["id"]
def get_queryset(self):
return InvestmentClass.objects.all()
@extend_schema_view(
balance=extend_schema(
summary="Get account balance",
description="Returns the current and projected balance for the account, along with currency data.",
responses={200: AccountBalanceSerializer},
),
performance=extend_schema(
summary="Get investment performance",
description="Returns quantity, cost basis, market value, realized/unrealized gains, income and total return, in the account's exchange currency (or its own currency when it has none).",
responses={200: InvestmentPerformanceSerializer},
),
)
class AccountViewSet(viewsets.ModelViewSet):
"""Accounts hold transactions in one currency; `exchange_currency` is the
currency their amounts are converted to. Asset accounts count towards net
worth but not towards the month; archived ones count towards neither."""
permission_classes = SHARED_OBJECT_PERMISSIONS
queryset = Account.objects.all()
serializer_class = AccountSerializer
filterset_fields = {
"name": ["exact", "icontains"],
"group": ["exact", "isnull"],
"investment_class": ["exact", "isnull"],
"currency": ["exact"],
"exchange_currency": ["exact", "isnull"],
"is_asset": ["exact"],
"is_investment": ["exact"],
"is_archived": ["exact"],
"owner": ["exact"],
}
search_fields = ["name"]
ordering_fields = "__all__"
ordering = ["id"]
def get_queryset(self):
return Account.objects.all().select_related(
"group", "currency", "exchange_currency", "investment_class"
)
@action(detail=True, methods=["get"], permission_classes=[IsAuthenticated])
def balance(self, request, pk=None):
"""Get current and projected balance for an account."""
account = self.get_object()
current_balance = get_account_balance(account, paid_only=True)
projected_balance = get_account_balance(account, paid_only=False)
serializer = AccountBalanceSerializer(
{
"current_balance": current_balance,
"projected_balance": projected_balance,
"currency": account.currency,
}
)
return Response(serializer.data)
@action(detail=True, methods=["get"], permission_classes=[IsAuthenticated])
def performance(self, request, pk=None):
"""Get investment performance (cost basis, value, returns) for an account."""
account = self.get_object()
if not account.is_investment:
raise ValidationError({"detail": "Only investment accounts have performance."})
return Response(
InvestmentPerformanceSerializer(get_holding_performance(account)).data
)