58 Commits
Author SHA1 Message Date
Vitaly d13d02fadb chore [P-0]: сhore 2026-12-01 16:13:26 +03:00
denzel dbe5dcae2d refactor [OVT-62]: фикс победителей 2026-10-21 08:57:12 -04:00
denzel ae8ca296fe refactor [OVT-62]: фикс победителей 2026-10-21 08:49:33 -04:00
Denis Voinovich 53736a1d5d chore [X-01]: версия 2025-10-23 16:37:04 +03:00
Denis Voinovich cba4f5cbf4 chore [X-01]: версия 2025-10-23 16:36:36 +03:00
Denis Voinovich 503a634c28 chore [X-01]: версия 2025-10-23 14:53:33 +03:00
Denis Voinovich 58f32ceaad chore [X-01]: фикс 2025-10-23 14:52:25 +03:00
Denis Voinovich c8bedd3c70 chore [X-01]: фикс 2025-10-23 14:44:52 +03:00
Denis Voinovich 3aeb0840f4 chore [X-01]: пулл 2025-10-22 15:39:02 +03:00
Nukeap 6a5e25a3d7 chore [X-01]: 1,3,0 2025-10-22 15:23:21 +03:00
Denis Voinovich 3bbc71eb23 chore [X-01]: пулл 2025-10-22 15:06:22 +03:00
Denis Voinovich 5dc38430c4 chore [X-01]: пулл 2025-10-22 14:32:24 +03:00
Denis Voinovich b2e864b7a3 chore [X-01]: пулл 2025-10-22 14:30:43 +03:00
Inna 8ff1c62ab6 fix [P-290]: чистка от комментов 2025-10-10 14:03:49 +03:00
Inna 2cb4e2577f fix [P-290]: правка доступных календарей для редактирования событий 2025-10-10 14:02:36 +03:00
Inna 635361eeba fix [P-290]: добавлены фильтры для событий 2025-10-10 13:35:56 +03:00
Inna bb6bbdedb1 fix [P-290]: исправлена логика чекбокса "Окончание события" 2025-10-09 12:21:44 +03:00
Inna b74e1342a8 fix [P-290]: отображение полного времени события в календаре 2025-10-09 08:23:59 +03:00
Inna f4cb8b14b9 fix [P-290]: изменения в цветовой гамме календарей 2025-10-09 08:09:07 +03:00
Inna 0328970ddd fix [P-290]: просмотр всех событий 2025-10-08 16:21:49 +03:00
Inna 4441cbf727 fix [P-290]: фикс селекта выбора времени событий 2025-10-08 10:21:08 +03:00
Inna cbbcae4f35 fix [P-290]: модалка просмотра события 2025-10-07 15:54:08 +03:00
Inna 127d4dba69 fix [P-290]: фикс событий в виджете календаря 2025-10-07 13:38:37 +03:00
Inna d0186bdabf fix [P-290]: фикс выбора начальников 2025-10-06 10:24:29 +03:00
Inna 4a3952123c fix [P-290]: выбор всех начальников/замначальников 2025-10-03 15:37:48 +03:00
Inna a69f59aa8d fix [P-290]: исправлено обновление календарей после редактирования 2025-10-03 09:17:32 +03:00
Inna a8272a8a90 fix [P-290]: добавлен функционал окончания события 2025-10-03 08:32:13 +03:00
Inna 57bf0889ab fix [P-290]: фикс обновления календарей при удалении 2025-10-02 10:41:43 +03:00
Inna ec76bad1e6 fix [P-290]: проверить время событий 2025-10-02 10:17:14 +03:00
Inna 4a95da910d fix [P-290]: поиск сотрудников 2025-10-02 09:23:07 +03:00
Inna 4ad311bc04 fix [P-290]: фикс участиников событий 2025-10-01 16:57:37 +03:00
Inna 0c68b1aaa6 fix [P-290]: убраны логи 2025-10-01 13:26:23 +03:00
Inna 0371a5ad74 fix [P-290]: Merge branch 'cja_new' into inna-dev 2025-10-01 13:13:22 +03:00
Inna 3738591122 fix [P-290]: поиск 2025-10-01 13:10:47 +03:00
cja 88c9403fa4 EventFiles 2025-10-01 13:06:13 +03:00
Inna f27037ebe5 fix [P-47]: фикс событий 2025-09-30 14:39:12 +03:00
Inna a839273951 fix [P-47]: фикс событий 2025-09-30 12:07:58 +03:00
Inna 2c609e2fd9 fix [P-51]: добавлены праздники к dare-picker 2025-09-29 15:51:16 +03:00
Inna 5edadc5ef7 fix [P-47]: прикрепление файлов 2025-09-29 13:19:37 +03:00
Inna b29e7eb535 fix [P-290]: добавление файла к событию 2025-09-29 08:25:21 +03:00
Inna 1e1311bb22 fix [P-51]: переход на расписание при клике на день 2025-09-26 14:54:11 +03:00
Inna 37b1f18c4c fix [P-51]: добавлено визуальное отображение праздничных дней 2025-09-26 14:34:20 +03:00
Inna 76a6d0ae20 fix [P-290]: исправлен виджет календаря на домашней странице 2025-09-26 08:41:29 +03:00
Inna 45f365f734 fix [P-290]: фикс повтора событий 2025-09-25 16:26:31 +03:00
Inna 76fb9316cd fix [P-290]: фикс повтора событий 2025-09-25 14:50:18 +03:00
Inna 22f9220a57 fix [P-290]: фикс ошибок 2025-09-25 12:37:53 +03:00
Inna 77d6679f39 refactor [P-52]: исправление функционала повторения событий 2025-09-24 11:19:35 +03:00
Inna f189636791 fix [P-47]: редактирование и удаление событий 2025-09-23 13:36:43 +03:00
Inna 1f898f9281 fix [P-47]: исправления выбора дат в форме 2025-09-23 09:45:33 +03:00
Inna 21ed19749e refactor [P-47]: упрощение логики, возможность выбора всех сотрудников для событий 2025-09-22 16:46:20 +03:00
Inna e8dbb47479 fix [P-56]: изменение логики отображения событий 2025-09-22 12:47:58 +03:00
Inna 65f76c65b7 fix [P-47]: отображение событий 2025-09-18 12:09:40 +03:00
cja 5a746ff4b0 MyEvents get 2025-09-17 16:02:04 +03:00
Inna dbb5799d7c fix [P-57]: тестовый запрос 2025-09-17 15:56:05 +03:00
Inna 0e2440d94e fix [P-57]: связка календарей 2025-09-16 14:13:21 +03:00
Inna d003ab12e7 fix [P-57]: фикс заголовков календаря 2025-09-11 16:27:00 +03:00
Inna ac9bb6dba1 refactor [P-57]: Merge branch 'develop' into inna-dev 2025-09-11 12:11:39 +03:00
Inna d77c9ec49b refactor [P-57]: add FullCalendar 2025-09-11 12:01:43 +03:00
64 changed files with 25099 additions and 1862 deletions

No files matched your search

