Esempio n. 1
0
 def mutate_and_get_payload(cls, root, info, id, name=None, scope=None, content=None, order=None, habits=None):
     user = info.context.user
     _type, id = from_global_id(id)
     routine = user.routines.get(id=id)
     if name is not None:
         routine.name = name
     if scope is not None:
         routine.scope = scope
     if content is not None:
         routine.content = content
     if order is not None:
         routine.to(order)
     if habits is not None:
         habit_ids = [from_global_id(id)[1] for id in habits]
         selected_habits = user.habits.filter(id__in=habit_ids)
         current_habits = routine.habits.all()
         # Adding new habits
         for habit in selected_habits:
             if not habit in current_habits:
                 routine.routine_habits.create(habit=habit)
         # Deleting removed habits.
         for habit in current_habits:
             if habit not in selected_habits:
                 routine.routine_habits.get(habit=habit).delete()
     routine.save()
     return UpdateRoutineMutation(success=True, routine=routine)
Esempio n. 2
0
    def mutate_and_get_payload(
        cls, root, info, id=None, scope=None, start=None, **kwargs):
        user = info.context.user

        if not kwargs.get('outcomes'):
            raise Exception('No outcomes provided for focus.')

        if id is not None and 'reason' in kwargs:
            _type, id = from_global_id(id)
            focus = user.focuses.get(id=id)
        elif scope is not None and start is not None:
            focus, created = user.focuses.get_or_create(scope=scope, start=start)
            if created:
                habit = get_controlled_habit(user, ControlledHabit.FOCUS_HABIT)
                tracked = habit.track()
                if tracked:
                    habit.save()
                    add_experience(user, 'office')
        else:
            raise Exception('ID or scope and start needed to get focus.')

        if 'outcomes' in kwargs:
            # TODO: Replace workaround (for removing outcomes).
            focus.outcome_1 = None
            focus.outcome_2 = None
            focus.outcome_3 = None
            focus.outcome_4 = None

            outcome_ids = [from_global_id(id)[1] for id in kwargs.get('outcomes', [])]
            new_outcomes = [user.outcomes.get(id=outcome_id) for outcome_id in outcome_ids]
            for index, outcome in enumerate(new_outcomes):
                setattr(focus, f'outcome_{index+1}', outcome)
        focus.save()

        return UpdateFocusMutation(success=True, focus=focus)
Esempio n. 3
0
 def mutate_and_get_payload(cls, root, info, id, **kwargs):
     user = info.context.user
     _type, id = from_global_id(id)
     outcome = user.outcomes.get(id=id)
     related_outcome_ids = [from_global_id(id)[1] for id in kwargs.get('outcomes', [])]
     outcome.related_outcomes.set(related_outcome_ids)
     return SetRelatedOutcomesMutation(success=True, outcome=outcome)
Esempio n. 4
0
def _assert_menu_is_exactly(menu_id: str, actual_data: dict, expected_data: List[Dict]):

    menu = actual_data.get("menu")
    assert menu, "Expected to receive a valid menu to compare from"

    # Check the returned menu is actually the one we requested to change
    assert menu["id"] == menu_id

    actual_menu_items = menu.get("items")
    assert actual_menu_items, "Expected the menu to have items"

    for expected_item in expected_data:
        the_item_was_found = False
        expected_sort_order = expected_item.get("sortOrder")
        expected_parent_id = expected_item.get("parentId")
        expected_item_id = from_global_id(expected_item["itemId"])[1]

        for actual_item in actual_menu_items:
            # Get the item that we want to compare, we retrieve by the database
            # entry ID as the node id may have changed between the initial
            # request and the one returned by the mutation
            actual_item_id = from_global_id(actual_item["id"])[1]
            if actual_item_id != expected_item_id:
                # Append the children, to check, if any
                children = actual_item.get("children")
                if children:
                    actual_menu_items += children

                # Skip this node as it is not the one we are looking for
                continue

            the_item_was_found = True

            if expected_sort_order:
                assert (
                    actual_item["sortOrder"] == expected_sort_order
                ), "The menu item did not have the expected sorting order"

            if "parentId" in expected_item:
                if expected_parent_id:
                    assert actual_item[
                        "parent"
                    ], "Expected the menu item to have a parent"
                    assert (
                        actual_item["parent"]["id"] == expected_parent_id
                    ), "The menu item did not have the expected parent"
                else:
                    assert not actual_item[
                        "parent"
                    ], "Expected the menu item to not have a parent"

        assert (
            the_item_was_found
        ), "The expected menu item was not found in the response"
Esempio n. 5
0
    def mutate_and_get_payload(cls, root, info, client_mutation_id, id, performances=[], **input):
        _, post_id = from_global_id(id)

        PostModel.objects.filter(pk=post_id, owner=info.context.user).update(**input)
        post = PostModel.objects.get(pk=post_id, owner=info.context.user)

        PerformanceModel.objects.filter(post__pk=post.id).delete()
        for performance_data in performances:
            event_data = performance_data.pop('event')
            _, event_id = from_global_id(event_data.id)
            event = EventModel.objects.get(pk=event_id, owner=info.context.user)
            performance = PerformanceModel.objects.create(post=post, event=event, **performance_data)
            post.performances.add(performance)

        return UpdatePost(post=post)
