Completed
Push — master ( 45f0c4...1295f2 )
by Vijay
9s
created

Profile.is_profile_filled()   B

Complexity

Conditions 7

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

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