def test_usecase(self):
        self.assertEqual(self.model.state, 'new')
        self.assertTrue(can_proceed(self.model.remove))
        self.model.remove()

        self.assertEqual(self.model.state, 'removed')
        self.assertFalse(can_proceed(self.model.remove))
Example #2
0
def build_settlement(request):
    gs_id = int(request.GET["gs_id"])
    game_state = GameState.objects.get(id=gs_id)

    if not can_proceed(game_state.build) and not can_proceed(game_state.setup):
        raise PermissionDenied

    vertex_id = request.GET["vertex"]  # vertex_id form is t1SVGvertexSW
    tile_index = int(vertex_id[1:vertex_id.find('v')])
    key_direction = vertex_id[vertex_id.rfind('r')+1:]

    is_first_build = game_state.state == 'initialized'
    the_game = pickle.loads(game_state.pickled_game)
    the_board = the_game.board
    the_tile = the_board.board_tiles[tile_index]
    the_vertex = the_tile.vertices[key_direction]
    current_player = the_game.current_player
    settlement = current_player.get_next_settlement()

    if settlement:
        is_built = current_player.build_settlement(settlement, the_vertex, is_first_build)
        if is_built:
            if is_first_build:
                pass  # prevent more settlements from being built?
            else:
                game_state.state = 'built'
            game_state.pickled_game = pickle.dumps(the_game)
            game_state.cooked_json_data = cook_the_json(the_game, game_state)
            game_state.save()

    return HttpResponse(game_state.cooked_json_data)
Example #3
0
    def test_unmet_condition(self):
        self.model.publish()
        self.assertEqual(self.model.state, 'published')
        self.assertFalse(can_proceed(self.model.destroy))
        self.assertRaises(TransitionNotAllowed, self.model.destroy)

        self.assertTrue(can_proceed(self.model.destroy,
                                    check_conditions=False))
Example #4
0
    def test_known_transition_should_succeed(self):
        self.assertTrue(can_proceed(self.model.publish))
        self.model.publish()
        self.assertEqual(self.model.state, 'published')

        self.assertTrue(can_proceed(self.model.hide))
        self.model.hide()
        self.assertEqual(self.model.state, 'hidden')
Example #5
0
    def get_user_task_url(self, task, user=None, url_type=None, **kwargs):
        flow_task = task.flow_task

        if user:
            if url_type is None:
                if can_proceed(task.prepare) and hasattr(flow_task, 'can_execute') and flow_task.can_execute(user, task):
                    return flow_task.get_task_url(task, 'execute', **kwargs)
                elif can_proceed(task.assign) and hasattr(flow_task, 'can_assign') and flow_task.can_assign(user, task):
                    return flow_task.get_task_url(task, 'assign', **kwargs)
            else:
                return flow_task.get_task_url(task, url_type, **kwargs)

        return flow_task.get_task_url(task, 'details', **kwargs)
Example #6
0
def build_city(request):
    gs_id = int(request.GET["gs_id"])
    game_state = GameState.objects.get(id=gs_id)

    if not can_proceed(game_state.build):
        raise PermissionDenied

    # vertex_id form is t9SettlementNW for settlement
    vertex_id = request.GET["vertex"]
    tile_index = int(vertex_id[1:vertex_id.find('S')])
    key_direction = vertex_id[vertex_id.rfind('t')+1:]

    the_game = pickle.loads(game_state.pickled_game)
    the_board = the_game.board
    the_tile = the_board.board_tiles[tile_index]
    the_vertex = the_tile.vertices[key_direction]
    current_player = the_game.current_player
    city = current_player.get_next_city()

    if city:
        is_built = current_player.build_city(city, the_vertex)
        if is_built:
            game_state.state = 'built'
            game_state.pickled_game = pickle.dumps(the_game)
            game_state.cooked_json_data = cook_the_json(the_game, game_state)
            game_state.save()

    return HttpResponse(game_state.cooked_json_data)
Example #7
0
def update_order(transaction):
    import logging
    from django_fsm import can_proceed
    from orders.utils import get_order, order2json, FraudAttemptError
    from privat24.integration import Privat24Integration
    logger = logging.getLogger('app')
    try:
        order, order_json = get_order(transaction.get('order'))
    except FraudAttemptError as e:
        logger.error(u'update_order: Have error: %s' % e.message)
    if order:
        local_json = order2json(order)
        if local_json == order_json:
            if order.transaction_id == transaction.pk:
                pass
            else:
                order.transaction = transaction
                order.save()
            p24 = Privat24Integration()
            valid_statuses = p24.get_valid_statuses()
            if transaction.state in valid_statuses:
                if can_proceed(order.pay):
                    order.pay()
                    order.save()
        else:
            logger.error("update_order: Order properties is not identical:")
            logger.error("update_order:   Local: %s" % local_json)
            logger.error("update_order:  Remote: %s" % order_json)
    return None
