示例#1
0
def join_user_from_page(request: WSGIRequest, group_id: int, profile_id: int):
    if request.is_ajax():
        if auth.get_user(request).is_anonymous:
            return JsonResponse({}, status=404)

        team = Group.objects.filter(id=group_id).first()
        if team is None:
            return JsonResponse({}, status=404)

        profile_added = Profile.objects.filter(id=profile_id).first()
        if profile_added is None:
            return JsonResponse({}, status=404)

        current_profile = get_user_profile(request)
        if team.owner != current_profile and not _profile_is_owner_or_moderator(
                current_profile):
            return JsonResponse({}, status=403)

        if current_profile.company is None:
            return JsonResponse({}, status=403)

        try:
            new_invitation = Invitation.objects.get(profile_id=profile_id,
                                                    team=team)
        except ObjectDoesNotExist:
            new_invitation = Invitation()
        new_invitation.profile = profile_added
        new_invitation.initiator = current_profile
        new_invitation.team = team
        new_invitation.date = date.today()
        new_invitation.is_viewed = False
        new_invitation.is_rendered = False
        new_invitation.save()
        return JsonResponse({}, status=200)
示例#2
0
def assign_position_profile(request: WSGIRequest, id_company: int,
                            profile_id: int, position_id: int):
    if request.is_ajax():
        if auth.get_user(request).is_anonymous:
            return JsonResponse({}, status=404)

        current_profile = get_user_profile(request)
        if not _profile_is_owner_or_moderator(current_profile):
            return JsonResponse({}, status=403)

        company = Company.objects.filter(id=id_company).first()
        if company is None:
            return JsonResponse({}, status=404)

        changed_profile: Profile = Profile.objects.filter(
            id=profile_id).first()
        if changed_profile is None:
            return JsonResponse({}, status=404)

        added_position = PositionCompany.objects.filter(id=position_id).first()
        if added_position is None:
            return JsonResponse({}, status=404)

        changed_profile.positions.add(added_position)
        return JsonResponse({}, status=200)
示例#3
0
def search_new_teammates(request: WSGIRequest, group_id: int) -> JsonResponse:
    if request.is_ajax():
        if auth.get_user(request).is_anonymous:
            return JsonResponse({}, status=404)

        team = Group.objects.filter(id=group_id).first()
        if team is None:
            return JsonResponse({}, status=404)

        profile = get_user_profile(request)
        if profile.company is None:
            return JsonResponse({}, status=403)

        user_input = request.GET.get('search', '')
        profiles = get_search_result_for_profiles(
            profile.company.profile_set.all(), user_input, profile.company)
        completed_profiles = _build_teammates(profiles, team, profile)
        if len(completed_profiles) == 0:
            content = get_render_bad_search(
                'По вашему запросу ничего не найдено')
        else:
            content = SimpleTemplateResponse(
                'main/teams/new_future_teammates.html', {
                    'users': completed_profiles
                }).rendered_content
        return JsonResponse({'content': content}, status=200)
示例#4
0
def remove_platform_profile(request: WSGIRequest, id_company: int,
                            profile_id: int, platform_id: int):
    if request.is_ajax():
        if auth.get_user(request).is_anonymous:
            return JsonResponse({}, status=404)

        current_profile = get_user_profile(request)
        if not _profile_is_owner_or_moderator(current_profile):
            return JsonResponse({}, status=403)

        company = Company.objects.filter(id=id_company).first()
        if company is None:
            return JsonResponse({}, status=404)

        changed_profile: Profile = Profile.objects.filter(
            id=profile_id).first()
        if changed_profile is None:
            return JsonResponse({}, status=404)

        added_platform = PlatformCompany.objects.filter(id=platform_id).first()
        if added_platform is None:
            return JsonResponse({}, status=404)

        changed_profile.platforms.remove(added_platform)
        return JsonResponse({}, status=200)