Esempio n. 6
0
 def mutate_and_get_payload(cls, root, info, id):
     user = info.context.user
     _type, id = from_global_id(id)
     # TODO: Checking permission.
     step = Step.objects.get(id=id)
     step.delete()
     return DeleteStepMutation(success=True)
Esempio n. 7
0
 def mutate_and_get_payload(cls, root, info, id=None, subject=None, message=None):
     # print('>> contact user')
     user = info.context.user
     _type, id = from_global_id(id)
     receiver = User.objects.get(id=id)
     receiver.contact(user, subject, message)
     return ContactUserMutation(success=True)
Esempio n. 8
0
    def filter(self, queryset, value):
        # value is either a list or an 'empty' value
        values = value or []

        for value in values:
            _type, id = from_global_id(value)
            queryset = queryset.filter(tags__id__exact=id)
        return queryset
Esempio n. 9
0
 def mutate_and_get_payload(cls, root, info, id, order=None):
     user = info.context.user
     _type, id = from_global_id(id)
     routine_habit = RoutineHabit.objects.get(id=id)
     if order is not None:
         routine_habit.to(order)
         routine_habit.save()
     return UpdateRoutineHabitMutation(success=True, routine_habit=routine_habit)
Esempio n. 10
0
 def mutate_and_get_payload(cls, root, info, id):
     user = info.context.user
     outcomes = user.outcomes
     if id:
         _type, id = from_global_id(id)
         outcomes = outcomes.filter(id=id)
     outcomes.update(score=1000)
     return DeleteOutcomeMutation(success=True)
Esempio n. 11
0
 def mutate_and_get_payload(cls, root, info, id, note=''):
     # print('>> add note to user')
     viewer = info.context.user
     if viewer.is_superuser:
         _type, id = from_global_id(id)
         user = User.objects.get(id=id)
         user.add_note(note)
     return UpdateUserMutation(user=user)
Esempio n. 12
0
def resolve_image_id(id: int = None, image_id: str = None) -> int:
    """Returms the image id contained in the specified id or image_id values."""
    if image_id is None:
        if id is None:
            raise ValueError("Either id or image_id must be specified")
        type, image_id = from_global_id(id)
        if type != "Image":
            raise ValueError(f"Wrong id type (expected 'Image', got '{type}'")
    return image_id
Esempio n. 13
0
 def mutate_and_get_payload(cls, root, info, id, name=None, notes=None):
     _type, id = from_global_id(id)
     tribe = Tribe.objects.get(id=id)
     if name is not None:
         tribe.name = name
     if notes is not None:
         tribe.notes = notes
     tribe.save()
     return UpdateTribeMutation(tribe=tribe)
Esempio n. 14
0
def resolve_gallery_id(id: int = None, gallery_id: str = None) -> int:
    """Returms the gallery id contained in the specified id or gallery_id values."""
    if gallery_id is None:
        if id is None:
            raise ValueError("Either id or gallery_id must be specified")
        type, gallery_id = from_global_id(id)
        if type != "Gallery":
            raise ValueError(f"Wrong id type (expected 'Gallery', got '{type}'")
    return gallery_id
Esempio n. 15
0
 def mutate_and_get_payload(cls, root, info, id, name=None, notes=None):
     _type, id = from_global_id(id)
     duo = Duo.objects.get(id=id)
     if name is not None:
         duo.name = name
     if notes is not None:
         duo.notes = notes
     duo.save()
     return UpdateDuoMutation(duo=duo)
Esempio n. 16
0
 def mutate_and_get_payload(cls, root, info, id):
     user = info.context.user
     _type, id = from_global_id(id)
     habit = user.habits.get(id=id)
     if not habit.is_controlled:
         habit.delete()
     else:
         raise Exception(f'Habit {habit} can only be deleted by the system.')
     return DeleteHabitMutation(success=True)
Esempio n. 17
0
 def mutate(self, info, id):
     query = Publicholiday.get_query(info)
     holiday_id = from_global_id(id)[1]
     publicHoliday = query.filter(
         PublicholidayModel.id == holiday_id).first()
     db_session.delete(publicHoliday)
     db_session.commit()
     ok = True
     return DeletePublicholiday(publicHoliday=publicHoliday, ok=ok)
Esempio n. 18
0
 def mutate_and_get_payload(cls, root, info, id, name=None, notes=None):
     _type, id = from_global_id(id)
     clan = Clan.objects.get(id=id)
     if name is not None:
         clan.name = name
     if notes is not None:
         clan.notes = notes
     clan.save()
     return UpdateClanMutation(clan=clan)
Esempio n. 19
0
 def mutate_and_get_payload(cls, root, info, id):
     user = info.context.user
     _type, id = from_global_id(id)
     # TODO: Checking permission. Workaround: Only my outcomes. ;)
     outcome = user.outcomes.get(id=id)
     if outcome.is_focus:
         raise Exception('This outcome is set as a focus and cannot be deleted.')
     outcome.delete()
     return DeleteOutcomeMutation(success=True)
