Skip to content

Commit

Permalink
Badge titles on user's profile (#524)
Browse files Browse the repository at this point in the history
* Use same border radius for next and prev buttons

* refactor button border radius code

* reverted master

* automated and custom badges on user's profile

* initially populate badges table

* #1 patch after review

* feature: change original badge title from admin panel

* migration file of badge table

Co-authored-by: Deepanshu039 <[email protected]>
  • Loading branch information
Deepanshu039 and Deepanshu039 authored Sep 6, 2022
1 parent 7415c8f commit 2599069
Show file tree
Hide file tree
Showing 13 changed files with 316 additions and 35 deletions.
1 change: 1 addition & 0 deletions zubhub_backend/compose/web/dev/start
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ python /zubhub_backend/zubhub/manage.py createcachetable
python /zubhub_backend/zubhub/manage.py populate_countries
python /zubhub_backend/zubhub/manage.py populate_categories
python /zubhub_backend/zubhub/manage.py populate_initial_creator_tags
python /zubhub_backend/zubhub/manage.py populate_initial_badges

exec /usr/local/bin/gunicorn zubhub.wsgi --reload --threads=3 --timeout 155 --bind 0.0.0.0:8000 \
--access-logfile - --error-logfile - --chdir /zubhub_backend/zubhub
1 change: 1 addition & 0 deletions zubhub_backend/compose/web/prod/start
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ python /zubhub_backend/zubhub/manage.py createcachetable
python /zubhub_backend/zubhub/manage.py populate_countries
python /zubhub_backend/zubhub/manage.py populate_initial_creator_tags
python /zubhub_backend/zubhub/manage.py populate_categories
python /zubhub_backend/zubhub/manage.py populate_initial_badges

exec /usr/local/bin/gunicorn zubhub.wsgi --threads=3 --timeout 155 --bind 0.0.0.0:8000 \
--access-logfile - --error-logfile - --chdir /zubhub_backend/zubhub
30 changes: 26 additions & 4 deletions zubhub_backend/zubhub/creators/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from django.db import transaction
from .models import PhoneNumber, Setting, CreatorGroup, CreatorTag
from .models import PhoneNumber, Setting, CreatorGroup, CreatorTag, Badge

from .utils import (send_group_invite_notification,
custom_set_creatortags_queryset,
Expand All @@ -21,6 +21,13 @@ def tags(obj):
return ", ".join(tags)
return None

def badges(obj):
if obj:
badges = []
for badge in obj.badges.all():
badges.append(badge.badge_title)
return ", ". join(badges)
return None

def group_projects(obj):
if obj:
Expand Down Expand Up @@ -142,7 +149,10 @@ class CreatorAdmin(UserAdmin):
('followers',),
('followers_count',),
('following_count',),
('projects_count',)
('projects_count',),
('total_likes',),
('total_views',),
('badges',),
)
}),
('Important Dates', {
Expand All @@ -160,9 +170,9 @@ class CreatorAdmin(UserAdmin):
)


list_display = UserAdmin.list_display + (tags, active,)
list_display = UserAdmin.list_display + (tags, active, badges)
list_per_page = 50 ## paginate when more than 50 items
readonly_fields = UserAdmin.readonly_fields + ('avatar',) + ('followers_count',) + ('following_count',) + ('projects_count',)
readonly_fields = UserAdmin.readonly_fields + ('avatar',) + ('followers_count',) + ('following_count',) + ('projects_count',) + ('total_likes',) + ('total_views',)
actions = ["activate_creators", "deactivate_creators"]

## disable the ability to add a new creator from the admin for now.
Expand Down Expand Up @@ -211,10 +221,22 @@ def save_model(self, request, obj, form, change):
super(CreatorAdmin, self).save_model(
request, obj, form, change)

class BadgeAdmin(admin.ModelAdmin):
list_display= ["badge_title", "type", "threshold_value", "id", used_by]
fields = ('type', 'badge_title', 'threshold_value', 'id',)
readonly_fields= ( 'id', 'type',)

def has_delete_permission(self, request, obj=None):
# Disable delete
return False

# disable the ability to add a new badge from the admin for now.
def has_add_permission(self, request, obj=None):
return False

admin.site.register(Creator, CreatorAdmin)
admin.site.register(PhoneNumber, PhoneNumberAdmin)
admin.site.register(Setting, SettingAdmin)
admin.site.register(CreatorGroup, CreatorGroupAdmin)
admin.site.register(CreatorTag, CreatorTagAdmin)
admin.site.register(Badge, BadgeAdmin)
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
Hatchling:0:1
Flying Bird:10:1
Master of the sky:50:1
Expert Builder:100:1
Helping Hand:10:2
Always Available:500:2
Expert Advisor:1000:2
Getting Famous:10:3
Person of Interest:100:3
Popular Projects:5000:3
Idea Factory:100000:3
Interesting Projects:10:4
Favourite Kid:500:4
Captain Projects:1000:4
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
from creators.models import Badge
from django.core.management.base import BaseCommand


class Command(BaseCommand):
help = 'Populate Badge table with initial badges'

def handle(self, *args, **kwargs):
if Badge.objects.all().count() == 0:
with open("./zubhub/creators/management/commands/initial_badges.txt", "r") as badges:
badges = badges.readlines()
for badge in badges:
remove_col=badge.split(':')
remove_col[2]=remove_col[2].split('\n')[0]
title=remove_col[0]
value=int(remove_col[1])
category_type=int(remove_col[2])
Badge.objects.create(badge_title = title, threshold_value=value,
type= category_type )
self.stdout.write(self.style.SUCCESS('The Badge table has been successfully populated!'))
else:
self.stdout.write(self.style.NOTICE('The Badge table is already populated'))
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Generated by Django 3.2 on 2022-08-22 08:42

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('creators', '0008_auto_20220222_0254'),
]