示例#5
0
def remove_role_from_profile(request: WSGIRequest, id_company: int,
                             profile_id: int):
    if request.is_ajax():
        if auth.get_user(request).is_anonymous:
            return JsonResponse({}, status=404)

        current_profile = get_user_profile(request)
        company = Company.objects.filter(id=id_company).first()
        if company is None:
            return JsonResponse({}, status=404)

        changed_profile_role = Profile.objects.filter(id=profile_id).first()
        if changed_profile_role is None:
            return JsonResponse({}, status=404)

        role_name = request.POST.get('roleName', '')
        if role_name == 'master':
            if not _profile_is_owner_or_moderator(current_profile):
                return JsonResponse({}, status=403)

            SurveyWizard.objects.filter(profile=changed_profile_role).delete()

        elif role_name == 'moderator':
            if current_profile != company.owner:
                return JsonResponse({}, status=403)

            Moderator.objects.filter(profile=changed_profile_role).delete()

        else:
            return JsonResponse({}, status=404)

        return JsonResponse({}, status=200)
示例#6
0
def kick_profile_from_company(request: WSGIRequest, id_company: int,
                              profile_id: int):
    if request.is_ajax():
        if auth.get_user(request).is_anonymous:
            return JsonResponse({}, status=404)

        current_profile = get_user_profile(request)
        if not _profile_is_owner_or_moderator(current_profile):
            return JsonResponse({}, status=403)

        company = Company.objects.filter(id=id_company).first()
        if company is None:
            return JsonResponse({}, status=404)

        changed_profile = Profile.objects.filter(id=profile_id).first()
        if changed_profile is None:
            return JsonResponse({}, status=404)

        changed_profile.platforms.clear()
        changed_profile.positions.clear()
        company.profile_set.remove(changed_profile)
        teams = Group.objects.filter(company=company, profile=changed_profile)
        for team in teams:
            if team.owner != changed_profile:
                team.profile_set.remove(changed_profile)
            else:
                team.delete()
        SurveyWizard.objects.filter(profile=changed_profile).delete()
        Moderator.objects.filter(profile=changed_profile).delete()
        NeedPassPoll.objects.filter(profile=changed_profile).delete()
        Poll.objects.filter(target=changed_profile).delete()
        return JsonResponse({}, status=200)
示例#7
0
def invite_to_team(request: WSGIRequest, profile_id: int):
    if request.is_ajax():
        if auth.get_user(request).is_anonymous:
            return JsonResponse({}, status=404)

        current_profile = get_user_profile(request)
        if current_profile.company is None:
            return JsonResponse({}, status=403)

        changed_profile_role = Profile.objects.filter(id=profile_id).first()
        if changed_profile_role is None:
            return JsonResponse({}, status=404)

        group_id = int(request.POST.get('teamId', '-1'))
        team = Group.objects.filter(id=group_id).first()
        if team is None:
            return JsonResponse({}, status=404)

        try:
            new_invitation = Invitation.objects.get(profile_id=profile_id,
                                                    team=team)
        except ObjectDoesNotExist:
            new_invitation = Invitation()
        new_invitation.profile = changed_profile_role
        new_invitation.initiator = current_profile
        new_invitation.team = team
        new_invitation.date = date.today()
        new_invitation.is_viewed = False
        new_invitation.is_rendered = False
        new_invitation.save()
        return JsonResponse({}, status=200)
示例#8
0
def review_query(request: WSGIRequest):
    """Delivers a HTTP response that contains only images wherefore it exists a specified annotation
    (groundtruth) for the current selected class (stored in session). Conditions were specified by
    HTTP Post method parameters.

    :param request: the request
    :return: serialized images (JSON) that match the conditions
    """
    if request.is_ajax() and request.method == "POST" and all(
            x in request.POST for x in ['groundtruth']):

        bbox_objects = Bboxannotation.objects.filter(
            classid_id=request.session[
                SessionConfig.SELECTED_PERSON_SESSION_KEY]).order_by(
                    '-imageid')
        serialized_images_dict = serialize_images(
            bbox_objects,
            request,
            lambda x: x.imageid,
            return_dict=True,
            additional_value_function=add_absolute_image_path)

        serialized_images_dict = update_groundtruth_annotation(
            serialized_images_dict,
            request.session[SessionConfig.SELECTED_PERSON_SESSION_KEY],
            mode="image")

        if 'face' in request.COOKIES.keys():
            if request.COOKIES['face'] != 'photo':
                serialized_images_dict['elements'] = update_face_list_from_db(
                    serialized_images_dict['elements'], bbox_objects)

        return HttpResponse(json.dumps(serialized_images_dict))
    return HttpResponseBadRequest()
