Completed
Push — master ( 2b3bff...10952a )
by Vijay
02:16 queued 01:05
created

Profile.is_profile_filled()   A

Complexity

Conditions 2

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
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, null=True)
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
    @property
65
    def is_profile_filled(self):
66
        if self.location:
67
            return True
68
        return False
69
70
    @cached_property
71
    def slug(self):
72
        return slugify(self.user.username, only_ascii=True)
73
74
    @property
75
    def get_workshop_details(self):
76
        return Workshop.objects.filter(presenter=self.user).order_by('-id')
77
78
    @property
79
    def get_workshop_completed_count(self):
80
        return len([x for x in
81
                    self.get_workshop_details if x.status == WorkshopStatus.COMPLETED])
82
83
    @property
84
    def get_workshop_upcoming_count(self):
85
        return len([x for x in
86
                    self.get_workshop_details if x.status == WorkshopStatus.ACCEPTED])
87
88
    @property
89
    def get_total_no_of_participants(self):
90
        return sum([x.no_of_participants for x in
91
                    self.get_workshop_details if x.status == WorkshopStatus.COMPLETED])
92
93
    @property
94
    def get_last_workshop_date(self):
95
        pass
96
97
    @property
98
    def get_avg_workshop_rating(self):
99
        # TODO: Complete!
100
        return 0
101
102
    @staticmethod
103
    def get_user_with_type(user_type=None):
104
        """
105
        Would return user with user type list in argument.
106
        Eg Collage POC, admin etc
107
        """
108
        return User.objects.filter(
109
            profile__usertype__display_name__in=user_type
110
        )
111
112
    @property
113
    def get_user_type(self):
114
        return [x.slug for x in self.usertype.all()]
115
116
    @property
117
    def get_interested_locations(self):
118
        return [x.name for x in self.interested_locations.all()]
119
120
    @property
121
    def get_graph_data(self):
122
        sections = WorkshopSections.objects.all()
123
        workshops = Workshop.objects.filter(
124
            presenter=self.user,
125
            status=WorkshopStatus.COMPLETED
126
        )
127
        if workshops:
128
            max_workshop_date = workshops.aggregate(
129
                models.Max('expected_date'))['expected_date__max']
130
            min_workshop_date = workshops.aggregate(
131
                models.Min('expected_date'))['expected_date__min']
132
            data = []
133
            if max_workshop_date and min_workshop_date:
134
                dates = [dt for dt in rrule(
135
                    MONTHLY, dtstart=min_workshop_date, until=max_workshop_date)]
136
                if dates:
137
                    for section in sections:
138
                        values = []
139
                        for d in dates:
140
                            y = workshops.filter(
141
                                expected_date__year=d.year,
142
                                expected_date__month=d.month,
143
                                workshop_section=section.pk).count()
144
                            values.append(
145
                                {'x': "{}-{}".format(d.year, d.month), 'y': y})
146
                        data.append({'key': section.name, 'values': values})
147
                    return json.dumps(data)
148
                else:
149
                    return []
150
            else:
151
                return []
152
        else:
153
            return []
154
155
    @classmethod
156
    def is_presenter(cls, user):
157
        return user.profile.usertype.filter(slug__iexact="tutor").exists()
158
159
    @classmethod
160
    def is_organiser(cls, user):
161
        return user.profile.usertype.filter(slug__icontains="poc").exists()
162
163
    @classmethod
164
    def is_regional_lead(cls, user):
165
        return user.profile.usertype.filter(slug__iexact="lead").exists()
166
167
    @classmethod
168
    def is_admin(cls, user):
169
        return user.profile.usertype.filter(slug__iexact="admin").exists()
170
171
172
def create_user_profile(sender, instance, created, **kwargs):
173
    if created:
174
        profile, created = Profile.objects.get_or_create(user=instance)
175
176
177
post_save.connect(
178
    create_user_profile, sender=User, dispatch_uid='create_user_profile')
179