operations = [
migrations.CreateModel(
name='Badge',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('type', models.PositiveSmallIntegerField(choices=[(1, 'Projects'), (2, 'Comments'), (3, 'Views'), (4, 'Likes')])),
('threshold_value', models.IntegerField(blank=True, default=0)),
('badge_title', models.CharField(default='', max_length=225)),
],
),
migrations.AlterField(
model_name='setting',
name='contact',
field=models.PositiveSmallIntegerField(blank=True, choices=[(1, 'WHATSAPP'), (2, 'EMAIL'), (3, 'SMS'), (4, 'WEB')], default=3, null=True),
),
migrations.AddField(
model_name='creator',
name='badges',
field=models.ManyToManyField(blank=True, related_name='creators', to='creators.Badge'),
),
]
28 changes: 27 additions & 1 deletion zubhub_backend/zubhub/creators/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from .tasks import update_creator_tag_index_task
from .managers import PhoneNumberManager
from .model_utils import user_phone
from django.db.models import Sum

try:
from allauth.account import app_settings as allauth_settings
Expand Down Expand Up @@ -54,6 +55,21 @@ def save(self, *args, **kwargs):
update_creator_tag_index_task.delay()
super().save(*args, **kwargs)

class Badge(models.Model):
class Type(models.IntegerChoices):
PROJECTS = 1
COMMENTS = 2
VIEWS = 3
LIKES = 4

type = models.PositiveSmallIntegerField(
choices=Type.choices,
)
threshold_value = models.IntegerField(blank=True, default=0)
badge_title = models.CharField(blank=False, default="", max_length=225)

def __str__(self):
return self.badge_title

class Creator(AbstractUser):

Expand All @@ -72,10 +88,20 @@ class Creator(AbstractUser):
projects_count = models.IntegerField(blank=True, default=0)
tags = models.ManyToManyField(CreatorTag, blank=True, related_name="creators")
search_vector = SearchVectorField(null=True)

badges = models.ManyToManyField(Badge, blank=True, related_name="creators" )
class Meta:
indexes = (GinIndex(fields=["search_vector"]),)

@property
def total_likes(self):
total_likes= self.projects.aggregate(Sum("likes_count"))["likes_count__sum"]
return total_likes

@property
def total_views(self):
total_views= self.projects.aggregate(Sum("views_count"))["views_count__sum"]
return total_views

def save(self, *args, **kwargs):
if not self.avatar:
self.avatar = 'https://robohash.org/{0}'.format(self.username)
Expand Down
17 changes: 12 additions & 5 deletions zubhub_backend/zubhub/creators/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from django.contrib.auth import get_user_model

