Skip to content

Commit

Permalink
Merge pull request #1849 from gtech-mulearn/dev
Browse files Browse the repository at this point in the history
award karma
  • Loading branch information
adnankattekaden authored Dec 23, 2023
2 parents 9c7652d + 654ed9b commit 5c9e5d6
Show file tree
Hide file tree
Showing 6 changed files with 314 additions and 11 deletions.
103 changes: 103 additions & 0 deletions alter-scripts/alter-1.43.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import os
import sys
import uuid
from decouple import config

import django

from connection import execute

os.chdir('..')
sys.path.append(os.getcwd())
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mulearnbackend.settings')
django.setup()

#order of socials table must be same as socials list
socials = [
"github",
"facebook",
"instagram",
"linkedin",
"dribble",
"behance",
"stackoverflow",
"medium",
"hackerrank"
]

def get_task_list(hashtag: str):
task_id = execute(f"""
SELECT id
FROM task_list
WHERE hashtag = '{hashtag}';
""")
return task_id[0][0] if task_id else None

def create_social_task():
user_id = config("SYSTEM_ADMIN_ID")
for ele in socials:
social = f"social_{ele}"

if get_task_list(f"#social_{ele}"):
continue

id = uuid.uuid4()
task_type = execute(f"""
SELECT id
FROM task_type
WHERE title = 'Mentor';
""")
execute(f"""
INSERT INTO task_list (id, hashtag, title, karma, type_id, updated_by, updated_at, created_by, created_at)
VALUES ('{id}', '#{social}', '{social}', 20, '{task_type[0][0]}', '{user_id}', now(), '{user_id}', now());
""")

def alter_task_message_id():
execute("""
ALTER TABLE karma_activity_log MODIFY COLUMN task_message_id VARCHAR(36)
""")

def give_karma(user_id, task_id):
id = uuid.uuid4()

log_id = execute(f"""
SELECT id
FROM karma_activity_log
WHERE user_id = '{user_id}' AND task_id = '{task_id}';
""")

if not log_id:
execute(f"""
INSERT INTO karma_activity_log (id, task_id, karma, user_id, updated_by, created_by, peer_approved, peer_approved_by, appraiser_approved_by, appraiser_approved, task_message_id, updated_at, created_at)
VALUES ('{id}', '{task_id}', 20, '{user_id}', '{user_id}', '{user_id}', true, '{user_id}', '{user_id}', true, null, now(), now());
""")
execute(f"""
UPDATE wallet SET karma = karma + 20 WHERE user_id = '{user_id}';
""")

def automate_socials_karma():
results = execute(f"""
SELECT
u.id, github, facebook, instagram, linkedin, dribble, behance, stackoverflow, medium, hackerrank
FROM
user AS u
INNER JOIN
socials AS s ON s.user_id = u.id;
"""
)

for result in results:
for idx, data in enumerate(result[1:]):
social = f"#social_{socials[idx]}"
if data and data != "":
if result[0] == '3a77f992-a8c9-4ca3-8e00-8f1eaaf91d0c':
print(socials[idx])
task_id = get_task_list(social)
give_karma(result[0], task_id)

if __name__ == '__main__':
alter_task_message_id()
create_social_task()
automate_socials_karma()
execute("UPDATE system_setting SET value = '1.43', updated_at = now() WHERE `key` = 'db.version';")

181 changes: 179 additions & 2 deletions api/dashboard/campus/campus_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
from rest_framework.views import APIView

from db.organization import UserOrganizationLink
from db.task import Level, Wallet
from db.user import User
from db.task import Level, Wallet, InterestGroup
from db.user import User, Role, UserRoleLink
from utils.permission import CustomizePermission, JWTUtils, role_required
from utils.response import CustomResponse
from utils.types import OrganizationType, RoleType
Expand Down Expand Up @@ -331,3 +331,180 @@ def patch(self, request, member_id):
serializer.save()
return CustomResponse(general_message='Student Type updated successfully').get_success_response()
return CustomResponse(message=serializer.errors).get_failure_response()

class TransferLeadRoleAPI(APIView):
authentication_classes = [CustomizePermission]

@role_required([RoleType.CAMPUS_LEAD.value])
def post(self, request):
user_id = JWTUtils.fetch_user_id(request)
new_lead_muid = request.data.get("new_lead_muid", None)
if new_lead_muid is None:
return CustomResponse(
general_message="Required data is missing"
).get_failure_response()

new_lead = User.objects.filter(muid=new_lead_muid).first()
if new_lead is None:
return CustomResponse(
general_message="Can't find the user"
).get_failure_response()