Example #8
0
def pass_turn(request):
    gs_id = int(request.GET["gs_id"])
    game_state = GameState.objects.get(id=gs_id)

    if not can_proceed(game_state.pass_turn):
        raise PermissionDenied

    the_game = pickle.loads(game_state.pickled_game)

    # allow any development cards bought this turn to be playable next turn
    for card in the_game.current_player.development_cards:
        if isinstance(card, ProgressCard):
            card.can_play = True
        if type(card) is KnightCard:
            if not card.is_played:
                card.can_play = True

    # change current players
    if the_game.players.index(the_game.current_player) == len(the_game.players) - 1:
        the_game.current_player = the_game.players[0]
    else:
        the_game.current_player = the_game.players[the_game.players.index(the_game.current_player) + 1]

    game_state.state = 'new'
    game_state.pickled_game = pickle.dumps(the_game)
    game_state.cooked_json_data = cook_the_json(the_game, game_state)
    game_state.save()

    return HttpResponse(game_state.cooked_json_data)
 def test_plus_shortcut_succeeds_for_other_source(self):
     """Tests that the '+' shortcut succeeds for a source
     other than the target.
     """
     self.assertTrue(can_proceed(self.model.block))
     self.model.block()
     self.assertEqual(self.model.state, 'blocked')
Example #10
0
def roll(request):
    gs_id = int(request.GET["gs_id"])
    game_state = GameState.objects.get(id=gs_id)

    if not can_proceed(game_state.roll):
        raise PermissionDenied

    the_game = pickle.loads(game_state.pickled_game)

    the_game.current_player.roll_dice()
    the_game.distribute_resources(the_game.current_player.die_value)
    game_state.state = 'rolled'

    # note: game state only goes to 'rolled_seven' if there are players with over 7 cards
    # in the future when move_robber() is written, it will always go to 'rolled_seven'
    if the_game.current_player.die_value == 7:
        the_game.rolled_seven()
        if the_game.players_to_discard:
            game_state.state = 'rolled_seven'
        else:
            # skip 'rolled seven' state if no players need to discard any cards
            game_state.state = 'discarded'

    game_state.pickled_game = pickle.dumps(the_game)
    game_state.cooked_json_data = cook_the_json(the_game, game_state)
    game_state.save()

    return HttpResponse(game_state.cooked_json_data)
Example #11
0
def trade(request):

    gs_id = int(request.GET["gs_id"])
    game_state = GameState.objects.get(id=gs_id)

    if not can_proceed(game_state.trade):
        raise PermissionDenied

    the_game = pickle.loads(game_state.pickled_game)
    is_successful = False
    take = request.GET["take"]

    give4 = request.GET["give4"]
    if give4 != "" and give4 != "Select a resource":
        is_successful = the_game.current_player.trade(give4, take, None)

    give3 = request.GET["give3"]
    if give3 != "" and give3 != "Select a resource":
        is_successful = the_game.current_player.trade(give3, take, 'wild')

    give2 = request.GET["give2"]
    if give2 != "" and give2 != "Select a resource":
        is_successful = the_game.current_player.trade(give2, take, give2)

    if is_successful:
        game_state.state = 'traded'
        game_state.pickled_game = pickle.dumps(the_game)
        game_state.cooked_json_data = cook_the_json(the_game, game_state)
        game_state.save()

    return HttpResponse(game_state.cooked_json_data)
Example #12
0
def discard(request):
    gs_id = int(request.GET["gs_id"])
    game_state = GameState.objects.get(id=gs_id)

    if not can_proceed(game_state.discard):
        raise PermissionDenied

    the_game = pickle.loads(game_state.pickled_game)

    card_id = request.GET['card']  # in form of player1woolCard11
    player_id = int(card_id[card_id.find('r')+1:card_id.find('r')+2])
    card_num = int(card_id[card_id.rfind('d')+1:card_id.rfind('d')+2])
    player = the_game.players[player_id]

    # more of this should probably be done in models.py. Change later.
    if player.color in the_game.players_to_discard:
        num_to_discard = the_game.players_to_discard[player.color]
        if num_to_discard > 0:
            player.resource_deck.put_card(player.resource_cards.pop(card_num))
            the_game.players_to_discard[player.color] = num_to_discard - 1
            for key, value in the_game.players_to_discard.items():
                if value <= 0:
                    the_game.players_to_discard.pop(key)

            # if the players are all done discarding their cards...
            if not the_game.players_to_discard:
                game_state.state = 'discarded' # used to be 'rolled'

            game_state.pickled_game = pickle.dumps(the_game)
            game_state.cooked_json_data = cook_the_json(the_game, game_state)
            game_state.save()

    return HttpResponse(game_state.cooked_json_data)
Example #13
0
def flow_perms(user, task):
    """
    Assigns list of permissions

    {% flow_perms request.user task as task_perms  %}
    """
    result = []

    if can_proceed(task.prepare) and hasattr(task.flow_task, 'can_execute') and task.flow_task.can_execute(user, task):
        result.append('can_execute')
    elif can_proceed(task.assign) and hasattr(task.flow_task, 'can_assign') and task.flow_task.can_assign(user, task):
        result.append('can_assign')
    elif hasattr(task.flow_task, 'can_view') and task.flow_task.can_view(user, task):
        result.append('can_view')

    return result
