Sfoglia il codice sorgente

Show graph for location user

Mohidul Islam 4 anni fa
parent
commit
65c48ff334
4 ha cambiato i file con 331 aggiunte e 4 eliminazioni
  1. 204 0
      user/templates/location-wise-reviews.html
  2. 10 1
      user/urls.py
  3. 94 2
      user/utils.py
  4. 23 1
      user/views.py

+ 204 - 0
user/templates/location-wise-reviews.html

@@ -0,0 +1,204 @@
+{% extends 'user-base.html' %}
+
+{% block content %}
+
+<canvas class="my-4" id="myChart" width="900" height="300"></canvas>
+<!--<div class="row">-->
+<!--  <canvas class="my-4" id="googleLineChart" width="900" height="300"></canvas>-->
+<!--  <canvas class="my-4" id="googlePieChart" width="900" height="300"></canvas>-->
+<!--</div>-->
+
+<div style="display: flex">
+    <div id="bar-chart-container" style="position: relative; width: 70%;">
+      <canvas id="googleLineChart" width="900" height="300"></canvas>
+    </div>
+    <div id="pie-chart-container" style="position: relative; width: 30%;">
+      <canvas id="googlePieChart" width="200" height="150"></canvas>
+    </div>
+</div>
+
+<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
+<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js" integrity="sha256-TQq84xX6vkwR0Qs1qH5ADkP+MvH0W+9E7TdHJsoIQiM=" crossorigin="anonymous"></script>
+<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
+
+<script>
+  var ctx = document.getElementById("myChart");
+  var google_line_ctx = document.getElementById("googleLineChart");
+  var google_pie_ctx = document.getElementById("googlePieChart");
+  var location_id = document.getElementById("location_id").value;
+  console.log(location_id.value)
+  var endpoint = '/user/api/analytics/all-platform';
+  params = {
+      "location_id":location_id.trim()
+  }
+  console.log(params)
+  $.ajax({
+        type: "get",
+        url: endpoint,
+        data: params,
+        dataType: 'json',
+        success: function(data) {
+        console.log(data)
+
+        // All data together in a bar chart..
+          var myBarChart = new Chart(ctx, {
+          type: 'bar',
+          data: {
+              labels: data.google.labels,
+              datasets: [
+                  {
+                    label: 'Google',
+                    data: data.google.total_review,
+                    borderColor: 'rgb(255, 204, 0)',
+                    backgroundColor: 'rgb(255, 204, 0)',
+                    borderWidth: 1,
+                    fill: false
+                },
+                {
+                    label: 'Facebook',
+                    data: data.facebook.total_review,
+                    borderColor: 'rgb(0, 51, 204)',
+                    backgroundColor: 'rgb(0, 51, 204)',
+                    borderWidth: 1,
+                    fill: false
+                },
+                {
+                    label: 'Yelp',
+                    data: data.yelp.total_review,
+                    borderColor: 'rgb(204, 51, 0)',
+                    backgroundColor: 'rgb(204, 51, 0)',
+                    borderWidth: 1,
+                    fill: false
+                }]
+            },
+            options: {
+                scales: {
+                    yAxes: [{
+                        ticks: {
+                            beginAtZero: true
+                        }
+                    }],
+                    xAxes: [{
+                        gridLines: {
+                            drawOnChartArea:false
+                        }
+                    }]
+                },
+                title: {
+                    display: true,
+                    fontSize: 16,
+                    text: "Review of this month in all platforms."
+                }
+            }
+        });
+
+        // Google review charts
+        // Google line chart
+        var myGoogleLineChart = new Chart(google_line_ctx, {
+          type: 'line',
+          data: {
+              labels: data.google.labels,
+              datasets: [
+                  {
+                    label: '1*',
+                    data: data.google.star_rating[0],
+                    borderColor: 'rgb(255, 204, 0)',
+                    backgroundColor: 'rgb(255, 204, 0)',
+                    borderWidth: 1,
+                    lineTension: 0,
+                    fill: false
+                },
+                {
+                    label: '2*',
+                    data: data.google.star_rating[1],
+                    borderColor: 'rgb(0, 51, 204)',
+                    backgroundColor: 'rgb(0, 51, 204)',
+                    borderWidth: 1,
+                    lineTension: 0,
+                    fill: false
+                },
+                {
+                    label: '3*',
+                    data: data.google.star_rating[2],
+                    borderColor: 'rgb(204, 51, 0)',
+                    backgroundColor: 'rgb(204, 51, 0)',
+                    borderWidth: 1,
+                    lineTension: 0,
+                    fill: false
+                },
+                {
+                    label: '4*',
+                    data: data.google.star_rating[3],
+                    borderColor: 'rgb(0, 51, 204)',
+                    backgroundColor: 'rgb(0, 51, 204)',
+                    borderWidth: 1,
+                    lineTension: 0,
+                    fill: false
+                },
+                {
+                    label: '5*',
+                    data: data.google.star_rating[4],
+                    borderColor: 'rgb(204, 51, 0)',
+                    backgroundColor: 'rgb(204, 51, 0)',
+                    borderWidth: 1,
+                    lineTension: 0,
+                    fill: false,
+
+                }]
+            },
+            options: {
+                borderJoinStyle: "bevel",
+                scales: {
+                    yAxes: [{
+                        ticks: {
+                            beginAtZero: true
+                        }
+                    }],
+                    xAxes: [{
+                        gridLines: {
+                            drawOnChartArea:false
+                        }
+                    }]
+                },
+                title: {
+                    display: true,
+                    fontSize: 16,
+                    text: "Monthly review in Google."
+                }
+            }
+        });
+
+        // Google pie chart
+        var myGooglePieChart = new Chart(google_pie_ctx, {
+          type: 'pie',
+          data: {
+              labels: data.google.curr_month.label,
+              datasets: [
+                  {
+                    data: data.google.curr_month.total,
+                    backgroundColor: [
+                        'rgb(255, 99, 132)',
+                        'rgb(255, 159, 64)',
+                        'rgb(153, 102, 255)',
+                        'rgb(54, 162, 235)',
+                        'rgb(75, 192, 192)'
+                    ]
+                }]
+            },
+            options: {
+              title: {
+                display: true,
+                fontSize: 16,
+                text: 'This is google reviews'
+              }
+            }
+        });
+    },
+
+    error: function(error_data) {
+       console.log(error_data);
+    }
+  });
+</script>
+
+{% endblock content %}

