def get_team(team_id):
    team = team_service.get_team(team_id)
    if not team:
        raise NotFoundError('Team {} does not exist'.format(team_id))

    team_member = team_member_service.find(
        is_team_lead=True,
        team_id=team_id,
        user_id=current_user.id
    ).one_or_none()

    if not team_member:
        raise UnauthorisedError('Only team leads can edit a team')

    domain = get_email_domain(current_user.email_address)

    if team['teamMembers'] is not None:
        for user_id, team_member in team['teamMembers'].iteritems():
            missing_permissions = [permission for permission in permission_types
                                   if permission not in team_member['permissions']]

            for permission in missing_permissions:
                team_member['permissions'][permission] = False

    team.update(domain=domain)

    return team
def send_team_member_notification_emails(team_id, user_ids=None):
    team = team_service.find(id=team_id).first()

    if user_ids is None or len(user_ids) == 0:
        # Team members added through the create flow
        members = team_member_service.find(team_id=team_id,
                                           is_team_lead=False).all()
    else:
        # Team members added through the edit flow
        members = team_member_service.get_team_members_by_user_id(
            team_id, user_ids)

    to_addresses = []
    for member in members:
        user = users.get(member.user_id)
        to_addresses.append(user.email_address)

    if len(to_addresses) == 0:
        return

    email_body = render_email_template(
        'team_member_added.md',
        frontend_url=current_app.config['FRONTEND_ADDRESS'],
        team_lead=escape_markdown(current_user.name),
        team_name=escape_markdown(team.name))

    subject = '{} added you as a member of {}'.format(
        current_user.name, team.name.encode('utf-8'))

    send_or_handle_error(
        to_addresses,
        email_body,
        subject,
        current_app.config['DM_GENERIC_NOREPLY_EMAIL'],
        current_app.config['DM_GENERIC_SUPPORT_NAME'],
        event_description_for_errors='team member added email')

    audit_service.log_audit_event(audit_type=audit_types.team_member_added,
                                  data={
                                      'to_address': to_addresses,
                                      'subject': subject
                                  },
                                  db_object=team,
                                  user='')
def send_team_lead_notification_emails(team_id, user_ids=None):
    team = team_service.find(id=team_id).first()

    if user_ids is None or len(user_ids) == 0:
        # Team leads added through the create flow
        team_leads = team_member_service.find(team_id=team_id,
                                              is_team_lead=True).all()
        team_leads = [
            team_lead for team_lead in team_leads
            if team_lead.user_id != current_user.id
        ]
    else:
        # Team leads added through the edit flow
        team_leads = team_member_service.get_team_leads_by_user_id(
            team_id, user_ids)

    to_addresses = []
    for team_lead in team_leads:
        user = users.get(team_lead.user_id)
        to_addresses.append(user.email_address)

    if len(to_addresses) == 0:
        return

    email_body = render_email_template(
        'team_lead_added.md',
        frontend_url=current_app.config['FRONTEND_ADDRESS'],
        team_name=escape_markdown(team.name))

    subject = 'You have been upgraded to a team lead'

    send_or_handle_error(to_addresses,
                         email_body,
                         subject,
                         current_app.config['DM_GENERIC_NOREPLY_EMAIL'],
                         current_app.config['DM_GENERIC_SUPPORT_NAME'],
                         event_description_for_errors='team lead added email')

    audit_service.log_audit_event(audit_type=audit_types.team_lead_added,
                                  data={'to_address': to_addresses},
                                  db_object=team,
                                  user='')
def get_team(team_id, allow_anyone=None):
    team = team_service.get_team(team_id)
    if not team:
        raise NotFoundError('Team {} does not exist'.format(team_id))

    if allow_anyone is None:
        team_member = team_member_service.find(
            is_team_lead=True, team_id=team_id,
            user_id=current_user.id).one_or_none()

        if not team_member:
            raise UnauthorisedError('Only team leads can edit a team')

    if team['teamMembers'] is not None:
        for user_id, team_member in team['teamMembers'].iteritems():
            missing_permissions = [
                permission for permission in permission_types
                if permission not in team_member['permissions']
            ]

            for permission in missing_permissions:
                team_member['permissions'][permission] = False

    return team