Esempio n. 20
0
    def perform_mutation(cls, _root, info, menu, moves):
        _type, menu_id = from_global_id(menu)  # type: str, int
        assert _type == "Menu", "Expected a menu of type Menu"

        operations = cls.clean_moves(info, menu_id, moves)

        for operation in operations:
            cls.perform_operation(operation)

        return cls(menu=models.Menu.objects.get(pk=menu_id))
Esempio n. 21
0
 def mutate_and_get_payload(cls, root, info, id, name=None, description=None):
     user = info.context.user
     _type, id = from_global_id(id)
     tag = user.tags.get(id=id)
     if name is not None:
         tag.name = name
     if description is not None:
         tag.description = description
     tag.save()
     return UpdateTagMutation(success=True, tag=tag)
Esempio n. 22
0
    def mutate_and_get_payload(cls, root, info, id, **kwargs):
        user = info.context.user
        _type, id = from_global_id(id)
        tension = user.tensions.get(id=id)

        for key, value in kwargs.items():
            if value is not None:
                setattr(tension, key, value)
        tension.save()
        return UpdateTensionMutation(tension=tension)
Esempio n. 23
0
    def mutate_and_get_payload(cls, root, info, id, *args, **kwargs):
        user = info.context.user
        _type, id = from_global_id(id)
        event = Event.objects.get(id=id)

        # Permission: Is it an upcomming event?
        if timezone.now() <= event.start:
            event.participants.add(user)
        else:
            raise Exception('Event is not upcoming')
        return JoinEventMutation(event=event)
Esempio n. 24
0
    def resolve_content_page(self, info, **kwargs):
        id = kwargs.get('id')
        slug = kwargs.get('slug')

        if id is not None:
            _type, id = from_global_id(id)
            return ContentPage.objects.get(id=id)

        if slug is not None:
            return ContentPage.objects.get(slug=slug)

        return ContentPage.objects.none()
Esempio n. 25
0
    def mutate_and_get_payload(cls, root, info, client_mutation_id, performances, **input):
        post = PostModel(owner=info.context.user, **input)
        post.save()

        for performance_data in performances:
            event_data = performance_data.pop('event')
            _, event_id = from_global_id(event_data.id)
            event = EventModel.objects.get(pk=event_id, owner=info.context.user)
            performance = PerformanceModel.objects.create(post=post, event=event, **performance_data)
            post.performances.add(performance)

        return CreatePost(post=post)
Esempio n. 26
0
 def mutate_and_get_payload(
     cls, root, info, id,
     name=None, description=None, status=None, inbox=None,
     scope=None, date=None, deadline=None, estimate=None, tags=None, deletions=None):
     user = info.context.user
     _type, id = from_global_id(id)
     outcome = user.outcomes.get(id=id)
     if name is not None:
         outcome.name = name
     if description is not None:
         outcome.description = description
     if status is not None:
         # Adding a completion date if newly completed.
         if status == outcome.DONE and not outcome.completed_at:
             outcome.completed_at = timezone.now()
         # Resetting score on status change.
         if status != outcome.status:
             outcome.score = 1000
             outcome.comparisons = 0
         outcome.status = status
     if inbox is not None:
         outcome.inbox = inbox
     if scope is not None:
         outcome.scope = scope
     if date is not None:
         outcome.date = date
     if deadline is not None:
         outcome.deadline = deadline
     if estimate is not None:
         outcome.estimate = estimate
     if tags is not None:
         tag_ids = [from_global_id(id)[1] for id in tags]
         tags = user.tags.filter(id__in=tag_ids)
         outcome.tags.set(tags)
     if deletions is not None:
         for field in deletions:
             setattr(outcome, field, None)
     outcome.save()
     return UpdateOutcomeMutation(success=True, outcome=outcome)
Esempio n. 27
0
def get_nodes(ids, graphene_type=None):
    """Return a list of nodes.

    If the `graphene_type` argument is provided, the IDs will be validated
    against this type. If the type was not provided, it will be looked up in
    the Graphene's registry. Raises an error if not all IDs are of the same
    type.
    """
    pks = []
    types = []
    invalid_ids = []
    error_msg = "Could not resolve to a nodes with the global id list of '%s'."
    for graphql_id in ids:
        if graphql_id:
            try:
                _type, _id = from_global_id(graphql_id)
            except Exception:
                invalid_ids.append(graphql_id)
            else:
                if graphene_type:
                    assert str(graphene_type) == _type, (
                        'Must receive an {} id.').format(
                            graphene_type._meta.name)
                pks.append(_id)
                types.append(_type)
    if invalid_ids:
        raise GraphQLError(
            error_msg % invalid_ids)

    # If `graphene_type` was not provided, check if all resolved types are
    # the same. This prevents from accidentally mismatching IDs of different
    # types.
    if types and not graphene_type:
        assert len(set(types)) == 1, 'Received IDs of more than one type.'
        # get type by name
        type_name = types[0]
        for model, _type in registry._registry.items():
            if _type._meta.name == type_name:
                graphene_type = _type
                break

    nodes = list(graphene_type._meta.model.objects.filter(pk__in=pks))
    nodes.sort(key=lambda e: pks.index(str(e.pk)))  # preserve order in pks
    if not nodes:
        raise GraphQLError(
            error_msg % ids)
    nodes_pk_list = [str(node.pk) for node in nodes]
    for pk in pks:
        assert pk in nodes_pk_list, (
            'There is no node of type {} with pk {}'.format(_type, pk))
    return nodes
