Beispiel #1
0
    def post(self, request, slug, format=None):
        """
        Submit poll answer
        """
        try:
            poll = get_object_or_none( Poll, article__slug=slug )
            if not poll:
                return Response( { "error": True, "message": "No such Poll" } )
            poll.article.update_cache()
            decr_answer = None
            incr_answer = None
            decr_abstain = False

            # see if the user has already answered, and change the counts.
            new_vote = False
            response = get_object_or_none( PollResponse, user=request.user, poll=poll )
            if not response:
                new_vote = True
                response = PollResponse( user=request.user, poll=poll )
            else:
                if not poll.allow_answer_changes:
                    raise PollAnswerChangeException( "You're not allowed to change your answer to this poll." )
                if response.answer != None:
                    decr_answer = PollAnswer.objects.filter(id=response.answer_id)
                else:
                    decr_abstain = True

            if request.POST.get("Answer",False):
                # this is a real answer, not an abstain
                answer_idx = request.POST.get("answer",None)
                if answer_idx:
                    answer = poll.get_ordered_answers()[int(answer_idx)].pollanswer
                else:
                    return Response( { "error": False } )
            else:
                answer = None

            response.answer = answer
            response.public = request.POST.get('public',False)
            response.save()

            if decr_answer:
                decr_answer.update(answer_count=F('answer_count')-1)
            if decr_abstain and answer:
                Poll.objects.filter( article__slug=slug ).update(abstain_count=F('abstain_count')-1)

            if answer:
                PollAnswer.objects.filter(id=response.answer_id).update(answer_count=F('answer_count')+1)
            else:
                Poll.objects.filter( article__slug=slug ).update(abstain_count=F('abstain_count')+1)

            poll.article.last_action = datetime.now()
            poll.article.save()
            vote_cast.send( sender=Poll, poll=poll, response=response, new_vote=new_vote, voter=request.user )
            return Response( { "error": False } )
        except Exception as e:
            return Response( { "error": True, "message": e.message } )        
Beispiel #2
0
    def get(self, request, slug, format=None):
        """
        Get a Problem with given slug
        """
        try:
            problem = get_object_or_none( Poll, article__slug=slug )
            if not problem:
                return Response( { "error": True, "message": "No such Poll" } )
            my_response = get_object_or_none( PollResponse, user_id=request.user.id, poll_id=problem.id )        
            user = problem.article.author
            name = user.first_name + ' ' + user.last_name
            avatar = bw_get_thumbnail( user.profile.get_avatar(), '21x21').url
            content = render_to_string('bw_restapi/problem_description.html', { 'problem': problem })
            answerMap = problem.get_ordered_answers()
            answers = []
            num_abstentions = problem.pollresponse_set.filter(answer__isnull=True).count()
            my_answer = None
            if my_response:
                my_answer = {
                    'public': my_response.public
                }
                if my_response.answer:
                    my_answer['answer'] = my_response.answer.answer_text
                else:
                    my_answer['answer'] = "Abstain"            
            for answer in answerMap:
                if answer.answer_count > 0:
                    if answer.answer_text.lower() == my_answer['answer'].lower():
                        my_answer['count'] = answer.answer_count;
                    answers.append( { 'text': answer.answer_text, 'count':answer.answer_count } )
            item = {
                'my_answer': my_answer,
                'num_answers': problem.article.num_poll_responses,
                'abstentions': num_abstentions,
                'num_abstentions': num_abstentions,
                'answers': answers,
                'slug': problem.article.slug,
                'description': content,
                'type': problem.poll_type,
                'lin_str': problem.hand.lin_str(),
                'author': name,
                'avatar': avatar,
                'scoring': problem.scoring,
                'vulnerability': problem.vul,
                'auction': problem.auction,
                'dealer': problem.dealer
            }
            item["error"] = False

            return Response( item )
        except Exception as e:
            return Response( { "error": True, "message": e.message } )          
