chore [P-261]: cja
This commit is contained in:
commit
d8056b6c80
1 file changed
+53
-31
+53
-31
@@ -100,6 +100,7 @@ class GetTests(generics.ListAPIView):
|
|||||||
test.attemps_number = test.attemps_number - attempt_counts.get(test.id, 0)
|
test.attemps_number = test.attemps_number - attempt_counts.get(test.id, 0)
|
||||||
|
|
||||||
def delete(self, request):
|
def delete(self, request):
|
||||||
|
"""makes the test not available"""
|
||||||
|
|
||||||
test_id = request.data.get("test_id")
|
test_id = request.data.get("test_id")
|
||||||
try:
|
try:
|
||||||
@@ -143,7 +144,7 @@ class TestCreate(APIView):
|
|||||||
create test
|
create test
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
test = self.create_test(request)
|
self.create_test(request)
|
||||||
|
|
||||||
return Response(
|
return Response(
|
||||||
{"status": "success", "message": "Test created successfully."},
|
{"status": "success", "message": "Test created successfully."},
|
||||||
@@ -215,8 +216,6 @@ class TestCreate(APIView):
|
|||||||
right_wrong=answer["right_wrong"],
|
right_wrong=answer["right_wrong"],
|
||||||
)
|
)
|
||||||
|
|
||||||
return test
|
|
||||||
|
|
||||||
# class GetTesting(APIView):
|
# class GetTesting(APIView):
|
||||||
|
|
||||||
# def get(self, request):
|
# def get(self, request):
|
||||||
@@ -254,7 +253,6 @@ class TestingView(generics.ListCreateAPIView):
|
|||||||
)
|
)
|
||||||
def get(self, request):
|
def get(self, request):
|
||||||
"""Get all testing records for a test"""
|
"""Get all testing records for a test"""
|
||||||
user = request.user
|
|
||||||
test_id = request.query_params.get('test_id')
|
test_id = request.query_params.get('test_id')
|
||||||
try:
|
try:
|
||||||
if test_id:
|
if test_id:
|
||||||
@@ -276,6 +274,7 @@ class TestingView(generics.ListCreateAPIView):
|
|||||||
dictemployees = DictEmployee.objects.filter(id__in=request.data["user_id"])
|
dictemployees = DictEmployee.objects.filter(id__in=request.data["user_id"])
|
||||||
users = User.objects.filter(user__in=dictemployees).distinct()
|
users = User.objects.filter(user__in=dictemployees).distinct()
|
||||||
test = Test.objects.get(id=request.data["test_id"])
|
test = Test.objects.get(id=request.data["test_id"])
|
||||||
|
testings =[]
|
||||||
for user in users:
|
for user in users:
|
||||||
testing = Testing.objects.create(
|
testing = Testing.objects.create(
|
||||||
user=user,
|
user=user,
|
||||||
@@ -284,8 +283,10 @@ class TestingView(generics.ListCreateAPIView):
|
|||||||
completion_date=request.data["completion_date"],
|
completion_date=request.data["completion_date"],
|
||||||
test_passed=False,
|
test_passed=False,
|
||||||
)
|
)
|
||||||
if request.data.get("news"):
|
testings.append(testing)
|
||||||
self.create_news(request, testing)
|
if request.data.get("news"):
|
||||||
|
if testings:
|
||||||
|
self.create_news(request, testings)
|
||||||
return Response(
|
return Response(
|
||||||
{"status": "success", "message": "Testing created successfully."},
|
{"status": "success", "message": "Testing created successfully."},
|
||||||
status=200,
|
status=200,
|
||||||
@@ -302,12 +303,17 @@ class TestingView(generics.ListCreateAPIView):
|
|||||||
"""when removing testing from an employee"""
|
"""when removing testing from an employee"""
|
||||||
try:
|
try:
|
||||||
testing_ids = request.data.get("id", [])
|
testing_ids = request.data.get("id", [])
|
||||||
Testing.objects.filter(id__in=testing_ids).update(is_active=False)
|
testings = Testing.objects.filter(id__in=testing_ids)
|
||||||
news_ids = Testing.objects.filter(id__in=testing_ids
|
testings.update(is_active=False)
|
||||||
).values_list('news_id', flat=True).distinct()
|
news_ids = testings.values_list('news_id', flat=True).distinct()
|
||||||
news_ids_list = [nid for nid in news_ids if nid is not None]
|
news_ids_list = [nid for nid in news_ids if nid is not None]
|
||||||
Testing.objects.filter(id__in=testing_ids).update(news=None)
|
for testing in testings:
|
||||||
News.objects.filter(id__in=news_ids_list).delete()
|
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."},
|
return Response({"status": "success", "message": "Testing is not active."},
|
||||||
status=200)
|
status=200)
|
||||||
except DatabaseError as e:
|
except DatabaseError as e:
|
||||||
@@ -315,6 +321,7 @@ class TestingView(generics.ListCreateAPIView):
|
|||||||
return Response({"status": "error", "message": str(e)}, status=400)
|
return Response({"status": "error", "message": str(e)}, status=400)
|
||||||
|
|
||||||
def delete(self, request):
|
def delete(self, request):
|
||||||
|
"""delete testing"""
|
||||||
testing_id = request.data.get("id")
|
testing_id = request.data.get("id")
|
||||||
try:
|
try:
|
||||||
testing = Testing.objects.get(id=testing_id)
|
testing = Testing.objects.get(id=testing_id)
|
||||||
@@ -325,13 +332,13 @@ class TestingView(generics.ListCreateAPIView):
|
|||||||
print(e)
|
print(e)
|
||||||
return Response({"status": "error", "message": str(e)}, status=400)
|
return Response({"status": "error", "message": str(e)}, status=400)
|
||||||
|
|
||||||
def create_news(self, request, testing):
|
def create_news(self, request, testings):
|
||||||
"""
|
"""
|
||||||
Комментарий
|
Комментарий
|
||||||
"""
|
"""
|
||||||
# formatted_date = datetime.strptime(
|
test_name = testings[0].test.name
|
||||||
# request.data["completion_date"][:-1], "%Y-%m-%dT%H:%M:%S.%f"
|
test_id = testings[0].test.id
|
||||||
# ).strftime("%d.%m.%Y %H:%M")
|
test_file = testings[0].test.file
|
||||||
date_str = request.data["completion_date"]
|
date_str = request.data["completion_date"]
|
||||||
if date_str.endswith('Z'):
|
if date_str.endswith('Z'):
|
||||||
date_str = date_str[:-1] + '+0000' # pytz требует формат +HHMM
|
date_str = date_str[:-1] + '+0000' # pytz требует формат +HHMM
|
||||||
@@ -341,19 +348,39 @@ class TestingView(generics.ListCreateAPIView):
|
|||||||
dt_msk = dt_utc.astimezone(msk_tz)
|
dt_msk = dt_utc.astimezone(msk_tz)
|
||||||
formatted_date = dt_msk.strftime("%d.%m.%Y %H:%M")
|
formatted_date = dt_msk.strftime("%d.%m.%Y %H:%M")
|
||||||
|
|
||||||
testing_url = make_clickable(testing.test.name,
|
testing_url = make_clickable(test_name,
|
||||||
f"/test/testdetail/{testing.test.id}?mode=exam")
|
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(
|
news = News(
|
||||||
title="Пройдите тестирование!",
|
title="Пройдите тестирование!",
|
||||||
text=f'Пройдите тестирование "{testing_url}" до {formatted_date}',
|
text=text,
|
||||||
cdate=request.data["datestart"],
|
cdate=request.data["datestart"],
|
||||||
author=request.user,
|
author=request.user,
|
||||||
link=testing.test.file,
|
link=test_file,
|
||||||
)
|
)
|
||||||
news.save()
|
news.save()
|
||||||
testing.news = news
|
for testing in testings:
|
||||||
testing.save()
|
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):
|
class TestResultView(generics.ListCreateAPIView):
|
||||||
"""API for getting and saving user test results."""
|
"""API for getting and saving user test results."""
|
||||||
@@ -450,7 +477,6 @@ class TestResultView(generics.ListCreateAPIView):
|
|||||||
'answer': None,
|
'answer': None,
|
||||||
})
|
})
|
||||||
# answer_ids = [item['answer'] for item in request.data]
|
# answer_ids = [item['answer'] for item in request.data]
|
||||||
|
|
||||||
test_info = self.get_test_info(answer_ids, test_id)
|
test_info = self.get_test_info(answer_ids, test_id)
|
||||||
if status == 'testing':
|
if status == 'testing':
|
||||||
test_attempt, testing = self.create_test_attempt(user, test_info)
|
test_attempt, testing = self.create_test_attempt(user, test_info)
|
||||||
@@ -459,12 +485,12 @@ class TestResultView(generics.ListCreateAPIView):
|
|||||||
serializer = self.get_serializer(data=prepared_data, many=True)
|
serializer = self.get_serializer(data=prepared_data, many=True)
|
||||||
if serializer.is_valid():
|
if serializer.is_valid():
|
||||||
serializer.save(attempt=test_attempt)
|
serializer.save(attempt=test_attempt)
|
||||||
self.update_testing(user, test_info, testing)
|
self.update_testing(test_info, testing)
|
||||||
|
|
||||||
return Response(data={'score': test_info['score'],
|
return Response(data={'score': test_info['score'],
|
||||||
'answered_questions_total': test_info['answered_questions_total'],
|
'answered_questions_total': test_info['answered_questions_total'],
|
||||||
'is_passed': test_info['is_passed']})
|
'is_passed': test_info['is_passed']})
|
||||||
except Exception as e:
|
except Exception as e: #pylint: disable=W0718
|
||||||
print(e)
|
print(e)
|
||||||
return Response({"status": "error", "message": str(e)}, status=400)
|
return Response({"status": "error", "message": str(e)}, status=400)
|
||||||
|
|
||||||
@@ -480,15 +506,11 @@ class TestResultView(generics.ListCreateAPIView):
|
|||||||
completion_date= datetime.now())
|
completion_date= datetime.now())
|
||||||
return test_attempt, testing
|
return test_attempt, testing
|
||||||
|
|
||||||
def update_testing(self, user, test_info, testing):
|
def update_testing(self, test_info, testing):
|
||||||
"""Updates or creates a Testing record with a test passing flag."""
|
"""Updates or creates a Testing record with a test passing flag."""
|
||||||
test = test_info['test']
|
|
||||||
test_passed = test_info['is_passed']
|
test_passed = test_info['is_passed']
|
||||||
testing.test_passed = test_passed
|
testing.test_passed = test_passed
|
||||||
testing.save()
|
testing.save()
|
||||||
# Testing.objects.update_or_create(user=user,
|
|
||||||
# test=test,
|
|
||||||
# defaults = {"test_passed":test_passed})
|
|
||||||
|
|
||||||
def get_test_info(self, answer_ids, test_id):
|
def get_test_info(self, answer_ids, test_id):
|
||||||
"""Calculates test results from a list of answer IDs."""
|
"""Calculates test results from a list of answer IDs."""
|
||||||
@@ -510,7 +532,7 @@ class TestResultView(generics.ListCreateAPIView):
|
|||||||
pass_perc = test.pass_perc
|
pass_perc = test.pass_perc
|
||||||
correct_answers_perc = 0
|
correct_answers_perc = 0
|
||||||
if answered_questions_total !=0:
|
if answered_questions_total !=0:
|
||||||
correct_answers_perc = (correct_questions/answered_questions_total*100)
|
correct_answers_perc = correct_questions/answered_questions_total*100
|
||||||
result = {
|
result = {
|
||||||
"is_passed": correct_answers_perc >= pass_perc,
|
"is_passed": correct_answers_perc >= pass_perc,
|
||||||
"score": correct_questions,
|
"score": correct_questions,
|
||||||
|
|||||||
Reference in new issue
Block a user