Пример #1
0
def submit_vote(request, question_id):
    """
	Submits a vote that has been made in the show_question view
	"""

    question = get_object_or_404(PollQuestion, poll=user.poll, id=question_id)

    next_question = question.next()
    valid_choices = {"yes": 0, "no": 1, "abstention": 2}

    # Check if the vote key exists and contains a valid value. Otherwise,
    # redirect to next question
    if not "vote" in request.POST or not request.POST["vote"] in valid_choices:
        if next_question == None:
            return HttpResponseRedirect(reverse("thanks"))

        return HttpResponseRedirect(reverse("show_question", kwargs={"question_id": next_question.id}))

        # Check if user already voted on this. If not, create new Vote object
    try:
        vote = Vote.objects.get(voting_user=user, poll_question=question)
    except Vote.DoesNotExist:
        vote = Vote(voting_user=user, poll_question=question)

    vote.choice = valid_choices[request.POST["vote"]]
    vote.save()

    if next_question == None:
        return HttpResponseRedirect(reverse("thanks"))

    return HttpResponseRedirect(reverse("show_question", kwargs={"question_id": next_question.id}))
Пример #2
0
def add_car_vote(request, car_name):
    s = Survey.get()
    v = Vote()
    v.survey = s
    v.choice = car_name
    v.save()
    cnt = Vote.objects.filter(survey=s, choice=car_name).count()
    return HttpResponse(str(cnt))
Пример #3
0
def woman(request):
    v = Vote(type=True)
    v.survey = Survey.get()
    v.save()
    votes = Vote.objects.filter(survey=v.survey).order_by('-date')
    mtot = votes.filter(type=Man).count()
    wtot = votes.filter(type=Woman).count()
    return redirect('/vote/')
Пример #4
0
def VoteQuestion(request, questionid):
    option = request.POST.get(questionid)
    option_obj = Question_option.objects.get(pk=option)
    question_obj = Question.objects.get(pk=questionid)
    username = request.user.username
    applyVote = Vote(question=question_obj, username=username, question_option=option_obj)
    applyVote.save()
    request.session['message'] = 'Your poll has been accepted'
    return redirect('/questions/'+str(questionid))
    def test_category(self):
        # Check that <category> value which is not
        # listed in VoteCategory enum
        # does not confuse Django ORM

        vote = Vote(congress=2011, session='2011',
                    chamber=CongressChamber.senate,
                    number=10,
                    source=VoteSource.random_value(),
                    created=datetime.now(),
                    vote_type='asdf',
                    category='zzz',
                    question='asdf',
                    required='asdf',
                    result='asdf')
        vote.save()

        self.assertEqual(vote.category, u'zzz')
        self.assertEqual(vote.get_category_display(), u'zzz')
Пример #6
0
def index(request):
    s = Survey.get()
    current_vote = request.GET.get('type')
    current_car = request.GET.get('car')
    if current_vote in ('man', 'woman'):
        if current_vote == 'man':
            v = Vote(type=Man)
        else:
            v = Vote(type=Woman)
        v.survey = s
        v.save()
    elif current_car:
        if current_car != 'delete':
            v = Vote()
            v.survey = s
            v.choice = current_car
            v.save()
        else:
            vote = Vote.objects.last()
            vote.delete()

    votes = Vote.objects.filter(survey=s).order_by('-date')
    if s == 'tesla':
        cnt = votes.count()
        #tallies = Vote.objects.filter(survey=s).values('choice').annotate(Count('choice')).order_by('choice')
        tallies = {}
        tallies['TeslaS'] = Vote.objects.filter(survey=s, choice='tesla_s').count()
        tallies['TeslaX'] = Vote.objects.filter(survey=s, choice='tesla_x').count()
        tallies['Tesla3'] = Vote.objects.filter(survey=s, choice='tesla_3').count()


        return render(request, 'vote/cars.html', {'vtot': cnt,
                                                  'tallies': tallies,
                                                  'survey': s,
                                                  'votes': votes[0:5]})
    else:
        mtot = votes.filter(type=Man).count()
        wtot = votes.filter(type=Woman).count()
        return render(request, 'vote/index.html', {'vtot': mtot+wtot,
                                                   'mtot': mtot,
                                                   'wtot': wtot,
                                                   'survey': s,
                                                   'votes': votes[0:5]})
Пример #7
0
 def test_has_user_voted_for_song(self):
     vote_service = VoteService()
     vote = Vote()
     vote.user_id = 1
     vote.song_id = 1
     vote.created_date = datetime.now()
     vote.like = True
     vote.save()
     user = User()
     user.id = 1
     song = Song
     song.id = 1
     self.assertTrue(vote_service.has_user_voted_for_song(song, user))
Пример #8
0
def create_votes():

	Vote.objects.all().delete()

	for pk, fields in votos.iteritems():

		try:
			v = Vote(pk=pk)
			v.user_id = get_user(fields['user'])
			v.value = fields['value']
			v.content_object = Dateo.objects.get(pk=fields['object_id'])
			v.object_id = fields['object_id']
			v.client_domain = datea
			v.save()

			created = date_parser(fields['created'])
			Vote.objects.filter(pk=v.pk).update(created=created)

		except: 
			pass
Пример #9
0
setup_environ(settings)


from django.core.mail import send_mail
from intranet.models import Member, Group
from vote.models import Vote
from django.utils.crypto import get_random_string


members = Member.objects.all()

poll=int(raw_input("Poll id: "))