Esempio n. 28
0
    def mutate(self, info, id):
        query = User.get_query(info)
        user_id = from_global_id(id)[1]
        user = query.filter(UserModel.id == user_id).first()

        if user.is_archived is False:
            raise Exception('This user has an unarchived status!')

        user.is_archived = False
        user.archive_reason = None
        db_session.add(user)
        db_session.commit()
        ok = True
        return UnArchiveUser(User=user, ok=ok)
Esempio n. 29
0
    def mutate_and_get_payload(cls, root, info, contestant, competitor, success):
        user = info.context.user
        _type, contestant = from_global_id(contestant)
        _type, competitor = from_global_id(competitor)

        # print(contestant, competitor, success)
        try:
            contestant = user.outcomes.get(id=contestant)
            competitor = user.outcomes.get(id=competitor)
        except Exception as error:
            raise Exception(error)

        # New score for competitor
        if not contestant.is_provisional:
            competitor.score = calculate_elo(competitor.score, contestant.score, not success)
            competitor.save(update_fields=['score', 'comparisons'])

        # New score for contestant
        contestant.score = calculate_elo(contestant.score, competitor.score, success)
        contestant.comparisons = contestant.comparisons + 1
        contestant.save(update_fields=['score', 'comparisons'])

        return MatchOutcomesMutation(success=True, contestant=contestant, competitor=competitor)
Esempio n. 30
0
 def resolve_current_quest_status(self, info, id=None):
     user = info.context.user
     # Getting the status of the current or next quest.
     if id is not None:
         _type, id = from_global_id(id)
         current_quest = user.quest_statuses.get(id=id)
     else:
         current_quest = user.quest_statuses.last()
     if not current_quest:
         first_quest = Quest.objects.first()
         if first_quest:
             current_quest = user.quest_statuses.create(
                 quest=first_quest,
             )
     return current_quest
Esempio n. 31
0
 def mutate_and_get_payload(cls,
                            root,
                            info,
                            id,
                            name=None,
                            description=None):
     user = info.context.user
     _type, id = from_global_id(id)
     tag = user.tags.get(id=id)
     if name is not None:
         tag.name = name
     if description is not None:
         tag.description = description
     tag.save()
     return UpdateTagMutation(success=True, tag=tag)
Esempio n. 32
0
File: schema.py Progetto: s1s5/todo
 def resolve_todolist_mutation(root, info, id):
     _id = int(from_global_id(id)[1])
     observable = Observable.merge(ChannelGroupObservable('todolist'),
                                   ChannelGroupObservable('todo'))
     return observable.map(lambda event: SubscriptionEvent.from_dict(
         event)).filter(lambda event: (
             (isinstance(event.instance, models.TodoList) and event.instance
              .id == _id) or (isinstance(event.instance, models.Todo) and
                              event.instance.parent_id == _id)
         )).map(lambda event: TodoListMutationValueObject(
             operation=event.operation,
             todolist=event.instance
             if isinstance(event.instance, models.TodoList) else None,
             todo=event.instance
             if isinstance(event.instance, models.Todo) else None))
Esempio n. 33
0
File: car.py Progetto: forrestp/cars
    def mutate_and_get_payload(cls, root, info, id, data):
        validate_dict = {
            'owner': {
                'max': 255,
            },
            'color': {
                'max': 255,
            },
            'year': {
                'max': 2100,
                'min': 1900,
            },
        }

        validate_mutation(validate_dict, data)

        trim = data.pop('trim', None)
        if trim is not None:
            data['trim_id'] = from_global_id(trim)[1]

        obj, _ = Car.objects.update_or_create(pk=from_global_id(id)[1],
                                              defaults=data)

        return UpdateCar(car=obj)
 def mutate_and_get_payload(cls,
                            root,
                            info,
                            client_mutation_id=None,
                            **data):
     if not info.context.user.is_authenticated:
         return SnapshotMutation(snapshot=None)
     municipality = Municipality.objects.get(pk=int(data['bfsNumber']))
     if client_mutation_id:
         snapshot = Snapshot.objects.get(
             pk=from_global_id(client_mutation_id)[1])
         snapshot.title = data['title']
         snapshot.topic = data['topic']
         snapshot.municipality = municipality
         snapshot.save()
     else:
         workspace = Workspace.objects.get(
             pk=from_global_id(data['wshash'])[1])
         snapshot = Snapshot(title=data['title'], topic=data['topic'])
         snapshot.user = info.context.user
         snapshot.municipality = municipality
         snapshot.save()
         workspace.snapshots.add(snapshot)
     return SnapshotMutation(snapshot=snapshot)
