Exemple #1
0
def create_vote(request, id):
    ''' Add a new vote to the system. '''

    # TODO:
    # - only allow a user to vote once on each ticket
    # - include the time that the vote was registered
    # - display a confirmation message in the template using the django messaging system

    ticket = get_object_or_404(Ticket, id=id)
    vote = Vote(ticket=ticket, user=request.user)

    if ticket.type == 'feature':
        vote.completed = True
        vote.save()
        #  Confirm Success message ######
        messages.success(request,
                         "Your Vote has been added to the Payment Feature!")

        return redirect('payment_form', id)

    else:
        # is a bug
        vote.completed = True
        vote.save()

        # Add confirmation message
        messages.success(request, "Your Vote has been added to the bug!")

    return redirect('ticket_detail', id)
Exemple #2
0
def add_vote(article, user, vote_value):
    vote = Vote()
    apply_article_rating(article, vote_value)
    vote.voteUrl = article
    vote.voter = user
    vote.voteValue = vote_value
    vote.save()
    json_data = vote.as_json()
    return json_data
Exemple #3
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))
Exemple #4
0
def vote(request):
    if request.method == "POST":
        vote = Vote()
        vote.img_a = Image.objects.get(pk=request.POST["img_a"])
        vote.img_b = Image.objects.get(pk=request.POST["img_b"])
        vote.user = request.user
        vote.winner = Image.objects.get(pk=request.POST["winner"])
        vote.save()

    img_a, img_b = contenders(request.user)

    return render(request, 'vote/vote.html', {"img_a": img_a, "img_b": img_b})
Exemple #5
0
def vote(request, question_id, wechat_id=None):
    if request.method == "GET":
        question = get_object_or_404(Question, pk=question_id)
        choices = Choice.objects.filter(question=question)
        gt = geetest.geetest(settings.CAPTCHA_ID, settings.PRIVATE_KEY)
        challenge = gt.geetest_register()
        BASE_URL = "api.geetest.com/get.php?gt="
        if len(challenge) == 32:
            geetest_url = "http://%s%s&challenge=%s&product=embed" % (BASE_URL, settings.CAPTCHA_ID, challenge)
        context = {
            "question": question,
            "choices": choices,
            "geetest_url": geetest_url,
        }
        return render(request, "vote/vote-page.html", context=context)

    if request.method == "POST":
        challenge = request.POST.get('geetest_challenge', '')
        validate = request.POST.get('geetest_validate', '')
        seccode = request.POST.get('geetest_seccode', '')
        gt = geetest.geetest(settings.CAPTCHA_ID, settings.PRIVATE_KEY)
        result = gt.geetest_validate(challenge, validate, seccode)
        if not result:
            messages.warning(request, '验证失败')
            return redirect(reverse('vote-page', args=(question_id,)))
        if wechat_id == None:
            try:
                user = VoteUser.objects.get(username=request.session["vote_user"])
            except:
                messages.warning(request, '请先登录投票系统或发送"投票"到微信公众号"创新人才"获取投票链接')
                return redirect(reverse('vote-page', args=(question_id,)))
        else:
            try:
                user = VoteUser.objects.get(openid=wechat_id)
            except:
                messages.warning(request, '用户ID无效,请发送"投票"到微信公众号"创新人才"获取相关信息')
                return redirect(reverse('vote-page', args=(question_id,)))
        question = get_object_or_404(Question, pk=question_id)
        polls = request.POST.getlist("check_box_list")
        if len(polls) > question.max_choice:
            polls = polls[:question.max_choice]
        for poll in polls:
            poll_obj = get_object_or_404(Choice, id=int(poll))
            vote = Vote(choice=poll_obj, user=user)
            vote.save()
        messages.success(request, "投票成功~谢谢您的参与~")
        return redirect(reverse('vote_page', args=(question_id,)))
Exemple #6
0
def voteProposition(request):
    resp = {}
    user = VoteUser.objects.filter(userkey=request.GET.get('userkey'))[0]
    if (user is None):
        resp['code'] = 'authentication error'
        return HttpResponse(json.dumps(resp), content_type='application/json')

    proposition = VoteProposition.objects.filter(
        id=request.GET.get('propositionid'))[0]
    votes = Vote.objects.filter(user=user, proposition=proposition)
    if (votes.count() == 0):
        v = Vote()
    else:
        v = votes[0]
        if (v.voteType == 1):
            proposition.strongDisagreeNb -= 1
        if (v.voteType == 2):
            proposition.disagreeNb -= 1
        if (v.voteType == 3):
            proposition.agreeNb -= 1
        if (v.voteType == 4):
            proposition.strongAgreeNb -= 1

    v.proposition = proposition
    v.user = user
    #1-pro, 2-against
    v.voteType = int(request.GET.get('type'))
    if (v.voteType == 1):
        proposition.strongDisagreeNb += 1
    if (v.voteType == 2):
        proposition.disagreeNb += 1
    if (v.voteType == 3):
        proposition.agreeNb += 1
    if (v.voteType == 4):
        proposition.strongAgreeNb += 1
    proposition.save()
    v.save()
    resp['id'] = v.id
    resp['strongDisagreeNb'] = proposition.strongDisagreeNb
    resp['disagreeNb'] = proposition.disagreeNb
    resp['agreeNb'] = proposition.agreeNb
    resp['strongAgreeNb'] = proposition.strongAgreeNb
    return HttpResponse(json.dumps(resp), content_type='application/json')
Exemple #7
0
def cast(request, poll_id, candidate_id):

    #Acquire data about the logged in user
    username = request.user.username
    student = Student.objects.get(user=request.user)

    #Assure that student is able to vote in the selected poll and has not already voted.
    #Also assure that the selected candidate is contesting for the selected poll
    try:
        poll = Poll.objects.get(
            id=poll_id)  #Extract poll data. Generate Exception if not found
        assert poll.active  #ensure that the poll is running
        assert poll.category == "HR" or poll.grade == student.grade  #Ensure that student is allowed to vote
        assert student not in poll.voted.all(
        )  #Ensure that the student has not already voted
        assert Candidate.objects.get(id=candidate_id) in poll.candidates.all(
        )  #Verify selected candidate_id
    except:
        return HttpResponseRedirect("/index/")  #Go back to polls page

    #Mark the logged in student as voted in the selected poll
    poll.voted.add(student)
    poll.save()

    #Get the selected candidate's data and current time
    candidate = Candidate.objects.get(id=candidate_id)
    poll_date = time.strftime("%Y-%m:%D")
    poll_time = time.strftime("%H:%M:%S")

    #Add a vote for the selected candidate in the Vote table
    vote_to_cast = Vote(poll=poll,
                        candidate=candidate,
                        poll_date=poll_date,
                        poll_time=poll_time)
    vote_to_cast.save()

    return HttpResponseRedirect(
        "/index/?vote_casted=True")  #Redirect to polls page
Exemple #8
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, ex:
            log.error('Error in processing %s' % fname, exc_info=ex)
            had_error = True
Exemple #9
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)
Exemple #10
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 
Exemple #11
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)
    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')
Exemple #13
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
Exemple #14
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
Exemple #15
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)