from rest_framework.views import APIView from rest_framework.response import Response from django.db.models import Count from django.db.models import Q from .models import * from userauth.models import * from .serializers import * from datetime import datetime from rest_framework import generics from rest_framework.generics import ListAPIView from navigation.models import News from django.db import DatabaseError import json from collections import defaultdict import os from django.conf import settings from django.urls import reverse import html from rest_framework.permissions import IsAuthenticated import base64 import hashlib from cryptography.fernet import Fernet from django.db.models import F from drf_yasg import openapi from drf_yasg.utils import swagger_auto_schema from vote.views import make_clickable, set_real_departments from vote.serializers import DictEmployeeSerializer import pytz class GetTests(generics.ListAPIView): queryset = Test.objects.all() serializer_class = TestsSerializer pagination_class = None @swagger_auto_schema( operation_description="""Получить список тестов по статусу *Нужно авторизоваться!""", manual_parameters=[ openapi.Parameter( 'status', openapi.IN_QUERY, description=("Статус тестов (например, 'active', 'completed'). " "Пустое значение вернет все тесты." ), type=openapi.TYPE_STRING, required=False, ), ], responses={ 200: "success", 400: 'error', } ) def get (self, request, *args, **kwargs): """receives tests assigned to the user""" user = request.user # user = User.objects.get(username='9966-00-125') status = request.query_params.get('status') tests = self.get_tests_by_status(status, datetime.now(), user) if status is not None: self.set_attemps_number(user, tests) serialized_tests = self.get_serializer(tests, many=True).data return Response(serialized_tests) def get_tests_by_status(self, status, now, user): """Returns a QuerySet of tests filtered by status for a given user.""" print(status) base_filters = { 'testing__user': user, 'testing__is_active': True, 'is_available': True, } if status is None: return Test.objects.filter(is_available=True) if status == 'active': filters = {**base_filters, 'testing__datestart__lte': now, 'testing__completion_date__gte': now} elif status == 'completed': filters = {**base_filters, 'testing__completion_date__lt': now} else: return Test.objects.none() return Test.objects.filter(**filters).distinct() def set_attemps_number(self, user, tests): """Updates the number of attempts remaining for each test for the user.""" attempt_counts = TestAttempt.objects.filter(testing__user=user, testing__test__in=tests, testing__is_active=True ).values('testing__test' ).annotate(count=Count('testing__test')) attempt_counts = {item['testing__test']: item['count'] for item in attempt_counts} for test in tests: test.attemps_number = test.attemps_number - attempt_counts.get(test.id, 0) def delete(self, request): """makes the test not available""" test_id = request.data.get("test_id") try: test = Test.objects.get(id=test_id) test.is_available = False test.save() # testings = Testing.objects.filter(test=test) # testings.update(is_active=False) return Response( {"status": "success", "message": "Test is not available."}, status=200, ) except DatabaseError as e: print(e) return Response({"status": "error", "message": str(e)}, status=400) class TestDetail(generics.RetrieveUpdateDestroyAPIView): """comment""" queryset = Test.objects.all() serializer_class = TestSerializer lookup_url_kwarg = 'id' lookup_field = 'id' def get(self, request, *args, **kwargs): """Processes a GET request to retrieve detailed information about a test.""" test = self.get_object() number_of_questions = test.question_count random_questions = test.questions.order_by('?')[:number_of_questions] test_serialized = TestSerializer(test).data test_serialized['questions'] = TestQuestionSerializer(random_questions, many=True).data return Response(test_serialized) class TestCreate(APIView): """ create test """ def post(self, request): """ create test """ try: self.create_test(request) return Response( {"status": "success", "message": "Test created successfully."}, status=200, ) except ValueError as e: return Response({"status": "error", "message": str(e)}, status=400) except DatabaseError as e: return Response({"status": "error", "message": str(e)}, status=400) def create_test(self, request): """ create test """ user = request.user test_image = ( request.FILES.get("image") if "image" in request.FILES else None ) test = Test.objects.create( file=test_image, name=request.data["name"], description=request.data["description"], author=user, pass_perc=request.data["pass_perc"], time=request.data["time"], question_count=request.data["question_count"], attemps_number=request.data["attemps_number"], is_available = True ) test_files=[TestFile(file=file,test=test) for file in request.FILES.getlist("test_files")] if len(test_files)>0: TestFile.objects.bulk_create(test_files) questions_files = { file.name: file for file in request.FILES.getlist("questionsfiles") } answers_files = { file.name: file for file in request.FILES.getlist("answersfiles") } questions = json.loads(request.data["questions"]) for count, question_data in enumerate(questions, start=1): question_image = ( questions_files.get(question_data["image"]["name"]) if "image" in question_data and question_data["image"] is not None else None ) question = TestQuestion.objects.create( name=question_data["text"], test=test, file=question_image, numb=count, settings=question_data.get("settings", {}), ) for answer in question_data["answers"]: answer_image = ( answers_files.get(answer["image"]["name"]) if "image" in answer and answer["image"] is not None else None ) TestAnswer.objects.create( name=answer["text"], file=answer_image, question=question, right_wrong=answer["right_wrong"], ) # class GetTesting(APIView): # def get(self, request): # user = request.user # tests = Testing.objects.filter(user=user) # test_names = {test.id: test.test.name for test in tests} # serializer = TestingSeriaizer(tests, many=True).data # for test in serializer: # if test['id'] in test_names: # test['test_name'] = test_names[test['id']] # return Response(serializer) class TestingView(generics.ListCreateAPIView): """API for testing.""" queryset = Testing.objects.all() serializer_class = TestingSeriaizer pagination_class = None @swagger_auto_schema( operation_description="""Получить все назначения теста *Нужно авторизоваться!""", manual_parameters=[ openapi.Parameter( 'test_id', openapi.IN_QUERY, description="ID теста", type=openapi.TYPE_INTEGER, required=False, ), ], responses={ 200: "success", 400: 'error', } ) def get(self, request): """Get all testing records for a test""" test_id = request.query_params.get('test_id') try: if test_id: testings = Testing.objects.filter(test_id=test_id, is_active=True).select_related('user__user') else: testings = Testing.objects.filter(is_active=True ).select_related('user__user') serializer = self.get_serializer(testings, many=True) return Response(serializer.data) except DatabaseError as e: print(e) return Response({"status": "error", "message": str(e)}, status=400) def post(self, request): """create testing""" try: dictemployees = DictEmployee.objects.filter(id__in=request.data["user_id"]) users = User.objects.filter(user__in=dictemployees).distinct() test = Test.objects.get(id=request.data["test_id"]) testings =[] for user in users: testing = Testing.objects.create( user=user, test=test, datestart=request.data["datestart"], completion_date=request.data["completion_date"], test_passed=False, ) testings.append(testing) if request.data.get("news"): if testings: self.create_news(request, testings) return Response( {"status": "success", "message": "Testing created successfully."}, status=200, ) except ValueError as e: return Response({"status": "error", "message": str(e)}, status=400) except DatabaseError as e: print(e) return Response({"status": "error", "message": str(e)}, status=400) def put(self, request): """when removing testing from an employee""" try: testing_ids = request.data.get("id", []) testings = Testing.objects.filter(id__in=testing_ids) testings.update(is_active=False) news_ids = testings.values_list('news_id', flat=True).distinct() news_ids_list = [nid for nid in news_ids if nid is not None] for testing in testings: if testing.news: self.change_news(testing) testing.news = None testing.save() if not Testing.objects.filter(news__id__in=news_ids_list): News.objects.filter(id__in=news_ids_list).delete() return Response({"status": "success", "message": "Testing is not active."}, status=200) except DatabaseError as e: print(e) return Response({"status": "error", "message": str(e)}, status=400) def delete(self, request): """delete testing""" testing_id = request.data.get("id") try: testing = Testing.objects.get(id=testing_id) testing.delete() return Response({"status": "success", "message": "Testing deleted successfully."}, status=200) except DatabaseError as e: print(e) return Response({"status": "error", "message": str(e)}, status=400) def create_news(self, request, testings): """ Комментарий """ test_name = testings[0].test.name test_id = testings[0].test.id test_file = testings[0].test.file date_str = request.data["completion_date"] if date_str.endswith('Z'): date_str = date_str[:-1] + '+0000' # pytz требует формат +HHMM dt_utc = datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%S.%f%z") msk_tz = pytz.timezone("Europe/Moscow") dt_msk = dt_utc.astimezone(msk_tz) formatted_date = dt_msk.strftime("%d.%m.%Y %H:%M") testing_url = make_clickable(test_name, f"/test/testdetail/{test_id}?mode=exam") text = f'Пройдите тестирование "{testing_url}" до {formatted_date} ' texts = [] for testing in testings: texts.append(testing.user.user.fio) text += ", ".join(testing.user.user.fio for testing in testings) + "." news = News( title="Пройдите тестирование!", text=text, cdate=request.data["datestart"], author=request.user, link=test_file, ) news.save() for testing in testings: testing.news = news testing.save() def change_news(self, testing): """change news if the test assignment for an employee has been removed""" if not testing.news: return user_fio = testing.user.user.fio new_text = testing.news.text substrings = [f'{user_fio}, ', f', {user_fio}'] for substr in substrings: if substr in new_text: new_text = new_text.replace(substr, "") break testing.news.text = new_text testing.news.save() class TestResultView(generics.ListCreateAPIView): """API for getting and saving user test results.""" queryset = TestResult.objects.all() serializer_class = TestResultSerializer pagination_class = None @swagger_auto_schema( operation_description="""Получить результаты тестов *Нужно авторизоваться!""", manual_parameters=[ openapi.Parameter( 'id', openapi.IN_QUERY, description="ID теста", type=openapi.TYPE_INTEGER, required=True, ), ], responses={ 200: "success", 400: 'error', } ) def get(self, request, *args, **kwargs): """Get the results of the last user test attempt.""" user = request.user # user = User.objects.get(username = "9966-00-125") test_id = request.GET.get('id') last_attempt = TestAttempt.objects.filter(testing__user=user, testing__test__id=test_id, testing__is_active=True, ).order_by('-completion_date').first() answer_ids = TestResult.objects.filter(attempt=last_attempt ).values_list('answer__id', flat=True) test_info = self.get_test_info(answer_ids, test_id) return Response(data={'score': test_info['score'], 'answered_questions_total': test_info['answered_questions_total'], 'is_passed': test_info['is_passed']}) @swagger_auto_schema( operation_description=""" Сохранить результаты тестов *Нужно авторизоваться!""", manual_parameters=[ openapi.Parameter( 'status', openapi.IN_QUERY, description=("Статус тестов (например, 'testing'). " "Пустое значение - режим тренировки"), type=openapi.TYPE_STRING, required=False, ), ], request_body=openapi.Schema( type=openapi.TYPE_ARRAY, items=openapi.Schema( type=openapi.TYPE_OBJECT, properties={ 'answer': openapi.Schema(type=openapi.TYPE_INTEGER, description='ID ответа') }, ), ), responses={ 200: "success", 400: 'error', } ) def post(self, request, *args, **kwargs): """Saves the results of a new test attempt.""" try: user = request.user # user = User.objects.get(username = "9966-00-125") status = request.query_params.get('status') test_id = request.query_params.get('id') answer_ids = [] prepared_data = [] for data in request.data: question_id = data.get('question_id') answers_id = data.get('answers_id', []) for sublist in answers_id: if isinstance(sublist, list): answer_ids.extend(sublist) else: answer_ids.append(sublist) if answers_id: for answer_id in answers_id: prepared_data.append({ 'question': question_id, 'answer': answer_id, }) else: prepared_data.append({ 'question': question_id, 'answer': None, }) # answer_ids = [item['answer'] for item in request.data] test_info = self.get_test_info(answer_ids, test_id) if status == 'testing': test_attempt, testing = self.create_test_attempt(user, test_info) # serializer = self.get_serializer(data=request.data, many=True) serializer = self.get_serializer(data=prepared_data, many=True) if serializer.is_valid(): serializer.save(attempt=test_attempt) self.update_testing(test_info, testing) return Response(data={'score': test_info['score'], 'answered_questions_total': test_info['answered_questions_total'], 'is_passed': test_info['is_passed']}) except Exception as e: #pylint: disable=W0718 print(e) return Response({"status": "error", "message": str(e)}, status=400) def create_test_attempt(self, user, test_info): """Creates a new test attempt for the user.""" test = test_info['test'] score = test_info['score'] testing = Testing.objects.get(user=user, test=test, is_active=True) attempt_count = get_attempt_count(testing)+ 1 test_attempt = TestAttempt.objects.create(testing=testing, score=score, attempt_number=attempt_count, completion_date= datetime.now()) return test_attempt, testing def update_testing(self, test_info, testing): """Updates or creates a Testing record with a test passing flag.""" test_passed = test_info['is_passed'] testing.test_passed = test_passed testing.save() def get_test_info(self, answer_ids, test_id): """Calculates test results from a list of answer IDs.""" test_answers = TestAnswer.objects.filter(id__in=answer_ids) test = Test.objects.get(id=test_id) answered_questions_total = test_answers.values('question').distinct().count() q_count = test.question_count all_questions = len(TestQuestion.objects.filter(test=test)) if all_questions <= q_count: q_count = all_questions correct_questions = sum( TestAnswer.objects.filter( question=question, id__in=test_answers, right_wrong=True ).count() == TestAnswer.objects.filter( question=question, right_wrong=True ).count() and TestAnswer.objects.filter( question=question, id__in=test_answers, right_wrong=False ).count() == 0 for question in set(test_answers.values_list('question', flat=True)) ) pass_perc = test.pass_perc correct_answers_perc = 0 if q_count !=0: correct_answers_perc = correct_questions/q_count*100 # if answered_questions_total !=0: # correct_answers_perc = correct_questions/answered_questions_total*100 result = { "is_passed": correct_answers_perc >= pass_perc, "score": correct_questions, "test": test, "answered_questions_total": answered_questions_total, } return result def get_attempt_count(testing): """get attempt count""" return TestAttempt.objects.filter(testing=testing).count() class GetUsers(APIView): """ Комментарий """ def get(self, request): """ Комментарий """ dictemployees = DictEmployee.objects.filter(deleted=0,id__in=User.objects.filter( user__isnull=False).values_list('user_id', flat=True)) set_real_departments(dictemployees) employees_serializer = DictEmployeeSerializer(dictemployees, many=True).data return Response(employees_serializer)