+1
View File
@@ -7,3 +7,4 @@ DB_USER="root"
DB_PASSWORD="yourpassword" DB_PASSWORD="yourpassword"
DB_HOST="db" DB_HOST="db"
DB_PORT=3306 DB_PORT=3306
MYDEBUG=True
+621 -30
View File
@@ -1,37 +1,628 @@
#!/usr/bin/env sh #!/usr/bin/env sh
LC_ALL=C; export LC_ALL
LANG=C; export LANG
commit_msg_file="$1" commit_msg_file="$1"
ACHIEVEMENTS_SERVICE="${ACHIEVEMENTS_SERVICE:-https://scores.9966hub.ru}"
# Читаем сообщение коммита REPO_ROOT=$(git rev-parse --show-toplevel)
commit_msg=$(cat "$commit_msg_file") RESULTS_DIR="$REPO_ROOT/.git/linter-results"
# Проверяем, был ли передан аргумент HTML_FILE="$REPO_ROOT/linter_errors.html"
if [ -z "$commit_msg" ]; then
echo "Ошибка: Необходимо передать сообщение коммита." # ============================================
exit 1 # ДАННЫЕ О КОММИТЕ
# ============================================
GIT_LOGIN=$(git config user.name 2>/dev/null | cut -d@ -f1 | tr '[:upper:]' '[:lower:]' | tr ' ' '_')
[ -z "$GIT_LOGIN" ] && GIT_LOGIN=$(git config user.email 2>/dev/null | cut -d@ -f1 | tr '[:upper:]' '[:lower:]')
[ -z "$GIT_LOGIN" ] && GIT_LOGIN="unknown"
commit_msg=$(sed '/^#/d' "$commit_msg_file" | sed '/^[[:space:]]*$/d' | head -n 1)
[ -z "$commit_msg" ] && { echo "Ошибка: пустое сообщение коммита."; exit 1; }
case "$commit_msg" in
Merge\ *|merge\ *|Release\ *|release\ *)
echo "Служебный коммит — сервис не дёргаем."
exit 0
;;
esac
PROJECT_CODE=$(echo "$commit_msg" | grep -oE '\[[A-Z0-9]+-[0-9]+\]' | head -1 | tr -d '[]' | cut -d- -f1)
PROJECT_SLUG=$(echo "$PROJECT_CODE" | tr '[:upper:]' '[:lower:]')
[ -z "$PROJECT_SLUG" ] && PROJECT_SLUG="${ACHIEVEMENTS_PROJECT_SLUG:-p}"
COMMIT_SHA=$(git rev-parse HEAD 2>/dev/null || echo "")
BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "")
PATTERN="^(feat|fix|docs|style|refactor|perf|test|chore) \[[A-Z0-9]+-[0-9]+\]: .+$"
MSG_OK=0
echo "$commit_msg" | grep -qE "$PATTERN" && MSG_OK=1
STATS=$(git diff --cached --shortstat 2>/dev/null)
LINES_ADDED=$(echo "$STATS" | grep -oE '[0-9]+ insertion' | grep -oE '[0-9]+')
LINES_DELETED=$(echo "$STATS" | grep -oE '[0-9]+ deletion' | grep -oE '[0-9]+')
FILES_CHANGED=$(echo "$STATS" | grep -oE '[0-9]+ file' | grep -oE '[0-9]+')
LINES_ADDED=${LINES_ADDED:-0}
LINES_DELETED=${LINES_DELETED:-0}
FILES_CHANGED=${FILES_CHANGED:-0}
# ============================================
# ЛИНТЕРЫ
# ============================================
HAS_ANY_ERRORS=0
HAS_JS=0; JS_OUTPUT=""; JS_STATUS=0; ESLINT_ERRORS=0; ESLINT_WARNINGS=0
if [ -f "$RESULTS_DIR/js.status" ]; then
HAS_JS=1
JS_STATUS=$(cat "$RESULTS_DIR/js.status" | tr -cd '0-9'); JS_STATUS=${JS_STATUS:-0}
JS_OUTPUT=$(cat "$RESULTS_DIR/js.out")
[ "$JS_STATUS" -ne 0 ] && HAS_ANY_ERRORS=1
ESLINT_ERRORS=$(echo "$JS_OUTPUT" | grep -oE '[0-9]+ errors?' | grep -oE '[0-9]+' | head -1)
ESLINT_WARNINGS=$(echo "$JS_OUTPUT" | grep -oE '[0-9]+ warnings?' | grep -oE '[0-9]+' | head -1)
ESLINT_ERRORS=$(echo "$ESLINT_ERRORS" | tr -cd '0-9'); ESLINT_ERRORS=${ESLINT_ERRORS:-0}
ESLINT_WARNINGS=$(echo "$ESLINT_WARNINGS" | tr -cd '0-9'); ESLINT_WARNINGS=${ESLINT_WARNINGS:-0}
fi fi
HAS_PYLINT=0; PYLINT_OUTPUT=""; PYLINT_STATUS=0; PYLINT_SCORE=0
if [ -f "$RESULTS_DIR/pylint.status" ]; then
HAS_PYLINT=1
PYLINT_STATUS=$(cat "$RESULTS_DIR/pylint.status" | tr -cd '0-9'); PYLINT_STATUS=${PYLINT_STATUS:-0}
PYLINT_OUTPUT=$(cat "$RESULTS_DIR/pylint.out")
[ "$PYLINT_STATUS" -ne 0 ] && HAS_ANY_ERRORS=1
# Определяем шаблон для проверки if [ -f "$RESULTS_DIR/pylint.score" ]; then
PATTERN="^(feat|fix|docs|style|refactor|perf|test|chore) \[[A-Z]+\-[0-9]+]: .+$" PYLINT_SCORE=$(cat "$RESULTS_DIR/pylint.score" | tr ',' '.')
PYLINT_SCORE=$(echo "$PYLINT_SCORE" | tr -cd '0-9.')
case "$PYLINT_SCORE" in *.*.*) PYLINT_SCORE=0 ;; esac
PYLINT_SCORE=${PYLINT_SCORE:-0}
# Проверяем соответствие шаблону fi
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 fi
HAS_MYPY=0; MYPY_OUTPUT=""; MYPY_STATUS=0; MYPY_SCORE=0; MYPY_ERRORS=0; MYPY_LINES=0
if [ -f "$RESULTS_DIR/mypy.status" ]; then
HAS_MYPY=1
MYPY_STATUS=$(cat "$RESULTS_DIR/mypy.status" | tr -cd '0-9'); MYPY_STATUS=${MYPY_STATUS:-0}
MYPY_OUTPUT=$(cat "$RESULTS_DIR/mypy.out")
[ "$MYPY_STATUS" -ne 0 ] && HAS_ANY_ERRORS=1
if [ -f "$RESULTS_DIR/mypy.score" ]; then
MYPY_SCORE=$(cat "$RESULTS_DIR/mypy.score" | tr ',' '.')
MYPY_SCORE=$(echo "$MYPY_SCORE" | tr -cd '0-9.')
case "$MYPY_SCORE" in *.*.*) MYPY_SCORE=0 ;; esac
MYPY_SCORE=${MYPY_SCORE:-0}
fi
[ -f "$RESULTS_DIR/mypy.errors" ] && MYPY_ERRORS=$(cat "$RESULTS_DIR/mypy.errors" | tr -cd '0-9')
[ -f "$RESULTS_DIR/mypy.lines" ] && MYPY_LINES=$(cat "$RESULTS_DIR/mypy.lines" | tr -cd '0-9')
MYPY_ERRORS=${MYPY_ERRORS:-0}
MYPY_LINES=${MYPY_LINES:-0}
fi
# ============================================
# ОЦЕНКИ FRONT / BACK / TOTAL
# ============================================
XP_PYLINT=""; XP_MYPY=""; XP_JS=""
if [ -n "$PYLINT_SCORE" ] && [ "$PYLINT_SCORE" != "0" ]; then
XP_PYLINT=$(awk -v s="$PYLINT_SCORE" 'BEGIN {
if (s < 0) s = 0; if (s > 10) s = 10; printf "%.2f", s
}')
fi
if [ -n "$MYPY_SCORE" ] && [ "$MYPY_SCORE" != "0" ]; then
XP_MYPY=$(awk -v s="$MYPY_SCORE" 'BEGIN {
if (s < 0) s = 0; if (s > 10) s = 10; printf "%.2f", s
}')
fi
if [ "$HAS_JS" -eq 1 ]; then
JS_FILES=$(cat "$RESULTS_DIR/js.files" 2>/dev/null | tr -cd '0-9')
JS_FILES=${JS_FILES:-1}
[ "$JS_FILES" -lt 1 ] && JS_FILES=1
XP_JS=$(awk -v err="$ESLINT_ERRORS" -v warn="$ESLINT_WARNINGS" -v files="$JS_FILES" 'BEGIN {
s = 10 - (err / files) * 3 - (warn / files) * 1
if (s < 0) s = 0; if (s > 10) s = 10; printf "%.2f", s
}')
fi
FRONT_ACTIVE=0
BACK_ACTIVE=0
[ "$HAS_JS" -eq 1 ] && FRONT_ACTIVE=1
if [ "$HAS_PYLINT" -eq 1 ] || [ "$HAS_MYPY" -eq 1 ]; then BACK_ACTIVE=1; fi
FRONT_SCORE=""
[ "$FRONT_ACTIVE" -eq 1 ] && FRONT_SCORE="$XP_JS"
BACK_SCORE=""
if [ "$BACK_ACTIVE" -eq 1 ]; then
if [ -n "$XP_PYLINT" ] && [ -n "$XP_MYPY" ]; then
BACK_SCORE=$(awk -v p="$XP_PYLINT" -v m="$XP_MYPY" 'BEGIN {
avg = (p + m) / 2
diff = (p > m) ? (p - m) : (m - p)
s = avg - diff * 0.5
if (s < 0) s = 0; if (s > 10) s = 10; printf "%.2f", s
}')
elif [ -n "$XP_PYLINT" ]; then BACK_SCORE="$XP_PYLINT"
elif [ -n "$XP_MYPY" ]; then BACK_SCORE="$XP_MYPY"
else BACK_SCORE=10
fi
fi
TOTAL_SCORE=""
if [ "$FRONT_ACTIVE" -eq 1 ] && [ "$BACK_ACTIVE" -eq 1 ]; then
TOTAL_SCORE=$(awk -v f="$FRONT_SCORE" -v b="$BACK_SCORE" 'BEGIN {
avg = (f + b) / 2
diff = (f > b) ? (f - b) : (b - f)
s = avg - diff * 0.5
if (s < 0) s = 0; if (s > 10) s = 10; printf "%.2f", s
}')
elif [ "$FRONT_ACTIVE" -eq 1 ]; then TOTAL_SCORE="$FRONT_SCORE"
elif [ "$BACK_ACTIVE" -eq 1 ]; then TOTAL_SCORE="$BACK_SCORE"
fi
# ============================================
# ДЕФОЛТЫ
# ============================================
XP=0
LEVEL=0
RANK_ICON="❓"
RANK_TITLE="Сервис недоступен"
DELTA_XP=0
CURRENT_XP=0
NEED_XP=100
PERCENT=0
COMMIT_COUNT=0
NEW_ACHIEVEMENTS=""
SERVICE_RESPONSE="{}"
# ============================================
# ОТПРАВКА В СЕРВИС
# ============================================
if command -v curl >/dev/null 2>&1 && command -v jq >/dev/null 2>&1 && [ "$MSG_OK" -eq 1 ]; then
HAD_ERRORS_JSON=$([ "$HAS_ANY_ERRORS" -eq 1 ] && echo true || echo false)
XP_DELTA=0
[ -n "$TOTAL_SCORE" ] && XP_DELTA=$(awk -v s="$TOTAL_SCORE" 'BEGIN {
xp = int(s + 0.5)
if (xp < 0) xp = 0
print xp
}')
PAYLOAD=$(jq -n \
--arg login "$GIT_LOGIN" \
--arg project_slug "$PROJECT_SLUG" \
--arg commit_sha "$COMMIT_SHA" \
--arg commit_msg "$commit_msg" \
--arg branch "$BRANCH" \
--argjson had_errors "$HAD_ERRORS_JSON" \
--argjson front "${FRONT_SCORE:-null}" \
--argjson back "${BACK_SCORE:-null}" \
--argjson total "${TOTAL_SCORE:-null}" \
--argjson pylint "${PYLINT_SCORE:-null}" \
--argjson mypy "${MYPY_SCORE:-null}" \
--argjson mypy_errors "${MYPY_ERRORS:-null}" \
--argjson mypy_lines "${MYPY_LINES:-null}" \
--argjson eslint_errors "${ESLINT_ERRORS:-null}" \
--argjson eslint_warnings "${ESLINT_WARNINGS:-null}" \
--argjson js_files "${JS_FILES:-null}" \
--argjson lines_added "$LINES_ADDED" \
--argjson lines_deleted "$LINES_DELETED" \
--argjson files_changed "$FILES_CHANGED" \
--argjson xp_delta "$XP_DELTA" \
'{
login: $login, project_slug: $project_slug,
commit_sha: $commit_sha, commit_msg: $commit_msg, branch: $branch,
had_errors: $had_errors,
front_score: $front, back_score: $back, total_score: $total,
pylint_score: $pylint, mypy_score: $mypy,
mypy_errors: $mypy_errors, mypy_lines: $mypy_lines,
eslint_errors: $eslint_errors, eslint_warnings: $eslint_warnings,
js_files: $js_files,
lines_added: $lines_added,
lines_deleted: $lines_deleted,
files_changed: $files_changed,
xp_delta: $xp_delta
}')
HTTP_CODE=$(curl -s -o /tmp/ach_resp.json -w "%{http_code}" --max-time 5 \
-X POST "$ACHIEVEMENTS_SERVICE/progress" \
-H "Content-Type: application/json" \
-d "$PAYLOAD" 2>/dev/null)
SERVICE_RESPONSE=$(cat /tmp/ach_resp.json 2>/dev/null)
[ -z "$SERVICE_RESPONSE" ] && SERVICE_RESPONSE="{}"
if [ "${ACHIEVEMENTS_DEBUG:-0}" = "1" ]; then
echo "ACH: POST $ACHIEVEMENTS_SERVICE/progress → HTTP $HTTP_CODE"
echo "ACH: payload: $PAYLOAD"
echo "ACH: response: $SERVICE_RESPONSE"
fi
XP=$(echo "$SERVICE_RESPONSE" | jq -r '.xp // 0')
LEVEL=$(echo "$SERVICE_RESPONSE" | jq -r '.level // 0')
RANK_ICON=$(echo "$SERVICE_RESPONSE" | jq -r '.rank_icon // "❓"')
RANK_TITLE=$(echo "$SERVICE_RESPONSE" | jq -r '.rank_title // "Неизвестный"')
DELTA_XP=$(echo "$SERVICE_RESPONSE" | jq -r '.xp_delta // 0')
CURRENT_XP=$(echo "$SERVICE_RESPONSE" | jq -r '.current_xp // 0')
NEED_XP=$(echo "$SERVICE_RESPONSE" | jq -r '.need_xp // 100')
PERCENT=$(echo "$SERVICE_RESPONSE" | jq -r '.percent // 0')
COMMIT_COUNT=$(echo "$SERVICE_RESPONSE" | jq -r '.commit_count // 0')
NEW_ACHIEVEMENTS=$(echo "$SERVICE_RESPONSE" | jq -r '.new_achievements // [] | join(", ")')
fi
if [ "${PERCENT:-0}" -lt 30 ]; then PERCENT_COLOR="#f14c4c"
elif [ "${PERCENT:-0}" -lt 70 ]; then PERCENT_COLOR="#e5c07b"
else PERCENT_COLOR="#4ec9b0"; fi
# ============================================
# ПРЕДЗАГРУЗКА ПРОФИЛЯ ЧЕРЕЗ CURL
# ============================================
PROFILE_JSON="null"
if command -v curl >/dev/null 2>&1 && [ -n "$GIT_LOGIN" ] && [ "$GIT_LOGIN" != "unknown" ]; then
PROFILE_JSON=$(curl -s --max-time 5 \
"$ACHIEVEMENTS_SERVICE/users/$(printf '%s' "$GIT_LOGIN" | jq -sRr @uri)/overview" \
2>/dev/null)
[ -z "$PROFILE_JSON" ] && PROFILE_JSON="null"
printf '%s' "$PROFILE_JSON" | jq -e . >/dev/null 2>&1 || PROFILE_JSON="null"
fi
PROFILE_JSON_ESCAPED=$(printf '%s' "$PROFILE_JSON" | sed 's/</\\u003c/g; s/>/\\u003e/g; s/&/\\u0026/g')
# ============================================
# HTML-ОТЧЁТ
# ============================================
if [ "$HAS_JS" -eq 1 ] || [ "$HAS_PYLINT" -eq 1 ] || [ "$HAS_MYPY" -eq 1 ]; then
DATETIME=$(date '+%Y-%m-%d %H:%M:%S')
cat > "$HTML_FILE" << EOF
<!DOCTYPE html>
<html lang="ru"><head><meta charset="UTF-8">
<title>$commit_msg</title>
<style>
* { margin:0; padding:0; box-sizing:border-box; }
body { background:#1e1e1e; color:#d4d4d4; font-family:'Segoe UI',monospace; padding:30px; line-height:1.6; }
.container { max-width:1200px; margin:0 auto; background:#252526; border-radius:12px; padding:30px; box-shadow:0 10px 40px rgba(0,0,0,0.5); }
h1 { color:#f14c4c; font-size:28px; border-bottom:2px solid #333; padding-bottom:15px; margin-bottom:20px; }
/* Табы */
.tabs { display:flex; gap:4px; border-bottom:2px solid #333; margin-bottom:25px; }
.tab-btn { background:#2d2d2d; color:#888; border:none; padding:12px 24px; font-family:inherit; font-size:14px; cursor:pointer; border-radius:8px 8px 0 0; border-bottom:3px solid transparent; transition:all 0.2s; }
.tab-btn:hover { color:#d4d4d4; background:#333; }
.tab-btn.active { color:#4ec9b0; background:#252526; border-bottom-color:#4ec9b0; }
.tab-content { display:none; }
.tab-content.active { display:block; }
/* Карточка пользователя */
.user-card { display:flex; align-items:center; gap:20px; background:#2d2d2d; padding:20px; border-radius:10px; margin-bottom:25px; }
.user-info { flex:1; }
.user-name { font-size:20px; color:#4ec9b0; font-weight:bold; }
.user-stats { display:flex; gap:25px; margin-top:8px; }
.user-stat { font-size:13px; color:#888; }
.user-stat b { color:#d4d4d4; font-size:16px; }
.level-bar { margin-top:10px; background:#1e1e1e; height:8px; border-radius:4px; overflow:hidden; position:relative; }
.level-fill { height:100%; min-width:4px; background:$PERCENT_COLOR; transition:width 0.5s; border-radius:4px; }
.level-bar::after { content:""; position:absolute; inset:0; border-radius:4px; box-shadow: inset 0 0 0 1px rgba(78,201,176,0.15); pointer-events:none; }
.level-text { margin-top:6px; font-size:12px; color:#666; text-align:right; }
.user-rank { text-align:center; padding:20px 25px; background:#1e1e1e; border-radius:10px; border:1px solid #4ec9b0; min-width:180px; }
.rank-icon { font-size:56px; line-height:1; }
.rank-title { color:#4ec9b0; font-size:20px; font-weight:bold; margin-top:10px; letter-spacing:1px; }
.meta { color:#888; font-size:14px; margin-bottom:25px; padding:10px; background:#2d2d2d; border-radius:6px; }
.summary { margin-bottom:25px; }
.summary-title { color:#4ec9b0; font-size:16px; margin-bottom:12px; text-transform:uppercase; letter-spacing:1px; }
.summary-grid { display:grid; grid-template-columns:repeat(3, 1fr); gap:12px; }
.summary-card { background:#2d2d2d; padding:16px 20px; border-radius:10px; border-left:4px solid #4ec9b0; display:flex; flex-direction:column; gap:6px; }
.summary-card.summary-total { border-left-color:#f14c4c; background:linear-gradient(135deg, #2d2d2d 0%, #3a2626 100%); }
.summary-label { font-size:13px; color:#888; text-transform:uppercase; letter-spacing:1px; }
.summary-value { font-size:32px; font-weight:bold; color:#4ec9b0; line-height:1; }
.summary-card.summary-total .summary-value { color:#f14c4c; }
.summary-value span { font-size:14px; color:#666; font-weight:normal; }
.achievements-section { margin-bottom:25px; }
.achievements-title { color:#4ec9b0; font-size:16px; margin-bottom:12px; text-transform:uppercase; letter-spacing:1px; }
.achievements-grid { display:grid; grid-template-columns:repeat(auto-fill,minmax(220px,1fr)); gap:12px; }
.achievement { background:#2d2d2d; padding:12px; border-radius:8px; display:flex; gap:12px; align-items:center; border-left:3px solid #4ec9b0; }
.ach-desc { color:#aaa; font-size:13px; }
.chapter { margin-top:20px; border:1px solid #333; border-radius:8px; overflow:hidden; }
.chapter-header { background:#2d2d2d; padding:15px 20px; }
.chapter-header h2 { font-size:18px; color:#4ec9b0; }
.badge { background:#f14c4c; color:white; padding:2px 12px; border-radius:12px; font-size:12px; margin-left:10px; }
.badge.success { background:#4ec9b0; }
.badge.score { background:#0e639c; }
.chapter-body { padding:20px; }
.chapter-body pre { background:#1e1e1e; padding:20px; border-radius:6px; white-space:pre-wrap; font-size:13px; border:1px solid #333; max-height:600px; overflow-y:auto; }
.no-errors { color:#4ec9b0; text-align:center; padding:20px; font-size:16px; }
.footer { margin-top:30px; text-align:center; color:#555; font-size:12px; border-top:1px solid #333; padding-top:20px; }
/* Профиль (таб 2) */
.profile-msg { padding:40px; color:#888; text-align:center; font-size:14px; }
.profile-msg.error { color:#f14c4c; }
.profile-totals { color:#888; font-size:14px; margin-bottom:20px; padding:12px 16px; background:#2d2d2d; border-radius:6px; }
.profile-totals b { color:#d4d4d4; font-size:16px; }
.profile-grid { display:grid; grid-template-columns:repeat(auto-fill,minmax(340px,1fr)); gap:16px; margin-bottom:25px; }
.profile-card { background:#2d2d2d; border-radius:10px; padding:18px; border-left:4px solid #4ec9b0; }
.profile-card h3 { color:#4ec9b0; font-size:15px; margin-bottom:10px; }
.profile-rank { font-size:28px; display:flex; align-items:center; gap:10px; margin:6px 0; }
.profile-rank .title { font-size:13px; color:#4ec9b0; font-weight:bold; letter-spacing:1px; }
.profile-stats { display:flex; gap:18px; font-size:12px; color:#888; margin-top:6px; }
.profile-stats b { color:#d4d4d4; font-size:14px; }
.profile-bar { background:#1e1e1e; height:8px; border-radius:4px; overflow:hidden; margin-top:12px; position:relative; }
.profile-bar-fill { height:100%; min-width:4px; border-radius:4px; }
.profile-bar-text { font-size:11px; color:#666; margin-top:4px; text-align:right; }
.profile-ach { margin-top:12px; font-size:12px; color:#aaa; }
.profile-ach div { padding:4px 0; border-top:1px solid #333; }
.profile-ach div:first-child { border-top:none; }
.profile-empty { color:#555; font-style:italic; padding:6px 0; }
.profile-chart { background:#2d2d2d; border-radius:10px; padding:18px; margin-bottom:25px; }
.profile-chart h2 { color:#4ec9b0; font-size:13px; margin-bottom:14px; text-transform:uppercase; letter-spacing:1px; }
.profile-bars { display:flex; align-items:flex-end; gap:4px; height:110px; }
.profile-bar-item { flex:1; background:linear-gradient(180deg,#4ec9b0,#2d7a68); border-radius:3px 3px 0 0; min-height:2px; position:relative; cursor:help; }
.profile-bar-item:hover::after { content:attr(data-label); position:absolute; bottom:100%; left:50%; transform:translateX(-50%); background:#000; color:#4ec9b0; padding:2px 8px; border-radius:4px; font-size:11px; white-space:nowrap; z-index:10; }
.profile-commits { background:#2d2d2d; border-radius:10px; padding:18px; }
.profile-commits h2 { color:#4ec9b0; font-size:13px; margin-bottom:14px; text-transform:uppercase; letter-spacing:1px; }
.profile-commit-row { display:grid; grid-template-columns:150px 80px 1fr 60px; gap:10px; padding:6px 0; border-top:1px solid #333; font-size:12px; align-items:center; }
.profile-commit-row:first-child { border-top:none; }
.profile-commit-row .proj { color:#4ec9b0; font-weight:bold; }
.profile-commit-row .delta { text-align:right; color:#e5c07b; }
.profile-commit-row .delta.neg { color:#f14c4c; }
.profile-commit-row .msg { color:#ccc; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
</style></head><body>
<div class="container">
<h1>📋 Результаты проверки кода</h1>
<div class="tabs">
<button class="tab-btn active" data-tab="report">📋 Проверка</button>
<button class="tab-btn" data-tab="profile">👤 Профиль в сервисе</button>
</div>
<div class="tab-content active" id="tab-report">
<div class="user-card">
<div class="user-info">
<div class="user-name">$GIT_LOGIN</div>
<div class="user-stats">
<div class="user-stat">XP: <b>$XP</b></div>
<div class="user-stat">Уровень: <b>$LEVEL</b></div>
<div class="user-stat">Коммитов: <b>$COMMIT_COUNT</b></div>
<div class="user-stat">Δ: <b>$DELTA_XP</b></div>
</div>
<div class="level-bar"><div class="level-fill" style="width:$PERCENT%"></div></div>
<div class="level-text">$CURRENT_XP / $NEED_XP XP · $PERCENT%</div>
</div>
<div class="user-rank">
<div class="rank-icon">$RANK_ICON</div>
<div class="rank-title">$RANK_TITLE</div>
</div>
</div>
<div class="meta">📅 $DATETIME &nbsp;|&nbsp; 📝 $commit_msg &nbsp;|&nbsp; 🏗️ $PROJECT_SLUG</div>
<div class="summary">
<div class="summary-title">📊 Сводка оценок</div>
<div class="summary-grid">
<div class="summary-card">
<div class="summary-label">🟨 FRONT (JS/TS)</div>
<div class="summary-value">${FRONT_SCORE:-N/A}<span>/10</span></div>
</div>
<div class="summary-card">
<div class="summary-label">🐍 BACK (Python)</div>
<div class="summary-value">${BACK_SCORE:-N/A}<span>/10</span></div>
</div>
<div class="summary-card summary-total">
<div class="summary-label">🏆 TOTAL</div>
<div class="summary-value">${TOTAL_SCORE:-N/A}<span>/10</span></div>
</div>
</div>
</div>
EOF
if [ -n "$NEW_ACHIEVEMENTS" ]; then
cat >> "$HTML_FILE" << EOF
<div class="achievements-section">
<div class="achievements-title">🏅 Новые достижения</div>
<div class="achievements-grid">
<div class="achievement"><div class="ach-desc">$NEW_ACHIEVEMENTS</div></div>
</div>
</div>
EOF
fi
add_chapter() {
local TITLE="$1" OUTPUT="$2" HAS_ERRORS="$3" ICON="$4" SCORE="$5"
local BADGE_CLASS="" STATUS_TEXT="❌ Есть ошибки"
[ "$HAS_ERRORS" -eq 0 ] && { BADGE_CLASS="success"; STATUS_TEXT="✅ Ошибок нет"; }
local SCORE_HTML=""
[ -n "$SCORE" ] && [ "$SCORE" != "0" ] && SCORE_HTML=" <span class='badge score'>Оценка: $SCORE/10</span>"
local ESCAPED=$(echo "$OUTPUT" | sed 's/&/\&amp;/g; s/</\&lt;/g; s/>/\&gt;/g')
cat >> "$HTML_FILE" << EOF
<div class="chapter">
<div class="chapter-header"><h2>$ICON $TITLE <span class="badge $BADGE_CLASS">$STATUS_TEXT</span>$SCORE_HTML</h2></div>
<div class="chapter-body">
EOF
if [ "$HAS_ERRORS" -eq 0 ]; then
echo '<div class="no-errors">Все проверки пройдены успешно</div>' >> "$HTML_FILE"
else
echo "<pre>$ESCAPED</pre>" >> "$HTML_FILE"
fi
echo '</div></div>' >> "$HTML_FILE"
}
[ "$HAS_JS" -eq 1 ] && add_chapter "JavaScript / Vue / TypeScript" "$JS_OUTPUT" "$JS_STATUS" "🟨" "$XP_JS"
[ "$HAS_PYLINT" -eq 1 ] && add_chapter "Pylint" "$PYLINT_OUTPUT" "$PYLINT_STATUS" "🐍" "$PYLINT_SCORE"
[ "$HAS_MYPY" -eq 1 ] && add_chapter "Mypy (types)" "$MYPY_OUTPUT" "$MYPY_STATUS" "🔎" "$MYPY_SCORE"
cat >> "$HTML_FILE" << EOF
<div class="footer">Сгенерировано commit-msg хуком • $GIT_LOGIN</div>
</div> <!-- /tab-report -->
<div class="tab-content" id="tab-profile">
<div class="profile-msg" id="profile-status">Нажми вкладку, чтобы загрузить…</div>
<div id="profile-body" style="display:none"></div>
</div>
</div> <!-- /container -->
<script>
(function() {
var ACHIEVEMENTS_SERVICE = "$ACHIEVEMENTS_SERVICE";
var LOGIN = "$GIT_LOGIN";
var profileLoaded = false;
function esc(s) {
return String(s == null ? '' : s).replace(/[&<>"']/g, function(c) {
return ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'})[c];
});
}
function colorFor(p) {
if (p < 30) return '#f14c4c';
if (p < 70) return '#e5c07b';
return '#4ec9b0';
}
function renderProfile(data) {
var status = document.getElementById('profile-status');
var body = document.getElementById('profile-body');
var maxXP = Math.max(1, ...data.daily_xp.map(function(d){ return d.xp; }));
var projectsHTML = data.projects.map(function(p) {
var ach = p.recent_achievements.length
? p.recent_achievements.map(function(a) {
return '<div>' + a.icon + ' ' + esc(a.title) + '</div>';
}).join('')
: '<div class="profile-empty">пока нет достижений</div>';
return ''
+ '<div class="profile-card">'
+ '<h3>🏗️ ' + esc(p.project_slug) + '</h3>'
+ '<div class="profile-rank">'
+ '<span>' + p.rank_icon + '</span>'
+ '<span class="title">' + esc(p.rank_title) + '</span>'
+ '</div>'
+ '<div class="profile-stats">'
+ '<div>Уровень: <b>' + p.level + '</b></div>'
+ '<div>Коммитов: <b>' + p.commit_count + '</b></div>'
+ '<div>Ачивок: <b>' + p.achievements_count + '</b></div>'
+ '</div>'
+ '<div class="profile-bar">'
+ '<div class="profile-bar-fill" style="width:' + p.percent + '%;background:' + colorFor(p.percent) + ';"></div>'
+ '</div>'
+ '<div class="profile-bar-text">' + p.current_xp + ' / ' + p.need_xp + ' XP · ' + p.percent + '%</div>'
+ '<div class="profile-ach">' + ach + '</div>'
+ '</div>';
}).join('');
var chartHTML = data.daily_xp.length
? '<div class="profile-bars">' + data.daily_xp.map(function(d) {
var h = Math.max(2, (d.xp / maxXP) * 110);
return '<div class="profile-bar-item" style="height:' + h + 'px" data-label="' + d.date + ': ' + d.xp + ' XP"></div>';
}).join('') + '</div>'
: '<div class="profile-empty">нет данных за последние 30 дней</div>';
var commitsHTML = data.recent_commits.length
? data.recent_commits.map(function(c) {
var deltaCls = c.xp_delta < 0 ? 'delta neg' : 'delta';
var deltaTxt = 'Δ ' + (c.xp_delta > 0 ? '+' : '') + c.xp_delta;
var dt = (c.created_at || '').replace('T', ' ').slice(0, 16);
return ''
+ '<div class="profile-commit-row">'
+ '<span>' + esc(dt) + '</span>'
+ '<span class="proj">' + esc(c.project_slug || '—') + '</span>'
+ '<span class="msg" title="' + esc(c.commit_msg) + '">' + esc(c.commit_msg || '') + '</span>'
+ '<span class="' + deltaCls + '">' + deltaTxt + '</span>'
+ '</div>';
}).join('')
: '<div class="profile-empty">нет коммитов</div>';
body.innerHTML = ''
+ '<div class="profile-totals">'
+ 'Всего XP: <b>' + data.total_xp + '</b> · '
+ 'Коммитов: <b>' + data.total_commits + '</b> · '
+ 'Проектов: <b>' + data.projects_count + '</b>'
+ '</div>'
+ '<div class="profile-grid">' + projectsHTML + '</div>'
+ '<div class="profile-chart"><h2>📈 XP за 30 дней</h2>' + chartHTML + '</div>'
+ '<div class="profile-commits"><h2>📜 Последние коммиты</h2>' + commitsHTML + '</div>';
status.style.display = 'none';
body.style.display = 'block';
}
var PROFILE_DATA = $PROFILE_JSON_ESCAPED;
var profileLoaded = false;
function loadProfile() {
if (profileLoaded) return;
var status = document.getElementById('profile-status');
if (!PROFILE_DATA || PROFILE_DATA === null) {
status.textContent = 'Профиль недоступен (сервис не ответил).';
status.className = 'profile-msg error';
return;
}
try {
profileLoaded = true;
renderProfile(PROFILE_DATA);
} catch (e) {
status.textContent = 'Ошибка отображения: ' + e;
status.className = 'profile-msg error';
}
}
document.querySelectorAll('.tab-btn').forEach(function(btn) {
btn.addEventListener('click', function() {
var tab = btn.dataset.tab;
document.querySelectorAll('.tab-btn').forEach(function(b) {
b.classList.toggle('active', b === btn);
});
document.querySelectorAll('.tab-content').forEach(function(c) {
c.classList.toggle('active', c.id === 'tab-' + tab);
});
if (tab === 'profile') loadProfile();
});
});
})();
</script>
</body></html>
EOF
if [ "$HAS_ANY_ERRORS" -eq 1 ]; then
notify-send -u normal -i dialog-warning "Проверка кода" \
"Найдены ошибки. Открой отчёт." 2>/dev/null || true
(xdg-open "$HTML_FILE" >/dev/null 2>&1 || flatpak-spawn --host xdg-open "$HTML_FILE" >/dev/null 2>&1) &
else
rm -f "$HTML_FILE"
fi
fi
# ============================================
# БЛОКИРОВКА — ТОЛЬКО ОФОРМЛЕНИЕ
# ============================================
if [ "$MSG_OK" -eq 0 ]; then
cat <<EOF
... --- ... Ошибка ... --- ...
$commit_msg
Сообщение коммита не соответствует шаблону.
Формат: <тип> [<номер задачи>]: <название>
Пример: feat [P-01]: я тут накоммитил
Тип Описание Рыба
--------- -------------------- ------------------------------
feat Новый функционал feat [P-]:
fix Исправление ошибки fix [P-]:
docs Документация docs [P-]:
style Форматирование style [P-]:
refactor Рефакторинг refactor [P-]:
perf Производительность perf [P-]:
test Тесты test [P-]:
chore Сборка, сервер chore [P-]:
EOF
exit 1
fi
exit 0
+167
View File
@@ -0,0 +1,167 @@
#!/usr/bin/env sh
LC_ALL=C
export LC_ALL
LANG=C
export LANG
# ============================================
# ЗАПУСК ЛИНТЕРОВ И СОХРАНЕНИЕ РЕЗУЛЬТАТОВ
# ============================================
REPO_ROOT=$(git rev-parse --show-toplevel)
RESULTS_DIR="$REPO_ROOT/.git/linter-results"
mkdir -p "$RESULTS_DIR"
# Сбрасываем старые результаты
rm -f "$RESULTS_DIR"/*.out "$RESULTS_DIR"/*.status "$RESULTS_DIR"/*.files \
"$RESULTS_DIR"/*.errors "$RESULTS_DIR"/*.score "$RESULTS_DIR"/*.lines
USER_ID=$(id -u)
GROUP_ID=$(id -g)
# ============================================
# JS / VUE / TS
# ============================================
filesjs=$(git diff --cached --name-only --diff-filter=ACM | grep '^src/front/' | grep -E '\.vue$|\.js$|\.ts$')
if [ -n "$filesjs" ]; then
filesjs_modified=$(echo "$filesjs" | sed 's|^src/front/||' | tr '\n' ' ')
if [ "$(docker compose -f docker-compose.yml ps -q frontend 2>/dev/null)" ]; then
JS_RAW=$(docker compose -f docker-compose.yml exec -T --user "$USER_ID:$GROUP_ID" frontend sh -c \
"npm run formatter -- $filesjs_modified && npm run linter -- $filesjs_modified; echo __EXIT__:\$?" 2>&1)
else
JS_RAW=$(docker compose -f docker-compose.yml -f docker/composes/docker-compose.dev.yml run --rm --user "$USER_ID:$GROUP_ID" --entrypoint sh frontend -c \
"npm run formatter -- $filesjs_modified && npm run linter -- $filesjs_modified; echo __EXIT__:\$?" 2>&1)
fi
LINTER_STATUS_JS=$(echo "$JS_RAW" | grep -oE '__EXIT__:[0-9]+' | grep -oE '[0-9]+' | tail -1)
LINTER_STATUS_JS=${LINTER_STATUS_JS:-0}
LINTER_OUTPUT_JS=$(echo "$JS_RAW" | sed 's/__EXIT__:[0-9]*$//')
echo "$LINTER_OUTPUT_JS" > "$RESULTS_DIR/js.out"
echo "$LINTER_STATUS_JS" > "$RESULTS_DIR/js.status"
echo "$filesjs" | grep -c . > "$RESULTS_DIR/js.files"
# Возвращаем отформатированные файлы в индекс
echo "$filesjs" | while read -r file; do
[ -f "$file" ] && git add "$file"
done
fi
# ============================================
# PYTHON
# ============================================
pyfiles=$(git diff --cached --name-only --diff-filter=ACM | grep '^src/back/' | grep '\.py$')
if [ -n "$pyfiles" ]; then
pyfiles_mod=$(echo "$pyfiles" | sed 's|^src/back/||' | tr '\n' ' ')
if [ -z "$(echo "$pyfiles_mod" | tr -d ' ')" ]; then
# Все файлы — тесты, линтеры не запускаем
: > "$RESULTS_DIR/fmt.out"; echo 0 > "$RESULTS_DIR/fmt.status"
: > "$RESULTS_DIR/pylint.out"; echo 0 > "$RESULTS_DIR/pylint.status"
echo 0 > "$RESULTS_DIR/pylint.score"
: > "$RESULTS_DIR/mypy.out"; echo 0 > "$RESULTS_DIR/mypy.status"
echo 0 > "$RESULTS_DIR/mypy.errors"
echo 0 > "$RESULTS_DIR/mypy.lines"
echo 0 > "$RESULTS_DIR/mypy.score"
: > "$RESULTS_DIR/py.out"; echo 0 > "$RESULTS_DIR/py.status"
echo 0 > "$RESULTS_DIR/py.files"
else
BACKEND_RUNNING=0
[ "$(docker compose -f docker-compose.yml ps -q backend 2>/dev/null)" ] && BACKEND_RUNNING=1
run_backend() {
local cmd="$1"
if [ "$BACKEND_RUNNING" -eq 1 ]; then
docker compose -f docker-compose.yml exec -T --user "$USER_ID:$GROUP_ID" backend \
sh -c "$cmd; echo __EXIT__:\$?" 2>&1
else
docker compose -f docker-compose.yml run --rm --user "$USER_ID:$GROUP_ID" \
--entrypoint sh backend -c "$cmd; echo __EXIT__:\$?" 2>&1
fi
}
# --- isort + black ---
fmt_raw=$(run_backend "poetry run ruff check $pyfiles_mod --fix; poetry run ruff format $pyfiles_mod")
fmt_status=$(echo "$fmt_raw" | grep -oE '__EXIT__:[0-9]+' | grep -oE '[0-9]+' | tail -1)
fmt_status=${fmt_status:-0}
fmt_out=$(echo "$fmt_raw" | sed 's/__EXIT__:[0-9]*$//')
echo "$fmt_out" > "$RESULTS_DIR/fmt.out"
echo "$fmt_status" > "$RESULTS_DIR/fmt.status"
# --- pylint ---
pylint_raw=$(run_backend "PYLINTHOME=/tmp poetry run pylint $pyfiles_mod")
pylint_status=$(echo "$pylint_raw" | grep -oE '__EXIT__:[0-9]+' | grep -oE '[0-9]+' | tail -1)
pylint_status=${pylint_status:-0}
pylint_out=$(echo "$pylint_raw" | sed 's/__EXIT__:[0-9]*$//')
echo "$pylint_out" > "$RESULTS_DIR/pylint.out"
echo "$pylint_status" > "$RESULTS_DIR/pylint.status"
# --- оценка pylint (пробуем достать из вывода, иначе 0) ---
PYLINT_SCORE=$(echo "$pylint_out" | grep -oE 'rated at [0-9]+\.[0-9]+' \
| grep -oE '[0-9]+\.[0-9]+' | tail -1)
PYLINT_SCORE=$(echo "$PYLINT_SCORE" | tr -cd '0-9.')
case "$PYLINT_SCORE" in
*.*.*) PYLINT_SCORE=0 ;;
esac
PYLINT_SCORE=${PYLINT_SCORE:-0}
echo "$PYLINT_SCORE" > "$RESULTS_DIR/pylint.score"
# --- mypy ---
mypy_raw=$(run_backend "poetry run mypy --cache-dir /dev/null --show-traceback $pyfiles_mod")
mypy_status=$(echo "$mypy_raw" | grep -oE '__EXIT__:[0-9]+' | grep -oE '[0-9]+' | tail -1)
mypy_status=${mypy_status:-0}
mypy_out=$(echo "$mypy_raw" | sed 's/__EXIT__:[0-9]*$//')
echo "$mypy_out" > "$RESULTS_DIR/mypy.out"
echo "$mypy_status" > "$RESULTS_DIR/mypy.status"
# --- метрики mypy: errors / lines ---
MYPY_ERRORS=$(echo "$mypy_out" | grep -oE 'Found [0-9]+ error' | grep -oE '[0-9]+' | tail -1)
MYPY_ERRORS=${MYPY_ERRORS:-0}
if echo "$mypy_out" | grep -q 'Success: no issues found'; then
MYPY_ERRORS=0
fi
# Считаем суммарное количество строк в проверяемых файлах
MYPY_LINES=0
for f in $pyfiles; do
if [ -f "$REPO_ROOT/$f" ]; then
L=$(wc -l < "$REPO_ROOT/$f" | tr -cd '0-9')
MYPY_LINES=$((MYPY_LINES + L))
fi
done
[ "$MYPY_LINES" -lt 1 ] && MYPY_LINES=1
# Оценка mypy 0..10: 10 - 10 * errors / lines
MYPY_SCORE=$(awk -v err="$MYPY_ERRORS" -v lines="$MYPY_LINES" 'BEGIN {
if (lines < 1) lines = 1
s = 10.0 - (10.0 * err / lines)
if (s < 0) s = 0
if (s > 10) s = 10
printf "%.2f", s
}')
echo "$MYPY_ERRORS" > "$RESULTS_DIR/mypy.errors"
echo "$MYPY_LINES" > "$RESULTS_DIR/mypy.lines"
echo "$MYPY_SCORE" > "$RESULTS_DIR/mypy.score"
# Итоговый статус Python: любой ненулевой → ошибка
PY_TOTAL_STATUS=0
[ "$fmt_status" -ne 0 ] && PY_TOTAL_STATUS=1
[ "$pylint_status" -ne 0 ] && PY_TOTAL_STATUS=1
[ "$mypy_status" -ne 0 ] && PY_TOTAL_STATUS=1
# Склейка для совместимости / общей сводки
cat "$RESULTS_DIR/fmt.out" "$RESULTS_DIR/pylint.out" "$RESULTS_DIR/mypy.out" > "$RESULTS_DIR/py.out"
echo "$PY_TOTAL_STATUS" > "$RESULTS_DIR/py.status"
echo "$pyfiles" | grep -c . > "$RESULTS_DIR/py.files"
# Возвращаем отформатированные файлы в индекс
echo "$pyfiles" | while read -r file; do
[ -f "$file" ] && git add "$file"
done
fi
fi
exit 0
-48
View File
@@ -1,48 +0,0 @@
#!/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
Generated Executable
+10
View File
@@ -0,0 +1,10 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Ignored default folder with query files
/queries/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
Generated Executable
+8
View File
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
Generated Executable
+59
View File
@@ -0,0 +1,59 @@
<component name="ProjectCodeStyleConfiguration">
<code_scheme name="Project" version="173">
<HTMLCodeStyleSettings>
<option name="HTML_SPACE_INSIDE_EMPTY_TAG" value="true" />
</HTMLCodeStyleSettings>
<JSCodeStyleSettings version="0">
<option name="FORCE_SEMICOLON_STYLE" value="true" />
<option name="SPACE_BEFORE_FUNCTION_LEFT_PARENTH" value="false" />
<option name="USE_DOUBLE_QUOTES" value="false" />
<option name="FORCE_QUOTE_STYlE" value="true" />
<option name="ENFORCE_TRAILING_COMMA" value="WhenMultiline" />
<option name="SPACES_WITHIN_OBJECT_LITERAL_BRACES" value="true" />
<option name="SPACES_WITHIN_IMPORTS" value="true" />
</JSCodeStyleSettings>
<TypeScriptCodeStyleSettings version="0">
<option name="FORCE_SEMICOLON_STYLE" value="true" />
<option name="SPACE_BEFORE_FUNCTION_LEFT_PARENTH" value="false" />
<option name="USE_DOUBLE_QUOTES" value="false" />
<option name="FORCE_QUOTE_STYlE" value="true" />
<option name="ENFORCE_TRAILING_COMMA" value="WhenMultiline" />
<option name="SPACES_WITHIN_OBJECT_LITERAL_BRACES" value="true" />
<option name="SPACES_WITHIN_IMPORTS" value="true" />
</TypeScriptCodeStyleSettings>
<VueCodeStyleSettings>
<option name="INTERPOLATION_NEW_LINE_AFTER_START_DELIMITER" value="false" />
<option name="INTERPOLATION_NEW_LINE_BEFORE_END_DELIMITER" value="false" />
</VueCodeStyleSettings>
<codeStyleSettings language="HTML">
<option name="SOFT_MARGINS" value="100" />
<indentOptions>
<option name="INDENT_SIZE" value="2" />
<option name="CONTINUATION_INDENT_SIZE" value="2" />
<option name="TAB_SIZE" value="2" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="JavaScript">
<option name="SOFT_MARGINS" value="100" />
<indentOptions>
<option name="INDENT_SIZE" value="2" />
<option name="CONTINUATION_INDENT_SIZE" value="2" />
<option name="TAB_SIZE" value="2" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="TypeScript">
<option name="SOFT_MARGINS" value="100" />
<indentOptions>
<option name="INDENT_SIZE" value="2" />
<option name="CONTINUATION_INDENT_SIZE" value="2" />
<option name="TAB_SIZE" value="2" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="Vue">
<option name="SOFT_MARGINS" value="100" />
<indentOptions>
<option name="CONTINUATION_INDENT_SIZE" value="2" />
</indentOptions>
</codeStyleSettings>
</code_scheme>
</component>
+5
View File
@@ -0,0 +1,5 @@
<component name="ProjectCodeStyleConfiguration">
<state>
<option name="USE_PER_PROJECT_SETTINGS" value="true" />
</state>
</component>
+6
View File
@@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="Eslint" enabled="true" level="WARNING" enabled_by_default="true" />
</profile>
</component>
Generated Executable
+8
View File
@@ -0,0 +1,8 @@
<?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 Executable
+7
View File
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
+2 -1
View File
@@ -94,7 +94,8 @@ class Event(models.Model):
return str(self.name) return str(self.name)
class EventFiles(models.Model): class EventFiles(models.Model):
event = models.ForeignKey(Event, on_delete=models.PROTECT, related_name='get_calendar_event_files',blank=True,null=True, verbose_name='Событие') # event = models.ForeignKey(Event, on_delete=models.PROTECT, related_name='get_calendar_event_files',blank=True,null=True, verbose_name='Событие')
event = models.ForeignKey(Event, on_delete=models.CASCADE, related_name='get_calendar_event_files',blank=True,null=True, verbose_name='Событие')
file = models.FileField(upload_to='calendar/%Y/%m/%d') file = models.FileField(upload_to='calendar/%Y/%m/%d')
class Meta: class Meta:
+4 -3
View File
@@ -20,11 +20,10 @@ class ExclusionDatesAPIView(APIView):
year = self.request.query_params.get('year', datetime.now().year) year = self.request.query_params.get('year', datetime.now().year)
exclude = ExclusionDates.objects.filter(exclusiondate__year=year) exclude = ExclusionDates.objects.filter(exclusiondate__year=year)
months = {} months = {}
for i in range(1,12): for i in range(1,13):
months[i] = exclude.filter(exclusiondate__month=i).values_list("exclusiondate", flat=True) months[i] = exclude.filter(exclusiondate__month=i).values_list("exclusiondate", flat=True)
return Response({year:months}) return Response({year:months})
class MyCalendars(APIView): class MyCalendars(APIView):
def get(self, request): def get(self, request):
@@ -104,7 +103,9 @@ class MyEvents(APIView):
resp = {'mycalendars':CalendarsSerializerForEventEdit(allcalendars, many=True).data } resp = {'mycalendars':CalendarsSerializerForEventEdit(allcalendars, many=True).data }
if request.query_params.get("id") is not None: if request.query_params.get("id") is not None:
event = Event.objects.get(id = request.query_params.get("id")) event = Event.objects.get(id = request.query_params.get("id"))
resp['event']=EventSerializerIdRequest(event).data resp['event']=EventSerializerIdRequest(event).data
# events = Event.objects.filter(calendar__id = request.query_params.get("id"))
# resp['events'] = EventSerializerIdRequest(events, many=True).data
return Response(resp) return Response(resp)
@@ -1,31 +0,0 @@
# Generated by Django 5.2.4 on 2025-07-18 09:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("commeteresp", "0001_initial"),
]
operations = [
migrations.CreateModel(
name="OrderResponsibilityEmployee",
fields=[
(
"id",
models.PositiveIntegerField(
db_comment="╥рсхы№э√щ эюьхЁ", primary_key=True, serialize=False
),
),
],
options={
"verbose_name": "Ответственный сотрудник",
"verbose_name_plural": "Ответственные сотрудники",
"db_table": "order_responsibility_employee",
"managed": False,
},
),
]
+6 -8
View File
@@ -177,15 +177,13 @@ def default_date():
return date.today().replace(year=1992) return date.today().replace(year=1992)
class Screensaver(models.Model): class Screensaver(models.Model):
img = models.ImageField(upload_to='screengallery/%Y/%m/%d', null=True, verbose_name='Изображение') img = models.ImageField(upload_to='screengallery/%Y/%m/%d', null=True, verbose_name='Изображение')
cdate =models.DateField(default=default_date, null=True, verbose_name='Дата начала периода') cdate = models.DateField(default=default_date, null=True, verbose_name='Дата начала периода')
enddate = models.DateField(default= default_date, verbose_name='Дата окончания периода', null=True) enddate = models.DateField(default=default_date, null=True, verbose_name='Дата окончания периода')
class Meta:
class Meta:
verbose_name = "Вход. Изображение" verbose_name = "Вход. Изображение"
verbose_name_plural = "Вход. Изображения" verbose_name_plural = "Вход. Изображения"
def __str__(self): def __str__(self):
return str(self.img) return str(self.img)
-1
View File
@@ -70,5 +70,4 @@ urlpatterns = [
path('api/safety/', include('safety.urls')), path('api/safety/', include('safety.urls')),
path('api/tests/', include('tests.urls')), path('api/tests/', include('tests.urls')),
path('api/vote/', include('vote.urls')), path('api/vote/', include('vote.urls')),
path('api/userauth/', include('userauth.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
+1 -12
View File
@@ -132,17 +132,6 @@ class InfoUserCardSerializer(serializers.ModelSerializer):
""" Собирает необходимую информацию о пользователе, содержит необходимые """ Собирает необходимую информацию о пользователе, содержит необходимые
поля для отрисовки карточки информации о пользователе при клике на фамилию поля для отрисовки карточки информации о пользователе при клике на фамилию
Необходим для компонента infoUserCard""" Необходим для компонента infoUserCard"""
position = serializers.IntegerField(source='id_dict_position.order_position')
department = serializers.CharField(source='id_dict_department.name')
class Meta: class Meta:
model = DictEmployee model = DictEmployee
fields = ['department', 'fio', 'post', 'email', 'tel', 'room', 'login', 'familyname', 'name', 'parentname', 'id', 'deleted','position'] fields = ['department', 'fio', 'post', 'email', 'tel', 'room', 'login', 'familyname', 'name', 'parentname', 'id']
class DepartmentsSerializer(serializers.ModelSerializer):
persons = InfoUserCardSerializer(source='dep_user', many=True)
class Meta:
model = DictDepartment
fields = ['id','name','persons']
-6
View File
@@ -1,6 +0,0 @@
from django.urls import path
from .views import *
urlpatterns = [
path('getdepartments', GetDepartment.as_view(), name= "GetDepartment")
]
+1 -14
View File
@@ -1,16 +1,3 @@
from django.shortcuts import render from django.shortcuts import render
from .models import DictDepartment
from .serializers import DepartmentsSerializer
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.views import APIView
from rest_framework.response import Response
class GetDepartment(APIView): # Create your views here.
permission_classes = (AllowAny,)
"""
Получаем отделы
"""
def get(self,request):
department = DictDepartment.objects.all()
return Response(DepartmentsSerializer(department, many=True).data)
+18432
View File
File diff suppressed because it is too large. Load diff
+10 -2
View File
@@ -1,6 +1,6 @@
{ {
"name": "front", "name": "front",
"version": "1.2.2", "version": "1.3.2",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
@@ -36,7 +36,15 @@
"vue3-autocounter": "^1.0.8", "vue3-autocounter": "^1.0.8",
"vuelidate": "^0.7.7", "vuelidate": "^0.7.7",
"vuetify": "^3.7.8", "vuetify": "^3.7.8",
"webfontloader": "^1.6.28" "webfontloader": "^1.6.28",
"@fullcalendar/core": "^6.1.19",
"@fullcalendar/daygrid": "^6.1.19",
"@fullcalendar/interaction": "^6.1.19",
"@fullcalendar/multimonth": "^6.1.19",
"@fullcalendar/timegrid": "^6.1.19",
"@fullcalendar/list": "6.1.19",
"@fullcalendar/vue3": "^6.1.19",
"@fullcalendar/rrule": "^6.1.15"
}, },
"devDependencies": { "devDependencies": {
"@commitlint/cli": "^19.7.1", "@commitlint/cli": "^19.7.1",
@@ -1,43 +0,0 @@
<template>
<div v-for="(sort, depart) in grouped" class="mt-2">
<h2 class="text-teal">{{ depart }}</h2>
<v-divider :thickness="4" color="teal"/>
<v-row class="mt-1">
<v-col v-for="person in sort.sort((a,b)=>a.position-b.position)" cols="4" :key="person.id" class="cursor-pointer">
<CardDictEmployee :person="person" v-model:moreInformation="moreInformation"/>
</v-col>
</v-row>
</div>
<v-dialog v-model="moreInformation" transition="dialog-top-transition">
<DialogEmployeeDirection />
</v-dialog>
</template>
<script setup>
import DialogEmployeeDirection from "./DialogEmployeeDirection.vue";
import CardDictEmployee from "../UI/DictEmployee/CardDictEmployee.vue";
import { ref, computed } from 'vue'
const props = defineProps({
selectedDep: {
name: String,
},
isWork: Number,
search: String,
})
const moreInformation = ref(false)
const filteredPerson = computed(() => {
return props.selectedDep.persons.filter(item => item.deleted == props.isWork && item.fio.toLowerCase().includes(props.search.toLowerCase()))
})
const grouped = computed(() => {
let group = []
group = Object.groupBy(filteredPerson.value, (item) => item.department)
return group
})
</script>
@@ -1,39 +0,0 @@
<template>
<v-card>
<v-row class="bg-red">
<v-col class="bg-blue">
Общие данные
<!-- <CardDictEmployee /> -->
</v-col>
<v-col class="bg-purple">Участия в комиссиях</v-col>
</v-row>
<v-row class="bg-green">
<v-col class="bg-orange">Сферы ответственности</v-col>
</v-row>
</v-card>
</template>
<script setup>
import CardDictEmployee from '../UI/DictEmployee/CardDictEmployee.vue';
import { axiosApiInstance } from '@/utils/axios-api'
import { onMounted } from 'vue'
const props = defineProps({
fullListInfo: {
}
})
async function getFullInfoList() {
try {
const response = await axiosApiInstance.get('api/userauth/getdepartments')
} catch (error) {
console.log('Ошибка получения полной информации из справоника', error);
}
}
onMounted(async () => {
await getFullInfoList();
})
</script>
@@ -1,55 +0,0 @@
<template>
<v-card class="pa-2">
<v-row align="center">
<v-col cols="6">
<v-select
return-object
item-title="name"
:items="props.department"
v-model="selectedDep"
variant="outlined"
density="compact"
hide-details bg-color="grey-lighten-5"
label="Список отделов">
</v-select>
</v-col>
<v-col cols="2">
<v-switch
v-model="isWork"
:false-value="0"
:true-value="1"
color="teal"
label="Уволенные"
hide-details>
</v-switch>
</v-col>
<v-col class="ml-auto" cols="2">
<v-text-field
v-model="search"
append-inner-icon="mdi-magnify"
label="Поиск сотрудников"
variant="outlined"
density="compact"
bg-color="grey-lighten-5"
hide-details
clearable
@click:clear="handleClear"
/>
</v-col>
</v-row>
</v-card>
</template>
<script setup>
const props = defineProps({
department: Array,
})
const selectedDep = defineModel('selectedDep')
const isWork = defineModel('isWork')
const search = defineModel('search')
const handleClear = () => {
search.value = '';
};
</script>
@@ -1,60 +0,0 @@
<template>
<!-- добавить проверку пользователи скрыты или нет (смена текста) от состояния -->
<v-tooltip v-for="itemMenu in navMenu" :text="itemMenu.text" location="bottom">
<template v-slot:activator="{ props }">
<v-btn :icon="itemMenu.icon" v-bind="props" @click="itemMenu.event" :color="itemMenu.color"/>
</template>
</v-tooltip>
<v-dialog v-model="isDialog" width="800">
<card-like :LikeDialog="isDialog" @menusClose="isDialog = false"/>
</v-dialog>
</template>
<script setup>
import router from '@/router';
import { useTheme } from "vuetify";
import { useAccountStore } from '@/store/AccountStore';
import { ref, computed } from 'vue';
import CardLike from '@/components/cardLike.vue'
const userStore = useAccountStore()
const theme = useTheme()
const isDialog = ref(null)
const rightRail = ref(true)
const emit = defineEmits(['showUser'])
const navMenu = computed(() => {
return [
{
text: 'F.A.Q.',
icon: 'mdi-comment-question-outline',
event: () => router.push('/faq'),
},
{
text: 'Обратная связь',
icon: 'mdi-thumb-up-outline',
event: () => isDialog.value = true,
},
{
text: 'Сменить тему',
icon: 'mdi-lightbulb-outline',
color: 'lampa',
event: () => theme.toggle(),
},
{
text: `${rightRail.value == true ? 'Скрыть ' : 'Показать '} пользователей`,
icon: 'mdi-account-multiple-outline',
event: () => {
rightRail.value = !rightRail.value
emit('showUser', rightRail.value)
},
},
{
text: 'Выход',
icon: 'mdi-logout',
event: () => userStore.logout(),
},
]})
</script>
+2 -5
View File
@@ -109,7 +109,6 @@ import {useAppStore} from '@/store/app'
import { useVuelidate } from '@vuelidate/core' import { useVuelidate } from '@vuelidate/core'
import { required, helpers } from '@vuelidate/validators' import { required, helpers } from '@vuelidate/validators'
import { ref, reactive, computed, onMounted } from 'vue' import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router';
const req= helpers.withMessage('Обязательное поле', required) const req= helpers.withMessage('Обязательное поле', required)
@@ -123,7 +122,7 @@ export default {
const err = ref('') const err = ref('')
const alert = ref(false) const alert = ref(false)
const eyeshow = ref(false) const eyeshow = ref(false)
const router = useRouter()
const anon=reactive({ const anon=reactive({
username:"9966-00-", username:"9966-00-",
@@ -159,9 +158,7 @@ export default {
} }
finally {
router.push('/')
}
} }
} }
@@ -1,27 +0,0 @@
<template>
<v-card v-model="moreInformation" @click="moreInformation = true">
<v-avatar :image="checkremote(`${spravURL}.jpg`)" rounded="0" size="100"></v-avatar>
<v-card-item>
<v-card-title>{{ props.person.familyname }} {{ props.person.name }} {{ props.person.parentname }}</v-card-title>
<v-card-title class="text-subtitle-1">{{ props.person.post }}</v-card-title>
<v-card-subtitle>{{ props.person.tel }}</v-card-subtitle>
</v-card-item>
</v-card>
</template>
<script setup>
import { checkremote } from "@/utils/universal_functions";
import { spravURL } from "@/utils/axios-api";
const props = defineProps({
person: {
familyname: String,
name: String,
parentname: String,
tel: String,
post: String,
}
})
const moreInformation = defineModel('moreInformation')
</script>
@@ -1,150 +1,453 @@
<template> <template>
<v-col> <v-col>
<v-file-input <div class="custom-file-input-wrapper">
label="Файлы" <label class="v-label v-field-label v-field-label--floating">
chips Добавить файл (размер файла не должен превышать 2Мб)
multiple </label>
v-model="eventFiles"
density="compact"
variant="outlined"
@click.stop=""
>
<template v-slot:selection="{ fileNames }">
<template v-for="(fileName, index) in fileNames" :key="fileName">
<v-chip
v-if="index < 4"
class="me-2"
color="teal-darken-3"
size="small"
label
>
{{ fileName }}
</v-chip>
<span <!-- Область, куда можно перетащить файлы -->
v-else-if="index === 4" <div
class="text-overline text-grey-darken-3 mx-2" class="file-input-area"
> @click="triggerFileInput"
+{{ files.length - 4 }} файла(ов) @drop="handleDrop"
</span> @dragover.prevent
</template> @dragenter.prevent
</template> >
</v-file-input> <!-- Кастомные чипы новых файлов ВНУТРИ "инпута" -->
<div class="chips-container" v-if="localNewFiles.length > 0">
<template v-for="(file, index) in localNewFiles" :key="getFileKey(file, index)">
<v-chip
class="file-chip"
color="grey-darken-1"
size="small"
label
closable
@click:close="removeNewFile(index)"
>
<v-icon start size="small">mdi-file-plus</v-icon>
<span class="text-truncate" style="max-width: 100px">
{{ file.name }}({{ formatFileSize(file.size) }})
</span>
</v-chip>
</template>
<span class="file-counter text-caption text-grey">
{{ localNewFiles.length }}/{{ MAX_NEW_FILES }}
</span>
</div>
<!-- Плейсхолдер, когда файлов нет -->
<div v-else class="placeholder">
<v-icon class="me-1">mdi-paperclip</v-icon>
<span class="text-caption">Перетащите файлы сюда или кликните для выбора</span>
</div>
<!-- Скрытый настоящий input -->
<input
ref="fileInputRef"
type="file"
multiple
style="display: none"
@change="handleFileSelect"
/>
</div>
<!-- Область ошибок -->
<div class="error-messages" v-if="errorMessages.length">
<div v-for="(error, index) in errorMessages" :key="index" class="text-caption text-error">
{{ error }}
</div>
</div>
</div>
<!-- Существующие файлы из БД -->
<div class="existing-files-section mb-2">
<div class="text-caption text-grey mb-2">Прикрепленные файлы:</div>
<div>
<template v-if="existingFiles.length">
<v-chip
v-for="file in existingFiles"
:key="file.id"
class="me-2 mb-1"
color="teal-darken-3"
label
@click:close="removeExistingFile(file.id)"
>
<v-icon start class="pb-1">{{ getFileIcon(file) }}</v-icon>
<span class="text-truncate" style="max-width: 120px">
{{ truncateFileName(getFileName(file)) }}
</span>
<v-icon
class="ms-1 download-icon"
@click.stop="downloadExistingFile(file)"
title="Скачать файл"
>
mdi-download
</v-icon>
<v-icon
class="ms-1 close-icon"
@click.stop="removeExistingFile(file.id)"
title="Удалить файл"
>
mdi-close
</v-icon>
</v-chip>
</template>
<template v-else>
<span class="text-caption text-grey">Файлов нет</span>
</template>
</div>
</div>
</v-col> </v-col>
</template> </template>
<script> <script>
import { computed, ref } from "vue"; import { computed, ref, watch } from 'vue';
import { get_name } from "@/utils/universal_functions";
export default { export default {
props: { props: {
files: { files: {
type: Object, type: Array,
default: () => {}, default: () => [],
},
newFiles: {
type: Array,
default: [],
}, },
}, },
emits: ['update:files', 'update:newFiles', 'postFiles'],
setup(props, { emit }) { setup(props, { emit }) {
const localNewFiles = ref([]);
const errorMessages = ref([]);
const MAX_FILE_SIZE = 2 * 1024 * 1024; // 2 МБ
const MAX_NEW_FILES = 5;
const propsFiles = computed({ const fileInputRef = ref(null);
get: () => props.files,
set: (value) => emit("update:files", value),
});
const arrFiles = ref([]); watch(
() => props.newFiles,
const eventFiles = computed({ (newVal) => {
get() { localNewFiles.value = Array.isArray(newVal) ? [...newVal] : [];
propsFiles.value.forEach((e) =>
{
arrFiles.value.push(
dataURLtoFile(
"data:text/plain;base64,aGVsbG8gd29ybGQ=",
get_name(decodeURI(e.file))
)
)}
);
return arrFiles.value;
}, },
{ immediate: true },
);
set(newValue) { // Существующие файлы из event.files
let newFile = [] const existingFiles = computed(() => (Array.isArray(props.files) ? props.files : []));
arrFiles.value = [];
if (newValue.length == 0) {
arrFiles.value = [];
propsFiles.value = [];
} else {
newValue.forEach((e) => {
arrFiles.value.push(e)
newFile.push(e)
});
}
emit("postFiles", newFile); const triggerFileInput = () => {
if (fileInputRef.value) {
fileInputRef.value.click();
}, }
}); };
//
function dataURLtoFile(dataurl, filename) { const handleFileSelect = (event) => {
var arr = dataurl.split(","), const files = Array.from(event.target.files || []);
mime = arr[0].match(/:(.*?);/)[1], if (files.length > 0) {
bstr = atob(arr[1]), handleFilesChange(files);
n = bstr.length, }
u8arr = new Uint8Array(n); // Очищаем input для возможности выбора тех же файлов снова
event.target.value = '';
};
while (n--) { // Обработка drag & drop
u8arr[n] = bstr.charCodeAt(n); const handleDrop = (event) => {
event.preventDefault();
const files = Array.from(event.dataTransfer.files || []);
if (files.length > 0) {
handleFilesChange(files);
}
};
const formatFileSize = (bytes) => {
if (bytes === 0) return '0 Б';
const k = 1024;
const sizes = ['Б', 'КБ', 'МБ', 'ГБ'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
};
const validateFiles = (files) => {
errorMessages.value = [];
const currentFiles = Array.isArray(localNewFiles.value) ? localNewFiles.value : [];
const totalFiles = currentFiles.length + files.length;
// Проверка количества
if (totalFiles > MAX_NEW_FILES) {
errorMessages.value.push(`Можно добавить не более ${MAX_NEW_FILES} файлов`);
return false;
} }
return new File([u8arr], filename, { type: mime }); // Проверка размера
} const oversizedFiles = files.filter((file) => file.size > MAX_FILE_SIZE);
if (oversizedFiles.length > 0) {
errorMessages.value.push(
// const eventFiles = computed({ `Следующие файлы превышают 2 МБ: ${oversizedFiles.map((f) => f.name).join(', ')}`,
// get() { );
// if (propsFiles.value.length > 0) { return false;
// propsFiles.value.forEach((e) => }
// files.value.push(
// dataURLtoFile(
// "data:text/plain;base64,aGVsbG8gd29ybGQ=",
// get_name(decodeURI(e.file))
// )
// )
// );
// // let file = dataURLtoFile(
// // "data:text/plain;base64,aGVsbG8gd29ybGQ=",
// // get_name(
// // decodeURI(propsFiles.value.event.files[0].file)
// // )
// // );
// // files.value.push(file); return true;
// } };
const getFileKey = (file, index) => {
return file instanceof File
? `${file.name}-${file.size}-${file.lastModified}`
: file.id || index;
};
// Получаем имя файла из объекта файла
const getFileName = (fileData) => {
// Для новых файлов (File object) - берем оригинальное имя
if (fileData instanceof File) {
return fileData.name;
}
// Для существующих файлов с бэкенда - извлекаем из URL
if (fileData.file) {
try {
const filePath = fileData.file.startsWith('http')
? new URL(fileData.file).pathname
: fileData.file;
// Извлекаем имя файла
let fileName = filePath.split('/').pop();
// Декодируем URL-encoded символы, но НЕ изменяем имя
fileName = decodeURIComponent(fileName);
return fileName || 'Файл';
} catch (error) {
console.warn('Ошибка извлечения имени файла:', error, fileData);
return 'Файл';
}
}
// Если есть name в данных - используем как есть
if (fileData.name) {
return fileData.name;
}
return 'Файл';
};
// Иконка в зависимости от типа файла
const getFileIcon = (fileData) => {
let fileName = '';
if (fileData instanceof File) {
fileName = fileData.name;
} else {
fileName = getFileName(fileData);
}
const extension = fileName.split('.').pop()?.toLowerCase() || '';
const iconMap = {
pdf: 'mdi-file-pdf',
doc: 'mdi-file-word',
docx: 'mdi-file-word',
xls: 'mdi-file-excel',
xlsx: 'mdi-file-excel',
jpg: 'mdi-file-image',
jpeg: 'mdi-file-image',
png: 'mdi-file-image',
gif: 'mdi-file-image',
svg: 'mdi-file-image',
zip: 'mdi-folder-zip',
rar: 'mdi-folder-zip',
'7z': 'mdi-folder-zip',
txt: 'mdi-file-document',
json: 'mdi-code-json',
js: 'mdi-language-javascript',
vue: 'mdi-vuejs',
html: 'mdi-language-html5',
css: 'mdi-language-css3',
};
return iconMap[extension] || 'mdi-file';
};
// Обработка изменения новых файлов
const handleFilesChange = (newFiles) => {
if (!newFiles || newFiles.length === 0) {
return;
}
const validFiles = newFiles.filter((file) => file instanceof File);
if (validFiles.length === 0) {
return;
}
// Валидация
if (!validateFiles(validFiles)) {
return;
}
// localNewFiles.value = [...validFiles];
const currentFiles = Array.isArray(localNewFiles.value) ? localNewFiles.value : [];
const updatedFiles = [...currentFiles, ...validFiles];
localNewFiles.value = updatedFiles;
emit('update:newFiles', updatedFiles);
emit('postFiles', updatedFiles);
};
// Удаление существующего файла
const removeExistingFile = (fileId) => {
try {
// Создаем копию event и удаляем файл
const updatedFiles = existingFiles.value.filter((file) => file.id !== fileId);
// props.files = updatedFiles;
emit('update:files', updatedFiles);
} catch (error) {
console.error('Ошибка при удалении файла:', error);
}
};
// Удаление нового файла (еще не загруженного)
const removeNewFile = (index) => {
const updatedFiles = localNewFiles.value.filter((_, i) => i !== index);
localNewFiles.value = updatedFiles;
// localNewFiles.value.splice(index, 1);
// emit('postFiles', localNewFiles.value);
emit('update:newFiles', updatedFiles);
emit('postFiles', updatedFiles);
};
const downloadExistingFile = async (file) => {
try {
const fileName = getFileName(file); // Теперь будет работать правильно!
const fileUrl = file.file.startsWith('http')
? file.file
: `${window.location.origin}${file.file}`; // Для относительных путей
const link = document.createElement('a');
link.href = fileUrl;
link.download = fileName;
link.style.display = 'none';
document.body.appendChild(link);
link.click();
setTimeout(() => {
document.body.removeChild(link);
}, 100);
} catch (error) {
console.error('Ошибка при скачивании файла:', error);
errorMessages.value = ['Ошибка скачивания файла'];
}
};
// Функция для обрезки длинных имен файлов
const truncateFileName = (fileName) => {
if (!fileName) return '';
if (fileName.length <= 20) return fileName;
const extension = fileName.split('.').pop();
const nameWithoutExt = fileName.slice(0, -(extension.length + 1));
if (nameWithoutExt.length <= 15) return fileName;
return `${nameWithoutExt.slice(0, 15)}...${extension ? '.' + extension : ''}`;
};
// return files.value;
// },
// set(newValue) {
// newValue.forEach((e) => {
// if (!files.value.some((l) => l.name == e.name.split(" ").join("_"))) {
// files.value.push(e);
// }
// });
// if (newValue.length == 0) {
// files.value = [];
// propsFiles.value = [];
// }
// },
// });
return { return {
eventFiles, localNewFiles,
arrFiles, existingFiles,
handleFilesChange,
removeExistingFile,
removeNewFile,
getFileName,
getFileIcon,
formatFileSize,
errorMessages,
validateFiles,
getFileKey,
MAX_NEW_FILES,
fileInputRef,
handleFileSelect,
triggerFileInput,
handleDrop,
downloadExistingFile,
truncateFileName,
}; };
}, },
}; };
</script> </script>
<style></style> <style scoped>
:deep(.v-chip) {
border-radius: 6px;
}
.custom-file-input-wrapper {
border: 1px solid rgba(0, 0, 0, 0.38);
border-radius: 4px;
padding: 12px;
position: relative;
background-color: white;
}
.custom-file-input-wrapper:focus-within {
border-color: #1976d2;
border-width: 2px;
}
.file-input-area {
min-height: 40px;
cursor: pointer;
padding: 4px;
}
.chips-container {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 4px;
}
.file-chip {
max-width: 150px;
}
.file-counter {
margin-left: 8px;
}
.placeholder {
display: flex;
align-items: center;
color: rgba(0, 0, 0, 0.6);
padding: 8px 0;
}
.error-messages {
margin-top: 4px;
}
.text-error {
color: #d32f2f;
}
.existing-files-section {
border-top: 1px solid #e0e0e0;
padding-top: 6px;
}
.download-icon {
cursor: pointer;
opacity: 0.7;
transition: opacity 0.2s;
}
.download-icon:hover {
opacity: 1;
color: #024e45;
}
.close-icon:hover {
opacity: 1;
color: #024e45;
}
</style>
@@ -1,127 +1,68 @@
<template> <template>
<v-row no-gutters> <v-row no-gutters>
<v-col class="flex-grow-0 d-flex flex-column"> <v-col class="flex-grow-0 d-flex flex-column">
<v-card class="h-100 rounded-0 d-flex flex-colmn" width="250"> <mini-calendar />
<v-row no-gutters class="flex-column">
<v-col class="flex-grow-0 px-2 pt-1">
<v-text-field
density="compact"
clearable
append-inner-icon="mdi-magnify"
hide-details
class="py-3"
label="Найти событие"
rows="1"
no-resize
variant="outlined"
/>
</v-col>
<v-col class="flex-grow-0 px-2">
<v-btn
type="submit"
class="text-subtitle-1 font-weight-light"
color="btn_text"
block
elevation="1"
@click="createEvent()"
>Создать событие</v-btn
>
<!-- {{eventFromCalendar}} -->
</v-col>
<v-col class="w100" lg="3">
<v-locale-provider locale="ru">
<v-date-picker
ref="cal"
v-model="selectdate"
color="btn_text"
class="rounded-0 minCal"
max-width="250"
hide-header
show-adjacent-months
@click="CheckingStore"
@update:month="getMonth"
@update:year="getYear"
>
</v-date-picker>
</v-locale-provider>
</v-col>
<v-col class="flex-column d-flex">
<v-row no-gutters class="h-0 overflow-auto flex-column flex-nowrap">
<v-col>
<calendar-my
:calendars="
calendarForMy.filter((e) => e.author == accountStore.user.is_idEmployee)
"
title="Мои календари"
@getCalendar="getCalendar"
/>
<calendar-my
:calendars="
calendarForMy.filter((e) => e.author != accountStore.user.is_idEmployee)
"
title="Подписки"
/>
</v-col>
</v-row>
</v-col>
</v-row>
</v-card>
</v-col> </v-col>
<v-col class="d-flex flex-column"> <v-col class="d-flex flex-column">
<calendar-full <custom-calendar
:allEvent="calendarForMy.filter((e) => e.events.length > 0)" :key="calendarKey"
@getEvent="createEvent" @openEventDialog="openEventDialog"
@update:allEvent="infoEvent($event)" @openEventView="openEventView"
/> />
</v-col> </v-col>
<!-- <v-navigation-drawer <v-dialog v-model="showEventDialog" max-width="700">
v-model="drawer_right"
floating
permanent
location="right"
rail-width="400"
rail
>
</v-navigation-drawer> -->
<v-dialog v-model="showDialog" max-width="700">
<event-create <event-create
@closeDialog="showDialog = false" @closeDialog="closeEventDialog"
:eventCalendar="eventFromCalendar" :eventCalendar="eventFromCalendar"
@update:eventCalendar="eventFromCalendar = $event" :allCalendars="allCalendars"
@getCalendar="getCalendar" @getCalendar="getCalendar"
@update:eventCalendar="eventFromCalendar = $event"
ref="createEvents" ref="createEvents"
:key="eventKey"
/> />
</v-dialog> </v-dialog>
<event-calendar-show
v-model:show="showViewDialog"
:all-calendars="allCalendars"
:event-data="selectedEventForView"
@close="handleViewDialogClose"
:employees="calendarStore.employees"
/>
</v-row> </v-row>
</template> </template>
<script> <script>
import { ref, onMounted, watch } from 'vue'; import { ref, onMounted, watch, computed } from 'vue';
import { useWeekendsStore } from '@/store/WeekendsStore'; import { useWeekendsStore } from '@/store/WeekendsStore';
import EventCreate from '@/components/calendar_of_events/event-create.vue'; import EventCreate from '@/components/calendar_of_events/event-create.vue';
import CalendarMy from '@/components/calendar_of_events/calendar-my.vue'; import CustomCalendar from '@/components/calendar_of_events/UI_calendar/CustomCalendar.vue';
import { useCalendarStore } from '@/store/calendarStore';
import { storeToRefs } from 'pinia';
import MiniCalendar from '@/components/calendar_of_events/UI_calendar/MiniCalendar.vue';
import { axiosApiInstance } from '@/utils/axios-api'; import { axiosApiInstance } from '@/utils/axios-api';
import { useAccountStore } from '@/store/AccountStore'; import { useAccountStore } from '@/store/AccountStore';
import CalendarFull from '@/components/calendar_of_events/UI_calendar/calendarFull.vue'; import EventCalendarShow from '@/components/calendar_of_events/event-calendar-show.vue';
export default { export default {
components: { EventCreate, CalendarMy, CalendarFull }, components: { EventCreate, MiniCalendar, CustomCalendar, EventCalendarShow },
setup() { setup() {
const accountStore = useAccountStore();
const showDialog = ref(false);
const week = useWeekendsStore(); const week = useWeekendsStore();
const drawer_right = ref(false);
const cal = ref(null);
const selectdate = ref(new Date()); const selectdate = ref(new Date());
const MyYear = ref(selectdate.value.getFullYear()); const MyYear = ref(selectdate.value.getFullYear());
const MyMonth = ref(selectdate.value.getMonth() + 1); const MyMonth = ref(selectdate.value.getMonth() + 1);
const calendarForMy = ref([]); const calendarForMy = ref([]);
const eventFromCalendar = ref({}); const eventFromCalendar = ref({});
const createEvents = ref(null); const eventKey = ref(0);
const calendarKey = ref(0);
const calendarStore = useCalendarStore();
const accountStore = useAccountStore();
const showViewDialog = ref(false);
const selectedEventForView = ref({});
const { selectedDate, showEventDialog } = storeToRefs(calendarStore); // синхронизируем с date-picker
const getMonth = (month) => { const getMonth = (month) => {
MyMonth.value = month + 1; MyMonth.value = month + 1;
@@ -131,79 +72,75 @@ export default {
}; };
const getCalendar = () => { const getCalendar = () => {
axiosApiInstance.get(`api/calendar_of_events/my_calendars/`).then((res) => { calendarStore.loadCalendars();
res.data.forEach((e) => (e.visible = accountStore.calendar.includes(e.id) ? false : true));
calendarForMy.value = res.data;
});
}; };
getCalendar(); const getDictEmployee = () => {
calendarStore.loadDictEmployees();
};
const getEvents = (idEvent, clik) => { const getEmployees = () => {
axiosApiInstance calendarStore.loadEmployees();
.get(`api/calendar_of_events/my_events/${idEvent === undefined ? '' : `?id=${idEvent}`}`) };
.then((res) => {
if (idEvent === undefined) { const allCalendars = computed(() => [
res.data.event = { ...calendarStore.myCalendars,
name: '', ...calendarStore.subscribedCalendars,
participant: [accountStore.user.is_idEmployee], ]);
files: [],
date_start: new Date(), const getEvent = (idEvent) => {
date_end: new Date(), if (!idEvent) {
period: null, eventFromCalendar.value = createEmptyEvent();
description: '', return;
calendar: null, } else {
}; axiosApiInstance.get(`api/calendar_of_events/my_events/?id=${idEvent}`).then((res) => {
}
eventFromCalendar.value = res.data; eventFromCalendar.value = res.data;
calendarStore.openEventDialog();
if (clik) showDialog.value = true;
}); });
};
getEvents();
const createEvent = (idEv) => {
getEvents(idEv, true);
if (idEv) {
getCalendar();
} }
}; };
const weekendsData = () => { const createEmptyEvent = () => ({
cal.value.$el.querySelectorAll('.v-date-picker-month__day').forEach((e) => { event: {
let datas = e.getAttribute('data-v-date'); name: '',
let weeks = new Date(datas).getDay() === 6 || new Date(datas).getDay() === 0; participant: [accountStore.user.is_idEmployee],
if (weeks) { files: [],
e.querySelectorAll('span').forEach((n) => { date_start: new Date().toISOString(),
n.classList.add('text-red'); date_end: new Date().toISOString(),
}); period: null,
} description: '',
if (MyMonth.value in week.week[MyYear.value]) { calendar: null,
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) { const openEventDialog = (selectedEvent) => {
n.classList.replace('text-red', 'text-black'); // Всегда сбрасываем данные перед открытием нового диалога
} if (!selectedEvent) {
}); eventFromCalendar.value = createEmptyEvent();
} eventKey.value++;
} }
});
getEvent(selectedEvent?.event?.id);
calendarStore.openEventDialog();
}; };
onMounted(() => { onMounted(() => {
getEvent();
week.getWeekend(MyYear.value); week.getWeekend(MyYear.value);
getDictEmployee();
getCalendar();
getEmployees();
}); });
watch( const closeEventDialog = () => {
() => week.week, calendarStore.closeEventDialog();
(newValue) => {
if (newValue) { // При ручном закрытии сбрасываем данные сразу
weekendsData(); setTimeout(() => {
} eventFromCalendar.value = createEmptyEvent();
}, eventKey.value++;
); }, 200);
};
const CheckingStore = () => { const CheckingStore = () => {
if (MyYear.value in week.week) { if (MyYear.value in week.week) {
@@ -213,44 +150,85 @@ export default {
} }
}; };
const infoEvent = (i) => { watch(
console.log(i, 'iiiiiiiiii'); () => calendarStore.showEventDialog,
(newValue, oldValue) => {
if (!newValue && oldValue) {
// Диалог был открыт и закрыт не через нашу кнопку
// Добавляем проверку чтобы не сбрасывать при инициализации
if (eventFromCalendar.value.event?.id) {
setTimeout(() => {
eventFromCalendar.value = createEmptyEvent();
eventKey.value++;
}, 200);
}
}
},
);
watch(
() => accountStore.user?.id,
(newUserId, oldUserId) => {
if (newUserId !== oldUserId) {
console.log('User changed, forcing calendar recreation...');
calendarKey.value += 1; // Изменяем key для пересоздания компонента
}
},
);
const getEventForView = (idEvent) => {
if (!idEvent) {
selectedEventForView.value = {};
return;
}
axiosApiInstance.get(`api/calendar_of_events/my_events/?id=${idEvent}`).then((res) => {
selectedEventForView.value = res.data;
showViewDialog.value = true;
});
};
const openEventView = (eventId) => {
if (eventId) {
getEventForView(eventId);
} else {
console.log('❌ No event ID provided');
}
};
// Закрытие модалки
const handleViewDialogClose = () => {
showViewDialog.value = false;
}; };
return { return {
drawer_right, selectedDate,
selectdate,
cal,
getMonth, getMonth,
getYear, getYear,
weekendsData,
week, week,
CheckingStore, CheckingStore,
showDialog, showEventDialog,
calendarForMy, calendarForMy,
accountStore,
getCalendar, getCalendar,
getEvent,
eventFromCalendar, eventFromCalendar,
createEvent, calendarStore,
infoEvent, accountStore,
createEvents, closeEventDialog,
openEventDialog,
createEmptyEvent,
eventKey,
getDictEmployee,
openEventView,
handleViewDialogClose,
showViewDialog,
selectedEventForView,
allCalendars,
eventKey,
calendarKey,
}; };
}, },
}; };
</script> </script>
<style> <style scoped></style>
.minCal .v-date-picker-month__day {
height: 31px;
width: 31px;
}
.minCal .v-btn--icon.v-btn--density-default {
width: calc(var(--v-btn-height) + 12px);
height: calc(var(--v-btn-height) + 6px);
}
.minCal .v-btn__content {
font-weight: 410;
}
</style>
@@ -0,0 +1,604 @@
<template>
<v-col cols="12" class="d-flex flex-column" style="height: 80vh">
<v-card class="d-flex flex-column flex-grow-1">
<v-card-text class="d-flex flex-column flex-grow-1">
<!-- Контролы навигации -->
<div class="flex-grow-0 mb-1">
<v-row no-gutters class="mb-2 align-end" style="height: 60px" justify="space-between">
<v-col md="5" class="flex-grow-0 d-flex align-center">
<template v-if="currentView !== 'listAllEvents'">
<div class="pb-3 d-flex align-center">
<v-btn
variant="outlined"
class="text-subtitle-2 mr-2"
@click="handleToday"
density="comfortable"
>
Сегодня
</v-btn>
<v-btn
variant="text"
@click="handlePrev"
:elevation="0"
style="border-radius: 4px"
density="compact"
icon
>
<v-icon size="large">mdi-chevron-left</v-icon>
</v-btn>
<v-btn
variant="text"
@click="handleNext"
:elevation="0"
style="border-radius: 4px"
density="compact"
icon
>
<v-icon size="large">mdi-chevron-right</v-icon>
</v-btn>
<span class="text-h5 text-no-wrap ml-2">
{{ currentTitle }}
</span>
</div>
</template>
<template v-else>
<!-- Фильтры для кастомного вида -->
<EventListFilters
:date-range="filters.dateRange.value"
:sort-order="filters.sortOrder.value"
:sort-options="filters.sortOptions"
@update:filters="handleFiltersUpdate"
/>
</template>
</v-col>
<v-col class="flex-grow-0 d-flex justify-end">
<v-btn-toggle
v-model="currentView"
mandatory
divided
variant="plain"
density="comfortable"
>
<v-btn value="timeGridDay">День</v-btn>
<v-btn value="timeGridWeek">Неделя</v-btn>
<v-btn value="dayGridMonth">Месяц</v-btn>
<v-btn value="multiMonthYear">Год</v-btn>
<v-btn value="listWeek">Расписание</v-btn>
<v-btn value="listAllEvents">Все события</v-btn>
</v-btn-toggle>
</v-col>
</v-row>
</div>
<div class="flex-grow-1 d-flex">
<!-- VCalendar -->
<FullCalendar
v-if="currentView !== 'listAllEvents'"
ref="calendarRef"
:options="calendarOptions"
class="custom-calendar"
/>
<!-- Кастомный список событий -->
<EventsListView v-else @event-click="handleEventClick" :filters="unwrappedFilters" />
</div>
</v-card-text>
</v-card>
</v-col>
</template>
<script>
import { ref, watch, nextTick, computed } from 'vue';
import { storeToRefs } from 'pinia';
import dayGridPlugin from '@fullcalendar/daygrid';
import timeGridPlugin from '@fullcalendar/timegrid';
import multiMonthPlugin from '@fullcalendar/multimonth';
import interactionPlugin from '@fullcalendar/interaction';
import listPlugin from '@fullcalendar/list';
import ruLocale from '@fullcalendar/core/locales/ru';
import rrulePlugin from '@fullcalendar/rrule';
import { onMounted } from 'vue';
import { useCalendarStore } from '@/store/calendarStore';
import { useRecurrence } from '@/components/calendar_of_events/composables/useReccurrence';
import { useAccountStore } from '@/store/AccountStore';
import EventsListView from './EventsListView.vue';
import EventListFilters from './EventListFilters.vue';
import { useEventListFilters } from '../composables/useEventListFilters';
export default {
name: 'CustomCalendar',
emits: ['openEventDialog', 'openEventView'],
components: {
EventsListView,
EventListFilters,
},
setup(props, { emit }) {
const currentView = ref('dayGridMonth');
const currentTitle = ref('Календарь');
const calendarRef = ref(null);
const accountStore = useAccountStore();
const calendarStore = useCalendarStore();
const { selectedDate, lastUpdatedBy, allEvents, calendarColorMap } = storeToRefs(calendarStore);
const { isRecurringEvent, generateRecurringInstances } = useRecurrence();
const calendarApi = computed(() => {
return calendarRef.value?.getApi?.() || null;
});
const filters = useEventListFilters();
// Создаем развернутую версию фильтров для передачи в EventsListView
const unwrappedFilters = computed(() => ({
dateRange: filters.dateRange.value,
sortOrder: filters.sortOrder.value,
}));
const handleEventClick = (info) => {
if (calendarStore.canEditEvent(info.event.id)) {
emit('openEventDialog', info);
} else {
emit('openEventView', info.event.id);
}
};
const calendarOptions = ref({
plugins: [
dayGridPlugin,
timeGridPlugin,
multiMonthPlugin,
interactionPlugin,
listPlugin,
rrulePlugin,
],
initialView: props.forHomePage ? props.view : currentView.value,
locales: [ruLocale],
locale: 'ru',
timeZone: 'local',
firstDay: 1,
headerToolbar: false,
height: '80vh',
aspectRatio: 1.5,
weekNumbers: true,
eventDisplay: 'block',
eventTimeFormat: {
hour: '2-digit',
minute: '2-digit',
hour12: false,
meridiem: false,
},
weekNumberFormat: {
week: 'numeric',
},
weekNumberCalculation: 'ISO', // ISO стандарт (понедельник - первый день)
selectable: true,
unselectAuto: false,
selectMirror: false,
dayCellDidMount: (arg) => {
const date = arg.date;
const dayInfo = calendarStore.isNonWorkingDay(date);
if (dayInfo.isHoliday === true) {
arg.el.classList.add('non-working-day');
}
if (dayInfo.isWeekendForStyling === true) {
arg.el.classList.add('grey-background');
}
},
views: {
timeGridDay: {
type: 'timeGrid',
duration: { days: 1 },
slotDuration: '01:00:00',
slotLabelInterval: '01:00:00',
slotLabelFormat: {
hour: '2-digit',
minute: '2-digit',
hour12: false,
meridiem: false,
},
allDaySlot: true,
slotMinTime: '07:00:00',
slotMaxTime: '22:00:00',
expandRows: true,
dayHeaderFormat: {
weekday: 'long',
day: 'numeric',
month: 'long',
omitCommas: true,
},
},
timeGridWeek: {
type: 'timeGrid',
duration: { weeks: 1 },
slotDuration: '01:00:00',
slotMinTime: '07:00:00',
slotMaxTime: '22:00:00',
allDaySlot: true,
expandRows: true,
dayHeaderFormat: { weekday: 'short', day: 'numeric' },
titleFormat: {
day: 'numeric',
month: 'long',
omitCommas: true,
},
},
dayGridMonth: {
type: 'dayGrid',
fixedWeekCount: false,
dayHeaderFormat: { weekday: 'short' },
weekNumbers: true,
weekNumberFormat: { week: 'numeric' },
weekNumberContent: (arg) => {
return arg.num;
},
weekText: 'Нед.',
eventTimeFormat: {
hour: '2-digit',
minute: '2-digit',
hour12: false,
omitZeroMinute: false,
},
},
multiMonthYear: {
type: 'multiMonth',
duration: { years: 1 },
multiMonthMaxColumns: 4,
fixedWeekCount: false,
weekNumbers: false,
},
listWeek: {
type: 'list',
duration: { days: 1 },
listDayFormat: {
weekday: 'long',
day: 'numeric',
month: 'long',
},
listDaySideFormat: false,
},
},
events: function (fetchInfo, successCallback) {
const events = allEvents.value.flatMap((event) => {
const eventColor = calendarColorMap.value.get(event.calendar) || '#3788d8';
const startDate = new Date(event.date_start);
const endDate = new Date(event.date_end);
const isMultiDay = startDate.toDateString() !== endDate.toDateString();
if (isRecurringEvent(event)) {
return generateRecurringInstances(event, 52).map((instance) => ({
id: instance.id,
title: instance.title,
start: instance.start,
end: instance.end,
allDay: instance.allDay || isMultiDay,
textColor: '#ffffff',
backgroundColor: eventColor,
borderColor: eventColor,
extendedProps: {
...instance.extendedProps,
_userHash: accountStore.user?.id || 'anonymous',
},
}));
} else {
return [
{
id: event.id,
title: event.name,
start: new Date(event.date_start),
end: new Date(event.date_end),
allDay: event.all_day,
textColor: '#ffffff',
backgroundColor: eventColor,
borderColor: eventColor,
allDay: isMultiDay,
extendedProps: {
originalEventId: event.id,
description: event.description,
participant: event.participant,
calendar: event.calendar,
files: event.files,
_userHash: accountStore.user?.id || 'anonymous',
},
},
];
}
});
successCallback(events);
},
editable: true,
selectable: true,
eventClick: handleEventClick,
dateClick: (info) => {
calendarStore.setSelectedDateFromCalendar(info);
handleDateSelection(info.dateStr);
handleCalendarDateClick(info);
calendarApi.value?.unselect();
},
datesSet: (info) => {
if (info.view.type === 'listWeek' && selectedDate.value) {
const date = new Date(selectedDate.value);
const options = {
weekday: 'long',
day: 'numeric',
month: 'long',
year: 'numeric',
};
const formattedDate = date.toLocaleDateString('ru-RU', options);
currentTitle.value = `Расписание на ${formattedDate}`;
} else {
currentTitle.value = info.view.title;
}
if (selectedDate?.value) {
handleDateSelection(selectedDate.value);
}
},
});
const handleCalendarDateClick = (info) => {
calendarStore.setSelectedDateFromCalendar(info);
currentTitle.value = info.view.title;
if (calendarApi.value) {
calendarApi.value.gotoDate(info.date);
calendarApi.value.changeView('listWeek');
currentView.value = 'listWeek';
}
};
const handleToday = () => {
calendarApi.value?.today();
// Получаем текущую дату из календаря и передаем в стор
updateSelectedDateFromCalendar();
};
const handlePrev = () => {
calendarApi.value?.prev();
updateSelectedDateFromCalendar();
};
const handleNext = () => {
calendarApi.value?.next();
updateSelectedDateFromCalendar();
};
const updateSelectedDateFromCalendar = () => {
const currentDate = calendarApi.value?.getDate();
if (currentDate) {
const todayInfo = {
dateStr: currentDate.toISOString().split('T')[0],
};
calendarStore.setSelectedDateFromCalendar(todayInfo);
}
};
// Функция обновления выделения
const handleDateSelection = (dateStr) => {
// Убираем предыдущее выделение
const previousSelected = document.querySelectorAll('.fc-day-selected-custom');
previousSelected.forEach((el) => el.classList.remove('fc-day-selected-custom'));
// Добавляем новое выделение
const dayElements = document.querySelectorAll(`[data-date="${dateStr}"]`);
dayElements.forEach((el) => el.classList.add('fc-day-selected-custom'));
selectedDate.value = dateStr;
};
onMounted(async () => {
const currentYear = new Date().getFullYear();
calendarStore.fetchHolidays(currentYear);
// Ждем следующего тика для гарантии, что календарь инициализирован
await nextTick();
// Принудительно обновляем события после загрузки праздников
if (calendarApi.value) {
calendarApi.value.refetchEvents();
}
if (selectedDate.value) {
handleDateSelection(selectedDate.value);
}
});
watch(
allEvents,
() => {
// При изменении событий перезагружаем календарь
if (calendarApi.value) {
calendarApi.value.refetchEvents();
}
},
{ deep: true },
);
watch(
calendarColorMap,
(newColorMap, oldColorMap) => {
if (calendarRef.value && JSON.stringify(newColorMap) !== JSON.stringify(oldColorMap)) {
renderEvents();
}
},
{ deep: true },
);
watch(selectedDate, (newDate) => {
if (newDate && calendarApi.value && lastUpdatedBy.value !== 'calendar') {
nextTick(() => {
calendarApi.value.gotoDate(newDate);
handleDateSelection(newDate);
});
}
});
watch(currentView, (newView) => {
if (newView === 'listAllEvents') {
currentTitle.value = 'Все события';
} else if (calendarApi.value) {
calendarApi.value.changeView(newView);
currentTitle.value = calendarApi.value.view.title;
}
});
const handleFiltersUpdate = (newFilters) => {
Object.keys(newFilters).forEach((key) => {
if (filters[key] !== undefined) {
filters[key].value = newFilters[key];
}
});
};
// Сброс фильтров при выходе из кастомного вида
watch(currentView, (newView, oldView) => {
if (oldView === 'listAllEvents' && newView !== 'listAllEvents') {
filters.resetFilters();
}
});
return {
currentTitle,
calendarRef,
calendarApi,
currentView,
calendarOptions,
handleToday,
handleNext,
handlePrev,
handleCalendarDateClick,
handleDateSelection,
handleEventClick,
calendarStore,
filters,
handleFiltersUpdate,
unwrappedFilters,
};
},
};
</script>
<style scoped>
:deep(.fc-daygrid-day-number) {
display: flex !important;
justify-content: center !important;
align-items: center !important;
width: 100% !important;
height: 100% !important;
margin: 0 !important;
padding: 0.6rem !important;
}
/* текущая дата обводка */
:deep(.fc-day-today) {
background-color: transparent !important;
}
:deep(.fc-day-today .fc-daygrid-day-number) {
position: relative;
z-index: 1;
color: #00897b;
&::before {
content: '';
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 32px;
height: 32px;
border: 1px solid #00897b;
border-radius: 50%;
z-index: -1;
}
}
/* Выбранная дата заливка */
:deep(.fc-day-selected-custom) {
background-color: transparent !important;
}
:deep(.fc-day-selected-custom .fc-daygrid-day-number) {
position: relative;
z-index: 1;
color: white !important;
}
:deep(.fc-day-selected-custom .fc-daygrid-day-number::before) {
content: '';
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 32px;
height: 32px;
background-color: #00897b;
border-radius: 50%;
z-index: -1;
}
:deep(.fc-multiMonthYear-view) {
.fc-day-today .fc-daygrid-day-number::before,
.fc-day-selected-custom .fc-daygrid-day-number::before {
width: 26px;
height: 26px;
}
}
:deep(.v-btn--active) {
background-color: transparent !important;
color: #00897b !important;
}
:deep(.fc .fc-timegrid-col.fc-day-today) {
background-color: #e0f2f1 !important;
}
:deep(.fc-highlight) {
background-color: transparent !important;
}
:deep(.fc-day),
:deep(.fc-list-event-title) {
cursor: pointer;
}
:deep(.fc-popover) {
background-color: rgb(248, 244, 244) !important;
}
.non-working-day {
color: red !important;
}
:global(.fc-daygrid-day.non-working-day .fc-daygrid-day-number) {
color: #d32f2f !important;
}
:global(.fc-daygrid-day.grey-background.fc-daygrid-day-number) {
background-color: rgb(196, 187, 187) !important;
}
.grey-background {
background-color: rgb(240, 229, 229) !important;
}
:deep(.fc-day.grey-background) {
background-color: #f5f5f5 !important;
}
.custom-calendar {
height: 100% !important;
min-height: 700px;
flex: 1 1 auto;
}
</style>
@@ -0,0 +1,302 @@
<template>
<div class="event-list-filters d-flex align-end ga-3">
<!-- Диапазон дат -->
<div class="date-range-group justify-center">
<div class="date-range-label">Выбрать период событий</div>
<div class="date-inputs d-flex align-center gap-2">
<!-- Дата начала -->
<v-menu :close-on-content-click="false" scrim>
<template v-slot:activator="{ props }">
<v-text-field
v-bind="props"
:model-value="formatDateDisplay(startDate)"
placeholder="Начало"
density="compact"
variant="outlined"
prepend-inner-icon="mdi-calendar-arrow-left"
readonly
hide-details
class="date-input compact-field"
:class="{ active: startDate }"
>
</v-text-field>
</template>
<v-locale-provider locale="ru">
<v-date-picker hide-header show-adjacent-months v-model="startDate" />
</v-locale-provider>
</v-menu>
<div class="date-separator">
<v-icon size="small" color="grey">mdi-arrow-right</v-icon>
</div>
<!-- Дата окончания -->
<v-menu :close-on-content-click="false" scrim>
<template v-slot:activator="{ props }">
<v-text-field
v-bind="props"
:model-value="formatDateDisplay(endDate)"
density="compact"
variant="outlined"
placeholder="Конец"
prepend-inner-icon="mdi-calendar-arrow-right"
readonly
hide-details
class="date-input compact-field"
:class="{ active: endDate }"
:disabled="!startDate"
>
</v-text-field>
</template>
<v-locale-provider locale="ru">
<v-date-picker v-model="endDate" :min="startDate" hide-header show-adjacent-months />
</v-locale-provider>
</v-menu>
</div>
</div>
<!-- Сортировка -->
<v-select
v-model="localSortOrder"
:items="sortOptions"
density="compact"
variant="outlined"
hide-details
class="sort-select compact-field"
style="min-width: 160px"
>
<template v-slot:item="{ item, props: itemProps }">
<v-list-item v-bind="itemProps" density="compact">
<template v-slot:prepend>
<v-icon :icon="item.raw.props.prependIcon" size="small" />
</template>
</v-list-item>
</template>
</v-select>
<!-- Сброс фильтров -->
<v-btn
class="mb-1"
variant="text"
@click="handleReset"
:disabled="!hasActiveFilters"
size="small"
>
Сбросить
</v-btn>
</div>
</template>
<script>
import { computed, watch } from 'vue';
export default {
name: 'EventListFilters',
props: {
dateRange: Array,
sortOrder: String,
sortOptions: Array,
},
emits: ['update:filters'],
setup(props, { emit }) {
const startDate = computed({
get: () => props.dateRange?.[0] || null,
set: (value) => {
const newRange = value ? [value, props.dateRange?.[1] || null] : null;
emit('update:filters', { dateRange: newRange });
},
});
const endDate = computed({
get: () => props.dateRange?.[1] || null,
set: (value) => {
const newRange = props.dateRange?.[0] ? [props.dateRange[0], value] : null;
emit('update:filters', { dateRange: newRange });
},
});
const localSortOrder = computed({
get: () => props.sortOrder,
set: (value) => emit('update:filters', { sortOrder: value }),
});
// Автоматически устанавливаем конец даты = начало, если конец не выбран
watch(startDate, (newStart) => {
if (newStart && !endDate.value) {
endDate.value = newStart;
}
});
const formatDateDisplay = (date) => {
if (!date) return '';
return new Date(date).toLocaleDateString('ru-RU');
};
const hasActiveFilters = computed(() => {
return props.dateRange && props.dateRange.length === 2;
});
const handleReset = () => {
emit('update:filters', {
dateRange: null,
});
};
return {
startDate,
endDate,
localSortOrder,
formatDateDisplay,
hasActiveFilters,
handleReset,
};
},
};
</script>
<style scoped>
.event-list-filters {
min-height: 50px;
}
.date-range-group {
display: flex;
flex-direction: column;
gap: 2px;
}
.sort-select :deep(.v-field) {
border-radius: 4px;
font-size: 0.9rem;
}
.sort-select :deep(.v-field__prepend-inner) {
padding-inline-start: 8px;
padding-top: 0;
}
.date-range-btn {
border-radius: 8px;
border: 1px solid rgba(0, 0, 0, 0.12);
height: 40px;
min-width: 200px;
padding: 0 16px;
transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
background: white;
}
.date-range-btn:hover {
border-color: rgb(var(--v-theme-primary));
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
transform: translateY(-1px);
}
.date-range-btn.active-filter {
background-color: rgba(var(--v-theme-primary), 0.04);
border-color: rgb(var(--v-theme-primary));
color: rgb(var(--v-theme-primary));
}
.btn-content {
display: flex;
flex-direction: column;
align-items: flex-start;
line-height: 1.2;
flex-grow: 1;
}
.btn-label {
font-size: 0.75rem;
font-weight: 500;
color: rgba(0, 0, 0, 0.6);
margin-bottom: 2px;
}
.btn-value {
font-size: 0.875rem;
font-weight: 500;
color: rgba(0, 0, 0, 0.87);
}
.date-range-btn.active-filter .btn-value {
color: rgb(var(--v-theme-primary));
font-weight: 600;
}
.date-range-label {
font-size: 1rem;
margin-left: 2px;
}
/* Убираем стандартные стили Vuetify для более кастомного вида */
.date-range-btn :deep(.v-btn__prepend) {
margin-inline-end: 8px;
}
.date-range-btn :deep(.v-btn__content) {
flex-grow: 1;
justify-content: space-between;
align-items: center;
}
.date-input {
min-width: 120px;
}
/* Выравнивание по высоте */
.date-input :deep(.v-field),
.sort-select :deep(.v-field),
.reset-control :deep(.v-btn) {
height: 40px;
}
/* Убираем проблему с закрытием date-picker */
:deep(.v-overlay__content) {
border-radius: 8px;
overflow: hidden;
}
:deep(.v-date-picker-controls) {
padding: 4px 8px;
}
:deep(.v-date-picker-month) {
padding: 0 8px 8px;
}
.compact-field :deep(.v-field) {
border-radius: 5px;
cursor: pointer;
height: 36px;
font-size: 0.9rem;
padding-left: 4px;
}
/* Уменьшаем отступы у иконки */
.compact-field :deep(.v-field__prepend-inner) {
height: 39px;
padding-inline-start: 0;
margin-inline-end: 4px; /* Уменьшили отступ после иконки */
}
.compact-field :deep(.v-field__prepend-inner .v-icon) {
font-size: 16px;
opacity: 0.7; /* Делаем иконку менее заметной */
}
/* Увеличиваем область текста */
.compact-field :deep(.v-field__input) {
padding-inline-start: 0;
}
.sort-select {
width: 170px;
}
.sort-select :deep(.v-field) {
padding: 0 6px ;
}
</style>
@@ -0,0 +1,348 @@
<template>
<div class="list-all-events d-flex flex-column" style="height: 100%">
<!-- Фильтры - растянуты на всю ширину -->
<div class="filters pa-6 flex-grow-0 mt-1">
<v-row class="flex-nowrap">
<v-col class="flex-grow-1 pa-0">
<v-select
v-model="selectedCalendar"
:items="calendarOptions"
density="compact"
label="Календарь"
variant="outlined"
hide-details
class="w-100"
/>
</v-col>
</v-row>
</div>
<!-- Статистика -->
<div class="px-3 pb-2 text-body-2 text-medium-emphasis flex-grow-0">
Найдено событий: {{ filteredEvents.length }}
</div>
<!-- Список событий - растянут на всю оставшуюся высоту -->
<div class="events-list flex-grow-1" style="overflow-y: auto">
<div
v-for="event in filteredEvents"
:key="event.id"
class="event-item pa-3 mb-3"
:style="{ borderLeft: `4px solid ${getEventColor(event)}` }"
@click="handleItemClick(event)"
style="cursor: pointer; border-bottom: 1px solid #e0e0e0; width: 100%"
>
<div class="event-date text-subtitle-2 pb-3">
{{ formatEventDate(event) }}
</div>
<div class="event-content">
<div class="event-title d-flex align-center">
<span class="font-weight-medium">{{ event.name }}</span>
<v-chip
v-if="isRecurringEvent(event)"
:prepend-icon="getRecurrenceIcon(event.period)"
size="x-small"
color="primary"
class="ml-2"
variant="outlined"
>
{{ getRecurrenceText(event) }}
</v-chip>
</div>
<div class="event-meta text-subtitle-2 text-medium-emphasis">
<span class="calendar-badge" :style="{ color: getEventColor(event) }">
{{ getCalendarName(event.calendar) }}
</span>
•
{{ formatEventTime(event) }}
•
{{ formatDuration(event) }}
<span v-if="isRecurringEvent(event)" class="ml-1">
• {{ getRecurrenceDetails(event) }}
</span>
</div>
<div v-if="event.description" class="event-description text-subtitle-1 mt-1">
{{ truncateDescription(event.description) }}
</div>
</div>
</div>
<div v-if="filteredEvents.length === 0" class="text-center pa-8 text-medium-emphasis">
{{ getEmptyStateMessage() }}
</div>
</div>
</div>
</template>
<script>
import { ref, computed } from 'vue';
import { useCalendarStore } from '@/store/calendarStore';
import { RRule } from 'rrule';
import { useRecurrence } from '@/components/calendar_of_events/composables/useReccurrence.js';
export default {
name: 'EventsListView',
emits: ['event-click'],
props: {
filters: {
type: Object,
required: true,
default: () => ({
dateRange: null,
sortOrder: 'asc',
}),
},
},
setup(props, { emit }) {
const { isRecurringEvent, formatRecurrenceText, getRecurrenceIcon } = useRecurrence();
const calendarStore = useCalendarStore();
// Локальное состояние для фильтра календаря
const selectedCalendar = ref(null);
// Подготовка данных
const flattenedEvents = computed(() => {
return calendarStore.allEvents
.map((event) => ({
...event,
startDate: new Date(event.date_start),
endDate: new Date(event.date_end),
}))
.sort((a, b) => a.startDate - b.startDate);
});
// Опции для селекта календарей
const calendarOptions = computed(() => {
const baseOptions = [{ title: 'Все календари', value: null }];
const activeCalendars = calendarStore.calendars
.filter((calendar) => !calendarStore.hiddenCalendarIds.includes(calendar.id))
.map((calendar) => ({
title: calendar.cl_name,
value: calendar.id,
}));
return [...baseOptions, ...activeCalendars];
});
// Фильтрация событий
const filteredEvents = computed(() => {
let filtered = flattenedEvents.value;
// Фильтр по дате (из props)
if (
props.filters.dateRange &&
Array.isArray(props.filters.dateRange) &&
props.filters.dateRange.length === 2
) {
const [startDate, endDate] = props.filters.dateRange;
filtered = filtered.filter(
(event) => event.startDate >= startDate && event.endDate <= endDate,
);
}
// Фильтр по календарю (локальный)
if (selectedCalendar.value) {
filtered = filtered.filter((event) => event.calendar === selectedCalendar.value);
}
// Сортировка (из props)
filtered = [...filtered].sort((a, b) => {
return props.filters.sortOrder === 'asc'
? a.startDate - b.startDate
: b.startDate - a.startDate;
});
return filtered;
});
// Вспомогательные функции
const getEventColor = (event) => {
return calendarStore.calendarColorMap.get(event.calendar) || '#3788d8';
};
const getCalendarName = (calendarId) => {
const calendar = calendarStore.calendars.find((c) => c.id === calendarId);
return calendar?.cl_name || 'Неизвестно';
};
const formatEventDate = (event) => {
const start = event.startDate;
const end = event.endDate;
// Если событие в один день
if (start.toDateString() === end.toDateString()) {
return start.toLocaleDateString('ru-RU', {
day: 'numeric',
month: 'long',
year: 'numeric',
weekday: 'short',
});
}
// Если событие (диапазон)
const startFormatted = start.toLocaleDateString('ru-RU', {
day: 'numeric',
month: 'long',
weekday: 'short',
});
const endFormatted = end.toLocaleDateString('ru-RU', {
day: 'numeric',
month: 'long',
year: 'numeric',
weekday: 'short',
});
return `${startFormatted} – ${endFormatted}`;
};
const formatEventTime = (event) => {
if (event.all_day) return 'Весь день'; // Исправлено: было allday, должно быть all_day
const start = event.startDate.toLocaleTimeString('ru-RU', {
hour: '2-digit',
minute: '2-digit',
});
const end = event.endDate.toLocaleTimeString('ru-RU', {
hour: '2-digit',
minute: '2-digit',
});
return `${start} - ${end}`;
};
const formatDuration = (event) => {
const diff = event.endDate - event.startDate;
const hours = Math.floor(diff / (1000 * 60 * 60));
const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
if (hours === 0) return `${minutes} мин`;
if (minutes === 0) return `${hours} ч`;
return `${hours} ч ${minutes} мин`;
};
const truncateDescription = (desc) => {
if (!desc) return '';
return desc.length > 150 ? desc.substring(0, 150) + '...' : desc;
};
const getEmptyStateMessage = () => {
if (props.filters.searchQuery) {
// Исправлено: используем props.filters.searchQuery
return 'События по вашему запросу не найдены';
}
if (selectedCalendar.value) {
return 'В выбранном календаре нет событий';
}
if (props.filters.dateRange) {
return 'В выбранном диапазоне дат нет событий';
}
return 'Нет событий для отображения';
};
// Получаем текст повторения
const getRecurrenceText = (event) => {
return formatRecurrenceText(event.period, event.date_start) || '';
};
// Дополнительные детали о повторении
const getRecurrenceDetails = (event) => {
if (!isRecurringEvent(event)) return '';
try {
let rrule;
if (event.period.includes('RRULE:')) {
rrule = RRule.fromString(event.period);
} else {
const periodData = JSON.parse(event.period);
if (periodData?.origOptions) {
rrule = new RRule(periodData.origOptions);
}
}
if (!rrule || !rrule.origOptions.until) return '';
const untilDate = new Date(rrule.origOptions.until);
return `до ${untilDate.toLocaleDateString('ru-RU')}`;
} catch (error) {
return '';
}
};
const handleItemClick = (event) => {
const eventInfo = {
event: {
id: event.id,
},
};
emit('event-click', eventInfo);
};
return {
// Реактивные данные
selectedCalendar,
// Вычисляемые свойства
filteredEvents,
calendarOptions,
// Методы
getEventColor,
getCalendarName,
formatEventDate,
formatEventTime,
formatDuration,
truncateDescription,
getEmptyStateMessage,
getRecurrenceText,
getRecurrenceDetails,
handleItemClick,
isRecurringEvent,
getRecurrenceIcon,
};
},
};
</script>
<style scoped>
.list-all-events {
width: 100%;
height: 100%;
}
.filters {
width: 100%;
}
.events-list {
width: 100%;
height: 70vh;
overflow-y: scroll !important;
}
.event-item {
width: 100%;
box-sizing: border-box;
}
.event-item:hover {
background-color: #f5f5f5;
transition: background-color 0.2s;
}
/* Убедимся, что все элементы занимают всю ширину */
.v-col.pa-0 {
min-width: 0; /* Для правильного flexbox поведения */
}
.v-text-field,
.v-select {
width: 100%;
}
</style>
@@ -0,0 +1,605 @@
<template>
<v-card class="home-calendar-widget" elevation="2" rounded="lg">
<v-card-text class="pa-4">
<v-row no-gutters class="calendar-pair">
<!-- Месячный календарь -->
<v-col cols="7" class="pr-2">
<div class="calendar-header">
<v-btn icon size="small" @click="prevMonth" class="nav-btn">
<v-icon>mdi-chevron-left</v-icon>
</v-btn>
<span class="month-title">{{ currentMonth }}</span>
<v-btn icon size="small" @click="nextMonth" class="nav-btn">
<v-icon>mdi-chevron-right</v-icon>
</v-btn>
</div>
<v-table class="month-table">
<thead>
<tr>
<th v-for="day in russianWeekdays" :key="day" class="weekday-header">
{{ day }}
</th>
</tr>
</thead>
<tbody>
<tr v-for="(week, weekIndex) in calendarWeeks" :key="weekIndex">
<td
v-for="day in week"
:key="day.date"
class="day-cell"
:class="{
'current-month': day.isCurrentMonth,
today: isToday(day.date),
selected: isSelected(day.date),
'non-working-day': calendarStore.isNonWorkingDay(day.date).isHoliday,
'grey-background': calendarStore.isNonWorkingDay(day.date).isWeekendForStyling,
}"
@click="onDateClick(day.date)"
>
<div class="day-content">
<span class="day-number">{{ day.day }}</span>
<div class="day-events">
<span
v-for="event in getDayEvents(day.date)"
:key="event.id"
class="event-indicator"
:style="{ backgroundColor: event.color }"
></span>
</div>
</div>
</td>
</tr>
</tbody>
</v-table>
</v-col>
<!-- Дневное расписание -->
<v-col cols="5" class="pl-2">
<div class="schedule-header">
<h3 class="day-title">
<span v-if="isToday(selectedDate)">Сегодня, </span>{{ formattedSelectedDate }}
</h3>
</div>
<v-card variant="outlined" class="day-schedule" elevation="0">
<v-list density="comfortable" class="py-0">
<v-list-item
v-for="event in dayEvents"
:key="event.id"
class="schedule-item"
:class="{ 'current-event': isCurrentEvent(event) }"
>
<template #prepend>
<div
class="event-color-indicator"
:style="{ backgroundColor: event.color }"
></div>
</template>
<v-list-item-title class="event-time">
{{ formatTime(event.start) }}
</v-list-item-title>
<v-list-item-subtitle class="event-title">
{{ event.title }}
</v-list-item-subtitle>
</v-list-item>
<v-list-item v-if="dayEvents.length === 0" class="no-events">
<v-list-item-title class="text-grey text-center">
На этот день событий нет
</v-list-item-title>
</v-list-item>
</v-list>
</v-card>
</v-col>
</v-row>
</v-card-text>
</v-card>
</template>
<script>
import { ref, computed, onMounted, watch } from 'vue';
import { storeToRefs } from 'pinia';
import { useCalendarStore } from '@/store/calendarStore';
import { useRecurrence } from '@/components/calendar_of_events/composables/useReccurrence';
export default {
name: 'HomeCalendarWidget',
setup() {
// Реактивные данные
const currentDate = ref(new Date());
const selectedDate = ref(''); // Будет установлено в формате YYYY-MM-DD
const currentYear = new Date().getFullYear();
// Работа с хранилищем
const calendarStore = useCalendarStore();
const { allEvents, calendarColorMap } = storeToRefs(calendarStore);
const { generateRecurringInstances, isRecurringEvent } = useRecurrence();
// Утилиты для работы с датами (главный источник проблем!)
const formatToLocalDate = (date) => {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
};
const getStartOfDay = (date) => {
const newDate = new Date(date);
newDate.setHours(0, 0, 0, 0);
return newDate;
};
const areDatesEqual = (date1, date2) => {
return getStartOfDay(date1).getTime() === getStartOfDay(date2).getTime();
};
const events = computed(() => {
const expandedEvents = allEvents.value.flatMap((event) => {
const startDate = new Date(event.date_start);
const endDate = new Date(event.date_end);
const isMultiDay = startDate.toDateString() !== endDate.toDateString();
const hasRecurrence = event.period && event.period !== 'null';
// 1. Периодичное + многодневное
if (hasRecurrence && isMultiDay) {
const instances = generateRecurringInstances(event, 12);
return instances.flatMap((instance) => expandMultiDayInstance(event, instance));
}
// 2. Периодичное + однодневное
if (hasRecurrence && !isMultiDay) {
const instances = generateRecurringInstances(event, 12);
return instances.map((instance) => ({
...event,
id: instance.id,
date_start: instance.date_start || instance.start,
date_end: instance.date_end || instance.end,
isRecurringInstance: true,
}));
}
// 3. Непериодичное + многодневное
if (!hasRecurrence && isMultiDay) {
return expandMultiDayInstance(event, event);
}
// 4. Непериодичное + однодневное
return event;
});
return expandedEvents.map((event) => formatForWidget(event));
});
// Разбивает многодневный экземпляр на дни
const expandMultiDayInstance = (originalEvent, instance) => {
const startDate = new Date(instance.date_start || instance.start);
const endDate = new Date(instance.date_end || instance.end);
const days = [];
const currentDay = new Date(startDate);
while (currentDay < endDate) {
const dayStart = new Date(currentDay);
const dayEnd = new Date(currentDay);
dayEnd.setDate(dayEnd.getDate() + 1);
days.push({
...originalEvent,
id: instance.id, // ID от экземпляра периодичности
date_start: dayStart.toISOString(),
date_end: dayEnd.toISOString(),
allday: true,
isMultiDayPart: true,
isRecurringInstance: instance.isRecurringInstance || false,
originalStart: instance.date_start || instance.start,
originalEnd: instance.date_end || instance.end,
});
currentDay.setDate(currentDay.getDate() + 1);
}
return days;
};
// Форматирование для виджета
const formatForWidget = (event) => {
const eventColor =
event.calendarData?.cl_color || calendarColorMap.value?.get(event.calendar) || '#1976d2';
return {
id: event.id,
title: event.name || 'Без названия',
start: event.date_start,
end: event.date_end,
description: event.description,
color: eventColor,
calendar: event.calendar,
calendarData: event.calendarData,
isRecurringInstance: event.isRecurringInstance || false,
isMultiDayPart: event.isMultiDayPart || false,
};
};
const russianWeekdays = ['Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс'];
// Генерация календаря
const calendarWeeks = computed(() => {
const year = currentDate.value.getFullYear();
const month = currentDate.value.getMonth();
const firstDay = new Date(year, month, 1);
const lastDay = new Date(year, month + 1, 0);
const weeks = [];
let week = [];
// Находим понедельник первой недели
const startDay = new Date(firstDay);
startDay.setDate(startDay.getDate() - ((startDay.getDay() + 6) % 7));
// Генерируем 6 недель (фиксированное количество для стабильности)
for (let i = 0; i < 42; i++) {
const currentDay = new Date(startDay);
currentDay.setDate(startDay.getDate() + i);
week.push({
day: currentDay.getDate(),
date: formatToLocalDate(currentDay),
isCurrentMonth: currentDay.getMonth() === month,
});
if (week.length === 7) {
weeks.push([...week]);
week = [];
}
}
return weeks;
});
const currentMonth = computed(() => {
return currentDate.value.toLocaleDateString('ru-RU', {
month: 'long',
year: 'numeric',
});
});
const formattedSelectedDate = computed(() => {
if (!selectedDate.value) return '';
// Добавляем время для избежания смещения часовых поясов
const date = new Date(selectedDate.value + 'T12:00:00');
return date.toLocaleDateString('ru-RU', {
day: 'numeric',
month: 'long',
year: 'numeric',
});
});
const dayEvents = computed(() => {
if (!selectedDate.value) return [];
const selected = new Date(selectedDate.value + 'T12:00:00');
return events.value
.filter((event) => {
const eventDate = new Date(event.start);
return areDatesEqual(eventDate, selected);
})
.sort((a, b) => new Date(a.start).getTime() - new Date(b.start).getTime());
});
// Методы
const isToday = (date) => {
const today = new Date();
const checkDate = new Date(date + 'T12:00:00');
return areDatesEqual(today, checkDate);
};
const isSelected = (date) => {
return date === selectedDate.value;
};
const getDayEvents = (date) => {
const checkDate = new Date(date + 'T12:00:00');
return events.value.filter((event) => {
const eventDate = new Date(event.start);
return areDatesEqual(eventDate, checkDate);
});
};
const isCurrentEvent = (event) => {
const now = new Date();
const start = new Date(event.start);
const end = new Date(event.end);
return now >= start && now <= end;
};
const formatTime = (dateString) => {
return new Date(dateString).toLocaleTimeString('ru-RU', {
hour: '2-digit',
minute: '2-digit',
});
};
const onDateClick = (date) => {
selectedDate.value = date;
};
const prevMonth = () => {
const date = new Date(currentDate.value);
date.setMonth(date.getMonth() - 1);
currentDate.value = date;
};
const nextMonth = () => {
const date = new Date(currentDate.value);
date.setMonth(date.getMonth() + 1);
currentDate.value = date;
};
const isWeekendOrHoliday = (dateString) => {
const dayInfo = calendarStore.isNonWorkingDay(dateString);
return dayInfo.isHoliday || dayInfo.isWeekendForStyling;
};
onMounted(async () => {
selectedDate.value = formatToLocalDate(new Date());
calendarStore.fetchHolidays(currentYear);
});
watch(
calendarColorMap,
(newMap) => {
newMap.value;
},
{ deep: true },
);
return {
// Реактивные данные
currentDate,
selectedDate,
// Вычисляемые свойства
events,
russianWeekdays,
calendarWeeks,
currentMonth,
formattedSelectedDate,
dayEvents,
isWeekendOrHoliday,
// Методы
isToday,
isSelected,
getDayEvents,
isCurrentEvent,
formatTime,
onDateClick,
prevMonth,
nextMonth,
calendarStore,
allEvents,
expandMultiDayInstance,
formatForWidget,
};
},
};
</script>
<style scoped>
.home-calendar-widget {
width: 100%;
/* width: 700px; */
height: 100%;
font-family: 'Roboto', sans-serif;
}
.calendar-pair {
height: 100%;
}
/* Месячный календарь */
.calendar-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 12px;
padding: 0 8px;
}
.month-title {
font-size: 1.1rem;
font-weight: 600;
color: #333;
text-transform: capitalize;
}
.nav-btn {
width: 28px;
height: 28px;
}
.month-table {
width: 100%;
height: 100%;
}
.weekday-header {
font-size: 0.8rem;
font-weight: 600;
color: #666;
text-align: center;
padding: 8px 4px;
border-bottom: 1px solid #afadad;
}
.day-cell {
width: 14.28%;
height: 15%;
/* height: 50px; */
text-align: center;
cursor: pointer;
border: 1px solid transparent;
transition: all 0.2s ease;
}
.day-cell:hover {
background-color: #f5f5f5;
}
.day-cell.current-month {
color: #333;
}
.day-cell:not(.current-month) {
color: #ccc;
}
.day-cell.today {
background-color: #e3f2fd;
}
.day-cell.selected {
background-color: #00897b;
color: white;
}
.day-cell.selected .day-number {
color: white;
}
.day-content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100%;
padding: 2px;
}
.day-number {
font-size: 0.9rem;
font-weight: 500;
margin-bottom: 2px;
}
.day-events {
display: flex;
gap: 2px;
justify-content: center;
}
.event-indicator {
width: 6px;
height: 6px;
border-radius: 50%;
display: block;
}
.event-color-indicator {
width: 10px;
height: 10px;
border-radius: 50%;
margin-right: 12px;
flex-shrink: 0;
box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1);
}
/* Дневное расписание */
.schedule-header {
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 12px;
padding: 0 4px;
}
.day-title {
font-size: 1.2rem;
font-weight: 600;
margin: 0;
color: #333;
}
.day-schedule {
height: 90%;
overflow-y: auto;
border: 1px solid #e0e0e0;
border-radius: 8px;
}
.schedule-item {
min-height: 48px;
padding: 8px 12px;
border-left: 4px solid transparent;
border-bottom: 1px solid #d3cecede;
}
.schedule-item:last-child {
border-bottom: none;
}
.schedule-item.current-event {
border-left-color: #2196f3;
background-color: #f8f9fa;
}
.event-time {
font-size: 0.8rem;
font-weight: 600;
color: #302f2f;
margin-bottom: 2px;
}
.event-title {
font-size: 0.9rem;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
color: #1b1b1b;
}
.no-events {
min-height: 120px;
display: flex;
align-items: center;
justify-content: center;
}
/* Скроллбар */
.day-schedule::-webkit-scrollbar {
width: 6px;
}
.day-schedule::-webkit-scrollbar-track {
background: #f1f1f1;
border-radius: 0 8px 8px 0;
}
.day-schedule::-webkit-scrollbar-thumb {
background: #c1c1c1;
border-radius: 3px;
}
.day-schedule::-webkit-scrollbar-thumb:hover {
background: #a8a8a8;
}
.non-working-day {
color: red !important;
}
.grey-background {
background-color: rgb(243, 243, 243) !important;
}
.day-cell:not(.current-month).non-working-day {
/* color: inherit !important; */
}
</style>
@@ -0,0 +1,288 @@
<template>
<v-card class="h-100 rounded-0 d-flex flex-colmn">
<v-row no-gutters class="flex-column">
<v-col class="flex-grow-0 px-2 pt-1">
<SearchEvents />
</v-col>
<v-col class="flex-grow-0 px-2">
<v-btn
type="submit"
class="text-subtitle-1 font-weight-light"
color="btn_text"
block
elevation="1"
@click="openEventDialog"
:disabled="!myCalendars || myCalendars.length === 0"
>Создать событие</v-btn
>
</v-col>
<v-col lg="3">
<v-locale-provider locale="ru">
<v-date-picker
v-model="selectedDate"
color="btn_text"
class="rounded-0 minCal"
hide-header
show-adjacent-months
@update:modelValue="handleDateClick"
@update:display="currentDisplay = $event"
>
</v-date-picker>
</v-locale-provider>
</v-col>
<v-col class="flex-column d-flex">
<v-row no-gutters class=" overflow-hidden flex-column flex-nowrap">
<v-col>
<calendar-my
:calendars="myCalendars"
title="Мои календари"
@getCalendar="loadCalendars"
/>
<calendar-my
:calendars="subscribedCalendars"
title="Подписки"
@getCalendar="loadCalendars"
/>
</v-col>
</v-row>
</v-col>
</v-row>
</v-card>
</template>
<script>
import { useCalendarStore } from '@/store/calendarStore';
import { useAccountStore } from '@/store/AccountStore';
import CalendarMy from '@/components/calendar_of_events/calendar-my.vue';
import SearchEvents from '@/components/calendar_of_events/UI_calendar/SearchEvents.vue';
import { onMounted, watch, nextTick, ref } from 'vue';
import { storeToRefs } from 'pinia';
export default {
name: 'MiniCalendar',
components: { CalendarMy, SearchEvents },
setup() {
const calendarStore = useCalendarStore();
const accountStore = useAccountStore();
const { selectedDate, myCalendars, subscribedCalendars } = storeToRefs(calendarStore);
const { user } = storeToRefs(accountStore);
const currentDisplay = ref(null);
const handleDateClick = (date) => {
calendarStore.setSelectedDateFromPicker(date);
setTimeout(updateCalendarDays, 200);
};
const openEventDialog = () => {
calendarStore.openEventDialog();
};
const loadCalendars = () => {
calendarStore.loadCalendars();
};
onMounted(() => {
loadCalendars();
updateCalendarDays();
});
// Реакция на изменения пользователя
watch(user, (newUser) => {
if (newUser) {
loadCalendars();
}
});
// Функция для добавления классов дням
const updateCalendarDays = () => {
nextTick(() => {
setTimeout(() => {
const dayButtons = document.querySelectorAll('.minCal .v-date-picker-month__day-btn');
dayButtons.forEach((button) => {
// Ищем дату в разных возможных атрибутах
const ariaLabel = button.getAttribute('aria-label');
if (ariaLabel) {
try {
const dayDate = parseDateFromAriaLabel(ariaLabel);
if (dayDate) {
const dayInfo = calendarStore.isNonWorkingDay(dayDate);
// Очищаем предыдущие классы
button.classList.remove('weekend-day', 'holiday-day');
// Добавляем классы по условию
if (dayInfo?.isWeekendForStyling) {
button.classList.add('weekend-day');
}
if (dayInfo?.isHoliday) {
button.classList.add('holiday-day');
}
}
} catch (error) {
console.error('Error processing day:', error);
}
}
});
}, 50);
});
};
const parseDateFromAriaLabel = (ariaLabel) => {
try {
// Убираем день недели и запятую, оставляем "28 сентября 2025 г."
const datePart = ariaLabel.replace(/^[^,]+,?\s*/, '');
// Заменяем русские названия месяцев на английские
const monthMap = {
января: 'January',
февраля: 'February',
марта: 'March',
апреля: 'April',
мая: 'May',
июня: 'June',
июля: 'July',
августа: 'August',
сентября: 'September',
октября: 'October',
ноября: 'November',
декабря: 'December',
};
let englishDateStr = datePart;
for (const [ru, en] of Object.entries(monthMap)) {
englishDateStr = englishDateStr.replace(ru, en);
}
// Убираем " г." в конце
englishDateStr = englishDateStr.replace(' г.', '');
const dayDate = new Date(englishDateStr);
return isNaN(dayDate.getTime()) ? null : dayDate;
} catch (error) {
console.error('Parse error:', error);
return null;
}
};
watch(
[selectedDate, currentDisplay],
() => {
updateCalendarDays();
},
{ deep: true, immediate: true },
);
watch(
[myCalendars, subscribedCalendars],
() => {
updateCalendarDays();
},
{ deep: true },
);
// При смене месяца через кнопки навигации
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (mutation.type === 'childList') {
updateCalendarDays();
}
});
});
onMounted(() => {
// Наблюдаем за изменениями в DOM date-picker
const datePicker = document.querySelector('.minCal');
if (datePicker) {
observer.observe(datePicker, { childList: true, subtree: true });
}
});
return {
accountStore,
user,
myCalendars,
subscribedCalendars,
selectedDate,
openEventDialog,
loadCalendars,
handleDateClick,
updateCalendarDays,
currentDisplay,
};
},
};
</script>
<style scoped>
/* .minCal:deep(.v-date-picker-month__days) {
display: grid !important;
grid-template-columns: repeat(7, 40px) !important;
gap: 3px !important;
width: 250px !important;
justify-content: center !important;
margin: 0 auto !important;
} */
.minCal .v-date-picker-monWth__day {
height: 31px;
width: 31px;
}
.minCal .v-btn--icon.v-btn--density-default {
width: calc(var(--v-btn-height) + 12px);
height: calc(var(--v-btn-height) + 6px);
}
.minCal .v-btn__content {
font-weight: 410;
}
.minCal:deep(.v-date-picker-years__content) {
gap: 0;
}
/* СТИЛИ ДЛЯ ВЫХОДНЫХ И ПРАЗДНИКОВ */
.minCal:deep(.weekend-day .v-btn__content) {
color: #666 !important;
}
.minCal:deep(.holiday-day .v-btn__content) {
color: #ff4444 !important;
font-weight: bold !important;
}
.minCal:deep(.weekend-day.holiday-day) {
background-color: #ffe0e0 !important;
}
.minCal:deep(.weekend-day.holiday-day .v-btn__content) {
color: #cc0000 !important;
}
search-dropdown {
max-height: 300px;
overflow-y: auto;
}
/* Стили для скроллбара */
.search-dropdown::-webkit-scrollbar {
width: 4px;
}
.search-dropdown::-webkit-scrollbar-track {
background: #f1f1f1;
}
.search-dropdown::-webkit-scrollbar-thumb {
background: #888;
border-radius: 2px;
}
</style>
@@ -0,0 +1,207 @@
<template>
<div class="search-events-wrapper" ref="searchContainerRef">
<v-text-field
v-model="searchQuery"
density="compact"
clearable
append-inner-icon="mdi-magnify"
hide-details
class="py-3"
label="Найти событие"
rows="1"
no-resize
variant="outlined"
@click:clear="clearSearch"
@focus="showResults = true"
@keydown.esc="hideResults"
/>
<div v-if="searchQuery" class="search-overlay" @click="closeResults"></div>
<!-- Выпадающий список результатов -->
<v-card class="search-dropdown mt-1" elevation="4">
<v-list density="compact" class="py-0">
<v-list-item
v-for="event in filteredEvents"
:key="event.id"
@click="selectEvent(event)"
class="px-2"
>
<v-list-item-title class="text-body-2">
{{ event.name }}
</v-list-item-title>
<v-list-item-subtitle class="text-caption">
{{ formatEventDate(event) }}
• {{ event.calendarData?.cl_name }}
</v-list-item-subtitle>
</v-list-item>
</v-list>
</v-card>
<!-- Сообщение "не найдено" -->
<v-card
v-if="searchQuery && filteredEvents.length === 0"
class="search-dropdown mt-1"
elevation="4"
>
<v-list density="compact" class="py-0">
<v-list-item>
<v-list-item-title class="text-body-2 text-center text-disabled">
События не найдены
</v-list-item-title>
</v-list-item>
</v-list>
</v-card>
</div>
</template>
<script setup>
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue';
import { useCalendarStore } from '@/store/calendarStore.js';
const calendarStore = useCalendarStore();
// Reactive data
const searchQuery = ref('');
const showResults = ref(false);
const searchContainerRef = ref(null);
const shouldShowDropdown = computed(() => {
return showResults.value && searchQuery.value;
});
const filteredEvents = ref([]);
const performSearch = () => {
if (!searchQuery.value) {
filteredEvents.value = [];
return;
}
if (!calendarStore.allEvents) {
filteredEvents.value = [];
return;
}
const query = searchQuery.value.toLowerCase().trim();
filteredEvents.value = calendarStore.allEvents
.filter((event) => {
return (
event.name?.toLowerCase().includes(query) ||
event.description?.toLowerCase().includes(query) ||
event.calendarData?.cl_name?.toLowerCase().includes(query)
);
})
.slice(0, 8);
};
watch(
searchQuery,
() => {
performSearch();
},
{ immediate: true },
);
const closeResults = () => {
showResults.value = false;
};
const hideResults = () => {
showResults.value = false;
};
const clearSearch = () => {
searchQuery.value = '';
showResults.value = false;
};
const formatEventDate = (event) => {
try {
const start = new Date(event.date_start);
return `${start.toLocaleDateString('ru-RU')} • ${formatTime(event.date_start)}`;
} catch {
return 'Дата неизвестна';
}
};
const formatTime = (dateString) => {
try {
return new Date(dateString).toLocaleTimeString('ru-RU', {
hour: '2-digit',
minute: '2-digit',
});
} catch {
return '--:--';
}
};
const selectEvent = (event) => {
calendarStore.setSelectedDate(event.date_start, 'search');
searchQuery.value = '';
closeResults();
};
// Click outside handler
const handleClickOutside = (event) => {
if (showResults.value) {
closeResults();
}
};
onMounted(() => {
document.addEventListener('click', handleClickOutside);
performSearch();
// Дополнительно через nextTick
nextTick(() => {
if (searchQuery.value) {
performSearch();
}
});
});
onUnmounted(() => {
document.removeEventListener('click', handleClickOutside);
});
</script>
<style scoped>
.search-events-wrapper {
position: relative;
z-index: 100;
}
.search-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
z-index: 999;
background: transparent;
}
.search-dropdown {
position: absolute;
top: 80%;
left: 0;
right: 0;
max-height: 400px;
overflow-y: auto;
margin-top: 4px;
z-index: 1001;
background: white;
}
.search-dropdown::-webkit-scrollbar {
width: 4px;
}
.search-dropdown::-webkit-scrollbar-track {
background: #f1f1f1;
}
.search-dropdown::-webkit-scrollbar-thumb {
background: #888;
border-radius: 2px;
}
</style>
@@ -93,7 +93,7 @@ export default {
{ type: "day", text: "День" }, { type: "day", text: "День" },
{ type: "week", text: "Неделя" }, { type: "week", text: "Неделя" },
{ type: "month", text: "Месяц" }, { type: "month", text: "Месяц" },
{ type: "modntdh", text: "Год" }, // { type: "modntdh", text: "Год" },
{ type: "modnth", text: "Расписание" }, { type: "modnth", text: "Расписание" },
]; ];
@@ -314,7 +314,7 @@ export default {
ev.rule.byweekday[ev.rule.byweekday.length - 1].weekday == 6 ev.rule.byweekday[ev.rule.byweekday.length - 1].weekday == 6
? 0 ? 0
: ev.rule.byweekday[ev.rule.byweekday.length - 1].weekday + 1; : ev.rule.byweekday[ev.rule.byweekday.length - 1].weekday + 1;
if (day.date.getDay() == weeknumS && weeknumS != weeknumE) { if (day.date.getDay() == weeknumS && weeknumS != weeknumE) {
return "rounded-e-lg"; return "rounded-e-lg";
} else if (day.date.getDay() == weeknumE && weeknumS != weeknumE) { } else if (day.date.getDay() == weeknumE && weeknumS != weeknumE) {
@@ -328,7 +328,7 @@ export default {
return "rounded-lg"; return "rounded-lg";
} }
} }
if (ev.rule.freq == 0) { if (ev.rule.freq == 0) {
if (zeroTime(day.date) == zeroTime(ev.start_event)) { if (zeroTime(day.date) == zeroTime(ev.start_event)) {
@@ -342,7 +342,7 @@ export default {
// ev.rule.byweekday[ev.rule.byweekday.length - 1].weekday == 6 // ev.rule.byweekday[ev.rule.byweekday.length - 1].weekday == 6
// ? 0 // ? 0
// : ev.rule.byweekday[ev.rule.byweekday.length - 1].weekday + 1; // : ev.rule.byweekday[ev.rule.byweekday.length - 1].weekday + 1;
// if (day.date.getDay() == weeknumS && weeknumS != weeknumE) { // if (day.date.getDay() == weeknumS && weeknumS != weeknumE) {
// return "rounded-e-lg"; // return "rounded-e-lg";
// } else if (day.date.getDay() == weeknumE && weeknumS != weeknumE) { // } else if (day.date.getDay() == weeknumE && weeknumS != weeknumE) {
@@ -1,5 +1,5 @@
<template> <template>
<v-card min-height="436" class="pa-3"> <v-card min-height="436" max-height="80%" class="pa-3" max-width="50vw">
<v-card-title class="pr-0 pl-2 d-flex justify-space-between"> <v-card-title class="pr-0 pl-2 d-flex justify-space-between">
{{ title }} {{ title }}
<v-icon <v-icon
@@ -22,23 +22,14 @@
size="36px" size="36px"
@click="$emit('delObject')" @click="$emit('delObject')"
/> />
<!-- <v-btn <v-btn
class="text-subtitle-1"
elevation="0"
width="150"
@click="clearValidation"
color="btn_gray"
variant="flat"
>резет</v-btn
> -->
<!-- <v-btn @click="clearFormValidation"></v-btn> -->
<v-btn
class="text-subtitle-1" class="text-subtitle-1"
elevation="0" elevation="0"
width="150" width="150"
@click="$emit('closeDialog')" @click="$emit('closeDialog')"
color="btn_gray" color="btn_gray"
variant="flat" variant="flat"
type="button"
>Отменить</v-btn >Отменить</v-btn
> >
@@ -48,9 +39,9 @@
variant="flat" variant="flat"
elevation="0" elevation="0"
width="150" width="150"
type="transformation" type="submit"
> >
{{ newOrOld ? "Создать" : "Редактировать" }} {{ newOrOld ? "Создать" : "Сохранить" }}
</v-btn> </v-btn>
</v-card-actions> </v-card-actions>
</v-form> </v-form>
@@ -2,10 +2,10 @@
<v-col lg="3" :class="`order-${order[0]}`"> <v-col lg="3" :class="`order-${order[0]}`">
<v-menu <v-menu
v-model="menudate" v-model="menudate"
:close-on-content-click="false"
:nudge-right="40" :nudge-right="40"
transition="scale-transition" transition="scale-transition"
offset-y offset-y
:close-on-content-click="false"
> >
<template v-slot:activator="{ props }"> <template v-slot:activator="{ props }">
<v-textarea <v-textarea
@@ -21,12 +21,7 @@
hide-details hide-details
> >
<template v-slot:prepend-inner> <template v-slot:prepend-inner>
<v-icon <v-icon v-bind="props" icon="mdi-calendar-today" color="cyan-darken-3" size="x-small" />
v-bind="props"
icon="mdi-calendar-today"
color="cyan-darken-3"
size="x-small"
/>
</template> </template>
</v-textarea> </v-textarea>
</template> </template>
@@ -38,13 +33,13 @@
hide-header hide-header
border border
no-time no-time
:max="order[0] == 2 ? new Date(limitation) : endMax()" :max="endMax()"
:min="order[0] == 2 ? startMin() : minData()" :min="order[0] == 2 ? startMin() : minData()"
/> />
</v-locale-provider> </v-locale-provider>
</v-menu> </v-menu>
</v-col> </v-col>
<v-col class="flex-grow-0" :class="`order-${order[1]}`"> <v-col class="flex-grow-0" :class="`order-${order[1]}`" v-if="showTime">
<v-textarea <v-textarea
density="compact" density="compact"
no-resize no-resize
@@ -68,7 +63,8 @@
> >
<v-time-picker <v-time-picker
v-if="menutime" v-if="menutime"
v-model="timeEvent" :model-value="timeEvent"
@update:model-value="onTimePickerChange"
full-width full-width
format="24hr" format="24hr"
></v-time-picker> ></v-time-picker>
@@ -77,18 +73,18 @@
</template> </template>
<script> <script>
import { ref, computed } from "vue"; import { ref, computed, watch } from 'vue';
import { formatComa, formatDash } from "@/utils/universal_functions"; import { formatComa } from '@/utils/universal_functions';
export default { export default {
props: { props: {
dateEvent: { dateEvent: {
type: String, type: String,
default: "", default: '',
}, },
limitation: { limitation: {
type: String, type: String,
default: "", default: '',
}, },
order: { order: {
@@ -103,15 +99,33 @@ export default {
type: Number, type: Number,
default: -1, default: -1,
}, },
isStart: {
type: Boolean,
default: false,
},
// Новый проп - ограничение по времени (для окончания повторений)
timeLimit: {
type: String,
default: '23:59',
},
// Новый проп - режим работы (обычный или для окончания повторений)
showTime: {
type: Boolean,
default: true,
},
}, },
emits: ['update:dateEvent', 'adjustEndDate'],
setup(props, { emit }) { setup(props, { emit }) {
const menudate = ref(false); const menudate = ref(false);
const menutime = ref(false); const menutime = ref(false);
const propsDateEvent = computed({ const propsDateEvent = computed({
get: () => new Date(props.dateEvent), get: () => new Date(props.dateEvent),
set: (value) => emit("update:dateEvent", value), set: (value) => {
emit('update:dateEvent', value);
},
}); });
const modelDate = computed({ const modelDate = computed({
@@ -119,83 +133,99 @@ export default {
return propsDateEvent.value; return propsDateEvent.value;
}, },
set(newValue) { set(newValue) {
creatwdDate(newValue, timeEvent.value); createdDate(newValue, timeEvent.value);
}, },
}); });
const timeEvent = computed({ const timeEvent = computed({
get() { get() {
return `${new Date(propsDateEvent.value).getHours()}:${String( const date = new Date(propsDateEvent.value);
new Date(propsDateEvent.value).getMinutes() const time = `${date.getHours()}:${String(date.getMinutes()).padStart(2, '0')}`;
).padStart(2, "0")}`; return time;
}, },
set(newValue) { set(newValue) {
creatwdDate(modelDate.value, newValue); applyTimeChange(newValue);
}, },
}); });
const creatwdDate = (date, time) => { // Новый метод для применения изменений времени
let tzero = time.split(":"); const applyTimeChange = (newTime) => {
time = tzero[0].padStart(2, "0") + ":" + tzero[1]; const [hours, minutes] = newTime.split(':').map(Number);
const newDate = new Date(propsDateEvent.value);
newDate.setHours(hours, minutes, 0, 0);
// Бизнес-логика из createdDate
if (props.order[0] == 4) { if (props.order[0] == 4) {
if (time == "0:00") { const startDate = new Date(props.limitation);
propsDateEvent.value = date; if (newDate <= startDate) {
} else if ( const correctedDate = new Date(startDate);
new Date(formatDash(date) + "T" + time) >= new Date(props.limitation) correctedDate.setHours(startDate.getHours() + 1);
) { propsDateEvent.value = correctedDate;
propsDateEvent.value = new Date(formatDash(date) + "T" + time);
} else { } else {
propsDateEvent.value = new Date(props.limitation); propsDateEvent.value = newDate;
} }
} else { } else {
propsDateEvent.value = propsDateEvent.value = newDate;
time == "0:00" ? date : new Date(formatDash(date) + "T" + time); const currentEnd = new Date(props.limitation);
if (newDate > currentEnd) {
const newEnd = new Date(newDate);
newEnd.setHours(newDate.getHours() + 1);
emit('adjustEndDate', newEnd.toISOString());
}
} }
}; };
const onTimePickerChange = (newTime) => {
// Применяем изменения времени сразу
applyTimeChange(newTime);
// Меню НЕ закрываем - пользователь может продолжить выбирать время
};
const createdDate = (date, time) => {
const [hours, minutes] = time.split(':').map(Number);
const newDate = new Date(date);
newDate.setHours(hours, minutes, 0, 0);
if (props.order[0] == 4) {
const startDate = new Date(props.limitation);
if (newDate <= startDate) {
const correctedDate = new Date(startDate);
correctedDate.setHours(startDate.getHours() + 1);
propsDateEvent.value = correctedDate;
} else {
propsDateEvent.value = newDate;
}
} else {
propsDateEvent.value = newDate;
const currentEnd = new Date(props.limitation);
if (newDate > currentEnd) {
const newEnd = new Date(newDate);
newEnd.setHours(newDate.getHours() + 1);
emit('adjustEndDate', newEnd.toISOString());
}
}
menudate.value = false;
menutime.value = false;
};
const minData = () => { const minData = () => {
let h = `${new Date(props.limitation).getHours()}:${String( return new Date(props.limitation);
new Date(props.limitation).getMinutes()
).padStart(2, "0")}`;
let min =
h == "0:00"
? new Date(props.limitation)
: new Date(
new Date(props.limitation).setDate(
new Date(props.limitation).getDate() - 1
)
);
return new Date(min);
}; };
const startMin = () => { const startMin = () => {
if (props.rule == 2) { return new Date(); // ← По умолчанию: нельзя выбрать прошедшие даты
return new Date(
new Date(props.limitation).setDate(
new Date(props.limitation).getDate() - 7
)
);
}
return false;
}; };
const endMax = () => { const endMax = () => {
if (props.rule == 2) { return null; // ← Без ограничения сверху
return new Date(
new Date(props.limitation).setDate(
new Date(props.limitation).getDate() + 6
)
);
}
return false;
}; };
return { return {
propsDateEvent, propsDateEvent,
menudate, menudate,
menutime, menutime,
onTimePickerChange,
modelDate, modelDate,
formatComa, formatComa,
timeEvent, timeEvent,
@@ -1,100 +1,136 @@
<template> <template>
<!-- --> <div>
<v-autocomplete <!-- -->
v-model="selectedStaff"
:items="staffed"
label="Выберите из списка или найдите по ФИО"
item-title="title"
item-value="id"
:custom-filter="onFilter"
@update:search="(val) => (filtered = val)"
multiple
hide-details
variant="outlined"
density="compact"
class="max-height-select py-3"
return-object
>
<template v-slot:selection="{ item }">
<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"
icon="mdi-close-circle"
size="x-small"
class="ml-3"
@click.stop="selectedStaff = item.raw"
/>
</v-chip>
</template>
<template v-slot:prepend-item>
<v-list-item
@click.stop="allUser()"
:disabled="staffed.length == 1 && staffed[0].employees.length == 1"
class="text-body-2"
>
<span class="text-body-2"> ВСЕ СОТРУДНИКИ </span>
<template v-slot:prepend>
<v-checkbox-btn
:model-value="staffed.every((e) => e[okey] == true)"
:disabled="staffed.length == 1 && staffed[0].employees.length == 1"
></v-checkbox-btn>
</template>
</v-list-item>
<v-divider class="mt-2"></v-divider>
</template>
<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">
<template v-slot:prepend>
<v-checkbox-btn
@click.stop="selectedStaff = item.raw"
:color="'indigo-darken-4'"
:true-value="true"
:false-value="false"
:disabled="disable(item.raw)"
:indeterminate="
item.raw.employees.some((e) => e[okey] == true) &&
!item.raw.employees.every((e) => e[okey] == true)
"
:model-value="item.raw[okey]"
></v-checkbox-btn>
</template>
</v-list-item>
</template>
<v-autocomplete
v-model="selectedStaff"
:items="staffed"
label="Выберите из списка или найдите по ФИО"
item-title="title"
item-value="id"
:search-input.sync="filtered"
@update:search="(val) => (filtered = val)"
multiple
hide-details
variant="outlined"
density="compact"
class="max-height-select py-3"
return-object
:custom-filter="customFilterFn"
>
<!-- :custom-filter="onFilter" -->
<template v-slot:selection="{ item }">
<v-chip class="me-2" color="teal-darken-3" size="small" label>
<span> {{ item.title }}</span>
<v-icon
v-if="!isAuthor(item.raw)"
icon="mdi-close-circle"
size="x-small"
class="ml-3"
@click.stop="selectedStaff = item.raw"
/>
</v-chip>
</template>
<template v-slot:prepend-item>
<v-list-item <v-list-item
v-for="x in item.raw.employees.filter((e) => :disabled="staffed.length == 1 && staffed[0].employees.length == 1"
e.title.toLowerCase().includes(filtered.toLowerCase()), class="text-body-2"
)" @click.stop="allUser()"
:key="x.id"
:value="x.title"
:disabled="x.id == accountStore.user.is_idEmployee"
@click.stop="selectedStaff = x"
density="compact"
> >
<span class="text-body-2"> ВСЕ СОТРУДНИКИ </span>
<template v-slot:prepend> <template v-slot:prepend>
<v-checkbox-btn <v-checkbox-btn
:disabled="x.id == accountStore.user.is_idEmployee" :model-value="staffed.every((e) => e[okey] == true)"
color="indigo-darken-4" :disabled="staffed.length == 1 && staffed[0].employees.length == 1"
:model-value="x[okey]"
></v-checkbox-btn> ></v-checkbox-btn>
</template> </template>
<span class="text-body-2"> {{ x.title }} </span>
</v-list-item> </v-list-item>
</v-list-group> <!-- ВСЕ НАЧАЛЬНИКИ -->
</template> <v-list-item
</v-autocomplete> :disabled="!hasBossesInStaff"
class="text-body-2"
@click.stop="toggleByPosition('начальник')"
>
<span class="text-body-2"> ВСЕ НАЧАЛЬНИКИ </span>
<template v-slot:prepend>
<v-checkbox-btn
:model-value="hasBossesSelected"
:disabled="!hasBossesInStaff"
></v-checkbox-btn>
</template>
</v-list-item>
<!-- ВСЕ ЗАМЕСТИТЕЛИ -->
<v-list-item
:disabled="!hasDeputiesInStaff"
class="text-body-2"
@click.stop="toggleByPosition('заместитель')"
>
<span class="text-body-2"> ВСЕ ЗАМЕСТИТЕЛИ </span>
<template v-slot:prepend>
<v-checkbox-btn
:model-value="hasDeputiesSelected"
:disabled="!hasDeputiesInStaff"
></v-checkbox-btn>
</template>
</v-list-item>
<v-divider class="mt-2"></v-divider>
</template>
<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">
<template v-slot:prepend>
<v-checkbox-btn
@click.stop="selectedStaff = item.raw"
:color="'indigo-darken-4'"
:true-value="true"
:false-value="false"
:disabled="disable(item.raw) || isAuthor(item.raw)"
:indeterminate="
item.raw.employees.some((e) => e[okey] == true) &&
!item.raw.employees.every((e) => e[okey] == true)
"
:model-value="item.raw[okey]"
></v-checkbox-btn>
</template>
</v-list-item>
</template>
<v-list-item
v-for="x in item.raw.employees.filter((e) =>
e.title.toLowerCase().includes(filtered.toLowerCase()),
)"
:key="x.id"
:value="x.title"
@click.stop="selectedStaff = x"
:disabled=" isAuthor(x)"
density="compact"
>
<template v-slot:prepend>
<v-checkbox-btn
:disabled="isAuthor(x)"
color="indigo-darken-4"
:model-value="x[okey]"
></v-checkbox-btn>
</template>
<span class="text-body-2"> {{ x.title }} </span>
</v-list-item>
</v-list-group>
</template>
</v-autocomplete>
</div>
</template> </template>
<script> <script>
import { ref, computed } from 'vue'; import { ref, computed } from 'vue';
import { storeToRefs } from 'pinia';
import { splitname } from '@/utils/universal_functions'; import { splitname } from '@/utils/universal_functions';
import { useAccountStore } from '@/store/AccountStore'; import { useAccountStore } from '@/store/AccountStore';
import { useCalendarStore } from '@/store/calendarStore';
export default { export default {
props: { props: {
@@ -106,11 +142,19 @@ export default {
type: String, type: String,
default: 'selected', default: 'selected',
}, },
authorID: {
type: Number,
default: null,
},
}, },
setup(props, { emit }) { setup(props, { emit }) {
const filtered = ref(''); const filtered = ref('');
const accountStore = useAccountStore(); const accountStore = useAccountStore();
const calendarStore = useCalendarStore();
const { dictEmployeesLoaded } = storeToRefs(calendarStore);
const back = ref([]); const back = ref([]);
const staffed = computed({ const staffed = computed({
@@ -119,7 +163,9 @@ export default {
let ns = []; let ns = [];
props.staff.forEach((e) => { props.staff.forEach((e) => {
let emp = { ...e }; let emp = { ...e };
emp.employees = e.employees.filter((n) => n.selected == true); emp.employees = e.employees.filter(
(n) => n.selected == true || n.isCurrentUser == true,
);
if (emp.employees.length > 0) ns.push(emp); if (emp.employees.length > 0) ns.push(emp);
}); });
@@ -128,8 +174,10 @@ export default {
e.editor = true; e.editor = true;
} }
}); });
return ns; return ns;
} }
return props.staff; return props.staff;
}, },
}); });
@@ -142,8 +190,14 @@ export default {
e[props.okey] = true; e[props.okey] = true;
selected.push(e); selected.push(e);
} else if (e.employees.length == 1) { } else if (e.employees.length == 1) {
e[props.okey] = true; const singleEmployee = e.employees[0];
selected.push(...e.employees.filter((n) => n[props.okey] == true)); if (singleEmployee[props.okey] === true) {
selected.push(singleEmployee);
}
// Состояние отдела должно вычисляться на основе сотрудника
e[props.okey] = singleEmployee[props.okey] === true;
// e[props.okey] = true;
// selected.push(...e.employees.filter((n) => n[props.okey] == true));
} else { } else {
e[props.okey] = false; e[props.okey] = false;
selected.push(...e.employees.filter((n) => n[props.okey] == true)); selected.push(...e.employees.filter((n) => n[props.okey] == true));
@@ -198,7 +252,7 @@ export default {
const cbstaff = (item, value) => { const cbstaff = (item, value) => {
item.forEach((e) => { item.forEach((e) => {
if (e.id != accountStore.user.is_idEmployee) { if (e.id !== accountStore.user.is_idEmployee) {
e[props.okey] = value; e[props.okey] = value;
} }
if (!('employees' in e)) { if (!('employees' in e)) {
@@ -210,14 +264,33 @@ export default {
}); });
}; };
function onFilter(item, itemText) { const customFilterFn = (item, queryText, itemText) => {
return ( if (!queryText) return true;
item.includes(filtered.value) ||
itemText.raw.employees.some((e) => const searchText = queryText.toLowerCase();
e.title.toLowerCase().includes(filtered.value.toLowerCase()), const target = item.raw || item;
)
); // Создаем Map для быстрого поиска отделов по названию
} const departmentMap = new Map(staffed.value.map((dept) => [dept.title, dept]));
let department;
if (typeof target === 'string') {
// Ищем отдел по названию
department = departmentMap.get(target);
} else if (target.title) {
// Уже имеем объект отдела
department = target;
}
if (department && department.employees) {
return department.employees.some((employee) =>
employee.title?.toLowerCase().includes(searchText),
);
}
return false;
};
const disable = (department) => { const disable = (department) => {
return department.id == accountStore.user.id_dict_department && return department.id == accountStore.user.id_dict_department &&
@@ -226,29 +299,148 @@ export default {
: false; : false;
}; };
// Функция проверки является ли сотрудник создателем
const isAuthor = (item) => {
if (!props.authorID) return false;
// Если это отдел - проверяем всех сотрудников
if ('employees' in item) {
return item.employees.some((emp) => emp.id === props.authorID);
}
// Если это сотрудник - проверяем напрямую
return item.id === props.authorID;
};
const allUser = () => { const allUser = () => {
emitUp(staffed.value); emitUp(staffed.value);
}; };
// Проверяем выбраны ли все начальники (с исключениями)
const hasBossesSelected = computed(() => {
const bosses = findEmployeesByPosition(['начальник', 'и.о'], ['заместитель', 'зам.']);
return bosses.length > 0 && bosses.every((emp) => emp[props.okey] === true);
});
// Проверяем выбраны ли все заместители (с исключениями)
const hasDeputiesSelected = computed(() => {
const deputies = findEmployeesByPosition(['заместитель', 'зам.'], []);
return deputies.length > 0 && deputies.every((emp) => emp[props.okey] === true);
});
// Toggle функция с исключением
const toggleByPosition = (positionType) => {
let keywords = [];
let excludeKeywords = [];
if (positionType === 'начальник') {
keywords = ['начальник', 'и.о'];
excludeKeywords = ['заместитель', 'зам.'];
} else if (positionType === 'заместитель') {
keywords = ['заместитель', 'зам.'];
excludeKeywords = [];
}
const employeesToToggle = findEmployeesByPosition(keywords, excludeKeywords);
const shouldSelect = !employeesToToggle.every((emp) => emp[props.okey] === true);
// if (employeesToToggle.length > 0) {
// employeesToToggle.forEach((employee) => {
// if (employee[props.okey] !== shouldSelect) {
// emitUp(employee);
// }
// });
// }
if (employeesToToggle.length > 0) {
// ФИЛЬТРУЕМ - убираем создателя события из массовых операций
const filteredEmployees = employeesToToggle.filter(
(employee) => employee.id !== props.authorID, //
);
if (filteredEmployees.length > 0) {
filteredEmployees.forEach((employee) => {
if (employee[props.okey] !== shouldSelect) {
selectedStaff.value = employee;
}
});
}
}
};
// Обновленная функция поиска с исключением
const findEmployeesByPosition = (positionKeywords, excludeKeywords = []) => {
const foundEmployees = [];
props.staff.forEach((department) => {
department.employees.forEach((employee) => {
if (department.id == 1) {
return;
}
if (employee.id === accountStore.user.is_idEmployee) {
return;
}
if (props.okey === 'editor' && employee.selected !== true) {
return;
}
const employeeData = calendarStore.dictEmployees.find((de) => de.id === employee.id);
if (employeeData && employeeData.post) {
const post = employeeData.post.toLowerCase();
// Ищем включения и исключения
const hasInclude = positionKeywords.some((keyword) =>
post.includes(keyword.toLowerCase()),
);
const hasExclude = excludeKeywords.some((exclude) =>
post.includes(exclude.toLowerCase()),
);
if (hasInclude && !hasExclude) {
foundEmployees.push(employee);
}
}
});
});
return foundEmployees;
};
// Проверяем есть ли начальники в staff
const hasBossesInStaff = computed(() => {
return (
findEmployeesByPosition(['начальник', 'и.о. начальника'], ['заместитель', 'зам.']).length >
0
);
});
// Проверяем есть ли заместители в staff
const hasDeputiesInStaff = computed(() => {
return (
findEmployeesByPosition(['заместитель начальника', 'зам. начальника', 'заместитель'])
.length > 0
);
});
return { return {
isAuthor,
staffed, staffed,
filtered, filtered,
accountStore, accountStore,
selectedStaff, selectedStaff,
splitname, splitname,
onFilter,
disable, disable,
allUser, allUser,
customFilterFn,
findEmployeesByPosition,
toggleByPosition,
hasBossesInStaff,
hasBossesSelected,
hasDeputiesInStaff,
hasDeputiesSelected,
dictEmployeesLoaded,
}; };
}, },
}; };
</script> </script>
<style>
.max-height-select .v-field__input {
max-height: 300px; /* Установите желаемую максимальную высоту */
overflow-y: auto; /* Добавьте прокрутку, если список превышает максимальную высоту */
overflow-x: hidden;
margin: 5px;
}
</style>
@@ -1,7 +1,7 @@
<template> <template>
<dialog-create <dialog-create
:title="titleCard" :title="titleCard"
:newOrOld="newCalendar" :newOrOld="isNewCalendar"
@closeDialog="$emit('closeDialog')" @closeDialog="$emit('closeDialog')"
@delObject="delCalendar(propsCalendar.id)" @delObject="delCalendar(propsCalendar.id)"
@postData="postCalendar" @postData="postCalendar"
@@ -46,6 +46,7 @@
<calendar-create-select <calendar-create-select
:staff="newStaff" :staff="newStaff"
@returnIdParticant="returnIdParticant" @returnIdParticant="returnIdParticant"
:authorID="calendarAuthorId"
/> </v-col /> </v-col
></v-row> ></v-row>
</v-col> </v-col>
@@ -69,6 +70,7 @@
:staff="newStaff" :staff="newStaff"
:okey="'editor'" :okey="'editor'"
@returnIdParticant="returnIdParticant" @returnIdParticant="returnIdParticant"
:authorID="calendarAuthorId"
/> />
</v-col> </v-col>
<v-col lg="1" class="text-center"> <v-col lg="1" class="text-center">
@@ -109,6 +111,15 @@ export default {
setup(props, { emit }) { setup(props, { emit }) {
const accountStore = useAccountStore(); const accountStore = useAccountStore();
const calendarAuthorId = computed(() => {
// Для нового календаря - текущий пользователь
if (isNewCalendar.value) {
return accountStore.user.is_idEmployee;
}
// Для существующего - автор из props
return propsCalendar.value.author;
});
const returnIdParticant = (idPart) => { const returnIdParticant = (idPart) => {
idPart.staff.forEach((e) => { idPart.staff.forEach((e) => {
let indx = propsCalendar.value.participant.findIndex((l) => l.participant_calendar == e.id); let indx = propsCalendar.value.participant.findIndex((l) => l.participant_calendar == e.id);
@@ -150,20 +161,14 @@ export default {
cl_descr: [(val) => req(val)], cl_descr: [(val) => req(val)],
}; };
const titleCard = ref(''); const isNewCalendar = computed(() => !propsCalendar.value.id);
const newCalendar = ref(false); const isAuthor = computed(() => propsCalendar.value.author === accountStore.user.is_idEmployee);
const calendarNewOrOld = () => { const titleCard = computed(() =>
if ('id' in propsCalendar.value) { isNewCalendar.value ? 'Новый календарь' : 'Редактирование календаря',
titleCard.value = 'Редактирование календаря'; );
if (propsCalendar.value.author != accountStore.user.is_idEmployee) newCalendar.value = true;
} else {
titleCard.value = 'Новый календарь';
newCalendar.value = true; const newCalendar = computed(() => (isNewCalendar.value ? true : !isAuthor.value));
}
};
calendarNewOrOld();
const postCalendar = (val) => { const postCalendar = (val) => {
if (val) { if (val) {
@@ -212,24 +217,41 @@ export default {
}, },
}); });
const color = [ // const color = [
'red', // '#0ea5e9', // Яркий голубой
'pink', // '#3b82f6', // Королевский синий
'deep-orange', // '#10b981', // Изумрудно-зеленый
'amber', // '#f59e0b', // Теплый янтарный
'yellow', // '#ef4444', // Акцентный красный
'lime', // '#8b5cf6', // Фиолетовый
'light-green', // '#4f46e5', // Индиго (профессиональный синий)
'green', // '#06b6d4', // Бирюзовый
'light-blue', // '#84cc16', // Лаймовый
'blue', // '#f97316', // Оранжевый
'indigo', // '#ec4899', // Розовый
'deep-purple', // '#6366f1', // Фиолетово-синий
'purple', // '#14b8a6', // Бирюзово-зеленый
'blue-grey', // '#eab308', // Золотисто-желтый
'brown', // '#22c55e', // Зеленый
]; // ];
const color = [
'#3b82f6', // Синий
'#10b981', // Зеленый
'#dc2626', // Красный
'#d97706', // Оранжевый
'#7c3aed', // Фиолетовый
'#0ea5e9', // Голубой
'#84cc16', // Лаймовый
'#f59e0b', // Янтарный
'#8b5cf6', // Пурпурный
'#06b6d4', // Бирюзовый
'#f97316', // Теплый оранжевый
'#6366f1', // Фиолетово-синий
'#14b8a6', // Морской волны
'#ec4899', // Розовый
'#64748b', // Серо-синий
];
const colorPik = (col) => { const colorPik = (col) => {
if (propsCalendar.value.cl_color === col) { if (propsCalendar.value.cl_color === col) {
propsCalendar.value.cl_color = null; propsCalendar.value.cl_color = null;
@@ -266,6 +288,8 @@ export default {
titleCard, titleCard,
newCalendar, newCalendar,
newStaff, newStaff,
isNewCalendar,
calendarAuthorId,
}; };
}, },
}; };
@@ -1,12 +1,5 @@
<template> <template>
<v-expansion-panels <v-expansion-panels class="calendar" variant="accordion" flat tile static v-model="openGroup">
class="calendar"
variant="accordion"
flat
tile
static
v-model="openGroup"
>
<v-expansion-panel elevation="0" flat tile static> <v-expansion-panel elevation="0" flat tile static>
<v-expansion-panel-title flat tile static class="py-0 px-3"> <v-expansion-panel-title flat tile static class="py-0 px-3">
<div @click.stop=""> <div @click.stop="">
@@ -26,7 +19,7 @@
<template v-if="Object.keys(calendars).length > 0"> <template v-if="Object.keys(calendars).length > 0">
<v-list-item <v-list-item
v-for="(x, i) in calendars" v-for="(x, i) in calendars"
:key="i" :key="x.id"
:value="x.cl_name" :value="x.cl_name"
@mouseenter="hover = i" @mouseenter="hover = i"
@mouseleave="hover = null" @mouseleave="hover = null"
@@ -37,9 +30,10 @@
<v-checkbox-btn <v-checkbox-btn
class="text-caption" class="text-caption"
:class="`text-${x.cl_color}`" :class="`text-${x.cl_color}`"
v-model="x.visible"
:color="x.cl_color" :color="x.cl_color"
@update:modelValue="chekUpdate(x)" v-model="x.visible"
@update:modelValue="toggleVisiblityEvents(x)"
:model-value="x.visible"
></v-checkbox-btn> ></v-checkbox-btn>
</template> </template>
<template v-slot:title> <template v-slot:title>
@@ -47,16 +41,12 @@
</template> </template>
<template v-slot:append> <template v-slot:append>
<transition name="fade"> <transition name="fade">
<v-btn <v-btn
v-if=" v-if="
x.author == accountStore.user.is_idEmployee || x.author == user.is_idEmployee ||
x.participant.some( x.participant.some(
(e) => (e) => e.editor === true && e.participant_calendar === user.is_idEmployee,
e.editor == true &&
e.participant_calendar ==
accountStore.user.is_idEmployee
) )
" "
size="x-small" size="x-small"
@@ -74,21 +64,23 @@
</template> </template>
</v-expansion-panel-text> </v-expansion-panel-text>
</v-expansion-panel> </v-expansion-panel>
<v-dialog v-model="showDialog" min-width="636" max-width="800"> <v-dialog v-model="showDialog" min-width="636" max-width="800">
<calendar-create <calendar-create
@closeDialog = "showDialog = false" @closeDialog="handleCloseDialog"
:calendar="calendar" :calendar="calendar"
@update:calendar="calendar = $event" @getCalendar="$emit('getCalendar')"
@getCalendar="$emit('getCalendar')" />
/>
</v-dialog> </v-dialog>
</v-expansion-panels> </v-expansion-panels>
</template> </template>
<script> <script>
import { ref } from "vue"; import { ref, watch } from 'vue';
import calendarCreate from "@/components/calendar_of_events/calendar-create.vue"; import calendarCreate from '@/components/calendar_of_events/calendar-create.vue';
import { useAccountStore } from "@/store/AccountStore"; import { useAccountStore } from '@/store/AccountStore';
import { storeToRefs } from 'pinia';
import { useCalendarStore } from '@/store/calendarStore';
export default { export default {
components: { calendarCreate }, components: { calendarCreate },
@@ -99,54 +91,69 @@ export default {
}, },
title: { title: {
typr: String, type: String,
default: "", default: '',
}, },
}, },
setup(props, { emit }) { setup(props) {
const showDialog = ref(false); const showDialog = ref(false);
const accountStore = useAccountStore(); const accountStore = useAccountStore();
const calendar = ref({}); const { user } = storeToRefs(accountStore);
const calendarStore = useCalendarStore();
const { toggleCalendarVisibility, hiddenCalendarIds } = calendarStore;
const calendar = ref(null);
const openGroup = ref([0]); const openGroup = ref([0]);
const trans = ref(false); const trans = ref(false);
const hover = ref(0); const hover = ref(0);
const editCreatedCalendar = (cal) => { const editCreatedCalendar = (cal) => {
if (cal === undefined) { if (cal === undefined) {
calendar.value = { calendar.value = {
cl_name: "", cl_name: '',
participant: [{ editor: true, participant_calendar: accountStore.user.is_idEmployee }], participant: [{ editor: true, participant_calendar: user.value.is_idEmployee }],
cl_color: "red", cl_color: 'red',
cl_descr: "", cl_descr: '',
}; };
} else { } else {
calendar.value = { ...cal };
calendar.value = cal;
} }
showDialog.value = true; showDialog.value = true;
}; };
const chekUpdate = (cal) => { const handleCloseDialog = () => {
let setcal = new Set(accountStore.calendar); showDialog.value = false;
if (cal.visible == false) {
setcal.add(cal.id);
} else {
setcal.delete(cal.id);
}
accountStore.calendar = Array.from(setcal);
}; };
const resetCalendar = () => {
calendar.value = {};
};
const toggleVisiblityEvents = (cal) => {
toggleCalendarVisibility(cal.id);
};
watch(hiddenCalendarIds, (newHiddenIds) => {}, { deep: true });
watch(
() => props.calendars,
(newCalendars) => {},
{ deep: true },
);
return { return {
showDialog,
calendar,
editCreatedCalendar,
chekUpdate,
accountStore, accountStore,
user,
calendar,
showDialog,
editCreatedCalendar,
toggleVisiblityEvents,
openGroup, openGroup,
trans, trans,
hover, hover,
handleCloseDialog,
resetCalendar,
}; };
}, },
}; };
@@ -0,0 +1,40 @@
import { ref, computed } from 'vue';
export function useEventListFilters() {
// Состояние фильтров
const dateRange = ref(null);
const sortOrder = ref('asc');
const sortOptions = [
{
title: 'По возрастанию',
value: 'asc',
props: {
prependIcon: 'mdi-sort-calendar-ascending',
},
},
{
title: 'По убыванию',
value: 'desc',
props: {
prependIcon: 'mdi-sort-calendar-descending',
},
},
];
// Сброс фильтров
const resetFilters = () => {
dateRange.value = null;
};
return {
// Состояние
dateRange,
sortOrder,
// Опции
sortOptions,
// Методы
resetFilters,
};
}
@@ -0,0 +1,183 @@
import { RRule } from 'rrule';
export function useRecurrence() {
const parseRecurrenceOptions = (periodString, eventDateStart) => {
if (!periodString || periodString === 'null') return null;
try {
// Пробуем распарсить как RRULE-строку
if (periodString.includes('RRULE:')) {
const rrule = RRule.fromString(periodString);
return {
...rrule.origOptions,
dtstart: new Date(eventDateStart),
interval: rrule.origOptions.interval || 1,
};
}
// Пробуем распарсить как JSON
const periodData = JSON.parse(periodString);
if (periodData?.origOptions) {
const options = { ...periodData.origOptions };
if (options.dtstart && typeof options.dtstart === 'string') {
options.dtstart = new Date(eventDateStart);
}
if (options.interval === undefined) {
options.interval = 1;
}
return options;
}
} catch (error) {
console.error('Parse recurrence error:', error);
}
return null;
};
/**
* Проверяет, является ли событие повторяющимся
*/
const isRecurringEvent = (event) => {
if (!event.period || event.period === 'null') return false;
return (
event.period.includes('RRULE:') || (event.period && event.period.includes('"origOptions"'))
);
};
/**
* Генерирует все экземпляры повторяющегося события
*/
const generateRecurringInstances = (event, count = 24) => {
if (!isRecurringEvent(event)) return [event];
try {
let rrule;
if (event.period.includes('RRULE:')) {
rrule = RRule.fromString(event.period);
} else {
const periodData = JSON.parse(event.period);
if (periodData?.origOptions) {
rrule = new RRule(periodData.origOptions);
}
}
if (!rrule) return [event];
const dates = rrule.all((date, i) => i < count);
const start = new Date(event.date_start);
const end = new Date(event.date_end);
const duration = end - start;
return dates.map((date, index) => ({
id: event.id,
title: event.name,
start: new Date(date),
end: new Date(date.getTime() + duration),
allDay: event.allday,
extendedProps: {
originalEventId: event.id,
description: event.description,
participant: event.participant,
calendar: event.calendar,
files: event.files,
isRecurringInstance: true,
},
}));
} catch (error) {
console.error('Error generating recurring instances:', error);
return [event];
}
};
const formatRecurrenceText = (periodString, eventDateStart) => {
if (!periodString || periodString === 'null') return null;
try {
let interval = 1;
if (periodString.includes('RRULE:')) {
// Парсим RRULE строку чтобы достать FREQ и INTERVAL
const rrulePart = periodString.split('RRULE:')[1];
if (rrulePart) {
const params = rrulePart.split(';');
// Достаем FREQ
const freqParam = params.find((p) => p.startsWith('FREQ='));
const freq = freqParam ? freqParam.split('=')[1] : '';
// Достаем INTERVAL
const intervalParam = params.find((p) => p.startsWith('INTERVAL='));
interval = intervalParam ? parseInt(intervalParam.split('=')[1]) : 1;
// Форматируем по частоте
switch (freq) {
case 'DAILY':
return interval === 1 ? 'Ежедневно' : `Каждый ${interval} день`;
case 'WEEKLY':
return interval === 1 ? 'Еженедельно' : `Каждую ${interval} неделю`;
case 'MONTHLY':
return interval === 1
? 'Каждый месяц'
: interval === 3
? 'Ежеквартально'
: `Каждый ${interval} месяц`;
case 'YEARLY':
return interval === 1 ? 'Ежегодно' : `Каждый ${interval} год`;
default:
return 'Повторяется';
}
}
}
return 'Повторяется';
} catch (error) {
console.error('Error formatting recurrence:', error);
return 'Повторяется';
}
};
/**
* Получает иконку для типа повторения
*/
const getRecurrenceIcon = (periodString) => {
if (!periodString) return 'mdi-repeat';
try {
let rrule;
if (periodString.includes('RRULE:')) {
rrule = RRule.fromString(periodString);
} else {
const periodData = JSON.parse(periodString);
if (periodData?.origOptions) {
rrule = new RRule(periodData.origOptions);
}
}
if (!rrule) return 'mdi-repeat';
const options = rrule.origOptions;
switch (options.freq) {
case RRule.DAILY:
return 'mdi-calendar-today';
case RRule.WEEKLY:
return 'mdi-calendar-week';
case RRule.MONTHLY:
return 'mdi-calendar-month';
case RRule.YEARLY:
return 'mdi-calendar-star';
default:
return 'mdi-repeat';
}
} catch (error) {
return 'mdi-repeat';
}
};
return {
isRecurringEvent,
generateRecurringInstances,
parseRecurrenceOptions,
formatRecurrenceText,
getRecurrenceIcon,
};
}
@@ -0,0 +1,513 @@
<template>
<v-dialog v-model="internalShow" max-width="700">
<v-card class="pa-4" min-height="400">
<!-- Заголовок -->
<v-card-title class="pr-0 pl-2 d-flex justify-space-between pb-3">
<span class="text-h5 font-weight-medium">Просмотр события</span>
<v-icon
icon="mdi-close"
size="small"
color="grey"
class="cursor-pointer"
@click="closeDialog"
/>
</v-card-title>
<v-divider></v-divider>
<!-- Контент -->
<v-card-text class="px-2">
<v-row no-gutters class="flex-column">
<!-- Название события -->
<v-row no-gutters class="align-center border-bottom">
<v-col
style="font-size: 1.1rem; line-height: 1.4"
class="text-body-1 text-text_grey font-weight-medium"
lg="3"
>
Название
</v-col>
<v-col>
<div class="text-body-1" style="font-size: 1.1rem; line-height: 1.4">
{{ eventData.event?.name || 'Без названия' }}
</div>
</v-col>
</v-row>
<!-- Календарь -->
<v-row no-gutters class="align-center pb-3 mb-3 border-bottom">
<v-col class="text-body-1 text-text_grey font-weight-medium" lg="3"> Календарь </v-col>
<v-col>
<div class="d-flex align-center">
<v-avatar size="20" :color="calendarColor" class="mr-3" />
<span class="text-body-1">{{ calendarName }}</span>
</div>
</v-col>
</v-row>
<!-- Участники -->
<v-row
no-gutters
class="align-start pb-3 mb-3 border-bottom"
v-if="participantsList.length > 0"
>
<v-col class="text-body-1 text-text_grey font-weight-medium pt-1" lg="3">
Участники
</v-col>
<v-col>
<div class="participants-list">
<div
v-for="participant in participantsList"
:key="participant.id"
class="text-body-1 mb-1"
>
• {{ participant.title }}
</div>
</div>
</v-col>
</v-row>
<!-- Дата и время -->
<v-row no-gutters class="align-top pb-3 mb-3 border-bottom">
<v-col class="text-body-1 text-text_grey font-weight-medium pt-1" lg="3">
Дата и время
</v-col>
<v-col class="d-flex flex-column">
<div class="d-flex align-center gap">
<div class="text-body-1 font-weight-medium">
{{ formatDateTime(eventData.event?.date_start, eventData.event?.allday) }}
</div>
<v-icon icon="mdi-minus" color="grey" class="mx-3" />
<div class="text-body-1 font-weight-medium">
{{ formatDateTime(eventData.event?.date_end, eventData.event?.allday) }}
</div>
</div>
</v-col>
</v-row>
<!-- Повторение -->
<v-row
no-gutters
class="align-center pb-3 mb-3 border-bottom"
v-if="eventData.event?.period"
>
<v-col class="text-body-1 text-text_grey font-weight-medium" lg="3"> Повтор события </v-col>
<v-col>
<div class="text-body-1">{{ recurrenceText }}</div>
</v-col>
</v-row>
<!-- Окончание события -->
<v-row no-gutters class="align-center pb-3 mb-3 border-bottom" v-if="showRepeatEnd">
<v-col class="text-body-1 text-text_grey font-weight-medium" lg="3">
Окончание события
</v-col>
<v-col>
<div class="text-body-1">
{{ formatRepeatEndDate }}
</div>
</v-col>
</v-row>
<!-- Файлы -->
<v-row
no-gutters
class="align-top pb-3 mb-3 border-bottom"
v-if="eventData.event?.files?.length"
>
<v-col class="text-body-1 text-text_grey font-weight-medium" lg="3"> Файлы </v-col>
<v-col>
<div class="files-list">
<div
v-for="file in eventData.event.files"
:key="file.id"
class="d-flex align-center mb-2 cursor-pointer"
@click="downloadFile(file)"
>
<v-icon :icon="getFileIcon(file)" color="primary" class="mr-2" size="small" />
<span class="text-body-1 text-primary text-decoration-underline">
{{ truncateFileName(getFileName(file)) }}
</span>
</div>
</div>
</v-col>
</v-row>
<!-- Описание -->
<v-row no-gutters class="align-top pb-3" v-if="eventData.event?.description">
<v-col class="text-body-1 text-text_grey font-weight-medium" lg="3"> Описание </v-col>
<v-col>
<div class="text-body-1 description-text">
{{ eventData.event.description }}
</div>
</v-col>
</v-row>
<!-- Если нет данных -->
<v-row v-if="!eventData.event?.name" class="justify-center mt-8">
<v-col class="text-center">
<v-icon size="64" color="grey-lighten-1">mdi-calendar-remove</v-icon>
<div class="text-h6 text-grey mt-2">Нет данных о событии</div>
</v-col>
</v-row>
</v-row>
</v-card-text>
<!-- Кнопки -->
<v-card-actions class="justify-end pa-4 pt-0">
<v-btn
width="120"
@click="closeDialog"
color="grey-darken-1"
variant="tonal"
class="text-body-1"
>
Закрыть
</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
</template>
<script>
import { computed, ref, watch } from 'vue';
import { useRecurrence } from '@/components/calendar_of_events/composables/useReccurrence';
import { RRule } from 'rrule';
export default {
name: 'EventCalendarShow',
props: {
show: {
type: Boolean,
default: false,
},
eventData: {
type: Object,
default: () => ({}),
},
allCalendars: {
type: Array,
default: () => [],
},
employees: {
type: Array,
default: [],
},
},
emits: ['update:show', 'close'],
setup(props, { emit }) {
const internalShow = ref(props.show);
const { parseRecurrenceOptions, isRecurringEvent } = useRecurrence();
// Синхронизация с внешним состоянием
watch(
() => props.show,
(newVal) => {
internalShow.value = newVal;
},
);
watch(internalShow, (newVal) => {
if (!newVal) {
emit('update:show', false);
emit('close');
}
});
const closeDialog = () => {
internalShow.value = false;
};
// Информация о календаре - ИСПРАВЛЕНО
const calendarInfo = computed(() => {
const calendarId = props.eventData.event?.calendar;
return props.allCalendars.find((cal) => cal.id == calendarId) || {};
});
const calendarName = computed(() => calendarInfo.value.cl_name || 'Неизвестный календарь');
const calendarColor = computed(() => calendarInfo.value.cl_color || 'grey');
// Участники - ИСПРАВЛЕНО
const participantsList = computed(() => {
const participantIds = props.eventData.event?.participant || [];
// Собираем всех сотрудников
const allEmployees = props.employees.flatMap((dept) => dept.employees || []);
return participantIds
.map((id) => {
const employee = allEmployees.find((emp) => emp.id == id);
return employee
? {
id: employee.id,
title: employee.title,
}
: null;
})
.filter(Boolean);
});
// Форматирование даты
const formatDateTime = (dateString, isAllDay) => {
if (!dateString) return 'Не указано';
try {
const date = new Date(dateString);
if (isAllDay) {
return date.toLocaleDateString('ru-RU', {
day: 'numeric',
month: 'long',
year: 'numeric',
});
}
return date.toLocaleString('ru-RU', {
day: 'numeric',
month: 'long',
year: 'numeric',
hour: '2-digit',
minute: '2-digit',
});
} catch {
return 'Неверный формат даты';
}
};
// Определяем показывать ли окончание повтора
const showRepeatEnd = computed(() => {
const period = props.eventData.event?.period;
if (!period || !isRecurringEvent(props.eventData.event)) return false;
try {
const options = parseRecurrenceOptions(period, props.eventData.event?.date_start);
return !!options?.until;
} catch {
return false;
}
});
// Форматируем дату окончания повтора
const formatRepeatEndDate = computed(() => {
const period = props.eventData.event?.period;
if (!period || !isRecurringEvent(props.eventData.event)) return '';
try {
const options = parseRecurrenceOptions(period, props.eventData.event?.date_start);
if (options?.until) {
return new Date(options.until).toLocaleDateString('ru-RU', {
day: 'numeric',
month: 'long',
year: 'numeric',
});
}
} catch (error) {
console.error('Error parsing repeat end date:', error);
}
return '';
});
// Текст повторения с использованием composable
const recurrenceText = computed(() => {
const period = props.eventData.event?.period;
if (!period || !isRecurringEvent(props.eventData.event)) return '';
try {
const options = parseRecurrenceOptions(period, props.eventData.event?.date_start);
if (!options) return 'Повторяющееся событие';
const freq = options.freq;
const interval = options.interval || 1;
switch (freq) {
case RRule.DAILY:
return interval === 1 ? 'Каждый день' : `Каждые ${interval} дней`;
case RRule.WEEKLY:
if (interval === 1) {
if (options.byweekday && options.byweekday.length > 0) {
const dayNames = options.byweekday
.map((day) => {
const dayMap = {
[RRule.MO]: 'понедельник',
[RRule.TU]: 'вторник',
[RRule.WE]: 'среду',
[RRule.TH]: 'четверг',
[RRule.FR]: 'пятницу',
[RRule.SA]: 'субботу',
[RRule.SU]: 'воскресенье',
};
return dayMap[day] || '';
})
.filter(Boolean);
if (dayNames.length === 1) return `Каждую ${dayNames[0]}`;
if (dayNames.length > 1) return `По ${dayNames.join(', ')}`;
}
return 'Каждую неделю';
}
return `Каждые ${interval} недель`;
case RRule.MONTHLY:
if (interval === 1) {
if (options.bymonthday && options.bymonthday.length > 0) {
const day = options.bymonthday[0];
return `Каждое ${day}-е число`;
}
return 'Каждый месяц';
}
return interval === 3 ? 'Каждый квартал' : `Каждые ${interval} месяцев`;
case RRule.YEARLY:
if (interval === 1) {
if (options.bymonth && options.bymonthday) {
const month = options.bymonth[0];
const day = options.bymonthday[0];
const monthNames = [
'января',
'февраля',
'марта',
'апреля',
'мая',
'июня',
'июля',
'августа',
'сентября',
'октября',
'ноября',
'декабря',
];
return `Каждый год ${day} ${monthNames[month - 1]}`;
}
return 'Каждый год';
}
return `Каждые ${interval} лет`;
default:
return 'Повторяющееся событие';
}
} catch (error) {
console.error('Error parsing recurrence:', error);
return 'Повторяющееся событие';
}
});
// Функции для файлов
const getFileName = (fileData) => {
if (fileData.file) {
const fileName = fileData.file.split('/').pop();
return decodeURIComponent(fileName) || 'Файл';
}
return fileData.name || 'Файл';
};
const getFileIcon = (fileData) => {
const fileName = getFileName(fileData);
const extension = fileName.split('.').pop()?.toLowerCase() || '';
const iconMap = {
pdf: 'mdi-file-pdf',
doc: 'mdi-file-word',
docx: 'mdi-file-word',
xls: 'mdi-file-excel',
xlsx: 'mdi-file-excel',
jpg: 'mdi-file-image',
jpeg: 'mdi-file-image',
png: 'mdi-file-image',
zip: 'mdi-folder-zip',
rar: 'mdi-folder-zip',
txt: 'mdi-file-document',
};
return iconMap[extension] || 'mdi-file';
};
const downloadFile = (file) => {
try {
const fileUrl = file.file.startsWith('http')
? file.file
: `${window.location.origin}${file.file}`;
const link = document.createElement('a');
link.href = fileUrl;
link.download = getFileName(file);
link.style.display = 'none';
document.body.appendChild(link);
link.click();
setTimeout(() => {
document.body.removeChild(link);
}, 100);
} catch (error) {
console.error('Ошибка скачивания файла:', error);
}
};
const truncateFileName = (fileName) => {
if (!fileName) return 'Файл';
if (fileName.length <= 30) return fileName;
const extension = fileName.split('.').pop();
const nameWithoutExt = fileName.slice(0, -(extension.length + 1));
if (nameWithoutExt.length <= 20) return fileName;
return `${nameWithoutExt.slice(0, 20)}...${extension ? '.' + extension : ''}`;
};
return {
internalShow,
closeDialog,
calendarName,
calendarColor,
participantsList,
formatDateTime,
recurrenceText,
getFileName,
getFileIcon,
downloadFile,
truncateFileName,
showRepeatEnd,
formatRepeatEndDate,
};
},
};
</script>
<style scoped>
.border-bottom {
border-bottom: 1px solid #e0e0e0;
}
.cursor-pointer {
cursor: pointer;
}
.participants-list {
line-height: 1.6;
}
.description-text {
white-space: pre-wrap;
line-height: 1.6;
background-color: #fafafa;
padding: 12px;
border-radius: 4px;
border-left: 3px solid #00897b;
}
.gap {
gap: 8px;
}
/* Убираем стандартные отступы Vuetify для более чистого вида */
:deep(.v-card-text) {
padding: 8px 12px;
}
:deep(.v-card-title) {
padding: 16px 20px;
}
</style>
File diff suppressed because it is too large. Load diff
+231 -94
View File
@@ -1,97 +1,146 @@
<template> <template>
<v-card> <v-card flat class="flip-card">
<v-card-text class="d-flex justify-space-between ga-3 text-h6"> <div class="flip-card-inner" :class="{ 'is-flipped': isExpanded }">
<v-tooltip bottom> <!-- Передняя сторона карточки -->
<template v-slot:activator="{ props }"> <div class="flip-card-front">
<span <v-card-text class="d-flex justify-space-between ga-3 text-h6">
style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis;" <v-tooltip bottom>
v-bind="props"> <template v-slot:activator="{ props }">
{{ voteCard.name }} <span
</span> style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis;"
</template> v-bind="props">
<span>{{ voteCard.name }}</span> {{ voteCard.name }}
</v-tooltip> </span>
</v-card-text>
<v-row>
<v-col>
<v-carousel
cycle
height="200" hide-delimiters
show-arrows="hover">
<v-carousel-item
v-for="(picture, index) in images"
:key="index"
:src="images[index].length < 1 ? defaultImage : `${baseURL.slice(0, -1)}${picture}`">
</v-carousel-item>
</v-carousel>
</v-col>
</v-row>
<v-card-text class="">
<v-tooltip bottom>
<template v-slot:activator="{ props }">
<span
style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis;"
v-bind="props">
{{ voteCard.description }}
</span>
</template>
<span>{{ voteCard.description }}</span>
</v-tooltip>
</v-card-text>
<div class="px-2">
<Timer v-if="!isFinished" :voteTime="{ dateend: voteCard.dateend, datestart: voteCard.datestart }"
@changeBtn="(time) => timeChange = time"/>
<div v-else class="font-weight-bold text-center"> Завершено: {{
new Date(voteCard.dateend).toLocaleDateString()
}}
</div>
</div>
<v-card-actions class="justify-space-between mt-4 pb-2">
<template v-if="!isFinished">
<v-btn :disabled="voteCard.is_passed || timeChange" color="teal-darken-4" prepend-icon="mdi-vote-outline"
rounded="xl" size="small" variant="outlined" @click="$emit('openVoteModal', voteCard)">
{{ !voteCard.is_passed ? "Проголосовать" : "Уже проголосовали" }}
</v-btn>
</template>
<template v-else>
<v-btn color="teal-darken-4" prepend-icon="mdi-trophy-outline"
rounded="xl" size="small" variant="outlined" @click="$emit('openResultModal', voteCard)">
Результаты
</v-btn>
</template>
<v-btn v-if="user.id === voteCard.author || user.is_superuser" color="error" size="medium" @click="youSure=true">
<v-icon>mdi-delete</v-icon>
<v-dialog v-model="youSure" width="500">
<v-card class="flex" max-width="450">
<v-btn
class="align-self-end ma-2 text-red"
icon="mdi-close"
size="medium"
variant="text"
@click="youSure = false"
/>
<div class="ml-5 text-h6">
Вы действительно хотите удалить голосование?
</div>
<template v-slot:actions>
<v-btn-group>
<v-btn
class="text-red"
@click="$emit('deleteVoting', voteCard.id), youSure = false">
Да
</v-btn>
<v-btn
class="text-green"
@click="youSure = false">
Нет
</v-btn>
</v-btn-group>
</template> </template>
</v-card> <span>{{ voteCard.name }}</span>
</v-dialog> </v-tooltip>
</v-btn> </v-card-text>
</v-card-actions> <v-row>
<v-col>
<v-carousel
cycle
height="200"
hide-delimiters
show-arrows="hover">
<v-carousel-item
v-for="(picture, index) in images"
:key="index"
:src="images[index].length < 1 ? defaultImage : `${baseURL.slice(0, -1)}${picture}`">
</v-carousel-item>
</v-carousel>
</v-col>
</v-row>
<v-card-text class="description-container">
<span>
{{ truncatedText }}
<span
v-if="needsTruncation"
class="show-more-btn"
@click="isExpanded = true"
>
...полное описание➡️
</span>
</span>
</v-card-text>
<div class="px-2">
<Timer
v-if="!isFinished"
:voteTime="{ dateend: voteCard.dateend, datestart: voteCard.datestart }"
@changeBtn="(time) => timeChange = time"
/>
<div v-else class="font-weight-bold text-center">
Завершено: {{ new Date(voteCard.dateend).toLocaleDateString() }}
</div>
</div>
<v-card-actions class="justify-space-between mt-4 pb-2">
<template v-if="!isFinished">
<v-btn
:disabled="voteCard.is_passed || timeChange"
color="teal-darken-4"
prepend-icon="mdi-vote-outline"
rounded="xl"
size="small"
variant="outlined"
@click="$emit('openVoteModal', voteCard)"
>
{{ !voteCard.is_passed ? "Проголосовать" : "Уже проголосовали" }}
</v-btn>
</template>
<template v-if="user.id === voteCard.author || isFinished || user.is_superuser">
<v-btn
color="teal-darken-4"
prepend-icon="mdi-trophy-outline"
rounded="xl"
size="small"
variant="outlined"
@click="$emit('openResultModal', voteCard)"
>
Результаты
</v-btn>
</template>
<v-btn
v-if="user.id === voteCard.author || user.is_superuser"
color="error"
size="medium"
@click="youSure=true"
>
<v-icon>mdi-delete</v-icon>
<v-dialog v-model="youSure" width="500">
<v-card class="flex" max-width="450">
<v-btn
class="align-self-end ma-2 text-red"
icon="mdi-close"
size="medium"
variant="text"
@click="youSure = false"
/>
<div class="ml-5 text-h6">
Вы действительно хотите удалить голосование?
</div>
<template v-slot:actions>
<v-btn-group>
<v-btn
class="text-red"
@click="$emit('deleteVoting', voteCard.id), youSure = false"
>
Да
</v-btn>
<v-btn
class="text-green"
@click="youSure = false"
>
Нет
</v-btn>
</v-btn-group>
</template>
</v-card>
</v-dialog>
</v-btn>
</v-card-actions>
</div>
<!-- Задняя сторона карточки -->
<div class="flip-card-back">
<v-card-text class="text-h6">
{{ voteCard.name }}
</v-card-text>
<v-card-text class="description-full">
{{ voteCard.description }}
</v-card-text>
<v-card-actions class="justify-center mt-4 pb-2">
<v-btn
color="teal-darken-4"
prepend-icon="mdi-arrow-left"
rounded="xl"
size="small"
variant="outlined"
@click="isExpanded = false"
>
Обратно
</v-btn>
</v-card-actions>
</div>
</div>
</v-card> </v-card>
</template> </template>
@@ -131,6 +180,20 @@ export default {
const accountStore = useAccountStore(); const accountStore = useAccountStore();
const user = accountStore.user; const user = accountStore.user;
const isExpanded = ref(false);
const maxLength = 22;
const needsTruncation = computed(() => {
return props.voteCard.description.length > maxLength;
});
const truncatedText = computed(() => {
if (!needsTruncation.value) {
return props.voteCard.description;
}
return props.voteCard.description.slice(0, maxLength);
});
const images = computed(() => { const images = computed(() => {
return props.voteCard.files.length > 0 ? props.voteCard.files : [''] return props.voteCard.files.length > 0 ? props.voteCard.files : ['']
}) })
@@ -143,9 +206,83 @@ export default {
isFinished.value = true; isFinished.value = true;
} }
return {timeChange, baseURL, images, youSure, isFinished, user, defaultImage} return {
timeChange,
baseURL,
images,
youSure,
isFinished,
user,
defaultImage,
isExpanded,
truncatedText,
needsTruncation
}
} }
}
</script>
<style scoped>
.flip-card {
perspective: 1000px;
background: transparent !important;
} }
</script> .flip-card-inner {
position: relative;
width: 100%;
transition: transform 0.6s;
transform-style: preserve-3d;
}
.flip-card-inner.is-flipped {
transform: rotateY(180deg);
}
.flip-card-front,
.flip-card-back {
width: 100%;
backface-visibility: hidden;
-webkit-backface-visibility: hidden;
}
.flip-card-front {
background: white;
}
.flip-card-back {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: white;
transform: rotateY(180deg);
display: flex;
flex-direction: column;
padding: 16px;
overflow-y: auto;
}
.description-container {
word-wrap: break-word;
}
.description-full {
word-wrap: break-word;
white-space: pre-wrap;
overflow-y: auto;
}
.show-more-btn {
color: #1976d2;
cursor: pointer;
font-weight: 500;
user-select: none;
white-space: nowrap;
}
.show-more-btn:hover {
text-decoration: underline;
}
</style>
+72 -67
View File
@@ -38,15 +38,15 @@
<v-card <v-card
class="cursor-pointer" class="cursor-pointer"
@click="opendialogWinn(department, getWinnersByDepartment(question).groupedByDepartment[department])" @click="opendialogWinn(department, getWinnersByDepartment(question).groupedByDepartment[department])"
style="max-height: 50vh; overflow-y: auto;"> style="height: 30vh; overflow-y: auto;">
<v-card-title> <v-card-title>
<strong class="text-teal-darken-4">{{ department }}</strong> <strong class="text-teal-darken-4" style="max-width: 800px; white-space: normal; word-wrap: break-word;">{{ department }}</strong>
</v-card-title> </v-card-title>
<v-card-subtitle> <v-card-subtitle>
Победитель: {{ winner.employee.fio || winner.name }} 🏆 Победитель: {{ getWinnerNames(winner) }} 🏆
</v-card-subtitle> </v-card-subtitle>
<v-card-text> <v-card-text>
Количество голосов: {{ winner.count }} Количество голосов: {{ winner[0]?.count || 0 }}
</v-card-text> </v-card-text>
</v-card> </v-card>
</v-col> </v-col>
@@ -57,10 +57,10 @@
<h3 class="text-center">{{ question.name }}</h3> <h3 class="text-center">{{ question.name }}</h3>
<v-card-title class="d-flex ga-2 align-center"> <v-card-title class="d-flex ga-2 align-center">
<h4 class="text-teal-darken-4">Победитель:</h4> <h4 class="text-teal-darken-4">Победитель:</h4>
<h3>{{ getWinner(question).employee?.fio || getWinner(question).name }} 🏆</h3> <h3>{{ getWinnerNames(getWinners(question)) }} 🏆</h3>
</v-card-title> </v-card-title>
<v-card-subtitle> <v-card-subtitle>
Количество голосов: {{ getWinner(question)?.count || 0 }} Количество голосов: {{ getWinners(question)[0]?.count || 0 }}
</v-card-subtitle> </v-card-subtitle>
</v-col> </v-col>
<v-col cols="12"> <v-col cols="12">
@@ -77,17 +77,17 @@
<v-avatar v-if="answer.file === null && answer.employee" <v-avatar v-if="answer.file === null && answer.employee"
:image="checkremote(`${spravURL()}${answer.employee.login}.jpg`)" :image="checkremote(`${spravURL()}${answer.employee.login}.jpg`)"
class="cursor-pointer" class="cursor-pointer"
@click.stop="opendialog(checkremote(`${spravURL()}${answer.employee.login}.jpg`))"/> @click.stop="opendialog(checkremote(`${spravURL()}${answer.employee.login}.jpg`))" />
<v-avatar v-if="answer.file !== null" :image="baseURL.slice(0, -1) + answer.file" <v-avatar v-if="answer.file !== null" :image="baseURL.slice(0, -1) + answer.file"
class="cursor-pointer" class="cursor-pointer"
@click.stop="opendialog(answer)"/> @click.stop="opendialog(answer)" />
<strong class="ml-4">{{ answer.employee ? answer.employee.fio : answer.name }}</strong>: <strong class="ml-4">{{ answer.employee ? answer.employee.fio : answer.name }}</strong>:
{{ answer.count }} {{ answer.count }}
{{ voteCount(answer.count) }} {{ voteCount(answer.count) }}
<template v-if="answer.employee"> <template v-if="answer.employee">
<br/> <br />
<small>Отдел: {{ answer.employee ? answer.employee.department : '' }}</small> <small>Отдел: {{ answer.employee ? answer.employee.department : '' }}</small>
<br/> <br />
<small>Должность: {{ answer.employee ? answer.employee.post : '' }}</small> <small>Должность: {{ answer.employee ? answer.employee.post : '' }}</small>
</template> </template>
</p> </p>
@@ -111,12 +111,12 @@
</v-row> </v-row>
</v-tabs-window-item> </v-tabs-window-item>
<v-tabs-window-item> <v-tabs-window-item>
<NonVoteSad v-if="nonVoters.length > 0"/> <NonVoteSad v-if="nonVoters.length > 0" />
<v-card-title v-if="nonVoters.length > 0" class="text-red-darken-3">Число сотрудников, которые не проголосовали <v-card-title v-if="nonVoters.length > 0" class="text-red-darken-3">Число сотрудников, которые не проголосовали
<strong>{{ nonVoters.length }}</strong> <strong>{{ nonVoters.length }}</strong>
</v-card-title> </v-card-title>
<v-card-item style="max-height: 50vh; overflow-y: auto;"> <v-card-item style="max-height: 50vh; overflow-y: auto;">
<NonVoteHappy v-if="nonVoters.length < 1"/> <NonVoteHappy v-if="nonVoters.length < 1" />
<template v-for="(voters, department) in groupedByDepartment" :key="department"> <template v-for="(voters, department) in groupedByDepartment" :key="department">
<v-list-item-title class="text-teal-darken-4">{{ department }}</v-list-item-title> <v-list-item-title class="text-teal-darken-4">{{ department }}</v-list-item-title>
<v-list-item v-for="(voter, voterIndex) in voters" :key="`${department}-${voterIndex}`"> <v-list-item v-for="(voter, voterIndex) in voters" :key="`${department}-${voterIndex}`">
@@ -148,7 +148,7 @@
</div> </div>
<v-spacer></v-spacer> <v-spacer></v-spacer>
<div> <div>
<v-btn color="red-darken-1" density="compact" icon="mdi-close-thick" size="small" @click="dialog=false"/> <v-btn color="red-darken-1" density="compact" icon="mdi-close-thick" size="small" @click="dialog=false" />
</div> </div>
</v-card-title> </v-card-title>
@@ -162,38 +162,37 @@
<v-dialog v-model="dialogWinner" max-width="800"> <v-dialog v-model="dialogWinner" max-width="800">
<v-card> <v-card>
<v-card-title class="d-flex"> <v-card-title class="d-flex">
<strong class="text-teal-darken-4">Результаты голосования: {{ activeDepartment }}</strong> <strong class="text-teal-darken-4" style="max-width: 800px; white-space: normal; word-wrap: break-word;">Результаты голосования: {{ activeDepartment }}</strong>
<v-spacer></v-spacer> <v-spacer></v-spacer>
<v-btn color="red-darken-1" density="compact" icon="mdi-close-thick" size="small" @click="dialogWinner=false"/> <v-btn color="red-darken-1" density="compact" icon="mdi-close-thick" size="small" @click="dialogWinner=false" />
</v-card-title> </v-card-title>
<v-card-text> <v-card-text>
<v-list> <v-list>
<v-list-item <v-list-item
v-for="(answer, index) in activeDepartmentResults.filter(el => el.count > 0)" v-for="(answer, index) in activeDepartmentResults.filter(el => el.count > 0).sort((a, b) => b.count - a.count)"
:key="index" :key="index"
> >
<p> <p>
<strong class="mr-4">{{ index + 1 }}.</strong> <strong class="mr-4">{{ index + 1 }}.</strong>
<v-avatar v-if="answer.file === null && answer.employee" <v-avatar v-if="answer.file === null && answer.employee"
:image="checkremote(`${spravURL()}${answer.employee.login}.jpg`)" :image="checkremote(`${spravURL()}${answer.employee.login}.jpg`)"
class="cursor-pointer" class="cursor-pointer"
@click.stop="opendialog(checkremote(`${spravURL()}${answer.employee.login}.jpg`))"/> @click.stop="opendialog(checkremote(`${spravURL()}${answer.employee.login}.jpg`))" />
<v-avatar v-if="answer.file !== null" :image="baseURL.slice(0, -1) + answer.file" <v-avatar v-if="answer.file !== null" :image="baseURL.slice(0, -1) + answer.file"
class="cursor-pointer" class="cursor-pointer"
@click.stop="opendialog(answer)"/> @click.stop="opendialog(answer)" />
<strong class="ml-4">{{ answer.employee ? answer.employee.fio : answer.name }}</strong>: <strong class="ml-4">{{ answer.employee ? answer.employee.fio : answer.name }}</strong>:
{{ answer.count }} {{ answer.count }}
{{ voteCount(answer.count) }} {{ voteCount(answer.count) }}
<template v-if="answer.employee"> <template v-if="answer.employee">
<br/> <br />
<small>Отдел: {{ answer.employee ? answer.employee.department : '' }}</small> <small>Отдел: {{ answer.employee ? answer.employee.department : '' }}</small>
<br/> <br />
<small>Должность: {{ answer.employee ? answer.employee.post : '' }}</small> <small>Должность: {{ answer.employee ? answer.employee.post : '' }}</small>
</template> </template>
</p> </p>
<v-progress-linear <v-progress-linear
:model-value="getPercentage(answer.count, questions[index])" :model-value="getPercentage(answer.count, questions[activeTab])"
color="teal-darken-4" color="teal-darken-4"
height="13" height="13"
rounded rounded
@@ -215,26 +214,26 @@
</template> </template>
<script> <script>
import {computed, ref} from 'vue'; import { computed, ref } from 'vue';
import {baseURL, spravURL} from "@/utils/axios-api"; import { baseURL, spravURL } from '@/utils/axios-api';
import {checkremote} from "@/utils/universal_functions"; import { checkremote } from '@/utils/universal_functions';
import NonVoteHappy from "@/components/vote/NonVoteHappy.vue"; import NonVoteHappy from '@/components/vote/NonVoteHappy.vue';
import NonVoteSad from "@/components/vote/NonVoteSad.vue"; import NonVoteSad from '@/components/vote/NonVoteSad.vue';
import InfoUserCard from "@/components/UI/fiousercard/infoUserCard.vue"; import InfoUserCard from '@/components/UI/fiousercard/infoUserCard.vue';
export default { export default {
name: 'VoteResult', name: 'VoteResult',
components: {InfoUserCard, NonVoteSad, NonVoteHappy}, components: { InfoUserCard, NonVoteSad, NonVoteHappy },
methods: { methods: {
checkremote, checkremote,
spravURL() { spravURL() {
return spravURL return spravURL;
} },
}, },
computed: { computed: {
baseURL() { baseURL() {
return baseURL return baseURL;
} },
}, },
emits: ['closer'], emits: ['closer'],
props: { props: {
@@ -250,7 +249,8 @@ export default {
const title = props.data.name; const title = props.data.name;
const description = props.data.description; const description = props.data.description;
const nonVoters = props.data.nonvoting; const allVoters = props.data.nonvoting;
const nonVoters = allVoters.filter(el => el.deleted !== 1);
const activeDepartment = ref(null); const activeDepartment = ref(null);
const activeDepartmentResults = ref([]); const activeDepartmentResults = ref([]);
@@ -263,11 +263,19 @@ export default {
dialogWinner.value = true; dialogWinner.value = true;
}; };
const getWinner = (question) => { const getWinners = (question) => {
return question.answers.reduce( const answers = question.answers || [];
(max, answer) => (answer.count > max.count ? answer : max), const maxCount = answers.reduce((max, answer) => Math.max(max, answer.count), 0);
{count: 0, employee: {fio: '', department: '', post: ''}, name: ''}
); if (maxCount === 0) {
return [{ count: 0, employee: { fio: '', department: '', post: '' }, name: '' }];
}
return answers.filter(answer => answer.count === maxCount);
};
const getWinnerNames = (winners) => {
return winners.map(answer => answer.employee?.fio || answer.name).join(' / ');
}; };
const getTopResults = (question) => { const getTopResults = (question) => {
@@ -283,7 +291,7 @@ export default {
} }
return { return {
...answer, ...answer,
rank rank,
}; };
}); });
}; };
@@ -300,34 +308,36 @@ export default {
const voteCount = (count) => { const voteCount = (count) => {
let currentVote = ''; let currentVote = '';
const lastDigit = count % 10; const lastDigit = count % 10;
if (lastDigit === 1) currentVote = 'голос' if (lastDigit === 1) currentVote = 'голос';
if (lastDigit > 1) currentVote = 'голоса' if (lastDigit > 1) currentVote = 'голоса';
if (lastDigit > 4 || count === 0 || count === 11 || count === 12 || count === 13 || count === 14) currentVote = 'голосов' if (lastDigit > 4 || count === 0 || count === 11 || count === 12 || count === 13 || count === 14) currentVote = 'голосов';
return currentVote return currentVote;
} };
const getPercentage = (count, question) => { const getPercentage = (count, question) => {
console.log(question);
if (typeof question === 'undefined') return 100
const totalVotes = question.answers.reduce((sum, answer) => sum + answer.count, 0); const totalVotes = question.answers.reduce((sum, answer) => sum + answer.count, 0);
return totalVotes > 0 ? (count / totalVotes) * 100 : 0; return totalVotes > 0 ? (count / totalVotes) * 100 : 0;
}; };
const activepick = ref(null) const activepick = ref(null);
// const dialog = ref(false) // const dialog = ref(false)
const opendialog = (val) => { const opendialog = (val) => {
dialog.value = true dialog.value = true;
activepick.value = val activepick.value = val;
} };
const groupedByDepartment = computed(() => { const groupedByDepartment = computed(() => {
// Группируем пользователей по департаментам // Группируем пользователей по департаментам
const departments = nonVoters.reduce((groups, voter) => { const departments = nonVoters.reduce((groups, voter) => {
const department = voter.department || ''; const department = voter.department || '';
if (!groups[department]) { if (!groups[department]) {
groups[department] = []; groups[department] = [];
} }
groups[department].push(voter); groups[department].push(voter);
return groups; return groups;
}, {}); }, {});
// Сортируем департаменты по id_dict_department // Сортируем департаменты по id_dict_department
const sortedDepartments = Object.keys(departments).sort((a, b) => { const sortedDepartments = Object.keys(departments).sort((a, b) => {
@@ -352,7 +362,6 @@ export default {
return sortedGroupedByDepartment; return sortedGroupedByDepartment;
}); });
// const groupedByDepartment = {};
const getWinnersByDepartment = (question) => { const getWinnersByDepartment = (question) => {
// Группируем ответы по департаментам // Группируем ответы по департаментам
@@ -365,15 +374,10 @@ export default {
return groups; return groups;
}, {}); }, {});
// Для каждого департамента находим победителя // Для каждого департамента находим всех лидеров
const winnersByDepartment = {}; const winnersByDepartment = {};
for (const department in groupedByDepartment) { for (const department in groupedByDepartment) {
const answers = groupedByDepartment[department]; winnersByDepartment[department] = getWinners({ answers: groupedByDepartment[department] });
const winner = answers.reduce(
(max, answer) => (answer.count > max.count ? answer : max),
{count: 0, employee: {fio: '', department: '', post: ''}, name: ''}
);
winnersByDepartment[department] = winner;
} }
return { groupedByDepartment, winnersByDepartment }; return { groupedByDepartment, winnersByDepartment };
@@ -392,7 +396,8 @@ export default {
dialog, dialog,
activeTab, activeTab,
questions, questions,
getWinner, getWinners,
getWinnerNames,
getTopResults, getTopResults,
truncateText, truncateText,
shouldShowTooltip, shouldShowTooltip,
@@ -401,7 +406,7 @@ export default {
description, description,
getPercentage, getPercentage,
nonVoters, nonVoters,
groupedByDepartment groupedByDepartment,
}; };
}, },
}; };
@@ -1,38 +0,0 @@
<template>
<v-app-bar density="compact" color="teal-darken-4" elevation="1">
<template v-slot:image>
<v-img gradient="to top right, rgba(19,84,122,.8), rgba(128,208,199,.8)" />
</template>
<v-icon :icon="props.showSideBar ? 'mdi-chevron-right' : 'mdi-chevron-left'" rounded="0" @click="$emit('showSide')" class="pl-7" size="small"/>
<v-col cols="3" class="d-flex align-center ml-3 cursor-pointer" @click="router.push('/')">
<v-img :src="props.logo" max-height="45" max-width="45"/>
<v-app-bar-title class="pl-2 text-h6 font-weight-bold">Портал МИ ФНС России по ЦОД № 2</v-app-bar-title>
</v-col>
<v-col class="d-flex justify-end align-center">
<vcard-user :author="accountStore.user"/>
<AppNavigation @showUser="showUser"/>
</v-col>
</v-app-bar>
</template>
<script setup>
import router from '@/router';
import { useAccountStore } from '@/store/AccountStore';
import vcardUser from '@/components/UI/fiousercard/vcardUser.vue';
import AppNavigation from '@/components/UI/AppHeader/AppNavigation.vue';
const accountStore = useAccountStore()
const props = defineProps({
showSideBar: Boolean,
logo: String,
})
const emit = defineEmits(['showSide', 'showUser'])
const showUser = (val) => {
emit('showUser', val)
}
</script>
@@ -1,86 +0,0 @@
<template>
<v-navigation-drawer :rail="props.isRail" permanent class="text-body-2">
<div class="d-flex flex-column h-100">
<v-list v-for="(nav, index) in props.asideNavigation" :key="index" density="compact" nav>
<v-list-item v-if="!('submenu' in nav)" :prepend-icon="nav.ico" @click="router.push(`${nav.path}`)">
{{ nav.name }}
<v-tooltip v-if="props.isRail" location="top" activator="parent">
{{ nav.name }}
</v-tooltip>
</v-list-item>
<v-list-group v-else :fluid="props.isRail ? true : false">
<template v-slot:activator="{ props: groupProps }">
<v-list-item v-bind="groupProps" :prepend-icon="nav.ico">
{{ nav.name }}
<v-tooltip v-if="props.isRail" location="top" activator="parent">
{{ nav.name }}
</v-tooltip>
</v-list-item>
</template>
<v-list-item v-for="(sub, index) in nav.submenu" :key="index" @click="router.push(`${sub.path}`)">
{{ props.isRail ? getAbbreviation(sub.name) : sub.name }}
<v-tooltip v-if="props.isRail" location="top" activator="parent">
{{ sub.name }}
</v-tooltip>
</v-list-item>
</v-list-group>
</v-list>
<v-list class="flex-grow-1" nav>
<v-list-item v-for="links in store.portallinks" :key="links.id" :href="links.link" target="_blank"
:prepend-icon="links.imagecode" link>
{{ links.name }}
<v-tooltip v-if="props.isRail" location="top" activator="parent">
{{ links.name }}
</v-tooltip>
</v-list-item>
</v-list>
<v-list v-if="accountUser.user.is_staff" class="text-blue-grey-lighten-1" nav>
<v-list-item prepend-icon="mdi-wrench" title="Панель администратора" :href="baseURL + 'admin'" target="_blank" link>
<v-tooltip v-if="props.isRail" location="top" activator="parent">
Панель администратора
</v-tooltip>
</v-list-item>
</v-list>
<page-counter :rail="props.isRail"/>
</div>
</v-navigation-drawer>
<v-navigation-drawer v-model="props.showUser" rail location="right">
<online-users />
</v-navigation-drawer>
</template>
<script setup>
import router from "@/router";
import { useMainmenuStore } from "@/store/MainmenuStore";
import { useAccountStore } from "@/store/AccountStore";
import { baseURL } from '@/utils/axios-api';
import pageCounter from "@/components/UI/defaultportal/page-counter.vue";
import onlineUsers from "@/components/UI/fiousercard/onlineUsers.vue";
const store = useMainmenuStore()
const accountUser = useAccountStore()
store.loadlinks()
defineEmits(['showUser'])
const props = defineProps({
isRail: Boolean,
showUser: Boolean,
asideNavigation: {
type: Array,
default: () => [{
name: "",
ico: "",
path: "",
submenu: [{
name: "",
path: "",
}],
}]
}
})
const getAbbreviation = (text) => {
return text.substring(0, 2).toUpperCase();
};
</script>
+284 -24
View File
@@ -1,42 +1,235 @@
<template> <template>
<v-app> <v-app>
<AppHeader @show-side="rail = !rail" :logo="imageSrc" @showUser="usersOnline" /> <v-app-bar :elevation="accountStore.cod2user ? 2 : 0" density="compact" color="app_bar" class="pl-4">
<AsideNav :asideNavigation="navigations" :isRail="rail" :showUser="showUser" /> <v-icon v-if="accountStore.cod2user" class="px-3" size="20" color="black_and_white"
<v-main class="d-flex"> :icon="rail ? 'mdi-chevron-right' : 'mdi-chevron-left'" @click="rail = !rail" />
<v-card v-if="accountStore.cod2user" class="bg-transparent py" color="black_and_white" density="compact"
:prepend-avatar="imageSrc" title="Портал МИ ФНС России по ЦОД № 2" variant="text" :to="'/'" />
<template v-slot:image>
<v-img class="bggrad" />
</template>
<template v-slot:append>
<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>
<span>F.A.Q.</span>
</v-tooltip>
<v-dialog v-model="LikeDialog" persistent width="800">
<template v-slot:activator="{ props }">
<v-btn color="black_and_white" v-bind="props" dark icon="mdi-thumb-up-outline">
<v-icon></v-icon>
<v-tooltip activator="parent" location="bottom">Обратная связь</v-tooltip>
</v-btn>
</template>
<Card-like :LikeDialog="LikeDialog" @menusClose="closeinfo()" />
</v-dialog>
<v-tooltip location="bottom">
<template v-slot:activator="{ props }">
<v-btn icon @click="toggleTheme">
<v-icon v-bind="props" class="mr-1" :color="theme.global.current.value.dark ? 'yellow' : 'lampa'">
mdi-lightbulb-outline
</v-icon>
</v-btn>
</template>
<span> Сменить тему</span>
</v-tooltip>
<v-card v-show="message" class="" width="50">{{ name }}</v-card>
<v-tooltip location="bottom">
<template v-slot:activator="{ props }">
<v-btn color="black_and_white" icon="mdi-account-multiple-outline" @click="drawer_right = !drawer_right"
v-bind="props" />
</template>
<span>
{{
drawer_right == true
? "Скрыть пользователей"
: "Показать пользователей"
}}
</span>
</v-tooltip>
<v-tooltip location="bottom">
<template v-slot:activator="{ props }">
<v-btn color="black_and_white" icon="mdi-logout" @click="accountStore.logout" v-bind="props" />
</template>
<span> Выход </span>
</v-tooltip>
</template>
<template v-else>
<v-row justify="center">
<Auth-form @challengealert="alert = true" />
</v-row>
</template>
</template>
</v-app-bar>
<v-navigation-drawer v-if="accountStore.cod2user" :width="245" :rail="rail" permanent v-model="drawer">
<v-row class="my-0 h-100">
<v-col class="flex-column d-flex">
<v-row><v-col>
<v-list nav density="compact">
<template v-for="(x, key) in navigations" :key="key">
<!-- v-if="!('submenu' in x) || (x.path== '/portal' && accountStore.user.is_staff)" -->
<v-list-item v-if="(x.path == '/portal'? accountStore.user.is_superuser : true) && !('submenu' in x)
" :key="x.key" :title="x.name" :value="x.name" :href="x.link" :disabled="x.path == ''" :to="x.path"
:target="x.link ? '_blank' : ''"
color="navigation"
>
<template v-slot:prepend>
<v-icon :icon="x.ico" />
<v-tooltip v-if="rail" activator="parent" location="top">
{{ x.name }}
</v-tooltip>
</template>
</v-list-item>
<v-list-group v-if="x.path != '/portal' && 'submenu' in x" :class="rail ? 'railmenu' : ''" :key="key"
:value="x.name">
<template v-slot:activator="{ props }">
<v-list-item v-bind="props" :title="x.name" :prepend-icon="x.ico" color="navigation">
<v-tooltip v-if="rail" activator="parent" location="top">
{{ x.name }}
</v-tooltip>
</v-list-item>
</template>
<v-list-item v-for="(child, k) in x.submenu" color="navigation" :href="child.link" :key="k"
:value="child.name" :title="!rail ? child.name : menuTruncated(child.name)" :to="child.path"
:target="child.link ? '_blank' : ''">
<v-tooltip v-if="rail" activator="parent" location="top">
{{ child.name }}
</v-tooltip>
</v-list-item>
</v-list-group>
</template>
</v-list>
<v-list nav density="compact">
<v-list-item v-for="x of mainmenuStore.portallinks" :key="x.name" :title="x.name" :value="x.name"
:href="x.link" color="app_bar" :target="x.link ? '_blank' : ''">
<template v-slot:prepend>
<v-icon :icon="x.imagecode" />
<v-tooltip v-if="rail" activator="parent" location="top">
{{ x.name }}
</v-tooltip>
</template>
</v-list-item>
</v-list>
</v-col>
</v-row>
<v-row class="flex-grow-0" v-if="accountStore.user.is_staff">
<v-col>
<AdminMenu :rail="rail" />
</v-col>
</v-row>
<v-row no-gutters class="flex-grow-0">
<v-col>
<page-counter :rail="rail" />
</v-col>
</v-row>
</v-col>
</v-row>
</v-navigation-drawer>
<v-main v-if="accountStore.cod2user" class="d-flex bg-main_theme">
<router-view /> <router-view />
<alert-default /> <alert-default />
</v-main> </v-main>
<v-main v-else class="d-flex align-center text-h3 bg-teal-lighten-2">
<v-card class="h-100 w-100 d-flex justify-center rounded-0 flex-column" :image="`${burl}${scrimg}`">
<v-card-text
class="justify-center bgCard h-100 ma-3 d-flex flex-column"
style="background: rgba(255, 255, 255, 0.3) !important; background-color: rgba(255, 255, 255, 0.3) !important;"
>
<v-row
class="bgText flex-grow-0"
style="background: rgba(255, 255, 255, 0.5) !important; background-color: rgba(255, 255, 255, 0.5) !important;"
>
<v-col class="text-center textcolor font-weight-black text-h3 pb-0">
Добро пожаловать на портал МИ ФНС России по ЦОД № 2
</v-col>
</v-row>
<v-row
class="bgText flex-grow-0"
style="background: rgba(255, 255, 255, 0.5) !important; background-color: rgba(255, 255, 255, 0.5) !important;"
>
<v-col class="text-subtitle-1 text-center textcolor pt-0">
Авторизуйтесь для получения доступа к контенту портала
</v-col>
</v-row>
</v-card-text>
</v-card>
<alert-default />
</v-main>
<v-navigation-drawer v-if="accountStore.cod2user" v-model="drawer_right" rail permanent location="right"
@click="rail = false">
<Online-users />
</v-navigation-drawer>
</v-app> </v-app>
</template> </template>
<script> <script>
import { ref, computed } from "vue"; import { ref, computed } from "vue";
import uf from "@/utils/universal_functions";
import { useAccountStore } from "@/store/AccountStore"; import { useAccountStore } from "@/store/AccountStore";
import { useMainmenuStore } from "@/store/MainmenuStore";
import { useTheme } from "vuetify";
import AuthForm from "@/components/UI/Auth-form.vue";
import OnlineUsers from "@/components/UI/fiousercard/onlineUsers.vue";
import CardLike from "@/components/cardLike.vue";
import { axiosApiInstance, clearAxios } from "@/utils/axios-api"; import { axiosApiInstance, clearAxios } from "@/utils/axios-api";
import { baseURL } from "@/utils/axios-api";
import AppHeader from "./AppHeader.vue"; import { baseURL } from "@/utils/axios-api";
import AsideNav from "./AsideNav.vue"; import VcardUser from "@/components/UI/fiousercard/vcardUser.vue";
import alertDefault from "./alertDefault.vue" import PageCounter from "@/components/UI/defaultportal/page-counter.vue";
import AdminMenu from "@/layouts/default/AdminMenu.vue";
import { useDisplay } from "vuetify";
export default { export default {
components: { components: {
AppHeader, AuthForm,
AsideNav, OnlineUsers,
alertDefault, CardLike,
VcardUser,
PageCounter,
AdminMenu,
}, },
emits: ['showUser'],
mixins: [uf],
setup() { setup() {
const { name } = useDisplay();
const theme = useTheme();
const mainmenuStore = useMainmenuStore();
const accountStore = useAccountStore(); const accountStore = useAccountStore();
const showUser = ref(true); const drawer = ref(true);
const drawer_right = ref(true);
const LikeDialog = ref(false);
const rail = ref(false); const rail = ref(false);
const showTooltip = ref(false);
const alert = ref(false); const alert = ref(false);
const burl = baseURL.slice(0, -1); const burl = baseURL.slice(0, -1);
const scrimg = ref([]); const scrimg = ref([]);
const usersOnline = (val) => {
showUser.value = val;
}
const message = computed({ const message = computed({
get: () => { get: () => {
return process.env.NODE_ENV == "development" ? true : false; return process.env.NODE_ENV == "development" ? true : false;
@@ -54,6 +247,20 @@ export default {
screenimg(); screenimg();
const menuTruncated = (menus) => {
return menus.slice(0, 2).toUpperCase();
};
const toggleTheme = () => {
theme.global.name.value = theme.global.current.value.dark
? "light"
: "dark";
};
mainmenuStore.loadlinks();
const navigations = ref([ const navigations = ref([
{ {
name: "Новости", name: "Новости",
@@ -76,7 +283,7 @@ export default {
submenu: [ submenu: [
{ {
name: "Справочник", name: "Справочник",
path: "/employee_directory", link: "http://10.252.44.33/accounting6/members.php",
}, },
// { // {
@@ -97,11 +304,11 @@ export default {
// ], // ],
// }, // },
// { {
// name: "Календарь", name: "Календарь",
// ico: "mdi-calendar", ico: "mdi-calendar",
// path: "/ical", path: "/ical",
// }, },
{ {
name: "Голосование", name: "Голосование",
ico: "mdi-vote", ico: "mdi-vote",
@@ -132,6 +339,11 @@ export default {
return new URL(`@/assets/FNS-logo-xs.png`, import.meta.url).href; return new URL(`@/assets/FNS-logo-xs.png`, import.meta.url).href;
}); });
const closeinfo = () => {
LikeDialog.value = false;
// feedalert.value=true
};
const getSafetyChapter = () => { const getSafetyChapter = () => {
axiosApiInstance.get("api/safety/gettypes/").then((response) => { axiosApiInstance.get("api/safety/gettypes/").then((response) => {
response.data.forEach((item) => { response.data.forEach((item) => {
@@ -155,23 +367,71 @@ export default {
// getSafetyChapter(); // getSafetyChapter();
return { return {
theme,
mainmenuStore,
accountStore, accountStore,
showUser, drawer,
drawer_right,
toggleTheme,
navigations, navigations,
imageSrc, imageSrc,
LikeDialog,
scrimg, scrimg,
rail, rail,
showTooltip,
menuTruncated,
alert, alert,
burl, burl,
name,
closeinfo,
baseURL, baseURL,
usersOnline,
message, message,
}; };
}, },
}; };
</script> </script>
<style lang="scss"> <style lang="scss">
.bgCard {
background: rgba(255, 255, 255, 0.3) !important;
background-color: rgba(255, 255, 255, 0.3) !important;
}
.v-card.bgCard {
background: rgba(255, 255, 255, 0.3) !important;
background-color: rgba(255, 255, 255, 0.3) !important;
}
.bgText {
background: rgba(255, 255, 255, 0.5) !important;
background-color: rgba(255, 255, 255, 0.5) !important;
}
.textcolor {
color: #2f535e !important;
}
.mystat {
position: fixed;
right: 10px;
bottom: 10px;
z-index: 1005;
}
.btnNav .v-navigation-drawer__content {
display: flex;
align-items: center;
}
.railmenu .v-list-group__items .v-list-item {
padding-inline-start: 11px !important;
}
.textcolor { .textcolor {
color: #2f535e; color: #2f535e;
} }
</style>
#tr-popup {
display: none;
}
</style>
+11
View File
@@ -1,3 +1,10 @@
/**
* main.js
*
* Bootstraps Vuetify and other plugins then mounts the App`
*/
// Components
import App from './App.vue' import App from './App.vue'
// Composables // Composables
@@ -20,6 +27,10 @@ components.forEach((component) => {
app.component('vue3-autocounter', Vue3Autocounter) app.component('vue3-autocounter', Vue3Autocounter)
// Vue.use(VueScrollTo)
registerPlugins(app) registerPlugins(app)
app.mount('#app') app.mount('#app')
-27
View File
@@ -1,27 +0,0 @@
<template>
<v-app>
<v-app-bar density="compact" color="teal-darken-4" elevation="1">
<template v-slot:image>
<v-img gradient="to top right, rgba(19,84,122,.8), rgba(128,208,199,.8)" />
</template>
<v-col class="d-flex justify-end">
<AuthForm @challengealert="alarm = true" />
</v-col>
</v-app-bar>
<v-card class="h-100 mt-11 pa-5 d-flex align-center text-center" variant="tonal" image="/src/assets/squirrel.jpg">
<v-card class="w-100 h-100 d-flex align-center bg-grey-lighten-1 opacity-70">
<!-- style="background-color: rgba(255, 255, 255, .5);" -->
<v-container class="opacity-100 mx-2 bg-grey-lighten-5" fluid>
<!-- style="background-color: #ffffff38;" -->
<v-col class=" font-weight-black text-text_card_auth text-h3">Добро пожаловать на портал МИ ФНС России по ЦОД № 2</v-col>
<v-col class="text-subtitle-1">Авторизуйтесь для получения доступа к контенту портала</v-col>
</v-container>
</v-card>
</v-card>
</v-app>
</template>
<script setup>
import AuthForm from "@/components/UI/Auth-form.vue"
</script>
+27 -10
View File
@@ -5,15 +5,32 @@
*/ */
// Plugins // Plugins
import { loadFonts } from './webfontloader' import { loadFonts } from './webfontloader';
import vuetify from './vuetify' import vuetify from './vuetify';
import pinia from '../store' import pinia from '../store';
import router from '../router' import router from '../router';
export function registerPlugins (app) { // FullCalendar
loadFonts() import FullCalendar from '@fullcalendar/vue3';
app import dayGridPlugin from '@fullcalendar/daygrid';
.use(vuetify) import timeGridPlugin from '@fullcalendar/timegrid';
.use(pinia) import multiMonthPlugin from '@fullcalendar/multimonth';
.use(router) import interactionPlugin from '@fullcalendar/interaction';
import listPlugin from '@fullcalendar/list';
import ruLocale from '@fullcalendar/core/locales/ru';
export function registerPlugins(app) {
loadFonts();
app.use(vuetify).use(pinia).use(router);
app.component('FullCalendar', FullCalendar);
app.config.globalProperties.$fullCalendarPlugins = {
dayGridPlugin,
timeGridPlugin,
multiMonthPlugin,
interactionPlugin,
listPlugin,
ruLocale,
};
} }
+8 -10
View File
@@ -1,25 +1,22 @@
import '@mdi/font/css/materialdesignicons.css' import '@mdi/font/css/materialdesignicons.css'
import 'vuetify/styles' import 'vuetify/styles'
import { VCalendar } from 'vuetify/labs/VCalendar' import { VCalendar } from 'vuetify/components/VCalendar'
import { createVuetify } from 'vuetify' import { createVuetify } from 'vuetify'
import { ru } from 'vuetify/locale' import { ru } from 'vuetify/locale'
export default createVuetify({ export default createVuetify({
locale: { locale: {
messages: { ru, }, messages: { ru, },
}, },
components: { components: {
VCalendar, VCalendar,
}, },
theme: { theme: {
defaultTheme: 'light', defaultTheme: 'light',
options: {
customProperties: true
},
themes: { themes: {
light: { light: {
colors: { colors: {
@@ -46,13 +43,12 @@ export default createVuetify({
insert_table: '#FAFAFA', insert_table: '#FAFAFA',
btn_text: '#00897B', // фигма, текст кнопки с иконкой btn_text: '#00897B', // фигма, текст кнопки с иконкой
select_list: '#E0EAE8', select_list: '#E0EAE8',
btn_gray: '#E0E0E0', btn_gray: '#E0E0E0'
text_card_auth: '#2f535e',
}, },
}, },
dark: { dark: {
colors: { colors: {
lampa: '#FFB300', lampa: '#121212',
primary: '#1E88E5', primary: '#1E88E5',
secondary: '#64B5F6', secondary: '#64B5F6',
main_theme: "#121212", main_theme: "#121212",
@@ -78,12 +74,14 @@ export default createVuetify({
btn_gray: '#2C2C2C', btn_gray: '#2C2C2C',
surface: '#1E1E1E', surface: '#1E1E1E',
background: '#121212', background: '#121212',
text_card_auth: '#2f535e',
'on-background': '#FFFFFF', 'on-background': '#FFFFFF',
'on-surface': '#FFFFFF', 'on-surface': '#FFFFFF',
'card-background': '#1E1E1E' 'card-background': '#1E1E1E'
}, },
}, },
options: {
customProperties: true
},
}, },
}, },
}) })
+19 -17
View File
@@ -1,18 +1,15 @@
// Composables
import { createRouter, createWebHistory } from "vue-router"; import { createRouter, createWebHistory } from "vue-router";
import { useAccountStore } from "@/store/AccountStore"; import { useAccountStore } from "@/store/AccountStore";
const routes = [ const routes = [
{
path: "/auth",
component: () => import('@/pages/AuthorizePage.vue'),
name: "Auth",
},
{ {
path: "/", path: "/",
component: () => import("@/layouts/default/DefaultPortal.vue"), component: () => import("@/layouts/default/DefaultPortal.vue"),
meta: { meta: {
requiresAuth: true, title: "Вход",
}, },
children: [ children: [
{ {
path: "/", path: "/",
@@ -195,13 +192,7 @@ const routes = [
name: 'Secret Page', name: 'Secret Page',
component: () => component: () =>
import("@/views/secret/SecretPage.vue") import("@/views/secret/SecretPage.vue")
}, }
{
path: '/employee_directory',
name: 'EmployeeDirectory',
component: () =>
import("@/views/employee_directory/EmployeeDirectoryMain.vue")
},
], ],
}, },
]; ];
@@ -211,12 +202,23 @@ const router = createRouter({
routes, routes,
}); });
router.beforeEach((to, from, next) => {
function isSuperuser() {
const accountStore = useAccountStore(); const accountStore = useAccountStore();
if (to.meta.requiresAuth && !accountStore.cod2user) {
document.title = to.meta.title; if (accountStore.user.is_superuser === false) {
next("/auth"); return true;
} else { } else {
return false;
}
}
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && isSuperuser()) {
document.title = to.meta.title;
next("/");
} else {
document.title = to.meta.title;
next(); next();
} }
}); });
+44 -60
View File
@@ -1,25 +1,19 @@
// Utilities // Utilities
import { defineStore } from "pinia"; import { defineStore } from 'pinia';
import { ref, watch, computed } from "vue"; import { ref, watch, computed } from 'vue';
import { clearAxios, spravURL } from "@/utils/axios-api"; import { clearAxios, spravURL } from '@/utils/axios-api';
import VueJwtDecode from "vue-jwt-decode"; import VueJwtDecode from 'vue-jwt-decode';
import { checkremote } from "@/utils/universal_functions"; import { checkremote } from '@/utils/universal_functions';
import { useAppStore } from "@/store/app.js"; import { useAppStore } from '@/store/app.js';
import { useRouter } from "vue-router";
export const useAccountStore = defineStore("AccountStore", () => { export const useAccountStore = defineStore('AccountStore', () => {
const AppStore = useAppStore(); const AppStore = useAppStore();
const user = ref(getuserFromStorage()); const user = ref(getuserFromStorage());
const router = useRouter();
const settingsStorage = computed({ const settingsStorage = computed({
get() { get() {
if (Object.keys(user.value).length==0){ if (Object.keys(user.value).length == 0) {
getuserFromStorage() getuserFromStorage();
} }
return JSON.parse(localStorage.getItem(user.value.is_idEmployee)); return JSON.parse(localStorage.getItem(user.value.is_idEmployee));
}, },
@@ -30,12 +24,11 @@ export const useAccountStore = defineStore("AccountStore", () => {
}; };
function get_setting(key) { function get_setting(key) {
return settingsStorage.value === null? defaultSettings[key]: settingsStorage.value[key]; return settingsStorage.value === null ? defaultSettings[key] : settingsStorage.value[key];
} }
const cod2user = ref(false); const cod2user = ref(false);
const calendar = ref(get_setting("calendar") const calendar = ref(get_setting('calendar'));
);
const setUser = (value) => { const setUser = (value) => {
value.photo = checkremote(`${spravURL}${value.login}.jpg`); value.photo = checkremote(`${spravURL}${value.login}.jpg`);
user.value = value; user.value = value;
@@ -44,66 +37,57 @@ export const useAccountStore = defineStore("AccountStore", () => {
// //
// геттер бывший // геттер бывший
// const getUser=computed(()=> uyser.value) // const getUser=computed(()=> uyser.value)
function getuserFromStorage(){ function getuserFromStorage() {
try{ try {
let u = VueJwtDecode.decode(localStorage.getItem("refresh")); let u = VueJwtDecode.decode(localStorage.getItem('refresh'));
u.user.photo = checkremote(`${spravURL}${u.user.login}.jpg`); u.user.photo = checkremote(`${spravURL}${u.user.login}.jpg`);
return u.user; return u.user;
}catch{ } catch {
return {}} return {};
}
} }
const logging = async (anon) => { const logging = async (anon) => {
AppStore.loading = true; AppStore.loading = true;
const result = await clearAxios.post("api/accounts/token/", anon); const result = await clearAxios.post('api/accounts/token/', anon);
localStorage.setItem("access", result.data.access); localStorage.setItem('access', result.data.access);
localStorage.setItem("refresh", result.data.refresh); localStorage.setItem('refresh', result.data.refresh);
user.value=getuserFromStorage() user.value = getuserFromStorage();
if (settingsStorage.value === null) { if (settingsStorage.value === null) {
settingsUp(defaultSettings) settingsUp(defaultSettings);
} }
console.log(user.value);
AppStore.loading = false; AppStore.loading = false;
}; };
const logout = () => { const logout = () => {
user.value = {}; user.value = {};
localStorage.removeItem("access"); localStorage.removeItem('access');
localStorage.removeItem("refresh"); localStorage.removeItem('refresh');
router.push('/auth')
}; };
watch( watch(
user, user,
(newValue, oldValue) => { (newValue, oldValue) => {
cod2user.value = cod2user.value = 'login' in newValue && newValue.login.startsWith('9966-') ? true : false;
"login" in newValue && newValue.login.startsWith("9966-")
? true
: false;
}, },
{ deep: true } { deep: true },
); );
function settingsUp(newSet) { function settingsUp(newSet) {
localStorage.setItem(user.value.is_idEmployee, JSON.stringify(newSet));
localStorage.setItem(user.value.is_idEmployee, JSON.stringify(newSet)
);
} }
watch(
() => calendar.value,
(newValue) => {
let settings = JSON.parse(localStorage.getItem(user.value.is_idEmployee));
settings.calendar = newValue;
settingsUp(settings);
},
{ deep: true },
);
watch(() => calendar.value, (newValue) => { return { user, setUser, cod2user, logging, logout, calendar, getuserFromStorage };
let settings = JSON.parse(localStorage.getItem(user.value.is_idEmployee))
settings.calendar = newValue
settingsUp(settings)
}, {deep: true})
return { user, setUser, cod2user, logging, logout, calendar,getuserFromStorage };
}); });
+1 -1
View File
@@ -1,5 +1,5 @@
import { defineStore } from 'pinia' import { defineStore } from 'pinia'
import { ref } from 'vue' import {ref, watch} from 'vue'
import { clearAxios } from '@/utils/axios-api' import { clearAxios } from '@/utils/axios-api'
export const useMainmenuStore = defineStore('MainmenuStore', () => { export const useMainmenuStore = defineStore('MainmenuStore', () => {
+292
View File
@@ -0,0 +1,292 @@
import { defineStore } from 'pinia';
import { ref, computed, watch } from 'vue';
import { axiosApiInstance } from '@/utils/axios-api';
import { useAccountStore } from '@/store/AccountStore';
export const useCalendarStore = defineStore('calendarStore', () => {
const accountStore = useAccountStore();
// State
const selectedDate = ref(new Date());
const events = ref([]);
const selectedEvent = ref(null);
const showEventDialog = ref(false);
const currentView = ref('dayGridMonth'); // Текущий вид календаря
const calendars = ref([]); // Список календарей пользователя
const lastUpdatedBy = ref(null);
const holidays = ref([]);
const dictEmployees = ref([]);
const dictEmployeesLoaded = ref(false);
const employees = ref([]);
// Массив ID скрытых календарей. Загружаем из localStorage при инициализации.
const hiddenCalendarIds = ref([]);
// Getters
const formattedSelectedDate = computed(() => selectedDate.value.toISOString().split('T')[0]);
const myCalendars = computed(() => {
const userId = accountStore.user.is_idEmployee;
return calendars.value
.filter((calendar) => calendar.author === userId) // ТОЛЬКО календари где пользователь автор
.map((calendar) => {
const participant = calendar.participant.find((p) => p.participant_calendar === userId);
const isEditor = participant?.editor === true;
return {
...calendar,
isAuthor: true, // Всегда true, так как отфильтровали по автору
isEditor,
visible: !hiddenCalendarIds.value.includes(calendar.id),
};
});
});
const subscribedCalendars = computed(() => {
const userId = accountStore.user.is_idEmployee;
return calendars.value
.filter((calendar) => calendar.author !== userId) // Все календари где пользователь НЕ автор
.map((calendar) => {
const participant = calendar.participant.find((p) => p.participant_calendar === userId);
const isEditor = participant?.editor === true;
return {
...calendar,
isAuthor: false,
isEditor,
visible: !hiddenCalendarIds.value.includes(calendar.id),
};
});
});
const eventsForSelectedDate = computed(() =>
events.value.filter((event) => event.date_start.split('T')[0] === formattedSelectedDate.value),
);
// Actions
const setSelectedDate = (date, source = 'unknown') => {
selectedDate.value = new Date(date);
lastUpdatedBy.value = source;
};
const setSelectedDateFromCalendar = (info) => {
const date = new Date(info.dateStr);
setSelectedDate(date, 'calendar');
};
const setSelectedDateFromPicker = (date) => {
setSelectedDate(date, 'datepicker');
};
const setCurrentView = (view) => {
currentView.value = view;
};
// Загрузка календарей пользователя
const loadCalendars = async () => {
try {
const response = await axiosApiInstance.get('api/calendar_of_events/my_calendars/');
calendars.value = response.data;
hiddenCalendarIds.value = [];
} catch (error) {
console.error('Ошибка загрузки календарей:', error);
}
};
const loadDictEmployees = async () => {
try {
const response = await axiosApiInstance.get(`api/vote/getdictemployee/`);
dictEmployees.value = response.data;
dictEmployeesLoaded.value = true;
} catch (error) {
console.error('Ошибка получения всех сотрудников:', error);
dictEmployeesLoaded.value = false;
}
};
const loadEmployees = async () => {
try {
const response = await axiosApiInstance.get('api/calendar_of_events/get_employees/');
employees.value = response.data;
} catch (error) {
console.error('Ошибка получения всех сотрудников:', error);
}
};
const toggleCalendarVisibility = (calendarId) => {
const index = hiddenCalendarIds.value.indexOf(calendarId);
if (index === -1) {
// Если ID нет в массиве скрытых, добавляем его (значит, календарь скрывается)
hiddenCalendarIds.value.push(calendarId);
} else {
// Если ID есть в массиве, удаляем его (значит, календарь показывается)
hiddenCalendarIds.value.splice(index, 1);
}
};
const visibleCalendars = computed(() =>
calendars.value.filter((calendar) => !hiddenCalendarIds.value.includes(calendar.id)),
);
const calendarColorMap = computed(() => {
const map = new Map();
calendars.value.forEach((calendar) => {
map.set(calendar.id, calendar.cl_color);
});
return map;
});
const allEvents = computed(() => {
return calendars.value
.filter((calendar) => !hiddenCalendarIds.value.includes(calendar.id))
.flatMap((calendar) =>
calendar.events.map((event) => ({
...event,
calendarData: calendar,
})),
);
});
const editableEvents = computed(() => {
const currentUserId = accountStore.user.is_idEmployee;
return allEvents.value.filter((event) => {
const calendar = event.calendarData;
if (!calendar) return false;
// Автор календаря
if (calendar.author === currentUserId) return true;
// Ищем участника с правами редактора
const isEditor = calendar.participant?.some(
(part) => part.participant_calendar === currentUserId && part.editor === true,
);
return isEditor;
});
});
const canEditEvent = (eventId) => {
const id = Number(eventId);
return editableEvents.value.some((e) => e.id === id);
};
const fetchHolidays = async (year) => {
try {
const response = await axiosApiInstance.get(
`api/calendar_of_events/exclusion_dates/?year=${year}`,
);
holidays.value = response.data;
return holidays.value;
} catch (err) {
console.error('Ошибка загрузки праздников:', err);
throw err;
}
};
// Метод для проверки, является ли день выходным или праздничным
const isNonWorkingDay = (dateInput) => {
let date;
// Если входные данные — это строка в формате 'YYYY-MM-DD'
if (typeof dateInput === 'string') {
date = new Date(dateInput);
}
// Если входные данные — это объект Date
else if (dateInput instanceof Date) {
date = new Date(dateInput);
}
// Если входные данные некорректны
else {
return false;
}
// Проверяем, что дата корректна
if (isNaN(date.getTime())) {
return false;
}
const day = date.getDay();
// Проверка на выходной (суббота или воскресенье)
const isWeekend = day === 0 || day === 6;
// Получаем год, месяц и день
const year = date.getFullYear();
const month = date.getMonth() + 1; // Месяцы в JS начинаются с 0
const dayOfMonth = date.getDate();
const normalizedCurrentDate = `${year}-${String(month).padStart(2, '0')}-${String(dayOfMonth).padStart(2, '0')}`;
// Проверяем, что данные о праздничных днях существуют для текущего года и месяца
const holidaysForYear = holidays.value[year] || {};
const holidaysForMonth = holidaysForYear[month] || [];
// Проверка на исключение (рабочая суббота или праздничный будний день)
const isExceptionDay = holidaysForMonth.includes(normalizedCurrentDate);
const result = {
isNonWorking: (isWeekend && !isExceptionDay) || (!isWeekend && isExceptionDay),
isWeekendForStyling: isWeekend && !isExceptionDay,
isHoliday: !isWeekend && isExceptionDay,
};
return result;
};
// Открыть диалог создания/редактирования
const openEventDialog = (event = null) => {
selectedEvent.value = event;
showEventDialog.value = true;
};
// Закрыть диалог
const closeEventDialog = () => {
showEventDialog.value = false;
selectedEvent.value = null;
};
return {
// State
selectedDate,
events,
selectedEvent,
showEventDialog,
currentView,
calendars,
lastUpdatedBy,
hiddenCalendarIds,
holidays,
dictEmployeesLoaded,
// Getters
formattedSelectedDate,
myCalendars,
subscribedCalendars,
eventsForSelectedDate,
visibleCalendars,
allEvents,
calendarColorMap,
dictEmployees,
employees,
editableEvents,
canEditEvent,
// Actions
setSelectedDate,
setCurrentView,
loadCalendars,
openEventDialog,
closeEventDialog,
setSelectedDateFromCalendar,
setSelectedDateFromPicker,
toggleCalendarVisibility,
fetchHolidays,
isNonWorkingDay,
loadDictEmployees,
loadEmployees,
};
});
+7 -7
View File
@@ -32,7 +32,7 @@ export function checking_for_entry(where, what) {
if (!where.includes(what)) { if (!where.includes(what)) {
where.push(what); where.push(what);
} }
} }
export function getfromserver(path, reactive) { export function getfromserver(path, reactive) {
try { try {
@@ -63,7 +63,7 @@ export function checkremote(filecheck) {
export default str; export default str;
export function splitname(name) { export function splitname(name) {
return name.familyname + " " + name.name[0] + "." + name.parentname[0] + "."; return name.familyname + " " + name.name[0] + "." + name.parentname[0] + ".";
} }
@@ -71,7 +71,7 @@ export function pagecounter() {
// Функция записи посещения страницы сотрудникам. // Функция записи посещения страницы сотрудникам.
// В случае, если в роуте присутствует ключ мета и в нем ико - тогда производится запись // В случае, если в роуте присутствует ключ мета и в нем ико - тогда производится запись
const router = useRouter(); const router = useRouter();
if('meta' in router.currentRoute.value && 'ico' in router.currentRoute.value.meta){ if('meta' in router.currentRoute.value && 'ico' in router.currentRoute.value.meta){
const accountStore = useAccountStore(); const accountStore = useAccountStore();
const appStore = useAppStore(); const appStore = useAppStore();
@@ -95,7 +95,7 @@ export function pagecounter() {
export function useICalReader(url) { export function useICalReader(url) {
/// ///
const events = ref([]); const events = ref([]);
const loadICalFile = async () => { const loadICalFile = async () => {
try { try {
const response = await fetch(url); const response = await fetch(url);
@@ -120,13 +120,13 @@ export function useICalReader(url) {
location: event.location, location: event.location,
} }
}) })
return { return {
type: "calendar", type: "calendar",
title: name, title: name,
calendar: calendarEvents, calendar: calendarEvents,
} }
// const vevents = comp.getAllSubcomponents('vevent') // const vevents = comp.getAllSubcomponents('vevent')
// const eventsData = vevents.map(vevent => ({ // const eventsData = vevents.map(vevent => ({
// vevent: vevent, // vevent: vevent,
@@ -173,4 +173,4 @@ export function useICalReader(url) {
export function declOfNum(value, titles) { export function declOfNum(value, titles) {
const cases = [2, 0, 1, 1, 1, 2]; const cases = [2, 0, 1, 1, 1, 2];
return titles[(value % 100 > 4 && value % 100 < 20) ? 2 : cases[(value % 10 < 5) ? value % 10 : 5]]; return titles[(value % 100 > 4 && value % 100 < 20) ? 2 : cases[(value % 10 < 5) ? value % 10 : 5]];
} }
+26 -16
View File
@@ -1,17 +1,15 @@
<template> <template>
<v-container fluid class="d-flex mx-0 pa-0"> <v-container fluid class="d-flex pa-0">
<v-row class="ma-2"> <v-row class="ma-0">
<v-col class="d-flex flex-column" lg="7" md="12" cols="12"> <v-col class="d-flex flex-column" lg="7" md="12" cols="12">
<v-row class="flex-grow-0"> <div class="flex-grow-0 mb-3">
<v-col class="pa-1">
<Carousel-list /> <Carousel-list />
</v-col> </div>
</v-row>
<v-row style="height: 250px"> <div class="flex-grow-1">
<v-col class="d-flex flex-column flex-grow-0 pa-1"> <HomeCalendarWidget class="h-100"/>
<!-- <event-calendar/> -->
</v-col> </div>
</v-row>
</v-col> </v-col>
<v-col class="d-flex flex-column" lg="5" md="12" cols="12"> <v-col class="d-flex flex-column" lg="5" md="12" cols="12">
<v-row> <v-row>
@@ -47,7 +45,12 @@
<v-btn-toggle v-model="toggle" divided variant="outlined" color="teal-darken-4"> <v-btn-toggle v-model="toggle" divided variant="outlined" color="teal-darken-4">
<v-tooltip :text="x.pages__page" location="top"> <v-tooltip :text="x.pages__page" location="top">
<template v-slot:activator="{ props }"> <template v-slot:activator="{ props }">
<v-btn v-bind="props" :icon="x.pages__ico" :to="x.pages__fullPath" color="teal-darken-4" /> <v-btn
v-bind="props"
:icon="x.pages__ico"
:to="x.pages__fullPath"
color="teal-darken-4"
/>
</template> </template>
</v-tooltip> </v-tooltip>
</v-btn-toggle> </v-btn-toggle>
@@ -74,14 +77,15 @@ import NewsHome from '@/components/news-home.vue';
import DigitalLetna from '@/components/digital-letna.vue'; import DigitalLetna from '@/components/digital-letna.vue';
import { axiosApiInstance } from '@/utils/axios-api'; import { axiosApiInstance } from '@/utils/axios-api';
import HomeCalendarWidget from '@/components/calendar_of_events/UI_calendar/HomeCalendarWidget.vue';
import { useCalendarStore } from '@/store/calendarStore';
export default { export default {
components: { components: {
CarouselList, CarouselList,
DigitalLetna, DigitalLetna,
NewsHome, NewsHome,
HomeCalendarWidget,
}, },
setup() { setup() {
@@ -90,11 +94,17 @@ export default {
const toggle = ref(null); const toggle = ref(null);
const accountStore = useAccountStore(); const accountStore = useAccountStore();
const calendarStore = useCalendarStore();
pagecounter(); pagecounter();
const fetchMyCalendars = () => {
calendarStore.loadCalendars();
};
onMounted(() => { onMounted(() => {
favoritLinks(); favoritLinks();
fetchMyCalendars();
}); });
const favoritLinks = () => { const favoritLinks = () => {
@@ -108,14 +118,14 @@ export default {
appStore, appStore,
favoritLinks, favoritLinks,
favorit, favorit,
fetchMyCalendars,
toggle, toggle,
}; };
}, },
}; };
</script> </script>
<style lang="scss"> <style lang="scss" scoped>
.v-picker-title, .v-picker-title,
.v-picker__header, .v-picker__header,
.v-picker__actions { .v-picker__actions {
+8 -1
View File
@@ -1,7 +1,14 @@
<template> <template>
<v-row class="justify-center ma-0 h-100"> <v-row class="justify-center ma-0 ">
<v-col class="flex-column d-flex"> <v-col class="flex-column d-flex">
<news-crossroad /> <news-crossroad />
</v-col> </v-col>
</v-row> </v-row>
</template> </template>
File renamed without changes.
+2 -2
View File
@@ -129,8 +129,8 @@ export default {
resultsModal.value = false; resultsModal.value = false;
selectedVoting.value = null; selectedVoting.value = null;
router.push({ name: 'VoteHomePage' }); router.push({ name: 'VoteHomePage' });
if (route.name === 'Voting') updating('active'); // if (route.name === 'Voting') updating('active');
if (route.name === 'VoteResults') updating('completed'); // if (route.name === 'VoteResults') updating('completed');
}; };
const openModal = async (type, voting) => { const openModal = async (type, voting) => {
@@ -1,42 +0,0 @@
<template>
<v-container fluid>
<HeaderEmployeeDirectory :department="department" v-model:selectedDep="selectedDep" v-model:isWork="isWork" v-model:search="search"/>
<CardEmployeeDirection :selectedDep="selectedDep" :isWork="isWork" :search="search"/>
</v-container>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { axiosApiInstance } from '@/utils/axios-api'
import HeaderEmployeeDirectory from '../../components/EmployeeDirectory/HeaderEmployeeDirectory.vue';
import CardEmployeeDirection from '../../components/EmployeeDirectory/CardEmployeeDirection.vue';
const department = ref([])
const selectedDep = ref({
id: 0,
persons: []
})
const isWork = ref(0)
const search = ref('')
async function getDepartment() {
try {
const response = await axiosApiInstance.get('api/userauth/getdepartments')
response.data[0].persons= response.data.reduce((acc,elm)=>{
acc.push(...elm.persons)
return acc},[]
)
department.value = response.data
} catch (error) {
console.error('Ошибка запроса получения отделов:', error);
throw error;
}
}
onMounted(async () => {
await getDepartment();
selectedDep.value = department.value[0]
})
</script>