Merge remote-tracking branch 'origin/main'

This commit is contained in:
Weblate committed 2026-11-15 19:44:44 +00:00
commit 82bcb635ef
17 files changed
+1220 -58

No files matched your search

+3
View File
@@ -47,6 +47,9 @@ TASK_WORKERS=1 # This only work if you're using the single container option. Inc
# Personal access tokens. How often (seconds) a token's last_used_at is rewritten.
#API_TOKEN_LAST_USED_UPDATE_INTERVAL=600
# Native MCP server at /mcp/, served by the web app itself. Off by default.
#MCP_ENABLED=false
# MCP OAuth Application. Uncomment to auto-create/update the OAuth client
# used by remote MCP integrations after migrations complete.
#MCP_OAUTH_CLIENT_NAME="WYGIWYH MCP"
+8 -1
View File
@@ -295,7 +295,14 @@ Check out our [Wiki](https://github.com/eitchtee/WYGIWYH/wiki) for more informat
# MCP Server
[IZIme07](https://github.com/IZIme07) has kindly created an MCP Server for WYGIWYH that you can self-host. [Check it out at MCP-WYGIWYH](https://github.com/ReNewator/MCP-WYGIWYH)!
WYGIWYH has a built-in MCP server, so AI assistants (Claude, ChatGPT, Claude Code, Cursor...) can read and record your transactions. It runs inside the web app; no extra container is needed. Set `MCP_ENABLED=true` to turn it on, then add `https://your.wygiwyh.domain/mcp` as a remote (Streamable HTTP) MCP server in your client.
Clients sign in in one of two ways:
- **OAuth** (Claude.ai, ChatGPT and most desktop clients): the client discovers WYGIWYH's OAuth server from `/.well-known/oauth-protected-resource`, and you log in and approve it in the browser. The client must either register itself, which needs `OAUTH2_DCR_ENABLED=true`, or use an OAuth app you created (see [MCP OAuth Application Bootstrap](#mcp-oauth-application-bootstrap)).
- **API token** (clients that let you set headers): send `Authorization: Token wygiwyh_pat_...`, created as in [API Tokens](#api-tokens-for-n8n-and-other-automations).
The client sees and changes what the signed-in user can in the app. It can list accounts, categories, tags and entities, check balances, search and summarize transactions, and create, edit or delete transactions. Everything else in the [API](#api-tokens-for-n8n-and-other-automations) (recurring transactions, installment plans, currencies, exchange rates, DCA...) is reachable through its `search_api` and `call_api` tools.
# Caveats and Warnings
+10 -3
View File
@@ -474,11 +474,11 @@ if DEBUG:
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
# Same access as the web UI: any signed-in user, limited by the user-scoped
# querysets and, for shared objects, SharedObjectPermission.
"DEFAULT_PERMISSION_CLASSES": [
"apps.api.permissions.NotInDemoMode",
"rest_framework.permissions.DjangoModelPermissions",
"rest_framework.permissions.IsAuthenticated",
],
"DEFAULT_FILTER_BACKENDS": [
"django_filters.rest_framework.DjangoFilterBackend",
@@ -512,11 +512,18 @@ OAUTH2_PROVIDER = {
OAUTH2_DCR_ENABLED = os.getenv("OAUTH2_DCR_ENABLED", "false").lower() == "true"
OAUTH2_DCR_INITIAL_ACCESS_TOKEN = os.getenv("OAUTH2_DCR_INITIAL_ACCESS_TOKEN", "")
# Native MCP server at /mcp/. Off by default; when off, /mcp/ and its OAuth
# protected-resource metadata return 404.
MCP_ENABLED = os.getenv("MCP_ENABLED", "false").lower() == "true"
SPECTACULAR_SETTINGS = {
"TITLE": "WYGIWYH API",
"DESCRIPTION": "A no-frills expense tracker",
"VERSION": "1.0.0",
"SERVE_INCLUDE_SCHEMA": False,
# Separate request schemas so read-only fields (id, owner, nested
# account...) don't show up as inputs for generated clients.
"COMPONENT_SPLIT_REQUEST": True,
# Several models have a "type" field with different choices
"ENUM_NAME_OVERRIDES": {
"TransactionTypeEnum": "apps.transactions.models.Transaction.Type",
+10 -1
View File
@@ -16,7 +16,7 @@ Including another URLconf
"""
from django.contrib import admin
from django.urls import path, include
from django.urls import path, include, re_path
from drf_spectacular.views import (
SpectacularAPIView,
SpectacularSwaggerView,
@@ -26,7 +26,9 @@ from apps.common.decorators.demo import disabled_on_demo
from apps.common.oauth_views import (
authorization_server_metadata,
dynamic_client_registration,
protected_resource_metadata,
)
from apps.api.mcp import MCPView
from oauth2_provider import urls as _dot_urls
@@ -71,6 +73,13 @@ urlpatterns = [
disabled_on_demo(authorization_server_metadata),
name="oauth-authorization-server-metadata",
),
# Clients may look it up with or without the resource path (RFC 9728)
re_path(
r"^\.well-known/oauth-protected-resource(?:/mcp)?/?$",
disabled_on_demo(protected_resource_metadata),
name="oauth-protected-resource-metadata",
),
re_path(r"^mcp/?$", MCPView.as_view(), name="mcp"),
path(
"oauth/register/",
disabled_on_demo(dynamic_client_registration),
+681
View File
@@ -0,0 +1,681 @@
"""Native MCP server (Streamable HTTP, stateless, JSON responses only).
Each tool runs the matching REST API view in-process, as the caller, so
permissions, sharing, filters, validation and signals stay the API's.
"""
import json
import logging
import re
from decimal import Decimal
from functools import cache
from threading import Lock
from urllib.parse import urlsplit
from django.conf import settings
from django.http import Http404
from django.test import RequestFactory
from django.urls import Resolver404, resolve
from drf_spectacular.generators import SchemaGenerator
from oauth2_provider.contrib.rest_framework import OAuth2Authentication
from rest_framework.exceptions import ParseError
from rest_framework.parsers import JSONParser
from rest_framework.permissions import IsAuthenticated
from rest_framework.renderers import JSONRenderer
from rest_framework.response import Response
from rest_framework.views import APIView
from apps.api import views
from apps.api.authentication import APITokenAuthentication
from apps.api.permissions import NotInDemoMode
from apps.common.oauth_views import _base_url
PROTOCOL_VERSIONS = ("2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05")
INSTRUCTIONS = (
"WYGIWYH is a personal finance tracker. Amounts are never negative: `type` "
"IN is income and EX is expense. `reference_date` is the month a "
"transaction counts toward: YYYY-MM in these tools, YYYY-MM-DD for recurring "
"transactions and installment plans in call_api. Use summarize_transactions for totals instead "
"of adding up search results. Look up ids with list_accounts and "
"list_categories/list_tags/list_entities. For anything else, find the "
"endpoint with search_api and run it with call_api."
)
_factory = RequestFactory()
logger = logging.getLogger(__name__)
class ToolError(Exception):
pass
def _dispatch(request, view, method, *, path="/", kwargs=None, query=None, data=None):
"""Run an API view as the MCP caller and return its response data."""
host = {"HTTP_HOST": request._request.get_host(), "secure": request.is_secure()}
if method == "get":
inner = _factory.get(path, query or {}, **host)
else:
inner = getattr(_factory, method)(
path, json.dumps(data or {}), content_type="application/json", **host
)
inner._force_auth_user = request.user
inner._force_auth_token = request.auth
response = view(inner, **(kwargs or {}))
if response.status_code >= 400:
raise ToolError(response.data)
return response.data
def _call_api(request, viewset, action, *, method="get", pk=None, query=None, data=None):
return _dispatch(
request,
viewset.as_view({method: action}),
method,
kwargs={"pk": pk} if pk is not None else None,
query=query,
data=data,
)
def _num(value):
"""'50.000000000000000000000000000000' -> '50'."""
if value is None:
return None
return format(Decimal(str(value)).normalize(), "f")
def _clean(item):
return {k: v for k, v in item.items() if v not in (None, "", [])}
def _names(items):
return [i["name"] for i in items or []]
def _transaction(t):
account = t["account"]
exchanged = t["exchanged_amount"] # {amount, prefix, suffix, ...} or None
return _clean(
{
"id": t["id"],
"date": t["date"],
"reference_date": t["reference_date"],
"type": t["type"],
"is_paid": t["is_paid"],
"amount": _num(t["amount"]),
"currency": account["currency"]["code"],
"exchanged": (
f"{exchanged['prefix']}{_num(exchanged['amount'])}{exchanged['suffix']}"
if exchanged
else None
),
"description": t["description"],
"account": {"id": account["id"], "name": account["name"]},
"category": t["category"]["name"] if t["category"] else None,
"tags": _names(t["tags"]),
"entities": _names(t["entities"]),
"notes": t["notes"],
"sub_transactions": [
{"name": s["name"], "amount": _num(s["amount"])}
for s in t["sub_transactions"]
],
"mute": t["mute"] or None,
"transfer_with": t["linked_transaction"],
"installment_plan": t["installment_plan"],
"recurring_transaction": t["recurring_transaction"],
}
)
def _page(data, compact):
return {
"count": data["count"],
"has_more": data["next"] is not None,
"results": [compact(item) for item in data["results"]],
}
# --- tools -------------------------------------------------------------------
DATE = {"type": "string", "format": "date", "description": "YYYY-MM-DD"}
MONTH = {"type": "string", "description": "YYYY-MM"}
TYPE = {"type": "string", "enum": ["IN", "EX"], "description": "IN = income, EX = expense"}
ID = {"type": "integer"}
FILTERS = {
"date_from": DATE,
"date_to": DATE,
"month_from": MONTH,
"month_to": MONTH,
"account_id": ID,
"category_id": ID,
"tag_id": ID,
"entity_id": ID,
"type": TYPE,
"is_paid": {"type": "boolean"},
"description": {"type": "string", "description": "Part of the description, case-insensitive"},
}
FILTER_PARAMS = {
"date_from": "date__gte",
"date_to": "date__lte",
"month_from": "reference_date__gte",
"month_to": "reference_date__lte",
"account_id": "account",
"category_id": "category",
"tag_id": "tags",
"entity_id": "entities",
"type": "type",
"is_paid": "is_paid",
"description": "description__icontains",
}
TRANSACTION_FIELDS = {
"account_id": ID,
"type": TYPE,
"amount": {"type": "string", "description": "Decimal, never negative"},
"date": DATE,
"reference_date": {**MONTH, "description": "YYYY-MM; when creating, defaults to the month of date"},
"description": {"type": "string"},
"is_paid": {"type": "boolean", "description": "false for a planned transaction; when creating, defaults to true"},
"category": {
"type": ["integer", "string", "null"],
"description": "Category id or name; an unknown name creates the category; null clears it",
},
"tags": {
"type": "array",
"items": {"type": ["integer", "string"]},
"description": "Tag ids or names; unknown names are created. Replaces the current tags.",
},
"entities": {
"type": "array",
"items": {"type": ["integer", "string"]},
"description": "Entity ids or names; unknown names are created. Replaces the current entities.",
},
"notes": {"type": "string"},
"mute": {"type": "boolean", "description": "Muted transactions are left out of totals"},
}
def _filters(args):
query = {}
for key, param in FILTER_PARAMS.items():
if key in args:
value = args[key]
if isinstance(value, bool):
value = str(value).lower()
elif key.startswith("month_"): # the filter takes full dates
if not re.fullmatch(r"\d{4}-\d{2}", str(value)):
raise ToolError({key: "Use YYYY-MM."})
value = f"{value}-01"
query[param] = value
return query
def _transaction_body(args):
body = {k: v for k, v in args.items() if k in TRANSACTION_FIELDS}
if "amount" in body:
body["amount"] = str(body["amount"])
return body
def list_accounts(request, args):
query = {} if args.get("include_archived") else {"is_archived": "false"}
data = _call_api(request, views.AccountViewSet, "list", query={**query, "page_size": 1000})
return [
_clean(
{
"id": a["id"],
"name": a["name"],
"group": a["group"]["name"] if a["group"] else None,
"currency": a["currency"]["code"],
"exchange_currency": (a["exchange_currency"] or {}).get("code"),
"is_asset": a["is_asset"] or None,
"is_investment": a["is_investment"] or None,
}
)
for a in data["results"]
]
def get_account_balance(request, args):
data = _call_api(request, views.AccountViewSet, "balance", pk=args["account_id"])
return {
"current_balance": _num(data["current_balance"]),
"projected_balance": _num(data["projected_balance"]),
"currency": data["currency"]["code"],
}
def _filtered_transactions(request, action, query):
"""Like _call_api, but errors name the tool's filters, not the API's."""
try:
return _call_api(request, views.TransactionViewSet, action, query=query)
except ToolError as e:
detail = e.args[0]
if isinstance(detail, dict):
names = {param: arg for arg, param in FILTER_PARAMS.items()}
detail = {names.get(k, k): v for k, v in detail.items()}
raise ToolError(detail) from e
def search_transactions(request, args):
query = _filters(args)
query["page"] = args.get("page", 1)
query["page_size"] = min(int(args.get("page_size", 50)), 100)
query["ordering"] = "-date"
return _page(_filtered_transactions(request, "list", query), _transaction)
def summarize_transactions(request, args):
query = _filters(args)
for key in ("group_by", "include_muted"):
if key in args:
query[key] = str(args[key]).lower()
rows = _filtered_transactions(request, "summary", query)
return [{**row, "total": _num(row["total"])} for row in rows]
def get_transaction(request, args):
return _transaction(
_call_api(request, views.TransactionViewSet, "retrieve", pk=args["id"])
)
def create_transaction(request, args):
return _transaction(
_call_api(
request,
views.TransactionViewSet,
"create",
method="post",
data=_transaction_body(args),
)
)
def update_transaction(request, args):
return _transaction(
_call_api(
request,
views.TransactionViewSet,
"partial_update",
method="patch",
pk=args["id"],
data=_transaction_body(args),
)
)
def delete_transaction(request, args):
_call_api(request, views.TransactionViewSet, "destroy", method="delete", pk=args["id"])
return {"deleted": args["id"]}
def _lister(viewset):
def handler(request, args):
query = {"page_size": 1000}
if not args.get("include_inactive"):
query["active"] = "true"
if args.get("name"):
query["name__icontains"] = args["name"]
data = _call_api(request, viewset, "list", query=query)
return [
_clean(
{
"id": i["id"],
"name": i["name"],
"inactive": not i["active"] or None,
"mute": i.get("mute") or None, # categories only
}
)
for i in data["results"]
]
return handler
_operations_lock = Lock()
def _operations():
# Schema generation isn't thread-safe; concurrent first calls broke it
with _operations_lock:
return _build_operations()
@cache
def _build_operations():
"""The REST API's operations from its OpenAPI schema, with $refs inlined."""
schema = SchemaGenerator().get_schema(request=None, public=True)
components = schema["components"]["schemas"]
def inline(node, depth=0):
if isinstance(node, list):
return [inline(i, depth) for i in node]
if not isinstance(node, dict):
return node
if "$ref" in node:
if depth > 4: # recursive schemas
return {"type": "object"}
return inline(components[node["$ref"].rsplit("/", 1)[-1]], depth + 1)
return {k: inline(v, depth) for k, v in node.items()}
operations = []
for path, item in schema["paths"].items():
if not path.startswith("/api/"):
continue
for method, op in item.items():
content = op.get("requestBody", {}).get("content", {})
body = content.get("application/json") or next(iter(content.values()), None)
operations.append(
_clean(
{
"method": method.upper(),
"path": path,
"summary": op.get("summary"),
"description": op.get("description"),
# name -> enum, format or type; path params are in the path
"query": {
p["name"]: (lambda s: s.get("enum") or s.get("format") or s.get("type"))(
inline(p.get("schema") or {})
)
for p in op.get("parameters", [])
if p["in"] == "query"
},
"body": inline(body["schema"]) if body else None,
}
)
)
return operations
def search_api(request, args):
words = str(args.get("query", "")).lower().split()
if not words:
return [f"{op['method']} {op['path']}" + (f" — {op['summary']}" if "summary" in op else "") for op in _operations()]
scored = []
for op in _operations():
exact = {op["method"].lower(), *op["path"].strip("/").split("/")}
head = f"{op['method']} {op['path']} {op.get('summary', '')}".lower()
text = f"{head} {op.get('description', '')}".lower()
if all(w in text for w in words):
score = sum(2 * (w in exact) + (w in head) for w in words)
scored.append((-score, len(op["path"]), op))
scored.sort(key=lambda s: s[:2])
return [op for _, _, op in scored[: min(int(args.get("limit", 5)), 20)]]
def call_api(request, args):
method = str(args["method"]).lower()
if method not in ("get", "post", "put", "patch", "delete"):
raise ToolError({"method": "Must be GET, POST, PUT, PATCH or DELETE."})
url = urlsplit(str(args["path"]))
if url.scheme or url.netloc:
raise ToolError({"path": "Pass only the path, e.g. /api/accounts/."})
path = url.path
path = path if path.endswith("/") else f"{path}/"
try:
match = resolve(path)
except Resolver404:
match = None
view_class = getattr(match.func, "cls", None) if match else None
if not (view_class and view_class.__module__.startswith("apps.api.views")):
raise ToolError({"path": "Not a WYGIWYH API endpoint; find one with search_api."})
query = {
k: str(v).lower() if isinstance(v, bool) else v
for k, v in (args.get("query") or {}).items()
}
data = _dispatch(
request, match.func, method, path=path, kwargs=match.kwargs, query=query, data=args.get("body")
)
return {"ok": True} if data is None else data
LISTER_INPUT = {
"type": "object",
"properties": {
"name": {"type": "string", "description": "Part of the name, case-insensitive"},
"include_inactive": {"type": "boolean"},
},
}
READ = {"readOnlyHint": True, "openWorldHint": False}
WRITE = {"readOnlyHint": False, "destructiveHint": False, "openWorldHint": False}
TOOLS = [
{
"name": "list_accounts",
"description": "Accounts with their group and currency. Archived accounts are left out unless include_archived is true.",
"inputSchema": {"type": "object", "properties": {"include_archived": {"type": "boolean"}}},
"annotations": READ,
"handler": list_accounts,
},
{
"name": "get_account_balance",
"description": "Current balance (paid transactions only) and projected balance (paid and unpaid) of an account.",
"inputSchema": {"type": "object", "properties": {"account_id": ID}, "required": ["account_id"]},
"annotations": READ,
"handler": get_account_balance,
},
{
"name": "search_transactions",
"description": "Transactions matching the filters, newest date first. Paginated; page_size is at most 100.",
"inputSchema": {
"type": "object",
"properties": {
**FILTERS,
"page": {"type": "integer", "minimum": 1},
"page_size": {"type": "integer", "minimum": 1, "maximum": 100},
},
},
"annotations": READ,
"handler": search_transactions,
},
{
"name": "summarize_transactions",
"description": (
"Totals and counts of the transactions matching the filters, per currency and type, "
"optionally grouped by category, tag, entity, account or month. Muted transactions and "
"those in muted categories (see list_categories) are left out unless include_muted is true. With tag or entity grouping, a transaction counts "
"once per tag/entity. Transfers between accounts count as an expense and an income."
),
"inputSchema": {
"type": "object",
"properties": {
**FILTERS,
"group_by": {"type": "string", "enum": ["category", "tag", "entity", "account", "month"]},
"include_muted": {"type": "boolean"},
},
},
"annotations": READ,
"handler": summarize_transactions,
},
{
"name": "get_transaction",
"description": "One transaction by id.",
"inputSchema": {"type": "object", "properties": {"id": ID}, "required": ["id"]},
"annotations": READ,
"handler": get_transaction,
},
{
"name": "create_transaction",
"description": "Records an income or expense. Your transaction rules run on it, as when created in the app.",
"inputSchema": {
"type": "object",
"properties": TRANSACTION_FIELDS,
"required": ["account_id", "type", "amount", "date"],
},
"annotations": WRITE,
"handler": create_transaction,
},
{
"name": "update_transaction",
"description": "Changes only the fields sent. Your transaction rules run on it, as when edited in the app.",
"inputSchema": {
"type": "object",
"properties": {"id": ID, **TRANSACTION_FIELDS},
"required": ["id"],
},
"annotations": {**WRITE, "idempotentHint": True},
"handler": update_transaction,
},
{
"name": "delete_transaction",
"description": "Deletes a transaction. Deleting either side of a transfer deletes both.",
"inputSchema": {"type": "object", "properties": {"id": ID}, "required": ["id"]},
"annotations": {**WRITE, "destructiveHint": True, "idempotentHint": True},
"handler": delete_transaction,
},
{
"name": "list_categories",
"description": "Transaction categories. Inactive ones are left out unless include_inactive is true.",
"inputSchema": LISTER_INPUT,
"annotations": READ,
"handler": _lister(views.TransactionCategoryViewSet),
},
{
"name": "list_tags",
"description": "Transaction tags. Inactive ones are left out unless include_inactive is true.",
"inputSchema": LISTER_INPUT,
"annotations": READ,
"handler": _lister(views.TransactionTagViewSet),
},
{
"name": "list_entities",
"description": "People and businesses on the other side of transactions. Inactive ones are left out unless include_inactive is true.",
"inputSchema": LISTER_INPUT,
"annotations": READ,
"handler": _lister(views.TransactionEntityViewSet),
},
{
"name": "search_api",
"description": (
"Finds REST API endpoints for anything the other tools don't cover: recurring "
"transactions, installment plans, currencies, exchange rates, account groups, "
"investment classes, DCA strategies, import runs. Returns each match's method, path, "
"parameters and JSON body schema, to use with call_api. Without a query, lists every endpoint."
),
"inputSchema": {
"type": "object",
"properties": {
"query": {"type": "string", "description": "Words that must all appear, e.g. 'recurring list'"},
"limit": {"type": "integer", "minimum": 1, "maximum": 20, "description": "Defaults to 5"},
},
},
"annotations": READ,
"handler": search_api,
},
{
"name": "call_api",
"description": (
"Calls a REST API endpoint found with search_api, as you. Replace path parameters "
"such as {id} with values. Responses are the API's full JSON; list endpoints are "
"paginated (page, page_size). File uploads aren't supported."
),
"inputSchema": {
"type": "object",
"properties": {
"method": {"type": "string", "enum": ["GET", "POST", "PUT", "PATCH", "DELETE"]},
"path": {"type": "string", "description": "e.g. /api/recurring-transactions/12/"},
"query": {"type": "object", "description": "Query string parameters"},
"body": {"type": "object", "description": "JSON body for POST, PUT and PATCH"},
},
"required": ["method", "path"],
},
"annotations": {**WRITE, "destructiveHint": True},
"handler": call_api,
},
]
TOOLS_BY_NAME = {tool["name"]: tool for tool in TOOLS}
# --- protocol ----------------------------------------------------------------
def _tool_result(data, is_error=False):
return {
"content": [{"type": "text", "text": json.dumps(data, ensure_ascii=False, default=str)}],
"isError": is_error,
}
class RpcError(Exception):
def __init__(self, code, message):
self.code, self.message = code, message
class MCPView(APIView):
authentication_classes = [OAuth2Authentication, APITokenAuthentication]
permission_classes = [IsAuthenticated, NotInDemoMode]
parser_classes = [JSONParser]
renderer_classes = [JSONRenderer]
schema = None # not part of the REST API docs
def initial(self, request, *args, **kwargs):
if not settings.MCP_ENABLED:
raise Http404
super().initial(request, *args, **kwargs)
def get_authenticate_header(self, request):
# Points MCP clients at the OAuth metadata (RFC 9728).
url = f"{_base_url(request)}/.well-known/oauth-protected-resource/mcp"
return f'Bearer resource_metadata="{url}"'
def handle_exception(self, exc):
# The body may be parsed during authentication, before post() runs
if isinstance(exc, ParseError):
return self._error(None, -32700, "Parse error")
return super().handle_exception(exc)
def post(self, request):
message = request.data
if (
not isinstance(message, dict)
or message.get("jsonrpc") != "2.0"
or not isinstance(message.get("method"), str)
):
return self._error(message.get("id") if isinstance(message, dict) else None, -32600, "Invalid Request")
if "id" not in message: # notification or response
return Response(status=202)
params = message.get("params") or {}
try:
result = self.handle(request, message["method"], params)
except RpcError as e:
return self._error(message["id"], e.code, e.message)
return Response({"jsonrpc": "2.0", "id": message["id"], "result": result})
def handle(self, request, method, params):
if method == "initialize":
requested = params.get("protocolVersion")
return {
"protocolVersion": requested if requested in PROTOCOL_VERSIONS else PROTOCOL_VERSIONS[0],
"capabilities": {"tools": {}},
"serverInfo": {"name": "WYGIWYH", "version": settings.APP_VERSION},
"instructions": INSTRUCTIONS,
}
if method == "ping":
return {}
if method == "tools/list":
return {"tools": [{k: v for k, v in t.items() if k != "handler"} for t in TOOLS]}
if method == "tools/call":
tool = TOOLS_BY_NAME.get(params.get("name"))
if tool is None:
raise RpcError(-32602, f"Unknown tool: {params.get('name')}")
args = params.get("arguments") or {}
if not isinstance(args, dict):
raise RpcError(-32602, "arguments must be an object")
missing = [k for k in tool["inputSchema"].get("required", []) if k not in args]
if missing:
return _tool_result({"missing": missing}, is_error=True)
try:
return _tool_result(tool["handler"](request, args))
except ToolError as e:
return _tool_result(e.args[0], is_error=True)
except Exception:
logger.exception("MCP tool %s failed", tool["name"])
return _tool_result({"detail": "Internal server error."}, is_error=True)
raise RpcError(-32601, f"Method not found: {method}")
@staticmethod
def _error(id_, code, message):
return Response({"jsonrpc": "2.0", "id": id_, "error": {"code": code, "message": message}})
+5 -7
View File
@@ -1,7 +1,7 @@
from rest_framework.permissions import (
SAFE_METHODS,
BasePermission,
DjangoModelPermissions,
IsAuthenticated,
)
from django.conf import settings
@@ -17,11 +17,9 @@ class NotInDemoMode(BasePermission):
class SharedObjectPermission(BasePermission):
"""Object-level ownership check for SharedObject-backed viewsets.
DjangoModelPermissions is model-level: a user holding ``change_account``
may write any object the viewset's queryset returns, and for SharedObject
that queryset includes other people's public and shared-with-them objects.
Sharing grants read access only, so writes are restricted to the owner
here as well.
The viewset's queryset includes other people's public and shared-with-them
objects. Sharing grants read access only, so writes are restricted to the
owner here, as the web UI does with ``get_shared_object_or_error``.
Set ``shared_object_via`` on the viewset when the governing SharedObject is
reached through a relation (e.g. ``"strategy"`` for a DCA entry).
@@ -43,6 +41,6 @@ class SharedObjectPermission(BasePermission):
#: ``permission_classes`` replaces the defaults, so they are repeated here.
SHARED_OBJECT_PERMISSIONS = [
NotInDemoMode,
DjangoModelPermissions,
IsAuthenticated,
SharedObjectPermission,
]
+4
View File
@@ -17,6 +17,7 @@ class AccountGroupSerializer(serializers.ModelSerializer):
class Meta:
model = AccountGroup
fields = "__all__"
read_only_fields = ["id", "owner"]
class InvestmentClassSerializer(serializers.ModelSerializer):
@@ -44,6 +45,7 @@ class AccountSerializer(serializers.ModelSerializer):
source="group",
write_only=True,
allow_null=True,
required=False,
)
currency = CurrencySerializer(read_only=True)
@@ -56,6 +58,7 @@ class AccountSerializer(serializers.ModelSerializer):
source="exchange_currency",
write_only=True,
allow_null=True,
required=False,
)
investment_class = InvestmentClassSerializer(read_only=True)
@@ -88,6 +91,7 @@ class AccountSerializer(serializers.ModelSerializer):
"income_entities",
"income_categories",
"income_tags",
"is_archived",
]
def __init__(self, *args, **kwargs):
+11
View File
@@ -1,3 +1,4 @@
from django.utils.translation import gettext_lazy as _
from rest_framework import serializers
from rest_framework.permissions import IsAuthenticated
@@ -10,6 +11,11 @@ class CurrencySerializer(serializers.ModelSerializer):
class Meta:
model = Currency
fields = "__all__"
# Prefixes and suffixes carry their spacing, e.g. "R$ "
extra_kwargs = {
"prefix": {"trim_whitespace": False},
"suffix": {"trim_whitespace": False},
}
class ExchangeRateSerializer(serializers.ModelSerializer):
@@ -33,3 +39,8 @@ class ExchangeRateSerializer(serializers.ModelSerializer):
class Meta:
model = ExchangeRate
fields = "__all__"
def validate_rate(self, value):
if value <= 0:
raise serializers.ValidationError(_("The rate must be greater than zero."))
return value
+4
View File
@@ -37,6 +37,10 @@ class DCAEntrySerializer(serializers.ModelSerializer):
"entry_price",
]
read_only_fields = ["created_at", "updated_at"]
extra_kwargs = {
"amount_paid": {"min_value": 0},
"amount_received": {"min_value": 0},
}
class DCAStrategySerializer(serializers.ModelSerializer):
+13 -8
View File
@@ -1,5 +1,3 @@
from decimal import Decimal
from django.db import transaction as db_transaction
from django.utils.translation import gettext_lazy as _
from drf_spectacular import openapi
@@ -36,8 +34,8 @@ class SubTransactionSerializer(serializers.ModelSerializer):
class SubTransactionsMixin:
"""`sub_transactions`, when sent, replaces the parts; a non-empty list sets
the amount to their sum. Declare the field on the serializer itself."""
# `sub_transactions`, when sent, replaces the parts; a non-empty list sets
# the amount to their sum. Declare the field on the serializer itself.
sub_amount_field = "amount"
@@ -141,7 +139,7 @@ class TransactionEntitySerializer(serializers.ModelSerializer):
class InstallmentPlanSerializer(SubTransactionsMixin, serializers.ModelSerializer):
sub_amount_field = "installment_amount"
sub_transactions = SubTransactionSerializer(many=True, required=False)
category: str | int = TransactionCategoryField(required=False)
category: str | int = TransactionCategoryField(required=False, allow_null=True)
tags: str | int = TransactionTagField(required=False)
entities: str | int = TransactionEntityField(required=False)
@@ -169,6 +167,7 @@ class InstallmentPlanSerializer(SubTransactionsMixin, serializers.ModelSerialize
"notes",
]
read_only_fields = ["installment_total_number", "end_date"]
extra_kwargs = {"installment_amount": {"min_value": 0}}
def after_save(self, instance, created):
if created:
@@ -179,7 +178,7 @@ class InstallmentPlanSerializer(SubTransactionsMixin, serializers.ModelSerialize
class RecurringTransactionSerializer(SubTransactionsMixin, serializers.ModelSerializer):
sub_transactions = SubTransactionSerializer(many=True, required=False)
category: str | int = TransactionCategoryField(required=False)
category: str | int = TransactionCategoryField(required=False, allow_null=True)
tags: str | int = TransactionTagField(required=False)
entities: str | int = TransactionEntityField(required=False)
@@ -208,6 +207,11 @@ class RecurringTransactionSerializer(SubTransactionsMixin, serializers.ModelSeri
"last_generated_reference_date",
]
read_only_fields = ["last_generated_date", "last_generated_reference_date"]
extra_kwargs = {
"amount": {"min_value": 0},
"to_amount": {"min_value": 0},
"recurrence_interval": {"min_value": 1},
}
def validate(self, attrs):
# Same rule as TransferTemplate.clean(), which DRF doesn't run
@@ -233,7 +237,7 @@ class RecurringTransactionSerializer(SubTransactionsMixin, serializers.ModelSeri
class TransactionSerializer(SubTransactionsMixin, serializers.ModelSerializer):
sub_transactions = SubTransactionSerializer(many=True, required=False)
category: str | int = TransactionCategoryField(required=False)
category: str | int = TransactionCategoryField(required=False, allow_null=True)
tags: str | int = TransactionTagField(required=False)
entities: str | int = TransactionEntityField(required=False)
@@ -308,5 +312,6 @@ class TransactionSerializer(SubTransactionsMixin, serializers.ModelSerializer):
return instance
@staticmethod
def get_exchanged_amount(obj) -> Decimal:
@extend_schema_field(OpenApiTypes.OBJECT)
def get_exchanged_amount(obj):
return obj.exchanged_amount()
+307
View File
@@ -0,0 +1,307 @@
import json
from datetime import date
from decimal import Decimal
from unittest import mock
from django.contrib.auth import get_user_model
from django.test import TestCase, override_settings
from apps.accounts.models import Account
from apps.common.middleware.thread_local import write_current_user, delete_current_user
from apps.accounts.models import AccountGroup
from apps.currencies.models import Currency, ExchangeRate
from apps.transactions.models import Transaction, TransactionCategory, TransactionTag
from apps.users.models import APIToken
User = get_user_model()
@override_settings(MCP_ENABLED=True, PUBLIC_BASE_URL="https://money.example")
class MCPTests(TestCase):
def setUp(self):
self.user = User.objects.create_user(email="me@example.com", password="x")
self.other = User.objects.create_user(email="other@example.com", password="x")
_token, self.raw_token = APIToken.objects.create_token(user=self.user, name="mcp")
self.brl = Currency.objects.create(code="BRL", name="Real", decimal_places=2)
self.account = self._as(self.user, Account.objects.create, name="Checking", currency=self.brl)
self.food = self._as(self.user, TransactionCategory.objects.create, name="Food")
self.muted = self._as(self.user, TransactionCategory.objects.create, name="Hidden", mute=True)
for amount, category in ((10, self.food), (5.5, self.food), (100, self.muted)):
self._as(
self.user,
Transaction.objects.create,
account=self.account,
type=Transaction.Type.EXPENSE,
amount=Decimal(str(amount)),
date=date(2026, 3, 5),
reference_date=date(2026, 3, 1),
category=category,
is_paid=True,
)
other_account = self._as(self.other, Account.objects.create, name="Theirs", currency=self.brl)
self.other_tx = self._as(
self.other,
Transaction.objects.create,
account=other_account,
type=Transaction.Type.EXPENSE,
amount=Decimal("999"),
date=date(2026, 3, 5),
reference_date=date(2026, 3, 1),
)
@staticmethod
def _as(user, create, **kwargs):
write_current_user(user) # owner comes from the current user
try:
return create(**kwargs)
finally:
delete_current_user()
def _rpc(self, method, params=None, id_=1, auth=True):
body = {"jsonrpc": "2.0", "method": method}
if id_ is not None:
body["id"] = id_
if params is not None:
body["params"] = params
headers = {"HTTP_AUTHORIZATION": f"Token {self.raw_token}"} if auth else {}
return self.client.post(
"/mcp", json.dumps(body), content_type="application/json", **headers
)
def _tool(self, name, **arguments):
response = self._rpc("tools/call", {"name": name, "arguments": arguments})
self.assertEqual(response.status_code, 200, response.content)
result = response.json()["result"]
return result["isError"], json.loads(result["content"][0]["text"])
@override_settings(MCP_ENABLED=False)
def test_disabled_by_setting(self):
self.assertEqual(self._rpc("ping").status_code, 404)
self.assertEqual(self.client.get("/.well-known/oauth-protected-resource/mcp").status_code, 404)
def test_unauthenticated_points_to_resource_metadata(self):
response = self._rpc("ping", auth=False)
self.assertEqual(response.status_code, 401)
self.assertEqual(
response["WWW-Authenticate"],
'Bearer resource_metadata="https://money.example/.well-known/oauth-protected-resource/mcp"',
)
metadata = self.client.get("/.well-known/oauth-protected-resource/mcp").json()
self.assertEqual(metadata["resource"], "https://money.example/mcp")
self.assertEqual(metadata["authorization_servers"], ["https://money.example"])
def test_handshake(self):
result = self._rpc("initialize", {"protocolVersion": "2025-06-18"}).json()["result"]
self.assertEqual(result["protocolVersion"], "2025-06-18")
self.assertIn("tools", result["capabilities"])
self.assertEqual(self._rpc("notifications/initialized", id_=None).status_code, 202)
tools = self._rpc("tools/list").json()["result"]["tools"]
self.assertIn("summarize_transactions", {t["name"] for t in tools})
self.assertNotIn("handler", tools[0])
def test_protocol_errors(self):
self.assertEqual(self._rpc("nope").json()["error"]["code"], -32601)
unknown_tool = self._rpc("tools/call", {"name": "nope"}).json()
self.assertEqual(unknown_tool["error"]["code"], -32602)
bad_json = self.client.post(
"/mcp", "{", content_type="application/json",
HTTP_AUTHORIZATION=f"Token {self.raw_token}",
)
self.assertEqual(bad_json.json()["error"]["code"], -32700)
def test_summary_leaves_out_muted_and_other_users(self):
is_error, rows = self._tool("summarize_transactions", group_by="category", month_from="2026-03")
self.assertFalse(is_error, rows)
self.assertEqual(
rows,
[{"currency": "BRL", "type": "EX", "group": "Food", "group_id": self.food.id, "total": "15.5", "count": 2}],
)
_, with_muted = self._tool("summarize_transactions", include_muted=True)
self.assertEqual(with_muted[0]["total"], "115.5")
def test_search_is_compact_and_scoped(self):
is_error, page = self._tool("search_transactions", category_id=self.food.id, page_size=1)
self.assertFalse(is_error, page)
self.assertEqual(page["count"], 2)
self.assertTrue(page["has_more"])
tx = page["results"][0]
self.assertEqual(tx["account"], {"id": self.account.id, "name": "Checking"})
self.assertEqual(tx["currency"], "BRL")
self.assertEqual(tx["category"], "Food")
self.assertIn(tx["amount"], ("10", "5.5"))
is_error, error = self._tool("get_transaction", id=self.other_tx.id)
self.assertTrue(is_error)
def test_create_update_delete(self):
is_error, created = self._tool(
"create_transaction",
account_id=self.account.id,
type="IN",
amount="1200.50",
date="2026-04-02",
description="Salary",
tags=["Work"],
)
self.assertFalse(is_error, created)
self.assertEqual(created["amount"], "1200.5")
self.assertEqual(created["reference_date"], "2026-04")
self.assertEqual(created["tags"], ["Work"])
is_error, updated = self._tool("update_transaction", id=created["id"], is_paid=True)
self.assertFalse(is_error, updated)
self.assertTrue(updated["is_paid"])
self.assertEqual(updated["description"], "Salary")
is_error, _ = self._tool("delete_transaction", id=created["id"])
self.assertFalse(is_error)
self.assertFalse(Transaction.objects.filter(pk=created["id"]).exists())
def test_search_api_finds_endpoints_with_their_inputs(self):
_, everything = self._tool("search_api")
self.assertIn("GET /api/currencies/", everything)
self.assertFalse(any("/api/schema/" in line for line in everything))
_, matches = self._tool("search_api", query="recurring post", limit=1)
self.assertEqual(matches[0]["path"], "/api/recurring-transactions/")
self.assertEqual(matches[0]["method"], "POST")
self.assertIn("recurrence_type", matches[0]["body"]["properties"])
def test_call_api_runs_endpoints_as_the_caller(self):
is_error, own = self._tool("call_api", method="GET", path="/api/currencies", query={"code": "BRL"})
self.assertFalse(is_error, own)
self.assertEqual(own["results"][0]["code"], "BRL")
is_error, _ = self._tool("call_api", method="GET", path=f"/api/transactions/{self.other_tx.id}/")
self.assertTrue(is_error)
is_error, deleted = self._tool(
"call_api", method="DELETE", path=f"/api/categories/{self.muted.id}/"
)
self.assertFalse(is_error, deleted)
self.assertFalse(TransactionCategory.objects.filter(pk=self.muted.id).exists())
def test_call_api_only_reaches_the_api(self):
for path in ("/api/schema/", "/api/", "/admin/", "/mcp"):
is_error, error = self._tool("call_api", method="GET", path=path)
self.assertTrue(is_error, path)
self.assertIn("path", error)
def test_exchanged_amount(self):
usd = Currency.objects.create(code="USD", name="Dollar", decimal_places=2, prefix="US$ ")
ExchangeRate.objects.create(from_currency=self.brl, to_currency=usd, rate=Decimal("0.2"), date=date(2026, 1, 1))
self.account.exchange_currency = usd
self.account.save()
is_error, page = self._tool("search_transactions", category_id=self.food.id, date_from="2026-03-01")
self.assertFalse(is_error, page)
self.assertEqual({t["exchanged"] for t in page["results"]}, {"US$ 2", "US$ 1.1"})
def test_category_can_be_cleared(self):
tx = Transaction.objects.filter(category=self.food).first()
is_error, updated = self._tool("update_transaction", id=tx.id, category=None)
self.assertFalse(is_error, updated)
self.assertNotIn("category", updated)
def test_filter_errors_use_tool_argument_names(self):
is_error, errors = self._tool("search_transactions", date_from="not-a-date")
self.assertTrue(is_error)
self.assertIn("date_from", errors)
is_error, errors = self._tool("summarize_transactions", month_from="2026-03-01")
self.assertTrue(is_error)
self.assertEqual(errors, {"month_from": "Use YYYY-MM."})
def test_exchange_rates_must_be_positive(self):
usd = Currency.objects.create(code="USD", name="Dollar", decimal_places=2)
is_error, errors = self._tool(
"call_api", method="POST", path="/api/exchange-rates/",
body={"from_currency_id": self.brl.id, "to_currency_id": usd.id, "rate": "-2", "date": "2026-01-01T00:00:00Z"},
)
self.assertTrue(is_error)
self.assertIn("rate", errors)
def test_unexpected_errors_are_tool_errors(self):
with mock.patch.dict(
"apps.api.mcp.TOOLS_BY_NAME",
{"list_tags": {"name": "list_tags", "inputSchema": {}, "handler": mock.Mock(side_effect=ValueError)}},
):
is_error, error = self._tool("list_tags")
self.assertTrue(is_error)
self.assertEqual(error, {"detail": "Internal server error."})
def test_api_keeps_currency_spacing_and_group_owner(self):
is_error, currency = self._tool(
"call_api", method="POST", path="/api/currencies/",
body={"code": "EUR", "name": "Euro", "prefix": "€ ", "suffix": " eur"},
)
self.assertFalse(is_error, currency)
self.assertEqual((currency["prefix"], currency["suffix"]), ("€ ", " eur"))
is_error, group = self._tool(
"call_api", method="POST", path="/api/account-groups/",
body={"name": "Planted", "owner": self.other.id},
)
self.assertFalse(is_error, group)
self.assertEqual(AccountGroup.all_objects.get(pk=group["id"]).owner, self.user)
def test_api_rejects_bad_amounts_and_intervals(self):
common = {"account": self.account.id, "type": "EX", "description": "x", "start_date": "2026-04-01"}
cases = [
("/api/installment-plans/", {**common, "installment_amount": "-10", "number_of_installments": 2, "recurrence": "monthly"}, "installment_amount"),
("/api/recurring-transactions/", {**common, "amount": "10", "recurrence_type": "month", "recurrence_interval": 0}, "recurrence_interval"),
]
for path, body, field in cases:
is_error, errors = self._tool("call_api", method="POST", path=path, body=body)
self.assertTrue(is_error, path)
self.assertIn(field, errors)
def test_accounts_can_be_archived_and_performance_needs_an_investment(self):
is_error, _ = self._tool(
"call_api", method="PATCH", path=f"/api/accounts/{self.account.id}/", body={"is_archived": True}
)
self.assertFalse(is_error)
self.account.refresh_from_db()
self.assertTrue(self.account.is_archived)
is_error, _ = self._tool("call_api", method="GET", path=f"/api/accounts/{self.account.id}/performance/")
self.assertTrue(is_error)
def test_tag_filter_muted_categories_and_month_order(self):
_, created = self._tool(
"create_transaction", account_id=self.account.id, type="EX", amount="7", date="2026-01-02", tags=["Trip"]
)
tag = TransactionTag.all_objects.get(name="Trip")
_, page = self._tool("search_transactions", tag_id=tag.id)
self.assertEqual([t["id"] for t in page["results"]], [created["id"]])
_, categories = self._tool("list_categories")
self.assertEqual({c["name"]: c.get("mute") for c in categories}, {"Food": None, "Hidden": True})
_, months = self._tool("summarize_transactions", group_by="month")
self.assertEqual([m["group"] for m in months], ["2026-01", "2026-03"])
def test_search_api_ranking_and_call_api_rejects_urls(self):
_, matches = self._tool("search_api", query="transactions post", limit=1)
self.assertEqual(matches[0]["path"], "/api/transactions/")
is_error, error = self._tool("call_api", method="GET", path="http://elsewhere.invalid/api/accounts/")
self.assertTrue(is_error)
self.assertIn("path", error)
def test_tool_validation_errors_are_tool_results(self):
is_error, missing = self._tool("create_transaction", account_id=self.account.id)
self.assertTrue(is_error)
self.assertEqual(set(missing["missing"]), {"type", "amount", "date"})
is_error, errors = self._tool(
"create_transaction", account_id=self.account.id, type="EX", amount="-1", date="2026-04-02"
)
self.assertTrue(is_error)
self.assertIn("amount", errors)
+5 -33
View File
@@ -1,10 +1,8 @@
"""Object-level ownership on the SharedObject API viewsets.
DjangoModelPermissions is model-level: a user holding ``change_account`` could
write any object the viewset's queryset returned, and for SharedObject that
queryset includes other people's public and shared-with-them objects. Ordinary
users hold no model permissions, so this was not reachable for them, but the
object-level check was missing entirely.
Any signed-in user may write through the API, and for SharedObject the
viewset's queryset includes other people's public and shared-with-them objects,
so the object-level check is what keeps those read-only.
Reads are unaffected -- they stay governed by SharedObjectManager.
"""
@@ -13,7 +11,6 @@ from datetime import date
from decimal import Decimal
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.test import TestCase, override_settings
from rest_framework import status
from rest_framework.test import APIClient
@@ -35,12 +32,7 @@ from apps.transactions.models import TransactionCategory
DEMO=False,
)
class SharedObjectAPIPermissionTests(TestCase):
"""The attacker here deliberately HOLDS the Django model permissions.
Without them DjangoModelPermissions already answers 403 and the
object-level check is never consulted, so the test would pass whether or
not it exists.
"""
"""The attacker is an ordinary signed-in user who can see the objects."""
def setUp(self):
User = get_user_model()
@@ -50,23 +42,6 @@ class SharedObjectAPIPermissionTests(TestCase):
self.attacker = User.objects.create_user(
email="attacker@test.com", password="testpass123"
)
self.attacker.user_permissions.set(
Permission.objects.filter(
codename__in=[
"add_account",
"change_account",
"delete_account",
"add_transactioncategory",
"change_transactioncategory",
"delete_transactioncategory",
"add_dcaentry",
"change_dcaentry",
"delete_dcaentry",
]
)
)
# Permissions are cached on the user instance.
self.attacker = User.objects.get(pk=self.attacker.pk)
self.currency = Currency.objects.create(
code="USD", name="US Dollar", decimal_places=2
@@ -149,10 +124,7 @@ class SharedObjectAPIPermissionTests(TestCase):
def test_owner_can_still_write_their_own_objects(self):
owner_client = APIClient()
self.owner.user_permissions.set(
Permission.objects.filter(codename__in=["change_account", "delete_account"])
)
owner = get_user_model().objects.get(pk=self.owner.pk)
owner = self.owner
owner_client.force_authenticate(user=owner)
account = Account.all_objects.create(
+9 -3
View File
@@ -1,6 +1,7 @@
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
@@ -18,7 +19,7 @@ from apps.investments.services import get_holding_performance
class AccountGroupViewSet(viewsets.ModelViewSet):
"""ViewSet for managing account groups."""
"""Groups that organize accounts, e.g. by bank."""
permission_classes = SHARED_OBJECT_PERMISSIONS
queryset = AccountGroup.objects.all()
@@ -36,7 +37,8 @@ class AccountGroupViewSet(viewsets.ModelViewSet):
class InvestmentClassViewSet(viewsets.ModelViewSet):
"""ViewSet for managing asset classes and their target allocation."""
"""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
@@ -62,7 +64,9 @@ class InvestmentClassViewSet(viewsets.ModelViewSet):
),
)
class AccountViewSet(viewsets.ModelViewSet):
"""ViewSet for managing accounts."""
"""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()
@@ -109,6 +113,8 @@ class AccountViewSet(viewsets.ModelViewSet):
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
)
+5
View File
@@ -7,6 +7,9 @@ from apps.currencies.models import ExchangeRate
class CurrencyViewSet(viewsets.ModelViewSet):
"""Currencies and assets (e.g. crypto). `exchange_currency` is the default
currency their amounts are converted to."""
queryset = Currency.objects.all()
serializer_class = CurrencySerializer
filterset_fields = {
@@ -23,6 +26,8 @@ class CurrencyViewSet(viewsets.ModelViewSet):
class ExchangeRateViewSet(viewsets.ModelViewSet):
"""How much one unit of `from_currency` is worth in `to_currency` on `date`."""
queryset = ExchangeRate.objects.all()
serializer_class = ExchangeRateSerializer
filterset_fields = {
+27
View File
@@ -1,3 +1,5 @@
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import extend_schema
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
@@ -7,6 +9,9 @@ from apps.api.serializers import DCAStrategySerializer, DCAEntrySerializer
class DCAStrategyViewSet(viewsets.ModelViewSet):
"""Dollar-cost averaging plans: recurring buys of `target_currency` paid in
`payment_currency`."""
permission_classes = SHARED_OBJECT_PERMISSIONS
queryset = DCAStrategy.objects.all()
serializer_class = DCAStrategySerializer
@@ -24,16 +29,36 @@ class DCAStrategyViewSet(viewsets.ModelViewSet):
def get_queryset(self):
return DCAStrategy.objects.all()
@extend_schema(
summary="Buys over time",
description="Chart data for the strategy's buys: `labels` are entry dates in the server's display format.",
responses=OpenApiTypes.OBJECT,
)
@action(detail=True, methods=["get"])
def investment_frequency(self, request, pk=None):
strategy = self.get_object()
return Response(strategy.investment_frequency_data())
@extend_schema(
summary="Paid vs current value per entry",
description=(
"Chart data, one item per entry. Despite their names, `entry_prices` holds "
"the amount paid and `current_prices` the entry's current value, both in the "
"payment currency; `amounts_bought` is the amount received. `labels` are entry "
"dates in the server's display format."
),
responses=OpenApiTypes.OBJECT,
)
@action(detail=True, methods=["get"])
def price_comparison(self, request, pk=None):
strategy = self.get_object()
return Response(strategy.price_comparison_data())
@extend_schema(
summary="Latest price of the target currency",
description="The latest exchange rate from the target to the payment currency, and its date.",
responses=OpenApiTypes.OBJECT,
)
@action(detail=True, methods=["get"])
def current_price(self, request, pk=None):
strategy = self.get_object()
@@ -45,6 +70,8 @@ class DCAStrategyViewSet(viewsets.ModelViewSet):
class DCAEntryViewSet(viewsets.ModelViewSet):
"""One buy in a DCA strategy: what was paid and what was received."""
permission_classes = SHARED_OBJECT_PERMISSIONS
shared_object_via = "strategy"
queryset = DCAEntry.objects.all()
+100 -1
View File
@@ -1,6 +1,12 @@
from copy import deepcopy
from rest_framework import viewsets
from django.db.models import Count, Sum
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiParameter, extend_schema, inline_serializer
from rest_framework import serializers, viewsets
from rest_framework.decorators import action
from rest_framework.exceptions import ValidationError
from rest_framework.response import Response
from apps.api.serializers import (
TransactionSerializer,
@@ -21,8 +27,23 @@ from apps.transactions.models import (
from apps.rules.signals import transaction_updated, transaction_created
from apps.api.permissions import SHARED_OBJECT_PERMISSIONS
# group_by -> (id field, name field)
SUMMARY_GROUPS = {
"category": ("category__id", "category__name"),
"tag": ("tags__id", "tags__name"),
"entity": ("entities__id", "entities__name"),
"account": ("account__id", "account__name"),
"month": (None, "reference_date"),
}
class TransactionViewSet(viewsets.ModelViewSet):
"""Income (`IN`) and expense (`EX`) entries. `amount` is never negative;
`type` gives the direction. `amount` is required unless `sub_transactions` is
sent; then it's their sum. `reference_date` is the month the transaction
counts toward, which may differ from `date`. Transfers are an expense and
an income linked through `linked_transaction`; deleting one deletes both."""
queryset = Transaction.objects.all()
serializer_class = TransactionSerializer
filterset_fields = {
@@ -36,6 +57,8 @@ class TransactionViewSet(viewsets.ModelViewSet):
"description": ["exact", "icontains"],
"notes": ["exact", "icontains"],
"category": ["exact", "isnull"],
"tags": ["exact"],
"entities": ["exact"],
"installment_plan": ["exact", "isnull"],
"installment_id": ["exact", "gte", "lte"],
"recurring_transaction": ["exact", "isnull"],
@@ -67,8 +90,76 @@ class TransactionViewSet(viewsets.ModelViewSet):
kwargs["partial"] = True
return self.update(request, *args, **kwargs)
@extend_schema(
summary="Sum transactions",
description=(
"Totals and counts of the transactions matching the same filters as "
"the list, split by currency and type, optionally grouped. Muted "
"transactions and those in muted categories are left out unless "
"`include_muted` is true. Grouping by tag or entity counts a "
"transaction once per tag/entity; untagged ones have a null group."
),
parameters=[
OpenApiParameter("group_by", enum=list(SUMMARY_GROUPS)),
OpenApiParameter("include_muted", OpenApiTypes.BOOL),
],
responses=inline_serializer(
"TransactionSummaryRow",
{
"currency": serializers.CharField(),
"type": serializers.CharField(),
"group": serializers.CharField(allow_null=True, required=False),
"group_id": serializers.IntegerField(allow_null=True, required=False),
"total": serializers.DecimalField(max_digits=42, decimal_places=30),
"count": serializers.IntegerField(),
},
many=True,
),
)
@action(detail=False, methods=["get"], pagination_class=None)
def summary(self, request):
group_by = request.query_params.get("group_by")
if group_by and group_by not in SUMMARY_GROUPS:
raise ValidationError(
{"group_by": f"Must be one of: {', '.join(SUMMARY_GROUPS)}."}
)
queryset = self.filter_queryset(self.get_queryset())
if request.query_params.get("include_muted", "").lower() != "true":
queryset = queryset.exclude(mute=True).exclude(category__mute=True)
id_field, group_field = SUMMARY_GROUPS.get(group_by, (None, None))
fields = ["account__currency__code", "type"] + [
f for f in (id_field, group_field) if f
]
rows = (
queryset.order_by() # the default ordering would split the groups
.values(*fields)
.annotate(total=Sum("amount"), count=Count("id"))
# by group first, so months come out in order
.order_by(*[f for f in (group_field,) if f], "account__currency__code", "type")
)
data = []
for row in rows:
item = {
"currency": row["account__currency__code"],
"type": row["type"],
"total": row["total"],
"count": row["count"],
}
if group_field:
group = row[group_field]
item["group"] = group.strftime("%Y-%m") if group_by == "month" and group else group
if id_field:
item["group_id"] = row[id_field]
data.append(item)
return Response(data)
class TransactionCategoryViewSet(viewsets.ModelViewSet):
"""Categories, one per transaction. Transactions in a muted category are left out of totals. Sending a category name that doesn't exist on a transaction creates it."""
permission_classes = SHARED_OBJECT_PERMISSIONS
queryset = TransactionCategory.objects.all()
serializer_class = TransactionCategorySerializer
@@ -87,6 +178,8 @@ class TransactionCategoryViewSet(viewsets.ModelViewSet):
class TransactionTagViewSet(viewsets.ModelViewSet):
"""Tags; a transaction can have many. Sending a tag name that doesn't exist on a transaction creates it."""
permission_classes = SHARED_OBJECT_PERMISSIONS
queryset = TransactionTag.objects.all()
serializer_class = TransactionTagSerializer
@@ -104,6 +197,8 @@ class TransactionTagViewSet(viewsets.ModelViewSet):
class TransactionEntityViewSet(viewsets.ModelViewSet):
"""Entities are the people or businesses on the other side of a transaction. Sending an entity name that doesn't exist on a transaction creates it."""
permission_classes = SHARED_OBJECT_PERMISSIONS
queryset = TransactionEntity.objects.all()
serializer_class = TransactionEntitySerializer
@@ -121,6 +216,8 @@ class TransactionEntityViewSet(viewsets.ModelViewSet):
class InstallmentPlanViewSet(viewsets.ModelViewSet):
"""A purchase split into a fixed number of installments. Saving a plan creates or updates one transaction per installment. `installment_amount` is required unless `sub_transactions` is sent; then it's their sum."""
queryset = InstallmentPlan.objects.all()
serializer_class = InstallmentPlanSerializer
filterset_fields = {
@@ -149,6 +246,8 @@ class InstallmentPlanViewSet(viewsets.ModelViewSet):
class RecurringTransactionViewSet(viewsets.ModelViewSet):
"""A transaction or transfer that repeats on a schedule. Saving one generates its upcoming transactions and updates the unpaid ones. `amount` is required unless `sub_transactions` is sent; then it's their sum."""
queryset = RecurringTransaction.objects.all()
serializer_class = RecurringTransactionSerializer
filterset_fields = {
+18 -1
View File
@@ -6,7 +6,7 @@ from secrets import token_urlsafe
from django.conf import settings
from django.core.exceptions import NON_FIELD_ERRORS, ValidationError
from django.http import JsonResponse
from django.http import Http404, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from oauth2_provider.models import get_application_model
@@ -116,6 +116,23 @@ def authorization_server_metadata(request):
return JsonResponse(metadata)
@require_http_methods(["GET"])
def protected_resource_metadata(request):
"""OAuth Protected Resource Metadata (RFC 9728) for the MCP endpoint."""
if not settings.MCP_ENABLED:
raise Http404
base_url = _base_url(request)
return JsonResponse(
{
"resource": f"{base_url}/mcp",
"resource_name": "WYGIWYH",
"authorization_servers": [base_url],
"scopes_supported": sorted(settings.OAUTH2_PROVIDER["SCOPES"].keys()),
"bearer_methods_supported": ["header"],
}
)
@csrf_exempt
@require_http_methods(["POST"])
def dynamic_client_registration(request):