1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
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
13 class CardToken(models.Model):
14 """ This should be attached to a payment schedule. """
15 pos_id = models.CharField(max_length=255)
16 disposable_token = models.CharField(max_length=255)
17 reusable_token = models.CharField(max_length=255, null=True, blank=True)
18 created_at = models.DateTimeField(auto_now_add=True)
24 class Order(models.Model):
25 pos_id = models.CharField(max_length=255) # TODO: redundant?
26 customer_ip = models.GenericIPAddressField()
27 order_id = models.CharField(max_length=255, blank=True)
29 status = models.CharField(max_length=128, blank=True, choices=[
30 ('PENDING', 'Pending'),
31 ('WAITING_FOR_CONFIRMATION', 'Waiting for confirmation'),
32 ('COMPLETED', 'Completed'),
33 ('CANCELED', 'Canceled'),
34 ('REJECTED', 'Rejected'),
40 # These need to be provided in a subclass.
43 raise NotImplementedError()
46 raise NotImplementedError()
48 def get_continue_url(self):
49 raise NotImplementedError()
51 def get_description(self):
52 raise NotImplementedError()
54 def get_products(self):
55 """ At least: name, unitPrice, quantity. """
58 'name': self.get_description(),
59 'unitPrice': str(int(self.get_amount() * 100)),
64 def is_recurring(self):
67 def get_notify_url(self):
68 raise NotImplementedError
70 def status_updated(self):
76 return POSS[self.pos_id]
78 def get_representation(self, token=None):
80 "notifyUrl": self.get_notify_url(),
81 "customerIp": self.customer_ip,
82 "merchantPosId": self.pos_id,
83 "currencyCode": self.get_pos().currency_code,
84 "totalAmount": str(int(self.get_amount() * 100)),
85 "extOrderId": "wolne-lektury-rcz-%d" % self.pk,
87 "buyer": self.get_buyer() or {},
88 "continueUrl": self.get_continue_url(),
89 "description": self.get_description(),
90 "products": self.get_products(),
93 token = self.get_card_token()
94 rep['recurring'] = 'STANDARD' if token.reusable_token else 'FIRST'
98 "value": token.reusable_token or token.disposable_token
104 token = self.get_card_token() if self.is_recurring() else None
105 representation = self.get_representation(token)
107 response = self.get_pos().request('POST', 'orders', representation)
108 except HTTPError as e:
109 resp = json.loads(e.read().decode('utf-8'))
110 if resp['status']['statusCode'] == 'ERROR_ORDER_NOT_UNIQUE':
116 reusable_token = response.get('payMethods', {}).get('payMethod', {}).get('value', None)
118 token.reusable_token = reusable_token
122 self.order_id = response['orderId']
126 return response.get('redirectUri', self.schedule.get_thanks_url())
129 class Notification(models.Model):
130 """ Add `order` FK to real Order model. """
131 body = models.TextField()
132 received_at = models.DateTimeField(auto_now_add=True)
137 def get_status(self):
138 return json.loads(self.body)['order']['status']
141 status = self.get_status()
142 if self.order.status not in (status, 'COMPLETED'):
143 self.order.status = status
145 self.order.status_updated()