# Path: payments/forms.py
# class NewPaymentForm(forms.Form):
#     TIME_CHOICES = (
#         ('1', '1'),
#         ('3', '3'),
#         ('6', '6'),
#         ('12', '12'),
#     )
# 
#     subscr = forms.ChoiceField(choices=(('0', 'no'), ('1', 'yes')))
#     time = forms.ChoiceField(choices=TIME_CHOICES)
#     method = forms.ChoiceField(choices=BACKEND_CHOICES)
# 
# Path: payments/models.py
# class Payment(models.Model):
#     """ Just a payment.
#     If subscription is not null, it has been automatically issued.
#     backend_extid is the external transaction ID, backend_data is other
#     things that should only be used by the associated backend.
#     """
#     user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
#     backend_id = models.CharField(max_length=16, choices=BACKEND_CHOICES)
#     status = models.CharField(max_length=16, choices=STATUS_CHOICES, default='new')
#     created = models.DateTimeField(auto_now_add=True)
#     modified = models.DateTimeField(auto_now=True)
#     confirmed_on = models.DateTimeField(null=True, blank=True)
#     amount = models.IntegerField()
#     paid_amount = models.IntegerField(default=0)
#     time = models.DurationField()
#     subscription = models.ForeignKey('Subscription', null=True, blank=True)
#     status_message = models.TextField(blank=True, null=True)
# 
#     backend_extid = models.CharField(max_length=64, null=True, blank=True)
#     backend_data = JSONField(blank=True)
# 
#     @property
#     def currency_code(self):
#         return CURRENCY_CODE
# 
#     @property
#     def currency_name(self):
#         return CURRENCY_NAME
# 
#     @property
#     def backend(self):
#         """ Returns a global instance of the backend
#         :rtype: BackendBase
#         """
#         return BACKENDS[self.backend_id]
# 
#     def get_amount_display(self):
#         return '%.2f %s' % (self.amount / 100, CURRENCY_NAME)
# 
#     @property
#     def is_confirmed(self):
#         return self.status == 'confirmed'
# 
#     class Meta:
#         ordering = ('-created', )
# 
#     @classmethod
#     def create_payment(self, backend_id, user, months):
#         payment = Payment(
#             user=user,
#             backend_id=backend_id,
#             status='new',
#             time=timedelta(days=30 * months),
#             amount=get_price() * months
#         )
#         return payment
# 
# class Subscription(models.Model):
#     """ Recurring payment subscription. """
#     user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
#     backend_id = models.CharField(max_length=16, choices=BACKEND_CHOICES)
#     created = models.DateTimeField(auto_now_add=True)
#     period = models.CharField(max_length=16, choices=SUBSCR_PERIOD_CHOICES)
#     last_confirmed_payment = models.DateTimeField(blank=True, null=True)
#     status = models.CharField(max_length=16, choices=SUBSCR_STATUS_CHOICES, default='new')
# 
#     backend_extid = models.CharField(max_length=64, null=True, blank=True)
#     backend_data = JSONField(blank=True)
# 
#     @property
#     def backend(self):
#         """ Returns a global instance of the backend
#         :rtype: BackendBase
#         """
#         return BACKENDS[self.backend_id]
# 
#     @property
#     def months(self):
#         return period_months(self.period)
# 
#     @property
#     def period_amount(self):
#         return self.months * get_price()
# 
#     @property
#     def next_renew(self):
#         """ Approximate date of the next payment """
#         if self.last_confirmed_payment:
#             return self.last_confirmed_payment + timedelta(days=self.months * 30)
#         return self.created + timedelta(days=self.months * 30)
# 
#     @property
#     def monthly_amount(self):
#         return get_price()
# 
#     def create_payment(self):
#         payment = Payment(
#             user=self.user,
#             backend_id=self.backend_id,
#             status='new',
#             time=timedelta(days=30 * self.months),
#             amount=get_price() * self.months,
#             subscription=self,
#         )
#         return payment
# 
# BACKENDS = {}
# 
# ACTIVE_BACKENDS = {}


from datetime import timedelta
from django.shortcuts import render, redirect
from django.core.urlresolvers import reverse
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseNotFound
from django.views.decorators.csrf import csrf_exempt
from django.utils import timezone
from django.contrib import messages
from django.utils.translation import ugettext_lazy as _
from .forms import NewPaymentForm
from .models import Payment, Subscription, BACKENDS, ACTIVE_BACKENDS
            user=request.user,
            backend_id=backend_id,
            period=str(months) + 'm',
        )
        rps.save()

        r = rps.backend.new_subscription(rps)

    else:
        payment = Payment.create_payment(backend_id, request.user, months)
        payment.save()

        r = payment.backend.new_payment(payment)

    if not r:
        payment.status = 'error'
        payment.save()
        raise Exception("Failed to initialize payment #%d" % payment.id)

    if isinstance(r, str):
        return render(request, 'payments/form.html', dict(html=r))
    elif r is None:
        return redirect('payments:view', payment.id)

    return r


@csrf_exempt
def callback_paypal(request, id):
    """ PayPal IPN """

