Skip to content
This repository has been archived by the owner on Oct 22, 2019. It is now read-only.

Commit

Permalink
Merge pull request #15 from firstziiz/feat/lock-task
Browse files Browse the repository at this point in the history
Feat/lock task
  • Loading branch information
penthaizza authored Sep 30, 2018
2 parents 782e8eb + 256f14e commit 95e7930
Show file tree
Hide file tree
Showing 7 changed files with 221 additions and 23 deletions.
1 change: 1 addition & 0 deletions luna-gateway/Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ uwsgi = "*"
toolz = "*"
djangorestframework-jwt = "*"
requests = "*"
arrow = "*"

[dev-packages]
pylint = "*"
Expand Down
43 changes: 32 additions & 11 deletions luna-gateway/Pipfile.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

23 changes: 22 additions & 1 deletion luna-gateway/luna_gateway/accounts/urls.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,30 @@
from django.urls import path

from .views import MeView, FacebookLoginView
from .views import (
MeView,
FacebookLoginView,
LearningProgressDataView,
FrequencyPracticsDataView,
SkillImprovementDataView,
)

app_name = 'accounts'
urlpatterns = [
path('me/', MeView.as_view(), name='my-user'),
path('fb-login/', FacebookLoginView.as_view(), name='fb-login'),
path(
'learning-progress/',
LearningProgressDataView.as_view(),
name='learning-progress'
),
path(
'frequency-practics/',
FrequencyPracticsDataView.as_view(),
name='frequency-practics'
),
path(
'skill-improvement/',
SkillImprovementDataView.as_view(),
name='skill-improvement'
),
]
153 changes: 146 additions & 7 deletions luna-gateway/luna_gateway/accounts/views.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,25 @@
import uuid
import requests
import arrow
from django.conf import settings

from typing import Dict
from django.contrib.auth import get_user_model
from django.shortcuts import get_object_or_404
from django.contrib.auth.models import User
from django.db.models import Count

from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.generics import RetrieveUpdateAPIView

from rest_framework_jwt.utils import jwt_payload_handler, jwt_encode_handler
from core.jwt import get_token

from tasks.models import Task
from topics.models import TopicLevel, Level
from answers.models import Answer
from topics.serializers import TopicLevelReadSerializer

from .serializers import UserSerializer, FacebookLoginSerializer
from .models import Account

Expand Down Expand Up @@ -75,12 +81,15 @@ def post(self, request, *args, **kwargs):
'client_secret': settings.FACEBOOK_APP_SECRET,
'grant_type': 'fb_exchange_token',
'fb_exchange_token': accessToken
})
}
)

fbRequest = requests.get('https://graph.facebook.com/me', {
'fields': 'id,first_name,last_name,email',
'access_token': accessToken
})
fbRequest = requests.get(
'https://graph.facebook.com/me', {
'fields': 'id,first_name,last_name,email',
'access_token': accessToken
}
)

fbUser = fbRequest.json()
account = None
Expand All @@ -105,3 +114,133 @@ def post(self, request, *args, **kwargs):
return Response({
'accessToken': token,
})


class LearningProgressDataView(APIView):
def get(self, request):
user = request.user

topic_levels = TopicLevelReadSerializer(
TopicLevel.objects.all(),
many=True,
context={
'request': request
},
).data

topic_level_with_user_stats = [
self._add_user_stats(topic_level, user)
for topic_level in topic_levels
]

resp = {}
for result in topic_level_with_user_stats:
stats = 2

# Check Exist stats
if (
result['topic']['id'] in resp and
'stats' in resp[result['topic']['id']]
):
stats = resp[result['topic']['id']]['stats']

# Calculate Stats of Topic
try:
stats = stats + (
(result['total_answer'] / result['total_tasks'] * 20) - 2
)
except ZeroDivisionError:
stats = stats

resp[result['topic']['id']] = {
"topic_name": result['topic']['topic_name'],
"stats": stats
}

return Response({**resp})

def _add_user_stats(self, topic_level, user):
total_answer = Answer.objects.filter(
owned_by=user, task__main_topic__pk=topic_level['pk']
).count()

total_tasks = Task.objects.filter(
main_topic__pk=topic_level['pk'],
order__isnull=False,
).count()

return {
"topic": topic_level['topic'],
"level": topic_level['level'],
"total_answer": total_answer,
"total_tasks": total_tasks,
}


class FrequencyPracticsDataView(APIView):
def get(self, request):
user = request.user

total_answer = Answer.objects.filter(owned_by=user).extra(
select={
'day': 'date(created)'
}
).values('day').annotate(total=Count('created'))

return Response(total_answer)


class SkillImprovementDataView(APIView):
def get(self, request):

user = request.user
total_answer = None

if 'start_date' not in request.GET and 'end_date' not in request.GET:
return Response(
{
"message": "please define 'start_date' and 'end_date'"
}
)

if 'topic_id' in request.GET:
total_answer = Answer.objects.filter(
owned_by=user,
task__main_topic__topic__pk=request.GET['topic_id']
)
else:
total_answer = Answer.objects.filter(owned_by=user, )

# get All Aswers
total_answer = total_answer.extra(
select={
'day': 'date(answers_answer.created)',
}
).values(
'day',
'task__main_topic__level__level_name',
'task__main_topic__level__score',
).annotate(total=Count('created'))

# Manipulate data
levels = Level.objects.all().values()
resp = {}

start = arrow.get(request.GET['start_date'])
end = arrow.get(request.GET['end_date'])

for r in arrow.Arrow.range('day', start, end):
date = r.format('YYYY-MM-DD')
resp[date] = {}
for level in levels:
resp[date][level['level_name']] = 0

for result in total_answer:
date = result['day'].strftime('%Y-%m-%d')
score = result['total'] * result['task__main_topic__level__score']

if date in resp:
level = result['task__main_topic__level__level_name']
resp[date][level] = score

return Response(resp)
18 changes: 18 additions & 0 deletions luna-gateway/luna_gateway/topics/migrations/0008_level_score.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Generated by Django 2.1.1 on 2018-09-30 07:26

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('topics', '0007_topic_description'),
]

operations = [
migrations.AddField(
model_name='level',
name='score',
field=models.PositiveIntegerField(default=0),
),
]
1 change: 1 addition & 0 deletions luna-gateway/luna_gateway/topics/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ class Level(models.Model):
blank=True,
default='',
)
score = models.PositiveIntegerField(default=0)

def __str__(self):
return f'{self.level_name}'
Expand Down
5 changes: 1 addition & 4 deletions luna-gateway/luna_gateway/topics/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ class Meta:
model = Topic
fields = (
'pk',
'url',
'topic_name',
'description',
)
Expand All @@ -18,8 +17,8 @@ class Meta:
model = Level
fields = (
'pk',
'url',
'level_name',
'score',
)


Expand All @@ -29,7 +28,6 @@ class Meta:
depth = 1
fields = (
'pk',
'url',
'level',
'topic',
'outcome',
Expand All @@ -42,7 +40,6 @@ class Meta:
model = TopicLevel
fields = (
'pk',
'url',
'level',
'topic',
'outcome',
Expand Down

0 comments on commit 95e7930

Please sign in to comment.