utils.py 9.5 KB

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