Example #14
0
def return_request(request):
    p24 = Privat24Integration()
    post_data, payment, result = p24.get_transaction(request)
    if payment:
        order = None
        try:
            order, order_json = get_order(post_data.get("order"))
        except FraudAttemptError as e:
            logger.error(u"return_request: Have error: %s" % e.message)
        if order:
            local_json = order2json(order)
            if local_json == order_json:
                if order.transaction_id == payment.pk:
                    pass
                else:
                    order.transaction = payment
                    order.save()
                valid_statuses = p24.get_valid_statuses(True)
                # logger.info("return_request: valid_statuses: %s" % valid_statuses)
                # logger.info("return_request: payment state: %s" % payment.state)
                if payment.state in valid_statuses:
                    if payment.state == P24_STATE_WAIT:
                        pass
                    else:
                        if can_proceed(order.pay):
                            order.pay()
                            order.save()
                    # request.session[ORDER_ID] = order.pk
                    to = reverse("payments-thank-you")
                    return redirect(to)
            else:
                logger.error("return_request: Order properties is not identical:")
                logger.error("return_request:   Local: %s" % local_json)
                logger.error("return_request:  Remote: %s" % order_json)
    return redirect("home")
Example #15
0
def play_plenty_card(request):
    gs_id = int(request.GET["gs_id"])
    game_state = GameState.objects.get(id=gs_id)

    if not can_proceed(game_state.play):
        raise PermissionDenied

    the_game = pickle.loads(game_state.pickled_game)
    card_index = int(request.GET["card"])

    if the_game.current_player.development_cards[card_index].can_play:
        resource1 = request.GET["resource1"]
        resource2 = request.GET["resource2"]

        card1 = the_game.resource_deck.get_card(resource1)
        card2 = the_game.resource_deck.get_card(resource2)

        if card1 is not None and card2 is not None:
            the_game.current_player.resource_cards.append(card1)
            the_game.current_player.resource_cards.append(card2)

            plenty_card = the_game.current_player.development_cards.pop(card_index)
            the_game.development_deck.put_card(plenty_card)
        else:
            the_game.resource_deck.put_card(card1)
            the_game.resource_deck.put_card(card2)

    # may not be necessary -- might not change state at all
    # game_state.state = request.GET["prior_state"]

    game_state.pickled_game = pickle.dumps(the_game)
    game_state.cooked_json_data = cook_the_json(the_game, game_state)
    game_state.save()

    return HttpResponse(game_state.cooked_json_data)
Example #16
0
def play_monopoly_card(request):
    gs_id = int(request.GET["gs_id"])
    game_state = GameState.objects.get(id=gs_id)

    if not can_proceed(game_state.play):
        raise PermissionDenied

    the_game = pickle.loads(game_state.pickled_game)

    card_index = int(request.GET["card"])
    if the_game.current_player.development_cards[card_index].can_play:
        chosen_resource = request.GET["resource"]

        # put this in Game class and possibly shorten it
        for player in the_game.players:
            if player is not the_game.current_player:
                card_to_give = player.get_card(chosen_resource)
                if card_to_give:
                    the_game.current_player.resource_cards.append(card_to_give)
                while card_to_give:
                    card_to_give = player.get_card(chosen_resource)
                    if card_to_give:
                        the_game.current_player.resource_cards.append(card_to_give)

        monopoly_card = the_game.current_player.development_cards.pop(card_index)
        the_game.development_deck.put_card(monopoly_card)

    # may not be necessary -- might not change state at all
    # game_state.state = request.GET["prior_state"]

    game_state.pickled_game = pickle.dumps(the_game)
    game_state.cooked_json_data = cook_the_json(the_game, game_state)
    game_state.save()

    return HttpResponse(game_state.cooked_json_data)
 def test_plus_shortcut_fails_for_same_source(self):
     """Tests that the '+' shortcut fails if the source
     equals the target.
     """
     self.model.block()
     self.assertFalse(can_proceed(self.model.block))
     self.assertRaises(TransitionNotAllowed, self.model.block)
Example #18
0
    def dispatch(self, request, *args, **kwargs):
        if not can_proceed(self.task.assign):
            messages.info(request, 'Task cannot be assigned')
            return redirect(self.task.get_absolute_url(user=request.user))

        if not self.flow_task.can_assign(request.user, self.task):
            raise PermissionDenied
        return super(AssignView, self).dispatch(request, *args, **kwargs)
Example #19
0
    def dispatch(self, request, *args, **kwargs):
        if not can_proceed(self.task.prepare):
            messages.info(request, 'Task cannot be executed')
            return redirect(self.task.get_absolute_url(user=request.user, url_type='details'))

        if not self.has_perm(request.user):
            raise PermissionDenied

        self.prepare(request.POST or None)
        return super(TaskActivationViewMixin, self).dispatch(request, *args, **kwargs)
Example #20
0
def flow_perms(user, task):
    """
    Assign list of permissions.

    Example::

        {% flow_perms request.user task as task_perms  %}

    """
    result = []

    if can_proceed(task.prepare) and hasattr(task.flow_task, "can_execute") and task.flow_task.can_execute(user, task):
        result.append("can_execute")
    elif can_proceed(task.assign) and hasattr(task.flow_task, "can_assign") and task.flow_task.can_assign(user, task):
        result.append("can_assign")
    elif hasattr(task.flow_task, "can_view") and task.flow_task.can_view(user, task):
        result.append("can_view")

    return result
Example #21
0
    def stolen(self, request, pk):
        bike = get_object_or_404(Bike, pk=pk)
        state = BikeState.TRANSFERRED_TO_POLICE
        if not can_proceed(bike.transfer_to_police):
            raise ValidationError(detail=f'Transition from {bike.state} to {state}')

        bike.transfer_to_police()
        bike.save()

        serializer = BikeSerializer(bike, context={'request': request})
        return Response(serializer.data, status=status.HTTP_200_OK)