示例#9
0
def kick_teammate(request: WSGIRequest, group_id: int):
    if request.is_ajax():
        if auth.get_user(request).is_anonymous:
            return JsonResponse({}, status=404)

        team = Group.objects.filter(id=group_id).first()
        if team is None:
            return JsonResponse({}, status=404)

        current_profile = get_user_profile(request)
        if current_profile.company is None:
            return JsonResponse({}, status=403)

        teammate_id = int(request.POST.get('teammateId', '-1'))
        teammate = Profile.objects.filter(id=teammate_id).first()
        if teammate is None:
            team.profile_set.remove(current_profile)
            return JsonResponse({}, status=200)

        if team.owner != current_profile and not _profile_is_owner_or_moderator(
                current_profile):
            return JsonResponse({}, status=403)

        team.profile_set.remove(teammate)
        return JsonResponse({}, status=200)
示例#10
0
文件: views.py 项目: TIBHannover/VIVA
 def retrieval_query_data(request: WSGIRequest) -> HttpResponse:
     class_type_name = Classtype.objects.get(id=class_type_id).name.lower()
     if not request.is_ajax() or request.method != "POST" or \
             not all(x in request.POST for x in [class_type_name, 'asc', 'annotations']):
         return HttpResponseBadRequest(
             "Wrong request method or missing parameter!")
     try:
         class_id = int(request.POST[class_type_name])
     except ValueError:
         return HttpResponseBadRequest("Class ID needs to be an integer!")
     s_class = Class.objects.get(id=class_id)
     s_ascending = request.POST['asc'] == "1"
     s_annotations = request.POST['annotations'] == "1"
     evaluation_classtypeid = Evaluation.objects.filter(
         classid__classtypeid_id=class_type_id).values_list('id', flat=True)
     latest_model = Model.objects.filter(
         evaluation__in=evaluation_classtypeid,
         inference_stored=True).latest('date')
     predictions = Imageprediction.objects \
         .filter(classid=s_class, modelid=latest_model.id) \
         .order_by('score' if s_ascending else '-score')
     if not s_annotations:
         # the image can be annotated for another class - so there might exist an image annotation but without a
         # matching class id
         predictions = predictions.filter(
             ~Q(imageid__imageannotation__classid=s_class)
             | Q(imageid__imageannotation__isnull=True))
     return HttpResponse(
         serialize_images(
             predictions, request, lambda x: x.imageid,
             lambda image_dict, image: add_prediction_score(
                 image_dict, image, latest_model.id, s_class.id)))
 def post(self, request: WSGIRequest, *args, **kwargs):
     log.info("We are in POST")
     if request.is_ajax():
         value = "Hi " + request.POST["value"]
         log.info(f"User sent {value} via Ajax")
         return JsonResponse({"success": True, "value": value})
     else:
         value = request.POST["post-text"]
         log.info(f"User sent {value} via POST")
         return self.render_to_response(context={"value": value})
示例#12
0
def new_notification(request: WSGIRequest, profile_id: int):
    if request.is_ajax():
        profile = get_user_profile(request)
        # todo забаговало
        #if profile.pk != profile_id:
        #    return JsonResponse({}, status=400)

        category = request.GET.get('category', '')

        if category == 'results':
            notifications = CreatedPoll.objects.filter(profile=profile, is_viewed=False, is_rendered=False)\
                .filter(poll__count_passed__gt=2)
            collected_notifications = _build_notifications_poll(
                notifications, False)

        elif category == 'polls':
            notifications = NeedPassPoll.objects.filter(profile=profile,
                                                        is_viewed=False,
                                                        is_rendered=False)
            collected_notifications = _build_notifications_poll(
                notifications, False)

        elif category == 'invites':
            collected_notifications = _build_invites(
                Invitation.objects.filter(profile=profile, is_rendered=False),
                False)

        else:
            return JsonResponse({}, status=400)

        if len(collected_notifications) != 0:
            print(collected_notifications)

        count_new_my_poll = CreatedPoll.objects.filter(
            profile=profile, is_viewed=False,
            poll__count_passed__gt=2).count()
        count_new_polls = NeedPassPoll.objects.filter(profile=profile,
                                                      is_viewed=False).count()
        count_new_invitations = Invitation.objects.filter(
            profile=profile, is_viewed=False).count()

        content = SimpleTemplateResponse(
            'main/user/notifications.html', {
                'notifications': collected_notifications
            }).rendered_content
        args = {
            'notificationsCount': {
                'polls': count_new_polls,
                'results': count_new_my_poll,
                'invites': count_new_invitations
            },
            'content': content
        }
        return JsonResponse(args, status=200)
