Пример #1
0
def award_points(request, answer_id, queryset=Answer.objects.all()):
    """ do transfer point from question's author to answerer """
    answer = get_object_or_404(queryset, id=answer_id)
    
    if request.user == answer.author:
        raise Http404(_(u'You can not award yourself!'))
    elif answer.question.author != request.user:
        raise Http404(_(u'This is not your question!'))
    elif answer.question.bounty_points:
        points = answer.question.bounty_points
        reason=ugettext(u'Award points to answer: %(answer)s') % {'answer': answer }
        try:
            UnitPack.consume(request.user, quantity=points, reason=reason)
        except ValueError, msg:
            url = construct_main_site_url(reverse('prepaid-index', urlconf=settings.MUACCOUNTS_MAIN_URLCONF))
            if request.is_ajax():
                data = simplejson.dumps({'not_enough_credits': '1',
                                         'available_credits': UnitPack.get_user_credits(request.user),
                                         'required_credits': points,
                                         'awarded': '0'})
                return HttpResponse(data, mimetype="application/json")
            else:
                return HttpResponseRedirect(url)
        else:
            UnitPack.credit(answer.author, quantity=points, reason=reason)
            PointAward(answer=answer, points=points).save()
            
            if request.is_ajax():
                data = simplejson.dumps({'not_enough_credits': '0', 
                                         'awarded': '1'})
                return HttpResponse(data, mimetype="application/json")
            else:
                return redirect(answer)
Пример #2
0
def task_do(request, object_id):
	task = get_object_or_404(Task, pk=object_id, published=True)
	if task.is_expired():
		return _activity_expired(request, task)
	
	# Create or retrieve achievement
	achievement = None
	remaining = task.get_chances_remaining(request.user)
	try:
		achievement = Achievement.objects.get(user=request.user, task=task, complete=False)
		if achievement.is_expired:
			# Reset achievement time as long as there is room on the waiting list
			if remaining > 0:
				achievement.date_started = datetime.datetime.now()
			else:
				request.user.message_set.create(message='Sorry, your time to complete this task has run out.')
				return redirect('tasks-task_detail', task.id)
	except Achievement.DoesNotExist:
		if remaining > 0:
			a = Achievement()
			a.task = task
			a.user = request.user
			a.save()
			achievement = a
			
	if not achievement:
		request.user.message_set.create(message='Sorry, you can\'t do that.')
	
	if request.method == 'POST':
		try:
			questions = task.questions.all()
			modified = []
			errors = []
			for form_id, question in zip(range(1, questions.count()+1), questions):
				typ = question.type
				data = question.data
				error = None
				if typ == 'poll':
					choices = map(int, request.POST.getlist('choice%s' % form_id))
					for choice in choices:
						data['answers'][choice]['count'] += 1
					
				elif typ == 'text':
					answer = request.POST['answer%s' % form_id].strip()
					if len(answer):
						data['answers'].append(answer)
					else:
						error = 'You must answer the question!'
				else:
					error = 'Invalid Task'
				"""
				elif typ == TaskType.QUIZ:
					choice = int(request.POST['choice'])
					if choice != data['answer']:
						error = 'Sorry, you answered incorrectly.'
					
				elif typ == TaskType.POST:
					request.twitter.set_status(data['message'])
				"""
				
					
				if error:
					errors.append(error)
					question.error = error
				else:
					question.data = data
				modified.append(question)
					
			if errors:
				# FIXME: Delete achievement and form if theres an error??
				# Maybe it should reload the form with info filled in somehow
				#achievement.delete()
				#return redirect('tasks-task_detail', task.id)
				return {'task':task, 'questions':modified}
			else:
				# No errors, yay!
				for m in modified:
					m.save()
				task.budget -= task.points
				task.save()
				
				achievement.complete = True
				achievement.save()
				if task.points > 0:
					UnitPack.credit(request.user, task.points, reason=COMPLETED_REASON % {'task':task.name})
					request.user.message_set.create(message='You earned %s points. How exciting!' % task.points)
				else:
					request.user.message_set.create(message='You didn\'t earn any points. But at least you had fun!')
				
				return redirect('tasks-task_detail', task.id)
			
		except KeyError, e:
			request.user.message_set.create(message='Error: Please complete all required fields')
Пример #3
0
	def delete(self):
		if self.budget > 0:
			UnitPack.credit(self.user, self.budget)
		super(Task, self).delete()