Esempio n. 35
0
 def mutate_and_get_payload(cls,
                            root,
                            info,
                            id,
                            keywords=None,
                            content=None):
     user = info.context.user
     _type, id = from_global_id(id)
     entry = user.journal_entries.get(id=id)
     if keywords is not None:
         entry.keywords = keywords
     if content is not None:
         entry.content = content
     entry.save()
     return UpdateJournalEntryMutation(success=True, journal_entry=entry)
Esempio n. 36
0
    def mutate(self, info, id, archiveReason):
        query = User.get_query(info)
        user_id = from_global_id(id)[1]

        user = query.filter(UserModel.id == user_id).first()

        if user.is_archived is True:
            raise Exception('This user has an archived status!')

        user.is_archived = True
        user.archive_reason = archiveReason
        db_session.add(user)
        db_session.commit()
        ok = True
        return ArchiveUser(User=user, ok=ok)
Esempio n. 37
0
    def mutate_and_get_payload(self, root, info, id):

        if not info.context.user.is_authenticated:
            message = "You are not logged in"
            return VoteMutation(question=None, message=message)


        questions = cache.get('questions')
        print(questions)
        if questions:
            question = questions.get(pk=from_global_id(id)[1])
        else:
            question = Question.objects.get(pk=from_global_id(id)[1])

        votes = question.votes.all()

        if votes.filter(pk=info.context.user.pk).exists():
            message = "Removed Vote"
            question.votes.remove(info.context.user.pk)
        else:
            message = "Voted"
            question.votes.add(info.context.user.pk)

        return VoteMutation(question=question, message=message)
Esempio n. 38
0
    def mutate_and_get_payload(cls, root, info, **kwargs):

        identifier = kwargs.pop("id", None)
        if identifier is not None:
            identifier = from_global_id(identifier)[1]

        if kwargs.pop("delete", False):
            result = Request.objects.get(pk=identifier)
            result.delete()
            return cls(ok=True)

        product_id = kwargs.pop("product_id", None)
        if product_id is not None:
            product_id = from_global_id(product_id)[1]
        kwargs["product_id"] = product_id

        user = info.context.user
        kwargs["client_id"] = user.id

        _, _ = Client.objects.get_or_create(pk=user.id)

        result, _ = Request.objects.update_or_create(defaults=kwargs,
                                                     pk=identifier)
        return cls(result=result, ok=True)
Esempio n. 39
0
	def mutate_and_get_payload(cls, root, info, **input):
		if input.get('mutation_option') not in (2,3):
			raise GraphQLError('provide proper value')

		try:
			public_date_obj = PublicDateInstitutionRelation.objects.select_related('date_institution__institution').get(
				id=from_global_id(input.get('public_institution_date_id'))[1]
				)
		except PublicDateInstitutionRelation.DoesNotExist:
			raise GraphQLError('public institution date ID is incorrect')

		institution_obj = public_date_obj.date_institution.institution

		result = UserAuthorizeTest(info,'adminUser',institution_obj=institution_obj)

		if result['adminUser'] is not True:
			raise GraphQLError('you are not approprate use. try differnt account')

		if input.get('mutation_option') == 2:
			if input.get('visibility_option') is not None:
				valide_choice = False

				for choice in PublicDateInstitutionRelation.VISIBILITY_OPTION:
					if input.get('visibility_option') == choice[0]:
						valide_choice = True
						break

				if valide_choice is False:
					raise GraphQLError('provie valide label value')

				public_date_obj.visibility = input.get('visibility_option')
				public_date_obj.save()

			if input.get('tags') is not None:
				json_data = json.loads(input.get('tags'))
				tags_array = json_data['tags']

				if len(tags_array) <= 5:
					public_date_obj.tags.clear()
					for tag in tags_array:
						public_date_obj.tags.add(tag)

			return PublicDateUpdateDelete(public_institution_date=public_date_obj)

		if input.get('mutation_option') == 3:
			public_date_obj.delete()

			return PublicDateUpdateDelete(public_institution_date=None)
