analytics.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. from django.db.models import Count
  2. from django.utils import timezone
  3. from .models import YelpReview
  4. from analytics.background_job import send_email
  5. from gauth.models import Location
  6. from django.conf import settings
  7. def get_yelp_weekly_summary(location_id):
  8. date = timezone.now() - timezone.timedelta(days=7)
  9. reviews = YelpReview.objects.filter(location__location_id=location_id, date_posted__gte=date)
  10. rating = reviews.values('rating').annotate(total=Count('rating')).order_by('-rating')
  11. return reviews, rating
  12. def send_email_bad_reviews():
  13. locations = Location.objects.all()
  14. for location in locations:
  15. to = settings.ADMIN_MAINTAINER_EMAILS
  16. date = timezone.now() - timezone.timedelta(hours=12)
  17. reviews = YelpReview.objects.filter(
  18. location__location_id=location.location_id,
  19. date_posted__gte=date,
  20. rating__lte=3
  21. )
  22. total_reviews = reviews.count()
  23. if total_reviews > 0:
  24. # Add location maintainer email if it has an email
  25. to.append(location.recipient_email) if location.recipient_email else None
  26. subject = f"A negative Yelp review has been post in {location.care_name}."
  27. message = f'''
  28. <p>Hi there, </p>
  29. <p>'''
  30. if total_reviews > 1:
  31. tt = f'{total_reviews} negative Yelp reviews have'
  32. else:
  33. tt = f'A negative Yelp review has '
  34. message += tt + f'been posted in {location.care_name}.</p>'
  35. for r in reviews:
  36. link = f'<p>Link: {r.location.url}</p>'
  37. name = f'<p><b>Reviewer Name:</b> {r.reviewer_name}</p>'
  38. rating = f'<p style="color: red"><b>Rating:</b> {str(r.rating)} star rating.</p>'
  39. comment = f'<p><b>Comment: </b>{r.comment if r.comment else "No comment"}</p>'
  40. message += name + rating + comment + link
  41. message += '<p>Regards,</p><p>Byte Trek Ltd.</p>'
  42. send_email(to_list=to, subject=subject, message_body=message)
  43. if location.recipient_email in to:
  44. to.remove(location.recipient_email)