class Application(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) task = models.ForeignKey(Task, on_delete=models.CASCADE) accepted = models.BooleanField(default=False) responded = models.BooleanField(default=False) pitch = models.CharField(max_length=1000, blank=True, null=True) hours_needed = models.PositiveIntegerField(blank=True, null=True) hours_available = models.PositiveIntegerField(blank=True, null=True) remarks = models.TextField( blank=True, null=True) # These will also be delivered as messages to the client deliver_at = models.DateTimeField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) channels = GenericRelation(Channel, related_query_name='task_applications') def __unicode__(self): return '%s - %s' % (self.user.get_short_name() or self.user.username, self.task.summary) class Meta: unique_together = ('user', 'task') @staticmethod @allow_staff_or_superuser def has_read_permission(request): return True @allow_staff_or_superuser def has_object_read_permission(self, request): return self.has_object_update_permission(request) @staticmethod @allow_staff_or_superuser def has_write_permission(request): return request.user.type == USER_TYPE_DEVELOPER @staticmethod @allow_staff_or_superuser def has_update_permission(request): return True @allow_staff_or_superuser def has_object_write_permission(self, request): return request.user == self.user @allow_staff_or_superuser def has_object_update_permission(self, request): # Task owner can update applications return request.user == self.user or request.user == self.task.user
class Document(models.Model): project = models.ForeignKey(Project) type = models.CharField(choices=PROJECT_DOCUMENT_CHOICES, max_length=30, default=DOC_OTHER) url = models.URLField(blank=True, null=True) file = models.FileField(verbose_name='Upload', upload_to='documents/%Y/%m/%d', blank=True, null=True) title = models.CharField(max_length=100, blank=True, null=True) description = models.TextField(blank=True, null=True) created_by = models.ForeignKey(settings.AUTH_USER_MODEL) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) legacy_id = models.PositiveIntegerField(blank=True, null=True) migrated_at = models.DateTimeField(blank=True, null=True) def __str__(self): return '{} | {}'.format(self.type, self.project) class Meta: ordering = ['-created_at'] @staticmethod @allow_staff_or_superuser def has_read_permission(request): return True @allow_staff_or_superuser def has_object_read_permission(self, request): return self.project.is_participant(request.user) @staticmethod @allow_staff_or_superuser def has_write_permission(request): return request.user.is_project_manager or request.user.is_project_owner @allow_staff_or_superuser def has_object_write_permission(self, request): return request.user == self.created_by @property def download_url(self): if self.file: return '{}{}'.format( not re.match(r'://', self.file.url) and TUNGA_URL or '', self.file.url) elif self.url: return self.url return None
class ProgressReport(models.Model): event = models.OneToOneField(ProgressEvent, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) status = models.PositiveSmallIntegerField( choices=PROGRESS_REPORT_STATUS_CHOICES, help_text=','.join([ '%s - %s' % (item[0], item[1]) for item in PROGRESS_REPORT_STATUS_CHOICES ])) percentage = models.PositiveIntegerField( validators=[MinValueValidator(0), MaxValueValidator(100)]) accomplished = models.TextField() next_steps = models.TextField(blank=True, null=True) remarks = models.TextField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) uploads = GenericRelation(Upload, related_query_name='progress_reports') def __unicode__(self): return '{0} - {1}%'.format(self.event, self.percentage) @staticmethod @allow_staff_or_superuser def has_read_permission(request): return True @allow_staff_or_superuser def has_object_read_permission(self, request): return self.event.task.has_object_read_permission(request) @staticmethod @allow_staff_or_superuser def has_write_permission(request): return request.user.type == USER_TYPE_DEVELOPER @allow_staff_or_superuser def has_object_write_permission(self, request): return request.user == self.user
class ProgressReport(models.Model): event = models.ForeignKey(ProgressEvent, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) # Status details status = models.CharField(max_length=50, choices=PROGRESS_REPORT_STATUS_CHOICES, help_text=','.join([ '%s - %s' % (item[0], item[1]) for item in PROGRESS_REPORT_STATUS_CHOICES ]), blank=True, null=True) percentage = models.PositiveIntegerField( validators=[MinValueValidator(0), MaxValueValidator(100)], blank=True, null=True) accomplished = models.TextField(blank=True, null=True) todo = models.TextField(blank=True, null=True) obstacles = models.TextField(blank=True, null=True) obstacles_prevention = models.TextField(blank=True, null=True) remarks = models.TextField(blank=True, null=True) stuck_reason = models.CharField( max_length=50, choices=PROGRESS_REPORT_STUCK_REASON_CHOICES, help_text=','.join([ '%s - %s' % (item[0], item[1]) for item in PROGRESS_REPORT_STUCK_REASON_CHOICES ]), blank=True, null=True) stuck_details = models.TextField(blank=True, null=True) # Deliverables rate_deliverables = models.PositiveIntegerField( validators=[MinValueValidator(1), MaxValueValidator(5)], blank=True, null=True) # Deadline Info started_at = models.DateTimeField(blank=True, null=True) last_deadline_met = models.NullBooleanField(blank=True, null=True) deadline_miss_communicated = models.NullBooleanField(blank=True, null=True) deadline_report = models.TextField(blank=True, null=True) next_deadline = models.DateTimeField(blank=True, null=True) next_deadline_meet = models.NullBooleanField(blank=True, null=True) next_deadline_fail_reason = models.TextField(blank=True, null=True) # PMs only team_appraisal = models.TextField(blank=True, null=True) # Clients only deliverable_satisfaction = models.NullBooleanField(blank=True, null=True) rate_communication = models.PositiveIntegerField( validators=[MinValueValidator(1), MaxValueValidator(5)], blank=True, null=True) pm_communication = models.NullBooleanField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) legacy_id = models.PositiveIntegerField(blank=True, null=True) migrated_at = models.DateTimeField(blank=True, null=True) def __str__(self): return '{0} - {1}%'.format(self.event, self.percentage) class Meta: ordering = ['-created_at'] @staticmethod @allow_staff_or_superuser def has_read_permission(request): return True @allow_staff_or_superuser def has_object_read_permission(self, request): return self.event.project.is_participant(request) @staticmethod @allow_staff_or_superuser def has_write_permission(request): return request.user.is_developer or request.user.is_project_manager or request.user.is_project_owner @allow_staff_or_superuser def has_object_write_permission(self, request): return request.user == self.user
class Project(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='projects_created', on_delete=models.DO_NOTHING) title = models.CharField(max_length=200) description = models.TextField() owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='projects_owned', on_delete=models.DO_NOTHING, blank=True, null=True) pm = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='projects_managed', on_delete=models.DO_NOTHING, blank=True, null=True) skills = tagulous.models.TagField(Skill, blank=True) budget = models.DecimalField(max_digits=17, decimal_places=2, blank=True, null=True, default=None) currency = models.CharField(max_length=5, choices=CURRENCY_CHOICES_EUR_ONLY, default=CURRENCY_EUR) type = models.ManyToManyField(ProjectType, blank=True) expected_duration = models.CharField( max_length=20, choices=PROJECT_EXPECTED_DURATION_CHOICES, blank=True, null=True) stage = models.CharField(max_length=20, choices=PROJECT_STAGE_CHOICES, default=PROJECT_STAGE_ACTIVE) # State identifiers client_survey_enabled = models.BooleanField(default=True) pm_updates_enabled = models.BooleanField(default=True) closed = models.BooleanField(default=False) archived = models.BooleanField(default=False) # Significant event dates start_date = models.DateTimeField(blank=True, null=True) deadline = models.DateTimeField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) closed_at = models.DateTimeField(blank=True, null=True) archived_at = models.DateTimeField(blank=True, null=True) participants = models.ManyToManyField(settings.AUTH_USER_MODEL, through='Participation', through_fields=('project', 'user'), related_name='project_participants', blank=True) legacy_id = models.PositiveIntegerField(blank=True, null=True) migrated_at = models.DateTimeField(blank=True, null=True) hubspot_deal_id = models.CharField(editable=False, null=True, max_length=12) activity_objects = GenericRelation( Action, object_id_field='target_object_id', content_type_field='target_content_type', related_query_name='projects') def __str__(self): return self.title class Meta: ordering = ['-created_at'] @allow_staff_or_superuser def is_participant(self, user, active=True): if user == self.user or user == self.owner: return True elif user.is_project_manager and self.pm == user: return True elif user.is_developer and self.participation_set.filter( user=user, status__in=active and [STATUS_ACCEPTED] or [STATUS_ACCEPTED, STATUS_INITIAL]).count() > 0: return True else: return False @staticmethod @allow_staff_or_superuser def has_read_permission(request): return True @allow_staff_or_superuser def has_object_read_permission(self, request): return True @staticmethod @allow_staff_or_superuser def has_write_permission(request): return request.user.is_project_owner or request.user.is_project_manager @allow_staff_or_superuser def has_object_write_permission(self, request): return request.user == self.user or request.user == self.owner or request.user == self.pm @property def margin(self): from tunga_payments.models import Invoice sales_amount = Invoice.objects.filter( project=self, type=INVOICE_TYPE_SALE).aggregate(Sum('amount')) project_amount = Invoice.objects.filter( project=self, type=INVOICE_TYPE_PURCHASE).aggregate(Sum('amount')) sales_amount = sales_amount['amount__sum'] or 0 project_amount = project_amount['amount__sum'] or 0 return sales_amount - project_amount
class ProgressEvent(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) type = models.CharField(max_length=50, choices=PROGRESS_EVENT_TYPE_CHOICES, default=PROGRESS_EVENT_DEVELOPER, help_text=','.join([ '{} - {}'.format(item[0], item[1]) for item in PROGRESS_EVENT_TYPE_CHOICES ])) due_at = models.DateTimeField() title = models.CharField(max_length=200, blank=True, null=True) description = models.TextField(blank=True, null=True) last_reminder_at = models.DateTimeField(blank=True, null=True) missed_notification_at = models.DateTimeField(blank=True, null=True) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='progress_events_created', blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) legacy_id = models.PositiveIntegerField(blank=True, null=True) migrated_at = models.DateTimeField(blank=True, null=True) activity_objects = GenericRelation( Action, object_id_field='target_object_id', content_type_field='target_content_type', related_query_name='progress_events') def __str__(self): return '{} | {} - {}'.format(self.type, self.title, self.due_at) class Meta: unique_together = ('project', 'type', 'due_at') ordering = ['-due_at'] @staticmethod @allow_staff_or_superuser def has_read_permission(request): return True @allow_staff_or_superuser def has_object_read_permission(self, request): return self.project.is_participant(request.user) @staticmethod @allow_staff_or_superuser def has_write_permission(request): return request.user.is_project_owner or request.user.is_project_manager or request.user.is_project_owner @allow_staff_or_superuser def has_object_write_permission(self, request): return request.user == self.project.user or request.user == self.project.owner @property def participants(self): participants = [] if self.type in [PROGRESS_EVENT_CLIENT, PROGRESS_EVENT_MILESTONE]: if self.project.owner: participants.append(self.project.owner) else: participants.append(self.project.user) if self.type in [ PROGRESS_EVENT_PM, PROGRESS_EVENT_MILESTONE, PROGRESS_EVENT_INTERNAL ] and self.project.pm: participants.append(self.project.pm) if self.type in [PROGRESS_EVENT_DEVELOPER, PROGRESS_EVENT_MILESTONE]: participants.extend([ participant.user for participant in self.project.participation_set.filter( status=STATUS_ACCEPTED, updates_enabled=True) ]) return participants @property def status(self): if self.progressreport_set.count() > 0: return 'completed' past_by_24_hours = datetime.datetime.utcnow() - relativedelta(hours=24) if self.due_at > past_by_24_hours: return 'upcoming' return 'missed'
class Participation(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='project_participation', on_delete=models.DO_NOTHING) status = models.CharField(max_length=20, choices=REQUEST_STATUS_CHOICES, help_text=','.join([ '%s - %s' % (item[0], item[1]) for item in REQUEST_STATUS_CHOICES ]), default=STATUS_INITIAL) updates_enabled = models.BooleanField(default=True) update_days = models.CharField(default=','.join(UPDATE_DAYS), max_length=40) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='project_participants_added') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) responded_at = models.DateTimeField(blank=True, null=True) legacy_id = models.PositiveIntegerField(blank=True, null=True) migrated_at = models.DateTimeField(blank=True, null=True) def __str__(self): return '#{} | {} - {}'.format( self.id, self.user.get_short_name() or self.user.username, self.project.title) class Meta: unique_together = ('user', 'project') ordering = ['-created_at'] verbose_name_plural = 'participation' def save(self, force_insert=False, force_update=False, using=None, update_fields=None): if self.status != STATUS_INITIAL and self.responded_at is None: self.responded_at = datetime.datetime.utcnow() super(Participation, self).save(force_insert=force_insert, force_update=force_update, using=using) @staticmethod @allow_staff_or_superuser def has_read_permission(request): return True @allow_staff_or_superuser def has_object_read_permission(self, request): return self.project.is_participant(request.user, active=False) @staticmethod @allow_staff_or_superuser def has_write_permission(request): return request.user.is_project_owner or request.user.is_project_manager @allow_staff_or_superuser def has_object_write_permission(self, request): allowed_users = [self.created_by, self.user, self.project.user] for user in [self.project.owner, self.project.pm]: if user: allowed_users.append(user) return request.user in allowed_users
class Task(models.Model): project = models.ForeignKey(Project, related_name='tasks', on_delete=models.DO_NOTHING, blank=True, null=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='tasks_created', on_delete=models.DO_NOTHING) title = models.CharField(max_length=200) description = models.TextField(blank=True, null=True) remarks = models.TextField(blank=True, null=True) url = models.URLField(blank=True, null=True) fee = models.BigIntegerField() currency = models.CharField(max_length=5, choices=CURRENCY_CHOICES, default=CURRENCY_CHOICES[0][0]) deadline = models.DateTimeField(blank=True, null=True) skills = tagulous.models.TagField(Skill, blank=True) visibility = models.PositiveSmallIntegerField( choices=VISIBILITY_CHOICES, default=VISIBILITY_CHOICES[0][0]) update_interval = models.PositiveIntegerField(blank=True, null=True) update_interval_units = models.PositiveSmallIntegerField( choices=UPDATE_SCHEDULE_CHOICES, blank=True, null=True) apply = models.BooleanField(default=True) closed = models.BooleanField(default=False) paid = models.BooleanField(default=False) applicants = models.ManyToManyField(settings.AUTH_USER_MODEL, through='Application', through_fields=('task', 'user'), related_name='task_applications', blank=True) participants = models.ManyToManyField(settings.AUTH_USER_MODEL, through='Participation', through_fields=('task', 'user'), related_name='task_participants', blank=True) satisfaction = models.SmallIntegerField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) apply_closed_at = models.DateTimeField(blank=True, null=True) closed_at = models.DateTimeField(blank=True, null=True) paid_at = models.DateTimeField(blank=True, null=True) comments = GenericRelation(Comment, related_query_name='tasks') uploads = GenericRelation(Upload, related_query_name='tasks') ratings = GenericRelation(Rating, related_query_name='tasks') def __unicode__(self): return self.summary class Meta: ordering = ['-created_at'] unique_together = ('user', 'title', 'fee') @staticmethod @allow_staff_or_superuser def has_read_permission(request): return True @allow_staff_or_superuser def has_object_read_permission(self, request): if self.visibility == VISIBILITY_DEVELOPER: return request.user.type == USER_TYPE_DEVELOPER elif self.visibility == VISIBILITY_MY_TEAM: return bool( Connection.objects.exclude(accepted=False).filter( Q(from_user=self.user, to_user=request.user) | Q(from_user=request.user, to_user=self.user)).count()) elif self.visibility == VISIBILITY_CUSTOM: return self.participation_set.filter( (Q(accepted=True) | Q(responded=False)), user=request.user).count() return False @staticmethod @allow_staff_or_superuser def has_write_permission(request): return request.user.type == USER_TYPE_PROJECT_OWNER @staticmethod @allow_staff_or_superuser def has_update_permission(request): return True @allow_staff_or_superuser def has_object_write_permission(self, request): return request.user == self.user @allow_staff_or_superuser def has_object_update_permission(self, request): if self.has_object_write_permission(request): return True # Participants can edit participation info directly on task object if request.method in ['PUT', 'PATCH']: allowed_keys = [ 'assignee', 'participants', 'confirmed_participants', 'rejected_participants' ] if not [x for x in request.data.keys() if not x in allowed_keys]: return self.participation_set.filter( (Q(accepted=True) | Q(responded=False)), user=request.user).count() return False def display_fee(self, amount=None): if amount is None: amount = self.fee if self.currency in CURRENCY_SYMBOLS: return '%s%s' % (CURRENCY_SYMBOLS[self.currency], floatformat(amount, arg=-2)) return amount @property def summary(self): return '%s - Fee: %s' % (self.title, self.display_fee()) @property def excerpt(self): try: return strip_tags(self.description).strip() except: return None @property def skills_list(self): return str(self.skills) @property def milestones(self): return self.progressevent_set.filter(type__in=[ PROGRESS_EVENT_TYPE_MILESTONE, PROGRESS_EVENT_TYPE_SUBMIT ]) @property def progress_events(self): return self.progressevent_set.all() @property def participation(self): return self.participation_set.filter( Q(accepted=True) | Q(responded=False)) @property def assignee(self): try: return self.participation_set.get( (Q(accepted=True) | Q(responded=False)), assignee=True) except: return None @property def update_schedule_display(self): if self.update_interval and self.update_interval_units: if self.update_interval == 1 and self.update_interval_units == UPDATE_SCHEDULE_DAILY: return 'Daily' interval_units = str( self.get_update_interval_units_display()).lower() if self.update_interval == 1: return 'Every %s' % interval_units return 'Every %s %ss' % (self.update_interval, interval_units) return None @property def applications(self): return self.application_set.filter(responded=False) @property def all_uploads(self): return Upload.objects.filter( Q(tasks=self) | Q(comments__tasks=self) | Q(progress_reports__event__task=self)) @property def meta_payment(self): return { 'task_url': '/task/%s/' % self.id, 'amount': self.fee, 'currency': self.currency } def get_default_participation(self): tags = ['tunga.io', 'tunga'] if self.skills: tags.extend(str(self.skills).split(',')) tunga_share = '{share}%'.format(**{'share': TUNGA_SHARE_PERCENTAGE}) return { 'type': 'payment', 'language': 'EN', 'title': self.summary, 'description': self.excerpt or self.summary, 'keywords': tags, 'participants': [{ 'id': 'mailto:%s' % TUNGA_SHARE_EMAIL, 'role': 'owner', 'share': tunga_share }] } def mobbr_participation(self, check_only=False): participation_meta = self.get_default_participation() if not self.url: return participation_meta, False mobbr_info_url = '%s?url=%s' % ( 'https://api.mobbr.com/api_v1/uris/info', urllib.quote_plus(self.url)) r = requests.get(mobbr_info_url, **{'headers': { 'Accept': 'application/json' }}) has_script = False if r.status_code == 200: response = r.json() task_script = response['result']['script'] for meta_key in participation_meta: if meta_key == 'keywords': if isinstance(task_script[meta_key], list): participation_meta[meta_key].extend( task_script[meta_key]) elif meta_key == 'participants': if isinstance(task_script[meta_key], list): absolute_shares = [] relative_shares = [] absolute_participants = [] relative_participants = [] for key, participant in enumerate( task_script[meta_key]): if re.match(r'\d+%$', participant['share']): share = int(participant['share'].replace( "%", "")) if share > 0: absolute_shares.append(share) new_participant = participant new_participant['share'] = share absolute_participants.append( new_participant) else: share = int(participant['share']) if share > 0: relative_shares.append(share) new_participant = participant new_participant['share'] = share relative_participants.append( new_participant) additional_participants = [] total_absolutes = sum(absolute_shares) total_relatives = sum(relative_shares) if total_absolutes >= 100 or total_relatives == 0: additional_participants = absolute_participants elif total_absolutes == 0: additional_participants = relative_participants else: additional_participants = absolute_participants for participant in relative_participants: share = int( round(((participant['share'] * (100 - total_absolutes)) / total_relatives), 0)) if share > 0: new_participant = participant new_participant['share'] = share additional_participants.append( new_participant) if len(additional_participants): participation_meta[meta_key].extend( additional_participants) has_script = True elif meta_key in task_script: participation_meta[meta_key] = task_script[meta_key] return participation_meta, has_script @property def meta_participation(self): participation_meta, has_script = self.mobbr_participation() # TODO: Update local participation script to use defined shares if not has_script: participants = self.participation_set.filter( accepted=True).order_by('share') total_shares = 100 - TUNGA_SHARE_PERCENTAGE num_participants = participants.count() for participant in participants: participation_meta['participants'].append({ 'id': 'mailto:%s' % participant.user.email, 'role': participant.role, 'share': int(total_shares / num_participants) }) return participation_meta