72d599c82533d0f841e9e25204db464d1a77c8c4
[prawokultury.git] / shop / models.py
1 # -*- coding: utf-8 -*-
2 # This file is part of PrawoKultury, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 #
5 from datetime import datetime
6 from django.core.mail import send_mail
7 from django.conf import settings
8 from django.contrib.sites.models import Site
9 from django.db import models
10 from django.template.loader import render_to_string
11 from django.utils.translation import ugettext_lazy as _, override
12 import getpaid
13 from migdal.models import Entry
14 from . import app_settings
15
16
17 class Offer(models.Model):
18     """ A fundraiser for a particular book. """
19     entry = models.ForeignKey(Entry)  # filter publications!
20     price = models.DecimalField(_('price'), decimal_places=2, max_digits=6)
21
22     class Meta:
23         verbose_name = _('offer')
24         verbose_name_plural = _('offers')
25         ordering = ['entry']
26
27     def __unicode__(self):
28         return self.entry.title
29
30     def get_absolute_url(self):
31         return self.entry.get_absolute_url()
32
33     def sum(self):
34         """ The money gathered. """
35         return self.order_payed().aggregate(s=models.Sum('amount'))['s'] or 0
36
37
38 class Order(models.Model):
39     """ A person paying for a book.
40
41     The payment was completed if and only if payed_at is set.
42
43     """
44     offer = models.ForeignKey(Offer, verbose_name=_('offer'))
45     name = models.CharField(_('name'), max_length=127, blank=True)
46     email = models.EmailField(_('email'), db_index=True)
47     address = models.TextField(_('address'), db_index=True)
48     payed_at = models.DateTimeField(_('payed at'), null=True, blank=True, db_index=True)
49     language_code = models.CharField(max_length = 2, null = True, blank = True)
50
51     class Meta:
52         verbose_name = _('order')
53         verbose_name_plural = _('orders')
54         ordering = ['-payed_at']
55
56     def __unicode__(self):
57         return unicode(self.offer)
58
59     def get_absolute_url(self):
60         return self.offer.get_absolute_url()
61
62     def notify(self, subject, template_name, extra_context=None):
63         context = {
64             'order': self,
65             'site': Site.objects.get_current(),
66         }
67         if extra_context:
68             context.update(extra_context)
69         with override(self.language_code or app_settings.DEFAULT_LANGUAGE):
70             send_mail(subject,
71                 render_to_string(template_name, context),
72                 getattr(settings, 'CONTACT_EMAIL', 'prawokultury@nowoczesnapolska.org.pl'),
73                 [self.email],
74                 fail_silently=False
75             )
76
77 # Register the Order model with django-getpaid for payments.
78 getpaid.register_to_payment(Order, unique=False, related_name='payment')
79
80
81 def new_payment_query_listener(sender, order=None, payment=None, **kwargs):
82     """ Set payment details for getpaid. """
83     payment.amount = order.offer.price
84     payment.currency = 'PLN'
85 getpaid.signals.new_payment_query.connect(new_payment_query_listener)
86
87
88 def user_data_query_listener(sender, order, user_data, **kwargs):
89     """ Set user data for payment. """
90     user_data['email'] = order.email
91 getpaid.signals.user_data_query.connect(user_data_query_listener)
92
93 def payment_status_changed_listener(sender, instance, old_status, new_status, **kwargs):
94     """ React to status changes from getpaid. """
95     if old_status != 'paid' and new_status == 'paid':
96         instance.order.payed_at = datetime.now()
97         instance.order.save()
98         instance.order.notify(
99             _('Your payment has been completed.'),
100             'shop/email/payed.txt'
101         )
102 getpaid.signals.payment_status_changed.connect(payment_status_changed_listener)