Club renewal procedure fixes.
[wolnelektury.git] / src / club / payu / models.py
1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
3 #
4 import json
5 from urllib.parse import urlencode
6 from urllib.request import HTTPError
7 from django.contrib.sites.models import Site
8 from django.db import models
9 from django.urls import reverse
10 from django.utils.timezone import now
11 from django.utils.translation import ugettext_lazy as _
12 from . import POSS
13
14
15 class CardToken(models.Model):
16     """ This should be attached to a payment schedule. """
17     pos_id = models.CharField(_('POS id'), max_length=255)
18     disposable_token = models.CharField(_('disposable token'), max_length=255)
19     reusable_token = models.CharField(_('reusable token'), max_length=255, null=True, blank=True)
20     created_at = models.DateTimeField(_('created_at'), auto_now_add=True)
21
22     class Meta:
23         abstract = True
24         verbose_name = _('PayU card token')
25         verbose_name_plural = _('PayU card tokens')
26
27
28 class Order(models.Model):
29     pos_id = models.CharField(_('POS id'), max_length=255)   # TODO: redundant?
30     customer_ip = models.GenericIPAddressField(_('customer IP'))
31     order_id = models.CharField(_('order ID'), max_length=255, blank=True)
32
33     status = models.CharField(max_length=128, blank=True, choices=[
34         ('PENDING', _('Pending')),
35         ('WAITING_FOR_CONFIRMATION', _('Waiting for confirmation')),
36         ('COMPLETED', _('Completed')),
37         ('CANCELED', _('Canceled')),
38         ('REJECTED', _('Rejected')),
39     ])
40     completed_at = models.DateTimeField(null=True, blank=True)
41
42     class Meta:
43         abstract = True
44         verbose_name = _('PayU order')
45         verbose_name_plural = _('PayU orders')
46
47     # These need to be provided in a subclass.
48
49     def get_amount(self):
50         raise NotImplementedError()
51
52     def get_buyer(self):
53         raise NotImplementedError()
54
55     def get_continue_url(self):
56         raise NotImplementedError()
57     
58     def get_description(self):
59         raise NotImplementedError()
60
61     def get_products(self):
62         """ At least: name, unitPrice, quantity. """
63         return [
64             {
65                 'name': self.get_description(),
66                 'unitPrice': str(int(self.get_amount() * 100)),
67                 'quantity': '1',
68             },
69         ]
70
71     def is_recurring(self):
72         return False
73
74     def get_notify_url(self):
75         raise NotImplementedError
76
77     def status_updated(self):
78         pass
79
80     # 
81     
82     def get_pos(self):
83         return POSS[self.pos_id]
84
85     def get_representation(self, token=None):
86         rep = {
87             "notifyUrl": self.get_notify_url(),
88             "customerIp": self.customer_ip,
89             "merchantPosId": self.pos_id,
90             "currencyCode": self.get_pos().currency_code,
91             "totalAmount": str(int(self.get_amount() * 100)),
92             "extOrderId": "wolne-lektury-%d" % self.pk,
93
94             "buyer": self.get_buyer() or {},
95             "continueUrl": self.get_continue_url(),
96             "description": self.get_description(),
97             "products": self.get_products(),
98         }
99         if token:
100             token = self.get_card_token()
101             rep['recurring'] = 'STANDARD' if token.reusable_token else 'FIRST'
102             rep['payMethods'] = {
103                 "payMethod": {
104                     "type": "CARD_TOKEN",
105                     "value": token.reusable_token or token.disposable_token
106                 }
107             }
108         return rep
109
110     def put(self):
111         token = self.get_card_token() if self.is_recurring() else None
112         representation = self.get_representation(token)
113         try:
114             response = self.get_pos().request('POST', 'orders', representation)
115         except HTTPError as e:
116             resp = json.loads(e.read().decode('utf-8'))
117             if resp['status']['statusCode'] == 'ERROR_ORDER_NOT_UNIQUE':
118                 pass
119             else:
120                 raise
121
122         if token:
123             reusable_token = response.get('payMethods', {}).get('payMethod', {}).get('value', None)
124             if reusable_token:
125                 token.reusable_token = reusable_token
126                 token.save()
127             # else?
128
129         if 'orderId' not in response:
130             raise ValueError("Expecting dict with `orderId` key, got: %s" % response)
131         self.order_id = response['orderId']
132         self.save()
133
134         
135         return response.get('redirectUri', self.schedule.get_thanks_url())
136
137
138 class Notification(models.Model):
139     """ Add `order` FK to real Order model. """
140     body = models.TextField(_('body'))
141     received_at = models.DateTimeField(_('received_at'), auto_now_add=True)
142
143     class Meta:
144         abstract = True
145         verbose_name = _('PayU notification')
146         verbose_name_plural = _('PayU notifications')
147
148     def get_status(self):
149         return json.loads(self.body)['order']['status']
150
151     def apply(self):
152         status = self.get_status()
153         if self.order.status not in (status, 'COMPLETED'):
154             self.order.status = status
155             if status == 'COMPLETED':
156                 self.order.completed_at = now()
157             self.order.save()
158             self.order.status_updated()