Compare commits
178
Commits
vs-patch-1
..
dkr
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
079bf1f9e3 | ||
|
|
7d6f042441 | ||
|
|
39c99d3420 | ||
|
|
e7826a98e6 | ||
|
|
8ea41ddc01 | ||
|
|
1630bee537 | ||
|
|
294189cd3d | ||
|
|
977cceca2f | ||
|
|
a808fc1016 | ||
|
|
c77096b829 | ||
|
|
d3bb74ac89 | ||
|
|
4a766146a0 | ||
|
|
0c058f2705 | ||
|
|
e939354f3c | ||
|
|
25f9f0d70c | ||
|
|
b385af522b | ||
|
|
9a144a4ced | ||
|
|
d5237ed734 | ||
|
|
491b08a6dc | ||
|
|
20e912d9ee | ||
|
|
996eea04de | ||
|
|
9b69adf3ea | ||
|
|
b6e3584d0b | ||
|
|
8493244459 | ||
|
|
7d1b8b3e00 | ||
|
|
f5ba96fb11 | ||
|
|
77b274c616 | ||
|
|
594b9ef327 | ||
|
|
d2118ed531 | ||
|
|
a336a1fb3e | ||
|
|
9bb72452bd | ||
|
|
c51b3048a0 | ||
|
|
0578b83478 | ||
|
|
8b871b1c03 | ||
|
|
9253203db1 | ||
|
|
9e934f4fb1 | ||
|
|
e86e637fa8 | ||
|
|
65b39ad9a8 | ||
|
|
e43bf02440 | ||
|
|
907693cab3 | ||
|
|
35d75a0134 | ||
|
|
1fb4ad3cf0 | ||
|
|
a80d89e74c | ||
|
|
79d0cf6f38 | ||
|
|
f682eb8235 | ||
|
|
f7d0fba4cf | ||
|
|
4996796ace | ||
|
|
251a4dc460 | ||
|
|
7b1d812b70 | ||
|
|
ce4314fb82 | ||
|
|
bf609053ae | ||
|
|
cdd3a17576 | ||
|
|
9f310ca030 | ||
|
|
82540e155a | ||
|
|
51a76fffa3 | ||
|
|
e9685cf858 | ||
|
|
acc8fb241c | ||
|
|
55c575be71 | ||
|
|
aae575f722 | ||
|
|
0ad046e920 | ||
|
|
385be2c425 | ||
|
|
6f43cad969 | ||
|
|
17f9da513f | ||
|
|
a7910fbf6f | ||
|
|
86f4385f30 | ||
|
|
64cfa658dd | ||
|
|
d8337cf7d7 | ||
|
|
3b57c20a77 | ||
|
|
da5d9c45f3 | ||
|
|
4f378046b1 | ||
|
|
5a077e8506 | ||
|
|
b895b60a86 | ||
|
|
7b76ba72b7 | ||
|
|
7a51856811 | ||
|
|
989d715af0 | ||
|
|
ac4be9ac46 | ||
|
|
b9dbabf5d3 | ||
|
|
48056c8e6e | ||
|
|
c1389454b2 | ||
|
|
ad0e21ef02 | ||
|
|
2de075cadd | ||
|
|
b9b19004b8 | ||
|
|
5c4f9a24aa | ||
|
|
803ac411a2 | ||
|
|
9d7674c0f7 | ||
|
|
e75bc2880c | ||
|
|
0ed5e19a54 | ||
|
|
9247fc5c5f | ||
|
|
9c2084f917 | ||
|
|
d73dfcb8bc | ||
|
|
22229ffc9b | ||
|
|
e9626bb430 | ||
|
|
3b2fa7d1ac | ||
|
|
29c41fe97d | ||
|
|
c8c70677a0 | ||
|
|
8ecafe6de7 | ||
|
|
cfff0af0c5 | ||
|
|
83c5aa3d68 | ||
|
|
b1334602a8 | ||
|
|
64db922e78 | ||
|
|
b3e08c49f2 | ||
|
|
615c24aa95 | ||
|
|
db0eb1f0b7 | ||
|
|
411ac93e40 | ||
|
|
10bbd4e078 | ||
|
|
6827e84884 | ||
|
|
5ae8d0e738 | ||
|
|
bbfe95aab5 | ||
|
|
61c203355e | ||
|
|
d9527a2588 | ||
|
|
5d69000777 | ||
|
|
cb71fd4eec | ||
|
|
71784e1bd3 | ||
|
|
9edc2d94b1 | ||
|
|
ef0513997b | ||
|
|
1e4153a95a | ||
|
|
117ce22751 | ||
|
|
7ba57b8e39 | ||
|
|
fc7641cbcf | ||
|
|
09cce37c30 | ||
|
|
a1b6faa4b3 | ||
|
|
33d648d864 | ||
|
|
d8f35639fa | ||
|
|
d0e5c7581f | ||
|
|
e26890470b | ||
|
|
65d55987d1 | ||
|
|
d2ebce22cd | ||
|
|
fc8deb73cd | ||
|
|
6b1e12fbb4 | ||
|
|
0b41076e00 | ||
|
|
2112ad06d5 | ||
|
|
104d320f8f | ||
|
|
82cb987a42 | ||
|
|
68c3f066fd | ||
|
|
f4d6cc1483 | ||
|
|
efd3a25254 | ||
|
|
a4d778fc79 | ||
|
|
7e4851825f | ||
|
|
5773aef685 | ||
|
|
d0648208b0 | ||
|
|
6eba1387d8 | ||
|
|
98b34cc264 | ||
|
|
875a2e0a0c | ||
|
|
f381ca108f | ||
|
|
b5c8b10f58 | ||
|
|
92ddda66bc | ||
|
|
98b0e53c31 | ||
|
|
9a3c0ad87f | ||
|
|
2afdfb716a | ||
|
|
bff52543d2 | ||
|
|
b04514307a | ||
|
|
8870e5891f | ||
|
|
b50542d069 | ||
|
|
374d825ba2 | ||
|
|
93ba51450f | ||
|
|
121cb6e0ea | ||
|
|
0622736dc3 | ||
|
|
2424f4dffd | ||
|
|
c17405e36e | ||
|
|
e0ef4d4a99 | ||
|
|
8e29d93126 | ||
|
|
b60e4df9d6 | ||
|
|
b7e6865730 | ||
|
|
cd1f954d15 | ||
|
|
db023639a8 | ||
|
|
983f2211ad | ||
|
|
b752c475aa | ||
|
|
3214ada2f5 | ||
|
|
799ff80bd0 | ||
|
|
04b111165e | ||
|
|
298e769bee | ||
|
|
dd3279f76f | ||
|
|
47b996cf03 | ||
|
|
92fe954582 | ||
|
|
c2ea382458 | ||
|
|
5acf0ab11f | ||
|
|
505b34f426 | ||
|
|
1044796302 |
No files matched your search
@@ -0,0 +1,19 @@
|
||||
src/back/portal/.env
|
||||
src/back/portal/media/
|
||||
src/back/static/
|
||||
src/back/media/
|
||||
docs/.vitepress/cache
|
||||
/node_modules
|
||||
media/
|
||||
docker-compose.yml
|
||||
**/dockerfiles
|
||||
**/composes
|
||||
**/media
|
||||
*.md
|
||||
easydump
|
||||
easynpm
|
||||
easypip
|
||||
easyrestore
|
||||
**/node_modules
|
||||
*/**/node_modules
|
||||
documentation/node_modules
|
||||
@@ -0,0 +1,58 @@
|
||||
COMPOSE_PROJECT_NAME=portal
|
||||
|
||||
HOST_NAME=localhost
|
||||
|
||||
#для LINUX
|
||||
PROJECT_DIR=$(cd $(dirname $(readlink -e $0)) && pwd)
|
||||
# Windows
|
||||
# PROJECT_DIR=$(cygpath -w "$(cd "$(dirname "$(readlink -f "$0")")" && pwd)")
|
||||
|
||||
# Директория с кодом приложения
|
||||
SOURCE_DIR=${PROJECT_DIR}/src
|
||||
# Директория docker
|
||||
DOCKER_DIR=${PROJECT_DIR}/docker
|
||||
CONFS_DIR=${PROJECT_DIR}/sys
|
||||
# Директория с docker-compose файлами
|
||||
DOCKER_COMPOSES_DIR=${DOCKER_DIR}/composes
|
||||
# Директория с конфигурациями для различных серфисов
|
||||
DOCKER_CONFS_DIR=${DOCKER_DIR}/confs
|
||||
# Директория с Dockerfile
|
||||
DOCKER_DOCKERFILES_DIR=${DOCKER_DIR}/dockerfiles
|
||||
# Директория со скриптами инициализации
|
||||
DOCKER_INITS_DIR=${DOCKER_DIR}/inits
|
||||
# Директория с локальными файлами
|
||||
LOCAL_FILES_DIR=${PROJECT_DIR}/.local_files
|
||||
|
||||
COMPOSE_FILE="${PROJECT_DIR}/docker-compose.yml"
|
||||
|
||||
|
||||
DB_ENGINE="django.db.backends.mysql"
|
||||
DB_NAME=""
|
||||
DB_USER=""
|
||||
DB_PASSWORD=""
|
||||
DB_HOST=""
|
||||
DB_EXTERNAL_PORT=3306
|
||||
DB_INTERNAL_PORT=3306
|
||||
|
||||
REDIS="redis://redis"
|
||||
REDISBROKER="redis://redis"
|
||||
REDIS_PORT=6379
|
||||
REDIS_BASE=0
|
||||
|
||||
AUTO_BACKEND=True
|
||||
|
||||
FRONTEND_EXTERNAL_PORT=3000
|
||||
FRONTEND_INTERNAL_PORT=3000
|
||||
|
||||
BACKEND_EXTERNAL_PORT=8000
|
||||
BACKEND_INTERNAL_PORT=8000
|
||||
|
||||
|
||||
|
||||
DOCS_EXTERNAL_PORT=5173
|
||||
DOCS_INTERNAL_PORT=5173
|
||||
NGINX_EXTERNAL_PORT=80
|
||||
NGINX_INTERNAL_PORT=80
|
||||
|
||||
RUN_WITH_DOCS=False
|
||||
PRODUCTION=False
|
||||
@@ -0,0 +1,10 @@
|
||||
RUN_WITH_DOCS=False
|
||||
|
||||
AUTO_BACKEND=False
|
||||
|
||||
DB_NAME="accounting"
|
||||
DB_USER="root"
|
||||
DB_PASSWORD="P@ssw0rd"
|
||||
DB_HOST="db"
|
||||
DB_EXTERNAL_PORT=3306
|
||||
DB_INTERNAL_PORT=3306
|
||||
@@ -0,0 +1,37 @@
|
||||
#!/usr/bin/env sh
|
||||
commit_msg_file="$1"
|
||||
|
||||
# Читаем сообщение коммита
|
||||
commit_msg=$(cat "$commit_msg_file")
|
||||
# Проверяем, был ли передан аргумент
|
||||
if [ -z "$commit_msg" ]; then
|
||||
echo "Ошибка: Необходимо передать сообщение коммита."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
|
||||
# Определяем шаблон для проверки
|
||||
PATTERN="^(feat|fix|docs|style|refactor|perf|test|chore) \[[A-Z]+\-[0-9]+]: .+$"
|
||||
|
||||
|
||||
|
||||
# Проверяем соответствие шаблону
|
||||
if echo "$commit_msg" | grep -qE "$PATTERN"; then
|
||||
|
||||
exit 0
|
||||
else
|
||||
echo "Ошибка: Сообщение коммита не соответствует шаблону."
|
||||
echo "Ожидается: feat|fix|docs|style|refactor|perf|test|chore [X-01]: ваше сообщение"
|
||||
echo "Заголовок должен содержать тип, номер задачи и название коммита. Формат: <тип> [<номер задачи>]: <название>"
|
||||
echo " 'feat' - Новый функционал"
|
||||
echo " 'fix' - Исправление ошибки"
|
||||
echo " 'docs' - Изменения в документации"
|
||||
echo " 'style' - Изменения, не влияющие на функциональность"
|
||||
echo " 'refactor' - Изменения кода, не исправляющие ошибки и не добавляющие функционал"
|
||||
echo " 'perf' - Изменения, улучшающие производительность"
|
||||
echo " 'test' - Добавление тестов"
|
||||
echo " 'chore' - Изменения в процессе сборки или вспомогательных инструментах."
|
||||
|
||||
echo " Например: feat [X-01]: я тут накоммитил"
|
||||
exit 1
|
||||
fi
|
||||
@@ -0,0 +1,48 @@
|
||||
#!/usr/bin/env sh
|
||||
|
||||
|
||||
|
||||
# # Получение списка всех Vue/js/ts-файлов, подготовленных для коммита
|
||||
filesjs=$(git diff --cached --name-only --diff-filter=ACM | grep -E '\.vue$|\.js$|\.ts$'| grep -v 'test\.js$')
|
||||
|
||||
|
||||
if [ -n "$filesjs" ]; then
|
||||
filesjs_modified=$(echo "$filesjs" | sed 's|^src/front/src/|src/|'| tr '\n' ' ')
|
||||
# Запускаем команду formatter в контейнере
|
||||
echo $filesjs_modified
|
||||
if [ "$(docker-compose -f docker-compose.yml ps -q frontend)" ]; then
|
||||
docker-compose -f docker-compose.yml exec frontend sh -c "npm run formatter $filesjs_modified && npm run linter $filesjs_modified"
|
||||
else
|
||||
docker-compose -f docker-compose.yml run --rm frontend sh -c "npm run formatter $filesjs_modified && npm run linter $filesjs_modified"
|
||||
|
||||
fi
|
||||
fi
|
||||
if [ $? -ne 0 ]; then
|
||||
echo "Ошибка: eslint обнаружил проблемы в коде."
|
||||
exit 1 # Выход с кодом ошибки
|
||||
|
||||
fi
|
||||
|
||||
|
||||
|
||||
|
||||
# # Получение списка всех Python-файлов, подготовленных для коммита
|
||||
pyfiles=$(git diff --cached --name-only --diff-filter=ACM | grep '\.py$')
|
||||
# # | sed 's|/|.|g; s|\.py$||'
|
||||
|
||||
if [ -n "$pyfiles" ]; then
|
||||
pyfiles_mod=$(echo "$pyfiles" | sed 's|^src/back/||'| tr '\n' ' ')
|
||||
if [ "$(docker-compose -f docker-compose.yml ps -q backend)" ]; then
|
||||
echo $pyfiles_mod
|
||||
docker-compose -f docker-compose.yml exec backend sh -c "poetry run isort $pyfiles_mod && poetry run black $pyfiles_mod && poetry run pylint $pyfiles_mod"
|
||||
else
|
||||
docker-compose -f docker-compose.yml run --rm --entrypoint sh backend -c "poetry run isort $pyfiles_mod && poetry run black $pyfiles_mod && poetry run pylint $pyfiles_mod"
|
||||
fi
|
||||
# # Запуск pylint для всех подготовленных Python-файлов
|
||||
# # echo 1
|
||||
fi
|
||||
if [ $? -ne 0 ]; then
|
||||
echo "Ошибка: pylint обнаружил проблемы в коде."
|
||||
exit 1 # Выход с кодом ошибки
|
||||
|
||||
fi
|
||||
+17
-8
@@ -1,8 +1,17 @@
|
||||
env/
|
||||
|
||||
/src/__pycache__/
|
||||
/src/*/__pycache__/
|
||||
/src/*/migrations/
|
||||
/src/front/public/Tiles/
|
||||
/src/front/node_modules/
|
||||
.vscode/
|
||||
/env/
|
||||
/documentation/docs/.vitepress/cache
|
||||
/node_modules/
|
||||
/**/node_modules/
|
||||
/docs/
|
||||
/.local_files/
|
||||
/documentation/docs/.vitepress/theme/*
|
||||
documentation/docs/.vitepress/cache/*
|
||||
.env.localfiles/
|
||||
.env
|
||||
.env.local
|
||||
easypip
|
||||
easynpm
|
||||
easydump
|
||||
easyrestore
|
||||
easymanage
|
||||
#
|
||||
Generated
-8
@@ -1,8 +0,0 @@
|
||||
# Default ignored files
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
# Editor-based HTTP Client requests
|
||||
/httpRequests/
|
||||
# Datasource local storage ignored files
|
||||
/dataSources/
|
||||
/dataSources.local.xml
|
||||
Generated
-27
@@ -1,27 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="PYTHON_MODULE" version="4">
|
||||
<component name="FacetManager">
|
||||
<facet type="django" name="Django">
|
||||
<configuration>
|
||||
<option name="rootFolder" value="$MODULE_DIR$/src/back" />
|
||||
<option name="settingsModule" value="settings.py" />
|
||||
<option name="manageScript" value="$MODULE_DIR$/src/back/manage.py" />
|
||||
<option name="environment" value="<map/>" />
|
||||
<option name="doNotUseTestRunner" value="false" />
|
||||
<option name="trackFilePattern" value="migrations" />
|
||||
</configuration>
|
||||
</facet>
|
||||
</component>
|
||||
<component name="NewModuleRootManager">
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<sourceFolder url="file://$MODULE_DIR$/src/back" isTestSource="false" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/env" />
|
||||
</content>
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
<component name="PyDocumentationSettings">
|
||||
<option name="format" value="PLAIN" />
|
||||
<option name="myDocStringFormat" value="Plain" />
|
||||
</component>
|
||||
</module>
|
||||
-6
@@ -1,6 +0,0 @@
|
||||
<component name="InspectionProjectProfileManager">
|
||||
<settings>
|
||||
<option name="USE_PROJECT_PROFILE" value="false" />
|
||||
<version value="1.0" />
|
||||
</settings>
|
||||
</component>
|
||||
Generated
-7
@@ -1,7 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="Black">
|
||||
<option name="sdkName" value="Python 3.10 (PORTAL_COD2)" />
|
||||
</component>
|
||||
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.10 (PORTAL_COD2)" project-jdk-type="Python SDK" />
|
||||
</project>
|
||||
Generated
-8
@@ -1,8 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectModuleManager">
|
||||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/.idea/PORTAL_COD2.iml" filepath="$PROJECT_DIR$/.idea/PORTAL_COD2.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
</project>
|
||||
Generated
-6
@@ -1,6 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="" vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Функция для вывода переменных, определенных во время исполнения скрипта
|
||||
print_script_variables() {
|
||||
set | sort | comm -13 .env.tmp -
|
||||
}
|
||||
git config core.hooksPath .git-hooks
|
||||
# Записываем переменные окружения и функции оболочки во временный файл
|
||||
set | sort > .env.tmp
|
||||
|
||||
# Импортируем базовые переменные окружения
|
||||
source ".env.base"
|
||||
|
||||
# Создаем локальные файлы из их шаблонов, если они еще не созданы
|
||||
cp -n ${PROJECT_DIR}/.env.local.sample ${PROJECT_DIR}/.env.local
|
||||
# cp -n ${SOURCE_DIR}/settings/local_settings.sample.py ${SOURCE_DIR}/settings/local_settings.py
|
||||
|
||||
# Импортируем локальные переменные окружения
|
||||
if [[ -f .env.local ]]; then
|
||||
source ".env.local"
|
||||
fi
|
||||
|
||||
# Создаем директорию с локальными фойлами
|
||||
mkdir -p "${LOCAL_FILES_DIR}"
|
||||
|
||||
# # Создаем символические ссылки на скрипты (сюда можно добавить создание и загрузку дампа бд)
|
||||
ln -sf "${CONFS_DIR}/scripts/easypip.sh" "${PROJECT_DIR}/easypip"
|
||||
ln -sf "${CONFS_DIR}/scripts/easynpm.sh" "${PROJECT_DIR}/easynpm"
|
||||
ln -sf "${CONFS_DIR}/scripts/easydump.sh" "${PROJECT_DIR}/easydump"
|
||||
ln -sf "${CONFS_DIR}/scripts/easyrestore.sh" "${PROJECT_DIR}/easyrestore"
|
||||
ln -sf "${CONFS_DIR}/scripts/easymanage.sh" "${PROJECT_DIR}/easymanage"
|
||||
# ln -sf "${PROJECT_DIR}/scripts/bash.sh" "${PROJECT_DIR}/bash"
|
||||
# ln -sf "${PROJECT_DIR}/scripts/dbshell.sh" "${PROJECT_DIR}/dbshell"
|
||||
# ln -sf "${PROJECT_DIR}/scripts/manage.sh" "${PROJECT_DIR}/manage"
|
||||
# ln -sf "${PROJECT_DIR}/scripts/shell.sh" "${PROJECT_DIR}/shell"
|
||||
# ln -sf "${PROJECT_DIR}/scripts/init.sh" "${PROJECT_DIR}/init"
|
||||
|
||||
# # Создание локальных файлов для postgres:
|
||||
mkdir -p "${LOCAL_FILES_DIR}/mysql"
|
||||
mkdir -p "${LOCAL_FILES_DIR}/mysql/log"
|
||||
mkdir -p "${LOCAL_FILES_DIR}/mysql/data"
|
||||
mkdir -p "${LOCAL_FILES_DIR}/mysql/backup"
|
||||
|
||||
FILE="${LOCAL_FILES_DIR}/mysql/data/mysql.sock"
|
||||
|
||||
# Проверяем, существует ли файл
|
||||
if [ -L "$FILE" ]; then
|
||||
# Удаляем файл
|
||||
rm "$FILE"
|
||||
echo "Ссылка '$FILE' была удалена."
|
||||
else
|
||||
echo "Ссылка '$FILE' не существует."
|
||||
fi
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# # Создание локальных файлов для redis:
|
||||
mkdir -p "${LOCAL_FILES_DIR}/redis"
|
||||
mkdir -p "${LOCAL_FILES_DIR}/redis/log"
|
||||
mkdir -p "${LOCAL_FILES_DIR}/redis/data"
|
||||
# # Создание локальных файлов для asgi:
|
||||
# mkdir -p "${LOCAL_FILES_DIR}/asgi"
|
||||
# mkdir -p "${LOCAL_FILES_DIR}/asgi/log"
|
||||
# mkdir -p "${LOCAL_FILES_DIR}/asgi/tmp"
|
||||
# mkdir -p "${LOCAL_FILES_DIR}/asgi/media"
|
||||
# # Создание локальных файлов для centry:
|
||||
# mkdir -p "${LOCAL_FILES_DIR}/celery"
|
||||
# mkdir -p "${LOCAL_FILES_DIR}/celery/log"
|
||||
# # Создание локальных файлов для nginx:
|
||||
mkdir -p "${LOCAL_FILES_DIR}/nginx"
|
||||
mkdir -p "${LOCAL_FILES_DIR}/nginx/conf"
|
||||
# mkdir -p "${LOCAL_FILES_DIR}/nginx/log"
|
||||
# mkdir -p "${LOCAL_FILES_DIR}/nginx/certs"
|
||||
|
||||
# Создания docker-compose.override.yml (под gitignore)
|
||||
# touch "${DOCKER_COMPOSES_DIR}/docker-compose.override.yml"
|
||||
|
||||
# Создание конфигов nginx из их шаблонов
|
||||
export NGINX_EXTERNAL_PORT=${NGINX_EXTERNAL_PORT}
|
||||
export BACKEND_EXTERNAL_PORT=${BACKEND_EXTERNAL_PORT}
|
||||
export FRONTEND_EXTERNAL_PORT=${FRONTEND_EXTERNAL_PORT}
|
||||
export DOCS_EXTERNAL_PORT=${DOCS_EXTERNAL_PORT}
|
||||
export HOST_NAME=${HOST_NAME}
|
||||
# # Следующие команды заполняют шаблон значениями переменных окружения
|
||||
envsubst '${NGINX_EXTERNAL_PORT},${BACKEND_EXTERNAL_PORT},${DOCS_EXTERNAL_PORT},${FRONTEND_EXTERNAL_PORT},${HOST_NAME}' \
|
||||
< "${CONFS_DIR}/nginx/nginx.dev.conf" > \
|
||||
"${LOCAL_FILES_DIR}/nginx/conf/nginx.dev.conf"
|
||||
# envsubst '${NGINX_PORT_INTERNAL},${ASGI_PORT_INTERNAL},${DOCS_PORT_INTERNAL},${HOST_NAME}' \
|
||||
# < "${CONFS_DIR}/nginx.prod.conf" > \
|
||||
# "${LOCAL_FILES_DIR}/nginx/conf/nginx.prod.conf"
|
||||
|
||||
|
||||
|
||||
|
||||
# Дополнение docker-compose.yaml в зависимости от значений переменных окружения
|
||||
# if [[ "${RUN_WITH_REDIS}" = "True" ]]; then
|
||||
# COMPOSE_FILE="${COMPOSE_FILE}:${DOCKER_COMPOSES_DIR}/docker-compose.redis.yml"
|
||||
# fi
|
||||
# if [[ "${RUN_WITH_POSTGRES}" = "True" ]]; then
|
||||
# COMPOSE_FILE="${COMPOSE_FILE}:${DOCKER_COMPOSES_DIR}/docker-compose.postgres.yml"
|
||||
# fi
|
||||
# if [[ "${RUN_WITH_OVERRIDE_DOCKER_COMPOSE}" = "True" ]]; then
|
||||
# COMPOSE_FILE="${COMPOSE_FILE}:${DOCKER_COMPOSES_DIR}/docker-compose.override.yml"
|
||||
# fi
|
||||
if [[ "${RUN_WITH_DOCS}" = "True" ]]; then
|
||||
echo $DOCKER_COMPOSES_DIR
|
||||
COMPOSE_FILE="${COMPOSE_FILE} -f ${DOCKER_COMPOSES_DIR}/docker-compose.docs.yml"
|
||||
fi
|
||||
# if [[ "${RUN_WITH_BUILD_LOCALLY}" = "True" ]]; then
|
||||
# COMPOSE_FILE="${COMPOSE_FILE}:${DOCKER_COMPOSES_DIR}/docker-compose.build-asgi-locally.yml"
|
||||
# if [[ "${RUN_WITH_DOCS}" = "True" ]]; then
|
||||
# COMPOSE_FILE="${COMPOSE_FILE}:${DOCKER_COMPOSES_DIR}/docker-compose.build-docs-locally.yml"
|
||||
# fi
|
||||
# fi
|
||||
# ARG_FOUND=false
|
||||
# TARGET_ARG="--lint"
|
||||
# for arg in "$@"; do
|
||||
# if [ "$arg" == "$TARGET_ARG" ]; then
|
||||
# ARG_FOUND=true
|
||||
# break
|
||||
# fi
|
||||
# done
|
||||
# if [ "$ARG_FOUND" = true ]; then
|
||||
# COMPOSE_FILE="${COMPOSE_FILE}:${DOCKER_COMPOSES_DIR}/docker-compose.frontlint.yml"
|
||||
# else
|
||||
# if [[ "${PRODUCTION}" = "False" ]]; then
|
||||
# COMPOSE_FILE="${COMPOSE_FILE}:${DOCKER_COMPOSES_DIR}/docker-compose.dev.yml"
|
||||
# else
|
||||
# COMPOSE_FILE="${COMPOSE_FILE}:${DOCKER_COMPOSES_DIR}/docker-compose.prod.yml"
|
||||
# fi
|
||||
# fi
|
||||
# Записываем в файл переменные окружения, объявленные в процессе выполнения текущего скрипта
|
||||
|
||||
|
||||
|
||||
EXCLUDE_RULES="^\(SHLVL=\|LINES=\|COLUMNS=\|BASH_SOURCE=\|BASH_LINENO=\|BASH_ARGV=\|BASH_ARGC=\|EXCLUDE_RULES=\|_=\|FUNCNAME=\|PIPESTATUS=\)"
|
||||
print_script_variables | grep -v $EXCLUDE_RULES > ${PROJECT_DIR}/.env
|
||||
|
||||
# Удаляем временный файл
|
||||
rm -f .env.tmp
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"singleQuote": true,
|
||||
"semi": true,
|
||||
"printWidth": 100,
|
||||
"trailingComma": "all",
|
||||
"endOfLine": "auto"
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
module.exports = {
|
||||
presets: ['@babel/preset-env', '@babel/preset-modules'],
|
||||
plugins: ['@babel/plugin-transform-runtime'],
|
||||
};
|
||||
@@ -0,0 +1,36 @@
|
||||
export default {
|
||||
rules: {
|
||||
'header-max-length': [2, 'always', 72], // Максимальная длина заголовка
|
||||
|
||||
'jira-issue': [2, 'always'], // Правило для проверки номера задачи
|
||||
},
|
||||
plugins: [
|
||||
{
|
||||
rules: {
|
||||
'jira-issue': ({ header }) => {
|
||||
const jiraIssuePattern =
|
||||
/^(feat|fix|docs|style|refactor|perf|test|chore)\s+\[([A-Z]+-\d+)\]:\s+(.+)/;
|
||||
const match = header.match(jiraIssuePattern);
|
||||
|
||||
if (!match) {
|
||||
return [
|
||||
false,
|
||||
`Заголовок должен содержать тип, номер задачи и название коммита. Формат: <тип> [<номер задачи>]: <название>
|
||||
'feat' - Новый функционал
|
||||
'fix' - Исправление ошибки
|
||||
'docs' - Изменения в документации
|
||||
'style' - Изменения, не влияющие на функциональность
|
||||
'refactor' - Изменения кода, не исправляющие ошибки и не добавляющие функционал
|
||||
'perf' - Изменения, улучшающие производительность
|
||||
'test' - Добавление тестов
|
||||
'chore' - Изменения в процессе сборки или вспомогательных инструментах.
|
||||
|
||||
Например: feat [X-01]: я тут накоммитил`,
|
||||
];
|
||||
}
|
||||
return [true];
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -0,0 +1,28 @@
|
||||
#!/bin/bash
|
||||
# ARG_FOUND=false
|
||||
# TARGET_ARG="--lint"
|
||||
# for arg in "$@"; do
|
||||
# if [ "$arg" == "$TARGET_ARG" ]; then
|
||||
# ARG_FOUND=true
|
||||
# break
|
||||
# fi
|
||||
# done
|
||||
|
||||
# if [ "$ARG_FOUND" = true ]; then
|
||||
# bash .prepare.sh --lint
|
||||
# else
|
||||
bash .prepare.sh
|
||||
# fi
|
||||
source ".env"
|
||||
|
||||
ARGS_STRING=""
|
||||
while [ $1 ]
|
||||
do
|
||||
|
||||
ARGS_STRING+="$1 "
|
||||
|
||||
|
||||
shift
|
||||
done
|
||||
echo $COMPOSE_FILE
|
||||
docker compose -f ${COMPOSE_FILE} ${ARGS_STRING}
|
||||
@@ -0,0 +1,97 @@
|
||||
|
||||
networks:
|
||||
dev:
|
||||
driver: bridge
|
||||
|
||||
services:
|
||||
|
||||
frontend:
|
||||
|
||||
restart:
|
||||
always
|
||||
env_file:
|
||||
- .env
|
||||
build:
|
||||
context: .
|
||||
dockerfile: docker/dockerfiles/dev
|
||||
args:
|
||||
SOURCE_DIR: ./src/front
|
||||
volumes:
|
||||
|
||||
- ./src/front/:/app
|
||||
- /app/node_modules
|
||||
|
||||
ports:
|
||||
- "${FRONTEND_EXTERNAL_PORT}:${FRONTEND_INTERNAL_PORT}"
|
||||
environment:
|
||||
- CHOKIDAR_USEPOLLING=true
|
||||
|
||||
|
||||
networks:
|
||||
- dev
|
||||
|
||||
|
||||
redis:
|
||||
env_file:
|
||||
- .env
|
||||
image: redis:alpine # Используем легковесный образ Redis
|
||||
ports:
|
||||
- "${REDIS_PORT}:${REDIS_PORT}" # Открываем порт Redis для внешнего доступа (по желанию)
|
||||
networks:
|
||||
- dev
|
||||
|
||||
db:
|
||||
env_file:
|
||||
- .env
|
||||
image: mysql:latest
|
||||
ports:
|
||||
- "${DB_EXTERNAL_PORT}:${DB_INTERNAL_PORT}" # Открываем порт MySQL для внешнего доступа
|
||||
environment:
|
||||
- MYSQL_DATABASE=${DB_NAME}
|
||||
- MYSQL_PASSWORD=${DB_PASSWORD}
|
||||
- MYSQL_ROOT_PASSWORD=${DB_PASSWORD}
|
||||
volumes:
|
||||
- ${CONFS_DIR}/database/init.sql:/docker-entrypoint-initdb.d/init.sql
|
||||
- ${LOCAL_FILES_DIR}/mysql/data/:/var/lib/mysql
|
||||
- ${LOCAL_FILES_DIR}/mysql/backup/:/backup/
|
||||
networks:
|
||||
- dev
|
||||
|
||||
backend:
|
||||
entrypoint: /script/backend-entrypoint.sh
|
||||
restart:
|
||||
always
|
||||
build:
|
||||
context: .
|
||||
dockerfile: docker/dockerfiles/back
|
||||
args:
|
||||
SOURCE_DIR: ./src/back
|
||||
PROJECT_DIR: .
|
||||
ports:
|
||||
- "${BACKEND_EXTERNAL_PORT}:${BACKEND_INTERNAL_PORT}"
|
||||
|
||||
env_file:
|
||||
- .env
|
||||
networks:
|
||||
- dev
|
||||
depends_on:
|
||||
- db
|
||||
- redis
|
||||
volumes:
|
||||
- /back/.venv/
|
||||
- ./src/back:/back
|
||||
# command: ["tail", "-f", "/dev/null"]
|
||||
nginx:
|
||||
image: nginx:latest
|
||||
ports:
|
||||
- "${NGINX_EXTERNAL_PORT}:${NGINX_INTERNAL_PORT}" # Открываем порт 80 для внешнего доступа
|
||||
volumes:
|
||||
- ${LOCAL_FILES_DIR}/nginx/log/:/var/log/nginx/
|
||||
- ${LOCAL_FILES_DIR}/nginx/conf/nginx.dev.conf:/etc/nginx/nginx.conf # Подключаем конфигурацию Nginx
|
||||
depends_on:
|
||||
- backend
|
||||
networks:
|
||||
- dev
|
||||
volumes:
|
||||
mysql_data:
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
services:
|
||||
documentation:
|
||||
|
||||
restart:
|
||||
always
|
||||
env_file:
|
||||
- .env
|
||||
build:
|
||||
context: .
|
||||
dockerfile: ${DOCKER_DOCKERFILES_DIR}/docfront
|
||||
volumes:
|
||||
|
||||
- ./documentation:/app/documentation
|
||||
- ./src/front/src:/app/src/front/src
|
||||
- /app/src/front/src/node_modules/
|
||||
- /app/documentation/node_modules/
|
||||
- /app/node_modules/
|
||||
- /app/documentation/docs/public/
|
||||
|
||||
ports:
|
||||
- 5173:5173
|
||||
|
||||
command: ["sh", "-c", "npx vue-md-parser && npx jest && npx vitepress dev docs --host 0.0.0.0"]
|
||||
networks:
|
||||
- dev
|
||||
|
||||
|
||||
networks:
|
||||
dev:
|
||||
driver: bridge
|
||||
@@ -0,0 +1,38 @@
|
||||
FROM python:3.10.13-slim AS builderstage
|
||||
|
||||
WORKDIR /back
|
||||
|
||||
ARG SOURCE_DIR
|
||||
ENV SOURCE_DIR=${SOURCE_DIR}
|
||||
# Устанавливаем рабочую директорию
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
libmariadb-dev-compat \
|
||||
build-essential \
|
||||
dos2unix \
|
||||
pkg-config && \
|
||||
apt-get clean && \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
|
||||
|
||||
# Копируем файлы зависимостей в контейнер
|
||||
COPY ${SOURCE_DIR}/pyproject.toml ${SOURCE_DIR}/README.md ./
|
||||
COPY docker/entries/backend-entrypoint.sh /script/backend-entrypoint.sh
|
||||
|
||||
RUN dos2unix /script/backend-entrypoint.sh && chmod 777 /script/backend-entrypoint.sh && \
|
||||
python -m pip install --no-cache-dir poetry \
|
||||
&& poetry config virtualenvs.in-project true \
|
||||
&& poetry install --no-interaction --no-ansi
|
||||
# --without dev,test
|
||||
# Устанавливаем зависимости
|
||||
# RUN python -m venv env
|
||||
# RUN pip install --no-cache-dir -r r.txt
|
||||
|
||||
|
||||
# Копируем все файлы проекта в контейнер
|
||||
# COPY ${SOURCE_DIR} .
|
||||
# FROM python:3.10.13-slim
|
||||
# RUN python -m pip install --no-cache-dir poetry
|
||||
|
||||
# COPY --from=builderstage /script /script
|
||||
# WORKDIR /back
|
||||
EXPOSE 8000
|
||||
@@ -0,0 +1,24 @@
|
||||
# Используем официальный образ Node.js на базе Alpine
|
||||
FROM node:lts-alpine as buildstage
|
||||
|
||||
|
||||
ARG SOURCE_DIR
|
||||
ENV SOURCE_DIR=${SOURCE_DIR}
|
||||
# Устанавливаем рабочую директорию
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY ${SOURCE_DIR}/* ./
|
||||
|
||||
RUN npm cache clean --force && npm install
|
||||
|
||||
# Копируем остальные файлы приложения
|
||||
# COPY ${SOURCE_DIR} ./
|
||||
|
||||
|
||||
EXPOSE 3000
|
||||
# COPY . .
|
||||
# RUN chmod -R 777 ${SOURCE_DIR}
|
||||
# Указываем команду для запуска lint-staged
|
||||
CMD ["npm","run", "dev"]
|
||||
# CMD ["tail", "-f", "/dev/null"]
|
||||
@@ -0,0 +1,37 @@
|
||||
FROM node:lts-alpine as buildstage
|
||||
|
||||
# Установить рабочую директорию
|
||||
WORKDIR /app
|
||||
|
||||
|
||||
RUN npm cache clean --force && npm install @babel/plugin-proposal-unicode-property-regex \
|
||||
@babel/preset-env @babel/preset-modules \
|
||||
babel-jest @babel/runtime @babel/plugin-transform-runtime
|
||||
|
||||
WORKDIR /app/documentation
|
||||
# Очистить кэш npm и установить необходимые пакеты
|
||||
RUN npm cache clean --force && npm install --prefix ./ vitepress vue-md-parser @vue/vue3-jest \
|
||||
@babel/plugin-proposal-unicode-property-regex \
|
||||
@babel/preset-env @babel/preset-modules babel-jest @babel/runtime \
|
||||
axios @babel/plugin-transform-runtime \
|
||||
babel-jest jest jest-environment-jsdom @jest/globals \
|
||||
@vue/cli-plugin-babel @vue/compiler-dom @vue/server-renderer @vue/test-utils \
|
||||
jest-transform-stub && \
|
||||
mkdir -p /app/documentation/docs/public/test-coverage/src/ &&\
|
||||
chmod 777 /app/documentation/docs/public/test-coverage/src/
|
||||
|
||||
COPY ./documentation/babel.config.cjs /app
|
||||
WORKDIR /app/src/front/
|
||||
COPY ./src/front/package.json .
|
||||
RUN npm cache clean --force && npm install
|
||||
# Открыть порт для VitePress
|
||||
|
||||
FROM node:lts-alpine
|
||||
WORKDIR /app
|
||||
COPY --from=buildstage /app .
|
||||
EXPOSE 5173
|
||||
WORKDIR /app/documentation/
|
||||
# Держать контейнер запущенным
|
||||
# CMD ["tail", "-f", "/dev/null"]
|
||||
# Раскомментируйте следующую строку, чтобы запустить приложение
|
||||
# CMD ["sh", "-c", "npx vue-md-parser && npx jest && npx vitepress dev docs --host 0.0.0.0"]
|
||||
@@ -0,0 +1,38 @@
|
||||
#!/bin/bash
|
||||
|
||||
until cd /back/
|
||||
do
|
||||
echo "Жду запуска сервера..."
|
||||
done
|
||||
|
||||
until poetry run python manage.py makemigrations
|
||||
do
|
||||
echo "Создаю миграции..."
|
||||
done
|
||||
|
||||
|
||||
until poetry run python manage.py migrate
|
||||
do
|
||||
echo "Применяю при необходимости..."
|
||||
sleep 2
|
||||
done
|
||||
poetry run python manage.py collectstatic --noinput
|
||||
if [ "$PRODUCTION" == "False" ]; then
|
||||
if [ "$AUTO_BACKEND" == "True" ]; then
|
||||
poetry run python manage.py runserver 0.0.0.0:$BACKEND_INTERNAL_PORT
|
||||
else
|
||||
exec tail -f /dev/null
|
||||
# &
|
||||
|
||||
fi
|
||||
else
|
||||
# Фронт и бэк в одном
|
||||
|
||||
|
||||
mkdir -p /app/front/ && rsync -av --delete /app/dist/ /app/front/
|
||||
poetry run daphne -p 8000 -b 0.0.0.0 portal.asgi:application
|
||||
# python -m uvicorn config.asgi:application --bind 0.0.0.0:8000 --worker-class uvicorn.workers.UvicornWorker --timeout 180 --workers $WORKERS_COUNT --log-level debug --access-logfile - --error-logfile - --pid /tmp/gunicorn.pid'
|
||||
# celery --app speaker worker --loglevel=$CELERY_LOGLEVEL --concurrency 1 -E &
|
||||
fi
|
||||
wait -n
|
||||
exit $?
|
||||
@@ -1,27 +0,0 @@
|
||||
# Резервное копирование
|
||||
|
||||
# Резервное копирование исходных текстов
|
||||
Копирование как таковое не осуществляется. Резервирование основано на вытягивании (PULL) репозитория по протоколу Git в место резервного хранения.
|
||||
|
||||
Дата последней проверки работы: 2023-12-18
|
||||
|
||||
## Схема размещения репозиториев
|
||||
|
||||
```mermaid
|
||||
|
||||
graph TD;
|
||||
Developers==Коммиты==>Sulaco;
|
||||
Sulaco--Таймер--oBigBox;
|
||||
Sulaco-.->|Запрос|Gitea/COD2;
|
||||
Gitea/COD2-.->|Запрос|APP28-Prod;
|
||||
Gitea/COD2-.->|Запрос|APP040-Test;
|
||||
|
||||
```
|
||||
|
||||
* Коммит - по мере выкатки в репозиторий очередных правок
|
||||
* Таймер - по заданному расписанию (как правило - раз в сутки)
|
||||
* Запрос - ручной запрос на проведение синхронизации
|
||||
|
||||
Учетки для резервного копирования
|
||||
* R2D2 - для вытягивания в ЦОД2
|
||||
* BigBoy - для вытягивания в BigBox
|
||||
@@ -1,91 +0,0 @@
|
||||
|
||||
<h1 align="center">Соглашение для разработчиков по GIT</h1>
|
||||
<h3 align="center">Основные принципы работы в репозитории</h3>
|
||||
|
||||
|
||||
```mermaid
|
||||
---
|
||||
title: Пример схемы GIT репозитория
|
||||
---
|
||||
%%{init: {'theme':'forest'}}%%
|
||||
gitGraph:
|
||||
commit id:"initial"
|
||||
branch test
|
||||
checkout test
|
||||
commit id:"Ветки поделились"
|
||||
branch develop
|
||||
checkout develop
|
||||
commit type:HIGHLIGHT id:"taskid1" tag:"Назначение задачи"
|
||||
branch git_id_shortName
|
||||
checkout git_id_shortName
|
||||
|
||||
|
||||
|
||||
commit
|
||||
checkout develop
|
||||
merge git_id_shortName
|
||||
commit type:HIGHLIGHT tag:"Назначение задачи"
|
||||
branch featureA
|
||||
commit type:HIGHLIGHT tag:"Назначение подзадачи"
|
||||
branch featureA1
|
||||
|
||||
commit
|
||||
checkout test
|
||||
merge develop
|
||||
checkout featureA
|
||||
commit
|
||||
branch featureA2
|
||||
commit
|
||||
|
||||
commit
|
||||
checkout featureA
|
||||
merge featureA2
|
||||
merge featureA1
|
||||
checkout develop
|
||||
merge featureA
|
||||
|
||||
|
||||
|
||||
checkout develop
|
||||
checkout test
|
||||
merge develop
|
||||
checkout main
|
||||
merge test
|
||||
|
||||
|
||||
```
|
||||
### Ветки, на которых делается сборка
|
||||
Основная ветка main используется только для размещения на сервере прод
|
||||
test - ветка для тестового сервера
|
||||
|
||||
|
||||
### Ветки разработки
|
||||
develop - основная ветка разработчиков
|
||||
|
||||
Все ветки выше защищены от merdge в соответствиями с ролями участников проекта
|
||||
|
||||
#### Ветки задач
|
||||
Формируются по принципу id_Задачи_краткое описание
|
||||
Id задачи находится во внутреннем GIT
|
||||
|
||||
|
||||
После того, как задача выполнена, разработчик создает PULL Request в ветку DEVELOP. НЕ ЗАБЫВАЕМ кратко описывать что сделано и есть-ли какие-то проблемы. НУ или крепить ссылку на задачу, по которой велись работы
|
||||
|
||||
Остальные участники проекта проверяют предложенные исправления и пишут на них рецензии.
|
||||
|
||||
Если разработчик не согласен с предлагаемыми изменениями, он должен написать причину своего несогласия.
|
||||
|
||||
В случае принятия или по своему усмотрению (крайний случай) ответственный производит merdge.
|
||||
|
||||
На ветке разработки производится апдейт версии, после чего команде следует приступать к другим задачам, производя ветвление от ветки разработки.
|
||||
|
||||
Сборку проекта следует производить на ветках серверов.
|
||||
|
||||
#### Хотфиксы
|
||||
Правила аналогичны веткам задач.
|
||||
|
||||
|
||||
## Gitignore
|
||||
В репозиторий не должны попадать файлы виртуального окружения, файлы модулей и прочего.
|
||||
|
||||
По возможности, следует исключать попадание и иных статических файлов, если их наличие не влияет на работу проекта.
|
||||
@@ -1,96 +0,0 @@
|
||||
# Спецификация организации проекта Vue
|
||||
Инструменты разработки
|
||||
* Vscode
|
||||
Инструмент проверки кода
|
||||
* ESLint
|
||||
|
||||
|
||||
|
||||
## Спецификации разработки
|
||||
### 1 Соглашения об именах для папок, файлов и компонентов
|
||||
1. Для компонентов используем соглашение об именах (PascalCase), начинающееся с заглавных букв.
|
||||
2. В дочерние компоненты, жестко привязанным к родителю, добавляем вперед название родительского компонента (РодительДочерний)
|
||||
3. Для не являющихся компонентами, используем kebab-case, начинающиеся с строчных букв (если не получается обойтись одним словом).
|
||||
|
||||
### 2 Формат файла UTF-8
|
||||
|
||||
### 3 Требования к названиям:
|
||||
|
||||
1. Стараемся избегать использования непонятного в названиях и используем английские слова, передающие смысл. Пишем правильно (если что, онлайн-переводчик не сложно запустить)
|
||||
2. Внутри методов допустимо использовать переменные, не несущие в своем названии смысла (arr, ob) для перебора какого-то массива или объекта, но на коротких дистанциях. НЕ совсем правильно, но удобно.
|
||||
|
||||
3. Названия для переменных
|
||||
* Верблюжий регистр, начиная с типа данных в нижнем регистре
|
||||
* Тип числа начинается с n,
|
||||
- [x] строка - **s**,
|
||||
- [x] логический - **b**,
|
||||
- [x] объект - **o**,
|
||||
- [x] массив - **a**.
|
||||
|
||||
Например: nAge = 29, sName = "Jone".
|
||||
|
||||
### 4. Название функции
|
||||
* Верблюжий регистр, соглашение об именах первой буквы в нижнем регистре
|
||||
* По типу операции + объекту операции
|
||||
Типы операций следующие:
|
||||
- [x] add (добавить),
|
||||
- [x] change/edit/set (изменить),
|
||||
- [x] del (удалить),
|
||||
- [x] get (получить),
|
||||
- [x] search/find/filter (поиск),
|
||||
- [x] load (загрузка)
|
||||
- [x] check (проверка),
|
||||
- [x] reset (сброс)
|
||||
|
||||
### 4. Спецификация структуры файла VUE:
|
||||
1. Порядок оформления:
|
||||
* template
|
||||
* script
|
||||
* style
|
||||
2. PROPS должны быть подробно определены:
|
||||
|
||||
```
|
||||
props: {
|
||||
sStatus: {
|
||||
type: String,
|
||||
required: true,
|
||||
defaut:""
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
3. Характеристики функциональных элементов:
|
||||
* Элементы с несколькими атрибутами записываем в несколько строк, по одной строке для каждого атрибута. (чтобы облегчить чтение)
|
||||
|
||||
```
|
||||
<my-component
|
||||
:data="data"
|
||||
:class="name"
|
||||
@click="..."
|
||||
....
|
||||
...
|
||||
...
|
||||
.........
|
||||
>
|
||||
```
|
||||
|
||||
! Если атрибутов немного и это не мешает чтению, допускается писать и в строку -
|
||||
### 5. Спецификация комментариев.
|
||||
Заполняем комментарий в следующих случаях:
|
||||
* Инструкции по использованию компонентов и функций
|
||||
* Описание важных/сложных функций функций
|
||||
* Больше комментариев - лучше для понимания.
|
||||
|
||||
|
||||
### 6. Дополнительно
|
||||
* Стараемся держать код в чистоте
|
||||
- неиспользуемого быть не должно
|
||||
- не забываем проверять свой код на console.log перед отправкой на слияние веток
|
||||
- Экономим теги, будто их мало и редко выдают на отдел небольшими порциями.
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
### Шаблон страницы
|
||||
|
||||
Пример использования верстки
|
||||
|
||||
```
|
||||
<v-row no-gutters class="gap flex-column">
|
||||
<v-col lg=2 class='bg-red w100'>
|
||||
1
|
||||
</v-col>
|
||||
<v-col class="d-flex flex-column">
|
||||
<v-row no-gutters class="gap">
|
||||
<v-col lg=9 class="d-flex flex-column">
|
||||
<v-row no-gutters class="gap flex-column">
|
||||
<v-col class=" d-flex flex-column">
|
||||
<v-row no-gutters class="gap">
|
||||
<v-col class="bg-green">1</v-col>
|
||||
<v-col class="bg-orange">2</v-col>
|
||||
</v-row>
|
||||
</v-col>
|
||||
<v-col class=" d-flex flex-column">
|
||||
<v-row no-gutters class="gap">
|
||||
<v-col class="bg-purple">1</v-col>
|
||||
<v-col class="bg-green">2</v-col>
|
||||
</v-row>
|
||||
</v-col>
|
||||
</v-row>
|
||||
</v-col>
|
||||
<v-col class="bg-yellow">2</v-col>
|
||||
</v-row>
|
||||
</v-col>
|
||||
<v-col lg=2 class="bg-grey w100">
|
||||
3
|
||||
</v-col>
|
||||
</v-row>
|
||||
```
|
||||
@@ -0,0 +1,746 @@
|
||||
import { withMermaid } from 'vitepress-plugin-mermaid';
|
||||
|
||||
export default withMermaid({
|
||||
themeConfig: {
|
||||
search: {
|
||||
provider: 'local'
|
||||
},
|
||||
sidebar: [
|
||||
{
|
||||
text: 'Структура',
|
||||
collapsed: false,
|
||||
items: [
|
||||
{
|
||||
"text": "App",
|
||||
"link": "/src/App"
|
||||
},
|
||||
{
|
||||
"text": "components",
|
||||
"collapsed": true,
|
||||
"items": [
|
||||
{
|
||||
"text": "CountDown",
|
||||
"link": "/src/components/CountDown"
|
||||
},
|
||||
{
|
||||
"text": "UI",
|
||||
"collapsed": true,
|
||||
"items": [
|
||||
{
|
||||
"text": "Auth-form",
|
||||
"link": "/src/components/UI/Auth-form"
|
||||
},
|
||||
{
|
||||
"text": "NewsCard",
|
||||
"link": "/src/components/UI/NewsCard"
|
||||
},
|
||||
{
|
||||
"text": "PatternTabs",
|
||||
"link": "/src/components/UI/PatternTabs"
|
||||
},
|
||||
{
|
||||
"text": "SearcEmployess",
|
||||
"link": "/src/components/UI/SearcEmployess"
|
||||
},
|
||||
{
|
||||
"text": "Timer",
|
||||
"link": "/src/components/UI/Timer"
|
||||
},
|
||||
{
|
||||
"text": "aboutportal",
|
||||
"collapsed": true,
|
||||
"items": [
|
||||
{
|
||||
"text": "card-feedback",
|
||||
"link": "/src/components/UI/aboutportal/card-feedback"
|
||||
},
|
||||
{
|
||||
"text": "card-top-comment",
|
||||
"link": "/src/components/UI/aboutportal/card-top-comment"
|
||||
},
|
||||
{
|
||||
"text": "card-total",
|
||||
"link": "/src/components/UI/aboutportal/card-total"
|
||||
},
|
||||
{
|
||||
"text": "card_top_comment",
|
||||
"collapsed": true,
|
||||
"items": [
|
||||
{
|
||||
"text": "card-comment",
|
||||
"link": "/src/components/UI/aboutportal/card_top_comment/card-comment"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"text": "feedmodul",
|
||||
"link": "/src/components/UI/aboutportal/feedmodul"
|
||||
},
|
||||
{
|
||||
"text": "line-chart",
|
||||
"link": "/src/components/UI/aboutportal/line-chart"
|
||||
},
|
||||
{
|
||||
"text": "pattern-card-feed",
|
||||
"link": "/src/components/UI/aboutportal/pattern-card-feed"
|
||||
},
|
||||
{
|
||||
"text": "pattern-card",
|
||||
"link": "/src/components/UI/aboutportal/pattern-card"
|
||||
},
|
||||
{
|
||||
"text": "portal-traffic",
|
||||
"link": "/src/components/UI/aboutportal/portal-traffic"
|
||||
},
|
||||
{
|
||||
"text": "rating-page",
|
||||
"link": "/src/components/UI/aboutportal/rating-page"
|
||||
},
|
||||
{
|
||||
"text": "toolbar-filter",
|
||||
"link": "/src/components/UI/aboutportal/toolbar-filter"
|
||||
},
|
||||
{
|
||||
"text": "tooltip-ico",
|
||||
"link": "/src/components/UI/aboutportal/tooltip-ico"
|
||||
},
|
||||
{
|
||||
"text": "tooltip-user",
|
||||
"link": "/src/components/UI/aboutportal/tooltip-user"
|
||||
},
|
||||
{
|
||||
"text": "top-user",
|
||||
"link": "/src/components/UI/aboutportal/top-user"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"text": "date-select",
|
||||
"link": "/src/components/UI/date-select"
|
||||
},
|
||||
{
|
||||
"text": "defaultportal",
|
||||
"collapsed": true,
|
||||
"items": [
|
||||
{
|
||||
"text": "page-counter",
|
||||
"link": "/src/components/UI/defaultportal/page-counter"
|
||||
},
|
||||
{
|
||||
"text": "uploading-file",
|
||||
"link": "/src/components/UI/defaultportal/uploading-file"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"text": "feedback",
|
||||
"collapsed": true,
|
||||
"items": [
|
||||
{
|
||||
"text": "feedstar-like",
|
||||
"link": "/src/components/UI/feedback/feedstar-like"
|
||||
},
|
||||
{
|
||||
"text": "statistik-like",
|
||||
"link": "/src/components/UI/feedback/statistik-like"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"text": "fiousercard",
|
||||
"collapsed": true,
|
||||
"items": [
|
||||
{
|
||||
"text": "icoUser",
|
||||
"link": "/src/components/UI/fiousercard/icoUser"
|
||||
},
|
||||
{
|
||||
"text": "infoUserCard",
|
||||
"link": "/src/components/UI/fiousercard/infoUserCard"
|
||||
},
|
||||
{
|
||||
"text": "listUser",
|
||||
"link": "/src/components/UI/fiousercard/listUser"
|
||||
},
|
||||
{
|
||||
"text": "onlineUsers",
|
||||
"link": "/src/components/UI/fiousercard/onlineUsers"
|
||||
},
|
||||
{
|
||||
"text": "vcardUser",
|
||||
"link": "/src/components/UI/fiousercard/vcardUser"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"text": "index",
|
||||
"link": "/src/components/UI/index"
|
||||
},
|
||||
{
|
||||
"text": "my-helper",
|
||||
"link": "/src/components/UI/my-helper"
|
||||
},
|
||||
{
|
||||
"text": "tooltip-number",
|
||||
"link": "/src/components/UI/tooltip-number"
|
||||
},
|
||||
{
|
||||
"text": "tooltip-text",
|
||||
"link": "/src/components/UI/tooltip-text"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"text": "about_inspection",
|
||||
"collapsed": true,
|
||||
"items": [
|
||||
{
|
||||
"text": "contacts",
|
||||
"collapsed": true,
|
||||
"items": [
|
||||
{
|
||||
"text": "ContactInfo",
|
||||
"link": "/src/components/about_inspection/contacts/ContactInfo"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"text": "general_information",
|
||||
"collapsed": true,
|
||||
"items": [
|
||||
{
|
||||
"text": "GeneralInformation",
|
||||
"link": "/src/components/about_inspection/general_information/GeneralInformation"
|
||||
},
|
||||
{
|
||||
"text": "GeneralInformationSize",
|
||||
"link": "/src/components/about_inspection/general_information/GeneralInformationSize"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"text": "open_vacancies",
|
||||
"collapsed": true,
|
||||
"items": [
|
||||
{
|
||||
"text": "OpenVacancies",
|
||||
"link": "/src/components/about_inspection/open_vacancies/OpenVacancies"
|
||||
},
|
||||
{
|
||||
"text": "ResponseVacancies",
|
||||
"link": "/src/components/about_inspection/open_vacancies/ResponseVacancies"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"text": "structure",
|
||||
"collapsed": true,
|
||||
"items": [
|
||||
{
|
||||
"text": "StructureInspection",
|
||||
"link": "/src/components/about_inspection/structure/StructureInspection"
|
||||
},
|
||||
{
|
||||
"text": "StructureInspectionRow",
|
||||
"link": "/src/components/about_inspection/structure/StructureInspectionRow"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"text": "calendar_of_events",
|
||||
"collapsed": true,
|
||||
"items": [
|
||||
{
|
||||
"text": "BigCalendar",
|
||||
"link": "/src/components/calendar_of_events/BigCalendar"
|
||||
},
|
||||
{
|
||||
"text": "UI_calendar",
|
||||
"collapsed": true,
|
||||
"items": [
|
||||
{
|
||||
"text": "calendarFull",
|
||||
"link": "/src/components/calendar_of_events/UI_calendar/calendarFull"
|
||||
},
|
||||
{
|
||||
"text": "dialogCreate",
|
||||
"link": "/src/components/calendar_of_events/UI_calendar/dialogCreate"
|
||||
},
|
||||
{
|
||||
"text": "periodEvents",
|
||||
"link": "/src/components/calendar_of_events/UI_calendar/periodEvents"
|
||||
},
|
||||
{
|
||||
"text": "reminderEvent",
|
||||
"link": "/src/components/calendar_of_events/UI_calendar/reminderEvent"
|
||||
},
|
||||
{
|
||||
"text": "timeSelect",
|
||||
"link": "/src/components/calendar_of_events/UI_calendar/timeSelect"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"text": "calendar-create-select",
|
||||
"link": "/src/components/calendar_of_events/calendar-create-select"
|
||||
},
|
||||
{
|
||||
"text": "calendar-create",
|
||||
"link": "/src/components/calendar_of_events/calendar-create"
|
||||
},
|
||||
{
|
||||
"text": "calendar-my",
|
||||
"link": "/src/components/calendar_of_events/calendar-my"
|
||||
},
|
||||
{
|
||||
"text": "event-calendar",
|
||||
"link": "/src/components/calendar_of_events/event-calendar"
|
||||
},
|
||||
{
|
||||
"text": "event-create",
|
||||
"link": "/src/components/calendar_of_events/event-create"
|
||||
},
|
||||
{
|
||||
"text": "event-dialog-edit-participant",
|
||||
"link": "/src/components/calendar_of_events/event-dialog-edit-participant"
|
||||
},
|
||||
{
|
||||
"text": "event-dialog-edit",
|
||||
"link": "/src/components/calendar_of_events/event-dialog-edit"
|
||||
},
|
||||
{
|
||||
"text": "event-dialog-info",
|
||||
"link": "/src/components/calendar_of_events/event-dialog-info"
|
||||
},
|
||||
{
|
||||
"text": "event-dialog",
|
||||
"link": "/src/components/calendar_of_events/event-dialog"
|
||||
},
|
||||
{
|
||||
"text": "load-ical",
|
||||
"link": "/src/components/calendar_of_events/load-ical"
|
||||
},
|
||||
{
|
||||
"text": "load-ical1",
|
||||
"link": "/src/components/calendar_of_events/load-ical1"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"text": "cardLike",
|
||||
"link": "/src/components/cardLike"
|
||||
},
|
||||
{
|
||||
"text": "carousel-list",
|
||||
"link": "/src/components/carousel-list"
|
||||
},
|
||||
{
|
||||
"text": "carousel-numbers",
|
||||
"link": "/src/components/carousel-numbers"
|
||||
},
|
||||
{
|
||||
"text": "dialog-search",
|
||||
"link": "/src/components/dialog-search"
|
||||
},
|
||||
{
|
||||
"text": "digital-letna",
|
||||
"link": "/src/components/digital-letna"
|
||||
},
|
||||
{
|
||||
"text": "graph",
|
||||
"collapsed": true,
|
||||
"items": [
|
||||
{
|
||||
"text": "chartConfig",
|
||||
"link": "/src/components/graph/chartConfig"
|
||||
},
|
||||
{
|
||||
"text": "line-graph",
|
||||
"link": "/src/components/graph/line-graph"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"text": "load-round",
|
||||
"link": "/src/components/load-round"
|
||||
},
|
||||
{
|
||||
"text": "news-crossroad",
|
||||
"link": "/src/components/news-crossroad"
|
||||
},
|
||||
{
|
||||
"text": "news-full",
|
||||
"link": "/src/components/news-full"
|
||||
},
|
||||
{
|
||||
"text": "news-home",
|
||||
"link": "/src/components/news-home"
|
||||
},
|
||||
{
|
||||
"text": "secret",
|
||||
"collapsed": true,
|
||||
"items": [
|
||||
{
|
||||
"text": "SmallTimer",
|
||||
"link": "/src/components/secret/SmallTimer"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"text": "testing",
|
||||
"collapsed": true,
|
||||
"items": [
|
||||
{
|
||||
"text": "BodyDetailTesting",
|
||||
"link": "/src/components/testing/BodyDetailTesting"
|
||||
},
|
||||
{
|
||||
"text": "CatalogTest",
|
||||
"link": "/src/components/testing/CatalogTest"
|
||||
},
|
||||
{
|
||||
"text": "DetailCardTest",
|
||||
"link": "/src/components/testing/DetailCardTest"
|
||||
},
|
||||
{
|
||||
"text": "HeaderDetailTesting",
|
||||
"link": "/src/components/testing/HeaderDetailTesting"
|
||||
},
|
||||
{
|
||||
"text": "QuestionBlock",
|
||||
"link": "/src/components/testing/QuestionBlock"
|
||||
},
|
||||
{
|
||||
"text": "TestResults",
|
||||
"link": "/src/components/testing/TestResults"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"text": "vote",
|
||||
"collapsed": true,
|
||||
"items": [
|
||||
{
|
||||
"text": "ConstructorVote",
|
||||
"collapsed": true,
|
||||
"items": [
|
||||
{
|
||||
"text": "AnswerList",
|
||||
"link": "/src/components/vote/ConstructorVote/AnswerList"
|
||||
},
|
||||
{
|
||||
"text": "CreatedVote",
|
||||
"link": "/src/components/vote/ConstructorVote/CreatedVote"
|
||||
},
|
||||
{
|
||||
"text": "MainInfo",
|
||||
"link": "/src/components/vote/ConstructorVote/MainInfo"
|
||||
},
|
||||
{
|
||||
"text": "NewQuestion",
|
||||
"link": "/src/components/vote/ConstructorVote/NewQuestion"
|
||||
},
|
||||
{
|
||||
"text": "QuestionHeader",
|
||||
"link": "/src/components/vote/ConstructorVote/QuestionHeader"
|
||||
},
|
||||
{
|
||||
"text": "QuestionItem",
|
||||
"link": "/src/components/vote/ConstructorVote/QuestionItem"
|
||||
},
|
||||
{
|
||||
"text": "QuestionSettings",
|
||||
"link": "/src/components/vote/ConstructorVote/QuestionSettings"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"text": "CurrentVote",
|
||||
"link": "/src/components/vote/CurrentVote"
|
||||
},
|
||||
{
|
||||
"text": "NonVoteHappy",
|
||||
"link": "/src/components/vote/NonVoteHappy"
|
||||
},
|
||||
{
|
||||
"text": "NonVoteSad",
|
||||
"link": "/src/components/vote/NonVoteSad"
|
||||
},
|
||||
{
|
||||
"text": "NoneVote",
|
||||
"link": "/src/components/vote/NoneVote"
|
||||
},
|
||||
{
|
||||
"text": "VoteAdmin",
|
||||
"link": "/src/components/vote/VoteAdmin"
|
||||
},
|
||||
{
|
||||
"text": "VoteAnimation",
|
||||
"link": "/src/components/vote/VoteAnimation"
|
||||
},
|
||||
{
|
||||
"text": "VoteCard",
|
||||
"link": "/src/components/vote/VoteCard"
|
||||
},
|
||||
{
|
||||
"text": "VoteConstructor",
|
||||
"link": "/src/components/vote/VoteConstructor"
|
||||
},
|
||||
{
|
||||
"text": "VoteForm",
|
||||
"link": "/src/components/vote/VoteForm"
|
||||
},
|
||||
{
|
||||
"text": "VoteResult",
|
||||
"link": "/src/components/vote/VoteResult"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"text": "layouts",
|
||||
"collapsed": true,
|
||||
"items": [
|
||||
{
|
||||
"text": "default",
|
||||
"collapsed": true,
|
||||
"items": [
|
||||
{
|
||||
"text": "AdminMenu",
|
||||
"link": "/src/layouts/default/AdminMenu"
|
||||
},
|
||||
{
|
||||
"text": "DefaultPortal",
|
||||
"link": "/src/layouts/default/DefaultPortal"
|
||||
},
|
||||
{
|
||||
"text": "alertDefault",
|
||||
"link": "/src/layouts/default/alertDefault"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"text": "main",
|
||||
"link": "/src/main"
|
||||
},
|
||||
{
|
||||
"text": "plugins",
|
||||
"collapsed": true,
|
||||
"items": [
|
||||
{
|
||||
"text": "index",
|
||||
"link": "/src/plugins/index"
|
||||
},
|
||||
{
|
||||
"text": "vuetify",
|
||||
"link": "/src/plugins/vuetify"
|
||||
},
|
||||
{
|
||||
"text": "webfontloader",
|
||||
"link": "/src/plugins/webfontloader"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"text": "router",
|
||||
"collapsed": true,
|
||||
"items": [
|
||||
{
|
||||
"text": "index",
|
||||
"link": "/src/router/index"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"text": "store",
|
||||
"collapsed": true,
|
||||
"items": [
|
||||
{
|
||||
"text": "AboutPortalFilter",
|
||||
"link": "/src/store/AboutPortalFilter"
|
||||
},
|
||||
{
|
||||
"text": "AccountStore",
|
||||
"link": "/src/store/AccountStore"
|
||||
},
|
||||
{
|
||||
"text": "MainmenuStore",
|
||||
"link": "/src/store/MainmenuStore"
|
||||
},
|
||||
{
|
||||
"text": "WeekendsStore",
|
||||
"link": "/src/store/WeekendsStore"
|
||||
},
|
||||
{
|
||||
"text": "app",
|
||||
"link": "/src/store/app"
|
||||
},
|
||||
{
|
||||
"text": "index",
|
||||
"link": "/src/store/index"
|
||||
},
|
||||
{
|
||||
"text": "seAlertStore",
|
||||
"link": "/src/store/UseAlertStore"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"text": "tests",
|
||||
"collapsed": true,
|
||||
"items": [
|
||||
{
|
||||
"text": "App.test",
|
||||
"link": "/src/tests/App.test"
|
||||
},
|
||||
{
|
||||
"text": "CarouselList.test",
|
||||
"link": "/src/tests/CarouselList.test"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"text": "utils",
|
||||
"collapsed": true,
|
||||
"items": [
|
||||
{
|
||||
"text": "axios-api",
|
||||
"link": "/src/utils/axios-api"
|
||||
},
|
||||
{
|
||||
"text": "universal_functions",
|
||||
"link": "/src/utils/universal_functions"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"text": "views",
|
||||
"collapsed": true,
|
||||
"items": [
|
||||
{
|
||||
"text": "AboutInspectionPage",
|
||||
"link": "/src/views/AboutInspectionPage"
|
||||
},
|
||||
{
|
||||
"text": "AboutPortalPage",
|
||||
"link": "/src/views/AboutPortalPage"
|
||||
},
|
||||
{
|
||||
"text": "FAQPage",
|
||||
"link": "/src/views/FAQPage"
|
||||
},
|
||||
{
|
||||
"text": "FeedbackPage",
|
||||
"link": "/src/views/FeedbackPage"
|
||||
},
|
||||
{
|
||||
"text": "FnsHol",
|
||||
"link": "/src/views/FnsHol"
|
||||
},
|
||||
{
|
||||
"text": "HomePage",
|
||||
"link": "/src/views/HomePage"
|
||||
},
|
||||
{
|
||||
"text": "LaborProtection",
|
||||
"link": "/src/views/LaborProtection"
|
||||
},
|
||||
{
|
||||
"text": "NewsPage",
|
||||
"link": "/src/views/NewsPage"
|
||||
},
|
||||
{
|
||||
"text": "ProvidingActivitiesPage",
|
||||
"link": "/src/views/ProvidingActivitiesPage"
|
||||
},
|
||||
{
|
||||
"text": "SecurityPage",
|
||||
"link": "/src/views/SecurityPage"
|
||||
},
|
||||
{
|
||||
"text": "StructurePage",
|
||||
"link": "/src/views/StructurePage"
|
||||
},
|
||||
{
|
||||
"text": "TestHomePage",
|
||||
"link": "/src/views/TestHomePage"
|
||||
},
|
||||
{
|
||||
"text": "Vote",
|
||||
"link": "/src/views/Vote"
|
||||
},
|
||||
{
|
||||
"text": "VoteHomePage",
|
||||
"link": "/src/views/VoteHomePage"
|
||||
},
|
||||
{
|
||||
"text": "nested_view",
|
||||
"collapsed": true,
|
||||
"items": [
|
||||
{
|
||||
"text": "o_OKiB",
|
||||
"link": "/src/views/nested_view/o_OKiB"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"text": "safety",
|
||||
"collapsed": true,
|
||||
"items": [
|
||||
{
|
||||
"text": "ChaptersSafety",
|
||||
"link": "/src/views/safety/ChaptersSafety"
|
||||
},
|
||||
{
|
||||
"text": "DocumentationSafety",
|
||||
"link": "/src/views/safety/DocumentationSafety"
|
||||
},
|
||||
{
|
||||
"text": "MainInfoSafety",
|
||||
"link": "/src/views/safety/MainInfoSafety"
|
||||
},
|
||||
{
|
||||
"text": "TestSafety",
|
||||
"link": "/src/views/safety/TestSafety"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"text": "secret",
|
||||
"collapsed": true,
|
||||
"items": [
|
||||
{
|
||||
"text": "SecretPage",
|
||||
"link": "/src/views/secret/SecretPage"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
text: 'Гайды',
|
||||
collapsed: true,
|
||||
items: [
|
||||
{ text: 'Как установить', link: '/guides/install' },
|
||||
{ text: 'Как использовать', link: '/guides/usage' },
|
||||
{ text: 'Правила комитов', link: '/guides/commits' }
|
||||
,
|
||||
{ text: 'Тесты', link: '/tests' },
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
mermaid: {
|
||||
// refer https://mermaid.js.org/config/setup/modules/mermaidAPI.html#mermaidapi-configuration-defaults for options
|
||||
},
|
||||
// optionally set additional config for plugin itself with MermaidPluginConfig
|
||||
mermaidPlugin: {
|
||||
class: 'mermaid my-class', // set additional css classes for parent container
|
||||
},});
|
||||
@@ -0,0 +1,25 @@
|
||||
# CatalogTest
|
||||
|
||||
### Карточка где буду отрисовываться тесты в цикле
|
||||
|
||||
## Описание пропсов
|
||||
|
||||
| Пропс | Тип | Значение по умолчанию | Комментарий |
|
||||
|-------|-----|-----------------------|-------------|
|
||||
| `title` | `String` | `'Не забыть передать тайтл сюда!'` | нет комментария |
|
||||
| `activeTab` | `Number` | `0` | нет комментария |
|
||||
| `testingCard` | `Array` | `() => []` | нет комментария |
|
||||
|
||||
|
||||
## Пример использования
|
||||
|
||||
```vue
|
||||
import CatalogTest from '@/components/components/testing/CatalogTest';
|
||||
```
|
||||
|
||||
```vue
|
||||
<CatalogTest />
|
||||
```
|
||||
|
||||
---
|
||||
> Документация сгенерирована автоматически.
|
||||
@@ -0,0 +1,18 @@
|
||||
# VoteConstructor
|
||||
|
||||
### Основная информация
|
||||
|
||||
|
||||
|
||||
## Пример использования
|
||||
|
||||
```vue
|
||||
import VoteConstructor from '@/components/components/vote/VoteConstructor';
|
||||
```
|
||||
|
||||
```vue
|
||||
<VoteConstructor />
|
||||
```
|
||||
|
||||
---
|
||||
> Документация сгенерирована автоматически.
|
||||
@@ -0,0 +1,22 @@
|
||||
module.exports = {
|
||||
// rootDir: '../',
|
||||
testEnvironment: 'jest-environment-jsdom',
|
||||
roots: ['/app/src/front/src'],
|
||||
setupFilesAfterEnv: ['/app/documentation/jest.setup.js'],
|
||||
transform: {
|
||||
'^.+\\.vue$': '@vue/vue3-jest',
|
||||
'^.+\\.mjs$': 'babel-jest',
|
||||
'^.+\\.js$': 'babel-jest',
|
||||
'\\.(png|jpe?g|gif|svg)$': 'jest-transform-stub',
|
||||
},
|
||||
moduleFileExtensions: ['js', 'json', 'vue', 'mjs'],
|
||||
moduleNameMapper: {
|
||||
'^@/(.*)$': '/app/src/front/src/$1',
|
||||
},
|
||||
transformIgnorePatterns: ['/node_modules/(?!(vuetify|quasar)/)'],
|
||||
collectCoverage: true,
|
||||
collectCoverageFrom: ['/app/src/front/src/**/*.{js,vue}'],
|
||||
coveragePathIgnorePatterns: ['/documentation/'],
|
||||
coverageReporters: ['json', 'html'],
|
||||
coverageDirectory: '/app/documentation/docs/public/test-coverage',
|
||||
};
|
||||
@@ -0,0 +1,12 @@
|
||||
[MASTER]
|
||||
load-plugins=pylint_django
|
||||
ignore-paths=.*/migrations/*
|
||||
init-hook='import sys; sys.path.append("/back/"); import os; os.environ["DJANGO_SETTINGS_MODULE"] = "portal.settings"; import django; django.setup()'
|
||||
|
||||
[FORMAT]
|
||||
# Настройки форматирования
|
||||
max-line-length=100
|
||||
|
||||
[MESSAGES CONTROL]
|
||||
# Отключение определенных сообщений
|
||||
disable=C0114 # Missing module docstring
|
||||
Vendored
+22
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Python: Django (Docker)",
|
||||
"type": "python",
|
||||
"request": "launch",
|
||||
"module": "manage",
|
||||
"args": [
|
||||
"runserver",
|
||||
"0.0.0.0:8000"
|
||||
],
|
||||
"django": true,
|
||||
"justMyCode": true,
|
||||
"env": {
|
||||
"PYTHONPATH": "${workspaceFolder}"
|
||||
},
|
||||
"console": "integratedTerminal",
|
||||
|
||||
}
|
||||
]
|
||||
}
|
||||
File renamed without changes.
@@ -14,6 +14,9 @@ class InspectionDirectionsAdmin(admin.ModelAdmin):
|
||||
def get_queryset(self, request):
|
||||
qs = super().get_queryset(request)
|
||||
qs = qs.filter(department__isnull=True)
|
||||
|
||||
|
||||
|
||||
return qs
|
||||
|
||||
class VacanciesAdmin(admin.ModelAdmin):
|
||||
|
||||
@@ -13,15 +13,22 @@ class GetStateSize(ListAPIView):
|
||||
def get(self, request):
|
||||
state_size ={}
|
||||
try:
|
||||
|
||||
|
||||
state_size = StateSizeSerializer(StateSize.objects.latest('date_created')).data
|
||||
except Exception as e:
|
||||
pass
|
||||
|
||||
|
||||
|
||||
return Response(state_size)
|
||||
|
||||
|
||||
class GetFactSize(ListAPIView):
|
||||
def get(self, request):
|
||||
|
||||
|
||||
|
||||
fact_size = {}
|
||||
try:
|
||||
fact_size = FactSizeSerializer(FactSize.objects.latest('date_created')).data
|
||||
|
||||
@@ -4,4 +4,5 @@ from django.apps import AppConfig
|
||||
class AccountsConfig(AppConfig):
|
||||
default_auto_field = 'django.db.models.BigAutoField'
|
||||
name = 'accounts'
|
||||
|
||||
verbose_name='Аккаунты Портала'
|
||||
@@ -19,6 +19,10 @@ class getuserAPIView(APIView):
|
||||
Результат: Выдает все данные о пользователе
|
||||
Если дать дополнительный параметр fullinfo = True, то будет выдаваться информация с комиссиями и ответсвенностью
|
||||
"""
|
||||
|
||||
|
||||
|
||||
|
||||
resp = None
|
||||
fullinfo = request.query_params.get('fullinfo')
|
||||
queryset = DictEmployee.objects.get(login=request.query_params.get('userlogin'))
|
||||
|
||||
@@ -5,6 +5,7 @@ from django.conf import settings
|
||||
# from enum import Enum
|
||||
from ckeditor_uploader.fields import RichTextUploadingField
|
||||
|
||||
|
||||
# class CalendarEventsName(models.Model):
|
||||
# """ Глобавльное название календаря"""
|
||||
# name=models.CharField(max_length=300, verbose_name='Название Календаря')
|
||||
@@ -12,6 +13,7 @@ from ckeditor_uploader.fields import RichTextUploadingField
|
||||
|
||||
|
||||
|
||||
|
||||
# class CalendarEvents(models.Model):
|
||||
# """ Основные данные по событиям"""
|
||||
# name=models.CharField(max_length=300, verbose_name='Название события')
|
||||
@@ -47,7 +49,7 @@ from ckeditor_uploader.fields import RichTextUploadingField
|
||||
|
||||
# Модели(Таблицы) для хранения календаря
|
||||
class Calendar(models.Model):
|
||||
author = models.ForeignKey(DictEmployee, on_delete=models.PROTECT, verbose_name='Автор календаря')
|
||||
author = models.ForeignKey(DictEmployee, on_delete=models.PROTECT, null=True, verbose_name='Автор календаря')
|
||||
cl_name = models.CharField(max_length=300, verbose_name='Название')
|
||||
cl_color = models.CharField(max_length=300, verbose_name='Цвет', null=True)
|
||||
cl_descr = models.CharField(max_length=300, verbose_name='Описание')
|
||||
@@ -83,6 +85,7 @@ class Event(models.Model):
|
||||
description = RichTextUploadingField(null=True, blank= True, verbose_name='Описание события')
|
||||
allday = models.BooleanField(default=False, verbose_name='Событие на целый день')
|
||||
|
||||
|
||||
class Meta:
|
||||
verbose_name = "Событие календаря"
|
||||
verbose_name_plural = "События календаря"
|
||||
|
||||
@@ -65,9 +65,11 @@ class CalendarParticipantsSerializerFullInfo(serializers.ModelSerializer):
|
||||
exclude = ['calendar']
|
||||
|
||||
|
||||
|
||||
class CalendarsSerializerForEventEdit(serializers.ModelSerializer):
|
||||
""" Сериализатор календарей для окна редактирования событий"""
|
||||
|
||||
|
||||
participant = CalendarParticipantsSerializerFullInfo(source="get_participants", many= True, read_only=True)
|
||||
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ from rest_framework_simplejwt.views import (
|
||||
|
||||
urlpatterns = [
|
||||
|
||||
|
||||
path('links/', CaorusAPIView.as_view(), name='CaorusAPIView'),
|
||||
|
||||
|
||||
|
||||
@@ -5,7 +5,6 @@ from django.conf import settings
|
||||
from ckeditor.fields import RichTextField
|
||||
from ckeditor_uploader.fields import RichTextUploadingField
|
||||
from datetime import date
|
||||
from vote.models import Vote
|
||||
from django.utils.timezone import now
|
||||
|
||||
class BaseSender(models.Model):
|
||||
@@ -37,11 +36,13 @@ class Links(models.Model):
|
||||
|
||||
class News(models.Model):
|
||||
title=models.CharField(max_length=255, verbose_name='Заголовок')
|
||||
|
||||
|
||||
|
||||
text= RichTextUploadingField(null=True, blank= True, verbose_name='Текст новости')
|
||||
cdate =models.DateTimeField(default=datetime.now, verbose_name='Дата создания')
|
||||
author = models.ForeignKey(settings.AUTH_USER_MODEL, editable=False, on_delete=models.PROTECT, verbose_name='Автор')
|
||||
link = models.ImageField(upload_to='newsimage/%Y/%m/%d', null=True, default="newsimage/default.jpg", verbose_name='Изображение')
|
||||
vote = models.ForeignKey(Vote, on_delete=models.CASCADE, null=True, blank=True)
|
||||
|
||||
class Meta:
|
||||
|
||||
|
||||
@@ -25,6 +25,8 @@ class LinkAPIView(ListAPIView):
|
||||
]
|
||||
"""
|
||||
permission_classes = (AllowAny,)
|
||||
|
||||
|
||||
serializer_class = LinkSerializer
|
||||
|
||||
|
||||
@@ -165,7 +167,7 @@ class CarouselsAPIView(ListAPIView):
|
||||
|
||||
result = CarouselsSerializer(queryset, many= True).data
|
||||
|
||||
manbrd = DictEmployee.objects.filter(birthdate__month=date.today().month, birthdate__day__gte=date.today().day).order_by('birthdate__day')
|
||||
manbrd = DictEmployee.objects.filter(birthdate__month=date.today().month, birthdate__day__gte=date.today().day, deleted=0).order_by('birthdate__day')
|
||||
dr_img = BaseSender.objects.update_or_create(name="День рождения", defaults={'name':"День рождения"})
|
||||
mess = ''
|
||||
if len(manbrd) > 0 :
|
||||
|
||||
Generated
+2804
File diff suppressed because it is too large.
Load diff
+32
-15
@@ -1,25 +1,42 @@
|
||||
from datetime import timedelta
|
||||
from dotenv import load_dotenv
|
||||
|
||||
import os
|
||||
dotenv_path = os.path.join(os.path.dirname(__file__), '.env')
|
||||
load_dotenv(dotenv_path)
|
||||
class Settings():
|
||||
|
||||
|
||||
class Settings:
|
||||
"""
|
||||
Настройки подключений - потом перенести
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
|
||||
self.secret_key='V7bvDZMztr3EU8S9g1Dipw'
|
||||
self.redis_hosts = [("127.0.0.1", 6379)]
|
||||
"""
|
||||
Настройки подключений - потом перенести
|
||||
"""
|
||||
self.secret_key = "V7bvDZMztr3EU8S9g1Dipw"
|
||||
self.redis_hosts = [f"{str(os.getenv('REDIS'))}:{str(os.getenv('REDIS_PORT'))}"]
|
||||
self.access_token_lifetime = timedelta(minutes=480)
|
||||
|
||||
self.refresh_token_lifetime = timedelta(days=1)
|
||||
|
||||
self.db = {
|
||||
'default':{
|
||||
'ENGINE': str(os.getenv('ENGINE')),
|
||||
'NAME': str(os.getenv('DBNAME')),
|
||||
'USER': str(os.getenv('USER')),
|
||||
'PASSWORD': str(os.getenv('PASSWORD')),
|
||||
'HOST': str(os.getenv('HOST')),
|
||||
'PORT': str(os.getenv('PORT')),
|
||||
"default": {
|
||||
"ENGINE": "django.db.backends.mysql",
|
||||
"NAME": os.getenv("DB_NAME"), # Имя базы данных
|
||||
"USER": os.getenv("DB_USER"), # Имя пользователя
|
||||
"PASSWORD": os.getenv("DB_PASSWORD"), # Пароль
|
||||
"HOST": os.getenv("DB_HOST"), # Хост
|
||||
"PORT": os.getenv("DB_INTERNAL_PORT"), # Порт
|
||||
}
|
||||
}
|
||||
|
||||
def foo1(self) -> None:
|
||||
"""
|
||||
Настройки - потом перенести
|
||||
"""
|
||||
return None
|
||||
|
||||
pass
|
||||
def foo2(self) -> None:
|
||||
"""
|
||||
Настройки подключений - потом перенести
|
||||
"""
|
||||
return None
|
||||
@@ -38,7 +38,12 @@ SWAGGER_SETTINGS = {
|
||||
}
|
||||
}
|
||||
}
|
||||
ALLOWED_HOSTS = ["*","portal-t",'portal9966']
|
||||
CSRF_TRUSTED_ORIGINS = [
|
||||
'http://localhost',
|
||||
'http://127.0.0.1',
|
||||
'http://yourdomain.com', # Add your production domain here
|
||||
]
|
||||
ALLOWED_HOSTS = ["*","portal-t",'portal9966','localhost','0.0.0.0']
|
||||
CHANNEL_LAYERS = {
|
||||
"default": {
|
||||
"BACKEND": "channels_redis.core.RedisChannelLayer",
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
[project]
|
||||
name = "portal"
|
||||
version = "0.1.0"
|
||||
description = ""
|
||||
authors = [
|
||||
{name = "Your Name",email = "you@example.com"}
|
||||
]
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10,<4.0"
|
||||
dependencies = [
|
||||
"anyio (>=4.8.0,<5.0.0)",
|
||||
"asgiref (>=3.8.1,<4.0.0)",
|
||||
"async-timeout (>=5.0.1,<6.0.0)",
|
||||
"attrs (>=25.1.0,<26.0.0)",
|
||||
"autobahn (>=24.4.2,<25.0.0)",
|
||||
"automat (>=24.8.1,<25.0.0)",
|
||||
"backports-tarfile (>=1.2.0,<2.0.0)",
|
||||
"build (==1.2.2.post1)",
|
||||
"cachecontrol (>=0.14.2,<0.15.0)",
|
||||
"certifi (>=2025.1.31,<2026.0.0)",
|
||||
"cffi (>=1.17.1,<2.0.0)",
|
||||
"channels (>=4.2.0,<5.0.0)",
|
||||
"channels-redis (>=4.2.1,<5.0.0)",
|
||||
"charset-normalizer (>=3.4.1,<4.0.0)",
|
||||
"cleo (>=2.1.0,<3.0.0)",
|
||||
"constantly (>=23.10.4,<24.0.0)",
|
||||
"crashtest (>=0.4.1,<0.5.0)",
|
||||
"cryptography (>=44.0.1,<45.0.0)",
|
||||
"daphne (>=4.1.2,<5.0.0)",
|
||||
"defusedxml (>=0.7.1,<0.8.0)",
|
||||
"distlib (>=0.3.9,<0.4.0)",
|
||||
"django (>=5.1.6,<6.0.0)",
|
||||
"django-ckeditor (>=6.7.2,<7.0.0)",
|
||||
"django-ckeditor-5 (>=0.2.17,<0.3.0)",
|
||||
"django-cors-headers (>=4.7.0,<5.0.0)",
|
||||
"django-filter (>=25.1,<26.0)",
|
||||
"django-grappelli (>=4.0.1,<5.0.0)",
|
||||
"django-js-asset (>=3.1.0,<4.0.0)",
|
||||
"django-templated-mail (>=1.1.1,<2.0.0)",
|
||||
"djangorestframework (>=3.15.2,<4.0.0)",
|
||||
"djangorestframework-simplejwt (>=5.5.0,<6.0.0)",
|
||||
"djoser (>=2.3.1,<3.0.0)",
|
||||
"drf-yasg (>=1.21.9,<2.0.0)",
|
||||
"dulwich (>=0.22.7,<0.23.0)",
|
||||
"et-xmlfile (>=2.0.0,<3.0.0)",
|
||||
"exceptiongroup (>=1.2.2,<2.0.0)",
|
||||
"fastjsonschema (>=2.21.1,<3.0.0)",
|
||||
"filelock (>=3.17.0,<4.0.0)",
|
||||
"findpython (>=0.6.2,<0.7.0)",
|
||||
"h11 (>=0.14.0,<0.15.0)",
|
||||
"httpcore (>=1.0.7,<2.0.0)",
|
||||
"httpx (>=0.28.1,<0.29.0)",
|
||||
"hyperlink (>=21.0.0,<22.0.0)",
|
||||
"idna (>=3.10,<4.0)",
|
||||
"importlib-metadata (>=8.6.1,<9.0.0)",
|
||||
"incremental (>=24.7.2,<25.0.0)",
|
||||
"inflection (>=0.5.1,<0.6.0)",
|
||||
"installer (>=0.7.0,<0.8.0)",
|
||||
"jaraco-classes (>=3.4.0,<4.0.0)",
|
||||
"jaraco-context (>=6.0.1,<7.0.0)",
|
||||
"jaraco-functools (>=4.1.0,<5.0.0)",
|
||||
"jeepney (>=0.9.0,<0.10.0)",
|
||||
"keyring (>=25.6.0,<26.0.0)",
|
||||
"markdown (>=3.7,<4.0)",
|
||||
"more-itertools (>=10.6.0,<11.0.0)",
|
||||
"msgpack (>=1.1.0,<2.0.0)",
|
||||
"mysqlclient (>=2.2.7,<3.0.0)",
|
||||
"numpy (>=2.2.3,<3.0.0)",
|
||||
"oauthlib (>=3.2.2,<4.0.0)",
|
||||
"openpyxl (>=3.1.5,<4.0.0)",
|
||||
"packaging (>=24.2,<25.0)",
|
||||
"pandas (>=2.2.3,<3.0.0)",
|
||||
"pbs-installer (>=2025.2.12,<2026.0.0)",
|
||||
"pillow (>=11.1.0,<12.0.0)",
|
||||
"pkginfo (>=1.12.1.2,<2.0.0.0)",
|
||||
"platformdirs (>=4.3.6,<5.0.0)",
|
||||
"pyasn1 (>=0.6.1,<0.7.0)",
|
||||
"pyasn1-modules (>=0.4.1,<0.5.0)",
|
||||
"pycparser (>=2.22,<3.0)",
|
||||
"pyopenssl (>=25.0.0,<26.0.0)",
|
||||
"pyproject-hooks (>=1.2.0,<2.0.0)",
|
||||
"python-dateutil (>=2.9.0.post0,<3.0.0)",
|
||||
"python3-openid (>=3.2.0,<4.0.0)",
|
||||
"pytz (>=2025.1,<2026.0)",
|
||||
"pyyaml (>=6.0.2,<7.0.0)",
|
||||
"rapidfuzz (>=3.12.1,<4.0.0)",
|
||||
"redis (>=5.2.1,<6.0.0)",
|
||||
"requests (>=2.32.3,<3.0.0)",
|
||||
"requests-oauthlib (>=2.0.0,<3.0.0)",
|
||||
"requests-toolbelt (>=1.0.0,<2.0.0)",
|
||||
"secretstorage (>=3.3.3,<4.0.0)",
|
||||
"service-identity (>=24.2.0,<25.0.0)",
|
||||
"shellingham (>=1.5.4,<2.0.0)",
|
||||
"six (>=1.17.0,<2.0.0)",
|
||||
"sniffio (>=1.3.1,<2.0.0)",
|
||||
"social-auth-app-django (>=5.4.3,<6.0.0)",
|
||||
"social-auth-core (>=4.5.6,<5.0.0)",
|
||||
"sqlparse (>=0.5.3,<0.6.0)",
|
||||
"tomli (>=2.2.1,<3.0.0)",
|
||||
"tomlkit (>=0.13.2,<0.14.0)",
|
||||
"trove-classifiers (>=2025.2.18.16,<2026.0.0.0)",
|
||||
"twisted (>=24.11.0,<25.0.0)",
|
||||
"txaio (>=23.1.1,<24.0.0)",
|
||||
"typing-extensions (>=4.12.2,<5.0.0)",
|
||||
"tzdata (>=2025.1,<2026.0)",
|
||||
"uritemplate (>=4.1.1,<5.0.0)",
|
||||
"urllib3 (>=2.3.0,<3.0.0)",
|
||||
"virtualenv (>=20.29.2,<21.0.0)",
|
||||
"xlsxwriter (>=3.2.2,<4.0.0)",
|
||||
"zipp (>=3.21.0,<4.0.0)",
|
||||
"zope-interface (>=7.2,<8.0)",
|
||||
"zstandard (>=0.23.0,<0.24.0)"
|
||||
]
|
||||
|
||||
[tool.poetry]
|
||||
package-mode = false
|
||||
[tool.poetry.group.dev.dependencies]
|
||||
black = "^25.1.0"
|
||||
pylint = "^3.3.4"
|
||||
pylint-django = "^2.6.1"
|
||||
isort = "^6.0.1"
|
||||
|
||||
|
||||
[build-system]
|
||||
requires = ["poetry-core>=2.0.0,<3.0.0"]
|
||||
build-backend = "poetry.core.masonry.api"
|
||||
|
||||
|
||||
[tool.black]
|
||||
line-length = 100
|
||||
target-version = ['py310']
|
||||
extend-exclude = '''
|
||||
(
|
||||
migrations # Django DB migrations
|
||||
)
|
||||
'''
|
||||
Binary file not shown.
@@ -21,6 +21,7 @@ class Safety_CommiteeInline(admin.StackedInline):
|
||||
ordering = ("comm",)
|
||||
extra = 0
|
||||
|
||||
|
||||
# class SafetyFileAdmin(admin.ModelAdmin):
|
||||
|
||||
# list_display = ('name', 'chapter', 'category', 'sign_date', 'formainpage')
|
||||
|
||||
+19
-1
@@ -1,18 +1,36 @@
|
||||
from django.contrib import admin
|
||||
from .models import *
|
||||
from .models import Test, TestAnswer, TestQuestion
|
||||
|
||||
|
||||
class TestAnswerInline(admin.StackedInline):
|
||||
"""
|
||||
Инлайн ответов
|
||||
"""
|
||||
|
||||
model = TestAnswer
|
||||
extra = 0
|
||||
|
||||
|
||||
class TestQuestionAdmin(admin.ModelAdmin):
|
||||
"""
|
||||
Админка вопросов к тесту
|
||||
"""
|
||||
|
||||
inlines = [TestAnswerInline]
|
||||
|
||||
|
||||
class TestQuestionInline(admin.StackedInline):
|
||||
"""
|
||||
Инлайн вопросов
|
||||
"""
|
||||
|
||||
model = TestQuestion
|
||||
extra = 0
|
||||
|
||||
|
||||
class TestAdmin(admin.ModelAdmin):
|
||||
"Админка тестов"
|
||||
|
||||
inlines = [TestQuestionInline]
|
||||
|
||||
|
||||
|
||||
+13
-15
@@ -50,9 +50,20 @@ class TestAnswer(models.Model):
|
||||
def __str__(self):
|
||||
return self.name
|
||||
|
||||
class Testing(models.Model):
|
||||
user = models.ForeignKey(User, on_delete=models.CASCADE)
|
||||
test = models.ForeignKey(Test, on_delete=models.PROTECT, blank=False, verbose_name="Тест")
|
||||
completion_date = models.DateTimeField(blank=True, null=True, verbose_name="Дата завершения тестирования")
|
||||
test_passed = models.BooleanField(blank=False, verbose_name="Тест пройден")
|
||||
|
||||
class Meta:
|
||||
verbose_name = "Тестирование"
|
||||
verbose_name_plural = "Тестирования"
|
||||
def __str__(self):
|
||||
return self.test.name
|
||||
|
||||
class TestAttempt(models.Model):
|
||||
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='test_attempts')
|
||||
test = models.ForeignKey(Test, on_delete=models.CASCADE)
|
||||
testing = models.ForeignKey(Testing, on_delete=models.CASCADE)
|
||||
score = models.FloatField(verbose_name='Результат', default=0.0)
|
||||
attempt_number = models.IntegerField(verbose_name='Номер попытки', default=1)
|
||||
completion_date = models.DateTimeField(default=datetime.datetime.now, verbose_name="Дата прохождения теста")
|
||||
@@ -72,16 +83,3 @@ class TestResult(models.Model):
|
||||
class Meta:
|
||||
verbose_name = "Результат"
|
||||
verbose_name_plural = "Результаты"
|
||||
|
||||
|
||||
class Testing(models.Model):
|
||||
user = models.ForeignKey(User, on_delete=models.CASCADE)
|
||||
test = models.ForeignKey(Test, on_delete=models.PROTECT, blank=False, verbose_name="Тест")
|
||||
completion_date = models.DateTimeField(blank=True, null=True, verbose_name="Дата завершения тестирования")
|
||||
test_passed = models.BooleanField(blank=False, verbose_name="Тест пройден")
|
||||
|
||||
class Meta:
|
||||
verbose_name = "Тестирование"
|
||||
verbose_name_plural = "Тестирования"
|
||||
def __str__(self):
|
||||
return self.test.name
|
||||
@@ -1,9 +1,13 @@
|
||||
from rest_framework import serializers
|
||||
from .models import *
|
||||
from userauth.models import *
|
||||
# pylint: skip-file
|
||||
import base64
|
||||
import hashlib
|
||||
|
||||
from cryptography.fernet import Fernet
|
||||
from rest_framework import serializers
|
||||
from userauth.models import *
|
||||
|
||||
from .models import *
|
||||
|
||||
|
||||
class TestAnswerSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
@@ -31,20 +35,25 @@ class TestAnswerSerializer(serializers.ModelSerializer):
|
||||
return validated_data
|
||||
|
||||
def to_representation(self, instance):
|
||||
user_login = self.context['request'].user.username
|
||||
# user_login = self.context['request'].user.username
|
||||
user_login = '9966-00-125'
|
||||
representation = super().to_representation(instance)
|
||||
representation['right_wrong'] = self.encrypt_data(str(representation['right_wrong']), user_login)
|
||||
# representation['right_wrong'] = self.encrypt_data(str(representation['right_wrong']), user_login)
|
||||
|
||||
return representation
|
||||
|
||||
|
||||
class TestQuestionSerializer(serializers.ModelSerializer):
|
||||
answers = TestAnswerSerializer(many=True, read_only=True)
|
||||
|
||||
class Meta:
|
||||
model = TestQuestion
|
||||
fields = '__all__'
|
||||
|
||||
|
||||
class TestSerializer(serializers.ModelSerializer):
|
||||
questions = TestQuestionSerializer(many=True, read_only=True)
|
||||
|
||||
class Meta:
|
||||
model = Test
|
||||
fields = '__all__'
|
||||
@@ -56,26 +65,29 @@ class TestSerializer(serializers.ModelSerializer):
|
||||
|
||||
return super().create(validated_data)
|
||||
|
||||
class TestingSeriaizer(serializers.ModelSerializer):
|
||||
|
||||
class TestingSeriaizer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = Testing
|
||||
fields = '__all__'
|
||||
|
||||
class TestAttemptSerializer(serializers.ModelSerializer):
|
||||
|
||||
class TestAttemptSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = TestAttempt
|
||||
fields = '__all__'
|
||||
|
||||
|
||||
class TestResultSerializer(serializers.ModelSerializer):
|
||||
attempt = TestAttemptSerializer(read_only=True)
|
||||
answer = serializers.PrimaryKeyRelatedField(queryset=TestAnswer.objects.all(), many=False)
|
||||
comment = serializers.CharField(allow_null=True)
|
||||
|
||||
class Meta:
|
||||
model = TestResult
|
||||
fields = '__all__'
|
||||
|
||||
|
||||
class TestsSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = Test
|
||||
@@ -87,3 +99,11 @@ class TestsSerializer(serializers.ModelSerializer):
|
||||
validated_data['author'] = user
|
||||
|
||||
return super().create(validated_data)
|
||||
|
||||
|
||||
class TestInfoSerializer(serializers.Serializer):
|
||||
test = TestsSerializer(read_only=True)
|
||||
# test_answers = TestAnswerSerializer(many=True, read_only=True)
|
||||
score = serializers.IntegerField(read_only=True)
|
||||
is_passed = serializers.BooleanField(read_only=True)
|
||||
test_answers = TestAnswerSerializer(many=True, read_only=True)
|
||||
@@ -5,7 +5,7 @@ from .views import *
|
||||
urlpatterns = [
|
||||
path('testdetail/<int:id>/', TestDetail.as_view(),name='TestDetail'),
|
||||
path('gettests/', GetTests.as_view(), name="GetTests"),
|
||||
path('gettesting/', GetTesting.as_view(), name="GetTesting"),
|
||||
path('testresultcreate/', TestResultCreate.as_view(), name="TestResultCreate"),
|
||||
# path('gettesting/', GetTesting.as_view(), name="GetTesting"),
|
||||
path('testresultview/', TestResultView.as_view(), name="TestResultView"),
|
||||
]
|
||||
|
||||
+102
-60
@@ -19,17 +19,37 @@ import base64
|
||||
import hashlib
|
||||
from cryptography.fernet import Fernet
|
||||
from django.db.models import F
|
||||
from drf_yasg import openapi
|
||||
from drf_yasg.utils import swagger_auto_schema
|
||||
|
||||
class GetTests(generics.ListAPIView):
|
||||
queryset = Test.objects.all()
|
||||
serializer_class = TestsSerializer
|
||||
pagination_class = None
|
||||
|
||||
@swagger_auto_schema(
|
||||
operation_description="""Получить список тестов по статусу
|
||||
*Нужно авторизоваться!""",
|
||||
manual_parameters=[
|
||||
openapi.Parameter(
|
||||
'status',
|
||||
openapi.IN_QUERY,
|
||||
description="Статус тестов (например, 'active', 'completed'). Пустое значение вернет все тесты",
|
||||
type=openapi.TYPE_STRING,
|
||||
required=False,
|
||||
),
|
||||
],
|
||||
responses={
|
||||
200: "success",
|
||||
400: 'error',
|
||||
}
|
||||
)
|
||||
def get (self, request, *args, **kwargs):
|
||||
user = request.user
|
||||
# user = User.objects.get(username='9966-00-125')
|
||||
status = request.query_params.get('status')
|
||||
tests = self.get_tests_by_status(status, datetime.now(), user)
|
||||
if status != None:
|
||||
if status is not None:
|
||||
self.set_attemps_number(user, tests)
|
||||
serialized_tests = self.get_serializer(tests, many=True).data
|
||||
|
||||
@@ -55,8 +75,11 @@ class GetTests(generics.ListAPIView):
|
||||
return status_filters.get(status, Test.objects.none()).order_by('dateend')
|
||||
|
||||
def set_attemps_number(self, user, tests):
|
||||
attempt_counts = TestAttempt.objects.filter(testing__user=user, testing__test__in=tests).values('testing__test').annotate(count=Count('testing__test'))
|
||||
attempt_counts = {item['testing__test']: item['count'] for item in attempt_counts}
|
||||
|
||||
for test in tests:
|
||||
test.attemps_number = get_attempt_count(user=user, test=test)
|
||||
test.attemps_number = test.attemps_number - attempt_counts.get(test.id, 0)
|
||||
|
||||
class TestDetail(generics.RetrieveUpdateDestroyAPIView):
|
||||
queryset = Test.objects.all()
|
||||
@@ -73,66 +96,83 @@ class TestDetail(generics.RetrieveUpdateDestroyAPIView):
|
||||
|
||||
return Response(test_serialized)
|
||||
|
||||
# class TestListCreate(generics.ListCreateAPIView):
|
||||
# queryset = Test.objects.all()
|
||||
# serializer_class = TestSerializer
|
||||
# class GetTesting(APIView):
|
||||
|
||||
# def get(self, request):
|
||||
# user = request.user
|
||||
# now = datetime.now()
|
||||
# status = request.query_params.get('status')
|
||||
# tests = self.get_tests_by_status(status, now)
|
||||
# serialized_tests = TestSerializer(tests, many=True).data
|
||||
# questions = TestQuestion.objects.filter(test__in=tests)
|
||||
# tests = Testing.objects.filter(user=user)
|
||||
# test_names = {test.id: test.test.name for test in tests}
|
||||
# serializer = TestingSeriaizer(tests, many=True).data
|
||||
# for test in serializer:
|
||||
# if test['id'] in test_names:
|
||||
# test['test_name'] = test_names[test['id']]
|
||||
# return Response(serializer)
|
||||
|
||||
# questions_by_test_id = defaultdict(list)
|
||||
# for question in questions:
|
||||
# questions_by_test_id[question.test.id].append(question)
|
||||
|
||||
# for test in serialized_tests:
|
||||
# test['is_passed'] = self.has_participated(user, test['id'])
|
||||
# related_questions = questions_by_test_id[test['id']]
|
||||
# test['files'] = [question.file.url for question in related_questions if question.file]
|
||||
|
||||
# return Response(serialized_tests)
|
||||
|
||||
# def get_tests_by_status(self, status, now):
|
||||
# print(status)
|
||||
# if status is None:
|
||||
# return Test.objects.all().order_by('dateend')
|
||||
|
||||
# status_filters = {
|
||||
# 'active': Test.objects.filter(dateend__gt=now),
|
||||
# 'completed': Test.objects.filter(dateend__lt=now),
|
||||
# }
|
||||
|
||||
# return status_filters.get(status, Test.objects.none()).order_by('dateend')
|
||||
|
||||
# def has_participated(self, employee, test):
|
||||
# return TestResult.objects.filter(user=employee, answer__question__test=test).exists()
|
||||
|
||||
class GetTesting(APIView):
|
||||
|
||||
def get(self, request):
|
||||
user = request.user
|
||||
tests = Testing.objects.filter(user=user)
|
||||
test_names = {test.id: test.test.name for test in tests}
|
||||
serializer = TestingSeriaizer(tests, many=True).data
|
||||
for test in serializer:
|
||||
if test['id'] in test_names:
|
||||
test['test_name'] = test_names[test['id']]
|
||||
return Response(serializer)
|
||||
|
||||
class TestResultCreate(generics.ListCreateAPIView):
|
||||
class TestResultView(generics.ListCreateAPIView):
|
||||
|
||||
queryset = TestResult.objects.all()
|
||||
serializer_class = TestResultSerializer
|
||||
pagination_class = None
|
||||
|
||||
@swagger_auto_schema(
|
||||
operation_description="""Получить результаты тестов
|
||||
*Нужно авторизоваться!""",
|
||||
manual_parameters=[
|
||||
openapi.Parameter(
|
||||
'id',
|
||||
openapi.IN_QUERY,
|
||||
description="ID теста",
|
||||
type=openapi.TYPE_INTEGER,
|
||||
required=True,
|
||||
),
|
||||
],
|
||||
responses={
|
||||
200: "success",
|
||||
400: 'error',
|
||||
}
|
||||
)
|
||||
def get(self, request, *args, **kwargs):
|
||||
user = request.user
|
||||
# user = User.objects.get(username = "9966-00-125")
|
||||
test_id = request.GET.get('id')
|
||||
last_attempt = TestAttempt.objects.filter(testing__user=user, testing__test__id=test_id).order_by('-completion_date').first()
|
||||
answer_ids = TestResult.objects.filter(attempt=last_attempt).values_list('answer__id', flat=True)
|
||||
test_info = self.get_test_info(answer_ids)
|
||||
return Response(data={'score': test_info['score'], 'answered_questions_total': test_info['answered_questions_total']})
|
||||
|
||||
@swagger_auto_schema(
|
||||
operation_description=""" Сохранить результаты тестов
|
||||
*Нужно авторизоваться!""",
|
||||
manual_parameters=[
|
||||
openapi.Parameter(
|
||||
'status',
|
||||
openapi.IN_QUERY,
|
||||
description="Статус тестов (например, 'testing'). Пустое значение - режим тренировки",
|
||||
type=openapi.TYPE_STRING,
|
||||
required=False,
|
||||
),
|
||||
],
|
||||
request_body=openapi.Schema(
|
||||
type=openapi.TYPE_ARRAY,
|
||||
items=openapi.Schema(
|
||||
type=openapi.TYPE_OBJECT,
|
||||
properties={
|
||||
'answer': openapi.Schema(type=openapi.TYPE_INTEGER, description='ID ответа')
|
||||
},
|
||||
),
|
||||
),
|
||||
responses={
|
||||
200: "success",
|
||||
400: 'error',
|
||||
}
|
||||
)
|
||||
def post(self, request, *args, **kwargs):
|
||||
user = request.user
|
||||
# user = User.objects.get(username = "9966-00-125")
|
||||
|
||||
test_info = self.get_test_info(request)
|
||||
status = request.query_params.get('status')
|
||||
answer_ids = [item['answer'] for item in request.data]
|
||||
test_info = self.get_test_info(answer_ids)
|
||||
if status == 'testing':
|
||||
test_attempt = self.create_test_attempt(user, test_info)
|
||||
|
||||
serializer = self.get_serializer(data=request.data, many=True)
|
||||
@@ -140,25 +180,26 @@ class TestResultCreate(generics.ListCreateAPIView):
|
||||
serializer.save(attempt=test_attempt)
|
||||
self.update_testing(user, test_info)
|
||||
|
||||
return Response(test_info['is_passed'])
|
||||
return Response(data={'score': test_info['score'], 'answered_questions_total': test_info['answered_questions_total']})
|
||||
|
||||
def create_test_attempt(self, user, test_info):
|
||||
test = test_info['test']
|
||||
score = test_info['score']
|
||||
attempt_count = get_attempt_count(user=user, test=test)+ 1
|
||||
test_attempt = TestAttempt.objects.create(user=user, test=test , score=score , attempt_number=attempt_count , completion_date= datetime.now())
|
||||
testing = Testing.objects.get(user=user, test=test)
|
||||
attempt_count = get_attempt_count(testing)+ 1
|
||||
test_attempt = TestAttempt.objects.create(testing=testing , score=score , attempt_number=attempt_count , completion_date= datetime.now())
|
||||
return test_attempt
|
||||
|
||||
def update_testing(self, user, test_info):
|
||||
test = test_info['test']
|
||||
test_passed = test_info['is_passed']
|
||||
Testing.objects.update_or_create(user=user, test=test, defaults = {"completion_date": test.dateend,"test_passed":test_passed})
|
||||
Testing.objects.update_or_create(user=user, test=test, defaults = {"test_passed":test_passed})
|
||||
|
||||
def get_test_info(self, request):
|
||||
def get_test_info(self, answer_ids):
|
||||
|
||||
answer_ids = [item['answer'] for item in request.data]
|
||||
test_answers = TestAnswer.objects.filter(id__in=answer_ids)
|
||||
test = test_answers[0].question.test
|
||||
answered_questions_total = test_answers.values('question').distinct().count()
|
||||
|
||||
correct_questions = sum(
|
||||
TestAnswer.objects.filter(
|
||||
@@ -175,9 +216,10 @@ class TestResultCreate(generics.ListCreateAPIView):
|
||||
result = {
|
||||
"is_passed": correct_questions >= pass_perc,
|
||||
"score": correct_questions,
|
||||
"test": test
|
||||
"test": test,
|
||||
"answered_questions_total": answered_questions_total,
|
||||
}
|
||||
return result
|
||||
|
||||
def get_attempt_count(user, test):
|
||||
return TestAttempt.objects.filter(user=user, test=test).count()
|
||||
def get_attempt_count(testing):
|
||||
return TestAttempt.objects.filter(testing=testing).count()
|
||||
@@ -2,6 +2,7 @@ from django.db import models
|
||||
from userauth.models import *
|
||||
from accounts.models import User
|
||||
import datetime
|
||||
from navigation.models import News
|
||||
# Create your models here.
|
||||
|
||||
class Vote(models.Model):
|
||||
@@ -10,10 +11,16 @@ class Vote(models.Model):
|
||||
datestart = models.DateTimeField(default=datetime.datetime.now, verbose_name='Дата и время начала периода')
|
||||
dateend = models.DateTimeField(default=datetime.datetime.now, verbose_name='Дата и время окончания периода')
|
||||
author = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='Создатель голосования')
|
||||
news = models.ForeignKey(News, on_delete=models.CASCADE, null=True, blank=True, verbose_name='Новость')
|
||||
|
||||
def __str__(self):
|
||||
return self.name
|
||||
|
||||
def delete(self, *args, **kwargs):
|
||||
if self.news:
|
||||
self.news.delete()
|
||||
super().delete(*args, **kwargs)
|
||||
|
||||
class Meta:
|
||||
verbose_name = "Голосование"
|
||||
verbose_name_plural = "Голосования"
|
||||
|
||||
+343
-116
@@ -1,232 +1,459 @@
|
||||
from rest_framework.views import APIView
|
||||
from rest_framework.response import Response
|
||||
from django.db.models import Count
|
||||
from django.db.models import Q
|
||||
from .models import *
|
||||
from userauth.models import *
|
||||
from .serializers import *
|
||||
from datetime import datetime
|
||||
from rest_framework import generics
|
||||
from navigation.models import News
|
||||
import json
|
||||
from collections import defaultdict
|
||||
import os
|
||||
from django.conf import settings
|
||||
from django.urls import reverse
|
||||
import html
|
||||
from datetime import datetime, timezone
|
||||
from collections import defaultdict
|
||||
|
||||
from rest_framework.views import APIView
|
||||
from rest_framework.response import Response
|
||||
from rest_framework import generics
|
||||
|
||||
from django.db import DatabaseError
|
||||
from django.db.models import Count
|
||||
from accounts.models import User
|
||||
from navigation.models import News
|
||||
from userauth.models import DictDepartment, DictEmployee, EmployeeDepartment
|
||||
|
||||
from .models import Vote, Answer, Question, Result
|
||||
from .serializers import (
|
||||
VoteSerializer,
|
||||
VotesSerializer,
|
||||
DictEmployeeSerializer,
|
||||
ResultSerializer,
|
||||
)
|
||||
|
||||
|
||||
class GetVotes(APIView):
|
||||
"""
|
||||
Комментарий
|
||||
"""
|
||||
|
||||
def get(self, request):
|
||||
"""
|
||||
Комментарий
|
||||
"""
|
||||
user = request.user
|
||||
# user = User.objects.get(username='9966-00-125')
|
||||
now = datetime.now()
|
||||
status = request.query_params.get('status')
|
||||
|
||||
#
|
||||
|
||||
status = request.query_params.get("status")
|
||||
votes = self.get_votes_by_status(status, now)
|
||||
serialized_votes = VotesSerializer(votes, many=True).data
|
||||
questions_by_vote_id = self.get_questions_by_vote_id(votes)
|
||||
self.enrich_votes(serialized_votes, questions_by_vote_id, user)
|
||||
|
||||
return Response(serialized_votes)
|
||||
|
||||
def get_votes_by_status(self, status, now):
|
||||
"""
|
||||
Комментарий
|
||||
"""
|
||||
print(status)
|
||||
if status is None:
|
||||
return Vote.objects.all().order_by("dateend")
|
||||
|
||||
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")
|
||||
|
||||
def get_questions_by_vote_id(self, votes):
|
||||
"""
|
||||
Комментарий
|
||||
"""
|
||||
questions = Question.objects.filter(vote__in=votes)
|
||||
|
||||
questions_by_vote_id = defaultdict(list)
|
||||
for question in questions:
|
||||
questions_by_vote_id[question.vote.id].append(question)
|
||||
return questions_by_vote_id
|
||||
|
||||
def enrich_votes(self, serialized_votes, questions_by_vote_id, user):
|
||||
"""
|
||||
Комментарий
|
||||
"""
|
||||
for vote in serialized_votes:
|
||||
vote['is_passed'] = self.has_participated(user, vote['id'])
|
||||
related_questions = questions_by_vote_id[vote['id']]
|
||||
vote['files'] = [question.file.url for question in related_questions if question.file]
|
||||
|
||||
return Response(serialized_votes)
|
||||
|
||||
def get_votes_by_status(self, status, now):
|
||||
print(status)
|
||||
if status is None:
|
||||
return Vote.objects.all().order_by('dateend')
|
||||
|
||||
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')
|
||||
vote["is_passed"] = self.has_participated(user, vote["id"])
|
||||
related_questions = questions_by_vote_id[vote["id"]]
|
||||
vote["files"] = [
|
||||
question.file.url for question in related_questions if question.file
|
||||
]
|
||||
|
||||
def has_participated(self, employee, vote):
|
||||
return Result.objects.filter(user=employee, answer__question__vote=vote).exists()
|
||||
"""
|
||||
Комментарий
|
||||
"""
|
||||
return Result.objects.filter(
|
||||
user=employee, answer__question__vote=vote
|
||||
).exists()
|
||||
|
||||
|
||||
class VoteDetail(generics.RetrieveUpdateDestroyAPIView):
|
||||
"""
|
||||
Комментарий
|
||||
"""
|
||||
|
||||
queryset = Vote.objects.all()
|
||||
serializer_class = VoteSerializer
|
||||
lookup_url_kwarg = 'id'
|
||||
lookup_field = 'id'
|
||||
lookup_url_kwarg = "id"
|
||||
lookup_field = "id"
|
||||
|
||||
def get(self, request, *args, **kwargs):
|
||||
results = Result.objects.filter(answer__question__vote=kwargs['id'], user=request.user)
|
||||
if results:
|
||||
return Response({'status': 'error', 'message': 'voted'}, status=400)
|
||||
"""
|
||||
Комментарий
|
||||
"""
|
||||
|
||||
try:
|
||||
vote = Vote.objects.get(id=kwargs['id'])
|
||||
if vote.dateend < datetime.now(timezone.utc):
|
||||
return Response({'status': 'error', 'message': 'Voting is over'}, status=400)
|
||||
except Exception as e:
|
||||
return Response({'status': 'error', 'message': str(e)}, status=400)
|
||||
# if self.check_user_vote(kwargs['id'], User.objects.get(username='9966-00-125')):
|
||||
if self.check_user_vote(kwargs["id"], request.user):
|
||||
return Response({"status": "error", "message": "voted"}, status=400)
|
||||
|
||||
answers_employee = Answer.objects.filter(question__vote=vote).filter(question__settings__choice="employee").values('name', 'question')
|
||||
vote = self.get_vote(kwargs["id"])
|
||||
if isinstance(vote, Response):
|
||||
return vote
|
||||
|
||||
answers_names = [item['name'] for item in answers_employee]
|
||||
question_ids = [item['question'] for item in answers_employee]
|
||||
answers_employee = self.get_employee_answers(vote)
|
||||
answers_names = [item["name"] for item in answers_employee]
|
||||
|
||||
if answers_employee:
|
||||
employees_serializer = get_employees_serializer(answers_names)
|
||||
employee_dict = {employee['id']: employee for employee in employees_serializer}
|
||||
employee_dict = self.serialize_employees(answers_names)
|
||||
|
||||
serialized_data = self.retrieve(request, *args, **kwargs).data
|
||||
|
||||
for question in serialized_data['questions']:
|
||||
for answer in question['answers']:
|
||||
if question['id'] in question_ids:
|
||||
if answer['name'] in answers_names:
|
||||
answer['employee'] = employee_dict.get(int(answer['name']))
|
||||
self.add_employee_info(
|
||||
serialized_data, answers_employee, answers_names, employee_dict
|
||||
)
|
||||
|
||||
return Response(serialized_data)
|
||||
|
||||
def check_user_vote(self, vote_id, user):
|
||||
"""
|
||||
Комментарий
|
||||
"""
|
||||
results = Result.objects.filter(answer__question__vote=vote_id, user=user)
|
||||
return results.exists()
|
||||
|
||||
def get_vote(self, vote_id):
|
||||
"""
|
||||
Получить незавершенное голосование
|
||||
"""
|
||||
try:
|
||||
vote = Vote.objects.get(id=vote_id)
|
||||
if vote.dateend < datetime.now(timezone.utc):
|
||||
return Response(
|
||||
{"status": "error", "message": "Voting is over"}, status=400
|
||||
)
|
||||
return vote
|
||||
except Vote.DoesNotExist as e:
|
||||
return Response({"status": "error", "message": str(e)}, status=400)
|
||||
|
||||
def get_employee_answers(self, vote):
|
||||
"""
|
||||
Комментарий
|
||||
"""
|
||||
return (
|
||||
Answer.objects.filter(question__vote=vote)
|
||||
.filter(question__settings__choice="employee")
|
||||
.values("name", "question")
|
||||
)
|
||||
|
||||
def serialize_employees(self, answers_names):
|
||||
"""
|
||||
Комментарий
|
||||
"""
|
||||
|
||||
employees_serializer = get_employees_serializer(answers_names)
|
||||
return {employee["id"]: employee for employee in employees_serializer}
|
||||
|
||||
def add_employee_info(
|
||||
self, serialized_data, answers_employee, answers_names, employee_dict
|
||||
):
|
||||
"""
|
||||
Комментарий
|
||||
"""
|
||||
question_ids = [item["question"] for item in answers_employee]
|
||||
|
||||
for question in serialized_data["questions"]:
|
||||
for answer in question["answers"]:
|
||||
if question["id"] in question_ids:
|
||||
if answer["name"] in answers_names:
|
||||
answer["employee"] = employee_dict.get(int(answer["name"]))
|
||||
|
||||
|
||||
class VoteCreate(APIView):
|
||||
"""
|
||||
Комментарий
|
||||
"""
|
||||
|
||||
def post(self, request):
|
||||
"""
|
||||
Комментарий
|
||||
"""
|
||||
try:
|
||||
vote = self.create_vote(request)
|
||||
if request.data.get("news") == "true":
|
||||
self.create_news(request, vote)
|
||||
return Response({'status': 'success', 'message': 'Vote and news created successfully.'}, status=200)
|
||||
except Exception as e:
|
||||
return Response(
|
||||
{"status": "success", "message": "Vote and news created successfully."},
|
||||
status=200,
|
||||
)
|
||||
except ValueError as e:
|
||||
|
||||
return Response({"status": "error", "message": str(e)}, status=400)
|
||||
|
||||
except DatabaseError as e:
|
||||
print(e)
|
||||
return Response({'status': 'error', 'message': str(e)}, status=400)
|
||||
return Response({"status": "error", "message": str(e)}, status=400)
|
||||
|
||||
def create_vote(self, request):
|
||||
"""
|
||||
Комментарий
|
||||
"""
|
||||
user = request.user
|
||||
|
||||
vote = Vote.objects.create(
|
||||
name=request.data['title'],
|
||||
description=request.data['description'],
|
||||
datestart=request.data['startDate'],
|
||||
dateend=request.data['endDate'],
|
||||
name=request.data["title"],
|
||||
description=request.data["description"],
|
||||
datestart=request.data["startDate"],
|
||||
dateend=request.data["endDate"],
|
||||
author=user,
|
||||
)
|
||||
|
||||
questions_files = {file.name: file for file in request.FILES.getlist('questionsfiles')}
|
||||
answers_files = {file.name: file for file in request.FILES.getlist('answersfiles')}
|
||||
questions_files = {
|
||||
file.name: file for file in request.FILES.getlist("questionsfiles")
|
||||
}
|
||||
answers_files = {
|
||||
file.name: file for file in request.FILES.getlist("answersfiles")
|
||||
}
|
||||
|
||||
questions = json.loads(request.data['questions'])
|
||||
questions = json.loads(request.data["questions"])
|
||||
for count, question_data in enumerate(questions, start=1):
|
||||
question_image = questions_files.get(question_data['image']['name']) if 'image' in question_data and question_data['image'] is not None else None
|
||||
question_image = (
|
||||
questions_files.get(question_data["image"]["name"])
|
||||
if "image" in question_data and question_data["image"] is not None
|
||||
else None
|
||||
)
|
||||
question = Question.objects.create(
|
||||
name=question_data['text'],
|
||||
name=question_data["text"],
|
||||
vote=vote,
|
||||
file=question_image,
|
||||
numb=count,
|
||||
settings=question_data.get('settings', {}),
|
||||
settings=question_data.get("settings", {}),
|
||||
)
|
||||
|
||||
for answer in question_data['answers']:
|
||||
answer_image = answers_files.get(answer['image']['name']) if 'image' in answer and answer['image'] is not None else None
|
||||
for answer in question_data["answers"]:
|
||||
answer_image = (
|
||||
answers_files.get(answer["image"]["name"])
|
||||
if "image" in answer and answer["image"] is not None
|
||||
else None
|
||||
)
|
||||
Answer.objects.create(
|
||||
name=answer['text'],
|
||||
file=answer_image,
|
||||
question=question
|
||||
name=answer["text"], file=answer_image, question=question
|
||||
)
|
||||
|
||||
return vote
|
||||
|
||||
def create_news(self, request, vote):
|
||||
"""
|
||||
Комментарий
|
||||
"""
|
||||
|
||||
formatted_date = datetime.strptime(request.data["endDate"][:-1], "%Y-%m-%dT%H:%M:%S.%f").strftime("%d.%m.%Y %H:%M")
|
||||
vote_url = make_clickable(request.data['title'], f"/vote/voting/{vote.id}")
|
||||
formatted_date = datetime.strptime(
|
||||
request.data["endDate"][:-1], "%Y-%m-%dT%H:%M:%S.%f"
|
||||
).strftime("%d.%m.%Y %H:%M")
|
||||
vote_url = make_clickable(request.data["title"], f"/vote/voting/{vote.id}")
|
||||
|
||||
news = News(
|
||||
title = 'Пройдите голосование!',
|
||||
title="Пройдите голосование!",
|
||||
text=f'Пройдите голосование "{vote_url}" до {formatted_date}',
|
||||
cdate = request.data['startDate'],
|
||||
cdate=request.data["startDate"],
|
||||
author=request.user,
|
||||
link = os.path.join('defaultimg','vote.png'),
|
||||
vote = vote
|
||||
link=os.path.join("defaultimg", "vote.png"),
|
||||
)
|
||||
news.save()
|
||||
vote.news = news
|
||||
vote.save()
|
||||
|
||||
|
||||
def make_clickable(text, url):
|
||||
"""
|
||||
Комментарий
|
||||
"""
|
||||
text = html.escape(text)
|
||||
anchor = f'<a href="{html.escape(url)}">{text}</a>'
|
||||
return anchor
|
||||
|
||||
|
||||
class GetDictEmployee(APIView):
|
||||
"""
|
||||
Комментарий
|
||||
"""
|
||||
|
||||
def get(self, request):
|
||||
"""
|
||||
Комментарий
|
||||
"""
|
||||
employees = DictEmployee.objects.filter(deleted=0)
|
||||
set_real_departments(employees)
|
||||
employees_serializer = DictEmployeeSerializer(employees, many=True).data
|
||||
return Response(employees_serializer)
|
||||
|
||||
|
||||
class GetResults(APIView):
|
||||
"""
|
||||
Комментарий
|
||||
"""
|
||||
|
||||
def get(self, request):
|
||||
vote_id = request.GET.get('id')
|
||||
try:
|
||||
vote = Vote.objects.get(id=vote_id)
|
||||
except Vote.DoesNotExist:
|
||||
return Response({'status': 'error', 'message': 'Vote not found'}, status=404)
|
||||
"""
|
||||
Комментарий
|
||||
"""
|
||||
vote_id = request.GET.get("id")
|
||||
vote = self.get_vote(vote_id)
|
||||
if isinstance(vote, Response):
|
||||
return vote
|
||||
|
||||
serialized_data = VoteSerializer(vote).data
|
||||
answers_employee = Answer.objects.filter(
|
||||
question__vote=vote,
|
||||
question__settings__choice="employee"
|
||||
).values('name', 'question')
|
||||
|
||||
answers_names = [item['name'] for item in answers_employee]
|
||||
question_ids = [item['question'] for item in answers_employee]
|
||||
answers_employee = self.get_employee_answers(vote)
|
||||
answers_names = [item["name"] for item in answers_employee]
|
||||
employee_dict = self.create_employee_dict(answers_names)
|
||||
result_dict = self.get_answer_counts(vote)
|
||||
info = {
|
||||
"serialized_data": serialized_data,
|
||||
"answers_employee": answers_employee,
|
||||
"answers_names": answers_names,
|
||||
"employee_dict": employee_dict,
|
||||
"result_dict": result_dict,
|
||||
}
|
||||
self.add_employee_info(info)
|
||||
|
||||
employee_dict = {}
|
||||
if answers_employee:
|
||||
employees_serializer = get_employees_serializer(answers_names)
|
||||
employee_dict = {employee['id']: employee for employee in employees_serializer}
|
||||
|
||||
results = Result.objects.filter(
|
||||
answer__question__vote=vote
|
||||
).values('answer_id').annotate(count=Count('id'))
|
||||
|
||||
result_dict = {int(result['answer_id']): result['count'] for result in results}
|
||||
|
||||
for question in serialized_data['questions']:
|
||||
for answer in question['answers']:
|
||||
answer['count'] = result_dict.get(int(answer['id']), 0)
|
||||
if question['id'] in question_ids:
|
||||
if answer['name'] in answers_names:
|
||||
answer['employee'] = employee_dict.get(int(answer['name']))
|
||||
|
||||
users = Result.objects.filter(answer__question__vote=vote).values('user_id')
|
||||
users = User.objects.filter(created_at__lt=vote.dateend).exclude(id__in=users)
|
||||
employee_ids = users.values_list('user_id', flat=True)
|
||||
serialized_data['nonvoting'] = get_employees_serializer(employee_ids)
|
||||
serialized_data["nonvoting"] = self.get_non_voting_employees(vote)
|
||||
|
||||
return Response(serialized_data)
|
||||
|
||||
def get_vote(self, vote_id):
|
||||
"""
|
||||
Комментарий
|
||||
"""
|
||||
try:
|
||||
vote = Vote.objects.get(id=vote_id)
|
||||
return vote
|
||||
except Vote.DoesNotExist:
|
||||
return Response(
|
||||
{"status": "error", "message": "Vote not found"}, status=404
|
||||
)
|
||||
|
||||
def get_employee_answers(self, vote):
|
||||
"""
|
||||
Комментарий
|
||||
"""
|
||||
answers_employee = Answer.objects.filter(
|
||||
question__vote=vote, question__settings__choice="employee"
|
||||
).values("name", "question")
|
||||
|
||||
return answers_employee
|
||||
|
||||
def create_employee_dict(self, answers_names):
|
||||
"""
|
||||
Комментарий
|
||||
"""
|
||||
if not answers_names:
|
||||
return {}
|
||||
|
||||
employees_serializer = get_employees_serializer(answers_names)
|
||||
return {employee["id"]: employee for employee in employees_serializer}
|
||||
|
||||
def get_answer_counts(self, vote):
|
||||
"""
|
||||
Комментарий
|
||||
"""
|
||||
results = (
|
||||
Result.objects.filter(answer__question__vote=vote)
|
||||
.values("answer_id")
|
||||
.annotate(count=Count("id"))
|
||||
)
|
||||
|
||||
return {int(result["answer_id"]): result["count"] for result in results}
|
||||
|
||||
def add_employee_info(self, info):
|
||||
"""
|
||||
info ={serialized_data, answers_employee, answers_names, employee_dict, result_dict}
|
||||
Комментарий
|
||||
"""
|
||||
|
||||
serialized_data = info.get("serialized_data")
|
||||
answers_employee = info.get("answers_employee")
|
||||
answers_names = info.get("answers_names")
|
||||
employee_dict = info.get("employee_dict")
|
||||
result_dict = info.get("result_dict")
|
||||
|
||||
question_ids = [item["question"] for item in answers_employee]
|
||||
for question in serialized_data["questions"]:
|
||||
for answer in question["answers"]:
|
||||
answer["count"] = result_dict.get(int(answer["id"]), 0)
|
||||
if question["id"] in question_ids:
|
||||
if answer["name"] in answers_names:
|
||||
answer["employee"] = employee_dict.get(int(answer["name"]))
|
||||
|
||||
def get_non_voting_employees(self, vote):
|
||||
"""
|
||||
Комментарий
|
||||
"""
|
||||
users = Result.objects.filter(answer__question__vote=vote).values("user_id")
|
||||
non_voting_users = User.objects.filter(created_at__lt=vote.dateend).exclude(
|
||||
id__in=users
|
||||
)
|
||||
employee_ids = non_voting_users.values_list("user_id", flat=True)
|
||||
return get_employees_serializer(employee_ids)
|
||||
|
||||
|
||||
class VoteResultCreate(generics.ListCreateAPIView):
|
||||
"""
|
||||
Комментарий
|
||||
"""
|
||||
|
||||
queryset = Result.objects.all()
|
||||
serializer_class = ResultSerializer
|
||||
|
||||
def create(self, request, *args, **kwargs):
|
||||
"""
|
||||
Комментарий
|
||||
"""
|
||||
serializer = self.get_serializer(data=request.data, many=True)
|
||||
if serializer.is_valid():
|
||||
serializer.save()
|
||||
return Response(serializer.data)
|
||||
|
||||
|
||||
def get_employees_serializer(ids):
|
||||
"""
|
||||
Комментарий
|
||||
"""
|
||||
employees = DictEmployee.objects.filter(id__in=ids)
|
||||
set_real_departments(employees)
|
||||
employees_serializer = DictEmployeeSerializer(employees, many=True).data
|
||||
return employees_serializer
|
||||
|
||||
|
||||
def set_real_departments(employees):
|
||||
"""
|
||||
Комментарий
|
||||
"""
|
||||
employee_departments = EmployeeDepartment.objects.filter(employee__in=employees)
|
||||
departments = DictDepartment.objects.in_bulk([ed.department.id for ed in employee_departments])
|
||||
department_map = {ed.employee.id: {'name': ed.department.name, 'id': departments[ed.department.id]} for ed in employee_departments}
|
||||
departments = DictDepartment.objects.in_bulk(
|
||||
[ed.department.id for ed in employee_departments]
|
||||
)
|
||||
department_map = {
|
||||
ed.employee.id: {
|
||||
"name": ed.department.name,
|
||||
"id": departments[ed.department.id],
|
||||
}
|
||||
for ed in employee_departments
|
||||
}
|
||||
|
||||
for employee in employees:
|
||||
if employee.id in department_map:
|
||||
employee.department = department_map[employee.id]['name']
|
||||
employee.id_dict_department = department_map[employee.id]['id']
|
||||
employee.department = department_map[employee.id]["name"]
|
||||
employee.id_dict_department = department_map[employee.id]["id"]
|
||||
@@ -3,4 +3,5 @@ from django.apps import AppConfig
|
||||
|
||||
class WatcherConfig(AppConfig):
|
||||
default_auto_field = 'django.db.models.BigAutoField'
|
||||
|
||||
name = 'watcher'
|
||||
@@ -8,14 +8,21 @@ import redis
|
||||
|
||||
class WatcherConsumer(AsyncWebsocketConsumer):
|
||||
async def connect(self):
|
||||
self.client = redis.Redis(host='127.0.0.1')
|
||||
print("Sdsdsdds")
|
||||
|
||||
self.client = redis.Redis(host='redis')
|
||||
user = parse_qs(self.scope["query_string"].decode("utf8"))["token"][0]
|
||||
user = jwt.decode(user, options={"verify_signature": False})
|
||||
|
||||
|
||||
|
||||
|
||||
# self.client.sadd('online',json.dumps(user['user'],indent=4))
|
||||
self.room_group_name = "online"
|
||||
self.client.hset('online',str(self.channel_name), user['user']['login'] )
|
||||
# Join room group
|
||||
|
||||
|
||||
await self.channel_layer.group_add(
|
||||
self.room_group_name, self.channel_name
|
||||
)
|
||||
|
||||
@@ -4,4 +4,4 @@ module.exports = {
|
||||
node: true,
|
||||
},
|
||||
extends: ['plugin:vue/vue3-essential', 'eslint:recommended', 'plugin:storybook/recommended'],
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,19 @@
|
||||
import globals from "globals";
|
||||
import pluginJs from "@eslint/js";
|
||||
import pluginVue from "eslint-plugin-vue";
|
||||
|
||||
|
||||
/** @type {import('eslint').Linter.Config[]} */
|
||||
export default [
|
||||
{files: ["**/*.{js,mjs,cjs,vue}"]
|
||||
},
|
||||
{languageOptions: { globals: {...globals.browser, ...globals.node} }},
|
||||
pluginJs.configs.recommended,
|
||||
...pluginVue.configs["flat/essential"],
|
||||
{rules: {
|
||||
'no-console': 'error',
|
||||
|
||||
|
||||
}},
|
||||
|
||||
];
|
||||
Generated
-4814
File diff suppressed because it is too large.
Load diff
+13
-4
@@ -1,12 +1,13 @@
|
||||
{
|
||||
"name": "front",
|
||||
"version": "0.0.84",
|
||||
"version": "1.0.2",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview",
|
||||
"lint": "eslint . --fix --ignore-path .gitignore",
|
||||
"docs": "vuepress build docs"
|
||||
"formatter": "prettier --write",
|
||||
"linter": "eslint --fix"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ckeditor/ckeditor5-build-classic": "^44.1.0",
|
||||
@@ -38,13 +39,21 @@
|
||||
"webfontloader": "^1.6.28"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@commitlint/cli": "^19.7.1",
|
||||
"@commitlint/config-conventional": "^19.7.1",
|
||||
"@eslint/js": "^9.19.0",
|
||||
"@vitejs/plugin-vue": "^5.2.1",
|
||||
"@vue-leaflet/vue-leaflet": "^0.10.1",
|
||||
"commitlint": "^19.7.1",
|
||||
"eslint": "^9.19.0",
|
||||
"eslint-config-prettier": "^10.0.1",
|
||||
"eslint-plugin-prettier": "^5.2.3",
|
||||
"eslint-plugin-vue": "^9.32.0",
|
||||
"globals": "^15.14.0",
|
||||
"leaflet": "^1.9.4",
|
||||
"prettier": "^3.4.2",
|
||||
"sass-embedded": "^1.83.4",
|
||||
"vite": "^6.0.11",
|
||||
"vite-plugin-vuetify": "^2.0.4"
|
||||
"vite-plugin-vuetify": "^2.1.0"
|
||||
}
|
||||
}
|
||||
+13
-15
@@ -1,23 +1,25 @@
|
||||
<template>
|
||||
<!-- Инициализация проекта -->
|
||||
<router-view />
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import {useAccountStore} from '@/store/AccountStore'
|
||||
const accountStore = useAccountStore()
|
||||
accountStore.setUser(accountStore.getuserFromStorage())
|
||||
|
||||
import { useAccountStore } from '@/store/AccountStore';
|
||||
/**
|
||||
* Получаем информацию о юзере из стора.
|
||||
*/
|
||||
const accountStore = useAccountStore();
|
||||
console.log("dfdffdfdf");
|
||||
accountStore.setUser(accountStore.getuserFromStorage());
|
||||
</script>
|
||||
|
||||
<style>
|
||||
|
||||
|
||||
::-webkit-scrollbar {
|
||||
width: 1px;
|
||||
height: 6px;
|
||||
}
|
||||
/* Track */
|
||||
::-webkit-scrollbar-track {
|
||||
|
||||
-webkit-border-radius: 6px;
|
||||
border-radius: 6px;
|
||||
}
|
||||
@@ -25,17 +27,14 @@ import {useAccountStore} from '@/store/AccountStore'
|
||||
::-webkit-scrollbar-thumb {
|
||||
-webkit-border-radius: 6px;
|
||||
border-radius: 6px;
|
||||
background: rgb(var(--v-theme-scrollbar))
|
||||
|
||||
background: rgb(var(--v-theme-scrollbar));
|
||||
}
|
||||
::-webkit-scrollbar-thumb:window-inactive {
|
||||
background: rgb(var(--v-theme-scrollbar))
|
||||
background: rgb(var(--v-theme-scrollbar));
|
||||
}
|
||||
|
||||
|
||||
|
||||
.bggrad {
|
||||
background: linear-gradient(to top right, rgba(19,84,122,.8), rgba(128,208,199,.8));
|
||||
background: linear-gradient(to top right, rgba(19, 84, 122, 0.8), rgba(128, 208, 199, 0.8));
|
||||
}
|
||||
|
||||
.bgCard {
|
||||
@@ -46,7 +45,6 @@ import {useAccountStore} from '@/store/AccountStore'
|
||||
.bgText {
|
||||
background: #ffffffb0;
|
||||
line-height: 2.1rem !important;
|
||||
|
||||
}
|
||||
|
||||
.gap {
|
||||
@@ -54,7 +52,7 @@ import {useAccountStore} from '@/store/AccountStore'
|
||||
}
|
||||
|
||||
.w100 {
|
||||
max-width: 100%!important
|
||||
max-width: 100% !important;
|
||||
}
|
||||
|
||||
.bottom-alert {
|
||||
|
||||
@@ -1,59 +1,90 @@
|
||||
<!-- Обратный отсчет: Компонент для отображения оставшегося времени голосования -->
|
||||
<template>
|
||||
<h6>ДО КОНЦА ГОЛОСОВАНИЯ ОСТАЛОСЬ:</h6>
|
||||
<div class="text-red text-h6">{{ displayDays }} дней {{ displayHours }} часов {{ displayMinutes }} минут</div>
|
||||
<div class="text-red text-h6">
|
||||
{{ displayDays }} дней {{ displayHours }} часов {{ displayMinutes }} минут
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { onMounted, ref } from 'vue';
|
||||
|
||||
export default {
|
||||
data: () => ({
|
||||
displayDays: 0,
|
||||
displayHours: 0,
|
||||
displayMinutes: 0
|
||||
}),
|
||||
setup() {
|
||||
/**
|
||||
* Хранит количество оставшихся дней.
|
||||
*/
|
||||
const displayDays = ref(0);
|
||||
|
||||
computed: {
|
||||
_seconds: () => 1000,
|
||||
_minutes() {
|
||||
return this._seconds * 60
|
||||
},
|
||||
_hours() {
|
||||
return this._minutes * 60
|
||||
},
|
||||
_days() {
|
||||
return this._hours * 24
|
||||
}
|
||||
},
|
||||
/**
|
||||
* Хранит количество оставшихся часов.
|
||||
*/
|
||||
const displayHours = ref(0);
|
||||
|
||||
mounted() {
|
||||
this.countDown();
|
||||
},
|
||||
/**
|
||||
* Хранит количество оставшихся минут.
|
||||
*/
|
||||
const displayMinutes = ref(0);
|
||||
|
||||
methods: {
|
||||
countDown() {
|
||||
/**
|
||||
* Определяет количество миллисекунд в одной секунде.
|
||||
*/
|
||||
const _seconds = 1000;
|
||||
|
||||
/**
|
||||
* Определяет количество миллисекунд в одной минуте.
|
||||
*/
|
||||
const _minutes = _seconds * 60;
|
||||
|
||||
/**
|
||||
* Определяет количество миллисекунд в одном часе.
|
||||
*/
|
||||
const _hours = _minutes * 60;
|
||||
|
||||
/**
|
||||
* Определяет количество миллисекунд в одном дне.
|
||||
*/
|
||||
const _days = _hours * 24;
|
||||
|
||||
/**
|
||||
* @arrowFunc
|
||||
* Обрабатывает обратный отсчет до окончания голосования.
|
||||
*/
|
||||
const countDown = () => {
|
||||
const timer = setInterval(() => {
|
||||
const now = new Date();
|
||||
// здесь задается конец отчета (гггг, мм, дд, остальные цифры не меняются)
|
||||
const end = new Date(2025, 0, 17, 23, 59, 59);
|
||||
// Здесь задается конец отчета (год, месяц, день, часы, минуты, секунды)
|
||||
const end = new Date(2025, 0, 13, 23, 59, 59);
|
||||
const distance = end.getTime() - now.getTime();
|
||||
|
||||
if (distance < 0) {
|
||||
clearInterval(timer);
|
||||
return
|
||||
return;
|
||||
}
|
||||
|
||||
const days = Math.floor(distance / this._days);
|
||||
const hours = Math.floor((distance % this._days) / this._hours);
|
||||
const minutes = Math.floor((distance % this._hours) / this._minutes);
|
||||
const daysLeft = Math.floor(distance / _days);
|
||||
const hoursLeft = Math.floor((distance % _days) / _hours);
|
||||
const minutesLeft = Math.floor((distance % _hours) / _minutes);
|
||||
|
||||
this.displayMinutes = minutes < 10 ? "0" + minutes : minutes;
|
||||
this.displayHours = minutes < 10 & minutes > 10 ? "0" + hours : hours;
|
||||
this.displayDays = days;
|
||||
}, 1000)
|
||||
}
|
||||
}
|
||||
displayDays.value = daysLeft;
|
||||
displayHours.value = hoursLeft < 10 ? '0' + hoursLeft : hoursLeft;
|
||||
displayMinutes.value = minutesLeft < 10 ? '0' + minutesLeft : minutesLeft;
|
||||
}, 1000);
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
countDown();
|
||||
});
|
||||
|
||||
return {
|
||||
displayDays,
|
||||
displayHours,
|
||||
displayMinutes,
|
||||
};
|
||||
},
|
||||
};
|
||||
</script>
|
||||
|
||||
<style>
|
||||
.card-count {
|
||||
font-size: 3em;
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
<template>
|
||||
<v-autocomplete
|
||||
v-model="selectedEmployees"
|
||||
:items="allEmployeesgroupedbydep"
|
||||
class="text-no-wrap ml-4"
|
||||
density="compact"
|
||||
item-title="fio"
|
||||
item-value="id"
|
||||
label="Выберите сотрудников"
|
||||
multiple
|
||||
variant="outlined"
|
||||
>
|
||||
<template #prepend-item>
|
||||
<v-checkbox
|
||||
:model-value="(selectedEmployees?.length || 0) === allEmployees.length"
|
||||
class="pa-0"
|
||||
label="Все"
|
||||
@click="handleSelectAll"
|
||||
></v-checkbox>
|
||||
</template>
|
||||
<template #selection="{ item }">
|
||||
<v-chip :prepend-avatar="checkremote(`${spravURL}${item.raw.login}.jpg`)">
|
||||
{{ item.raw.familyname }}
|
||||
</v-chip>
|
||||
</template>
|
||||
<template #item="data">
|
||||
<template v-if="typeof data.item.raw !== 'object'">
|
||||
<v-divider />
|
||||
<v-list-group class="pa-4 text-overline text-grey" v-text="data.item.raw"></v-list-group>
|
||||
</template>
|
||||
<template v-else>
|
||||
<v-list-item
|
||||
:append-avatar="checkremote(`${spravURL}${data.item.raw.login}.jpg`)
|
||||
" density="compact" slim @click="onEmployeesChange(data.item.raw.id)"
|
||||
>
|
||||
<template #prepend>
|
||||
<v-checkbox
|
||||
:model-value="selectedEmployees.includes(data.item.raw.id)"
|
||||
density="compact"
|
||||
hide-details
|
||||
></v-checkbox>
|
||||
</template>
|
||||
<v-list-item-title class="text-third" v-text="data.item.raw.fio"></v-list-item-title>
|
||||
</v-list-item>
|
||||
</template>
|
||||
</template>
|
||||
</v-autocomplete>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { computed, ref } from 'vue';
|
||||
import { getEmployees, spravURL } from '@/utils/axios-api';
|
||||
import { checkremote } from '@/utils/universal_functions.js';
|
||||
|
||||
export default {
|
||||
props: {
|
||||
modelValue: Array,
|
||||
},
|
||||
emits: ['update:modelValue'],
|
||||
setup(props, { emit }) {
|
||||
const selectedEmployees = ref(props.modelValue || []);
|
||||
const groupedEmployees = ref([]);
|
||||
const allEmployees = computed(() => [...groupedEmployees.value]);
|
||||
|
||||
getEmployees().then((r) => (groupedEmployees.value = r));
|
||||
|
||||
const allEmployeesgroupedbydep = computed(() => {
|
||||
let groupped = [];
|
||||
for (let x of allEmployees.value.sort(
|
||||
(a, b) => a.id_dict_department - b.id_dict_department,
|
||||
)) {
|
||||
if (!groupped.includes(x.department)) groupped.push(x.department);
|
||||
groupped.push(x);
|
||||
}
|
||||
return groupped;
|
||||
});
|
||||
|
||||
const onEmployeesChange = (employeeId) => {
|
||||
const index = selectedEmployees.value.indexOf(employeeId);
|
||||
if (index !== -1) {
|
||||
selectedEmployees.value.splice(index, 1);
|
||||
} else {
|
||||
selectedEmployees.value.push(employeeId);
|
||||
}
|
||||
emit('update:modelValue', selectedEmployees.value);
|
||||
};
|
||||
|
||||
const handleSelectAll = () => {
|
||||
if (selectedEmployees.value.length === allEmployees.value.length) {
|
||||
selectedEmployees.value = [];
|
||||
} else {
|
||||
selectedEmployees.value = allEmployees.value.map(emp => emp.id);
|
||||
}
|
||||
emit('update:modelValue', selectedEmployees.value);
|
||||
};
|
||||
|
||||
return {
|
||||
selectedEmployees,
|
||||
allEmployeesgroupedbydep,
|
||||
onEmployeesChange,
|
||||
handleSelectAll,
|
||||
checkremote,
|
||||
spravURL,
|
||||
allEmployees
|
||||
};
|
||||
},
|
||||
};
|
||||
</script>
|
||||
@@ -50,7 +50,7 @@
|
||||
|
||||
<script>
|
||||
import { ref } from "vue";
|
||||
import { useAlertStore } from "@/store/useAlertStore";
|
||||
import { useAlertStore } from "@/store/UseAlertStore";
|
||||
import { clearAxios } from "@/utils/axios-api";
|
||||
|
||||
export default {
|
||||
|
||||
@@ -51,9 +51,7 @@
|
||||
<v-col>
|
||||
<calendar-my
|
||||
:calendars="
|
||||
calendarForMy.filter(
|
||||
(e) => e.author == accountStore.user.is_idEmployee
|
||||
)
|
||||
calendarForMy.filter((e) => e.author == accountStore.user.is_idEmployee)
|
||||
"
|
||||
title="Мои календари"
|
||||
@getCalendar="getCalendar"
|
||||
@@ -61,9 +59,7 @@
|
||||
|
||||
<calendar-my
|
||||
:calendars="
|
||||
calendarForMy.filter(
|
||||
(e) => e.author != accountStore.user.is_idEmployee
|
||||
)
|
||||
calendarForMy.filter((e) => e.author != accountStore.user.is_idEmployee)
|
||||
"
|
||||
title="Подписки"
|
||||
/>
|
||||
@@ -103,18 +99,18 @@
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { ref, onMounted, watch } from "vue";
|
||||
import { useWeekendsStore } from "@/store/WeekendsStore";
|
||||
import EventCreate from "@/components/calendar_of_events/event-create.vue";
|
||||
import CalendarMy from "@/components/calendar_of_events/calendar-my.vue";
|
||||
import { axiosApiInstance } from "@/utils/axios-api";
|
||||
import { useAccountStore } from "@/store/AccountStore";
|
||||
import CalendarFull from "@/components/calendar_of_events/UI_calendar/calendarFull.vue";
|
||||
import { ref, onMounted, watch } from 'vue';
|
||||
import { useWeekendsStore } from '@/store/WeekendsStore';
|
||||
import EventCreate from '@/components/calendar_of_events/event-create.vue';
|
||||
import CalendarMy from '@/components/calendar_of_events/calendar-my.vue';
|
||||
import { axiosApiInstance } from '@/utils/axios-api';
|
||||
import { useAccountStore } from '@/store/AccountStore';
|
||||
import CalendarFull from '@/components/calendar_of_events/UI_calendar/calendarFull.vue';
|
||||
|
||||
export default {
|
||||
components: { EventCreate, CalendarMy, CalendarFull },
|
||||
|
||||
setup(props, { emit }) {
|
||||
setup() {
|
||||
const accountStore = useAccountStore();
|
||||
const showDialog = ref(false);
|
||||
const week = useWeekendsStore();
|
||||
@@ -135,13 +131,8 @@ export default {
|
||||
};
|
||||
|
||||
const getCalendar = () => {
|
||||
axiosApiInstance
|
||||
.get(`api/calendar_of_events/my_calendars/`)
|
||||
.then((res) => {
|
||||
res.data.forEach(
|
||||
(e) =>
|
||||
(e.visible = accountStore.calendar.includes(e.id) ? false : true)
|
||||
);
|
||||
axiosApiInstance.get(`api/calendar_of_events/my_calendars/`).then((res) => {
|
||||
res.data.forEach((e) => (e.visible = accountStore.calendar.includes(e.id) ? false : true));
|
||||
calendarForMy.value = res.data;
|
||||
});
|
||||
};
|
||||
@@ -150,21 +141,17 @@ export default {
|
||||
|
||||
const getEvents = (idEvent, clik) => {
|
||||
axiosApiInstance
|
||||
.get(
|
||||
`api/calendar_of_events/my_events/${
|
||||
idEvent === undefined ? "" : `?id=${idEvent}`
|
||||
}`
|
||||
)
|
||||
.get(`api/calendar_of_events/my_events/${idEvent === undefined ? '' : `?id=${idEvent}`}`)
|
||||
.then((res) => {
|
||||
if (idEvent === undefined) {
|
||||
res.data.event = {
|
||||
name: "",
|
||||
name: '',
|
||||
participant: [accountStore.user.is_idEmployee],
|
||||
files: [],
|
||||
date_start: new Date(),
|
||||
date_end: new Date(),
|
||||
period: null,
|
||||
description: "",
|
||||
description: '',
|
||||
calendar: null,
|
||||
};
|
||||
}
|
||||
@@ -184,23 +171,20 @@ export default {
|
||||
};
|
||||
|
||||
const weekendsData = () => {
|
||||
cal.value.$el
|
||||
.querySelectorAll(".v-date-picker-month__day")
|
||||
.forEach((e) => {
|
||||
let datas = e.getAttribute("data-v-date");
|
||||
let weeks =
|
||||
new Date(datas).getDay() === 6 || new Date(datas).getDay() === 0;
|
||||
cal.value.$el.querySelectorAll('.v-date-picker-month__day').forEach((e) => {
|
||||
let datas = e.getAttribute('data-v-date');
|
||||
let weeks = new Date(datas).getDay() === 6 || new Date(datas).getDay() === 0;
|
||||
if (weeks) {
|
||||
e.querySelectorAll("span").forEach((n) => {
|
||||
n.classList.add("text-red");
|
||||
e.querySelectorAll('span').forEach((n) => {
|
||||
n.classList.add('text-red');
|
||||
});
|
||||
}
|
||||
if (MyMonth.value in week.week[MyYear.value]) {
|
||||
if (week.week[MyYear.value][MyMonth.value].includes(datas)) {
|
||||
e.querySelectorAll("span").forEach((n) => {
|
||||
n.classList.add("text-red");
|
||||
if (n.classList.contains("text-red") && weeks) {
|
||||
n.classList.replace("text-red", "text-black");
|
||||
e.querySelectorAll('span').forEach((n) => {
|
||||
n.classList.add('text-red');
|
||||
if (n.classList.contains('text-red') && weeks) {
|
||||
n.classList.replace('text-red', 'text-black');
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -214,11 +198,11 @@ export default {
|
||||
|
||||
watch(
|
||||
() => week.week,
|
||||
(newValue, oldValue) => {
|
||||
(newValue) => {
|
||||
if (newValue) {
|
||||
weekendsData();
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
const CheckingStore = () => {
|
||||
@@ -230,7 +214,7 @@ export default {
|
||||
};
|
||||
|
||||
const infoEvent = (i) => {
|
||||
console.log(i, "iiiiiiiiii");
|
||||
console.log(i, 'iiiiiiiiii');
|
||||
};
|
||||
|
||||
return {
|
||||
|
||||
@@ -16,11 +16,7 @@
|
||||
return-object
|
||||
>
|
||||
<template v-slot:selection="{ item }">
|
||||
<v-chip
|
||||
class="me-2"
|
||||
color="teal-darken-3"
|
||||
size="small"
|
||||
label>
|
||||
<v-chip class="me-2" color="teal-darken-3" size="small" label>
|
||||
<span> {{ item.title }}</span>
|
||||
<v-icon
|
||||
v-if="item.value != accountStore.user.is_idEmployee"
|
||||
@@ -53,12 +49,7 @@
|
||||
<template v-slot:item="{ props, item }">
|
||||
<v-list-group v-bind="props" :value="item.raw.title">
|
||||
<template v-slot:activator="{ props }">
|
||||
<v-list-item
|
||||
v-bind="props"
|
||||
@click.stop=""
|
||||
density="compact"
|
||||
class="text-body-2"
|
||||
>
|
||||
<v-list-item v-bind="props" @click.stop="" density="compact" class="text-body-2">
|
||||
<template v-slot:prepend>
|
||||
<v-checkbox-btn
|
||||
@click.stop="selectedStaff = item.raw"
|
||||
@@ -78,7 +69,7 @@
|
||||
|
||||
<v-list-item
|
||||
v-for="x in item.raw.employees.filter((e) =>
|
||||
e.title.toLowerCase().includes(filtered.toLowerCase())
|
||||
e.title.toLowerCase().includes(filtered.toLowerCase()),
|
||||
)"
|
||||
:key="x.id"
|
||||
:value="x.title"
|
||||
@@ -101,9 +92,9 @@
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { ref, computed } from "vue";
|
||||
import { splitname } from "@/utils/universal_functions";
|
||||
import { useAccountStore } from "@/store/AccountStore";
|
||||
import { ref, computed } from 'vue';
|
||||
import { splitname } from '@/utils/universal_functions';
|
||||
import { useAccountStore } from '@/store/AccountStore';
|
||||
|
||||
export default {
|
||||
props: {
|
||||
@@ -113,18 +104,19 @@ export default {
|
||||
},
|
||||
okey: {
|
||||
type: String,
|
||||
default: "selected",
|
||||
default: 'selected',
|
||||
},
|
||||
},
|
||||
|
||||
setup(props, { emit }) {
|
||||
const filtered = ref("");
|
||||
console.log("sd")
|
||||
const filtered = ref('');
|
||||
const accountStore = useAccountStore();
|
||||
const back = ref([]);
|
||||
|
||||
const staffed = computed({
|
||||
get() {
|
||||
if (props.okey == "editor") {
|
||||
if (props.okey == 'editor') {
|
||||
let ns = [];
|
||||
props.staff.forEach((e) => {
|
||||
let emp = { ...e };
|
||||
@@ -147,10 +139,7 @@ export default {
|
||||
get() {
|
||||
let selected = [];
|
||||
props.staff.forEach((e) => {
|
||||
if (
|
||||
e.employees.length != 1 &&
|
||||
e.employees.every((n) => n[props.okey] == true)
|
||||
) {
|
||||
if (e.employees.length != 1 && e.employees.every((n) => n[props.okey] == true)) {
|
||||
e[props.okey] = true;
|
||||
selected.push(e);
|
||||
} else if (e.employees.length == 1) {
|
||||
@@ -176,13 +165,13 @@ export default {
|
||||
});
|
||||
|
||||
const emitUp = (part) => {
|
||||
if ("employees" in part) {
|
||||
if ('employees' in part) {
|
||||
part.employees.forEach((e) => {
|
||||
if (e.id != accountStore.user.is_idEmployee) {
|
||||
e[props.okey] = !part[props.okey];
|
||||
}
|
||||
});
|
||||
emit("returnIdParticant", {
|
||||
emit('returnIdParticant', {
|
||||
okey: props.okey,
|
||||
staff: part.employees,
|
||||
select: [],
|
||||
@@ -191,7 +180,7 @@ export default {
|
||||
if (part[0].id != accountStore.user.is_idEmployee) {
|
||||
let val = part.every((e) => e[props.okey] == true) ? false : true;
|
||||
cbstaff(part, val);
|
||||
emit("returnIdParticant", {
|
||||
emit('returnIdParticant', {
|
||||
okey: props.okey,
|
||||
staff: back.value,
|
||||
select: [],
|
||||
@@ -200,7 +189,7 @@ export default {
|
||||
}
|
||||
} else {
|
||||
part[props.okey] = !part[props.okey];
|
||||
emit("returnIdParticant", {
|
||||
emit('returnIdParticant', {
|
||||
okey: props.okey,
|
||||
staff: [part],
|
||||
select: [],
|
||||
@@ -213,10 +202,10 @@ export default {
|
||||
if (e.id != accountStore.user.is_idEmployee) {
|
||||
e[props.okey] = value;
|
||||
}
|
||||
if (!("employees" in e)) {
|
||||
if (!('employees' in e)) {
|
||||
back.value.push(e);
|
||||
}
|
||||
if ("employees" in e) {
|
||||
if ('employees' in e) {
|
||||
cbstaff(e.employees, value);
|
||||
}
|
||||
});
|
||||
@@ -226,7 +215,7 @@ export default {
|
||||
return (
|
||||
item.includes(filtered.value) ||
|
||||
itemText.raw.employees.some((e) =>
|
||||
e.title.toLowerCase().includes(filtered.value.toLowerCase())
|
||||
e.title.toLowerCase().includes(filtered.value.toLowerCase()),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -10,10 +10,7 @@
|
||||
<v-row no-gutters class="flex-column">
|
||||
<v-col class="d-flex flex-column">
|
||||
<v-row no-gutters class="align-center">
|
||||
<v-col class="text-body-2 text-text_grey pb-5" lg="2">
|
||||
|
||||
Название
|
||||
</v-col>
|
||||
<v-col class="text-body-2 text-text_grey pb-5" lg="2"> Название </v-col>
|
||||
<v-col>
|
||||
<v-textarea
|
||||
density="compact"
|
||||
@@ -80,8 +77,8 @@
|
||||
<v-icon v-bind="props" icon="mdi-help-circle-outline" />
|
||||
</template>
|
||||
<div class="custom-tooltip">
|
||||
Участники с доступом редактирования смогут изменять поля
|
||||
календаря, а также редактировать и удалять события
|
||||
Участники с доступом редактирования смогут изменять поля календаря, а также
|
||||
редактировать и удалять события
|
||||
</div>
|
||||
</v-tooltip>
|
||||
</v-col>
|
||||
@@ -92,12 +89,12 @@
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { computed, ref } from "vue";
|
||||
import { axiosApiInstance } from "@/utils/axios-api";
|
||||
import calendarCreateSelect from "@/components/calendar_of_events/calendar-create-select.vue";
|
||||
import { useAlertStore } from "@/store/useAlertStore";
|
||||
import DialogCreate from "./UI_calendar/dialogCreate.vue";
|
||||
import { useAccountStore } from "@/store/AccountStore";
|
||||
import { computed, ref } from 'vue';
|
||||
import { axiosApiInstance } from '@/utils/axios-api';
|
||||
import calendarCreateSelect from '@/components/calendar_of_events/calendar-create-select.vue';
|
||||
import { useAlertStore } from '@/store/UseAlertStore';
|
||||
import DialogCreate from './UI_calendar/dialogCreate.vue';
|
||||
import { useAccountStore } from '@/store/AccountStore';
|
||||
|
||||
export default {
|
||||
components: { calendarCreateSelect, DialogCreate },
|
||||
@@ -105,7 +102,7 @@ export default {
|
||||
props: {
|
||||
calendar: {
|
||||
type: Object,
|
||||
default: {},
|
||||
default: () => {},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -113,15 +110,10 @@ export default {
|
||||
const accountStore = useAccountStore();
|
||||
|
||||
const returnIdParticant = (idPart) => {
|
||||
|
||||
idPart.staff.forEach((e) => {
|
||||
let indx = propsCalendar.value.participant.findIndex(
|
||||
(l) => l.participant_calendar == e.id
|
||||
);
|
||||
let ind = propsCalendar.value.participant.find(
|
||||
(l) => l.participant_calendar == e.id
|
||||
);
|
||||
if (idPart.okey == "editor") {
|
||||
let indx = propsCalendar.value.participant.findIndex((l) => l.participant_calendar == e.id);
|
||||
let ind = propsCalendar.value.participant.find((l) => l.participant_calendar == e.id);
|
||||
if (idPart.okey == 'editor') {
|
||||
ind.editor = e.editor;
|
||||
} else {
|
||||
if (e.selected == true) {
|
||||
@@ -135,7 +127,7 @@ export default {
|
||||
}
|
||||
} else {
|
||||
let ind = propsCalendar.value.participant.findIndex(
|
||||
(l) => l.participant_calendar == e.id
|
||||
(l) => l.participant_calendar == e.id,
|
||||
);
|
||||
|
||||
if (ind != -1) {
|
||||
@@ -144,32 +136,29 @@ export default {
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
};
|
||||
|
||||
const propsCalendar = computed({
|
||||
get: () => props.calendar,
|
||||
set: (value) => emit("update:calendar", value),
|
||||
set: (value) => emit('update:calendar', value),
|
||||
});
|
||||
|
||||
const feedalert = useAlertStore().alert;
|
||||
|
||||
const rules = {
|
||||
|
||||
cl_name: [(val) => req(val)],
|
||||
cl_descr: [(val) => req(val)],
|
||||
};
|
||||
|
||||
const titleCard = ref("");
|
||||
const titleCard = ref('');
|
||||
const newCalendar = ref(false);
|
||||
|
||||
const calendarNewOrOld = () => {
|
||||
if (propsCalendar.value.hasOwnProperty("id")) {
|
||||
titleCard.value = "Редактирование календаря";
|
||||
if (propsCalendar.value.author != accountStore.user.is_idEmployee)
|
||||
newCalendar.value = true;
|
||||
if ('id' in propsCalendar.value) {
|
||||
titleCard.value = 'Редактирование календаря';
|
||||
if (propsCalendar.value.author != accountStore.user.is_idEmployee) newCalendar.value = true;
|
||||
} else {
|
||||
titleCard.value = "Новый календарь";
|
||||
titleCard.value = 'Новый календарь';
|
||||
|
||||
newCalendar.value = true;
|
||||
}
|
||||
@@ -186,20 +175,17 @@ export default {
|
||||
.then((result) => {
|
||||
feedalert.alert = true;
|
||||
feedalert.text = result.data.mess;
|
||||
feedalert.ico = "mdi-check";
|
||||
feedalert.color = "green-darken-4";
|
||||
emit("getCalendar");
|
||||
emit("closeDialog");
|
||||
feedalert.ico = 'mdi-check';
|
||||
feedalert.color = 'green-darken-4';
|
||||
emit('getCalendar');
|
||||
emit('closeDialog');
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const staff = ref([]);
|
||||
|
||||
axiosApiInstance
|
||||
|
||||
.get("api/calendar_of_events/get_employees/")
|
||||
.then((res) => {
|
||||
axiosApiInstance.get('api/calendar_of_events/get_employees/').then((res) => {
|
||||
staff.value = res.data.filter((e) => e.employees.length > 0);
|
||||
});
|
||||
|
||||
@@ -209,7 +195,7 @@ export default {
|
||||
if (propsCalendar.value.participant.length > 0) {
|
||||
e.employees.forEach((empl) => {
|
||||
let ab = propsCalendar.value.participant.find(
|
||||
(a) => a.participant_calendar === empl.id
|
||||
(a) => a.participant_calendar === empl.id,
|
||||
);
|
||||
if (ab) {
|
||||
empl.selected = true;
|
||||
@@ -227,21 +213,21 @@ export default {
|
||||
});
|
||||
|
||||
const color = [
|
||||
"red",
|
||||
"pink",
|
||||
"deep-orange",
|
||||
"amber",
|
||||
"yellow",
|
||||
"lime",
|
||||
"light-green",
|
||||
"green",
|
||||
"light-blue",
|
||||
"blue",
|
||||
"indigo",
|
||||
"deep-purple",
|
||||
"purple",
|
||||
"blue-grey",
|
||||
"brown",
|
||||
'red',
|
||||
'pink',
|
||||
'deep-orange',
|
||||
'amber',
|
||||
'yellow',
|
||||
'lime',
|
||||
'light-green',
|
||||
'green',
|
||||
'light-blue',
|
||||
'blue',
|
||||
'indigo',
|
||||
'deep-purple',
|
||||
'purple',
|
||||
'blue-grey',
|
||||
'brown',
|
||||
];
|
||||
|
||||
const colorPik = (col) => {
|
||||
@@ -258,16 +244,15 @@ export default {
|
||||
.then((result) => {
|
||||
feedalert.alert = true;
|
||||
feedalert.text = result.data.mess;
|
||||
feedalert.ico = "mdi-check";
|
||||
feedalert.color = "orange-accent-1";
|
||||
emit("getCalendar");
|
||||
feedalert.ico = 'mdi-check';
|
||||
feedalert.color = 'orange-accent-1';
|
||||
emit('getCalendar');
|
||||
});
|
||||
emit("closeDialog");
|
||||
emit('closeDialog');
|
||||
};
|
||||
|
||||
const req = (val) => {
|
||||
|
||||
return !!val || "Поле обязательно";
|
||||
return !!val || 'Поле обязательно';
|
||||
};
|
||||
|
||||
return {
|
||||
|
||||
@@ -208,7 +208,7 @@ import { useAccountStore } from "@/store/AccountStore";
|
||||
import UploadingFile from "@/components/UI/defaultportal/uploading-file.vue";
|
||||
import ReminderEvent from "@/components/calendar_of_events/UI_calendar/reminderEvent.vue";
|
||||
import PeriodEvents from "@/components/calendar_of_events/UI_calendar/periodEvents.vue";
|
||||
import { useAlertStore } from "@/store/useAlertStore";
|
||||
import { useAlertStore } from "@/store/UseAlertStore";
|
||||
import { RRule } from "rrule";
|
||||
|
||||
export default {
|
||||
|
||||
@@ -60,7 +60,7 @@ import { ref, onMounted, computed } from 'vue'
|
||||
import { axiosApiInstance } from '@/utils/axios-api'
|
||||
|
||||
import FeedstarLike from '@/components/UI/feedback/feedstar-like.vue'
|
||||
import { useAlertStore } from '@/store/useAlertStore'
|
||||
import { useAlertStore } from '@/store/UseAlertStore'
|
||||
|
||||
export default {
|
||||
components: { FeedstarLike },
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<template>
|
||||
|
||||
<!-- Карусель: Компонент для отображения изображений и видео с сервера в виде карусели -->
|
||||
<v-carousel
|
||||
v-model="currentslide"
|
||||
:interval="interval"
|
||||
@@ -12,27 +12,10 @@
|
||||
color="white"
|
||||
@update:modelValue="slidechanged"
|
||||
>
|
||||
|
||||
<template v-for="(x, i) in carous" :key="i">
|
||||
<v-carousel-item
|
||||
v-if="!x.link.endsWith('mp4')"
|
||||
:src="`${burl}${x.link}`"
|
||||
cover
|
||||
eager
|
||||
>
|
||||
|
||||
<v-container
|
||||
fill-height
|
||||
fluid
|
||||
pa-0
|
||||
ma-0
|
||||
pb-3
|
||||
class="flex-column h-100 d-flex"
|
||||
>
|
||||
<v-card
|
||||
v-if="x.text != '' || x.title != null"
|
||||
class="bgCard h-100 d-flex flex-column"
|
||||
>
|
||||
<v-carousel-item v-if="!x.link.endsWith('mp4')" :src="`${burl}${x.link}`" cover eager>
|
||||
<v-container fill-height fluid pa-0 ma-0 pb-3 class="flex-column h-100 d-flex">
|
||||
<v-card v-if="x.text !== '' || x.title != null" class="bgCard h-100 d-flex flex-column">
|
||||
<v-card-title
|
||||
v-if="x.title != null"
|
||||
class="text-h3 text-uppercase titles text-text_carous ma-1 mb-0"
|
||||
@@ -42,17 +25,12 @@
|
||||
{{ x.title }}
|
||||
</v-col>
|
||||
<v-col class="flex-grow-0">
|
||||
<v-img
|
||||
width="50"
|
||||
:aspect-ratio="1"
|
||||
:src="`${burl}${x.sender}`"
|
||||
cover
|
||||
/>
|
||||
<v-img width="50" :aspect-ratio="1" :src="`${burl}${x.sender}`" cover />
|
||||
</v-col>
|
||||
</v-row>
|
||||
</v-card-title>
|
||||
<v-card-text
|
||||
v-if="x.text != ''"
|
||||
v-if="x.text !== ''"
|
||||
class="w-50 flex-grow-0 text-h6 bgText overflow-auto ma-1 pa-0"
|
||||
>
|
||||
<v-textarea
|
||||
@@ -71,115 +49,130 @@
|
||||
</v-container>
|
||||
</v-carousel-item>
|
||||
<v-carousel-item v-else>
|
||||
|
||||
<div class="d-flex justify-center">
|
||||
<video
|
||||
ref="videoElement"
|
||||
style="height: 450px"
|
||||
|
||||
controls
|
||||
|
||||
preload="metadata"
|
||||
@ended="ended"
|
||||
@loadedmetadata="interval = 10000000000"
|
||||
>
|
||||
<source :src="`${burl}${x.link}`" type="video/mp4" />
|
||||
|
||||
Текущий браузер не поддерживает воспроизведение этого видео.
|
||||
</video>
|
||||
</div>
|
||||
<!-- currentslide=currentslide<carous.length-1?currentslide+1:0 -->
|
||||
</v-carousel-item>
|
||||
</template>
|
||||
</v-carousel>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { ref, computed } from "vue";
|
||||
import { baseURL } from "@/utils/axios-api";
|
||||
import { axiosApiInstance } from "@/utils/axios-api";
|
||||
import { useAlertStore } from "@/store/useAlertStore";
|
||||
import { ref } from 'vue';
|
||||
import { baseURL } from '@/utils/axios-api';
|
||||
import { axiosApiInstance } from '@/utils/axios-api';
|
||||
import { useAlertStore } from '@/store/UseAlertStore';
|
||||
|
||||
export default {
|
||||
|
||||
setup() {
|
||||
const currentslide=ref(0)
|
||||
/**
|
||||
* Хранит индекс текущего слайда карусели.
|
||||
*/
|
||||
const currentslide = ref(0);
|
||||
|
||||
/**
|
||||
* Базовый URL для загрузки медиа.
|
||||
*/
|
||||
const burl = baseURL.slice(0, -1);
|
||||
const videoElement=ref(null)
|
||||
const carous = ref([{ link: `/media/newsimage/scales.jpg`, "title": null, "text": "" }]);
|
||||
|
||||
/**
|
||||
* Ссылка на элемент видео.
|
||||
*/
|
||||
const videoElement = ref(null);
|
||||
|
||||
/**
|
||||
* Хранит массив данных карусели, по умолчанию содержит одно изображение.
|
||||
*/
|
||||
const carous = ref([{ link: `/media/newsimage/scales.jpg`, title: null, text: '' }]);
|
||||
|
||||
/**
|
||||
* Получает объект alert из хранилища alert для уведомлений.
|
||||
*/
|
||||
const feedalert = useAlertStore().alert;
|
||||
|
||||
/**
|
||||
* Интервал переключения слайдов в миллисекундах.
|
||||
*/
|
||||
const interval = ref(10000);
|
||||
|
||||
/**
|
||||
* @arrowFunc
|
||||
* Обрабатывает запрос для получения данных карусели с сервера.
|
||||
*/
|
||||
const getfromserver = () => {
|
||||
axiosApiInstance.get("api/navigation/carousels/").then((result) => {
|
||||
if (result.data.mess != "") {
|
||||
axiosApiInstance.get('api/navigation/carousels/').then((result) => {
|
||||
if (result.data.mess !== '') {
|
||||
feedalert.alert = true;
|
||||
feedalert.text = result.data.mess;
|
||||
feedalert.color = "red-darken-2";
|
||||
feedalert.ico = "mdi-alert-outline";
|
||||
feedalert.color = 'red-darken-2';
|
||||
feedalert.ico = 'mdi-alert-outline';
|
||||
}
|
||||
|
||||
console.log(result.data);
|
||||
if (result.data.result.length > 0) {
|
||||
carous.value = result.data.result;
|
||||
}
|
||||
|
||||
});
|
||||
};
|
||||
|
||||
getfromserver();
|
||||
const interval=ref(10000)
|
||||
|
||||
/**
|
||||
* @arrowFunc
|
||||
* Управляет изменением слайда и переключением интервала в зависимости от типа медиа.
|
||||
*/
|
||||
const slidechanged = () => {
|
||||
console.log(videoElement.value);
|
||||
|
||||
if (carous.value[currentslide.value].link.endsWith('mp4')) {
|
||||
// При переключении на видео, останавливаем все другие видео
|
||||
videoElement.value.forEach((e) => {
|
||||
if(e.currentSrc!=burl+carous.value[currentslide.value].link){
|
||||
e.pause()
|
||||
|
||||
if (e.currentSrc !== burl + carous.value[currentslide.value].link) {
|
||||
e.pause();
|
||||
}
|
||||
// else{
|
||||
// console.log("sdflkhlh");
|
||||
// e.play()
|
||||
// }
|
||||
})
|
||||
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
if (carous.value[currentslide.value].link.endsWith('mp4')) {
|
||||
interval.value = 10000000000
|
||||
|
||||
|
||||
interval.value = 10000000000;
|
||||
} else {
|
||||
|
||||
interval.value=10000
|
||||
interval.value = 10000;
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
/**
|
||||
* @arrowFunc
|
||||
* Обрабатывает окончание воспроизведения видео и переключает слайд.
|
||||
* @param {Object} val Событие окончания воспроизведения видео.
|
||||
*/
|
||||
const ended = (val) => {
|
||||
val.target.currentTime = 0
|
||||
val.target.currentTime = 0;
|
||||
val.target.pause();
|
||||
document.exitFullscreen()
|
||||
currentslide.value=currentslide.value<carous.value.length-1?currentslide.value+1:0
|
||||
}
|
||||
document.exitFullscreen();
|
||||
currentslide.value =
|
||||
currentslide.value < carous.value.length - 1 ? currentslide.value + 1 : 0;
|
||||
};
|
||||
|
||||
return {
|
||||
slidechanged,
|
||||
videoElement,
|
||||
currentslide,
|
||||
getfromserver,
|
||||
interval,
|
||||
// intervalcomp,
|
||||
burl,
|
||||
carous,
|
||||
ended
|
||||
ended,
|
||||
};
|
||||
},
|
||||
};
|
||||
</script>
|
||||
|
||||
<style>
|
||||
.titles {
|
||||
font-family: cursive !important;
|
||||
|
||||
@@ -1,54 +1,24 @@
|
||||
<template>
|
||||
<!-- Компонент данных: Отображает цифры в виде слайд-группы карточек с анимацией счетчика -->
|
||||
<v-card class="d-flex ml-3">
|
||||
<v-sheet
|
||||
class="mx-auto"
|
||||
elevation="0"
|
||||
max-width="813"
|
||||
|
||||
>
|
||||
<v-slide-group
|
||||
v-model="model"
|
||||
class="pa-0"
|
||||
selected-class="bg-primary"
|
||||
mandatory
|
||||
show-arrows
|
||||
|
||||
>
|
||||
|
||||
<v-slide-group-item
|
||||
v-for="n in digitalData"
|
||||
:key="n"
|
||||
|
||||
>
|
||||
|
||||
|
||||
<v-card
|
||||
|
||||
class="ma-2 mt-4 d-flex flex-column"
|
||||
height="100"
|
||||
width="169"
|
||||
elevation="0"
|
||||
|
||||
>
|
||||
<!-- <v-img
|
||||
height="100"
|
||||
:src="`${burl}${n.img}`"
|
||||
cover
|
||||
class="text-white"
|
||||
> -->
|
||||
<v-sheet class="mx-auto" elevation="0" max-width="813">
|
||||
<v-slide-group v-model="model" class="pa-0" mandatory selected-class="bg-primary" show-arrows>
|
||||
<v-slide-group-item v-for="n in digitalData" :key="n">
|
||||
<v-card class="ma-2 mt-4 d-flex flex-column" elevation="0" height="100" width="169">
|
||||
<v-card class="h-100 text-center g text-black_grey">
|
||||
<v-card-title class="statstyle my-2 py-0 text-overline font-weight-bold">
|
||||
{{ n.status }}
|
||||
</v-card-title>
|
||||
<v-card-text class="numstyle mt-4 py-0 font-weight-bold">
|
||||
<vue3-autocounter ref='counter' :startAmount='0' :endAmount='Number(n.num)' :duration='1'/>
|
||||
<vue3-autocounter
|
||||
ref="counter"
|
||||
:duration="1"
|
||||
:endAmount="Number(n.num)"
|
||||
:startAmount="0"
|
||||
/>
|
||||
</v-card-text>
|
||||
</v-card>
|
||||
|
||||
<!-- </v-img> -->
|
||||
</v-card>
|
||||
|
||||
|
||||
</v-slide-group-item>
|
||||
</v-slide-group>
|
||||
</v-sheet>
|
||||
@@ -56,29 +26,32 @@
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { ref } from 'vue'
|
||||
import { baseURL } from '@/utils/axios-api'
|
||||
|
||||
import { ref } from 'vue';
|
||||
import { baseURL } from '@/utils/axios-api';
|
||||
|
||||
export default {
|
||||
|
||||
|
||||
|
||||
props: {
|
||||
digitalData: {
|
||||
type: Object,
|
||||
default: {}
|
||||
}
|
||||
default: () => {},
|
||||
comment: 'Объект с данными для отображения',
|
||||
},
|
||||
},
|
||||
|
||||
setup() {
|
||||
const burl = baseURL.slice(0,-1)
|
||||
const model = ref(false)
|
||||
/**
|
||||
* Получает базовый URL из конфигурации axios.
|
||||
*/
|
||||
const burl = baseURL.slice(0, -1);
|
||||
|
||||
/**
|
||||
* Хранит выбранное значение модели для v-slide-group.
|
||||
*/
|
||||
const model = ref(false);
|
||||
|
||||
return {model, burl}
|
||||
}
|
||||
}
|
||||
return { model, burl };
|
||||
},
|
||||
};
|
||||
</script>
|
||||
|
||||
<style>
|
||||
@@ -95,7 +68,6 @@ export default {
|
||||
}
|
||||
|
||||
.g {
|
||||
/* background-color: rgb(240 248 255 / 35%);; */
|
||||
background-color: rgb(255 255 255);;
|
||||
background-color: rgb(255, 255, 255);
|
||||
}
|
||||
</style>
|
||||
Whitespace-only changes.
@@ -180,7 +180,8 @@ export default {
|
||||
|
||||
const onPickFile = (ex) => {
|
||||
const sdata = new FormData()
|
||||
sdata.append('dailyfiles', dailyfiles.value[0])
|
||||
sdata.append('dailyfiles', dailyfiles.value)
|
||||
console.log(dailyfiles.value);
|
||||
axiosApiInstance.post(`api/general_vacation/dailyroundup/?excel=${ex}`, sdata).then(result => {
|
||||
info.value = result.data
|
||||
dailyfun()
|
||||
|
||||
File renamed without changes.
@@ -1,10 +1,8 @@
|
||||
|
||||
|
||||
<template>
|
||||
<Line :data="data" :options="options" />
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
<script>
|
||||
import {
|
||||
Chart as ChartJS,
|
||||
CategoryScale,
|
||||
@@ -14,12 +12,12 @@ import {
|
||||
Title,
|
||||
Tooltip,
|
||||
Legend,
|
||||
TimeScale
|
||||
} from 'chart.js'
|
||||
import { Line } from 'vue-chartjs'
|
||||
import * as chartConfig from './chartConfig.js'
|
||||
import ChartDataLabels from 'chartjs-plugin-datalabels'
|
||||
import 'chartjs-adapter-moment'
|
||||
TimeScale,
|
||||
} from 'chart.js';
|
||||
import { Line } from 'vue-chartjs';
|
||||
import * as chartConfig from './chartConfig.js';
|
||||
import ChartDataLabels from 'chartjs-plugin-datalabels';
|
||||
import 'chartjs-adapter-moment';
|
||||
ChartJS.register(
|
||||
ChartDataLabels,
|
||||
CategoryScale,
|
||||
@@ -29,16 +27,16 @@ ChartJS.register(
|
||||
Title,
|
||||
Tooltip,
|
||||
Legend,
|
||||
TimeScale
|
||||
)
|
||||
TimeScale,
|
||||
);
|
||||
|
||||
export default {
|
||||
name: 'App',
|
||||
components: {
|
||||
Line
|
||||
Line,
|
||||
},
|
||||
data() {
|
||||
return chartConfig
|
||||
}
|
||||
}
|
||||
return chartConfig;
|
||||
},
|
||||
};
|
||||
</script>
|
||||
@@ -56,7 +56,7 @@
|
||||
import { ref } from 'vue'
|
||||
import { baseURL } from '@/utils/axios-api'
|
||||
import { axiosApiInstance } from '@/utils/axios-api'
|
||||
import { useAlertStore } from '@/store/useAlertStore'
|
||||
import { useAlertStore } from '@/store/UseAlertStore'
|
||||
|
||||
export default {
|
||||
|
||||
@@ -76,8 +76,8 @@ export default {
|
||||
|
||||
const onPickFile = (ex) => {
|
||||
const sdata = new FormData()
|
||||
sdata.append('dailyfiles', dailyfiles.value[0])
|
||||
|
||||
sdata.append('dailyfiles', dailyfiles.value)
|
||||
console.log(dailyfiles.value);
|
||||
axiosApiInstance.post(`api/general_vacation/dailyroundup/?excel=${ex}`, sdata).then(result => {
|
||||
textFromAlert(result.data['mess'])
|
||||
})
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
<template>
|
||||
<div class="px-4">
|
||||
{{ displayDays + declOfNum(displayDays, [' день', ' дня', ' дней']) }}
|
||||
{{ displayHours + declOfNum(displayHours, [' час', ' часа', ' часов']) }}
|
||||
{{ displayMinutes + declOfNum(displayMinutes, [' минута', ' минуты', ' минут']) }}
|
||||
{{ displaySeconds + declOfNum(displaySeconds, [' секунда', ' секунды', ' секунд']) }}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
<template>
|
||||
<v-container class="pa-4">
|
||||
<v-row class="justify-center mt-6">
|
||||
<v-col cols="12" md="8" lg="6">
|
||||
<v-card elevation="2">
|
||||
<v-card-title class="text-h6 font-weight-bold">Информация</v-card-title>
|
||||
<v-card-text class="d-flex flex-lg-column ga-6 border-b-thin">
|
||||
<p>
|
||||
{{ data?.description }}
|
||||
</p>
|
||||
<p>
|
||||
<strong>Время на прохождение — {{ data?.time }} минут</strong>
|
||||
</p>
|
||||
<p>
|
||||
<strong>Срок окончания — {{ new Date(data?.dateend).toLocaleDateString() }}</strong>
|
||||
</p>
|
||||
</v-card-text>
|
||||
<v-card-actions class="mx-2 my-4">
|
||||
<p>Попытка 1 из {{ data?.attemps_number }}</p>
|
||||
<v-btn color="white" class="ml-auto bg-teal-darken-1 px-9" @click="startTest">
|
||||
Начать
|
||||
</v-btn>
|
||||
</v-card-actions>
|
||||
</v-card>
|
||||
</v-col>
|
||||
</v-row>
|
||||
</v-container>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
props: {
|
||||
startTest: Function,
|
||||
data: Object,
|
||||
},
|
||||
};
|
||||
</script>
|
||||
@@ -9,19 +9,22 @@
|
||||
label="Найти тестирование по названию"
|
||||
variant="solo"
|
||||
@click:append-inner="searchTest"
|
||||
clearable/>
|
||||
clearable
|
||||
/>
|
||||
</v-row>
|
||||
</v-container>
|
||||
<!-- Карточка где буду отрисовываться тесты в цикле -->
|
||||
<v-card v-for="cardValue in searchTest" :key="cardValue.id" class="my-2 border-sm">
|
||||
<v-row class="pa-2">
|
||||
<v-col cols="1">
|
||||
<v-img height="125" :src="cardValue.file" />
|
||||
<v-col cols="2" class="justify-center my-auto">
|
||||
<v-img :src="cardValue.file" class="mx-auto" />
|
||||
</v-col>
|
||||
<v-col cols="auto" class="d-flex flex-grow-1">
|
||||
<div class="d-flex flex-column justify-center flex-grow-1">
|
||||
<div class="text-body-1 font-weight-medium mb-2">{{ cardValue.name }}</div>
|
||||
<div class="text-body-1 text-disabled mb-2">{{ cardValue.description }}</div>
|
||||
<div class="text-body-1 text-disabled mb-2" style="max-width: 600px">
|
||||
{{ cardValue.description }}
|
||||
</div>
|
||||
<div class="d-flex ga-4">
|
||||
<slot name="results"></slot>
|
||||
<div v-for="icon in activeTabIcon">
|
||||
@@ -32,12 +35,12 @@
|
||||
</div>
|
||||
</v-col>
|
||||
<v-col cols="auto" class="align-self-center">
|
||||
<slot name="buttons"></slot>
|
||||
<slot name="buttons" :cardValue="cardValue"></slot>
|
||||
</v-col>
|
||||
</v-row>
|
||||
</v-card>
|
||||
<!-- Если данные отсутствуют, выводим сообщение об этом -->
|
||||
<v-container v-if="!searchTest.length" :fluid="true">
|
||||
<v-container v-if="!searchTest.length" :fluid="true" class="h-100">
|
||||
<v-row class="align-center flex-column">
|
||||
<v-icon icon="mdi-note-off-outline" color="grey-lighten-1" size="x-large" />
|
||||
<v-card-title class="text-h4 text-grey-lighten-1">Данные не найдены</v-card-title>
|
||||
@@ -47,8 +50,8 @@
|
||||
|
||||
<script>
|
||||
import moment from 'moment';
|
||||
import { declOfNum } from '@/utils/universal_functions'
|
||||
import { baseURL } from "@/utils/axios-api";
|
||||
import { declOfNum } from '@/utils/universal_functions';
|
||||
import { baseURL } from '@/utils/axios-api';
|
||||
import { ref, computed } from 'vue';
|
||||
|
||||
export default {
|
||||
@@ -63,39 +66,18 @@ export default {
|
||||
},
|
||||
testingCard: {
|
||||
type: Array,
|
||||
default: () => [
|
||||
{
|
||||
id: 1,
|
||||
name: 'Комплекс тестовых вопросов на знание в области информационно-коммуникационных технологий',
|
||||
type: 'test',
|
||||
description: 'Краткое описание тестирования',
|
||||
file: 'https://icdn.lenta.ru/images/2024/03/27/12/20240327123127525/square_1280_63e6b3d7acbfce65d885ae4cf216dfe2.jpg',
|
||||
dateend: new Date(),
|
||||
question_count: 20,
|
||||
time: 20,
|
||||
attemps_number: 3,
|
||||
default: () => [],
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
name: 'Удобство раздела тестирования',
|
||||
type: 'test',
|
||||
description: 'Опрос среди сотрудников ЦОД МФ',
|
||||
file: 'https://icdn.lenta.ru/images/2024/03/27/12/20240327123127525/square_1280_63e6b3d7acbfce65d885ae4cf216dfe2.jpg',
|
||||
dateend: new Date(),
|
||||
question_count: 28,
|
||||
time: 15,
|
||||
attemps_number: 1,
|
||||
},
|
||||
]
|
||||
}
|
||||
},
|
||||
setup(props) {
|
||||
const search = ref('');
|
||||
|
||||
const searchTest = computed(() => {
|
||||
if (!search.value) return props.testingCard
|
||||
return props.testingCard.filter(item => item.name.toLowerCase().includes(search.value.toLowerCase()))
|
||||
})
|
||||
if (!search.value) return props.testingCard;
|
||||
return props.testingCard.filter((item) =>
|
||||
item.name.toLowerCase().includes(search.value.toLowerCase()),
|
||||
);
|
||||
});
|
||||
|
||||
const activeTabIcon = computed(() => {
|
||||
let icons = [
|
||||
@@ -118,31 +100,28 @@ export default {
|
||||
{
|
||||
icon: 'mdi-fire',
|
||||
field: 'attemps_number',
|
||||
color: '#FF9800'
|
||||
color: '#FF9800',
|
||||
},
|
||||
]
|
||||
if (props.activeTab == 0) {
|
||||
return icons
|
||||
];
|
||||
if (props.activeTab === 0) {
|
||||
return icons;
|
||||
} else {
|
||||
return icons.splice(1,2)
|
||||
return icons.splice(1, 2);
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
const momenter = (val, field) => {
|
||||
if (field == 'dateend'){
|
||||
return 'до ' + moment(val).format('DD.MM.YYYY, HH:mm')
|
||||
}
|
||||
else if (field == 'question_count') {
|
||||
return val + declOfNum(val, [' вопрос', ' вопроса', ' вопросов'])
|
||||
}
|
||||
else if (field == 'time') {
|
||||
return val + declOfNum(val, [' минута', ' минуты', ' минут'])
|
||||
}
|
||||
return val
|
||||
}
|
||||
|
||||
return { search, searchTest, momenter, activeTabIcon, baseURL }
|
||||
}
|
||||
if (field === 'dateend') {
|
||||
return 'до ' + moment(val).format('DD.MM.YYYY, HH:mm');
|
||||
} else if (field === 'question_count') {
|
||||
return val + declOfNum(val, [' вопрос', ' вопроса', ' вопросов']);
|
||||
} else if (field === 'time') {
|
||||
return val + declOfNum(val, [' минута', ' минуты', ' минут']);
|
||||
}
|
||||
return val;
|
||||
};
|
||||
|
||||
return { search, searchTest, momenter, activeTabIcon, baseURL };
|
||||
},
|
||||
};
|
||||
</script>
|
||||
@@ -0,0 +1,191 @@
|
||||
<template>
|
||||
<v-container class="pa-4">
|
||||
<!-- Верхняя панель -->
|
||||
<HeaderDetailTesting
|
||||
:testStarted="testStarted"
|
||||
:formattedTime="formattedTime"
|
||||
:finishTest="openFinishDialog"
|
||||
:currentQuestion="currentQuestion"
|
||||
:totalQuestions="data?.question_count"
|
||||
@change-question="changeQuestion"
|
||||
:data="data"
|
||||
/>
|
||||
|
||||
<!-- Блок информации о тесте -->
|
||||
<BodyDetailTesting v-if="!testStarted && !testFinished" :data="data" :startTest="startTest" />
|
||||
|
||||
<!-- Вопросы теста -->
|
||||
<QuestionBlock
|
||||
v-if="testStarted"
|
||||
:question="data.questions[currentQuestion]"
|
||||
:currentQuestion="currentQuestion"
|
||||
:totalQuestions="data.question_count"
|
||||
:answers="answers"
|
||||
:finishTest="openFinishDialog"
|
||||
@change-question="changeQuestion"
|
||||
/>
|
||||
|
||||
<!-- Результаты теста -->
|
||||
<TestResults
|
||||
v-if="testFinished"
|
||||
:testFinished="testFinished"
|
||||
:testPassed="testPassed"
|
||||
:correctAnswers="correctAnswers"
|
||||
:answeredQuestions="answeredQuestions"
|
||||
:totalQuestions="data.question_count"
|
||||
:formattedTime="formattedTime"
|
||||
/>
|
||||
|
||||
<!-- Диалог подтверждения завершения теста -->
|
||||
<v-dialog v-model="showFinishDialog" persistent max-width="400px">
|
||||
<v-card>
|
||||
<v-card-title class="text-h6">Завершить тест?</v-card-title>
|
||||
<v-card-text>Вы уверены, что хотите завершить тестирование?</v-card-text>
|
||||
<v-card-actions class="d-flex justify-end">
|
||||
<v-btn color="teal-darken-4" @click="finishTest">Да, завершить</v-btn>
|
||||
<v-btn color="grey" @click="showFinishDialog = false">Отмена</v-btn>
|
||||
</v-card-actions>
|
||||
</v-card>
|
||||
</v-dialog>
|
||||
</v-container>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { computed, ref, onUnmounted, onMounted, watch } from 'vue';
|
||||
import HeaderDetailTesting from '@/components/testing/HeaderDetailTesting.vue';
|
||||
import BodyDetailTesting from '@/components/testing/BodyDetailTesting.vue';
|
||||
import QuestionBlock from '@/components/testing/QuestionBlock.vue';
|
||||
import TestResults from '@/components/testing/TestResults.vue';
|
||||
import { axiosApiInstance } from '@/utils/axios-api';
|
||||
import { useRoute } from 'vue-router';
|
||||
|
||||
export default {
|
||||
components: { BodyDetailTesting, HeaderDetailTesting, QuestionBlock, TestResults },
|
||||
setup() {
|
||||
const route = useRoute();
|
||||
const testId = route.params.id;
|
||||
const testStarted = ref(false);
|
||||
const testFinished = ref(false);
|
||||
const showFinishDialog = ref(false);
|
||||
const currentQuestion = ref(0);
|
||||
let timer = null;
|
||||
const data = ref(null);
|
||||
|
||||
const getTestById = async (id) => {
|
||||
const resp = await axiosApiInstance.get(`/api/tests/testdetail/${id}`);
|
||||
data.value = resp.data;
|
||||
// console.log(data.value);
|
||||
};
|
||||
|
||||
const formattedTime = computed(() => {
|
||||
if (!data.value?.time) return '00:00';
|
||||
|
||||
// Если тест не запущен и не завершён — считаем, что время в data.value.time в минутах
|
||||
if (!testStarted.value && !testFinished.value) {
|
||||
return `${String(data.value.time).padStart(2, '0')}:00`;
|
||||
}
|
||||
|
||||
// Если тест запущен или завершён — data.value.time уже в секундах
|
||||
const minutes = Math.floor(data.value.time / 60);
|
||||
const seconds = data.value.time % 60;
|
||||
return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
|
||||
});
|
||||
|
||||
const startTest = () => {
|
||||
testStarted.value = true;
|
||||
testFinished.value = false;
|
||||
|
||||
// Переводим минуты в секунды перед запуском таймера
|
||||
data.value = { ...data.value, time: data.value.time * 60 };
|
||||
|
||||
timer = setInterval(() => {
|
||||
if (data.value?.time > 0) {
|
||||
data.value = { ...data.value, time: data.value.time - 1 };
|
||||
} else {
|
||||
finishTest(); // Завершаем тест, если время закончилось
|
||||
}
|
||||
}, 1000);
|
||||
};
|
||||
|
||||
const finishTest = () => {
|
||||
clearInterval(timer);
|
||||
testStarted.value = false;
|
||||
testFinished.value = true;
|
||||
showFinishDialog.value = false;
|
||||
};
|
||||
|
||||
const answers = ref([]);
|
||||
|
||||
watch(data.value?.questions, (newData) => {
|
||||
if (newData && Array.isArray(newData.questions)) {
|
||||
answers.value = newData.questions.map(() => null);
|
||||
}
|
||||
});
|
||||
|
||||
const correctAnswers = computed(
|
||||
() =>
|
||||
answers.value.filter((answer, index) => {
|
||||
const correctAnswerObjs = data?.value.questions[index].answers.filter(
|
||||
(a) => a.right_wrong,
|
||||
);
|
||||
|
||||
if (!correctAnswerObjs.length) return false; // Если нет правильных ответов, пропускаем
|
||||
|
||||
const correctNames = correctAnswerObjs.map((a) => a.name); // Все правильные варианты
|
||||
|
||||
// Если пользователь выбрал несколько вариантов, сравниваем как массивы
|
||||
if (Array.isArray(answer)) {
|
||||
return (
|
||||
answer.length === correctNames.length && // Должно совпадать количество
|
||||
answer.every((ans) => correctNames.includes(ans)) // Все варианты должны быть правильными
|
||||
);
|
||||
}
|
||||
|
||||
// Если один вариант ответа — сравниваем просто строку
|
||||
return correctNames.includes(answer);
|
||||
}).length,
|
||||
);
|
||||
|
||||
const answeredQuestions = computed(
|
||||
() => answers.value.filter((answer) => answer !== null).length,
|
||||
);
|
||||
|
||||
const testPassed = computed(() => correctAnswers.value >= data?.value.questions.length / 2);
|
||||
|
||||
const changeQuestion = (newIndex) => {
|
||||
if (newIndex >= 0 && newIndex < data?.value.questions.length) {
|
||||
currentQuestion.value = newIndex;
|
||||
}
|
||||
};
|
||||
|
||||
const openFinishDialog = () => {
|
||||
showFinishDialog.value = true;
|
||||
};
|
||||
|
||||
onUnmounted(() => {
|
||||
if (timer) clearInterval(timer);
|
||||
});
|
||||
|
||||
onMounted(() => {
|
||||
getTestById(testId);
|
||||
});
|
||||
|
||||
return {
|
||||
testStarted,
|
||||
testFinished,
|
||||
formattedTime,
|
||||
startTest,
|
||||
finishTest,
|
||||
answers,
|
||||
currentQuestion,
|
||||
changeQuestion,
|
||||
showFinishDialog,
|
||||
openFinishDialog,
|
||||
correctAnswers,
|
||||
answeredQuestions,
|
||||
testPassed,
|
||||
data,
|
||||
};
|
||||
},
|
||||
};
|
||||
</script>
|
||||
@@ -0,0 +1,97 @@
|
||||
<template>
|
||||
<v-container class="pa-4">
|
||||
<v-row align="center" class="border-b-thin">
|
||||
<v-col class="text-h6 font-weight-regular">
|
||||
{{ data?.name }}
|
||||
</v-col>
|
||||
<span class="text-h6 text-grey-darken-1 font-weight-bold mr-4">{{ formattedTime }}</span>
|
||||
</v-row>
|
||||
|
||||
<v-row align="center" class="border-b-thin pa-2">
|
||||
<v-btn
|
||||
elevation="1"
|
||||
color="teal-darken-1"
|
||||
size="x-small"
|
||||
rounded
|
||||
icon="mdi-information-outline"
|
||||
/>
|
||||
|
||||
<!-- Пагинация только при запущенном тесте -->
|
||||
<v-pagination
|
||||
v-if="testStarted"
|
||||
:length="totalQuestions"
|
||||
:total-visible="5"
|
||||
active-color="teal-darken-4"
|
||||
:model-value="currentQuestion + 1"
|
||||
@update:model-value="changePage"
|
||||
></v-pagination>
|
||||
|
||||
<v-btn
|
||||
v-if="testStarted"
|
||||
elevation="0"
|
||||
color="red-darken-1"
|
||||
rounded="lg"
|
||||
class="ml-auto"
|
||||
@click="finishTest"
|
||||
>
|
||||
Завершить
|
||||
</v-btn>
|
||||
<v-btn
|
||||
v-else
|
||||
elevation="0"
|
||||
color="grey-lighten-3"
|
||||
rounded="lg"
|
||||
class="ml-auto"
|
||||
@click="showExitDialog = true"
|
||||
>
|
||||
Выйти
|
||||
</v-btn>
|
||||
</v-row>
|
||||
|
||||
<!-- Диалоговое окно выхода -->
|
||||
<v-dialog v-model="showExitDialog" width="400">
|
||||
<v-card>
|
||||
<v-card-title class="text-h6">Вы действительно хотите выйти?</v-card-title>
|
||||
<v-card-actions>
|
||||
<v-btn color="red" @click="exitTest">Да</v-btn>
|
||||
<v-btn color="grey" @click="showExitDialog = false">Отмена</v-btn>
|
||||
</v-card-actions>
|
||||
</v-card>
|
||||
</v-dialog>
|
||||
</v-container>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { ref } from 'vue';
|
||||
|
||||
export default {
|
||||
props: {
|
||||
testStarted: Boolean,
|
||||
formattedTime: String,
|
||||
finishTest: Function,
|
||||
currentQuestion: Number,
|
||||
totalQuestions: Number,
|
||||
data: {
|
||||
name: {
|
||||
type: String,
|
||||
default: 'Тест',
|
||||
},
|
||||
},
|
||||
},
|
||||
emits: ['change-question'],
|
||||
setup(props, { emit }) {
|
||||
const showExitDialog = ref(false);
|
||||
|
||||
const exitTest = () => {
|
||||
showExitDialog.value = false;
|
||||
window.history.back();
|
||||
};
|
||||
|
||||
const changePage = (newPage) => {
|
||||
emit('change-question', newPage - 1);
|
||||
};
|
||||
|
||||
return { showExitDialog, exitTest, changePage };
|
||||
},
|
||||
};
|
||||
</script>
|
||||
@@ -0,0 +1,119 @@
|
||||
<template>
|
||||
<v-card
|
||||
class="mt-4 w-75 mx-auto d-flex flex-lg-column"
|
||||
style="min-height: 450px; max-height: 700px"
|
||||
>
|
||||
<v-card-title class="text-h6 font-weight-bold">
|
||||
Вопрос {{ currentQuestion + 1 }} из {{ totalQuestions }}
|
||||
</v-card-title>
|
||||
<h3 class="mb-2 px-4">{{ question.name }}</h3>
|
||||
<v-card-text style="overflow-y: scroll">
|
||||
<v-img
|
||||
v-if="question.file"
|
||||
:src="`http://127.0.0.1:8000${question.file}`"
|
||||
class="w-50 mx-auto"
|
||||
/>
|
||||
|
||||
<!-- Одиночный выбор -->
|
||||
<v-radio-group v-if="!isMultipleChoice" v-model="answers[currentQuestion]">
|
||||
<v-radio v-for="(option, index) in question.answers" :key="index" :value="option.name">
|
||||
<template v-slot:label>
|
||||
<div class="text-center">
|
||||
<v-img
|
||||
v-if="option.file"
|
||||
:src="`http://127.0.0.1:8000${option.file}`"
|
||||
class="mb-4"
|
||||
max-height="140"
|
||||
contain
|
||||
/>
|
||||
<span>{{ option.name }}</span>
|
||||
</div>
|
||||
</template>
|
||||
</v-radio>
|
||||
</v-radio-group>
|
||||
|
||||
<!-- Множественный выбор -->
|
||||
<div v-else>
|
||||
<v-checkbox
|
||||
v-for="(option, index) in question.answers"
|
||||
:key="index"
|
||||
v-model="answers[currentQuestion]"
|
||||
:value="option.name"
|
||||
style="margin-bottom: -25px"
|
||||
>
|
||||
<template v-slot:label>
|
||||
<div class="text-center">
|
||||
<v-img
|
||||
v-if="option.file"
|
||||
:src="`http://127.0.0.1:8000${option.file}`"
|
||||
class="mb-4"
|
||||
max-height="140"
|
||||
contain
|
||||
/>
|
||||
<span>{{ option.name }}</span>
|
||||
</div>
|
||||
</template>
|
||||
</v-checkbox>
|
||||
</div>
|
||||
</v-card-text>
|
||||
<v-card-actions class="d-flex">
|
||||
<v-btn
|
||||
:disabled="currentQuestion === 0"
|
||||
@click="$emit('change-question', currentQuestion - 1)"
|
||||
>
|
||||
Назад
|
||||
</v-btn>
|
||||
<v-btn
|
||||
v-if="currentQuestion !== totalQuestions - 1"
|
||||
color="teal-darken-1"
|
||||
@click="$emit('change-question', currentQuestion + 1)"
|
||||
>
|
||||
Далее
|
||||
</v-btn>
|
||||
<v-btn
|
||||
v-if="currentQuestion === totalQuestions - 1"
|
||||
elevation="0"
|
||||
color="white"
|
||||
rounded="lg"
|
||||
class="bg-teal-darken-4"
|
||||
@click="finishTest"
|
||||
>
|
||||
Завершить
|
||||
</v-btn>
|
||||
</v-card-actions>
|
||||
</v-card>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { computed, watch } from 'vue';
|
||||
|
||||
export default {
|
||||
props: {
|
||||
question: Object,
|
||||
currentQuestion: Number,
|
||||
totalQuestions: Number,
|
||||
finishTest: Function,
|
||||
answers: Array,
|
||||
},
|
||||
setup(props) {
|
||||
// Определяем, является ли вопрос с множественным выбором
|
||||
const isMultipleChoice = computed(() => props.question.settings?.multiply === 'true');
|
||||
|
||||
// Следим за изменением текущего вопроса и создаем пустой массив, если множественный выбор
|
||||
watch(
|
||||
() => props.currentQuestion,
|
||||
(newVal) => {
|
||||
if (isMultipleChoice.value && !Array.isArray(props.answers[newVal])) {
|
||||
props.answers[newVal] = [];
|
||||
}
|
||||
},
|
||||
{ immediate: true }, // Устанавливаем сразу при инициализации
|
||||
);
|
||||
|
||||
return {
|
||||
isMultipleChoice,
|
||||
};
|
||||
},
|
||||
emits: ['change-question'],
|
||||
};
|
||||
</script>
|
||||
@@ -0,0 +1,45 @@
|
||||
<template>
|
||||
<v-card v-if="testFinished" class="mt-4 pa-4" flat>
|
||||
<v-card-title class="text-h6 font-weight-bold">Результаты тестирования</v-card-title>
|
||||
<v-card-text>
|
||||
<v-alert v-if="testPassed" type="success"> Тест успешно пройден </v-alert>
|
||||
<v-alert v-if="!testPassed" type="error"> Тест не пройден </v-alert>
|
||||
</v-card-text>
|
||||
|
||||
<v-row class="mt-2">
|
||||
<v-col cols="4">
|
||||
<v-card class="pa-2 text-center">
|
||||
<p class="text-h6">{{ correctAnswers }}/{{ totalQuestions }}</p>
|
||||
<small>Правильных ответов</small>
|
||||
</v-card>
|
||||
</v-col>
|
||||
|
||||
<v-col cols="4">
|
||||
<v-card class="pa-2 text-center">
|
||||
<p class="text-h6">{{ answeredQuestions }}/{{ totalQuestions }}</p>
|
||||
<small>Ответов дано</small>
|
||||
</v-card>
|
||||
</v-col>
|
||||
|
||||
<v-col cols="4">
|
||||
<v-card class="pa-2 text-center">
|
||||
<p class="text-h6">{{ formattedTime }}</p>
|
||||
<small>Оставшееся время</small>
|
||||
</v-card>
|
||||
</v-col>
|
||||
</v-row>
|
||||
</v-card>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
props: {
|
||||
testFinished: Boolean,
|
||||
testPassed: Boolean,
|
||||
correctAnswers: Number,
|
||||
answeredQuestions: Number,
|
||||
totalQuestions: Number,
|
||||
formattedTime: String,
|
||||
},
|
||||
};
|
||||
</script>
|
||||
@@ -1,35 +0,0 @@
|
||||
<template>
|
||||
<v-card-title>{{ item.title }}</v-card-title>
|
||||
<v-card-subtitle>
|
||||
<div>{{ item.description }}</div>
|
||||
</v-card-subtitle>
|
||||
<v-card-actions class="ga-4">
|
||||
<div>
|
||||
<v-icon color="teal-darken-4">mdi-calendar</v-icon>
|
||||
<strong> До:</strong> {{ new Date(item.date).toLocaleDateString() }}
|
||||
</div>
|
||||
<div>
|
||||
<v-icon color="teal-darken-4">mdi-calendar-text</v-icon>
|
||||
<strong> Вопросов:</strong> {{ item.questions }}
|
||||
</div>
|
||||
<div v-if="item.time">
|
||||
<v-icon color="teal-darken-4">mdi-clock</v-icon>
|
||||
<strong> Время:</strong> {{ item.time }}
|
||||
</div>
|
||||
<div v-if="item.attempts">
|
||||
<v-icon color="deep-orange-accent-4">mdi-alert-outline</v-icon>
|
||||
<strong> Попытки:</strong> {{ item.attempts }}
|
||||
</div>
|
||||
</v-card-actions>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
props: {
|
||||
item: {
|
||||
type: Object,
|
||||
required: true
|
||||
}
|
||||
}
|
||||
};
|
||||
</script>
|
||||
@@ -0,0 +1,98 @@
|
||||
<template>
|
||||
<div v-if="question.settings.choice === 'free'">
|
||||
<transition-group name="list" tag="div">
|
||||
<div
|
||||
v-for="(answer, aIndex) in question.answers"
|
||||
:key="aIndex"
|
||||
class="d-flex align-start mb-4"
|
||||
>
|
||||
<!-- Показываем иконку для переключения статуса только если роут содержит "test" -->
|
||||
<v-btn
|
||||
v-if="isTestRoute"
|
||||
class="ml-2"
|
||||
icon
|
||||
size="small"
|
||||
@click="toggleCorrect(answer)"
|
||||
>
|
||||
<v-icon color="green" v-if="answer.correct" large>mdi-check</v-icon>
|
||||
<v-icon color="red" v-else large>mdi-close</v-icon>
|
||||
</v-btn>
|
||||
|
||||
<v-text-field
|
||||
v-model="answer.text"
|
||||
:label="'Ответ ' + (aIndex + 1)"
|
||||
:rules="[rules.required]"
|
||||
class="mr-4"
|
||||
density="compact"
|
||||
variant="outlined"
|
||||
></v-text-field>
|
||||
|
||||
<v-file-input
|
||||
v-model="answer.image"
|
||||
accept="image/*"
|
||||
dense
|
||||
density="compact"
|
||||
hide-details
|
||||
label="Картинка"
|
||||
variant="outlined"
|
||||
></v-file-input>
|
||||
|
||||
<v-btn
|
||||
class="ms-1"
|
||||
color="error"
|
||||
icon="mdi-delete"
|
||||
size="small"
|
||||
@click="removeAnswer(aIndex)"
|
||||
></v-btn>
|
||||
</div>
|
||||
</transition-group>
|
||||
<div class="d-flex justify-start">
|
||||
<v-btn color="teal-darken-4" size="small" @click="addAnswer">
|
||||
Добавить ответ
|
||||
</v-btn>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { computed } from 'vue';
|
||||
import { useRoute } from 'vue-router';
|
||||
|
||||
export default {
|
||||
name: 'AnswerList',
|
||||
props: {
|
||||
question: {
|
||||
type: Object,
|
||||
required: true,
|
||||
},
|
||||
rules: {
|
||||
type: Object,
|
||||
required: true,
|
||||
},
|
||||
addAnswer: {
|
||||
type: Function,
|
||||
required: true,
|
||||
},
|
||||
removeAnswer: {
|
||||
type: Function,
|
||||
required: true,
|
||||
}
|
||||
},
|
||||
setup() {
|
||||
const route = useRoute();
|
||||
|
||||
const isTestRoute = computed(() => {
|
||||
return route.path && String(route.path).includes('test');
|
||||
});
|
||||
|
||||
const toggleCorrect = (answer) => {
|
||||
answer.correct = !answer.correct;
|
||||
};
|
||||
|
||||
return {
|
||||
isTestRoute,
|
||||
toggleCorrect,
|
||||
};
|
||||
}
|
||||
};
|
||||
</script>
|
||||
@@ -0,0 +1,13 @@
|
||||
<template>
|
||||
<v-card class="d-flex flex-column flex-grow-1 flex-shrink-0 text-center pa-8" flat>
|
||||
<v-spacer></v-spacer>
|
||||
<div class>
|
||||
<v-icon color="success" size="48">mdi-check-circle</v-icon>
|
||||
<h2 class="mt-4">Голосование создано!</h2>
|
||||
<slot></slot>
|
||||
</div>
|
||||
<v-spacer></v-spacer>
|
||||
</v-card>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
</script>
|
||||
@@ -0,0 +1,197 @@
|
||||
<template>
|
||||
<v-card class="fill-height d-flex flex-column" flat>
|
||||
<v-card-title>Основная информация</v-card-title>
|
||||
<v-card-text class="d-flex flex-column overflow-auto">
|
||||
<v-text-field
|
||||
v-model="localForm.title"
|
||||
:rules="[rules.required]"
|
||||
class="flex-grow-0 flex-shrink-1"
|
||||
label="Название"
|
||||
variant="underlined"
|
||||
></v-text-field>
|
||||
<div class="flex-grow-1 flex-shrink-0">
|
||||
<v-textarea
|
||||
v-model="localForm.description"
|
||||
:rules="[rules.required]"
|
||||
label="Описание"
|
||||
variant="outlined"
|
||||
></v-textarea>
|
||||
</div>
|
||||
<v-divider></v-divider>
|
||||
<div class="flex-grow-0 flex-shrink-1">
|
||||
<div class="pt-2 d-flex align-center">
|
||||
<span class="text-overline text-grey text-center">Публикация новости: </span>
|
||||
<v-switch
|
||||
v-model="localForm.createnews"
|
||||
class="px-2"
|
||||
density="comfortable"
|
||||
hide-details
|
||||
color="primary"
|
||||
:label="localForm.createnews ? 'да' : 'нет'"
|
||||
></v-switch>
|
||||
</div>
|
||||
<div class="pt-2 d-flex align-center" v-if="isTestRoute">
|
||||
<span class="text-overline text-grey text-center">Назначить: </span>
|
||||
<v-switch
|
||||
v-model="localForm.appoint"
|
||||
class="px-2"
|
||||
density="comfortable"
|
||||
hide-details
|
||||
color="primary"
|
||||
:label="localForm.appoint ? 'да' : 'нет'"
|
||||
></v-switch>
|
||||
<SearcEmployess v-if="localForm.appoint" />
|
||||
</div>
|
||||
<div class="pt-2 text-overline text-grey">Дата и время:</div>
|
||||
<div class="d-flex justify-space-around">
|
||||
<div class="d-flex ga-3 align-center">
|
||||
<h6 class="text-subtitle-1 pt-2">начало:</h6>
|
||||
<date-select :datedefault="form.startDate" @returndate="returnstart" />
|
||||
<v-select
|
||||
v-model="selectedTimeStart"
|
||||
:items="timeOptions"
|
||||
density="compact"
|
||||
hide-details
|
||||
variant="plain"
|
||||
>
|
||||
<template v-slot:prepend-inner>
|
||||
<v-icon color="red" icon="mdi-timer" size="xsmall"></v-icon>
|
||||
</template>
|
||||
</v-select>
|
||||
</div>
|
||||
<div class="d-flex ga-3 align-center">
|
||||
<h6 class="text-subtitle-1 pt-2">окончание:</h6>
|
||||
<date-select :datedefault="form.endDate" @returndate="returnend" />
|
||||
<v-select
|
||||
v-model="selectedTimeEnd"
|
||||
:items="timeOptions"
|
||||
density="compact"
|
||||
hide-details
|
||||
outlined
|
||||
variant="plain"
|
||||
>
|
||||
<template v-slot:prepend-inner>
|
||||
<v-icon color="red" icon="mdi-timer" size="xsmall"></v-icon>
|
||||
</template>
|
||||
</v-select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</v-card-text>
|
||||
<slot></slot>
|
||||
</v-card>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import DateSelect from '@/components/UI/date-select.vue';
|
||||
import { ref, watch, computed } from 'vue';
|
||||
import { checkremote } from '@/utils/universal_functions.js';
|
||||
import { spravURL } from '@/utils/axios-api.js';
|
||||
import { useRoute } from 'vue-router';
|
||||
import SearcEmployess from '@/components/UI/SearcEmployess.vue';
|
||||
|
||||
export default {
|
||||
methods: {
|
||||
spravURL() {
|
||||
return spravURL
|
||||
}, checkremote },
|
||||
components: { SearcEmployess, DateSelect },
|
||||
props: {
|
||||
form: Object,
|
||||
rules: {
|
||||
type: Object,
|
||||
default: () => ({
|
||||
required: (value) => !!value || 'Это поле обязательно для заполнения',
|
||||
}),
|
||||
},
|
||||
},
|
||||
emits: ['update:form'],
|
||||
setup(props, { emit }) {
|
||||
const route = useRoute();
|
||||
const isTestRoute = computed(() => {
|
||||
return route.path && String(route.path).includes('test');
|
||||
});
|
||||
// Если form не передан, создаём объект с дефолтными значениями
|
||||
const localForm = ref(
|
||||
props.form
|
||||
? { ...props.form }
|
||||
: {
|
||||
title: '',
|
||||
description: '',
|
||||
createnews: false,
|
||||
appoint: false,
|
||||
startDate: new Date(),
|
||||
endDate: new Date(),
|
||||
}
|
||||
);
|
||||
|
||||
// Отправляем изменения в родителя
|
||||
watch(
|
||||
localForm,
|
||||
(newForm) => {
|
||||
emit('update:form', newForm);
|
||||
},
|
||||
{ deep: true }
|
||||
);
|
||||
|
||||
const returnstart = (date) => {
|
||||
localForm.value.startDate =
|
||||
date instanceof Date ? date : new Date(date);
|
||||
};
|
||||
|
||||
const returnend = (date) => {
|
||||
localForm.value.endDate =
|
||||
date instanceof Date ? date : new Date(date);
|
||||
};
|
||||
|
||||
const formatTime = (date) =>
|
||||
date instanceof Date ? date.toTimeString().slice(0, 5) : '00:00';
|
||||
|
||||
const selectedTimeStart = computed({
|
||||
get: () => formatTime(localForm.value.startDate),
|
||||
set: (newTime) => {
|
||||
const [hours, minutes] = newTime.split(':').map(Number);
|
||||
const oldDate =
|
||||
localForm.value.startDate instanceof Date
|
||||
? localForm.value.startDate
|
||||
: new Date();
|
||||
const newDate = new Date(oldDate); // создаём новый объект с копией даты
|
||||
newDate.setHours(hours, minutes, 0, 0);
|
||||
localForm.value.startDate = newDate;
|
||||
},
|
||||
});
|
||||
|
||||
const selectedTimeEnd = computed({
|
||||
get: () => formatTime(localForm.value.endDate),
|
||||
set: (newTime) => {
|
||||
const [hours, minutes] = newTime.split(':').map(Number);
|
||||
const oldDate =
|
||||
localForm.value.endDate instanceof Date ? localForm.value.endDate : new Date();
|
||||
const newDate = new Date(oldDate);
|
||||
newDate.setHours(hours, minutes, 0, 0);
|
||||
localForm.value.endDate = newDate;
|
||||
},
|
||||
});
|
||||
|
||||
const timeOptions = Array.from({ length: 48 }, (_, i) => {
|
||||
const hours = String(Math.floor(i / 2)).padStart(2, '0');
|
||||
const minutes = i % 2 === 0 ? '00' : '30';
|
||||
return `${hours}:${minutes}`;
|
||||
});
|
||||
|
||||
return {
|
||||
localForm,
|
||||
returnstart,
|
||||
returnend,
|
||||
selectedTimeStart,
|
||||
selectedTimeEnd,
|
||||
timeOptions,
|
||||
isTestRoute
|
||||
};
|
||||
},
|
||||
};
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
|
||||
</style>
|
||||
@@ -0,0 +1,127 @@
|
||||
<template>
|
||||
<transition-group name="list" tag="div">
|
||||
<QuestionItem
|
||||
v-for="(question, index) in form.questions"
|
||||
:key="index"
|
||||
:allEmployees="allEmployees"
|
||||
:allEmployeesgroupedbydep="allEmployeesgroupedbydep"
|
||||
:checkremote="checkremote"
|
||||
:findEmployeeById="findEmployeeById"
|
||||
:handleSelectAll="handleSelectAll"
|
||||
:index="index"
|
||||
:onEmployeesChange="onEmployeesChange"
|
||||
:onlyDepdict="onlyDepdict"
|
||||
:question="question"
|
||||
:questionTypes="questionTypes"
|
||||
:removeQuestion="removeQuestion"
|
||||
:rules="rules"
|
||||
:spravURL="spravURL"
|
||||
@update:question="form.questions[index] = $event"
|
||||
/>
|
||||
</transition-group>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { computed } from 'vue';
|
||||
import { checkremote } from '@/utils/universal_functions';
|
||||
import { spravURL } from '@/utils/axios-api';
|
||||
import QuestionItem from '@/components/vote/ConstructorVote/QuestionItem.vue';
|
||||
|
||||
export default {
|
||||
components: { QuestionItem },
|
||||
props: {
|
||||
form: {
|
||||
type: Object,
|
||||
required: true,
|
||||
},
|
||||
rules: {
|
||||
type: Object,
|
||||
default: () => ({
|
||||
required: (value) => !!value || 'Это поле обязательно для заполнения',
|
||||
}),
|
||||
},
|
||||
quests: {
|
||||
type: Array,
|
||||
default: () => [],
|
||||
},
|
||||
allEmployees: {
|
||||
type: Array,
|
||||
required: true,
|
||||
},
|
||||
allEmployeesgroupedbydep: {
|
||||
type: Array,
|
||||
required: true,
|
||||
},
|
||||
handleSelectAll: {
|
||||
type: Function,
|
||||
required: true,
|
||||
},
|
||||
onEmployeesChange: {
|
||||
type: Function,
|
||||
required: true,
|
||||
},
|
||||
findEmployeeById: {
|
||||
type: Function,
|
||||
required: true,
|
||||
},
|
||||
onlyDepdict: {
|
||||
type: Array,
|
||||
},
|
||||
},
|
||||
emits: ['update:form'],
|
||||
setup(props, { emit }) {
|
||||
const localForm = computed({
|
||||
get() {
|
||||
return props.form;
|
||||
},
|
||||
set(newForm) {
|
||||
emit('update:form', newForm);
|
||||
},
|
||||
});
|
||||
|
||||
const questionTypes = [
|
||||
{ name: 'Ввести вручную', choice: 'free' },
|
||||
{ name: 'Выбрать сотрудника', choice: 'employee' },
|
||||
];
|
||||
|
||||
const updateQuest = (index) => {
|
||||
const updatedQuests = [...props.quests];
|
||||
updatedQuests[index] = localForm.value.questions[index].text.trim().length > 0;
|
||||
emit('update:quests', updatedQuests);
|
||||
};
|
||||
|
||||
const removeQuestion = (index) => {
|
||||
localForm.value.questions.splice(index, 1);
|
||||
};
|
||||
|
||||
const addAnswer = (index) => {
|
||||
const updatedQuestions = [...localForm.value.questions];
|
||||
updatedQuestions[index] = {
|
||||
...updatedQuestions[index],
|
||||
answers: [...updatedQuestions[index].answers, { text: '', image: null }],
|
||||
};
|
||||
localForm.value = { ...localForm.value, questions: updatedQuestions };
|
||||
};
|
||||
|
||||
const removeAnswer = (qIndex, aIndex) => {
|
||||
const updatedQuestions = [...localForm.value.questions];
|
||||
updatedQuestions[qIndex] = {
|
||||
...updatedQuestions[qIndex],
|
||||
answers: updatedQuestions[qIndex].answers.filter((_, i) => i !== aIndex),
|
||||
};
|
||||
localForm.value = { ...localForm.value, questions: updatedQuestions };
|
||||
};
|
||||
|
||||
return {
|
||||
localForm,
|
||||
questionTypes,
|
||||
updateQuest,
|
||||
removeQuestion,
|
||||
addAnswer,
|
||||
removeAnswer,
|
||||
checkremote,
|
||||
spravURL,
|
||||
};
|
||||
},
|
||||
};
|
||||
</script>
|
||||
@@ -0,0 +1,59 @@
|
||||
<template>
|
||||
<div class="d-flex">
|
||||
<v-text-field
|
||||
v-model="localQuestion.text"
|
||||
:label="'Вопрос ' + (index + 1)"
|
||||
:rules="[rules.required]"
|
||||
density="comfortable"
|
||||
variant="underlined"
|
||||
>
|
||||
<template v-slot:append>
|
||||
<v-btn
|
||||
color="error"
|
||||
icon="mdi-delete"
|
||||
size="small"
|
||||
@click="removeQuestion(index)"
|
||||
/>
|
||||
</template>
|
||||
</v-text-field>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { computed } from 'vue';
|
||||
|
||||
export default {
|
||||
props: {
|
||||
question: {
|
||||
type: Object,
|
||||
required: true,
|
||||
},
|
||||
rules: {
|
||||
type: Object,
|
||||
required: true,
|
||||
},
|
||||
index: {
|
||||
type: Number,
|
||||
required: true,
|
||||
},
|
||||
removeQuestion: {
|
||||
type: Function,
|
||||
required: true,
|
||||
},
|
||||
},
|
||||
setup(props, { emit }) {
|
||||
const localQuestion = computed({
|
||||
get() {
|
||||
return props.question;
|
||||
},
|
||||
set(newValue) {
|
||||
emit('update:question', newValue);
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
localQuestion,
|
||||
};
|
||||
},
|
||||
};
|
||||
</script>
|
||||
@@ -0,0 +1,266 @@
|
||||
<template>
|
||||
<div class="question-item mb-4">
|
||||
<!-- Заголовок вопроса: текстовое поле с кнопкой удаления -->
|
||||
<QuestionHeader :question="question" :rules="rules" :index="index" :removeQuestion="removeQuestion" />
|
||||
|
||||
<!-- Загрузка изображения для вопроса -->
|
||||
<v-file-input
|
||||
v-model="question.image"
|
||||
accept="image/*"
|
||||
density="comfortable"
|
||||
label="Картинка для вопроса"
|
||||
variant="outlined"
|
||||
></v-file-input>
|
||||
|
||||
<v-divider></v-divider>
|
||||
|
||||
<!-- Настройки вопроса -->
|
||||
<QuestionSettings :question="question" :rules="rules" :question-types="questionTypes" :resetAnswers="resetAnswers" v-if="!isTestRoute" />
|
||||
|
||||
<!-- Ответы или выбор сотрудников в зависимости от типа ответа -->
|
||||
<v-card-text class="px-0">
|
||||
<!-- Для типа "free" – ручной ввод ответов -->
|
||||
<AnswerList v-if="question.settings.choice === 'free'" :rules="rules" :question="question" :remove-answer="removeAnswer" :add-answer="addAnswer" />
|
||||
|
||||
<!-- Для типа "employee" – выбор сотрудников -->
|
||||
<div v-else>
|
||||
<div class="v-row">
|
||||
<v-radio-group
|
||||
v-model="question.settings.onlyDep"
|
||||
class="text-caption"
|
||||
inline
|
||||
>
|
||||
<template v-slot:label>
|
||||
<div class="text-body-2 font-weight-bold">
|
||||
Голосование по отделам:
|
||||
</div>
|
||||
</template>
|
||||
<v-radio
|
||||
v-for="x in onlyDepdict"
|
||||
:key="x.name"
|
||||
:value="x.value"
|
||||
>
|
||||
<template v-slot:label>
|
||||
<div class="text-caption">{{ x.name }}</div>
|
||||
</template>
|
||||
</v-radio>
|
||||
</v-radio-group>
|
||||
</div>
|
||||
<v-autocomplete
|
||||
v-model="question.selectedEmployees"
|
||||
:items="allEmployeesgroupedbydep"
|
||||
class="text-no-wrap"
|
||||
density="compact"
|
||||
item-title="fio"
|
||||
item-value="id"
|
||||
label="Выберите сотрудников"
|
||||
multiple
|
||||
variant="outlined"
|
||||
@update:model-value="onEmployeeUpdate"
|
||||
>
|
||||
<template #prepend-item>
|
||||
<v-checkbox
|
||||
:model-value="(question.selectedEmployees?.length || 0) === allEmployees.length"
|
||||
class="pa-0"
|
||||
label="Все"
|
||||
@update:model-value="toggleSelectAll"
|
||||
></v-checkbox>
|
||||
</template>
|
||||
<template #selection="{ item }">
|
||||
<v-chip
|
||||
:prepend-avatar="checkremote(`${spravURL}${item.raw.login}.jpg`)"
|
||||
>
|
||||
{{ item.raw.familyname }}
|
||||
</v-chip>
|
||||
</template>
|
||||
<template #item="data">
|
||||
<template v-if="typeof data.item.raw !== 'object'">
|
||||
<v-divider />
|
||||
<v-list-group
|
||||
class="pa-4 text-overline text-grey"
|
||||
v-text="data.item.raw"
|
||||
></v-list-group>
|
||||
</template>
|
||||
<template v-else>
|
||||
<v-list-item
|
||||
:append-avatar="checkremote(`${spravURL}${data.item.raw.login}.jpg`)"
|
||||
density="compact"
|
||||
slim
|
||||
@click="onEmployeesChange(data.item.raw.id)"
|
||||
>
|
||||
<template #prepend>
|
||||
<v-checkbox
|
||||
:model-value="question.selectedEmployees.includes(data.item.raw.id)"
|
||||
density="compact"
|
||||
hide-details
|
||||
></v-checkbox>
|
||||
</template>
|
||||
<v-list-item-title
|
||||
class="text-third"
|
||||
v-text="data.item.raw.fio"
|
||||
></v-list-item-title>
|
||||
</v-list-item>
|
||||
</template>
|
||||
</template>
|
||||
</v-autocomplete>
|
||||
<transition-group name="list" tag="div">
|
||||
<div
|
||||
v-for="(person, pIndex) in question.answers"
|
||||
:key="person"
|
||||
class="v-row align-center mb-4"
|
||||
>
|
||||
<v-col class="py-0" cols="7">
|
||||
<v-chip
|
||||
:prepend-avatar="checkremote(`${spravURL}${findEmployeeById(person.text)?.login}.jpg`)"
|
||||
>
|
||||
{{ findEmployeeById(person.text)?.fio }}
|
||||
</v-chip>
|
||||
</v-col>
|
||||
<v-col class="py-0 d-flex" cols="5">
|
||||
<v-file-input
|
||||
v-model="person.image"
|
||||
accept="image/*"
|
||||
dense
|
||||
density="compact"
|
||||
hide-details
|
||||
label="Картинка"
|
||||
variant="outlined"
|
||||
></v-file-input>
|
||||
<v-btn
|
||||
class="ms-1"
|
||||
color="error"
|
||||
icon="mdi-delete"
|
||||
size="small"
|
||||
@click="removeEmployeeAnswer(pIndex)"
|
||||
></v-btn>
|
||||
</v-col>
|
||||
</div>
|
||||
</transition-group>
|
||||
</div>
|
||||
</v-card-text>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import QuestionHeader from '@/components/vote/ConstructorVote/QuestionHeader.vue';
|
||||
import QuestionSettings from '@/components/vote/ConstructorVote/QuestionSettings.vue';
|
||||
import AnswerList from '@/components/vote/ConstructorVote/AnswerList.vue';
|
||||
import { computed } from 'vue';
|
||||
import { useRoute } from 'vue-router';
|
||||
|
||||
export default {
|
||||
name: 'QuestionItem',
|
||||
components: { AnswerList, QuestionSettings, QuestionHeader },
|
||||
props: {
|
||||
question: {
|
||||
type: Object,
|
||||
required: true,
|
||||
},
|
||||
index: {
|
||||
type: Number,
|
||||
required: true,
|
||||
},
|
||||
rules: {
|
||||
type: Object,
|
||||
required: true,
|
||||
},
|
||||
questionTypes: {
|
||||
type: Array,
|
||||
required: true,
|
||||
},
|
||||
onlyDepdict: {
|
||||
type: Array,
|
||||
default: () => [],
|
||||
},
|
||||
allEmployees: {
|
||||
type: Array,
|
||||
required: true,
|
||||
},
|
||||
allEmployeesgroupedbydep: {
|
||||
type: Array,
|
||||
required: true,
|
||||
},
|
||||
handleSelectAll: {
|
||||
type: Function,
|
||||
required: true,
|
||||
},
|
||||
onEmployeesChange: {
|
||||
type: Function,
|
||||
required: true,
|
||||
},
|
||||
findEmployeeById: {
|
||||
type: Function,
|
||||
required: true,
|
||||
},
|
||||
checkremote: {
|
||||
type: Function,
|
||||
required: true,
|
||||
},
|
||||
spravURL: {
|
||||
type: String,
|
||||
required: true,
|
||||
},
|
||||
removeQuestion: {
|
||||
type: Function,
|
||||
required: true,
|
||||
}
|
||||
},
|
||||
emits: ['update:question'],
|
||||
setup(props, { emit }) {
|
||||
const route = useRoute();
|
||||
|
||||
const resetAnswers = () => {
|
||||
props.question.answers = [];
|
||||
emit('update:question', props.question);
|
||||
};
|
||||
|
||||
const addAnswer = () => {
|
||||
props.question.answers.push({ text: '', image: null });
|
||||
emit('update:question', props.question);
|
||||
};
|
||||
|
||||
const removeAnswer = (aIndex) => {
|
||||
props.question.answers.splice(aIndex, 1);
|
||||
emit('update:question', props.question);
|
||||
};
|
||||
|
||||
const onEmployeeUpdate = (selected) => {
|
||||
props.question.answers = props.question.answers.filter((e) =>
|
||||
selected.includes(e.text)
|
||||
);
|
||||
emit('update:question', props.question);
|
||||
};
|
||||
|
||||
const toggleSelectAll = (value) => {
|
||||
props.handleSelectAll(value, props.index);
|
||||
emit('update:question', props.question);
|
||||
};
|
||||
|
||||
const removeEmployeeAnswer = (pIndex) => {
|
||||
props.question.selectedEmployees.splice(pIndex, 1);
|
||||
props.question.answers.splice(pIndex, 1);
|
||||
emit('update:question', props.question);
|
||||
};
|
||||
|
||||
const onEmployeesChange = (employeeId) => {
|
||||
props.onEmployeesChange(employeeId, props.index);
|
||||
emit('update:question', props.question);
|
||||
};
|
||||
|
||||
const isTestRoute = computed(() => {
|
||||
return route.path && String(route.path).includes('test');
|
||||
});
|
||||
|
||||
return {
|
||||
resetAnswers,
|
||||
addAnswer,
|
||||
removeAnswer,
|
||||
onEmployeeUpdate,
|
||||
toggleSelectAll,
|
||||
removeEmployeeAnswer,
|
||||
onEmployeesChange,
|
||||
isTestRoute
|
||||
};
|
||||
},
|
||||
};
|
||||
</script>
|
||||
@@ -0,0 +1,63 @@
|
||||
<template>
|
||||
<div class="py-2 text-overline text-grey">Настройки вопроса</div>
|
||||
<div class="v-row">
|
||||
<v-col class="align-self-center font-weight-bold py-0" cols="auto">
|
||||
Тип ответа
|
||||
</v-col>
|
||||
<v-col class="py-0 align-self-center" cols="3">
|
||||
<v-select
|
||||
v-model="question.settings.choice"
|
||||
:items="questionTypes"
|
||||
:list-props="{ density: 'compact' }"
|
||||
density="compact"
|
||||
hide-details
|
||||
item-title="name"
|
||||
item-value="choice"
|
||||
label=""
|
||||
variant="outlined"
|
||||
@update:model-value="resetAnswers"
|
||||
></v-select>
|
||||
</v-col>
|
||||
<v-spacer />
|
||||
<v-col class="align-self-center font-weight-bold" cols="auto" >
|
||||
Число возможных ответов
|
||||
</v-col>
|
||||
<v-col cols="1" >
|
||||
<v-text-field
|
||||
v-model="question.settings.multiChoice"
|
||||
:rules="[rules.required && question.settings.multiChoice > 0]"
|
||||
density="compact"
|
||||
hide-details
|
||||
min="1"
|
||||
type="number"
|
||||
variant="outlined"
|
||||
></v-text-field>
|
||||
</v-col>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
props: {
|
||||
question: {
|
||||
type: Object,
|
||||
required: true,
|
||||
},
|
||||
rules: {
|
||||
type: Object,
|
||||
required: true,
|
||||
},
|
||||
questionTypes: {
|
||||
type: Array,
|
||||
required: true,
|
||||
},
|
||||
resetAnswers:{
|
||||
type: Function,
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
|
||||
</style>
|
||||
@@ -1,25 +1,13 @@
|
||||
<template>
|
||||
|
||||
<v-row class="pt-2 mx-1 flex-column fill-height flex-grow-0">
|
||||
<template v-if="isVoteCreated">
|
||||
<v-card class="d-flex flex-column flex-grow-1 flex-shrink-0 text-center pa-8" flat>
|
||||
<v-spacer></v-spacer>
|
||||
<div class>
|
||||
<v-icon color="success" size="48">mdi-check-circle</v-icon>
|
||||
<h2 class="mt-4">Голосование создано!</h2>
|
||||
<CreatedVote v-if="isVoteCreated">
|
||||
<v-btn class="mt-4" color="teal-darken-4" @click="resetForm">Создать ещё</v-btn>
|
||||
|
||||
</div>
|
||||
<v-spacer></v-spacer>
|
||||
</v-card>
|
||||
</template>
|
||||
</CreatedVote>
|
||||
<template v-else>
|
||||
<div class="v-col flex-grow-1 flex-shrink-0">
|
||||
<v-stepper v-model="step" class="d-flex flex-column fill-height" editable>
|
||||
<v-stepper-header class="flex-grow-0 flex-shrink-1">
|
||||
<v-stepper-item :complete="step > 0" step="1">Основная информация
|
||||
|
||||
</v-stepper-item>
|
||||
<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>
|
||||
@@ -29,235 +17,36 @@
|
||||
<v-stepper-window class="fill-height">
|
||||
<!-- Основная информация -->
|
||||
<v-stepper-window-item class="fill-height" step="1">
|
||||
<v-card class="fill-height d-flex flex-column " flat>
|
||||
<v-card-title>Основная информация</v-card-title>
|
||||
<v-card-text class="d-flex flex-column overflow-auto">
|
||||
<v-text-field v-model="form.title" :rules="[rules.required]" class="flex-grow-0 flex-shrink-1"
|
||||
label="Название голосования"
|
||||
variant="underlined"></v-text-field>
|
||||
<div class="flex-grow-1 flex-shrink-0">
|
||||
|
||||
<v-textarea v-model="form.description" :rules="[rules.required]" label="Описание"
|
||||
|
||||
variant="outlined"></v-textarea>
|
||||
</div>
|
||||
<v-divider></v-divider>
|
||||
<div class="flex-grow-0 flex-shrink-1">
|
||||
<div class="pt-2 text-overline text-grey">Дата и время:</div>
|
||||
<div class="d-flex justify-space-around">
|
||||
<div class="d-flex ga-3 align-center">
|
||||
<h6 class="text-subtitle-1 pt-2">начало:</h6>
|
||||
<date-select :datedefault="form.startDate" @returndate="returnstart"/>
|
||||
<v-select v-model="selectedTimeStart" :items="timeOptions" density="compact" hide-details
|
||||
variant="plain">
|
||||
<template v-slot:prepend-inner>
|
||||
<v-icon color="red" icon="mdi-timer" size="xsmall"></v-icon>
|
||||
</template>
|
||||
</v-select>
|
||||
</div>
|
||||
<div class="d-flex ga-3 align-center">
|
||||
<h6 class="text-subtitle-1 pt-2">окончание:</h6>
|
||||
<date-select :datedefault="form.endDate" @returndate="returnend"/>
|
||||
<v-select v-model="selectedTimeEnd" :items="timeOptions" density="compact" hide-details
|
||||
outlined
|
||||
variant="plain">
|
||||
<template v-slot:prepend-inner>
|
||||
<v-icon color="red" icon="mdi-timer" size="xsmall"></v-icon>
|
||||
</template>
|
||||
</v-select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</v-card-text>
|
||||
|
||||
<MainInfo v-model:form="form" :rules="rules">
|
||||
<v-card-actions>
|
||||
<v-btn color="teal-darken-4" size="medium" @click="step = 1">Далее</v-btn>
|
||||
</v-card-actions>
|
||||
</v-card>
|
||||
</MainInfo>
|
||||
</v-stepper-window-item>
|
||||
|
||||
<!-- Создание опроса -->
|
||||
<v-stepper-window-item class="fill-height" step="2">
|
||||
|
||||
<v-card class="fill-height d-flex flex-column" flat>
|
||||
<v-card-title>Создание опроса:</v-card-title>
|
||||
<v-card-text style="max-height: 62vh; overflow-y: auto;">
|
||||
<transition-group name="list" tag="div">
|
||||
<div v-for="(question, index) in form.questions" :key="index" class="mb-4">
|
||||
<div class="d-flex">
|
||||
<!-- <v-text-field v-model="question.text" :label="'Вопрос ' + (index + 1)" :rules="[rules.required]"-->
|
||||
<!-- density="comfortable" variant="underlined">-->
|
||||
<v-text-field
|
||||
v-model="question.text"
|
||||
:label="'Вопрос ' + (index + 1)"
|
||||
density="comfortable"
|
||||
variant="underlined"
|
||||
:rules="[rules.required]"
|
||||
@input="updateQuest(index)"
|
||||
>
|
||||
<template v-slot:append>
|
||||
<v-btn color="error" icon="mdi-delete" size="small" @click="removeQuestion(index)"/>
|
||||
</template>
|
||||
|
||||
</v-text-field>
|
||||
</div>
|
||||
<v-file-input v-model="question.image" accept="image/*" density="comfortable"
|
||||
label="Картинка для вопроса" variant="outlined"></v-file-input>
|
||||
<v-divider></v-divider>
|
||||
<div class="py-2 text-overline text-grey">Настройки вопроса</div>
|
||||
<div class="v-row ">
|
||||
|
||||
<v-col class="align-self-center font-weight-bold py-0" cols="auto">
|
||||
Тип ответа
|
||||
</v-col>
|
||||
<v-col class="py-0 align-self-center " cols="3">
|
||||
|
||||
<v-select v-model="question.settings.choice" :items="questionTypes" :list-props="{density:'compact'}"
|
||||
density="compact"
|
||||
hide-details
|
||||
item-title="name" item-value="choice" label="" variant="outlined"
|
||||
@update:model-value="question.answers=[]"></v-select>
|
||||
<!-- choice -->
|
||||
|
||||
</v-col>
|
||||
<v-spacer/>
|
||||
<v-col class="align-self-center font-weight-bold" cols="auto">
|
||||
Число возможных ответов
|
||||
</v-col>
|
||||
<v-col class="" cols="1">
|
||||
<v-text-field v-model="question.settings.multiChoice" :rules="[rules.required && question.settings.multiChoice > 0]"
|
||||
density="compact" hide-details
|
||||
min="1"
|
||||
type="number" variant="outlined">
|
||||
<template v-slot:prepend>
|
||||
|
||||
</template>
|
||||
</v-text-field>
|
||||
</v-col>
|
||||
</div>
|
||||
<div class="v-row">
|
||||
</div>
|
||||
|
||||
<v-card-text class="px-0">
|
||||
<div v-if="question.settings.choice === 'free'">
|
||||
<transition-group name="list" tag="div">
|
||||
<div v-for="(answer, ind) in question.answers" :key="ind" class="d-flex align-start mb-4">
|
||||
<v-text-field
|
||||
v-model="answer.text"
|
||||
:label="'Ответ ' + (ind + 1)"
|
||||
:rules="[rules.required]"
|
||||
class="mr-4"
|
||||
density="compact"
|
||||
variant="outlined">
|
||||
</v-text-field>
|
||||
<v-file-input
|
||||
v-model="answer.image"
|
||||
accept="image/*"
|
||||
dense
|
||||
density="compact"
|
||||
hide-details
|
||||
label="Картинка"
|
||||
variant="outlined">
|
||||
</v-file-input>
|
||||
<v-btn
|
||||
class="ms-1"
|
||||
color="error"
|
||||
icon="mdi-delete"
|
||||
size="small"
|
||||
@click="removeAnswer(index, ind)">
|
||||
</v-btn>
|
||||
</div>
|
||||
</transition-group>
|
||||
<div class="d-flex justify-start">
|
||||
<v-btn color="teal-darken-4" size="small" @click="addAnswer(index)">Добавить ответ</v-btn>
|
||||
</div>
|
||||
</div>
|
||||
<div v-else>
|
||||
<div class="v-row">
|
||||
<v-radio-group v-model="question.settings.onlyDep" class="text-caption" inline>
|
||||
<template v-slot:label>
|
||||
<div class="text-body-2 font-weight-bold">Голосование по отделам:</div>
|
||||
</template>
|
||||
<v-radio v-for="x in onlyDepdict" :key="x.name" :value=x.value>
|
||||
<template v-slot:label>
|
||||
<div class="text-caption">{{ x.name }}</div>
|
||||
</template>
|
||||
</v-radio>
|
||||
</v-radio-group>
|
||||
</div>
|
||||
<v-autocomplete
|
||||
v-model="question.selectedEmployees"
|
||||
:items="allEmployeesgroupedbydep" class=" text-no-wrap"
|
||||
density="compact" item-title="fio" item-value="id" label="Выберите сотрудников" multiple
|
||||
variant="outlined"
|
||||
@update:model-value="(selected)=>question.answers=question.answers.filter(e=>selected.includes(e.text))"
|
||||
>
|
||||
<template #prepend-item>
|
||||
<v-checkbox :model-value="question.selectedEmployees.length===allEmployees.length"
|
||||
class="pa-0"
|
||||
label="Все"
|
||||
@update:model-value="handleSelectAll(question.selectedEmployees.length===allEmployees.length, index)"></v-checkbox>
|
||||
</template>
|
||||
<template #selection="{item}">
|
||||
<v-chip
|
||||
:prepend-avatar="checkremote(`${spravURL}${item.raw.login}.jpg`)"
|
||||
>
|
||||
|
||||
{{ item.raw.familyname }}
|
||||
</v-chip>
|
||||
</template>
|
||||
<template #item="data">
|
||||
<template v-if="typeof data.item.raw !== 'object'">
|
||||
<v-divider/>
|
||||
<v-list-group class='pa-4 text-overline text-grey'
|
||||
v-text="data.item.raw"></v-list-group>
|
||||
</template>
|
||||
<template v-else>
|
||||
<v-list-item
|
||||
|
||||
:append-avatar="checkremote(`${spravURL}${data.item.raw.login}.jpg`)"
|
||||
density="compact"
|
||||
slim
|
||||
@click="onEmployeesChange(data.item.raw.id, index)"
|
||||
>
|
||||
<template #prepend>
|
||||
|
||||
<v-checkbox :model-value="question.selectedEmployees.includes(data.item.raw.id)"
|
||||
|
||||
density="compact"
|
||||
hide-details></v-checkbox>
|
||||
</template>
|
||||
<v-list-item-title class="text-third" v-text="data.item.raw.fio"></v-list-item-title>
|
||||
</v-list-item>
|
||||
</template>
|
||||
</template>
|
||||
</v-autocomplete>
|
||||
<transition-group name="list" tag="div">
|
||||
<div v-for="(person, ind) in question.answers" :key="person"
|
||||
class="v-row align-center mb-4">
|
||||
<v-col class="py-0" cols="7">
|
||||
<v-chip
|
||||
:prepend-avatar="checkremote(`${spravURL}${findEmployeeById(person.text)?.login}.jpg`)"
|
||||
:text="findEmployeeById(person.text)?.fio ">
|
||||
</v-chip>
|
||||
</v-col>
|
||||
<v-col class="py-0 d-flex" cols="5">
|
||||
<v-file-input v-model="person.image" accept="image/*" dense density="compact"
|
||||
hide-details
|
||||
label="Картинка" variant="outlined"></v-file-input>
|
||||
<v-btn class="ms-1" color="error" icon="mdi-delete" size="small"
|
||||
@click="question.selectedEmployees.splice(ind,1); removeAnswer(index,ind)">
|
||||
</v-btn>
|
||||
</v-col>
|
||||
</div>
|
||||
</transition-group>
|
||||
</div>
|
||||
</v-card-text>
|
||||
</div>
|
||||
</transition-group>
|
||||
<v-card-text style="max-height: 62vh; overflow-y: auto">
|
||||
<NewQuestion
|
||||
:form="form"
|
||||
:rules="rules"
|
||||
:quests="quests"
|
||||
@update:form="val => form.value = val"
|
||||
:allEmployees="allEmployees"
|
||||
:allEmployeesgroupedbydep="allEmployeesgroupedbydep"
|
||||
:handleSelectAll="handleSelectAll"
|
||||
:onEmployeesChange="onEmployeesChange"
|
||||
:findEmployeeById="findEmployeeById"
|
||||
:onlyDepdict="onlyDepdict"
|
||||
/>
|
||||
<v-divider class="ma-2 pa-1"></v-divider>
|
||||
<div class="d-flex justify-center">
|
||||
<v-btn color="orange-darken-4" size="small" @click="addQuestion">Добавить вопрос</v-btn>
|
||||
<v-btn color="orange-darken-4" size="small" @click="addQuestion"
|
||||
>Добавить вопрос
|
||||
</v-btn
|
||||
>
|
||||
</div>
|
||||
</v-card-text>
|
||||
<v-card-actions>
|
||||
@@ -265,52 +54,78 @@
|
||||
<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 class="fill-height" step="3">
|
||||
|
||||
<v-card class="fill-height d-flex flex-column" flat>
|
||||
<v-card-title>Подтверждение</v-card-title>
|
||||
<v-card-text style="max-height: 62vh; overflow-y: auto;">
|
||||
<v-card-text style="max-height: 62vh; overflow-y: auto">
|
||||
<v-alert v-if="errorMessage" class="mb-4" type="error">
|
||||
{{ errorMessage }}
|
||||
</v-alert>
|
||||
|
||||
<p>
|
||||
<v-icon :class="form.title===null||form.title.length===0?'':'opacity-0'" color='red' icon="mdi-alert"
|
||||
size="xsmall"/>
|
||||
<v-icon
|
||||
:class="form.title === null || form.title.length === 0 ? '' : 'opacity-0'"
|
||||
color="red"
|
||||
icon="mdi-alert"
|
||||
size="xsmall"
|
||||
/>
|
||||
<strong class="px-2">Название:</strong> {{ form.title }}
|
||||
</p>
|
||||
<p>
|
||||
<v-icon :class="form.description===null||form.description.length===0?'':'opacity-0'" color='red'
|
||||
icon="mdi-alert" size="xsmall"/>
|
||||
<v-icon
|
||||
:class="
|
||||
form.description === null || form.description.length === 0
|
||||
? ''
|
||||
: 'opacity-0'
|
||||
"
|
||||
color="red"
|
||||
icon="mdi-alert"
|
||||
size="xsmall"
|
||||
/>
|
||||
<strong class="px-2">Описание:</strong> {{ form.description }}
|
||||
</p>
|
||||
<p><strong class="px-2">Дата начала:</strong> {{ form.startDate.toLocaleDateString() }}</p>
|
||||
<p><strong class="px-2">Дата окончания:</strong> {{ form.endDate.toLocaleDateString() }}</p>
|
||||
<p>
|
||||
<strong class="px-2">Дата начала:</strong>
|
||||
{{ form.startDate.toLocaleDateString() }}
|
||||
</p>
|
||||
<p>
|
||||
<strong class="px-2">Дата окончания:</strong>
|
||||
{{ form.endDate.toLocaleDateString() }}
|
||||
</p>
|
||||
<p><strong class="px-2">Вопросы:</strong></p>
|
||||
|
||||
<v-card v-for="(question, index) in form.questions" :key="index" class="mb-4 pa-3">
|
||||
<v-card
|
||||
v-for="(question, index) in form.questions"
|
||||
:key="index"
|
||||
class="mb-4 pa-3"
|
||||
>
|
||||
<div class="pa-2">
|
||||
|
||||
<p><strong>Вопрос {{ index + 1 }}:</strong> {{ question.text }} ({{ question.type }})</p>
|
||||
<p>
|
||||
<strong>Вопрос {{ index + 1 }}:</strong> {{ question.text }} ({{
|
||||
question.type
|
||||
}})
|
||||
</p>
|
||||
|
||||
<div v-if="question.settings.choice === 'free' && 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.settings.choice === 'employee' && question.answers.length">
|
||||
<div>Количество допустимых ответов: {{ question.settings.multiChoice }}</div>
|
||||
<div class="">Голосование по отделам:
|
||||
{{ onlyDepdict.find(e => e.value === question.settings.onlyDep).name }}
|
||||
<div
|
||||
v-if="question.settings.choice === 'employee' && question.answers.length"
|
||||
>
|
||||
<div>
|
||||
Количество допустимых ответов: {{ question.settings.multiChoice }}
|
||||
</div>
|
||||
<div class="">
|
||||
Голосование по отделам:
|
||||
{{ onlyDepdict.find((e) => e.value === question.settings.onlyDep).name }}
|
||||
</div>
|
||||
<p><strong>Выбранные сотрудники:</strong></p>
|
||||
<ul>
|
||||
@@ -321,99 +136,104 @@
|
||||
</div>
|
||||
</div>
|
||||
</v-card>
|
||||
|
||||
</v-card-text>
|
||||
<v-card-actions>
|
||||
<v-btn color="teal-darken-4" size="medium" @click="step -= 1">Назад</v-btn>
|
||||
<v-btn :disabled="errorMessage!=''" color="teal-darken-4" size="medium" @click="saveVoting">
|
||||
<v-btn
|
||||
:disabled="errorMessage !== ''"
|
||||
color="teal-darken-4"
|
||||
size="medium"
|
||||
@click="saveVoting"
|
||||
>
|
||||
Сохранить
|
||||
</v-btn>
|
||||
</v-card-actions>
|
||||
|
||||
</v-card>
|
||||
</v-stepper-window-item>
|
||||
|
||||
</v-stepper-window>
|
||||
</v-stepper>
|
||||
</div>
|
||||
|
||||
</template>
|
||||
</v-row>
|
||||
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import {computed, ref, watch} from "vue";
|
||||
import {createVote, getEmployees, spravURL} from "@/utils/axios-api";
|
||||
import DateSelect from "@/components/UI/date-select.vue";
|
||||
import {checkremote} from "@/utils/universal_functions";
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { createVote, getEmployees } from '@/utils/axios-api';
|
||||
import DateSelect from '@/components/UI/date-select.vue';
|
||||
import MainInfo from '@/components/vote/ConstructorVote/MainInfo.vue';
|
||||
import CreatedVote from '@/components/vote/ConstructorVote/CreatedVote.vue';
|
||||
import NewQuestion from '@/components/vote/ConstructorVote/NewQuestion.vue';
|
||||
|
||||
export default {
|
||||
components: {DateSelect},
|
||||
components: { NewQuestion, CreatedVote, MainInfo, DateSelect },
|
||||
emits: ['updating'],
|
||||
setup(props, { emit }) {
|
||||
const step = ref(0);
|
||||
const isVoteCreated = ref(false);
|
||||
const form = ref({
|
||||
title: "",
|
||||
description: "",
|
||||
title: '',
|
||||
description: '',
|
||||
startDate: new Date(),
|
||||
endDate: new Date(new Date().setDate(new Date().getDate() + 14)),
|
||||
questions: [],
|
||||
createnews: false,
|
||||
appoint: false
|
||||
});
|
||||
|
||||
const rules = {
|
||||
required: (value) => !!value || "Это поле обязательно для заполнения",
|
||||
required: (value) => !!value || 'Это поле обязательно для заполнения',
|
||||
};
|
||||
|
||||
const currentQuestionIndex = ref(0);
|
||||
const questionTypes = [{name: "Ввести вручную", choice: 'free'}, {name: "Выбрать сотрудника", choice: 'employee'}];
|
||||
|
||||
const groupedEmployees = ref([]);
|
||||
const allEmployees = computed(() => [
|
||||
...groupedEmployees.value,
|
||||
]);
|
||||
const allEmployees = computed(() => [...groupedEmployees.value]);
|
||||
|
||||
getEmployees()
|
||||
.then(r => groupedEmployees.value = r)
|
||||
getEmployees().then((r) => (groupedEmployees.value = r));
|
||||
|
||||
const currentQuestion = computed(() =>
|
||||
form.value.questions[currentQuestionIndex.value] || null
|
||||
const currentQuestion = computed(
|
||||
() => form.value.questions[currentQuestionIndex.value] || null,
|
||||
);
|
||||
const allEmployeesgroupedbydep = computed(() => {
|
||||
let groupped = []
|
||||
for (let x of allEmployees.value.sort((a, b) => a.id_dict_department - b.id_dict_department)) {
|
||||
if (!groupped.includes(x.department)) groupped.push(x.department)
|
||||
groupped.push(x)
|
||||
let groupped = [];
|
||||
for (let x of allEmployees.value.sort(
|
||||
(a, b) => a.id_dict_department - b.id_dict_department,
|
||||
)) {
|
||||
if (!groupped.includes(x.department)) groupped.push(x.department);
|
||||
groupped.push(x);
|
||||
}
|
||||
return groupped
|
||||
})
|
||||
return groupped;
|
||||
});
|
||||
const findEmployeeById = (id) =>
|
||||
groupedEmployees.value.find((employee) => employee.id === id) || {};
|
||||
|
||||
|
||||
const handleSelectAll = (selected, index) => {
|
||||
if (!selected) {
|
||||
form.value.questions[index].answers = groupedEmployees.value.map((employee) => ({
|
||||
text: employee.id,
|
||||
image: null,
|
||||
}));
|
||||
form.value.questions[index].selectedEmployees = groupedEmployees.value.map(employee => employee.id);
|
||||
form.value.questions[index].selectedEmployees = groupedEmployees.value.map(
|
||||
(employee) => employee.id,
|
||||
);
|
||||
} else {
|
||||
form.value.questions[index].answers = [];
|
||||
form.value.questions[index].selectedEmployees = []
|
||||
form.value.questions[index].selectedEmployees = [];
|
||||
}
|
||||
};
|
||||
|
||||
const isAllSelected = computed(() => currentQuestion.value.answers.length === groupedEmployees.value.length);
|
||||
const isAllSelected = computed(
|
||||
() => currentQuestion.value.answers.length === groupedEmployees.value.length,
|
||||
);
|
||||
|
||||
const addQuestion = () => {
|
||||
form.value.questions.push({
|
||||
text: "",
|
||||
settings: {choice: "free", multiChoice: 1, onlyDep: null},
|
||||
text: '',
|
||||
settings: { choice: 'free', multiChoice: 1, onlyDep: null },
|
||||
image: null,
|
||||
answers: [],
|
||||
selectedEmployees: []
|
||||
selectedEmployees: [],
|
||||
});
|
||||
currentQuestionIndex.value = form.value.questions.length - 1;
|
||||
};
|
||||
@@ -425,28 +245,22 @@ export default {
|
||||
}
|
||||
};
|
||||
|
||||
const updateQuest = (index) => {
|
||||
quests[index] = form.value.questions[index].text.length > 0;
|
||||
};
|
||||
|
||||
const addAnswer = (index) => {
|
||||
if (currentQuestion.value) {
|
||||
form.value.questions[index].answers.push({text: "", image: null});
|
||||
form.value.questions[index].answers.push({ text: '', image: null });
|
||||
}
|
||||
};
|
||||
|
||||
const removeAnswer = (index, ind) => {
|
||||
form.value.questions[index].answers.splice(ind, 1)
|
||||
form.value.questions[index].answers.splice(ind, 1);
|
||||
};
|
||||
|
||||
const errorMessage = ref("");
|
||||
const errorMessage = ref('');
|
||||
|
||||
const validateAnswers = () => {
|
||||
return form.value.questions.some((question) => {
|
||||
if (question.settings.choice === "free") {
|
||||
return question.answers.some(
|
||||
(answer) => !answer.text || answer.text.trim() === ""
|
||||
);
|
||||
if (question.settings.choice === 'free') {
|
||||
return question.answers.some((answer) => !answer.text || answer.text.trim() === '');
|
||||
}
|
||||
return false;
|
||||
});
|
||||
@@ -463,25 +277,23 @@ export default {
|
||||
hasEmptyQuestions ||
|
||||
hasInvalidAnswers
|
||||
) {
|
||||
errorMessage.value = "Все обязательные поля и ответы должны быть заполнены";
|
||||
errorMessage.value = 'Все обязательные поля и ответы должны быть заполнены';
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await createVote(form.value);
|
||||
console.log("Голосование успешно создано:", response);
|
||||
await createVote(form.value);
|
||||
isVoteCreated.value = true;
|
||||
emit("updating", "active");
|
||||
emit('updating', 'active');
|
||||
} catch (error) {
|
||||
console.error("Ошибка при создании голосования:", error);
|
||||
return new Error(error)
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
const resetForm = () => {
|
||||
form.value = {
|
||||
title: "",
|
||||
description: "",
|
||||
title: '',
|
||||
description: '',
|
||||
startDate: new Date(),
|
||||
endDate: new Date(new Date().setDate(new Date().getDate() + 14)),
|
||||
questions: [],
|
||||
@@ -490,106 +302,65 @@ export default {
|
||||
isVoteCreated.value = false;
|
||||
};
|
||||
|
||||
const timeOptions = Array.from({length: 48}, (_, i) => {
|
||||
const hours = String(Math.floor(i / 2)).padStart(2, "0");
|
||||
const minutes = i % 2 === 0 ? "00" : "30";
|
||||
return `${hours}:${minutes}`;
|
||||
});
|
||||
|
||||
const selectedTimeStart = ref(
|
||||
`${(form.value.startDate.getHours() + 1).toString().padStart(2, "0")}:00`
|
||||
);
|
||||
|
||||
const selectedTimeEnd = ref(
|
||||
`${(form.value.endDate.getHours() + 1).toString().padStart(2, "0")}:00`
|
||||
);
|
||||
|
||||
watch(form.value, () => {
|
||||
watch(
|
||||
form.value,
|
||||
() => {
|
||||
if (!form.value.title || !form.value.description || form.value.questions.length < 1) {
|
||||
errorMessage.value = "Все обязательные поля должны быть заполнены";
|
||||
errorMessage.value = 'Все обязательные поля должны быть заполнены';
|
||||
} else {
|
||||
errorMessage.value = "";
|
||||
errorMessage.value = '';
|
||||
}
|
||||
}, { deep: true });
|
||||
|
||||
const updateQuests = () => {
|
||||
quests.value = form.value.questions.map((q) => !!q.text.trim());
|
||||
};
|
||||
|
||||
watch(() => form.value.questions, updateQuests, { deep: true });
|
||||
},
|
||||
{ deep: true },
|
||||
);
|
||||
|
||||
watch(
|
||||
() => form.value.questions,
|
||||
(newQuestions) => {
|
||||
const hasEmptyQuestions = newQuestions.some((q) => !q.text || q.text.trim() === "");
|
||||
quests.value = newQuestions.map((q) => !!q.text.trim());
|
||||
|
||||
// Проверяем, есть ли пустые вопросы или невалидные ответы
|
||||
const hasEmptyQuestions = newQuestions.some((q) => !q.text || q.text.trim() === '');
|
||||
const hasInvalidAnswers = validateAnswers();
|
||||
|
||||
if (hasEmptyQuestions || hasInvalidAnswers) {
|
||||
errorMessage.value = "Все вопросы и ответы должны быть заполнены";
|
||||
} else {
|
||||
errorMessage.value = "";
|
||||
}
|
||||
errorMessage.value =
|
||||
hasEmptyQuestions || hasInvalidAnswers
|
||||
? 'Все вопросы и ответы должны быть заполнены'
|
||||
: '';
|
||||
},
|
||||
{ deep: true }
|
||||
{ deep: true },
|
||||
);
|
||||
|
||||
|
||||
watch(selectedTimeStart, () => {
|
||||
updateStartDate()
|
||||
})
|
||||
watch(selectedTimeEnd, () => {
|
||||
updateEndDate()
|
||||
})
|
||||
|
||||
const updateStartDate = () => {
|
||||
const [hours, minutes] = selectedTimeStart.value.split(":").map(Number);
|
||||
form.value.startDate.setHours(hours, minutes);
|
||||
};
|
||||
const updateEndDate = () => {
|
||||
const [hours, minutes] = selectedTimeEnd.value.split(":").map(Number);
|
||||
form.value.endDate.setHours(hours, minutes);
|
||||
};
|
||||
|
||||
const returnstart = (dates) => {
|
||||
form.value.startDate = dates
|
||||
}
|
||||
|
||||
const returnend = (dates) => {
|
||||
form.value.endDate = dates
|
||||
}
|
||||
|
||||
const onEmployeesChange = (selected, index) => {
|
||||
let ind = form.value.questions[index].selectedEmployees.findIndex(e => e === selected)
|
||||
let ind = form.value.questions[index].selectedEmployees.findIndex((e) => e === selected);
|
||||
if (ind > -1) {
|
||||
form.value.questions[index].selectedEmployees.splice(ind, 1)
|
||||
let answ = form.value.questions[index].answers.findIndex(a => a.text === selected)
|
||||
form.value.questions[index].answers.splice(answ, 1)
|
||||
form.value.questions[index].selectedEmployees.splice(ind, 1);
|
||||
let answ = form.value.questions[index].answers.findIndex((a) => a.text === selected);
|
||||
form.value.questions[index].answers.splice(answ, 1);
|
||||
} else {
|
||||
form.value.questions[index].selectedEmployees.push(selected)
|
||||
form.value.questions[index].selectedEmployees.push(selected);
|
||||
form.value.questions[index].answers.push({ text: selected, image: null });
|
||||
}
|
||||
};
|
||||
|
||||
const onlyDepdict = [{name: 'За любого сотрудника', value: null}, {
|
||||
name: "Кроме своего отдела",
|
||||
value: false
|
||||
}, {name: "Только за свой отдел", value: true}]
|
||||
const onlyDepdict = [
|
||||
{ name: 'За любого сотрудника', value: null },
|
||||
{
|
||||
name: 'Кроме своего отдела',
|
||||
value: false,
|
||||
},
|
||||
{ name: 'Только за свой отдел', value: true },
|
||||
];
|
||||
|
||||
const quests = computed(() =>
|
||||
form.value.questions.map((question) => question.text.length > 0)
|
||||
);
|
||||
const quests = computed(() => form.value.questions.map((question) => question.text.length > 0));
|
||||
|
||||
return {
|
||||
quests,
|
||||
updateQuest,
|
||||
onlyDepdict,
|
||||
allEmployeesgroupedbydep,
|
||||
onEmployeesChange,
|
||||
returnend,
|
||||
returnstart,
|
||||
step,
|
||||
form,
|
||||
questionTypes,
|
||||
addQuestion,
|
||||
removeQuestion,
|
||||
addAnswer,
|
||||
@@ -600,14 +371,9 @@ export default {
|
||||
resetForm,
|
||||
rules,
|
||||
errorMessage,
|
||||
timeOptions,
|
||||
selectedTimeStart,
|
||||
selectedTimeEnd,
|
||||
allEmployees,
|
||||
handleSelectAll,
|
||||
isAllSelected,
|
||||
checkremote,
|
||||
spravURL
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -628,5 +394,4 @@ export default {
|
||||
opacity: 0;
|
||||
transform: translateX(50px);
|
||||
}
|
||||
|
||||
</style>
|
||||
@@ -1,8 +1,6 @@
|
||||
<template>
|
||||
<div>
|
||||
<v-list nav density="compact" class="text-blue-grey-lighten-1">
|
||||
|
||||
|
||||
<v-list-item
|
||||
v-for="x in aMenuItem"
|
||||
:key="x"
|
||||
@@ -10,47 +8,45 @@
|
||||
:value="x.name"
|
||||
:href="x.link"
|
||||
:target="x.link ? '_blank' : ''"
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
slim
|
||||
>
|
||||
<template v-slot:prepend>
|
||||
<v-icon :icon="x.ico" size="x_small" />
|
||||
<v-tooltip v-if="rail" activator="parent" location="top">
|
||||
</v-tooltip>
|
||||
<v-tooltip v-if="rail" activator="parent" location="top"> </v-tooltip>
|
||||
</template>
|
||||
</v-list-item>
|
||||
|
||||
</v-list>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { baseURL } from "@/utils/axios-api";
|
||||
|
||||
import { baseURL } from '@/utils/axios-api';
|
||||
|
||||
export default {
|
||||
name: 'AdminMenu',
|
||||
props: {
|
||||
rail: {
|
||||
type: Boolean,
|
||||
default: false
|
||||
default: false,
|
||||
},
|
||||
},
|
||||
|
||||
setup() {
|
||||
const aMenuItem = [
|
||||
{
|
||||
name: "Панель администратора",
|
||||
ico: "mdi-wrench",
|
||||
link: baseURL + "admin",
|
||||
name: 'Панель администратора',
|
||||
ico: 'mdi-wrench',
|
||||
link: baseURL + 'admin',
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
|
||||
];
|
||||
|
||||
return {
|
||||
aMenuItem,
|
||||
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
@@ -13,6 +13,8 @@
|
||||
<template v-if="accountStore.cod2user">
|
||||
<vcard-user :author="accountStore.user" />
|
||||
<v-tooltip location="bottom">
|
||||
|
||||
|
||||
<template v-slot:activator="{ props }">
|
||||
<v-btn color="black_and_white" v-bind="props" dark to="/faq" icon="mdi-comment-question-outline" />
|
||||
</template>
|
||||
@@ -298,16 +300,16 @@ export default {
|
||||
// ico: "mdi-calendar",
|
||||
// path: "/ical",
|
||||
// },
|
||||
// {
|
||||
// name: "Голосование",
|
||||
// ico: "mdi-vote",
|
||||
// path: "/vote",
|
||||
// },
|
||||
// {
|
||||
// name: "Тестирование",
|
||||
// ico: "mdi-book-open-blank-variant",
|
||||
// path: "/test",
|
||||
// },
|
||||
{
|
||||
name: "Голосование",
|
||||
ico: "mdi-vote",
|
||||
path: "/vote",
|
||||
},
|
||||
{
|
||||
name: "Тестирование",
|
||||
ico: "mdi-book-open-blank-variant",
|
||||
path: "/test",
|
||||
},
|
||||
|
||||
{
|
||||
name: "Об инспекции",
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
#### Строка импорта:
|
||||
```
|
||||
import { useAlertStore } from '@/store/useAlertStore'
|
||||
import { useAlertStore } from '@/store/UseAlertStore'
|
||||
|
||||
```
|
||||
|
||||
|
||||
@@ -5,8 +5,10 @@
|
||||
:color="feedalert.color"
|
||||
:icon="feedalert.ico"
|
||||
|
||||
|
||||
>
|
||||
<v-icon :icon="feedalert.ico" />
|
||||
|
||||
<span class="pl-2 text-body-2">
|
||||
{{ feedalert.text }}
|
||||
</span>
|
||||
@@ -17,7 +19,7 @@
|
||||
|
||||
<script>
|
||||
import { watch } from "vue";
|
||||
import { useAlertStore } from "@/store/useAlertStore";
|
||||
import { useAlertStore } from "@/store/UseAlertStore";
|
||||
|
||||
export default {
|
||||
name: "AlertDefault",
|
||||
@@ -25,11 +27,14 @@ export default {
|
||||
const feedalert = useAlertStore().alert;
|
||||
|
||||
watch(
|
||||
|
||||
() => feedalert,
|
||||
() => {
|
||||
setTimeout(function () {
|
||||
feedalert.text = "";
|
||||
feedalert.ico = "";
|
||||
|
||||
|
||||
feedalert.color = "";
|
||||
feedalert.alert = false;
|
||||
}, 8000);
|
||||
|
||||
@@ -177,6 +177,12 @@ const routes = [
|
||||
ico: "mdi-account",
|
||||
},
|
||||
},
|
||||
{
|
||||
path: "/test/testdetail/:id",
|
||||
name: "TestDetail",
|
||||
component: () =>
|
||||
import("@/components/testing/DetailCardTest.vue")
|
||||
},
|
||||
{
|
||||
path: '/secret',
|
||||
name: 'Secret Page',
|
||||
|
||||
Loaded 100 of 122 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user