mirror of
https://github.com/eitchtee/WYGIWYH.git
synced 2026-11-19 07:08:54 +01:00
Merge pull request #682 from eitchtee/feat/quick-transactions-api
feat(api): quick transactions endpoint
This commit is contained in:
6 files changed
+168
-36
No files matched your search
@@ -24,6 +24,7 @@ from apps.transactions.models import (
|
||||
TransactionEntity,
|
||||
RecurringTransaction,
|
||||
SubTransaction,
|
||||
QuickTransaction,
|
||||
)
|
||||
from apps.common.middleware.thread_local import get_current_user
|
||||
|
||||
@@ -310,3 +311,60 @@ class TransactionSerializer(SubTransactionsMixin, serializers.ModelSerializer):
|
||||
@staticmethod
|
||||
def get_exchanged_amount(obj) -> Decimal:
|
||||
return obj.exchanged_amount()
|
||||
|
||||
|
||||
class QuickTransactionSerializer(SubTransactionsMixin, serializers.ModelSerializer):
|
||||
sub_transactions = SubTransactionSerializer(many=True, required=False)
|
||||
category: str | int = TransactionCategoryField(required=False)
|
||||
tags: str | int = TransactionTagField(required=False)
|
||||
entities: str | int = TransactionEntityField(required=False)
|
||||
|
||||
class Meta:
|
||||
model = QuickTransaction
|
||||
fields = [
|
||||
"id",
|
||||
"name",
|
||||
"account",
|
||||
"type",
|
||||
"is_paid",
|
||||
"mute",
|
||||
"amount",
|
||||
"sub_transactions",
|
||||
"to_account",
|
||||
"to_amount",
|
||||
"description",
|
||||
"notes",
|
||||
"category",
|
||||
"tags",
|
||||
"entities",
|
||||
"internal_note",
|
||||
"internal_id",
|
||||
]
|
||||
|
||||
def is_transfer(self, data):
|
||||
type_ = data.get("type", getattr(self.instance, "type", None))
|
||||
return type_ == QuickTransaction.Type.TRANSFER
|
||||
|
||||
def validate(self, attrs):
|
||||
# Same rules as the model's, which DRF doesn't run
|
||||
name = attrs.get("name", getattr(self.instance, "name", None))
|
||||
same_name = QuickTransaction.objects.filter(name=name)
|
||||
if self.instance:
|
||||
same_name = same_name.exclude(pk=self.instance.pk)
|
||||
if same_name.exists():
|
||||
raise serializers.ValidationError(
|
||||
{"name": _("A quick transaction with this name already exists.")}
|
||||
)
|
||||
if self.is_transfer(attrs):
|
||||
account = attrs.get("account", getattr(self.instance, "account", None))
|
||||
to_account = attrs.get("to_account", getattr(self.instance, "to_account", None))
|
||||
if not to_account:
|
||||
raise serializers.ValidationError(
|
||||
{"to_account": _("This field is required.")}
|
||||
)
|
||||
if to_account == account:
|
||||
raise serializers.ValidationError(
|
||||
{"to_account": _("From and To accounts must be different.")}
|
||||
)
|
||||
return super().validate(attrs)
|
||||
|
||||
@@ -10,6 +10,7 @@ router.register(r"tags", views.TransactionTagViewSet)
|
||||
router.register(r"entities", views.TransactionEntityViewSet)
|
||||
router.register(r"installment-plans", views.InstallmentPlanViewSet)
|
||||
router.register(r"recurring-transactions", views.RecurringTransactionViewSet)
|
||||
router.register(r"quick-transactions", views.QuickTransactionViewSet)
|
||||
router.register(r"account-groups", views.AccountGroupViewSet)
|
||||
router.register(r"accounts", views.AccountViewSet)
|
||||
router.register(r"investment-classes", views.InvestmentClassViewSet)
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
from copy import deepcopy
|
||||
|
||||
from rest_framework import viewsets
|
||||
from rest_framework import status, viewsets
|
||||
from rest_framework.decorators import action
|
||||
from rest_framework.response import Response
|
||||
|
||||
from apps.api.serializers import (
|
||||
TransactionSerializer,
|
||||
@@ -9,6 +11,7 @@ from apps.api.serializers import (
|
||||
InstallmentPlanSerializer,
|
||||
TransactionEntitySerializer,
|
||||
RecurringTransactionSerializer,
|
||||
QuickTransactionSerializer,
|
||||
)
|
||||
from apps.transactions.models import (
|
||||
Transaction,
|
||||
@@ -17,6 +20,7 @@ from apps.transactions.models import (
|
||||
InstallmentPlan,
|
||||
TransactionEntity,
|
||||
RecurringTransaction,
|
||||
QuickTransaction,
|
||||
)
|
||||
from apps.rules.signals import transaction_updated, transaction_created
|
||||
from apps.api.permissions import SHARED_OBJECT_PERMISSIONS
|
||||
@@ -176,3 +180,36 @@ class RecurringTransactionViewSet(viewsets.ModelViewSet):
|
||||
|
||||
def get_queryset(self):
|
||||
return RecurringTransaction.objects.prefetch_related("sub_transactions")
|
||||
|
||||
|
||||
class QuickTransactionViewSet(viewsets.ModelViewSet):
|
||||
queryset = QuickTransaction.objects.all()
|
||||
serializer_class = QuickTransactionSerializer
|
||||
filterset_fields = {
|
||||
"name": ["exact", "icontains"],
|
||||
"account": ["exact"],
|
||||
"type": ["exact"],
|
||||
"amount": ["exact", "gte", "lte", "gt", "lt"],
|
||||
"description": ["exact", "icontains"],
|
||||
"category": ["exact", "isnull"],
|
||||
}
|
||||
search_fields = ["name", "description", "notes"]
|
||||
ordering_fields = "__all__"
|
||||
ordering = ["name"]
|
||||
|
||||
def get_queryset(self):
|
||||
return QuickTransaction.objects.prefetch_related("sub_transactions")
|
||||
|
||||
@action(detail=True, methods=["post"], serializer_class=TransactionSerializer)
|
||||
def use(self, request, pk=None):
|
||||
"""Creates today's transaction from this quick transaction, like its button
|
||||
in the app. For a transfer, returns the "from" (expense) side."""
|
||||
new_transaction, to_transaction = self.get_object().create_transaction()
|
||||
transaction_created.send(sender=new_transaction)
|
||||
if to_transaction:
|
||||
transaction_created.send(sender=to_transaction)
|
||||
return Response(
|
||||
TransactionSerializer(new_transaction, context=self.get_serializer_context()).data,
|
||||
status=status.HTTP_201_CREATED,
|
||||
)
|
||||
|
||||
@@ -1484,5 +1484,30 @@ class QuickTransaction(TransferTemplate, OwnedObject):
|
||||
self.full_clean()
|
||||
super().save(*args, **kwargs)
|
||||
|
||||
def create_transaction(self):
|
||||
"""Creates today's transaction from this template, and the "to" side when
|
||||
it's a transfer (None otherwise). Callers send the created signals."""
|
||||
today = timezone.localdate(timezone.now())
|
||||
new_transaction = Transaction(
|
||||
account=self.account,
|
||||
type=self.transaction_type,
|
||||
is_paid=self.is_paid,
|
||||
mute=self.mute,
|
||||
amount=self.amount,
|
||||
description=self.description,
|
||||
notes=self.notes,
|
||||
category=self.category,
|
||||
internal_note=self.internal_note,
|
||||
date=today,
|
||||
reference_date=today.replace(day=1),
|
||||
)
|
||||
with transaction.atomic():
|
||||
new_transaction.save()
|
||||
new_transaction.tags.set(self.tags.all())
|
||||
new_transaction.entities.set(self.entities.all())
|
||||
new_transaction.copy_sub_transactions_from(self)
|
||||
to_transaction = self.complete_transfer(new_transaction)
|
||||
return new_transaction, to_transaction
|
||||
|
||||
def __str__(self):
|
||||
return self.name
|
||||
@@ -319,3 +319,48 @@ class SubTransactionApiTests(TestCase):
|
||||
response = self.api.patch(url, {"type": "TR", "to_account": other.id}, format="json")
|
||||
self.assertEqual(response.status_code, 200, response.data)
|
||||
self.assertEqual(response.data["sub_transactions"], [])
|
||||
|
||||
def test_quick_transaction_endpoint_creates_and_uses_templates(self):
|
||||
response = self.api.post(
|
||||
"/api/quick-transactions/",
|
||||
{"name": "Lunch", "account": self.account.id, "type": "EX", "description": "Lunch",
|
||||
"sub_transactions": [{"name": "Meal", "amount": "11.90"}, {"name": "Tip", "amount": "2"}]},
|
||||
format="json",
|
||||
)
|
||||
self.assertEqual(response.status_code, 201, response.data)
|
||||
self.assertEqual(Decimal(response.data["amount"]), Decimal("13.90"))
|
||||
|
||||
response = self.api.post(f"/api/quick-transactions/{response.data['id']}/use/")
|
||||
self.assertEqual(response.status_code, 201, response.data)
|
||||
self.assertEqual(Decimal(response.data["amount"]), Decimal("13.90"))
|
||||
self.assertEqual([s["name"] for s in response.data["sub_transactions"]], ["Meal", "Tip"])
|
||||
self.assertEqual(response.data["date"], timezone.localdate().isoformat())
|
||||
|
||||
def test_quick_transaction_endpoint_validates_like_the_app(self):
|
||||
other = Account.objects.create(name="B", currency=self.account.currency, owner=self.account.owner)
|
||||
base = {"account": self.account.id, "amount": "5"}
|
||||
self.assertEqual(
|
||||
self.api.post("/api/quick-transactions/", {**base, "name": "Coffee", "type": "EX"}, format="json").status_code,
|
||||
201,
|
||||
)
|
||||
for data, field in (
|
||||
({"name": "Coffee", "type": "EX"}, "name"),
|
||||
({"name": "Move", "type": "TR"}, "to_account"),
|
||||
({"name": "Move", "type": "TR", "to_account": self.account.id}, "to_account"),
|
||||
({"name": "Move", "type": "TR", "to_account": other.id,
|
||||
"sub_transactions": [{"name": "X", "amount": "1"}]}, "sub_transactions"),
|
||||
):
|
||||
with self.subTest(data=data):
|
||||
response = self.api.post("/api/quick-transactions/", {**base, **data}, format="json")
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertIn(field, response.data)
|
||||
|
||||
response = self.api.post(
|
||||
"/api/quick-transactions/",
|
||||
{**base, "name": "Move", "type": "TR", "to_account": other.id}, format="json",
|
||||
)
|
||||
self.assertEqual(response.status_code, 201, response.data)
|
||||
response = self.api.post(f"/api/quick-transactions/{response.data['id']}/use/")
|
||||
self.assertEqual(response.status_code, 201, response.data)
|
||||
self.assertTrue(response.data["linked_transaction"])
|
||||
|
||||
@@ -1,17 +1,13 @@
|
||||
from django.contrib import messages
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.db import transaction as db_transaction
|
||||
from django.forms import model_to_dict
|
||||
from django.http import HttpResponse
|
||||
from django.shortcuts import render, get_object_or_404
|
||||
from django.utils import timezone
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from django.views.decorators.http import require_http_methods
|
||||
|
||||
from apps.common.decorators.htmx import only_htmx
|
||||
from apps.transactions.forms import QuickTransactionForm
|
||||
from apps.transactions.models import QuickTransaction, transaction_created
|
||||
from apps.transactions.models import Transaction
|
||||
|
||||
|
||||
@login_required
|
||||
@@ -126,37 +122,7 @@ def quick_transaction_add_as_transaction(request, quick_transaction_id):
|
||||
quick_transaction: QuickTransaction = get_object_or_404(
|
||||
QuickTransaction, id=quick_transaction_id
|
||||
)
|
||||
today = timezone.localdate(timezone.now())
|
||||
|
||||
quick_transaction_data = model_to_dict(
|
||||
quick_transaction,
|
||||
exclude=[
|
||||
"id",
|
||||
"name",
|
||||
"owner",
|
||||
"account",
|
||||
"category",
|
||||
"tags",
|
||||
"entities",
|
||||
"internal_id",
|
||||
"to_account",
|
||||
"to_amount",
|
||||
],
|
||||
)
|
||||
|
||||
new_transaction = Transaction(**quick_transaction_data)
|
||||
new_transaction.type = quick_transaction.transaction_type
|
||||
new_transaction.account = quick_transaction.account
|
||||
new_transaction.category = quick_transaction.category
|
||||
|
||||
new_transaction.date = today
|
||||
new_transaction.reference_date = today.replace(day=1)
|
||||
with db_transaction.atomic():
|
||||
new_transaction.save()
|
||||
new_transaction.tags.set(quick_transaction.tags.all())
|
||||
new_transaction.entities.set(quick_transaction.entities.all())
|
||||
new_transaction.copy_sub_transactions_from(quick_transaction)
|
||||
to_transaction = quick_transaction.complete_transfer(new_transaction)
|
||||
new_transaction, to_transaction = quick_transaction.create_transaction()
|
||||
|
||||
transaction_created.send(sender=new_transaction)
|
||||
if to_transaction:
|
||||
|
||||
Reference in new issue
Block a user