Skip to content
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions stregsystem/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@

class SaleAdmin(admin.ModelAdmin):
list_filter = ('room', 'timestamp')
list_display = ('get_username', 'get_fullname', 'get_product_name', 'get_room_name', 'timestamp', 'get_price_display')
list_display = ('get_username', 'get_fullname', 'get_product_name', 'get_room_name', 'timestamp', 'get_price_display', 'is_reimbursed')
actions = ['refund']
search_fields = ['^member__username', '=product__id', 'product__name']
valid_lookups = ('member')
Expand Down Expand Up @@ -224,7 +224,7 @@ def get_queryset(self):


class PaymentAdmin(admin.ModelAdmin):
list_display = ('get_username', 'timestamp', 'get_amount_display', 'is_mobilepayment')
list_display = ('get_username', 'timestamp', 'get_amount_display', 'is_mobilepayment', 'is_reimbursement')
valid_lookups = ('member')
search_fields = ['member__username']
autocomplete_fields = ['member']
Expand Down
21 changes: 21 additions & 0 deletions stregsystem/migrations/0014_added_reimbursement.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('stregsystem', '0013_mobilepayment_permission_20201123_1344'),
]

operations = [
migrations.AddField(
model_name='payment',
name='is_reimbursement',
field=models.BooleanField(default=False, help_text='Viser om en betaling er tilbageført'),
),
migrations.AddField(
model_name='sale',
name='is_reimbursed',
field=models.BooleanField(default=False, help_text='Viser om et salg er tilbageført'),
),
]
28 changes: 24 additions & 4 deletions stregsystem/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,18 @@ def execute(self):
# We changed the user balance, so save that
self.member.save()

class Reimbursement(object):
#Limits the amount of hours a reimbursement is available.
MAX_REIMBUSEMENT_HOURS = 12

@transaction.atomic
def from_sale(sale_id):
sale = Sale.objects.get(id=sale_id)
if not sale.is_reimbursable():
return
sale.is_reimbursed = True
sale.save()
Payment.objects.create(amount=sale.price, member=sale.member, is_reimbursement=True)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should add a LogEntry to the Payment object to note that it is a result of a refund.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

While I think this is a great idea, during implementation, I found out that LogEntry has a NOT NULL constraint on the user_id. So that pretty much rules it out.
https://github.com/django/django/blob/b9fe7f9294b1b4fc974c008adeb96e1375cdb0c6/django/contrib/admin/models.py#L45

An idea would be to make a "reimbursement user" and set that user as the person who did it. Buut that is kinda hacky.

Any ideas on how to overcome this?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would actually prefer if the person who did the reimbursement was referenced on the LogEntry. That allows for tracability of reimbursements. The Payment object to be reimbursed should also be referenced.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Completely agree, but since stregsystemet has modeled it's own members seperate from django users, it does not have users and thus it seems impossible to use the LogEntry table since LogEntry has a NOT NULL constraint to users.


class GetTransaction(MoneyTransaction):
# The change to the users account
Expand Down Expand Up @@ -295,6 +307,8 @@ class Meta:
member = models.ForeignKey(Member, on_delete=models.CASCADE)
timestamp = models.DateTimeField(auto_now_add=True)
amount = models.IntegerField() # penge, oere...
is_reimbursement = models.BooleanField(default=False, null=False,
help_text='Viser om en betaling er tilbageført')

@deprecated
def amount_display(self):
Expand Down Expand Up @@ -513,6 +527,8 @@ class Sale(models.Model):
room = models.ForeignKey(Room, on_delete=models.CASCADE, null=True)
timestamp = models.DateTimeField(auto_now_add=True)
price = models.IntegerField()
is_reimbursed = models.BooleanField(default=False, null=False,
help_text='Viser om et salg er tilbageført',)

