Profile.get_graph_data()   D
last analyzed

Complexity

Conditions 8

Size

Total Lines 37

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 37
cc 8
rs 4
1
2
import json
3
from dateutil.rrule import rrule, MONTHLY
4
from django.contrib.auth.models import User
5
from django.db import models
6
from django.db.models.signals import post_save
7
from django.utils.functional import cached_property
8
9
from slugify import slugify
10
from wye.base.constants import WorkshopLevel, WorkshopStatus
11
from wye.regions.models import Location, State
12
from wye.workshops.models import Workshop, WorkshopSections
13
from wye.organisations.models import Organisation
14
15
16
class UserType(models.Model):
17
    '''
18
    USER_TYPE = ['Tutor', 'Regional Lead', 'College POC','admin', 'Volunteer']
19
    '''
20
    slug = models.CharField(max_length=100,
21
                            verbose_name="slug")
22
    display_name = models.CharField(
23
        max_length=300, verbose_name="Display Name")
24
    active = models.BooleanField(default=1)
25
26
    class Meta:
27
        db_table = 'users_type'
28
        verbose_name = 'UserType'
29
        verbose_name_plural = 'UserTypes'
30
        ordering = ('-id',)
31
32
    def __str__(self):
33
        return '{}'.format(self.display_name)
34
35
36
class Profile(models.Model):
37
    user = models.OneToOneField(User, primary_key=True, related_name='profile')
38
    mobile = models.CharField(max_length=10, blank=False, null=True)
39
    occupation = models.CharField(
40
        null=True, blank=True, max_length=300, verbose_name=u"Occupation")
41
    work_location = models.CharField(
42
        null=True, blank=True, max_length=500, verbose_name=u"Organisaiton/Company")
43
    work_experience = models.FloatField(
44
        null=True, blank=True, verbose_name=u"Work Experience(If Any)")
45
    no_workshop = models.IntegerField(
46
        verbose_name=u"Workshop conducted(apart from pythonexpress)",
47
        default=0)
48
    is_mobile_visible = models.BooleanField(default=False)
49
    is_email_visible = models.BooleanField(default=False)
50
51
    enable_notifications = models.BooleanField(
52
        default=True,
53
        verbose_name=u"Email Notification")
54
55
    usertype = models.ManyToManyField(UserType)
56
57
    interested_sections = models.ManyToManyField(WorkshopSections)
58
    interested_level = models.PositiveSmallIntegerField(
59
        choices=WorkshopLevel.CHOICES,
60
        verbose_name="Interested Workshop Level",
61
        null=True, blank=True)
62
    interested_locations = models.ManyToManyField(
63
        Location)
64
    interested_states = models.ManyToManyField(
65
        State,
66
        verbose_name=u"Interested State *")
67
    location = models.ForeignKey(
68
        Location, related_name="user_location", null=True)
69
70
    github = models.URLField(null=True, blank=True)
71
    facebook = models.URLField(null=True, blank=True)
72
    googleplus = models.URLField(null=True, blank=True)
73
    linkedin = models.URLField(null=True, blank=True)
74
    twitter = models.URLField(null=True, blank=True)
75
    slideshare = models.URLField(null=True, blank=True)
76
    picture = models.ImageField(
77
        upload_to='images/', default='images/newuser.png')
78
79
    class Meta:
80
        db_table = 'user_profile'
81
        verbose_name = 'UserProfile'
82
        verbose_name_plural = 'UserProfiles'
83
84
    def __str__(self):
85
        return '{} {}'.format(self.user, self.slug)
86
87
    @property
88
    def is_profile_filled(self):
89
        if ('tutor' in [x.slug for x in self.usertype.all()]):
90
            if (self.location and
91
                    self.interested_level and
92
                    self.interested_states and
93
                    self.interested_sections):
94
                return True
95
            return False
96
        if self.location:
97
            return True
98
        return False
99
100
    @cached_property
101
    def slug(self):
102
        return slugify(
103
            self.user.username,
104
            only_ascii=True)
105
106
    @property
107
    def get_workshop_details(self):
108
        return Workshop.objects.filter(is_active=True).filter(
109
            presenter=self.user).order_by('-id')