示例#13
0
 def post(self, request: WSGIRequest, *args, **kwargs):
     if not request.is_ajax():
         return HttpResponse(status=400)
     if "action" not in request.POST:
         return HttpResponse(status=400)
     action = request.POST["action"]
     if action == "change_program":
         return self.on_program_choice(request.POST["program_id"])
     if action == "move_course":
         return self.on_move_course(request.POST["course_id"], request.POST["block_id"])
     return HttpResponse(status=400)
def users_page(request: WSGIRequest):
    """
    Страница с пользователями, проходящих тесты
    """
    if request.is_ajax():
        HRUser = get_user_model()
        hr_users = HRUser.objects.filter(role__exact=HRUser.USER_ROLE) \
                    .values('id', 'first_name', 'last_name') \
                    .annotate(answers=Count('answer'))

        return JsonResponse({'data': list(hr_users)}, safe=False)

    return render(request, 'questionnaire/users.html')
示例#15
0
def remove_team(request: WSGIRequest, id_company: int, team_id: int):
    if request.is_ajax():
        profile = get_user_profile(request)
        company = profile.company
        if company is None:
            return JsonResponse({}, status=404)
        team = Group.objects.filter(id=team_id).first()
        if team is None:
            return JsonResponse({}, status=404)
        if not _profile_is_owner_or_moderator(profile):
            return JsonResponse({}, status=403)
        team.delete()
        return JsonResponse({}, status=200)
示例#16
0
 def post(self, request: WSGIRequest, *args, **kwargs):
     if not request.is_ajax():
         raise NotImplementedError()
     text = request.POST["free_text"]
     department = request.POST["department"]
     faculty = request.POST["faculty"]
     queryset = courses.search(text, department, faculty)[:40]
     result = [c.as_dict for c in queryset]
     result.sort(key=lambda c: c["score"], reverse=True)
     for course in result:
         course["url"] = reverse("course-details",
                                 args=[course["course_number"]])
         course["score"] = floatformat(course["score"])
     return JsonResponse({"courses": result})
示例#17
0
def send_answer(request: WSGIRequest, poll_id: int):
    if request.is_ajax():
        if auth.get_user(request).is_anonymous:
            return JsonResponse({}, status=404)

        poll = Poll.objects.filter(id=poll_id)
        if poll.first() is None:
            return JsonResponse({}, status=400)

        _collect_answers(request, poll.first().questions.all().count())
        poll.update(count_passed=F('count_passed') + 1)
        NeedPassPoll.objects.filter(
            poll=poll.first(), profile=get_user_profile(request)).delete()
        return JsonResponse({}, status=200)
示例#18
0
def remove_invite(request: WSGIRequest, profile_id: int, notification_id: int):
    if request.is_ajax():
        if auth.get_user(request).is_anonymous:
            return JsonResponse({}, status=404)

        profile = get_user_profile(request)
        if profile.pk != profile_id:
            return JsonResponse({}, status=400)

        invite = Invitation.objects.filter(id=notification_id).first()
        if invite is None:
            return JsonResponse({}, status=404)
        invite.delete()
        return JsonResponse({}, status=200)