Example #22
0
    def assessed(self, request, pk):
        bike = get_object_or_404(Bike, pk=pk)
        state = BikeState.ASSESSED.lower()
        if not can_proceed(bike.assessed):
            raise ValidationError(detail=f'Transition from {bike.state} to {state}')

        bike.assessed()
        bike.save()

        serializer = BikeSerializer(bike, context={'request': request})
        return Response(serializer.data, status=status.HTTP_200_OK)
Example #23
0
    def available(self, request, pk):
        bike = get_object_or_404(Bike, pk=pk)
        state = BikeState.AVAILABLE
        if not can_proceed(bike.available):
            raise ValidationError(detail=f'Transition from {bike.state} to {state} failed.')

        bike.available()
        bike.save()

        serializer = BikeSerializer(bike, context={'request': request})
        return Response(serializer.data, status=status.HTTP_200_OK)
Example #24
0
    def claim(self, request, pk):
        bike = get_object_or_404(Bike, pk=pk)
        member = get_object_or_404(Member, id=request.data.get('member'))
        state = BikeState.CLAIMED
        if not can_proceed(bike.claimed):
            raise ValidationError(detail=f'Transition from {bike.state} to {state}')

        bike.claimed(member)
        bike.save()

        serializer = BikeSerializer(bike, context={'request': request})
        return Response(serializer.data, status=status.HTTP_200_OK)
Example #25
0
def build_road(request):
    gs_id = int(request.GET["gs_id"])
    game_state = GameState.objects.get(id=gs_id)

    if not can_proceed(game_state.build) and not can_proceed(game_state.setup):
        raise PermissionDenied

    edge_id = request.GET["edge"]  # in form of t5edgeNE
    tile_index = int(edge_id[1:edge_id.find('e')])
    key_direction = edge_id[edge_id.rfind('e')+1:]

    is_free_build = game_state.state == 'initialized' or game_state.state == 'played_road'
    the_game = pickle.loads(game_state.pickled_game)
    the_board = the_game.board
    the_tile = the_board.board_tiles[tile_index]
    the_edge = the_tile.edges[key_direction]
    current_player = the_game.current_player
    road = current_player.get_next_road()

    if road:
        is_built = current_player.build_road(road, the_edge, is_free_build)
        if is_built:
            if is_free_build and game_state.state == 'initialized':
                is_finished = the_game.first_build()
                if is_finished:  # everyone has had two turns building
                    game_state.state = 'new'
                    the_game.first_distribute()
            elif is_free_build and game_state.state == 'played_road':
                pass
            else:
                game_state.state = 'built'

            # the_board.calculate_longest_road(road)

            game_state.pickled_game = pickle.dumps(the_game)
            game_state.cooked_json_data = cook_the_json(the_game, game_state)
            game_state.save()

    return HttpResponse(game_state.cooked_json_data)
Example #26
0
    def update(self, instance, validated_data):
        if not can_proceed(instance.crawl):
            raise PermissionDenied

        instance.domain_name = validated_data.get('domain_name', instance.domain_name)
        if validated_data.get('processed_linkchecker'):
            instance.crawl()
        else:
            if instance.state == SourceStates.CRAWLED.value:
                instance.fail()
            else:
                instance.reject()

        instance.save()
        return instance
Example #27
0
def buy_a_card(request):
    gs_id = int(request.GET["gs_id"])
    game_state = GameState.objects.get(id=gs_id)

    if not can_proceed(game_state.buy):
        raise PermissionDenied

    the_game = pickle.loads(game_state.pickled_game)
    current_player = the_game.current_player
    is_bought = current_player.buy_development_card()

    if is_bought:
        game_state.state = 'bought'
    game_state.pickled_game = pickle.dumps(the_game)
    game_state.cooked_json_data = cook_the_json(the_game, game_state)
    game_state.save()

    return HttpResponse(game_state.cooked_json_data)
Example #28
0
 def accept(self, request, pk=None):
     """
     Accept the request and validate/complete the survey : change the state of the request to 'ACCEPTED'.
     """
     target_request = get_object_or_404(Request, id=pk)
     if not can_proceed(target_request.accept):
         raise PermissionDenied
     serializer = AcceptRequestSerializer(data=request.data,
                                          target_request=target_request,
                                          user=request.user,
                                          read_only_form=False)
     if serializer.is_valid():
         target_request = serializer.save()
         send_mail_request_update(target_request,
                                  user_applied_state=request.user)
         return Response(AdminRequestSerializer(target_request).data,
                         status=status.HTTP_200_OK)
     return Response(serializer.error_messages,
                     status=status.HTTP_400_BAD_REQUEST)
Example #29
0
def admin_request_need_info(request, request_id):
    target_request = get_object_or_404(Request, id=request_id)
    parameters = {'request_id': target_request.id, 'message_required': True}
    if request.method == "POST":
        form = MessageOnRequestForm(request.user, request.POST, **parameters)
        if form.is_valid():
            # check that we can ask for info the request
            if not can_proceed(target_request.need_info):
                raise PermissionDenied
            form.save()
            target_request.need_info()
            target_request.save()
            # TODO: notify user
            return redirect(admin_request_list)
    else:
        form = MessageOnRequestForm(request.user, **parameters)

    context = {"form": form, "target_request": target_request}
    return render(request, "admin/request/request-need-info.html", context)
