diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml new file mode 100644 index 0000000..68e97bb --- /dev/null +++ b/.gitea/workflows/deploy.yml @@ -0,0 +1,507 @@ +name: Deploy + +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 + 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 + + # ═══════════════════════════════════════════════════════════════ + # ШАГ 4: Inject config + # ═══════════════════════════════════════════════════════════════ + - name: 🔐 Inject Config + if: env.SKIP_DEPLOY == 'false' + run: | + 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" + + # ═══════════════════════════════════════════════════════════════ + # ШАГ 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/.gitignore b/.gitignore new file mode 100644 index 0000000..e928d8f --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +.DS_STORE +.idea diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 0000000..ea1405d --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,52 @@ +linters-settings: + errcheck: # Настройки для линтера errcheck, который проверяет, что ошибки не игнорируются + check-type-assertions: true # Не проверять утверждения типов на ошибки + check-blank: true # Проверять игнорирование ошибок через присваивание в _ + prealloc: # Настройки для линтера prealloc, который предлагает предварительное выделение памяти для срезов + simple: true # Простой режим, предлагает предварительное выделение для простых циклов + range-loops: true # Предлагает предварительное выделение для циклов range + for-loops: false # Не предлагает предварительное выделение для обычных for-циклов + gocyclo: # Настройки для линтера gocyclo, который проверяет сложность функций + min-complexity: 15 # Установите порог сложности, который считаете приемлемым + +linters: + enable: # Список линтеров, которые будут включены + - noctx # Находит отправку HTTP-запроса без контекста.Контекст. + - protogetter # Сообщает о прямом чтении из полей прото-сообщения, когда следует использовать геттеры. + - reassign # Проверяет, что переменные пакета не переназначаются. + - rowserrcheck # Проверяет, успешно ли проверен Rows.Err строк. + - sqlclosecheck # Проверяет, что sql.Rows, sql.Stmt, sqlx.NamedStmt, pgx.Query закрыты. + - ineffassign # Обнаруживает, когда назначения существующим переменным не используются. + - nilerr # Находит код, который возвращает ноль, даже если он проверяет, что ошибка не равна нулю. + - makezero # Проверяет, что нулевые значения создаются правильно + - gochecksumtype # Проверяет, что тип контрольной суммы в go.sum соответствует содержимому + - copyloopvar # Проверяет, что циклические зависимости пакетов не имеют экспортируемых идентификаторов + - exhaustive # Проверьте полноту операторов перечисления. + - errchkjson # Проверяет типы, передаваемые функциям кодирования JSON. Сообщает о неподдерживаемых типах и событиях, при которых проверку возвращаемой ошибки можно опустить. + - durationcheck # Проверяет, что длительность таймаута не равна 0 + - contextcheck # Проверяет, что контекст не игнорируется + - bodyclose # Проверяет, что тело запроса закрывается + - bidichk # Проверяет, что строки в исходном коде не содержат символов из разных языков + - govet # Проверяет код на наличие конструкций, которые могут быть ошибочными + - errcheck # Проверяет, что ошибки не игнорируются + - staticcheck # Статический анализ кода, находит ошибки, неэффективные конструкции и т.д. + - unused # Проверяет на неиспользуемые переменные, функции, константы + - gocritic # Линтер, основанный на проверке кода на соответствие определенным критериям качества и стиля + - stylecheck # Проверяет стиль кодирования + - whitespace # Проверяет проблемы с пробелами в коде + - gosec # Линтер gosec, который проверяет код на наличие потенциальных уязвимостей + - prealloc # Предлагает предварительное выделение памяти для срезов + + - dupl # Находит дублирующийся код + - gocyclo # Проверяет сложность функций + - ineffassign # Обнаруживает неэффективные присваивания + - unparam # Находит неиспользуемые параметры функций + + - gosimple # Предлагает упрощения кода + + disable: # Список линтеров, которые будут отключены + - gofumpt # Более строгая версия gofmt, применяет дополнительные правила форматирования + # - golint # Отключает golint, который проверяет стиль написания кода на Go + +run: + timeout: 15m # Устанавливает тайм-аут для выполнения всех линтеров \ No newline at end of file diff --git a/README.md b/README.md index 7782779..968d04e 100644 --- a/README.md +++ b/README.md @@ -1 +1,658 @@ -# Project Init +# 🏢 Портал Сотрудника — RuspetPortal + +
+ +**Корпоративная CRM-система для управления сотрудниками, задачами и процессами согласования** + +![Go](https://img.shields.io/badge/Go-1.21+-00ADD8?style=flat&logo=go&logoColor=white) +![PostgreSQL](https://img.shields.io/badge/PostgreSQL-15+-4169E1?style=flat&logo=postgresql&logoColor=white) +![Redis](https://img.shields.io/badge/Redis-7+-DC382D?style=flat&logo=redis&logoColor=white) +![gRPC](https://img.shields.io/badge/gRPC-1.60+-244C5A?style=flat&logo=grpc) +![Telegram](https://img.shields.io/badge/Telegram_Bot-API-26A5E4?style=flat&logo=telegram) + +
+ +--- + +## 📋 Содержание + +- [О проекте](#о-проекте) +- [Архитектура](#архитектура) +- [Сервисы](#сервисы) +- [Технологический стек](#технологический-стек) +- [Структура проекта](#структура-проекта) +- [Быстрый старт](#быстрый-старт) +- [Конфигурация](#конфигурация) +- [База данных](#база-данных) +- [API](#api) +- [Telegram Bot](#telegram-bot) +- [Разработка](#разработка) + +--- + +## 🎯 О проекте + +**Портал Сотрудника** — это внутренняя корпоративная платформа, объединяющая в себе: + +- 📊 Управление сотрудниками и их профилями +- ✅ Систему согласований через Telegram (отпуска, отгулы, закупки, расходы и др.) +- 📦 Управление заявками на заказ товаров +- 🔔 Уведомления об отсутствующих сотрудниках и ВРИО +- 📋 Систему задач и поручений +- 🔐 Авторизацию и управление правами доступа + +Проект построен на микросервисной архитектуре — каждый сервис решает строго определённую задачу и общается с другими через gRPC или REST API. + +--- + +## 🏗️ Архитектура + +``` +┌─────────────────────────────────────────────────────────────────┐ +│ Клиенты │ +│ Web App Telegram Bot │ +└────────────────┬─────────────────────────┬──────────────────────┘ + │ REST │ Bot API (SOCKS5/HTTP) + ▼ ▼ +┌────────────────────────┐ ┌─────────────────────────────────┐ +│ rest_user_service │ │ telegram_service │ +│ rest_admin_service │ │ (Система согласований) │ +└────────┬───────────────┘ └──────────────┬──────────────────┘ + │ gRPC │ gRPC + ▼ ▼ +┌─────────────────┐ ┌──────────────────────────────────────┐ +│ auth_service │ │ tasks_service │ +│ user_service │ │ goods_order_service │ +└────────┬────────┘ └──────────────┬───────────────────────┘ + │ │ + ▼ ▼ +┌─────────────────────────────────────────────────────────────┐ +│ core │ +│ Типы • БД-методы • Утилиты • Библиотеки │ +└──────────────────────────────┬──────────────────────────────┘ + │ + ┌────────────────┼─────────────────┐ + ▼ ▼ ▼ + PostgreSQL Redis system_service + (Миграции / Фоновые задачи) +``` + +--- + +## 📦 Сервисы + +### `core` — Ядро системы +Общая библиотека, используемая всеми сервисами. Содержит: +- **`typescore/`** — все модели данных (User, Approval, Role, Department и др.) +- **`db/dbcore/`** — методы работы с PostgreSQL (pgx + squirrel) +- **`utilscore/`** — вспомогательные функции +- **`db/table_names/`** — константы названий таблиц +- **`db/dbutils/`** — утилиты для построения запросов (GenerateInsertRequest, ScanRowsToStructRows и др.) + +> ⚠️ Изменения в `core` затрагивают все сервисы. Вносить с осторожностью. + +--- + +### `auth_service` — Авторизация +gRPC-сервис авторизации. Обрабатывает: +- Вход по логину/паролю +- Генерацию и валидацию JWT-токенов +- Обновление токенов (refresh) +- Связан с `rest_user_service` для проверки прав + +**Порт:** настраивается в конфиге +**Протокол:** gRPC + +--- + +### `rest_user_service` — API для клиентского приложения +REST API для веб/мобильного клиента: +- Профиль пользователя +- Список сотрудников +- Уведомления +- Заявки и задачи + +**Порт:** настраивается в конфиге +**Протокол:** HTTP/REST (Gin) + +--- + +### `rest_admin_service` — API для административной панели +REST API для внутренней администрации: +- Управление пользователями и ролями +- Управление отделами +- Настройка иерархий согласования +- Управление правами доступа (permissions) +- Просмотр и управление всеми заявками + +**Порт:** настраивается в конфиге +**Протокол:** HTTP/REST (Gin) + +--- + +### `tasks_service` — Сервис задач +gRPC-сервис управления задачами и поручениями: +- Создание задач +- Назначение исполнителей +- Отслеживание статусов +- Интеграция с системой согласований + +**Протокол:** gRPC + +--- + +### `system_service` — Системный сервис +Фоновый сервис без внешних точек доступа: +- **Миграции БД** — запускаются при старте, поддерживают схему в актуальном состоянии +- **Фоновые задачи** — периодические задания (планировщики, чистка данных, напоминания) +- Планировщик уведомлений о делегировании прав +- Планировщик отчётов об отсутствующих сотрудниках + +--- + +### `telegram_service` — Telegram Bot +Ключевой сервис системы согласований через Telegram: + +**Возможности:** +- 📋 Многоуровневая система согласований (до N шагов) +- 🌳 Гибкие деревья тем (отгулы, отпуска, больничные, закупки, расходы и др.) +- 👥 Дополнительные согласующие +- 🔄 Возврат на доработку с комментарием +- 📁 Прикрепление файлов к заявкам +- 💬 Комментарии от согласующих/наблюдателей/исполнителей +- 👁️ Наблюдатели с уведомлениями +- 🎯 Задачи для исполнителей после согласования +- 🔀 Делегирование прав согласования +- 📊 Отчёты по согласованиям +- 📢 Ежедневные отчёты об отсутствующих в группу с ВРИО +- 💡 Предложения и пожелания (диалог инициатор ↔ директор) + +**Прокси:** поддержка SOCKS5 и HTTP прокси (обязательно для работы в РФ) + +--- + +### `user_service` — Профиль пользователя +gRPC-сервис управления профилями: +- Данные сотрудника +- Отдел и должность +- Роли и права +- История активности + +--- + +### `goods_order_service` — Заявки на заказ товаров +Сервис обработки заявок на заказ: +- Создание заявок на месяц и дополнительных +- Процесс согласования +- Назначение исполнителей +- Отслеживание статусов + +--- + +## 🛠️ Технологический стек + +| Категория | Технология | Версия | Назначение | +|-----------|---------------------|--------|------------| +| **Язык** | Go | 1.21+ | Основной язык разработки | +| **БД** | PostgreSQL | 15+ | Основная реляционная БД | +| **Кэш** | Redis | 7+ | Сессии, состояния флоу, кэш | +| **RPC** | gRPC + protobuf | latest | Межсервисное взаимодействие | +| **HTTP** | chi | v5 | REST API сервисы | +| **БД-драйвер** | pgx/v5 | v5 | PostgreSQL драйвер | +| **Query Builder** | squirrel | latest | Построение SQL-запросов | +| **Telegram** | go-telegram-bot-api | v5 | Telegram Bot API | +| **Прокси** | golang.org/x/net | latest | SOCKS5 прокси для Telegram | +| **Логирование** | logrus | latest | Структурированные логи | +| **Конфиг** | embed / envconfig | latest | Конфигурация из env/файлов | +| **Миграции** | gorm | latest | Управление схемой БД | + +--- + +## 📁 Структура проекта + +``` +ruspetportal/ +│ +├── core/ # Общее ядро +│ ├── typescore/ # Модели данных +│ │ └── models.go # User, Approval, Role, Department... +│ ├── db/ +│ │ ├── dbcore/ # Реализации методов БД +│ │ │ ├── user.go +│ │ │ ├── approval.go +│ │ │ └── ... +│ │ ├── table_names/ # Константы имён таблиц +│ │ └── dbutils/ # Утилиты для работы с БД +│ └── utilscore/ # Вспомогательные функции +│ +├── auth_service/ # Сервис авторизации +│ ├── cmd/main.go +│ ├── handlers/ +│ └── proto/ +│ +├── rest_user_service/ # REST API для клиента +│ ├── cmd/main.go +│ ├── handlers/ +│ ├── middleware/ +│ └── routes/ +│ +├── rest_admin_service/ # REST API для админки +│ ├── cmd/main.go +│ ├── handlers/ +│ ├── middleware/ +│ └── routes/ +│ +├── tasks_service/ # Сервис задач +│ ├── cmd/main.go +│ ├── handlers/ +│ └── proto/ +│ +├── system_service/ # Системный сервис +│ ├── cmd/main.go +│ ├── migrations/ # SQL-миграции +│ │ ├── 000001_init.up.sql +│ │ └── ... +│ └── scheduler/ # Фоновые задачи +│ +├── telegram_service/ # Telegram Bot +│ ├── cmd/main.go +│ ├── common/ +│ │ └── update/ # Обработчик обновлений +│ ├── handlers/ +│ │ ├── approval/ # Система согласований +│ │ │ ├── handler.go +│ │ │ ├── decision.go +│ │ │ ├── helpers.go +│ │ │ ├── revision.go +│ │ │ ├── comment.go +│ │ │ ├── executor.go +│ │ │ ├── delegation.go +│ │ │ ├── observer_selection.go +│ │ │ ├── first_approver_selection.go +│ │ │ └── topics/ # Деревья тем согласований +│ │ │ ├── timeoff/ # Отгулы +│ │ │ ├── vacation/ # Отпуска +│ │ │ ├── sick_leave/ # Больничные +│ │ │ ├── free/ # Свободные темы +│ │ │ ├── returns/ # Возвраты +│ │ │ ├── client_changes/ # Изменения клиентов +│ │ │ ├── goods_order/ # Заказ товаров +│ │ │ ├── shipments_soh/ # Отгрузки на СОХ +│ │ │ ├── transaction_passport/ # Паспорт сделки +│ │ │ ├── rates_logistics/ # Ставки логистики +│ │ │ ├── receipts/ # Поступления +│ │ │ └── non_budget*/ # Внебюджетные расходы +│ │ ├── suggestion/ # Предложения и пожелания +│ │ ├── acting/ # ВРИО +│ │ └── start/ # Стартовый обработчик +│ ├── approvalflow/ # Движок флоу согласований +│ │ └── flow.go # FlowNode, FindNode +│ ├── keyboard/ # Построители клавиатур +│ ├── scheduler/ # Планировщики +│ │ ├── delegation_checker.go # Проверка делегирований +│ │ └── absence_reporter.go # Отчёты об отсутствующих +│ ├── state/ # Управление состояниями (Redis) +│ └── types/ # Внутренние типы сервиса +│ +├── user_service/ # Сервис профиля +│ ├── cmd/main.go +│ ├── handlers/ +│ └── proto/ +│ +├── goods_order_service/ # Сервис заказов товаров +│ ├── cmd/main.go +│ └── handlers/ +│ +└── docker-compose.yml # Docker Compose для локального запуска +``` + +--- + +## 🚀 Быстрый старт + +### Требования + +- Go 1.21+ +- PostgreSQL 15+ +- Redis 7+ +- Docker & Docker Compose (опционально) + +### 1. Клонирование + +```bash +git clone https://github.com/your-org/ruspetportal.git +cd ruspetportal +``` + +### 2. Переменные окружения + +Скопируйте примеры конфигов: + +```bash +cp .env.example .env +``` + +Заполните переменные (см. раздел [Конфигурация](#конфигурация)). + +### 3. Запуск через Docker Compose + +```bash +# Запуск всей инфраструктуры (PostgreSQL, Redis) +docker-compose up -d postgres redis + +# Запуск миграций +cd system_service && go run cmd/main.go migrate + +# Запуск сервисов +go run auth_service/cmd/main.go & +go run rest_user_service/cmd/main.go & +go run rest_admin_service/cmd/main.go & +go run telegram_service/cmd/main.go & +``` + +### 4. Запуск отдельного сервиса + +```bash +cd telegram_service +go run cmd/main.go +``` + +--- + +## ⚙️ Конфигурация + +### Общие переменные + +```env +# PostgreSQL +DATABASE_HOST=localhost +DATABASE_PORT=5432 +DATABASE_NAME=ruspetportal +DATABASE_USER=postgres +DATABASE_PASSWORD=your_password +DATABASE_SSL_MODE=disable + +# Redis +REDIS_HOST=localhost +REDIS_PORT=6379 +REDIS_PASSWORD= +REDIS_DB=0 +``` + +### Telegram Service + +```env +# Telegram Bot +TELEGRAM_BOT_TOKEN=your_bot_token + +# Прокси (обязательно для РФ) +TELEGRAM_PROXY_URL=socks5://user:pass@proxy.host:1080 +# или HTTP прокси: +# TELEGRAM_PROXY_URL=http://proxy.host:8080 +``` + +### Auth Service + +```env +JWT_SECRET=your_jwt_secret_key +JWT_EXPIRY=24h +JWT_REFRESH_EXPIRY=720h +``` + +### Порты сервисов + +```env +AUTH_SERVICE_PORT=50051 # gRPC +USER_SERVICE_PORT=50052 # gRPC +TASKS_SERVICE_PORT=50053 # gRPC +REST_USER_SERVICE_PORT=8080 # HTTP +REST_ADMIN_SERVICE_PORT=8081 # HTTP +``` + +--- + +## 🗄️ База данных + +### Основные таблицы + +| Таблица | Назначение | +|---------|------------| +| `users` | Сотрудники | +| `roles` | Роли (approver, observer, executor, director...) | +| `user_roles` | Связь пользователей и ролей | +| `departments` | Отделы | +| `permissions` | Права доступа по ролям и темам | +| `approval_topic_categories` | Категории тем согласований | +| `approval_topics` | Темы согласований | +| `approvals` | Заявки на согласование | +| `approval_steps` | Шаги согласования | +| `approval_files` | Файлы к заявкам | +| `approval_comments` | Комментарии к заявкам | +| `approval_additional_approvers` | Дополнительные согласующие | +| `approval_additional_observers` | Дополнительные наблюдатели | +| `approval_tasks` | Задачи исполнителям после согласования | +| `approval_delegations` | Делегирование прав согласования | +| `acting_assignments` | Назначения ВРИО | +| `suggestions` | Предложения и пожелания | +| `suggestion_messages` | Переписка по предложениям | +| `user_hierarchies` | Иерархии согласования | +| `group_notification_settings` | Настройки уведомлений в группы | + +### Миграции + +Миграции хранятся в `system_service/jobs/` и применяются автоматически при старте `system_service`. + +```bash +# Применить миграции вручную +cd system_service +go run cmd/main.go +``` + +### Важные настройки в БД + +Для работы системы согласований необходимо заполнить: + +```sql +-- Добавить роли +INSERT INTO roles (name, code, is_approver, is_director, is_observer, is_executor) +VALUES + ('Согласующий', 'approver', true, false, false, false), + ('Директор', 'director', false, true, false, false), + ('Наблюдатель', 'observer', false, false, true, false), + ('Исполнитель', 'executor', false, false, false, true); + +-- Включить флаги для тем с выбором первого согласующего +UPDATE approval_topics +SET first_approver_role_code = 'manager' +WHERE code IN ('returns_other_manager_crimea', 'returns_other_manager_krasnodar'); + +-- Включить флаги для тем с выбором наблюдателей +UPDATE approval_topics +SET allow_observer_selection = true +WHERE code IN ('goods_order_monthly', 'goods_order_additional'); +``` + +--- + +## 🌐 API + +### REST User Service (`rest_user_service`) + +``` +GET /api/v1/profile — Профиль текущего пользователя +PUT /api/v1/profile — Обновление профиля +GET /api/v1/employees — Список сотрудников +GET /api/v1/approvals — Мои заявки +GET /api/v1/tasks — Мои задачи +``` + +### REST Admin Service (`rest_admin_service`) + +``` +# Пользователи +GET /api/v1/admin/users — Список пользователей +POST /api/v1/admin/users — Создать пользователя +PUT /api/v1/admin/users/:id — Обновить пользователя +DELETE /api/v1/admin/users/:id — Удалить пользователя + +# Роли и права +GET /api/v1/admin/roles — Список ролей +POST /api/v1/admin/permissions — Выдать право доступа + +# Иерархии согласования +POST /api/v1/admin/hierarchies — Настроить иерархию +GET /api/v1/admin/hierarchies — Список иерархий + +# Темы согласований +GET /api/v1/admin/topics — Список тем +PUT /api/v1/admin/topics/:id — Обновить тему +``` + +### gRPC сервисы + +Proto-файлы расположены в `{service_name}/proto/`. + +--- + +## 🤖 Telegram Bot + +### Подключение прокси + +Бот обязательно требует прокси для работы в РФ. Поддерживаются: + +```env +# SOCKS5 (рекомендуется) +TELEGRAM_PROXY_URL=socks5://login:password@proxy.example.com:1080 + +# HTTP прокси +TELEGRAM_PROXY_URL=http://proxy.example.com:8080 + +# SOCKS5 без авторизации +TELEGRAM_PROXY_URL=socks5://proxy.example.com:1080 +``` + +### Команды бота + +| Команда | Назначение | +|---------|------------| +| `/start` | Регистрация и главное меню | +| `/approvals` | Открыть список согласований | +| `/set_report_time HH:MM` | Установить время отчёта (в группе) | + +### Роли пользователей в боте + +| Роль | Код | Возможности | +|------|-----|-------------| +| Сотрудник | `employee` | Создание заявок | +| Согласующий | `approver` | Согласование/отклонение заявок | +| Директор | `director` | Финальное согласование, просмотр всех | +| Наблюдатель | `observer` | Просмотр заявок по категориям | +| Исполнитель | `executor` | Выполнение задач после согласования | + +### Добавление новой темы согласования + +1. Добавить запись в таблицы `approval_topic_categories` и `approval_topics` +2. Создать файл `telegram_service/handlers/approval/topics/{name}/topic.go` +3. Реализовать интерфейс `approvalflow.Topic`: + ```go + type Topic interface { + Code() string + Name() string + BuildTree() *FlowNode + TopicCodeFromCollected(collected map[string]string) (string, error) + FormatApproverMessage(initiator *typescore.User, collected map[string]string) string + } + ``` +4. Зарегистрировать в `telegram_service/handlers/approval/registry.go` + +### Уведомления об отсутствующих в группу + +Добавьте бота в Telegram-группу — он автоматически зарегистрируется и начнёт присылать ежедневный отчёт в 09:00: + +``` +📋 Отсутствующие сотрудники — 29.04.2026 + +1. Иванов Иван Иванович + 📌 Отпуск + 📅 25.04.2026 — 05.05.2026 + 👤 ВРИО: Петров Пётр Петрович + +2. Сидорова Анна Михайловна + 📌 Больничный + 📅 29.04.2026 + 👤 ВРИО: не назначен +``` + +Изменить время отчёта: `/set_report_time 08:30` + +--- + +## 🔧 Разработка + +### Добавление нового сервиса + +1. Создайте директорию `new_service/` +2. Добавьте `cmd/main.go` с инициализацией +3. Подключите `core` через `go.work` или `go.mod replace` +4. Зарегистрируйте в `docker-compose.yml` + +### Добавление нового метода в core + +1. Добавьте модель в `core/typescore/models.go` +2. Добавьте константу таблицы в `core/db/table_names/` +3. Создайте файл `core/db/dbcore/{entity}.go` с реализацией интерфейса +4. Добавьте в `ModuleDB` в `core/db/dbcore/module_db.go` + +### Паттерн реализации методов БД + +Все методы работы с БД следуют единому паттерну: + +```go +func (u *EntityDB) CreateEntityDB( + ctx context.Context, + tx pgx.Tx, + obj *typescore.Entity, + returnObj ...bool, +) (*typescore.Entity, pgx.Tx, error) { + // 1. Проверка nil + // 2. ExecuteTx — INSERT с RETURNING id + // 3. Если returnObj=true — GetByID и вернуть объект +} +``` + +### Состояния в Telegram боте + +Все состояния флоу хранятся в Redis с TTL 30 минут. Паттерн: + +```go +// Установить состояние +h.States.Set(ctx, telegramID, flowState) + +// Получить состояние +flowState, err := h.States.Get(ctx, telegramID) + +// Очистить состояние +h.States.Clear(ctx, telegramID) +``` + +### Линтер и форматирование + +```bash +# Форматирование +gofmt -w ./... + +# Линтер +golangci-lint run ./... +``` + +--- + +## 📄 Лицензия + +Проект является внутренней разработкой и не предназначен для открытого распространения. + +--- + +
+Разработано для внутреннего использования · RuspetPortal +
# Test deploy diff --git a/build_core.sh b/build_core.sh new file mode 100644 index 0000000..673b199 --- /dev/null +++ b/build_core.sh @@ -0,0 +1,13 @@ +#!/bin/bash + +set -e +trap 'echo "🔴 Error build core"; exit 1' ERR + +THIS_PATH=$(dirname "$(realpath "$0")") +CORE_PATH="$THIS_PATH/core" + +echo "CORE_PATH: $CORE_PATH" + +cd "$CORE_PATH" +go vet ./... +go mod tidy \ No newline at end of file diff --git a/core/.gitignore b/core/.gitignore new file mode 100644 index 0000000..8542d90 --- /dev/null +++ b/core/.gitignore @@ -0,0 +1,6 @@ +.env +system-service_app +config.yml +vendor +app +.DS_STORE \ No newline at end of file diff --git a/core/.golangci.yml b/core/.golangci.yml new file mode 100644 index 0000000..ea1405d --- /dev/null +++ b/core/.golangci.yml @@ -0,0 +1,52 @@ +linters-settings: + errcheck: # Настройки для линтера errcheck, который проверяет, что ошибки не игнорируются + check-type-assertions: true # Не проверять утверждения типов на ошибки + check-blank: true # Проверять игнорирование ошибок через присваивание в _ + prealloc: # Настройки для линтера prealloc, который предлагает предварительное выделение памяти для срезов + simple: true # Простой режим, предлагает предварительное выделение для простых циклов + range-loops: true # Предлагает предварительное выделение для циклов range + for-loops: false # Не предлагает предварительное выделение для обычных for-циклов + gocyclo: # Настройки для линтера gocyclo, который проверяет сложность функций + min-complexity: 15 # Установите порог сложности, который считаете приемлемым + +linters: + enable: # Список линтеров, которые будут включены + - noctx # Находит отправку HTTP-запроса без контекста.Контекст. + - protogetter # Сообщает о прямом чтении из полей прото-сообщения, когда следует использовать геттеры. + - reassign # Проверяет, что переменные пакета не переназначаются. + - rowserrcheck # Проверяет, успешно ли проверен Rows.Err строк. + - sqlclosecheck # Проверяет, что sql.Rows, sql.Stmt, sqlx.NamedStmt, pgx.Query закрыты. + - ineffassign # Обнаруживает, когда назначения существующим переменным не используются. + - nilerr # Находит код, который возвращает ноль, даже если он проверяет, что ошибка не равна нулю. + - makezero # Проверяет, что нулевые значения создаются правильно + - gochecksumtype # Проверяет, что тип контрольной суммы в go.sum соответствует содержимому + - copyloopvar # Проверяет, что циклические зависимости пакетов не имеют экспортируемых идентификаторов + - exhaustive # Проверьте полноту операторов перечисления. + - errchkjson # Проверяет типы, передаваемые функциям кодирования JSON. Сообщает о неподдерживаемых типах и событиях, при которых проверку возвращаемой ошибки можно опустить. + - durationcheck # Проверяет, что длительность таймаута не равна 0 + - contextcheck # Проверяет, что контекст не игнорируется + - bodyclose # Проверяет, что тело запроса закрывается + - bidichk # Проверяет, что строки в исходном коде не содержат символов из разных языков + - govet # Проверяет код на наличие конструкций, которые могут быть ошибочными + - errcheck # Проверяет, что ошибки не игнорируются + - staticcheck # Статический анализ кода, находит ошибки, неэффективные конструкции и т.д. + - unused # Проверяет на неиспользуемые переменные, функции, константы + - gocritic # Линтер, основанный на проверке кода на соответствие определенным критериям качества и стиля + - stylecheck # Проверяет стиль кодирования + - whitespace # Проверяет проблемы с пробелами в коде + - gosec # Линтер gosec, который проверяет код на наличие потенциальных уязвимостей + - prealloc # Предлагает предварительное выделение памяти для срезов + + - dupl # Находит дублирующийся код + - gocyclo # Проверяет сложность функций + - ineffassign # Обнаруживает неэффективные присваивания + - unparam # Находит неиспользуемые параметры функций + + - gosimple # Предлагает упрощения кода + + disable: # Список линтеров, которые будут отключены + - gofumpt # Более строгая версия gofmt, применяет дополнительные правила форматирования + # - golint # Отключает golint, который проверяет стиль написания кода на Go + +run: + timeout: 15m # Устанавливает тайм-аут для выполнения всех линтеров \ No newline at end of file diff --git a/core/config/config-load-options.go b/core/config/config-load-options.go new file mode 100644 index 0000000..cf83fd1 --- /dev/null +++ b/core/config/config-load-options.go @@ -0,0 +1,19 @@ +package configcore + +// ExposedServiceOptions определяет, какие сервисы нужно загружать +type ExposedServiceOptions struct { + TelegramService bool + RESTBaseService bool + RESTAdminService bool +} + +// ConfigLoadOptions определяет, какие группы конфигурации нужно загружать +type ConfigLoadOptions struct { + Env bool + Redis bool + Database bool + Bitrix bool + Secrets SecretsOptions + Telegram bool + Server ExposedServiceOptions +} diff --git a/core/config/config-types.go b/core/config/config-types.go new file mode 100644 index 0000000..9df48cf --- /dev/null +++ b/core/config/config-types.go @@ -0,0 +1,131 @@ +package configcore + +import "net/url" + +// RedisConfig конфигурация Redis +type RedisConfig struct { + Host string `yaml:"host" env-required:"true"` + Port int `yaml:"port" env-required:"true"` + User string `yaml:"user" env-required:"true"` + Password string `yaml:"password" env-required:"true"` +} + +// DatabaseConfig конфигурация базы данных +type DatabaseConfig struct { + Host string `yaml:"host" env-required:"true"` + User string `yaml:"user" env-required:"true"` + Password string `yaml:"password" env-required:"true"` + DB string `yaml:"methods" env-required:"true"` + Port int `yaml:"port" env-required:"true"` + SSL string `yaml:"ssl" env-required:"true" default:"disable"` +} + +// TelegramConfig конфигурация Telegram +type TelegramConfig struct { + BotToken string `yaml:"bot_token"` + WebAppUrl string `yaml:"web_app_url"` + ProxyURL string `yaml:"proxy_url"` + ProxyUsername string `yaml:"proxy_username"` + ProxyPassword string `yaml:"proxy_password"` + ParsedProxy *url.URL // кэшированный распарсенный прокси +} + +// ServiceConfig конфигурация сервиса +type ServiceConfig struct { + Host string `yaml:"host" env-required:"true"` + Port int `yaml:"port" env-required:"true"` +} + +// CorsConfig конфигурация CORS +type CorsConfig struct { + AllowedOrigins []string `yaml:"allowed_origins"` +} + +// SwaggerConfig конфигурация Swagger +type SwaggerConfig struct { + User string `yaml:"user" env-required:"true"` + Pass string `yaml:"pass" env-required:"true"` +} + +// AuthJWTOptions определяет, какие JWT секреты нужно загружать +type AuthJWTOptions struct { + Admin bool + User bool +} + +type SecretsOptions struct { + AuthJWT AuthJWTOptions + OAuthConfig bool + WebAuth bool + AdminAccessCode bool + UserAccessCode bool + TonProofConfig bool +} + +// RestServiceConfig конфигурация REST сервиса +type RestServiceConfig struct { + PortRest int `yaml:"port_rest" env-required:"true"` + BindRest string `yaml:"bind_rest" env-required:"true"` + PortSocket int `yaml:"port_socket" env-required:"true"` + Cors CorsConfig `yaml:"cors"` + Swagger SwaggerConfig `yaml:"swagger"` + Internal string `yaml:"internally"` + MaxHttpBufferSize int64 `yaml:"max_http_buffer_size"` + MessageTimeout int64 `yaml:"message_timeout"` +} + +// GrpcServiceConfig конфигурация gRPC сервиса +type GrpcServiceConfig struct { + GrpcPort int `yaml:"grpc_port" env-required:"true"` + CertFileName string +} + +type Server struct { + RESTBaseService RestServiceConfig `yaml:"rest_balancer_service"` + RESTAdminService RestServiceConfig `yaml:"rest_admin_service"` + Telegram GrpcServiceConfig `yaml:"telegram_service"` +} + +type Bitrix struct { + PortalID string `yaml:"portal_id"` + IsEnterprise bool `yaml:"is_enterprise"` +} + +type Service struct { + Bind string `yaml:"bind"` + Port int `yaml:"port"` + Internal string `yaml:"internally"` + MaxHttpBufferSize int64 `yaml:"max_http_buffer_size"` + MessageTimeout int64 `yaml:"message_timeout"` +} + +// AuthJWTConfig конфигурация JWT аутентификации +type AuthJWTConfig struct { + AdminSecret string `yaml:"admin_secret"` + UserSecret string `yaml:"user_secret"` + TempSecret string `yaml:"temp_secret"` + TemporaryPasswordLifeMinute int `yaml:"temporary_password_life_minute"` + JwtAdminSessionLengthHours int `yaml:"jwt_admin_session_length_hours"` + JwtUserSessionLengthHours int `yaml:"jwt_user_session_length_hours"` +} + +// SecretsConfig конфигурация секретов +type SecretsConfig struct { + AuthJWT AuthJWTConfig `yaml:"auth_jwt"` + ApiPublicUser string `yaml:"access_code_user"` + ApiPrivateUser string + ApiPublicAdmin string `yaml:"access_code_admin"` + ApiPrivateAdmin string + ApiPublicBase string `yaml:"api_public_base"` + ApiPrivateBase string `yaml:"api_private_base"` +} + +type Config struct { + Environment string `yaml:"env"` + Redis RedisConfig `yaml:"redis"` + Database DatabaseConfig `yaml:"database"` + Telegram TelegramConfig `yaml:"telegram"` + Server Server `yaml:"server"` + Secrets SecretsConfig `yaml:"secrets"` + Bitrix Bitrix `yaml:"bitrix"` +} diff --git a/core/config/config.example.yml b/core/config/config.example.yml new file mode 100644 index 0000000..01c81ab --- /dev/null +++ b/core/config/config.example.yml @@ -0,0 +1,29 @@ +env: "dev" # dev \ prod +redis: + addr: "" + username: "" + password: "" # Password for the Redis server (if required) + port: 0 # Redis server port, default is 6379 + db: 0 +secrets: + api_public_base: "test" + api_private_base: "testtest" +bitrix: + portal_id: "" + is_enterprise: false +database: + host: "localhost" + port: 5432 + methods: "ruspetportal" + user: "postgres" + password: "root" +telegram: # Telegram settings + bot_token: "19191919191:******-******************" # Telegram bot token + web_app_url: "https://google.com/"# Telegram web app URL +server: + rest_base_service: # Base service address + bind_rest: "0.0.0.0" + port_rest: 15000 + internal: "rest_base_service_balancer_c" + telegram_service: + grpc_port: 4553 \ No newline at end of file diff --git a/core/config/configcore.go b/core/config/configcore.go new file mode 100644 index 0000000..058298f --- /dev/null +++ b/core/config/configcore.go @@ -0,0 +1,87 @@ +package configcore + +import ( + cfgldrlib "bitrix_balancer_api/core/lib/internally/config-loader" + _ "embed" + "errors" + "fmt" + "github.com/sirupsen/logrus" +) + +//go:embed config.yml +var configYML string + +// LoadConfig загружает конфигурацию из встраиваемого YAML файла +func LoadConfig(options *ConfigLoadOptions) (*Config, error) { + params := &cfgldrlib.ConfigLoaders{ + ConfigYml: &configYML, + } + + var fullConfig Config + config, err := cfgldrlib.LoadConfig[Config](params) + if err != nil { + return nil, errors.New(fmt.Sprintf("failed to load config using cfg-ldr: %v", err)) + } + fullConfig = *config + result := &Config{} + copyConfigFields(options, &fullConfig, result) + + return result, nil +} + +// copyConfigFields копирует поля из source в target на основе опций options +func copyConfigFields(options *ConfigLoadOptions, source, target *Config) { + if options == nil { + logrus.Error("config options is nil") + return + } + + if options.Env { + target.Environment = source.Environment + } + // Копируем Redis + if options.Redis { + target.Redis = source.Redis + } + + // Копируем Database + if options.Database { + target.Database = source.Database + } + + // Копируем Telegram + if options.Telegram { + target.Telegram = source.Telegram + } + + // Копируем Bitrix + if options.Bitrix { + target.Bitrix = source.Bitrix + } + + // Копируем ExposedServiceConfig + 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 + } + + if options.Secrets.AuthJWT.Admin { + target.Secrets.AuthJWT.AdminSecret = source.Secrets.AuthJWT.AdminSecret + target.Secrets.AuthJWT.JwtAdminSessionLengthHours = source.Secrets.AuthJWT.JwtAdminSessionLengthHours + } + if options.Secrets.AuthJWT.User { + target.Secrets.AuthJWT.UserSecret = source.Secrets.AuthJWT.UserSecret + target.Secrets.AuthJWT.JwtUserSessionLengthHours = source.Secrets.AuthJWT.JwtUserSessionLengthHours + } + if options.Secrets.AdminAccessCode { + target.Secrets.ApiPublicAdmin = source.Secrets.ApiPublicAdmin + } + if options.Secrets.UserAccessCode { + target.Secrets.ApiPublicUser = source.Secrets.ApiPublicUser + } +} diff --git a/core/db/db.go b/core/db/db.go new file mode 100644 index 0000000..34f19f8 --- /dev/null +++ b/core/db/db.go @@ -0,0 +1,93 @@ +package database + +import ( + dbmigration "bitrix_balancer_api/core/db/db_migration" + dbcore "bitrix_balancer_api/core/db/methods" + gormmodule "bitrix_balancer_api/core/lib/external/gorm" + pgxpoolmodule "bitrix_balancer_api/core/lib/external/pgxpool" + redismodule "bitrix_balancer_api/core/lib/internally/redis" + "github.com/jackc/pgx/v5/pgxpool" + "gorm.io/gorm" +) + +type ModuleDB struct { + Pool *pgxpool.Pool + gormDB *gorm.DB + + User *dbcore.UserDB + Approval *dbcore.ApprovalDB + ApprovalFile *dbcore.ApprovalFileDB + ApprovalStep *dbcore.ApprovalStepDB + ApprovalTopic *dbcore.ApprovalTopicDB + ApprovalTopicCategory *dbcore.ApprovalTopicCategoryDB + Department *dbcore.DepartmentDB + Permission *dbcore.PermissionDB + Role *dbcore.RoleDB + UserRole *dbcore.UserRoleDB + UserHierarchy *dbcore.UserHierarchyDB + ApprovalDelegation *dbcore.ApprovalDelegationDB + ApprovalAdditionalApprover *dbcore.ApprovalAdditionalApproverDB + ApprovalTasks *dbcore.ApprovalTaskDB + ApprovalComment *dbcore.ApprovalCommentDB + Suggestion *dbcore.SuggestionDB + SuggestionMessage *dbcore.SuggestionMessageDB + ApprovalAdditionalObserver *dbcore.ApprovalAdditionalObserverDB + ApprovalTopicExecutor *dbcore.ApprovalTopicExecutorDB + Admin *dbcore.AdminDB +} + +func NewModuleDB( + config *pgxpoolmodule.ConfigConnectPgxPool, + redisClient *redismodule.ModuleRedis, +) (*ModuleDB, error) { + pool, err := pgxpoolmodule.ConnectDB(config) + if err != nil { + return nil, err + } + + gormDataBase, _, err := gormmodule.GormDatabaseConnect(&gormmodule.ConfigConnectGorm{ + Host: config.Host, + Port: config.Port, + User: config.User, + Password: config.Password, + Name: config.Name, + SslMode: config.SSLMode, + }) + if err != nil { + return nil, err + } + + moduleDB := &ModuleDB{Pool: pool, gormDB: gormDataBase} + moduleDB = initDBModules(moduleDB, redisClient) + + return moduleDB, nil +} + +func initDBModules(modules *ModuleDB, redisClient *redismodule.ModuleRedis) *ModuleDB { + modules.User = dbcore.NewUserDB(modules.Pool) + modules.Approval = dbcore.NewApprovalDB(modules.Pool) + modules.ApprovalStep = dbcore.NewApprovalStepDB(modules.Pool) + modules.ApprovalTopic = dbcore.NewApprovalTopicDB(modules.Pool) + modules.ApprovalTopicCategory = dbcore.NewApprovalTopicCategoryDB(modules.Pool) + modules.Department = dbcore.NewDepartmentDB(modules.Pool) + modules.Permission = dbcore.NewPermissionDB(modules.Pool) + modules.Role = dbcore.NewRoleDB(modules.Pool) + modules.UserHierarchy = dbcore.NewUserHierarchyDB(modules.Pool) + modules.UserRole = dbcore.NewUserRoleDB(modules.Pool) + modules.ApprovalFile = dbcore.NewApprovalFileDB(modules.Pool) + modules.ApprovalDelegation = dbcore.NewApprovalDelegationDB(modules.Pool) + modules.ApprovalAdditionalApprover = dbcore.NewApprovalAdditionalApproverDB(modules.Pool) + modules.ApprovalTasks = dbcore.NewApprovalTaskDB(modules.Pool) + modules.ApprovalComment = dbcore.NewApprovalCommentDB(modules.Pool) + modules.SuggestionMessage = dbcore.NewSuggestionMessageDB(modules.Pool) + 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 +} + +func (m *ModuleDB) Migrate() *dbmigration.MigrationFunctions { + return dbmigration.NewMigrationFunctions(m.Pool, m.gormDB) +} diff --git a/core/db/db_migration/0_init.go b/core/db/db_migration/0_init.go new file mode 100644 index 0000000..b2a15b3 --- /dev/null +++ b/core/db/db_migration/0_init.go @@ -0,0 +1,37 @@ +package dbmigration + +import ( + gormmodule "bitrix_balancer_api/core/lib/external/gorm" + "github.com/jackc/pgx/v5/pgxpool" + "github.com/sirupsen/logrus" + "gorm.io/gorm" +) + +type MigrationFunctions struct { + pool *pgxpool.Pool + gormDB *gorm.DB +} + +func NewMigrationFunctions(pool *pgxpool.Pool, gorm *gorm.DB) *MigrationFunctions { + return &MigrationFunctions{ + pool: pool, + gormDB: gorm, + } +} + +func (m *MigrationFunctions) MigrateDB() error { + m.DropAllTriggers() + + err := m.migrateTables() + if err != nil { + return err + } + + m.TriggerMigrations() + m.DefaultDataSet() + // Закрытие соединения с базой данных + gormmodule.GormDatabaseDisconnect() + + logrus.Info("🟢🟢🟢 Database migration completed successfully") + return nil +} diff --git a/core/db/db_migration/common.go b/core/db/db_migration/common.go new file mode 100644 index 0000000..16b0ba0 --- /dev/null +++ b/core/db/db_migration/common.go @@ -0,0 +1,21 @@ +package dbmigration + +import ( + "fmt" + "gorm.io/gorm" + "strings" +) + +func CreateEnumType(db *gorm.DB, typeName string, values []string, comment string) error { + valuesStr := "'" + strings.Join(values, "', '") + "'" + createQuery := fmt.Sprintf(` + DO $$ + BEGIN + IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = '%s') THEN + CREATE TYPE %s AS ENUM (%s); + COMMENT ON TYPE %s IS '%s'; + END IF; + END $$; + `, typeName, typeName, valuesStr, typeName, comment) + return db.Exec(createQuery).Error +} diff --git a/core/db/db_migration/default_data.go b/core/db/db_migration/default_data.go new file mode 100644 index 0000000..04f2ce8 --- /dev/null +++ b/core/db/db_migration/default_data.go @@ -0,0 +1,315 @@ +package dbmigration + +import ( + "bitrix_balancer_api/core/typescore" + _ "embed" + "encoding/csv" + "encoding/json" + "errors" + "fmt" + "io" + "reflect" + "regexp" + "strconv" + "strings" + "time" + + "github.com/mitchellh/mapstructure" + "github.com/shopspring/decimal" + "github.com/sirupsen/logrus" + "gorm.io/gorm" +) + +//go:embed default_data/approval_topic_categories.csv +var approvalCategoriesCSV string + +//go:embed default_data/approval_topics.csv +var approvalTopicsCSV string + +// identifierRe is compiled once and reused across all sanitizeIdentifier calls. +var identifierRe = regexp.MustCompile(`[^a-z0-9_]`) + +// timeFormats lists candidate layouts tried in order when parsing a CSV time cell. +var timeFormats = []string{ + "2006-01-02 15:04:05.999999", + "2006-01-02 15:04:05", + "2006-01-02T15:04:05Z", + "2006-01-02T15:04:05.999Z", + "2006-01-02", +} + +// dataEntry associates a table name, its model type, and its embedded CSV source. +type dataEntry struct { + table string + model interface{} + csv string +} + +// defaultDataEntries defines the ordered list of tables to seed. +// Adding a new table only requires appending one entry here. +var defaultDataEntries = []dataEntry{ + {"approval_topic_categories", &typescore.ApprovalTopicCategory{}, approvalCategoriesCSV}, + {"approval_topics", &typescore.ApprovalTopic{}, approvalTopicsCSV}, +} + +// DefaultDataSet seeds every table defined in defaultDataEntries. +// It attempts all tables and returns a combined error if any fail. +func (m *MigrationFunctions) DefaultDataSet() error { + if m.gormDB == nil { + return fmt.Errorf("DefaultDataSet: gormDB is nil") + } + + logrus.Infof("🚀 Start db default data set: %s", time.Now().UTC()) + + var errs []error + for _, entry := range defaultDataEntries { + if err := m.seedTable(entry); err != nil { + logrus.Errorf("❌ seeding table %q: %v", entry.table, err) + errs = append(errs, fmt.Errorf("table %q: %w", entry.table, err)) + } + } + + return errors.Join(errs...) +} + +// seedTable handles the full pipeline for a single table: +// parse CSV → build field index → map to structs → upsert. +func (m *MigrationFunctions) seedTable(entry dataEntry) error { + headers, records, err := readCSV(entry.csv) + if err != nil { + return fmt.Errorf("reading CSV: %w", err) + } + + fieldIndex := buildFieldIndexMap(entry.model) + + objects, err := mapRecordsToStructs(headers, records, fieldIndex, entry.model) + if err != nil { + return fmt.Errorf("mapping records: %w", err) + } + + return m.upsertRecords(entry.table, objects) +} + +// buildFieldIndexMap returns a map of sanitized db-tag → struct field index. +func buildFieldIndexMap(model interface{}) map[string]int { + t := reflect.TypeOf(model).Elem() + index := make(map[string]int, t.NumField()) + for i := range t.NumField() { + if tag := sanitizeIdentifier(t.Field(i).Tag.Get("db")); tag != "" { + index[tag] = i + } + } + return index +} + +// mapRecordsToStructs converts raw CSV rows into a slice of model instances. +func mapRecordsToStructs( + headers []string, + records [][]string, + fieldIndex map[string]int, + model interface{}, +) ([]interface{}, error) { + modelType := reflect.TypeOf(model).Elem() + results := make([]interface{}, 0, len(records)) + + for _, record := range records { + data := make(map[string]interface{}, len(headers)) + + for i, raw := range headers { + key := sanitizeIdentifier(raw) + if record[i] == "" { + continue + } + idx, ok := fieldIndex[key] + if !ok { + logrus.Errorf("❌ CSV column %q has no matching db tag in %s", key, modelType.Name()) + continue + } + data[key] = convertType(key, record[i], modelType.Field(idx).Type) + } + + // reflect.New returns a *T; pass it directly so mapstructure decodes into *T, + // not into a double pointer (**T). + obj := reflect.New(modelType).Interface() + dec, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{ + TagName: "db", + Result: obj, + }) + if err != nil { + return nil, fmt.Errorf("creating decoder: %w", err) + } + if err := dec.Decode(data); err != nil { + logrus.Errorf("❌ decoding CSV record into %s: %v", modelType.Name(), err) + continue + } + results = append(results, obj) + } + + return results, nil +} + +// upsertRecords inserts each object if it doesn't already exist in the given table. +// Duplicate-key conflicts are silently skipped; all other errors are logged and collected. +func (m *MigrationFunctions) upsertRecords(table string, objects []interface{}) error { + var errs []error + for _, obj := range objects { + err := m.gormDB.Table(table).FirstOrCreate(obj).Error + switch { + case err == nil: + // inserted or already existed — nothing to do + case errors.Is(err, gorm.ErrDuplicatedKey): + logrus.Warnf("⚠️ duplicate key in %q — skipping", table) + default: + logrus.Errorf("❌ inserting record into %q: %v", table, err) + errs = append(errs, err) + } + } + return errors.Join(errs...) +} + +// sanitizeIdentifier lowercases s, trims whitespace, and removes any character +// that is not a lowercase letter, digit, or underscore. +func sanitizeIdentifier(s string) string { + return identifierRe.ReplaceAllString(strings.ToLower(strings.TrimSpace(s)), "") +} + +// readCSV parses a CSV string and returns the header row and all data rows. +func readCSV(data string) (headers []string, records [][]string, err error) { + r := csv.NewReader(strings.NewReader(data)) + + headers, err = r.Read() + if err != nil { + return nil, nil, fmt.Errorf("reading headers: %w", err) + } + + for line := 2; ; line++ { + row, err := r.Read() + if errors.Is(err, io.EOF) { + break + } + if err != nil { + return nil, nil, fmt.Errorf("line %d: %w", line, err) + } + records = append(records, row) + } + + if len(records) == 0 { + return nil, nil, errors.New("CSV contains no data rows") + } + return headers, records, nil +} + +// convertType converts a CSV cell string to the Go type required by the struct field. +// Pointer fields are handled by wrapping the converted base value. +func convertType(field, value string, target reflect.Type) interface{} { + base := target + if base.Kind() == reflect.Ptr { + base = base.Elem() + } + + result := convertValue(field, value, base) + + if target.Kind() != reflect.Ptr || result == nil { + return result + } + + // Wrap result in a pointer to base. + ptr := reflect.New(base) + v := reflect.ValueOf(result) + switch { + case v.Type().AssignableTo(base): + ptr.Elem().Set(v) + case v.Type().ConvertibleTo(base): + ptr.Elem().Set(v.Convert(base)) + default: + logrus.Errorf("❌ cannot assign %v to *%v for field %q", v.Type(), base, field) + return nil + } + return ptr.Interface() +} + +// convertValue converts value to the concrete (non-pointer) type t. +func convertValue(field, value string, t reflect.Type) interface{} { + switch { + case t == reflect.TypeOf(decimal.Decimal{}): + d, err := decimal.NewFromString(value) + if err != nil { + logrus.Errorf("❌ %s → decimal: %v", field, err) + return decimal.Zero + } + return d + + case t == reflect.TypeOf(json.RawMessage{}): + return json.RawMessage(value) + + case t == reflect.TypeOf(time.Time{}): + return parseTime(field, value) + + case t.Kind() == reflect.Slice, t.Kind() == reflect.Struct, t.Kind() == reflect.Map: + return unmarshalJSON(field, value, t) + + default: + return convertPrimitive(field, value, t) + } +} + +func parseTime(field, value string) time.Time { + for _, layout := range timeFormats { + if t, err := time.Parse(layout, value); err == nil { + return t + } + } + logrus.Errorf("❌ %s: cannot parse %q as time.Time", field, value) + return time.Time{} +} + +func unmarshalJSON(field, value string, t reflect.Type) interface{} { + target := reflect.New(t).Interface() + if err := json.Unmarshal([]byte(value), target); err != nil { + logrus.Errorf("❌ %s: JSON unmarshal into %s: %v", field, t, err) + return reflect.Zero(t).Interface() + } + return reflect.ValueOf(target).Elem().Interface() +} + +func convertPrimitive(field, value string, t reflect.Type) interface{} { + switch t.Kind() { + case reflect.String: + return value + + case reflect.Bool: + b, err := strconv.ParseBool(strings.ToLower(value)) + if err != nil { + logrus.Errorf("❌ %s → bool: %v", field, err) + return false + } + return b + + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + n, err := strconv.ParseInt(value, 10, 64) + if err != nil { + logrus.Errorf("❌ %s → int: %v", field, err) + return reflect.Zero(t).Interface() + } + return reflect.ValueOf(n).Convert(t).Interface() + + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + n, err := strconv.ParseUint(value, 10, 64) + if err != nil { + logrus.Errorf("❌ %s → uint: %v", field, err) + return reflect.Zero(t).Interface() + } + return reflect.ValueOf(n).Convert(t).Interface() + + case reflect.Float32, reflect.Float64: + n, err := strconv.ParseFloat(value, 64) + if err != nil { + logrus.Errorf("❌ %s → float: %v", field, err) + return reflect.Zero(t).Interface() + } + return reflect.ValueOf(n).Convert(t).Interface() + + default: + return unmarshalJSON(field, value, t) + } +} diff --git a/core/db/db_migration/default_data/approval_topic_categories.csv b/core/db/db_migration/default_data/approval_topic_categories.csv new file mode 100644 index 0000000..3b0f19f --- /dev/null +++ b/core/db/db_migration/default_data/approval_topic_categories.csv @@ -0,0 +1,29 @@ +id,name,code,description,is_active,created_at,updated_at +1,Отгул,timeoff,Отгул,true,2026-04-23 10:00:00,2026-04-23 10:00:00 +2,Отпуск,vacation,Отпуск,true,2026-04-23 10:00:00,2026-04-23 10:00:00 +3,Больничный,sickleave,Больничный,true,2026-04-23 10:00:00,2026-04-23 10:00:00 +4,Внебюджетные расходы,non_budget_expenses,Внебюджетные расходы с выбором филиала и типа,true,2026-04-23 10:00:00,2026-04-23 10:00:00 +5,Внебюджетные расходы ПЭТ Лайн,non_budget_expenses_pet_line,Внебюджетные расходы ПЭТ Лайн с выбором филиала и типа,true,2026-04-23 10:00:00,2026-04-23 10:00:00 +6,Возвраты,returns,Возвраты товаров с выбором типа и региона,true,2026-04-23 10:00:00,2026-04-23 10:00:00 +7,Изменение клиента в ОКБ и 1С,client_changes,Изменение данных клиента в системах,true,2026-04-23 10:00:00,2026-04-23 10:00:00 +8,Заказ товаров,goods_order,Заказ товаров на месяц или дополнительно,true,2026-04-23 10:00:00,2026-04-23 10:00:00 +9,Отгрузки на СОХ,shipments_soh,Отгрузки на СОХ реальные или для лимита,true,2026-04-23 10:00:00,2026-04-23 10:00:00 +10,Паспорт сделки,transaction_passport,Паспорт сделки по регионам,true,2026-04-23 10:00:00,2026-04-23 10:00:00 +11,Ставки логистика,rates_logistics,Ставки логистики разово или надолго,true,2026-04-23 10:00:00,2026-04-23 10:00:00 +12,Поступления по приходным документам,receipts,Поступления по филиалам,true,2026-04-23 10:00:00,2026-04-23 10:00:00 +13,Доставка клиентам/на склад,delivery_clients,Доставка с выбором согласующего,true,2026-04-23 10:00:00,2026-04-23 10:00:00 +14,В. Отгрузки,v_shipments,Внутренние отгрузки,true,2026-04-23 10:00:00,2026-04-23 10:00:00 +15,Менеджерские расходы,manager_expenses,Расходы менеджеров,true,2026-04-23 10:00:00,2026-04-23 10:00:00 +16,Отгрузки,shipments,Обычные отгрузки,true,2026-04-23 10:00:00,2026-04-23 10:00:00 +17,Нестандартные условия договора поставки,nonstandard_contract,Нестандартные условия договоров,true,2026-04-23 10:00:00,2026-04-23 10:00:00 +18,Вакансии,vacancies,Согласование вакансий,true,2026-04-23 10:00:00,2026-04-23 10:00:00 +19,Ставки доставки АП,delivery_rates_ap,Ставки доставки Альфапэт,true,2026-04-23 10:00:00,2026-04-23 10:00:00 +20,Утверждение фрилансеров,freelancers_approval,Согласование фрилансеров,true,2026-04-23 10:00:00,2026-04-23 10:00:00 +21,Выход в нерабочий день,non_working_day,Выход в выходной или праздничный день,true,2026-04-23 10:00:00,2026-04-23 10:00:00 +22,Предложения и пожелания,suggestions,Предложения по улучшению работы,true,2026-04-23 10:00:00,2026-04-23 10:00:00 +23,Долгосрочные условия ОТК,otk_conditions,Долгосрочные условия отсрочки,true,2026-04-23 10:00:00,2026-04-23 10:00:00 +24,Остаток в кассах,cash_balance,Остатки в кассах с выбором согласующего,true,2026-04-23 10:00:00,2026-04-23 10:00:00 +25,Продажи по клиенту,client_sales,Информация о продажах по клиенту,true,2026-04-23 10:00:00,2026-04-23 10:00:00 +26,Проведенные расходы по менеджеру,manager_expenses_report,Отчет о расходах менеджера,true,2026-04-23 10:00:00,2026-04-23 10:00:00 +27,Заведение новых клиентов,new_clients,Добавление новых клиентов в базу,true,2026-04-23 10:00:00,2026-04-23 10:00:00 +28,Утверждение оплат безнал,payments_cashless,Согласование безналичных оплат,true,2026-04-23 10:00:00,2026-04-23 10:00:00 \ No newline at end of file diff --git a/core/db/db_migration/default_data/approval_topics.csv b/core/db/db_migration/default_data/approval_topics.csv new file mode 100644 index 0000000..b609521 --- /dev/null +++ b/core/db/db_migration/default_data/approval_topics.csv @@ -0,0 +1,148 @@ +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 new file mode 100644 index 0000000..5dcea35 --- /dev/null +++ b/core/db/db_migration/tables.go @@ -0,0 +1,50 @@ +package dbmigration + +import ( + tablesmigration "bitrix_balancer_api/core/db/db_migration/tables" + "github.com/sirupsen/logrus" + "gorm.io/gorm" +) + +func (m *MigrationFunctions) migrateTables() error { + logrus.Warningln("🔍 Initialize db migration...") + + migrations := []func(*gorm.DB) error{ + // Независимые справочники + tablesmigration.DepartmentsTableMigrate, + tablesmigration.RolesTableMigrate, + tablesmigration.ApprovalTopicCategoriesTableMigrate, + + // Зависят от справочников + tablesmigration.UsersTableMigrate, // → departments + tablesmigration.ApprovalTopicsTableMigrate, // → approval_topic_categories + tablesmigration.PermissionsTableMigrate, // → roles, approval_topic_categories, approval_topics + + // Зависят от users + tablesmigration.UserRolesTableMigrate, // → users, roles + tablesmigration.UserHierarchyTableMigrate, // → users, departments + + // Зависят от всего выше + tablesmigration.ApprovalsTableMigrate, // → users, approval_topics, departments + tablesmigration.ApprovalStepsTableMigrate, // → approvals, users + tablesmigration.ApprovalsFilesTableMigrate, // → approvals + + tablesmigration.ApprovalDelegationTableMigrate, + tablesmigration.ApprovalAdditionalApproverTableMigrate, + tablesmigration.ApprovalTasksTableMigrate, + tablesmigration.ApprovalCommentsTableMigrate, + tablesmigration.SuggestionsTableMigrate, + tablesmigration.SuggestionMessagesTableMigrate, + tablesmigration.ApprovalAdditionalObserverTableMigrate, + tablesmigration.ApprovalTopicExecutorsTableMigrate, + tablesmigration.AdminsTableMigrate, + } + + for _, migrate := range migrations { + if err := migrate(m.gormDB); err != nil { + return err + } + } + + return nil +} 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/db_migration/tables/approval.go b/core/db/db_migration/tables/approval.go new file mode 100644 index 0000000..ecaf200 --- /dev/null +++ b/core/db/db_migration/tables/approval.go @@ -0,0 +1,40 @@ +package tablesmigration + +import ( + "gorm.io/gorm" + "time" +) + +func ApprovalsTableMigrate(db *gorm.DB) error { + hasTable := db.Migrator().HasTable(&LocalApprovalProvider{}) + + if err := db.AutoMigrate(&LocalApprovalProvider{}); err != nil { + return err + } + + if !hasTable { + time.Sleep(5 * time.Second) + + db.Exec(`ALTER TABLE approvals ADD CONSTRAINT fk_approvals_initiator_id FOREIGN KEY (initiator_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`) + db.Exec(`ALTER TABLE approvals ADD CONSTRAINT fk_approvals_topic_id FOREIGN KEY (topic_id) REFERENCES approval_topics(id) ON DELETE RESTRICT ON UPDATE CASCADE`) + db.Exec(`ALTER TABLE approvals ADD CONSTRAINT fk_approvals_department_id FOREIGN KEY (department_id) REFERENCES departments(id) ON DELETE RESTRICT ON UPDATE CASCADE`) + db.Exec(`ALTER TABLE approvals ADD CONSTRAINT fk_approvals_revoked_by_id FOREIGN KEY (revoked_by_id) REFERENCES users(id) ON DELETE SET NULL ON UPDATE CASCADE`) + + execComments(db, ` + COMMENT ON TABLE "approvals" IS 'Заявки на согласование, поданные сотрудниками'; + COMMENT ON COLUMN "approvals".id IS 'Внутренний ID заявки'; + COMMENT ON COLUMN "approvals".initiator_id IS 'Сотрудник, подавший заявку'; + COMMENT ON COLUMN "approvals".topic_id IS 'Тема заявки'; + COMMENT ON COLUMN "approvals".department_id IS 'Снимок отдела инициатора на момент подачи. Не меняется при переводе сотрудника'; + COMMENT ON COLUMN "approvals".content IS 'Данные, введённые пользователем по шаблону темы'; + COMMENT ON COLUMN "approvals".status IS 'Статус заявки: draft | pending | approved | rejected | revoked'; + COMMENT ON COLUMN "approvals".file_base64 IS 'Прикреплённый файл в формате base64. Заполняется только если тема допускает файл'; + COMMENT ON COLUMN "approvals".file_name IS 'Оригинальное имя прикреплённого файла'; + COMMENT ON COLUMN "approvals".revoked_by_id IS 'Кто отозвал заявку: сам инициатор или директор'; + COMMENT ON COLUMN "approvals".revoked_at IS 'Дата и время отзыва заявки'; + COMMENT ON COLUMN "approvals".created_at IS 'Дата подачи заявки'; + COMMENT ON COLUMN "approvals".updated_at IS 'Дата последнего изменения заявки'; + `) + } + return nil +} diff --git a/core/db/db_migration/tables/approval_additional_approver.go b/core/db/db_migration/tables/approval_additional_approver.go new file mode 100644 index 0000000..9db720b --- /dev/null +++ b/core/db/db_migration/tables/approval_additional_approver.go @@ -0,0 +1,38 @@ +package tablesmigration + +import ( + "gorm.io/gorm" + "time" +) + +func ApprovalAdditionalApproverTableMigrate(db *gorm.DB) error { + hasTable := db.Migrator().HasTable(&ApprovalAdditionalApprover{}) + + if err := db.AutoMigrate(&ApprovalAdditionalApprover{}); err != nil { + return err + } + + if !hasTable { + time.Sleep(5 * time.Second) + + // Foreign key constraints + db.Exec(`ALTER TABLE approval_additional_approvers ADD CONSTRAINT fk_approval_additional_approvers_approval_id FOREIGN KEY (approval_id) REFERENCES approvals(id) ON DELETE CASCADE ON UPDATE CASCADE`) + db.Exec(`ALTER TABLE approval_additional_approvers ADD CONSTRAINT fk_approval_additional_approvers_approver_id FOREIGN KEY (approver_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`) + db.Exec(`ALTER TABLE approval_additional_approvers ADD CONSTRAINT fk_approval_additional_approvers_added_by_id FOREIGN KEY (added_by_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`) + + // Comments + execComments(db, ` + COMMENT ON TABLE "approval_additional_approvers" IS 'Дополнительные согласующие заявки: кто добавлен для согласования конкретной заявки'; + COMMENT ON COLUMN "approval_additional_approvers".id IS 'Внутренний уникальный идентификатор записи'; + COMMENT ON COLUMN "approval_additional_approvers".approval_id IS 'ID заявки, к которой добавлен согласующий (ссылка на approvals.id)'; + COMMENT ON COLUMN "approval_additional_approvers".approver_id IS 'ID сотрудника, добавленного как дополнительный согласующий (ссылка на users.id)'; + COMMENT ON COLUMN "approval_additional_approvers".added_by_id IS 'ID сотрудника, который добавил этого согласующего (ссылка на users.id)'; + COMMENT ON COLUMN "approval_additional_approvers".status IS 'Статус действия согласующего: pending, approved, rejected'; + COMMENT ON COLUMN "approval_additional_approvers".comment IS 'Комментарий согласующего к своему решению (опционально)'; + COMMENT ON COLUMN "approval_additional_approvers".acted_at IS 'Дата и время, когда согласующий принял решение (опционально)'; + COMMENT ON COLUMN "approval_additional_approvers".created_at IS 'Дата и время создания записи'; + COMMENT ON COLUMN "approval_additional_approvers".updated_at IS 'Дата и время последнего изменения записи'; + `) + } + return nil +} diff --git a/core/db/db_migration/tables/approval_additional_observer.go b/core/db/db_migration/tables/approval_additional_observer.go new file mode 100644 index 0000000..7939b91 --- /dev/null +++ b/core/db/db_migration/tables/approval_additional_observer.go @@ -0,0 +1,34 @@ +package tablesmigration + +import ( + "gorm.io/gorm" + "time" +) + +func ApprovalAdditionalObserverTableMigrate(db *gorm.DB) error { + hasTable := db.Migrator().HasTable(&ApprovalAdditionalObserver{}) + + if err := db.AutoMigrate(&ApprovalAdditionalObserver{}); err != nil { + return err + } + + if !hasTable { + time.Sleep(5 * time.Second) + + // Foreign key constraints + db.Exec(`ALTER TABLE approval_additional_observers ADD CONSTRAINT fk_approval_additional_approvers_approval_id FOREIGN KEY (approval_id) REFERENCES approvals(id) ON DELETE CASCADE ON UPDATE CASCADE`) + db.Exec(`ALTER TABLE approval_additional_observers ADD CONSTRAINT fk_approval_additional_approvers_observer_id FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`) + db.Exec(`ALTER TABLE approval_additional_observers ADD CONSTRAINT fk_approval_additional_approvers_added_by_id FOREIGN KEY (added_by_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`) + + // Comments + execComments(db, ` + COMMENT ON TABLE "approval_additional_observers" IS 'Дополнительные наблюдатели заявки: кто добавлен для согласования конкретной заявки'; + COMMENT ON COLUMN "approval_additional_observers".id IS 'Внутренний уникальный идентификатор записи'; + COMMENT ON COLUMN "approval_additional_observers".approval_id IS 'ID заявки, к которой добавлен согласующий (ссылка на approvals.id)'; + COMMENT ON COLUMN "approval_additional_observers".user_id IS 'ID сотрудника, добавленного как дополнительный наблюдатель (ссылка на users.id)'; + COMMENT ON COLUMN "approval_additional_observers".added_by_id IS 'ID сотрудника, который добавил этого согласующего (ссылка на users.id)'; + COMMENT ON COLUMN "approval_additional_observers".created_at IS 'Дата и время создания записи'; + `) + } + return nil +} diff --git a/core/db/db_migration/tables/approval_comment.go b/core/db/db_migration/tables/approval_comment.go new file mode 100644 index 0000000..83785a2 --- /dev/null +++ b/core/db/db_migration/tables/approval_comment.go @@ -0,0 +1,32 @@ +package tablesmigration + +import ( + "gorm.io/gorm" + "time" +) + +func ApprovalCommentsTableMigrate(db *gorm.DB) error { + hasTable := db.Migrator().HasTable(&ApprovalCommentsProvider{}) + + if err := db.AutoMigrate(&ApprovalCommentsProvider{}); err != nil { + return err + } + + if !hasTable { + time.Sleep(5 * time.Second) + + db.Exec(`ALTER TABLE approval_comments ADD CONSTRAINT fk_approval_id FOREIGN KEY (approval_id) REFERENCES approvals(id) ON DELETE CASCADE ON UPDATE CASCADE`) + db.Exec(`ALTER TABLE approval_comments ADD CONSTRAINT fk_approval_comm_user_id FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE RESTRICT ON UPDATE CASCADE`) + + execComments(db, ` + COMMENT ON TABLE "approval_comments" IS 'Заявки на согласование, поданные сотрудниками'; + COMMENT ON COLUMN "approval_comments".id IS 'Внутренний ID файла'; + COMMENT ON COLUMN "approval_comments".approval_id IS 'ID заявки, к которой привязаны комментарии'; + COMMENT ON COLUMN "approval_comments".user_id IS 'ID пользователя, оставившего комментарий'; + COMMENT ON COLUMN "approval_comments".comment IS 'Комментарий к согласованию'; + COMMENT ON COLUMN "approval_comments".created_at IS 'Дата создания комментария'; + COMMENT ON COLUMN "approval_comments".updated_at IS 'Дата последнего изменения комментария'; + `) + } + return nil +} diff --git a/core/db/db_migration/tables/approval_delegation.go b/core/db/db_migration/tables/approval_delegation.go new file mode 100644 index 0000000..80a1cdd --- /dev/null +++ b/core/db/db_migration/tables/approval_delegation.go @@ -0,0 +1,39 @@ +package tablesmigration + +import ( + "gorm.io/gorm" + "time" +) + +func ApprovalDelegationTableMigrate(db *gorm.DB) error { + hasTable := db.Migrator().HasTable(&LocalApprovalDelegationProvider{}) + + if err := db.AutoMigrate(&LocalApprovalDelegationProvider{}); err != nil { + return err + } + + if !hasTable { + time.Sleep(5 * time.Second) + + // Foreign key constraints + db.Exec(`ALTER TABLE approval_delegations ADD CONSTRAINT fk_approval_delegations_delegator_id FOREIGN KEY (delegator_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`) + db.Exec(`ALTER TABLE approval_delegations ADD CONSTRAINT fk_approval_delegations_delegate_id FOREIGN KEY (delegate_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`) + db.Exec(`ALTER TABLE approval_delegations ADD CONSTRAINT fk_approval_delegations_topic_id FOREIGN KEY (topic_id) REFERENCES approval_topics(id) ON DELETE RESTRICT ON UPDATE CASCADE`) + + // Comments + execComments(db, ` + COMMENT ON TABLE "approval_delegations" IS 'Делегирование прав согласования: кто кому может согласовывать заявки по определённым темам'; + COMMENT ON COLUMN "approval_delegations".id IS 'Внутренний уникальный идентификатор записи делегирования'; + COMMENT ON COLUMN "approval_delegations".delegator_id IS 'ID сотрудника, который делегирует право согласования (ссылка на users.id)'; + COMMENT ON COLUMN "approval_delegations".delegate_id IS 'ID сотрудника, получающего право согласования вместо делегатора (ссылка на users.id)'; + COMMENT ON COLUMN "approval_delegations".topic_id IS 'ID темы заявки, на которую распространяется делегирование (ссылка на approval_topics.id)'; + COMMENT ON COLUMN "approval_delegations".valid_until IS 'Дата и время, до которого действует делегирование (включительно)'; + COMMENT ON COLUMN "approval_delegations".is_active IS 'Флаг активности: true — делегирование применяется, false — временно отключено'; + COMMENT ON COLUMN "approval_delegations".notified_day IS 'Флаг: отправлено ли уведомление делегатору за 1 день до истечения срока'; + COMMENT ON COLUMN "approval_delegations".notified_2h IS 'Флаг: отправлено ли уведомление делегатору за 2 часа до истечения срока'; + COMMENT ON COLUMN "approval_delegations".created_at IS 'Дата и время создания записи делегирования'; + COMMENT ON COLUMN "approval_delegations".updated_at IS 'Дата и время последнего изменения записи'; + `) + } + return nil +} diff --git a/core/db/db_migration/tables/approval_files.go b/core/db/db_migration/tables/approval_files.go new file mode 100644 index 0000000..b39cbdc --- /dev/null +++ b/core/db/db_migration/tables/approval_files.go @@ -0,0 +1,30 @@ +package tablesmigration + +import ( + "gorm.io/gorm" + "time" +) + +func ApprovalsFilesTableMigrate(db *gorm.DB) error { + hasTable := db.Migrator().HasTable(&LocalApprovalFileProvider{}) + + if err := db.AutoMigrate(&LocalApprovalFileProvider{}); err != nil { + return err + } + + if !hasTable { + time.Sleep(5 * time.Second) + + db.Exec(`ALTER TABLE approval_files ADD CONSTRAINT fk_approval_id FOREIGN KEY (initiator_id) REFERENCES approvals(id) ON DELETE CASCADE ON UPDATE CASCADE`) + + execComments(db, ` + COMMENT ON TABLE "approval_files" IS 'Файлы, приложенные к заявкам на согласование'; + COMMENT ON COLUMN "approval_files".id IS 'Внутренний ID файла'; + COMMENT ON COLUMN "approval_files".approval_id IS 'ID заявки, к которой привязаны файлы'; + COMMENT ON COLUMN "approval_files".file_base64 IS 'Прикреплённый файл в формате base64. Заполняется только если тема допускает файл'; + COMMENT ON COLUMN "approval_files".file_name IS 'Оригинальное имя прикреплённого файла'; + COMMENT ON COLUMN "approval_files".created_at IS 'Дата создания файла'; + `) + } + return nil +} diff --git a/core/db/db_migration/tables/approval_steps.go b/core/db/db_migration/tables/approval_steps.go new file mode 100644 index 0000000..0fc96ff --- /dev/null +++ b/core/db/db_migration/tables/approval_steps.go @@ -0,0 +1,37 @@ +package tablesmigration + +import ( + "gorm.io/gorm" + "time" +) + +func ApprovalStepsTableMigrate(db *gorm.DB) error { + hasTable := db.Migrator().HasTable(&LocalApprovalStepProvider{}) + + if err := db.AutoMigrate(&LocalApprovalStepProvider{}); err != nil { + return err + } + + if !hasTable { + time.Sleep(5 * time.Second) + + db.Exec(`ALTER TABLE approval_steps ADD CONSTRAINT fk_approval_steps_approval_id FOREIGN KEY (approval_id) REFERENCES approvals(id) ON DELETE CASCADE ON UPDATE CASCADE`) + db.Exec(`ALTER TABLE approval_steps ADD CONSTRAINT fk_approval_steps_approver_id FOREIGN KEY (approver_id) REFERENCES users(id) ON DELETE RESTRICT ON UPDATE CASCADE`) + + execComments(db, ` + COMMENT ON TABLE "approval_steps" IS 'Шаги согласования по каждой заявке. Один шаг — один согласующий'; + COMMENT ON COLUMN "approval_steps".id IS 'Внутренний ID шага'; + COMMENT ON COLUMN "approval_steps".approval_id IS 'Ссылка на заявку'; + COMMENT ON COLUMN "approval_steps".approver_id IS 'Согласующий на данном шаге'; + COMMENT ON COLUMN "approval_steps".step_order IS 'Порядковый номер шага. 1 = первый согласующий'; + COMMENT ON COLUMN "approval_steps".status IS 'Статус шага: pending | approved | rejected'; + COMMENT ON COLUMN "approval_steps".comment IS 'Комментарий согласующего при отклонении. Может быть пустым'; + COMMENT ON COLUMN "approval_steps".approver_name_snapshot IS 'Снимок имени согласующего на момент действия. Для корректных исторических отчётов'; + COMMENT ON COLUMN "approval_steps".approver_department_snapshot IS 'Снимок отдела согласующего на момент действия. Для корректных исторических отчётов'; + COMMENT ON COLUMN "approval_steps".acted_at IS 'Дата и время принятия решения по шагу'; + COMMENT ON COLUMN "approval_steps".created_at IS 'Дата создания шага'; + COMMENT ON COLUMN "approval_steps".updated_at IS 'Дата последнего обновления шага'; + `) + } + return nil +} diff --git a/core/db/db_migration/tables/approval_task.go b/core/db/db_migration/tables/approval_task.go new file mode 100644 index 0000000..c3720bb --- /dev/null +++ b/core/db/db_migration/tables/approval_task.go @@ -0,0 +1,37 @@ +package tablesmigration + +import ( + "gorm.io/gorm" + "time" +) + +func ApprovalTasksTableMigrate(db *gorm.DB) error { + hasTable := db.Migrator().HasTable(&ApprovalTaskProvider{}) + + if err := db.AutoMigrate(&ApprovalTaskProvider{}); err != nil { + return err + } + + if !hasTable { + time.Sleep(5 * time.Second) + + // Внешние ключи + db.Exec(`ALTER TABLE approval_tasks ADD CONSTRAINT fk_approval_tasks_approval_id FOREIGN KEY (approval_id) REFERENCES approvals(id) ON DELETE CASCADE ON UPDATE CASCADE`) + db.Exec(`ALTER TABLE approval_tasks ADD CONSTRAINT fk_approval_tasks_executor_id FOREIGN KEY (executor_id) REFERENCES users(id) ON DELETE RESTRICT ON UPDATE CASCADE`) + + // Комментарии к таблице и колонкам + execComments(db, ` + COMMENT ON TABLE "approval_tasks" IS 'Задачи согласования, назначенные исполнителям'; + COMMENT ON COLUMN "approval_tasks".id IS 'Внутренний ID задачи'; + COMMENT ON COLUMN "approval_tasks".approval_id IS 'Связанная заявка на согласование'; + COMMENT ON COLUMN "approval_tasks".executor_id IS 'Сотрудник-исполнитель задачи'; + COMMENT ON COLUMN "approval_tasks".task_text IS 'Текст или описание задачи'; + COMMENT ON COLUMN "approval_tasks".status IS 'Статус задачи: pending | completed | rejected'; + COMMENT ON COLUMN "approval_tasks".completed_at IS 'Дата и время выполнения задачи'; + COMMENT ON COLUMN "approval_tasks".created_at IS 'Дата создания задачи'; + COMMENT ON COLUMN "approval_tasks".updated_at IS 'Дата последнего изменения задачи'; + `) + } + + return nil +} diff --git a/core/db/db_migration/tables/approval_topic.go b/core/db/db_migration/tables/approval_topic.go new file mode 100644 index 0000000..0ef0237 --- /dev/null +++ b/core/db/db_migration/tables/approval_topic.go @@ -0,0 +1,37 @@ +package tablesmigration + +import ( + "gorm.io/gorm" + "time" +) + +func ApprovalTopicsTableMigrate(db *gorm.DB) error { + hasTable := db.Migrator().HasTable(&LocalApprovalTopicProvider{}) + + if err := db.AutoMigrate(&LocalApprovalTopicProvider{}); err != nil { + return err + } + + if !hasTable { + time.Sleep(5 * time.Second) + + db.Exec(`ALTER TABLE approval_topics ADD CONSTRAINT fk_approval_topics_category_id FOREIGN KEY (category_id) REFERENCES approval_topic_categories(id) ON DELETE CASCADE ON UPDATE CASCADE`) + + execComments(db, ` + COMMENT ON TABLE "approval_topics" IS 'Конкретные темы согласований внутри категорий'; + COMMENT ON COLUMN "approval_topics".id IS 'Внутренний ID темы'; + COMMENT ON COLUMN "approval_topics".category_id IS 'Ссылка на категорию'; + COMMENT ON COLUMN "approval_topics".name IS 'Название темы'; + COMMENT ON COLUMN "approval_topics".code IS 'Уникальный код темы: otgul_single_full_own, otgul_single_partial и т.д.'; + COMMENT ON COLUMN "approval_topics".duration_type IS 'Тип длительности: single_day | date_range | multi_day'; + COMMENT ON COLUMN "approval_topics".time_type IS 'Тип времени: full_day | partial'; + COMMENT ON COLUMN "approval_topics".payment_type IS 'Тип оплаты: own_expense | vacation_account | not_applicable'; + COMMENT ON COLUMN "approval_topics".template IS 'Шаблон ввода для пользователя: 22.02.2022 или 22.02.2022 с 16:00 по 18:00'; + COMMENT ON COLUMN "approval_topics".allows_file IS 'Разрешено ли прикрепление файла к заявке по этой теме'; + COMMENT ON COLUMN "approval_topics".is_active IS 'Активна ли тема. Неактивная тема скрыта из меню бота'; + COMMENT ON COLUMN "approval_topics".created_at IS 'Дата создания записи'; + COMMENT ON COLUMN "approval_topics".updated_at IS 'Дата последнего обновления записи'; + `) + } + return nil +} diff --git a/core/db/db_migration/tables/approval_topic_category.go b/core/db/db_migration/tables/approval_topic_category.go new file mode 100644 index 0000000..6bb154f --- /dev/null +++ b/core/db/db_migration/tables/approval_topic_category.go @@ -0,0 +1,32 @@ +package tablesmigration + +import ( + "gorm.io/gorm" + "time" +) + +func ApprovalTopicCategoriesTableMigrate(db *gorm.DB) error { + hasTable := db.Migrator().HasTable(&LocalApprovalTopicCategoryProvider{}) + + if err := db.AutoMigrate(&LocalApprovalTopicCategoryProvider{}); err != nil { + return err + } + + db.Exec(`ALTER TABLE approval_topics ADD CONSTRAINT fk_approval_topics_category_id FOREIGN KEY (category_id) REFERENCES approval_topic_categories(id) ON DELETE CASCADE ON UPDATE CASCADE`) + + if !hasTable { + time.Sleep(5 * time.Second) + + execComments(db, ` + COMMENT ON TABLE "approval_topic_categories" IS 'Категории тем согласований: Отгул, Отпуск, Больничный и т.д.'; + COMMENT ON COLUMN "approval_topic_categories".id IS 'Внутренний ID категории'; + COMMENT ON COLUMN "approval_topic_categories".name IS 'Название категории: Отгул, Отпуск, Больничный'; + COMMENT ON COLUMN "approval_topic_categories".code IS 'Уникальный код категории: otgul, vacation, sick_leave'; + COMMENT ON COLUMN "approval_topic_categories".description IS 'Описание категории'; + COMMENT ON COLUMN "approval_topic_categories".is_active IS 'Активна ли категория. Неактивная категория скрыта из меню бота'; + COMMENT ON COLUMN "approval_topic_categories".created_at IS 'Дата создания записи'; + COMMENT ON COLUMN "approval_topic_categories".updated_at IS 'Дата последнего обновления записи'; + `) + } + return nil +} diff --git a/core/db/db_migration/tables/approval_topic_executor.go b/core/db/db_migration/tables/approval_topic_executor.go new file mode 100644 index 0000000..2a2d799 --- /dev/null +++ b/core/db/db_migration/tables/approval_topic_executor.go @@ -0,0 +1,35 @@ +package tablesmigration + +import ( + "gorm.io/gorm" + "time" +) + +func ApprovalTopicExecutorsTableMigrate(db *gorm.DB) error { + hasTable := db.Migrator().HasTable(&LocalApprovalTopicExecutorProvider{}) + + if err := db.AutoMigrate(&LocalApprovalTopicExecutorProvider{}); err != nil { + return err + } + + if !hasTable { + time.Sleep(5 * time.Second) + + db.Exec(`ALTER TABLE approval_topic_executor ADD CONSTRAINT fk_users FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL ON UPDATE CASCADE`) + db.Exec(`ALTER TABLE approval_topic_executor ADD CONSTRAINT fk_topic_id FOREIGN KEY (topic_id) REFERENCES approval_topics(id) ON DELETE SET NULL ON UPDATE CASCADE`) + + execComments(db, ` + COMMENT ON TABLE "approval_topic_executor" IS 'Исполнители шагов согласования по темам'; + COMMENT ON COLUMN "approval_topic_executor".id IS 'Внутренний ID записи исполнителя'; + COMMENT ON COLUMN "approval_topic_executor".topic_id IS 'ID темы согласования, к которой относится шаг'; + COMMENT ON COLUMN "approval_topic_executor".user_id IS 'ID пользователя, назначенного исполнителем на данном шаге'; + COMMENT ON COLUMN "approval_topic_executor".step_order IS 'Порядковый номер шага согласования'; + COMMENT ON COLUMN "approval_topic_executor".require_file IS 'Требуется ли от исполнителя прикрепление файла'; + COMMENT ON COLUMN "approval_topic_executor".task_text IS 'Текст задачи или комментарий для исполнителя'; + COMMENT ON COLUMN "approval_topic_executor".is_active IS 'Активен ли данный шаг/исполнитель в маршруте согласования'; + COMMENT ON COLUMN "approval_topic_executor".created_at IS 'Дата создания записи'; + COMMENT ON COLUMN "approval_topic_executor".updated_at IS 'Дата последнего обновления записи'; + `) + } + return nil +} diff --git a/core/db/db_migration/tables/department.go b/core/db/db_migration/tables/department.go new file mode 100644 index 0000000..1b22519 --- /dev/null +++ b/core/db/db_migration/tables/department.go @@ -0,0 +1,30 @@ +package tablesmigration + +import ( + "gorm.io/gorm" + "time" +) + +func DepartmentsTableMigrate(db *gorm.DB) error { + hasTable := db.Migrator().HasTable(&LocalDepartmentProvider{}) + + if err := db.AutoMigrate(&LocalDepartmentProvider{}); err != nil { + return err + } + + if !hasTable { + time.Sleep(5 * time.Second) + + execComments(db, ` + COMMENT ON TABLE "departments" IS 'Отделы компании'; + COMMENT ON COLUMN "departments".id IS 'Внутренний ID отдела'; + COMMENT ON COLUMN "departments".name IS 'Название отдела: Финансовый отдел, IT отдел и т.д.'; + COMMENT ON COLUMN "departments".code IS 'Уникальный код отдела: finance, hr, it и т.д.'; + COMMENT ON COLUMN "departments".description IS 'Описание отдела'; + COMMENT ON COLUMN "departments".is_active IS 'Активен ли отдел. Неактивный отдел скрыт из интерфейса'; + COMMENT ON COLUMN "departments".created_at IS 'Дата создания записи'; + COMMENT ON COLUMN "departments".updated_at IS 'Дата последнего обновления записи'; + `) + } + return nil +} diff --git a/core/db/db_migration/tables/helpers.go b/core/db/db_migration/tables/helpers.go new file mode 100644 index 0000000..45fa420 --- /dev/null +++ b/core/db/db_migration/tables/helpers.go @@ -0,0 +1,15 @@ +package tablesmigration + +import ( + "gorm.io/gorm" + "time" +) + +func execComments(db *gorm.DB, sql string) { + for i := range 3 { + if err := db.Exec(sql).Error; err == nil { + return + } + time.Sleep(time.Duration(i+1) * time.Second) + } +} diff --git a/core/db/db_migration/tables/permission.go b/core/db/db_migration/tables/permission.go new file mode 100644 index 0000000..d1e0119 --- /dev/null +++ b/core/db/db_migration/tables/permission.go @@ -0,0 +1,35 @@ +package tablesmigration + +import ( + "gorm.io/gorm" + "time" +) + +func PermissionsTableMigrate(db *gorm.DB) error { + hasTable := db.Migrator().HasTable(&LocalPermissionProvider{}) + + if err := db.AutoMigrate(&LocalPermissionProvider{}); err != nil { + return err + } + + if !hasTable { + time.Sleep(5 * time.Second) + + db.Exec(`ALTER TABLE permissions ADD CONSTRAINT fk_permissions_role_id FOREIGN KEY (role_id) REFERENCES roles(id) ON DELETE CASCADE ON UPDATE CASCADE`) + db.Exec(`ALTER TABLE permissions ADD CONSTRAINT fk_permissions_topic_category_id FOREIGN KEY (topic_category_id) REFERENCES approval_topic_categories(id) ON DELETE CASCADE ON UPDATE CASCADE`) + db.Exec(`ALTER TABLE permissions ADD CONSTRAINT fk_permissions_topic_id FOREIGN KEY (topic_id) REFERENCES approval_topics(id) ON DELETE CASCADE ON UPDATE CASCADE`) + db.Exec(`ALTER TABLE permissions ADD CONSTRAINT uq_permissions_role_category_action UNIQUE (role_id, topic_category_id, action)`) + + execComments(db, ` + COMMENT ON TABLE "permissions" IS 'Права ролей на действия в рамках тем или категорий согласований'; + COMMENT ON COLUMN "permissions".id IS 'Внутренний ID записи'; + COMMENT ON COLUMN "permissions".role_id IS 'Роль, которой выдано право'; + COMMENT ON COLUMN "permissions".topic_category_id IS 'Категория тем. Если заполнено и topic_id = NULL — право на все темы категории'; + COMMENT ON COLUMN "permissions".topic_id IS 'Конкретная тема. Если заполнено — право только на эту тему'; + COMMENT ON COLUMN "permissions".action IS 'Действие: create | read | update | delete | approve | revoke'; + COMMENT ON COLUMN "permissions".created_at IS 'Дата создания записи'; + COMMENT ON COLUMN "permissions".updated_at IS 'Дата последнего обновления записи'; + `) + } + return nil +} diff --git a/core/db/db_migration/tables/providers.go b/core/db/db_migration/tables/providers.go new file mode 100644 index 0000000..29b3b6f --- /dev/null +++ b/core/db/db_migration/tables/providers.go @@ -0,0 +1,84 @@ +package tablesmigration + +import ( + dbcoretablenames "bitrix_balancer_api/core/db/table_names" + "bitrix_balancer_api/core/typescore" +) + +type LocalUserProvider typescore.User +type LocalDepartmentProvider typescore.Department +type LocalRoleProvider typescore.Role +type LocalUserRoleProvider typescore.UserRole +type LocalUserHierarchyProvider typescore.UserHierarchy +type LocalPermissionProvider typescore.Permission +type LocalApprovalTopicCategoryProvider typescore.ApprovalTopicCategory +type LocalApprovalTopicProvider typescore.ApprovalTopic +type LocalApprovalProvider typescore.Approval +type LocalApprovalDelegationProvider typescore.ApprovalDelegation +type LocalApprovalFileProvider typescore.ApprovalFile +type LocalApprovalStepProvider typescore.ApprovalStep +type ApprovalAdditionalApprover typescore.ApprovalAdditionalApprover +type ApprovalAdditionalObserver typescore.ApprovalAdditionalObserver +type ApprovalTaskProvider typescore.ApprovalTask +type ApprovalCommentsProvider typescore.ApprovalComment +type LocalSuggestionProvider typescore.Suggestion +type LocalSuggestionMessagesProvider typescore.SuggestionMessage +type LocalApprovalTopicExecutorProvider typescore.ApprovalTopicExecutor + +func (LocalUserProvider) TableName() string { + return dbcoretablenames.TableNameUsers.ToString() +} +func (LocalDepartmentProvider) TableName() string { + return dbcoretablenames.TableNameDepartments.ToString() +} +func (LocalRoleProvider) TableName() string { + return dbcoretablenames.TableNameRoles.ToString() +} +func (LocalUserRoleProvider) TableName() string { + return dbcoretablenames.TableNameUserRoles.ToString() +} +func (LocalUserHierarchyProvider) TableName() string { + return dbcoretablenames.TableNameUserHierarchy.ToString() +} +func (LocalPermissionProvider) TableName() string { + return dbcoretablenames.TableNamePermissions.ToString() +} +func (LocalApprovalTopicCategoryProvider) TableName() string { + return dbcoretablenames.TableNameApprovalTopicCategories.ToString() +} +func (LocalApprovalTopicProvider) TableName() string { + return dbcoretablenames.TableNameApprovalTopics.ToString() +} +func (LocalApprovalProvider) TableName() string { + return dbcoretablenames.TableNameApprovals.ToString() +} +func (LocalApprovalStepProvider) TableName() string { + return dbcoretablenames.TableNameApprovalSteps.ToString() +} +func (LocalApprovalFileProvider) TableName() string { + return dbcoretablenames.TableNameApprovalFiles.ToString() +} +func (LocalApprovalDelegationProvider) TableName() string { + return dbcoretablenames.TableNameApprovalDelegations.ToString() +} +func (ApprovalAdditionalApprover) TableName() string { + return dbcoretablenames.TableNameApprovalAdditionalApprovers.ToString() +} +func (ApprovalTaskProvider) TableName() string { + return dbcoretablenames.TableNameApprovalTasks.ToString() +} +func (ApprovalCommentsProvider) TableName() string { + return dbcoretablenames.TableNameApprovalComments.ToString() +} +func (LocalSuggestionProvider) TableName() string { + return dbcoretablenames.TableNameSuggestions.ToString() +} +func (LocalSuggestionMessagesProvider) TableName() string { + return dbcoretablenames.TableNameSuggestionMessages.ToString() +} +func (ApprovalAdditionalObserver) TableName() string { + return dbcoretablenames.TableNameApprovalAdditionalObservers.ToString() +} +func (LocalApprovalTopicExecutorProvider) TableName() string { + return dbcoretablenames.TableNameApprovalTopicExecutor.ToString() +} diff --git a/core/db/db_migration/tables/role.go b/core/db/db_migration/tables/role.go new file mode 100644 index 0000000..eaf0897 --- /dev/null +++ b/core/db/db_migration/tables/role.go @@ -0,0 +1,32 @@ +package tablesmigration + +import ( + "gorm.io/gorm" + "time" +) + +func RolesTableMigrate(db *gorm.DB) error { + hasTable := db.Migrator().HasTable(&LocalRoleProvider{}) + + if err := db.AutoMigrate(&LocalRoleProvider{}); err != nil { + return err + } + + if !hasTable { + time.Sleep(5 * time.Second) + + execComments(db, ` + COMMENT ON TABLE "roles" IS 'Роли пользователей в системе согласований'; + COMMENT ON COLUMN "roles".id IS 'Внутренний ID роли'; + COMMENT ON COLUMN "roles".name IS 'Название роли: Сотрудник, Согласующий, Директор'; + COMMENT ON COLUMN "roles".code IS 'Уникальный код роли: employee, approver, director'; + COMMENT ON COLUMN "roles".is_default IS 'Назначается ли роль автоматически при регистрации пользователя'; + COMMENT ON COLUMN "roles".is_director IS 'Получает финальные уведомления по всем отделам. Может отозвать любое согласование'; + COMMENT ON COLUMN "roles".is_approver IS 'Может согласовывать заявки своих подчинённых'; + COMMENT ON COLUMN "roles".description IS 'Описание роли'; + COMMENT ON COLUMN "roles".created_at IS 'Дата создания записи'; + COMMENT ON COLUMN "roles".updated_at IS 'Дата последнего обновления записи'; + `) + } + return nil +} diff --git a/core/db/db_migration/tables/suggestion_messages.go b/core/db/db_migration/tables/suggestion_messages.go new file mode 100644 index 0000000..f7bac16 --- /dev/null +++ b/core/db/db_migration/tables/suggestion_messages.go @@ -0,0 +1,34 @@ +package tablesmigration + +import ( + "gorm.io/gorm" + "time" +) + +func SuggestionMessagesTableMigrate(db *gorm.DB) error { + hasTable := db.Migrator().HasTable(&LocalSuggestionMessagesProvider{}) + + if err := db.AutoMigrate(&LocalSuggestionMessagesProvider{}); err != nil { + return err + } + + if !hasTable { + time.Sleep(5 * time.Second) + + db.Exec(`ALTER TABLE suggestion_messages ADD CONSTRAINT fk_suggestion_messages_suggestion_id FOREIGN KEY (suggestion_id) REFERENCES suggestions(id) ON DELETE CASCADE ON UPDATE CASCADE`) + db.Exec(`ALTER TABLE suggestion_messages ADD CONSTRAINT fk_suggestion_messages_user_id FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL ON UPDATE CASCADE`) + + execComments(db, ` + COMMENT ON TABLE "suggestion_messages" IS 'Сообщения переписки в рамках обсуждения предложения'; + COMMENT ON COLUMN "suggestion_messages".id IS 'Внутренний уникальный идентификатор сообщения'; + COMMENT ON COLUMN "suggestion_messages".suggestion_id IS 'ID предложения, к которому относится сообщение (ссылка на suggestions.id)'; + COMMENT ON COLUMN "suggestion_messages".user_id IS 'ID автора сообщения (ссылка на users.id)'; + COMMENT ON COLUMN "suggestion_messages".message IS 'Текст сообщения'; + COMMENT ON COLUMN "suggestion_messages".file_data IS 'Прикреплённый файл в формате base64 (опционально)'; + COMMENT ON COLUMN "suggestion_messages".file_name IS 'Оригинальное имя прикреплённого файла (опционально)'; + COMMENT ON COLUMN "suggestion_messages".created_at IS 'Дата и время отправки сообщения'; + `) + } + + return nil +} diff --git a/core/db/db_migration/tables/suggestions.go b/core/db/db_migration/tables/suggestions.go new file mode 100644 index 0000000..fadb44d --- /dev/null +++ b/core/db/db_migration/tables/suggestions.go @@ -0,0 +1,34 @@ +package tablesmigration + +import ( + "gorm.io/gorm" + "time" +) + +func SuggestionsTableMigrate(db *gorm.DB) error { + hasTable := db.Migrator().HasTable(&LocalSuggestionProvider{}) + + if err := db.AutoMigrate(&LocalSuggestionProvider{}); err != nil { + return err + } + + if !hasTable { + time.Sleep(5 * time.Second) + + db.Exec(`ALTER TABLE suggestions ADD CONSTRAINT fk_suggestions_initiator_id FOREIGN KEY (initiator_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`) + db.Exec(`ALTER TABLE suggestions ADD CONSTRAINT fk_suggestions_director_id FOREIGN KEY (director_id) REFERENCES users(id) ON DELETE SET NULL ON UPDATE CASCADE`) + + execComments(db, ` + COMMENT ON TABLE "suggestions" IS 'Предложения и обращения сотрудников к руководству'; + COMMENT ON COLUMN "suggestions".id IS 'Внутренний уникальный идентификатор предложения'; + COMMENT ON COLUMN "suggestions".initiator_id IS 'ID сотрудника, создавшего предложение (ссылка на users.id)'; + COMMENT ON COLUMN "suggestions".director_id IS 'ID руководителя, к которому обращено предложение (ссылка на users.id)'; + COMMENT ON COLUMN "suggestions".subject IS 'Тема или заголовок предложения'; + COMMENT ON COLUMN "suggestions".status IS 'Статус предложения: open (открыто) | closed (закрыто)'; + COMMENT ON COLUMN "suggestions".created_at IS 'Дата и время создания предложения'; + COMMENT ON COLUMN "suggestions".updated_at IS 'Дата и время последнего изменения предложения'; + `) + } + + return nil +} diff --git a/core/db/db_migration/tables/user.go b/core/db/db_migration/tables/user.go new file mode 100644 index 0000000..5893d70 --- /dev/null +++ b/core/db/db_migration/tables/user.go @@ -0,0 +1,36 @@ +package tablesmigration + +import ( + "gorm.io/gorm" + "time" +) + +func UsersTableMigrate(db *gorm.DB) error { + hasTable := db.Migrator().HasTable(&LocalUserProvider{}) + + if err := db.AutoMigrate(&LocalUserProvider{}); err != nil { + return err + } + + if !hasTable { + time.Sleep(5 * time.Second) + + db.Exec(`ALTER TABLE users ADD CONSTRAINT fk_users_department_id FOREIGN KEY (department_id) REFERENCES departments(id) ON DELETE SET NULL ON UPDATE CASCADE`) + + execComments(db, ` + COMMENT ON TABLE "users" IS 'Сотрудники компании РусПЭТ'; + COMMENT ON COLUMN "users".id IS 'Внутренний ID пользователя'; + COMMENT ON COLUMN "users".telegram_id IS 'Уникальный Telegram ID пользователя'; + COMMENT ON COLUMN "users".username IS 'Telegram @username, может быть NULL'; + COMMENT ON COLUMN "users".full_name IS 'Полное имя сотрудника'; + COMMENT ON COLUMN "users".language_code IS 'Языковой код клиента: ru, en и т.д.'; + COMMENT ON COLUMN "users".department_id IS 'Основной отдел сотрудника. NULL — бот пуст, функционал недоступен'; + COMMENT ON COLUMN "users".is_blocked IS 'Заблокирован ли пользователь'; + COMMENT ON COLUMN "users".blocked_at IS 'Дата блокировки'; + COMMENT ON COLUMN "users".last_login IS 'Дата последнего входа'; + COMMENT ON COLUMN "users".created_at IS 'Дата регистрации'; + COMMENT ON COLUMN "users".updated_at IS 'Дата последнего обновления записи'; + `) + } + return nil +} diff --git a/core/db/db_migration/tables/user_hierarchy.go b/core/db/db_migration/tables/user_hierarchy.go new file mode 100644 index 0000000..74eb664 --- /dev/null +++ b/core/db/db_migration/tables/user_hierarchy.go @@ -0,0 +1,34 @@ +package tablesmigration + +import ( + "gorm.io/gorm" + "time" +) + +func UserHierarchyTableMigrate(db *gorm.DB) error { + hasTable := db.Migrator().HasTable(&LocalUserHierarchyProvider{}) + + if err := db.AutoMigrate(&LocalUserHierarchyProvider{}); err != nil { + return err + } + + if !hasTable { + time.Sleep(5 * time.Second) + + db.Exec(`ALTER TABLE user_hierarchy ADD CONSTRAINT fk_user_hierarchy_subordinate_id FOREIGN KEY (subordinate_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`) + db.Exec(`ALTER TABLE user_hierarchy ADD CONSTRAINT fk_user_hierarchy_approver_id FOREIGN KEY (approver_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`) + db.Exec(`ALTER TABLE user_hierarchy ADD CONSTRAINT fk_user_hierarchy_department_id FOREIGN KEY (department_id) REFERENCES departments(id) ON DELETE CASCADE ON UPDATE CASCADE`) + + execComments(db, ` + COMMENT ON TABLE "user_hierarchy" IS 'Иерархия согласования. Определяет кто кому подчиняется в рамках отдела'; + COMMENT ON COLUMN "user_hierarchy".id IS 'Внутренний ID записи'; + COMMENT ON COLUMN "user_hierarchy".subordinate_id IS 'Подчинённый — инициатор согласования'; + COMMENT ON COLUMN "user_hierarchy".approver_id IS 'Согласующий. Может быть привязан к нескольким отделам через разные записи'; + COMMENT ON COLUMN "user_hierarchy".department_id IS 'Контекст связи — в рамках какого отдела действует иерархия'; + COMMENT ON COLUMN "user_hierarchy".priority IS 'Порядок шага согласования. 1 = первый согласующий'; + COMMENT ON COLUMN "user_hierarchy".created_at IS 'Дата создания записи'; + COMMENT ON COLUMN "user_hierarchy".updated_at IS 'Дата последнего обновления записи'; + `) + } + return nil +} diff --git a/core/db/db_migration/tables/user_role.go b/core/db/db_migration/tables/user_role.go new file mode 100644 index 0000000..428019b --- /dev/null +++ b/core/db/db_migration/tables/user_role.go @@ -0,0 +1,31 @@ +package tablesmigration + +import ( + "gorm.io/gorm" + "time" +) + +func UserRolesTableMigrate(db *gorm.DB) error { + hasTable := db.Migrator().HasTable(&LocalUserRoleProvider{}) + + if err := db.AutoMigrate(&LocalUserRoleProvider{}); err != nil { + return err + } + + if !hasTable { + time.Sleep(5 * time.Second) + + db.Exec(`ALTER TABLE user_roles ADD CONSTRAINT fk_user_roles_user_id FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`) + db.Exec(`ALTER TABLE user_roles ADD CONSTRAINT fk_user_roles_role_id FOREIGN KEY (role_id) REFERENCES roles(id) ON DELETE CASCADE ON UPDATE CASCADE`) + + execComments(db, ` + COMMENT ON TABLE "user_roles" IS 'Связь пользователей и ролей. Один пользователь может иметь несколько ролей'; + COMMENT ON COLUMN "user_roles".id IS 'Внутренний ID записи'; + COMMENT ON COLUMN "user_roles".user_id IS 'Ссылка на пользователя'; + COMMENT ON COLUMN "user_roles".role_id IS 'Ссылка на роль'; + COMMENT ON COLUMN "user_roles".created_at IS 'Дата назначения роли'; + COMMENT ON COLUMN "user_roles".updated_at IS 'Дата последнего обновления записи'; + `) + } + return nil +} diff --git a/core/db/db_migration/triggers.go b/core/db/db_migration/triggers.go new file mode 100644 index 0000000..efac995 --- /dev/null +++ b/core/db/db_migration/triggers.go @@ -0,0 +1,157 @@ +package dbmigration + +import ( + "fmt" + "github.com/sirupsen/logrus" + "time" +) + +func (m *MigrationFunctions) TriggerMigrations() { + logrus.Info(fmt.Sprintf(" Start db triggers creation: %s", time.Now().UTC())) + + // Функция: назначает роль is_default=true пользователю если её ещё нет + m.gormDB.Exec(` + CREATE OR REPLACE FUNCTION assign_default_role_on_department() + RETURNS TRIGGER AS $$ + DECLARE + v_default_role_id BIGINT; + BEGIN + -- Срабатываем только когда department_id впервые становится не NULL + -- или меняется с NULL на значение + IF (OLD.department_id IS NOT DISTINCT FROM NEW.department_id) THEN + RETURN NEW; + END IF; + + IF NEW.department_id IS NULL THEN + RETURN NEW; + END IF; + + -- Ищем роль с is_default = true + SELECT id INTO v_default_role_id + FROM roles + WHERE is_default = true + LIMIT 1; + + IF v_default_role_id IS NULL THEN + RETURN NEW; + END IF; + + -- Вставляем связь только если её ещё нет + INSERT INTO user_roles (user_id, role_id, created_at, updated_at) + VALUES (NEW.id, v_default_role_id, NOW(), NOW()) + ON CONFLICT DO NOTHING; + + RETURN NEW; + END; + $$ LANGUAGE plpgsql; + `) + + m.gormDB.Exec(` + DROP TRIGGER IF EXISTS trg_assign_default_role_on_department ON users; + CREATE TRIGGER trg_assign_default_role_on_department + AFTER UPDATE OF department_id ON users + FOR EACH ROW + EXECUTE FUNCTION assign_default_role_on_department(); + `) + + // ─── Seed: базовые права для роли employee если permissions пусты ──────── + + // выдаёт права create на timeoff/vacation/sick_leave для роли employee + // Срабатывает при INSERT в roles — один раз при создании роли employee + m.gormDB.Exec(` + CREATE OR REPLACE FUNCTION seed_default_permissions_on_role() + RETURNS TRIGGER AS $$ + BEGIN + -- Только для роли с is_default = true + IF NEW.is_default IS NOT TRUE THEN + RETURN NEW; + END IF; + + -- Вставляем права на базовые категории если их ещё нет + INSERT INTO permissions (role_id, topic_category_id, action, created_at, updated_at) + SELECT + NEW.id, + tc.id, + 'create', + NOW(), + NOW() + FROM approval_topic_categories tc + WHERE tc.code IN ('timeoff', 'vacation', 'sick_leave') + AND tc.is_active = true + AND NOT EXISTS ( + SELECT 1 FROM permissions p + WHERE p.role_id = NEW.id + AND p.topic_category_id = tc.id + AND p.action = 'create' + ); + + RETURN NEW; + END; + $$ LANGUAGE plpgsql; + `) + + m.gormDB.Exec(` + DROP TRIGGER IF EXISTS trg_seed_default_permissions_on_role ON roles; + CREATE TRIGGER trg_seed_default_permissions_on_role + AFTER INSERT ON roles + FOR EACH ROW + EXECUTE FUNCTION seed_default_permissions_on_role(); + `) + + // ─── Страховка: выдать права если permissions пусты для existing ролей ─── + m.gormDB.Exec(` + INSERT INTO permissions (role_id, topic_category_id, action, created_at, updated_at) + SELECT + r.id, + tc.id, + 'create', + NOW(), + NOW() + FROM roles r + CROSS JOIN approval_topic_categories tc + WHERE r.is_default = true + AND tc.code IN ('timeoff', 'vacation', 'sick_leave') + AND tc.is_active = true + AND NOT EXISTS ( + SELECT 1 FROM permissions p + WHERE p.role_id = r.id + AND p.topic_category_id = tc.id + AND p.action = 'create' + ); + `) +} + +func (m *MigrationFunctions) DropAllTriggers() { + logrus.Info(fmt.Sprintf("🧹 Start dropping all database triggers: %s", time.Now().UTC())) + + // Получаем список всех триггеров в схеме public + m.gormDB.Exec(` + DO $$ + DECLARE + trigger_record RECORD; + BEGIN + -- Получаем все триггеры из схемы public + FOR trigger_record IN + SELECT + ns.nspname as schema_name, + tg.tgname as trigger_name, + rel.relname as table_name + FROM pg_trigger tg + JOIN pg_class rel ON tg.tgrelid = rel.oid + JOIN pg_namespace ns ON rel.relnamespace = ns.oid + WHERE ns.nspname = 'public' + AND NOT tg.tgisinternal -- исключаем системные триггеры + AND tg.tgname NOT LIKE 'pg_%' -- исключаем системные триггеры + LOOP + -- Формируем и выполняем DROP TRIGGER + EXECUTE format('DROP TRIGGER IF EXISTS %I ON %I.%I CASCADE', + trigger_record.trigger_name, + trigger_record.schema_name, + trigger_record.table_name + ); + END LOOP; + END $$; + `) + + logrus.Info(fmt.Sprintf("✅ All database triggers have been dropped: %s", time.Now().UTC())) +} 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/approval.go b/core/db/methods/approval.go new file mode 100644 index 0000000..90a45c5 --- /dev/null +++ b/core/db/methods/approval.go @@ -0,0 +1,424 @@ +package dbcore + +import ( + dbcoretablenames "bitrix_balancer_api/core/db/table_names" + "bitrix_balancer_api/core/typescore" + dbutils "bitrix_balancer_api/core/utilscore/db" + "context" + "errors" + "fmt" + "github.com/sirupsen/logrus" + "time" + + "github.com/Masterminds/squirrel" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" +) + +type ApprovalDB struct { + pool *pgxpool.Pool +} + +func NewApprovalDB(pool *pgxpool.Pool) *ApprovalDB { + return &ApprovalDB{ + pool: pool, + } +} + +type ApprovalDBI interface { + GetApprovalsListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.Approval, uint64, error) + CreateApprovalDB(ctx context.Context, tx pgx.Tx, ApprovalObj *typescore.Approval, returnObj ...bool) (*typescore.Approval, pgx.Tx, error) + UpdateApprovalDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.Approval, returnObj ...bool) (*typescore.Approval, pgx.Tx, error) + DeleteApprovalDB(ctx context.Context, params *typescore.Approval) error + GetApprovalByIDDB(ctx context.Context, id uint64) (*typescore.Approval, error) + GetActiveApprovalsByInitiatorDB(ctx context.Context, initiatorID uint64) ([]*typescore.Approval, error) + GetPendingApprovalsByApproverDB(ctx context.Context, approverID uint64) ([]*typescore.Approval, error) + GetApprovalsByInitiatorAndCategoryDB(ctx context.Context, initiatorID uint64, categoryCode string) ([]*typescore.Approval, error) + GetPendingApprovalsByApproverAndCategoryDB(ctx context.Context, approverID uint64, categoryCode string) ([]*typescore.Approval, error) + GetApprovalsByCategoryDB(ctx context.Context, categoryCode string) ([]*typescore.Approval, error) + GetClosedApprovalsByInitiatorDB(ctx context.Context, initiatorID uint64) ([]*typescore.Approval, error) +} + +func (u *ApprovalDB) GetApprovalsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.Approval, uint64, error) { + fields := dbutils.GetStructFieldsDB(&typescore.Approval{}, dbcoretablenames.TableNameApprovals.ToString()) + selectFields := append(fields, "COUNT(*) OVER() AS total_count") + + options, filter, err := dbutils.GetOptionsDB[typescore.Approval](opts...) + if err != nil { + return nil, 0, err + } + + query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovals.ToString(), selectFields) + query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit) + query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovals.ToString()) + query = query.OrderBy("created_at DESC") + + sql, args, err := query.ToSql() + if err != nil { + return nil, 0, err + } + + rows, err := u.pool.Query(ctx, sql, args...) + if err != nil { + return nil, 0, err + } + defer rows.Close() + + var Approvals []*typescore.Approval + var totalCount uint64 + for rows.Next() { + Approval := &typescore.Approval{} + if err := dbutils.ScanRowsToStructRows(rows, Approval, &totalCount); err != nil { + logrus.Warn("GetApprovalsListDB:ScanRowsToStructRows", err) + continue + } + Approvals = append(Approvals, Approval) + } + + return Approvals, totalCount, nil +} + +func (u *ApprovalDB) CreateApprovalDB(ctx context.Context, tx pgx.Tx, ApprovalObj *typescore.Approval, returnObj ...bool) (*typescore.Approval, pgx.Tx, error) { + if ApprovalObj == nil { + return nil, nil, errors.New("approval obj is nil") + } + + var insertedID uint64 + + err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { + query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Insert(dbcoretablenames.TableNameApprovals.ToString()) + + sqlV, args, err := dbutils.GenerateInsertRequest(query, ApprovalObj) + if err != nil { + return err + } + + *sqlV = *sqlV + " RETURNING id" + + return tx.QueryRow(ctx, *sqlV, args...).Scan(&insertedID) + }) + + if err != nil { + return nil, tx, err + } + + returnObjBool := len(returnObj) > 0 && returnObj[0] + if returnObjBool && insertedID > 0 { + created, err := u.GetApprovalByIDDB(ctx, insertedID) + return created, tx, err + } + + return nil, tx, nil +} + +func (u *ApprovalDB) UpdateApprovalDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.Approval, returnObj ...bool) (*typescore.Approval, pgx.Tx, error) { + if paramsUpdate.ID == nil { + return nil, nil, errors.New("approval obj is nil") + } + + err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { + query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameApprovals.ToString()) + query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate) + query = query.Where(squirrel.Eq{"id": paramsUpdate.ID}) + + sql, args, err := query.ToSql() + if err != nil { + return err + } + + _, err = tx.Exec(ctx, sql, args...) + if err != nil { + 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.Approval{ID: paramsUpdate.ID}} + getInfoUp, _, err := u.GetApprovalsListDB(ctx, options) + if err != nil { + return nil, nil, err + } + if len(getInfoUp) > 0 { + return getInfoUp[0], tx, nil + } + } + + return nil, tx, nil +} + +func (u *ApprovalDB) DeleteApprovalDB(ctx context.Context, params *typescore.Approval) error { + if params != nil && params.ID != nil { + query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Delete(dbcoretablenames.TableNameApprovals.ToString()). + Where(squirrel.Eq{"id": *params.ID}). + ToSql() + + if err != nil { + return err + } + + rows, err := u.pool.Query(ctx, query, args...) + if err != nil { + return err + } + defer rows.Close() + + return nil + } else { + return errors.New("approval obj is nil") + } +} + +func (u *ApprovalDB) GetApprovalByIDDB(ctx context.Context, id uint64) (*typescore.Approval, error) { + approvals, _, err := u.GetApprovalsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.Approval{ID: &id}, + }) + if err != nil { + return nil, err + } + if len(approvals) == 0 { + return nil, nil + } + return approvals[0], nil +} + +// GetActiveApprovalsByInitiatorDB — активные заявки инициатора (не закрытые) +func (u *ApprovalDB) GetActiveApprovalsByInitiatorDB(ctx context.Context, initiatorID uint64) ([]*typescore.Approval, error) { + sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Select(dbutils.GetStructFieldsDB(&typescore.Approval{}, dbcoretablenames.TableNameApprovals.ToString())...). + From(dbcoretablenames.TableNameApprovals.ToString()). + Where(squirrel.Eq{"initiator_id": initiatorID}). + // Показываем pending и approved — закрытые (revoked, rejected) не показываем + Where(squirrel.Eq{"status": []string{"pending", "approved"}}). + OrderBy("created_at DESC"). + ToSql() + if err != nil { + return nil, err + } + + rows, err := u.pool.Query(ctx, sql, args...) + if err != nil { + return nil, err + } + defer rows.Close() + + var result []*typescore.Approval + for rows.Next() { + a := &typescore.Approval{} + if err := dbutils.ScanRowsToStructRows(rows, a, nil); err != nil { + logrus.Warn("GetActiveApprovalsByInitiatorDB:ScanRowsToStruct", err) + continue + } + result = append(result, a) + } + return result, nil +} + +// GetPendingApprovalsByApproverDB — заявки ожидающие действия от согласующего +func (u *ApprovalDB) GetPendingApprovalsByApproverDB(ctx context.Context, approverID uint64) ([]*typescore.Approval, error) { + sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Select("DISTINCT a.*"). + From(dbcoretablenames.TableNameApprovals.ToString() + " a"). + Join(dbcoretablenames.TableNameApprovalSteps.ToString() + " s ON s.approval_id = a.id"). + Where(squirrel.Eq{"s.approver_id": approverID}). + Where(squirrel.Eq{"s.status": "pending"}). + Where(squirrel.Eq{"a.status": "pending"}). + OrderBy("a.created_at DESC"). + ToSql() + if err != nil { + return nil, err + } + + rows, err := u.pool.Query(ctx, sql, args...) + if err != nil { + return nil, err + } + defer rows.Close() + + var result []*typescore.Approval + for rows.Next() { + a := &typescore.Approval{} + if err := dbutils.ScanRowsToStructRows(rows, a, nil); err != nil { + logrus.Warn("GetPendingApprovalsByApproverDB:ScanRowsToStruct", err) + continue + } + result = append(result, a) + } + return result, nil +} + +// GetApprovalsByInitiatorAndCategoryDB — заявки инициатора по категории +func (u *ApprovalDB) GetApprovalsByInitiatorAndCategoryDB(ctx context.Context, initiatorID uint64, categoryCode string) ([]*typescore.Approval, error) { + sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Select("a.*"). + From(dbcoretablenames.TableNameApprovals.ToString() + " a"). + Join(dbcoretablenames.TableNameApprovalTopics.ToString() + " t ON t.id = a.topic_id"). + Join(dbcoretablenames.TableNameApprovalTopicCategories.ToString() + " c ON c.id = t.category_id"). + Where(squirrel.Eq{"a.initiator_id": initiatorID}). + Where(squirrel.Eq{"c.code": categoryCode}). + Where(squirrel.Eq{"a.status": []string{"pending", "approved"}}). + OrderBy("a.created_at DESC"). + ToSql() + if err != nil { + return nil, err + } + return u.queryApprovals(ctx, sql, args) +} + +// GetPendingApprovalsByApproverAndCategoryDB — входящие по категории для согласующего +func (u *ApprovalDB) GetPendingApprovalsByApproverAndCategoryDB(ctx context.Context, approverID uint64, categoryCode string) ([]*typescore.Approval, error) { + sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Select("DISTINCT a.*"). + From(dbcoretablenames.TableNameApprovals.ToString() + " a"). + Join(dbcoretablenames.TableNameApprovalSteps.ToString() + " s ON s.approval_id = a.id"). + Join(dbcoretablenames.TableNameApprovalTopics.ToString() + " t ON t.id = a.topic_id"). + Join(dbcoretablenames.TableNameApprovalTopicCategories.ToString() + " c ON c.id = t.category_id"). + Where(squirrel.Eq{"s.approver_id": approverID}). + Where(squirrel.Eq{"s.status": "pending"}). + Where(squirrel.Eq{"a.status": "pending"}). + Where(squirrel.Eq{"c.code": categoryCode}). + OrderBy("a.created_at DESC"). + ToSql() + if err != nil { + return nil, err + } + return u.queryApprovals(ctx, sql, args) +} + +// GetApprovalsByCategoryDB — все заявки по категории для наблюдателя +func (u *ApprovalDB) GetApprovalsByCategoryDB(ctx context.Context, categoryCode string) ([]*typescore.Approval, error) { + sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Select("a.*"). + From(dbcoretablenames.TableNameApprovals.ToString() + " a"). + Join(dbcoretablenames.TableNameApprovalTopics.ToString() + " t ON t.id = a.topic_id"). + Join(dbcoretablenames.TableNameApprovalTopicCategories.ToString() + " c ON c.id = t.category_id"). + Where(squirrel.Eq{"c.code": categoryCode}). + OrderBy("a.created_at DESC"). + ToSql() + if err != nil { + return nil, err + } + return u.queryApprovals(ctx, sql, args) +} + +// queryApprovals — общий сканер строк +func (u *ApprovalDB) queryApprovals(ctx context.Context, sql string, args []interface{}) ([]*typescore.Approval, error) { + rows, err := u.pool.Query(ctx, sql, args...) + if err != nil { + return nil, err + } + defer rows.Close() + + var result []*typescore.Approval + for rows.Next() { + a := &typescore.Approval{} + if err := dbutils.ScanRowsToStructRows(rows, a, nil); err != nil { + logrus.Warn("queryApprovals:ScanRowsToStruct", err) + continue + } + result = append(result, a) + } + return result, nil +} + +// GetClosedApprovalsByInitiatorDB — отклонённые и отозванные заявки инициатора. +func (u *ApprovalDB) GetClosedApprovalsByInitiatorDB(ctx context.Context, initiatorID uint64) ([]*typescore.Approval, error) { + sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Select(dbutils.GetStructFieldsDB(&typescore.Approval{}, dbcoretablenames.TableNameApprovals.ToString())...). + From(dbcoretablenames.TableNameApprovals.ToString()). + Where(squirrel.Eq{"initiator_id": initiatorID}). + Where(squirrel.Eq{"status": []string{"rejected", "revoked"}}). + OrderBy("updated_at DESC"). + Limit(50). + ToSql() + if err != nil { + return nil, err + } + return u.queryApprovals(ctx, sql, args) +} + +// GetApprovalsForReportDB — получение согласований для отчёта с учётом всех ролей пользователя. +// Пользователь видит согласования где он: инициатор, согласующий, наблюдатель или исполнитель. +func (u *ApprovalDB) GetApprovalsForReportDB(ctx context.Context, filter typescore.ReportFilter) ([]*typescore.Approval, error) { + q := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Select("DISTINCT a.*"). + From(dbcoretablenames.TableNameApprovals.ToString() + " a"). + OrderBy("a.created_at DESC") + + if !filter.AllAccess && filter.UserID != nil { + subQ1 := buildApprovalIdSubquery("initiator", filter.UserID) + subQ2 := buildApprovalIdSubquery("approver", filter.UserID) + subQ3 := buildApprovalIdSubquery("observer", filter.UserID) + subQ4 := buildApprovalIdSubquery("executor", filter.UserID) + + s1, a1, _ := subQ1.PlaceholderFormat(squirrel.Question).ToSql() + s2, a2, _ := subQ2.PlaceholderFormat(squirrel.Question).ToSql() + s3, a3, _ := subQ3.PlaceholderFormat(squirrel.Question).ToSql() + s4, a4, _ := subQ4.PlaceholderFormat(squirrel.Question).ToSql() + + unionSQL := fmt.Sprintf("(%s) UNION (%s) UNION (%s) UNION (%s)", s1, s2, s3, s4) + allArgs := append(append(append(a1, a2...), a3...), a4...) + + q = q.Where(squirrel.Expr("a.id IN ("+unionSQL+")", allArgs...)) + } + + if filter.DateFrom != nil { + q = q.Where(squirrel.GtOrEq{"a.created_at": filter.DateFrom}) + } + if filter.DateTo != nil { + endOfDay := filter.DateTo.Add(24*time.Hour - time.Second) + q = q.Where(squirrel.LtOrEq{"a.created_at": endOfDay}) + } + + sql, args, err := q.ToSql() + if err != nil { + return nil, err + } + return u.queryApprovals(ctx, sql, args) +} + +func buildApprovalIdSubquery(role string, userID *uint64) squirrel.SelectBuilder { + q := squirrel.Select("a.id"). + From(dbcoretablenames.TableNameApprovals.ToString() + " a") + + switch role { + case "initiator": + return q.Where(squirrel.Eq{"a.initiator_id": userID}) + + case "approver": + return q. + Join(dbcoretablenames.TableNameApprovalSteps.ToString() + " s ON s.approval_id = a.id"). + Where(squirrel.Eq{"s.approver_id": userID}) + + case "executor": + return q. + Join(dbcoretablenames.TableNameApprovalTasks.ToString() + " task ON task.approval_id = a.id"). + Where(squirrel.Eq{"task.executor_id": userID}) + + case "observer": + return q. + Join(dbcoretablenames.TableNameApprovalTopics.ToString() + " t ON t.id = a.topic_id"). + Join(dbcoretablenames.TableNameApprovalTopicCategories.ToString() + " c ON c.id = t.category_id"). + Join(dbcoretablenames.TableNamePermissions.ToString() + " p ON p.topic_category_id = c.id"). + Join("user_roles ur ON ur.role_id = p.role_id"). + Where(squirrel.And{ + squirrel.Eq{"ur.user_id": userID}, + squirrel.Eq{"p.action": "observe"}, + }) + + default: + return q.Where(squirrel.Expr("false")) + } +} diff --git a/core/db/methods/approval_additional_approver.go b/core/db/methods/approval_additional_approver.go new file mode 100644 index 0000000..e9a0350 --- /dev/null +++ b/core/db/methods/approval_additional_approver.go @@ -0,0 +1,186 @@ +package dbcore + +import ( + dbcoretablenames "bitrix_balancer_api/core/db/table_names" + "bitrix_balancer_api/core/typescore" + dbutils "bitrix_balancer_api/core/utilscore/db" + "context" + "errors" + "github.com/Masterminds/squirrel" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + "github.com/sirupsen/logrus" +) + +type ApprovalAdditionalApproverDB struct { + pool *pgxpool.Pool +} + +func NewApprovalAdditionalApproverDB(pool *pgxpool.Pool) *ApprovalAdditionalApproverDB { + return &ApprovalAdditionalApproverDB{ + pool: pool, + } +} + +type ApprovalAdditionalApproverDBI interface { + GetApprovalAdditionalApproversListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.ApprovalAdditionalApprover, uint64, error) + CreateApprovalAdditionalApproverDB(ctx context.Context, tx pgx.Tx, ApprovalAdditionalApproverObj *typescore.ApprovalAdditionalApprover, returnObj ...bool) (*typescore.ApprovalAdditionalApprover, pgx.Tx, error) + UpdateApprovalAdditionalApproverDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalAdditionalApprover, returnObj ...bool) (*typescore.ApprovalAdditionalApprover, pgx.Tx, error) + DeleteApprovalAdditionalApproverDB(ctx context.Context, params *typescore.ApprovalAdditionalApprover) error + GetApprovalAdditionalApproverByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalAdditionalApprover, error) +} + +func (u *ApprovalAdditionalApproverDB) GetApprovalAdditionalApproversListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalAdditionalApprover, uint64, error) { + fields := dbutils.GetStructFieldsDB(&typescore.ApprovalAdditionalApprover{}, dbcoretablenames.TableNameApprovalAdditionalApprovers.ToString()) + selectFields := append(fields, "COUNT(*) OVER() AS total_count") + + options, filter, err := dbutils.GetOptionsDB[typescore.ApprovalAdditionalApprover](opts...) + if err != nil { + return nil, 0, err + } + + query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovalAdditionalApprovers.ToString(), selectFields) + query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit) + query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovalAdditionalApprovers.ToString()) + query = query.OrderBy("created_at DESC") + + sql, args, err := query.ToSql() + if err != nil { + return nil, 0, err + } + + rows, err := u.pool.Query(ctx, sql, args...) + if err != nil { + return nil, 0, err + } + defer rows.Close() + + var ApprovalAdditionalApprovers []*typescore.ApprovalAdditionalApprover + var totalCount uint64 + for rows.Next() { + ApprovalAdditionalApprover := &typescore.ApprovalAdditionalApprover{} + if err := dbutils.ScanRowsToStructRows(rows, ApprovalAdditionalApprover, &totalCount); err != nil { + logrus.Warn("GetApprovalAdditionalApproversListDB:ScanRowsToStructRows", err) + continue + } + ApprovalAdditionalApprovers = append(ApprovalAdditionalApprovers, ApprovalAdditionalApprover) + } + + return ApprovalAdditionalApprovers, totalCount, nil +} + +func (u *ApprovalAdditionalApproverDB) CreateApprovalAdditionalApproverDB(ctx context.Context, tx pgx.Tx, ApprovalAdditionalApproverObj *typescore.ApprovalAdditionalApprover, returnObj ...bool) (*typescore.ApprovalAdditionalApprover, pgx.Tx, error) { + if ApprovalAdditionalApproverObj == nil { + return nil, nil, errors.New("ApprovalAdditionalApprover obj is nil") + } + + var insertedID uint64 + + err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { + query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Insert(dbcoretablenames.TableNameApprovalAdditionalApprovers.ToString()) + + sqlV, args, err := dbutils.GenerateInsertRequest(query, ApprovalAdditionalApproverObj) + if err != nil { + return err + } + + *sqlV = *sqlV + " RETURNING id" + + return tx.QueryRow(ctx, *sqlV, args...).Scan(&insertedID) + }) + + if err != nil { + return nil, tx, err + } + + returnObjBool := len(returnObj) > 0 && returnObj[0] + if returnObjBool && insertedID > 0 { + created, err := u.GetApprovalAdditionalApproverByIDDB(ctx, insertedID) + return created, tx, err + } + + return nil, tx, nil +} + +func (u *ApprovalAdditionalApproverDB) UpdateApprovalAdditionalApproverDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalAdditionalApprover, returnObj ...bool) (*typescore.ApprovalAdditionalApprover, pgx.Tx, error) { + if paramsUpdate.ID == nil { + return nil, nil, errors.New("ApprovalAdditionalApprover obj is nil") + } + + err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { + query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameApprovalAdditionalApprovers.ToString()) + query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate) + query = query.Where(squirrel.Eq{"id": paramsUpdate.ID}) + + sql, args, err := query.ToSql() + if err != nil { + return err + } + + _, err = tx.Exec(ctx, sql, args...) + if err != nil { + 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.ApprovalAdditionalApprover{ID: paramsUpdate.ID}} + getInfoUp, _, err := u.GetApprovalAdditionalApproversListDB(ctx, options) + if err != nil { + return nil, nil, err + } + if len(getInfoUp) > 0 { + return getInfoUp[0], tx, nil + } + } + + return nil, tx, nil +} + +func (u *ApprovalAdditionalApproverDB) DeleteApprovalAdditionalApproverDB(ctx context.Context, params *typescore.ApprovalAdditionalApprover) error { + if params != nil && params.ID != nil { + query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Delete(dbcoretablenames.TableNameApprovalAdditionalApprovers.ToString()). + Where(squirrel.Eq{"id": *params.ID}). + ToSql() + + if err != nil { + return err + } + + rows, err := u.pool.Query(ctx, query, args...) + if err != nil { + return err + } + defer rows.Close() + + return nil + } else { + return errors.New("ApprovalAdditionalApprover obj is nil") + } +} + +func (u *ApprovalAdditionalApproverDB) GetApprovalAdditionalApproverByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalAdditionalApprover, error) { + ApprovalAdditionalApprovers, _, err := u.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalAdditionalApprover{ID: &id}, + }) + if err != nil { + return nil, err + } + if len(ApprovalAdditionalApprovers) == 0 { + return nil, nil + } + return ApprovalAdditionalApprovers[0], nil +} diff --git a/core/db/methods/approval_additional_observer.go b/core/db/methods/approval_additional_observer.go new file mode 100644 index 0000000..7c5295c --- /dev/null +++ b/core/db/methods/approval_additional_observer.go @@ -0,0 +1,186 @@ +package dbcore + +import ( + dbcoretablenames "bitrix_balancer_api/core/db/table_names" + "bitrix_balancer_api/core/typescore" + dbutils "bitrix_balancer_api/core/utilscore/db" + "context" + "errors" + "github.com/Masterminds/squirrel" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + "github.com/sirupsen/logrus" +) + +type ApprovalAdditionalObserverDB struct { + pool *pgxpool.Pool +} + +func NewApprovalAdditionalObserverDB(pool *pgxpool.Pool) *ApprovalAdditionalObserverDB { + return &ApprovalAdditionalObserverDB{ + pool: pool, + } +} + +type ApprovalAdditionalObserverDBI interface { + GetApprovalAdditionalObserversListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.ApprovalAdditionalObserver, uint64, error) + CreateApprovalAdditionalObserverDB(ctx context.Context, tx pgx.Tx, ApprovalAdditionalObserverObj *typescore.ApprovalAdditionalObserver, returnObj ...bool) (*typescore.ApprovalAdditionalObserver, pgx.Tx, error) + UpdateApprovalAdditionalObserverDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalAdditionalObserver, returnObj ...bool) (*typescore.ApprovalAdditionalObserver, pgx.Tx, error) + DeleteApprovalAdditionalObserverDB(ctx context.Context, params *typescore.ApprovalAdditionalObserver) error + GetApprovalAdditionalObserverByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalAdditionalObserver, error) +} + +func (u *ApprovalAdditionalObserverDB) GetApprovalAdditionalObserversListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalAdditionalObserver, uint64, error) { + fields := dbutils.GetStructFieldsDB(&typescore.ApprovalAdditionalObserver{}, dbcoretablenames.TableNameApprovalAdditionalObservers.ToString()) + selectFields := append(fields, "COUNT(*) OVER() AS total_count") + + options, filter, err := dbutils.GetOptionsDB[typescore.ApprovalAdditionalObserver](opts...) + if err != nil { + return nil, 0, err + } + + query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovalAdditionalObservers.ToString(), selectFields) + query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit) + query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovalAdditionalObservers.ToString()) + query = query.OrderBy("created_at DESC") + + sql, args, err := query.ToSql() + if err != nil { + return nil, 0, err + } + + rows, err := u.pool.Query(ctx, sql, args...) + if err != nil { + return nil, 0, err + } + defer rows.Close() + + var ApprovalAdditionalObservers []*typescore.ApprovalAdditionalObserver + var totalCount uint64 + for rows.Next() { + ApprovalAdditionalObserver := &typescore.ApprovalAdditionalObserver{} + if err := dbutils.ScanRowsToStructRows(rows, ApprovalAdditionalObserver, &totalCount); err != nil { + logrus.Warn("GetApprovalAdditionalObserversListDB:ScanRowsToStructRows", err) + continue + } + ApprovalAdditionalObservers = append(ApprovalAdditionalObservers, ApprovalAdditionalObserver) + } + + return ApprovalAdditionalObservers, totalCount, nil +} + +func (u *ApprovalAdditionalObserverDB) CreateApprovalAdditionalObserverDB(ctx context.Context, tx pgx.Tx, ApprovalAdditionalObserverObj *typescore.ApprovalAdditionalObserver, returnObj ...bool) (*typescore.ApprovalAdditionalObserver, pgx.Tx, error) { + if ApprovalAdditionalObserverObj == nil { + return nil, nil, errors.New("ApprovalAdditionalObserver obj is nil") + } + + var insertedID uint64 + + err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { + query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Insert(dbcoretablenames.TableNameApprovalAdditionalObservers.ToString()) + + sqlV, args, err := dbutils.GenerateInsertRequest(query, ApprovalAdditionalObserverObj) + if err != nil { + return err + } + + *sqlV = *sqlV + " RETURNING id" + + return tx.QueryRow(ctx, *sqlV, args...).Scan(&insertedID) + }) + + if err != nil { + return nil, tx, err + } + + returnObjBool := len(returnObj) > 0 && returnObj[0] + if returnObjBool && insertedID > 0 { + created, err := u.GetApprovalAdditionalObserverByIDDB(ctx, insertedID) + return created, tx, err + } + + return nil, tx, nil +} + +func (u *ApprovalAdditionalObserverDB) UpdateApprovalAdditionalObserverDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalAdditionalObserver, returnObj ...bool) (*typescore.ApprovalAdditionalObserver, pgx.Tx, error) { + if paramsUpdate.ID == nil { + return nil, nil, errors.New("ApprovalAdditionalObserver obj is nil") + } + + err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { + query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameApprovalAdditionalObservers.ToString()) + query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate) + query = query.Where(squirrel.Eq{"id": paramsUpdate.ID}) + + sql, args, err := query.ToSql() + if err != nil { + return err + } + + _, err = tx.Exec(ctx, sql, args...) + if err != nil { + 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.ApprovalAdditionalObserver{ID: paramsUpdate.ID}} + getInfoUp, _, err := u.GetApprovalAdditionalObserversListDB(ctx, options) + if err != nil { + return nil, nil, err + } + if len(getInfoUp) > 0 { + return getInfoUp[0], tx, nil + } + } + + return nil, tx, nil +} + +func (u *ApprovalAdditionalObserverDB) DeleteApprovalAdditionalObserverDB(ctx context.Context, params *typescore.ApprovalAdditionalObserver) error { + if params != nil && params.ID != nil { + query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Delete(dbcoretablenames.TableNameApprovalAdditionalObservers.ToString()). + Where(squirrel.Eq{"id": *params.ID}). + ToSql() + + if err != nil { + return err + } + + rows, err := u.pool.Query(ctx, query, args...) + if err != nil { + return err + } + defer rows.Close() + + return nil + } else { + return errors.New("ApprovalAdditionalObserver obj is nil") + } +} + +func (u *ApprovalAdditionalObserverDB) GetApprovalAdditionalObserverByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalAdditionalObserver, error) { + ApprovalAdditionalObservers, _, err := u.GetApprovalAdditionalObserversListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalAdditionalObserver{ID: &id}, + }) + if err != nil { + return nil, err + } + if len(ApprovalAdditionalObservers) == 0 { + return nil, nil + } + return ApprovalAdditionalObservers[0], nil +} diff --git a/core/db/methods/approval_comment.go b/core/db/methods/approval_comment.go new file mode 100644 index 0000000..642be67 --- /dev/null +++ b/core/db/methods/approval_comment.go @@ -0,0 +1,217 @@ +package dbcore + +import ( + dbcoretablenames "bitrix_balancer_api/core/db/table_names" + "bitrix_balancer_api/core/typescore" + dbutils "bitrix_balancer_api/core/utilscore/db" + "context" + "errors" + "github.com/Masterminds/squirrel" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + "github.com/sirupsen/logrus" +) + +type ApprovalCommentDB struct { + pool *pgxpool.Pool +} + +func NewApprovalCommentDB(pool *pgxpool.Pool) *ApprovalCommentDB { + return &ApprovalCommentDB{ + pool: pool, + } +} + +type ApprovalCommentDBI interface { + GetApprovalCommentsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalComment, uint64, error) + CreateApprovalCommentDB(ctx context.Context, tx pgx.Tx, ApprovalCommentObj *typescore.ApprovalComment, returnObj ...bool) (*typescore.ApprovalComment, pgx.Tx, error) + UpdateApprovalCommentDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalComment, returnObj ...bool) (*typescore.ApprovalComment, pgx.Tx, error) + DeleteApprovalCommentDB(ctx context.Context, params *typescore.ApprovalComment) error + GetCommentsByApprovalIDDB(ctx context.Context, id uint64) ([]*typescore.ApprovalComment, error) + GetApprovalCommentByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalComment, error) +} + +func (u *ApprovalCommentDB) GetApprovalCommentsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalComment, uint64, error) { + fields := dbutils.GetStructFieldsDB(&typescore.ApprovalComment{}, dbcoretablenames.TableNameApprovalComments.ToString()) + selectFields := append(fields, "COUNT(*) OVER() AS total_count") + + options, filter, err := dbutils.GetOptionsDB[typescore.ApprovalComment](opts...) + if err != nil { + return nil, 0, err + } + + query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovalComments.ToString(), selectFields) + query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit) + query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovalComments.ToString()) + query = query.OrderBy("created_at DESC") + + sql, args, err := query.ToSql() + if err != nil { + return nil, 0, err + } + + rows, err := u.pool.Query(ctx, sql, args...) + if err != nil { + return nil, 0, err + } + defer rows.Close() + + var ApprovalComments []*typescore.ApprovalComment + var totalCount uint64 + for rows.Next() { + ApprovalComment := &typescore.ApprovalComment{} + if err := dbutils.ScanRowsToStructRows(rows, ApprovalComment, &totalCount); err != nil { + logrus.Warn("GetApprovalCommentsListDB:ScanRowsToStructRows", err) + continue + } + ApprovalComments = append(ApprovalComments, ApprovalComment) + } + + return ApprovalComments, totalCount, nil +} + +func (u *ApprovalCommentDB) CreateApprovalCommentDB(ctx context.Context, tx pgx.Tx, ApprovalCommentObj *typescore.ApprovalComment, returnObj ...bool) (*typescore.ApprovalComment, pgx.Tx, error) { + if ApprovalCommentObj == nil { + return nil, nil, errors.New("ApprovalComment obj is nil") + } + + var insertedID uint64 + + err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { + query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Insert(dbcoretablenames.TableNameApprovalComments.ToString()) + + sqlV, args, err := dbutils.GenerateInsertRequest(query, ApprovalCommentObj) + if err != nil { + return err + } + + *sqlV = *sqlV + " RETURNING id" + + return tx.QueryRow(ctx, *sqlV, args...).Scan(&insertedID) + }) + + if err != nil { + return nil, tx, err + } + + returnObjBool := len(returnObj) > 0 && returnObj[0] + if returnObjBool && insertedID > 0 { + created, err := u.GetApprovalCommentByIDDB(ctx, insertedID) + return created, tx, err + } + + return nil, tx, nil +} + +func (u *ApprovalCommentDB) UpdateApprovalCommentDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalComment, returnObj ...bool) (*typescore.ApprovalComment, pgx.Tx, error) { + if paramsUpdate.ID == nil { + return nil, nil, errors.New("ApprovalComment obj is nil") + } + + err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { + query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameApprovalComments.ToString()) + query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate) + query = query.Where(squirrel.Eq{"id": paramsUpdate.ID}) + + sql, args, err := query.ToSql() + if err != nil { + return err + } + + _, err = tx.Exec(ctx, sql, args...) + if err != nil { + 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.ApprovalComment{ID: paramsUpdate.ID}} + getInfoUp, _, err := u.GetApprovalCommentsListDB(ctx, options) + if err != nil { + return nil, nil, err + } + if len(getInfoUp) > 0 { + return getInfoUp[0], tx, nil + } + } + + return nil, tx, nil +} + +func (u *ApprovalCommentDB) DeleteApprovalCommentDB(ctx context.Context, params *typescore.ApprovalComment) error { + if params != nil && params.ID != nil { + query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Delete(dbcoretablenames.TableNameApprovalComments.ToString()). + Where(squirrel.Eq{"id": *params.ID}). + ToSql() + + if err != nil { + return err + } + + rows, err := u.pool.Query(ctx, query, args...) + if err != nil { + return err + } + defer rows.Close() + + return nil + } else { + return errors.New("ApprovalComment obj is nil") + } +} + +func (u *ApprovalCommentDB) GetCommentsByApprovalIDDB(ctx context.Context, id uint64) ([]*typescore.ApprovalComment, error) { + ApprovalComments, _, err := u.GetApprovalCommentsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalComment{ApprovalID: &id}, + }) + if err != nil { + return nil, err + } + return ApprovalComments, nil +} + +func (u *ApprovalCommentDB) GetApprovalCommentByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalComment, error) { + approvals, _, err := u.GetApprovalCommentsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.Approval{ID: &id}, + }) + if err != nil { + return nil, err + } + if len(approvals) == 0 { + return nil, nil + } + return approvals[0], nil +} + +// queryApprovalComments — общий сканер строк +func (u *ApprovalCommentDB) queryApprovalComments(ctx context.Context, sql string, args []interface{}) ([]*typescore.ApprovalComment, error) { + rows, err := u.pool.Query(ctx, sql, args...) + if err != nil { + return nil, err + } + defer rows.Close() + + var result []*typescore.ApprovalComment + for rows.Next() { + a := &typescore.ApprovalComment{} + if err := dbutils.ScanRowsToStructRows(rows, a, nil); err != nil { + logrus.Warn("queryApprovalComments:ScanRowsToStruct", err) + continue + } + result = append(result, a) + } + return result, nil +} diff --git a/core/db/methods/approval_delegation.go b/core/db/methods/approval_delegation.go new file mode 100644 index 0000000..eb58957 --- /dev/null +++ b/core/db/methods/approval_delegation.go @@ -0,0 +1,186 @@ +package dbcore + +import ( + dbcoretablenames "bitrix_balancer_api/core/db/table_names" + "bitrix_balancer_api/core/typescore" + dbutils "bitrix_balancer_api/core/utilscore/db" + "context" + "errors" + "github.com/Masterminds/squirrel" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + "github.com/sirupsen/logrus" +) + +type ApprovalDelegationDB struct { + pool *pgxpool.Pool +} + +func NewApprovalDelegationDB(pool *pgxpool.Pool) *ApprovalDelegationDB { + return &ApprovalDelegationDB{ + pool: pool, + } +} + +type ApprovalDelegationDBI interface { + GetApprovalDelegationsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalDelegation, uint64, error) + CreateApprovalDelegationDB(ctx context.Context, tx pgx.Tx, ApprovalDelegationObj *typescore.ApprovalDelegation, returnObj ...bool) (*typescore.ApprovalDelegation, pgx.Tx, error) + UpdateApprovalDelegationDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalDelegation, returnObj ...bool) (*typescore.ApprovalDelegation, pgx.Tx, error) + DeleteApprovalDelegationDB(ctx context.Context, params *typescore.ApprovalDelegation) error + GetApprovalDelegationByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalDelegation, error) +} + +func (u *ApprovalDelegationDB) GetApprovalDelegationsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalDelegation, uint64, error) { + fields := dbutils.GetStructFieldsDB(&typescore.ApprovalDelegation{}, dbcoretablenames.TableNameApprovalDelegations.ToString()) + selectFields := append(fields, "COUNT(*) OVER() AS total_count") + + options, filter, err := dbutils.GetOptionsDB[typescore.ApprovalDelegation](opts...) + if err != nil { + return nil, 0, err + } + + query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovalDelegations.ToString(), selectFields) + query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit) + query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovalDelegations.ToString()) + query = query.OrderBy("created_at DESC") + + sql, args, err := query.ToSql() + if err != nil { + return nil, 0, err + } + + rows, err := u.pool.Query(ctx, sql, args...) + if err != nil { + return nil, 0, err + } + defer rows.Close() + + var ApprovalDelegations []*typescore.ApprovalDelegation + var totalCount uint64 + for rows.Next() { + ApprovalDelegation := &typescore.ApprovalDelegation{} + if err := dbutils.ScanRowsToStructRows(rows, ApprovalDelegation, &totalCount); err != nil { + logrus.Warn("GetApprovalDelegationsListDB:ScanRowsToStructRows", err) + continue + } + ApprovalDelegations = append(ApprovalDelegations, ApprovalDelegation) + } + + return ApprovalDelegations, totalCount, nil +} + +func (u *ApprovalDelegationDB) CreateApprovalDelegationDB(ctx context.Context, tx pgx.Tx, ApprovalDelegationObj *typescore.ApprovalDelegation, returnObj ...bool) (*typescore.ApprovalDelegation, pgx.Tx, error) { + if ApprovalDelegationObj == nil { + return nil, nil, errors.New("ApprovalDelegation obj is nil") + } + + var insertedID uint64 + + err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { + query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Insert(dbcoretablenames.TableNameApprovalDelegations.ToString()) + + sqlV, args, err := dbutils.GenerateInsertRequest(query, ApprovalDelegationObj) + if err != nil { + return err + } + + *sqlV = *sqlV + " RETURNING id" + + return tx.QueryRow(ctx, *sqlV, args...).Scan(&insertedID) + }) + + if err != nil { + return nil, tx, err + } + + returnObjBool := len(returnObj) > 0 && returnObj[0] + if returnObjBool && insertedID > 0 { + created, err := u.GetApprovalDelegationByIDDB(ctx, insertedID) + return created, tx, err + } + + return nil, tx, nil +} + +func (u *ApprovalDelegationDB) UpdateApprovalDelegationDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalDelegation, returnObj ...bool) (*typescore.ApprovalDelegation, pgx.Tx, error) { + if paramsUpdate.ID == nil { + return nil, nil, errors.New("ApprovalDelegation obj is nil") + } + + err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { + query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameApprovalDelegations.ToString()) + query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate) + query = query.Where(squirrel.Eq{"id": paramsUpdate.ID}) + + sql, args, err := query.ToSql() + if err != nil { + return err + } + + _, err = tx.Exec(ctx, sql, args...) + if err != nil { + 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.ApprovalDelegation{ID: paramsUpdate.ID}} + getInfoUp, _, err := u.GetApprovalDelegationsListDB(ctx, options) + if err != nil { + return nil, nil, err + } + if len(getInfoUp) > 0 { + return getInfoUp[0], tx, nil + } + } + + return nil, tx, nil +} + +func (u *ApprovalDelegationDB) DeleteApprovalDelegationDB(ctx context.Context, params *typescore.ApprovalDelegation) error { + if params != nil && params.ID != nil { + query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Delete(dbcoretablenames.TableNameApprovalDelegations.ToString()). + Where(squirrel.Eq{"id": *params.ID}). + ToSql() + + if err != nil { + return err + } + + rows, err := u.pool.Query(ctx, query, args...) + if err != nil { + return err + } + defer rows.Close() + + return nil + } else { + return errors.New("ApprovalDelegation obj is nil") + } +} + +func (u *ApprovalDelegationDB) GetApprovalDelegationByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalDelegation, error) { + approvals, _, err := u.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalDelegation{ID: &id}, + }) + if err != nil { + return nil, err + } + if len(approvals) == 0 { + return nil, nil + } + return approvals[0], nil +} diff --git a/core/db/methods/approval_file.go b/core/db/methods/approval_file.go new file mode 100644 index 0000000..78d46e0 --- /dev/null +++ b/core/db/methods/approval_file.go @@ -0,0 +1,217 @@ +package dbcore + +import ( + dbcoretablenames "bitrix_balancer_api/core/db/table_names" + "bitrix_balancer_api/core/typescore" + dbutils "bitrix_balancer_api/core/utilscore/db" + "context" + "errors" + "github.com/Masterminds/squirrel" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + "github.com/sirupsen/logrus" +) + +type ApprovalFileDB struct { + pool *pgxpool.Pool +} + +func NewApprovalFileDB(pool *pgxpool.Pool) *ApprovalFileDB { + return &ApprovalFileDB{ + pool: pool, + } +} + +type ApprovalFileDBI interface { + GetApprovalFilesListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalFile, uint64, error) + CreateApprovalFileDB(ctx context.Context, tx pgx.Tx, ApprovalFileObj *typescore.ApprovalFile, returnObj ...bool) (*typescore.ApprovalFile, pgx.Tx, error) + UpdateApprovalFileDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalFile, returnObj ...bool) (*typescore.ApprovalFile, pgx.Tx, error) + DeleteApprovalFileDB(ctx context.Context, params *typescore.ApprovalFile) error + GetFilesByApprovalIDDB(ctx context.Context, id uint64) ([]*typescore.ApprovalFile, error) + GetApprovalFileByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalFile, error) +} + +func (u *ApprovalFileDB) GetApprovalFilesListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalFile, uint64, error) { + fields := dbutils.GetStructFieldsDB(&typescore.ApprovalFile{}, dbcoretablenames.TableNameApprovalFiles.ToString()) + selectFields := append(fields, "COUNT(*) OVER() AS total_count") + + options, filter, err := dbutils.GetOptionsDB[typescore.ApprovalFile](opts...) + if err != nil { + return nil, 0, err + } + + query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovalFiles.ToString(), selectFields) + query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit) + query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovalFiles.ToString()) + query = query.OrderBy("created_at DESC") + + sql, args, err := query.ToSql() + if err != nil { + return nil, 0, err + } + + rows, err := u.pool.Query(ctx, sql, args...) + if err != nil { + return nil, 0, err + } + defer rows.Close() + + var ApprovalFiles []*typescore.ApprovalFile + var totalCount uint64 + for rows.Next() { + ApprovalFile := &typescore.ApprovalFile{} + if err := dbutils.ScanRowsToStructRows(rows, ApprovalFile, &totalCount); err != nil { + logrus.Warn("GetApprovalFilesListDB:ScanRowsToStructRows", err) + continue + } + ApprovalFiles = append(ApprovalFiles, ApprovalFile) + } + + return ApprovalFiles, totalCount, nil +} + +func (u *ApprovalFileDB) CreateApprovalFileDB(ctx context.Context, tx pgx.Tx, ApprovalFileObj *typescore.ApprovalFile, returnObj ...bool) (*typescore.ApprovalFile, pgx.Tx, error) { + if ApprovalFileObj == nil { + return nil, nil, errors.New("ApprovalFile obj is nil") + } + + var insertedID uint64 + + err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { + query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Insert(dbcoretablenames.TableNameApprovalFiles.ToString()) + + sqlV, args, err := dbutils.GenerateInsertRequest(query, ApprovalFileObj) + if err != nil { + return err + } + + *sqlV = *sqlV + " RETURNING id" + + return tx.QueryRow(ctx, *sqlV, args...).Scan(&insertedID) + }) + + if err != nil { + return nil, tx, err + } + + returnObjBool := len(returnObj) > 0 && returnObj[0] + if returnObjBool && insertedID > 0 { + created, err := u.GetApprovalFileByIDDB(ctx, insertedID) + return created, tx, err + } + + return nil, tx, nil +} + +func (u *ApprovalFileDB) UpdateApprovalFileDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalFile, returnObj ...bool) (*typescore.ApprovalFile, pgx.Tx, error) { + if paramsUpdate.ID == nil { + return nil, nil, errors.New("ApprovalFile obj is nil") + } + + err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { + query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameApprovalFiles.ToString()) + query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate) + query = query.Where(squirrel.Eq{"id": paramsUpdate.ID}) + + sql, args, err := query.ToSql() + if err != nil { + return err + } + + _, err = tx.Exec(ctx, sql, args...) + if err != nil { + 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.ApprovalFile{ID: paramsUpdate.ID}} + getInfoUp, _, err := u.GetApprovalFilesListDB(ctx, options) + if err != nil { + return nil, nil, err + } + if len(getInfoUp) > 0 { + return getInfoUp[0], tx, nil + } + } + + return nil, tx, nil +} + +func (u *ApprovalFileDB) DeleteApprovalFileDB(ctx context.Context, params *typescore.ApprovalFile) error { + if params != nil && params.ID != nil { + query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Delete(dbcoretablenames.TableNameApprovalFiles.ToString()). + Where(squirrel.Eq{"id": *params.ID}). + ToSql() + + if err != nil { + return err + } + + rows, err := u.pool.Query(ctx, query, args...) + if err != nil { + return err + } + defer rows.Close() + + return nil + } else { + return errors.New("ApprovalFile obj is nil") + } +} + +func (u *ApprovalFileDB) GetFilesByApprovalIDDB(ctx context.Context, id uint64) ([]*typescore.ApprovalFile, error) { + ApprovalFiles, _, err := u.GetApprovalFilesListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalFile{ApprovalID: &id}, + }) + if err != nil { + return nil, err + } + return ApprovalFiles, nil +} + +func (u *ApprovalFileDB) GetApprovalFileByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalFile, error) { + approvals, _, err := u.GetApprovalFilesListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.Approval{ID: &id}, + }) + if err != nil { + return nil, err + } + if len(approvals) == 0 { + return nil, nil + } + return approvals[0], nil +} + +// queryApprovalFiles — общий сканер строк +func (u *ApprovalFileDB) queryApprovalFiles(ctx context.Context, sql string, args []interface{}) ([]*typescore.ApprovalFile, error) { + rows, err := u.pool.Query(ctx, sql, args...) + if err != nil { + return nil, err + } + defer rows.Close() + + var result []*typescore.ApprovalFile + for rows.Next() { + a := &typescore.ApprovalFile{} + if err := dbutils.ScanRowsToStructRows(rows, a, nil); err != nil { + logrus.Warn("queryApprovalFiles:ScanRowsToStruct", err) + continue + } + result = append(result, a) + } + return result, nil +} diff --git a/core/db/methods/approval_step.go b/core/db/methods/approval_step.go new file mode 100644 index 0000000..9cf04d3 --- /dev/null +++ b/core/db/methods/approval_step.go @@ -0,0 +1,234 @@ +package dbcore + +import ( + dbcoretablenames "bitrix_balancer_api/core/db/table_names" + "bitrix_balancer_api/core/typescore" + dbutils "bitrix_balancer_api/core/utilscore/db" + "context" + "errors" + "github.com/sirupsen/logrus" + + "github.com/Masterminds/squirrel" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" +) + +type ApprovalStepDB struct { + pool *pgxpool.Pool +} + +func NewApprovalStepDB(pool *pgxpool.Pool) *ApprovalStepDB { + return &ApprovalStepDB{ + pool: pool, + } +} + +type ApprovalStepDBI interface { + GetApprovalStepsListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.ApprovalStep, uint64, error) + CreateApprovalStepDB(ctx context.Context, tx pgx.Tx, ApprovalStepObj *typescore.ApprovalStep, returnObj ...bool) (*typescore.ApprovalStep, pgx.Tx, error) + UpdateApprovalStepDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalStep, returnObj ...bool) (*typescore.ApprovalStep, pgx.Tx, error) + DeleteApprovalStepDB(ctx context.Context, params *typescore.ApprovalStep) error + + GetActiveStepDB(ctx context.Context, approvalID uint64) (*typescore.ApprovalStep, error) + GetNextStepDB(ctx context.Context, approvalID uint64, currentOrder int) (*typescore.ApprovalStep, error) +} + +func (u *ApprovalStepDB) GetApprovalStepsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalStep, uint64, error) { + fields := dbutils.GetStructFieldsDB(&typescore.ApprovalStep{}, dbcoretablenames.TableNameApprovalSteps.ToString()) + selectFields := append(fields, "COUNT(*) OVER() AS total_count") + + options, filter, err := dbutils.GetOptionsDB[typescore.ApprovalStep](opts...) + if err != nil { + return nil, 0, err + } + + query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovalSteps.ToString(), selectFields) + query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit) + query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovalSteps.ToString()) + query = query.OrderBy("created_at DESC") + + sql, args, err := query.ToSql() + if err != nil { + return nil, 0, err + } + + rows, err := u.pool.Query(ctx, sql, args...) + if err != nil { + return nil, 0, err + } + defer rows.Close() + + var ApprovalSteps []*typescore.ApprovalStep + var totalCount uint64 + for rows.Next() { + ApprovalStep := &typescore.ApprovalStep{} + if err := dbutils.ScanRowsToStructRows(rows, ApprovalStep, &totalCount); err != nil { + logrus.Warn("GetApprovalStepsListDB:ScanRowsToStructRows", err) + continue + } + ApprovalSteps = append(ApprovalSteps, ApprovalStep) + } + + return ApprovalSteps, totalCount, nil +} + +func (u *ApprovalStepDB) CreateApprovalStepDB(ctx context.Context, tx pgx.Tx, ApprovalStepObj *typescore.ApprovalStep, returnObj ...bool) (*typescore.ApprovalStep, pgx.Tx, error) { + if ApprovalStepObj == nil { + return nil, nil, errors.New("ApprovalStep obj is nil") + } + + err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { + query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Insert(dbcoretablenames.TableNameApprovalSteps.ToString()) + + sqlV, args, err := dbutils.GenerateInsertRequest(query, ApprovalStepObj) + if err != nil { + return err + } + + _, err = tx.Exec(ctx, *sqlV, args...) + if err != nil { + return err + } + + return nil + }) + + if err != nil { + return nil, tx, err + } + + returnObjBool := false + if len(returnObj) > 0 { + returnObjBool = returnObj[0] + } + if returnObjBool { + ApprovalStep, _, err := u.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{Filtering: ApprovalStepObj}) + if err != nil { + return nil, tx, err + } + if len(ApprovalStep) > 0 { + return ApprovalStep[0], tx, nil + } + } + + return nil, tx, nil +} + +func (u *ApprovalStepDB) UpdateApprovalStepDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalStep, returnObj ...bool) (*typescore.ApprovalStep, pgx.Tx, error) { + if paramsUpdate.ID == nil { + return nil, nil, errors.New("ApprovalStep obj is nil") + } + + err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { + query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameApprovalSteps.ToString()) + query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate) + query = query.Where(squirrel.Eq{"id": paramsUpdate.ID}) + + sql, args, err := query.ToSql() + if err != nil { + return err + } + + _, err = tx.Exec(ctx, sql, args...) + if err != nil { + 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.ApprovalStep{ID: paramsUpdate.ID}} + getInfoUp, _, err := u.GetApprovalStepsListDB(ctx, options) + if err != nil { + return nil, nil, err + } + if len(getInfoUp) > 0 { + return getInfoUp[0], tx, nil + } + } + + return nil, tx, nil +} + +func (u *ApprovalStepDB) DeleteApprovalStepDB(ctx context.Context, params *typescore.ApprovalStep) error { + if params != nil && params.ID != nil { + query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Delete(dbcoretablenames.TableNameApprovalSteps.ToString()). + Where(squirrel.Eq{"id": *params.ID}). + ToSql() + + if err != nil { + return err + } + + rows, err := u.pool.Query(ctx, query, args...) + if err != nil { + return err + } + defer rows.Close() + + return nil + } else { + return errors.New("approvalStep obj is nil") + } +} + +// GetActiveStepDB возвращает текущий активный шаг — первый pending по порядку. +func (u *ApprovalStepDB) GetActiveStepDB(ctx context.Context, approvalID uint64) (*typescore.ApprovalStep, error) { + pendingStatus := "pending" + steps, _, err := u.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalStep{ + ApprovalID: &approvalID, + Status: &pendingStatus, + }, + Limit: func() *uint64 { v := uint64(1); return &v }(), + }) + if err != nil { + return nil, err + } + if len(steps) == 0 { + return nil, nil + } + return steps[0], nil +} + +// GetNextStepDB возвращает следующий шаг после текущего (status = waiting, step_order > current). +func (u *ApprovalStepDB) GetNextStepDB(ctx context.Context, approvalID uint64, currentOrder int) (*typescore.ApprovalStep, error) { + sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Select(dbutils.GetStructFieldsDB(&typescore.ApprovalStep{}, dbcoretablenames.TableNameApprovalSteps.ToString())...). + From(dbcoretablenames.TableNameApprovalSteps.ToString()). + Where(squirrel.Eq{"approval_id": approvalID}). + Where(squirrel.Eq{"status": "waiting"}). + Where(squirrel.Gt{"step_order": currentOrder}). + OrderBy("step_order ASC"). + Limit(1). + ToSql() + if err != nil { + return nil, err + } + + rows, err := u.pool.Query(ctx, sql, args...) + if err != nil { + return nil, err + } + defer rows.Close() + + if rows.Next() { + step := &typescore.ApprovalStep{} + if err := dbutils.ScanRowsToStructRows(rows, step, nil); err != nil { + return nil, err + } + return step, nil + } + return nil, nil +} diff --git a/core/db/methods/approval_task.go b/core/db/methods/approval_task.go new file mode 100644 index 0000000..7b69084 --- /dev/null +++ b/core/db/methods/approval_task.go @@ -0,0 +1,263 @@ +package dbcore + +import ( + dbcoretablenames "bitrix_balancer_api/core/db/table_names" + "bitrix_balancer_api/core/typescore" + dbutils "bitrix_balancer_api/core/utilscore/db" + "context" + "errors" + "fmt" + "github.com/Masterminds/squirrel" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + "github.com/sirupsen/logrus" + "time" +) + +type ApprovalTaskDB struct { + pool *pgxpool.Pool +} + +func NewApprovalTaskDB(pool *pgxpool.Pool) *ApprovalTaskDB { + return &ApprovalTaskDB{ + pool: pool, + } +} + +type ApprovalTaskDBI interface { + GetApprovalTasksListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.ApprovalTask, uint64, error) + CreateApprovalTaskDB(ctx context.Context, tx pgx.Tx, ApprovalTaskObj *typescore.ApprovalTask, returnObj ...bool) (*typescore.ApprovalTask, pgx.Tx, error) + UpdateApprovalTaskDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalTask, returnObj ...bool) (*typescore.ApprovalTask, pgx.Tx, error) + DeleteApprovalTaskDB(ctx context.Context, params *typescore.ApprovalTask) error + GetApprovalTaskByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalTask, error) + GetApprovalTaskByApprovalIDDB(ctx context.Context, id uint64) (*typescore.ApprovalTask, error) +} + +func (u *ApprovalTaskDB) GetApprovalTasksListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalTask, uint64, error) { + fields := dbutils.GetStructFieldsDB(&typescore.ApprovalTask{}, dbcoretablenames.TableNameApprovalTasks.ToString()) + selectFields := append(fields, "COUNT(*) OVER() AS total_count") + + options, filter, err := dbutils.GetOptionsDB[typescore.ApprovalTask](opts...) + if err != nil { + return nil, 0, err + } + + query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovalTasks.ToString(), selectFields) + query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit) + query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovalTasks.ToString()) + query = query.OrderBy("created_at DESC") + + sql, args, err := query.ToSql() + if err != nil { + return nil, 0, err + } + + rows, err := u.pool.Query(ctx, sql, args...) + if err != nil { + return nil, 0, err + } + defer rows.Close() + + var ApprovalTasks []*typescore.ApprovalTask + var totalCount uint64 + for rows.Next() { + ApprovalTask := &typescore.ApprovalTask{} + if err := dbutils.ScanRowsToStructRows(rows, ApprovalTask, &totalCount); err != nil { + logrus.Warn("GetApprovalTasksListDB:ScanRowsToStructRows", err) + continue + } + ApprovalTasks = append(ApprovalTasks, ApprovalTask) + } + + return ApprovalTasks, totalCount, nil +} + +func (u *ApprovalTaskDB) CreateApprovalTaskDB(ctx context.Context, tx pgx.Tx, ApprovalTaskObj *typescore.ApprovalTask, returnObj ...bool) (*typescore.ApprovalTask, pgx.Tx, error) { + if ApprovalTaskObj == nil { + return nil, nil, errors.New("ApprovalTask obj is nil") + } + + var insertedID uint64 + + err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { + query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Insert(dbcoretablenames.TableNameApprovalTasks.ToString()) + + sqlV, args, err := dbutils.GenerateInsertRequest(query, ApprovalTaskObj) + if err != nil { + return err + } + + *sqlV = *sqlV + " RETURNING id" + + return tx.QueryRow(ctx, *sqlV, args...).Scan(&insertedID) + }) + + if err != nil { + return nil, tx, err + } + + returnObjBool := len(returnObj) > 0 && returnObj[0] + if returnObjBool && insertedID > 0 { + created, err := u.GetApprovalTaskByIDDB(ctx, insertedID) + return created, tx, err + } + + return nil, tx, nil +} + +func (u *ApprovalTaskDB) UpdateApprovalTaskDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalTask, returnObj ...bool) (*typescore.ApprovalTask, pgx.Tx, error) { + if paramsUpdate.ID == nil { + return nil, nil, errors.New("ApprovalTask obj is nil") + } + + err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { + query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameApprovalTasks.ToString()) + query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate) + query = query.Where(squirrel.Eq{"id": paramsUpdate.ID}) + + sql, args, err := query.ToSql() + if err != nil { + return err + } + + _, err = tx.Exec(ctx, sql, args...) + if err != nil { + 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.ApprovalTask{ID: paramsUpdate.ID}} + getInfoUp, _, err := u.GetApprovalTasksListDB(ctx, options) + if err != nil { + return nil, nil, err + } + if len(getInfoUp) > 0 { + return getInfoUp[0], tx, nil + } + } + + return nil, tx, nil +} + +func (u *ApprovalTaskDB) DeleteApprovalTaskDB(ctx context.Context, params *typescore.ApprovalTask) error { + if params != nil && params.ID != nil { + query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Delete(dbcoretablenames.TableNameApprovalTasks.ToString()). + Where(squirrel.Eq{"id": *params.ID}). + ToSql() + + if err != nil { + return err + } + + rows, err := u.pool.Query(ctx, query, args...) + if err != nil { + return err + } + defer rows.Close() + + return nil + } else { + return errors.New("ApprovalTask obj is nil") + } +} + +func (u *ApprovalTaskDB) GetApprovalTaskByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalTask, error) { + ApprovalTasks, _, err := u.GetApprovalTasksListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalTask{ID: &id}, + }) + if err != nil { + return nil, err + } + if len(ApprovalTasks) == 0 { + return nil, nil + } + return ApprovalTasks[0], nil +} + +func (u *ApprovalTaskDB) GetApprovalTaskByApprovalIDDB(ctx context.Context, id uint64) (*typescore.ApprovalTask, error) { + ApprovalTasks, _, err := u.GetApprovalTasksListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalTask{ApprovalID: &id}, + }) + if err != nil { + return nil, err + } + if len(ApprovalTasks) == 0 { + return nil, nil + } + return ApprovalTasks[0], nil +} + +func (u *ApprovalTaskDB) GetTasksForReportDB(ctx context.Context, filter typescore.TaskReportFilter) ([]*typescore.ApprovalTask, error) { + q := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Select("DISTINCT t.*"). + From(dbcoretablenames.TableNameApprovalTasks.ToString() + " t"). + Join(dbcoretablenames.TableNameApprovals.ToString() + " a ON a.id = t.approval_id"). + OrderBy("t.created_at DESC") + + if !filter.AllAccess && filter.UserID != nil { + subQ1 := buildApprovalIdSubquery("initiator", filter.UserID) + subQ2 := buildApprovalIdSubquery("approver", filter.UserID) + subQ3 := buildApprovalIdSubquery("observer", filter.UserID) + subQ4 := buildApprovalIdSubquery("executor", filter.UserID) + + s1, a1, _ := subQ1.PlaceholderFormat(squirrel.Question).ToSql() + s2, a2, _ := subQ2.PlaceholderFormat(squirrel.Question).ToSql() + s3, a3, _ := subQ3.PlaceholderFormat(squirrel.Question).ToSql() + s4, a4, _ := subQ4.PlaceholderFormat(squirrel.Question).ToSql() + + unionSQL := fmt.Sprintf("(%s) UNION (%s) UNION (%s) UNION (%s)", s1, s2, s3, s4) + allArgs := append(append(append(a1, a2...), a3...), a4...) + + q = q.Where(squirrel.Expr("a.id IN ("+unionSQL+")", allArgs...)) + } + + // Применяем фильтр по датам (по дате создания задачи) + if filter.DateFrom != nil { + q = q.Where(squirrel.GtOrEq{"t.created_at": filter.DateFrom}) + } + if filter.DateTo != nil { + // До конца дня + endOfDay := filter.DateTo.Add(24*time.Hour - time.Second) + q = q.Where(squirrel.LtOrEq{"t.created_at": endOfDay}) + } + + sql, args, err := q.ToSql() + if err != nil { + return nil, err + } + return u.queryTasks(ctx, sql, args) +} + +// queryTasks — вспомогательная функция для выполнения запроса задач. +func (u *ApprovalTaskDB) queryTasks(ctx context.Context, sql string, args []interface{}) ([]*typescore.ApprovalTask, error) { + rows, err := u.pool.Query(ctx, sql, args...) + if err != nil { + return nil, err + } + defer rows.Close() + + var result []*typescore.ApprovalTask + for rows.Next() { + task := &typescore.ApprovalTask{} + if err := dbutils.ScanRowsToStructRows(rows, task, nil); err != nil { + logrus.Warn("queryTasks:ScanRowsToStruct", err) + continue + } + result = append(result, task) + } + return result, nil +} diff --git a/core/db/methods/approval_topic.go b/core/db/methods/approval_topic.go new file mode 100644 index 0000000..be16758 --- /dev/null +++ b/core/db/methods/approval_topic.go @@ -0,0 +1,210 @@ +package dbcore + +import ( + dbcoretablenames "bitrix_balancer_api/core/db/table_names" + "bitrix_balancer_api/core/typescore" + dbutils "bitrix_balancer_api/core/utilscore/db" + "context" + "errors" + "github.com/sirupsen/logrus" + + "github.com/Masterminds/squirrel" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" +) + +type ApprovalTopicDB struct { + pool *pgxpool.Pool +} + +func NewApprovalTopicDB(pool *pgxpool.Pool) *ApprovalTopicDB { + return &ApprovalTopicDB{ + pool: pool, + } +} + +type ApprovalTopicDBI interface { + GetApprovalTopicsListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.ApprovalTopic, uint64, error) + CreateApprovalTopicDB(ctx context.Context, tx pgx.Tx, ApprovalTopicObj *typescore.ApprovalTopic, returnObj ...bool) (*typescore.ApprovalTopic, pgx.Tx, error) + UpdateApprovalTopicDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalTopic, returnObj ...bool) (*typescore.ApprovalTopic, pgx.Tx, error) + DeleteApprovalTopicDB(ctx context.Context, params *typescore.ApprovalTopic) error + + GetApprovalTopicByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalTopic, error) + GetApprovalTopicByCodeDB(ctx context.Context, code string) (*typescore.ApprovalTopic, error) +} + +func (u *ApprovalTopicDB) GetApprovalTopicsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalTopic, uint64, error) { + fields := dbutils.GetStructFieldsDB(&typescore.ApprovalTopic{}, dbcoretablenames.TableNameApprovalTopics.ToString()) + selectFields := append(fields, "COUNT(*) OVER() AS total_count") + + options, filter, err := dbutils.GetOptionsDB[typescore.ApprovalTopic](opts...) + if err != nil { + return nil, 0, err + } + + query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovalTopics.ToString(), selectFields) + query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit) + query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovalTopics.ToString()) + query = query.OrderBy("created_at DESC") + + sql, args, err := query.ToSql() + if err != nil { + return nil, 0, err + } + + rows, err := u.pool.Query(ctx, sql, args...) + if err != nil { + return nil, 0, err + } + defer rows.Close() + + var ApprovalTopics []*typescore.ApprovalTopic + var totalCount uint64 + for rows.Next() { + ApprovalTopic := &typescore.ApprovalTopic{} + if err := dbutils.ScanRowsToStructRows(rows, ApprovalTopic, &totalCount); err != nil { + logrus.Warn("GetApprovalTopicsListDB:ScanRowsToStructRows", err) + continue + } + ApprovalTopics = append(ApprovalTopics, ApprovalTopic) + } + + return ApprovalTopics, totalCount, nil +} + +func (u *ApprovalTopicDB) CreateApprovalTopicDB(ctx context.Context, tx pgx.Tx, ApprovalTopicObj *typescore.ApprovalTopic, returnObj ...bool) (*typescore.ApprovalTopic, pgx.Tx, error) { + if ApprovalTopicObj == nil { + return nil, nil, errors.New("ApprovalTopic obj is nil") + } + + err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { + query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Insert(dbcoretablenames.TableNameApprovalTopics.ToString()) + + sqlV, args, err := dbutils.GenerateInsertRequest(query, ApprovalTopicObj) + if err != nil { + return err + } + + _, err = tx.Exec(ctx, *sqlV, args...) + if err != nil { + return err + } + + return nil + }) + + if err != nil { + return nil, tx, err + } + + returnObjBool := false + if len(returnObj) > 0 { + returnObjBool = returnObj[0] + } + if returnObjBool { + ApprovalTopic, _, err := u.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{Filtering: ApprovalTopicObj}) + if err != nil { + return nil, tx, err + } + if len(ApprovalTopic) > 0 { + return ApprovalTopic[0], tx, nil + } + } + + return nil, tx, nil +} + +func (u *ApprovalTopicDB) UpdateApprovalTopicDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalTopic, returnObj ...bool) (*typescore.ApprovalTopic, pgx.Tx, error) { + if paramsUpdate.ID == nil { + return nil, nil, errors.New("ApprovalTopic obj is nil") + } + + err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { + query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameApprovalTopics.ToString()) + query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate) + query = query.Where(squirrel.Eq{"id": paramsUpdate.ID}) + + sql, args, err := query.ToSql() + if err != nil { + return err + } + + _, err = tx.Exec(ctx, sql, args...) + if err != nil { + 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.ApprovalTopic{ID: paramsUpdate.ID}} + getInfoUp, _, err := u.GetApprovalTopicsListDB(ctx, options) + if err != nil { + return nil, nil, err + } + if len(getInfoUp) > 0 { + return getInfoUp[0], tx, nil + } + } + + return nil, tx, nil +} + +func (u *ApprovalTopicDB) DeleteApprovalTopicDB(ctx context.Context, params *typescore.ApprovalTopic) error { + if params != nil && params.ID != nil { + query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Delete(dbcoretablenames.TableNameApprovalTopics.ToString()). + Where(squirrel.Eq{"id": *params.ID}). + ToSql() + + if err != nil { + return err + } + + rows, err := u.pool.Query(ctx, query, args...) + if err != nil { + return err + } + defer rows.Close() + + return nil + } else { + return errors.New("approvalTopic obj is nil") + } +} + +func (u *ApprovalTopicDB) GetApprovalTopicByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalTopic, error) { + topics, _, err := u.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalTopic{ID: &id}, + }) + if err != nil { + return nil, err + } + if len(topics) == 0 { + return nil, nil + } + return topics[0], nil +} + +func (u *ApprovalTopicDB) GetApprovalTopicByCodeDB(ctx context.Context, code string) (*typescore.ApprovalTopic, error) { + topics, _, err := u.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalTopic{Code: &code}, + }) + if err != nil { + return nil, err + } + if len(topics) == 0 { + return nil, nil + } + return topics[0], nil +} diff --git a/core/db/methods/approval_topic_category.go b/core/db/methods/approval_topic_category.go new file mode 100644 index 0000000..7a7d8d2 --- /dev/null +++ b/core/db/methods/approval_topic_category.go @@ -0,0 +1,288 @@ +package dbcore + +import ( + dbcoretablenames "bitrix_balancer_api/core/db/table_names" + "bitrix_balancer_api/core/typescore" + dbutils "bitrix_balancer_api/core/utilscore/db" + "context" + "errors" + "github.com/sirupsen/logrus" + + "github.com/Masterminds/squirrel" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" +) + +type ApprovalTopicCategoryDB struct { + pool *pgxpool.Pool +} + +func NewApprovalTopicCategoryDB(pool *pgxpool.Pool) *ApprovalTopicCategoryDB { + return &ApprovalTopicCategoryDB{ + pool: pool, + } +} + +type ApprovalTopicCategoryDBI interface { + GetApprovalTopicCategoryListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.ApprovalTopicCategory, uint64, error) + CreateApprovalTopicCategoryDB(ctx context.Context, tx pgx.Tx, ApprovalTopicCategoryObj *typescore.ApprovalTopicCategory, returnObj ...bool) (*typescore.ApprovalTopicCategory, pgx.Tx, error) + UpdateApprovalTopicCategoryDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalTopicCategory, returnObj ...bool) (*typescore.ApprovalTopicCategory, pgx.Tx, error) + DeleteApprovalTopicCategoryDB(ctx context.Context, params *typescore.ApprovalTopicCategory) error + GetApprovalTopicCategoryByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalTopicCategory, error) + GetApprovalTopicCategoryByCodeDB(ctx context.Context, code string) (*typescore.ApprovalTopicCategory, error) + GetCategoriesWithApprovalsByInitiatorDB( + ctx context.Context, + initiatorID uint64, + ) ([]*typescore.ApprovalTopicCategory, error) + GetCategoriesWithApprovalsByApproverDB(ctx context.Context, approverID uint64) ([]*typescore.ApprovalTopicCategory, error) +} + +// GetCategoriesWithApprovalsByInitiatorDB — категории тем, по которым у инициатора есть заявки +func (u *ApprovalTopicCategoryDB) GetCategoriesWithApprovalsByInitiatorDB( + ctx context.Context, + initiatorID uint64, +) ([]*typescore.ApprovalTopicCategory, error) { + sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Select("DISTINCT c.*"). + From(dbcoretablenames.TableNameApprovalTopicCategories.ToString() + " c"). + Join(dbcoretablenames.TableNameApprovalTopics.ToString() + " t ON t.category_id = c.id"). + Join(dbcoretablenames.TableNameApprovals.ToString() + " a ON a.topic_id = t.id"). + Where(squirrel.Eq{"a.initiator_id": initiatorID}). + Where(squirrel.Eq{"c.is_active": true}). + OrderBy("c.name ASC"). + ToSql() + if err != nil { + return nil, err + } + + rows, err := u.pool.Query(ctx, sql, args...) + if err != nil { + return nil, err + } + defer rows.Close() + + var result []*typescore.ApprovalTopicCategory + for rows.Next() { + obj := &typescore.ApprovalTopicCategory{} + if err := dbutils.ScanRowsToStructRows(rows, obj, nil); err != nil { + logrus.Warn("GetCategoriesWithApprovalsByInitiatorDB:Scan", err) + continue + } + result = append(result, obj) + } + return result, nil +} + +// GetCategoriesWithApprovalsByApproverDB — категории тем, в которых +// пользователь участвовал как согласующий (через approval_steps). +func (u *ApprovalTopicCategoryDB) GetCategoriesWithApprovalsByApproverDB( + ctx context.Context, + approverID uint64, +) ([]*typescore.ApprovalTopicCategory, error) { + sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Select("DISTINCT c.*"). + From(dbcoretablenames.TableNameApprovalTopicCategories.ToString() + " c"). + Join(dbcoretablenames.TableNameApprovalTopics.ToString() + " t ON t.category_id = c.id"). + Join(dbcoretablenames.TableNameApprovals.ToString() + " a ON a.topic_id = t.id"). + Join(dbcoretablenames.TableNameApprovalSteps.ToString() + " s ON s.approval_id = a.id"). + Where(squirrel.Eq{"s.approver_id": approverID}). + Where(squirrel.Eq{"c.is_active": true}). + OrderBy("c.name ASC"). + ToSql() + if err != nil { + return nil, err + } + + rows, err := u.pool.Query(ctx, sql, args...) + if err != nil { + return nil, err + } + defer rows.Close() + + var result []*typescore.ApprovalTopicCategory + for rows.Next() { + obj := &typescore.ApprovalTopicCategory{} + if err := dbutils.ScanRowsToStructRows(rows, obj, nil); err != nil { + logrus.Warn("GetCategoriesWithApprovalsByApproverDB:Scan", err) + continue + } + result = append(result, obj) + } + return result, nil +} + +func (u *ApprovalTopicCategoryDB) GetApprovalTopicCategoryListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalTopicCategory, uint64, error) { + fields := dbutils.GetStructFieldsDB(&typescore.ApprovalTopicCategory{}, dbcoretablenames.TableNameApprovalTopicCategories.ToString()) + selectFields := append(fields, "COUNT(*) OVER() AS total_count") + + options, filter, err := dbutils.GetOptionsDB[typescore.ApprovalTopicCategory](opts...) + if err != nil { + return nil, 0, err + } + + query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovalTopicCategories.ToString(), selectFields) + query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit) + query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovalTopicCategories.ToString()) + query = query.OrderBy("created_at DESC") + + sql, args, err := query.ToSql() + if err != nil { + return nil, 0, err + } + + rows, err := u.pool.Query(ctx, sql, args...) + if err != nil { + return nil, 0, err + } + defer rows.Close() + + var ApprovalTopicCategorys []*typescore.ApprovalTopicCategory + var totalCount uint64 + for rows.Next() { + ApprovalTopicCategory := &typescore.ApprovalTopicCategory{} + if err := dbutils.ScanRowsToStructRows(rows, ApprovalTopicCategory, &totalCount); err != nil { + logrus.Warn("GetApprovalTopicCategorysListDB:ScanRowsToStructRows", err) + continue + } + ApprovalTopicCategorys = append(ApprovalTopicCategorys, ApprovalTopicCategory) + } + + return ApprovalTopicCategorys, totalCount, nil +} + +func (u *ApprovalTopicCategoryDB) CreateApprovalTopicCategoryDB(ctx context.Context, tx pgx.Tx, ApprovalTopicCategoryObj *typescore.ApprovalTopicCategory, returnObj ...bool) (*typescore.ApprovalTopicCategory, pgx.Tx, error) { + if ApprovalTopicCategoryObj == nil { + return nil, nil, errors.New("ApprovalTopicCategory obj is nil") + } + + err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { + query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Insert(dbcoretablenames.TableNameApprovalTopicCategories.ToString()) + + sqlV, args, err := dbutils.GenerateInsertRequest(query, ApprovalTopicCategoryObj) + if err != nil { + return err + } + + _, err = tx.Exec(ctx, *sqlV, args...) + if err != nil { + return err + } + + return nil + }) + + if err != nil { + return nil, tx, err + } + + returnObjBool := false + if len(returnObj) > 0 { + returnObjBool = returnObj[0] + } + if returnObjBool { + ApprovalTopicCategory, _, err := u.GetApprovalTopicCategoryListDB(ctx, typescore.ListDbOptions{Filtering: ApprovalTopicCategoryObj}) + if err != nil { + return nil, tx, err + } + if len(ApprovalTopicCategory) > 0 { + return ApprovalTopicCategory[0], tx, nil + } + } + + return nil, tx, nil +} + +func (u *ApprovalTopicCategoryDB) UpdateApprovalTopicCategoryDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalTopicCategory, returnObj ...bool) (*typescore.ApprovalTopicCategory, pgx.Tx, error) { + if paramsUpdate.ID == nil { + return nil, nil, errors.New("ApprovalTopicCategory obj is nil") + } + + err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { + query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameApprovalTopicCategories.ToString()) + query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate) + query = query.Where(squirrel.Eq{"id": paramsUpdate.ID}) + + sql, args, err := query.ToSql() + if err != nil { + return err + } + + _, err = tx.Exec(ctx, sql, args...) + if err != nil { + 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.ApprovalTopicCategory{ID: paramsUpdate.ID}} + getInfoUp, _, err := u.GetApprovalTopicCategoryListDB(ctx, options) + if err != nil { + return nil, nil, err + } + if len(getInfoUp) > 0 { + return getInfoUp[0], tx, nil + } + } + + return nil, tx, nil +} + +func (u *ApprovalTopicCategoryDB) DeleteApprovalTopicCategoryDB(ctx context.Context, params *typescore.ApprovalTopicCategory) error { + if params != nil && params.ID != nil { + query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Delete(dbcoretablenames.TableNameApprovalTopicCategories.ToString()). + Where(squirrel.Eq{"id": *params.ID}). + ToSql() + + if err != nil { + return err + } + + rows, err := u.pool.Query(ctx, query, args...) + if err != nil { + return err + } + defer rows.Close() + + return nil + } else { + return errors.New("approvalTopicCategory obj is nil") + } +} + +func (u *ApprovalTopicCategoryDB) GetApprovalTopicCategoryByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalTopicCategory, error) { + categories, _, err := u.GetApprovalTopicCategoryListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalTopicCategory{ID: &id}, + }) + if err != nil { + return nil, err + } + if len(categories) == 0 { + return nil, nil + } + return categories[0], nil +} + +func (u *ApprovalTopicCategoryDB) GetApprovalTopicCategoryByCodeDB(ctx context.Context, code string) (*typescore.ApprovalTopicCategory, error) { + categories, _, err := u.GetApprovalTopicCategoryListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalTopicCategory{Code: &code}, + }) + if err != nil { + return nil, err + } + if len(categories) == 0 { + return nil, nil + } + return categories[0], nil +} diff --git a/core/db/methods/approval_topic_executor.go b/core/db/methods/approval_topic_executor.go new file mode 100644 index 0000000..681026e --- /dev/null +++ b/core/db/methods/approval_topic_executor.go @@ -0,0 +1,199 @@ +package dbcore + +import ( + dbcoretablenames "bitrix_balancer_api/core/db/table_names" + "bitrix_balancer_api/core/typescore" + dbutils "bitrix_balancer_api/core/utilscore/db" + "context" + "errors" + "github.com/sirupsen/logrus" + + "github.com/Masterminds/squirrel" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" +) + +type ApprovalTopicExecutorDB struct { + pool *pgxpool.Pool +} + +func NewApprovalTopicExecutorDB(pool *pgxpool.Pool) *ApprovalTopicExecutorDB { + return &ApprovalTopicExecutorDB{pool: pool} +} + +type ApprovalTopicExecutorDBI interface { + GetApprovalTopicExecutorListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.ApprovalTopicExecutor, uint64, error) + CreateApprovalTopicExecutorDB(ctx context.Context, tx pgx.Tx, obj *typescore.ApprovalTopicExecutor, returnObj ...bool) (*typescore.ApprovalTopicExecutor, pgx.Tx, error) + UpdateApprovalTopicExecutorDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalTopicExecutor, returnObj ...bool) (*typescore.ApprovalTopicExecutor, pgx.Tx, error) + DeleteApprovalTopicExecutorDB(ctx context.Context, params *typescore.ApprovalTopicExecutor) error + GetExecutorsByTopicIDDB(ctx context.Context, topicID uint64) ([]*typescore.ApprovalTopicExecutor, error) +} + +func (d *ApprovalTopicExecutorDB) GetApprovalTopicExecutorListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalTopicExecutor, uint64, error) { + fields := dbutils.GetStructFieldsDB(&typescore.ApprovalTopicExecutor{}, dbcoretablenames.TableNameApprovalTopicExecutor.ToString()) + selectFields := append(fields, "COUNT(*) OVER() AS total_count") + + options, filter, err := dbutils.GetOptionsDB[typescore.ApprovalTopicExecutor](opts...) + if err != nil { + return nil, 0, err + } + + query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovalTopicExecutor.ToString(), selectFields) + query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit) + query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovalTopicExecutor.ToString()) + query = query.OrderBy("step_order ASC, id ASC") + + sql, args, err := query.ToSql() + if err != nil { + return nil, 0, err + } + + rows, err := d.pool.Query(ctx, sql, args...) + if err != nil { + return nil, 0, err + } + defer rows.Close() + + var result []*typescore.ApprovalTopicExecutor + var totalCount uint64 + for rows.Next() { + item := &typescore.ApprovalTopicExecutor{} + if err := dbutils.ScanRowsToStructRows(rows, item, &totalCount); err != nil { + logrus.Warn("GetApprovalTopicExecutorListDB:ScanRowsToStructRows", err) + continue + } + result = append(result, item) + } + + return result, totalCount, nil +} + +func (d *ApprovalTopicExecutorDB) CreateApprovalTopicExecutorDB(ctx context.Context, tx pgx.Tx, obj *typescore.ApprovalTopicExecutor, returnObj ...bool) (*typescore.ApprovalTopicExecutor, pgx.Tx, error) { + if obj == nil { + return nil, nil, errors.New("ApprovalTopicExecutor obj is nil") + } + + err := dbutils.ExecuteTx(ctx, d.pool, tx, func(tx pgx.Tx) error { + query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Insert(dbcoretablenames.TableNameApprovalTopicExecutor.ToString()) + + sqlV, args, err := dbutils.GenerateInsertRequest(query, obj) + if err != nil { + return err + } + + _, err = tx.Exec(ctx, *sqlV, args...) + return err + }) + + if err != nil { + return nil, tx, err + } + + returnObjBool := false + if len(returnObj) > 0 { + returnObjBool = returnObj[0] + } + if returnObjBool { + items, _, err := d.GetApprovalTopicExecutorListDB(ctx, typescore.ListDbOptions{Filtering: obj}) + if err != nil { + return nil, tx, err + } + if len(items) > 0 { + return items[0], tx, nil + } + } + + return nil, tx, nil +} + +func (d *ApprovalTopicExecutorDB) UpdateApprovalTopicExecutorDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalTopicExecutor, returnObj ...bool) (*typescore.ApprovalTopicExecutor, pgx.Tx, error) { + if paramsUpdate.ID == nil { + return nil, nil, errors.New("ApprovalTopicExecutor obj is nil") + } + + err := dbutils.ExecuteTx(ctx, d.pool, tx, func(tx pgx.Tx) error { + query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Update(dbcoretablenames.TableNameApprovalTopicExecutor.ToString()) + query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate) + query = query.Where(squirrel.Eq{"id": paramsUpdate.ID}) + + sql, args, err := query.ToSql() + if err != nil { + return err + } + + _, err = tx.Exec(ctx, sql, args...) + return err + }) + + if err != nil { + return nil, tx, err + } + + returnObjBool := false + if len(returnObj) > 0 { + returnObjBool = returnObj[0] + } + + if returnObjBool { + options := typescore.ListDbOptions{Filtering: &typescore.ApprovalTopicExecutor{ID: paramsUpdate.ID}} + items, _, err := d.GetApprovalTopicExecutorListDB(ctx, options) + if err != nil { + return nil, nil, err + } + if len(items) > 0 { + return items[0], tx, nil + } + } + + return nil, tx, nil +} + +func (d *ApprovalTopicExecutorDB) DeleteApprovalTopicExecutorDB(ctx context.Context, params *typescore.ApprovalTopicExecutor) error { + if params != nil && params.ID != nil { + query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Delete(dbcoretablenames.TableNameApprovalTopicExecutor.ToString()). + Where(squirrel.Eq{"id": *params.ID}). + ToSql() + + if err != nil { + return err + } + + _, err = d.pool.Query(ctx, query, args...) + return err + } + return errors.New("ApprovalTopicExecutor obj is nil") +} + +// GetExecutorsByTopicIDDB возвращает всех исполнителей для темы, отсортированных по step_order +func (d *ApprovalTopicExecutorDB) GetExecutorsByTopicIDDB(ctx context.Context, topicID uint64) ([]*typescore.ApprovalTopicExecutor, error) { + sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Select("ate.*"). + From(dbcoretablenames.TableNameApprovalTopicExecutor.ToString() + " ate"). + Where(squirrel.Eq{"ate.topic_id": topicID}). + Where(squirrel.Eq{"ate.is_active": true}). + OrderBy("ate.step_order ASC, ate.id ASC"). + ToSql() + if err != nil { + return nil, err + } + + rows, err := d.pool.Query(ctx, sql, args...) + if err != nil { + return nil, err + } + defer rows.Close() + + var result []*typescore.ApprovalTopicExecutor + for rows.Next() { + item := &typescore.ApprovalTopicExecutor{} + if err := dbutils.ScanRowsToStructRows(rows, item, nil); err != nil { + logrus.Warn("GetExecutorsByTopicIDDB:ScanRowsToStructRows", err) + continue + } + result = append(result, item) + } + return result, nil +} diff --git a/core/db/methods/department.go b/core/db/methods/department.go new file mode 100644 index 0000000..c3d7797 --- /dev/null +++ b/core/db/methods/department.go @@ -0,0 +1,192 @@ +package dbcore + +import ( + dbcoretablenames "bitrix_balancer_api/core/db/table_names" + "bitrix_balancer_api/core/typescore" + dbutils "bitrix_balancer_api/core/utilscore/db" + "context" + "errors" + "github.com/sirupsen/logrus" + + "github.com/Masterminds/squirrel" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" +) + +type DepartmentDB struct { + pool *pgxpool.Pool +} + +func NewDepartmentDB(pool *pgxpool.Pool) *DepartmentDB { + return &DepartmentDB{ + pool: pool, + } +} + +type DepartmentDBI interface { + GetDepartmentsListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.Department, uint64, error) + CreateDepartmentDB(ctx context.Context, tx pgx.Tx, DepartmentObj *typescore.Department, returnObj ...bool) (*typescore.Department, pgx.Tx, error) + UpdateDepartmentDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.Department, returnObj ...bool) (*typescore.Department, pgx.Tx, error) + DeleteDepartmentDB(ctx context.Context, params *typescore.Department) error + GetDepartmentByIDDB(ctx context.Context, id uint64) (*typescore.Department, error) +} + +func (u *DepartmentDB) GetDepartmentsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.Department, uint64, error) { + fields := dbutils.GetStructFieldsDB(&typescore.Department{}, dbcoretablenames.TableNameDepartments.ToString()) + selectFields := append(fields, "COUNT(*) OVER() AS total_count") + + options, filter, err := dbutils.GetOptionsDB[typescore.Department](opts...) + if err != nil { + return nil, 0, err + } + + query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameDepartments.ToString(), selectFields) + query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit) + query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameDepartments.ToString()) + query = query.OrderBy("created_at DESC") + + sql, args, err := query.ToSql() + if err != nil { + return nil, 0, err + } + + rows, err := u.pool.Query(ctx, sql, args...) + if err != nil { + return nil, 0, err + } + defer rows.Close() + + var Departments []*typescore.Department + var totalCount uint64 + for rows.Next() { + Department := &typescore.Department{} + if err := dbutils.ScanRowsToStructRows(rows, Department, &totalCount); err != nil { + logrus.Warn("GetDepartmentsListDB:ScanRowsToStructRows", err) + continue + } + Departments = append(Departments, Department) + } + + return Departments, totalCount, nil +} + +func (u *DepartmentDB) CreateDepartmentDB(ctx context.Context, tx pgx.Tx, DepartmentObj *typescore.Department, returnObj ...bool) (*typescore.Department, pgx.Tx, error) { + if DepartmentObj == nil { + return nil, nil, errors.New("Department obj is nil") + } + + err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { + query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Insert(dbcoretablenames.TableNameDepartments.ToString()) + + sqlV, args, err := dbutils.GenerateInsertRequest(query, DepartmentObj) + if err != nil { + return err + } + + _, err = tx.Exec(ctx, *sqlV, args...) + if err != nil { + return err + } + + return nil + }) + + if err != nil { + return nil, tx, err + } + + returnObjBool := false + if len(returnObj) > 0 { + returnObjBool = returnObj[0] + } + if returnObjBool { + Department, _, err := u.GetDepartmentsListDB(ctx, typescore.ListDbOptions{Filtering: DepartmentObj}) + if err != nil { + return nil, tx, err + } + if len(Department) > 0 { + return Department[0], tx, nil + } + } + + return nil, tx, nil +} + +func (u *DepartmentDB) UpdateDepartmentDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.Department, returnObj ...bool) (*typescore.Department, pgx.Tx, error) { + if paramsUpdate.ID == nil { + return nil, nil, errors.New("Department obj is nil") + } + + err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { + query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameDepartments.ToString()) + query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate) + query = query.Where(squirrel.Eq{"id": paramsUpdate.ID}) + + sql, args, err := query.ToSql() + if err != nil { + return err + } + + _, err = tx.Exec(ctx, sql, args...) + if err != nil { + 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.Department{ID: paramsUpdate.ID}} + getInfoUp, _, err := u.GetDepartmentsListDB(ctx, options) + if err != nil { + return nil, nil, err + } + if len(getInfoUp) > 0 { + return getInfoUp[0], tx, nil + } + } + + return nil, tx, nil +} + +func (u *DepartmentDB) DeleteDepartmentDB(ctx context.Context, params *typescore.Department) error { + if params != nil && params.ID != nil { + query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Delete(dbcoretablenames.TableNameDepartments.ToString()). + Where(squirrel.Eq{"id": *params.ID}). + ToSql() + + if err != nil { + return err + } + + rows, err := u.pool.Query(ctx, query, args...) + if err != nil { + return err + } + defer rows.Close() + + return nil + } else { + return errors.New("department obj is nil") + } +} + +func (u *DepartmentDB) GetDepartmentByIDDB(ctx context.Context, id uint64) (*typescore.Department, error) { + deps, _, err := u.GetDepartmentsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.Department{ID: &id}, + }) + if err != nil || len(deps) == 0 { + return nil, err + } + return deps[0], nil +} diff --git a/core/db/methods/permission.go b/core/db/methods/permission.go new file mode 100644 index 0000000..7989ba2 --- /dev/null +++ b/core/db/methods/permission.go @@ -0,0 +1,258 @@ +package dbcore + +import ( + dbcoretablenames "bitrix_balancer_api/core/db/table_names" + "bitrix_balancer_api/core/typescore" + dbutils "bitrix_balancer_api/core/utilscore/db" + "context" + "errors" + "github.com/sirupsen/logrus" + + "github.com/Masterminds/squirrel" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" +) + +type PermissionDB struct { + pool *pgxpool.Pool +} + +func NewPermissionDB(pool *pgxpool.Pool) *PermissionDB { + return &PermissionDB{ + pool: pool, + } +} + +type PermissionDBI interface { + GetPermissionsListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.Permission, uint64, error) + CreatePermissionDB(ctx context.Context, tx pgx.Tx, PermissionObj *typescore.Permission, returnObj ...bool) (*typescore.Permission, pgx.Tx, error) + UpdatePermissionDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.Permission, returnObj ...bool) (*typescore.Permission, pgx.Tx, error) + DeletePermissionDB(ctx context.Context, params *typescore.Permission) error + GetUserPermissionsDB(ctx context.Context, userID uint64, action string) ([]*typescore.Permission, error) + UserCanCreateTopicDB(ctx context.Context, userID uint64, topicCode string) (bool, error) +} + +func (u *PermissionDB) GetPermissionsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.Permission, uint64, error) { + fields := dbutils.GetStructFieldsDB(&typescore.Permission{}, dbcoretablenames.TableNamePermissions.ToString()) + selectFields := append(fields, "COUNT(*) OVER() AS total_count") + + options, filter, err := dbutils.GetOptionsDB[typescore.Permission](opts...) + if err != nil { + return nil, 0, err + } + + query := dbutils.BuildSelectQuery(dbcoretablenames.TableNamePermissions.ToString(), selectFields) + query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit) + query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNamePermissions.ToString()) + query = query.OrderBy("created_at DESC") + + sql, args, err := query.ToSql() + if err != nil { + return nil, 0, err + } + + rows, err := u.pool.Query(ctx, sql, args...) + if err != nil { + return nil, 0, err + } + defer rows.Close() + + var Permissions []*typescore.Permission + var totalCount uint64 + for rows.Next() { + Permission := &typescore.Permission{} + if err := dbutils.ScanRowsToStructRows(rows, Permission, &totalCount); err != nil { + logrus.Warn("GetPermissionsListDB:ScanRowsToStructRows", err) + continue + } + Permissions = append(Permissions, Permission) + } + + return Permissions, totalCount, nil +} + +func (u *PermissionDB) CreatePermissionDB(ctx context.Context, tx pgx.Tx, PermissionObj *typescore.Permission, returnObj ...bool) (*typescore.Permission, pgx.Tx, error) { + if PermissionObj == nil { + return nil, nil, errors.New("Permission obj is nil") + } + + err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { + query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Insert(dbcoretablenames.TableNamePermissions.ToString()) + + sqlV, args, err := dbutils.GenerateInsertRequest(query, PermissionObj) + if err != nil { + return err + } + + _, err = tx.Exec(ctx, *sqlV, args...) + if err != nil { + return err + } + + return nil + }) + + if err != nil { + return nil, tx, err + } + + returnObjBool := false + if len(returnObj) > 0 { + returnObjBool = returnObj[0] + } + if returnObjBool { + Permission, _, err := u.GetPermissionsListDB(ctx, typescore.ListDbOptions{Filtering: PermissionObj}) + if err != nil { + return nil, tx, err + } + if len(Permission) > 0 { + return Permission[0], tx, nil + } + } + + return nil, tx, nil +} + +func (u *PermissionDB) UpdatePermissionDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.Permission, returnObj ...bool) (*typescore.Permission, pgx.Tx, error) { + if paramsUpdate.ID == nil { + return nil, nil, errors.New("Permission obj is nil") + } + + err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { + query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNamePermissions.ToString()) + query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate) + query = query.Where(squirrel.Eq{"id": paramsUpdate.ID}) + + sql, args, err := query.ToSql() + if err != nil { + return err + } + + _, err = tx.Exec(ctx, sql, args...) + if err != nil { + 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.Permission{ID: paramsUpdate.ID}} + getInfoUp, _, err := u.GetPermissionsListDB(ctx, options) + if err != nil { + return nil, nil, err + } + if len(getInfoUp) > 0 { + return getInfoUp[0], tx, nil + } + } + + return nil, tx, nil +} + +func (u *PermissionDB) DeletePermissionDB(ctx context.Context, params *typescore.Permission) error { + if params != nil && params.ID != nil { + query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Delete(dbcoretablenames.TableNamePermissions.ToString()). + Where(squirrel.Eq{"id": *params.ID}). + ToSql() + + if err != nil { + return err + } + + rows, err := u.pool.Query(ctx, query, args...) + if err != nil { + return err + } + defer rows.Close() + + return nil + } else { + return errors.New("permission obj is nil") + } +} + +// GetUserPermissionsDB возвращает все permissions для пользователя через его роли. +// action — фильтр: create | approve | revoke | "" (все) +func (u *PermissionDB) GetUserPermissionsDB(ctx context.Context, userID uint64, action string) ([]*typescore.Permission, error) { + // Используем алиас "p" и в GetStructFieldsDB тоже + fields := dbutils.GetStructFieldsDB(&typescore.Permission{}, "p") + + q := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Select(fields...). + From(dbcoretablenames.TableNamePermissions.ToString() + " p"). + Join(dbcoretablenames.TableNameUserRoles.ToString() + " ur ON ur.role_id = p.role_id"). + Where(squirrel.Eq{"ur.user_id": userID}) + + if action != "" { + q = q.Where(squirrel.Eq{"p.action": action}) + } + + sql, args, err := q.ToSql() + if err != nil { + return nil, err + } + + rows, err := u.pool.Query(ctx, sql, args...) + if err != nil { + return nil, err + } + defer rows.Close() + + var perms []*typescore.Permission + for rows.Next() { + p := &typescore.Permission{} + if err := dbutils.ScanRowsToStructRows(rows, p, nil); err != nil { + logrus.Warn("GetUserPermissionsDB:ScanRowsToStruct", err) + continue + } + perms = append(perms, p) + } + return perms, nil +} + +func (u *PermissionDB) UserCanCreateTopicDB(ctx context.Context, userID uint64, topicCode string) (bool, error) { + sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Select("COUNT(*)"). + From(dbcoretablenames.TableNamePermissions.ToString() + " p"). + Join(dbcoretablenames.TableNameRoles.ToString() + " r ON r.id = p.role_id"). + Join(dbcoretablenames.TableNameUserRoles.ToString() + " ur ON ur.role_id = r.id"). + LeftJoin(dbcoretablenames.TableNameApprovalTopics.ToString() + " t ON t.id = p.topic_id"). + LeftJoin(dbcoretablenames.TableNameApprovalTopicCategories.ToString() + " c ON c.id = p.topic_category_id"). + Where(squirrel.Eq{"ur.user_id": userID}). + Where(squirrel.Eq{"p.action": "create"}). + Where( + // Право на конкретную тему ИЛИ на всю категорию темы + squirrel.Or{ + squirrel.Eq{"t.code": topicCode}, + squirrel.And{ + squirrel.Eq{"p.topic_id": nil}, + squirrel.Expr(`c.id = ( + SELECT topic_category_id FROM `+ + dbcoretablenames.TableNameApprovalTopics.ToString()+ + ` WHERE code = ? + )`, topicCode), // ← используем ? вместо ручной подстановки $N + }, + }, + ). + ToSql() + if err != nil { + return false, err + } + + var count int + if err := u.pool.QueryRow(ctx, sql, args...).Scan(&count); err != nil { + return false, err + } + return count > 0, nil +} diff --git a/core/db/methods/role.go b/core/db/methods/role.go new file mode 100644 index 0000000..6332fdd --- /dev/null +++ b/core/db/methods/role.go @@ -0,0 +1,192 @@ +package dbcore + +import ( + dbcoretablenames "bitrix_balancer_api/core/db/table_names" + "bitrix_balancer_api/core/typescore" + dbutils "bitrix_balancer_api/core/utilscore/db" + "context" + "errors" + "github.com/sirupsen/logrus" + + "github.com/Masterminds/squirrel" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" +) + +type RoleDB struct { + pool *pgxpool.Pool +} + +func NewRoleDB(pool *pgxpool.Pool) *RoleDB { + return &RoleDB{ + pool: pool, + } +} + +type RoleDBI interface { + GetRolesListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.Role, uint64, error) + 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) { + fields := dbutils.GetStructFieldsDB(&typescore.Role{}, dbcoretablenames.TableNameRoles.ToString()) + selectFields := append(fields, "COUNT(*) OVER() AS total_count") + + options, filter, err := dbutils.GetOptionsDB[typescore.Role](opts...) + if err != nil { + return nil, 0, err + } + + query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameRoles.ToString(), selectFields) + query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit) + query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameRoles.ToString()) + query = query.OrderBy("created_at DESC") + + sql, args, err := query.ToSql() + if err != nil { + return nil, 0, err + } + + rows, err := u.pool.Query(ctx, sql, args...) + if err != nil { + return nil, 0, err + } + defer rows.Close() + + var Roles []*typescore.Role + var totalCount uint64 + for rows.Next() { + Role := &typescore.Role{} + if err := dbutils.ScanRowsToStructRows(rows, Role, &totalCount); err != nil { + logrus.Warn("GetRolesListDB:ScanRowsToStructRows", err) + continue + } + Roles = append(Roles, Role) + } + + return Roles, totalCount, nil +} + +func (u *RoleDB) CreateRoleDB(ctx context.Context, tx pgx.Tx, RoleObj *typescore.Role, returnObj ...bool) (*typescore.Role, pgx.Tx, error) { + if RoleObj == nil { + return nil, nil, errors.New("Role obj is nil") + } + + err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { + query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Insert(dbcoretablenames.TableNameRoles.ToString()) + + sqlV, args, err := dbutils.GenerateInsertRequest(query, RoleObj) + if err != nil { + return err + } + + _, err = tx.Exec(ctx, *sqlV, args...) + if err != nil { + return err + } + + return nil + }) + + if err != nil { + return nil, tx, err + } + + returnObjBool := false + if len(returnObj) > 0 { + returnObjBool = returnObj[0] + } + if returnObjBool { + Role, _, err := u.GetRolesListDB(ctx, typescore.ListDbOptions{Filtering: RoleObj}) + if err != nil { + return nil, tx, err + } + if len(Role) > 0 { + return Role[0], tx, nil + } + } + + return nil, tx, nil +} + +func (u *RoleDB) UpdateRoleDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.Role, returnObj ...bool) (*typescore.Role, pgx.Tx, error) { + if paramsUpdate.ID == nil { + return nil, nil, errors.New("Role obj is nil") + } + + err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { + query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameRoles.ToString()) + query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate) + query = query.Where(squirrel.Eq{"id": paramsUpdate.ID}) + + sql, args, err := query.ToSql() + if err != nil { + return err + } + + _, err = tx.Exec(ctx, sql, args...) + if err != nil { + 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.Role{ID: paramsUpdate.ID}} + getInfoUp, _, err := u.GetRolesListDB(ctx, options) + if err != nil { + return nil, nil, err + } + if len(getInfoUp) > 0 { + return getInfoUp[0], tx, nil + } + } + + return nil, tx, nil +} + +func (u *RoleDB) DeleteRoleDB(ctx context.Context, params *typescore.Role) error { + if params != nil && params.ID != nil { + query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Delete(dbcoretablenames.TableNameRoles.ToString()). + Where(squirrel.Eq{"id": *params.ID}). + ToSql() + + if err != nil { + return err + } + + rows, err := u.pool.Query(ctx, query, args...) + if err != nil { + return err + } + defer rows.Close() + + return nil + } else { + 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/methods/suggestion.go b/core/db/methods/suggestion.go new file mode 100644 index 0000000..60fd8ee --- /dev/null +++ b/core/db/methods/suggestion.go @@ -0,0 +1,192 @@ +package dbcore + +import ( + dbcoretablenames "bitrix_balancer_api/core/db/table_names" + "bitrix_balancer_api/core/typescore" + dbutils "bitrix_balancer_api/core/utilscore/db" + "context" + "errors" + "github.com/sirupsen/logrus" + + "github.com/Masterminds/squirrel" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" +) + +type SuggestionDB struct { + pool *pgxpool.Pool +} + +func NewSuggestionDB(pool *pgxpool.Pool) *SuggestionDB { + return &SuggestionDB{ + pool: pool, + } +} + +type SuggestionDBI interface { + GetSuggestionsListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.Suggestion, uint64, error) + CreateSuggestionDB(ctx context.Context, tx pgx.Tx, SuggestionObj *typescore.Suggestion, returnObj ...bool) (*typescore.Suggestion, pgx.Tx, error) + UpdateSuggestionDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.Suggestion, returnObj ...bool) (*typescore.Suggestion, pgx.Tx, error) + DeleteSuggestionDB(ctx context.Context, params *typescore.Suggestion) error + GetSuggestionByIDDB(ctx context.Context, id uint64) (*typescore.Suggestion, error) +} + +func (u *SuggestionDB) GetSuggestionsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.Suggestion, uint64, error) { + fields := dbutils.GetStructFieldsDB(&typescore.Suggestion{}, dbcoretablenames.TableNameSuggestions.ToString()) + selectFields := append(fields, "COUNT(*) OVER() AS total_count") + + options, filter, err := dbutils.GetOptionsDB[typescore.Suggestion](opts...) + if err != nil { + return nil, 0, err + } + + query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameSuggestions.ToString(), selectFields) + query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit) + query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameSuggestions.ToString()) + query = query.OrderBy("created_at DESC") + + sql, args, err := query.ToSql() + if err != nil { + return nil, 0, err + } + + rows, err := u.pool.Query(ctx, sql, args...) + if err != nil { + return nil, 0, err + } + defer rows.Close() + + var Suggestions []*typescore.Suggestion + var totalCount uint64 + for rows.Next() { + Suggestion := &typescore.Suggestion{} + if err := dbutils.ScanRowsToStructRows(rows, Suggestion, &totalCount); err != nil { + logrus.Warn("GetSuggestionsListDB:ScanRowsToStructRows", err) + continue + } + Suggestions = append(Suggestions, Suggestion) + } + + return Suggestions, totalCount, nil +} + +func (u *SuggestionDB) CreateSuggestionDB(ctx context.Context, tx pgx.Tx, SuggestionObj *typescore.Suggestion, returnObj ...bool) (*typescore.Suggestion, pgx.Tx, error) { + if SuggestionObj == nil { + return nil, nil, errors.New("Suggestion obj is nil") + } + + err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { + query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Insert(dbcoretablenames.TableNameSuggestions.ToString()) + + sqlV, args, err := dbutils.GenerateInsertRequest(query, SuggestionObj) + if err != nil { + return err + } + + _, err = tx.Exec(ctx, *sqlV, args...) + if err != nil { + return err + } + + return nil + }) + + if err != nil { + return nil, tx, err + } + + returnObjBool := false + if len(returnObj) > 0 { + returnObjBool = returnObj[0] + } + if returnObjBool { + Suggestion, _, err := u.GetSuggestionsListDB(ctx, typescore.ListDbOptions{Filtering: SuggestionObj}) + if err != nil { + return nil, tx, err + } + if len(Suggestion) > 0 { + return Suggestion[0], tx, nil + } + } + + return nil, tx, nil +} + +func (u *SuggestionDB) UpdateSuggestionDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.Suggestion, returnObj ...bool) (*typescore.Suggestion, pgx.Tx, error) { + if paramsUpdate.ID == nil { + return nil, nil, errors.New("Suggestion obj is nil") + } + + err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { + query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameSuggestions.ToString()) + query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate) + query = query.Where(squirrel.Eq{"id": paramsUpdate.ID}) + + sql, args, err := query.ToSql() + if err != nil { + return err + } + + _, err = tx.Exec(ctx, sql, args...) + if err != nil { + 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.Suggestion{ID: paramsUpdate.ID}} + getInfoUp, _, err := u.GetSuggestionsListDB(ctx, options) + if err != nil { + return nil, nil, err + } + if len(getInfoUp) > 0 { + return getInfoUp[0], tx, nil + } + } + + return nil, tx, nil +} + +func (u *SuggestionDB) DeleteSuggestionDB(ctx context.Context, params *typescore.Suggestion) error { + if params != nil && params.ID != nil { + query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Delete(dbcoretablenames.TableNameSuggestions.ToString()). + Where(squirrel.Eq{"id": *params.ID}). + ToSql() + + if err != nil { + return err + } + + rows, err := u.pool.Query(ctx, query, args...) + if err != nil { + return err + } + defer rows.Close() + + return nil + } else { + return errors.New("Suggestion obj is nil") + } +} + +func (u *SuggestionDB) GetSuggestionByIDDB(ctx context.Context, id uint64) (*typescore.Suggestion, error) { + deps, _, err := u.GetSuggestionsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.Suggestion{ID: &id}, + }) + if err != nil || len(deps) == 0 { + return nil, err + } + return deps[0], nil +} diff --git a/core/db/methods/suggestion_message.go b/core/db/methods/suggestion_message.go new file mode 100644 index 0000000..063a2d9 --- /dev/null +++ b/core/db/methods/suggestion_message.go @@ -0,0 +1,192 @@ +package dbcore + +import ( + dbcoretablenames "bitrix_balancer_api/core/db/table_names" + "bitrix_balancer_api/core/typescore" + dbutils "bitrix_balancer_api/core/utilscore/db" + "context" + "errors" + "github.com/sirupsen/logrus" + + "github.com/Masterminds/squirrel" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" +) + +type SuggestionMessageDB struct { + pool *pgxpool.Pool +} + +func NewSuggestionMessageDB(pool *pgxpool.Pool) *SuggestionMessageDB { + return &SuggestionMessageDB{ + pool: pool, + } +} + +type SuggestionMessageDBI interface { + GetSuggestionMessagesListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.SuggestionMessage, uint64, error) + CreateSuggestionMessageDB(ctx context.Context, tx pgx.Tx, SuggestionMessageObj *typescore.SuggestionMessage, returnObj ...bool) (*typescore.SuggestionMessage, pgx.Tx, error) + UpdateSuggestionMessageDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.SuggestionMessage, returnObj ...bool) (*typescore.SuggestionMessage, pgx.Tx, error) + DeleteSuggestionMessageDB(ctx context.Context, params *typescore.SuggestionMessage) error + GetSuggestionMessageByIDDB(ctx context.Context, id uint64) (*typescore.SuggestionMessage, error) +} + +func (u *SuggestionMessageDB) GetSuggestionMessagesListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.SuggestionMessage, uint64, error) { + fields := dbutils.GetStructFieldsDB(&typescore.SuggestionMessage{}, dbcoretablenames.TableNameSuggestionMessages.ToString()) + selectFields := append(fields, "COUNT(*) OVER() AS total_count") + + options, filter, err := dbutils.GetOptionsDB[typescore.SuggestionMessage](opts...) + if err != nil { + return nil, 0, err + } + + query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameSuggestionMessages.ToString(), selectFields) + query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit) + query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameSuggestionMessages.ToString()) + query = query.OrderBy("created_at DESC") + + sql, args, err := query.ToSql() + if err != nil { + return nil, 0, err + } + + rows, err := u.pool.Query(ctx, sql, args...) + if err != nil { + return nil, 0, err + } + defer rows.Close() + + var SuggestionMessages []*typescore.SuggestionMessage + var totalCount uint64 + for rows.Next() { + SuggestionMessage := &typescore.SuggestionMessage{} + if err := dbutils.ScanRowsToStructRows(rows, SuggestionMessage, &totalCount); err != nil { + logrus.Warn("GetSuggestionMessagesListDB:ScanRowsToStructRows", err) + continue + } + SuggestionMessages = append(SuggestionMessages, SuggestionMessage) + } + + return SuggestionMessages, totalCount, nil +} + +func (u *SuggestionMessageDB) CreateSuggestionMessageDB(ctx context.Context, tx pgx.Tx, SuggestionMessageObj *typescore.SuggestionMessage, returnObj ...bool) (*typescore.SuggestionMessage, pgx.Tx, error) { + if SuggestionMessageObj == nil { + return nil, nil, errors.New("SuggestionMessage obj is nil") + } + + err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { + query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Insert(dbcoretablenames.TableNameSuggestionMessages.ToString()) + + sqlV, args, err := dbutils.GenerateInsertRequest(query, SuggestionMessageObj) + if err != nil { + return err + } + + _, err = tx.Exec(ctx, *sqlV, args...) + if err != nil { + return err + } + + return nil + }) + + if err != nil { + return nil, tx, err + } + + returnObjBool := false + if len(returnObj) > 0 { + returnObjBool = returnObj[0] + } + if returnObjBool { + SuggestionMessage, _, err := u.GetSuggestionMessagesListDB(ctx, typescore.ListDbOptions{Filtering: SuggestionMessageObj}) + if err != nil { + return nil, tx, err + } + if len(SuggestionMessage) > 0 { + return SuggestionMessage[0], tx, nil + } + } + + return nil, tx, nil +} + +func (u *SuggestionMessageDB) UpdateSuggestionMessageDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.SuggestionMessage, returnObj ...bool) (*typescore.SuggestionMessage, pgx.Tx, error) { + if paramsUpdate.ID == nil { + return nil, nil, errors.New("SuggestionMessage obj is nil") + } + + err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { + query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameSuggestionMessages.ToString()) + query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate) + query = query.Where(squirrel.Eq{"id": paramsUpdate.ID}) + + sql, args, err := query.ToSql() + if err != nil { + return err + } + + _, err = tx.Exec(ctx, sql, args...) + if err != nil { + 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.SuggestionMessage{ID: paramsUpdate.ID}} + getInfoUp, _, err := u.GetSuggestionMessagesListDB(ctx, options) + if err != nil { + return nil, nil, err + } + if len(getInfoUp) > 0 { + return getInfoUp[0], tx, nil + } + } + + return nil, tx, nil +} + +func (u *SuggestionMessageDB) DeleteSuggestionMessageDB(ctx context.Context, params *typescore.SuggestionMessage) error { + if params != nil && params.ID != nil { + query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Delete(dbcoretablenames.TableNameSuggestionMessages.ToString()). + Where(squirrel.Eq{"id": *params.ID}). + ToSql() + + if err != nil { + return err + } + + rows, err := u.pool.Query(ctx, query, args...) + if err != nil { + return err + } + defer rows.Close() + + return nil + } else { + return errors.New("SuggestionMessage obj is nil") + } +} + +func (u *SuggestionMessageDB) GetSuggestionMessageByIDDB(ctx context.Context, id uint64) (*typescore.SuggestionMessage, error) { + deps, _, err := u.GetSuggestionMessagesListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.SuggestionMessage{ID: &id}, + }) + if err != nil || len(deps) == 0 { + return nil, err + } + return deps[0], nil +} diff --git a/core/db/methods/user.go b/core/db/methods/user.go new file mode 100644 index 0000000..82347e9 --- /dev/null +++ b/core/db/methods/user.go @@ -0,0 +1,392 @@ +package dbcore + +import ( + dbcoretablenames "bitrix_balancer_api/core/db/table_names" + "bitrix_balancer_api/core/typescore" + dbutils "bitrix_balancer_api/core/utilscore/db" + "context" + "errors" + "github.com/sirupsen/logrus" + + "github.com/Masterminds/squirrel" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" +) + +type UserDB struct { + pool *pgxpool.Pool +} + +func NewUserDB(pool *pgxpool.Pool) *UserDB { + return &UserDB{ + pool: pool, + } +} + +type UserDBI interface { + GetUsersListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.User, uint64, error) + CreateUserDB(ctx context.Context, tx pgx.Tx, UserObj *typescore.User, returnObj ...bool) (*typescore.User, pgx.Tx, error) + UpdateUserDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.User, returnObj ...bool) (*typescore.User, pgx.Tx, error) + DeleteUserDB(ctx context.Context, params *typescore.User) error + + GetUserByTelegramIDDB(ctx context.Context, telegramID int64) (*typescore.User, error) + GetUserByIDDB(ctx context.Context, id uint64) (*typescore.User, error) + GetDirectorsDB(ctx context.Context) ([]*typescore.User, error) + IsDirectorDB(ctx context.Context, userID uint64) (bool, error) + IsApproverDB(ctx context.Context, userID uint64) (bool, error) + IsExecutorDB(ctx context.Context, userID uint64) (bool, error) + GetObserversForCategoryDB(ctx context.Context, categoryCode string) ([]*typescore.User, error) + GetUsersByRoleCodeDB(ctx context.Context, roleCode string) ([]*typescore.User, error) +} + +func (u *UserDB) GetUsersListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.User, uint64, error) { + fields := dbutils.GetStructFieldsDB(&typescore.User{}, dbcoretablenames.TableNameUsers.ToString()) + selectFields := append(fields, "COUNT(*) OVER() AS total_count") + + options, filter, err := dbutils.GetOptionsDB[typescore.User](opts...) + if err != nil { + return nil, 0, err + } + + query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameUsers.ToString(), selectFields) + query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit) + query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameUsers.ToString()) + query = query.OrderBy("created_at DESC") + + sql, args, err := query.ToSql() + if err != nil { + return nil, 0, err + } + + rows, err := u.pool.Query(ctx, sql, args...) + if err != nil { + return nil, 0, err + } + defer rows.Close() + + var Users []*typescore.User + var totalCount uint64 + for rows.Next() { + User := &typescore.User{} + if err := dbutils.ScanRowsToStructRows(rows, User, &totalCount); err != nil { + logrus.Warn("GetUsersListDB:ScanRowsToStructRows", err) + continue + } + Users = append(Users, User) + } + + return Users, totalCount, nil +} + +func (u *UserDB) CreateUserDB(ctx context.Context, tx pgx.Tx, UserObj *typescore.User, returnObj ...bool) (*typescore.User, pgx.Tx, error) { + if UserObj == nil { + return nil, nil, errors.New("user obj is nil") + } + + err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { + query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Insert(dbcoretablenames.TableNameUsers.ToString()) + + sqlV, args, err := dbutils.GenerateInsertRequest(query, UserObj) + if err != nil { + return err + } + + _, err = tx.Exec(ctx, *sqlV, args...) + if err != nil { + return err + } + + return nil + }) + + if err != nil { + return nil, tx, err + } + + returnObjBool := false + if len(returnObj) > 0 { + returnObjBool = returnObj[0] + } + if returnObjBool { + User, _, err := u.GetUsersListDB(ctx, typescore.ListDbOptions{Filtering: UserObj}) + if err != nil { + return nil, tx, err + } + if len(User) > 0 { + return User[0], tx, nil + } + } + + return nil, tx, nil +} + +func (u *UserDB) UpdateUserDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.User, returnObj ...bool) (*typescore.User, pgx.Tx, error) { + if paramsUpdate.ID == nil { + return nil, nil, errors.New("user obj is nil") + } + + err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { + query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameUsers.ToString()) + query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate) + query = query.Where(squirrel.Eq{"id": paramsUpdate.ID}) + + sql, args, err := query.ToSql() + if err != nil { + return err + } + + _, err = tx.Exec(ctx, sql, args...) + if err != nil { + 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.User{ID: paramsUpdate.ID}} + getInfoUp, _, err := u.GetUsersListDB(ctx, options) + if err != nil { + return nil, nil, err + } + if len(getInfoUp) > 0 { + return getInfoUp[0], tx, nil + } + } + + return nil, tx, nil +} + +func (u *UserDB) DeleteUserDB(ctx context.Context, params *typescore.User) error { + if params != nil && params.ID != nil { + query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Delete(dbcoretablenames.TableNameUsers.ToString()). + Where(squirrel.Eq{"id": *params.ID}). + ToSql() + + if err != nil { + return err + } + + rows, err := u.pool.Query(ctx, query, args...) + if err != nil { + return err + } + defer rows.Close() + + return nil + } else { + return errors.New("user obj is nil") + } +} + +func (u *UserDB) GetUserByTelegramIDDB(ctx context.Context, telegramID int64) (*typescore.User, error) { + users, _, err := u.GetUsersListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.User{TelegramID: &telegramID}, + }) + if err != nil { + return nil, err + } + if len(users) == 0 { + return nil, nil + } + return users[0], nil +} + +func (u *UserDB) GetUserByIDDB(ctx context.Context, id uint64) (*typescore.User, error) { + users, _, err := u.GetUsersListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.User{ID: &id}, + }) + if err != nil { + return nil, err + } + if len(users) == 0 { + return nil, nil + } + return users[0], nil +} + +// GetDirectorsDB возвращает всех пользователей у которых есть роль с is_director = true. +func (u *UserDB) GetDirectorsDB(ctx context.Context) ([]*typescore.User, error) { + sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Select("DISTINCT u.*"). + From(dbcoretablenames.TableNameUsers.ToString() + " u"). + Join(dbcoretablenames.TableNameUserRoles.ToString() + " ur ON ur.user_id = u.id"). + Join(dbcoretablenames.TableNameRoles.ToString() + " r ON r.id = ur.role_id"). + Where(squirrel.Eq{"r.is_director": true}). + Where(squirrel.Eq{"u.is_blocked": false}). + ToSql() + if err != nil { + return nil, err + } + + rows, err := u.pool.Query(ctx, sql, args...) + if err != nil { + return nil, err + } + defer rows.Close() + + var users []*typescore.User + for rows.Next() { + user := &typescore.User{} + if err := dbutils.ScanRowsToStructRows(rows, user, nil, nil); err != nil { + logrus.Warn("GetDirectorsDB:ScanRowsToStruct", err) + continue + } + users = append(users, user) + } + return users, nil +} + +// IsDirectorDB проверяет наличие директорской роли у конкретного пользователя. +func (u *UserDB) IsDirectorDB(ctx context.Context, userID uint64) (bool, error) { + sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Select("COUNT(*)"). + From(dbcoretablenames.TableNameUserRoles.ToString() + " ur"). + Join(dbcoretablenames.TableNameRoles.ToString() + " r ON r.id = ur.role_id"). + Where(squirrel.Eq{"ur.user_id": userID}). + Where(squirrel.Eq{"r.is_director": true}). + ToSql() + if err != nil { + return false, err + } + + var count int + if err := u.pool.QueryRow(ctx, sql, args...).Scan(&count); err != nil { + return false, err + } + return count > 0, nil +} + +// IsApproverDB проверяет есть ли у пользователя роль с is_approver = true +func (u *UserDB) IsApproverDB(ctx context.Context, userID uint64) (bool, error) { + sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Select("COUNT(*)"). + From(dbcoretablenames.TableNameUserRoles.ToString() + " ur"). + Join(dbcoretablenames.TableNameRoles.ToString() + " r ON r.id = ur.role_id"). + Where(squirrel.Eq{"ur.user_id": userID}). + Where(squirrel.Eq{"r.is_approver": true}). + ToSql() + if err != nil { + return false, err + } + + var count int + if err := u.pool.QueryRow(ctx, sql, args...).Scan(&count); err != nil { + return false, err + } + return count > 0, nil +} + +func (u *UserDB) IsObserverDB(ctx context.Context, userID uint64) (bool, error) { + sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Select("COUNT(*)"). + From(dbcoretablenames.TableNameUserRoles.ToString() + " ur"). + Join(dbcoretablenames.TableNameRoles.ToString() + " r ON r.id = ur.role_id"). + Where(squirrel.Eq{"ur.user_id": userID}). + Where(squirrel.Eq{"r.is_observer": true}). + ToSql() + if err != nil { + return false, err + } + var count int + if err := u.pool.QueryRow(ctx, sql, args...).Scan(&count); err != nil { + return false, err + } + return count > 0, nil +} + +func (u *UserDB) IsExecutorDB(ctx context.Context, userID uint64) (bool, error) { + sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Select("COUNT(*)"). + From(dbcoretablenames.TableNameUserRoles.ToString() + " ur"). + Join(dbcoretablenames.TableNameRoles.ToString() + " r ON r.id = ur.role_id"). + Where(squirrel.Eq{"ur.user_id": userID}). + Where(squirrel.Eq{"r.is_executor": true}). + ToSql() + if err != nil { + return false, err + } + + var count int + if err := u.pool.QueryRow(ctx, sql, args...).Scan(&count); err != nil { + return false, err + } + return count > 0, nil +} + +// GetObserversForCategoryDB — пользователи с ролью наблюдателя и правом observe на категорию. +func (u *UserDB) GetObserversForCategoryDB(ctx context.Context, categoryCode string) ([]*typescore.User, error) { + sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Select("DISTINCT u.*"). + From(dbcoretablenames.TableNameUsers.ToString() + " u"). + Join(dbcoretablenames.TableNameUserRoles.ToString() + " ur ON ur.user_id = u.id"). + Join(dbcoretablenames.TableNameRoles.ToString() + " r ON r.id = ur.role_id"). + Join(dbcoretablenames.TableNamePermissions.ToString() + " p ON p.role_id = r.id"). + Join(dbcoretablenames.TableNameApprovalTopicCategories.ToString() + " c ON c.id = p.topic_category_id"). + Where(squirrel.Eq{"r.is_observer": true}). + Where(squirrel.Eq{"p.action": "observe"}). + Where(squirrel.Eq{"c.code": categoryCode}). + ToSql() + if err != nil { + return nil, err + } + + rows, err := u.pool.Query(ctx, sql, args...) + if err != nil { + return nil, err + } + defer rows.Close() + + var result []*typescore.User + for rows.Next() { + usr := &typescore.User{} + if err := dbutils.ScanRowsToStructRows(rows, usr, nil); err != nil { + logrus.Warn("GetObserversForCategoryDB:ScanRowsToStruct", err) + continue + } + result = append(result, usr) + } + return result, nil +} + +func (u *UserDB) GetUsersByRoleCodeDB(ctx context.Context, roleCode string) ([]*typescore.User, error) { + sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Select("DISTINCT u.*"). + From(dbcoretablenames.TableNameUsers.ToString() + " u"). + Join(dbcoretablenames.TableNameUserRoles.ToString() + " ur ON ur.user_id = u.id"). + Join(dbcoretablenames.TableNameRoles.ToString() + " r ON r.id = ur.role_id"). + Where(squirrel.Eq{"r.code": roleCode}). + Where(squirrel.Eq{"u.is_blocked": false}). + OrderBy("u.full_name ASC"). + ToSql() + if err != nil { + return nil, err + } + + rows, err := u.pool.Query(ctx, sql, args...) + if err != nil { + return nil, err + } + defer rows.Close() + + var users []*typescore.User + for rows.Next() { + user := &typescore.User{} + if err := dbutils.ScanRowsToStructRows(rows, user, nil); err != nil { + logrus.Warn("GetUsersByRoleCodeDB:ScanRowsToStruct", err) + continue + } + users = append(users, user) + } + return users, nil +} diff --git a/core/db/methods/user_hierarchy.go b/core/db/methods/user_hierarchy.go new file mode 100644 index 0000000..b1ecd4b --- /dev/null +++ b/core/db/methods/user_hierarchy.go @@ -0,0 +1,238 @@ +package dbcore + +import ( + dbcoretablenames "bitrix_balancer_api/core/db/table_names" + "bitrix_balancer_api/core/typescore" + dbutils "bitrix_balancer_api/core/utilscore/db" + "context" + "errors" + "github.com/sirupsen/logrus" + + "github.com/Masterminds/squirrel" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" +) + +type UserHierarchyDB struct { + pool *pgxpool.Pool +} + +func NewUserHierarchyDB(pool *pgxpool.Pool) *UserHierarchyDB { + return &UserHierarchyDB{ + pool: pool, + } +} + +type UserHierarchyDBI interface { + GetUserHierarchyListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.UserHierarchy, uint64, error) + CreateUserHierarchyDB(ctx context.Context, tx pgx.Tx, UserHierarchyObj *typescore.UserHierarchy, returnObj ...bool) (*typescore.UserHierarchy, pgx.Tx, error) + UpdateUserHierarchyDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.UserHierarchy, returnObj ...bool) (*typescore.UserHierarchy, pgx.Tx, error) + DeleteUserHierarchyDB(ctx context.Context, params *typescore.UserHierarchy) error + + GetApproversDB(ctx context.Context, subordinateID uint64, departmentID uint64) ([]*typescore.User, error) +} + +func (u *UserHierarchyDB) GetUserHierarchyListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.UserHierarchy, uint64, error) { + fields := dbutils.GetStructFieldsDB(&typescore.UserHierarchy{}, dbcoretablenames.TableNameUserHierarchy.ToString()) + selectFields := append(fields, "COUNT(*) OVER() AS total_count") + + options, filter, err := dbutils.GetOptionsDB[typescore.UserHierarchy](opts...) + if err != nil { + return nil, 0, err + } + + query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameUserHierarchy.ToString(), selectFields) + query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit) + query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameUserHierarchy.ToString()) + query = query.OrderBy("created_at DESC") + + sql, args, err := query.ToSql() + if err != nil { + return nil, 0, err + } + + rows, err := u.pool.Query(ctx, sql, args...) + if err != nil { + return nil, 0, err + } + defer rows.Close() + + var UserHierarchys []*typescore.UserHierarchy + var totalCount uint64 + for rows.Next() { + UserHierarchy := &typescore.UserHierarchy{} + if err := dbutils.ScanRowsToStructRows(rows, UserHierarchy, &totalCount); err != nil { + logrus.Warn("GetUserHierarchysListDB:ScanRowsToStructRows", err) + continue + } + UserHierarchys = append(UserHierarchys, UserHierarchy) + } + + return UserHierarchys, totalCount, nil +} + +func (u *UserHierarchyDB) CreateUserHierarchyDB(ctx context.Context, tx pgx.Tx, UserHierarchyObj *typescore.UserHierarchy, returnObj ...bool) (*typescore.UserHierarchy, pgx.Tx, error) { + if UserHierarchyObj == nil { + return nil, nil, errors.New("UserHierarchy obj is nil") + } + + err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { + query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Insert(dbcoretablenames.TableNameUserHierarchy.ToString()) + + sqlV, args, err := dbutils.GenerateInsertRequest(query, UserHierarchyObj) + if err != nil { + return err + } + + _, err = tx.Exec(ctx, *sqlV, args...) + if err != nil { + return err + } + + return nil + }) + + if err != nil { + return nil, tx, err + } + + returnObjBool := false + if len(returnObj) > 0 { + returnObjBool = returnObj[0] + } + if returnObjBool { + UserHierarchy, _, err := u.GetUserHierarchyListDB(ctx, typescore.ListDbOptions{Filtering: UserHierarchyObj}) + if err != nil { + return nil, tx, err + } + if len(UserHierarchy) > 0 { + return UserHierarchy[0], tx, nil + } + } + + return nil, tx, nil +} + +func (u *UserHierarchyDB) UpdateUserHierarchyDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.UserHierarchy, returnObj ...bool) (*typescore.UserHierarchy, pgx.Tx, error) { + if paramsUpdate.ID == nil { + return nil, nil, errors.New("UserHierarchy obj is nil") + } + + err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { + query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameUserHierarchy.ToString()) + query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate) + query = query.Where(squirrel.Eq{"id": paramsUpdate.ID}) + + sql, args, err := query.ToSql() + if err != nil { + return err + } + + _, err = tx.Exec(ctx, sql, args...) + if err != nil { + 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.UserHierarchy{ID: paramsUpdate.ID}} + getInfoUp, _, err := u.GetUserHierarchyListDB(ctx, options) + if err != nil { + return nil, nil, err + } + if len(getInfoUp) > 0 { + return getInfoUp[0], tx, nil + } + } + + return nil, tx, nil +} + +func (u *UserHierarchyDB) DeleteUserHierarchyDB(ctx context.Context, params *typescore.UserHierarchy) error { + if params != nil && params.ID != nil { + query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Delete(dbcoretablenames.TableNameUserHierarchy.ToString()). + Where(squirrel.Eq{"id": *params.ID}). + ToSql() + + if err != nil { + return err + } + + rows, err := u.pool.Query(ctx, query, args...) + if err != nil { + return err + } + defer rows.Close() + + return nil + } else { + return errors.New("userHierarchy obj is nil") + } +} + +func (u *UserHierarchyDB) GetApproversDB(ctx context.Context, subordinateID, departmentID, topicID, categoryID uint64) ([]*typescore.User, error) { + rawSQL := ` + WITH ranked AS ( + SELECT + uh.approver_id, + uh.priority, + CASE + WHEN uh.topic_id = $3 THEN 1 + WHEN uh.topic_category_id = $4 THEN 2 + WHEN uh.topic_id IS NULL + AND uh.topic_category_id IS NULL THEN 3 + END AS specificity + FROM user_hierarchy uh + WHERE uh.subordinate_id = $1 + AND uh.department_id = $2 + AND ( + uh.topic_id = $3 + OR uh.topic_category_id = $4 + OR (uh.topic_id IS NULL AND uh.topic_category_id IS NULL) + ) + ), + best AS ( + -- берём только уровень с наивысшей специфичностью + SELECT MIN(specificity) AS min_spec FROM ranked + ) + SELECT u.* + FROM ranked r + JOIN best b ON r.specificity = b.min_spec + JOIN users u ON u.id = r.approver_id + ORDER BY r.priority ASC + ` + + rows, err := u.pool.Query(ctx, rawSQL, + subordinateID, + departmentID, + topicID, + categoryID, + ) + if err != nil { + return nil, err + } + defer rows.Close() + + var result []*typescore.User + for rows.Next() { + usr := &typescore.User{} + if err := dbutils.ScanRowsToStructRows(rows, usr, nil); err != nil { + logrus.Warn("GetApproversDB:ScanRowsToStructRows", err) + continue + } + result = append(result, usr) + } + return result, nil +} diff --git a/core/db/methods/user_role.go b/core/db/methods/user_role.go new file mode 100644 index 0000000..6266924 --- /dev/null +++ b/core/db/methods/user_role.go @@ -0,0 +1,181 @@ +package dbcore + +import ( + dbcoretablenames "bitrix_balancer_api/core/db/table_names" + "bitrix_balancer_api/core/typescore" + dbutils "bitrix_balancer_api/core/utilscore/db" + "context" + "errors" + "github.com/sirupsen/logrus" + + "github.com/Masterminds/squirrel" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" +) + +type UserRoleDB struct { + pool *pgxpool.Pool +} + +func NewUserRoleDB(pool *pgxpool.Pool) *UserRoleDB { + return &UserRoleDB{ + pool: pool, + } +} + +type UserRoleDBI interface { + GetUserRolesListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.UserRole, uint64, error) + CreateUserRoleDB(ctx context.Context, tx pgx.Tx, UserRoleObj *typescore.UserRole, returnObj ...bool) (*typescore.UserRole, pgx.Tx, error) + UpdateUserRoleDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.UserRole, returnObj ...bool) (*typescore.UserRole, pgx.Tx, error) + DeleteUserRoleDB(ctx context.Context, params *typescore.UserRole) error +} + +func (u *UserRoleDB) GetUserRolesListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.UserRole, uint64, error) { + fields := dbutils.GetStructFieldsDB(&typescore.UserRole{}, dbcoretablenames.TableNameUserRoles.ToString()) + selectFields := append(fields, "COUNT(*) OVER() AS total_count") + + options, filter, err := dbutils.GetOptionsDB[typescore.UserRole](opts...) + if err != nil { + return nil, 0, err + } + + query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameUserRoles.ToString(), selectFields) + query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit) + query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameUserRoles.ToString()) + query = query.OrderBy("created_at DESC") + + sql, args, err := query.ToSql() + if err != nil { + return nil, 0, err + } + + rows, err := u.pool.Query(ctx, sql, args...) + if err != nil { + return nil, 0, err + } + defer rows.Close() + + var UserRoles []*typescore.UserRole + var totalCount uint64 + for rows.Next() { + UserRole := &typescore.UserRole{} + if err := dbutils.ScanRowsToStructRows(rows, UserRole, &totalCount); err != nil { + logrus.Warn("GetUserRolesListDB:ScanRowsToStructRows", err) + continue + } + UserRoles = append(UserRoles, UserRole) + } + + return UserRoles, totalCount, nil +} + +func (u *UserRoleDB) CreateUserRoleDB(ctx context.Context, tx pgx.Tx, UserRoleObj *typescore.UserRole, returnObj ...bool) (*typescore.UserRole, pgx.Tx, error) { + if UserRoleObj == nil { + return nil, nil, errors.New("UserRole obj is nil") + } + + err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { + query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Insert(dbcoretablenames.TableNameUserRoles.ToString()) + + sqlV, args, err := dbutils.GenerateInsertRequest(query, UserRoleObj) + if err != nil { + return err + } + + _, err = tx.Exec(ctx, *sqlV, args...) + if err != nil { + return err + } + + return nil + }) + + if err != nil { + return nil, tx, err + } + + returnObjBool := false + if len(returnObj) > 0 { + returnObjBool = returnObj[0] + } + if returnObjBool { + UserRole, _, err := u.GetUserRolesListDB(ctx, typescore.ListDbOptions{Filtering: UserRoleObj}) + if err != nil { + return nil, tx, err + } + if len(UserRole) > 0 { + return UserRole[0], tx, nil + } + } + + return nil, tx, nil +} + +func (u *UserRoleDB) UpdateUserRoleDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.UserRole, returnObj ...bool) (*typescore.UserRole, pgx.Tx, error) { + if paramsUpdate.ID == nil { + return nil, nil, errors.New("UserRole obj is nil") + } + + err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { + query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameUserRoles.ToString()) + query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate) + query = query.Where(squirrel.Eq{"id": paramsUpdate.ID}) + + sql, args, err := query.ToSql() + if err != nil { + return err + } + + _, err = tx.Exec(ctx, sql, args...) + if err != nil { + 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.UserRole{ID: paramsUpdate.ID}} + getInfoUp, _, err := u.GetUserRolesListDB(ctx, options) + if err != nil { + return nil, nil, err + } + if len(getInfoUp) > 0 { + return getInfoUp[0], tx, nil + } + } + + return nil, tx, nil +} + +func (u *UserRoleDB) DeleteUserRoleDB(ctx context.Context, params *typescore.UserRole) error { + if params != nil && params.ID != nil { + query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Delete(dbcoretablenames.TableNameUserRoles.ToString()). + Where(squirrel.Eq{"id": *params.ID}). + ToSql() + + if err != nil { + return err + } + + rows, err := u.pool.Query(ctx, query, args...) + if err != nil { + return err + } + defer rows.Close() + + return nil + } else { + return errors.New("userRole obj is nil") + } +} diff --git a/core/db/table_names/table_names.go b/core/db/table_names/table_names.go new file mode 100644 index 0000000..42b6f4e --- /dev/null +++ b/core/db/table_names/table_names.go @@ -0,0 +1,30 @@ +package dbcoretablenames + +type TableName string + +const ( + TableNameApprovals TableName = "approvals" + TableNameApprovalSteps TableName = "approval_steps" + TableNameApprovalTopics TableName = "approval_topics" + TableNameApprovalTopicCategories TableName = "approval_topic_categories" + TableNameDepartments TableName = "departments" + TableNamePermissions TableName = "permissions" + TableNameRoles TableName = "roles" + TableNameUsers TableName = "users" + TableNameUserHierarchy TableName = "user_hierarchy" + TableNameUserRoles TableName = "user_roles" + TableNameApprovalFiles TableName = "approval_files" + TableNameApprovalDelegations TableName = "approval_delegations" + TableNameApprovalAdditionalApprovers TableName = "approval_additional_approvers" + TableNameApprovalAdditionalObservers TableName = "approval_additional_observers" + TableNameApprovalTasks TableName = "approval_tasks" + TableNameApprovalComments TableName = "approval_comments" + TableNameSuggestions TableName = "suggestions" + TableNameSuggestionMessages TableName = "suggestion_messages" + TableNameApprovalTopicExecutor TableName = "approval_topic_executor" + TableNameAdmin TableName = "admin" +) + +func (t TableName) ToString() string { + return string(t) +} diff --git a/core/go.mod b/core/go.mod new file mode 100644 index 0000000..bcc1b46 --- /dev/null +++ b/core/go.mod @@ -0,0 +1,53 @@ +module bitrix_balancer_api/core + +go 1.25.6 + +require ( + github.com/Masterminds/squirrel v1.5.4 + github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1 + github.com/golang-jwt/jwt/v5 v5.3.1 + github.com/google/uuid v1.6.0 + github.com/hashicorp/vault/api v1.22.0 + github.com/jackc/pgx/v5 v5.8.0 + github.com/mitchellh/mapstructure v1.5.0 + github.com/redis/go-redis/v9 v9.18.0 + github.com/shopspring/decimal v1.4.0 + github.com/sirupsen/logrus v1.9.4 + golang.org/x/crypto v0.40.0 + golang.org/x/net v0.42.0 + gopkg.in/yaml.v3 v3.0.1 + gorm.io/driver/postgres v1.6.0 + gorm.io/gorm v1.31.1 +) + +require ( + 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/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/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // 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/kr/text v0.2.0 // 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/rogpeppe/go-internal v1.14.1 // indirect + github.com/ryanuber/go-glob v1.0.0 // indirect + go.uber.org/atomic v1.11.0 // indirect + golang.org/x/sync v0.17.0 // indirect + golang.org/x/sys v0.41.0 // indirect + golang.org/x/text v0.29.0 // indirect + golang.org/x/time v0.12.0 // indirect +) diff --git a/core/go.sum b/core/go.sum new file mode 100644 index 0000000..34ff3d7 --- /dev/null +++ b/core/go.sum @@ -0,0 +1,125 @@ +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/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +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-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-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/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.0.9 h1:lgaqFMSdTdQYdZ04uHyN2d/eKdOMyi2YLSvlQIBFYa4= +github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +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/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= +golang.org/x/crypto v0.40.0 h1:r4x+VvoG5Fm+eJcxMaY8CQM7Lb0l1lsmjGBQ6s8BfKM= +golang.org/x/crypto v0.40.0/go.mod h1:Qr1vMER5WyS2dfPHAlsOj01wgLbsyWtFn/aY+5+ZdxY= +golang.org/x/net v0.42.0 h1:jzkYrhi3YQWD6MLBJcsklgQsoAcw89EcZbJw8Z614hs= +golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8= +golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug= +golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= +golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k= +golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk= +golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4= +golang.org/x/time v0.12.0 h1:ScB/8o8olJvc+CQPWrK3fPZNfh7qgwCrY0zJmoEQLSE= +golang.org/x/time v0.12.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg= +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/core/lib/external/gorm/gorm.go b/core/lib/external/gorm/gorm.go new file mode 100644 index 0000000..24071bd --- /dev/null +++ b/core/lib/external/gorm/gorm.go @@ -0,0 +1,139 @@ +package gormmodule + +import ( + "database/sql" + "errors" + "fmt" + "log" + "os" + "sync" + "time" + + "github.com/sirupsen/logrus" + + "gorm.io/driver/postgres" + "gorm.io/gorm" + "gorm.io/gorm/logger" +) + +type ConfigConnectGorm struct { + Host string + Port string + User string + Password string + Name string + SslMode string +} + +var ( + gormDB *gorm.DB + once sync.Once +) + +func connectGormDB(configObj *ConfigConnectGorm) (*gorm.DB, error) { + if configObj == nil { + return nil, errors.New("connectGormDB: configObj is nil") + } + + log.Println("🚀 ConnectGormDB") + sslMode := "disable" + if configObj.SslMode != "" { + sslMode = configObj.SslMode + } + + // Поддерживаем только disable и require + if sslMode != "disable" && sslMode != "require" { + return nil, errors.New("ConnectDB: unsupported sslmode, only 'disable' and 'require' are allowed") + } + + connStr := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=%s", + configObj.Host, + configObj.Port, + configObj.User, + configObj.Password, + configObj.Name, + sslMode) + + newLogger := logger.New( + log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer + logger.Config{ + SlowThreshold: time.Second, // медленный SQL порог + LogLevel: logger.Silent, // уровень логирования + IgnoreRecordNotFoundError: true, // игнорировать ошибки записи не найдены + Colorful: false, // отключить цвет + }, + ) + + db, err := gorm.Open(postgres.Open(connStr), &gorm.Config{ + Logger: newLogger, + }) + if err != nil { + logrus.Errorf("🔴 error: %s: %+v", "connectGormDB-Open", err) + return nil, err + } + + return db, nil +} + +// Подключение к базе данных GORM с использованием Singleton +func GormDatabaseConnect(configObj *ConfigConnectGorm) (*gorm.DB, *sql.DB, error) { + logrus.Info("🚀 GormDatabaseConnect") + if configObj == nil { + return nil, nil, errors.New("configObj is nil") + } + + var err error + once.Do(func() { + gormDB, err = connectGormDB(configObj) + }) + + if err != nil { + return nil, nil, err + } + + if gormDB == nil { + return nil, nil, errors.New("failed to connect database: GormDB instance is nil") + } + + sqlDB, err := gormDB.DB() + if err != nil { + return nil, nil, errors.New("failed to get DB from GORM") + } + + // SetMaxIdleConns устанавливает максимальное количество соединений в пуле простаивающих соединений. + sqlDB.SetMaxIdleConns(2) + + // SetMaxOpenConns устанавливает максимальное количество открытых соединений с базой данных. + sqlDB.SetMaxOpenConns(10) + + // SetConnMaxLifetime устанавливает максимальное время, в течение которого может быть повторно использовано соединение. + sqlDB.SetConnMaxLifetime(5 * time.Minute) + + gormDB.Exec("CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\";") + return gormDB, sqlDB, nil +} + +// Отключение от базы данных GORM +func GormDatabaseDisconnect() error { + if gormDB == nil { + return nil + } + + sqlDB, err := gormDB.DB() + if err != nil { + return err + } + + // Закрываем все открытые соединения + if err := sqlDB.Close(); err != nil { + return errors.New(fmt.Sprintf("failed to close database connections: %v", err)) + } + + // Очищаем пул соединений + sqlDB.SetMaxIdleConns(0) + sqlDB.SetMaxOpenConns(0) + + // Обнуляем глобальную переменную + gormDB = nil + return nil +} diff --git a/core/lib/external/pgxpool/pgxpools.go b/core/lib/external/pgxpool/pgxpools.go new file mode 100644 index 0000000..a0d43a1 --- /dev/null +++ b/core/lib/external/pgxpool/pgxpools.go @@ -0,0 +1,86 @@ +package pgxpoolmodule + +import ( + "context" + "errors" + "fmt" + "log" + "sync" + "time" + + "github.com/jackc/pgx/v5/pgxpool" +) + +type ConfigConnectPgxPool struct { + Host string + Port string + User string + Password string + Name string + SSLMode string +} + +var ( + pool *pgxpool.Pool + once sync.Once +) + +func ConnectDB(configObj *ConfigConnectPgxPool) (*pgxpool.Pool, error) { + var err error + once.Do(func() { + if configObj == nil { + err = errors.New("ConnectDB: configObj is nil") + return + } + + log.Println("🚀 ConnectDB") + sslMode := "disable" + if configObj.SSLMode != "" { + sslMode = configObj.SSLMode + } + + // Поддерживаем только disable и require + if sslMode != "disable" && sslMode != "require" { + err = errors.New("ConnectDB: unsupported sslmode, only 'disable' and 'require' are allowed") + return + } + + log.Println("🚀 sslMode: ", sslMode) + connStr := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=%s target_session_attrs=read-write", + configObj.Host, + configObj.Port, + configObj.User, + configObj.Password, + configObj.Name, + sslMode) + + configDB, err := pgxpool.ParseConfig(connStr) + if err != nil { + err = errors.New("ConnectDB: failed to parse config: " + err.Error()) + return + } + + // настройки пула + configDB.MaxConns = 2 // Максимальное количество открытых соединений в пуле + configDB.MinConns = 1 // Минимальное количество открытых соединений, которое пул будет поддерживать + configDB.MaxConnLifetime = time.Second * 45 // Максимальное время жизни соединения. После этого времени соединение будет закрыто + configDB.MaxConnIdleTime = time.Second * 45 // Максимальное время простоя соединения. Если соединение не используется в течение этого времени, оно будет закрыто + configDB.HealthCheckPeriod = time.Second * 15 // Периодичность проверки состояния соединений в пуле + + pool, err = pgxpool.NewWithConfig(context.Background(), configDB) + if err != nil { + err = errors.New("ConnectDB: failed to connect to database: " + err.Error()) + return + } + }) + + if err != nil { + return nil, err + } + + if pool == nil { + return nil, errors.New("ConnectDB: failed to connect to database: pool is nil") + } + + return pool, nil +} diff --git a/core/lib/external/telegram/init.go b/core/lib/external/telegram/init.go new file mode 100644 index 0000000..3da6e25 --- /dev/null +++ b/core/lib/external/telegram/init.go @@ -0,0 +1,51 @@ +package telegram + +import ( + "errors" + "fmt" + "sync" + + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" + "github.com/sirupsen/logrus" +) + +type TgBotClient struct { + bot *tgbotapi.BotAPI + config *BotConfig +} + +var ( + onceTgBotClient sync.Once + tgBotClientInstance *TgBotClient +) + +// NewTgBotClient создает новый экземпляр Client с заданным API ключом. +func NewTgBotClient(config *BotConfig) (*TgBotClient, error) { + if config == nil { + return nil, errors.New("failed to init TgBotClient: Api key is nil") + } + if config.BotKey == "" { + return nil, errors.New("failed to init TgBotClient: Api key is nil") + } + + onceTgBotClient.Do(func() { + bot, err := tgbotapi.NewBotAPI(config.BotKey) + if err != nil { + println(errors.New(fmt.Sprintf("🔴 error failed to setup telegram bot: %v", err))) + return + } + + tgBotClientInstance = &TgBotClient{ + bot: bot, + config: config, + } + + logrus.Info("✅ Telegram BOT API success connected") + }) + + return tgBotClientInstance, nil +} + +func (client *TgBotClient) GetBot() *tgbotapi.BotAPI { + return client.bot +} diff --git a/core/lib/external/telegram/message.go b/core/lib/external/telegram/message.go new file mode 100644 index 0000000..91beee5 --- /dev/null +++ b/core/lib/external/telegram/message.go @@ -0,0 +1,56 @@ +package telegram + +import ( + "errors" + "fmt" + "io" + + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" + "github.com/sirupsen/logrus" +) + +// SendMessageToTelegramBot отправляет сообщение в указанный чат. +func (client *TgBotClient) SendMessageToTelegramBot(title, text *string, ChatID *int64, photoReader io.ReadCloser, buttonText, buttonURL *string) error { + if text == nil || ChatID == nil || title == nil { + logrus.Error("🔴 error SendMessageToTelegramBot: invalid parameter") + return errors.New("invalid parameter") + } + + var markup *tgbotapi.InlineKeyboardMarkup + if buttonText != nil && *buttonText != "" && buttonURL != nil { + button := tgbotapi.NewInlineKeyboardButtonURL(*buttonText, *buttonURL) + row := tgbotapi.NewInlineKeyboardRow(button) + markup = &tgbotapi.InlineKeyboardMarkup{ + InlineKeyboard: [][]tgbotapi.InlineKeyboardButton{row}, + } + } + + if photoReader != nil { + photoMsg := tgbotapi.NewPhoto(*ChatID, tgbotapi.FileReader{ + Name: "photo", + Reader: photoReader, + }) + photoMsg.Caption = fmt.Sprintf("%s\n\n%s", *title, *text) + photoMsg.ParseMode = "HTML" + if markup != nil { + photoMsg.ReplyMarkup = markup + } + + if _, err := client.bot.Send(photoMsg); err != nil { + logrus.Error("🔴 error SendMessageToTelegramBot: Failed to send photo with message", err) + return err + } + } else { + msg := tgbotapi.NewMessage(*ChatID, fmt.Sprintf("%s\n\n%s", *title, *text)) + msg.ParseMode = "HTML" + if markup != nil { + msg.ReplyMarkup = markup + } + + if _, err := client.bot.Send(msg); err != nil { + logrus.Error("🔴 error SendMessageToTelegramBot: Failed to send message", err) + return err + } + } + return nil +} diff --git a/core/lib/external/telegram/req.go b/core/lib/external/telegram/req.go new file mode 100644 index 0000000..0cbf34f --- /dev/null +++ b/core/lib/external/telegram/req.go @@ -0,0 +1,60 @@ +package telegram + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" +) + +// apiResponse описывает ответ API Telegram +type apiResponse struct { + Ok bool `json:"ok"` + Result json.RawMessage `json:"result"` +} + +// sendRequest отправляет запрос к API Telegram и возвращает ответ +func (client *TgBotClient) sendRequest(method string, requestBody interface{}) (*apiResponse, error) { + var reqBody []byte + var err error + if requestBody != nil { + reqBody, err = json.Marshal(requestBody) + if err != nil { + return nil, errors.New(fmt.Sprintf("marshaling request body: %v", err)) + } + } + + req, err := http.NewRequest(http.MethodPost, fmt.Sprintf("https://api.telegram.org/bot%s/%s", client.config.BotKey, method), bytes.NewReader(reqBody)) + if err != nil { + return nil, errors.New(fmt.Sprintf("creating request: %v", err)) + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-Telegram-Bot-Api-Secret-Token", client.config.BotKey) + + resp, err := http.DefaultClient.Do(req) + if err != nil { + return nil, errors.New(fmt.Sprintf("sending request error: %v", err)) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + bodyBytes, err := io.ReadAll(resp.Body) + if err != nil { + println(errors.New(fmt.Sprintf("🔴 error reading response body: %v", err))) + } else { + bodyString := string(bodyBytes) + println(errors.New(fmt.Sprintf("🔴 unexpected status body: %v", bodyString))) + } + + return nil, errors.New(fmt.Sprintf("unexpected status code: %d", resp.StatusCode)) + } + + var apiResponse apiResponse + if err := json.NewDecoder(resp.Body).Decode(&apiResponse); err != nil { + return nil, errors.New(fmt.Sprintf("decoding response: %v", err)) + } + + return &apiResponse, nil +} diff --git a/core/lib/external/telegram/types.go b/core/lib/external/telegram/types.go new file mode 100644 index 0000000..98f962c --- /dev/null +++ b/core/lib/external/telegram/types.go @@ -0,0 +1,25 @@ +package telegram + +import tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" + +type BotConfig struct { + BotKey string + ApiURL string +} + +type InvoiceRequestAmount struct { + Amount *int `json:"amount"` +} + +type InvoiceLink struct { + Link *string `json:"link"` +} + +type InvoiceRequest struct { + Title string `json:"title"` + Description string `json:"description"` + Payload string `json:"payload"` + Currency string `json:"currency"` + Prices []tgbotapi.LabeledPrice `json:"prices"` + SubscriptionPeriod *int `json:"subscription_period"` //The currency must be set to “XTR” (Telegram Stars) if the parameter is used. Currently, it must always be 2592000 (30 days) if specified. +} diff --git a/core/lib/external/tgkit/client.go b/core/lib/external/tgkit/client.go new file mode 100644 index 0000000..ba34607 --- /dev/null +++ b/core/lib/external/tgkit/client.go @@ -0,0 +1,182 @@ +package tgkit + +import ( + "crypto/tls" + "fmt" + "github.com/sirupsen/logrus" + "net/http" + "net/url" + "sync" + "time" + + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" + "golang.org/x/net/proxy" +) + +// Client — основной клиент библиотеки +type Client struct { + bot *tgbotapi.BotAPI + timeout time.Duration +} + +// ClientConfig — конфигурация клиента +type ClientConfig struct { + Token string + Proxy *ProxyConfig + Timeout time.Duration // по умолчанию 30s + Debug bool +} + +var ( + mu sync.Mutex + instance *Client +) + +func GetClient(cfg ClientConfig) (*Client, error) { + if instance != nil { + return instance, nil + } + + mu.Lock() + defer mu.Unlock() + + if instance != nil { + return instance, nil + } + + client, err := newClient(cfg) + if err != nil { + return nil, err + } + + instance = client + return instance, nil +} + +// New создаёт нового клиента +func newClient(cfg ClientConfig) (*Client, error) { + if cfg.Token == "" { + return nil, fmt.Errorf("tgkit: token is required") + } + if cfg.Timeout == 0 { + cfg.Timeout = 30 * time.Second + } + + if cfg.Proxy != nil { + logrus.Debugf("tgkit: proxy is configured: url: %s, username: %s, pass: %s", cfg.Proxy.URL, cfg.Proxy.Username, cfg.Proxy.Password) + } + httpClient, err := buildHTTPClient(cfg.Proxy, cfg.Timeout) + if err != nil { + return nil, fmt.Errorf("tgkit: build http client: %w", err) + } + + bot, err := tgbotapi.NewBotAPIWithClient(cfg.Token, tgbotapi.APIEndpoint, httpClient) + if err != nil { + return nil, fmt.Errorf("tgkit: init bot: %w", err) + } + + bot.Debug = cfg.Debug + + return &Client{ + bot: bot, + timeout: cfg.Timeout, + }, nil +} + +// NewFromExisting оборачивает существующий *tgbotapi.BotAPI +// Используется для постепенной миграции без переписывания всего кода +func NewFromExisting(bot *tgbotapi.BotAPI) *Client { + return &Client{bot: bot, timeout: 30 * time.Second} +} + +// Bot возвращает сырой *tgbotapi.BotAPI для обратной совместимости +func (c *Client) Bot() *tgbotapi.BotAPI { + return c.bot +} + +// Self возвращает информацию о боте +func (c *Client) Self() tgbotapi.User { + return c.bot.Self +} + +// GetUpdates возвращает канал обновлений +func (c *Client) GetUpdates(timeout int) tgbotapi.UpdatesChannel { + u := tgbotapi.NewUpdate(0) + u.Timeout = timeout + return c.bot.GetUpdatesChan(u) +} + +// AnswerCallback отвечает на callback query +func (c *Client) AnswerCallback(callbackID string, text string) error { + cb := tgbotapi.NewCallback(callbackID, text) + _, err := c.bot.Request(cb) + return err +} + +// DeleteMessage удаляет сообщение +func (c *Client) DeleteMessage(chatID int64, messageID int) error { + _, err := c.bot.Request(tgbotapi.NewDeleteMessage(chatID, messageID)) + return err +} + +// GetFileDirectURL возвращает прямую ссылку на файл +func (c *Client) GetFileDirectURL(fileID string) (string, error) { + return c.bot.GetFileDirectURL(fileID) +} + +// Request выполняет произвольный запрос к API (для edge cases) +func (c *Client) Request(cfg tgbotapi.Chattable) (*tgbotapi.APIResponse, error) { + return c.bot.Request(cfg) +} + +// buildHTTPClient создаёт http.Client с поддержкой прокси +func buildHTTPClient(proxyCfg *ProxyConfig, timeout time.Duration) (*http.Client, error) { + transport := &http.Transport{ + TLSClientConfig: &tls.Config{InsecureSkipVerify: false}, + } + + if proxyCfg != nil && proxyCfg.URL != "" { + proxyURL, err := url.Parse(proxyCfg.URL) + if err != nil { + return nil, fmt.Errorf("parse proxy url: %w", err) + } + + scheme := proxyURL.Scheme + + switch scheme { + case "socks5", "socks5h": + var auth *proxy.Auth + + if proxyCfg.Username != "" { + auth = &proxy.Auth{ + User: proxyCfg.Username, + Password: proxyCfg.Password, + } + } else if proxyURL.User != nil { + pass, _ := proxyURL.User.Password() + auth = &proxy.Auth{ + User: proxyURL.User.Username(), + Password: pass, + } + } + + dialer, err := proxy.SOCKS5("tcp", proxyURL.Host, auth, proxy.Direct) + if err != nil { + return nil, fmt.Errorf("create socks5 dialer: %w", err) + } + + transport.Dial = dialer.Dial //nolint:staticcheck + + case "http", "https": + transport.Proxy = http.ProxyURL(proxyURL) + + default: + return nil, fmt.Errorf("unsupported proxy scheme: %s", scheme) + } + } + + return &http.Client{ + Transport: transport, + Timeout: timeout, + }, nil +} diff --git a/core/lib/external/tgkit/err.go b/core/lib/external/tgkit/err.go new file mode 100644 index 0000000..c6207e0 --- /dev/null +++ b/core/lib/external/tgkit/err.go @@ -0,0 +1,25 @@ +package tgkit + +import "fmt" + +type ErrSend struct { + ChatID int64 + Reason string +} + +func (e *ErrSend) Error() string { + return fmt.Sprintf("tgkit: send to chat %d failed: %s", e.ChatID, e.Reason) +} + +type ErrNilBot struct{} + +func (e *ErrNilBot) Error() string { + return "tgkit: bot client is nil" +} + +func wrapSendErr(chatID int64, err error) error { + if err == nil { + return nil + } + return &ErrSend{ChatID: chatID, Reason: err.Error()} +} diff --git a/core/lib/external/tgkit/keyboard.go b/core/lib/external/tgkit/keyboard.go new file mode 100644 index 0000000..38327f4 --- /dev/null +++ b/core/lib/external/tgkit/keyboard.go @@ -0,0 +1,163 @@ +package tgkit + +import ( + "fmt" + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" +) + +// ───────────────────────────────────────────── +// Inline-клавиатура +// ───────────────────────────────────────────── + +// InlineKeyboard — построитель inline-клавиатуры +type InlineKeyboard struct { + Rows [][]tgbotapi.InlineKeyboardButton +} + +// NewInlineKeyboard создаёт пустой построитель +func NewInlineKeyboard() *InlineKeyboard { + return &InlineKeyboard{} +} + +// Row добавляет ряд кнопок +func (kb *InlineKeyboard) Row(buttons ...InlineButton) *InlineKeyboard { + var row []tgbotapi.InlineKeyboardButton + for _, btn := range buttons { + row = append(row, btn.Build()) + } + kb.Rows = append(kb.Rows, row) + return kb +} + +// Build возвращает готовую клавиатуру +func (kb *InlineKeyboard) Build() tgbotapi.InlineKeyboardMarkup { + return tgbotapi.NewInlineKeyboardMarkup(kb.Rows...) +} + +// InlineButton — кнопка inline-клавиатуры +type InlineButton struct { + label string + style ButtonStyle + callback string + url string +} + +// Btn создаёт кнопку с callback +func Btn(label, callback string) InlineButton { + return InlineButton{label: label, callback: callback} +} + +// BtnStyled создаёт кнопку с визуальным стилем (эмодзи) и callback +func BtnStyled(style ButtonStyle, label, callback string) InlineButton { + return InlineButton{label: label, style: style, callback: callback} +} + +// BtnURL создаёт кнопку-ссылку +func BtnURL(label, url string) InlineButton { + return InlineButton{label: label, url: url} +} + +// WithStyle задаёт стиль кнопке +func (b InlineButton) WithStyle(style ButtonStyle) InlineButton { + b.style = style + return b +} + +func (b InlineButton) Build() tgbotapi.InlineKeyboardButton { + text := string(b.style) + b.label + if b.url != "" { + return tgbotapi.NewInlineKeyboardButtonURL(text, b.url) + } + return tgbotapi.NewInlineKeyboardButtonData(text, b.callback) +} + +// ───────────────────────────────────────────── +// Reply-клавиатура (постоянные кнопки) +// ───────────────────────────────────────────── + +// ReplyKeyboard — построитель reply-клавиатуры +type ReplyKeyboard struct { + rows [][]tgbotapi.KeyboardButton + resize bool + oneTime bool +} + +// NewReplyKeyboard создаёт пустой построитель +func NewReplyKeyboard() *ReplyKeyboard { + return &ReplyKeyboard{resize: true} +} + +// Row добавляет ряд текстовых кнопок +func (kb *ReplyKeyboard) Row(labels ...string) *ReplyKeyboard { + var row []tgbotapi.KeyboardButton + for _, label := range labels { + row = append(row, tgbotapi.NewKeyboardButton(label)) + } + kb.rows = append(kb.rows, row) + return kb +} + +// OneTime скрывает клавиатуру после нажатия +func (kb *ReplyKeyboard) OneTime() *ReplyKeyboard { + kb.oneTime = true + return kb +} + +// NoResize отключает авторесайз +func (kb *ReplyKeyboard) NoResize() *ReplyKeyboard { + kb.resize = false + return kb +} + +// Build возвращает готовую клавиатуру +func (kb *ReplyKeyboard) Build() tgbotapi.ReplyKeyboardMarkup { + markup := tgbotapi.NewReplyKeyboard(kb.rows...) + markup.ResizeKeyboard = kb.resize + markup.OneTimeKeyboard = kb.oneTime + return markup +} + +// RemoveKeyboard убирает reply-клавиатуру +func RemoveKeyboard() tgbotapi.ReplyKeyboardRemove { + return tgbotapi.NewRemoveKeyboard(false) +} + +// ───────────────────────────────────────────── +// Готовые шаблоны клавиатур +// ───────────────────────────────────────────── + +// ConfirmKeyboard — клавиатура Да/Нет +func ConfirmKeyboard(yesCallback, noCallback string) tgbotapi.InlineKeyboardMarkup { + return NewInlineKeyboard(). + Row( + BtnStyled(ButtonStyleSuccess, "Да", yesCallback), + BtnStyled(ButtonStyleDanger, "Нет", noCallback), + ). + Build() +} + +// BackKeyboard — одна кнопка "← Назад" +func BackKeyboard(callback string) tgbotapi.InlineKeyboardMarkup { + return NewInlineKeyboard(). + Row(BtnStyled(ButtonStyleBack, "Назад", callback)). + Build() +} + +// PaginationRow — ряд кнопок пагинации +func PaginationRow(page, totalPages int, prevCallback, nextCallback, noopCallback string) []tgbotapi.InlineKeyboardButton { + var row []tgbotapi.InlineKeyboardButton + + if page > 0 { + row = append(row, Btn("←", prevCallback).Build()) + } + + row = append(row, tgbotapi.NewInlineKeyboardButtonData( + fmt.Sprintf("%d / %d", page+1, totalPages), noopCallback, + )) + + if page < totalPages-1 { + row = append(row, Btn("→", nextCallback).Build()) + } + + return row +} diff --git a/core/lib/external/tgkit/media.go b/core/lib/external/tgkit/media.go new file mode 100644 index 0000000..2fd0c07 --- /dev/null +++ b/core/lib/external/tgkit/media.go @@ -0,0 +1,180 @@ +package tgkit + +import ( + "encoding/base64" + "fmt" + "io" + "net/http" + "os" + + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" + "github.com/sirupsen/logrus" +) + +// SendPhoto отправляет фото по URL, пути к файлу или base64 +func (c *Client) SendPhoto(chatID int64, source string, caption string, opts ...MessageOptions) (*SentMessage, error) { + var photo tgbotapi.RequestFileData + + switch { + case isURL(source): + photo = tgbotapi.FileURL(source) + case isBase64(source): + data, err := base64.StdEncoding.DecodeString(source) + if err != nil { + return nil, fmt.Errorf("tgkit: decode base64: %w", err) + } + photo = tgbotapi.FileBytes{Name: "photo.jpg", Bytes: data} + default: + photo = tgbotapi.FilePath(source) + } + + msg := tgbotapi.NewPhoto(chatID, photo) + msg.Caption = caption + msg.ParseMode = "HTML" + + if len(opts) > 0 && opts[0].ReplyMarkup != nil { + msg.ReplyMarkup = opts[0].ReplyMarkup + } + + sent, err := c.bot.Send(msg) + if err != nil { + return nil, wrapSendErr(chatID, err) + } + + return &SentMessage{MessageID: sent.MessageID, ChatID: sent.Chat.ID}, nil +} + +// SendDocument отправляет документ +func (c *Client) SendDocument(chatID int64, data []byte, fileName string, caption string, opts ...MessageOptions) (*SentMessage, error) { + doc := tgbotapi.NewDocument(chatID, tgbotapi.FileBytes{ + Name: fileName, + Bytes: data, + }) + doc.Caption = caption + doc.ParseMode = "HTML" + + if len(opts) > 0 && opts[0].ReplyMarkup != nil { + doc.ReplyMarkup = opts[0].ReplyMarkup + } + + sent, err := c.bot.Send(doc) + if err != nil { + return nil, wrapSendErr(chatID, err) + } + + return &SentMessage{MessageID: sent.MessageID, ChatID: sent.Chat.ID}, nil +} + +// SendDocumentFromBase64 отправляет документ из base64-строки +func (c *Client) SendDocumentFromBase64(chatID int64, base64Data string, fileName string, caption string, opts ...MessageOptions) (*SentMessage, error) { + data, err := base64.StdEncoding.DecodeString(base64Data) + if err != nil { + return nil, fmt.Errorf("tgkit: decode base64: %w", err) + } + return c.SendDocument(chatID, data, fileName, caption, opts...) +} + +// SendSticker отправляет стикер по fileID +func (c *Client) SendSticker(chatID int64, fileID string) (*SentMessage, error) { + sticker := tgbotapi.NewSticker(chatID, tgbotapi.FileID(fileID)) + sent, err := c.bot.Send(sticker) + if err != nil { + return nil, wrapSendErr(chatID, err) + } + return &SentMessage{MessageID: sent.MessageID, ChatID: sent.Chat.ID}, nil +} + +// SendMediaGroup отправляет группу медиафайлов (альбом) +func (c *Client) SendMediaGroup(chatID int64, files []MediaFile) error { + if len(files) == 0 { + return nil + } + + var media []interface{} + for i, f := range files { + photo := tgbotapi.NewInputMediaPhoto(tgbotapi.FileBytes{ + Name: f.FileName, + Bytes: f.Data, + }) + if i == 0 && f.Caption != "" { + photo.Caption = f.Caption + photo.ParseMode = "HTML" + } + media = append(media, photo) + } + + mediaGroup := tgbotapi.NewMediaGroup(chatID, media) + _, err := c.bot.Request(mediaGroup) + return err +} + +// DownloadFile скачивает файл из Telegram по fileID, возвращает байты +func (c *Client) DownloadFile(fileID string) ([]byte, string, error) { + fileURL, err := c.bot.GetFileDirectURL(fileID) + if err != nil { + return nil, "", fmt.Errorf("tgkit: get file url: %w", err) + } + + resp, err := http.Get(fileURL) //nolint:gosec + if err != nil { + return nil, "", fmt.Errorf("tgkit: download file: %w", err) + } + defer resp.Body.Close() + + data, err := io.ReadAll(resp.Body) + if err != nil { + return nil, "", fmt.Errorf("tgkit: read file: %w", err) + } + + // Извлекаем имя файла из URL + fileName := extractFileName(fileURL) + return data, fileName, nil +} + +// DownloadFileAsBase64 скачивает файл и возвращает base64 +func (c *Client) DownloadFileAsBase64(fileID string) (string, string, error) { + data, fileName, err := c.DownloadFile(fileID) + if err != nil { + return "", "", err + } + return base64.StdEncoding.EncodeToString(data), fileName, nil +} + +// MustSendDocument отправляет документ, логирует ошибку +func (c *Client) MustSendDocument(chatID int64, data []byte, fileName, caption string, opts ...MessageOptions) { + if _, err := c.SendDocument(chatID, data, fileName, caption, opts...); err != nil { + logrus.Warnf("tgkit.MustSendDocument: chatID=%d file=%s err=%v", chatID, fileName, err) + } +} + +// MediaFile — структура для SendMediaGroup +type MediaFile struct { + Data []byte + FileName string + Caption string +} + +func isURL(s string) bool { + return len(s) > 4 && (s[:4] == "http" || s[:5] == "https") +} + +func isBase64(s string) bool { + if len(s) < 4 { + return false + } + _, err := base64.StdEncoding.DecodeString(s[:4]) + return err == nil && len(s)%4 == 0 +} + +func extractFileName(fileURL string) string { + for i := len(fileURL) - 1; i >= 0; i-- { + if fileURL[i] == '/' { + return fileURL[i+1:] + } + } + return "file" +} + +func readFile(path string) ([]byte, error) { + return os.ReadFile(path) //nolint:gosec +} diff --git a/core/lib/external/tgkit/message.go b/core/lib/external/tgkit/message.go new file mode 100644 index 0000000..c049e35 --- /dev/null +++ b/core/lib/external/tgkit/message.go @@ -0,0 +1,87 @@ +package tgkit + +import ( + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" + "github.com/sirupsen/logrus" +) + +// Send отправляет текстовое сообщение +func (c *Client) Send(chatID int64, text string, opts ...MessageOptions) (*SentMessage, error) { + if c.bot == nil { + return nil, &ErrNilBot{} + } + + msg := tgbotapi.NewMessage(chatID, text) + msg.ParseMode = "HTML" // дефолт + + if len(opts) > 0 { + opt := opts[0] + if opt.ParseMode != "" { + msg.ParseMode = string(opt.ParseMode) + } + if opt.ReplyMarkup != nil { + msg.ReplyMarkup = opt.ReplyMarkup + } + msg.DisableWebPagePreview = opt.DisablePreview + msg.DisableNotification = opt.Silent + } + + sent, err := c.bot.Send(msg) + if err != nil { + return nil, wrapSendErr(chatID, err) + } + + return &SentMessage{ + MessageID: sent.MessageID, + ChatID: sent.Chat.ID, + Date: sent.Time(), + }, nil +} + +// MustSend отправляет сообщение, логирует ошибку но не возвращает её. +// Используется когда ошибка некритична (уведомление). +func (c *Client) MustSend(chatID int64, text string, opts ...MessageOptions) { + if _, err := c.Send(chatID, text, opts...); err != nil { + logrus.Warnf("tgkit.MustSend: chatID=%d err=%v", chatID, err) + } +} + +// EditText редактирует текст существующего сообщения +func (c *Client) EditText(chatID int64, messageID int, text string, opts ...MessageOptions) error { + edit := tgbotapi.NewEditMessageText(chatID, messageID, text) + edit.ParseMode = "HTML" + + if len(opts) > 0 && opts[0].ParseMode != "" { + edit.ParseMode = string(opts[0].ParseMode) + } + + _, err := c.bot.Request(edit) + return err +} + +// EditKeyboard заменяет клавиатуру у существующего сообщения +func (c *Client) EditKeyboard(chatID int64, messageID int, keyboard tgbotapi.InlineKeyboardMarkup) error { + edit := tgbotapi.NewEditMessageReplyMarkup(chatID, messageID, keyboard) + _, err := c.bot.Request(edit) + return err +} + +// WithKeyboard — хелпер для построения MessageOptions с клавиатурой +func WithKeyboard(markup interface{}) MessageOptions { + return MessageOptions{ReplyMarkup: markup} +} + +// WithInline — хелпер для inline-клавиатуры +func WithInline(kb *InlineKeyboard) MessageOptions { + return MessageOptions{ReplyMarkup: kb.Build()} +} + +// WithReply — хелпер для reply-клавиатуры +func WithReply(kb *ReplyKeyboard) MessageOptions { + return MessageOptions{ReplyMarkup: kb.Build()} +} + +// WithSilent — хелпер для тихой отправки +func WithSilent() MessageOptions { + return MessageOptions{Silent: true} +} diff --git a/core/lib/external/tgkit/types.go b/core/lib/external/tgkit/types.go new file mode 100644 index 0000000..cbdfdf7 --- /dev/null +++ b/core/lib/external/tgkit/types.go @@ -0,0 +1,58 @@ +package tgkit + +import "time" + +// ParseMode — режим форматирования текста +type ParseMode string + +const ( + ParseModeHTML ParseMode = "HTML" + ParseModeMarkdown ParseMode = "MarkdownV2" + ParseModePlain ParseMode = "" +) + +// ButtonColorStyle — стили цветов кнопок +type ButtonColorStyle string + +const ( + ButtonColorStyleDanger ButtonColorStyle = "danger" // красная + ButtonColorStyleSuccess ButtonColorStyle = "success" // зеленая + ButtonColorStylePrimary ButtonColorStyle = "primary" // синяя +) + +// ButtonStyle — визуальный стиль кнопки (через эмодзи) +type ButtonStyle string + +const ( + ButtonStyleDefault ButtonStyle = "" + ButtonStyleSuccess ButtonStyle = "✅ " + ButtonStyleDanger ButtonStyle = "❌ " + ButtonStyleWarning ButtonStyle = "⚠️ " + ButtonStyleInfo ButtonStyle = "ℹ️ " + ButtonStylePrimary ButtonStyle = "🔵 " + ButtonStyleBack ButtonStyle = "← " + ButtonStyleForward ButtonStyle = "→ " + ButtonStyleRevision ButtonStyle = "↩️ " +) + +// MessageOptions — опции отправки сообщения +type MessageOptions struct { + ParseMode ParseMode + ReplyMarkup interface{} + DisablePreview bool + Silent bool +} + +// ProxyConfig — настройки прокси +type ProxyConfig struct { + URL string // socks5://user:pass@host:port или http://host:port + Username string + Password string +} + +// SentMessage — результат отправки +type SentMessage struct { + MessageID int + ChatID int64 + Date time.Time +} diff --git a/core/lib/internally/client-controllers/0_init.go b/core/lib/internally/client-controllers/0_init.go new file mode 100644 index 0000000..fec6696 --- /dev/null +++ b/core/lib/internally/client-controllers/0_init.go @@ -0,0 +1,47 @@ +package clientcontrollers + +import ( + configcore "bitrix_balancer_api/core/config" + database "bitrix_balancer_api/core/db" + redismodule "bitrix_balancer_api/core/lib/internally/redis" + "errors" + "fmt" +) + +type ClientsExternal struct { + Config *configcore.Config + Redis *redismodule.ModuleRedis + DB *database.ModuleDB +} + +func ReturnClientsExternal(cfgOptions *configcore.ConfigLoadOptions) (ClientsExternal, error) { + clientsExternal := ClientsExternal{} + if cfgOptions == nil { + cfgOptions = &configcore.ConfigLoadOptions{} + return clientsExternal, errors.New("cfgOptions is nil") + } + cfg, err := configcore.LoadConfig(cfgOptions) + if err != nil { + return clientsExternal, errors.New(fmt.Sprintf("failed to load config file: %v", err)) + } + + clientsExternal.Config = cfg + + if cfgOptions.Redis { + redisClient, err = getRedisClient(cfg) + if err != nil { + return clientsExternal, errors.New(fmt.Sprintf("failed to get redis client: %v", err)) + } + clientsExternal.Redis = redisClient + } + + if cfgOptions.Database { + dbClient, err = getDbClient(cfg) + if err != nil { + return clientsExternal, errors.New(fmt.Sprintf("failed to get db client: %v", err)) + } + clientsExternal.DB = dbClient + } + + return clientsExternal, nil +} diff --git a/core/lib/internally/client-controllers/db-client.go b/core/lib/internally/client-controllers/db-client.go new file mode 100644 index 0000000..58b1ead --- /dev/null +++ b/core/lib/internally/client-controllers/db-client.go @@ -0,0 +1,49 @@ +package clientcontrollers + +import ( + configcore "bitrix_balancer_api/core/config" + database "bitrix_balancer_api/core/db" + pgxpoolmodule "bitrix_balancer_api/core/lib/external/pgxpool" + "fmt" + "sync" +) + +var ( + dbOnce sync.Once + dbClient *database.ModuleDB +) + +func getDbClient(cfg *configcore.Config) (*database.ModuleDB, error) { + var err error + + if redisClient == nil { + cfg0, err := configcore.LoadConfig(&configcore.ConfigLoadOptions{ + Redis: true, + }) + if err != nil { + return nil, err + } + redisClient, err = getRedisClient(cfg0) + if err != nil { + return nil, err + } + } + + dbOnce.Do(func() { + var initErr error + dbClient, initErr = database.NewModuleDB(&pgxpoolmodule.ConfigConnectPgxPool{ + Host: cfg.Database.Host, + Port: fmt.Sprintf("%d", cfg.Database.Port), + User: cfg.Database.User, + Password: cfg.Database.Password, + Name: cfg.Database.DB, + SSLMode: cfg.Database.SSL, + }, redisClient) + if initErr != nil { + err = initErr + return + } + }) + + return dbClient, err +} diff --git a/core/lib/internally/client-controllers/redis-client.go b/core/lib/internally/client-controllers/redis-client.go new file mode 100644 index 0000000..1b03774 --- /dev/null +++ b/core/lib/internally/client-controllers/redis-client.go @@ -0,0 +1,34 @@ +package clientcontrollers + +import ( + configcore "bitrix_balancer_api/core/config" + redismodule "bitrix_balancer_api/core/lib/internally/redis" + "fmt" + "sync" + + "github.com/sirupsen/logrus" +) + +var ( + redisOnce sync.Once + + redisClient *redismodule.ModuleRedis +) + +func getRedisClient(cfg *configcore.Config) (*redismodule.ModuleRedis, error) { + var err error + + redisOnce.Do(func() { + redisClient = redismodule.GetRedisModuleInstance(&redismodule.RedisConfig{ + Host: cfg.Redis.Host, + Port: fmt.Sprintf("%d", cfg.Redis.Port), + User: cfg.Redis.User, + Password: cfg.Redis.Password, + }) + if err != nil { + logrus.Errorln("🔴 failed to get Redis client: ", err) + } + }) + + return redisClient, err +} diff --git a/core/lib/internally/config-loader/cfgldr.go b/core/lib/internally/config-loader/cfgldr.go new file mode 100644 index 0000000..b27f5f0 --- /dev/null +++ b/core/lib/internally/config-loader/cfgldr.go @@ -0,0 +1,22 @@ +package cfgldrlib + +import "errors" + +func LoadConfig[T any](params *ConfigLoaders) (*T, error) { + err := validateParams(params) + if err != nil { + return nil, err + } + configProvider, err := loadConfigProvider(params) + if err != nil { + return nil, err + } + + if configProvider == ConfigProviderYml { + return loadConfigFromYml[T](params.ConfigYml) + } else if configProvider == ConfigProviderVault { + return loadConfigFromVault[T](params.VaultParams) + } + + return nil, errors.New("config error detected") +} diff --git a/core/lib/internally/config-loader/loader.go b/core/lib/internally/config-loader/loader.go new file mode 100644 index 0000000..aa9914a --- /dev/null +++ b/core/lib/internally/config-loader/loader.go @@ -0,0 +1,28 @@ +package cfgldrlib + +import ( + "strings" + + "gopkg.in/yaml.v3" +) + +func loadConfigFromYml[T any](configYML *string) (*T, error) { + readerConfig := strings.NewReader(*configYML) + decoder := yaml.NewDecoder(readerConfig) + + var config T + if err := decoder.Decode(&config); err != nil { + return nil, err + } + + return &config, nil +} + +func loadConfigFromVault[T any](vaultParams *VaultParamsT) (*T, error) { + var config T + err := fillStructFromVault(&config, vaultParams.VaultClient, *vaultParams.KvName) + if err != nil { + return nil, err + } + return &config, nil +} diff --git a/core/lib/internally/config-loader/tag-worker.go b/core/lib/internally/config-loader/tag-worker.go new file mode 100644 index 0000000..2e98c1a --- /dev/null +++ b/core/lib/internally/config-loader/tag-worker.go @@ -0,0 +1,290 @@ +package cfgldrlib + +import ( + "fmt" + "reflect" + "strings" + + "github.com/hashicorp/vault/api" +) + +func buildDataVaultPath(basePath string) (string, error) { + if basePath == "" { + return "", fmt.Errorf("basePath is empty") + } + + slashIndex := strings.Index(basePath, "/") + if slashIndex == -1 { + return basePath + "/data", nil + } + + return basePath[:slashIndex+1] + "data" + basePath[slashIndex:], nil +} + +func getVaultValue(client *api.Client, vaultPath, key string) (any, error) { + + secret, err := client.Logical().Read(vaultPath) + if err != nil { + return nil, err + } + if secret == nil || secret.Data == nil { + return nil, fmt.Errorf("vault: secret not found at path %s", vaultPath) + } + + data, ok := secret.Data["data"].(map[string]any) + if !ok { + return nil, fmt.Errorf("vault: failed to get data from secret %s", vaultPath) + } + + if key == "" { + return data, nil + } + val, ok := data[key] + if !ok { + return nil, fmt.Errorf("vault: key %s not found in secret %s", key, vaultPath) + } + return val, nil +} + +func fillStructFromVault(v any, client *api.Client, basePath string) error { + val := reflect.ValueOf(v) + if val.Kind() != reflect.Ptr || val.IsNil() { + return fmt.Errorf("expected pointer to struct, got %T", v) + } + val = val.Elem() + typ := val.Type() + if typ.Kind() != reflect.Struct { + return fmt.Errorf("expected struct, got %T", v) + } + + for _, field := range reflect.VisibleFields(typ) { + fieldVal := val.FieldByName(field.Name) + cfgldrTag := field.Tag.Get(TagName) + if cfgldrTag == "-" { + continue + } + vaultKey := field.Name + if cfgldrTag != "" { + for part := range strings.SplitSeq(cfgldrTag, ",") { + if v, ok := strings.CutPrefix(part, ValTagParam); ok { + vaultKey = v + } + } + } + if fieldVal.Kind() == reflect.Struct { + nextPath := vaultKey + if basePath != "" { + nextPath = basePath + "/" + vaultKey + } + err := fillStructFromVault(fieldVal.Addr().Interface(), client, nextPath) + if err != nil { + fmt.Printf("⚠️ Error processing nested struct at path %s: %v\n", nextPath, err) + } + continue + } + + vaultPath, err := buildDataVaultPath(basePath) + if err != nil { + fmt.Printf("⚠️ Error building vault path: %s, %v\n", basePath, err) + continue + } + + valFromVault, err := getVaultValue(client, vaultPath, vaultKey) + if err != nil { + fmt.Printf("⚠️ Value not found for key: %s (field: %s) — %v\n", basePath, vaultKey, err) + continue + } + if fieldVal.CanSet() { + err = setValue(fieldVal, valFromVault) + if err != nil { + fmt.Printf("⚠️ Failed to set value for %s (field: %s): %v\n", basePath, vaultKey, err) + } + } + } + return nil +} + +func setValue(fieldVal reflect.Value, val any) error { + switch fieldVal.Kind() { + case reflect.String: + str, ok := val.(string) + if !ok { + str = fmt.Sprintf("%v", val) + } + fieldVal.SetString(str) + case reflect.Int, reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8: + var intVal int64 + switch v := val.(type) { + case int: + intVal = int64(v) + case int64: + intVal = v + case float64: + intVal = int64(v) + case string: + var err error + intVal, err = parseStringToInt64(v) + if err != nil { + return err + } + default: + str := fmt.Sprintf("%v", v) + var err error + intVal, err = parseStringToInt64(str) + if err != nil { + return err + } + } + fieldVal.SetInt(intVal) + case reflect.Float32, reflect.Float64: + var floatVal float64 + switch v := val.(type) { + case float64: + floatVal = v + case float32: + floatVal = float64(v) + case int: + floatVal = float64(v) + case int64: + floatVal = float64(v) + case string: + var err error + floatVal, err = parseStringToFloat64(v) + if err != nil { + return err + } + default: + str := fmt.Sprintf("%v", v) + var err error + floatVal, err = parseStringToFloat64(str) + if err != nil { + return err + } + } + fieldVal.SetFloat(floatVal) + case reflect.Bool: + var boolVal bool + switch v := val.(type) { + case bool: + boolVal = v + case string: + var err error + boolVal, err = parseStringToBool(v) + if err != nil { + return err + } + default: + str := fmt.Sprintf("%v", v) + var err error + boolVal, err = parseStringToBool(str) + if err != nil { + return err + } + } + fieldVal.SetBool(boolVal) + case reflect.Slice: + return setSliceValue(fieldVal, val) + default: + return fmt.Errorf("unsupported field type: %s", fieldVal.Kind()) + } + return nil +} + +func setSliceValue(fieldVal reflect.Value, val any) error { + elemType := fieldVal.Type().Elem() + + if slice, ok := val.([]any); ok { + result := reflect.MakeSlice(fieldVal.Type(), len(slice), len(slice)) + + for i, item := range slice { + elem := reflect.New(elemType).Elem() + + err := setValue(elem, item) + if err != nil { + return fmt.Errorf("failed to set slice element %d: %v", i, err) + } + + result.Index(i).Set(elem) + } + + fieldVal.Set(result) + return nil + } + + if str, ok := val.(string); ok { + if strings.HasPrefix(strings.TrimSpace(str), "[") && strings.HasSuffix(strings.TrimSpace(str), "]") { + if elemType.Kind() == reflect.String { + content := strings.TrimSpace(str[1 : len(str)-1]) + if content == "" { + fieldVal.Set(reflect.MakeSlice(fieldVal.Type(), 0, 0)) + return nil + } + + items := strings.Split(content, ",") + result := reflect.MakeSlice(fieldVal.Type(), len(items), len(items)) + + for i, item := range items { + cleanItem := strings.Trim(strings.TrimSpace(item), `"'`) + result.Index(i).SetString(cleanItem) + } + + fieldVal.Set(result) + return nil + } + } + + if elemType.Kind() == reflect.String { + items := strings.Split(str, ",") + result := reflect.MakeSlice(fieldVal.Type(), len(items), len(items)) + + for i, item := range items { + cleanItem := strings.TrimSpace(item) + result.Index(i).SetString(cleanItem) + } + + fieldVal.Set(result) + return nil + } + } + + elem := reflect.New(elemType).Elem() + err := setValue(elem, val) + if err != nil { + return fmt.Errorf("failed to set single element in slice: %v", err) + } + + result := reflect.MakeSlice(fieldVal.Type(), 1, 1) + result.Index(0).Set(elem) + fieldVal.Set(result) + + return nil +} + +func parseStringToInt64(s string) (int64, error) { + var i int64 + _, err := fmt.Sscanf(s, "%d", &i) + if err != nil { + return 0, fmt.Errorf("failed to parse int from string: %s", s) + } + return i, nil +} + +func parseStringToFloat64(s string) (float64, error) { + var f float64 + _, err := fmt.Sscanf(s, "%f", &f) + if err != nil { + return 0, fmt.Errorf("failed to parse float from string: %s", s) + } + return f, nil +} + +func parseStringToBool(s string) (bool, error) { + s = strings.ToLower(strings.TrimSpace(s)) + if s == "true" || s == "1" { + return true, nil + } + if s == "false" || s == "0" { + return false, nil + } + return false, fmt.Errorf("failed to parse bool from string: %s", s) +} diff --git a/core/lib/internally/config-loader/type.go b/core/lib/internally/config-loader/type.go new file mode 100644 index 0000000..15a89f1 --- /dev/null +++ b/core/lib/internally/config-loader/type.go @@ -0,0 +1,26 @@ +package cfgldrlib + +import ( + "github.com/hashicorp/vault/api" +) + +const TagName = "cfgldr" +const ValTagParam = "val=" + +type ConfigProvider string + +const ( + ConfigProviderYml ConfigProvider = "yml" + ConfigProviderVault ConfigProvider = "vault" +) + +type ConfigLoaders struct { + ConfigYml *string + ConfigProvider *ConfigProvider + VaultParams *VaultParamsT +} + +type VaultParamsT struct { + KvName *string + VaultClient *api.Client +} diff --git a/core/lib/internally/config-loader/validate.go b/core/lib/internally/config-loader/validate.go new file mode 100644 index 0000000..834b7ef --- /dev/null +++ b/core/lib/internally/config-loader/validate.go @@ -0,0 +1,40 @@ +package cfgldrlib + +import "errors" + +func validateParams(params *ConfigLoaders) error { + if params == nil { + return errors.New("params is nil") + } + if params.ConfigYml == nil && params.VaultParams == nil { + return errors.New("config yml or vault client is nil") + } + + // Проверяем VaultParams только если они предоставлены + if params.VaultParams != nil { + if params.VaultParams.KvName == nil { + return errors.New("vault kv name is nil") + } + if params.VaultParams.VaultClient == nil { + return errors.New("vault client is nil") + } + } + + return nil +} + +func loadConfigProvider(params *ConfigLoaders) (ConfigProvider, error) { + if params.ConfigProvider != nil { + return *params.ConfigProvider, nil + } + + if params.ConfigYml != nil { + return ConfigProviderYml, nil + } + + if params.VaultParams != nil && params.VaultParams.VaultClient != nil { + return ConfigProviderVault, nil + } + + return "", errors.New("config provider error detected") +} diff --git a/core/lib/internally/init.go b/core/lib/internally/init.go new file mode 100644 index 0000000..d865753 --- /dev/null +++ b/core/lib/internally/init.go @@ -0,0 +1,7 @@ +package internalservices + +import redismodule "bitrix_balancer_api/core/lib/internally/redis" + +func InitRedisModule(redisConfigObj *redismodule.RedisConfig) *redismodule.ModuleRedis { + return redismodule.GetRedisModuleInstance(redisConfigObj) +} diff --git a/core/lib/internally/redis/0_init.go b/core/lib/internally/redis/0_init.go new file mode 100644 index 0000000..f2ddb32 --- /dev/null +++ b/core/lib/internally/redis/0_init.go @@ -0,0 +1,82 @@ +package redismodule + +import ( + "fmt" + "github.com/redis/go-redis/v9" + "os" + "sync" + "time" +) + +var ( + onceRedisModule sync.Once + redisModuleInstance *ModuleRedis +) + +type ModuleRedis struct { + RedisConfig *RedisConfig + RedisClient *redis.Client +} + +func GetRedisModuleInstance(redisConfigObj *RedisConfig) *ModuleRedis { + onceRedisModule.Do(func() { + redisClient := CreateRedisClient(redisConfigObj, 0) + redisModuleInstance = &ModuleRedis{ + RedisConfig: redisConfigObj, + RedisClient: redisClient, + } + }) + return redisModuleInstance +} + +func CreateRedisClient(redisConfigObj *RedisConfig, redisNDb int) *redis.Client { + redisHost := os.Getenv("REDISHOST") + redisPort := os.Getenv("REDISPORT") + redisUser := "" + redisPassword := "" + redisConnectURI := "" + + if redisHost == "" || redisPort == "" { + redisHost = redisConfigObj.Host + redisPort = redisConfigObj.Port + } + if redisConfigObj.User != "" { + redisUser = redisConfigObj.User + } + if redisConfigObj.Password != "" { + redisPassword = redisConfigObj.Password + } else { + if redisConfigObj.ConnectURI != "" { + redisConnectURI = redisConfigObj.ConnectURI + } else { + redisConnectURI = fmt.Sprintf("%s:%s", redisHost, redisPort) + } + } + + var opts *redis.Options + if redisConnectURI != "" { + opts = &redis.Options{ + Addr: redisConnectURI, + Username: redisUser, + Password: redisPassword, + DB: redisNDb, + } + } else { // Обычное подключение + opts = &redis.Options{ + Addr: fmt.Sprintf("%s:%s", redisHost, redisPort), + Username: redisUser, + Password: redisPassword, + DB: redisNDb, + DialTimeout: 10 * time.Second, + ReadTimeout: 30 * time.Second, + WriteTimeout: 30 * time.Second, + PoolSize: 20, + PoolTimeout: 30 * time.Second, + } + } + return redis.NewClient(opts) +} + +func (m *ModuleRedis) GetClient() *redis.Client { + return m.RedisClient +} diff --git a/core/lib/internally/redis/redis_check.go b/core/lib/internally/redis/redis_check.go new file mode 100644 index 0000000..e0df130 --- /dev/null +++ b/core/lib/internally/redis/redis_check.go @@ -0,0 +1,39 @@ +package redismodule + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/redis/go-redis/v9" + "github.com/sirupsen/logrus" +) + +// Проверка и удаление временных данных данных из Redis +func (m *ModuleRedis) CheckAndDeleteFromRedis(userIdent, expectedValue, identType string) error { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + userIdentCustom := fmt.Sprintf("%s:%s", identType, userIdent) + + result, err := m.RedisClient.Get(ctx, userIdentCustom).Result() + if err == redis.Nil { + logrus.Error("🛑 error CheckAndDeleteFromRedis 1: ", err) + return errors.New("not_found") + } else if err != nil { + logrus.Error("🛑 error CheckAndDeleteFromRedis 0: ", err) + return errors.New("not_found") + } + + if result != expectedValue { + return errors.New("invalid_code") + } + + _, err = m.RedisClient.Del(ctx, userIdentCustom).Result() + if err != nil { + logrus.Error("🛑 error CheckAndDeleteFromRedis: ", err) + return errors.New("not_found") + } + return nil +} diff --git a/core/lib/internally/redis/redis_methods.go b/core/lib/internally/redis/redis_methods.go new file mode 100644 index 0000000..5e16e8b --- /dev/null +++ b/core/lib/internally/redis/redis_methods.go @@ -0,0 +1,26 @@ +package redismodule + +import ( + "context" + "github.com/redis/go-redis/v9" + "time" +) + +// Set сохраняет значение по ключу с TTL. ttl=0 — без истечения. +func (m *ModuleRedis) Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error { + return m.RedisClient.Set(ctx, key, value, ttl).Err() +} + +// Get возвращает значение по ключу. Если ключ не найден — возвращает redis.Nil. +func (m *ModuleRedis) Get(ctx context.Context, key string) (string, error) { + result, err := m.RedisClient.Get(ctx, key).Result() + if err == redis.Nil { + return "", err // пробрасываем redis.Nil как есть — caller сам решает + } + return result, err +} + +// Del удаляет ключ. Не возвращает ошибку если ключа нет. +func (m *ModuleRedis) Del(ctx context.Context, key string) error { + return m.RedisClient.Del(ctx, key).Err() +} diff --git a/core/lib/internally/redis/redis_w.go b/core/lib/internally/redis/redis_w.go new file mode 100644 index 0000000..dd23ddf --- /dev/null +++ b/core/lib/internally/redis/redis_w.go @@ -0,0 +1,42 @@ +package redismodule + +import ( + "context" + "errors" + "reflect" + "strings" + "time" + + "github.com/sirupsen/logrus" +) + +func (m *ModuleRedis) GetRedisMemoryUsage() (*RedisMemoryInfo, error) { + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + + result, err := m.RedisClient.Info(ctx, "memory").Result() + if err != nil { + logrus.Error("🛑 error GetRedisMemoryUsage: ", err) + return nil, errors.New("not_found") + } + + lines := strings.Split(result, "\n") + info := &RedisMemoryInfo{} + v := reflect.ValueOf(info).Elem() + + for _, line := range lines { + parts := strings.Split(line, ":") + if len(parts) != 2 { + logrus.Error("🛑 error GetRedisMemoryUsage: invalid line") + continue + } + + fieldName := strings.ReplaceAll(parts[0], "-", "") + field := v.FieldByName(fieldName) + if field.IsValid() && field.CanSet() && field.Kind() == reflect.String { + field.SetString(parts[1]) + } + } + + return info, nil +} diff --git a/core/lib/internally/redis/request_quota.go b/core/lib/internally/redis/request_quota.go new file mode 100644 index 0000000..a429816 --- /dev/null +++ b/core/lib/internally/redis/request_quota.go @@ -0,0 +1,109 @@ +package redismodule + +import ( + "context" + "fmt" + "github.com/redis/go-redis/v9" + "github.com/sirupsen/logrus" + "time" +) + +// Параметры Leaky Bucket из документации Bitrix24 +// Non-enterprise: X=50, Y=2/sec +// Enterprise: X=250, Y=5/sec +const ( + QuotaLimitDefault = int64(50) // порог до блокировки (X) + QuotaDecreaseDefault = int64(2) // декремент в секунду (Y) + QuotaLimitEnterprise = int64(250) + QuotaDecreaseEnterprise = int64(5) +) + +// QuotaKey — ключ счётчика в Redis для конкретного портала +func QuotaKey(portalID string) string { + return fmt.Sprintf("bitrix_quota:%s", portalID) +} + +// GetQuotaCounter возвращает текущее значение счётчика квоты +func (m *ModuleRedis) GetQuotaCounter(ctx context.Context, portalID string) (int64, error) { + val, err := m.RedisClient.Get(ctx, QuotaKey(portalID)).Int64() + if err == redis.Nil { + return 0, nil // ключа нет — счётчик нулевой + } + return val, err +} + +// GetFreeQuota возвращает сколько запросов ещё можно отправить до блокировки +func (m *ModuleRedis) GetFreeQuota(ctx context.Context, portalID string, limit int64) (int64, error) { + counter, err := m.GetQuotaCounter(ctx, portalID) + if err != nil { + return 0, err + } + free := limit - counter + if free < 0 { + free = 0 + } + return free, nil +} + +// TryAcquireQuota атомарно проверяет и инкрементит счётчик. +// Возвращает true если запрос разрешён, false если квота исчерпана. +func (m *ModuleRedis) TryAcquireQuota(ctx context.Context, portalID string, limit int64) (bool, error) { + key := QuotaKey(portalID) + + // Lua-скрипт: атомарно читаем, сравниваем и инкрементим + // Возвращает новое значение счётчика или -1 если квота исчерпана + script := redis.NewScript(` + local current = redis.call('GET', KEYS[1]) + if current == false then current = 0 else current = tonumber(current) end + if current >= tonumber(ARGV[1]) then + return -1 + end + local new = redis.call('INCR', KEYS[1]) + -- TTL 60 секунд — страховка от зависшего счётчика + redis.call('EXPIRE', KEYS[1], 60) + return new + `) + + result, err := script.Run(ctx, m.RedisClient, []string{key}, limit).Int64() + if err != nil { + return false, err + } + return result != -1, nil +} + +// DecrementQuota уменьшает счётчик на delta (вызывается background-job каждую секунду) +func (m *ModuleRedis) DecrementQuota(ctx context.Context, portalID string, delta int64) error { + key := QuotaKey(portalID) + + script := redis.NewScript(` + local current = redis.call('GET', KEYS[1]) + if current == false then return 0 end + local new = tonumber(current) - tonumber(ARGV[1]) + if new <= 0 then + redis.call('DEL', KEYS[1]) + return 0 + end + redis.call('SET', KEYS[1], new) + return new + `) + + return script.Run(ctx, m.RedisClient, []string{key}, delta).Err() +} + +// StartQuotaLeaker запускает background-job который освобождает квоту +// согласно алгоритму Leaky Bucket из документации Bitrix24. +// Вызывать один раз при старте сервера в горутине. +func (m *ModuleRedis) StartQuotaLeaker(portalID string, decreasePerSec int64) { + ticker := time.NewTicker(1 * time.Second) + defer ticker.Stop() + + logrus.Infof("🪣 QuotaLeaker started for portal %s (-%d/sec)", portalID, decreasePerSec) + + for range ticker.C { + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + if err := m.DecrementQuota(ctx, portalID, decreasePerSec); err != nil { + logrus.Errorf("🛑 QuotaLeaker: DecrementQuota: %v", err) + } + cancel() + } +} diff --git a/core/lib/internally/redis/types.go b/core/lib/internally/redis/types.go new file mode 100644 index 0000000..1e22cf1 --- /dev/null +++ b/core/lib/internally/redis/types.go @@ -0,0 +1,36 @@ +package redismodule + +type RedisConfig struct { + Host string + Port string + User string + Password string + ConnectURI string +} + +type RedisMemoryInfo struct { + UsedMemory string // Общее количество байтов, выделенных Redis + UsedMemoryHuman string // Человеко-читаемое представление UsedMemory + UsedMemoryRss string // Количество памяти, которое Redis занимает в оперативной памяти + UsedMemoryRssHuman string // Человеко-читаемое представление UsedMemoryRss + UsedMemoryPeak string // Максимальное количество памяти, использованное Redis + UsedMemoryPeakHuman string // Человеко-читаемое представление UsedMemoryPeak + UsedMemoryPeakPerc string // Процент пикового использования памяти от текущего использования + UsedMemoryOverhead string // Общее количество памяти, используемое для внутренних механизмов Redis + UsedMemoryStartup string // Количество памяти, использованное Redis при запуске + UsedMemoryDataset string // Общее количество памяти, используемое для хранения данных + UsedMemoryDatasetPerc string // Процент использования памяти, занимаемый данными + AllocatorAllocated string // Общее количество памяти, выделенное аллокатором + AllocatorActive string // Общее количество памяти, выделенное и активно используемое аллокатором + AllocatorResident string // Общее количество памяти, выделенное аллокатором и занимаемое в оперативной памяти + TotalSystemMemory string // Общее количество оперативной памяти в системе + TotalSystemMemoryHuman string // Человеко-читаемое представление TotalSystemMemory + UsedMemoryLua string // Общее количество памяти, используемое движком Lua в Redis + UsedMemoryLuaHuman string // Человеко-читаемое представление UsedMemoryLua + Maxmemory string // Максимальное количество памяти, которое Redis может использовать + MaxmemoryHuman string // Человеко-читаемое представление Maxmemory + MaxmemoryPolicy string // Политика, которую Redis будет следовать при достижении Maxmemory + MemFragmentationRatio string // Отношение памяти RSS к памяти, выделенной аллокатором + MemFragmentationBytes string // Разница между памятью RSS и памятью, выделенной аллокатором + MemAllocator string // Аллокатор, используемый Redis (jemalloc или glibc) +} diff --git a/core/securecore/hashing.go b/core/securecore/hashing.go new file mode 100644 index 0000000..6deb914 --- /dev/null +++ b/core/securecore/hashing.go @@ -0,0 +1,50 @@ +package securecore + +import ( + "encoding/hex" + "errors" + "golang.org/x/crypto/bcrypt" + "golang.org/x/crypto/sha3" +) + +// HashStringSHA3_256 вычисляет SHA‑3 (256 бит) хэш от входной строки. +func HashStringSHA3_256(input string) string { + sum := sha3.Sum256([]byte(input)) + res := hex.EncodeToString(sum[:]) + return res + // return input +} + +// HexEncode - кодирует строку в hex +func HexEncode(data []byte) string { + return hex.EncodeToString(data) + // return string(data) +} + +// HexDecode - декодирует строку из hex +func HexDecode(content string) ([]byte, error) { + return hex.DecodeString(content) + // return []byte(content), nil +} + +// Функция для проверки пароля +func CheckPasswordHash(password, hash *string) bool { + if password == nil || hash == nil { + println("CheckPasswordHash(): password or hash is nil") + return false + } + + err := bcrypt.CompareHashAndPassword([]byte(*hash), []byte(*password)) + return err == nil +} + +// Функция для хэширования пароля +func HashPassword(password *string) (*string, error) { + if password == nil { + return nil, errors.New("missed password") + } + + bytes, err := bcrypt.GenerateFromPassword([]byte(*password), bcrypt.DefaultCost) + hashedPass := string(bytes) + return &hashedPass, err +} diff --git a/core/securecore/jwt-methods.go b/core/securecore/jwt-methods.go new file mode 100644 index 0000000..c0891cc --- /dev/null +++ b/core/securecore/jwt-methods.go @@ -0,0 +1,95 @@ +package securecore + +import ( + "bitrix_balancer_api/core/typescore" + "errors" + "github.com/golang-jwt/jwt/v5" + + "time" +) + +// Определить пользовательский тип для контекстных ключей +type contextKey string + +func (c contextKey) String() string { + return string(c) +} + +const AddressContextKey contextKey = "raw_user_address" +const IDContextKey contextKey = "user_id" +const AccessContextKey contextKey = "access_code" +const IpContextKey contextKey = "user_ip" +const expContextKey contextKey = "exp" + +func GenerateTokenJWT( + userAddr string, + userID uint64, + userIP string, + secretJWT string, + sessionTime int, +) (string, error) { + duration := time.Duration(72) + if sessionTime > 0 { + duration = time.Duration(sessionTime) + } + // Создаем новый токен + token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ + AddressContextKey.String(): userAddr, + IDContextKey.String(): float64(userID), + IpContextKey.String(): userIP, + expContextKey.String(): time.Now().Add(time.Hour * duration).Unix(), // срок действия токена 72 часа + }) + + t, err := token.SignedString([]byte(secretJWT)) + if err != nil { + return "", err + } + + return t, nil +} + +// VerifyToken верифицирует JWT токен и возвращает данные по токену или ошибку +func VerifyToken(tokenString string, jwtSecret string) (*jwt.Token, jwt.MapClaims, error) { + token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { + if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { + return nil, errors.New("unexpected signing method") + } + return []byte(jwtSecret), nil + }) + + if err != nil || !token.Valid { + return nil, nil, errors.New("invalid token") + } + + claims, ok := token.Claims.(jwt.MapClaims) + if !ok { + return nil, nil, errors.New("invalid token claims") + } + + if exp, ok := claims[expContextKey.String()].(float64); ok { + if time.Unix(int64(exp), 0).Before(time.Now()) { + return nil, nil, errors.New("token expired") + } + } + + return token, claims, nil +} + +func IsSameIP(ip1, ip2 string) bool { + // Простое сравнение для начала + return ip1 == ip2 +} + +func FindDeviceID(deviceList []typescore.DeviceList, deviceID string) bool { + if len(deviceList) == 0 { + return false + } + + for _, device := range deviceList { + if device.DeviceID == deviceID { + return true + } + } + + return false +} 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/approval.go b/core/typescore/approval.go new file mode 100644 index 0000000..0750cc9 --- /dev/null +++ b/core/typescore/approval.go @@ -0,0 +1,81 @@ +package typescore + +import ( + "encoding/json" + "time" +) + +type ApprovalStatus string + +const ( + ApprovalStatusApproved ApprovalStatus = "approved" + ApprovalStatusRejected ApprovalStatus = "rejected" + ApprovalStatusDraft ApprovalStatus = "draft" + ApprovalStatusRevoked ApprovalStatus = "revoked" + ApprovalStatusRevision ApprovalStatus = "revision" + ApprovalStatusPending ApprovalStatus = "pending" +) + +func (status ApprovalStatus) String() string { + return string(status) +} + +// Approval — заявка на согласование. +// Status: draft | pending | approved | rejected | revoked +// DepartmentID копируется с инициатора в момент создания — для отчётов и изоляции без JOIN. +// FileBase64 и FileName заполняются только если ApprovalTopic.AllowsFile = true. +type Approval struct { + ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"` + InitiatorID *uint64 `gorm:"type:bigint;not null;index;column:initiator_id" json:"initiator_id" db:"initiator_id" mapstructure:"initiator_id"` + TopicID *uint64 `gorm:"type:bigint;not null;index;column:topic_id" json:"topic_id" db:"topic_id" mapstructure:"topic_id"` + DepartmentID *uint64 `gorm:"type:bigint;not null;index;column:department_id" json:"department_id" db:"department_id" mapstructure:"department_id"` // снимок отдела на момент создания + Content *string `gorm:"type:text;not null;column:content" json:"content" db:"content" mapstructure:"content"` // введённые пользователем данные по шаблону + Status *string `gorm:"type:text;not null;default:'pending';index;column:status" json:"status" db:"status" mapstructure:"status"` + RevokedByID *uint64 `gorm:"type:bigint;index;column:revoked_by_id" json:"revoked_by_id,omitempty" db:"revoked_by_id" mapstructure:"revoked_by_id"` + RevokedAt *time.Time `gorm:"type:timestamp;column:revoked_at" json:"revoked_at,omitempty" db:"revoked_at"` + CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"` + UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at"` + Metadata *string `gorm:"type:jsonb;column:metadata" json:"metadata,omitempty" db:"metadata"` + RevisionComment *string `gorm:"type:text;column:revision_comment" json:"revision_comment,omitempty" db:"revision_comment"` + RevisionByID *uint64 `gorm:"type:bigint;column:revision_by_id" json:"revision_by_id,omitempty" db:"revision_by_id"` + RevisionAt *time.Time `gorm:"type:timestamp;column:revision_at" json:"revision_at,omitempty" db:"revision_at"` + RevisionCount *int `gorm:"type:int;not null;default:0;column:revision_count" json:"revision_count" db:"revision_count"` + + Files []*ApprovalFile `gorm:"-" json:"files,omitempty"` + Initiator *User `gorm:"-" json:"initiator,omitempty"` + Topic *ApprovalTopic `gorm:"-" json:"topic,omitempty"` + Department *Department `gorm:"-" json:"department,omitempty"` + RevokedBy *User `gorm:"-" json:"revoked_by,omitempty"` + Steps []*ApprovalStep `gorm:"-" json:"steps,omitempty"` +} + +type ApprovalMetadata struct { + // Выбранные системы при мультиселекте, например ["okb","bitrix"] + SelectedSystems []string `json:"selected_systems,omitempty"` + // Регион + Region string `json:"region,omitempty"` + // Тип изменения + ChangeType string `json:"change_type,omitempty"` + // Любые другие поля из collected которые нужно сохранить + Extra map[string]string `json:"extra,omitempty"` +} + +func (m *ApprovalMetadata) ToJSON() (*string, error) { + b, err := json.Marshal(m) + if err != nil { + return nil, err + } + s := string(b) + return &s, nil +} + +func ParseApprovalMetadata(raw *string) (*ApprovalMetadata, error) { + if raw == nil || *raw == "" { + return &ApprovalMetadata{}, nil + } + var m ApprovalMetadata + if err := json.Unmarshal([]byte(*raw), &m); err != nil { + return nil, err + } + return &m, nil +} diff --git a/core/typescore/approval_additional_approver.go b/core/typescore/approval_additional_approver.go new file mode 100644 index 0000000..2194d19 --- /dev/null +++ b/core/typescore/approval_additional_approver.go @@ -0,0 +1,19 @@ +package typescore + +import "time" + +type ApprovalAdditionalApprover struct { + ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" json:"id" db:"id"` + ApprovalID *uint64 `gorm:"type:bigint;not null;index;column:approval_id" json:"approval_id" db:"approval_id"` + ApproverID *uint64 `gorm:"type:bigint;not null;index;column:approver_id" json:"approver_id" db:"approver_id"` + AddedByID *uint64 `gorm:"type:bigint;not null;column:added_by_id" json:"added_by_id" db:"added_by_id"` + Status *string `gorm:"type:text;not null;default:'pending';column:status" json:"status" db:"status"` + Comment *string `gorm:"type:text;column:comment" json:"comment,omitempty" db:"comment"` + ActedAt *time.Time `gorm:"type:timestamp;column:acted_at" json:"acted_at,omitempty" db:"acted_at"` + CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"` + UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at"` + + Approval *Approval `gorm:"-" json:"approval,omitempty"` + Approver *User `gorm:"-" json:"approver,omitempty"` + AddedBy *User `gorm:"-" json:"added_by,omitempty"` +} diff --git a/core/typescore/approval_additional_observer.go b/core/typescore/approval_additional_observer.go new file mode 100644 index 0000000..1daf440 --- /dev/null +++ b/core/typescore/approval_additional_observer.go @@ -0,0 +1,15 @@ +package typescore + +import "time" + +type ApprovalAdditionalObserver struct { + ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" json:"id" db:"id"` + ApprovalID *uint64 `gorm:"type:bigint;not null;index;column:approval_id" json:"approval_id" db:"approval_id"` + UserID *uint64 `gorm:"type:bigint;not null;index;column:user_id" json:"user_id" db:"user_id"` + AddedByID *uint64 `gorm:"type:bigint;not null;index;column:added_by_id" json:"added_by_id" db:"added_by_id"` + CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"` + + User *User `gorm:"-" json:"user,omitempty"` + AddedBy *User `gorm:"-" json:"added_by,omitempty"` + Approval *Approval `gorm:"-" json:"approval,omitempty"` +} diff --git a/core/typescore/approval_comment.go b/core/typescore/approval_comment.go new file mode 100644 index 0000000..754a50f --- /dev/null +++ b/core/typescore/approval_comment.go @@ -0,0 +1,15 @@ +package typescore + +import "time" + +type ApprovalComment struct { + ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" json:"id" db:"id"` + ApprovalID *uint64 `gorm:"type:bigint;not null;index;column:approval_id" json:"approval_id" db:"approval_id"` + UserID *uint64 `gorm:"type:bigint;not null;index;column:user_id" json:"user_id" db:"user_id"` + Comment *string `gorm:"type:text;not null;column:comment" json:"comment" db:"comment"` + CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"` + UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at"` + + Approval *Approval `gorm:"-" json:"approval,omitempty"` + User *User `gorm:"-" json:"user,omitempty"` +} diff --git a/core/typescore/approval_delegation.go b/core/typescore/approval_delegation.go new file mode 100644 index 0000000..03e9aae --- /dev/null +++ b/core/typescore/approval_delegation.go @@ -0,0 +1,22 @@ +package typescore + +import "time" + +type ApprovalDelegation struct { + ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" json:"id" db:"id"` + DelegatorID *uint64 `gorm:"type:bigint;not null;index;column:delegator_id" json:"delegator_id" db:"delegator_id"` + DelegateID *uint64 `gorm:"type:bigint;not null;index;column:delegate_id" json:"delegate_id" db:"delegate_id"` + CategoryID *uint64 `gorm:"type:bigint;index;column:category_id" json:"category_id,omitempty" db:"category_id"` + TopicID *uint64 `gorm:"type:bigint;index;column:topic_id" json:"topic_id,omitempty" db:"topic_id"` + ValidUntil *time.Time `gorm:"type:timestamp;not null;column:valid_until" json:"valid_until" db:"valid_until"` + IsActive *bool `gorm:"type:boolean;not null;default:true;column:is_active" json:"is_active" db:"is_active"` + NotifiedDay *bool `gorm:"type:boolean;not null;default:false;column:notified_day" json:"notified_day" db:"notified_day"` + Notified2h *bool `gorm:"type:boolean;not null;default:false;column:notified_2h" json:"notified_2h" db:"notified_2h"` + CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"` + UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at"` + + Delegator *User `gorm:"-" json:"delegator,omitempty"` + Delegate *User `gorm:"-" json:"delegate,omitempty"` + Category *ApprovalTopicCategory `gorm:"-" json:"category,omitempty"` + Topic *ApprovalTopic `gorm:"-" json:"topic,omitempty"` +} diff --git a/core/typescore/approval_file.go b/core/typescore/approval_file.go new file mode 100644 index 0000000..fe9d03e --- /dev/null +++ b/core/typescore/approval_file.go @@ -0,0 +1,13 @@ +package typescore + +import "time" + +type ApprovalFile struct { + ID *uint64 `gorm:"column:id;autoIncrement;not null;unique" json:"id" db:"id"` + ApprovalID *uint64 `gorm:"type:bigint;not null;index;column:approval_id" json:"approval_id" db:"approval_id"` + FileBase64 *string `gorm:"type:text;not null;column:file_base64" json:"file_base64" db:"file_base64"` + FileName *string `gorm:"type:text;not null;column:file_name" json:"file_name" db:"file_name"` + AttachedByID *uint64 `gorm:"type:bigint;index;column:attached_by_id" json:"attached_by_id" db:"attached_by_id"` + TaskID *uint64 `gorm:"type:bigint;index;column:task_id" json:"task_id,omitempty" db:"task_id"` + CreatedAt *time.Time `gorm:"default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"` +} diff --git a/core/typescore/approval_step.go b/core/typescore/approval_step.go new file mode 100644 index 0000000..b9cb1c1 --- /dev/null +++ b/core/typescore/approval_step.go @@ -0,0 +1,27 @@ +package typescore + +import "time" + +// ApprovalStep — один шаг согласования. +// Status: pending | approved | rejected +// Comment заполняется согласующим при отклонении (может быть пустым). +// StepOrder определяет порядок (1 = первый согласующий). +// ApproverNameSnapshot и ApproverDepartmentSnapshot — снимок данных согласующего +// на момент действия, чтобы отчёты не ломались при изменении оргструктуры. +type ApprovalStep struct { + ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"` + ApprovalID *uint64 `gorm:"type:bigint;not null;index;column:approval_id" json:"approval_id" db:"approval_id" mapstructure:"approval_id"` + ApproverID *uint64 `gorm:"type:bigint;not null;index;column:approver_id" json:"approver_id" db:"approver_id" mapstructure:"approver_id"` + StepOrder *int `gorm:"type:int;not null;column:step_order" json:"step_order" db:"step_order" mapstructure:"step_order"` + Status *string `gorm:"type:text;not null;default:'pending';index;column:status" json:"status" db:"status" mapstructure:"status"` + Comment *string `gorm:"type:text;column:comment" json:"comment,omitempty" db:"comment" mapstructure:"comment"` + ApproverNameSnapshot *string `gorm:"type:text;column:approver_name_snapshot" json:"approver_name_snapshot,omitempty" db:"approver_name_snapshot" mapstructure:"approver_name_snapshot"` + ApproverDepartmentSnapshot *string `gorm:"type:text;column:approver_department_snapshot" json:"approver_department_snapshot,omitempty" db:"approver_department_snapshot" mapstructure:"approver_department_snapshot"` + ActedAt *time.Time `gorm:"type:timestamp;column:acted_at" json:"acted_at,omitempty" db:"acted_at"` + CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"` + UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at"` + ReturnedAt *time.Time `gorm:"type:timestamp;column:returned_at" json:"returned_at,omitempty" db:"returned_at"` + + Approval *Approval `gorm:"-" json:"approval,omitempty"` + Approver *User `gorm:"-" json:"approver,omitempty"` +} diff --git a/core/typescore/approval_task.go b/core/typescore/approval_task.go new file mode 100644 index 0000000..afc36f8 --- /dev/null +++ b/core/typescore/approval_task.go @@ -0,0 +1,20 @@ +package typescore + +import "time" + +type ApprovalTask struct { + ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" json:"id" db:"id"` + ApprovalID *uint64 `gorm:"type:bigint;not null;index;column:approval_id" json:"approval_id" db:"approval_id"` + ExecutorID *uint64 `gorm:"type:bigint;not null;index;column:executor_id" json:"executor_id" db:"executor_id"` + TaskText *string `gorm:"type:text;not null;column:task_text" json:"task_text" db:"task_text"` + Status *string `gorm:"type:text;not null;default:'pending';index;column:status" json:"status" db:"status"` + StepOrder *int `gorm:"type:int;default:0;column:step_order" json:"step_order" db:"step_order"` + RequireFile *bool `gorm:"type:boolean;default:false;column:require_file" json:"require_file" db:"require_file"` + TopicExecutorID *uint64 `gorm:"type:bigint;column:topic_executor_id" json:"topic_executor_id,omitempty" db:"topic_executor_id"` + CompletedAt *time.Time `gorm:"type:timestamp;column:completed_at" json:"completed_at,omitempty" db:"completed_at"` + CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"` + UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at"` + + Approval *Approval `gorm:"-" json:"approval,omitempty"` + Executor *User `gorm:"-" json:"executor,omitempty"` +} diff --git a/core/typescore/approval_task_assigment.go b/core/typescore/approval_task_assigment.go new file mode 100644 index 0000000..0a805db --- /dev/null +++ b/core/typescore/approval_task_assigment.go @@ -0,0 +1,14 @@ +package typescore + +import "time" + +type ApprovalTaskAssignment struct { + ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique"` + ApprovalID *uint64 `gorm:"type:bigint;not null;index;column:approval_id"` + ExecutorID *uint64 `gorm:"type:bigint;not null;index;column:executor_id"` + TaskText *string `gorm:"type:text;not null;column:task_text"` + Status *string `gorm:"type:text;not null;default:'pending';column:status"` // pending|completed|cancelled + CompletedAt *time.Time `gorm:"type:timestamp;column:completed_at"` + CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at"` + UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at"` +} diff --git a/core/typescore/approval_topic.go b/core/typescore/approval_topic.go new file mode 100644 index 0000000..5294fd1 --- /dev/null +++ b/core/typescore/approval_topic.go @@ -0,0 +1,38 @@ +package typescore + +import "time" + +// ApprovalTopic — конкретная тема внутри категории. +// DurationType: single_day | date_range | multi_day +// TimeType: full_day | partial +// PaymentType: own_expense | vacation_account | not_applicable (для partial) +// Template хранит шаблон строки для подсказки пользователю при вводе. +type ApprovalTopic struct { + ID *uint64 `gorm:"column:id;index;type:bigserial;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"` + CategoryID *uint64 `gorm:"type:bigint;not null;index;column:category_id" json:"category_id" db:"category_id" mapstructure:"category_id"` + Name *string `gorm:"type:text;not null;column:name" json:"name" db:"name" mapstructure:"name"` + Code *string `gorm:"type:text;not null;unique;column:code" json:"code" db:"code" mapstructure:"code"` + ApprovalMode *string `gorm:"type:text;default:'sequential';column:approval_mode" db:"approval_mode"` + // sequential — последовательно (текущее поведение) + // any_of — любой из согласующих (задача 10) + + DurationType *string `gorm:"type:text;column:duration_type" json:"duration_type,omitempty" db:"duration_type" mapstructure:"duration_type"` + TimeType *string `gorm:"type:text;column:time_type" json:"time_type,omitempty" db:"time_type" mapstructure:"time_type"` + PaymentType *string `gorm:"type:text;column:payment_type" json:"payment_type,omitempty" db:"payment_type" mapstructure:"payment_type"` + Template *string `gorm:"type:text;column:template" json:"template" db:"template" mapstructure:"template"` + FirstApproverRoleCode *string `gorm:"type:text;column:first_approver_role_code" json:"first_approver_role_code,omitempty" db:"first_approver_role_code" mapstructure:"first_approver_role_code"` // если задан — первый согласующий выбирается из этой роли + + AllowsFile *bool `gorm:"type:boolean;not null;default:false;column:allows_file" json:"allows_file,omitempty" db:"allows_file" mapstructure:"allows_file"` + AllowApproverSelection *bool `gorm:"type:boolean;not null;default:false;column:allow_approver_selection" json:"allow_approver_selection,omitempty" db:"allow_approver_selection" mapstructure:"allow_approver_selection"` + AllowObserverSelection *bool `gorm:"type:boolean;not null;default:false;column:allow_observer_selection" json:"allow_observer_selection,omitempty" db:"allow_observer_selection" mapstructure:"allow_observer_selection"` + + RequireApproverComment *bool `gorm:"type:boolean;default:false;column:require_approver_comment" json:"require_approver_comment" db:"require_approver_comment"` + RequiresFile *bool `gorm:"type:boolean;not null;default:false;column:requires_file" json:"requires_file" db:"requires_file"` + RequireObserverSelection *bool `gorm:"type:boolean;not null;default:false;column:require_observer_selection" json:"require_observer_selection" db:"require_observer_selection"` + + IsActive *bool `gorm:"type:boolean;not null;default:true;column:is_active" json:"is_active" db:"is_active" mapstructure:"is_active"` + CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"` + UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at"` + Instructions *string `gorm:"type:text;column:instructions" json:"instructions,omitempty" db:"instructions"` + Category *ApprovalTopicCategory `gorm:"-" json:"category,omitempty"` +} diff --git a/core/typescore/approval_topic_category.go b/core/typescore/approval_topic_category.go new file mode 100644 index 0000000..735d5c3 --- /dev/null +++ b/core/typescore/approval_topic_category.go @@ -0,0 +1,15 @@ +package typescore + +import "time" + +type ApprovalTopicCategory struct { + ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"` + Name *string `gorm:"type:text;not null;column:name" json:"name" db:"name" mapstructure:"name"` + Code *string `gorm:"type:text;not null;unique;column:code" json:"code" db:"code" mapstructure:"code"` // otgul, vacation, sick_leave + Description *string `gorm:"type:text;column:description" json:"description,omitempty" db:"description" mapstructure:"description"` + IsActive *bool `gorm:"type:boolean;not null;default:true;column:is_active" json:"is_active" db:"is_active" mapstructure:"is_active"` + CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"` + UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at"` + + Topics []*ApprovalTopic `gorm:"-" json:"topics,omitempty"` +} diff --git a/core/typescore/approval_topic_executor.go b/core/typescore/approval_topic_executor.go new file mode 100644 index 0000000..c377da3 --- /dev/null +++ b/core/typescore/approval_topic_executor.go @@ -0,0 +1,19 @@ +package typescore + +import "time" + +type ApprovalTopicExecutor struct { + ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"` + TopicID *uint64 `gorm:"type:bigint;not null;index;column:topic_id" json:"topic_id" db:"topic_id" mapstructure:"topic_id"` + UserID *uint64 `gorm:"type:bigint;not null;index;column:user_id" json:"user_id" db:"user_id" mapstructure:"user_id"` + StepOrder *int `gorm:"type:int;not null;default:0;column:step_order" json:"step_order" db:"step_order" mapstructure:"step_order"` + RequireFile *bool `gorm:"type:boolean;default:false;column:require_file" json:"require_file" db:"require_file" mapstructure:"require_file"` + TargetSystem *string `gorm:"type:text;column:target_system" json:"target_system,omitempty" db:"target_system" mapstructure:"target_system"` + TaskText *string `gorm:"type:text;column:task_text" json:"task_text,omitempty" db:"task_text" mapstructure:"task_text"` + IsActive *bool `gorm:"type:boolean;default:true;column:is_active" json:"is_active" db:"is_active" mapstructure:"is_active"` + CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"` + UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at"` + + Topic *ApprovalTopic `gorm:"-" json:"topic,omitempty"` + User *User `gorm:"-" json:"user,omitempty"` +} diff --git a/core/typescore/balancer.go b/core/typescore/balancer.go new file mode 100644 index 0000000..37c2f21 --- /dev/null +++ b/core/typescore/balancer.go @@ -0,0 +1,36 @@ +package typescore + +// BalancerRequest — тело запроса на /api/balancer/send +type BalancerRequest struct { + URL *string `json:"url"` // URL метода Bitrix24 + Method *string `json:"method"` // HTTP метод (GET, POST) + Headers map[string]string `json:"headers,omitempty"` // Заголовки для Bitrix24 + Body map[string]interface{} `json:"body,omitempty"` // Тело запроса + + // IsRecurrent — если true, бэк автоматически загружает ВСЕ записи + // постранично (по 50 за запрос) и возвращает одним массивом. + // Nil/false = обычный разовый запрос. + IsRecurrent bool `json:"is_recurrent,omitempty"` + + // ResultKey — ключ внутри result где лежит массив. + // "tasks" для tasks.task.list, пусто для crm.lead.list и др. + ResultKey *string `json:"result_key,omitempty"` +} + +// BalancerResponse — ответ от Bitrix24 проксированный клиенту +type BalancerResponse struct { + StatusCode *int `json:"status_code"` + Body interface{} `json:"body"` + QuotaLeft *int64 `json:"quota_left"` + IsRecurrent bool `json:"is_recurrent,omitempty"` + TotalFetched *int `json:"total_fetched,omitempty"` +} + +// QuotaResponse — ответ на /api/balancer/quota +type QuotaResponse struct { + PortalID *string `json:"portal_id"` + Counter *int64 `json:"counter"` // текущий счётчик + Limit *int64 `json:"limit"` // порог блокировки (X) + FreeSlots *int64 `json:"free_slots"` // доступные слоты + DecreasePerSec *int64 `json:"decrease_per_sec"` // скорость освобождения (Y) +} diff --git a/core/typescore/base_db.go b/core/typescore/base_db.go new file mode 100644 index 0000000..34e249d --- /dev/null +++ b/core/typescore/base_db.go @@ -0,0 +1,22 @@ +package typescore + +import "time" + +// объединяет общие параметры запроса. +type ListDbOptions struct { + Filtering interface{} + LikeFields map[string]string + Offset *uint64 + Limit *uint64 + FromDate *time.Time + ToDate *time.Time + NotNullFields map[string]bool // поля, не нулевые(при запросе ставит where на эти поля not null) bool-true для числовых полей + SortingParams map[string]string // поля, по которым сортируется + SortBy string // поля, по которым сортируется +} + +type InsertOptions struct { + Prefix string // Префикс для запроса (например, WITH) + Suffix string // Суффикс для запроса (например, ON CONFLICT, RETURNING) + IgnoreConflict bool // Флаг игнорирования конфликтов +} diff --git a/core/typescore/department.go b/core/typescore/department.go new file mode 100644 index 0000000..b05c930 --- /dev/null +++ b/core/typescore/department.go @@ -0,0 +1,13 @@ +package typescore + +import "time" + +type Department struct { + ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"` + Name *string `gorm:"type:text;not null;column:name" json:"name" db:"name" mapstructure:"name"` + Code *string `gorm:"type:text;not null;unique;column:code" json:"code" db:"code" mapstructure:"code"` // finance, hr, it + Description *string `gorm:"type:text;column:description" json:"description,omitempty" db:"description" mapstructure:"description"` + IsActive *bool `gorm:"type:boolean;not null;default:true;column:is_active" json:"is_active" db:"is_active" mapstructure:"is_active"` + CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"` + UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at"` +} diff --git a/core/typescore/handler.go b/core/typescore/handler.go new file mode 100644 index 0000000..17334a3 --- /dev/null +++ b/core/typescore/handler.go @@ -0,0 +1,9 @@ +package typescore + +type Response struct { + Success bool `json:"success"` + Data interface{} `json:"data,omitempty"` + Error error `json:"error,omitempty"` + Count int `json:"count,omitempty"` + TotalCount *uint64 `json:"total_count,omitempty"` +} diff --git a/core/typescore/permission.go b/core/typescore/permission.go new file mode 100644 index 0000000..ed8cf09 --- /dev/null +++ b/core/typescore/permission.go @@ -0,0 +1,21 @@ +package typescore + +import "time" + +// Permission — право роли на действие в рамках категории или конкретной темы. +// Action: create | read | update | delete | approve | revoke +// Если TopicCategoryID заполнен, а TopicID = nil — право на все темы категории. +// Если TopicID заполнен — право только на конкретную тему. +type Permission struct { + ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"` + RoleID *uint64 `gorm:"type:bigint;not null;index;column:role_id" json:"role_id" db:"role_id" mapstructure:"role_id"` + TopicCategoryID *uint64 `gorm:"type:bigint;index;column:topic_category_id" json:"topic_category_id,omitempty" db:"topic_category_id" mapstructure:"topic_category_id"` + TopicID *uint64 `gorm:"type:bigint;index;column:topic_id" json:"topic_id,omitempty" db:"topic_id" mapstructure:"topic_id"` + Action *string `gorm:"type:text;not null;column:action" json:"action" db:"action" mapstructure:"action"` + CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"` + UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at"` + + Role *Role `gorm:"-" json:"role,omitempty"` + TopicCategory *ApprovalTopicCategory `gorm:"-" json:"topic_category,omitempty"` + Topic *ApprovalTopic `gorm:"-" json:"topic,omitempty"` +} diff --git a/core/typescore/report.go b/core/typescore/report.go new file mode 100644 index 0000000..bc61490 --- /dev/null +++ b/core/typescore/report.go @@ -0,0 +1,20 @@ +package typescore + +import "time" + +// ReportFilter — фильтр для выгрузки отчёта по согласованиям +type ReportFilter struct { + AllAccess bool // true для директора (видит всё) + UserID *uint64 // ID пользователя для фильтрации по ролям + CategoryCodes []string // DEPRECATED: теперь не используется, роли определяются через UserID + DateFrom *time.Time // начало периода + DateTo *time.Time // конец периода +} + +// TaskReportFilter — фильтр для выгрузки отчёта по задачам +type TaskReportFilter struct { + AllAccess bool // true для директора (видит всё) + UserID *uint64 // ID пользователя для фильтрации по ролям + DateFrom *time.Time // начало периода + DateTo *time.Time // конец периода +} diff --git a/core/typescore/role.go b/core/typescore/role.go new file mode 100644 index 0000000..a9445d6 --- /dev/null +++ b/core/typescore/role.go @@ -0,0 +1,19 @@ +package typescore + +import "time" + +type Role struct { + ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"` + Name *string `gorm:"type:text;not null;column:name" json:"name" db:"name" mapstructure:"name"` + Code *string `gorm:"type:text;not null;unique;column:code" json:"code" db:"code" mapstructure:"code"` + IsDefault *bool `gorm:"type:boolean;not null;default:false;column:is_default" json:"is_default" db:"is_default" mapstructure:"is_default"` + IsDirector *bool `gorm:"type:boolean;not null;default:false;column:is_director" json:"is_director" db:"is_director" mapstructure:"is_director"` + IsApprover *bool `gorm:"type:boolean;not null;default:false;column:is_approver" json:"is_approver" db:"is_approver" mapstructure:"is_approver"` + IsObserver *bool `gorm:"type:boolean;not null;default:false;column:is_observer" json:"is_observer" db:"is_observer" mapstructure:"is_observer"` + IsExecutor *bool `gorm:"type:boolean;not null;default:false;column:is_executor" json:"is_executor" db:"is_executor" mapstructure:"is_executor"` + Description *string `gorm:"type:text;column:description" json:"description,omitempty" db:"description" mapstructure:"description"` + CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"` + UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at"` + + Permissions []*Permission `gorm:"-" json:"permissions,omitempty"` +} diff --git a/core/typescore/suggestion.go b/core/typescore/suggestion.go new file mode 100644 index 0000000..eb287ea --- /dev/null +++ b/core/typescore/suggestion.go @@ -0,0 +1,30 @@ +package typescore + +import "time" + +type Suggestion struct { + ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" json:"id" db:"id"` + InitiatorID *uint64 `gorm:"type:bigint;not null;index;column:initiator_id" json:"initiator_id" db:"initiator_id"` + DirectorID *uint64 `gorm:"type:bigint;not null;index;column:director_id" json:"director_id" db:"director_id"` + Subject *string `gorm:"type:text;not null;column:subject" json:"subject" db:"subject"` + Status *string `gorm:"type:text;not null;default:'open';column:status" json:"status" db:"status"` // open, closed + CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"` + UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at"` + + Initiator *User `gorm:"-" json:"initiator,omitempty"` + Director *User `gorm:"-" json:"director,omitempty"` + Messages []*SuggestionMessage `gorm:"-" json:"messages,omitempty"` +} + +type SuggestionMessage struct { + ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" json:"id" db:"id"` + SuggestionID *uint64 `gorm:"type:bigint;not null;index;column:suggestion_id" json:"suggestion_id" db:"suggestion_id"` + UserID *uint64 `gorm:"type:bigint;not null;index;column:user_id" json:"user_id" db:"user_id"` + Message *string `gorm:"type:text;not null;column:message" json:"message" db:"message"` + FileData *string `gorm:"type:text;column:file_data" json:"file_data,omitempty" db:"file_data"` // base64 + FileName *string `gorm:"type:text;column:file_name" json:"file_name,omitempty" db:"file_name"` + CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"` + + Suggestion *Suggestion `gorm:"-" json:"suggestion,omitempty"` + User *User `gorm:"-" json:"user,omitempty"` +} diff --git a/core/typescore/user.go b/core/typescore/user.go new file mode 100644 index 0000000..a2219d6 --- /dev/null +++ b/core/typescore/user.go @@ -0,0 +1,31 @@ +package typescore + +import "time" + +type User struct { + ID *uint64 `gorm:"column:id;index;type:bigserial;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"` + TelegramID *int64 `gorm:"type:numeric;not null;unique;column:telegram_id" json:"telegram_id" db:"telegram_id" mapstructure:"telegram_id"` + Username *string `gorm:"type:text;column:username" json:"username,omitempty" db:"username" mapstructure:"username"` + FullName *string `gorm:"type:text;not null;column:full_name" json:"full_name" db:"full_name" mapstructure:"full_name"` + //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"` + LanguageCode *string `gorm:"type:text;not null;default:'ru';column:language_code" json:"language_code" db:"language_code" mapstructure:"language_code"` + DepartmentID *uint64 `gorm:"type:bigint;index;column:department_id" json:"department_id,omitempty" db:"department_id" mapstructure:"department_id"` + IsBlocked *bool `gorm:"type:boolean;not null;default:false;index;column:is_blocked" json:"is_blocked" db:"is_blocked" mapstructure:"is_blocked"` + IsFired *bool `gorm:"type:boolean;not null;default:false;index;column:is_fired" json:"is_fired" db:"is_fired" mapstructure:"is_fired"` + BlockedAt *time.Time `gorm:"type:timestamp;column:blocked_at" json:"blocked_at,omitempty" db:"blocked_at"` + LastLogin *time.Time `gorm:"type:timestamp;column:last_login" json:"last_login,omitempty" db:"last_login"` + CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"` + UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at"` + + 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_auth.go b/core/typescore/user_auth.go new file mode 100644 index 0000000..640baf5 --- /dev/null +++ b/core/typescore/user_auth.go @@ -0,0 +1,12 @@ +package typescore + +import "time" + +type UserAuth struct { + ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"` + UserID *uint64 `gorm:"type:bigint;not null;index;column:user_id" json:"user_id" db:"user_id" mapstructure:"user_id"` + PasswordHash *string `gorm:"type:text;not null;column:password_hash" json:"password_hash" db:"password_hash"` + Salt *string `gorm:"type:text;not null;column:salt" json:"-" db:"salt"` + CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"` + UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at"` +} diff --git a/core/typescore/user_hierarchy.go b/core/typescore/user_hierarchy.go new file mode 100644 index 0000000..1ecac90 --- /dev/null +++ b/core/typescore/user_hierarchy.go @@ -0,0 +1,22 @@ +package typescore + +import "time" + +// UserHierarchy — связь подчинённого и его согласующего. +// Согласующий может быть привязан к нескольким отделам через разные записи. +// Priority определяет порядок шагов согласования (1 = первый). +type UserHierarchy struct { + ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"` + SubordinateID *uint64 `gorm:"type:bigint;not null;index;column:subordinate_id" json:"subordinate_id" db:"subordinate_id" mapstructure:"subordinate_id"` + ApproverID *uint64 `gorm:"type:bigint;not null;index;column:approver_id" json:"approver_id" db:"approver_id" mapstructure:"approver_id"` + DepartmentID *uint64 `gorm:"type:bigint;not null;index;column:department_id" json:"department_id" db:"department_id" mapstructure:"department_id"` + TopicCategoryID *uint64 `gorm:"type:bigint;index;column:topic_category_id" json:"topic_category_id,omitempty" db:"topic_category_id" mapstructure:"topic_category_id"` + TopicID *uint64 `gorm:"type:bigint;index;column:topic_id" json:"topic_id,omitempty" db:"topic_id" mapstructure:"topic_id"` + Priority *int `gorm:"type:int;not null;default:1;column:priority" json:"priority" db:"priority" mapstructure:"priority"` + CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"` + UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at"` + + Subordinate *User `gorm:"-" json:"subordinate,omitempty"` + Approver *User `gorm:"-" json:"approver,omitempty"` + Department *Department `gorm:"-" json:"department,omitempty"` +} diff --git a/core/typescore/user_role.go b/core/typescore/user_role.go new file mode 100644 index 0000000..5058fae --- /dev/null +++ b/core/typescore/user_role.go @@ -0,0 +1,16 @@ +package typescore + +import "time" + +// UserRole — связь пользователя с ролью. +// Один пользователь может иметь несколько ролей (например, сотрудник и согласующий одновременно). +type UserRole struct { + ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"` // Автоматически заполняемое уникальное поле для большого числа записей + UserID *uint64 `gorm:"type:bigint;not null;index;column:user_id" json:"user_id" db:"user_id" mapstructure:"user_id"` + RoleID *uint64 `gorm:"type:bigint;not null;index;column:role_id" json:"role_id" db:"role_id" mapstructure:"role_id"` + CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"` + UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at"` + + User *User `gorm:"-" json:"user,omitempty"` // ← добавить gorm:"-" + Role *Role `gorm:"-" json:"role,omitempty"` // ← добавить gorm:"-" +} diff --git a/core/typescore/user_sessions.go b/core/typescore/user_sessions.go new file mode 100644 index 0000000..8f6f3ad --- /dev/null +++ b/core/typescore/user_sessions.go @@ -0,0 +1,14 @@ +package typescore + +import "time" + +type DeviceList struct { + DeviceID string `json:"device_id"` + CreatedAt *time.Time `json:"created_at"` +} + +type UsersSessions struct { + UserID *uint64 `json:"user_id,omitempty"` + AuthorizedDevices []DeviceList `json:"authorized_devices"` + LastIP string `json:"last_ip"` +} diff --git a/core/utilscore/conversion.go b/core/utilscore/conversion.go new file mode 100644 index 0000000..3d14c64 --- /dev/null +++ b/core/utilscore/conversion.go @@ -0,0 +1,58 @@ +package utilscore + +import ( + "time" + + "github.com/shopspring/decimal" +) + +func PointerToBool(b bool) *bool { + return &b +} + +func PointerToUint32(i uint32) *uint32 { + return &i +} + +func PointerToDecimal(i decimal.Decimal) *decimal.Decimal { + return &i +} + +func PointerToUint64(i uint64) *uint64 { + return &i +} + +func PointerToString(s string) *string { + return &s +} + +func PointerToFloat64(f float64) *float64 { + return &f +} + +func PointerToFloat32(f float32) *float32 { + return &f +} + +func PointerToInt(i int) *int { + return &i +} +func PointerToTime(t time.Time) *time.Time { + return &t +} + +func PointerToInt64(i int64) *int64 { + return &i +} + +func PointerToInt32(i int32) *int32 { + return &i +} + +// GetStringValue получает значение из указателя на строку +func GetStringValue(ptr *string) string { + if ptr == nil { + return "" + } + return *ptr +} diff --git a/core/utilscore/db/db.go b/core/utilscore/db/db.go new file mode 100644 index 0000000..6d42aab --- /dev/null +++ b/core/utilscore/db/db.go @@ -0,0 +1,174 @@ +package dbutils + +import ( + "bitrix_balancer_api/core/typescore" + "errors" + "fmt" + "reflect" + "sync" + + "github.com/Masterminds/squirrel" + "github.com/sirupsen/logrus" +) + +var ( + fieldsCache sync.Map // Используем sync.Map для кэширования +) + +type cacheKey struct { + typ reflect.Type + dbName string +} + +// GetOptionsDB обобщённая функция для разбора опций. +// Если Filtering не передан, создаётся новый объект типа T. +// Если передан, то выполняется проверка соответствия типу *T. +func GetOptionsDB[T any](opts ...typescore.ListDbOptions) (typescore.ListDbOptions, *T, error) { + var options typescore.ListDbOptions + if len(opts) > 0 { + options = opts[0] + } + + var filter *T + if options.Filtering == nil { + filter = new(T) + } else { + var ok bool + filter, ok = options.Filtering.(*T) + if !ok { + return typescore.ListDbOptions{}, nil, errors.New("expected *T") + } + } + return options, filter, nil +} + +func GetStructFieldsDB(processor interface{}, dbName ...string) []string { + if processor == nil || reflect.ValueOf(processor).Kind() != reflect.Ptr || reflect.ValueOf(processor).Elem().Kind() != reflect.Struct { + logrus.Error("🔴 error GetStructFieldsDB: processor must be a non-nil pointer to a struct") + return nil + } + + procType := reflect.TypeOf(processor).Elem() + nameDB := "" + if len(dbName) > 0 { + nameDB = dbName[0] + } + key := cacheKey{ + typ: procType, + dbName: nameDB, + } + + if fields, exists := fieldsCache.Load(key); exists { + return fields.([]string) + } + + val := reflect.ValueOf(processor).Elem() + + var fields []string + for i := 0; i < val.NumField(); i++ { + typeField := procType.Field(i) + dbTag := typeField.Tag.Get("db") + if dbTag != "" { + if typeField.Tag.Get("ignore_db") == "true" { + continue + } + + // Добавляем alias, чтобы исключить конфликты при одинаковых именах полей + if nameDB != "" { + fullField := fmt.Sprintf("%s.%s", nameDB, dbTag) + fields = append(fields, fullField) + } else { + fields = append(fields, dbTag) + } + } + } + + fieldsCache.Store(key, fields) + return fields +} + +func AddNonNullFieldsToQueryUpdate(query squirrel.UpdateBuilder, paramsUpdate interface{}) squirrel.UpdateBuilder { + v := reflect.ValueOf(paramsUpdate) + t := v.Type() + + for i := 0; i < v.NumField(); i++ { + field := v.Field(i) + if (field.Kind() == reflect.Ptr && !field.IsNil()) || (field.Kind() != reflect.Ptr && !field.IsZero()) { + // Проверяем тег ignore_update_db для игнорирования полей при обновлении + ignoreUpdateDbTag := t.Field(i).Tag.Get("ignore_update_db") + if ignoreUpdateDbTag == "true" { + continue + } + ignoreDbTag := t.Field(i).Tag.Get("ignore_db") + if ignoreDbTag == "true" { + continue + } + dbTag := t.Field(i).Tag.Get("db") + if dbTag != "system_id" && dbTag != "role" && dbTag != "created_at" { + query = query.Set(dbTag, field.Interface()) + } + } + } + + return query +} + +// Создаем два списка для хранения названий столбцов и соответствующих значений +func GenerateInsertRequest(query squirrel.InsertBuilder, processor interface{}, options ...typescore.InsertOptions) (*string, []interface{}, error) { + var columns []string + var values []interface{} + v := reflect.ValueOf(processor).Elem() + t := v.Type() + + for i := 0; i < v.NumField(); i++ { + field := v.Field(i) + ignoreDbTag := t.Field(i).Tag.Get("ignore_db") + if ignoreDbTag == "true" { + continue + } + dbTag := t.Field(i).Tag.Get("db") + if dbTag == "" { + continue + } + if dbTag == "serial_id" || dbTag == "system_id" { + continue + } + + if (field.Kind() == reflect.Ptr && !field.IsNil()) || (field.Kind() != reflect.Ptr && !field.IsZero()) { + columns = append(columns, dbTag) + values = append(values, field.Interface()) + } + } + + if len(columns) == 0 { + logrus.Error("🔴 error GenerateInsertRequest: all fields are zero") + return nil, nil, errors.New("all fields are zero") + } + + // Применяем опции, если они есть + if len(options) > 0 { + for _, opt := range options { + if opt.Prefix != "" { + query = query.Prefix(opt.Prefix) + } + if opt.Suffix != "" { + query = query.Suffix(opt.Suffix) + } else if opt.IgnoreConflict { + query = query.Suffix("ON CONFLICT DO NOTHING") + } + } + } + + query = query.Columns(columns...).Values(values...) + + sql, args, err := query.ToSql() + if err != nil { + logrus.Error("🔴 error GenerateInsertRequest: ", err) + return nil, nil, err + } + if sql == "" { + logrus.Error("🔴 error GenerateInsertRequest: sql is empty") + return nil, nil, errors.New("sql is empty") + } + return &sql, args, nil +} diff --git a/core/utilscore/db/db_operations.go b/core/utilscore/db/db_operations.go new file mode 100644 index 0000000..458cc5b --- /dev/null +++ b/core/utilscore/db/db_operations.go @@ -0,0 +1,16 @@ +package dbutils + +import ( + "github.com/Masterminds/squirrel" +) + +// SetterLimitAndOffsetQuery применяет limit и offset к переданному SelectBuilder, если они не nil. +func SetterLimitAndOffsetQuery(query squirrel.SelectBuilder, offset *uint64, limit *uint64) squirrel.SelectBuilder { + if limit != nil { + query = query.Limit(*limit) + } + if offset != nil { + query = query.Offset(*offset) + } + return query +} diff --git a/core/utilscore/db/db_rows.go b/core/utilscore/db/db_rows.go new file mode 100644 index 0000000..309d3d0 --- /dev/null +++ b/core/utilscore/db/db_rows.go @@ -0,0 +1,139 @@ +package dbutils + +import ( + "encoding/json" + "errors" + "reflect" + "sync" + + "github.com/jackc/pgx/v5" + "github.com/sirupsen/logrus" +) + +// Кэш для функции prepareFieldMap +var prepareFieldMapCache sync.Map // Используем sync.Map для кэширования + +type cachedFieldInfo struct { + dbTag string + fieldPath []int +} + +// ScanRowsToStructRows сканирует строки из pgx.Rows в структуру и totalCount. +func ScanRowsToStructRows(rows pgx.Rows, dest interface{}, totalCount *uint64, totalAmount ...*float64) error { + if dest == nil { + return errors.New("dest must not be nil") + } + + val := reflect.ValueOf(dest) + if val.Kind() != reflect.Ptr || val.IsNil() { + return errors.New("dest must be a non-nil pointer") + } + + elem := val.Elem() + if elem.Kind() != reflect.Struct { + return errors.New("dest must be a pointer to a struct") + } + + typ := elem.Type() + fieldMap := prepareFieldMap(elem, typ) + + columns := getColumnsFromRows(rows) + args := getScanArgs(columns, fieldMap, totalCount, totalAmount...) + + err := rows.Scan(args...) + if err != nil { + logrus.Error("🔴 error ScanRowsToStructRows: ", err) + return err + } + + return nil +} + +func getColumnsFromRows(rows pgx.Rows) []string { + fieldDescriptions := rows.FieldDescriptions() + columns := make([]string, len(fieldDescriptions)) + for i, fd := range fieldDescriptions { + columns[i] = string(fd.Name) + } + return columns +} + +func getScanArgs(columns []string, fieldMap map[string]interface{}, totalCount *uint64, totalAmount ...*float64) []interface{} { + scanArgs := make([]interface{}, len(columns)) + + for i, col := range columns { + switch col { + case "total_count": + if totalCount != nil { + scanArgs[i] = totalCount + } else { + scanArgs[i] = new(uint64) + } + case "total_amount": + if totalAmount[0] != nil { + scanArgs[i] = totalAmount[0] + } else { + dummy := new(float64) + scanArgs[i] = dummy + } + default: + if field, ok := fieldMap[col]; ok { + scanArgs[i] = field + } else { + dummy := new(interface{}) + scanArgs[i] = dummy + } + } + } + + return scanArgs +} + +func prepareFieldMap(val reflect.Value, typ reflect.Type) map[string]interface{} { + if cachedFields, ok := prepareFieldMapCache.Load(typ); ok { + fieldMap := make(map[string]interface{}) + // Используем закешированные данные + for _, info := range cachedFields.([]cachedFieldInfo) { + field := val.FieldByIndex(info.fieldPath) + if field.CanAddr() { + fieldMap[info.dbTag] = field.Addr().Interface() + } + } + return fieldMap + } + + // Если тип не закеширован, собираем информацию о полях + var cachedFieldsInfo []cachedFieldInfo + fieldMap := make(map[string]interface{}) + if val.Kind() == reflect.Ptr { + val = val.Elem() + } + for i := 0; i < val.NumField(); i++ { + field := val.Field(i) + fieldType := typ.Field(i) + + if fieldType.Tag.Get("ignore_db_select") == "true" { + continue + } + if tag := fieldType.Tag.Get("db"); tag != "" { + if field.Type() == reflect.TypeOf(json.RawMessage{}) { + fieldMap[tag] = field.Addr().Interface() + } else if field.Kind() == reflect.Slice && field.Type().Elem() == reflect.TypeOf(json.RawMessage{}) { + fieldMap[tag] = &json.RawMessage{} + } else if field.Kind() == reflect.Struct && field.Type() == reflect.TypeOf(json.RawMessage{}) { + fieldMap[tag] = &json.RawMessage{} + } else { + fieldMap[tag] = field.Addr().Interface() + } + cachedFieldsInfo = append(cachedFieldsInfo, cachedFieldInfo{ + dbTag: tag, + fieldPath: fieldType.Index, + }) + } + } + + // Сохраняем информацию в кэше + prepareFieldMapCache.Store(typ, cachedFieldsInfo) + + return fieldMap +} diff --git a/core/utilscore/db/query.go b/core/utilscore/db/query.go new file mode 100644 index 0000000..5639802 --- /dev/null +++ b/core/utilscore/db/query.go @@ -0,0 +1,22 @@ +package dbutils + +import ( + "github.com/Masterminds/squirrel" +) + +// BuildSelectQuery создает базовый SELECT-запрос. +func BuildSelectQuery(table string, fields []string) squirrel.SelectBuilder { + return squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Select(fields...).From(table) +} + +// ApplyFilters добавляет фильтры к запросу +func ApplyFilters(query squirrel.SelectBuilder, paramsFiltering interface{}, likeFields map[string]string, baseName ...string) squirrel.SelectBuilder { + var baseNamePtr *string + if len(baseName) > 0 { + baseNamePtr = &baseName[0] + } else { + baseNamePtr = nil + } + return AddNonNullFieldsToQueryWhere(query, paramsFiltering, likeFields, baseNamePtr) +} diff --git a/core/utilscore/db/query_where.go b/core/utilscore/db/query_where.go new file mode 100644 index 0000000..02e9366 --- /dev/null +++ b/core/utilscore/db/query_where.go @@ -0,0 +1,170 @@ +package dbutils + +import ( + "fmt" + "reflect" + "strings" + "sync" + + "github.com/Masterminds/squirrel" +) + +var ( + reflectionCacheQueryWhere sync.Map // Используем sync.Map для кэширования +) + +func getCachedFieldsQueryWhere(t reflect.Type) []reflect.StructField { + if fields, exists := reflectionCacheQueryWhere.Load(t); exists { + return fields.([]reflect.StructField) + } + + var cachedFields []reflect.StructField + for i := 0; i < t.NumField(); i++ { + cachedFields = append(cachedFields, t.Field(i)) + } + reflectionCacheQueryWhere.Store(t, cachedFields) + return cachedFields +} +func AddNonNullFieldsToQueryWhere( + query squirrel.SelectBuilder, + processor interface{}, + likeFields map[string]string, + baseName *string, +) squirrel.SelectBuilder { + val := reflect.ValueOf(processor).Elem() + typ := val.Type() + + var or squirrel.Or + fields := getCachedFieldsQueryWhere(typ) + + for i := 0; i < val.NumField(); i++ { + field := val.Field(i) + typeField := fields[i] + + // Пропускаем невалидные или пустые поля + if !field.IsValid() || field.IsZero() { + continue + } + + // Безопасно проверяем на nil, только если тип позволяет + if isNilable(field.Kind()) && field.IsNil() { + continue + } + + ignoreDbTag := typeField.Tag.Get("ignore_db") + if ignoreDbTag == "true" { + continue + } + + ignoreReqDbTag := typeField.Tag.Get("ignore_req_db") + if ignoreReqDbTag == "true" { + continue + } + + dbTag := typeField.Tag.Get("db") + if dbTag != "" { + if baseName != nil { + dbTag = fmt.Sprintf("%s.%s", *baseName, dbTag) + } + + if likeValue, ok := likeFields[dbTag]; ok { + // Добавляем LIKE фильтр + switch dbTag { + case "serial_id": + or = append(or, squirrel.Expr("CAST(serial_id AS TEXT) ILIKE ?", likeValue+"%")) + case "telegram_id": + or = append(or, squirrel.Expr("CAST(telegram_id AS TEXT) ILIKE ?", likeValue+"%")) + default: + or = append(or, squirrel.ILike{dbTag: likeValue + "%"}) + } + } else { + query = query.Where(processFieldCached(field, dbTag)) + } + } + } + + if len(or) > 0 { + query = query.Where(or) + } + + return query +} + +func AddNotNullAndPositiveConditions(query squirrel.SelectBuilder, fields map[string]bool) squirrel.SelectBuilder { + for field, value := range fields { + // Для числовых полей добавляем проверку на > 0 + if value { + query = query.Where(squirrel.And{ + squirrel.NotEq{field: nil}, + squirrel.Gt{field: 0}, + }) + } else { + // Для нечисловых полей проверяем только на null + query = query.Where(squirrel.NotEq{field: nil}) + } + + } + return query +} + +// Вспомогательная функция — проверка, может ли тип быть nil +func isNilable(kind reflect.Kind) bool { + switch kind { + case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice: + return true + default: + return false + } +} + +func processFieldCached(field reflect.Value, dbTag string) squirrel.Sqlizer { + fieldType := field.Type().String() + + switch fieldType { + case "*bool": + boolVal := *field.Interface().(*bool) + return squirrel.Eq{dbTag: boolVal} + case "*string": + str := *field.Interface().(*string) + if strings.Contains(str, ",") { + values := strings.Split(str, ",") + or := squirrel.Or{} + for _, value := range values { + or = append(or, squirrel.Eq{dbTag: value}) + } + return or + } + return squirrel.Eq{dbTag: str} + case "[]*string": + stringPtrSlice := field.Interface().([]*string) + + if len(stringPtrSlice) == 0 { + return squirrel.Eq{dbTag: nil} + } + + // Специальная обработка для поля categories + if dbTag == "categories" || strings.HasSuffix(dbTag, ".categories") { + or := squirrel.Or{} + for _, strPtr := range stringPtrSlice { + if strPtr != nil { + or = append(or, squirrel.Expr( + dbTag+" && ARRAY[?]", + *strPtr, + )) + } + } + return or + } + + // Для других полей типа []*string используем обычный подход + or := squirrel.Or{} + for _, strPtr := range stringPtrSlice { + if strPtr != nil { + or = append(or, squirrel.Eq{dbTag: *strPtr}) + } + } + return or + default: + return squirrel.Eq{dbTag: field.Interface()} + } +} diff --git a/core/utilscore/db/transaction.go b/core/utilscore/db/transaction.go new file mode 100644 index 0000000..1effda0 --- /dev/null +++ b/core/utilscore/db/transaction.go @@ -0,0 +1,70 @@ +package dbutils + +import ( + "context" + "errors" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + "github.com/sirupsen/logrus" + "log" +) + +func RollbackTransactionDB(ctx context.Context, tx pgx.Tx) { + if rErr := tx.Rollback(ctx); rErr != nil && !errors.Is(rErr, pgx.ErrTxClosed) { + log.Printf("error: failed to rollback transaction: %v", rErr) + } +} + +func BeginTransaction(ctx context.Context, databasePull *pgxpool.Pool) (*pgxpool.Conn, pgx.Tx, error) { + conn, err := databasePull.Acquire(ctx) + if err != nil { + logrus.Errorf("🔴 error: %s: %+v", "BeginTransaction-BeginTransaction", err) + return nil, nil, err + } + tx, err := conn.Begin(ctx) + if err != nil { + logrus.Errorf("🔴 error: %s: %+v", "BeginTransaction-Begin", err) + conn.Release() + return nil, nil, err + } + return conn, tx, nil +} + +// ExecuteTx выполняет функцию fn в транзакции. +// Если tx не nil, то используется переданная транзакция. +// Иначе создается новая транзакция. +func ExecuteTx(ctx context.Context, db *pgxpool.Pool, tx pgx.Tx, fn func(tx pgx.Tx) error) error { + var err error + var transactionStarted bool + + if tx == nil { + tx, err = db.Begin(ctx) + if err != nil { + logrus.Errorf("🔴 error: %s: %+v", "ExecuteTx-Begin", err) + return err + } + + transactionStarted = true + } + + err = fn(tx) + + if transactionStarted { + if err != nil { + logrus.Errorf("🔴 error: %s: %+v", "ExecuteTx-transactionStarted", err) + if rollbackErr := tx.Rollback(ctx); rollbackErr != nil { + return err + } + return err + } + + if commitErr := tx.Commit(ctx); commitErr != nil { + return err + } + } + + if err != nil { + return err + } + return nil +} diff --git a/core/utilscore/db/update_set.go b/core/utilscore/db/update_set.go new file mode 100644 index 0000000..ef20333 --- /dev/null +++ b/core/utilscore/db/update_set.go @@ -0,0 +1,59 @@ +package dbutils + +import ( + "reflect" + "sync" + + "github.com/Masterminds/squirrel" +) + +var ( + typeCache sync.Map // Используем sync.Map для кэширования +) + +type fieldInfo struct { + dbTag string + ignoreDb bool + ignoreReqDb bool + updatableDb bool + fieldInterface func(reflect.Value) interface{} +} + +func getCachedFields(t reflect.Type) []fieldInfo { + if fields, exists := typeCache.Load(t); exists { + return fields.([]fieldInfo) + } + + var cachedFields []fieldInfo + for i := 0; i < t.NumField(); i++ { + f := t.Field(i) + cInfo := fieldInfo{ + dbTag: f.Tag.Get("db"), + ignoreDb: f.Tag.Get("ignore_db") == "true" || f.Tag.Get("db") == "", + ignoreReqDb: f.Tag.Get("ignore_req_db") == "true", + updatableDb: f.Tag.Get("updatable_db") != "false", + fieldInterface: func(v reflect.Value) interface{} { + return v.Interface() + }, + } + cachedFields = append(cachedFields, cInfo) + } + typeCache.Store(t, cachedFields) + return cachedFields +} + +func UpdateSetField(query squirrel.UpdateBuilder, processor interface{}) squirrel.UpdateBuilder { + v := reflect.ValueOf(processor).Elem() + t := v.Type() + fields := getCachedFields(t) + for i, f := range fields { + field := v.Field(i) + if (field.Kind() == reflect.Ptr && !field.IsNil()) || (field.Kind() != reflect.Ptr && !field.IsZero()) { + if f.ignoreDb || f.ignoreReqDb || !f.updatableDb { + continue + } + query = query.Set(f.dbTag, f.fieldInterface(field)) + } + } + return query +} 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/plural.go b/core/utilscore/plural.go new file mode 100644 index 0000000..0d69228 --- /dev/null +++ b/core/utilscore/plural.go @@ -0,0 +1,14 @@ +package utilscore + +import "fmt" + +func PluralFiles(n int) string { + switch { + case n%10 == 1 && n%100 != 11: + return fmt.Sprintf("%d файл", n) + case n%10 >= 2 && n%10 <= 4 && (n%100 < 10 || n%100 >= 20): + return fmt.Sprintf("%d файла", n) + default: + return fmt.Sprintf("%d файлов", n) + } +} diff --git a/core/utilscore/rest.go b/core/utilscore/rest.go new file mode 100644 index 0000000..2f4a734 --- /dev/null +++ b/core/utilscore/rest.go @@ -0,0 +1,165 @@ +package utilscore + +import ( + "fmt" + "github.com/mitchellh/mapstructure" + "github.com/shopspring/decimal" + "github.com/sirupsen/logrus" + "net/url" + "reflect" + "strconv" + "strings" +) + +func ParseParamsGetRequest(queryParams url.Values, result interface{}) (*uint64, *uint64, map[string]string, error) { + likeFields := map[string]string{} + singleValueQueryParams := make(map[string]interface{}) + offset := PointerToUint64(0) + limit := PointerToUint64(50) + + paramTypes := make(map[string]string) + + resultType := reflect.TypeOf(result).Elem() + for i := 0; i < resultType.NumField(); i++ { + field := resultType.Field(i) + tag := field.Tag.Get("mapstructure") + if tag != "" { + fieldType := field.Type + if fieldType.Kind() == reflect.Ptr { + fieldType = fieldType.Elem() + } + paramTypes[tag] = fieldType.String() + } + } + + for key, values := range queryParams { + if len(values) > 0 { + value := values[0] + switch key { + case "offset": + offset = parseUintParam(value) + case "limit": + limit = parseUintParam(value) + default: + singleValueQueryParams[key] = parseQueryParam(value, key, paramTypes) + } + } + } + + decoder, err := setupDecoder(result) + if err != nil { + logrus.Error("🛑 error setting up decoder: ", err) + return offset, limit, likeFields, err + } + + err = decoder.Decode(singleValueQueryParams) + if err != nil { + logrus.Error("🛑 error decoding query params: ", err) + return offset, limit, likeFields, err + } + + return offset, limit, likeFields, nil +} + +func parseQueryParam(value string, key string, paramTypes map[string]string) interface{} { + switch value { + case "true": + return true + case "false": + return false + case "all": + return nil + default: + if strings.Contains(value, ",") { + return strings.Split(value, ",") + } + + if paramTypes[key] == "decimal.Decimal" { + if decVal, err := decimal.NewFromString(value); err == nil { + return decVal + } else { + // Логирование ошибки + logrus.Error("🛑 error parsing decimal param: ", err) + return nil + } + } + + if paramTypes[key] == "uint64" { + if uintVal, err := strconv.ParseUint(value, 10, 64); err == nil { + logrus.Error("🛑 error parsing uint64 param: ", err) + return uintVal + } else { + return nil + } + } + + // Проверяем тип данных из paramTypes + if paramTypes[key] == "string" { + return value + } + + if floatVal, err := strconv.ParseFloat(value, 64); err == nil { + return floatVal + } + return value + } +} + +func parseUintParam(value string) *uint64 { + val, err := strconv.ParseUint(value, 10, 64) + if err == nil { + return &val + } + logrus.Error("🛑 error parsing uint param: ", err) + return nil +} + +func setupDecoder(result interface{}) (*mapstructure.Decoder, error) { + decoderConfig := &mapstructure.DecoderConfig{ + DecodeHook: mapstructure.ComposeDecodeHookFunc( + decodeHookStringSliceToString, + decodeHookStringToPtrStringSlice, + decodeHookStringToDecimal, + ), + Result: result, + } + decoder, err := mapstructure.NewDecoder(decoderConfig) + if err != nil { + logrus.Error("🛑 error creating decoder: ", err) + return nil, err + } + return decoder, nil +} + +func decodeHookStringSliceToString(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { + if t == reflect.TypeOf(new(string)) && f.Kind() == reflect.Slice { + slice := reflect.ValueOf(data) + strSlice := make([]string, slice.Len()) + for i := 0; i < slice.Len(); i++ { + strSlice[i] = fmt.Sprint(slice.Index(i).Interface()) + } + result := strings.Join(strSlice, ",") + return &result, nil + } + return data, nil +} + +func decodeHookStringToPtrStringSlice(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { + if t == reflect.TypeOf([]*string{}) && f.Kind() == reflect.String { + str := data.(string) + return []*string{&str}, nil + } + return data, nil +} + +func decodeHookStringToDecimal(from reflect.Type, to reflect.Type, data interface{}) (interface{}, error) { + if from.Kind() == reflect.String && to == reflect.TypeOf(&decimal.Decimal{}) { + dec, err := decimal.NewFromString(data.(string)) + if err != nil { + logrus.Error("🛑 error parsing decimal: ", err) + return nil, err + } + return &dec, nil + } + return data, nil +} diff --git a/core/utilscore/secure.go b/core/utilscore/secure.go new file mode 100644 index 0000000..7842702 --- /dev/null +++ b/core/utilscore/secure.go @@ -0,0 +1,26 @@ +package utilscore + +import ( + "crypto/hmac" + "crypto/sha256" + "encoding/hex" +) + +func GenerateHMACSignature(public, timestampStr, private string) string { + h := hmac.New(sha256.New, []byte(private)) + h.Write([]byte(public + ":" + timestampStr)) + signature := h.Sum(nil) + return hex.EncodeToString(signature) +} + +func HmacEquals(expected, actual string) bool { + expectedBytes, err := hex.DecodeString(expected) + if err != nil { + return false + } + actualBytes, err := hex.DecodeString(actual) + if err != nil { + return false + } + return hmac.Equal(expectedBytes, actualBytes) +} diff --git a/core/utilscore/sendBotMsg.go b/core/utilscore/sendBotMsg.go new file mode 100644 index 0000000..71faca4 --- /dev/null +++ b/core/utilscore/sendBotMsg.go @@ -0,0 +1,9 @@ +package utilscore + +import tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" + +func SendBotMessage(bot *tgbotapi.BotAPI, chatID int64, text string) { + msg := tgbotapi.NewMessage(chatID, text) + msg.ParseMode = "HTML" + bot.Send(msg) //nolint:errcheck +} 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/utilscore/w-recover.go b/core/utilscore/w-recover.go new file mode 100644 index 0000000..e283697 --- /dev/null +++ b/core/utilscore/w-recover.go @@ -0,0 +1,36 @@ +package utilscore + +import ( + "github.com/google/uuid" + "github.com/sirupsen/logrus" + "net/http" + "runtime/debug" +) + +// RecoverMiddleware глобально перехватывает паники в HTTP-стеке, логирует и возвращает 500 +func RecoverMiddleware() func(http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + defer func() { + if rec := recover(); rec != nil { + logrus.Errorf("panic recovered: %v", rec) + logrus.Errorf("stacktrace: %s", string(debug.Stack())) + w.Header().Set("Content-Type", "application/json") + http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) + } + }() + next.ServeHTTP(w, r) + }) + } +} + +func RecoverAndLog(scope ...string) { + scopeString := uuid.New().String() + if len(scope) > 0 { + scopeString = scope[0] + } + if rec := recover(); rec != nil { + logrus.Errorf("%s: panic recovered: %v", scopeString, rec) + logrus.Errorf("%s: stacktrace: %s", scopeString, string(debug.Stack())) + } +} diff --git a/core/variables/api_headers.go b/core/variables/api_headers.go new file mode 100644 index 0000000..fc9ac04 --- /dev/null +++ b/core/variables/api_headers.go @@ -0,0 +1,9 @@ +package variables + +type contextKey string + +func (c contextKey) String() string { + return string(c) +} + +const AccessContextKey contextKey = "accessCode" 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 new file mode 100644 index 0000000..a2ae15c --- /dev/null +++ b/deploy.sh @@ -0,0 +1,262 @@ +#!/bin/bash + +set -e +trap 'echo "🔴 Deploy failed at line $LINENO"; exit 1' ERR + +THIS_PATH=$(dirname "$(realpath "$0")") + +# ═══════════════════════════════════════════════════════════════ +# Цвета для вывода +# ═══════════════════════════════════════════════════════════════ +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 "════════════════════════════════════════" +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 "" + +# ═══════════════════════════════════════════════════════════════ +# Сборка сервиса +# ═══════════════════════════════════════════════════════════════ +log_info "Building $SERVICE_NAME..." +cd "$SERVICE_PATH" + +gofmt -w . +go vet ./... + +# Сборка с оптимизациями (убираем отладочную информацию) +go build -ldflags="-s -w" -o "$BINARY_PATH" . + +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 b/go.work new file mode 100644 index 0000000..e758a7c --- /dev/null +++ b/go.work @@ -0,0 +1,9 @@ +go 1.25.6 + +use ( + core + ./service/rest_balancer_service + service/telegram_service + service/system_service + service/rest_admin_service +) diff --git a/go.work.sum b/go.work.sum new file mode 100644 index 0000000..fdb2c38 --- /dev/null +++ b/go.work.sum @@ -0,0 +1,102 @@ +github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI= +github.com/Masterminds/goutils v1.1.1/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU= +github.com/Masterminds/semver/v3 v3.1.1 h1:hLg3sBzpNErnxhQtUy/mmLR2I9foDujNK030IGemrRc= +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/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= +github.com/mitchellh/cli v1.1.5/go.mod h1:v8+iFts2sPIKUV1ltktPXMCC8fumSKFItNcD2cLtRR4= +github.com/mitchellh/copystructure v1.0.0 h1:Laisrj+bAB6b/yJwB5Bt3ITZhGJdqmxquMKeZ+mmkFQ= +github.com/mitchellh/copystructure v1.0.0/go.mod h1:SNtv71yrdKgLRyLFxmLdkAbkKEFWgYaq1OVrnRcwhnw= +github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0= +github.com/mitchellh/go-wordwrap v1.0.1/go.mod h1:R62XHJLzvMFRBbcrT7m7WgmE1eOyTSsCt+hzestvNj0= +github.com/mitchellh/reflectwalk v1.0.0 h1:9D+8oIskB4VJBN5SFlmc27fSlIBZaov1Wpk/IfikLNY= +github.com/mitchellh/reflectwalk v1.0.0/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= +github.com/natefinch/atomic v1.0.1 h1:ZPYKxkqQOx3KZ+RsbnP/YsgvxWQPGxjC0oBt2AhwV0A= +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= +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= +golang.org/x/image v0.25.0/go.mod h1:tCAmOEGthTtkalusGp1g3xa2gke8J6c2N565dTyl9Rs= +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/.gitignore b/service/rest_admin_service/.gitignore new file mode 100644 index 0000000..89c0c75 --- /dev/null +++ b/service/rest_admin_service/.gitignore @@ -0,0 +1,5 @@ +.env +user-service_app +config.yml +vendor +app \ No newline at end of file diff --git a/service/rest_admin_service/.golangci.yml b/service/rest_admin_service/.golangci.yml new file mode 100644 index 0000000..ea1405d --- /dev/null +++ b/service/rest_admin_service/.golangci.yml @@ -0,0 +1,52 @@ +linters-settings: + errcheck: # Настройки для линтера errcheck, который проверяет, что ошибки не игнорируются + check-type-assertions: true # Не проверять утверждения типов на ошибки + check-blank: true # Проверять игнорирование ошибок через присваивание в _ + prealloc: # Настройки для линтера prealloc, который предлагает предварительное выделение памяти для срезов + simple: true # Простой режим, предлагает предварительное выделение для простых циклов + range-loops: true # Предлагает предварительное выделение для циклов range + for-loops: false # Не предлагает предварительное выделение для обычных for-циклов + gocyclo: # Настройки для линтера gocyclo, который проверяет сложность функций + min-complexity: 15 # Установите порог сложности, который считаете приемлемым + +linters: + enable: # Список линтеров, которые будут включены + - noctx # Находит отправку HTTP-запроса без контекста.Контекст. + - protogetter # Сообщает о прямом чтении из полей прото-сообщения, когда следует использовать геттеры. + - reassign # Проверяет, что переменные пакета не переназначаются. + - rowserrcheck # Проверяет, успешно ли проверен Rows.Err строк. + - sqlclosecheck # Проверяет, что sql.Rows, sql.Stmt, sqlx.NamedStmt, pgx.Query закрыты. + - ineffassign # Обнаруживает, когда назначения существующим переменным не используются. + - nilerr # Находит код, который возвращает ноль, даже если он проверяет, что ошибка не равна нулю. + - makezero # Проверяет, что нулевые значения создаются правильно + - gochecksumtype # Проверяет, что тип контрольной суммы в go.sum соответствует содержимому + - copyloopvar # Проверяет, что циклические зависимости пакетов не имеют экспортируемых идентификаторов + - exhaustive # Проверьте полноту операторов перечисления. + - errchkjson # Проверяет типы, передаваемые функциям кодирования JSON. Сообщает о неподдерживаемых типах и событиях, при которых проверку возвращаемой ошибки можно опустить. + - durationcheck # Проверяет, что длительность таймаута не равна 0 + - contextcheck # Проверяет, что контекст не игнорируется + - bodyclose # Проверяет, что тело запроса закрывается + - bidichk # Проверяет, что строки в исходном коде не содержат символов из разных языков + - govet # Проверяет код на наличие конструкций, которые могут быть ошибочными + - errcheck # Проверяет, что ошибки не игнорируются + - staticcheck # Статический анализ кода, находит ошибки, неэффективные конструкции и т.д. + - unused # Проверяет на неиспользуемые переменные, функции, константы + - gocritic # Линтер, основанный на проверке кода на соответствие определенным критериям качества и стиля + - stylecheck # Проверяет стиль кодирования + - whitespace # Проверяет проблемы с пробелами в коде + - gosec # Линтер gosec, который проверяет код на наличие потенциальных уязвимостей + - prealloc # Предлагает предварительное выделение памяти для срезов + + - dupl # Находит дублирующийся код + - gocyclo # Проверяет сложность функций + - ineffassign # Обнаруживает неэффективные присваивания + - unparam # Находит неиспользуемые параметры функций + + - gosimple # Предлагает упрощения кода + + disable: # Список линтеров, которые будут отключены + - gofumpt # Более строгая версия gofmt, применяет дополнительные правила форматирования + # - golint # Отключает golint, который проверяет стиль написания кода на Go + +run: + timeout: 15m # Устанавливает тайм-аут для выполнения всех линтеров \ No newline at end of file diff --git a/service/rest_admin_service/README.MD b/service/rest_admin_service/README.MD new file mode 100644 index 0000000..f201b6d --- /dev/null +++ b/service/rest_admin_service/README.MD @@ -0,0 +1,33 @@ +0.0.2 +# rest_admin_service + +### Инициализация проекта +```bash +go mod init sveves-team/fusionai-aggregator-backend/rest_admin_service +go mod tidy +go mod edit -replace sveves-team/fusionai-aggregator-backend/core=../../core +``` + + + +### Локальный старт +```bash +go run cmd/app.go +``` + +### Старт автотестов +``` bash +go test ./... +``` + +``` bash +go vet ./... +``` + +```bash +gofmt -w . +``` + +```bash +swag init -g cmd/app.go --dir ./,../../core +``` diff --git a/service/rest_admin_service/cmd/app.go b/service/rest_admin_service/cmd/app.go new file mode 100644 index 0000000..974056e --- /dev/null +++ b/service/rest_admin_service/cmd/app.go @@ -0,0 +1,242 @@ +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" + "github.com/go-chi/chi/v5" + "github.com/go-chi/chi/v5/middleware" + "github.com/go-chi/cors" + "github.com/go-chi/httprate" + "github.com/sirupsen/logrus" + httpSwagger "github.com/swaggo/http-swagger" + "log" + "net/http" + "time" +) + +const ( + readTimeout = 15 * time.Minute // Таймаут чтения + writeTimeout = 15 * time.Minute // Таймаут записи + idleTimeout = 15 * time.Minute // Таймаут бездействия + rateLimit = 15 // Лимит запросов + 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 { + logrus.Errorln("🔴 failed to init common: ", err) + } + select {} +} + +func initService() error { + clientsExternal, err := getClientsExternal() + if err != nil { + logrus.Errorln("🔴 failed to load config: ", err) + return err + } + + ipc, err := initInternalProvider(clientsExternal) + if err != nil { + logrus.Errorln("🔴 failed to init internal provider: ", err) + return err + } + + router, err := initBaseApiRouter(ipc) + if err != nil { + logrus.Errorln("🔴 failed to init base api router: ", err) + return err + } + + if err := startRestApiServer(ipc, router); err != nil { + logrus.Errorln("🔴 failed to start server: ", err) + return err + } + + return nil +} + +func getClientsExternal() (clientcontrollers.ClientsExternal, error) { + options := &configcore.ConfigLoadOptions{ + Redis: true, + Database: true, + Secrets: configcore.SecretsOptions{ + AuthJWT: configcore.AuthJWTOptions{ + Admin: true, + }, + AdminAccessCode: true, + }, + Server: configcore.ExposedServiceOptions{ + RESTAdminService: true, + }, + } + + return clientcontrollers.ReturnClientsExternal(options) +} + +func initInternalProvider(clientsExternal clientcontrollers.ClientsExternal) (*typesm.InternalProviderControl, error) { + return &typesm.InternalProviderControl{ + Config: clientsExternal.Config, + RedisClient: clientsExternal.Redis, + Database: clientsExternal.DB, + }, nil +} + +func startRestApiServer(ipc *typesm.InternalProviderControl, router *chi.Mux) error { + serverPort := fmt.Sprintf("%d", ipc.Config.Server.RESTAdminService.PortRest) + + serverAddr := ":" + serverPort + httpServer := &http.Server{ + Addr: serverAddr, + Handler: router, + ReadTimeout: readTimeout, + WriteTimeout: writeTimeout, + IdleTimeout: idleTimeout, + } + + log.Printf("✅ Starting server on %s", serverAddr) + return httpServer.ListenAndServe() +} + +func initBaseApiRouter(ipc *typesm.InternalProviderControl) (*chi.Mux, error) { + router := chi.NewRouter() + corsOptions := cors.New(cors.Options{ + AllowedOrigins: ipc.Config.Server.RESTAdminService.Cors.AllowedOrigins, // Список разрешенных origin + AllowedMethods: []string{http.MethodGet, http.MethodPost, http.MethodPut, http.MethodDelete, http.MethodPatch, http.MethodOptions}, + AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "ApiKey", "x-device-id"}, + ExposedHeaders: []string{"Link", "Cache-Control"}, + AllowCredentials: false, + MaxAge: 300, // Максимальное время жизни предварительных запросов в секундах + }) + + router.Use(corsOptions.Handler) + router.Use(middleware.RealIP) + + // Добавляем ограничение по IP + router.Use(httprate.LimitByIP(rateLimit, rateWindow)) + + if ipc.Database == nil { + return nil, errors.New("failed_to_connect_db") + } + + err := registerRoutes(router, ipc) + if err != nil { + return nil, err + } + + return router, nil +} + +// регистрирует маршруты +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}, + } + + // Регистрация всех маршрутов + for _, rh := range routeHandlers { + if errObj := rh.handler(router, ipc); errObj != nil { + return errors.New(fmt.Sprintf("🔴 failed to register %s routes", rh.name)) + } + } + + // Вывод зарегистрированных маршрутов + if err := printRoutes(router, ipc); err != nil { + return errors.New(fmt.Sprintf("🔴 failed to print routes: %v", err)) + } + + return nil +} + +func printRoutes(r chi.Router, ipc *typesm.InternalProviderControl) error { + err := chi.Walk(r, func(method, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error { + logrus.Info(fmt.Sprintf("🩵 [ %s ] %s\n", method, route)) + return nil + }) + if err != nil { + return err + } + return nil +} 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 new file mode 100644 index 0000000..6e1d727 --- /dev/null +++ b/service/rest_admin_service/go.mod @@ -0,0 +1,76 @@ +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/middleware.go b/service/rest_admin_service/handlers/middleware.go new file mode 100644 index 0000000..0b7da34 --- /dev/null +++ b/service/rest_admin_service/handlers/middleware.go @@ -0,0 +1,217 @@ +package handlers + +import ( + configcore "bitrix_balancer_api/core/config" + dbcore "bitrix_balancer_api/core/db/methods" + redismodule "bitrix_balancer_api/core/lib/internally/redis" + "bitrix_balancer_api/core/securecore" + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/core/utilscore" + "bitrix_balancer_api/core/variables" + "context" + "encoding/json" + "errors" + "fmt" + "log" + "net/http" + "strconv" + "strings" + "time" +) + +func BasicAuthMiddleware(username, password string) func(http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + user, pass, ok := r.BasicAuth() + if !ok || !validateCredentials(user, pass, username, password) { + w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`) + http.Error(w, "Unauthorized", http.StatusUnauthorized) + return + } + next.ServeHTTP(w, r) + }) + } +} + +func validateCredentials(username, password, validUsername, validPassword string) bool { + return username == validUsername && password == validPassword +} + +// JWTVerifier middleware для проверки JWT токена и соответствия IP +func JWTVerifier(cfg *configcore.Config, adminDB dbcore.AdminDBI, redisModule *redismodule.ModuleRedis) func(http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if cfg.Secrets.AuthJWT.AdminSecret == "" { + http.Error(w, "Internal server error", http.StatusInternalServerError) + return + } + + authHeader := r.Header.Get("Authorization") + if authHeader == "" { + http.Error(w, "Unauthorized", http.StatusUnauthorized) + return + } + + deviceID := r.Header.Get("x-device-id") + if deviceID == "" { + http.Error(w, "Unauthorized device", http.StatusUnauthorized) + return + } + + if redisModule == nil { + http.Error(w, "Internal server error: Redis storage not initialized", http.StatusInternalServerError) + return + } + + parts := strings.Split(authHeader, " ") + if len(parts) != 2 || parts[0] != "Bearer" { + http.Error(w, "Invalid authorization header", http.StatusUnauthorized) + return + } + tokenString := parts[1] + + _, claims, err := securecore.VerifyToken(tokenString, cfg.Secrets.AuthJWT.AdminSecret) + if err != nil { + http.Error(w, "Invalid token", http.StatusUnauthorized) + return + } + + userIDFloat, ok := claims[securecore.IDContextKey.String()].(float64) + if !ok { + http.Error(w, "Invalid token: missing user_id", http.StatusUnauthorized) + return + } + userID := uint64(userIDFloat) + + adminList, _, errW := adminDB.GetAdminsListDB(typescore.ListDbOptions{ + Filtering: &typescore.Admin{ + ID: &userID, + IsBlocked: utilscore.PointerToBool(false), + }, + }) + if errW != nil || len(adminList) == 0 { + http.Error(w, "Admin not found or blocked", http.StatusUnauthorized) + return + } + + if adminList[0].IsBlocked == nil || *adminList[0].IsBlocked { + http.Error(w, "Forbidden: account is blocked", http.StatusUnauthorized) + return + } + + ctx := context.WithValue(r.Context(), securecore.IDContextKey, userID) + + sessionJSON, err := redisModule.Get(ctx, fmt.Sprintf("%s:admin:%d", variables.RedisPathUserAuthSessions, userID)) + if err != nil || sessionJSON == "" { + http.Error(w, "User session not found. Please authorize again", http.StatusUnauthorized) + return + } + + var session typescore.UsersSessions + if err := json.Unmarshal([]byte(sessionJSON), &session); err != nil { + http.Error(w, "Failed to get user session data. Please authorize again", http.StatusUnauthorized) + return + } + + if !securecore.FindDeviceID(session.AuthorizedDevices, deviceID) { + http.Error(w, "Unauthorized device", http.StatusUnauthorized) + return + } + + next.ServeHTTP(w, r.WithContext(ctx)) + }) + } +} + +// AccessCodeVerifier middleware для проверки Access Code для валидного фронта +func AccessCodeVerifier(cfg *configcore.Config) func(http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if cfg.Secrets.ApiPublicAdmin == "" || cfg.Secrets.ApiPrivateAdmin == "" { + http.Error(w, "Internal server error", http.StatusInternalServerError) + return + } + + authHeader := r.Header.Get("ApiKey") + timestampStr := r.Header.Get("X-Timestamp") + + if authHeader == "" || timestampStr == "" { + http.Error(w, "Unauthorized client", http.StatusUnauthorized) + return + } + + // Парсим timestamp как Unix timestamp + timestampUnix, err := strconv.ParseInt(timestampStr, 10, 64) + if err != nil { + http.Error(w, "Invalid timestamp", http.StatusBadRequest) + return + } + + // Конвертируем Unix timestamp в time.Time + // Unix timestamp всегда представляет время в UTC + timestampTime := time.Unix(timestampUnix, 0).UTC() + now := time.Now().UTC() + + // Округляем время до минут, игнорируя секунды и миллисекунды + // Используем time.Date для явного обнуления секунд и наносекунд + timestampTimeRounded := time.Date( + timestampTime.Year(), timestampTime.Month(), timestampTime.Day(), + timestampTime.Hour(), timestampTime.Minute(), 0, 0, time.UTC, + ) + nowRounded := time.Date( + now.Year(), now.Month(), now.Day(), + now.Hour(), now.Minute(), 0, 0, time.UTC, + ) + + // Проверяем, что timestamp не старше 3 минут и не в будущем + // Используем Before/After для более точной проверки времени + threeMinutesAgo := nowRounded.Add(-3 * time.Minute) + + // Проверяем, что timestamp не не старше 3 минут + if timestampTimeRounded.Before(threeMinutesAgo) { + log.Printf("Timestamp expired - received: %v (rounded: %v), current: %v (rounded: %v), 3min ago: %v", + timestampTime, timestampTimeRounded, now, nowRounded, threeMinutesAgo) + http.Error(w, "Timestamp expired", http.StatusUnauthorized) + return + } + + // Проверяем, что timestamp не в будущем + if timestampTimeRounded.After(nowRounded) { + log.Printf("Timestamp in future - received: %v (rounded: %v), current: %v (rounded: %v)", + timestampTime, timestampTimeRounded, now, nowRounded) + http.Error(w, "Timestamp in future", http.StatusUnauthorized) + return + } + + // Генерируем ожидаемую подпись + expectedSignature := utilscore.GenerateHMACSignature(cfg.Secrets.ApiPublicAdmin, timestampStr, cfg.Secrets.ApiPrivateAdmin) + + // Сравниваем безопасно + if !utilscore.HmacEquals(expectedSignature, authHeader) { + http.Error(w, "Unauthorized client", http.StatusUnauthorized) + return + } + + ctx := context.WithValue(r.Context(), securecore.AccessContextKey, authHeader) + next.ServeHTTP(w, r.WithContext(ctx)) + }) + } +} + +// GetIDFromContext извлекает user id из контекста +func GetIDFromContext(ctx context.Context) (uint64, error) { + address, ok := ctx.Value(securecore.IDContextKey).(uint64) + if !ok { + return 0, errors.New("no id found in context") + } + return address, nil +} + +// GetIPFromContext извлекает user ip из контекста +func GetIPFromContext(ctx context.Context) (string, error) { + address, ok := ctx.Value(securecore.IpContextKey).(string) + if !ok { + return "", errors.New("no ip found in context") + } + return address, 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/register.go b/service/rest_admin_service/handlers/register.go new file mode 100644 index 0000000..88e93fc --- /dev/null +++ b/service/rest_admin_service/handlers/register.go @@ -0,0 +1,131 @@ +package handlers + +import ( + "encoding/json" + "errors" + "github.com/go-chi/chi/v5" + "io" + "net/http" +) + +// ErrorResponse структура для возврата ошибок +type ErrorResponse struct { + ErrorCode int `json:"error_code"` // Код ошибки + ErrorDescription string `json:"error_description"` // Описание ошибки +} + +// WrapHandlerParams структура для параметров обертки +type WrapHandlerParams struct { + HandlerFunc func(http.ResponseWriter, *http.Request) (interface{}, error) +} + +// responseWriterWrapper предотвращает повторный вызов WriteHeader +type responseWriterWrapper struct { + http.ResponseWriter + wroteHeader bool +} + +// WriteHeader перехватывает вызов WriteHeader +func (rw *responseWriterWrapper) WriteHeader(statusCode int) { + if !rw.wroteHeader { + rw.ResponseWriter.WriteHeader(statusCode) + rw.wroteHeader = true + } +} + +// Write перехватывает вызов Write +func (rw *responseWriterWrapper) Write(b []byte) (int, error) { + if !rw.wroteHeader { + rw.WriteHeader(http.StatusOK) // Устанавливаем статус по умолчанию + } + return rw.ResponseWriter.Write(b) +} + +// WrapHandlerF обертка для обработчиков +func WrapHandlerF(p WrapHandlerParams) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + rw := &responseWriterWrapper{ResponseWriter: w} + payload, err := p.HandlerFunc(rw, r) + respondWithJSON(rw, err, payload) + } +} + +// RegisterRoute вспомогательная функция для регистрации маршрутов +func RegisterRoute(r chi.Router, method, path string, handlerFunc func(http.ResponseWriter, *http.Request) (interface{}, error)) { + wrappedHandler := WrapHandlerF(WrapHandlerParams{ + HandlerFunc: handlerFunc, + }) + + switch method { + case http.MethodGet: + r.Get(path, wrappedHandler) + case http.MethodPost: + r.Post(path, wrappedHandler) + case http.MethodPatch: + r.Patch(path, wrappedHandler) + case http.MethodPut: + r.Put(path, wrappedHandler) + case http.MethodDelete: + r.Delete(path, wrappedHandler) + } +} + +// ParseRequestBodyPost обрабатывает тело запроса и заполняет структуру запроса +func ParseRequestBodyPost(r *http.Request, v interface{}) error { + defer r.Body.Close() + + if r.ContentLength == 0 { + return errors.New("body content is empty") + } + + body, err := io.ReadAll(r.Body) + if err != nil { + return err + } + + if err := json.Unmarshal(body, v); err != nil { + return err + } + + return nil +} + +// respondWithJSON отправляет ответ в формате JSON +func respondWithJSON(w http.ResponseWriter, err error, payload interface{}) { + w.Header().Set("Content-Type", "application/json") + + var status int + var response []byte + + if err != nil { + status = http.StatusInternalServerError + errorResponse := ErrorResponse{ + ErrorCode: status, + ErrorDescription: err.Error(), + } + response, _ = json.Marshal(errorResponse) + } else { + response, err = json.Marshal(payload) + if err != nil { + status = http.StatusInternalServerError + errorResponse := ErrorResponse{ + ErrorCode: status, + ErrorDescription: err.Error(), + } + response, _ = json.Marshal(errorResponse) + } else { + status = http.StatusOK + } + } + + // Проверяем, является ли w нашим responseWriterWrapper + if rw, ok := w.(*responseWriterWrapper); ok { + if !rw.wroteHeader { + rw.WriteHeader(status) + } + } else { + w.WriteHeader(status) + } + + _, _ = w.Write(response) +} 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/rest_admin_service/types/module.go b/service/rest_admin_service/types/module.go new file mode 100644 index 0000000..41ddded --- /dev/null +++ b/service/rest_admin_service/types/module.go @@ -0,0 +1,15 @@ +package typesm + +import ( + configcore "bitrix_balancer_api/core/config" + database "bitrix_balancer_api/core/db" + "bitrix_balancer_api/core/lib/external/tgkit" + redismodule "bitrix_balancer_api/core/lib/internally/redis" +) + +type InternalProviderControl struct { + Config *configcore.Config + RedisClient *redismodule.ModuleRedis + TGBotClient *tgkit.Client + Database *database.ModuleDB +} diff --git a/service/rest_admin_service/types/req.go b/service/rest_admin_service/types/req.go new file mode 100644 index 0000000..23e7112 --- /dev/null +++ b/service/rest_admin_service/types/req.go @@ -0,0 +1,13 @@ +package typesm + +type LimitRequest struct { + Limit uint64 `json:"limit"` + Offset uint64 `json:"offset"` +} + +type Response struct { + TotalCount *uint64 `json:"total_count,omitempty"` + Count int `json:"count,omitempty"` + Error *string `json:"error,omitempty"` + Data interface{} `json:"data,omitempty"` +} diff --git a/service/rest_admin_service/version b/service/rest_admin_service/version new file mode 100644 index 0000000..be26007 --- /dev/null +++ b/service/rest_admin_service/version @@ -0,0 +1 @@ +v-0.0.3 \ No newline at end of file diff --git a/service/rest_balancer_service/.gitignore b/service/rest_balancer_service/.gitignore new file mode 100644 index 0000000..8542d90 --- /dev/null +++ b/service/rest_balancer_service/.gitignore @@ -0,0 +1,6 @@ +.env +system-service_app +config.yml +vendor +app +.DS_STORE \ No newline at end of file diff --git a/service/rest_balancer_service/.golangci.yml b/service/rest_balancer_service/.golangci.yml new file mode 100644 index 0000000..84625ed --- /dev/null +++ b/service/rest_balancer_service/.golangci.yml @@ -0,0 +1,52 @@ +linters-settings: + errcheck: # Настройки для линтера errcheck, который проверяет, что ошибки не игнорируются + check-type-assertions: true # Не проверять утверждения типов на ошибки + check-blank: true # Проверять игнорирование ошибок через присваивание в _ + prealloc: # Настройки для линтера prealloc, который предлагает предварительное выделение памяти для срезов + simple: true # Простой режим, предлагает предварительное выделение для простых циклов + range-loops: true # Предлагает предварительное выделение для циклов range + for-loops: false # Не предлагает предварительное выделение для обычных for-циклов + gocyclo: # Настройки для линтера gocyclo, который проверяет сложность функций + min-complexity: 15 # Установите порог сложности, который считаете приемлемым + +linters: + enable: # Список линтеров, которые будут включены + - noctx # Находит отправку HTTP-запроса без контекста.Контекст. + - protogetter # Сообщает о прямом чтении из полей прото-сообщения, когда следует использовать геттеры. + - reassign # Проверяет, что переменные пакета не переназначаются. + - rowserrcheck # Проверяет, успешно ли проверен Rows.Err строк. + - sqlclosecheck # Проверяет, что sql.Rows, sql.Stmt, sqlx.NamedStmt, pgx.Query закрыты. + - ineffassign # Обнаруживает, когда назначения существующим переменным не используются. + - nilerr # Находит код, который возвращает ноль, даже если он проверяет, что ошибка не равна нулю. + - makezero # Проверяет, что нулевые значения создаются правильно + - gochecksumtype # Проверяет, что тип контрольной суммы в go.sum соответствует содержимому + - copyloopvar # Проверяет, что циклические зависимости пакетов не имеют экспортируемых идентификаторов + - exhaustive # Проверьте полноту операторов перечисления. + - errchkjson # Проверяет типы, передаваемые функциям кодирования JSON. Сообщает о неподдерживаемых типах и событиях, при которых проверку возвращаемой ошибки можно опустить. + - durationcheck # Проверяет, что длительность таймаута не равна 0 + - contextcheck # Проверяет, что контекст не игнорируется + - bodyclose # Проверяет, что тело запроса закрывается + - bidichk # Проверяет, что строки в исходном коде не содержат символов из разных языков + - govet # Проверяет код на наличие конструкций, которые могут быть ошибочными + - errcheck # Проверяет, что ошибки не игнорируются + - staticcheck # Статический анализ кода, находит ошибки, неэффективные конструкции и т.д. + - unused # Проверяет на неиспользуемые переменные, функции, константы + - gocritic # Линтер, основанный на проверке кода на соответствие определенным критериям качества и стиля + - stylecheck # Проверяет стиль кодирования + - whitespace # Проверяет проблемы с пробелами в коде + - gosec # Линтер gosec, который проверяет код на наличие потенциальных уязвимостей + - prealloc # Предлагает предварительное выделение памяти для срезов + + - dupl # Находит дублирующийся код + - gocyclo # Проверяет сложность функций + - ineffassign # Обнаруживает неэффективные присваивания + - unparam # Находит неиспользуемые параметры функций + + - gosimple # Предлагает упрощения кода + + disable: # Список линтеров, которые будут отключены + - gofumpt # Более строгая версия gofmt, применяет дополнительные правила форматирования + # - golint # Отключает golint, который проверяет стиль написания кода на Go + +run: + timeout: 15m # Устанавливает тайм-аут для выполнения всех линтеров \ No newline at end of file diff --git a/service/rest_balancer_service/Dockerfile b/service/rest_balancer_service/Dockerfile new file mode 100644 index 0000000..1d36a15 --- /dev/null +++ b/service/rest_balancer_service/Dockerfile @@ -0,0 +1,15 @@ +# FROM ubuntu:22.04 +FROM kartashs/ubuntu:22.04 + +WORKDIR /app + +# Определяем аргумент сборки +ARG APP_NAME + +COPY ./${APP_NAME} /app/${APP_NAME} + +RUN chmod +x /app/${APP_NAME} + +RUN echo "APP_NAME=${APP_NAME}" + +CMD ["sh", "-c", "/app/${APP_NAME}"] \ No newline at end of file diff --git a/service/rest_balancer_service/build.sh b/service/rest_balancer_service/build.sh new file mode 100644 index 0000000..e8af79c --- /dev/null +++ b/service/rest_balancer_service/build.sh @@ -0,0 +1,21 @@ +#!/bin/bash + +SERVICE_PATH=$(dirname "$(realpath "$0")") +SERVICE_NAME="rest_base_service" # Название сервиса +PARENT_PATH=$(dirname "$SERVICE_PATH") +BACKEND_PATH=$(dirname "$PARENT_PATH") + +set -e +trap 'echo "🔴 Error build $SERVICE_NAME"; exit 1' ERR + +sudo ls +echo "🟡 Start Build: $SERVICE_NAME" +echo "🔵 SERVICE_PATH: $SERVICE_PATH" +echo "🔵 BACKEND_PATH: $BACKEND_PATH" + +go mod tidy + +go build -o "${SERVICE_NAME}_app" "$SERVICE_PATH/cmd/app.go" +sudo chmod +x "${SERVICE_NAME}_app" + +echo "🟢 Finish build $SERVICE_NAME generate" \ No newline at end of file diff --git a/service/rest_balancer_service/cmd/app.go b/service/rest_balancer_service/cmd/app.go new file mode 100644 index 0000000..3076792 --- /dev/null +++ b/service/rest_balancer_service/cmd/app.go @@ -0,0 +1,172 @@ +package main + +import ( + configcore "bitrix_balancer_api/core/config" + clientcontrollers "bitrix_balancer_api/core/lib/internally/client-controllers" + "bitrix_balancer_api/core/lib/internally/redis" + "bitrix_balancer_api/core/utilscore" + balancerhandler "bitrix_balancer_api/rest_base_service/handler/balancer" + "bitrix_balancer_api/rest_base_service/types" + "errors" + "fmt" + "github.com/go-chi/chi/v5" + "github.com/go-chi/chi/v5/middleware" + "github.com/go-chi/cors" + "github.com/go-chi/httprate" + "github.com/sirupsen/logrus" + "log" + "net" + "net/http" + "time" +) + +const ( + readTimeout = 15 * time.Minute // Таймаут чтения + writeTimeout = 15 * time.Minute // Таймаут записи + idleTimeout = 15 * time.Minute // Таймаут бездействия + rateLimit = 25 // Лимит запросов + rateWindow = 1 * time.Second // Окно времени для лимита запросов +) + +func main() { + // Получение конфигурации приложения + appConfig, clientsExternal, err := getClientsExternal() + if err != nil { + logrus.Error("error getting external clients", err) + return + } + + // ** Инициализация модулей + ipc, err := initInternalProvider(appConfig, clientsExternal) + if err != nil { + logrus.Error("error initializing internal provider", err) + return + } + + decreasePerSec := redismodule.QuotaDecreaseDefault + if appConfig.Bitrix.IsEnterprise { + decreasePerSec = redismodule.QuotaDecreaseEnterprise + } + + go ipc.RedisClient.StartQuotaLeaker(ipc.Config.Bitrix.PortalID, decreasePerSec) + + startRest(ipc) +} + +func getClientsExternal() (*configcore.Config, clientcontrollers.ClientsExternal, error) { + options := &configcore.ConfigLoadOptions{ + Redis: true, + Bitrix: true, + Secrets: true, + Server: configcore.ExposedServiceOptions{ + RESTBaseService: true, + }, + } + + return clientcontrollers.ReturnClientsExternal(options) +} + +func initInternalProvider(cfg *configcore.Config, clientsExternal clientcontrollers.ClientsExternal) (*types.InternalProviderControl, error) { + return &types.InternalProviderControl{ + Config: cfg, + RedisClient: clientsExternal.Redis, + }, nil +} + +// запуск сервера REST API +func startRest(ipc *types.InternalProviderControl) { + router := chi.NewRouter() + corsOptions := cors.New(cors.Options{ + AllowedOrigins: []string{"*"}, + AllowedMethods: []string{http.MethodGet, http.MethodPost, http.MethodPut, http.MethodDelete, http.MethodOptions}, + AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "Cache-Control", "X-Requested-With", "x-api"}, + ExposedHeaders: []string{"Link", "Cache-Control"}, + AllowCredentials: false, + MaxAge: 300, // Максимальное время жизни предварительных запросов в секундах + }) + + router.Use(corsOptions.Handler) + router.Use(middleware.RealIP) + // Глобальный перехват паник, чтобы сервис продолжал работать + router.Use(utilscore.RecoverMiddleware()) + // Добавляем ограничение по IP + router.Use(httprate.LimitByIP(rateLimit, rateWindow)) + + // Регистрация обработчиков + err := registerRoutes(router, ipc) + if err != nil { + logrus.Error(err) + return + } + + serverBind := ipc.Config.Server.RESTBaseService.BindRest + serverPort := ipc.Config.Server.RESTBaseService.PortRest + if serverBind == "" || serverPort == 0 { + log.Fatal(errors.New("rest_balancer_service: missed bind or port params")) + } + serverStartURI := fmt.Sprintf("%s:%d", + serverBind, + serverPort) + + listener, err := net.Listen("tcp", serverStartURI) + if err != nil { + logrus.Error("🛑 error start listener: ", err) + log.Fatal(err) + } + + httpServer := &http.Server{ + Handler: router, + ReadTimeout: readTimeout, + WriteTimeout: writeTimeout, + IdleTimeout: idleTimeout, + } + + log.Println("✅ Application initialized and started: ", serverStartURI) + + if err := httpServer.Serve(listener); err != nil { + switch { + case errors.Is(err, http.ErrServerClosed): + logrus.Error("🛑 Server shutdown") + default: + log.Fatal(err) + } + } +} + +// регистрирует маршруты +func registerRoutes(router chi.Router, ipc *types.InternalProviderControl) error { + // Слайс обработчиков маршрутов + routeHandlers := []struct { + name string + handler func(chi.Router, *types.InternalProviderControl) error + }{ + {"balancer_base", balancerhandler.RegisterBalancerRoutes}, + } + + // Регистрация всех маршрутов + for _, rh := range routeHandlers { + if errObj := rh.handler(router, ipc); errObj != nil { + logrus.Errorln("🔴 failed to register", rh.name, "routes:", errObj) + return fmt.Errorf("🔴 failed to register %s routes", rh.name) + } + } + + // Вывод зарегистрированных маршрутов + if err := printRoutes(router); err != nil { + logrus.Errorln("🔴 failed to print routes:", err) + return fmt.Errorf("🔴 failed to print routes: %w", err) + } + + return nil +} + +func printRoutes(r chi.Router) error { + err := chi.Walk(r, func(method, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error { + return nil + }) + if err != nil { + logrus.Error("failed to walk routes: ", err) + return err + } + return nil +} diff --git a/service/rest_balancer_service/docker_run.sh b/service/rest_balancer_service/docker_run.sh new file mode 100644 index 0000000..579a7a2 --- /dev/null +++ b/service/rest_balancer_service/docker_run.sh @@ -0,0 +1,119 @@ +#!/bin/bash + +set -e +trap 'echo "🔴 Скрипт остановлен"; exit' SIGINT + +# Должен ли порт быть доступен снаружи +OPEN_PORT_EXTERNALLY="true" +# Порт хоста +HOST_PORT=15000 +# Наименование сервиса +SERVICE_NAME="main_app" + +# Имя сети Docker +DOCKER_NETWORK_NAME="networklocal1" +# Список дополнительных сетей Docker, к которым нужно подключить контейнер +ADDITIONAL_DOCKER_NETWORKS="" + +# IP-адрес для добавления в hosts контейнера +DATABASE_HOST_IP="" + +W_BUILD="false" +W_START="false" + +# Разбор именованных аргументов +while [ $# -gt 0 ]; do + case "$1" in + OPEN_PORT_EXTERNALLY=*) + OPEN_PORT_EXTERNALLY="${1#*=}" + ;; + HOST_PORT=*) + HOST_PORT="${1#*=}" + ;; + SERVICE_NAME=*) + SERVICE_NAME="${1#*=}" + ;; + DOCKER_NETWORK_NAME=*) + DOCKER_NETWORK_NAME="${1#*=}" + ;; + DATABASE_HOST_IP=*) + DATABASE_HOST_IP="${1#*=}" + ;; + W_BUILD=*) + W_BUILD="${1#*=}" + ;; + W_START=*) + W_START="${1#*=}" + ;; + *) + echo "Ошибка: Неизвестный параметр $1" >&2 + exit 1 + ;; + esac + shift +done + + +# Наименование образа +IMAGE_NAME="${SERVICE_NAME}_balancer_i" +# Наименование контейнера +CONTAINER_NAME="${SERVICE_NAME}_balancer_c" +# Имя приложения +APP_NAME="${SERVICE_NAME}_app" + + +if [ "$W_BUILD" = "true" ]; then + # Билд бинарника + ./build.sh $APP_NAME + + # Собираем образ + docker build --no-cache --build-arg APP_NAME=$APP_NAME -t $IMAGE_NAME . +fi + + +# Проверка и выполнение запуска контейнера +if [ "$W_START" = "true" ]; then + # Останавливаем и удаляем существующий контейнер, если он существует + # Проверяем существование контейнера перед его остановкой и удалением + if docker ps -a --format "{{.Names}}" | grep -w "^$CONTAINER_NAME$"; then + docker stop $CONTAINER_NAME + docker rm $CONTAINER_NAME + fi + + # Определяем, нужно ли открывать порт для внешнего мира + PORT_MAPPING="" + if [ "$OPEN_PORT_EXTERNALLY" = "true" ]; then + PORT_MAPPING="-p $HOST_PORT:$HOST_PORT" + fi + + if [ -n "$DATABASE_HOST_IP" ]; then + ADD_HOST_OPTION="--add-host=database_host:$DATABASE_HOST_IP" + else + ADD_HOST_OPTION="" + fi + + # Проверяем существование сети и создаем, если не существует + docker network ls | grep $DOCKER_NETWORK_NAME || docker network create $DOCKER_NETWORK_NAME + + # Запускаем контейнер с новым образом в сетевом режиме host и подключаем к сети по имени + docker run -d \ + $PORT_MAPPING \ + $ADD_HOST_OPTION \ + --network $DOCKER_NETWORK_NAME \ + --restart always \ + --name $CONTAINER_NAME \ + -e APP_NAME=$APP_NAME \ + $IMAGE_NAME + + # Подключаем контейнер к дополнительным сетям Docker, если список не пустой + if [ -n "$ADDITIONAL_DOCKER_NETWORKS" ]; then + for network in $ADDITIONAL_DOCKER_NETWORKS; do + docker network connect $network $CONTAINER_NAME + echo "🟢 Container $CONTAINER_NAME is connected to additional network $network" + done + fi + + echo "🟢 Container $CONTAINER_NAME is running on port $HOST_PORT" +fi + +echo "🟢 Скрипт завершен $APP_NAME" diff --git a/service/rest_balancer_service/go.mod b/service/rest_balancer_service/go.mod new file mode 100644 index 0000000..ff46a19 --- /dev/null +++ b/service/rest_balancer_service/go.mod @@ -0,0 +1,27 @@ +module bitrix_balancer_api/rest_base_service + +go 1.25.6 + +replace bitrix_balancer_api/core => ../../core + +require ( + bitrix_balancer_api/core v0.0.0-00010101000000-000000000000 + github.com/go-chi/chi/v5 v5.2.5 + github.com/go-chi/cors v1.2.2 + github.com/go-chi/httprate v0.15.0 + github.com/sirupsen/logrus v1.9.4 +) + +require ( + github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/klauspost/cpuid/v2 v2.2.10 // indirect + github.com/mitchellh/mapstructure v1.5.0 // indirect + github.com/redis/go-redis/v9 v9.18.0 // indirect + github.com/shopspring/decimal v1.4.0 // indirect + github.com/zeebo/xxh3 v1.0.2 // indirect + go.uber.org/atomic v1.11.0 // indirect + golang.org/x/sys v0.41.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/service/rest_balancer_service/go.sum b/service/rest_balancer_service/go.sum new file mode 100644 index 0000000..86b5998 --- /dev/null +++ b/service/rest_balancer_service/go.sum @@ -0,0 +1,46 @@ +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/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.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/go-chi/chi/v5 v5.2.5 h1:Eg4myHZBjyvJmAFjFvWgrqDTXFyOzjj7YIm3L3mu6Ug= +github.com/go-chi/chi/v5 v5.2.5/go.mod h1:X7Gx4mteadT3eDOMTsXzmI4/rwUpOwBHLpAfupzFJP0= +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/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/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE= +github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= +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/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/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +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= +golang.org/x/sync v0.12.0 h1:MHc5BpPuC30uJk597Ri8TV3CNZcTLu6B6z4lJy+g6Jw= +golang.org/x/sync v0.12.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= +golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k= +golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/service/rest_balancer_service/handler/balancer/handler.go b/service/rest_balancer_service/handler/balancer/handler.go new file mode 100644 index 0000000..dd88b50 --- /dev/null +++ b/service/rest_balancer_service/handler/balancer/handler.go @@ -0,0 +1,65 @@ +package balancerhandler + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/rest_base_service/handler" + "context" + "fmt" + "net/http" + "time" +) + +const ( + quotaPollInterval = 2 * time.Second + quotaPollTimeout = 5 * time.Minute + bitrixPageSize = 50 + maxSafetyPages = 500 // страховка: не более 25 000 записей за один вызов +) + +// SendRequestHandler — POST /api/balancer/send +// Принимает запрос, ждёт свободную квоту и проксирует в Bitrix24 +func (s *BalancerReg) SendRequestHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + var req typescore.BalancerRequest + if err := handler.ParseRequestBodyPost(r, &req); err != nil { + return nil, fmt.Errorf("invalid request body: %w", err) + } + if req.URL == nil || req.Method == nil { + return nil, fmt.Errorf("url and method are required") + } + + quotaLimit, _ := quotaParams(s.ipc.Config.Bitrix.IsEnterprise) + + ctx, cancel := context.WithTimeout(r.Context(), quotaPollTimeout) + defer cancel() + + if req.IsRecurrent { + return s.sendRecurrentRequest(ctx, &req, quotaLimit) + } + return s.sendSingleRequest(ctx, &req, quotaLimit) +} + +// GetQuotaHandler — GET /api/balancer/quota +func (s *BalancerReg) GetQuotaHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { + limit, decreasePerSec := quotaParams(s.ipc.Config.Bitrix.IsEnterprise) + + ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second) + defer cancel() + + counter, err := s.ipc.RedisClient.GetQuotaCounter(ctx, s.ipc.Config.Bitrix.PortalID) + if err != nil { + return nil, fmt.Errorf("failed to get quota: %w", err) + } + + freeSlots := limit - counter + if freeSlots < 0 { + freeSlots = 0 + } + + return &typescore.QuotaResponse{ + PortalID: &s.ipc.Config.Bitrix.PortalID, + Counter: &counter, + Limit: &limit, + FreeSlots: &freeSlots, + DecreasePerSec: &decreasePerSec, + }, nil +} diff --git a/service/rest_balancer_service/handler/balancer/routes.go b/service/rest_balancer_service/handler/balancer/routes.go new file mode 100644 index 0000000..2b0ad83 --- /dev/null +++ b/service/rest_balancer_service/handler/balancer/routes.go @@ -0,0 +1,30 @@ +package balancerhandler + +import ( + "bitrix_balancer_api/rest_base_service/handler" + "bitrix_balancer_api/rest_base_service/types" + "github.com/go-chi/chi/v5" + "net/http" +) + +type BalancerReg struct { + ipc *types.InternalProviderControl +} + +func RegisterBalancerRoutes( + r chi.Router, + ipc *types.InternalProviderControl, +) error { + s := &BalancerReg{ + ipc: ipc, + } + + r.Route("/api/balancer", func(r chi.Router) { + r.Use(handler.AccessCodeVerifier(ipc.Config)) + + handler.RegisterRoute(r, http.MethodPost, "/send", s.SendRequestHandler) // отправить запрос + handler.RegisterRoute(r, http.MethodGet, "/quota", s.GetQuotaHandler) // получить квоту + }) + + return nil +} diff --git a/service/rest_balancer_service/handler/balancer/utils.go b/service/rest_balancer_service/handler/balancer/utils.go new file mode 100644 index 0000000..859bf3e --- /dev/null +++ b/service/rest_balancer_service/handler/balancer/utils.go @@ -0,0 +1,229 @@ +package balancerhandler + +import ( + redismodule "bitrix_balancer_api/core/lib/internally/redis" + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/core/utilscore" + "bytes" + "context" + "encoding/json" + "fmt" + "github.com/sirupsen/logrus" + "io" + "net/http" + "time" +) + +// sendSingleRequest — один запрос без пагинации +func (s *BalancerReg) sendSingleRequest( + ctx context.Context, + req *typescore.BalancerRequest, + quotaLimit int64, +) (interface{}, error) { + if err := s.waitForQuota(ctx, s.ipc.Config.Bitrix.PortalID, quotaLimit); err != nil { + return nil, fmt.Errorf("quota timeout: %w", err) + } + + resp, err := s.proxyRequest(ctx, req) + if err != nil { + s.ipc.RedisClient.DecrementQuota(context.Background(), s.ipc.Config.Bitrix.PortalID, 1) + return nil, fmt.Errorf("proxy request failed: %w", err) + } + + freeSlots, _ := s.ipc.RedisClient.GetFreeQuota(context.Background(), s.ipc.Config.Bitrix.PortalID, quotaLimit) + return &typescore.BalancerResponse{ + StatusCode: utilscore.PointerToInt(resp.StatusCode), + Body: resp.Body, + QuotaLeft: &freeSlots, + }, nil +} + +// sendRecurrentRequest — загружает ВСЕ записи постранично. +// Крутит цикл пока Bitrix24 возвращает next, учитывая квоту перед каждым запросом. +func (s *BalancerReg) sendRecurrentRequest( + ctx context.Context, + req *typescore.BalancerRequest, + quotaLimit int64, +) (interface{}, error) { + allItems := make([]interface{}, 0) + start := 0 + + for page := 0; page < maxSafetyPages; page++ { + // Ждём свободную квоту перед каждым запросом + if err := s.waitForQuota(ctx, s.ipc.Config.Bitrix.PortalID, quotaLimit); err != nil { + return nil, fmt.Errorf("quota timeout on page %d: %w", page+1, err) + } + + // Инжектируем start в тело + pageBody := make(map[string]interface{}) + for k, v := range req.Body { + pageBody[k] = v + } + pageBody["start"] = start + + pageReq := *req + pageReq.Body = pageBody + + resp, err := s.proxyRequest(ctx, &pageReq) + if err != nil { + s.ipc.RedisClient.DecrementQuota(context.Background(), s.ipc.Config.Bitrix.PortalID, 1) + return nil, fmt.Errorf("proxy request failed on page %d: %w", page+1, err) + } + + items, nextStart, err := extractPageItems(resp.Body, req.ResultKey) + if err != nil { + return nil, fmt.Errorf("failed to parse page %d: %w", page+1, err) + } + + allItems = append(allItems, items...) + + logrus.Infof("📦 recurrent fetch: page=%d start=%d got=%d total=%d", + page+1, start, len(items), len(allItems)) + + // Нет следующей страницы — все записи получены + if nextStart <= 0 || len(items) < bitrixPageSize { + break + } + start = nextStart + } + + total := len(allItems) + freeSlots, _ := s.ipc.RedisClient.GetFreeQuota(context.Background(), s.ipc.Config.Bitrix.PortalID, quotaLimit) + + return &typescore.BalancerResponse{ + StatusCode: utilscore.PointerToInt(200), + Body: allItems, + QuotaLeft: &freeSlots, + IsRecurrent: true, + TotalFetched: &total, + }, nil +} + +// waitForQuota блокирует выполнение пока не появится свободная квота. +// Проверяет каждые 2 секунды согласно требованию. +func (s *BalancerReg) waitForQuota(ctx context.Context, portalID string, limit int64) error { + for { + acquired, err := s.ipc.RedisClient.TryAcquireQuota(ctx, portalID, limit) + if err != nil { + return err + } + if acquired { + return nil + } + + logrus.Infof("⏳ quota exhausted for portal %s, waiting %v...", portalID, quotaPollInterval) + + select { + case <-ctx.Done(): + return fmt.Errorf("quota wait timeout exceeded") + case <-time.After(quotaPollInterval): + // повторяем проверку + } + } +} + +// proxyRequest выполняет реальный HTTP-запрос к Bitrix24 +func (s *BalancerReg) proxyRequest(ctx context.Context, req *typescore.BalancerRequest) (*proxyResult, error) { + if req.Body == nil || req.Method == nil || req.URL == nil { + return nil, fmt.Errorf("body or method or url is required") + } + var bodyReader io.Reader + if req.Body != nil && req.Method != nil && (*req.Method == http.MethodPost || *req.Method == http.MethodPut) { + bodyBytes, err := json.Marshal(req.Body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(bodyBytes) + } + + httpReq, err := http.NewRequestWithContext(ctx, *req.Method, *req.URL, bodyReader) + if err != nil { + return nil, err + } + + // Проставляем заголовки от клиента + for k, v := range req.Headers { + httpReq.Header.Set(k, v) + } + if req.Body != nil { + httpReq.Header.Set("Content-Type", "application/json") + } + + client := &http.Client{Timeout: 30 * time.Second} + resp, err := client.Do(httpReq) + if err != nil { + return nil, err + } + defer resp.Body.Close() + + respBytes, err := io.ReadAll(resp.Body) + if err != nil { + return nil, err + } + + var respBody interface{} + if err := json.Unmarshal(respBytes, &respBody); err != nil { + // не JSON — возвращаем как строку + respBody = string(respBytes) + } + + return &proxyResult{ + StatusCode: resp.StatusCode, + Body: respBody, + }, nil +} + +type proxyResult struct { + StatusCode int + Body interface{} +} + +// quotaParams возвращает лимит и скорость декремента по тарифу +func quotaParams(isEnterprise bool) (limit int64, decreasePerSec int64) { + if isEnterprise { + return redismodule.QuotaLimitEnterprise, redismodule.QuotaDecreaseEnterprise + } + return redismodule.QuotaLimitDefault, redismodule.QuotaDecreaseDefault +} + +func extractPageItems(body interface{}, resultKey *string) ([]interface{}, int, error) { + bodyMap, ok := body.(map[string]interface{}) + if !ok { + return nil, 0, fmt.Errorf("unexpected response format") + } + + nextStart := 0 + if nextVal, ok := bodyMap["next"]; ok { + switch v := nextVal.(type) { + case float64: + nextStart = int(v) + case int: + nextStart = v + } + } + + resultRaw, ok := bodyMap["result"] + if !ok { + return nil, 0, fmt.Errorf("no 'result' field in response") + } + + // Вложенный ключ — например "tasks" для tasks.task.list + if resultKey != nil && *resultKey != "" { + resultObj, ok := resultRaw.(map[string]interface{}) + if !ok { + return nil, 0, fmt.Errorf("result is not an object, cannot use result_key '%s'", *resultKey) + } + nested, ok := resultObj[*resultKey] + if !ok { + return nil, 0, fmt.Errorf("result_key '%s' not found in result", *resultKey) + } + resultRaw = nested + } + + items, ok := resultRaw.([]interface{}) + if !ok { + return nil, 0, fmt.Errorf("result is not an array") + } + + return items, nextStart, nil +} diff --git a/service/rest_balancer_service/handler/handler.go b/service/rest_balancer_service/handler/handler.go new file mode 100644 index 0000000..407f86a --- /dev/null +++ b/service/rest_balancer_service/handler/handler.go @@ -0,0 +1,131 @@ +package handler + +import ( + "encoding/json" + "errors" + "github.com/go-chi/chi/v5" + "io" + + "net/http" +) + +// ErrorResponse структура для возврата ошибок +type ErrorResponse struct { + ErrorCode int `json:"error_code"` // Код ошибки + ErrorDescription string `json:"error_description"` // Описание ошибки +} + +// WrapHandlerParams структура для параметров обертки +type WrapHandlerParams struct { + HandlerFunc func(http.ResponseWriter, *http.Request) (interface{}, error) +} + +// responseWriterWrapper предотвращает повторный вызов WriteHeader +type responseWriterWrapper struct { + http.ResponseWriter + wroteHeader bool +} + +// WriteHeader перехватывает вызов WriteHeader +func (rw *responseWriterWrapper) WriteHeader(statusCode int) { + if !rw.wroteHeader { + rw.ResponseWriter.WriteHeader(statusCode) + rw.wroteHeader = true + } +} + +// Write перехватывает вызов Write +func (rw *responseWriterWrapper) Write(b []byte) (int, error) { + if !rw.wroteHeader { + rw.WriteHeader(http.StatusOK) // Устанавливаем статус по умолчанию + } + return rw.ResponseWriter.Write(b) +} + +// WrapHandlerF обертка для обработчиков +func WrapHandlerF(p WrapHandlerParams) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + rw := &responseWriterWrapper{ResponseWriter: w} + payload, err := p.HandlerFunc(rw, r) + respondWithJSON(rw, err, payload) + } +} + +// RegisterRoute вспомогательная функция для регистрации маршрутов +func RegisterRoute(r chi.Router, method, path string, handlerFunc func(http.ResponseWriter, *http.Request) (interface{}, error)) { + wrappedHandler := WrapHandlerF(WrapHandlerParams{ + HandlerFunc: handlerFunc, + }) + switch method { + case http.MethodGet: + r.Get(path, wrappedHandler) + case http.MethodPost: + r.Post(path, wrappedHandler) + case http.MethodPatch: + r.Patch(path, wrappedHandler) + case http.MethodPut: + r.Put(path, wrappedHandler) + case http.MethodDelete: + r.Delete(path, wrappedHandler) + } +} + +// ParseRequestBodyPost обрабатывает тело запроса и заполняет структуру запроса +func ParseRequestBodyPost(r *http.Request, v interface{}) error { + defer r.Body.Close() + + if r.ContentLength == 0 { + return errors.New("body content is empty") + } + + body, err := io.ReadAll(r.Body) + if err != nil { + return err + } + + if err := json.Unmarshal(body, v); err != nil { + return err + } + + return nil +} + +// respondWithJSON отправляет ответ в формате JSON +func respondWithJSON(w http.ResponseWriter, err error, payload interface{}) { + w.Header().Set("Content-Type", "application/json") + + var status int + var response []byte + + if err != nil { + status = http.StatusInternalServerError + errorResponse := ErrorResponse{ + ErrorCode: status, + ErrorDescription: err.Error(), + } + response, _ = json.Marshal(errorResponse) + } else { + response, err = json.Marshal(payload) + if err != nil { + status = http.StatusInternalServerError + errorResponse := ErrorResponse{ + ErrorCode: status, + ErrorDescription: err.Error(), + } + response, _ = json.Marshal(errorResponse) + } else { + status = http.StatusOK + } + } + + // Проверяем, является ли w нашим responseWriterWrapper + if rw, ok := w.(*responseWriterWrapper); ok { + if !rw.wroteHeader { + rw.WriteHeader(status) + } + } else { + w.WriteHeader(status) + } + + _, _ = w.Write(response) +} diff --git a/service/rest_balancer_service/handler/middleware.go b/service/rest_balancer_service/handler/middleware.go new file mode 100644 index 0000000..fa1f00f --- /dev/null +++ b/service/rest_balancer_service/handler/middleware.go @@ -0,0 +1,76 @@ +package handler + +import ( + configcore "bitrix_balancer_api/core/config" + "bitrix_balancer_api/core/utilscore" + "bitrix_balancer_api/core/variables" + "context" + "log" + "net/http" + "strconv" + "time" +) + +// AccessCodeVerifier middleware для проверки API Signature для валидного клиента +func AccessCodeVerifier(cfg *configcore.Config) func(http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if cfg.Secrets.ApiPublicBase == "" || cfg.Secrets.ApiPrivateBase == "" { + http.Error(w, "Servers secrets not configured", http.StatusInternalServerError) + return + } + + authHeader := r.Header.Get("X-Signature") + timestampStr := r.Header.Get("X-Timestamp") + + if authHeader == "" || timestampStr == "" { + http.Error(w, "Unauthorized client", http.StatusUnauthorized) + return + } + + timestampUnix, err := strconv.ParseInt(timestampStr, 10, 64) + if err != nil { + http.Error(w, "Invalid timestamp", http.StatusBadRequest) + return + } + + timestampTime := time.Unix(timestampUnix, 0).UTC() + now := time.Now().UTC() + + timestampTimeRounded := time.Date( + timestampTime.Year(), timestampTime.Month(), timestampTime.Day(), + timestampTime.Hour(), timestampTime.Minute(), 0, 0, time.UTC, + ) + nowRounded := time.Date( + now.Year(), now.Month(), now.Day(), + now.Hour(), now.Minute(), 0, 0, time.UTC, + ) + + threeMinutesAgo := nowRounded.Add(-3 * time.Minute) + + if timestampTimeRounded.Before(threeMinutesAgo) { + log.Printf("Timestamp expired - received: %v (rounded: %v), current: %v (rounded: %v), 3min ago: %v", + timestampTime, timestampTimeRounded, now, nowRounded, threeMinutesAgo) + http.Error(w, "Timestamp expired", http.StatusUnauthorized) + return + } + + if timestampTimeRounded.After(nowRounded) { + log.Printf("Timestamp in future - received: %v (rounded: %v), current: %v (rounded: %v)", + timestampTime, timestampTimeRounded, now, nowRounded) + http.Error(w, "Timestamp in future", http.StatusUnauthorized) + return + } + + expectedSignature := utilscore.GenerateHMACSignature(cfg.Secrets.ApiPublicBase, timestampStr, cfg.Secrets.ApiPrivateBase) + + if !utilscore.HmacEquals(expectedSignature, authHeader) { + http.Error(w, "Unauthorized client", http.StatusUnauthorized) + return + } + + ctx := context.WithValue(r.Context(), variables.AccessContextKey, authHeader) + next.ServeHTTP(w, r.WithContext(ctx)) + }) + } +} diff --git a/service/rest_balancer_service/types/handler.go b/service/rest_balancer_service/types/handler.go new file mode 100644 index 0000000..0ed334d --- /dev/null +++ b/service/rest_balancer_service/types/handler.go @@ -0,0 +1,12 @@ +package types + +import ( + "net/http" +) + +// структура для представления маршрута с добавлением новых параметров +type RouteParams struct { + Method string // метод запроса + Url string // url + HandlerFunc func(w http.ResponseWriter, r *http.Request) (interface{}, *uint64, error) // функция обработчик +} diff --git a/service/rest_balancer_service/types/types.go b/service/rest_balancer_service/types/types.go new file mode 100644 index 0000000..eba2496 --- /dev/null +++ b/service/rest_balancer_service/types/types.go @@ -0,0 +1,12 @@ +package types + +import ( + configcore "bitrix_balancer_api/core/config" + redismodule "bitrix_balancer_api/core/lib/internally/redis" +) + +type InternalProviderControl struct { + Config *configcore.Config + + RedisClient *redismodule.ModuleRedis +} diff --git a/service/rest_user_service/cmd/app.go b/service/rest_user_service/cmd/app.go new file mode 100644 index 0000000..7905807 --- /dev/null +++ b/service/rest_user_service/cmd/app.go @@ -0,0 +1,5 @@ +package main + +func main() { + +} diff --git a/service/system_service/.gitignore b/service/system_service/.gitignore new file mode 100644 index 0000000..8542d90 --- /dev/null +++ b/service/system_service/.gitignore @@ -0,0 +1,6 @@ +.env +system-service_app +config.yml +vendor +app +.DS_STORE \ No newline at end of file diff --git a/service/system_service/.golangci.yml b/service/system_service/.golangci.yml new file mode 100644 index 0000000..ea1405d --- /dev/null +++ b/service/system_service/.golangci.yml @@ -0,0 +1,52 @@ +linters-settings: + errcheck: # Настройки для линтера errcheck, который проверяет, что ошибки не игнорируются + check-type-assertions: true # Не проверять утверждения типов на ошибки + check-blank: true # Проверять игнорирование ошибок через присваивание в _ + prealloc: # Настройки для линтера prealloc, который предлагает предварительное выделение памяти для срезов + simple: true # Простой режим, предлагает предварительное выделение для простых циклов + range-loops: true # Предлагает предварительное выделение для циклов range + for-loops: false # Не предлагает предварительное выделение для обычных for-циклов + gocyclo: # Настройки для линтера gocyclo, который проверяет сложность функций + min-complexity: 15 # Установите порог сложности, который считаете приемлемым + +linters: + enable: # Список линтеров, которые будут включены + - noctx # Находит отправку HTTP-запроса без контекста.Контекст. + - protogetter # Сообщает о прямом чтении из полей прото-сообщения, когда следует использовать геттеры. + - reassign # Проверяет, что переменные пакета не переназначаются. + - rowserrcheck # Проверяет, успешно ли проверен Rows.Err строк. + - sqlclosecheck # Проверяет, что sql.Rows, sql.Stmt, sqlx.NamedStmt, pgx.Query закрыты. + - ineffassign # Обнаруживает, когда назначения существующим переменным не используются. + - nilerr # Находит код, который возвращает ноль, даже если он проверяет, что ошибка не равна нулю. + - makezero # Проверяет, что нулевые значения создаются правильно + - gochecksumtype # Проверяет, что тип контрольной суммы в go.sum соответствует содержимому + - copyloopvar # Проверяет, что циклические зависимости пакетов не имеют экспортируемых идентификаторов + - exhaustive # Проверьте полноту операторов перечисления. + - errchkjson # Проверяет типы, передаваемые функциям кодирования JSON. Сообщает о неподдерживаемых типах и событиях, при которых проверку возвращаемой ошибки можно опустить. + - durationcheck # Проверяет, что длительность таймаута не равна 0 + - contextcheck # Проверяет, что контекст не игнорируется + - bodyclose # Проверяет, что тело запроса закрывается + - bidichk # Проверяет, что строки в исходном коде не содержат символов из разных языков + - govet # Проверяет код на наличие конструкций, которые могут быть ошибочными + - errcheck # Проверяет, что ошибки не игнорируются + - staticcheck # Статический анализ кода, находит ошибки, неэффективные конструкции и т.д. + - unused # Проверяет на неиспользуемые переменные, функции, константы + - gocritic # Линтер, основанный на проверке кода на соответствие определенным критериям качества и стиля + - stylecheck # Проверяет стиль кодирования + - whitespace # Проверяет проблемы с пробелами в коде + - gosec # Линтер gosec, который проверяет код на наличие потенциальных уязвимостей + - prealloc # Предлагает предварительное выделение памяти для срезов + + - dupl # Находит дублирующийся код + - gocyclo # Проверяет сложность функций + - ineffassign # Обнаруживает неэффективные присваивания + - unparam # Находит неиспользуемые параметры функций + + - gosimple # Предлагает упрощения кода + + disable: # Список линтеров, которые будут отключены + - gofumpt # Более строгая версия gofmt, применяет дополнительные правила форматирования + # - golint # Отключает golint, который проверяет стиль написания кода на Go + +run: + timeout: 15m # Устанавливает тайм-аут для выполнения всех линтеров \ No newline at end of file diff --git a/service/system_service/Dockerfile b/service/system_service/Dockerfile new file mode 100644 index 0000000..ef05f7e --- /dev/null +++ b/service/system_service/Dockerfile @@ -0,0 +1,29 @@ +# Используем официальный образ Go для сборки приложения +FROM golang:1.24.2 AS builder + +# Рабочая директория +WORKDIR /app + +# Определяем аргумент сборки +ARG APP_NAME +RUN echo "APP_NAME=${APP_NAME}" + +# Копируем код внутрь контейнера +COPY . . + +# Сборка приложения +RUN go build -o ${APP_NAME} ./cmd/app.go + +# Создаём конечный образ на основе Ubuntu +FROM kartashs/ubuntu:22.04 + +WORKDIR /app + +# Определяем аргумент сборки +ARG APP_NAME + +# Копируем собранное приложение из предыдущего образа +COPY --from=builder /app/${APP_NAME} /app/${APP_NAME} + +# Запуск приложения +CMD ["sh", "-c", "/app/${APP_NAME}"] \ No newline at end of file diff --git a/service/system_service/Dockerfile.serv b/service/system_service/Dockerfile.serv new file mode 100644 index 0000000..9ca674f --- /dev/null +++ b/service/system_service/Dockerfile.serv @@ -0,0 +1,38 @@ +# syntax=docker/dockerfile:1.4 + +# Этап сборки +FROM golang:1.24.5 AS builder + +# Принимаем аргументы сборки +ARG GO_PAT +ARG APP_NAME + +WORKDIR /app + +# Копируем исходники core и сервиса +COPY core ./core +COPY service/system_service ./service/system_service + +# Сборка приложения +WORKDIR /app/service/system_service +RUN go mod tidy && go vet ./... && gofmt -w ./ +RUN go build -o /app/${APP_NAME} ./cmd/app.go +WORKDIR /app +RUN chmod +x /app/${APP_NAME} + +# Финальный образ +FROM kartashs/ubuntu:22.04 + +WORKDIR /app + +# Принимаем APP_NAME в финальном слое и сохраняем как переменную окружения +ARG APP_NAME +ENV APP_NAME=${APP_NAME} + +# Копируем бинарник из builder-слоя +COPY --from=builder /app/${APP_NAME} /app/${APP_NAME} + +RUN chmod +x /app/${APP_NAME} + +# Запуск приложения +CMD ["sh", "-c", "/app/${APP_NAME}"] \ No newline at end of file diff --git a/service/system_service/cmd/app.go b/service/system_service/cmd/app.go new file mode 100644 index 0000000..ed1a2bb --- /dev/null +++ b/service/system_service/cmd/app.go @@ -0,0 +1,59 @@ +package main + +import ( + configcore "bitrix_balancer_api/core/config" + clientcontrollers "bitrix_balancer_api/core/lib/internally/client-controllers" + workerjobs "bitrix_balancer_api/system_service/jobs" + "bitrix_balancer_api/system_service/types" + "errors" + "fmt" + "github.com/sirupsen/logrus" +) + +func main() { + err := initService() + if err != nil { + logrus.Error(errors.New(fmt.Sprintf("failed to init service: %v", err))) + return + } + select {} +} + +func initService() error { + clientsExternal, err := getClientsExternal() + if err != nil { + return errors.New(fmt.Sprintf("failed to load config: %v", err)) + } + + ipc, err := initInternalProvider(clientsExternal) + if err != nil { + return errors.New(fmt.Sprintf("🔴 failed to init internal provider: %v", err)) + } + if ipc == nil { + return errors.New("failed to init internal provider: nil ipc") + } + + // Запуск воркеров + err = workerjobs.WorkerJobsStart(ipc) + if err != nil { + return errors.New(fmt.Sprintf("failed to init workerjobs: %v", err)) + } + + return nil +} + +func initInternalProvider(clientsExternal clientcontrollers.ClientsExternal) (*types.InternalProviderControl, error) { + return &types.InternalProviderControl{ + Database: clientsExternal.DB, + Config: clientsExternal.Config, + RedisClient: clientsExternal.Redis, + }, nil +} + +func getClientsExternal() (clientcontrollers.ClientsExternal, error) { + options := &configcore.ConfigLoadOptions{ + Redis: true, + Database: true, + } + return clientcontrollers.ReturnClientsExternal(options) +} diff --git a/service/system_service/database_additionally/tables.go b/service/system_service/database_additionally/tables.go new file mode 100644 index 0000000..53d2e3f --- /dev/null +++ b/service/system_service/database_additionally/tables.go @@ -0,0 +1,2 @@ +package database_additionally + diff --git a/service/system_service/go.mod b/service/system_service/go.mod new file mode 100644 index 0000000..7047d1e --- /dev/null +++ b/service/system_service/go.mod @@ -0,0 +1,17 @@ +module bitrix_balancer_api/system_service + +go 1.25.6 + +replace bitrix_balancer_api/core => ../../core + +require ( + github.com/sirupsen/logrus v1.9.4 + gorm.io/gorm v1.31.1 +) + +require ( + github.com/jinzhu/inflection v1.0.0 // indirect + github.com/jinzhu/now v1.1.5 // indirect + golang.org/x/sys v0.13.0 // indirect + golang.org/x/text v0.20.0 // indirect +) diff --git a/service/system_service/go.sum b/service/system_service/go.sum new file mode 100644 index 0000000..90740e3 --- /dev/null +++ b/service/system_service/go.sum @@ -0,0 +1,20 @@ +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/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/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w= +github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g= +github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE= +golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/text v0.20.0 h1:gK/Kv2otX8gz+wn7Rmb3vT96ZwuoxnQlY+HlJVj7Qug= +golang.org/x/text v0.20.0/go.mod h1:D4IsuqiFMhST5bX19pQ9ikHC2GsaKyk/oF+pn3ducp4= +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/gorm v1.31.1 h1:7CA8FTFz/gRfgqgpeKIBcervUn3xSyPUmr6B2WXJ7kg= +gorm.io/gorm v1.31.1/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs= diff --git a/service/system_service/jobs/init.go b/service/system_service/jobs/init.go new file mode 100644 index 0000000..46b8ca4 --- /dev/null +++ b/service/system_service/jobs/init.go @@ -0,0 +1,28 @@ +package workerjobs + +import ( + "bitrix_balancer_api/system_service/types" + "github.com/sirupsen/logrus" +) + +type WorkerJobs struct { + ipc *types.InternalProviderControl +} + +func WorkerJobsStart(ipc *types.InternalProviderControl) error { + jobs := &WorkerJobs{ + ipc: ipc, + } + + if ipc.Config.Environment == "" || ipc.Config.Environment == "dev" { + err := jobs.ipc.Database.Migrate().MigrateDB() + if err != nil { + return err + } + logrus.Info("🟢🟢🟢 Database migration completed successfully") + } else { + logrus.Info("⚠️ production environment variable is set to prod mode. Skip migration") + } + + return nil +} diff --git a/service/system_service/start.sh b/service/system_service/start.sh new file mode 100755 index 0000000..d928bba --- /dev/null +++ b/service/system_service/start.sh @@ -0,0 +1,49 @@ +#!/bin/bash + +set -e +trap 'echo "🔴 Скрипт остановлен"; exit' SIGINT + +# Имя сети Docker +DOCKER_NETWORK_NAME="networklocal1" +# Наименование сервиса +SERVICE_NAME="ruspet_system_service" + +# Наименование образа +IMAGE_NAME="${SERVICE_NAME}_i" +# Наименование контейнера +CONTAINER_NAME="${SERVICE_NAME}_c" +# Имя приложения +APP_NAME="${SERVICE_NAME}_app" + + +# Останавливаем и удаляем старый контейнер, если он существует +if [ "$(docker ps -q -f name=$CONTAINER_NAME)" ]; then + docker stop $CONTAINER_NAME + docker rm $CONTAINER_NAME +fi + +# Удаляем старый образ, если он существует +if [ "$(docker images -q $IMAGE_NAME)" ]; then + docker rmi $IMAGE_NAME +fi + +# Создаем директорию vendor с зависимостями +go mod tidy +rm -rf vendor +go mod vendor + +# Проверяем существование сети и создаем, если не существует +docker network ls | grep $DOCKER_NETWORK_NAME || docker network create $DOCKER_NETWORK_NAME + +# Собираем образ +docker build --build-arg APP_NAME=$APP_NAME -t $IMAGE_NAME . + +# Запускаем контейнер с новым образом в сетевом режиме host и подключаем к сети по имени +docker run -d \ + --add-host=rmq_host:192.168.1.102 \ + --network $DOCKER_NETWORK_NAME \ + --restart always \ + --name $CONTAINER_NAME \ + -e APP_NAME=$APP_NAME \ + --add-host=database_host:192.168.0.15 \ + $IMAGE_NAME \ No newline at end of file diff --git a/service/system_service/types/types.go b/service/system_service/types/types.go new file mode 100644 index 0000000..3f60a73 --- /dev/null +++ b/service/system_service/types/types.go @@ -0,0 +1,15 @@ +package types + +import ( + configcore "bitrix_balancer_api/core/config" + database "bitrix_balancer_api/core/db" + "bitrix_balancer_api/core/lib/external/telegram" + redismodule "bitrix_balancer_api/core/lib/internally/redis" +) + +type InternalProviderControl struct { + Config *configcore.Config + RedisClient *redismodule.ModuleRedis + TGBotClient *telegram.TgBotClient + Database *database.ModuleDB +} diff --git a/service/system_service/version b/service/system_service/version new file mode 100644 index 0000000..aa6e22c --- /dev/null +++ b/service/system_service/version @@ -0,0 +1 @@ +v-0.0.2 \ No newline at end of file diff --git a/service/telegram_service/.gitignore b/service/telegram_service/.gitignore new file mode 100644 index 0000000..159c516 --- /dev/null +++ b/service/telegram_service/.gitignore @@ -0,0 +1,6 @@ +.env +telegram-service_app +config.yml +vendor +app +.DS_STORE \ No newline at end of file diff --git a/service/telegram_service/.golangci.yml b/service/telegram_service/.golangci.yml new file mode 100644 index 0000000..ea1405d --- /dev/null +++ b/service/telegram_service/.golangci.yml @@ -0,0 +1,52 @@ +linters-settings: + errcheck: # Настройки для линтера errcheck, который проверяет, что ошибки не игнорируются + check-type-assertions: true # Не проверять утверждения типов на ошибки + check-blank: true # Проверять игнорирование ошибок через присваивание в _ + prealloc: # Настройки для линтера prealloc, который предлагает предварительное выделение памяти для срезов + simple: true # Простой режим, предлагает предварительное выделение для простых циклов + range-loops: true # Предлагает предварительное выделение для циклов range + for-loops: false # Не предлагает предварительное выделение для обычных for-циклов + gocyclo: # Настройки для линтера gocyclo, который проверяет сложность функций + min-complexity: 15 # Установите порог сложности, который считаете приемлемым + +linters: + enable: # Список линтеров, которые будут включены + - noctx # Находит отправку HTTP-запроса без контекста.Контекст. + - protogetter # Сообщает о прямом чтении из полей прото-сообщения, когда следует использовать геттеры. + - reassign # Проверяет, что переменные пакета не переназначаются. + - rowserrcheck # Проверяет, успешно ли проверен Rows.Err строк. + - sqlclosecheck # Проверяет, что sql.Rows, sql.Stmt, sqlx.NamedStmt, pgx.Query закрыты. + - ineffassign # Обнаруживает, когда назначения существующим переменным не используются. + - nilerr # Находит код, который возвращает ноль, даже если он проверяет, что ошибка не равна нулю. + - makezero # Проверяет, что нулевые значения создаются правильно + - gochecksumtype # Проверяет, что тип контрольной суммы в go.sum соответствует содержимому + - copyloopvar # Проверяет, что циклические зависимости пакетов не имеют экспортируемых идентификаторов + - exhaustive # Проверьте полноту операторов перечисления. + - errchkjson # Проверяет типы, передаваемые функциям кодирования JSON. Сообщает о неподдерживаемых типах и событиях, при которых проверку возвращаемой ошибки можно опустить. + - durationcheck # Проверяет, что длительность таймаута не равна 0 + - contextcheck # Проверяет, что контекст не игнорируется + - bodyclose # Проверяет, что тело запроса закрывается + - bidichk # Проверяет, что строки в исходном коде не содержат символов из разных языков + - govet # Проверяет код на наличие конструкций, которые могут быть ошибочными + - errcheck # Проверяет, что ошибки не игнорируются + - staticcheck # Статический анализ кода, находит ошибки, неэффективные конструкции и т.д. + - unused # Проверяет на неиспользуемые переменные, функции, константы + - gocritic # Линтер, основанный на проверке кода на соответствие определенным критериям качества и стиля + - stylecheck # Проверяет стиль кодирования + - whitespace # Проверяет проблемы с пробелами в коде + - gosec # Линтер gosec, который проверяет код на наличие потенциальных уязвимостей + - prealloc # Предлагает предварительное выделение памяти для срезов + + - dupl # Находит дублирующийся код + - gocyclo # Проверяет сложность функций + - ineffassign # Обнаруживает неэффективные присваивания + - unparam # Находит неиспользуемые параметры функций + + - gosimple # Предлагает упрощения кода + + disable: # Список линтеров, которые будут отключены + - gofumpt # Более строгая версия gofmt, применяет дополнительные правила форматирования + # - golint # Отключает golint, который проверяет стиль написания кода на Go + +run: + timeout: 15m # Устанавливает тайм-аут для выполнения всех линтеров \ No newline at end of file diff --git a/service/telegram_service/Dockerfile b/service/telegram_service/Dockerfile new file mode 100644 index 0000000..ef05f7e --- /dev/null +++ b/service/telegram_service/Dockerfile @@ -0,0 +1,29 @@ +# Используем официальный образ Go для сборки приложения +FROM golang:1.24.2 AS builder + +# Рабочая директория +WORKDIR /app + +# Определяем аргумент сборки +ARG APP_NAME +RUN echo "APP_NAME=${APP_NAME}" + +# Копируем код внутрь контейнера +COPY . . + +# Сборка приложения +RUN go build -o ${APP_NAME} ./cmd/app.go + +# Создаём конечный образ на основе Ubuntu +FROM kartashs/ubuntu:22.04 + +WORKDIR /app + +# Определяем аргумент сборки +ARG APP_NAME + +# Копируем собранное приложение из предыдущего образа +COPY --from=builder /app/${APP_NAME} /app/${APP_NAME} + +# Запуск приложения +CMD ["sh", "-c", "/app/${APP_NAME}"] \ No newline at end of file diff --git a/service/telegram_service/Dockerfile.serv b/service/telegram_service/Dockerfile.serv new file mode 100644 index 0000000..ef32672 --- /dev/null +++ b/service/telegram_service/Dockerfile.serv @@ -0,0 +1,38 @@ +# syntax=docker/dockerfile:1.4 + +# Этап сборки +FROM golang:1.24.5 AS builder + +# Принимаем аргументы сборки +ARG GO_PAT +ARG APP_NAME + +WORKDIR /app + +# Копируем исходники core и сервиса +COPY core ./core +COPY service/telegram_service ./service/telegram_service + +# Сборка приложения +WORKDIR /app/service/telegram_service +RUN go mod tidy && go vet ./... && gofmt -w ./ +RUN go build -o /app/${APP_NAME} ./cmd/app.go +WORKDIR /app +RUN chmod +x /app/${APP_NAME} + +# Финальный образ +FROM kartashs/ubuntu:22.04 + +WORKDIR /app + +# Принимаем APP_NAME в финальном слое и сохраняем как переменную окружения +ARG APP_NAME +ENV APP_NAME=${APP_NAME} + +# Копируем бинарник из builder-слоя +COPY --from=builder /app/${APP_NAME} /app/${APP_NAME} + +RUN chmod +x /app/${APP_NAME} + +# Запуск приложения +CMD ["sh", "-c", "/app/${APP_NAME}"] \ No newline at end of file diff --git a/service/telegram_service/approvalflow/flow.go b/service/telegram_service/approvalflow/flow.go new file mode 100644 index 0000000..68b0d43 --- /dev/null +++ b/service/telegram_service/approvalflow/flow.go @@ -0,0 +1,40 @@ +package approvalflow + +// FlowNode — узел дерева навигации. +type FlowNode struct { + Key string + Label string + DataKey string + DataValue string + IsInput bool + InputKey string + InputHint string + + // Мультиселект — для выбора нескольких значений на одном уровне + IsMultiSelect bool + MultiSelectKey string // ключ в Collected где хранится результат, например "systems" + MultiSelectValue string // значение этого узла при выборе, например "okb" + + // Код темы в БД — для проверки прав доступа + // Если задан — кнопка показывается только при наличии права "create" на эту тему + TopicCode string + + Children []*FlowNode +} + +// FindNode ищет узел по ключу (BFS). +func FindNode(root *FlowNode, key string) *FlowNode { + if root == nil { + return nil + } + queue := []*FlowNode{root} + for len(queue) > 0 { + node := queue[0] + queue = queue[1:] + if node.Key == key { + return node + } + queue = append(queue, node.Children...) + } + return nil +} diff --git a/service/telegram_service/approvalflow/topic.go b/service/telegram_service/approvalflow/topic.go new file mode 100644 index 0000000..7048bb8 --- /dev/null +++ b/service/telegram_service/approvalflow/topic.go @@ -0,0 +1,14 @@ +package approvalflow + +import "bitrix_balancer_api/core/typescore" + +// Topic — интерфейс каждой темы согласования. +// Чтобы добавить новую тему: реализовать этот интерфейс и добавить +// одну строку в handlers/approval/registry.go → registerAll(). +type Topic interface { + Code() string + Name() string + BuildTree() *FlowNode + FormatApproverMessage(initiator *typescore.User, collected map[string]string) string + TopicCodeFromCollected(collected map[string]string) (string, error) +} diff --git a/service/telegram_service/cmd/app.go b/service/telegram_service/cmd/app.go new file mode 100644 index 0000000..e79e65b --- /dev/null +++ b/service/telegram_service/cmd/app.go @@ -0,0 +1,94 @@ +package main + +import ( + configcore "bitrix_balancer_api/core/config" + "bitrix_balancer_api/core/lib/external/tgkit" + clientcontrollers "bitrix_balancer_api/core/lib/internally/client-controllers" + tgupdatehandler "bitrix_balancer_api/telegram_service/common/update" + "bitrix_balancer_api/telegram_service/scheduler" + "bitrix_balancer_api/telegram_service/types" + "github.com/sirupsen/logrus" + "log" + "net/url" + "runtime/debug" +) + +func main() { + err := initService() + if err != nil { + log.Println("🔴 failed to init service: ", err) + } + select {} +} + +func initService() error { + // Получение конфигурации приложения + clientsExternal, err := getClientsExternal() + if err != nil { + return err + } + + ipc, err := initInternalProvider(clientsExternal.Config, clientsExternal) + if err != nil { + return err + } + + delegationChecker := scheduler.NewDelegationChecker(ipc) + delegationChecker.Start() + + update := tgupdatehandler.NewUpdateHandler(ipc) + go func() { + defer handlePanic("update.GetUpdateTelegram goroutine") // Обработка паник в горутине + update.GetUpdateTelegram() + }() + + return nil +} + +func getClientsExternal() (clientcontrollers.ClientsExternal, error) { + options := &configcore.ConfigLoadOptions{ + Redis: true, + Database: true, + Telegram: true, + Server: configcore.ExposedServiceOptions{ + TelegramService: true, + }, + } + + return clientcontrollers.ReturnClientsExternal(options) +} + +func initInternalProvider(cfg *configcore.Config, clientsExternal clientcontrollers.ClientsExternal) (*types.InternalProviderControl, error) { + if cfg.Telegram.ProxyURL != "" { + parsed, err := url.Parse(cfg.Telegram.ProxyURL) + if err != nil { + logrus.Fatalf("Invalid proxy URL '%s': %v", cfg.Telegram.ProxyURL, err) + } + cfg.Telegram.ParsedProxy = parsed + logrus.Infof("Proxy configured: %s", cfg.Telegram.ProxyURL) + } + tgKitClient, err := tgkit.GetClient(tgkit.ClientConfig{ + Token: cfg.Telegram.BotToken, + Proxy: &tgkit.ProxyConfig{ + URL: cfg.Telegram.ProxyURL, + }, + }) + if err != nil { + return nil, err + } + + return &types.InternalProviderControl{ + Config: cfg, + Database: clientsExternal.DB, + RedisClient: clientsExternal.Redis, + TGBotClient: tgKitClient, + }, nil +} + +// handlePanic перехватывает паники и логирует их +func handlePanic(context string) { + if r := recover(); r != nil { + log.Printf("🚨 Panic recovered in %s: %v", context, r) + log.Printf("🚨 Stack trace:\n%s", debug.Stack()) + } +} diff --git a/service/telegram_service/common/update/0_init.go b/service/telegram_service/common/update/0_init.go new file mode 100644 index 0000000..7b80554 --- /dev/null +++ b/service/telegram_service/common/update/0_init.go @@ -0,0 +1,80 @@ +package tgupdatehandler + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/telegram_service/handlers/approval" + "bitrix_balancer_api/telegram_service/handlers/faq" + "bitrix_balancer_api/telegram_service/handlers/start" + "bitrix_balancer_api/telegram_service/handlers/suggestion" + "bitrix_balancer_api/telegram_service/types" + "context" + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" + "github.com/sirupsen/logrus" + "log" + "time" +) + +type UpdateHandler struct { + ipc *types.InternalProviderControl + approvalHandler *approval.Handler + startHandler *start.Handler + suggestionHandler *suggestion.Handler + faqHandler *faq.HandlerFAQ +} + +func NewUpdateHandler(ipc *types.InternalProviderControl) *UpdateHandler { + if ipc == nil { + log.Println("🔴 error: ipc is nil") + return nil + } + + approvalHandler := approval.NewHandler(ipc) + + handler := &UpdateHandler{ + ipc: ipc, + approvalHandler: approvalHandler, + suggestionHandler: suggestion.NewHandler(ipc), + startHandler: start.NewHandler(ipc, approvalHandler), + faqHandler: faq.NewHandler(ipc), + } + + // TODO: вызывается только после обновлений + //go handler.broadcastBotUpdated() + + return handler +} + +func (s *UpdateHandler) broadcastBotUpdated() { + ctx := context.Background() + bot := s.ipc.TGBotClient.Bot() + + users, _, err := s.ipc.Database.User.GetUsersListDB(ctx, typescore.ListDbOptions{}) + if err != nil { + logrus.Errorf("broadcastBotUpdated: GetUsersListDB err=%v", err) + return + } + + text := "🔄 Бот был обновлён!\n\n" + + "Нажмите кнопку ниже чтобы перезапустить бота:" + + keyboard := tgbotapi.NewInlineKeyboardMarkup( + tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData("🚀 Перезапустить бота", "restart_bot"), + ), + ) + + for _, user := range users { + if user.TelegramID == nil { + continue + } + msg := tgbotapi.NewMessage(*user.TelegramID, text) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard + if _, err := bot.Send(msg); err != nil { + logrus.Warnf("broadcastBotUpdated: Send to telegramID=%d err=%v", *user.TelegramID, err) + } + time.Sleep(50 * time.Millisecond) + } + + logrus.Infof("broadcastBotUpdated: отправлено %d пользователям", len(users)) +} diff --git a/service/telegram_service/common/update/callback.go b/service/telegram_service/common/update/callback.go new file mode 100644 index 0000000..d637a2c --- /dev/null +++ b/service/telegram_service/common/update/callback.go @@ -0,0 +1,585 @@ +package tgupdatehandler + +import ( + "bitrix_balancer_api/telegram_service/keyboard" + "context" + "fmt" + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" + "github.com/sirupsen/logrus" + "strconv" + "strings" + "time" +) + +func (s *UpdateHandler) handleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery) { + data := cq.Data + + switch { + case strings.HasPrefix(data, "appr:"): + parts := strings.SplitN(data, ":", 3) + if len(parts) != 3 { + return + } + s.approvalHandler.HandleCallback(bot, cq, parts[1], parts[2]) + + case strings.HasPrefix(data, "task_complete:"): + 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) + s.approvalHandler.HandleDecision(bot, cq, approvalID, true, "") + + case strings.HasPrefix(data, "appr_stage:"): + approvalID := parseID(data, "appr_stage:") + logrus.Infof("handleCallback: appr_stage approvalID=%d", approvalID) + s.approvalHandler.HandleApprovalStages(bot, cq, approvalID) + + // Мультиселект кнопок + case strings.HasPrefix(data, "appr_ms_toggle:"): + parts := strings.SplitN(strings.TrimPrefix(data, "appr_ms_toggle:"), ":", 3) + if len(parts) == 3 { + s.approvalHandler.HandleMultiSelectToggle(bot, cq, parts[0], parts[1], parts[2]) + } + + case strings.HasPrefix(data, "appr_ms_confirm:"): + topicCode := strings.TrimPrefix(data, "appr_ms_confirm:") + s.approvalHandler.HandleMultiSelectConfirm(bot, cq, topicCode) + + // НА ДОРАБОТКУ + case strings.HasPrefix(data, "revision_attach_cancel:"): + approvalID := parseID(data, "revision_attach_cancel:") + ctx := context.Background() + key := fmt.Sprintf("appr_revision_attach_file:%d", cq.From.ID) + s.ipc.RedisClient.Del(ctx, key) //nolint:errcheck + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck + // Возвращаем меню доработки + optMsg := tgbotapi.NewMessage(cq.Message.Chat.ID, fmt.Sprintf("📋 Заявка #%d на доработке:", approvalID)) + optMsg.ParseMode = "HTML" + optMsg.ReplyMarkup = keyboard.BuildRevisionOptions(approvalID) + bot.Send(optMsg) //nolint:errcheck + + case strings.HasPrefix(data, "appr_revision:"): + approvalID := parseID(data, "appr_revision:") + s.approvalHandler.HandleRevisionCallback(bot, cq, approvalID) + + case strings.HasPrefix(data, "appr_revision_comment:"): + approvalID := parseID(data, "appr_revision_comment:") + s.approvalHandler.HandleRevisionCommentStart(bot, cq, approvalID) + + case strings.HasPrefix(data, "appr_revision_skip:"): + approvalID := parseID(data, "appr_revision_skip:") + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck + s.approvalHandler.HandleRevisionWithComment(bot, cq.Message.Chat.ID, cq.From.ID, approvalID, "") + + case strings.HasPrefix(data, "revision_edit_text:"): + approvalID := parseID(data, "revision_edit_text:") + s.approvalHandler.HandleRevisionEditText(bot, cq, approvalID) + + case strings.HasPrefix(data, "revision_add_files:"): + approvalID := parseID(data, "revision_add_files:") + s.approvalHandler.HandleRevisionAddFiles(bot, cq, approvalID) + + case strings.HasPrefix(data, "revision_resubmit:"): + approvalID := parseID(data, "revision_resubmit:") + s.approvalHandler.HandleRevisionResubmit(bot, cq, approvalID) + + // ── ОТКАЗ — + case strings.HasPrefix(data, "appr_no_comment:"): + approvalID := parseID(data, "appr_no_comment:") + s.handleApprovalRejectStart(bot, cq, approvalID) + + case strings.HasPrefix(data, "appr_no_defer:"): + approvalID := parseID(data, "appr_no_defer:") + s.approvalHandler.HandlePendingDeferCallback(bot, cq, approvalID, "reject") + + case strings.HasPrefix(data, "appr_no_skip:"): + approvalID := parseID(data, "appr_no_skip:") + ctx := context.Background() + rejectKey := fmt.Sprintf("appr_reject_pending:%d", cq.From.ID) + s.ipc.RedisClient.Del(ctx, rejectKey) //nolint:errcheck + s.approvalHandler.HandleDecision(bot, cq, approvalID, false, "") + s.approvalHandler.States.RemovePendingComment(ctx, cq.From.ID, approvalID) //nolint:errcheck + + case strings.HasPrefix(data, "appr_no:"): + approvalID := parseID(data, "appr_no:") + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck + msg := tgbotapi.NewMessage(cq.Message.Chat.ID, fmt.Sprintf("❌ Заявка #%d — выберите действие:", approvalID)) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildRejectOptions(approvalID) + bot.Send(msg) //nolint:errcheck + + // ── ОТЗЫВ — + case strings.HasPrefix(data, "appr_revoke_comment:"): + approvalID := parseID(data, "appr_revoke_comment:") + s.handleRevokeStart(bot, cq, approvalID) + + case strings.HasPrefix(data, "appr_revoke_defer:"): + approvalID := parseID(data, "appr_revoke_defer:") + s.approvalHandler.HandlePendingDeferCallback(bot, cq, approvalID, "revoke") + + case strings.HasPrefix(data, "appr_revoke_skip:"): + approvalID := parseID(data, "appr_revoke_skip:") + ctx := context.Background() + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + s.approvalHandler.HandleRevokeWithComment(bot, cq.Message.Chat.ID, cq.From.ID, approvalID, "") + s.approvalHandler.States.RemovePendingComment(ctx, cq.From.ID, approvalID) //nolint:errcheck + + case strings.HasPrefix(data, "appr_revoke:"): + approvalID := parseID(data, "appr_revoke:") + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck + msg := tgbotapi.NewMessage(cq.Message.Chat.ID, fmt.Sprintf("↩️ Заявка #%d — выберите действие:", approvalID)) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildRevokeOptions(approvalID) + bot.Send(msg) //nolint:errcheck + + // ── ОТЛОЖЕННЫЕ ────────────────────────────────────────────── + case strings.HasPrefix(data, "pending_item:"): + approvalID := parseID(data, "pending_item:") + s.approvalHandler.HandlePendingItemCallback(bot, cq, approvalID) + + case data == "pending_back": + s.approvalHandler.HandlePendingBackCallback(bot, cq) + + // ── НАБЛЮДАТЕЛЬ ───────────────────────────────────────────── + case strings.HasPrefix(data, "obs_topic:"): + topicCode := strings.TrimPrefix(data, "obs_topic:") + s.approvalHandler.HandleObserverTopicCallback(bot, cq, topicCode) + + case strings.HasPrefix(data, "obs_approval:"): + approvalID := parseID(data, "obs_approval:") + s.approvalHandler.HandleObserverApprovalCallback(bot, cq, approvalID) + + case strings.HasPrefix(data, "obs_remind:"): + approvalID := parseID(data, "obs_remind:") + s.approvalHandler.HandleObserverReminderCallback(bot, cq, approvalID) + + case strings.HasPrefix(data, "obs_back:"): + topicCode := strings.TrimPrefix(data, "obs_back:") + s.approvalHandler.HandleObserverBackToTopic(bot, cq, topicCode) + + case data == "obs_back_topics": + s.approvalHandler.HandleObserverBackToTopics(bot, cq) + + // ── УПРАВЛЕНИЕ ФАЙЛАМИ ────────────────────────────────────── + case strings.HasPrefix(data, "appr_file_detach:"): + indexStr := strings.TrimPrefix(data, "appr_file_detach:") + index, err := strconv.Atoi(indexStr) + if err != nil { + logrus.Warnf("handleCallback: bad detach index %q", indexStr) + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + return + } + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + // НЕ удаляем сообщение — это делает showFileStatus + s.approvalHandler.HandleDetachFile(bot, cq.Message.Chat.ID, int64(cq.From.ID), index) + + case strings.HasPrefix(data, "appr_file_submit:"): + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + s.approvalHandler.HandleSubmitFiles(bot, cq.Message.Chat.ID, int64(cq.From.ID), true) + + case strings.HasPrefix(data, "appr_file_skip:"): + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + s.approvalHandler.HandleSubmitFiles(bot, cq.Message.Chat.ID, int64(cq.From.ID), false) + + case strings.HasPrefix(data, "appr_attach:"): + approvalID := parseID(data, "appr_attach:") + s.approvalHandler.HandleAttachFileStart(bot, cq, approvalID) + + case strings.HasPrefix(data, "appr_attach_cancel:"): + s.approvalHandler.HandleAttachCancel(bot, cq) + + // ── НАВИГАЦИЯ ФЛОУ ────────────────────────────────────────── + case strings.HasPrefix(data, "appr_back:"): + topicCode := strings.TrimPrefix(data, "appr_back:") + s.approvalHandler.HandleBackCallback(bot, cq, topicCode) + + case strings.HasPrefix(data, "appr_page:"): + page := 0 + fmt.Sscanf(strings.TrimPrefix(data, "appr_page:"), "%d", &page) + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + s.approvalHandler.HandleMenuPage(bot, cq.Message.Chat.ID, cq.From.ID, page, cq.Message.MessageID) + + case data == "appr_page_noop": + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + + // ── ФЛОУ ДЕЛЕГИРОВАНИЯ ПРАВ ────────────────────────────────────────── + case strings.HasPrefix(data, "deleg_category_page:"): + page := 0 + fmt.Sscanf(strings.TrimPrefix(data, "deleg_category_page:"), "%d", &page) + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + s.approvalHandler.HandleDelegationMenuPage(bot, cq.Message.Chat.ID, cq.From.ID, page, cq.Message.MessageID) + + case strings.HasPrefix(data, "deleg_category:"): + categoryID := parseID(data, "deleg_category:") + s.approvalHandler.HandleDelegationCategoryCallback(bot, cq, categoryID) + + case strings.HasPrefix(data, "deleg_topic_page:"): + parts := strings.Split(strings.TrimPrefix(data, "deleg_topic_page:"), ":") + if len(parts) == 2 { + var categoryID, page uint64 + fmt.Sscanf(parts[0], "%d", &categoryID) + fmt.Sscanf(parts[1], "%d", &page) + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck + s.approvalHandler.HandleDelegationCategoryCallbackPage(bot, cq, categoryID, int(page)) + } + + case strings.HasPrefix(data, "deleg_all_category:"): + categoryID := parseID(data, "deleg_all_category:") + s.approvalHandler.HandleDelegationAllCategoryCallback(bot, cq, categoryID) + + case strings.HasPrefix(data, "deleg_topic:"): + topicID := parseID(data, "deleg_topic:") + s.approvalHandler.HandleDelegationTopicCallback(bot, cq, topicID) + + case strings.HasPrefix(data, "deleg_user_page:"): + parts := strings.Split(strings.TrimPrefix(data, "deleg_user_page:"), ":") + if len(parts) == 3 { + var categoryID, topicID, page uint64 + fmt.Sscanf(parts[0], "%d", &categoryID) + fmt.Sscanf(parts[1], "%d", &topicID) + fmt.Sscanf(parts[2], "%d", &page) + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck + s.approvalHandler.HandleDelegationSelectUserPage(bot, cq, categoryID, topicID, int(page)) + } + + case strings.HasPrefix(data, "deleg_user:"): + delegateID := parseID(data, "deleg_user:") + s.approvalHandler.HandleDelegationUserCallback(bot, cq, delegateID) + + case data == "deleg_back_categories": + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck + s.approvalHandler.HandleDelegationMenu(bot, cq.Message.Chat.ID, cq.From.ID) + + case data == "deleg_create": + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck + s.approvalHandler.HandleDelegationMenu(bot, cq.Message.Chat.ID, cq.From.ID) + + case data == "deleg_list": + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck + s.approvalHandler.HandleDelegatedRightsList(bot, cq.Message.Chat.ID, cq.From.ID) + + case strings.HasPrefix(data, "deleg_list_page:"): + page := 0 + fmt.Sscanf(strings.TrimPrefix(data, "deleg_list_page:"), "%d", &page) + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + s.approvalHandler.HandleDelegatedRightsListPage(bot, cq.Message.Chat.ID, cq.From.ID, page, cq.Message.MessageID) + + case strings.HasPrefix(data, "deleg_detail:"): + delegationID := parseID(data, "deleg_detail:") + s.approvalHandler.HandleDelegatedRightDetail(bot, cq, delegationID) + + case strings.HasPrefix(data, "deleg_revoke:"): + delegationID := parseID(data, "deleg_revoke:") + s.approvalHandler.HandleDelegationRevoke(bot, cq, delegationID) + + case strings.HasPrefix(data, "deleg_extend:"): + delegationID := parseID(data, "deleg_extend:") + s.approvalHandler.HandleDelegationExtendPrompt(bot, cq, delegationID) + + case data == "deleg_page_noop": + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + + // ── ДОБАВЛЕНИЕ СОГЛАСУЮЩЕГО ─────────────────────────────────────────────────── + case strings.HasPrefix(data, "add_appr_category_page:"): + page := 0 + fmt.Sscanf(strings.TrimPrefix(data, "add_appr_category_page:"), "%d", &page) + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + s.approvalHandler.HandleAddApproverCategoryMenuPage(bot, cq.Message.Chat.ID, cq.From.ID, page, cq.Message.MessageID) + + case strings.HasPrefix(data, "add_appr_category:"): + categoryID := parseID(data, "add_appr_category:") + s.approvalHandler.HandleAddApproverCategoryCallback(bot, cq, categoryID) + + case strings.HasPrefix(data, "add_appr_to_approval:"): + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + + approvalIDStr := strings.TrimPrefix(data, "add_appr_to_approval:") + approvalID, err := strconv.ParseUint(approvalIDStr, 10, 64) + if err != nil { + logrus.Errorf("handleCallback: invalid approvalID=%s err=%v", approvalIDStr, err) + return + } + + s.approvalHandler.HandleAddApproverFromApproval(bot, cq.Message.Chat.ID, cq.From.ID, approvalID) + return + + case strings.HasPrefix(data, "add_appr_approval_page:"): + parts := strings.Split(strings.TrimPrefix(data, "add_appr_approval_page:"), ":") + if len(parts) == 2 { + var categoryID, page uint64 + fmt.Sscanf(parts[0], "%d", &categoryID) + fmt.Sscanf(parts[1], "%d", &page) + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck + s.approvalHandler.HandleAddApproverCategoryCallbackPage(bot, cq, categoryID, int(page)) + } + + case strings.HasPrefix(data, "add_appr_approval:"): + approvalID := parseID(data, "add_appr_approval:") + s.approvalHandler.HandleAddApproverApprovalCallback(bot, cq, approvalID) + + case strings.HasPrefix(data, "add_appr_user_page:"): + parts := strings.Split(strings.TrimPrefix(data, "add_appr_user_page:"), ":") + if len(parts) == 3 { + var approvalID, categoryID, page uint64 + fmt.Sscanf(parts[0], "%d", &approvalID) + fmt.Sscanf(parts[1], "%d", &categoryID) + fmt.Sscanf(parts[2], "%d", &page) + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck + s.approvalHandler.HandleAddApproverApprovalCallbackPage(bot, cq, approvalID, int(page)) + } + + case strings.HasPrefix(data, "add_appr_user:"): + approverID := parseID(data, "add_appr_user:") + s.approvalHandler.HandleAddApproverUserCallback(bot, cq, approverID) + + case data == "add_appr_create": + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck + s.approvalHandler.HandleAddApproverCategoryMenu(bot, cq.Message.Chat.ID, cq.From.ID) + + case data == "add_appr_list": + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck + s.approvalHandler.HandleAddedApproversList(bot, cq.Message.Chat.ID, cq.From.ID) + + case strings.HasPrefix(data, "add_appr_list_page:"): + page := 0 + fmt.Sscanf(strings.TrimPrefix(data, "add_appr_list_page:"), "%d", &page) + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + s.approvalHandler.HandleAddedApproversListPage(bot, cq.Message.Chat.ID, cq.From.ID, page, cq.Message.MessageID) + + case strings.HasPrefix(data, "add_appr_detail:"): + additionalApproverID := parseID(data, "add_appr_detail:") + s.approvalHandler.HandleAddedApproverDetail(bot, cq, additionalApproverID) + + case data == "add_appr_page_noop": + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + + // ── ОТЧЁТ ─────────────────────────────────────────────────── + case data == "report_set_dates": + s.approvalHandler.HandleReportSetDates(bot, cq) + + case data == "report_all_time": + s.approvalHandler.HandleReportAllTime(bot, cq) + + case data == "report_generate": + s.approvalHandler.HandleReportGenerate(bot, cq) + + // ПРЕДЛОЖЕНИЯ И ПОЖЕЛАНИЯ + case strings.HasPrefix(data, "sugg_reply:"): + suggestionID := parseID(data, "sugg_reply:") + s.suggestionHandler.HandleReplyToSuggestion(bot, cq, suggestionID) + + case strings.HasPrefix(data, "sugg_view:"): + suggestionID := parseID(data, "sugg_view:") + s.suggestionHandler.HandleViewSuggestion(bot, cq, suggestionID) + + // КОММЕНТАРИИ К СОГЛАСОВАНИЯМ + case strings.HasPrefix(data, "appr_comment:"): + approvalID := parseID(data, "appr_comment:") + s.approvalHandler.HandleAddCommentCallback(bot, cq, approvalID) + + case strings.HasPrefix(data, "comment_reply:"): + approvalID := parseID(data, "comment_reply:") + s.approvalHandler.HandleCommentReplyCallback(bot, cq, approvalID) + + // ВЫБОР СОГЛАСУЮЩЕГО + case strings.HasPrefix(data, "select_approver:"): + approverID := parseID(data, "select_approver:") + s.approvalHandler.HandleApproverSelectionCallback(bot, cq, approverID) + + case strings.HasPrefix(data, "select_approver_page:"): + page := 0 + fmt.Sscanf(strings.TrimPrefix(data, "select_approver_page:"), "%d", &page) + s.approvalHandler.HandleApproverSelectionPageCallback(bot, cq, page) + + case data == "select_approver_noop": + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + + // ПРОСМОТР ФАЙЛОВ В ЗАЯВКЕ + case strings.HasPrefix(data, "appr_view_files:"): + approvalID := parseID(data, "appr_view_files:") + s.approvalHandler.HandleViewFilesCallback(bot, cq, approvalID) + + // Мои заявки + case strings.HasPrefix(data, "my_appr_topic:"): + topicFilter := strings.TrimPrefix(data, "my_appr_topic:") + s.approvalHandler.HandleMyApprovalsTopicCallback(bot, cq, topicFilter) + + case strings.HasPrefix(data, "my_appr_status:"): + // формат: my_appr_status:{status}:{topicFilter} + parts := strings.SplitN(strings.TrimPrefix(data, "my_appr_status:"), ":", 2) + status := parts[0] + topicFilter := "all" + if len(parts) > 1 { + topicFilter = parts[1] + } + s.approvalHandler.HandleMyApprovalsStatusCallback(bot, cq, status, topicFilter) + + case data == "my_appr_back": + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck + s.approvalHandler.HandleMyApprovals(bot, cq.Message.Chat.ID, cq.From.ID) + + case strings.HasPrefix(data, "appr_appr_topic:"): + topicFilter := strings.TrimPrefix(data, "appr_appr_topic:") + s.approvalHandler.HandleApproverApprovalsTopicCallback(bot, cq, topicFilter) + + case strings.HasPrefix(data, "appr_appr_status:"): + // формат: appr_appr_status:{status}:{topicFilter} + parts := strings.SplitN(strings.TrimPrefix(data, "appr_appr_status:"), ":", 2) + status, topicFilter := parts[0], "all" + if len(parts) == 2 { + topicFilter = parts[1] + } + s.approvalHandler.HandleApproverApprovalsStatusCallback(bot, cq, status, topicFilter) + + case data == "appr_appr_back": + s.approvalHandler.HandleApproverApprovals(bot, cq.Message.Chat.ID, cq.From.ID) + + case strings.HasPrefix(data, "obs_topic_page:"): + page := 0 + fmt.Sscanf(strings.TrimPrefix(data, "obs_topic_page:"), "%d", &page) + bot.Request(tgbotapi.NewCallback(cq.ID, "")) + bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) + s.approvalHandler.HandleObservedApprovalsPage(bot, cq.Message.Chat.ID, cq.From.ID, page) + + case data == "obs_topic_noop": + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + + // ВЫБОР ПЕРВОГО НАБЛДАТЕЛЯ + case strings.HasPrefix(data, "obs_select_toggle:"): + observerID := parseID(data, "obs_select_toggle:") + s.approvalHandler.HandleObserverToggleCallback(bot, cq, observerID) + + case strings.HasPrefix(data, "obs_select_page:"): + page := 0 + fmt.Sscanf(strings.TrimPrefix(data, "obs_select_page:"), "%d", &page) + s.approvalHandler.HandleObserverPageCallback(bot, cq, page) + + case strings.HasPrefix(data, "obs_confirm"): + s.approvalHandler.HandleObserverConfirmCallback(bot, cq) + + case data == "obs_select_noop": + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + + // ВЫБОР ПЕРВОГО СОГЛАСУЮЩеГО + case strings.HasPrefix(data, "first_approver_select:"): + userID := parseID(data, "first_approver_select:") + s.approvalHandler.HandleFirstApproverSelectCallback(bot, cq, userID) + + case strings.HasPrefix(data, "first_approver_page:"): + page := 0 + fmt.Sscanf(strings.TrimPrefix(data, "first_approver_page:"), "%d", &page) + s.approvalHandler.HandleFirstApproverPageCallback(bot, cq, page) + + case data == "first_approver_noop": + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + + case strings.HasPrefix(data, "revoke_task_no_changes:"): + var taskID, approvalID uint64 + fmt.Sscanf(strings.TrimPrefix(data, "revoke_task_no_changes:"), "%d:%d", &taskID, &approvalID) + s.approvalHandler.HandleRevokeTaskNoChanges(bot, cq, taskID, approvalID) + + case strings.HasPrefix(data, "revoke_task_has_changes:"): + var taskID, approvalID uint64 + fmt.Sscanf(strings.TrimPrefix(data, "revoke_task_has_changes:"), "%d:%d", &taskID, &approvalID) + s.approvalHandler.HandleRevokeTaskHasChanges(bot, cq, taskID, approvalID) + + case strings.HasPrefix(data, "executor_attach:"): + parts := strings.Split(data, ":") + if len(parts) >= 3 { + taskID, _ := strconv.ParseUint(parts[1], 10, 64) + approvalID, _ := strconv.ParseUint(parts[2], 10, 64) + s.approvalHandler.HandleExecutorAttachStart(bot, cq, approvalID, taskID) + } + + case strings.HasPrefix(data, "attach_submit:"): + approvalID := parseID(data, "attach_submit:") + s.approvalHandler.HandleAttachSubmit(bot, cq, approvalID) + + case strings.HasPrefix(data, "attach_clear:"): + approvalID := parseID(data, "attach_clear:") + s.approvalHandler.HandleAttachClear(bot, cq, approvalID) + + case strings.HasPrefix(data, "attach_cancel:"): + s.approvalHandler.HandleAttachCancel(bot, cq) + + // ── ПРОЧЕЕ ────────────────────────────────────────────────── + case data == "restart_bot": + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck + s.startHandler.Handle(bot, &tgbotapi.Message{ + Chat: &tgbotapi.Chat{ID: cq.Message.Chat.ID}, + From: cq.From, + }) + + default: + logrus.Warnf("handleCallback: unknown callback: %s (from user=%d, chat=%d, msgID=%d)", + data, cq.From.ID, cq.Message.Chat.ID, cq.Message.MessageID) + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + } +} + +// handleApprovalRejectStart сохраняет состояние "ожидаем комментарий к отказу" +// и просит согласующего ввести причину (или оставить пустой). +func (s *UpdateHandler) handleApprovalRejectStart(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64) { + ctx := context.Background() + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck + + rejectKey := fmt.Sprintf("appr_reject_pending:%d", cq.From.ID) + if err := s.ipc.RedisClient.Set(ctx, rejectKey, fmt.Sprintf("%d", approvalID), 10*time.Minute); err != nil { + logrus.Errorf("handleApprovalRejectStart: Set err=%v", err) + return + } + + msg := tgbotapi.NewMessage(cq.Message.Chat.ID, + "Укажите причину отказа или нажмите кнопку ниже:") + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildApprovalRejectComment(approvalID) + bot.Send(msg) //nolint:errcheck +} + +func (s *UpdateHandler) handleApprovalDecision(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64, approved bool, comment string) { + // Логика финализации шага — делегируем в approvalHandler + s.approvalHandler.HandleDecision(bot, cq, approvalID, approved, comment) +} + +func parseID(data, prefix string) uint64 { + var id uint64 + fmt.Sscanf(strings.TrimPrefix(data, prefix), "%d", &id) + return id +} + +func (s *UpdateHandler) handleRevokeStart(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64) { + ctx := context.Background() + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck + + revokeKey := fmt.Sprintf("appr_revoke_pending:%d", cq.From.ID) + if err := s.ipc.RedisClient.Set(ctx, revokeKey, fmt.Sprintf("%d", approvalID), 10*time.Minute); err != nil { + logrus.Errorf("handleRevokeStart: Set err=%v", err) + return + } + + msg := tgbotapi.NewMessage(cq.Message.Chat.ID, "Укажите причину отзыва заявки:") + msg.ParseMode = "HTML" + bot.Send(msg) //nolint:errcheck +} diff --git a/service/telegram_service/common/update/update.go b/service/telegram_service/common/update/update.go new file mode 100644 index 0000000..0148d32 --- /dev/null +++ b/service/telegram_service/common/update/update.go @@ -0,0 +1,250 @@ +package tgupdatehandler + +import ( + "context" + "fmt" + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" + "github.com/sirupsen/logrus" + "strings" +) + +func (s *UpdateHandler) GetUpdateTelegram() { + bot := s.ipc.TGBotClient.Bot() + + u := tgbotapi.NewUpdate(0) + u.Timeout = 10 + updates := bot.GetUpdatesChan(u) + + logrus.Info("🟢 Telegram Bot запущен. Ожидание обновлений...") + + for update := range updates { + if update.Message != nil { + go s.handleMessage(bot, update.Message) + continue + } + if update.CallbackQuery != nil { + go s.handleCallback(bot, update.CallbackQuery) + continue + } + } +} + +func (s *UpdateHandler) handleMessage(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) { + ctx := context.Background() + + if msg.IsCommand() { + switch msg.Command() { + case "start": + s.startHandler.Handle(bot, msg) + case "approvals": + s.withDepartmentCheck(bot, msg, func() { + s.approvalHandler.HandleMenu(bot, msg.Chat.ID, msg.From.ID) + }) + } + return + } + + // ── Постоянные кнопки меню ─────────────────────────────────────────────── + switch msg.Text { + case "👤 Инициатор": + s.withDepartmentCheck(bot, msg, func() { + s.approvalHandler.HandleInitiatorSubmenu(bot, msg.Chat.ID) + }) + return + + case "✅ Согласующий": + s.withDepartmentCheck(bot, msg, func() { + ctx := context.Background() + user, err := s.ipc.Database.User.GetUserByTelegramIDDB(ctx, msg.From.ID) + if err != nil || user == nil || user.ID == nil { + return + } + isApprover, _ := s.ipc.Database.User.IsApproverDB(ctx, *user.ID) + isDirector, _ := s.ipc.Database.User.IsDirectorDB(ctx, *user.ID) + if !isApprover && !isDirector { + return + } + s.approvalHandler.HandleApproverSubmenu(bot, msg.Chat.ID) + }) + return + + case "👁 Наблюдатель": + s.withDepartmentCheck(bot, msg, func() { + ctx := context.Background() + user, err := s.ipc.Database.User.GetUserByTelegramIDDB(ctx, msg.From.ID) + if err != nil || user == nil || user.ID == nil { + return + } + isObserver, _ := s.ipc.Database.User.IsObserverDB(ctx, *user.ID) + if !isObserver { + return + } + s.approvalHandler.HandleObserverSubmenu(bot, msg.Chat.ID) + }) + return + + case "➕ Создать согласование": + s.withDepartmentCheck(bot, msg, func() { + s.approvalHandler.HandleMenu(bot, msg.Chat.ID, msg.From.ID) + }) + return + + case "Ранее созданные согласования": + s.withDepartmentCheck(bot, msg, func() { + s.approvalHandler.HandleMyApprovals(bot, msg.Chat.ID, msg.From.ID) + }) + return + + case "Принять согласование в работу": + s.withDepartmentCheck(bot, msg, func() { + s.approvalHandler.HandleIncomingApprovals(bot, msg.Chat.ID, msg.From.ID) + }) + return + + case "Отложенные согласования": + s.withDepartmentCheck(bot, msg, func() { + s.approvalHandler.HandlePendingCommentsList(bot, msg.Chat.ID, msg.From.ID) + }) + return + + case "Список согласований": + s.withDepartmentCheck(bot, msg, func() { + s.approvalHandler.HandleApproverApprovals(bot, msg.Chat.ID, msg.From.ID) + }) + return + + case "📊 Сформировать отчёт": + s.withDepartmentCheck(bot, msg, func() { + s.approvalHandler.HandleReportMenu(bot, msg.Chat.ID, msg.From.ID) + }) + return + + case "Делегировать права": + s.withDepartmentCheck(bot, msg, func() { + s.approvalHandler.HandleDelegationMainMenu(bot, msg.Chat.ID, msg.From.ID) + }) + return + + case "Наблюдать за согласованием": + s.withDepartmentCheck(bot, msg, func() { + s.approvalHandler.HandleObservedApprovals(bot, msg.Chat.ID, msg.From.ID) + }) + return + + case "Задачи к исполнению": + s.withDepartmentCheck(bot, msg, func() { + s.approvalHandler.HandleMyTasks(bot, msg.Chat.ID, msg.From.ID) + }) + return + + case "Все", "Согласованные", "Не согласованные", "Ожидают согласования": + statusMap := map[string]string{ + "Все": "all", "Согласованные": "approved", + "Не согласованные": "rejected", "Ожидают согласования": "pending", + } + s.approvalHandler.HandleMyApprovalsByStatus(bot, msg.Chat.ID, msg.From.ID, statusMap[msg.Text]) + return + + case "❓ Как создать согласование?": + s.withDepartmentCheck(bot, msg, func() { + s.faqHandler.Handle(bot, msg) + }) + return + + case "💬 Предложения и пожелания": + s.withDepartmentCheck(bot, msg, func() { + s.suggestionHandler.HandleCreateSuggestion(bot, msg.Chat.ID, msg.From.ID) + }) + return + + case "← Назад": + s.withDepartmentCheck(bot, msg, func() { + s.approvalHandler.HandleBackNavigation(bot, msg.Chat.ID, msg.From.ID) + }) + return + } + + revisionKey := fmt.Sprintf("appr_revision_pending:%d", msg.From.ID) + if val, err := s.ipc.RedisClient.Get(ctx, revisionKey); err == nil && val != "" { + var approvalID uint64 + fmt.Sscanf(val, "%d", &approvalID) + s.ipc.RedisClient.Del(ctx, revisionKey) //nolint:errcheck + s.approvalHandler.HandleRevisionWithComment(bot, msg.Chat.ID, msg.From.ID, approvalID, strings.TrimSpace(msg.Text)) + return + } + + approveCommentKey := fmt.Sprintf("appr_approve_comment_pending:%d", msg.From.ID) + if val, err := s.ipc.RedisClient.Get(ctx, approveCommentKey); err == nil && val != "" { + var approvalID uint64 + fmt.Sscanf(val, "%d", &approvalID) + s.ipc.RedisClient.Del(ctx, approveCommentKey) //nolint:errcheck + s.approvalHandler.HandleDecisionWithChat(bot, msg.Chat.ID, msg.From.ID, approvalID, true, strings.TrimSpace(msg.Text)) + return + } + + rejectKey := fmt.Sprintf("appr_reject_pending:%d", msg.From.ID) + if val, err := s.ipc.RedisClient.Get(ctx, rejectKey); err == nil && val != "" { + var approvalID uint64 + fmt.Sscanf(val, "%d", &approvalID) + s.ipc.RedisClient.Del(ctx, rejectKey) //nolint:errcheck + s.approvalHandler.HandleDecisionWithChat(bot, msg.Chat.ID, msg.From.ID, approvalID, false, strings.TrimSpace(msg.Text)) + return + } + + if s.approvalHandler.HandleRevisionTextInput(bot, msg) { + return + } + if s.approvalHandler.HandleAttachFileInput(bot, msg) { + return + } + if s.approvalHandler.HandleRevisionFileInput(bot, msg) { + return + } + if s.approvalHandler.HandlePendingCommentInput(bot, msg) { + return + } + if s.approvalHandler.HandleReportTextInput(bot, msg) { + return + } + if s.startHandler.HandleTextInput(bot, msg) { + return + } + if s.approvalHandler.HandleCommentReplyInput(bot, msg) { + return + } + if s.approvalHandler.HandleCommentTextInput(bot, msg) { + return + } + if s.suggestionHandler.HandleSuggestionTextInput(bot, msg) { + return + } + + if msg.Photo != nil || msg.Document != nil { + s.withDepartmentCheck(bot, msg, func() { + s.approvalHandler.HandleFileInput(bot, msg) + }) + return + } + + if s.approvalHandler.HandleDelegationDateInput(bot, msg) { + return + } + if s.approvalHandler.HandleDelegationExtendInput(bot, msg) { + return + } + + s.withDepartmentCheck(bot, msg, func() { + s.approvalHandler.HandleTextInput(bot, msg) + }) +} + +// withDepartmentCheck блокирует действие если отдел не назначен. +func (s *UpdateHandler) withDepartmentCheck(bot *tgbotapi.BotAPI, msg *tgbotapi.Message, action func()) { + ctx := context.Background() + + user, err := s.ipc.Database.User.GetUserByTelegramIDDB(ctx, msg.From.ID) + if err != nil || user == nil || user.DepartmentID == nil { + return // молчим — бот пуст + } + action() +} diff --git a/service/telegram_service/go.mod b/service/telegram_service/go.mod new file mode 100644 index 0000000..cf64f92 --- /dev/null +++ b/service/telegram_service/go.mod @@ -0,0 +1,57 @@ +module bitrix_balancer_api/telegram_service + +go 1.25.6 + +replace bitrix_balancer_api/core => ../../core + +require ( + bitrix_balancer_api/core v0.0.0-00010101000000-000000000000 + github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1 + github.com/sirupsen/logrus v1.9.4 +) + +require ( + 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/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/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/richardlehane/mscfb v1.0.6 // indirect + github.com/richardlehane/msoleps v1.0.6 // indirect + github.com/ryanuber/go-glob v1.0.0 // indirect + github.com/tiendc/go-deepcopy v1.7.2 // indirect + github.com/xuri/efp v0.0.1 // indirect + github.com/xuri/excelize/v2 v2.10.1 // indirect + github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9 // indirect + go.uber.org/atomic v1.11.0 // indirect + golang.org/x/crypto v0.48.0 // indirect + golang.org/x/net v0.50.0 // indirect + golang.org/x/sync v0.19.0 // indirect + golang.org/x/sys v0.41.0 // indirect + golang.org/x/text v0.34.0 // indirect + golang.org/x/time v0.12.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/telegram_service/go.sum b/service/telegram_service/go.sum new file mode 100644 index 0000000..ea3638a --- /dev/null +++ b/service/telegram_service/go.sum @@ -0,0 +1,137 @@ +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-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-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/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.0.9 h1:lgaqFMSdTdQYdZ04uHyN2d/eKdOMyi2YLSvlQIBFYa4= +github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +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/richardlehane/mscfb v1.0.6 h1:eN3bvvZCp00bs7Zf52bxNwAx5lJDBK1tCuH19qq5aC8= +github.com/richardlehane/mscfb v1.0.6/go.mod h1:pe0+IUIc0AHh0+teNzBlJCtSyZdFOGgV4ZK9bsoV+Jo= +github.com/richardlehane/msoleps v1.0.6 h1:9BvkpjvD+iUBalUY4esMwv6uBkfOip/Lzvd93jvR9gg= +github.com/richardlehane/msoleps v1.0.6/go.mod h1:BWev5JBpU9Ko2WAgmZEuiz4/u3ZYTKbjLycmwiWUfWg= +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/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/tiendc/go-deepcopy v1.7.2 h1:Ut2yYR7W9tWjTQitganoIue4UGxZwCcJy3orjrrIj44= +github.com/tiendc/go-deepcopy v1.7.2/go.mod h1:4bKjNC2r7boYOkD2IOuZpYjmlDdzjbpTRyCx+goBCJQ= +github.com/xuri/efp v0.0.1 h1:fws5Rv3myXyYni8uwj2qKjVaRP30PdjeYe2Y6FDsCL8= +github.com/xuri/efp v0.0.1/go.mod h1:ybY/Jr0T0GTCnYjKqmdwxyxn2BQf2RcQIIvex5QldPI= +github.com/xuri/excelize/v2 v2.10.1 h1:V62UlqopMqha3kOpnlHy2CcRVw1V8E63jFoWUmMzxN0= +github.com/xuri/excelize/v2 v2.10.1/go.mod h1:iG5tARpgaEeIhTqt3/fgXCGoBRt4hNXgCp3tfXKoOIc= +github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9 h1:+C0TIdyyYmzadGaL/HBLbf3WdLgC29pgyhTjAT/0nuE= +github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9/go.mod h1:WwHg+CVyzlv/TX9xqBFXEZAuxOPxn2k1GNHwG41IIUQ= +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= +golang.org/x/crypto v0.40.0 h1:r4x+VvoG5Fm+eJcxMaY8CQM7Lb0l1lsmjGBQ6s8BfKM= +golang.org/x/crypto v0.40.0/go.mod h1:Qr1vMER5WyS2dfPHAlsOj01wgLbsyWtFn/aY+5+ZdxY= +golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts= +golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos= +golang.org/x/net v0.42.0 h1:jzkYrhi3YQWD6MLBJcsklgQsoAcw89EcZbJw8Z614hs= +golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8= +golang.org/x/net v0.50.0 h1:ucWh9eiCGyDR3vtzso0WMQinm2Dnt8cFMuQa9K33J60= +golang.org/x/net v0.50.0/go.mod h1:UgoSli3F/pBgdJBHCTc+tp3gmrU4XswgGRgtnwWTfyM= +golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug= +golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= +golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= +golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k= +golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk= +golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4= +golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk= +golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA= +golang.org/x/time v0.12.0 h1:ScB/8o8olJvc+CQPWrK3fPZNfh7qgwCrY0zJmoEQLSE= +golang.org/x/time v0.12.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg= +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/telegram_service/handlers/approval/approver_approvals.go b/service/telegram_service/handlers/approval/approver_approvals.go new file mode 100644 index 0000000..5c68e3b --- /dev/null +++ b/service/telegram_service/handlers/approval/approver_approvals.go @@ -0,0 +1,211 @@ +package approval + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/core/utilscore" + "context" + "fmt" + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" + "github.com/sirupsen/logrus" +) + +// HandleApproverApprovals — вход в флоу: показываем темы, по которым +// пользователь участвовал как согласующий. +func (h *Handler) HandleApproverApprovals(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) { + ctx := context.Background() + + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || user == nil || user.ID == nil { + return + } + + // Категории, в которых пользователь был согласующим + categories, err := h.ipc.Database.ApprovalTopicCategory.GetCategoriesWithApprovalsByApproverDB(ctx, *user.ID) + if err != nil || len(categories) == 0 { + // Сразу показываем все без фильтра по теме + h.HandleApproverApprovalsStatusCallback( + bot, + &tgbotapi.CallbackQuery{ + Message: &tgbotapi.Message{Chat: &tgbotapi.Chat{ID: chatID}}, + From: &tgbotapi.User{ID: telegramID}, + }, + "all", "all", + ) + return + } + + msg := tgbotapi.NewMessage(chatID, "📂 Согласования в работе\n\nВыберите тему:") + msg.ParseMode = "HTML" + msg.ReplyMarkup = buildApproverApprovalsTopicFilter(categories) + bot.Send(msg) //nolint:errcheck +} + +// HandleApproverApprovalsTopicCallback — пользователь выбрал тему. +func (h *Handler) HandleApproverApprovalsTopicCallback( + bot *tgbotapi.BotAPI, + cq *tgbotapi.CallbackQuery, + topicFilter string, +) { + ctx := context.Background() + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck + + header := "Все темы" + if topicFilter != "all" && topicFilter != "" { + cat, _ := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByCodeDB(ctx, topicFilter) + if cat != nil && cat.Name != nil { + header = *cat.Name + } + } + + msg := tgbotapi.NewMessage(cq.Message.Chat.ID, + fmt.Sprintf("📂 %s\n\nВыберите статус:", header), + ) + msg.ParseMode = "HTML" + msg.ReplyMarkup = buildApproverApprovalsStatusFilter(topicFilter) + bot.Send(msg) //nolint:errcheck +} + +// HandleApproverApprovalsStatusCallback — пользователь выбрал статус, +// показываем список согласований, где он был согласующим. +func (h *Handler) HandleApproverApprovalsStatusCallback( + bot *tgbotapi.BotAPI, + cq *tgbotapi.CallbackQuery, + status, topicFilter string, +) { + ctx := context.Background() + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck + + chatID := cq.Message.Chat.ID + telegramID := cq.From.ID + + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || user == nil || user.ID == nil { + return + } + + stepStatus := status + if stepStatus == "all" { + stepStatus = "" + } + + stepFilter := &typescore.ApprovalStep{ + ApproverID: user.ID, + } + if stepStatus != "" { + stepFilter.Status = utilscore.PointerToString(stepStatus) + } + + steps, _, err := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ + Filtering: stepFilter, + }) + if err != nil { + logrus.Errorf("HandleApproverApprovalsStatusCallback: GetApprovalStepsListDB err=%v", err) + sendText(bot, chatID, "Ошибка при получении заявок.") + return + } + + allowedTopicIDs := make(map[uint64]bool) + if topicFilter != "" && topicFilter != "all" { + cat, _ := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByCodeDB(ctx, topicFilter) + if cat != nil && cat.ID != nil { + topics, _, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalTopic{CategoryID: cat.ID}, + }) + for _, t := range topics { + if t.ID != nil { + allowedTopicIDs[*t.ID] = true + } + } + } + } + + // Дедублируем approvalID + seen := make(map[uint64]struct{}) + var filtered []*typescore.ApprovalStep + for _, step := range steps { + if step.ApprovalID == nil { + continue + } + if _, ok := seen[*step.ApprovalID]; ok { + continue + } + seen[*step.ApprovalID] = struct{}{} + filtered = append(filtered, step) + } + + if len(filtered) == 0 { + sendText(bot, chatID, "📭 Заявок по выбранным фильтрам не найдено.") + return + } + + sent := 0 + for _, step := range filtered { + approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, *step.ApprovalID) + if err != nil || approval == nil { + continue + } + + // 🚀 Фильтр по теме через map разрешённых ID + if len(allowedTopicIDs) > 0 { + if approval.TopicID == nil || !allowedTopicIDs[*approval.TopicID] { + continue + } + } + + h.sendApprovalCard(bot, chatID, approval, false, false) + sent++ + } + + if sent == 0 { + sendText(bot, chatID, "📭 Заявок по выбранным фильтрам не найдено.") + } +} + +// ─── inline-клавиатуры ─────────────────────────────────────────────────────── + +func buildApproverApprovalsTopicFilter( + categories []*typescore.ApprovalTopicCategory, +) tgbotapi.InlineKeyboardMarkup { + var rows [][]tgbotapi.InlineKeyboardButton + + rows = append(rows, tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData("📋 Все темы", "appr_appr_topic:all"), + )) + + for _, c := range categories { + if c.ID == nil || c.Name == nil || c.Code == nil { + continue + } + rows = append(rows, tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData( + *c.Name, + fmt.Sprintf("appr_appr_topic:%s", *c.Code), + ), + )) + } + + return tgbotapi.NewInlineKeyboardMarkup(rows...) +} + +func buildApproverApprovalsStatusFilter(topicFilter string) tgbotapi.InlineKeyboardMarkup { + cb := func(status string) string { + return fmt.Sprintf("appr_appr_status:%s:%s", status, topicFilter) + } + return tgbotapi.NewInlineKeyboardMarkup( + tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData("Все", cb("all")), + ), + tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData("✅ Согласованные", cb("approved")), + tgbotapi.NewInlineKeyboardButtonData("❌ Отклонённые", cb("rejected")), + ), + tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData("⏳ Ожидают", cb("pending")), + ), + tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData("← Назад", "appr_appr_back"), + ), + ) +} diff --git a/service/telegram_service/handlers/approval/handle_attachment.go b/service/telegram_service/handlers/approval/handle_attachment.go new file mode 100644 index 0000000..0b731a0 --- /dev/null +++ b/service/telegram_service/handlers/approval/handle_attachment.go @@ -0,0 +1,4 @@ +// telegram_service/handlers/approval/attachment.go - ЗАМЕНИТЬ полностью + +package approval + diff --git a/service/telegram_service/handlers/approval/handle_files.go b/service/telegram_service/handlers/approval/handle_files.go new file mode 100644 index 0000000..900b678 --- /dev/null +++ b/service/telegram_service/handlers/approval/handle_files.go @@ -0,0 +1,466 @@ +package approval + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/telegram_service/keyboard" + "bitrix_balancer_api/telegram_service/state" + "context" + "fmt" + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" + "github.com/sirupsen/logrus" + "sync" + "time" +) + +const maxAttachFiles = 10 + +var ( + albumDebounce = make(map[int64]*time.Timer) + albumDebounceMu sync.Mutex +) + +var ( + fileInputMu = make(map[int64]*sync.Mutex) + fileInputMuMu sync.Mutex +) + +func getFileInputMutex(telegramID int64) *sync.Mutex { + fileInputMuMu.Lock() + defer fileInputMuMu.Unlock() + + if _, ok := fileInputMu[telegramID]; !ok { + fileInputMu[telegramID] = &sync.Mutex{} + } + return fileInputMu[telegramID] +} + +// HandleAttachFileStart — начало прикрепления файлов (согласующий/исполнитель) +func (h *Handler) HandleAttachFileStart(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64) { + ctx := context.Background() + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, cq.From.ID) + if err != nil || user == nil || user.ID == nil { + return + } + + approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID) + if err != nil || approval == nil { + sendText(bot, cq.Message.Chat.ID, "⚠️ Заявка не найдена.") + return + } + + canAttach, _ := h.canUserCommentApproval(ctx, *user.ID, approval) + if !canAttach { + sendText(bot, cq.Message.Chat.ID, "⚠️ Нет прав на прикрепление файлов.") + return + } + + session := &state.AttachmentSession{ + ApprovalID: approvalID, + Files: []state.FileAttachment{}, + Stage: "collecting", + } + h.States.SetAttachmentSession(ctx, cq.From.ID, session) //nolint:errcheck + + msg := tgbotapi.NewMessage(cq.Message.Chat.ID, + fmt.Sprintf( + "📎 Прикрепление файлов к заявке #%d\n\n"+ + "Отправляйте файлы по одному или альбомом.\n"+ + "Максимум %d файлов за раз.\n\n"+ + "Когда закончите — нажмите «Отправить».", + approvalID, maxAttachFiles, + ), + ) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildAttachSessionKeyboard(approvalID, 0) + bot.Send(msg) //nolint:errcheck +} + +// HandleAttachFileInput — пользователь отправил файл в режиме прикрепления +func (h *Handler) HandleAttachFileInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) bool { + ctx := context.Background() + telegramID := msg.From.ID + chatID := msg.Chat.ID + + mu := getFileInputMutex(telegramID) + mu.Lock() + defer mu.Unlock() + + session, err := h.States.GetAttachmentSession(ctx, telegramID) + if err != nil || session == nil || session.Stage != "collecting" { + return false + } + + if len(session.Files) >= maxAttachFiles { + sendText(bot, chatID, fmt.Sprintf("⚠️ Максимум %d файлов. Сначала отправьте текущие.", maxAttachFiles)) + return true + } + + var fileID, fileName string + switch { + case msg.Document != nil: + fileID = msg.Document.FileID + fileName = msg.Document.FileName + if fileName == "" { + fileName = fmt.Sprintf("document_%s", time.Now().Format("20060102_150405")) + } + case msg.Photo != nil && len(msg.Photo) > 0: + fileID = msg.Photo[len(msg.Photo)-1].FileID + fileName = fmt.Sprintf("photo_%s.jpg", time.Now().Format("20060102_150405.000")) + default: + sendText(bot, chatID, "⚠️ Отправьте фото или документ.") + return true + } + + fileURL, err := bot.GetFileDirectURL(fileID) + if err != nil { + logrus.Errorf("HandleAttachFileInput: GetFileDirectURL err=%v", err) + sendText(bot, chatID, "Ошибка при получении файла.") + return true + } + + base64Data, err := fetchFileAsBase64(fileURL, h.ipc.Config.Telegram) + if err != nil { + logrus.Errorf("HandleAttachFileInput: fetchFileAsBase64 err=%v", err) + sendText(bot, chatID, "Ошибка при обработке файла.") + return true + } + + session.Files = append(session.Files, state.FileAttachment{ + Base64: base64Data, + FileName: fileName, + }) + h.States.SetAttachmentSession(ctx, telegramID, session) //nolint:errcheck + + if msg.MediaGroupID != "" { + albumDebounceMu.Lock() + if t, ok := albumDebounce[telegramID]; ok { + t.Stop() + } + albumDebounce[telegramID] = time.AfterFunc(500*time.Millisecond, func() { + albumDebounceMu.Lock() + delete(albumDebounce, telegramID) + albumDebounceMu.Unlock() + + mu := getFileInputMutex(telegramID) + mu.Lock() + defer mu.Unlock() + + fresh, err := h.States.GetAttachmentSession(ctx, telegramID) + if err != nil || fresh == nil { + return + } + h.sendAttachStatusMessage(bot, chatID, fresh) + }) + albumDebounceMu.Unlock() + } else { + h.sendAttachStatusMessage(bot, chatID, session) + } + + return true +} + +func (h *Handler) sendAttachStatusMessage(bot *tgbotapi.BotAPI, chatID int64, session *state.AttachmentSession) { + fileListText := fmt.Sprintf( + "📎 Прикрепление файлов к заявке #%d\n\n"+ + "✅ Добавлено файлов: %d/%d\n\n", + session.ApprovalID, len(session.Files), maxAttachFiles, + ) + for i, f := range session.Files { + fileListText += fmt.Sprintf("%d. %s\n", i+1, f.FileName) + } + fileListText += "\nОтправьте ещё или нажмите «Отправить»." + + statusMsg := tgbotapi.NewMessage(chatID, fileListText) + statusMsg.ParseMode = "HTML" + statusMsg.ReplyMarkup = keyboard.BuildAttachSessionKeyboard(session.ApprovalID, len(session.Files)) + bot.Send(statusMsg) //nolint:errcheck +} + +// HandleAttachSubmit — пользователь нажал "Отправить файлы" +func (h *Handler) HandleAttachSubmit(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64) { + ctx := context.Background() + chatID := cq.Message.Chat.ID + telegramID := cq.From.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck + + session, err := h.States.GetAttachmentSession(ctx, telegramID) + if err != nil || session == nil { + sendText(bot, chatID, "⚠️ Сессия истекла. Начните заново.") + return + } + + if len(session.Files) == 0 { + sendText(bot, chatID, "⚠️ Нет файлов для отправки.") + return + } + + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || user == nil || user.ID == nil { + return + } + + // 🚀 Если это прикрепление к задаче — получаем taskID из сессии + var taskIDPtr *uint64 + if session.TaskID > 0 { + taskIDPtr = &session.TaskID + } + + // Сохраняем все файлы пакетом + savedCount := 0 + for _, f := range session.Files { + fileCopy := f + file := &typescore.ApprovalFile{ + ApprovalID: &approvalID, + FileBase64: &fileCopy.Base64, + FileName: &fileCopy.FileName, + AttachedByID: user.ID, + TaskID: taskIDPtr, // 🚀 НОВОЕ: связываем с задачей + } + if _, _, err := h.ipc.Database.ApprovalFile.CreateApprovalFileDB(ctx, nil, file); err != nil { + logrus.Errorf("HandleAttachSubmit: CreateApprovalFileDB file=%s err=%v", f.FileName, err) + continue + } + savedCount++ + } + + h.States.ClearAttachmentSession(ctx, telegramID) //nolint:errcheck + + sendText(bot, chatID, fmt.Sprintf( + "✅ Файлы прикреплены к заявке #%d\n\n📎 Сохранено файлов: %d", + approvalID, savedCount, + )) + + // Если это было прикрепление к задаче — показываем карточку задачи + if session.TaskID > 0 { + task, _ := h.ipc.Database.ApprovalTasks.GetApprovalTaskByIDDB(ctx, session.TaskID) + if task != nil { + approval, _ := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID) + if approval != nil { + h.sendTaskCard(bot, chatID, approval, task) + } + } + } + + // Уведомляем всех участников с отправкой самих файлов медиагруппами + fileDesc := fmt.Sprintf("%d файл(ов)", savedCount) + h.notifyAllParticipantsAboutFile(bot, approvalID, user, fileDesc) +} + +// HandleAttachClear — очистить список файлов +func (h *Handler) HandleAttachClear(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64) { + ctx := context.Background() + telegramID := cq.From.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + + session, _ := h.States.GetAttachmentSession(ctx, telegramID) + if session != nil { + session.Files = []state.FileAttachment{} + h.States.SetAttachmentSession(ctx, telegramID, session) //nolint:errcheck + } + + editMsg := tgbotapi.NewEditMessageReplyMarkup( + cq.Message.Chat.ID, + cq.Message.MessageID, + keyboard.BuildAttachSessionKeyboard(approvalID, 0), + ) + bot.Request(editMsg) //nolint:errcheck + + sendText(bot, cq.Message.Chat.ID, "🗑 Список файлов очищен. Отправьте новые файлы.") +} + +// HandleAttachCancel — отмена прикрепления +func (h *Handler) HandleAttachCancel(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery) { + ctx := context.Background() + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck + + h.States.ClearAttachmentSession(ctx, cq.From.ID) //nolint:errcheck + sendText(bot, cq.Message.Chat.ID, "❌ Прикрепление файлов отменено.") +} + +// HandleFileInput обрабатывает прикреплённый файл (фото или документ) во время флоу. +func (h *Handler) HandleFileInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) bool { + ctx := context.Background() + telegramID := msg.From.ID + chatID := msg.Chat.ID + + mu := getFileInputMutex(telegramID) + mu.Lock() + defer mu.Unlock() + + flowState, err := h.States.Get(ctx, telegramID) + if err != nil || flowState == nil || !flowState.AwaitFileInput { + return false + } + + var fileID, fileName string + + switch { + case msg.Document != nil: + fileID = msg.Document.FileID + fileName = msg.Document.FileName + if fileName == "" { + fileName = fmt.Sprintf("document_%s", time.Now().Format("20060102_150405")) + } + case msg.Photo != nil && len(msg.Photo) > 0: + fileID = msg.Photo[len(msg.Photo)-1].FileID + fileName = fmt.Sprintf("photo_%s.jpg", time.Now().Format("20060102_150405.000")) + default: + sendText(bot, chatID, "⚠️ Пожалуйста, отправьте фото или документ.") + return true + } + + fileURL, err := bot.GetFileDirectURL(fileID) + if err != nil { + logrus.Errorf("HandleFileInput: GetFileDirectURL fileID=%s err=%v", fileID, err) + sendText(bot, chatID, "Ошибка при получении файла. Попробуйте ещё раз.") + return true + } + + if fileURL == "" { + logrus.Errorf("HandleFileInput: empty fileURL for fileID=%s", fileID) + sendText(bot, chatID, "Ошибка: не удалось получить ссылку на файл.") + return true + } + + base64Data, err := fetchFileAsBase64(fileURL, h.ipc.Config.Telegram) + if err != nil { + logrus.Errorf("HandleFileInput: fetchFileAsBase64 url=%s err=%v", fileURL, err) + sendText(bot, chatID, "Ошибка при обработке файла. Попробуйте ещё раз.") + return true + } + + if base64Data == "" { + logrus.Errorf("HandleFileInput: empty base64 for fileID=%s", fileID) + sendText(bot, chatID, "Ошибка: файл пустой. Попробуйте ещё раз.") + return true + } + + flowState.Files = append(flowState.Files, state.FileAttachment{ + Base64: base64Data, + FileName: fileName, + MessageID: msg.MessageID, + }) + h.States.Set(ctx, telegramID, flowState) //nolint:errcheck + + logrus.Infof("HandleFileInput: attached file=%s size=%d telegramID=%d total=%d", + fileName, len(base64Data), telegramID, len(flowState.Files)) + + // Дебаунс для альбомов + if msg.MediaGroupID != "" { + albumDebounceMu.Lock() + if t, ok := albumDebounce[telegramID]; ok { + t.Stop() + } + albumDebounce[telegramID] = time.AfterFunc(500*time.Millisecond, func() { + albumDebounceMu.Lock() + delete(albumDebounce, telegramID) + albumDebounceMu.Unlock() + + mu := getFileInputMutex(telegramID) + mu.Lock() + defer mu.Unlock() + + fresh, err := h.States.Get(ctx, telegramID) + if err != nil || fresh == nil { + return + } + h.showFileStatus(bot, chatID, telegramID, fresh, false) + }) + albumDebounceMu.Unlock() + } else { + h.showFileStatus(bot, chatID, telegramID, flowState, false) + } + + return true +} + +// HandleDetachFile удаляет файл из списка по индексу и обновляет статусное сообщение. +func (h *Handler) HandleDetachFile(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, index int) { + ctx := context.Background() + + flowState, err := h.States.Get(ctx, telegramID) + if err != nil || flowState == nil { + return + } + + if index < 0 || index >= len(flowState.Files) { + logrus.Warnf("HandleDetachFile: invalid index %d (total=%d)", index, len(flowState.Files)) + return + } + + removed := flowState.Files[index] + + // Удаляем сообщение с файлом из чата + if removed.MessageID != 0 { + bot.Request(tgbotapi.NewDeleteMessage(chatID, removed.MessageID)) //nolint:errcheck + } + + flowState.Files = append(flowState.Files[:index], flowState.Files[index+1:]...) + logrus.Infof("HandleDetachFile: removed file %q, remaining=%d", removed.FileName, len(flowState.Files)) + + h.States.Set(ctx, telegramID, flowState) //nolint:errcheck + isRequired := false + if topic, err := h.Registry.Get(flowState.TopicCode); err == nil { + if code, err := topic.TopicCodeFromCollected(flowState.Collected); err == nil { + if at, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByCodeDB(ctx, code); at != nil { + isRequired = (at.RequiresFile != nil && *at.RequiresFile) || + flowState.Collected["payment_type"] == "official" + } + } + } + h.showFileStatus(bot, chatID, telegramID, flowState, isRequired) +} + +// HandleSubmitFiles финализирует заявку. withFiles=false очищает список файлов перед отправкой. +func (h *Handler) HandleSubmitFiles(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, withFiles bool) { + ctx := context.Background() + + flowState, err := h.States.Get(ctx, telegramID) + if err != nil || flowState == nil { + return + } + + // Проверяем обязательность файла + if withFiles == false { + topic, _ := h.Registry.Get(flowState.TopicCode) + if topic != nil { + topicCode, _ := topic.TopicCodeFromCollected(flowState.Collected) + approvalTopic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByCodeDB(ctx, topicCode) + + isRequired := (approvalTopic != nil && approvalTopic.RequiresFile != nil && *approvalTopic.RequiresFile) || + flowState.Collected["payment_type"] == "official" + + if isRequired { + // Нельзя отправить без файла — показываем предупреждение + sendText(bot, chatID, + "⚠️ Файл обязателен для этой темы.\n\n"+ + "Прикрепите файл чтобы продолжить.") + // Перерисовываем экран файлов + h.showFileStatus(bot, chatID, telegramID, flowState, true) + return + } + } + } + + if !withFiles { + flowState.Files = nil + } + + if flowState.FileStatusMsgID != 0 { + bot.Request(tgbotapi.NewDeleteMessage(chatID, flowState.FileStatusMsgID)) //nolint:errcheck + flowState.FileStatusMsgID = 0 + } + + flowState.AwaitFileInput = false + flowState.FilesStepCompleted = true + + h.States.Set(ctx, telegramID, flowState) //nolint:errcheck + h.continueFlowAfterInput(bot, ctx, chatID, telegramID, flowState) +} diff --git a/service/telegram_service/handlers/approval/handle_multiselect.go b/service/telegram_service/handlers/approval/handle_multiselect.go new file mode 100644 index 0000000..fb0908e --- /dev/null +++ b/service/telegram_service/handlers/approval/handle_multiselect.go @@ -0,0 +1,149 @@ +package approval + +import ( + "bitrix_balancer_api/telegram_service/approvalflow" + "bitrix_balancer_api/telegram_service/keyboard" + "context" + "fmt" + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" + "strings" +) + +// HandleMultiSelectToggle — пользователь нажал на один из вариантов мультиселекта +func (h *Handler) HandleMultiSelectToggle(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, topicCode, nodeKey, value string) { + ctx := context.Background() + chatID := cq.Message.Chat.ID + telegramID := cq.From.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + + flowState, err := h.States.Get(ctx, telegramID) + if err != nil || flowState == nil || !flowState.AwaitMultiSelectConfirm { + return + } + + if flowState.MultiSelected == nil { + flowState.MultiSelected = make(map[string][]string) + } + + // Toggle значения + current := flowState.MultiSelected[flowState.MultiSelectNodeKey] + found := false + updated := make([]string, 0, len(current)) + for _, v := range current { + if v == value { + found = true // убираем + } else { + updated = append(updated, v) + } + } + if !found { + updated = append(updated, value) + } + flowState.MultiSelected[flowState.MultiSelectNodeKey] = updated + + h.States.Set(ctx, telegramID, flowState) //nolint:errcheck + + // Перестраиваем клавиатуру + topic, _ := h.Registry.Get(topicCode) + if topic == nil { + return + } + tree := topic.BuildTree() + node := approvalflow.FindNode(tree, flowState.MultiSelectNodeKey) + if node == nil { + return + } + + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || user == nil { + return + } + + _ = h.filterNodesByAccess(ctx, telegramID, node.Children) + + editMsg := tgbotapi.NewEditMessageReplyMarkup( + chatID, + cq.Message.MessageID, + keyboard.BuildMultiSelectStep(topicCode, node.Children, updated, nil), + ) + bot.Request(editMsg) //nolint:errcheck +} + +// HandleMultiSelectConfirm — пользователь подтвердил выбор +func (h *Handler) HandleMultiSelectConfirm(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, topicCode string) { + ctx := context.Background() + chatID := cq.Message.Chat.ID + telegramID := cq.From.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck + + flowState, err := h.States.Get(ctx, telegramID) + if err != nil || flowState == nil { + sendText(bot, chatID, "⚠️ Состояние утеряно. Начните заново.") + return + } + + selected := flowState.MultiSelected[flowState.MultiSelectNodeKey] + if len(selected) == 0 { + // Напоминаем что нужно выбрать хотя бы один вариант + bot.Request(tgbotapi.NewCallback(cq.ID, "⚠️ Выберите хотя бы один вариант")) //nolint:errcheck + return + } + + // Сохраняем выбранные значения как строку через запятую в Collected + topic, _ := h.Registry.Get(topicCode) + if topic == nil { + return + } + tree := topic.BuildTree() + node := approvalflow.FindNode(tree, flowState.MultiSelectNodeKey) + if node == nil { + return + } + + // Берём MultiSelectKey из первого дочернего узла + if len(node.Children) > 0 { + msKey := node.Children[0].MultiSelectKey + if msKey != "" { + flowState.Collected[msKey] = strings.Join(selected, ",") + } + } + + flowState.AwaitMultiSelectConfirm = false + flowState.MultiSelectNodeKey = "" + + // Переходим к вводу текста — находим первый input среди детей выбранных узлов + // (InputHint берём из первого выбранного) + var inputNode *approvalflow.FlowNode + for _, child := range node.Children { + for _, sel := range selected { + if child.MultiSelectValue == sel && len(child.Children) > 0 && child.Children[0].IsInput { + inputNode = child.Children[0] + break + } + } + if inputNode != nil { + break + } + } + + if inputNode != nil { + flowState.AwaitInput = true + flowState.InputKey = inputNode.InputKey + flowState.NodeKey = flowState.MultiSelectNodeKey + + h.States.Set(ctx, telegramID, flowState) //nolint:errcheck + + hint := fmt.Sprintf("Введите данные по шаблону:\n%s", inputNode.InputHint) + msg := tgbotapi.NewMessage(chatID, hint) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildApprovalInputPrompt(topicCode) + bot.Send(msg) //nolint:errcheck + return + } + + h.States.Set(ctx, telegramID, flowState) //nolint:errcheck + h.continueFlowAfterInput(bot, ctx, chatID, telegramID, flowState) +} diff --git a/service/telegram_service/handlers/approval/handler.go b/service/telegram_service/handlers/approval/handler.go new file mode 100644 index 0000000..3d298c1 --- /dev/null +++ b/service/telegram_service/handlers/approval/handler.go @@ -0,0 +1,633 @@ +package approval + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/telegram_service/approvalflow" + "bitrix_balancer_api/telegram_service/keyboard" + "bitrix_balancer_api/telegram_service/state" + "bitrix_balancer_api/telegram_service/types" + "context" + "encoding/base64" + "fmt" + "time" + + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" + "github.com/sirupsen/logrus" +) + +type Handler struct { + ipc *types.InternalProviderControl + Registry *Registry + States *state.StateManager +} + +func NewHandler(ipc *types.InternalProviderControl) *Handler { + return &Handler{ + ipc: ipc, + Registry: NewRegistry(), + States: state.NewStateManager(ipc.RedisClient), + } +} + +// HandleMenu — первая страница меню. +func (h *Handler) HandleMenu(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) { + h.HandleMenuPage(bot, chatID, telegramID, 0, 0) +} + +func (h *Handler) HandleInitiatorSubmenu(bot *tgbotapi.BotAPI, chatID int64) { + msg := tgbotapi.NewMessage(chatID, "👤 Инициатор\n\nВыберите действие:") + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildInitiatorSubmenu() + bot.Send(msg) //nolint:errcheck +} + +// HandleApproverSubmenu — подменю для согласующего +func (h *Handler) HandleApproverSubmenu(bot *tgbotapi.BotAPI, chatID int64) { + msg := tgbotapi.NewMessage(chatID, "✅ Согласующий\n\nВыберите действие:") + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildApproverSubmenu() + bot.Send(msg) //nolint:errcheck +} + +// HandleObserverSubmenu — подменю для наблюдателя +func (h *Handler) HandleObserverSubmenu(bot *tgbotapi.BotAPI, chatID int64) { + msg := tgbotapi.NewMessage(chatID, "✅ Наблюдатель\n\nВыберите действие:") + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildObserverSubmenu() + bot.Send(msg) //nolint:errcheck +} + +// HandleMenuPage — показывает меню на нужной странице. +// prevMessageID != 0 — удаляем старое сообщение с пагинацией. +func (h *Handler) HandleMenuPage(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, page int, prevMessageID int) { + ctx := context.Background() + + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || user == nil { + return + } + + allowed, err := h.getAllowedTopicCodes(ctx, user) + if err != nil { + logrus.Error("HandleMenuPage: getAllowedTopicCodes: ", err) + return + } + + var visibleTopics []approvalflow.Topic + for _, t := range h.Registry.All() { + if allowed[t.Code()] { + visibleTopics = append(visibleTopics, t) + } + } + + if len(visibleTopics) == 0 { + msg := tgbotapi.NewMessage(chatID, "У вас нет доступных тем для согласования") + msg.ParseMode = "HTML" + bot.Send(msg) //nolint:errcheck + return + } + + if prevMessageID != 0 { + bot.Request(tgbotapi.NewDeleteMessage(chatID, prevMessageID)) //nolint:errcheck + } + + msg := tgbotapi.NewMessage(chatID, "Выберите тип согласования:") + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildApprovalMenu(visibleTopics, page) + bot.Send(msg) //nolint:errcheck +} + +// HandleCallback обрабатывает нажатие inline-кнопки внутри флоу согласования. +// callbackData формат: appr:{topic_code}:{node_key} +// HandleCallback обрабатывает нажатие inline-кнопки внутри флоу согласования. +func (h *Handler) HandleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, topicCode, nodeKey string) { + ctx := context.Background() + chatID := cq.Message.Chat.ID + telegramID := cq.From.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck + + topic, err := h.Registry.Get(topicCode) + if err != nil { + logrus.Warnf("HandleCallback: unknown topic %s", topicCode) + return + } + + flowState, err := h.States.Get(ctx, telegramID) + if err != nil { + logrus.Error("HandleCallback: get state error", err) + return + } + + isNew := flowState == nil + if isNew { + flowState = &state.ApprovalFlowState{ + TopicCode: topicCode, + NodeKey: nodeKey, + Collected: make(map[string]string), + } + } + + tree := topic.BuildTree() + node := approvalflow.FindNode(tree, nodeKey) + if node == nil { + logrus.Warnf("HandleCallback: node not found: %s", nodeKey) + return + } + + if !isNew { + flowState.History = append(flowState.History, flowState.NodeKey) + } + + if node.DataKey != "" { + flowState.Collected[node.DataKey] = node.DataValue + } + + if len(node.Children) == 0 && !node.IsInput { + logrus.Warnf("HandleCallback: leaf node without IsInput: %s", nodeKey) + return + } + + // Единственный ребёнок — input + if len(node.Children) == 1 && node.Children[0].IsInput { + inputNode := node.Children[0] + if inputNode.DataKey != "" { + flowState.Collected[inputNode.DataKey] = inputNode.DataValue + } + flowState.AwaitInput = true + flowState.InputKey = inputNode.InputKey + flowState.NodeKey = nodeKey + + h.States.Set(ctx, telegramID, flowState) //nolint:errcheck + + hint := fmt.Sprintf("Введите данные по шаблону:\n%s", inputNode.InputHint) + msg := tgbotapi.NewMessage(chatID, hint) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildApprovalInputPrompt(topicCode) + bot.Send(msg) //nolint:errcheck + return + } + + flowState.NodeKey = nodeKey + h.States.Set(ctx, telegramID, flowState) //nolint:errcheck + + visibleChildren := h.filterNodesByAccess(ctx, telegramID, node.Children) + if len(visibleChildren) == 0 { + sendText(bot, chatID, "⚠️ У вас нет доступа к подкатегориям этого раздела.") + h.States.Clear(ctx, telegramID) + return + } + + // Детектируем мультиселект + isMultiSelect := len(visibleChildren) > 0 && visibleChildren[0].IsMultiSelect + if isMultiSelect { + if flowState.MultiSelected == nil { + flowState.MultiSelected = make(map[string][]string) + } + flowState.AwaitMultiSelectConfirm = true + flowState.MultiSelectNodeKey = nodeKey + h.States.Set(ctx, telegramID, flowState) //nolint:errcheck + + msg := tgbotapi.NewMessage(chatID, "Выберите системы (можно несколько):") + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildMultiSelectStep(topicCode, visibleChildren, nil, nil) + bot.Send(msg) //nolint:errcheck + return + } + + msg := tgbotapi.NewMessage(chatID, "Выберите:") + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildApprovalStep(topicCode, visibleChildren) + bot.Send(msg) //nolint:errcheck +} + +func (h *Handler) HandleTextInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) bool { + ctx := context.Background() + telegramID := msg.From.ID + chatID := msg.Chat.ID + + commentKey := fmt.Sprintf("appr_approve_comment_pending:%d", telegramID) + commentApprovalIDStr, err := h.ipc.RedisClient.Get(ctx, commentKey) + if err == nil && commentApprovalIDStr != "" { + var approvalID uint64 + if _, scanErr := fmt.Sscanf(commentApprovalIDStr, "%d", &approvalID); scanErr == nil { + h.ipc.RedisClient.Del(ctx, commentKey) //nolint:errcheck + + h.HandleDecisionWithChat(bot, chatID, telegramID, approvalID, true, msg.Text) + return true + } + } + + commentState, _ := h.States.GetCommentFlow(ctx, telegramID) + if commentState != nil && commentState.Stage == "await_text" { + // Делегируем в HandleCommentTextInput + return h.HandleCommentTextInput(bot, msg) + } + + replyState, _ := h.States.GetCommentReply(ctx, telegramID) + if replyState != nil && replyState.Stage == "await_text" { + return h.HandleCommentReplyInput(bot, msg) + } + + flowState, err := h.States.Get(ctx, telegramID) + if err != nil || flowState == nil || !flowState.AwaitInput { + return false + } + + flowState.Collected[flowState.InputKey] = msg.Text + flowState.AwaitInput = false + + topic, _ := h.Registry.Get(flowState.TopicCode) + if topic != nil { + tree := topic.BuildTree() + parentNode := approvalflow.FindNode(tree, flowState.NodeKey) + if parentNode != nil && len(parentNode.Children) == 1 && parentNode.Children[0].IsInput { + inputNode := parentNode.Children[0] + if len(inputNode.Children) > 0 { + visibleChildren := h.filterNodesByAccess(ctx, telegramID, inputNode.Children) + if len(visibleChildren) == 0 { + sendText(bot, chatID, "⚠️ У вас нет доступа к подкатегориям этого раздела.") + h.States.Clear(ctx, telegramID) //nolint:errcheck + return true + } + + flowState.NodeKey = inputNode.Key + h.States.Set(ctx, telegramID, flowState) //nolint:errcheck + + msg := tgbotapi.NewMessage(chatID, "Выберите:") + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildApprovalStep(flowState.TopicCode, visibleChildren) + bot.Send(msg) //nolint:errcheck + return true + } + } + } + + h.States.Set(ctx, telegramID, flowState) //nolint:errcheck + h.continueFlowAfterInput(bot, ctx, chatID, telegramID, flowState) + return true +} + +func (h *Handler) HandleRevokeWithComment(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, approvalID uint64, comment string) { + ctx := context.Background() + + revoker, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, int64(telegramID)) + if err != nil || revoker == nil || revoker.ID == nil { + sendText(bot, chatID, "⚠️ Пользователь не найден.") + return + } + + approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID) + if err != nil || approval == nil { + sendText(bot, chatID, "⚠️ Заявка не найдена.") + return + } + + if approval.Status == nil { + sendText(bot, chatID, "⚠️ Статус заявки не определён.") + return + } + + // Определяем роли пользователя + isInitiator := approval.InitiatorID != nil && *approval.InitiatorID == *revoker.ID + isDirector, _ := h.ipc.Database.User.IsDirectorDB(ctx, *revoker.ID) + + // 🚀 НОВОЕ: Проверяем, является ли пользователь согласующим по этой заявке + isApprover := false + steps, _, _ := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalStep{ApprovalID: &approvalID}, + }) + for _, step := range steps { + if step.ApproverID != nil && *step.ApproverID == *revoker.ID { + isApprover = true + break + } + } + + // Проверка прав в зависимости от статуса + switch *approval.Status { + case "revoked": + sendText(bot, chatID, "Заявка уже отозвана.") + return + case "rejected": + sendText(bot, chatID, "Нельзя отозвать отклонённую заявку.") + return + case "pending", "revision": + if !isInitiator && !isDirector { + sendText(bot, chatID, "⚠️ В процессе согласования заявку может отозвать только инициатор или директор.") + return + } + case "approved": + if !isInitiator && !isDirector && !isApprover { + sendText(bot, chatID, "⚠️ У вас нет прав для отзыва этой заявки.") + return + } + default: + if !isInitiator && !isDirector { + sendText(bot, chatID, "⚠️ У вас нет прав для отзыва этой заявки.") + return + } + } + + now := time.Now() + revokedStatus := "revoked" + approval.Status = &revokedStatus + approval.RevokedByID = revoker.ID + approval.RevokedAt = &now + + if _, _, err := h.ipc.Database.Approval.UpdateApprovalDB(ctx, nil, approval); err != nil { + logrus.Errorf("HandleRevokeWithComment: UpdateApprovalDB err=%v", err) + sendText(bot, chatID, "Ошибка при отзыве заявки.") + return + } + + h.handleRevokeCancellationTask(bot, ctx, approval, revoker, comment) + + revokerName := "—" + if revoker.FullName != nil { + revokerName = *revoker.FullName + } + + topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID) + + content := "—" + if approval.Content != nil { + content = *approval.Content + } + + revokerRole := "" + switch { + case isInitiator: + revokerRole = "инициатором" + case isDirector: + revokerRole = "директором" + case isApprover: + revokerRole = "согласующим" + } + + approvalCard := fmt.Sprintf( + "📋 Тема: %s\n"+ + "📝 Текст: %s\n"+ + "💬 Причина отзыва: %s", + topicFullName, content, comment, + ) + + // Уведомление тому, кто отзывает + sendText(bot, chatID, fmt.Sprintf( + "↩️ Заявка #%d отозвана\n\n%s", + approvalID, approvalCard, + )) + + if !isInitiator && approval.InitiatorID != nil { + initiator, err := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID) + if err == nil && initiator != nil && initiator.TelegramID != nil { + sendText(bot, *initiator.TelegramID, fmt.Sprintf( + "↩️ Ваша заявка #%d отозвана %s %s\n\n%s", + approvalID, revokerRole, revokerName, approvalCard, + )) + } + } + + if !isDirector { + directors, _ := h.ipc.Database.User.GetDirectorsDB(ctx) + for _, director := range directors { + if director.TelegramID == nil { + continue + } + if revoker.ID != nil && director.ID != nil && *director.ID == *revoker.ID { + continue + } + sendText(bot, *director.TelegramID, fmt.Sprintf( + "↩️ Заявка #%d отозвана %s %s\n\n%s", + approvalID, revokerRole, revokerName, approvalCard, + )) + } + } + + for _, step := range steps { + if step.ApproverID == nil { + continue + } + if revoker.ID != nil && *step.ApproverID == *revoker.ID { + continue + } + approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *step.ApproverID) + if approver == nil || approver.TelegramID == nil { + continue + } + sendText(bot, *approver.TelegramID, fmt.Sprintf( + "↩️ Заявка #%d отозвана %s %s\n\n%s", + approvalID, revokerRole, revokerName, approvalCard, + )) + } + + if *approval.Status == "revoked" { + categoryCode := h.getTopicCodeByApproval(ctx, approval) + observers, _ := h.ipc.Database.User.GetObserversForCategoryDB(ctx, categoryCode) + for _, obs := range observers { + if obs.TelegramID == nil { + continue + } + if revoker.ID != nil && obs.ID != nil && *obs.ID == *revoker.ID { + continue + } + sendText(bot, *obs.TelegramID, fmt.Sprintf( + "↩️ Заявка #%d отозвана %s %s\n\n%s", + approvalID, revokerRole, revokerName, approvalCard, + )) + } + } +} + +// HandleBackCallback — обработчик кнопки "← Назад". +// Логика: pop из History → показываем children того узла. +// Если history пуста — возвращаемся в HandleMenu (выбор темы). +// HandleBackCallback возвращает пользователя на предыдущий шаг флоу. +func (h *Handler) HandleBackCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, topicCode string) { + ctx := context.Background() + chatID := cq.Message.Chat.ID + telegramID := cq.From.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck + + flowState, err := h.States.Get(ctx, telegramID) + if err != nil || flowState == nil { + logrus.Warnf("HandleBackCallback: no active flow for user=%d", telegramID) + return + } + + // Если в режиме файлового ввода — очищаем файлы и статусное сообщение + if flowState.AwaitFileInput { + flowState.AwaitFileInput = false + flowState.Files = nil + + // Удаляем статусное сообщение если есть + if flowState.FileStatusMsgID != 0 { + bot.Request(tgbotapi.NewDeleteMessage(chatID, flowState.FileStatusMsgID)) //nolint:errcheck + flowState.FileStatusMsgID = 0 + } + } + + // Если в режиме текстового ввода — очищаем + if flowState.AwaitInput { + flowState.AwaitInput = false + flowState.InputKey = "" + } + + // Проверяем историю + if len(flowState.History) == 0 { + // Нет истории — возвращаемся в главное меню + h.States.Clear(ctx, telegramID) //nolint:errcheck + h.HandleMenu(bot, chatID, telegramID) + return + } + + // Достаём предыдущий узел из стека + prevNodeKey := flowState.History[len(flowState.History)-1] + flowState.History = flowState.History[:len(flowState.History)-1] + flowState.NodeKey = prevNodeKey + + topic, err := h.Registry.Get(topicCode) + if err != nil { + logrus.Errorf("HandleBackCallback: unknown topic %s", topicCode) + return + } + + tree := topic.BuildTree() + node := approvalflow.FindNode(tree, prevNodeKey) + if node == nil { + logrus.Warnf("HandleBackCallback: node not found: %s", prevNodeKey) + return + } + + h.States.Set(ctx, telegramID, flowState) //nolint:errcheck + + // Фильтруем по правам + visibleChildren := h.filterNodesByAccess(ctx, telegramID, node.Children) + + msg := tgbotapi.NewMessage(chatID, "Выберите:") + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildApprovalStep(topicCode, visibleChildren) + bot.Send(msg) //nolint:errcheck +} + +func (h *Handler) continueFlowAfterInput( + bot *tgbotapi.BotAPI, + ctx context.Context, + chatID int64, + telegramID int64, + flowState *state.ApprovalFlowState, +) { + topic, _ := h.Registry.Get(flowState.TopicCode) + if topic == nil { + h.States.Clear(ctx, telegramID) //nolint:errcheck + return + } + + topicCode, err := topic.TopicCodeFromCollected(flowState.Collected) + if err != nil { + logrus.Warnf("continueFlowAfterInput: TopicCodeFromCollected err=%v", err) + h.States.Clear(ctx, telegramID) //nolint:errcheck + return + } + + approvalTopic, err := h.ipc.Database.ApprovalTopic.GetApprovalTopicByCodeDB(ctx, topicCode) + if err != nil { + logrus.Errorf("continueFlowAfterInput: GetApprovalTopicByCodeDB topicCode=%s err=%v", topicCode, err) + } + + if approvalTopic != nil && !flowState.FilesStepCompleted { + requiresFile := approvalTopic.RequiresFile != nil && *approvalTopic.RequiresFile + allowsFile := approvalTopic.AllowsFile != nil && *approvalTopic.AllowsFile + isOfficial := flowState.Collected["payment_type"] == "official" + + needFileStep := requiresFile || allowsFile || isOfficial + + if needFileStep && !flowState.AwaitFileInput { + flowState.AwaitFileInput = true + flowState.FilesStepCompleted = false + h.States.Set(ctx, telegramID, flowState) //nolint:errcheck + h.showFileStatus(bot, chatID, telegramID, flowState, requiresFile || isOfficial) + return + } + } + + if approvalTopic != nil && + approvalTopic.FirstApproverRoleCode != nil && + *approvalTopic.FirstApproverRoleCode != "" && + flowState.SelectedFirstApproverID == 0 && + !flowState.AwaitFirstApproverSelection { + + flowState.AwaitFirstApproverSelection = true + h.States.Set(ctx, telegramID, flowState) //nolint:errcheck + + roleCode := *approvalTopic.FirstApproverRoleCode + roleLabel := roleCode + role := h.getRoleLabelByCode(ctx, roleCode) + if role != nil && role.Name != nil { + roleLabel = *role.Name + } + h.showFirstApproverSelection(bot, ctx, chatID, telegramID, roleCode, roleLabel) + return + } + + if approvalTopic != nil && + approvalTopic.AllowApproverSelection != nil && + *approvalTopic.AllowApproverSelection && + flowState.SelectedApproverID == 0 && + !flowState.AwaitApproverSelection { + + flowState.AwaitApproverSelection = true + h.States.Set(ctx, telegramID, flowState) //nolint:errcheck + h.showApproverSelection(bot, ctx, chatID, telegramID, approvalTopic) + return + } + + if approvalTopic != nil && + approvalTopic.AllowObserverSelection != nil && + *approvalTopic.AllowObserverSelection && + !flowState.ObserverSelectionDone { + + flowState.ObserverSelectionDone = true + flowState.AwaitObserverSelection = true + h.States.Set(ctx, telegramID, flowState) + h.showObserverSelection(bot, ctx, chatID, telegramID, flowState, approvalTopic) + return + } + + h.States.Clear(ctx, telegramID) //nolint:errcheck + h.finalizeAndSubmit(bot, ctx, chatID, telegramID, flowState) +} + +func (h *Handler) HandleViewFilesCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64) { + ctx := context.Background() + chatID := cq.Message.Chat.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + + files, err := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, approvalID) + if err != nil || len(files) == 0 { + sendText(bot, chatID, "📭 Файлы не найдены.") + return + } + + sendText(bot, chatID, fmt.Sprintf("📎 Файлы к заявке #%d (%d шт.):", approvalID, len(files))) + + for _, f := range files { + if f.FileBase64 == nil || f.FileName == nil { + continue + } + data, err := base64.StdEncoding.DecodeString(*f.FileBase64) + if err != nil { + logrus.Errorf("HandleViewFilesCallback: decode err=%v", err) + continue + } + doc := tgbotapi.NewDocument(chatID, tgbotapi.FileBytes{ + Name: *f.FileName, + Bytes: data, + }) + bot.Send(doc) //nolint:errcheck + } +} diff --git a/service/telegram_service/handlers/approval/handler_add_approver.go b/service/telegram_service/handlers/approval/handler_add_approver.go new file mode 100644 index 0000000..4800c9b --- /dev/null +++ b/service/telegram_service/handlers/approval/handler_add_approver.go @@ -0,0 +1,531 @@ +package approval + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/core/utilscore" + "bitrix_balancer_api/telegram_service/keyboard" + "bitrix_balancer_api/telegram_service/state" + "context" + "fmt" + + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" + "github.com/sirupsen/logrus" +) + +// HandleAddApproverFromApproval — добавление согласующего к конкретной заявке (прямой вход) +func (h *Handler) HandleAddApproverFromApproval(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, approvalID uint64) { + ctx := context.Background() + + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || user == nil || user.ID == nil { + sendText(bot, chatID, "⚠️ Пользователь не найден.") + return + } + isApprover, _ := h.ipc.Database.User.IsApproverDB(ctx, *user.ID) + isDirector, _ := h.ipc.Database.User.IsDirectorDB(ctx, *user.ID) + if !isApprover && !isDirector { + sendText(bot, chatID, "У вас нет прав для добавления согласующих.") + return + } + + approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID) + if err != nil || approval == nil { + sendText(bot, chatID, "⚠️ Заявка не найдена.") + return + } + + users, _, err := h.ipc.Database.User.GetUsersListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.User{IsBlocked: utilscore.PointerToBool(false)}, + }) + if err != nil { + logrus.Errorf("HandleAddApproverFromApproval: GetUsersListDB err=%v", err) + sendText(bot, chatID, "Ошибка при получении списка пользователей.") + return + } + + // Исключаем текущего и уже добавленных + alreadyAdded, _, _ := h.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalAdditionalApprover{ApprovalID: &approvalID}, + }) + addedIDs := make(map[uint64]bool) + for _, aa := range alreadyAdded { + if aa.ApproverID != nil { + addedIDs[*aa.ApproverID] = true + } + } + + var availableUsers []*typescore.User + for _, u := range users { + if u.ID != nil && *u.ID != *user.ID && !addedIDs[*u.ID] && u.TelegramID != nil { + availableUsers = append(availableUsers, u) + } + } + + if len(availableUsers) == 0 { + sendText(bot, chatID, "Нет доступных пользователей для добавления.") + return + } + + h.States.SetAddApprover(ctx, telegramID, &state.AddApproverFlowState{ + ApprovalID: approvalID, + CategoryID: 0, // не нужно, т.к. заявка уже известна + Stage: "select_user", + }) //nolint:errcheck + + topicName := "—" + if approval.TopicID != nil { + topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID) + if topic != nil && topic.Name != nil { + topicName = *topic.Name + } + } + + msg := tgbotapi.NewMessage(chatID, fmt.Sprintf( + "➕ Добавить согласующего к заявке #%d\n\n📋 Тема: %s\n\n👇 Выберите пользователя:", + approvalID, topicName, + )) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildAddApproverUserMenu(availableUsers, approvalID, 0, 0) // page=0, categoryID=0 + bot.Send(msg) //nolint:errcheck +} + +func (h *Handler) HandleAddApproverMainMenu(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) { + ctx := context.Background() + + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || user == nil || user.ID == nil { + return + } + + isApprover, _ := h.ipc.Database.User.IsApproverDB(ctx, *user.ID) + if !isApprover { + sendText(bot, chatID, "У вас нет прав согласующего.") + return + } + + msg := tgbotapi.NewMessage(chatID, "➕ Добавить согласующего\n\nВыберите действие:") + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildAddApproverMainMenu() + bot.Send(msg) //nolint:errcheck +} + +func (h *Handler) HandleAddApproverCategoryMenu(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) { + h.HandleAddApproverCategoryMenuPage(bot, chatID, telegramID, 0, 0) +} + +func (h *Handler) HandleAddApproverCategoryMenuPage(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, page int, prevMessageID int) { + ctx := context.Background() + + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || user == nil || user.ID == nil { + return + } + + categories, err := h.getApproverCategoriesWithPendingApprovals(ctx, *user.ID) + if err != nil { + logrus.Errorf("HandleAddApproverCategoryMenu: err=%v", err) + sendText(bot, chatID, "Ошибка при получении списка категорий.") + return + } + + if len(categories) == 0 { + sendText(bot, chatID, "Нет категорий с активными согласованиями, где вы являетесь согласующим.") + return + } + + if prevMessageID != 0 { + bot.Request(tgbotapi.NewDeleteMessage(chatID, prevMessageID)) //nolint:errcheck + } + + msg := tgbotapi.NewMessage(chatID, "➕ Добавить согласующего\n\nВыберите категорию:") + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildAddApproverCategoryMenu(categories, page) + bot.Send(msg) //nolint:errcheck +} + +func (h *Handler) HandleAddApproverCategoryCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, categoryID uint64) { + h.HandleAddApproverCategoryCallbackPage(bot, cq, categoryID, 0) +} + +func (h *Handler) HandleAddApproverCategoryCallbackPage(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, categoryID uint64, page int) { + ctx := context.Background() + chatID := cq.Message.Chat.ID + telegramID := cq.From.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck + + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || user == nil || user.ID == nil { + return + } + + approvals, err := h.getPendingApprovalsByCategory(ctx, *user.ID, categoryID) + if err != nil { + logrus.Errorf("HandleAddApproverCategoryCallback: err=%v", err) + sendText(bot, chatID, "Ошибка при получении списка согласований.") + return + } + + if len(approvals) == 0 { + sendText(bot, chatID, "Нет активных согласований в этой категории.") + return + } + + category, _ := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, categoryID) + categoryName := "—" + if category != nil && category.Name != nil { + categoryName = *category.Name + } + + h.States.SetAddApprover(ctx, telegramID, &state.AddApproverFlowState{ + CategoryID: categoryID, + Stage: "select_approval", + }) //nolint:errcheck + + msg := tgbotapi.NewMessage(chatID, fmt.Sprintf("📋 Категория: %s\n\nВыберите согласование:", categoryName)) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildAddApproverApprovalMenu(approvals, categoryID, page, ctx, h.ipc) + bot.Send(msg) //nolint:errcheck +} + +func (h *Handler) HandleAddApproverApprovalCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64) { + h.HandleAddApproverApprovalCallbackPage(bot, cq, approvalID, 0) +} + +func (h *Handler) HandleAddApproverApprovalCallbackPage(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64, page int) { + ctx := context.Background() + chatID := cq.Message.Chat.ID + telegramID := cq.From.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck + + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || user == nil || user.ID == nil { + return + } + + approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID) + if err != nil || approval == nil { + sendText(bot, chatID, "⚠️ Согласование не найдено.") + return + } + + users, _, err := h.ipc.Database.User.GetUsersListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.User{ + IsBlocked: utilscore.PointerToBool(false), + }, + }) + if err != nil { + logrus.Errorf("HandleAddApproverApprovalCallback: GetUsersListDB err=%v", err) + return + } + + // Исключаем текущего пользователя и уже добавленных + alreadyAdded, _, _ := h.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalAdditionalApprover{ + ApprovalID: &approvalID, + }, + }) + addedIDs := make(map[uint64]bool) + for _, aa := range alreadyAdded { + if aa.ApproverID != nil { + addedIDs[*aa.ApproverID] = true + } + } + + var availableUsers []*typescore.User + for _, u := range users { + if u.ID != nil && *u.ID != *user.ID && !addedIDs[*u.ID] { + availableUsers = append(availableUsers, u) + } + } + + if len(availableUsers) == 0 { + sendText(bot, chatID, "Нет доступных пользователей для добавления.") + return + } + + addApproverState, _ := h.States.GetAddApprover(ctx, telegramID) + if addApproverState == nil { + addApproverState = &state.AddApproverFlowState{} + } + addApproverState.ApprovalID = approvalID + addApproverState.Stage = "select_user" + h.States.SetAddApprover(ctx, telegramID, addApproverState) //nolint:errcheck + + topicName := "—" + if approval.TopicID != nil { + topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID) + if topic != nil && topic.Name != nil { + topicName = *topic.Name + } + } + + msg := tgbotapi.NewMessage(chatID, fmt.Sprintf("📋 Заявка #%d — %s\n\nВыберите пользователя:", approvalID, topicName)) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildAddApproverUserMenu(availableUsers, approvalID, addApproverState.CategoryID, page) + bot.Send(msg) //nolint:errcheck +} + +func (h *Handler) HandleAddApproverUserCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approverID uint64) { + ctx := context.Background() + chatID := cq.Message.Chat.ID + telegramID := cq.From.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck + + addApproverState, err := h.States.GetAddApprover(ctx, telegramID) + if err != nil || addApproverState == nil { + sendText(bot, chatID, "⚠️ Состояние утеряно. Начните заново.") + return + } + + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || user == nil || user.ID == nil { + return + } + + status := typescore.ApprovalStatusPending.String() + additionalApprover := &typescore.ApprovalAdditionalApprover{ + ApprovalID: &addApproverState.ApprovalID, + ApproverID: &approverID, + AddedByID: user.ID, + Status: &status, + } + + _, _, err = h.ipc.Database.ApprovalAdditionalApprover.CreateApprovalAdditionalApproverDB(ctx, nil, additionalApprover) + if err != nil { + logrus.Errorf("HandleAddApproverUserCallback: CreateApprovalAdditionalApproverDB err=%v", err) + sendText(bot, chatID, "Ошибка при добавлении согласующего.") + return + } + + h.States.ClearAddApprover(ctx, telegramID) //nolint:errcheck + + approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, addApproverState.ApprovalID) + if err != nil || approval == nil { + logrus.Errorf("HandleAddApproverUserCallback: GetApprovalByIDDB err=%v", err) + sendText(bot, chatID, "Ошибка. Сообщите в технический отдел.") + return + } + topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID) + + addedApprover, _ := h.ipc.Database.User.GetUserByIDDB(ctx, approverID) + approverName := "—" + if addedApprover != nil && addedApprover.FullName != nil { + approverName = *addedApprover.FullName + } + + sendText(bot, chatID, fmt.Sprintf( + "✅ Согласующий добавлен\n\n"+ + "📋 Заявка: #%d — %s\n"+ + "👤 Согласующий: %s", + addApproverState.ApprovalID, topicFullName, approverName, + )) + + // Уведомляем добавленного согласующего + if addedApprover != nil && addedApprover.TelegramID != nil { + initiatorName := "—" + if approval.InitiatorID != nil { + initiator, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID) + if initiator != nil && initiator.FullName != nil { + initiatorName = *initiator.FullName + } + } + + content := "—" + if approval.Content != nil { + content = *approval.Content + } + + status := "" + if approval.Status != nil { + status = *approval.Status + } + + files, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID) + notifyMsg := tgbotapi.NewMessage(*addedApprover.TelegramID, fmt.Sprintf( + "➕ Вас добавили к согласованию заявки #%d\n\n"+ + "👤 Инициатор: %s\n"+ + "📋 Тема: %s\n"+ + "📝 Текст: %s", + addApproverState.ApprovalID, initiatorName, topicFullName, content, + )) + notifyMsg.ParseMode = "HTML" + notifyMsg.ReplyMarkup = keyboard.BuildApproverDecision(addApproverState.ApprovalID, status, len(files) > 0, len(files)) + bot.Send(notifyMsg) //nolint:errcheck + } +} + +func (h *Handler) HandleAddedApproversList(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) { + h.HandleAddedApproversListPage(bot, chatID, telegramID, 0, 0) +} + +func (h *Handler) HandleAddedApproversListPage(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, page int, prevMessageID int) { + ctx := context.Background() + + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || user == nil || user.ID == nil { + return + } + + addedApprovers, _, err := h.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalAdditionalApprover{ + AddedByID: user.ID, + }, + }) + if err != nil { + logrus.Errorf("HandleAddedApproversList: err=%v", err) + sendText(bot, chatID, "Ошибка при получении списка.") + return + } + + if len(addedApprovers) == 0 { + sendText(bot, chatID, "Вы еще не добавляли согласующих.") + return + } + + if prevMessageID != 0 { + bot.Request(tgbotapi.NewDeleteMessage(chatID, prevMessageID)) //nolint:errcheck + } + + msg := tgbotapi.NewMessage(chatID, fmt.Sprintf("📋 Ранее добавленные (%d)\n\nВыберите запись:", len(addedApprovers))) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildAddedApproversList(addedApprovers, page, ctx, h.ipc) + bot.Send(msg) //nolint:errcheck +} + +func (h *Handler) HandleAddedApproverDetail(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, additionalApproverID uint64) { + ctx := context.Background() + chatID := cq.Message.Chat.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck + + addedApprover, err := h.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproverByIDDB(ctx, additionalApproverID) + if err != nil || addedApprover == nil { + sendText(bot, chatID, "⚠️ Запись не найдена.") + return + } + + approverName := "—" + if addedApprover.ApproverID != nil { + approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *addedApprover.ApproverID) + if approver != nil && approver.FullName != nil { + approverName = *approver.FullName + } + } + + approvalInfo := "—" + if addedApprover.ApprovalID != nil { + approval, _ := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, *addedApprover.ApprovalID) + if approval != nil && approval.TopicID != nil { + topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID) + topicName := "—" + if topic != nil && topic.Name != nil { + topicName = *topic.Name + } + approvalInfo = fmt.Sprintf("#%d — %s", *addedApprover.ApprovalID, topicName) + } + } + + statusText := "⏳ Ожидает" + if addedApprover.Status != nil { + switch *addedApprover.Status { + case typescore.ApprovalStatusApproved.String(): + statusText = "✅ Одобрено" + case typescore.ApprovalStatusRejected.String(): + statusText = "❌ Отклонено" + } + } + + text := fmt.Sprintf( + "📋 Добавленный согласующий\n\n"+ + "👤 Пользователь: %s\n"+ + "📄 Заявка: %s\n"+ + "📊 Статус: %s", + approverName, approvalInfo, statusText, + ) + + if addedApprover.Comment != nil && *addedApprover.Comment != "" { + text += fmt.Sprintf("\n💬 Комментарий: %s", *addedApprover.Comment) + } + + msg := tgbotapi.NewMessage(chatID, text) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildAddedApproverDetail() + bot.Send(msg) //nolint:errcheck +} + +func (h *Handler) getApproverCategoriesWithPendingApprovals(ctx context.Context, userID uint64) ([]*typescore.ApprovalTopicCategory, error) { + hierarchies, _, err := h.ipc.Database.UserHierarchy.GetUserHierarchyListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.UserHierarchy{ + ApproverID: &userID, + }, + }) + if err != nil { + return nil, err + } + + categoryIDs := make(map[uint64]bool) + for _, hier := range hierarchies { + if hier.TopicID != nil { + topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *hier.TopicID) + if topic != nil && topic.CategoryID != nil { + // Проверяем, есть ли pending заявки + steps, _, _ := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalStep{ + ApproverID: &userID, + Status: utilscore.PointerToString(typescore.ApprovalStatusPending.String()), + }, + }) + if len(steps) > 0 { + categoryIDs[*topic.CategoryID] = true + } + } + } + } + + var categories []*typescore.ApprovalTopicCategory + for categoryID := range categoryIDs { + category, err := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, categoryID) + if err == nil && category != nil { + categories = append(categories, category) + } + } + + return categories, nil +} + +func (h *Handler) getPendingApprovalsByCategory(ctx context.Context, userID, categoryID uint64) ([]*typescore.Approval, error) { + steps, _, err := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalStep{ + ApproverID: &userID, + Status: utilscore.PointerToString(typescore.ApprovalStatusPending.String()), + }, + }) + if err != nil { + return nil, err + } + + var approvals []*typescore.Approval + for _, step := range steps { + if step.ApprovalID == nil { + continue + } + approval, _ := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, *step.ApprovalID) + if approval == nil || approval.TopicID == nil { + continue + } + topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID) + if topic == nil || topic.CategoryID == nil || *topic.CategoryID != categoryID { + continue + } + approvals = append(approvals, approval) + } + + return approvals, nil +} diff --git a/service/telegram_service/handlers/approval/handler_comment.go b/service/telegram_service/handlers/approval/handler_comment.go new file mode 100644 index 0000000..b6d3dc6 --- /dev/null +++ b/service/telegram_service/handlers/approval/handler_comment.go @@ -0,0 +1,397 @@ +package approval + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/telegram_service/keyboard" + "bitrix_balancer_api/telegram_service/state" + "context" + "fmt" + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" + "github.com/sirupsen/logrus" +) + +func (h *Handler) HandleAddCommentCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64) { + ctx := context.Background() + chatID := cq.Message.Chat.ID + telegramID := cq.From.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil { + logrus.Errorf("HandleAddCommentCallback: GetUserByTelegramIDDB err=%v", err) + sendText(bot, chatID, "⚠️ Ошибка при получении данных пользователя.") + return + } + + if user == nil || user.ID == nil { + logrus.Warn("HandleAddCommentCallback: user or user.ID is nil") + sendText(bot, chatID, "⚠️ Пользователь не найден.") + return + } + + approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID) + if err != nil { + logrus.Errorf("HandleAddCommentCallback: GetApprovalByIDDB err=%v", err) + sendText(bot, chatID, "⚠️ Ошибка при получении заявки.") + return + } + + if approval == nil { + logrus.Warnf("HandleAddCommentCallback: approval not found approvalID=%d", approvalID) + sendText(bot, chatID, "⚠️ Заявка не найдена.") + return + } + + // Проверяем, может ли пользователь комментировать эту заявку + canComment, err := h.canUserCommentApproval(ctx, *user.ID, approval) + if err != nil { + logrus.Errorf("HandleAddCommentCallback: canUserCommentApproval err=%v", err) + sendText(bot, chatID, "Ошибка при проверке прав.") + return + } + + if !canComment { + sendText(bot, chatID, "⚠️ Вы не можете комментировать эту заявку в текущем статусе.") + return + } + + // Сохраняем состояние ожидания комментария + commentState := &state.CommentFlowState{ + ApprovalID: approvalID, + Stage: "await_text", + } + + if err := h.States.SetCommentFlow(ctx, telegramID, commentState); err != nil { + logrus.Errorf("HandleAddCommentCallback: SetCommentFlow err=%v", err) + sendText(bot, chatID, "Ошибка при сохранении состояния.") + return + } + + sendText(bot, chatID, "💬 Введите текст комментария:") +} + +func (h *Handler) canUserCommentApproval(ctx context.Context, userID uint64, approval *typescore.Approval) (bool, error) { + if approval == nil || approval.ID == nil { + return false, fmt.Errorf("approval or approval ID is nil") + } + + if approval.InitiatorID != nil && *approval.InitiatorID == userID { + return true, nil + } + + // Проверяем, является ли пользователь текущим согласующим + activeStep, err := h.ipc.Database.ApprovalStep.GetActiveStepDB(ctx, *approval.ID) + if err == nil && activeStep != nil && activeStep.ApproverID != nil && *activeStep.ApproverID == userID { + return true, nil + } + + // Проверяем, является ли пользователь дополнительным согласующим с pending статусом + additionalApprovers, _, err := h.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalAdditionalApprover{ + ApprovalID: approval.ID, + }, + }) + if err == nil && additionalApprovers != nil { + for _, aa := range additionalApprovers { + if aa.ApproverID != nil && *aa.ApproverID == userID { + if aa.Status != nil && *aa.Status == "pending" { + return true, nil + } + } + } + } + + // Проверяем, является ли пользователь наблюдателем этой категории + if approval.TopicID != nil { + topic, err := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID) + if err == nil && topic != nil && topic.Code != nil { + isObserver, _ := h.ipc.Database.User.IsObserverDB(ctx, userID) + if isObserver { + // Проверяем права наблюдателя на эту категорию + observers, _ := h.ipc.Database.User.GetObserversForCategoryDB(ctx, *topic.Code) + if observers != nil { + for _, obs := range observers { + if obs.ID != nil && *obs.ID == userID { + return true, nil + } + } + } + } + } + } + + // Проверяем, является ли пользователь исполнителем задачи по этой заявке + task, err := h.ipc.Database.ApprovalTasks.GetApprovalTaskByApprovalIDDB(ctx, *approval.ID) + if err == nil && task != nil && task.ExecutorID != nil && *task.ExecutorID == userID { + if task.Status != nil && *task.Status == "pending" { + return true, nil + } + } + + isDirector, _ := h.ipc.Database.User.IsDirectorDB(ctx, userID) + return isDirector, nil +} + +func (h *Handler) formatCommentsSection(ctx context.Context, approvalID uint64) string { + comments, err := h.ipc.Database.ApprovalComment.GetCommentsByApprovalIDDB(ctx, approvalID) + if err != nil { + logrus.Errorf("formatCommentsSection: GetCommentsByApprovalIDDB err=%v", err) + return "" + } + + if len(comments) == 0 { + return "" + } + + result := "\n\n💬 Комментарии:" + + for _, comment := range comments { + if comment == nil { + continue + } + + if comment.UserID == nil || comment.Comment == nil { + logrus.Warnf("formatCommentsSection: comment UserID or Comment is nil, commentID=%v", comment.ID) + continue + } + + user, err := h.ipc.Database.User.GetUserByIDDB(ctx, *comment.UserID) + if err != nil { + logrus.Errorf("formatCommentsSection: GetUserByIDDB err=%v", err) + continue + } + + if user == nil { + logrus.Warnf("formatCommentsSection: user is nil for userID=%d", *comment.UserID) + continue + } + + userName := "—" + if user.FullName != nil { + userName = *user.FullName + } + + timestamp := "" + if comment.CreatedAt != nil { + timestamp = comment.CreatedAt.Format("02.01.2006 15:04") + } + + result += fmt.Sprintf("\n\n%s (%s):\n%s", userName, timestamp, *comment.Comment) + } + + return result +} + +func (h *Handler) HandleCommentReplyCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64) { + ctx := context.Background() + chatID := cq.Message.Chat.ID + telegramID := cq.From.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + + replyState := &state.CommentReplyState{ + ApprovalID: approvalID, + Stage: "await_text", + } + h.States.SetCommentReply(ctx, telegramID, replyState) //nolint:errcheck + + sendText(bot, chatID, "↩️ Введите текст ответа:") +} + +func (h *Handler) HandleCommentTextInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) bool { + ctx := context.Background() + telegramID := msg.From.ID + chatID := msg.Chat.ID + + commentState, err := h.States.GetCommentFlow(ctx, telegramID) + if err != nil || commentState == nil || commentState.Stage != "await_text" { + return false + } + + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || user == nil || user.ID == nil { + return false + } + + approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, commentState.ApprovalID) + if err != nil || approval == nil { + sendText(bot, chatID, "⚠️ Заявка не найдена.") + h.States.ClearCommentFlow(ctx, telegramID) //nolint:errcheck + return true + } + + comment := &typescore.ApprovalComment{ + ApprovalID: &commentState.ApprovalID, + UserID: user.ID, + Comment: &msg.Text, + } + + _, _, err = h.ipc.Database.ApprovalComment.CreateApprovalCommentDB(ctx, nil, comment) + if err != nil { + logrus.Errorf("HandleCommentTextInput: CreateApprovalCommentDB err=%v", err) + sendText(bot, chatID, "Ошибка при сохранении комментария.") + h.States.ClearCommentFlow(ctx, telegramID) //nolint:errcheck + return true + } + + h.States.ClearCommentFlow(ctx, telegramID) //nolint:errcheck + + userName := "—" + if user.FullName != nil { + userName = *user.FullName + } + + sendText(bot, chatID, fmt.Sprintf( + "✅ Комментарий добавлен\n\n"+ + "📋 Заявка: #%d\n"+ + "👤 Автор: %s\n"+ + "💬 Текст: %s", + commentState.ApprovalID, userName, msg.Text, + )) + + h.notifyAllParticipantsAboutComment(bot, ctx, approval, user, comment, telegramID) + + return true +} + +func (h *Handler) notifyAllParticipantsAboutComment( + bot *tgbotapi.BotAPI, + ctx context.Context, + approval *typescore.Approval, + commenter *typescore.User, + comment *typescore.ApprovalComment, + skipTelegramID int64, +) { + if approval == nil || approval.ID == nil { + return + } + + commenterName := "—" + if commenter != nil && commenter.FullName != nil { + commenterName = *commenter.FullName + } + + topicName := h.getTopicNameByApproval(ctx, approval) + content := "—" + if approval.Content != nil { + content = *approval.Content + } + + text := fmt.Sprintf( + "💬 Новый комментарий к заявке #%d\n\n"+ + "📋 Тема: %s\n"+ + "📝 Текст заявки: %s\n\n"+ + "👤 Автор комментария: %s\n"+ + "💬 Комментарий:\n%s", + *approval.ID, topicName, content, commenterName, *comment.Comment, + ) + + // 🚀 Определяем, является ли статус финальным + isFinalStatus := approval.Status != nil && + (*approval.Status == "approved" || *approval.Status == "rejected" || *approval.Status == "revoked") + + recipients := make(map[int64]bool) + + // Инициатор — всегда получает уведомления о комментариях + if approval.InitiatorID != nil { + initiator, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID) + if initiator != nil && initiator.TelegramID != nil && *initiator.TelegramID != skipTelegramID { + recipients[*initiator.TelegramID] = true + } + } + + // Текущий согласующий — всегда получает + activeStep, _ := h.ipc.Database.ApprovalStep.GetActiveStepDB(ctx, *approval.ID) + if activeStep != nil && activeStep.ApproverID != nil { + approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *activeStep.ApproverID) + if approver != nil && approver.TelegramID != nil && *approver.TelegramID != skipTelegramID { + recipients[*approver.TelegramID] = true + } + } + + // Дополнительные согласующие — всегда получают + additionalApprovers, _, _ := h.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalAdditionalApprover{ + ApprovalID: approval.ID, + }, + }) + for _, aa := range additionalApprovers { + if aa.ApproverID != nil { + addApprover, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *aa.ApproverID) + if addApprover != nil && addApprover.TelegramID != nil && *addApprover.TelegramID != skipTelegramID { + recipients[*addApprover.TelegramID] = true + } + } + } + + if isFinalStatus && approval.TopicID != nil { + categoryCode := h.getTopicCodeByApproval(ctx, approval) + if categoryCode != "" { + observers, _ := h.ipc.Database.User.GetObserversForCategoryDB(ctx, categoryCode) + for _, obs := range observers { + if obs.TelegramID != nil && *obs.TelegramID != skipTelegramID { + recipients[*obs.TelegramID] = true + } + } + } + } + + if isFinalStatus { + directors, _ := h.ipc.Database.User.GetDirectorsDB(ctx) + for _, dir := range directors { + if dir.TelegramID != nil && *dir.TelegramID != skipTelegramID { + recipients[*dir.TelegramID] = true + } + } + } + + for telegramID := range recipients { + msg := tgbotapi.NewMessage(telegramID, text) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildCommentReplyKeyboard(*approval.ID) + if _, err := bot.Send(msg); err != nil { + logrus.Errorf("notifyAllParticipantsAboutComment: Send to %d err=%v", telegramID, err) + } + } +} + +func (h *Handler) HandleCommentReplyInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) bool { + ctx := context.Background() + telegramID := msg.From.ID + chatID := msg.Chat.ID + + replyState, err := h.States.GetCommentReply(ctx, telegramID) + if err != nil || replyState == nil || replyState.Stage != "await_text" { + return false + } + + h.States.ClearCommentReply(ctx, telegramID) //nolint:errcheck + + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || user == nil || user.ID == nil { + return false + } + + approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, replyState.ApprovalID) + if err != nil || approval == nil { + sendText(bot, chatID, "⚠️ Заявка не найдена.") + return true + } + + comment := &typescore.ApprovalComment{ + ApprovalID: &replyState.ApprovalID, + UserID: user.ID, + Comment: &msg.Text, + } + created, _, err := h.ipc.Database.ApprovalComment.CreateApprovalCommentDB(ctx, nil, comment, true) //nolint:errcheck + if err != nil { + sendText(bot, chatID, "⚠️ Ошибка при создании комментария: "+err.Error()) + return false + } + sendText(bot, chatID, "✅ Ответ отправлен.") + + h.notifyAllParticipantsAboutComment(bot, ctx, approval, user, created, telegramID) + + return true +} diff --git a/service/telegram_service/handlers/approval/handler_decision.go b/service/telegram_service/handlers/approval/handler_decision.go new file mode 100644 index 0000000..b1606f0 --- /dev/null +++ b/service/telegram_service/handlers/approval/handler_decision.go @@ -0,0 +1,806 @@ +package approval + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/core/utilscore" + "bitrix_balancer_api/telegram_service/keyboard" + "context" + "fmt" + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" + "github.com/sirupsen/logrus" + "strings" + "time" +) + +// HandleDecision — вызывается при нажатии inline-кнопки. +func (h *Handler) HandleDecision( + bot *tgbotapi.BotAPI, + cq *tgbotapi.CallbackQuery, + approvalID uint64, + approved bool, + comment string, +) { + var approverChatID int64 + if cq != nil { + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + approverChatID = cq.Message.Chat.ID + } + var telegramID int64 + if cq != nil { + telegramID = cq.From.ID + } + h.handleDecision(bot, cq, approverChatID, telegramID, approvalID, approved, comment) +} + +func (h *Handler) processNextStepOrComplete(bot *tgbotapi.BotAPI, ctx context.Context, approval *typescore.Approval, currentStep *typescore.ApprovalStep, approvalCard string, categoryCode string, notifier *Notifier, initiator *typescore.User, collected map[string]string, actualExecutorID uint64) { + approvalID := *approval.ID + + nextStep, err := h.ipc.Database.ApprovalStep.GetNextStepDB(ctx, approvalID, *currentStep.StepOrder) + if err == nil && nextStep != nil && nextStep.ApproverID != nil { + pendingStatus := "pending" + nextStep.Status = &pendingStatus + h.ipc.Database.ApprovalStep.UpdateApprovalStepDB(ctx, nil, nextStep) //nolint:errcheck + + nextApprover, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *nextStep.ApproverID) + + actualApprover := nextApprover + originalApproverID := *nextStep.ApproverID + if approval.TopicID != nil { + topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID) + if topic != nil && topic.CategoryID != nil { + if delegations, _, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalDelegation{ + IsActive: utilscore.PointerToBool(true), + TopicID: approval.TopicID, + }, + }); err == nil { + for _, deleg := range delegations { + if deleg.DelegatorID != nil && *deleg.DelegatorID == originalApproverID && deleg.DelegateID != nil { + delegate, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *deleg.DelegateID) + if delegate != nil && delegate.TelegramID != nil { + actualApprover = delegate + break + } + } + } + } + if actualApprover == nextApprover { + if delegations, _, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalDelegation{ + IsActive: utilscore.PointerToBool(true), + CategoryID: topic.CategoryID, + }, + }); err == nil { + for _, deleg := range delegations { + if deleg.DelegatorID != nil && *deleg.DelegatorID == originalApproverID && deleg.DelegateID != nil { + delegate, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *deleg.DelegateID) + if delegate != nil && delegate.TelegramID != nil { + actualApprover = delegate + break + } + } + } + } + } + } + } + + // Уведомляем инициатора о прогрессе + if initiator.TelegramID != nil { + currentApproverName := "—" + if currentStep.ApproverNameSnapshot != nil { + currentApproverName = *currentStep.ApproverNameSnapshot + } + + nextApproverName := "—" + if actualApprover != nil && actualApprover.FullName != nil { + nextApproverName = *actualApprover.FullName + } + + topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID) + + content := "—" + if approval.Content != nil { + content = *approval.Content + } + + progressText := fmt.Sprintf( + "⏩ Заявка #%d: на согласовании\n\n"+ + "✅ Согласовал: %s\n"+ + "⏳ Передано: %s\n\n"+ + "📋 Тема: %s\n"+ + "📝 Текст: %s", + approvalID, currentApproverName, nextApproverName, topicFullName, content, + ) + + progressMsg := tgbotapi.NewMessage(*initiator.TelegramID, progressText) + progressMsg.ParseMode = "HTML" + progressMsg.ReplyMarkup = keyboard.BuildApprovalStagesButton(approvalID) + bot.Send(progressMsg) //nolint:errcheck + } + + currentStepIsDelegate := currentStep.ApproverID != nil && *currentStep.ApproverID != actualExecutorID + + if currentStep.ApproverID != nil { + mainApprover, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *currentStep.ApproverID) + if mainApprover != nil && mainApprover.TelegramID != nil { + nextName := "следующему согласующему" + if actualApprover != nil && actualApprover.FullName != nil { + nextName = *actualApprover.FullName + } + + messageText := "" + if currentStepIsDelegate { + executor, _ := h.ipc.Database.User.GetUserByIDDB(ctx, actualExecutorID) + executorName := "—" + if executor != nil && executor.FullName != nil { + executorName = *executor.FullName + } + messageText = fmt.Sprintf( + "➡️ Ваш делегат согласовал заявку #%d и передал: %s\n\n"+ + "👤 Делегат: %s\n"+ + "%s", + approvalID, nextName, executorName, approvalCard, + ) + } else { + messageText = fmt.Sprintf( + "➡️ Заявка #%d передана: %s\n\n%s", + approvalID, nextName, approvalCard, + ) + } + + notifyMsg := tgbotapi.NewMessage(*mainApprover.TelegramID, messageText) + notifyMsg.ParseMode = "HTML" + bot.Send(notifyMsg) //nolint:errcheck + } + } + + if actualApprover != nil && actualApprover.TelegramID != nil { + notifier.NotifyApprover(bot, actualApprover, initiator, approval, collected) + } + + if actualApprover != nextApprover && nextApprover != nil && nextApprover.TelegramID != nil { + delegateName := "—" + if actualApprover != nil && actualApprover.FullName != nil { + delegateName = *actualApprover.FullName + } + notifyOwner := tgbotapi.NewMessage(*nextApprover.TelegramID, fmt.Sprintf( + "ℹ️ Новая заявка #%d передана делегату\n\n"+ + "👤 Делегат: %s\n"+ + "%s", + approvalID, delegateName, approvalCard, + )) + notifyOwner.ParseMode = "HTML" + bot.Send(notifyOwner) //nolint:errcheck + } + return + } + + approvedStatus := "approved" + approval.Status = &approvedStatus + h.ipc.Database.Approval.UpdateApprovalDB(ctx, nil, approval) //nolint:errcheck + + lastStepIsDelegate := currentStep.ApproverID != nil && *currentStep.ApproverID != actualExecutorID + + if currentStep.ApproverID != nil { + mainApprover, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *currentStep.ApproverID) + if mainApprover != nil && mainApprover.TelegramID != nil { + messageText := "" + if lastStepIsDelegate { + executor, _ := h.ipc.Database.User.GetUserByIDDB(ctx, actualExecutorID) + executorName := "—" + if executor != nil && executor.FullName != nil { + executorName = *executor.FullName + } + messageText = fmt.Sprintf( + "🎉 Ваш делегат полностью согласовал заявку #%d\n\n"+ + "👤 Делегат: %s\n"+ + "%s\n\nИнициатор уведомлён.", + approvalID, executorName, approvalCard, + ) + } + + notifyMsg := tgbotapi.NewMessage(*mainApprover.TelegramID, messageText) + notifyMsg.ParseMode = "HTML" + bot.Send(notifyMsg) //nolint:errcheck + } + } + + h.createTasksForApproval(bot, ctx, approval, initiator) + + if initiator.TelegramID != nil { + lastApprover, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *currentStep.ApproverID) + notifier.NotifyInitiatorApproved(bot, initiator, approval, collected, lastApprover) + } + + if approval.TopicID != nil && currentStep.ApproverID != nil { + if delegations, _, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalDelegation{ + IsActive: utilscore.PointerToBool(true), + TopicID: approval.TopicID, + }, + }); err == nil { + for _, deleg := range delegations { + if deleg.DelegatorID != nil && deleg.DelegateID != nil && *deleg.DelegateID == *currentStep.ApproverID { + delegator, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *deleg.DelegatorID) + if delegator != nil && delegator.TelegramID != nil { + lastApprover, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *currentStep.ApproverID) + delegateName := "—" + if lastApprover != nil && lastApprover.FullName != nil { + delegateName = *lastApprover.FullName + } + notifyOwner := tgbotapi.NewMessage(*delegator.TelegramID, fmt.Sprintf( + "✅ Заявка #%d согласована вашим делегатом\n\n"+ + "👤 Делегат: %s\n"+ + "%s", + approvalID, delegateName, approvalCard, + )) + notifyOwner.ParseMode = "HTML" + bot.Send(notifyOwner) //nolint:errcheck + } + } + } + } + } + + directors, _ := h.ipc.Database.User.GetDirectorsDB(ctx) + for _, director := range directors { + if director.TelegramID != nil { + notifier.NotifyDirector(bot, director, initiator, approval, collected) + } + } + + if observers, err := h.ipc.Database.User.GetObserversForCategoryDB(ctx, categoryCode); err == nil && len(observers) > 0 { + stepApprover, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *currentStep.ApproverID) + notifier.NotifyObserversDecision(bot, observers, initiator, stepApprover, approval, collected) + } +} + +// HandleDecisionWithChat — вызывается при текстовом вводе комментария. +// chatID — чат согласующего для отправки обратной связи. +func (h *Handler) HandleDecisionWithChat( + bot *tgbotapi.BotAPI, + chatID int64, + telegramID int64, + approvalID uint64, + approved bool, + comment string, +) { + h.handleDecision(bot, nil, chatID, telegramID, approvalID, approved, comment) +} + +// handleDecision — основная логика, принимает chatID явно. +func (h *Handler) handleDecision( + bot *tgbotapi.BotAPI, + cq *tgbotapi.CallbackQuery, + approverChatID int64, + telegramID int64, + approvalID uint64, + approved bool, + comment string, +) { + ctx := context.Background() + + if cq != nil { + bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck + } + + user, _ := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if user == nil || user.ID == nil { + return + } + currentUserID := *user.ID + actualExecutor, _ := h.ipc.Database.User.GetUserByIDDB(ctx, currentUserID) + + approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID) + if err != nil || approval == nil { + logrus.Errorf("handleDecision: approval not found id=%d err=%v", approvalID, err) + if approverChatID != 0 { + sendText(bot, approverChatID, "⚠️ Заявка не найдена.") + } + return + } + + if approval.Status != nil && *approval.Status == typescore.ApprovalStatusRevision.String() { + if approverChatID != 0 { + sendText(bot, approverChatID, "⚠️ Заявка находится на доработке у инициатора.") + } + return + } + + approvalTopic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID) + requireComment := approvalTopic != nil && approvalTopic.RequireApproverComment != nil && *approvalTopic.RequireApproverComment + isAnyOf := approvalTopic != nil && approvalTopic.ApprovalMode != nil && *approvalTopic.ApprovalMode == "any_of" + + additionalApprovers, _, _ := h.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalAdditionalApprover{ApprovalID: &approvalID}, + }) + + var isAdditionalApprover bool + var additionalApproverRecord *typescore.ApprovalAdditionalApprover + for _, aa := range additionalApprovers { + if aa.ApproverID != nil && *aa.ApproverID == currentUserID && aa.Status != nil && *aa.Status == "pending" { + isAdditionalApprover = true + additionalApproverRecord = aa + break + } + } + + initiator, err := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID) + if err != nil || initiator == nil { + logrus.Errorf("handleDecision: initiator not found err=%v", err) + return + } + + initiatorName := "—" + if initiator.FullName != nil { + initiatorName = *initiator.FullName + } + topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID) + content := "—" + if approval.Content != nil { + content = *approval.Content + } + + approvalCard := fmt.Sprintf( + "👤 Инициатор: %s\n📋 Тема: %s\n📝 Текст: %s", + initiatorName, topicFullName, content, + ) + + categoryCode := h.getTopicCodeByApproval(ctx, approval) + topic, err := h.Registry.Get(categoryCode) + if err != nil { + logrus.Errorf("handleDecision: topic not found code=%s err=%v", categoryCode, err) + return + } + notifier := NewNotifier(h.ipc, topic) + collected := h.getCollectedFromApproval(ctx, approval) + now := time.Now() + + // 🚀 Вспомогательная функция: сохранить решение/комментарий в общую таблицу комментариев + saveCommentToApproval := func(commentText string) { + if strings.TrimSpace(commentText) == "" || user.ID == nil { + return + } + approvalComment := &typescore.ApprovalComment{ + ApprovalID: &approvalID, + UserID: user.ID, + Comment: &commentText, + } + if _, _, err := h.ipc.Database.ApprovalComment.CreateApprovalCommentDB(ctx, nil, approvalComment); err != nil { + logrus.Errorf("handleDecision: CreateApprovalCommentDB err=%v", err) + } + } + + // 🚀 Вспомогательная функция: проверить, является ли текущий шаг последним + isLastStep := func(currentStepOrder int) bool { + allSteps, _, _ := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalStep{ApprovalID: &approvalID}, + }) + for _, s := range allSteps { + if s.StepOrder == nil { + continue + } + if *s.StepOrder > currentStepOrder { + // Есть следующий шаг — значит текущий не последний + return false + } + } + return true + } + + notifyRejection := func(stepApproverID *uint64) { + if approverChatID != 0 { + commentText := "" + if comment != "" { + commentText = fmt.Sprintf("\n💬 Комментарий: %s", comment) + } + sendText(bot, approverChatID, fmt.Sprintf("❌ Заявка #%d отклонена\n\n%s%s", approvalID, approvalCard, commentText)) + } + if initiator.TelegramID != nil { + var stepApprover *typescore.User + if stepApproverID != nil { + stepApprover, _ = h.ipc.Database.User.GetUserByIDDB(ctx, *stepApproverID) + } else { + stepApprover = actualExecutor + } + notifier.NotifyInitiatorRejected(bot, initiator, stepApprover, approval, collected, comment) + } + if observers, err := h.ipc.Database.User.GetObserversForCategoryDB(ctx, categoryCode); err == nil && len(observers) > 0 { + var stepApprover *typescore.User + if stepApproverID != nil { + stepApprover, _ = h.ipc.Database.User.GetUserByIDDB(ctx, *stepApproverID) + } else { + stepApprover = actualExecutor + } + notifier.NotifyObserversDecision(bot, observers, initiator, stepApprover, approval, collected) + } + } + + // ========================================== + // === БЛОК ОТКЛОНЕНИЯ === + // ========================================== + if !approved { + if isAdditionalApprover { + rejectedStatus := "rejected" + additionalApproverRecord.Status = &rejectedStatus + additionalApproverRecord.Comment = &comment + additionalApproverRecord.ActedAt = &now + h.ipc.Database.ApprovalAdditionalApprover.UpdateApprovalAdditionalApproverDB(ctx, nil, additionalApproverRecord) //nolint:errcheck + + // 🚀 Сохраняем комментарий отклонения в общую таблицу + if comment != "" { + commentText := fmt.Sprintf("❌ Отклонение (доп. согласующий): %s", comment) + saveCommentToApproval(commentText) + } + + approval.Status = &rejectedStatus + h.ipc.Database.Approval.UpdateApprovalDB(ctx, nil, approval) //nolint:errcheck + notifyRejection(nil) + return + } + + step := h.findStepForCurrentApprover(ctx, approvalID, currentUserID, approval, isAnyOf) + if step == nil { + logrus.Warnf("handleDecision: active step not found for user approvalID=%d userID=%d", approvalID, currentUserID) + if approverChatID != 0 { + sendText(bot, approverChatID, "⚠️ Шаг согласования не найден или уже обработан.") + } + return + } + + isDelegate := step.ApproverID != nil && *step.ApproverID != currentUserID + var originalApprover *typescore.User + if isDelegate { + originalApprover, _ = h.ipc.Database.User.GetUserByIDDB(ctx, *step.ApproverID) + } + + rejectedStatus := "rejected" + step.Status = &rejectedStatus + step.Comment = &comment + step.ActedAt = &now + if actualExecutor != nil && actualExecutor.FullName != nil { + step.ApproverNameSnapshot = actualExecutor.FullName + } + h.ipc.Database.ApprovalStep.UpdateApprovalStepDB(ctx, nil, step) //nolint:errcheck + + // 🚀 Сохраняем комментарий отклонения в общую таблицу + if comment != "" { + commentText := fmt.Sprintf("❌ Отклонение: %s", comment) + saveCommentToApproval(commentText) + } + + if isAnyOf { + allSteps, _, _ := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalStep{ApprovalID: &approvalID}, + }) + for _, s := range allSteps { + if s.ID == nil || (step.ID != nil && *s.ID == *step.ID) { + continue + } + if s.Status == nil || (*s.Status != "waiting" && *s.Status != "pending") { + continue + } + cancelledStatus := "cancelled_any_of" + s.Status = &cancelledStatus + h.ipc.Database.ApprovalStep.UpdateApprovalStepDB(ctx, nil, s) //nolint:errcheck + + if s.ApproverID != nil { + approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *s.ApproverID) + if approver != nil && approver.TelegramID != nil { + deciderName := "—" + if actualExecutor != nil && actualExecutor.FullName != nil { + deciderName = *actualExecutor.FullName + } + sendText(bot, *approver.TelegramID, fmt.Sprintf( + "ℹ️ Заявка #%d отклонена\n\n👤 Отклонил: %s\n\nВаше участие в согласовании больше не требуется.", + approvalID, deciderName, + )) + } + } + } + approval.Status = &rejectedStatus + h.ipc.Database.Approval.UpdateApprovalDB(ctx, nil, approval) //nolint:errcheck + notifyRejection(step.ApproverID) + return + } + + approval.Status = &rejectedStatus + h.ipc.Database.Approval.UpdateApprovalDB(ctx, nil, approval) //nolint:errcheck + notifyRejection(step.ApproverID) + + if isDelegate && originalApprover != nil && originalApprover.TelegramID != nil { + executorName := "—" + if actualExecutor != nil && actualExecutor.FullName != nil { + executorName = *actualExecutor.FullName + } + commentText := "" + if comment != "" { + commentText = fmt.Sprintf("\n💬 Комментарий: %s", comment) + } + notifyMsg := tgbotapi.NewMessage(*originalApprover.TelegramID, fmt.Sprintf( + "ℹ️ Ваш делегат отклонил заявку #%d\n\n👤 Делегат: %s\n%s%s", + approvalID, executorName, approvalCard, commentText, + )) + notifyMsg.ParseMode = "HTML" + bot.Send(notifyMsg) //nolint:errcheck + } + return + } + + // ========================================== + // === БЛОК ОДОБРЕНИЯ === + // ========================================== + + // Запрос обязательного комментария для первого шага + if requireComment && comment == "" { + activeStep, _ := h.ipc.Database.ApprovalStep.GetActiveStepDB(ctx, approvalID) + if activeStep != nil && activeStep.StepOrder != nil && *activeStep.StepOrder == 0 { + commentKey := fmt.Sprintf("appr_approve_comment_pending:%d", telegramID) + h.ipc.RedisClient.Set(ctx, commentKey, fmt.Sprintf("%d", approvalID), 10*time.Minute) //nolint:errcheck + + if approverChatID != 0 { + msg := tgbotapi.NewMessage(approverChatID, + "💬 Для согласования этой заявки необходимо оставить комментарий.\n\nВведите комментарий:") + msg.ParseMode = "HTML" + bot.Send(msg) //nolint:errcheck + } + return + } + } + + getPendingAdditionalInfo := func() (int, []string) { + var pendingNames []string + count := 0 + for _, aa := range additionalApprovers { + if isAdditionalApprover && additionalApproverRecord != nil && aa.ID != nil && additionalApproverRecord.ID != nil && *aa.ID == *additionalApproverRecord.ID { + continue + } + if aa.Status != nil && *aa.Status == "pending" && aa.ApproverID != nil { + count++ + approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *aa.ApproverID) + if approver != nil && approver.FullName != nil { + pendingNames = append(pendingNames, *approver.FullName) + } + } + } + return count, pendingNames + } + + // --- Дополнительный согласующий --- + if isAdditionalApprover { + approvedStatus := "approved" + additionalApproverRecord.Status = &approvedStatus + additionalApproverRecord.ActedAt = &now + h.ipc.Database.ApprovalAdditionalApprover.UpdateApprovalAdditionalApproverDB(ctx, nil, additionalApproverRecord) //nolint:errcheck + + // 🚀 Сохраняем одобрение доп. согласующего в комментарии (если есть комментарий) + if comment != "" { + commentText := fmt.Sprintf("✅ Одобрение (доп. согласующий): %s", comment) + saveCommentToApproval(commentText) + } + + mainStep, _ := h.ipc.Database.ApprovalStep.GetActiveStepDB(ctx, approvalID) + + if mainStep != nil && mainStep.ApproverID != nil && *mainStep.ApproverID != currentUserID { + mainApprover, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *mainStep.ApproverID) + if mainApprover != nil && mainApprover.TelegramID != nil { + addApproverName := "—" + if actualExecutor != nil && actualExecutor.FullName != nil { + addApproverName = *actualExecutor.FullName + } + notifyMsg := tgbotapi.NewMessage(*mainApprover.TelegramID, fmt.Sprintf( + "✅ Дополнительный согласующий одобрил заявку #%d\n\n"+ + "👤 Согласующий: %s\n%s", + approvalID, addApproverName, approvalCard, + )) + notifyMsg.ParseMode = "HTML" + bot.Send(notifyMsg) //nolint:errcheck + } + } + + step := h.findStepForCurrentApprover(ctx, approvalID, currentUserID, approval, isAnyOf) + if step == nil { + logrus.Warnf("handleDecision: active step not found for user approvalID=%d userID=%d", approvalID, currentUserID) + if approverChatID != 0 { + sendText(bot, approverChatID, "⚠️ Шаг согласования не найден или уже обработан.") + } + return + } + + allAdditionalApproved := true + for _, aa := range additionalApprovers { + if aa.ID != nil && additionalApproverRecord.ID != nil && *aa.ID == *additionalApproverRecord.ID { + continue + } + if aa.Status == nil || *aa.Status == "pending" { + allAdditionalApproved = false + break + } + if aa.Status != nil && *aa.Status == "rejected" { + allAdditionalApproved = false + break + } + } + + mainApproverApproved := step.Status != nil && *step.Status == "approved" + + if approverChatID != 0 { + pendingCount, pendingNames := getPendingAdditionalInfo() + pendingText := "" + if pendingCount > 0 { + pendingText = fmt.Sprintf("\n\n⏳ Ожидается решение других дополнительных согласующих (%d):\n• %s", + pendingCount, strings.Join(pendingNames, "\n• ")) + } + + if !mainApproverApproved { + sendText(bot, approverChatID, fmt.Sprintf("✅ Вы одобрили заявку #%d\n\n%s\n\nОжидается решение основного согласующего.", approvalID, approvalCard)) + } else if !allAdditionalApproved { + sendText(bot, approverChatID, fmt.Sprintf("✅ Вы одобрили заявку #%d\n\n%s%s", approvalID, approvalCard, pendingText)) + } else { + // 🚀 Все доп. согласующие одобрили, но нужно проверить, последний ли это шаг + var currentOrder int + if step.StepOrder != nil { + currentOrder = *step.StepOrder + } + if isLastStep(currentOrder) { + sendText(bot, approverChatID, fmt.Sprintf("✅ Вы одобрили заявку #%d\n\n%s\n\nВсе согласующие одобрили заявку.", approvalID, approvalCard)) + } else { + sendText(bot, approverChatID, fmt.Sprintf("✅ Вы одобрили заявку #%d\n\n%s\n\nЗаявка передана следующему согласующему.", approvalID, approvalCard)) + } + } + } + + if mainApproverApproved && allAdditionalApproved { + h.processNextStepOrComplete(bot, ctx, approval, step, approvalCard, categoryCode, notifier, initiator, collected, currentUserID) + } + return + } + + // --- Основной согласующий --- + step, err := h.ipc.Database.ApprovalStep.GetActiveStepDB(ctx, approvalID) + if err != nil || step == nil { + logrus.Warnf("handleDecision: active step not found approvalID=%d err=%v", approvalID, err) + if approverChatID != 0 { + sendText(bot, approverChatID, "⚠️ Шаг согласования не найден или уже обработан.") + } + return + } + + isDelegate := step.ApproverID != nil && *step.ApproverID != currentUserID + var originalApprover *typescore.User + if isDelegate { + originalApprover, _ = h.ipc.Database.User.GetUserByIDDB(ctx, *step.ApproverID) + } + + approvedStatus := "approved" + step.Status = &approvedStatus + step.ActedAt = &now + if actualExecutor != nil && actualExecutor.FullName != nil { + step.ApproverNameSnapshot = actualExecutor.FullName + } + + updated, _, err := h.ipc.Database.ApprovalStep.UpdateApprovalStepDB(ctx, nil, step, true) + if err != nil || updated == nil { + if approverChatID != 0 { + sendText(bot, approverChatID, "⚠️ Ошибка при сохранении решения.") + } + return + } + + // 🚀 Сохраняем одобрение/комментарий в общую таблицу комментариев + if comment != "" { + commentText := fmt.Sprintf("✅ Одобрение: %s", comment) + saveCommentToApproval(commentText) + } + + // --- Режим any_of --- + if isAnyOf { + allSteps, _, _ := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalStep{ApprovalID: &approvalID}, + }) + for _, s := range allSteps { + if s.ID == nil || s.Status == nil || (*s.Status != "waiting" && *s.Status != "pending") { + continue + } + if s.ID != nil && step.ID != nil && *s.ID == *step.ID { + continue + } + cancelledStatus := "cancelled_any_of" + s.Status = &cancelledStatus + h.ipc.Database.ApprovalStep.UpdateApprovalStepDB(ctx, nil, s) //nolint:errcheck + + if s.ApproverID != nil { + approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *s.ApproverID) + if approver != nil && approver.TelegramID != nil { + deciderName := "—" + if actualExecutor != nil && actualExecutor.FullName != nil { + deciderName = *actualExecutor.FullName + } + sendText(bot, *approver.TelegramID, fmt.Sprintf( + "ℹ️ Заявка #%d уже согласована\n\n"+ + "👤 Согласовал: %s\n\n"+ + "Ваше участие в согласовании больше не требуется.", + approvalID, deciderName, + )) + } + } + } + + h.processNextStepOrComplete(bot, ctx, approval, step, approvalCard, categoryCode, notifier, initiator, collected, currentUserID) + return + } + + freshApproval, _ := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID) + if freshApproval != nil && freshApproval.Status != nil && *freshApproval.Status != "pending" { + if approverChatID != 0 { + sendText(bot, approverChatID, fmt.Sprintf("✅ Заявка #%d уже обработана.", approvalID)) + } + return + } + + allAdditionalApproved := true + var pendingAdditional []*typescore.ApprovalAdditionalApprover + for _, aa := range additionalApprovers { + if aa.Status == nil || *aa.Status == "pending" { + allAdditionalApproved = false + pendingAdditional = append(pendingAdditional, aa) + } + if aa.Status != nil && *aa.Status == "rejected" { + allAdditionalApproved = false + break + } + } + + // Ожидаются дополнительные согласующие + if !allAdditionalApproved { + if approverChatID != 0 { + pendingCount, pendingNames := getPendingAdditionalInfo() + if pendingCount > 0 { + pendingText := fmt.Sprintf("\n\n⏳ Ожидается решение дополнительных согласующих (%d):\n• %s", + pendingCount, strings.Join(pendingNames, "\n• ")) + sendText(bot, approverChatID, fmt.Sprintf("✅ Вы одобрили заявку #%d\n\n%s%s", approvalID, approvalCard, pendingText)) + } else { + sendText(bot, approverChatID, fmt.Sprintf("✅ Вы одобрили заявку #%d\n\n%s", approvalID, approvalCard)) + } + } + return + } + + // 🚀 Все доп. согласующие одобрили — проверяем, последний ли это шаг + if approverChatID != 0 { + var currentOrder int + if step.StepOrder != nil { + currentOrder = *step.StepOrder + } + if isLastStep(currentOrder) { + sendText(bot, approverChatID, fmt.Sprintf("✅ Вы одобрили заявку #%d\n\n%s\n\nВсе согласующие одобрили заявку.", approvalID, approvalCard)) + } else { + sendText(bot, approverChatID, fmt.Sprintf("✅ Вы одобрили заявку #%d\n\n%s\n\nЗаявка передана следующему согласующему.", approvalID, approvalCard)) + } + } + + if isDelegate && originalApprover != nil && originalApprover.TelegramID != nil { + executorName := "—" + if actualExecutor != nil && actualExecutor.FullName != nil { + executorName = *actualExecutor.FullName + } + notifyMsg := tgbotapi.NewMessage(*originalApprover.TelegramID, fmt.Sprintf( + "ℹ️ Ваш делегат одобрил заявку #%d\n\n👤 Делегат: %s\n%s", + approvalID, executorName, approvalCard, + )) + notifyMsg.ParseMode = "HTML" + bot.Send(notifyMsg) //nolint:errcheck + } + + h.processNextStepOrComplete(bot, ctx, approval, step, approvalCard, categoryCode, notifier, initiator, collected, currentUserID) +} + +// Вспомогательный метод рядом: +func (h *Handler) getApproverName(ctx context.Context, userID uint64) string { + user, _ := h.ipc.Database.User.GetUserByIDDB(ctx, userID) + if user != nil && user.FullName != nil { + return *user.FullName + } + return "—" +} diff --git a/service/telegram_service/handlers/approval/handler_delegation.go b/service/telegram_service/handlers/approval/handler_delegation.go new file mode 100644 index 0000000..f52077c --- /dev/null +++ b/service/telegram_service/handlers/approval/handler_delegation.go @@ -0,0 +1,703 @@ +package approval + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/core/utilscore" + "bitrix_balancer_api/telegram_service/keyboard" + "bitrix_balancer_api/telegram_service/state" + "context" + "fmt" + "strings" + "time" + + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" + "github.com/sirupsen/logrus" +) + +func (h *Handler) HandleDelegationMainMenu(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) { + ctx := context.Background() + + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || user == nil || user.ID == nil { + return + } + + isApprover, _ := h.ipc.Database.User.IsApproverDB(ctx, *user.ID) + if !isApprover { + sendText(bot, chatID, "У вас нет прав согласующего.") + return + } + + msg := tgbotapi.NewMessage(chatID, "🔄 Делегирование прав\n\nВыберите действие:") + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildDelegationMainMenu() + bot.Send(msg) //nolint:errcheck +} + +func (h *Handler) HandleDelegationMenu(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) { + h.HandleDelegationMenuPage(bot, chatID, telegramID, 0, 0) +} + +func (h *Handler) HandleDelegationMenuPage(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, page int, prevMessageID int) { + ctx := context.Background() + + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || user == nil || user.ID == nil { + return + } + + categories, err := h.getApproverCategories(ctx, *user.ID) + if err != nil { + logrus.Errorf("HandleDelegationMenu: getApproverCategories err=%v", err) + sendText(bot, chatID, "Ошибка при получении списка категорий.") + return + } + + if len(categories) == 0 { + sendText(bot, chatID, "Нет категорий, где вы являетесь согласующим.") + return + } + + if prevMessageID != 0 { + bot.Request(tgbotapi.NewDeleteMessage(chatID, prevMessageID)) //nolint:errcheck + } + + msg := tgbotapi.NewMessage(chatID, "🔄 Делегирование прав\n\nВыберите категорию:") + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildDelegationCategoryMenu(categories, page) + bot.Send(msg) //nolint:errcheck +} + +func (h *Handler) HandleDelegationCategoryCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, categoryID uint64) { + h.HandleDelegationCategoryCallbackPage(bot, cq, categoryID, 0) +} + +func (h *Handler) HandleDelegationCategoryCallbackPage(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, categoryID uint64, page int) { + ctx := context.Background() + chatID := cq.Message.Chat.ID + telegramID := cq.From.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck + + category, _ := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, categoryID) + categoryName := "—" + if category != nil && category.Name != nil { + categoryName = *category.Name + } + + topics, _, err := h.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalTopic{CategoryID: &categoryID}, + }) + if err != nil { + logrus.Errorf("HandleDelegationCategoryCallback: GetApprovalTopicsListDB err=%v", err) + return + } + + h.States.SetDelegation(ctx, telegramID, &state.DelegationFlowState{ + CategoryID: categoryID, + Stage: "select_topic", + }) //nolint:errcheck + + msg := tgbotapi.NewMessage(chatID, fmt.Sprintf("📋 Категория: %s\n\nВыберите тему или делегируйте всю категорию:", categoryName)) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildDelegationTopicMenu(topics, categoryID, page) + bot.Send(msg) //nolint:errcheck +} + +func (h *Handler) HandleDelegationTopicCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, topicID uint64) { + h.HandleDelegationTopicCallbackPage(bot, cq, topicID, 0) +} + +func (h *Handler) HandleDelegationAllCategoryCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, categoryID uint64) { + h.HandleDelegationSelectUserPage(bot, cq, categoryID, 0, 0) +} + +func (h *Handler) HandleDelegationTopicCallbackPage(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, topicID uint64, page int) { + ctx := context.Background() + telegramID := cq.From.ID + + topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, topicID) + if topic == nil || topic.CategoryID == nil { + return + } + + delegationState, _ := h.States.GetDelegation(ctx, telegramID) + if delegationState == nil { + delegationState = &state.DelegationFlowState{} + } + delegationState.CategoryID = *topic.CategoryID + delegationState.TopicID = topicID + delegationState.Stage = "select_user" + h.States.SetDelegation(ctx, telegramID, delegationState) //nolint:errcheck + + h.HandleDelegationSelectUserPage(bot, cq, *topic.CategoryID, topicID, page) +} + +func (h *Handler) HandleDelegationSelectUserPage(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, categoryID, topicID uint64, page int) { + ctx := context.Background() + chatID := cq.Message.Chat.ID + telegramID := cq.From.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck + + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || user == nil || user.ID == nil { + return + } + + users, _, err := h.ipc.Database.User.GetUsersListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.User{ + IsBlocked: utilscore.PointerToBool(false), + }, + }) + if err != nil { + logrus.Errorf("HandleDelegationSelectUserPage: GetUsersListDB err=%v", err) + return + } + + var availableUsers []*typescore.User + for _, u := range users { + if u.ID != nil && *u.ID != *user.ID { + availableUsers = append(availableUsers, u) + } + } + + if len(availableUsers) == 0 { + sendText(bot, chatID, "Нет доступных пользователей для делегирования.") + return + } + + scopeName := "" + if topicID > 0 { + topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, topicID) + if topic != nil && topic.Name != nil { + scopeName = *topic.Name + } + } else { + category, _ := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, categoryID) + if category != nil && category.Name != nil { + scopeName = *category.Name + " (все права)" + } + } + + msg := tgbotapi.NewMessage(chatID, fmt.Sprintf("📋 Тема: %s\n\nВыберите пользователя:", scopeName)) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildDelegationUserMenu(availableUsers, categoryID, topicID, page) + bot.Send(msg) //nolint:errcheck +} + +func (h *Handler) HandleDelegationUserCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, delegateID uint64) { + ctx := context.Background() + chatID := cq.Message.Chat.ID + telegramID := cq.From.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck + + delegationState, err := h.States.GetDelegation(ctx, telegramID) + if err != nil || delegationState == nil { + sendText(bot, chatID, "⚠️ Состояние делегирования утеряно. Начните заново.") + return + } + + user, _ := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if user == nil || user.ID == nil { + return + } + + // Проверка на существующее активное делегирование + allDelegations, _, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalDelegation{ + DelegatorID: user.ID, + IsActive: utilscore.PointerToBool(true), + }, + }) + if err == nil { + for _, d := range allDelegations { + conflict := h.isDelegationConflict(ctx, d, delegationState.CategoryID, delegationState.TopicID) + if conflict { + h.sendDelegationAlreadyExists(bot, chatID, d, telegramID) + return + } + } + } + + delegationState.DelegateID = delegateID + delegationState.Stage = "input_date" + h.States.SetDelegation(ctx, telegramID, delegationState) //nolint:errcheck + + delegate, _ := h.ipc.Database.User.GetUserByIDDB(ctx, delegateID) + delegateName := "—" + if delegate != nil && delegate.FullName != nil { + delegateName = *delegate.FullName + } + + msg := tgbotapi.NewMessage(chatID, fmt.Sprintf( + "👤 Делегат: %s\n\n"+ + "Введите дату и время окончания делегирования в формате:\n"+ + "ДД.ММ.ГГГГ ЧЧ:ММ или ДД.ММ.ГГГГ\n\n"+ + "Например: 31.12.2024 18:00 или 31.12.2024", + delegateName, + )) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildDelegationBackToUsers(delegationState.CategoryID, delegationState.TopicID) + bot.Send(msg) //nolint:errcheck +} + +func (h *Handler) HandleDelegationDateInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) bool { + ctx := context.Background() + telegramID := msg.From.ID + chatID := msg.Chat.ID + + delegationState, err := h.States.GetDelegation(ctx, telegramID) + if err != nil || delegationState == nil || delegationState.Stage != "input_date" { + return false + } + + dateStr := strings.TrimSpace(msg.Text) + var validUntil time.Time + + if t, err := time.Parse("02.01.2006 15:04", dateStr); err == nil { + validUntil = t + } else if t, err := time.Parse("02.01.2006", dateStr); err == nil { + validUntil = time.Date(t.Year(), t.Month(), t.Day(), 23, 59, 59, 0, t.Location()) + } else { + sendText(bot, chatID, "⚠️ Неверный формат даты. Используйте ДД.ММ.ГГГГ ЧЧ:ММ или ДД.ММ.ГГГГ") + return true + } + + if validUntil.Before(time.Now()) { + sendText(bot, chatID, "⚠️ Дата окончания не может быть в прошлом.") + return true + } + + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || user == nil || user.ID == nil { + return true + } + + // ИСПРАВЛЕНИЕ 1: Проверяем, является ли текущий пользователь делегатом + // Если да - создаём делегирование от имени оригинального согласующего + actualDelegatorID := user.ID + + if delegationState.TopicID > 0 { + // Проверяем делегирование по теме + existingDelegations, _, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalDelegation{ + DelegateID: user.ID, + TopicID: &delegationState.TopicID, + IsActive: utilscore.PointerToBool(true), + }, + }) + if err == nil && len(existingDelegations) > 0 && existingDelegations[0].DelegatorID != nil { + // Пользователь сам является делегатом - используем оригинального делегатора + actualDelegatorID = existingDelegations[0].DelegatorID + } + } else { + // Проверяем делегирование по категории + existingDelegations, _, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalDelegation{ + DelegateID: user.ID, + CategoryID: &delegationState.CategoryID, + IsActive: utilscore.PointerToBool(true), + }, + }) + if err == nil && len(existingDelegations) > 0 && existingDelegations[0].DelegatorID != nil { + actualDelegatorID = existingDelegations[0].DelegatorID + } + } + + isActive := true + delegation := &typescore.ApprovalDelegation{ + DelegatorID: actualDelegatorID, // Используем оригинального делегатора + DelegateID: &delegationState.DelegateID, + ValidUntil: &validUntil, + IsActive: &isActive, + } + + if delegationState.TopicID > 0 { + delegation.TopicID = &delegationState.TopicID + } else { + delegation.CategoryID = &delegationState.CategoryID + } + + _, _, err = h.ipc.Database.ApprovalDelegation.CreateApprovalDelegationDB(ctx, nil, delegation) + if err != nil { + logrus.Errorf("HandleDelegationDateInput: CreateApprovalDelegationDB err=%v", err) + sendText(bot, chatID, "Ошибка при создании делегирования.") + return true + } + + h.States.ClearDelegation(ctx, telegramID) //nolint:errcheck + + scopeName := "" + if delegationState.TopicID > 0 { + topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, delegationState.TopicID) + if topic != nil && topic.Name != nil { + scopeName = *topic.Name + } + } else { + category, _ := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, delegationState.CategoryID) + if category != nil && category.Name != nil { + scopeName = *category.Name + } + } + + delegate, _ := h.ipc.Database.User.GetUserByIDDB(ctx, delegationState.DelegateID) + delegateName := "—" + if delegate != nil && delegate.FullName != nil { + delegateName = *delegate.FullName + } + + sendText(bot, chatID, fmt.Sprintf( + "✅ Делегирование создано\n\n"+ + "📋 Тема: %s\n"+ + "👤 Делегат: %s\n"+ + "📅 Действует до: %s", + scopeName, delegateName, validUntil.Format("02.01.2006 15:04"), + )) + + // Уведомляем делегата + if delegate != nil && delegate.TelegramID != nil { + delegatorName := "—" + if user.FullName != nil { + delegatorName = *user.FullName + } + notifyMsg := tgbotapi.NewMessage(*delegate.TelegramID, fmt.Sprintf( + "🔄 Вам делегированы права согласования\n\n"+ + "👤 От: %s\n"+ + "📋 Тема: %s\n"+ + "📅 До: %s", + delegatorName, scopeName, validUntil.Format("02.01.2006 15:04"), + )) + notifyMsg.ParseMode = "HTML" + bot.Send(notifyMsg) //nolint:errcheck + } + + return true +} + +func (h *Handler) HandleDelegatedRightsList(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) { + h.HandleDelegatedRightsListPage(bot, chatID, telegramID, 0, 0) +} + +func (h *Handler) HandleDelegatedRightsListPage(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, page int, prevMessageID int) { + ctx := context.Background() + + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || user == nil || user.ID == nil { + return + } + + isActive := true + delegations, _, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalDelegation{ + DelegatorID: user.ID, + IsActive: &isActive, + }, + }) + if err != nil { + logrus.Errorf("HandleDelegatedRightsList: GetApprovalDelegationsListDB err=%v", err) + sendText(bot, chatID, "Ошибка при получении списка делегирований.") + return + } + + if len(delegations) == 0 { + sendText(bot, chatID, "У вас нет активных делегирований.") + return + } + + if prevMessageID != 0 { + bot.Request(tgbotapi.NewDeleteMessage(chatID, prevMessageID)) //nolint:errcheck + } + + msg := tgbotapi.NewMessage(chatID, fmt.Sprintf("📋 Делегированные права (%d)\n\nВыберите делегирование:", len(delegations))) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildDelegatedRightsList(delegations, page, ctx, h.ipc) + bot.Send(msg) //nolint:errcheck +} + +func (h *Handler) HandleDelegatedRightDetail(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, delegationID uint64) { + ctx := context.Background() + chatID := cq.Message.Chat.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck + + delegation, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationByIDDB(ctx, delegationID) + if err != nil || delegation == nil { + sendText(bot, chatID, "⚠️ Делегирование не найдено.") + return + } + + scopeName := "" + if delegation.TopicID != nil { + topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *delegation.TopicID) + if topic != nil && topic.Name != nil { + scopeName = *topic.Name + } + } else if delegation.CategoryID != nil { + category, _ := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *delegation.CategoryID) + if category != nil && category.Name != nil { + scopeName = *category.Name + " (все права)" + } + } + + delegateName := "—" + if delegation.DelegateID != nil { + delegate, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *delegation.DelegateID) + if delegate != nil && delegate.FullName != nil { + delegateName = *delegate.FullName + } + } + + validUntil := "—" + if delegation.ValidUntil != nil { + validUntil = delegation.ValidUntil.Format("02.01.2006 15:04") + } + + text := fmt.Sprintf( + "📋 Делегирование #%d\n\n"+ + "📋 Тема: %s\n"+ + "👤 Делегат: %s\n"+ + "📅 Действует до: %s", + delegationID, scopeName, delegateName, validUntil, + ) + + msg := tgbotapi.NewMessage(chatID, text) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildDelegationActions(delegationID) + bot.Send(msg) //nolint:errcheck +} + +func (h *Handler) HandleDelegationRevoke(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, delegationID uint64) { + ctx := context.Background() + chatID := cq.Message.Chat.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck + + delegation, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationByIDDB(ctx, delegationID) + if err != nil || delegation == nil { + println(2) + sendText(bot, chatID, "⚠️ Делегирование не найдено.") + return + } + + now := time.Now() + isActive := false + delegation.ValidUntil = &now + delegation.IsActive = &isActive + + _, _, err = h.ipc.Database.ApprovalDelegation.UpdateApprovalDelegationDB(ctx, nil, delegation) + if err != nil { + logrus.Errorf("HandleDelegationRevoke: UpdateApprovalDelegationDB err=%v", err) + sendText(bot, chatID, "Ошибка при отзыве делегирования.") + return + } + + scopeName := "" + if delegation.TopicID != nil { + topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *delegation.TopicID) + if topic != nil && topic.Name != nil { + scopeName = *topic.Name + } + } else if delegation.CategoryID != nil { + category, _ := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *delegation.CategoryID) + if category != nil && category.Name != nil { + scopeName = *category.Name + } + } + + sendText(bot, chatID, fmt.Sprintf("✅ Делегирование отозвано\n\n📋 Тема: %s", scopeName)) + + // Уведомляем делегата + if delegation.DelegateID != nil { + delegate, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *delegation.DelegateID) + if delegate != nil && delegate.TelegramID != nil { + notifyMsg := tgbotapi.NewMessage(*delegate.TelegramID, fmt.Sprintf( + "⚠️ Делегирование отозвано\n\n📋 Тема: %s", + scopeName, + )) + notifyMsg.ParseMode = "HTML" + bot.Send(notifyMsg) //nolint:errcheck + } + } +} + +func (h *Handler) HandleDelegationExtendPrompt(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, delegationID uint64) { + ctx := context.Background() + chatID := cq.Message.Chat.ID + telegramID := cq.From.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck + + delegation, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationByIDDB(ctx, delegationID) + if err != nil || delegation == nil { + println(3) + sendText(bot, chatID, "⚠️ Делегирование не найдено.") + return + } + + // Сохраняем ID делегирования для продления + extendKey := fmt.Sprintf("deleg_extend:%d", telegramID) + h.ipc.RedisClient.Set(ctx, extendKey, fmt.Sprintf("%d", delegationID), 10*time.Minute) //nolint:errcheck + + msg := tgbotapi.NewMessage(chatID, + "Введите новую дату окончания в формате:\n"+ + "ДД.ММ.ГГГГ ЧЧ:ММ или ДД.ММ.ГГГГ") + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildDelegationExtendCancel(delegationID) + bot.Send(msg) //nolint:errcheck +} + +func (h *Handler) HandleDelegationExtendInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) bool { + ctx := context.Background() + telegramID := msg.From.ID + chatID := msg.Chat.ID + + extendKey := fmt.Sprintf("deleg_extend:%d", telegramID) + raw, err := h.ipc.RedisClient.Get(ctx, extendKey) + if err != nil || raw == "" { + return false + } + + var delegationID uint64 + fmt.Sscanf(raw, "%d", &delegationID) + + dateStr := strings.TrimSpace(msg.Text) + var validUntil time.Time + + if t, err := time.Parse("02.01.2006 15:04", dateStr); err == nil { + validUntil = t + } else if t, err := time.Parse("02.01.2006", dateStr); err == nil { + validUntil = time.Date(t.Year(), t.Month(), t.Day(), 23, 59, 59, 0, t.Location()) + } else { + sendText(bot, chatID, "⚠️ Неверный формат даты. Используйте ДД.ММ.ГГГГ ЧЧ:ММ или ДД.ММ.ГГГГ") + return true + } + + if validUntil.Before(time.Now()) { + sendText(bot, chatID, "⚠️ Дата окончания не может быть в прошлом.") + return true + } + + delegation, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationByIDDB(ctx, delegationID) + if err != nil || delegation == nil { + println(4) + sendText(bot, chatID, "⚠️ Делегирование не найдено.") + h.ipc.RedisClient.Del(ctx, extendKey) //nolint:errcheck + return true + } + + delegation.ValidUntil = &validUntil + notifiedDay := false + notified2h := false + delegation.NotifiedDay = ¬ifiedDay + delegation.Notified2h = ¬ified2h + + _, _, err = h.ipc.Database.ApprovalDelegation.UpdateApprovalDelegationDB(ctx, nil, delegation) + if err != nil { + logrus.Errorf("HandleDelegationExtendInput: UpdateApprovalDelegationDB err=%v", err) + sendText(bot, chatID, "Ошибка при продлении делегирования.") + h.ipc.RedisClient.Del(ctx, extendKey) //nolint:errcheck + return true + } + + h.ipc.RedisClient.Del(ctx, extendKey) //nolint:errcheck + + scopeName := "" + if delegation.TopicID != nil { + topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *delegation.TopicID) + if topic != nil && topic.Name != nil { + scopeName = *topic.Name + } + } else if delegation.CategoryID != nil { + category, _ := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *delegation.CategoryID) + if category != nil && category.Name != nil { + scopeName = *category.Name + } + } + + sendText(bot, chatID, fmt.Sprintf( + "✅ Срок делегирования изменён.\n\n"+ + "📋 Тема: %s\n"+ + "📅 Новый срок: %s", + scopeName, validUntil.Format("02.01.2006 15:04"), + )) + + // Уведомляем делегата + if delegation.DelegateID != nil { + delegate, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *delegation.DelegateID) + if delegate != nil && delegate.TelegramID != nil { + notifyMsg := tgbotapi.NewMessage(*delegate.TelegramID, fmt.Sprintf( + "🔄 Срок делегирования изменён.\n\n"+ + "📋 Тема: %s\n"+ + "📅 Новый срок: %s", + scopeName, validUntil.Format("02.01.2006 15:04"), + )) + notifyMsg.ParseMode = "HTML" + bot.Send(notifyMsg) //nolint:errcheck + } + } + + return true +} + +func (h *Handler) getApproverCategories(ctx context.Context, userID uint64) ([]*typescore.ApprovalTopicCategory, error) { + hierarchies, _, err := h.ipc.Database.UserHierarchy.GetUserHierarchyListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.UserHierarchy{ + ApproverID: &userID, + }, + }) + if err != nil { + return nil, err + } + + categoryIDs := make(map[uint64]bool) + for _, hier := range hierarchies { + if hier.TopicID != nil { + topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *hier.TopicID) + if topic != nil && topic.CategoryID != nil { + categoryIDs[*topic.CategoryID] = true + } + } + } + + var categories []*typescore.ApprovalTopicCategory + for categoryID := range categoryIDs { + category, err := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, categoryID) + if err == nil && category != nil { + categories = append(categories, category) + } + } + + return categories, nil +} + +func (h *Handler) isDelegationConflict(ctx context.Context, d *typescore.ApprovalDelegation, newCategoryID, newTopicID uint64) bool { + if d.TopicID == nil && d.CategoryID != nil { + if *d.CategoryID == newCategoryID { + return true + } + return false + } + + if d.TopicID != nil { + if newTopicID > 0 && *d.TopicID == newTopicID { + return true + } + + if newTopicID == 0 { + topic, err := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *d.TopicID) + if err == nil && topic != nil && topic.CategoryID != nil && *topic.CategoryID == newCategoryID { + return true + } + } + } + + return false +} diff --git a/service/telegram_service/handlers/approval/handler_executor.go b/service/telegram_service/handlers/approval/handler_executor.go new file mode 100644 index 0000000..e8f53ff --- /dev/null +++ b/service/telegram_service/handlers/approval/handler_executor.go @@ -0,0 +1,556 @@ +package approval + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/core/utilscore" + "bitrix_balancer_api/telegram_service/keyboard" + "bitrix_balancer_api/telegram_service/state" + "context" + "fmt" + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" + "github.com/sirupsen/logrus" + "sort" + "strings" + "time" +) + +func (h *Handler) HandleMyTasks(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) { + ctx := context.Background() + + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || user == nil || user.ID == nil { + return + } + + isExecutor, _ := h.ipc.Database.User.IsExecutorDB(ctx, *user.ID) + if !isExecutor { + sendText(bot, chatID, "У вас нет роли исполнителя.") + return + } + + tasks, _, err := h.ipc.Database.ApprovalTasks.GetApprovalTasksListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalTask{ + ExecutorID: user.ID, + Status: utilscore.PointerToString("pending"), + }, + }) + if err != nil { + logrus.Errorf("HandleMyTasks: GetPendingTasksByExecutorDB err=%v", err) + sendText(bot, chatID, "Ошибка при получении списка задач.") + return + } + + if len(tasks) == 0 { + sendText(bot, chatID, "📭 Нет активных задач.") + return + } + + sendText(bot, chatID, fmt.Sprintf("📋 Мои задачи (%d):", len(tasks))) + + for _, task := range tasks { + if task.ApprovalID == nil { + continue + } + approval, _ := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, *task.ApprovalID) + if approval == nil { + continue + } + h.sendTaskCard(bot, chatID, approval, task) + } +} + +func (h *Handler) sendTaskCard(bot *tgbotapi.BotAPI, chatID int64, approval *typescore.Approval, task *typescore.ApprovalTask) { + ctx := context.Background() + + if approval.ID == nil || task.ID == nil { + return + } + + initiatorName := "—" + if approval.InitiatorID != nil { + initiator, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID) + if initiator != nil && initiator.FullName != nil { + initiatorName = *initiator.FullName + } + } + + topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID) + + content := "—" + if approval.Content != nil { + content = *approval.Content + } + + taskText := "—" + if task.TaskText != nil { + taskText = *task.TaskText + } + + createdAt := "—" + if task.CreatedAt != nil { + createdAt = task.CreatedAt.Format("02.01.2006 15:04") + } + + text := fmt.Sprintf( + "📋 Задача по заявке #%d\n\n"+ + "👤 Инициатор: %s\n"+ + "📋 Тема: %s\n"+ + "📝 Текст заявки: %s\n"+ + "📅 Создана: %s\n\n"+ + "🎯 Задача:\n%s", + *approval.ID, initiatorName, topicFullName, content, createdAt, taskText, + ) + + allFiles, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID) + var taskFiles []string + for _, f := range allFiles { + if f.TaskID != nil && *f.TaskID == *task.ID && f.FileName != nil { + taskFiles = append(taskFiles, *f.FileName) + } + } + if len(taskFiles) > 0 { + text += "\n\n📎 Прикреплённые файлы:\n" + for i, name := range taskFiles { + text += fmt.Sprintf("%d. %s\n", i+1, name) + } + } + + commentsSection := h.formatCommentsSection(ctx, *approval.ID) + text += commentsSection + + msg := tgbotapi.NewMessage(chatID, text) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildExecutorTaskActions(*task.ID, *approval.ID) + bot.Send(msg) //nolint:errcheck +} + +func (h *Handler) HandleCompleteTask(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, taskID uint64) { + ctx := context.Background() + chatID := cq.Message.Chat.ID + telegramID := cq.From.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck + + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || user == nil || user.ID == nil { + return + } + + task, err := h.ipc.Database.ApprovalTasks.GetApprovalTaskByIDDB(ctx, taskID) + if err != nil || task == nil { + sendText(bot, chatID, "⚠️ Задача не найдена.") + return + } + + if task.ExecutorID == nil || *task.ExecutorID != *user.ID { + sendText(bot, chatID, "⚠️ Это не ваша задача.") + return + } + + if task.Status != nil && *task.Status != "pending" { + sendText(bot, chatID, "⚠️ Задача уже выполнена или не активна.") + return + } + + approval, _ := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, *task.ApprovalID) + topicName := "—" + if approval != nil && approval.TopicID != nil { + topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID) + if topic != nil && topic.Name != nil { + topicName = *topic.Name + } + } + + // 🚀 Проверка обязательности файла — ищем файлы, привязанные именно к этой задаче + requireFile := task.RequireFile != nil && *task.RequireFile + if requireFile { + files, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *task.ApprovalID) + hasExecutorFile := false + for _, f := range files { + if f.AttachedByID != nil && *f.AttachedByID == *user.ID && + f.TaskID != nil && *f.TaskID == *task.ID { + hasExecutorFile = true + break + } + } + if !hasExecutorFile { + msg := tgbotapi.NewMessage(chatID, + "⚠️ Для завершения необходимо прикрепить файл.\n\n"+ + "Нажмите «📎 Прикрепить файл», прикрепите документ, затем нажмите «Выполнено».") + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildExecutorTaskActions(*task.ID, *approval.ID) + bot.Send(msg) //nolint:errcheck + return + } + } + + // Обновляем статус текущей задачи + now := time.Now() + completedStatus := "completed" + task.Status = &completedStatus + task.CompletedAt = &now + + _, _, err = h.ipc.Database.ApprovalTasks.UpdateApprovalTaskDB(ctx, nil, task) + if err != nil { + logrus.Errorf("HandleCompleteTask: UpdateApprovalTaskDB err=%v", err) + sendText(bot, chatID, "Ошибка при выполнении задачи.") + return + } + + sendText(bot, chatID, fmt.Sprintf( + "✅ Задача выполнена\n\n"+ + "📋 Заявка: #%d — %s\n\n"+ + "Инициатор уведомлён.", + *task.ApprovalID, topicName, + )) + + h.activateNextTask(bot, ctx, approval, task) + + // Уведомляем инициатора + if approval != nil && approval.InitiatorID != nil { + initiator, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID) + if initiator != nil && initiator.TelegramID != nil { + executorName := "—" + if user.FullName != nil { + executorName = *user.FullName + } + + content := "—" + if approval.Content != nil { + content = *approval.Content + } + + notifyMsg := tgbotapi.NewMessage(*initiator.TelegramID, fmt.Sprintf( + "✅ Исполнитель завершил задачу\n\n"+ + "📋 Заявка #%d — %s\n"+ + "👤 Исполнитель: %s\n"+ + "📝 Текст: %s", + *task.ApprovalID, topicName, executorName, content, + )) + notifyMsg.ParseMode = "HTML" + bot.Send(notifyMsg) //nolint:errcheck + + if approval.TopicID != nil { + approvalTopic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID) + if approvalTopic != nil && approvalTopic.Code != nil { + topicCode := *approvalTopic.Code + // Проверяем, что тема относится к "Заказу товаров" + if strings.HasPrefix(topicCode, "goods_order_") { + hintMsg := tgbotapi.NewMessage(*initiator.TelegramID, + "📦 Следи за выполнением заказа") + hintMsg.ParseMode = "HTML" + bot.Send(hintMsg) //nolint:errcheck + } + } + } + } + } +} + +// activateNextTask активирует следующую задачу в очереди после завершения текущей +func (h *Handler) activateNextTask(bot *tgbotapi.BotAPI, ctx context.Context, approval *typescore.Approval, completedTask *typescore.ApprovalTask) { + if approval == nil || approval.ID == nil || completedTask.StepOrder == nil { + return + } + + allTasks, _, err := h.ipc.Database.ApprovalTasks.GetApprovalTasksListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalTask{ApprovalID: approval.ID}, + }) + if err != nil || len(allTasks) == 0 { + return + } + + var nextTask *typescore.ApprovalTask + for _, t := range allTasks { + if t.Status != nil && *t.Status == "waiting" && t.StepOrder != nil && completedTask.StepOrder != nil { + if *t.StepOrder == *completedTask.StepOrder+1 { + nextTask = t + break + } + } + } + + if nextTask == nil || nextTask.ExecutorID == nil { + return + } + + pendingStatus := "pending" + nextTask.Status = &pendingStatus + _, _, err = h.ipc.Database.ApprovalTasks.UpdateApprovalTaskDB(ctx, nil, nextTask) + if err != nil { + logrus.Errorf("activateNextTask: UpdateApprovalTaskDB err=%v", err) + return + } + + executor, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *nextTask.ExecutorID) + if executor != nil && executor.TelegramID != nil { + initiator, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID) + if initiator == nil { + return + } + h.notifyExecutor(bot, ctx, executor, initiator, approval, nextTask) + } +} + +// handleRevokeCancellationTask — вызывается при отзыве заявки. +// Если задача выполнена — создаём задачу на обращение изменений. +// Если задача ожидает — спрашиваем исполнителя, вносил ли он изменения. +func (h *Handler) handleRevokeCancellationTask( + bot *tgbotapi.BotAPI, + ctx context.Context, + approval *typescore.Approval, + revoker *typescore.User, + revokeComment string, +) { + if approval.ID == nil { + return + } + + tasks, _, err := h.ipc.Database.ApprovalTasks.GetApprovalTasksListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalTask{ApprovalID: approval.ID}, + }) + if err != nil || len(tasks) == 0 { + return + } + + sort.Slice(tasks, func(i, j int) bool { + if tasks[i].StepOrder == nil || tasks[j].StepOrder == nil { + return false + } + return *tasks[i].StepOrder < *tasks[j].StepOrder + }) + + for _, task := range tasks { + if task.Status == nil || task.ExecutorID == nil || task.ID == nil { + continue + } + + executor, err := h.ipc.Database.User.GetUserByIDDB(ctx, *task.ExecutorID) + if err != nil || executor == nil || executor.TelegramID == nil { + continue + } + + switch *task.Status { + case "completed": + h.createReversalTask(bot, ctx, approval, task, executor) + + case "pending": + h.askExecutorAboutChanges(bot, ctx, approval, task, executor) + + case "waiting": + cancelledStatus := "cancelled" + task.Status = &cancelledStatus + h.ipc.Database.ApprovalTasks.UpdateApprovalTaskDB(ctx, nil, task) //nolint:errcheck + + if executor.TelegramID != nil { + sendText(bot, *executor.TelegramID, fmt.Sprintf( + "↩️ Заявка #%d отозвана\n\nВаша задача отменена.", + *approval.ID, + )) + } + } + } +} + +// createReversalTask — создаёт задачу "обратить изменения" и уведомляет исполнителя. +func (h *Handler) createReversalTask( + bot *tgbotapi.BotAPI, + ctx context.Context, + approval *typescore.Approval, + originalTask *typescore.ApprovalTask, + executor *typescore.User, +) { + if approval.ID == nil || executor.TelegramID == nil { + return + } + + originalTaskText := "—" + if originalTask.TaskText != nil { + originalTaskText = *originalTask.TaskText + } + + topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID) + content := "—" + if approval.Content != nil { + content = *approval.Content + } + + reversalText := fmt.Sprintf( + "Обратить изменения по заявке #%d\n\nТема: %s\nИсходная задача: %s", + *approval.ID, topicFullName, originalTaskText, + ) + + pendingStatus := "pending" + reversalTask := &typescore.ApprovalTask{ + ApprovalID: approval.ID, + ExecutorID: originalTask.ExecutorID, + TaskText: &reversalText, + Status: &pendingStatus, + } + + created, _, err := h.ipc.Database.ApprovalTasks.CreateApprovalTaskDB(ctx, nil, reversalTask, true) + if err != nil || created == nil || created.ID == nil { + logrus.Errorf("createReversalTask: CreateApprovalTaskDB err=%v", err) + return + } + + msg := tgbotapi.NewMessage(*executor.TelegramID, fmt.Sprintf( + "⚠️ Заявка #%d отозвана — требуется обратить изменения\n\n"+ + "📋 Тема: %s\n"+ + "📝 Текст заявки: %s\n\n"+ + "🔄 Новая задача:\n%s", + *approval.ID, topicFullName, content, reversalText, + )) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildExecutorTaskActions(*created.ID, *approval.ID) + bot.Send(msg) //nolint:errcheck +} + +// askExecutorAboutChanges — спрашивает исполнителя, вносил ли он изменения +// по задаче, которая ещё не выполнена на момент отзыва заявки. +func (h *Handler) askExecutorAboutChanges( + bot *tgbotapi.BotAPI, + ctx context.Context, + approval *typescore.Approval, + task *typescore.ApprovalTask, + executor *typescore.User, +) { + if approval.ID == nil || task.ID == nil || executor.TelegramID == nil { + return + } + + topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID) + content := "—" + if approval.Content != nil { + content = *approval.Content + } + taskText := "—" + if task.TaskText != nil { + taskText = *task.TaskText + } + + msg := tgbotapi.NewMessage(*executor.TelegramID, fmt.Sprintf( + "↩️ Заявка #%d отозвана\n\n"+ + "📋 Тема: %s\n"+ + "📝 Текст заявки: %s\n\n"+ + "🎯 Ваша задача: %s\n\n"+ + "Вы уже вносили какие-либо изменения по этой задаче?", + *approval.ID, topicFullName, content, taskText, + )) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildRevokeTaskConfirmation(*task.ID, *approval.ID) + bot.Send(msg) //nolint:errcheck +} + +// HandleRevokeTaskNoChanges — исполнитель подтвердил, что изменений не вносил. +// Задача отменяется. +func (h *Handler) HandleRevokeTaskNoChanges(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, taskID uint64, approvalID uint64) { + ctx := context.Background() + chatID := cq.Message.Chat.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck + + task, err := h.ipc.Database.ApprovalTasks.GetApprovalTaskByIDDB(ctx, taskID) + if err != nil || task == nil { + sendText(bot, chatID, "⚠️ Задача не найдена.") + return + } + + cancelledStatus := "cancelled" + task.Status = &cancelledStatus + if _, _, err := h.ipc.Database.ApprovalTasks.UpdateApprovalTaskDB(ctx, nil, task); err != nil { + logrus.Errorf("HandleRevokeTaskNoChanges: UpdateApprovalTaskDB err=%v", err) + sendText(bot, chatID, "Ошибка при отмене задачи.") + return + } + + sendText(bot, chatID, fmt.Sprintf( + "✅ Подтверждено\n\n"+ + "Задача по заявке #%d отменена.\n"+ + "Спасибо за подтверждение.", + approvalID, + )) +} + +// HandleRevokeTaskHasChanges — исполнитель подтвердил, что уже вносил изменения. +// Исходная задача отменяется, создаётся задача на обращение изменений. +func (h *Handler) HandleRevokeTaskHasChanges(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, taskID uint64, approvalID uint64) { + ctx := context.Background() + chatID := cq.Message.Chat.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck + + approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID) + if err != nil || approval == nil { + sendText(bot, chatID, "⚠️ Заявка не найдена.") + return + } + + task, err := h.ipc.Database.ApprovalTasks.GetApprovalTaskByIDDB(ctx, taskID) + if err != nil || task == nil { + sendText(bot, chatID, "⚠️ Задача не найдена.") + return + } + + // Отменяем исходную задачу + cancelledStatus := "cancelled" + task.Status = &cancelledStatus + if _, _, err := h.ipc.Database.ApprovalTasks.UpdateApprovalTaskDB(ctx, nil, task); err != nil { + logrus.Errorf("HandleRevokeTaskHasChanges: UpdateApprovalTaskDB err=%v", err) + } + + // Получаем исполнителя для уведомления + executor, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, cq.From.ID) + if err != nil || executor == nil { + sendText(bot, chatID, "⚠️ Пользователь не найден.") + return + } + + // Создаём задачу на обращение изменений + h.createReversalTask(bot, ctx, approval, task, executor) + + sendText(bot, chatID, fmt.Sprintf( + "📋 Создана задача на обращение изменений по заявке #%d.", + approvalID, + )) +} + +func (h *Handler) HandleExecutorAttachStart(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID, taskID uint64) { + ctx := context.Background() + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, cq.From.ID) + if err != nil || user == nil || user.ID == nil { + return + } + + approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID) + if err != nil || approval == nil { + sendText(bot, cq.Message.Chat.ID, "⚠️ Заявка не найдена.") + return + } + + // Создаём сессию прикрепления (как в HandleAttachFileStart) + session := &state.AttachmentSession{ + ApprovalID: approvalID, + TaskID: taskID, + Files: []state.FileAttachment{}, + Stage: "collecting", + } + h.States.SetAttachmentSession(ctx, cq.From.ID, session) //nolint:errcheck + + msg := tgbotapi.NewMessage(cq.Message.Chat.ID, + fmt.Sprintf( + "📎 Прикрепление файла к задаче по заявке #%d\n\n"+ + "Отправьте фото или документ.\n"+ + "Когда закончите — нажмите «Отправить».", + approvalID, + ), + ) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildAttachSessionKeyboard(approvalID, 0) + bot.Send(msg) //nolint:errcheck +} diff --git a/service/telegram_service/handlers/approval/handler_observer.go b/service/telegram_service/handlers/approval/handler_observer.go new file mode 100644 index 0000000..16b9b04 --- /dev/null +++ b/service/telegram_service/handlers/approval/handler_observer.go @@ -0,0 +1,353 @@ +package approval + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/telegram_service/approvalflow" + "bitrix_balancer_api/telegram_service/keyboard" + "context" + "fmt" + "time" + + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" + "github.com/sirupsen/logrus" +) + +const observerTopicTTL = 30 * time.Minute + +func observerTopicKey(telegramID int64) string { + return fmt.Sprintf("obs_topic:%d", telegramID) +} + +func (h *Handler) HandleObservedApprovals(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) { + h.HandleObservedApprovalsPage(bot, chatID, telegramID, 0) +} + +func (h *Handler) HandleObservedApprovalsPage(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, page int) { + ctx := context.Background() + + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || user == nil || user.ID == nil { + return + } + + // Получаем все категории на которые у пользователя есть права наблюдателя + perms, err := h.ipc.Database.Permission.GetUserPermissionsDB(ctx, *user.ID, "observe") + if err != nil { + logrus.Errorf("HandleObservedApprovalsPage: GetUserPermissionsDB err=%v", err) + return + } + + if len(perms) == 0 { + sendText(bot, chatID, "У вас нет прав наблюдателя ни по одной теме.") + return + } + + // Собираем коды категорий + var visibleTopics []approvalflow.Topic + seenCodes := make(map[string]bool) + + for _, p := range perms { + if p.TopicCategoryID == nil { + continue + } + category, err := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *p.TopicCategoryID) + if err != nil || category == nil || category.Code == nil { + continue + } + if seenCodes[*category.Code] { + continue + } + seenCodes[*category.Code] = true + + topic, err := h.Registry.Get(*category.Code) + if err != nil { + continue + } + visibleTopics = append(visibleTopics, topic) + } + + if len(visibleTopics) == 0 { + sendText(bot, chatID, "Нет доступных тем для наблюдения.") + return + } + + msg := tgbotapi.NewMessage(chatID, "👁 Наблюдение за согласованиями\n\nВыберите тему:") + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildObserverTopicMenu(visibleTopics, page) + bot.Send(msg) //nolint:errcheck +} + +// HandleObserverTopicCallback — выбор темы наблюдателем. +func (h *Handler) HandleObserverTopicCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, topicCode string) { + ctx := context.Background() + chatID := cq.Message.Chat.ID + telegramID := cq.From.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck + + // Запоминаем тему для кнопки "назад" в карточке + h.ipc.RedisClient.Set(ctx, observerTopicKey(telegramID), topicCode, observerTopicTTL) //nolint:errcheck + + h.sendObserverTopicApprovals(bot, ctx, chatID, topicCode) +} + +// HandleObserverBackToTopic — возврат к списку заявок темы из карточки. +func (h *Handler) HandleObserverBackToTopic(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, topicCode string) { + ctx := context.Background() + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck + h.sendObserverTopicApprovals(bot, ctx, cq.Message.Chat.ID, topicCode) +} + +// HandleObserverBackToTopics — возврат к списку тем. +func (h *Handler) HandleObserverBackToTopics(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery) { + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck + h.HandleObservedApprovals(bot, cq.Message.Chat.ID, cq.From.ID) +} + +// HandleObserverApprovalCallback — карточка конкретной заявки. +func (h *Handler) HandleObserverApprovalCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64) { + ctx := context.Background() + chatID := cq.Message.Chat.ID + telegramID := cq.From.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck + + approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID) + if err != nil || approval == nil { + sendText(bot, chatID, "⚠️ Заявка не найдена.") + return + } + + initiatorName := "—" + if approval.InitiatorID != nil { + if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID); u != nil && u.FullName != nil { + initiatorName = *u.FullName + } + } + + deptName := "—" + if approval.DepartmentID != nil { + if d, _ := h.ipc.Database.Department.GetDepartmentByIDDB(ctx, *approval.DepartmentID); d != nil && d.Name != nil { + deptName = *d.Name + } + } + + // categoryCode для кнопки "назад" — берём отдельно, не смешиваем с отображением + categoryCode, _ := h.ipc.RedisClient.Get(ctx, observerTopicKey(telegramID)) + if categoryCode == "" && approval.TopicID != nil { + if topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID); topic != nil && topic.CategoryID != nil { + if cat, _ := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *topic.CategoryID); cat != nil && cat.Code != nil { + categoryCode = *cat.Code + } + } + } + + topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID) + + approverName := "—" + if activeStep, _ := h.ipc.Database.ApprovalStep.GetActiveStepDB(ctx, approvalID); activeStep != nil && activeStep.ApproverID != nil { + if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *activeStep.ApproverID); u != nil && u.FullName != nil { + approverName = *u.FullName + } + } + + createdAt := "—" + if approval.CreatedAt != nil { + createdAt = approval.CreatedAt.Format("02.01.2006 15:04") + } + content := "—" + if approval.Content != nil { + content = *approval.Content + } + + text := fmt.Sprintf( + "📄 Заявка #%d\n\n"+ + "📋 Тема: %s\n"+ + "👤 Инициатор: %s\n"+ + "🏢 Отдел: %s\n"+ + "📅 Создана: %s\n"+ + "📝 Содержание: %s\n\n"+ + "⏳ Ожидает решения: %s", + approvalID, topicFullName, initiatorName, deptName, createdAt, content, approverName, + ) + + msg := tgbotapi.NewMessage(chatID, text) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildObserverApprovalDetail(approvalID, categoryCode) + bot.Send(msg) //nolint:errcheck +} + +// HandleObserverReminderCallback — напоминание согласующему от наблюдателя. +func (h *Handler) HandleObserverReminderCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64) { + ctx := context.Background() + chatID := cq.Message.Chat.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + + approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID) + if err != nil || approval == nil { + sendText(bot, chatID, "⚠️ Заявка не найдена.") + return + } + if approval.Status == nil || *approval.Status != "pending" { + sendText(bot, chatID, "ℹ️ Заявка уже не ожидает согласования.") + return + } + + activeStep, err := h.ipc.Database.ApprovalStep.GetActiveStepDB(ctx, approvalID) + if err != nil || activeStep == nil || activeStep.ApproverID == nil { + sendText(bot, chatID, "⚠️ Активный шаг согласования не найден.") + return + } + + approver, err := h.ipc.Database.User.GetUserByIDDB(ctx, *activeStep.ApproverID) + if err != nil || approver == nil { + sendText(bot, chatID, "⚠️ Согласующий не найден.") + return + } + if approver.TelegramID == nil { + sendText(bot, chatID, "⚠️ У согласующего нет Telegram-аккаунта.") + return + } + + initiatorName := "—" + if approval.InitiatorID != nil { + if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID); u != nil && u.FullName != nil { + initiatorName = *u.FullName + } + } + content := "—" + if approval.Content != nil { + content = *approval.Content + } + + status := "" + if approval.Status != nil { + status = *approval.Status + } + reminder := fmt.Sprintf( + "🔔 Напоминание о заявке #%d\n\n"+ + "👤 Инициатор: %s\n"+ + "📝 %s\n\n"+ + "Заявка ожидает вашего решения.", + approvalID, initiatorName, content, + ) + files, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID) + + reminderMsg := tgbotapi.NewMessage(*approver.TelegramID, reminder) + reminderMsg.ParseMode = "HTML" + reminderMsg.ReplyMarkup = keyboard.BuildApproverDecision(approvalID, status, len(files) > 0, len(files)) + bot.Send(reminderMsg) //nolint:errcheck + + approverName := "согласующему" + if approver.FullName != nil { + approverName = *approver.FullName + } + sendText(bot, chatID, fmt.Sprintf("✅ Напоминание отправлено: %s.", approverName)) +} + +// sendObserverTopicApprovals — общий рендер списка заявок по теме. +func (h *Handler) sendObserverTopicApprovals(bot *tgbotapi.BotAPI, ctx context.Context, chatID int64, topicCode string) { + approvals, err := h.ipc.Database.Approval.GetApprovalsByCategoryDB(ctx, topicCode) + if err != nil { + logrus.Errorf("sendObserverTopicApprovals: GetApprovalsByCategoryDB err=%v", err) + sendText(bot, chatID, "Ошибка при получении заявок.") + return + } + + // Только pending + var pending []*typescore.Approval + for _, a := range approvals { + if a.Status != nil && *a.Status == "pending" { + pending = append(pending, a) + } + } + + topic, _ := h.Registry.Get(topicCode) + topicName := topicCode + if topic != nil { + topicName = topic.Name() + } + + if len(pending) == 0 { + msg := tgbotapi.NewMessage(chatID, fmt.Sprintf("👁 %s\n\nНет заявок, ожидающих согласования.", topicName)) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildObserverApprovalList(nil, nil, nil) + bot.Send(msg) //nolint:errcheck + return + } + + // Пакетная загрузка инициаторов и отделов + initiators := make(map[uint64]*typescore.User) + departments := make(map[uint64]*typescore.Department) + for _, a := range pending { + if a.InitiatorID != nil { + if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *a.InitiatorID); u != nil { + initiators[*a.InitiatorID] = u + } + } + if a.DepartmentID != nil { + if d, _ := h.ipc.Database.Department.GetDepartmentByIDDB(ctx, *a.DepartmentID); d != nil { + departments[*a.DepartmentID] = d + } + } + } + + msg := tgbotapi.NewMessage(chatID, fmt.Sprintf( + "👁 %s\n\nОжидают согласования: %d", topicName, len(pending), + )) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildObserverApprovalList(pending, initiators, departments) + bot.Send(msg) //nolint:errcheck +} + +// getAllowedObserverTopics — темы с правом observe для пользователя. +func (h *Handler) getAllowedObserverTopics(ctx context.Context, user *typescore.User) ([]approvalflow.Topic, error) { + perms, err := h.ipc.Database.Permission.GetUserPermissionsDB(ctx, *user.ID, "observe") + if err != nil { + return nil, err + } + if len(perms) == 0 { + return nil, nil + } + + allowedCategoryIDs := map[uint64]bool{} + allowedTopicIDs := map[uint64]bool{} + for _, p := range perms { + if p.TopicCategoryID != nil { + allowedCategoryIDs[*p.TopicCategoryID] = true + } + if p.TopicID != nil { + allowedTopicIDs[*p.TopicID] = true + } + } + + var result []approvalflow.Topic + for _, t := range h.Registry.All() { + category, err := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByCodeDB(ctx, t.Code()) + if err != nil || category == nil || category.ID == nil { + continue + } + if allowedCategoryIDs[*category.ID] { + result = append(result, t) + continue + } + topics, _, err := h.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalTopic{CategoryID: category.ID}, + }) + if err != nil { + continue + } + for _, topic := range topics { + if topic.ID != nil && allowedTopicIDs[*topic.ID] { + result = append(result, t) + break + } + } + } + return result, nil +} diff --git a/service/telegram_service/handlers/approval/handler_pending_comments.go b/service/telegram_service/handlers/approval/handler_pending_comments.go new file mode 100644 index 0000000..ed8fd17 --- /dev/null +++ b/service/telegram_service/handlers/approval/handler_pending_comments.go @@ -0,0 +1,209 @@ +package approval + +import ( + "bitrix_balancer_api/telegram_service/keyboard" + "bitrix_balancer_api/telegram_service/state" + "context" + "fmt" + "strings" + + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" + "github.com/sirupsen/logrus" +) + +// HandlePendingCommentInput — перехватывает текстовый ввод, если пользователь +// находится в состоянии ожидания комментария к отказу или отзыву. +// Возвращает true, если ввод был обработан. +func (h *Handler) HandlePendingCommentInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) bool { + ctx := context.Background() + telegramID := msg.From.ID + chatID := msg.Chat.ID + + // ── Проверяем отказ ──────────────────────────────────────── + rejectKey := fmt.Sprintf("appr_reject_pending:%d", telegramID) + if raw, err := h.ipc.RedisClient.Get(ctx, rejectKey); err == nil && raw != "" { + var approvalID uint64 + fmt.Sscanf(raw, "%d", &approvalID) + + // Удаляем сообщение с просьбой ввести комментарий + if msg.ReplyToMessage != nil { + bot.Request(tgbotapi.NewDeleteMessage(chatID, msg.ReplyToMessage.MessageID)) //nolint:errcheck + } + // Удаляем само сообщение пользователя + bot.Request(tgbotapi.NewDeleteMessage(chatID, msg.MessageID)) //nolint:errcheck + + h.ipc.RedisClient.Del(ctx, rejectKey) //nolint:errcheck + h.States.RemovePendingComment(ctx, telegramID, approvalID) //nolint:errcheck + + h.HandleDecisionWithChat(bot, msg.Chat.ID, msg.From.ID, approvalID, false, strings.TrimSpace(msg.Text)) + return true + } + + // ── Проверяем отзыв ──────────────────────────────────────── + revokeKey := fmt.Sprintf("appr_revoke_pending:%d", telegramID) + if raw, err := h.ipc.RedisClient.Get(ctx, revokeKey); err == nil && raw != "" { + var approvalID uint64 + fmt.Sscanf(raw, "%d", &approvalID) + + // Удаляем сообщение с просьбой ввести комментарий + if msg.ReplyToMessage != nil { + bot.Request(tgbotapi.NewDeleteMessage(chatID, msg.ReplyToMessage.MessageID)) //nolint:errcheck + } + // Удаляем само сообщение пользователя + bot.Request(tgbotapi.NewDeleteMessage(chatID, msg.MessageID)) //nolint:errcheck + + h.ipc.RedisClient.Del(ctx, revokeKey) //nolint:errcheck + h.States.RemovePendingComment(ctx, telegramID, approvalID) //nolint:errcheck + + h.HandleRevokeWithComment(bot, chatID, telegramID, approvalID, msg.Text) + return true + } + + return false +} + +// HandlePendingCommentsList — показывает список отложенных заявок. +func (h *Handler) HandlePendingCommentsList(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) { + ctx := context.Background() + + items, err := h.States.GetPendingComments(ctx, telegramID) + if err != nil { + logrus.Errorf("HandlePendingCommentsList: GetPendingComments err=%v", err) + sendText(bot, chatID, "Ошибка при получении отложенных согласований.") + return + } + + logrus.Infof("HandlePendingCommentsList: telegramID=%d items=%d", telegramID, len(items)) + + if len(items) == 0 { + sendText(bot, chatID, "📭 Нет отложенных согласований.") + return + } + + topicNames := h.loadTopicNamesForPending(ctx, items) + + msg := tgbotapi.NewMessage(chatID, + fmt.Sprintf("📝 Ожидают комментария (%d):\n\nВыберите заявку для обработки:", len(items)), + ) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildPendingCommentsList(items, topicNames) + bot.Send(msg) //nolint:errcheck +} + +// HandlePendingItemCallback — карточка конкретной отложенной заявки. +func (h *Handler) HandlePendingItemCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64) { + ctx := context.Background() + chatID := cq.Message.Chat.ID + telegramID := cq.From.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck + + items, _ := h.States.GetPendingComments(ctx, telegramID) + var found *state.PendingCommentItem + for _, item := range items { + if item.ApprovalID == approvalID { + i := item + found = &i + break + } + } + if found == nil { + reply := tgbotapi.NewMessage(chatID, "⚠️ Заявка не найдена в очереди.") + reply.ParseMode = "HTML" + bot.Send(reply) //nolint:errcheck + return + } + + approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID) + if err != nil || approval == nil { + reply := tgbotapi.NewMessage(chatID, "⚠️ Заявка не найдена.") + reply.ParseMode = "HTML" + bot.Send(reply) //nolint:errcheck + return + } + + topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID) + + content := "—" + if approval.Content != nil { + content = *approval.Content + } + initiatorName := "—" + if approval.InitiatorID != nil { + if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID); u != nil && u.FullName != nil { + initiatorName = *u.FullName + } + } + + actionLabel := "отклонить" + if found.Action == "revoke" { + actionLabel = "отозвать" + } + + text := fmt.Sprintf( + "📄 Заявка #%d — %s\n\n"+ + "👤 Инициатор: %s\n"+ + "📋 Тема: %s\n"+ + "📝 Текст: %s\n\n"+ + "Выберите действие чтобы %s:", + approvalID, found.Action, + initiatorName, topicFullName, content, actionLabel, + ) + + msg := tgbotapi.NewMessage(chatID, text) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildPendingItemOptions(approvalID, found.Action) + bot.Send(msg) //nolint:errcheck +} + +// HandlePendingBackCallback — возврат к списку отложенных. +func (h *Handler) HandlePendingBackCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery) { + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck + h.HandlePendingCommentsList(bot, cq.Message.Chat.ID, cq.From.ID) +} + +// HandlePendingDeferCallback — добавляет заявку в очередь отложенных. +func (h *Handler) HandlePendingDeferCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64, action string) { + ctx := context.Background() + telegramID := cq.From.ID + chatID := cq.Message.Chat.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck + + if err := h.States.AddPendingComment(ctx, telegramID, state.PendingCommentItem{ + ApprovalID: approvalID, + Action: action, + }); err != nil { + logrus.Errorf("HandlePendingDeferCallback: AddPendingComment err=%v", err) + return + } + + items, _ := h.States.GetPendingComments(ctx, telegramID) + reply := tgbotapi.NewMessage(chatID, fmt.Sprintf( + "⏳ Заявка #%d отложена. В очереди: %d.\n\n"+ + "Обработайте их через кнопку Отложенные.", + approvalID, len(items), + )) + reply.ParseMode = "HTML" + bot.Send(reply) //nolint:errcheck +} + +// loadTopicNamesForPending — вспомогательный метод для загрузки названий тем. +func (h *Handler) loadTopicNamesForPending(ctx context.Context, items []state.PendingCommentItem) map[uint64]string { + topicNames := make(map[uint64]string) + for _, item := range items { + approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, item.ApprovalID) + if err != nil || approval == nil || approval.TopicID == nil { + continue + } + t, err := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID) + if err != nil || t == nil || t.Name == nil { + continue + } + topicNames[item.ApprovalID] = *t.Name + } + return topicNames +} diff --git a/service/telegram_service/handlers/approval/handler_report.go b/service/telegram_service/handlers/approval/handler_report.go new file mode 100644 index 0000000..ca9f11e --- /dev/null +++ b/service/telegram_service/handlers/approval/handler_report.go @@ -0,0 +1,641 @@ +package approval + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/telegram_service/keyboard" + "bitrix_balancer_api/telegram_service/state" + "bytes" + "context" + "fmt" + "github.com/xuri/excelize/v2" + "sort" + "strings" + "time" + + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" + "github.com/sirupsen/logrus" +) + +// getReportCategoryCodes — объединяет категории согласующего и наблюдателя. +func (h *Handler) getReportCategoryCodes(ctx context.Context, user *typescore.User) []string { + seen := map[string]bool{} + var codes []string + + addCodes := func(action string) { + perms, err := h.ipc.Database.Permission.GetUserPermissionsDB(ctx, *user.ID, action) + if err != nil { + return + } + for _, p := range perms { + if p.TopicCategoryID == nil { + continue + } + cat, err := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *p.TopicCategoryID) + if err != nil || cat == nil || cat.Code == nil { + continue + } + if !seen[*cat.Code] { + seen[*cat.Code] = true + codes = append(codes, *cat.Code) + } + } + } + + addCodes("create") // согласующий видит то, что сам может согласовывать + addCodes("observe") // наблюдатель видит свои категории + + return codes +} + +// buildExcelApprovalsReport — строит xlsx-файл отчёта по согласованиям и возвращает байты. +func (h *Handler) buildExcelApprovalsReport(ctx context.Context, approvals []*typescore.Approval) ([]byte, error) { + f := excelize.NewFile() + sheet := "Согласования" + f.SetSheetName("Sheet1", sheet) + + headers := []string{ + "ФИО инициатора", // A + "Тема согласования", // B + "Дата создания", // C + "Согласующие", // D + "Наблюдатели", // E + "Статус", // F + "Текст согласования", // G + "Отдел сотрудника", // H + "Комментарии", // I + "Дата согласования", // J + "Текст задачи", // K + "Исполнитель", // L + "Статус задачи", // M + "Дата исполнения", // N + } + + cols := []string{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N"} + + colWidths := map[string]float64{ + "A": 25, "B": 40, "C": 18, "D": 30, + "E": 30, "F": 16, "G": 40, "H": 25, + "I": 30, "J": 18, "K": 40, "L": 25, + "M": 18, "N": 18, + } + + headerStyle, _ := f.NewStyle(&excelize.Style{ + Font: &excelize.Font{Bold: true, Color: "FFFFFF"}, + Fill: excelize.Fill{Type: "pattern", Color: []string{"2E75B6"}, Pattern: 1}, + Border: []excelize.Border{ + {Type: "left", Color: "000000", Style: 1}, + {Type: "right", Color: "000000", Style: 1}, + {Type: "top", Color: "000000", Style: 1}, + {Type: "bottom", Color: "000000", Style: 1}, + }, + Alignment: &excelize.Alignment{Horizontal: "center", Vertical: "center", WrapText: true}, + }) + + dataStyle, _ := f.NewStyle(&excelize.Style{ + Border: []excelize.Border{ + {Type: "left", Color: "CCCCCC", Style: 1}, + {Type: "right", Color: "CCCCCC", Style: 1}, + {Type: "top", Color: "CCCCCC", Style: 1}, + {Type: "bottom", Color: "CCCCCC", Style: 1}, + }, + Alignment: &excelize.Alignment{Vertical: "center", WrapText: true}, + }) + + rejectedStyle, _ := f.NewStyle(&excelize.Style{ + Fill: excelize.Fill{Type: "pattern", Color: []string{"FFE0E0"}, Pattern: 1}, + Border: []excelize.Border{ + {Type: "left", Color: "CCCCCC", Style: 1}, + {Type: "right", Color: "CCCCCC", Style: 1}, + {Type: "top", Color: "CCCCCC", Style: 1}, + {Type: "bottom", Color: "CCCCCC", Style: 1}, + }, + Alignment: &excelize.Alignment{Vertical: "center", WrapText: true}, + }) + + errorStyle, _ := f.NewStyle(&excelize.Style{ + Fill: excelize.Fill{Type: "pattern", Color: []string{"FFCCCC"}, Pattern: 1}, + Border: []excelize.Border{ + {Type: "left", Color: "CCCCCC", Style: 1}, + {Type: "right", Color: "CCCCCC", Style: 1}, + {Type: "top", Color: "CCCCCC", Style: 1}, + {Type: "bottom", Color: "CCCCCC", Style: 1}, + }, + Alignment: &excelize.Alignment{Vertical: "center", WrapText: true}, + }) + + for col, width := range colWidths { + f.SetColWidth(sheet, col, col, width) //nolint:errcheck + } + + for i, header := range headers { + cell := fmt.Sprintf("%s1", cols[i]) + f.SetCellValue(sheet, cell, header) //nolint:errcheck + f.SetCellStyle(sheet, cell, cell, headerStyle) //nolint:errcheck + } + f.SetRowHeight(sheet, 1, 36) //nolint:errcheck + + for rowIdx, a := range approvals { + row := rowIdx + 2 + + initiatorName := "" + if a.InitiatorID != nil { + if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *a.InitiatorID); u != nil && u.FullName != nil { + initiatorName = *u.FullName + } + } + + topicName := "" + if a.TopicID != nil { + if t, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *a.TopicID); t != nil { + if t.CategoryID != nil { + if c, _ := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *t.CategoryID); c != nil && c.Name != nil { + topicName = *c.Name + ": " + } + } + if t.Name != nil { + topicName += *t.Name + } + } + } + + createdAt := "" + if a.CreatedAt != nil { + createdAt = a.CreatedAt.Format("02.01.2006 15:04") + } + + var approverParts []string + var commentFromStep string + lastApprovedAt := "" + + steps, _, _ := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalStep{ApprovalID: a.ID}, + }) + sort.Slice(steps, func(i, j int) bool { + if steps[i].StepOrder == nil || steps[j].StepOrder == nil { + return false + } + return *steps[i].StepOrder < *steps[j].StepOrder + }) + for _, s := range steps { + name := "" + if s.ApproverNameSnapshot != nil && *s.ApproverNameSnapshot != "" { + name = *s.ApproverNameSnapshot + } else if s.ApproverID != nil { + if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *s.ApproverID); u != nil && u.FullName != nil { + name = *u.FullName + } + } + if name != "" { + approverParts = append(approverParts, name) + } + if s.Status != nil && *s.Status == "rejected" && s.Comment != nil && *s.Comment != "" { + commentFromStep = *s.Comment + } + if s.Status != nil && *s.Status == "approved" && s.ActedAt != nil { + lastApprovedAt = s.ActedAt.Format("02.01.2006 15:04") + } + } + approversCell := strings.Join(approverParts, "\n") + + var observerParts []string + categoryCode := h.getTopicCodeByApproval(ctx, a) + if categoryCode != "" { + observers, _ := h.ipc.Database.User.GetObserversForCategoryDB(ctx, categoryCode) + for _, obs := range observers { + if obs.FullName != nil { + observerParts = append(observerParts, *obs.FullName) + } + } + } + observersCell := strings.Join(observerParts, "\n") + + status := "—" + if a.Status != nil { + switch *a.Status { + case "pending": + status = "На согласовании" + case "approved": + status = "Согласовано" + case "rejected": + status = "Отклонено" + case "revoked": + status = "Отозвано" + } + } + + content := "" + if a.Content != nil { + content = *a.Content + } + + deptName := "" + if a.DepartmentID != nil { + if d, _ := h.ipc.Database.Department.GetDepartmentByIDDB(ctx, *a.DepartmentID); d != nil && d.Name != nil { + deptName = *d.Name + } + } + + comment := "" + if a.Status != nil && *a.Status == "rejected" { + comment = commentFromStep + } + + taskText := "Не предусмотрено" + executorName := "Не предусмотрено" + taskStatus := "Не предусмотрено" + taskCompletedAt := "" + hasTaskError := false + + if a.TopicID != nil { + topicExecutors, _ := h.ipc.Database.ApprovalTopicExecutor.GetExecutorsByTopicIDDB(ctx, *a.TopicID) + + if len(topicExecutors) == 0 { + taskText = "Не предусмотрено" + executorName = "Не предусмотрено" + taskStatus = "Не предусмотрено" + } else { + tasks, _, _ := h.ipc.Database.ApprovalTasks.GetApprovalTasksListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalTask{ApprovalID: a.ID}, + }) + + if len(tasks) == 0 { + if a.Status == nil { + taskText = "Не предусмотрено" + executorName = "Не предусмотрено" + taskStatus = "Не предусмотрено" + } else { + switch *a.Status { + case "approved": + taskText = "Ошибка: задачи не созданы" + executorName = "Ошибка" + taskStatus = "Ошибка" + hasTaskError = true + case "pending": + taskText = "Ожидает согласования" + executorName = "Ожидает согласования" + taskStatus = "Ожидает согласования" + case "rejected": + taskText = "Не выполнено (заявка отклонена)" + executorName = "Не выполнено (заявка отклонена)" + taskStatus = "Не выполнено (заявка отклонена)" + case "revoked": + taskText = "Не выполнено (заявка отозвана)" + executorName = "Не выполнено (заявка отозвана)" + taskStatus = "Не выполнено (заявка отозвана)" + default: + taskText = "Не предусмотрено" + executorName = "Не предусмотрено" + taskStatus = "Не предусмотрено" + } + } + } else { + var taskTexts []string + var executorNames []string + var taskStatuses []string + + sort.Slice(tasks, func(i, j int) bool { + if tasks[i].StepOrder == nil || tasks[j].StepOrder == nil { + return false + } + return *tasks[i].StepOrder < *tasks[j].StepOrder + }) + + for _, task := range tasks { + if task.TaskText != nil { + taskTexts = append(taskTexts, *task.TaskText) + } else { + taskTexts = append(taskTexts, "—") + } + + eName := "" + if task.ExecutorID != nil { + if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *task.ExecutorID); u != nil && u.FullName != nil { + eName = *u.FullName + } + } + executorNames = append(executorNames, eName) + + ts := "—" + if task.Status != nil { + switch *task.Status { + case "pending": + ts = "В работе" + case "waiting": + ts = "Ожидает" + case "completed": + ts = "Выполнено" + case "cancelled": + ts = "Отменено" + } + } + taskStatuses = append(taskStatuses, ts) + + if taskCompletedAt == "" && task.CompletedAt != nil { + taskCompletedAt = task.CompletedAt.Format("02.01.2006 15:04") + } + } + + taskText = strings.Join(taskTexts, "\n") + executorName = strings.Join(executorNames, "\n") + taskStatus = strings.Join(taskStatuses, "\n") + } + } + } + + values := []interface{}{ + initiatorName, topicName, createdAt, + approversCell, observersCell, + status, content, deptName, comment, + lastApprovedAt, + taskText, executorName, taskStatus, + taskCompletedAt, + } + + // Базовый стиль строки + style := dataStyle + if a.Status != nil && *a.Status == "rejected" { + style = rejectedStyle + } + + // 🚀 Заполняем ячейки с индивидуальными стилями для задач + for colIdx, val := range values { + cell := fmt.Sprintf("%s%d", cols[colIdx], row) + f.SetCellValue(sheet, cell, val) //nolint:errcheck + + // 🚀 Для ячеек задач (K, L, M) применяем errorStyle при ошибке + cellStyle := style + if hasTaskError && colIdx >= 10 && colIdx <= 12 { + cellStyle = errorStyle + } + f.SetCellStyle(sheet, cell, cell, cellStyle) //nolint:errcheck + } + + // Высота строки + rowHeight := 20.0 + maxLines := len(approverParts) + if len(strings.Split(taskText, "\n")) > maxLines { + maxLines = len(strings.Split(taskText, "\n")) + } + if maxLines > 1 { + rowHeight = float64(maxLines) * 18 + } + f.SetRowHeight(sheet, row, rowHeight) //nolint:errcheck + } + + lastCol := cols[len(headers)-1] + lastRow := len(approvals) + 1 + f.AutoFilter(sheet, //nolint:errcheck + fmt.Sprintf("A1:%s%d", lastCol, lastRow), + []excelize.AutoFilterOptions{}, + ) + + f.SetPanes(sheet, &excelize.Panes{ //nolint:errcheck + Freeze: true, + YSplit: 1, + TopLeftCell: "A2", + ActivePane: "bottomLeft", + }) + + var buf bytes.Buffer + if err := f.Write(&buf); err != nil { + return nil, err + } + return buf.Bytes(), nil +} + +const reportDateLayout = "02.01.2006" + +// HandleReportMenu — первый шаг: показываем выбор типа отчёта. +// HandleReportMenu — сразу показываем выбор периода (тип отчёта один — согласования). +func (h *Handler) HandleReportMenu(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) { + ctx := context.Background() + + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || user == nil || user.ID == nil { + return + } + + isApprover, _ := h.ipc.Database.User.IsApproverDB(ctx, *user.ID) + isObserver, _ := h.ipc.Database.User.IsObserverDB(ctx, *user.ID) + isDirector, _ := h.ipc.Database.User.IsDirectorDB(ctx, *user.ID) + + if !isApprover && !isObserver && !isDirector { + sendText(bot, chatID, "У вас нет доступа к выгрузке отчётов.") + return + } + + h.States.ClearReport(ctx, telegramID) //nolint:errcheck + + msg := tgbotapi.NewMessage(chatID, + "📊 Выгрузка отчёта по согласованиям\n\n"+ + "Выберите период или выгрузите за всё время:") + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildReportDateToMenu() + bot.Send(msg) //nolint:errcheck +} + +// HandleReportSetDates — пользователь хочет указать период, просим дату ОТ. +func (h *Handler) HandleReportSetDates(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery) { + ctx := context.Background() + telegramID := cq.From.ID + chatID := cq.Message.Chat.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck + + // Получаем текущий state чтобы сохранить ReportType + filterState, _ := h.States.GetReport(ctx, telegramID) + reportType := "" + if filterState != nil { + reportType = filterState.ReportType + } + + h.States.SetReport(ctx, telegramID, &state.ReportFilterState{ //nolint:errcheck + ReportType: reportType, + AwaitDateFrom: true, + }) + + sendText(bot, chatID, "Введите дату начала периода в формате ДД.ММ.ГГГГ:") +} + +// HandleReportAllTime — выгрузить без фильтра по дате. +func (h *Handler) HandleReportAllTime(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery) { + ctx := context.Background() + telegramID := cq.From.ID + chatID := cq.Message.Chat.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck + + filterState, _ := h.States.GetReport(ctx, telegramID) + reportType := "" + if filterState != nil { + reportType = filterState.ReportType + } + + h.generateAndSendReport(ctx, bot, chatID, telegramID, reportType, nil, nil) +} + +// HandleReportGenerate — выгрузить с датой ОТ, без даты ДО (по сегодня). +func (h *Handler) HandleReportGenerate(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery) { + ctx := context.Background() + telegramID := cq.From.ID + chatID := cq.Message.Chat.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck + + filterState, _ := h.States.GetReport(ctx, telegramID) + h.States.ClearReport(ctx, telegramID) //nolint:errcheck + + reportType := "" + var dateFrom *time.Time + if filterState != nil { + reportType = filterState.ReportType + if filterState.DateFrom != "" { + if t, err := time.ParseInLocation(reportDateLayout, filterState.DateFrom, time.Local); err == nil { + dateFrom = &t + } + } + } + + now := time.Now() + h.generateAndSendReport(ctx, bot, chatID, telegramID, reportType, dateFrom, &now) +} + +// HandleReportTextInput — обрабатывает ввод дат фильтра. +// Возвращает true если сообщение принято. +func (h *Handler) HandleReportTextInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) bool { + ctx := context.Background() + telegramID := msg.From.ID + chatID := msg.Chat.ID + + filterState, err := h.States.GetReport(ctx, telegramID) + if err != nil || filterState == nil { + return false + } + if !filterState.AwaitDateFrom && !filterState.AwaitDateTo { + return false + } + + input := msg.Text + if _, err := time.ParseInLocation(reportDateLayout, input, time.Local); err != nil { + sendText(bot, chatID, "⚠️ Неверный формат даты. Введите в формате ДД.ММ.ГГГГ:") + return true + } + + if filterState.AwaitDateFrom { + filterState.DateFrom = input + filterState.AwaitDateFrom = false + filterState.AwaitDateTo = true + h.States.SetReport(ctx, telegramID, filterState) //nolint:errcheck + + reply := tgbotapi.NewMessage(chatID, + fmt.Sprintf("Дата начала: %s\n\nВведите дату окончания периода в формате ДД.ММ.ГГГГ:", input)) + reply.ParseMode = "HTML" + reply.ReplyMarkup = keyboard.BuildReportDateToMenu() + bot.Send(reply) //nolint:errcheck + return true + } + + if filterState.AwaitDateTo { + filterState.DateTo = input + filterState.AwaitDateTo = false + reportType := filterState.ReportType + h.States.ClearReport(ctx, telegramID) //nolint:errcheck + + dateFrom, _ := time.ParseInLocation(reportDateLayout, filterState.DateFrom, time.Local) + dateTo, _ := time.ParseInLocation(reportDateLayout, filterState.DateTo, time.Local) + + if dateTo.Before(dateFrom) { + sendText(bot, chatID, "⚠️ Дата окончания не может быть раньше даты начала. Попробуйте снова — нажмите 📊 Выгрузка отчёта.") + return true + } + + h.generateAndSendReport(ctx, bot, chatID, telegramID, reportType, &dateFrom, &dateTo) + return true + } + + return false +} + +// generateAndSendReport — сборка отчёта и отправка файла. +func (h *Handler) generateAndSendReport( + ctx context.Context, + bot *tgbotapi.BotAPI, + chatID int64, + telegramID int64, + reportType string, + dateFrom *time.Time, + dateTo *time.Time, +) { + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || user == nil || user.ID == nil { + return + } + + sendText(bot, chatID, "⏳ Формирую отчёт...") + + isDirector, _ := h.ipc.Database.User.IsDirectorDB(ctx, *user.ID) + + var buf []byte + var fileName string + var caption string + + approvals, err := h.getApprovalsForReport(ctx, user, isDirector, dateFrom, dateTo) + if err != nil { + logrus.Errorf("generateAndSendReport: getApprovalsForReport err=%v", err) + sendText(bot, chatID, "Ошибка при получении данных. Попробуйте позже.") + return + } + + if len(approvals) == 0 { + sendText(bot, chatID, "📭 Нет согласований за выбранный период.") + return + } + + buf, err = h.buildExcelApprovalsReport(ctx, approvals) + if err != nil { + logrus.Errorf("generateAndSendReport: buildExcelApprovalsReport err=%v", err) + sendText(bot, chatID, "Ошибка при формировании файла. Попробуйте позже.") + return + } + + now := time.Now() + fileName = fmt.Sprintf("Согласования %s %s.xlsx", + now.Format("02.01.2006"), + now.Format("15-04"), + ) + caption = fmt.Sprintf("📊 Отчёт по согласованиям сформирован: %s %s", now.Format("02.01.2006"), now.Format("15:04")) + + fileBytes := tgbotapi.FileBytes{Name: fileName, Bytes: buf} + doc := tgbotapi.NewDocument(chatID, fileBytes) + doc.Caption = caption + doc.ParseMode = "HTML" + + if _, err := bot.Send(doc); err != nil { + logrus.Errorf("generateAndSendReport: Send err=%v", err) + } +} + +// getApprovalsForReport — получение согласований с учётом всех ролей пользователя. +func (h *Handler) getApprovalsForReport( + ctx context.Context, + user *typescore.User, + isDirector bool, + dateFrom *time.Time, + dateTo *time.Time, +) ([]*typescore.Approval, error) { + filter := typescore.ReportFilter{ + AllAccess: isDirector, + DateFrom: dateFrom, + DateTo: dateTo, + } + + if !isDirector { + // Для обычного пользователя собираем ID согласований, где он участвует + filter.UserID = user.ID + } + + return h.ipc.Database.Approval.GetApprovalsForReportDB(ctx, filter) +} diff --git a/service/telegram_service/handlers/approval/helper.go b/service/telegram_service/handlers/approval/helper.go new file mode 100644 index 0000000..fb98f25 --- /dev/null +++ b/service/telegram_service/handlers/approval/helper.go @@ -0,0 +1,801 @@ +package approval + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/core/utilscore" + "bitrix_balancer_api/telegram_service/approvalflow" + "bitrix_balancer_api/telegram_service/keyboard" + "bitrix_balancer_api/telegram_service/state" + "bitrix_balancer_api/telegram_service/types" + "context" + "fmt" + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" + "github.com/sirupsen/logrus" + "strings" +) + +func sendText(bot *tgbotapi.BotAPI, chatID int64, text string) { + msg := tgbotapi.NewMessage(chatID, text) + msg.ParseMode = "HTML" + bot.Send(msg) //nolint:errcheck +} + +// submitApproval создаёт запись в БД и уведомляет согласующих. +func (h *Handler) submitApproval(ctx context.Context, bot *tgbotapi.BotAPI, telegramID int64, flowState *state.ApprovalFlowState) (*typescore.Approval, error) { + topic, err := h.Registry.Get(flowState.TopicCode) + if err != nil { + return nil, err + } + + initiator, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil { + return nil, fmt.Errorf("GetUserByTelegramIDDB: %w", err) + } + if initiator == nil { + return nil, fmt.Errorf("initiator not found for telegramID=%d", telegramID) + } + if initiator.ID == nil { + return nil, fmt.Errorf("initiator.ID is nil") + } + if initiator.DepartmentID == nil { + return nil, fmt.Errorf("initiator.DepartmentID is nil") + } + + topicCode, err := topic.TopicCodeFromCollected(flowState.Collected) + if err != nil { + return nil, err + } + + approvalTopic, err := h.ipc.Database.ApprovalTopic.GetApprovalTopicByCodeDB(ctx, topicCode) + if err != nil { + return nil, fmt.Errorf("GetApprovalTopicByCodeDB: %w", err) + } + if approvalTopic == nil { + return nil, fmt.Errorf("approval topic not found: %s", topicCode) + } + if approvalTopic.ID == nil { + return nil, fmt.Errorf("approvalTopic.ID is nil") + } + + content := flowState.Collected["content"] + status := "pending" + + metadata := &typescore.ApprovalMetadata{ + Region: flowState.Collected["region"], + ChangeType: flowState.Collected["change_type"], + Extra: make(map[string]string), + } + + if systems := flowState.Collected["systems"]; systems != "" { + metadata.SelectedSystems = strings.Split(systems, ",") + } + + for k, v := range flowState.Collected { + if k != "content" && k != "region" && k != "change_type" && k != "systems" { + metadata.Extra[k] = v + } + } + + metadataJSON, err := metadata.ToJSON() + if err != nil { + logrus.Warnf("submitApproval: metadata marshal err=%v", err) + } + + approval := &typescore.Approval{ + InitiatorID: initiator.ID, + TopicID: approvalTopic.ID, + DepartmentID: initiator.DepartmentID, + Content: &content, + Status: &status, + Metadata: metadataJSON, + } + + created, _, err := h.ipc.Database.Approval.CreateApprovalDB(ctx, nil, approval, true) + if err != nil { + return nil, fmt.Errorf("CreateApprovalDB: %w", err) + } + if created == nil || created.ID == nil { + return nil, fmt.Errorf("created approval is nil or has no ID") + } + + for _, f := range flowState.Files { + f := f + base64Copy := f.Base64 + nameCopy := f.FileName + + if base64Copy == "" || nameCopy == "" { + logrus.Warnf("submitApproval: skipping empty file name=%q base64_len=%d", nameCopy, len(base64Copy)) + continue + } + + file := &typescore.ApprovalFile{ + ApprovalID: created.ID, + FileBase64: &base64Copy, + FileName: &nameCopy, + AttachedByID: initiator.ID, + } + if _, _, err := h.ipc.Database.ApprovalFile.CreateApprovalFileDB(ctx, nil, file); err != nil { + logrus.Errorf("submitApproval: CreateApprovalFileDB name=%s err=%v", nameCopy, err) + } else { + logrus.Infof("submitApproval: saved file=%s approvalID=%d attachedByID=%d", + nameCopy, *created.ID, *initiator.ID) + } + } + + // Подгружаем файлы обратно в объект для уведомлений + files, err := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *created.ID) + if err != nil { + logrus.Warnf("submitApproval: GetFilesByApprovalIDDB err=%v", err) + } + created.Files = files + + var approvers []*typescore.User + + // Если выбран первый согласующий по роли — он будет шагом 0 + var firstRoleApprover *typescore.User + if flowState.SelectedFirstApproverID > 0 { + firstRoleApprover, err = h.ipc.Database.User.GetUserByIDDB(ctx, flowState.SelectedFirstApproverID) + if err != nil || firstRoleApprover == nil { + return nil, fmt.Errorf("selected first approver not found: %d", flowState.SelectedFirstApproverID) + } + } + + // Если согласующий был выбран вручную - используем его + if flowState.SelectedApproverID > 0 { + selectedApprover, err := h.ipc.Database.User.GetUserByIDDB(ctx, flowState.SelectedApproverID) + if err != nil || selectedApprover == nil { + return nil, fmt.Errorf("selected approver not found: %d", flowState.SelectedApproverID) + } + approvers = []*typescore.User{selectedApprover} + } else { + // Получаем согласующих автоматически через иерархию + approvers, err = h.ipc.Database.UserHierarchy.GetApproversDB(ctx, + *initiator.ID, + *initiator.DepartmentID, + *approvalTopic.ID, + *approvalTopic.CategoryID, + ) + if err != nil { + return nil, fmt.Errorf("GetApproversDB: %w", err) + } + } + + // Если есть первый согласующий по роли — вставляем его перед остальными + if firstRoleApprover != nil { + approvers = append([]*typescore.User{firstRoleApprover}, approvers...) + } + + if len(approvers) == 0 { + logrus.Warnf("submitApproval: no approvers found for userID=%d deptID=%d topicID=%d", + *initiator.ID, *initiator.DepartmentID, *approvalTopic.ID) + + h.ipc.Database.Approval.DeleteApprovalDB(ctx, created) //nolint:errcheck + return nil, fmt.Errorf("⚠️ Для вас в данной теме не настроены согласующие. Пожалуйста, обратитесь к руководителю с просьбой о настройке прав в системе согласований") + } + + // === НОВЫЙ БЛОК: ГРУППИРОВКА ПО ПРИОРИТЕТУ === + priorityGroups := make(map[int][]*typescore.User) + + if approvalTopic.ApprovalMode != nil { + logrus.Infof("submitApproval: approvalMode=%s for topicID=%d", *approvalTopic.ApprovalMode, *approvalTopic.ID) + } else { + logrus.Warnf("submitApproval: approvalMode is NIL for topicID=%d — будет использован sequential!", *approvalTopic.ID) + } + + for i, approver := range approvers { + p := i + if approvalTopic.ApprovalMode != nil && *approvalTopic.ApprovalMode == "any_of" { + p = 0 + } + priorityGroups[p] = append(priorityGroups[p], approver) + } + + for p, group := range priorityGroups { + var ids []string + for _, a := range group { + if a.ID != nil { + ids = append(ids, fmt.Sprintf("%d", *a.ID)) + } + } + logrus.Infof("submitApproval: priorityGroup[%d] contains approvers: %s (count=%d)", p, strings.Join(ids, ","), len(group)) + } + + stepOrder := 0 + for priority := 0; priority <= len(priorityGroups); priority++ { + group, ok := priorityGroups[priority] + if !ok { + continue + } + for _, approver := range group { + if approver.ID == nil { + continue + } + stepStatus := "waiting" + if priority == 0 { + stepStatus = "pending" // первая группа активна сразу + } + order := stepOrder + approverName := "" + if approver.FullName != nil { + approverName = *approver.FullName + } + + step := &typescore.ApprovalStep{ + ApprovalID: created.ID, + ApproverID: approver.ID, + StepOrder: &order, + Status: &stepStatus, + ApproverNameSnapshot: &approverName, + } + h.ipc.Database.ApprovalStep.CreateApprovalStepDB(ctx, nil, step) //nolint:errcheck + stepOrder++ + } + } + + // Сохраняем выбранных наблюдателей + if len(flowState.SelectedObserverIDs) > 0 { + h.saveSelectedObservers(ctx, *created.ID, *initiator.ID, flowState.SelectedObserverIDs) + } + + // === НОВЫЙ БЛОК: УВЕДОМЛЕНИЕ ВСЕХ ИЗ ПЕРВОЙ ГРУППЫ === + firstGroup := priorityGroups[0] + notifier := NewNotifier(h.ipc, topic) + + for _, approver := range firstGroup { + actualApprover := approver + + if actualApprover.TelegramID == nil { + if actualApprover.ID != nil { + logrus.Warnf("submitApproval: approver.TelegramID is nil, userID=%d", *actualApprover.ID) + } + continue + } + + // Проверяем делегирование для каждого согласующего + if approvalTopic.CategoryID != nil { + if delegations, _, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalDelegation{ + IsActive: utilscore.PointerToBool(true), + TopicID: approvalTopic.ID, + }}); err == nil && len(delegations) > 0 { + for _, deleg := range delegations { + if deleg.DelegatorID != nil && *deleg.DelegatorID == *actualApprover.ID && deleg.DelegateID != nil { + delegate, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *deleg.DelegateID) + if delegate != nil && delegate.TelegramID != nil { + actualApprover = delegate + break + } + } + } + } else { + if delegations, _, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalDelegation{ + IsActive: utilscore.PointerToBool(true), + CategoryID: approvalTopic.CategoryID, + }}); err == nil && len(delegations) > 0 { + for _, deleg := range delegations { + if deleg.DelegatorID != nil && *deleg.DelegatorID == *actualApprover.ID && deleg.DelegateID != nil { + delegate, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *deleg.DelegateID) + if delegate != nil && delegate.TelegramID != nil { + actualApprover = delegate + break + } + } + } + } + } + } + + notifier.NotifyApprover(bot, actualApprover, initiator, created, flowState.Collected) + } + + return created, nil +} + +func (h *Handler) getTopicCodeByApproval(ctx context.Context, approval *typescore.Approval) string { + if approval.TopicID == nil { + return "" + } + topic, err := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID) + if err != nil || topic == nil { + return "" + } + category, err := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *topic.CategoryID) + if err != nil || category == nil || category.Code == nil { + return "" + } + + categoryCode := *category.Code + + _, err = h.Registry.Get(categoryCode) + if err == nil { + return categoryCode + } + + absenceCategories := map[string]bool{ + "timeoff": true, "vacation": true, "sickleave": true, + } + if absenceCategories[categoryCode] { + return "absence" + } + + return categoryCode +} + +func (h *Handler) getTopicNameByApproval(ctx context.Context, approval *typescore.Approval) string { + if approval.TopicID == nil { + return "—" + } + topic, err := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID) + if err != nil || topic == nil || topic.Name == nil { + return "—" + } + return *topic.Name +} + +// getCollectedFromApproval восстанавливает map collected из сохранённого контента заявки. +// Контент хранится как введённая строка — для уведомлений этого достаточно. +func (h *Handler) getCollectedFromApproval(ctx context.Context, approval *typescore.Approval) map[string]string { + collected := map[string]string{} + if approval.Content != nil { + collected["content"] = *approval.Content + } + + topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID) + if topic != nil { + if topic.PaymentType != nil { + collected["payment_type"] = *topic.PaymentType + } + if topic.DurationType != nil { + collected["duration_type"] = *topic.DurationType + } + if topic.TimeType != nil { + collected["time_type"] = *topic.TimeType + } + if topic.Instructions != nil && *topic.Instructions != "" { + collected["instructions"] = *topic.Instructions + } + } + + if approval.Metadata != nil { + if meta, err := typescore.ParseApprovalMetadata(approval.Metadata); err == nil && meta != nil { + if meta.Region != "" { + collected["region"] = meta.Region + } + if meta.ChangeType != "" { + collected["change_type"] = meta.ChangeType + } + + if len(meta.SelectedSystems) > 0 { + systemsStr := strings.Join(meta.SelectedSystems, ", ") + collected["target_system"] = systemsStr + collected["target_systems"] = systemsStr + collected["systems"] = systemsStr + collected["selected_systems"] = systemsStr + } + + for k, v := range meta.Extra { + collected[k] = v + } + } + } + + return collected +} + +// getAllowedTopicCodes возвращает map[category_code]bool с разрешёнными для пользователя категориями. +// Право считается выданным если: +// - есть запись permissions с action=create и topic_category_id совпадает с категорией темы +// - ИЛИ есть запись с action=create и topic_id совпадает с конкретной темой +func (h *Handler) getAllowedTopicCodes(ctx context.Context, user *typescore.User) (map[string]bool, error) { + allowed := map[string]bool{} + + perms, err := h.ipc.Database.Permission.GetUserPermissionsDB(ctx, *user.ID, "create") + if err != nil { + return nil, err + } + + if len(perms) == 0 { + return allowed, nil + } + + allowedCategoryIDs := map[uint64]bool{} + allowedTopicIDs := map[uint64]bool{} + for _, p := range perms { + if p.TopicCategoryID != nil { + allowedCategoryIDs[*p.TopicCategoryID] = true + } + if p.TopicID != nil { + allowedTopicIDs[*p.TopicID] = true + } + } + + for _, t := range h.Registry.All() { + category, err := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByCodeDB(ctx, t.Code()) + if err != nil { + logrus.Warnf("getAllowedTopicCodes: GetApprovalTopicCategoryByCodeDB err=%v", err) + continue + } + if category == nil { + logrus.Warnf("getAllowedTopicCodes: category not found for code=%s", t.Code()) + continue + } + + if !allowed[t.Code()] && t.Code() == "absence" { + childCodes := []string{"timeoff", "vacation", "sickleave"} + for _, childCode := range childCodes { + childCategory, err := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByCodeDB(ctx, childCode) + if err != nil || childCategory == nil || childCategory.ID == nil { + continue + } + if allowedCategoryIDs[*childCategory.ID] { + allowed[t.Code()] = true + break + } + // Или по конкретным подтемам + childTopics, _, err := h.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalTopic{CategoryID: childCategory.ID}, + }) + if err != nil { + continue + } + for _, ct := range childTopics { + if ct.ID != nil && allowedTopicIDs[*ct.ID] { + allowed[t.Code()] = true + break + } + } + if allowed[t.Code()] { + break + } + } + } + if allowedCategoryIDs[*category.ID] { + allowed[t.Code()] = true + continue + } + + topics, _, err := h.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalTopic{CategoryID: category.ID}, + }) + if err != nil { + logrus.Warnf("getAllowedTopicCodes: GetApprovalTopicsListDB err=%v", err) + continue + } + for _, topic := range topics { + if allowedTopicIDs[*topic.ID] { + allowed[t.Code()] = true + break + } + } + } + + logrus.Infof("getAllowedTopicCodes: result allowed=%v", allowed) + return allowed, nil +} + +func (h *Handler) canUserAccessNode(ctx context.Context, userID uint64, topicCode string) bool { + if topicCode == "" { + return true // нет ограничений — показываем всем + } + allowed, err := h.ipc.Database.Permission.UserCanCreateTopicDB(ctx, userID, topicCode) + if err != nil { + logrus.Warnf("canUserAccessNode: UserCanCreateTopicDB topicCode=%s err=%v", topicCode, err) + return true // при ошибке не скрываем кнопку + } + return allowed +} + +func (h *Handler) filterNodesByAccess(ctx context.Context, telegramID int64, nodes []*approvalflow.FlowNode) []*approvalflow.FlowNode { + // Проверяем нужна ли фильтрация вообще + needsFilter := false + for _, n := range nodes { + if n != nil && n.TopicCode != "" { + needsFilter = true + break + } + } + if !needsFilter { + return nodes + } + + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || user == nil || user.ID == nil { + return nodes // не можем проверить — показываем всё + } + + var filtered []*approvalflow.FlowNode + for _, n := range nodes { + if n == nil { + continue + } + if h.canUserAccessNode(ctx, *user.ID, n.TopicCode) { + filtered = append(filtered, n) + } + } + return filtered +} + +func (h *Handler) showFileStatus(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, flowState *state.ApprovalFlowState, required bool) { + ctx := context.Background() + + if flowState.FileStatusMsgID != 0 { + bot.Request(tgbotapi.NewDeleteMessage(chatID, flowState.FileStatusMsgID)) //nolint:errcheck + flowState.FileStatusMsgID = 0 + } + + var sb strings.Builder + if len(flowState.Files) == 0 { + if required { + sb.WriteString("📎 Необходимо прикрепить файл\n\n") + sb.WriteString("⚠️ Для этой темы прикрепление файла обязательно.\n") + sb.WriteString("Отправьте файл или фото.") + } else { + sb.WriteString("📎 Файлы не прикреплены\n\n") + sb.WriteString("Отправьте файл или нажмите «Отправить без файлов».") + } + } else { + sb.WriteString(fmt.Sprintf("📎 Прикреплённые файлы (%s):\n\n", utilscore.PluralFiles(len(flowState.Files)))) + for i, f := range flowState.Files { + sb.WriteString(fmt.Sprintf("%d. %s\n", i+1, f.FileName)) + } + sb.WriteString("\nМожете прикрепить ещё или отправить заявку.") + } + + msg := tgbotapi.NewMessage(chatID, sb.String()) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildFileInputKeyboard(flowState.TopicCode, flowState.Files, required) + + sent, err := bot.Send(msg) + if err != nil { + logrus.Errorf("showFileStatus: Send err=%v", err) + return + } + + flowState.FileStatusMsgID = sent.MessageID + h.States.Set(ctx, telegramID, flowState) //nolint:errcheck +} + +func (h *Handler) buildApprovalCard(ctx context.Context, approval *typescore.Approval, collected map[string]string) string { + if approval.ID == nil { + return "" + } + + approvalID := *approval.ID + initiatorName := "—" + if approval.InitiatorID != nil { + initiator, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID) + if initiator != nil && initiator.FullName != nil { + initiatorName = *initiator.FullName + } + } + + topicName := getTopicFullName(ctx, h.ipc, approval.TopicID) + + content := "—" + if approval.Content != nil { + content = *approval.Content + } + + paymentLabel := "" + if approval.TopicID != nil { + topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID) + if topic != nil { + switch { + case topic.PaymentType != nil && *topic.PaymentType == "own_expense": + paymentLabel = "За свой счёт" + case topic.PaymentType != nil && *topic.PaymentType == "vacation_account": + paymentLabel = "В счёт ежегодного отпуска" + case topic.PaymentType != nil && *topic.PaymentType == "official": + paymentLabel = "Официальный больничный" + } + } + } + + files, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, approvalID) + filesLabel := "Без файлов" + if len(files) > 0 { + filesLabel = fmt.Sprintf("📎 %d файл(ов)", len(files)) + } + + paymentLine := "" + if paymentLabel != "" { + paymentLine = fmt.Sprintf("\nДоп. информация: %s", paymentLabel) + } + + region := "" + if approval.Metadata != nil { + meta, err := typescore.ParseApprovalMetadata(approval.Metadata) + if err == nil && meta != nil { + switch meta.Region { + case "crimea": + region = "Крым" + case "krasnodar": + region = "Краснодар" + case "belarus": + region = "Беларусь" + default: + region = meta.Region + } + } + } + + regionLine := "" + if region != "" { + regionLine = fmt.Sprintf("\n🌍 Регион: %s", region) + } + + status := "⏳ ожидает" + if approval.Status != nil { + switch *approval.Status { + case "approved": + status = "✅ согласована" + case "rejected": + status = "❌ отклонена" + case "revoked": + status = "🔙 отозвана" + } + } + + createdAt := "—" + if approval.CreatedAt != nil { + createdAt = approval.CreatedAt.Format("02.01.2006 15:04") + } + + card := fmt.Sprintf( + "📋 Заявка #%d\n\n"+ + "👤 Инициатор: %s\n"+ + "📂 Тема: %s\n"+ + "📝 Текст: %s%s%s\n"+ + "📎 Файлы: %s\n"+ + "📅 Создана: %s\n"+ + "📊 Статус: %s", + approvalID, initiatorName, topicName, content, regionLine, paymentLine, + filesLabel, createdAt, status, + ) + + // Добавляем информацию о текущем согласующем если заявка в процессе + if approval.Status != nil && *approval.Status == "pending" { + activeStep, _ := h.ipc.Database.ApprovalStep.GetActiveStepDB(ctx, approvalID) + if activeStep != nil && activeStep.ApproverID != nil { + approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *activeStep.ApproverID) + if approver != nil && approver.FullName != nil { + card += fmt.Sprintf("\n🔄 У согласующего: %s", *approver.FullName) + } + } + } + + // Добавляем информацию о дополнительных согласующих + additionalApprovers, _, _ := h.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalAdditionalApprover{ + ApprovalID: &approvalID, + }, + }) + if len(additionalApprovers) > 0 { + card += "\n\n👥 Дополнительные согласующие:" + for _, aa := range additionalApprovers { + if aa.ApproverID == nil { + continue + } + approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *aa.ApproverID) + if approver == nil || approver.FullName == nil { + continue + } + + statusIcon := "⏳" + if aa.Status != nil { + switch *aa.Status { + case "approved": + statusIcon = "✅" + case "rejected": + statusIcon = "❌" + } + } + card += fmt.Sprintf("\n• %s %s", statusIcon, *approver.FullName) + } + } + + // Добавляем комментарии + commentsSection := h.formatCommentsSection(ctx, approvalID) + card += commentsSection + + return card +} + +// getTopicFullName возвращает строку вида "Категория: Тема" (или просто "Тема", если категория не найдена). +func getTopicFullName(ctx context.Context, ipc *types.InternalProviderControl, topicID *uint64) string { + if ipc == nil { + logrus.Error("ipc is nil") + return "—" + } + if topicID == nil { + return "—" + } + topic, err := ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *topicID) + if err != nil { + logrus.Errorf("getTopicFullName: Send err=%v", err) + return "—" + } + if topic == nil || topic.Name == nil { + return "—" + } + if topic.CategoryID == nil { + return *topic.Name + } + category, err := ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *topic.CategoryID) + if err != nil { + logrus.Errorf("getTopicFullName: Send err=%v", err) + return "—" + } + if category == nil || category.Name == nil { + return *topic.Name + } + return fmt.Sprintf("%s: %s", *category.Name, *topic.Name) +} + +// findStepForCurrentApprover находит активный шаг, принадлежащий текущему пользователю +func (h *Handler) findStepForCurrentApprover(ctx context.Context, approvalID uint64, currentUserID uint64, approval *typescore.Approval, isAnyOf bool) *typescore.ApprovalStep { + allSteps, _, _ := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalStep{ApprovalID: &approvalID}, + }) + + if !isAnyOf { + for _, s := range allSteps { + if s.Status != nil && (*s.Status == "pending" || *s.Status == "waiting") { + return s + } + } + return nil + } + + for _, s := range allSteps { + if s.Status == nil || (*s.Status != "pending" && *s.Status != "waiting") { + continue + } + if s.ApproverID != nil && *s.ApproverID == currentUserID { + return s + } + } + + if approval.TopicID != nil { + topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID) + if topic != nil && topic.CategoryID != nil { + var allDelegations []*typescore.ApprovalDelegation + + if delegations, _, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalDelegation{ + IsActive: utilscore.PointerToBool(true), + TopicID: approval.TopicID, + }, + }); err == nil { + allDelegations = append(allDelegations, delegations...) + } + + if delegations, _, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalDelegation{ + IsActive: utilscore.PointerToBool(true), + CategoryID: topic.CategoryID, + }, + }); err == nil { + allDelegations = append(allDelegations, delegations...) + } + + for _, s := range allSteps { + if s.Status == nil || (*s.Status != "pending" && *s.Status != "waiting") { + continue + } + if s.ApproverID == nil { + continue + } + for _, deleg := range allDelegations { + if deleg.DelegatorID != nil && *deleg.DelegatorID == *s.ApproverID && + deleg.DelegateID != nil && *deleg.DelegateID == currentUserID { + return s + } + } + } + } + } + + return nil +} diff --git a/service/telegram_service/handlers/approval/http_fetch.go b/service/telegram_service/handlers/approval/http_fetch.go new file mode 100644 index 0000000..33677b5 --- /dev/null +++ b/service/telegram_service/handlers/approval/http_fetch.go @@ -0,0 +1,91 @@ +package approval + +import ( + configcore "bitrix_balancer_api/core/config" + "context" + "encoding/base64" + "errors" + "fmt" + "github.com/sirupsen/logrus" + "io" + "net/http" + "sync" + "time" +) + +var ( + fileHTTPClient *http.Client + fileHTTPClientOnce sync.Once +) + +func buildFileHTTPClient(tgConfig configcore.TelegramConfig) (*http.Client, error) { + if tgConfig.ProxyURL == "" || tgConfig.ParsedProxy == nil { + return nil, errors.New("proxy url is empty or not configured") + } + + fileHTTPClientOnce.Do(func() { + fileHTTPClient = &http.Client{ + Timeout: 30 * time.Second, + Transport: &http.Transport{ + TLSHandshakeTimeout: 10 * time.Second, + ResponseHeaderTimeout: 10 * time.Second, + MaxIdleConns: 100, + MaxIdleConnsPerHost: 10, + IdleConnTimeout: 90 * time.Second, + Proxy: http.ProxyURL(tgConfig.ParsedProxy), + }, + } + }) + + return fileHTTPClient, nil +} + +// fetchFileAsBase64 скачивает файл по URL и возвращает base64-строку. +func fetchFileAsBase64(url string, tgConfig configcore.TelegramConfig) (string, error) { + client, err := buildFileHTTPClient(tgConfig) + if err != nil { + return "", err + } + + const maxRetries = 3 + const baseDelay = 500 * time.Millisecond + + var lastErr error + for attempt := 1; attempt <= maxRetries; attempt++ { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + cancel() + return "", fmt.Errorf("create request: %w", err) + } + + resp, err := client.Do(req) + if err == nil && resp.StatusCode == http.StatusOK { + data, readErr := io.ReadAll(resp.Body) + resp.Body.Close() + cancel() + + if readErr != nil { + return "", fmt.Errorf("read body: %w", readErr) + } + return base64.StdEncoding.EncodeToString(data), nil + } + + if resp != nil { + resp.Body.Close() + } + cancel() + + lastErr = err + if err != nil { + logrus.Warnf("fetchFileAsBase64: attempt %d/%d failed: %v", attempt, maxRetries, err) + } + + if attempt < maxRetries { + delay := baseDelay * time.Duration(1<<(attempt-1)) + time.Sleep(delay) + } + } + + return "", fmt.Errorf("all retries failed: %w", lastErr) +} diff --git a/service/telegram_service/handlers/approval/list.go b/service/telegram_service/handlers/approval/list.go new file mode 100644 index 0000000..7d7a65c --- /dev/null +++ b/service/telegram_service/handlers/approval/list.go @@ -0,0 +1,455 @@ +package approval + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/core/utilscore" + "bitrix_balancer_api/telegram_service/keyboard" + "context" + "fmt" + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" + "github.com/sirupsen/logrus" + "sort" +) + +// HandleMyApprovals — список активных заявок инициатора +func (h *Handler) HandleMyApprovals(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) { + ctx := context.Background() + + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || user == nil || user.ID == nil { + return + } + + // Получаем только те категории, по которым у пользователя есть заявки + categories, err := h.ipc.Database.ApprovalTopicCategory.GetCategoriesWithApprovalsByInitiatorDB(ctx, *user.ID) + if err != nil || len(categories) == 0 { + // Нет заявок вообще — сразу показываем все + h.HandleMyApprovalsStatusCallback( + bot, + &tgbotapi.CallbackQuery{ + Message: &tgbotapi.Message{Chat: &tgbotapi.Chat{ID: chatID}}, + From: &tgbotapi.User{ID: telegramID}, + }, + "all", + "all", + ) + return + } + + msg := tgbotapi.NewMessage(chatID, "📂 Инициированные согласования\n\nВыберите тему:") + msg.ParseMode = "HTML" + msg.ReplyMarkup = buildMyApprovalsTopicFilter(categories) + bot.Send(msg) //nolint:errcheck +} + +func (h *Handler) HandleMyApprovalsTopicCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, topicFilter string) { + ctx := context.Background() + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck + + // Получаем название выбранной категории + header := "Все темы" + if topicFilter != "all" && topicFilter != "" { + cat, _ := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByCodeDB(ctx, topicFilter) + if cat != nil && cat.Name != nil { + header = *cat.Name + } + } + + msg := tgbotapi.NewMessage(cq.Message.Chat.ID, + fmt.Sprintf("📂 %s\n\nВыберите статус:", header), + ) + msg.ParseMode = "HTML" + msg.ReplyMarkup = buildMyApprovalStatusFilter(topicFilter) + bot.Send(msg) //nolint:errcheck +} + +func buildMyApprovalStatusFilter(topicFilter string) tgbotapi.InlineKeyboardMarkup { + cb := func(status string) string { + return fmt.Sprintf("my_appr_status:%s:%s", status, topicFilter) + } + return tgbotapi.NewInlineKeyboardMarkup( + tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData("Все", cb("all")), + ), + tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData("✅ Согласованные", cb("approved")), + tgbotapi.NewInlineKeyboardButtonData("❌ Отклонённые", cb("rejected")), + ), + tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData("⏳ Ожидают", cb("pending")), + ), + tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData("← Назад", "my_appr_back"), + ), + ) +} + +func (h *Handler) HandleMyApprovalsStatusCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, status, topicFilter string) { + ctx := context.Background() + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck + + chatID := cq.Message.Chat.ID + telegramID := cq.From.ID + + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || user == nil || user.ID == nil { + return + } + + var filterStatus *string + if status != "" && status != "all" { + filterStatus = &status + } + + approvals, _, err := h.ipc.Database.Approval.GetApprovalsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.Approval{ + Status: filterStatus, + InitiatorID: user.ID, + }, + }) + if err != nil { + logrus.Errorf("HandleMyApprovalsStatusCallback: err=%v", err) + sendText(bot, chatID, "Ошибка при получении заявок.") + return + } + + if topicFilter != "" && topicFilter != "all" { + cat, _ := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByCodeDB(ctx, topicFilter) + if cat != nil && cat.ID != nil { + topics, _, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalTopic{CategoryID: cat.ID}, + }) + // Собираем ID разрешённых тем + allowedTopicIDs := make(map[uint64]bool) + for _, t := range topics { + if t.ID != nil { + allowedTopicIDs[*t.ID] = true + } + } + // Фильтруем заявки + var filtered []*typescore.Approval + for _, a := range approvals { + if a.TopicID != nil && allowedTopicIDs[*a.TopicID] { + filtered = append(filtered, a) + } + } + approvals = filtered + } + } + + if len(approvals) == 0 { + sendText(bot, chatID, "📭 Заявок по выбранным фильтрам не найдено.") + return + } + + for _, approval := range approvals { + if approval.ID == nil { + continue + } + card := h.buildApprovalCard(ctx, approval, h.getCollectedFromApproval(ctx, approval)) + approvalStatus := "" + if approval.Status != nil { + approvalStatus = *approval.Status + } + files, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID) + msg := tgbotapi.NewMessage(chatID, card) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildInitiatorCard(*approval.ID, approvalStatus, len(files) > 0, len(files)) + bot.Send(msg) //nolint:errcheck + } +} + +func buildMyApprovalsTopicFilter(categories []*typescore.ApprovalTopicCategory) tgbotapi.InlineKeyboardMarkup { + var rows [][]tgbotapi.InlineKeyboardButton + + // Кнопка "Все" + rows = append(rows, tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData("📋 Все темы", "my_appr_topic:all"), + )) + + // Кнопки по категориям из БД + for _, c := range categories { + if c.ID == nil || c.Name == nil { + continue + } + rows = append(rows, tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData( + *c.Name, + fmt.Sprintf("my_appr_topic:%s", *c.Code), + ), + )) + } + + return tgbotapi.NewInlineKeyboardMarkup(rows...) +} + +// HandleIncomingApprovals — список заявок ожидающих действия согласующего +func (h *Handler) HandleIncomingApprovals(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) { + ctx := context.Background() + + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || user == nil || user.ID == nil { + return + } + + // Основные согласования + steps, _, err := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalStep{ + ApproverID: user.ID, + Status: utilscore.PointerToString("pending"), + }, + }) + if err != nil { + logrus.Errorf("HandleIncomingApprovals: GetApprovalStepsListDB err=%v", err) + return + } + + // Дополнительные согласования + additionalApprovers, _, err := h.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalAdditionalApprover{ + ApproverID: user.ID, + Status: utilscore.PointerToString("pending"), + }, + }) + if err != nil { + logrus.Warnf("HandleIncomingApprovals: GetPendingAdditionalApprovalsByApproverDB err=%v", err) + } + + totalCount := len(steps) + len(additionalApprovers) + if totalCount == 0 { + sendText(bot, chatID, "📭 Нет заявок для согласования.") + return + } + + sendText(bot, chatID, fmt.Sprintf("📬 Входящие согласования (%d):", totalCount)) + + // Отправляем основные согласования + for _, step := range steps { + if step.ApprovalID == nil { + continue + } + approval, _ := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, *step.ApprovalID) + if approval == nil { + continue + } + + // Проверяем добавленных согласующих + addedApprovers, _, _ := h.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalAdditionalApprover{ + ApprovalID: step.ApprovalID, + Status: utilscore.PointerToString("pending"), + }, + }) + h.sendApprovalCard(bot, chatID, approval, true, true, addedApprovers) + } + + // Отправляем дополнительные согласования + for _, aa := range additionalApprovers { + if aa.ApprovalID == nil { + continue + } + approval, _ := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, *aa.ApprovalID) + if approval == nil { + continue + } + h.sendAdditionalApprovalCard(bot, chatID, approval, aa) + } +} + +// sendApprovalCard отправляет карточку одной заявки. +// withDecision=true — добавляет кнопки Да/Нет для согласующего. +func (h *Handler) sendApprovalCard(bot *tgbotapi.BotAPI, chatID int64, approval *typescore.Approval, withButtons, showAddApprover bool, addedApprovers ...[]*typescore.ApprovalAdditionalApprover) { + ctx := context.Background() + + if approval.ID == nil { + return + } + + initiatorName := "—" + if approval.InitiatorID != nil { + initiator, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID) + if initiator != nil && initiator.FullName != nil { + initiatorName = *initiator.FullName + } + } + + topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID) + + content := "—" + if approval.Content != nil { + content = *approval.Content + } + + createdAt := "—" + if approval.CreatedAt != nil { + createdAt = approval.CreatedAt.Format("02.01.2006 15:04") + } + + statusEmoji := "⏳" + statusText := "ожидает" + if approval.Status != nil { + switch *approval.Status { + case "approved": + statusEmoji = "✅" + statusText = "согласовано" + case "rejected": + statusEmoji = "❌" + statusText = "отклонено" + case "revoked": + statusEmoji = "↩️" + statusText = "отозвано" + } + } + + text := fmt.Sprintf( + "📄 Заявка #%d %s %s\n\n"+ + "👤 Инициатор: %s\n"+ + "📋 Тема: %s\n"+ + "📝 Текст: %s\n"+ + "📅 Создана: %s", + *approval.ID, statusEmoji, statusText, initiatorName, topicFullName, content, createdAt, + ) + + if len(addedApprovers) > 0 && len(addedApprovers[0]) > 0 { + text += "\n\n➕ Добавлены согласующие:" + for _, aa := range addedApprovers[0] { + if aa.ApproverID != nil { + approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *aa.ApproverID) + if approver != nil && approver.FullName != nil { + text += fmt.Sprintf("\n• %s", *approver.FullName) + } + } + } + } + + msg := tgbotapi.NewMessage(chatID, text) + msg.ParseMode = "HTML" + + if withButtons && approval.Status != nil && *approval.Status == "pending" { + files, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID) + markup := keyboard.BuildApproverDecision(*approval.ID, *approval.Status, len(files) > 0, len(files)) + + //if showAddApprover { + // addBtn := tgbotapi.NewInlineKeyboardButtonData( + // "➕ Добавить согласующего", + // fmt.Sprintf("appr:add_approver:%d", *approval.ID), + // ) + // markup.InlineKeyboard = append(markup.InlineKeyboard, []tgbotapi.InlineKeyboardButton{addBtn}) + //} + + msg.ReplyMarkup = markup + + } else if approval.Status != nil && (*approval.Status == "pending" || *approval.Status == "approved") { + files, err := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID) + if err != nil { + logrus.Errorf("failed to load files for approval, %v", err) + } + markup := keyboard.BuildInitiatorCard(*approval.ID, *approval.Status, len(files) > 0, len(files)) + + msg.ReplyMarkup = markup + } + + bot.Send(msg) //nolint:errcheck +} + +// HandleApprovalStages показывает все стадии согласования заявки +func (h *Handler) HandleApprovalStages(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64) { + ctx := context.Background() + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + + approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID) + if err != nil || approval == nil { + sendText(bot, cq.Message.Chat.ID, "⚠️ Заявка не найдена.") + return + } + + steps, _, err := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalStep{ApprovalID: &approvalID}, + }) + if err != nil { + return + } + sort.Slice(steps, func(i, j int) bool { + if steps[i].StepOrder == nil || steps[j].StepOrder == nil { + return false + } + return *steps[i].StepOrder < *steps[j].StepOrder + }) + + text := fmt.Sprintf("📊 Стадии согласования заявки #%d\n\n", approvalID) + + if len(steps) == 0 { + if approval.Status != nil && *approval.Status == "approved" { + text += "✅ Заявка согласована автоматически\n\n" + text += "Согласующие не были назначены для этой темы.\n" + text += "Заявка принята без этапа согласования.\n" + } else { + text += "⚠️ Этапы согласования отсутствуют\n\n" + text += "Для этой заявки не созданы этапы согласования.\n" + } + } else { + statusIcons := map[string]string{ + "pending": "⏳", + "approved": "✅", + "rejected": "❌", + "waiting": "🔜", + } + + for i, step := range steps { + icon := "🔜" + if step.Status != nil { + if ic, ok := statusIcons[*step.Status]; ok { + icon = ic + } + } + name := "—" + if step.ApproverNameSnapshot != nil { + name = *step.ApproverNameSnapshot + } + text += fmt.Sprintf("%d. %s %s\n", i+1, icon, name) + if step.ActedAt != nil { + text += fmt.Sprintf(" 📅 %s\n", step.ActedAt.Format("02.01.2006 15:04")) + } + } + } + + // Статус задач + tasks, _, _ := h.ipc.Database.ApprovalTasks.GetApprovalTasksListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalTask{ApprovalID: &approvalID}, + }) + + if len(tasks) > 0 { + text += "\n🎯 Задачи:\n" + taskStatusLabels := map[string]string{ + "pending": "⏳ Ожидает выполнения", + "completed": "✅ Выполнена", + "cancelled": "❌ Отменена", + "cancellation": "⚠️ Требует отмены изменений", + } + for _, task := range tasks { + statusLabel := "—" + if task.Status != nil { + if l, ok := taskStatusLabels[*task.Status]; ok { + statusLabel = l + } + } + executorName := "—" + if task.ExecutorID != nil { + if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *task.ExecutorID); u != nil && u.FullName != nil { + executorName = *u.FullName + } + } + text += fmt.Sprintf("• %s — %s", executorName, statusLabel) + if task.CompletedAt != nil { + text += fmt.Sprintf(" (%s)", task.CompletedAt.Format("02.01.2006 15:04")) + } + text += "\n" + } + } + + msg := tgbotapi.NewMessage(cq.Message.Chat.ID, text) + msg.ParseMode = "HTML" + bot.Send(msg) //nolint:errcheck +} diff --git a/service/telegram_service/handlers/approval/navigation.go b/service/telegram_service/handlers/approval/navigation.go new file mode 100644 index 0000000..19d25be --- /dev/null +++ b/service/telegram_service/handlers/approval/navigation.go @@ -0,0 +1,168 @@ +package approval + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/telegram_service/keyboard" + "context" + "fmt" + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" + "github.com/sirupsen/logrus" + "time" +) + +// HandleApprovalsSubmenu открывает подменю "Согласования" +func (h *Handler) HandleApprovalsSubmenu(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) { + ctx := context.Background() + + // Проверяем, является ли пользователь наблюдателем + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || user == nil || user.ID == nil { + logrus.Warnf("HandleApprovalsSubmenu: user not found telegramID=%d", telegramID) + return + } + + isObserver, _ := h.ipc.Database.User.IsObserverDB(ctx, *user.ID) + isApprover, _ := h.ipc.Database.User.IsApproverDB(ctx, *user.ID) + + // Сохраняем текущее меню в Redis для навигации "Назад" + menuKey := fmt.Sprintf("menu_state:%d", telegramID) + h.ipc.RedisClient.Set(ctx, menuKey, "approvals_submenu", 10*time.Minute) //nolint:errcheck + + msg := tgbotapi.NewMessage(chatID, "📋 Согласования\n\nВыберите действие:") + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.ApprovalsSubmenuKeyboard(isObserver, isApprover) + bot.Send(msg) //nolint:errcheck +} + +// HandleApprovalsListSubmenu открывает подменю "Список согласований" +func (h *Handler) HandleApprovalsListSubmenu(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) { + ctx := context.Background() + + // Сохраняем текущее меню в Redis для навигации "Назад" + menuKey := fmt.Sprintf("menu_state:%d", telegramID) + h.ipc.RedisClient.Set(ctx, menuKey, "approvals_list_submenu", 10*time.Minute) //nolint:errcheck + + msg := tgbotapi.NewMessage(chatID, "📋 Список согласований\n\nВыберите фильтр:") + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.ApprovalsListSubmenuKeyboard() + bot.Send(msg) //nolint:errcheck +} + +// HandleMyApprovalsByStatus показывает заявки пользователя с фильтрацией по статусу +func (h *Handler) HandleMyApprovalsByStatus(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, status string) { + ctx := context.Background() + + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || user == nil || user.ID == nil { + logrus.Warnf("HandleMyApprovalsByStatus: user not found telegramID=%d", telegramID) + return + } + + var statusText string + switch status { + case "all": + statusText = "Все заявки" + case typescore.ApprovalStatusApproved.String(): + statusText = "✅ Принятые заявки" + case typescore.ApprovalStatusRejected.String(): + statusText = "❌ Отклонённые заявки" + case typescore.ApprovalStatusPending.String(): + statusText = "⏳ Ожидающие заявки" + default: + // По умолчанию показываем активные + statusText = "Активные заявки" + } + + approvals, _, err := h.ipc.Database.Approval.GetApprovalsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.Approval{ + InitiatorID: user.ID, + Status: &status, + }, + }) + if err != nil { + logrus.Errorf("HandleMyApprovalsByStatus: GetApprovals err=%v", err) + sendText(bot, chatID, "Ошибка при получении списка заявок.") + return + } + + if len(approvals) == 0 { + sendText(bot, chatID, fmt.Sprintf("📂 %s: не найдено.", statusText)) + return + } + + sendText(bot, chatID, fmt.Sprintf("📂 %s (%d):", statusText, len(approvals))) + + for _, a := range approvals { + h.sendApprovalCard(bot, chatID, a, false, false) + } +} + +// HandleBackNavigation обрабатывает навигацию "Назад" +func (h *Handler) HandleBackNavigation(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) { + ctx := context.Background() + + // Получаем текущее состояние меню из Redis + menuKey := fmt.Sprintf("menu_state:%d", telegramID) + currentMenu, err := h.ipc.RedisClient.Get(ctx, menuKey) + + user, userErr := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if userErr != nil || user == nil || user.ID == nil { + logrus.Warnf("HandleBackNavigation: user not found telegramID=%d", telegramID) + return + } + + isObserver, _ := h.ipc.Database.User.IsObserverDB(ctx, *user.ID) + isApprover, _ := h.ipc.Database.User.IsApproverDB(ctx, *user.ID) + + if err != nil || currentMenu == "" { + // Если состояние не найдено, возвращаемся в главное меню + h.sendMainMenu(bot, chatID, telegramID, isObserver, isApprover) + return + } + + switch currentMenu { + case "approvals_list_submenu": + // Из "Список согласований" возвращаемся в "Согласования" + h.ipc.RedisClient.Del(ctx, menuKey) //nolint:errcheck + h.HandleApprovalsSubmenu(bot, chatID, telegramID) + + case "approvals_submenu": + // Из "Согласования" возвращаемся в главное меню + h.ipc.RedisClient.Del(ctx, menuKey) //nolint:errcheck + h.sendMainMenu(bot, chatID, telegramID, isObserver, isApprover) + + default: + // По умолчанию возвращаемся в главное меню + h.ipc.RedisClient.Del(ctx, menuKey) //nolint:errcheck + h.sendMainMenu(bot, chatID, telegramID, isObserver, isApprover) + } +} + +// sendMainMenu отправляет главное меню с соответствующей клавиатурой +func (h *Handler) sendMainMenu(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, isObserver bool, isApprover bool) { + ctx := context.Background() + + user, _ := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + + isExecutor := false + if user != nil && user.ID != nil { + isExecutor, _ = h.ipc.Database.User.IsExecutorDB(ctx, *user.ID) + } + + isDirector := false + if user != nil && user.ID != nil { + isDirector, _ = h.ipc.Database.User.IsDirectorDB(ctx, *user.ID) + } + + replyMarkup := keyboard.BuildMainMenu(keyboard.UserRole{ + IsApprover: isApprover, + IsObserver: isObserver, + IsExecutor: isExecutor, + IsDirector: isDirector, + }) + + msg := tgbotapi.NewMessage(chatID, "🏠 Главное меню") + msg.ParseMode = "HTML" + msg.ReplyMarkup = replyMarkup + bot.Send(msg) //nolint:errcheck +} diff --git a/service/telegram_service/handlers/approval/notify.go b/service/telegram_service/handlers/approval/notify.go new file mode 100644 index 0000000..5a055bf --- /dev/null +++ b/service/telegram_service/handlers/approval/notify.go @@ -0,0 +1,781 @@ +package approval + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/telegram_service/approvalflow" + "bitrix_balancer_api/telegram_service/keyboard" + "bitrix_balancer_api/telegram_service/types" + "context" + "encoding/base64" + "fmt" + "github.com/sirupsen/logrus" + + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" +) + +type Notifier struct { + ipc *types.InternalProviderControl + topic approvalflow.Topic +} + +func NewNotifier(ipc *types.InternalProviderControl, topic approvalflow.Topic) *Notifier { + return &Notifier{ipc: ipc, topic: topic} +} + +func (h *Handler) notifyExecutor(bot *tgbotapi.BotAPI, ctx context.Context, executor *typescore.User, initiator *typescore.User, approval *typescore.Approval, task *typescore.ApprovalTask) { + if executor.TelegramID == nil || task.ID == nil || approval.ID == nil { + return + } + + initiatorName := "—" + if initiator.FullName != nil { + initiatorName = *initiator.FullName + } + + topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID) + + content := "—" + if approval.Content != nil { + content = *approval.Content + } + + taskText := "—" + if task.TaskText != nil { + taskText = *task.TaskText + } + + text := fmt.Sprintf( + "📋 Новая задача по заявке #%d\n\n"+ + "👤 Инициатор: %s\n"+ + "📋 Тема: %s\n"+ + "📝 Текст заявки: %s\n\n"+ + "🎯 Задача:\n%s", + *approval.ID, initiatorName, topicFullName, content, taskText, + ) + + // Добавляем комментарии + commentsSection := h.formatCommentsSection(ctx, *approval.ID) + text += commentsSection + + msg := tgbotapi.NewMessage(*executor.TelegramID, text) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildExecutorTaskActions(*task.ID, *approval.ID) + bot.Send(msg) //nolint:errcheck +} + +// NotifyApprover отправляет уведомление согласующему с кнопками Да/Нет. +func (n *Notifier) NotifyApprover( + bot *tgbotapi.BotAPI, + approver *typescore.User, + initiator *typescore.User, + approval *typescore.Approval, + collected map[string]string, +) { + if approver.TelegramID == nil || approval.ID == nil { + return + } + + ctx := context.Background() + + // Формируем основное сообщение + msgText := fmt.Sprintf("📬 Новая заявка #%d на согласование\n\n", *approval.ID) + + n.topic.FormatApproverMessage(initiator, collected) + + // Добавляем комментарии если есть + comments, _ := n.ipc.Database.ApprovalComment.GetCommentsByApprovalIDDB(ctx, *approval.ID) + if len(comments) > 0 { + msgText += "\n\n💬 Комментарии:" + for _, comment := range comments { + if comment.UserID == nil || comment.Comment == nil { + continue + } + + user, _ := n.ipc.Database.User.GetUserByIDDB(ctx, *comment.UserID) + if user == nil || user.FullName == nil { + continue + } + + timestamp := "" + if comment.CreatedAt != nil { + timestamp = comment.CreatedAt.Format("02.01.2006 15:04") + } + + msgText += fmt.Sprintf("\n\n%s (%s):\n%s", *user.FullName, timestamp, *comment.Comment) + } + } + + // Отправляем с файлами или без + if len(approval.Files) == 0 { + n.sendTextToApprover(bot, approver, approval, msgText) + return + } + + status := "" + if approval.Status != nil { + status = *approval.Status + } + + files, _ := n.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID) + + n.sendFilesToRecipient( + bot, + *approver.TelegramID, + approval, + msgText, + keyboard.BuildApproverDecision(*approval.ID, status, len(files) > 0, len(files)), + ) +} + +func (n *Notifier) sendTextToApprover(bot *tgbotapi.BotAPI, approver *typescore.User, approval *typescore.Approval, text string) { + status := "" + if approval.Status != nil { + status = *approval.Status + } + ctx := context.Background() + files, _ := n.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID) + + msg := tgbotapi.NewMessage(*approver.TelegramID, text) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildApproverDecision(*approval.ID, status, len(files) > 0, len(files)) + bot.Send(msg) //nolint:errcheck +} + +// NotifyInitiatorApproved уведомляет инициатора об одобрении. +func (n *Notifier) NotifyInitiatorApproved( + bot *tgbotapi.BotAPI, + initiator *typescore.User, + approval *typescore.Approval, + collected map[string]string, + lastApprover *typescore.User, +) { + if initiator.TelegramID == nil { + logrus.Warnf("NotifyInitiatorApproved: TelegramID is nil") + return + } + logrus.Infof("NotifyInitiatorApproved: sending to telegramID=%d approvalID=%d", *initiator.TelegramID, *approval.ID) + + approverName := "—" + if lastApprover != nil && lastApprover.FullName != nil { + approverName = *lastApprover.FullName + } + + content := collected["content"] + if content == "" { + content = "—" + } + + status := "" + if approval.Status != nil { + status = *approval.Status + } + + ctx := context.Background() + + topicFullName := getTopicFullName(ctx, n.ipc, approval.TopicID) + text := fmt.Sprintf( + "✅ Заявка #%d согласована\n\n"+ + "👤 Последний согласующий: %s\n"+ + "📋 Тема: %s\n"+ + "📝 Текст: %s", + *approval.ID, approverName, topicFullName, content, + ) + + filesCount := len(approval.Files) + if filesCount == 0 { + files, _ := n.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID) + filesCount = len(files) + } + + msg := tgbotapi.NewMessage(*initiator.TelegramID, text) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildRevokeButton(*approval.ID, status, filesCount) + if _, err := bot.Send(msg); err != nil { + logrus.Errorf("NotifyInitiatorApproved: Send err=%v", err) + } +} + +// NotifyInitiatorRejected уведомляет инициатора об отклонении. +func (n *Notifier) NotifyInitiatorRejected( + bot *tgbotapi.BotAPI, + initiator *typescore.User, + approver *typescore.User, + approval *typescore.Approval, + collected map[string]string, + comment string, +) { + if initiator.TelegramID == nil { + return + } + + approverName := "—" + if approver != nil && approver.FullName != nil { + approverName = *approver.FullName + } + + content := collected["content"] + if content == "" { + content = "—" + } + ctx := context.Background() + topicFullName := getTopicFullName(ctx, n.ipc, approval.TopicID) + text := fmt.Sprintf( + "❌ Заявка #%d отклонена\n\n"+ + "👤 Согласующий: %s\n"+ + "📋 Тема: %s\n"+ + "📝 Текст: %s", + *approval.ID, approverName, topicFullName, content, + ) + + if comment != "" { + text += fmt.Sprintf("\n💬 Причина: %s", comment) + } + + msg := tgbotapi.NewMessage(*initiator.TelegramID, text) + msg.ParseMode = "HTML" + bot.Send(msg) //nolint:errcheck +} + +// NotifyDirector уведомляет директора о финально согласованной заявке. +func (n *Notifier) NotifyDirector(bot *tgbotapi.BotAPI, director *typescore.User, initiator *typescore.User, approval *typescore.Approval, collected map[string]string) { + if director.TelegramID == nil { + return + } + + ctx := context.Background() + // 🚀 Передаем initiator и collected для построения ПОЛНОЙ карточки + card := n.buildApprovalCard(ctx, approval, initiator, collected) + + text := "📌 Финально согласовано\n\n" + card + + status := "" + if approval.Status != nil { + status = *approval.Status + } + + // Считаем файлы для кнопки + filesCount := len(approval.Files) + if filesCount == 0 { + files, _ := n.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID) + filesCount = len(files) + } + + msg := tgbotapi.NewMessage(*director.TelegramID, text) + msg.ParseMode = "HTML" + // 🚀 Передаем filesCount в клавиатуру + msg.ReplyMarkup = keyboard.BuildRevokeButton(*approval.ID, status, filesCount) + bot.Send(msg) //nolint:errcheck +} + +// NotifyObserversDecision — кто, кому и что согласовал/отклонил. +func (n *Notifier) NotifyObserversDecision( + bot *tgbotapi.BotAPI, + observers []*typescore.User, + initiator *typescore.User, + approver *typescore.User, + approval *typescore.Approval, + collected map[string]string, +) { + if approval.Status == nil || *approval.Status != "approved" { + return + } + + ctx := context.Background() + // 🚀 Передаем initiator и collected + card := n.buildApprovalCard(ctx, approval, initiator, collected) + + approverName := "—" + if approver != nil && approver.FullName != nil { + approverName = *approver.FullName + } + header := fmt.Sprintf( + "✅ %s согласовал(а) заявку\n\n", + approverName, + ) + + text := header + card + + // Считаем файлы для кнопки + filesCount := len(approval.Files) + if filesCount == 0 { + files, _ := n.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID) + filesCount = len(files) + } + + status := "" + if approval.Status != nil { + status = *approval.Status + } + for _, obs := range observers { + if obs.TelegramID == nil { + continue + } + msg := tgbotapi.NewMessage(*obs.TelegramID, text) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildObserverActions(*approval.ID, "", status, filesCount) + bot.Send(msg) //nolint:errcheck + } +} + +// sendFilesToRecipient отправляет файлы из approval получателю. +// Текст прикрепляется к первому файлу (caption), клавиатура — к последнему. +// Если файл не декодируется — пропускается с логированием. +func (n *Notifier) sendFilesToRecipient( + bot *tgbotapi.BotAPI, + chatID int64, + approval *typescore.Approval, + text string, + replyMarkup interface{}, +) { + type decodedFile struct { + name string + bytes []byte + } + + var validFiles []decodedFile + for _, f := range approval.Files { + if f.FileBase64 == nil || f.FileName == nil { + continue + } + data, err := base64.StdEncoding.DecodeString(*f.FileBase64) + if err != nil { + logrus.Errorf("sendFilesToRecipient: base64 decode file=%s err=%v", *f.FileName, err) + continue + } + validFiles = append(validFiles, decodedFile{name: *f.FileName, bytes: data}) + } + + if len(validFiles) == 0 { + msg := tgbotapi.NewMessage(chatID, text) + msg.ParseMode = "HTML" + if replyMarkup != nil { + msg.ReplyMarkup = replyMarkup + } + bot.Send(msg) //nolint:errcheck + return + } + + const batchSize = 10 + batches := splitIntoBatches(validFiles, batchSize) + + for batchIdx, batch := range batches { + isLastBatch := batchIdx == len(batches)-1 + + if len(batch) == 1 { + // Один файл — отправляем как документ с текстом и кнопками + doc := tgbotapi.NewDocument(chatID, tgbotapi.FileBytes{ + Name: batch[0].name, + Bytes: batch[0].bytes, + }) + doc.ParseMode = "HTML" + if batchIdx == 0 { + doc.Caption = text + } + if isLastBatch && replyMarkup != nil { + doc.ReplyMarkup = replyMarkup + } + if _, err := bot.Send(doc); err != nil { + logrus.Errorf("sendFilesToRecipient: Send doc err=%v", err) + } + continue + } + + var mediaGroup []interface{} + for i, f := range batch { + photo := tgbotapi.NewInputMediaDocument(tgbotapi.FileBytes{ + Name: f.name, + Bytes: f.bytes, + }) + if i == 0 && batchIdx == 0 { + photo.Caption = text + photo.ParseMode = "HTML" + } + mediaGroup = append(mediaGroup, photo) + } + + mg := tgbotapi.NewMediaGroup(chatID, mediaGroup) + if _, err := bot.Request(mg); err != nil { + logrus.Errorf("sendFilesToRecipient: SendMediaGroup batch=%d err=%v", batchIdx, err) + } + + if isLastBatch && replyMarkup != nil { + btnMsg := tgbotapi.NewMessage(chatID, "⬆️ Файлы выше") + btnMsg.ParseMode = "HTML" + btnMsg.ReplyMarkup = replyMarkup + bot.Send(btnMsg) //nolint:errcheck + } + } +} + +// splitIntoBatches делит слайс на батчи размером size +func splitIntoBatches[T any](items []T, size int) [][]T { + if len(items) == 0 { + return nil + } + var batches [][]T + for len(items) > size { + batches = append(batches, items[:size]) + items = items[size:] + } + return append(batches, items) +} + +func (h *Handler) sendDelegationAlreadyExists(bot *tgbotapi.BotAPI, chatID int64, existing *typescore.ApprovalDelegation, telegramID int64) { + ctx := context.Background() + + scopeName := "—" + if existing.TopicID != nil { + topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *existing.TopicID) + if topic != nil && topic.Name != nil { + scopeName = *topic.Name + } + } else if existing.CategoryID != nil { + category, _ := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *existing.CategoryID) + if category != nil && category.Name != nil { + scopeName = *category.Name + " (все права)" + } + } + + delegateName := "—" + if existing.DelegateID != nil { + delegate, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *existing.DelegateID) + if delegate != nil && delegate.FullName != nil { + delegateName = *delegate.FullName + } + } + + validUntil := "—" + if existing.ValidUntil != nil { + validUntil = existing.ValidUntil.Format("02.01.2006 15:04") + } + + msg := tgbotapi.NewMessage(chatID, fmt.Sprintf( + "⚠️ Делегирование уже существует\n\n"+ + "📋 Тема: %s\n"+ + "👤 Делегат: %s\n"+ + "📅 Действует до: %s", + scopeName, delegateName, validUntil, + )) + msg.ParseMode = "HTML" + bot.Send(msg) //nolint:errcheck + h.States.ClearDelegation(ctx, telegramID) //nolint:errcheck +} + +func (h *Handler) sendAdditionalApprovalCard(bot *tgbotapi.BotAPI, chatID int64, approval *typescore.Approval, additionalApprover *typescore.ApprovalAdditionalApprover) { + ctx := context.Background() + if approval.ID == nil { + return + } + + // Подгружаем актуальные файлы + files, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID) + approval.Files = files + + addedByName := "—" + if additionalApprover.AddedByID != nil { + if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *additionalApprover.AddedByID); u != nil && u.FullName != nil { + addedByName = *u.FullName + } + } + + // Используем единую карточку + card := h.buildApprovalCard(ctx, approval, h.getCollectedFromApproval(ctx, approval)) + + text := fmt.Sprintf("📄 Добавлен пользователем: %s\n\n%s", addedByName, card) + + status := "" + if approval.Status != nil { + status = *approval.Status + } + + if len(files) == 0 { + msg := tgbotapi.NewMessage(chatID, text) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildApproverDecision(*approval.ID, status, len(files) > 0, len(files)) + bot.Send(msg) //nolint:errcheck + return + } + + categoryCode := h.getTopicCodeByApproval(ctx, approval) + topic, _ := h.Registry.Get(categoryCode) + if topic != nil { + notifier := NewNotifier(h.ipc, topic) + notifier.sendFilesToRecipient(bot, chatID, approval, text, keyboard.BuildApproverDecision(*approval.ID, status, len(files) > 0, len(files))) + } +} + +// notifyObserversAboutNewFile уведомляет наблюдателей о прикреплённом файле +func (h *Handler) notifyObserversAboutNewFile( + bot *tgbotapi.BotAPI, + approvalID uint64, + attachedBy *typescore.User, + fileName, fileBase64 string, +) { + ctx := context.Background() + + approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID) + if err != nil || approval == nil { + logrus.Errorf("notifyObserversAboutNewFile: GetApprovalByIDDB err=%v", err) + return + } + + topic, err := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID) + if err != nil || topic == nil || topic.Code == nil { + logrus.Errorf("notifyObserversAboutNewFile: GetApprovalTopicByIDDB err=%v", err) + return + } + + observers, err := h.ipc.Database.User.GetObserversForCategoryDB(ctx, *topic.Code) + if err != nil { + logrus.Warnf("notifyObserversAboutNewFile: GetObserversForCategoryDB err=%v", err) + return + } + + userName := "Пользователь" + if attachedBy.FullName != nil { + userName = *attachedBy.FullName + } + + fileData, decodeErr := base64.StdEncoding.DecodeString(fileBase64) + + for _, obs := range observers { + if obs.TelegramID == nil { + continue + } + + text := fmt.Sprintf( + "📎 К заявке #%d добавлен файл\n\n"+ + "👤 Кем: %s\n"+ + "📄 Файл: %s", + approvalID, userName, fileName, + ) + + if decodeErr != nil { + logrus.Errorf("notifyObserversAboutNewFile: base64 decode err=%v", decodeErr) + msg := tgbotapi.NewMessage(*obs.TelegramID, text) + msg.ParseMode = "HTML" + bot.Send(msg) //nolint:errcheck + continue + } + + doc := tgbotapi.NewDocument(*obs.TelegramID, tgbotapi.FileBytes{ + Name: fileName, + Bytes: fileData, + }) + doc.Caption = text + doc.ParseMode = "HTML" + + if _, err := bot.Send(doc); err != nil { + logrus.Errorf("notifyObserversAboutNewFile: Send document err=%v", err) + } + } +} + +func (h *Handler) notifyAllParticipantsAboutFile( + bot *tgbotapi.BotAPI, + approvalID uint64, + attachedBy *typescore.User, + fileDescription string, +) { + ctx := context.Background() + + approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID) + if err != nil || approval == nil { + logrus.Errorf("notifyAllParticipantsAboutFile: GetApprovalByIDDB err=%v", err) + return + } + + files, err := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, approvalID) + if err != nil { + logrus.Warnf("notifyAllParticipantsAboutFile: GetFilesByApprovalIDDB err=%v", err) + } + approval.Files = files + + senderID := uint64(0) + if attachedBy != nil && attachedBy.ID != nil { + senderID = *attachedBy.ID + } + + senderName := "—" + if attachedBy != nil && attachedBy.FullName != nil { + senderName = *attachedBy.FullName + } + + text := fmt.Sprintf( + "📎 Файлы прикреплены к заявке #%d\n\n"+ + "👤 Кем: %s\n"+ + "📄 Количество: %s", + approvalID, senderName, fileDescription, + ) + + var recipients []*typescore.User + + if approval.InitiatorID != nil { + if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID); u != nil { + recipients = append(recipients, u) + } + } + + if step, _ := h.ipc.Database.ApprovalStep.GetActiveStepDB(ctx, approvalID); step != nil && step.ApproverID != nil { + if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *step.ApproverID); u != nil { + recipients = append(recipients, u) + } + } + + categoryCode := h.getTopicCodeByApproval(ctx, approval) + observers, _ := h.ipc.Database.User.GetObserversForCategoryDB(ctx, categoryCode) + recipients = append(recipients, observers...) + + // Получаем нотифайер для sendFilesToRecipient + topic, err := h.Registry.Get(categoryCode) + if err != nil { + logrus.Errorf("notifyAllParticipantsAboutFile: Registry.Get err=%v", err) + return + } + notifier := NewNotifier(h.ipc, topic) + + seen := make(map[uint64]bool) + for _, r := range recipients { + if r == nil || r.ID == nil || r.TelegramID == nil { + continue + } + if *r.ID == senderID || seen[*r.ID] { + continue + } + seen[*r.ID] = true + + if len(approval.Files) == 0 { + msg := tgbotapi.NewMessage(*r.TelegramID, text) + msg.ParseMode = "HTML" + bot.Send(msg) //nolint:errcheck + } else { + notifier.sendFilesToRecipient(bot, *r.TelegramID, approval, text, nil) + } + } +} + +func (n *Notifier) formatApprovalMessage(initiator *typescore.User, collected map[string]string) string { + return n.topic.FormatApproverMessage(initiator, collected) +} + +func (n *Notifier) buildApprovalCard(ctx context.Context, approval *typescore.Approval, initiator *typescore.User, collected map[string]string) string { + if approval.ID == nil { + return "" + } + approvalID := *approval.ID + + topicInfo := n.topic.FormatApproverMessage(initiator, collected) + + filesCount := len(approval.Files) + if filesCount == 0 { + files, _ := n.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, approvalID) + filesCount = len(files) + } + + filesLabel := "Без файлов" + if filesCount > 0 { + filesLabel = fmt.Sprintf("📎 %d файл(ов)", filesCount) + } + + status := "⏳ ожидает" + if approval.Status != nil { + switch *approval.Status { + case "approved": + status = "✅ согласована" + case "rejected": + status = "❌ отклонена" + case "revoked": + status = "🔙 отозвана" + } + } + + createdAt := "—" + if approval.CreatedAt != nil { + createdAt = approval.CreatedAt.Format("02.01.2006 15:04") + } + + card := fmt.Sprintf( + "📋 Заявка #%d\n\n"+ + "%s\n\n"+ // 🚀 Сюда вставляется полное тело заявки из topicInfo + "📎 Файлы: %s\n"+ + "📅 Создана: %s\n"+ + "📊 Статус: %s", + approvalID, topicInfo, filesLabel, createdAt, status, + ) + + // Добавляем информацию о текущем согласующем если заявка в процессе + if approval.Status != nil && *approval.Status == "pending" { + activeStep, _ := n.ipc.Database.ApprovalStep.GetActiveStepDB(ctx, approvalID) + if activeStep != nil && activeStep.ApproverID != nil { + approver, _ := n.ipc.Database.User.GetUserByIDDB(ctx, *activeStep.ApproverID) + if approver != nil && approver.FullName != nil { + card += fmt.Sprintf("\n🔄 У согласующего: %s", *approver.FullName) + } + } + } + + // Добавляем информацию о дополнительных согласующих + additionalApprovers, _, _ := n.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalAdditionalApprover{ + ApprovalID: &approvalID, + }, + }) + if len(additionalApprovers) > 0 { + card += "\n\n👥 Дополнительные согласующие:" + for _, aa := range additionalApprovers { + if aa.ApproverID == nil { + continue + } + approver, _ := n.ipc.Database.User.GetUserByIDDB(ctx, *aa.ApproverID) + if approver == nil || approver.FullName == nil { + continue + } + + statusIcon := "⏳" + if aa.Status != nil { + switch *aa.Status { + case "approved": + statusIcon = "✅" + case "rejected": + statusIcon = "❌" + } + } + card += fmt.Sprintf("\n• %s %s", statusIcon, *approver.FullName) + } + } + + // Добавляем комментарии + commentsSection := n.formatCommentsSection(ctx, approvalID) + card += commentsSection + + return card +} + +func (n *Notifier) formatCommentsSection(ctx context.Context, approvalID uint64) string { + comments, _, _ := n.ipc.Database.ApprovalComment.GetApprovalCommentsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalComment{ApprovalID: &approvalID}, + }) + if len(comments) == 0 { + return "" + } + + section := "\n\n💬 Комментарии:" + for _, c := range comments { + authorName := "—" + if c.UserID != nil { + author, _ := n.ipc.Database.User.GetUserByIDDB(ctx, *c.UserID) + if author != nil && author.FullName != nil { + authorName = *author.FullName + } + } + createdAt := "" + if c.CreatedAt != nil { + createdAt = c.CreatedAt.Format("02.01 15:04") + } + comment := "-" + if c.Comment != nil { + comment = *c.Comment + } + section += fmt.Sprintf("\n• %s (%s): %s", authorName, createdAt, comment) + } + return section +} diff --git a/service/telegram_service/handlers/approval/registry.go b/service/telegram_service/handlers/approval/registry.go new file mode 100644 index 0000000..80f7163 --- /dev/null +++ b/service/telegram_service/handlers/approval/registry.go @@ -0,0 +1,89 @@ +package approval + +import ( + "bitrix_balancer_api/telegram_service/approvalflow" + "bitrix_balancer_api/telegram_service/handlers/approval/topics/absence" + clientchanges "bitrix_balancer_api/telegram_service/handlers/approval/topics/client_changes" + "bitrix_balancer_api/telegram_service/handlers/approval/topics/free" + goodsorder "bitrix_balancer_api/telegram_service/handlers/approval/topics/goods_order" + managerexpenses "bitrix_balancer_api/telegram_service/handlers/approval/topics/manager_expenses" + nonbudgetexpenses "bitrix_balancer_api/telegram_service/handlers/approval/topics/non_budget_expenses" + nonbudgetexpensespetline "bitrix_balancer_api/telegram_service/handlers/approval/topics/non_budget_expenses_pet_line" + nonstandardcontract "bitrix_balancer_api/telegram_service/handlers/approval/topics/nonstandard_contract" + otkconditions "bitrix_balancer_api/telegram_service/handlers/approval/topics/otk_conditions" + paymentscashless "bitrix_balancer_api/telegram_service/handlers/approval/topics/payments_cashless" + rateslogistics "bitrix_balancer_api/telegram_service/handlers/approval/topics/rates_logistics" + "bitrix_balancer_api/telegram_service/handlers/approval/topics/receipts" + "bitrix_balancer_api/telegram_service/handlers/approval/topics/returns" + shipmentssoh "bitrix_balancer_api/telegram_service/handlers/approval/topics/shipments_soh" + transactionpassport "bitrix_balancer_api/telegram_service/handlers/approval/topics/transaction_passport" + "fmt" +) + +type Registry struct { + topics map[string]approvalflow.Topic + order []string +} + +func NewRegistry() *Registry { + r := &Registry{topics: make(map[string]approvalflow.Topic)} + r.registerAll() + return r +} + +func (r *Registry) registerAll() { + r.register(absence.NewAbsenceTopic()) + r.register(nonbudgetexpenses.NewNonBudgetExpensesTopic()) + r.register(nonbudgetexpensespetline.NewNonBudgetExpensesPetLineTopic()) + r.register(returns.NewReturnsTopic()) + r.register(clientchanges.NewClientChangesTopic()) + r.register(goodsorder.NewGoodsOrderTopic()) + r.register(shipmentssoh.NewShipmentsSOHTopic()) + r.register(transactionpassport.NewTransactionPassportTopic()) + r.register(rateslogistics.NewRatesLogisticsTopic()) + r.register(receipts.NewReceiptsTopic()) + r.register(paymentscashless.NewPaymentsCashlessTopic()) + r.register(managerexpenses.NewManagerExpensesTopic()) + r.register(nonstandardcontract.NewNonstandardContractTopic()) + r.register(otkconditions.NewOtkConditionsTopic()) + + // Свободные темы (без подтем) + freeTopics := []struct{ code, name, template, instructions string }{ + {"delivery_clients", "Доставка клиентам/на склад", "Иванов Иван Иванович\nТел 89781234567\nПаспорт 1234 567890\nДАФ н862нн46 п/п АА8473|46\n\n61 бц с ад - 52 кор\nЧП000001676\n\nЕПР-СтройКрым", ""}, + {"v_shipments", "В. Отгрузки", "ООО Нива на 370 тыс. руб. под 19%", ""}, + {"shipments", "Отгрузки", "", "Если не входит в рамки согласованного лимита, добавь руководителя соответствующего филиала к согласованию через кнопку 'Добавить согласующего'"}, + {"vacancies", "Вакансии", "", ""}, + {"delivery_rates_ap", "Ставки доставки АП", "Прошу согласовать доставку 14 кор преформы клиенту Олег-Выдув-Сочи за 34 000 руб.", ""}, + {"freelancers_approval", "Утверждение фрилансеров", "Одного помощника на выгрузку полной фуры с крышкой ручкой с КТ на 23.04.2026 на весь день", ""}, + {"non_working_day", "Выход в нерабочий день", "Прошу вывести склад для учета c 25.04 по 26.04", ""}, + {"suggestions", "Предложения и пожелания", "", ""}, + {"cash_balance", "Остаток в кассах", "", ""}, + {"client_sales", "Продажи по клиенту", "", ""}, + {"manager_expenses_report", "Проведенные расходы по менеджеру", "", ""}, + {"remote_access", "Согласование удаленной работы", "Прошу согласовать удалённый выход на работу 06.06.2026", ""}, + } + for _, t := range freeTopics { + r.register(free.NewFreeTopic(t.code, t.name, t.template)) + } +} + +func (r *Registry) register(t approvalflow.Topic) { + r.topics[t.Code()] = t + r.order = append(r.order, t.Code()) +} + +func (r *Registry) Get(code string) (approvalflow.Topic, error) { + t, ok := r.topics[code] + if !ok { + return nil, fmt.Errorf("unknown topic code: %s", code) + } + return t, nil +} + +func (r *Registry) All() []approvalflow.Topic { + result := make([]approvalflow.Topic, 0, len(r.order)) + for _, code := range r.order { + result = append(result, r.topics[code]) + } + return result +} diff --git a/service/telegram_service/handlers/approval/revision.go b/service/telegram_service/handlers/approval/revision.go new file mode 100644 index 0000000..329340a --- /dev/null +++ b/service/telegram_service/handlers/approval/revision.go @@ -0,0 +1,495 @@ +package approval + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/telegram_service/keyboard" + "bitrix_balancer_api/telegram_service/state" + "context" + "fmt" + "time" + + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" + "github.com/sirupsen/logrus" +) + +// HandleRevisionCallback — согласующий нажал "Вернуть на доработку" +func (h *Handler) HandleRevisionCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64) { + chatID := cq.Message.Chat.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck + + msg := tgbotapi.NewMessage(chatID, fmt.Sprintf( + "🔄 Заявка #%d — вернуть на доработку\n\n"+ + "Хотите указать причину?", + approvalID, + )) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildRevisionRejectOptions(approvalID) + bot.Send(msg) //nolint:errcheck +} + +// HandleRevisionCommentStart — согласующий хочет указать причину доработки +func (h *Handler) HandleRevisionCommentStart(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64) { + ctx := context.Background() + chatID := cq.Message.Chat.ID + telegramID := cq.From.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck + + // Сохраняем в Redis ожидание комментария (аналогично reject) + revisionKey := fmt.Sprintf("appr_revision_pending:%d", telegramID) + if err := h.ipc.RedisClient.Set(ctx, revisionKey, fmt.Sprintf("%d", approvalID), 10*time.Minute); err != nil { + logrus.Errorf("HandleRevisionCommentStart: Set err=%v", err) + return + } + + sendText(bot, chatID, "Укажите причину возврата на доработку:") +} + +// HandleRevisionWithComment — основной метод возврата на доработку +func (h *Handler) HandleRevisionWithComment(bot *tgbotapi.BotAPI, approverChatID int64, approverTelegramID int64, approvalID uint64, comment string) { + ctx := context.Background() + + approver, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, approverTelegramID) + if err != nil || approver == nil || approver.ID == nil { + sendText(bot, approverChatID, "⚠️ Пользователь не найден.") + return + } + + approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID) + if err != nil || approval == nil { + sendText(bot, approverChatID, "⚠️ Заявка не найдена.") + return + } + + if approval.Status != nil && *approval.Status != "pending" { + sendText(bot, approverChatID, "⚠️ Заявку можно вернуть на доработку только в статусе 'На согласовании'.") + return + } + + now := time.Now() + revisionStatus := "revision" + revisionCount := 1 + if approval.RevisionCount != nil { + revisionCount = *approval.RevisionCount + 1 + } + + approval.Status = &revisionStatus + approval.RevisionComment = &comment + approval.RevisionByID = approver.ID + approval.RevisionAt = &now + approval.RevisionCount = &revisionCount + + if _, _, err := h.ipc.Database.Approval.UpdateApprovalDB(ctx, nil, approval); err != nil { + logrus.Errorf("HandleRevisionWithComment: UpdateApprovalDB err=%v", err) + sendText(bot, approverChatID, "Ошибка при возврате заявки.") + return + } + + activeStep, _ := h.ipc.Database.ApprovalStep.GetActiveStepDB(ctx, approvalID) + if activeStep != nil { + returnedAt := now + activeStep.ReturnedAt = &returnedAt + h.ipc.Database.ApprovalStep.UpdateApprovalStepDB(ctx, nil, activeStep) //nolint:errcheck + } + + topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID) + + content := "—" + if approval.Content != nil { + content = *approval.Content + } + + commentText := "" + if comment != "" { + commentText = fmt.Sprintf("\n💬 Причина: %s", comment) + } + + approvalCard := h.buildApprovalCard(ctx, approval, h.getCollectedFromApproval(ctx, approval)) + + sendText(bot, approverChatID, fmt.Sprintf( + "🔄 Заявка #%d возвращена на доработку\n\n%s%s", + approvalID, approvalCard, commentText, + )) + + if approval.InitiatorID != nil { + initiator, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID) + if initiator != nil && initiator.TelegramID != nil { + h.notifyInitiatorRevision(bot, initiator, approval, approver, comment, topicFullName, content) + } + } +} + +// notifyInitiatorRevision — сигнатура не меняется, topicFullName теперь содержит "Категория: Тема". +func (h *Handler) notifyInitiatorRevision( + bot *tgbotapi.BotAPI, + initiator *typescore.User, + approval *typescore.Approval, + approver *typescore.User, + comment string, + topicFullName string, + content string, +) { + if initiator.TelegramID == nil || approval.ID == nil { + return + } + + approverName := "—" + if approver != nil && approver.FullName != nil { + approverName = *approver.FullName + } + + commentText := "" + if comment != "" { + commentText = fmt.Sprintf("\n💬 Причина: %s", comment) + } + + revisionCount := 1 + if approval.RevisionCount != nil { + revisionCount = *approval.RevisionCount + } + + text := fmt.Sprintf( + "🔄 Заявка #%d возвращена на доработку\n\n"+ + "📋 Тема: %s\n"+ + "📝 Текущий текст: %s\n"+ + "👤 Вернул: %s%s\n\n"+ + "🔢 Доработка #%d\n\n"+ + "Что хотите сделать?", + *approval.ID, topicFullName, content, approverName, commentText, revisionCount, + ) + + msg := tgbotapi.NewMessage(*initiator.TelegramID, text) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildRevisionOptions(*approval.ID) + bot.Send(msg) //nolint:errcheck +} + +// HandleRevisionEditText — инициатор хочет изменить текст +func (h *Handler) HandleRevisionEditText(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64) { + ctx := context.Background() + chatID := cq.Message.Chat.ID + telegramID := cq.From.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck + + // Проверяем что это инициатор + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || user == nil || user.ID == nil { + return + } + + approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID) + if err != nil || approval == nil { + sendText(bot, chatID, "⚠️ Заявка не найдена.") + return + } + + if approval.InitiatorID == nil || *approval.InitiatorID != *user.ID { + sendText(bot, chatID, "⚠️ Только инициатор может редактировать заявку.") + return + } + + if approval.Status == nil || *approval.Status != "revision" { + sendText(bot, chatID, "⚠️ Редактирование доступно только для заявок на доработке.") + return + } + + // Сохраняем состояние ожидания нового текста + revisionState := &state.RevisionFlowState{ + ApprovalID: approvalID, + Stage: "await_content", + } + h.States.SetRevisionFlow(ctx, telegramID, revisionState) //nolint:errcheck + + currentContent := "—" + if approval.Content != nil { + currentContent = *approval.Content + } + + sendText(bot, chatID, fmt.Sprintf( + "✏️ Редактирование заявки #%d\n\n"+ + "📝 Текущий текст:\n%s\n\n"+ + "Введите новый текст:", + approvalID, currentContent, + )) +} + +// HandleRevisionTextInput — обработка нового текста от инициатора +func (h *Handler) HandleRevisionTextInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) bool { + ctx := context.Background() + telegramID := msg.From.ID + chatID := msg.Chat.ID + + revisionState, err := h.States.GetRevisionFlow(ctx, telegramID) + if err != nil || revisionState == nil || revisionState.Stage != "await_content" { + return false + } + + h.States.ClearRevisionFlow(ctx, telegramID) //nolint:errcheck + + approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, revisionState.ApprovalID) + if err != nil || approval == nil { + sendText(bot, chatID, "⚠️ Заявка не найдена.") + return true + } + + newContent := msg.Text + approval.Content = &newContent + + if _, _, err := h.ipc.Database.Approval.UpdateApprovalDB(ctx, nil, approval); err != nil { + logrus.Errorf("HandleRevisionTextInput: UpdateApprovalDB err=%v", err) + sendText(bot, chatID, "Ошибка при сохранении текста.") + return true + } + + sendText(bot, chatID, fmt.Sprintf( + "✅ Текст обновлён\n\n"+ + "📝 Новый текст:\n%s\n\n"+ + "Что ещё хотите сделать?", + newContent, + )) + + // Показываем опции снова + optMsg := tgbotapi.NewMessage(chatID, fmt.Sprintf("📋 Заявка #%d на доработке:", revisionState.ApprovalID)) + optMsg.ParseMode = "HTML" + optMsg.ReplyMarkup = keyboard.BuildRevisionOptions(revisionState.ApprovalID) + bot.Send(optMsg) //nolint:errcheck + + return true +} + +// HandleRevisionResubmit — инициатор отправляет заявку на повторное согласование +func (h *Handler) HandleRevisionResubmit(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64) { + ctx := context.Background() + chatID := cq.Message.Chat.ID + telegramID := cq.From.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck + + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || user == nil || user.ID == nil { + return + } + + approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID) + if err != nil || approval == nil { + sendText(bot, chatID, "⚠️ Заявка не найдена.") + return + } + + if approval.InitiatorID == nil || *approval.InitiatorID != *user.ID { + sendText(bot, chatID, "⚠️ Только инициатор может отправить заявку на повторное согласование.") + return + } + + if approval.Status == nil || *approval.Status != "revision" { + sendText(bot, chatID, "⚠️ Заявка не находится на доработке.") + return + } + + // Возвращаем статус pending + pendingStatus := "pending" + approval.Status = &pendingStatus + approval.RevisionComment = nil + + if _, _, err := h.ipc.Database.Approval.UpdateApprovalDB(ctx, nil, approval); err != nil { + logrus.Errorf("HandleRevisionResubmit: UpdateApprovalDB err=%v", err) + sendText(bot, chatID, "Ошибка при отправке заявки.") + return + } + + // Сбрасываем шаг согласования обратно в pending и убираем ReturnedAt + activeStep, err := h.ipc.Database.ApprovalStep.GetActiveStepDB(ctx, approvalID) + if err != nil || activeStep == nil { + logrus.Warnf("HandleRevisionResubmit: active step not found approvalID=%d", approvalID) + sendText(bot, chatID, "⚠️ Шаг согласования не найден.") + return + } + + pendingStepStatus := "pending" + activeStep.Status = &pendingStepStatus + activeStep.ReturnedAt = nil + h.ipc.Database.ApprovalStep.UpdateApprovalStepDB(ctx, nil, activeStep) //nolint:errcheck + + sendText(bot, chatID, fmt.Sprintf( + "✅ Заявка #%d отправлена на повторное согласование\n\n"+ + "Согласующий получил уведомление.", + approvalID, + )) + + // Уведомляем согласующего + if activeStep.ApproverID != nil { + approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *activeStep.ApproverID) + if approver != nil && approver.TelegramID != nil { + topicCode := h.getTopicCodeByApproval(ctx, approval) + topic, _ := h.Registry.Get(topicCode) + + collected := h.getCollectedFromApproval(ctx, approval) + + // Подгружаем актуальные файлы + files, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, approvalID) + approval.Files = files + + revisionCount := 1 + if approval.RevisionCount != nil { + revisionCount = *approval.RevisionCount + } + + initiatorName := "—" + if user.FullName != nil { + initiatorName = *user.FullName + } + + text := fmt.Sprintf( + "🔄 Заявка #%d возвращена после доработки (доработка #%d)\n\n"+ + "👤 Инициатор: %s\n", + approvalID, revisionCount, initiatorName, + ) + + status := "" + if approval.Status != nil { + status = *approval.Status + } + + if topic != nil { + notifier := NewNotifier(h.ipc, topic) + // Добавляем заголовок о доработке к стандартному сообщению + fullText := text + notifier.formatApprovalMessage(user, collected) + + if len(files) == 0 { + msg := tgbotapi.NewMessage(*approver.TelegramID, fullText) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildApproverDecision(approvalID, status, len(files) > 0, len(files)) + bot.Send(msg) //nolint:errcheck + } else { + notifier.sendFilesToRecipient(bot, *approver.TelegramID, approval, fullText, keyboard.BuildApproverDecision(approvalID, status, len(files) > 0, len(files))) + } + } else { + msg := tgbotapi.NewMessage(*approver.TelegramID, text) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildApproverDecision(approvalID, status, len(files) > 0, len(files)) + bot.Send(msg) //nolint:errcheck + } + } + } +} + +// HandleRevisionAddFiles — инициатор хочет добавить файлы +func (h *Handler) HandleRevisionAddFiles(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64) { + ctx := context.Background() + chatID := cq.Message.Chat.ID + telegramID := cq.From.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck + + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || user == nil || user.ID == nil { + return + } + + approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID) + if err != nil || approval == nil || approval.InitiatorID == nil || *approval.InitiatorID != *user.ID { + sendText(bot, chatID, "⚠️ Нет прав или заявка не найдена.") + return + } + + if approval.Status == nil || *approval.Status != "revision" { + sendText(bot, chatID, "⚠️ Добавление файлов доступно только для заявок на доработке.") + return + } + + // Используем существующий механизм через Redis — тот же что HandleAttachFileStart + key := fmt.Sprintf("appr_revision_attach_file:%d", telegramID) + if err := h.ipc.RedisClient.Set(ctx, key, fmt.Sprintf("%d", approvalID), 10*time.Minute); err != nil { + logrus.Errorf("HandleRevisionAddFiles: Redis.Set err=%v", err) + return + } + + msg := tgbotapi.NewMessage(chatID, + fmt.Sprintf("📎 Добавление файла к заявке #%d\n\nОтправьте фото или документ:", approvalID), + ) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildRevisionAttachCancel(approvalID) + bot.Send(msg) //nolint:errcheck +} + +// HandleRevisionFileInput — обрабатывает файл от инициатора при доработке. +// Вызывается ДО HandleAttachFileInput в update_handler, проверяет свой Redis ключ. +func (h *Handler) HandleRevisionFileInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) bool { + ctx := context.Background() + telegramID := msg.From.ID + chatID := msg.Chat.ID + + key := fmt.Sprintf("appr_revision_attach_file:%d", telegramID) + val, err := h.ipc.RedisClient.Get(ctx, key) + if err != nil || val == "" { + return false + } + + var approvalID uint64 + fmt.Sscanf(val, "%d", &approvalID) + + var fileID, fileName string + switch { + case msg.Photo != nil && len(msg.Photo) > 0: + best := msg.Photo[len(msg.Photo)-1] + fileID = best.FileID + fileName = fmt.Sprintf("photo_%s.jpg", time.Now().Format("20060102_150405")) + case msg.Document != nil: + fileID = msg.Document.FileID + fileName = msg.Document.FileName + default: + sendText(bot, chatID, "⚠️ Пожалуйста, отправьте фото или документ.") + return true + } + + fileURL, err := bot.GetFileDirectURL(fileID) + if err != nil { + logrus.Errorf("HandleRevisionFileInput: GetFileDirectURL err=%v", err) + sendText(bot, chatID, "Ошибка при получении файла.") + return true + } + + base64Data, err := fetchFileAsBase64(fileURL, h.ipc.Config.Telegram) // используем существующую функцию + if err != nil { + logrus.Errorf("HandleRevisionFileInput: fetchFileAsBase64 err=%v", err) + sendText(bot, chatID, "Ошибка при обработке файла.") + return true + } + + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || user == nil || user.ID == nil { + return true + } + + file := &typescore.ApprovalFile{ + ApprovalID: &approvalID, + FileBase64: &base64Data, + FileName: &fileName, + AttachedByID: user.ID, + } + + if _, _, err := h.ipc.Database.ApprovalFile.CreateApprovalFileDB(ctx, nil, file); err != nil { + logrus.Errorf("HandleRevisionFileInput: CreateApprovalFileDB err=%v", err) + sendText(bot, chatID, "Ошибка при сохранении файла.") + return true + } + + h.ipc.RedisClient.Del(ctx, key) //nolint:errcheck + + sendText(bot, chatID, fmt.Sprintf("✅ Файл %s прикреплён к заявке #%d", fileName, approvalID)) + + // Показываем опции снова + optMsg := tgbotapi.NewMessage(chatID, fmt.Sprintf("📋 Заявка #%d на доработке:", approvalID)) + optMsg.ParseMode = "HTML" + optMsg.ReplyMarkup = keyboard.BuildRevisionOptions(approvalID) + bot.Send(optMsg) //nolint:errcheck + + return true +} diff --git a/service/telegram_service/handlers/approval/selection_approver.go b/service/telegram_service/handlers/approval/selection_approver.go new file mode 100644 index 0000000..ba11a5e --- /dev/null +++ b/service/telegram_service/handlers/approval/selection_approver.go @@ -0,0 +1,378 @@ +package approval + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/telegram_service/keyboard" + "bitrix_balancer_api/telegram_service/state" + "context" + "fmt" + "strings" + + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" + "github.com/sirupsen/logrus" +) + +func (h *Handler) showApproverSelection(bot *tgbotapi.BotAPI, ctx context.Context, chatID int64, telegramID int64, approvalTopic *typescore.ApprovalTopic) { + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || user == nil || user.ID == nil || user.DepartmentID == nil { + return + } + + // Получаем список согласующих для этой темы + approvers, err := h.getAvailableApproversForTopic(ctx, *user.ID, *user.DepartmentID, approvalTopic) + if err != nil { + logrus.Errorf("showApproverSelection: getAvailableApproversForTopic err=%v", err) + sendText(bot, chatID, "Ошибка при получении списка согласующих.") + return + } + + if len(approvers) == 0 { + sendText(bot, chatID, "⚠️ Нет доступных согласующих для этой темы.") + h.States.Clear(ctx, telegramID) //nolint:errcheck + return + } + + msg := tgbotapi.NewMessage(chatID, "👤 Выберите согласующего:") + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildApproverSelectionMenu(approvers, 0) + bot.Send(msg) //nolint:errcheck +} + +func (h *Handler) HandleApproverSelectionCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approverID uint64) { + ctx := context.Background() + chatID := cq.Message.Chat.ID + telegramID := cq.From.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck + + flowState, err := h.States.Get(ctx, telegramID) + if err != nil || flowState == nil { + sendText(bot, chatID, "⚠️ Состояние утеряно. Начните заново.") + return + } + + if !flowState.AwaitApproverSelection { + logrus.Warnf("HandleApproverSelectionCallback: not awaiting approver selection, userID=%d", telegramID) + return + } + + selected, err := h.ipc.Database.User.GetUserByIDDB(ctx, approverID) + if err != nil || selected == nil { + sendText(bot, chatID, "⚠️ Согласующий не найден.") + return + } + + selectedName := "выбранный согласующий" + if selected.FullName != nil { + selectedName = *selected.FullName + } + + flowState.SelectedApproverID = approverID + flowState.AwaitApproverSelection = false + h.States.Set(ctx, telegramID, flowState) //nolint:errcheck + + sendText(bot, chatID, fmt.Sprintf("✅ Выбран согласующий: %s", selectedName)) + + h.continueFlowAfterInput(bot, ctx, chatID, telegramID, flowState) +} + +func (h *Handler) HandleApproverSelectionPageCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, page int) { + ctx := context.Background() + chatID := cq.Message.Chat.ID + telegramID := cq.From.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck + + flowState, err := h.States.Get(ctx, telegramID) + if err != nil || flowState == nil { + sendText(bot, chatID, "⚠️ Состояние утеряно. Начните заново.") + return + } + + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || user == nil || user.ID == nil || user.DepartmentID == nil { + return + } + + topic, _ := h.Registry.Get(flowState.TopicCode) + if topic == nil { + return + } + + topicCode, _ := topic.TopicCodeFromCollected(flowState.Collected) + approvalTopic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByCodeDB(ctx, topicCode) + if approvalTopic == nil { + return + } + + approvers, err := h.getAvailableApproversForTopic(ctx, *user.ID, *user.DepartmentID, approvalTopic) + if err != nil { + logrus.Errorf("HandleApproverSelectionPageCallback: getAvailableApproversForTopic err=%v", err) + return + } + + msg := tgbotapi.NewMessage(chatID, "👤 Выберите согласующего:") + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildApproverSelectionMenu(approvers, page) + bot.Send(msg) //nolint:errcheck +} + +func (h *Handler) getAvailableApproversForTopic(ctx context.Context, userID, departmentID uint64, approvalTopic *typescore.ApprovalTopic) ([]*typescore.User, error) { + if approvalTopic.ID == nil || approvalTopic.CategoryID == nil { + return nil, fmt.Errorf("invalid topic") + } + + // Получаем все иерархии для этого пользователя и отдела + hierarchies, _, err := h.ipc.Database.UserHierarchy.GetUserHierarchyListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.UserHierarchy{ + SubordinateID: &userID, + DepartmentID: &departmentID, + }, + }) + if err != nil { + return nil, err + } + + // Собираем уникальных согласующих для этой темы или категории + approverIDs := make(map[uint64]bool) + for _, hier := range hierarchies { + if hier.ApproverID == nil { + continue + } + + // Проверяем совпадение по теме + if hier.TopicID != nil && *hier.TopicID == *approvalTopic.ID { + approverIDs[*hier.ApproverID] = true + continue + } + + // Проверяем совпадение по категории + if hier.TopicCategoryID != nil && *hier.TopicCategoryID == *approvalTopic.CategoryID { + approverIDs[*hier.ApproverID] = true + } + } + + var approvers []*typescore.User + for approverID := range approverIDs { + approver, err := h.ipc.Database.User.GetUserByIDDB(ctx, approverID) + if err == nil && approver != nil { + approvers = append(approvers, approver) + } + } + + return approvers, nil +} + +func (h *Handler) finalizeAndSubmit(bot *tgbotapi.BotAPI, ctx context.Context, chatID int64, telegramID int64, flowState *state.ApprovalFlowState) { + approval, err := h.submitApproval(ctx, bot, telegramID, flowState) + if err != nil { + logrus.Errorf("finalizeAndSubmit: submitApproval error: %v", err) + + errMsg := err.Error() + if !strings.HasPrefix(errMsg, "⚠️") { + errMsg = "Произошла ошибка при отправке заявки. Попробуйте позже." + } + + msg := tgbotapi.NewMessage(chatID, errMsg) + msg.ParseMode = "HTML" + bot.Send(msg) //nolint:errcheck + return + } + + if approval == nil || approval.ID == nil { + logrus.Error("finalizeAndSubmit: approval is nil after submitApproval") + bot.Send(tgbotapi.NewMessage(chatID, "📤 Отправлено на согласование")) //nolint:errcheck + return + } + + var approvalTopic *typescore.ApprovalTopic + if approval.TopicID != nil { + approvalTopic, _ = h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID) + } + isAnyOf := approvalTopic != nil && approvalTopic.ApprovalMode != nil && *approvalTopic.ApprovalMode == "any_of" + + approverLine := "—" + + allSteps, _, _ := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalStep{ApprovalID: approval.ID}, + }) + + if isAnyOf { + var names []string + for _, s := range allSteps { + if s.Status == nil || (*s.Status != "pending" && *s.Status != "waiting") { + continue + } + if s.ApproverID != nil { + if approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *s.ApproverID); approver != nil && approver.FullName != nil { + names = append(names, *approver.FullName) + } + } + } + if len(names) > 0 { + approverLine = strings.Join(names, " или ") + } + } else { + if len(allSteps) > 0 { + var firstStep *typescore.ApprovalStep + for _, s := range allSteps { + if s.StepOrder == nil { + continue + } + if firstStep == nil || *s.StepOrder < *firstStep.StepOrder { + firstStep = s + } + } + + if firstStep != nil && firstStep.ApproverID != nil { + if approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *firstStep.ApproverID); approver != nil && approver.FullName != nil { + approverLine = *approver.FullName + } + } + } + } + + topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID) + + content := "—" + if approval.Content != nil { + content = *approval.Content + } + + var confirmMsg string + if isAnyOf { + confirmMsg = fmt.Sprintf( + "📤 Заявка #%d отправлена на согласование\n\n"+ + "👤 Согласует один из: %s\n\n"+ + "📋 Тема: %s\n"+ + "📝 Текст: %s", + *approval.ID, approverLine, topicFullName, content, + ) + } else { + confirmMsg = fmt.Sprintf( + "📤 Заявка #%d отправлена на согласование\n\n"+ + "👤 Согласующий: %s\n\n"+ + "📋 Тема: %s\n"+ + "📝 Текст: %s", + *approval.ID, approverLine, topicFullName, content, + ) + } + + msgChat := tgbotapi.NewMessage(chatID, confirmMsg) + msgChat.ParseMode = "HTML" + + approvalStatus := "pending" + if approval.Status != nil { + approvalStatus = *approval.Status + } + msgChat.ReplyMarkup = keyboard.BuildInitiatorCard(*approval.ID, approvalStatus, len(approval.Files) > 0, len(approval.Files)) + + bot.Send(msgChat) //nolint:errcheck +} + +// createTasksForApproval создаёт задачи для исполнителей на основе конфигурации темы +func (h *Handler) createTasksForApproval( + bot *tgbotapi.BotAPI, + ctx context.Context, + approval *typescore.Approval, + initiator *typescore.User, +) { + if approval == nil || approval.TopicID == nil { + return + } + + topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID) + if topic == nil { + return + } + + topicExecutors, err := h.ipc.Database.ApprovalTopicExecutor.GetExecutorsByTopicIDDB(ctx, *approval.TopicID) + if err != nil { + logrus.Errorf("createTasksForApproval: GetExecutorsByTopicIDDB err=%v", err) + return + } + + if len(topicExecutors) == 0 { + logrus.Infof("createTasksForApproval: no executors configured for topicID=%d", *approval.TopicID) + return + } + + meta, _ := typescore.ParseApprovalMetadata(approval.Metadata) + systemsToProcess := meta.SelectedSystems + if len(systemsToProcess) == 0 { + systemsToProcess = []string{"all"} + } + + logrus.Infof("createTasksForApproval: topicID=%d systems=%v executors=%d", + *approval.TopicID, systemsToProcess, len(topicExecutors)) + + taskCounter := 0 + + for _, system := range systemsToProcess { + for _, topicExec := range topicExecutors { + if topicExec.UserID == nil { + continue + } + + if topicExec.TargetSystem != nil && *topicExec.TargetSystem != "all" && *topicExec.TargetSystem != system { + continue + } + + if topicExec.TaskText == nil || *topicExec.TaskText == "" { + continue + } + + executor, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *topicExec.UserID) + if executor == nil || executor.ID == nil { + continue + } + + taskText := *topicExec.TaskText + systemLabel := "" + if system != "all" && system != "" { + switch system { + case "okb": + systemLabel = "[ОКБ] " + case "1c": + systemLabel = "[1С] " + } + taskText = systemLabel + taskText + } + + taskStatus := "waiting" + if taskCounter == 0 { + taskStatus = "pending" + } + + stepOrder := taskCounter + requireFile := false + if topicExec.RequireFile != nil { + requireFile = *topicExec.RequireFile + } + + createdTask, _, err := h.ipc.Database.ApprovalTasks.CreateApprovalTaskDB(ctx, nil, &typescore.ApprovalTask{ + ApprovalID: approval.ID, + ExecutorID: executor.ID, + TaskText: &taskText, + Status: &taskStatus, + StepOrder: &stepOrder, + RequireFile: &requireFile, + TopicExecutorID: topicExec.ID, + }, true) + if err != nil { + logrus.Errorf("createTasksForApproval: CreateApprovalTask system=%s executor=%d err=%v", system, *executor.ID, err) + continue + } + + if createdTask != nil && taskStatus == "pending" && executor.TelegramID != nil { + h.notifyExecutor(bot, ctx, executor, initiator, approval, createdTask) + } + + taskCounter++ + } + } + + logrus.Infof("createTasksForApproval: created %d tasks for approvalID=%d", taskCounter, *approval.ID) +} diff --git a/service/telegram_service/handlers/approval/selection_first_approver.go b/service/telegram_service/handlers/approval/selection_first_approver.go new file mode 100644 index 0000000..22c42ec --- /dev/null +++ b/service/telegram_service/handlers/approval/selection_first_approver.go @@ -0,0 +1,185 @@ +package approval + +import ( + "bitrix_balancer_api/core/typescore" + "context" + "fmt" + + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" + "github.com/sirupsen/logrus" + + "bitrix_balancer_api/telegram_service/keyboard" + "bitrix_balancer_api/telegram_service/state" +) + +// showFirstApproverSelection показывает список пользователей с нужной ролью +func (h *Handler) showFirstApproverSelection( + bot *tgbotapi.BotAPI, + ctx context.Context, + chatID int64, + telegramID int64, + roleCode string, + roleLabel string, +) { + users, err := h.ipc.Database.User.GetUsersByRoleCodeDB(ctx, roleCode) + if err != nil { + logrus.Errorf("showFirstApproverSelection: GetUsersByRoleCodeDB roleCode=%s err=%v", roleCode, err) + sendText(bot, chatID, "Ошибка при получении списка пользователей.") + h.States.Clear(ctx, telegramID) //nolint:errcheck + return + } + + if len(users) == 0 { + // Пользователей с такой ролью нет — пропускаем шаг + logrus.Warnf("showFirstApproverSelection: no users with role=%s, skipping", roleCode) + flowState, err := h.States.Get(ctx, telegramID) + if err != nil || flowState == nil { + return + } + flowState.AwaitFirstApproverSelection = false + h.States.Set(ctx, telegramID, flowState) //nolint:errcheck + h.continueFlowAfterInput(bot, ctx, chatID, telegramID, flowState) + return + } + + msg := tgbotapi.NewMessage(chatID, fmt.Sprintf( + "👤 Выберите %s\n\n"+ + "Этот пользователь согласует заявку первым.", + roleLabel, + )) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildFirstApproverSelectionMenu(users, 0) + bot.Send(msg) //nolint:errcheck +} + +// getRoleLabelByCode — вспомогательный метод получения названия роли +func (h *Handler) getRoleLabelByCode(ctx context.Context, roleCode string) *typescore.Role { + roleList, _, err := h.ipc.Database.Role.GetRolesListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.Role{ + Code: &roleCode, + }, + }) + if err != nil || roleList == nil || len(roleList) < 1 || roleList[0] == nil { + return nil + } + return roleList[0] +} + +// HandleFirstApproverSelectCallback — пользователь выбрал первого согласующего +func (h *Handler) HandleFirstApproverSelectCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, userID uint64) { + ctx := context.Background() + chatID := cq.Message.Chat.ID + telegramID := cq.From.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck + + flowState, err := h.States.Get(ctx, telegramID) + if err != nil || flowState == nil { + sendText(bot, chatID, "⚠️ Состояние утеряно. Начните заново.") + return + } + + if !flowState.AwaitFirstApproverSelection { + logrus.Warnf("HandleFirstApproverSelectCallback: not awaiting first approver, userID=%d", telegramID) + return + } + + selected, err := h.ipc.Database.User.GetUserByIDDB(ctx, userID) + if err != nil || selected == nil { + sendText(bot, chatID, "⚠️ Пользователь не найден.") + return + } + + selectedName := "выбранный пользователь" + if selected.FullName != nil { + selectedName = *selected.FullName + } + + flowState.SelectedFirstApproverID = userID + flowState.AwaitFirstApproverSelection = false + h.States.Set(ctx, telegramID, flowState) //nolint:errcheck + + sendText(bot, chatID, fmt.Sprintf("✅ Выбран первый согласующий: %s", selectedName)) + + h.continueFlowAfterInput(bot, ctx, chatID, telegramID, flowState) +} + +func (h *Handler) HandleFirstApproverPageCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, page int) { + ctx := context.Background() + chatID := cq.Message.Chat.ID + telegramID := cq.From.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + + flowState, err := h.States.Get(ctx, telegramID) + if err != nil || flowState == nil || !flowState.AwaitFirstApproverSelection { + return + } + + topic, _ := h.Registry.Get(flowState.TopicCode) + if topic == nil { + return + } + topicCode, _ := topic.TopicCodeFromCollected(flowState.Collected) + approvalTopic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByCodeDB(ctx, topicCode) + if approvalTopic == nil || approvalTopic.FirstApproverRoleCode == nil { + return + } + + roleCode := *approvalTopic.FirstApproverRoleCode + users, err := h.ipc.Database.User.GetUsersByRoleCodeDB(ctx, roleCode) + if err != nil { + return + } + + editMsg := tgbotapi.NewEditMessageReplyMarkup( + chatID, + cq.Message.MessageID, + keyboard.BuildFirstApproverSelectionMenu(users, page), + ) + bot.Request(editMsg) //nolint:errcheck +} + +// getFirstApproverRoleForFlow возвращает тему и код роли для первого согласующего +func (h *Handler) getFirstApproverRoleForFlow( + ctx context.Context, + flowState *state.ApprovalFlowState, +) (*typescore.ApprovalTopic, string, string) { + topic, _ := h.Registry.Get(flowState.TopicCode) + if topic == nil { + return nil, "", "" + } + + topicCode, _ := topic.TopicCodeFromCollected(flowState.Collected) + approvalTopic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByCodeDB(ctx, topicCode) + if approvalTopic == nil || approvalTopic.FirstApproverRoleCode == nil { + return nil, "", "" + } + + // Получаем название роли для отображения + roleList, _, err := h.ipc.Database.Role.GetRolesListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.Role{ + Code: approvalTopic.FirstApproverRoleCode, + }, + }) + if err != nil { + logrus.Errorf("getFirstApproverRoleForFlow err=%v", err) + return nil, "", "" + } + if roleList == nil || len(roleList) == 0 { + logrus.Errorf("getFirstApproverRoleForFlow. Role not found err=%v", err) + return nil, "", "" + } + role := roleList[0] + if role == nil || role.Code == nil { + logrus.Errorf("getFirstApproverRoleForFlow. Role not found err=%v", err) + return nil, "", "" + } + roleLabel := *role.Code + if role.Name != nil { + roleLabel = *role.Name + } + + return approvalTopic, *role.Code, roleLabel +} diff --git a/service/telegram_service/handlers/approval/selection_observer.go b/service/telegram_service/handlers/approval/selection_observer.go new file mode 100644 index 0000000..4441ecf --- /dev/null +++ b/service/telegram_service/handlers/approval/selection_observer.go @@ -0,0 +1,246 @@ +package approval + +import ( + "bitrix_balancer_api/core/typescore" + "context" + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" + "github.com/sirupsen/logrus" + + "bitrix_balancer_api/telegram_service/keyboard" + "bitrix_balancer_api/telegram_service/state" +) + +// showObserverSelection показывает экран выбора наблюдателей +func (h *Handler) showObserverSelection( + bot *tgbotapi.BotAPI, + ctx context.Context, + chatID int64, + telegramID int64, + flowState *state.ApprovalFlowState, + approvalTopic *typescore.ApprovalTopic, +) { + observers, err := h.getAvailableObservers(ctx) + if err != nil || len(observers) == 0 { + // Если выбор обязателен, но наблюдателей нет — блокируем создание заявки + isRequired := approvalTopic != nil && + approvalTopic.RequireObserverSelection != nil && + *approvalTopic.RequireObserverSelection + + if isRequired { + sendText(bot, chatID, + "⚠️ Для этой темы обязательно выбрать наблюдателя,\n"+ + "но в системе нет пользователей с ролью наблюдателя.\n\n"+ + "Обратитесь к администратору.") + flowState.AwaitObserverSelection = false + flowState.ObserverSelectionDone = false // не помечаем как выполненное + h.States.Set(ctx, telegramID, flowState) //nolint:errcheck + return + } + + flowState.AwaitObserverSelection = false + flowState.ObserverSelectionDone = true + h.States.Clear(ctx, telegramID) //nolint:errcheck + h.finalizeAndSubmit(bot, ctx, chatID, telegramID, flowState) + return + } + + isRequired := approvalTopic != nil && + approvalTopic.RequireObserverSelection != nil && + *approvalTopic.RequireObserverSelection + + var text string + if isRequired { + text = "👁 Выберите наблюдателей для заявки\n\n" + + "⚠️ Выберите менеджера, чья это отгрузка." + } else { + text = "👁 Выберите наблюдателей для заявки\n" + + "Они получат уведомления, но не смогут влиять на решение.\n" + + "Можно выбрать несколько или пропустить." + } + + msg := tgbotapi.NewMessage(chatID, text) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildObserverSelectionMenu(observers, flowState.SelectedObserverIDs, 0, isRequired) + bot.Send(msg) //nolint:errcheck +} + +// HandleObserverToggleCallback — пользователь нажал на наблюдателя (toggle) +func (h *Handler) HandleObserverToggleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, observerID uint64) { + ctx := context.Background() + chatID := cq.Message.Chat.ID + telegramID := cq.From.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + + flowState, err := h.States.Get(ctx, telegramID) + if err != nil || flowState == nil || !flowState.AwaitObserverSelection { + return + } + + found := false + newIDs := make([]uint64, 0, len(flowState.SelectedObserverIDs)) + for _, id := range flowState.SelectedObserverIDs { + if id == observerID { + found = true + } else { + newIDs = append(newIDs, id) + } + } + if !found { + newIDs = append(newIDs, observerID) + } + flowState.SelectedObserverIDs = newIDs + + if err := h.States.Set(ctx, telegramID, flowState); err != nil { + logrus.Errorf("HandleObserverToggleCallback: Set state err=%v", err) + return + } + + var approvalTopic *typescore.ApprovalTopic + if flowState.TopicCode != "" { + topic, _ := h.Registry.Get(flowState.TopicCode) + if topic != nil { + topicCode, _ := topic.TopicCodeFromCollected(flowState.Collected) + approvalTopic, _ = h.ipc.Database.ApprovalTopic.GetApprovalTopicByCodeDB(ctx, topicCode) + } + } + isRequired := approvalTopic != nil && + approvalTopic.RequireObserverSelection != nil && + *approvalTopic.RequireObserverSelection + + observers, _ := h.getAvailableObservers(ctx) + editMsg := tgbotapi.NewEditMessageReplyMarkup( + chatID, + cq.Message.MessageID, + keyboard.BuildObserverSelectionMenu(observers, flowState.SelectedObserverIDs, 0, isRequired), + ) + bot.Request(editMsg) //nolint:errcheck +} + +func (h *Handler) HandleObserverPageCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, page int) { + ctx := context.Background() + chatID := cq.Message.Chat.ID + telegramID := cq.From.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + + flowState, err := h.States.Get(ctx, telegramID) + if err != nil || flowState == nil || !flowState.AwaitObserverSelection { + return + } + + var approvalTopic *typescore.ApprovalTopic + if flowState.TopicCode != "" { + topic, _ := h.Registry.Get(flowState.TopicCode) + if topic != nil { + topicCode, _ := topic.TopicCodeFromCollected(flowState.Collected) + approvalTopic, _ = h.ipc.Database.ApprovalTopic.GetApprovalTopicByCodeDB(ctx, topicCode) + } + } + isRequired := approvalTopic != nil && + approvalTopic.RequireObserverSelection != nil && + *approvalTopic.RequireObserverSelection + + observers, err := h.getAvailableObservers(ctx) + if err != nil { + return + } + + editMsg := tgbotapi.NewEditMessageReplyMarkup( + chatID, + cq.Message.MessageID, + keyboard.BuildObserverSelectionMenu(observers, flowState.SelectedObserverIDs, page, isRequired), + ) + bot.Request(editMsg) //nolint:errcheck +} + +// HandleObserverConfirmCallback — пользователь подтвердил выбор наблюдателей +func (h *Handler) HandleObserverConfirmCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery) { + ctx := context.Background() + chatID := cq.Message.Chat.ID + telegramID := cq.From.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + + flowState, err := h.States.Get(ctx, telegramID) + if err != nil || flowState == nil { + sendText(bot, chatID, "⚠️ Состояние утеряно. Начните заново.") + return + } + + var approvalTopic *typescore.ApprovalTopic + if flowState.TopicCode != "" { + topic, _ := h.Registry.Get(flowState.TopicCode) + if topic != nil { + topicCode, _ := topic.TopicCodeFromCollected(flowState.Collected) + approvalTopic, _ = h.ipc.Database.ApprovalTopic.GetApprovalTopicByCodeDB(ctx, topicCode) + } + } + + isRequired := approvalTopic != nil && + approvalTopic.RequireObserverSelection != nil && + *approvalTopic.RequireObserverSelection + + if isRequired && len(flowState.SelectedObserverIDs) == 0 { + bot.Request(tgbotapi.NewCallback(cq.ID, "⚠️ Выберите хотя бы одного наблюдателя")) //nolint:errcheck + return + } + + bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck + + h.States.Clear(ctx, telegramID) //nolint:errcheck + h.finalizeAndSubmit(bot, ctx, chatID, telegramID, flowState) +} + +// getAvailableObservers — возвращает всех пользователей с ролью наблюдателя +func (h *Handler) getAvailableObservers(ctx context.Context) ([]*typescore.User, error) { + return h.ipc.Database.User.GetUsersByRoleCodeDB(ctx, "observer") +} + +// saveSelectedObservers сохраняет выбранных наблюдателей после создания заявки +func (h *Handler) saveSelectedObservers( + ctx context.Context, + approvalID uint64, + addedByID uint64, + observerIDs []uint64, +) { + for _, observerID := range observerIDs { + id := observerID // копия для замыкания + addedBy := addedByID + aID := approvalID + + obj := &typescore.ApprovalAdditionalObserver{ + ApprovalID: &aID, + UserID: &id, + AddedByID: &addedBy, + } + if _, _, err := h.ipc.Database.ApprovalAdditionalObserver.CreateApprovalAdditionalObserverDB(ctx, nil, obj); err != nil { + logrus.Errorf("saveSelectedObservers: err observerID=%d err=%v", id, err) + } + } +} + +// getAdditionalObserversForApproval возвращает всех дополнительных наблюдателей заявки +func (h *Handler) getAdditionalObserversForApproval(ctx context.Context, approvalID uint64) []*typescore.User { + records, _, err := h.ipc.Database.ApprovalAdditionalObserver.GetApprovalAdditionalObserversListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalAdditionalObserver{ + ApprovalID: &approvalID, + }, + }) + if err != nil { + logrus.Errorf("failed to get additional observers list. %v", err) + return nil + } + + var users []*typescore.User + for _, r := range records { + if r.UserID == nil { + continue + } + u, err := h.ipc.Database.User.GetUserByIDDB(ctx, *r.UserID) + if err == nil && u != nil { + users = append(users, u) + } + } + return users +} diff --git a/service/telegram_service/handlers/approval/topics/absence/topic.go b/service/telegram_service/handlers/approval/topics/absence/topic.go new file mode 100644 index 0000000..826d7c7 --- /dev/null +++ b/service/telegram_service/handlers/approval/topics/absence/topic.go @@ -0,0 +1,91 @@ +package absence + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/telegram_service/approvalflow" + sickleave "bitrix_balancer_api/telegram_service/handlers/approval/topics/sick_leave" + timeoff "bitrix_balancer_api/telegram_service/handlers/approval/topics/time_off" + "bitrix_balancer_api/telegram_service/handlers/approval/topics/vacation" + "fmt" +) + +type AbsenceTopic struct { + timeoffTopic *timeoff.TimeOffTopic + vacationTopic *vacation.VacationTopic + sickleaveTopic *sickleave.SickLeaveTopic +} + +func NewAbsenceTopic() *AbsenceTopic { + return &AbsenceTopic{ + timeoffTopic: timeoff.NewTimeOffTopic(), + vacationTopic: vacation.NewVacationTopic(), + sickleaveTopic: sickleave.NewSickLeaveTopic(), + } +} + +func (a *AbsenceTopic) Code() string { return "absence" } +func (a *AbsenceTopic) Name() string { + return "Согласование отпусков/отгулов" +} + +func (a *AbsenceTopic) BuildTree() *approvalflow.FlowNode { + return &approvalflow.FlowNode{ + Key: "absence", + Label: "Согласование отпусков/отгулов", + Children: []*approvalflow.FlowNode{ + { + Key: "absence_timeoff", + Label: "Отгул", + DataKey: "absence_type", + DataValue: "timeoff", + // Копируем детей из оригинального дерева timeoff + Children: a.timeoffTopic.BuildTree().Children, + }, + { + Key: "absence_vacation", + Label: "Отпуск", + DataKey: "absence_type", + DataValue: "vacation", + Children: a.vacationTopic.BuildTree().Children, + }, + { + Key: "absence_sickleave", + Label: "Официальный больничный", + DataKey: "absence_type", + DataValue: "sickleave", + Children: a.sickleaveTopic.BuildTree().Children, + }, + }, + } +} + +func (a *AbsenceTopic) TopicCodeFromCollected(collected map[string]string) (string, error) { + absenceType := collected["absence_type"] + switch absenceType { + case "timeoff": + return a.timeoffTopic.TopicCodeFromCollected(collected) + case "vacation": + return a.vacationTopic.TopicCodeFromCollected(collected) + case "sickleave": + return a.sickleaveTopic.TopicCodeFromCollected(collected) + default: + return "", fmt.Errorf("absence_type не указан в collected: %v", collected) + } +} + +func (a *AbsenceTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { + switch collected["absence_type"] { + case "timeoff": + return a.timeoffTopic.FormatApproverMessage(initiator, collected) + case "vacation": + return a.vacationTopic.FormatApproverMessage(initiator, collected) + case "sickleave": + return a.sickleaveTopic.FormatApproverMessage(initiator, collected) + default: + name := "" + if initiator.FullName != nil { + name = *initiator.FullName + } + return fmt.Sprintf("📋 Согласование отсутствия\n\n%s:\n%s", name, collected["content"]) + } +} diff --git a/service/telegram_service/handlers/approval/topics/client_changes/topic.go b/service/telegram_service/handlers/approval/topics/client_changes/topic.go new file mode 100644 index 0000000..2a2ce4b --- /dev/null +++ b/service/telegram_service/handlers/approval/topics/client_changes/topic.go @@ -0,0 +1,149 @@ +package clientchanges + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/telegram_service/approvalflow" + "fmt" + "strings" +) + +type ClientChangesTopic struct{} + +func NewClientChangesTopic() *ClientChangesTopic { + return &ClientChangesTopic{} +} + +func (c *ClientChangesTopic) Code() string { return "client_changes" } +func (c *ClientChangesTopic) Name() string { + return "Изменение клиента в ОКБ и 1С" +} + +func (c *ClientChangesTopic) BuildTree() *approvalflow.FlowNode { + return &approvalflow.FlowNode{ + Key: "client_changes", + Label: "Изменение клиента", + Children: []*approvalflow.FlowNode{ + c.buildChangeType("rename", "Поменять название"), + c.buildChangeType("change_manager", "Сменить менеджера"), + c.buildChangeType("new_client", "Внести нового клиента"), + }, + } +} + +func (c *ClientChangesTopic) buildChangeType(changeKey, changeLabel string) *approvalflow.FlowNode { + return &approvalflow.FlowNode{ + Key: changeKey, + Label: changeLabel, + DataKey: "change_type", + DataValue: changeKey, + Children: []*approvalflow.FlowNode{ + c.buildRegion(changeKey, "crimea", "Крым"), + c.buildRegion(changeKey, "krasnodar", "Краснодар"), + }, + } +} + +func (c *ClientChangesTopic) buildRegion(changeKey, regionKey, regionLabel string) *approvalflow.FlowNode { + return &approvalflow.FlowNode{ + Key: changeKey + "_" + regionKey, + Label: regionLabel, + DataKey: "region", + DataValue: regionKey, + Children: []*approvalflow.FlowNode{ + { + Key: changeKey + "_" + regionKey + "_okb", + IsMultiSelect: true, + MultiSelectKey: "systems", + MultiSelectValue: "okb", + Label: "ОКБ", + Children: []*approvalflow.FlowNode{ + { + Key: changeKey + "_" + regionKey + "_okb_input", + IsInput: true, + InputKey: "content", + InputHint: "Опишите изменения: текущие данные → новые данные", + }, + }, + }, + { + Key: changeKey + "_" + regionKey + "_1c", + IsMultiSelect: true, + MultiSelectKey: "systems", + MultiSelectValue: "1c", + Label: "1С", + Children: []*approvalflow.FlowNode{ + { + Key: changeKey + "_" + regionKey + "_1c_input", + IsInput: true, + InputKey: "content", + InputHint: "Опишите изменения: текущие данные → новые данные", + }, + }, + }, + }, + } +} + +func (c *ClientChangesTopic) TopicCodeFromCollected(collected map[string]string) (string, error) { + changeType := collected["change_type"] + region := collected["region"] + + if changeType == "" || region == "" { + return "", fmt.Errorf("неполные данные: change_type=%s, region=%s", changeType, region) + } + + return fmt.Sprintf("client_changes_%s_%s", changeType, region), nil +} + +func (c *ClientChangesTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { + name := "" + if initiator.FullName != nil { + name = *initiator.FullName + } + + var changeLabel string + switch collected["change_type"] { + case "rename": + changeLabel = "Поменять название" + case "change_manager": + changeLabel = "Сменить менеджера" + case "new_client": + changeLabel = "Внести нового клиента" + default: + changeLabel = "Изменение клиента" + } + + regionLabel := "—" + switch collected["region"] { + case "crimea": + regionLabel = "Крым" + case "krasnodar": + regionLabel = "Краснодар" + } + + var systemLabels []string + systems := collected["systems"] + if systems != "" { + for _, s := range strings.Split(systems, ",") { + switch strings.TrimSpace(s) { + case "okb": + systemLabels = append(systemLabels, "ОКБ") + case "1c": + systemLabels = append(systemLabels, "1С") + } + } + } + + systemsStr := "не указаны" + if len(systemLabels) > 0 { + systemsStr = strings.Join(systemLabels, ", ") + } + + return fmt.Sprintf( + "📋 Изменение клиентов в ОКБ и 1С: – %s\n"+ + "🖥 Системы: %s\n"+ + "📍 Регион: %s\n\n"+ + "%s:\n%s", + changeLabel, systemsStr, regionLabel, name, collected["content"], + ) +} diff --git a/service/telegram_service/handlers/approval/topics/free/topic.go b/service/telegram_service/handlers/approval/topics/free/topic.go new file mode 100644 index 0000000..bd8c505 --- /dev/null +++ b/service/telegram_service/handlers/approval/topics/free/topic.go @@ -0,0 +1,75 @@ +package free + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/telegram_service/approvalflow" + "fmt" +) + +// FreeTopic — тема с единственным шагом: свободный текстовый ввод. +// Подходит для всех тем без разветвлённой логики. +type FreeTopic struct { + code string + name string + template string +} + +func NewFreeTopic(code, name, template string) *FreeTopic { + return &FreeTopic{ + code: code, + name: name, + template: template, + } +} + +func (o *FreeTopic) Code() string { return o.code } +func (o *FreeTopic) Name() string { return o.name } + +func (o *FreeTopic) BuildTree() *approvalflow.FlowNode { + tmp := "Напишите текст согласования" + if o.template != "" { + tmp = o.template + } + return &approvalflow.FlowNode{ + Key: o.code, + Label: o.name, + Children: []*approvalflow.FlowNode{ + { + Key: o.code + "_input", + IsInput: true, + InputKey: "content", + InputHint: tmp, + }, + }, + } +} + +func (o *FreeTopic) TopicCodeFromCollected(_ map[string]string) (string, error) { + return o.code, nil +} + +func (t *FreeTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { + initiatorName := "—" + if initiator != nil && initiator.FullName != nil { + initiatorName = *initiator.FullName + } + + content := collected["content"] + if content == "" { + content = "—" + } + + text := fmt.Sprintf( + "📋 Заявка на согласование\n\n"+ + "👤 От: %s\n"+ + "📂 Тема: %s\n"+ + "📝 Текст:\n%s", + initiatorName, t.Name(), content, + ) + + if instructions, ok := collected["instructions"]; ok && instructions != "" { + text += fmt.Sprintf("\n\n💡 Инструкция:\n%s", instructions) + } + + return text +} diff --git a/service/telegram_service/handlers/approval/topics/goods_order/topic.go b/service/telegram_service/handlers/approval/topics/goods_order/topic.go new file mode 100644 index 0000000..211414c --- /dev/null +++ b/service/telegram_service/handlers/approval/topics/goods_order/topic.go @@ -0,0 +1,108 @@ +package goodsorder + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/telegram_service/approvalflow" + "fmt" +) + +type GoodsOrderTopic struct{} + +func NewGoodsOrderTopic() *GoodsOrderTopic { + return &GoodsOrderTopic{} +} + +func (g *GoodsOrderTopic) Code() string { return "goods_order" } +func (g *GoodsOrderTopic) Name() string { return "Заказ товаров" } + +func (g *GoodsOrderTopic) BuildTree() *approvalflow.FlowNode { + return &approvalflow.FlowNode{ + Key: "goods_order", + Label: "Заказ товаров", + Children: []*approvalflow.FlowNode{ + { + Key: "monthly", + Label: "На месяц", + DataKey: "order_type", + DataValue: "monthly", + Children: g.buildRegions("monthly"), + }, + { + Key: "additional", + Label: "Дополнительный заказ", + DataKey: "order_type", + DataValue: "additional", + Children: g.buildRegions("additional"), + }, + }, + } +} + +func (g *GoodsOrderTopic) buildRegions(orderType string) []*approvalflow.FlowNode { + return []*approvalflow.FlowNode{ + { + Key: orderType + "_crimea", + Label: "Крым", + DataKey: "region", + DataValue: "crimea", + Children: []*approvalflow.FlowNode{{ + Key: orderType + "_crimea_input", + IsInput: true, + InputKey: "content", + InputHint: "Скилур заказ:\n22 гр.38 мм бесцветная (10176) ЕПМ - 5кор.\nф1, на склад Гвардейское, 2я декада.", + }}, + }, + { + Key: orderType + "_krasnodar", + Label: "Краснодар", + DataKey: "region", + DataValue: "krasnodar", + Children: []*approvalflow.FlowNode{{ + Key: orderType + "_krasnodar_input", + IsInput: true, + InputKey: "content", + InputHint: "Скилур заказ:\n22 гр.38 мм бесцветная (10176) ЕПМ - 5кор.\nф1, на склад Гвардейское, 2я декада.", + }}, + }, + } +} + +func (g *GoodsOrderTopic) TopicCodeFromCollected(collected map[string]string) (string, error) { + orderType := collected["order_type"] + region := collected["region"] + if orderType == "" { + return "", fmt.Errorf("order_type не указан") + } + // region опционален для обратной совместимости + if region != "" { + return fmt.Sprintf("goods_order_%s_%s", orderType, region), nil + } + return fmt.Sprintf("goods_order_%s", orderType), nil +} + +func (g *GoodsOrderTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { + name := "" + if initiator.FullName != nil { + name = *initiator.FullName + } + + typeLabel := "На месяц" + if collected["order_type"] == "additional" { + typeLabel = "Дополнительный заказ" + } + + regionLabel := "—" + switch collected["region"] { + case "crimea": + regionLabel = "Крым" + case "krasnodar": + regionLabel = "Краснодар" + } + + return fmt.Sprintf( + "📋 Заказ товаров — %s\n"+ + "📍 Регион: %s\n\n"+ + "%s:\n%s", + typeLabel, regionLabel, name, collected["content"], + ) +} diff --git a/service/telegram_service/handlers/approval/topics/manager_expenses/topic.go b/service/telegram_service/handlers/approval/topics/manager_expenses/topic.go new file mode 100644 index 0000000..4e030bd --- /dev/null +++ b/service/telegram_service/handlers/approval/topics/manager_expenses/topic.go @@ -0,0 +1,70 @@ +package managerexpenses + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/telegram_service/approvalflow" + "fmt" +) + +type ManagerExpensesTopic struct{} + +func NewManagerExpensesTopic() *ManagerExpensesTopic { return &ManagerExpensesTopic{} } + +func (s *ManagerExpensesTopic) Code() string { return "manager_expenses" } +func (s *ManagerExpensesTopic) Name() string { return "Менеджерские расходы" } + +func (s *ManagerExpensesTopic) BuildTree() *approvalflow.FlowNode { + return &approvalflow.FlowNode{ + Key: "manager_expenses", + Label: "Менеджерские расходы", + Children: []*approvalflow.FlowNode{ + s.buildRegion("crimea", "Крым"), + s.buildRegion("krasnodar", "Краснодар"), + }, + } +} + +func (s *ManagerExpensesTopic) buildRegion(regionKey, regionLabel string) *approvalflow.FlowNode { + return &approvalflow.FlowNode{ + Key: regionKey, + Label: regionLabel, + DataKey: "region", + DataValue: regionKey, + Children: []*approvalflow.FlowNode{ + { + Key: regionKey + "_input", + IsInput: true, + InputKey: "content", + InputHint: "Оплата платной дороги Краснодар-Темрюк-Краснодар в сумме 1420 руб. (клиент РУСМолоко) (расход Макаренко)", + }, + }, + } +} + +func (s *ManagerExpensesTopic) TopicCodeFromCollected(collected map[string]string) (string, error) { + region := collected["region"] + if region == "" { + return "", fmt.Errorf("неполные данные: region пуст") + } + return fmt.Sprintf("manager_expenses_%s", region), nil +} + +func (s *ManagerExpensesTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { + name := "" + if initiator.FullName != nil { + name = *initiator.FullName + } + + regionLabel := collected["region"] + switch regionLabel { + case "crimea": + regionLabel = "Крым" + case "krasnodar": + regionLabel = "Краснодар" + } + + return fmt.Sprintf( + "📋 Менеджерские расходы — %s\n\n%s:\n%s", + regionLabel, name, collected["content"], + ) +} diff --git a/service/telegram_service/handlers/approval/topics/non_budget_expenses/topic.go b/service/telegram_service/handlers/approval/topics/non_budget_expenses/topic.go new file mode 100644 index 0000000..3a5cc82 --- /dev/null +++ b/service/telegram_service/handlers/approval/topics/non_budget_expenses/topic.go @@ -0,0 +1,125 @@ +package nonbudgetexpenses + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/telegram_service/approvalflow" + "fmt" +) + +type NonBudgetExpensesTopic struct{} + +func NewNonBudgetExpensesTopic() *NonBudgetExpensesTopic { + return &NonBudgetExpensesTopic{} +} + +func (n *NonBudgetExpensesTopic) Code() string { return "non_budget_expenses" } +func (n *NonBudgetExpensesTopic) Name() string { return "Внебюджетные расходы" } + +func (n *NonBudgetExpensesTopic) BuildTree() *approvalflow.FlowNode { + return &approvalflow.FlowNode{ + Key: "non_budget_expenses", + Label: "Внебюджетные расходы", + Children: []*approvalflow.FlowNode{ + { + Key: "f1", Label: "Ф1", + DataKey: "branch", DataValue: "f1", + Children: []*approvalflow.FlowNode{ + // 🚀 Ф1 — с развилкой ПП (разные подтемы) + n.buildExpenseTypeWithPP("f1_tmc", "tmc", "ТМЦ", + "Прошу согласовать и оплатить Счет от ООО Интернет Решения (Озон) за ноутбук и мышь для закупщика в сумме 31 335 руб. С НДС"), + n.buildExpenseTypeWithPP("f1_expense", "expense", "Расход", + "Прошу оплатить счет ИП Гулякина на сумму 3180,00 руб (без НДС) за продление 1С-Отчетность на 1 год"), + }, + }, + { + Key: "f2", Label: "Ф2", + DataKey: "branch", DataValue: "f2", + Children: []*approvalflow.FlowNode{ + // Ф2 — без развилки ПП (одна подтема) + n.buildExpenseTypeSimple("f2_tmc", "tmc", "ТМЦ", + "Прошу согласовать и оплатить Счет от ООО Интернет Решения (Озон) за ноутбук и мышь для закупщика в сумме 31 335 руб. С НДС"), + n.buildExpenseTypeSimple("f2_expense", "expense", "Расход", + "Прошу оплатить счет ИП Гулякина на сумму 3180,00 руб (без НДС) за продление 1С-Отчетность на 1 год"), + }, + }, + }, + } +} + +// buildExpenseTypeWithPP создаёт узел с выбором "Нужна ПП" / "Не нужна ПП" +// Каждый выбор ведёт к СВОЕЙ подтеме +func (n *NonBudgetExpensesTopic) buildExpenseTypeWithPP(key, typeVal, label, hint string) *approvalflow.FlowNode { + return &approvalflow.FlowNode{ + Key: key, Label: label, + DataKey: "expense_type", DataValue: typeVal, + Children: []*approvalflow.FlowNode{ + { + Key: key + "_pp_yes", Label: "✅ Нужна ПП", + DataKey: "pp_required", DataValue: "yes", + Children: []*approvalflow.FlowNode{{ + Key: key + "_pp_yes_input", IsInput: true, + InputKey: "content", InputHint: hint, + }}, + }, + { + Key: key + "_pp_no", Label: "❌ Не нужна ПП", + DataKey: "pp_required", DataValue: "no", + Children: []*approvalflow.FlowNode{{ + Key: key + "_pp_no_input", IsInput: true, + InputKey: "content", InputHint: hint, + }}, + }, + }, + } +} + +func (n *NonBudgetExpensesTopic) buildExpenseTypeSimple(key, typeVal, label, hint string) *approvalflow.FlowNode { + return &approvalflow.FlowNode{ + Key: key, Label: label, + DataKey: "expense_type", DataValue: typeVal, + Children: []*approvalflow.FlowNode{{ + Key: key + "_input", IsInput: true, + InputKey: "content", InputHint: hint, + }}, + } +} + +// 🚀 TopicCodeFromCollected теперь включает pp_required в код темы +func (n *NonBudgetExpensesTopic) TopicCodeFromCollected(collected map[string]string) (string, error) { + branch := collected["branch"] + expenseType := collected["expense_type"] + ppRequired := collected["pp_required"] + + if branch == "" || expenseType == "" { + return "", fmt.Errorf("неполные данные: branch=%s, expense_type=%s", branch, expenseType) + } + + // 🚀 Если pp_required указан — добавляем его в код темы + if ppRequired != "" { + return fmt.Sprintf("non_budget_expenses_%s_%s_pp_%s", branch, expenseType, ppRequired), nil + } + // Для Ф2 (без ПП) — старый формат + return fmt.Sprintf("non_budget_expenses_%s_%s", branch, expenseType), nil +} + +func (n *NonBudgetExpensesTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { + name := "" + if initiator.FullName != nil { + name = *initiator.FullName + } + + branchLabel := map[string]string{"f1": "Ф1", "f2": "Ф2"}[collected["branch"]] + typeLabel := map[string]string{"tmc": "ТМЦ", "expense": "Расход"}[collected["expense_type"]] + + // 🚀 Информация о ПП теперь в названии темы, не дублируем + ppLine := "" + if pp := collected["pp_required"]; pp != "" { + ppLabel := map[string]string{"yes": "✅ Нужна ПП", "no": "❌ Не нужна ПП"}[pp] + ppLine = fmt.Sprintf("\n💳 ПП: %s", ppLabel) + } + + return fmt.Sprintf( + "📋 Внебюджетные расходы — %s (%s)%s\n\n%s:\n%s", + branchLabel, typeLabel, ppLine, name, collected["content"], + ) +} diff --git a/service/telegram_service/handlers/approval/topics/non_budget_expenses_pet_line/topic.go b/service/telegram_service/handlers/approval/topics/non_budget_expenses_pet_line/topic.go new file mode 100644 index 0000000..39f67e1 --- /dev/null +++ b/service/telegram_service/handlers/approval/topics/non_budget_expenses_pet_line/topic.go @@ -0,0 +1,135 @@ +package nonbudgetexpensespetline + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/telegram_service/approvalflow" + "fmt" +) + +type NonBudgetExpensesPetLineTopic struct{} + +func NewNonBudgetExpensesPetLineTopic() *NonBudgetExpensesPetLineTopic { + return &NonBudgetExpensesPetLineTopic{} +} + +func (n *NonBudgetExpensesPetLineTopic) Code() string { return "non_budget_expenses_pet_line" } +func (n *NonBudgetExpensesPetLineTopic) Name() string { + return "Внебюджетные расходы ПЭТ Лайн" +} + +func (n *NonBudgetExpensesPetLineTopic) BuildTree() *approvalflow.FlowNode { + return &approvalflow.FlowNode{ + Key: "non_budget_expenses_pet_line", + Label: "Внебюджетные расходы ПЭТ Лайн", + Children: []*approvalflow.FlowNode{ + { + Key: "f1", + Label: "Ф1", + DataKey: "branch", + DataValue: "f1", + Children: []*approvalflow.FlowNode{ + { + Key: "f1_tmc", + Label: "ТМЦ", + DataKey: "expense_type", + DataValue: "tmc", + Children: []*approvalflow.FlowNode{ + { + Key: "f1_tmc_input", + IsInput: true, + InputKey: "content", + InputHint: "Опишите расход ТМЦ ПЭТ Лайн: наименование, количество, сумма", + }, + }, + }, + { + Key: "f1_expense", + Label: "Расход", + DataKey: "expense_type", + DataValue: "expense", + Children: []*approvalflow.FlowNode{ + { + Key: "f1_expense_input", + IsInput: true, + InputKey: "content", + InputHint: "Опишите расход ПЭТ Лайн: назначение, сумма, детали", + }, + }, + }, + }, + }, + { + Key: "f2", + Label: "Ф2", + DataKey: "branch", + DataValue: "f2", + Children: []*approvalflow.FlowNode{ + { + Key: "f2_tmc", + Label: "ТМЦ", + DataKey: "expense_type", + DataValue: "tmc", + Children: []*approvalflow.FlowNode{ + { + Key: "f2_tmc_input", + IsInput: true, + InputKey: "content", + InputHint: "Опишите расход ТМЦ ПЭТ Лайн: наименование, количество, сумма", + }, + }, + }, + { + Key: "f2_expense", + Label: "Расход", + DataKey: "expense_type", + DataValue: "expense", + Children: []*approvalflow.FlowNode{ + { + Key: "f2_expense_input", + IsInput: true, + InputKey: "content", + InputHint: "Опишите расход ПЭТ Лайн: назначение, сумма, детали", + }, + }, + }, + }, + }, + }, + } +} + +func (n *NonBudgetExpensesPetLineTopic) TopicCodeFromCollected(collected map[string]string) (string, error) { + branch := collected["branch"] + expenseType := collected["expense_type"] + + if branch == "" || expenseType == "" { + return "", fmt.Errorf("неполные данные: branch=%s, expense_type=%s", branch, expenseType) + } + + return fmt.Sprintf("non_budget_expenses_pet_line_%s_%s", branch, expenseType), nil +} + +func (n *NonBudgetExpensesPetLineTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { + name := "" + if initiator.FullName != nil { + name = *initiator.FullName + } + + branchLabel := collected["branch"] + if branchLabel == "f1" { + branchLabel = "Ф1" + } else if branchLabel == "f2" { + branchLabel = "Ф2" + } + + typeLabel := "Расход" + if collected["expense_type"] == "tmc" { + typeLabel = "ТМЦ" + } + + return fmt.Sprintf( + "📋 Внебюджетные расходы ПЭТ Лайн — %s (%s)\n\n"+ + "%s:\n%s", + branchLabel, typeLabel, name, collected["content"], + ) +} diff --git a/service/telegram_service/handlers/approval/topics/nonstandard_contract/topic.go b/service/telegram_service/handlers/approval/topics/nonstandard_contract/topic.go new file mode 100644 index 0000000..b4b46bb --- /dev/null +++ b/service/telegram_service/handlers/approval/topics/nonstandard_contract/topic.go @@ -0,0 +1,75 @@ +package nonstandardcontract + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/telegram_service/approvalflow" + "fmt" +) + +type NonstandardContractTopic struct{} + +func NewNonstandardContractTopic() *NonstandardContractTopic { return &NonstandardContractTopic{} } + +func (s *NonstandardContractTopic) Code() string { return "nonstandard_contract" } +func (s *NonstandardContractTopic) Name() string { + return "Нестандартные условия договора поставки" +} + +func (s *NonstandardContractTopic) BuildTree() *approvalflow.FlowNode { + return &approvalflow.FlowNode{ + Key: "nonstandard_contract", + Label: "Нестандартные условия договора поставки", + Children: []*approvalflow.FlowNode{ + s.buildRegion("crimea", "Крым"), + s.buildRegion("krasnodar", "Краснодар"), + s.buildRegion("belarus", "Беларусь"), + }, + } +} + +func (s *NonstandardContractTopic) buildRegion(regionKey, regionLabel string) *approvalflow.FlowNode { + return &approvalflow.FlowNode{ + Key: regionKey, + Label: regionLabel, + DataKey: "region", + DataValue: regionKey, + Children: []*approvalflow.FlowNode{ + { + Key: regionKey + "_input", + IsInput: true, + InputKey: "content", + InputHint: "Прошу согласовать отсрочку 21 день для клиента ООО Роса (другое юрлицо ООО Аквариум) (менеджер Петров)", + }, + }, + } +} + +func (s *NonstandardContractTopic) TopicCodeFromCollected(collected map[string]string) (string, error) { + region := collected["region"] + if region == "" { + return "", fmt.Errorf("неполные данные: region пуст") + } + return fmt.Sprintf("nonstandard_contract_%s", region), nil +} + +func (s *NonstandardContractTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { + name := "" + if initiator.FullName != nil { + name = *initiator.FullName + } + + regionLabel := collected["region"] + switch regionLabel { + case "crimea": + regionLabel = "Крым" + case "krasnodar": + regionLabel = "Краснодар" + case "belarus": + regionLabel = "Беларусь" + } + + return fmt.Sprintf( + "📋 Нестандартные условия договора поставки — %s\n\n%s:\n%s", + regionLabel, name, collected["content"], + ) +} diff --git a/service/telegram_service/handlers/approval/topics/otk_conditions/topic.go b/service/telegram_service/handlers/approval/topics/otk_conditions/topic.go new file mode 100644 index 0000000..573ec2d --- /dev/null +++ b/service/telegram_service/handlers/approval/topics/otk_conditions/topic.go @@ -0,0 +1,82 @@ +package otkconditions + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/telegram_service/approvalflow" + "fmt" +) + +type OtkConditionsTopic struct{} + +func NewOtkConditionsTopic() *OtkConditionsTopic { return &OtkConditionsTopic{} } + +func (s *OtkConditionsTopic) Code() string { return "otk_conditions" } +func (s *OtkConditionsTopic) Name() string { return "Долгосрочные условия ОТК" } + +func (s *OtkConditionsTopic) BuildTree() *approvalflow.FlowNode { + return &approvalflow.FlowNode{ + Key: "otk_conditions", + Label: "Долгосрочные условия ОТК", + Children: []*approvalflow.FlowNode{ + s.buildRegion("crimea", "Крым"), + s.buildRegion("krasnodar", "Краснодар"), + s.buildRegion("belarus", "Беларусь"), + }, + } +} + +func (s *OtkConditionsTopic) buildRegion(regionKey, regionLabel string) *approvalflow.FlowNode { + return &approvalflow.FlowNode{ + Key: regionKey, + Label: regionLabel, + DataKey: "region", + DataValue: regionKey, + Children: []*approvalflow.FlowNode{ + { + Key: regionKey + "_input", + IsInput: true, + InputKey: "content", + InputHint: "Опишите долгосрочные условия ОТК", + }, + }, + } +} + +func (s *OtkConditionsTopic) TopicCodeFromCollected(collected map[string]string) (string, error) { + region := collected["region"] + if region == "" { + return "", fmt.Errorf("неполные данные: region пуст") + } + return fmt.Sprintf("otk_conditions_%s", region), nil +} + +func (s *OtkConditionsTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { + name := "—" + if initiator != nil && initiator.FullName != nil { + name = *initiator.FullName + } + + regionLabel := "—" + if collected != nil { + switch collected["region"] { + case "crimea": + regionLabel = "Крым" + case "krasnodar": + regionLabel = "Краснодар" + case "belarus": + regionLabel = "Беларусь" + } + } + + content := "—" + if collected != nil && collected["content"] != "" { + content = collected["content"] + } + + return fmt.Sprintf( + "📋 Долгосрочные условия ОТК — %s\n\n"+ + "👤 Инициатор: %s\n"+ + "📝 Текст:\n%s", + regionLabel, name, content, + ) +} diff --git a/service/telegram_service/handlers/approval/topics/payments_cashless/topic.go b/service/telegram_service/handlers/approval/topics/payments_cashless/topic.go new file mode 100644 index 0000000..54220a5 --- /dev/null +++ b/service/telegram_service/handlers/approval/topics/payments_cashless/topic.go @@ -0,0 +1,90 @@ +package paymentscashless + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/telegram_service/approvalflow" + "fmt" +) + +type PaymentsCashlessTopic struct{} + +func NewPaymentsCashlessTopic() *PaymentsCashlessTopic { return &PaymentsCashlessTopic{} } + +func (p *PaymentsCashlessTopic) Code() string { return "payments_cashless" } +func (p *PaymentsCashlessTopic) Name() string { + return "Утверждение оплат безнал" +} + +func (p *PaymentsCashlessTopic) BuildTree() *approvalflow.FlowNode { + return &approvalflow.FlowNode{ + Key: "payments_cashless", + Label: "Утверждение оплат безнал", + Children: []*approvalflow.FlowNode{ + p.buildCategoryWithPP("goods", "Товар", + "Счет 2838 от 12.05.2026 от ООО Упаковка на сумму 2 464 700,16 руб."), + p.buildCategoryWithPP("misc", "Разное", + "Счет 2838 от 12.05.2026 от ООО Упаковка на сумму 2 464 700,16 руб."), + }, + } +} + +func (p *PaymentsCashlessTopic) buildCategoryWithPP(key, label, hint string) *approvalflow.FlowNode { + return &approvalflow.FlowNode{ + Key: key, Label: label, + DataKey: "payment_category", DataValue: key, + Children: []*approvalflow.FlowNode{ + { + Key: key + "_pp_yes", Label: "✅ Нужна ПП", + DataKey: "pp_required", DataValue: "yes", + Children: []*approvalflow.FlowNode{{ + Key: key + "_pp_yes_input", IsInput: true, + InputKey: "content", InputHint: hint, + }}, + }, + { + Key: key + "_pp_no", Label: "❌ Не нужна ПП", + DataKey: "pp_required", DataValue: "no", + Children: []*approvalflow.FlowNode{{ + Key: key + "_pp_no_input", IsInput: true, + InputKey: "content", InputHint: hint, + }}, + }, + }, + } +} + +// 🚀 TopicCodeFromCollected теперь включает pp_required в код темы +func (p *PaymentsCashlessTopic) TopicCodeFromCollected(collected map[string]string) (string, error) { + cat := collected["payment_category"] + ppRequired := collected["pp_required"] + + if cat == "" { + return "", fmt.Errorf("payment_category не указан") + } + + // 🚀 Если pp_required указан — добавляем его в код темы + if ppRequired != "" { + return fmt.Sprintf("payments_cashless_%s_pp_%s", cat, ppRequired), nil + } + return fmt.Sprintf("payments_cashless_%s", cat), nil +} + +func (p *PaymentsCashlessTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { + name := "" + if initiator.FullName != nil { + name = *initiator.FullName + } + + catLabel := map[string]string{"goods": "Товар", "misc": "Разное"}[collected["payment_category"]] + + ppLine := "" + if pp := collected["pp_required"]; pp != "" { + ppLabel := map[string]string{"yes": "✅ Нужна ПП", "no": "❌ Не нужна ПП"}[pp] + ppLine = fmt.Sprintf("\n💳 ПП: %s", ppLabel) + } + + return fmt.Sprintf( + "📋 Оплата безнал — %s%s\n\n%s:\n%s", + catLabel, ppLine, name, collected["content"], + ) +} diff --git a/service/telegram_service/handlers/approval/topics/rates_logistics/topic.go b/service/telegram_service/handlers/approval/topics/rates_logistics/topic.go new file mode 100644 index 0000000..72cd3bf --- /dev/null +++ b/service/telegram_service/handlers/approval/topics/rates_logistics/topic.go @@ -0,0 +1,79 @@ +package rateslogistics + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/telegram_service/approvalflow" + "fmt" +) + +type RatesLogisticsTopic struct{} + +func NewRatesLogisticsTopic() *RatesLogisticsTopic { + return &RatesLogisticsTopic{} +} + +func (r *RatesLogisticsTopic) Code() string { return "rates_logistics" } +func (r *RatesLogisticsTopic) Name() string { return "Ставки логистика" } + +func (r *RatesLogisticsTopic) BuildTree() *approvalflow.FlowNode { + return &approvalflow.FlowNode{ + Key: "rates_logistics", + Label: "Ставки логистика", + Children: []*approvalflow.FlowNode{ + { + Key: "once", + Label: "Разово", + DataKey: "rate_type", + DataValue: "once", + Children: []*approvalflow.FlowNode{ + { + Key: "once_input", + IsInput: true, + InputKey: "content", + InputHint: "Опишите разовые ставки: маршрут, стоимость, срок", + }, + }, + }, + { + Key: "long_term", + Label: "Надолго", + DataKey: "rate_type", + DataValue: "long_term", + Children: []*approvalflow.FlowNode{ + { + Key: "long_term_input", + IsInput: true, + InputKey: "content", + InputHint: "Опишите долгосрочные ставки: маршрут, стоимость, период", + }, + }, + }, + }, + } +} + +func (r *RatesLogisticsTopic) TopicCodeFromCollected(collected map[string]string) (string, error) { + rateType := collected["rate_type"] + if rateType == "" { + return "", fmt.Errorf("rate_type не указан") + } + return fmt.Sprintf("rates_logistics_%s", rateType), nil +} + +func (r *RatesLogisticsTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { + name := "" + if initiator.FullName != nil { + name = *initiator.FullName + } + + typeLabel := "Разово" + if collected["rate_type"] == "long_term" { + typeLabel = "Надолго" + } + + return fmt.Sprintf( + "📋 Ставки логистика — %s\n\n"+ + "%s:\n%s", + typeLabel, name, collected["content"], + ) +} diff --git a/service/telegram_service/handlers/approval/topics/receipts/topic.go b/service/telegram_service/handlers/approval/topics/receipts/topic.go new file mode 100644 index 0000000..c8c88da --- /dev/null +++ b/service/telegram_service/handlers/approval/topics/receipts/topic.go @@ -0,0 +1,81 @@ +package receipts + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/telegram_service/approvalflow" + "fmt" +) + +type ReceiptsTopic struct{} + +func NewReceiptsTopic() *ReceiptsTopic { + return &ReceiptsTopic{} +} + +func (r *ReceiptsTopic) Code() string { return "receipts" } +func (r *ReceiptsTopic) Name() string { + return "Поступления по приходным документам" +} + +func (r *ReceiptsTopic) BuildTree() *approvalflow.FlowNode { + return &approvalflow.FlowNode{ + Key: "receipts", + Label: "Поступления", + Children: []*approvalflow.FlowNode{ + { + Key: "f1", + Label: "Ф1", + DataKey: "branch", + DataValue: "f1", + Children: []*approvalflow.FlowNode{ + { + Key: "f1_input", + IsInput: true, + InputKey: "content", + InputHint: "Опишите поступление по филиалу Ф1: товар, количество, поставщик", + }, + }, + }, + { + Key: "f2", + Label: "Ф2", + DataKey: "branch", + DataValue: "f2", + Children: []*approvalflow.FlowNode{ + { + Key: "f2_input", + IsInput: true, + InputKey: "content", + InputHint: "Опишите поступление по филиалу Ф2: товар, количество, поставщик", + }, + }, + }, + }, + } +} + +func (r *ReceiptsTopic) TopicCodeFromCollected(collected map[string]string) (string, error) { + branch := collected["branch"] + if branch == "" { + return "", fmt.Errorf("branch не указан") + } + return fmt.Sprintf("receipts_%s", branch), nil +} + +func (r *ReceiptsTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { + name := "" + if initiator.FullName != nil { + name = *initiator.FullName + } + + branchLabel := "Ф1" + if collected["branch"] == "f2" { + branchLabel = "Ф2" + } + + return fmt.Sprintf( + "📋 Поступления — %s\n\n"+ + "%s:\n%s", + branchLabel, name, collected["content"], + ) +} diff --git a/service/telegram_service/handlers/approval/topics/returns/topic.go b/service/telegram_service/handlers/approval/topics/returns/topic.go new file mode 100644 index 0000000..ba6977c --- /dev/null +++ b/service/telegram_service/handlers/approval/topics/returns/topic.go @@ -0,0 +1,177 @@ +package returns + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/telegram_service/approvalflow" + "fmt" +) + +type ReturnsTopic struct{} + +func NewReturnsTopic() *ReturnsTopic { + return &ReturnsTopic{} +} + +func (r *ReturnsTopic) Code() string { return "returns" } +func (r *ReturnsTopic) Name() string { return "Возвраты" } + +// BuildTree: Тип возврата → Регион → Ввод +// Примечание: "Продажа другим менеджером" требует выбора менеджера - +// это будет реализовано позже через дополнительный флоу +func (r *ReturnsTopic) BuildTree() *approvalflow.FlowNode { + return &approvalflow.FlowNode{ + Key: "returns", + Label: "Возвраты", + Children: []*approvalflow.FlowNode{ + { + Key: "supplier", + Label: "Возврат поставщику", + DataKey: "return_type", + DataValue: "supplier", + Children: []*approvalflow.FlowNode{ + { + Key: "supplier_crimea", + Label: "Крым", + DataKey: "region", + DataValue: "crimea", + Children: []*approvalflow.FlowNode{ + { + Key: "supplier_crimea_input", + IsInput: true, + InputKey: "content", + InputHint: "Бишули\n28 гр.1881 бесцветная (9504) ПФ - 2 короба\nРеализация товаров и услуг ЧП000001326 от 20.04.2026 8:00:01\nФ1\n\nПричина: Короб приехал с завода и сильно порвался в дороге, клиент не может на свою продукцию использовать его", + }, + }, + }, + { + Key: "supplier_krasnodar", + Label: "Краснодар", + DataKey: "region", + DataValue: "krasnodar", + Children: []*approvalflow.FlowNode{ + { + Key: "supplier_krasnodar_input", + IsInput: true, + InputKey: "content", + InputHint: "Бишули\n28 гр.1881 бесцветная (9504) ПФ - 2 короба\nРеализация товаров и услуг ЧП000001326 от 20.04.2026 8:00:01\nФ1\n\nПричина: Короб приехал с завода и сильно порвался в дороге, клиент не может на свою продукцию использовать его", + }, + }, + }, + }, + }, + { + Key: "other_manager", + Label: "Продажа другим менеджером", + DataKey: "return_type", + DataValue: "other_manager", + Children: []*approvalflow.FlowNode{ + { + Key: "other_manager_crimea", + Label: "Крым", + DataKey: "region", + DataValue: "crimea", + Children: []*approvalflow.FlowNode{ + { + Key: "other_manager_crimea_input", + IsInput: true, + InputKey: "content", + InputHint: "Бишули\n61 гр.38 мм бесцветная (3888) ЕП - 11 коробов\nРеализация товаров и услуг ЧП000000584 от 05.03.2026 8:00:01\nФ1\n\nПричина: Часть заказа отвалилась, будут переходить на эту позицию не раньше, чем через 3 мес\n\nПродаст выбранный менеджер на Бойко", + }, + }, + }, + { + Key: "other_manager_krasnodar", + Label: "Краснодар", + DataKey: "region", + DataValue: "krasnodar", + Children: []*approvalflow.FlowNode{ + { + Key: "other_manager_krasnodar_input", + IsInput: true, + InputKey: "content", + InputHint: "Бишули\n61 гр.38 мм бесцветная (3888) ЕП - 11 коробов\nРеализация товаров и услуг ЧП000000584 от 05.03.2026 8:00:01\nФ1\n\nПричина: Часть заказа отвалилась, будут переходить на эту позицию не раньше, чем через 3 мес\n\nПродаст выбранный менеджер на Бойко", + }, + }, + }, + }, + }, + { + Key: "self_sale", + Label: "Самостоятельная продажа", + DataKey: "return_type", + DataValue: "self_sale", + Children: []*approvalflow.FlowNode{ + { + Key: "self_sale_crimea", + Label: "Крым", + DataKey: "region", + DataValue: "crimea", + Children: []*approvalflow.FlowNode{ + { + Key: "self_sale_crimea_input", + IsInput: true, + InputKey: "content", + InputHint: "ТД Крымэколайф\n40,5 гр.1881 бесцветная (7808) ПФ - 52 короба\nРеализация товаров и услуг ЧП000003123 от 4.08.25\nФ1\n\nПричина: для сокращения долга клиента\n\nДействия: продам ООО Нива", + }, + }, + }, + { + Key: "self_sale_krasnodar", + Label: "Краснодар", + DataKey: "region", + DataValue: "krasnodar", + Children: []*approvalflow.FlowNode{ + { + Key: "self_sale_krasnodar_input", + IsInput: true, + InputKey: "content", + InputHint: "ТД Крымэколайф\n40,5 гр.1881 бесцветная (7808) ПФ - 52 короба\nРеализация товаров и услуг ЧП000003123 от 4.08.25\nФ1\n\nПричина: для сокращения долга клиента\n\nДействия: продам ООО Нива", + }, + }, + }, + }, + }, + }, + } +} + +func (r *ReturnsTopic) TopicCodeFromCollected(collected map[string]string) (string, error) { + returnType := collected["return_type"] + region := collected["region"] + + if returnType == "" || region == "" { + return "", fmt.Errorf("неполные данные: return_type=%s, region=%s", returnType, region) + } + + return fmt.Sprintf("returns_%s_%s", returnType, region), nil +} + +func (r *ReturnsTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { + name := "" + if initiator.FullName != nil { + name = *initiator.FullName + } + + var typeLabel string + switch collected["return_type"] { + case "supplier": + typeLabel = "Возврат поставщику" + case "other_manager": + typeLabel = "Продажа другим менеджером" + case "self_sale": + typeLabel = "Самостоятельная продажа" + default: + typeLabel = "Возврат" + } + + regionLabel := "Крым" + if collected["region"] == "krasnodar" { + regionLabel = "Краснодар" + } + + return fmt.Sprintf( + "📋 %s — %s\n\n"+ + "%s:\n%s", + typeLabel, regionLabel, name, collected["content"], + ) +} diff --git a/service/telegram_service/handlers/approval/topics/shipments_soh/topic.go b/service/telegram_service/handlers/approval/topics/shipments_soh/topic.go new file mode 100644 index 0000000..fa5b796 --- /dev/null +++ b/service/telegram_service/handlers/approval/topics/shipments_soh/topic.go @@ -0,0 +1,97 @@ +package shipments_soh + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/telegram_service/approvalflow" + "fmt" +) + +type ShipmentsSOHTopic struct{} + +func NewShipmentsSOHTopic() *ShipmentsSOHTopic { return &ShipmentsSOHTopic{} } + +func (s *ShipmentsSOHTopic) Code() string { return "shipments_soh" } +func (s *ShipmentsSOHTopic) Name() string { return "Отгрузки на СОХ" } + +func (s *ShipmentsSOHTopic) BuildTree() *approvalflow.FlowNode { + return &approvalflow.FlowNode{ + Key: "shipments_soh", + Label: "Отгрузки на СОХ", + Children: []*approvalflow.FlowNode{ + s.buildRegion("crimea", "Крым"), + s.buildRegion("krasnodar", "Краснодар"), + }, + } +} + +func (s *ShipmentsSOHTopic) buildRegion(regionKey, regionLabel string) *approvalflow.FlowNode { + return &approvalflow.FlowNode{ + Key: regionKey, + Label: regionLabel, + DataKey: "region", + DataValue: regionKey, + Children: []*approvalflow.FlowNode{ + { + Key: regionKey + "_real", + Label: "Реальная", + DataKey: "shipment_type", + DataValue: "real", + Children: []*approvalflow.FlowNode{{ + Key: regionKey + "_real_input", + IsInput: true, + InputKey: "content", + InputHint: "Прошу согласовать перемещение на СОХ\nНива ООО \n31,6 гр. 1810 бесцветная (8352) АТФ 5 кор. 7,21 руб.\n81 гр.48 мм бесцветная (2464) ОП 10 кор. 18,23 руб.\nна сумму 750 276,8 руб.\nОстаток лимита у клиента с учётом текущей задолженности 2 656 689,12 руб.", + }}, + }, + { + Key: regionKey + "_limit", + Label: "Для лимита", + DataKey: "shipment_type", + DataValue: "limit", + Children: []*approvalflow.FlowNode{{ + Key: regionKey + "_limit_input", + IsInput: true, + InputKey: "content", + InputHint: "ЭКОИЛЬИЧПРОДУКТ ООО\nна сумму 750 276,8 руб\nОстаток лимита у клиента с учётом текущей задолженности 2 656 689,12 руб", + }}, + }, + }, + } +} + +func (s *ShipmentsSOHTopic) TopicCodeFromCollected(collected map[string]string) (string, error) { + region := collected["region"] + shipmentType := collected["shipment_type"] + if region == "" || shipmentType == "" { + return "", fmt.Errorf("неполные данные: region=%s, shipment_type=%s", region, shipmentType) + } + return fmt.Sprintf("shipments_soh_%s_%s", region, shipmentType), nil +} + +func (s *ShipmentsSOHTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { + name := "" + if initiator.FullName != nil { + name = *initiator.FullName + } + + regionLabel := collected["region"] + switch regionLabel { + case "crimea": + regionLabel = "Крым" + case "krasnodar": + regionLabel = "Краснодар" + } + + typeLabel := collected["shipment_type"] + switch typeLabel { + case "real": + typeLabel = "Реальная" + case "limit": + typeLabel = "Для лимита" + } + + return fmt.Sprintf( + "📋 Отгрузки на СОХ — %s (%s)\n\n%s:\n%s", + regionLabel, typeLabel, name, collected["content"], + ) +} diff --git a/service/telegram_service/handlers/approval/topics/sick_leave/topic.go b/service/telegram_service/handlers/approval/topics/sick_leave/topic.go new file mode 100644 index 0000000..2a4bf41 --- /dev/null +++ b/service/telegram_service/handlers/approval/topics/sick_leave/topic.go @@ -0,0 +1,116 @@ +package sickleave + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/telegram_service/approvalflow" + "fmt" +) + +type SickLeaveTopic struct{} + +func NewSickLeaveTopic() *SickLeaveTopic { return &SickLeaveTopic{} } + +func (o *SickLeaveTopic) Code() string { return "sickleave" } +func (o *SickLeaveTopic) Name() string { return "Официальный больничный" } + +func (o *SickLeaveTopic) BuildTree() *approvalflow.FlowNode { + return &approvalflow.FlowNode{ + Key: "sickleave", + Label: "Официальный больничный", + Children: []*approvalflow.FlowNode{ + { + // 🚀 Уникальный ключ: sl_open_date + Key: "sl_open_date", + IsInput: true, + InputKey: "open_date", + InputHint: "Введите дату открытия больничного листа (например: 22.02.2022)", + Children: []*approvalflow.FlowNode{ + { + // 🚀 Уникальный ключ: sl_vacation (не конфликтует с vacation-темой) + Key: "sl_vacation", Label: "В счёт отпуска", + DataKey: "payment_type", DataValue: "vacation_account", + Children: []*approvalflow.FlowNode{ + o.buildDuration("sl_single_day", "На один день", "22.02.2022"), + o.buildDuration("sl_date_range", "Диапазон дат", "22.02.2022 - 25.02.2022"), + }, + }, + { + // 🚀 Уникальный ключ: sl_official + Key: "sl_official", Label: "Только оф. больничный", + DataKey: "payment_type", DataValue: "official", + Children: []*approvalflow.FlowNode{ + o.buildDuration("sl_single_day", "На один день", "22.02.2022"), + o.buildDuration("sl_date_range", "Диапазон дат", "22.02.2022 - 25.02.2022"), + }, + }, + }, + }, + }, + } +} + +// 🚀 Все ключи теперь с префиксом sl_ +func (o *SickLeaveTopic) buildDuration(durKey, durLabel, hint string) *approvalflow.FlowNode { + return &approvalflow.FlowNode{ + Key: durKey, Label: durLabel, + DataKey: "duration_type", DataValue: durKey, // ⚠️ DataValue тоже с префиксом — нужно учесть в TopicCodeFromCollected + Children: []*approvalflow.FlowNode{ + { + Key: durKey + "_input", + IsInput: true, + InputKey: "content", + InputHint: hint, + DataKey: "time_type", DataValue: "full_day", + }, + }, + } +} + +func (o *SickLeaveTopic) TopicCodeFromCollected(collected map[string]string) (string, error) { + dur := collected["duration_type"] + payment := collected["payment_type"] + if dur == "" || payment == "" { + return "", fmt.Errorf("неполные данные для определения темы: %v", collected) + } + + // 🚀 Убираем префикс sl_ из duration_type, т.к. код темы в БД без префикса + durClean := dur + if len(durClean) > 3 && durClean[:3] == "sl_" { + durClean = durClean[3:] + } + + return fmt.Sprintf("sickleave_%s_full_day_%s", durClean, payment), nil +} + +func (o *SickLeaveTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { + name := "" + if initiator.FullName != nil { + name = *initiator.FullName + } + + var paymentLabel string + switch collected["payment_type"] { + case "vacation_account": + paymentLabel = "в счёт ежегодного отпуска" + case "official": + paymentLabel = "только официальный больничный" + default: + paymentLabel = collected["payment_type"] + } + + content := collected["content"] + openDate := collected["open_date"] + if openDate != "" { + content = fmt.Sprintf("Дата открытия больничного листа - %s.\n%s", openDate, content) + } + + msg := fmt.Sprintf( + "📋 Тип: Официальный больничный\n\n"+ + "%s: прошу согласовать больничный\n"+ + "%s\n"+ + "%s", + name, content, paymentLabel, + ) + + return msg +} diff --git a/service/telegram_service/handlers/approval/topics/time_off/time_off.go b/service/telegram_service/handlers/approval/topics/time_off/time_off.go new file mode 100644 index 0000000..339944f --- /dev/null +++ b/service/telegram_service/handlers/approval/topics/time_off/time_off.go @@ -0,0 +1,123 @@ +package timeoff + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/telegram_service/approvalflow" + "fmt" +) + +type TimeOffTopic struct{} + +func NewTimeOffTopic() *TimeOffTopic { return &TimeOffTopic{} } + +func (o *TimeOffTopic) Code() string { return "timeoff" } +func (o *TimeOffTopic) Name() string { return "Отгул" } + +// BuildTree строит дерево навигации согласно бизнес-логике: +// длительность → тип дня → тип оплаты (только для весь день) → ввод +func (o *TimeOffTopic) BuildTree() *approvalflow.FlowNode { + return &approvalflow.FlowNode{ + Key: "timeoff", + Label: "Отгул", + Children: []*approvalflow.FlowNode{ + o.buildDuration("single_day", "На один день", + "22.02.2022", + "22.02.2022 с 16:00 по 18:00"), + o.buildDuration("multi_day", "Несколько дней", + "22.02.2022, 24.02.2022, 26.02.2022", + "22.02.2022 с 10:00 по 14:00, 24.02.2022 с 09:00 по 12:00"), + }, + } +} + +// buildDuration — общий строитель поддерева для каждого типа длительности. +// fullHint и partialHint — шаблоны ввода для каждой ветки. +func (o *TimeOffTopic) buildDuration(durKey, durLabel, fullHint, partialHint string) *approvalflow.FlowNode { + return &approvalflow.FlowNode{ + Key: durKey, Label: durLabel, + DataKey: "duration_type", DataValue: durKey, + Children: []*approvalflow.FlowNode{ + { + // Весь день → выбор типа оплаты + Key: durKey + "_full", Label: "Весь день", + DataKey: "time_type", DataValue: "full_day", + Children: []*approvalflow.FlowNode{ + { + Key: durKey + "_full_own", Label: "За свой счёт", + DataKey: "payment_type", DataValue: "own_expense", + Children: []*approvalflow.FlowNode{ + { + Key: durKey + "_full_own_input", + IsInput: true, + InputKey: "content", + InputHint: fullHint, + }, + }, + }, + { + Key: durKey + "_full_vac", Label: "В счёт отпуска", + DataKey: "payment_type", DataValue: "vacation_account", + Children: []*approvalflow.FlowNode{ + { + Key: durKey + "_full_vac_input", + IsInput: true, + InputKey: "content", + InputHint: fullHint, + }, + }, + }, + }, + }, + { + // Частично → сразу ввод (оплата только за свой счёт) + Key: durKey + "_partial", Label: "Частично", + DataKey: "time_type", DataValue: "partial", + Children: []*approvalflow.FlowNode{ + // payment_type проставляем автоматически, узел ввода сразу + { + Key: durKey + "_partial_input", + IsInput: true, + InputKey: "content", + InputHint: partialHint, + DataKey: "payment_type", DataValue: "own_expense", // авто + }, + }, + }, + }, + } +} + +// TopicCodeFromCollected возвращает code конкретной записи approvalflow_topics. +// Формат: timeoff_{duration_type}_{time_type}_{payment_type} +func (o *TimeOffTopic) TopicCodeFromCollected(collected map[string]string) (string, error) { + dur := collected["duration_type"] + timeType := collected["time_type"] + payment := collected["payment_type"] + if dur == "" || timeType == "" || payment == "" { + return "", fmt.Errorf("неполные данные для определения темы: %v", collected) + } + return fmt.Sprintf("timeoff_%s_%s_%s", dur, timeType, payment), nil +} + +// FormatApproverMessage форматирует сообщение для согласующего. +func (o *TimeOffTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { + name := "" + if initiator.FullName != nil { + name = *initiator.FullName + } + + paymentLabel := "за свой счёт" + if collected["payment_type"] == "vacation_account" { + paymentLabel = "в счёт ежегодного отпуска" + } + + return fmt.Sprintf( + "📋 Тип: Отгул\n\n"+ + "%s: прошу согласовать отгул\n"+ + "%s\n"+ + "%s", + name, + collected["content"], + paymentLabel, + ) +} diff --git a/service/telegram_service/handlers/approval/topics/transaction_passport/topic.go b/service/telegram_service/handlers/approval/topics/transaction_passport/topic.go new file mode 100644 index 0000000..b6328ab --- /dev/null +++ b/service/telegram_service/handlers/approval/topics/transaction_passport/topic.go @@ -0,0 +1,100 @@ +package transactionpassport + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/telegram_service/approvalflow" + "fmt" +) + +type TransactionPassportTopic struct{} + +func NewTransactionPassportTopic() *TransactionPassportTopic { + return &TransactionPassportTopic{} +} + +func (t *TransactionPassportTopic) Code() string { return "transaction_passport" } +func (t *TransactionPassportTopic) Name() string { return "Паспорт сделки" } + +func (t *TransactionPassportTopic) BuildTree() *approvalflow.FlowNode { + return &approvalflow.FlowNode{ + Key: "transaction_passport", + Label: "Паспорт сделки", + Children: []*approvalflow.FlowNode{ + { + Key: "krasnodar", + Label: "Краснодар", + DataKey: "region", + DataValue: "krasnodar", + Children: []*approvalflow.FlowNode{ + { + Key: "krasnodar_input", + IsInput: true, + InputKey: "content", + InputHint: "Текст для паспорта сделки (Краснодар)", + }, + }, + }, + { + Key: "crimea", + Label: "Крым", + DataKey: "region", + DataValue: "crimea", + Children: []*approvalflow.FlowNode{ + { + Key: "crimea_input", + IsInput: true, + InputKey: "content", + InputHint: "Текст для паспорта сделки (Крым)", + }, + }, + }, + { + Key: "belarus", + Label: "Беларусь", + DataKey: "region", + DataValue: "belarus", + Children: []*approvalflow.FlowNode{ + { + Key: "belarus_input", + IsInput: true, + InputKey: "content", + InputHint: "Текст для паспорта сделки (Беларусь)", + }, + }, + }, + }, + } +} + +func (t *TransactionPassportTopic) TopicCodeFromCollected(collected map[string]string) (string, error) { + region := collected["region"] + if region == "" { + return "", fmt.Errorf("region не указан") + } + return fmt.Sprintf("transaction_passport_%s", region), nil +} + +func (t *TransactionPassportTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { + name := "" + if initiator.FullName != nil { + name = *initiator.FullName + } + + var regionLabel string + switch collected["region"] { + case "krasnodar": + regionLabel = "Краснодар" + case "crimea": + regionLabel = "Крым" + case "belarus": + regionLabel = "Беларусь" + default: + regionLabel = collected["region"] + } + + return fmt.Sprintf( + "📋 Паспорт сделки — %s\n\n"+ + "%s:\n%s", + regionLabel, name, collected["content"], + ) +} diff --git a/service/telegram_service/handlers/approval/topics/vacation/topic.go b/service/telegram_service/handlers/approval/topics/vacation/topic.go new file mode 100644 index 0000000..3b849af --- /dev/null +++ b/service/telegram_service/handlers/approval/topics/vacation/topic.go @@ -0,0 +1,89 @@ +package vacation + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/telegram_service/approvalflow" + "fmt" +) + +type VacationTopic struct{} + +func NewVacationTopic() *VacationTopic { return &VacationTopic{} } + +func (o *VacationTopic) Code() string { return "vacation" } +func (o *VacationTopic) Name() string { return "Отпуск" } + +func (o *VacationTopic) BuildTree() *approvalflow.FlowNode { + return &approvalflow.FlowNode{ + Key: "vacation", + Label: "Отпуск", + Children: []*approvalflow.FlowNode{ + o.buildDuration("vac_single_day", "На один день", "22.02.2022", "single_day"), + o.buildDuration("vac_date_range", "Диапазон дат", "22.02.2022 - 25.02.2022", "date_range"), + o.buildDuration("vac_multi_day", "Несколько дней", "22.02.2022, 24.02.2022, 26.02.2022", "multi_day"), + }, + } +} + +func (o *VacationTopic) buildDuration(key, durLabel, hint, dataValue string) *approvalflow.FlowNode { + return &approvalflow.FlowNode{ + Key: key, Label: durLabel, + DataKey: "duration_type", DataValue: dataValue, + Children: []*approvalflow.FlowNode{ + { + Key: key + "_own", Label: "За свой счёт", + DataKey: "payment_type", DataValue: "own_expense", + Children: []*approvalflow.FlowNode{ + { + Key: key + "_own_input", + IsInput: true, + InputKey: "content", + InputHint: hint, + DataKey: "time_type", DataValue: "full_day", + }, + }, + }, + { + Key: key + "_vac", Label: "В счёт отпуска", + DataKey: "payment_type", DataValue: "vacation_account", + Children: []*approvalflow.FlowNode{ + { + Key: key + "_vac_input", + IsInput: true, + InputKey: "content", + InputHint: hint, + DataKey: "time_type", DataValue: "full_day", + }, + }, + }, + }, + } +} + +func (o *VacationTopic) TopicCodeFromCollected(collected map[string]string) (string, error) { + dur := collected["duration_type"] + payment := collected["payment_type"] + if dur == "" || payment == "" { + return "", fmt.Errorf("неполные данные для определения темы: %v", collected) + } + // 🚀 DataValue уже без префикса — ничего убирать не нужно + return fmt.Sprintf("vacation_%s_full_day_%s", dur, payment), nil +} + +func (o *VacationTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { + name := "" + if initiator.FullName != nil { + name = *initiator.FullName + } + paymentLabel := "за свой счёт" + if collected["payment_type"] == "vacation_account" { + paymentLabel = "в счёт ежегодного отпуска" + } + return fmt.Sprintf( + "📋 Тип: Отпуск\n\n"+ + "%s: прошу согласовать отпуск\n"+ + "%s\n"+ + "%s", + name, collected["content"], paymentLabel, + ) +} diff --git a/service/telegram_service/handlers/faq/handler.go b/service/telegram_service/handlers/faq/handler.go new file mode 100644 index 0000000..cf1b7f5 --- /dev/null +++ b/service/telegram_service/handlers/faq/handler.go @@ -0,0 +1,97 @@ +package faq + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/core/utilscore" + "bitrix_balancer_api/telegram_service/keyboard" + "bitrix_balancer_api/telegram_service/types" + "context" + "fmt" + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" + "github.com/sirupsen/logrus" +) + +type HandlerFAQ struct { + ipc *types.InternalProviderControl +} + +func NewHandler(ipc *types.InternalProviderControl) *HandlerFAQ { + return &HandlerFAQ{ + ipc: ipc, + } +} + +// Handle — точка входа для команды /start. +// Если пользователь уже зарегистрирован — приветствуем. +// Если нет — запускаем флоу регистрации. +func (h *HandlerFAQ) Handle(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) { + ctx := context.Background() + + existing, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, msg.From.ID) + if err != nil { + logrus.Error("start.Handle: GetUserByTelegramIDDB: ", err) + return + } + + // Пользователь уже есть — показываем главное меню или сообщение об ожидании отдела + if existing != nil { + h.sendHowToCreate(bot, msg.Chat.ID, msg.From.ID, existing) + return + } +} + +func (h *HandlerFAQ) sendHowToCreate(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, user *typescore.User) { + ctx := context.Background() + name := "" + if user.FullName != nil { + name = *user.FullName + } + + if user.DepartmentID == nil { + utilscore.SendBotMessage(bot, chatID, fmt.Sprintf( + "👋 Здравствуйте, %s!\n\n"+ + "Ожидайте назначения в отдел.\n"+ + "Только по назначению в отдел вы сможете начать работу с системой согласований.", name, + )) + return + } + + // Определяем клавиатуру по роли + replyMarkup := h.buildMenuKeyboard(ctx, user) + + msg := tgbotapi.NewMessage(chatID, fmt.Sprintf( + "👋 Здравствуйте, %s!\n\n"+ + "Данный раздел предназначен для ознакомления с порядком работы в системе согласований.\n\n"+ + "В инструкции будет представлена информация о:\n"+ + "• создании заявок\n"+ + "• направлении заявок на согласование\n"+ + "• отслеживании статуса заявок\n"+ + "• обработке входящих задач\n\n"+ + "📘 Инструкция находится в разработке и будет доступна в ближайшее время.\n"+ + "По возникающим вопросам вы можете обратиться к администратору системы.", + name, + )) + msg.ParseMode = "HTML" + msg.ReplyMarkup = replyMarkup + bot.Send(msg) //nolint:errcheck +} + +// buildMenuKeyboard возвращает клавиатуру в зависимости от роли пользователя +func (h *HandlerFAQ) buildMenuKeyboard(ctx context.Context, user *typescore.User) tgbotapi.ReplyKeyboardMarkup { + if user.ID == nil { + return keyboard.BuildMainMenu(keyboard.UserRole{}) + } + + // Получаем все роли пользователя + isApprover, _ := h.ipc.Database.User.IsApproverDB(ctx, *user.ID) + isObserver, _ := h.ipc.Database.User.IsObserverDB(ctx, *user.ID) + isExecutor, _ := h.ipc.Database.User.IsExecutorDB(ctx, *user.ID) + isDirector, _ := h.ipc.Database.User.IsDirectorDB(ctx, *user.ID) + + return keyboard.BuildMainMenu(keyboard.UserRole{ + IsApprover: isApprover, + IsObserver: isObserver, + IsExecutor: isExecutor, + IsDirector: isDirector, + }) +} diff --git a/service/telegram_service/handlers/start/handler.go b/service/telegram_service/handlers/start/handler.go new file mode 100644 index 0000000..e6eeb51 --- /dev/null +++ b/service/telegram_service/handlers/start/handler.go @@ -0,0 +1,179 @@ +package start + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/core/utilscore" + "bitrix_balancer_api/telegram_service/handlers/approval" + "bitrix_balancer_api/telegram_service/keyboard" + "bitrix_balancer_api/telegram_service/types" + "context" + "fmt" + + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" + "github.com/sirupsen/logrus" +) + +type Handler struct { + approvalHandler *approval.Handler + ipc *types.InternalProviderControl +} + +func NewHandler(ipc *types.InternalProviderControl, approvalHandler *approval.Handler) *Handler { + return &Handler{ + ipc: ipc, + approvalHandler: approvalHandler, + } +} + +// Handle — точка входа для команды /start. +// Если пользователь уже зарегистрирован — приветствуем. +// Если нет — запускаем флоу регистрации. +func (h *Handler) Handle(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) { + ctx := context.Background() + + existing, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, msg.From.ID) + if err != nil { + logrus.Error("start.Handle: GetUserByTelegramIDDB: ", err) + return + } + + // Пользователь уже есть — показываем главное меню или сообщение об ожидании отдела + if existing != nil { + h.sendWelcomeBack(bot, msg.Chat.ID, msg.From.ID, existing) + return + } + + // Новый пользователь — сохраняем состояние "ожидаем ФИО" + stateKey := registrationStateKey(msg.From.ID) + if err := h.ipc.RedisClient.Set(ctx, stateKey, stateAwaitingFullName, registrationTTL); err != nil { + logrus.Error("start.Handle: Set redis state: ", err) + return + } + + utilscore.SendBotMessage(bot, msg.Chat.ID, + "👋 Добро пожаловать в Портал сотрудника РусПЭТ!\n\n"+ + "Для регистрации введите ваше полное имя (Фамилию Имя).\n\n"+ + "Например: Иванов Иван", + ) +} + +// HandleTextInput обрабатывает текстовый ввод в рамках флоу регистрации. +// Возвращает true если сообщение было обработано (пользователь в процессе регистрации). +func (h *Handler) HandleTextInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) bool { + ctx := context.Background() + stateKey := registrationStateKey(msg.From.ID) + + state, err := h.ipc.RedisClient.Get(ctx, stateKey) + if err != nil || state == "" { + return false // не наш ввод + } + + switch state { + case stateAwaitingFullName: + h.handleFullNameInput(ctx, bot, msg, stateKey) + return true + } + + return false +} + +func (h *Handler) handleFullNameInput(ctx context.Context, bot *tgbotapi.BotAPI, msg *tgbotapi.Message, stateKey string) { + fullName := sanitizeFullName(msg.Text) + + if !isValidFullName(fullName) { + utilscore.SendBotMessage(bot, msg.Chat.ID, + "⚠️ Пожалуйста, введите корректное ФИО.\n\n"+ + "Например: Иванов Иван", + ) + return + } + + // Создаём пользователя + telegramID := msg.From.ID + username := msg.From.UserName + langCode := msg.From.LanguageCode + + user := &typescore.User{ + TelegramID: &telegramID, + FullName: &fullName, + LanguageCode: &langCode, + } + if username != "" { + user.Username = &username + } + + created, _, err := h.ipc.Database.User.CreateUserDB(ctx, nil, user, true) + if err != nil { + logrus.Error("start.handleFullNameInput: CreateUserDB: ", err) + utilscore.SendBotMessage(bot, msg.Chat.ID, "Произошла ошибка при регистрации. Попробуйте ещё раз — /start") + return + } + + // Сбрасываем состояние регистрации + h.ipc.RedisClient.Del(ctx, stateKey) //nolint:errcheck + + logrus.Infof("✅ Новый пользователь зарегистрирован: %s (tg_id=%d)", fullName, telegramID) + + h.sendRegistrationDone(bot, msg.Chat.ID, created) +} + +// sendWelcomeBack — приветствие для уже зарегистрированного пользователя. +func (h *Handler) sendWelcomeBack(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, user *typescore.User) { + ctx := context.Background() + name := "" + if user.FullName != nil { + name = *user.FullName + } + + if user.DepartmentID == nil { + utilscore.SendBotMessage(bot, chatID, fmt.Sprintf( + "👋 Здравствуйте, %s!\n\n"+ + "⏳ Ваша учётная запись ожидает назначения в отдел.\n"+ + "Обратитесь к администратору.", name, + )) + return + } + + // Определяем клавиатуру по роли + replyMarkup := h.buildMenuKeyboard(ctx, user) + + msg := tgbotapi.NewMessage(chatID, fmt.Sprintf("👋 Здравствуйте, %s!", name)) + msg.ParseMode = "HTML" + msg.ReplyMarkup = replyMarkup + bot.Send(msg) //nolint:errcheck +} + +// buildMenuKeyboard возвращает клавиатуру в зависимости от роли пользователя +func (h *Handler) buildMenuKeyboard(ctx context.Context, user *typescore.User) tgbotapi.ReplyKeyboardMarkup { + if user.ID == nil { + return keyboard.BuildMainMenu(keyboard.UserRole{}) + } + + // Получаем все роли пользователя + isApprover, _ := h.ipc.Database.User.IsApproverDB(ctx, *user.ID) + isObserver, _ := h.ipc.Database.User.IsObserverDB(ctx, *user.ID) + isExecutor, _ := h.ipc.Database.User.IsExecutorDB(ctx, *user.ID) + isDirector, _ := h.ipc.Database.User.IsDirectorDB(ctx, *user.ID) + + return keyboard.BuildMainMenu(keyboard.UserRole{ + IsApprover: isApprover, + IsObserver: isObserver, + IsExecutor: isExecutor, + IsDirector: isDirector, + }) +} + +// sendRegistrationDone — подтверждение успешной регистрации. +func (h *Handler) sendRegistrationDone(bot *tgbotapi.BotAPI, chatID int64, user *typescore.User) { + name := "" + if user.FullName != nil { + name = *user.FullName + } + + utilscore.SendBotMessage(bot, chatID, fmt.Sprintf( + "✅ Вы успешно зарегистрированы!\n\n"+ + "Имя: %s\n\n"+ + "⏳ Ожидайте назначения в отдел. После этого вам станут доступны функции портала.\n", + name, + )) +} diff --git a/service/telegram_service/handlers/start/helpers.go b/service/telegram_service/handlers/start/helpers.go new file mode 100644 index 0000000..56dcb7e --- /dev/null +++ b/service/telegram_service/handlers/start/helpers.go @@ -0,0 +1,47 @@ +package start + +import ( + "fmt" + "strings" + "time" + "unicode" +) + +const ( + stateAwaitingFullName = "awaiting_full_name" + registrationTTL = 30 * time.Minute +) + +func registrationStateKey(telegramID int64) string { + return fmt.Sprintf("registration:%d", telegramID) +} + +// sanitizeFullName убирает лишние пробелы и приводит к нормальному виду. +func sanitizeFullName(input string) string { + parts := strings.Fields(input) // разбивает по любым пробелам, убирает пустые + for i, p := range parts { + runes := []rune(p) + if len(runes) > 0 { + runes[0] = unicode.ToUpper(runes[0]) + } + parts[i] = string(runes) + } + return strings.Join(parts, " ") +} + +// isValidFullName проверяет что введено минимум два слова (имя + фамилия) +// и нет посторонних символов. +func isValidFullName(name string) bool { + parts := strings.Fields(name) + if len(parts) < 2 { + return false + } + for _, part := range parts { + for _, r := range part { + if !unicode.IsLetter(r) && r != '-' { + return false + } + } + } + return true +} diff --git a/service/telegram_service/handlers/suggestion/handler.go b/service/telegram_service/handlers/suggestion/handler.go new file mode 100644 index 0000000..2e04109 --- /dev/null +++ b/service/telegram_service/handlers/suggestion/handler.go @@ -0,0 +1,450 @@ +package suggestion + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/telegram_service/state" + "bitrix_balancer_api/telegram_service/types" + "context" + "encoding/base64" + "fmt" + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" + "github.com/sirupsen/logrus" +) + +type Handler struct { + ipc *types.InternalProviderControl + States *state.StateManager +} + +func NewHandler(ipc *types.InternalProviderControl) *Handler { + return &Handler{ + ipc: ipc, + States: state.NewStateManager(ipc.RedisClient), + } +} + +func (h *Handler) HandleCreateSuggestion(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) { + ctx := context.Background() + + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || user == nil || user.ID == nil { + sendText(bot, chatID, "⚠️ Пользователь не найден.") + return + } + + // Сохраняем состояние ожидания темы + suggestionState := &state.SuggestionFlowState{ + Stage: "await_subject", + } + h.States.SetSuggestionFlow(ctx, telegramID, suggestionState) //nolint:errcheck + + sendText(bot, chatID, "💡 Новое предложение/пожелание\n\nВведите тему предложения:") +} + +func (h *Handler) HandleSuggestionTextInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) bool { + ctx := context.Background() + telegramID := msg.From.ID + chatID := msg.Chat.ID + + suggestionState, err := h.States.GetSuggestionFlow(ctx, telegramID) + if err != nil { + logrus.Errorf("HandleSuggestionTextInput: GetSuggestionFlow err=%v", err) + return false + } + + if suggestionState == nil { + return false + } + + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil { + logrus.Errorf("HandleSuggestionTextInput: GetUserByTelegramIDDB err=%v", err) + return false + } + + if user == nil || user.ID == nil { + logrus.Warnf("HandleSuggestionTextInput: user not found telegramID=%d", telegramID) + return false + } + + switch suggestionState.Stage { + case "await_subject": + return h.handleSubjectInput(bot, ctx, chatID, telegramID, user, msg.Text) + + case "await_message": + return h.handleMessageInput(bot, ctx, chatID, telegramID, user, suggestionState, msg.Text, nil, nil) + + default: + logrus.Warnf("HandleSuggestionTextInput: unknown stage=%s", suggestionState.Stage) + return false + } +} + +func (h *Handler) handleSubjectInput(bot *tgbotapi.BotAPI, ctx context.Context, chatID, telegramID int64, user *typescore.User, subject string) bool { + directors, err := h.ipc.Database.User.GetDirectorsDB(ctx) + if err != nil { + logrus.Errorf("handleSubjectInput: GetDirectorsDB err=%v", err) + sendText(bot, chatID, "⚠️ Ошибка при получении списка директоров.") + h.States.ClearSuggestionFlow(ctx, telegramID) //nolint:errcheck + return true + } + + if len(directors) == 0 { + sendText(bot, chatID, "⚠️ Директор не найден в системе. Обратитесь к администратору.") + h.States.ClearSuggestionFlow(ctx, telegramID) //nolint:errcheck + return true + } + + // Ищем первого директора с заполненным ID + var director *typescore.User + for _, d := range directors { + if d != nil && d.ID != nil { + director = d + break + } + } + + if director == nil { + logrus.Errorf("handleSubjectInput: all directors have nil ID, count=%d", len(directors)) + sendText(bot, chatID, "⚠️ Директор не найден в системе. Обратитесь к администратору.") + h.States.ClearSuggestionFlow(ctx, telegramID) //nolint:errcheck + return true + } + + // Создаем предложение + openStatus := "open" + suggestion := &typescore.Suggestion{ + InitiatorID: user.ID, + DirectorID: director.ID, + Subject: &subject, + Status: &openStatus, + } + + created, _, err := h.ipc.Database.Suggestion.CreateSuggestionDB(ctx, nil, suggestion, true) + if err != nil { + logrus.Errorf("handleSubjectInput: CreateSuggestionDB err=%v", err) + sendText(bot, chatID, "Ошибка при создании предложения. Попробуйте позже.") + h.States.ClearSuggestionFlow(ctx, telegramID) //nolint:errcheck + return true + } + + if created == nil || created.ID == nil { + logrus.Errorf("handleSubjectInput: created suggestion is nil or has no ID") + sendText(bot, chatID, "Ошибка при создании предложения. Попробуйте позже.") + h.States.ClearSuggestionFlow(ctx, telegramID) //nolint:errcheck + return true + } + + // Обновляем state — переходим к вводу текста + suggestionState := &state.SuggestionFlowState{ + SuggestionID: *created.ID, + Stage: "await_message", + } + if err := h.States.SetSuggestionFlow(ctx, telegramID, suggestionState); err != nil { + logrus.Errorf("handleSubjectInput: SetSuggestionFlow err=%v", err) + sendText(bot, chatID, "Ошибка при сохранении состояния. Попробуйте позже.") + return true + } + + directorName := "директору" + if director.FullName != nil { + directorName = *director.FullName + } + + sendText(bot, chatID, fmt.Sprintf( + "✅ Тема сохранена\n\n"+ + "📋 Тема: %s\n"+ + "👤 Получатель: %s\n\n"+ + "Теперь введите текст предложения или прикрепите файл:", + subject, directorName, + )) + + return true +} + +func (h *Handler) handleMessageInput( + bot *tgbotapi.BotAPI, + ctx context.Context, + chatID, telegramID int64, + user *typescore.User, + suggestionState *state.SuggestionFlowState, + messageText string, + fileData, fileName *string, +) bool { + message := &typescore.SuggestionMessage{ + SuggestionID: &suggestionState.SuggestionID, + UserID: user.ID, + Message: &messageText, + FileData: fileData, + FileName: fileName, + } + + _, _, err := h.ipc.Database.SuggestionMessage.CreateSuggestionMessageDB(ctx, nil, message) + if err != nil { + logrus.Errorf("handleMessageInput: CreateSuggestionMessageDB err=%v", err) + sendText(bot, chatID, "Ошибка при отправке сообщения.") + return true + } + + suggestion, err := h.ipc.Database.Suggestion.GetSuggestionByIDDB(ctx, suggestionState.SuggestionID) + if err != nil || suggestion == nil { + logrus.Errorf("handleMessageInput: GetSuggestionByIDDB err=%v", err) + return true + } + + if suggestion.InitiatorID == nil || suggestion.DirectorID == nil || user.ID == nil { + logrus.Errorf("handleMessageInput: suggestion participants are nil") + return true + } + + sendText(bot, chatID, "✅ Ваше сообщение отправлено.") + + var recipientID uint64 + if *user.ID == *suggestion.InitiatorID { + recipientID = *suggestion.DirectorID + } else { + recipientID = *suggestion.InitiatorID + } + + recipient, err := h.ipc.Database.User.GetUserByIDDB(ctx, recipientID) + if err != nil || recipient == nil { + logrus.Errorf("handleMessageInput: GetUserByIDDB recipient err=%v", err) + h.States.ClearSuggestionFlow(ctx, telegramID) //nolint:errcheck + return true + } + + if recipient.TelegramID != nil { + isNew := suggestionState.Stage == "await_subject" // первое сообщение + h.notifyAboutMessage(bot, ctx, *recipient.TelegramID, suggestion, user, messageText, fileData, fileName, isNew) + } + + h.States.ClearSuggestionFlow(ctx, telegramID) //nolint:errcheck + return true +} + +func (h *Handler) HandleReplyToSuggestion(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, suggestionID uint64) { + ctx := context.Background() + chatID := cq.Message.Chat.ID + telegramID := cq.From.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || user == nil || user.ID == nil { + sendText(bot, chatID, "⚠️ Пользователь не найден.") + return + } + + suggestion, err := h.ipc.Database.Suggestion.GetSuggestionByIDDB(ctx, suggestionID) + if err != nil || suggestion == nil { + sendText(bot, chatID, "⚠️ Предложение не найдено.") + return + } + + if suggestion.InitiatorID == nil || suggestion.DirectorID == nil { + sendText(bot, chatID, "⚠️ Ошибка данных предложения.") + return + } + + // Проверяем что пользователь - участник диалога + isInitiator := *user.ID == *suggestion.InitiatorID + isDirector := *user.ID == *suggestion.DirectorID + + if !isInitiator && !isDirector { + sendText(bot, chatID, "⚠️ Вы не участник этого диалога.") + return + } + + suggestionState := &state.SuggestionFlowState{ + SuggestionID: suggestionID, + Stage: "await_message", + } + h.States.SetSuggestionFlow(ctx, telegramID, suggestionState) //nolint:errcheck + + // Показываем кому пойдёт ответ + var recipientName string + if isInitiator { + director, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *suggestion.DirectorID) + if director != nil && director.FullName != nil { + recipientName = *director.FullName + } + } else { + initiator, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *suggestion.InitiatorID) + if initiator != nil && initiator.FullName != nil { + recipientName = *initiator.FullName + } + } + + subject := "—" + if suggestion.Subject != nil { + subject = *suggestion.Subject + } + + sendText(bot, chatID, fmt.Sprintf( + "💬 Ответить на предложение #%d\n"+ + "📋 Тема: %s\n"+ + "➡️ Получатель: %s\n\n"+ + "Введите текст или прикрепите файл:", + suggestionID, subject, recipientName, + )) +} + +func (h *Handler) HandleViewSuggestion(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, suggestionID uint64) { + ctx := context.Background() + chatID := cq.Message.Chat.ID + telegramID := cq.From.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || user == nil || user.ID == nil { + return + } + + suggestion, err := h.ipc.Database.Suggestion.GetSuggestionByIDDB(ctx, suggestionID) + if err != nil || suggestion == nil { + sendText(bot, chatID, "⚠️ Предложение не найдено.") + return + } + + h.showSuggestionThread(bot, ctx, chatID, suggestion) +} + +func (h *Handler) showSuggestionThread(bot *tgbotapi.BotAPI, ctx context.Context, chatID int64, suggestion *typescore.Suggestion) { + if suggestion.ID == nil { + return + } + + messages, _, err := h.ipc.Database.SuggestionMessage.GetSuggestionMessagesListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.SuggestionMessage{ + SuggestionID: suggestion.ID, + }, + }) + if err != nil { + logrus.Errorf("showSuggestionThread: GetMessagesBySuggestionIDDB err=%v", err) + return + } + + subject := "—" + if suggestion.Subject != nil { + subject = *suggestion.Subject + } + + initiatorName := "—" + if suggestion.InitiatorID != nil { + initiator, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *suggestion.InitiatorID) + if initiator != nil && initiator.FullName != nil { + initiatorName = *initiator.FullName + } + } + + text := fmt.Sprintf( + "💡 Предложение #%d\n\n"+ + "📋 Тема: %s\n"+ + "👤 Автор: %s\n\n"+ + "💬 Переписка:", + *suggestion.ID, subject, initiatorName, + ) + + for _, msg := range messages { + if msg.UserID == nil || msg.Message == nil { + continue + } + + user, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *msg.UserID) + userName := "—" + if user != nil && user.FullName != nil { + userName = *user.FullName + } + + timestamp := "" + if msg.CreatedAt != nil { + timestamp = msg.CreatedAt.Format("02.01.2006 15:04") + } + + text += fmt.Sprintf("\n\n%s (%s):\n%s", userName, timestamp, *msg.Message) + + if msg.FileData != nil && msg.FileName != nil { + text += fmt.Sprintf("\n📎 %s", *msg.FileName) + } + } + + message := tgbotapi.NewMessage(chatID, text) + message.ParseMode = "HTML" + message.ReplyMarkup = buildSuggestionActions(*suggestion.ID) + bot.Send(message) //nolint:errcheck +} + +func (h *Handler) notifyAboutMessage( + bot *tgbotapi.BotAPI, + ctx context.Context, + recipientChatID int64, + suggestion *typescore.Suggestion, + sender *typescore.User, + messageText string, + fileData, fileName *string, + isNew bool, +) { + subject := "—" + if suggestion.Subject != nil { + subject = *suggestion.Subject + } + + senderName := "—" + if sender.FullName != nil { + senderName = *sender.FullName + } + + header := "📬 Новое сообщение" + if isNew { + header = "💡 Новое предложение" + } + + text := fmt.Sprintf( + "%s\n\n"+ + "📋 Тема: %s\n"+ + "👤 От: %s\n"+ + "💬 Сообщение:\n%s", + header, subject, senderName, messageText, + ) + + if fileData != nil && fileName != nil { + // Отправляем файл + decoded, err := base64.StdEncoding.DecodeString(*fileData) + if err != nil { + logrus.Errorf("notifyAboutMessage: base64 decode err=%v", err) + } else { + doc := tgbotapi.NewDocument(recipientChatID, tgbotapi.FileBytes{ + Name: *fileName, + Bytes: decoded, + }) + doc.Caption = text + doc.ParseMode = "HTML" + doc.ReplyMarkup = buildSuggestionActions(*suggestion.ID) + bot.Send(doc) //nolint:errcheck + return + } + } + + msg := tgbotapi.NewMessage(recipientChatID, text) + msg.ParseMode = "HTML" + msg.ReplyMarkup = buildSuggestionActions(*suggestion.ID) + bot.Send(msg) //nolint:errcheck +} + +func buildSuggestionActions(suggestionID uint64) tgbotapi.InlineKeyboardMarkup { + return tgbotapi.NewInlineKeyboardMarkup( + tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData("↩️ Ответить", fmt.Sprintf("sugg_reply:%d", suggestionID)), + ), + tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData("👁 Посмотреть всю переписку", fmt.Sprintf("sugg_view:%d", suggestionID)), + ), + ) +} + +func sendText(bot *tgbotapi.BotAPI, chatID int64, text string) { + msg := tgbotapi.NewMessage(chatID, text) + msg.ParseMode = "HTML" + bot.Send(msg) //nolint:errcheck +} diff --git a/service/telegram_service/keyboard/add_approver.go b/service/telegram_service/keyboard/add_approver.go new file mode 100644 index 0000000..2ae5a3e --- /dev/null +++ b/service/telegram_service/keyboard/add_approver.go @@ -0,0 +1,159 @@ +// telegram_service/keyboard/add_approver.go - ПОЛНОСТЬЮ ЗАМЕНИТЬ + +package keyboard + +import ( + "bitrix_balancer_api/core/lib/external/tgkit" + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/telegram_service/types" + "context" + "fmt" +) + +func BuildAddApproverMainMenu() interface{} { + return tgkit.NewInlineKeyboard(). + Row(tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "Добавить согласующего", "add_appr_create")). + Row(tgkit.Btn("📋 Ранее добавленные", "add_appr_list")). + Build() +} + +func BuildAddApproverCategoryMenu(categories []*typescore.ApprovalTopicCategory, page int) interface{} { + const perPage = 6 + total := len(categories) + totalPages := (total + perPage - 1) / perPage + if page < 0 { + page = 0 + } + if page >= totalPages && totalPages > 0 { + page = totalPages - 1 + } + start, end := page*perPage, page*perPage+perPage + if end > total { + end = total + } + + kb := tgkit.NewInlineKeyboard() + for _, c := range categories[start:end] { + if c.ID == nil || c.Name == nil { + continue + } + kb.Row(tgkit.Btn(*c.Name, fmt.Sprintf("add_appr_category:%d", *c.ID))) + } + if totalPages > 1 { + kb.Rows = append(kb.Rows, buildPageRow(page, totalPages, "add_appr_category_page", "add_appr_page_noop")) + } + return kb.Build() +} + +func BuildAddApproverApprovalMenu(approvals []*typescore.Approval, categoryID uint64, page int, ctx context.Context, ipc *types.InternalProviderControl) interface{} { + const perPage = 6 + total := len(approvals) + totalPages := (total + perPage - 1) / perPage + if page < 0 { + page = 0 + } + if page >= totalPages && totalPages > 0 { + page = totalPages - 1 + } + start, end := page*perPage, page*perPage+perPage + if end > total { + end = total + } + + kb := tgkit.NewInlineKeyboard() + for _, a := range approvals[start:end] { + if a.ID == nil { + continue + } + topicName := "—" + if a.TopicID != nil { + if t, _ := ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *a.TopicID); t != nil && t.Name != nil { + topicName = *t.Name + } + } + kb.Row(tgkit.Btn(fmt.Sprintf("#%d — %s", *a.ID, topicName), fmt.Sprintf("add_appr_approval:%d", *a.ID))) + } + if totalPages > 1 { + kb.Rows = append(kb.Rows, buildPageRow(page, totalPages, + fmt.Sprintf("add_appr_approval_page:%d", categoryID), "add_appr_page_noop")) + } + kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "К категориям", "add_appr_create")) + return kb.Build() +} + +func BuildAddApproverUserMenu(users []*typescore.User, approvalID, categoryID uint64, page int) interface{} { + const perPage = 8 + total := len(users) + totalPages := (total + perPage - 1) / perPage + if page < 0 { + page = 0 + } + if page >= totalPages && totalPages > 0 { + page = totalPages - 1 + } + start, end := page*perPage, page*perPage+perPage + if end > total { + end = total + } + + kb := tgkit.NewInlineKeyboard() + for _, u := range users[start:end] { + if u.ID == nil || u.FullName == nil { + continue + } + kb.Row(tgkit.Btn(*u.FullName, fmt.Sprintf("add_appr_user:%d", *u.ID))) + } + if totalPages > 1 { + kb.Rows = append(kb.Rows, buildPageRow(page, totalPages, + fmt.Sprintf("add_appr_user_page:%d:%d", approvalID, categoryID), "add_appr_page_noop")) + } + kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "Назад", fmt.Sprintf("add_appr_category:%d", categoryID))) + return kb.Build() +} + +func BuildAddedApproversList(items []*typescore.ApprovalAdditionalApprover, page int, ctx context.Context, ipc *types.InternalProviderControl) interface{} { + const perPage = 6 + total := len(items) + totalPages := (total + perPage - 1) / perPage + if page < 0 { + page = 0 + } + if page >= totalPages && totalPages > 0 { + page = totalPages - 1 + } + start, end := page*perPage, page*perPage+perPage + if end > total { + end = total + } + + kb := tgkit.NewInlineKeyboard() + for _, aa := range items[start:end] { + if aa.ID == nil || aa.ApprovalID == nil { + continue + } + approverName := "—" + if aa.ApproverID != nil { + if u, _ := ipc.Database.User.GetUserByIDDB(ctx, *aa.ApproverID); u != nil && u.FullName != nil { + approverName = *u.FullName + } + } + kb.Row(tgkit.Btn(fmt.Sprintf("#%d — %s", *aa.ApprovalID, approverName), fmt.Sprintf("add_appr_detail:%d", *aa.ID))) + } + if totalPages > 1 { + kb.Rows = append(kb.Rows, buildPageRow(page, totalPages, "add_appr_list_page", "add_appr_page_noop")) + } + return kb.Build() +} + +func BuildAddedApproverDetail() interface{} { + return tgkit.NewInlineKeyboard(). + Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "К списку", "add_appr_list")). + Build() +} + +// BuildAddApproverToApproval — добавить согласующего прямо из карточки +func BuildAddApproverToApproval(approvalID uint64) interface{} { + return tgkit.NewInlineKeyboard(). + Row(tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "Добавить согласующего", fmt.Sprintf("add_appr_to_approval:%d", approvalID))). + Build() +} diff --git a/service/telegram_service/keyboard/approval.go b/service/telegram_service/keyboard/approval.go new file mode 100644 index 0000000..4f7c252 --- /dev/null +++ b/service/telegram_service/keyboard/approval.go @@ -0,0 +1,337 @@ +package keyboard + +import ( + "bitrix_balancer_api/core/lib/external/tgkit" + "bitrix_balancer_api/core/utilscore" + "bitrix_balancer_api/telegram_service/approvalflow" + "bitrix_balancer_api/telegram_service/state" + "fmt" + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" +) + +// BuildApproverDecision — кнопки для согласующего +func BuildApproverDecision(approvalID uint64, status string, hasFiles bool, filesCount int) tgbotapi.InlineKeyboardMarkup { + kb := tgkit.NewInlineKeyboard() + + if status == "approved" { + kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleRevision, "Отозвать", fmt.Sprintf("appr_revoke:%d", approvalID))) + kb.Row(tgkit.Btn("📊 Стадия согласования", fmt.Sprintf("appr_stage:%d", approvalID))) + return kb.Build() + } + + if hasFiles { + buttonTitle := fmt.Sprintf("📎 Просмотреть файлы (%d)", filesCount) + kb.Row(tgkit.Btn(buttonTitle, fmt.Sprintf("appr_view_files:%d", approvalID))) + } + + // Для всех остальных статусов — полный набор кнопок + kb.Row( + tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "Да", fmt.Sprintf("appr_yes:%d", approvalID)), + tgkit.BtnStyled(tgkit.ButtonStyleDanger, "Нет", fmt.Sprintf("appr_no:%d", approvalID)), + ). + Row(tgkit.Btn("🔄 Вернуть на доработку", fmt.Sprintf("appr_revision:%d", approvalID))). + Row( + tgkit.Btn("💬 Комментировать", fmt.Sprintf("appr_comment:%d", approvalID)), + tgkit.Btn("📎 Прикрепить файл", fmt.Sprintf("appr_attach:%d", approvalID)), + ). + Row( + tgkit.Btn("➕ Добавить согласующего", fmt.Sprintf("add_appr_to_approval:%d", approvalID)), + ). + Row(tgkit.Btn("📊 Стадия согласования", fmt.Sprintf("appr_stage:%d", approvalID))) + + return kb.Build() +} + +// BuildInitiatorCard — кнопки инициатора на карточке заявки +func BuildInitiatorCard(approvalID uint64, status string, hasFiles bool, filesCount int) interface{} { + kb := tgkit.NewInlineKeyboard() + + if hasFiles { + buttonTitle := fmt.Sprintf("📎 Просмотреть файлы (%d)", filesCount) + kb.Row(tgkit.Btn(buttonTitle, fmt.Sprintf("appr_view_files:%d", approvalID))) + } + + if status != "approved" { + kb.Row(tgkit.Btn("💬 Комментировать", fmt.Sprintf("appr_comment:%d", approvalID))) + } + + if status == "pending" || status == "revision" || status == "approved" { + kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleRevision, "Отозвать", fmt.Sprintf("appr_revoke:%d", approvalID))) + } + + kb.Row(tgkit.Btn("📊 Стадия согласования", fmt.Sprintf("appr_stage:%d", approvalID))) + return kb.Build() +} + +// BuildRevokeButton — кнопка отзыва (для директора и инициатора) +func BuildRevokeButton(approvalID uint64, status string, filesCount int) interface{} { + kb := tgkit.NewInlineKeyboard() + + if filesCount > 0 { + kb.Row(tgkit.Btn(fmt.Sprintf("📎 Просмотреть файлы (%d)", filesCount), fmt.Sprintf("appr_view_files:%d", approvalID))) + } + + if status == "pending" || status == "revision" || status == "approved" { + kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleRevision, "Отозвать заявку", fmt.Sprintf("appr_revoke:%d", approvalID))) + } + + kb.Row(tgkit.Btn("📊 Стадия согласования", fmt.Sprintf("appr_stage:%d", approvalID))) + return kb.Build() +} + +// BuildObserverActions — кнопки наблюдателя +func BuildObserverActions(approvalID uint64, topicCode string, status string, filesCount int) interface{} { + kb := tgkit.NewInlineKeyboard() + + if filesCount > 0 { + kb.Row(tgkit.Btn(fmt.Sprintf("📎 Просмотреть файлы (%d)", filesCount), fmt.Sprintf("appr_view_files:%d", approvalID))) + } + + if status != "approved" { + kb.Row(tgkit.Btn("💬 Комментировать", fmt.Sprintf("appr_comment:%d", approvalID))) + } + + kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "К списку", fmt.Sprintf("obs_back:%s", topicCode))) + return kb.Build() +} + +// BuildExecutorTaskActions — кнопки исполнителя +func BuildExecutorTaskActions(taskID, approvalID uint64) interface{} { + return tgkit.NewInlineKeyboard(). + Row(tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "Выполнено", fmt.Sprintf("task_complete:%d", taskID))). + Row(tgkit.Btn("📎 Прикрепить файл", fmt.Sprintf("executor_attach:%d:%d", taskID, approvalID))). + Row(tgkit.Btn("💬 Комментировать", fmt.Sprintf("appr_comment:%d", approvalID))). + Build() +} + +// BuildApprovalMenu — список тем для создания заявки +func BuildApprovalMenu(topics []approvalflow.Topic, page int) interface{} { + const perPage = 6 + total := len(topics) + totalPages := (total + perPage - 1) / perPage + if page < 0 { + page = 0 + } + if page >= totalPages && totalPages > 0 { + page = totalPages - 1 + } + start := page * perPage + end := start + perPage + if end > total { + end = total + } + + kb := tgkit.NewInlineKeyboard() + for _, t := range topics[start:end] { + kb.Row(tgkit.Btn(t.Name(), fmt.Sprintf("appr:%s:%s", t.Code(), t.Code()))) + } + if totalPages > 1 { + pagination := tgkit.PaginationRow( + page, + totalPages, + fmt.Sprintf("appr_page:%d", page-1), + fmt.Sprintf("appr_page:%d", page+1), + "appr_page_noop", + ) + kb.Rows = append(kb.Rows, pagination) + } + return kb.Build() +} + +// BuildApprovalStep — шаг флоу согласования +func BuildApprovalStep(topicCode string, nodes []*approvalflow.FlowNode) interface{} { + kb := tgkit.NewInlineKeyboard() + for _, n := range nodes { + if n == nil { + continue + } + kb.Row(tgkit.Btn(n.Label, fmt.Sprintf("appr:%s:%s", topicCode, n.Key))) + } + kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "Назад", fmt.Sprintf("appr_back:%s", topicCode))) + return kb.Build() +} + +// BuildApprovalInputPrompt — подсказка ввода +func BuildApprovalInputPrompt(topicCode string) interface{} { + return tgkit.NewInlineKeyboard(). + Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "Назад", fmt.Sprintf("appr_back:%s", topicCode))). + Build() +} + +// BuildRejectOptions — варианты при отклонении +func BuildRejectOptions(approvalID uint64) interface{} { + return tgkit.NewInlineKeyboard(). + Row(tgkit.Btn("💬 Написать причину", fmt.Sprintf("appr_no_comment:%d", approvalID))). + Row(tgkit.Btn("⏳ Отложить", fmt.Sprintf("appr_no_defer:%d", approvalID))). + Row(tgkit.Btn("Отклонить без комментария", fmt.Sprintf("appr_no_skip:%d", approvalID))). + Build() +} + +// BuildRevokeOptions — варианты при отзыве +func BuildRevokeOptions(approvalID uint64) interface{} { + return tgkit.NewInlineKeyboard(). + Row(tgkit.Btn("💬 Написать причину", fmt.Sprintf("appr_revoke_comment:%d", approvalID))). + Row(tgkit.Btn("⏳ Отложить", fmt.Sprintf("appr_revoke_defer:%d", approvalID))). + Row(tgkit.Btn("Отозвать без комментария", fmt.Sprintf("appr_revoke_skip:%d", approvalID))). + Build() +} + +// BuildApprovalRejectComment — кнопка "без комментария" при вводе причины +func BuildApprovalRejectComment(approvalID uint64) interface{} { + return tgkit.NewInlineKeyboard(). + Row(tgkit.Btn("Отправить без комментария", fmt.Sprintf("appr_no_skip:%d", approvalID))). + Build() +} + +// BuildApprovalStagesButton — кнопка стадий +func BuildApprovalStagesButton(approvalID uint64) interface{} { + return tgkit.NewInlineKeyboard(). + Row(tgkit.Btn("📊 Стадия согласования", fmt.Sprintf("appr_stage:%d", approvalID))). + Build() +} + +// BuildFileInputKeyboard — управление файлами в процессе флоу +func BuildFileInputKeyboard(topicCode string, files []state.FileAttachment, required bool) tgbotapi.InlineKeyboardMarkup { + var rows [][]tgbotapi.InlineKeyboardButton + + for i, f := range files { + label := []rune(f.FileName) + if len(label) > 25 { + label = append(label[:22], []rune("...")...) + } + rows = append(rows, tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData("🗑 "+string(label), fmt.Sprintf("appr_file_detach:%d", i)), + )) + } + + if len(files) > 0 { + submitLabel := fmt.Sprintf("✅ Отправить (%s)", utilscore.PluralFiles(len(files))) + rows = append(rows, tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData(submitLabel, "appr_file_submit:"+topicCode), + )) + } + + // Кнопка "без файлов" только если прикрепление НЕ обязательно + if !required { + skipLabel := "📤 Отправить без файлов" + if len(files) == 0 { + skipLabel = "✅ Отправить на согласование (без файлов)" + } + rows = append(rows, tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData(skipLabel, "appr_file_skip:"+topicCode), + )) + } + + rows = append(rows, tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData("← Назад", "appr_back:"+topicCode), + )) + + return tgbotapi.NewInlineKeyboardMarkup(rows...) +} + +// BuildPendingCommentsList — список отложенных заявок +func BuildPendingCommentsList(items []state.PendingCommentItem, topicNames map[uint64]string) interface{} { + kb := tgkit.NewInlineKeyboard() + for _, item := range items { + icon := "❌" + if item.Action == "revoke" { + icon = "↩️" + } + label := fmt.Sprintf("%s #%d", icon, item.ApprovalID) + if name, ok := topicNames[item.ApprovalID]; ok { + label += " — " + name + } + kb.Row(tgkit.Btn(label, fmt.Sprintf("pending_item:%d", item.ApprovalID))) + } + return kb.Build() +} + +// BuildPendingItemOptions — действия по отложенной заявке +func BuildPendingItemOptions(approvalID uint64, action string) interface{} { + commentCB := fmt.Sprintf("appr_no_comment:%d", approvalID) + skipCB := fmt.Sprintf("appr_no_skip:%d", approvalID) + if action == "revoke" { + commentCB = fmt.Sprintf("appr_revoke_comment:%d", approvalID) + skipCB = fmt.Sprintf("appr_revoke_skip:%d", approvalID) + } + return tgkit.NewInlineKeyboard(). + Row(tgkit.Btn("💬 Написать причину", commentCB)). + Row(tgkit.Btn("Без комментария", skipCB)). + Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "К списку", "pending_back")). + Build() +} + +// BuildAttachFileCancel — отмена прикрепления файла +func BuildAttachFileCancel(approvalID uint64) interface{} { + return tgkit.NewInlineKeyboard(). + Row(tgkit.BtnStyled(tgkit.ButtonStyleDanger, "Отмена", fmt.Sprintf("appr_attach_cancel:%d", approvalID))). + Build() +} + +// BuildMultiSelectStep — мультиселект (например, системы ОКБ/1С/Битрикс) +func BuildMultiSelectStep(topicCode string, nodes []*approvalflow.FlowNode, selectedValues []string, allowedTopicCodes map[string]bool) tgbotapi.InlineKeyboardMarkup { + selectedSet := make(map[string]bool, len(selectedValues)) + for _, v := range selectedValues { + selectedSet[v] = true + } + + kb := tgkit.NewInlineKeyboard() + for _, n := range nodes { + if n == nil { + continue + } + if n.TopicCode != "" && allowedTopicCodes != nil && !allowedTopicCodes[n.TopicCode] { + continue + } + label := n.Label + if selectedSet[n.MultiSelectValue] { + label = "✅ " + label + } + kb.Row(tgkit.Btn(label, fmt.Sprintf("appr_ms_toggle:%s:%s:%s", topicCode, n.Key, n.MultiSelectValue))) + } + + confirmLabel := "✅ Подтвердить" + if len(selectedValues) > 0 { + confirmLabel = fmt.Sprintf("✅ Подтвердить (%d)", len(selectedValues)) + } + kb.Row(tgkit.Btn(confirmLabel, fmt.Sprintf("appr_ms_confirm:%s", topicCode))) + kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "Назад", fmt.Sprintf("appr_back:%s", topicCode))) + return kb.Build() +} + +// вспомогательная функция пагинации +func buildPageRow(page, totalPages int, prefix, noop string) []tgbotapi.InlineKeyboardButton { + var row []tgbotapi.InlineKeyboardButton + if page > 0 { + row = append(row, tgkit.Btn("←", fmt.Sprintf("%s:%d", prefix, page-1)).Build()) + } + if page < totalPages-1 { + row = append(row, tgkit.Btn(fmt.Sprintf("%d/%d →", page+1, totalPages), fmt.Sprintf("%s:%d", prefix, page+1)).Build()) + } else { + row = append(row, tgkit.Btn(fmt.Sprintf("%d/%d", page+1, totalPages), noop).Build()) + } + return row +} + +func BuildAttachSessionKeyboard(approvalID uint64, fileCount int) tgbotapi.InlineKeyboardMarkup { + kb := tgkit.NewInlineKeyboard() + + if fileCount > 0 { + kb.Row(tgkit.Btn( + fmt.Sprintf("✅ Отправить файлы (%d)", fileCount), + fmt.Sprintf("attach_submit:%d", approvalID), + )) + kb.Row(tgkit.Btn( + "🗑 Очистить все", + fmt.Sprintf("attach_clear:%d", approvalID), + )) + } + + kb.Row(tgkit.BtnStyled( + tgkit.ButtonStyleDanger, + "Отмена", + fmt.Sprintf("attach_cancel:%d", approvalID), + )) + + return kb.Build() +} diff --git a/service/telegram_service/keyboard/builder.go b/service/telegram_service/keyboard/builder.go new file mode 100644 index 0000000..419a008 --- /dev/null +++ b/service/telegram_service/keyboard/builder.go @@ -0,0 +1,64 @@ +package keyboard + +import ( + "bitrix_balancer_api/core/lib/external/tgkit" + "fmt" + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" +) + +// ApprovalsSubmenuKeyboard - подменю "Согласования" +func ApprovalsSubmenuKeyboard(isObserver, isApprover bool) tgbotapi.ReplyKeyboardMarkup { + rows := [][]tgbotapi.KeyboardButton{ + tgbotapi.NewKeyboardButtonRow( + tgbotapi.NewKeyboardButton("Согласования"), + tgbotapi.NewKeyboardButton("Создать согласование"), + ), + } + if isApprover { + rows = append(rows, tgbotapi.NewKeyboardButtonRow( + tgbotapi.NewKeyboardButton("Сформировать отчёт"), + tgbotapi.NewKeyboardButton("Делегирование прав"), + )) + rows = append(rows, tgbotapi.NewKeyboardButtonRow( + tgbotapi.NewKeyboardButton("Добавить согласующего"), + )) + } + + rows = append(rows, tgbotapi.NewKeyboardButtonRow( + tgbotapi.NewKeyboardButton("← Назад"), + )) + + return tgbotapi.NewReplyKeyboard(rows...) +} + +// ApprovalsListSubmenuKeyboard - подменю "Список согласований" +func ApprovalsListSubmenuKeyboard() tgbotapi.ReplyKeyboardMarkup { + return tgbotapi.NewReplyKeyboard( + tgbotapi.NewKeyboardButtonRow( + tgbotapi.NewKeyboardButton("Все"), + tgbotapi.NewKeyboardButton("Принятые"), + ), + tgbotapi.NewKeyboardButtonRow( + tgbotapi.NewKeyboardButton("Отклонённые"), + tgbotapi.NewKeyboardButton("На согласовании"), + ), + tgbotapi.NewKeyboardButtonRow( + tgbotapi.NewKeyboardButton("← Назад"), + ), + ) +} + +// BuildCommentNotificationKeyboard — для уведомления инициатора о комментарии +func BuildCommentNotificationKeyboard(approvalID uint64) interface{} { + return tgkit.NewInlineKeyboard(). + Row(tgkit.Btn("↩️ Ответить на комментарий", fmt.Sprintf("comment_reply:%d", approvalID))). + Build() +} + +// BuildCommentReplyKeyboard — для согласующего/наблюдателя при получении ответа +func BuildCommentReplyKeyboard(approvalID uint64) interface{} { + return tgkit.NewInlineKeyboard(). + Row(tgkit.Btn("↩️ Ответить на комментарий", fmt.Sprintf("comment_reply:%d", approvalID))). + Row(tgkit.Btn("💬 Добавить комментарий", fmt.Sprintf("appr_comment:%d", approvalID))). + Build() +} diff --git a/service/telegram_service/keyboard/delegation.go b/service/telegram_service/keyboard/delegation.go new file mode 100644 index 0000000..75e6cd4 --- /dev/null +++ b/service/telegram_service/keyboard/delegation.go @@ -0,0 +1,172 @@ +// telegram_service/keyboard/delegation.go - ПОЛНОСТЬЮ ЗАМЕНИТЬ + +package keyboard + +import ( + "bitrix_balancer_api/core/lib/external/tgkit" + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/telegram_service/types" + "context" + "fmt" + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" +) + +const delegationPerPage = 6 + +func BuildDelegationMainMenu() interface{} { + return tgkit.NewInlineKeyboard(). + Row(tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "Делегировать права", "deleg_create")). + Row(tgkit.Btn("📋 Делегированные права", "deleg_list")). + Build() +} + +func BuildDelegationCategoryMenu(categories []*typescore.ApprovalTopicCategory, page int) interface{} { + total := len(categories) + totalPages := (total + delegationPerPage - 1) / delegationPerPage + if page < 0 { + page = 0 + } + if page >= totalPages && totalPages > 0 { + page = totalPages - 1 + } + start, end := page*delegationPerPage, page*delegationPerPage+delegationPerPage + if end > total { + end = total + } + + kb := tgkit.NewInlineKeyboard() + for _, c := range categories[start:end] { + if c.ID == nil || c.Name == nil { + continue + } + kb.Row(tgkit.Btn(*c.Name, fmt.Sprintf("deleg_category:%d", *c.ID))) + } + if totalPages > 1 { + kb.Rows = append(kb.Rows, buildPageRow(page, totalPages, "deleg_category_page", "deleg_page_noop")) + } + return kb.Build() +} + +func BuildDelegationTopicMenu(topics []*typescore.ApprovalTopic, categoryID uint64, page int) interface{} { + const perPage = 6 + total := len(topics) + totalPages := (total + perPage - 1) / perPage + if page < 0 { + page = 0 + } + if page >= totalPages && totalPages > 0 { + page = totalPages - 1 + } + start, end := page*perPage, page*perPage+perPage + if end > total { + end = total + } + + kb := tgkit.NewInlineKeyboard() + kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "Вся категория", fmt.Sprintf("deleg_all_category:%d", categoryID))) + + for _, t := range topics[start:end] { + if t.ID == nil || t.Name == nil { + continue + } + kb.Row(tgkit.Btn(*t.Name, fmt.Sprintf("deleg_topic:%d", *t.ID))) + } + if totalPages > 1 { + kb.Rows = append(kb.Rows, buildPageRow(page, totalPages, + fmt.Sprintf("deleg_topic_page:%d", categoryID), "deleg_page_noop")) + } + kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "К категориям", "deleg_back_categories")) + return kb.Build() +} + +func BuildDelegationUserMenu(users []*typescore.User, categoryID, topicID uint64, page int) interface{} { + const perPage = 8 + total := len(users) + totalPages := (total + perPage - 1) / perPage + if page < 0 { + page = 0 + } + if page >= totalPages && totalPages > 0 { + page = totalPages - 1 + } + start, end := page*perPage, page*perPage+perPage + if end > total { + end = total + } + + kb := tgkit.NewInlineKeyboard() + for _, u := range users[start:end] { + if u.ID == nil || u.FullName == nil { + continue + } + kb.Row(tgkit.Btn(*u.FullName, fmt.Sprintf("deleg_user:%d", *u.ID))) + } + if totalPages > 1 { + kb.Rows = append(kb.Rows, buildPageRow(page, totalPages, + fmt.Sprintf("deleg_user_page:%d:%d", categoryID, topicID), "deleg_page_noop")) + } + kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "Назад", fmt.Sprintf("deleg_category:%d", categoryID))) + return kb.Build() +} + +func BuildDelegatedRightsList(delegations []*typescore.ApprovalDelegation, page int, ctx context.Context, ipc *types.InternalProviderControl) interface{} { + const perPage = 6 + total := len(delegations) + totalPages := (total + perPage - 1) / perPage + if page < 0 { + page = 0 + } + if page >= totalPages && totalPages > 0 { + page = totalPages - 1 + } + start, end := page*perPage, page*perPage+perPage + if end > total { + end = total + } + + kb := tgkit.NewInlineKeyboard() + for _, d := range delegations[start:end] { + if d.ID == nil { + continue + } + scopeName := "—" + if d.TopicID != nil { + if t, _ := ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *d.TopicID); t != nil && t.Name != nil { + scopeName = *t.Name + } + } else if d.CategoryID != nil { + if c, _ := ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *d.CategoryID); c != nil && c.Name != nil { + scopeName = *c.Name + } + } + kb.Row(tgkit.Btn(scopeName, fmt.Sprintf("deleg_detail:%d", *d.ID))) + } + if totalPages > 1 { + kb.Rows = append(kb.Rows, buildPageRow(page, totalPages, "deleg_list_page", "deleg_page_noop")) + } + return kb.Build() +} + +func BuildDelegationActions(delegationID uint64) interface{} { + return tgkit.NewInlineKeyboard(). + Row(tgkit.Btn("📅 Изменить срок", fmt.Sprintf("deleg_extend:%d", delegationID))). + Row(tgkit.BtnStyled(tgkit.ButtonStyleDanger, "Отозвать делегирование", fmt.Sprintf("deleg_revoke:%d", delegationID))). + Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "К списку", "deleg_list")). + Build() +} + +func BuildDelegationExtendCancel(delegationID uint64) interface{} { + return tgkit.NewInlineKeyboard(). + Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "Отмена", fmt.Sprintf("deleg_detail:%d", delegationID))). + Build() +} + +func BuildDelegationBackToUsers(categoryID, topicID uint64) tgbotapi.InlineKeyboardMarkup { + callback := fmt.Sprintf("deleg_all_category:%d", categoryID) + if topicID > 0 { + callback = fmt.Sprintf("deleg_topic:%d", topicID) + } + return tgkit.NewInlineKeyboard(). + Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "Назад", callback)). + Build() +} diff --git a/service/telegram_service/keyboard/menu.go b/service/telegram_service/keyboard/menu.go new file mode 100644 index 0000000..df8dffd --- /dev/null +++ b/service/telegram_service/keyboard/menu.go @@ -0,0 +1,71 @@ +package keyboard + +import ( + "bitrix_balancer_api/core/lib/external/tgkit" + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" +) + +// UserRole — набор ролей пользователя для построения меню +type UserRole struct { + IsApprover bool + IsObserver bool + IsExecutor bool + IsDirector bool +} + +// BuildMainMenu — главное меню с разделами по ролям +func BuildMainMenu(roles UserRole) tgbotapi.ReplyKeyboardMarkup { + kb := tgkit.NewReplyKeyboard() + + // Раздел: Инициатор (всегда видим) + kb.Row("👤 Инициатор") + + // Раздел: Согласующий + if roles.IsApprover || roles.IsDirector { + kb.Row("✅ Согласующий") + } + + // Раздел: Наблюдатель + if roles.IsObserver { + kb.Row("👁 Наблюдатель") + } + + // Раздел: Исполнитель + if roles.IsExecutor { + kb.Row("Задачи к исполнению") + } + + // Общие кнопки — всегда внизу + kb.Row("❓ Как создать согласование?") + kb.Row("💬 Предложения и пожелания") + + return kb.Build() +} + +// BuildInitiatorSubmenu — подменю для инициатора +func BuildInitiatorSubmenu() tgbotapi.ReplyKeyboardMarkup { + return tgkit.NewReplyKeyboard(). + Row("➕ Создать согласование"). + Row("Ранее созданные согласования"). + Row("← Назад"). + Build() +} + +// BuildApproverSubmenu — подменю для согласующего +func BuildApproverSubmenu() tgbotapi.ReplyKeyboardMarkup { + return tgkit.NewReplyKeyboard(). + Row("Принять согласование в работу"). + Row("Список согласований", "Отложенные согласования"). + Row("📊 Сформировать отчёт", "Делегировать права"). + Row("← Назад"). + Build() +} + +// BuildObserverSubmenu — подменю для наблюдателя +func BuildObserverSubmenu() tgbotapi.ReplyKeyboardMarkup { + return tgkit.NewReplyKeyboard(). + Row("Наблюдать за согласованием"). + Row("📊 Сформировать отчёт"). + Row("← Назад"). + Build() +} diff --git a/service/telegram_service/keyboard/misc.go b/service/telegram_service/keyboard/misc.go new file mode 100644 index 0000000..1508b00 --- /dev/null +++ b/service/telegram_service/keyboard/misc.go @@ -0,0 +1,242 @@ +package keyboard + +import ( + "bitrix_balancer_api/core/lib/external/tgkit" + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/telegram_service/approvalflow" + "fmt" + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" +) + +// ── Выбор согласующего ────────────────────────────────────────── + +func BuildApproverSelectionMenu(approvers []*typescore.User, page int) interface{} { + const perPage = 8 + total := len(approvers) + totalPages := (total + perPage - 1) / perPage + if page < 0 { + page = 0 + } + if page >= totalPages && totalPages > 0 { + page = totalPages - 1 + } + start, end := page*perPage, page*perPage+perPage + if end > total { + end = total + } + + kb := tgkit.NewInlineKeyboard() + for _, a := range approvers[start:end] { + if a.ID == nil || a.FullName == nil { + continue + } + kb.Row(tgkit.Btn(*a.FullName, fmt.Sprintf("select_approver:%d", *a.ID))) + } + if totalPages > 1 { + kb.Rows = append(kb.Rows, buildPageRow(page, totalPages, "select_approver_page", "select_approver_noop")) + } + return kb.Build() +} + +func BuildFirstApproverSelectionMenu(users []*typescore.User, page int) tgbotapi.InlineKeyboardMarkup { + const perPage = 8 + total := len(users) + totalPages := (total + perPage - 1) / perPage + if page < 0 { + page = 0 + } + if page >= totalPages && totalPages > 0 { + page = totalPages - 1 + } + start := page * perPage + end := start + perPage + if end > total { + end = total + } + + kb := tgkit.NewInlineKeyboard() + for _, u := range users[start:end] { + if u.ID == nil || u.FullName == nil { + continue + } + kb.Row(tgkit.Btn(*u.FullName, fmt.Sprintf("first_approver_select:%d", *u.ID))) + } + if totalPages > 1 { + kb.Rows = append(kb.Rows, buildPageRow(page, totalPages, "first_approver_page", "first_approver_noop")) + } + return kb.Build() +} + +func BuildObserverSelectionMenu(observers []*typescore.User, selectedIDs []uint64, page int, isRequired bool) tgbotapi.InlineKeyboardMarkup { + const perPage = 8 + + if len(observers) == 0 { + kb := tgkit.NewInlineKeyboard() + if isRequired { + kb.Row(tgkit.Btn("⚠️ Нет доступных наблюдателей", "obs_select_noop")) + } else { + kb.Row(tgkit.Btn("✅ Подтвердить без наблюдателей", "obs_select_confirm")) + } + return kb.Build() + } + + total := len(observers) + totalPages := (total + perPage - 1) / perPage + if page < 0 { + page = 0 + } + if page >= totalPages { + page = totalPages - 1 + } + start := page * perPage + end := start + perPage + if end > total { + end = total + } + + selected := make(map[uint64]bool, len(selectedIDs)) + for _, id := range selectedIDs { + selected[id] = true + } + + kb := tgkit.NewInlineKeyboard() + for _, u := range observers[start:end] { + if u.ID == nil || u.FullName == nil { + continue + } + label := *u.FullName + if selected[*u.ID] { + label = "✅ " + label + } + kb.Row(tgkit.Btn(label, fmt.Sprintf("obs_select_toggle:%d", *u.ID))) + } + if totalPages > 1 { + kb.Rows = append(kb.Rows, buildPageRow(page, totalPages, "obs_select_page", "obs_select_noop")) + } + + if isRequired { + if len(selectedIDs) == 0 { + kb.Row(tgkit.Btn("⚠️ Выберите хотя бы одного наблюдателя", "obs_select_confirm")) + } else { + kb.Row(tgkit.Btn( + fmt.Sprintf("✅ Подтвердить (%d выбрано)", len(selectedIDs)), + "obs_select_confirm", + )) + } + } else { + confirmLabel := "✅ Подтвердить" + if len(selectedIDs) > 0 { + confirmLabel = fmt.Sprintf("✅ Подтвердить (%d выбрано)", len(selectedIDs)) + } else { + confirmLabel = "✅ Подтвердить без наблюдателей" + } + kb.Row(tgkit.Btn(confirmLabel, "obs_select_confirm")) + } + + return kb.Build() +} + +func BuildObserverTopicMenu(topics []approvalflow.Topic, page int) tgbotapi.InlineKeyboardMarkup { + const perPage = 6 + total := len(topics) + totalPages := (total + perPage - 1) / perPage + if page < 0 { + page = 0 + } + if page >= totalPages && totalPages > 0 { + page = totalPages - 1 + } + start := page * perPage + end := start + perPage + if end > total { + end = total + } + + var rows [][]tgbotapi.InlineKeyboardButton + for _, t := range topics[start:end] { + rows = append(rows, tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData(t.Name(), fmt.Sprintf("obs_topic:%s", t.Code())), + )) + } + + if totalPages > 1 { + rows = append(rows, tgkit.PaginationRow( + page, totalPages, + fmt.Sprintf("obs_topic_page:%d", page-1), + fmt.Sprintf("obs_topic_page:%d", page+1), + "obs_topic_noop", + )) + } + + return tgbotapi.NewInlineKeyboardMarkup(rows...) +} + +func BuildObserverApprovalList(approvals []*typescore.Approval, initiators map[uint64]*typescore.User, departments map[uint64]*typescore.Department) interface{} { + kb := tgkit.NewInlineKeyboard() + for _, a := range approvals { + if a.ID == nil { + continue + } + label := fmt.Sprintf("#%d", *a.ID) + if a.InitiatorID != nil { + if u, ok := initiators[*a.InitiatorID]; ok && u.FullName != nil { + label += " " + *u.FullName + } + } + if a.DepartmentID != nil { + if d, ok := departments[*a.DepartmentID]; ok && d.Name != nil { + label += " — " + *d.Name + } + } + kb.Row(tgkit.Btn(label, fmt.Sprintf("obs_approval:%d", *a.ID))) + } + kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "К темам", "obs_back_topics")) + return kb.Build() +} + +func BuildReportDateToMenu() interface{} { + return tgkit.NewInlineKeyboard(). + Row(tgkit.Btn("📤 Выгрузить (по сегодня)", "report_generate")). + Build() +} + +// ── Доработка ─────────────────────────────────────────────────── + +func BuildRevisionOptions(approvalID uint64) interface{} { + return tgkit.NewInlineKeyboard(). + Row(tgkit.Btn("✏️ Изменить текст", fmt.Sprintf("revision_edit_text:%d", approvalID))). + Row(tgkit.Btn("📎 Добавить файлы", fmt.Sprintf("revision_add_files:%d", approvalID))). + Row(tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "Отправить на повторное согласование", fmt.Sprintf("revision_resubmit:%d", approvalID))). + Row(tgkit.BtnStyled(tgkit.ButtonStyleDanger, "Отозвать заявку", fmt.Sprintf("appr_revoke:%d", approvalID))). + Build() +} + +func BuildRevisionRejectOptions(approvalID uint64) interface{} { + return tgkit.NewInlineKeyboard(). + Row(tgkit.Btn("💬 Указать причину", fmt.Sprintf("appr_revision_comment:%d", approvalID))). + Row(tgkit.Btn("↩️ Вернуть без комментария", fmt.Sprintf("appr_revision_skip:%d", approvalID))). + Build() +} + +func BuildRevisionAttachCancel(approvalID uint64) interface{} { + return tgkit.NewInlineKeyboard(). + Row(tgkit.BtnStyled(tgkit.ButtonStyleDanger, "Отмена", fmt.Sprintf("revision_attach_cancel:%d", approvalID))). + Build() +} + +func BuildRevokeTaskConfirmation(taskID uint64, approvalID uint64) tgbotapi.InlineKeyboardMarkup { + return tgbotapi.NewInlineKeyboardMarkup( + tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData( + "✅ Нет, изменений не вносил", + fmt.Sprintf("revoke_task_no_changes:%d:%d", taskID, approvalID), + ), + ), + tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData( + "⚠️ Да, изменения были", + fmt.Sprintf("revoke_task_has_changes:%d:%d", taskID, approvalID), + ), + ), + ) +} diff --git a/service/telegram_service/keyboard/observer.go b/service/telegram_service/keyboard/observer.go new file mode 100644 index 0000000..7bb207b --- /dev/null +++ b/service/telegram_service/keyboard/observer.go @@ -0,0 +1,22 @@ +package keyboard + +import ( + "fmt" + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" +) + +// BuildObserverApprovalDetail — карточка заявки с кнопками наблюдателя. +func BuildObserverApprovalDetail(approvalID uint64, topicCode string) tgbotapi.InlineKeyboardMarkup { + return tgbotapi.NewInlineKeyboardMarkup( + tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData("🔔 Напомнить согласующему", fmt.Sprintf("obs_remind:%d", approvalID)), + tgbotapi.NewInlineKeyboardButtonData("💬 Добавить комментарий", fmt.Sprintf("appr_comment:%d", approvalID)), + ), + tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData( + "🔙 Назад к списку", + fmt.Sprintf("obs_back:%s", topicCode), + ), + ), + ) +} diff --git a/service/telegram_service/scheduler/delegation_checker.go b/service/telegram_service/scheduler/delegation_checker.go new file mode 100644 index 0000000..f48220c --- /dev/null +++ b/service/telegram_service/scheduler/delegation_checker.go @@ -0,0 +1,139 @@ +package scheduler + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/telegram_service/types" + "context" + "fmt" + "time" + + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" + "github.com/sirupsen/logrus" +) + +type DelegationChecker struct { + ipc *types.InternalProviderControl +} + +func NewDelegationChecker(ipc *types.InternalProviderControl) *DelegationChecker { + return &DelegationChecker{ipc: ipc} +} + +func (dc *DelegationChecker) Start() { + ticker := time.NewTicker(30 * time.Minute) + go func() { + for range ticker.C { + dc.checkDelegations() + } + }() + // Первая проверка сразу + go dc.checkDelegations() +} + +func (dc *DelegationChecker) checkDelegations() { + ctx := context.Background() + bot := dc.ipc.TGBotClient.Bot() + + isActive := true + delegations, _, err := dc.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalDelegation{ + IsActive: &isActive, + }, + }) + if err != nil { + logrus.Errorf("DelegationChecker: GetApprovalDelegationsListDB err=%v", err) + return + } + + now := time.Now() + + for _, deleg := range delegations { + if deleg.ValidUntil == nil { + continue + } + + timeLeft := deleg.ValidUntil.Sub(now) + + // Истекло - деактивируем + if timeLeft <= 0 { + inactive := false + deleg.IsActive = &inactive + dc.ipc.Database.ApprovalDelegation.UpdateApprovalDelegationDB(ctx, nil, deleg) //nolint:errcheck + dc.notifyExpired(bot, ctx, deleg) + continue + } + + // За 24 часа + if timeLeft <= 24*time.Hour && (deleg.NotifiedDay == nil || !*deleg.NotifiedDay) { + dc.notifyExpiringDay(bot, ctx, deleg) + notified := true + deleg.NotifiedDay = ¬ified + dc.ipc.Database.ApprovalDelegation.UpdateApprovalDelegationDB(ctx, nil, deleg) //nolint:errcheck + continue + } + + // За 2 часа + if timeLeft <= 2*time.Hour && (deleg.Notified2h == nil || !*deleg.Notified2h) { + dc.notifyExpiring2h(bot, ctx, deleg) + notified := true + deleg.Notified2h = ¬ified + dc.ipc.Database.ApprovalDelegation.UpdateApprovalDelegationDB(ctx, nil, deleg) //nolint:errcheck + } + } +} + +func (dc *DelegationChecker) notifyExpiringDay(bot *tgbotapi.BotAPI, ctx context.Context, deleg *typescore.ApprovalDelegation) { + dc.sendExpiringNotification(bot, ctx, deleg, "⏰ Делегирование истекает через 24 часа") +} + +func (dc *DelegationChecker) notifyExpiring2h(bot *tgbotapi.BotAPI, ctx context.Context, deleg *typescore.ApprovalDelegation) { + dc.sendExpiringNotification(bot, ctx, deleg, "⏰ Делегирование истекает через 2 часа") +} + +func (dc *DelegationChecker) notifyExpired(bot *tgbotapi.BotAPI, ctx context.Context, deleg *typescore.ApprovalDelegation) { + dc.sendExpiringNotification(bot, ctx, deleg, "⏱ Срок делегирования истёк") +} + +func (dc *DelegationChecker) sendExpiringNotification(bot *tgbotapi.BotAPI, ctx context.Context, deleg *typescore.ApprovalDelegation, title string) { + if deleg.DelegatorID == nil || deleg.DelegateID == nil || deleg.TopicID == nil || deleg.ValidUntil == nil { + return + } + + topic, _ := dc.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *deleg.TopicID) + topicName := "—" + if topic != nil && topic.Name != nil { + topicName = *topic.Name + } + + text := fmt.Sprintf( + "%s\n\n"+ + "📋 Тема: %s\n"+ + "📅 Окончание: %s", + title, topicName, deleg.ValidUntil.Format("02.01.2006 15:04"), + ) + + // Уведомляем делегатора + delegator, _ := dc.ipc.Database.User.GetUserByIDDB(ctx, *deleg.DelegatorID) + if delegator != nil && delegator.TelegramID != nil { + delegate, _ := dc.ipc.Database.User.GetUserByIDDB(ctx, *deleg.DelegateID) + delegateName := "—" + if delegate != nil && delegate.FullName != nil { + delegateName = *delegate.FullName + } + msg := tgbotapi.NewMessage(*delegator.TelegramID, text+fmt.Sprintf("\n👤 Делегат: %s", delegateName)) + msg.ParseMode = "HTML" + bot.Send(msg) //nolint:errcheck + } + + // Уведомляем делегата + delegate, _ := dc.ipc.Database.User.GetUserByIDDB(ctx, *deleg.DelegateID) + if delegate != nil && delegate.TelegramID != nil { + delegatorName := "—" + if delegator != nil && delegator.FullName != nil { + delegatorName = *delegator.FullName + } + msg := tgbotapi.NewMessage(*delegate.TelegramID, text+fmt.Sprintf("\n👤 От: %s", delegatorName)) + msg.ParseMode = "HTML" + bot.Send(msg) //nolint:errcheck + } +} diff --git a/service/telegram_service/start.sh b/service/telegram_service/start.sh new file mode 100755 index 0000000..1220e87 --- /dev/null +++ b/service/telegram_service/start.sh @@ -0,0 +1,49 @@ +#!/bin/bash + +set -e +trap 'echo "🔴 Скрипт остановлен"; exit' SIGINT + +# Имя сети Docker +DOCKER_NETWORK_NAME="networklocal1" +# Наименование сервиса +SERVICE_NAME="ruspet_telegram_service" + +# Наименование образа +IMAGE_NAME="${SERVICE_NAME}_i" +# Наименование контейнера +CONTAINER_NAME="${SERVICE_NAME}_c" +# Имя приложения +APP_NAME="${SERVICE_NAME}_app" + + +# Останавливаем и удаляем старый контейнер, если он существует +if [ "$(docker ps -q -f name=$CONTAINER_NAME)" ]; then + docker stop $CONTAINER_NAME + docker rm $CONTAINER_NAME +fi + +# Удаляем старый образ, если он существует +if [ "$(docker images -q $IMAGE_NAME)" ]; then + docker rmi $IMAGE_NAME +fi + +# Создаем директорию vendor с зависимостями +go mod tidy +rm -rf vendor +go mod vendor + +# Проверяем существование сети и создаем, если не существует +docker network ls | grep $DOCKER_NETWORK_NAME || docker network create $DOCKER_NETWORK_NAME + +# Собираем образ +docker build --build-arg APP_NAME=$APP_NAME -t $IMAGE_NAME . + +# Запускаем контейнер с новым образом в сетевом режиме host и подключаем к сети по имени +docker run -d \ + --add-host=rmq_host:192.168.1.102 \ + --network $DOCKER_NETWORK_NAME \ + --restart always \ + --name $CONTAINER_NAME \ + -e APP_NAME=$APP_NAME \ + --add-host=database_host:192.168.0.15 \ + $IMAGE_NAME \ No newline at end of file diff --git a/service/telegram_service/state/add_approver.go b/service/telegram_service/state/add_approver.go new file mode 100644 index 0000000..8ebd339 --- /dev/null +++ b/service/telegram_service/state/add_approver.go @@ -0,0 +1,42 @@ +package state + +import ( + "context" + "encoding/json" + "fmt" + "time" +) + +type AddApproverFlowState struct { + CategoryID uint64 `json:"category_id"` + ApprovalID uint64 `json:"approval_id"` + Stage string `json:"stage"` // "select_category", "select_approval", "select_user" +} + +func addApproverKey(telegramID int64) string { + return fmt.Sprintf("add_approver_flow:%d", telegramID) +} + +func (s *StateManager) SetAddApprover(ctx context.Context, telegramID int64, state *AddApproverFlowState) error { + data, err := json.Marshal(state) + if err != nil { + return err + } + return s.redis.Set(ctx, addApproverKey(telegramID), string(data), 30*time.Minute) +} + +func (s *StateManager) GetAddApprover(ctx context.Context, telegramID int64) (*AddApproverFlowState, error) { + data, err := s.redis.Get(ctx, addApproverKey(telegramID)) + if err != nil { + return nil, nil + } + var state AddApproverFlowState + if err := json.Unmarshal([]byte(data), &state); err != nil { + return nil, err + } + return &state, nil +} + +func (s *StateManager) ClearAddApprover(ctx context.Context, telegramID int64) error { + return s.redis.Del(ctx, addApproverKey(telegramID)) +} diff --git a/service/telegram_service/state/attachment.go b/service/telegram_service/state/attachment.go new file mode 100644 index 0000000..7c30522 --- /dev/null +++ b/service/telegram_service/state/attachment.go @@ -0,0 +1,46 @@ +package state + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "github.com/redis/go-redis/v9" + "time" +) + +type AttachmentSession struct { + ApprovalID uint64 `json:"approval_id"` + TaskID uint64 `json:"task_id,omitempty"` + Files []FileAttachment `json:"files"` // накапливаем + Stage string `json:"stage"` // "collecting" +} + +func (s *StateManager) SetAttachmentSession(ctx context.Context, telegramID int64, session *AttachmentSession) error { + key := fmt.Sprintf("attach_session:%d", telegramID) + data, err := json.Marshal(session) + if err != nil { + return err + } + return s.redis.Set(ctx, key, data, 30*time.Minute) +} + +func (s *StateManager) GetAttachmentSession(ctx context.Context, telegramID int64) (*AttachmentSession, error) { + key := fmt.Sprintf("attach_session:%d", telegramID) + data, err := s.redis.Get(ctx, key) + if errors.Is(err, redis.Nil) { + return nil, nil + } + if err != nil { + return nil, err + } + var session AttachmentSession + if err := json.Unmarshal([]byte(data), &session); err != nil { + return nil, err + } + return &session, nil +} + +func (s *StateManager) ClearAttachmentSession(ctx context.Context, telegramID int64) error { + return s.redis.Del(ctx, fmt.Sprintf("attach_session:%d", telegramID)) +} diff --git a/service/telegram_service/state/comment.go b/service/telegram_service/state/comment.go new file mode 100644 index 0000000..393f06d --- /dev/null +++ b/service/telegram_service/state/comment.go @@ -0,0 +1,76 @@ +package state + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "time" + + "github.com/redis/go-redis/v9" +) + +type CommentFlowState struct { + ApprovalID uint64 `json:"approval_id"` + Stage string `json:"stage"` // "await_text" +} + +type CommentReplyState struct { + ApprovalID uint64 `json:"approval_id"` + Stage string `json:"stage"` // "await_text" +} + +func (s *StateManager) SetCommentFlow(ctx context.Context, telegramID int64, state *CommentFlowState) error { + key := fmt.Sprintf("comment_flow:%d", telegramID) + data, err := json.Marshal(state) + if err != nil { + return err + } + return s.redis.Set(ctx, key, data, 30*time.Minute) +} + +func (s *StateManager) GetCommentFlow(ctx context.Context, telegramID int64) (*CommentFlowState, error) { + key := fmt.Sprintf("comment_flow:%d", telegramID) + data, err := s.redis.Get(ctx, key) + if errors.Is(err, redis.Nil) { + return nil, nil + } + if err != nil { + return nil, err + } + + var state CommentFlowState + if err := json.Unmarshal([]byte(data), &state); err != nil { + return nil, err + } + return &state, nil +} + +func (s *StateManager) ClearCommentFlow(ctx context.Context, telegramID int64) error { + key := fmt.Sprintf("comment_flow:%d", telegramID) + return s.redis.Del(ctx, key) +} + +func (s *StateManager) SetCommentReply(ctx context.Context, telegramID int64, state *CommentReplyState) error { + key := fmt.Sprintf("comment_reply:%d", telegramID) + data, _ := json.Marshal(state) + return s.redis.Set(ctx, key, data, 30*time.Minute) +} + +func (s *StateManager) GetCommentReply(ctx context.Context, telegramID int64) (*CommentReplyState, error) { + key := fmt.Sprintf("comment_reply:%d", telegramID) + data, err := s.redis.Get(ctx, key) + if errors.Is(err, redis.Nil) { + return nil, nil + } + if err != nil { + return nil, err + } + var state CommentReplyState + json.Unmarshal([]byte(data), &state) + return &state, nil +} + +func (s *StateManager) ClearCommentReply(ctx context.Context, telegramID int64) error { + return s.redis.Del(ctx, fmt.Sprintf("comment_reply:%d", telegramID)) +} diff --git a/service/telegram_service/state/delegation.go b/service/telegram_service/state/delegation.go new file mode 100644 index 0000000..db2c54d --- /dev/null +++ b/service/telegram_service/state/delegation.go @@ -0,0 +1,45 @@ +// telegram_service/state/handler_delegation.go - новый файл + +package state + +import ( + "context" + "encoding/json" + "fmt" + "time" +) + +type DelegationFlowState struct { + CategoryID uint64 `json:"category_id"` + TopicID uint64 `json:"topic_id,omitempty"` + DelegateID uint64 `json:"delegate_id"` + Stage string `json:"stage"` // "select_category", "select_topic", "select_user", "input_date" +} + +func delegationKey(telegramID int64) string { + return fmt.Sprintf("delegation_flow:%d", telegramID) +} + +func (s *StateManager) SetDelegation(ctx context.Context, telegramID int64, state *DelegationFlowState) error { + data, err := json.Marshal(state) + if err != nil { + return err + } + return s.redis.Set(ctx, delegationKey(telegramID), string(data), 30*time.Minute) +} + +func (s *StateManager) GetDelegation(ctx context.Context, telegramID int64) (*DelegationFlowState, error) { + data, err := s.redis.Get(ctx, delegationKey(telegramID)) + if err != nil { + return nil, nil + } + var state DelegationFlowState + if err := json.Unmarshal([]byte(data), &state); err != nil { + return nil, err + } + return &state, nil +} + +func (s *StateManager) ClearDelegation(ctx context.Context, telegramID int64) error { + return s.redis.Del(ctx, delegationKey(telegramID)) +} diff --git a/service/telegram_service/state/pending_state.go b/service/telegram_service/state/pending_state.go new file mode 100644 index 0000000..df07f46 --- /dev/null +++ b/service/telegram_service/state/pending_state.go @@ -0,0 +1,67 @@ +package state + +import ( + "context" + "encoding/json" + "fmt" + "time" +) + +// PendingCommentItem — одна отложенная заявка, ожидающая комментария. +type PendingCommentItem struct { + ApprovalID uint64 `json:"approval_id"` + Action string `json:"action"` // "reject" | "revoke" +} + +func pendingCommentsKey(telegramID int64) string { + return fmt.Sprintf("appr_pending_comments:%d", telegramID) +} + +func (s *StateManager) GetPendingComments(ctx context.Context, telegramID int64) ([]PendingCommentItem, error) { + data, err := s.redis.Get(ctx, pendingCommentsKey(telegramID)) + if err != nil { + return nil, nil + } + var items []PendingCommentItem + if err := json.Unmarshal([]byte(data), &items); err != nil { + return nil, err + } + return items, nil +} + +func (s *StateManager) AddPendingComment(ctx context.Context, telegramID int64, item PendingCommentItem) error { + items, _ := s.GetPendingComments(ctx, telegramID) + for _, existing := range items { + if existing.ApprovalID == item.ApprovalID { + return nil // уже есть — не дублируем + } + } + items = append(items, item) + data, err := json.Marshal(items) + if err != nil { + return err + } + return s.redis.Set(ctx, pendingCommentsKey(telegramID), string(data), 24*time.Hour) +} + +func (s *StateManager) RemovePendingComment(ctx context.Context, telegramID int64, approvalID uint64) error { + items, _ := s.GetPendingComments(ctx, telegramID) + var filtered []PendingCommentItem + for _, item := range items { + if item.ApprovalID != approvalID { + filtered = append(filtered, item) + } + } + if len(filtered) == 0 { + return s.redis.Del(ctx, pendingCommentsKey(telegramID)) + } + data, err := json.Marshal(filtered) + if err != nil { + return err + } + return s.redis.Set(ctx, pendingCommentsKey(telegramID), string(data), 24*time.Hour) +} + +func (s *StateManager) ClearPendingComments(ctx context.Context, telegramID int64) error { + return s.redis.Del(ctx, pendingCommentsKey(telegramID)) +} diff --git a/service/telegram_service/state/report_state.go b/service/telegram_service/state/report_state.go new file mode 100644 index 0000000..2a4ce3a --- /dev/null +++ b/service/telegram_service/state/report_state.go @@ -0,0 +1,44 @@ +package state + +import ( + "context" + "encoding/json" + "fmt" +) + +// ReportFilterState — состояние фильтра отчёта для пользователя +type ReportFilterState struct { + ReportType string // "approvals" или "tasks" + DateFrom string // дата начала в формате "ДД.ММ.ГГГГ" + DateTo string // дата окончания в формате "ДД.ММ.ГГГГ" + AwaitDateFrom bool // ожидаем ввод даты начала + AwaitDateTo bool // ожидаем ввод даты окончания +} + +func reportKey(telegramID int64) string { + return fmt.Sprintf("report_filter:%d", telegramID) +} + +func (s *StateManager) SetReport(ctx context.Context, telegramID int64, state *ReportFilterState) error { + data, err := json.Marshal(state) + if err != nil { + return err + } + return s.redis.Set(ctx, reportKey(telegramID), string(data), stateTTL) +} + +func (s *StateManager) GetReport(ctx context.Context, telegramID int64) (*ReportFilterState, error) { + data, err := s.redis.Get(ctx, reportKey(telegramID)) + if err != nil { + return nil, nil + } + var state ReportFilterState + if err := json.Unmarshal([]byte(data), &state); err != nil { + return nil, err + } + return &state, nil +} + +func (s *StateManager) ClearReport(ctx context.Context, telegramID int64) error { + return s.redis.Del(ctx, reportKey(telegramID)) +} diff --git a/service/telegram_service/state/revision.go b/service/telegram_service/state/revision.go new file mode 100644 index 0000000..7f6f80a --- /dev/null +++ b/service/telegram_service/state/revision.go @@ -0,0 +1,47 @@ +package state + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "time" + + "github.com/redis/go-redis/v9" +) + +type RevisionFlowState struct { + ApprovalID uint64 `json:"approval_id"` + Stage string `json:"stage"` // "await_action" | "await_content" | "await_files" +} + +func (s *StateManager) SetRevisionFlow(ctx context.Context, telegramID int64, state *RevisionFlowState) error { + key := fmt.Sprintf("revision_flow:%d", telegramID) + data, err := json.Marshal(state) + if err != nil { + return err + } + return s.redis.Set(ctx, key, data, 30*time.Minute) +} + +func (s *StateManager) GetRevisionFlow(ctx context.Context, telegramID int64) (*RevisionFlowState, error) { + key := fmt.Sprintf("revision_flow:%d", telegramID) + data, err := s.redis.Get(ctx, key) + if errors.Is(err, redis.Nil) { + return nil, nil + } + if err != nil { + return nil, err + } + + var state RevisionFlowState + if err := json.Unmarshal([]byte(data), &state); err != nil { + return nil, err + } + return &state, nil +} + +func (s *StateManager) ClearRevisionFlow(ctx context.Context, telegramID int64) error { + key := fmt.Sprintf("revision_flow:%d", telegramID) + return s.redis.Del(ctx, key) +} diff --git a/service/telegram_service/state/state.go b/service/telegram_service/state/state.go new file mode 100644 index 0000000..dc336bd --- /dev/null +++ b/service/telegram_service/state/state.go @@ -0,0 +1,85 @@ +package state + +import ( + "context" + "encoding/json" + "fmt" + "time" + + redismodule "bitrix_balancer_api/core/lib/internally/redis" +) + +const stateTTL = 30 * time.Minute + +type FileAttachment struct { + Base64 string + FileName string + MessageID int +} + +// ApprovalFlowState — состояние пользователя внутри флоу согласования. +// Хранится в Redis, сбрасывается по TTL или после отправки заявки. +type ApprovalFlowState struct { + TopicCode string `json:"topic_code"` + NodeKey string `json:"node_key"` + Collected map[string]string `json:"collected"` + AwaitInput bool `json:"await_input"` + InputKey string `json:"input_key"` + History []string `json:"history"` + AwaitFileInput bool `json:"await_file_input"` + Files []FileAttachment `json:"files"` + FileStatusMsgID int `json:"file_status_msg_id"` + FilesStepCompleted bool `json:"files_step_completed"` + MultiSelected map[string][]string `json:"multi_selected,omitempty"` + AwaitMultiSelectConfirm bool `json:"await_multi_select_confirm,omitempty"` + MultiSelectNodeKey string `json:"multi_select_node_key,omitempty"` + + // Выбор первого согласующего по роли + AwaitFirstApproverSelection bool `json:"await_first_approver_selection"` + SelectedFirstApproverID uint64 `json:"selected_first_approver_id,omitempty"` + + // Выбор основного согласующего + AwaitApproverSelection bool `json:"await_approver_selection"` + SelectedApproverID uint64 `json:"selected_approver_id,omitempty"` + + // Выбор наблюдателей (мультиселект) + AwaitObserverSelection bool `json:"await_observer_selection"` + ObserverSelectionDone bool `json:"observer_selection_done"` + SelectedObserverIDs []uint64 `json:"selected_observer_ids,omitempty"` +} + +type StateManager struct { + redis *redismodule.ModuleRedis +} + +func NewStateManager(redis *redismodule.ModuleRedis) *StateManager { + return &StateManager{redis: redis} +} + +func key(telegramID int64) string { + return fmt.Sprintf("approval_flow:%d", telegramID) +} + +func (s *StateManager) Set(ctx context.Context, telegramID int64, state *ApprovalFlowState) error { + data, err := json.Marshal(state) + if err != nil { + return err + } + return s.redis.Set(ctx, key(telegramID), string(data), stateTTL) +} + +func (s *StateManager) Get(ctx context.Context, telegramID int64) (*ApprovalFlowState, error) { + data, err := s.redis.Get(ctx, key(telegramID)) + if err != nil { + return nil, nil // нет активного состояния — это норма + } + var state ApprovalFlowState + if err := json.Unmarshal([]byte(data), &state); err != nil { + return nil, err + } + return &state, nil +} + +func (s *StateManager) Clear(ctx context.Context, telegramID int64) error { + return s.redis.Del(ctx, key(telegramID)) +} diff --git a/service/telegram_service/state/suggesttion.go b/service/telegram_service/state/suggesttion.go new file mode 100644 index 0000000..0683eb6 --- /dev/null +++ b/service/telegram_service/state/suggesttion.go @@ -0,0 +1,47 @@ +package state + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "time" + + "github.com/redis/go-redis/v9" +) + +type SuggestionFlowState struct { + SuggestionID uint64 `json:"suggestion_id,omitempty"` + Stage string `json:"stage"` // "await_subject", "await_message", "await_file" +} + +func (s *StateManager) SetSuggestionFlow(ctx context.Context, telegramID int64, state *SuggestionFlowState) error { + key := fmt.Sprintf("suggestion_flow:%d", telegramID) + data, err := json.Marshal(state) + if err != nil { + return err + } + return s.redis.Set(ctx, key, data, 30*time.Minute) +} + +func (s *StateManager) GetSuggestionFlow(ctx context.Context, telegramID int64) (*SuggestionFlowState, error) { + key := fmt.Sprintf("suggestion_flow:%d", telegramID) + data, err := s.redis.Get(ctx, key) + if errors.Is(err, redis.Nil) { + return nil, nil + } + if err != nil { + return nil, err + } + + var state SuggestionFlowState + if err := json.Unmarshal([]byte(data), &state); err != nil { + return nil, err + } + return &state, nil +} + +func (s *StateManager) ClearSuggestionFlow(ctx context.Context, telegramID int64) error { + key := fmt.Sprintf("suggestion_flow:%d", telegramID) + return s.redis.Del(ctx, key) +} diff --git a/service/telegram_service/types/types.go b/service/telegram_service/types/types.go new file mode 100644 index 0000000..d42782a --- /dev/null +++ b/service/telegram_service/types/types.go @@ -0,0 +1,16 @@ +package types + +import ( + configcore "bitrix_balancer_api/core/config" + database "bitrix_balancer_api/core/db" + "bitrix_balancer_api/core/lib/external/tgkit" + + redismodule "bitrix_balancer_api/core/lib/internally/redis" +) + +type InternalProviderControl struct { + Config *configcore.Config + RedisClient *redismodule.ModuleRedis + TGBotClient *tgkit.Client + Database *database.ModuleDB +} diff --git a/service/telegram_service/version b/service/telegram_service/version new file mode 100644 index 0000000..aa6e22c --- /dev/null +++ b/service/telegram_service/version @@ -0,0 +1 @@ +v-0.0.2 \ No newline at end of file diff --git a/update-go-and-deps.sh b/update-go-and-deps.sh new file mode 100644 index 0000000..b1c66eb --- /dev/null +++ b/update-go-and-deps.sh @@ -0,0 +1,87 @@ +#!/bin/bash + +ROOT=$(pwd) + +# Определяем версии Go +LOCAL_GO_FULL=$(go version 2>/dev/null | awk '{print $3}' || echo "unknown") +[[ "$LOCAL_GO_FULL" == "unknown" ]] && { echo "❌ Go is not installed"; exit 1; } +LOCAL_GO=${LOCAL_GO_FULL#go} + +LATEST_GO_FULL=$(curl -fsSL 'https://go.dev/VERSION?m=text' | grep '^go[0-9]' | head -n1) +[[ -z "$LATEST_GO_FULL" ]] && { echo "❌ Failed to fetch latest Go version"; exit 1; } +LATEST_GO=${LATEST_GO_FULL#go} + +echo "🛠️ Local Go: go $LOCAL_GO" +echo "🆕 Latest Go: $LATEST_GO_FULL" + +update_module() { + local mod_path="$1" + local module_name="$2" + local dir=$(dirname "$mod_path") + + cd "$dir" || return 1 + + current_go=$(grep '^go ' "$mod_path" 2>/dev/null | awk '{print $2}' || echo "unknown") + echo " 📁 $module_name | go.mod: $current_go → $LATEST_GO" + + go mod edit -go="$LATEST_GO" || return 1 + + echo " 📥 go get -u" + go get -u ./... 2>&1 | grep -v "unmatched selector" || true + + echo " 🧹 go mod tidy" + go mod tidy || return 1 + + if [[ -f go.mod ]]; then + total_deps=$(go list -m all 2>/dev/null | wc -l | tr -d ' ') + upgraded_deps=$(go list -u -m all 2>/dev/null | grep -c '\[.*\]' 2>/dev/null || echo 0) + echo " 📦 $((total_deps - 1)) deps | 🔼 $upgraded_deps upgraded" + fi + + echo " 🔨 go build" + go build ./... || return 1 + + echo " ✅ $module_name" + cd "$ROOT" + return 0 +} + +# Обновляем core +CORE_MOD="$ROOT/core/go.mod" +if [[ -f "$CORE_MOD" ]]; then + echo -e "\n🔷 Core module" + read -rp " ▶️ Update core to $LATEST_GO? (y/N): " confirm + if [[ "$confirm" =~ ^[Yy]$ ]]; then + update_module "$CORE_MOD" "core" || { echo -e "\n🛑 Core update failed. Aborted."; exit 1; } + else + echo " ➖ Skipped." + fi +fi + +# Обновляем сервисы +SERVICES_DIR="$ROOT/service" +mapfile -t MOD_FILES < <(find "$SERVICES_DIR" -name "go.mod" -type f | sort) + +SERVICE_COUNT=${#MOD_FILES[@]} +if [[ $SERVICE_COUNT -eq 0 ]]; then + echo -e "\n📦 No services found." +else + echo -e "\n📦 Found $SERVICE_COUNT service(s):" + for mod in "${MOD_FILES[@]}"; do + name=$(basename "$(dirname "$mod")") + current_go=$(grep '^go ' "$mod" 2>/dev/null | awk '{print $2}' || echo "?") + echo " - $name (go $current_go)" + done + + read -rp $'\n ▶️ Update ALL lib to '"$LATEST_GO"'? (y/N): ' confirm + if [[ "$confirm" =~ ^[Yy]$ ]]; then + echo -e "\n🚀 Updating services...\n" + for mod in "${MOD_FILES[@]}"; do + name=$(basename "$(dirname "$mod")") + update_module "$mod" "$name" || { echo -e "\n🛑 Failed on $name. Aborted."; exit 1; } + done + echo -e "\n🎉 Successfully updated $SERVICE_COUNT service(s)." + else + echo " ➖ All services skipped." + fi +fi \ No newline at end of file