110
111
    @property
112
    def can_create_organisation(self):
113
        org_count = Organisation.objects.filter(
114
            created_by=self.user).count()
115
        return False if org_count > 5 else True
116
117
    @property
118
    def get_workshop_completed_count(self):
119
        return len([x for x in
120
                    self.get_workshop_details if (
121
                        x.status in [
122
                            WorkshopStatus.COMPLETED,
123
                            WorkshopStatus.FEEDBACK_PENDING])])
124
125
    @property
126
    def get_workshop_upcoming_count(self):
127
        return len([x for x in
128
                    self.get_workshop_details if (
129
                        x.status == WorkshopStatus.ACCEPTED)])
130
131
    @property
132
    def get_total_no_of_participants(self):
133
        return sum([x.no_of_participants for x in
134
                    self.get_workshop_details if (
135
                        x.status == WorkshopStatus.COMPLETED)])
136
137
    @property
138
    def get_last_workshop_date(self):
139
        pass
140
141
    @property
142
    def get_avg_workshop_rating(self):
143
        # TODO: Complete!
144
        return 0
145
146
    @staticmethod
147
    def get_user_with_type(user_type=None):
148
        """
149
        Would return user with user type list in argument.
150
        Eg Collage POC, admin etc
151
        """
152
        return User.objects.filter(
153
            profile__usertype__display_name__in=user_type
154
        )
155
156
    @property
157
    def get_user_type(self):
158
        return [x.slug for x in self.usertype.all()]
159
160
    @property
161
    def get_interested_locations(self):
162
        return [x.name for x in self.interested_locations.all()]
163
164
    @property
165
    def get_graph_data(self):
166
        sections = WorkshopSections.objects.all()
167
        workshops = Workshop.objects.filter(
168
            presenter=self.user,
169
            status=WorkshopStatus.COMPLETED,
170
            is_active=True
171
        )
172
        if workshops:
173
            max_workshop_date = workshops.aggregate(
174
                models.Max('expected_date'))['expected_date__max']
175
            min_workshop_date = workshops.aggregate(
176
                models.Min('expected_date'))['expected_date__min']
177
            data = []
178
            if max_workshop_date and min_workshop_date:
179
                dates = [dt for dt in rrule(
180
                    MONTHLY,
181
                    dtstart=min_workshop_date,
182
                    until=max_workshop_date)]
183
                if dates:
184
                    for section in sections:
185
                        values = []
186
                        for d in dates:
187
                            y = workshops.filter(
188
                                expected_date__year=d.year,
189
                                expected_date__month=d.month,
190
                                workshop_section=section.pk).count()
191
                            values.append(
192
                                {'x': "{}-{}".format(d.year, d.month), 'y': y})
193
                        data.append({'key': section.name, 'values': values})
194
                    return json.dumps(data)
195
                else:
196
                    return []
197
            else:
198
                return []
199
        else:
200
            return []
201
202
    @classmethod
203
    def is_presenter(cls, user):
204
        return user.profile.usertype.filter(slug__iexact="tutor").exists()
205
206
    @classmethod
207
    def is_organiser(cls, user):
208
        return user.profile.usertype.filter(slug__icontains="poc").exists()
209
210
    @classmethod
211
    def is_regional_lead(cls, user):
212
        return user.profile.usertype.filter(slug__iexact="lead").exists()
213
214
    @classmethod
215
    def is_admin(cls, user):
216
        return user.profile.usertype.filter(slug__iexact="admin").exists()
217
218
    @classmethod
219
    def is_coordinator(cls, user):
220
        return user.profile.usertype.filter(
221
            slug__iexact="coordinator").exists()
222
223
    @classmethod
224
    def is_volunteer(cls, user):
225
        return user.profile.usertype.filter(slug__iexact="volunteer").exists()
226
227
228
def create_user_profile(sender, instance, created, **kwargs):
229
    if created:
230
        profile, created = Profile.objects.get_or_create(user=instance)
231
        profile.usertype.add(UserType.objects.get(slug='tutor'))
232
233
234
post_save.connect(
235
    create_user_profile, sender=User, dispatch_uid='create_user_profile')
236