diff --git a/.gitignore b/.gitignore index 21ae74341..6038ab190 100644 --- a/.gitignore +++ b/.gitignore @@ -4,4 +4,5 @@ env/ /src/*/__pycache__/ /src/*/migrations/ /src/front/public/Tiles/ -/src/front/node_modules/ \ No newline at end of file +/src/front/node_modules/ +.vscode/ \ No newline at end of file diff --git a/src/back/.gitignore b/src/back/.gitignore index ff9ed2a56..06d57e9ee 100644 --- a/src/back/.gitignore +++ b/src/back/.gitignore @@ -8,4 +8,5 @@ portal/settings.py /front/node_modules/ *.sqlite3 /media/ -/static/ \ No newline at end of file +/static/ +*.env \ No newline at end of file diff --git a/src/back/portal/.envfish b/src/back/portal/.envfish new file mode 100644 index 000000000..3da11e43d --- /dev/null +++ b/src/back/portal/.envfish @@ -0,0 +1,6 @@ +ENGINE=django.db.backends.mysql +DBNAME = accounting +USER = +PASSWORD= +HOST=127.0.0.1 +PORT=3306 \ No newline at end of file diff --git a/src/back/portal/ds_FISH.py b/src/back/portal/ds_FISH.py deleted file mode 100644 index 455e9c99c..000000000 --- a/src/back/portal/ds_FISH.py +++ /dev/null @@ -1,8 +0,0 @@ -class Settings(): - def __init__(self) -> None: - self.secret_key='' - self.redis_hosts = [] - self.db = { - } - - pass diff --git a/src/back/portal/settings.py b/src/back/portal/settings.py new file mode 100644 index 000000000..207689378 --- /dev/null +++ b/src/back/portal/settings.py @@ -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' + ]), + } +} \ No newline at end of file diff --git a/src/back/r.txt b/src/back/r.txt index b8c98b9db..7946e77f4 100644 Binary files a/src/back/r.txt and b/src/back/r.txt differ diff --git a/src/back/vote/admin.py b/src/back/vote/admin.py index e59747e9c..d202aa96d 100644 --- a/src/back/vote/admin.py +++ b/src/back/vote/admin.py @@ -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) \ No newline at end of file +admin.site.register(Vote) diff --git a/src/back/vote/apps.py b/src/back/vote/apps.py index 61738946f..2eea978e0 100644 --- a/src/back/vote/apps.py +++ b/src/back/vote/apps.py @@ -4,4 +4,5 @@ from django.apps import AppConfig class VoteConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'vote' + verbose_name = 'Голосование' diff --git a/src/back/vote/models.py b/src/back/vote/models.py index f107cbe9d..a4e3ca20d 100644 --- a/src/back/vote/models.py +++ b/src/back/vote/models.py @@ -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) \ No newline at end of file + 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}' \ No newline at end of file diff --git a/src/back/vote/serializers.py b/src/back/vote/serializers.py index 841d8c498..6716093c5 100644 --- a/src/back/vote/serializers.py +++ b/src/back/vote/serializers.py @@ -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() \ No newline at end of file diff --git a/src/back/vote/urls.py b/src/back/vote/urls.py index dd966a677..77389fdc3 100644 --- a/src/back/vote/urls.py +++ b/src/back/vote/urls.py @@ -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'), ] diff --git a/src/back/vote/views.py b/src/back/vote/views.py index 770678c70..e98246257 100644 --- a/src/back/vote/views.py +++ b/src/back/vote/views.py @@ -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) \ No newline at end of file diff --git a/src/front/package-lock.json b/src/front/package-lock.json index cdceec982..5c08c4055 100644 --- a/src/front/package-lock.json +++ b/src/front/package-lock.json @@ -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", diff --git a/src/front/package.json b/src/front/package.json index 717ffa632..5cc2ad8ca 100644 --- a/src/front/package.json +++ b/src/front/package.json @@ -1,6 +1,6 @@ { "name": "front", - "version": "0.0.75", + "version": "0.0.82", "scripts": { "dev": "vite", "build": "vite build", diff --git a/src/front/src/assets/best_employee.jpg b/src/front/src/assets/best_employee.jpg deleted file mode 100644 index 06c94c186..000000000 Binary files a/src/front/src/assets/best_employee.jpg and /dev/null differ diff --git a/src/front/src/assets/bg/bg.png b/src/front/src/assets/bg/bg.png new file mode 100644 index 000000000..d5248af88 Binary files /dev/null and b/src/front/src/assets/bg/bg.png differ diff --git a/src/front/src/components/CountDown.vue b/src/front/src/components/CountDown.vue index 0ae98bad0..fdeaa6a8f 100644 --- a/src/front/src/components/CountDown.vue +++ b/src/front/src/components/CountDown.vue @@ -1,6 +1,6 @@ - ДО КОНЦА ГОЛОСОВАНИЯ ОСТАЛОСЬ: - {{ displayDays }} дней {{ displayHours }} часов {{ displayMinutes }} минут + ДО КОНЦА ГОЛОСОВАНИЯ ОСТАЛОСЬ: + {{ displayDays }} дней {{ displayHours }} часов {{ displayMinutes }} минут - \ No newline at end of file diff --git a/src/front/src/components/vote/PercThn.vue b/src/front/src/components/vote/PercThn.vue deleted file mode 100644 index d6dfe08f8..000000000 --- a/src/front/src/components/vote/PercThn.vue +++ /dev/null @@ -1,46 +0,0 @@ - - {{ perc_thn }}% - - - \ No newline at end of file diff --git a/src/front/src/components/vote/VoteAdmin.vue b/src/front/src/components/vote/VoteAdmin.vue index 776f9b693..31134483c 100644 --- a/src/front/src/components/vote/VoteAdmin.vue +++ b/src/front/src/components/vote/VoteAdmin.vue @@ -1,73 +1,33 @@ - - - - - Голосование - «Мой коллега самый лучший» - - - Процент проголосовавших - - - - {{ perc_bst }}% - - - - Лидер номинации - - - - {{ department }} - - {{ employee.name }} - - - - - ФИО не участвовавших в голосовании - - - - - {{ key }} - - {{ item_fio.fio }} - - - - - - - + + - - Голосование - «Хочу сказать Спасибо!» + + + «Лучший новогодний костюм!» - - Процент проголосовавших - - - - + + Процент проголосовавших + + {{ perc_thanks }}% - + + Лидер номинации - - {{ leader }} + + {{ leader.cand_name }} - {{ leader.total }} ФИО не участвовавших в голосовании - + + {{ key }} {{ 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; -} + \ No newline at end of file diff --git a/src/front/src/components/vote/VoteForm.vue b/src/front/src/components/vote/VoteForm.vue index 2a828ca20..55fe248d0 100644 --- a/src/front/src/components/vote/VoteForm.vue +++ b/src/front/src/components/vote/VoteForm.vue @@ -1,79 +1,92 @@ - - + + + - + + - + - - - - Подтвердить выбор - - - - Вы подтверждаете выбор? - После подтверждения внесение измений станет невозможным. - Выбранный кандидат - {{ approve_name }} - Кандидат не выбран повторите голосование - - - ДА - ДА - - - НЕТ - + + + + + + Вы подтверждаете выбор? + После подтверждения внесение измений станет невозможным. + Выбранный кандидат + {{ approve_name }} + Кандидат не выбран повторите голосование + + + ДА + ДА - - - - + + НЕТ + + + + + + + diff --git a/src/front/src/views/VoteHomePage.vue b/src/front/src/views/VoteHomePage.vue new file mode 100644 index 000000000..cab3df511 --- /dev/null +++ b/src/front/src/views/VoteHomePage.vue @@ -0,0 +1,227 @@ + + + + Голосования + + + + Текущие голосования + Завершенные голосования + Создать новое голосование + + + + + + + + + + + + {{ voting.title }} + + mdi-pencil + + + + Окончание: {{ formatDate(voting.endDate) }} + + + Осталось: {{ timeRemaining(voting.endDate) }} + + + + Проголосовать + + Уже проголосовали + + mdi-delete + + + + + + + + + + + + + + + {{ voting.title }} + + Завершено: {{ formatDate(voting.endDate) }} + + + + Результаты + + + mdi-delete + + + + + + + + + + + + + + + + + + Голосование: {{ selectedVoting?.title }} + + Описание голосования... + + + Проголосовать + Закрыть + + + + + + + + Результаты голосования: {{ selectedVoting?.title }} + + Здесь отображаются результаты голосования... + + + Закрыть + + + + + + + + +
Выбранный кандидат
Описание голосования...
Здесь отображаются результаты голосования...