subscriptions.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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(
  18. 'storefront/new_subscription_email.html', email, duration, paper)
  19. def send_gift_email(email, duration, paper):
  20. _send_email(
  21. 'storefront/gift_subscription_email.html', email, duration, paper)
  22. def send_renewal_email(email, duration, paper):
  23. _send_email(
  24. 'storefront/renewal_subscription_email.html', email, duration, paper)
  25. def send_subscription_email(order, email=None):
  26. """ sends a new subscription email for each subscription on the order """
  27. LOG.debug("Send Subscription Email: In")
  28. if order and isinstance(order, Order):
  29. if not email:
  30. user = order.user
  31. if user and not user.is_anonymous() and user.email:
  32. email = user.email
  33. else:
  34. LOG.debug("User is anonymous or email is empty, no email will "
  35. "be found.")
  36. return
  37. for sub_item in order.subscription_items:
  38. LOG.debug("Found subscription item ({0})on order({1})".format(
  39. sub_item, order))
  40. product = sub_item.product.child()
  41. is_renewal = product.renewal
  42. is_gift = sub_item.is_gift
  43. title = product.title
  44. duration = product.duration
  45. if is_renewal:
  46. LOG.debug("Sending renewal email to {0}...".format(email))
  47. send_renewal_email(email, duration, title)
  48. elif is_gift:
  49. LOG.debug("Sending gift email to {0}...".format(email))
  50. send_gift_email(email, duration, title)
  51. else:
  52. LOG.debug("Sending new email to {0}...".format(email))
  53. send_new_email(email, duration, title)
  54. LOG.debug("Send Subscription Email: Out")
  55. else:
  56. LOG.debug("Not an order: {0}".format(order))