Esempio n. 40
0
def get_nodes(ids, graphene_type=None):
    """Return a list of nodes.

    If the `graphene_type` argument is provided, the IDs will be validated
    against this type. If the type was not provided, it will be looked up in
    the Graphene's registry. Raises an error if not all IDs are of the same
    type.
    """
    pks = []
    types = []
    invalid_ids = []
    error_msg = "Could not resolve to a nodes with the global id list of '%s'."
    for graphql_id in ids:
        if graphql_id:
            try:
                _type, _id = from_global_id(graphql_id)
            except Exception:
                invalid_ids.append(graphql_id)
            else:
                if graphene_type:
                    assert str(graphene_type) == _type, (
                        'Must receive an {} id.').format(
                            graphene_type._meta.name)
                pks.append(_id)
                types.append(_type)
    if invalid_ids:
        raise GraphQLError(error_msg % invalid_ids)

    # If `graphene_type` was not provided, check if all resolved types are
    # the same. This prevents from accidentally mismatching IDs of different
    # types.
    if types and not graphene_type:
        assert len(set(types)) == 1, 'Received IDs of more than one type.'
        # get type by name
        type_name = types[0]
        for model, _type in registry._registry.items():
            if _type._meta.name == type_name:
                graphene_type = _type
                break

    nodes = list(graphene_type._meta.model.objects.filter(pk__in=pks))
    if not nodes:
        raise GraphQLError(error_msg % ids)
    nodes_pk_list = [str(node.pk) for node in nodes]
    for pk in pks:
        assert pk in nodes_pk_list, (
            'There is no node of type {} with pk {}'.format(_type, pk))
    return nodes
Esempio n. 41
0
    def mutate_and_get_payload(self, info, **_input):
        discord_id = _input.get('discord_id')
        badge_reference = _input.get('badge').title()
        league_global_id = _input.get('league')

        # Verifica a liga fornecida
        kind, league_id = from_global_id(league_global_id)
        if not kind == 'LeagueType':
            raise Exception('Wrong league ID.')
        try:
            league = League.objects.get(id=league_id)
        except League.DoesNotExist:
            raise Exception('Sorry, this league does not exist.')

        # Tenta recuperar a insígnia do banco de dados
        try:
            badge = Badge.objects.get(reference=badge_reference)
        except Badge.DoesNotExist:
            raise Exception('This Badge does not exist!')

        # Tenta recuperar o treinador
        try:
            trainer = Trainer.objects.get(discord_id=discord_id)
        except Trainer.DoesNotExist:
            raise Exception(f'The trainer does not exist')

        # Recupera o score do treinador
        try:
            trainer_score = trainer.score_set.get(league=league)
        except Score.DoesNotExist:
            raise Exception(
                'This trainer doesnt seems to be registered ' \
                'on the given league!'
            )

        # verifica que o treinaro ainda não possui esta insígina
        if badge in trainer_score.badges.all():
            raise Exception('This trainer already have this badge!')

        # Adiciona a insígnia ao treinador
        trainer_score.badges.add(badge)
        trainer.badge_counter += 1

        trainer_score.save()
        trainer.save()

        return AddBadgeToTrainer(
            f'{discord_id} received {badge_reference} badge!')
Esempio n. 42
0
    def mutate_and_get_payload(root, info, **input):
        profile = Profile.objects.get(id=info.context.user.profile.id)

        if input.get('nickname') is not None:
            profile.nickname = input.get('nickname')
        if input.get('team_prof') is not None:
            team_prof = Team.objects.get(
                id=from_global_id(input.get('team_prof'))[1])
            profile.team_prof = team_prof
            profile.is_coach = input.get('is_coach')
            team_board = TeamBoard.objects.get(team=team_prof)
            team_board.join_count += 1
            team_board.save()
        profile.save()

        return UpdateProfileMutation(profile=profile)
Esempio n. 43
0
    def mutate_and_get_payload(cls, root, info, **input):
        category_id = input.get('category_id')
        user = AndelaUserProfile.objects.get(user=info.context.user)
        user_category = Category.objects.get(pk=from_global_id(category_id)[1])
        try:
            joined_category = Interest(
                follower=user,
                follower_category=user_category
            )
            joined_category.save()
        except IntegrityError:
            raise GraphQLError(
                'User has already shown interest in this category'
            )

        return JoinCategory(joined_category=joined_category)
Esempio n. 44
0
    def mutate_and_get_payload(self, info, **input):
        user = info.context.user
        if user.is_anonymous:
            raise Exception('You must be logged to vote!')

        link = Link.objects.filter(
            id=from_global_id(input.get('link_id'))[1]).first()
        if not link:
            raise Exception('Invalid Link!')

        Vote.objects.create(
            user=user,
            link=link,
        )

        return CreateVote(user=user, link=link)
Esempio n. 45
0
    def clean(self, value):
        if not value and not self.required:
            return None

        try:
            _type, _id = from_global_id(value)
        except (TypeError, ValueError, UnicodeDecodeError, binascii.Error):
            raise ValidationError(self.error_messages["invalid"])

        try:
            CharField().clean(_id)
            CharField().clean(_type)
        except ValidationError:
            raise ValidationError(self.error_messages["invalid"])

        return value
Esempio n. 46
0
    def mutate_and_get_payload(cls, root, info: ResolveInfo,
                               **input) -> 'UpdateReporter':
        _, id = from_global_id(input['id'])

        reporter = Reporter.objects.get(id=id)

        assert info.context.user.is_staff or info.context.user == reporter, 'Permission denied. You can only update your own account.'

        for field, value in input.items():
            if field != 'id':
                setattr(reporter, field, value)

        reporter.full_clean()
        reporter.save()

        return UpdateReporter(reporter=reporter)
