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.

184 lines
5.7 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 = (
  12. "company",
  13. "street_address",
  14. "extended_address",
  15. "locality",
  16. "region",
  17. "postal_code",
  18. "country_code_alpha2",
  19. )
  20. class SubscriptionManager(models.Manager):
  21. def for_user(self, user):
  22. sub, created = Subscription.objects.get_or_create(user_id=user.id)
  23. return sub
  24. def by_transaction(self, transaction_id):
  25. try:
  26. tx = braintree.Transaction.find(transaction_id)
  27. except braintree.exceptions.NotFoundError:
  28. return None, None
  29. try:
  30. sub = self.get(customer_id=tx.customer_details.id)
  31. except Subscription.DoesNotExist:
  32. return None, None
  33. return sub, tx
  34. def by_braintree_webhook(self, request):
  35. sig = str(request.POST["bt_signature"])
  36. payload = str(request.POST["bt_payload"])
  37. doc = braintree.WebhookNotification.parse(sig, payload)
  38. assert doc.kind == "subscription_charged_successfully"
  39. sub = self.get(subscription_id=doc.subscription.id)
  40. return sub, doc.subscription.transactions[0]
  41. class Subscription(models.Model):
  42. user = models.OneToOneField(User, models.CASCADE, blank=True, null=True)
  43. customer_id = models.CharField(max_length=36, blank=True)
  44. payment_method_token = models.CharField(max_length=35, blank=True)
  45. subscription_id = models.CharField(max_length=10, blank=True)
  46. plan_id = models.CharField(max_length=10, blank=True)
  47. plan_name = models.CharField(max_length=50, blank=True)
  48. address_id = models.CharField(max_length=2, blank=True)
  49. send_invoices = models.BooleanField(default=True)
  50. invoice_email = models.EmailField(blank=True)
  51. objects = SubscriptionManager()
  52. @property
  53. def payment_method(self):
  54. if not hasattr(self, "_pm"):
  55. o = self._get_braintree_subscription()
  56. self._pm = braintree.PaymentMethod.find(o.payment_method_token)
  57. return self._pm
  58. def _get_braintree_subscription(self):
  59. if not hasattr(self, "_sub"):
  60. self._sub = braintree.Subscription.find(self.subscription_id)
  61. return self._sub
  62. def get_client_token(self):
  63. assert self.customer_id
  64. return braintree.ClientToken.generate({"customer_id": self.customer_id})
  65. def update_payment_method(self, nonce):
  66. assert self.subscription_id
  67. result = braintree.Subscription.update(
  68. self.subscription_id, {"payment_method_nonce": nonce}
  69. )
  70. if not result.is_success:
  71. return result
  72. def update_address(self, post_data):
  73. # Create customer record if it does not exist:
  74. if not self.customer_id:
  75. result = braintree.Customer.create({"email": self.user.email})
  76. if not result.is_success:
  77. return result
  78. self.customer_id = result.customer.id
  79. self.save()
  80. payload = {key: str(post_data.get(key)) for key in ADDRESS_KEYS}
  81. if self.address_id:
  82. result = braintree.Address.update(
  83. self.customer_id, self.address_id, payload
  84. )
  85. else:
  86. payload["customer_id"] = self.customer_id
  87. result = braintree.Address.create(payload)
  88. if result.is_success:
  89. self.address_id = result.address.id
  90. self.save()
  91. if not result.is_success:
  92. return result
  93. def setup(self, plan_id, nonce):
  94. result = braintree.Subscription.create(
  95. {"payment_method_nonce": nonce, "plan_id": plan_id}
  96. )
  97. if result.is_success:
  98. self.subscription_id = result.subscription.id
  99. self.plan_id = plan_id
  100. if plan_id == "P20":
  101. self.plan_name = "Business ($20 / month)"
  102. elif plan_id == "Y192":
  103. self.plan_name = "Business ($192 / year)"
  104. elif plan_id == "P80":
  105. self.plan_name = "Business Plus ($80 / month)"
  106. elif plan_id == "Y768":
  107. self.plan_name = "Business Plus ($768 / year)"
  108. self.save()
  109. return result
  110. def cancel(self):
  111. if self.subscription_id:
  112. braintree.Subscription.cancel(self.subscription_id)
  113. self.subscription_id = ""
  114. self.plan_id = ""
  115. self.plan_name = ""
  116. self.save()
  117. def pm_is_card(self):
  118. pm = self.payment_method
  119. return isinstance(pm, braintree.credit_card.CreditCard)
  120. def pm_is_paypal(self):
  121. pm = self.payment_method
  122. return isinstance(pm, braintree.paypal_account.PayPalAccount)
  123. def next_billing_date(self):
  124. o = self._get_braintree_subscription()
  125. return o.next_billing_date
  126. @property
  127. def address(self):
  128. if not hasattr(self, "_address"):
  129. try:
  130. self._address = braintree.Address.find(
  131. self.customer_id, self.address_id
  132. )
  133. except braintree.exceptions.NotFoundError:
  134. self._address = None
  135. return self._address
  136. @property
  137. def transactions(self):
  138. if not hasattr(self, "_tx"):
  139. if not self.customer_id:
  140. self._tx = []
  141. else:
  142. self._tx = list(
  143. braintree.Transaction.search(
  144. braintree.TransactionSearch.customer_id == self.customer_id
  145. )
  146. )
  147. return self._tx