Skip to content

Commit

Permalink
Merge branch 'production' into dev-server
Browse files Browse the repository at this point in the history
  • Loading branch information
shaheenhyderk authored Nov 21, 2023
2 parents ead5aba + 1b4af4e commit 96ad86c
Show file tree
Hide file tree
Showing 4 changed files with 162 additions and 107 deletions.
134 changes: 107 additions & 27 deletions api/common/common_views.py
Original file line number Diff line number Diff line change
@@ -1,55 +1,79 @@
import json

import requests
import requests
from django.db import models
from django.db.models import Count, Subquery, OuterRef
from django.db.models import Sum, F, Case, When, Value, CharField, Count, Q
from django.db.models.functions import Coalesce
from rest_framework.views import APIView
from django.db import models

from db.learning_circle import LearningCircle
from db.learning_circle import UserCircleLink
from db.organization import Organization
from db.task import InterestGroup
from db.task import InterestGroup, KarmaActivityLog, UserIgLink
from db.user import User, UserRoleLink
from utils.response import CustomResponse
from utils.types import IntegrationType, OrganizationType, RoleType
from utils.utils import CommonUtils
from .serializer import StudentInfoSerializer, CollegeInfoSerializer
from django.db.models import Count, Subquery, OuterRef


class LcDashboardAPI(APIView):
def get(self, request):
date = request.query_params.get("date")
if date:
learning_circle_count = LearningCircle.objects.filter(
created_at__gt=date
).count()
learning_circle_count = LearningCircle.objects.filter(created_at__gt=date).count()
total_no_enrollment = UserCircleLink.objects.filter(accepted=True, created_at__gt=date).count()
user_circle_link_count = UserCircleLink.objects.filter(created_at__gt=date, circle=OuterRef('pk')).values(
'circle_id').annotate(
total_users=Count('id')).values('total_users')

query = InterestGroup.objects.annotate(
total_circles=Count("learning_circle_ig", distinct=True),
total_users=Subquery(user_circle_link_count, output_field=models.IntegerField())
).values("name", "total_circles", "total_users")

circle_count_by_ig = (
query.values("name")
.order_by("name")
.annotate(
total_circles=Count("learning_circle_ig", distinct=True),
total_users=Count("learning_circle_ig__user_circle_link_circle", distinct=True),
)
)
unique_user_count = (
UserCircleLink.objects.filter(created_at__gt=date, accepted=True)
.values("user")
.distinct()
.count()
)
else:
learning_circle_count = LearningCircle.objects.all().count()
total_no_enrollment = UserCircleLink.objects.filter(accepted=True).count()

total_no_enrollment = UserCircleLink.objects.filter(accepted=True).count()
user_circle_link_count = UserCircleLink.objects.filter(circle=OuterRef('pk')).values('circle_id').annotate(
total_users=Count('id')).values('total_users')
user_circle_link_count = UserCircleLink.objects.filter(circle=OuterRef('pk')).values('circle_id').annotate(
total_users=Count('id')).values('total_users')

query = InterestGroup.objects.annotate(
total_circles=Count("learning_circle_ig", distinct=True),
total_users=Subquery(user_circle_link_count, output_field=models.IntegerField())
).values("name", "total_circles", "total_users")

