Merge branch 'dev-denzel' into test

This commit is contained in:
Nukeap committed 2025-01-13 08:15:54 +03:00
commit db01218e94
26 files changed
+1470 -677

No files matched your search

+2 -1
View File
@@ -8,4 +8,5 @@ portal/settings.py
/front/node_modules/
*.sqlite3
/media/
/static/
/static/
*.env
+6
View File
@@ -0,0 +1,6 @@
ENGINE=django.db.backends.mysql
DBNAME = accounting
USER =
PASSWORD=
HOST=127.0.0.1
PORT=3306
-8
View File
@@ -1,8 +0,0 @@
class Settings():
def __init__(self) -> None:
self.secret_key=''
self.redis_hosts = []
self.db = {
}
pass
+301
View File
@@ -0,0 +1,301 @@
"""
Django settings for portal project.
Generated by 'django-admin startproject' using Django 4.2.3.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/ref/settings/
"""
from pathlib import Path
import os
from .ds import Settings
stngs = Settings()
CORS_ORIGIN_ALLOW_ALL=True
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
LIST_PER_PAGE=25
SECRET_KEY=stngs.secret_key
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
myDEBUG=True
SWAGGER_SETTINGS = {
'DEFAULT_INFO': 'import.path.to.urls.api_info',
'SECURITY_DEFINITIONS': {
'Basic': {
'type': 'basic'
},
'Bearer': {
'type': 'apiKey',
'name': 'Authorization',
'in': 'header'
}
}
}
ALLOWED_HOSTS = []
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": {
"hosts":stngs.redis_hosts,
},
},
}
# Application definition
INSTALLED_APPS = [
'daphne',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'djoser',
'rest_framework_simplejwt',
'navigation.apps.NavigationConfig',
'drf_yasg',
'accounts',
'safety',
'vote.apps.VoteConfig',
'commeteresp',
# 'orgmanagment',
'corsheaders',
'watcher.apps.WatcherConfig',
'userauth.apps.UserauthConfig',
'feedback.apps.FeedbackConfig',
'general_vacation.apps.GeneralVacationConfig',
'about_inspection.apps.AboutInspectionConfig',
'calendar_of_events.apps.CalendarOfEventsConfig',
'tests.apps.TestsConfig',
'ckeditor'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
# 'django.contrib.auth.middleware.RemoteUserMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
AUTHENTICATION_BACKENDS = [
# 'django.contrib.auth.backends.RemoteUserBackend',
'accounts.backends.CustomAuth',
'django.contrib.auth.backends.ModelBackend'
]
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10,
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
),
}
ROOT_URLCONF = 'portal.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
# WSGI_APPLICATION = 'portal.wsgi.application'
ASGI_APPLICATION = "portal.asgi.application"
# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases
DATABASES = stngs.db
# Password validation
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
AUTH_USER_MODEL = 'accounts.User'
# Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/
LANGUAGE_CODE = 'ru'
# TIME_ZONE = 'UTC'
TIME_ZONE = 'Europe/Moscow'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/
STATIC_URL = '/static/'
# STATICFILES_DIRS = (
# BASE_DIR.joinpath('static'),
# )
STATIC_ROOT = BASE_DIR.joinpath('static')
CKEDITOR_UPLOAD_PATH = "uploads/"
# Media
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR.joinpath('media')
# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
from datetime import timedelta
SIMPLE_JWT = {
"ACCESS_TOKEN_LIFETIME": stngs.access_token_lifetime,
"REFRESH_TOKEN_LIFETIME": stngs.refresh_token_lifetime,
"ROTATE_REFRESH_TOKENS": False,
"BLACKLIST_AFTER_ROTATION": False,
"UPDATE_LAST_LOGIN": False,
"ALGORITHM": "HS256",
"SIGNING_KEY": SECRET_KEY,
"VERIFYING_KEY": "",
"AUDIENCE": None,
"ISSUER": None,
"JSON_ENCODER": None,
"JWK_URL": None,
"LEEWAY": 0,
"AUTH_HEADER_TYPES": ("Bearer",),
"AUTH_HEADER_NAME": "HTTP_AUTHORIZATION",
"USER_ID_FIELD": "id",
"USER_ID_CLAIM": "user_id",
"USER_AUTHENTICATION_RULE": "rest_framework_simplejwt.authentication.default_user_authentication_rule",
"AUTH_TOKEN_CLASSES": ("rest_framework_simplejwt.tokens.AccessToken",),
"TOKEN_TYPE_CLAIM": "token_type",
"TOKEN_USER_CLASS": "rest_framework_simplejwt.models.TokenUser",
"JTI_CLAIM": "jti",
"SLIDING_TOKEN_REFRESH_EXP_CLAIM": "refresh_exp",
"SLIDING_TOKEN_LIFETIME": timedelta(minutes=5),
"SLIDING_TOKEN_REFRESH_LIFETIME": timedelta(days=1),
"TOKEN_OBTAIN_SERIALIZER": 'accounts.backends.MyTokenObtainPairSerializer',
"TOKEN_REFRESH_SERIALIZER": "rest_framework_simplejwt.serializers.TokenRefreshSerializer",
"TOKEN_VERIFY_SERIALIZER": "rest_framework_simplejwt.serializers.TokenVerifySerializer",
"TOKEN_BLACKLIST_SERIALIZER": "rest_framework_simplejwt.serializers.TokenBlacklistSerializer",
"SLIDING_TOKEN_OBTAIN_SERIALIZER": "rest_framework_simplejwt.serializers.TokenObtainSlidingSerializer",
"SLIDING_TOKEN_REFRESH_SERIALIZER": "rest_framework_simplejwt.serializers.TokenRefreshSlidingSerializer",
}
CKEDITOR_CONFIGS = {
'default': {
# 'skin': 'moono',
# 'skin': 'office2013',
'toolbar_Basic': [
['Source', '-', 'Bold', 'Italic']
],
'toolbar_YourCustomToolbarConfig': [
# {'name': 'document', 'items': ['Source', '-', 'Save', 'NewPage', 'Preview', 'Print', '-', 'Templates']},
# {'name': 'clipboard', 'items': ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo']},
{'name': 'editing', 'items': ['Find',]},
# {'name': 'forms',
# 'items': ['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton',
# 'HiddenField']},
# '/',
{'name': 'basicstyles',
'items': ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat']},
{'name': 'paragraph',
'items': ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-',
'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-',
# 'BidiLtr', 'BidiRtl',
]},
# '/',
{'name': 'links', 'items': ['Link', 'Unlink', 'Anchor']},
{'name': 'insert',
'items': [ 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak']},
# 'Image', 'Flash', 'Iframe']},
'/',
{'name': 'styles', 'items': ['Styles', 'Format', 'Font', 'FontSize']},
{'name': 'colors', 'items': ['TextColor', 'BGColor']},
{'name': 'tools', 'items': ['Maximize', 'ShowBlocks']},
# {'name': 'about', 'items': ['About']},
# '/', # put this to force next toolbar on new line
{'name': 'yourcustomtools', 'items': [
# put the name of your editor.ui.addButton here
'Preview',
'Maximize',
]},
],
'toolbar': 'YourCustomToolbarConfig', # put selected toolbar config here
# 'toolbarGroups': [{ 'name': 'document', 'groups': [ 'mode', 'document', 'doctools' ] }],
# 'height': 291,
# 'width': '100%',
# 'filebrowserWindowHeight': 725,
# 'filebrowserWindowWidth': 940,
# 'toolbarCanCollapse': True,
# 'mathJaxLib': '//cdn.mathjax.org/mathjax/2.2-latest/MathJax.js?config=TeX-AMS_HTML',
'tabSpaces': 4,
'extraPlugins': ','.join([
'uploadimage', # the upload image feature
# your extra plugins here
'div',
'autolink',
'autoembed',
'embedsemantic',
'autogrow',
# 'devtools',
'widget',
'lineutils',
'clipboard',
'dialog',
'dialogui',
'elementspath'
]),
}
}
BIN
View File
Binary file not shown.
+1 -12
View File
@@ -1,15 +1,4 @@
from django.contrib import admin
from .models import *
# Register your models here.
admin.site.register(ThanksVote)
admin.site.register(BestVote)
class DictEmplyeeRAdmin(admin.ModelAdmin):
list_display=('id_dict_employee', 'id_dict_department',)
list_editable=('id_dict_department', )
admin.site.register(DictEmplyeeR, DictEmplyeeRAdmin)
admin.site.register(Vote)
+1
View File
@@ -4,4 +4,5 @@ from django.apps import AppConfig
class VoteConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'vote'
verbose_name = 'Голосование'
+34 -32
View File
@@ -1,43 +1,45 @@
from django.db import models
from userauth.models import *
from accounts.models import User
import datetime
# Create your models here.
class ThanksVote(models.Model):
voted_user = models.CharField(blank=False, max_length=255)
department_user = models.CharField(
blank=False, default=None, max_length=255)
cand_name = models.CharField(blank=False, default=None, max_length=255)
vote_thanks_date = models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name = "Голосование, хочу сказать спасибо!"
verbose_name_plural = "Голосование, хочу сказать спасибо!"
class Vote(models.Model):
name = models.CharField(max_length=255,verbose_name='Название голосования')
description = models.TextField(verbose_name='Описание')
datestart = models.DateTimeField(default=datetime.datetime.now, verbose_name='Дата и время начала периода')
dateend = models.DateTimeField(default=datetime.datetime.now, verbose_name='Дата и время окончания периода')
settings = models.JSONField(default=dict, verbose_name='Json настроек голосования')
author = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='Создатель голосования')
def __str__(self):
return self.cand_name
class BestVote(models.Model):
voted_user = models.CharField(blank=False, max_length=255)
department_user = models.CharField(
blank=False, default=None, max_length=255)
cand_name = models.CharField(blank=False, default=None, max_length=255)
vote_best_date = models.DateTimeField(auto_now_add=True)
return self.name
class Meta:
verbose_name = "Голосование, мой коллега самый лучший"
verbose_name_plural = "Голосование, мой коллега самый лучший"
verbose_name = "Голосование"
verbose_name_plural = "Голосования"
class Question(models.Model):
question = models.CharField(max_length=255)
vote = models.ForeignKey(Vote, related_name='questions', on_delete=models.CASCADE)
file = models.ImageField(upload_to='question_images/', null=True, blank=True)
numb = models.PositiveIntegerField()
def __str__(self):
return self.cand_name
return self.question
class Answer(models.Model):
answer = models.CharField(max_length=255)
file = models.FileField(upload_to='answer_files/', null=True, blank=True)
question = models.ForeignKey(Question, related_name='answers', on_delete=models.CASCADE)
class DictEmplyeeR(models.Model):
# id = models.IntegerField(primary_key=True)
id_dict_employee = models.ForeignKey(DictEmployee, models.DO_NOTHING)
id_dict_department = models.ForeignKey(DictDepartment, models.DO_NOTHING)
class Meta:
verbose_name = "Сотрудники(реальные отделы)"
verbose_name_plural = "Сотрудники(реальные отделы)"
def __str__(self):
return str(self.id_dict_employee)
return self.answer
class Result(models.Model):
user = models.ForeignKey(DictEmployee, on_delete=models.CASCADE)
answer = models.ForeignKey(Answer, on_delete=models.CASCADE)
comment = models.TextField(null=True, blank=True)
def __str__(self):
return f'Result by {self.user.username} for {self.answer.answer}'
+16 -22
View File
@@ -3,32 +3,26 @@ from .models import *
from userauth.models import *
class GetEmpSerializer(serializers.ModelSerializer):
class VoteSerializer(serializers.ModelSerializer):
class Meta:
model = DictEmployee
fields = ['id', 'id_dict_department',
'fio', 'post', 'department']
model = Vote
fields = '__all__'
class GetEmpSerializerR(serializers.ModelSerializer):
id = serializers.CharField(source="id_dict_employee.id")
fio = serializers.CharField(source="id_dict_employee.fio")
id_dict_department = serializers.CharField(source="id_dict_employee.id_dict_department")
post = serializers.CharField(source="id_dict_employee.post")
department = serializers.CharField(source="id_dict_employee.department")
class QuestionSerializer(serializers.ModelSerializer):
class Meta:
model = DictEmplyeeR
fields = ['id', 'id_dict_department',
'fio', 'post', 'department']
model = Question
fields = '__all__'
class AnswerSerializer(serializers.ModelSerializer):
class Meta:
model = Answer
fields = '__all__'
class ThanksVoteSerializer(serializers.ModelSerializer):
class ResultSerializer(serializers.ModelSerializer):
class Meta:
model = ThanksVote
fields = ('id', 'voted_user', 'cand_name', 'vote_thanks_date')
model = Result
fields = '__all__'
class BestVoteSerializer(serializers.ModelSerializer):
class Meta:
model = BestVote
fields = ('id', 'voted_user', 'cand_name', 'vote_best_date')
class VoteResultSerializer(serializers.Serializer):
answer = serializers.CharField(source='answer__answer')
count = serializers.IntegerField()
+1 -8
View File
@@ -4,12 +4,5 @@ from .views import *
urlpatterns = [
path('get_for_thn/', GetForThn.as_view(),),
path('get_for_bst/', GetForBst.as_view(),),
path('setthanks/', SetThanks.as_view(), name=''),
path('getthanks/', GetThanks.as_view(), name=''),
path('setbest/', SetBest.as_view(), name=''),
path('getbest/', GetBest.as_view(), name=''),
path('getnotvotethn/', GetNotVoteThn.as_view()),
path('getnotvotebst/', GetNotVoteBst.as_view()),
path('getvotes/', GetVotes.as_view(),name='GetVotes'),
]
+49 -63
View File
@@ -5,78 +5,64 @@ from django.db.models import Q
from .models import *
from userauth.models import *
from .serializers import *
import datetime
# Create your views here.
class GetVotes(APIView):
class GetForThn(APIView):
def get(self, request):
user_login = request.GET.get('login')
all_emps = DictEmplyeeR.objects.exclude(id_dict_employee__login=user_login).exclude(id_dict_employee__department='Руководство').exclude(id_dict_employee__deleted=1).order_by('id_dict_employee__fio')
return Response(GetEmpSerializerR(all_emps, many=True).data)
user = request.user
# user = DictEmployee.objects.get(login='9966-00-125')
now = datetime.datetime.now()
status = request.query_params.get('status')
print(status)
votes = self.get_votes_by_status(status, now)
serialized_votes = VoteSerializer(votes, many=True).data
for vote in serialized_votes:
vote['is_passed'] = self.has_participated(user, vote['id'])
return Response(serialized_votes)
def get_votes_by_status(self, status, now):
status_filters = {
'active': Vote.objects.filter(dateend__gt=now),
'completed': Vote.objects.filter(dateend__lt=now),
}
return status_filters.get(status, Vote.objects.none()).order_by('dateend')
class GetForBst(APIView):
def get(self, request):
user_login = request.GET.get('login')
dep_id = DictEmplyeeR.objects.get(id_dict_employee__login=user_login)
emp_user = DictEmplyeeR.objects.filter(Q(id_dict_department=dep_id.id_dict_department), ~Q(id_dict_employee__login=user_login)).exclude(id_dict_employee__deleted=1).order_by('id_dict_employee__fio')
return Response(GetEmpSerializerR(emp_user, many=True).data)
def has_participated(self, employee, vote):
return Result.objects.filter(user=employee, answer__question__vote=vote).exists()
class SetThanks(APIView):
def post(self, request):
voted_user = request.data['voted_user']
department_user = request.data['department_user']
cand_name = request.data['cand_name_id']
ThanksVote.objects.create(
voted_user=voted_user,
department_user=department_user,
cand_name=cand_name
def create_vote(self, request):
vote = Vote(
name=request.data['name'],
description=request.data['description'],
datestart=request.data['datestart'],
dateend=request.data['dateend'],
settings=request.data.get('settings', {}),
author=request.user,
)
return Response("Ваш голос добавлен!")
vote.save()
def delete_vote(self,request):
vote_id = request.data.get('vote_id')
vote = Vote.objects.get(id=vote_id)
questions = vote.questions.all()
for question in questions:
answers = question.answers.all()
answers.delete()
class GetThanks(APIView):
def get(self, request):
# Группировка кандидатов по имени и подсчет каждого
count_thanks = ThanksVote.objects.values('voted_user',
'cand_name').annotate(total=Count('id')).order_by('cand_name')
return Response(count_thanks)
questions.delete()
results = Result.objects.filter(answer__question__vote=vote)
results.delete()
class SetBest(APIView):
def post(self, request):
voted_user = request.data['voted_user']
department_user = request.data['department_user']
cand_name = request.data['cand_name_id']
BestVote.objects.create(
voted_user=voted_user,
department_user=department_user,
cand_name=cand_name
)
return Response("Ваш голос добавлен!")
vote.delete()
class GetBest(APIView):
def get(self, request):
# Группировка кандидатов по имени и подсчет каждого
count_bests = BestVote.objects.values('voted_user','department_user', 'cand_name').annotate(total=Count('id')).order_by('cand_name')
return Response(count_bests)
class GetNotVoteThn(APIView):
def get(self, request):
list_thn_users = ThanksVote.objects.values('voted_user')
list_emp = DictEmplyeeR.objects.filter(
id_dict_employee__deleted=0).exclude(id_dict_employee__login__in=list_thn_users).exclude(id_dict_employee__department='Руководство').order_by('id_dict_employee__fio')
return Response(GetEmpSerializerR(list_emp, many=True).data)
class GetNotVoteBst(APIView):
def get(self, request):
list_bst_users = BestVote.objects.values('voted_user')
list_emp_bst = DictEmplyeeR.objects.filter(
id_dict_employee__deleted=0).exclude(id_dict_employee__login__in=list_bst_users).exclude(id_dict_employee__department='Руководство').order_by('id_dict_employee__fio')
return Response(GetEmpSerializerR(list_emp_bst, many=True).data)
def get_vote_results(self, request):
vote_id = request.data.get('vote_id')
vote = Vote.objects.get(id=vote_id)
results = Result.objects.filter(answer__question__vote=vote).values('answer__answer').annotate(count=Count('id'))
serialized_results = VoteResultSerializer(results, many=True).data
return Response(serialized_results)
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "front",
"version": "0.0.75",
"version": "0.0.82",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "front",
"version": "0.0.75",
"version": "0.0.82",
"dependencies": {
"-": "^0.0.1",
"@ckeditor/ckeditor5-build-classic": "^41.4.2",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "front",
"version": "0.0.75",
"version": "0.0.82",
"scripts": {
"dev": "vite",
"build": "vite build",
Binary file not shown.

Before

Width:  |  Height:  |  Size: 281 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 MiB

+3 -3
View File
@@ -1,6 +1,6 @@
<template>
<h3>ДО КОНЦА ГОЛОСОВАНИЯ ОСТАЛОСЬ:</h3>
<div class="card-count">{{ displayDays }} дней {{ displayHours }} часов {{ displayMinutes }} минут</div>
<h6>ДО КОНЦА ГОЛОСОВАНИЯ ОСТАЛОСЬ:</h6>
<div class="text-red text-h6">{{ displayDays }} дней {{ displayHours }} часов {{ displayMinutes }} минут</div>
</template>
<script>
export default {
@@ -32,7 +32,7 @@ export default {
const timer = setInterval(() => {
const now = new Date();
// здесь задается конец отчета (гггг, мм, дд, остальные цифры не меняются)
const end = new Date(2024, 11 - 1, 14, 10, 10, 10);
const end = new Date(2025, 0, 13, 23, 59, 59);
const distance = end.getTime() - now.getTime();
if (distance < 0) {
-47
View File
@@ -1,47 +0,0 @@
<template>
<span>{{ perc_best }}%</span>
</template>
<script>
import { ref } from "vue";
import { computed } from "vue";
import { clearAxios } from "@/utils/axios-api";
import { useAccountStore } from '@/store/AccountStore';
export default {
setup() {
let account_login = useAccountStore().user.login;
let department_id = useAccountStore().user.id_dict_department;
let all_dep = ref([]);
let all_voted = ref([]);
let perc_best = ref();
const getAllDep = () => {
clearAxios.get(`api/vote/get_for_bst/?login=${account_login}&dep=${department_id}`).then((data) => {
all_dep.value = data.data;
});
};
const getVoted = () => {
clearAxios.get(`api/vote/getbest/`).then((data) => {
all_voted.value = data.data;
});
};
getAllDep();
getVoted();
perc_best = computed(() => Math.round(all_voted.value.length / all_dep.value.length * 100))
return {
all_dep,
all_voted,
perc_best,
}
}
}
</script>
<style></style>
-46
View File
@@ -1,46 +0,0 @@
<template>
<span>{{ perc_thn }}%</span>
</template>
<script>
import { ref } from "vue";
import { computed } from "vue";
import { clearAxios } from "@/utils/axios-api";
import { useAccountStore } from '@/store/AccountStore';
export default {
setup() {
let account_login = useAccountStore().user.login;
let all_cod = ref([]);
let all_voted = ref([]);
let perc_thn = ref();
const getAllCod = () => {
clearAxios.get(`api/vote/get_for_thn/?login=${account_login}`).then((data) => {
all_cod.value = data.data;
});
};
const getVoted = () => {
clearAxios.get(`api/vote/getthanks/`).then((data) => {
all_voted.value = data.data;
});
};
getAllCod();
getVoted();
perc_thn = computed(() => Math.round(all_voted.value.length / all_cod.value.length * 100))
return {
all_cod,
all_voted,
perc_thn,
}
}
}
</script>
<style></style>
+206 -110
View File
@@ -1,73 +1,33 @@
<template>
<v-row justify="center" align="center">
<v-col justify="center" align="center" class="ma-3">
<v-card width="700" height="820" class="elevation-12">
<v-card class="mb-2" color="teal-darken-1" elevation="0">
<v-card-title>Голосование</v-card-title>
<v-card-title color="teal-darken-1">&laquo;Мой коллега самый лучший&raquo;</v-card-title>
</v-card>
<v-card color="teal-darken-1" class="ma-2">
<v-card-title>Процент проголосовавших</v-card-title>
</v-card>
<v-card elevation="0">
<v-card-text class="perc-voted">
{{ perc_bst }}%
</v-card-text>
</v-card>
<v-card color="teal-darken-1" class="mb-2">
<v-card-title>Лидер номинации</v-card-title>
</v-card>
<v-card class="scroll-leaders" elevation="0">
<v-card v-for="(employees, department) in max_bst" :key="department" elevation="0">
<v-card-title>{{ department }}</v-card-title>
<div v-for="employee in employees" :key="employee.name">
{{ employee.name }}
</div>
</v-card>
</v-card>
<v-card color="teal-darken-1" class="ma-2">
<v-card-title>ФИО не участвовавших в голосовании</v-card-title>
</v-card>
<v-card elevation="0">
<v-card class="scroll-window" elevation="0">
<v-card v-for="[key, val] of Object.entries(result_bst)">
<v-card-title>{{ key }}</v-card-title>
<div v-for="item_fio in val">
{{ item_fio.fio }}
</div>
</v-card>
</v-card>
</v-card>
</v-card>
</v-col>
<v-row justify="center" align="center" class="pa-2">
<v-col justify="center" align="center">
<v-card width="700" height="820" class="elevation-12">
<v-card class="mb-2" color="teal-darken-1" elevation="0">
<v-card-title>Голосование</v-card-title>
<v-card-title>&laquo;Хочу сказать Спасибо!&raquo;</v-card-title>
<v-card class="" color="teal-darken-1" elevation="0">
<!-- <v-card-title>Голосование</v-card-title> -->
<v-card-title >&laquo;Лучший новогодний костюм!&raquo;</v-card-title>
</v-card>
<v-card color="teal-darken-1" class="ma-2">
<v-card-title>Процент проголосовавших</v-card-title>
</v-card>
<v-card elevation="0">
<v-card-text class="perc-voted">
<perc-thn />
<v-card class="px-2">
<v-card-title class="bg-teal-darken-1">Процент проголосовавших</v-card-title>
<v-card-text class="text-h6 pa-1">
{{ perc_thanks }}%
</v-card-text>
</v-card>
<v-card color="teal-darken-1" class="mb-2">
<v-card color="teal-darken-1" >
<v-card-title>Лидер номинации</v-card-title>
</v-card>
<v-card class="scroll-leaders pt-4" elevation="0">
<div v-for="leader in max_thn">
{{ leader }}
<div v-for="leader in max_thn.slice(0,3)">
{{ leader.cand_name }} - {{ leader.total }}
</div>
</v-card>
<v-card color="teal-darken-1" class="ma-2">
<v-card-title>ФИО не участвовавших в голосовании</v-card-title>
</v-card>
<v-card class="scroll-window" elevation="0">
<v-card v-for="[key, val] of Object.entries(result_thn)">
<v-card v-for="[key, val] of Object.entries(notvotedthanks)">
<v-card-title>{{ key }}</v-card-title>
<div v-for="item_fio in val">
{{ item_fio.fio }}
@@ -85,84 +45,222 @@ import { computed } from "vue";
import { clearAxios } from "@/utils/axios-api";
import { objectToString } from "@vue/shared";
import { useAccountStore } from '@/store/AccountStore';
import PercThn from '@/components/vote/PercThn.vue';
import { el } from "date-fns/locale";
export default {
components: {
PercThn,
},
setup() {
props:{
usersvotedbest:{
type:Array,
default:()=>[]
},
uservotedthanks:{
type:Array,
default:()=>[]
},
all_cod:{
type:Array,
default:()=>[]
}
},
setup(props) {
let account_login = useAccountStore().user.login;
let result_thn = ref([]);
let result_bst = ref([]);
let all_voted_bst = ref([]);
let all_voted_thn = ref([]);
let max_thn = ref();
let max_bst = ref({});
let all_cod = ref([]);
// let max_thn = ref({});
// let max_bst = ref({});
let perc_bst = ref();
const getNotVoted = () => {
clearAxios.get(`/api/vote/getnotvotethn/`).then((data) => {
let not_voted_thn = data.data;
result_thn.value = Object.groupBy(not_voted_thn, ({ department }) => department);
});
clearAxios.get(`/api/vote/getnotvotebst/`).then((data) => {
let not_voted_bst = data.data;
result_bst.value = Object.groupBy(not_voted_bst, ({ department }) => department);
});
};
// const
const perc_thanks = computed({
get(){
// console.log(props.all_cod);
return Math.round(props.uservotedthanks.length*100/(props.all_cod.length+1))
}
})
const perc_best = computed({
get(){
const getPercAndWin = () => {
clearAxios.get(`/api/vote/getthanks/`).then((data) => {
all_voted_thn = data.data;
let max_total = Math.max(...all_voted_thn.map(item => item.total));
max_thn.value = all_voted_thn.filter(item => item.total === max_total).map(item => item.cand_name)
});
return Math.round(props.usersvotedbest.length*100/(props.all_cod.length+1))
}
})
clearAxios.get(`api/vote/get_for_thn/?login=${account_login}`).then((data) => {
all_cod.value = data.data;
});
clearAxios.get(`/api/vote/getbest/`).then((data) => {
all_voted_bst.value = data.data;
// Групировка по департаметам
const groupedEmployees = {}
all_voted_bst.value.forEach(item => {
const { department_user, cand_name, total } = item;
if (!groupedEmployees[department_user]) {
groupedEmployees[department_user] = [];
}
groupedEmployees[department_user].push({ name: cand_name, total });
});
// Нахождение лучших сотрудников в каждом департаменте
for (const department in groupedEmployees) {
const employees = groupedEmployees[department];
// Поиск максимального количества голосов
const maxTotal = Math.max(...employees.map(emp => emp.total));
// Фильтрация сотрудников с максимальным количетсвом голосов
max_bst.value[department] = employees.filter(emp => emp.total === maxTotal);
const max_bst= computed({
get(){
return getmax(props.usersvotedbest)
}
})
const max_thn= computed({
get(){
let nob = []
props.uservotedthanks.forEach((n)=>{
let ind = nob.findIndex(e=>e.cand_name==n.cand_name)
if (ind==-1){
nob.push({...n, total:1})
}else{
nob[ind].total+=1
}
})
return nob.sort((a,b)=>{return b.total-a.total})
}
})
const groupit=(grpd)=>{
let nob = {}
for(let [key, val] of Object.entries(grpd) ){
if (!(key in nob)){
nob[key]=[]
}
val.forEach((n)=>{
let ind = nob[key].findIndex(elm=>elm.cand_name==n.cand_name)
if (ind>-1){
nob[key][ind].total+=1
}else{
nob[key].push(n)
}
})
nob[key]=nob[key].sort((a,b)=>{return b.total-a.total})
}
return nob
}
const getmax=(data)=>{
let ob = []
data.forEach(el => {
ob.push({...el, total:1})
});
console.log(max_bst);
let grpd = Object.groupBy(ob, ({ department_user }) => department_user);
return groupit(grpd)
}
const thanksleader = computed({get(){
// u
return []
}})
const notvotedbest= computed({
get(){
let logins = props.usersvotedbest.reduce((arr,elm)=>[...arr,elm.voted_user],[])
console.log(props.usersvotedbest);
let grpd = Object.groupBy(props.all_cod.filter(el=>logins.includes(el.login)==false
), ({ department }) => department);
console.log(grpd);
return novoted(grpd)
}})
const notvotedthanks = computed({
get(){
console.log(props.usersvotedbest);
let logins = props.uservotedthanks.reduce((arr,elm)=>[...arr,elm.voted_user],[])
let grpd = Object.groupBy(props.all_cod.filter(el=>logins.includes(el.login)==false), ({ department }) => department);
return novoted(grpd)
}
})
};
const novoted=(grpd)=>{
let nob = {}
for(let [key, val] of Object.entries(grpd) ){
if (!(key in nob)){
nob[key]=[]
}
val.forEach((n)=>{
nob[key].push(n)
})
nob[key]=nob[key].sort((a,b)=>{return b.total-a.total})
perc_bst = computed(() => Math.round(all_voted_bst.value.length / all_cod.value.length * 100))
}
return nob
}
// const getNotVoted = () => {
// clearAxios.get(`/api/vote/getnotvotethn/`).then((data) => {
// let not_voted_thn = data.data;
// result_thn.value = Object.groupBy(not_voted_thn, ({ department }) => department);
// });
// clearAxios.get(`/api/vote/getnotvotebst/`).then((data) => {
// let not_voted_bst = data.data;
// result_bst.value = Object.groupBy(not_voted_bst, ({ department }) => department);
// });
// };
getPercAndWin();
getNotVoted();
// const getPercAndWin = () => {
// clearAxios.get(`/api/vote/getthanks/`).then((data) => {
// all_voted_thn = data.data;
// let max_total = Math.max(...all_voted_thn.map(item => item.total));
// max_thn.value = all_voted_thn.filter(item => item.total === max_total).map(item => item.cand_name)
// });
// clearAxios.get(`api/vote/get_for_thn/?login=${account_login}`).then((data) => {
// all_cod.value = data.data;
// });
// clearAxios.get(`/api/vote/getbest/`).then((data) => {
// all_voted_bst.value = data.data;
// // Групировка по департаметам
// const groupedEmployees = {}
// all_voted_bst.value.forEach(item => {
// const { department_user, cand_name, total } = item;
// if (!groupedEmployees[department_user]) {
// groupedEmployees[department_user] = [];
// }
// groupedEmployees[department_user].push({ name: cand_name, total });
// });
// // Нахождение лучших сотрудников в каждом департаменте
// for (const department in groupedEmployees) {
// const employees = groupedEmployees[department];
// // Поиск максимального количества голосов
// const maxTotal = Math.max(...employees.map(emp => emp.total));
// // Фильтрация сотрудников с максимальным количетсвом голосов
// max_bst.value[department] = employees.filter(emp => emp.total === maxTotal);
// }
// });
// console.log(max_bst);
// };
// perc_bst = computed(() => Math.round(all_voted_bst.value.length / all_cod.value.length * 100))
// getPercAndWin();
// getNotVoted();
return {
max_thn,
max_bst,
perc_bst,
perc_best,
result_thn,
result_bst,
perc_thanks,
notvotedthanks,
notvotedbest
}
}
@@ -178,7 +276,7 @@ export default {
.scroll-leaders {
overflow-y: scroll;
height: 95px;
height: 125px;
}
.scroll-window {
@@ -186,7 +284,5 @@ export default {
height: 378px;
}
.perc-voted {
font-size: 1.2em;
}
</style>
+82 -61
View File
@@ -1,79 +1,92 @@
<template>
<v-form @submit="voteSend">
<v-card id="scroll-window-chekbox" height="300" elevation="0">
<v-form @submit="voteSend" ref="vot" >
<v-card id="scroll-window-chekbox" :height="heightel" elevation="0">
<!-- Форма голосования -->
<v-virtual-scroll :items="vote_data" :item-height="40">
<v-virtual-scroll :items="persons">
<template v-slot:default="{ item }">
<v-checkbox v-model="vote" :id="item.fio" :value="item.fio" :label="item.fio" required />
<v-checkbox hide-details="true" v-model="vote" :id="item.fio" :value="item.fio" :label="item.fio" required />
</template>
</v-virtual-scroll>
</v-card>
<v-card-actions class="justify-center vote-button-back">
<v-dialog max-width="500">
<template v-slot:activator="{ props: activatorProps }">
<v-btn variant="elevated" v-bind="activatorProps" color="teal-darken-1"
@click="approveCandidate">Подтвердить выбор</v-btn>
</template>
<template v-slot:default="{ isActive }">
<v-card class="justify-center align-center">
<v-card-title>Вы подтверждаете выбор?</v-card-title>
<v-card-text>После подтверждения внесение измений станет невозможным.</v-card-text>
<p>Выбранный кандидат</p>
<v-card-title v-if="approve_name">{{ approve_name }}</v-card-title>
<v-card-title v-else>Кандидат не выбран повторите голосование</v-card-title>
<v-col class="d-flex flex-rows justify-center align-center" cols="12">
<v-col cols="2">
<v-btn v-if="approve_name" variant="elevated" color="green-darken-1"
@click="voteSend">ДА</v-btn>
<v-btn v-else variant="elevated" color="green-darken-1" @click="voteSend"
disabled>ДА</v-btn>
</v-col>
<v-col cols="2">
<v-btn variant="elevated" color="red-darken-1"
@click="isActive.value = false">НЕТ</v-btn>
</v-col>
<v-dialog max-width="500" v-model="dialog">
<!-- <template v-slot:activator>
</template> -->
<template v-slot:default>
<v-card class="justify-center align-center">
<v-card-title>Вы подтверждаете выбор?</v-card-title>
<v-card-text>После подтверждения внесение измений станет невозможным.</v-card-text>
<p>Выбранный кандидат</p>
<v-card-title v-if="approve_name">{{ approve_name }}</v-card-title>
<v-card-title v-else>Кандидат не выбран повторите голосование</v-card-title>
<v-col class="d-flex flex-rows justify-center align-center" cols="12">
<v-col cols="2">
<v-btn v-if="approve_name" variant="elevated" color="green-darken-1"
@click="voteSend">ДА</v-btn>
<v-btn v-else variant="elevated" color="green-darken-1" @click="voteSend"
disabled>ДА</v-btn>
</v-col>
</v-card>
</template>
</v-dialog>
</v-card-actions>
<v-col cols="2">
<v-btn variant="elevated" color="red-darken-1"
@click="dialog = false">НЕТ</v-btn>
</v-col>
</v-col>
</v-card>
</template>
</v-dialog>
</v-form>
</template>
<script scope>
import { ref } from "vue";
import { clearAxios } from "@/utils/axios-api";
import { ref, computed } from "vue";
import { clearAxios, axiosApiInstance } from "@/utils/axios-api";
import { useAccountStore } from '@/store/AccountStore';
import Vote from "@/views/Vote.vue";
export default {
props: ['type_fetch'],
setup(props) {
let account_login = useAccountStore().user.login;
let department_id = useAccountStore().user.id_dict_department;
let department_name = useAccountStore().user.department
let type_fetch = props.type_fetch;
props: {type_fetch:{type:String, default:'best'},
persons:{
type:Array,
default:()=>[]
},
myrealdep:{
type:Object,
default:()=>{}
}
},
setup(props, {emit}) {
let account_login = useAccountStore();
// let department_id = useAccountStore().user.id_dict_department;
// let department_name = useAccountStore().user.department
// let type_fetch = props.type_fetch;
const dialog=ref(false)
let vote = ref();
let get_address = ref();
// let get_address = ref();
let send_address = ref();
let vote_data = ref([]);
// let vote_data = ref([]);
let approve_name = ref();
let aproveFalseMessage = ref();
if (type_fetch == "thn") {
get_address = `api/vote/get_for_thn/?login=${account_login}`;
if (props.type_fetch == "thanks") {
send_address = `api/vote/setthanks/`;
} else if (type_fetch == "bst") {
get_address = `api/vote/get_for_bst/?login=${account_login}&dep=${department_id}`;
} else if (props.type_fetch == "best") {
send_address = `api/vote/setbest/`;
}
const getVotesData = () => {
clearAxios.get(get_address).then((data) => {
vote_data.value = data.data;
});
};
// const getVotesData = () => {
// clearAxios.get(get_address).then((data) => {
// vote_data.value = data.data;
// });
// };
const approveCandidate = () => {
if (vote.value === 'False' || vote.value === '') {
@@ -84,34 +97,42 @@ export default {
}
dialog.value=true
}
const voteSend = () => {
window.location.reload();
clearAxios.post(send_address, {
console.log(vote.value);
axiosApiInstance.post(send_address, {
cand_name_id: vote.value,
department_user: department_name,
voted_user: account_login
// department_user: props.myrealdep.department,
},
{
headers: {
'Content-Type': 'application/json'
}
}
);
).then(res=>
{
dialog.value=false
window.location.reload()
});
};
getVotesData();
// getVotesData();
const vot = ref(null)
const heightel = computed(()=>!!vot.value?vot.value.clientHeight:300)
return {
vot,
heightel,
approveCandidate,
voteSend,
vote_data,
// vote_data,
vote,
approve_name,
aproveFalseMessage,
dialog
}
},
+6 -1
View File
@@ -141,12 +141,17 @@ const routes = [
},
},
{
path: "/vote",
name: "Vote",
component: () =>
import("@/views/Vote.vue")
},
{
path: "/votehomepage",
name: "VoteHomePage",
component: () =>
import("@/views/VoteHomePage.vue")
},
],
},
];
+51 -18
View File
@@ -2,7 +2,7 @@ import {useAccountStore} from '@/store/AccountStore'
import axios from "axios";
const spravURL = 'http://10.252.44.33/accounting6/images/photo/'
const spravURLBase = 'http://10.252.44.33/accounting6/'
const baseURL = process.env.NODE_ENV == 'development'? 'http://127.0.0.1:8000/': `http://${window.location.host}/`;
const baseURL = process.env.NODE_ENV === 'development'? 'http://127.0.0.1:8000/': `http://${window.location.host}/`;
const baseWS = process.env.NODE_ENV == 'development'? 'ws://127.0.0.1:8000/': `ws://${window.location.host}/`;
// const baseURL = process.env.NODE_ENV == 'development'? 'http://127.0.0.1:8000/': `http://10.252.44.60:9965/`;
// const baseWS = process.env.NODE_ENV == 'development'? 'ws://127.0.0.1:8000/': `ws://10.252.44.60:9966/`;
@@ -17,18 +17,18 @@ async function refreshToken() {
const result = await axios.post('/api/accounts/token/refresh/', {refresh}, {
baseURL
})
if (result.config.data) localStorage.setItem('refresh', JSON.parse(result.config.data).refresh);
localStorage.setItem('access', result.data.access)
return result.data.access;
}
catch(e) {
const accountStore = useAccountStore()
catch(e) {
const accountStore = useAccountStore()
accountStore.logout()
accountStore.cod2user.value=false
return Promise.reject(e);
}
}
@@ -46,7 +46,7 @@ axiosApiInstance.defaults.headers.common['Authorization'] = `Bearer ${localStora
axiosApiInstance.interceptors.request.use(config => {
const access = localStorage.getItem('access');
if (access) {
config.headers = {
config.headers = {
'Authorization': `Bearer ${access}`,
}
}
@@ -63,30 +63,63 @@ async error => {
const originalRequest = error.config;
if ((error.response.status === 401 || error.response.status === 403) && !originalRequest._retry) {
originalRequest._retry = true;
try {
const token = await refreshToken();
axiosApiInstance.defaults.headers.common['Authorization'] = `Bearer ${token}`;
axiosApiInstance.defaults.headers.common['Authorization'] = `Bearer ${token}`;
if (originalRequest.data){
originalRequest.data = JSON.parse(originalRequest.data); }
originalRequest.data = JSON.parse(originalRequest.data); }
return axiosApiInstance(originalRequest);
} catch(e) {
//
} catch(e) {
//
// if (window.location.pathname!='/auth') window.location.reload()
// window.location.reload()
return Promise.reject(error);
}
}
return Promise.reject(error);
})
async function getVotes(status) {
try {
const response = await axiosApiInstance.get(`/api/vote/getvotes?status=${status}`,
// {
// params: {
// status,
// }
// }
);
return response.data;
} catch (error) {
console.error('Ошибка запроса голосования:', error);
throw error;
}
}
export { axiosApiInstance, clearAxios, baseURL,spravURL, spravURLBase, baseWS }
getVotes('completed')
.then(data => {
console.log('Завершённые голосования:', data);
})
.catch(err => {
console.error('Ошибка:', err);
});
getVotes('active')
.then(data => {
console.log('Активные голосования:', data);
})
.catch(err => {
console.error('Ошибка:', err);
});
export { axiosApiInstance, clearAxios, baseURL,spravURL, spravURLBase, baseWS, getVotes }
+154 -241
View File
@@ -1,101 +1,55 @@
<template>
<v-row justify="center" class="d-flex align-start h-100">
<v-col cols="12" class="d-flex align-center justify-center vote-main-title pa-0 ma-0">
<v-col cols="6" class="pb-0 mb-0">ВЫБИРАЕМ ЛУЧШИХ СОТРУДНИКОВ 2024</v-col>
<v-row justify="center" class="d-flex align-start h-100" :style="{ backgroundImage: `url('${bgImage}')`, backgroundSize: 'cover' }">
<v-col cols="12" class="d-flex align-center justify-center text-h5 py-3 ma-0">
<!-- <v-col class="pb-0 mb-0 text-center">ТЕКУЩИЕ ГОЛОСОВАНИЯ</v-col> -->
</v-col>
<!-- Голосование Лучший сотрудник -->
<v-col cols="12" justify="center" class="d-flex vote-card-container">
<v-col cols="6" justify="center" align="center">
<div class="flip-card" :class="{ 'flipped': isFlipped1 }">
<div class="flip-card-inner">
<div v-if="voted_bst" class="flip-card-front">
<!-- Передняя сторона карточки -->
<v-card class="justify-center elevation-24" width="500" height="510" variant="elevated">
<v-card-title class="vote-title">ЛУЧШИЙ В ОТДЕЛЕ</v-card-title>
<div class="justify-center">
<div>
<v-card class="vote-card-information" variant="flat">
<v-card-text
class="justify-center align-center vote-card-information-title">
<p>ВЫ УЖЕ ПРОГОЛОСОВАЛИ.</p>
<p>СПАСИБО!</p>
</v-card-text>
</v-card>
</div>
</div>
<!-- Кнопка активации поворота КОНЕЦ-->
</v-card>
</div>
<div v-else class="flip-card-front" @click="toggleFlip1">
<!-- Передняя сторона карточки -->
<v-card class="justify-center elevation-24" width="500" height="510" variant="elevated">
<v-card-title class="vote-title">ЛУЧШИЙ В ОТДЕЛЕ</v-card-title>
<div class="justify-center">
<div>
<v-card class="vote-card-information" variant="flat">
<v-card-text class="justify-center align-center
vote-card-information-title">
Выберите сотрудника,<br>
который, на Ваш взгляд,<br>
внес наибольший вклад в результат работы<br>
Отдела в 2024 году
</v-card-text>
</v-card>
</div>
<v-btn :height="100" variant="flat" type="button">
<v-img :width="100" cover src="@/assets/click3.gif"></v-img>
</v-btn>
</div>
<!-- Кнопка активации поворота КОНЕЦ-->
</v-card>
</div>
<!-- Передняя сторона карточки КОНЕЦ-->
<div class="flip-card-back">
<!-- Задняя сторона карточки -->
<v-card class="justify-center elevation-24" width="500" height="510">
<v-card-title class="vote-title">
МОЙ КОЛЛЕГА САМЫЙ ЛУЧШИЙ
</v-card-title>
<v-card-text>
<vote-form :type_fetch="'bst'" />
</v-card-text>
<!-- Кнопка активации поворота -->
<v-card-actions class="justify-center vote-button-back">
<v-btn @click="toggleFlip1" variant="elevated" color="teal-darken-1"
type="button">назад</v-btn>
</v-card-actions>
<!-- Кнопка активации поворота КОНЕЦ-->
</v-card>
</div>
</div>
</div>
<!-- Задняя сторона карточки КОНЕЦ-->
</v-col>
<!-- Голосование Лучший сотрудник КОНЕЦ-->
<!-- Голосование Спасибо -->
<v-col cols="6" justify="center" align="center">
<v-col cols="12" justify="center" align="center">
<div class="flip-card" :class="{ 'flipped': isFlipped2 }">
<div class="flip-card-inner">
<div v-if="voted_thn" class="flip-card-front">
<div v-if="!uservotedthanks" class="flip-card-front">
<!-- Передняя сторона карточки -->
<v-card class="justify-center elevation-24" width="500" height="510" variant="elevated">
<v-card-title class="vote-title">ХОЧУ СКАЗАТЬ СПАСИБО</v-card-title>
<v-card-title class="text-h5 my-2">ЛУЧШИЙ НОВОГОДНИЙ КОСТЮМ</v-card-title>
<div class="justify-center">
<div>
<v-card class="vote-card-information" variant="flat">
<v-card-text
class="justify-center align-center vote-card-information-title">
<v-card-text class="justify-center align-center vote-card-information-title">
<p>ВЫ УЖЕ ПРОГОЛОСОВАЛИ.</p>
<p>СПАСИБО!</p>
</v-card-text>
<v-dialog >
<template v-slot:activator="{ props: activatorProps }">
<span class="text-h5">Проголосовало</span> <span
v-bind="admin_panel ? activatorProps : ''" class="text-green text-h4"
:class="{ 'cursor-pointer': admin_panel }">
{{
Math.round((voteresults.uservotedthanks.length * 100 / (allsorted.length + 1)).toFixed(2)) }}%</span>
</template>
<template v-slot:default="{ isActive }">
<v-row justify="center" class="h-100 admin-vote">
<v-card width="1500" height="900">
<vote-admin :usersvotedbest="voteresults.usersvotedbest"
:uservotedthanks="voteresults.uservotedthanks"
:all_cod="allsorted" />
<v-row justify="center" align="center">
<v-btn color="teal-darken-1"
@click="isActive.value = false">ЗАКРЫТЬ</v-btn>
</v-row>
</v-card>
</v-row>
</template>
</v-dialog>
</v-card>
</div>
</div>
<!-- Кнопка активации поворота КОНЕЦ-->
@@ -103,27 +57,54 @@
</div>
<div v-else class="flip-card-front" @click="toggleFlip2">
<!-- Передняя сторона карточки -->
<v-card class="justify-center elevation-24" width="500" height="510" variant="elevated">
<v-card-title class="vote-title ">ХОЧУ СКАЗАТЬ СПАСИБО</v-card-title>
<div class="justify-center">
<v-card
<div>
<v-card class="vote-card-information" variant="flat">
<v-card-text class="justify-center align-center
vote-card-information-title">
Выберите сотрудника <br>
(не из Вашего отдела),<br>
которому Вы лично готовы обьявить<br>
благодарность по итогам работы в 2024 году
</v-card-text>
</v-card>
class="elevation-24 d-flex align-сenter justify-space-between flex-column" width="500" height="510" variant="elevated" >
<div class="">
<div class="text-h5 my-2">ЛУЧШИЙ НОВОГОДНИЙ КОСТЮМ</div>
<div class="mt-4 ">
<div class=" align-center font-weight-bold">
Выберите сотрудника,
костюм которого вам больше всего понравился
</div>
</div>
</div>
<div class="mt-4">
<v-btn :height="100" variant="flat" type="button">
<v-img :width="100" cover src="@/assets/click3.gif"></v-img>
</v-btn>
</div>
<div align="center" class="">
<v-dialog >
<template v-slot:activator="{ props: activatorProps }">
<span class="text-h5">Проголосовало</span> <span
v-bind="admin_panel ? activatorProps : ''" class="text-green text-h4"
:class="{ 'cursor-pointer': admin_panel }">
{{
Math.round((voteresults.uservotedthanks.length * 100 / (allsorted.length + 1)).toFixed(2)) }}%</span>
</template>
<template v-slot:default="{ isActive }">
<v-row justify="center" class="h-100 admin-vote">
<v-card width="1500" height="900">
<vote-admin :usersvotedbest="voteresults.usersvotedbest"
:uservotedthanks="voteresults.uservotedthanks"
:all_cod="allsorted" />
<v-row justify="center" align="center">
<v-btn color="teal-darken-1"
@click="isActive.value = false">ЗАКРЫТЬ</v-btn>
</v-row>
</v-card>
</v-row>
</template>
</v-dialog>
<div class="my-4"><count-down /></div>
</div>
<!-- Кнопка активации поворота КОНЕЦ-->
</v-card>
@@ -131,17 +112,20 @@
<!-- Передняя сторона карточки КОНЕЦ-->
<!-- Задняя сторона карточки -->
<div class="flip-card-back">
<v-card class="justify-center elevation-24" width="500" height="510" variant="elevated">
<v-card-title class="vote-title ">
ХОЧУ СКАЗАТЬ СПАСИБО
</v-card-title>
<v-card-text>
<vote-form :type_fetch="'thn'" />
</v-card-text>
<v-card class="d-flex align-сenter justify-space-between elevated-24 flex-column" width="500" height="510" variant="elevated">
<div class="text-h5 my-2">ЛУЧШИЙ НОВОГОДНИЙ КОСТЮМ</div>
<!-- <v-card-text class=""> -->
<vote-form class="flex-grow-1 " ref="voteform" :type_fetch="'thanks'"
:persons="allsorted"
:myrealdep="myrealdep" @voted="toggleFlip2" />
<!-- </v-card-text> -->
<!-- Кнопка активации поворота -->
<v-card-actions class="justify-center vote-button-back">
<v-btn @click="toggleFlip2" variant="elevated" color="teal-darken-1"
<v-card-actions class="justify-center">
<v-btn @click="toggleFlip2" variant="elevated" color="red-darken-4"
type="button">назад</v-btn>
<v-btn variant="elevated" color="teal-darken-1"
@click="approveCandidate">Подтвердить выбор</v-btn>
</v-card-actions>
<!-- Кнопка активации поворота КОНЕЦ-->
</v-card>
@@ -151,80 +135,19 @@
</div>
</v-col>
</v-col>
<v-col cols="12" class="d-flex justify-center align-end ">
<h1>ПРИНЯЛИ УЧАСТИЕ В ГОЛОСОВАНИИ</h1>
</v-col>
<v-col cols="12" class="d-flex justify-center align-end pa-0">
<v-col v-if="admin_panel" justify="center" align="center" cols="6" class=" pa-0">
<v-dialog>
<template v-slot:activator="{ props: VoteAdmin }">
<v-btn variant="transparent" v-bind="VoteAdmin"
class="procent-card-font pa-0"><perc-bst /></v-btn>
</template>
<template v-slot:default="{ isActive }">
<v-row justify="center" class="h-100 admin-vote">
<v-card width="1500" height="900">
<vote-admin />
<v-row justify="center" align="center">
<v-btn variant="elevated" color="teal-darken-1"
@click="isActive.value = false">ЗАКРЫТЬ</v-btn>
</v-row>
</v-card>
</v-row>
</template>
</v-dialog>
</v-col>
<v-col v-else justify="center" align="center" cols="6" class="procent-card-font pa-0">
<perc-bst />
</v-col>
<v-col v-if="admin_panel" justify="center" align="center" cols="6" class=" pa-0">
<v-dialog>
<template v-slot:activator="{ props: VoteAdmin }">
<v-btn variant="transparent" v-bind="VoteAdmin"
class="procent-card-font pa-0"><perc-thn /></v-btn>
</template>
<template v-slot:default="{ isActive }">
<v-row justify="center" class="h-100 admin-vote">
<v-card width="1500" height="900">
<vote-admin />
<v-row justify="center" align="center">
<v-btn variant="elevated" color="teal-darken-1"
@click="isActive.value = false">ЗАКРЫТЬ</v-btn>
</v-row>
</v-card>
</v-row>
</template>
</v-dialog>
</v-col>
<v-col v-else justify="center" align="center" cols="6" class="procent-card-font pa-0">
<perc-thn />
</v-col>
</v-col>
<v-col cols="12" class="d-flex justify-center align-start pa-0">
<v-col justify="center" align="center" cols="6" class="vote-cards_cell ">
<count-down />
</v-col>
</v-col>
<!-- Голосование Спасибо КОНЕЦ-->
</v-row>
</template>
<script>
import { ref } from "vue";
import { clearAxios } from "@/utils/axios-api";
import { ref, computed } from "vue";
import { clearAxios, axiosApiInstance } from "@/utils/axios-api";
import VoteForm from '@/components/vote/VoteForm.vue';
import PercBst from '@/components/vote/PercBst.vue';
import PercThn from '@/components/vote/PercThn.vue';
import bgImage from '@/assets/bg/bg.png';
import VoteAdmin from '@/components/vote/VoteAdmin.vue';
import CountDown from '@/components/CountDown.vue';
import { useAccountStore } from '@/store/AccountStore';
let admin_panel = ref(false);
let account_login = useAccountStore().user.login;
let account_login = useAccountStore();
export default {
@@ -232,43 +155,31 @@ export default {
components: {
VoteForm,
CountDown,
PercBst,
PercThn,
VoteAdmin,
},
setup() {
const voteform=ref(null)
const voted_best = ref([])
const full_list_pers = ref([])
let votedListBst = ref([]);
let votedListThn = ref([]);
let voted_thn = ref(false);
let voted_bst = ref(false);
const myrealdep = ref({ id_dict_department: 0, id: 0 })
const uservoted = ref([true, true])
const allcod = ref([])
const isFlipped1 = ref(false);
const isFlipped2 = ref(false);
const voteresults = ref({ usersvotedbest: [], uservotedthanks: [] })
const isVoted = () => {
clearAxios.get(`/api/vote/getthanks/`).then((data) => {
votedListThn = data.data;
let finded_thn = votedListThn.find(({ voted_user }) => voted_user === account_login)
if (finded_thn.voted_user === account_login) {
voted_thn.value = true;
}
});
clearAxios.get(`/api/vote/getbest/`).then((data) => {
votedListBst = data.data;
let finded_bst = votedListBst.find(({ voted_user }) => voted_user === account_login)
if (finded_bst.voted_user === account_login) {
voted_bst.value = true;
}
});
}
axiosApiInstance.get('/api/vote/getvoteinfo/').then((res) => {
allcod.value = res.data.allcod
myrealdep.value = allcod.value.find(e => e.login === account_login.user.login)
voteresults.value = res.data.voteresults
})
const toggleFlip1 = () => {
isFlipped1.value = !isFlipped1.value;
@@ -278,12 +189,54 @@ export default {
isFlipped2.value = !isFlipped2.value;
}
if (account_login == '9966-00-134' || account_login == '9966-00-141' || account_login == '9966-00-011') {
admin_panel = true;
if (['9966-00-134', '9966-00-141', '9966-00-011', '9966-00-125'].includes(account_login.user.login)) {
admin_panel.value = true;
}
const allsorted = computed({
get() {
let all = allcod.value.filter(e => e.id !== myrealdep.value.id)
return all.sort((a, b) => {
if (b.fio > a.fio) return -1
else if (b.fio < a.fio) return 1
return 0
})
}
})
isVoted();
const uservotedthanks = computed({
get() {
let ind = voteresults.value.uservotedthanks.findIndex(e => e.voted_user === account_login.user.login)
if (ind > -1) return false
return true
}
})
const uservotedbest = computed({
get() {
let ind = voteresults.value.usersvotedbest.findIndex(e => e.voted_user === account_login.user.login)
if (ind > -1) return false
return true
}
})
const mydepartment = computed({
get() {
let ac = allcod.value.filter(e => e.id_dict_department === myrealdep.value.id_dict_department && e.id != myrealdep.value.id)
return ac.sort((a, b) => {
if (b.fio > a.fio) return -1
else if (b.fio < a.fio) return 1
return 0
})
}
})
const approveCandidate=()=>{
if (voteform.value!==null) voteform.value.approveCandidate()
}
return {
approveCandidate,
voteform,
myrealdep,
allsorted,
mydepartment,
isFlipped1,
toggleFlip1,
isFlipped2,
@@ -292,6 +245,11 @@ export default {
admin_panel,
voted_bst,
voted_thn,
uservotedthanks,
uservotedbest,
voteresults,
bgImage
};
},
};
@@ -301,8 +259,6 @@ export default {
height: 600px !important;
}
/* .flip-card {} */
.flip-card-inner {
display: flex;
position: relative;
@@ -325,57 +281,14 @@ export default {
transform: rotateY(-180deg);
}
.vote-card-title {
background-color: rgba(255, 255, 255, 0.1);
color: white;
font-size: 1.7em;
}
.vote-button {
margin-top: 57px;
}
.vote-cards_cell {
height: 2% !important;
}
.procent-card-font {
font-size: 5em;
color: #008000;
}
.card-count {
font-size: 3em;
}
.you-voted {
background-color: rgba(182, 182, 182, 0.4);
color: #ffff;
border-radius: 5px;
}
.vote-card-information {
background-color: rgba(255, 255, 255, 0.7);
margin-top: 20%;
width: 460px;
height: 200px;
}
.vote-card-information-title {
font-size: 1.2em;
}
.vote-title {
font-size: 1.8em;
font-weight: 400;
}
.vote-main-title {
font-size: 2.3em;
font-weight: 400;
}
</style>
</style>
+325
View File
@@ -0,0 +1,325 @@
<template>
<v-container>
<v-stepper v-model="step" editable>
<v-stepper-header>
<v-stepper-item :complete="step > 0" step="1">Основная информация</v-stepper-item>
<v-divider></v-divider>
<v-stepper-item :complete="step > 1" step="2">Создание опроса</v-stepper-item>
<v-divider></v-divider>
<v-stepper-item :complete="step > 2" step="3">Настройка ответов</v-stepper-item>
<v-divider></v-divider>
<v-stepper-item step="4">Подтверждение</v-stepper-item>
</v-stepper-header>
<v-stepper-window>
<!-- Основная информация -->
<v-stepper-window-item step="1">
<v-card flat>
<v-card-title>Основная информация</v-card-title>
<v-card-text>
<v-text-field v-model="form.title" label="Название голосования" outlined></v-text-field>
<v-textarea v-model="form.description" label="Описание" outlined></v-textarea>
<v-text-field
:placeholder="form.startDate.toLocaleDateString()"
:value="form.startDate.toLocaleDateString()"
color="teal-darken-4"
label="Дата начала"
persistentPlaceholder
readonly
>
<v-menu activator="parent">
<v-date-picker
v-model="form.startDate"
color="teal-darken-4"
hideHeader
hideWeekdays
>
</v-date-picker>
</v-menu>
<v-btn flat icon style="background-color: transparent">
<v-icon>mdi-calendar</v-icon>
</v-btn>
</v-text-field>
<v-text-field
:placeholder="form.endDate.toLocaleDateString()"
:value="form.endDate.toLocaleDateString()"
color="teal-darken-4"
label="Дата окончания"
persistentPlaceholder
readonly
>
<v-menu activator="parent">
<v-date-picker
v-model="form.endDate"
color="teal-darken-4"
hideHeader
hideWeekdays
>
</v-date-picker>
</v-menu>
<v-btn flat icon style="background-color: transparent">
<v-icon>mdi-calendar</v-icon>
</v-btn>
</v-text-field>
</v-card-text>
<v-card-actions>
<v-btn color="teal-darken-4" @click="step = 1" size="medium">Далее</v-btn>
</v-card-actions>
</v-card>
</v-stepper-window-item>
<!-- Создание опроса -->
<v-stepper-window-item step="2">
<v-card flat>
<v-card-title>Создание опроса</v-card-title>
<v-card-text>
<div v-for="(question, index) in form.questions" :key="index" class="mb-4">
<v-text-field
v-model="question.text"
:label="'Вопрос ' + (index + 1)"
outlined
></v-text-field>
<v-file-input
v-model="question.image"
accept="image/*"
label="Картинка для вопроса"
outlined
></v-file-input>
<v-select
v-model="question.type"
:items="questionTypes"
label="Тип ответа"
outlined
></v-select>
<v-btn color="error" icon @click="removeQuestion(index)">
<v-icon>mdi-delete</v-icon>
</v-btn>
</div>
<v-btn color="teal-darken-4" @click="addQuestion">Добавить вопрос</v-btn>
</v-card-text>
<v-card-actions>
<v-btn color="teal-darken-4" size="medium" @click="step -= 1">Назад</v-btn>
<v-btn color="teal-darken-4" size="medium" @click="step = 2">Далее</v-btn>
</v-card-actions>
</v-card>
</v-stepper-window-item>
<!-- Настройка ответов -->
<v-stepper-window-item step="3">
<v-card flat>
<v-card-title>
Настройка ответов
<v-select
v-model="currentQuestionIndex"
:items="form.questions.map((q, i) => ({ text: `Вопрос ${i + 1}: ${q.text || 'Без названия'}`, value: i }))"
class="ml-4"
dense
item-title="text"
item-value="value"
label="Выберите вопрос"
outlined
></v-select>
</v-card-title>
<v-card-text>
<div v-if="currentQuestion">
<div v-if="currentQuestion.type === 'Ввести вручную'">
<div
v-for="(answer, index) in currentQuestion.answers"
:key="index"
class="d-flex align-start mb-4"
>
<v-text-field
v-model="answer.text"
:label="'Ответ ' + (index + 1)"
class="mr-4"
outlined
></v-text-field>
<v-file-input
v-model="answer.image"
accept="image/*"
dense
hide-details
label="Картинка"
outlined
></v-file-input>
<v-btn color="error" icon @click="removeAnswer(index)">
<v-icon>mdi-delete</v-icon>
</v-btn>
</div>
<v-btn color="primary" @click="addAnswer">Добавить ответ</v-btn>
</div>
<div v-else>
<v-autocomplete
v-model="currentQuestion.selectedEmployees"
:items="groupedEmployees"
item-title="fio"
item-value="id"
label="Выберите сотрудников"
multiple
outlined
></v-autocomplete>
<div
v-for="(person, index) in currentQuestion.selectedEmployees"
:key="person.id"
class="d-flex align-center mb-4"
>
<v-chip>{{ findEmployeeById(person).fio }}</v-chip>
<v-file-input
v-model="currentQuestion.selectedEmployeeImages[person]"
accept="image/*"
class="ml-4"
dense
hide-details
label="Картинка"
outlined
></v-file-input>
<v-btn color="error" icon @click="removeEmployee(index)">
<v-icon>mdi-delete</v-icon>
</v-btn>
</div>
</div>
</div>
<div v-else>
<p>Выберите вопрос, чтобы добавить ответы.</p>
</div>
</v-card-text>
<v-card-actions>
<v-btn color="teal-darken-4" size="medium" @click="step -= 1">Назад</v-btn>
<v-btn color="teal-darken-4" size="medium" @click="step = 3">Далее</v-btn>
</v-card-actions>
</v-card>
</v-stepper-window-item>
<!-- Подтверждение -->
<v-stepper-window-item step="4">
<v-card flat>
<v-card-title>Подтверждение</v-card-title>
<v-card-text>
<p><strong>Название:</strong> {{ form.title }}</p>
<p><strong>Описание:</strong> {{ form.description }}</p>
<p><strong>Дата начала:</strong> {{ form.startDate.toLocaleDateString() }}</p>
<p><strong>Дата окончания:</strong> {{ form.endDate.toLocaleDateString() }}</p>
<p><strong>Вопросы:</strong></p>
<ul>
<li v-for="(question, index) in form.questions" :key="index" class="mb-4">
<p><strong>Вопрос {{ index + 1 }}:</strong> {{ question.text }} ({{ question.type }})</p>
<div v-if="question.type === 'Ввести вручную' && question.answers.length">
<p><strong>Варианты ответов:</strong></p>
<ul>
<li v-for="(answer, answerIndex) in question.answers" :key="answerIndex">
{{ answer.text }}
</li>
</ul>
</div>
<div v-if="question.type === 'Выбрать сотрудника' && question.selectedEmployees.length">
<p><strong>Выбранные сотрудники:</strong></p>
<ul>
<li
v-for="employeeId in question.selectedEmployees"
:key="employeeId"
>
{{ findEmployeeById(employeeId).fio }}
</li>
</ul>
</div>
</li>
</ul>
</v-card-text>
<v-card-actions>
<v-btn color="teal-darken-4" size="medium" @click="step -= 1">Назад</v-btn>
<v-btn color="teal-darken-4" size="medium" @click="saveVoting">Сохранить</v-btn>
</v-card-actions>
</v-card>
</v-stepper-window-item>
</v-stepper-window>
</v-stepper>
</v-container>
</template>
<script>
import {computed, ref} from "vue";
export default {
setup() {
const step = ref(0);
const form = ref({
title: "",
description: "",
startDate: new Date(),
endDate: new Date(new Date().setDate(new Date().getDate() + 14)),
questions: [],
});
const currentQuestionIndex = ref(0);
const questionTypes = ["Ввести вручную", "Выбрать сотрудника"];
const groupedEmployees = [
{id: 1, fio: "Иван Иванов", department: "Отдел A"},
{id: 2, fio: "Петр Петров", department: "Отдел B"},
];
const currentQuestion = computed(() =>
form.value.questions[currentQuestionIndex.value] || null
);
const findEmployeeById = (id) =>
groupedEmployees.find((employee) => employee.id === id) || {};
const removeEmployee = (index) => {
currentQuestion.value.selectedEmployees.splice(index, 1);
};
const addQuestion = () => {
form.value.questions.push({
text: "",
type: "Ввести вручную",
image: null,
answers: [],
selectedEmployees: [],
selectedEmployeeImages: {},
});
};
const removeQuestion = (index) => {
form.value.questions.splice(index, 1);
if (currentQuestionIndex.value >= form.value.questions.length) {
currentQuestionIndex.value = form.value.questions.length - 1;
}
};
const addAnswer = () => {
if (currentQuestion.value) {
currentQuestion.value.answers.push({text: "", image: null});
}
};
const removeAnswer = (index) => {
if (currentQuestion.value) {
currentQuestion.value.answers.splice(index, 1);
}
};
const saveVoting = () => {
console.log("Голосование сохранено:", form.value);
};
return {
step,
form,
questionTypes,
groupedEmployees,
currentQuestionIndex,
currentQuestion,
addQuestion,
removeQuestion,
addAnswer,
removeAnswer,
findEmployeeById,
removeEmployee,
saveVoting,
};
},
};
</script>
+227
View File
@@ -0,0 +1,227 @@
<template>
<v-container>
<v-toolbar color="transparent">
<v-toolbar-title>Голосования</v-toolbar-title>
<template v-slot:extension>
<v-tabs v-model="currentTab">
<v-tab :key="0" value="current">Текущие голосования</v-tab>
<v-tab :key="1" value="completed">Завершенные голосования</v-tab>
<v-tab :key="2" value="constructor">Создать новое голосование</v-tab>
</v-tabs>
</template>
</v-toolbar>
<v-tabs-window v-model="currentTab">
<!-- Текущие голосования -->
<v-tabs-window-item value="current">
<v-container>
<v-row>
<v-col
v-for="voting in sortedCurrentVotes"
:key="voting.id"
cols="12" lg="3" md="4"
>
<v-card :class="{ 'voted-card': voting.voted }">
<v-card-title class="d-flex justify-space-between">{{ voting.title }}
<v-btn flat size="medium">
<v-icon color="orange-lighten-1">mdi-pencil</v-icon>
</v-btn>
</v-card-title>
<v-card-subtitle>
Окончание: {{ formatDate(voting.endDate) }}
</v-card-subtitle>
<v-card-text>
Осталось: {{ timeRemaining(voting.endDate) }}
</v-card-text>
<v-card-actions class="justify-space-between">
<v-btn
v-if="!voting.voted"
color="teal-darken-4"
size="medium"
@click="openVoteModal(voting)"
>
Проголосовать
</v-btn>
<v-btn v-else color="teal-darken-4" disabled size="medium">Уже проголосовали</v-btn>
<v-btn color="error" @click="deleteVoting(voting.id)" size="medium">
<v-icon>mdi-delete</v-icon>
</v-btn>
</v-card-actions>
</v-card>
</v-col>
</v-row>
</v-container>
</v-tabs-window-item>
<!-- Завершенные голосования -->
<v-tabs-window-item value="completed">
<v-container>
<v-row>
<v-col
v-for="voting in sortedCompletedVotes"
:key="voting.id"
cols="12" lg="3" md="4"
>
<v-card>
<v-card-title>{{ voting.title }}</v-card-title>
<v-card-subtitle>
Завершено: {{ formatDate(voting.endDate) }}
</v-card-subtitle>
<v-card-actions class="justify-space-between">
<v-btn color="teal-darken-4" size="medium" @click="openResultsModal(voting)">
Результаты
</v-btn>
<v-btn color="error" size="medium" @click="deleteVoting(voting.id)">
<v-icon>mdi-delete</v-icon>
</v-btn>
</v-card-actions>
</v-card>
</v-col>
</v-row>
</v-container>
</v-tabs-window-item>
<!-- Конструктор -->
<v-tabs-window-item value="constructor">
<VoteConstructor/>
</v-tabs-window-item>
</v-tabs-window>
<!-- Модальное окно для голосования -->
<v-dialog v-model="voteModal" max-width="600px">
<v-card>
<v-card-title>Голосование: {{ selectedVoting?.title }}</v-card-title>
<v-card-text>
<p>Описание голосования...</p>
</v-card-text>
<v-card-actions>
<v-btn color="primary" @click="submitVote">Проголосовать</v-btn>
<v-btn @click="closeVoteModal">Закрыть</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
<!-- Модальное окно для результатов -->
<v-dialog v-model="resultsModal" max-width="600px">
<v-card>
<v-card-title>Результаты голосования: {{ selectedVoting?.title }}</v-card-title>
<v-card-text>
<p>Здесь отображаются результаты голосования...</p>
</v-card-text>
<v-card-actions>
<v-btn @click="closeResultsModal">Закрыть</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
</v-container>
</template>
<script>
import {computed, ref} from "vue";
import VoteConstructor from "@/views/VoteConstructor.vue";
export default {
components: {VoteConstructor},
setup() {
const currentTab = ref("current");
const votes = ref([
{
id: 1,
title: "Голосование 1",
endDate: new Date(new Date().getTime() + 600000), // 10 минут
voted: false,
},
{
id: 2,
title: "Голосование 2",
endDate: new Date(new Date().getTime() - 600000), // Уже завершено
voted: true,
},
{
id: 3,
title: "Голосование 3",
endDate: new Date(new Date().getTime() + 3600000), // 1 час
voted: true,
},
]);
const voteModal = ref(false);
const resultsModal = ref(false);
const selectedVoting = ref(null);
const sortedCurrentVotes = computed(() => {
return votes.value
.filter((v) => new Date(v.endDate) > new Date())
.sort((a, b) => new Date(a.endDate) - new Date(b.endDate));
});
const sortedCompletedVotes = computed(() => {
return votes.value
.filter((v) => new Date(v.endDate) <= new Date())
.sort((a, b) => new Date(b.endDate) - new Date(a.endDate));
});
const timeRemaining = (endDate) => {
const now = new Date();
const diff = new Date(endDate) - now;
return diff > 0 ? `${Math.floor(diff / 60000)} минут` : "Завершено";
};
const formatDate = (date) => new Date(date).toLocaleString();
const openVoteModal = (voting) => {
selectedVoting.value = voting;
voteModal.value = true;
};
const closeVoteModal = () => {
voteModal.value = false;
selectedVoting.value = null;
};
const submitVote = () => {
selectedVoting.value.voted = true;
closeVoteModal();
};
const openResultsModal = (voting) => {
selectedVoting.value = voting;
resultsModal.value = true;
};
const closeResultsModal = () => {
resultsModal.value = false;
selectedVoting.value = null;
};
const deleteVoting = (id) => {
votes.value = votes.value.filter((v) => v.id !== id);
};
return {
currentTab,
votes,
sortedCurrentVotes,
sortedCompletedVotes,
voteModal,
resultsModal,
selectedVoting,
timeRemaining,
formatDate,
openVoteModal,
closeVoteModal,
submitVote,
openResultsModal,
closeResultsModal,
deleteVoting,
};
},
};
</script>
<style>
.voted-card {
opacity: 0.6;
}
</style>