for m in members:
   key = get_random_string(length=32,allowed_chars='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
   v = Vote(user=m,key=key,poll=poll)
   v.save()
   email = """Dear %s,

We've been working on updating the ACM constitution to better reflect how we currently operate and to incorporate some new ideas. Under the guidelines of the current constitution, amendments have to be approved by our executive council and then by our membership. The proposed changes have been approved by exec, so now we're sending it out to you so that you can take a look at it and vote on it. 

Here's a link to the new constitution https://www-s.acm.illinois.edu/confluence/display/general/ACM+Constitution+-+Draft; there's also a summary of the changes below. 

Amendment highlights:
-Classifying members as undergraduate members, graduate members, faculty/staff members, active members and alumni members
-Updating duties of officers
-Not allowing officers to run for a second consecutive term in the same position 
-Making it possible for individuals to get funding for a project in addition to SIGs
-Defining what committees are and how they're run
-Requiring 5 members to start a SIG
-Allowing for a designated proxy for SIG leadership at exec meetings 
Пример #10
0
def election(request, elecName):
    votearea = DummyCitizenInfo.objects.get(email=request.user.email)
    electionobj = Election.objects.get(elec_name=elecName)
    admincandidates = CanInfo.objects.filter(elec_name=elecName)
    if (electionobj.elec_type == 'national'):
        candidates = CanInfo.objects.filter(elec_name=elecName,
                                            voting_area=votearea.area_name)
    else:
        # mayorcandidates=CanInfo.objects.filter(elec_name = elecName, candidate_type = 'MAYOR')
        candidates = CanInfo.objects.filter(
            Q(elec_name=elecName) & Q(voting_ward=votearea.ward_number)
            | Q(voting_ward='M'))
    print(admincandidates)

    canlistname = []
    canlistphoto = []
    candiparty = []
    canlisttype = []
    canlistnid = []
    counter = []
    canlistward = []
    canlistarea = []

    admincanlistname = []
    admincanlistphoto = []
    admincandiparty = []
    admincanlisttype = []
    admincanlistnid = []
    admincounter = []
    admincanlistward = []
    admincanlistarea = []
    for j in range(len(admincandidates)):
        dummyvar = DummyCitizenInfo.objects.get(nid=admincandidates[j].nid)
        admincanlistname.append(dummyvar.name)
        admincanlistphoto.append(dummyvar.picture)
        admincanlisttype.append(admincandidates[j].candidate_type)
        admincandiparty.append(admincandidates[j].party_name)
        admincanlistnid.append(admincandidates[j].nid)
        admincanlistward.append(admincandidates[j].voting_ward)
        admincanlistarea.append(admincandidates[j].voting_area)
        admincounter.append(
            Vote.objects.filter(elec_name=elecName,
                                candidate=admincandidates[j]).count())

    for i in range(len(candidates)):
        dummyvar = DummyCitizenInfo.objects.get(nid=candidates[i].nid)
        canlistname.append(dummyvar.name)
        canlistphoto.append(dummyvar.picture)
        canlisttype.append(candidates[i].candidate_type)
        candiparty.append(candidates[i].party_name)
        canlistnid.append(candidates[i].nid)
        canlistward.append(candidates[i].voting_ward)
        canlistarea.append(candidates[i].voting_area)
        counter.append(
            Vote.objects.filter(elec_name=elecName,
                                candidate=candidates[i]).count())
    print(canlistname)
    flag = Vote.objects.filter(
        elec_name=elecName,
        user=DummyCitizenInfo.objects.get(email=request.user.email),
        vote_status=True)
    context = {
        'uData':
        DummyCitizenInfo.objects.get(email=request.user.email),
        'getElectionData':
        CanInfo.objects.filter(elec_name=elecName),
        'electionTable':
        Election.objects.get(elec_name=elecName),
        'elec_name':
        elecName,
        'admincanlistcity':
        zip(admincanlistname, admincanlisttype, admincanlistward,
            admincounter),
        'admincanlistnational':
        zip(admincanlistname, admincandiparty, admincanlistarea, admincounter),
        'canlist':
        zip(canlistname, canlistphoto, canlisttype, candiparty, canlistnid),
        'canlist1':
        zip(canlistname, canlistphoto, canlisttype, candiparty, canlistnid),
        'canlist2':
        zip(canlistname, canlistphoto, canlisttype, candiparty, canlistnid),
        'canlist3':
        zip(canlistname, canlisttype, canlistward, counter),
        'nationalcanlist':
        zip(canlistname, candiparty, canlistarea, counter),
        'voteFlag':
        flag,
        'votearea':
        votearea
    }
    if request.method == 'POST':
        et = Election.objects.get(elec_name=elecName)
        if request.POST.get('actionOp') == 'active':
            et.elec_status = request.POST.get('actionOp')
            et.save()
        if request.POST.get('actionOp') == 'cancle':
            Election.objects.get(elec_name=elecName).delete()
            CanInfo.objects.filter(elec_name=elecName).delete()
        if request.POST.get('actionOp') == 'ended':
            et.elec_status = 'ended'
            et.save()
        if request.POST.get('MAYOR') and request.POST.get(
                'COUNCILLOR') and request.POST.get('RESERVED'):
            vModel1 = Vote(
                elec_name=elecName,
                vote_status=True,
                user=DummyCitizenInfo.objects.get(email=request.user.email),
                candidate=CanInfo.objects.filter(candidate_type='MAYOR').get(
                    nid=request.POST.get('MAYOR')))
            vModel2 = Vote(
                elec_name=elecName,
                vote_status=True,
                user=DummyCitizenInfo.objects.get(email=request.user.email),
                candidate=CanInfo.objects.filter(
                    candidate_type='COUNCILLOR').get(
                        nid=request.POST.get('COUNCILLOR')))
            vModel3 = Vote(
                elec_name=elecName,
                vote_status=True,
                user=DummyCitizenInfo.objects.get(email=request.user.email),
                candidate=CanInfo.objects.filter(
                    candidate_type='RESERVED').get(
                        nid=request.POST.get('RESERVED')))
            vModel1.save()
            vModel2.save()
            vModel3.save()
        if request.POST.get('MP'):
            vModel1 = Vote(
                elec_name=elecName,
                vote_status=True,
                user=DummyCitizenInfo.objects.get(email=request.user.email),
                candidate=CanInfo.objects.filter(
                    candidate_type='MP',
                    elec_name=elecName).get(nid=request.POST.get('MP')))
            vModel1.save()

        checkAccess = DummyCitizenInfo.objects.get(email=request.user.email)
        if checkAccess.elec_Worker == True:
            return redirect('election-worker')
        else:
            return redirect('dashboard')
    elif Election.objects.filter(elec_name=elecName, elec_type='national'):
        return render(request, 'home/national.html', context)
    elif Election.objects.filter(elec_name=elecName, elec_type='city'):
        return render(request, 'home/city.html', context)
Пример #11
0
    def post(self, request):
        message_fr = "Merci pour votre vote Bonne chance pour la tombola RDV le 18 février 2021 sur 2M"
        message_ar = "شكرا لتصويتكم حظ موفق موعدنا يوم 18 فبراير 2021 على قناة 2M  "
        status = "success"

        data = request.data

        temp_person = Person.objects.all().filter(email=data["email"])


        config_demo = Config.objects.all().filter(type="demo", active=True)
        site_demo = False
        if config_demo.count() == 1:
            site_demo = True

        if temp_person.count() > 0: # and site_demo == False
            message_fr = "Vote non enregistré. Vous avez déjà voté pour votre candidat préféré."
            message_ar = "لم يتم تسجيل التصويت. لقد قمتم بالفعل بالتصويت لمرشحكم المفضل. "
            return Response({"status": "error", "message_fr": message_fr, "message_ar": message_ar, "uid_ref": "",
                             "site_demo": site_demo}, content_type="application/json", status=200)

        uid_ref = None
        candidat = Candidat.objects.all().filter(uid=data["candidat"])
        config_vote = Config.objects.all().filter(type="vote", active=True)
        if candidat.count() == 1 and config_vote.count() > 0:
            candidat = candidat[0]




            uid_ref = self.generateUID() + "-" + self.generateUID()
            person = Person()
            person.name = data["name"]
            person.email = data["email"]
            person.phone = str(data["phone"])
            person.uid = self.generateUID()
            person.uid_ref = uid_ref
            person.accept_reglement = True

            person.save()

            vote = Vote()
            vote.candidat = candidat
            vote.person = person
            vote.uid = self.generateUID()
            vote.project = candidat.project

            vote.save()

            candidat.total_votes = candidat.total_votes + 1
            candidat.save()
        else:
            if config_vote.count() == 0 :
                status = "error"
                message_fr = "Le vote est fermé, Merci pour votre visite."
                message_ar = "لقد تم إغلاق التصويت، شكرا لزيارتكم."
            else:
                status = "error"
                message_fr = "Candidat n'existe plus, Merci de réessayer plus tard"
                message_ar = "لم يعد المرشح موجودًا ، يرجى المحاولة مرة أخرى لاحقًا"


        return Response({ "status" : status, "message_fr" : message_fr, "message_ar" : message_ar, "uid_ref" : uid_ref, "site_demo" : site_demo}, content_type="application/json", status=200)
Пример #12
0
def main(options):
    """
    Parse rolls.
    """
    
    # Setup XML processors
    vote_processor = VoteProcessor()
    option_processor = VoteOptionProcessor()
    voter_processor = VoterProcessor()
    voter_processor.PERSON_CACHE = dict((x.pk, x) for x in Person.objects.all())

    # The pattern which the roll file matches
    # Filename contains info which should be placed to DB
    # along with info extracted from the XML file
    re_path = re.compile('data/us/(\d+)/rolls/([hs])(\w+)-(\d+)\.xml')

    chamber_mapping = {'s': CongressChamber.senate,
                       'h': CongressChamber.house}

    if options.filter:
        files = glob.glob(options.filter)
        log.info('Parsing rolls matching %s' % options.filter)
    elif options.congress:
        files = glob.glob('data/us/%s/rolls/*.xml' % options.congress)
        log.info('Parsing rolls of only congress#%s' % options.congress)
    else:
        files = glob.glob('data/us/*/rolls/*.xml')
    log.info('Processing votes: %d files' % len(files))
    total = len(files)
    progress = Progress(total=total, name='files', step=10)

    def log_delete_qs(qs):
        if qs.count() == 0: return
        print("Deleting obsoleted records: ", qs)
        #if qs.count() > 3:
        #    print "Delete skipped..."
        #    return
        qs.delete()

    seen_obj_ids = set()
    had_error = False

    for fname in files:
        progress.tick()

        match = re_path.search(fname)
        
        try:
            existing_vote = Vote.objects.get(congress=match.group(1), chamber=chamber_mapping[match.group(2)], session=match.group(3), number=match.group(4))
        except Vote.DoesNotExist:
            existing_vote = None
        
        if not File.objects.is_changed(fname) and not options.force and existing_vote != None and not existing_vote.missing_data:
            seen_obj_ids.add(existing_vote.id)
            continue
            
        try:
            tree = etree.parse(fname)
            
            ## Look for votes with VP tie breakers.
            #if len(tree.xpath("/roll/voter[@VP='1']")) == 0:
            #    had_error = True # prevent delete at the end
            #    continue
            
            # Process role object
            roll_node = tree.xpath('/roll')[0]

            # Sqlite is much faster when lots of saves are wrapped in a transaction,
            # and we do a lot of saves because it's a lot of voters.
            from django.db import transaction
            with transaction.atomic():

                vote = vote_processor.process(Vote(), roll_node)
                if existing_vote: vote.id = existing_vote.id
                match = re_path.search(fname)
                vote.congress = int(match.group(1))
                vote.chamber = chamber_mapping[match.group(2)]
                vote.session = match.group(3)
                vote.number = int(match.group(4))
                
                # Get related bill & amendment.
                
                for bill_node in roll_node.xpath("bill"):
                    related_bill_num = bill_node.get("number")
                    if 9 <= vote.congress <= 42 and vote.session in ('1', '2'):
                         # Bill numbering from the American Memory colletion is different. The number combines
                         # the session, bill number, and a 0 or 5 for regular or 'half' numbering. Prior to
                         # the 9th congress numbering seems to be wholly assigned by us and not related to
                         # actual numbering, so we skip matching those bills.
                         related_bill_num = "%d%04d%d" % (int(vote.session), int(bill_node.get("number")), 0)
                    try:
                        vote.related_bill = Bill.objects.get(congress=bill_node.get("session"), bill_type=BillType.by_xml_code(bill_node.get("type")), number=related_bill_num)
                    except Bill.DoesNotExist:
                        if vote.congress >= 93:
                            vote.missing_data = True

                for amdt_node in roll_node.xpath("amendment"):
                    if amdt_node.get("ref") == "regular" and vote.related_bill is not None:
                        try:
                            vote.related_amendment = Amendment.objects.get(congress=vote.related_bill.congress, amendment_type=AmendmentType.by_slug(amdt_node.get("number")[0]), number=amdt_node.get("number")[1:])
                        except Amendment.DoesNotExist:
                            if vote.congress >= 93:
                                print("Missing amendment", fname)
                                vote.missing_data = True
                    elif amdt_node.get("ref") == "bill-serial":
                        # It is impossible to associate House votes with amendments just from the House
                        # vote XML because the amendment-num might correspond either with the A___ number
                        # or with the "An amendment, numbered ____" number from the amendment purpose,
                        # and there's really no way to figure out which. Maybe we can use the amendment
                        # sponsor instead?
                        #vote.related_amendment = Amendment.objects.get(bill=vote.related_bill, sequence=amdt_node.get("number"))
                        # Instead, we set related_amendment from the amendment parser. Here, we have to
                        # preserve the related_amendment if it is set.
                        if existing_vote: vote.related_amendment = existing_vote.related_amendment

                # clean up some question text and use the question_details field
                
                if vote.category in (VoteCategory.passage, VoteCategory.passage_suspension, VoteCategory.veto_override) and vote.related_bill:
                    # For passage votes, set the question to the bill title and put the question
                    # details in the details field.
                    vote.question = vote.related_bill.title
                    vote.question_details = vote.vote_type + " in the " + vote.get_chamber_display()
                    
                elif vote.category == VoteCategory.amendment and vote.related_amendment:
                    # For votes on amendments, make a better title/explanation.
                    vote.question = vote.related_amendment.title
                    vote.question_details = vote.vote_type + " in the " + vote.get_chamber_display()
                    
                elif vote.related_bill and vote.question.startswith("On the Cloture Motion " + vote.related_bill.display_number):
                    vote.question = "Cloture on " + vote.related_bill.title
                elif vote.related_bill and vote.question.startswith("On Cloture on the Motion to Proceed " + vote.related_bill.display_number):
                    vote.question = "Cloture on " + vote.related_bill.title
                    vote.question_details = "On Cloture on the Motion to Proceed in the " + vote.get_chamber_display()
                elif vote.related_bill and vote.question.startswith("On the Motion to Proceed " + vote.related_bill.display_number):
                    vote.question = "Motion to Proceed on " + vote.related_bill.title
                    
                elif vote.related_amendment and vote.question.startswith("On the Cloture Motion " + vote.related_amendment.get_amendment_type_display() + " " + str(vote.related_amendment.number)):
                    vote.question = "Cloture on " + vote.related_amendment.title
                    vote.question_details = vote.vote_type + " in the " + vote.get_chamber_display()
                
                # weird House foratting of bill numbers ("H RES 123 Blah blah")
                if vote.related_bill:
                    vote.question = re.sub(
                        "(On [^:]+): " + vote.related_bill.display_number.replace(". ", " ").replace(".", " ").upper() + " .*",
                        r"\1: " + truncatewords(vote.related_bill.title, 15),
                        vote.question)
                    
                vote.save()
                
                seen_obj_ids.add(vote.id) # don't delete me later
                
                # Process roll options, overwrite existing options where possible.
                seen_option_ids = set()
                roll_options = {}
                for option_node in roll_node.xpath('./option'):
                    option = option_processor.process(VoteOption(), option_node)
                    option.vote = vote
                    if existing_vote:
                        try:
                            option.id = VoteOption.objects.filter(vote=vote, key=option.key)[0].id # get is better, but I had the database corruption problem
                        except IndexError:
                            pass
                    option.save()
                    roll_options[option.key] = option
                    seen_option_ids.add(option.id)
                log_delete_qs(VoteOption.objects.filter(vote=vote).exclude(id__in=seen_option_ids)) # may cascade and delete the Voters too?

                # Process roll voters, overwriting existing voters where possible.
                if existing_vote:
                    existing_voters = dict(Voter.objects.filter(vote=vote).values_list("person", "id"))
                seen_voter_ids = set()
                voters = list()
                for voter_node in roll_node.xpath('./voter'):
                    voter = voter_processor.process(roll_options, Voter(), voter_node)
                    voter.vote = vote
                    voter.created = vote.created
                        
                    # for VP votes, load the actual person & role...
                    if voter.voter_type == VoterType.vice_president:
                        try:
                            r = PersonRole.objects.get(role_type=RoleType.vicepresident, startdate__lte=vote.created, enddate__gte=vote.created)
                            voter.person_role = r
                            voter.person = r.person
                        except PersonRole.DoesNotExist:
                            # overlapping roles? missing data?
                            log.error('Could not resolve vice president in %s' % fname)
                        
                    if existing_vote and voter.person:
                        try:
                            voter.id = existing_voters[voter.person.id]
                        except KeyError:
                            pass
                        
                    voters.append(voter)
                    
                    if voter.voter_type == VoterType.unknown and not vote.missing_data:
                        vote.missing_data = True
                        vote.save()
                        
                # pre-fetch the role of each voter
                load_roles_at_date([x.person for x in voters if x.person != None], vote.created, vote.congress)
                for voter in list(voters):
                    if voter.voter_type != VoterType.vice_president:
                        voter.person_role = voter.person.role
                    # If we couldn't match a role for this person on the date of the vote, and if the voter was Not Voting,
                    # and we're looking at historical data, then this is probably a data error --- the voter wasn't even in office.
                    if voter.person_role is None:
                        if vote.source == VoteSource.keithpoole and voter.option.key == "0":
                            # Drop this record.
                            voters.remove(voter)
                        else:
                            log.error("%s: Could not find role for %s on %s." % (fname, voter.person, vote.created))
                            vote.missing_data = True
                            vote.save()

                # save all of the records (inserting/updating)
                for voter in voters:
                    voter.save()
                    seen_voter_ids.add(voter.id)
                    
                # remove obsolete voter records
                log_delete_qs(Voter.objects.filter(vote=vote).exclude(id__in=seen_voter_ids)) # possibly already deleted by cascade above

                # pre-calculate totals
                vote.calculate_totals()

                if not options.disable_events:
                    vote.create_event()
                    
            File.objects.save_file(fname)

        except Exception as ex:
            log.error('Error in processing %s' % fname, exc_info=ex)
            had_error = True
        
    # delete vote objects that are no longer represented on disk
    if options.congress and not options.filter and not had_error:
        log_delete_qs(Vote.objects.filter(congress=options.congress).exclude(id__in = seen_obj_ids))
Пример #13
0
def do_site_search(q, allow_redirect=False, request=None):
    if q.strip() == "":
        return []

    results = []

    from bill.models import Bill
    from vote.models import Vote
    if "pass" in q or "fail" in q or "vote" in q:
        results.append({
            "title":
            "Tracking Federal Legislation",
            "href":
            "/start",
            "noun":
            "feeds",
            "results": [{
                "href": f.link,
                "label": f.title,
                "obj": f,
                "feed": f,
                "secondary": False
            } for f in (
                Bill.EnactedBillsFeed(),
                Bill.ActiveBillsExceptIntroductionsFeed(),
                Bill.ComingUpFeed(),
                Vote.AllVotesFeed(),
            )]
        })

    from haystack.query import SearchQuerySet
    from events.models import Feed

    from person.models import RoleType
    sqs = SearchQuerySet().using("person")\
        .filter(
            indexed_model_name__in=["Person"],
            all_role_types__in=(RoleType.representative, RoleType.senator),
            content=q)
    if 'XapianEngine' not in settings.HAYSTACK_CONNECTIONS['person']['ENGINE']:
        # Xapian doesn't provide a 'score' so we can't do this when debugging.
        sqs = sqs.order_by('-is_currently_serving', '-score')
    results.append({
        "title":
        "Members of Congress",
        "href":
        "/congress/members/all",
        "qsarg":
        "name",
        "noun":
        "Members of Congress",
        "results": [{
            "href": p.object.get_absolute_url(),
            "label": p.object.name,
            "obj": p.object,
            "feed": p.object.get_feed(),
            "secondary": p.object.get_current_role() == None
        } for p in sqs[0:9]]
    })

    import us
    results.append({
        "title":
        "States",
        "href":
        "/congress/members",
        "noun":
        "states",
        "results":
        sorted([{
            "href": "/congress/members/%s" % s,
            "label": us.statenames[s]
        } for s in us.statenames
                if us.statenames[s].lower().startswith(q.lower())],
               key=lambda p: p["label"])
    })

    # search committees -- name must contain all of the words in the
    # search query (e.g. "rules committee" should match "committee on rules")
    from committee.models import Committee
    committees_qs = Committee.objects.filter(obsolete=False)
    for word in q.split(" "):
        committees_qs = committees_qs.filter(name__icontains=word)
    results.append({
        "title":
        "Congressional Committees",
        "href":
        "/congress/committees",
        "noun":
        "committees in Congress",
        "results":
        sorted([{
            "href": c.get_absolute_url(),
            "label": c.fullname,
            "feed": c.get_feed(),
            "obj": c,
            "secondary": c.committee != None
        } for c in committees_qs],
               key=lambda c: c["label"])
    })

    from settings import CURRENT_CONGRESS
    from bill.search import parse_bill_citation
    bill = parse_bill_citation(q)
    congress = "__ALL__"
    if not bill or not allow_redirect:
        # query Solr w/ the boosted field
        from haystack.inputs import AutoQuery
        from haystack.query import SQ
        q = SearchQuerySet().using("bill").filter(indexed_model_name__in=["Bill"])\
            .filter( SQ(text=AutoQuery(q)) | SQ(text_boosted=AutoQuery(q)) )

        # restrict to current bills if any (at least 10) bills match
        q1 = q.filter(congress=CURRENT_CONGRESS)
        if q1.count() >= 10:
            q = q1
            congress = str(CURRENT_CONGRESS)

        bills = [\
            {"href": b.object.get_absolute_url(),
             "label": b.object.title,
             "obj": b.object,
             "feed": b.object.get_feed() if b.object.is_alive else None,
             "secondary": b.object.congress != CURRENT_CONGRESS }
            for b in q[0:9]]
    else:
        url = bill.get_absolute_url()
        if request.GET.get("track"): url += "#track"
        return HttpResponseRedirect(url)
    results.append({
        "title": "Bills and Resolutions",
        "href": "/congress/bills/browse",
        "qsarg": "congress=%s&text" % congress,
        "noun": "federal bills or resolutions",
        "results": bills
    })

    # subject terms, but exclude subject terms that look like committee names because
    # that is confusing to also see with committee results
    from bill.models import BillTerm, TermType
    results.append({
        "title":
        "Subject Areas",
        "href":
        "/congress/bills",
        "noun":
        "subject areas",
        "results": [{
            "href": p.get_absolute_url(),
            "label": p.name,
            "obj": p,
            "feed": p.get_feed(),
            "secondary": not p.is_top_term()
        } for p in BillTerm.objects.filter(
            name__icontains=q, term_type=TermType.new).exclude(
                name__contains=" Committee on ")[0:9]]
    })

    # in each group, make sure the secondary results are placed last, but otherwise preserve order
    for grp in results:
        for i, obj in enumerate(grp["results"]):
            obj["index"] = i
        grp["results"].sort(
            key=lambda o: (o.get("secondary", False), o["index"]))

    # sort categories first by whether all results are secondary results, then by number of matches (fewest first, if greater than zero)
    results.sort(key=lambda c: (len([
        d for d in c["results"] if d.get("secondary", False) == False
    ]) == 0, len(c["results"]) == 0, len(c["results"])))

    return results
Пример #14
0
from django.core.mail import send_mail
from intranet.models import Member, Group
from vote.models import Vote
from django.utils.crypto import get_random_string

members = Member.objects.all()

poll = int(raw_input("Poll id: "))

for m in members:
    key = get_random_string(
        length=32,
        allowed_chars=
        'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
    v = Vote(user=m, key=key, poll=poll)
    v.save()
    email = """Dear %s,

We've been working on updating the ACM constitution to better reflect how we currently operate and to incorporate some new ideas. Under the guidelines of the current constitution, amendments have to be approved by our executive council and then by our membership. The proposed changes have been approved by exec, so now we're sending it out to you so that you can take a look at it and vote on it. 

Here's a link to the new constitution https://www-s.acm.illinois.edu/confluence/display/general/ACM+Constitution+-+Draft; there's also a summary of the changes below. 

Amendment highlights:
-Classifying members as undergraduate members, graduate members, faculty/staff members, active members and alumni members
-Updating duties of officers
-Not allowing officers to run for a second consecutive term in the same position 
-Making it possible for individuals to get funding for a project in addition to SIGs
-Defining what committees are and how they're run
-Requiring 5 members to start a SIG
-Allowing for a designated proxy for SIG leadership at exec meetings 
Пример #15
0
    def post(self, request):

        logging_dict = {
            'client_ip': get_client_ip(request),
            'user': request.user,
            'body': request.body[:1024],
            'election': '-1',
        }

        serialized_data = AddVoteSerializer(data=request.body)

        if serialized_data.is_valid():
            election = self._get_next_election()

            if not election:
                logger.error('User has no valid election left',
                             extra=logging_dict)
                messages.add_message(
                    request, messages.ERROR,
                    'You\'ve no active election. This incident is logged',
                    AlertTags.DANGER)
                return self.get(request)

            logging_dict['election'] = election.id

            votes_for_this_ip = None

            if election.votes_per_ip > 0:
                votes_for_this_ip = election.vote_ips.filter(
                    ip=logging_dict['client_ip']).first()
                if votes_for_this_ip:
                    if votes_for_this_ip.votes >= election.votes_per_ip:
                        logger.error('User is voting for extra votes',
                                     extra=logging_dict)
                        messages.add_message(
                            request, messages.ERROR,
                            'Only {} vote(s) are allowed per IP'.format(
                                election.votes_per_ip), AlertTags.DANGER)
                        request.method = 'POST'
                        return VoterLogoutView.as_view()(request)

            # Validate is valid voter
            voters = election.voter
            voter = voters[0]
            if len(voters) != 1:
                logger.error('User is not a valid voter', extra=logging_dict)
                messages.add_message(request, messages.ERROR,
                                     'You\'re not a voter.', AlertTags.DANGER)
                return self.get(request)

            # Validate key
            if election.is_key_required:
                key = serialized_data.validated_data['key']
                if not key or key.upper() != voter.key.upper():
                    logger.error('User has entered invalid key',
                                 extra=logging_dict)
                    messages.add_message(
                        request, messages.ERROR,
                        'Invalid Key. This incident is logged',
                        AlertTags.DANGER)
                    return self.get(request)

            # Validate votes
            votes = serialized_data.validated_data['votes']
            keys = dict()
            for key, value in votes.items():
                keys[key] = (False, value)

            # Checks that there is a vote for all candidate in election that are visible to voter
            # Like it checks for posts for which voter should be allowed to vote (UG/PG)
            # It also checks if number of non-neutral votes for a post are less then total posts.
            for post in election.posts.all():
                non_neutral_nota_votes = 0

                candidate_count = len(post.human_candidates)

                post_processed = False

                for candidate in post.auto_candidates:
                    if candidate.id in keys:
                        if post_processed:
                            logger.error(
                                'Multiple entries for non auto candidates',
                                extra=logging_dict)
                            messages.add_message(
                                request, messages.ERROR,
                                'Found invalid data. Attempt is logged',
                                AlertTags.DANGER)
                            return self.get(request)

                        keys[candidate.id] = (True, keys[candidate.id][1])

                        # Checking if NO is voted for neutral and NOTA
                        if keys[candidate.id][1] == VoteTypes.NO:
                            logger.log(
                                'User voted for NO for auto accounts. User is stupid',
                                extra=logging_dict)
                            messages.add_message(
                                request, messages.ERROR,
                                'Found invalid data. Attempt is logged',
                                AlertTags.DANGER)
                            return self.get(request)

                        post_processed = True

                for candidate in post.human_candidates:
                    if candidate.id in keys:
                        if post_processed:
                            logger.error(
                                'Entries for normal candidates is present when with auto candidates',
                                extra=logging_dict)

                            messages.add_message(
                                request, messages.ERROR,
                                'Found invalid data. Attempt is logged',
                                AlertTags.DANGER)
                            return self.get(request)

                        keys[candidate.id] = (True, keys[candidate.id][1])

                        if keys[candidate.id][1] == VoteTypes.NO:
                            """
                            Checking if NO vote is casted for a post where candidates > post
                            """
                            if candidate_count > post.number:
                                logger.error(
                                    'Voted NO for a post where candidates > post',
                                    extra=logging_dict)
                                messages.add_message(
                                    request, messages.ERROR,
                                    'Found invalid data. Attempt is logged',
                                    AlertTags.DANGER)
                                return self.get(request)

                        non_neutral_nota_votes += 1

                if non_neutral_nota_votes > post.number:
                    logger.error(
                        'Number of non-neutral votes are greater than number of posts',
                        extra=logging_dict)
                    messages.add_message(
                        request, messages.ERROR,
                        'Found invalid data. Attempt is logged',
                        AlertTags.DANGER)
                    return self.get(request)

            # Check if there is an entry present which are not pk for candidates in election available
            # To person
            for key, value in keys.items():
                if not value[0]:
                    logger.error(
                        'User has entered a candidate id %s which is not a valid value',
                        key,
                        extra=logging_dict)
                    messages.add_message(
                        request, messages.ERROR,
                        'Found corrupted data. Incident will be reported',
                        AlertTags.DANGER)
                    return self.get(request)

            # create votes

            with transaction.atomic():
                # Create Session. Each vote will be associated with a session
                vote_session = VoteSession.objects.create(election=election)

                if not votes_for_this_ip:
                    votes_for_this_ip = VoteIPMap(
                        election=election,
                        votes=1,
                        ip=logging_dict['client_ip'],
                    )
                else:
                    votes_for_this_ip.votes += 1

                votes_for_this_ip.save()

                vote_list = []
                for key, value in keys.items():
                    vote = Vote(candidate_id=key, session=vote_session)
                    vote.vote = value[1]
                    vote_list.append(vote)

                # Add votes to server
                Vote.objects.bulk_create(vote_list)
                voter.voted = True
                voter.save()

            messages.add_message(request, messages.INFO,
                                 'Your vote has been recorded',
                                 AlertTags.SUCCESS)
            return self.get(request, new_session=True)
        else:
            logger.error('Request data is invalidated by serializer',
                         extra=logging_dict)
            messages.add_message(
                request, messages.INFO,
                'Received corrupted data. Incident is recorded',
                AlertTags.DANGER)
            return self.get(request)
Пример #16
0
def do_site_search(q, allow_redirect=False):
    if q.strip() == "":
        return []
    
    results = []
    
    from bill.models import Bill
    from vote.models import Vote
    if "pass" in q or "fail" in q or "vote" in q:
        results.append({
            "title": "Tracking Federal Legislation",
            "href": "/start",
            "noun": "feeds",
            "results": [
                {"href": f.link,
                 "label": f.title,
                 "obj": f,
                 "feed": f,
                 "secondary": False }
                for f in (
                    Bill.EnactedBillsFeed(), Bill.ActiveBillsExceptIntroductionsFeed(), Bill.ComingUpFeed(), Vote.AllVotesFeed(),
                    )
                ]
            })
    
    from haystack.query import SearchQuerySet
    from events.models import Feed
    
    results.append({
        "title": "Members of Congress, Presidents, and Vice Presidents",
        "href": "/congress/members/all",
        "qsarg": "name",
        "noun": "Members of Congress, Presidents, or Vice Presidents",
        "results": [
            {"href": p.object.get_absolute_url(),
             "label": p.object.name,
             "obj": p.object,
             "feed": p.object.get_feed(),
             "secondary": p.object.get_current_role() == None }
            for p in SearchQuerySet().using("person").filter(indexed_model_name__in=["Person"], content=q).order_by('-is_currently_serving', '-score')[0:9]]
        })
       
    # Skipping states for now because we might want to go to the district maps or to
    # the state's main page for state legislative information.
    #import us
    #results.append(("States", "/congress/members", "most_recent_role_state", "states",
    #    sorted([{"href": "/congress/members/%s" % s, "label": us.statenames[s] }
    #        for s in us.statenames
    #        if us.statenames[s].lower().startswith(q.lower())
    #        ], key=lambda p : p["label"])))
    
    from committee.models import Committee
    results.append({
        "title": "Congressional Committees",
        "href": "/congress/committees",
        "noun": "committees in Congress",
        "results": sorted([
            {"href": c.get_absolute_url(),
             "label": c.fullname,
             "feed": c.get_feed(),
             "obj": c,
             "secondary": c.committee != None}
            for c in Committee.objects.filter(name__icontains=q, obsolete=False)
            ], key=lambda c : c["label"])
        })
       
    from settings import CURRENT_CONGRESS
    from bill.search import parse_bill_citation
    bill = parse_bill_citation(q)
    if not bill or not allow_redirect:
        from haystack.inputs import AutoQuery
        bills = [\
            {"href": b.object.get_absolute_url(),
             "label": b.object.title,
             "obj": b.object,
             "feed": b.object.get_feed() if b.object.is_alive else None,
             "secondary": b.object.congress != CURRENT_CONGRESS }
            for b in SearchQuerySet().using("bill").filter(indexed_model_name__in=["Bill"], content=AutoQuery(q)).order_by('-current_status_date')[0:9]]
    else:
        #bills = [{"href": bill.get_absolute_url(), "label": bill.title, "obj": bill, "secondary": bill.congress != CURRENT_CONGRESS }]
        return HttpResponseRedirect(bill.get_absolute_url())
    results.append({
        "title": "Bills and Resolutions (Federal)",
        "href": "/congress/bills/browse",
        "qsarg": "congress=__ALL__&text",
        "noun": "federal bills or resolutions",
        "results": bills})

    
    results.append({
        "title": "State Legislation",
        "href": "/states/bills/browse",
        "qsarg": "text",
        "noun": "state legislation",
        "results": [
            {"href": p.object.get_absolute_url(),
             "label": p.object.short_display_title,
             "obj": p.object,
             "feed": Feed(feedname="states_bill:%d" % p.object.id),
             "secondary": True }
            for p in SearchQuerySet().using('states').filter(indexed_model_name__in=["StateBill"], content=q)[0:9]]
            })

    # subject terms, but exclude subject terms that look like committee names because
    # that is confusing to also see with committee results
    from bill.models import BillTerm, TermType
    results.append({
        "title": "Subject Areas (Federal Legislation)",
        "href": "/congress/bills",
        "noun": "subject areas",
        "results": [
            {"href": p.get_absolute_url(),
             "label": p.name,
             "obj": p,
             "feed": p.get_feed(),
             "secondary": not p.is_top_term() }
            for p in BillTerm.objects.filter(name__icontains=q, term_type=TermType.new).exclude(name__contains=" Committee on ")[0:9]]
        })
    
    # in each group, make sure the secondary results are placed last, but otherwise preserve order
    for grp in results:
        for i, obj in enumerate(grp["results"]):
           obj["index"] = i
        grp["results"].sort(key = lambda o : (o.get("secondary", False), o["index"]))
    
    # sort categories first by whether all results are secondary results, then by number of matches (fewest first, if greater than zero)
    results.sort(key = lambda c : (
        len([d for d in c["results"] if d.get("secondary", False) == False]) == 0,
        len(c["results"]) == 0,
        len(c["results"])))
        
    return results
Пример #17
0
def main(options):
    """
    Parse rolls.
    """

    # Setup XML processors
    vote_processor = VoteProcessor()
    option_processor = VoteOptionProcessor()
    voter_processor = VoterProcessor()
    voter_processor.PERSON_CACHE = dict(
        (x.pk, x) for x in Person.objects.all())

    # The pattern which the roll file matches
    # Filename contains info which should be placed to DB
    # along with info extracted from the XML file
    re_path = re.compile('data/us/(\d+)/rolls/([hs])(\w+)-(\d+)\.xml')

    chamber_mapping = {'s': CongressChamber.senate, 'h': CongressChamber.house}

    if options.filter:
        files = glob.glob(options.filter)
        log.info('Parsing rolls matching %s' % options.filter)
    elif options.congress:
        files = glob.glob('data/us/%s/rolls/*.xml' % options.congress)
        log.info('Parsing rolls of only congress#%s' % options.congress)
    else:
        files = glob.glob('data/us/*/rolls/*.xml')
    log.info('Processing votes: %d files' % len(files))
    total = len(files)
    progress = Progress(total=total, name='files', step=10)

    def log_delete_qs(qs):
        if qs.count() > 0:
            try:
                print "Deleting: ", qs
            except Exception as e:
                print "Deleting [%s]..." % str(e)
            if qs.count() > 3:
                print "Delete skipped..."
                return
            qs.delete()

    seen_obj_ids = set()
    had_error = False

    for fname in files:
        progress.tick()

        match = re_path.search(fname)

        try:
            existing_vote = Vote.objects.get(
                congress=match.group(1),
                chamber=chamber_mapping[match.group(2)],
                session=match.group(3),
                number=match.group(4))
        except Vote.DoesNotExist:
            existing_vote = None

        if not File.objects.is_changed(
                fname
        ) and not options.force and existing_vote != None and not existing_vote.missing_data:
            seen_obj_ids.add(existing_vote.id)
            continue

        try:
            tree = etree.parse(fname)

            ## Look for votes with VP tie breakers.
            #if len(tree.xpath("/roll/voter[@VP='1']")) == 0:
            #    had_error = True # prevent delete at the end
            #    continue

            # Process role object
            for roll_node in tree.xpath('/roll'):
                vote = vote_processor.process(Vote(), roll_node)
                if existing_vote: vote.id = existing_vote.id
                match = re_path.search(fname)
                vote.congress = int(match.group(1))
                vote.chamber = chamber_mapping[match.group(2)]
                vote.session = match.group(3)
                vote.number = int(match.group(4))

                # Get related bill & amendment.

                for bill_node in roll_node.xpath("bill"):
                    try:
                        vote.related_bill = Bill.objects.get(
                            congress=bill_node.get("session"),
                            bill_type=BillType.by_xml_code(
                                bill_node.get("type")),
                            number=bill_node.get("number"))
                    except Bill.DoesNotExist:
                        vote.missing_data = True

                for amdt_node in roll_node.xpath("amendment"):
                    if amdt_node.get("ref") == "regular":
                        try:
                            vote.related_amendment = Amendment.objects.get(
                                congress=vote.related_bill.congress,
                                amendment_type=AmendmentType.by_slug(
                                    amdt_node.get("number")[0]),
                                number=amdt_node.get("number")[1:])
                        except Amendment.DoesNotExist:
                            print "Missing amendment", fname
                            vote.missing_data = True
                    elif amdt_node.get("ref") == "bill-serial":
                        # It is impossible to associate House votes with amendments just from the House
                        # vote XML because the amendment-num might correspond either with the A___ number
                        # or with the "An amendment, numbered ____" number from the amendment purpose,
                        # and there's really no way to figure out which. Maybe we can use the amendment
                        # sponsor instead?
                        #vote.related_amendment = Amendment.objects.get(bill=vote.related_bill, sequence=amdt_node.get("number"))
                        # Instead, we set related_amendment from the amendment parser. Here, we have to
                        # preserve the related_amendment if it is set.
                        if existing_vote:
                            vote.related_amendment = existing_vote.related_amendment

                # clean up some question text and use the question_details field

                if vote.category in (
                        VoteCategory.passage, VoteCategory.passage_suspension,
                        VoteCategory.veto_override) and vote.related_bill:
                    # For passage votes, set the question to the bill title and put the question
                    # details in the details field.
                    vote.question = truncatewords(vote.related_bill.title, 20)
                    vote.question_details = vote.vote_type + " in the " + vote.get_chamber_display(
                    )

                elif vote.category == VoteCategory.amendment and vote.related_amendment:
                    # For votes on amendments, make a better title/explanation.
                    vote.question = truncatewords(vote.related_amendment.title,
                                                  20)
                    vote.question_details = vote.vote_type + " in the " + vote.get_chamber_display(
                    )

                elif vote.related_bill and vote.question.startswith(
                        "On the Cloture Motion " +
                        vote.related_bill.display_number):
                    vote.question = "Cloture on " + truncatewords(
                        vote.related_bill.title, 20)
                elif vote.related_bill and vote.question.startswith(
                        "On Cloture on the Motion to Proceed " +
                        vote.related_bill.display_number):
                    vote.question = "Cloture on " + truncatewords(
                        vote.related_bill.title, 20)
                    vote.question_details = "On Cloture on the Motion to Proceed in the " + vote.get_chamber_display(
                    )
                elif vote.related_bill and vote.question.startswith(
                        "On the Motion to Proceed " +
                        vote.related_bill.display_number):
                    vote.question = "Motion to Proceed on " + truncatewords(
                        vote.related_bill.title, 20)

                elif vote.related_amendment and vote.question.startswith(
                        "On the Cloture Motion " +
                        vote.related_amendment.get_amendment_type_display() +
                        " " + str(vote.related_amendment.number)):
                    vote.question = "Cloture on " + truncatewords(
                        vote.related_amendment.title, 20)
                    vote.question_details = vote.vote_type + " in the " + vote.get_chamber_display(
                    )

                # weird House foratting of bill numbers ("H RES 123 Blah blah")
                if vote.related_bill:
                    vote.question = re.sub(
                        "(On [^:]+): " +
                        vote.related_bill.display_number.replace(
                            ". ", " ").replace(".", " ").upper() + " .*",
                        r"\1: " + truncatewords(vote.related_bill.title, 15),
                        vote.question)

                vote.save()

                seen_obj_ids.add(vote.id)  # don't delete me later

                # Process roll options, overwrite existing options where possible.
                seen_option_ids = set()
                roll_options = {}
                for option_node in roll_node.xpath('./option'):
                    option = option_processor.process(VoteOption(),
                                                      option_node)
                    option.vote = vote
                    if existing_vote:
                        try:
                            option.id = VoteOption.objects.filter(
                                vote=vote, key=option.key
                            )[0].id  # get is better, but I had the database corruption problem
                        except IndexError:
                            pass
                    option.save()
                    roll_options[option.key] = option
                    seen_option_ids.add(option.id)
                log_delete_qs(
                    VoteOption.objects.filter(vote=vote).exclude(
                        id__in=seen_option_ids)
                )  # may cascade and delete the Voters too?

                # Process roll voters, overwriting existing voters where possible.
                if existing_vote:
                    existing_voters = dict(
                        Voter.objects.filter(vote=vote).values_list(
                            "person", "id"))
                seen_voter_ids = set()
                for voter_node in roll_node.xpath('./voter'):
                    voter = voter_processor.process(roll_options, Voter(),
                                                    voter_node)
                    voter.vote = vote
                    voter.created = vote.created

                    # for VP votes, load the actual person...
                    if voter.voter_type == VoterType.vice_president:
                        try:
                            r = PersonRole.objects.get(
                                role_type=RoleType.vicepresident,
                                startdate__lte=vote.created,
                                enddate__gte=vote.created)
                            voter.person = r.person
                        except:
                            # overlapping roles? missing data?
                            log.error(
                                'Could not resolve vice president in %s' %
                                fname,
                                exc_info=ex)

                    if existing_vote and voter.person:
                        try:
                            voter.id = existing_voters[voter.person.id]
                        except KeyError:
                            pass

                    voter.save()

                    if voter.voter_type == VoterType.unknown and not vote.missing_data:
                        vote.missing_data = True
                        vote.save()

                    seen_voter_ids.add(voter.id)

                log_delete_qs(
                    Voter.objects.filter(vote=vote).exclude(
                        id__in=seen_voter_ids)
                )  # possibly already deleted by cascade above

                vote.calculate_totals()

                if not options.disable_events:
                    vote.create_event()

            File.objects.save_file(fname)

        except Exception, ex:
            log.error('Error in processing %s' % fname, exc_info=ex)
            had_error = True
Пример #18
0
    def parse_vote(self, response):
        if not hasattr(response, 'body_as_unicode'):
            self.log('Cannot parse: {u}'.format(u=response.url),
                     level=log.INFO)
            return
        x = XmlXPathSelector(response)

        info = x.select('//Resultado/Informacion')
        session_id = info.select('//Sesion/text()').extract()
        if not session_id:
            # can't identify session, so we skip this file
            self.log('Missing session ID: {u}'.format(u=response.url),
                     level=log.INFO)
            return
        # general session info
        session_id = session_id[0]
        session_date = date_parser.parse(
            info.select('//Fecha/text()').extract()[0], dayfirst=True)
        session_instance, session_created = Session.objects.get_or_create(
            session=session_id, defaults={'date': session_date})
        if not session_created:
            session_instance.date = session_date
            session_instance.save()

        # specific voting session info
        voting_number = info.select('//NumeroVotacion/text()').extract()
        if not voting_number:
            self.log('Missing voting number: {u}'.format(u=response.url),
                     level=log.INFO)
            return
        voting_number = voting_number[0]
        voting_title = info.select('//Titulo/text()').extract()[0]
        voting_text = info.select('//TextoExpediente/text()').extract()[0]
        voting_title_sub = info.select('//TituloSubGrupo/text()').extract()
        voting_title_sub = voting_title_sub[0] if voting_title_sub else ''
        voting_text_sub = info.select('//TextoSubGrupo/text()').extract()
        voting_text_sub = voting_text_sub[0] if voting_text_sub else ''

        voting_instance, voting_created = Voting.objects.get_or_create(
            session=session_instance, number=voting_number)
        voting_instance.title = voting_title
        voting_instance.record_text = voting_text
        voting_instance.subgroup_title = voting_title_sub
        voting_instance.subgroup_text = voting_text_sub
        # voting session counters
        counts = x.select('//Resultado/Totales')
        counts_assent = counts.select('//Asentimiento/text()').extract()[0]
        if counts_assent.lower() == 'no':
            counts_assent = False
        else:
            counts_assent = True
        if counts_assent is False:
            counts_presents = counts.select('//Presentes/text()').extract()[0]
            counts_for = counts.select('//AFavor/text()').extract()[0]
            counts_against = counts.select('//EnContra/text()').extract()[0]
            counts_abstentions = counts.select(
                '//Abstenciones/text()').extract()[0]
            counts_dont = counts.select('//NoVotan/text()').extract()[0]

            voting_instance.attendee = counts_presents
            voting_instance.for_votes = counts_for
            voting_instance.against_votes = counts_against
            voting_instance.abstains = counts_abstentions
            voting_instance.no_votes = counts_dont

        voting_instance.assent = counts_assent

        record = response.meta['record']
        initiatives = Initiative.objects.filter(record__exact=record)
        if initiatives:
            voting_instance.initiative_set.add(initiatives.latest('id'))

        voting_instance.save()

        if counts_assent is False:
            # time to parse votes!
            votes = x.select('//Resultado/Votaciones/Votacion')
            Vote.objects.filter(voting=voting_instance).delete()
            votes_list = []
            for v in votes:
                member_seat = v.select('Asiento/text()').extract()[0]
                # @jneight: I don't like search members by name, seats better?
                full_name = v.select('Diputado/text()').extract()[0]
                second_name, first_name = full_name.split(',')
                vote_type = v.select('Voto/text()').extract()[0]
                member_pk = Member.objects.filter(
                    name__iexact=first_name.strip(),
                    second_name__iexact=second_name.strip()).values_list(
                        'pk', flat=True)
                if member_pk:
                    votes_list.append(
                        Vote(voting=voting_instance,
                             member_id=member_pk[0],
                             vote=vote_type))
            Vote.objects.bulk_create(votes_list)

        return voting_instance
Пример #19
0
    def post(self, request):
        voter = request.user.voter

        # Check if the voter has already voted
        # If not yet...
        if not voter.voting_status:
            # Take note of the voter's votes
            votes = []
            poll_votes = []

            # Collect all "voteable" positions
            positions = request.POST.getlist('position')

            # Collect all polls
            polls = request.POST.getlist('poll')

            if positions is not False and len(positions) > 0:
                for position in positions:
                    # For each position, get the voter's pick through its identifier
                    # It should return False when the voter abstained for that position (picked no one)
                    votes.append((
                        position,
                        request.POST.get(position, False),
                    ))

            if polls is not False and len(polls) > 0:
                for poll in polls:
                    poll_votes.append((
                        poll,
                        request.POST.get(poll)
                        [request.POST.get(poll).rfind('-') + 1:],
                    ))

            # Proceed only when there are no duplicate votes and positions
            if self.contains_duplicates(votes) and self.contains_duplicates(
                    poll_votes):
                # If there are no duplicates, convert the list of tuples into a dict
                votes_dict = {}

                for vote in votes:
                    votes_dict[vote[0]] = vote[1]

                votes = votes_dict

                poll_votes_dict = {}

                for poll in poll_votes:
                    poll_votes_dict[poll[0]] = poll[1]

                polls = poll_votes_dict

                try:
                    # Change the identifiers to the actual candidates they represent
                    for position, candidate in votes.items():
                        votes[position] = (
                            Position.objects.get(identifier=position),
                            Candidate.objects.get(identifier=candidate)
                            if candidate is not False else False,
                        )

                    for identifier, answer in polls.items():
                        polls[identifier] = (
                            Poll.objects.get(identifier=identifier),
                            answer,
                        )

                    with transaction.atomic():
                        # Create a vote object to represent a single vote of a user
                        vote = Vote(voter_id_number=voter.user.username,
                                    voter_college=voter.college.name)
                        vote.save()

                        # Generate its serial number
                        serial_number = self.generate_serial_number(vote.id)

                        vote.serial_number = serial_number
                        vote.save()

                        # Create a vote set array representing the individual votes to be saved in the database
                        actual_votes = [
                            VoteSet(vote=vote,
                                    candidate=(position_candidate[1]
                                               if position_candidate[1]
                                               is not False else None),
                                    position=position_candidate[0])
                            for position_candidate in votes.values()
                        ]

                        actual_poll_votes = [
                            PollSet(vote=vote,
                                    poll=(poll[0]),
                                    answer=(poll[1]))
                            for poll in polls.values()
                        ]

                        # Save all votes into the database
                        for actual_vote in actual_votes:
                            actual_vote.save()

                        for actual_poll_vote in actual_poll_votes:
                            actual_poll_vote.save()

                        # Send email receipt
                        self.send_email_receipt(request.user, votes,
                                                serial_number)

                        # Mark the voter as already voted
                        voter.voting_status = True
                        voter.save()

                    # Log the user out
                    logout(request)

                    return redirect('logout:logout_voter')
                except PollAnswerType.ValueError:
                    # One of the votes for the polls is not a valid answer
                    messages.error(
                        request,
                        'Some of your answers to the polls do not exist')

                    return self.get(request)
                except Candidate.DoesNotExist:
                    # One of the votes do not represent a candidate
                    messages.error(
                        request, 'One of your voted candidates do not exist.')

                    return self.get(request)
                except IntegrityError:
                    # A vote has already been created to the voter's name, meaning he has already voted
                    messages.error(request,
                                   'You may have already voted before.')

                    # Log the user out
                    logout(request)

                    voter.voting_status = True
                    voter.save()

                    return redirect('logout:logout_fail')
                # except SMTPException:
                #     # Could not send an email receipt
                #     messages.error(request, 'Could not send an email receipt to your email address.')
                #
                #     return self.get(request)
            else:
                # If there are duplicate votes
                messages.error(
                    request, 'There are duplicate votes in your submission.')

                return self.get(request)
        else:
            # But if the voter already did...
            messages.error(request,
                           'You have already voted. You may only vote once.')

            # Log the user out
            logout(request)

            return redirect('logout:logout_fail')