Style fix
[wolnelektury.git] / src / club / payu / models.py
index 1a49dd7..10dd60a 100644 (file)
@@ -7,6 +7,7 @@ from urllib.request import HTTPError
 from django.contrib.sites.models import Site
 from django.db import models
 from django.urls import reverse
+from django.utils.timezone import now
 from django.utils.translation import ugettext_lazy as _
 from . import POSS
 
@@ -35,7 +36,11 @@ class Order(models.Model):
         ('COMPLETED', _('Completed')),
         ('CANCELED', _('Canceled')),
         ('REJECTED', _('Rejected')),
+
+        ('ERR-INVALID_TOKEN', _('Invalid token')),
     ])
+    created_at = models.DateTimeField(null=True, blank=True, auto_now_add=True)
+    completed_at = models.DateTimeField(null=True, blank=True)
 
     class Meta:
         abstract = True
@@ -87,7 +92,7 @@ class Order(models.Model):
             "merchantPosId": self.pos_id,
             "currencyCode": self.get_pos().currency_code,
             "totalAmount": str(int(self.get_amount() * 100)),
-            "extOrderId": "wolne-lektury-rcz-%d" % self.pk,
+            "extOrderId": "wolne-lektury-%d" % self.pk,
 
             "buyer": self.get_buyer() or {},
             "continueUrl": self.get_continue_url(),
@@ -124,10 +129,18 @@ class Order(models.Model):
                 token.save()
             # else?
 
-        self.order_id = response['orderId']
-        self.save()
+        if 'orderId' not in response:
+            code = response.get('status', {}).get('codeLiteral', '')
+            if code:
+                self.status = 'ERR-' + str(code)
+                self.save()
+                self.status_updated()
+            else:
+                raise ValueError("Expecting dict with `orderId` key, got: %s" % response)
+        else:
+            self.order_id = response['orderId']
+            self.save()
 
-        
         return response.get('redirectUri', self.schedule.get_thanks_url())
 
 
@@ -148,5 +161,7 @@ class Notification(models.Model):
         status = self.get_status()
         if self.order.status not in (status, 'COMPLETED'):
             self.order.status = status
+            if status == 'COMPLETED':
+                self.order.completed_at = now()
             self.order.save()
             self.order.status_updated()