Esempio n. 47
0
def _cast(new_type, obj):
    if isinstance(new_type, NonNull):
        assert obj is not None
        return _cast(new_type.of_type, obj)
    elif obj is None:
        return None
    elif isinstance(new_type, List):
        return [_cast(new_type.of_type, x) for x in obj]
    elif isinstance(new_type, Field):
        return _cast(new_type.type, obj)
    elif isinstance(new_type, type) and issubclass(new_type, ObjectType):
        return new_type(obj)
    elif isinstance(new_type, ID):
        return from_global_id(obj)[1]
    else:
        return obj
Esempio n. 48
0
    def mutate_and_get_payload(cls, root, info, id=None, title=None, description=None, date=None):
        login_user = info.context.user
        tsk_obj = task.objects.get(id=from_global_id(id)[1])

        if title:
            tsk_obj.title = title

        if description:
            tsk_obj.description = description

        if date:
            tsk_obj.date = date

        tsk_obj.save()

        return UpdateTaskMutation(tsk=tsk_obj)
Esempio n. 49
0
    def mutate_and_get_payload(self, info, **_input):
        global_id = _input.get('id', '')
        kind, league_id = from_global_id(global_id)

        # Verifica que o id é de uma League
        if not kind == 'LeagueType':
            raise Exception('The ID doesnt match with a League object!')

        try:
            league = League.objects.get(id=league_id)
        except League.DoesNotExist:
            raise Exception('Sorry, the given League does not exist!')

        league.delete()

        return DeleteLeague(league)
Esempio n. 50
0
    def mutate_and_get_payload(cls, root, info, id, Awr=None, Cog=None, Com=None, Mot=None, RRB=None):
        raw_obj = raw_score.objects.get(pk=from_global_id(id)[1])
        if Awr is not None:
            raw_obj.Awr = Awr
        if Cog is not None:
            raw_obj.Cog = Cog
        if Com is not None:
            raw_obj.Com = Com
        if Mot is not None:
            raw_obj.Mot = Mot
        if RRB is not None:
            raw_obj.RRB = RRB

        raw_obj.save()

        return UpdateRawScoreMutation(rawScore=raw_obj)
    def mutate(root, info, question_node_id: graphene.ID,
               answer_indices: graphene.List(graphene.Int)):
        payload = {"answer_index": answer_indices}

        answer_id = create_question_answer(question_node_id, payload)

        if not answer_id:
            raise GraphQLError("Failed to create answer")

        _, question_id = from_global_id(question_node_id)
        question = Question.query.get(question_id)
        for answer_index in answer_indices:
            question.payload["submitted_answers"][answer_index] += 1
        question.question_set.to_update = True

        return CreateTextQuestionAnswer(success=True)
Esempio n. 52
0
def resolve_some_aggregation_by_day(date,
                                    delta,
                                    department,
                                    aggregate_func,
                                    isMonth=False):

    returned_list = []

    filter_kwargs = {
        "department":
        AmebaDepartment.objects.get(id=from_global_id(department)[1]),
    }

    if isMonth:
        now = date - relativedelta.relativedelta(months=delta)
        filter_kwargs["date__month"] = now.month
        filter_kwargs["date__year"] = now.year

    else:
        now = date - timedelta(days=delta)
        filter_kwargs["date"] = now

    i = 0
    while i < delta:
        if isMonth:
            now += relativedelta.relativedelta(months=1)
            filter_kwargs["date__month"] = now.month
            filter_kwargs["date__year"] = now.year
            aggregation = aggregate_func(filter_kwargs=filter_kwargs)
        else:
            filter_kwargs["date"] += datetime.timedelta(days=1)
            aggregation = aggregate_func(
                filter_kwargs={
                    "department": filter_kwargs["department"],
                    "date__gte": filter_kwargs.get("date"),
                    "date__lte": filter_kwargs.get("date")
                })

        returned_list.append({
            "date": filter_kwargs["date"]
            if not isMonth else f"{now.year}年 {now.month}月",
            "aggregation": aggregation
        })

        i += 1

    return returned_list
Esempio n. 53
0
def test_sale_create_updates_products_discounted_prices(
    mock_update_products_discounted_prices_of_catalogues,
    staff_api_client,
    permission_manage_discounts,
):
    query = """
    mutation SaleCreate(
            $name: String,
            $type: DiscountValueTypeEnum,
            $value: PositiveDecimal,
            $products: [ID]
    ) {
        saleCreate(input: {
                name: $name,
                type: $type,
                value: $value,
                products: $products
        }) {
            sale {
                id
            }
            errors {
                field
                message
            }
        }
    }
    """
    variables = {
        "name": "Half price product",
        "type": DiscountValueTypeEnum.PERCENTAGE.name,
        "value": "50",
    }
    response = staff_api_client.post_graphql(
        query, variables, permissions=[permission_manage_discounts]
    )
    assert response.status_code == 200

    content = get_graphql_content(response)
    assert content["data"]["saleCreate"]["errors"] == []

    relay_sale_id = content["data"]["saleCreate"]["sale"]["id"]
    _sale_class_name, sale_id_str = from_global_id(relay_sale_id)
    sale_id = int(sale_id_str)
    mock_update_products_discounted_prices_of_catalogues.delay.assert_called_once_with(
        sale_id
    )
