aca0703835213e6d75ce8d5ff1338bb8a42a62c9
[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, mail_managers
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.OneToOneField(Entry)  # filter publications!
20     price = models.DecimalField(_('price'), decimal_places=2, max_digits=6)
21     cost_const = models.DecimalField(decimal_places=2, max_digits=6)
22     cost_per_item = models.DecimalField(decimal_places=2, max_digits=6, default=0)
23
24     class Meta:
25         verbose_name = _('offer')
26         verbose_name_plural = _('offers')
27         ordering = ['entry']
28
29     def __unicode__(self):
30         return unicode(self.entry)
31
32     def get_absolute_url(self):
33         return self.entry.get_absolute_url()
34
35     def total_per_item(self):
36         return self.price + self.cost_per_item
37
38     def price_per_items(self, items):
39         return self.cost_const + items * self.total_per_item()
40
41
42 class Order(models.Model):
43     """ A person paying for a book.
44
45     The payment was completed if and only if payed_at is set.
46
47     """
48     offer = models.ForeignKey(Offer, verbose_name=_('offer'))
49     items = models.IntegerField(verbose_name=_('items'), default=1)
50     name = models.CharField(_('name'), max_length=127, blank=True)
51     email = models.EmailField(_('email'), db_index=True)
52     address = models.TextField(_('address'), db_index=True)
53     payed_at = models.DateTimeField(_('payed at'), null=True, blank=True, db_index=True)
54     language_code = models.CharField(max_length = 2, null = True, blank = True)
55
56     class Meta:
57         verbose_name = _('order')
58         verbose_name_plural = _('orders')
59         ordering = ['-payed_at']
60
61     def __unicode__(self):
62         return "%s (%d egz.)" % (unicode(self.offer), self.items)
63
64     def get_absolute_url(self):
65         return self.offer.get_absolute_url()
66
67     def amount(self):
68         return self.offer.price_per_items(self.items)
69
70     def notify(self, subject, template_name, extra_context=None):
71         context = {
72             'order': self,
73             'site': Site.objects.get_current(),
74         }
75         if extra_context:
76             context.update(extra_context)
77         with override(self.language_code or app_settings.DEFAULT_LANGUAGE):
78             send_mail(subject,
79                 render_to_string(template_name, context),
80                 getattr(settings, 'CONTACT_EMAIL', 'prawokultury@nowoczesnapolska.org.pl'),
81                 [self.email],
82                 fail_silently=False
83             )
84
85     def notify_managers(self, subject, template_name, extra_context=None):
86         context = {
87             'order': self,
88             'site': Site.objects.get_current(),
89         }
90         if extra_context:
91             context.update(extra_context)
92         with override(app_settings.DEFAULT_LANGUAGE):
93             mail_managers(subject, render_to_string(template_name, context))
94
95 # Register the Order model with django-getpaid for payments.
96 getpaid.register_to_payment(Order, unique=False, related_name='payment')
97
98
99 def new_payment_query_listener(sender, order=None, payment=None, **kwargs):
100     """ Set payment details for getpaid. """
101     payment.amount = order.amount()
102     payment.currency = 'PLN'
103 getpaid.signals.new_payment_query.connect(new_payment_query_listener)
104
105
106 def user_data_query_listener(sender, order, user_data, **kwargs):
107     """ Set user data for payment. """
108     user_data['email'] = order.email
109 getpaid.signals.user_data_query.connect(user_data_query_listener)
110
111 def payment_status_changed_listener(sender, instance, old_status, new_status, **kwargs):
112     """ React to status changes from getpaid. """
113     if old_status != 'paid' and new_status == 'paid':
114         instance.order.payed_at = datetime.now()
115         instance.order.save()
116         instance.order.notify(
117             _('Your payment has been completed.'),
118             'shop/email/payed.txt'
119         )
120         instance.order.notify_managers(
121             _('New order has been placed.'),
122             'shop/email/payed_managers.txt'
123         )
124 getpaid.signals.payment_status_changed.connect(payment_status_changed_listener, dispatch_uid='shop.models.payment_status_changed_listener')