class Meta:
index_together = [
Expand All @@ -530,17 +546,21 @@ def price_display(self):
# XXX - django bug - kan ikke vaelge mellem desc og asc i admin, som ved normalt felt
price_display.admin_order_field = 'price'

def is_reimbursable(self):
from datetime import timedelta
return (not self.is_reimbursed) and timedelta(hours=Reimbursement.MAX_REIMBUSEMENT_HOURS) >= timezone.now() - self.timestamp

@deprecated
def __unicode__(self):
return self.__str__()

def __str__(self):
return self.member.username + " " + self.product.name + " (" + money(self.price) + ") " + str(self.timestamp)

def save(self, *args, **kwargs):
if self.id:
raise RuntimeError("Updates of sales are not allowed")
super(Sale, self).save(*args, **kwargs)
#def save(self, *args, **kwargs):
# if self.id:
# raise RuntimeError("Updates of sales are not allowed")
# super(Sale, self).save(*args, **kwargs)

def delete(self, *args, **kwargs):
if self.id:
Expand Down
10 changes: 10 additions & 0 deletions stregsystem/templates/stregsystem/menu_userinfo.html
Original file line number Diff line number Diff line change
Expand Up @@ -39,13 +39,23 @@
<th align=left>Dato og tidspunkt</th>
<th align=left>Produkt</th>
<th align=left>Pris</th>
<th align=left>Tilbagefør</th>
</tr>
{% autoescape off %}
{% for sale in last_sale_list %}
<tr>
<td>{{sale.timestamp}}</td>
<td>{{sale.product.name}}</td>
<td align="right">{{sale.price|money}}</td>
<td>
{% if sale.is_reimbursable %}
<form action="" method="post">
{% csrf_token %}
<input type="hidden" name="sale_id" value="{{ sale.pk }}"/>
<button name="action" value="reimburse" onclick="return confirm('Er du sikker på at du vil refundere salget på {{sale.product.name}} til en værdi af {{sale.price|money}} kr?')">Undo</button>
</form>
{% endif %}
</td>
</tr>
{% endfor %}
{% endautoescape %}
Expand Down
55 changes: 52 additions & 3 deletions stregsystem/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
Payment,
PayTransaction,
Product,
Reimbursement,
Room,
Sale,
StregForbudError,
Expand Down Expand Up @@ -770,9 +771,7 @@ def test_sale_save_already_saved(self):
price=100
)
sale.save()

with self.assertRaises(RuntimeError):
sale.save()
sale.save()

def test_sale_delete_not_saved(self):
sale = Sale(
Expand All @@ -796,6 +795,56 @@ def test_sale_delete_already_saved(self):

self.assertIsNone(sale.id)

class ReimbursementTests(TestCase):
@classmethod
def setUpTestData(self):
self.member = Member.objects.create(
username="jon",
balance=100
)
self.product = Product.objects.create(
name="beer",
price=1.0,
active=True,
)
with freeze_time(timezone.now() - datetime.timedelta(hours=11)):
self.almost_oldsale = Sale.objects.create(
member=self.member,
product=self.product,
price=200,
)
with freeze_time(timezone.now() - datetime.timedelta(hours=12, minutes=1)):
self.oldsale = Sale.objects.create(
member=self.member,
product=self.product,
price=300,
)
self.newsale = Sale.objects.create(
member=self.member,
product=self.product,
price=100,
)

def test_reimbursement_success(self):
self.assertFalse(Payment.objects.filter(is_reimbursement=True).exists())
self.assertFalse(Sale.objects.filter(is_reimbursed=True, id=self.newsale.id).exists())
Reimbursement.from_sale(self.newsale.id)
self.assertTrue(Payment.objects.filter(is_reimbursement=True).exists())
self.assertTrue(Sale.objects.filter(is_reimbursed=True, id=self.newsale.id).exists())

def test_reimbursement_later_success(self):
self.assertFalse(Payment.objects.filter(is_reimbursement=True).exists())
self.assertFalse(Sale.objects.filter(is_reimbursed=True, id=self.almost_oldsale.id).exists())
Reimbursement.from_sale(self.almost_oldsale.id)
self.assertTrue(Payment.objects.filter(is_reimbursement=True).exists())
self.assertTrue(Sale.objects.filter(is_reimbursed=True, id=self.almost_oldsale.id).exists())

def test_reimbursement_fail(self):
self.assertFalse(Payment.objects.filter(is_reimbursement=True).exists())
self.assertFalse(Sale.objects.filter(is_reimbursed=True, id=self.oldsale.id).exists())
Reimbursement.from_sale(self.oldsale.id)
self.assertFalse(Payment.objects.filter(is_reimbursement=True).exists())
self.assertFalse(Sale.objects.filter(is_reimbursed=True, id=self.oldsale.id).exists())

class MemberTests(TestCase):
def test_fulfill_pay_transaction(self):
Expand Down
10 changes: 7 additions & 3 deletions stregsystem/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@
Room,
Sale,
StregForbudError,
MobilePayment
MobilePayment,
Reimbursement,
)
from stregsystem.utils import (
make_active_productlist_query,
Expand Down Expand Up @@ -185,11 +186,14 @@ def usermenu(request, room, member, bought, from_sale=False):
def menu_userinfo(request, room_id, member_id):
room = Room.objects.get(pk=room_id)
news = __get_news()

if request.method == 'POST' and request.POST.get('action') is not None and request.POST['action'] == 'reimburse':
Reimbursement.from_sale(int(request.POST['sale_id']))
member = Member.objects.get(pk=member_id, active=True)

last_sale_list = member.sale_set.order_by('-timestamp')[:10]
last_sale_list = member.sale_set.filter(is_reimbursed=False).order_by('-timestamp')[:10]
try:
last_payment = member.payment_set.order_by('-timestamp')[0]
last_payment = member.payment_set.filter(is_reimbursement=False).order_by('-timestamp')[0]
except IndexError:
last_payment = None

Expand Down