Skip to content

Commit

Permalink
Merge pull request #1764 from gtech-mulearn/dev-server
Browse files Browse the repository at this point in the history
urlshortner
  • Loading branch information
adnankattekaden authored Dec 7, 2023
2 parents f35ddde + 2646f47 commit f5af47c
Show file tree
Hide file tree
Showing 7 changed files with 182 additions and 84 deletions.
4 changes: 3 additions & 1 deletion .env.sample
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,6 @@ FR_DOMAIN_NAME=http://127.0.0.1:8000
BE_DOMAIN_NAME = http://127.0.0.1:8000
AUTH_DOMAIN=http://127.0.0.1:8000

PROTECTED_API_KEY =
PROTECTED_API_KEY =

SYSADMIN_ID =
86 changes: 86 additions & 0 deletions alter-scripts/alter-1.42.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import os
import sys
import uuid

import django
from decouple import config

from connection import execute
from utils.types import OrganizationType

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


def clg_levels_check():
results = execute(f"""
SELECT
org.id AS org_id,
uol.user_id AS user_id,
lvl.level_order AS lvl_order,
w.karma_last_updated_at AS karma_last_updated_at
FROM
user_organization_link AS uol
INNER JOIN
user_lvl_link AS ull ON uol.user_id = ull.user_id
INNER JOIN level AS lvl ON ull.level_id = lvl.id
INNER JOIN
wallet AS w ON w.user_id = uol.user_id
INNER JOIN
organization AS org ON uol.org_id = org.id
WHERE
org.org_type = {OrganizationType.COLLEGE.value}
AND w.karma_last_updated_at > DATE_SUB(NOW(), INTERVAL 6 MONTH)
AND org.id IN (
SELECT org.id FROM organization AS org
INNER JOIN user_organization_link url ON url.org_id = org.id
INNER JOIN wallet AS w ON w.user_id = url.user_id
WHERE w.karma_last_updated_at > DATE_SUB(NOW(), INTERVAL 6 MONTH)
GROUP BY org.id
HAVING COUNT(*) >= 20
)
ORDER BY lvl_order ASC
""")

data = defaultdict(lambda: defaultdict(list))

for result in results:
org_id, user_id, lvl_order = result[0], result[1], result[2]

for other_lvl_order in range(1, lvl_order + 1):
data[org_id][other_lvl_order].append(user_id)

clg_data = {}
for org_id, levels in data.items():
for lvl in range(1, 8):
if len(levels.get(lvl, [])) >= 20:
clg_data[org_id] = lvl
else:
break
print(f"Org ID: {org_id}, College Level: {lvl}")

return clg_data


def delete_colleges():
return execute("""DELETE FROM college""")


def insert_colleges(clgdata):
user_id = config("SYSADMIN_ID")
for org_id, lvl in clgdata.items():
execute(f"""
INSERT INTO college (id, level, org_id, updated_by, updated_at, created_by, created_at)
VALUES ('{uuid.uuid4()}', '{lvl}', '{org_id}', '{user_id}', NOW(), '{user_id}', NOW())
""")
return


if __name__ == "__main__":
data = clg_levels_check()
delete_colleges()
insert_colleges(data)
execute("UPDATE system_setting SET value = '1.42', updated_at = now() WHERE `key` = 'db.version';")
2 changes: 1 addition & 1 deletion alter-scripts/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@


def execute(query):
with pymysql.connect(**db_config) as connection:
with pymysql.connect(**db_config, autocommit=True) as connection:
with connection.cursor() as cursor:
cursor.execute(query)
return cursor.fetchall()
79 changes: 39 additions & 40 deletions api/dashboard/discord_moderator/discord_mod_views.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
from collections import defaultdict

from django.db.models import Q
from rest_framework.views import APIView
from utils.permission import CustomizePermission, JWTUtils, role_required

from db.task import KarmaActivityLog
from utils.permission import CustomizePermission
from utils.response import CustomResponse
from utils.types import RoleType
from utils.utils import CommonUtils
from .serializer import KarmaActivityLogSerializer
from db.task import KarmaActivityLog
from django.utils import timezone
from utils.utils import DateTimeUtils
from django.db.models import Count, Q