Beispiel #3
0
 def get(self, request, slug, format=None):
     """
     Get the names of responders for a poll
     """
     try:
         problem = get_object_or_none( Poll, article__slug=slug )
         if not problem:
             return Response( { "error": True, "message": "No such Poll" } )            
         my_response = get_object_or_none( PollResponse, user_id=request.user.id, poll_id=problem.id )
         if not my_response:
             return Response({ 'success': False, 'message': 'Sorry, you have to vote publicly to see public poll results.' })
         answerMap = problem.get_ordered_answers()
         responses = []
         for answer in answerMap:
             if answer.answer_count > 0:
                 item = {
                     'answer_text': answer.answer_text,
                     'num_private_responses': answer.pollresponse_set.filter(public=False).count(),
                     'public_responses': []
                 }
                 
                 for response in answer.pollresponse_set.filter(public=True).order_by("-user__stats__num_followers"):
                     user = response.user
                     name = user.first_name + ' ' + user.last_name
                     item[ 'public_responses' ].append(name)
                 responses.append(item)
         num_abstentions = problem.pollresponse_set.filter(answer__isnull=True).count()
         if num_abstentions > 0:
             item = {
                 'answer_text': 'Abstain',
                 'num_private_responses': problem.pollresponse_set.filter(public=False,answer__isnull=True).count(),
                 'public_responses': []
             }
             for response in problem.pollresponse_set.filter(public=True,answer__isnull=True):
                 user = response.user
                 name = user.first_name + ' ' + user.last_name
                 item[ 'public_responses' ].append(name)
             responses.append(item)            
         return Response({ 'responses': responses, 'success': True, 'type': problem.poll_type })
     except Exception as e:
         return Response( { "error": True, "message": e.message } )          
Beispiel #4
0
 def get(self, request, slug, format=None):
     """
     Update count
     """
     try:
         problem = get_object_or_none( Poll, article__slug=slug )
         if not problem:
             return Response( { "error": True, "message": "No such Poll" } )
         problem.article.num_poll_responses = problem.pollresponse_set.count()
         problem.article.save()
         return Response({ "error": False  })
     except Exception as e:
         return Response( { "error": True, "message": e.message } )         
Beispiel #5
0
 def get(self, request, slug, format=None):
     """
     Get a Problem with given slug
     """
     try:
         problem = get_object_or_none( Poll, article__slug=slug )
         if not problem:
             return Response( { "error": True, "message": "No such Poll" } )                 
         if not problem.article.unpublished:
             problem.article.toggle_publish()
             return Response({ "error": False  })
         return Response({ "error": True, 'message': 'Already unpublished' })
     except Exception as e:
         return Response( { "error": True, "message": e.message } )         
Beispiel #6
0
 def post(self, request, format=None):
     """
     Get Recent Published Problems
     """
     try:
         start = int(request.POST.get( "start", 0))
         end = int(request.POST.get( "end", 0))
         end = end+1
         recent_polls = Poll.objects.filter(article__author_id=request.user.id).exclude(article__unpublished=True).exclude(poll_type='Basic').order_by('-created')[start:end]
         answers = []
         for poll in recent_polls:
             num_abstentions = poll.pollresponse_set.filter(answer__isnull=True).count()
             num_answers = poll.article.num_poll_responses
             user = poll.article.author
             name = user.first_name + ' ' + user.last_name
             avatar = bw_get_thumbnail( user.profile.get_avatar(), '21x21').url
             answerMap = poll.get_ordered_answers()
             all_answers = []
             for item in answerMap:
                 if item.answer_count > 0:
                     itemPercent = int( 100.0 * float( item.answer_count ) / (num_answers - num_abstentions)  + 0.5 )
                     all_answers.append( { 'text': item.answer_text, 'count':item.answer_count, 'percent': itemPercent } )
             my_response = get_object_or_none( PollResponse, user_id=request.user.id, poll_id=poll.id )        
             my_answer = None
             if my_response:
                 my_answer = {
                     'public': my_response.public
                 }
                 if my_response.answer:
                     my_answer['count'] = my_response.answer.answer_count
                     my_answer['answer'] = my_response.answer.answer_text
                 else:
                     my_answer['count'] = num_abstentions
                     my_answer['answer'] = "Abstain"                            
             item = {
                 'type': poll.poll_type,
                 'slug': poll.article.slug,
                 'lin_str': poll.hand.lin_str(),
                 'num_answers': num_answers,
                 'num_abstentions': num_abstentions,
                 'avatar': avatar,
                 'author': name,
                 'answers': all_answers,
                 'my_answer': my_answer                    
             }
             answers.append(item)
                 
         return Response( { "error": False, "recent_answers": answers } )
     except Exception as e:
         return Response( { "error": True, "message": e.message } )         
