class AngelSerializer(serializers.ModelSerializer): owned_tasks = TaskSerializer(many=True, read_only=True) helped_tasks = TaskSerializer(many=True, read_only=True) class Meta: model = Angel fields = ('id', 'real_name', 'contribution', 'owned_tasks', 'helped_tasks') read_only_fields = ('id', 'real_name', 'contribution')
def cancel(request, pk): task = get_object_or_404(Task, pk=pk) if request.user.angel not in [task.owner, task.helper]: raise serializers.ValidationError('cannot cancel not-owned or -helped task') if task.status not in [Task.CREATED, Task.ACCEPTED, Task.FINISHED]: raise serializers.ValidationError('invalid task status') task.status = Task.CANCELED task.canceled_at = timezone.now() task.save() return Response(TaskSerializer(task).data)
def accept(request, pk): task = get_object_or_404(Task, pk=pk) if request.user.angel == task.owner: raise serializers.ValidationError('cannot accept owned task') if task.status != Task.CREATED: raise serializers.ValidationError('invalid task status') task.status = Task.ACCEPTED task.helper = request.user.angel task.save() return Response(TaskSerializer(task).data)
def complete(request, pk): task = get_object_or_404(Task, pk=pk) if request.user.angel != task.owner: raise serializers.ValidationError('cannot complete not-owned task') if task.status != Task.FINISHED: raise serializers.ValidationError('invalid task status') task.status = Task.COMPLETED task.save() task.helper.contribution += task.contribution task.helper.save() return Response(TaskSerializer(task).data)
def finish(request, pk): task = get_object_or_404(Task, pk=pk) if request.user.angel != task.helper: raise serializers.ValidationError('cannot finish not-helped task') if task.status != Task.ACCEPTED: raise serializers.ValidationError('invalid task status') task.status = Task.FINISHED try: contribution = request.data['contribution'] assert 0 <= contribution <= task.cost task.contribution = contribution except: raise serializers.ValidationError('invalid contribution') task.save() return Response(TaskSerializer(task).data)