Fix for expired tokens.
[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         ('ERR-INVALID_TOKEN', _('Invalid token')),
41     ])
42     created_at = models.DateTimeField(null=True, blank=True, auto_now_add=True)
43     completed_at = models.DateTimeField(null=True, blank=True)
44
45     class Meta:
46         abstract = True
47         verbose_name = _('PayU order')
48         verbose_name_plural = _('PayU orders')
49
50     # These need to be provided in a subclass.
51
52     def get_amount(self):
53         raise NotImplementedError()
54
55     def get_buyer(self):
56         raise NotImplementedError()
57
58     def get_continue_url(self):
59         raise NotImplementedError()
60     
61     def get_description(self):
62         raise NotImplementedError()
63
64     def get_products(self):
65         """ At least: name, unitPrice, quantity. """
66         return [
67             {
68                 'name': self.get_description(),
69                 'unitPrice': str(int(self.get_amount() * 100)),
70                 'quantity': '1',
71             },
72         ]
73
74     def is_recurring(self):
75         return False
76
77     def get_notify_url(self):
78         raise NotImplementedError
79
80     def status_updated(self):
81         pass
82
83     # 
84     
85     def get_pos(self):
86         return POSS[self.pos_id]
87
88     def get_representation(self, token=None):
89         rep = {
90             "notifyUrl": self.get_notify_url(),
91             "customerIp": self.customer_ip,
92             "merchantPosId": self.pos_id,
93             "currencyCode": self.get_pos().currency_code,
94             "totalAmount": str(int(self.get_amount() * 100)),
95             "extOrderId": "wolne-lektury-%d" % self.pk,
96
97             "buyer": self.get_buyer() or {},
98             "continueUrl": self.get_continue_url(),
99             "description": self.get_description(),
100             "products": self.get_products(),
101         }
102         if token:
103             token = self.get_card_token()
104             rep['recurring'] = 'STANDARD' if token.reusable_token else 'FIRST'
105             rep['payMethods'] = {
106                 "payMethod": {
107                     "type": "CARD_TOKEN",
108                     "value": token.reusable_token or token.disposable_token
109                 }
110             }
111         return rep
112
113     def put(self):
114         token = self.get_card_token() if self.is_recurring() else None
115         representation = self.get_representation(token)
116         try:
117             response = self.get_pos().request('POST', 'orders', representation)
118         except HTTPError as e:
119             resp = json.loads(e.read().decode('utf-8'))
120             if resp['status']['statusCode'] == 'ERROR_ORDER_NOT_UNIQUE':
121                 pass
122             else:
123                 raise
124
125         if token:
126             reusable_token = response.get('payMethods', {}).get('payMethod', {}).get('value', None)
127             if reusable_token:
128                 token.reusable_token = reusable_token
129                 token.save()
130             # else?
131
132         if 'orderId' not in response:
133             code = response.get('status', {}).get('codeLiteral', '')
134             if code:
135                 self.status = 'ERR-' + str(code)
136                 self.save()
137                 self.status_updated()
138             else:
139                 raise ValueError("Expecting dict with `orderId` key, got: %s" % response)
140         else:
141             self.order_id = response['orderId']
142             self.save()
143
144         return response.get('redirectUri', self.schedule.get_thanks_url())
145
146
147 class Notification(models.Model):
148     """ Add `order` FK to real Order model. """
149     body = models.TextField(_('body'))
150     received_at = models.DateTimeField(_('received_at'), auto_now_add=True)
151
152     class Meta:
153         abstract = True
154         verbose_name = _('PayU notification')
155         verbose_name_plural = _('PayU notifications')
156
157     def get_status(self):
158         return json.loads(self.body)['order']['status']
159
160     def apply(self):
161         status = self.get_status()
162         if self.order.status not in (status, 'COMPLETED'):
163             self.order.status = status
164             if status == 'COMPLETED':
165                 self.order.completed_at = now()
166             self.order.save()
167             self.order.status_updated()