Fundraising in PDF.
[wolnelektury.git] / src / club / payu / models.py
1 # This file is part of Wolne Lektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Wolne Lektury. 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 . import POSS
12
13
14 class CardToken(models.Model):
15     """ This should be attached to a payment schedule. """
16     pos_id = models.CharField('POS id', max_length=255)
17     disposable_token = models.CharField('token jednorazowy', max_length=255)
18     reusable_token = models.CharField('token wielokrotnego użytku', max_length=255, null=True, blank=True)
19     created_at = models.DateTimeField('utworzony', auto_now_add=True)
20
21     class Meta:
22         abstract = True
23         verbose_name = 'token PayU karty płatniczej'
24         verbose_name_plural = 'tokeny PayU kart płatniczych'
25
26
27 class Order(models.Model):
28     pos_id = models.CharField('POS id', max_length=255, blank=True)   # TODO: redundant?
29     customer_ip = models.GenericIPAddressField('adres IP klienta')
30     order_id = models.CharField('ID zamówienia', max_length=255, blank=True)
31
32     status = models.CharField(max_length=128, blank=True, choices=[
33         ('PENDING', 'Czeka'),
34         ('WAITING_FOR_CONFIRMATION', 'Czeka na potwierdzenie'),
35         ('COMPLETED', 'Ukończone'),
36         ('CANCELED', 'Anulowane'),
37         ('REJECTED', 'Odrzucone'),
38
39         ('ERR-INVALID_TOKEN', 'Błędny token'),
40     ])
41     created_at = models.DateTimeField(null=True, blank=True, auto_now_add=True)
42     completed_at = models.DateTimeField(null=True, blank=True)
43
44     class Meta:
45         abstract = True
46         verbose_name = 'Zamówienie PayU'
47         verbose_name_plural = 'Zamówienia PayU'
48
49     # These need to be provided in a subclass.
50
51     def get_amount(self):
52         raise NotImplementedError()
53
54     def get_buyer(self):
55         raise NotImplementedError()
56
57     def get_continue_url(self):
58         raise NotImplementedError()
59     
60     def get_description(self):
61         raise NotImplementedError()
62
63     def get_products(self):
64         """ At least: name, unitPrice, quantity. """
65         return [
66             {
67                 'name': self.get_description(),
68                 'unitPrice': str(int(self.get_amount() * 100)),
69                 'quantity': '1',
70             },
71         ]
72
73     def is_recurring(self):
74         return False
75
76     def get_notify_url(self):
77         raise NotImplementedError
78
79     def get_thanks_url(self):
80         raise NotImplementedError
81
82     def status_updated(self):
83         pass
84
85     # 
86     
87     def get_pos(self):
88         return POSS[self.pos_id]
89
90     def get_continue_url(self):
91         return "https://{}{}".format(
92             Site.objects.get_current().domain,
93             self.get_thanks_url())
94
95     def get_representation(self, token=None):
96         rep = {
97             "notifyUrl": self.get_notify_url(),
98             "customerIp": self.customer_ip,
99             "merchantPosId": self.pos_id,
100             "currencyCode": self.get_pos().currency_code,
101             "totalAmount": str(int(self.get_amount() * 100)),
102             "extOrderId": "wolne-lektury-%d" % self.pk,
103
104             "buyer": self.get_buyer() or {},
105             "continueUrl": self.get_continue_url(),
106             "description": self.get_description(),
107             "products": self.get_products(),
108         }
109         if token:
110             token = self.get_card_token()
111             rep['recurring'] = 'STANDARD' if token.reusable_token else 'FIRST'
112             rep['payMethods'] = {
113                 "payMethod": {
114                     "type": "CARD_TOKEN",
115                     "value": token.reusable_token or token.disposable_token
116                 }
117             }
118         return rep
119
120     def put(self):
121         token = self.get_card_token() if self.is_recurring() else None
122         representation = self.get_representation(token)
123         try:
124             response = self.get_pos().request('POST', 'orders', representation)
125         except HTTPError as e:
126             resp = json.loads(e.read().decode('utf-8'))
127             if resp['status']['statusCode'] == 'ERROR_ORDER_NOT_UNIQUE':
128                 pass
129             else:
130                 raise
131
132         if token:
133             reusable_token = response.get('payMethods', {}).get('payMethod', {}).get('value', None)
134             if reusable_token:
135                 token.reusable_token = reusable_token
136                 token.save()
137             # else?
138
139         if 'orderId' not in response:
140             code = response.get('status', {}).get('codeLiteral', '')
141             if code:
142                 self.status = 'ERR-' + str(code)
143                 self.save()
144                 self.status_updated()
145             else:
146                 raise ValueError("Expecting dict with `orderId` key, got: %s" % response)
147         else:
148             self.order_id = response['orderId']
149             self.save()
150
151         return response.get('redirectUri', self.get_thanks_url())
152
153
154 class Notification(models.Model):
155     """ Add `order` FK to real Order model. """
156     body = models.TextField('treść')
157     received_at = models.DateTimeField('odebrana', auto_now_add=True)
158
159     class Meta:
160         abstract = True
161         verbose_name = 'notyfikacja PayU'
162         verbose_name_plural = 'notyfikacje PayU'
163
164     def get_status(self):
165         return json.loads(self.body)['order']['status']
166
167     def apply(self):
168         status = self.get_status()
169         if self.order.status not in (status, 'COMPLETED'):
170             self.order.status = status
171             if status == 'COMPLETED':
172                 self.order.completed_at = now()
173             self.order.save()
174             self.order.status_updated()