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

WorkshopSections.__str__()   A

Complexity

Conditions 1

Size

Total Lines 2

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 1
dl 0
loc 2
rs 10
1
from django.contrib.auth.models import User
2
from django.core.validators import MaxValueValidator
3
from django.db import models
4
5
from wye.base.constants import (
6
    FeedbackType,
7
    WorkshopAction,
8
    WorkshopLevel,
9
    WorkshopStatus,
10
)
11
from wye.base.models import TimeAuditModel
12
from wye.organisations.models import Organisation
13
from wye.regions.models import Location
14
15
from .decorators import validate_action_param, validate_assignme_action
16
17
18
class WorkshopSections(TimeAuditModel):
19
    '''
20
    python2, Python3, Django, Flask, Gaming
21
    '''
22
    name = models.CharField(max_length=300, unique=True)
23
24
    class Meta:
25
        db_table = 'workshop_section'
26
27
    def __str__(self):
28
        return '{}'.format(self.name)
29
30
31
class Workshop(TimeAuditModel):
32
    no_of_participants = models.PositiveIntegerField(
33
        validators=[MaxValueValidator(1000)])
34
    expected_date = models.DateField()
35
    description = models.TextField()
36
    requester = models.ForeignKey(
37
        Organisation, related_name='workshop_requester')
38
    presenter = models.ManyToManyField(User, related_name='workshop_presenter')
39
    location = models.ForeignKey(Location, related_name='workshop_location')
40
    workshop_level = models.PositiveSmallIntegerField(
41
        choices=WorkshopLevel.CHOICES, verbose_name="Workshop Level")
42
    workshop_section = models.ForeignKey(WorkshopSections)
43
    is_active = models.BooleanField(default=True)
44
    status = models.PositiveSmallIntegerField(
45
        choices=WorkshopStatus.CHOICES, verbose_name="Current Status",
46
        default=WorkshopStatus.REQUESTED)
47
48
    class Meta:
49
        db_table = 'workshops'
50
51
    def __str__(self):
52
        return '{}-{}'.format(self.requester, self.workshop_section)
53
54
    def is_presenter(self, user):
55
        return self.presenter.filter(pk=user.pk).exists()
56
57
    def is_organiser(self, user):
58
        return self.requester.user.filter(pk=user.pk).exists()
59
60
    def manage_action(self, user, **kwargs):
61
        actions = {
62
            'accept': ("opt-in", self.assign_me),
63
            'reject': ("opt-out", self.assign_me),
64
            'publish': (WorkshopStatus.REQUESTED, self.set_status),
65
            'hold': (WorkshopStatus.HOLD, self.set_status),
66
            'assign': ""
67
        }
68
        if kwargs.get('action') not in actions:
69
            return {
70
                'status': False,
71
                'msg': 'Action not allowed'
72
            }
73
74
        action, func = actions.get(kwargs.get('action'))
75
        kwargs["action"] = action
76
        return func(user, **kwargs)
77
78
    def set_status(self, user, **kwargs):
79
        self.status = kwargs.get('action')
80
        self.save()
81
        return {
82
            'status': True,
83
            'msg': 'Workshop successfully updated.'}
84
85
    @validate_action_param(WorkshopAction.ACTIVE)
86
    def toggle_active(self, user, **kwargs):
87
        """
88
        Helper method to toggle is_active for the model.
89
        """
90
91
        action_map = {'active': True, 'deactive': False}
92
        action = kwargs.get('action')
93
        self.is_active = action_map.get(action)
94
        self.save()
95
        return {
96
            'status': True,
97
            'msg': 'Workshop successfully updated.'}
98
99
    # @validate_action_param(WorkshopAction.ASSIGNME)
100
    @validate_assignme_action
101
    def assign_me(self, user, **kwargs):
102
        """
103
        Method to assign workshop by presenter self.
104
        """
105
106
        action_map = {
107
            'opt-in': self.presenter.add,
108
            'opt-out': self.presenter.remove
109
        }
110
        message_map = {
111
            'opt-in': 'Assigned successfully.',
112
            'opt-out': 'Unassigned successfully.'
113
        }
114
        assigned = {
115
            'opt-in': True,
116
            'opt-out': False
117
        }