+ 10 - 1
user/urls.py

@@ -1,6 +1,13 @@
 from django.urls import path
 from django.contrib.auth import views as auth_views
-from .views import RegistrationView, LocationAnalytics, ChartDataThisMonth, ReviewListLocationWise
+from .views import (
+    RegistrationView,
+    LocationAnalytics,
+    ChartDataThisMonth,
+    ReviewListLocationWise,
+    ReviewAnalyticsGraph,
+    ChartDataAllPlatform,
+)
 
 urlpatterns = [
     path('login/', auth_views.LoginView.as_view(template_name='login.html'), name='login'),
@@ -9,4 +16,6 @@ urlpatterns = [
     path('analytics', LocationAnalytics.as_view(), name='location-analytics'),
     path('reviews/<platform>', ReviewListLocationWise.as_view(), name='location-wise-review-list'),
     path('api/analytics', ChartDataThisMonth.as_view(), name='location-api-analytics'),
+    path('api/analytics/all-platform', ChartDataAllPlatform.as_view(), name='location-api-analytics-all-platform'),
+    path('graph', ReviewAnalyticsGraph.as_view(), name='location-analytics-graph'),
 ]

+ 94 - 2
user/utils.py

@@ -1,9 +1,28 @@
+import numpy as np
 from django.utils import timezone
+from django.db import connection
 from django.db.models import Count
 from review.models import Review
-from facebook_app.models import FacebookReview
-from yelp.models import YelpReview
+from facebook_app.models import FacebookReview, FacebookPage
+from yelp.models import YelpReview, YelpLocation
 
+DATE_IDENTIFIER = {
+    'google': 'create_time',
+    'yelp': 'date_posted',
+    'facebook': 'create_time'
+}
+
+REVIEW_IDENTIFIER = {
+    'google': 'star_rating',
+    'yelp': 'rating',
+    'facebook': 'recommendation_type'
+}
+
+TABLE_NAME = {
+    'google': 'review_review',
+    'facebook': 'facebook_app_facebookreview',
+    'yelp': 'yelp_yelpreview'
+}
 
 now = timezone.now()
 beginning_of_month = now.replace(day=1, hour=0, minute=0, second=0)
@@ -162,3 +181,76 @@ def get_this_month_analytics(location_id):
         'facebook': facebook,
         'yelp': yelp
     }