Example #30
0
 def cancel(self, request, pk=None):
     """
     Cancel the request : change the state of the request to 'CANCELED', when instance still in 'PENDING' state it will be deleted.
     """
     user_requests = get_objects_for_user(request.user,
                                          'service_catalog.cancel_request')
     target_request = get_object_or_404(user_requests, id=pk)
     if not can_proceed(target_request.cancel):
         raise PermissionDenied
     if target_request.cancel():
         target_request.save()
     send_email_request_canceled(target_request,
                                 user_applied_state=request.user,
                                 request_owner_user=target_request.user)
     if request.user.is_superuser:
         return Response(AdminRequestSerializer(target_request).data,
                         status=status.HTTP_200_OK)
     return Response(RequestSerializer(target_request).data,
                     status=status.HTTP_200_OK)
Example #31
0
def admin_request_process(request, request_id):
    target_request = get_object_or_404(Request, id=request_id)
    error = False
    error_message = ""
    if request.method == "POST":
        if not can_proceed(target_request.process):
            raise PermissionDenied
        import towerlib
        try:
            # switch the state to processing before trying to execute the process
            target_request.process()
            target_request.save()
            target_request.perform_processing()
            target_request.save()
        except towerlib.towerlibexceptions.AuthFailed:
            error = True
            logger.error(
                "[admin_request_process] Fail to authenticate with provided token when trying "
                "to process request id '{}'".format(target_request.id))
            error_message = "Fail to authenticate with provided token"
        except requests.exceptions.SSLError:
            error = True
            error_message = "Certificate verify failed"
            logger.error(
                "[admin_request_process] Certificate verify failed when trying "
                "to process request id '{}'".format(target_request.id))
        except requests.exceptions.ConnectionError:
            error = True
            error_message = "Unable to connect to remote server"
            logger.error(
                "[admin_request_process] Unable to connect to remote server when trying "
                "to process request id '{}'".format(target_request.id))
        if not error:
            target_request.save()
            send_mail_request_update(target_request,
                                     from_email=request.user.email)
            return redirect(admin_request_list)

    context = {
        "target_request": target_request,
        "error_message": error_message
    }
    return render(request, "admin/request/request-process.html", context)
Example #32
0
def admin_request_re_submit(request, request_id):
    target_request = get_object_or_404(Request, id=request_id)
    parameters = {'request_id': target_request.id, 'message_required': False}
    if request.method == "POST":
        form = MessageOnRequestForm(request.user, request.POST, **parameters)
        if form.is_valid():
            if not can_proceed(target_request.re_submit):
                raise PermissionDenied
            form.save()
            target_request.re_submit()
            target_request.save()
            send_mail_request_update(target_request,
                                     from_email=request.user.email)
            return redirect(admin_request_list)
    else:
        form = MessageOnRequestForm(request.user, **parameters)

    context = {"form": form, "target_request": target_request}
    return render(request, "admin/request/request-re-submit.html", context)
Example #33
0
    def mqtt_message(self, topic, payload):
        """
        Handle the mqtt message passed from the room
        """
        payload = payload.lower().strip()

        if payload not in ["switchedoff", "switchedon", "on", "off"]:
            return

        method = getattr(self, payload)

        if can_proceed(method):
            method()
            self.save()
            logger.info(f"Socket {self.mqtt_topic}: {self.state}")
        else:
            logger.warning(
                f"Socket {self.mqtt_topic}: '{payload}' impossible, current state is {self.state}"
            )
Example #34
0
    def mqtt_message(self, topic, payload):
        """
        Handle the mqtt message passed from the room
        """
        payload = payload.lower().strip()

        if payload not in ("opened", "closed", "open", "close"):
            return

        method = getattr(self, payload)

        if can_proceed(method):
            method()
            self.save()
            logger.info(f"Roller {self.mqtt_topic}: {self.state}")
        else:
            logger.warning(
                f"Roller {self.mqtt_topic} can't '{payload}', current state is {self.state}"
            )
Example #35
0
 def re_submit(self, request, pk=None):
     """
     Re-submit the request : change the state of the request to 'SUBMITTED'.
     """
     target_request = get_object_or_404(Request, id=pk)
     if not can_proceed(target_request.re_submit):
         raise PermissionDenied
     data = QueryDict.copy(request.data)
     data['sender'] = request.user.id
     data['request'] = target_request.id
     message = RequestMessageSerializer(data=data)
     if message.is_valid():
         message.save()
     target_request.re_submit()
     target_request.save()
     send_mail_request_update(target_request,
                              user_applied_state=request.user,
                              message=message)
     return Response(AdminRequestSerializer(target_request).data,
                     status=status.HTTP_200_OK)