circle_count_by_ig = (
query.values("name")
.order_by("name")
.annotate(
query = InterestGroup.objects.annotate(
total_circles=Count("learning_circle_ig", distinct=True),
total_users=Count("learning_circle_ig__user_circle_link_circle", distinct=True),
total_users=Subquery(user_circle_link_count, output_field=models.IntegerField())
).values("name", "total_circles", "total_users")

circle_count_by_ig = (
query.values("name")
.order_by("name")
.annotate(
total_circles=Count("learning_circle_ig", distinct=True),
total_users=Count("learning_circle_ig__user_circle_link_circle", distinct=True),
)
)
)

unique_user_count = (
UserCircleLink.objects.filter(accepted=True)
.values("user")
.distinct()
.count()
)
unique_user_count = (
UserCircleLink.objects.filter(accepted=True)
.values("user")
.distinct()
.count()
)

return CustomResponse(
response={
Expand Down Expand Up @@ -303,3 +327,59 @@ def get(self, request):
# If it doesn't exist, create a new entry
grouped_colleges[cleaned_college] = int(count)
return CustomResponse(response=grouped_colleges).get_success_response()


class UserProfilePicAPI(APIView):
def get(self, request, muid):
user = User.objects.filter(muid=muid).annotate(image=F("profile_pic")).values("image")
return CustomResponse(response=user).get_success_response()


class ListIGAPI(APIView):

def get(self, request):
return CustomResponse(response=InterestGroup.objects.all().values("name")).get_success_response()


class ListTopIgUsersAPI(APIView):

def get(self, request):
ig_name = request.query_params.getlist("ig_name", [])

user_karma_by_ig = KarmaActivityLog.objects.filter(
task__ig__name__in=ig_name, appraiser_approved=True
).values(
userid=F('user__id'),
muid=F('user__muid'),
first_name=F('user__first_name'),
last_name=F('user__last_name'),
).annotate(
ig_karma=Sum('karma')
).order_by('-ig_karma')[:100]

# Extract 'userid' values into a new list
userid_list = [entry['userid'] for entry in user_karma_by_ig]

# Fetch user muid and interest group as a list
results = UserIgLink.objects.filter(user__id__in=userid_list).values_list('user__muid', 'ig__name', named=True)

# Process the results to create the desired structure
user_ig_dict = {}
for result in results:
muid = result.user__muid
ig = result.ig__name

if muid not in user_ig_dict:
user_ig_dict[muid] = {'muid': muid, 'igs': [ig]}
else:
user_ig_dict[muid]['igs'].append(ig)

# Iterate through user_karma_by_ig and add 'igs' information
for user_karma in user_karma_by_ig:
muid = user_karma['muid']
if muid in user_ig_dict:
user_karma['igs'] = user_ig_dict[muid]['igs']
else:
user_karma['igs'] = []

return CustomResponse(response=user_karma_by_ig).get_success_response()
5 changes: 4 additions & 1 deletion api/common/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,8 @@
path('college-wise-lc-report/csv/', common_views.CollegeWiseLcReportCSV.as_view()),
path('lc-report/csv/', common_views.LcReportDownloadAPI.as_view()),
path('global-count/', common_views.GlobalCountAPI.as_view()),
path('gta-sandshore/', common_views.GTASANDSHOREAPI.as_view())
path('gta-sandshore/', common_views.GTASANDSHOREAPI.as_view()),
path('profile-pic/<str:muid>/', common_views.UserProfilePicAPI.as_view()),
path('list-ig/', common_views.ListIGAPI.as_view()),
path('list-ig-top100/', common_views.ListTopIgUsersAPI.as_view()),
]
10 changes: 7 additions & 3 deletions api/dashboard/profile/profile_serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ def get_profile_pic(self,obj):
return profile_pic

def get_roles(self, obj):
return list({link.role.title for link in obj.user_role_link_user.all()})
return list({link.role.title for link in obj.user_role_link_user.filter(verified=True)})

def get_college_id(self, obj):
org_type = (
Expand Down Expand Up @@ -120,17 +120,19 @@ def get_rank(self, obj):
user_karma = obj.wallet_user.karma
if RoleType.MENTOR.value in roles:
ranks = Wallet.objects.filter(
user__user_role_link_user__verified=True,
user__user_role_link_user__role__title=RoleType.MENTOR.value,
karma__gte=user_karma,
).count()
elif RoleType.ENABLER.value in roles:
ranks = Wallet.objects.filter(
user__user_role_link_user__verified=True,
user__user_role_link_user__role__title=RoleType.ENABLER.value,
karma__gte=user_karma,
).count()
else:
ranks = (
Wallet.objects.filter(karma__gte=user_karma)
Wallet.objects.filter(karma__gte=user_karma, user__user_role_link_user__verified=True, )
.exclude(
Q(
user__user_role_link_user__role__title__in=[
Expand Down Expand Up @@ -224,17 +226,19 @@ def get_rank(self, obj):
user_karma = obj.wallet_user.karma
if RoleType.MENTOR.value in roles:
ranks = Wallet.objects.filter(
user__user_role_link_user__verified=True,
user__user_role_link_user__role__title=RoleType.MENTOR.value,
karma__gte=user_karma,
).count()
elif RoleType.ENABLER.value in roles:
ranks = Wallet.objects.filter(
user__user_role_link_user__verified=True,
user__user_role_link_user__role__title=RoleType.ENABLER.value,
karma__gte=user_karma,
).count()
else:
ranks = (
Wallet.objects.filter(karma__gte=user_karma)
Wallet.objects.filter(karma__gte=user_karma,user__user_role_link_user__verified=True)
.exclude(
Q(
user__user_role_link_user__role__title__in=[
Expand Down
120 changes: 44 additions & 76 deletions api/top100_coders/top100_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,85 +6,53 @@

class Leaderboard(APIView):
def get(self, request):
query ="""
SELECT
u.id,
u.first_name,
u.last_name,
SUM(kal.karma) AS total_karma,
org.title AS org,
COALESCE(org.dis, d.name) AS dis,
org.state,
u.profile_pic,
MAX(kal.created_at) AS time_,
kal.created_at AS created_at
FROM
karma_activity_log AS kal
INNER JOIN user AS u ON kal.user_id = u.id
INNER JOIN task_list AS tl ON tl.id = kal.task_id
LEFT JOIN (
SELECT
uol.user_id,
org.id,
org.title AS title,
d.name dis,
s.name state
FROM
user_organization_link AS uol
INNER JOIN organization AS org ON org.id = uol.org_id
LEFT JOIN district AS d ON d.id = org.district_id
LEFT JOIN zone AS z ON z.id = d.zone_id
LEFT JOIN state AS s ON s.id = z.state_id
GROUP BY uol.user_id
) AS org ON org.user_id = u.id
LEFT JOIN district AS d ON d.id = u.district_id
WHERE
tl.event = 'TOP100'
AND kal.appraiser_approved = TRUE
AND tl.hashtag = '#thc-realworld-problem-proposal'
GROUP BY u.id
ORDER BY total_karma DESC, time_;
"""
query2 = """
SELECT * from (SELECT
u.id,
u.first_name,
u.last_name,
SUM(kal.karma) AS total_karma,
org.title AS org,
org.dis,
org.state,
u.profile_pic,
MAX(kal.created_at) AS time_,
kal.created_at AS created_at
FROM
karma_activity_log AS kal
INNER JOIN user AS u ON kal.user_id = u.id
INNER JOIN task_list AS tl ON tl.id = kal.task_id
LEFT JOIN (
SELECT
uol.user_id,
org.id,
org.title AS title,
d.name dis,
s.name state
FROM
user_organization_link AS uol
INNER JOIN organization AS org ON org.id = uol.org_id
LEFT JOIN district AS d ON d.id = org.district_id
LEFT JOIN zone AS z ON z.id = d.zone_id
LEFT JOIN state AS s ON s.id = z.state_id
GROUP BY uol.user_id
query = """
SELECT
u.id,
u.first_name,
u.last_name,
u.profile_pic,
SUM(kal.karma) AS total_karma,
COALESCE(org.title, comm.title) AS org,
COALESCE(org.dis, d.name) AS dis,
COALESCE(org.state, s.name) AS state,
MAX(kal.created_at) AS time_
FROM karma_activity_log AS kal
INNER JOIN user AS u ON kal.user_id = u.id
INNER JOIN task_list AS tl ON tl.id = kal.task_id
LEFT JOIN (
SELECT
uol.user_id,
org.id,
org.title AS title,
d.name dis,
s.name state
FROM user_organization_link AS uol
INNER JOIN organization AS org ON org.id = uol.org_id AND org.org_type IN ('College', 'School', 'Company')
LEFT JOIN district AS d ON d.id = org.district_id
LEFT JOIN zone AS z ON z.id = d.zone_id
LEFT JOIN state AS s ON s.id = z.state_id
GROUP BY uol.user_id
) AS org ON org.user_id = u.id
LEFT JOIN (SELECT
uol.user_id,
org.id,
org.title AS title
FROM user_organization_link AS uol
INNER JOIN organization AS org ON org.id = uol.org_id AND org.org_type IN ('Community')
GROUP BY uol.user_id) AS comm ON comm.user_id = u.id
LEFT JOIN district AS d ON d.id = u.district_id
LEFT JOIN zone AS z ON d.zone_id = z.id
LEFT JOIN state AS s ON z.state_id = s.id
WHERE
tl.event = 'TOP100'
AND kal.appraiser_approved = TRUE
AND DATE(kal.created_at) < CURDATE() - INTERVAL 1 DAY
tl.event = 'TOP100' AND
kal.appraiser_approved = TRUE
AND u.id IN (select user_id from karma_activity_log as kal
INNER JOIN task_list AS tl ON tl.id = kal.task_id
WHERE tl.hashtag = '#thc-realworld-problem-proposal' AND kal.appraiser_approved = TRUE)
GROUP BY u.id
ORDER BY total_karma DESC, time_
)
"""
ORDER BY total_karma DESC, time_;
"""
with connection.cursor() as cursor:
cursor.execute(query)
results = cursor.fetchall()
Expand Down

0 comments on commit 96ad86c

Please sign in to comment.