Esempio n. 54
0
    def mutate_and_get_payload(cls, root, info, id, **kwargs):
        user = info.context.user
        _type, id = from_global_id(id)
        role = Role.objects.get(id=id)

        # TODO: Add role superior check: Am I above this role?
        if not user.is_superuser:
            raise Exception('Permission denied.')

        for key, value in kwargs.items():
            if value is not None:
                setattr(role, key, value)
        icon = extract_file(info)
        if icon:
            role.icon = icon
        role.save()
        return UpdateRoleMutation(success=True, role=role)
Esempio n. 55
0
def resolveFilter(qs, args, filters=[], filter_fields=[]):
    filters = {f: args[f] for f in filters if f in args}
    for filterName, className in filter_fields.items():
        filterValue = args.get(filterName)
        if filterValue is None:
            continue
        try:
            filters[filterName] = className.objects.get(
                pk=from_global_id(filterValue)[1])
        except Exception as e:
            print("resolveFilter:", e)
            continue

    if len(filters) > 0:
        qs = qs.filter(**filters)

    return qs
Esempio n. 56
0
    def get_search_results(self, request, queryset, search_term):
        # INFO: 모든 유져의 리스트를 조회할 수 없도록 한다.
        if not search_term:
            return TicketForRegistration.objects.none(), False

        queryset, use_distinct = super().get_search_results(
            request, queryset, search_term)

        # INFO: QR 코드로 읽는 경우를 가정한다.
        if search_term.startswith('https://www.pycon.kr/ticket/my-ticket?id='):
            global_id = search_term.replace(
                'https://www.pycon.kr/ticket/my-ticket?id=', '')
            _, pk = from_global_id(global_id)
            queryset = Ticket.objects.filter(id=pk)
            return queryset, False

        return queryset, use_distinct
Esempio n. 57
0
    def mutate(self, info, input):
        db_hotel_id = from_global_id(input.get('hotel_id'))[1]
        user = info.context.user or None
        hotel = Hotel.objects.get(pk=db_hotel_id)

        if not user or user.is_anonymous:
            raise Exception('You must be logged to delete a hotel!')

        if not hotel:
            raise Exception('Hotel does not exist!')

        reservation = Reservation(user=user,
                                  hotel=hotel,
                                  start_date=input.get('start_date'),
                                  end_date=input.get('end_date'))

        return CreateReservation(reservation=reservation)
Esempio n. 58
0
    def mutate_and_get_payload(cls, root, info, id, question, model_answer):
        team = Team.objects.get(pk=from_global_id(id)[1])

        team.questions.create(
            author=info.context.user,
            question=question,
            model_answer=model_answer,
            topic=team.topic,
        )

        if team.questions.count() == team.members.count():
            team.current_question = team.questions.first()
            team.state = "answer"

        team.save()

        return PostQuestionMutation(team=team)
Esempio n. 59
0
    def mutate_and_get_payload(root, info, **input):
        blog = Blog(
            user_id=info.context.user.id,
            title=input.get('title'),
            content=input.get('content'),
        )
        blog.save()
        blog_comp = Blog.objects.get(id=blog.id)
        if input.get('tags') is not None:
            tags_set = []
            for tag in input.get('tags'):
                tag_id = from_global_id(tag)[1]
                tags_object = Tag.objects.get(id=tag_id)
                tags_set.append(tags_object)
            blog_comp.tags.set(tags_set)

        return CreateBlogMutation(blog=blog_comp)
Esempio n. 60
0
def handle_additional_actions(
    request: WSGIRequest,
    payment_details: Callable,
):
    payment_id = request.GET.get("payment")
    checkout_pk = request.GET.get("checkout")

    if not payment_id or not checkout_pk:
        return HttpResponseNotFound()

    _type, payment_pk = from_global_id(payment_id)
    try:
        payment = Payment.objects.get(
            pk=payment_pk,
            checkout__pk=checkout_pk,
            is_active=True,
            gateway="mirumee.payments.adyen",
        )
    except ObjectDoesNotExist:
        return HttpResponseNotFound(
            "Cannot perform payment. "
            "There is no active adyen payment with specified checkout.")

    extra_data = json.loads(payment.extra_data)
    data = extra_data[-1] if isinstance(extra_data, list) else extra_data

    return_url = payment.return_url

    if not return_url:
        return HttpResponseNotFound(
            "Cannot perform payment. Lack of data about returnUrl.")

    try:
        request_data = prepare_api_request_data(request, data)
    except KeyError as e:
        return HttpResponseBadRequest(e.args[0])
    try:
        result = api_call(request_data, payment_details)
    except PaymentError as e:
        return HttpResponseBadRequest(str(e))

    handle_api_response(payment, result)

    redirect_url = prepare_redirect_url(payment_id, checkout_pk, result,
                                        return_url)
    return redirect(redirect_url)