Example #36
0
def test_pull_flow(
    remote_status,
    our_status,
    callback,
    payment_factory,
    settings,
    requests_mock,
    getpaid_client,
):
    settings.GETPAID_BACKEND_SETTINGS = _prep_conf(confirm_method=cm.PULL)

    payment = payment_factory(external_id=uuid.uuid4())
    payment.confirm_prepared()
    requests_mock.get(
        f"/api/v2_1/orders/{payment.external_id}",
        json={
            "orders": [{
                "extOrderId": f"{payment.id}",
                "customerIp": "127.0.0.1",
                "merchantPosId": getpaid_client.pos_id,
                "description": "description",
                "validityTime": 46000,
                "currencyCode": payment.currency,
                "totalAmount": f"{payment.amount_required}",
                "buyer": {},  # doesn't matter now
                "products": {},  # doesn't matter now
                "status": remote_status,
            }],
            "status": {
                "statusCode": "SUCCESS",
                "statusDesc": "some status"
            },
        },
    )
    payment.fetch_and_update_status()
    # all confirmed payments are by default marked as PARTIAL
    assert payment.status == our_status
    # and need to be checked and marked if complete
    if callback:
        callback_meth = getattr(payment, callback)
        assert can_proceed(callback_meth)
Example #37
0
def request_cancel(request, request_id):
    target_request = get_object_or_404(Request, id=request_id)
    if request.method == "POST":
        # check that we can cancel the request
        if not can_proceed(target_request.cancel):
            raise PermissionDenied
        send_email_request_canceled(target_request,
                                    user_applied_state=request.user,
                                    request_owner_user=target_request.user)

        if target_request.cancel():
            target_request.save()
        return redirect('service_catalog:request_list')
    breadcrumbs = [
        {
            'text': 'Requests',
            'url': reverse('service_catalog:request_list')
        },
        {
            'text': request_id,
            'url': ""
        },
    ]
    context = {
        'breadcrumbs':
        breadcrumbs,
        'confirm_text':
        mark_safe(
            f"Do you want to cancel the request <strong>{target_request.id}</strong>?"
        ),
        'action_url':
        reverse('service_catalog:request_cancel',
                kwargs={'request_id': request_id}),
        'button_text':
        'Confirm cancel request',
        'details': {
            'warning_sentence':
            f"Canceling this request will delete the instance {target_request.instance.name}."
        } if target_request.instance.state == InstanceState.PENDING else None
    }
    return render(request, "generics/confirm-delete-template.html", context)
Example #38
0
    def fn(self, request, **kwargs):
        transition_args = []

        if self.get_serializer_class() != Serializer:
            serializer = self.get_serializer(data=request.data)
            serializer.is_valid(raise_exception=True)
            transition_args = [serializer.validated_data]

        obj = self.get_object()
        transition = getattr(obj, name)

        if can_proceed(transition) and \
                has_transition_perm(transition, request.user):
            try:
                transition(*transition_args)
            except TransitionNotAllowed as err:
                raise ValidationError(str(err))
            obj.save()
            return Response(status=204)
        else:
            raise ValidationError("Can't perform '{}' transition".format(name))
Example #39
0
def play_knight_card(request):
    gs_id = int(request.GET["gs_id"])
    game_state = GameState.objects.get(id=gs_id)
    # game_state_prior_to_playing_card = game_state.state

    if not can_proceed(game_state.play):
        raise PermissionDenied

    card_id = int(request.GET["card"])
    the_game = pickle.loads(game_state.pickled_game)
    the_card = the_game.current_player.development_cards[card_id]

    if the_card.can_play and type(the_card) is KnightCard:
        the_game.knight_played(the_card)
        game_state.state = 'played_knight'

    game_state.pickled_game = pickle.dumps(the_game)
    game_state.cooked_json_data = cook_the_json(the_game, game_state)
    game_state.save()

    return HttpResponse(game_state.cooked_json_data)
Example #40
0
def play_road_bldg_card(request):
    gs_id = int(request.GET["gs_id"])
    game_state = GameState.objects.get(id=gs_id)

    if not can_proceed(game_state.play):
        raise PermissionDenied

    card_index = int(request.GET["card"])
    the_game = pickle.loads(game_state.pickled_game)
    the_card = the_game.current_player.development_cards[card_index]

    if the_card.can_play and the_card.kind == 'Road Building':
        road_card = the_game.current_player.development_cards.pop(card_index)
        the_game.development_deck.put_card(road_card)
        game_state.state = 'played_road'

    game_state.pickled_game = pickle.dumps(the_game)
    game_state.cooked_json_data = cook_the_json(the_game, game_state)
    game_state.save()

    return HttpResponse(game_state.cooked_json_data)
Example #41
0
    def progress_application(self, **kwargs):
        target = None
        for phase in STAGE_CHANGE_ACTIONS:
            transition = self.get_transition(phase)
            if can_proceed(transition):
                # We convert to dict as not concerned about transitions from the first phase
                # See note in workflow.py
                target = dict(PHASES)[phase].stage
        if not target:
            raise ValueError('Incorrect State for transition')

        submission_in_db = ApplicationSubmission.objects.get(id=self.id)

        self.id = None
        self.form_fields = self.get_from_parent('get_defined_fields')(target)

        self.live_revision = None
        self.draft_revision = None
        self.save()

        submission_in_db.next = self
        submission_in_db.save()