def update_team_leads_and_members(team, data):
    incoming_team_leads = data.get('teamLeads', {})
    incoming_team_members = data.get('teamMembers', {})

    incoming_team_lead_ids = []
    if incoming_team_leads:
        incoming_team_lead_ids = [
            int(team_lead_id) for team_lead_id in incoming_team_leads
        ]

    incoming_team_member_ids = []
    if incoming_team_members:
        incoming_team_member_ids = [
            int(team_member_id) for team_member_id in incoming_team_members
        ]

    # set any active join requests for the incoming users to this team as approved and done
    incoming_user_emails = []
    for user_id in incoming_team_lead_ids + incoming_team_member_ids:
        user = users.get_by_id(user_id)
        if user:
            incoming_user_emails.append(user.email_address)
    for email_address in incoming_user_emails:
        clear_all_join_requests(email_address, team.id)

    current_team_members = [tm.user_id for tm in team.team_members]
    new_team_leads = []
    new_team_members = []
    removed_team_members = []

    for tm in team.team_members:
        if tm.user_id in incoming_team_lead_ids:
            if tm.is_team_lead is False:
                tm.is_team_lead = True
                new_team_leads.append(tm.user_id)

        if tm.user_id in incoming_team_member_ids:
            if tm.is_team_lead is True:
                tm.is_team_lead = False

        if tm.user_id not in incoming_team_lead_ids + incoming_team_member_ids:
            removed_team_members.append(tm.user_id)

    for user_id in removed_team_members:
        team_member = team_member_service.find(team_id=team.id,
                                               user_id=user_id).one_or_none()

        if team_member:
            team.team_members.remove(team_member)

    for user_id in incoming_team_lead_ids:
        if user_id not in current_team_members:
            team.team_members.append(
                TeamMember(team_id=team.id, user_id=user_id,
                           is_team_lead=True))
            new_team_leads.append(user_id)

    for user_id in incoming_team_member_ids:
        if user_id not in current_team_members:
            team.team_members.append(
                TeamMember(team_id=team.id,
                           user_id=user_id,
                           is_team_lead=False))
            new_team_members.append(user_id)

    return {
        'new_team_leads': new_team_leads,
        'new_team_members': new_team_members,
        'removed_team_members': removed_team_members
    }
def update_team_leads_and_members(team, data):
    incoming_team_leads = data.get('teamLeads', {})
    incoming_team_members = data.get('teamMembers', {})

    incoming_team_lead_ids = []
    if incoming_team_leads:
        incoming_team_lead_ids = [int(team_lead_id) for team_lead_id in incoming_team_leads]

    incoming_team_member_ids = []
    if incoming_team_members:
        incoming_team_member_ids = [int(team_member_id) for team_member_id in incoming_team_members]

    current_team_members = [tm.user_id for tm in team.team_members]
    new_team_leads = []
    new_team_members = []
    removed_team_members = []

    for tm in team.team_members:
        if tm.user_id in incoming_team_lead_ids:
            if tm.is_team_lead is False:
                tm.is_team_lead = True
                new_team_leads.append(tm.user_id)

        if tm.user_id in incoming_team_member_ids:
            if tm.is_team_lead is True:
                tm.is_team_lead = False

        if tm.user_id not in incoming_team_lead_ids + incoming_team_member_ids:
            removed_team_members.append(tm.user_id)

    for user_id in removed_team_members:
        team_member = team_member_service.find(
            team_id=team.id,
            user_id=user_id
        ).one_or_none()

        if team_member:
            team.team_members.remove(team_member)

    for user_id in incoming_team_lead_ids:
        if user_id not in current_team_members:
            team.team_members.append(
                TeamMember(
                    team_id=team.id,
                    user_id=user_id,
                    is_team_lead=True
                )
            )
            new_team_leads.append(user_id)

    for user_id in incoming_team_member_ids:
        if user_id not in current_team_members:
            team.team_members.append(
                TeamMember(
                    team_id=team.id,
                    user_id=user_id,
                    is_team_lead=False
                )
            )
            new_team_members.append(user_id)

    return {
        'new_team_leads': new_team_leads,
        'new_team_members': new_team_members,
        'removed_team_members': removed_team_members
    }