# Path: payments/forms.py
# class NewPaymentForm(forms.Form):
#     TIME_CHOICES = (
#         ('1', '1'),
#         ('3', '3'),
#         ('6', '6'),
#         ('12', '12'),
#     )
# 
#     subscr = forms.ChoiceField(choices=(('0', 'no'), ('1', 'yes')))
#     time = forms.ChoiceField(choices=TIME_CHOICES)
#     method = forms.ChoiceField(choices=BACKEND_CHOICES)
# 
# Path: payments/models.py
# class Payment(models.Model):
#     """ Just a payment.
#     If subscription is not null, it has been automatically issued.
#     backend_extid is the external transaction ID, backend_data is other
#     things that should only be used by the associated backend.
#     """
#     user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
#     backend_id = models.CharField(max_length=16, choices=BACKEND_CHOICES)
#     status = models.CharField(max_length=16, choices=STATUS_CHOICES, default='new')
#     created = models.DateTimeField(auto_now_add=True)
#     modified = models.DateTimeField(auto_now=True)
#     confirmed_on = models.DateTimeField(null=True, blank=True)
#     amount = models.IntegerField()
#     paid_amount = models.IntegerField(default=0)
#     time = models.DurationField()
#     subscription = models.ForeignKey('Subscription', null=True, blank=True)
#     status_message = models.TextField(blank=True, null=True)
# 
#     backend_extid = models.CharField(max_length=64, null=True, blank=True)
#     backend_data = JSONField(blank=True)
# 
#     @property
#     def currency_code(self):
#         return CURRENCY_CODE
# 
#     @property
#     def currency_name(self):
#         return CURRENCY_NAME
# 
#     @property
#     def backend(self):
#         """ Returns a global instance of the backend
#         :rtype: BackendBase
#         """
#         return BACKENDS[self.backend_id]
# 
#     def get_amount_display(self):
#         return '%.2f %s' % (self.amount / 100, CURRENCY_NAME)
# 
#     @property
#     def is_confirmed(self):
#         return self.status == 'confirmed'
# 
#     class Meta:
#         ordering = ('-created', )
# 
#     @classmethod
#     def create_payment(self, backend_id, user, months):
#         payment = Payment(
#             user=user,
#             backend_id=backend_id,
#             status='new',
#             time=timedelta(days=30 * months),
#             amount=get_price() * months
#         )
#         return payment
# 
# class Subscription(models.Model):
#     """ Recurring payment subscription. """
#     user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
#     backend_id = models.CharField(max_length=16, choices=BACKEND_CHOICES)
#     created = models.DateTimeField(auto_now_add=True)
#     period = models.CharField(max_length=16, choices=SUBSCR_PERIOD_CHOICES)
#     last_confirmed_payment = models.DateTimeField(blank=True, null=True)
#     status = models.CharField(max_length=16, choices=SUBSCR_STATUS_CHOICES, default='new')
# 
#     backend_extid = models.CharField(max_length=64, null=True, blank=True)
#     backend_data = JSONField(blank=True)
# 
#     @property
#     def backend(self):
#         """ Returns a global instance of the backend
#         :rtype: BackendBase
#         """
#         return BACKENDS[self.backend_id]
# 
#     @property
#     def months(self):
#         return period_months(self.period)
# 
#     @property
#     def period_amount(self):
#         return self.months * get_price()
# 
#     @property
#     def next_renew(self):
#         """ Approximate date of the next payment """
#         if self.last_confirmed_payment:
#             return self.last_confirmed_payment + timedelta(days=self.months * 30)
#         return self.created + timedelta(days=self.months * 30)
# 
#     @property
#     def monthly_amount(self):
#         return get_price()
# 
#     def create_payment(self):
#         payment = Payment(
#             user=self.user,
#             backend_id=self.backend_id,
#             status='new',
#             time=timedelta(days=30 * self.months),
#             amount=get_price() * self.months,
#             subscription=self,
#         )
#         return payment
# 
# BACKENDS = {}
# 
# ACTIVE_BACKENDS = {}


# Path: payments/views.py
from datetime import timedelta
from django.shortcuts import render, redirect
from django.core.urlresolvers import reverse
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseNotFound
from django.views.decorators.csrf import csrf_exempt
from django.utils import timezone
from django.contrib import messages
from django.utils.translation import ugettext_lazy as _
from .forms import NewPaymentForm
from .models import Payment, Subscription, BACKENDS, ACTIVE_BACKENDS

            user=request.user,
            backend_id=backend_id,
            period=str(months) + 'm',
        )
        rps.save()

        r = rps.backend.new_subscription(rps)

    else:
        payment = Payment.create_payment(backend_id, request.user, months)
        payment.save()

        r = payment.backend.new_payment(payment)

    if not r:
        payment.status = 'error'
        payment.save()
        raise Exception("Failed to initialize payment #%d" % payment.id)

    if isinstance(r, str):
        return render(request, 'payments/form.html', dict(html=r))
    elif r is None:
        return redirect('payments:view', payment.id)

    return r


@csrf_exempt
def callback_paypal(request, id):
    """ PayPal IPN """

    if not BACKENDS['paypal'].backend_enabled: