subscriptions.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import logging
  2. from django.core.mail import EmailMultiAlternatives
  3. from django.conf import settings
  4. from django.template.loader import render_to_string
  5. from store_order.models import Order
  6. LOG = logging.getLogger(__name__)
  7. def _send_email(template, email, duration, paper):
  8. DEFAULT_FROM_EMAIL = getattr(settings, "DEFAULT_FROM_EMAIL")
  9. subject, from_email, to = ("Thank you", DEFAULT_FROM_EMAIL, email)
  10. data = {"duration": duration, "paper": paper}
  11. text_content = render_to_string(template, dictionary=data)
  12. html_content = render_to_string(template, dictionary=data)
  13. msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
  14. msg.attach_alternative(html_content, "text/html")
  15. msg.send()
  16. def send_new_email(email, duration, paper):
  17. _send_email("storefront/new_subscription_email.html", email, duration, paper)
  18. def send_gift_email(email, duration, paper):
  19. _send_email("storefront/gift_subscription_email.html", email, duration, paper)
  20. def send_renewal_email(email, duration, paper):
  21. _send_email("storefront/renewal_subscription_email.html", email, duration, paper)
  22. def send_subscription_email(order, email=None):
  23. """ sends a new subscription email for each subscription on the order """
  24. LOG.debug("Send Subscription Email: In")
  25. if order and isinstance(order, Order):
  26. if not email:
  27. user = order.user
  28. if user and not user.is_anonymous() and user.email:
  29. email = user.email
  30. else:
  31. LOG.debug(
  32. "User is anonymous or email is empty, no email will " "be found."
  33. )
  34. return
  35. for sub_item in order.subscription_items:
  36. LOG.debug(
  37. "Found subscription item ({0})on order({1})".format(sub_item, order)
  38. )
  39. product = sub_item.product.child()
  40. is_renewal = product.renewal
  41. is_gift = sub_item.is_gift
  42. title = product.title
  43. duration = product.duration
  44. if is_renewal:
  45. LOG.debug("Sending renewal email to {0}...".format(email))
  46. send_renewal_email(email, duration, title)
  47. elif is_gift:
  48. LOG.debug("Sending gift email to {0}...".format(email))
  49. send_gift_email(email, duration, title)
  50. else:
  51. LOG.debug("Sending new email to {0}...".format(email))
  52. send_new_email(email, duration, title)
  53. LOG.debug("Send Subscription Email: Out")
  54. else:
  55. LOG.debug("Not an order: {0}".format(order))