+
+
+def get_review_count_by_month(location_id, platform):
+    now = timezone.now()
+    date = now.replace(day=1) - timezone.timedelta(days=1)
+    day = date.day - now.day
+    curr_month = {
+
+    }
+    if platform == 'google':
+        loc_id = location_id
+        field_name = 'location_id'
+        curr_month_data = Review.objects.filter(create_time__gte=date, location_id=location_id).values('star_rating')\
+            .annotate(total=Count('star_rating')).order_by('star_rating')
+        curr_month['label'] = [r.get('star_rating') for r in curr_month_data]
+        curr_month['total'] = [r.get('total') for r in curr_month_data]
+
+    elif platform == 'yelp':
+        loc_id = YelpLocation.objects.get(location_id=location_id).id
+        field_name = 'location_id'
+        curr_month_data = YelpReview.objects.filter(date_posted__gte=date, location__location_id=location_id)\
+            .values('rating').annotate(total=Count('rating')).order_by('rating')
+        curr_month['label'] = [r.get('rating') for r in curr_month_data]
+        curr_month['total'] = [r.get('total') for r in curr_month_data]
+
+    elif platform == 'facebook':
+        loc_id = FacebookPage.objects.get(location_id=location_id).id
+        field_name = 'page_id'
+        curr_month_data = FacebookReview.objects.filter(create_time__gte=date, page__location_id=location_id)\
+            .values('recommendation_type').annotate(total=Count('recommendation_type'))
+        curr_month['label'] = ['Recommended' if r.get('recommendation_type') else 'Not Recommended' for r in curr_month_data]
+        curr_month['total'] = [r.get('total') for r in curr_month_data]
+
+    else:
+        raise ValueError(f'No platform name {platform}')
+
+    sql = f'''
+            SELECT MONTHNAME({DATE_IDENTIFIER[platform]}) as month, {REVIEW_IDENTIFIER[platform]}, COUNT(*) as total_review
+            FROM {TABLE_NAME[platform]}
+            WHERE DATE_ADD(DATE_ADD(CURRENT_TIMESTAMP(),
+            INTERVAL -1 YEAR), INTERVAL {day} DAY) <= {DATE_IDENTIFIER[platform]} and {field_name}={loc_id}
+            GROUP BY MONTHNAME({DATE_IDENTIFIER[platform]}), {REVIEW_IDENTIFIER[platform]}
+            ORDER BY {DATE_IDENTIFIER[platform]};
+           '''
+    with connection.cursor() as cursor:
+        cursor.execute(sql)
+        rows = cursor.fetchall()
+        # It will transform a cursor like (('September', 5, 26), ('October', 3, 21), ...)
+        # to a dict like this {('September', 5): 26, ('October', 3): 21), ...}
+        # Here key tuple ('September', 5) means 5 star ratings in September month and value is the number of star count.
+        row_dict = {(row[0], row[1]): row[2] for row in rows}
+        # Get all month names for graph label
+        labels = []
+        for row in rows:
+            if row[0] not in labels:
+                labels.append(row[0])
+        star_ratings = []
+        if platform == 'facebook':
+            for i in range(2):
+                row = [row_dict.get((m, i), 0) for m in labels]
+                star_ratings.append(row)
+        else:
+            for i in range(1, 6):
+                row = [row_dict.get((m, i), 0) for m in labels]
+                star_ratings.append(row)
+    total_review = list(np.sum(star_ratings, axis=0))
+    response = {
+        'total_review': total_review,
+        'labels': labels,
+        'star_rating': star_ratings,
+        'curr_month': curr_month
+    }
+    return response

+ 23 - 1
user/views.py

@@ -15,7 +15,8 @@ from .utils import (
     get_google_review_report,
     get_facebook_report,
     get_yelp_review_report,
-    get_this_month_analytics
+    get_this_month_analytics,
+    get_review_count_by_month
 )
 from rest_framework.views import APIView
 from rest_framework.response import Response
@@ -82,6 +83,20 @@ class ChartDataThisMonth(APIView):
         return Response(res)
 
 
+class ChartDataAllPlatform(APIView):
+    def get(self, request, *args, **kwargs):
+        location_id = request.GET['location_id']
+        g_res = get_review_count_by_month(location_id, 'google')
+        f_res = get_review_count_by_month(location_id, 'facebook')
+        y_res = get_review_count_by_month(location_id, 'yelp')
+        res = {
+            'google': g_res,
+            'facebook': f_res,
+            'yelp': y_res
+        }
+        return Response(res)
+
+
 class ReviewListLocationWise(View):
     def get(self, request, platform,  *args, **kwargs):
         location_id = request.user.useraccount.location_id
@@ -104,3 +119,10 @@ class ReviewListLocationWise(View):
             reviews = paginator.page(paginator.num_pages)
         context = {'reviews': reviews, 'platform': platform}
         return render(request, 'review-list.html', context=context)
+
+
+class ReviewAnalyticsGraph(View):
+
+    def get(self, requests, *args, **kwargs):
+        return render(requests, 'location-wise-reviews.html')
+