示例#19
0
def remove_platform(request: WSGIRequest, id_company: int,
                    platform_id: int) -> JsonResponse:
    if request.is_ajax():
        company = Company.objects.filter(pk=id_company).first()
        if company is None:
            return JsonResponse({}, status=404)
        profile = get_user_profile(request)
        if not _profile_is_owner_or_moderator(profile):
            return JsonResponse({}, status=403)
        platform = PlatformCompany.objects.filter(id=platform_id).first()
        if platform is None:
            return JsonResponse({}, status=404)

        platform.delete()
        return JsonResponse({}, status=200)
def user_results_page(request: WSGIRequest, user_id: int):
    """
    Отображает тесты, пройденные пользователем.
    """
    HRUser = get_user_model()
    hr_user = get_object_or_404(HRUser, id=user_id)

    if request.is_ajax():
        answers = Answer.objects.filter(user=hr_user) \
                    .values('end_datetime', 'evaluation', 'max_evaluation', \
                            name=F('questionnaire__name'), q_id=F('questionnaire__id'))

        return JsonResponse({'data': list(answers)}, safe=False)

    return render(request, 'questionnaire/user_results.html',
                  {'hr_user': hr_user})
示例#21
0
def load_teams_and_users(request: WSGIRequest,
                         id_company: int) -> JsonResponse:
    if request.is_ajax():
        category = request.GET.get('category', None)
        if category is None:
            return JsonResponse({}, status=404)
        company: Company = Company.objects.filter(pk=id_company).first()
        if company is None:
            return JsonResponse({}, status=404)

        search = request.GET.get('search', '')
        if category == 'users':
            content = _load_users(company, get_user_profile(request), search)
        elif category == 'teams':
            content = _load_teams(company, get_user_profile(request), search)
        return JsonResponse({'content': content}, status=200)
示例#22
0
 def post(self, request: WSGIRequest, *args, **kwargs):
     if not request.is_ajax():
         raise NotImplementedError()
     text = request.POST["free_text"]
     school = request.POST["school"]
     faculty = request.POST["faculty"]
     log.info(
         f"Searching for {text}, school {school}, faculty {faculty}...")
     queryset = Course.find_by(text, school, faculty)[:35]
     result = [c.as_dict for c in queryset]
     result.sort(key=lambda c: c["score"], reverse=True)
     for course in result:
         course["url"] = reverse("course-details",
                                 args=[course["course_number"]])
         course["score"] = floatformat(course["score"])
     return JsonResponse({"courses": result})
示例#23
0
def add_platform(request: WSGIRequest, id_company):
    if request.is_ajax():
        company = Company.objects.filter(pk=id_company).first()
        if company is None:
            return JsonResponse({}, status=404)
        profile = get_user_profile(request)
        if not _profile_is_owner_or_moderator(profile):
            return JsonResponse({}, status=403)
        name_platform = request.POST['namePlatform']
        if not validate_user_input_in_company_settings(name_platform):
            return JsonResponse({}, status=400)

        platform = PlatformCompany()
        platform.name = name_platform
        platform.company = company
        platform.save()
        return JsonResponse({'platformId': platform.pk}, status=200)
示例#24
0
def add_position(request: WSGIRequest, id_company) -> JsonResponse:
    if request.is_ajax():
        company = Company.objects.filter(pk=id_company).first()
        if company is None:
            return JsonResponse({}, status=404)
        profile = get_user_profile(request)
        if not _profile_is_owner_or_moderator(profile):
            return JsonResponse({}, status=403)
        name_position = request.POST['namePosition']
        if not validate_user_input_in_company_settings(name_position):
            return JsonResponse({}, status=400)

        position = PositionCompany()
        position.name = name_position
        position.company = company
        position.save()
        return JsonResponse({'positionId': position.pk}, status=200)
示例#25
0
def loading(request: WSGIRequest, profile_id: int) -> JsonResponse:
    if request.is_ajax():
        profile = get_user_profile(request)
        if profile != Profile.objects.filter(id=profile_id).first():
            return JsonResponse({}, status=404)

        selected_category = request.GET.get('selectedCategory', '')
        collected = _build_notifications(profile, selected_category)

        if collected is None:
            return JsonResponse({}, status=400)
        if len(collected) == 0:
            content = get_render_bad_search("Сейчас нет уведомлений")
        else:
            content = SimpleTemplateResponse('main/user/notifications.html', {
                'notifications': collected
            }).rendered_content
        return JsonResponse({'content': content}, status=200)
