From ecfe0975897ad8383e3fcb410fd820b8ad5473db Mon Sep 17 00:00:00 2001 From: romanskijdev Date: Mon, 15 Jun 2026 13:14:29 +0300 Subject: [PATCH] Added admin service --- .gitea/workflows/deploy.yml | 495 +- core/config/config-load-options.go | 5 +- core/config/configcore.go | 3 + core/db/db.go | 2 + .../default_data/approval_topics.csv | 232 +- core/db/db_migration/tables.go | 1 + core/db/db_migration/tables/admins.go | 43 + core/db/methods/admin.go | 249 + core/db/methods/role.go | 11 + core/db/table_names/table_names.go | 1 + core/typescore/admin.go | 21 + core/typescore/api.go | 21 + core/typescore/user.go | 7 + core/typescore/user_hierarchy.go | 1 - core/utilscore/gen.go | 18 + core/utilscore/ip.go | 37 + core/utilscore/validation.go | 34 + core/variables/const.go | 10 + core/variables/redis-const.go | 5 + deploy.sh | 258 +- go.work.sum | 40 +- service/rest_admin_service/cmd/app.go | 78 + service/rest_admin_service/docs/docs.go | 3990 +++++++++++++++++ service/rest_admin_service/docs/swagger.json | 3966 ++++++++++++++++ service/rest_admin_service/docs/swagger.yaml | 2645 +++++++++++ service/rest_admin_service/go.mod | 71 + service/rest_admin_service/go.sum | 202 + .../handlers/admin/handlers.go | 138 + .../handlers/admin/routes.go | 37 + .../handlers/approval_steps/handlers.go | 446 ++ .../handlers/approval_steps/routes.go | 43 + .../handlers/approvals/handlers.go | 372 ++ .../handlers/approvals/routes.go | 41 + .../handlers/auth/handlers.go | 184 + .../handlers/auth/routes.go | 39 + .../handlers/departments/handlers.go | 262 ++ .../handlers/departments/routes.go | 47 + .../handlers/permission/handlers.go | 467 ++ .../handlers/permission/routes.go | 43 + .../handlers/profile/handlers.go | 102 + .../handlers/profile/routes.go | 36 + .../handlers/roles/handlers.go | 282 ++ .../handlers/roles/routes.go | 39 + .../handlers/topic_categories/handlers.go | 281 ++ .../handlers/topic_categories/routes.go | 39 + .../handlers/topic_executors/handlers.go | 419 ++ .../handlers/topic_executors/routes.go | 43 + .../handlers/topics/handlers.go | 361 ++ .../handlers/topics/routes.go | 39 + .../handlers/user_hierarchy/handlers.go | 441 ++ .../handlers/user_hierarchy/routes.go | 39 + .../handlers/user_roles/handlers.go | 378 ++ .../handlers/user_roles/routes.go | 53 + .../handlers/users/handlers.go | 237 + .../handlers/users/routes.go | 37 + .../common/update/callback.go | 3 + 56 files changed, 17280 insertions(+), 114 deletions(-) create mode 100644 core/db/db_migration/tables/admins.go create mode 100644 core/db/methods/admin.go create mode 100644 core/typescore/admin.go create mode 100644 core/typescore/api.go create mode 100644 core/utilscore/gen.go create mode 100644 core/utilscore/ip.go create mode 100644 core/utilscore/validation.go create mode 100644 core/variables/const.go create mode 100644 core/variables/redis-const.go create mode 100644 service/rest_admin_service/docs/docs.go create mode 100644 service/rest_admin_service/docs/swagger.json create mode 100644 service/rest_admin_service/docs/swagger.yaml create mode 100644 service/rest_admin_service/go.sum create mode 100644 service/rest_admin_service/handlers/admin/handlers.go create mode 100644 service/rest_admin_service/handlers/admin/routes.go create mode 100644 service/rest_admin_service/handlers/approval_steps/handlers.go create mode 100644 service/rest_admin_service/handlers/approval_steps/routes.go create mode 100644 service/rest_admin_service/handlers/approvals/handlers.go create mode 100644 service/rest_admin_service/handlers/approvals/routes.go create mode 100644 service/rest_admin_service/handlers/auth/handlers.go create mode 100644 service/rest_admin_service/handlers/auth/routes.go create mode 100644 service/rest_admin_service/handlers/departments/handlers.go create mode 100644 service/rest_admin_service/handlers/departments/routes.go create mode 100644 service/rest_admin_service/handlers/permission/handlers.go create mode 100644 service/rest_admin_service/handlers/permission/routes.go create mode 100644 service/rest_admin_service/handlers/profile/handlers.go create mode 100644 service/rest_admin_service/handlers/profile/routes.go create mode 100644 service/rest_admin_service/handlers/roles/handlers.go create mode 100644 service/rest_admin_service/handlers/roles/routes.go create mode 100644 service/rest_admin_service/handlers/topic_categories/handlers.go create mode 100644 service/rest_admin_service/handlers/topic_categories/routes.go create mode 100644 service/rest_admin_service/handlers/topic_executors/handlers.go create mode 100644 service/rest_admin_service/handlers/topic_executors/routes.go create mode 100644 service/rest_admin_service/handlers/topics/handlers.go create mode 100644 service/rest_admin_service/handlers/topics/routes.go create mode 100644 service/rest_admin_service/handlers/user_hierarchy/handlers.go create mode 100644 service/rest_admin_service/handlers/user_hierarchy/routes.go create mode 100644 service/rest_admin_service/handlers/user_roles/handlers.go create mode 100644 service/rest_admin_service/handlers/user_roles/routes.go create mode 100644 service/rest_admin_service/handlers/users/handlers.go create mode 100644 service/rest_admin_service/handlers/users/routes.go diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml index 438292b..68e97bb 100644 --- a/.gitea/workflows/deploy.yml +++ b/.gitea/workflows/deploy.yml @@ -4,31 +4,504 @@ on: push: branches: [main] +env: + REPO_DIR: "/workspace/ruspet_portal_back" + REPO_URL: "https://72.56.235.246.nip.io/gitea/romanskijdev/ruspet_portal_back.git" + BACKUP_DIR: "/tmp/deploy_backups" + + # Имена сервисов + TELEGRAM_SERVICE: "telegram_service" + BALANCER_SERVICE: "rest_balancer_service" + ADMIN_SERVICE: "rest_admin_service" + MIGRATIONS_SERVICE: "system_service" + jobs: deploy: runs-on: self-hosted - steps: - - name: Checkout - run: | - REPO_DIR="/workspace/ruspet_portal_back" - REPO_URL="https://72.56.235.246.nip.io/gitea/romanskijdev/ruspet_portal_back.git" + timeout-minutes: 20 + steps: + # ═══════════════════════════════════════════════════════════════ + # ШАГ 1: Информация о деплое + # ═══════════════════════════════════════════════════════════════ + - name: 📋 Deployment Info + run: | + echo "════════════════════════════════════════" + echo "🚀 Starting deployment" + echo "════════════════════════════════════════" + echo "Branch: ${{ github.ref }}" + echo "Commit: ${{ github.sha }}" + echo "Author: ${{ github.actor }}" + echo "Message: ${{ github.event.head_commit.message }}" + echo "Time: $(date '+%Y-%m-%d %H:%M:%S')" + echo "Runner: $(hostname)" + echo "════════════════════════════════════════" + + # ═══════════════════════════════════════════════════════════════ + # ШАГ 2: Checkout с анализом изменений + # ═══════════════════════════════════════════════════════════════ + - name: 📦 Checkout & Analyze Changes + id: checkout + run: | + mkdir -p "$BACKUP_DIR" + + # Инициализируем флаги + DEPLOY_MIGRATIONS=false + DEPLOY_TELEGRAM=false + DEPLOY_BALANCER=false + DEPLOY_ADMIN=false + if [ -d "$REPO_DIR/.git" ]; then echo "📦 Updating existing repo..." cd "$REPO_DIR" + + OLD_COMMIT=$(git rev-parse HEAD) + echo "Previous commit: $OLD_COMMIT" + git fetch origin + + # Получаем список изменённых файлов + CHANGED_FILES=$(git diff --name-only $OLD_COMMIT origin/develop 2>/dev/null || echo "") + + if [ -z "$CHANGED_FILES" ]; then + echo "⚠️ No changes detected, deploying all services..." + DEPLOY_MIGRATIONS=true + DEPLOY_TELEGRAM=true + DEPLOY_BALANCER=true + DEPLOY_ADMIN=true + else + echo "📝 Changed files:" + echo "$CHANGED_FILES" | sed 's/^/ /' + echo "" + + # Изменения в core или deploy.sh влияют на все сервисы + if echo "$CHANGED_FILES" | grep -qE "^(core/|deploy\.sh)"; then + echo "🔄 Core or deploy.sh changed — deploying ALL services" + DEPLOY_MIGRATIONS=true + DEPLOY_TELEGRAM=true + DEPLOY_BALANCER=true + DEPLOY_ADMIN=true + else + # Проверяем изменения в конкретных сервисах + if echo "$CHANGED_FILES" | grep -q "^service/system_service/"; then + echo "🗄️ Migrations service changed" + DEPLOY_MIGRATIONS=true + fi + + if echo "$CHANGED_FILES" | grep -q "^service/telegram_service/"; then + echo "🤖 Telegram bot changed" + DEPLOY_TELEGRAM=true + fi + + if echo "$CHANGED_FILES" | grep -q "^service/rest_balancer_service/"; then + echo "⚖️ Balancer service changed" + DEPLOY_BALANCER=true + fi + + if echo "$CHANGED_FILES" | grep -q "^service/rest_admin_service/"; then + echo "🔧 Admin service changed" + DEPLOY_ADMIN=true + fi + fi + fi + git reset --hard origin/develop + NEW_COMMIT=$(git rev-parse HEAD) + echo "New commit: $NEW_COMMIT" else echo "📦 Cloning repo..." git clone -b develop "$REPO_URL" "$REPO_DIR" + DEPLOY_MIGRATIONS=true + DEPLOY_TELEGRAM=true + DEPLOY_BALANCER=true + DEPLOY_ADMIN=true + fi + + # Сохраняем переменные + { + echo "DEPLOY_MIGRATIONS=$DEPLOY_MIGRATIONS" + echo "DEPLOY_TELEGRAM=$DEPLOY_TELEGRAM" + echo "DEPLOY_BALANCER=$DEPLOY_BALANCER" + echo "DEPLOY_ADMIN=$DEPLOY_ADMIN" + } >> $GITHUB_ENV + + echo "" + echo "📊 Deployment plan:" + echo " 🗄️ Migrations: $DEPLOY_MIGRATIONS" + echo " 🤖 Telegram: $DEPLOY_TELEGRAM" + echo " ⚖️ Balancer: $DEPLOY_BALANCER" + echo " 🔧 Admin: $DEPLOY_ADMIN" + + # ═══════════════════════════════════════════════════════════════ + # ШАГ 3: Проверка плана деплоя + # ═══════════════════════════════════════════════════════════════ + - name: 🔍 Check Deployment Plan + id: check_plan + run: | + if [ "$DEPLOY_MIGRATIONS" = "false" ] && \ + [ "$DEPLOY_TELEGRAM" = "false" ] && \ + [ "$DEPLOY_BALANCER" = "false" ] && \ + [ "$DEPLOY_ADMIN" = "false" ]; then + echo "⏭️ No services need to be deployed — skipping" + echo "SKIP_DEPLOY=true" >> $GITHUB_ENV + else + echo "SKIP_DEPLOY=false" >> $GITHUB_ENV fi - - name: Inject config + # ═══════════════════════════════════════════════════════════════ + # ШАГ 4: Inject config + # ═══════════════════════════════════════════════════════════════ + - name: 🔐 Inject Config + if: env.SKIP_DEPLOY == 'false' run: | - cp /etc/ruspet/config.yml /workspace/ruspet_portal_back/core/config/config.yml + if [ ! -f "/etc/ruspet/config.yml" ]; then + echo "❌ Config file not found at /etc/ruspet/config.yml" + exit 1 + fi + + cp /etc/ruspet/config.yml "$REPO_DIR/core/config/config.yml" echo "✅ Config injected" -# - name: Build & Deploy -# run: | -# cd /workspace/ruspet_portal_back -# bash deploy.sh \ No newline at end of file + # ═══════════════════════════════════════════════════════════════ + # ШАГ 5: Кэширование Go модулей + # ═══════════════════════════════════════════════════════════════ + - name: 💾 Cache Go Modules + if: env.SKIP_DEPLOY == 'false' + uses: actions/cache@v3 + with: + path: | + ~/.cache/go-build + ~/go/pkg/mod + /root/.cache/go-build + /root/go/pkg/mod + key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} + restore-keys: | + ${{ runner.os }}-go- + + # ═══════════════════════════════════════════════════════════════ + # ШАГ 6: Создание backup-ов перед деплоем + # ═══════════════════════════════════════════════════════════════ + - name: 💾 Create Backups + if: env.SKIP_DEPLOY == 'false' + run: | + BACKUP_TIMESTAMP=$(date +%Y%m%d_%H%M%S) + echo "BACKUP_TIMESTAMP=$BACKUP_TIMESTAMP" >> $GITHUB_ENV + + # Функция для создания backup + create_backup() { + local service=$1 + local binary="/usr/local/bin/$service" + + if [ -f "$binary" ]; then + local backup_file="$BACKUP_DIR/${service}_${BACKUP_TIMESTAMP}" + cp "$binary" "$backup_file" + echo "💾 Backup created: $backup_file" + # Сохраняем путь к backup в env (в верхнем регистре) + local var_name="${service^^}_BACKUP" + var_name=$(echo "$var_name" | tr '-' '_') + echo "$var_name=$backup_file" >> $GITHUB_ENV + fi + } + + # Создаём backup-ы для долгоживущих сервисов + if [ "$DEPLOY_TELEGRAM" = "true" ]; then + create_backup "$TELEGRAM_SERVICE" + fi + + if [ "$DEPLOY_BALANCER" = "true" ]; then + create_backup "$BALANCER_SERVICE" + fi + + if [ "$DEPLOY_ADMIN" = "true" ]; then + create_backup "$ADMIN_SERVICE" + fi + + # Очистка старых backup-ов (оставляем последние 10) + echo "🧹 Cleaning old backups..." + ls -t "$BACKUP_DIR"/* 2>/dev/null | tail -n +11 | xargs -r rm -- + echo "✅ Backups ready" + + # ═══════════════════════════════════════════════════════════════ + # ШАГ 7: Миграции БД (ВСЕГДА ПЕРВЫМ!) + # ═══════════════════════════════════════════════════════════════ + - name: 🗄️ Run Database Migrations + if: env.DEPLOY_MIGRATIONS == 'true' && env.SKIP_DEPLOY == 'false' + id: deploy_migrations + run: | + cd "$REPO_DIR" + echo "🗄️ Running database migrations..." + + if bash deploy.sh migrations; then + echo "✅ Migrations completed successfully" + echo "MIGRATIONS_DEPLOYED=true" >> $GITHUB_ENV + else + echo "❌ Migrations failed" + echo "MIGRATIONS_DEPLOYED=false" >> $GITHUB_ENV + exit 1 + fi + + # ═══════════════════════════════════════════════════════════════ + # ШАГ 8: Деплой Telegram бота + # ═══════════════════════════════════════════════════════════════ + - name: 🤖 Deploy Telegram Bot + if: env.DEPLOY_TELEGRAM == 'true' && env.SKIP_DEPLOY == 'false' + id: deploy_telegram + run: | + cd "$REPO_DIR" + echo "🤖 Deploying Telegram bot..." + + if bash deploy.sh telegram; then + echo "✅ Telegram bot deployed" + echo "TELEGRAM_DEPLOYED=true" >> $GITHUB_ENV + + sleep 3 + if systemctl is-active --quiet "$TELEGRAM_SERVICE"; then + echo "✅ Telegram bot is running" + else + echo "❌ Telegram bot failed to start" + exit 1 + fi + else + echo "❌ Telegram bot deployment failed" + echo "TELEGRAM_DEPLOYED=false" >> $GITHUB_ENV + exit 1 + fi + + # ═══════════════════════════════════════════════════════════════ + # ШАГ 9: Деплой балансировщика + # ═══════════════════════════════════════════════════════════════ + - name: ⚖️ Deploy Balancer Service + if: env.DEPLOY_BALANCER == 'true' && env.SKIP_DEPLOY == 'false' + id: deploy_balancer + run: | + cd "$REPO_DIR" + echo "⚖️ Deploying balancer service..." + + if bash deploy.sh balancer; then + echo "✅ Balancer service deployed" + echo "BALANCER_DEPLOYED=true" >> $GITHUB_ENV + + sleep 3 + if systemctl is-active --quiet "$BALANCER_SERVICE"; then + echo "✅ Balancer service is running" + else + echo "❌ Balancer service failed to start" + exit 1 + fi + else + echo "❌ Balancer deployment failed" + echo "BALANCER_DEPLOYED=false" >> $GITHUB_ENV + exit 1 + fi + + # ═══════════════════════════════════════════════════════════════ + # ШАГ 10: Деплой админки + # ═══════════════════════════════════════════════════════════════ + - name: 🔧 Deploy Admin Service + if: env.DEPLOY_ADMIN == 'true' && env.SKIP_DEPLOY == 'false' + id: deploy_admin + run: | + cd "$REPO_DIR" + echo "🔧 Deploying admin service..." + + if bash deploy.sh admin swagger; then + echo "✅ Admin service deployed with Swagger" + echo "ADMIN_DEPLOYED=true" >> $GITHUB_ENV + + sleep 3 + if systemctl is-active --quiet "$ADMIN_SERVICE"; then + echo "✅ Admin service is running" + else + echo "❌ Admin service failed to start" + exit 1 + fi + + if [ -f "$REPO_DIR/service/rest_admin_service/docs/swagger.json" ]; then + echo "✅ Swagger documentation generated" + fi + else + echo "❌ Admin deployment failed" + echo "ADMIN_DEPLOYED=false" >> $GITHUB_ENV + exit 1 + fi + + # ═══════════════════════════════════════════════════════════════ + # ШАГ 11: Rollback при ошибке + # ═══════════════════════════════════════════════════════════════ + - name: ⏮️ Rollback on Failure + if: failure() + run: | + echo "════════════════════════════════════════" + echo "⏮️ Starting rollback..." + echo "════════════════════════════════════════" + + # Функция для rollback сервиса + rollback_service() { + local service=$1 + local backup_var="${service^^}_BACKUP" + backup_var=$(echo "$backup_var" | tr '-' '_') + local backup_file="${!backup_var}" + + if [ -n "$backup_file" ] && [ -f "$backup_file" ]; then + echo "⏮️ Rolling back $service..." + sudo cp "$backup_file" "/usr/local/bin/$service" + sudo chmod +x "/usr/local/bin/$service" + sudo systemctl restart "$service" + sleep 2 + + if systemctl is-active --quiet "$service"; then + echo "✅ $service rolled back successfully" + else + echo "❌ $service rollback failed" + fi + else + echo "⚠️ No backup available for $service" + fi + } + + # Rollback всех задеплоенных сервисов + if [ "$DEPLOY_TELEGRAM" = "true" ]; then + rollback_service "$TELEGRAM_SERVICE" + fi + + if [ "$DEPLOY_BALANCER" = "true" ]; then + rollback_service "$BALANCER_SERVICE" + fi + + if [ "$DEPLOY_ADMIN" = "true" ]; then + rollback_service "$ADMIN_SERVICE" + fi + + echo "════════════════════════════════════════" + echo "✅ Rollback completed" + echo "════════════════════════════════════════" + + # ═══════════════════════════════════════════════════════════════ + # ШАГ 12: Финальная верификация + # ═══════════════════════════════════════════════════════════════ + - name: ✅ Verify Services + if: env.SKIP_DEPLOY == 'false' && success() + run: | + echo "🔍 Verifying services..." + echo "" + + ALL_OK=true + + verify_service() { + local service=$1 + local should_deploy=$2 + + if [ "$should_deploy" = "true" ]; then + if systemctl is-active --quiet "$service"; then + UPTIME=$(systemctl show "$service" --property=ActiveEnterTimestamp --value) + echo "✅ $service: running (since $UPTIME)" + else + echo "❌ $service: NOT RUNNING" + ALL_OK=false + fi + else + echo "⏭️ $service: skipped" + fi + } + + verify_service "$TELEGRAM_SERVICE" "$DEPLOY_TELEGRAM" + verify_service "$BALANCER_SERVICE" "$DEPLOY_BALANCER" + verify_service "$ADMIN_SERVICE" "$DEPLOY_ADMIN" + + echo "" + if [ "$ALL_OK" = "true" ]; then + echo "✅ All services verified successfully" + else + echo "❌ Some services are not running" + exit 1 + fi + + # ═══════════════════════════════════════════════════════════════ + # ШАГ 13: Уведомление об успехе + # ═══════════════════════════════════════════════════════════════ + - name: 📢 Notify Success + if: success() + run: | + echo "════════════════════════════════════════" + echo "✅ Deployment completed successfully!" + echo "════════════════════════════════════════" + + if [ -n "${{ secrets.TELEGRAM_BOT_TOKEN }}" ] && [ -n "${{ secrets.TELEGRAM_CHAT_ID }}" ]; then + MESSAGE="✅ Deployment successful%0A%0A" + MESSAGE+="🌿 Branch: ${{ github.ref_name }}%0A" + MESSAGE+="📝 Commit: ${{ github.sha }}%0A" + MESSAGE+="👤 Author: ${{ github.actor }}%0A%0A" + + if [ "$DEPLOY_MIGRATIONS" = "true" ]; then + MESSAGE+="🗄️ Migrations: applied%0A" + fi + if [ "$DEPLOY_TELEGRAM" = "true" ]; then + MESSAGE+="🤖 Telegram: deployed%0A" + fi + if [ "$DEPLOY_BALANCER" = "true" ]; then + MESSAGE+="⚖️ Balancer: deployed%0A" + fi + if [ "$DEPLOY_ADMIN" = "true" ]; then + MESSAGE+="🔧 Admin: deployed%0A" + fi + + MESSAGE+="%0A⏰ $(date '+%Y-%m-%d %H:%M:%S')" + + curl -s -X POST "https://api.telegram.org/bot${{ secrets.TELEGRAM_BOT_TOKEN }}/sendMessage" \ + -d "chat_id=${{ secrets.TELEGRAM_CHAT_ID }}" \ + -d "parse_mode=HTML" \ + -d "text=$MESSAGE" || echo "⚠️ Telegram notification failed" + fi + + # ═══════════════════════════════════════════════════════════════ + # ШАГ 14: Уведомление об ошибке + # ═══════════════════════════════════════════════════════════════ + - name: 🚨 Notify Failure + if: failure() + run: | + echo "════════════════════════════════════════" + echo "❌ Deployment failed!" + echo "════════════════════════════════════════" + + # Показываем логи сервисов + for service in "$TELEGRAM_SERVICE" "$BALANCER_SERVICE" "$ADMIN_SERVICE"; do + echo "" + echo "📜 $service logs (last 20 lines):" + sudo journalctl -u "$service" -n 20 --no-pager || true + done + + if [ -n "${{ secrets.TELEGRAM_BOT_TOKEN }}" ] && [ -n "${{ secrets.TELEGRAM_CHAT_ID }}" ]; then + MESSAGE="❌ Deployment failed%0A%0A" + MESSAGE+="🌿 Branch: ${{ github.ref_name }}%0A" + MESSAGE+="📝 Commit: ${{ github.sha }}%0A" + MESSAGE+="👤 Author: ${{ github.actor }}%0A%0A" + MESSAGE+="⏮️ Rollback executed%0A" + MESSAGE+="%0A⏰ $(date '+%Y-%m-%d %H:%M:%S')" + + curl -s -X POST "https://api.telegram.org/bot${{ secrets.TELEGRAM_BOT_TOKEN }}/sendMessage" \ + -d "chat_id=${{ secrets.TELEGRAM_CHAT_ID }}" \ + -d "parse_mode=HTML" \ + -d "text=$MESSAGE" || echo "⚠️ Telegram notification failed" + fi + + # ═══════════════════════════════════════════════════════════════ + # ШАГ 15: Итоговая сводка + # ═══════════════════════════════════════════════════════════════ + - name: 📊 Deployment Summary + if: always() + run: | + echo "════════════════════════════════════════" + echo "📊 DEPLOYMENT SUMMARY" + echo "════════════════════════════════════════" + echo "Status: ${{ job.status }}" + echo "Branch: ${{ github.ref }}" + echo "Commit: ${{ github.sha }}" + echo "Author: ${{ github.actor }}" + echo "Duration: $SECONDS seconds" + echo "────────────────────────────────────────" + echo "Migrations: ${DEPLOY_MIGRATIONS:-false}" + echo "Telegram bot: ${DEPLOY_TELEGRAM:-false}" + echo "Balancer: ${DEPLOY_BALANCER:-false}" + echo "Admin: ${DEPLOY_ADMIN:-false}" + echo "Skip deploy: ${SKIP_DEPLOY:-false}" + echo "════════════════════════════════════════" \ No newline at end of file diff --git a/core/config/config-load-options.go b/core/config/config-load-options.go index 4d44a85..cf83fd1 100644 --- a/core/config/config-load-options.go +++ b/core/config/config-load-options.go @@ -2,8 +2,9 @@ package configcore // ExposedServiceOptions определяет, какие сервисы нужно загружать type ExposedServiceOptions struct { - TelegramService bool - RESTBaseService bool + TelegramService bool + RESTBaseService bool + RESTAdminService bool } // ConfigLoadOptions определяет, какие группы конфигурации нужно загружать diff --git a/core/config/configcore.go b/core/config/configcore.go index 80aab71..058298f 100644 --- a/core/config/configcore.go +++ b/core/config/configcore.go @@ -63,6 +63,9 @@ func copyConfigFields(options *ConfigLoadOptions, source, target *Config) { if options.Server.RESTBaseService { target.Server.RESTBaseService = source.Server.RESTBaseService } + if options.Server.RESTAdminService { + target.Server.RESTAdminService = source.Server.RESTAdminService + } if options.Server.TelegramService { target.Server.Telegram = source.Server.Telegram } diff --git a/core/db/db.go b/core/db/db.go index f6601eb..34f19f8 100644 --- a/core/db/db.go +++ b/core/db/db.go @@ -33,6 +33,7 @@ type ModuleDB struct { SuggestionMessage *dbcore.SuggestionMessageDB ApprovalAdditionalObserver *dbcore.ApprovalAdditionalObserverDB ApprovalTopicExecutor *dbcore.ApprovalTopicExecutorDB + Admin *dbcore.AdminDB } func NewModuleDB( @@ -82,6 +83,7 @@ func initDBModules(modules *ModuleDB, redisClient *redismodule.ModuleRedis) *Mod modules.Suggestion = dbcore.NewSuggestionDB(modules.Pool) modules.ApprovalAdditionalObserver = dbcore.NewApprovalAdditionalObserverDB(modules.Pool) modules.ApprovalTopicExecutor = dbcore.NewApprovalTopicExecutorDB(modules.Pool) + modules.Admin = dbcore.NewAdminDB(modules.Pool) return modules } diff --git a/core/db/db_migration/default_data/approval_topics.csv b/core/db/db_migration/default_data/approval_topics.csv index a553b82..b609521 100644 --- a/core/db/db_migration/default_data/approval_topics.csv +++ b/core/db/db_migration/default_data/approval_topics.csv @@ -1,84 +1,148 @@ -id,category_id,name,code,duration_type,time_type,payment_type,template,task_template,allows_file,allow_approver_selection,is_active,created_at,updated_at -1,1,Отгул — несколько дней частично,timeoff_multi_day_partial_own_expense,multi_day,partial,own_expense,"22.02.2022 с 10:00 по 14:00, 24.02.2022 с 09:00 по 12:00",,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -2,1,Отгул — несколько дней весь день в счёт отпуска,timeoff_multi_day_full_day_vacation_account,multi_day,full_day,vacation_account,"22.02.2022, 24.02.2022, 26.02.2022",,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -3,1,Отгул — несколько дней весь день за свой счёт,timeoff_multi_day_full_day_own_expense,multi_day,full_day,own_expense,"22.02.2022, 24.02.2022, 26.02.2022",,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -4,1,Отгул — диапазон частично,timeoff_date_range_partial_own_expense,date_range,partial,own_expense,22.02.2022 - 25.02.2022 с 16:00 по 18:00,,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -5,1,Отгул — диапазон весь день в счёт отпуска,timeoff_date_range_full_day_vacation_account,date_range,full_day,vacation_account,22.02.2022 - 25.02.2022,,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -6,1,Отгул — диапазон весь день за свой счёт,timeoff_date_range_full_day_own_expense,date_range,full_day,own_expense,22.02.2022 - 25.02.2022,,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -7,1,Отгул — один день частично,timeoff_single_day_partial_own_expense,single_day,partial,own_expense,22.02.2022 с 16:00 по 18:00,,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -8,1,Отгул — один день весь день в счёт отпуска,timeoff_single_day_full_day_vacation_account,single_day,full_day,vacation_account,22.02.2022,,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -9,1,Отгул — один день весь день за свой счёт,timeoff_single_day_full_day_own_expense,single_day,full_day,own_expense,22.02.2022,,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -10,2,Отпуск — несколько дней в счёт отпуска,vacation_multi_day_full_day_vacation_account,multi_day,full_day,vacation_account,"22.02.2022, 24.02.2022, 26.02.2022",,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -11,2,Отпуск — несколько дней за свой счёт,vacation_multi_day_full_day_own_expense,multi_day,full_day,own_expense,"22.02.2022, 24.02.2022, 26.02.2022",,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -12,2,Отпуск — диапазон в счёт отпуска,vacation_date_range_full_day_vacation_account,date_range,full_day,vacation_account,22.02.2022 - 25.02.2022,,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -13,2,Отпуск — диапазон за свой счёт,vacation_date_range_full_day_own_expense,date_range,full_day,own_expense,22.02.2022 - 25.02.2022,,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -14,2,Отпуск — один день в счёт отпуска,vacation_single_day_full_day_vacation_account,single_day,full_day,vacation_account,22.02.2022,,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -15,2,Отпуск — один день за свой счёт,vacation_single_day_full_day_own_expense,single_day,full_day,own_expense,22.02.2022,,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -16,3,Больничный — несколько дней официальный,sickleave_multi_day_full_day_official,multi_day,full_day,official,"22.02.2022, 24.02.2022, 26.02.2022",,true,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -17,3,Больничный — несколько дней в счёт отпуска,sickleave_multi_day_full_day_vacation_account,multi_day,full_day,vacation_account,"22.02.2022, 24.02.2022, 26.02.2022",,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -18,3,Больничный — несколько дней за свой счёт,sickleave_multi_day_full_day_own_expense,multi_day,full_day,own_expense,"22.02.2022, 24.02.2022, 26.02.2022",,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -19,3,Больничный — диапазон официальный,sickleave_date_range_full_day_official,date_range,full_day,official,22.02.2022 - 25.02.2022,,true,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -20,3,Больничный — диапазон в счёт отпуска,sickleave_date_range_full_day_vacation_account,date_range,full_day,vacation_account,22.02.2022 - 25.02.2022,,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -21,3,Больничный — диапазон за свой счёт,sickleave_date_range_full_day_own_expense,date_range,full_day,own_expense,22.02.2022 - 25.02.2022,,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -22,3,Больничный — один день официальный,sickleave_single_day_full_day_official,single_day,full_day,official,22.02.2022,,true,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -23,3,Больничный — один день в счёт отпуска,sickleave_single_day_full_day_vacation_account,single_day,full_day,vacation_account,22.02.2022,,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -24,3,Больничный — один день за свой счёт,sickleave_single_day_full_day_own_expense,single_day,full_day,own_expense,22.02.2022,,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -25,4,Внебюджетные расходы Ф1 ТМЦ,non_budget_expenses_f1_tmc,,,,,Опишите расход ТМЦ по филиалу Ф1,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -26,4,Внебюджетные расходы Ф1 Расход,non_budget_expenses_f1_expense,,,,,Опишите расход по филиалу Ф1,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -27,4,Внебюджетные расходы Ф2 ТМЦ,non_budget_expenses_f2_tmc,,,,,Опишите расход ТМЦ по филиалу Ф2,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -28,4,Внебюджетные расходы Ф2 Расход,non_budget_expenses_f2_expense,,,,,Опишите расход по филиалу Ф2,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -29,5,Внебюджетные расходы ПЭТ Лайн Ф1 ТМЦ,non_budget_expenses_pet_line_f1_tmc,,,,,Опишите расход ТМЦ ПЭТ Лайн по филиалу Ф1,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -30,5,Внебюджетные расходы ПЭТ Лайн Ф1 Расход,non_budget_expenses_pet_line_f1_expense,,,,,Опишите расход ПЭТ Лайн по филиалу Ф1,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -31,5,Внебюджетные расходы ПЭТ Лайн Ф2 ТМЦ,non_budget_expenses_pet_line_f2_tmc,,,,,Опишите расход ТМЦ ПЭТ Лайн по филиалу Ф2,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -32,5,Внебюджетные расходы ПЭТ Лайн Ф2 Расход,non_budget_expenses_pet_line_f2_expense,,,,,Опишите расход ПЭТ Лайн по филиалу Ф2,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -33,6,Возврат поставщику Крым,returns_supplier_crimea,,,,,Опишите возврат поставщику (Крым),false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -34,6,Возврат поставщику Краснодар,returns_supplier_krasnodar,,,,,Опишите возврат поставщику (Краснодар),false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -35,6,Продажа другим менеджером Крым,returns_other_manager_crimea,,,,,Опишите продажу другим менеджером (Крым),false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -36,6,Продажа другим менеджером Краснодар,returns_other_manager_krasnodar,,,,,Опишите продажу другим менеджером (Краснодар),false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -37,6,Самостоятельная продажа Крым,returns_self_sale_crimea,,,,,Опишите самостоятельную продажу (Крым),false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -38,6,Самостоятельная продажа Краснодар,returns_self_sale_krasnodar,,,,,Опишите самостоятельную продажу (Краснодар),false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -39,7,Поменять название ОКБ Крым,client_changes_rename_okb_crimea,,,,Опишите изменение названия клиента в ОКБ (Крым),Внести изменения в ОКБ,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -40,7,Поменять название Битрикс Крым,client_changes_rename_bitrix_crimea,,,,Опишите изменение названия клиента в Битрикс (Крым),Внести изменения в Битрикс,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -41,7,Поменять название 1С Крым,client_changes_rename_1c_crimea,,,,Опишите изменение названия клиента в 1С (Крым),Внести изменения в 1С,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -42,7,Поменять название ОКБ Краснодар,client_changes_rename_okb_krasnodar,,,,Опишите изменение названия клиента в ОКБ (Краснодар),Внести изменения в ОКБ,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -43,7,Поменять название Битрикс Краснодар,client_changes_rename_bitrix_krasnodar,,,,Опишите изменение названия клиента в Битрикс (Краснодар),Внести изменения в Битрикс,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -44,7,Поменять название 1С Краснодар,client_changes_rename_1c_krasnodar,,,,Опишите изменение названия клиента в 1С (Краснодар),Внести изменения в 1С,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -45,7,Сменить менеджера ОКБ Крым,client_changes_change_manager_okb_crimea,,,,Опишите смену менеджера в ОКБ (Крым),Внести изменения в ОКБ,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -46,7,Сменить менеджера Битрикс Крым,client_changes_change_manager_bitrix_crimea,,,,Опишите смену менеджера в Битрикс (Крым),Внести изменения в Битрикс,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -47,7,Сменить менеджера 1С Крым,client_changes_change_manager_1c_crimea,,,,Опишите смену менеджера в 1С (Крым),Внести изменения в 1С,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -48,7,Сменить менеджера ОКБ Краснодар,client_changes_change_manager_okb_krasnodar,,,,Опишите смену менеджера в ОКБ (Краснодар),Внести изменения в ОКБ,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -49,7,Сменить менеджера Битрикс Краснодар,client_changes_change_manager_bitrix_krasnodar,,,,Опишите смену менеджера в Битрикс (Краснодар),Внести изменения в Битрикс,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -50,7,Сменить менеджера 1С Краснодар,client_changes_change_manager_1c_krasnodar,,,,Опишите смену менеджера в 1С (Краснодар),Внести изменения в 1С,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -51,7,Внести нового клиента ОКБ Крым,client_changes_new_client_okb_crimea,,,,Опишите данные нового клиента для ОКБ (Крым),Внести нового клиента в ОКБ,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -52,7,Внести нового клиента Битрикс Крым,client_changes_new_client_bitrix_crimea,,,,Опишите данные нового клиента для Битрикс (Крым),Внести нового клиента в Битрикс,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -53,7,Внести нового клиента 1С Крым,client_changes_new_client_1c_crimea,,,,Опишите данные нового клиента для 1С (Крым),Внести нового клиента в 1С,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -54,7,Внести нового клиента ОКБ Краснодар,client_changes_new_client_okb_krasnodar,,,,Опишите данные нового клиента для ОКБ (Краснодар),Внести нового клиента в ОКБ,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -55,7,Внести нового клиента Битрикс Краснодар,client_changes_new_client_bitrix_krasnodar,,,,Опишите данные нового клиента для Битрикс (Краснодар),Внести нового клиента в Битрикс,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -56,7,Внести нового клиента 1С Краснодар,client_changes_new_client_1c_krasnodar,,,,Опишите данные нового клиента для 1С (Краснодар),Внести нового клиента в 1С,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -57,8,Заказ товаров на месяц,goods_order_monthly,,,,Опишите заказ на месяц,Обработать заказ товаров,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -58,8,Заказ товаров дополнительный,goods_order_additional,,,,Опишите дополнительный заказ,Обработать заказ товаров,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -59,9,Отгрузки на СОХ реальная,shipments_soh_real,,,,Опишите реальную отгрузку на СОХ,Выполнить отгрузку,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -60,9,Отгрузки на СОХ для лимита,shipments_soh_limit,,,,Опишите отгрузку для лимита на СОХ,Выполнить отгрузку,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -61,10,Паспорт сделки Краснодар,transaction_passport_krasnodar,,,,,Опишите паспорт сделки (Краснодар),false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -62,10,Паспорт сделки Крым,transaction_passport_crimea,,,,,Опишите паспорт сделки (Крым),false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -63,10,Паспорт сделки Беларусь,transaction_passport_belarus,,,,,Опишите паспорт сделки (Беларусь),false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -64,11,Ставки логистика разово,rates_logistics_once,,,,,Опишите ставки логистики на разовую поставку,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -65,11,Ставки логистика надолго,rates_logistics_long_term,,,,,Опишите ставки логистики на долгосрочный период,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -66,12,Поступления Ф1,receipts_f1,,,,,Опишите поступление по филиалу Ф1,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -67,12,Поступления Ф2,receipts_f2,,,,,Опишите поступление по филиалу Ф2,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -68,13,Доставка клиентам/на склад,delivery_clients,,,,,Опишите детали доставки,false,true,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -69,14,В. Отгрузки,v_shipments,,,,,Опишите детали внутренних отгрузок,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -70,15,Менеджерские расходы,manager_expenses,,,,,Опишите менеджерские расходы,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -71,16,Отгрузки,shipments,,,,,Опишите детали отгрузки,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -72,17,Нестандартные условия договора поставки,nonstandard_contract,,,,,Опишите нестандартные условия,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -73,18,Вакансии,vacancies,,,,,Опишите вакансию,false,true,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -74,19,Ставки доставки АП,delivery_rates_ap,,,,,Опишите ставки доставки,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -75,20,Утверждение фрилансеров,freelancers_approval,,,,,Опишите данные фрилансера,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -76,21,Выход в нерабочий день,non_working_day,,,,,Опишите причину выхода в нерабочий день,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -77,22,Предложения и пожелания,suggestions,,,,,Опишите ваше предложение или пожелание,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -78,23,Долгосрочные условия ОТК,otk_conditions,,,,Опишите долгосрочные условия ОТК,Обработать заявку по ОТК,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -79,24,Остаток в кассах,cash_balance,,,,,Опишите остаток в кассах,false,true,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -80,25,Продажи по клиенту,client_sales,,,,,Укажите клиента для проверки продаж,false,true,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -81,26,Проведенные расходы по менеджеру,manager_expenses_report,,,,,Укажите менеджера для проверки расходов,false,true,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -82,27,Заведение новых клиентов,new_clients,,,,,Опишите данные нового клиента,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 -83,28,Утверждение оплат безнал,payments_cashless,,,,,Опишите детали безналичной оплаты,false,false,true,2026-04-23 10:00:00,2026-04-23 10:00:00 \ No newline at end of file +id,category_id,name,code,duration_type,time_type,payment_type,template,allows_file,is_active,created_at,updated_at,allow_approver_selection,first_approver_role_code,allow_observer_selection,approval_mode,require_approver_comment,requires_file,require_observer_selection,instructions +70,15,Менеджерские расходы: Крым,manager_expenses_crimea,,,,Оплата платной дороги Краснодар-Темрюк-Краснодар в сумме 1420 руб. (клиент РУСМолоко) (расход Макаренко),false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +590,15,Менеджерские расходы: Краснодар,manager_expenses_krasnodar,,,,,false,true,2026-06-03 08:55:52.439479,2026-06-03 08:55:52.439479,false,,false,sequential,false,false,false, +49,7,Сменить менеджера Битрикс Краснодар,client_changes_change_manager_bitrix_krasnodar,,,,Опишите смену менеджера в Битрикс (Краснодар),false,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +586,9,Отгрузка на СОХ — Крым (реальная),shipments_soh_crimea_real,,,,Опишите отгрузку,false,true,2026-06-02 07:10:13.844873,2026-06-02 07:10:13.844873,false,,false,sequential,true,false,false, +4,1,Отгул — диапазон частично,timeoff_date_range_partial_own_expense,date_range,partial,own_expense,22.02.2022 - 25.02.2022 с 16:00 по 18:00,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +65,11,Ставки Логистика: Надолго,rates_logistics_long_term,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +592,17,Нестандартные условия поставки: Беларусь,nonstandard_contract_belarus,,,,,true,true,2026-06-03 09:20:00.662572,2026-06-03 09:20:00.662572,false,,false,sequential,true,false,false, +591,17,Нестандартные условия поставки: Краснодар,nonstandard_contract_krasnodar,,,,,true,true,2026-06-03 09:20:00.662572,2026-06-03 09:20:00.662572,false,,false,sequential,true,false,false, +594,23,ОТК: Краснодар,otk_conditions_krasnodar,,,,,false,true,2026-06-03 09:29:10.377976,2026-06-03 09:29:10.377976,false,,false,sequential,false,false,false, +595,23,ОТК: Беларусь,otk_conditions_belarus,,,,,false,true,2026-06-03 09:29:10.377976,2026-06-03 09:29:10.377976,false,,false,sequential,false,false,false, +5,1,Отгул — диапазон весь день в счёт отпуска,timeoff_date_range_full_day_vacation_account,date_range,full_day,vacation_account,22.02.2022 - 25.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +6,1,Отгул — диапазон весь день за свой счёт,timeoff_date_range_full_day_own_expense,date_range,full_day,own_expense,22.02.2022 - 25.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +16,3,Больничный — несколько дней официальный,sickleave_multi_day_full_day_official,multi_day,full_day,official,"22.02.2022, 24.02.2022, 26.02.2022",true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +17,3,Больничный — несколько дней в счёт отпуска,sickleave_multi_day_full_day_vacation_account,multi_day,full_day,vacation_account,"22.02.2022, 24.02.2022, 26.02.2022",false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +589,9,Отгрузка на СОХ — Краснодар (лимит),shipments_soh_krasnodar_limit,,,,Опишите отгрузку,false,true,2026-06-02 07:10:13.915061,2026-06-02 07:10:13.915061,false,,false,sequential,true,false,false, +587,9,Отгрузка на СОХ — Крым (лимит),shipments_soh_crimea_limit,,,,Опишите отгрузку,false,true,2026-06-02 07:10:13.868383,2026-06-02 07:10:13.868383,false,,false,sequential,true,false,false, +21,3,Больничный — диапазон за свой счёт,sickleave_date_range_full_day_own_expense,date_range,full_day,own_expense,22.02.2022 - 25.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +24,3,Больничный — один день за свой счёт,sickleave_single_day_full_day_own_expense,single_day,full_day,own_expense,22.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +588,9,Отгрузка на СОХ — Краснодар (реальная),shipments_soh_krasnodar_real,,,,Опишите отгрузку,false,true,2026-06-02 07:10:13.892797,2026-06-02 07:10:13.892797,false,,false,sequential,true,false,false, +18,3,Больничный — несколько дней за свой счёт,sickleave_multi_day_full_day_own_expense,multi_day,full_day,own_expense,"22.02.2022, 24.02.2022, 26.02.2022",false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +59,9,Отгрузки на СОХ реальная,shipments_soh_real,,,,Опишите реальную отгрузку на СОХ,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +43,7,Поменять название Битрикс Краснодар,client_changes_rename_bitrix_krasnodar,,,,Опишите изменение названия клиента в Битрикс (Краснодар),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +27,4,Внебюджетные расходы: Ф2 ТМЦ,non_budget_expenses_f2_tmc,,,,Прошу согласовать оплату за зарядку для телефона (руководителю отдела логистики) в сумме 293 руб.,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +60,9,Отгрузки на СОХ для лимита,shipments_soh_limit,,,,Опишите отгрузку для лимита на СОХ,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +19,3,Больничный — диапазон официальный,sickleave_date_range_full_day_official,date_range,full_day,official,22.02.2022 - 25.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +22,3,Больничный — один день официальный,sickleave_single_day_full_day_official,single_day,full_day,official,22.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +82,27,Заведение новых клиентов,new_clients,,,,,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +83,28,Утверждение оплат безнал,payments_cashless,,,,,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +1,1,Отгул — несколько дней частично,timeoff_multi_day_partial_own_expense,multi_day,partial,own_expense,"22.02.2022 с 10:00 по 14:00, 24.02.2022 с 09:00 по 12:00",false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +2,1,Отгул — несколько дней весь день в счёт отпуска,timeoff_multi_day_full_day_vacation_account,multi_day,full_day,vacation_account,"22.02.2022, 24.02.2022, 26.02.2022",false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +3,1,Отгул — несколько дней весь день за свой счёт,timeoff_multi_day_full_day_own_expense,multi_day,full_day,own_expense,"22.02.2022, 24.02.2022, 26.02.2022",false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +7,1,Отгул — один день частично,timeoff_single_day_partial_own_expense,single_day,partial,own_expense,22.02.2022 с 16:00 по 18:00,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +8,1,Отгул — один день весь день в счёт отпуска,timeoff_single_day_full_day_vacation_account,single_day,full_day,vacation_account,22.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +9,1,Отгул — один день весь день за свой счёт,timeoff_single_day_full_day_own_expense,single_day,full_day,own_expense,22.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +10,2,Отпуск — несколько дней в счёт отпуска,vacation_multi_day_full_day_vacation_account,multi_day,full_day,vacation_account,"22.02.2022, 24.02.2022, 26.02.2022",false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +11,2,Отпуск — несколько дней за свой счёт,vacation_multi_day_full_day_own_expense,multi_day,full_day,own_expense,"22.02.2022, 24.02.2022, 26.02.2022",false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +12,2,Отпуск — диапазон в счёт отпуска,vacation_date_range_full_day_vacation_account,date_range,full_day,vacation_account,22.02.2022 - 25.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +13,2,Отпуск — диапазон за свой счёт,vacation_date_range_full_day_own_expense,date_range,full_day,own_expense,22.02.2022 - 25.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +14,2,Отпуск — один день в счёт отпуска,vacation_single_day_full_day_vacation_account,single_day,full_day,vacation_account,22.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +15,2,Отпуск — один день за свой счёт,vacation_single_day_full_day_own_expense,single_day,full_day,own_expense,22.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +20,3,Больничный — диапазон в счёт отпуска,sickleave_date_range_full_day_vacation_account,date_range,full_day,vacation_account,22.02.2022 - 25.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +23,3,Больничный — один день в счёт отпуска,sickleave_single_day_full_day_vacation_account,single_day,full_day,vacation_account,22.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +61,10,ПС: Краснодар,transaction_passport_krasnodar,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,true,false, +580,8,Заказ на месяц — Крым,goods_order_monthly_crimea,,,,"Опишите Скилур заказ: + 22 гр.38 мм бесцветная (10176) ЕПМ - 5кор. + ф1, на склад Гвардейское, 2я декада.",true,true,2026-05-27 07:32:42.878447,2026-05-27 07:32:42.878447,false,,false,sequential,true,true,false, +58,8,Заказ товаров дополнительный,goods_order_additional,,,,Опишите дополнительный заказ,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,true,false, +582,8,Дополнительный заказ — Крым,goods_order_additional_crimea,,,,"Опишите Скилур заказ: + 22 гр.38 мм бесцветная (10176) ЕПМ - 5кор. + ф1, на склад Гвардейское, 2я декада.",true,true,2026-05-27 07:32:42.959177,2026-05-27 07:32:42.959177,false,,false,sequential,true,true,false, +57,8,Заказ товаров на месяц,goods_order_monthly,,,,Опишите заказ на месяц,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,true,false, +597,4,Внебюджетные расходы: Ф1 ТМЦ (без ПП),non_budget_expenses_f1_tmc_pp_no,,,,,false,true,2026-06-10 09:06:59.648658,2026-06-10 09:06:59.648658,false,,false,sequential,false,false,false, +599,4,Внебюджетные расходы: Ф1 Расход (без ПП),non_budget_expenses_f1_expense_pp_no,,,,,false,true,2026-06-10 09:06:59.684144,2026-06-10 09:06:59.684144,false,,false,sequential,false,false,false, +42,7,Поменять название ОКБ Краснодар,client_changes_rename_okb_krasnodar,,,,Опишите изменение названия клиента в ОКБ (Краснодар),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +602,28,Оплата безнал — Разное (нужна ПП),payments_cashless_misc_pp_yes,,,,,true,true,2026-06-10 09:06:59.730960,2026-06-10 09:06:59.730960,false,,false,sequential,false,true,false, +603,28,Оплата безнал — Разное (без ПП),payments_cashless_misc_pp_no,,,,,true,true,2026-06-10 09:06:59.746484,2026-06-10 09:06:59.746484,false,,false,sequential,false,true,false, +600,28,Оплата безнал — Товар (нужна ПП),payments_cashless_goods_pp_yes,,,,,true,true,2026-06-10 09:06:59.699401,2026-06-10 09:06:59.699401,false,,false,sequential,false,true,false, +601,28,Оплата безнал — Товар (без ПП),payments_cashless_goods_pp_no,,,,,true,true,2026-06-10 09:06:59.716456,2026-06-10 09:06:59.716456,false,,false,sequential,false,true,false, +598,4,Внебюджетные расходы: Ф1 Расход (нужна ПП),non_budget_expenses_f1_expense_pp_yes,,,,,true,true,2026-06-10 09:06:59.666345,2026-06-10 09:06:59.666345,false,,false,sequential,false,true,false, +596,4,Внебюджетные расходы: Ф1 ТМЦ (нужна ПП),non_budget_expenses_f1_tmc_pp_yes,,,,,true,true,2026-06-10 09:06:59.628993,2026-06-10 09:06:59.628993,false,,false,sequential,false,true,false, +37,6,Самостоятельная продажа Крым,returns_self_sale_crimea,,,,"ТД Крымэколайф +40,5 гр.1881 бесцветная (7808) ПФ - 52 короба +Реализация товаров и услуг ЧП000003123 от 4.08.25 +Ф1 + +Причина: для сокращения долга клиента + +Действия: продам ООО Нива",false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +34,6,Возврат поставщику Краснодар,returns_supplier_krasnodar,,,,,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +38,6,Самостоятельная продажа Краснодар,returns_self_sale_krasnodar,,,,,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +33,6,Возврат поставщику Крым,returns_supplier_crimea,,,,"Бишули +28 гр.1881 бесцветная (9504) ПФ - 2 короба +Реализация товаров и услуг ЧП000001326 от 20.04.2026 8:00:01 +Ф1 + +Причина: Короб приехал с завода и сильно порвался в дороге, клиент не может на свою продукцию использовать его",false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +62,10,ПС: Крым,transaction_passport_crimea,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,true,false, +73,18,Вакансии,vacancies,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,supervisor,false,sequential,false,false,false, +80,25,Продажи по клиенту,client_sales,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,manager,false,sequential,false,true,false, +78,23,ОТК: Крым,otk_conditions_crimea,,,,Опишите долгосрочные условия ОТК,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +605,7,Внести нового клиента - Краснодар,client_changes_new_client_krasnodar,,,,,false,true,2026-06-11 04:33:53.266045,2026-06-11 04:33:53.266045,false,,false,sequential,false,false,false, +607,7,Внести нового клиента - Крым,client_changes_new_client_crimea,,,,,false,true,2026-06-11 04:33:53.266045,2026-06-11 04:33:53.266045,false,,false,sequential,false,false,false, +609,7,Поменять название - Краснодар,client_changes_rename_krasnodar,,,,,false,true,2026-06-11 04:33:53.266045,2026-06-11 04:33:53.266045,false,,false,sequential,false,false,false, +611,7,Поменять название - Крым,client_changes_rename_crimea,,,,,false,true,2026-06-11 04:33:53.266045,2026-06-11 04:33:53.266045,false,,false,sequential,false,false,false, +613,7,Сменить менеджера - Краснодар,client_changes_change_manager_krasnodar,,,,,false,true,2026-06-11 04:33:53.266045,2026-06-11 04:33:53.266045,false,,false,sequential,false,false,false, +615,7,Сменить менеджера - Крым,client_changes_change_manager_crimea,,,,,false,true,2026-06-11 04:33:53.266045,2026-06-11 04:33:53.266045,false,,false,sequential,false,false,false, +53,7,Внести нового клиента 1С Крым,client_changes_new_client_1c_crimea,,,,Опишите данные нового клиента для 1С (Крым),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +50,7,Сменить менеджера 1С Краснодар,client_changes_change_manager_1c_krasnodar,,,,Опишите смену менеджера в 1С (Краснодар),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +72,17,Нестандартные условия поставки: Крым,nonstandard_contract_crimea,,,,Прошу согласовать отсрочку 21 день для клиента ООО Роса (другое юрлицо ООО Аквариум) (менеджер Петров),true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,true,false,false, +36,6,Продажа другим менеджером Краснодар,returns_other_manager_krasnodar,,,,,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,manager,false,sequential,false,false,false, +64,11,Ставки Логистика: Разово,rates_logistics_once,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +67,12,Приходные документы Ф2,receipts_f2,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,true,true,false, +66,12,Приходные документы Ф1,receipts_f1,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,true,true,false, +51,7,Внести нового клиента ОКБ Крым,client_changes_new_client_okb_crimea,,,,Опишите данные нового клиента для ОКБ (Крым),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +54,7,Внести нового клиента ОКБ Краснодар,client_changes_new_client_okb_krasnodar,,,,Опишите данные нового клиента для ОКБ (Краснодар),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +47,7,Сменить менеджера 1С Крым,client_changes_change_manager_1c_crimea,,,,Опишите смену менеджера в 1С (Крым),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +41,7,Поменять название 1С Крым,client_changes_rename_1c_crimea,,,,Опишите изменение названия клиента в 1С (Крым),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +29,5,ПЭТ Лайн Ф1 ТМЦ,non_budget_expenses_pet_line_f1_tmc,,,,,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +31,5,ПЭТ Лайн Ф2 ТМЦ,non_budget_expenses_pet_line_f2_tmc,,,,,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +26,4,Внебюджетные расходы: Ф1 Расход,non_budget_expenses_f1_expense,,,,"Прошу оплатить счет ИП Гулякина на сумму 3180,00 руб (без НДС) за продление 1С-Отчетность на 1 год",true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +28,4,Внебюджетные расходы: Ф2 Расход,non_budget_expenses_f2_expense,,,,Прошу согласовать 1000 руб на покупку контактов резюме грузчиков на платформе Авито,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +75,20,Утверждение фрилансеров,freelancers_approval,,,,Одного помощника на выгрузку полной фуры с крышкой ручкой с КТ на 23.04.2026 на весь день,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +35,6,Продажа другим менеджером Крым,returns_other_manager_crimea,,,,"Бишули +61 гр.38 мм бесцветная (3888) ЕП - 11 коробов +Реализация товаров и услуг ЧП000000584 от 05.03.2026 8:00:01 +Ф1 + +Причина: Часть заказа отвалилась, будут переходить на эту позицию не раньше, чем через 3 мес + +Продаст Чекальский на Бойко",false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,manager,false,sequential,false,false,false, +77,22,Предложения и пожелания,suggestions,,,,,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +63,10,ПС: Беларусь,transaction_passport_belarus,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,true,false, +74,19,Ставки доставки АП,delivery_rates_ap,,,,Прошу согласовать доставку 14 кор преформы клиенту Олег-Выдув-Сочи за 34 000 руб.,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +71,16,Отгрузки,shipments,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,true,sequential,false,true,true,"Если не входит в рамки согласованного лимита, добавь руководителя соответствующего филиала к согласованию через кнопку 'Добавить согласующего'" +584,28,Оплата безнал — Товар,payments_cashless_goods,,,,Опишите оплату,false,true,2026-06-02 06:14:34.876867,2026-06-02 06:14:34.876867,false,,false,sequential,false,false,false, +585,28,Оплата безнал — Разное,payments_cashless_misc,,,,Опишите оплату,false,true,2026-06-02 06:14:34.926542,2026-06-02 06:14:34.926542,false,,false,sequential,false,false,false, +583,8,Дополнительный заказ — Краснодар,goods_order_additional_krasnodar,,,,"Опишите Скилур заказ: + 22 гр.38 мм бесцветная (10176) ЕПМ - 5кор. + ф1, на склад Гвардейское, 2я декада.",true,true,2026-05-27 07:32:42.987951,2026-05-27 07:32:42.987951,false,,false,sequential,true,true,false, +581,8,Заказ на месяц — Краснодар,goods_order_monthly_krasnodar,,,,"Скилур заказ: +22 гр.38 мм бесцветная (10176) ЕПМ - 5кор. +ф1, на склад Гвардейское, 2я декада.",true,true,2026-05-27 07:32:42.929341,2026-05-27 07:32:42.929341,false,,false,sequential,true,true,false, +79,24,Остаток в кассах,cash_balance,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,supervisor,false,sequential,false,false,false, +55,7,Внести нового клиента Битрикс Краснодар,client_changes_new_client_bitrix_krasnodar,,,,Опишите данные нового клиента для Битрикс (Краснодар),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +25,4,Внебюджетные расходы: Ф1 ТМЦ,non_budget_expenses_f1_tmc,,,,Прошу согласовать и оплатить Счет от ООО Интернет Решения (Озон) за ноутбук и мышь для закупщика в сумме 31 335 руб. С НДС,true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +30,5,ПЭТ Лайн Ф1 Расход,non_budget_expenses_pet_line_f1_expense,,,,,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +76,21,Выход в нерабочий день,non_working_day,,,,Прошу вывести склад для учета c 25.04 по 26.04,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +68,13,Доставка клиентам/на склад,delivery_clients,,,,"Иванов Иван Иванович +Тел 89781234567 +Паспорт 1234 567890 +ДАФ н862нн46 п/п АА8473|46 + +61 бц с ад - 52 кор +ЧП000001676 + +ЕПР-СтройКрым",true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,manager,false,sequential,false,false,false, +32,5,ПЭТ Лайн Ф2 Расход,non_budget_expenses_pet_line_f2_expense,,,,,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +40,7,Поменять название Битрикс Крым,client_changes_rename_bitrix_crimea,,,,Опишите изменение названия клиента в Битрикс (Крым),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +44,7,Поменять название 1С Краснодар,client_changes_rename_1c_krasnodar,,,,Опишите изменение названия клиента в 1С (Краснодар),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +46,7,Сменить менеджера Битрикс Крым,client_changes_change_manager_bitrix_crimea,,,,Опишите смену менеджера в Битрикс (Крым),false,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +56,7,Внести нового клиента 1С Краснодар,client_changes_new_client_1c_krasnodar,,,,Опишите данные нового клиента для 1С (Краснодар),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +52,7,Внести нового клиента Битрикс Крым,client_changes_new_client_bitrix_crimea,,,,Опишите данные нового клиента для Битрикс (Крым),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +45,7,Сменить менеджера ОКБ Крым,client_changes_change_manager_okb_crimea,,,,Опишите смену менеджера в ОКБ (Крым),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +48,7,Сменить менеджера ОКБ Краснодар,client_changes_change_manager_okb_krasnodar,,,,Опишите смену менеджера в ОКБ (Краснодар),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +69,14,В. Отгрузки,v_shipments,,,,ООО Нива на 370 тыс. руб. под 19%,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, +81,26,Проведенные расходы по менеджеру,manager_expenses_report,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,manager,false,sequential,false,false,false, +39,7,Поменять название ОКБ Крым,client_changes_rename_okb_crimea,,,,Опишите изменение названия клиента в ОКБ (Крым),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false, diff --git a/core/db/db_migration/tables.go b/core/db/db_migration/tables.go index 70793f7..5dcea35 100644 --- a/core/db/db_migration/tables.go +++ b/core/db/db_migration/tables.go @@ -37,6 +37,7 @@ func (m *MigrationFunctions) migrateTables() error { tablesmigration.SuggestionMessagesTableMigrate, tablesmigration.ApprovalAdditionalObserverTableMigrate, tablesmigration.ApprovalTopicExecutorsTableMigrate, + tablesmigration.AdminsTableMigrate, } for _, migrate := range migrations { diff --git a/core/db/db_migration/tables/admins.go b/core/db/db_migration/tables/admins.go new file mode 100644 index 0000000..8a951b4 --- /dev/null +++ b/core/db/db_migration/tables/admins.go @@ -0,0 +1,43 @@ +package tablesmigration + +import ( + dbcoretablenames "bitrix_balancer_api/core/db/table_names" + "bitrix_balancer_api/core/typescore" + "gorm.io/gorm" + "time" +) + +// LocalAdminProvider - локальная структура для миграции +type LocalAdminProvider typescore.Admin + +func (LocalAdminProvider) TableName() string { + return dbcoretablenames.TableNameAdmin.ToString() +} + +// AdminsTableMigrate - миграция таблицы Admins +func AdminsTableMigrate(db *gorm.DB) error { + hasTable := db.Migrator().HasTable(&LocalAdminProvider{}) + + // Выполняем автосоздание таблицы + err := db.AutoMigrate(&LocalAdminProvider{}) + if err != nil { + return err + } + + if !hasTable { + time.Sleep(5 * time.Second) // Добавляем задержку + + // Add comments to table and columns + db.Exec(` + COMMENT ON TABLE admins IS 'Таблица для хранения данных о администраторах'; + COMMENT ON COLUMN admins.id IS 'Уникальный идентификатор администратора'; + COMMENT ON COLUMN admins.login IS 'Логин администратора'; + COMMENT ON COLUMN admins.password_hash IS 'Хэшированный пароль администратора'; + COMMENT ON COLUMN admins.created_at IS 'Дата создания записи'; + COMMENT ON COLUMN admins.last_login IS 'Дата последнего входа'; + COMMENT ON COLUMN admins.last_ip_login IS 'Последний IP-адрес авторизации'; + COMMENT ON COLUMN admins.is_blocked IS 'Заблокирован ли администратор'; + `) + } + return nil +} diff --git a/core/db/methods/admin.go b/core/db/methods/admin.go new file mode 100644 index 0000000..556d036 --- /dev/null +++ b/core/db/methods/admin.go @@ -0,0 +1,249 @@ +package dbcore + +import ( + dbcoretablenames "bitrix_balancer_api/core/db/table_names" + "bitrix_balancer_api/core/typescore" + dbutils "bitrix_balancer_api/core/utilscore/db" + "bitrix_balancer_api/core/variables" + "context" + "errors" + "fmt" + "strings" + + "github.com/Masterminds/squirrel" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + "github.com/sirupsen/logrus" +) + +type AdminDB struct { + pool *pgxpool.Pool +} + +func NewAdminDB(pool *pgxpool.Pool) *AdminDB { + + return &AdminDB{pool: pool} +} + +type AdminDBI interface { + GetAdminsListDB(options ...typescore.ListDbOptions) ([]*typescore.Admin, uint64, error) + CreateAdminDB(tx pgx.Tx, adminObj *typescore.Admin, returnObj ...bool) (*typescore.Admin, pgx.Tx, error) + UpdateAdminDB(tx pgx.Tx, paramsUpdate *typescore.Admin, returnObj ...bool) (*typescore.Admin, pgx.Tx, error) + DeleteAdminDB(params *typescore.Admin) error + + CheckAdminAvailabilityDB(email *string) (bool, error) +} + +func (u *AdminDB) GetAdminsListDB(opts ...typescore.ListDbOptions) ([]*typescore.Admin, uint64, error) { + ctx, cancel := context.WithTimeout(context.Background(), variables.ContextTimeoutBase) + defer cancel() + + fields := dbutils.GetStructFieldsDB(&typescore.Admin{}, dbcoretablenames.TableNameAdmin.ToString()) + // Добавляем поле total_count + selectFields := append(fields, "COUNT(*) OVER() AS total_count") + + // Используем обобщённую функцию для обработки опций + options, filter, err := dbutils.GetOptionsDB[typescore.Admin](opts...) + if err != nil { + return nil, 0, errors.New(fmt.Sprintf("%s: failed to parse options for %s: %v", "error_get", dbcoretablenames.TableNameAdmin.ToString(), err)) + } + + query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameAdmin.ToString(), selectFields) + query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit) + query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameAdmin.ToString()) + query = query.OrderBy("created_at DESC") + + sql, args, err := query.ToSql() + if err != nil { + return nil, 0, errors.New(fmt.Sprintf("%s: failed to create SELECT %s SQL: %v", "error_get", dbcoretablenames.TableNameAdmin.ToString(), err)) + } + + rows, err := u.pool.Query(ctx, sql, args...) + if err != nil { + return nil, 0, errors.New(fmt.Sprintf("%s: failed to execute query on %s SQL: %v", "error_get", dbcoretablenames.TableNameAdmin.ToString(), err)) + } + defer rows.Close() + + var admins []*typescore.Admin + var totalCount uint64 + for rows.Next() { + admin := &typescore.Admin{} + if err := dbutils.ScanRowsToStructRows(rows, admin, &totalCount); err != nil { + logrus.Errorf("🔴 error: %s: %+v", "GetAdminsListDB-ScanRowsToStructRows", err) + continue + } + admins = append(admins, admin) + } + + return admins, totalCount, nil +} + +// CreateAdminDB Создает нового пользователя +func (u *AdminDB) CreateAdminDB(tx pgx.Tx, adminObj *typescore.Admin, returnObj ...bool) (*typescore.Admin, pgx.Tx, error) { + if adminObj == nil { + return nil, nil, errors.New(fmt.Sprintf("object_is_nil: failed to create %s INSERT SQL. error: %s", dbcoretablenames.TableNameAdmin.ToString(), "adminObj is nil")) + } + + ctx, cancel := context.WithTimeout(context.Background(), variables.ContextTimeoutBase) + defer cancel() + + err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { + query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Insert(dbcoretablenames.TableNameAdmin.ToString()) + + sqlV, args, err := dbutils.GenerateInsertRequest(query, adminObj) + if err != nil { + return err + } + + _, err = tx.Exec(ctx, *sqlV, args...) + if err != nil { + logrus.Errorf("🔴 error: %s: %+v", "CreateAdminDB-Exec", err) + return err + } + + return nil + }) + + if err != nil { + return nil, tx, err + } + + returnObjBool := false + if len(returnObj) > 0 { + returnObjBool = returnObj[0] + } + if returnObjBool { + admin, _, err := u.GetAdminsListDB(typescore.ListDbOptions{Filtering: adminObj}) + if err != nil { + return nil, tx, err + } + if len(admin) > 0 { + return admin[0], tx, nil + } + } + + return nil, tx, nil +} + +func (u *AdminDB) UpdateAdminDB(tx pgx.Tx, paramsUpdate *typescore.Admin, returnObj ...bool) (*typescore.Admin, pgx.Tx, error) { + if paramsUpdate.ID == nil && paramsUpdate.Login == nil { + logrus.Errorf("❌ UpdateAdminDB error: %s", errors.New("id and email is nil")) + return nil, nil, errors.New(fmt.Sprintf("error_update: failed to create UPDATE %s SQL: %v", dbcoretablenames.TableNameAdmin.ToString(), errors.New("id and email is nil"))) + } + + ctx, cancel := context.WithTimeout(context.Background(), variables.ContextTimeoutBase) + defer cancel() + + err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { + query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameAdmin.ToString()) + + // Используем функцию для добавления ненулевых полей в запрос + query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate) + + // Добавляем условие WHERE + if paramsUpdate.ID != nil { + query = query.Where(squirrel.Eq{"id": paramsUpdate.ID}) + } + if paramsUpdate.Login != nil { + query = query.Where(squirrel.Eq{"login": paramsUpdate.Login}) + } + + // Генерируем SQL и аргументы + sql, args, err := query.ToSql() + if err != nil { + logrus.Errorf("🔴 error: %s: %+v", "UpdateAdminDB-ToSql", err) + return err + } + + _, err = tx.Exec(ctx, sql, args...) + if err != nil { + logrus.Errorf("🔴 error: %s: %+v", "UpdateAdminDB-Exec", err) + if strings.Contains(err.Error(), "violates foreign key constraint") { + return err + } + return err + } + + return nil + }) + + if err != nil { + return nil, tx, err + } + + returnObjBool := false + if len(returnObj) > 0 { + returnObjBool = returnObj[0] + } + + if returnObjBool { + options := typescore.ListDbOptions{Filtering: &typescore.Admin{ID: paramsUpdate.ID}} + getInfoUp, _, errW := u.GetAdminsListDB(options) + if errW != nil { + logrus.Errorf("🔴 error: %s: %+v", "UpdateAdminDB-GetAdminsListDB", errW) + return nil, nil, errW + } + if len(getInfoUp) > 0 { + return getInfoUp[0], tx, nil + } + } + + return nil, tx, nil +} + +func (u *AdminDB) DeleteAdminDB(params *typescore.Admin) error { + if params != nil && params.Login != nil { + ctx, cancel := context.WithTimeout(context.Background(), variables.ContextTimeoutBase) + defer cancel() + + query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Delete(dbcoretablenames.TableNameAdmin.ToString()). + Where(squirrel.Eq{"email": *params.Login}). + ToSql() + + if err != nil { + return errors.New(fmt.Sprintf("error_delete: failed to create DELETE %s SQL: %v", dbcoretablenames.TableNameAdmin.ToString(), err)) + } + + rows, err := u.pool.Query(ctx, query, args...) + if err != nil { + return errors.New(fmt.Sprintf("error_delete: failed to create DELETE %s SQL: %v", dbcoretablenames.TableNameAdmin.ToString(), err)) + } + defer rows.Close() + + return nil + } else { + return errors.New(fmt.Sprintf("error_delete: failed to create DELETE %s SQL: %v", dbcoretablenames.TableNameAdmin.ToString(), errors.New("admin obj is nil"))) + } +} + +func (u *AdminDB) CheckAdminAvailabilityDB(email *string) (bool, error) { + ctx, cancel := context.WithTimeout(context.Background(), variables.ContextTimeoutBase) + defer cancel() + + if email == nil { + return false, errors.New("error_check_admin_availability: email is nil") + } + + query := squirrel.StatementBuilder. + PlaceholderFormat(squirrel.Dollar). + Select("EXISTS(SELECT 1)"). + From(dbcoretablenames.TableNameAdmin.ToString()). + Where(squirrel.Eq{"email": *email}). + Where(squirrel.Eq{"is_blocked": false}) + + sql, args, err := query.ToSql() + if err != nil { + logrus.Errorln("🔴 error: CheckAdminAvailabilityDB-ToSql:", email, err) + return false, errors.New(fmt.Sprintf("error_check_admin_availability: %v", err)) + } + + var exists bool + err = u.pool.QueryRow(ctx, sql, args...).Scan(&exists) + if err != nil { + logrus.Errorln("🔴 error: CheckAdminAvailabilityDB-QueryRow", email, err) + return false, errors.New(fmt.Sprintf("error_check_admin_availability: %v", err)) + } + + return exists, nil +} diff --git a/core/db/methods/role.go b/core/db/methods/role.go index 2c29360..6332fdd 100644 --- a/core/db/methods/role.go +++ b/core/db/methods/role.go @@ -28,6 +28,7 @@ type RoleDBI interface { CreateRoleDB(ctx context.Context, tx pgx.Tx, RoleObj *typescore.Role, returnObj ...bool) (*typescore.Role, pgx.Tx, error) UpdateRoleDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.Role, returnObj ...bool) (*typescore.Role, pgx.Tx, error) DeleteRoleDB(ctx context.Context, params *typescore.Role) error + GetRoleByIDDB(ctx context.Context, id uint64) (*typescore.Role, error) } func (u *RoleDB) GetRolesListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.Role, uint64, error) { @@ -179,3 +180,13 @@ func (u *RoleDB) DeleteRoleDB(ctx context.Context, params *typescore.Role) error return errors.New("role obj is nil") } } + +func (u *RoleDB) GetRoleByIDDB(ctx context.Context, id uint64) (*typescore.Role, error) { + roles, _, err := u.GetRolesListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.Role{ID: &id}, + }) + if err != nil || len(roles) == 0 { + return nil, err + } + return roles[0], nil +} diff --git a/core/db/table_names/table_names.go b/core/db/table_names/table_names.go index b7184e8..42b6f4e 100644 --- a/core/db/table_names/table_names.go +++ b/core/db/table_names/table_names.go @@ -22,6 +22,7 @@ const ( TableNameSuggestions TableName = "suggestions" TableNameSuggestionMessages TableName = "suggestion_messages" TableNameApprovalTopicExecutor TableName = "approval_topic_executor" + TableNameAdmin TableName = "admin" ) func (t TableName) ToString() string { diff --git a/core/typescore/admin.go b/core/typescore/admin.go new file mode 100644 index 0000000..c4486bb --- /dev/null +++ b/core/typescore/admin.go @@ -0,0 +1,21 @@ +package typescore + +import ( + "time" +) + +// Admin - структура для хранения данных о администраторах. +type Admin struct { + ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"` // Автоматически заполняемое уникальное поле для большого числа записей + Login *string `gorm:"type:text;not null;unique;column:login" json:"login" db:"login" mapstructure:"login"` // Логин администратора + PasswordHash *string `gorm:"type:text;not null;column:password_hash" json:"-" db:"password_hash" mapstructure:"password_hash"` // Пароль администратора + CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"` // Дата создания записи + LastLogin *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:last_login" json:"last_login" db:"last_login"` // Дата входа + LastIPLogin *string `gorm:"type:text;column:last_ip_login" json:"last_ip_login" db:"last_ip_login" mapstructure:"last_ip_login"` // Последний IP входа + IsBlocked *bool `gorm:"type:boolean;not null;index;default:false;column:is_blocked" json:"is_blocked" db:"is_blocked" mapstructure:"is_blocked"` // Заблокирован ли администратор +} + +type AdminReq struct { + Login *string `json:"login"` + Password *string `json:"password"` // Пароль пользователя +} diff --git a/core/typescore/api.go b/core/typescore/api.go new file mode 100644 index 0000000..2ae96c2 --- /dev/null +++ b/core/typescore/api.go @@ -0,0 +1,21 @@ +package typescore + +type ApiResponseBase struct { + Data interface{} `json:"data"` // данные полученные от api + TotalCount uint64 `json:"total_count,omitempty"` + TotalAmount float64 `json:"total_amount,omitempty"` +} + +type AuthHandlerResponse struct { + TempSession *string `json:"temp_session,omitempty"` // Временный токен для 2FA + Token *string `json:"token"` // токен аутентификации +} + +type AuthReqAccount struct { + Login *string `json:"login,omitempty"` + Password *string `json:"password,omitempty"` + AccessCode *string `json:"access_code,omitempty"` + Token *string `json:"token,omitempty"` + + RedirectURI *string `json:"redirect_uri,omitempty"` +} diff --git a/core/typescore/user.go b/core/typescore/user.go index 386876b..a2219d6 100644 --- a/core/typescore/user.go +++ b/core/typescore/user.go @@ -22,3 +22,10 @@ type User struct { Department *Department `gorm:"-" json:"department,omitempty"` UserRoles []*UserRole `gorm:"-" json:"user_roles,omitempty"` } + +type UpdateUserReqAdmin struct { + ID *uint64 `json:"id"` + DepartmentID *uint64 `json:"department_id"` // Логин пользователя + IsBlocked *bool `json:"is_blocked"` // Заблокирован ли пользователь + IsFired *bool `json:"is_fired"` // Заблокирован ли пользователь +} diff --git a/core/typescore/user_hierarchy.go b/core/typescore/user_hierarchy.go index 1583145..1ecac90 100644 --- a/core/typescore/user_hierarchy.go +++ b/core/typescore/user_hierarchy.go @@ -18,6 +18,5 @@ type UserHierarchy struct { Subordinate *User `gorm:"-" json:"subordinate,omitempty"` Approver *User `gorm:"-" json:"approver,omitempty"` - Executor *User `gorm:"-" json:"executor,omitempty"` Department *Department `gorm:"-" json:"department,omitempty"` } diff --git a/core/utilscore/gen.go b/core/utilscore/gen.go new file mode 100644 index 0000000..4c0948d --- /dev/null +++ b/core/utilscore/gen.go @@ -0,0 +1,18 @@ +package utilscore + +import ( + "crypto/rand" + "encoding/base64" +) + +// GenerateRandomString генерирует случайную строку заданной длины +func GenerateRandomString(length int) (string, error) { + // Создаем срез байтов нужной длины + bytes := make([]byte, length) + // Заполняем срез случайными байтами + if _, err := rand.Read(bytes); err != nil { + return "", err + } + // Кодируем байты в строку в формате base64 + return base64.URLEncoding.EncodeToString(bytes), nil +} diff --git a/core/utilscore/ip.go b/core/utilscore/ip.go new file mode 100644 index 0000000..abe0e1c --- /dev/null +++ b/core/utilscore/ip.go @@ -0,0 +1,37 @@ +package utilscore + +import ( + "net" + "net/http" + "strings" +) + +func GetClientIP(r *http.Request) string { + + httpXRealIP := r.Header.Get("HTTP_X_REAL_IP") + if httpXRealIP != "" { + return httpXRealIP + } + + xForwardedFor := r.Header.Get("X-Forwarded-For") + if xForwardedFor != "" { + parts := strings.Split(xForwardedFor, ",") + for i, ip := range parts { + parts[i] = strings.TrimSpace(ip) + } + return parts[0] + } + + xRealIP := r.Header.Get("X-Real-IP") + if xRealIP != "" { + return xRealIP + } + + ip, _, err := net.SplitHostPort(r.RemoteAddr) + if err != nil { + // В случае ошибки возвращаем RemoteAddr как есть + // Это может быть не IP адрес пользователя, если за вашим приложением стоит прокси + return r.RemoteAddr + } + return ip +} diff --git a/core/utilscore/validation.go b/core/utilscore/validation.go new file mode 100644 index 0000000..5dbf4e8 --- /dev/null +++ b/core/utilscore/validation.go @@ -0,0 +1,34 @@ +package utilscore + +import ( + "errors" + "regexp" +) + +func ValidatePassword(password string) error { + // Проверка длины + if len(password) < 8 { + return errors.New("password must be at least 8 characters") + } + + // Проверка наличия хотя бы одной цифры + hasDigit := regexp.MustCompile(`\d`).MatchString(password) + if !hasDigit { + return errors.New("password must contain at least one digit") + } + + // Проверка наличия хотя бы одной латинской буквы (верхний или нижний регистр) + hasLetter := regexp.MustCompile(`[a-zA-Z]`).MatchString(password) + if !hasLetter { + return errors.New("password must contain at least one letter") + } + + // Проверка, что пароль содержит только разрешённые символы: латинские буквы, цифры, спецсимволы + validChars := regexp.MustCompile(`^[a-zA-Z0-9!@#$%^&*()_+{}[\]:;'"|,.<>/?~` + "`" + `-]*$`).MatchString(password) + if !validChars { + return errors.New("password contain invalid characters") + } + + // Все проверки пройдены + return nil +} diff --git a/core/variables/const.go b/core/variables/const.go new file mode 100644 index 0000000..e61b7c4 --- /dev/null +++ b/core/variables/const.go @@ -0,0 +1,10 @@ +package variables + +import "time" + +// context timeout +const ( + ContextTimeoutShort = 10 * time.Second + ContextTimeoutBase = 15 * time.Second + ContextTimeoutLong = 30 * time.Second +) diff --git a/core/variables/redis-const.go b/core/variables/redis-const.go new file mode 100644 index 0000000..2086344 --- /dev/null +++ b/core/variables/redis-const.go @@ -0,0 +1,5 @@ +package variables + +var ( + RedisPathUserAuthSessions = "auth_sessions" +) diff --git a/deploy.sh b/deploy.sh index e2000f0..a2ae15c 100644 --- a/deploy.sh +++ b/deploy.sh @@ -1,30 +1,262 @@ #!/bin/bash set -e -trap 'echo "🔴 Deploy failed"; exit 1' ERR +trap 'echo "🔴 Deploy failed at line $LINENO"; exit 1' ERR THIS_PATH=$(dirname "$(realpath "$0")") -SERVICE_NAME="rest_balancer_service" + +# ═══════════════════════════════════════════════════════════════ +# Цвета для вывода +# ═══════════════════════════════════════════════════════════════ +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +BLUE='\033[0;34m' +MAGENTA='\033[0;35m' +NC='\033[0m' + +log_info() { echo -e "${BLUE}ℹ️ $1${NC}"; } +log_success() { echo -e "${GREEN}✅ $1${NC}"; } +log_warning() { echo -e "${YELLOW}⚠️ $1${NC}"; } +log_error() { echo -e "${RED}❌ $1${NC}"; } +log_service() { echo -e "${MAGENTA}📦 $1${NC}"; } + +# ═══════════════════════════════════════════════════════════════ +# Парсинг аргументов +# ═══════════════════════════════════════════════════════════════ +SERVICE_TYPE="${1:-all}" # bot | admin | balancer | telegram | migrations | all +GENERATE_SWAGGER="${2:-false}" # swagger + +# Валидация +validate_service_type() { + case "$1" in + bot|telegram|balancer|admin|migrations|all) return 0 ;; + *) return 1 ;; + esac +} + +if ! validate_service_type "$SERVICE_TYPE"; then + log_error "Unknown service type: $SERVICE_TYPE" + echo "" + echo "Usage: $0 [service] [swagger]" + echo "" + echo "Services:" + echo " telegram - Telegram bot service" + echo " balancer - REST balancer service" + echo " admin - REST admin service" + echo " migrations - Run database migrations only" + echo " all - Deploy all services (default)" + echo "" + echo "Options:" + echo " swagger - Generate Swagger docs (for admin)" + echo "" + echo "Examples:" + echo " $0 # Deploy all services" + echo " $0 telegram # Deploy only bot" + echo " $0 admin swagger # Deploy admin with Swagger" + echo " $0 migrations # Run migrations only" + exit 1 +fi + +# ═══════════════════════════════════════════════════════════════ +# Обработка 'all' — деплоим всё последовательно +# ═══════════════════════════════════════════════════════════════ +if [ "$SERVICE_TYPE" = "all" ]; then + log_info "Deploying all services..." + echo "" + + # 1. Сначала миграции + log_service "Step 1/4: Database migrations" + "$0" migrations + echo "" + + # 2. Потом Telegram бот + log_service "Step 2/4: Telegram bot" + "$0" telegram + echo "" + + # 3. Потом балансировщик + log_service "Step 3/4: REST balancer" + "$0" balancer + echo "" + + # 4. В конце админка (с Swagger если нужно) + log_service "Step 4/4: REST admin" + "$0" admin "$GENERATE_SWAGGER" + + echo "" + log_success "All services deployed successfully!" + exit 0 +fi + +# ═══════════════════════════════════════════════════════════════ +# Определяем конфигурацию сервиса +# ═══════════════════════════════════════════════════════════════ +case "$SERVICE_TYPE" in + telegram|bot) + SERVICE_NAME="telegram_service" + DESCRIPTION="Telegram Bot Service" + SERVICE_KIND="daemon" + ;; + balancer) + SERVICE_NAME="rest_balancer_service" + DESCRIPTION="REST Balancer Service" + SERVICE_KIND="daemon" + ;; + admin) + SERVICE_NAME="rest_admin_service" + DESCRIPTION="REST Admin Service" + SERVICE_KIND="daemon" + ;; + migrations) + SERVICE_NAME="system_service" + DESCRIPTION="Database Migrations" + SERVICE_KIND="oneshot" + ;; +esac + SERVICE_PATH="$THIS_PATH/service/$SERVICE_NAME" BINARY_PATH="/usr/local/bin/$SERVICE_NAME" -echo "🔨 Building core..." +echo "════════════════════════════════════════" +log_info "Deploying: $DESCRIPTION" +log_info "Service: $SERVICE_NAME" +log_info "Kind: $SERVICE_KIND" +log_info "Path: $SERVICE_PATH" +log_info "Binary: $BINARY_PATH" +echo "════════════════════════════════════════" +echo "" + +# Проверка существования директории сервиса +if [ ! -d "$SERVICE_PATH" ]; then + log_error "Service directory not found: $SERVICE_PATH" + exit 1 +fi + +# ═══════════════════════════════════════════════════════════════ +# Генерация Swagger документации (только для админки) +# ═══════════════════════════════════════════════════════════════ +if [ "$SERVICE_TYPE" = "admin" ] && [ "$GENERATE_SWAGGER" = "swagger" ]; then + log_info "Generating Swagger documentation..." + + if ! command -v swag &> /dev/null; then + log_warning "swag CLI not found. Installing..." + go install github.com/swaggo/swag/cmd/swag@latest + export PATH=$PATH:$(go env GOPATH)/bin + fi + + cd "$SERVICE_PATH" + mkdir -p ./docs + swag init -g main.go --parseDependency --parseInternal -o ./docs + + log_success "Swagger documentation generated" + cd "$THIS_PATH" + echo "" +fi + +# ═══════════════════════════════════════════════════════════════ +# Сборка core +# ═══════════════════════════════════════════════════════════════ +log_info "Building core module..." cd "$THIS_PATH/core" go mod tidy go vet ./... +log_success "Core built successfully" +echo "" -echo "🔨 Building $SERVICE_NAME..." +# ═══════════════════════════════════════════════════════════════ +# Сборка сервиса +# ═══════════════════════════════════════════════════════════════ +log_info "Building $SERVICE_NAME..." cd "$SERVICE_PATH" -go mod tidy + gofmt -w . -go build -o "$BINARY_PATH" . +go vet ./... -echo "✅ Binary deployed to $BINARY_PATH" +# Сборка с оптимизациями (убираем отладочную информацию) +go build -ldflags="-s -w" -o "$BINARY_PATH" . -# Перезапускаем сервис если systemd юнит уже существует -if systemctl is-active --quiet "$SERVICE_NAME"; then - echo "🔄 Restarting systemd service..." - sudo systemctl restart "$SERVICE_NAME" -else - echo "⚠️ Service not running. Start with: sudo systemctl start $SERVICE_NAME" +log_success "Binary deployed to $BINARY_PATH" + +BINARY_SIZE=$(du -h "$BINARY_PATH" | cut -f1) +log_info "Binary size: $BINARY_SIZE" +echo "" + +# ═══════════════════════════════════════════════════════════════ +# Управление сервисом в зависимости от типа +# ═══════════════════════════════════════════════════════════════ +if [ "$SERVICE_KIND" = "daemon" ]; then + # ─── Долгоживущий сервис: перезапускаем ─── + if systemctl is-active --quiet "$SERVICE_NAME"; then + log_info "Restarting systemd service..." + sudo systemctl restart "$SERVICE_NAME" + sleep 2 + + if systemctl is-active --quiet "$SERVICE_NAME"; then + log_success "Service restarted successfully" + SERVICE_STATUS=$(systemctl is-active "$SERVICE_NAME") + log_info "Status: $SERVICE_STATUS" + else + log_error "Service failed to restart" + log_info "Check logs: sudo journalctl -u $SERVICE_NAME -n 50" + exit 1 + fi + else + log_warning "Service not running" + log_info "Start with: sudo systemctl start $SERVICE_NAME" + log_info "Enable on boot: sudo systemctl enable $SERVICE_NAME" + fi + +elif [ "$SERVICE_KIND" = "oneshot" ]; then + # ─── Одноразовый сервис (миграции): запускаем и ждём ─── + log_info "Running migrations..." + + # Запускаем сервис + sudo systemctl start "$SERVICE_NAME" + + # Ждём завершения (максимум 5 минут) + TIMEOUT=300 + ELAPSED=0 + + while systemctl is-active --quiet "$SERVICE_NAME"; do + sleep 2 + ELAPSED=$((ELAPSED + 2)) + + if [ $ELAPSED -ge $TIMEOUT ]; then + log_error "Migrations timed out after ${TIMEOUT}s" + sudo journalctl -u "$SERVICE_NAME" -n 50 --no-pager + exit 1 + fi + + # Показываем прогресс + printf "." + done + echo "" + + # Проверяем статус завершения + RESULT=$(systemctl show "$SERVICE_NAME" --property=ExecMainStatus --value) + + if [ "$RESULT" = "0" ]; then + log_success "Migrations completed successfully" + # Показываем последние строки лога + log_info "Migration log:" + sudo journalctl -u "$SERVICE_NAME" -n 20 --no-pager + else + log_error "Migrations failed with exit code: $RESULT" + sudo journalctl -u "$SERVICE_NAME" -n 50 --no-pager + exit 1 + fi +fi + +echo "" +echo "════════════════════════════════════════" +log_success "Deployment of $SERVICE_NAME completed!" +echo "════════════════════════════════════════" + +# Дополнительная информация для админки +if [ "$SERVICE_TYPE" = "admin" ]; then + echo "" + log_info "Admin panel info:" + echo " - Swagger UI: http://localhost:/swagger/index.html" + echo " - API docs: http://localhost:/swagger/doc.json" fi \ No newline at end of file diff --git a/go.work.sum b/go.work.sum index 7d0f59d..fdb2c38 100644 --- a/go.work.sum +++ b/go.work.sum @@ -4,17 +4,34 @@ github.com/Masterminds/semver/v3 v3.1.1 h1:hLg3sBzpNErnxhQtUy/mmLR2I9foDujNK030I github.com/Masterminds/semver/v3 v3.1.1/go.mod h1:VPu/7SZ7ePZ3QOrcuXROw5FAcLl4a0cBrbBpGY/8hQs= github.com/Masterminds/sprig/v3 v3.2.1 h1:n6EPaDyLSvCEa3frruQvAiHuNp2dhBlMSmkEr+HuzGc= github.com/Masterminds/sprig/v3 v3.2.1/go.mod h1:UoaO7Yp8KlPnJIYWTFkMaqPUYKTfGFPhxNuwnnxkKlk= +github.com/PuerkitoBio/purell v1.1.1 h1:WEQqlqaGbrPkxLJWfBwQmfEAE1Z7ONdDLqrN38tNFfI= +github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0= +github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 h1:d+Bc7a5rLufV/sSk/8dngufqelfh6jnri85riMAaF/M= +github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE= github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310 h1:BUAU3CGlLvorLI26FmByPp2eC2qla6E1Tw+scpcg/to= github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= github.com/bgentry/speakeasy v0.1.0 h1:ByYyxL9InA1OWqxJqqp2A5pYHUrCiAL6K3J+LKSsQkY= github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= +github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d h1:U+s90UTSYgptZMwQh2aRr3LuazLJIa+Pg3Kc1ylSYVY= +github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/creack/pty v1.1.9 h1:uDmaGzcdjhF4i/plgjmEsriH11Y0o7RKapEf/LDaM3w= -github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= -github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/go-openapi/swag v0.19.15/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ= +github.com/go-openapi/swag/cmdutils v0.26.1 h1:f2iE1ijYaJ3nuu5PaEMx3zpEhzhZFgivCJObWEObLIQ= +github.com/go-openapi/swag/cmdutils v0.26.1/go.mod h1:Sm1MVFMkF6guJJ+pQqHnQA3N0j9qALV3NxzDSv6bETM= +github.com/go-openapi/swag/fileutils v0.26.1 h1:K1XCM2CGhfNsc6YDt6v7Q5+1e59rftYWdcu/isZhvFw= +github.com/go-openapi/swag/fileutils v0.26.1/go.mod h1:mYUgxQAKX4ShS3qvvySx+/9yrlUnDhjiD1CalaQl8lQ= +github.com/go-openapi/swag/mangling v0.26.1 h1:gpYI4WuPKFJJVjV5cDLGlDVJhFIxYjQc7yN5eEb4CqM= +github.com/go-openapi/swag/mangling v0.26.1/go.mod h1:POETDH01hqAdASXfw7ISEd9bCOE6xBHOt8NHmGZRmYM= +github.com/go-openapi/swag/netutils v0.26.1 h1:BNctoc39WTAUMxyAs355fExOPzMZtPbZ0ZZ1Am2FR5M= +github.com/go-openapi/swag/netutils v0.26.1/go.mod h1:y02vByhZhQPAVwOX+0KipXFZ/hUbk6G/Enhf5rGaOkQ= github.com/huandu/xstrings v1.3.2 h1:L18LIDzqlW6xN2rEkpdV8+oL/IXWJ1APd+vsdYy4Wdw= github.com/huandu/xstrings v1.3.2/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE= github.com/imdario/mergo v0.3.11 h1:3tnifQM4i+fbajXKBHXWEH+KvNHqojZ778UH75j3bGA= github.com/imdario/mergo v0.3.11/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= +github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= +github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= +github.com/mailru/easyjson v0.7.6 h1:8yTIVnZgCoiM1TgqoeTl+LfU5Jg6/xL3QhGQnimLYnA= +github.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU= github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= github.com/mitchellh/cli v1.1.5 h1:OxRIeJXpAMztws/XHlN2vu6imG5Dpq+j61AzAX5fLng= @@ -29,13 +46,18 @@ github.com/natefinch/atomic v1.0.1 h1:ZPYKxkqQOx3KZ+RsbnP/YsgvxWQPGxjC0oBt2AhwV0 github.com/natefinch/atomic v1.0.1/go.mod h1:N/D/ELrljoqDyT3rZrsUmtsuzvHkeB/wWjHV22AZRbM= github.com/posener/complete v1.1.1 h1:ccV59UEOTzVDnDUEFdT95ZzHVZ+5+158q8+SJb2QV5w= github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= +github.com/russross/blackfriday/v2 v2.0.1 h1:lPqVAte+HuHNfhJ/0LC98ESWRz8afy9tM/0RK8m9o+Q= +github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/ryanuber/columnize v2.1.2+incompatible h1:C89EOx/XBWwIXl8wm8OPJBd7kPF25UfsK2X7Ph/zCAk= github.com/ryanuber/columnize v2.1.2+incompatible/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= +github.com/shurcooL/sanitized_anchor_name v1.0.0 h1:PdmoCO6wvbs+7yrJyMORt4/BmY5IYyJwS/kOiWx8mHo= +github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= github.com/spf13/cast v1.3.1 h1:nFm6S0SMdyzrzcmThSipiEubIDy8WEXKNZ0UOgiRpng= github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= github.com/stretchr/objx v0.1.0 h1:4G4v2dO3VZwixGIRoQ5Lfboy6nUhCyYzaqnIAPPhYs4= +github.com/urfave/cli/v2 v2.3.0 h1:qph92Y649prgesehzOrQjdWyxFOp/QVM+6imKHad91M= +github.com/urfave/cli/v2 v2.3.0/go.mod h1:LJmUH05zAU44vOAcrfzZQKsZbVcdbOG8rtL3/XcUArI= github.com/yuin/goldmark v1.4.13 h1:fVcFKWvrslecOb/tg+Cc05dkeYx540o0FuFt3nUVDoE= -github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= golang.org/x/crypto v0.41.0 h1:WKYxWedPGCTVVl5+WHSSrOBT0O8lx32+zxmHxijgXp4= golang.org/x/crypto v0.41.0/go.mod h1:pO5AFd7FA68rFak7rOAGVuygIISepHftHnr8dr6+sUc= golang.org/x/image v0.25.0 h1:Y6uW6rH1y5y/LK1J8BPWZtr6yZ7hrsy6hFrXjgsc2fQ= @@ -44,25 +66,37 @@ golang.org/x/mod v0.27.0 h1:kb+q2PyFnEADO2IEF935ehFUXlWiNjJWtRNgBLSfbxQ= golang.org/x/mod v0.27.0/go.mod h1:rWI627Fq0DEoudcK+MBkNkCe0EetEaDSwJJkCcjpazc= golang.org/x/mod v0.32.0 h1:9F4d3PHLljb6x//jOyokMv3eX+YDeepZSEo3mFJy93c= golang.org/x/mod v0.32.0/go.mod h1:SgipZ/3h2Ci89DlEtEXWUk/HteuRin+HHhN+WbNhguU= +golang.org/x/mod v0.36.0/go.mod h1:moc6ELqsWcOw5Ef3xVprK5ul/MvtVvkIXLziUOICjUQ= golang.org/x/net v0.43.0 h1:lat02VYK2j4aLzMzecihNvTlJNQUq316m2Mr9rnM6YE= golang.org/x/net v0.43.0/go.mod h1:vhO1fvI4dGsIjh73sWfUVjj3N7CA9WkKJNQm2svM6Jg= golang.org/x/net v0.49.0/go.mod h1:/ysNB2EvaqvesRkuLAyjI1ycPZlQHM3q01F02UY/MV8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4= golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= golang.org/x/telemetry v0.0.0-20250807160809-1a19826ec488 h1:3doPGa+Gg4snce233aCWnbZVFsyFMo/dR40KK/6skyE= golang.org/x/telemetry v0.0.0-20250807160809-1a19826ec488/go.mod h1:fGb/2+tgXXjhjHsTNdVEEMZNWA0quBnfrO+AfoDSAKw= golang.org/x/telemetry v0.0.0-20260109210033-bd525da824e2 h1:O1cMQHRfwNpDfDJerqRoE2oD+AFlyid87D40L/OkkJo= golang.org/x/telemetry v0.0.0-20260109210033-bd525da824e2/go.mod h1:b7fPSJ0pKZ3ccUh8gnTONJxhn3c/PS6tyzQvyqw4iA8= +golang.org/x/telemetry v0.0.0-20260610154732-fb80ec83bdd9 h1:FjUup8XrRy7lv+XHONi6KKUSizeF2NnVrTnz/HhbohQ= +golang.org/x/telemetry v0.0.0-20260610154732-fb80ec83bdd9/go.mod h1:3AWMyWHS+caVoiEXpiq6+tzKA40J4vQT3MYr80ZtQpc= golang.org/x/term v0.33.0 h1:NuFncQrRcaRvVmgRkvM3j/F00gWIAlcmlB8ACEKmGIg= golang.org/x/term v0.33.0/go.mod h1:s18+ql9tYWp1IfpV9DmCtQDDSRBUjKaw9M1eAv5UeF0= golang.org/x/term v0.34.0 h1:O/2T7POpk0ZZ7MAzMeWFSg6S5IpWd/RXDlM9hgM3DR4= golang.org/x/term v0.34.0/go.mod h1:5jC53AEywhIVebHgPVeg0mj8OD3VO9OzclacVrqpaAw= golang.org/x/term v0.40.0 h1:36e4zGLqU4yhjlmxEaagx2KuYbJq3EwY8K943ZsHcvg= golang.org/x/term v0.40.0/go.mod h1:w2P8uVp06p2iyKKuvXIm7N/y0UCRt3UfJTfZ7oOpglM= +golang.org/x/term v0.44.0 h1:0rLvDRCtNj0gZkyIXhCyOb2OAzEhLVqc4B+hrsBhrmc= +golang.org/x/term v0.44.0/go.mod h1:7ze4MdzUzLXpSAoFP1H0bOI9aXDqveSvatT5vKcFh2Y= golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU= golang.org/x/tools v0.36.0 h1:kWS0uv/zsvHEle1LbV5LE8QujrxB3wfQyxHfhOk0Qkg= golang.org/x/tools v0.36.0/go.mod h1:WBDiHKJK8YgLHlcQPYQzNCkUxUypCaa5ZegCVutKm+s= golang.org/x/tools v0.41.0 h1:a9b8iMweWG+S0OBnlU36rzLp20z1Rp10w+IY2czHTQc= golang.org/x/tools v0.41.0/go.mod h1:XSY6eDqxVNiYgezAVqqCeihT4j1U2CCsqvH3WhQpnlg= +golang.org/x/tools v0.45.0/go.mod h1:LuUGqqaXcXMEFEruIVJVm5mgDD8vww/z/SR1gQ4uE/0= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7 h1:9zdDQZ7Thm29KFXgAX/+yaf3eVbP7djjWp/dXAppNCc= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ= gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8= +sigs.k8s.io/yaml v1.3.0 h1:a2VclLzOGrwOHDiV8EfBGhvjHvP46CtW5j6POvhYGGo= +sigs.k8s.io/yaml v1.3.0/go.mod h1:GeOyir5tyXNByN85N/dRIT9es5UQNerPYEKK56eTBm8= diff --git a/service/rest_admin_service/cmd/app.go b/service/rest_admin_service/cmd/app.go index 0ca3aeb..974056e 100644 --- a/service/rest_admin_service/cmd/app.go +++ b/service/rest_admin_service/cmd/app.go @@ -3,6 +3,21 @@ package main import ( configcore "bitrix_balancer_api/core/config" clientcontrollers "bitrix_balancer_api/core/lib/internally/client-controllers" + _ "bitrix_balancer_api/rest_admin_service/docs" + adminhandler "bitrix_balancer_api/rest_admin_service/handlers/admin" + approvalstepshandler "bitrix_balancer_api/rest_admin_service/handlers/approval_steps" + approvalshandler "bitrix_balancer_api/rest_admin_service/handlers/approvals" + authhandler "bitrix_balancer_api/rest_admin_service/handlers/auth" + departmentshandler "bitrix_balancer_api/rest_admin_service/handlers/departments" + permissionshandler "bitrix_balancer_api/rest_admin_service/handlers/permission" + profilehandler "bitrix_balancer_api/rest_admin_service/handlers/profile" + roleshandler "bitrix_balancer_api/rest_admin_service/handlers/roles" + categorieshandler "bitrix_balancer_api/rest_admin_service/handlers/topic_categories" + topicexecutorshandler "bitrix_balancer_api/rest_admin_service/handlers/topic_executors" + topicshandler "bitrix_balancer_api/rest_admin_service/handlers/topics" + hierarchieshandler "bitrix_balancer_api/rest_admin_service/handlers/user_hierarchy" + userroleshandler "bitrix_balancer_api/rest_admin_service/handlers/user_roles" + usershandler "bitrix_balancer_api/rest_admin_service/handlers/users" typesm "bitrix_balancer_api/rest_admin_service/types" "errors" "fmt" @@ -11,6 +26,7 @@ import ( "github.com/go-chi/cors" "github.com/go-chi/httprate" "github.com/sirupsen/logrus" + httpSwagger "github.com/swaggo/http-swagger" "log" "net/http" "time" @@ -24,6 +40,45 @@ const ( rateWindow = 1 * time.Second // Окно времени для лимита запросов ) +// @title RusPet Admin API +// @version 0.1 +// @description API админ-панели для системы согласований +// @description +// @description ## Возможности +// @description - Управление отделами, ролями и пользователями +// @description - Настройка тем и категорий согласований +// @description - Управление иерархией согласований +// @description - Назначение исполнителей и прав +// @description - Просмотр заявок и шагов согласования +// @description +// @description ## Аутентификация +// @description Все защищённые эндпоинты требуют: +// @description - `Authorization: Bearer ` — JWT токен администратора +// @description - `ApiKey: ` — HMAC подпись для верификации клиента +// @description - `X-Timestamp: ` — Unix timestamp (не старше 3 минут) +// @description - `x-device-id: ` — ID устройства +// +// @host localhost:8080 +// @BasePath / +// +// @securityDefinitions.apikey BearerAuth +// @in header +// @name Authorization +// +// @securityDefinitions.apikey ApiKeyAuth +// @in header +// @name ApiKey +// +// @securityDefinitions.apikey DeviceID +// @in header +// @name x-device-id +// +// @securityDefinitions.apikey Timestamp +// @in header +// @name X-Timestamp +// +// @contact.name Roman +// @contact.email romanzabolotskij0@gmail.com func main() { err := initService() if err != nil { @@ -69,6 +124,9 @@ func getClientsExternal() (clientcontrollers.ClientsExternal, error) { }, AdminAccessCode: true, }, + Server: configcore.ExposedServiceOptions{ + RESTAdminService: true, + }, } return clientcontrollers.ReturnClientsExternal(options) @@ -129,12 +187,32 @@ func initBaseApiRouter(ipc *typesm.InternalProviderControl) (*chi.Mux, error) { // регистрирует маршруты func registerRoutes(router chi.Router, ipc *typesm.InternalProviderControl) error { + router.Get("/swagger/*", httpSwagger.Handler( + httpSwagger.URL("/swagger/doc.json"), // URL к сгенерированному JSON + httpSwagger.DeepLinking(true), + httpSwagger.DocExpansion("none"), + httpSwagger.DomID("swagger-ui"), + )) + // Слайс обработчиков маршрутов routeHandlers := []struct { name string handler func(chi.Router, *typesm.InternalProviderControl) error }{ {"admin", adminhandler.RegisterAdminRoutes}, + {"auth", authhandler.RegisterAuthRoutes}, + {"profile", profilehandler.RegisterProfileRoutes}, + {"users", usershandler.RegisterUserRoutes}, + {"departments", departmentshandler.RegisterDepartmentRoutes}, + {"roles", roleshandler.RegisterRoleRoutes}, + {"categories", categorieshandler.RegisterCategoryRoutes}, + {"topics", topicshandler.RegisterTopicRoutes}, + {"user-roles", userroleshandler.RegisterUserRoleRoutes}, + {"hierarchies", hierarchieshandler.RegisterHierarchyRoutes}, + {"topic-executors", topicexecutorshandler.RegisterTopicExecutorRoutes}, + {"approvals", approvalshandler.RegisterApprovalRoutes}, + {"approval-steps", approvalstepshandler.RegisterApprovalStepRoutes}, + {"permissions", permissionshandler.RegisterPermissionRoutes}, } // Регистрация всех маршрутов diff --git a/service/rest_admin_service/docs/docs.go b/service/rest_admin_service/docs/docs.go new file mode 100644 index 0000000..3c24c6f --- /dev/null +++ b/service/rest_admin_service/docs/docs.go @@ -0,0 +1,3990 @@ +// Package docs Code generated by swaggo/swag. DO NOT EDIT +package docs + +import "github.com/swaggo/swag" + +const docTemplate = `{ + "schemes": {{ marshal .Schemes }}, + "swagger": "2.0", + "info": { + "description": "{{escape .Description}}", + "title": "{{.Title}}", + "contact": {}, + "version": "{{.Version}}" + }, + "host": "{{.Host}}", + "basePath": "{{.BasePath}}", + "paths": { + "/api/admin": { + "get": { + "description": "Получение списка администраторов", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "admin" + ], + "summary": "Получение списка администраторов", + "parameters": [ + { + "type": "integer", + "description": "Смещение для пагинации", + "name": "offset", + "in": "query" + }, + { + "type": "integer", + "description": "Количество записей на странице", + "name": "limit", + "in": "query" + }, + { + "type": "boolean", + "description": "Фильтр по активности", + "name": "is_active", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.Admin" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "post": { + "description": "Создание администратора", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "admin" + ], + "summary": "Создание администратора", + "parameters": [ + { + "description": "Запрос", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.AdminReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/typescore.Admin" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "delete": { + "description": "Удаление администратора", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "admin" + ], + "summary": "Удаление администратора", + "parameters": [ + { + "description": "Запрос", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.AdminReq" + } + } + ], + "responses": { + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/admin/profile": { + "get": { + "description": "Получение профиля пользователя", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "profile" + ], + "summary": "Получение профиля пользователя", + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/typescore.Admin" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "put": { + "description": "Обновление профиля пользователя", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "profile" + ], + "summary": "Обновление профиля пользователя", + "parameters": [ + { + "description": "Запрос", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.AdminReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/typescore.Admin" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/approval-steps": { + "get": { + "description": "Получение списка шагов согласования с пагинацией и фильтрацией", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "approval-steps" + ], + "summary": "Получение списка шагов", + "parameters": [ + { + "type": "integer", + "description": "Смещение для пагинации", + "name": "offset", + "in": "query" + }, + { + "type": "integer", + "description": "Количество записей на странице", + "name": "limit", + "in": "query" + }, + { + "type": "integer", + "description": "Фильтр по заявке", + "name": "approval_id", + "in": "query" + }, + { + "type": "integer", + "description": "Фильтр по согласующему", + "name": "approver_id", + "in": "query" + }, + { + "type": "string", + "description": "Фильтр по статусу (pending, waiting, approved, rejected, cancelled_any_of)", + "name": "status", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApiResponseBase" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "put": { + "description": "Обновление данных шага согласования (статус, комментарий)", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "approval-steps" + ], + "summary": "Обновление шага", + "parameters": [ + { + "description": "Данные шага", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.ApprovalStep" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApprovalStep" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Шаг не найден", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "post": { + "description": "Создание нового шага согласования для заявки", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "approval-steps" + ], + "summary": "Создание шага", + "parameters": [ + { + "description": "Данные шага", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.ApprovalStep" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApprovalStep" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Заявка или согласующий не найдены", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "delete": { + "description": "Удаление шага согласования (только для заявок в статусе pending)", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "approval-steps" + ], + "summary": "Удаление шага", + "parameters": [ + { + "description": "ID шага для удаления", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.ApprovalStep" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "type": "boolean" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "403": { + "description": "Нельзя удалить шаг завершённой заявки", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Шаг не найден", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/approval-steps/by-approval/{approval_id}": { + "get": { + "description": "Получение списка всех шагов согласования для указанной заявки, отсортированных по step_order", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "approval-steps" + ], + "summary": "Получение шагов по заявке", + "parameters": [ + { + "type": "integer", + "description": "ID заявки", + "name": "approval_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApiResponseBase" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Заявка не найдена", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/approval-steps/{id}": { + "get": { + "description": "Получение детальной информации о шаге согласования по его ID", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "approval-steps" + ], + "summary": "Получение шага по ID", + "parameters": [ + { + "type": "integer", + "description": "ID шага", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApprovalStep" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Шаг не найден", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/approvals": { + "get": { + "description": "Получение списка заявок с пагинацией и фильтрацией", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "approvals" + ], + "summary": "Получение списка заявок", + "parameters": [ + { + "type": "integer", + "description": "Смещение для пагинации", + "name": "offset", + "in": "query" + }, + { + "type": "integer", + "description": "Количество записей на странице", + "name": "limit", + "in": "query" + }, + { + "type": "string", + "description": "Фильтр по статусу (pending, approved, rejected, revoked, revision)", + "name": "status", + "in": "query" + }, + { + "type": "integer", + "description": "Фильтр по инициатору", + "name": "initiator_id", + "in": "query" + }, + { + "type": "integer", + "description": "Фильтр по теме", + "name": "topic_id", + "in": "query" + }, + { + "type": "integer", + "description": "Фильтр по отделу", + "name": "department_id", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApiResponseBase" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "put": { + "description": "Обновление данных заявки (статус, комментарии и т.д.)", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "approvals" + ], + "summary": "Обновление заявки", + "parameters": [ + { + "description": "Данные заявки", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.Approval" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.Approval" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Заявка не найдена", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "delete": { + "description": "Удаление заявки (только для черновиков)", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "approvals" + ], + "summary": "Удаление заявки", + "parameters": [ + { + "description": "ID заявки для удаления", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.Approval" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "type": "boolean" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "403": { + "description": "Нельзя удалить не-черновую заявку", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Заявка не найдена", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/approvals/report": { + "get": { + "description": "Получение списка заявок для отчёта с учётом периода и доступа пользователя", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "approvals" + ], + "summary": "Получение заявок для отчёта", + "parameters": [ + { + "type": "integer", + "description": "ID пользователя (если не указан - все заявки)", + "name": "user_id", + "in": "query" + }, + { + "type": "string", + "description": "Начальная дата (YYYY-MM-DD)", + "name": "date_from", + "in": "query" + }, + { + "type": "string", + "description": "Конечная дата (YYYY-MM-DD)", + "name": "date_to", + "in": "query" + }, + { + "type": "boolean", + "description": "Полный доступ (игнорировать фильтрацию по пользователю)", + "name": "all_access", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApiResponseBase" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/approvals/{id}": { + "get": { + "description": "Получение детальной информации о заявке по её ID со всеми связанными данными", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "approvals" + ], + "summary": "Получение заявки по ID", + "parameters": [ + { + "type": "integer", + "description": "ID заявки", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.Approval" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Заявка не найдена", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/auth/login": { + "post": { + "description": "авторизация с помощью связки логин-пароль", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "auth" + ], + "summary": "авторизация с помощью связки логин-пароль", + "parameters": [ + { + "description": "Запрос", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.AuthReqAccount" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/typescore.AuthHandlerResponse" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/auth/token": { + "post": { + "description": "Авторизация при помощи JWT-токена", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "auth" + ], + "summary": "Авторизация при помощи JWT-токена", + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/typescore.AuthHandlerResponse" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/categories": { + "get": { + "description": "Получение списка категорий тем с пагинацией и фильтрацией", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "categories" + ], + "summary": "Получение списка категорий тем", + "parameters": [ + { + "type": "integer", + "description": "Смещение для пагинации", + "name": "offset", + "in": "query" + }, + { + "type": "integer", + "description": "Количество записей на странице", + "name": "limit", + "in": "query" + }, + { + "type": "boolean", + "description": "Фильтр по активности", + "name": "is_active", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApiResponseBase" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "put": { + "description": "Обновление данных существующей категории", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "categories" + ], + "summary": "Обновление категории", + "parameters": [ + { + "description": "Данные категории", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.ApprovalTopicCategory" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApprovalTopicCategory" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Категория не найдена", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "post": { + "description": "Создание новой категории тем", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "categories" + ], + "summary": "Создание категории тем", + "parameters": [ + { + "description": "Данные категории", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.ApprovalTopicCategory" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApprovalTopicCategory" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "delete": { + "description": "Удаление категории по ID", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "categories" + ], + "summary": "Удаление категории", + "parameters": [ + { + "description": "ID категории для удаления", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.ApprovalTopicCategory" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "type": "boolean" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Категория не найдена", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "409": { + "description": "Категория содержит темы", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/categories/{id}": { + "get": { + "description": "Получение детальной информации о категории по её ID", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "categories" + ], + "summary": "Получение категории по ID", + "parameters": [ + { + "type": "integer", + "description": "ID категории", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApprovalTopicCategory" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Категория не найдена", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/departments": { + "get": { + "description": "Получение списка отделов с пагинацией и фильтрацией", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "departments" + ], + "summary": "Получение списка отделов", + "parameters": [ + { + "type": "integer", + "description": "Смещение для пагинации", + "name": "offset", + "in": "query" + }, + { + "type": "integer", + "description": "Количество записей на странице", + "name": "limit", + "in": "query" + }, + { + "type": "boolean", + "description": "Фильтр по активности", + "name": "is_active", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApiResponseBase" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "put": { + "description": "Обновление данных существующего отдела", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "departments" + ], + "summary": "Обновление отдела", + "parameters": [ + { + "description": "Данные отдела", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.Department" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.Department" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Отдел не найден", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "post": { + "description": "Создание нового отдела", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "departments" + ], + "summary": "Создание отдела", + "parameters": [ + { + "description": "Данные отдела", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.Department" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.Department" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "delete": { + "description": "Удаление отдела по ID", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "departments" + ], + "summary": "Удаление отдела", + "parameters": [ + { + "description": "ID отдела для удаления", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.Department" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "type": "boolean" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Отдел не найден", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/departments/{id}": { + "get": { + "description": "Получение детальной информации об отделе по его ID", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "departments" + ], + "summary": "Получение отдела по ID", + "parameters": [ + { + "type": "integer", + "description": "ID отдела", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.Department" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Отдел не найден", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/hierarchies": { + "get": { + "description": "Получение списка связей подчинённый-согласующий с пагинацией и фильтрацией", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "hierarchies" + ], + "summary": "Получение списка записей иерархии", + "parameters": [ + { + "type": "integer", + "description": "Смещение для пагинации", + "name": "offset", + "in": "query" + }, + { + "type": "integer", + "description": "Количество записей на странице", + "name": "limit", + "in": "query" + }, + { + "type": "integer", + "description": "Фильтр по подчинённому", + "name": "subordinate_id", + "in": "query" + }, + { + "type": "integer", + "description": "Фильтр по согласующему", + "name": "approver_id", + "in": "query" + }, + { + "type": "integer", + "description": "Фильтр по отделу", + "name": "department_id", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApiResponseBase" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "put": { + "description": "Обновление данных существующей записи иерархии", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "hierarchies" + ], + "summary": "Обновление записи иерархии", + "parameters": [ + { + "description": "Данные иерархии", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.UserHierarchy" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.UserHierarchy" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Запись не найдена", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "post": { + "description": "Создание новой связи подчинённый-согласующий", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "hierarchies" + ], + "summary": "Создание записи иерархии", + "parameters": [ + { + "description": "Данные иерархии", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.UserHierarchy" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.UserHierarchy" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "409": { + "description": "Такая связь уже существует", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "delete": { + "description": "Удаление связи подчинённый-согласующий по ID", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "hierarchies" + ], + "summary": "Удаление записи иерархии", + "parameters": [ + { + "description": "ID записи для удаления", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.UserHierarchy" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "type": "boolean" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Запись не найдена", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/hierarchies/{id}": { + "get": { + "description": "Получение детальной информации о записи иерархии по её ID", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "hierarchies" + ], + "summary": "Получение записи иерархии по ID", + "parameters": [ + { + "type": "integer", + "description": "ID записи", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.UserHierarchy" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Запись не найдена", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/permissions": { + "get": { + "description": "Получение списка прав ролей с пагинацией и фильтрацией", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "permissions" + ], + "summary": "Получение списка прав", + "parameters": [ + { + "type": "integer", + "description": "Смещение для пагинации", + "name": "offset", + "in": "query" + }, + { + "type": "integer", + "description": "Количество записей на странице", + "name": "limit", + "in": "query" + }, + { + "type": "integer", + "description": "Фильтр по роли", + "name": "role_id", + "in": "query" + }, + { + "type": "string", + "description": "Фильтр по действию (create, read, update, delete, approve, revoke)", + "name": "action", + "in": "query" + }, + { + "type": "integer", + "description": "Фильтр по категории тем", + "name": "topic_category_id", + "in": "query" + }, + { + "type": "integer", + "description": "Фильтр по теме", + "name": "topic_id", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApiResponseBase" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "put": { + "description": "Обновление данных существующего права", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "permissions" + ], + "summary": "Обновление права", + "parameters": [ + { + "description": "Данные права", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.Permission" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.Permission" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Право не найдено", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "post": { + "description": "Назначение права на действие для роли", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "permissions" + ], + "summary": "Создание права", + "parameters": [ + { + "description": "Данные права", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.Permission" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.Permission" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Роль, категория или тема не найдены", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "409": { + "description": "Такое право уже существует", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "delete": { + "description": "Удаление права по ID", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "permissions" + ], + "summary": "Удаление права", + "parameters": [ + { + "description": "ID права для удаления", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.Permission" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "type": "boolean" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Право не найдено", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/permissions/by-role/{role_id}": { + "get": { + "description": "Получение списка всех прав для указанной роли", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "permissions" + ], + "summary": "Получение прав по роли", + "parameters": [ + { + "type": "integer", + "description": "ID роли", + "name": "role_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApiResponseBase" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Роль не найдена", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/permissions/{id}": { + "get": { + "description": "Получение детальной информации о праве по его ID", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "permissions" + ], + "summary": "Получение права по ID", + "parameters": [ + { + "type": "integer", + "description": "ID права", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.Permission" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Право не найдено", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/roles": { + "get": { + "description": "Получение списка ролей с пагинацией и фильтрацией", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "roles" + ], + "summary": "Получение списка ролей", + "parameters": [ + { + "type": "integer", + "description": "Смещение для пагинации", + "name": "offset", + "in": "query" + }, + { + "type": "integer", + "description": "Количество записей на странице", + "name": "limit", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApiResponseBase" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "put": { + "description": "Обновление данных существующей роли", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "roles" + ], + "summary": "Обновление роли", + "parameters": [ + { + "description": "Данные роли", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.Role" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.Role" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Роль не найдена", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "post": { + "description": "Создание новой роли", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "roles" + ], + "summary": "Создание роли", + "parameters": [ + { + "description": "Данные роли", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.Role" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.Role" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "delete": { + "description": "Удаление роли по ID", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "roles" + ], + "summary": "Удаление роли", + "parameters": [ + { + "description": "ID роли для удаления", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.Role" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "type": "boolean" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Роль не найдена", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/roles/{id}": { + "get": { + "description": "Получение детальной информации о роли по её ID", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "roles" + ], + "summary": "Получение роли по ID", + "parameters": [ + { + "type": "integer", + "description": "ID роли", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.Role" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Роль не найдена", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/topic-executors": { + "get": { + "description": "Получение списка исполнителей с пагинацией и фильтрацией", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "topic-executors" + ], + "summary": "Получение списка исполнителей тем", + "parameters": [ + { + "type": "integer", + "description": "Смещение для пагинации", + "name": "offset", + "in": "query" + }, + { + "type": "integer", + "description": "Количество записей на странице", + "name": "limit", + "in": "query" + }, + { + "type": "integer", + "description": "Фильтр по теме", + "name": "topic_id", + "in": "query" + }, + { + "type": "integer", + "description": "Фильтр по пользователю", + "name": "user_id", + "in": "query" + }, + { + "type": "boolean", + "description": "Фильтр по активности", + "name": "is_active", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApiResponseBase" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "put": { + "description": "Обновление данных исполнителя для темы", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "topic-executors" + ], + "summary": "Обновление исполнителя", + "parameters": [ + { + "description": "Данные исполнителя", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.ApprovalTopicExecutor" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApprovalTopicExecutor" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Исполнитель не найден", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "post": { + "description": "Назначение исполнителя для конкретной темы согласования", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "topic-executors" + ], + "summary": "Создание исполнителя", + "parameters": [ + { + "description": "Данные исполнителя", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.ApprovalTopicExecutor" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApprovalTopicExecutor" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Тема или пользователь не найдены", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "409": { + "description": "Такой исполнитель уже назначен на этот шаг", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "delete": { + "description": "Удаление исполнителя из темы по ID", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "topic-executors" + ], + "summary": "Удаление исполнителя", + "parameters": [ + { + "description": "ID записи для удаления", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.ApprovalTopicExecutor" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "type": "boolean" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Запись не найдена", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/topic-executors/by-topic/{topic_id}": { + "get": { + "description": "Получение списка всех активных исполнителей для указанной темы, отсортированных по step_order", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "topic-executors" + ], + "summary": "Получение исполнителей по теме", + "parameters": [ + { + "type": "integer", + "description": "ID темы", + "name": "topic_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApiResponseBase" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Тема не найдена", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/topic-executors/{id}": { + "get": { + "description": "Получение детальной информации об исполнителе по его ID", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "topic-executors" + ], + "summary": "Получение исполнителя по ID", + "parameters": [ + { + "type": "integer", + "description": "ID исполнителя", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApprovalTopicExecutor" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Исполнитель не найден", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/topics": { + "get": { + "description": "Получение списка тем с пагинацией и фильтрацией", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "topics" + ], + "summary": "Получение списка тем", + "parameters": [ + { + "type": "integer", + "description": "Смещение для пагинации", + "name": "offset", + "in": "query" + }, + { + "type": "integer", + "description": "Количество записей на странице", + "name": "limit", + "in": "query" + }, + { + "type": "integer", + "description": "Фильтр по категории", + "name": "category_id", + "in": "query" + }, + { + "type": "boolean", + "description": "Фильтр по активности", + "name": "is_active", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApiResponseBase" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "put": { + "description": "Обновление данных существующей темы", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "topics" + ], + "summary": "Обновление темы", + "parameters": [ + { + "description": "Данные темы", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.ApprovalTopic" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApprovalTopic" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Тема не найдена", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "post": { + "description": "Создание новой темы согласования", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "topics" + ], + "summary": "Создание темы", + "parameters": [ + { + "description": "Данные темы", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.ApprovalTopic" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApprovalTopic" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "delete": { + "description": "Удаление темы по ID", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "topics" + ], + "summary": "Удаление темы", + "parameters": [ + { + "description": "ID темы для удаления", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.ApprovalTopic" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "type": "boolean" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Тема не найдена", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "409": { + "description": "Тема содержит заявки", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/topics/{id}": { + "get": { + "description": "Получение детальной информации о теме по её ID", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "topics" + ], + "summary": "Получение темы по ID", + "parameters": [ + { + "type": "integer", + "description": "ID темы", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApprovalTopic" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Тема не найдена", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/user-roles": { + "get": { + "description": "Получение списка ролей, назначенных конкретному пользователю", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "user-roles" + ], + "summary": "Получение списка ролей пользователя", + "parameters": [ + { + "type": "integer", + "description": "ID пользователя", + "name": "user_id", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApiResponseBase" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "post": { + "description": "Назначение роли пользователю (создание связи user_id + role_id)", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "user-roles" + ], + "summary": "Назначение роли пользователю", + "parameters": [ + { + "description": "user_id и role_id", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/handlers_user_roles.AssignUserRoleRequest" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.UserRole" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Пользователь или роль не найдены", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "409": { + "description": "Роль уже назначена", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "delete": { + "description": "Удаление связи user_id + role_id по ID записи", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "user-roles" + ], + "summary": "Удаление роли у пользователя", + "parameters": [ + { + "description": "ID записи для удаления", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.UserRole" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "type": "boolean" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Запись не найдена", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/user-roles/bulk": { + "post": { + "description": "Полная замена ролей пользователя: удаляет все текущие роли и назначает новые", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "user-roles" + ], + "summary": "Массовое назначение ролей", + "parameters": [ + { + "description": "user_id и список role_ids", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/handlers_user_roles.BulkAssignRolesRequest" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApiResponseBase" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Пользователь не найден", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/users": { + "get": { + "description": "Получение списка пользователей с пагинацией, фильтрацией и подгрузкой связанных данных", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "users" + ], + "summary": "Получение списка пользователей", + "parameters": [ + { + "type": "integer", + "description": "Смещение для пагинации", + "name": "offset", + "in": "query" + }, + { + "type": "integer", + "description": "Количество записей на странице", + "name": "limit", + "in": "query" + }, + { + "type": "boolean", + "description": "Фильтр по блокировке", + "name": "is_blocked", + "in": "query" + }, + { + "type": "boolean", + "description": "Фильтр по увольнению", + "name": "is_fired", + "in": "query" + }, + { + "type": "integer", + "description": "Фильтр по отделу", + "name": "department_id", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApiResponseBase" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "put": { + "description": "Обновление данных существующего пользователя", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "users" + ], + "summary": "Обновление пользователя", + "parameters": [ + { + "description": "Данные пользователя", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.UpdateUserReqAdmin" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.User" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Пользователь не найден", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/users/{id}": { + "get": { + "description": "Получение детальной информации о пользователе по его ID с подгрузкой связанных данных", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "users" + ], + "summary": "Получение пользователя по ID", + "parameters": [ + { + "type": "integer", + "description": "ID пользователя", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.User" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Пользователь не найден", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/users/{user_id}/roles": { + "get": { + "description": "Получение списка ролей, назначенных пользователю с указанным ID", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "user-roles" + ], + "summary": "Получение списка ролей пользователя по ID", + "parameters": [ + { + "type": "integer", + "description": "ID пользователя", + "name": "user_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApiResponseBase" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Пользователь не найден", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + } + }, + "definitions": { + "handlers.ErrorResponse": { + "type": "object", + "properties": { + "error_code": { + "description": "Код ошибки", + "type": "integer" + }, + "error_description": { + "description": "Описание ошибки", + "type": "string" + } + } + }, + "handlers_user_roles.AssignUserRoleRequest": { + "type": "object", + "properties": { + "role_id": { + "type": "integer" + }, + "user_id": { + "type": "integer" + } + } + }, + "handlers_user_roles.BulkAssignRolesRequest": { + "type": "object", + "properties": { + "role_ids": { + "type": "array", + "items": { + "type": "integer" + } + }, + "user_id": { + "type": "integer" + } + } + }, + "typescore.Admin": { + "type": "object", + "properties": { + "created_at": { + "description": "Дата создания записи", + "type": "string" + }, + "id": { + "description": "Автоматически заполняемое уникальное поле для большого числа записей", + "type": "integer" + }, + "is_blocked": { + "description": "Заблокирован ли администратор", + "type": "boolean" + }, + "last_ip_login": { + "description": "Последний IP входа", + "type": "string" + }, + "last_login": { + "description": "Дата входа", + "type": "string" + }, + "login": { + "description": "Логин администратора", + "type": "string" + } + } + }, + "typescore.AdminReq": { + "type": "object", + "properties": { + "login": { + "type": "string" + }, + "password": { + "description": "Пароль пользователя", + "type": "string" + } + } + }, + "typescore.ApiResponseBase": { + "type": "object", + "properties": { + "data": { + "description": "данные полученные от api" + }, + "total_amount": { + "type": "number" + }, + "total_count": { + "type": "integer" + } + } + }, + "typescore.Approval": { + "type": "object", + "properties": { + "content": { + "description": "введённые пользователем данные по шаблону", + "type": "string" + }, + "created_at": { + "type": "string" + }, + "department": { + "$ref": "#/definitions/typescore.Department" + }, + "department_id": { + "description": "снимок отдела на момент создания", + "type": "integer" + }, + "files": { + "type": "array", + "items": { + "$ref": "#/definitions/typescore.ApprovalFile" + } + }, + "id": { + "type": "integer" + }, + "initiator": { + "$ref": "#/definitions/typescore.User" + }, + "initiator_id": { + "type": "integer" + }, + "metadata": { + "type": "string" + }, + "revision_at": { + "type": "string" + }, + "revision_by_id": { + "type": "integer" + }, + "revision_comment": { + "type": "string" + }, + "revision_count": { + "type": "integer" + }, + "revoked_at": { + "type": "string" + }, + "revoked_by": { + "$ref": "#/definitions/typescore.User" + }, + "revoked_by_id": { + "type": "integer" + }, + "status": { + "type": "string" + }, + "steps": { + "type": "array", + "items": { + "$ref": "#/definitions/typescore.ApprovalStep" + } + }, + "topic": { + "$ref": "#/definitions/typescore.ApprovalTopic" + }, + "topic_id": { + "type": "integer" + }, + "updated_at": { + "type": "string" + } + } + }, + "typescore.ApprovalFile": { + "type": "object", + "properties": { + "approval_id": { + "type": "integer" + }, + "attached_by_id": { + "type": "integer" + }, + "created_at": { + "type": "string" + }, + "file_base64": { + "type": "string" + }, + "file_name": { + "type": "string" + }, + "id": { + "type": "integer" + }, + "task_id": { + "type": "integer" + } + } + }, + "typescore.ApprovalStep": { + "type": "object", + "properties": { + "acted_at": { + "type": "string" + }, + "approval": { + "$ref": "#/definitions/typescore.Approval" + }, + "approval_id": { + "type": "integer" + }, + "approver": { + "$ref": "#/definitions/typescore.User" + }, + "approver_department_snapshot": { + "type": "string" + }, + "approver_id": { + "type": "integer" + }, + "approver_name_snapshot": { + "type": "string" + }, + "comment": { + "type": "string" + }, + "created_at": { + "type": "string" + }, + "id": { + "type": "integer" + }, + "returned_at": { + "type": "string" + }, + "status": { + "type": "string" + }, + "step_order": { + "type": "integer" + }, + "updated_at": { + "type": "string" + } + } + }, + "typescore.ApprovalTopic": { + "type": "object", + "properties": { + "allow_approver_selection": { + "type": "boolean" + }, + "allow_observer_selection": { + "type": "boolean" + }, + "allows_file": { + "type": "boolean" + }, + "approvalMode": { + "type": "string" + }, + "category": { + "$ref": "#/definitions/typescore.ApprovalTopicCategory" + }, + "category_id": { + "type": "integer" + }, + "code": { + "type": "string" + }, + "created_at": { + "type": "string" + }, + "duration_type": { + "type": "string" + }, + "first_approver_role_code": { + "description": "если задан — первый согласующий выбирается из этой роли", + "type": "string" + }, + "id": { + "type": "integer" + }, + "instructions": { + "type": "string" + }, + "is_active": { + "type": "boolean" + }, + "name": { + "type": "string" + }, + "payment_type": { + "type": "string" + }, + "require_approver_comment": { + "type": "boolean" + }, + "require_observer_selection": { + "type": "boolean" + }, + "requires_file": { + "type": "boolean" + }, + "template": { + "type": "string" + }, + "time_type": { + "type": "string" + }, + "updated_at": { + "type": "string" + } + } + }, + "typescore.ApprovalTopicCategory": { + "type": "object", + "properties": { + "code": { + "description": "otgul, vacation, sick_leave", + "type": "string" + }, + "created_at": { + "type": "string" + }, + "description": { + "type": "string" + }, + "id": { + "type": "integer" + }, + "is_active": { + "type": "boolean" + }, + "name": { + "type": "string" + }, + "topics": { + "type": "array", + "items": { + "$ref": "#/definitions/typescore.ApprovalTopic" + } + }, + "updated_at": { + "type": "string" + } + } + }, + "typescore.ApprovalTopicExecutor": { + "type": "object", + "properties": { + "created_at": { + "type": "string" + }, + "id": { + "type": "integer" + }, + "is_active": { + "type": "boolean" + }, + "require_file": { + "type": "boolean" + }, + "step_order": { + "type": "integer" + }, + "target_system": { + "type": "string" + }, + "task_text": { + "type": "string" + }, + "topic": { + "$ref": "#/definitions/typescore.ApprovalTopic" + }, + "topic_id": { + "type": "integer" + }, + "updated_at": { + "type": "string" + }, + "user": { + "$ref": "#/definitions/typescore.User" + }, + "user_id": { + "type": "integer" + } + } + }, + "typescore.AuthHandlerResponse": { + "type": "object", + "properties": { + "temp_session": { + "description": "Временный токен для 2FA", + "type": "string" + }, + "token": { + "description": "токен аутентификации", + "type": "string" + } + } + }, + "typescore.AuthReqAccount": { + "type": "object", + "properties": { + "access_code": { + "type": "string" + }, + "login": { + "type": "string" + }, + "password": { + "type": "string" + }, + "redirect_uri": { + "type": "string" + }, + "token": { + "type": "string" + } + } + }, + "typescore.Department": { + "type": "object", + "properties": { + "code": { + "description": "finance, hr, it", + "type": "string" + }, + "created_at": { + "type": "string" + }, + "description": { + "type": "string" + }, + "id": { + "type": "integer" + }, + "is_active": { + "type": "boolean" + }, + "name": { + "type": "string" + }, + "updated_at": { + "type": "string" + } + } + }, + "typescore.Permission": { + "type": "object", + "properties": { + "action": { + "type": "string" + }, + "created_at": { + "type": "string" + }, + "id": { + "type": "integer" + }, + "role": { + "$ref": "#/definitions/typescore.Role" + }, + "role_id": { + "type": "integer" + }, + "topic": { + "$ref": "#/definitions/typescore.ApprovalTopic" + }, + "topic_category": { + "$ref": "#/definitions/typescore.ApprovalTopicCategory" + }, + "topic_category_id": { + "type": "integer" + }, + "topic_id": { + "type": "integer" + }, + "updated_at": { + "type": "string" + } + } + }, + "typescore.Role": { + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "created_at": { + "type": "string" + }, + "description": { + "type": "string" + }, + "id": { + "type": "integer" + }, + "is_approver": { + "type": "boolean" + }, + "is_default": { + "type": "boolean" + }, + "is_director": { + "type": "boolean" + }, + "is_executor": { + "type": "boolean" + }, + "is_observer": { + "type": "boolean" + }, + "name": { + "type": "string" + }, + "permissions": { + "type": "array", + "items": { + "$ref": "#/definitions/typescore.Permission" + } + }, + "updated_at": { + "type": "string" + } + } + }, + "typescore.UpdateUserReqAdmin": { + "type": "object", + "properties": { + "department_id": { + "description": "Логин пользователя", + "type": "integer" + }, + "id": { + "type": "integer" + }, + "is_blocked": { + "description": "Заблокирован ли пользователь", + "type": "boolean" + }, + "is_fired": { + "description": "Заблокирован ли пользователь", + "type": "boolean" + } + } + }, + "typescore.User": { + "type": "object", + "properties": { + "blocked_at": { + "type": "string" + }, + "created_at": { + "type": "string" + }, + "department": { + "$ref": "#/definitions/typescore.Department" + }, + "department_id": { + "type": "integer" + }, + "full_name": { + "type": "string" + }, + "id": { + "type": "integer" + }, + "is_blocked": { + "type": "boolean" + }, + "is_fired": { + "type": "boolean" + }, + "language_code": { + "description": "FirstName *string ` + "`" + `gorm:\"type:text;not null;column:first_name\" json:\"first_name\" db:\"first_name\" mapstructure:\"first_name\"` + "`" + `\nLastName *string ` + "`" + `gorm:\"type:text;not null;column:last_name\" json:\"last_name\" db:\"last_name\" mapstructure:\"last_name\"` + "`" + `\nPatronymic *string ` + "`" + `gorm:\"type:text;column:patronymic\" json:\"patronymic,omitempty\" db:\"patronymic\" mapstructure:\"patronymic\"` + "`" + `", + "type": "string" + }, + "last_login": { + "type": "string" + }, + "telegram_id": { + "type": "integer" + }, + "updated_at": { + "type": "string" + }, + "user_roles": { + "type": "array", + "items": { + "$ref": "#/definitions/typescore.UserRole" + } + }, + "username": { + "type": "string" + } + } + }, + "typescore.UserHierarchy": { + "type": "object", + "properties": { + "approver": { + "$ref": "#/definitions/typescore.User" + }, + "approver_id": { + "type": "integer" + }, + "created_at": { + "type": "string" + }, + "department": { + "$ref": "#/definitions/typescore.Department" + }, + "department_id": { + "type": "integer" + }, + "id": { + "type": "integer" + }, + "priority": { + "type": "integer" + }, + "subordinate": { + "$ref": "#/definitions/typescore.User" + }, + "subordinate_id": { + "type": "integer" + }, + "topic_category_id": { + "type": "integer" + }, + "topic_id": { + "type": "integer" + }, + "updated_at": { + "type": "string" + } + } + }, + "typescore.UserRole": { + "type": "object", + "properties": { + "created_at": { + "type": "string" + }, + "id": { + "description": "Автоматически заполняемое уникальное поле для большого числа записей", + "type": "integer" + }, + "role": { + "description": "← добавить gorm:\"-\"", + "allOf": [ + { + "$ref": "#/definitions/typescore.Role" + } + ] + }, + "role_id": { + "type": "integer" + }, + "updated_at": { + "type": "string" + }, + "user": { + "description": "← добавить gorm:\"-\"", + "allOf": [ + { + "$ref": "#/definitions/typescore.User" + } + ] + }, + "user_id": { + "type": "integer" + } + } + } + }, + "securityDefinitions": { + "ApiKeyAuth": { + "type": "apiKey", + "name": "ApiKey", + "in": "header" + }, + "BearerAuth": { + "type": "apiKey", + "name": "Authorization", + "in": "header" + }, + "DeviceID": { + "type": "apiKey", + "name": "x-device-id", + "in": "header" + }, + "Timestamp": { + "type": "apiKey", + "name": "X-Timestamp", + "in": "header" + } + } +}` + +// SwaggerInfo holds exported Swagger Info so clients can modify it +var SwaggerInfo = &swag.Spec{ + Version: "0.1", + Host: "localhost:8080", + BasePath: "/", + Schemes: []string{}, + Title: "RusPet Admin API", + Description: "API админ-панели для системы согласований\n\n## Возможности\n- Управление отделами, ролями и пользователями\n- Настройка тем и категорий согласований\n- Управление иерархией согласований\n- Назначение исполнителей и прав\n- Просмотр заявок и шагов согласования\n\n## Аутентификация\nВсе защищённые эндпоинты требуют:\n- `Authorization: Bearer ` — JWT токен администратора\n- `ApiKey: ` — HMAC подпись для верификации клиента\n- `X-Timestamp: ` — Unix timestamp (не старше 3 минут)\n- `x-device-id: ` — ID устройства", + InfoInstanceName: "swagger", + SwaggerTemplate: docTemplate, + LeftDelim: "{{", + RightDelim: "}}", +} + +func init() { + swag.Register(SwaggerInfo.InstanceName(), SwaggerInfo) +} diff --git a/service/rest_admin_service/docs/swagger.json b/service/rest_admin_service/docs/swagger.json new file mode 100644 index 0000000..7366983 --- /dev/null +++ b/service/rest_admin_service/docs/swagger.json @@ -0,0 +1,3966 @@ +{ + "swagger": "2.0", + "info": { + "description": "API админ-панели для системы согласований\n\n## Возможности\n- Управление отделами, ролями и пользователями\n- Настройка тем и категорий согласований\n- Управление иерархией согласований\n- Назначение исполнителей и прав\n- Просмотр заявок и шагов согласования\n\n## Аутентификация\nВсе защищённые эндпоинты требуют:\n- `Authorization: Bearer \u003cJWT_TOKEN\u003e` — JWT токен администратора\n- `ApiKey: \u003cHMAC_SIGNATURE\u003e` — HMAC подпись для верификации клиента\n- `X-Timestamp: \u003cUNIX_TIMESTAMP\u003e` — Unix timestamp (не старше 3 минут)\n- `x-device-id: \u003cDEVICE_ID\u003e` — ID устройства", + "title": "RusPet Admin API", + "contact": {}, + "version": "0.1" + }, + "host": "localhost:8080", + "basePath": "/", + "paths": { + "/api/admin": { + "get": { + "description": "Получение списка администраторов", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "admin" + ], + "summary": "Получение списка администраторов", + "parameters": [ + { + "type": "integer", + "description": "Смещение для пагинации", + "name": "offset", + "in": "query" + }, + { + "type": "integer", + "description": "Количество записей на странице", + "name": "limit", + "in": "query" + }, + { + "type": "boolean", + "description": "Фильтр по активности", + "name": "is_active", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.Admin" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "post": { + "description": "Создание администратора", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "admin" + ], + "summary": "Создание администратора", + "parameters": [ + { + "description": "Запрос", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.AdminReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/typescore.Admin" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "delete": { + "description": "Удаление администратора", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "admin" + ], + "summary": "Удаление администратора", + "parameters": [ + { + "description": "Запрос", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.AdminReq" + } + } + ], + "responses": { + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/admin/profile": { + "get": { + "description": "Получение профиля пользователя", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "profile" + ], + "summary": "Получение профиля пользователя", + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/typescore.Admin" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "put": { + "description": "Обновление профиля пользователя", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "profile" + ], + "summary": "Обновление профиля пользователя", + "parameters": [ + { + "description": "Запрос", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.AdminReq" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/typescore.Admin" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/approval-steps": { + "get": { + "description": "Получение списка шагов согласования с пагинацией и фильтрацией", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "approval-steps" + ], + "summary": "Получение списка шагов", + "parameters": [ + { + "type": "integer", + "description": "Смещение для пагинации", + "name": "offset", + "in": "query" + }, + { + "type": "integer", + "description": "Количество записей на странице", + "name": "limit", + "in": "query" + }, + { + "type": "integer", + "description": "Фильтр по заявке", + "name": "approval_id", + "in": "query" + }, + { + "type": "integer", + "description": "Фильтр по согласующему", + "name": "approver_id", + "in": "query" + }, + { + "type": "string", + "description": "Фильтр по статусу (pending, waiting, approved, rejected, cancelled_any_of)", + "name": "status", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApiResponseBase" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "put": { + "description": "Обновление данных шага согласования (статус, комментарий)", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "approval-steps" + ], + "summary": "Обновление шага", + "parameters": [ + { + "description": "Данные шага", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.ApprovalStep" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApprovalStep" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Шаг не найден", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "post": { + "description": "Создание нового шага согласования для заявки", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "approval-steps" + ], + "summary": "Создание шага", + "parameters": [ + { + "description": "Данные шага", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.ApprovalStep" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApprovalStep" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Заявка или согласующий не найдены", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "delete": { + "description": "Удаление шага согласования (только для заявок в статусе pending)", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "approval-steps" + ], + "summary": "Удаление шага", + "parameters": [ + { + "description": "ID шага для удаления", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.ApprovalStep" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "type": "boolean" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "403": { + "description": "Нельзя удалить шаг завершённой заявки", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Шаг не найден", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/approval-steps/by-approval/{approval_id}": { + "get": { + "description": "Получение списка всех шагов согласования для указанной заявки, отсортированных по step_order", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "approval-steps" + ], + "summary": "Получение шагов по заявке", + "parameters": [ + { + "type": "integer", + "description": "ID заявки", + "name": "approval_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApiResponseBase" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Заявка не найдена", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/approval-steps/{id}": { + "get": { + "description": "Получение детальной информации о шаге согласования по его ID", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "approval-steps" + ], + "summary": "Получение шага по ID", + "parameters": [ + { + "type": "integer", + "description": "ID шага", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApprovalStep" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Шаг не найден", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/approvals": { + "get": { + "description": "Получение списка заявок с пагинацией и фильтрацией", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "approvals" + ], + "summary": "Получение списка заявок", + "parameters": [ + { + "type": "integer", + "description": "Смещение для пагинации", + "name": "offset", + "in": "query" + }, + { + "type": "integer", + "description": "Количество записей на странице", + "name": "limit", + "in": "query" + }, + { + "type": "string", + "description": "Фильтр по статусу (pending, approved, rejected, revoked, revision)", + "name": "status", + "in": "query" + }, + { + "type": "integer", + "description": "Фильтр по инициатору", + "name": "initiator_id", + "in": "query" + }, + { + "type": "integer", + "description": "Фильтр по теме", + "name": "topic_id", + "in": "query" + }, + { + "type": "integer", + "description": "Фильтр по отделу", + "name": "department_id", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApiResponseBase" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "put": { + "description": "Обновление данных заявки (статус, комментарии и т.д.)", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "approvals" + ], + "summary": "Обновление заявки", + "parameters": [ + { + "description": "Данные заявки", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.Approval" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.Approval" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Заявка не найдена", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "delete": { + "description": "Удаление заявки (только для черновиков)", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "approvals" + ], + "summary": "Удаление заявки", + "parameters": [ + { + "description": "ID заявки для удаления", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.Approval" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "type": "boolean" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "403": { + "description": "Нельзя удалить не-черновую заявку", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Заявка не найдена", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/approvals/report": { + "get": { + "description": "Получение списка заявок для отчёта с учётом периода и доступа пользователя", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "approvals" + ], + "summary": "Получение заявок для отчёта", + "parameters": [ + { + "type": "integer", + "description": "ID пользователя (если не указан - все заявки)", + "name": "user_id", + "in": "query" + }, + { + "type": "string", + "description": "Начальная дата (YYYY-MM-DD)", + "name": "date_from", + "in": "query" + }, + { + "type": "string", + "description": "Конечная дата (YYYY-MM-DD)", + "name": "date_to", + "in": "query" + }, + { + "type": "boolean", + "description": "Полный доступ (игнорировать фильтрацию по пользователю)", + "name": "all_access", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApiResponseBase" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/approvals/{id}": { + "get": { + "description": "Получение детальной информации о заявке по её ID со всеми связанными данными", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "approvals" + ], + "summary": "Получение заявки по ID", + "parameters": [ + { + "type": "integer", + "description": "ID заявки", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.Approval" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Заявка не найдена", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/auth/login": { + "post": { + "description": "авторизация с помощью связки логин-пароль", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "auth" + ], + "summary": "авторизация с помощью связки логин-пароль", + "parameters": [ + { + "description": "Запрос", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.AuthReqAccount" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/typescore.AuthHandlerResponse" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/auth/token": { + "post": { + "description": "Авторизация при помощи JWT-токена", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "auth" + ], + "summary": "Авторизация при помощи JWT-токена", + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/typescore.AuthHandlerResponse" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/categories": { + "get": { + "description": "Получение списка категорий тем с пагинацией и фильтрацией", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "categories" + ], + "summary": "Получение списка категорий тем", + "parameters": [ + { + "type": "integer", + "description": "Смещение для пагинации", + "name": "offset", + "in": "query" + }, + { + "type": "integer", + "description": "Количество записей на странице", + "name": "limit", + "in": "query" + }, + { + "type": "boolean", + "description": "Фильтр по активности", + "name": "is_active", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApiResponseBase" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "put": { + "description": "Обновление данных существующей категории", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "categories" + ], + "summary": "Обновление категории", + "parameters": [ + { + "description": "Данные категории", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.ApprovalTopicCategory" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApprovalTopicCategory" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Категория не найдена", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "post": { + "description": "Создание новой категории тем", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "categories" + ], + "summary": "Создание категории тем", + "parameters": [ + { + "description": "Данные категории", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.ApprovalTopicCategory" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApprovalTopicCategory" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "delete": { + "description": "Удаление категории по ID", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "categories" + ], + "summary": "Удаление категории", + "parameters": [ + { + "description": "ID категории для удаления", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.ApprovalTopicCategory" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "type": "boolean" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Категория не найдена", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "409": { + "description": "Категория содержит темы", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/categories/{id}": { + "get": { + "description": "Получение детальной информации о категории по её ID", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "categories" + ], + "summary": "Получение категории по ID", + "parameters": [ + { + "type": "integer", + "description": "ID категории", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApprovalTopicCategory" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Категория не найдена", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/departments": { + "get": { + "description": "Получение списка отделов с пагинацией и фильтрацией", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "departments" + ], + "summary": "Получение списка отделов", + "parameters": [ + { + "type": "integer", + "description": "Смещение для пагинации", + "name": "offset", + "in": "query" + }, + { + "type": "integer", + "description": "Количество записей на странице", + "name": "limit", + "in": "query" + }, + { + "type": "boolean", + "description": "Фильтр по активности", + "name": "is_active", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApiResponseBase" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "put": { + "description": "Обновление данных существующего отдела", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "departments" + ], + "summary": "Обновление отдела", + "parameters": [ + { + "description": "Данные отдела", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.Department" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.Department" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Отдел не найден", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "post": { + "description": "Создание нового отдела", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "departments" + ], + "summary": "Создание отдела", + "parameters": [ + { + "description": "Данные отдела", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.Department" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.Department" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "delete": { + "description": "Удаление отдела по ID", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "departments" + ], + "summary": "Удаление отдела", + "parameters": [ + { + "description": "ID отдела для удаления", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.Department" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "type": "boolean" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Отдел не найден", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/departments/{id}": { + "get": { + "description": "Получение детальной информации об отделе по его ID", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "departments" + ], + "summary": "Получение отдела по ID", + "parameters": [ + { + "type": "integer", + "description": "ID отдела", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.Department" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Отдел не найден", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/hierarchies": { + "get": { + "description": "Получение списка связей подчинённый-согласующий с пагинацией и фильтрацией", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "hierarchies" + ], + "summary": "Получение списка записей иерархии", + "parameters": [ + { + "type": "integer", + "description": "Смещение для пагинации", + "name": "offset", + "in": "query" + }, + { + "type": "integer", + "description": "Количество записей на странице", + "name": "limit", + "in": "query" + }, + { + "type": "integer", + "description": "Фильтр по подчинённому", + "name": "subordinate_id", + "in": "query" + }, + { + "type": "integer", + "description": "Фильтр по согласующему", + "name": "approver_id", + "in": "query" + }, + { + "type": "integer", + "description": "Фильтр по отделу", + "name": "department_id", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApiResponseBase" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "put": { + "description": "Обновление данных существующей записи иерархии", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "hierarchies" + ], + "summary": "Обновление записи иерархии", + "parameters": [ + { + "description": "Данные иерархии", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.UserHierarchy" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.UserHierarchy" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Запись не найдена", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "post": { + "description": "Создание новой связи подчинённый-согласующий", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "hierarchies" + ], + "summary": "Создание записи иерархии", + "parameters": [ + { + "description": "Данные иерархии", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.UserHierarchy" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.UserHierarchy" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "409": { + "description": "Такая связь уже существует", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "delete": { + "description": "Удаление связи подчинённый-согласующий по ID", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "hierarchies" + ], + "summary": "Удаление записи иерархии", + "parameters": [ + { + "description": "ID записи для удаления", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.UserHierarchy" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "type": "boolean" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Запись не найдена", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/hierarchies/{id}": { + "get": { + "description": "Получение детальной информации о записи иерархии по её ID", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "hierarchies" + ], + "summary": "Получение записи иерархии по ID", + "parameters": [ + { + "type": "integer", + "description": "ID записи", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.UserHierarchy" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Запись не найдена", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/permissions": { + "get": { + "description": "Получение списка прав ролей с пагинацией и фильтрацией", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "permissions" + ], + "summary": "Получение списка прав", + "parameters": [ + { + "type": "integer", + "description": "Смещение для пагинации", + "name": "offset", + "in": "query" + }, + { + "type": "integer", + "description": "Количество записей на странице", + "name": "limit", + "in": "query" + }, + { + "type": "integer", + "description": "Фильтр по роли", + "name": "role_id", + "in": "query" + }, + { + "type": "string", + "description": "Фильтр по действию (create, read, update, delete, approve, revoke)", + "name": "action", + "in": "query" + }, + { + "type": "integer", + "description": "Фильтр по категории тем", + "name": "topic_category_id", + "in": "query" + }, + { + "type": "integer", + "description": "Фильтр по теме", + "name": "topic_id", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApiResponseBase" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "put": { + "description": "Обновление данных существующего права", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "permissions" + ], + "summary": "Обновление права", + "parameters": [ + { + "description": "Данные права", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.Permission" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.Permission" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Право не найдено", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "post": { + "description": "Назначение права на действие для роли", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "permissions" + ], + "summary": "Создание права", + "parameters": [ + { + "description": "Данные права", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.Permission" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.Permission" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Роль, категория или тема не найдены", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "409": { + "description": "Такое право уже существует", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "delete": { + "description": "Удаление права по ID", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "permissions" + ], + "summary": "Удаление права", + "parameters": [ + { + "description": "ID права для удаления", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.Permission" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "type": "boolean" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Право не найдено", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/permissions/by-role/{role_id}": { + "get": { + "description": "Получение списка всех прав для указанной роли", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "permissions" + ], + "summary": "Получение прав по роли", + "parameters": [ + { + "type": "integer", + "description": "ID роли", + "name": "role_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApiResponseBase" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Роль не найдена", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/permissions/{id}": { + "get": { + "description": "Получение детальной информации о праве по его ID", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "permissions" + ], + "summary": "Получение права по ID", + "parameters": [ + { + "type": "integer", + "description": "ID права", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.Permission" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Право не найдено", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/roles": { + "get": { + "description": "Получение списка ролей с пагинацией и фильтрацией", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "roles" + ], + "summary": "Получение списка ролей", + "parameters": [ + { + "type": "integer", + "description": "Смещение для пагинации", + "name": "offset", + "in": "query" + }, + { + "type": "integer", + "description": "Количество записей на странице", + "name": "limit", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApiResponseBase" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "put": { + "description": "Обновление данных существующей роли", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "roles" + ], + "summary": "Обновление роли", + "parameters": [ + { + "description": "Данные роли", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.Role" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.Role" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Роль не найдена", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "post": { + "description": "Создание новой роли", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "roles" + ], + "summary": "Создание роли", + "parameters": [ + { + "description": "Данные роли", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.Role" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.Role" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "delete": { + "description": "Удаление роли по ID", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "roles" + ], + "summary": "Удаление роли", + "parameters": [ + { + "description": "ID роли для удаления", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.Role" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "type": "boolean" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Роль не найдена", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/roles/{id}": { + "get": { + "description": "Получение детальной информации о роли по её ID", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "roles" + ], + "summary": "Получение роли по ID", + "parameters": [ + { + "type": "integer", + "description": "ID роли", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.Role" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Роль не найдена", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/topic-executors": { + "get": { + "description": "Получение списка исполнителей с пагинацией и фильтрацией", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "topic-executors" + ], + "summary": "Получение списка исполнителей тем", + "parameters": [ + { + "type": "integer", + "description": "Смещение для пагинации", + "name": "offset", + "in": "query" + }, + { + "type": "integer", + "description": "Количество записей на странице", + "name": "limit", + "in": "query" + }, + { + "type": "integer", + "description": "Фильтр по теме", + "name": "topic_id", + "in": "query" + }, + { + "type": "integer", + "description": "Фильтр по пользователю", + "name": "user_id", + "in": "query" + }, + { + "type": "boolean", + "description": "Фильтр по активности", + "name": "is_active", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApiResponseBase" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "put": { + "description": "Обновление данных исполнителя для темы", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "topic-executors" + ], + "summary": "Обновление исполнителя", + "parameters": [ + { + "description": "Данные исполнителя", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.ApprovalTopicExecutor" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApprovalTopicExecutor" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Исполнитель не найден", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "post": { + "description": "Назначение исполнителя для конкретной темы согласования", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "topic-executors" + ], + "summary": "Создание исполнителя", + "parameters": [ + { + "description": "Данные исполнителя", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.ApprovalTopicExecutor" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApprovalTopicExecutor" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Тема или пользователь не найдены", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "409": { + "description": "Такой исполнитель уже назначен на этот шаг", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "delete": { + "description": "Удаление исполнителя из темы по ID", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "topic-executors" + ], + "summary": "Удаление исполнителя", + "parameters": [ + { + "description": "ID записи для удаления", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.ApprovalTopicExecutor" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "type": "boolean" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Запись не найдена", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/topic-executors/by-topic/{topic_id}": { + "get": { + "description": "Получение списка всех активных исполнителей для указанной темы, отсортированных по step_order", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "topic-executors" + ], + "summary": "Получение исполнителей по теме", + "parameters": [ + { + "type": "integer", + "description": "ID темы", + "name": "topic_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApiResponseBase" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Тема не найдена", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/topic-executors/{id}": { + "get": { + "description": "Получение детальной информации об исполнителе по его ID", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "topic-executors" + ], + "summary": "Получение исполнителя по ID", + "parameters": [ + { + "type": "integer", + "description": "ID исполнителя", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApprovalTopicExecutor" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Исполнитель не найден", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/topics": { + "get": { + "description": "Получение списка тем с пагинацией и фильтрацией", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "topics" + ], + "summary": "Получение списка тем", + "parameters": [ + { + "type": "integer", + "description": "Смещение для пагинации", + "name": "offset", + "in": "query" + }, + { + "type": "integer", + "description": "Количество записей на странице", + "name": "limit", + "in": "query" + }, + { + "type": "integer", + "description": "Фильтр по категории", + "name": "category_id", + "in": "query" + }, + { + "type": "boolean", + "description": "Фильтр по активности", + "name": "is_active", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApiResponseBase" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "put": { + "description": "Обновление данных существующей темы", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "topics" + ], + "summary": "Обновление темы", + "parameters": [ + { + "description": "Данные темы", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.ApprovalTopic" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApprovalTopic" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Тема не найдена", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "post": { + "description": "Создание новой темы согласования", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "topics" + ], + "summary": "Создание темы", + "parameters": [ + { + "description": "Данные темы", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.ApprovalTopic" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApprovalTopic" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "delete": { + "description": "Удаление темы по ID", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "topics" + ], + "summary": "Удаление темы", + "parameters": [ + { + "description": "ID темы для удаления", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.ApprovalTopic" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "type": "boolean" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Тема не найдена", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "409": { + "description": "Тема содержит заявки", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/topics/{id}": { + "get": { + "description": "Получение детальной информации о теме по её ID", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "topics" + ], + "summary": "Получение темы по ID", + "parameters": [ + { + "type": "integer", + "description": "ID темы", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApprovalTopic" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Тема не найдена", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/user-roles": { + "get": { + "description": "Получение списка ролей, назначенных конкретному пользователю", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "user-roles" + ], + "summary": "Получение списка ролей пользователя", + "parameters": [ + { + "type": "integer", + "description": "ID пользователя", + "name": "user_id", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApiResponseBase" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "post": { + "description": "Назначение роли пользователю (создание связи user_id + role_id)", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "user-roles" + ], + "summary": "Назначение роли пользователю", + "parameters": [ + { + "description": "user_id и role_id", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/handlers_user_roles.AssignUserRoleRequest" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.UserRole" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Пользователь или роль не найдены", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "409": { + "description": "Роль уже назначена", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "delete": { + "description": "Удаление связи user_id + role_id по ID записи", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "user-roles" + ], + "summary": "Удаление роли у пользователя", + "parameters": [ + { + "description": "ID записи для удаления", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.UserRole" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "type": "boolean" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Запись не найдена", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/user-roles/bulk": { + "post": { + "description": "Полная замена ролей пользователя: удаляет все текущие роли и назначает новые", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "user-roles" + ], + "summary": "Массовое назначение ролей", + "parameters": [ + { + "description": "user_id и список role_ids", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/handlers_user_roles.BulkAssignRolesRequest" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApiResponseBase" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Пользователь не найден", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/users": { + "get": { + "description": "Получение списка пользователей с пагинацией, фильтрацией и подгрузкой связанных данных", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "users" + ], + "summary": "Получение списка пользователей", + "parameters": [ + { + "type": "integer", + "description": "Смещение для пагинации", + "name": "offset", + "in": "query" + }, + { + "type": "integer", + "description": "Количество записей на странице", + "name": "limit", + "in": "query" + }, + { + "type": "boolean", + "description": "Фильтр по блокировке", + "name": "is_blocked", + "in": "query" + }, + { + "type": "boolean", + "description": "Фильтр по увольнению", + "name": "is_fired", + "in": "query" + }, + { + "type": "integer", + "description": "Фильтр по отделу", + "name": "department_id", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApiResponseBase" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + }, + "put": { + "description": "Обновление данных существующего пользователя", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "users" + ], + "summary": "Обновление пользователя", + "parameters": [ + { + "description": "Данные пользователя", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/typescore.UpdateUserReqAdmin" + } + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.User" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Пользователь не найден", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/users/{id}": { + "get": { + "description": "Получение детальной информации о пользователе по его ID с подгрузкой связанных данных", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "users" + ], + "summary": "Получение пользователя по ID", + "parameters": [ + { + "type": "integer", + "description": "ID пользователя", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.User" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Пользователь не найден", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + }, + "/api/users/{user_id}/roles": { + "get": { + "description": "Получение списка ролей, назначенных пользователю с указанным ID", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "user-roles" + ], + "summary": "Получение списка ролей пользователя по ID", + "parameters": [ + { + "type": "integer", + "description": "ID пользователя", + "name": "user_id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Успех", + "schema": { + "$ref": "#/definitions/typescore.ApiResponseBase" + } + }, + "400": { + "description": "Некорректный запрос", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "404": { + "description": "Пользователь не найден", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + }, + "500": { + "description": "Ошибка сервера", + "schema": { + "$ref": "#/definitions/handlers.ErrorResponse" + } + } + } + } + } + }, + "definitions": { + "handlers.ErrorResponse": { + "type": "object", + "properties": { + "error_code": { + "description": "Код ошибки", + "type": "integer" + }, + "error_description": { + "description": "Описание ошибки", + "type": "string" + } + } + }, + "handlers_user_roles.AssignUserRoleRequest": { + "type": "object", + "properties": { + "role_id": { + "type": "integer" + }, + "user_id": { + "type": "integer" + } + } + }, + "handlers_user_roles.BulkAssignRolesRequest": { + "type": "object", + "properties": { + "role_ids": { + "type": "array", + "items": { + "type": "integer" + } + }, + "user_id": { + "type": "integer" + } + } + }, + "typescore.Admin": { + "type": "object", + "properties": { + "created_at": { + "description": "Дата создания записи", + "type": "string" + }, + "id": { + "description": "Автоматически заполняемое уникальное поле для большого числа записей", + "type": "integer" + }, + "is_blocked": { + "description": "Заблокирован ли администратор", + "type": "boolean" + }, + "last_ip_login": { + "description": "Последний IP входа", + "type": "string" + }, + "last_login": { + "description": "Дата входа", + "type": "string" + }, + "login": { + "description": "Логин администратора", + "type": "string" + } + } + }, + "typescore.AdminReq": { + "type": "object", + "properties": { + "login": { + "type": "string" + }, + "password": { + "description": "Пароль пользователя", + "type": "string" + } + } + }, + "typescore.ApiResponseBase": { + "type": "object", + "properties": { + "data": { + "description": "данные полученные от api" + }, + "total_amount": { + "type": "number" + }, + "total_count": { + "type": "integer" + } + } + }, + "typescore.Approval": { + "type": "object", + "properties": { + "content": { + "description": "введённые пользователем данные по шаблону", + "type": "string" + }, + "created_at": { + "type": "string" + }, + "department": { + "$ref": "#/definitions/typescore.Department" + }, + "department_id": { + "description": "снимок отдела на момент создания", + "type": "integer" + }, + "files": { + "type": "array", + "items": { + "$ref": "#/definitions/typescore.ApprovalFile" + } + }, + "id": { + "type": "integer" + }, + "initiator": { + "$ref": "#/definitions/typescore.User" + }, + "initiator_id": { + "type": "integer" + }, + "metadata": { + "type": "string" + }, + "revision_at": { + "type": "string" + }, + "revision_by_id": { + "type": "integer" + }, + "revision_comment": { + "type": "string" + }, + "revision_count": { + "type": "integer" + }, + "revoked_at": { + "type": "string" + }, + "revoked_by": { + "$ref": "#/definitions/typescore.User" + }, + "revoked_by_id": { + "type": "integer" + }, + "status": { + "type": "string" + }, + "steps": { + "type": "array", + "items": { + "$ref": "#/definitions/typescore.ApprovalStep" + } + }, + "topic": { + "$ref": "#/definitions/typescore.ApprovalTopic" + }, + "topic_id": { + "type": "integer" + }, + "updated_at": { + "type": "string" + } + } + }, + "typescore.ApprovalFile": { + "type": "object", + "properties": { + "approval_id": { + "type": "integer" + }, + "attached_by_id": { + "type": "integer" + }, + "created_at": { + "type": "string" + }, + "file_base64": { + "type": "string" + }, + "file_name": { + "type": "string" + }, + "id": { + "type": "integer" + }, + "task_id": { + "type": "integer" + } + } + }, + "typescore.ApprovalStep": { + "type": "object", + "properties": { + "acted_at": { + "type": "string" + }, + "approval": { + "$ref": "#/definitions/typescore.Approval" + }, + "approval_id": { + "type": "integer" + }, + "approver": { + "$ref": "#/definitions/typescore.User" + }, + "approver_department_snapshot": { + "type": "string" + }, + "approver_id": { + "type": "integer" + }, + "approver_name_snapshot": { + "type": "string" + }, + "comment": { + "type": "string" + }, + "created_at": { + "type": "string" + }, + "id": { + "type": "integer" + }, + "returned_at": { + "type": "string" + }, + "status": { + "type": "string" + }, + "step_order": { + "type": "integer" + }, + "updated_at": { + "type": "string" + } + } + }, + "typescore.ApprovalTopic": { + "type": "object", + "properties": { + "allow_approver_selection": { + "type": "boolean" + }, + "allow_observer_selection": { + "type": "boolean" + }, + "allows_file": { + "type": "boolean" + }, + "approvalMode": { + "type": "string" + }, + "category": { + "$ref": "#/definitions/typescore.ApprovalTopicCategory" + }, + "category_id": { + "type": "integer" + }, + "code": { + "type": "string" + }, + "created_at": { + "type": "string" + }, + "duration_type": { + "type": "string" + }, + "first_approver_role_code": { + "description": "если задан — первый согласующий выбирается из этой роли", + "type": "string" + }, + "id": { + "type": "integer" + }, + "instructions": { + "type": "string" + }, + "is_active": { + "type": "boolean" + }, + "name": { + "type": "string" + }, + "payment_type": { + "type": "string" + }, + "require_approver_comment": { + "type": "boolean" + }, + "require_observer_selection": { + "type": "boolean" + }, + "requires_file": { + "type": "boolean" + }, + "template": { + "type": "string" + }, + "time_type": { + "type": "string" + }, + "updated_at": { + "type": "string" + } + } + }, + "typescore.ApprovalTopicCategory": { + "type": "object", + "properties": { + "code": { + "description": "otgul, vacation, sick_leave", + "type": "string" + }, + "created_at": { + "type": "string" + }, + "description": { + "type": "string" + }, + "id": { + "type": "integer" + }, + "is_active": { + "type": "boolean" + }, + "name": { + "type": "string" + }, + "topics": { + "type": "array", + "items": { + "$ref": "#/definitions/typescore.ApprovalTopic" + } + }, + "updated_at": { + "type": "string" + } + } + }, + "typescore.ApprovalTopicExecutor": { + "type": "object", + "properties": { + "created_at": { + "type": "string" + }, + "id": { + "type": "integer" + }, + "is_active": { + "type": "boolean" + }, + "require_file": { + "type": "boolean" + }, + "step_order": { + "type": "integer" + }, + "target_system": { + "type": "string" + }, + "task_text": { + "type": "string" + }, + "topic": { + "$ref": "#/definitions/typescore.ApprovalTopic" + }, + "topic_id": { + "type": "integer" + }, + "updated_at": { + "type": "string" + }, + "user": { + "$ref": "#/definitions/typescore.User" + }, + "user_id": { + "type": "integer" + } + } + }, + "typescore.AuthHandlerResponse": { + "type": "object", + "properties": { + "temp_session": { + "description": "Временный токен для 2FA", + "type": "string" + }, + "token": { + "description": "токен аутентификации", + "type": "string" + } + } + }, + "typescore.AuthReqAccount": { + "type": "object", + "properties": { + "access_code": { + "type": "string" + }, + "login": { + "type": "string" + }, + "password": { + "type": "string" + }, + "redirect_uri": { + "type": "string" + }, + "token": { + "type": "string" + } + } + }, + "typescore.Department": { + "type": "object", + "properties": { + "code": { + "description": "finance, hr, it", + "type": "string" + }, + "created_at": { + "type": "string" + }, + "description": { + "type": "string" + }, + "id": { + "type": "integer" + }, + "is_active": { + "type": "boolean" + }, + "name": { + "type": "string" + }, + "updated_at": { + "type": "string" + } + } + }, + "typescore.Permission": { + "type": "object", + "properties": { + "action": { + "type": "string" + }, + "created_at": { + "type": "string" + }, + "id": { + "type": "integer" + }, + "role": { + "$ref": "#/definitions/typescore.Role" + }, + "role_id": { + "type": "integer" + }, + "topic": { + "$ref": "#/definitions/typescore.ApprovalTopic" + }, + "topic_category": { + "$ref": "#/definitions/typescore.ApprovalTopicCategory" + }, + "topic_category_id": { + "type": "integer" + }, + "topic_id": { + "type": "integer" + }, + "updated_at": { + "type": "string" + } + } + }, + "typescore.Role": { + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "created_at": { + "type": "string" + }, + "description": { + "type": "string" + }, + "id": { + "type": "integer" + }, + "is_approver": { + "type": "boolean" + }, + "is_default": { + "type": "boolean" + }, + "is_director": { + "type": "boolean" + }, + "is_executor": { + "type": "boolean" + }, + "is_observer": { + "type": "boolean" + }, + "name": { + "type": "string" + }, + "permissions": { + "type": "array", + "items": { + "$ref": "#/definitions/typescore.Permission" + } + }, + "updated_at": { + "type": "string" + } + } + }, + "typescore.UpdateUserReqAdmin": { + "type": "object", + "properties": { + "department_id": { + "description": "Логин пользователя", + "type": "integer" + }, + "id": { + "type": "integer" + }, + "is_blocked": { + "description": "Заблокирован ли пользователь", + "type": "boolean" + }, + "is_fired": { + "description": "Заблокирован ли пользователь", + "type": "boolean" + } + } + }, + "typescore.User": { + "type": "object", + "properties": { + "blocked_at": { + "type": "string" + }, + "created_at": { + "type": "string" + }, + "department": { + "$ref": "#/definitions/typescore.Department" + }, + "department_id": { + "type": "integer" + }, + "full_name": { + "type": "string" + }, + "id": { + "type": "integer" + }, + "is_blocked": { + "type": "boolean" + }, + "is_fired": { + "type": "boolean" + }, + "language_code": { + "description": "FirstName *string `gorm:\"type:text;not null;column:first_name\" json:\"first_name\" db:\"first_name\" mapstructure:\"first_name\"`\nLastName *string `gorm:\"type:text;not null;column:last_name\" json:\"last_name\" db:\"last_name\" mapstructure:\"last_name\"`\nPatronymic *string `gorm:\"type:text;column:patronymic\" json:\"patronymic,omitempty\" db:\"patronymic\" mapstructure:\"patronymic\"`", + "type": "string" + }, + "last_login": { + "type": "string" + }, + "telegram_id": { + "type": "integer" + }, + "updated_at": { + "type": "string" + }, + "user_roles": { + "type": "array", + "items": { + "$ref": "#/definitions/typescore.UserRole" + } + }, + "username": { + "type": "string" + } + } + }, + "typescore.UserHierarchy": { + "type": "object", + "properties": { + "approver": { + "$ref": "#/definitions/typescore.User" + }, + "approver_id": { + "type": "integer" + }, + "created_at": { + "type": "string" + }, + "department": { + "$ref": "#/definitions/typescore.Department" + }, + "department_id": { + "type": "integer" + }, + "id": { + "type": "integer" + }, + "priority": { + "type": "integer" + }, + "subordinate": { + "$ref": "#/definitions/typescore.User" + }, + "subordinate_id": { + "type": "integer" + }, + "topic_category_id": { + "type": "integer" + }, + "topic_id": { + "type": "integer" + }, + "updated_at": { + "type": "string" + } + } + }, + "typescore.UserRole": { + "type": "object", + "properties": { + "created_at": { + "type": "string" + }, + "id": { + "description": "Автоматически заполняемое уникальное поле для большого числа записей", + "type": "integer" + }, + "role": { + "description": "← добавить gorm:\"-\"", + "allOf": [ + { + "$ref": "#/definitions/typescore.Role" + } + ] + }, + "role_id": { + "type": "integer" + }, + "updated_at": { + "type": "string" + }, + "user": { + "description": "← добавить gorm:\"-\"", + "allOf": [ + { + "$ref": "#/definitions/typescore.User" + } + ] + }, + "user_id": { + "type": "integer" + } + } + } + }, + "securityDefinitions": { + "ApiKeyAuth": { + "type": "apiKey", + "name": "ApiKey", + "in": "header" + }, + "BearerAuth": { + "type": "apiKey", + "name": "Authorization", + "in": "header" + }, + "DeviceID": { + "type": "apiKey", + "name": "x-device-id", + "in": "header" + }, + "Timestamp": { + "type": "apiKey", + "name": "X-Timestamp", + "in": "header" + } + } +} \ No newline at end of file diff --git a/service/rest_admin_service/docs/swagger.yaml b/service/rest_admin_service/docs/swagger.yaml new file mode 100644 index 0000000..048a2fd --- /dev/null +++ b/service/rest_admin_service/docs/swagger.yaml @@ -0,0 +1,2645 @@ +basePath: / +definitions: + handlers.ErrorResponse: + properties: + error_code: + description: Код ошибки + type: integer + error_description: + description: Описание ошибки + type: string + type: object + handlers_user_roles.AssignUserRoleRequest: + properties: + role_id: + type: integer + user_id: + type: integer + type: object + handlers_user_roles.BulkAssignRolesRequest: + properties: + role_ids: + items: + type: integer + type: array + user_id: + type: integer + type: object + typescore.Admin: + properties: + created_at: + description: Дата создания записи + type: string + id: + description: Автоматически заполняемое уникальное поле для большого числа + записей + type: integer + is_blocked: + description: Заблокирован ли администратор + type: boolean + last_ip_login: + description: Последний IP входа + type: string + last_login: + description: Дата входа + type: string + login: + description: Логин администратора + type: string + type: object + typescore.AdminReq: + properties: + login: + type: string + password: + description: Пароль пользователя + type: string + type: object + typescore.ApiResponseBase: + properties: + data: + description: данные полученные от api + total_amount: + type: number + total_count: + type: integer + type: object + typescore.Approval: + properties: + content: + description: введённые пользователем данные по шаблону + type: string + created_at: + type: string + department: + $ref: '#/definitions/typescore.Department' + department_id: + description: снимок отдела на момент создания + type: integer + files: + items: + $ref: '#/definitions/typescore.ApprovalFile' + type: array + id: + type: integer + initiator: + $ref: '#/definitions/typescore.User' + initiator_id: + type: integer + metadata: + type: string + revision_at: + type: string + revision_by_id: + type: integer + revision_comment: + type: string + revision_count: + type: integer + revoked_at: + type: string + revoked_by: + $ref: '#/definitions/typescore.User' + revoked_by_id: + type: integer + status: + type: string + steps: + items: + $ref: '#/definitions/typescore.ApprovalStep' + type: array + topic: + $ref: '#/definitions/typescore.ApprovalTopic' + topic_id: + type: integer + updated_at: + type: string + type: object + typescore.ApprovalFile: + properties: + approval_id: + type: integer + attached_by_id: + type: integer + created_at: + type: string + file_base64: + type: string + file_name: + type: string + id: + type: integer + task_id: + type: integer + type: object + typescore.ApprovalStep: + properties: + acted_at: + type: string + approval: + $ref: '#/definitions/typescore.Approval' + approval_id: + type: integer + approver: + $ref: '#/definitions/typescore.User' + approver_department_snapshot: + type: string + approver_id: + type: integer + approver_name_snapshot: + type: string + comment: + type: string + created_at: + type: string + id: + type: integer + returned_at: + type: string + status: + type: string + step_order: + type: integer + updated_at: + type: string + type: object + typescore.ApprovalTopic: + properties: + allow_approver_selection: + type: boolean + allow_observer_selection: + type: boolean + allows_file: + type: boolean + approvalMode: + type: string + category: + $ref: '#/definitions/typescore.ApprovalTopicCategory' + category_id: + type: integer + code: + type: string + created_at: + type: string + duration_type: + type: string + first_approver_role_code: + description: если задан — первый согласующий выбирается из этой роли + type: string + id: + type: integer + instructions: + type: string + is_active: + type: boolean + name: + type: string + payment_type: + type: string + require_approver_comment: + type: boolean + require_observer_selection: + type: boolean + requires_file: + type: boolean + template: + type: string + time_type: + type: string + updated_at: + type: string + type: object + typescore.ApprovalTopicCategory: + properties: + code: + description: otgul, vacation, sick_leave + type: string + created_at: + type: string + description: + type: string + id: + type: integer + is_active: + type: boolean + name: + type: string + topics: + items: + $ref: '#/definitions/typescore.ApprovalTopic' + type: array + updated_at: + type: string + type: object + typescore.ApprovalTopicExecutor: + properties: + created_at: + type: string + id: + type: integer + is_active: + type: boolean + require_file: + type: boolean + step_order: + type: integer + target_system: + type: string + task_text: + type: string + topic: + $ref: '#/definitions/typescore.ApprovalTopic' + topic_id: + type: integer + updated_at: + type: string + user: + $ref: '#/definitions/typescore.User' + user_id: + type: integer + type: object + typescore.AuthHandlerResponse: + properties: + temp_session: + description: Временный токен для 2FA + type: string + token: + description: токен аутентификации + type: string + type: object + typescore.AuthReqAccount: + properties: + access_code: + type: string + login: + type: string + password: + type: string + redirect_uri: + type: string + token: + type: string + type: object + typescore.Department: + properties: + code: + description: finance, hr, it + type: string + created_at: + type: string + description: + type: string + id: + type: integer + is_active: + type: boolean + name: + type: string + updated_at: + type: string + type: object + typescore.Permission: + properties: + action: + type: string + created_at: + type: string + id: + type: integer + role: + $ref: '#/definitions/typescore.Role' + role_id: + type: integer + topic: + $ref: '#/definitions/typescore.ApprovalTopic' + topic_category: + $ref: '#/definitions/typescore.ApprovalTopicCategory' + topic_category_id: + type: integer + topic_id: + type: integer + updated_at: + type: string + type: object + typescore.Role: + properties: + code: + type: string + created_at: + type: string + description: + type: string + id: + type: integer + is_approver: + type: boolean + is_default: + type: boolean + is_director: + type: boolean + is_executor: + type: boolean + is_observer: + type: boolean + name: + type: string + permissions: + items: + $ref: '#/definitions/typescore.Permission' + type: array + updated_at: + type: string + type: object + typescore.UpdateUserReqAdmin: + properties: + department_id: + description: Логин пользователя + type: integer + id: + type: integer + is_blocked: + description: Заблокирован ли пользователь + type: boolean + is_fired: + description: Заблокирован ли пользователь + type: boolean + type: object + typescore.User: + properties: + blocked_at: + type: string + created_at: + type: string + department: + $ref: '#/definitions/typescore.Department' + department_id: + type: integer + full_name: + type: string + id: + type: integer + is_blocked: + type: boolean + is_fired: + type: boolean + language_code: + description: |- + FirstName *string `gorm:"type:text;not null;column:first_name" json:"first_name" db:"first_name" mapstructure:"first_name"` + LastName *string `gorm:"type:text;not null;column:last_name" json:"last_name" db:"last_name" mapstructure:"last_name"` + Patronymic *string `gorm:"type:text;column:patronymic" json:"patronymic,omitempty" db:"patronymic" mapstructure:"patronymic"` + type: string + last_login: + type: string + telegram_id: + type: integer + updated_at: + type: string + user_roles: + items: + $ref: '#/definitions/typescore.UserRole' + type: array + username: + type: string + type: object + typescore.UserHierarchy: + properties: + approver: + $ref: '#/definitions/typescore.User' + approver_id: + type: integer + created_at: + type: string + department: + $ref: '#/definitions/typescore.Department' + department_id: + type: integer + id: + type: integer + priority: + type: integer + subordinate: + $ref: '#/definitions/typescore.User' + subordinate_id: + type: integer + topic_category_id: + type: integer + topic_id: + type: integer + updated_at: + type: string + type: object + typescore.UserRole: + properties: + created_at: + type: string + id: + description: Автоматически заполняемое уникальное поле для большого числа + записей + type: integer + role: + allOf: + - $ref: '#/definitions/typescore.Role' + description: ← добавить gorm:"-" + role_id: + type: integer + updated_at: + type: string + user: + allOf: + - $ref: '#/definitions/typescore.User' + description: ← добавить gorm:"-" + user_id: + type: integer + type: object +host: localhost:8080 +info: + contact: {} + description: |- + API админ-панели для системы согласований + + ## Возможности + - Управление отделами, ролями и пользователями + - Настройка тем и категорий согласований + - Управление иерархией согласований + - Назначение исполнителей и прав + - Просмотр заявок и шагов согласования + + ## Аутентификация + Все защищённые эндпоинты требуют: + - `Authorization: Bearer ` — JWT токен администратора + - `ApiKey: ` — HMAC подпись для верификации клиента + - `X-Timestamp: ` — Unix timestamp (не старше 3 минут) + - `x-device-id: ` — ID устройства + title: RusPet Admin API + version: "0.1" +paths: + /api/admin: + delete: + consumes: + - application/json + description: Удаление администратора + parameters: + - description: Запрос + in: body + name: request + required: true + schema: + $ref: '#/definitions/typescore.AdminReq' + produces: + - application/json + responses: + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Удаление администратора + tags: + - admin + get: + consumes: + - application/json + description: Получение списка администраторов + parameters: + - description: Смещение для пагинации + in: query + name: offset + type: integer + - description: Количество записей на странице + in: query + name: limit + type: integer + - description: Фильтр по активности + in: query + name: is_active + type: boolean + produces: + - application/json + responses: + "200": + description: Успех + schema: + $ref: '#/definitions/typescore.Admin' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Получение списка администраторов + tags: + - admin + post: + consumes: + - application/json + description: Создание администратора + parameters: + - description: Запрос + in: body + name: request + required: true + schema: + $ref: '#/definitions/typescore.AdminReq' + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/typescore.Admin' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Создание администратора + tags: + - admin + /api/admin/profile: + get: + consumes: + - application/json + description: Получение профиля пользователя + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/typescore.Admin' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Получение профиля пользователя + tags: + - profile + put: + consumes: + - application/json + description: Обновление профиля пользователя + parameters: + - description: Запрос + in: body + name: request + required: true + schema: + $ref: '#/definitions/typescore.AdminReq' + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/typescore.Admin' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Обновление профиля пользователя + tags: + - profile + /api/approval-steps: + delete: + consumes: + - application/json + description: Удаление шага согласования (только для заявок в статусе pending) + parameters: + - description: ID шага для удаления + in: body + name: request + required: true + schema: + $ref: '#/definitions/typescore.ApprovalStep' + produces: + - application/json + responses: + "200": + description: Успех + schema: + type: boolean + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "403": + description: Нельзя удалить шаг завершённой заявки + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "404": + description: Шаг не найден + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Удаление шага + tags: + - approval-steps + get: + consumes: + - application/json + description: Получение списка шагов согласования с пагинацией и фильтрацией + parameters: + - description: Смещение для пагинации + in: query + name: offset + type: integer + - description: Количество записей на странице + in: query + name: limit + type: integer + - description: Фильтр по заявке + in: query + name: approval_id + type: integer + - description: Фильтр по согласующему + in: query + name: approver_id + type: integer + - description: Фильтр по статусу (pending, waiting, approved, rejected, cancelled_any_of) + in: query + name: status + type: string + produces: + - application/json + responses: + "200": + description: Успех + schema: + $ref: '#/definitions/typescore.ApiResponseBase' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Получение списка шагов + tags: + - approval-steps + post: + consumes: + - application/json + description: Создание нового шага согласования для заявки + parameters: + - description: Данные шага + in: body + name: request + required: true + schema: + $ref: '#/definitions/typescore.ApprovalStep' + produces: + - application/json + responses: + "200": + description: Успех + schema: + $ref: '#/definitions/typescore.ApprovalStep' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "404": + description: Заявка или согласующий не найдены + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Создание шага + tags: + - approval-steps + put: + consumes: + - application/json + description: Обновление данных шага согласования (статус, комментарий) + parameters: + - description: Данные шага + in: body + name: request + required: true + schema: + $ref: '#/definitions/typescore.ApprovalStep' + produces: + - application/json + responses: + "200": + description: Успех + schema: + $ref: '#/definitions/typescore.ApprovalStep' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "404": + description: Шаг не найден + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Обновление шага + tags: + - approval-steps + /api/approval-steps/{id}: + get: + consumes: + - application/json + description: Получение детальной информации о шаге согласования по его ID + parameters: + - description: ID шага + in: path + name: id + required: true + type: integer + produces: + - application/json + responses: + "200": + description: Успех + schema: + $ref: '#/definitions/typescore.ApprovalStep' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "404": + description: Шаг не найден + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Получение шага по ID + tags: + - approval-steps + /api/approval-steps/by-approval/{approval_id}: + get: + consumes: + - application/json + description: Получение списка всех шагов согласования для указанной заявки, + отсортированных по step_order + parameters: + - description: ID заявки + in: path + name: approval_id + required: true + type: integer + produces: + - application/json + responses: + "200": + description: Успех + schema: + $ref: '#/definitions/typescore.ApiResponseBase' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "404": + description: Заявка не найдена + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Получение шагов по заявке + tags: + - approval-steps + /api/approvals: + delete: + consumes: + - application/json + description: Удаление заявки (только для черновиков) + parameters: + - description: ID заявки для удаления + in: body + name: request + required: true + schema: + $ref: '#/definitions/typescore.Approval' + produces: + - application/json + responses: + "200": + description: Успех + schema: + type: boolean + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "403": + description: Нельзя удалить не-черновую заявку + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "404": + description: Заявка не найдена + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Удаление заявки + tags: + - approvals + get: + consumes: + - application/json + description: Получение списка заявок с пагинацией и фильтрацией + parameters: + - description: Смещение для пагинации + in: query + name: offset + type: integer + - description: Количество записей на странице + in: query + name: limit + type: integer + - description: Фильтр по статусу (pending, approved, rejected, revoked, revision) + in: query + name: status + type: string + - description: Фильтр по инициатору + in: query + name: initiator_id + type: integer + - description: Фильтр по теме + in: query + name: topic_id + type: integer + - description: Фильтр по отделу + in: query + name: department_id + type: integer + produces: + - application/json + responses: + "200": + description: Успех + schema: + $ref: '#/definitions/typescore.ApiResponseBase' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Получение списка заявок + tags: + - approvals + put: + consumes: + - application/json + description: Обновление данных заявки (статус, комментарии и т.д.) + parameters: + - description: Данные заявки + in: body + name: request + required: true + schema: + $ref: '#/definitions/typescore.Approval' + produces: + - application/json + responses: + "200": + description: Успех + schema: + $ref: '#/definitions/typescore.Approval' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "404": + description: Заявка не найдена + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Обновление заявки + tags: + - approvals + /api/approvals/{id}: + get: + consumes: + - application/json + description: Получение детальной информации о заявке по её ID со всеми связанными + данными + parameters: + - description: ID заявки + in: path + name: id + required: true + type: integer + produces: + - application/json + responses: + "200": + description: Успех + schema: + $ref: '#/definitions/typescore.Approval' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "404": + description: Заявка не найдена + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Получение заявки по ID + tags: + - approvals + /api/approvals/report: + get: + consumes: + - application/json + description: Получение списка заявок для отчёта с учётом периода и доступа пользователя + parameters: + - description: ID пользователя (если не указан - все заявки) + in: query + name: user_id + type: integer + - description: Начальная дата (YYYY-MM-DD) + in: query + name: date_from + type: string + - description: Конечная дата (YYYY-MM-DD) + in: query + name: date_to + type: string + - description: Полный доступ (игнорировать фильтрацию по пользователю) + in: query + name: all_access + type: boolean + produces: + - application/json + responses: + "200": + description: Успех + schema: + $ref: '#/definitions/typescore.ApiResponseBase' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Получение заявок для отчёта + tags: + - approvals + /api/auth/login: + post: + consumes: + - application/json + description: авторизация с помощью связки логин-пароль + parameters: + - description: Запрос + in: body + name: request + required: true + schema: + $ref: '#/definitions/typescore.AuthReqAccount' + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/typescore.AuthHandlerResponse' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: авторизация с помощью связки логин-пароль + tags: + - auth + /api/auth/token: + post: + consumes: + - application/json + description: Авторизация при помощи JWT-токена + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/typescore.AuthHandlerResponse' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Авторизация при помощи JWT-токена + tags: + - auth + /api/categories: + delete: + consumes: + - application/json + description: Удаление категории по ID + parameters: + - description: ID категории для удаления + in: body + name: request + required: true + schema: + $ref: '#/definitions/typescore.ApprovalTopicCategory' + produces: + - application/json + responses: + "200": + description: Успех + schema: + type: boolean + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "404": + description: Категория не найдена + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "409": + description: Категория содержит темы + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Удаление категории + tags: + - categories + get: + consumes: + - application/json + description: Получение списка категорий тем с пагинацией и фильтрацией + parameters: + - description: Смещение для пагинации + in: query + name: offset + type: integer + - description: Количество записей на странице + in: query + name: limit + type: integer + - description: Фильтр по активности + in: query + name: is_active + type: boolean + produces: + - application/json + responses: + "200": + description: Успех + schema: + $ref: '#/definitions/typescore.ApiResponseBase' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Получение списка категорий тем + tags: + - categories + post: + consumes: + - application/json + description: Создание новой категории тем + parameters: + - description: Данные категории + in: body + name: request + required: true + schema: + $ref: '#/definitions/typescore.ApprovalTopicCategory' + produces: + - application/json + responses: + "200": + description: Успех + schema: + $ref: '#/definitions/typescore.ApprovalTopicCategory' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Создание категории тем + tags: + - categories + put: + consumes: + - application/json + description: Обновление данных существующей категории + parameters: + - description: Данные категории + in: body + name: request + required: true + schema: + $ref: '#/definitions/typescore.ApprovalTopicCategory' + produces: + - application/json + responses: + "200": + description: Успех + schema: + $ref: '#/definitions/typescore.ApprovalTopicCategory' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "404": + description: Категория не найдена + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Обновление категории + tags: + - categories + /api/categories/{id}: + get: + consumes: + - application/json + description: Получение детальной информации о категории по её ID + parameters: + - description: ID категории + in: path + name: id + required: true + type: integer + produces: + - application/json + responses: + "200": + description: Успех + schema: + $ref: '#/definitions/typescore.ApprovalTopicCategory' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "404": + description: Категория не найдена + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Получение категории по ID + tags: + - categories + /api/departments: + delete: + consumes: + - application/json + description: Удаление отдела по ID + parameters: + - description: ID отдела для удаления + in: body + name: request + required: true + schema: + $ref: '#/definitions/typescore.Department' + produces: + - application/json + responses: + "200": + description: Успех + schema: + type: boolean + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "404": + description: Отдел не найден + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Удаление отдела + tags: + - departments + get: + consumes: + - application/json + description: Получение списка отделов с пагинацией и фильтрацией + parameters: + - description: Смещение для пагинации + in: query + name: offset + type: integer + - description: Количество записей на странице + in: query + name: limit + type: integer + - description: Фильтр по активности + in: query + name: is_active + type: boolean + produces: + - application/json + responses: + "200": + description: Успех + schema: + $ref: '#/definitions/typescore.ApiResponseBase' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Получение списка отделов + tags: + - departments + post: + consumes: + - application/json + description: Создание нового отдела + parameters: + - description: Данные отдела + in: body + name: request + required: true + schema: + $ref: '#/definitions/typescore.Department' + produces: + - application/json + responses: + "200": + description: Успех + schema: + $ref: '#/definitions/typescore.Department' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Создание отдела + tags: + - departments + put: + consumes: + - application/json + description: Обновление данных существующего отдела + parameters: + - description: Данные отдела + in: body + name: request + required: true + schema: + $ref: '#/definitions/typescore.Department' + produces: + - application/json + responses: + "200": + description: Успех + schema: + $ref: '#/definitions/typescore.Department' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "404": + description: Отдел не найден + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Обновление отдела + tags: + - departments + /api/departments/{id}: + get: + consumes: + - application/json + description: Получение детальной информации об отделе по его ID + parameters: + - description: ID отдела + in: path + name: id + required: true + type: integer + produces: + - application/json + responses: + "200": + description: Успех + schema: + $ref: '#/definitions/typescore.Department' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "404": + description: Отдел не найден + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Получение отдела по ID + tags: + - departments + /api/hierarchies: + delete: + consumes: + - application/json + description: Удаление связи подчинённый-согласующий по ID + parameters: + - description: ID записи для удаления + in: body + name: request + required: true + schema: + $ref: '#/definitions/typescore.UserHierarchy' + produces: + - application/json + responses: + "200": + description: Успех + schema: + type: boolean + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "404": + description: Запись не найдена + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Удаление записи иерархии + tags: + - hierarchies + get: + consumes: + - application/json + description: Получение списка связей подчинённый-согласующий с пагинацией и + фильтрацией + parameters: + - description: Смещение для пагинации + in: query + name: offset + type: integer + - description: Количество записей на странице + in: query + name: limit + type: integer + - description: Фильтр по подчинённому + in: query + name: subordinate_id + type: integer + - description: Фильтр по согласующему + in: query + name: approver_id + type: integer + - description: Фильтр по отделу + in: query + name: department_id + type: integer + produces: + - application/json + responses: + "200": + description: Успех + schema: + $ref: '#/definitions/typescore.ApiResponseBase' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Получение списка записей иерархии + tags: + - hierarchies + post: + consumes: + - application/json + description: Создание новой связи подчинённый-согласующий + parameters: + - description: Данные иерархии + in: body + name: request + required: true + schema: + $ref: '#/definitions/typescore.UserHierarchy' + produces: + - application/json + responses: + "200": + description: Успех + schema: + $ref: '#/definitions/typescore.UserHierarchy' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "409": + description: Такая связь уже существует + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Создание записи иерархии + tags: + - hierarchies + put: + consumes: + - application/json + description: Обновление данных существующей записи иерархии + parameters: + - description: Данные иерархии + in: body + name: request + required: true + schema: + $ref: '#/definitions/typescore.UserHierarchy' + produces: + - application/json + responses: + "200": + description: Успех + schema: + $ref: '#/definitions/typescore.UserHierarchy' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "404": + description: Запись не найдена + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Обновление записи иерархии + tags: + - hierarchies + /api/hierarchies/{id}: + get: + consumes: + - application/json + description: Получение детальной информации о записи иерархии по её ID + parameters: + - description: ID записи + in: path + name: id + required: true + type: integer + produces: + - application/json + responses: + "200": + description: Успех + schema: + $ref: '#/definitions/typescore.UserHierarchy' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "404": + description: Запись не найдена + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Получение записи иерархии по ID + tags: + - hierarchies + /api/permissions: + delete: + consumes: + - application/json + description: Удаление права по ID + parameters: + - description: ID права для удаления + in: body + name: request + required: true + schema: + $ref: '#/definitions/typescore.Permission' + produces: + - application/json + responses: + "200": + description: Успех + schema: + type: boolean + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "404": + description: Право не найдено + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Удаление права + tags: + - permissions + get: + consumes: + - application/json + description: Получение списка прав ролей с пагинацией и фильтрацией + parameters: + - description: Смещение для пагинации + in: query + name: offset + type: integer + - description: Количество записей на странице + in: query + name: limit + type: integer + - description: Фильтр по роли + in: query + name: role_id + type: integer + - description: Фильтр по действию (create, read, update, delete, approve, revoke) + in: query + name: action + type: string + - description: Фильтр по категории тем + in: query + name: topic_category_id + type: integer + - description: Фильтр по теме + in: query + name: topic_id + type: integer + produces: + - application/json + responses: + "200": + description: Успех + schema: + $ref: '#/definitions/typescore.ApiResponseBase' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Получение списка прав + tags: + - permissions + post: + consumes: + - application/json + description: Назначение права на действие для роли + parameters: + - description: Данные права + in: body + name: request + required: true + schema: + $ref: '#/definitions/typescore.Permission' + produces: + - application/json + responses: + "200": + description: Успех + schema: + $ref: '#/definitions/typescore.Permission' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "404": + description: Роль, категория или тема не найдены + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "409": + description: Такое право уже существует + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Создание права + tags: + - permissions + put: + consumes: + - application/json + description: Обновление данных существующего права + parameters: + - description: Данные права + in: body + name: request + required: true + schema: + $ref: '#/definitions/typescore.Permission' + produces: + - application/json + responses: + "200": + description: Успех + schema: + $ref: '#/definitions/typescore.Permission' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "404": + description: Право не найдено + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Обновление права + tags: + - permissions + /api/permissions/{id}: + get: + consumes: + - application/json + description: Получение детальной информации о праве по его ID + parameters: + - description: ID права + in: path + name: id + required: true + type: integer + produces: + - application/json + responses: + "200": + description: Успех + schema: + $ref: '#/definitions/typescore.Permission' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "404": + description: Право не найдено + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Получение права по ID + tags: + - permissions + /api/permissions/by-role/{role_id}: + get: + consumes: + - application/json + description: Получение списка всех прав для указанной роли + parameters: + - description: ID роли + in: path + name: role_id + required: true + type: integer + produces: + - application/json + responses: + "200": + description: Успех + schema: + $ref: '#/definitions/typescore.ApiResponseBase' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "404": + description: Роль не найдена + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Получение прав по роли + tags: + - permissions + /api/roles: + delete: + consumes: + - application/json + description: Удаление роли по ID + parameters: + - description: ID роли для удаления + in: body + name: request + required: true + schema: + $ref: '#/definitions/typescore.Role' + produces: + - application/json + responses: + "200": + description: Успех + schema: + type: boolean + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "404": + description: Роль не найдена + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Удаление роли + tags: + - roles + get: + consumes: + - application/json + description: Получение списка ролей с пагинацией и фильтрацией + parameters: + - description: Смещение для пагинации + in: query + name: offset + type: integer + - description: Количество записей на странице + in: query + name: limit + type: integer + produces: + - application/json + responses: + "200": + description: Успех + schema: + $ref: '#/definitions/typescore.ApiResponseBase' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Получение списка ролей + tags: + - roles + post: + consumes: + - application/json + description: Создание новой роли + parameters: + - description: Данные роли + in: body + name: request + required: true + schema: + $ref: '#/definitions/typescore.Role' + produces: + - application/json + responses: + "200": + description: Успех + schema: + $ref: '#/definitions/typescore.Role' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Создание роли + tags: + - roles + put: + consumes: + - application/json + description: Обновление данных существующей роли + parameters: + - description: Данные роли + in: body + name: request + required: true + schema: + $ref: '#/definitions/typescore.Role' + produces: + - application/json + responses: + "200": + description: Успех + schema: + $ref: '#/definitions/typescore.Role' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "404": + description: Роль не найдена + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Обновление роли + tags: + - roles + /api/roles/{id}: + get: + consumes: + - application/json + description: Получение детальной информации о роли по её ID + parameters: + - description: ID роли + in: path + name: id + required: true + type: integer + produces: + - application/json + responses: + "200": + description: Успех + schema: + $ref: '#/definitions/typescore.Role' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "404": + description: Роль не найдена + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Получение роли по ID + tags: + - roles + /api/topic-executors: + delete: + consumes: + - application/json + description: Удаление исполнителя из темы по ID + parameters: + - description: ID записи для удаления + in: body + name: request + required: true + schema: + $ref: '#/definitions/typescore.ApprovalTopicExecutor' + produces: + - application/json + responses: + "200": + description: Успех + schema: + type: boolean + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "404": + description: Запись не найдена + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Удаление исполнителя + tags: + - topic-executors + get: + consumes: + - application/json + description: Получение списка исполнителей с пагинацией и фильтрацией + parameters: + - description: Смещение для пагинации + in: query + name: offset + type: integer + - description: Количество записей на странице + in: query + name: limit + type: integer + - description: Фильтр по теме + in: query + name: topic_id + type: integer + - description: Фильтр по пользователю + in: query + name: user_id + type: integer + - description: Фильтр по активности + in: query + name: is_active + type: boolean + produces: + - application/json + responses: + "200": + description: Успех + schema: + $ref: '#/definitions/typescore.ApiResponseBase' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Получение списка исполнителей тем + tags: + - topic-executors + post: + consumes: + - application/json + description: Назначение исполнителя для конкретной темы согласования + parameters: + - description: Данные исполнителя + in: body + name: request + required: true + schema: + $ref: '#/definitions/typescore.ApprovalTopicExecutor' + produces: + - application/json + responses: + "200": + description: Успех + schema: + $ref: '#/definitions/typescore.ApprovalTopicExecutor' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "404": + description: Тема или пользователь не найдены + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "409": + description: Такой исполнитель уже назначен на этот шаг + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Создание исполнителя + tags: + - topic-executors + put: + consumes: + - application/json + description: Обновление данных исполнителя для темы + parameters: + - description: Данные исполнителя + in: body + name: request + required: true + schema: + $ref: '#/definitions/typescore.ApprovalTopicExecutor' + produces: + - application/json + responses: + "200": + description: Успех + schema: + $ref: '#/definitions/typescore.ApprovalTopicExecutor' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "404": + description: Исполнитель не найден + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Обновление исполнителя + tags: + - topic-executors + /api/topic-executors/{id}: + get: + consumes: + - application/json + description: Получение детальной информации об исполнителе по его ID + parameters: + - description: ID исполнителя + in: path + name: id + required: true + type: integer + produces: + - application/json + responses: + "200": + description: Успех + schema: + $ref: '#/definitions/typescore.ApprovalTopicExecutor' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "404": + description: Исполнитель не найден + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Получение исполнителя по ID + tags: + - topic-executors + /api/topic-executors/by-topic/{topic_id}: + get: + consumes: + - application/json + description: Получение списка всех активных исполнителей для указанной темы, + отсортированных по step_order + parameters: + - description: ID темы + in: path + name: topic_id + required: true + type: integer + produces: + - application/json + responses: + "200": + description: Успех + schema: + $ref: '#/definitions/typescore.ApiResponseBase' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "404": + description: Тема не найдена + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Получение исполнителей по теме + tags: + - topic-executors + /api/topics: + delete: + consumes: + - application/json + description: Удаление темы по ID + parameters: + - description: ID темы для удаления + in: body + name: request + required: true + schema: + $ref: '#/definitions/typescore.ApprovalTopic' + produces: + - application/json + responses: + "200": + description: Успех + schema: + type: boolean + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "404": + description: Тема не найдена + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "409": + description: Тема содержит заявки + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Удаление темы + tags: + - topics + get: + consumes: + - application/json + description: Получение списка тем с пагинацией и фильтрацией + parameters: + - description: Смещение для пагинации + in: query + name: offset + type: integer + - description: Количество записей на странице + in: query + name: limit + type: integer + - description: Фильтр по категории + in: query + name: category_id + type: integer + - description: Фильтр по активности + in: query + name: is_active + type: boolean + produces: + - application/json + responses: + "200": + description: Успех + schema: + $ref: '#/definitions/typescore.ApiResponseBase' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Получение списка тем + tags: + - topics + post: + consumes: + - application/json + description: Создание новой темы согласования + parameters: + - description: Данные темы + in: body + name: request + required: true + schema: + $ref: '#/definitions/typescore.ApprovalTopic' + produces: + - application/json + responses: + "200": + description: Успех + schema: + $ref: '#/definitions/typescore.ApprovalTopic' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Создание темы + tags: + - topics + put: + consumes: + - application/json + description: Обновление данных существующей темы + parameters: + - description: Данные темы + in: body + name: request + required: true + schema: + $ref: '#/definitions/typescore.ApprovalTopic' + produces: + - application/json + responses: + "200": + description: Успех + schema: + $ref: '#/definitions/typescore.ApprovalTopic' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "404": + description: Тема не найдена + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Обновление темы + tags: + - topics + /api/topics/{id}: + get: + consumes: + - application/json + description: Получение детальной информации о теме по её ID + parameters: + - description: ID темы + in: path + name: id + required: true + type: integer + produces: + - application/json + responses: + "200": + description: Успех + schema: + $ref: '#/definitions/typescore.ApprovalTopic' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "404": + description: Тема не найдена + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Получение темы по ID + tags: + - topics + /api/user-roles: + delete: + consumes: + - application/json + description: Удаление связи user_id + role_id по ID записи + parameters: + - description: ID записи для удаления + in: body + name: request + required: true + schema: + $ref: '#/definitions/typescore.UserRole' + produces: + - application/json + responses: + "200": + description: Успех + schema: + type: boolean + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "404": + description: Запись не найдена + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Удаление роли у пользователя + tags: + - user-roles + get: + consumes: + - application/json + description: Получение списка ролей, назначенных конкретному пользователю + parameters: + - description: ID пользователя + in: query + name: user_id + required: true + type: integer + produces: + - application/json + responses: + "200": + description: Успех + schema: + $ref: '#/definitions/typescore.ApiResponseBase' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Получение списка ролей пользователя + tags: + - user-roles + post: + consumes: + - application/json + description: Назначение роли пользователю (создание связи user_id + role_id) + parameters: + - description: user_id и role_id + in: body + name: request + required: true + schema: + $ref: '#/definitions/handlers_user_roles.AssignUserRoleRequest' + produces: + - application/json + responses: + "200": + description: Успех + schema: + $ref: '#/definitions/typescore.UserRole' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "404": + description: Пользователь или роль не найдены + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "409": + description: Роль уже назначена + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Назначение роли пользователю + tags: + - user-roles + /api/user-roles/bulk: + post: + consumes: + - application/json + description: 'Полная замена ролей пользователя: удаляет все текущие роли и назначает + новые' + parameters: + - description: user_id и список role_ids + in: body + name: request + required: true + schema: + $ref: '#/definitions/handlers_user_roles.BulkAssignRolesRequest' + produces: + - application/json + responses: + "200": + description: Успех + schema: + $ref: '#/definitions/typescore.ApiResponseBase' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "404": + description: Пользователь не найден + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Массовое назначение ролей + tags: + - user-roles + /api/users: + get: + consumes: + - application/json + description: Получение списка пользователей с пагинацией, фильтрацией и подгрузкой + связанных данных + parameters: + - description: Смещение для пагинации + in: query + name: offset + type: integer + - description: Количество записей на странице + in: query + name: limit + type: integer + - description: Фильтр по блокировке + in: query + name: is_blocked + type: boolean + - description: Фильтр по увольнению + in: query + name: is_fired + type: boolean + - description: Фильтр по отделу + in: query + name: department_id + type: integer + produces: + - application/json + responses: + "200": + description: Успех + schema: + $ref: '#/definitions/typescore.ApiResponseBase' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Получение списка пользователей + tags: + - users + put: + consumes: + - application/json + description: Обновление данных существующего пользователя + parameters: + - description: Данные пользователя + in: body + name: request + required: true + schema: + $ref: '#/definitions/typescore.UpdateUserReqAdmin' + produces: + - application/json + responses: + "200": + description: Успех + schema: + $ref: '#/definitions/typescore.User' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "404": + description: Пользователь не найден + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Обновление пользователя + tags: + - users + /api/users/{id}: + get: + consumes: + - application/json + description: Получение детальной информации о пользователе по его ID с подгрузкой + связанных данных + parameters: + - description: ID пользователя + in: path + name: id + required: true + type: integer + produces: + - application/json + responses: + "200": + description: Успех + schema: + $ref: '#/definitions/typescore.User' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "404": + description: Пользователь не найден + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Получение пользователя по ID + tags: + - users + /api/users/{user_id}/roles: + get: + consumes: + - application/json + description: Получение списка ролей, назначенных пользователю с указанным ID + parameters: + - description: ID пользователя + in: path + name: user_id + required: true + type: integer + produces: + - application/json + responses: + "200": + description: Успех + schema: + $ref: '#/definitions/typescore.ApiResponseBase' + "400": + description: Некорректный запрос + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "404": + description: Пользователь не найден + schema: + $ref: '#/definitions/handlers.ErrorResponse' + "500": + description: Ошибка сервера + schema: + $ref: '#/definitions/handlers.ErrorResponse' + summary: Получение списка ролей пользователя по ID + tags: + - user-roles +securityDefinitions: + ApiKeyAuth: + in: header + name: ApiKey + type: apiKey + BearerAuth: + in: header + name: Authorization + type: apiKey + DeviceID: + in: header + name: x-device-id + type: apiKey + Timestamp: + in: header + name: X-Timestamp + type: apiKey +swagger: "2.0" diff --git a/service/rest_admin_service/go.mod b/service/rest_admin_service/go.mod index 38f492d..6e1d727 100644 --- a/service/rest_admin_service/go.mod +++ b/service/rest_admin_service/go.mod @@ -3,3 +3,74 @@ module bitrix_balancer_api/rest_admin_service replace bitrix_balancer_api/core => ../../core go 1.25.6 + +require ( + bitrix_balancer_api/core v0.0.0-00010101000000-000000000000 + github.com/go-chi/chi/v5 v5.3.0 + github.com/go-chi/cors v1.2.2 + github.com/go-chi/httprate v0.15.0 + github.com/sirupsen/logrus v1.9.4 + github.com/swaggo/http-swagger v1.3.4 + github.com/swaggo/swag v1.16.6 +) + +require ( + github.com/KyleBanks/depth v1.2.1 // indirect + github.com/Masterminds/squirrel v1.5.4 // indirect + github.com/cenkalti/backoff/v4 v4.3.0 // indirect + github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect + github.com/go-jose/go-jose/v4 v4.1.1 // indirect + github.com/go-openapi/jsonpointer v0.23.1 // indirect + github.com/go-openapi/jsonreference v0.21.6 // indirect + github.com/go-openapi/spec v0.22.6 // indirect + github.com/go-openapi/swag/conv v0.26.1 // indirect + github.com/go-openapi/swag/jsonname v0.26.1 // indirect + github.com/go-openapi/swag/jsonutils v0.26.1 // indirect + github.com/go-openapi/swag/loading v0.26.1 // indirect + github.com/go-openapi/swag/stringutils v0.26.1 // indirect + github.com/go-openapi/swag/typeutils v0.26.1 // indirect + github.com/go-openapi/swag/yamlutils v0.26.1 // indirect + github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1 // indirect + github.com/golang-jwt/jwt/v5 v5.3.1 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/hashicorp/errwrap v1.1.0 // indirect + github.com/hashicorp/go-cleanhttp v0.5.2 // indirect + github.com/hashicorp/go-multierror v1.1.1 // indirect + github.com/hashicorp/go-retryablehttp v0.7.8 // indirect + github.com/hashicorp/go-rootcerts v1.0.2 // indirect + github.com/hashicorp/go-secure-stdlib/parseutil v0.2.0 // indirect + github.com/hashicorp/go-secure-stdlib/strutil v0.1.2 // indirect + github.com/hashicorp/go-sockaddr v1.0.7 // indirect + github.com/hashicorp/hcl v1.0.1-vault-7 // indirect + github.com/hashicorp/vault/api v1.22.0 // indirect + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect + github.com/jackc/pgx/v5 v5.8.0 // indirect + github.com/jackc/puddle/v2 v2.2.2 // indirect + github.com/jinzhu/inflection v1.0.0 // indirect + github.com/jinzhu/now v1.1.5 // indirect + github.com/klauspost/cpuid/v2 v2.2.10 // indirect + github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 // indirect + github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 // indirect + github.com/mitchellh/go-homedir v1.1.0 // indirect + github.com/mitchellh/mapstructure v1.5.0 // indirect + github.com/redis/go-redis/v9 v9.18.0 // indirect + github.com/ryanuber/go-glob v1.0.0 // indirect + github.com/shopspring/decimal v1.4.0 // indirect + github.com/swaggo/files v1.0.1 // indirect + github.com/zeebo/xxh3 v1.0.2 // indirect + go.uber.org/atomic v1.11.0 // indirect + go.yaml.in/yaml/v3 v3.0.4 // indirect + golang.org/x/crypto v0.53.0 // indirect + golang.org/x/mod v0.37.0 // indirect + golang.org/x/net v0.56.0 // indirect + golang.org/x/sync v0.21.0 // indirect + golang.org/x/sys v0.46.0 // indirect + golang.org/x/text v0.38.0 // indirect + golang.org/x/time v0.12.0 // indirect + golang.org/x/tools v0.46.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect + gorm.io/driver/postgres v1.6.0 // indirect + gorm.io/gorm v1.31.1 // indirect +) diff --git a/service/rest_admin_service/go.sum b/service/rest_admin_service/go.sum new file mode 100644 index 0000000..0c3896f --- /dev/null +++ b/service/rest_admin_service/go.sum @@ -0,0 +1,202 @@ +github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc= +github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE= +github.com/Masterminds/squirrel v1.5.4 h1:uUcX/aBc8O7Fg9kaISIUsHXdKuqehiXAMQTYX8afzqM= +github.com/Masterminds/squirrel v1.5.4/go.mod h1:NNaOrjSoIDfDA40n7sr2tPNZRfjzjA400rg+riTZj10= +github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs= +github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c= +github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= +github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0= +github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8= +github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= +github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= +github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM= +github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU= +github.com/go-chi/chi/v5 v5.3.0 h1:halUjDxhshgXHMrao5bB8eNBXo/rnzwr8m5m36glehM= +github.com/go-chi/chi/v5 v5.3.0/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto= +github.com/go-chi/cors v1.2.2 h1:Jmey33TE+b+rB7fT8MUy1u0I4L+NARQlK6LhzKPSyQE= +github.com/go-chi/cors v1.2.2/go.mod h1:sSbTewc+6wYHBBCW7ytsFSn836hqM7JxpglAy2Vzc58= +github.com/go-chi/httprate v0.15.0 h1:j54xcWV9KGmPf/X4H32/aTH+wBlrvxL7P+SdnRqxh5g= +github.com/go-chi/httprate v0.15.0/go.mod h1:rzGHhVrsBn3IMLYDOZQsSU4fJNWcjui4fWKJcCId1R4= +github.com/go-jose/go-jose/v4 v4.1.1 h1:JYhSgy4mXXzAdF3nUx3ygx347LRXJRrpgyU3adRmkAI= +github.com/go-jose/go-jose/v4 v4.1.1/go.mod h1:BdsZGqgdO3b6tTc6LSE56wcDbMMLuPsw5d4ZD5f94kA= +github.com/go-openapi/jsonpointer v0.23.1 h1:1HBACs7XIwR2RcmItfdSFlALhGbe6S92p0ry4d1GWg4= +github.com/go-openapi/jsonpointer v0.23.1/go.mod h1:iWRmZTrGn7XwYhtPt/fvdSFj1OfNBngqRT2UG3BxSqY= +github.com/go-openapi/jsonreference v0.21.6 h1:NZ5nGfnaM1n4I43Xjm1e5/M2GjOwQwndQz22uhxwD+Y= +github.com/go-openapi/jsonreference v0.21.6/go.mod h1:xzbgtQ3ZbWxvET3AxdzCJlJt6vkovbf+IfSPJjD0tUY= +github.com/go-openapi/spec v0.22.6 h1:Tyy1pLaNCM8GBCFLoGYLonjJi6zykqyLCjXLc19ZPic= +github.com/go-openapi/spec v0.22.6/go.mod h1:HZvTHat+iH0PALQRWhrqIHtU/PEqxqd89fu0MxGlMeM= +github.com/go-openapi/swag v0.19.15 h1:D2NRCBzS9/pEY3gP9Nl8aDqGUcPFrwG2p+CNFrLyrCM= +github.com/go-openapi/swag/conv v0.26.1 h1:slr5FVkg9Wc3Y5zcwenD8Sd/PQ94b2I/QJI7N7KTBpg= +github.com/go-openapi/swag/conv v0.26.1/go.mod h1:mvQXgPptZk9GTrFgGwWvT4q+dN+zQej9JfmGwnipz1A= +github.com/go-openapi/swag/jsonname v0.26.1 h1:VReupaV6WxlAsCn0e4DUfgV6bPmINnPpyJDLqSfNPcE= +github.com/go-openapi/swag/jsonname v0.26.1/go.mod h1:OvdW6BoWoj33pTfi7x9vFrgmT+fk7aw0BRwvCE0YOuc= +github.com/go-openapi/swag/jsonutils v0.26.1 h1:2hdBfFkHg+7Wrz2VsCbeyR6hzkRDs7AztnMR2u84yOY= +github.com/go-openapi/swag/jsonutils v0.26.1/go.mod h1:U+RMJH3wa+6BRiphuRtIyI8fW9HPFqFQ4sHk2oRx0UQ= +github.com/go-openapi/swag/jsonutils/fixtures_test v0.26.1 h1:1CD7NiLLb/TXl3tOnFYU4b+mNfb5rtgHkaA+q7RMYYQ= +github.com/go-openapi/swag/jsonutils/fixtures_test v0.26.1/go.mod h1:ZWafc8nMdYzTE3uYY6W86f0n46+IF0g4uUyRhJw/kXc= +github.com/go-openapi/swag/loading v0.26.1 h1:E9K4wqXeROlhjFQ13K9zMz6ojFGXIggGe+ad1odrK9w= +github.com/go-openapi/swag/loading v0.26.1/go.mod h1:3qvRIlWzWdq1HvmldwmuJ2ohpcAryN6xVt2OTKd0/7E= +github.com/go-openapi/swag/stringutils v0.26.1 h1:f88uYyTso7TnHrKM/bUBsQ5e2wKf37cpgo6pvbzd9yU= +github.com/go-openapi/swag/stringutils v0.26.1/go.mod h1:Sc6d3bU8fgk5AyZR8/8jEQ+Is/Ald+TD/IIggPN8UJk= +github.com/go-openapi/swag/typeutils v0.26.1 h1:yg42FgMzRR6PVQ3M3qHz1s+Y6/P4HoJ3cBarXa3OVnU= +github.com/go-openapi/swag/typeutils v0.26.1/go.mod h1:VfnV+oUtSP2vCSCn2aJgnr8OevUYemyIzzS1VOzS10o= +github.com/go-openapi/swag/yamlutils v0.26.1 h1:0TSLK+lXs9vfIhAWzBeI/lOzEnIoot6WTCO1aAeWFTk= +github.com/go-openapi/swag/yamlutils v0.26.1/go.mod h1:7W5b7PRX9MxwL7TjeG7H8HkyBGRsIDRObhyMWFgBI2M= +github.com/go-openapi/testify/enable/yaml/v2 v2.5.1 h1:q9NtHwK4qHF7yZziBPvZyv7zWAIk8ok88Gh2mR6Jpc8= +github.com/go-openapi/testify/enable/yaml/v2 v2.5.1/go.mod h1:JW0MXIotCYps/XsgJnG3a8Q7rE5xAiBwoOD5OfaIQBk= +github.com/go-openapi/testify/v2 v2.5.1 h1:TMdhCaw8fUNraVSf3Omoob1dO/AzBfhtFAPW0an6sBo= +github.com/go-openapi/testify/v2 v2.5.1/go.mod h1:SgsVHtfooshd0tublTtJ50FPKhujf47YRqauXXOUxfw= +github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1 h1:wG8n/XJQ07TmjbITcGiUaOtXxdrINDz1b0J1w0SzqDc= +github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1/go.mod h1:A2S0CWkNylc2phvKXWBBdD3K0iGnDBGbzRpISP2zBl8= +github.com/go-test/deep v1.1.1 h1:0r/53hagsehfO4bzD2Pgr/+RgHqhmf+k1Bpse2cTu1U= +github.com/go-test/deep v1.1.1/go.mod h1:5C2ZWiW0ErCdrYzpqxLbTX7MG14M9iiw8DgHncVwcsE= +github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY= +github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I= +github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ= +github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48= +github.com/hashicorp/go-hclog v1.6.3 h1:Qr2kF+eVWjTiYmU7Y31tYlP1h0q/X3Nl3tPGdaB11/k= +github.com/hashicorp/go-hclog v1.6.3/go.mod h1:W4Qnvbt70Wk/zYJryRzDRU/4r0kIg0PVHBcfoyhpF5M= +github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= +github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= +github.com/hashicorp/go-retryablehttp v0.7.8 h1:ylXZWnqa7Lhqpk0L1P1LzDtGcCR0rPVUrx/c8Unxc48= +github.com/hashicorp/go-retryablehttp v0.7.8/go.mod h1:rjiScheydd+CxvumBsIrFKlx3iS0jrZ7LvzFGFmuKbw= +github.com/hashicorp/go-rootcerts v1.0.2 h1:jzhAVGtqPKbwpyCPELlgNWhE1znq+qwJtW5Oi2viEzc= +github.com/hashicorp/go-rootcerts v1.0.2/go.mod h1:pqUvnprVnM5bf7AOirdbb01K4ccR319Vf4pU3K5EGc8= +github.com/hashicorp/go-secure-stdlib/parseutil v0.2.0 h1:U+kC2dOhMFQctRfhK0gRctKAPTloZdMU5ZJxaesJ/VM= +github.com/hashicorp/go-secure-stdlib/parseutil v0.2.0/go.mod h1:Ll013mhdmsVDuoIXVfBtvgGJsXDYkTw1kooNcoCXuE0= +github.com/hashicorp/go-secure-stdlib/strutil v0.1.2 h1:kes8mmyCpxJsI7FTwtzRqEy9CdjCtrXrXGuOpxEA7Ts= +github.com/hashicorp/go-secure-stdlib/strutil v0.1.2/go.mod h1:Gou2R9+il93BqX25LAKCLuM+y9U2T4hlwvT1yprcna4= +github.com/hashicorp/go-sockaddr v1.0.7 h1:G+pTkSO01HpR5qCxg7lxfsFEZaG+C0VssTy/9dbT+Fw= +github.com/hashicorp/go-sockaddr v1.0.7/go.mod h1:FZQbEYa1pxkQ7WLpyXJ6cbjpT8q0YgQaK/JakXqGyWw= +github.com/hashicorp/hcl v1.0.1-vault-7 h1:ag5OxFVy3QYTFTJODRzTKVZ6xvdfLLCA1cy/Y6xGI0I= +github.com/hashicorp/hcl v1.0.1-vault-7/go.mod h1:XYhtn6ijBSAj6n4YqAaf7RBPS4I06AItNorpy+MoQNM= +github.com/hashicorp/vault/api v1.22.0 h1:+HYFquE35/B74fHoIeXlZIP2YADVboaPjaSicHEZiH0= +github.com/hashicorp/vault/api v1.22.0/go.mod h1:IUZA2cDvr4Ok3+NtK2Oq/r+lJeXkeCrHRmqdyWfpmGM= +github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= +github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgx/v5 v5.8.0 h1:TYPDoleBBme0xGSAX3/+NujXXtpZn9HBONkQC7IEZSo= +github.com/jackc/pgx/v5 v5.8.0/go.mod h1:QVeDInX2m9VyzvNeiCJVjCkNFqzsNb43204HshNSZKw= +github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= +github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= +github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= +github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= +github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= +github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= +github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE= +github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= +github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= +github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 h1:SOEGU9fKiNWd/HOJuq6+3iTQz8KNCLtVX6idSoTLdUw= +github.com/lann/builder v0.0.0-20180802200727-47ae307949d0/go.mod h1:dXGbAdH5GtBTC4WfIxhKZfyBF/HBFgRZSWwZ9g/He9o= +github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 h1:P6pPBnrTSX3DEVR4fDembhRWSsG5rVo6hYhAB/ADZrk= +github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0/go.mod h1:vmVJ0l/dxyfGW6FmdpVm2joNMFikkuWg0EoCKLGUMNw= +github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE= +github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= +github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= +github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= +github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/redis/go-redis/v9 v9.18.0 h1:pMkxYPkEbMPwRdenAzUNyFNrDgHx9U+DrBabWNfSRQs= +github.com/redis/go-redis/v9 v9.18.0/go.mod h1:k3ufPphLU5YXwNTUcCRXGxUoF1fqxnhFQmscfkCoDA0= +github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= +github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= +github.com/ryanuber/go-glob v1.0.0 h1:iQh3xXAumdQ+4Ufa5b25cRpC5TYKlno6hsv6Cb3pkBk= +github.com/ryanuber/go-glob v1.0.0/go.mod h1:807d1WSdnB0XRJzKNil9Om6lcp/3a0v4qIHxIXzX/Yc= +github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp81k= +github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME= +github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w= +github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/swaggo/files v1.0.1 h1:J1bVJ4XHZNq0I46UU90611i9/YzdrF7x92oX1ig5IdE= +github.com/swaggo/files v1.0.1/go.mod h1:0qXmMNH6sXNf+73t65aKeB+ApmgxdnkQzVTAj2uaMUg= +github.com/swaggo/http-swagger v1.3.4 h1:q7t/XLx0n15H1Q9/tk3Y9L4n210XzJF5WtnDX64a5ww= +github.com/swaggo/http-swagger v1.3.4/go.mod h1:9dAh0unqMBAlbp1uE2Uc2mQTxNMU/ha4UbucIg1MFkQ= +github.com/swaggo/swag v1.16.6 h1:qBNcx53ZaX+M5dxVyTrgQ0PJ/ACK+NzhwcbieTt+9yI= +github.com/swaggo/swag v1.16.6/go.mod h1:ngP2etMK5a0P3QBizic5MEwpRmluJZPHjXcMoj4Xesg= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +github.com/zeebo/assert v1.3.0 h1:g7C04CbJuIDKNPFHmsk4hwZDO5O+kntRxzaUoNXj+IQ= +github.com/zeebo/assert v1.3.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0= +github.com/zeebo/xxh3 v1.0.2 h1:xZmwmqxHZA8AI603jOQ0tMqmBr9lPeFwGg6d+xy9DC0= +github.com/zeebo/xxh3 v1.0.2/go.mod h1:5NWz9Sef7zIDm2JHfFlcQvNekmcEl9ekUZQQKCYaDcA= +go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= +go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= +go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= +go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.53.0 h1:QZ4Muo8THX6CizN2vPPd5fBGHyogrdK9fG4wLPFUsto= +golang.org/x/crypto v0.53.0/go.mod h1:DNLU434OwVakk9PzuwV8w62mAJpRJL3vsgcfp4Qnsio= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ= +golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o= +golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM= +golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw= +golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.38.0 h1:sXmwo9DwP3OK9EZ7PqAdaooSGozfl/3a6/xJcbzPRhE= +golang.org/x/text v0.38.0/go.mod h1:YXZt3QhHUKYT53r2lLKFIVi6Ao1jdzrTR/KQ09qyxF4= +golang.org/x/time v0.12.0 h1:ScB/8o8olJvc+CQPWrK3fPZNfh7qgwCrY0zJmoEQLSE= +golang.org/x/time v0.12.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/tools v0.46.0 h1:7jTurBkPZu4moS/Uy4OQT1M+QBlsj3wejyZwsT8Z7rk= +golang.org/x/tools v0.46.0/go.mod h1:FrD85F8l+NWL+9XWBSyVSHO6Ne4jutsfIFba7AWQ5Ys= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gorm.io/driver/postgres v1.6.0 h1:2dxzU8xJ+ivvqTRph34QX+WrRaJlmfyPqXmoGVjMBa4= +gorm.io/driver/postgres v1.6.0/go.mod h1:vUw0mrGgrTK+uPHEhAdV4sfFELrByKVGnaVRkXDhtWo= +gorm.io/gorm v1.31.1 h1:7CA8FTFz/gRfgqgpeKIBcervUn3xSyPUmr6B2WXJ7kg= +gorm.io/gorm v1.31.1/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs= diff --git a/service/rest_admin_service/handlers/admin/handlers.go b/service/rest_admin_service/handlers/admin/handlers.go new file mode 100644 index 0000000..65350d3 --- /dev/null +++ b/service/rest_admin_service/handlers/admin/handlers.go @@ -0,0 +1,138 @@ +package adminhandler + +import ( + "bitrix_balancer_api/core/securecore" + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/core/utilscore" + "encoding/json" + "errors" + "io" + "net/http" +) + +// GetAdminsListHandler Получение списка администраторов +// @Summary Получение списка администраторов +// @Description Получение списка администраторов +// @Tags admin +// @Accept json +// @Produce json +// @Param offset query integer false "Смещение для пагинации" +// @Param limit query integer false "Количество записей на странице" +// @Param is_active query boolean false "Фильтр по активности" +// @Success 200 {object} typescore.Admin "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/admin [get] +func (s *AdminsReg) GetAdminsListHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + queryParams := r.URL.Query() + + AdminsParams := &typescore.Admin{} + offset, limit, likeFields, errW := utilscore.ParseParamsGetRequest(queryParams, AdminsParams) + if errW != nil { + return nil, errW + } + + options := typescore.ListDbOptions{ + Filtering: AdminsParams, + Offset: offset, + Limit: limit, + LikeFields: likeFields, + } + + adminsDbLst, total, errW := s.ipc.Database.Admin.GetAdminsListDB(options) + if errW != nil { + return nil, errW + } + + return &typescore.ApiResponseBase{ + TotalCount: total, + Data: adminsDbLst, + }, nil +} + +// CreateAdminHandler Создание администратора +// @Summary Создание администратора +// @Description Создание администратора +// @Tags admin +// @Accept json +// @Produce json +// @Param request body typescore.AdminReq true "Запрос" +// @Success 200 {object} typescore.Admin +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/admin [post] +func (s *AdminsReg) CreateAdminHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + defer r.Body.Close() + + body, err := io.ReadAll(r.Body) + if err != nil { + return nil, err + } + + var req typescore.AdminReq + if err := json.Unmarshal(body, &req); err != nil { + return nil, err + } + + usersList, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{Filtering: &typescore.Admin{Login: req.Login}}) + if err != nil { + return nil, err + } + if len(usersList) > 0 { + return nil, errors.New("admin_is_not_available") + } + + tempPassword, err := utilscore.GenerateRandomString(12) + if err != nil { + return nil, err + } + + tempPasswordHash, err := securecore.HashPassword(&tempPassword) + if err != nil { + return nil, err + } + + newAdminObj := &typescore.Admin{ + Login: req.Login, + PasswordHash: tempPasswordHash, + } + + newAdmin, _, err := s.ipc.Database.Admin.CreateAdminDB(nil, newAdminObj, true) + if err != nil { + return nil, err + } + + newAdmin.PasswordHash = &tempPassword + return newAdmin, nil +} + +// DeleteAdminHandler Удаление администратора +// @Summary Удаление администратора +// @Description Удаление администратора +// @Tags admin +// @Accept json +// @Produce json +// @Param request body typescore.AdminReq true "Запрос" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/admin [delete] +func (s *AdminsReg) DeleteAdminHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + defer r.Body.Close() + + body, err := io.ReadAll(r.Body) + if err != nil { + return nil, err + } + + var req typescore.Admin + if err := json.Unmarshal(body, &req); err != nil { + return nil, err + } + + err = s.ipc.Database.Admin.DeleteAdminDB(&req) + if err != nil { + return nil, err + } + + return true, nil +} diff --git a/service/rest_admin_service/handlers/admin/routes.go b/service/rest_admin_service/handlers/admin/routes.go new file mode 100644 index 0000000..e530ad0 --- /dev/null +++ b/service/rest_admin_service/handlers/admin/routes.go @@ -0,0 +1,37 @@ +package adminhandler + +import ( + "bitrix_balancer_api/rest_admin_service/handlers" + typesm "bitrix_balancer_api/rest_admin_service/types" + "github.com/go-chi/chi/v5" + "net/http" +) + +const ( + adminURL = "/" +) + +type AdminsReg struct { + ipc *typesm.InternalProviderControl +} + +// RegisterAdminRoutes регистрирует маршруты для группы admin +func RegisterAdminRoutes( + r chi.Router, + ipc *typesm.InternalProviderControl, +) error { + s := &AdminsReg{ + ipc: ipc, + } + + r.Route("/api/admin", func(r chi.Router) { + r.Use(handlers.AccessCodeVerifier(ipc.Config)) + r.Use(handlers.JWTVerifier(ipc.Config, ipc.Database.Admin, ipc.RedisClient)) + + handlers.RegisterRoute(r, http.MethodGet, adminURL, s.GetAdminsListHandler) + handlers.RegisterRoute(r, http.MethodPost, adminURL, s.CreateAdminHandler) + handlers.RegisterRoute(r, http.MethodDelete, adminURL, s.DeleteAdminHandler) + }) + + return nil +} diff --git a/service/rest_admin_service/handlers/approval_steps/handlers.go b/service/rest_admin_service/handlers/approval_steps/handlers.go new file mode 100644 index 0000000..70e1058 --- /dev/null +++ b/service/rest_admin_service/handlers/approval_steps/handlers.go @@ -0,0 +1,446 @@ +package approvalstepshandler + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/core/utilscore" + "context" + "encoding/json" + "errors" + "github.com/sirupsen/logrus" + "io" + "net/http" + "strconv" + + "github.com/go-chi/chi/v5" +) + +// GetApprovalStepsListHandler Получение списка шагов согласования +// @Summary Получение списка шагов +// @Description Получение списка шагов согласования с пагинацией и фильтрацией +// @Tags approval-steps +// @Accept json +// @Produce json +// @Param offset query integer false "Смещение для пагинации" +// @Param limit query integer false "Количество записей на странице" +// @Param approval_id query integer false "Фильтр по заявке" +// @Param approver_id query integer false "Фильтр по согласующему" +// @Param status query string false "Фильтр по статусу (pending, waiting, approved, rejected, cancelled_any_of)" +// @Success 200 {object} typescore.ApiResponseBase "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/approval-steps [get] +func (s *ApprovalStepsReg) GetApprovalStepsListHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + queryParams := r.URL.Query() + + stepParams := &typescore.ApprovalStep{} + offset, limit, likeFields, errW := utilscore.ParseParamsGetRequest(queryParams, stepParams) + if errW != nil { + return nil, errW + } + + options := typescore.ListDbOptions{ + Filtering: stepParams, + Offset: offset, + Limit: limit, + LikeFields: likeFields, + } + + ctx := context.Background() + stepsDbLst, total, errW := s.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, options) + if errW != nil { + return nil, errW + } + + // 🚀 Подгружаем связанные данные + for _, step := range stepsDbLst { + s.enrichStep(ctx, step, false) + } + + return &typescore.ApiResponseBase{ + TotalCount: total, + Data: stepsDbLst, + }, nil +} + +// GetApprovalStepByIDHandler Получение шага по ID +// @Summary Получение шага по ID +// @Description Получение детальной информации о шаге согласования по его ID +// @Tags approval-steps +// @Accept json +// @Produce json +// @Param id path integer true "ID шага" +// @Success 200 {object} typescore.ApprovalStep "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 404 {object} handlers.ErrorResponse "Шаг не найден" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/approval-steps/{id} [get] +func (s *ApprovalStepsReg) GetApprovalStepByIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + idStr := chi.URLParam(r, "id") + if idStr == "" { + return nil, errors.New("step id is required") + } + + id, err := strconv.ParseUint(idStr, 10, 64) + if err != nil { + return nil, errors.New("invalid step id") + } + + ctx := context.Background() + steps, _, err := s.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalStep{ID: &id}, + }) + if err != nil { + return nil, err + } + if len(steps) == 0 { + return nil, errors.New("approval step not found") + } + + step := steps[0] + s.enrichStep(ctx, step, true) + + return step, nil +} + +// GetStepsByApprovalIDHandler Получение всех шагов для заявки +// @Summary Получение шагов по заявке +// @Description Получение списка всех шагов согласования для указанной заявки, отсортированных по step_order +// @Tags approval-steps +// @Accept json +// @Produce json +// @Param approval_id path integer true "ID заявки" +// @Success 200 {object} typescore.ApiResponseBase "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 404 {object} handlers.ErrorResponse "Заявка не найдена" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/approval-steps/by-approval/{approval_id} [get] +func (s *ApprovalStepsReg) GetStepsByApprovalIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + approvalIDStr := chi.URLParam(r, "approval_id") + if approvalIDStr == "" { + return nil, errors.New("approval_id is required") + } + + approvalID, err := strconv.ParseUint(approvalIDStr, 10, 64) + if err != nil { + return nil, errors.New("invalid approval_id") + } + + ctx := context.Background() + + // Проверяем, что заявка существует + approval, err := s.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID) + if err != nil { + return nil, err + } + if approval == nil { + return nil, errors.New("approval not found") + } + + steps, _, err := s.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalStep{ApprovalID: &approvalID}, + }) + if err != nil { + return nil, err + } + + // Сортируем по step_order + sortStepsByOrder(steps) + + // Подгружаем связанные данные + for _, step := range steps { + s.enrichStep(ctx, step, false) + } + + return &typescore.ApiResponseBase{ + TotalCount: uint64(len(steps)), + Data: steps, + }, nil +} + +// CreateApprovalStepHandler Создание шага согласования +// @Summary Создание шага +// @Description Создание нового шага согласования для заявки +// @Tags approval-steps +// @Accept json +// @Produce json +// @Param request body typescore.ApprovalStep true "Данные шага" +// @Success 200 {object} typescore.ApprovalStep "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 404 {object} handlers.ErrorResponse "Заявка или согласующий не найдены" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/approval-steps [post] +func (s *ApprovalStepsReg) CreateApprovalStepHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + defer r.Body.Close() + + body, err := io.ReadAll(r.Body) + if err != nil { + logrus.Error("🛑 CreateApprovalStepHandler: ReadAll error:", err) + return nil, err + } + + var req typescore.ApprovalStep + if err := json.Unmarshal(body, &req); err != nil { + return nil, errors.New("invalid request body") + } + + // Валидация обязательных полей + if req.ApprovalID == nil { + return nil, errors.New("approval_id is required") + } + if req.ApproverID == nil { + return nil, errors.New("approver_id is required") + } + if req.StepOrder == nil { + return nil, errors.New("step_order is required") + } + + ctx := context.Background() + + // Проверяем существование заявки + approval, err := s.ipc.Database.Approval.GetApprovalByIDDB(ctx, *req.ApprovalID) + if err != nil { + return nil, err + } + if approval == nil { + return nil, errors.New("approval not found") + } + + // 🛡 Можно добавлять шаги только к заявкам в статусе pending + if approval.Status == nil || *approval.Status != "pending" { + return nil, errors.New("can only add steps to pending approvals") + } + + // Проверяем существование согласующего + approver, err := s.ipc.Database.User.GetUserByIDDB(ctx, *req.ApproverID) + if err != nil { + return nil, err + } + if approver == nil { + return nil, errors.New("approver user not found") + } + + // Проверяем, что пользователь не заблокирован и не уволен + if approver.IsBlocked != nil && *approver.IsBlocked { + return nil, errors.New("approver user is blocked") + } + if approver.IsFired != nil && *approver.IsFired { + return nil, errors.New("approver user is fired") + } + + // Устанавливаем значения по умолчанию + if req.Status == nil { + defaultStatus := "waiting" + req.Status = &defaultStatus + } + + // Создаём снимок имени согласующего + if approver.FullName != nil && req.ApproverNameSnapshot == nil { + req.ApproverNameSnapshot = approver.FullName + } + + createdStep, _, err := s.ipc.Database.ApprovalStep.CreateApprovalStepDB(ctx, nil, &req, true) + if err != nil { + return nil, err + } + + s.enrichStep(ctx, createdStep, false) + + return createdStep, nil +} + +// UpdateApprovalStepHandler Обновление шага +// @Summary Обновление шага +// @Description Обновление данных шага согласования (статус, комментарий) +// @Tags approval-steps +// @Accept json +// @Produce json +// @Param request body typescore.ApprovalStep true "Данные шага" +// @Success 200 {object} typescore.ApprovalStep "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 404 {object} handlers.ErrorResponse "Шаг не найден" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/approval-steps [put] +func (s *ApprovalStepsReg) UpdateApprovalStepHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + defer r.Body.Close() + + body, err := io.ReadAll(r.Body) + if err != nil { + logrus.Error("🛑 UpdateApprovalStepHandler: ReadAll error:", err) + return nil, err + } + + var req typescore.ApprovalStep + if err := json.Unmarshal(body, &req); err != nil { + return nil, errors.New("invalid request body") + } + + if req.ID == nil { + return nil, errors.New("step id is required") + } + + ctx := context.Background() + + // Проверяем, что шаг существует + existingSteps, _, err := s.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalStep{ID: req.ID}, + }) + if err != nil { + return nil, err + } + if len(existingSteps) == 0 { + return nil, errors.New("approval step not found") + } + existing := existingSteps[0] + + // 🛡 Если обновляется статус — проверяем валидность перехода + if req.Status != nil && existing.Status != nil { + if !isValidStepStatusTransition(*existing.Status, *req.Status) { + return nil, errors.New("invalid status transition from " + *existing.Status + " to " + *req.Status) + } + } + + updatedStep, _, err := s.ipc.Database.ApprovalStep.UpdateApprovalStepDB(ctx, nil, &req, true) + if err != nil { + return nil, err + } + + s.enrichStep(ctx, updatedStep, false) + + return updatedStep, nil +} + +// DeleteApprovalStepHandler Удаление шага +// @Summary Удаление шага +// @Description Удаление шага согласования (только для заявок в статусе pending) +// @Tags approval-steps +// @Accept json +// @Produce json +// @Param request body typescore.ApprovalStep true "ID шага для удаления" +// @Success 200 {object} bool "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 403 {object} handlers.ErrorResponse "Нельзя удалить шаг завершённой заявки" +// @Failure 404 {object} handlers.ErrorResponse "Шаг не найден" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/approval-steps [delete] +func (s *ApprovalStepsReg) DeleteApprovalStepHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + defer r.Body.Close() + + body, err := io.ReadAll(r.Body) + if err != nil { + logrus.Error("🛑 DeleteApprovalStepHandler: ReadAll error:", err) + return nil, err + } + + var req typescore.ApprovalStep + if err := json.Unmarshal(body, &req); err != nil { + return nil, errors.New("invalid request body") + } + + if req.ID == nil { + return nil, errors.New("step id is required") + } + + ctx := context.Background() + + // Проверяем, что шаг существует + existingSteps, _, err := s.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalStep{ID: req.ID}, + }) + if err != nil { + return nil, err + } + if len(existingSteps) == 0 { + return nil, errors.New("approval step not found") + } + existing := existingSteps[0] + + // Проверяем заявку + if existing.ApprovalID != nil { + approval, err := s.ipc.Database.Approval.GetApprovalByIDDB(ctx, *existing.ApprovalID) + if err != nil { + return nil, err + } + if approval == nil { + return nil, errors.New("approval not found") + } + + // 🛡 Можно удалять шаги только у заявок в статусе pending + if approval.Status == nil || *approval.Status != "pending" { + return nil, errors.New("can only delete steps from pending approvals") + } + } + + // 🛡 Нельзя удалять уже обработанные шаги + if existing.Status != nil { + if *existing.Status == "approved" || *existing.Status == "rejected" { + return nil, errors.New("cannot delete completed steps") + } + } + + err = s.ipc.Database.ApprovalStep.DeleteApprovalStepDB(ctx, &req) + if err != nil { + return nil, err + } + + return true, nil +} + +// enrichStep подгружает связанные данные для шага +func (s *ApprovalStepsReg) enrichStep(ctx context.Context, step *typescore.ApprovalStep, loadApproval bool) { + if step == nil { + return + } + + // Подгружаем согласующего + if step.ApproverID != nil { + approver, err := s.ipc.Database.User.GetUserByIDDB(ctx, *step.ApproverID) + if err == nil && approver != nil { + step.Approver = approver + } + } + + // Подгружаем заявку (только для детального просмотра) + if loadApproval && step.ApprovalID != nil { + approval, err := s.ipc.Database.Approval.GetApprovalByIDDB(ctx, *step.ApprovalID) + if err == nil && approval != nil { + step.Approval = approval + } + } +} + +// sortStepsByOrder сортирует шаги по step_order +func sortStepsByOrder(steps []*typescore.ApprovalStep) { + for i := 0; i < len(steps); i++ { + for j := i + 1; j < len(steps); j++ { + if steps[i].StepOrder != nil && steps[j].StepOrder != nil { + if *steps[i].StepOrder > *steps[j].StepOrder { + steps[i], steps[j] = steps[j], steps[i] + } + } + } + } +} + +// isValidStepStatusTransition проверяет валидность перехода между статусами шага +func isValidStepStatusTransition(from, to string) bool { + validTransitions := map[string][]string{ + "pending": {"approved", "rejected", "cancelled_any_of"}, + "waiting": {"pending", "cancelled_any_of"}, + "approved": {}, // финальный статус + "rejected": {}, // финальный статус + "cancelled_any_of": {}, // финальный статус + } + + allowed, exists := validTransitions[from] + if !exists { + return false + } + + for _, status := range allowed { + if status == to { + return true + } + } + + return false +} diff --git a/service/rest_admin_service/handlers/approval_steps/routes.go b/service/rest_admin_service/handlers/approval_steps/routes.go new file mode 100644 index 0000000..e25e258 --- /dev/null +++ b/service/rest_admin_service/handlers/approval_steps/routes.go @@ -0,0 +1,43 @@ +package approvalstepshandler + +import ( + "bitrix_balancer_api/rest_admin_service/handlers" + typesm "bitrix_balancer_api/rest_admin_service/types" + "net/http" + + "github.com/go-chi/chi/v5" +) + +type ApprovalStepsReg struct { + ipc *typesm.InternalProviderControl +} + +// RegisterApprovalStepRoutes регистрирует маршруты для группы approval-steps +func RegisterApprovalStepRoutes( + r chi.Router, + ipc *typesm.InternalProviderControl, +) error { + s := &ApprovalStepsReg{ + ipc: ipc, + } + + r.Route("/api/approval-steps", func(r chi.Router) { + r.Use(handlers.AccessCodeVerifier(ipc.Config)) + r.Use(handlers.JWTVerifier(ipc.Config, ipc.Database.Admin, ipc.RedisClient)) + + handlers.RegisterRoute(r, http.MethodGet, "/", s.GetApprovalStepsListHandler) + handlers.RegisterRoute(r, http.MethodPost, "/", s.CreateApprovalStepHandler) + handlers.RegisterRoute(r, http.MethodPut, "/", s.UpdateApprovalStepHandler) + handlers.RegisterRoute(r, http.MethodDelete, "/", s.DeleteApprovalStepHandler) + + r.Get("/{id}", handlers.WrapHandlerF(handlers.WrapHandlerParams{ + HandlerFunc: s.GetApprovalStepByIDHandler, + })) + + r.Get("/by-approval/{approval_id}", handlers.WrapHandlerF(handlers.WrapHandlerParams{ + HandlerFunc: s.GetStepsByApprovalIDHandler, + })) + }) + + return nil +} diff --git a/service/rest_admin_service/handlers/approvals/handlers.go b/service/rest_admin_service/handlers/approvals/handlers.go new file mode 100644 index 0000000..8d33b40 --- /dev/null +++ b/service/rest_admin_service/handlers/approvals/handlers.go @@ -0,0 +1,372 @@ +package approvalshandler + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/core/utilscore" + "context" + "encoding/json" + "errors" + "github.com/sirupsen/logrus" + "io" + "net/http" + "strconv" + "time" + + "github.com/go-chi/chi/v5" +) + +// GetApprovalsListHandler Получение списка заявок +// @Summary Получение списка заявок +// @Description Получение списка заявок с пагинацией и фильтрацией +// @Tags approvals +// @Accept json +// @Produce json +// @Param offset query integer false "Смещение для пагинации" +// @Param limit query integer false "Количество записей на странице" +// @Param status query string false "Фильтр по статусу (pending, approved, rejected, revoked, revision)" +// @Param initiator_id query integer false "Фильтр по инициатору" +// @Param topic_id query integer false "Фильтр по теме" +// @Param department_id query integer false "Фильтр по отделу" +// @Success 200 {object} typescore.ApiResponseBase "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/approvals [get] +func (s *ApprovalsReg) GetApprovalsListHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + queryParams := r.URL.Query() + + approvalParams := &typescore.Approval{} + offset, limit, likeFields, errW := utilscore.ParseParamsGetRequest(queryParams, approvalParams) + if errW != nil { + return nil, errW + } + + options := typescore.ListDbOptions{ + Filtering: approvalParams, + Offset: offset, + Limit: limit, + LikeFields: likeFields, + } + + ctx := context.Background() + approvalsDbLst, total, errW := s.ipc.Database.Approval.GetApprovalsListDB(ctx, options) + if errW != nil { + return nil, errW + } + + // 🚀 Подгружаем связанные данные + for _, approval := range approvalsDbLst { + s.enrichApproval(ctx, approval, false) + } + + return &typescore.ApiResponseBase{ + TotalCount: total, + Data: approvalsDbLst, + }, nil +} + +// GetApprovalByIDHandler Получение заявки по ID +// @Summary Получение заявки по ID +// @Description Получение детальной информации о заявке по её ID со всеми связанными данными +// @Tags approvals +// @Accept json +// @Produce json +// @Param id path integer true "ID заявки" +// @Success 200 {object} typescore.Approval "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 404 {object} handlers.ErrorResponse "Заявка не найдена" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/approvals/{id} [get] +func (s *ApprovalsReg) GetApprovalByIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + idStr := chi.URLParam(r, "id") + if idStr == "" { + return nil, errors.New("approval id is required") + } + + id, err := strconv.ParseUint(idStr, 10, 64) + if err != nil { + return nil, errors.New("invalid approval id") + } + + ctx := context.Background() + approval, err := s.ipc.Database.Approval.GetApprovalByIDDB(ctx, id) + if err != nil { + return nil, err + } + if approval == nil { + return nil, errors.New("approval not found") + } + + // 🚀 Подгружаем все связанные данные + s.enrichApproval(ctx, approval, true) + + return approval, nil +} + +// UpdateApprovalHandler Обновление заявки +// @Summary Обновление заявки +// @Description Обновление данных заявки (статус, комментарии и т.д.) +// @Tags approvals +// @Accept json +// @Produce json +// @Param request body typescore.Approval true "Данные заявки" +// @Success 200 {object} typescore.Approval "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 404 {object} handlers.ErrorResponse "Заявка не найдена" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/approvals [put] +func (s *ApprovalsReg) UpdateApprovalHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + defer r.Body.Close() + + body, err := io.ReadAll(r.Body) + if err != nil { + logrus.Error("🛑 UpdateApprovalHandler: ReadAll error:", err) + return nil, err + } + + var req typescore.Approval + if err := json.Unmarshal(body, &req); err != nil { + return nil, errors.New("invalid request body") + } + + if req.ID == nil { + return nil, errors.New("approval id is required") + } + + ctx := context.Background() + + // Проверяем, что заявка существует + existingApproval, err := s.ipc.Database.Approval.GetApprovalByIDDB(ctx, *req.ID) + if err != nil { + return nil, err + } + if existingApproval == nil { + return nil, errors.New("approval not found") + } + + // 🛡 Если обновляется статус — проверяем валидность перехода + if req.Status != nil && existingApproval.Status != nil { + if !isValidStatusTransition(*existingApproval.Status, *req.Status) { + return nil, errors.New("invalid status transition from " + *existingApproval.Status + " to " + *req.Status) + } + } + + updatedApproval, _, err := s.ipc.Database.Approval.UpdateApprovalDB(ctx, nil, &req, true) + if err != nil { + return nil, err + } + + s.enrichApproval(ctx, updatedApproval, true) + + return updatedApproval, nil +} + +// DeleteApprovalHandler Удаление заявки +// @Summary Удаление заявки +// @Description Удаление заявки (только для черновиков) +// @Tags approvals +// @Accept json +// @Produce json +// @Param request body typescore.Approval true "ID заявки для удаления" +// @Success 200 {object} bool "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 403 {object} handlers.ErrorResponse "Нельзя удалить не-черновую заявку" +// @Failure 404 {object} handlers.ErrorResponse "Заявка не найдена" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/approvals [delete] +func (s *ApprovalsReg) DeleteApprovalHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + defer r.Body.Close() + + body, err := io.ReadAll(r.Body) + if err != nil { + logrus.Error("🛑 DeleteApprovalHandler: ReadAll error:", err) + return nil, err + } + + var req typescore.Approval + if err := json.Unmarshal(body, &req); err != nil { + return nil, errors.New("invalid request body") + } + + if req.ID == nil { + return nil, errors.New("approval id is required") + } + + ctx := context.Background() + + // Проверяем, что заявка существует + existingApproval, err := s.ipc.Database.Approval.GetApprovalByIDDB(ctx, *req.ID) + if err != nil { + return nil, err + } + if existingApproval == nil { + return nil, errors.New("approval not found") + } + + // 🛡 Можно удалять только черновики + if existingApproval.Status == nil || *existingApproval.Status != "draft" { + return nil, errors.New("only draft approvals can be deleted") + } + + err = s.ipc.Database.Approval.DeleteApprovalDB(ctx, &req) + if err != nil { + return nil, err + } + + return true, nil +} + +// GetApprovalsForReportHandler Получение заявок для отчёта +// @Summary Получение заявок для отчёта +// @Description Получение списка заявок для отчёта с учётом периода и доступа пользователя +// @Tags approvals +// @Accept json +// @Produce json +// @Param user_id query integer false "ID пользователя (если не указан - все заявки)" +// @Param date_from query string false "Начальная дата (YYYY-MM-DD)" +// @Param date_to query string false "Конечная дата (YYYY-MM-DD)" +// @Param all_access query boolean false "Полный доступ (игнорировать фильтрацию по пользователю)" +// @Success 200 {object} typescore.ApiResponseBase "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/approvals/report [get] +func (s *ApprovalsReg) GetApprovalsForReportHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + queryParams := r.URL.Query() + + filter := typescore.ReportFilter{} + + // Парсим user_id + if userIDStr := queryParams.Get("user_id"); userIDStr != "" { + userID, err := strconv.ParseUint(userIDStr, 10, 64) + if err != nil { + return nil, errors.New("invalid user_id") + } + filter.UserID = &userID + } + + // Парсим даты + if dateFromStr := queryParams.Get("date_from"); dateFromStr != "" { + dateFrom, err := time.Parse("2006-01-02", dateFromStr) + if err != nil { + return nil, errors.New("invalid date_from format, use YYYY-MM-DD") + } + filter.DateFrom = &dateFrom + } + + if dateToStr := queryParams.Get("date_to"); dateToStr != "" { + dateTo, err := time.Parse("2006-01-02", dateToStr) + if err != nil { + return nil, errors.New("invalid date_to format, use YYYY-MM-DD") + } + filter.DateTo = &dateTo + } + + // Парсим all_access + if allAccessStr := queryParams.Get("all_access"); allAccessStr == "true" { + filter.AllAccess = true + } + + ctx := context.Background() + approvals, err := s.ipc.Database.Approval.GetApprovalsForReportDB(ctx, filter) + if err != nil { + return nil, err + } + + // Подгружаем связанные данные + for _, approval := range approvals { + s.enrichApproval(ctx, approval, false) + } + + return &typescore.ApiResponseBase{ + TotalCount: uint64(len(approvals)), + Data: approvals, + }, nil +} + +// enrichApproval подгружает связанные данные для заявки +func (s *ApprovalsReg) enrichApproval(ctx context.Context, approval *typescore.Approval, loadSteps bool) { + if approval == nil { + return + } + + // Подгружаем инициатора + if approval.InitiatorID != nil { + initiator, err := s.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID) + if err == nil && initiator != nil { + approval.Initiator = initiator + } + } + + // Подгружаем тему + if approval.TopicID != nil { + topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID) + if err == nil && topic != nil { + approval.Topic = topic + } + } + + // Подгружаем отдел + if approval.DepartmentID != nil { + department, err := s.ipc.Database.Department.GetDepartmentByIDDB(ctx, *approval.DepartmentID) + if err == nil && department != nil { + approval.Department = department + } + } + + // Подгружаем того, кто отозвал (если есть) + if approval.RevokedByID != nil { + revokedBy, err := s.ipc.Database.User.GetUserByIDDB(ctx, *approval.RevokedByID) + if err == nil && revokedBy != nil { + approval.RevokedBy = revokedBy + } + } + + // Подгружаем файлы + files, err := s.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID) + if err == nil { + approval.Files = files + } + + // Подгружаем шаги согласования (только для детального просмотра) + if loadSteps { + steps, _, err := s.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalStep{ApprovalID: approval.ID}, + }) + if err == nil { + // Подгружаем информацию о согласующих для каждого шага + for _, step := range steps { + if step.ApproverID != nil { + approver, err := s.ipc.Database.User.GetUserByIDDB(ctx, *step.ApproverID) + if err == nil && approver != nil { + step.Approver = approver + } + } + } + approval.Steps = steps + } + } +} + +// isValidStatusTransition проверяет валидность перехода между статусами +func isValidStatusTransition(from, to string) bool { + validTransitions := map[string][]string{ + "draft": {"pending", "approved", "rejected"}, + "pending": {"approved", "rejected", "revoked", "revision"}, + "approved": {"revoked", "revision"}, + "rejected": {"pending", "revision"}, + "revoked": {"pending"}, + "revision": {"pending"}, + } + + allowed, exists := validTransitions[from] + if !exists { + return false + } + + for _, status := range allowed { + if status == to { + return true + } + } + + return false +} diff --git a/service/rest_admin_service/handlers/approvals/routes.go b/service/rest_admin_service/handlers/approvals/routes.go new file mode 100644 index 0000000..c815cb8 --- /dev/null +++ b/service/rest_admin_service/handlers/approvals/routes.go @@ -0,0 +1,41 @@ +package approvalshandler + +import ( + "bitrix_balancer_api/rest_admin_service/handlers" + typesm "bitrix_balancer_api/rest_admin_service/types" + "net/http" + + "github.com/go-chi/chi/v5" +) + +type ApprovalsReg struct { + ipc *typesm.InternalProviderControl +} + +// RegisterApprovalRoutes регистрирует маршруты для группы approvals +func RegisterApprovalRoutes( + r chi.Router, + ipc *typesm.InternalProviderControl, +) error { + s := &ApprovalsReg{ + ipc: ipc, + } + + r.Route("/api/approvals", func(r chi.Router) { + r.Use(handlers.AccessCodeVerifier(ipc.Config)) + r.Use(handlers.JWTVerifier(ipc.Config, ipc.Database.Admin, ipc.RedisClient)) + + handlers.RegisterRoute(r, http.MethodGet, "/", s.GetApprovalsListHandler) + handlers.RegisterRoute(r, http.MethodPut, "/", s.UpdateApprovalHandler) + handlers.RegisterRoute(r, http.MethodDelete, "/", s.DeleteApprovalHandler) + + // Отчёты + handlers.RegisterRoute(r, http.MethodGet, "/report", s.GetApprovalsForReportHandler) + + r.Get("/{id}", handlers.WrapHandlerF(handlers.WrapHandlerParams{ + HandlerFunc: s.GetApprovalByIDHandler, + })) + }) + + return nil +} diff --git a/service/rest_admin_service/handlers/auth/handlers.go b/service/rest_admin_service/handlers/auth/handlers.go new file mode 100644 index 0000000..4dcb518 --- /dev/null +++ b/service/rest_admin_service/handlers/auth/handlers.go @@ -0,0 +1,184 @@ +package authhandler + +import ( + "bitrix_balancer_api/core/securecore" + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/core/utilscore" + "bitrix_balancer_api/core/variables" + "bitrix_balancer_api/rest_admin_service/handlers" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "time" + + "github.com/sirupsen/logrus" +) + +// TokenAuthHandler +// @Summary Авторизация при помощи JWT-токена +// @Description Авторизация при помощи JWT-токена +// @Tags auth +// @Accept json +// @Produce json +// @Success 200 {object} typescore.AuthHandlerResponse +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/auth/token [post] +func (s *AuthReg) TokenAuthHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + ctx := r.Context() + defer r.Body.Close() + + userID, err := handlers.GetIDFromContext(ctx) + if err != nil { + return nil, err + } + userObjAuthBody := &typescore.Admin{ + ID: &userID, + } + + usersList, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{Filtering: userObjAuthBody}) + if err != nil { + return nil, err + } + + if len(usersList) == 0 { + return nil, errors.New("no users found") + } + + if usersList[0].IsBlocked != nil && *usersList[0].IsBlocked { + return nil, errors.New("user is blocked") + } + + tokens, err := securecore.GenerateTokenJWT("", *usersList[0].ID, r.RemoteAddr, s.ipc.Config.Secrets.AuthJWT.UserSecret, s.ipc.Config.Secrets.AuthJWT.JwtUserSessionLengthHours) + if err != nil { + return nil, err + } + + return &typescore.AuthHandlerResponse{Token: &tokens}, nil +} + +// LoginByPasswordHandler авторизация с помощью связки логин-пароль +// @Summary авторизация с помощью связки логин-пароль +// @Description авторизация с помощью связки логин-пароль +// @Tags auth +// @Accept json +// @Produce json +// @Param request body typescore.AuthReqAccount true "Запрос" +// @Success 200 {object} typescore.AuthHandlerResponse +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/auth/login [post] +func (s *AuthReg) LoginByPasswordHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + defer r.Body.Close() + ctx := r.Context() + + body, err := io.ReadAll(r.Body) + if err != nil { + logrus.Error("🛑 error LoginByPassword: ReadAll: ", err) + return nil, err + } + + if len(body) == 0 { + return nil, errors.New("body is empty") + } + + deviceID := r.Header.Get("x-device-id") + if deviceID == "" { + return nil, errors.New("device id is empty") + } + + var req typescore.AuthReqAccount + if err := json.Unmarshal(body, &req); err != nil { + return nil, err + } + + tokens, err := s.loginAcc(ctx, req.Login, req.Password, utilscore.GetClientIP(r), deviceID) + if err != nil { + return nil, err + } + if tokens == nil { + return nil, errors.New("token is nil") + } + + return &typescore.AuthHandlerResponse{Token: tokens}, nil +} + +func (s *AuthReg) loginAcc(ctx context.Context, login, password *string, ip, deviceID string) (*string, error) { + usersList, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{Filtering: &typescore.Admin{Login: login}}) + if err != nil { + return nil, err + } + + if usersList == nil || len(usersList) == 0 { + return nil, errors.New("no users found") + } + + loggedUser := usersList[0] + if password != nil && *password != "" { + validPass := securecore.CheckPasswordHash(password, loggedUser.PasswordHash) + if !validPass { + return nil, errors.New("invalid login or password") + } + } + + if loggedUser.IsBlocked != nil && *loggedUser.IsBlocked { + return nil, errors.New("user is blocked") + } + + lastLogin, err := time.Parse("2006-01-02 15:04:05", time.Now().UTC().Format("2006-01-02 15:04:05")) + if err != nil { + return nil, err + } + + keyPath := fmt.Sprintf("%s:admin:%d", variables.RedisPathUserAuthSessions, *loggedUser.ID) + sessionJSON, err := s.ipc.RedisClient.Get(ctx, keyPath) + if err != nil { + return nil, err + } + // Создаем переменную для десериализации + var session typescore.UsersSessions + + if sessionJSON != "" { + // Парсим JSON + if err := json.Unmarshal([]byte(sessionJSON), &session); err != nil { + return nil, err + } + } else { + session = typescore.UsersSessions{ + UserID: loggedUser.ID, + LastIP: ip, + } + } + + foundDevice := securecore.FindDeviceID(session.AuthorizedDevices, deviceID) + if !foundDevice { + now := time.Now().UTC() + session.AuthorizedDevices = append(session.AuthorizedDevices, typescore.DeviceList{ + DeviceID: deviceID, + CreatedAt: &now, + }) + + err := s.ipc.RedisClient.Set(ctx, fmt.Sprintf("%s:admin:%d", variables.RedisPathUserAuthSessions, *loggedUser.ID), session, 0) + if err != nil { + return nil, err + } + } + + loggedUser.LastLogin = &lastLogin + loggedUser.LastIPLogin = &ip + + upUser, _, err := s.ipc.Database.Admin.UpdateAdminDB(nil, loggedUser, true) + if err != nil { + return nil, err + } + + tokens, err := securecore.GenerateTokenJWT("", *upUser.ID, ip, s.ipc.Config.Secrets.AuthJWT.AdminSecret, s.ipc.Config.Secrets.AuthJWT.JwtAdminSessionLengthHours) + if err != nil { + return nil, err + } + + return &tokens, nil +} diff --git a/service/rest_admin_service/handlers/auth/routes.go b/service/rest_admin_service/handlers/auth/routes.go new file mode 100644 index 0000000..eb53fb9 --- /dev/null +++ b/service/rest_admin_service/handlers/auth/routes.go @@ -0,0 +1,39 @@ +package authhandler + +import ( + "bitrix_balancer_api/rest_admin_service/handlers" + typesm "bitrix_balancer_api/rest_admin_service/types" + "github.com/go-chi/chi/v5" + "net/http" +) + +const ( + oauthURLogin = "/auth/login" // вход по паролю +) + +type AuthReg struct { + ipc *typesm.InternalProviderControl +} + +// RegisterAuthRoutes регистрирует маршруты для группы auth +func RegisterAuthRoutes( + r chi.Router, + ipc *typesm.InternalProviderControl, +) error { + s := &AuthReg{ + ipc: ipc, + } + + r.Route("/api", func(r chi.Router) { + r.Use(handlers.AccessCodeVerifier(ipc.Config)) + + handlers.RegisterRoute(r, http.MethodPost, oauthURLogin, s.LoginByPasswordHandler) + }) + + r.Route("/api/auth/token", func(r chi.Router) { + r.Use(handlers.JWTVerifier(ipc.Config, ipc.Database.Admin, s.ipc.RedisClient)) + handlers.RegisterRoute(r, http.MethodPost, "/", s.TokenAuthHandler) + }) + + return nil +} diff --git a/service/rest_admin_service/handlers/departments/handlers.go b/service/rest_admin_service/handlers/departments/handlers.go new file mode 100644 index 0000000..1be63be --- /dev/null +++ b/service/rest_admin_service/handlers/departments/handlers.go @@ -0,0 +1,262 @@ +package departmentshandler + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/core/utilscore" + "context" + "encoding/json" + "errors" + "github.com/sirupsen/logrus" + "io" + "net/http" + "strconv" + + "github.com/go-chi/chi/v5" +) + +// GetDepartmentsListHandler Получение списка отделов +// @Summary Получение списка отделов +// @Description Получение списка отделов с пагинацией и фильтрацией +// @Tags departments +// @Accept json +// @Produce json +// @Param offset query integer false "Смещение для пагинации" +// @Param limit query integer false "Количество записей на странице" +// @Param is_active query boolean false "Фильтр по активности" +// @Success 200 {object} typescore.ApiResponseBase "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/departments [get] +func (s *DepartmentsReg) GetDepartmentsListHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + queryParams := r.URL.Query() + + departmentParams := &typescore.Department{} + offset, limit, likeFields, errW := utilscore.ParseParamsGetRequest(queryParams, departmentParams) + if errW != nil { + return nil, errW + } + + options := typescore.ListDbOptions{ + Filtering: departmentParams, + Offset: offset, + Limit: limit, + LikeFields: likeFields, + } + + ctx := context.Background() + departmentsDbLst, total, errW := s.ipc.Database.Department.GetDepartmentsListDB(ctx, options) + if errW != nil { + return nil, errW + } + + return &typescore.ApiResponseBase{ + TotalCount: total, + Data: departmentsDbLst, + }, nil +} + +// GetDepartmentByIDHandler Получение отдела по ID +// @Summary Получение отдела по ID +// @Description Получение детальной информации об отделе по его ID +// @Tags departments +// @Accept json +// @Produce json +// @Param id path integer true "ID отдела" +// @Success 200 {object} typescore.Department "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 404 {object} handlers.ErrorResponse "Отдел не найден" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/departments/{id} [get] +func (s *DepartmentsReg) GetDepartmentByIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + idStr := chi.URLParam(r, "id") + if idStr == "" { + return nil, errors.New("department id is required") + } + + id, err := strconv.ParseUint(idStr, 10, 64) + if err != nil { + return nil, errors.New("invalid department id") + } + + ctx := context.Background() + department, err := s.ipc.Database.Department.GetDepartmentByIDDB(ctx, id) + if err != nil { + return nil, err + } + + if department == nil { + return nil, errors.New("department not found") + } + + return department, nil +} + +// CreateDepartmentHandler Создание отдела +// @Summary Создание отдела +// @Description Создание нового отдела +// @Tags departments +// @Accept json +// @Produce json +// @Param request body typescore.Department true "Данные отдела" +// @Success 200 {object} typescore.Department "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/departments [post] +func (s *DepartmentsReg) CreateDepartmentHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + defer r.Body.Close() + + body, err := io.ReadAll(r.Body) + if err != nil { + logrus.Error("🛑 CreateDepartmentHandler: ReadAll error:", err) + return nil, err + } + + var req typescore.Department + if err := json.Unmarshal(body, &req); err != nil { + return nil, errors.New("invalid request body") + } + + // Валидация обязательных полей + if req.Name == nil || *req.Name == "" { + return nil, errors.New("department name is required") + } + if req.Code == nil || *req.Code == "" { + return nil, errors.New("department code is required") + } + + // Проверяем, что код уникален + ctx := context.Background() + existingDepts, _, err := s.ipc.Database.Department.GetDepartmentsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.Department{Code: req.Code}, + }) + if err != nil { + return nil, err + } + if len(existingDepts) > 0 { + return nil, errors.New("department code already exists") + } + + // Устанавливаем is_active по умолчанию, если не указано + if req.IsActive == nil { + isActive := true + req.IsActive = &isActive + } + + createdDept, _, err := s.ipc.Database.Department.CreateDepartmentDB(ctx, nil, &req, true) + if err != nil { + return nil, err + } + + return createdDept, nil +} + +// UpdateDepartmentHandler Обновление отдела +// @Summary Обновление отдела +// @Description Обновление данных существующего отдела +// @Tags departments +// @Accept json +// @Produce json +// @Param request body typescore.Department true "Данные отдела" +// @Success 200 {object} typescore.Department "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 404 {object} handlers.ErrorResponse "Отдел не найден" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/departments [put] +func (s *DepartmentsReg) UpdateDepartmentHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + defer r.Body.Close() + + body, err := io.ReadAll(r.Body) + if err != nil { + logrus.Error("🛑 UpdateDepartmentHandler: ReadAll error:", err) + return nil, err + } + + var req typescore.Department + if err := json.Unmarshal(body, &req); err != nil { + return nil, errors.New("invalid request body") + } + + if req.ID == nil { + return nil, errors.New("department id is required") + } + + // Проверяем, что отдел существует + ctx := context.Background() + existingDept, err := s.ipc.Database.Department.GetDepartmentByIDDB(ctx, *req.ID) + if err != nil { + return nil, err + } + if existingDept == nil { + return nil, errors.New("department not found") + } + + // Если обновляется код, проверяем уникальность + if req.Code != nil && *req.Code != "" { + if existingDept.Code == nil || *existingDept.Code != *req.Code { + existingDepts, _, err := s.ipc.Database.Department.GetDepartmentsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.Department{Code: req.Code}, + }) + if err != nil { + return nil, err + } + if len(existingDepts) > 0 { + return nil, errors.New("department code already exists") + } + } + } + + updatedDept, _, err := s.ipc.Database.Department.UpdateDepartmentDB(ctx, nil, &req, true) + if err != nil { + return nil, err + } + + return updatedDept, nil +} + +// DeleteDepartmentHandler Удаление отдела +// @Summary Удаление отдела +// @Description Удаление отдела по ID +// @Tags departments +// @Accept json +// @Produce json +// @Param request body typescore.Department true "ID отдела для удаления" +// @Success 200 {object} bool "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 404 {object} handlers.ErrorResponse "Отдел не найден" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/departments [delete] +func (s *DepartmentsReg) DeleteDepartmentHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + defer r.Body.Close() + + body, err := io.ReadAll(r.Body) + if err != nil { + logrus.Error("🛑 DeleteDepartmentHandler: ReadAll error:", err) + return nil, err + } + + var req typescore.Department + if err := json.Unmarshal(body, &req); err != nil { + return nil, errors.New("invalid request body") + } + + if req.ID == nil { + return nil, errors.New("department id is required") + } + + // Проверяем, что отдел существует + ctx := context.Background() + existingDept, err := s.ipc.Database.Department.GetDepartmentByIDDB(ctx, *req.ID) + if err != nil { + return nil, err + } + if existingDept == nil { + return nil, errors.New("department not found") + } + + err = s.ipc.Database.Department.DeleteDepartmentDB(ctx, &req) + if err != nil { + return nil, err + } + + return true, nil +} diff --git a/service/rest_admin_service/handlers/departments/routes.go b/service/rest_admin_service/handlers/departments/routes.go new file mode 100644 index 0000000..cc73fd9 --- /dev/null +++ b/service/rest_admin_service/handlers/departments/routes.go @@ -0,0 +1,47 @@ +package departmentshandler + +import ( + "bitrix_balancer_api/rest_admin_service/handlers" + typesm "bitrix_balancer_api/rest_admin_service/types" + "net/http" + + "github.com/go-chi/chi/v5" +) + +type DepartmentsReg struct { + ipc *typesm.InternalProviderControl +} + +// RegisterDepartmentRoutes регистрирует маршруты для группы departments +func RegisterDepartmentRoutes( + r chi.Router, + ipc *typesm.InternalProviderControl, +) error { + s := &DepartmentsReg{ + ipc: ipc, + } + + r.Route("/api/departments", func(r chi.Router) { + r.Use(handlers.AccessCodeVerifier(ipc.Config)) + r.Use(handlers.JWTVerifier(ipc.Config, ipc.Database.Admin, ipc.RedisClient)) + + // GET /api/departments - список отделов + handlers.RegisterRoute(r, http.MethodGet, "/", s.GetDepartmentsListHandler) + + // POST /api/departments - создание отдела + handlers.RegisterRoute(r, http.MethodPost, "/", s.CreateDepartmentHandler) + + // PUT /api/departments - обновление отдела + handlers.RegisterRoute(r, http.MethodPut, "/", s.UpdateDepartmentHandler) + + // DELETE /api/departments - удаление отдела + handlers.RegisterRoute(r, http.MethodDelete, "/", s.DeleteDepartmentHandler) + + // GET /api/departments/{id} - получение отдела по ID + r.Get("/{id}", handlers.WrapHandlerF(handlers.WrapHandlerParams{ + HandlerFunc: s.GetDepartmentByIDHandler, + })) + }) + + return nil +} diff --git a/service/rest_admin_service/handlers/permission/handlers.go b/service/rest_admin_service/handlers/permission/handlers.go new file mode 100644 index 0000000..e0ea51a --- /dev/null +++ b/service/rest_admin_service/handlers/permission/handlers.go @@ -0,0 +1,467 @@ +package permissionshandler + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/core/utilscore" + "context" + "encoding/json" + "errors" + "github.com/sirupsen/logrus" + "io" + "net/http" + "strconv" + + "github.com/go-chi/chi/v5" +) + +// GetPermissionsListHandler Получение списка прав +// @Summary Получение списка прав +// @Description Получение списка прав ролей с пагинацией и фильтрацией +// @Tags permissions +// @Accept json +// @Produce json +// @Param offset query integer false "Смещение для пагинации" +// @Param limit query integer false "Количество записей на странице" +// @Param role_id query integer false "Фильтр по роли" +// @Param action query string false "Фильтр по действию (create, read, update, delete, approve, revoke)" +// @Param topic_category_id query integer false "Фильтр по категории тем" +// @Param topic_id query integer false "Фильтр по теме" +// @Success 200 {object} typescore.ApiResponseBase "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/permissions [get] +func (s *PermissionsReg) GetPermissionsListHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + queryParams := r.URL.Query() + + permissionParams := &typescore.Permission{} + offset, limit, likeFields, errW := utilscore.ParseParamsGetRequest(queryParams, permissionParams) + if errW != nil { + return nil, errW + } + + options := typescore.ListDbOptions{ + Filtering: permissionParams, + Offset: offset, + Limit: limit, + LikeFields: likeFields, + } + + ctx := context.Background() + permissionsDbLst, total, errW := s.ipc.Database.Permission.GetPermissionsListDB(ctx, options) + if errW != nil { + return nil, errW + } + + // 🚀 Подгружаем связанные данные + for _, perm := range permissionsDbLst { + s.enrichPermission(ctx, perm) + } + + return &typescore.ApiResponseBase{ + TotalCount: total, + Data: permissionsDbLst, + }, nil +} + +// GetPermissionByIDHandler Получение права по ID +// @Summary Получение права по ID +// @Description Получение детальной информации о праве по его ID +// @Tags permissions +// @Accept json +// @Produce json +// @Param id path integer true "ID права" +// @Success 200 {object} typescore.Permission "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 404 {object} handlers.ErrorResponse "Право не найдено" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/permissions/{id} [get] +func (s *PermissionsReg) GetPermissionByIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + idStr := chi.URLParam(r, "id") + if idStr == "" { + return nil, errors.New("permission id is required") + } + + id, err := strconv.ParseUint(idStr, 10, 64) + if err != nil { + return nil, errors.New("invalid permission id") + } + + ctx := context.Background() + permissions, _, err := s.ipc.Database.Permission.GetPermissionsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.Permission{ID: &id}, + }) + if err != nil { + return nil, err + } + if len(permissions) == 0 { + return nil, errors.New("permission not found") + } + + permission := permissions[0] + s.enrichPermission(ctx, permission) + + return permission, nil +} + +// GetPermissionsByRoleIDHandler Получение всех прав для роли +// @Summary Получение прав по роли +// @Description Получение списка всех прав для указанной роли +// @Tags permissions +// @Accept json +// @Produce json +// @Param role_id path integer true "ID роли" +// @Success 200 {object} typescore.ApiResponseBase "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 404 {object} handlers.ErrorResponse "Роль не найдена" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/permissions/by-role/{role_id} [get] +func (s *PermissionsReg) GetPermissionsByRoleIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + roleIDStr := chi.URLParam(r, "role_id") + if roleIDStr == "" { + return nil, errors.New("role_id is required") + } + + roleID, err := strconv.ParseUint(roleIDStr, 10, 64) + if err != nil { + return nil, errors.New("invalid role_id") + } + + ctx := context.Background() + + // Проверяем, что роль существует + role, err := s.ipc.Database.Role.GetRoleByIDDB(ctx, roleID) + if err != nil { + return nil, err + } + if role == nil { + return nil, errors.New("role not found") + } + + permissions, _, err := s.ipc.Database.Permission.GetPermissionsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.Permission{RoleID: &roleID}, + }) + if err != nil { + return nil, err + } + + // Подгружаем связанные данные + for _, perm := range permissions { + s.enrichPermission(ctx, perm) + } + + return &typescore.ApiResponseBase{ + TotalCount: uint64(len(permissions)), + Data: permissions, + }, nil +} + +// CreatePermissionHandler Создание права +// @Summary Создание права +// @Description Назначение права на действие для роли +// @Tags permissions +// @Accept json +// @Produce json +// @Param request body typescore.Permission true "Данные права" +// @Success 200 {object} typescore.Permission "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 404 {object} handlers.ErrorResponse "Роль, категория или тема не найдены" +// @Failure 409 {object} handlers.ErrorResponse "Такое право уже существует" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/permissions [post] +func (s *PermissionsReg) CreatePermissionHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + defer r.Body.Close() + + body, err := io.ReadAll(r.Body) + if err != nil { + logrus.Error("🛑 CreatePermissionHandler: ReadAll error:", err) + return nil, err + } + + var req typescore.Permission + if err := json.Unmarshal(body, &req); err != nil { + return nil, errors.New("invalid request body") + } + + // Валидация обязательных полей + if req.RoleID == nil { + return nil, errors.New("role_id is required") + } + if req.Action == nil || *req.Action == "" { + return nil, errors.New("action is required") + } + + // 🛡 Проверяем валидность action + if !isValidAction(*req.Action) { + return nil, errors.New("invalid action: must be one of create, read, update, delete, approve, revoke, observe") + } + + ctx := context.Background() + + // Проверяем существование роли + role, err := s.ipc.Database.Role.GetRoleByIDDB(ctx, *req.RoleID) + if err != nil { + return nil, err + } + if role == nil { + return nil, errors.New("role not found") + } + + // Если указана категория — проверяем её существование + if req.TopicCategoryID != nil { + category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *req.TopicCategoryID) + if err != nil { + return nil, err + } + if category == nil { + return nil, errors.New("topic category not found") + } + } + + // Если указана тема — проверяем её существование + if req.TopicID != nil { + topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *req.TopicID) + if err != nil { + return nil, err + } + if topic == nil { + return nil, errors.New("topic not found") + } + + // Проверяем, что тема принадлежит указанной категории (если обе указаны) + if req.TopicCategoryID != nil && topic.CategoryID != nil { + if *topic.CategoryID != *req.TopicCategoryID { + return nil, errors.New("topic does not belong to the specified category") + } + } + } + + // 🛡 Проверяем, что такое право ещё не существует + existingPermissions, _, err := s.ipc.Database.Permission.GetPermissionsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.Permission{ + RoleID: req.RoleID, + TopicCategoryID: req.TopicCategoryID, + TopicID: req.TopicID, + Action: req.Action, + }, + }) + if err != nil { + return nil, err + } + if len(existingPermissions) > 0 { + return nil, errors.New("this permission already exists") + } + + createdPermission, _, err := s.ipc.Database.Permission.CreatePermissionDB(ctx, nil, &req, true) + if err != nil { + return nil, err + } + + s.enrichPermission(ctx, createdPermission) + + return createdPermission, nil +} + +// UpdatePermissionHandler Обновление права +// @Summary Обновление права +// @Description Обновление данных существующего права +// @Tags permissions +// @Accept json +// @Produce json +// @Param request body typescore.Permission true "Данные права" +// @Success 200 {object} typescore.Permission "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 404 {object} handlers.ErrorResponse "Право не найдено" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/permissions [put] +func (s *PermissionsReg) UpdatePermissionHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + defer r.Body.Close() + + body, err := io.ReadAll(r.Body) + if err != nil { + logrus.Error("🛑 UpdatePermissionHandler: ReadAll error:", err) + return nil, err + } + + var req typescore.Permission + if err := json.Unmarshal(body, &req); err != nil { + return nil, errors.New("invalid request body") + } + + if req.ID == nil { + return nil, errors.New("permission id is required") + } + + ctx := context.Background() + + // Проверяем, что право существует + existingPermissions, _, err := s.ipc.Database.Permission.GetPermissionsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.Permission{ID: req.ID}, + }) + if err != nil { + return nil, err + } + if len(existingPermissions) == 0 { + return nil, errors.New("permission not found") + } + existing := existingPermissions[0] + + // Если обновляется action — проверяем валидность + if req.Action != nil && *req.Action != "" { + if !isValidAction(*req.Action) { + return nil, errors.New("invalid action: must be one of create, read, update, delete, approve, revoke, observe") + } + } + + // Если обновляется role_id — проверяем существование + if req.RoleID != nil { + if existing.RoleID == nil || *existing.RoleID != *req.RoleID { + role, err := s.ipc.Database.Role.GetRoleByIDDB(ctx, *req.RoleID) + if err != nil { + return nil, err + } + if role == nil { + return nil, errors.New("role not found") + } + } + } + + // Если обновляется topic_category_id — проверяем существование + if req.TopicCategoryID != nil { + if existing.TopicCategoryID == nil || *existing.TopicCategoryID != *req.TopicCategoryID { + category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *req.TopicCategoryID) + if err != nil { + return nil, err + } + if category == nil { + return nil, errors.New("topic category not found") + } + } + } + + // Если обновляется topic_id — проверяем существование и принадлежность категории + if req.TopicID != nil { + if existing.TopicID == nil || *existing.TopicID != *req.TopicID { + topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *req.TopicID) + if err != nil { + return nil, err + } + if topic == nil { + return nil, errors.New("topic not found") + } + + // Проверяем соответствие категории + categoryIDToCheck := req.TopicCategoryID + if categoryIDToCheck == nil { + categoryIDToCheck = existing.TopicCategoryID + } + if categoryIDToCheck != nil && topic.CategoryID != nil && *topic.CategoryID != *categoryIDToCheck { + return nil, errors.New("topic does not belong to the specified category") + } + } + } + + updatedPermission, _, err := s.ipc.Database.Permission.UpdatePermissionDB(ctx, nil, &req, true) + if err != nil { + return nil, err + } + + s.enrichPermission(ctx, updatedPermission) + + return updatedPermission, nil +} + +// DeletePermissionHandler Удаление права +// @Summary Удаление права +// @Description Удаление права по ID +// @Tags permissions +// @Accept json +// @Produce json +// @Param request body typescore.Permission true "ID права для удаления" +// @Success 200 {object} bool "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 404 {object} handlers.ErrorResponse "Право не найдено" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/permissions [delete] +func (s *PermissionsReg) DeletePermissionHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + defer r.Body.Close() + + body, err := io.ReadAll(r.Body) + if err != nil { + logrus.Error("🛑 DeletePermissionHandler: ReadAll error:", err) + return nil, err + } + + var req typescore.Permission + if err := json.Unmarshal(body, &req); err != nil { + return nil, errors.New("invalid request body") + } + + if req.ID == nil { + return nil, errors.New("permission id is required") + } + + ctx := context.Background() + + // Проверяем, что право существует + existingPermissions, _, err := s.ipc.Database.Permission.GetPermissionsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.Permission{ID: req.ID}, + }) + if err != nil { + return nil, err + } + if len(existingPermissions) == 0 { + return nil, errors.New("permission not found") + } + + err = s.ipc.Database.Permission.DeletePermissionDB(ctx, &req) + if err != nil { + return nil, err + } + + return true, nil +} + +// enrichPermission подгружает связанные данные для права +func (s *PermissionsReg) enrichPermission(ctx context.Context, perm *typescore.Permission) { + if perm == nil { + return + } + + // Подгружаем роль + if perm.RoleID != nil { + role, err := s.ipc.Database.Role.GetRoleByIDDB(ctx, *perm.RoleID) + if err == nil && role != nil { + perm.Role = role + } + } + + // Подгружаем категорию тем + if perm.TopicCategoryID != nil { + category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *perm.TopicCategoryID) + if err == nil && category != nil { + perm.TopicCategory = category + } + } + + // Подгружаем тему + if perm.TopicID != nil { + topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *perm.TopicID) + if err == nil && topic != nil { + perm.Topic = topic + } + } +} + +// isValidAction проверяет валидность действия +func isValidAction(action string) bool { + validActions := map[string]bool{ + "create": true, + "read": true, + "update": true, + "delete": true, + "approve": true, + "revoke": true, + "observe": true, + } + return validActions[action] +} diff --git a/service/rest_admin_service/handlers/permission/routes.go b/service/rest_admin_service/handlers/permission/routes.go new file mode 100644 index 0000000..3bfc7ee --- /dev/null +++ b/service/rest_admin_service/handlers/permission/routes.go @@ -0,0 +1,43 @@ +package permissionshandler + +import ( + "bitrix_balancer_api/rest_admin_service/handlers" + typesm "bitrix_balancer_api/rest_admin_service/types" + "net/http" + + "github.com/go-chi/chi/v5" +) + +type PermissionsReg struct { + ipc *typesm.InternalProviderControl +} + +// RegisterPermissionRoutes регистрирует маршруты для группы permissions +func RegisterPermissionRoutes( + r chi.Router, + ipc *typesm.InternalProviderControl, +) error { + s := &PermissionsReg{ + ipc: ipc, + } + + r.Route("/api/permissions", func(r chi.Router) { + r.Use(handlers.AccessCodeVerifier(ipc.Config)) + r.Use(handlers.JWTVerifier(ipc.Config, ipc.Database.Admin, ipc.RedisClient)) + + handlers.RegisterRoute(r, http.MethodGet, "/", s.GetPermissionsListHandler) + handlers.RegisterRoute(r, http.MethodPost, "/", s.CreatePermissionHandler) + handlers.RegisterRoute(r, http.MethodPut, "/", s.UpdatePermissionHandler) + handlers.RegisterRoute(r, http.MethodDelete, "/", s.DeletePermissionHandler) + + r.Get("/{id}", handlers.WrapHandlerF(handlers.WrapHandlerParams{ + HandlerFunc: s.GetPermissionByIDHandler, + })) + + r.Get("/by-role/{role_id}", handlers.WrapHandlerF(handlers.WrapHandlerParams{ + HandlerFunc: s.GetPermissionsByRoleIDHandler, + })) + }) + + return nil +} diff --git a/service/rest_admin_service/handlers/profile/handlers.go b/service/rest_admin_service/handlers/profile/handlers.go new file mode 100644 index 0000000..0a37edf --- /dev/null +++ b/service/rest_admin_service/handlers/profile/handlers.go @@ -0,0 +1,102 @@ +package profilehandler + +import ( + "bitrix_balancer_api/core/securecore" + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/core/utilscore" + "bitrix_balancer_api/rest_admin_service/handlers" + "encoding/json" + "errors" + "github.com/sirupsen/logrus" + "io" + "net/http" +) + +// GetProfileHandler Получение профиля пользователя +// @Summary Получение профиля пользователя +// @Description Получение профиля пользователя +// @Tags profile +// @Accept json +// @Produce json +// @Success 200 {object} typescore.Admin +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/admin/profile [get] +func (h *ProfileReg) GetProfileHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + ctx := r.Context() + + userID, err := handlers.GetIDFromContext(ctx) + if err != nil { + return nil, err + } + userObjBody := &typescore.Admin{ + ID: &userID, + } + + usersList, _, err := h.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{Filtering: userObjBody}) + if err != nil { + return nil, err + } + + if usersList == nil || len(usersList) == 0 { + return nil, errors.New("no users found") + } + + return usersList[0], nil +} + +// UpdateProfileHandler Обновление профиля пользователя +// @Summary Обновление профиля пользователя +// @Description Обновление профиля пользователя +// @Tags profile +// @Accept json +// @Produce json +// @Param request body typescore.AdminReq true "Запрос" +// @Success 200 {object} typescore.Admin +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/admin/profile [put] +func (h *ProfileReg) UpdateProfileHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + ctx := r.Context() + defer r.Body.Close() + + body, err := io.ReadAll(r.Body) + if err != nil { + logrus.Error("🛑 error LoginByPassword: ReadAll: ", err) + return nil, err + } + + var req typescore.AdminReq + if err := json.Unmarshal(body, &req); err != nil { + return nil, err + } + + userID, err := handlers.GetIDFromContext(ctx) + if err != nil { + return nil, err + } + userObjBody := &typescore.Admin{ + ID: &userID, + } + + if req.Password != nil { + err := utilscore.ValidatePassword(*req.Password) + if err != nil { + return nil, err + } + + hash, err := securecore.HashPassword(req.Password) + + if err != nil { + return nil, err + } + userObjBody.PasswordHash = hash + } + + upUser, _, err := h.ipc.Database.Admin.UpdateAdminDB(nil, userObjBody, true) + if err != nil { + return nil, err + } + + return upUser, nil +} diff --git a/service/rest_admin_service/handlers/profile/routes.go b/service/rest_admin_service/handlers/profile/routes.go new file mode 100644 index 0000000..5217b0d --- /dev/null +++ b/service/rest_admin_service/handlers/profile/routes.go @@ -0,0 +1,36 @@ +package profilehandler + +import ( + "bitrix_balancer_api/rest_admin_service/handlers" + typesm "bitrix_balancer_api/rest_admin_service/types" + "github.com/go-chi/chi/v5" + "net/http" +) + +const ( + profileURI = "/" +) + +type ProfileReg struct { + ipc *typesm.InternalProviderControl +} + +// RegisterProfileRoutes регистрирует маршруты для группы profile +func RegisterProfileRoutes( + r chi.Router, + ipc *typesm.InternalProviderControl, +) error { + s := &ProfileReg{ + ipc: ipc, + } + + r.Route("/api/admin/profile", func(r chi.Router) { + r.Use(handlers.AccessCodeVerifier(ipc.Config)) + r.Use(handlers.JWTVerifier(ipc.Config, ipc.Database.Admin, ipc.RedisClient)) + + handlers.RegisterRoute(r, http.MethodGet, profileURI, s.GetProfileHandler) + handlers.RegisterRoute(r, http.MethodPut, profileURI, s.UpdateProfileHandler) + }) + + return nil +} diff --git a/service/rest_admin_service/handlers/roles/handlers.go b/service/rest_admin_service/handlers/roles/handlers.go new file mode 100644 index 0000000..2d67153 --- /dev/null +++ b/service/rest_admin_service/handlers/roles/handlers.go @@ -0,0 +1,282 @@ +package roleshandler + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/core/utilscore" + "context" + "encoding/json" + "errors" + "github.com/sirupsen/logrus" + "io" + "net/http" + "strconv" + + "github.com/go-chi/chi/v5" +) + +// GetRolesListHandler Получение списка ролей +// @Summary Получение списка ролей +// @Description Получение списка ролей с пагинацией и фильтрацией +// @Tags roles +// @Accept json +// @Produce json +// @Param offset query integer false "Смещение для пагинации" +// @Param limit query integer false "Количество записей на странице" +// @Success 200 {object} typescore.ApiResponseBase "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/roles [get] +func (s *RolesReg) GetRolesListHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + queryParams := r.URL.Query() + + roleParams := &typescore.Role{} + offset, limit, likeFields, errW := utilscore.ParseParamsGetRequest(queryParams, roleParams) + if errW != nil { + return nil, errW + } + + options := typescore.ListDbOptions{ + Filtering: roleParams, + Offset: offset, + Limit: limit, + LikeFields: likeFields, + } + + ctx := context.Background() + rolesDbLst, total, errW := s.ipc.Database.Role.GetRolesListDB(ctx, options) + if errW != nil { + return nil, errW + } + + return &typescore.ApiResponseBase{ + TotalCount: total, + Data: rolesDbLst, + }, nil +} + +// GetRoleByIDHandler Получение роли по ID +// @Summary Получение роли по ID +// @Description Получение детальной информации о роли по её ID +// @Tags roles +// @Accept json +// @Produce json +// @Param id path integer true "ID роли" +// @Success 200 {object} typescore.Role "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 404 {object} handlers.ErrorResponse "Роль не найдена" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/roles/{id} [get] +func (s *RolesReg) GetRoleByIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + idStr := chi.URLParam(r, "id") + if idStr == "" { + return nil, errors.New("role id is required") + } + + id, err := strconv.ParseUint(idStr, 10, 64) + if err != nil { + return nil, errors.New("invalid role id") + } + + ctx := context.Background() + role, err := s.ipc.Database.Role.GetRoleByIDDB(ctx, id) + if err != nil { + return nil, err + } + + if role == nil { + return nil, errors.New("role not found") + } + + return role, nil +} + +// CreateRoleHandler Создание роли +// @Summary Создание роли +// @Description Создание новой роли +// @Tags roles +// @Accept json +// @Produce json +// @Param request body typescore.Role true "Данные роли" +// @Success 200 {object} typescore.Role "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/roles [post] +func (s *RolesReg) CreateRoleHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + defer r.Body.Close() + + body, err := io.ReadAll(r.Body) + if err != nil { + logrus.Error("🛑 CreateRoleHandler: ReadAll error:", err) + return nil, err + } + + var req typescore.Role + if err := json.Unmarshal(body, &req); err != nil { + return nil, errors.New("invalid request body") + } + + // Валидация обязательных полей + if req.Name == nil || *req.Name == "" { + return nil, errors.New("role name is required") + } + if req.Code == nil || *req.Code == "" { + return nil, errors.New("role code is required") + } + + // Проверяем, что код уникален + ctx := context.Background() + existingRoles, _, err := s.ipc.Database.Role.GetRolesListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.Role{Code: req.Code}, + }) + if err != nil { + return nil, err + } + if len(existingRoles) > 0 { + return nil, errors.New("role code already exists") + } + + // Устанавливаем значения по умолчанию для булевых флагов + if req.IsDefault == nil { + v := false + req.IsDefault = &v + } + if req.IsDirector == nil { + v := false + req.IsDirector = &v + } + if req.IsApprover == nil { + v := false + req.IsApprover = &v + } + if req.IsObserver == nil { + v := false + req.IsObserver = &v + } + if req.IsExecutor == nil { + v := false + req.IsExecutor = &v + } + + createdRole, _, err := s.ipc.Database.Role.CreateRoleDB(ctx, nil, &req, true) + if err != nil { + return nil, err + } + + return createdRole, nil +} + +// UpdateRoleHandler Обновление роли +// @Summary Обновление роли +// @Description Обновление данных существующей роли +// @Tags roles +// @Accept json +// @Produce json +// @Param request body typescore.Role true "Данные роли" +// @Success 200 {object} typescore.Role "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 404 {object} handlers.ErrorResponse "Роль не найдена" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/roles [put] +func (s *RolesReg) UpdateRoleHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + defer r.Body.Close() + + body, err := io.ReadAll(r.Body) + if err != nil { + logrus.Error("🛑 UpdateRoleHandler: ReadAll error:", err) + return nil, err + } + + var req typescore.Role + if err := json.Unmarshal(body, &req); err != nil { + return nil, errors.New("invalid request body") + } + + if req.ID == nil { + return nil, errors.New("role id is required") + } + + // Проверяем, что роль существует + ctx := context.Background() + existingRole, err := s.ipc.Database.Role.GetRoleByIDDB(ctx, *req.ID) + if err != nil { + return nil, err + } + if existingRole == nil { + return nil, errors.New("role not found") + } + + // Если обновляется код, проверяем уникальность + if req.Code != nil && *req.Code != "" { + if existingRole.Code == nil || *existingRole.Code != *req.Code { + existingRoles, _, err := s.ipc.Database.Role.GetRolesListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.Role{Code: req.Code}, + }) + if err != nil { + return nil, err + } + if len(existingRoles) > 0 { + return nil, errors.New("role code already exists") + } + } + } + + updatedRole, _, err := s.ipc.Database.Role.UpdateRoleDB(ctx, nil, &req, true) + if err != nil { + return nil, err + } + + return updatedRole, nil +} + +// DeleteRoleHandler Удаление роли +// @Summary Удаление роли +// @Description Удаление роли по ID +// @Tags roles +// @Accept json +// @Produce json +// @Param request body typescore.Role true "ID роли для удаления" +// @Success 200 {object} bool "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 404 {object} handlers.ErrorResponse "Роль не найдена" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/roles [delete] +func (s *RolesReg) DeleteRoleHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + defer r.Body.Close() + + body, err := io.ReadAll(r.Body) + if err != nil { + logrus.Error("🛑 DeleteRoleHandler: ReadAll error:", err) + return nil, err + } + + var req typescore.Role + if err := json.Unmarshal(body, &req); err != nil { + return nil, errors.New("invalid request body") + } + + if req.ID == nil { + return nil, errors.New("role id is required") + } + + // Проверяем, что роль существует + ctx := context.Background() + existingRole, err := s.ipc.Database.Role.GetRoleByIDDB(ctx, *req.ID) + if err != nil { + return nil, err + } + if existingRole == nil { + return nil, errors.New("role not found") + } + + // 🛡 Защита от удаления дефолтной роли + if existingRole.IsDefault != nil && *existingRole.IsDefault { + return nil, errors.New("cannot delete default role") + } + + err = s.ipc.Database.Role.DeleteRoleDB(ctx, &req) + if err != nil { + return nil, err + } + + return true, nil +} diff --git a/service/rest_admin_service/handlers/roles/routes.go b/service/rest_admin_service/handlers/roles/routes.go new file mode 100644 index 0000000..20d7524 --- /dev/null +++ b/service/rest_admin_service/handlers/roles/routes.go @@ -0,0 +1,39 @@ +package roleshandler + +import ( + "bitrix_balancer_api/rest_admin_service/handlers" + typesm "bitrix_balancer_api/rest_admin_service/types" + "net/http" + + "github.com/go-chi/chi/v5" +) + +type RolesReg struct { + ipc *typesm.InternalProviderControl +} + +// RegisterRoleRoutes регистрирует маршруты для группы roles +func RegisterRoleRoutes( + r chi.Router, + ipc *typesm.InternalProviderControl, +) error { + s := &RolesReg{ + ipc: ipc, + } + + r.Route("/api/roles", func(r chi.Router) { + r.Use(handlers.AccessCodeVerifier(ipc.Config)) + r.Use(handlers.JWTVerifier(ipc.Config, ipc.Database.Admin, ipc.RedisClient)) + + handlers.RegisterRoute(r, http.MethodGet, "/", s.GetRolesListHandler) + handlers.RegisterRoute(r, http.MethodPost, "/", s.CreateRoleHandler) + handlers.RegisterRoute(r, http.MethodPut, "/", s.UpdateRoleHandler) + handlers.RegisterRoute(r, http.MethodDelete, "/", s.DeleteRoleHandler) + + r.Get("/{id}", handlers.WrapHandlerF(handlers.WrapHandlerParams{ + HandlerFunc: s.GetRoleByIDHandler, + })) + }) + + return nil +} diff --git a/service/rest_admin_service/handlers/topic_categories/handlers.go b/service/rest_admin_service/handlers/topic_categories/handlers.go new file mode 100644 index 0000000..4b70ae5 --- /dev/null +++ b/service/rest_admin_service/handlers/topic_categories/handlers.go @@ -0,0 +1,281 @@ +package categorieshandler + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/core/utilscore" + "context" + "encoding/json" + "errors" + "github.com/sirupsen/logrus" + "io" + "net/http" + "strconv" + + "github.com/go-chi/chi/v5" +) + +// GetCategoriesListHandler Получение списка категорий тем +// @Summary Получение списка категорий тем +// @Description Получение списка категорий тем с пагинацией и фильтрацией +// @Tags categories +// @Accept json +// @Produce json +// @Param offset query integer false "Смещение для пагинации" +// @Param limit query integer false "Количество записей на странице" +// @Param is_active query boolean false "Фильтр по активности" +// @Success 200 {object} typescore.ApiResponseBase "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/categories [get] +func (s *CategoriesReg) GetCategoriesListHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + queryParams := r.URL.Query() + + categoryParams := &typescore.ApprovalTopicCategory{} + offset, limit, likeFields, errW := utilscore.ParseParamsGetRequest(queryParams, categoryParams) + if errW != nil { + return nil, errW + } + + options := typescore.ListDbOptions{ + Filtering: categoryParams, + Offset: offset, + Limit: limit, + LikeFields: likeFields, + } + + ctx := context.Background() + categoriesDbLst, total, errW := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryListDB(ctx, options) + if errW != nil { + return nil, errW + } + + return &typescore.ApiResponseBase{ + TotalCount: total, + Data: categoriesDbLst, + }, nil +} + +// GetCategoryByIDHandler Получение категории по ID +// @Summary Получение категории по ID +// @Description Получение детальной информации о категории по её ID +// @Tags categories +// @Accept json +// @Produce json +// @Param id path integer true "ID категории" +// @Success 200 {object} typescore.ApprovalTopicCategory "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 404 {object} handlers.ErrorResponse "Категория не найдена" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/categories/{id} [get] +func (s *CategoriesReg) GetCategoryByIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + idStr := chi.URLParam(r, "id") + if idStr == "" { + return nil, errors.New("category id is required") + } + + id, err := strconv.ParseUint(idStr, 10, 64) + if err != nil { + return nil, errors.New("invalid category id") + } + + ctx := context.Background() + category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, id) + if err != nil { + return nil, err + } + + if category == nil { + return nil, errors.New("category not found") + } + + // Подгружаем темы этой категории + topics, _, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalTopic{CategoryID: &id}, + }) + if err == nil { + category.Topics = topics + } + + return category, nil +} + +// CreateCategoryHandler Создание категории тем +// @Summary Создание категории тем +// @Description Создание новой категории тем +// @Tags categories +// @Accept json +// @Produce json +// @Param request body typescore.ApprovalTopicCategory true "Данные категории" +// @Success 200 {object} typescore.ApprovalTopicCategory "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/categories [post] +func (s *CategoriesReg) CreateCategoryHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + defer r.Body.Close() + + body, err := io.ReadAll(r.Body) + if err != nil { + logrus.Error("🛑 CreateCategoryHandler: ReadAll error:", err) + return nil, err + } + + var req typescore.ApprovalTopicCategory + if err := json.Unmarshal(body, &req); err != nil { + return nil, errors.New("invalid request body") + } + + // Валидация обязательных полей + if req.Name == nil || *req.Name == "" { + return nil, errors.New("category name is required") + } + if req.Code == nil || *req.Code == "" { + return nil, errors.New("category code is required") + } + + // Проверяем, что код уникален + ctx := context.Background() + existingCategories, _, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalTopicCategory{Code: req.Code}, + }) + if err != nil { + return nil, err + } + if len(existingCategories) > 0 { + return nil, errors.New("category code already exists") + } + + // Устанавливаем is_active по умолчанию + if req.IsActive == nil { + isActive := true + req.IsActive = &isActive + } + + createdCategory, _, err := s.ipc.Database.ApprovalTopicCategory.CreateApprovalTopicCategoryDB(ctx, nil, &req, true) + if err != nil { + return nil, err + } + + return createdCategory, nil +} + +// UpdateCategoryHandler Обновление категории +// @Summary Обновление категории +// @Description Обновление данных существующей категории +// @Tags categories +// @Accept json +// @Produce json +// @Param request body typescore.ApprovalTopicCategory true "Данные категории" +// @Success 200 {object} typescore.ApprovalTopicCategory "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 404 {object} handlers.ErrorResponse "Категория не найдена" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/categories [put] +func (s *CategoriesReg) UpdateCategoryHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + defer r.Body.Close() + + body, err := io.ReadAll(r.Body) + if err != nil { + logrus.Error("🛑 UpdateCategoryHandler: ReadAll error:", err) + return nil, err + } + + var req typescore.ApprovalTopicCategory + if err := json.Unmarshal(body, &req); err != nil { + return nil, errors.New("invalid request body") + } + + if req.ID == nil { + return nil, errors.New("category id is required") + } + + // Проверяем, что категория существует + ctx := context.Background() + existingCategory, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *req.ID) + if err != nil { + return nil, err + } + if existingCategory == nil { + return nil, errors.New("category not found") + } + + // Если обновляется код, проверяем уникальность + if req.Code != nil && *req.Code != "" { + if existingCategory.Code == nil || *existingCategory.Code != *req.Code { + existingCategories, _, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalTopicCategory{Code: req.Code}, + }) + if err != nil { + return nil, err + } + if len(existingCategories) > 0 { + return nil, errors.New("category code already exists") + } + } + } + + updatedCategory, _, err := s.ipc.Database.ApprovalTopicCategory.UpdateApprovalTopicCategoryDB(ctx, nil, &req, true) + if err != nil { + return nil, err + } + + return updatedCategory, nil +} + +// DeleteCategoryHandler Удаление категории +// @Summary Удаление категории +// @Description Удаление категории по ID +// @Tags categories +// @Accept json +// @Produce json +// @Param request body typescore.ApprovalTopicCategory true "ID категории для удаления" +// @Success 200 {object} bool "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 404 {object} handlers.ErrorResponse "Категория не найдена" +// @Failure 409 {object} handlers.ErrorResponse "Категория содержит темы" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/categories [delete] +func (s *CategoriesReg) DeleteCategoryHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + defer r.Body.Close() + + body, err := io.ReadAll(r.Body) + if err != nil { + logrus.Error("🛑 DeleteCategoryHandler: ReadAll error:", err) + return nil, err + } + + var req typescore.ApprovalTopicCategory + if err := json.Unmarshal(body, &req); err != nil { + return nil, errors.New("invalid request body") + } + + if req.ID == nil { + return nil, errors.New("category id is required") + } + + // Проверяем, что категория существует + ctx := context.Background() + existingCategory, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *req.ID) + if err != nil { + return nil, err + } + if existingCategory == nil { + return nil, errors.New("category not found") + } + + topics, _, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalTopic{CategoryID: req.ID}, + }) + if err != nil { + return nil, err + } + if len(topics) > 0 { + return nil, errors.New("cannot delete category: it contains topics") + } + + err = s.ipc.Database.ApprovalTopicCategory.DeleteApprovalTopicCategoryDB(ctx, &req) + if err != nil { + return nil, err + } + + return true, nil +} diff --git a/service/rest_admin_service/handlers/topic_categories/routes.go b/service/rest_admin_service/handlers/topic_categories/routes.go new file mode 100644 index 0000000..83291e1 --- /dev/null +++ b/service/rest_admin_service/handlers/topic_categories/routes.go @@ -0,0 +1,39 @@ +package categorieshandler + +import ( + "bitrix_balancer_api/rest_admin_service/handlers" + typesm "bitrix_balancer_api/rest_admin_service/types" + "net/http" + + "github.com/go-chi/chi/v5" +) + +type CategoriesReg struct { + ipc *typesm.InternalProviderControl +} + +// RegisterCategoryRoutes регистрирует маршруты для группы categories +func RegisterCategoryRoutes( + r chi.Router, + ipc *typesm.InternalProviderControl, +) error { + s := &CategoriesReg{ + ipc: ipc, + } + + r.Route("/api/categories", func(r chi.Router) { + r.Use(handlers.AccessCodeVerifier(ipc.Config)) + r.Use(handlers.JWTVerifier(ipc.Config, ipc.Database.Admin, ipc.RedisClient)) + + handlers.RegisterRoute(r, http.MethodGet, "/", s.GetCategoriesListHandler) + handlers.RegisterRoute(r, http.MethodPost, "/", s.CreateCategoryHandler) + handlers.RegisterRoute(r, http.MethodPut, "/", s.UpdateCategoryHandler) + handlers.RegisterRoute(r, http.MethodDelete, "/", s.DeleteCategoryHandler) + + r.Get("/{id}", handlers.WrapHandlerF(handlers.WrapHandlerParams{ + HandlerFunc: s.GetCategoryByIDHandler, + })) + }) + + return nil +} diff --git a/service/rest_admin_service/handlers/topic_executors/handlers.go b/service/rest_admin_service/handlers/topic_executors/handlers.go new file mode 100644 index 0000000..fcab152 --- /dev/null +++ b/service/rest_admin_service/handlers/topic_executors/handlers.go @@ -0,0 +1,419 @@ +package topicexecutorshandler + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/core/utilscore" + "context" + "encoding/json" + "errors" + "github.com/sirupsen/logrus" + "io" + "net/http" + "strconv" + + "github.com/go-chi/chi/v5" +) + +// GetTopicExecutorsListHandler Получение списка исполнителей тем +// @Summary Получение списка исполнителей тем +// @Description Получение списка исполнителей с пагинацией и фильтрацией +// @Tags topic-executors +// @Accept json +// @Produce json +// @Param offset query integer false "Смещение для пагинации" +// @Param limit query integer false "Количество записей на странице" +// @Param topic_id query integer false "Фильтр по теме" +// @Param user_id query integer false "Фильтр по пользователю" +// @Param is_active query boolean false "Фильтр по активности" +// @Success 200 {object} typescore.ApiResponseBase "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/topic-executors [get] +func (s *TopicExecutorsReg) GetTopicExecutorsListHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + queryParams := r.URL.Query() + + executorParams := &typescore.ApprovalTopicExecutor{} + offset, limit, likeFields, errW := utilscore.ParseParamsGetRequest(queryParams, executorParams) + if errW != nil { + return nil, errW + } + + options := typescore.ListDbOptions{ + Filtering: executorParams, + Offset: offset, + Limit: limit, + LikeFields: likeFields, + } + + ctx := context.Background() + executorsDbLst, total, errW := s.ipc.Database.ApprovalTopicExecutor.GetApprovalTopicExecutorListDB(ctx, options) + if errW != nil { + return nil, errW + } + + // 🚀 Подгружаем связанные данные + for _, exec := range executorsDbLst { + s.enrichExecutor(ctx, exec) + } + + return &typescore.ApiResponseBase{ + TotalCount: total, + Data: executorsDbLst, + }, nil +} + +// GetTopicExecutorByIDHandler Получение исполнителя по ID +// @Summary Получение исполнителя по ID +// @Description Получение детальной информации об исполнителе по его ID +// @Tags topic-executors +// @Accept json +// @Produce json +// @Param id path integer true "ID исполнителя" +// @Success 200 {object} typescore.ApprovalTopicExecutor "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 404 {object} handlers.ErrorResponse "Исполнитель не найден" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/topic-executors/{id} [get] +func (s *TopicExecutorsReg) GetTopicExecutorByIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + idStr := chi.URLParam(r, "id") + if idStr == "" { + return nil, errors.New("executor id is required") + } + + id, err := strconv.ParseUint(idStr, 10, 64) + if err != nil { + return nil, errors.New("invalid executor id") + } + + ctx := context.Background() + executors, _, err := s.ipc.Database.ApprovalTopicExecutor.GetApprovalTopicExecutorListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalTopicExecutor{ID: &id}, + }) + if err != nil { + return nil, err + } + if len(executors) == 0 { + return nil, errors.New("topic executor not found") + } + + executor := executors[0] + s.enrichExecutor(ctx, executor) + + return executor, nil +} + +// GetExecutorsByTopicIDHandler Получение всех исполнителей для темы +// @Summary Получение исполнителей по теме +// @Description Получение списка всех активных исполнителей для указанной темы, отсортированных по step_order +// @Tags topic-executors +// @Accept json +// @Produce json +// @Param topic_id path integer true "ID темы" +// @Success 200 {object} typescore.ApiResponseBase "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 404 {object} handlers.ErrorResponse "Тема не найдена" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/topic-executors/by-topic/{topic_id} [get] +func (s *TopicExecutorsReg) GetExecutorsByTopicIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + topicIDStr := chi.URLParam(r, "topic_id") + if topicIDStr == "" { + return nil, errors.New("topic_id is required") + } + + topicID, err := strconv.ParseUint(topicIDStr, 10, 64) + if err != nil { + return nil, errors.New("invalid topic_id") + } + + ctx := context.Background() + + // Проверяем, что тема существует + topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, topicID) + if err != nil { + return nil, err + } + if topic == nil { + return nil, errors.New("topic not found") + } + + executors, err := s.ipc.Database.ApprovalTopicExecutor.GetExecutorsByTopicIDDB(ctx, topicID) + if err != nil { + return nil, err + } + + // Подгружаем связанные данные + for _, exec := range executors { + s.enrichExecutor(ctx, exec) + } + + return &typescore.ApiResponseBase{ + TotalCount: uint64(len(executors)), + Data: executors, + }, nil +} + +// CreateTopicExecutorHandler Создание исполнителя для темы +// @Summary Создание исполнителя +// @Description Назначение исполнителя для конкретной темы согласования +// @Tags topic-executors +// @Accept json +// @Produce json +// @Param request body typescore.ApprovalTopicExecutor true "Данные исполнителя" +// @Success 200 {object} typescore.ApprovalTopicExecutor "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 404 {object} handlers.ErrorResponse "Тема или пользователь не найдены" +// @Failure 409 {object} handlers.ErrorResponse "Такой исполнитель уже назначен на этот шаг" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/topic-executors [post] +func (s *TopicExecutorsReg) CreateTopicExecutorHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + defer r.Body.Close() + + body, err := io.ReadAll(r.Body) + if err != nil { + logrus.Error("🛑 CreateTopicExecutorHandler: ReadAll error:", err) + return nil, err + } + + var req typescore.ApprovalTopicExecutor + if err := json.Unmarshal(body, &req); err != nil { + return nil, errors.New("invalid request body") + } + + // Валидация обязательных полей + if req.TopicID == nil { + return nil, errors.New("topic_id is required") + } + if req.UserID == nil { + return nil, errors.New("user_id is required") + } + + ctx := context.Background() + + // Проверяем существование темы + topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *req.TopicID) + if err != nil { + return nil, err + } + if topic == nil { + return nil, errors.New("topic not found") + } + + // Проверяем существование пользователя + user, err := s.ipc.Database.User.GetUserByIDDB(ctx, *req.UserID) + if err != nil { + return nil, err + } + if user == nil { + return nil, errors.New("user not found") + } + + // Проверяем, что пользователь не заблокирован и не уволен + if user.IsBlocked != nil && *user.IsBlocked { + return nil, errors.New("user is blocked") + } + if user.IsFired != nil && *user.IsFired { + return nil, errors.New("user is fired") + } + + // 🛡 Проверяем, что такой исполнитель на этом шаге ещё не существует + stepOrder := 0 + if req.StepOrder != nil { + stepOrder = *req.StepOrder + } + existingExecutors, _, err := s.ipc.Database.ApprovalTopicExecutor.GetApprovalTopicExecutorListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalTopicExecutor{ + TopicID: req.TopicID, + UserID: req.UserID, + StepOrder: &stepOrder, + }, + }) + if err != nil { + return nil, err + } + if len(existingExecutors) > 0 { + return nil, errors.New("this executor is already assigned to this step for the topic") + } + + // Устанавливаем значения по умолчанию + if req.StepOrder == nil { + defaultStep := 0 + req.StepOrder = &defaultStep + } + if req.RequireFile == nil { + defaultRequire := false + req.RequireFile = &defaultRequire + } + if req.IsActive == nil { + defaultActive := true + req.IsActive = &defaultActive + } + + createdExecutor, _, err := s.ipc.Database.ApprovalTopicExecutor.CreateApprovalTopicExecutorDB(ctx, nil, &req, true) + if err != nil { + return nil, err + } + + s.enrichExecutor(ctx, createdExecutor) + + return createdExecutor, nil +} + +// UpdateTopicExecutorHandler Обновление исполнителя +// @Summary Обновление исполнителя +// @Description Обновление данных исполнителя для темы +// @Tags topic-executors +// @Accept json +// @Produce json +// @Param request body typescore.ApprovalTopicExecutor true "Данные исполнителя" +// @Success 200 {object} typescore.ApprovalTopicExecutor "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 404 {object} handlers.ErrorResponse "Исполнитель не найден" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/topic-executors [put] +func (s *TopicExecutorsReg) UpdateTopicExecutorHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + defer r.Body.Close() + + body, err := io.ReadAll(r.Body) + if err != nil { + logrus.Error("🛑 UpdateTopicExecutorHandler: ReadAll error:", err) + return nil, err + } + + var req typescore.ApprovalTopicExecutor + if err := json.Unmarshal(body, &req); err != nil { + return nil, errors.New("invalid request body") + } + + if req.ID == nil { + return nil, errors.New("executor id is required") + } + + ctx := context.Background() + + // Проверяем, что запись существует + existingExecutors, _, err := s.ipc.Database.ApprovalTopicExecutor.GetApprovalTopicExecutorListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalTopicExecutor{ID: req.ID}, + }) + if err != nil { + return nil, err + } + if len(existingExecutors) == 0 { + return nil, errors.New("topic executor not found") + } + existing := existingExecutors[0] + + // Если обновляется topic_id — проверяем существование + if req.TopicID != nil { + if existing.TopicID == nil || *existing.TopicID != *req.TopicID { + topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *req.TopicID) + if err != nil { + return nil, err + } + if topic == nil { + return nil, errors.New("topic not found") + } + } + } + + // Если обновляется user_id — проверяем существование и статус + if req.UserID != nil { + if existing.UserID == nil || *existing.UserID != *req.UserID { + user, err := s.ipc.Database.User.GetUserByIDDB(ctx, *req.UserID) + if err != nil { + return nil, err + } + if user == nil { + return nil, errors.New("user not found") + } + if user.IsBlocked != nil && *user.IsBlocked { + return nil, errors.New("user is blocked") + } + if user.IsFired != nil && *user.IsFired { + return nil, errors.New("user is fired") + } + } + } + + updatedExecutor, _, err := s.ipc.Database.ApprovalTopicExecutor.UpdateApprovalTopicExecutorDB(ctx, nil, &req, true) + if err != nil { + return nil, err + } + + s.enrichExecutor(ctx, updatedExecutor) + + return updatedExecutor, nil +} + +// DeleteTopicExecutorHandler Удаление исполнителя +// @Summary Удаление исполнителя +// @Description Удаление исполнителя из темы по ID +// @Tags topic-executors +// @Accept json +// @Produce json +// @Param request body typescore.ApprovalTopicExecutor true "ID записи для удаления" +// @Success 200 {object} bool "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 404 {object} handlers.ErrorResponse "Запись не найдена" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/topic-executors [delete] +func (s *TopicExecutorsReg) DeleteTopicExecutorHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + defer r.Body.Close() + + body, err := io.ReadAll(r.Body) + if err != nil { + logrus.Error("🛑 DeleteTopicExecutorHandler: ReadAll error:", err) + return nil, err + } + + var req typescore.ApprovalTopicExecutor + if err := json.Unmarshal(body, &req); err != nil { + return nil, errors.New("invalid request body") + } + + if req.ID == nil { + return nil, errors.New("executor id is required") + } + + ctx := context.Background() + + // Проверяем, что запись существует + existingExecutors, _, err := s.ipc.Database.ApprovalTopicExecutor.GetApprovalTopicExecutorListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalTopicExecutor{ID: req.ID}, + }) + if err != nil { + return nil, err + } + if len(existingExecutors) == 0 { + return nil, errors.New("topic executor not found") + } + + err = s.ipc.Database.ApprovalTopicExecutor.DeleteApprovalTopicExecutorDB(ctx, &req) + if err != nil { + return nil, err + } + + return true, nil +} + +// enrichExecutor подгружает связанные данные для записи исполнителя +func (s *TopicExecutorsReg) enrichExecutor(ctx context.Context, exec *typescore.ApprovalTopicExecutor) { + if exec == nil { + return + } + + // Подгружаем тему + if exec.TopicID != nil { + topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *exec.TopicID) + if err == nil && topic != nil { + exec.Topic = topic + } + } + + // Подгружаем пользователя + if exec.UserID != nil { + user, err := s.ipc.Database.User.GetUserByIDDB(ctx, *exec.UserID) + if err == nil && user != nil { + exec.User = user + } + } +} diff --git a/service/rest_admin_service/handlers/topic_executors/routes.go b/service/rest_admin_service/handlers/topic_executors/routes.go new file mode 100644 index 0000000..90d8bc6 --- /dev/null +++ b/service/rest_admin_service/handlers/topic_executors/routes.go @@ -0,0 +1,43 @@ +package topicexecutorshandler + +import ( + "bitrix_balancer_api/rest_admin_service/handlers" + typesm "bitrix_balancer_api/rest_admin_service/types" + "net/http" + + "github.com/go-chi/chi/v5" +) + +type TopicExecutorsReg struct { + ipc *typesm.InternalProviderControl +} + +// RegisterTopicExecutorRoutes регистрирует маршруты для группы topic-executors +func RegisterTopicExecutorRoutes( + r chi.Router, + ipc *typesm.InternalProviderControl, +) error { + s := &TopicExecutorsReg{ + ipc: ipc, + } + + r.Route("/api/topic-executors", func(r chi.Router) { + r.Use(handlers.AccessCodeVerifier(ipc.Config)) + r.Use(handlers.JWTVerifier(ipc.Config, ipc.Database.Admin, ipc.RedisClient)) + + handlers.RegisterRoute(r, http.MethodGet, "/", s.GetTopicExecutorsListHandler) + handlers.RegisterRoute(r, http.MethodPost, "/", s.CreateTopicExecutorHandler) + handlers.RegisterRoute(r, http.MethodPut, "/", s.UpdateTopicExecutorHandler) + handlers.RegisterRoute(r, http.MethodDelete, "/", s.DeleteTopicExecutorHandler) + + r.Get("/{id}", handlers.WrapHandlerF(handlers.WrapHandlerParams{ + HandlerFunc: s.GetTopicExecutorByIDHandler, + })) + + r.Get("/by-topic/{topic_id}", handlers.WrapHandlerF(handlers.WrapHandlerParams{ + HandlerFunc: s.GetExecutorsByTopicIDHandler, + })) + }) + + return nil +} diff --git a/service/rest_admin_service/handlers/topics/handlers.go b/service/rest_admin_service/handlers/topics/handlers.go new file mode 100644 index 0000000..3189cbb --- /dev/null +++ b/service/rest_admin_service/handlers/topics/handlers.go @@ -0,0 +1,361 @@ +package topicshandler + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/core/utilscore" + "context" + "encoding/json" + "errors" + "github.com/sirupsen/logrus" + "io" + "net/http" + "strconv" + + "github.com/go-chi/chi/v5" +) + +// GetTopicsListHandler Получение списка тем +// @Summary Получение списка тем +// @Description Получение списка тем с пагинацией и фильтрацией +// @Tags topics +// @Accept json +// @Produce json +// @Param offset query integer false "Смещение для пагинации" +// @Param limit query integer false "Количество записей на странице" +// @Param category_id query integer false "Фильтр по категории" +// @Param is_active query boolean false "Фильтр по активности" +// @Success 200 {object} typescore.ApiResponseBase "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/topics [get] +func (s *TopicsReg) GetTopicsListHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + queryParams := r.URL.Query() + + topicParams := &typescore.ApprovalTopic{} + offset, limit, likeFields, errW := utilscore.ParseParamsGetRequest(queryParams, topicParams) + if errW != nil { + return nil, errW + } + + options := typescore.ListDbOptions{ + Filtering: topicParams, + Offset: offset, + Limit: limit, + LikeFields: likeFields, + } + + ctx := context.Background() + topicsDbLst, total, errW := s.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, options) + if errW != nil { + return nil, errW + } + + // Подгружаем информацию о категории для каждой темы + for _, topic := range topicsDbLst { + if topic.CategoryID != nil { + category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *topic.CategoryID) + if err == nil && category != nil { + topic.Category = category + } + } + } + + return &typescore.ApiResponseBase{ + TotalCount: total, + Data: topicsDbLst, + }, nil +} + +// GetTopicByIDHandler Получение темы по ID +// @Summary Получение темы по ID +// @Description Получение детальной информации о теме по её ID +// @Tags topics +// @Accept json +// @Produce json +// @Param id path integer true "ID темы" +// @Success 200 {object} typescore.ApprovalTopic "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 404 {object} handlers.ErrorResponse "Тема не найдена" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/topics/{id} [get] +func (s *TopicsReg) GetTopicByIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + idStr := chi.URLParam(r, "id") + if idStr == "" { + return nil, errors.New("topic id is required") + } + + id, err := strconv.ParseUint(idStr, 10, 64) + if err != nil { + return nil, errors.New("invalid topic id") + } + + ctx := context.Background() + topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, id) + if err != nil { + return nil, err + } + + if topic == nil { + return nil, errors.New("topic not found") + } + + // Подгружаем информацию о категории + if topic.CategoryID != nil { + category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *topic.CategoryID) + if err == nil && category != nil { + topic.Category = category + } + } + + return topic, nil +} + +// CreateTopicHandler Создание темы +// @Summary Создание темы +// @Description Создание новой темы согласования +// @Tags topics +// @Accept json +// @Produce json +// @Param request body typescore.ApprovalTopic true "Данные темы" +// @Success 200 {object} typescore.ApprovalTopic "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/topics [post] +func (s *TopicsReg) CreateTopicHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + defer r.Body.Close() + + body, err := io.ReadAll(r.Body) + if err != nil { + logrus.Error("🛑 CreateTopicHandler: ReadAll error:", err) + return nil, err + } + + var req typescore.ApprovalTopic + if err := json.Unmarshal(body, &req); err != nil { + return nil, errors.New("invalid request body") + } + + // Валидация обязательных полей + if req.Name == nil || *req.Name == "" { + return nil, errors.New("topic name is required") + } + if req.Code == nil || *req.Code == "" { + return nil, errors.New("topic code is required") + } + if req.CategoryID == nil { + return nil, errors.New("category_id is required") + } + + // Проверяем, что категория существует + ctx := context.Background() + category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *req.CategoryID) + if err != nil { + return nil, err + } + if category == nil { + return nil, errors.New("category not found") + } + + // Проверяем, что код уникален + existingTopics, _, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalTopic{Code: req.Code}, + }) + if err != nil { + return nil, err + } + if len(existingTopics) > 0 { + return nil, errors.New("topic code already exists") + } + + // Устанавливаем значения по умолчанию + if req.IsActive == nil { + isActive := true + req.IsActive = &isActive + } + if req.ApprovalMode == nil { + mode := "sequential" + req.ApprovalMode = &mode + } + if req.AllowsFile == nil { + v := false + req.AllowsFile = &v + } + if req.AllowApproverSelection == nil { + v := false + req.AllowApproverSelection = &v + } + if req.AllowObserverSelection == nil { + v := false + req.AllowObserverSelection = &v + } + if req.RequireApproverComment == nil { + v := false + req.RequireApproverComment = &v + } + if req.RequiresFile == nil { + v := false + req.RequiresFile = &v + } + if req.RequireObserverSelection == nil { + v := false + req.RequireObserverSelection = &v + } + + createdTopic, _, err := s.ipc.Database.ApprovalTopic.CreateApprovalTopicDB(ctx, nil, &req, true) + if err != nil { + return nil, err + } + + // Подгружаем информацию о категории + if createdTopic.CategoryID != nil { + category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *createdTopic.CategoryID) + if err == nil && category != nil { + createdTopic.Category = category + } + } + + return createdTopic, nil +} + +// UpdateTopicHandler Обновление темы +// @Summary Обновление темы +// @Description Обновление данных существующей темы +// @Tags topics +// @Accept json +// @Produce json +// @Param request body typescore.ApprovalTopic true "Данные темы" +// @Success 200 {object} typescore.ApprovalTopic "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 404 {object} handlers.ErrorResponse "Тема не найдена" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/topics [put] +func (s *TopicsReg) UpdateTopicHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + defer r.Body.Close() + + body, err := io.ReadAll(r.Body) + if err != nil { + logrus.Error("🛑 UpdateTopicHandler: ReadAll error:", err) + return nil, err + } + + var req typescore.ApprovalTopic + if err := json.Unmarshal(body, &req); err != nil { + return nil, errors.New("invalid request body") + } + + if req.ID == nil { + return nil, errors.New("topic id is required") + } + + // Проверяем, что тема существует + ctx := context.Background() + existingTopic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *req.ID) + if err != nil { + return nil, err + } + if existingTopic == nil { + return nil, errors.New("topic not found") + } + + // Если обновляется category_id, проверяем, что категория существует + if req.CategoryID != nil { + if existingTopic.CategoryID == nil || *existingTopic.CategoryID != *req.CategoryID { + category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *req.CategoryID) + if err != nil { + return nil, err + } + if category == nil { + return nil, errors.New("category not found") + } + } + } + + // Если обновляется код, проверяем уникальность + if req.Code != nil && *req.Code != "" { + if existingTopic.Code == nil || *existingTopic.Code != *req.Code { + existingTopics, _, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalTopic{Code: req.Code}, + }) + if err != nil { + return nil, err + } + if len(existingTopics) > 0 { + return nil, errors.New("topic code already exists") + } + } + } + + updatedTopic, _, err := s.ipc.Database.ApprovalTopic.UpdateApprovalTopicDB(ctx, nil, &req, true) + if err != nil { + return nil, err + } + + // Подгружаем информацию о категории + if updatedTopic.CategoryID != nil { + category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *updatedTopic.CategoryID) + if err == nil && category != nil { + updatedTopic.Category = category + } + } + + return updatedTopic, nil +} + +// DeleteTopicHandler Удаление темы +// @Summary Удаление темы +// @Description Удаление темы по ID +// @Tags topics +// @Accept json +// @Produce json +// @Param request body typescore.ApprovalTopic true "ID темы для удаления" +// @Success 200 {object} bool "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 404 {object} handlers.ErrorResponse "Тема не найдена" +// @Failure 409 {object} handlers.ErrorResponse "Тема содержит заявки" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/topics [delete] +func (s *TopicsReg) DeleteTopicHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + defer r.Body.Close() + + body, err := io.ReadAll(r.Body) + if err != nil { + logrus.Error("🛑 DeleteTopicHandler: ReadAll error:", err) + return nil, err + } + + var req typescore.ApprovalTopic + if err := json.Unmarshal(body, &req); err != nil { + return nil, errors.New("invalid request body") + } + + if req.ID == nil { + return nil, errors.New("topic id is required") + } + + // Проверяем, что тема существует + ctx := context.Background() + existingTopic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *req.ID) + if err != nil { + return nil, err + } + if existingTopic == nil { + return nil, errors.New("topic not found") + } + + approvals, _, err := s.ipc.Database.Approval.GetApprovalsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.Approval{TopicID: req.ID}, + }) + if err != nil { + return nil, err + } + if len(approvals) > 0 { + return nil, errors.New("cannot delete topic: it has existing approvals") + } + + err = s.ipc.Database.ApprovalTopic.DeleteApprovalTopicDB(ctx, &req) + if err != nil { + return nil, err + } + + return true, nil +} diff --git a/service/rest_admin_service/handlers/topics/routes.go b/service/rest_admin_service/handlers/topics/routes.go new file mode 100644 index 0000000..527b914 --- /dev/null +++ b/service/rest_admin_service/handlers/topics/routes.go @@ -0,0 +1,39 @@ +package topicshandler + +import ( + "bitrix_balancer_api/rest_admin_service/handlers" + typesm "bitrix_balancer_api/rest_admin_service/types" + "net/http" + + "github.com/go-chi/chi/v5" +) + +type TopicsReg struct { + ipc *typesm.InternalProviderControl +} + +// RegisterTopicRoutes регистрирует маршруты для группы topics +func RegisterTopicRoutes( + r chi.Router, + ipc *typesm.InternalProviderControl, +) error { + s := &TopicsReg{ + ipc: ipc, + } + + r.Route("/api/topics", func(r chi.Router) { + r.Use(handlers.AccessCodeVerifier(ipc.Config)) + r.Use(handlers.JWTVerifier(ipc.Config, ipc.Database.Admin, ipc.RedisClient)) + + handlers.RegisterRoute(r, http.MethodGet, "/", s.GetTopicsListHandler) + handlers.RegisterRoute(r, http.MethodPost, "/", s.CreateTopicHandler) + handlers.RegisterRoute(r, http.MethodPut, "/", s.UpdateTopicHandler) + handlers.RegisterRoute(r, http.MethodDelete, "/", s.DeleteTopicHandler) + + r.Get("/{id}", handlers.WrapHandlerF(handlers.WrapHandlerParams{ + HandlerFunc: s.GetTopicByIDHandler, + })) + }) + + return nil +} diff --git a/service/rest_admin_service/handlers/user_hierarchy/handlers.go b/service/rest_admin_service/handlers/user_hierarchy/handlers.go new file mode 100644 index 0000000..e48b110 --- /dev/null +++ b/service/rest_admin_service/handlers/user_hierarchy/handlers.go @@ -0,0 +1,441 @@ +package hierarchieshandler + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/core/utilscore" + "context" + "encoding/json" + "errors" + "github.com/sirupsen/logrus" + "io" + "net/http" + "strconv" + + "github.com/go-chi/chi/v5" +) + +// GetHierarchiesListHandler Получение списка записей иерархии +// @Summary Получение списка записей иерархии +// @Description Получение списка связей подчинённый-согласующий с пагинацией и фильтрацией +// @Tags hierarchies +// @Accept json +// @Produce json +// @Param offset query integer false "Смещение для пагинации" +// @Param limit query integer false "Количество записей на странице" +// @Param subordinate_id query integer false "Фильтр по подчинённому" +// @Param approver_id query integer false "Фильтр по согласующему" +// @Param department_id query integer false "Фильтр по отделу" +// @Success 200 {object} typescore.ApiResponseBase "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/hierarchies [get] +func (s *HierarchiesReg) GetHierarchiesListHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + queryParams := r.URL.Query() + + hierarchyParams := &typescore.UserHierarchy{} + offset, limit, likeFields, errW := utilscore.ParseParamsGetRequest(queryParams, hierarchyParams) + if errW != nil { + return nil, errW + } + + options := typescore.ListDbOptions{ + Filtering: hierarchyParams, + Offset: offset, + Limit: limit, + LikeFields: likeFields, + } + + ctx := context.Background() + hierarchiesDbLst, total, errW := s.ipc.Database.UserHierarchy.GetUserHierarchyListDB(ctx, options) + if errW != nil { + return nil, errW + } + + // 🚀 Подгружаем связанные данные + for _, h := range hierarchiesDbLst { + s.enrichHierarchy(ctx, h) + } + + return &typescore.ApiResponseBase{ + TotalCount: total, + Data: hierarchiesDbLst, + }, nil +} + +// GetHierarchyByIDHandler Получение записи иерархии по ID +// @Summary Получение записи иерархии по ID +// @Description Получение детальной информации о записи иерархии по её ID +// @Tags hierarchies +// @Accept json +// @Produce json +// @Param id path integer true "ID записи" +// @Success 200 {object} typescore.UserHierarchy "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 404 {object} handlers.ErrorResponse "Запись не найдена" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/hierarchies/{id} [get] +func (s *HierarchiesReg) GetHierarchyByIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + idStr := chi.URLParam(r, "id") + if idStr == "" { + return nil, errors.New("hierarchy id is required") + } + + id, err := strconv.ParseUint(idStr, 10, 64) + if err != nil { + return nil, errors.New("invalid hierarchy id") + } + + ctx := context.Background() + hierarchies, _, err := s.ipc.Database.UserHierarchy.GetUserHierarchyListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.UserHierarchy{ID: &id}, + }) + if err != nil { + return nil, err + } + if len(hierarchies) == 0 { + return nil, errors.New("hierarchy not found") + } + + hierarchy := hierarchies[0] + s.enrichHierarchy(ctx, hierarchy) + + return hierarchy, nil +} + +// CreateHierarchyHandler Создание записи иерархии +// @Summary Создание записи иерархии +// @Description Создание новой связи подчинённый-согласующий +// @Tags hierarchies +// @Accept json +// @Produce json +// @Param request body typescore.UserHierarchy true "Данные иерархии" +// @Success 200 {object} typescore.UserHierarchy "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 409 {object} handlers.ErrorResponse "Такая связь уже существует" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/hierarchies [post] +func (s *HierarchiesReg) CreateHierarchyHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + defer r.Body.Close() + + body, err := io.ReadAll(r.Body) + if err != nil { + logrus.Error("🛑 CreateHierarchyHandler: ReadAll error:", err) + return nil, err + } + + var req typescore.UserHierarchy + if err := json.Unmarshal(body, &req); err != nil { + return nil, errors.New("invalid request body") + } + + // Валидация обязательных полей + if req.SubordinateID == nil { + return nil, errors.New("subordinate_id is required") + } + if req.ApproverID == nil { + return nil, errors.New("approver_id is required") + } + if req.DepartmentID == nil { + return nil, errors.New("department_id is required") + } + + ctx := context.Background() + + // Проверяем существование подчинённого + subordinate, err := s.ipc.Database.User.GetUserByIDDB(ctx, *req.SubordinateID) + if err != nil { + return nil, err + } + if subordinate == nil { + return nil, errors.New("subordinate user not found") + } + + // Проверяем существование согласующего + approver, err := s.ipc.Database.User.GetUserByIDDB(ctx, *req.ApproverID) + if err != nil { + return nil, err + } + if approver == nil { + return nil, errors.New("approver user not found") + } + + // Проверяем существование отдела + department, err := s.ipc.Database.Department.GetDepartmentByIDDB(ctx, *req.DepartmentID) + if err != nil { + return nil, err + } + if department == nil { + return nil, errors.New("department not found") + } + + // Если указана категория — проверяем её существование + if req.TopicCategoryID != nil { + category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *req.TopicCategoryID) + if err != nil { + return nil, err + } + if category == nil { + return nil, errors.New("topic category not found") + } + } + + // Если указана тема — проверяем её существование + if req.TopicID != nil { + topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *req.TopicID) + if err != nil { + return nil, err + } + if topic == nil { + return nil, errors.New("topic not found") + } + + // Проверяем, что тема принадлежит указанной категории (если обе указаны) + if req.TopicCategoryID != nil && topic.CategoryID != nil { + if *topic.CategoryID != *req.TopicCategoryID { + return nil, errors.New("topic does not belong to the specified category") + } + } + } + + // 🛡 Проверяем, что такая связь ещё не существует + existingHierarchies, _, err := s.ipc.Database.UserHierarchy.GetUserHierarchyListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.UserHierarchy{ + SubordinateID: req.SubordinateID, + ApproverID: req.ApproverID, + DepartmentID: req.DepartmentID, + TopicID: req.TopicID, + TopicCategoryID: req.TopicCategoryID, + }, + }) + if err != nil { + return nil, err + } + if len(existingHierarchies) > 0 { + return nil, errors.New("this hierarchy relation already exists") + } + + // Устанавливаем priority по умолчанию + if req.Priority == nil { + defaultPriority := 1 + req.Priority = &defaultPriority + } + + createdHierarchy, _, err := s.ipc.Database.UserHierarchy.CreateUserHierarchyDB(ctx, nil, &req, true) + if err != nil { + return nil, err + } + + s.enrichHierarchy(ctx, createdHierarchy) + + return createdHierarchy, nil +} + +// UpdateHierarchyHandler Обновление записи иерархии +// @Summary Обновление записи иерархии +// @Description Обновление данных существующей записи иерархии +// @Tags hierarchies +// @Accept json +// @Produce json +// @Param request body typescore.UserHierarchy true "Данные иерархии" +// @Success 200 {object} typescore.UserHierarchy "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 404 {object} handlers.ErrorResponse "Запись не найдена" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/hierarchies [put] +func (s *HierarchiesReg) UpdateHierarchyHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + defer r.Body.Close() + + body, err := io.ReadAll(r.Body) + if err != nil { + logrus.Error("🛑 UpdateHierarchyHandler: ReadAll error:", err) + return nil, err + } + + var req typescore.UserHierarchy + if err := json.Unmarshal(body, &req); err != nil { + return nil, errors.New("invalid request body") + } + + if req.ID == nil { + return nil, errors.New("hierarchy id is required") + } + + ctx := context.Background() + + // Проверяем, что запись существует + existingHierarchies, _, err := s.ipc.Database.UserHierarchy.GetUserHierarchyListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.UserHierarchy{ID: req.ID}, + }) + if err != nil { + return nil, err + } + if len(existingHierarchies) == 0 { + return nil, errors.New("hierarchy not found") + } + existing := existingHierarchies[0] + + // Если обновляется subordinate_id — проверяем существование + if req.SubordinateID != nil { + if existing.SubordinateID == nil || *existing.SubordinateID != *req.SubordinateID { + subordinate, err := s.ipc.Database.User.GetUserByIDDB(ctx, *req.SubordinateID) + if err != nil { + return nil, err + } + if subordinate == nil { + return nil, errors.New("subordinate user not found") + } + } + } + + // Если обновляется approver_id — проверяем существование + if req.ApproverID != nil { + if existing.ApproverID == nil || *existing.ApproverID != *req.ApproverID { + approver, err := s.ipc.Database.User.GetUserByIDDB(ctx, *req.ApproverID) + if err != nil { + return nil, err + } + if approver == nil { + return nil, errors.New("approver user not found") + } + } + } + + // Если обновляется department_id — проверяем существование + if req.DepartmentID != nil { + if existing.DepartmentID == nil || *existing.DepartmentID != *req.DepartmentID { + department, err := s.ipc.Database.Department.GetDepartmentByIDDB(ctx, *req.DepartmentID) + if err != nil { + return nil, err + } + if department == nil { + return nil, errors.New("department not found") + } + } + } + + // Если обновляется topic_category_id — проверяем существование + if req.TopicCategoryID != nil { + if existing.TopicCategoryID == nil || *existing.TopicCategoryID != *req.TopicCategoryID { + category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *req.TopicCategoryID) + if err != nil { + return nil, err + } + if category == nil { + return nil, errors.New("topic category not found") + } + } + } + + // Если обновляется topic_id — проверяем существование и принадлежность категории + if req.TopicID != nil { + if existing.TopicID == nil || *existing.TopicID != *req.TopicID { + topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *req.TopicID) + if err != nil { + return nil, err + } + if topic == nil { + return nil, errors.New("topic not found") + } + + // Проверяем соответствие категории + categoryIDToCheck := req.TopicCategoryID + if categoryIDToCheck == nil { + categoryIDToCheck = existing.TopicCategoryID + } + if categoryIDToCheck != nil && topic.CategoryID != nil && *topic.CategoryID != *categoryIDToCheck { + return nil, errors.New("topic does not belong to the specified category") + } + } + } + + updatedHierarchy, _, err := s.ipc.Database.UserHierarchy.UpdateUserHierarchyDB(ctx, nil, &req, true) + if err != nil { + return nil, err + } + + s.enrichHierarchy(ctx, updatedHierarchy) + + return updatedHierarchy, nil +} + +// DeleteHierarchyHandler Удаление записи иерархии +// @Summary Удаление записи иерархии +// @Description Удаление связи подчинённый-согласующий по ID +// @Tags hierarchies +// @Accept json +// @Produce json +// @Param request body typescore.UserHierarchy true "ID записи для удаления" +// @Success 200 {object} bool "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 404 {object} handlers.ErrorResponse "Запись не найдена" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/hierarchies [delete] +func (s *HierarchiesReg) DeleteHierarchyHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + defer r.Body.Close() + + body, err := io.ReadAll(r.Body) + if err != nil { + logrus.Error("🛑 DeleteHierarchyHandler: ReadAll error:", err) + return nil, err + } + + var req typescore.UserHierarchy + if err := json.Unmarshal(body, &req); err != nil { + return nil, errors.New("invalid request body") + } + + if req.ID == nil { + return nil, errors.New("hierarchy id is required") + } + + ctx := context.Background() + + // Проверяем, что запись существует + existingHierarchies, _, err := s.ipc.Database.UserHierarchy.GetUserHierarchyListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.UserHierarchy{ID: req.ID}, + }) + if err != nil { + return nil, err + } + if len(existingHierarchies) == 0 { + return nil, errors.New("hierarchy not found") + } + + err = s.ipc.Database.UserHierarchy.DeleteUserHierarchyDB(ctx, &req) + if err != nil { + return nil, err + } + + return true, nil +} + +// enrichHierarchy подгружает связанные данные для записи иерархии +func (s *HierarchiesReg) enrichHierarchy(ctx context.Context, h *typescore.UserHierarchy) { + if h == nil { + return + } + + // Подгружаем подчинённого + if h.SubordinateID != nil { + subordinate, err := s.ipc.Database.User.GetUserByIDDB(ctx, *h.SubordinateID) + if err == nil && subordinate != nil { + h.Subordinate = subordinate + } + } + + // Подгружаем согласующего + if h.ApproverID != nil { + approver, err := s.ipc.Database.User.GetUserByIDDB(ctx, *h.ApproverID) + if err == nil && approver != nil { + h.Approver = approver + } + } + + // Подгружаем отдел + if h.DepartmentID != nil { + department, err := s.ipc.Database.Department.GetDepartmentByIDDB(ctx, *h.DepartmentID) + if err == nil && department != nil { + h.Department = department + } + } +} diff --git a/service/rest_admin_service/handlers/user_hierarchy/routes.go b/service/rest_admin_service/handlers/user_hierarchy/routes.go new file mode 100644 index 0000000..b994103 --- /dev/null +++ b/service/rest_admin_service/handlers/user_hierarchy/routes.go @@ -0,0 +1,39 @@ +package hierarchieshandler + +import ( + "bitrix_balancer_api/rest_admin_service/handlers" + typesm "bitrix_balancer_api/rest_admin_service/types" + "net/http" + + "github.com/go-chi/chi/v5" +) + +type HierarchiesReg struct { + ipc *typesm.InternalProviderControl +} + +// RegisterHierarchyRoutes регистрирует маршруты для группы hierarchies +func RegisterHierarchyRoutes( + r chi.Router, + ipc *typesm.InternalProviderControl, +) error { + s := &HierarchiesReg{ + ipc: ipc, + } + + r.Route("/api/hierarchies", func(r chi.Router) { + r.Use(handlers.AccessCodeVerifier(ipc.Config)) + r.Use(handlers.JWTVerifier(ipc.Config, ipc.Database.Admin, ipc.RedisClient)) + + handlers.RegisterRoute(r, http.MethodGet, "/", s.GetHierarchiesListHandler) + handlers.RegisterRoute(r, http.MethodPost, "/", s.CreateHierarchyHandler) + handlers.RegisterRoute(r, http.MethodPut, "/", s.UpdateHierarchyHandler) + handlers.RegisterRoute(r, http.MethodDelete, "/", s.DeleteHierarchyHandler) + + r.Get("/{id}", handlers.WrapHandlerF(handlers.WrapHandlerParams{ + HandlerFunc: s.GetHierarchyByIDHandler, + })) + }) + + return nil +} diff --git a/service/rest_admin_service/handlers/user_roles/handlers.go b/service/rest_admin_service/handlers/user_roles/handlers.go new file mode 100644 index 0000000..ec9c6e1 --- /dev/null +++ b/service/rest_admin_service/handlers/user_roles/handlers.go @@ -0,0 +1,378 @@ +package userroleshandler + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/core/utilscore" + "context" + "encoding/json" + "errors" + "github.com/sirupsen/logrus" + "io" + "net/http" + "strconv" + + "github.com/go-chi/chi/v5" +) + +// AssignUserRoleRequest — запрос на назначение роли пользователю +type AssignUserRoleRequest struct { + UserID *uint64 `json:"user_id"` + RoleID *uint64 `json:"role_id"` +} + +// BulkAssignRolesRequest — запрос на массовое назначение ролей +type BulkAssignRolesRequest struct { + UserID *uint64 `json:"user_id"` + RoleIDs []*uint64 `json:"role_ids"` +} + +// GetUserRolesListHandler Получение списка ролей пользователя +// @Summary Получение списка ролей пользователя +// @Description Получение списка ролей, назначенных конкретному пользователю +// @Tags user-roles +// @Accept json +// @Produce json +// @Param user_id query integer true "ID пользователя" +// @Success 200 {object} typescore.ApiResponseBase "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/user-roles [get] +func (s *UserRolesReg) GetUserRolesListHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + queryParams := r.URL.Query() + + roleParams := &typescore.UserRole{} + offset, limit, likeFields, errW := utilscore.ParseParamsGetRequest(queryParams, roleParams) + if errW != nil { + return nil, errW + } + + // user_id обязателен для этого эндпоинта + if roleParams.UserID == nil { + return nil, errors.New("user_id is required") + } + + options := typescore.ListDbOptions{ + Filtering: roleParams, + Offset: offset, + Limit: limit, + LikeFields: likeFields, + } + + ctx := context.Background() + userRolesDbLst, total, errW := s.ipc.Database.UserRole.GetUserRolesListDB(ctx, options) + if errW != nil { + return nil, errW + } + + // 🚀 Подгружаем информацию о ролях + for _, ur := range userRolesDbLst { + if ur.RoleID != nil { + role, err := s.ipc.Database.Role.GetRoleByIDDB(ctx, *ur.RoleID) + if err == nil && role != nil { + ur.Role = role + } + } + } + + return &typescore.ApiResponseBase{ + TotalCount: total, + Data: userRolesDbLst, + }, nil +} + +// GetUserRolesByUserIDHandler Получение списка ролей пользователя по ID из URL +// @Summary Получение списка ролей пользователя по ID +// @Description Получение списка ролей, назначенных пользователю с указанным ID +// @Tags user-roles +// @Accept json +// @Produce json +// @Param user_id path integer true "ID пользователя" +// @Success 200 {object} typescore.ApiResponseBase "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 404 {object} handlers.ErrorResponse "Пользователь не найден" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/users/{user_id}/roles [get] +func (s *UserRolesReg) GetUserRolesByUserIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + userIDStr := chi.URLParam(r, "user_id") + if userIDStr == "" { + return nil, errors.New("user_id is required") + } + + userID, err := strconv.ParseUint(userIDStr, 10, 64) + if err != nil { + return nil, errors.New("invalid user_id") + } + + ctx := context.Background() + + // Проверяем, что пользователь существует + user, err := s.ipc.Database.User.GetUserByIDDB(ctx, userID) + if err != nil { + return nil, err + } + if user == nil { + return nil, errors.New("user not found") + } + + userRolesDbLst, _, errW := s.ipc.Database.UserRole.GetUserRolesListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.UserRole{UserID: &userID}, + }) + if errW != nil { + return nil, errW + } + + // 🚀 Подгружаем информацию о ролях + for _, ur := range userRolesDbLst { + if ur.RoleID != nil { + role, err := s.ipc.Database.Role.GetRoleByIDDB(ctx, *ur.RoleID) + if err == nil && role != nil { + ur.Role = role + } + } + } + + return &typescore.ApiResponseBase{ + TotalCount: uint64(len(userRolesDbLst)), + Data: userRolesDbLst, + }, nil +} + +// AssignUserRoleHandler Назначение роли пользователю +// @Summary Назначение роли пользователю +// @Description Назначение роли пользователю (создание связи user_id + role_id) +// @Tags user-roles +// @Accept json +// @Produce json +// @Param request body AssignUserRoleRequest true "user_id и role_id" +// @Success 200 {object} typescore.UserRole "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 404 {object} handlers.ErrorResponse "Пользователь или роль не найдены" +// @Failure 409 {object} handlers.ErrorResponse "Роль уже назначена" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/user-roles [post] +func (s *UserRolesReg) AssignUserRoleHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + defer r.Body.Close() + + body, err := io.ReadAll(r.Body) + if err != nil { + logrus.Error("🛑 AssignUserRoleHandler: ReadAll error:", err) + return nil, err + } + + var req AssignUserRoleRequest + if err := json.Unmarshal(body, &req); err != nil { + return nil, errors.New("invalid request body") + } + + if req.UserID == nil { + return nil, errors.New("user_id is required") + } + if req.RoleID == nil { + return nil, errors.New("role_id is required") + } + + ctx := context.Background() + + // Проверяем, что пользователь существует + user, err := s.ipc.Database.User.GetUserByIDDB(ctx, *req.UserID) + if err != nil { + return nil, err + } + if user == nil { + return nil, errors.New("user not found") + } + + // Проверяем, что роль существует + role, err := s.ipc.Database.Role.GetRoleByIDDB(ctx, *req.RoleID) + if err != nil { + return nil, err + } + if role == nil { + return nil, errors.New("role not found") + } + + // 🛡 Проверяем, что такая связь ещё не существует + existingRoles, _, err := s.ipc.Database.UserRole.GetUserRolesListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.UserRole{ + UserID: req.UserID, + RoleID: req.RoleID, + }, + }) + if err != nil { + return nil, err + } + if len(existingRoles) > 0 { + return nil, errors.New("this role is already assigned to the user") + } + + userRoleObj := &typescore.UserRole{ + UserID: req.UserID, + RoleID: req.RoleID, + } + + createdUserRole, _, err := s.ipc.Database.UserRole.CreateUserRoleDB(ctx, nil, userRoleObj, true) + if err != nil { + return nil, err + } + + // Подгружаем информацию о роли + if createdUserRole.RoleID != nil { + role, err := s.ipc.Database.Role.GetRoleByIDDB(ctx, *createdUserRole.RoleID) + if err == nil && role != nil { + createdUserRole.Role = role + } + } + + return createdUserRole, nil +} + +// BulkAssignRolesHandler Массовое назначение ролей пользователю +// @Summary Массовое назначение ролей +// @Description Полная замена ролей пользователя: удаляет все текущие роли и назначает новые +// @Tags user-roles +// @Accept json +// @Produce json +// @Param request body BulkAssignRolesRequest true "user_id и список role_ids" +// @Success 200 {object} typescore.ApiResponseBase "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 404 {object} handlers.ErrorResponse "Пользователь не найден" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/user-roles/bulk [post] +func (s *UserRolesReg) BulkAssignRolesHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + defer r.Body.Close() + + body, err := io.ReadAll(r.Body) + if err != nil { + logrus.Error("🛑 BulkAssignRolesHandler: ReadAll error:", err) + return nil, err + } + + var req BulkAssignRolesRequest + if err := json.Unmarshal(body, &req); err != nil { + return nil, errors.New("invalid request body") + } + + if req.UserID == nil { + return nil, errors.New("user_id is required") + } + + ctx := context.Background() + + // Проверяем, что пользователь существует + user, err := s.ipc.Database.User.GetUserByIDDB(ctx, *req.UserID) + if err != nil { + return nil, err + } + if user == nil { + return nil, errors.New("user not found") + } + + // 🗑 Удаляем все текущие роли пользователя + existingRoles, _, err := s.ipc.Database.UserRole.GetUserRolesListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.UserRole{UserID: req.UserID}, + }) + if err != nil { + return nil, err + } + + for _, existingRole := range existingRoles { + if err := s.ipc.Database.UserRole.DeleteUserRoleDB(ctx, existingRole); err != nil { + logrus.Errorf("BulkAssignRolesHandler: failed to delete user_role id=%d: %v", *existingRole.ID, err) + return nil, err + } + } + + // 🆕 Назначаем новые роли + var createdRoles []*typescore.UserRole + for _, roleID := range req.RoleIDs { + if roleID == nil { + continue + } + + // Проверяем, что роль существует + role, err := s.ipc.Database.Role.GetRoleByIDDB(ctx, *roleID) + if err != nil { + return nil, err + } + if role == nil { + return nil, errors.New("role not found: " + strconv.FormatUint(*roleID, 10)) + } + + userRoleObj := &typescore.UserRole{ + UserID: req.UserID, + RoleID: roleID, + } + + createdUserRole, _, err := s.ipc.Database.UserRole.CreateUserRoleDB(ctx, nil, userRoleObj, true) + if err != nil { + logrus.Errorf("BulkAssignRolesHandler: failed to create user_role: %v", err) + return nil, err + } + + // Подгружаем информацию о роли + if createdUserRole != nil && createdUserRole.RoleID != nil { + role, err := s.ipc.Database.Role.GetRoleByIDDB(ctx, *createdUserRole.RoleID) + if err == nil && role != nil { + createdUserRole.Role = role + } + } + + createdRoles = append(createdRoles, createdUserRole) + } + + return &typescore.ApiResponseBase{ + TotalCount: uint64(len(createdRoles)), + Data: createdRoles, + }, nil +} + +// RemoveUserRoleHandler Удаление роли у пользователя +// @Summary Удаление роли у пользователя +// @Description Удаление связи user_id + role_id по ID записи +// @Tags user-roles +// @Accept json +// @Produce json +// @Param request body typescore.UserRole true "ID записи для удаления" +// @Success 200 {object} bool "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 404 {object} handlers.ErrorResponse "Запись не найдена" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/user-roles [delete] +func (s *UserRolesReg) RemoveUserRoleHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + defer r.Body.Close() + + body, err := io.ReadAll(r.Body) + if err != nil { + logrus.Error("🛑 RemoveUserRoleHandler: ReadAll error:", err) + return nil, err + } + + var req typescore.UserRole + if err := json.Unmarshal(body, &req); err != nil { + return nil, errors.New("invalid request body") + } + + if req.ID == nil { + return nil, errors.New("user_role id is required") + } + + ctx := context.Background() + + // Проверяем, что запись существует + existingRoles, _, err := s.ipc.Database.UserRole.GetUserRolesListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.UserRole{ID: req.ID}, + }) + if err != nil { + return nil, err + } + if len(existingRoles) == 0 { + return nil, errors.New("user_role not found") + } + + err = s.ipc.Database.UserRole.DeleteUserRoleDB(ctx, &req) + if err != nil { + return nil, err + } + + return true, nil +} diff --git a/service/rest_admin_service/handlers/user_roles/routes.go b/service/rest_admin_service/handlers/user_roles/routes.go new file mode 100644 index 0000000..190164f --- /dev/null +++ b/service/rest_admin_service/handlers/user_roles/routes.go @@ -0,0 +1,53 @@ +package userroleshandler + +import ( + "bitrix_balancer_api/rest_admin_service/handlers" + typesm "bitrix_balancer_api/rest_admin_service/types" + "net/http" + + "github.com/go-chi/chi/v5" +) + +type UserRolesReg struct { + ipc *typesm.InternalProviderControl +} + +// RegisterUserRoleRoutes регистрирует маршруты для группы user-roles +func RegisterUserRoleRoutes( + r chi.Router, + ipc *typesm.InternalProviderControl, +) error { + s := &UserRolesReg{ + ipc: ipc, + } + + // Основной маршрут для управления ролями + r.Route("/api/user-roles", func(r chi.Router) { + r.Use(handlers.AccessCodeVerifier(ipc.Config)) + r.Use(handlers.JWTVerifier(ipc.Config, ipc.Database.Admin, ipc.RedisClient)) + + // GET /api/user-roles?user_id=X - список ролей пользователя + handlers.RegisterRoute(r, http.MethodGet, "/", s.GetUserRolesListHandler) + + // POST /api/user-roles - назначить роль пользователю + handlers.RegisterRoute(r, http.MethodPost, "/", s.AssignUserRoleHandler) + + // DELETE /api/user-roles - удалить роль у пользователя + handlers.RegisterRoute(r, http.MethodDelete, "/", s.RemoveUserRoleHandler) + + // POST /api/user-roles/bulk - массовое назначение ролей + handlers.RegisterRoute(r, http.MethodPost, "/bulk", s.BulkAssignRolesHandler) + }) + + // Альтернативный маршрут: GET /api/users/{user_id}/roles + r.Route("/api/users/{user_id}/roles", func(r chi.Router) { + r.Use(handlers.AccessCodeVerifier(ipc.Config)) + r.Use(handlers.JWTVerifier(ipc.Config, ipc.Database.Admin, ipc.RedisClient)) + + r.Get("/", handlers.WrapHandlerF(handlers.WrapHandlerParams{ + HandlerFunc: s.GetUserRolesByUserIDHandler, + })) + }) + + return nil +} diff --git a/service/rest_admin_service/handlers/users/handlers.go b/service/rest_admin_service/handlers/users/handlers.go new file mode 100644 index 0000000..bff6aec --- /dev/null +++ b/service/rest_admin_service/handlers/users/handlers.go @@ -0,0 +1,237 @@ +package usershandler + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/core/utilscore" + "context" + "encoding/json" + "errors" + "github.com/sirupsen/logrus" + "io" + "net/http" + "strconv" + + "github.com/go-chi/chi/v5" +) + +// GetUserListHandler Получение списка пользователей +// @Summary Получение списка пользователей +// @Description Получение списка пользователей с пагинацией, фильтрацией и подгрузкой связанных данных +// @Tags users +// @Accept json +// @Produce json +// @Param offset query integer false "Смещение для пагинации" +// @Param limit query integer false "Количество записей на странице" +// @Param is_blocked query boolean false "Фильтр по блокировке" +// @Param is_fired query boolean false "Фильтр по увольнению" +// @Param department_id query integer false "Фильтр по отделу" +// @Success 200 {object} typescore.ApiResponseBase "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/users [get] +func (s *UserReg) GetUserListHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + queryParams := r.URL.Query() + + userParams := &typescore.User{} + offset, limit, likeFields, errW := utilscore.ParseParamsGetRequest(queryParams, userParams) + if errW != nil { + return nil, errW + } + + options := typescore.ListDbOptions{ + Filtering: userParams, + Offset: offset, + Limit: limit, + LikeFields: likeFields, + } + + ctx := context.Background() + userDbLst, total, errW := s.ipc.Database.User.GetUsersListDB(ctx, options) + if errW != nil { + return nil, errW + } + + // 🚀 Подгружаем связанные данные для каждого пользователя + for _, user := range userDbLst { + // Подгружаем отдел + if user.DepartmentID != nil { + department, err := s.ipc.Database.Department.GetDepartmentByIDDB(ctx, *user.DepartmentID) + if err == nil && department != nil { + user.Department = department + } + } + + // Подгружаем роли пользователя + userRoles, _, err := s.ipc.Database.UserRole.GetUserRolesListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.UserRole{UserID: user.ID}, + }) + if err == nil && len(userRoles) > 0 { + // Для каждой роли подгружаем информацию о роли + for _, ur := range userRoles { + if ur.RoleID != nil { + role, err := s.ipc.Database.Role.GetRoleByIDDB(ctx, *ur.RoleID) + if err == nil && role != nil { + ur.Role = role + } + } + } + user.UserRoles = userRoles + } + } + + return &typescore.ApiResponseBase{ + TotalCount: total, + Data: userDbLst, + }, nil +} + +// GetUserByIDHandler Получение пользователя по ID +// @Summary Получение пользователя по ID +// @Description Получение детальной информации о пользователе по его ID с подгрузкой связанных данных +// @Tags users +// @Accept json +// @Produce json +// @Param id path integer true "ID пользователя" +// @Success 200 {object} typescore.User "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 404 {object} handlers.ErrorResponse "Пользователь не найден" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/users/{id} [get] +func (s *UserReg) GetUserByIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + idStr := chi.URLParam(r, "id") + if idStr == "" { + return nil, errors.New("user id is required") + } + + id, err := strconv.ParseUint(idStr, 10, 64) + if err != nil { + return nil, errors.New("invalid user id") + } + + ctx := context.Background() + user, err := s.ipc.Database.User.GetUserByIDDB(ctx, id) + if err != nil { + return nil, err + } + + if user == nil { + return nil, errors.New("user not found") + } + + // 🚀 Подгружаем отдел + if user.DepartmentID != nil { + department, err := s.ipc.Database.Department.GetDepartmentByIDDB(ctx, *user.DepartmentID) + if err == nil && department != nil { + user.Department = department + } + } + + // 🚀 Подгружаем роли пользователя + userRoles, _, err := s.ipc.Database.UserRole.GetUserRolesListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.UserRole{UserID: user.ID}, + }) + if err == nil && len(userRoles) > 0 { + // Для каждой роли подгружаем информацию о роли + for _, ur := range userRoles { + if ur.RoleID != nil { + role, err := s.ipc.Database.Role.GetRoleByIDDB(ctx, *ur.RoleID) + if err == nil && role != nil { + ur.Role = role + } + } + } + user.UserRoles = userRoles + } + + return user, nil +} + +// UpdateUserHandler Обновление пользователя +// @Summary Обновление пользователя +// @Description Обновление данных существующего пользователя +// @Tags users +// @Accept json +// @Produce json +// @Param request body typescore.UpdateUserReqAdmin true "Данные пользователя" +// @Success 200 {object} typescore.User "Успех" +// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" +// @Failure 404 {object} handlers.ErrorResponse "Пользователь не найден" +// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" +// @Router /api/users [put] +func (s *UserReg) UpdateUserHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + body, err := io.ReadAll(r.Body) + if err != nil { + logrus.Error("🛑 UpdateUserHandler: ReadAll error:", err) + return nil, err + } + defer r.Body.Close() + + var req typescore.UpdateUserReqAdmin + if err := json.Unmarshal(body, &req); err != nil { + return nil, errors.New("invalid request body") + } + + if req.ID == nil { + return nil, errors.New("user id is required") + } + + // Проверяем, что пользователь существует + ctx := context.Background() + existingUser, err := s.ipc.Database.User.GetUserByIDDB(ctx, *req.ID) + if err != nil { + return nil, err + } + if existingUser == nil { + return nil, errors.New("user not found") + } + + // Если обновляется department_id, проверяем, что отдел существует + if req.DepartmentID != nil { + if existingUser.DepartmentID == nil || *existingUser.DepartmentID != *req.DepartmentID { + department, err := s.ipc.Database.Department.GetDepartmentByIDDB(ctx, *req.DepartmentID) + if err != nil { + return nil, err + } + if department == nil { + return nil, errors.New("department not found") + } + } + } + + upUserObj := &typescore.User{ + ID: req.ID, + DepartmentID: req.DepartmentID, + IsBlocked: req.IsBlocked, + IsFired: req.IsFired, + } + + upUser, _, errW := s.ipc.Database.User.UpdateUserDB(ctx, nil, upUserObj, true) + if errW != nil { + return nil, errW + } + + // Подгружаем связанные данные + if upUser.DepartmentID != nil { + department, err := s.ipc.Database.Department.GetDepartmentByIDDB(ctx, *upUser.DepartmentID) + if err == nil && department != nil { + upUser.Department = department + } + } + + userRoles, _, err := s.ipc.Database.UserRole.GetUserRolesListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.UserRole{UserID: upUser.ID}, + }) + if err == nil && len(userRoles) > 0 { + for _, ur := range userRoles { + if ur.RoleID != nil { + role, err := s.ipc.Database.Role.GetRoleByIDDB(ctx, *ur.RoleID) + if err == nil && role != nil { + ur.Role = role + } + } + } + upUser.UserRoles = userRoles + } + + return upUser, nil +} diff --git a/service/rest_admin_service/handlers/users/routes.go b/service/rest_admin_service/handlers/users/routes.go new file mode 100644 index 0000000..159d165 --- /dev/null +++ b/service/rest_admin_service/handlers/users/routes.go @@ -0,0 +1,37 @@ +package usershandler + +import ( + "bitrix_balancer_api/rest_admin_service/handlers" + typesm "bitrix_balancer_api/rest_admin_service/types" + "net/http" + + "github.com/go-chi/chi/v5" +) + +type UserReg struct { + ipc *typesm.InternalProviderControl +} + +// RegisterUserRoutes регистрирует маршруты для группы users +func RegisterUserRoutes( + r chi.Router, + ipc *typesm.InternalProviderControl, +) error { + s := &UserReg{ + ipc: ipc, + } + + r.Route("/api/users", func(r chi.Router) { + r.Use(handlers.AccessCodeVerifier(ipc.Config)) + r.Use(handlers.JWTVerifier(ipc.Config, ipc.Database.Admin, ipc.RedisClient)) + + handlers.RegisterRoute(r, http.MethodGet, "/", s.GetUserListHandler) + handlers.RegisterRoute(r, http.MethodPut, "/", s.UpdateUserHandler) + + r.Get("/{id}", handlers.WrapHandlerF(handlers.WrapHandlerParams{ + HandlerFunc: s.GetUserByIDHandler, + })) + }) + + return nil +} diff --git a/service/telegram_service/common/update/callback.go b/service/telegram_service/common/update/callback.go index 31461ec..d637a2c 100644 --- a/service/telegram_service/common/update/callback.go +++ b/service/telegram_service/common/update/callback.go @@ -26,6 +26,9 @@ func (s *UpdateHandler) handleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.Callba taskID := parseID(data, "task_complete:") s.approvalHandler.HandleCompleteTask(bot, cq, taskID) + case strings.HasPrefix(data, "obs_select_confirm"): + s.approvalHandler.HandleObserverConfirmCallback(bot, cq) + case strings.HasPrefix(data, "appr_yes:"): approvalID := parseID(data, "appr_yes:") logrus.Infof("handleCallback: appr_yes approvalID=%d", approvalID)