class List(models.Model): """Content lists which can be created for each user.""" user = models.ForeignKey(BucketUser, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=255, verbose_name="Name") slug = models.SlugField(max_length=150, unique=True, editable=False, verbose_name="Slug") description = models.TextField(blank=True, verbose_name="Description") image = models.ImageField(upload_to='list_images', blank=True, null=True, verbose_name="Image") image_thumbnail = ImageSpecField(source='image', processors=[ResizeToFill(100, 150)], options={'quality': 100}) content = models.ManyToManyField(Content, blank=True, related_name='content', verbose_name='Content') visibility = models.CharField(max_length=150, choices=visibility, default='public', verbose_name="Visibility") topics = tagulous.models.TagField(to=Topic, related_name='list_topic') list_bookmarked_by = models.ManyToManyField(BucketUser, related_name='list_bookmark') class Meta: ordering = ['name'] def __str__(self): return "{0} by {1}".format(self.name, self.user) def save(self, *args, **kwargs): self.slug = add_slug(self) super().save(*args, **kwargs)
class Post(models.Model): POST_TYPE = ( (1, 'Article'), (2, 'Course'), (3, 'Job'), (4, 'Project'), ) identifier = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) slug = models.SlugField(unique=True, null=True, blank=True, max_length=512) type = models.PositiveSmallIntegerField(choices=POST_TYPE, default=1) tags = tagulous.models.TagField(related_name='posts', to=Tag, blank=True) author = models.ForeignKey('users.CustomUser', on_delete=models.CASCADE, related_name='blogs') title = models.CharField(max_length=255) body = BleachField() preview = models.CharField( max_length=300, help_text='A short preview of this post that is shown in list of posts.' ) likes = models.ManyToManyField('users.CustomUser', blank=True) allow_comments = models.BooleanField(default=True) def save(self, *args, **kwargs): self.slug = slugify(f'{self.title} {self.identifier}', allow_unicode=True) super(Post, self).save(*args, **kwargs) def __str__(self): return f'{self.title}, by {self.author.first_name} {self.author.last_name}' @property def likes_count(self): return self.likes.count() @property def relative_url(self): return reverse('blog-post', kwargs={'slug': self.slug}) def get_absolute_url(self): domain = Site.objects.get_current().domain protocol = "https" if settings.PRODUCTION_SERVER else "http" absolute_url = f'{protocol}://{domain}{self.relative_url}' return absolute_url
class Skills(tagulous.models.TagModel): class TagMeta: # Tag options initial = [ 'Python', 'JQuery', 'Angular.js', 'nginx', 'uwsgi', ] autocomplete_view = 'skills_autocomplete' verification_tests = models.ManyToManyField('expertratings.SkillTest', through='VerificationTest') def is_verified(self, user): return SkillTestResult.objects.filter( user=user, test__in=self.verification_tests.all(), test_result='PASS').exists()
class Content(models.Model): """Model to store content related to a subject""" subject = models.ManyToManyField(Subject, blank=True, related_name='content') title = models.CharField(max_length=255, verbose_name="Title") slug = models.SlugField(max_length=150, unique=True, editable=False, verbose_name="Slug") url = models.URLField(blank=True, null=True, default='', verbose_name="URL") content_id = models.CharField(max_length=255) type = models.CharField(max_length=150, choices=media_types, default='other', verbose_name="Type") image = models.ImageField(upload_to='content_images', blank=True, null=True, verbose_name="Image") image_thumbnail = ImageSpecField(source='image', processors=[ResizeToFill(100, 150)], options={'quality': 100}) description = models.TextField(blank=True, verbose_name="Description") tags = tagulous.models.TagField(to=Tag, related_name='content_tag') topics = tagulous.models.TagField(to=Topic, related_name='content_topic') class Meta: ordering = ['title'] def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = str(self.content_id) + '-' + slugify(self.title) super().save(*args, **kwargs) def url_text(self): if self.url and '//' not in self.url: self.url = '%s%s' % ('https://', self.url) parsed_url = urlparse(self.url) if parsed_url.hostname: return parsed_url.hostname.replace("www.", "") + "/..." else: return ""
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 Profile(AbstractUser): address = models.CharField(max_length=255, blank=True, null=True) address2 = models.CharField(max_length=255, blank=True, null=True) city = models.CharField(max_length=255, blank=True, null=True) state = models.CharField(max_length=255, blank=True, null=True) country = models.CharField(max_length=100, blank=True, null=True) country_code = models.CharField(max_length=100, blank=True, null=True) zipcode = models.IntegerField(blank=True, null=True) location = models.CharField(max_length=100, blank=True, null=True) capacity = models.IntegerField(blank=True, null=True) notes = models.TextField(blank=True, null=True) photo = models.ImageField(blank=True, null=True, upload_to=path_and_rename) skills = tagulous.models.TagField(to=Skills, blank=True) signup_code = models.CharField(max_length=25, blank=True, null=True) title = models.CharField(max_length=100, blank=True, null=True) roles = models.ManyToManyField(Role, blank=True) stripe = models.CharField(max_length=255, blank=True, null=True) stripe_connect = models.CharField(max_length=255, blank=True, null=True) verification = models.CharField(max_length=255, default='unverified') payouts_enabled = models.BooleanField(default=False) biography = models.TextField(blank=True, null=True) long_description = models.TextField(blank=True, null=True) objects = CustomUserManager() email_notifications = models.BooleanField(default=True) email_confirmed = models.BooleanField(default=False) featured = models.BooleanField(default=False) tos = models.BooleanField(default=False) work_examples = GenericRelation('generics.Attachment') score = models.DecimalField(blank=True, null=True, max_digits=5, decimal_places=2) referral_code = models.CharField(max_length=50, blank=True, null=True) full_time = models.BooleanField(default=True) contract_to_hire = models.BooleanField(default=True) freelance = models.BooleanField(default=True) @property def name(self): return '{0} {1}'.format(self.first_name, self.last_name) @property def get_photo(self): if self.photo: return '{0}{1}'.format(settings.MEDIA_URL, self.photo) else: try: return self.social_auth.get( provider='linkedin-oauth2' ).extra_data['picture_urls']['values'][0] except: return '' @property def linkedin(self): try: return self.social_auth.get(provider='linkedin-oauth2') except UserSocialAuth.DoesNotExist: return None @property def company(self): """ TODO Needs to support multiple primary companies """ try: return Employee.objects.get(profile=self, primary=True).company except Employee.DoesNotExist: return None @property def contact_details(self): details, created = ContactDetails.objects.get_or_create(profile=self) if (created): details.email = self.email details.email_confirmed = self.email_confirmed details.save() return details def get_skills(self): return self.skills.all() @property def skilltests(self): return SkillTest.objects.filter(profile=self) @property def taken_tests(self): return [t.expertratings_test for t in self.skilltests] def get_default_payment(self): if self.stripe: stripe.api_key = settings.STRIPE_KEY stripe_customer = stripe.Customer.retrieve(self.stripe) for card in stripe_customer['sources']['data']: if card['id'] == stripe_customer['default_source']: # TODO Manually serialize card, circular import error if using api serializer return card return None @property def subscribed(self): active_projects = Project.objects.filter(project_manager=self, status='active') if len(active_projects) > 0: return True return False def invite(self, sender): invite, created = Invite.objects.get_or_create(recipient=self, sender=sender) if created: return True return False
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
class Integration(models.Model): task = models.ForeignKey(Task, on_delete=models.CASCADE) provider = models.CharField(max_length=30, choices=providers.registry.as_choices()) type = models.PositiveSmallIntegerField( choices=INTEGRATION_TYPE_CHOICES, help_text=','.join([ '%s - %s' % (item[0], item[1]) for item in INTEGRATION_TYPE_CHOICES ])) events = models.ManyToManyField(IntegrationEvent, related_name='integrations') secret = models.CharField(max_length=30, default=get_random_string) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='integrations_created', blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __unicode__(self): return '%s - %s' % (self.get_provider_display(), self.task.summary) class Meta: unique_together = ('task', 'provider') 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 request.user == self.task.user @staticmethod @allow_staff_or_superuser def has_write_permission(request): return request.user.type == USER_TYPE_PROJECT_OWNER @allow_staff_or_superuser def has_object_write_permission(self, request): return request.user == self.task.user @property def hook_id(self): try: return self.integrationmeta_set.get(meta_key='hook_id').meta_value except: return None @property def repo_id(self): try: return self.integrationmeta_set.get(meta_key='repo_id').meta_value except: return None @property def repo_full_name(self): try: return self.integrationmeta_set.get( meta_key='repo_full_name').meta_value except: return None @property def issue_id(self): try: return self.integrationmeta_set.get(meta_key='issue_id').meta_value except: return None @property def issue_number(self): try: return self.integrationmeta_set.get( meta_key='issue_number').meta_value except: return None