<commit_before>import datetime
import os
import uuid

from django.core.urlresolvers import reverse
from django.db import models
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _

from django.contrib.auth.models import User

import reversion

from kaleo.models import JoinInvitation
from slugify import slugify

from . import signals


def avatar_upload(instance, filename):
    ext = filename.split(".")[-1]
    filename = "%s.%s" % (uuid.uuid4(), ext)
    return os.path.join("avatars", filename)


def create_slug(name):
    return slugify(name)[:50]


@python_2_unicode_compatible
class Team(models.Model):

    MEMBER_ACCESS_OPEN = "open"
    MEMBER_ACCESS_APPLICATION = "application"
    MEMBER_ACCESS_INVITATION = "invitation"

    MANAGER_ACCESS_ADD = "add someone"
    MANAGER_ACCESS_INVITE = "invite someone"

    MEMBER_ACCESS_CHOICES = [
        (MEMBER_ACCESS_OPEN, _("open")),
        (MEMBER_ACCESS_APPLICATION, _("by application")),
        (MEMBER_ACCESS_INVITATION, _("by invitation"))
    ]

    MANAGER_ACCESS_CHOICES = [
        (MANAGER_ACCESS_ADD, _("add someone")),
        (MANAGER_ACCESS_INVITE, _("invite someone"))
    ]

    slug = models.SlugField(unique=True)
    name = models.CharField(max_length=100, verbose_name=_("name"))
    avatar = models.ImageField(upload_to=avatar_upload, blank=True, verbose_name=_("avatar"))
    description = models.TextField(blank=True, verbose_name=_("description"))
    member_access = models.CharField(max_length=20, choices=MEMBER_ACCESS_CHOICES, verbose_name=_("member access"))
    manager_access = models.CharField(max_length=20, choices=MANAGER_ACCESS_CHOICES, verbose_name=_("manager access"))
    creator = models.ForeignKey(User, related_name="teams_created", verbose_name=_("creator"))
    created = models.DateTimeField(default=timezone.now, editable=False, verbose_name=_("created"))

    def get_absolute_url(self):
        return reverse("team_detail", args=[self.slug])

    def __str__(self):
        return self.name

    def can_join(self, user):
        state = self.state_for(user)
        if self.member_access == Team.MEMBER_ACCESS_OPEN and state is None:
            return True
        elif state == Membership.STATE_INVITED:
            return True
        else:
            return False

    def can_leave(self, user):
        # managers can't leave at the moment
        role = self.role_for(user)
        return role == Membership.ROLE_MEMBER

    def can_apply(self, user):
        state = self.state_for(user)
        return self.member_access == Team.MEMBER_ACCESS_APPLICATION and state is None

    @property
    def applicants(self):
        return self.memberships.filter(state=Membership.STATE_APPLIED)

    @property
    def invitees(self):
        return self.memberships.filter(state=Membership.STATE_INVITED)

    @property
    def declines(self):
        return self.memberships.filter(state=Membership.STATE_DECLINED)

    @property
    def rejections(self):
        return self.memberships.filter(state=Membership.STATE_REJECTED)

    @property
    def acceptances(self):
        return self.memberships.filter(state__in=[
            Membership.STATE_ACCEPTED,
            Membership.STATE_AUTO_JOINED]
        )

    @property
    def members(self):
        return self.acceptances.filter(role=Membership.ROLE_MEMBER)

    @property
    def managers(self):
        return self.acceptances.filter(role=Membership.ROLE_MANAGER)

    @property
    def owners(self):
        return self.acceptances.filter(role=Membership.ROLE_OWNER)

    def is_owner_or_manager(self, user):
        return self.acceptances.filter(
            role__in=[
                Membership.ROLE_OWNER,
                Membership.ROLE_MANAGER
            ],
            user=user
        ).exists()

    def is_member(self, user):
        return self.members.filter(user=user).exists()

    def is_manager(self, user):
        return self.managers.filter(user=user).exists()

    def is_owner(self, user):
        return self.owners.filter(user=user).exists()

    def is_on_team(self, user):
        return self.acceptances.filter(user=user).exists()

    def add_member(self, user, role=None, state=None):
        # we do this, rather than put the Membership constants in declaration
        # because Membership is not yet defined
        if role is None:
            role = Membership.ROLE_MEMBER
        if state is None:
            state = Membership.STATE_AUTO_JOINED
        
        membership, created = Membership.objects.get_or_create(
            team=self,
            user=request.user,
            defaults={"role": role, "state": state},
        )
        return membership

    def add_user(self, user, role):
        state = Membership.STATE_AUTO_JOINED
        if self.manager_access == Team.MANAGER_ACCESS_INVITE:
            state = Membership.STATE_INVITED
        membership, _ = self.memberships.get_or_create(
            user=user,
            defaults={"role": role, "state": state}
        )
        signals.added_member.send(sender=self, membership=membership)
        return membership

    def invite_user(self, from_user, to_email, role, message=None):
        if not JoinInvitation.objects.filter(signup_code__email=to_email).exists():
            invite = JoinInvitation.invite(from_user, to_email, message, send=False)
            membership, _ = self.memberships.get_or_create(
                invite=invite,
                defaults={"role": role, "state": Membership.STATE_INVITED}
            )<commit_msg>fixed another NameError in `add_member`<commit_after>import datetime
import os
import uuid

from django.core.urlresolvers import reverse
from django.db import models
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _

