diff --git a/core/bookloader.py b/core/bookloader.py index 631c7d59..74dd6e60 100755 --- a/core/bookloader.py +++ b/core/bookloader.py @@ -474,6 +474,8 @@ def merge_works(w1, w2, user=None): w1.description = w2.description if w2.featured and not w1.featured: w1.featured = w2.featured + if w2.is_free and not w1.is_free: + w1.is_free = True w1.save() for wishlist in models.Wishlist.objects.filter(works__in=[w2]): w2source = wishlist.work_source(w2) diff --git a/core/models.py b/core/models.py index 0934afa9..6bf84b28 100755 --- a/core/models.py +++ b/core/models.py @@ -26,7 +26,7 @@ from django.core.urlresolvers import reverse from django.core.files.base import ContentFile from django.db import models from django.db.models import F, Q, get_model -from django.db.models.signals import post_save +from django.db.models.signals import post_save, pre_delete from django.utils.translation import ugettext_lazy as _ ''' @@ -1862,6 +1862,21 @@ class Ebook(models.Model): self.active=True self.save() +def set_free_flag(sender, instance, created, **kwargs): + if created: + if not instance.edition.work.is_free: + instance.edition.work.is_free = True + instance.edition.work.save() + +post_save.connect(set_free_flag,sender=Ebook) + +def reset_free_flag(sender, instance, **kwargs): + if instance.edition.work.ebooks().count()==1: + instance.edition.work.is_free = False + instance.edition.work.save() + +pre_delete.connect(reset_free_flag,sender=Ebook) + class Wishlist(models.Model): created = models.DateTimeField(auto_now_add=True) user = models.OneToOneField(User, related_name='wishlist') diff --git a/core/tests.py b/core/tests.py index 4abc1311..350f1e9d 100755 --- a/core/tests.py +++ b/core/tests.py @@ -183,6 +183,9 @@ class BookLoaderTests(TestCase): e2 = Edition(work=w2) e2.save() + eb1 = Ebook(edition = e2) + eb1.save() + e2a = Edition(work=w2) e2a.save() @@ -192,7 +195,10 @@ class BookLoaderTests(TestCase): self.assertTrue(e1.work) self.assertTrue(e2.work) self.assertEqual(models.Work.objects.count(), 2) - + + self.assertTrue(w2.is_free) + self.assertFalse(w1.is_free) + w1_id = w1.id w2_id = w2.id @@ -206,6 +212,8 @@ class BookLoaderTests(TestCase): self.assertEqual(models.WasWork.objects.count(),1) self.assertEqual(w1.subjects.count(),2) + self.assertTrue(w1.is_free) + # getting proper view? anon_client = Client() r = anon_client.get("/work/%s/" % w1_id) @@ -788,6 +796,11 @@ class DownloadPageTest(TestCase): response = anon_client.get("/work/%s/download/" % w.id, follow=True) self.assertContains(response, "/download_ebook/%s/"% eb1.id, count=10) self.assertContains(response, "/download_ebook/%s/"% eb2.id, count=5) + self.assertTrue(eb1.edition.work.is_free) + eb1.delete() + self.assertTrue(eb2.edition.work.is_free) + eb2.delete() + self.assertFalse(eb2.edition.work.is_free) class LocaldatetimeTest(TestCase):