For upgrades
[wolnelektury.git] / src / club / models.py
index b79a7a8..8c6c8db 100644 (file)
@@ -1,7 +1,7 @@
-# This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
-# Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
+# This file is part of Wolne Lektury, licensed under GNU Affero GPLv3 or later.
+# Copyright © Fundacja Wolne Lektury. See NOTICE for more information.
 #
-from datetime import datetime, timedelta
+from datetime import datetime, timedelta, timezone
 from decimal import Decimal
 import os
 import tempfile
@@ -12,7 +12,7 @@ from django.core.mail import send_mail, EmailMessage
 from django.urls import reverse
 from django.db import models
 from django import template
-from django.utils.timezone import now, utc
+from django.utils.timezone import now
 from django.utils.translation import get_language
 from django_countries.fields import CountryField
 from catalogue.utils import get_random_hash
@@ -161,6 +161,15 @@ class Schedule(models.Model):
         club = Club.objects.first()
         return club.get_description_for_amount(self.amount, self.monthly)
 
+    def is_custom_amount(self):
+        club = Club.objects.first()
+        if not self.amount:
+            return False
+        if self.monthly:
+            return not club.monthlyamount_set.filter(amount=self.amount).exists()
+        else:
+            return not club.singleamount_set.filter(amount=self.amount).exists()
+
     def initiate_payment(self, request):
         return self.get_payment_method().initiate(request, self)
 
@@ -192,6 +201,20 @@ class Schedule(models.Model):
     def is_recurring(self):
         return self.monthly or self.yearly
 
+    def n_paypal_payments(self, since, until):
+        # TODO: pull BA payments.
+        t = self.payed_at
+        if t is None: return 0
+        c = 0
+        until = min(until, now())
+        t += timedelta(days=1)
+        while t < until:
+            if t >= since:
+                c += 1
+            m = datetime(t.year, t.month, 1)
+            t += ((m + timedelta(days=31)).replace(day=1)) - m
+        return c
+
     def set_payed(self):
         since = self.expires_at
         n = now()
@@ -291,7 +314,7 @@ class Membership(models.Model):
 
         Contact = apps.get_model('messaging', 'Contact')
         if self.manual:
-            Contact.update(email, Level.MANUAL_MEMBER, datetime.combine(self.updated_at, datetime.min.time(), utc))
+            Contact.update(email, Level.MANUAL_MEMBER, datetime.combine(self.updated_at, datetime.min.time(), timezone.utc))
         else:
             Contact.reset(email)
 
@@ -417,7 +440,8 @@ class PayUOrder(payu_models.Order):
         )            
 
     @classmethod
-    def send_receipt(cls, email, year, resend=False):
+    def generate_receipt(cls, email, year):
+        # TODO: abstract out
         Contact = apps.get_model('messaging', 'Contact')
         Funding = apps.get_model('funding', 'Funding')
         BillingAgreement = apps.get_model('paypal', 'BillingAgreement')
@@ -473,7 +497,7 @@ class PayUOrder(payu_models.Order):
                 booking_date__year=year
         ):
             payments.append({
-                'timestamp': datetime(pa.booking_date.year, pa.booking_date.month, pa.booking_date.day, tzinfo=utc),
+                'timestamp': datetime(pa.booking_date.year, pa.booking_date.month, pa.booking_date.day, tzinfo=timezone.utc),
                 'amount': Decimal(str(pa.debit.amount) + '.00')
             })
 
@@ -485,11 +509,8 @@ class PayUOrder(payu_models.Order):
         ctx = {
             "email": email,
             "year": year,
-            "next_year": year + 1,
             "total": sum(x['amount'] for x in payments),
             "payments": payments,
-            "optout": optout,
-            "resend": resend,
         }
         temp = tempfile.NamedTemporaryFile(prefix='receipt-', suffix='.pdf', delete=False)
         temp.close()
@@ -497,15 +518,34 @@ class PayUOrder(payu_models.Order):
             "wl.eps": os.path.join(settings.STATIC_ROOT, "img/wl.eps"),
             })
 
+        with open(temp.name, 'rb') as f:
+            content = f.read()
+        os.unlink(f.name)
+        return content, optout, payments
+
+    @classmethod
+    def send_receipt(cls, email, year, resend=False):
+        receipt = cls.generate_receipt(email, year)
+        if receipt:
+            content, optout, payments = receipt
+        else:
+            return
+        ctx = {
+            "email": email,
+            "year": year,
+            "next_year": year + 1,
+            "total": sum(x['amount'] for x in payments),
+            "payments": payments,
+            "optout": optout,
+            "resend": resend,
+        }
         message = EmailMessage(
                 'Odlicz darowiznę na Wolne Lektury od podatku',
                 template.loader.render_to_string('club/receipt_email.txt', ctx),
                 settings.CLUB_CONTACT_EMAIL, [email]
             )
-        with open(temp.name, 'rb') as f:
-            message.attach('wolnelektury-darowizny.pdf', f.read(), 'application/pdf')
+        message.attach('wolnelektury-darowizny.pdf', content, 'application/pdf')
         message.send()
-        os.unlink(f.name)
 
 
 class PayUCardToken(payu_models.CardToken):