user_org_link = get_user_college_link(user_id)
validate_new_lead = UserOrganizationLink.objects.filter(
user__id=new_lead.id,
org=user_org_link.org,
org__org_type=OrganizationType.COLLEGE.value,
is_alumni=False
).first()
if validate_new_lead is None:
return CustomResponse(
general_message="Can't find the user in your college"
).get_failure_response()

role_id = Role.objects.filter(title=RoleType.CAMPUS_LEAD.value).first()
if role_id is None:
return CustomResponse(
general_message="Can't find the role"
).get_failure_response()
role_id = role_id.id

UserRoleLink.objects.filter(
user__id=user_id,
role__id=role_id,
).delete()

serializer = serializers.UserRoleLinkSerializer(data={
"user": new_lead.id,
"role": role_id,
}, context={"user_id": user_id})
if serializer.is_valid():
serializer.save()
return CustomResponse(general_message='Assigned new Campus Lead successfully').get_success_response()
return CustomResponse(message=serializer.errors).get_failure_response()

class TransferEnablerRoleAPI(APIView):
authentication_classes = [CustomizePermission]

@role_required([RoleType.CAMPUS_LEAD.value])
def post(self, request):
user_id = JWTUtils.fetch_user_id(request)
new_enabler_muid = request.data.get("new_enabler_muid", None)
if new_enabler_muid is None:
return CustomResponse(
general_message="Required data is missing"
).get_failure_response()

new_enabler = User.objects.filter(muid=new_enabler_muid).first()
if new_enabler is None:
return CustomResponse(
general_message="Can't find the user"
).get_failure_response()

user_org_link = get_user_college_link(user_id)
validate_new_enabler = UserOrganizationLink.objects.filter(
user__id=new_enabler.id,
org=user_org_link.org,
org__org_type=OrganizationType.COLLEGE.value,
is_alumni=False
).first()

if validate_new_enabler is None:
return CustomResponse(
general_message="Can't find the user in your college"
).get_failure_response()

role_id = Role.objects.filter(title=RoleType.LEAD_ENABLER.value).first()
if role_id is None:
return CustomResponse(
general_message="Can't find the role"
).get_failure_response()
role_id = role_id.id

current_enabler = UserRoleLink.objects.filter(
user__user_organization_link_user__org=user_org_link.org,
user__user_organization_link_user__org__org_type=OrganizationType.COLLEGE.value,
role__id=role_id
).first()
if current_enabler:
current_enabler.delete()

serializer = serializers.UserRoleLinkSerializer(data={
"user": new_enabler.id,
"role": role_id,
}, context={"user_id": user_id})
if serializer.is_valid():
serializer.save()
return CustomResponse(general_message='Assigned new Enabler Lead successfully').get_success_response()
return CustomResponse(message=serializer.errors).get_failure_response()

class TransferIGRoleAPI(APIView):
authentication_classes = [CustomizePermission]

@role_required([RoleType.CAMPUS_LEAD.value, RoleType.LEAD_ENABLER.value])
def get(self, request):
user_id = JWTUtils.fetch_user_id(request)
user_org_link = get_user_college_link(user_id)
ig_list = User.objects.filter(
user_organization_link_user__org=user_org_link.org,
user_organization_link_user__org__org_type=OrganizationType.COLLEGE.value,
).values_list('user_ig_link_user__ig__code', flat=True).distinct()

return CustomResponse(response={"ig_list":ig_list}).get_success_response()


@role_required([RoleType.CAMPUS_LEAD.value, RoleType.LEAD_ENABLER.value])
def post(self, request):
user_id = JWTUtils.fetch_user_id(request)
new_ig_muid = request.data.get("new_ig_muid", None)
ig_code = request.data.get("ig_code", None)

if new_ig_muid is None or ig_code is None:
return CustomResponse(
general_message="Required data is missing"
).get_failure_response()

new_ig = User.objects.filter(muid=new_ig_muid).first()
if new_ig is None:
return CustomResponse(
general_message="Can't find the user"
).get_failure_response()

user_org_link = get_user_college_link(user_id)
validate_ig = UserOrganizationLink.objects.filter(
user__id=new_ig.id,
org=user_org_link.org,
org__org_type=OrganizationType.COLLEGE.value,
is_alumni=False
).first()
if validate_ig is None:
return CustomResponse(
general_message="Can't find the user in your college"
).get_failure_response()

#need to change title according to the ig role
#below code filter role for title=ig_code+CampusLead
role_id = Role.objects.filter(title=f"{ig_code}CampusLead").first()
if role_id is None:
return CustomResponse(
general_message="Can't find the role"
).get_failure_response()
role_id = role_id.id

current_ig = UserRoleLink.objects.filter(
user__user_organization_link_user__org=user_org_link.org,
user__user_organization_link_user__org__org_type=OrganizationType.COLLEGE.value,
role__id=role_id
).first()
if current_ig:
current_ig.delete()