from django.contrib.auth.models import User

import reversion

from kaleo.models import JoinInvitation
from slugify import slugify

from . import signals


def avatar_upload(instance, filename):
    ext = filename.split(".")[-1]
    filename = "%s.%s" % (uuid.uuid4(), ext)
    return os.path.join("avatars", filename)


def create_slug(name):
    return slugify(name)[:50]


@python_2_unicode_compatible
class Team(models.Model):

    MEMBER_ACCESS_OPEN = "open"
    MEMBER_ACCESS_APPLICATION = "application"
    MEMBER_ACCESS_INVITATION = "invitation"

    MANAGER_ACCESS_ADD = "add someone"
    MANAGER_ACCESS_INVITE = "invite someone"

    MEMBER_ACCESS_CHOICES = [
        (MEMBER_ACCESS_OPEN, _("open")),
        (MEMBER_ACCESS_APPLICATION, _("by application")),
        (MEMBER_ACCESS_INVITATION, _("by invitation"))
    ]

    MANAGER_ACCESS_CHOICES = [
        (MANAGER_ACCESS_ADD, _("add someone")),
        (MANAGER_ACCESS_INVITE, _("invite someone"))
    ]

    slug = models.SlugField(unique=True)
    name = models.CharField(max_length=100, verbose_name=_("name"))
    avatar = models.ImageField(upload_to=avatar_upload, blank=True, verbose_name=_("avatar"))
    description = models.TextField(blank=True, verbose_name=_("description"))
    member_access = models.CharField(max_length=20, choices=MEMBER_ACCESS_CHOICES, verbose_name=_("member access"))
    manager_access = models.CharField(max_length=20, choices=MANAGER_ACCESS_CHOICES, verbose_name=_("manager access"))
    creator = models.ForeignKey(User, related_name="teams_created", verbose_name=_("creator"))
    created = models.DateTimeField(default=timezone.now, editable=False, verbose_name=_("created"))

    def get_absolute_url(self):
        return reverse("team_detail", args=[self.slug])

    def __str__(self):
        return self.name

    def can_join(self, user):
        state = self.state_for(user)
        if self.member_access == Team.MEMBER_ACCESS_OPEN and state is None:
            return True
        elif state == Membership.STATE_INVITED:
            return True
        else:
            return False

    def can_leave(self, user):
        # managers can't leave at the moment
        role = self.role_for(user)
        return role == Membership.ROLE_MEMBER

    def can_apply(self, user):
        state = self.state_for(user)
        return self.member_access == Team.MEMBER_ACCESS_APPLICATION and state is None

    @property
    def applicants(self):
        return self.memberships.filter(state=Membership.STATE_APPLIED)

    @property
    def invitees(self):
        return self.memberships.filter(state=Membership.STATE_INVITED)

    @property
    def declines(self):
        return self.memberships.filter(state=Membership.STATE_DECLINED)

    @property
    def rejections(self):
        return self.memberships.filter(state=Membership.STATE_REJECTED)

    @property
    def acceptances(self):
        return self.memberships.filter(state__in=[
            Membership.STATE_ACCEPTED,
            Membership.STATE_AUTO_JOINED]
        )

    @property
    def members(self):
        return self.acceptances.filter(role=Membership.ROLE_MEMBER)

    @property
    def managers(self):
        return self.acceptances.filter(role=Membership.ROLE_MANAGER)

    @property
    def owners(self):
        return self.acceptances.filter(role=Membership.ROLE_OWNER)

    def is_owner_or_manager(self, user):
        return self.acceptances.filter(
            role__in=[
                Membership.ROLE_OWNER,
                Membership.ROLE_MANAGER
            ],
            user=user
        ).exists()

    def is_member(self, user):
        return self.members.filter(user=user).exists()

    def is_manager(self, user):
        return self.managers.filter(user=user).exists()

    def is_owner(self, user):
        return self.owners.filter(user=user).exists()

    def is_on_team(self, user):
        return self.acceptances.filter(user=user).exists()

    def add_member(self, user, role=None, state=None):
        # we do this, rather than put the Membership constants in declaration
        # because Membership is not yet defined
        if role is None:
            role = Membership.ROLE_MEMBER
        if state is None:
            state = Membership.STATE_AUTO_JOINED
        
        membership, created = Membership.objects.get_or_create(
            team=self,
            user=user,
            defaults={"role": role, "state": state},
        )
        return membership

    def add_user(self, user, role):
        state = Membership.STATE_AUTO_JOINED
        if self.manager_access == Team.MANAGER_ACCESS_INVITE:
            state = Membership.STATE_INVITED
        membership, _ = self.memberships.get_or_create(
            user=user,
            defaults={"role": role, "state": state}
        )
        signals.added_member.send(sender=self, membership=membership)
        return membership

    def invite_user(self, from_user, to_email, role, message=None):
        if not JoinInvitation.objects.filter(signup_code__email=to_email).exists():
            invite = JoinInvitation.invite(from_user, to_email, message, send=False)
            membership, _ = self.memberships.get_or_create(
                invite=invite,
                defaults={"role": role, "state": Membership.STATE_INVITED}
            )
{'fraction_non_alphanumeric': 0.09730353024658506, 'fraction_numerical': 0.0023061912364733014, 'mean_word_length': 3.055755395683453, 'pattern_counts': {'":': 12, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2319601', 'n_tokens_mistral': 3478, 'n_tokens_neox': 3354, 'n_words': 680}