class TaskList(APIView):
Expand All @@ -25,40 +24,40 @@ class PendingTasks(APIView):
def get(self, request):
date = request.query_params.get("date")
if date:
tasks = KarmaActivityLog.objects.filter(created_at = date)
peerpending = tasks.filter(peer_approved = False).count()
appraiserpending = tasks.filter(appraiser_approved = False).count()
data = {'peer_pending':peerpending,'appraise_pending':appraiserpending}
return CustomResponse(response = data).get_success_response()

peerpending = KarmaActivityLog.objects.filter(peer_approved = False).count()
appraiserpending = KarmaActivityLog.objects.filter(appraiser_approved = False).count()
data = {'peer_pending':peerpending,'appraise_pending':appraiserpending}
return CustomResponse(response = data).get_success_response()

tasks = KarmaActivityLog.objects.filter(created_at=date)
peerpending = tasks.filter(peer_approved=False).count()
appraiserpending = tasks.filter(appraiser_approved=False).count()
data = {'peer_pending': peerpending, 'appraise_pending': appraiserpending}
return CustomResponse(response=data).get_success_response()

peerpending = KarmaActivityLog.objects.filter(peer_approved=False).count()
appraiserpending = KarmaActivityLog.objects.filter(appraiser_approved=False).count()
data = {'peer_pending': peerpending, 'appraise_pending': appraiserpending}
return CustomResponse(response=data).get_success_response()


class LeaderBoard(APIView):
authentication_classes = [CustomizePermission]

def get(self, request):
choice = request.query_params.get("option")
if choice == "peer":
data = {}
logs_with_peer_approval = KarmaActivityLog.objects.filter(Q(peer_approved_by__isnull=False) & ~Q(peer_approved_by = ''))
for obj in logs_with_peer_approval:
if data.get(obj.peer_approved_by.fullname) == None:
data[obj.peer_approved_by.fullname] = {"count":0,"muid":obj.peer_approved_by.muid }
data[obj.peer_approved_by.fullname]['count']+=1
return CustomResponse(response=data).get_success_response()

elif choice == "appraiser":
data = {}
logs_with_appraiser_approval = KarmaActivityLog.objects.filter(Q(appraiser_approved_by__isnull = False) & ~Q(appraiser_approved_by = ''))
for obj in logs_with_appraiser_approval:
if data.get(obj.appraiser_approved_by.fullname) == None:
data[obj.appraiser_approved_by.fullname] = {"count":0,"muid":obj.peer_approved_by.muid}
data[obj.appraiser_approved_by.fullname]['count']+=1
return CustomResponse(response=data).get_success_response()

else:
return CustomResponse(response="Bad Request").get_success_response()

choice = request.query_params.get("option", "peer")

approval_field = f"{choice}_approved_by"
logs_with_approval = KarmaActivityLog.objects.filter(
Q(**{f"{approval_field}__isnull": False}) & ~Q(**{approval_field: ''})
)

data = defaultdict(lambda: {"count": 0, "muid": None})

for obj in logs_with_approval:
approver_name = getattr(obj, approval_field).fullname
if data[approver_name]["muid"] is None:
data[approver_name]["muid"] = getattr(obj, approval_field).muid
data[approver_name]["count"] += 1

response_data = [
{"name": name, "count": info["count"], "muid": info["muid"]}
for name, info in data.items()
]

return CustomResponse(response=response_data).get_success_response()
28 changes: 13 additions & 15 deletions api/dashboard/organisation/serializers.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import uuid

from django.db import models
from django.db import transaction
from django.db.models import Count
from rest_framework import serializers
from django.db import models

from db.organization import (
Organization,
Expand All @@ -17,8 +18,6 @@
)
from utils.permission import JWTUtils
from utils.types import OrganizationType
from django.db import transaction
from django.forms.models import model_to_dict


