import random
from collections import defaultdict
from optparse import make_option

from django.contrib.auth.models import User
from django.core.management.base import BaseCommand

from symposion.reviews.models import ProposalGroup, ReviewAssignment
from symposion.utils.mail import send_email


class Command(BaseCommand):
    option_list = BaseCommand.option_list + (
        make_option(
            "--proposal-group-name",
            help="Which proposal group to assign reviewers for",
        ),
    )

    def handle(self, *args, **options):
        group = ProposalGroup.objects.get(
            name=options["proposal_group_name"],
        )
        reviewers = list(User.objects.filter(
            groups__name="reviewers",
        ))
        user_reviews = defaultdict(list)
        for proposal_result in group.proposal_results.all():
            proposal_reviewers = random.sample([
                user for user in reviewers
                if user.id not in self.proposal_speaker_user_ids(proposal_result.proposal)
            ], 7)
            for reviewer in proposal_reviewers:
                user_reviews[reviewer].append(proposal_result)

        for user, proposal_results in user_reviews.iteritems():
            for pr in proposal_results:
                ReviewAssignment.objects.create(
                    proposal=pr.proposal,
                    user=user,
                    origin=ReviewAssignment.AUTO_ASSIGNED_INITIAL,
                )
            send_email([user.email], "new_review_assignments", context={
                "user": user,
                "proposal_results": proposal_results,
                "proposal_group": group,
            })



    def proposal_speaker_user_ids(self, proposal):
        speakers = [proposal.speaker] + list(proposal.additional_speakers.all())
        return [speaker.user_id for speaker in speakers if speaker.user_id is not None]

@@ -81,52 +81,8 @@
 on%0A%0A
-from django.contrib.auth.models import User%0A
 from
@@ -128,16 +128,47 @@
 eCommand
+%0Afrom django.db.models import Q
 %0A%0Afrom s
@@ -230,16 +230,56 @@
 ignment%0A
+from symposion.teams.models import Team%0A
 from sym
@@ -697,81 +697,27 @@
 s = 
-list(User.objects.filter(%0A            groups__name=%22reviewers%22,%0A        )
+self.get_reviewers(
 )%0A  
@@ -1654,16 +1654,411 @@
     %7D)%0A%0A
+    def get_reviewers(self):%0A        teams = Team.objects.filter(%0A            permissions__codename=%22can_review_talks%22%0A        )%0A        memberships = set()%0A        for team in teams:%0A            memberships.update(team.memberships.filter(%0A                Q(state=%22member%22) %7C Q(state=%22manager%22)%0A            ).select_related(%22user%22))%0A        return %5Bmembership.user for membership in memberships%5D
 %0A%0A    de

Use teams to find reviewers, not django.contrib.auth Groups -- they're different