2 from urllib.parse import urlencode
3 from urllib.request import HTTPError
4 from django.contrib.sites.models import Site
5 from django.db import models
6 from django.urls import reverse
10 class CardToken(models.Model):
11 """ This should be attached to a payment schedule. """
12 pos_id = models.CharField(max_length=255)
13 disposable_token = models.CharField(max_length=255)
14 reusable_token = models.CharField(max_length=255, null=True, blank=True)
15 created_at = models.DateTimeField(auto_now_add=True)
21 class Order(models.Model):
22 pos_id = models.CharField(max_length=255) # TODO: redundant?
23 customer_ip = models.GenericIPAddressField()
24 order_id = models.CharField(max_length=255, blank=True)
26 status = models.CharField(max_length=128, blank=True, choices=[
27 ('PENDING', 'Pending'),
28 ('WAITING_FOR_CONFIRMATION', 'Waiting for confirmation'),
29 ('COMPLETED', 'Completed'),
30 ('CANCELED', 'Canceled'),
31 ('REJECTED', 'Rejected'),
37 # These need to be provided in a subclass.
40 raise NotImplementedError()
43 raise NotImplementedError()
45 def get_continue_url(self):
46 raise NotImplementedError()
48 def get_description(self):
49 raise NotImplementedError()
51 def get_products(self):
52 """ At least: name, unitPrice, quantity. """
55 'name': self.get_description(),
56 'unitPrice': str(int(self.get_amount() * 100)),
61 def is_recurring(self):
64 def get_notify_url(self):
65 raise NotImplementedError
67 def status_updated(self):
73 return POSS[self.pos_id]
75 def get_representation(self, token=None):
77 "notifyUrl": self.get_notify_url(),
78 "customerIp": self.customer_ip,
79 "merchantPosId": self.pos_id,
80 "currencyCode": self.get_pos().currency_code,
81 "totalAmount": str(int(self.get_amount() * 100)),
82 "extOrderId": "wolne-lektury-rcz-%d" % self.pk,
84 "buyer": self.get_buyer() or {},
85 "continueUrl": self.get_continue_url(),
86 "description": self.get_description(),
87 "products": self.get_products(),
90 token = self.get_card_token()
91 rep['recurring'] = 'STANDARD' if token.reusable_token else 'FIRST'
95 "value": token.reusable_token or token.disposable_token
101 token = self.get_card_token() if self.is_recurring() else None
102 representation = self.get_representation(token)
104 response = self.get_pos().request('POST', 'orders', representation)
105 except HTTPError as e:
106 resp = json.loads(e.read().decode('utf-8'))
107 if resp['status']['statusCode'] == 'ERROR_ORDER_NOT_UNIQUE':
113 reusable_token = response.get('payMethods', {}).get('payMethod', {}).get('value', None)
115 token.reusable_token = reusable_token
119 self.order_id = response['orderId']
123 return response.get('redirectUri', self.schedule.get_absolute_url())
126 class Notification(models.Model):
127 """ Add `order` FK to real Order model. """
128 body = models.TextField()
129 received_at = models.DateTimeField(auto_now_add=True)
134 def get_status(self):
135 return json.loads(self.body)['order']['status']
138 status = self.get_status()
139 if self.order.status not in (status, 'COMPLETED'):
140 self.order.status = status
142 self.order.status_updated()