class InstitutionSerializer(serializers.ModelSerializer):
Expand Down Expand Up @@ -117,7 +116,7 @@ def create(self, validated_data):
validated_data["updated_by_id"] = user_id
orgobj = Organization.objects.create(**validated_data)
if validated_data.get("org_type") == OrganizationType.COLLEGE.value:
College.objects.create(org = orgobj, created_by_id=user_id, updated_by_id = user_id )
College.objects.create(org=orgobj, created_by_id=user_id, updated_by_id=user_id)
return orgobj

def update(self, instance, validated_data):
Expand Down Expand Up @@ -275,8 +274,8 @@ def get_update_summary(self, instance):
# Simulate the transaction
for relation in Organization._meta.related_objects:
if isinstance(
relation,
(models.ForeignKey, models.OneToOneField, models.ManyToManyField),
relation,
(models.ForeignKey, models.OneToOneField, models.ManyToManyField),
):
related_model = relation.related_model
related_field_name = relation.field.name
Expand All @@ -287,7 +286,7 @@ def get_update_summary(self, instance):
field.name
for field in related_model._meta.fields
if isinstance(field, models.ForeignKey)
and field.related_model == Organization
and field.related_model == Organization
),
None,
)
Expand All @@ -298,7 +297,7 @@ def get_update_summary(self, instance):
continue

if existing_relations := related_model.objects.filter(
**{related_field_name: instance}
**{related_field_name: instance}
):
update_summary.append(
{
Expand Down Expand Up @@ -327,8 +326,8 @@ def update(self, instance, validated_data):
for relation in Organization._meta.related_objects:
# Determine related model and related field name
if isinstance(
relation,
(models.ForeignKey, models.OneToOneField, models.ManyToManyField),
relation,
(models.ForeignKey, models.OneToOneField, models.ManyToManyField),
):
related_model = relation.related_model
related_field_name = relation.field.name
Expand All @@ -340,7 +339,7 @@ def update(self, instance, validated_data):
field.name
for field in related_model._meta.fields
if isinstance(field, models.ForeignKey)
and field.related_model == Organization
and field.related_model == Organization
),
None,
)
Expand All @@ -356,7 +355,7 @@ def update(self, instance, validated_data):
# Handle OneToOne relationships: delete existing relation if it points to the instance
if isinstance(relation, (models.OneToOneField, models.OneToOneRel)):
if existing_relation := related_model.objects.filter(
**{related_field_name: instance}
**{related_field_name: instance}
).first():
existing_relation.delete()

Expand All @@ -370,7 +369,6 @@ def update(self, instance, validated_data):


class OrganizationKarmaTypeGetPostPatchDeleteSerializer(serializers.ModelSerializer):

class Meta:
model = OrgKarmaType
fields = [
Expand All @@ -388,7 +386,6 @@ def create(self, validated_data):


class OrganizationKarmaLogGetPostPatchDeleteSerializer(serializers.ModelSerializer):

class Meta:
model = OrgKarmaLog
fields = [
Expand All @@ -404,6 +401,7 @@ def create(self, validated_data):

return OrgKarmaLog.objects.create(**validated_data)


class OrganizationImportSerializer(serializers.ModelSerializer):
created_by_id = serializers.CharField(required=True, allow_null=False)
updated_by_id = serializers.CharField(required=True, allow_null=False)
Expand All @@ -429,4 +427,4 @@ def to_representation(self, instance):
representation['affiliation_id'] = instance.affiliation.title if instance.affiliation else None
representation['district_id'] = instance.district.name if instance.district else None

return representation
return representation
4 changes: 4 additions & 0 deletions api/dashboard/profile/profile_serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -379,6 +379,10 @@ def create_karma_activity_log(task_title, karma_value):
updated_by_id=user_id,
created_by_id=user_id,
)
Wallet.objects.filter(user_id=user_id).update(
karma=F("karma") + karma_value,
updated_by_id=user_id
)

for account, account_url in validated_data.items():
old_account_url = getattr(instance, account)
Expand Down
Loading

0 comments on commit f5af47c

Please sign in to comment.