utils.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. import numpy as np
  2. from django.utils import timezone
  3. from django.db import connection
  4. from django.db.models import Count
  5. from review.models import Review
  6. from facebook_app.models import FacebookReview, FacebookPage
  7. from yelp.models import YelpReview, YelpLocation
  8. DATE_IDENTIFIER = {
  9. 'google': 'create_time',
  10. 'yelp': 'date_posted',
  11. 'facebook': 'create_time'
  12. }
  13. REVIEW_IDENTIFIER = {
  14. 'google': 'star_rating',
  15. 'yelp': 'rating',
  16. 'facebook': 'recommendation_type'
  17. }
  18. TABLE_NAME = {
  19. 'google': 'review_review',
  20. 'facebook': 'facebook_app_facebookreview',
  21. 'yelp': 'yelp_yelpreview'
  22. }
  23. def get_google_review_report(location_id):
  24. now = timezone.now()
  25. beginning_of_month = now.replace(day=1, hour=0, minute=0, second=0)
  26. beginning_of_last_month = now - timezone.timedelta(days=now.day + 31)
  27. pos = Review.objects.filter(
  28. location_id=location_id,
  29. create_time__range=(beginning_of_month, now),
  30. star_rating__gte=3
  31. ).count()
  32. neg = Review.objects.filter(
  33. location_id=location_id,
  34. create_time__range=(beginning_of_month, now),
  35. star_rating__lte=2
  36. ).count()
  37. pos_last_month = Review.objects.filter(
  38. location_id=location_id,
  39. create_time__range=(beginning_of_last_month, beginning_of_month),
  40. star_rating__gte=3
  41. ).count()
  42. neg_last_month = Review.objects.filter(
  43. location_id=location_id,
  44. create_time__range=(beginning_of_last_month, beginning_of_month),
  45. star_rating__lte=2
  46. ).count()
  47. pos_growth = 'inf' if pos_last_month == 0 else round(((((pos / now.day) * 30) - pos_last_month) / pos_last_month) * 100, 2)
  48. neg_growth = 'inf' if neg_last_month == 0 else round(((((neg / now.day) * 30) - neg_last_month) / neg_last_month) * 100, 2)
  49. total = pos + neg
  50. last_month_total = pos_last_month + neg_last_month
  51. total_growth = 'inf' if last_month_total == 0 else round(((((total / now.day) * 30) - last_month_total) / last_month_total) * 100, 2)
  52. return {
  53. 'positive': pos,
  54. 'positive_growth': pos_growth,
  55. 'negative': neg,
  56. 'negative_growth': neg_growth,
  57. 'total': total,
  58. 'total_growth': total_growth
  59. }
  60. def get_facebook_report(location_id):
  61. now = timezone.now()
  62. beginning_of_month = now.replace(day=1, hour=0, minute=0, second=0)
  63. beginning_of_last_month = now - timezone.timedelta(days=now.day + 31)
  64. pos = FacebookReview.objects.filter(
  65. page__location_id=location_id,
  66. create_time__range=(beginning_of_month, now),
  67. recommendation_type=True
  68. ).count()
  69. neg = FacebookReview.objects.filter(
  70. page__location_id=location_id,
  71. create_time__range=(beginning_of_month, now),
  72. recommendation_type=False
  73. ).count()
  74. pos_last_month = FacebookReview.objects.filter(
  75. page__location_id=location_id,
  76. create_time__range=(beginning_of_last_month, beginning_of_month),
  77. recommendation_type=True
  78. ).count()
  79. neg_last_month = FacebookReview.objects.filter(
  80. page__location_id=location_id,
  81. create_time__range=(beginning_of_last_month, beginning_of_month),
  82. recommendation_type=False
  83. ).count()
  84. pos_growth = 'inf' if pos_last_month == 0 else round(((((pos / now.day) * 30) - pos_last_month) / pos_last_month) * 100, 2)
  85. neg_growth = 'inf' if neg_last_month == 0 else round(((((neg / now.day) * 30) - neg_last_month) / neg_last_month) * 100, 2)
  86. total = pos + neg
  87. last_month_total = pos_last_month + neg_last_month
  88. total_growth = 'inf' if last_month_total == 0 else round(((((total / now.day) * 30) - last_month_total) / last_month_total) * 100, 2)
  89. return {
  90. 'positive': pos,
  91. 'positive_growth': pos_growth,
  92. 'negative': neg,
  93. 'negative_growth': neg_growth,
  94. 'total': total,
  95. 'total_growth': total_growth
  96. }
  97. def get_yelp_review_report(location_id):
  98. now = timezone.now()
  99. beginning_of_month = now.replace(day=1, hour=0, minute=0, second=0)
  100. beginning_of_last_month = now - timezone.timedelta(days=now.day + 31)
  101. pos = YelpReview.objects.filter(
  102. location__location_id=location_id,
  103. date_posted__range=(beginning_of_month, now),
  104. rating__gte=3
  105. ).count()
  106. neg = YelpReview.objects.filter(
  107. location__location_id=location_id,
  108. date_posted__range=(beginning_of_month, now),
  109. rating__lte=2
  110. ).count()
  111. pos_last_month = YelpReview.objects.filter(
  112. location__location_id=location_id,
  113. date_posted__range=(beginning_of_last_month, beginning_of_month),
  114. rating__gte=3
  115. ).count()
  116. neg_last_month = YelpReview.objects.filter(
  117. location__location_id=location_id,
  118. date_posted__range=(beginning_of_last_month, beginning_of_month),
  119. rating__lte=2
  120. ).count()
  121. pos_growth = 'inf' if pos_last_month == 0 else round(((((pos / now.day) * 30) - pos_last_month) / pos_last_month) * 100, 2)
  122. neg_growth = 'inf' if neg_last_month == 0 else round(((((neg / now.day) * 30) - neg_last_month) / neg_last_month) * 100, 2)
  123. total = pos + neg
  124. last_month_total = pos_last_month + neg_last_month
  125. total_growth = 'inf' if last_month_total == 0 else round(((((total / now.day) * 30) - last_month_total) / last_month_total) * 100, 2)
  126. return {
  127. 'positive': pos,
  128. 'positive_growth': pos_growth,
  129. 'negative': neg,
  130. 'negative_growth': neg_growth,
  131. 'total': total,
  132. 'total_growth': total_growth
  133. }
  134. def get_this_month_analytics(location_id):
  135. now = timezone.now()
  136. beginning_of_month = now.replace(day=1, hour=0, minute=0, second=0)
  137. google_qs = Review.objects.filter(
  138. create_time__range=(beginning_of_month, now),
  139. location_id=location_id
  140. )\
  141. .values('create_time__day')\
  142. .annotate(total=Count('create_time__day'))
  143. google_qs_dict = {q['create_time__day']: q['total'] for q in google_qs}
  144. yelp_qs = YelpReview.objects.filter(
  145. location__location_id=location_id,
  146. date_posted__range=(beginning_of_month, now),
  147. )\
  148. .values('date_posted__day')\
  149. .annotate(total=Count('date_posted__day'))
  150. yelp_qs_dict = {q['date_posted__day']: q['total'] for q in yelp_qs}
  151. facebook_qs = FacebookReview.objects.filter(
  152. page__location_id=location_id,
  153. create_time__range=(beginning_of_month, now),
  154. )\
  155. .values('create_time__day')\
  156. .annotate(total=Count('create_time__day'))
  157. facebook_qs_dict = {q['create_time__day']: q['total'] for q in facebook_qs}
  158. label = []
  159. facebook = []
  160. yelp = []
  161. google = []
  162. for day in range(1, now.day+1):
  163. label.append(day)
  164. facebook.append(facebook_qs_dict.get(day, 0))
  165. yelp.append(yelp_qs_dict.get(day, 0))
  166. google.append(google_qs_dict.get(day, 0))
  167. return {
  168. 'label': label,
  169. 'google': google,
  170. 'facebook': facebook,
  171. 'yelp': yelp
  172. }
  173. def get_review_count_by_month(location_id, platform):
  174. now = timezone.now()
  175. date = now.replace(day=1) - timezone.timedelta(days=1)
  176. day = date.day - now.day
  177. curr_month = {
  178. }
  179. if platform == 'google':
  180. loc_id = location_id
  181. field_name = 'location_id'
  182. curr_month_data = Review.objects.filter(create_time__gte=date, location_id=location_id).values('star_rating')\
  183. .annotate(total=Count('star_rating')).order_by('star_rating')
  184. curr_month['label'] = [r.get('star_rating') for r in curr_month_data]
  185. curr_month['total'] = [r.get('total') for r in curr_month_data]
  186. elif platform == 'yelp':
  187. loc_id = YelpLocation.objects.get(location_id=location_id).id
  188. field_name = 'location_id'
  189. curr_month_data = YelpReview.objects.filter(date_posted__gte=date, location__location_id=location_id)\
  190. .values('rating').annotate(total=Count('rating')).order_by('rating')
  191. curr_month['label'] = [r.get('rating') for r in curr_month_data]
  192. curr_month['total'] = [r.get('total') for r in curr_month_data]
  193. elif platform == 'facebook':
  194. loc_id = FacebookPage.objects.get(location_id=location_id).id
  195. field_name = 'page_id'
  196. curr_month_data = FacebookReview.objects.filter(create_time__gte=date, page__location_id=location_id)\
  197. .values('recommendation_type').annotate(total=Count('recommendation_type'))
  198. curr_month['label'] = ['Recommended' if r.get('recommendation_type') else 'Not Recommended' for r in curr_month_data]
  199. curr_month['total'] = [r.get('total') for r in curr_month_data]
  200. else:
  201. raise ValueError(f'No platform name {platform}')
  202. sql = f'''
  203. SELECT MONTHNAME({DATE_IDENTIFIER[platform]}) as month, {REVIEW_IDENTIFIER[platform]}, COUNT(*) as total_review
  204. FROM {TABLE_NAME[platform]}
  205. WHERE DATE_ADD(DATE_ADD(CURRENT_TIMESTAMP(),
  206. INTERVAL -1 YEAR), INTERVAL {day} DAY) <= {DATE_IDENTIFIER[platform]} and {field_name}={loc_id}
  207. GROUP BY MONTHNAME({DATE_IDENTIFIER[platform]}), {REVIEW_IDENTIFIER[platform]}
  208. ORDER BY {DATE_IDENTIFIER[platform]};
  209. '''
  210. with connection.cursor() as cursor:
  211. cursor.execute(sql)
  212. rows = cursor.fetchall()
  213. # It will transform a cursor like (('September', 5, 26), ('October', 3, 21), ...)
  214. # to a dict like this {('September', 5): 26, ('October', 3): 21), ...}
  215. # Here key tuple ('September', 5) means 5 star ratings in September month and value is the number of star count.
  216. row_dict = {(row[0], row[1]): row[2] for row in rows}
  217. # Get all month names for graph label
  218. labels = formatter_month(now.month)
  219. # labels = []
  220. # for row in rows:
  221. # if row[0] not in labels:
  222. # labels.append(row[0])
  223. # print(labels)
  224. star_ratings = []
  225. if platform == 'facebook':
  226. for i in range(2):
  227. row = [row_dict.get((m, i), 0) for m in labels]
  228. star_ratings.append(row)
  229. else:
  230. for i in range(1, 6):
  231. row = [row_dict.get((m, i), 0) for m in labels]
  232. star_ratings.append(row)
  233. total_review = list(np.sum(star_ratings, axis=0))
  234. response = {
  235. 'total_review': total_review,
  236. 'labels': labels,
  237. 'star_rating': star_ratings,
  238. 'curr_month': curr_month
  239. }
  240. return response
  241. def date_str2datetime(date):
  242. year, month, day = date.split('-')
  243. date = timezone.datetime(year=int(year), month=int(month), day=int(day))
  244. dt_aware = timezone.make_aware(date, timezone.get_current_timezone())
  245. return dt_aware
  246. def formatter_month(m):
  247. '''
  248. Make month this formate
  249. >>> formatter_month(5)
  250. [5, 4, 3, 2, 1, 12, 11, 10, 9, 8, 7, 6]
  251. >>> formatter_month(7)
  252. [7, 6, 5, 4, 3, 2, 1, 12, 11, 10, 9, 8]
  253. :param m: index of current month
  254. :return: formatter of mentioned formate
  255. '''
  256. month = ['January', 'February', 'March', 'April', 'May', 'June', 'July',
  257. 'August', 'September', 'October', 'November', 'December']
  258. return month[m:] + month[:m]