You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

199 lines
6.3 KiB

9 years ago
9 years ago
  1. from django.conf import settings
  2. from django.contrib.auth.models import User
  3. from django.db import models
  4. from django.template.loader import render_to_string
  5. if settings.USE_PAYMENTS:
  6. import braintree
  7. else:
  8. # hc.payments tests mock this object, so tests should
  9. # still be able to run:
  10. braintree = None
  11. ADDRESS_KEYS = ("first_name", "last_name", "company", "street_address",
  12. "extended_address", "locality", "region", "postal_code",
  13. "country_code_alpha2")
  14. class SubscriptionManager(models.Manager):
  15. def for_user(self, user):
  16. sub, created = Subscription.objects.get_or_create(user_id=user.id)
  17. return sub
  18. def by_transaction(self, transaction_id):
  19. try:
  20. tx = braintree.Transaction.find(transaction_id)
  21. except braintree.exceptions.NotFoundError:
  22. return None, None
  23. try:
  24. sub = self.get(customer_id=tx.customer_details.id)
  25. except Subscription.DoesNotExist:
  26. return None, None
  27. return sub, tx
  28. class Subscription(models.Model):
  29. user = models.OneToOneField(User, models.CASCADE, blank=True, null=True)
  30. customer_id = models.CharField(max_length=36, blank=True)
  31. payment_method_token = models.CharField(max_length=35, blank=True)
  32. subscription_id = models.CharField(max_length=10, blank=True)
  33. plan_id = models.CharField(max_length=10, blank=True)
  34. plan_name = models.CharField(max_length=50, blank=True)
  35. address_id = models.CharField(max_length=2, blank=True)
  36. send_invoices = models.BooleanField(default=True)
  37. objects = SubscriptionManager()
  38. @property
  39. def payment_method(self):
  40. if not self.payment_method_token:
  41. return None
  42. if not hasattr(self, "_pm"):
  43. self._pm = braintree.PaymentMethod.find(self.payment_method_token)
  44. return self._pm
  45. def _get_braintree_subscription(self):
  46. if not hasattr(self, "_sub"):
  47. self._sub = braintree.Subscription.find(self.subscription_id)
  48. return self._sub
  49. def get_client_token(self):
  50. return braintree.ClientToken.generate({
  51. "customer_id": self.customer_id
  52. })
  53. def update_payment_method(self, nonce):
  54. # Create customer record if it does not exist:
  55. if not self.customer_id:
  56. result = braintree.Customer.create({
  57. "email": self.user.email
  58. })
  59. if not result.is_success:
  60. return result
  61. self.customer_id = result.customer.id
  62. self.save()
  63. # Create payment method
  64. result = braintree.PaymentMethod.create({
  65. "customer_id": self.customer_id,
  66. "payment_method_nonce": nonce,
  67. "options": {"make_default": True}
  68. })
  69. if not result.is_success:
  70. return result
  71. self.payment_method_token = result.payment_method.token
  72. self.save()
  73. # Update an existing subscription to use this payment method
  74. if self.subscription_id:
  75. result = braintree.Subscription.update(self.subscription_id, {
  76. "payment_method_token": self.payment_method_token
  77. })
  78. if not result.is_success:
  79. return result
  80. def update_address(self, post_data):
  81. # Create customer record if it does not exist:
  82. if not self.customer_id:
  83. result = braintree.Customer.create({
  84. "email": self.user.email
  85. })
  86. if not result.is_success:
  87. return result
  88. self.customer_id = result.customer.id
  89. self.save()
  90. payload = {key: str(post_data.get(key)) for key in ADDRESS_KEYS}
  91. if self.address_id:
  92. result = braintree.Address.update(self.customer_id,
  93. self.address_id,
  94. payload)
  95. else:
  96. payload["customer_id"] = self.customer_id
  97. result = braintree.Address.create(payload)
  98. if result.is_success:
  99. self.address_id = result.address.id
  100. self.save()
  101. if not result.is_success:
  102. return result
  103. def setup(self, plan_id):
  104. result = braintree.Subscription.create({
  105. "payment_method_token": self.payment_method_token,
  106. "plan_id": plan_id
  107. })
  108. if result.is_success:
  109. self.subscription_id = result.subscription.id
  110. self.plan_id = plan_id
  111. if plan_id == "P20":
  112. self.plan_name = "Standard ($20 / month)"
  113. elif plan_id == "Y192":
  114. self.plan_name = "Standard ($192 / year)"
  115. elif plan_id == "P80":
  116. self.plan_name = "Plus ($80 / month)"
  117. elif plan_id == "Y768":
  118. self.plan_name = "Plus ($768 / year)"
  119. self.save()
  120. return result
  121. def cancel(self):
  122. if self.subscription_id:
  123. braintree.Subscription.cancel(self.subscription_id)
  124. self.subscription_id = ""
  125. self.plan_id = ""
  126. self.save()
  127. def pm_is_card(self):
  128. pm = self.payment_method
  129. return isinstance(pm, braintree.credit_card.CreditCard)
  130. def pm_is_paypal(self):
  131. pm = self.payment_method
  132. return isinstance(pm, braintree.paypal_account.PayPalAccount)
  133. def next_billing_date(self):
  134. o = self._get_braintree_subscription()
  135. return o.next_billing_date
  136. @property
  137. def address(self):
  138. if not hasattr(self, "_address"):
  139. try:
  140. self._address = braintree.Address.find(self.customer_id,
  141. self.address_id)
  142. except braintree.exceptions.NotFoundError:
  143. self._address = None
  144. return self._address
  145. def flattened_address(self):
  146. if self.address_id:
  147. ctx = {"a": self.address}
  148. return render_to_string("payments/address_plain.html", ctx)
  149. else:
  150. return self.user.email
  151. @property
  152. def transactions(self):
  153. if not hasattr(self, "_tx"):
  154. if not self.customer_id:
  155. self._tx = []
  156. else:
  157. self._tx = list(braintree.Transaction.search(braintree.TransactionSearch.customer_id == self.customer_id))
  158. return self._tx