Completed
Push — master ( ac4cc2...edf0e4 )
by Vijay
01:10
created

Profile.get_graph_data()   D

Complexity

Conditions 8

Size

Total Lines 34

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 8
dl 0
loc 34
rs 4
1
import json
2
3
from django.contrib.auth.models import User
4
from django.db import models
5
from django.db.models.signals import post_save
6
from django.utils.functional import cached_property
7
8
from dateutil.rrule import rrule, MONTHLY
9
from slugify import slugify
10
from wye.base.constants import WorkshopStatus
11
from wye.regions.models import Location
12
from wye.workshops.models import Workshop, WorkshopSections
13
14
15
# from django.dispatch import receiver
16
# from rest_framework.authtoken.models import Token
17
class UserType(models.Model):
18
    '''
19
    USER_TYPE = ['Tutor', 'Regional Lead', 'College POC','admin']
20
    '''
21
    slug = models.CharField(max_length=100,
22
                            verbose_name="slug")
23
    display_name = models.CharField(
24
        max_length=300, verbose_name="Display Name")
25
    active = models.BooleanField(default=1)
26
27
    class Meta:
28
        db_table = 'users_type'
29
        verbose_name = 'UserType'
30
        verbose_name_plural = 'UserTypes'
31
        ordering = ('-id',)
32
33
    def __str__(self):
34
        return '{}'.format(self.display_name)
35
36
37
class Profile(models.Model):
38
    user = models.OneToOneField(User, primary_key=True, related_name='profile')
39
    mobile = models.CharField(max_length=10, blank=False, null=True)
40
    is_mobile_visible = models.BooleanField(default=False)
41
    is_email_visible = models.BooleanField(default=False)
42
    usertype = models.ManyToManyField(UserType)
43
    interested_sections = models.ManyToManyField(WorkshopSections)
44
    interested_locations = models.ManyToManyField(Location)
45
    location = models.ForeignKey(
46
        Location, related_name="user_location", null=True)
47
    github = models.URLField(null=True, blank=True)
48
    facebook = models.URLField(null=True, blank=True)
49
    googleplus = models.URLField(null=True, blank=True)
50
    linkedin = models.URLField(null=True, blank=True)
51
    twitter = models.URLField(null=True, blank=True)
52
    slideshare = models.URLField(null=True, blank=True)
53
    picture = models.ImageField(
54
        upload_to='images/', default='images/newuser.png')
55
56
    class Meta:
57
        db_table = 'user_profile'
58
        verbose_name = 'UserProfile'
59
        verbose_name_plural = 'UserProfiles'
60
61
    def __str__(self):
62
        return '{} {}'.format(self.user, self.slug)
63
64
    @cached_property
65
    def slug(self):
66
        return slugify(self.user.username, only_ascii=True)
67
68
    @property
69
    def get_workshop_details(self):
70
        return Workshop.objects.filter(presenter=self.user).order_by('-id')
71
72
    @property
73
    def get_workshop_completed_count(self):
74
        return len([x for x in
75
                    self.get_workshop_details if x.status == WorkshopStatus.COMPLETED])
76
77
    @property
78
    def get_workshop_upcoming_count(self):
79
        return len([x for x in
80
                    self.get_workshop_details if x.status == WorkshopStatus.ACCEPTED])
81
82
    @property
83
    def get_total_no_of_participants(self):
84
        return sum([x.no_of_participants for x in
85
                    self.get_workshop_details if x.status == WorkshopStatus.COMPLETED])
86
87
    @property
88
    def get_last_workshop_date(self):
89
        pass
90
91
    @property
92
    def get_avg_workshop_rating(self):
93
        # TODO: Complete!
94
        return 0
95
96
    @staticmethod
97
    def get_user_with_type(user_type=None):
98
        """
99
        Would return user with user type list in argument.
100
        Eg Collage POC, admin etc
101
        """
102
        return User.objects.filter(
103
            profile__usertype__display_name__in=user_type
104
        )
105
106
    @property
107
    def get_user_type(self):
108
        return [x.slug for x in self.usertype.all()]
109
110
    @property
111
    def get_interested_locations(self):
112
        return [x.name for x in self.interested_locations.all()]
113
114
    @property
115
    def get_graph_data(self):
116
        sections = WorkshopSections.objects.all()
117
        workshops = Workshop.objects.filter(
118
            presenter=self.user,
119
            status=WorkshopStatus.COMPLETED
120
        )
121
        if workshops:
122
            max_workshop_date = workshops.aggregate(
123
                models.Max('expected_date'))['expected_date__max']
124
            min_workshop_date = workshops.aggregate(
125
                models.Min('expected_date'))['expected_date__min']
126
            data = []
127
            if max_workshop_date and min_workshop_date:
128
                dates = [dt for dt in rrule(
129
                    MONTHLY, dtstart=min_workshop_date, until=max_workshop_date)]
130
                if dates:
131
                    for section in sections:
132
                        values = []
133
                        for d in dates:
134
                            y = workshops.filter(
135
                                expected_date__year=d.year,
136
                                expected_date__month=d.month,
137
                                workshop_section=section.pk).count()
138
                            values.append(
139
                                {'x': "{}-{}".format(d.year, d.month), 'y': y})
140
                        data.append({'key': section.name, 'values': values})
141
                    return json.dumps(data)
142
                else:
143
                    return []
144
            else:
145
                return []
146
        else:
147
            return []
148
149
    @classmethod
150
    def is_presenter(cls, user):
151
        return user.profile.usertype.filter(slug__iexact="tutor").exists()
152
153
    @classmethod
154
    def is_organiser(cls, user):
155
        return user.profile.usertype.filter(slug__icontains="poc").exists()
156
157
    @classmethod
158
    def is_regional_lead(cls, user):
159
        return user.profile.usertype.filter(slug__iexact="lead").exists()
160
161
    @classmethod
162
    def is_admin(cls, user):
163
        return user.profile.usertype.filter(slug__iexact="admin").exists()
164
# @receiver(post_save, sender=settings.AUTH_USER_MODEL)
165
# def create_auth_token(sender, instance=None, created=False, **kwargs):
166
#     if created:
167
#         token, created = Token.objects.get_or_create(user=instance)
168
169
170
def create_user_profile(sender, instance, created, **kwargs):
171
    if created:
172
        profile, created = Profile.objects.get_or_create(user=instance)
173
174
175
post_save.connect(
176
    create_user_profile, sender=User, dispatch_uid='create_user_profile')
177