diff --git a/refunding/admin.py b/refunding/admin.py index f2fb438..906bdf9 100644 --- a/refunding/admin.py +++ b/refunding/admin.py @@ -1,4 +1,5 @@ from django.contrib import admin +from refunding.forms import RefundForm from refunding.models import Refund, Payment @@ -8,11 +9,13 @@ class RefundAdmin(admin.ModelAdmin): list_display_links = ('title',) search_fields = ('title',) date_hierarchy = 'date' + form = RefundForm + readonly_fields = ('amount',) @admin.register(Payment) class PaymentAdmin(admin.ModelAdmin): - list_display = ('title', 'date', 'value', 'user', 'refund') + list_display = ('title', 'date', 'eur_value', 'user', 'refund') list_display_links = ('title',) search_fields = ('title',) date_hierarchy = 'date' diff --git a/refunding/forms.py b/refunding/forms.py new file mode 100644 index 0000000..78583fc --- /dev/null +++ b/refunding/forms.py @@ -0,0 +1,24 @@ +from django import forms +from refunding.models import Refund, Payment + + +class RefundForm(forms.ModelForm): + class Meta: + model = Refund + fields = '__all__' + + payments = forms.ModelMultipleChoiceField(queryset=Payment.objects.all()) + + def __init__(self, *args, **kwargs): + super(RefundForm, self).__init__(*args, **kwargs) + if self.instance: + self.fields['payments'].initial = self.instance.payment_set.all() + + def save(self, *args, **kwargs): + # Save the refund + instance = super(RefundForm, self).save(commit=False) + # Remove the refund from payments it was previously assigned to + self.fields['payments'].initial.update(refund=None) + # Add the refund to the selected payments + self.cleaned_data['payments'].update(refund=instance) + return instance diff --git a/refunding/models.py b/refunding/models.py index aa85635..717815a 100644 --- a/refunding/models.py +++ b/refunding/models.py @@ -1,5 +1,6 @@ from django.db import models from django.conf import settings +from django.db.models import Sum AUTH_USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User') @@ -14,6 +15,12 @@ class Refund(models.Model): on_delete=models.PROTECT ) + def amount(self) -> float: + return self.payment_set.all().aggregate(Sum('value')).get('value__sum') / 100 + + def __str__(self) -> str: + return "{0} on {1} for {2}".format(self.title, self.date, self.amount()) + class Payment(models.Model): title = models.CharField(max_length=100) @@ -31,3 +38,9 @@ class Payment(models.Model): null=True, blank=True ) + + def __str__(self) -> str: + return '{0} on {1} for {2}'.format(self.title, self.date, self.value / 100) + + def eur_value(self) -> float: + return self.value / 100