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.

68 lines
1.9 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. if settings.USE_PAYMENTS:
  5. import braintree
  6. else:
  7. # hc.payments tests mock this object, so tests should
  8. # still be able to run:
  9. braintree = None
  10. class SubscriptionManager(models.Manager):
  11. def for_user(self, user):
  12. sub, created = Subscription.objects.get_or_create(user_id=user.id)
  13. return sub
  14. class Subscription(models.Model):
  15. user = models.OneToOneField(User, blank=True, null=True)
  16. customer_id = models.CharField(max_length=36, blank=True)
  17. payment_method_token = models.CharField(max_length=35, blank=True)
  18. subscription_id = models.CharField(max_length=10, blank=True)
  19. plan_id = models.CharField(max_length=10, blank=True)
  20. objects = SubscriptionManager()
  21. def price(self):
  22. if self.plan_id == "P5":
  23. return 5
  24. elif self.plan_id == "P75":
  25. return 75
  26. return 0
  27. def _get_braintree_payment_method(self):
  28. if not hasattr(self, "_pm"):
  29. self._pm = braintree.PaymentMethod.find(self.payment_method_token)
  30. return self._pm
  31. def cancel(self):
  32. if self.subscription_id:
  33. braintree.Subscription.cancel(self.subscription_id)
  34. self.subscription_id = ""
  35. self.plan_id = ""
  36. self.save()
  37. def pm_is_credit_card(self):
  38. return isinstance(self._get_braintree_payment_method(),
  39. braintree.credit_card.CreditCard)
  40. def pm_is_paypal(self):
  41. return isinstance(self._get_braintree_payment_method(),
  42. braintree.paypal_account.PayPalAccount)
  43. def card_type(self):
  44. o = self._get_braintree_payment_method()
  45. return o.card_type
  46. def last_4(self):
  47. o = self._get_braintree_payment_method()
  48. return o.last_4
  49. def paypal_email(self):
  50. o = self._get_braintree_payment_method()
  51. return o.email