Example #42
0
def admin_request_re_submit(request, request_id):
    target_request = get_object_or_404(Request, id=request_id)
    if not can_proceed(target_request.re_submit):
        raise PermissionDenied
    if request.method == "POST":
        form = RequestMessageForm(request.POST or None,
                                  request.FILES or None,
                                  sender=request.user,
                                  target_request=target_request)
        if form.is_valid():
            message = form.save(send_notification=False)
            target_request.re_submit()
            target_request.save()
            send_mail_request_update(target_request,
                                     user_applied_state=request.user,
                                     message=message)
            return redirect('service_catalog:request_list')
    else:
        form = RequestMessageForm(sender=request.user,
                                  target_request=target_request)
    breadcrumbs = [
        {
            'text': 'Requests',
            'url': reverse('service_catalog:request_list')
        },
        {
            'text': request_id,
            'url': ""
        },
    ]
    context = {
        'form': form,
        'target_request': target_request,
        'breadcrumbs': breadcrumbs
    }
    return render(request,
                  "service_catalog/admin/request/request-re-submit.html",
                  context)
Example #43
0
def task_view(request, task_status_id=None):
    task_status = get_object_or_404(TaskStatus, pk=task_status_id)
    if request.method == 'POST':
        form = SendTaskBackForm(request.POST)
        if form.is_valid():
            task_status.comment = form.cleaned_data['comment']
            task_status.response = form.cleaned_data['response']
            task_status.save()
            return redirect('send_task_back', task_status_id=task_status_id)
    task = task_status.task
    can_be_sent = (can_proceed(task_status.send)
                   and has_transition_perm(task_status.send, request.user))
    review_mode = (task_status.state == 'RVW' and request.user.is_superuser)
    context = {
        'task': task,
        'task_status': task_status,
        'can_be_sent': can_be_sent,
        'review_mode': review_mode,
        'user': request.user
    }
    if review_mode:
        form = SendTaskBackForm()
        context['form'] = form
    return render(request, "task.html", context)
Example #44
0
    def inner_func(self, request, pk=None, **kwargs):
        object = self.get_object()
        transition_method = getattr(object, transition_name)
        if can_proceed(transition_method, self.request.user):

            # Perform the requested transition
            if isinstance(self.request.user, User):
                transition_method(by=self.request.user)
            else:
                transition_method()

            if self.save_after_transition:
                object.save()
        else:
            raise exceptions.PermissionDenied(
                'User {user} cannot perform transition {transition} from {state}'
                .format(user=self.request.user,
                        transition=transition_name,
                        state=getattr(
                            object,
                            transition_method._django_fsm.field.attname)))

        serializer = self.get_serializer(object)
        return Response(serializer.data)
Example #45
0
def get_action_text_class(request_id, target_action):
    target_request = Request.objects.get(id=request_id)
    if target_action == "cancel":
        if can_proceed(target_request.cancel):
            return "text-dark"
    if target_action == "need_info":
        if can_proceed(target_request.need_info):
            return "text-warning"
    if target_action == "reject":
        if can_proceed(target_request.reject):
            return "text-danger"
    if target_action == "accept":
        if can_proceed(target_request.accept):
            return "text-primary"
    if target_action == "process":
        if can_proceed(target_request.process):
            return "text-success"
    if target_action == "re_submit":
        if can_proceed(target_request.re_submit):
            return "text-info"
    return ""
Example #46
0
def is_action_dropdown_disabled(request_id, target_action):
    target_request = Request.objects.get(id=request_id)
    if target_action == "cancel":
        if not can_proceed(target_request.cancel):
            return "disabled"
    if target_action == "need_info":
        if not can_proceed(target_request.need_info):
            return "disabled"
    if target_action == "reject":
        if not can_proceed(target_request.reject):
            return "disabled"
    if target_action == "accept":
        if not can_proceed(target_request.accept):
            return "disabled"
    if target_action == "process":
        if not can_proceed(target_request.process):
            return "disabled"
    if target_action == "re_submit":
        if not can_proceed(target_request.re_submit):
            return "disabled"

    return ""
Example #47
0
 def can_trans(self, action):
     return can_proceed(getattr(self, action.lower()))
 def test_state_non_changed_after_fail(self):
     self.assertTrue(can_proceed(self.model.remove))
     self.assertRaises(Exception, self.model.remove)
     self.assertEqual(self.model.state, 'new')
Example #49
0
 def change_state(self, state, user):
     state_method = getattr(self, state)
     if can_proceed(state_method) and has_transition_perm(
             state_method, user):
         state_method()
         self.save()
Example #50
0
 def test_allowed_null_transition_should_succeed(self):
     self.assertTrue(can_proceed(self.model.publish))
     self.model.publish()
     self.model.notify_all()
     self.assertEqual(self.model.state, 'published')