Beispiel #7
0
    def post(self, request, format=None):
        """
        Create New Problem
        """
        try:
            poll = None
            pollType = request.POST.get( "type", "Bidding" )
            
            article = get_object_or_none( Article, slug=None )

            if is_probated( request.user ):
                return Response( { "error": True, "message": "You cannot create or edit problems while suspended." } )
            if is_banned( request.user ):
                return Response( { "error": True, "message": "You cannot create or edit problems while banned." } )
            
            if pollType == "Bidding":
                form = BiddingProblemForm( request.user, request.POST or None, instance=article )
            else:
                form = LeadProblemForm( request.user, request.POST or None, instance=article )
                    
            if form.is_valid():
                article = form.save(commit=False)
                if not form.cleaned_data.get("author",None):
                    article.author = request.user
                article.quick = True
                article.hide_on_front_page = True
                article.save()
                article.post_inline_save()

                if pollType == "Bidding":
                    answers = [
                        '1c','1d','1h','1s','1n',
                        '2c','2d','2h','2s','2n',
                        '3c','3d','3h','3s','3n',
                        '4c','4d','4h','4s','4n',
                        '5c','5d','5h','5s','5n',
                        '6c','6d','6h','6s','6n',
                        '7c','7d','7h','7s','7n',
                        'X','R','P'
                    ]
                else:
                    answers = [
                        'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9', 'CT', 'CJ', 'CQ', 'CK', 'CA', 'Cx',
                        'D2', 'D3', 'D4', 'D5', 'D6', 'D7', 'D8', 'D9', 'DT', 'DJ', 'DQ', 'DK', 'DA', 'Dx',
                        'H2', 'H3', 'H4', 'H5', 'H6', 'H7', 'H8', 'H9', 'HT', 'HJ', 'HQ', 'HK', 'HA', 'Hx',
                        'S2', 'S3', 'S4', 'S5', 'S6', 'S7', 'S8', 'S9', 'ST', 'SJ', 'SQ', 'SK', 'SA', 'Sx',
                    ]                             
                poll = get_object_or_none( Poll, article=article )
                if poll:
                    poll.content=form.cleaned_data["description"]
                    poll.auction=form.cleaned_data["auction"]
                    poll.vul=form.cleaned_data["vul"]
                    poll.dealer=form.cleaned_data["dealer"]
                    poll.scoring=form.cleaned_data["scoring"]
                    poll.hand=form.cleaned_data["hand"]
                    poll.save()
                else:
                    poll = Poll.objects.create( poll_type=pollType, content=form.cleaned_data["description"], auction=form.cleaned_data['auction'], vul=form.cleaned_data['vul'], scoring = form.cleaned_data['scoring'], dealer=form.cleaned_data['dealer'], hand=form.cleaned_data['hand'], article=article )
                    for i,answer in enumerate(answers):
                        PollAnswer.objects.create( order=i, question=poll.multiplechoicequestion_ptr, answer_text=answer )
                # Preview will be done on client side. Publish immediately
                article.toggle_publish()
                return Response( { "error": False, "slug": article.slug } )
            return Response( { "error": True, "message": "Form data is not valid." } )
        except Exception as e:
            return Response( { "error": True, "message": e.message } )