from .admin import badges
from .models import Location, PhoneNumber
from allauth.account.models import EmailAddress
from rest_auth.registration.serializers import RegisterSerializer
Expand All @@ -25,14 +27,17 @@ class CreatorMinimalSerializer(serializers.ModelSerializer):
tags = serializers.SlugRelatedField(slug_field="name",
read_only=True,
many=True)
badges = serializers.SlugRelatedField(slug_field="badge_title",
read_only=True,
many=True)

class Meta:
model = Creator

fields = ('id', 'username', 'avatar', 'comments', 'bio', 'followers',
'following_count', 'projects_count', 'members_count', 'tags')
'following_count', 'projects_count', 'members_count', 'tags', 'badges')

read_only_fields = ["id", "projects_count", "following_count", "tags"]
read_only_fields = ["id", "projects_count", "following_count", "tags", "badges"]

def get_members_count(self, obj):
if hasattr(obj, "creatorgroup"):
Expand Down Expand Up @@ -80,16 +85,18 @@ class CreatorSerializer(CreatorMinimalSerializer):
tags = serializers.SlugRelatedField(slug_field="name",
read_only=True,
many=True)

badges = serializers.SlugRelatedField(slug_field="badge_title",
read_only=True,
many=True)
class Meta:
model = Creator

fields = ('id', 'username', 'email', 'phone', 'avatar', 'location',
'comments', 'dateOfBirth', 'bio', 'followers',
'following_count', 'projects_count', 'members_count', 'tags')
'following_count', 'projects_count', 'members_count', 'tags', 'badges')

read_only_fields = [
"id", "projects_count", "following_count", "dateOfBirth", "tags"
"id", "projects_count", "following_count", "dateOfBirth", "tags", "badges"
]

def validate_email(self, email):
Expand Down
58 changes: 57 additions & 1 deletion zubhub_backend/zubhub/creators/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,10 @@
from activitylog.models import Activitylog
from activitylog.utils import push_activity
from notifications.utils import push_notification, get_notification_template_name
from creators.models import Creator
from creators.models import Creator, Badge
from projects.models import Project, Comment
from django.template.loader import render_to_string
from django.db.models import Sum

try:
from allauth.account.adapter import get_adapter
Expand Down Expand Up @@ -464,3 +466,57 @@ def send_notification(users: List[Creator], source: Creator, contexts,
# EmailAddress.objects.create(
# user=user, email=email, primary=False, verified=False
# )


def remove_initial_titles(creator, ids):
for id in ids:
creator.badges.remove(Badge.objects.get(id= id))

def add_titles(creator, count, ids):
for id in ids:
value = Badge.objects.get(id= id).threshold_value
if count > value:
creator.badges.add(Badge.objects.get(id = id))
break

def set_badge_like_category(creator):
likes_count = (Project.objects.filter(creator= creator)
.aggregate(Sum(('likes_count')))["likes_count__sum"])

badge_ids = [14, 13, 12]

remove_initial_titles(creator, badge_ids)
add_titles(creator, likes_count, badge_ids)

def set_badge_view_category(creator):
views_count = (Project.objects.filter(creator= creator).aggregate(
Sum(('views_count')))["views_count__sum"])

badge_ids = [11, 10, 9, 8]

remove_initial_titles(creator, badge_ids)
add_titles(creator, views_count, badge_ids)

def set_badge_comment_category(creator):
creator_id = creator.id
comments_count = Comment.objects.filter(creator__id= creator_id).count()

badge_ids = [7, 6, 5]

remove_initial_titles(creator, badge_ids)
add_titles(creator, comments_count, badge_ids)

def set_badge_project_category(creator, projects_count):
project_count_before_del = creator.projects_count

if(projects_count < project_count_before_del):
queryset = Project.objects.filter(creator= creator)
if( queryset.exists()):
set_badge_view_category(creator)
set_badge_like_category(creator)
set_badge_comment_category(creator)

badge_ids = [4, 3, 2, 1]

remove_initial_titles(creator, badge_ids)
add_titles(creator, projects_count, badge_ids)
Loading

0 comments on commit 2599069

Please sign in to comment.