Merge branch 'сja' into develop

This commit is contained in:
Nukeap committed 2025-01-20 17:01:43 +03:00
commit 5d74846942
1 file changed
+47 -68
+47 -68
View File
@@ -68,19 +68,22 @@ class VoteDetail(generics.RetrieveUpdateDestroyAPIView):
except Exception as e: except Exception as e:
return Response({'status': 'error', 'message': str(e)}, status=400) return Response({'status': 'error', 'message': str(e)}, status=400)
answers_employee = set(Answer.objects.filter(question__vote=vote).filter(question__settings__choice="employee").values_list('name', flat=True)) answers_employee = Answer.objects.filter(question__vote=vote).filter(question__settings__choice="employee").values('name', 'question')
answers_names = [item['name'] for item in answers_employee]
question_ids = [item['question'] for item in answers_employee]
if answers_employee: if answers_employee:
employees = DictEmployee.objects.filter(id__in=answers_employee) employees = DictEmployee.objects.filter(id__in=answers_names)
employee_dict = {employee['id']: employee for employee in DictEmployeeSerializer(employees, many=True).data} employee_dict = {employee['id']: employee for employee in DictEmployeeSerializer(employees, many=True).data}
result_dict = {result['answer__id']: {'employee': employee_dict.get(int(result['answer__name']))} for result in results}
serialized_data = self.retrieve(request, *args, **kwargs).data serialized_data = self.retrieve(request, *args, **kwargs).data
for question in serialized_data['questions']: for question in serialized_data['questions']:
for answer in question['answers']: for answer in question['answers']:
if answer['name'] in answers_employee: if question['id'] in question_ids:
answer['employee'] = employee_dict.get(int(answer['name'])) if answer['name'] in answers_names:
answer['employee'] = employee_dict.get(int(answer['name']))
return Response(serialized_data) return Response(serialized_data)
@@ -95,89 +98,59 @@ class VoteCreate(APIView):
return Response({'status': 'error', 'message': str(e)}, status=400) return Response({'status': 'error', 'message': str(e)}, status=400)
def create_vote(self, request): def create_vote(self, request):
user = request.user user = request.user
# for test vote = Vote.objects.create(
# # user = DictEmployee.objects.get(login='9966-00-125')
# # user = User.objects.get(user=user)
vote = Vote(
name=request.data['title'], name=request.data['title'],
description=request.data['description'], description=request.data['description'],
datestart=request.data['startDate'], datestart=request.data['startDate'],
dateend=request.data['endDate'], dateend=request.data['endDate'],
author=user, author=user,
) )
vote.save()
questions_files = request.FILES.getlist('questionsfiles') questions_files = {file.name: file for file in request.FILES.getlist('questionsfiles')}
answers_files = request.FILES.getlist('answersfiles') answers_files = {file.name: file for file in request.FILES.getlist('answersfiles')}
questions = json.loads(request.data['questions']) questions = json.loads(request.data['questions'])
for count, question_data in enumerate(questions, start=1): for count, question_data in enumerate(questions, start=1):
question_image = questions_files.get(question_data['image']['name']) if 'image' in question_data else None
question_image = None question = Question.objects.create(
if 'image' in question_data:
for file in questions_files:
if file.name == question_data['image']['name']:
question_image = file
break
question = Question(
name=question_data['text'], name=question_data['text'],
vote=vote, vote=vote,
file=question_image, file=question_image,
numb=count, numb=count,
settings=question_data.get('settings', {}), settings=question_data.get('settings', {}),
) )
question.save()
for answer in question_data['answers']: for answer in question_data['answers']:
answer_image = None answer_image = answers_files.get(answer['image']['name']) if 'image' in answer else None
if 'image' in answer: Answer.objects.create(
for file in answers_files:
if file.name == answer['image']['name']:
answer_image = file
break
Answer(
name=answer['text'], name=answer['text'],
file=answer_image, file=answer_image,
question=question question=question
).save() )
return vote return vote
def create_news(self, request, vote): def create_news(self, request, vote):
vote_img =os.path.join(settings.MEDIA_ROOT,'defaultimg','vote.png')
vote_name = request.data['title']
vote_author = request.user
# for test formatted_date = datetime.strptime(request.data["endDate"][:-1], "%Y-%m-%dT%H:%M:%S.%f").strftime("%d.%m.%Y %H:%M")
# user = DictEmployee.objects.get(login='9966-00-125') vote_url = make_clickable(request.data['title'], f"/vote/voting/{vote.id}")
# vote_author = User.objects.get(user=user)
title = 'Пройдите голосование!'
end_date_str = request.data["endDate"]
formatted_date = datetime.strptime(end_date_str[:-1], "%Y-%m-%dT%H:%M:%S.%f").strftime("%d.%m.%Y %H:%M")
# formatted_date = datetime.fromisoformat(request.data["endDate"]).strftime("%d.%m.%Y %H:%M")
vote_url = make_clickable(vote_name, f"/vote/voting/{vote.id}")
text = f'Пройдите голосование "{vote_url}" до {formatted_date}'
news = News( news = News(
title=title, title = 'Пройдите голосование!',
text = text, text = f'Пройдите голосование "{vote_url}" до {formatted_date}',
cdate = request.data['startDate'], cdate = request.data['startDate'],
author = vote_author, author = request.user,
link = vote_img, link = os.path.join(settings.MEDIA_ROOT,'defaultimg','vote.png'),
vote = vote vote = vote
) )
news.save() news.save()
def make_clickable(text, url): def make_clickable(text, url):
text = html.escape(text) text = html.escape(text)
anchor = f'<a href="{html.escape(url)}">{text}</a>' anchor = f'<a href="{html.escape(url)}">{text}</a>'
return anchor return anchor
class GetDictEmployee(APIView): class GetDictEmployee(APIView):
def get(self, request): def get(self, request):
@@ -191,29 +164,35 @@ class GetResults(APIView):
vote_id = request.GET.get('id') vote_id = request.GET.get('id')
try: try:
vote = Vote.objects.get(id=vote_id) vote = Vote.objects.get(id=vote_id)
except Exception as e: except Vote.DoesNotExist:
return Response({'status': 'error', 'message': str(e)}, status=400) return Response({'status': 'error', 'message': 'Vote not found'}, status=404)
answers_employee = set(Answer.objects.filter(question__vote=vote).filter(question__settings__choice="employee").values_list('name', flat=True))
results = Result.objects.filter(answer__question__vote=vote).values('answer__id', 'answer__name').annotate(count=Count('id'))
serialized_data = VoteSerializer(vote).data serialized_data = VoteSerializer(vote).data
answers_employee = Answer.objects.filter(
question__vote=vote,
question__settings__choice="employee"
).values('name', 'question')
answers_names = [item['name'] for item in answers_employee]
question_ids = [item['question'] for item in answers_employee]
employee_dict = {}
if answers_employee: if answers_employee:
employees = DictEmployee.objects.filter(id__in=answers_employee) employees = DictEmployee.objects.filter(id__in=answers_names)
employee_dict = {employee['id']: employee for employee in DictEmployeeSerializer(employees, many=True).data} employee_dict = {employee['id']: employee for employee in DictEmployeeSerializer(employees, many=True).data}
result_dict = {result['answer__id']: {
'count': result['count'], results = Result.objects.filter(
**({'employee': employee_dict.get(int(result['answer__name']), None)} if result['answer__name'] in answers_employee else {}) answer__question__vote=vote
} ).values('answer_id').annotate(count=Count('id'))
for result in results
} result_dict = {int(result['answer_id']): result['count'] for result in results}
for question in serialized_data['questions']: for question in serialized_data['questions']:
for answer in question['answers']: for answer in question['answers']:
answer_data = result_dict.get(answer['id'], {}) answer['count'] = result_dict.get(int(answer['id']), 0)
answer['count'] = answer_data.get('count', 0) if question['id'] in question_ids:
if answer['name'] in answers_employee: if answer['name'] in answers_names:
answer['employee'] = employee_dict.get(int(answer['name'])) answer['employee'] = employee_dict.get(int(answer['name']))
return Response(serialized_data) return Response(serialized_data)