serializer = serializers.UserRoleLinkSerializer(data={
"user": new_ig.id,
"role": role_id,
}, context={"user_id": user_id})
if serializer.is_valid():
serializer.save()
return CustomResponse(general_message='Assigned new Ig lead successfully').get_success_response()
return CustomResponse(message=serializer.errors).get_failure_response()

21 changes: 20 additions & 1 deletion api/dashboard/campus/serializers.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import uuid
from datetime import timedelta

from django.db.models import Sum
from rest_framework import serializers

from db.organization import UserOrganizationLink, College
from db.task import KarmaActivityLog
from db.user import User
from db.user import User, UserRoleLink
from utils.types import OrganizationType
from utils.types import RoleType
from utils.utils import DateTimeUtils
Expand Down Expand Up @@ -190,3 +191,21 @@ class ListAluminiSerializer(serializers.Serializer):
class Meta:
fields = ("user_id", "full_name", "karma",
"muid", "rank", "level", "join_date")

class UserRoleLinkSerializer(serializers.ModelSerializer):

class Meta:
model = UserRoleLink
fields = [
"user",
"role",
]

def create(self, validated_data):
user_id = self.context.get("user_id")
validated_data["created_by_id"] = user_id
validated_data["id"] = uuid.uuid4()
validated_data["verified"] = True

user_role_link = UserRoleLink.objects.create(**validated_data)
return user_role_link
5 changes: 4 additions & 1 deletion api/dashboard/campus/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,8 @@
path("student-details/csv/", campus_views.CampusStudentDetailsCSVAPI.as_view(), name='student-details-csv'),
path("weekly-karma/", campus_views.WeeklyKarmaAPI.as_view(), name='weekly-karma-insights'),

path('change-student-type/<str:member_id>/', campus_views.ChangeStudentTypeAPI.as_view(), name='change-student-type')
path('change-student-type/<str:member_id>/', campus_views.ChangeStudentTypeAPI.as_view(), name='change-student-type'),
path('transfer-lead-role/', campus_views.TransferLeadRoleAPI.as_view(), name='transfer-lead-role'),
path('transfer-enabler-role/', campus_views.TransferEnablerRoleAPI.as_view(), name='transfer-enabler-role'),
path('transfer-ig-role/', campus_views.TransferIGRoleAPI.as_view(), name='transfer-lead-role'),
]
13 changes: 7 additions & 6 deletions api/dashboard/profile/profile_serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,11 +174,12 @@ class Meta:

def get_tasks(self, obj):
user_id = self.context.get("user_id")
user_lvl = UserLvlLink.objects.filter(
user__id=user_id).first().level.level_order
user_igs = UserIgLink.objects.filter(
user__id=user_id).values_list("ig__name", flat=True)
tasks = TaskList.objects.filter(level=obj)

if obj.level_order > 4:
tasks = tasks.filter(ig__name__in=user_igs)

data = []
for task in tasks:
Expand Down Expand Up @@ -386,8 +387,8 @@ class Meta:
def update(self, instance, validated_data):
user_id = JWTUtils.fetch_user_id(self.context.get("request"))

def create_karma_activity_log(task_title, karma_value):
task = TaskList.objects.filter(title=task_title).first()
def create_karma_activity_log(task_hashtag, karma_value):
task = TaskList.objects.filter(hashtag=task_hashtag).first()
if task:
if karma_value > 0:
karma_log = KarmaActivityLog.objects.create(
Expand Down Expand Up @@ -425,8 +426,8 @@ def create_karma_activity_log(task_title, karma_value):
if old_account_url in [None, ""] and account_url in [None, ""]:
pass
elif old_account_url is None or old_account_url == "":
create_karma_activity_log(f"social_{account}", 20)
create_karma_activity_log(f"#social_{account}", 20)
elif account_url is None or account_url == "":
create_karma_activity_log(f"social_{account}", -20)
create_karma_activity_log(f"#social_{account}", -20)

return super().update(instance, validated_data)
2 changes: 1 addition & 1 deletion db/task.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ class KarmaActivityLog(models.Model):
task = models.ForeignKey(TaskList, on_delete=models.CASCADE, related_name="karma_activity_log_task")
user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True,
related_name="karma_activity_log_user")
task_message_id = models.CharField(max_length=36)
task_message_id = models.CharField(max_length=36, blank=True, null=True)
lobby_message_id = models.CharField(max_length=36, blank=True, null=True)
dm_message_id = models.CharField(max_length=36, blank=True, null=True)
peer_approved = models.BooleanField(blank=True, null=True)
Expand Down

0 comments on commit 5c9e5d6

Please sign in to comment.