Example #51
0
    def handle_paywall_callback(self, request, **kwargs):
        payu_header_raw = request.headers.get(
            "Openpayu-Signature") or request.headers.get(
                "X-Openpayu-Signature", "")

        if not payu_header_raw:
            return HttpResponse("NO SIGNATURE", status=400)
        payu_header = {
            k: v
            for k, v in [i.split("=") for i in payu_header_raw.split(";")]
        }
        algo_name = payu_header.get("algorithm", "MD5")
        signature = payu_header.get("signature")
        second_key = self.get_setting("second_key")
        algorithm = getattr(hashlib, algo_name.replace("-", "").lower())

        body = request.body.decode()

        expected_signature = algorithm(
            f"{body}{second_key}".encode("utf-8")).hexdigest()

        if expected_signature == signature:
            data = json.loads(body)

            if "order" in data:
                order_data = data.get("order")
                status = order_data.get("status")
                if status == OrderStatus.COMPLETED:
                    if can_proceed(self.payment.confirm_payment):
                        self.payment.confirm_payment()
                        if can_proceed(self.payment.mark_as_paid):
                            self.payment.mark_as_paid()
                    else:
                        logger.debug(
                            "Cannot confirm payment",
                            extra={
                                "payment_id": self.payment.id,
                                "payment_status": self.payment.status,
                            },
                        )
                elif status == OrderStatus.CANCELED:
                    self.payment.fail()
                elif status == OrderStatus.WAITING_FOR_CONFIRMATION:
                    if can_proceed(self.payment.confirm_lock):
                        self.payment.confirm_lock()
                    else:
                        logger.debug(
                            "Already locked",
                            extra={
                                "payment_id": self.payment.id,
                                "payment_status": self.payment.status,
                            },
                        )
            elif "refund" in data:
                refund_data = data.get("refund")
                status = refund_data.get("status")
                if status == RefundStatus.FINALIZED:
                    amount = refund_data.get("amount") / 100
                    self.payment.confirm_refund(amount)
                    if can_proceed(self.payment.mark_as_refunded):
                        self.payment.mark_as_refunded()
                elif status == RefundStatus.CANCELED:
                    self.payment.cancel_refund()
                    if can_proceed(self.payment.mark_as_paid):
                        self.payment.mark_as_paid()
            self.payment.save()
            return HttpResponse("OK")
        else:
            logger.error(
                f"Received bad signature for payment {self.payment.id}! "
                f"Got '{signature}', expected '{expected_signature}'")
            return HttpResponse("BAD SIGNATURE",
                                status=422)  # https://httpstatuses.com/422
 def in_payable_state(self):
     return can_proceed(self.pay)
Example #53
0
 def check_transition_permission(self, transition, user):
     try:
         if not can_proceed(transition) or not has_transition_perm(transition, user):
             raise PermissionDenied
     except CoreValidationError as exc:
         raise ValidationError(dict([error for error in exc]))
Example #54
0
 def can_proceed(self, transition_method):
     return can_proceed(transition_method)
Example #55
0
 def check_transition_conditions(self, transition):
     if not transition:
         return True
     return can_proceed(transition)
Example #56
0
def generate_state_change_registrar(request, telephone_expense_id):
    """
    Generates view for registrar i.e R for changing of states(Approve, Reject)
    This function assumes current user is authenticated as R
    :param request: HttpRequestObject
    :param telephone_expense_id:
    :return: HttpResponseObject
    """
    telephone_expense = get_object_or_404(TelephoneExpense, id=telephone_expense_id)
    form_errors = {}
    if request.method == 'POST':
        if request.POST.get('APPROVED_BY_R', False):
            try:
                with transaction.atomic():
                    if not can_proceed(telephone_expense.approve_by_r):
                        raise PermissionDenied
                    transition = TelephoneExpenseTransitionHistory.objects.create(
                        state_from=STATE.APPROVED_BY_SrAO,
                        state_to=STATE.APPROVED_BY_R,
                        remarks=request.POST.get('state-change-remarks', ''),
                        approved_by=request.user,
                        telephone_expense=telephone_expense
                    )
                    transition.save()
                    telephone_expense.approve_by_r()
                    telephone_expense.save()
                    messages.success(request, 'Request for Telephone Expense reimbursement #'
                                     + str(telephone_expense_id)
                                     + ' successfully approved!')
                    return redirect('reimbursement:telephone-expense-show', telephone_expense_id)
            except IntegrityError:
                messages.error(request, 'There was an error approving the reimbursement request')
            else:
                messages.error(request, 'Please resolve the errors below and try again')
        elif request.POST.get('REJECTED_BY_R', False):
            try:
                with transaction.atomic():
                    if not can_proceed(telephone_expense.reject_by_r):
                        raise PermissionDenied
                    transition = TelephoneExpenseTransitionHistory.objects.create(
                        state_from=STATE.APPROVED_BY_SrAO,
                        state_to=STATE.REJECTED_BY_R,
                        remarks=request.POST.get('state-change-remarks', ''),
                        approved_by=request.user,
                        telephone_expense=telephone_expense
                    )
                    transition.save()
                    telephone_expense.reject_by_r()
                    telephone_expense.save()
                    messages.success(request, 'Request for Telephone Expense reimbursement #'
                                     + str(telephone_expense_id)
                                     + ' successfully rejected!')
                    return redirect('reimbursement:telephone-expense-show', telephone_expense_id)
            except IntegrityError:
                messages.error(request, 'There was an error rejecting the reimbursement request')
            else:
                messages.error(request, 'Please resolve the errors below and try again')
    else:
        pass
    context = {
        'form_errors': form_errors,
        'telephone_expense': telephone_expense
    }
    return render(request, 'reimbursement/telephone_expense/state_change/role_based/registrar.html', context)
 def test_unknown_transition_fails(self):
     self.assertFalse(can_proceed(self.model.hide))
     self.assertRaises(TransitionNotAllowed, self.model.hide)
 def can_be_archived(self):
     return can_proceed(self._set_archive)
 def test_star_shortcut_succeed(self):
     self.assertTrue(can_proceed(self.model.moderate))
     self.model.moderate()
     self.assertEqual(self.model.state, 'moderated')
 def can_be_unpublished(self):
     return can_proceed(self._set_unpublish)