118
        action = kwargs.get('action')
119
        if assigned[action] and self.presenter.filter(pk=user.pk).exists():
120
            # This save has been added as fail safe
121
            # once the logic is consolidated may be
122
            # it can be removed
123
            self.status = WorkshopStatus.ACCEPTED
124
            self.save()
125
            return {
126
                'status': False,
127
                'msg': 'Workshop has already been assigned.'
128
            }
129
130
        func = action_map.get(action)
131
        func(user)
132
133
        if self.presenter.count() > 0:
134
            self.status = WorkshopStatus.ACCEPTED
135
        else:
136
            self.status = WorkshopStatus.DECLINED
137
        self.save()
138
139
        return {
140
            'status': True,
141
            'assigned': assigned[action],
142
            'msg': message_map[action],
143
            'notify': True
144
        }
145
146
    def get_presenter_list(self):
147
        return [user.get_full_name() for user in self.presenter.all()]
148
149
    def get_tweet(self, context):
150
        workshop = self
151
        date = workshop.expected_date
152
        topic = workshop.workshop_section
153
        organization = workshop.requester
154
        workshop_url = context.get('workshop_url', None)
155
        message = "{} workshop at {} on {} confirmed! Details at {}".format(
156
            topic, organization, date, workshop_url)
157
        if len(message) >= 140:
158
            message = "{} workshop on {} confirmed! Details at {}".format(
159
                topic, date, workshop_url)
160
161
        return message
162
163
164
class WorkshopRatingValues(TimeAuditModel):
165
    '''
166
    Requesting Rating values -2, -1, 0 , 1, 2
167
    '''
168
169
    name = models.CharField(max_length=300)
170
171
    class Meta:
172
        db_table = 'workshop_vote_value'
173
174
    def __str__(self):
175
        return '{}'.format(self.name)
176
177
    @classmethod
178
    def get_questions(cls):
179
        return cls.objects.values('name', 'pk')
180
181
182
class WorkshopFeedBack(TimeAuditModel):
183
    '''
184
    Requesting for Feedback from requester and Presenter
185
    '''
186
187
    workshop = models.ForeignKey(Workshop)
188
    comment = models.TextField()
189
    feedback_type = models.PositiveSmallIntegerField(
190
        choices=FeedbackType.CHOICES, verbose_name="User_type")
191
192
    class Meta:
193
        db_table = 'workshop_feedback'
194
195
    def __str__(self):
196
        return '{}'.format(self.workshop)
197
198
    @classmethod
199
    def save_feedback(cls, user, workshop_id, **kwargs):
200
        workshop = Workshop.objects.get(pk=workshop_id)
201
        presenter = workshop.is_presenter(user)
202
        organiser = workshop.is_organiser(user)
203
        comment = kwargs.get('comment', '')
204
        del kwargs['comment']
205
206
        if presenter:
207
            feedback_type = FeedbackType.PRESENTER
208
        elif organiser:
209
            feedback_type = FeedbackType.ORGANISATION
210
211
        workshop_feedback = cls.objects.create(
212
            workshop=workshop,
213
            comment=comment,
214
            feedback_type=feedback_type
215
        )
216
        WorkshopVoting.save_rating(workshop_feedback, **kwargs)
217
218
219
class WorkshopVoting(TimeAuditModel):
220
    workshop_feedback = models.ForeignKey(
221
        WorkshopFeedBack, related_name='workshop_feedback')
222
    workshop_rating = models.ForeignKey(
223
        WorkshopRatingValues, related_name='workshop_rating')
224
    rating = models.IntegerField()
225
226
    class Meta:
227
        db_table = 'workshop_votes'
228
229
    def __str__(self):
230
        return '{}-{}-{}'.format(self.workshop_feedback,
231
                                 self.workshop_rating,
232
                                 self.rating)
233
234
    @classmethod
235
    def save_rating(cls, workshop_feedback, **kwargs):
236
        object_list = [
237
            cls(workshop_feedback=workshop_feedback,
238
                workshop_rating_id=int(k), rating=v)
239
            for k, v in kwargs.items()
240
        ]
241
242
        cls.objects.bulk_create(object_list)
243