示例#26
0
def search_teams(request: WSGIRequest) -> JsonResponse:
    if request.is_ajax():
        if auth.get_user(request).is_anonymous:
            return JsonResponse({}, status=404)
        profile = get_user_profile(request)
        if profile.company is None:
            return JsonResponse({}, status=403)
        user_input = request.GET.get('search', '')
        teams = profile.groups.all()
        teams = get_search_result_for_teams(teams, user_input)
        collected_teams = _build_teams(teams, profile)
        if len(collected_teams) == 0:
            content = get_render_bad_search(
                'По вашему запросу ничего не найдено')
        else:
            content = SimpleTemplateResponse('main/teams/teams.html', {
                'teams': collected_teams
            }).rendered_content
        return JsonResponse({'content': content}, status=200)
def survey_result_page(request: WSGIRequest, questionnaire_id: int):
    """
    Отображает список результотов теста
    """
    questionnaire = get_object_or_404(Questionnaire, id=questionnaire_id)
    if request.is_ajax():
        answers = Answer.objects.filter(questionnaire=questionnaire) \
            .values('end_datetime', 'evaluation', 'max_evaluation', first_name=F('user__first_name'),
                        last_name=F('user__last_name'), u_id=F('user__id'))

        return JsonResponse({'data': list(answers)}, safe=False)

    if request.method == 'POST':
        answers = Answer.objects.filter(questionnaire=questionnaire)
        for answer in answers:
            answer.get_evaluation(force=True)

    return render(request, 'questionnaire/survey_result.html',
                  {'questionnaire': questionnaire})
示例#28
0
def save_settings_change(request: WSGIRequest, id_company: int):
    if request.is_ajax():
        profile = get_user_profile(request)
        company_queryset = Company.objects.filter(pk=id_company)
        company = company_queryset.first()
        if company is None:
            return JsonResponse({}, status=404)
        if not _profile_is_owner_or_moderator(profile):
            return JsonResponse({}, status=403)
        name = request.POST.get('name', company.name)
        description = request.POST.get('description', company.description)
        if name is None or description is None:
            return JsonResponse({}, status=403)
        if not validate_user_input_in_company_settings(name) or \
                not validate_user_input_in_company_settings(description):
            return JsonResponse({}, status=400)

        company_queryset.update(name=name, description=description)
        return JsonResponse({}, status=200)
示例#29
0
def review_query(request: WSGIRequest):
    """Delivers a HTTP response that contains only images wherefore it exists a specified annotation
    (difficult, groundtruth) for the current selected class (stored in session). Conditions were specified by
    HTTP Post method parameters.

    :param request: the request
    :return: serialized images (JSON) that match the conditions
    """
    if request.is_ajax() and request.method == "POST" and all(
            x in request.POST for x in ['difficult', 'groundtruth']):
        return HttpResponse(
            serialize_images(Imageannotation.objects.filter(
                groundtruth=request.POST['groundtruth'] == "1",
                difficult=request.POST['difficult'] == "1",
                classid_id=request.session[
                    SessionConfig.SELECTED_CONCEPT_SESSION_KEY]).order_by(
                        '-imageid'),
                             request,
                             image_extractor=lambda x: x.imageid))
    return HttpResponseBadRequest()
示例#30
0
def team_change(request: WSGIRequest, group_id: int) -> redirect:
    if auth.get_user(request).is_anonymous:
        return redirect('/')
    if request.is_ajax():
        team: Group = Group.objects.filter(id=group_id).first()
        if team is None:
            return JsonResponse({}, status=404)

        profile = get_user_profile(request)
        if profile.company is None:
            return JsonResponse({}, status=403)

        if team.owner != profile and not _profile_is_owner_or_moderator(
                profile):
            return JsonResponse({}, status=403)

        team.name = request.POST.get('name', team.name)
        team.description = request.POST.get('description', team.description)
        team.save()
        return JsonResponse({}, status=200)