diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml
index 41f1341..ff79913 100644
--- a/.gitea/workflows/deploy.yml
+++ b/.gitea/workflows/deploy.yml
@@ -6,13 +6,13 @@ on:
env:
REPO_DIR: "/workspace/ruspet_portal_back"
- REPO_URL: "https://72.56.235.246.nip.io/gitea/romanskijdev/ruspet_portal_back.git"
+ REPO_URL: "https://${{ github.actor }}:${{ github.token }}@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"
+ TELEPHONY_SERVICE: "rest_telephony_service"
jobs:
deploy:
@@ -20,9 +20,6 @@ jobs:
timeout-minutes: 30
steps:
- # ═══════════════════════════════════════════════════════════════
- # ШАГ 1: Информация о деплое
- # ═══════════════════════════════════════════════════════════════
- name: 📋 Deployment Info
run: |
echo "════════════════════════════════════════"
@@ -37,23 +34,24 @@ jobs:
echo "User: $(whoami)"
echo "════════════════════════════════════════"
- # ═══════════════════════════════════════════════════════════════
- # ШАГ 2: Checkout
- # ═══════════════════════════════════════════════════════════════
- name: 📦 Checkout & Analyze Changes
id: checkout
run: |
mkdir -p "$BACKUP_DIR"
+ git config --global --add safe.directory "$REPO_DIR"
+
DEPLOY_MIGRATIONS=false
DEPLOY_TELEGRAM=false
- DEPLOY_BALANCER=false
DEPLOY_ADMIN=false
+ DEPLOY_TELEPHONY=false
if [ -d "$REPO_DIR/.git" ]; then
echo "📦 Updating existing repo..."
cd "$REPO_DIR"
+ git remote set-url origin "$REPO_URL"
+
OLD_COMMIT=$(git rev-parse HEAD)
echo "Previous commit: $OLD_COMMIT"
@@ -65,8 +63,8 @@ jobs:
echo "⚠️ No changes detected, deploying all services..."
DEPLOY_MIGRATIONS=true
DEPLOY_TELEGRAM=true
- DEPLOY_BALANCER=true
DEPLOY_ADMIN=true
+ DEPLOY_TELEPHONY=true
else
echo "📝 Changed files:"
echo "$CHANGED_FILES" | sed 's/^/ /'
@@ -76,8 +74,8 @@ jobs:
echo "🔄 Core or deploy.sh changed — deploying ALL services"
DEPLOY_MIGRATIONS=true
DEPLOY_TELEGRAM=true
- DEPLOY_BALANCER=true
DEPLOY_ADMIN=true
+ DEPLOY_TELEPHONY=true
else
if echo "$CHANGED_FILES" | grep -q "^service/system_service/"; then
echo "🗄️ Migrations service changed"
@@ -87,14 +85,14 @@ jobs:
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
+ if echo "$CHANGED_FILES" | grep -q "^service/rest_telephony_service/"; then
+ echo "📞 Telephony service changed"
+ DEPLOY_TELEPHONY=true
+ fi
fi
fi
@@ -106,43 +104,34 @@ jobs:
git clone -b main "$REPO_URL" "$REPO_DIR"
DEPLOY_MIGRATIONS=true
DEPLOY_TELEGRAM=true
- DEPLOY_BALANCER=true
DEPLOY_ADMIN=true
+ DEPLOY_TELEPHONY=true
fi
{
echo "DEPLOY_MIGRATIONS=$DEPLOY_MIGRATIONS"
echo "DEPLOY_TELEGRAM=$DEPLOY_TELEGRAM"
- echo "DEPLOY_BALANCER=$DEPLOY_BALANCER"
echo "DEPLOY_ADMIN=$DEPLOY_ADMIN"
+ echo "DEPLOY_TELEPHONY=$DEPLOY_TELEPHONY"
} >> $GITHUB_ENV
echo ""
echo "📊 Deployment plan:"
echo " 🗄️ Migrations: $DEPLOY_MIGRATIONS"
echo " 🤖 Telegram: $DEPLOY_TELEGRAM"
- echo " ⚖️ Balancer: $DEPLOY_BALANCER"
echo " 🔧 Admin: $DEPLOY_ADMIN"
+ echo " 📞 Telephony: $DEPLOY_TELEPHONY"
- # ═══════════════════════════════════════════════════════════════
- # ШАГ 3: Проверка плана
- # ═══════════════════════════════════════════════════════════════
- name: 🔍 Check Deployment Plan
id: check_plan
run: |
- if [ "$DEPLOY_MIGRATIONS" = "false" ] && \
- [ "$DEPLOY_TELEGRAM" = "false" ] && \
- [ "$DEPLOY_BALANCER" = "false" ] && \
- [ "$DEPLOY_ADMIN" = "false" ]; then
+ if [ "$DEPLOY_MIGRATIONS" = "false" ] && [ "$DEPLOY_TELEGRAM" = "false" ] && [ "$DEPLOY_ADMIN" = "false" ] && [ "$DEPLOY_TELEPHONY" = "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: |
@@ -154,9 +143,6 @@ jobs:
cp /etc/ruspet/config.yml "$REPO_DIR/core/config/config.yml"
echo "✅ Config injected"
- # ═══════════════════════════════════════════════════════════════
- # ШАГ 5: Создание backup-ов (безопасное)
- # ═══════════════════════════════════════════════════════════════
- name: 💾 Create Backups
if: env.SKIP_DEPLOY == 'false'
run: |
@@ -178,121 +164,88 @@ jobs:
fi
}
- if [ "$DEPLOY_TELEGRAM" = "true" ]; then
- create_backup "$TELEGRAM_SERVICE"
- fi
+ if [ "$DEPLOY_MIGRATIONS" = "true" ]; then create_backup "$MIGRATIONS_SERVICE"; fi
+ if [ "$DEPLOY_TELEGRAM" = "true" ]; then create_backup "$TELEGRAM_SERVICE"; fi
+ if [ "$DEPLOY_ADMIN" = "true" ]; then create_backup "$ADMIN_SERVICE"; fi
+ if [ "$DEPLOY_TELEPHONY" = "true" ]; then create_backup "$TELEPHONY_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 -- || true
echo "✅ Backups ready"
- # ═══════════════════════════════════════════════════════════════
- # ШАГ 6: Миграции БД
- # ═══════════════════════════════════════════════════════════════
- - name: 🗄️ Run Database Migrations
+ - name: 🗄️ Deploy System Service (Migrations & Background Tasks)
if: env.DEPLOY_MIGRATIONS == 'true' && env.SKIP_DEPLOY == 'false'
id: deploy_migrations
run: |
- echo "🗄️ Running database migrations..."
+ echo "🗄️ Deploying system service..."
if sudo /usr/bin/bash "$REPO_DIR/deploy.sh" migrations; then
- echo "✅ Migrations completed successfully"
+ echo "✅ System service deployed"
echo "MIGRATIONS_DEPLOYED=true" >> $GITHUB_ENV
+ sleep 3
+ # Check if the service FAILED, rather than if it is ACTIVE
+ if ! sudo /usr/bin/systemctl is-failed --quiet "$MIGRATIONS_SERVICE"; then
+ echo "✅ System service executed successfully"
+ else
+ echo "❌ System service failed during execution"
+ sudo /usr/bin/journalctl -u "$MIGRATIONS_SERVICE" -n 30 --no-pager
+ exit 1
+ fi
else
- echo "❌ Migrations failed"
+ echo "❌ System deployment failed"
echo "MIGRATIONS_DEPLOYED=false" >> $GITHUB_ENV
exit 1
fi
- # ═══════════════════════════════════════════════════════════════
- # ШАГ 7: Деплой Telegram бота
- # ═══════════════════════════════════════════════════════════════
- name: 🤖 Deploy Telegram Bot
if: env.DEPLOY_TELEGRAM == 'true' && env.SKIP_DEPLOY == 'false'
id: deploy_telegram
run: |
- echo "🤖 Deploying Telegram bot..."
if sudo /usr/bin/bash "$REPO_DIR/deploy.sh" telegram; then
echo "✅ Telegram bot deployed"
- echo "TELEGRAM_DEPLOYED=true" >> $GITHUB_ENV
sleep 3
- if sudo /usr/bin/systemctl is-active --quiet "$TELEGRAM_SERVICE"; then
- echo "✅ Telegram bot is running"
- else
- echo "❌ Telegram bot failed to start"
- sudo /usr/bin/journalctl -u "$TELEGRAM_SERVICE" -n 30 --no-pager
+ if ! sudo /usr/bin/systemctl is-active --quiet "$TELEGRAM_SERVICE"; then
exit 1
fi
else
- echo "❌ Telegram bot deployment failed"
- echo "TELEGRAM_DEPLOYED=false" >> $GITHUB_ENV
exit 1
fi
- # ═══════════════════════════════════════════════════════════════
- # ШАГ 8: Деплой балансировщика
- # ═══════════════════════════════════════════════════════════════
- - name: ⚖️ Deploy Balancer Service
- if: env.DEPLOY_BALANCER == 'true' && env.SKIP_DEPLOY == 'false' && false
- id: deploy_balancer
- run: |
- echo "⚖️ Deploying balancer service..."
- if sudo /usr/bin/bash "$REPO_DIR/deploy.sh" balancer; then
- echo "✅ Balancer service deployed"
- echo "BALANCER_DEPLOYED=true" >> $GITHUB_ENV
- sleep 3
- if sudo /usr/bin/systemctl is-active --quiet "$BALANCER_SERVICE"; then
- echo "✅ Balancer service is running"
- else
- echo "❌ Balancer service failed to start"
- sudo /usr/bin/journalctl -u "$BALANCER_SERVICE" -n 30 --no-pager
- exit 1
- fi
- else
- echo "❌ Admin deployment failed"
- echo "BALANCER_DEPLOYED=false" >> $GITHUB_ENV
- exit 1
- fi
-
- # ═══════════════════════════════════════════════════════════════
- # ШАГ 9: Деплой админки
- # ═══════════════════════════════════════════════════════════════
- name: 🔧 Deploy Admin Service
if: env.DEPLOY_ADMIN == 'true' && env.SKIP_DEPLOY == 'false'
id: deploy_admin
run: |
- echo "🔧 Deploying admin service..."
if sudo /usr/bin/bash "$REPO_DIR/deploy.sh" admin swagger; then
echo "✅ Admin service deployed with Swagger"
- echo "ADMIN_DEPLOYED=true" >> $GITHUB_ENV
sleep 3
- if sudo /usr/bin/systemctl is-active --quiet "$ADMIN_SERVICE"; then
- echo "✅ Admin service is running"
- else
- echo "❌ Admin service failed to start"
- sudo /usr/bin/journalctl -u "$ADMIN_SERVICE" -n 30 --no-pager
+ if ! sudo /usr/bin/systemctl is-active --quiet "$ADMIN_SERVICE"; then
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
- # ═══════════════════════════════════════════════════════════════
- # ШАГ 10: Rollback при ошибке
- # ═══════════════════════════════════════════════════════════════
+ - name: 📞 Deploy Telephony Service
+ if: env.DEPLOY_TELEPHONY == 'true' && env.SKIP_DEPLOY == 'false'
+ id: deploy_telephony
+ run: |
+ echo "📞 Deploying telephony service..."
+ if sudo /usr/bin/bash "$REPO_DIR/deploy.sh" telephony; then
+ echo "✅ Telephony service deployed"
+ echo "TELEPHONY_DEPLOYED=true" >> $GITHUB_ENV
+ sleep 3
+ if sudo /usr/bin/systemctl is-active --quiet "$TELEPHONY_SERVICE"; then
+ echo "✅ Telephony service is running"
+ else
+ echo "❌ Telephony service failed to start"
+ sudo /usr/bin/journalctl -u "$TELEPHONY_SERVICE" -n 30 --no-pager
+ exit 1
+ fi
+ else
+ echo "❌ Telephony deployment failed"
+ echo "TELEPHONY_DEPLOYED=false" >> $GITHUB_ENV
+ exit 1
+ fi
+
- name: ⏮️ Rollback on Failure
if: failure()
run: |
@@ -311,149 +264,87 @@ jobs:
sudo chmod +x "/usr/local/bin/$service"
sudo systemctl restart "$service"
sleep 2
-
- if sudo 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
}
- 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
+ if [ "$DEPLOY_MIGRATIONS" = "true" ]; then rollback_service "$MIGRATIONS_SERVICE"; fi
+ if [ "$DEPLOY_TELEGRAM" = "true" ]; then rollback_service "$TELEGRAM_SERVICE"; fi
+ if [ "$DEPLOY_ADMIN" = "true" ]; then rollback_service "$ADMIN_SERVICE"; fi
+ if [ "$DEPLOY_TELEPHONY" = "true" ]; then rollback_service "$TELEPHONY_SERVICE"; fi
echo "✅ Rollback completed"
- # ═══════════════════════════════════════════════════════════════
- # ШАГ 11: Финальная верификация
- # ═══════════════════════════════════════════════════════════════
- name: ✅ Verify Services
if: env.SKIP_DEPLOY == 'false' && success()
run: |
echo "🔍 Verifying services..."
-
ALL_OK=true
verify_service() {
local service=$1
local should_deploy=$2
-
if [ "$should_deploy" = "true" ]; then
if sudo systemctl is-active --quiet "$service"; then
- UPTIME=$(systemctl show "$service" --property=ActiveEnterTimestamp --value)
- echo "✅ $service: running (since $UPTIME)"
+ echo "✅ $service: running"
else
echo "❌ $service: NOT RUNNING"
ALL_OK=false
fi
- else
- echo "⏭️ $service: skipped"
fi
}
+ verify_service "$MIGRATIONS_SERVICE" "$DEPLOY_MIGRATIONS"
verify_service "$TELEGRAM_SERVICE" "$DEPLOY_TELEGRAM"
- verify_service "$BALANCER_SERVICE" "$DEPLOY_BALANCER"
verify_service "$ADMIN_SERVICE" "$DEPLOY_ADMIN"
+ verify_service "$TELEPHONY_SERVICE" "$DEPLOY_TELEPHONY"
- if [ "$ALL_OK" = "true" ]; then
- echo "✅ All services verified successfully"
- else
- echo "❌ Some services are not running"
- exit 1
- fi
+ if [ "$ALL_OK" != "true" ]; then exit 1; fi
- # ═══════════════════════════════════════════════════════════════
- # ШАГ 12: Уведомление об успехе
- # ═══════════════════════════════════════════════════════════════
- name: 📢 Notify Success
if: success()
run: |
- echo "✅ Deployment completed successfully!"
-
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
+ if [ "$DEPLOY_MIGRATIONS" = "true" ]; then MESSAGE+="🗄️ System (Migrations): deployed%0A"; fi
+ if [ "$DEPLOY_TELEGRAM" = "true" ]; then MESSAGE+="🤖 Telegram: deployed%0A"; fi
+ if [ "$DEPLOY_ADMIN" = "true" ]; then MESSAGE+="🔧 Admin: deployed%0A"; fi
+ if [ "$DEPLOY_TELEPHONY" = "true" ]; then MESSAGE+="📞 Telephony: 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"
+ -d "chat_id=${{ secrets.TELEGRAM_CHAT_ID }}" -d "parse_mode=HTML" -d "text=$MESSAGE"
fi
- # ═══════════════════════════════════════════════════════════════
- # ШАГ 13: Уведомление об ошибке
- # ═══════════════════════════════════════════════════════════════
- name: 🚨 Notify Failure
if: failure()
run: |
- echo "❌ Deployment failed!"
-
- for service in "$TELEGRAM_SERVICE" "$BALANCER_SERVICE" "$ADMIN_SERVICE"; do
- echo ""
- echo "📜 $service logs (last 20 lines):"
+ for service in "$MIGRATIONS_SERVICE" "$TELEGRAM_SERVICE" "$ADMIN_SERVICE" "$TELEPHONY_SERVICE"; do
+ echo "📜 $service logs:"
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"
+ -d "chat_id=${{ secrets.TELEGRAM_CHAT_ID }}" -d "parse_mode=HTML" -d "text=$MESSAGE"
fi
- # ═══════════════════════════════════════════════════════════════
- # ШАГ 14: Итоговая сводка
- # ═══════════════════════════════════════════════════════════════
- 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 "System (Migrations): ${DEPLOY_MIGRATIONS:-false}"
+ echo "Telegram bot: ${DEPLOY_TELEGRAM:-false}"
+ echo "Admin: ${DEPLOY_ADMIN:-false}"
+ echo "Telephony: ${DEPLOY_TELEPHONY:-false}"
echo "════════════════════════════════════════"
\ No newline at end of file
diff --git a/code2text.py b/code2text.py
new file mode 100644
index 0000000..0a7428e
--- /dev/null
+++ b/code2text.py
@@ -0,0 +1,31 @@
+import os
+
+def generate_codebase(root_dir, output_file):
+ # Папки, которые мы игнорируем
+ ignore_dirs = {'.git', 'vendor', '__pycache__', 'node_modules', '.idea', '.vscode'}
+ # Расширения файлов, которые нам не нужны (бинарники и контрольные суммы)
+ ignore_exts = {'.pyc', '.sum', '.exe', '.dll', '.so', '.pdf', '.png', '.jpg'}
+
+ with open(output_file, 'w', encoding='utf-8') as outfile:
+ for root, dirs, files in os.walk(root_dir):
+ # Исключаем игнорируемые директории, модифицируя список dirs на месте
+ dirs[:] = [d for d in dirs if d not in ignore_dirs]
+
+ for file in files:
+ # Пропускаем сам выходной файл, этот скрипт и файлы с ненужными расширениями
+ if file == output_file or file == "code2text.py" or any(file.endswith(ext) for ext in ignore_exts):
+ continue
+
+ filepath = os.path.join(root, file)
+ try:
+ with open(filepath, 'r', encoding='utf-8') as infile:
+ outfile.write(f"\n\n=== ФАЙЛ: {filepath} ===\n")
+ outfile.write(infile.read())
+ except Exception as e:
+ # Если файл нельзя прочитать как текст (например, это картинка без расширения), просто запишем ошибку и пойдем дальше
+ outfile.write(f"\n\n=== ПРОПУЩЕН БИНАРНЫЙ ФАЙЛ ИЛИ ОШИБКА ЧТЕНИЯ: {filepath} ===\n")
+
+if __name__ == "__main__":
+ # Меняем '.' на './service/telegram_service' (или как у вас называется эта папка)
+ generate_codebase('./service/telegram_service', 'telegram_codebase.txt')
+ print("Готово! Код собран в файл telegram_codebase.txt")
diff --git a/core/config/config-types.go b/core/config/config-types.go
index 3134bec..1d87568 100644
--- a/core/config/config-types.go
+++ b/core/config/config-types.go
@@ -1,7 +1,5 @@
package configcore
-import "net/url"
-
// RedisConfig конфигурация Redis
type RedisConfig struct {
Host string `yaml:"host" env-required:"true"`
@@ -22,12 +20,8 @@ type DatabaseConfig struct {
// 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 // кэшированный распарсенный прокси
+ BotToken string `yaml:"bot_token"`
+ WebAppUrl string `yaml:"web_app_url"`
}
// ServiceConfig конфигурация сервиса
diff --git a/core/db/db.go b/core/db/db.go
index 34f19f8..d728e3c 100644
--- a/core/db/db.go
+++ b/core/db/db.go
@@ -34,6 +34,15 @@ type ModuleDB struct {
ApprovalAdditionalObserver *dbcore.ApprovalAdditionalObserverDB
ApprovalTopicExecutor *dbcore.ApprovalTopicExecutorDB
Admin *dbcore.AdminDB
+ Notification *dbcore.NotificationDB
+ DirectorNotifications *dbcore.DirectorNotificationDB
+ ApprovalTaskTransfer *dbcore.ApprovalTaskTransferDB
+ ApprovalRevocation *dbcore.ApprovalRevocationDB
+ ApprovalFlowNode *dbcore.ApprovalFlowNodeDB
+ AdminActionLogs *dbcore.AdminActionLogDB
+ SMSLog *dbcore.SmsLogDB
+ MonthlyOrders *dbcore.MonthlyOrderDB
+ TaskDelegation *dbcore.TaskDelegationDB
}
func NewModuleDB(
@@ -84,6 +93,15 @@ func initDBModules(modules *ModuleDB, redisClient *redismodule.ModuleRedis) *Mod
modules.ApprovalAdditionalObserver = dbcore.NewApprovalAdditionalObserverDB(modules.Pool)
modules.ApprovalTopicExecutor = dbcore.NewApprovalTopicExecutorDB(modules.Pool)
modules.Admin = dbcore.NewAdminDB(modules.Pool)
+ modules.Notification = dbcore.NewNotificationDB(modules.Pool)
+ modules.DirectorNotifications = dbcore.NewDirectorNotificationDB(modules.Pool)
+ modules.ApprovalTaskTransfer = dbcore.NewApprovalTaskTransferDB(modules.Pool)
+ modules.ApprovalRevocation = dbcore.NewApprovalRevocationDB(modules.Pool)
+ modules.ApprovalFlowNode = dbcore.NewApprovalFlowNodeDB(modules.Pool)
+ modules.AdminActionLogs = dbcore.NewAdminActionLogDB(modules.Pool)
+ modules.SMSLog = dbcore.NewSmsLogDB(modules.Pool)
+ modules.MonthlyOrders = dbcore.NewMonthlyOrderDB(modules.Pool)
+ modules.TaskDelegation = dbcore.NewTaskDelegationDB(modules.Pool)
return modules
}
diff --git a/core/db/db_migration/default_data.go b/core/db/db_migration/default_data.go
index 04f2ce8..974ea38 100644
--- a/core/db/db_migration/default_data.go
+++ b/core/db/db_migration/default_data.go
@@ -1,7 +1,6 @@
package dbmigration
import (
- "bitrix_balancer_api/core/typescore"
_ "embed"
"encoding/csv"
"encoding/json"
@@ -20,12 +19,6 @@ import (
"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_]`)
@@ -47,10 +40,7 @@ type dataEntry struct {
// 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},
-}
+var defaultDataEntries []dataEntry
// DefaultDataSet seeds every table defined in defaultDataEntries.
// It attempts all tables and returns a combined error if any fail.
diff --git a/core/db/db_migration/default_data/approval_topic_categories.csv b/core/db/db_migration/default_data/approval_topic_categories.csv
deleted file mode 100644
index 3b0f19f..0000000
--- a/core/db/db_migration/default_data/approval_topic_categories.csv
+++ /dev/null
@@ -1,29 +0,0 @@
-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
deleted file mode 100644
index b609521..0000000
--- a/core/db/db_migration/default_data/approval_topics.csv
+++ /dev/null
@@ -1,148 +0,0 @@
-id,category_id,name,code,duration_type,time_type,payment_type,template,allows_file,is_active,created_at,updated_at,allow_approver_selection,first_approver_role_code,allow_observer_selection,approval_mode,require_approver_comment,requires_file,require_observer_selection,instructions
-70,15,Менеджерские расходы: Крым,manager_expenses_crimea,,,,Оплата платной дороги Краснодар-Темрюк-Краснодар в сумме 1420 руб. (клиент РУСМолоко) (расход Макаренко),false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-590,15,Менеджерские расходы: Краснодар,manager_expenses_krasnodar,,,,,false,true,2026-06-03 08:55:52.439479,2026-06-03 08:55:52.439479,false,,false,sequential,false,false,false,
-49,7,Сменить менеджера Битрикс Краснодар,client_changes_change_manager_bitrix_krasnodar,,,,Опишите смену менеджера в Битрикс (Краснодар),false,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-586,9,Отгрузка на СОХ — Крым (реальная),shipments_soh_crimea_real,,,,Опишите отгрузку,false,true,2026-06-02 07:10:13.844873,2026-06-02 07:10:13.844873,false,,false,sequential,true,false,false,
-4,1,Отгул — диапазон частично,timeoff_date_range_partial_own_expense,date_range,partial,own_expense,22.02.2022 - 25.02.2022 с 16:00 по 18:00,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-65,11,Ставки Логистика: Надолго,rates_logistics_long_term,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-592,17,Нестандартные условия поставки: Беларусь,nonstandard_contract_belarus,,,,,true,true,2026-06-03 09:20:00.662572,2026-06-03 09:20:00.662572,false,,false,sequential,true,false,false,
-591,17,Нестандартные условия поставки: Краснодар,nonstandard_contract_krasnodar,,,,,true,true,2026-06-03 09:20:00.662572,2026-06-03 09:20:00.662572,false,,false,sequential,true,false,false,
-594,23,ОТК: Краснодар,otk_conditions_krasnodar,,,,,false,true,2026-06-03 09:29:10.377976,2026-06-03 09:29:10.377976,false,,false,sequential,false,false,false,
-595,23,ОТК: Беларусь,otk_conditions_belarus,,,,,false,true,2026-06-03 09:29:10.377976,2026-06-03 09:29:10.377976,false,,false,sequential,false,false,false,
-5,1,Отгул — диапазон весь день в счёт отпуска,timeoff_date_range_full_day_vacation_account,date_range,full_day,vacation_account,22.02.2022 - 25.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-6,1,Отгул — диапазон весь день за свой счёт,timeoff_date_range_full_day_own_expense,date_range,full_day,own_expense,22.02.2022 - 25.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-16,3,Больничный — несколько дней официальный,sickleave_multi_day_full_day_official,multi_day,full_day,official,"22.02.2022, 24.02.2022, 26.02.2022",true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-17,3,Больничный — несколько дней в счёт отпуска,sickleave_multi_day_full_day_vacation_account,multi_day,full_day,vacation_account,"22.02.2022, 24.02.2022, 26.02.2022",false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-589,9,Отгрузка на СОХ — Краснодар (лимит),shipments_soh_krasnodar_limit,,,,Опишите отгрузку,false,true,2026-06-02 07:10:13.915061,2026-06-02 07:10:13.915061,false,,false,sequential,true,false,false,
-587,9,Отгрузка на СОХ — Крым (лимит),shipments_soh_crimea_limit,,,,Опишите отгрузку,false,true,2026-06-02 07:10:13.868383,2026-06-02 07:10:13.868383,false,,false,sequential,true,false,false,
-21,3,Больничный — диапазон за свой счёт,sickleave_date_range_full_day_own_expense,date_range,full_day,own_expense,22.02.2022 - 25.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-24,3,Больничный — один день за свой счёт,sickleave_single_day_full_day_own_expense,single_day,full_day,own_expense,22.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-588,9,Отгрузка на СОХ — Краснодар (реальная),shipments_soh_krasnodar_real,,,,Опишите отгрузку,false,true,2026-06-02 07:10:13.892797,2026-06-02 07:10:13.892797,false,,false,sequential,true,false,false,
-18,3,Больничный — несколько дней за свой счёт,sickleave_multi_day_full_day_own_expense,multi_day,full_day,own_expense,"22.02.2022, 24.02.2022, 26.02.2022",false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-59,9,Отгрузки на СОХ реальная,shipments_soh_real,,,,Опишите реальную отгрузку на СОХ,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-43,7,Поменять название Битрикс Краснодар,client_changes_rename_bitrix_krasnodar,,,,Опишите изменение названия клиента в Битрикс (Краснодар),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-27,4,Внебюджетные расходы: Ф2 ТМЦ,non_budget_expenses_f2_tmc,,,,Прошу согласовать оплату за зарядку для телефона (руководителю отдела логистики) в сумме 293 руб.,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-60,9,Отгрузки на СОХ для лимита,shipments_soh_limit,,,,Опишите отгрузку для лимита на СОХ,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-19,3,Больничный — диапазон официальный,sickleave_date_range_full_day_official,date_range,full_day,official,22.02.2022 - 25.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-22,3,Больничный — один день официальный,sickleave_single_day_full_day_official,single_day,full_day,official,22.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-82,27,Заведение новых клиентов,new_clients,,,,,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-83,28,Утверждение оплат безнал,payments_cashless,,,,,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-1,1,Отгул — несколько дней частично,timeoff_multi_day_partial_own_expense,multi_day,partial,own_expense,"22.02.2022 с 10:00 по 14:00, 24.02.2022 с 09:00 по 12:00",false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-2,1,Отгул — несколько дней весь день в счёт отпуска,timeoff_multi_day_full_day_vacation_account,multi_day,full_day,vacation_account,"22.02.2022, 24.02.2022, 26.02.2022",false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-3,1,Отгул — несколько дней весь день за свой счёт,timeoff_multi_day_full_day_own_expense,multi_day,full_day,own_expense,"22.02.2022, 24.02.2022, 26.02.2022",false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-7,1,Отгул — один день частично,timeoff_single_day_partial_own_expense,single_day,partial,own_expense,22.02.2022 с 16:00 по 18:00,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-8,1,Отгул — один день весь день в счёт отпуска,timeoff_single_day_full_day_vacation_account,single_day,full_day,vacation_account,22.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-9,1,Отгул — один день весь день за свой счёт,timeoff_single_day_full_day_own_expense,single_day,full_day,own_expense,22.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-10,2,Отпуск — несколько дней в счёт отпуска,vacation_multi_day_full_day_vacation_account,multi_day,full_day,vacation_account,"22.02.2022, 24.02.2022, 26.02.2022",false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-11,2,Отпуск — несколько дней за свой счёт,vacation_multi_day_full_day_own_expense,multi_day,full_day,own_expense,"22.02.2022, 24.02.2022, 26.02.2022",false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-12,2,Отпуск — диапазон в счёт отпуска,vacation_date_range_full_day_vacation_account,date_range,full_day,vacation_account,22.02.2022 - 25.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-13,2,Отпуск — диапазон за свой счёт,vacation_date_range_full_day_own_expense,date_range,full_day,own_expense,22.02.2022 - 25.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-14,2,Отпуск — один день в счёт отпуска,vacation_single_day_full_day_vacation_account,single_day,full_day,vacation_account,22.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-15,2,Отпуск — один день за свой счёт,vacation_single_day_full_day_own_expense,single_day,full_day,own_expense,22.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-20,3,Больничный — диапазон в счёт отпуска,sickleave_date_range_full_day_vacation_account,date_range,full_day,vacation_account,22.02.2022 - 25.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-23,3,Больничный — один день в счёт отпуска,sickleave_single_day_full_day_vacation_account,single_day,full_day,vacation_account,22.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-61,10,ПС: Краснодар,transaction_passport_krasnodar,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,true,false,
-580,8,Заказ на месяц — Крым,goods_order_monthly_crimea,,,,"Опишите Скилур заказ:
- 22 гр.38 мм бесцветная (10176) ЕПМ - 5кор.
- ф1, на склад Гвардейское, 2я декада.",true,true,2026-05-27 07:32:42.878447,2026-05-27 07:32:42.878447,false,,false,sequential,true,true,false,
-58,8,Заказ товаров дополнительный,goods_order_additional,,,,Опишите дополнительный заказ,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,true,false,
-582,8,Дополнительный заказ — Крым,goods_order_additional_crimea,,,,"Опишите Скилур заказ:
- 22 гр.38 мм бесцветная (10176) ЕПМ - 5кор.
- ф1, на склад Гвардейское, 2я декада.",true,true,2026-05-27 07:32:42.959177,2026-05-27 07:32:42.959177,false,,false,sequential,true,true,false,
-57,8,Заказ товаров на месяц,goods_order_monthly,,,,Опишите заказ на месяц,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,true,false,
-597,4,Внебюджетные расходы: Ф1 ТМЦ (без ПП),non_budget_expenses_f1_tmc_pp_no,,,,,false,true,2026-06-10 09:06:59.648658,2026-06-10 09:06:59.648658,false,,false,sequential,false,false,false,
-599,4,Внебюджетные расходы: Ф1 Расход (без ПП),non_budget_expenses_f1_expense_pp_no,,,,,false,true,2026-06-10 09:06:59.684144,2026-06-10 09:06:59.684144,false,,false,sequential,false,false,false,
-42,7,Поменять название ОКБ Краснодар,client_changes_rename_okb_krasnodar,,,,Опишите изменение названия клиента в ОКБ (Краснодар),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-602,28,Оплата безнал — Разное (нужна ПП),payments_cashless_misc_pp_yes,,,,,true,true,2026-06-10 09:06:59.730960,2026-06-10 09:06:59.730960,false,,false,sequential,false,true,false,
-603,28,Оплата безнал — Разное (без ПП),payments_cashless_misc_pp_no,,,,,true,true,2026-06-10 09:06:59.746484,2026-06-10 09:06:59.746484,false,,false,sequential,false,true,false,
-600,28,Оплата безнал — Товар (нужна ПП),payments_cashless_goods_pp_yes,,,,,true,true,2026-06-10 09:06:59.699401,2026-06-10 09:06:59.699401,false,,false,sequential,false,true,false,
-601,28,Оплата безнал — Товар (без ПП),payments_cashless_goods_pp_no,,,,,true,true,2026-06-10 09:06:59.716456,2026-06-10 09:06:59.716456,false,,false,sequential,false,true,false,
-598,4,Внебюджетные расходы: Ф1 Расход (нужна ПП),non_budget_expenses_f1_expense_pp_yes,,,,,true,true,2026-06-10 09:06:59.666345,2026-06-10 09:06:59.666345,false,,false,sequential,false,true,false,
-596,4,Внебюджетные расходы: Ф1 ТМЦ (нужна ПП),non_budget_expenses_f1_tmc_pp_yes,,,,,true,true,2026-06-10 09:06:59.628993,2026-06-10 09:06:59.628993,false,,false,sequential,false,true,false,
-37,6,Самостоятельная продажа Крым,returns_self_sale_crimea,,,,"ТД Крымэколайф
-40,5 гр.1881 бесцветная (7808) ПФ - 52 короба
-Реализация товаров и услуг ЧП000003123 от 4.08.25
-Ф1
-
-Причина: для сокращения долга клиента
-
-Действия: продам ООО Нива",false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-34,6,Возврат поставщику Краснодар,returns_supplier_krasnodar,,,,,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-38,6,Самостоятельная продажа Краснодар,returns_self_sale_krasnodar,,,,,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-33,6,Возврат поставщику Крым,returns_supplier_crimea,,,,"Бишули
-28 гр.1881 бесцветная (9504) ПФ - 2 короба
-Реализация товаров и услуг ЧП000001326 от 20.04.2026 8:00:01
-Ф1
-
-Причина: Короб приехал с завода и сильно порвался в дороге, клиент не может на свою продукцию использовать его",false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-62,10,ПС: Крым,transaction_passport_crimea,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,true,false,
-73,18,Вакансии,vacancies,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,supervisor,false,sequential,false,false,false,
-80,25,Продажи по клиенту,client_sales,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,manager,false,sequential,false,true,false,
-78,23,ОТК: Крым,otk_conditions_crimea,,,,Опишите долгосрочные условия ОТК,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-605,7,Внести нового клиента - Краснодар,client_changes_new_client_krasnodar,,,,,false,true,2026-06-11 04:33:53.266045,2026-06-11 04:33:53.266045,false,,false,sequential,false,false,false,
-607,7,Внести нового клиента - Крым,client_changes_new_client_crimea,,,,,false,true,2026-06-11 04:33:53.266045,2026-06-11 04:33:53.266045,false,,false,sequential,false,false,false,
-609,7,Поменять название - Краснодар,client_changes_rename_krasnodar,,,,,false,true,2026-06-11 04:33:53.266045,2026-06-11 04:33:53.266045,false,,false,sequential,false,false,false,
-611,7,Поменять название - Крым,client_changes_rename_crimea,,,,,false,true,2026-06-11 04:33:53.266045,2026-06-11 04:33:53.266045,false,,false,sequential,false,false,false,
-613,7,Сменить менеджера - Краснодар,client_changes_change_manager_krasnodar,,,,,false,true,2026-06-11 04:33:53.266045,2026-06-11 04:33:53.266045,false,,false,sequential,false,false,false,
-615,7,Сменить менеджера - Крым,client_changes_change_manager_crimea,,,,,false,true,2026-06-11 04:33:53.266045,2026-06-11 04:33:53.266045,false,,false,sequential,false,false,false,
-53,7,Внести нового клиента 1С Крым,client_changes_new_client_1c_crimea,,,,Опишите данные нового клиента для 1С (Крым),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-50,7,Сменить менеджера 1С Краснодар,client_changes_change_manager_1c_krasnodar,,,,Опишите смену менеджера в 1С (Краснодар),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-72,17,Нестандартные условия поставки: Крым,nonstandard_contract_crimea,,,,Прошу согласовать отсрочку 21 день для клиента ООО Роса (другое юрлицо ООО Аквариум) (менеджер Петров),true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,true,false,false,
-36,6,Продажа другим менеджером Краснодар,returns_other_manager_krasnodar,,,,,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,manager,false,sequential,false,false,false,
-64,11,Ставки Логистика: Разово,rates_logistics_once,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-67,12,Приходные документы Ф2,receipts_f2,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,true,true,false,
-66,12,Приходные документы Ф1,receipts_f1,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,true,true,false,
-51,7,Внести нового клиента ОКБ Крым,client_changes_new_client_okb_crimea,,,,Опишите данные нового клиента для ОКБ (Крым),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-54,7,Внести нового клиента ОКБ Краснодар,client_changes_new_client_okb_krasnodar,,,,Опишите данные нового клиента для ОКБ (Краснодар),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-47,7,Сменить менеджера 1С Крым,client_changes_change_manager_1c_crimea,,,,Опишите смену менеджера в 1С (Крым),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-41,7,Поменять название 1С Крым,client_changes_rename_1c_crimea,,,,Опишите изменение названия клиента в 1С (Крым),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-29,5,ПЭТ Лайн Ф1 ТМЦ,non_budget_expenses_pet_line_f1_tmc,,,,,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-31,5,ПЭТ Лайн Ф2 ТМЦ,non_budget_expenses_pet_line_f2_tmc,,,,,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-26,4,Внебюджетные расходы: Ф1 Расход,non_budget_expenses_f1_expense,,,,"Прошу оплатить счет ИП Гулякина на сумму 3180,00 руб (без НДС) за продление 1С-Отчетность на 1 год",true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-28,4,Внебюджетные расходы: Ф2 Расход,non_budget_expenses_f2_expense,,,,Прошу согласовать 1000 руб на покупку контактов резюме грузчиков на платформе Авито,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-75,20,Утверждение фрилансеров,freelancers_approval,,,,Одного помощника на выгрузку полной фуры с крышкой ручкой с КТ на 23.04.2026 на весь день,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-35,6,Продажа другим менеджером Крым,returns_other_manager_crimea,,,,"Бишули
-61 гр.38 мм бесцветная (3888) ЕП - 11 коробов
-Реализация товаров и услуг ЧП000000584 от 05.03.2026 8:00:01
-Ф1
-
-Причина: Часть заказа отвалилась, будут переходить на эту позицию не раньше, чем через 3 мес
-
-Продаст Чекальский на Бойко",false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,manager,false,sequential,false,false,false,
-77,22,Предложения и пожелания,suggestions,,,,,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-63,10,ПС: Беларусь,transaction_passport_belarus,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,true,false,
-74,19,Ставки доставки АП,delivery_rates_ap,,,,Прошу согласовать доставку 14 кор преформы клиенту Олег-Выдув-Сочи за 34 000 руб.,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-71,16,Отгрузки,shipments,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,true,sequential,false,true,true,"Если не входит в рамки согласованного лимита, добавь руководителя соответствующего филиала к согласованию через кнопку 'Добавить согласующего'"
-584,28,Оплата безнал — Товар,payments_cashless_goods,,,,Опишите оплату,false,true,2026-06-02 06:14:34.876867,2026-06-02 06:14:34.876867,false,,false,sequential,false,false,false,
-585,28,Оплата безнал — Разное,payments_cashless_misc,,,,Опишите оплату,false,true,2026-06-02 06:14:34.926542,2026-06-02 06:14:34.926542,false,,false,sequential,false,false,false,
-583,8,Дополнительный заказ — Краснодар,goods_order_additional_krasnodar,,,,"Опишите Скилур заказ:
- 22 гр.38 мм бесцветная (10176) ЕПМ - 5кор.
- ф1, на склад Гвардейское, 2я декада.",true,true,2026-05-27 07:32:42.987951,2026-05-27 07:32:42.987951,false,,false,sequential,true,true,false,
-581,8,Заказ на месяц — Краснодар,goods_order_monthly_krasnodar,,,,"Скилур заказ:
-22 гр.38 мм бесцветная (10176) ЕПМ - 5кор.
-ф1, на склад Гвардейское, 2я декада.",true,true,2026-05-27 07:32:42.929341,2026-05-27 07:32:42.929341,false,,false,sequential,true,true,false,
-79,24,Остаток в кассах,cash_balance,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,supervisor,false,sequential,false,false,false,
-55,7,Внести нового клиента Битрикс Краснодар,client_changes_new_client_bitrix_krasnodar,,,,Опишите данные нового клиента для Битрикс (Краснодар),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-25,4,Внебюджетные расходы: Ф1 ТМЦ,non_budget_expenses_f1_tmc,,,,Прошу согласовать и оплатить Счет от ООО Интернет Решения (Озон) за ноутбук и мышь для закупщика в сумме 31 335 руб. С НДС,true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-30,5,ПЭТ Лайн Ф1 Расход,non_budget_expenses_pet_line_f1_expense,,,,,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-76,21,Выход в нерабочий день,non_working_day,,,,Прошу вывести склад для учета c 25.04 по 26.04,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-68,13,Доставка клиентам/на склад,delivery_clients,,,,"Иванов Иван Иванович
-Тел 89781234567
-Паспорт 1234 567890
-ДАФ н862нн46 п/п АА8473|46
-
-61 бц с ад - 52 кор
-ЧП000001676
-
-ЕПР-СтройКрым",true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,manager,false,sequential,false,false,false,
-32,5,ПЭТ Лайн Ф2 Расход,non_budget_expenses_pet_line_f2_expense,,,,,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-40,7,Поменять название Битрикс Крым,client_changes_rename_bitrix_crimea,,,,Опишите изменение названия клиента в Битрикс (Крым),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-44,7,Поменять название 1С Краснодар,client_changes_rename_1c_krasnodar,,,,Опишите изменение названия клиента в 1С (Краснодар),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-46,7,Сменить менеджера Битрикс Крым,client_changes_change_manager_bitrix_crimea,,,,Опишите смену менеджера в Битрикс (Крым),false,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-56,7,Внести нового клиента 1С Краснодар,client_changes_new_client_1c_krasnodar,,,,Опишите данные нового клиента для 1С (Краснодар),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-52,7,Внести нового клиента Битрикс Крым,client_changes_new_client_bitrix_crimea,,,,Опишите данные нового клиента для Битрикс (Крым),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-45,7,Сменить менеджера ОКБ Крым,client_changes_change_manager_okb_crimea,,,,Опишите смену менеджера в ОКБ (Крым),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-48,7,Сменить менеджера ОКБ Краснодар,client_changes_change_manager_okb_krasnodar,,,,Опишите смену менеджера в ОКБ (Краснодар),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-69,14,В. Отгрузки,v_shipments,,,,ООО Нива на 370 тыс. руб. под 19%,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
-81,26,Проведенные расходы по менеджеру,manager_expenses_report,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,manager,false,sequential,false,false,false,
-39,7,Поменять название ОКБ Крым,client_changes_rename_okb_crimea,,,,Опишите изменение названия клиента в ОКБ (Крым),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
diff --git a/core/db/db_migration/tables.go b/core/db/db_migration/tables.go
index 5dcea35..cfff54f 100644
--- a/core/db/db_migration/tables.go
+++ b/core/db/db_migration/tables.go
@@ -38,6 +38,17 @@ func (m *MigrationFunctions) migrateTables() error {
tablesmigration.ApprovalAdditionalObserverTableMigrate,
tablesmigration.ApprovalTopicExecutorsTableMigrate,
tablesmigration.AdminsTableMigrate,
+
+ tablesmigration.NotificationsTableMigrate,
+ tablesmigration.DirectorNotificationSubscriptionsTableMigrate,
+ tablesmigration.ApprovalTaskTransfersTableMigrate,
+ tablesmigration.ApprovalRevocationTablesMigrate,
+ tablesmigration.ApprovalFlowNodesTableMigrate,
+ tablesmigration.AdminActionLogsTableMigrate,
+
+ tablesmigration.SmsLogsTableMigrate,
+ tablesmigration.MonthlyOrdersTablesMigrate,
+ tablesmigration.TaskDelegationsTableMigrate,
}
for _, migrate := range migrations {
diff --git a/core/db/db_migration/tables/admin_action_log.go b/core/db/db_migration/tables/admin_action_log.go
new file mode 100644
index 0000000..df45b90
--- /dev/null
+++ b/core/db/db_migration/tables/admin_action_log.go
@@ -0,0 +1,36 @@
+package tablesmigration
+
+import (
+ dbcoretablenames "bitrix_balancer_api/core/db/table_names"
+ "bitrix_balancer_api/core/typescore"
+ "gorm.io/gorm"
+ "time"
+)
+
+// LocalAdminProvider - локальная структура для миграции
+type LocalAdminActionProvider typescore.AdminActionLog
+
+func (LocalAdminActionProvider) TableName() string {
+ return dbcoretablenames.TableNameAdminActionLogs.ToString()
+}
+
+// AdminsTableMigrate - миграция таблицы Admins
+func AdminActionLogsTableMigrate(db *gorm.DB) error {
+ hasTable := db.Migrator().HasTable(&LocalAdminActionProvider{})
+
+ // Выполняем автосоздание таблицы
+ err := db.AutoMigrate(&LocalAdminActionProvider{})
+ if err != nil {
+ return err
+ }
+
+ if !hasTable {
+ time.Sleep(5 * time.Second) // Добавляем задержку
+
+ // Add comments to table and columns
+ db.Exec(`
+ COMMENT ON TABLE admin_action_logs IS 'Таблица для хранения данных о действиях администратора';
+ `)
+ }
+ return nil
+}
diff --git a/core/db/db_migration/tables/approval.go b/core/db/db_migration/tables/approval.go
index ecaf200..5bb4b4e 100644
--- a/core/db/db_migration/tables/approval.go
+++ b/core/db/db_migration/tables/approval.go
@@ -36,5 +36,20 @@ func ApprovalsTableMigrate(db *gorm.DB) error {
COMMENT ON COLUMN "approvals".updated_at IS 'Дата последнего изменения заявки';
`)
}
+
+ // 🚀 Индексы: покрывают фильтры GetApprovalsListHandler, JOIN'ы enrichApprovalsBatch и сортировку
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approvals_initiator_id ON approvals (initiator_id)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approvals_topic_id ON approvals (topic_id)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approvals_department_id ON approvals (department_id)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approvals_revoked_by_id ON approvals (revoked_by_id)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approvals_status ON approvals (status)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approvals_created_at ON approvals (created_at DESC)`)
+ // Композитный индекс под самый частый сценарий: список заявок конкретного статуса, отсортированный по дате
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approvals_status_created_at ON approvals (status, created_at DESC)`)
+ // Под фильтр report по инициатору + период
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approvals_initiator_created_at ON approvals (initiator_id, created_at DESC)`)
+ // Под DeleteTopicHandler / проверку "есть ли заявки по теме"
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approvals_topic_status ON approvals (topic_id, status)`)
+
return nil
}
diff --git a/core/db/db_migration/tables/approval_additional_approver.go b/core/db/db_migration/tables/approval_additional_approver.go
index 9db720b..12bb199 100644
--- a/core/db/db_migration/tables/approval_additional_approver.go
+++ b/core/db/db_migration/tables/approval_additional_approver.go
@@ -15,12 +15,10 @@ func ApprovalAdditionalApproverTableMigrate(db *gorm.DB) error {
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 'Внутренний уникальный идентификатор записи';
@@ -34,5 +32,13 @@ func ApprovalAdditionalApproverTableMigrate(db *gorm.DB) error {
COMMENT ON COLUMN "approval_additional_approvers".updated_at IS 'Дата и время последнего изменения записи';
`)
}
+
+ // 🚀 approval_id — джойн при обогащении заявки; approver_id — "мои задачи на согласование";
+ // композит approval_id+status — фильтр pending-согласующих конкретной заявки
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_add_approvers_approval_id ON approval_additional_approvers (approval_id)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_add_approvers_approver_id ON approval_additional_approvers (approver_id)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_add_approvers_added_by_id ON approval_additional_approvers (added_by_id)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_add_approvers_approval_status ON approval_additional_approvers (approval_id, status)`)
+
return nil
}
diff --git a/core/db/db_migration/tables/approval_additional_observer.go b/core/db/db_migration/tables/approval_additional_observer.go
index 7939b91..2cbf238 100644
--- a/core/db/db_migration/tables/approval_additional_observer.go
+++ b/core/db/db_migration/tables/approval_additional_observer.go
@@ -15,12 +15,10 @@ func ApprovalAdditionalObserverTableMigrate(db *gorm.DB) error {
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 'Внутренний уникальный идентификатор записи';
@@ -30,5 +28,10 @@ func ApprovalAdditionalObserverTableMigrate(db *gorm.DB) error {
COMMENT ON COLUMN "approval_additional_observers".created_at IS 'Дата и время создания записи';
`)
}
+
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_add_observers_approval_id ON approval_additional_observers (approval_id)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_add_observers_user_id ON approval_additional_observers (user_id)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_add_observers_added_by_id ON approval_additional_observers (added_by_id)`)
+
return nil
}
diff --git a/core/db/db_migration/tables/approval_comment.go b/core/db/db_migration/tables/approval_comment.go
index 83785a2..0235fa2 100644
--- a/core/db/db_migration/tables/approval_comment.go
+++ b/core/db/db_migration/tables/approval_comment.go
@@ -28,5 +28,10 @@ func ApprovalCommentsTableMigrate(db *gorm.DB) error {
COMMENT ON COLUMN "approval_comments".updated_at IS 'Дата последнего изменения комментария';
`)
}
+
+ // 🚀 Композит покрывает типичный запрос "комментарии заявки в хронологическом порядке"
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_comments_approval_id_created_at ON approval_comments (approval_id, created_at)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_comments_user_id ON approval_comments (user_id)`)
+
return nil
}
diff --git a/core/db/db_migration/tables/approval_delegation.go b/core/db/db_migration/tables/approval_delegation.go
index 80a1cdd..f69a974 100644
--- a/core/db/db_migration/tables/approval_delegation.go
+++ b/core/db/db_migration/tables/approval_delegation.go
@@ -15,12 +15,10 @@ func ApprovalDelegationTableMigrate(db *gorm.DB) error {
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 'Внутренний уникальный идентификатор записи делегирования';
@@ -35,5 +33,13 @@ func ApprovalDelegationTableMigrate(db *gorm.DB) error {
COMMENT ON COLUMN "approval_delegations".updated_at IS 'Дата и время последнего изменения записи';
`)
}
+
+ // 🚀 Композит под самый вероятный запрос: "активные делегирования делегата по теме, ещё не истёкшие"
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_delegations_delegator_id ON approval_delegations (delegator_id)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_delegations_delegate_id ON approval_delegations (delegate_id)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_delegations_topic_id ON approval_delegations (topic_id)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_delegations_active_valid_until ON approval_delegations (is_active, valid_until) WHERE is_active = true`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_delegations_delegator_topic_active ON approval_delegations (delegator_id, topic_id) WHERE is_active = true`)
+
return nil
}
diff --git a/core/db/db_migration/tables/approval_files.go b/core/db/db_migration/tables/approval_files.go
index b39cbdc..44a6d0f 100644
--- a/core/db/db_migration/tables/approval_files.go
+++ b/core/db/db_migration/tables/approval_files.go
@@ -26,5 +26,9 @@ func ApprovalsFilesTableMigrate(db *gorm.DB) error {
COMMENT ON COLUMN "approval_files".created_at IS 'Дата создания файла';
`)
}
+
+ // 🚀 Ключевой индекс под GetFilesByApprovalIDsDB (батч IN по approval_id)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_files_approval_id ON approval_files (approval_id)`)
+
return nil
}
diff --git a/core/db/db_migration/tables/approval_flow_node.go b/core/db/db_migration/tables/approval_flow_node.go
new file mode 100644
index 0000000..63356da
--- /dev/null
+++ b/core/db/db_migration/tables/approval_flow_node.go
@@ -0,0 +1,52 @@
+package tablesmigration
+
+import (
+ "gorm.io/gorm"
+ "time"
+)
+
+// ApprovalFlowNodesTableMigrate создаёт таблицу узлов дерева навигации
+func ApprovalFlowNodesTableMigrate(db *gorm.DB) error {
+ hasTable := db.Migrator().HasTable(&LocalApprovalFlowNodeProvider{})
+
+ if err := db.AutoMigrate(&LocalApprovalFlowNodeProvider{}); err != nil {
+ return err
+ }
+
+ if !hasTable {
+ time.Sleep(5 * time.Second)
+
+ // Foreign key на approval_topics
+ db.Exec(`ALTER TABLE approval_flow_nodes ADD CONSTRAINT fk_approval_flow_nodes_topic_id FOREIGN KEY (topic_id) REFERENCES approval_topics(id) ON DELETE CASCADE ON UPDATE CASCADE`)
+
+ // Самореференсный foreign key (parent_id -> id)
+ db.Exec(`ALTER TABLE approval_flow_nodes ADD CONSTRAINT fk_approval_flow_nodes_parent_id FOREIGN KEY (parent_id) REFERENCES approval_flow_nodes(id) ON DELETE CASCADE ON UPDATE CASCADE`)
+
+ // Уникальный индекс (topic_id, key) — чтобы ключи узлов были уникальны в рамках одной темы
+ db.Exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_flow_nodes_topic_key ON approval_flow_nodes(topic_id, key)`)
+
+ // Комментарии
+ execComments(db, `
+ COMMENT ON TABLE "approval_flow_nodes" IS 'Узлы дерева навигации темы согласования: описывают структуру кнопок, шагов ввода и мультиселекта для динамического построения флоу';
+ COMMENT ON COLUMN "approval_flow_nodes".id IS 'Внутренний уникальный идентификатор узла';
+ COMMENT ON COLUMN "approval_flow_nodes".topic_id IS 'ID темы согласования, к которой принадлежит узел (ссылка на approval_topics.id)';
+ COMMENT ON COLUMN "approval_flow_nodes".parent_id IS 'ID родительского узла (ссылка на approval_flow_nodes.id). NULL для корневого узла';
+ COMMENT ON COLUMN "approval_flow_nodes".key IS 'Уникальный ключ узла в рамках темы (используется для навигации и идентификации)';
+ COMMENT ON COLUMN "approval_flow_nodes".label IS 'Отображаемое название узла (текст на кнопке)';
+ COMMENT ON COLUMN "approval_flow_nodes".data_key IS 'Ключ в map collected, куда сохраняется значение при выборе этого узла';
+ COMMENT ON COLUMN "approval_flow_nodes".data_value IS 'Значение, сохраняемое в collected[data_key] при выборе этого узла';
+ COMMENT ON COLUMN "approval_flow_nodes".is_input IS 'Флаг: является ли узел шагом текстового ввода';
+ COMMENT ON COLUMN "approval_flow_nodes".input_key IS 'Ключ в collected, куда сохраняется введённый пользователем текст';
+ COMMENT ON COLUMN "approval_flow_nodes".input_hint IS 'Подсказка/шаблон для пользователя при текстовом вводе';
+ COMMENT ON COLUMN "approval_flow_nodes".is_multi_select IS 'Флаг: является ли узел узлом мультиселекта (выбор нескольких значений)';
+ COMMENT ON COLUMN "approval_flow_nodes".multi_select_key IS 'Ключ в collected, куда сохраняется результат мультиселекта (через запятую)';
+ COMMENT ON COLUMN "approval_flow_nodes".multi_select_value IS 'Значение этого варианта в мультиселекте';
+ COMMENT ON COLUMN "approval_flow_nodes".topic_code IS 'Код темы для проверки прав доступа (если задан — кнопка показывается только при наличии права create на эту тему)';
+ COMMENT ON COLUMN "approval_flow_nodes".sort_order IS 'Порядок сортировки узла среди братьев (0, 1, 2, ...)';
+ COMMENT ON COLUMN "approval_flow_nodes".created_at IS 'Дата и время создания узла';
+ COMMENT ON COLUMN "approval_flow_nodes".updated_at IS 'Дата и время последнего изменения узла';
+ `)
+ }
+
+ return nil
+}
diff --git a/core/db/db_migration/tables/approval_revocation_request.go b/core/db/db_migration/tables/approval_revocation_request.go
new file mode 100644
index 0000000..730972f
--- /dev/null
+++ b/core/db/db_migration/tables/approval_revocation_request.go
@@ -0,0 +1,77 @@
+package tablesmigration
+
+import (
+ "gorm.io/gorm"
+ "time"
+)
+
+type LocalApprovalRevocationRequestProvider struct {
+ ID uint64 `gorm:"column:id;primaryKey;autoIncrement"`
+ ApprovalID uint64 `gorm:"column:approval_id;not null"`
+ RequestedByID uint64 `gorm:"column:requested_by_id;not null"`
+ Reason *string `gorm:"column:reason;type:text"`
+ Status string `gorm:"column:status;type:text;not null;default:'pending'"`
+ CreatedAt time.Time `gorm:"column:created_at;default:CURRENT_TIMESTAMP"`
+ UpdatedAt time.Time `gorm:"column:updated_at;default:CURRENT_TIMESTAMP"`
+}
+
+func (LocalApprovalRevocationRequestProvider) TableName() string {
+ return "approval_revocation_requests"
+}
+
+type LocalApprovalRevocationApproverProvider struct {
+ ID uint64 `gorm:"column:id;primaryKey;autoIncrement"`
+ RevocationRequestID uint64 `gorm:"column:revocation_request_id;not null"`
+ ApproverID uint64 `gorm:"column:approver_id;not null"`
+ Status string `gorm:"column:status;type:text;not null;default:'pending'"`
+ Comment *string `gorm:"column:comment;type:text"`
+ ActedAt *time.Time `gorm:"column:acted_at"`
+ CreatedAt time.Time `gorm:"column:created_at;default:CURRENT_TIMESTAMP"`
+}
+
+func (LocalApprovalRevocationApproverProvider) TableName() string {
+ return "approval_revocation_approvers"
+}
+
+func ApprovalRevocationTablesMigrate(db *gorm.DB) error {
+ hasReqTable := db.Migrator().HasTable(&LocalApprovalRevocationRequestProvider{})
+ hasApprTable := db.Migrator().HasTable(&LocalApprovalRevocationApproverProvider{})
+
+ if err := db.AutoMigrate(&LocalApprovalRevocationRequestProvider{}); err != nil {
+ return err
+ }
+ if err := db.AutoMigrate(&LocalApprovalRevocationApproverProvider{}); err != nil {
+ return err
+ }
+
+ if !hasReqTable || !hasApprTable {
+ time.Sleep(5 * time.Second)
+
+ db.Exec(`ALTER TABLE approval_revocation_requests ADD CONSTRAINT fk_arr_approval_id FOREIGN KEY (approval_id) REFERENCES approvals(id) ON DELETE CASCADE ON UPDATE CASCADE`)
+ db.Exec(`ALTER TABLE approval_revocation_requests ADD CONSTRAINT fk_arr_requested_by_id FOREIGN KEY (requested_by_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
+
+ db.Exec(`ALTER TABLE approval_revocation_approvers ADD CONSTRAINT fk_ara_request_id FOREIGN KEY (revocation_request_id) REFERENCES approval_revocation_requests(id) ON DELETE CASCADE ON UPDATE CASCADE`)
+ db.Exec(`ALTER TABLE approval_revocation_approvers ADD CONSTRAINT fk_ara_approver_id FOREIGN KEY (approver_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
+
+ execComments(db, `
+ COMMENT ON TABLE "approval_revocation_requests" IS 'Запрос инициатора на отзыв уже согласованной заявки, требующий согласия всех согласующих';
+ COMMENT ON COLUMN "approval_revocation_requests".approval_id IS 'Заявка, которую пытаются отозвать';
+ COMMENT ON COLUMN "approval_revocation_requests".requested_by_id IS 'Инициатор, запросивший отзыв';
+ COMMENT ON COLUMN "approval_revocation_requests".reason IS 'Причина отзыва, указанная инициатором';
+ COMMENT ON COLUMN "approval_revocation_requests".status IS 'pending | approved | rejected | cancelled';
+
+ COMMENT ON TABLE "approval_revocation_approvers" IS 'Согласующие, чьё согласие требуется для отзыва уже согласованной заявки';
+ COMMENT ON COLUMN "approval_revocation_approvers".revocation_request_id IS 'Запрос на отзыв';
+ COMMENT ON COLUMN "approval_revocation_approvers".approver_id IS 'Согласующий, участвовавший в первоначальном согласовании';
+ COMMENT ON COLUMN "approval_revocation_approvers".status IS 'pending | approved | rejected';
+ `)
+ }
+
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_arr_approval_id ON approval_revocation_requests (approval_id)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_arr_status ON approval_revocation_requests (status)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_ara_request_id ON approval_revocation_approvers (revocation_request_id)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_ara_approver_id ON approval_revocation_approvers (approver_id)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_ara_request_status ON approval_revocation_approvers (revocation_request_id, status)`)
+
+ return nil
+}
diff --git a/core/db/db_migration/tables/approval_steps.go b/core/db/db_migration/tables/approval_steps.go
index 0fc96ff..2e8288b 100644
--- a/core/db/db_migration/tables/approval_steps.go
+++ b/core/db/db_migration/tables/approval_steps.go
@@ -33,5 +33,12 @@ func ApprovalStepsTableMigrate(db *gorm.DB) error {
COMMENT ON COLUMN "approval_steps".updated_at IS 'Дата последнего обновления шага';
`)
}
+
+ // 🚀 Композит покрывает GetApprovalStepsByApprovalIDsDB (IN approval_id + ORDER BY step_order)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_steps_approval_id_step_order ON approval_steps (approval_id, step_order)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_steps_approver_id ON approval_steps (approver_id)`)
+ // Под "мои pending-согласования"
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_steps_approver_status ON approval_steps (approver_id, status)`)
+
return nil
}
diff --git a/core/db/db_migration/tables/approval_task.go b/core/db/db_migration/tables/approval_task.go
index c3720bb..24dad35 100644
--- a/core/db/db_migration/tables/approval_task.go
+++ b/core/db/db_migration/tables/approval_task.go
@@ -15,11 +15,9 @@ func ApprovalTasksTableMigrate(db *gorm.DB) error {
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 задачи';
@@ -33,5 +31,9 @@ func ApprovalTasksTableMigrate(db *gorm.DB) error {
`)
}
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_tasks_approval_id ON approval_tasks (approval_id)`)
+ // Под "мои задачи исполнителя, отфильтрованные по статусу"
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_tasks_executor_status ON approval_tasks (executor_id, status)`)
+
return nil
}
diff --git a/core/db/db_migration/tables/approval_task_transfer.go b/core/db/db_migration/tables/approval_task_transfer.go
new file mode 100644
index 0000000..72db76f
--- /dev/null
+++ b/core/db/db_migration/tables/approval_task_transfer.go
@@ -0,0 +1,38 @@
+package tablesmigration
+
+import (
+ "gorm.io/gorm"
+ "time"
+)
+
+func ApprovalTaskTransfersTableMigrate(db *gorm.DB) error {
+ hasTable := db.Migrator().HasTable(&LocalApprovalTaskTransferProvider{})
+
+ if err := db.AutoMigrate(&LocalApprovalTaskTransferProvider{}); err != nil {
+ return err
+ }
+
+ if !hasTable {
+ time.Sleep(5 * time.Second)
+
+ db.Exec(`ALTER TABLE approval_task_transfers ADD CONSTRAINT fk_att_task_id FOREIGN KEY (task_id) REFERENCES approval_tasks(id) ON DELETE CASCADE ON UPDATE CASCADE`)
+ db.Exec(`ALTER TABLE approval_task_transfers ADD CONSTRAINT fk_att_from_executor_id FOREIGN KEY (from_executor_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
+ db.Exec(`ALTER TABLE approval_task_transfers ADD CONSTRAINT fk_att_to_executor_id FOREIGN KEY (to_executor_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
+
+ execComments(db, `
+ COMMENT ON TABLE "approval_task_transfers" IS 'История запросов на передачу задач исполнения между пользователями';
+ COMMENT ON COLUMN "approval_task_transfers".task_id IS 'Передаваемая задача';
+ COMMENT ON COLUMN "approval_task_transfers".from_executor_id IS 'Исполнитель, инициировавший передачу';
+ COMMENT ON COLUMN "approval_task_transfers".to_executor_id IS 'Пользователь, которому предлагается принять задачу';
+ COMMENT ON COLUMN "approval_task_transfers".status IS 'Статус: pending | accepted | declined | cancelled';
+ COMMENT ON COLUMN "approval_task_transfers".responded_at IS 'Когда получатель ответил на запрос';
+ `)
+ }
+
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_att_task_id ON approval_task_transfers (task_id)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_att_to_executor_id ON approval_task_transfers (to_executor_id)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_att_status ON approval_task_transfers (status)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_att_task_status ON approval_task_transfers (task_id, status)`)
+
+ return nil
+}
diff --git a/core/db/db_migration/tables/approval_topic.go b/core/db/db_migration/tables/approval_topic.go
index 0ef0237..ad75602 100644
--- a/core/db/db_migration/tables/approval_topic.go
+++ b/core/db/db_migration/tables/approval_topic.go
@@ -33,5 +33,12 @@ func ApprovalTopicsTableMigrate(db *gorm.DB) error {
COMMENT ON COLUMN "approval_topics".updated_at IS 'Дата последнего обновления записи';
`)
}
+
+ // 🚀 code — уникальность/поиск при создании темы; category_id — под GetTopicsListHandler фильтр и enrich;
+ // композит category_id+is_active — под список активных тем категории (частый сценарий в боте)
+ db.Exec(`CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_approval_topics_code ON approval_topics (code)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_topics_category_id ON approval_topics (category_id)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_topics_category_active ON approval_topics (category_id, is_active)`)
+
return nil
}
diff --git a/core/db/db_migration/tables/approval_topic_category.go b/core/db/db_migration/tables/approval_topic_category.go
index 6bb154f..c8f6e3c 100644
--- a/core/db/db_migration/tables/approval_topic_category.go
+++ b/core/db/db_migration/tables/approval_topic_category.go
@@ -28,5 +28,10 @@ func ApprovalTopicCategoriesTableMigrate(db *gorm.DB) error {
COMMENT ON COLUMN "approval_topic_categories".updated_at IS 'Дата последнего обновления записи';
`)
}
+
+ // 🚀 code используется в GetApprovalTopicCategoryByCodeDB и в JOIN'ах GetObserversForApprovalDB/GetUserPermissionsDB
+ db.Exec(`CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_approval_topic_categories_code ON approval_topic_categories (code)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_topic_categories_active ON approval_topic_categories (is_active)`)
+
return nil
}
diff --git a/core/db/db_migration/tables/approval_topic_executor.go b/core/db/db_migration/tables/approval_topic_executor.go
index 2a2d799..2bc24b4 100644
--- a/core/db/db_migration/tables/approval_topic_executor.go
+++ b/core/db/db_migration/tables/approval_topic_executor.go
@@ -31,5 +31,14 @@ func ApprovalTopicExecutorsTableMigrate(db *gorm.DB) error {
COMMENT ON COLUMN "approval_topic_executor".updated_at IS 'Дата последнего обновления записи';
`)
}
+
+ // 🚀 Композит покрывает GetExecutorsByTopicIDDB (topic_id + is_active + ORDER BY step_order)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_topic_executor_topic_active_step ON approval_topic_executor (topic_id, is_active, step_order)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_topic_executor_user_id ON approval_topic_executor (user_id)`)
+ // Уникальность под проверку "исполнитель уже назначен на этот шаг" в CreateTopicExecutorHandler
+ db.Exec(`CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_approval_topic_executor_topic_user_step ON approval_topic_executor (topic_id, user_id, step_order)`)
+ // Под фильтрацию GetApprovalTopicExecutorListByCategoryDB (JOIN approval_topics ON t.category_id)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_topic_executor_id_step ON approval_topic_executor (id, step_order)`)
+
return nil
}
diff --git a/core/db/db_migration/tables/department.go b/core/db/db_migration/tables/department.go
index 1b22519..e10e42f 100644
--- a/core/db/db_migration/tables/department.go
+++ b/core/db/db_migration/tables/department.go
@@ -26,5 +26,9 @@ func DepartmentsTableMigrate(db *gorm.DB) error {
COMMENT ON COLUMN "departments".updated_at IS 'Дата последнего обновления записи';
`)
}
+
+ db.Exec(`CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_departments_code ON departments (code)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_departments_active ON departments (is_active)`)
+
return nil
}
diff --git a/core/db/db_migration/tables/directors_category_subscription.go b/core/db/db_migration/tables/directors_category_subscription.go
new file mode 100644
index 0000000..ccae5a9
--- /dev/null
+++ b/core/db/db_migration/tables/directors_category_subscription.go
@@ -0,0 +1,33 @@
+package tablesmigration
+
+import (
+ "gorm.io/gorm"
+ "time"
+)
+
+func DirectorNotificationSubscriptionsTableMigrate(db *gorm.DB) error {
+ hasTable := db.Migrator().HasTable(&LocalDirectorNotificationSubscriptionProvider{})
+
+ if err := db.AutoMigrate(&LocalDirectorNotificationSubscriptionProvider{}); err != nil {
+ return err
+ }
+
+ if !hasTable {
+ time.Sleep(5 * time.Second)
+
+ db.Exec(`ALTER TABLE director_notification_subscriptions ADD CONSTRAINT fk_dns_director_id FOREIGN KEY (director_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
+ db.Exec(`ALTER TABLE director_notification_subscriptions ADD CONSTRAINT fk_dns_category_id FOREIGN KEY (category_id) REFERENCES approval_topic_categories(id) ON DELETE CASCADE ON UPDATE CASCADE`)
+ db.Exec(`ALTER TABLE director_notification_subscriptions ADD CONSTRAINT uq_dns_director_category UNIQUE (director_id, category_id)`)
+
+ execComments(db, `
+ COMMENT ON TABLE "director_notification_subscriptions" IS 'Подписки директоров на уведомления по категориям тем согласования. Наличие строки = подписка включена, по умолчанию для всех категорий выключено';
+ COMMENT ON COLUMN "director_notification_subscriptions".director_id IS 'Директор, оформивший подписку';
+ COMMENT ON COLUMN "director_notification_subscriptions".category_id IS 'Категория тем, на которую подписан директор';
+ `)
+ }
+
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_dns_director_id ON director_notification_subscriptions (director_id)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_dns_category_id ON director_notification_subscriptions (category_id)`)
+
+ return nil
+}
diff --git a/core/db/db_migration/tables/monthly_orders.go b/core/db/db_migration/tables/monthly_orders.go
new file mode 100644
index 0000000..9a153bc
--- /dev/null
+++ b/core/db/db_migration/tables/monthly_orders.go
@@ -0,0 +1,51 @@
+package tablesmigration
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "gorm.io/gorm"
+ "time"
+)
+
+type LocalMonthlyOrderSetting typescore.MonthlyOrderSetting
+type LocalMonthlyOrderClient typescore.MonthlyOrderClient
+type LocalMonthlyOrderItem typescore.MonthlyOrderItem
+type LocalMonthlyOrderFile typescore.MonthlyOrderFile
+
+func (LocalMonthlyOrderSetting) TableName() string { return "monthly_order_settings" }
+func (LocalMonthlyOrderClient) TableName() string { return "monthly_order_clients" }
+func (LocalMonthlyOrderItem) TableName() string { return "monthly_order_items" }
+func (LocalMonthlyOrderFile) TableName() string { return "monthly_order_files" }
+
+func MonthlyOrdersTablesMigrate(db *gorm.DB) error {
+ tables := []interface{}{
+ &LocalMonthlyOrderSetting{},
+ &LocalMonthlyOrderClient{},
+ &LocalMonthlyOrderItem{},
+ &LocalMonthlyOrderFile{},
+ }
+
+ for _, table := range tables {
+ if err := db.AutoMigrate(table); err != nil {
+ return err
+ }
+ }
+
+ // Устанавливаем внешние ключи (Foreign Keys)
+ time.Sleep(2 * time.Second)
+
+ db.Exec(`ALTER TABLE monthly_order_clients ADD CONSTRAINT fk_moc_manager_id FOREIGN KEY (manager_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
+ db.Exec(`ALTER TABLE monthly_order_clients ADD CONSTRAINT fk_moc_approval_id FOREIGN KEY (approval_id) REFERENCES approvals(id) ON DELETE SET NULL ON UPDATE CASCADE`)
+
+ db.Exec(`ALTER TABLE monthly_order_items ADD CONSTRAINT fk_moi_order_client_id FOREIGN KEY (order_client_id) REFERENCES monthly_order_clients(id) ON DELETE CASCADE ON UPDATE CASCADE`)
+
+ db.Exec(`ALTER TABLE monthly_order_files ADD CONSTRAINT fk_mof_order_client_id FOREIGN KEY (order_client_id) REFERENCES monthly_order_clients(id) ON DELETE CASCADE ON UPDATE CASCADE`)
+
+ // Индексы для быстрого поиска
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_moc_manager_month_year ON monthly_order_clients (manager_id, month, year)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_moi_order_client_id ON monthly_order_items (order_client_id)`)
+
+ db.Exec(`CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_moc_unique_client_order ON monthly_order_clients (manager_id, month, year, client_name)`)
+ db.Exec(`CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_mos_unique_settings ON monthly_order_settings (month, year)`)
+
+ return nil
+}
diff --git a/core/db/db_migration/tables/notifications.go b/core/db/db_migration/tables/notifications.go
new file mode 100644
index 0000000..7a955b1
--- /dev/null
+++ b/core/db/db_migration/tables/notifications.go
@@ -0,0 +1,66 @@
+package tablesmigration
+
+import (
+ "gorm.io/gorm"
+ "time"
+)
+
+func NotificationsTableMigrate(db *gorm.DB) error {
+ hasNotificationsTable := db.Migrator().HasTable(&LocalNotificationProvider{})
+ hasRecipientsTable := db.Migrator().HasTable(&LocalNotificationRecipientProvider{})
+
+ if err := db.AutoMigrate(&LocalNotificationProvider{}); err != nil {
+ return err
+ }
+ if err := db.AutoMigrate(&LocalNotificationRecipientProvider{}); err != nil {
+ return err
+ }
+
+ if !hasNotificationsTable || !hasRecipientsTable {
+ time.Sleep(5 * time.Second)
+
+ db.Exec(`ALTER TABLE notifications ADD CONSTRAINT fk_notifications_created_by_id FOREIGN KEY (created_by_id) REFERENCES users(id) ON DELETE SET NULL ON UPDATE CASCADE`)
+
+ db.Exec(`ALTER TABLE notification_recipients ADD CONSTRAINT fk_notification_recipients_notification_id FOREIGN KEY (notification_id) REFERENCES notifications(id) ON DELETE CASCADE ON UPDATE CASCADE`)
+ db.Exec(`ALTER TABLE notification_recipients ADD CONSTRAINT fk_notification_recipients_user_id FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
+
+ execComments(db, `
+ COMMENT ON TABLE "notifications" IS 'Уведомления/рассылки, отправляемые администратором через Telegram-бота';
+ COMMENT ON COLUMN "notifications".id IS 'Внутренний ID уведомления';
+ COMMENT ON COLUMN "notifications".title IS 'Заголовок рассылки (для админки, не отправляется в Telegram)';
+ COMMENT ON COLUMN "notifications".message_html IS 'Текст сообщения в HTML-разметке, совместимой с Telegram ParseMode=HTML';
+ COMMENT ON COLUMN "notifications".photo_base64 IS 'Прикреплённое фото в формате base64, опционально';
+ COMMENT ON COLUMN "notifications".photo_file_name IS 'Оригинальное имя прикреплённого файла фото';
+ COMMENT ON COLUMN "notifications".target_filters IS 'Критерии выбора получателей (user_ids, role_ids, role_type_flags, department_ids) в формате JSON, для аудита';
+ COMMENT ON COLUMN "notifications".status IS 'Статус рассылки: pending | sending | completed | failed';
+ COMMENT ON COLUMN "notifications".total_count IS 'Общее число подобранных получателей';
+ COMMENT ON COLUMN "notifications".sent_count IS 'Число успешно доставленных сообщений';
+ COMMENT ON COLUMN "notifications".failed_count IS 'Число сообщений с ошибкой доставки';
+ COMMENT ON COLUMN "notifications".created_by_id IS 'Администратор, инициировавший рассылку';
+ COMMENT ON COLUMN "notifications".created_at IS 'Дата создания рассылки';
+ COMMENT ON COLUMN "notifications".updated_at IS 'Дата последнего изменения статуса рассылки';
+ COMMENT ON COLUMN "notifications".sent_at IS 'Дата фактической отправки рассылки получателям';
+
+ COMMENT ON TABLE "notification_recipients" IS 'История доставки уведомления конкретным пользователям';
+ COMMENT ON COLUMN "notification_recipients".id IS 'Внутренний ID записи истории доставки';
+ COMMENT ON COLUMN "notification_recipients".notification_id IS 'Уведомление, к которому относится доставка';
+ COMMENT ON COLUMN "notification_recipients".user_id IS 'Получатель уведомления';
+ COMMENT ON COLUMN "notification_recipients".status IS 'Статус доставки: pending | sent | failed';
+ COMMENT ON COLUMN "notification_recipients".error_message IS 'Текст ошибки при неудачной отправке';
+ COMMENT ON COLUMN "notification_recipients".telegram_message_id IS 'ID отправленного сообщения в Telegram, если доставка успешна';
+ COMMENT ON COLUMN "notification_recipients".sent_at IS 'Дата и время фактической отправки этому получателю';
+ COMMENT ON COLUMN "notification_recipients".created_at IS 'Дата создания записи (постановка в очередь на отправку)';
+ `)
+ }
+
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_notifications_status ON notifications (status)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_notifications_created_at ON notifications (created_at DESC)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_notifications_created_by_id ON notifications (created_by_id)`)
+
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_notification_recipients_notification_id ON notification_recipients (notification_id)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_notification_recipients_user_id ON notification_recipients (user_id)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_notification_recipients_status ON notification_recipients (status)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_notification_recipients_notification_status ON notification_recipients (notification_id, status)`)
+
+ return nil
+}
diff --git a/core/db/db_migration/tables/permission.go b/core/db/db_migration/tables/permission.go
index d1e0119..79a762a 100644
--- a/core/db/db_migration/tables/permission.go
+++ b/core/db/db_migration/tables/permission.go
@@ -31,5 +31,16 @@ func PermissionsTableMigrate(db *gorm.DB) error {
COMMENT ON COLUMN "permissions".updated_at IS 'Дата последнего обновления записи';
`)
}
+
+ // 🚀 role_id — под GetUserPermissionsDB JOIN с user_roles; композит role_id+action — под UserCanCreateTopicDB;
+ // topic_id/topic_category_id — под enrichPermissionsBatch и JOIN'ы наблюдателей
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_permissions_role_id ON permissions (role_id)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_permissions_role_id_action ON permissions (role_id, action)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_permissions_topic_id ON permissions (topic_id)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_permissions_topic_category_id ON permissions (topic_category_id)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_permissions_action ON permissions (action)`)
+ // Под GetObserversForCategoryDB / GetObserversForApprovalDB: action='observe' + topic_category_id
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_permissions_action_category ON permissions (action, topic_category_id)`)
+
return nil
}
diff --git a/core/db/db_migration/tables/providers.go b/core/db/db_migration/tables/providers.go
index 29b3b6f..aec5b6f 100644
--- a/core/db/db_migration/tables/providers.go
+++ b/core/db/db_migration/tables/providers.go
@@ -24,7 +24,18 @@ type ApprovalCommentsProvider typescore.ApprovalComment
type LocalSuggestionProvider typescore.Suggestion
type LocalSuggestionMessagesProvider typescore.SuggestionMessage
type LocalApprovalTopicExecutorProvider typescore.ApprovalTopicExecutor
+type LocalNotificationProvider typescore.Notification
+type LocalNotificationRecipientProvider typescore.NotificationRecipient
+type LocalDirectorNotificationSubscriptionProvider typescore.DirectorNotificationSubscription
+type LocalApprovalTaskTransferProvider typescore.ApprovalTaskTransfer
+type LocalApprovalFlowNodeProvider typescore.ApprovalFlowNode
+func (LocalApprovalTaskTransferProvider) TableName() string {
+ return dbcoretablenames.TableNameApprovalTaskTransfers.ToString()
+}
+func (LocalDirectorNotificationSubscriptionProvider) TableName() string {
+ return dbcoretablenames.TableNameDirectorNotificationSubscriptions.ToString()
+}
func (LocalUserProvider) TableName() string {
return dbcoretablenames.TableNameUsers.ToString()
}
@@ -82,3 +93,12 @@ func (ApprovalAdditionalObserver) TableName() string {
func (LocalApprovalTopicExecutorProvider) TableName() string {
return dbcoretablenames.TableNameApprovalTopicExecutor.ToString()
}
+func (LocalNotificationProvider) TableName() string {
+ return dbcoretablenames.TableNameNotifications.ToString()
+}
+func (LocalNotificationRecipientProvider) TableName() string {
+ return dbcoretablenames.TableNameNotificationsRecipients.ToString()
+}
+func (LocalApprovalFlowNodeProvider) TableName() string {
+ return dbcoretablenames.TableNameApprovalFlowNodes.ToString()
+}
diff --git a/core/db/db_migration/tables/role.go b/core/db/db_migration/tables/role.go
index eaf0897..b58b494 100644
--- a/core/db/db_migration/tables/role.go
+++ b/core/db/db_migration/tables/role.go
@@ -28,5 +28,15 @@ func RolesTableMigrate(db *gorm.DB) error {
COMMENT ON COLUMN "roles".updated_at IS 'Дата последнего обновления записи';
`)
}
+
+ // 🚀 code — под GetUsersByRoleCodeDB; флаги is_director/is_approver/is_observer используются
+ // как условия в JOIN'ах GetDirectorsDB/IsDirectorDB/IsApproverDB/IsObserverDB/GetObserversForCategoryDB —
+ // частичные индексы дают максимальную выборочность, т.к. флаг true встречается редко
+ db.Exec(`CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_roles_code ON roles (code)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_roles_is_director ON roles (id) WHERE is_director = true`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_roles_is_approver ON roles (id) WHERE is_approver = true`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_roles_is_observer ON roles (id) WHERE is_observer = true`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_roles_is_default ON roles (id) WHERE is_default = true`)
+
return nil
}
diff --git a/core/db/db_migration/tables/sms_log.go b/core/db/db_migration/tables/sms_log.go
new file mode 100644
index 0000000..6b106c4
--- /dev/null
+++ b/core/db/db_migration/tables/sms_log.go
@@ -0,0 +1,31 @@
+package tablesmigration
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "gorm.io/gorm"
+ "time"
+)
+
+type LocalSmsLogProvider typescore.SmsLog
+
+func (LocalSmsLogProvider) TableName() string {
+ return "sms_logs"
+}
+
+func SmsLogsTableMigrate(db *gorm.DB) error {
+ hasTable := db.Migrator().HasTable(&LocalSmsLogProvider{})
+
+ err := db.AutoMigrate(&LocalSmsLogProvider{})
+ if err != nil {
+ return err
+ }
+
+ if !hasTable {
+ time.Sleep(5 * time.Second)
+ db.Exec(`
+ COMMENT ON TABLE sms_logs IS 'Таблица для хранения логов SMS из внешней телефонии';
+ COMMENT ON COLUMN sms_logs.direction IS '0 - входящее, 1 - исходящее';
+ `)
+ }
+ return nil
+}
diff --git a/core/db/db_migration/tables/suggestion_messages.go b/core/db/db_migration/tables/suggestion_messages.go
index f7bac16..5d53451 100644
--- a/core/db/db_migration/tables/suggestion_messages.go
+++ b/core/db/db_migration/tables/suggestion_messages.go
@@ -30,5 +30,9 @@ func SuggestionMessagesTableMigrate(db *gorm.DB) error {
`)
}
+ // 🚀 Композит покрывает "переписка по предложению в хронологическом порядке"
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_suggestion_messages_suggestion_id_created_at ON suggestion_messages (suggestion_id, created_at)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_suggestion_messages_user_id ON suggestion_messages (user_id)`)
+
return nil
}
diff --git a/core/db/db_migration/tables/suggestions.go b/core/db/db_migration/tables/suggestions.go
index fadb44d..4b90596 100644
--- a/core/db/db_migration/tables/suggestions.go
+++ b/core/db/db_migration/tables/suggestions.go
@@ -30,5 +30,9 @@ func SuggestionsTableMigrate(db *gorm.DB) error {
`)
}
+ // 🚀 Композиты под "мои открытые предложения" / "предложения, адресованные директору"
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_suggestions_initiator_status ON suggestions (initiator_id, status)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_suggestions_director_status ON suggestions (director_id, status)`)
+
return nil
}
diff --git a/core/db/db_migration/tables/task_delegation.go b/core/db/db_migration/tables/task_delegation.go
new file mode 100644
index 0000000..7c07f5b
--- /dev/null
+++ b/core/db/db_migration/tables/task_delegation.go
@@ -0,0 +1,56 @@
+package tablesmigration
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "gorm.io/gorm"
+ "time"
+)
+
+// Вспомогательная структура для автомиграции, чтобы не тянуть зависимости
+type LocalTaskDelegation typescore.TaskDelegation
+
+func (LocalTaskDelegation) TableName() string {
+ return "task_delegations"
+}
+
+func TaskDelegationsTableMigrate(db *gorm.DB) error {
+ hasTable := db.Migrator().HasTable(&LocalTaskDelegation{})
+
+ if err := db.AutoMigrate(&LocalTaskDelegation{}); err != nil {
+ return err
+ }
+
+ if !hasTable {
+ time.Sleep(5 * time.Second)
+
+ // Внешние ключи для связи с таблицей пользователей
+ db.Exec(`ALTER TABLE task_delegations ADD CONSTRAINT fk_task_delegator FOREIGN KEY (delegator_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
+ db.Exec(`ALTER TABLE task_delegations ADD CONSTRAINT fk_task_delegate FOREIGN KEY (delegate_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
+ db.Exec(`ALTER TABLE task_delegations ADD CONSTRAINT fk_task_category FOREIGN KEY (category_id) REFERENCES approval_topic_categories(id) ON DELETE CASCADE ON UPDATE CASCADE`)
+ db.Exec(`ALTER TABLE task_delegations ADD CONSTRAINT fk_task_topic FOREIGN KEY (topic_id) REFERENCES approval_topics(id) ON DELETE CASCADE ON UPDATE CASCADE`)
+
+ execComments(db, `
+ COMMENT ON TABLE "task_delegations" IS 'Делегирование прав на задачи';
+ COMMENT ON COLUMN "task_delegations".id IS 'Внутренний ID записи делегирования';
+ COMMENT ON COLUMN "task_delegations".delegator_id IS 'ID пользователя, который передает свои задачи (делегатор)';
+ COMMENT ON COLUMN "task_delegations".delegate_id IS 'ID пользователя, которому передаются задачи (делегат)';
+ COMMENT ON COLUMN "task_delegations".valid_until IS 'Дата и время окончания делегирования';
+ COMMENT ON COLUMN "task_delegations".is_active IS 'Активно ли данное делегирование';
+ COMMENT ON COLUMN "task_delegations".notified_day IS 'Отправлено ли уведомление за день до окончания';
+ COMMENT ON COLUMN "task_delegations".notified_2h IS 'Отправлено ли уведомление за 2 часа до окончания';
+ COMMENT ON COLUMN "task_delegations".created_at IS 'Дата создания записи';
+ COMMENT ON COLUMN "task_delegations".updated_at IS 'Дата последнего обновления записи';
+ `)
+ }
+
+ // 🚀 Индексы для быстрого поиска активных делегирований по делегатору
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_task_delegations_delegator_active ON task_delegations (delegator_id, is_active)`)
+
+ // Индекс для поиска активных делегирований по делегату (чтобы делегат мог видеть переданные ему права)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_task_delegations_delegate_active ON task_delegations (delegate_id, is_active)`)
+
+ // Индекс для крона/воркеров, которые будут проверять истекшие сроки и рассылать уведомления
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_task_delegations_valid_until_active ON task_delegations (valid_until, is_active)`)
+
+ return nil
+}
diff --git a/core/db/db_migration/tables/user.go b/core/db/db_migration/tables/user.go
index e7e455a..c1656f6 100644
--- a/core/db/db_migration/tables/user.go
+++ b/core/db/db_migration/tables/user.go
@@ -31,5 +31,20 @@ func UsersTableMigrate(db *gorm.DB) error {
COMMENT ON COLUMN "users".updated_at IS 'Дата последнего обновления записи';
`)
}
+
+ // 🚀 telegram_id — под GetUserByTelegramIDDB (уникальный лукап при каждом сообщении в бота);
+ // department_id — под фильтр users и JOIN'ы в enrichUsersBatch;
+ // pg_trgm-индекс под LIKE-поиск по full_name (GetUserListHandler search)
+ db.Exec(`CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_users_telegram_id ON users (telegram_id)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_users_department_id ON users (department_id)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_users_is_blocked ON users (is_blocked)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_users_is_fired ON users (is_fired)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_users_created_at ON users (created_at DESC)`)
+ // Композит под самый частый вызов фильтра списка: не заблокирован + не уволен
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_users_blocked_fired ON users (is_blocked, is_fired)`)
+ // Требует расширения pg_trgm: CREATE EXTENSION IF NOT EXISTS pg_trgm;
+ db.Exec(`CREATE EXTENSION IF NOT EXISTS pg_trgm`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_users_full_name_trgm ON users USING gin (full_name gin_trgm_ops)`)
+
return nil
}
diff --git a/core/db/db_migration/tables/user_hierarchy.go b/core/db/db_migration/tables/user_hierarchy.go
index 74eb664..0d8f06d 100644
--- a/core/db/db_migration/tables/user_hierarchy.go
+++ b/core/db/db_migration/tables/user_hierarchy.go
@@ -30,5 +30,11 @@ func UserHierarchyTableMigrate(db *gorm.DB) error {
COMMENT ON COLUMN "user_hierarchy".updated_at IS 'Дата последнего обновления записи';
`)
}
+
+ // 🚀 Композит покрывает основной сценарий: "цепочка согласующих подчинённого в отделе по приоритету"
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_user_hierarchy_subordinate_dept_priority ON user_hierarchy (subordinate_id, department_id, priority)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_user_hierarchy_approver_id ON user_hierarchy (approver_id)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_user_hierarchy_department_id ON user_hierarchy (department_id)`)
+
return nil
}
diff --git a/core/db/db_migration/tables/user_role.go b/core/db/db_migration/tables/user_role.go
index 428019b..531298b 100644
--- a/core/db/db_migration/tables/user_role.go
+++ b/core/db/db_migration/tables/user_role.go
@@ -27,5 +27,13 @@ func UserRolesTableMigrate(db *gorm.DB) error {
COMMENT ON COLUMN "user_roles".updated_at IS 'Дата последнего обновления записи';
`)
}
+
+ // 🚀 Индексы: user_id — под GetUserRolesByUserIDsDB/DeleteUserRolesByUserIDDB,
+ // role_id — под GetPermissionsByRoleIDHandler JOIN'ы,
+ // уникальный композит — защита от дублей роли у пользователя + быстрый lookup в AssignUserRoleHandler
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_user_roles_user_id ON user_roles (user_id)`)
+ db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_user_roles_role_id ON user_roles (role_id)`)
+ db.Exec(`CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_user_roles_user_role ON user_roles (user_id, role_id)`)
+
return nil
}
diff --git a/core/db/methods/admin.go b/core/db/methods/admin.go
index 7f753ee..af8ed90 100644
--- a/core/db/methods/admin.go
+++ b/core/db/methods/admin.go
@@ -9,6 +9,7 @@ import (
"errors"
"fmt"
"strings"
+ "time"
"github.com/Masterminds/squirrel"
"github.com/jackc/pgx/v5"
@@ -87,6 +88,8 @@ func (u *AdminDB) CreateAdminDB(tx pgx.Tx, adminObj *typescore.Admin, returnObj
ctx, cancel := context.WithTimeout(context.Background(), variables.ContextTimeoutBase)
defer cancel()
+ now := time.Now().UTC()
+ adminObj.CreatedAt = &now
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Insert(dbcoretablenames.TableNameAdmin.ToString())
diff --git a/core/db/methods/admin_action_logs.go b/core/db/methods/admin_action_logs.go
new file mode 100644
index 0000000..eb245fb
--- /dev/null
+++ b/core/db/methods/admin_action_logs.go
@@ -0,0 +1,195 @@
+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"
+ "time"
+
+ "github.com/Masterminds/squirrel"
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgxpool"
+ "github.com/sirupsen/logrus"
+)
+
+type AdminActionLogDB struct {
+ pool *pgxpool.Pool
+}
+
+func NewAdminActionLogDB(pool *pgxpool.Pool) *AdminActionLogDB {
+ return &AdminActionLogDB{pool: pool}
+}
+
+type AdminActionLogDBI interface {
+ GetAdminActionLogsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.AdminActionLog, uint64, error)
+ CreateAdminActionLogDB(ctx context.Context, tx pgx.Tx, obj *typescore.AdminActionLog, returnObj ...bool) (*typescore.AdminActionLog, pgx.Tx, error)
+ DeleteAdminActionLogDB(ctx context.Context, params *typescore.AdminActionLog) error
+ GetAdminActionLogByIDDB(ctx context.Context, id uint64) (*typescore.AdminActionLog, error)
+ GetAdminActionLogsFilteredDB(ctx context.Context, filter typescore.AdminActionLogFilter, offset, limit *uint64) ([]*typescore.AdminActionLog, uint64, error)
+}
+
+func (u *AdminActionLogDB) GetAdminActionLogsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.AdminActionLog, uint64, error) {
+ fields := dbutils.GetStructFieldsDB(&typescore.AdminActionLog{}, dbcoretablenames.TableNameAdminActionLogs.ToString())
+ selectFields := append(fields, "COUNT(*) OVER() AS total_count")
+
+ options, filter, err := dbutils.GetOptionsDB[typescore.AdminActionLog](opts...)
+ if err != nil {
+ return nil, 0, err
+ }
+
+ query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameAdminActionLogs.ToString(), selectFields)
+ query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
+ query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameAdminActionLogs.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 logs []*typescore.AdminActionLog
+ var totalCount uint64
+ for rows.Next() {
+ entry := &typescore.AdminActionLog{}
+ if err := dbutils.ScanRowsToStructRows(rows, entry, &totalCount); err != nil {
+ logrus.Warn("GetAdminActionLogsListDB:ScanRowsToStructRows", err)
+ continue
+ }
+ logs = append(logs, entry)
+ }
+
+ return logs, totalCount, nil
+}
+
+func (u *AdminActionLogDB) GetAdminActionLogsFilteredDB(ctx context.Context, filter typescore.AdminActionLogFilter, offset, limit *uint64) ([]*typescore.AdminActionLog, uint64, error) {
+ fields := dbutils.GetStructFieldsDB(&typescore.AdminActionLog{}, dbcoretablenames.TableNameAdminActionLogs.ToString())
+ selectFields := append(fields, "COUNT(*) OVER() AS total_count")
+
+ query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameAdminActionLogs.ToString(), selectFields)
+
+ if filter.AdminID != nil {
+ query = query.Where(squirrel.Eq{"admin_id": *filter.AdminID})
+ }
+ if filter.AdminLogin != nil && *filter.AdminLogin != "" {
+ query = query.Where(squirrel.ILike{"admin_login": "%" + *filter.AdminLogin + "%"})
+ }
+ if filter.Action != nil {
+ query = query.Where(squirrel.Eq{"action": *filter.Action})
+ }
+ if filter.EntityType != nil {
+ query = query.Where(squirrel.Eq{"entity_type": *filter.EntityType})
+ }
+ if filter.EntityID != nil {
+ query = query.Where(squirrel.Eq{"entity_id": *filter.EntityID})
+ }
+ if filter.DateFrom != nil {
+ query = query.Where(squirrel.GtOrEq{"created_at": *filter.DateFrom})
+ }
+ if filter.DateTo != nil {
+ query = query.Where(squirrel.LtOrEq{"created_at": *filter.DateTo})
+ }
+ if filter.Search != nil && *filter.Search != "" {
+ query = query.Where(squirrel.ILike{"description": "%" + *filter.Search + "%"})
+ }
+
+ query = dbutils.SetterLimitAndOffsetQuery(query, offset, limit)
+ 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 logs []*typescore.AdminActionLog
+ var totalCount uint64
+ for rows.Next() {
+ entry := &typescore.AdminActionLog{}
+ if err := dbutils.ScanRowsToStructRows(rows, entry, &totalCount); err != nil {
+ logrus.Warn("GetAdminActionLogsFilteredDB:ScanRowsToStructRows", err)
+ continue
+ }
+ logs = append(logs, entry)
+ }
+
+ return logs, totalCount, nil
+}
+
+func (u *AdminActionLogDB) CreateAdminActionLogDB(ctx context.Context, tx pgx.Tx, obj *typescore.AdminActionLog, returnObj ...bool) (*typescore.AdminActionLog, pgx.Tx, error) {
+ if obj == nil {
+ return nil, nil, errors.New("AdminActionLog obj is nil")
+ }
+
+ var insertedID uint64
+
+ now := time.Now().UTC()
+ obj.CreatedAt = &now
+ err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Insert(dbcoretablenames.TableNameAdminActionLogs.ToString())
+
+ sqlV, args, err := dbutils.GenerateInsertRequest(query, obj)
+ 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.GetAdminActionLogByIDDB(ctx, insertedID)
+ return created, tx, err
+ }
+ return nil, tx, nil
+}
+
+func (u *AdminActionLogDB) DeleteAdminActionLogDB(ctx context.Context, params *typescore.AdminActionLog) error {
+ if params == nil || params.ID == nil {
+ return errors.New("AdminActionLog obj is nil")
+ }
+
+ query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Delete(dbcoretablenames.TableNameAdminActionLogs.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
+}
+
+func (u *AdminActionLogDB) GetAdminActionLogByIDDB(ctx context.Context, id uint64) (*typescore.AdminActionLog, error) {
+ logs, _, err := u.GetAdminActionLogsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.AdminActionLog{ID: &id},
+ })
+ if err != nil {
+ return nil, err
+ }
+ if len(logs) == 0 {
+ return nil, nil
+ }
+ return logs[0], nil
+}
diff --git a/core/db/methods/approval.go b/core/db/methods/approval.go
index 15ad334..151fdf7 100644
--- a/core/db/methods/approval.go
+++ b/core/db/methods/approval.go
@@ -44,6 +44,100 @@ type ApprovalDBI interface {
CountApprovalsCreatedOnDB(ctx context.Context, date time.Time) (int, error)
CountApprovalsApprovedOnDB(ctx context.Context, date time.Time) (int, error)
GetTopTopicsDB(ctx context.Context, limit int) ([]map[string]interface{}, error)
+ GetApprovalsListFilteredDB(ctx context.Context, filter typescore.ApprovalFilter, offset, limit uint64) ([]*typescore.Approval, uint64, error)
+}
+
+// GetApprovalsListFilteredDB — расширенный метод с JOIN'ами и поддержкой массивов
+func (u *ApprovalDB) GetApprovalsListFilteredDB(ctx context.Context, filter typescore.ApprovalFilter, offset, limit uint64) ([]*typescore.Approval, uint64, error) {
+ q := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Select("DISTINCT a.*, COUNT(*) OVER() AS total_count").
+ From("approvals a").
+ LeftJoin("approval_topics t ON t.id = a.topic_id").
+ LeftJoin("approval_topic_categories c ON c.id = t.category_id").
+ OrderBy("a.created_at DESC")
+
+ if filter.ObserverUserID != nil {
+ subQ1 := buildApprovalIdSubquery("initiator", filter.ObserverUserID)
+ subQ2 := buildApprovalIdSubquery("approver", filter.ObserverUserID)
+ subQ3 := buildApprovalIdSubquery("observer", filter.ObserverUserID)
+ subQ4 := buildApprovalIdSubquery("executor", filter.ObserverUserID)
+ subQ5 := buildApprovalIdSubquery("additional_approver", filter.ObserverUserID)
+ subQ6 := buildApprovalIdSubquery("additional_observer", filter.ObserverUserID)
+
+ 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()
+ s5, a5, _ := subQ5.PlaceholderFormat(squirrel.Question).ToSql()
+ s6, a6, _ := subQ6.PlaceholderFormat(squirrel.Question).ToSql()
+
+ unionSQL := fmt.Sprintf("(%s) UNION (%s) UNION (%s) UNION (%s) UNION (%s) UNION (%s)", s1, s2, s3, s4, s5, s6)
+ allArgs := append(append(append(append(append(a1, a2...), a3...), a4...), a5...), a6...)
+
+ q = q.Where(squirrel.Expr("a.id IN ("+unionSQL+")", allArgs...))
+ }
+
+ if filter.Status != nil && *filter.Status != "" {
+ q = q.Where(squirrel.Eq{"a.status": *filter.Status})
+ }
+ if filter.InitiatorID != nil {
+ q = q.Where(squirrel.Eq{"a.initiator_id": *filter.InitiatorID})
+ }
+ if filter.DepartmentID != nil {
+ q = q.Where(squirrel.Eq{"a.department_id": *filter.DepartmentID})
+ }
+ if filter.ID != nil {
+ q = q.Where(squirrel.Eq{"a.id": *filter.ID})
+ }
+ if filter.Content != nil && *filter.Content != "" {
+ q = q.Where(squirrel.Like{"a.content": "%" + *filter.Content + "%"})
+ }
+
+ 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})
+ }
+ if len(filter.CategoryIDs) > 0 {
+ q = q.Where(squirrel.Eq{"t.category_id": filter.CategoryIDs})
+ }
+ if len(filter.TopicIDs) > 0 {
+ q = q.Where(squirrel.Eq{"a.topic_id": filter.TopicIDs})
+ }
+
+ // Пагинация
+ if limit > 0 {
+ q = q.Limit(limit)
+ }
+ if offset > 0 {
+ q = q.Offset(offset)
+ }
+
+ sql, args, err := q.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("GetApprovalsListFilteredDB:ScanRowsToStructRows", err)
+ continue
+ }
+ approvals = append(approvals, approval)
+ }
+
+ return approvals, totalCount, nil
}
// SearchApprovalsByContentDB — поиск заявок по частичному совпадению в тексте
@@ -149,6 +243,8 @@ func (u *ApprovalDB) CreateApprovalDB(ctx context.Context, tx pgx.Tx, ApprovalOb
var insertedID uint64
+ now := time.Now().UTC()
+ ApprovalObj.CreatedAt = &now
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
Insert(dbcoretablenames.TableNameApprovals.ToString())
@@ -181,6 +277,8 @@ func (u *ApprovalDB) UpdateApprovalDB(ctx context.Context, tx pgx.Tx, paramsUpda
return nil, nil, errors.New("approval obj is nil")
}
+ now := time.Now().UTC()
+ paramsUpdate.CreatedAt = &now
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)
@@ -415,6 +513,7 @@ func (u *ApprovalDB) GetClosedApprovalsByInitiatorDB(ctx context.Context, initia
// GetApprovalsForReportDB — получение согласований для отчёта с учётом всех ролей пользователя.
// Пользователь видит согласования где он: инициатор, согласующий, наблюдатель или исполнитель.
+// GetApprovalsForReportDB — получение согласований для отчёта с учётом всех ролей пользователя.
func (u *ApprovalDB) GetApprovalsForReportDB(ctx context.Context, filter typescore.ReportFilter) ([]*typescore.Approval, error) {
q := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
Select("DISTINCT a.*").
@@ -426,14 +525,19 @@ func (u *ApprovalDB) GetApprovalsForReportDB(ctx context.Context, filter typesco
subQ2 := buildApprovalIdSubquery("approver", filter.UserID)
subQ3 := buildApprovalIdSubquery("observer", filter.UserID)
subQ4 := buildApprovalIdSubquery("executor", filter.UserID)
+ subQ5 := buildApprovalIdSubquery("additional_approver", filter.UserID) // 🆕 Доп. согласующий
+ subQ6 := buildApprovalIdSubquery("additional_observer", 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()
+ s5, a5, _ := subQ5.PlaceholderFormat(squirrel.Question).ToSql() // 🆕
+ s6, a6, _ := subQ6.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...)
+ unionSQL := fmt.Sprintf("(%s) UNION (%s) UNION (%s) UNION (%s) UNION (%s) UNION (%s)", s1, s2, s3, s4, s5, s6)
+
+ allArgs := append(append(append(append(append(a1, a2...), a3...), a4...), a5...), a6...)
q = q.Where(squirrel.Expr("a.id IN ("+unionSQL+")", allArgs...))
}
@@ -471,15 +575,28 @@ func buildApprovalIdSubquery(role string, userID *uint64) squirrel.SelectBuilder
Join(dbcoretablenames.TableNameApprovalTasks.ToString() + " task ON task.approval_id = a.id").
Where(squirrel.Eq{"task.executor_id": userID})
+ case "additional_approver":
+ return q.
+ Join(dbcoretablenames.TableNameApprovalAdditionalApprovers.ToString() + " aaa ON aaa.approval_id = a.id").
+ Where(squirrel.Eq{"aaa.approver_id": userID})
+
+ case "additional_observer":
+ return q.
+ Join(dbcoretablenames.TableNameApprovalAdditionalObservers.ToString() + " ao ON ao.approval_id = a.id").
+ Where(squirrel.Eq{"ao.user_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"},
+ 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.role_id IN (SELECT ur.role_id FROM user_roles ur WHERE ur.user_id = ?)", userID).
+ Where(squirrel.Eq{"p.action": "observe"}).
+ Where(squirrel.Or{
+ squirrel.And{
+ squirrel.Expr("p.topic_id IS NULL"),
+ squirrel.Expr("p.topic_category_id = c.id"),
+ },
+ squirrel.Expr("p.topic_id = t.id"),
})
default:
diff --git a/core/db/methods/approval_additional_approver.go b/core/db/methods/approval_additional_approver.go
index e9a0350..1ebadad 100644
--- a/core/db/methods/approval_additional_approver.go
+++ b/core/db/methods/approval_additional_approver.go
@@ -10,6 +10,7 @@ import (
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/sirupsen/logrus"
+ "time"
)
type ApprovalAdditionalApproverDB struct {
@@ -76,6 +77,8 @@ func (u *ApprovalAdditionalApproverDB) CreateApprovalAdditionalApproverDB(ctx co
var insertedID uint64
+ now := time.Now().UTC()
+ ApprovalAdditionalApproverObj.CreatedAt = &now
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
Insert(dbcoretablenames.TableNameApprovalAdditionalApprovers.ToString())
diff --git a/core/db/methods/approval_additional_observer.go b/core/db/methods/approval_additional_observer.go
index 7c5295c..2be7dd4 100644
--- a/core/db/methods/approval_additional_observer.go
+++ b/core/db/methods/approval_additional_observer.go
@@ -10,6 +10,7 @@ import (
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/sirupsen/logrus"
+ "time"
)
type ApprovalAdditionalObserverDB struct {
@@ -76,6 +77,8 @@ func (u *ApprovalAdditionalObserverDB) CreateApprovalAdditionalObserverDB(ctx co
var insertedID uint64
+ now := time.Now().UTC()
+ ApprovalAdditionalObserverObj.CreatedAt = &now
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
Insert(dbcoretablenames.TableNameApprovalAdditionalObservers.ToString())
diff --git a/core/db/methods/approval_comment.go b/core/db/methods/approval_comment.go
index 642be67..6b20106 100644
--- a/core/db/methods/approval_comment.go
+++ b/core/db/methods/approval_comment.go
@@ -10,6 +10,7 @@ import (
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/sirupsen/logrus"
+ "time"
)
type ApprovalCommentDB struct {
@@ -77,6 +78,8 @@ func (u *ApprovalCommentDB) CreateApprovalCommentDB(ctx context.Context, tx pgx.
var insertedID uint64
+ now := time.Now().UTC()
+ ApprovalCommentObj.CreatedAt = &now
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
Insert(dbcoretablenames.TableNameApprovalComments.ToString())
@@ -92,18 +95,23 @@ func (u *ApprovalCommentDB) CreateApprovalCommentDB(ctx context.Context, tx pgx.
})
if err != nil {
- return nil, tx, err
+ return nil, nil, err
}
returnObjBool := len(returnObj) > 0 && returnObj[0]
- if returnObjBool && insertedID > 0 {
+ if returnObjBool {
+ if insertedID == 0 {
+ return nil, nil, errors.New("inserted ID is 0 after insert")
+ }
created, err := u.GetApprovalCommentByIDDB(ctx, insertedID)
- return created, tx, err
+ if err != nil {
+ return nil, nil, err
+ }
+ return created, nil, nil
}
- return nil, tx, nil
+ return nil, nil, 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")
diff --git a/core/db/methods/approval_file.go b/core/db/methods/approval_file.go
index 634dc4a..678b604 100644
--- a/core/db/methods/approval_file.go
+++ b/core/db/methods/approval_file.go
@@ -10,6 +10,7 @@ import (
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/sirupsen/logrus"
+ "time"
)
type ApprovalFileDB struct {
@@ -30,6 +31,7 @@ type ApprovalFileDBI interface {
GetFilesByApprovalIDDB(ctx context.Context, id uint64) ([]*typescore.ApprovalFile, error)
GetApprovalFileByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalFile, error)
GetFilesByTaskIDDB(ctx context.Context, taskID uint64) ([]*typescore.ApprovalFile, error)
+ GetFilesByApprovalIDsDB(ctx context.Context, approvalIDs []uint64) ([]*typescore.ApprovalFile, error)
}
func (u *ApprovalFileDB) GetApprovalFilesListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalFile, uint64, error) {
@@ -78,6 +80,8 @@ func (u *ApprovalFileDB) CreateApprovalFileDB(ctx context.Context, tx pgx.Tx, Ap
var insertedID uint64
+ now := time.Now().UTC()
+ ApprovalFileObj.CreatedAt = &now
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
Insert(dbcoretablenames.TableNameApprovalFiles.ToString())
@@ -226,3 +230,42 @@ func (u *ApprovalFileDB) GetFilesByTaskIDDB(ctx context.Context, taskID uint64)
}
return files, nil
}
+
+// GetFilesByApprovalIDsDB — пакетное получение файлов сразу для нескольких заявок (устраняет N+1)
+func (a *ApprovalFileDB) GetFilesByApprovalIDsDB(ctx context.Context, approvalIDs []uint64) ([]*typescore.ApprovalFile, error) {
+ if len(approvalIDs) == 0 {
+ return nil, nil
+ }
+
+ fields := dbutils.GetStructFieldsDB(&typescore.ApprovalFile{}, dbcoretablenames.TableNameApprovalFiles.ToString())
+
+ sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Select(fields...).
+ From(dbcoretablenames.TableNameApprovalFiles.ToString()).
+ Where(squirrel.Eq{"approval_id": approvalIDs}).
+ ToSql()
+ if err != nil {
+ return nil, err
+ }
+
+ rows, err := a.pool.Query(ctx, sql, args...)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ var files []*typescore.ApprovalFile
+ for rows.Next() {
+ f := &typescore.ApprovalFile{}
+ if err := dbutils.ScanRowsToStructRows(rows, f, nil); err != nil {
+ logrus.Warn("GetFilesByApprovalIDsDB:ScanRowsToStructRows", err)
+ continue
+ }
+ files = append(files, f)
+ }
+ if err = rows.Err(); err != nil {
+ return nil, err
+ }
+
+ return files, nil
+}
diff --git a/core/db/methods/approval_flow_node.go b/core/db/methods/approval_flow_node.go
new file mode 100644
index 0000000..f4ce815
--- /dev/null
+++ b/core/db/methods/approval_flow_node.go
@@ -0,0 +1,175 @@
+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"
+)
+
+type ApprovalFlowNodeDB struct {
+ pool *pgxpool.Pool
+}
+
+func NewApprovalFlowNodeDB(pool *pgxpool.Pool) *ApprovalFlowNodeDB {
+ return &ApprovalFlowNodeDB{pool: pool}
+}
+
+type ApprovalFlowNodeDBI interface {
+ GetApprovalFlowNodesListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.ApprovalFlowNode, uint64, error)
+ CreateApprovalFlowNodeDB(ctx context.Context, tx pgx.Tx, node *typescore.ApprovalFlowNode, returnObj ...bool) (*typescore.ApprovalFlowNode, pgx.Tx, error)
+ UpdateApprovalFlowNodeDB(ctx context.Context, tx pgx.Tx, node *typescore.ApprovalFlowNode, returnObj ...bool) (*typescore.ApprovalFlowNode, pgx.Tx, error)
+ DeleteApprovalFlowNodeDB(ctx context.Context, node *typescore.ApprovalFlowNode) error
+ DeleteFlowNodesByCategoryIDDB(ctx context.Context, catID uint64) error
+ GetFlowNodeByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalFlowNode, error)
+}
+
+func (u *ApprovalFlowNodeDB) GetApprovalFlowNodesListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalFlowNode, uint64, error) {
+ fields := dbutils.GetStructFieldsDB(&typescore.ApprovalFlowNode{}, dbcoretablenames.TableNameApprovalFlowNodes.ToString())
+ selectFields := append(fields, "COUNT(*) OVER() AS total_count")
+
+ options, filter, err := dbutils.GetOptionsDB[typescore.ApprovalFlowNode](opts...)
+ if err != nil {
+ return nil, 0, err
+ }
+
+ query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovalFlowNodes.ToString(), selectFields)
+ query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
+ query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovalFlowNodes.ToString())
+ query = query.OrderBy("sort_order ASC, id ASC")
+
+ 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 nodes []*typescore.ApprovalFlowNode
+ var totalCount uint64
+ for rows.Next() {
+ node := &typescore.ApprovalFlowNode{}
+ if err := dbutils.ScanRowsToStructRows(rows, node, &totalCount); err != nil {
+ continue
+ }
+ nodes = append(nodes, node)
+ }
+
+ return nodes, totalCount, nil
+}
+
+func (u *ApprovalFlowNodeDB) CreateApprovalFlowNodeDB(ctx context.Context, tx pgx.Tx, node *typescore.ApprovalFlowNode, returnObj ...bool) (*typescore.ApprovalFlowNode, pgx.Tx, error) {
+ if node == nil {
+ return nil, nil, errors.New("node is nil")
+ }
+
+ err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Insert(dbcoretablenames.TableNameApprovalFlowNodes.ToString())
+
+ sqlV, args, err := dbutils.GenerateInsertRequest(query, node)
+ if err != nil {
+ return err
+ }
+
+ _, err = tx.Exec(ctx, *sqlV, args...)
+ return err
+ })
+
+ if err != nil {
+ return nil, tx, err
+ }
+
+ if len(returnObj) > 0 && returnObj[0] {
+ nodes, _, _ := u.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{Filtering: node})
+ if len(nodes) > 0 {
+ return nodes[0], tx, nil
+ }
+ }
+
+ return nil, tx, nil
+}
+
+func (u *ApprovalFlowNodeDB) UpdateApprovalFlowNodeDB(ctx context.Context, tx pgx.Tx, node *typescore.ApprovalFlowNode, returnObj ...bool) (*typescore.ApprovalFlowNode, pgx.Tx, error) {
+ if node == nil || node.ID == nil {
+ return nil, nil, errors.New("node or node.ID is nil")
+ }
+
+ err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Update(dbcoretablenames.TableNameApprovalFlowNodes.ToString())
+ query = dbutils.AddNonNullFieldsToQueryUpdate(query, *node)
+ query = query.Where(squirrel.Eq{"id": node.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
+ }
+
+ if len(returnObj) > 0 && returnObj[0] {
+ updated, _ := u.GetFlowNodeByIDDB(ctx, *node.ID)
+ return updated, tx, nil
+ }
+
+ return nil, tx, nil
+}
+
+func (u *ApprovalFlowNodeDB) DeleteApprovalFlowNodeDB(ctx context.Context, node *typescore.ApprovalFlowNode) error {
+ if node == nil || node.ID == nil {
+ return errors.New("node or node.ID is nil")
+ }
+
+ query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Delete(dbcoretablenames.TableNameApprovalFlowNodes.ToString()).
+ Where(squirrel.Eq{"id": *node.ID}).
+ ToSql()
+ if err != nil {
+ return err
+ }
+
+ _, err = u.pool.Exec(ctx, query, args...)
+ return err
+}
+
+func (u *ApprovalFlowNodeDB) DeleteFlowNodesByCategoryIDDB(ctx context.Context, catID uint64) error {
+ query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Delete(dbcoretablenames.TableNameApprovalFlowNodes.ToString()).
+ Where(squirrel.Eq{"category_id": catID}).
+ ToSql()
+ if err != nil {
+ return err
+ }
+
+ _, err = u.pool.Exec(ctx, query, args...)
+ return err
+}
+
+func (u *ApprovalFlowNodeDB) GetFlowNodeByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalFlowNode, error) {
+ nodes, _, err := u.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalFlowNode{ID: &id},
+ })
+ if err != nil {
+ return nil, err
+ }
+ if len(nodes) == 0 {
+ return nil, nil
+ }
+ return nodes[0], nil
+}
diff --git a/core/db/methods/approval_revocation_request.go b/core/db/methods/approval_revocation_request.go
new file mode 100644
index 0000000..331d0b9
--- /dev/null
+++ b/core/db/methods/approval_revocation_request.go
@@ -0,0 +1,215 @@
+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/pgxpool"
+ "github.com/sirupsen/logrus"
+)
+
+type ApprovalRevocationDB struct {
+ pool *pgxpool.Pool
+}
+
+func NewApprovalRevocationDB(pool *pgxpool.Pool) *ApprovalRevocationDB {
+ return &ApprovalRevocationDB{pool: pool}
+}
+
+type ApprovalRevocationDBI interface {
+ CreateRevocationRequestDB(ctx context.Context, obj *typescore.ApprovalRevocationRequest, returnObj ...bool) (*typescore.ApprovalRevocationRequest, error)
+ UpdateRevocationRequestDB(ctx context.Context, obj *typescore.ApprovalRevocationRequest, returnObj ...bool) (*typescore.ApprovalRevocationRequest, error)
+ GetRevocationRequestByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalRevocationRequest, error)
+ GetPendingRevocationRequestForApprovalDB(ctx context.Context, approvalID uint64) (*typescore.ApprovalRevocationRequest, error)
+
+ CreateRevocationApproversDB(ctx context.Context, approvers []*typescore.ApprovalRevocationApprover) error
+ UpdateRevocationApproverDB(ctx context.Context, obj *typescore.ApprovalRevocationApprover) error
+ GetRevocationApproversByRequestIDDB(ctx context.Context, requestID uint64) ([]*typescore.ApprovalRevocationApprover, error)
+ GetRevocationApproverForUserDB(ctx context.Context, requestID uint64, approverID uint64) (*typescore.ApprovalRevocationApprover, error)
+}
+
+func (d *ApprovalRevocationDB) CreateRevocationRequestDB(ctx context.Context, obj *typescore.ApprovalRevocationRequest, returnObj ...bool) (*typescore.ApprovalRevocationRequest, error) {
+ if obj == nil {
+ return nil, errors.New("revocation request obj is nil")
+ }
+
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Insert(dbcoretablenames.TableNameApprovalRevocationRequests.ToString())
+
+ sqlV, args, err := dbutils.GenerateInsertRequest(query, obj)
+ if err != nil {
+ return nil, err
+ }
+ *sqlV = *sqlV + " RETURNING id"
+
+ var insertedID uint64
+ if err := d.pool.QueryRow(ctx, *sqlV, args...).Scan(&insertedID); err != nil {
+ return nil, err
+ }
+
+ if len(returnObj) > 0 && returnObj[0] {
+ return d.GetRevocationRequestByIDDB(ctx, insertedID)
+ }
+ obj.ID = &insertedID
+ return obj, nil
+}
+
+func (d *ApprovalRevocationDB) UpdateRevocationRequestDB(ctx context.Context, obj *typescore.ApprovalRevocationRequest, returnObj ...bool) (*typescore.ApprovalRevocationRequest, error) {
+ if obj.ID == nil {
+ return nil, errors.New("revocation request id is nil")
+ }
+
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Update(dbcoretablenames.TableNameApprovalRevocationRequests.ToString())
+ query = dbutils.AddNonNullFieldsToQueryUpdate(query, *obj)
+ query = query.Where(squirrel.Eq{"id": obj.ID})
+
+ sql, args, err := query.ToSql()
+ if err != nil {
+ return nil, err
+ }
+ if _, err := d.pool.Exec(ctx, sql, args...); err != nil {
+ return nil, err
+ }
+
+ if len(returnObj) > 0 && returnObj[0] {
+ return d.GetRevocationRequestByIDDB(ctx, *obj.ID)
+ }
+ return nil, nil
+}
+
+func (d *ApprovalRevocationDB) getRevocationRequestListDB(ctx context.Context, opts typescore.ListDbOptions) ([]*typescore.ApprovalRevocationRequest, error) {
+ fields := dbutils.GetStructFieldsDB(&typescore.ApprovalRevocationRequest{}, dbcoretablenames.TableNameApprovalRevocationRequests.ToString())
+ query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovalRevocationRequests.ToString(), fields)
+
+ options, filter, err := dbutils.GetOptionsDB[typescore.ApprovalRevocationRequest](opts)
+ if err != nil {
+ return nil, err
+ }
+ query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovalRevocationRequests.ToString())
+ query = query.OrderBy("created_at DESC")
+
+ sql, args, err := query.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.ApprovalRevocationRequest
+ for rows.Next() {
+ obj := &typescore.ApprovalRevocationRequest{}
+ if err := dbutils.ScanRowsToStructRows(rows, obj, nil); err != nil {
+ logrus.Warn("getRevocationRequestListDB:ScanRowsToStructRows", err)
+ continue
+ }
+ result = append(result, obj)
+ }
+ return result, nil
+}
+
+func (d *ApprovalRevocationDB) GetRevocationRequestByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalRevocationRequest, error) {
+ list, err := d.getRevocationRequestListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalRevocationRequest{ID: &id},
+ })
+ if err != nil || len(list) == 0 {
+ return nil, err
+ }
+ return list[0], nil
+}
+
+func (d *ApprovalRevocationDB) GetPendingRevocationRequestForApprovalDB(ctx context.Context, approvalID uint64) (*typescore.ApprovalRevocationRequest, error) {
+ pendingStatus := "pending"
+ list, err := d.getRevocationRequestListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalRevocationRequest{ApprovalID: &approvalID, Status: &pendingStatus},
+ })
+ if err != nil || len(list) == 0 {
+ return nil, err
+ }
+ return list[0], nil
+}
+
+func (d *ApprovalRevocationDB) CreateRevocationApproversDB(ctx context.Context, approvers []*typescore.ApprovalRevocationApprover) error {
+ if len(approvers) == 0 {
+ return nil
+ }
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Insert(dbcoretablenames.TableNameApprovalRevocationApprovers.ToString()).
+ Columns("revocation_request_id", "approver_id", "status")
+
+ for _, a := range approvers {
+ query = query.Values(*a.RevocationRequestID, *a.ApproverID, *a.Status)
+ }
+
+ sql, args, err := query.ToSql()
+ if err != nil {
+ return err
+ }
+ _, err = d.pool.Exec(ctx, sql, args...)
+ return err
+}
+
+func (d *ApprovalRevocationDB) UpdateRevocationApproverDB(ctx context.Context, obj *typescore.ApprovalRevocationApprover) error {
+ if obj.ID == nil {
+ return errors.New("revocation approver id is nil")
+ }
+
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Update(dbcoretablenames.TableNameApprovalRevocationApprovers.ToString())
+ query = dbutils.AddNonNullFieldsToQueryUpdate(query, *obj)
+ query = query.Where(squirrel.Eq{"id": obj.ID})
+
+ sql, args, err := query.ToSql()
+ if err != nil {
+ return err
+ }
+ _, err = d.pool.Exec(ctx, sql, args...)
+ return err
+}
+
+func (d *ApprovalRevocationDB) GetRevocationApproversByRequestIDDB(ctx context.Context, requestID uint64) ([]*typescore.ApprovalRevocationApprover, error) {
+ fields := dbutils.GetStructFieldsDB(&typescore.ApprovalRevocationApprover{}, dbcoretablenames.TableNameApprovalRevocationApprovers.ToString())
+ query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovalRevocationApprovers.ToString(), fields).
+ Where(squirrel.Eq{"revocation_request_id": requestID})
+
+ sql, args, err := query.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.ApprovalRevocationApprover
+ for rows.Next() {
+ obj := &typescore.ApprovalRevocationApprover{}
+ if err := dbutils.ScanRowsToStructRows(rows, obj, nil); err != nil {
+ continue
+ }
+ result = append(result, obj)
+ }
+ return result, nil
+}
+
+func (d *ApprovalRevocationDB) GetRevocationApproverForUserDB(ctx context.Context, requestID uint64, approverID uint64) (*typescore.ApprovalRevocationApprover, error) {
+ all, err := d.GetRevocationApproversByRequestIDDB(ctx, requestID)
+ if err != nil {
+ return nil, err
+ }
+ for _, a := range all {
+ if a.ApproverID != nil && *a.ApproverID == approverID {
+ return a, nil
+ }
+ }
+ return nil, nil
+}
diff --git a/core/db/methods/approval_step.go b/core/db/methods/approval_step.go
index 9cf04d3..7d58a73 100644
--- a/core/db/methods/approval_step.go
+++ b/core/db/methods/approval_step.go
@@ -7,6 +7,7 @@ import (
"context"
"errors"
"github.com/sirupsen/logrus"
+ "time"
"github.com/Masterminds/squirrel"
"github.com/jackc/pgx/v5"
@@ -31,6 +32,7 @@ type ApprovalStepDBI interface {
GetActiveStepDB(ctx context.Context, approvalID uint64) (*typescore.ApprovalStep, error)
GetNextStepDB(ctx context.Context, approvalID uint64, currentOrder int) (*typescore.ApprovalStep, error)
+ GetApprovalStepsByApprovalIDsDB(ctx context.Context, approvalIDs []uint64) ([]*typescore.ApprovalStep, error)
}
func (u *ApprovalStepDB) GetApprovalStepsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalStep, uint64, error) {
@@ -77,6 +79,8 @@ func (u *ApprovalStepDB) CreateApprovalStepDB(ctx context.Context, tx pgx.Tx, Ap
return nil, nil, errors.New("ApprovalStep obj is nil")
}
+ now := time.Now().UTC()
+ ApprovalStepObj.CreatedAt = &now
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Insert(dbcoretablenames.TableNameApprovalSteps.ToString())
@@ -119,6 +123,8 @@ func (u *ApprovalStepDB) UpdateApprovalStepDB(ctx context.Context, tx pgx.Tx, pa
return nil, nil, errors.New("ApprovalStep obj is nil")
}
+ now := time.Now().UTC()
+ paramsUpdate.UpdatedAt = &now
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)
@@ -232,3 +238,43 @@ func (u *ApprovalStepDB) GetNextStepDB(ctx context.Context, approvalID uint64, c
}
return nil, nil
}
+
+// GetApprovalStepsByApprovalIDsDB — пакетное получение шагов сразу для нескольких заявок (устраняет N+1)
+func (a *ApprovalStepDB) GetApprovalStepsByApprovalIDsDB(ctx context.Context, approvalIDs []uint64) ([]*typescore.ApprovalStep, error) {
+ if len(approvalIDs) == 0 {
+ return nil, nil
+ }
+
+ fields := dbutils.GetStructFieldsDB(&typescore.ApprovalStep{}, dbcoretablenames.TableNameApprovalSteps.ToString())
+
+ sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Select(fields...).
+ From(dbcoretablenames.TableNameApprovalSteps.ToString()).
+ Where(squirrel.Eq{"approval_id": approvalIDs}).
+ OrderBy("step_order ASC").
+ ToSql()
+ if err != nil {
+ return nil, err
+ }
+
+ rows, err := a.pool.Query(ctx, sql, args...)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ var steps []*typescore.ApprovalStep
+ for rows.Next() {
+ st := &typescore.ApprovalStep{}
+ if err := dbutils.ScanRowsToStructRows(rows, st, nil); err != nil {
+ logrus.Warn("GetApprovalStepsByApprovalIDsDB:ScanRowsToStructRows", err)
+ continue
+ }
+ steps = append(steps, st)
+ }
+ if err = rows.Err(); err != nil {
+ return nil, err
+ }
+
+ return steps, nil
+}
diff --git a/core/db/methods/approval_task.go b/core/db/methods/approval_task.go
index 4d03fb9..1e4ed03 100644
--- a/core/db/methods/approval_task.go
+++ b/core/db/methods/approval_task.go
@@ -11,6 +11,7 @@ import (
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/sirupsen/logrus"
+ "strings"
"time"
)
@@ -45,6 +46,28 @@ func (u *ApprovalTaskDB) GetApprovalTasksListDB(ctx context.Context, opts ...typ
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())
+
+ if filter != nil && filter.ObserverUserID != nil {
+ subQ1 := buildApprovalIdSubquery("initiator", filter.ObserverUserID)
+ subQ2 := buildApprovalIdSubquery("approver", filter.ObserverUserID)
+ subQ3 := buildApprovalIdSubquery("observer", filter.ObserverUserID)
+ subQ4 := buildApprovalIdSubquery("executor", filter.ObserverUserID)
+ subQ5 := buildApprovalIdSubquery("additional_approver", filter.ObserverUserID)
+ subQ6 := buildApprovalIdSubquery("additional_observer", filter.ObserverUserID)
+
+ 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()
+ s5, a5, _ := subQ5.PlaceholderFormat(squirrel.Question).ToSql()
+ s6, a6, _ := subQ6.PlaceholderFormat(squirrel.Question).ToSql()
+
+ unionSQL := fmt.Sprintf("(%s) UNION (%s) UNION (%s) UNION (%s) UNION (%s) UNION (%s)", s1, s2, s3, s4, s5, s6)
+ allArgs := append(append(append(append(append(a1, a2...), a3...), a4...), a5...), a6...)
+
+ query = query.Where(squirrel.Expr(dbcoretablenames.TableNameApprovalTasks.ToString()+".approval_id IN ("+unionSQL+")", allArgs...))
+ }
+
query = query.OrderBy("created_at DESC")
sql, args, err := query.ToSql()
@@ -71,7 +94,6 @@ func (u *ApprovalTaskDB) GetApprovalTasksListDB(ctx context.Context, opts ...typ
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")
@@ -79,7 +101,44 @@ func (u *ApprovalTaskDB) CreateApprovalTaskDB(ctx context.Context, tx pgx.Tx, Ap
var insertedID uint64
+ now := time.Now().UTC()
+ ApprovalTaskObj.CreatedAt = &now
+
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
+ // Автоматически дополняем текст задачи номером и текстом заявки перед сохранением в БД
+ if ApprovalTaskObj.ApprovalID != nil {
+ var approvalContent *string
+ err := tx.QueryRow(
+ ctx,
+ "SELECT content FROM approvals WHERE id = $1",
+ *ApprovalTaskObj.ApprovalID,
+ ).Scan(&approvalContent)
+
+ if err == nil {
+ contentStr := "—"
+ if approvalContent != nil && *approvalContent != "" {
+ contentStr = *approvalContent
+ }
+
+ origTaskText := ""
+ if ApprovalTaskObj.TaskText != nil {
+ origTaskText = *ApprovalTaskObj.TaskText
+ }
+
+ // Проверяем, чтобы не задублировать, если номер заявки уже есть в тексте
+ checkHeader := fmt.Sprintf("Заявка #%d", *ApprovalTaskObj.ApprovalID)
+ if !strings.Contains(origTaskText, checkHeader) {
+ enrichedText := fmt.Sprintf(
+ "Заявка #%d\nТекст заявки: %s\n\nЗадача:\n%s",
+ *ApprovalTaskObj.ApprovalID,
+ contentStr,
+ origTaskText,
+ )
+ ApprovalTaskObj.TaskText = &enrichedText
+ }
+ }
+ }
+
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
Insert(dbcoretablenames.TableNameApprovalTasks.ToString())
diff --git a/core/db/methods/approval_task_transfer.go b/core/db/methods/approval_task_transfer.go
new file mode 100644
index 0000000..eb03e58
--- /dev/null
+++ b/core/db/methods/approval_task_transfer.go
@@ -0,0 +1,151 @@
+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/pgxpool"
+ "github.com/sirupsen/logrus"
+)
+
+type ApprovalTaskTransferDB struct {
+ pool *pgxpool.Pool
+}
+
+func NewApprovalTaskTransferDB(pool *pgxpool.Pool) *ApprovalTaskTransferDB {
+ return &ApprovalTaskTransferDB{pool: pool}
+}
+
+type ApprovalTaskTransferDBI interface {
+ GetApprovalTaskTransferListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalTaskTransfer, uint64, error)
+ CreateApprovalTaskTransferDB(ctx context.Context, obj *typescore.ApprovalTaskTransfer, returnObj ...bool) (*typescore.ApprovalTaskTransfer, error)
+ UpdateApprovalTaskTransferDB(ctx context.Context, paramsUpdate *typescore.ApprovalTaskTransfer, returnObj ...bool) (*typescore.ApprovalTaskTransfer, error)
+ GetApprovalTaskTransferByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalTaskTransfer, error)
+ GetPendingTransferForTaskDB(ctx context.Context, taskID uint64) (*typescore.ApprovalTaskTransfer, error)
+}
+
+func (u *ApprovalTaskTransferDB) GetApprovalTaskTransferListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalTaskTransfer, uint64, error) {
+ fields := dbutils.GetStructFieldsDB(&typescore.ApprovalTaskTransfer{}, dbcoretablenames.TableNameApprovalTaskTransfers.ToString())
+ selectFields := append(fields, "COUNT(*) OVER() AS total_count")
+
+ options, filter, err := dbutils.GetOptionsDB[typescore.ApprovalTaskTransfer](opts...)
+ if err != nil {
+ return nil, 0, err
+ }
+
+ query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovalTaskTransfers.ToString(), selectFields)
+ query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
+ query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovalTaskTransfers.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 result []*typescore.ApprovalTaskTransfer
+ var totalCount uint64
+ for rows.Next() {
+ obj := &typescore.ApprovalTaskTransfer{}
+ if err := dbutils.ScanRowsToStructRows(rows, obj, &totalCount); err != nil {
+ logrus.Warn("GetApprovalTaskTransferListDB:ScanRowsToStructRows", err)
+ continue
+ }
+ result = append(result, obj)
+ }
+
+ return result, totalCount, nil
+}
+
+func (u *ApprovalTaskTransferDB) CreateApprovalTaskTransferDB(ctx context.Context, obj *typescore.ApprovalTaskTransfer, returnObj ...bool) (*typescore.ApprovalTaskTransfer, error) {
+ if obj == nil {
+ return nil, errors.New("approval task transfer obj is nil")
+ }
+
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Insert(dbcoretablenames.TableNameApprovalTaskTransfers.ToString())
+
+ sqlV, args, err := dbutils.GenerateInsertRequest(query, obj)
+ if err != nil {
+ return nil, err
+ }
+
+ *sqlV = *sqlV + " RETURNING id"
+
+ var insertedID uint64
+ if err := u.pool.QueryRow(ctx, *sqlV, args...).Scan(&insertedID); err != nil {
+ return nil, err
+ }
+
+ returnObjBool := len(returnObj) > 0 && returnObj[0]
+ if returnObjBool && insertedID > 0 {
+ return u.GetApprovalTaskTransferByIDDB(ctx, insertedID)
+ }
+
+ obj.ID = &insertedID
+ return obj, nil
+}
+
+func (u *ApprovalTaskTransferDB) UpdateApprovalTaskTransferDB(ctx context.Context, paramsUpdate *typescore.ApprovalTaskTransfer, returnObj ...bool) (*typescore.ApprovalTaskTransfer, error) {
+ if paramsUpdate.ID == nil {
+ return nil, errors.New("approval task transfer obj is nil")
+ }
+
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Update(dbcoretablenames.TableNameApprovalTaskTransfers.ToString())
+ query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate)
+ query = query.Where(squirrel.Eq{"id": paramsUpdate.ID})
+
+ sql, args, err := query.ToSql()
+ if err != nil {
+ return nil, err
+ }
+
+ if _, err := u.pool.Exec(ctx, sql, args...); err != nil {
+ return nil, err
+ }
+
+ returnObjBool := len(returnObj) > 0 && returnObj[0]
+ if returnObjBool {
+ return u.GetApprovalTaskTransferByIDDB(ctx, *paramsUpdate.ID)
+ }
+
+ return nil, nil
+}
+
+func (u *ApprovalTaskTransferDB) GetApprovalTaskTransferByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalTaskTransfer, error) {
+ list, _, err := u.GetApprovalTaskTransferListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalTaskTransfer{ID: &id},
+ })
+ if err != nil {
+ return nil, err
+ }
+ if len(list) == 0 {
+ return nil, nil
+ }
+ return list[0], nil
+}
+
+// GetPendingTransferForTaskDB — есть ли уже незакрытый запрос по этой задаче (защита от дублей)
+func (u *ApprovalTaskTransferDB) GetPendingTransferForTaskDB(ctx context.Context, taskID uint64) (*typescore.ApprovalTaskTransfer, error) {
+ pendingStatus := "pending"
+ list, _, err := u.GetApprovalTaskTransferListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalTaskTransfer{TaskID: &taskID, Status: &pendingStatus},
+ })
+ if err != nil {
+ return nil, err
+ }
+ if len(list) == 0 {
+ return nil, nil
+ }
+ return list[0], nil
+}
diff --git a/core/db/methods/approval_topic.go b/core/db/methods/approval_topic.go
index be16758..e76cd16 100644
--- a/core/db/methods/approval_topic.go
+++ b/core/db/methods/approval_topic.go
@@ -31,6 +31,7 @@ type ApprovalTopicDBI interface {
GetApprovalTopicByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalTopic, error)
GetApprovalTopicByCodeDB(ctx context.Context, code string) (*typescore.ApprovalTopic, error)
+ GetApprovalTopicsByIDsDB(ctx context.Context, ids []uint64) ([]*typescore.ApprovalTopic, error)
}
func (u *ApprovalTopicDB) GetApprovalTopicsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalTopic, uint64, error) {
@@ -208,3 +209,42 @@ func (u *ApprovalTopicDB) GetApprovalTopicByCodeDB(ctx context.Context, code str
}
return topics[0], nil
}
+
+// GetApprovalTopicsByIDsDB — пакетное получение тем по списку ID (устраняет N+1)
+func (u *ApprovalTopicDB) GetApprovalTopicsByIDsDB(ctx context.Context, ids []uint64) ([]*typescore.ApprovalTopic, error) {
+ if len(ids) == 0 {
+ return nil, nil
+ }
+
+ fields := dbutils.GetStructFieldsDB(&typescore.ApprovalTopic{}, dbcoretablenames.TableNameApprovalTopics.ToString())
+
+ sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Select(fields...).
+ From(dbcoretablenames.TableNameApprovalTopics.ToString()).
+ Where(squirrel.Eq{"id": ids}).
+ 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 topics []*typescore.ApprovalTopic
+ for rows.Next() {
+ topic := &typescore.ApprovalTopic{}
+ if err := dbutils.ScanRowsToStructRows(rows, topic, nil); err != nil {
+ logrus.Warn("GetApprovalTopicsByIDsDB:ScanRowsToStructRows", err)
+ continue
+ }
+ topics = append(topics, topic)
+ }
+ if err = rows.Err(); err != nil {
+ return nil, err
+ }
+
+ return topics, nil
+}
diff --git a/core/db/methods/approval_topic_category.go b/core/db/methods/approval_topic_category.go
index 7a7d8d2..a4e1dd7 100644
--- a/core/db/methods/approval_topic_category.go
+++ b/core/db/methods/approval_topic_category.go
@@ -35,6 +35,7 @@ type ApprovalTopicCategoryDBI interface {
initiatorID uint64,
) ([]*typescore.ApprovalTopicCategory, error)
GetCategoriesWithApprovalsByApproverDB(ctx context.Context, approverID uint64) ([]*typescore.ApprovalTopicCategory, error)
+ GetApprovalTopicCategoriesByIDsDB(ctx context.Context, ids []uint64) ([]*typescore.ApprovalTopicCategory, error)
}
// GetCategoriesWithApprovalsByInitiatorDB — категории тем, по которым у инициатора есть заявки
@@ -286,3 +287,42 @@ func (u *ApprovalTopicCategoryDB) GetApprovalTopicCategoryByCodeDB(ctx context.C
}
return categories[0], nil
}
+
+// GetApprovalTopicCategoriesByIDsDB — пакетное получение категорий по списку ID (устраняет N+1)
+func (u *ApprovalTopicCategoryDB) GetApprovalTopicCategoriesByIDsDB(ctx context.Context, ids []uint64) ([]*typescore.ApprovalTopicCategory, error) {
+ if len(ids) == 0 {
+ return nil, nil
+ }
+
+ fields := dbutils.GetStructFieldsDB(&typescore.ApprovalTopicCategory{}, dbcoretablenames.TableNameApprovalTopicCategories.ToString())
+
+ sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Select(fields...).
+ From(dbcoretablenames.TableNameApprovalTopicCategories.ToString()).
+ Where(squirrel.Eq{"id": ids}).
+ 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 categories []*typescore.ApprovalTopicCategory
+ for rows.Next() {
+ category := &typescore.ApprovalTopicCategory{}
+ if err := dbutils.ScanRowsToStructRows(rows, category, nil); err != nil {
+ logrus.Warn("GetApprovalTopicCategoriesByIDsDB:ScanRowsToStructRows", err)
+ continue
+ }
+ categories = append(categories, category)
+ }
+ if err = rows.Err(); err != nil {
+ return nil, err
+ }
+
+ return categories, nil
+}
diff --git a/core/db/methods/approval_topic_executor.go b/core/db/methods/approval_topic_executor.go
index c2c84ba..377b1dd 100644
--- a/core/db/methods/approval_topic_executor.go
+++ b/core/db/methods/approval_topic_executor.go
@@ -28,6 +28,156 @@ type ApprovalTopicExecutorDBI interface {
DeleteApprovalTopicExecutorDB(ctx context.Context, params *typescore.ApprovalTopicExecutor) error
GetExecutorsByTopicIDDB(ctx context.Context, topicID uint64) ([]*typescore.ApprovalTopicExecutor, error)
GetApprovalTopicExecutorListWithParamsDB(ctx context.Context, opts typescore.ListDbOptions) ([]*typescore.ApprovalTopicExecutor, uint64, error)
+ GetApprovalTopicExecutorListByCategoryDB(ctx context.Context, opts typescore.ListDbOptions, categoryID uint64) ([]*typescore.ApprovalTopicExecutor, uint64, error)
+ GetExecutorCategoriesDB(ctx context.Context, userID uint64) ([]*typescore.ApprovalTopicCategory, error)
+ GetExecutorTopicsByCategoryDB(ctx context.Context, userID uint64, categoryID uint64) ([]*typescore.ApprovalTopic, error)
+}
+
+func (d *ApprovalTopicExecutorDB) GetExecutorTopicsByCategoryDB(ctx context.Context, userID uint64, categoryID uint64) ([]*typescore.ApprovalTopic, error) {
+ fields := dbutils.GetStructFieldsDB(&typescore.ApprovalTopic{}, "t")
+
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Select(fields...).
+ From(dbcoretablenames.TableNameApprovalTopicExecutor.ToString() + " ate").
+ Join(dbcoretablenames.TableNameApprovalTopics.ToString() + " t ON t.id = ate.topic_id").
+ Where(squirrel.Eq{
+ "ate.user_id": userID,
+ "ate.is_active": true,
+ "t.category_id": categoryID,
+ "t.is_active": true,
+ }).
+ GroupBy("t.id").
+ OrderBy("t.name ASC")
+
+ sql, args, err := query.ToSql()
+ if err != nil {
+ return nil, err
+ }
+
+ rows, err := d.pool.Query(ctx, sql, args...)
+ if err != nil {
+ logrus.Errorf("GetExecutorTopicsByCategoryDB Query error: %v", err)
+ return nil, err
+ }
+ defer rows.Close()
+
+ var topics []*typescore.ApprovalTopic
+ for rows.Next() {
+ topic := &typescore.ApprovalTopic{}
+ if err := dbutils.ScanRowsToStructRows(rows, topic, nil); err != nil {
+ logrus.Warn("GetExecutorTopicsByCategoryDB:ScanRowsToStructRows", err)
+ continue
+ }
+ topics = append(topics, topic)
+ }
+
+ return topics, nil
+}
+func (d *ApprovalTopicExecutorDB) GetExecutorCategoriesDB(ctx context.Context, userID uint64) ([]*typescore.ApprovalTopicCategory, error) {
+ fields := dbutils.GetStructFieldsDB(&typescore.ApprovalTopicCategory{}, "c")
+
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Select(fields...).
+ From(dbcoretablenames.TableNameApprovalTopicExecutor.ToString() + " ate").
+ Join(dbcoretablenames.TableNameApprovalTopics.ToString() + " t ON t.id = ate.topic_id").
+ Join(dbcoretablenames.TableNameApprovalTopicCategories.ToString() + " c ON c.id = t.category_id").
+ Where(squirrel.Eq{
+ "ate.user_id": userID,
+ "ate.is_active": true,
+ "c.is_active": true,
+ }).
+ GroupBy("c.id").
+ OrderBy("c.name ASC")
+
+ sql, args, err := query.ToSql()
+ if err != nil {
+ return nil, err
+ }
+
+ rows, err := d.pool.Query(ctx, sql, args...)
+ if err != nil {
+ logrus.Errorf("GetExecutorCategoriesDB Query error: %v", err)
+ return nil, err
+ }
+ defer rows.Close()
+
+ var categories []*typescore.ApprovalTopicCategory
+ for rows.Next() {
+ cat := &typescore.ApprovalTopicCategory{}
+ if err := dbutils.ScanRowsToStructRows(rows, cat, nil); err != nil {
+ logrus.Warn("GetExecutorCategoriesDB:ScanRowsToStructRows", err)
+ continue
+ }
+ categories = append(categories, cat)
+ }
+
+ return categories, nil
+}
+
+func (d *ApprovalTopicExecutorDB) GetApprovalTopicExecutorListByCategoryDB(ctx context.Context, opts typescore.ListDbOptions, categoryID uint64) ([]*typescore.ApprovalTopicExecutor, uint64, error) {
+ options, filter, err := dbutils.GetOptionsDB[typescore.ApprovalTopicExecutor](opts)
+ if err != nil {
+ return nil, 0, err
+ }
+
+ countQuery := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Select("COUNT(DISTINCT ate.id)").
+ From(dbcoretablenames.TableNameApprovalTopicExecutor.ToString() + " ate").
+ Join(dbcoretablenames.TableNameApprovalTopics.ToString() + " t ON t.id = ate.topic_id").
+ Where(squirrel.Eq{"t.category_id": categoryID})
+
+ countQuery = dbutils.ApplyFilters(countQuery, filter, options.LikeFields, dbcoretablenames.TableNameApprovalTopicExecutor.ToString())
+
+ countSQL, countArgs, err := countQuery.ToSql()
+ if err != nil {
+ return nil, 0, err
+ }
+
+ var totalCount uint64
+ err = d.pool.QueryRow(ctx, countSQL, countArgs...).Scan(&totalCount)
+ if err != nil {
+ return nil, 0, err
+ }
+
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Select("ate.*").
+ From(dbcoretablenames.TableNameApprovalTopicExecutor.ToString() + " ate").
+ Join(dbcoretablenames.TableNameApprovalTopics.ToString() + " t ON t.id = ate.topic_id").
+ Where(squirrel.Eq{"t.category_id": categoryID}).
+ GroupBy("ate.id")
+
+ query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovalTopicExecutor.ToString())
+
+ query = query.OrderBy("ate.step_order ASC, ate.id ASC")
+ query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
+
+ sql, args, err := query.ToSql()
+ if err != nil {
+ return nil, 0, err
+ }
+
+ rows, err := d.pool.Query(ctx, sql, args...)
+ if err != nil {
+ logrus.Errorf("GetApprovalTopicExecutorListByCategoryDB Query error: %v", err)
+ return nil, 0, 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("GetApprovalTopicExecutorListByCategoryDB:ScanRowsToStructRows", err)
+ continue
+ }
+ result = append(result, item)
+ }
+
+ if err = rows.Err(); err != nil {
+ return nil, 0, err
+ }
+
+ return result, totalCount, nil
}
func (d *ApprovalTopicExecutorDB) GetApprovalTopicExecutorListWithParamsDB(ctx context.Context, opts typescore.ListDbOptions) ([]*typescore.ApprovalTopicExecutor, uint64, error) {
diff --git a/core/db/methods/department.go b/core/db/methods/department.go
index 7a359d9..bd5944c 100644
--- a/core/db/methods/department.go
+++ b/core/db/methods/department.go
@@ -29,6 +29,7 @@ type DepartmentDBI interface {
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)
+ GetDepartmentsByIDsDB(ctx context.Context, ids []uint64) ([]*typescore.Department, error)
}
func (u *DepartmentDB) GetDepartmentsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.Department, uint64, error) {
@@ -189,3 +190,42 @@ func (u *DepartmentDB) GetDepartmentByIDDB(ctx context.Context, id uint64) (*typ
}
return deps[0], nil
}
+
+// GetDepartmentsByIDsDB — пакетное получение отделов по списку ID (устраняет N+1)
+func (d *DepartmentDB) GetDepartmentsByIDsDB(ctx context.Context, ids []uint64) ([]*typescore.Department, error) {
+ if len(ids) == 0 {
+ return nil, nil
+ }
+
+ fields := dbutils.GetStructFieldsDB(&typescore.Department{}, dbcoretablenames.TableNameDepartments.ToString())
+
+ sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Select(fields...).
+ From(dbcoretablenames.TableNameDepartments.ToString()).
+ Where(squirrel.Eq{"id": ids}).
+ 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 departments []*typescore.Department
+ for rows.Next() {
+ dep := &typescore.Department{}
+ if err := dbutils.ScanRowsToStructRows(rows, dep, nil); err != nil {
+ logrus.Warn("GetDepartmentsByIDsDB:ScanRowsToStructRows", err)
+ continue
+ }
+ departments = append(departments, dep)
+ }
+ if err = rows.Err(); err != nil {
+ return nil, err
+ }
+
+ return departments, nil
+}
diff --git a/core/db/methods/director_notification.go b/core/db/methods/director_notification.go
new file mode 100644
index 0000000..c1286ed
--- /dev/null
+++ b/core/db/methods/director_notification.go
@@ -0,0 +1,126 @@
+package dbcore
+
+import (
+ dbcoretablenames "bitrix_balancer_api/core/db/table_names"
+ "bitrix_balancer_api/core/typescore"
+ dbutils "bitrix_balancer_api/core/utilscore/db"
+ "context"
+ "github.com/Masterminds/squirrel"
+ "github.com/jackc/pgx/v5/pgxpool"
+)
+
+type DirectorNotificationDB struct {
+ pool *pgxpool.Pool
+}
+
+func NewDirectorNotificationDB(pool *pgxpool.Pool) *DirectorNotificationDB {
+ return &DirectorNotificationDB{pool: pool}
+}
+
+type DirectorNotificationDBI interface {
+ GetSubscribedCategoryIDsDB(ctx context.Context, directorID uint64) ([]uint64, error)
+ ToggleSubscriptionDB(ctx context.Context, directorID, categoryID uint64) (enabled bool, err error)
+ GetDirectorsSubscribedToCategoryDB(ctx context.Context, categoryID uint64) ([]*typescore.User, error)
+}
+
+// GetSubscribedCategoryIDsDB — список ID категорий, на которые подписан директор
+func (d *DirectorNotificationDB) GetSubscribedCategoryIDsDB(ctx context.Context, directorID uint64) ([]uint64, error) {
+ sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Select("category_id").
+ From("director_notification_subscriptions").
+ Where(squirrel.Eq{"director_id": directorID}).
+ 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 ids []uint64
+ for rows.Next() {
+ var id uint64
+ if err := rows.Scan(&id); err != nil {
+ continue
+ }
+ ids = append(ids, id)
+ }
+ return ids, nil
+}
+
+// ToggleSubscriptionDB — переключает подписку директора на категорию.
+// Если подписки не было — создаёт (enabled=true). Если была — удаляет (enabled=false).
+func (d *DirectorNotificationDB) ToggleSubscriptionDB(ctx context.Context, directorID, categoryID uint64) (bool, error) {
+ checkSQL, checkArgs, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Select("id").
+ From("director_notification_subscriptions").
+ Where(squirrel.Eq{"director_id": directorID, "category_id": categoryID}).
+ ToSql()
+ if err != nil {
+ return false, err
+ }
+
+ var existingID uint64
+ err = d.pool.QueryRow(ctx, checkSQL, checkArgs...).Scan(&existingID)
+
+ if err == nil {
+ // Подписка есть — удаляем (выключаем)
+ delSQL, delArgs, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Delete("director_notification_subscriptions").
+ Where(squirrel.Eq{"id": existingID}).
+ ToSql()
+ if err != nil {
+ return false, err
+ }
+ _, err = d.pool.Exec(ctx, delSQL, delArgs...)
+ return false, err
+ }
+
+ // Подписки нет — создаём (включаем)
+ insSQL, insArgs, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Insert("director_notification_subscriptions").
+ Columns("director_id", "category_id").
+ Values(directorID, categoryID).
+ ToSql()
+ if err != nil {
+ return false, err
+ }
+ _, err = d.pool.Exec(ctx, insSQL, insArgs...)
+ return true, err
+}
+
+// GetDirectorsSubscribedToCategoryDB — все директора, подписанные на указанную категорию
+func (d *DirectorNotificationDB) GetDirectorsSubscribedToCategoryDB(ctx context.Context, categoryID uint64) ([]*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("director_notification_subscriptions dns ON dns.director_id = u.id").
+ Where(squirrel.Eq{"r.is_director": true}).
+ Where(squirrel.Eq{"u.is_blocked": false}).
+ Where(squirrel.Eq{"dns.category_id": categoryID}).
+ 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 users []*typescore.User
+ for rows.Next() {
+ user := &typescore.User{}
+ if err := dbutils.ScanRowsToStructRows(rows, user, nil); err != nil {
+ continue
+ }
+ users = append(users, user)
+ }
+ return users, nil
+}
diff --git a/core/db/methods/monthly_orders.go b/core/db/methods/monthly_orders.go
new file mode 100644
index 0000000..25fc5eb
--- /dev/null
+++ b/core/db/methods/monthly_orders.go
@@ -0,0 +1,508 @@
+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"
+)
+
+type MonthlyOrderDB struct {
+ pool *pgxpool.Pool
+}
+
+func NewMonthlyOrderDB(pool *pgxpool.Pool) *MonthlyOrderDB {
+ return &MonthlyOrderDB{pool: pool}
+}
+
+type OrderFilterOptions struct {
+ ManagerID *uint64
+ Month *int
+ Year *int
+ Status *string
+ OrderType *string
+}
+
+// GetFilteredClientOrdersDB получает заказы с опциональной фильтрацией в SQL
+func (db *MonthlyOrderDB) GetFilteredClientOrdersDB(ctx context.Context, opts OrderFilterOptions) ([]*typescore.MonthlyOrderClient, error) {
+ fields := dbutils.GetStructFieldsDB(&typescore.MonthlyOrderClient{}, string(dbcoretablenames.TableNameMonthlyOrderClients))
+
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Select(fields...).
+ From(string(dbcoretablenames.TableNameMonthlyOrderClients))
+
+ if opts.ManagerID != nil {
+ query = query.Where(squirrel.Eq{"manager_id": *opts.ManagerID})
+ }
+ if opts.Month != nil {
+ query = query.Where(squirrel.Eq{"month": *opts.Month})
+ }
+ if opts.Year != nil {
+ query = query.Where(squirrel.Eq{"year": *opts.Year})
+ }
+ if opts.Status != nil {
+ query = query.Where(squirrel.Eq{"status": *opts.Status})
+ }
+ if opts.OrderType != nil {
+ query = query.Where(squirrel.Eq{"order_type": *opts.OrderType})
+ }
+
+ sqlStr, args, err := query.ToSql()
+ if err != nil {
+ return nil, err
+ }
+
+ rows, err := db.pool.Query(ctx, sqlStr, args...)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ var orders []*typescore.MonthlyOrderClient
+ for rows.Next() {
+ order := &typescore.MonthlyOrderClient{}
+ if err := dbutils.ScanRowsToStructRows(rows, order, nil); err != nil {
+ return nil, err
+ }
+ orders = append(orders, order)
+ }
+
+ return orders, nil
+}
+
+func (db *MonthlyOrderDB) GetFilesByOrderIDDB(ctx context.Context, orderID uint64) ([]*typescore.MonthlyOrderFile, error) {
+ fields := dbutils.GetStructFieldsDB(&typescore.MonthlyOrderFile{}, "monthly_order_files")
+
+ sqlStr, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Select(fields...).
+ From("monthly_order_files").
+ Where(squirrel.Eq{"order_client_id": orderID}).
+ ToSql()
+
+ if err != nil {
+ return nil, err
+ }
+
+ rows, err := db.pool.Query(ctx, sqlStr, args...)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ var files []*typescore.MonthlyOrderFile
+ for rows.Next() {
+ file := &typescore.MonthlyOrderFile{}
+ if err := dbutils.ScanRowsToStructRows(rows, file, nil); err != nil {
+ return nil, err
+ }
+ files = append(files, file)
+ }
+
+ return files, nil
+}
+
+// GetCurrentSettings получает настройки заказа для указанного месяца и года
+func (db *MonthlyOrderDB) GetCurrentSettings(ctx context.Context, month, year int) (*typescore.MonthlyOrderSetting, error) {
+ fields := dbutils.GetStructFieldsDB(&typescore.MonthlyOrderSetting{}, string(dbcoretablenames.TableNameMonthlyOrderSettings))
+ sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Select(fields...).
+ From(string(dbcoretablenames.TableNameMonthlyOrderSettings)).
+ Where(squirrel.Eq{"month": month, "year": year}).
+ Limit(1).
+ ToSql()
+
+ if err != nil {
+ return nil, err
+ }
+
+ rows, err := db.pool.Query(ctx, sql, args...)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ if rows.Next() {
+ setting := &typescore.MonthlyOrderSetting{}
+ if err := dbutils.ScanRowsToStructRows(rows, setting, nil); err != nil {
+ return nil, err
+ }
+ return setting, nil
+ }
+ return nil, nil // Настройки еще не заданы
+}
+
+// SaveSettings сохраняет или обновляет настройки (для аналитика)
+func (db *MonthlyOrderDB) SaveSettings(ctx context.Context, tx pgx.Tx, setting *typescore.MonthlyOrderSetting) error {
+ if setting == nil {
+ return errors.New("setting is nil")
+ }
+
+ return dbutils.ExecuteTx(ctx, db.pool, tx, func(tx pgx.Tx) error {
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Insert(string(dbcoretablenames.TableNameMonthlyOrderSettings)).
+ Columns("month", "year", "deadline_date", "assembly_time_days").
+ Values(*setting.Month, *setting.Year, *setting.DeadlineDate, *setting.AssemblyTimeDays).
+ Suffix("ON CONFLICT (month, year) DO UPDATE SET deadline_date = EXCLUDED.deadline_date, assembly_time_days = EXCLUDED.assembly_time_days, updated_at = NOW()")
+
+ sqlV, args, err := query.ToSql()
+ if err != nil {
+ return err
+ }
+
+ _, err = tx.Exec(ctx, sqlV, args...)
+ return err
+ })
+}
+
+// SaveClientOrder сохраняет черновик или обновляет заказ менеджера с использованием UPSERT
+// SaveClientOrder сохраняет черновик или перезаписывает существующий заказ менеджера
+func (db *MonthlyOrderDB) SaveClientOrder(ctx context.Context, tx pgx.Tx, order *typescore.MonthlyOrderClient) (*typescore.MonthlyOrderClient, error) {
+ if order == nil {
+ return nil, errors.New("order is nil")
+ }
+
+ // 1. Проверяем обязательные поля
+ if order.ClientName == nil || *order.ClientName == "" {
+ return nil, errors.New("client_name is required")
+ }
+ if order.ManagerID == nil {
+ return nil, errors.New("manager_id is required")
+ }
+ if order.Month == nil || order.Year == nil {
+ return nil, errors.New("month and year are required")
+ }
+ if order.Status == nil {
+ defaultStatus := "draft"
+ order.Status = &defaultStatus
+ }
+
+ var insertedID uint64
+ err := dbutils.ExecuteTx(ctx, db.pool, tx, func(tx pgx.Tx) error {
+ var existingID uint64
+
+ // 2. Ищем существующую запись (по ID, если пришел, либо по уникальным полям заказа)
+ if order.ID != nil && *order.ID > 0 {
+ existingID = *order.ID
+ } else {
+ // ВАЖНО: убрали фильтр по status = "draft", чтобы находить уже существующие записи в любом статусе
+ querySelect := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Select("id").
+ From(string(dbcoretablenames.TableNameMonthlyOrderClients)).
+ Where(squirrel.Eq{
+ "manager_id": *order.ManagerID,
+ "month": *order.Month,
+ "year": *order.Year,
+ "client_name": *order.ClientName,
+ "order_type": order.OrderType,
+ })
+
+ sqlS, argsS, _ := querySelect.ToSql()
+ err := tx.QueryRow(ctx, sqlS, argsS...).Scan(&existingID)
+ if err != nil && err != pgx.ErrNoRows {
+ return err
+ }
+ }
+
+ if existingID == 0 {
+ // Записи нет — создаем новую
+ queryInsert := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Insert(string(dbcoretablenames.TableNameMonthlyOrderClients)).
+ Columns(
+ "manager_id",
+ "month",
+ "year",
+ "client_name",
+ "order_type",
+ "manager_comment",
+ "custom_reason",
+ "free_form_comment",
+ "decade",
+ "delivery",
+ "conditions",
+ "payment_form",
+ "status",
+ ).
+ Values(
+ *order.ManagerID,
+ *order.Month,
+ *order.Year,
+ *order.ClientName,
+ order.OrderType,
+ order.ManagerComment,
+ order.CustomReason,
+ order.FreeFormComment,
+ order.Decade,
+ order.Delivery,
+ order.Conditions,
+ order.PaymentForm,
+ *order.Status,
+ ).
+ Suffix("RETURNING id")
+
+ sqlI, argsI, _ := queryInsert.ToSql()
+ if err := tx.QueryRow(ctx, sqlI, argsI...).Scan(&insertedID); err != nil {
+ return err
+ }
+ } else {
+ // Запись есть — обновляем ее новыми значениями
+ queryUpdate := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Update(string(dbcoretablenames.TableNameMonthlyOrderClients)).
+ Set("order_type", order.OrderType).
+ Set("manager_comment", order.ManagerComment).
+ Set("custom_reason", order.CustomReason).
+ Set("free_form_comment", order.FreeFormComment).
+ Set("decade", order.Decade).
+ Set("delivery", order.Delivery).
+ Set("conditions", order.Conditions).
+ Set("payment_form", order.PaymentForm).
+ Set("approval_id", order.ApprovalID).
+ Set("status", *order.Status).
+ Set("updated_at", squirrel.Expr("NOW()")).
+ Where(squirrel.Eq{"id": existingID})
+
+ sqlU, argsU, _ := queryUpdate.ToSql()
+ if _, err := tx.Exec(ctx, sqlU, argsU...); err != nil {
+ return err
+ }
+ insertedID = existingID
+ }
+
+ order.ID = &insertedID
+
+ // 3. Перезаписываем товары
+ delSQL, delArgs, _ := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Delete(string(dbcoretablenames.TableNameMonthlyOrderItems)).
+ Where(squirrel.Eq{"order_client_id": insertedID}).
+ ToSql()
+
+ if _, err := tx.Exec(ctx, delSQL, delArgs...); err != nil {
+ return err
+ }
+
+ if len(order.Items) > 0 {
+ insertItems := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Insert(string(dbcoretablenames.TableNameMonthlyOrderItems)).
+ Columns("order_client_id", "nomenclature_name", "nomenclature_type", "quantity")
+
+ hasValidItems := false
+ for _, item := range order.Items {
+ if item.Quantity != nil && *item.Quantity > 0 {
+ insertItems = insertItems.Values(insertedID, item.NomenclatureName, item.NomenclatureType, item.Quantity)
+ hasValidItems = true
+ }
+ }
+
+ if hasValidItems {
+ iSQL, iArgs, err := insertItems.ToSql()
+ if err != nil {
+ return err
+ }
+ if _, err = tx.Exec(ctx, iSQL, iArgs...); err != nil {
+ return err
+ }
+ }
+ }
+
+ // 4. Перезаписываем файлы
+ delFilesSQL, delFilesArgs, _ := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Delete("monthly_order_files").
+ Where(squirrel.Eq{"order_client_id": insertedID}).
+ ToSql()
+
+ if _, err := tx.Exec(ctx, delFilesSQL, delFilesArgs...); err != nil {
+ return err
+ }
+
+ if len(order.Files) > 0 {
+ insertFiles := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Insert("monthly_order_files").
+ Columns("order_client_id", "file_name", "file_base64")
+
+ hasValidFiles := false
+ for _, f := range order.Files {
+ if f.FileBase64 != nil && *f.FileBase64 != "" {
+ insertFiles = insertFiles.Values(insertedID, f.FileName, f.FileBase64)
+ hasValidFiles = true
+ }
+ }
+
+ if hasValidFiles {
+ fSQL, fArgs, err := insertFiles.ToSql()
+ if err != nil {
+ return err
+ }
+ if _, err = tx.Exec(ctx, fSQL, fArgs...); err != nil {
+ return err
+ }
+ }
+ }
+
+ return nil
+ })
+
+ if err != nil {
+ return nil, err
+ }
+ return order, nil
+}
+
+// GetAllOrdersForMonthDB получает абсолютно все заказы за указанный месяц и год без фильтрации по менеджеру
+func (db *MonthlyOrderDB) GetAllOrdersForMonthDB(ctx context.Context, month, year int) ([]*typescore.MonthlyOrderClient, error) {
+ fields := dbutils.GetStructFieldsDB(&typescore.MonthlyOrderClient{}, string(dbcoretablenames.TableNameMonthlyOrderClients))
+
+ sqlStr, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Select(fields...).
+ From(string(dbcoretablenames.TableNameMonthlyOrderClients)).
+ Where(squirrel.Eq{"month": month, "year": year}).
+ ToSql()
+
+ if err != nil {
+ return nil, err
+ }
+
+ rows, err := db.pool.Query(ctx, sqlStr, args...)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ var orders []*typescore.MonthlyOrderClient
+ for rows.Next() {
+ order := &typescore.MonthlyOrderClient{}
+ if err := dbutils.ScanRowsToStructRows(rows, order, nil); err != nil {
+ return nil, err
+ }
+ orders = append(orders, order)
+ }
+
+ return orders, nil
+}
+
+// GetClientOrdersByManagerDB получает все заказы менеджера за указанный месяц и год
+func (db *MonthlyOrderDB) GetClientOrdersByManagerDB(ctx context.Context, managerID uint64, month, year int) ([]*typescore.MonthlyOrderClient, error) {
+ fields := dbutils.GetStructFieldsDB(&typescore.MonthlyOrderClient{}, string(dbcoretablenames.TableNameMonthlyOrderClients))
+
+ sqlStr, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Select(fields...).
+ From(string(dbcoretablenames.TableNameMonthlyOrderClients)).
+ Where(squirrel.Eq{"manager_id": managerID, "month": month, "year": year}).
+ ToSql()
+
+ if err != nil {
+ return nil, err
+ }
+
+ rows, err := db.pool.Query(ctx, sqlStr, args...)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ var orders []*typescore.MonthlyOrderClient
+ for rows.Next() {
+ order := &typescore.MonthlyOrderClient{}
+ if err := dbutils.ScanRowsToStructRows(rows, order, nil); err != nil {
+ return nil, err
+ }
+ orders = append(orders, order)
+ }
+
+ return orders, nil
+}
+
+// GetItemsForMonthDB - получает все товары для всех заказов месяца одним запросом
+func (db *MonthlyOrderDB) GetItemsForMonthDB(ctx context.Context, month, year int) (map[uint64][]*typescore.MonthlyOrderItem, error) {
+ // Делаем JOIN таблиц Items и Clients, чтобы вытащить только товары текущего месяца
+ sqlStr := `
+ SELECT i.id, i.order_client_id, i.nomenclature_name, i.nomenclature_type, i.quantity
+ FROM monthly_order_items i
+ JOIN monthly_order_clients c ON i.order_client_id = c.id
+ WHERE c.month = $1 AND c.year = $2
+ `
+ rows, err := db.pool.Query(ctx, sqlStr, month, year)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ itemsMap := make(map[uint64][]*typescore.MonthlyOrderItem)
+ for rows.Next() {
+ item := &typescore.MonthlyOrderItem{}
+ // Сканируем поля вручную (в порядке SELECT)
+ err := rows.Scan(&item.ID, &item.OrderClientID, &item.NomenclatureName, &item.NomenclatureType, &item.Quantity)
+ if err != nil {
+ return nil, err
+ }
+
+ if item.OrderClientID != nil {
+ itemsMap[*item.OrderClientID] = append(itemsMap[*item.OrderClientID], item)
+ }
+ }
+ return itemsMap, nil
+}
+
+// GetItemsByOrderIDDB получает позиции конкретного заказа (номенклатуру и количество)
+func (db *MonthlyOrderDB) GetItemsByOrderIDDB(ctx context.Context, orderID uint64) ([]*typescore.MonthlyOrderItem, error) {
+ fields := dbutils.GetStructFieldsDB(&typescore.MonthlyOrderItem{}, string(dbcoretablenames.TableNameMonthlyOrderItems))
+
+ sqlStr, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Select(fields...).
+ From(string(dbcoretablenames.TableNameMonthlyOrderItems)).
+ Where(squirrel.Eq{"order_client_id": orderID}).
+ ToSql()
+
+ if err != nil {
+ return nil, err
+ }
+
+ rows, err := db.pool.Query(ctx, sqlStr, args...)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ var items []*typescore.MonthlyOrderItem
+ for rows.Next() {
+ item := &typescore.MonthlyOrderItem{}
+ if err := dbutils.ScanRowsToStructRows(rows, item, nil); err != nil {
+ return nil, err
+ }
+ items = append(items, item)
+ }
+
+ return items, nil
+}
+
+// GetManagersWithDraftsDB получает список ID менеджеров, у которых есть черновики за указанный период
+func (db *MonthlyOrderDB) GetManagersWithDraftsDB(ctx context.Context, month, year int) ([]uint64, error) {
+ sqlStr, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Select("DISTINCT manager_id").
+ From(string(dbcoretablenames.TableNameMonthlyOrderClients)).
+ Where(squirrel.Eq{"month": month, "year": year, "status": "draft"}).
+ ToSql()
+
+ if err != nil {
+ return nil, err
+ }
+
+ rows, err := db.pool.Query(ctx, sqlStr, args...)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ var managerIDs []uint64
+ for rows.Next() {
+ var id uint64
+ if err := rows.Scan(&id); err != nil {
+ return nil, err
+ }
+ managerIDs = append(managerIDs, id)
+ }
+
+ return managerIDs, nil
+}
diff --git a/core/db/methods/notifications.go b/core/db/methods/notifications.go
new file mode 100644
index 0000000..7c5339b
--- /dev/null
+++ b/core/db/methods/notifications.go
@@ -0,0 +1,169 @@
+package dbcore
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ dbutils "bitrix_balancer_api/core/utilscore/db"
+ "context"
+ "github.com/Masterminds/squirrel"
+ "github.com/jackc/pgx/v5/pgxpool"
+)
+
+type NotificationDB struct {
+ pool *pgxpool.Pool
+}
+
+func NewNotificationDB(pool *pgxpool.Pool) *NotificationDB {
+ return &NotificationDB{pool: pool}
+}
+
+type NotificationDBI interface {
+ CreateNotificationDB(ctx context.Context, n *typescore.Notification) (*typescore.Notification, error)
+ UpdateNotificationDB(ctx context.Context, n *typescore.Notification) error
+ GetNotificationsListDB(ctx context.Context, opts typescore.ListDbOptions) ([]*typescore.Notification, uint64, error)
+ GetNotificationByIDDB(ctx context.Context, id uint64) (*typescore.Notification, error)
+
+ CreateNotificationRecipientsDB(ctx context.Context, recipients []*typescore.NotificationRecipient) error
+ UpdateNotificationRecipientDB(ctx context.Context, r *typescore.NotificationRecipient) error
+ GetNotificationRecipientsDB(ctx context.Context, notificationID uint64) ([]*typescore.NotificationRecipient, error)
+}
+
+func (n *NotificationDB) CreateNotificationDB(ctx context.Context, obj *typescore.Notification) (*typescore.Notification, error) {
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Insert("notifications")
+
+ sqlV, args, err := dbutils.GenerateInsertRequest(query, obj)
+ if err != nil {
+ return nil, err
+ }
+
+ var newID uint64
+ sqlStr := *sqlV + " RETURNING id"
+ err = n.pool.QueryRow(ctx, sqlStr, args...).Scan(&newID)
+ if err != nil {
+ return nil, err
+ }
+
+ obj.ID = &newID
+ return obj, nil
+}
+
+func (n *NotificationDB) UpdateNotificationDB(ctx context.Context, obj *typescore.Notification) error {
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Update("notifications")
+ query = dbutils.AddNonNullFieldsToQueryUpdate(query, *obj)
+ query = query.Where(squirrel.Eq{"id": obj.ID})
+
+ sql, args, err := query.ToSql()
+ if err != nil {
+ return err
+ }
+ _, err = n.pool.Exec(ctx, sql, args...)
+ return err
+}
+
+func (n *NotificationDB) GetNotificationsListDB(ctx context.Context, opts typescore.ListDbOptions) ([]*typescore.Notification, uint64, error) {
+ fields := dbutils.GetStructFieldsDB(&typescore.Notification{}, "notifications")
+ selectFields := append(fields, "COUNT(*) OVER() AS total_count")
+
+ query := dbutils.BuildSelectQuery("notifications", selectFields)
+ query = dbutils.SetterLimitAndOffsetQuery(query, opts.Offset, opts.Limit)
+ query = query.OrderBy("created_at DESC")
+
+ sql, args, err := query.ToSql()
+ if err != nil {
+ return nil, 0, err
+ }
+
+ rows, err := n.pool.Query(ctx, sql, args...)
+ if err != nil {
+ return nil, 0, err
+ }
+ defer rows.Close()
+
+ var result []*typescore.Notification
+ var total uint64
+ for rows.Next() {
+ obj := &typescore.Notification{}
+ if err := dbutils.ScanRowsToStructRows(rows, obj, &total); err != nil {
+ continue
+ }
+ result = append(result, obj)
+ }
+ return result, total, nil
+}
+
+func (n *NotificationDB) GetNotificationByIDDB(ctx context.Context, id uint64) (*typescore.Notification, error) {
+ list, _, err := n.GetNotificationsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.Notification{ID: &id},
+ })
+ if err != nil {
+ return nil, err
+ }
+ if len(list) == 0 {
+ return nil, nil
+ }
+ return list[0], nil
+}
+
+func (n *NotificationDB) CreateNotificationRecipientsDB(ctx context.Context, recipients []*typescore.NotificationRecipient) error {
+ if len(recipients) == 0 {
+ return nil
+ }
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Insert("notification_recipients").
+ Columns("notification_id", "user_id", "status")
+
+ for _, r := range recipients {
+ query = query.Values(*r.NotificationID, *r.UserID, *r.Status)
+ }
+
+ sql, args, err := query.ToSql()
+ if err != nil {
+ return err
+ }
+ _, err = n.pool.Exec(ctx, sql, args...)
+ return err
+}
+
+func (n *NotificationDB) UpdateNotificationRecipientDB(ctx context.Context, r *typescore.NotificationRecipient) error {
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Update("notification_recipients")
+ query = dbutils.AddNonNullFieldsToQueryUpdate(query, *r)
+ query = query.Where(squirrel.Eq{"id": r.ID})
+
+ sql, args, err := query.ToSql()
+ if err != nil {
+ return err
+ }
+ _, err = n.pool.Exec(ctx, sql, args...)
+ return err
+}
+
+func (n *NotificationDB) GetNotificationRecipientsDB(ctx context.Context, notificationID uint64) ([]*typescore.NotificationRecipient, error) {
+ fields := dbutils.GetStructFieldsDB(&typescore.NotificationRecipient{}, "notification_recipients")
+
+ sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Select(fields...).
+ From("notification_recipients").
+ Where(squirrel.Eq{"notification_id": notificationID}).
+ ToSql()
+ if err != nil {
+ return nil, err
+ }
+
+ rows, err := n.pool.Query(ctx, sql, args...)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ var result []*typescore.NotificationRecipient
+ for rows.Next() {
+ obj := &typescore.NotificationRecipient{}
+ if err := dbutils.ScanRowsToStructRows(rows, obj, nil); err != nil {
+ continue
+ }
+ result = append(result, obj)
+ }
+ return result, nil
+}
diff --git a/core/db/methods/permission.go b/core/db/methods/permission.go
index 9d3a7c5..09d38a2 100644
--- a/core/db/methods/permission.go
+++ b/core/db/methods/permission.go
@@ -184,7 +184,6 @@ func (u *PermissionDB) DeletePermissionDB(ctx context.Context, params *typescore
// 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).
diff --git a/core/db/methods/role.go b/core/db/methods/role.go
index 7428e9b..0db6e23 100644
--- a/core/db/methods/role.go
+++ b/core/db/methods/role.go
@@ -29,6 +29,7 @@ type RoleDBI interface {
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)
+ GetRolesByIDsDB(ctx context.Context, ids []uint64) ([]*typescore.Role, error)
}
func (u *RoleDB) GetRolesListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.Role, uint64, error) {
@@ -189,3 +190,42 @@ func (u *RoleDB) GetRoleByIDDB(ctx context.Context, id uint64) (*typescore.Role,
}
return roles[0], nil
}
+
+// GetRolesByIDsDB — пакетное получение ролей по списку ID (устраняет N+1)
+func (u *RoleDB) GetRolesByIDsDB(ctx context.Context, ids []uint64) ([]*typescore.Role, error) {
+ if len(ids) == 0 {
+ return nil, nil
+ }
+
+ fields := dbutils.GetStructFieldsDB(&typescore.Role{}, dbcoretablenames.TableNameRoles.ToString())
+
+ sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Select(fields...).
+ From(dbcoretablenames.TableNameRoles.ToString()).
+ Where(squirrel.Eq{"id": ids}).
+ 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 roles []*typescore.Role
+ for rows.Next() {
+ role := &typescore.Role{}
+ if err := dbutils.ScanRowsToStructRows(rows, role, nil); err != nil {
+ logrus.Warn("GetRolesByIDsDB:ScanRowsToStructRows", err)
+ continue
+ }
+ roles = append(roles, role)
+ }
+ if err = rows.Err(); err != nil {
+ return nil, err
+ }
+
+ return roles, nil
+}
diff --git a/core/db/methods/sms_log.go b/core/db/methods/sms_log.go
new file mode 100644
index 0000000..c40de9b
--- /dev/null
+++ b/core/db/methods/sms_log.go
@@ -0,0 +1,76 @@
+package dbcore
+
+import (
+ "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"
+ "time"
+)
+
+type SmsLogDB struct {
+ pool *pgxpool.Pool
+}
+
+func NewSmsLogDB(pool *pgxpool.Pool) *SmsLogDB {
+ return &SmsLogDB{pool: pool}
+}
+
+// CreateSmsLogDB сохраняет новую SMS в базу
+func (s *SmsLogDB) CreateSmsLogDB(ctx context.Context, tx pgx.Tx, obj *typescore.SmsLog) error {
+ if obj == nil {
+ return errors.New("SmsLog obj is nil")
+ }
+
+ err := dbutils.ExecuteTx(ctx, s.pool, tx, func(tx pgx.Tx) error {
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Insert("sms_logs")
+
+ sqlV, args, err := dbutils.GenerateInsertRequest(query, obj)
+ if err != nil {
+ return err
+ }
+
+ _, err = tx.Exec(ctx, *sqlV, args...)
+ return err
+ })
+
+ return err
+}
+
+// GetSmsLogsByDateRangeDB получает список SMS за период (для Google Script)
+func (s *SmsLogDB) GetSmsLogsByDateRangeDB(ctx context.Context, startDate, endDate time.Time) ([]*typescore.SmsLog, error) {
+ fields := dbutils.GetStructFieldsDB(&typescore.SmsLog{}, "sms_logs")
+
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Select(fields...).
+ From("sms_logs").
+ Where(squirrel.GtOrEq{"event_created": startDate}).
+ Where(squirrel.LtOrEq{"event_created": endDate}).
+ OrderBy("event_created DESC")
+
+ sqlStr, args, err := query.ToSql()
+ if err != nil {
+ return nil, err
+ }
+
+ rows, err := s.pool.Query(ctx, sqlStr, args...)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ var logs []*typescore.SmsLog
+ for rows.Next() {
+ log := &typescore.SmsLog{}
+ if err := dbutils.ScanRowsToStructRows(rows, log, nil); err != nil {
+ continue
+ }
+ logs = append(logs, log)
+ }
+
+ return logs, nil
+}
diff --git a/core/db/methods/task_delegation.go b/core/db/methods/task_delegation.go
new file mode 100644
index 0000000..dc6c6c8
--- /dev/null
+++ b/core/db/methods/task_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 TaskDelegationDB struct {
+ pool *pgxpool.Pool
+}
+
+func NewTaskDelegationDB(pool *pgxpool.Pool) *TaskDelegationDB {
+ return &TaskDelegationDB{
+ pool: pool,
+ }
+}
+
+type TaskDelegationDBI interface {
+ GetTaskDelegationsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.TaskDelegation, uint64, error)
+ CreateTaskDelegationDB(ctx context.Context, tx pgx.Tx, TaskDelegationObj *typescore.TaskDelegation, returnObj ...bool) (*typescore.TaskDelegation, pgx.Tx, error)
+ UpdateTaskDelegationDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.TaskDelegation, returnObj ...bool) (*typescore.TaskDelegation, pgx.Tx, error)
+ DeleteTaskDelegationDB(ctx context.Context, params *typescore.TaskDelegation) error
+ GetTaskDelegationByIDDB(ctx context.Context, id uint64) (*typescore.TaskDelegation, error)
+}
+
+func (u *TaskDelegationDB) GetTaskDelegationsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.TaskDelegation, uint64, error) {
+ fields := dbutils.GetStructFieldsDB(&typescore.TaskDelegation{}, dbcoretablenames.TableNameTaskDelegations.ToString())
+ selectFields := append(fields, "COUNT(*) OVER() AS total_count")
+
+ options, filter, err := dbutils.GetOptionsDB[typescore.TaskDelegation](opts...)
+ if err != nil {
+ return nil, 0, err
+ }
+
+ query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameTaskDelegations.ToString(), selectFields)
+ query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
+ query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameTaskDelegations.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 taskDelegations []*typescore.TaskDelegation
+ var totalCount uint64
+ for rows.Next() {
+ taskDelegation := &typescore.TaskDelegation{}
+ if err := dbutils.ScanRowsToStructRows(rows, taskDelegation, &totalCount); err != nil {
+ logrus.Warn("GetTaskDelegationsListDB:ScanRowsToStructRows", err)
+ continue
+ }
+ taskDelegations = append(taskDelegations, taskDelegation)
+ }
+
+ return taskDelegations, totalCount, nil
+}
+
+func (u *TaskDelegationDB) CreateTaskDelegationDB(ctx context.Context, tx pgx.Tx, taskDelegationObj *typescore.TaskDelegation, returnObj ...bool) (*typescore.TaskDelegation, pgx.Tx, error) {
+ if taskDelegationObj == nil {
+ return nil, nil, errors.New("TaskDelegation 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.TableNameTaskDelegations.ToString())
+
+ sqlV, args, err := dbutils.GenerateInsertRequest(query, taskDelegationObj)
+ 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.GetTaskDelegationByIDDB(ctx, insertedID)
+ return created, tx, err
+ }
+
+ return nil, tx, nil
+}
+
+func (u *TaskDelegationDB) UpdateTaskDelegationDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.TaskDelegation, returnObj ...bool) (*typescore.TaskDelegation, pgx.Tx, error) {
+ if paramsUpdate.ID == nil {
+ return nil, nil, errors.New("TaskDelegation obj is nil")
+ }
+
+ err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameTaskDelegations.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.TaskDelegation{ID: paramsUpdate.ID}}
+ getInfoUp, _, err := u.GetTaskDelegationsListDB(ctx, options)
+ if err != nil {
+ return nil, nil, err
+ }
+ if len(getInfoUp) > 0 {
+ return getInfoUp[0], tx, nil
+ }
+ }
+
+ return nil, tx, nil
+}
+
+func (u *TaskDelegationDB) DeleteTaskDelegationDB(ctx context.Context, params *typescore.TaskDelegation) error {
+ if params != nil && params.ID != nil {
+ query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Delete(dbcoretablenames.TableNameTaskDelegations.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("TaskDelegation obj is nil")
+ }
+}
+
+func (u *TaskDelegationDB) GetTaskDelegationByIDDB(ctx context.Context, id uint64) (*typescore.TaskDelegation, error) {
+ taskDelegations, _, err := u.GetTaskDelegationsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.TaskDelegation{ID: &id},
+ })
+ if err != nil {
+ return nil, err
+ }
+ if len(taskDelegations) == 0 {
+ return nil, nil
+ }
+ return taskDelegations[0], nil
+}
diff --git a/core/db/methods/user.go b/core/db/methods/user.go
index eb8ab34..dd325fe 100644
--- a/core/db/methods/user.go
+++ b/core/db/methods/user.go
@@ -6,10 +6,10 @@ import (
dbutils "bitrix_balancer_api/core/utilscore/db"
"context"
"errors"
+ "github.com/jackc/pgx/v5"
"github.com/sirupsen/logrus"
"github.com/Masterminds/squirrel"
- "github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
@@ -37,6 +37,14 @@ type UserDBI interface {
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)
+ GetObserversForApprovalDB(ctx context.Context, categoryCode string, topicID *uint64) ([]*typescore.User, error)
+ GetUsersListByRoleIDsDB(ctx context.Context, opts typescore.ListDbOptions, roleIDs []uint64) ([]*typescore.User, uint64, error)
+ GetUsersByIDsDB(ctx context.Context, ids []uint64) ([]*typescore.User, error)
+
+ IsControllerDB(ctx context.Context, userID uint64) (bool, error)
+ GetControllerObserversForApprovalDB(ctx context.Context, categoryCode string, topicID *uint64) ([]*typescore.User, error)
+ GetUsersByRoleFlagsDB(ctx context.Context, flags []string) ([]*typescore.User, error)
+ GetUsersByDepartmentIDsDB(ctx context.Context, departmentIDs []uint64) ([]*typescore.User, error)
}
func (u *UserDB) GetUsersListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.User, uint64, error) {
@@ -48,9 +56,27 @@ func (u *UserDB) GetUsersListDB(ctx context.Context, opts ...typescore.ListDbOpt
return nil, 0, err
}
+ // ✅ Сохраняем значение поиска и удаляем из LikeFields
+ searchName := ""
+ if options.LikeFields != nil && options.LikeFields["full_name"] != "" {
+ searchName = options.LikeFields["full_name"]
+ delete(options.LikeFields, "full_name")
+ }
+
+ // ✅ Обнуляем FullName в filter
+ filter.FullName = nil
+
query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameUsers.ToString(), selectFields)
query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
+
+ // ✅ Сначала добавляем условие поиска
+ if searchName != "" {
+ query = query.Where("LOWER(full_name) LIKE LOWER(?)", "%"+searchName+"%")
+ }
+
+ // ✅ Потом применяем остальные фильтры
query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameUsers.ToString())
+
query = query.OrderBy("created_at DESC")
sql, args, err := query.ToSql()
@@ -58,6 +84,8 @@ func (u *UserDB) GetUsersListDB(ctx context.Context, opts ...typescore.ListDbOpt
return nil, 0, err
}
+ logrus.Debugf("GetUsersListDB SQL: %s, Args: %v", sql, args)
+
rows, err := u.pool.Query(ctx, sql, args...)
if err != nil {
return nil, 0, err
@@ -358,6 +386,74 @@ func (u *UserDB) GetObserversForCategoryDB(ctx context.Context, categoryCode str
return result, nil
}
+// GetObserversForApprovalDB — возвращает наблюдателей для конкретной заявки.
+// Учитывает права как на категорию темы, так и на саму тему (topic_id).
+// Дубли устраняются через DISTINCT.
+func (u *UserDB) GetObserversForApprovalDB(
+ ctx context.Context,
+ categoryCode string,
+ topicID *uint64,
+) ([]*typescore.User, error) {
+ q := 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").
+ Where(squirrel.Eq{"r.is_observer": true}).
+ Where(squirrel.Eq{"p.action": "observe"}).
+ Where(squirrel.Eq{"u.is_blocked": false})
+
+ if topicID != nil {
+ // Логика:
+ // 1. Наблюдатели категории: topic_id IS NULL И category_id совпадает
+ // 2. Наблюдатели конкретной темы: topic_id совпадает (category игнорируем)
+ q = q.Where(squirrel.Or{
+ squirrel.And{
+ squirrel.Expr("p.topic_id IS NULL"),
+ squirrel.Expr(
+ "p.topic_category_id IN (SELECT id FROM approval_topic_categories WHERE code = ?)",
+ categoryCode,
+ ),
+ },
+ squirrel.Eq{"p.topic_id": *topicID},
+ })
+ } else {
+ // Если topicID не передан — fallback на старую логику (только по категории)
+ q = q.Join(
+ dbcoretablenames.TableNameApprovalTopicCategories.ToString() +
+ " c ON c.id = p.topic_category_id",
+ ).Where(squirrel.Eq{"c.code": categoryCode})
+ }
+
+ sql, args, err := q.ToSql()
+ if err != nil {
+ return nil, err
+ }
+
+ logrus.Infof("🔍 GetObserversForApprovalDB SQL: %s", sql)
+ logrus.Infof("🔍 GetObserversForApprovalDB Args: %v", args)
+
+ 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("GetObserversForApprovalDB:ScanRowsToStruct", err)
+ continue
+ }
+ result = append(result, usr)
+ }
+
+ logrus.Infof("✅ GetObserversForApprovalDB found %d observers", len(result))
+ 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.*").
@@ -389,3 +485,303 @@ func (u *UserDB) GetUsersByRoleCodeDB(ctx context.Context, roleCode string) ([]*
}
return users, nil
}
+
+// GetUsersListByRoleIDsDB - фильтрация пользователей по массиву ID ролей
+func (u *UserDB) GetUsersListByRoleIDsDB(ctx context.Context, opts typescore.ListDbOptions, roleIDs []uint64) ([]*typescore.User, uint64, error) {
+ if len(roleIDs) == 0 {
+ return u.GetUsersListDB(ctx, opts)
+ }
+
+ options, filter, err := dbutils.GetOptionsDB[typescore.User](opts)
+ if err != nil {
+ return nil, 0, err
+ }
+
+ searchName := ""
+ if options.LikeFields != nil && options.LikeFields["full_name"] != "" {
+ searchName = options.LikeFields["full_name"]
+ delete(options.LikeFields, "full_name")
+ }
+
+ filter.FullName = nil
+
+ logrus.Infof("🔍 GetUsersListByRoleIDsDB: searchName='%s', filter.FullName=%v, options.Offset=%d, options.Limit=%d",
+ searchName, filter.FullName, options.Offset, options.Limit)
+
+ countQuery := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Select("COUNT(DISTINCT u.id)").
+ From(dbcoretablenames.TableNameUsers.ToString() + " u").
+ Join(dbcoretablenames.TableNameUserRoles.ToString() + " ur ON ur.user_id = u.id").
+ Where(squirrel.Eq{"ur.role_id": roleIDs})
+
+ if searchName != "" {
+ countQuery = countQuery.Where("LOWER(u.full_name) LIKE LOWER(?)", "%"+searchName+"%")
+ }
+ countQuery = dbutils.ApplyFilters(countQuery, filter, options.LikeFields, dbcoretablenames.TableNameUsers.ToString())
+
+ countSQL, countArgs, err := countQuery.ToSql()
+ if err != nil {
+ return nil, 0, err
+ }
+
+ var totalCount uint64
+ err = u.pool.QueryRow(ctx, countSQL, countArgs...).Scan(&totalCount)
+ if err != nil {
+ logrus.Errorf("🔍 GetUsersListByRoleIDsDB Count error: %v", err)
+ return nil, 0, err
+ }
+
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Select("u.*").
+ From(dbcoretablenames.TableNameUsers.ToString() + " u").
+ Join(dbcoretablenames.TableNameUserRoles.ToString() + " ur ON ur.user_id = u.id").
+ Where(squirrel.Eq{"ur.role_id": roleIDs}).
+ GroupBy("u.id")
+
+ if searchName != "" {
+ query = query.Where("LOWER(u.full_name) LIKE LOWER(?)", "%"+searchName+"%")
+ }
+
+ query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameUsers.ToString())
+
+ query = query.OrderBy("u.created_at DESC")
+ query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
+
+ sql, args, err := query.ToSql()
+ if err != nil {
+ return nil, 0, err
+ }
+
+ rows, err := u.pool.Query(ctx, sql, args...)
+ if err != nil {
+ logrus.Errorf("🔍 GetUsersListByRoleIDsDB Query error: %v", err)
+ return nil, 0, 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("GetUsersListByRoleIDsDB:ScanRowsToStructRows", err)
+ continue
+ }
+ users = append(users, user)
+ }
+
+ if err = rows.Err(); err != nil {
+ return nil, 0, err
+ }
+
+ return users, totalCount, nil
+}
+
+// GetUsersByIDsDB — пакетное получение пользователей по списку ID (устраняет N+1)
+func (u *UserDB) GetUsersByIDsDB(ctx context.Context, ids []uint64) ([]*typescore.User, error) {
+ if len(ids) == 0 {
+ return nil, nil
+ }
+
+ fields := dbutils.GetStructFieldsDB(&typescore.User{}, dbcoretablenames.TableNameUsers.ToString())
+
+ sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Select(fields...).
+ From(dbcoretablenames.TableNameUsers.ToString()).
+ Where(squirrel.Eq{"id": ids}).
+ 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("GetUsersByIDsDB:ScanRowsToStructRows", err)
+ continue
+ }
+ users = append(users, user)
+ }
+ if err = rows.Err(); err != nil {
+ return nil, err
+ }
+
+ return users, nil
+}
+
+// IsControllerDB проверяет, есть ли у пользователя роль наблюдателя с флагом is_controller = true.
+func (u *UserDB) IsControllerDB(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}).
+ Where(squirrel.Eq{"r.is_controller": 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
+}
+
+// GetControllerObserversForApprovalDB — то же самое, что GetObserversForApprovalDB,
+// но только пользователи, у которых роль имеет флаг is_controller = true.
+func (u *UserDB) GetControllerObserversForApprovalDB(
+ ctx context.Context,
+ categoryCode string,
+ topicID *uint64,
+) ([]*typescore.User, error) {
+ q := 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").
+ Where(squirrel.Eq{"r.is_observer": true}).
+ Where(squirrel.Eq{"r.is_controller": true}).
+ Where(squirrel.Eq{"p.action": "observe"}).
+ Where(squirrel.Eq{"u.is_blocked": false})
+
+ if topicID != nil {
+ q = q.Where(squirrel.Or{
+ squirrel.And{
+ squirrel.Expr("p.topic_id IS NULL"),
+ squirrel.Expr(
+ "p.topic_category_id IN (SELECT id FROM approval_topic_categories WHERE code = ?)",
+ categoryCode,
+ ),
+ },
+ squirrel.Eq{"p.topic_id": *topicID},
+ })
+ } else {
+ q = q.Join(
+ dbcoretablenames.TableNameApprovalTopicCategories.ToString() +
+ " c ON c.id = p.topic_category_id",
+ ).Where(squirrel.Eq{"c.code": categoryCode})
+ }
+
+ 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 result []*typescore.User
+ for rows.Next() {
+ usr := &typescore.User{}
+ if err := dbutils.ScanRowsToStructRows(rows, usr, nil); err != nil {
+ logrus.Warn("GetControllerObserversForApprovalDB:ScanRowsToStruct", err)
+ continue
+ }
+ result = append(result, usr)
+ }
+ return result, nil
+}
+
+// GetUsersByRoleFlagsDB — пользователи, у которых есть роль с любым из указанных флагов
+// (is_director, is_approver, is_observer, is_executor, is_controller)
+func (u *UserDB) GetUsersByRoleFlagsDB(ctx context.Context, flags []string) ([]*typescore.User, error) {
+ if len(flags) == 0 {
+ return nil, nil
+ }
+
+ allowedFlags := map[string]string{
+ "director": "r.is_director",
+ "approver": "r.is_approver",
+ "observer": "r.is_observer",
+ "executor": "r.is_executor",
+ "controller": "r.is_controller",
+ }
+
+ var orConds squirrel.Or
+ for _, f := range flags {
+ if col, ok := allowedFlags[f]; ok {
+ orConds = append(orConds, squirrel.Expr(col+" = true"))
+ }
+ }
+ if len(orConds) == 0 {
+ return nil, nil
+ }
+
+ 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(orConds).
+ 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); err != nil {
+ logrus.Warn("GetUsersByRoleFlagsDB:ScanRowsToStructRows", err)
+ continue
+ }
+ users = append(users, user)
+ }
+ return users, nil
+}
+
+// GetUsersByDepartmentIDsDB — пользователи из списка отделов
+func (u *UserDB) GetUsersByDepartmentIDsDB(ctx context.Context, departmentIDs []uint64) ([]*typescore.User, error) {
+ if len(departmentIDs) == 0 {
+ return nil, nil
+ }
+
+ fields := dbutils.GetStructFieldsDB(&typescore.User{}, dbcoretablenames.TableNameUsers.ToString())
+
+ sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Select(fields...).
+ From(dbcoretablenames.TableNameUsers.ToString()).
+ Where(squirrel.Eq{"department_id": departmentIDs}).
+ Where(squirrel.Eq{"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); err != nil {
+ logrus.Warn("GetUsersByDepartmentIDsDB:ScanRowsToStructRows", 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
index 18db30c..15fb563 100644
--- a/core/db/methods/user_hierarchy.go
+++ b/core/db/methods/user_hierarchy.go
@@ -6,6 +6,7 @@ import (
dbutils "bitrix_balancer_api/core/utilscore/db"
"context"
"errors"
+ "fmt"
"github.com/sirupsen/logrus"
"github.com/Masterminds/squirrel"
@@ -28,8 +29,8 @@ type UserHierarchyDBI interface {
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)
+ GetApproversDB(ctx context.Context, subordinateID, departmentID, topicID, categoryID uint64, systems []string) ([]*typescore.User, error)
+ GetHierarchiesWithRelations(ctx context.Context, opts typescore.ListDbOptions, userStatuses ...string) ([]*typescore.UserHierarchy, uint64, error)
}
func (u *UserHierarchyDB) GetUserHierarchyListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.UserHierarchy, uint64, error) {
@@ -181,36 +182,76 @@ func (u *UserHierarchyDB) DeleteUserHierarchyDB(ctx context.Context, params *typ
return nil
}
-func (u *UserHierarchyDB) GetApproversDB(ctx context.Context, subordinateID, departmentID, topicID, categoryID uint64) ([]*typescore.User, error) {
+// GetApproversDB возвращает список согласующих для (subordinateID, departmentID,
+// topicID, categoryID), с учётом целевой системы (systems[0], если задана).
+// GetApproversDB возвращает список согласующих для (subordinateID, departmentID,
+// topicID, categoryID), с учётом целевой системы (systems[0], если задана).
+// ИСПОЛЬЗУЕТ КАСКАДНЫЙ ПОИСК: Точная тема -> Родительская тема -> Категория -> Глобальное правило
+// GetApproversDB возвращает список согласующих для (subordinateID, departmentID,
+// topicID, categoryID), с учётом целевой системы (systems[0], если задана).
+// ИСПОЛЬЗУЕТ КАСКАДНЫЙ ПОИСК: Точная тема -> Родительская тема -> Категория -> Глобальное правило
+func (u *UserHierarchyDB) GetApproversDB(
+ ctx context.Context,
+ subordinateID, departmentID, topicID, categoryID uint64,
+ systems []string,
+) ([]*typescore.User, error) {
+ system := ""
+ if len(systems) > 0 {
+ system = systems[0]
+ }
+
rawSQL := `
- WITH ranked AS (
+ WITH target_topic AS (
+ SELECT code, category_id FROM approval_topics WHERE id = $3
+ ),
+ matching_topics AS (
+ SELECT t.id, LENGTH(t.code) as spec_score
+ FROM approval_topics t
+ CROSS JOIN target_topic tt
+ WHERE strpos(tt.code || '_', t.code || '_') = 1
+ AND t.category_id = tt.category_id
+ ),
+ ranked AS (
SELECT
uh.approver_id,
uh.priority,
+ uh.target_system,
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
+ WHEN mt.id IS NOT NULL THEN 1000 - mt.spec_score
+ WHEN uh.topic_category_id = $4 AND uh.topic_id IS NULL THEN 2000
+ WHEN uh.topic_id IS NULL AND uh.topic_category_id IS NULL THEN 3000
END AS specificity
FROM user_hierarchy uh
+ LEFT JOIN matching_topics mt ON uh.topic_id = mt.id
WHERE uh.subordinate_id = $1
AND uh.department_id = $2
AND (
- uh.topic_id = $3
- OR uh.topic_category_id = $4
+ mt.id IS NOT NULL
+ OR (uh.topic_category_id = $4 AND uh.topic_id IS NULL)
OR (uh.topic_id IS NULL AND uh.topic_category_id IS NULL)
)
),
best AS (
- -- берём только уровень с наивысшей специфичностью
SELECT MIN(specificity) AS min_spec FROM ranked
+ ),
+ candidates AS (
+ SELECT r.approver_id, r.priority, r.target_system
+ FROM ranked r
+ JOIN best b ON r.specificity = b.min_spec
+ ),
+ system_choice AS (
+ SELECT EXISTS (
+ SELECT 1 FROM candidates c WHERE c.target_system = $5
+ ) AS has_override
)
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
+ FROM candidates c
+ CROSS JOIN system_choice sc
+ JOIN users u ON u.id = c.approver_id
+ WHERE
+ (sc.has_override AND c.target_system = $5)
+ OR (NOT sc.has_override AND (c.target_system IS NULL OR c.target_system = 'all'))
+ ORDER BY c.priority ASC
`
rows, err := u.pool.Query(ctx, rawSQL,
@@ -218,37 +259,62 @@ func (u *UserHierarchyDB) GetApproversDB(ctx context.Context, subordinateID, dep
departmentID,
topicID,
categoryID,
+ system,
)
if err != nil {
return nil, err
}
defer rows.Close()
- var result []*typescore.User
+ var approvers []*typescore.User
+ seen := make(map[uint64]bool)
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)
+ if usr.ID == nil || seen[*usr.ID] {
+ continue
+ }
+ seen[*usr.ID] = true
+ approvers = append(approvers, usr)
}
- return result, nil
+
+ logrus.Infof("✅ GetApproversDB DONE: Найдено уникальных согласующих: %d", len(approvers))
+ return approvers, nil
}
-func (u *UserHierarchyDB) GetHierarchiesWithRelations(ctx context.Context, opts typescore.ListDbOptions) ([]*typescore.UserHierarchy, uint64, error) {
+// GetHierarchiesWithRelations(ctx context.Context, opts typescore.ListDbOptions, userStatus string) ([]*typescore.UserHierarchy, uint64, error)
+func (u *UserHierarchyDB) GetHierarchiesWithRelations(ctx context.Context, opts typescore.ListDbOptions, userStatuses ...string) ([]*typescore.UserHierarchy, uint64, error) {
options, filter, err := dbutils.GetOptionsDB[typescore.UserHierarchy](opts)
if err != nil {
return nil, 0, err
}
- query := squirrel.Select("uh.*",
- "sub.id", "sub.full_name", "sub.username", // поля Subordinate
- "app.id", "app.full_name", "app.username", // поля Approver
- "dep.id", "dep.name", // поля Department
- "cat.id", "cat.name", // поля Category
- "top.id", "top.name", // поля Topic
- "COUNT(*) OVER() AS total_count").
+ userStatus := ""
+ if len(userStatuses) > 0 {
+ userStatus = userStatuses[0]
+ }
+
+ query := squirrel.Select(
+ "uh.id",
+ "uh.subordinate_id",
+ "uh.approver_id",
+ "uh.department_id",
+ "uh.topic_category_id",
+ "uh.topic_id",
+ "uh.priority",
+ "uh.target_system",
+ "uh.created_at",
+ "uh.updated_at",
+ "sub.id", "sub.full_name", "sub.username", "sub.is_blocked", "sub.is_fired",
+ "app.id", "app.full_name", "app.username", "app.is_blocked", "app.is_fired",
+ "dep.id", "dep.name",
+ "cat.id", "cat.name",
+ "top.id", "top.name",
+ "COUNT(*) OVER() AS total_count",
+ ).
From("user_hierarchy uh").
LeftJoin("users sub ON uh.subordinate_id = sub.id").
LeftJoin("users app ON uh.approver_id = app.id").
@@ -257,8 +323,52 @@ func (u *UserHierarchyDB) GetHierarchiesWithRelations(ctx context.Context, opts
LeftJoin("approval_topics top ON uh.topic_id = top.id")
query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
- query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameUserHierarchy.ToString())
- query = query.OrderBy("created_at DESC")
+
+ // 1. Фильтр по сотруднику (инициатору)
+ if filter.SubordinateID != nil {
+ query = query.Where(squirrel.Eq{"uh.subordinate_id": *filter.SubordinateID})
+ }
+
+ // 2. Фильтр по согласующему: ищем ВСЮ цепочку, где этот пользователь является согласующим хотя бы на одном шаге
+ if filter.ApproverID != nil {
+ query = query.Where(squirrel.Expr(`
+ EXISTS (
+ SELECT 1 FROM user_hierarchy uh2
+ WHERE uh2.approver_id = ?
+ AND uh2.subordinate_id = uh.subordinate_id
+ AND uh2.department_id = uh.department_id
+ AND COALESCE(uh2.topic_category_id, 0) = COALESCE(uh.topic_category_id, 0)
+ AND COALESCE(uh2.topic_id, 0) = COALESCE(uh.topic_id, 0)
+ )
+ `, *filter.ApproverID))
+ }
+
+ // 3. Фильтр по отделу
+ if filter.DepartmentID != nil {
+ query = query.Where(squirrel.Eq{"uh.department_id": *filter.DepartmentID})
+ }
+
+ // 4. Починка поиска по категории: категория + все темы внутри этой категории
+ if filter.TopicID != nil {
+ query = query.Where(squirrel.Eq{"uh.topic_id": *filter.TopicID})
+ } else if filter.TopicCategoryID != nil {
+ query = query.Where(squirrel.Or{
+ squirrel.Eq{"uh.topic_category_id": *filter.TopicCategoryID},
+ squirrel.Eq{"top.category_id": *filter.TopicCategoryID},
+ })
+ }
+
+ // 5. Фильтр по статусу пользователя (сотрудника)
+ switch userStatus {
+ case "active":
+ query = query.Where("COALESCE(sub.is_blocked, false) = false AND COALESCE(sub.is_fired, false) = false")
+ case "fired":
+ query = query.Where("COALESCE(sub.is_fired, false) = true")
+ case "blocked":
+ query = query.Where("COALESCE(sub.is_blocked, false) = true")
+ }
+
+ query = query.OrderBy("uh.created_at DESC")
sql, args, err := query.PlaceholderFormat(squirrel.Dollar).ToSql()
if err != nil {
@@ -275,25 +385,28 @@ func (u *UserHierarchyDB) GetHierarchiesWithRelations(ctx context.Context, opts
var totalCount uint64
for rows.Next() {
- h := &typescore.UserHierarchy{}
- h.Subordinate = &typescore.User{}
- h.Approver = &typescore.User{}
- h.Department = &typescore.Department{}
- h.TopicCategory = &typescore.ApprovalTopicCategory{}
- h.Topic = &typescore.ApprovalTopic{}
+ h := &typescore.UserHierarchy{
+ Subordinate: &typescore.User{},
+ Approver: &typescore.User{},
+ Department: &typescore.Department{},
+ TopicCategory: &typescore.ApprovalTopicCategory{},
+ Topic: &typescore.ApprovalTopic{},
+ }
- // Сканируем все поля в соответствующие структуры
err := rows.Scan(
- &h.ID, &h.SubordinateID, &h.ApproverID, &h.DepartmentID, &h.TopicCategoryID, &h.TopicID, &h.Priority, &h.CreatedAt, &h.UpdatedAt,
- &h.Subordinate.ID, &h.Subordinate.FullName, &h.Subordinate.Username,
- &h.Approver.ID, &h.Approver.FullName, &h.Approver.Username,
+ &h.ID, &h.SubordinateID, &h.ApproverID, &h.DepartmentID,
+ &h.TopicCategoryID, &h.TopicID, &h.Priority,
+ &h.TargetSystem,
+ &h.CreatedAt, &h.UpdatedAt,
+ &h.Subordinate.ID, &h.Subordinate.FullName, &h.Subordinate.Username, &h.Subordinate.IsBlocked, &h.Subordinate.IsFired,
+ &h.Approver.ID, &h.Approver.FullName, &h.Approver.Username, &h.Approver.IsBlocked, &h.Approver.IsFired,
&h.Department.ID, &h.Department.Name,
&h.TopicCategory.ID, &h.TopicCategory.Name,
&h.Topic.ID, &h.Topic.Name,
&totalCount,
)
if err != nil {
- continue
+ return nil, 0, fmt.Errorf("scan error: %w", err)
}
results = append(results, h)
}
diff --git a/core/db/methods/user_role.go b/core/db/methods/user_role.go
index f34e980..d101f1b 100644
--- a/core/db/methods/user_role.go
+++ b/core/db/methods/user_role.go
@@ -28,6 +28,7 @@ type UserRoleDBI interface {
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
+ CreateUserRolesBulkDB(ctx context.Context, tx pgx.Tx, userID uint64, roleIDs []uint64) ([]*typescore.UserRole, error)
}
func (u *UserRoleDB) GetUserRolesListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.UserRole, uint64, error) {
@@ -178,3 +179,86 @@ func (u *UserRoleDB) DeleteUserRoleDB(ctx context.Context, params *typescore.Use
return errors.New("userRole obj is nil")
}
}
+
+// GetUserRolesByUserIDsDB — пакетное получение ролей сразу для нескольких пользователей (устраняет N+1)
+func (ur *UserRoleDB) GetUserRolesByUserIDsDB(ctx context.Context, userIDs []uint64) ([]*typescore.UserRole, error) {
+ if len(userIDs) == 0 {
+ return nil, nil
+ }
+
+ fields := dbutils.GetStructFieldsDB(&typescore.UserRole{}, dbcoretablenames.TableNameUserRoles.ToString())
+
+ sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Select(fields...).
+ From(dbcoretablenames.TableNameUserRoles.ToString()).
+ Where(squirrel.Eq{"user_id": userIDs}).
+ ToSql()
+ if err != nil {
+ return nil, err
+ }
+
+ rows, err := ur.pool.Query(ctx, sql, args...)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ var result []*typescore.UserRole
+ for rows.Next() {
+ item := &typescore.UserRole{}
+ if err := dbutils.ScanRowsToStructRows(rows, item, nil); err != nil {
+ logrus.Warn("GetUserRolesByUserIDsDB:ScanRowsToStructRows", err)
+ continue
+ }
+ result = append(result, item)
+ }
+ if err = rows.Err(); err != nil {
+ return nil, err
+ }
+
+ return result, nil
+}
+
+// DeleteUserRolesByUserIDDB — удаляет все роли пользователя одним запросом вместо цикла DELETE
+func (ur *UserRoleDB) DeleteUserRolesByUserIDDB(ctx context.Context, userID uint64) error {
+ sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Delete(dbcoretablenames.TableNameUserRoles.ToString()).
+ Where(squirrel.Eq{"user_id": userID}).
+ ToSql()
+ if err != nil {
+ return err
+ }
+
+ _, err = ur.pool.Exec(ctx, sql, args...)
+ return err
+}
+
+// CreateUserRolesBulkDB — вставляет сразу несколько ролей одним multi-row INSERT вместо цикла
+func (ur *UserRoleDB) CreateUserRolesBulkDB(ctx context.Context, tx pgx.Tx, userID uint64, roleIDs []uint64) ([]*typescore.UserRole, error) {
+ if len(roleIDs) == 0 {
+ return nil, nil
+ }
+
+ err := dbutils.ExecuteTx(ctx, ur.pool, tx, func(tx pgx.Tx) error {
+ query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
+ Insert(dbcoretablenames.TableNameUserRoles.ToString()).
+ Columns("user_id", "role_id")
+
+ for _, roleID := range roleIDs {
+ query = query.Values(userID, roleID)
+ }
+
+ sql, args, err := query.ToSql()
+ if err != nil {
+ return err
+ }
+
+ _, err = tx.Exec(ctx, sql, args...)
+ return err
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ return ur.GetUserRolesByUserIDsDB(ctx, []uint64{userID})
+}
diff --git a/core/db/table_names/table_names.go b/core/db/table_names/table_names.go
index 42b6f4e..0e09d75 100644
--- a/core/db/table_names/table_names.go
+++ b/core/db/table_names/table_names.go
@@ -3,26 +3,39 @@ 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"
+ 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"
+ TableNameNotifications TableName = "notifications"
+ TableNameNotificationsRecipients TableName = "notification_recipients"
+ TableNameDirectorNotificationSubscriptions TableName = "director_notification_subscriptions"
+ TableNameApprovalTaskTransfers TableName = "approval_task_transfers"
+ TableNameApprovalRevocationRequests TableName = "approval_revocation_requests"
+ TableNameApprovalRevocationApprovers TableName = "approval_revocation_approvers"
+ TableNameApprovalFlowNodes TableName = "approval_flow_nodes"
+ TableNameAdminActionLogs TableName = "admin_action_logs"
+ TableNameMonthlyOrderSettings TableName = "monthly_order_settings"
+ TableNameMonthlyOrderClients TableName = "monthly_order_clients"
+ TableNameMonthlyOrderItems TableName = "monthly_order_items"
+ TableNameMonthlyOrderFiles TableName = "monthly_order_files"
+ TableNameTaskDelegations TableName = "task_delegations"
)
func (t TableName) ToString() string {
diff --git a/core/go.mod b/core/go.mod
index bcc1b46..d091b21 100644
--- a/core/go.mod
+++ b/core/go.mod
@@ -13,18 +13,27 @@ require (
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
+ golang.org/x/crypto v0.54.0
+ golang.org/x/net v0.57.0
gopkg.in/yaml.v3 v3.0.1
gorm.io/driver/postgres v1.6.0
gorm.io/gorm v1.31.1
)
require (
+ cloud.google.com/go/auth v0.23.0 // indirect
+ cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect
+ cloud.google.com/go/compute/metadata v0.9.0 // 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/felixge/httpsnoop v1.0.4 // indirect
+ github.com/go-jose/go-jose/v4 v4.1.4 // indirect
+ github.com/go-logr/logr v1.4.3 // indirect
+ github.com/go-logr/stdr v1.2.2 // indirect
+ github.com/google/s2a-go v0.1.9 // indirect
+ github.com/googleapis/enterprise-certificate-proxy v0.3.20 // indirect
+ github.com/googleapis/gax-go/v2 v2.23.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
@@ -45,9 +54,19 @@ require (
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.opentelemetry.io/auto/sdk v1.2.1 // indirect
+ go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0 // indirect
+ go.opentelemetry.io/otel v1.44.0 // indirect
+ go.opentelemetry.io/otel/metric v1.44.0 // indirect
+ go.opentelemetry.io/otel/trace v1.44.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
+ golang.org/x/oauth2 v0.36.0 // indirect
+ golang.org/x/sync v0.22.0 // indirect
+ golang.org/x/sys v0.47.0 // indirect
+ golang.org/x/text v0.40.0 // indirect
+ golang.org/x/time v0.15.0 // indirect
+ google.golang.org/api v0.293.0 // indirect
+ google.golang.org/genproto/googleapis/rpc v0.0.0-20260807164820-c8921c73eeea // indirect
+ google.golang.org/grpc v1.83.0 // indirect
+ google.golang.org/protobuf v1.36.11 // indirect
)
diff --git a/core/go.sum b/core/go.sum
index 34ff3d7..3342705 100644
--- a/core/go.sum
+++ b/core/go.sum
@@ -1,3 +1,9 @@
+cloud.google.com/go/auth v0.23.0 h1:6Gg1CMgpgubRG7DGz5Vf1pcoNo8RfiRiRAPS4crTp54=
+cloud.google.com/go/auth v0.23.0/go.mod h1:4DhBRcqvtljQN3dJ57qtqbib5ZGCYE5f2crfiiC2EM0=
+cloud.google.com/go/auth/oauth2adapt v0.2.8 h1:keo8NaayQZ6wimpNSmW5OPc283g65QNIiLpZnkHRbnc=
+cloud.google.com/go/auth/oauth2adapt v0.2.8/go.mod h1:XQ9y31RkqZCcwJWNSx2Xvric3RrU88hAYYbjDWYDL+c=
+cloud.google.com/go/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdBtwLoEkH9Zs=
+cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10=
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=
@@ -16,16 +22,30 @@ github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/r
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/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
+github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
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-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
+github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
+github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
+github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
+github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
+github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
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/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0=
+github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM=
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/googleapis/enterprise-certificate-proxy v0.3.20 h1:t/xL64VUoN69MuMRQuJETqYGOw4Z9mSRJK9epIEtwFk=
+github.com/googleapis/enterprise-certificate-proxy v0.3.20/go.mod h1:L3D/IQExI6LqEjBdXcZQ1WluSgigQmSwBboFstVPM4w=
+github.com/googleapis/gax-go/v2 v2.23.0 h1:Tchl7qkvE7Ip3y+ztvNufYFvkfqTe7NfLTYGIdJRLuE=
+github.com/googleapis/gax-go/v2 v2.23.0/go.mod h1:rBQKOVJCdb8IFEzg+FCwlt1LP/xMDGuqUXhUG+XMXEg=
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=
@@ -99,20 +119,52 @@ github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu
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.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
+go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
+go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0 h1:OyrsyzuttWTSur2qN/Lm0m2a8yqyIjUVBZcxFPuXq2o=
+go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0/go.mod h1:C2NGBr+kAB4bk3xtMXfZ94gqFDtg/GkI7e9zqGh5Beg=
+go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU=
+go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc=
+go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc=
+go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo=
+go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk=
+go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE=
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.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
+golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
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.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE=
+golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=
+golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs=
+golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
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.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
+golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
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/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
+golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
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.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
+golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
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/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
+golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
+google.golang.org/api v0.293.0 h1:p9XIWOf63U4OgYx120ZwVU8+vl4XTPmWfgVPnmOAS9w=
+google.golang.org/api v0.293.0/go.mod h1:6n5tjEB1gzwniZTepZ0g5u+wM7Bof5GeULCx/zh8ZE0=
+google.golang.org/genproto/googleapis/rpc v0.0.0-20260807164820-c8921c73eeea h1:kVhQEPTpKQahD5+JSBTfBB19wcgQTTjAIn45MBqnyHk=
+google.golang.org/genproto/googleapis/rpc v0.0.0-20260807164820-c8921c73eeea/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
+google.golang.org/grpc v1.83.0 h1:JeNZEKJFbQxArAMl+hiytHauacDNqJUllNfmIMmpqnQ=
+google.golang.org/grpc v1.83.0/go.mod h1:kDyl6SKsiHKt0uylY5gtn5cEjkrIOhQOGDgIc4JGwzQ=
+google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
+google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
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=
diff --git a/core/lib/external/googlesheets/sheets.go b/core/lib/external/googlesheets/sheets.go
new file mode 100644
index 0000000..8d578ff
--- /dev/null
+++ b/core/lib/external/googlesheets/sheets.go
@@ -0,0 +1,200 @@
+package googlesheets
+
+import (
+ "context"
+ "fmt"
+ "google.golang.org/api/drive/v3"
+ "strings"
+ "time"
+
+ "golang.org/x/oauth2/google"
+ "google.golang.org/api/option"
+ "google.golang.org/api/sheets/v4"
+)
+
+type Client struct {
+ srv *sheets.Service
+ driveSrv *drive.Service
+}
+
+func NewClient(ctx context.Context, credentialsJSON []byte) (*Client, error) {
+ if len(credentialsJSON) == 0 {
+ return nil, fmt.Errorf("google-creds.json is empty")
+ }
+
+ creds, err := google.CredentialsFromJSON(ctx, credentialsJSON, sheets.SpreadsheetsScope, drive.DriveScope)
+ if err != nil {
+ return nil, fmt.Errorf("invalid google-creds.json format: %v", err)
+ }
+
+ srv, err := sheets.NewService(ctx, option.WithCredentials(creds))
+ if err != nil {
+ return nil, err
+ }
+
+ driveSrv, err := drive.NewService(ctx, option.WithCredentials(creds))
+ if err != nil {
+ return nil, err
+ }
+
+ return &Client{srv: srv, driveSrv: driveSrv}, nil
+}
+
+func (c *Client) ExportMonthlyReportToMasterSheet(ctx context.Context, spreadsheetID string, sheet1Data, sheet2Data [][]interface{}) (string, error) {
+ monthYearTitle := time.Now().Format("January 2006") // Например: "August 2026"
+ ordersSheetName := "Заказы - " + monthYearTitle
+ commentsSheetName := "Комментарии - " + monthYearTitle
+
+ // 1. Получаем структуру мастер-таблицы
+ spreadsheet, err := c.srv.Spreadsheets.Get(spreadsheetID).Context(ctx).Do()
+ if err != nil {
+ return "", fmt.Errorf("не удалось получить доступ к мастер-таблице: %v", err)
+ }
+
+ existingSheets := make(map[string]int64)
+ for _, sheet := range spreadsheet.Sheets {
+ existingSheets[sheet.Properties.Title] = sheet.Properties.SheetId
+ }
+
+ // 2. Создаем или очищаем листы текущего месяца
+ ensureSheet := func(title string) error {
+ if _, exists := existingSheets[title]; exists {
+ clearReq := &sheets.ClearValuesRequest{}
+ _, err := c.srv.Spreadsheets.Values.Clear(spreadsheetID, title+"!A1:Z10000", clearReq).Context(ctx).Do()
+ return err
+ } else {
+ addReq := &sheets.AddSheetRequest{
+ Properties: &sheets.SheetProperties{Title: title},
+ }
+ batchReq := &sheets.BatchUpdateSpreadsheetRequest{
+ Requests: []*sheets.Request{{AddSheet: addReq}},
+ }
+ _, err := c.srv.Spreadsheets.BatchUpdate(spreadsheetID, batchReq).Context(ctx).Do()
+ return err
+ }
+ }
+
+ if err := ensureSheet(ordersSheetName); err != nil {
+ return "", fmt.Errorf("ошибка подготовки листа заказов: %v", err)
+ }
+ if err := ensureSheet(commentsSheetName); err != nil {
+ return "", fmt.Errorf("ошибка подготовки листа комментариев: %v", err)
+ }
+
+ // 3. Заливаем данные
+ var data []*sheets.ValueRange
+ data = append(data, &sheets.ValueRange{Range: ordersSheetName + "!A1", Values: sheet1Data})
+ data = append(data, &sheets.ValueRange{Range: commentsSheetName + "!A1", Values: sheet2Data})
+
+ batchUpdateReq := &sheets.BatchUpdateValuesRequest{
+ ValueInputOption: "USER_ENTERED",
+ Data: data,
+ }
+
+ _, err = c.srv.Spreadsheets.Values.BatchUpdate(spreadsheetID, batchUpdateReq).Context(ctx).Do()
+ if err != nil {
+ return "", fmt.Errorf("ошибка записи данных в таблицу: %v", err)
+ }
+
+ // Возвращаем постоянную ссылку на таблицу
+ return fmt.Sprintf("https://docs.google.com/spreadsheets/d/%s", spreadsheetID), nil
+}
+
+// FetchNomenclature вытягивает справочник товаров
+func (c *Client) FetchNomenclature(spreadsheetID string) ([]NomenclatureItem, error) {
+ resp, err := c.srv.Spreadsheets.Values.Get(spreadsheetID, "A:B").Do()
+ if err != nil {
+ return nil, err
+ }
+
+ var items []NomenclatureItem
+ for i, row := range resp.Values {
+ if i == 0 {
+ continue // Пропускаем заголовок
+ }
+ if len(row) > 0 {
+ name := fmt.Sprintf("%v", row[0])
+ itemType := ""
+ if len(row) > 1 {
+ itemType = fmt.Sprintf("%v", row[1])
+ }
+ if strings.TrimSpace(name) != "" {
+ items = append(items, NomenclatureItem{Name: name, Type: itemType})
+ }
+ }
+ }
+ return items, nil
+}
+
+// FetchActiveClientsForManager вытягивает действующих клиентов для конкретного менеджера
+func (c *Client) FetchActiveClientsForManager(spreadsheetID, managerName string) ([]ClientItem, error) {
+ // Расширяем диапазон до DB, чтобы захватить столбец филиала
+ resp, err := c.srv.Spreadsheets.Values.Get(spreadsheetID, "A:DB").Do()
+ if err != nil {
+ return nil, err
+ }
+
+ var clients []ClientItem
+ for i, row := range resp.Values {
+ if i == 0 {
+ continue // Пропускаем заголовок
+ }
+
+ // Убеждаемся, что строка достаточно длинная (индекс 74 для Status)
+ if len(row) > 74 {
+ clientName := fmt.Sprintf("%v", row[1]) // Столбец B
+ manager := fmt.Sprintf("%v", row[24]) // Столбец Y
+ status := fmt.Sprintf("%v", row[74]) // Столбец BW
+
+ // Пытаемся достать филиал из столбца DB (индекс 105).
+ // Проверяем длину строки, так как в Go Sheets API пустые ячейки в конце строки обрезаются.
+ branch := ""
+ if len(row) > 105 {
+ branch = fmt.Sprintf("%v", row[105])
+ }
+
+ if strings.Contains(strings.ToLower(status), "действующий") &&
+ strings.EqualFold(strings.TrimSpace(manager), strings.TrimSpace(managerName)) {
+ clients = append(clients, ClientItem{
+ Name: clientName,
+ Manager: manager,
+ Status: status,
+ Branch: branch,
+ })
+ }
+ }
+ }
+ return clients, nil
+}
+
+// NomenclatureItem представляет одну строку из таблицы номенклатуры
+type NomenclatureItem struct {
+ Name string `json:"name"`
+ Type string `json:"type"`
+}
+
+// ClientItem представляет клиента из таблицы клиентов
+type ClientItem struct {
+ Name string `json:"name"`
+ Manager string `json:"manager"`
+ Status string `json:"status"`
+ Branch string `json:"branch"`
+}
+
+// IsMonthReportExist проверяет, есть ли уже лист с отчетом за этот месяц в мастер-таблице
+func (c *Client) IsMonthReportExist(ctx context.Context, spreadsheetID string, targetDate time.Time) (bool, error) {
+ monthYearTitle := targetDate.Format("January 2006")
+ ordersSheetName := "Заказы - " + monthYearTitle
+
+ spreadsheet, err := c.srv.Spreadsheets.Get(spreadsheetID).Context(ctx).Do()
+ if err != nil {
+ return false, err
+ }
+
+ for _, sheet := range spreadsheet.Sheets {
+ if sheet.Properties.Title == ordersSheetName {
+ return true, nil
+ }
+ }
+ return false, nil
+}
diff --git a/core/lib/external/tgkit/client.go b/core/lib/external/tgkit/client.go
index ba34607..d6f75af 100644
--- a/core/lib/external/tgkit/client.go
+++ b/core/lib/external/tgkit/client.go
@@ -1,18 +1,403 @@
package tgkit
import (
+ "bitrix_balancer_api/core/variables"
+ "bytes"
+ "context"
"crypto/tls"
+ "encoding/json"
"fmt"
- "github.com/sirupsen/logrus"
+ "io"
+ "mime"
+ "mime/multipart"
+ "net"
"net/http"
"net/url"
+ "strings"
"sync"
"time"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
- "golang.org/x/net/proxy"
+ "github.com/sirupsen/logrus"
)
+// APIProxyRequest описывает структуру тела запроса к твоему прокси-сервису
+type APIProxyRequest struct {
+ URL string `json:"url"`
+ Method string `json:"method"`
+ Body interface{} `json:"body,omitempty"`
+}
+
+type CustomAPIProxyTransport struct {
+ wrapped http.RoundTripper
+
+ // Поля для fallback-механизма на бесплатные прокси
+ fallbackSince time.Time
+ mu sync.RWMutex
+ fallbackMode bool
+ fallbackProxyURL string
+ fallbackTransport http.RoundTripper
+}
+
+const (
+ maxProxyConnectAttempts = 2
+ proxyConnectRetryDelay = 500 * time.Millisecond
+ defaultTimeout = 120 * time.Second
+ maxStartupAttempts = 3
+ startupRetryDelay = 3 * time.Second
+ fallbackRetryInterval = 2 * time.Minute
+)
+
+var (
+ mu sync.Mutex
+ instance *Client
+)
+
+func (t *CustomAPIProxyTransport) RoundTrip(req *http.Request) (*http.Response, error) {
+ // 1. Сразу считываем оригинальное тело запроса в память.
+ // Это критично, так как при падении шлюза нам нужно будет отправить
+ // эти же оригинальные данные через резервный бесплатный прокси.
+ var rawOriginalBody []byte
+ if req.Body != nil {
+ rawOriginalBody, _ = io.ReadAll(req.Body)
+ _ = req.Body.Close()
+ }
+
+ t.mu.Lock()
+ useFallback := t.fallbackMode && t.fallbackTransport != nil
+ if useFallback && time.Since(t.fallbackSince) >= fallbackRetryInterval {
+ t.fallbackSince = time.Now()
+ useFallback = false
+ logrus.Infof("tgkit: trying to return to the main gateway...")
+ }
+ fallbackTrans := t.fallbackTransport
+ currentFallbackURL := t.fallbackProxyURL
+ t.mu.Unlock()
+
+ if useFallback {
+ return t.executeFallback(req, rawOriginalBody, fallbackTrans, currentFallbackURL)
+ }
+
+ // === Стандартный путь через приватный шлюз ===
+ targetURL := req.URL.String()
+ method := req.Method
+ var proxyReq *http.Request
+ var bodyBytesForRetry []byte
+
+ contentType := req.Header.Get("Content-Type")
+ mediaType, params, _ := mime.ParseMediaType(contentType)
+
+ if mediaType == "multipart/form-data" && len(rawOriginalBody) > 0 {
+ var buf bytes.Buffer
+ writer := multipart.NewWriter(&buf)
+
+ _ = writer.WriteField("url", targetURL)
+ _ = writer.WriteField("method", method)
+
+ boundary := params["boundary"]
+ mr := multipart.NewReader(bytes.NewReader(rawOriginalBody), boundary)
+ for {
+ part, err := mr.NextPart()
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ return nil, fmt.Errorf("proxy transport: parse incoming multipart: %w", err)
+ }
+
+ partBytes, _ := io.ReadAll(part)
+
+ if part.FileName() != "" {
+ filePart, err := writer.CreateFormFile(part.FormName(), part.FileName())
+ if err != nil {
+ return nil, fmt.Errorf("proxy transport: create form file: %w", err)
+ }
+ _, _ = filePart.Write(partBytes)
+ } else {
+ fieldPart, err := writer.CreateFormField(part.FormName())
+ if err != nil {
+ return nil, fmt.Errorf("proxy transport: create form field: %w", err)
+ }
+ _, _ = fieldPart.Write(partBytes)
+ }
+ }
+ _ = writer.Close()
+ bodyBytesForRetry = buf.Bytes()
+
+ var err error
+ proxyReq, err = http.NewRequestWithContext(req.Context(), "POST", variables.ProxyForwardURL, bytes.NewReader(bodyBytesForRetry))
+ if err != nil {
+ return nil, fmt.Errorf("proxy transport: failed to create multipart request: %w", err)
+ }
+ proxyReq.Header.Set("Content-Type", writer.FormDataContentType())
+ } else {
+ var originalBody interface{} = map[string]interface{}{}
+
+ if len(rawOriginalBody) > 0 {
+ var raw json.RawMessage
+ if err := json.Unmarshal(rawOriginalBody, &raw); err == nil {
+ originalBody = raw
+ } else {
+ values, err := url.ParseQuery(string(rawOriginalBody))
+ if err == nil && len(values) > 0 {
+ bodyMap := make(map[string]interface{})
+ for key, val := range values {
+ if len(val) == 1 {
+ bodyMap[key] = val[0]
+ } else if len(val) > 1 {
+ bodyMap[key] = val
+ }
+ }
+ originalBody = bodyMap
+ } else {
+ originalBody = string(rawOriginalBody)
+ }
+ }
+ }
+
+ proxyReqPayload := APIProxyRequest{
+ URL: targetURL,
+ Method: method,
+ Body: originalBody,
+ }
+
+ proxyJsonBytes, err := json.Marshal(proxyReqPayload)
+ if err != nil {
+ return nil, fmt.Errorf("proxy transport: failed to marshal proxy payload: %w", err)
+ }
+ bodyBytesForRetry = proxyJsonBytes
+
+ proxyReq, err = http.NewRequestWithContext(req.Context(), "POST", variables.ProxyForwardURL, bytes.NewReader(bodyBytesForRetry))
+ if err != nil {
+ return nil, fmt.Errorf("proxy transport: failed to create json request: %w", err)
+ }
+ proxyReq.Header.Set("Content-Type", "application/json")
+ }
+
+ proxyReq.Header.Set(variables.ProxySecretHeader, variables.ProxySecretKey)
+
+ resp, err := t.roundTripWithRetry(proxyReq, bodyBytesForRetry)
+ if err == nil {
+ resp, err = readJSONResponse(resp) // функция из пункта 1 прошлого ответа
+ }
+ if err != nil {
+ logrus.Warnf("tgkit: custom gateway failed (%v), switching to free fallback proxies.", err)
+ return t.switchToFallbackAndExecute(req, rawOriginalBody, "")
+ }
+
+ t.mu.Lock()
+ if t.fallbackMode {
+ t.fallbackMode = false
+ logrus.Infof("tgkit: main gateway is back, fallback proxy disabled")
+ }
+ t.mu.Unlock()
+
+ return resp, nil
+}
+
+func looksLikeJSON(b []byte) bool {
+ b = bytes.TrimSpace(b)
+ return len(b) > 0 && b[0] == '{'
+}
+
+// readJSONResponse читает тело, проверяет что это JSON, и возвращает тело обратно в resp
+func readJSONResponse(resp *http.Response) (*http.Response, error) {
+ body, err := io.ReadAll(resp.Body)
+ _ = resp.Body.Close()
+ if err != nil {
+ return nil, err
+ }
+ if !looksLikeJSON(body) {
+ return nil, fmt.Errorf("non-JSON response (status %d): %.200q", resp.StatusCode, body)
+ }
+ resp.Body = io.NopCloser(bytes.NewReader(body))
+ return resp, nil
+}
+
+func (t *CustomAPIProxyTransport) roundTripWithRetry(req *http.Request, bodyBytes []byte) (*http.Response, error) {
+ var lastErr error
+ for attempt := 1; attempt <= maxProxyConnectAttempts; attempt++ {
+ req.Body = io.NopCloser(bytes.NewReader(bodyBytes))
+ req.ContentLength = int64(len(bodyBytes))
+
+ resp, err := t.wrapped.RoundTrip(req)
+ if err != nil {
+ lastErr = err
+ logrus.Warnf("tgkit: gateway connect attempt %d/%d failed: %v", attempt, maxProxyConnectAttempts, err)
+ if attempt < maxProxyConnectAttempts {
+ time.Sleep(proxyConnectRetryDelay)
+ }
+ continue
+ }
+
+ if resp.StatusCode >= 500 {
+ defer resp.Body.Close()
+ errorBody, _ := io.ReadAll(resp.Body)
+ return nil, fmt.Errorf("proxy returned status %d (%s): %s", resp.StatusCode, resp.Status, string(errorBody))
+ }
+
+ return resp, nil
+ }
+ return nil, lastErr
+}
+
+// executeFallback перенаправляет оригинальный запрос напрямую в Telegram через найденный бесплатный прокси
+func (t *CustomAPIProxyTransport) executeFallback(req *http.Request, body []byte, trans http.RoundTripper, currentProxyURL string) (*http.Response, error) {
+ newReq := req.Clone(req.Context())
+ if len(body) > 0 {
+ newReq.Body = io.NopCloser(bytes.NewReader(body))
+ newReq.ContentLength = int64(len(body))
+ }
+
+ resp, err := trans.RoundTrip(newReq)
+ if err == nil {
+ resp, err = readJSONResponse(resp)
+ }
+ if err != nil {
+ logrus.Warnf("tgkit: fallback proxy %s failed (%v), searching for a new one...", currentProxyURL, err)
+ return t.switchToFallbackAndExecute(req, body, currentProxyURL)
+ }
+ return resp, nil
+}
+
+// switchToFallbackAndExecute блокирует транспорт, находит самый быстрый прокси и обновляет конфигурацию
+func (t *CustomAPIProxyTransport) switchToFallbackAndExecute(req *http.Request, body []byte, failedProxyURL string) (*http.Response, error) {
+ t.mu.Lock()
+ // Если другая горутина уже нашла новый прокси, пока мы ждали мьютекс, используем его
+ if t.fallbackMode && t.fallbackProxyURL != failedProxyURL {
+ savedTrans := t.fallbackTransport
+ currentURL := t.fallbackProxyURL
+ t.mu.Unlock()
+ return t.executeFallback(req, body, savedTrans, currentURL)
+ }
+
+ logrus.Infof("tgkit: searching for the fastest free proxy...")
+ newProxyURL, err := findFastestFreeProxy()
+ if err != nil {
+ t.mu.Unlock()
+ return nil, fmt.Errorf("failed to find a working free proxy: %w", err)
+ }
+
+ parsedURL, _ := url.Parse(newProxyURL)
+ newTrans := &http.Transport{
+ Proxy: http.ProxyURL(parsedURL),
+ DialContext: (&net.Dialer{
+ Timeout: 10 * time.Second,
+ KeepAlive: 30 * time.Second,
+ }).DialContext,
+ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // Бесплатные прокси часто имеют кривые сертификаты
+ }
+
+ t.fallbackMode = true
+ t.fallbackProxyURL = newProxyURL
+ t.fallbackTransport = newTrans
+ savedTrans := newTrans
+ t.fallbackSince = time.Now()
+ t.mu.Unlock()
+
+ logrus.Infof("tgkit: successfully switched to free proxy: %s", newProxyURL)
+ return t.executeFallback(req, body, savedTrans, newProxyURL)
+}
+
+// findFastestFreeProxy скачивает списки бесплатных прокси, конкурентно пингует их и возвращает первый успешный
+func findFastestFreeProxy() (string, error) {
+ sources := []string{
+ "https://raw.githubusercontent.com/TheSpeedX/SOCKS-List/master/http.txt",
+ "https://raw.githubusercontent.com/ShiftyTR/Proxy-List/master/http.txt",
+ "https://api.proxyscrape.com/v2/?request=displayproxies&protocol=http&timeout=5000&country=all&ssl=all&anonymity=all",
+ }
+
+ var proxies []string
+ for _, src := range sources {
+ resp, err := http.Get(src)
+ if err == nil {
+ body, _ := io.ReadAll(resp.Body)
+ _ = resp.Body.Close()
+ lines := strings.Split(string(body), "\n")
+ for _, line := range lines {
+ line = strings.TrimSpace(line)
+ if line != "" {
+ proxies = append(proxies, line)
+ }
+ }
+ }
+ if len(proxies) > 100 {
+ break // Собрали достаточное количество для тестирования
+ }
+ }
+
+ if len(proxies) == 0 {
+ return "", fmt.Errorf("could not fetch proxies from public sources")
+ }
+
+ resultCh := make(chan string, 1)
+ var wg sync.WaitGroup
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+
+ limit := 100
+ if len(proxies) < limit {
+ limit = len(proxies)
+ }
+
+ for i := 0; i < limit; i++ {
+ p := proxies[i]
+ if !strings.HasPrefix(p, "http") && !strings.HasPrefix(p, "socks") {
+ p = "http://" + p
+ }
+ wg.Add(1)
+ go func(proxyUrl string) {
+ defer wg.Done()
+ u, err := url.Parse(proxyUrl)
+ if err != nil {
+ return
+ }
+
+ // Делаем запрос к Telegram API с фейковым токеном.
+ // Реальный сервер Telegram обязательно ответит JSON: {"ok":false,"error_code":401,"description":"Unauthorized"}
+ req, _ := http.NewRequestWithContext(ctx, "GET", "https://api.telegram.org/bot123456:invalid_token/getMe", nil)
+ client := &http.Client{
+ Transport: &http.Transport{
+ Proxy: http.ProxyURL(u),
+ DialContext: (&net.Dialer{Timeout: 3 * time.Second}).DialContext,
+ TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
+ },
+ Timeout: 4 * time.Second,
+ }
+
+ resp, err := client.Do(req)
+ if err == nil {
+ body, _ := io.ReadAll(resp.Body)
+ _ = resp.Body.Close()
+
+ // Если в ответе есть маркер структуры Telegram API - прокси действительно пропускает трафик
+ if bytes.Contains(body, []byte(`"ok":`)) {
+ select {
+ case resultCh <- proxyUrl:
+ cancel() // Отменяем проверки остальных прокси, победитель найден
+ default:
+ }
+ }
+ }
+ }(p)
+ }
+
+ go func() {
+ wg.Wait()
+ close(resultCh)
+ }()
+
+ select {
+ case best, ok := <-resultCh:
+ if !ok {
+ return "", fmt.Errorf("all %d tested proxies failed to reach Telegram properly", limit)
+ }
+ return best, nil
+ case <-time.After(8 * time.Second):
+ return "", fmt.Errorf("timeout waiting for a valid proxy (tested %d proxies)", limit)
+ }
+}
+
// Client — основной клиент библиотеки
type Client struct {
bot *tgbotapi.BotAPI
@@ -20,163 +405,124 @@ type Client struct {
}
// ClientConfig — конфигурация клиента
+type ProxyConfig struct{} // Заглушка, если структура была в другом файле
type ClientConfig struct {
Token string
Proxy *ProxyConfig
- Timeout time.Duration // по умолчанию 30s
+ Timeout time.Duration
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
+ cfg.Timeout = defaultTimeout
}
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)
+ logrus.Debugf("tgkit: custom API proxy is enabled")
}
+
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)
+ var bot *tgbotapi.BotAPI
+ for attempt := 1; attempt <= maxStartupAttempts; attempt++ {
+ bot, err = tgbotapi.NewBotAPIWithClient(cfg.Token, tgbotapi.APIEndpoint, httpClient)
+ if err == nil {
+ break
+ }
+ logrus.Warnf("tgkit: init bot attempt %d/%d failed: %v", attempt, maxStartupAttempts, err)
+ if attempt < maxStartupAttempts {
+ time.Sleep(time.Duration(attempt) * startupRetryDelay)
+ }
+ }
if err != nil {
- return nil, fmt.Errorf("tgkit: init bot: %w", err)
+ return nil, fmt.Errorf("tgkit: init bot after %d attempts: %w", maxStartupAttempts, err)
}
bot.Debug = cfg.Debug
-
- return &Client{
- bot: bot,
- timeout: cfg.Timeout,
- }, nil
+ 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}
+ return &Client{bot: bot, timeout: defaultTimeout}
}
-// 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},
+ baseTransport := &http.Transport{
+ DialContext: (&net.Dialer{
+ Timeout: 10 * time.Second,
+ KeepAlive: 30 * time.Second,
+ }).DialContext,
+ MaxIdleConns: 100,
+ MaxIdleConnsPerHost: 100,
+ TLSHandshakeTimeout: 10 * time.Second,
+ ResponseHeaderTimeout: 60 * time.Second,
+ 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)
- }
+ var finalTransport http.RoundTripper = baseTransport
+ if proxyCfg != nil {
+ finalTransport = &CustomAPIProxyTransport{wrapped: baseTransport}
}
return &http.Client{
- Transport: transport,
+ Transport: finalTransport,
Timeout: timeout,
}, nil
}
diff --git a/core/lib/external/tgkit/media.go b/core/lib/external/tgkit/media.go
index 2fd0c07..ff3cfd3 100644
--- a/core/lib/external/tgkit/media.go
+++ b/core/lib/external/tgkit/media.go
@@ -11,6 +11,22 @@ import (
"github.com/sirupsen/logrus"
)
+func detectImageExtension(data []byte) string {
+ contentType := http.DetectContentType(data)
+ switch contentType {
+ case "image/png":
+ return "photo.png"
+ case "image/jpeg":
+ return "photo.jpg"
+ case "image/webp":
+ return "photo.webp"
+ case "image/gif":
+ return "photo.gif"
+ default:
+ return "photo.jpg"
+ }
+}
+
// SendPhoto отправляет фото по URL, пути к файлу или base64
func (c *Client) SendPhoto(chatID int64, source string, caption string, opts ...MessageOptions) (*SentMessage, error) {
var photo tgbotapi.RequestFileData
@@ -23,7 +39,8 @@ func (c *Client) SendPhoto(chatID int64, source string, caption string, opts ...
if err != nil {
return nil, fmt.Errorf("tgkit: decode base64: %w", err)
}
- photo = tgbotapi.FileBytes{Name: "photo.jpg", Bytes: data}
+ fileName := detectImageExtension(data)
+ photo = tgbotapi.FileBytes{Name: fileName, Bytes: data}
default:
photo = tgbotapi.FilePath(source)
}
diff --git a/core/lib/external/tgkit/types.go b/core/lib/external/tgkit/types.go
index cbdfdf7..0b4b75b 100644
--- a/core/lib/external/tgkit/types.go
+++ b/core/lib/external/tgkit/types.go
@@ -43,13 +43,6 @@ type MessageOptions struct {
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
diff --git a/core/lib/internally/client-controllers/0_init.go b/core/lib/internally/client-controllers/0_init.go
index fec6696..cafe90b 100644
--- a/core/lib/internally/client-controllers/0_init.go
+++ b/core/lib/internally/client-controllers/0_init.go
@@ -3,15 +3,17 @@ package clientcontrollers
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"
"errors"
"fmt"
)
type ClientsExternal struct {
- Config *configcore.Config
- Redis *redismodule.ModuleRedis
- DB *database.ModuleDB
+ Config *configcore.Config
+ Redis *redismodule.ModuleRedis
+ DB *database.ModuleDB
+ Telegram *tgkit.Client
}
func ReturnClientsExternal(cfgOptions *configcore.ConfigLoadOptions) (ClientsExternal, error) {
@@ -43,5 +45,16 @@ func ReturnClientsExternal(cfgOptions *configcore.ConfigLoadOptions) (ClientsExt
clientsExternal.DB = dbClient
}
+ if cfgOptions.Telegram {
+ tgKitClient, err := tgkit.GetClient(tgkit.ClientConfig{
+ Token: cfg.Telegram.BotToken,
+ Proxy: &tgkit.ProxyConfig{},
+ })
+ if err != nil {
+ return clientsExternal, errors.New(fmt.Sprintf("failed to get tg client: %v", err))
+ }
+ clientsExternal.Telegram = tgKitClient
+ }
+
return clientsExternal, nil
}
diff --git a/core/lib/internally/monthly_orders/service.go b/core/lib/internally/monthly_orders/service.go
new file mode 100644
index 0000000..c47635b
--- /dev/null
+++ b/core/lib/internally/monthly_orders/service.go
@@ -0,0 +1,492 @@
+package monthly_orders
+
+import (
+ dbcore "bitrix_balancer_api/core/db/methods"
+ "bitrix_balancer_api/core/lib/external/googlesheets"
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/telegram_service/types"
+ "context"
+ "errors"
+ "fmt"
+ "github.com/sirupsen/logrus"
+ "sort"
+ "strings"
+ "time"
+)
+
+const MasterReportSpreadsheetID = "1wMyQIA-ShXE0TzHcjadMxkN1eu_637SflFHrUJjRuQw"
+
+type ApprovalFlowStarter interface {
+ StartFlowForOrder(ctx context.Context, approval *typescore.Approval) error
+}
+
+type MonthlyOrderService struct {
+ ipc *types.InternalProviderControl
+ gsClient *googlesheets.Client
+ clientsSheet string
+ nomSheet string
+ flowStarter ApprovalFlowStarter // 2. НОВОЕ: Добавляем зависимость
+}
+
+func NewMonthlyOrderService(
+ ipc *types.InternalProviderControl,
+ gsClient *googlesheets.Client,
+ clientsSheetID, nomSheetID string,
+ flowStarter ApprovalFlowStarter,
+) *MonthlyOrderService {
+ return &MonthlyOrderService{
+ ipc: ipc,
+ gsClient: gsClient,
+ clientsSheet: clientsSheetID,
+ nomSheet: nomSheetID,
+ flowStarter: flowStarter,
+ }
+}
+
+type FrontendOrderMatrix struct {
+ Settings *typescore.MonthlyOrderSetting `json:"settings"`
+ Nomenclatures []googlesheets.NomenclatureItem `json:"nomenclatures"`
+ Clients []FrontendClientData `json:"clients"`
+ IsLocked bool `json:"is_locked"`
+}
+
+type FrontendClientData struct {
+ GoogleData googlesheets.ClientItem `json:"google_data"`
+ DBOrder *typescore.MonthlyOrderClient `json:"db_order"` // Черновик или отправленный заказ (если есть)
+}
+
+// GetMyOrderData собирает "матрицу" для менеджера: тянет Google Sheets + БД
+func (s *MonthlyOrderService) GetMyOrderData(ctx context.Context, managerID uint64) (*FrontendOrderMatrix, error) {
+ logrus.Info("🛑 GET MY ORDER ")
+
+ manager, err := s.ipc.Database.User.GetUserByIDDB(ctx, managerID)
+ if err != nil || manager == nil || manager.FullName == nil {
+ return nil, errors.New("менеджер не найден")
+ }
+
+ now := time.Now()
+ month, year := int(now.Month()), now.Year()
+
+ // 1. Получаем настройки месяца
+ settings, err := s.ipc.Database.MonthlyOrders.GetCurrentSettings(ctx, month, year)
+ if err != nil {
+ return nil, err
+ }
+
+ isLocked := true
+ if settings != nil && settings.DeadlineDate != nil {
+ // Открыто с 15-го числа И до дедлайна включительно
+ if now.Day() >= 15 && now.Before(*settings.DeadlineDate) {
+ isLocked = false
+ }
+ }
+
+ // 2. Идем в Google Sheets за свежими данными
+ noms, err := s.gsClient.FetchNomenclature(s.nomSheet)
+ if err != nil {
+ return nil, fmt.Errorf("ошибка парсинга номенклатуры: %v", err)
+ }
+
+ gsClients, err := s.gsClient.FetchActiveClientsForManager(s.clientsSheet, *manager.FullName)
+ if err != nil {
+ return nil, fmt.Errorf("ошибка парсинга клиентов: %v", err)
+ }
+
+ ordersMap := make(map[string]*typescore.MonthlyOrderClient)
+
+ // Определяем, какой статус и тип заказа нам нужен в зависимости от блокировки (дедлайна)
+ statusDraft := "draft"
+ suppType := "supplementary"
+ mainType := "main"
+
+ filterOpts := dbcore.OrderFilterOptions{
+ ManagerID: &managerID,
+ Month: &month,
+ Year: &year,
+ Status: &statusDraft, // Берем только черновики!
+ }
+
+ if isLocked {
+ filterOpts.OrderType = &suppType
+ } else {
+ filterOpts.OrderType = &mainType
+ }
+
+ logrus.Infof("🛑 Период: %s", *filterOpts.OrderType)
+
+ dbOrders, err := s.ipc.Database.MonthlyOrders.GetFilteredClientOrdersDB(ctx, filterOpts)
+ if err != nil {
+ logrus.Errorf("🚨 ОШИБКА ЧТЕНИЯ ЗАКАЗОВ ИЗ БД: %v", err)
+ }
+
+ for _, o := range dbOrders {
+ if o.ID != nil {
+ // Достаем позиции
+ items, err := s.ipc.Database.MonthlyOrders.GetItemsByOrderIDDB(ctx, *o.ID)
+ if err == nil && len(items) > 0 {
+ for _, item := range items {
+ o.Items = append(o.Items, *item)
+ }
+ }
+
+ // Достаем файлы
+ files, err := s.ipc.Database.MonthlyOrders.GetFilesByOrderIDDB(ctx, *o.ID)
+ if err == nil && len(files) > 0 {
+ for _, file := range files {
+ o.Files = append(o.Files, *file)
+ }
+ }
+ }
+
+ if o.ClientName != nil {
+ cleanName := strings.TrimSpace(*o.ClientName)
+ ordersMap[cleanName] = o
+ }
+ }
+
+ var clientDataList []FrontendClientData
+ for _, gsc := range gsClients {
+ cleanName := strings.TrimSpace(gsc.Name)
+
+ clientDataList = append(clientDataList, FrontendClientData{
+ GoogleData: gsc,
+ DBOrder: ordersMap[cleanName],
+ })
+ }
+
+ return &FrontendOrderMatrix{
+ Settings: settings,
+ Nomenclatures: noms,
+ Clients: clientDataList,
+ IsLocked: isLocked,
+ }, nil
+}
+
+// ExportGoogleReport собирает все заказы за текущий месяц и пушит в гугл
+func (s *MonthlyOrderService) ExportGoogleReport(ctx context.Context) (string, error) {
+ if s.gsClient == nil {
+ return "", errors.New("google sheets client не инициализирован (проверьте google-creds.json)")
+ }
+
+ now := time.Now()
+ month, year := int(now.Month()), now.Year()
+
+ allOrders, err := s.ipc.Database.MonthlyOrders.GetAllOrdersForMonthDB(ctx, month, year)
+ if err != nil {
+ return "", fmt.Errorf("ошибка получения заказов из БД: %v", err)
+ }
+
+ // 1. Сортируем заказы по ID, чтобы сохранить хронологию (сначала старые/основные)
+ sort.Slice(allOrders, func(i, j int) bool {
+ if allOrders[i].ID != nil && allOrders[j].ID != nil {
+ return *allOrders[i].ID < *allOrders[j].ID
+ }
+ return false
+ })
+
+ var mainOrders []*typescore.MonthlyOrderClient
+ var suppOrders []*typescore.MonthlyOrderClient
+
+ // 2. Строго разделяем на основные и доп. заказы по полю OrderType
+ for _, o := range allOrders {
+ if o.ClientName == nil {
+ continue
+ }
+
+ if o.OrderType != nil && *o.OrderType == "supplementary" {
+ suppOrders = append(suppOrders, o)
+ } else {
+ // Всё, что не помечено как supplementary, уходит в основные
+ mainOrders = append(mainOrders, o)
+ }
+ }
+
+ // 3. Формируем заголовки
+ sheet1Data := [][]interface{}{{"Клиент", "Номенклатура", "Количество", "Итог (Формула)", "Тип заказа"}}
+ sheet2Data := [][]interface{}{{"Клиент", "Тип заказа", "Комментарий менеджера", "Декада", "Доставка", "Оплата", "Условия"}}
+
+ currentRow := 2
+
+ processOrderList := func(orders []*typescore.MonthlyOrderClient, orderTypeLabel string) {
+ for _, o := range orders {
+ clientName := strings.TrimSpace(*o.ClientName)
+
+ // --- СБОРКА ЛИСТА КОММЕНТАРИЕВ ---
+ comment, decade, delivery, payment, conditions := "", "", "", "", ""
+ if o.ManagerComment != nil {
+ comment = *o.ManagerComment
+ }
+ if o.Decade != nil {
+ decade = *o.Decade
+ }
+ if o.Delivery != nil {
+ delivery = *o.Delivery
+ }
+ if o.PaymentForm != nil {
+ payment = *o.PaymentForm
+ }
+ if o.Conditions != nil {
+ conditions = *o.Conditions
+ }
+
+ if comment != "" || decade != "" || delivery != "" || payment != "" || conditions != "" {
+ sheet2Data = append(sheet2Data, []interface{}{
+ clientName,
+ orderTypeLabel, // Для основных здесь пустая строка или "Основной", для доп — "Доп заказ"
+ comment,
+ decade,
+ delivery,
+ payment,
+ conditions,
+ })
+ }
+
+ if o.ID != nil {
+ items, _ := s.ipc.Database.MonthlyOrders.GetItemsByOrderIDDB(ctx, *o.ID)
+ for _, item := range items {
+ if item == nil || item.Quantity == nil || *item.Quantity <= 0 {
+ continue
+ }
+
+ nomName := ""
+ if item.NomenclatureName != nil {
+ nomName = *item.NomenclatureName
+ }
+
+ formula := fmt.Sprintf(`=VALUE(REGEXEXTRACT(B%d; "\((\d+)\)[^()]*$"))*C%d`, currentRow, currentRow)
+
+ sheet1Data = append(sheet1Data, []interface{}{
+ clientName,
+ nomName,
+ *item.Quantity,
+ formula,
+ orderTypeLabel,
+ })
+
+ currentRow++
+ }
+ }
+ }
+ }
+
+ // 4. Запускаем формирование: сначала основные (с пустым метки типа или "Основной"), затем доп. заказы
+ processOrderList(mainOrders, "")
+ processOrderList(suppOrders, "Доп заказ")
+
+ return s.gsClient.ExportMonthlyReportToMasterSheet(ctx, MasterReportSpreadsheetID, sheet1Data, sheet2Data)
+}
+
+// SubmitOrdersToTelegram превращает отправленные заказы в Telegram-заявки
+func (s *MonthlyOrderService) SubmitOrdersToTelegram(ctx context.Context, managerID uint64) error {
+ now := time.Now()
+ month, year := int(now.Month()), now.Year()
+
+ statusDraft := "draft"
+ filterOpts := dbcore.OrderFilterOptions{
+ ManagerID: &managerID,
+ Month: &month,
+ Year: &year,
+ Status: &statusDraft,
+ }
+ dbOrders, err := s.ipc.Database.MonthlyOrders.GetFilteredClientOrdersDB(ctx, filterOpts)
+ if err != nil {
+ return err
+ }
+
+ manager, err := s.ipc.Database.User.GetUserByIDDB(ctx, managerID)
+ if err != nil || manager == nil || manager.FullName == nil {
+ return errors.New("менеджер не найден")
+ }
+
+ gsClients, err := s.gsClient.FetchActiveClientsForManager(s.clientsSheet, *manager.FullName)
+ if err != nil {
+ return fmt.Errorf("ошибка получения клиентов из Google Sheets: %v", err)
+ }
+
+ branchMap := make(map[string]string)
+ for _, c := range gsClients {
+ branchMap[strings.TrimSpace(c.Name)] = strings.TrimSpace(c.Branch)
+ }
+
+ submittedCount := 0
+ skippedEmpty := 0
+ skippedAlreadyDone := 0
+
+ for _, order := range dbOrders {
+ if order.ClientName == nil {
+ continue
+ }
+ clientNameClean := strings.TrimSpace(*order.ClientName)
+
+ // 1. Получаем номенклатуру (позиции) заказа
+ items, err := s.ipc.Database.MonthlyOrders.GetItemsByOrderIDDB(ctx, *order.ID)
+ if err != nil || len(items) == 0 {
+ logrus.Warnf("⚠️ [SubmitOrders] У клиента '%s' (OrderID: %v) не найдено позиций в БД.", clientNameClean, order.ID)
+ skippedEmpty++
+ continue
+ }
+
+ hasActualQuantity := false
+ for _, item := range items {
+ if item.Quantity != nil && *item.Quantity > 0 {
+ hasActualQuantity = true
+ break
+ }
+ }
+
+ if !hasActualQuantity {
+ logrus.Warnf("⚠️ [SubmitOrders] У клиента '%s' позиции имеют нулевое количество.", clientNameClean)
+ skippedEmpty++
+ continue
+ }
+
+ if order.ApprovalID != nil && *order.ApprovalID > 0 {
+ skippedAlreadyDone++
+ continue
+ }
+
+ // 2. Получаем прикрепленные файлы (скрины) из БД
+ files, err := s.ipc.Database.MonthlyOrders.GetFilesByOrderIDDB(ctx, *order.ID)
+ if err != nil {
+ logrus.Warnf("⚠️ [SubmitOrders] Ошибка получения файлов для клиента '%s': %v", clientNameClean, err)
+ }
+
+ branch := ""
+ for gsName, gsBranch := range branchMap {
+ if strings.EqualFold(gsName, clientNameClean) {
+ branch = gsBranch
+ break
+ }
+ }
+
+ isSupplementary := order.OrderType != nil && *order.OrderType == "supplementary"
+
+ var topicID uint64
+ branchLower := strings.ToLower(branch)
+
+ if strings.Contains(branchLower, "краснодар") {
+ if isSupplementary {
+ topicID = 583
+ } else {
+ topicID = 581
+ }
+ } else if strings.Contains(branchLower, "крым") {
+ if isSupplementary {
+ topicID = 582
+ } else {
+ topicID = 580
+ }
+ } else {
+ continue
+ }
+
+ var contentBuilder strings.Builder
+ contentBuilder.WriteString(fmt.Sprintf("Клиент: %s\n", *order.ClientName))
+
+ if order.Decade != nil {
+ contentBuilder.WriteString(fmt.Sprintf("Декада: %s\n", *order.Decade))
+ }
+ if order.Delivery != nil {
+ contentBuilder.WriteString(fmt.Sprintf("Доставка: %s\n", *order.Delivery))
+ }
+ if order.Conditions != nil {
+ contentBuilder.WriteString(fmt.Sprintf("Условия: %s\n", *order.Conditions))
+ }
+ if order.PaymentForm != nil {
+ contentBuilder.WriteString(fmt.Sprintf("Оплата: %s\n", *order.PaymentForm))
+ }
+
+ contentBuilder.WriteString("\n📦 Позиции:\n")
+
+ for _, item := range items {
+ nomName := "Ошибка при получении названия"
+ if item.NomenclatureName != nil {
+ nomName = *item.NomenclatureName
+ }
+
+ qty := 0
+ if item.Quantity != nil {
+ qty = *item.Quantity
+ }
+
+ contentBuilder.WriteString(fmt.Sprintf("- %s: %d шт.\n", nomName, qty))
+ order.Items = append(order.Items, *item)
+ }
+
+ for _, f := range files {
+ if f != nil {
+ order.Files = append(order.Files, *f)
+ }
+ }
+
+ if order.ManagerComment != nil {
+ contentBuilder.WriteString(fmt.Sprintf("\n💬 Комментарий: %s", *order.ManagerComment))
+ }
+ if order.FreeFormComment != nil && *order.FreeFormComment != "" {
+ contentBuilder.WriteString(fmt.Sprintf("\n✍️ Доп. комментарий: %s", *order.FreeFormComment))
+ }
+
+ contentStr := contentBuilder.String()
+ status := "pending"
+
+ approval := &typescore.Approval{
+ InitiatorID: manager.ID,
+ DepartmentID: manager.DepartmentID,
+ TopicID: &topicID,
+ Content: &contentStr,
+ Status: &status,
+ }
+
+ createdApproval, _, err := s.ipc.Database.Approval.CreateApprovalDB(ctx, nil, approval, true)
+ if err == nil && createdApproval != nil {
+ var approvalFiles []*typescore.ApprovalFile
+ for _, f := range files {
+ if f == nil {
+ continue
+ }
+ appFile := &typescore.ApprovalFile{
+ ApprovalID: createdApproval.ID, // Привязываем к ID созданной заявки
+ FileName: f.FileName,
+ FileBase64: f.FileBase64,
+ }
+
+ savedFile, _, fileErr := s.ipc.Database.ApprovalFile.CreateApprovalFileDB(ctx, nil, appFile, true)
+ if fileErr != nil {
+ logrus.Errorf("❌ [SubmitOrders] Ошибка сохранения файла в БД (ApprovalID: %v): %v", createdApproval.ID, fileErr)
+ continue
+ }
+ if savedFile != nil {
+ approvalFiles = append(approvalFiles, savedFile)
+ } else {
+ approvalFiles = append(approvalFiles, appFile)
+ }
+ }
+
+ createdApproval.Files = approvalFiles
+
+ order.ApprovalID = createdApproval.ID
+ orderStatus := "submitted"
+ order.Status = &orderStatus
+ _, err = s.ipc.Database.MonthlyOrders.SaveClientOrder(ctx, nil, order)
+ if err != nil {
+ logrus.Errorf("❌ [SubmitOrders] Ошибка сохранения заказа от клиента (MonthlyOrders.SaveClientOrder): %v", err)
+ }
+
+ if s.flowStarter != nil {
+ if err := s.flowStarter.StartFlowForOrder(ctx, createdApproval); err != nil {
+ appID := uint64(0)
+ if createdApproval.ID != nil {
+ appID = *createdApproval.ID
+ }
+ logrus.Errorf("❌ [SubmitOrders] Ошибка запуска флоу (ApprovalID: %d): %v", appID, err)
+ } else {
+ submittedCount++
+ }
+ }
+ } else {
+ logrus.Errorf("❌ [SubmitOrders] Ошибка создания заявки в БД для клиента %s: %v", clientNameClean, err)
+ }
+ }
+
+ return nil
+}
diff --git a/core/lib/internally/monthly_orders/worker.go b/core/lib/internally/monthly_orders/worker.go
new file mode 100644
index 0000000..36abb1f
--- /dev/null
+++ b/core/lib/internally/monthly_orders/worker.go
@@ -0,0 +1,63 @@
+package monthly_orders
+
+import (
+ "context"
+ "time"
+
+ "github.com/sirupsen/logrus"
+)
+
+// StartDeadlineWorker запускает фоновый процесс проверки дедлайна заказов
+func (s *MonthlyOrderService) StartDeadlineWorker(ctx context.Context) {
+ logrus.Infof("Фоновая задача по дедлайну заказов на месяц запущена")
+ // Проверяем статус каждые 3 часа (или можно настроить под твои нужды)
+ ticker := time.NewTicker(3 * time.Hour)
+ go func() {
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ logrus.Info("🛑 Deadline worker остановлен")
+ return
+ case <-ticker.C:
+ s.checkAndExportByDeadline(ctx)
+ }
+ }
+ }()
+ logrus.Info("🚀 Deadline worker успешно запущен")
+}
+
+func (s *MonthlyOrderService) checkAndExportByDeadline(ctx context.Context) {
+ now := time.Now()
+ month, year := int(now.Month()), now.Year()
+
+ // 1. Получаем настройки текущего месяца (где хранится DeadlineDate)
+ settings, err := s.ipc.Database.MonthlyOrders.GetCurrentSettings(ctx, month, year)
+ if err != nil || settings == nil || settings.DeadlineDate == nil {
+ return // Настройки еще не заданы аналитиком
+ }
+
+ deadline := *settings.DeadlineDate
+ if now.After(deadline) || sameDay(now, deadline) {
+ alreadyExported, err := s.gsClient.IsMonthReportExist(ctx, MasterReportSpreadsheetID, deadline)
+ if err == nil && alreadyExported {
+ return // Отчет за этот период уже сформирован
+ }
+
+ logrus.Infof("⏰ Наступил дедлайн заказов (%s). Автоматически выгружаем отчет...", deadline.Format("02.01.2006"))
+
+ _, err = s.ExportGoogleReport(ctx)
+ if err != nil {
+ logrus.Errorf("❌ Ошибка автовыгрузки отчета по дедлайну: %v", err)
+ } else {
+ logrus.Infof("✅ Отчет за %s успешно автовыгружен в мастер-таблицу", deadline.Format("January 2006"))
+ }
+ }
+}
+
+// Вспомогательная функция для сравнения дат (день, месяц, год)
+func sameDay(t1, t2 time.Time) bool {
+ y1, m1, d1 := t1.Date()
+ y2, m2, d2 := t2.Date()
+ return y1 == y2 && m1 == m2 && d1 == d2
+}
diff --git a/core/reportcore/autoFitCol.go b/core/reportcore/autoFitCol.go
new file mode 100644
index 0000000..e32e5e3
--- /dev/null
+++ b/core/reportcore/autoFitCol.go
@@ -0,0 +1,90 @@
+package reportcore
+
+import (
+ "github.com/xuri/excelize/v2"
+ "strings"
+ "unicode/utf8"
+)
+
+// autoFitColumns автоматически подгоняет ширину колонок под содержимое.
+// Учитывает длину заголовка и всех ячеек, добавляет небольшой отступ.
+func autoFitColumns(f *excelize.File, sheetName string, headers []string, dataRowCount int) {
+ for colIdx, header := range headers {
+ colLetter, _ := excelize.ColumnNumberToName(colIdx + 1)
+
+ // Начинаем с длины заголовка
+ maxWidth := stringWidth(header)
+
+ // Проверяем все строки данных в этой колонке
+ for row := 2; row <= dataRowCount+1; row++ {
+ cellName, _ := excelize.CoordinatesToCellName(colIdx+1, row)
+ cellValue, _ := f.GetCellValue(sheetName, cellName)
+ w := stringWidth(cellValue)
+ if w > maxWidth {
+ maxWidth = w
+ }
+ }
+
+ // Добавляем небольшой отступ для красоты
+ finalWidth := float64(maxWidth) + 2
+
+ // Ограничиваем минимальную и максимальную ширину
+ if finalWidth < 10 {
+ finalWidth = 10
+ }
+ if finalWidth > 60 {
+ finalWidth = 60
+ }
+
+ _ = f.SetColWidth(sheetName, colLetter, colLetter, finalWidth)
+ }
+}
+
+// stringWidth вычисляет "визуальную" ширину строки.
+// Кириллица и другие широкие символы занимают больше места, чем латиница.
+func stringWidth(s string) int {
+ width := 0
+ for _, r := range s {
+ if isWideRune(r) {
+ width += 2 // широкие символы (кириллица, CJK)
+ } else {
+ width += 1
+ }
+ }
+ // Учитываем переносы строк — берём самую длинную строку
+ lines := strings.Split(s, "\n")
+ maxLine := 0
+ for _, line := range lines {
+ lw := 0
+ for _, r := range line {
+ if isWideRune(r) {
+ lw += 2
+ } else {
+ lw += 1
+ }
+ }
+ if lw > maxLine {
+ maxLine = lw
+ }
+ }
+ if maxLine > width {
+ width = maxLine
+ }
+ return width
+}
+
+// isWideRune определяет, является ли символ "широким"
+func isWideRune(r rune) bool {
+ // Кириллица
+ if r >= 0x0400 && r <= 0x04FF {
+ return true
+ }
+ // CJK (китайские, японские, корейские)
+ if r >= 0x4E00 && r <= 0x9FFF {
+ return true
+ }
+ return false
+}
+
+// _ используется, чтобы убрать предупреждение о неиспользуемом импорте
+var _ = utf8.RuneCountInString
diff --git a/core/reportcore/excel.go b/core/reportcore/excel.go
index 4d8b034..40b44d5 100644
--- a/core/reportcore/excel.go
+++ b/core/reportcore/excel.go
@@ -14,7 +14,6 @@ import (
)
// BuildExcelApprovalsReport — строит xlsx-файл отчёта по согласованиям и возвращает байты.
-// Универсальная функция, используется и из админки, и из телеграм-бота.
func BuildExcelApprovalsReport(ctx context.Context, db *database.ModuleDB, approvals []*typescore.Approval) ([]byte, error) {
f := excelize.NewFile()
sheet := "Согласования"
@@ -22,30 +21,34 @@ func BuildExcelApprovalsReport(ctx context.Context, db *database.ModuleDB, appro
return nil, fmt.Errorf("set sheet name: %w", err)
}
+ // 1. Обновленные заголовки (добавлены Доп. согласующие и Доп. наблюдатели)
headers := []string{
- "ФИО инициатора", // A
- "Тема согласования", // B
- "Дата создания", // C
- "Согласующие", // D
- "Наблюдатели", // E
- "Статус", // F
- "Текст согласования", // G
- "Отдел сотрудника", // H
- "Комментарии", // I
- "Дата согласования", // J
- "Текст задачи", // K
- "Исполнитель", // L
- "Статус задачи", // M
- "Дата исполнения", // N
+ "ID", // A
+ "ФИО инициатора", // B
+ "Тема согласования", // C
+ "Дата создания", // D
+ "Согласующие", // E
+ "Наблюдатели", // F
+ "Доп. согласующие", // G 🆕
+ "Доп. наблюдатели", // H 🆕
+ "Статус", // I
+ "Текст согласования", // J
+ "Отдел сотрудника", // K
+ "Комментарии", // L
+ "Дата согласования", // M
+ "Текст задачи", // N
+ "Исполнитель", // O
+ "Статус задачи", // P
+ "Дата исполнения", // Q
}
- cols := []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", "O", "P", "Q"}
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,
+ "A": 10, "B": 25, "C": 40, "D": 18, "E": 30,
+ "F": 30, "G": 30, "H": 30, "I": 16, "J": 40,
+ "K": 25, "L": 30, "M": 18, "N": 40, "O": 25,
+ "P": 18, "Q": 18,
}
headerStyle, err := f.NewStyle(&excelize.Style{
@@ -126,6 +129,11 @@ func BuildExcelApprovalsReport(ctx context.Context, db *database.ModuleDB, appro
for rowIdx, a := range approvals {
row := rowIdx + 2
+ approvalID := uint64(0)
+ if a.ID != nil {
+ approvalID = *a.ID
+ }
+
// === ФИО инициатора ===
initiatorName := ""
if a.Initiator != nil && a.Initiator.FullName != nil {
@@ -203,11 +211,11 @@ func BuildExcelApprovalsReport(ctx context.Context, db *database.ModuleDB, appro
}
approversCell := strings.Join(approverParts, "\n")
- // === Наблюдатели ===
+ // === Наблюдатели (Базовые) ===
var observerParts []string
categoryCode := GetTopicCategoryCodeByApproval(ctx, db, a)
if categoryCode != "" {
- observers, _ := db.User.GetObserversForCategoryDB(ctx, categoryCode)
+ observers, _ := db.User.GetObserversForApprovalDB(ctx, categoryCode, a.TopicID)
for _, obs := range observers {
if obs.FullName != nil {
observerParts = append(observerParts, *obs.FullName)
@@ -216,6 +224,68 @@ func BuildExcelApprovalsReport(ctx context.Context, db *database.ModuleDB, appro
}
observersCell := strings.Join(observerParts, "\n")
+ var addApproverParts []string
+
+ addApprovers, _, _ := db.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalAdditionalApprover{ApprovalID: a.ID},
+ })
+
+ for _, aa := range addApprovers {
+ name := "Неизвестный пользователь"
+
+ // Получаем имя (используем ApproverID согласно вашей структуре)
+ if aa.ApproverID != nil {
+ if u, err := db.User.GetUserByIDDB(ctx, *aa.ApproverID); err == nil && u != nil && u.FullName != nil {
+ name = *u.FullName
+ }
+ }
+
+ // Переводим статус на русский язык
+ aaStatus := "Ожидает"
+ if aa.Status != nil {
+ switch *aa.Status {
+ case "approved":
+ aaStatus = "Согласовано"
+ case "rejected":
+ aaStatus = "Отклонено"
+ case "pending":
+ aaStatus = "Ожидает"
+ }
+ }
+
+ // Формируем основную строку: "Иванов И.И. (Статус: Согласовано)"
+ info := fmt.Sprintf("%s (Статус: %s)", name, aaStatus)
+
+ // Добавляем дату действия, если она есть
+ if aa.ActedAt != nil {
+ info += fmt.Sprintf(" от %s", aa.ActedAt.Format("02.01.2006 15:04"))
+ }
+
+ // Добавляем комментарий с новой строки, если он был оставлен
+ if aa.Comment != nil && *aa.Comment != "" {
+ info += fmt.Sprintf("\nКомментарий: %s", *aa.Comment)
+ }
+
+ addApproverParts = append(addApproverParts, info)
+ }
+
+ // Если доп. согласующих несколько, разделяем их пустой строкой (\n\n) для читаемости в ячейке
+ addApproversCell := strings.Join(addApproverParts, "\n\n")
+
+ var addObserverParts []string
+ // Запрашиваем из базы доп. наблюдателей для данной заявки.
+ addObservers, _, _ := db.ApprovalAdditionalObserver.GetApprovalAdditionalObserversListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalAdditionalObserver{ApprovalID: a.ID},
+ })
+ for _, ao := range addObservers {
+ if ao.UserID != nil {
+ if u, err := db.User.GetUserByIDDB(ctx, *ao.UserID); err == nil && u != nil && u.FullName != nil {
+ addObserverParts = append(addObserverParts, *u.FullName)
+ }
+ }
+ }
+ addObserversCell := strings.Join(addObserverParts, "\n")
+
// === Статус ===
status := "—"
if a.Status != nil {
@@ -360,22 +430,23 @@ func BuildExcelApprovalsReport(ctx context.Context, db *database.ModuleDB, appro
}
}
+ // 🆕 Добавлены две новые переменные в массив
values := []interface{}{
+ approvalID,
initiatorName, topicName, createdAt,
approversCell, observersCell,
+ addApproversCell, addObserversCell,
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)
if err := f.SetCellValue(sheet, cell, val); err != nil {
@@ -384,7 +455,8 @@ func BuildExcelApprovalsReport(ctx context.Context, db *database.ModuleDB, appro
}
cellStyle := style
- if hasTaskError && colIdx >= 10 && colIdx <= 12 {
+ // 🆕 Индексы колонок задач сместились из-за двух новых колонок (было 11-13, стало 13-15)
+ if hasTaskError && colIdx >= 13 && colIdx <= 15 {
cellStyle = errorStyle
}
if err := f.SetCellStyle(sheet, cell, cell, cellStyle); err != nil {
@@ -392,7 +464,6 @@ func BuildExcelApprovalsReport(ctx context.Context, db *database.ModuleDB, appro
}
}
- // Высота строки
rowHeight := 20.0
maxLines := len(approverParts)
if len(strings.Split(taskText, "\n")) > maxLines {
@@ -421,6 +492,8 @@ func BuildExcelApprovalsReport(ctx context.Context, db *database.ModuleDB, appro
logrus.Warnf("reportcore: set panes: %v", err)
}
+ autoFitColumns(f, sheet, headers, len(approvals))
+
var buf bytes.Buffer
if err := f.Write(&buf); err != nil {
return nil, fmt.Errorf("write excel: %w", err)
diff --git a/core/typescore/admin.go b/core/typescore/admin.go
index 0006a08..4b3e5b4 100644
--- a/core/typescore/admin.go
+++ b/core/typescore/admin.go
@@ -11,17 +11,24 @@ type Admin struct {
Name *string `gorm:"type:text;column:name" json:"name,omitempty" db:"name" mapstructure:"name"`
PasswordHash *string `gorm:"type:text;not null;column:password_hash" json:"-" db:"password_hash" mapstructure:"password_hash"`
IsRoot *bool `gorm:"type:boolean;not null;default:false;column:is_root" json:"is_root" db:"is_root" mapstructure:"is_root"`
+ IsAnalyst *bool `gorm:"type:boolean;not null;default:false;column:is_analyst" json:"is_analyst" db:"is_analyst" mapstructure:"is_analyst"`
+ IsObserver *bool `gorm:"type:boolean;not null;default:false;column:is_observer" json:"is_observer" db:"is_observer" mapstructure:"is_observer"`
+ TelegramID *int64 `gorm:"type:bigint;column:telegram_id" json:"telegram_id,omitempty" db:"telegram_id" mapstructure:"telegram_id"`
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"`
IsBlocked *bool `gorm:"type:boolean;not null;index;default:false;column:is_blocked" json:"is_blocked" db:"is_blocked" mapstructure:"is_blocked"`
- Password *string `gorm:"-" json:"password,omitempty"`
+ Password *string `gorm:"-" json:"password,omitempty"`
+ TelegramUser *User `gorm:"-" json:"telegram_user,omitempty"`
}
type AdminReq struct {
- Login *string `json:"login"`
- Name *string `json:"name"`
- Password *string `json:"password"` // Пароль пользователя
- IsRoot *bool `json:"is_root"`
+ Login *string `json:"login"`
+ Name *string `json:"name"`
+ Password *string `json:"password"`
+ IsAnalyst *bool `json:"is_analyst"`
+ IsRoot *bool `json:"is_root"`
+ IsObserver *bool `json:"is_observer"`
+ TelegramID *int64 `json:"telegram_id"`
}
diff --git a/core/typescore/admin_action_log.go b/core/typescore/admin_action_log.go
new file mode 100644
index 0000000..eab6b54
--- /dev/null
+++ b/core/typescore/admin_action_log.go
@@ -0,0 +1,28 @@
+package typescore
+
+import "time"
+
+type AdminActionLog struct {
+ ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" json:"id" db:"id"`
+ AdminID *uint64 `gorm:"type:bigint;not null;index;column:admin_id" json:"admin_id" db:"admin_id"`
+ AdminLogin *string `gorm:"type:text;not null;column:admin_login" json:"admin_login" db:"admin_login"`
+ Action *string `gorm:"type:text;not null;column:action" json:"action" db:"action"`
+ EntityType *string `gorm:"type:text;not null;column:entity_type" json:"entity_type" db:"entity_type"`
+ EntityID *uint64 `gorm:"type:bigint;column:entity_id" json:"entity_id,omitempty" db:"entity_id"`
+ Description *string `gorm:"type:text;not null;column:description" json:"description" db:"description"`
+ Metadata *string `gorm:"type:jsonb;column:metadata" json:"metadata,omitempty" db:"metadata"`
+ CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"`
+
+ Admin *Admin `gorm:"-" json:"admin,omitempty"`
+}
+
+type AdminActionLogFilter struct {
+ AdminID *uint64
+ AdminLogin *string // ILIKE-подстрока
+ Action *string
+ EntityType *string
+ EntityID *uint64
+ DateFrom *time.Time
+ DateTo *time.Time
+ Search *string // ILIKE-подстрока по Description
+}
diff --git a/core/typescore/approval.go b/core/typescore/approval.go
index d165d9b..6125d64 100644
--- a/core/typescore/approval.go
+++ b/core/typescore/approval.go
@@ -20,6 +20,20 @@ func (status ApprovalStatus) String() string {
return string(status)
}
+// ApprovalFilter — расширенный фильтр для списка заявок
+type ApprovalFilter struct {
+ ID *uint64 `json:"id"`
+ Status *string `json:"status,omitempty"`
+ InitiatorID *uint64 `json:"initiator_id,omitempty"`
+ DepartmentID *uint64 `json:"department_id,omitempty"`
+ Content *string `json:"content,omitempty"`
+ DateFrom *time.Time `json:"date_from,omitempty"`
+ DateTo *time.Time `json:"date_to,omitempty"`
+ CategoryIDs []uint64 `json:"category_ids,omitempty"` // множественный выбор категорий
+ TopicIDs []uint64 `json:"topic_ids,omitempty"` // множественный выбор тем
+ ObserverUserID *uint64 `json:"observer_user_id"`
+}
+
// Approval — заявка на согласование.
// Status: draft | pending | approved | rejected | revoked
// DepartmentID копируется с инициатора в момент создания — для отчётов и изоляции без JOIN.
diff --git a/core/typescore/approval_delegation.go b/core/typescore/approval_delegation.go
index 03e9aae..202395e 100644
--- a/core/typescore/approval_delegation.go
+++ b/core/typescore/approval_delegation.go
@@ -12,6 +12,7 @@ type ApprovalDelegation struct {
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"`
+ ApprovalID *uint64 `gorm:"type:bigint;index;column:approval_id" json:"approval_id,omitempty" db:"approval_id" mapstructure:"approval_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"`
diff --git a/core/typescore/approval_flow_node.go b/core/typescore/approval_flow_node.go
new file mode 100644
index 0000000..8ff9045
--- /dev/null
+++ b/core/typescore/approval_flow_node.go
@@ -0,0 +1,37 @@
+package typescore
+
+import "time"
+
+// ApprovalFlowNode — узел дерева навигации темы согласования
+type ApprovalFlowNode struct {
+ ID *uint64 `gorm:"column:id;type:bigserial;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"`
+ TopicID *uint64 `gorm:"type:bigint;index;column:topic_id" json:"topic_id,omitempty" db:"topic_id" mapstructure:"topic_id"`
+ ParentID *uint64 `gorm:"type:bigint;index;column:parent_id" json:"parent_id,omitempty" db:"parent_id" mapstructure:"parent_id"`
+ CategoryID *uint64 `gorm:"type:bigint;not null;index;column:category_id" json:"category_id" db:"category_id" mapstructure:"category_id"`
+
+ Key *string `gorm:"type:text;not null;column:key" json:"key" db:"key" mapstructure:"key"`
+ Label *string `gorm:"type:text;not null;column:label" json:"label" db:"label" mapstructure:"label"`
+
+ DataKey *string `gorm:"type:text;column:data_key" json:"data_key,omitempty" db:"data_key" mapstructure:"data_key"`
+ DataValue *string `gorm:"type:text;column:data_value" json:"data_value,omitempty" db:"data_value" mapstructure:"data_value"`
+
+ IsInput *bool `gorm:"type:boolean;default:false;column:is_input" json:"is_input" db:"is_input" mapstructure:"is_input"`
+ InputKey *string `gorm:"type:text;column:input_key" json:"input_key,omitempty" db:"input_key" mapstructure:"input_key"`
+ InputHint *string `gorm:"type:text;column:input_hint" json:"input_hint,omitempty" db:"input_hint" mapstructure:"input_hint"`
+
+ IsMultiSelect *bool `gorm:"type:boolean;default:false;column:is_multi_select" json:"is_multi_select" db:"is_multi_select" mapstructure:"is_multi_select"`
+ MultiSelectKey *string `gorm:"type:text;column:multi_select_key" json:"multi_select_key,omitempty" db:"multi_select_key" mapstructure:"multi_select_key"`
+ MultiSelectValue *string `gorm:"type:text;column:multi_select_value" json:"multi_select_value,omitempty" db:"multi_select_value" mapstructure:"multi_select_value"`
+
+ TopicCode *string `gorm:"type:text;column:topic_code" json:"topic_code,omitempty" db:"topic_code" mapstructure:"topic_code"`
+
+ SortOrder *int `gorm:"type:integer;default:0;column:sort_order" json:"sort_order" db:"sort_order" mapstructure:"sort_order"`
+
+ CodeTemplate *string `gorm:"type:text;column:code_template" json:"code_template,omitempty" db:"code_template" mapstructure:"code_template"`
+ MessageTemplate *string `gorm:"type:text;column:message_template" json:"message_template,omitempty" db:"message_template" mapstructure:"message_template"`
+
+ CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at" mapstructure:"created_at"`
+ UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at" mapstructure:"updated_at"`
+
+ Children []*ApprovalFlowNode `gorm:"-" json:"children,omitempty"`
+}
diff --git a/core/typescore/approval_revocation_request.go b/core/typescore/approval_revocation_request.go
new file mode 100644
index 0000000..cf29282
--- /dev/null
+++ b/core/typescore/approval_revocation_request.go
@@ -0,0 +1,23 @@
+package typescore
+
+import "time"
+
+type ApprovalRevocationRequest struct {
+ ID *uint64 `gorm:"column:id" json:"id" db:"id"`
+ ApprovalID *uint64 `gorm:"column:approval_id" json:"approval_id" db:"approval_id"`
+ RequestedByID *uint64 `gorm:"column:requested_by_id" json:"requested_by_id" db:"requested_by_id"`
+ Reason *string `gorm:"column:reason" json:"reason,omitempty" db:"reason"`
+ Status *string `gorm:"column:status" json:"status" db:"status"`
+ CreatedAt *time.Time `gorm:"column:created_at" json:"created_at" db:"created_at"`
+ UpdatedAt *time.Time `gorm:"column:updated_at" json:"updated_at" db:"updated_at"`
+}
+
+type ApprovalRevocationApprover struct {
+ ID *uint64 `gorm:"column:id" json:"id" db:"id"`
+ RevocationRequestID *uint64 `gorm:"column:revocation_request_id" json:"revocation_request_id" db:"revocation_request_id"`
+ ApproverID *uint64 `gorm:"column:approver_id" json:"approver_id" db:"approver_id"`
+ Status *string `gorm:"column:status" json:"status" db:"status"`
+ Comment *string `gorm:"column:comment" json:"comment,omitempty" db:"comment"`
+ ActedAt *time.Time `gorm:"column:acted_at" json:"acted_at,omitempty" db:"acted_at"`
+ CreatedAt *time.Time `gorm:"column:created_at" json:"created_at" db:"created_at"`
+}
diff --git a/core/typescore/approval_task.go b/core/typescore/approval_task.go
index eb4758d..7049be4 100644
--- a/core/typescore/approval_task.go
+++ b/core/typescore/approval_task.go
@@ -15,7 +15,8 @@ type ApprovalTask struct {
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"`
- Files []*ApprovalFile `gorm:"-" json:"files,omitempty"`
+ ObserverUserID *uint64 `json:"observer_user_id,omitempty" db:"-" ignore_db:"true"`
+ Approval *Approval `gorm:"-" json:"approval,omitempty"`
+ Executor *User `gorm:"-" json:"executor,omitempty"`
+ Files []*ApprovalFile `gorm:"-" json:"files,omitempty"`
}
diff --git a/core/typescore/approval_task_transfer.go b/core/typescore/approval_task_transfer.go
new file mode 100644
index 0000000..3752dc6
--- /dev/null
+++ b/core/typescore/approval_task_transfer.go
@@ -0,0 +1,13 @@
+package typescore
+
+import "time"
+
+type ApprovalTaskTransfer struct {
+ ID *uint64 `gorm:"column:id;primaryKey;autoIncrement" json:"id" db:"id"`
+ TaskID *uint64 `gorm:"column:task_id;not null" json:"task_id" db:"task_id"`
+ FromExecutorID *uint64 `gorm:"column:from_executor_id;not null" json:"from_executor_id" db:"from_executor_id"`
+ ToExecutorID *uint64 `gorm:"column:to_executor_id;not null" json:"to_executor_id" db:"to_executor_id"`
+ Status *string `gorm:"column:status;type:text;not null;default:'pending'" json:"status" db:"status"`
+ CreatedAt *time.Time `gorm:"column:created_at;default:CURRENT_TIMESTAMP" json:"created_at" db:"created_at"`
+ RespondedAt *time.Time `gorm:"column:responded_at" json:"responded_at,omitempty" db:"responded_at"`
+}
diff --git a/core/typescore/approval_topic.go b/core/typescore/approval_topic.go
index 5294fd1..3e3c3ae 100644
--- a/core/typescore/approval_topic.go
+++ b/core/typescore/approval_topic.go
@@ -29,6 +29,7 @@ type ApprovalTopic struct {
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"`
+ AllowDelegationSelection *bool `gorm:"type:boolean;not null;default:false;column:allow_delegation_selection" json:"allow_delegation_selection,omitempty" db:"allow_delegation_selection" mapstructure:"allow_delegation_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"`
diff --git a/core/typescore/director_notification.go b/core/typescore/director_notification.go
new file mode 100644
index 0000000..b14a712
--- /dev/null
+++ b/core/typescore/director_notification.go
@@ -0,0 +1,10 @@
+package typescore
+
+import "time"
+
+type DirectorNotificationSubscription struct {
+ ID *uint64 `gorm:"column:id" json:"id" db:"id"`
+ DirectorID *uint64 `gorm:"column:director_id" json:"director_id" db:"director_id"`
+ CategoryID *uint64 `gorm:"column:category_id" json:"category_id" db:"category_id"`
+ CreatedAt *time.Time `gorm:"column:created_at" json:"created_at" db:"created_at"`
+}
diff --git a/core/typescore/monthly_orders.go b/core/typescore/monthly_orders.go
new file mode 100644
index 0000000..44fd618
--- /dev/null
+++ b/core/typescore/monthly_orders.go
@@ -0,0 +1,62 @@
+package typescore
+
+import "time"
+
+// MonthlyOrderSetting — настройки периода заказа (задаются аналитиком)
+type MonthlyOrderSetting struct {
+ ID *uint64 `json:"id" db:"id" gorm:"primaryKey;autoIncrement"`
+ Month *int `json:"month" db:"month"`
+ Year *int `json:"year" db:"year"`
+ DeadlineDate *time.Time `json:"deadline_date" db:"deadline_date"` // Дата закрытия доступа
+ AssemblyTimeDays *int `json:"assembly_time_days" db:"assembly_time_days"` // Срок сборки заказа (задается аналитиком)
+ CreatedAt *time.Time `json:"created_at" db:"created_at"`
+ UpdatedAt *time.Time `json:"updated_at" db:"updated_at"`
+}
+
+// MonthlyOrderClient — заказ конкретного клиента у менеджера
+type MonthlyOrderClient struct {
+ ID *uint64 `json:"id" db:"id" gorm:"primaryKey;autoIncrement"`
+ ManagerID *uint64 `json:"manager_id" db:"manager_id"`
+ Month *int `json:"month" db:"month"`
+ Year *int `json:"year" db:"year"`
+ ClientName *string `json:"client_name" db:"client_name"`
+
+ OrderType *string `json:"order_type" db:"order_type"`
+
+ // Комментарии
+ ManagerComment *string `json:"manager_comment" db:"manager_comment"` // Основной из списка
+ CustomReason *string `json:"custom_reason" db:"custom_reason"` // Причина, если "Заказа не будет"
+ FreeFormComment *string `json:"free_form_comment" db:"free_form_comment"` // Свободный текст в конце
+
+ // Сопроводительная информация
+ Decade *string `json:"decade" db:"decade"`
+ Delivery *string `json:"delivery" db:"delivery"`
+ Conditions *string `json:"conditions" db:"conditions"`
+ PaymentForm *string `json:"payment_form" db:"payment_form"`
+
+ Status *string `json:"status" db:"status"` // draft, submitted, approved
+ ApprovalID *uint64 `json:"approval_id" db:"approval_id"` // ID созданной заявки в боте (если уже отправлено)
+ CreatedAt *time.Time `json:"created_at" db:"created_at"`
+ UpdatedAt *time.Time `json:"updated_at" db:"updated_at"`
+
+ // Связи (не хранятся напрямую в этой таблице)
+ Items []MonthlyOrderItem `json:"items,omitempty" gorm:"-"`
+ Files []MonthlyOrderFile `json:"files,omitempty" gorm:"-"`
+}
+
+// MonthlyOrderItem — конкретная номенклатура и ее количество в заказе клиента
+type MonthlyOrderItem struct {
+ ID *uint64 `json:"id" db:"id" gorm:"primaryKey;autoIncrement"`
+ OrderClientID *uint64 `json:"order_client_id" db:"order_client_id"`
+ NomenclatureName *string `json:"nomenclature_name" db:"nomenclature_name"`
+ NomenclatureType *string `json:"nomenclature_type" db:"nomenclature_type"`
+ Quantity *int `json:"quantity" db:"quantity"`
+}
+
+// MonthlyOrderFile — приложенные файлы к заказе клиента
+type MonthlyOrderFile struct {
+ ID *uint64 `json:"id" db:"id" gorm:"primaryKey;autoIncrement"`
+ OrderClientID *uint64 `json:"order_client_id" db:"order_client_id"`
+ FileBase64 *string `json:"file_base64" db:"file_base64"`
+ FileName *string `json:"file_name" db:"file_name"`
+}
diff --git a/core/typescore/notifications.go b/core/typescore/notifications.go
new file mode 100644
index 0000000..d02ebf2
--- /dev/null
+++ b/core/typescore/notifications.go
@@ -0,0 +1,54 @@
+package typescore
+
+import "time"
+
+// Notification — рассылка/уведомление
+type Notification struct {
+ ID *uint64 `gorm:"column:id" json:"id" db:"id"`
+ Title *string `gorm:"column:title" json:"title" db:"title"`
+ MessageHTML *string `gorm:"column:message_html" json:"message_html" db:"message_html"`
+ PhotoBase64 *string `gorm:"column:photo_base64" json:"photo_base64,omitempty" db:"photo_base64"`
+ PhotoFileName *string `gorm:"column:photo_file_name" json:"photo_file_name,omitempty" db:"photo_file_name"`
+ TargetFilters *string `gorm:"column:target_filters" json:"target_filters" db:"target_filters"` // JSON-строка
+ Status *string `gorm:"column:status" json:"status" db:"status"`
+ TotalCount *int `gorm:"column:total_count" json:"total_count" db:"total_count"`
+ SentCount *int `gorm:"column:sent_count" json:"sent_count" db:"sent_count"`
+ FailedCount *int `gorm:"column:failed_count" json:"failed_count" db:"failed_count"`
+ CreatedByID *uint64 `gorm:"column:created_by_id" json:"created_by_id,omitempty" db:"created_by_id"`
+ CreatedAt *time.Time `gorm:"column:created_at" json:"created_at" db:"created_at"`
+ UpdatedAt *time.Time `gorm:"column:updated_at" json:"updated_at" db:"updated_at"`
+ SentAt *time.Time `gorm:"column:sent_at" json:"sent_at,omitempty" db:"sent_at"`
+
+ Recipients []*NotificationRecipient `gorm:"-" json:"recipients,omitempty"`
+}
+
+// NotificationRecipient — история доставки конкретному пользователю
+type NotificationRecipient struct {
+ ID *uint64 `gorm:"column:id" json:"id" db:"id"`
+ NotificationID *uint64 `gorm:"column:notification_id" json:"notification_id" db:"notification_id"`
+ UserID *uint64 `gorm:"column:user_id" json:"user_id" db:"user_id"`
+ Status *string `gorm:"column:status" json:"status" db:"status"`
+ ErrorMessage *string `gorm:"column:error_message" json:"error_message,omitempty" db:"error_message"`
+ TelegramMessageID *int `gorm:"column:telegram_message_id" json:"telegram_message_id,omitempty" db:"telegram_message_id"`
+ SentAt *time.Time `gorm:"column:sent_at" json:"sent_at,omitempty" db:"sent_at"`
+ CreatedAt *time.Time `gorm:"column:created_at" json:"created_at" db:"created_at"`
+
+ User *User `gorm:"-" json:"user,omitempty"`
+}
+
+// TargetFilters — критерии выбора получателей, приходят из админки и сохраняются как есть в JSONB
+type TargetFilters struct {
+ UserIDs []uint64 `json:"user_ids,omitempty"` // 1. конкретные пользователи
+ RoleIDs []uint64 `json:"role_ids,omitempty"` // 2. конкретные роли (по id)
+ RoleTypeFlags []string `json:"role_type_flags,omitempty"` // 3. типы ролей: director|approver|observer|executor|controller
+ DepartmentIDs []uint64 `json:"department_ids,omitempty"` // 4. отделы
+}
+
+// CreateNotificationReq — тело запроса на создание+отправку рассылки
+type CreateNotificationReq struct {
+ Title string `json:"title"`
+ MessageHTML string `json:"message_html"`
+ PhotoBase64 *string `json:"photo_base64,omitempty"`
+ PhotoFileName *string `json:"photo_file_name,omitempty"`
+ Targets TargetFilters `json:"targets"`
+}
diff --git a/core/typescore/role.go b/core/typescore/role.go
index a9445d6..5a79688 100644
--- a/core/typescore/role.go
+++ b/core/typescore/role.go
@@ -3,17 +3,18 @@ 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"`
+ 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"`
+ IsController *bool `gorm:"type:boolean;not null;default:false;column:is_controller" json:"is_controller" db:"is_controller" mapstructure:"is_controller"`
+ 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/task_delegations.go b/core/typescore/task_delegations.go
new file mode 100644
index 0000000..58317a0
--- /dev/null
+++ b/core/typescore/task_delegations.go
@@ -0,0 +1,21 @@
+package typescore
+
+import "time"
+
+type TaskDelegation 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"`
+ 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"`
+ ApprovalID *uint64 `gorm:"type:bigint;index;column:approval_id" json:"approval_id,omitempty" db:"approval_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"`
+
+ Delegator *User `gorm:"-" json:"delegator,omitempty"`
+ Delegate *User `gorm:"-" json:"delegate,omitempty"`
+}
diff --git a/core/typescore/telephony.go b/core/typescore/telephony.go
new file mode 100644
index 0000000..716f277
--- /dev/null
+++ b/core/typescore/telephony.go
@@ -0,0 +1,78 @@
+package typescore
+
+import (
+ "encoding/json"
+ "time"
+)
+
+// SmsLog - модель для хранения истории SMS
+type SmsLog struct {
+ ID *uint64 `json:"id" db:"id" gorm:"column:id;primaryKey;autoIncrement"`
+ AccountID *string `json:"account_id" db:"account_id" gorm:"column:account_id"`
+ UserID *string `json:"user_id" db:"user_id" gorm:"column:user_id"`
+ ClientNumber *string `json:"client_number" db:"client_number" gorm:"column:client_number;index"`
+ Direction *int `json:"direction" db:"direction" gorm:"column:direction"`
+ Text *string `json:"text" db:"text" gorm:"column:text"`
+ EventCreated *time.Time `json:"event_created" db:"event_created" gorm:"column:event_created;index"`
+ CreatedAt *time.Time `json:"created_at" db:"created_at" gorm:"column:created_at;default:CURRENT_TIMESTAMP"`
+}
+
+// TelephonyWebhookReq описывает корневой объект POST-запроса от Webhook API
+type TelephonyWebhookReq struct {
+ Webhook WebhookMeta `json:"webhook"`
+ Event CallEvent `json:"event"`
+}
+
+// WebhookMeta содержит метаданные о том, кто и где сгенерировал событие
+type WebhookMeta struct {
+ Action string `json:"action"`
+ AccountID string `json:"account_id"`
+ AccountName string `json:"account_name"`
+ UserID string `json:"user_id"`
+ UserLogin string `json:"user_login"`
+}
+
+// CallEvent описывает полезную нагрузку события (звонок или SMS)
+type CallEvent struct {
+ EventType int `json:"event_type"` // 1 - начало; 2 - ответ; 4 - окончание; 32 - SMS
+ EventCreated int64 `json:"event_created"`
+ Direction int `json:"direction"` // 0 - входящий, 1 - исходящий
+ ClientNumber string `json:"client_number"`
+ ClientName string `json:"client_name"`
+ SrcNumber string `json:"src_number"`
+ SrcSlot int `json:"src_slot"`
+
+ EventPbxCallID FlexString `json:"event_pbx_call_id"`
+ SrcID FlexString `json:"src_id"`
+ DBCallID FlexString `json:"db_call_id,omitempty"`
+
+ // Поля, которые приходят только в событии окончания звонка (event_type == 4)
+ StartTime int64 `json:"start_time,omitempty"`
+ AnswerTime int64 `json:"answer_time,omitempty"`
+ EndTime int64 `json:"end_time,omitempty"`
+ Duration int `json:"duration,omitempty"`
+ Answered int `json:"answered,omitempty"` // 0 - не отвечен, 1 - отвечен
+ Recording string `json:"recording,omitempty"` // Ссылка на запись разговора
+
+ // Поле, которое приходит только для SMS (event_type == 32)
+ Text string `json:"text,omitempty"`
+}
+
+// FlexString принимает JSON-строку или число.
+type FlexString string
+
+func (f *FlexString) UnmarshalJSON(b []byte) error {
+ if string(b) == "null" {
+ return nil
+ }
+ if len(b) > 0 && b[0] == '"' {
+ var s string
+ if err := json.Unmarshal(b, &s); err != nil {
+ return err
+ }
+ *f = FlexString(s)
+ return nil
+ }
+ *f = FlexString(b) // число как есть
+ return nil
+}
diff --git a/core/typescore/user_hierarchy.go b/core/typescore/user_hierarchy.go
index c8857e0..df9300d 100644
--- a/core/typescore/user_hierarchy.go
+++ b/core/typescore/user_hierarchy.go
@@ -15,6 +15,7 @@ type UserHierarchy struct {
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"`
+ TargetSystem *string `gorm:"type:text;column:target_system" json:"target_system,omitempty" db:"target_system" mapstructure:"target_system"`
Subordinate *User `gorm:"-" json:"subordinate,omitempty"`
Approver *User `gorm:"-" json:"approver,omitempty"`
diff --git a/core/utilscore/eq.go b/core/utilscore/eq.go
new file mode 100644
index 0000000..de487f2
--- /dev/null
+++ b/core/utilscore/eq.go
@@ -0,0 +1,62 @@
+package utilscore
+
+func DerefStr(s *string) string {
+ if s == nil {
+ return ""
+ }
+ return *s
+}
+
+func DerefBool(b *bool) bool {
+ if b == nil {
+ return false
+ }
+ return *b
+}
+
+func StrEq(a, b *string) bool {
+ if a == nil && b == nil {
+ return true
+ }
+ if a == nil || b == nil {
+ return false
+ }
+ return *a == *b
+}
+
+func BoolEq(a, b *bool) bool {
+ if a == nil && b == nil {
+ return true
+ }
+ if a == nil || b == nil {
+ return false
+ }
+ return *a == *b
+}
+
+func Uint64Eq(a, b *uint64) bool {
+ if a == nil && b == nil {
+ return true
+ }
+ if a == nil || b == nil {
+ return false
+ }
+ return *a == *b
+}
+
+func IntEq(a, b *int) bool {
+ if a == nil && b == nil {
+ return true
+ }
+ if a == nil || b == nil {
+ return false
+ }
+ return *a == *b
+}
+
+func DerefInt(i *int) int {
+ if i == nil {
+ return 0
+ }
+ return *i
+}
diff --git a/core/variables/const.go b/core/variables/const.go
index e61b7c4..ef00c5e 100644
--- a/core/variables/const.go
+++ b/core/variables/const.go
@@ -8,3 +8,10 @@ const (
ContextTimeoutBase = 15 * time.Second
ContextTimeoutLong = 30 * time.Second
)
+
+// Константы для нового API-прокси
+const (
+ ProxyForwardURL = "https://37.252.5.229.nip.io/forward"
+ ProxySecretHeader = "X-Proxy-Secret"
+ ProxySecretKey = "9cb0a2655bde593de45b2f3fd17f39e5"
+)
diff --git a/deploy.sh b/deploy.sh
index 4b91eb0..644015f 100644
--- a/deploy.sh
+++ b/deploy.sh
@@ -34,14 +34,14 @@ GENERATE_SWAGGER="${2:-false}"
validate_service_type() {
case "$1" in
- bot|telegram|balancer|admin|migrations|all) return 0 ;;
+ bot|telegram|balancer|admin|migrations|telephony|all) return 0 ;; # 🆕 Добавлен telephony
*) return 1 ;;
esac
}
if ! validate_service_type "$SERVICE_TYPE"; then
log_error "Unknown service type: $SERVICE_TYPE"
- echo "Usage: $0 [telegram|balancer|admin|migrations|all] [swagger]"
+ echo "Usage: $0 [telegram|balancer|admin|migrations|telephony|all] [swagger]"
exit 1
fi
@@ -54,20 +54,25 @@ if [ "$SERVICE_TYPE" = "all" ]; then
SELF="$THIS_PATH/deploy.sh"
- log_service "Step 1/4: Database migrations"
+ log_service "Step 1/5: Database migrations"
bash "$SELF" migrations
echo ""
- log_service "Step 2/4: Telegram bot"
+ log_service "Step 2/5: Telegram bot"
bash "$SELF" telegram
echo ""
-# log_service "Step 3/4: REST balancer"
+# log_service "Step 3/5: REST balancer"
# bash "$SELF" balancer
# echo ""
- log_service "Step 4/4: REST admin"
+ log_service "Step 4/5: REST admin"
bash "$SELF" admin "$GENERATE_SWAGGER"
+ echo ""
+
+ log_service "Step 5/5: REST telephony" # 🆕 Добавлен шаг деплоя телефонии
+ bash "$SELF" telephony
+ echo ""
echo ""
log_success "All services deployed successfully!"
@@ -96,6 +101,11 @@ case "$SERVICE_TYPE" in
migrations)
SERVICE_NAME="system_service"
DESCRIPTION="Database Migrations"
+ SERVICE_KIND="oneshot" # 🔧 ИСПРАВЛЕНИЕ: здесь раньше ошибочно стояло "daemon"
+ ;;
+ telephony) # 🆕 Конфигурация для нового сервиса
+ SERVICE_NAME="rest_telephony_service"
+ DESCRIPTION="REST Telephony Service"
SERVICE_KIND="daemon"
;;
esac
@@ -142,7 +152,7 @@ if [ "$SERVICE_TYPE" = "admin" ] && [ "$GENERATE_SWAGGER" = "swagger" ]; then
cd "$MAIN_DIR"
- # Исправлено: Явно передаем имя файла через -g, так как оно отличается от main.go
+ # Явно передаем имя файла через -g, так как оно отличается от main.go
swag init -g "$FILE_NAME" --parseDependency --parseInternal
# Если мы генерировали в подпапке, переносим папку docs в корень сервиса
@@ -151,7 +161,9 @@ if [ "$SERVICE_TYPE" = "admin" ] && [ "$GENERATE_SWAGGER" = "swagger" ]; then
mv ./docs "$SERVICE_PATH/docs"
log_success "Swagger documentation moved to service root"
fi
- sudo chown -R git:git "$SERVICE_PATH/docs"
+
+ # 🔧 ИСПРАВЛЕНИЕ: Отдаем права пользователю rom4ik, чтобы GitHub Actions не падал!
+ chown -R rom4ik:rom4ik "$SERVICE_PATH/docs"
cd "$SERVICE_PATH"
else
@@ -200,7 +212,7 @@ if [ "$SERVICE_KIND" = "daemon" ]; then
log_warning "Systemd unit not found: /etc/systemd/system/$SERVICE_NAME.service"
log_info "Creating systemd unit..."
- sudo tee /etc/systemd/system/$SERVICE_NAME.service > /dev/null < /dev/null < /dev/null < /dev/null <` — 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,
+ Telegram: 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,
+ TGBotClient: clientsExternal.Telegram,
+ }, 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)
+ router.Use(middleware.Recoverer)
+ // Добавляем ограничение по 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},
+ {"approval-tasks", approvaltaskshandler.RegisterApprovalTasksRoutes},
+ {"dashboard", dashboardhandler.RegisterDashboardRoutes},
+ {"notifications", notificationshandler.RegisterNotificationRoutes},
+ {"flownodes", nodeshandler.RegisterFlowNodesRoutes},
+ {"approvalextras", approvalextrashandler.RegisterApprovalExtrasRoutes},
+ {"adminlog", adminloghandler.RegisterAdminLogRoutes},
+ }
+
+ // Регистрация всех маршрутов
+ 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
+}
+
+-----END cmd/app.go-----
+
+File: docs/docs.go
+Lines: 3990
+-----BEGIN docs/docs.go-----
+// 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)
+}
+
+-----END docs/docs.go-----
+
+File: handlers/admin/handlers.go
+Lines: 502
+-----BEGIN handlers/admin/handlers.go-----
+package adminhandler
+
+import (
+ "bitrix_balancer_api/core/securecore"
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/core/utilscore"
+ "bitrix_balancer_api/rest_admin_service/handlers"
+ adminloghandler "bitrix_balancer_api/rest_admin_service/handlers/admin_actions"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "github.com/sirupsen/logrus"
+ "io"
+ "net/http"
+ "strings"
+)
+
+// 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
+ }
+
+ ctx := r.Context()
+ for _, admin := range adminsDbLst {
+ if admin.TelegramID != nil {
+ telegramUser, err := s.ipc.Database.User.GetUserByTelegramIDDB(ctx, *admin.TelegramID)
+ if err == nil && telegramUser != nil {
+ admin.TelegramUser = telegramUser
+ }
+ }
+ }
+
+ return &typescore.ApiResponseBase{
+ TotalCount: total,
+ Data: adminsDbLst,
+ }, nil
+}
+
+// CreateAdminHandler Создание администратора
+func (s *AdminsReg) CreateAdminHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ defer r.Body.Close()
+
+ // Проверка, что текущий админ — root
+ currentUserID, err := handlers.GetIDFromContext(r.Context())
+ if err != nil {
+ return nil, errors.New("user not authenticated")
+ }
+
+ currentAdmins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{
+ Filtering: &typescore.Admin{ID: ¤tUserID},
+ })
+ if err != nil || len(currentAdmins) == 0 {
+ return nil, errors.New("current admin not found")
+ }
+
+ if currentAdmins[0].IsRoot == nil || !*currentAdmins[0].IsRoot {
+ return nil, errors.New("only_root_can_create_admins")
+ }
+
+ 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
+ }
+
+ if req.Login == nil || *req.Login == "" {
+ return nil, errors.New("login is required")
+ }
+
+ if req.IsObserver != nil && *req.IsObserver {
+ if req.TelegramID == nil {
+ return nil, errors.New("telegram_id_required_for_observer")
+ }
+ telegramUser, err := s.ipc.Database.User.GetUserByTelegramIDDB(r.Context(), *req.TelegramID)
+ if err != nil || telegramUser == nil {
+ return nil, errors.New("telegram_user_not_found")
+ }
+ }
+
+ // Проверка уникальности логина
+ 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,
+ Name: req.Name,
+ PasswordHash: tempPasswordHash,
+ IsRoot: req.IsRoot,
+ IsObserver: req.IsObserver,
+ TelegramID: req.TelegramID,
+ }
+
+ newAdmin, _, err := s.ipc.Database.Admin.CreateAdminDB(nil, newAdminObj, true)
+ if err != nil {
+ return nil, err
+ }
+
+ newAdmin.Password = &tempPassword
+
+ userID, err := handlers.GetIDFromContext(r.Context())
+ if err != nil {
+ logrus.Errorf("Failed to get user id: %v", err)
+ } else {
+ admins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{
+ Filtering: &typescore.Admin{
+ ID: &userID,
+ },
+ })
+ if err != nil {
+ logrus.Errorf("get admin list error: %v", err)
+ }
+ if len(admins) > 0 && admins[0] != nil {
+ snapshot := map[string]interface{}{
+ "login": derefStr(newAdmin.Login),
+ "name": derefStr(newAdmin.Name),
+ "is_root": derefBool(newAdmin.IsRoot),
+ "is_observer": derefBool(newAdmin.IsObserver),
+ }
+ if newAdmin.TelegramID != nil {
+ snapshot["telegram_id"] = *newAdmin.TelegramID
+ }
+
+ adminloghandler.LogAdminActionWithMetadata(
+ r.Context(), s.ipc,
+ *admins[0].ID, *admins[0].Login,
+ "create", "admin", newAdmin.ID,
+ fmt.Sprintf("Создан администратор «%s»", *newAdmin.Login),
+ map[string]interface{}{"snapshot": snapshot},
+ )
+ }
+ }
+
+ return newAdmin, nil
+}
+
+// UpdateAdminHandler Обновление администратора
+func (s *AdminsReg) UpdateAdminHandler(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, errors.New("invalid request body")
+ }
+
+ if req.ID == nil {
+ return nil, errors.New("admin id is required")
+ }
+
+ // Получаем существующего админа
+ existingAdmins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{
+ Filtering: &typescore.Admin{ID: req.ID},
+ })
+ if err != nil || len(existingAdmins) == 0 {
+ return nil, errors.New("admin not found")
+ }
+ existing := existingAdmins[0]
+
+ // Получаем текущего админа
+ currentUserID, err := handlers.GetIDFromContext(r.Context())
+ if err != nil {
+ return nil, errors.New("user not authenticated")
+ }
+ currentAdmins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{
+ Filtering: &typescore.Admin{ID: ¤tUserID},
+ })
+ if err != nil || len(currentAdmins) == 0 {
+ return nil, errors.New("current admin not found")
+ }
+ currentIsRoot := currentAdmins[0].IsRoot != nil && *currentAdmins[0].IsRoot
+
+ // Проверки root-прав (как было)
+ if req.IsRoot != nil {
+ if !currentIsRoot {
+ return nil, errors.New("only_root_can_manage_root_rights")
+ }
+ if *req.ID == currentUserID && !*req.IsRoot {
+ return nil, errors.New("cannot_remove_root_from_self")
+ }
+ if !*req.IsRoot && existing.IsRoot != nil && *existing.IsRoot {
+ allAdmins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{
+ Filtering: &typescore.Admin{},
+ })
+ if err == nil {
+ rootCount := 0
+ for _, a := range allAdmins {
+ if a.IsRoot != nil && *a.IsRoot {
+ rootCount++
+ }
+ }
+ if rootCount <= 1 {
+ return nil, errors.New("cannot_remove_last_root")
+ }
+ }
+ }
+ }
+
+ if req.IsBlocked != nil && *req.IsBlocked {
+ if existing.IsRoot != nil && *existing.IsRoot && !currentIsRoot {
+ return nil, errors.New("cannot_block_root")
+ }
+ }
+
+ if *req.ID == currentUserID && req.IsBlocked != nil && *req.IsBlocked {
+ return nil, errors.New("cannot_block_self")
+ }
+
+ isObserver := existing.IsObserver
+ telegramID := existing.TelegramID
+
+ if req.IsObserver != nil {
+ isObserver = req.IsObserver
+ }
+ if req.TelegramID != nil {
+ telegramID = req.TelegramID
+ }
+
+ if isObserver != nil && *isObserver {
+ if telegramID == nil {
+ return nil, errors.New("telegram_id_required_for_observer")
+ }
+ telegramUser, err := s.ipc.Database.User.GetUserByTelegramIDDB(r.Context(), *telegramID)
+ if err != nil || telegramUser == nil {
+ return nil, errors.New("telegram_user_not_found")
+ }
+ }
+
+ type fieldChange struct {
+ Field string `json:"field"`
+ Old interface{} `json:"old"`
+ New interface{} `json:"new"`
+ }
+ var changes []fieldChange
+ var summary []string
+
+ if req.Name != nil && !strEq(existing.Name, req.Name) {
+ changes = append(changes, fieldChange{"name", derefStr(existing.Name), *req.Name})
+ summary = append(summary, fmt.Sprintf("имя: «%s» → «%s»", derefStr(existing.Name), *req.Name))
+ }
+ if req.IsBlocked != nil && !boolEq(existing.IsBlocked, req.IsBlocked) {
+ changes = append(changes, fieldChange{"is_blocked", derefBool(existing.IsBlocked), *req.IsBlocked})
+ if *req.IsBlocked {
+ summary = append(summary, "заблокирован")
+ } else {
+ summary = append(summary, "разблокирован")
+ }
+ }
+ if req.IsRoot != nil && !boolEq(existing.IsRoot, req.IsRoot) {
+ changes = append(changes, fieldChange{"is_root", derefBool(existing.IsRoot), *req.IsRoot})
+ if *req.IsRoot {
+ summary = append(summary, "выдана роль root")
+ } else {
+ summary = append(summary, "роль root снята")
+ }
+ }
+ if req.IsObserver != nil && !boolEq(existing.IsObserver, req.IsObserver) {
+ changes = append(changes, fieldChange{"is_observer", derefBool(existing.IsObserver), *req.IsObserver})
+ if *req.IsObserver {
+ summary = append(summary, "включён режим наблюдателя")
+ } else {
+ summary = append(summary, "режим наблюдателя выключен")
+ }
+ }
+ if req.TelegramID != nil && !int64Eq(existing.TelegramID, req.TelegramID) {
+ var oldVal interface{}
+ if existing.TelegramID != nil {
+ oldVal = *existing.TelegramID
+ }
+ changes = append(changes, fieldChange{"telegram_id", oldVal, *req.TelegramID})
+ summary = append(summary, fmt.Sprintf("telegram_id: %v → %d", oldVal, *req.TelegramID))
+ }
+
+ // Создаём объект для обновления
+ updateObj := &typescore.Admin{
+ ID: req.ID,
+ }
+ if req.Name != nil {
+ updateObj.Name = req.Name
+ }
+ if req.IsBlocked != nil {
+ updateObj.IsBlocked = req.IsBlocked
+ }
+ if req.IsRoot != nil {
+ updateObj.IsRoot = req.IsRoot
+ }
+ if req.IsObserver != nil {
+ updateObj.IsObserver = req.IsObserver
+ }
+ if req.TelegramID != nil {
+ updateObj.TelegramID = req.TelegramID
+ }
+
+ updated, _, err := s.ipc.Database.Admin.UpdateAdminDB(nil, updateObj, true)
+ if err != nil {
+ return nil, err
+ }
+
+ // 🆕 Логируем ПОСЛЕ успешного обновления, и только если реально что-то
+ // изменилось (пустой запрос на обновление без факта изменений в
+ // журнал не пишем — иначе он будет засоряться).
+ if len(changes) > 0 {
+ description := fmt.Sprintf("Изменён администратор «%s»: %s", derefStr(existing.Login), strings.Join(summary, "; "))
+ adminloghandler.LogAdminActionWithMetadata(
+ r.Context(), s.ipc,
+ *currentAdmins[0].ID, *currentAdmins[0].Login,
+ "update", "admin", req.ID,
+ description,
+ map[string]interface{}{"changes": changes},
+ )
+ }
+
+ return updated, nil
+}
+
+// DeleteAdminHandler Удаление администратора
+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, errors.New("invalid request body")
+ }
+
+ if req.ID == nil {
+ return nil, errors.New("admin id is required")
+ }
+
+ // Нельзя удалить себя
+ currentUserID, err := handlers.GetIDFromContext(r.Context())
+ if err != nil {
+ return nil, errors.New("user not authenticated")
+ }
+ if *req.ID == currentUserID {
+ return nil, errors.New("cannot_delete_self")
+ }
+
+ // Получаем удаляемого админа
+ admins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{
+ Filtering: &typescore.Admin{ID: req.ID},
+ })
+ if err != nil || len(admins) == 0 {
+ return nil, errors.New("admin not found")
+ }
+
+ // 🆕 Нельзя удалить root (если текущий не root)
+ currentAdmins, _, _ := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{
+ Filtering: &typescore.Admin{ID: ¤tUserID},
+ })
+ currentIsRoot := len(currentAdmins) > 0 && currentAdmins[0].IsRoot != nil && *currentAdmins[0].IsRoot
+
+ targetIsRoot := admins[0].IsRoot != nil && *admins[0].IsRoot
+ if targetIsRoot && !currentIsRoot {
+ return nil, errors.New("cannot_delete_root")
+ }
+
+ // 🆕 Снапшот удаляемого администратора — берём ДО удаления (после
+ // DeleteAdminDB запись из БД уже не достать).
+ deletedSnapshot := map[string]interface{}{
+ "login": derefStr(admins[0].Login),
+ "name": derefStr(admins[0].Name),
+ "is_root": derefBool(admins[0].IsRoot),
+ "is_observer": derefBool(admins[0].IsObserver),
+ }
+ if admins[0].TelegramID != nil {
+ deletedSnapshot["telegram_id"] = *admins[0].TelegramID
+ }
+
+ err = s.ipc.Database.Admin.DeleteAdminDB(&req)
+ if err != nil {
+ return nil, err
+ }
+
+ if len(currentAdmins) > 0 && currentAdmins[0] != nil {
+ adminloghandler.LogAdminActionWithMetadata(
+ r.Context(), s.ipc,
+ *currentAdmins[0].ID, *currentAdmins[0].Login,
+ "delete", "admin", req.ID,
+ fmt.Sprintf("Удалён администратор «%s»", derefStr(admins[0].Login)),
+ map[string]interface{}{"snapshot": deletedSnapshot},
+ )
+ }
+
+ return true, nil
+}
+
+// ============================================================
+// Небольшие помощники сравнения/разыменования — чтобы не плодить
+// одинаковые проверки "оба nil или оба равны" по всему файлу.
+// ============================================================
+
+func derefStr(s *string) string {
+ if s == nil {
+ return ""
+ }
+ return *s
+}
+
+func derefBool(b *bool) bool {
+ if b == nil {
+ return false
+ }
+ return *b
+}
+
+func strEq(a, b *string) bool {
+ if a == nil && b == nil {
+ return true
+ }
+ if a == nil || b == nil {
+ return false
+ }
+ return *a == *b
+}
+
+func boolEq(a, b *bool) bool {
+ if a == nil && b == nil {
+ return true
+ }
+ if a == nil || b == nil {
+ return false
+ }
+ return *a == *b
+}
+
+func uint64Eq(a, b *uint64) bool {
+ if a == nil && b == nil {
+ return true
+ }
+ if a == nil || b == nil {
+ return false
+ }
+ return *a == *b
+}
+
+func int64Eq(a, b *int64) bool {
+ if a == nil && b == nil {
+ return true
+ }
+ if a == nil || b == nil {
+ return false
+ }
+ return *a == *b
+}
+
+-----END handlers/admin/handlers.go-----
+
+File: handlers/admin/routes.go
+Lines: 38
+-----BEGIN handlers/admin/routes.go-----
+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)
+ handlers.RegisterRoute(r, http.MethodPut, adminURL, s.UpdateAdminHandler)
+ })
+
+ return nil
+}
+
+-----END handlers/admin/routes.go-----
+
+File: handlers/admin_actions/handlers.go
+Lines: 210
+-----BEGIN handlers/admin_actions/handlers.go-----
+package adminloghandler
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/rest_admin_service/handlers"
+ typesm "bitrix_balancer_api/rest_admin_service/types"
+ "context"
+ "encoding/json"
+ "net/http"
+ "strconv"
+ "time"
+
+ "github.com/go-chi/chi/v5"
+ "github.com/sirupsen/logrus"
+)
+
+type AdminLogReg struct {
+ ipc *typesm.InternalProviderControl
+}
+
+func RegisterAdminLogRoutes(r chi.Router, ipc *typesm.InternalProviderControl) error {
+ s := &AdminLogReg{ipc: ipc}
+
+ r.Route("/api/admin-logs", 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.ListLogsHandler)
+ handlers.RegisterRoute(r, http.MethodDelete, "/{id}", s.DeleteLogEntryHandler)
+ })
+
+ return nil
+}
+
+// ListLogsHandler — теперь поддерживает:
+//
+// admin_id, admin_login (ILIKE), action, entity_type, entity_id,
+// date_from, date_to (YYYY-MM-DD, включительно на весь день),
+// search (ILIKE по description)
+func (s *AdminLogReg) ListLogsHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ ctx := r.Context()
+ q := r.URL.Query()
+
+ filter := typescore.AdminActionLogFilter{}
+
+ if v := q.Get("admin_id"); v != "" {
+ if id, err := strconv.ParseUint(v, 10, 64); err == nil {
+ filter.AdminID = &id
+ }
+ }
+ if v := q.Get("admin_login"); v != "" {
+ filter.AdminLogin = &v
+ }
+ if v := q.Get("action"); v != "" {
+ filter.Action = &v
+ }
+ if v := q.Get("entity_type"); v != "" {
+ filter.EntityType = &v
+ }
+ if v := q.Get("entity_id"); v != "" {
+ if id, err := strconv.ParseUint(v, 10, 64); err == nil {
+ filter.EntityID = &id
+ }
+ }
+ if v := q.Get("date_from"); v != "" {
+ if t, err := time.Parse("2006-01-02", v); err == nil {
+ filter.DateFrom = &t
+ }
+ }
+ if v := q.Get("date_to"); v != "" {
+ if t, err := time.Parse("2006-01-02", v); err == nil {
+ endOfDay := t.Add(24*time.Hour - time.Second)
+ filter.DateTo = &endOfDay
+ }
+ }
+ if v := q.Get("search"); v != "" {
+ filter.Search = &v
+ }
+
+ limit := parseUintPtr(q.Get("limit"), 50)
+ offset := parseUintPtr(q.Get("offset"), 0)
+
+ logs, totalCount, err := s.ipc.Database.AdminActionLogs.GetAdminActionLogsFilteredDB(ctx, filter, offset, limit)
+ if err != nil {
+ return nil, err
+ }
+
+ return map[string]interface{}{
+ "data": logs,
+ "total_count": totalCount,
+ }, nil
+}
+
+// DeleteLogEntryHandler — 🩹 восстановлена проверка is_root, потерянная
+// в промежуточной версии. Удалять записи журнала может только
+// root-администратор — без этой проверки endpoint открыт любому админу,
+// что сводит на нет саму цель журнала (неизменяемость для всех, кроме root).
+func (s *AdminLogReg) DeleteLogEntryHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ ctx := r.Context()
+
+ currentAdmin, ok := GetCurrentAdmin(ctx, s.ipc)
+ if !ok {
+ http.Error(w, "unauthorized", http.StatusUnauthorized)
+ return nil, nil
+ }
+ if currentAdmin.IsRoot == nil || !*currentAdmin.IsRoot {
+ http.Error(w, "только root-администратор может удалять записи журнала", http.StatusForbidden)
+ return nil, nil
+ }
+
+ id, err := strconv.ParseUint(chi.URLParam(r, "id"), 10, 64)
+ if err != nil {
+ return nil, err
+ }
+
+ if err := s.ipc.Database.AdminActionLogs.DeleteAdminActionLogDB(ctx, &typescore.AdminActionLog{ID: &id}); err != nil {
+ return nil, err
+ }
+
+ return map[string]interface{}{"success": true}, nil
+}
+
+func LogAdminAction(
+ ctx context.Context,
+ ipc *typesm.InternalProviderControl,
+ adminID uint64,
+ adminLogin string,
+ action string,
+ entityType string,
+ entityID *uint64,
+ description string,
+) {
+ LogAdminActionWithMetadata(ctx, ipc, adminID, adminLogin, action, entityType, entityID, description, nil)
+}
+
+func LogAdminActionWithMetadata(
+ ctx context.Context,
+ ipc *typesm.InternalProviderControl,
+ adminID uint64,
+ adminLogin string,
+ action string,
+ entityType string,
+ entityID *uint64,
+ description string,
+ metadata map[string]interface{},
+) {
+ var metadataJSON *string
+ if metadata != nil {
+ if b, err := json.Marshal(metadata); err == nil {
+ s := string(b)
+ metadataJSON = &s
+ } else {
+ logrus.Warnf("LogAdminActionWithMetadata: не удалось сериализовать metadata: %v", err)
+ }
+ }
+
+ now := time.Now()
+ entry := &typescore.AdminActionLog{
+ AdminID: &adminID,
+ AdminLogin: &adminLogin,
+ Action: &action,
+ EntityType: &entityType,
+ EntityID: entityID,
+ Description: &description,
+ Metadata: metadataJSON,
+ CreatedAt: &now,
+ }
+
+ if _, _, err := ipc.Database.AdminActionLogs.CreateAdminActionLogDB(ctx, nil, entry); err != nil {
+ logrus.Errorf("LogAdminActionWithMetadata: не удалось записать в журнал (admin=%s, action=%s, entity=%s:%v): %v",
+ adminLogin, action, entityType, entityID, err)
+ }
+}
+
+// GetCurrentAdmin — 🆕 вынесено сюда из 13 хендлеров, где было
+// продублировано один в один под именем getCurrentAdmin (локальная,
+// неэкспортируемая версия в каждом пакете отдельно). Экспортируемая
+// версия здесь, в "родном" пакете журнала — логичное место, раз уже
+// каждый из этих 13 хендлеров и так импортирует adminloghandler ради
+// LogAdminActionWithMetadata.
+//
+// Миграция существующих хендлеров не обязательна прямо сейчас (все они
+// рабочие как есть, с локальными копиями) — но при следующей правке
+// любого из них имеет смысл заменить его локальный getCurrentAdmin на
+// вызов adminloghandler.GetCurrentAdmin(ctx, s.ipc) и удалить дубликат.
+func GetCurrentAdmin(ctx context.Context, ipc *typesm.InternalProviderControl) (*typescore.Admin, bool) {
+ currentUserID, err := handlers.GetIDFromContext(ctx)
+ if err != nil {
+ return nil, false
+ }
+
+ admins, _, err := ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{
+ Filtering: &typescore.Admin{ID: ¤tUserID},
+ })
+ if err != nil || len(admins) == 0 || admins[0] == nil || admins[0].ID == nil || admins[0].Login == nil {
+ return nil, false
+ }
+
+ return admins[0], true
+}
+
+func parseUintPtr(v string, fallback uint64) *uint64 {
+ if v == "" {
+ return &fallback
+ }
+ n, err := strconv.ParseUint(v, 10, 64)
+ if err != nil {
+ return &fallback
+ }
+ return &n
+}
+
+-----END handlers/admin_actions/handlers.go-----
+
+File: handlers/approval_steps/handlers.go
+Lines: 442
+-----BEGIN handlers/approval_steps/handlers.go-----
+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,
+ }
+
+ stepsDbLst, total, errW := s.ipc.Database.ApprovalStep.GetApprovalStepsListDB(r.Context(), options)
+ if errW != nil {
+ return nil, errW
+ }
+
+ // 🚀 Подгружаем связанные данные
+ for _, step := range stepsDbLst {
+ s.enrichStep(r.Context(), 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")
+ }
+
+ steps, _, err := s.ipc.Database.ApprovalStep.GetApprovalStepsListDB(r.Context(), 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(r.Context(), 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")
+ }
+
+ // Проверяем, что заявка существует
+ approval, err := s.ipc.Database.Approval.GetApprovalByIDDB(r.Context(), approvalID)
+ if err != nil {
+ return nil, err
+ }
+ if approval == nil {
+ return nil, errors.New("approval not found")
+ }
+
+ steps, _, err := s.ipc.Database.ApprovalStep.GetApprovalStepsListDB(r.Context(), typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalStep{ApprovalID: &approvalID},
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ // Сортируем по step_order
+ sortStepsByOrder(steps)
+
+ // Подгружаем связанные данные
+ for _, step := range steps {
+ s.enrichStep(r.Context(), 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 := r.Context()
+
+ // Проверяем существование заявки
+ 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 := r.Context()
+
+ // Проверяем, что шаг существует
+ 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 := r.Context()
+
+ // Проверяем, что шаг существует
+ 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
+}
+
+-----END handlers/approval_steps/handlers.go-----
+
+File: handlers/approval_steps/routes.go
+Lines: 43
+-----BEGIN handlers/approval_steps/routes.go-----
+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
+}
+
+-----END handlers/approval_steps/routes.go-----
+
+File: handlers/approval_tasks/handlers.go
+Lines: 518
+-----BEGIN handlers/approval_tasks/handlers.go-----
+package approvaltaskshandler
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/core/utilscore"
+ "bitrix_balancer_api/rest_admin_service/handlers"
+ adminloghandler "bitrix_balancer_api/rest_admin_service/handlers/admin_actions"
+ "context"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "path/filepath"
+ "strconv"
+ "strings"
+
+ "github.com/go-chi/chi/v5"
+ "github.com/sirupsen/logrus"
+)
+
+// GetApprovalTasksListHandler Получение списка задач
+func (s *ApprovalTasksReg) GetApprovalTasksListHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ queryParams := r.URL.Query()
+
+ taskParams := &typescore.ApprovalTask{}
+ offset, limit, likeFields, errW := utilscore.ParseParamsGetRequest(queryParams, taskParams)
+ if errW != nil {
+ return nil, errW
+ }
+
+ options := typescore.ListDbOptions{
+ Filtering: taskParams,
+ Offset: offset,
+ Limit: limit,
+ LikeFields: likeFields,
+ }
+
+ ctx := r.Context()
+ tasks, total, errW := s.ipc.Database.ApprovalTasks.GetApprovalTasksListDB(ctx, options)
+ if errW != nil {
+ return nil, errW
+ }
+
+ for _, task := range tasks {
+ s.enrichTask(ctx, task)
+ }
+
+ return &typescore.ApiResponseBase{
+ TotalCount: total,
+ Data: tasks,
+ }, nil
+}
+
+// GetApprovalTaskByIDHandler Получение задачи по ID
+func (s *ApprovalTasksReg) GetApprovalTaskByIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ idStr := chi.URLParam(r, "id")
+ if idStr == "" {
+ return nil, errors.New("task id is required")
+ }
+
+ id, err := strconv.ParseUint(idStr, 10, 64)
+ if err != nil {
+ return nil, errors.New("invalid task id")
+ }
+
+ ctx := r.Context()
+ task, err := s.ipc.Database.ApprovalTasks.GetApprovalTaskByIDDB(ctx, id)
+ if err != nil {
+ return nil, err
+ }
+ if task == nil {
+ return nil, errors.New("task not found")
+ }
+
+ s.enrichTask(ctx, task)
+
+ return task, nil
+}
+
+// UpdateApprovalTaskHandler Обновление задачи
+func (s *ApprovalTasksReg) UpdateApprovalTaskHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ defer r.Body.Close()
+
+ body, err := io.ReadAll(r.Body)
+ if err != nil {
+ logrus.Error("🛑 UpdateApprovalTaskHandler: ReadAll error:", err)
+ return nil, err
+ }
+
+ var req typescore.ApprovalTask
+ if err := json.Unmarshal(body, &req); err != nil {
+ return nil, errors.New("invalid request body")
+ }
+
+ if req.ID == nil {
+ return nil, errors.New("task id is required")
+ }
+
+ ctx := r.Context()
+
+ // Проверяем существование
+ existingTask, err := s.ipc.Database.ApprovalTasks.GetApprovalTaskByIDDB(ctx, *req.ID)
+ if err != nil || existingTask == nil {
+ return nil, errors.New("task not found")
+ }
+
+ if req.Status != nil {
+ validStatuses := map[string]bool{
+ "pending": true,
+ "waiting": true,
+ "completed": true,
+ "cancelled": true,
+ }
+ if !validStatuses[*req.Status] {
+ return nil, errors.New("invalid status")
+ }
+ }
+
+ type fieldChange struct {
+ Field string `json:"field"`
+ Old interface{} `json:"old"`
+ New interface{} `json:"new"`
+ }
+ var changes []fieldChange
+ var summary []string
+
+ if req.Status != nil && !utilscore.StrEq(existingTask.Status, req.Status) {
+ changes = append(changes, fieldChange{"status", utilscore.DerefStr(existingTask.Status), *req.Status})
+ summary = append(summary, fmt.Sprintf("статус: «%s» → «%s»", utilscore.DerefStr(existingTask.Status), *req.Status))
+ }
+ if req.TaskText != nil && !utilscore.StrEq(existingTask.TaskText, req.TaskText) {
+ changes = append(changes, fieldChange{"task_text", utilscore.DerefStr(existingTask.TaskText), *req.TaskText})
+ summary = append(summary, "изменён текст задачи")
+ }
+ if req.ExecutorID != nil && !utilscore.Uint64Eq(existingTask.ExecutorID, req.ExecutorID) {
+ var oldVal interface{}
+ if existingTask.ExecutorID != nil {
+ oldVal = *existingTask.ExecutorID
+ }
+ changes = append(changes, fieldChange{"executor_id", oldVal, *req.ExecutorID})
+ summary = append(summary, fmt.Sprintf("исполнитель: %v → %d", oldVal, *req.ExecutorID))
+ }
+ if req.RequireFile != nil && !utilscore.BoolEq(existingTask.RequireFile, req.RequireFile) {
+ changes = append(changes, fieldChange{"require_file", utilscore.DerefBool(existingTask.RequireFile), *req.RequireFile})
+ if *req.RequireFile {
+ summary = append(summary, "включено обязательное вложение файла")
+ } else {
+ summary = append(summary, "отключено обязательное вложение файла")
+ }
+ }
+ if req.StepOrder != nil && !utilscore.IntEq(existingTask.StepOrder, req.StepOrder) {
+ var oldVal interface{}
+ if existingTask.StepOrder != nil {
+ oldVal = *existingTask.StepOrder
+ }
+ changes = append(changes, fieldChange{"step_order", oldVal, *req.StepOrder})
+ summary = append(summary, fmt.Sprintf("порядок шага: %v → %d", oldVal, *req.StepOrder))
+ }
+
+ updated, _, err := s.ipc.Database.ApprovalTasks.UpdateApprovalTaskDB(ctx, nil, &req, true)
+ if err != nil {
+ return nil, err
+ }
+
+ s.enrichTask(ctx, updated)
+
+ if len(changes) > 0 {
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ approvalRef := ""
+ if existingTask.ApprovalID != nil {
+ approvalRef = fmt.Sprintf(" (заявка #%d)", *existingTask.ApprovalID)
+ }
+ description := fmt.Sprintf("Изменена задача #%d%s: %s", *req.ID, approvalRef, strings.Join(summary, "; "))
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "update", "approval_task", req.ID,
+ description,
+ map[string]interface{}{"changes": changes},
+ )
+ }
+ }
+
+ return updated, nil
+}
+
+// DeleteApprovalTaskHandler Удаление задачи
+func (s *ApprovalTasksReg) DeleteApprovalTaskHandler(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.ApprovalTask
+ if err := json.Unmarshal(body, &req); err != nil {
+ return nil, errors.New("invalid request body")
+ }
+
+ if req.ID == nil {
+ return nil, errors.New("task id is required")
+ }
+
+ ctx := r.Context()
+
+ existingTask, err := s.ipc.Database.ApprovalTasks.GetApprovalTaskByIDDB(ctx, *req.ID)
+ if err != nil || existingTask == nil {
+ return nil, errors.New("task not found")
+ }
+ snapshot := map[string]interface{}{
+ "task_text": utilscore.DerefStr(existingTask.TaskText),
+ "status": utilscore.DerefStr(existingTask.Status),
+ "require_file": utilscore.DerefBool(existingTask.RequireFile),
+ }
+ if existingTask.ApprovalID != nil {
+ snapshot["approval_id"] = *existingTask.ApprovalID
+ }
+ if existingTask.ExecutorID != nil {
+ snapshot["executor_id"] = *existingTask.ExecutorID
+ }
+ if existingTask.StepOrder != nil {
+ snapshot["step_order"] = *existingTask.StepOrder
+ }
+
+ err = s.ipc.Database.ApprovalTasks.DeleteApprovalTaskDB(ctx, &req)
+ if err != nil {
+ return nil, err
+ }
+
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ approvalRef := ""
+ if existingTask.ApprovalID != nil {
+ approvalRef = fmt.Sprintf(" (заявка #%d)", *existingTask.ApprovalID)
+ }
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "delete", "approval_task", req.ID,
+ fmt.Sprintf("Удалена задача #%d%s", *req.ID, approvalRef),
+ map[string]interface{}{"snapshot": snapshot},
+ )
+ }
+
+ return true, nil
+}
+
+func (s *ApprovalTasksReg) getCurrentAdmin(ctx context.Context) (*typescore.Admin, bool) {
+ currentUserID, err := handlers.GetIDFromContext(ctx)
+ if err != nil {
+ logrus.Warnf("getCurrentAdmin: GetIDFromContext err=%v", err)
+ return nil, false
+ }
+
+ admins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{
+ Filtering: &typescore.Admin{ID: ¤tUserID},
+ })
+ if err != nil || len(admins) == 0 || admins[0] == nil || admins[0].ID == nil || admins[0].Login == nil {
+ logrus.Warnf("getCurrentAdmin: admin not found for userID=%d err=%v", currentUserID, err)
+ return nil, false
+ }
+
+ return admins[0], true
+}
+
+// enrichTask подгружает связанные данные для задачи
+func (s *ApprovalTasksReg) enrichTask(ctx context.Context, task *typescore.ApprovalTask) {
+ if task == nil {
+ return
+ }
+
+ // Подгружаем заявку
+ if task.ApprovalID != nil {
+ approval, err := s.ipc.Database.Approval.GetApprovalByIDDB(ctx, *task.ApprovalID)
+ if err == nil && approval != nil {
+ task.Approval = approval
+ s.enrichApproval(ctx, approval)
+ }
+ }
+
+ // Подгружаем исполнителя
+ if task.ExecutorID != nil {
+ executor, err := s.ipc.Database.User.GetUserByIDDB(ctx, *task.ExecutorID)
+ if err == nil && executor != nil {
+ task.Executor = executor
+ if executor.DepartmentID != nil {
+ department, err := s.ipc.Database.Department.GetDepartmentByIDDB(ctx, *executor.DepartmentID)
+ if err == nil && department != nil {
+ executor.Department = department
+ }
+ }
+ }
+ }
+
+ if task.ID != nil {
+ files, err := s.ipc.Database.ApprovalFile.GetFilesByTaskIDDB(ctx, *task.ID)
+ if err == nil {
+ task.Files = files
+ }
+ }
+}
+
+func (s *ApprovalTasksReg) enrichApproval(ctx context.Context, approval *typescore.Approval) {
+ 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 initiator.DepartmentID != nil {
+ department, err := s.ipc.Database.Department.GetDepartmentByIDDB(ctx, *initiator.DepartmentID)
+ if err == nil && department != nil {
+ initiator.Department = department
+ }
+ }
+ }
+ }
+
+ // Подгружаем тему
+ if approval.TopicID != nil {
+ topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID)
+ if err == nil && topic != nil {
+ approval.Topic = topic
+
+ // Подгружаем категорию темы
+ if topic.CategoryID != nil {
+ category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *topic.CategoryID)
+ if err == nil && category != nil {
+ topic.Category = category
+ }
+ }
+ }
+ }
+
+ // Подгружаем отдел
+ if approval.DepartmentID != nil {
+ department, err := s.ipc.Database.Department.GetDepartmentByIDDB(ctx, *approval.DepartmentID)
+ if err == nil && department != nil {
+ approval.Department = department
+ }
+ }
+}
+
+// GetApprovalTaskFileHandler Получение файла задачи (для предпросмотра)
+//
+// 🆕 Не логирую просмотр/скачивание файлов — журнал задуман под
+// create/update/delete-действия, а не под чтение. Если захотите отслеживать
+// ещё и скачивания (например, для файлов с чувствительными данными) — это
+// отдельное решение, скажите, добавлю action="download" по тому же паттерну.
+func (s *ApprovalTasksReg) GetApprovalTaskFileHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ ctx := r.Context()
+
+ taskIDStr := chi.URLParam(r, "task_id")
+ fileIDStr := chi.URLParam(r, "file_id")
+
+ if taskIDStr == "" || fileIDStr == "" {
+ return nil, errors.New("task_id and file_id are required")
+ }
+
+ taskID, err := strconv.ParseUint(taskIDStr, 10, 64)
+ if err != nil {
+ return nil, errors.New("invalid task_id")
+ }
+
+ fileID, err := strconv.ParseUint(fileIDStr, 10, 64)
+ if err != nil {
+ return nil, errors.New("invalid file_id")
+ }
+
+ // Проверяем, что задача существует
+ task, err := s.ipc.Database.ApprovalTasks.GetApprovalTaskByIDDB(ctx, taskID)
+ if err != nil || task == nil {
+ return nil, errors.New("task not found")
+ }
+
+ // Получаем файл
+ file, err := s.ipc.Database.ApprovalFile.GetApprovalFileByIDDB(ctx, fileID)
+ if err != nil || file == nil {
+ return nil, errors.New("file not found")
+ }
+
+ // Проверяем, что файл принадлежит задаче
+ if file.TaskID == nil || *file.TaskID != taskID {
+ return nil, errors.New("file does not belong to this task")
+ }
+
+ if file.FileBase64 == nil || *file.FileBase64 == "" {
+ return nil, errors.New("file content is empty")
+ }
+
+ fileData, err := base64.StdEncoding.DecodeString(*file.FileBase64)
+ if err != nil {
+ return nil, errors.New("failed to decode file")
+ }
+
+ fileName := ""
+ if file.FileName != nil {
+ fileName = *file.FileName
+ }
+ mimeType := getMimeType(fileName)
+
+ w.Header().Set("Content-Type", mimeType)
+ w.Header().Set("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, fileName))
+ w.Header().Set("Content-Length", fmt.Sprintf("%d", len(fileData)))
+ w.Header().Set("Cache-Control", "public, max-age=31536000")
+
+ w.WriteHeader(http.StatusOK)
+ _, err = w.Write(fileData)
+ if err != nil {
+ return nil, errors.New("failed to send file")
+ }
+
+ return nil, nil
+}
+
+// DownloadApprovalTaskFileHandler Скачивание файла задачи
+func (s *ApprovalTasksReg) DownloadApprovalTaskFileHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ ctx := r.Context()
+
+ taskIDStr := chi.URLParam(r, "task_id")
+ fileIDStr := chi.URLParam(r, "file_id")
+
+ if taskIDStr == "" || fileIDStr == "" {
+ return nil, errors.New("task_id and file_id are required")
+ }
+
+ taskID, err := strconv.ParseUint(taskIDStr, 10, 64)
+ if err != nil {
+ return nil, errors.New("invalid task_id")
+ }
+
+ fileID, err := strconv.ParseUint(fileIDStr, 10, 64)
+ if err != nil {
+ return nil, errors.New("invalid file_id")
+ }
+
+ task, err := s.ipc.Database.ApprovalTasks.GetApprovalTaskByIDDB(ctx, taskID)
+ if err != nil || task == nil {
+ return nil, errors.New("task not found")
+ }
+
+ file, err := s.ipc.Database.ApprovalFile.GetApprovalFileByIDDB(ctx, fileID)
+ if err != nil || file == nil {
+ return nil, errors.New("file not found")
+ }
+
+ if file.TaskID == nil || *file.TaskID != taskID {
+ return nil, errors.New("file does not belong to this task")
+ }
+
+ if file.FileBase64 == nil || *file.FileBase64 == "" {
+ return nil, errors.New("file content is empty")
+ }
+
+ fileData, err := base64.StdEncoding.DecodeString(*file.FileBase64)
+ if err != nil {
+ return nil, errors.New("failed to decode file")
+ }
+
+ fileName := ""
+ if file.FileName != nil {
+ fileName = *file.FileName
+ }
+ mimeType := getMimeType(fileName)
+
+ w.Header().Set("Content-Type", mimeType)
+ w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
+ w.Header().Set("Content-Length", fmt.Sprintf("%d", len(fileData)))
+
+ w.WriteHeader(http.StatusOK)
+ _, err = w.Write(fileData)
+ if err != nil {
+ return nil, errors.New("failed to send file")
+ }
+
+ return nil, nil
+}
+
+// 🆕 getMimeType определяет MIME тип по расширению файла
+func getMimeType(fileName string) string {
+ ext := strings.ToLower(filepath.Ext(fileName))
+
+ mimeTypes := map[string]string{
+ ".jpg": "image/jpeg",
+ ".jpeg": "image/jpeg",
+ ".png": "image/png",
+ ".gif": "image/gif",
+ ".webp": "image/webp",
+ ".svg": "image/svg+xml",
+ ".bmp": "image/bmp",
+ ".pdf": "application/pdf",
+ ".txt": "text/plain",
+ ".doc": "application/msword",
+ ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
+ ".xls": "application/vnd.ms-excel",
+ ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
+ ".csv": "text/csv",
+ ".zip": "application/zip",
+ ".json": "application/json",
+ ".xml": "application/xml",
+ ".html": "text/html",
+ ".mp3": "audio/mpeg",
+ ".mp4": "video/mp4",
+ }
+
+ if mimeType, ok := mimeTypes[ext]; ok {
+ return mimeType
+ }
+
+ return "application/octet-stream"
+}
+
+-----END handlers/approval_tasks/handlers.go-----
+
+File: handlers/approval_tasks/routes.go
+Lines: 44
+-----BEGIN handlers/approval_tasks/routes.go-----
+package approvaltaskshandler
+
+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 ApprovalTasksReg struct {
+ ipc *typesm.InternalProviderControl
+}
+
+// RegisterApprovalTasksRoutes регистрирует маршруты для группы approvals
+func RegisterApprovalTasksRoutes(
+ r chi.Router,
+ ipc *typesm.InternalProviderControl,
+) error {
+ s := &ApprovalTasksReg{
+ ipc: ipc,
+ }
+
+ r.Route("/api/approval-tasks", 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.GetApprovalTasksListHandler)
+ handlers.RegisterRoute(r, http.MethodPut, "/", s.UpdateApprovalTaskHandler)
+ handlers.RegisterRoute(r, http.MethodDelete, "/", s.DeleteApprovalTaskHandler)
+
+ r.Get("/{id}", handlers.WrapHandlerF(handlers.WrapHandlerParams{
+ HandlerFunc: s.GetApprovalTaskByIDHandler,
+ }))
+ r.Get("/{task_id}/files/{file_id}", handlers.WrapHandlerF(handlers.WrapHandlerParams{
+ HandlerFunc: s.GetApprovalTaskFileHandler,
+ }))
+ r.Get("/{task_id}/files/{file_id}/download", handlers.WrapHandlerF(handlers.WrapHandlerParams{
+ HandlerFunc: s.DownloadApprovalTaskFileHandler,
+ }))
+ })
+
+ return nil
+}
+
+-----END handlers/approval_tasks/routes.go-----
+
+File: handlers/approvalextras/handler.go
+Lines: 422
+-----BEGIN handlers/approvalextras/handler.go-----
+package approvalextrashandler
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/rest_admin_service/handlers"
+ typesm "bitrix_balancer_api/rest_admin_service/types"
+ "errors"
+ "net/http"
+ "strconv"
+ "time"
+
+ "github.com/go-chi/chi/v5"
+)
+
+type ApprovalExtrasReg struct {
+ ipc *typesm.InternalProviderControl
+}
+
+// RegisterApprovalExtrasRoutes регистрирует данные о заявке, которые НЕ
+// хранятся прямо на самой Approval (или пока не отдаются в основном ответе
+// GET /api/approvals/{id}) — доп. согласующие, комментарии, наблюдатели
+// (вычисляются динамически по категории/теме, не хранимая связь) и активный
+// запрос на отзыв.
+//
+// ⚠️ ВАЖНО: регистрируем через r.Get() с полными путями, а НЕ через
+// r.Route("/api/approvals/{id}", ...). r.Route создаёт отдельный вложенный
+// роутер, который занимает узел {id} целиком — из-за этого существующий
+// GET /api/approvals/{id} (без суффикса) становится недостижим и отдаёт 404,
+// хотя вложенные пути (/additional-approvers и т.п.) продолжают работать.
+// Проверено эмпирически на реальном chi.Router — с r.Route ломается, с
+// r.Get(полный путь) — нет.
+func RegisterApprovalExtrasRoutes(
+ r chi.Router,
+ ipc *typesm.InternalProviderControl,
+) error {
+ s := &ApprovalExtrasReg{ipc: ipc}
+
+ r.Group(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, "/api/approvals/{id}/additional-approvers", s.GetAdditionalApproversHandler)
+ handlers.RegisterRoute(r, http.MethodGet, "/api/approvals/{id}/comments", s.GetCommentsHandler)
+ handlers.RegisterRoute(r, http.MethodGet, "/api/approvals/{id}/observers", s.GetObserversHandler)
+ handlers.RegisterRoute(r, http.MethodGet, "/api/approvals/{id}/revocation-request", s.GetRevocationRequestHandler)
+ handlers.RegisterRoute(r, http.MethodGet, "/api/approvals/{id}/tasks", s.GetTasksHandler)
+ })
+
+ return nil
+}
+
+func parseApprovalID(r *http.Request) (uint64, error) {
+ idStr := chi.URLParam(r, "id")
+ id, err := strconv.ParseUint(idStr, 10, 64)
+ if err != nil {
+ return 0, errors.New("invalid approval id")
+ }
+ return id, nil
+}
+
+func userName(u *typescore.User) string {
+ if u != nil && u.FullName != nil {
+ return *u.FullName
+ }
+ return "—"
+}
+
+// ============================================================
+// GET /api/approvals/{id}/additional-approvers
+// ============================================================
+
+type additionalApproverDTO struct {
+ ID uint64 `json:"id"`
+ ApproverID uint64 `json:"approver_id"`
+ ApproverName string `json:"approver_name"`
+ Status string `json:"status"`
+ Comment string `json:"comment,omitempty"`
+ ActedAt *time.Time `json:"acted_at,omitempty"`
+}
+
+func (s *ApprovalExtrasReg) GetAdditionalApproversHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ approvalID, err := parseApprovalID(r)
+ if err != nil {
+ return nil, err
+ }
+ ctx := r.Context()
+
+ records, _, err := s.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalAdditionalApprover{ApprovalID: &approvalID},
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ result := make([]additionalApproverDTO, 0, len(records))
+ for _, rec := range records {
+ if rec.ApproverID == nil {
+ continue
+ }
+ approver, _ := s.ipc.Database.User.GetUserByIDDB(ctx, *rec.ApproverID)
+
+ dto := additionalApproverDTO{
+ ApproverID: *rec.ApproverID,
+ ApproverName: userName(approver),
+ Status: "pending",
+ ActedAt: rec.ActedAt,
+ }
+ if rec.ID != nil {
+ dto.ID = *rec.ID
+ }
+ if rec.Status != nil {
+ dto.Status = *rec.Status
+ }
+ if rec.Comment != nil {
+ dto.Comment = *rec.Comment
+ }
+ result = append(result, dto)
+ }
+
+ return &typescore.ApiResponseBase{
+ TotalCount: uint64(len(result)),
+ Data: result,
+ }, nil
+}
+
+// ============================================================
+// GET /api/approvals/{id}/comments
+// ============================================================
+
+type commentDTO struct {
+ ID uint64 `json:"id"`
+ UserID uint64 `json:"user_id"`
+ UserName string `json:"user_name"`
+ Comment string `json:"comment"`
+ CreatedAt *time.Time `json:"created_at,omitempty"`
+}
+
+func (s *ApprovalExtrasReg) GetCommentsHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ approvalID, err := parseApprovalID(r)
+ if err != nil {
+ return nil, err
+ }
+ ctx := r.Context()
+
+ records, _, err := s.ipc.Database.ApprovalComment.GetApprovalCommentsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalComment{ApprovalID: &approvalID},
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ result := make([]commentDTO, 0, len(records))
+ for _, rec := range records {
+ dto := commentDTO{CreatedAt: rec.CreatedAt}
+ if rec.ID != nil {
+ dto.ID = *rec.ID
+ }
+ if rec.UserID != nil {
+ dto.UserID = *rec.UserID
+ user, _ := s.ipc.Database.User.GetUserByIDDB(ctx, *rec.UserID)
+ dto.UserName = userName(user)
+ }
+ if rec.Comment != nil {
+ dto.Comment = *rec.Comment
+ }
+ result = append(result, dto)
+ }
+
+ return &typescore.ApiResponseBase{
+ TotalCount: uint64(len(result)),
+ Data: result,
+ }, nil
+}
+
+// ============================================================
+// GET /api/approvals/{id}/observers
+//
+// Наблюдатели НЕ хранятся как связь на самой заявке — они вычисляются по
+// категории/теме через права (см. GetObserversForApprovalDB в
+// telegram_service). Здесь та же логика: сначала получаем код категории
+// темы этой заявки, затем спрашиваем БД.
+// ============================================================
+
+type observerDTO struct {
+ ID uint64 `json:"id"`
+ FullName string `json:"full_name"`
+}
+
+func (s *ApprovalExtrasReg) GetObserversHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ approvalID, err := parseApprovalID(r)
+ if err != nil {
+ return nil, err
+ }
+ ctx := r.Context()
+
+ 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")
+ }
+
+ categoryCode := ""
+ if approval.TopicID != nil {
+ topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID)
+ if err == nil && topic != nil && topic.CategoryID != nil {
+ category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *topic.CategoryID)
+ if err == nil && category != nil && category.Code != nil {
+ categoryCode = *category.Code
+ }
+ }
+ }
+
+ observers, err := s.ipc.Database.User.GetObserversForApprovalDB(ctx, categoryCode, approval.TopicID)
+ if err != nil {
+ return nil, err
+ }
+
+ result := make([]observerDTO, 0, len(observers))
+ for _, obs := range observers {
+ if obs.ID == nil {
+ continue
+ }
+ result = append(result, observerDTO{
+ ID: *obs.ID,
+ FullName: userName(obs),
+ })
+ }
+
+ return &typescore.ApiResponseBase{
+ TotalCount: uint64(len(result)),
+ Data: result,
+ }, nil
+}
+
+// ============================================================
+// GET /api/approvals/{id}/revocation-request
+//
+// Возвращает {"data": null}, если активного (pending) запроса на отзыв нет —
+// это нормальный случай для большинства заявок, не ошибка.
+// ============================================================
+
+type revocationApproverDTO struct {
+ ApproverID uint64 `json:"approver_id"`
+ ApproverName string `json:"approver_name"`
+ Status string `json:"status"`
+}
+
+type revocationRequestDTO struct {
+ ID uint64 `json:"id"`
+ Status string `json:"status"`
+ Reason string `json:"reason,omitempty"`
+ RequestedByID uint64 `json:"requested_by_id"`
+ RequestedByName string `json:"requested_by_name"`
+ Approvers []revocationApproverDTO `json:"approvers"`
+}
+
+func (s *ApprovalExtrasReg) GetRevocationRequestHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ approvalID, err := parseApprovalID(r)
+ if err != nil {
+ return nil, err
+ }
+ ctx := r.Context()
+
+ request, err := s.ipc.Database.ApprovalRevocation.GetPendingRevocationRequestForApprovalDB(ctx, approvalID)
+ if err != nil {
+ return nil, err
+ }
+ if request == nil {
+ return &typescore.ApiResponseBase{Data: nil}, nil
+ }
+
+ dto := revocationRequestDTO{Status: "pending"}
+ if request.ID != nil {
+ dto.ID = *request.ID
+ }
+ if request.Status != nil {
+ dto.Status = *request.Status
+ }
+ if request.Reason != nil {
+ dto.Reason = *request.Reason
+ }
+ if request.RequestedByID != nil {
+ dto.RequestedByID = *request.RequestedByID
+ requestedBy, _ := s.ipc.Database.User.GetUserByIDDB(ctx, *request.RequestedByID)
+ dto.RequestedByName = userName(requestedBy)
+ }
+
+ if request.ID != nil {
+ approvers, err := s.ipc.Database.ApprovalRevocation.GetRevocationApproversByRequestIDDB(ctx, *request.ID)
+ if err == nil {
+ for _, a := range approvers {
+ if a.ApproverID == nil {
+ continue
+ }
+ approverUser, _ := s.ipc.Database.User.GetUserByIDDB(ctx, *a.ApproverID)
+ status := "pending"
+ if a.Status != nil {
+ status = *a.Status
+ }
+ dto.Approvers = append(dto.Approvers, revocationApproverDTO{
+ ApproverID: *a.ApproverID,
+ ApproverName: userName(approverUser),
+ Status: status,
+ })
+ }
+ }
+ }
+
+ return &typescore.ApiResponseBase{Data: dto}, nil
+}
+
+// ============================================================
+// GET /api/approvals/{id}/tasks
+//
+// Две вещи в одном ответе:
+// - topic_executors — что НАСТРОЕНО для темы этой заявки (ApprovalTopicExecutor),
+// нужно для превью "какие задачи будут поставлены после согласования"
+// на pending-заявках, ещё до их фактического создания.
+// - tasks — что РЕАЛЬНО создано (ApprovalTask), уже после согласования.
+// - has_task_error — та же логика, что в отчёте (reportcore.BuildExcelApprovalsReport):
+// если для темы настроены исполнители, заявка уже approved, а задач
+// по факту нет — это ошибка на этапе создания задач, а не "не предусмотрено".
+// ============================================================
+
+type plannedTaskDTO struct {
+ ID uint64 `json:"id"`
+ TaskText string `json:"task_text"`
+ ExecutorName string `json:"executor_name,omitempty"`
+ StepOrder int `json:"step_order"`
+}
+
+type taskDTO struct {
+ ID uint64 `json:"id"`
+ TaskText string `json:"task_text"`
+ ExecutorName string `json:"executor_name"`
+ Status string `json:"status"`
+ CompletedAt *time.Time `json:"completed_at,omitempty"`
+}
+
+type approvalTasksResponse struct {
+ TopicExecutors []plannedTaskDTO `json:"topic_executors"`
+ Tasks []taskDTO `json:"tasks"`
+ HasTaskError bool `json:"has_task_error"`
+}
+
+func (s *ApprovalExtrasReg) GetTasksHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ approvalID, err := parseApprovalID(r)
+ if err != nil {
+ return nil, err
+ }
+ ctx := r.Context()
+
+ 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")
+ }
+
+ resp := &approvalTasksResponse{}
+
+ if approval.TopicID == nil {
+ return &typescore.ApiResponseBase{Data: resp}, nil
+ }
+
+ topicExecutors, err := s.ipc.Database.ApprovalTopicExecutor.GetExecutorsByTopicIDDB(ctx, *approval.TopicID)
+ if err != nil {
+ return nil, err
+ }
+
+ for _, te := range topicExecutors {
+ if te.ID == nil {
+ continue
+ }
+ dto := plannedTaskDTO{ID: *te.ID}
+ if te.TaskText != nil {
+ dto.TaskText = *te.TaskText
+ }
+ if te.StepOrder != nil {
+ dto.StepOrder = *te.StepOrder
+ }
+ if te.UserID != nil {
+ executor, _ := s.ipc.Database.User.GetUserByIDDB(ctx, *te.UserID)
+ dto.ExecutorName = userName(executor)
+ }
+ resp.TopicExecutors = append(resp.TopicExecutors, dto)
+ }
+
+ tasks, _, err := s.ipc.Database.ApprovalTasks.GetApprovalTasksListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalTask{ApprovalID: &approvalID},
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ for _, t := range tasks {
+ if t.ID == nil {
+ continue
+ }
+ dto := taskDTO{ID: *t.ID, Status: "—", CompletedAt: t.CompletedAt}
+ if t.TaskText != nil {
+ dto.TaskText = *t.TaskText
+ }
+ if t.Status != nil {
+ dto.Status = *t.Status
+ }
+ if t.ExecutorID != nil {
+ executor, _ := s.ipc.Database.User.GetUserByIDDB(ctx, *t.ExecutorID)
+ dto.ExecutorName = userName(executor)
+ }
+ resp.Tasks = append(resp.Tasks, dto)
+ }
+
+ if len(topicExecutors) > 0 && len(tasks) == 0 && approval.Status != nil && *approval.Status == "approved" {
+ resp.HasTaskError = true
+ }
+
+ return &typescore.ApiResponseBase{Data: resp}, nil
+}
+
+-----END handlers/approvalextras/handler.go-----
+
+File: handlers/approvals/files.go
+Lines: 278
+-----BEGIN handlers/approvals/files.go-----
+package approvalshandler
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "encoding/base64"
+ "fmt"
+ "net/http"
+ "path/filepath"
+ "strings"
+
+ "github.com/go-chi/chi/v5"
+)
+
+// GetApprovalFileHandler Получение файла заявки
+// @Summary Получение файла заявки
+// @Description Возвращает файл по ID заявки и ID файла
+// @Tags approvals
+// @Produce application/octet-stream
+// @Param approval_id path integer true "ID заявки"
+// @Param file_id path integer true "ID файла"
+// @Success 200 {file} binary "Файл"
+// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос"
+// @Failure 404 {object} handlers.ErrorResponse "Файл не найден"
+// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера"
+// @Router /api/approvals/{approval_id}/files/{file_id} [get]
+func (s *ApprovalsReg) GetApprovalFileHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ ctx := r.Context()
+
+ // Получаем ID из URL
+ approvalIDStr := chi.URLParam(r, "approval_id")
+ fileIDStr := chi.URLParam(r, "file_id")
+
+ if approvalIDStr == "" || fileIDStr == "" {
+ return nil, fmt.Errorf("approval_id and file_id are required")
+ }
+
+ approvalID, err := parseUint64(approvalIDStr)
+ if err != nil {
+ return nil, fmt.Errorf("invalid approval_id: %w", err)
+ }
+
+ fileID, err := parseUint64(fileIDStr)
+ if err != nil {
+ return nil, fmt.Errorf("invalid file_id: %w", err)
+ }
+
+ // Получаем заявку
+ approval, err := s.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID)
+ if err != nil {
+ return nil, fmt.Errorf("failed to get approval: %w", err)
+ }
+ if approval == nil {
+ return nil, fmt.Errorf("approval not found")
+ }
+
+ // Ищем файл в заявке
+ var targetFile *typescore.ApprovalFile
+ if approval.Files != nil {
+ for i := range approval.Files {
+ if approval.Files[i].ID != nil && *approval.Files[i].ID == fileID {
+ targetFile = approval.Files[i]
+ break
+ }
+ }
+ }
+
+ // Если файл не найден в кэше, загружаем все файлы заявки
+ if targetFile == nil {
+ files, err := s.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, approvalID)
+ if err != nil {
+ return nil, fmt.Errorf("failed to get files: %w", err)
+ }
+
+ for i := range files {
+ if files[i].ID != nil && *files[i].ID == fileID {
+ targetFile = files[i]
+ break
+ }
+ }
+ }
+
+ if targetFile == nil {
+ return nil, fmt.Errorf("file not found")
+ }
+
+ // Проверяем, что файл существует
+ if targetFile.FileBase64 == nil || *targetFile.FileBase64 == "" {
+ return nil, fmt.Errorf("file content is empty")
+ }
+
+ // Декодируем base64
+ fileData, err := base64.StdEncoding.DecodeString(*targetFile.FileBase64)
+ if err != nil {
+ return nil, fmt.Errorf("failed to decode file: %w", err)
+ }
+
+ // Определяем MIME тип
+ fileName := ""
+ if targetFile.FileName != nil {
+ fileName = *targetFile.FileName
+ }
+ mimeType := getMimeType(fileName)
+
+ // Устанавливаем заголовки
+ w.Header().Set("Content-Type", mimeType)
+ w.Header().Set("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, fileName))
+ w.Header().Set("Content-Length", fmt.Sprintf("%d", len(fileData)))
+ w.Header().Set("Cache-Control", "public, max-age=31536000")
+
+ // Отправляем файл
+ w.WriteHeader(http.StatusOK)
+ _, err = w.Write(fileData)
+ if err != nil {
+ return nil, fmt.Errorf("failed to send file: %w", err)
+ }
+
+ return nil, nil // nil означает, что мы уже отправили ответ
+}
+
+// DownloadApprovalFileHandler Скачивание файла заявки
+// @Summary Скачивание файла заявки
+// @Description Скачивает файл по ID заявки и ID файла
+// @Tags approvals
+// @Produce application/octet-stream
+// @Param approval_id path integer true "ID заявки"
+// @Param file_id path integer true "ID файла"
+// @Success 200 {file} binary "Файл"
+// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос"
+// @Failure 404 {object} handlers.ErrorResponse "Файл не найден"
+// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера"
+// @Router /api/approvals/{approval_id}/files/{file_id}/download [get]
+func (s *ApprovalsReg) DownloadApprovalFileHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ ctx := r.Context()
+
+ approvalIDStr := chi.URLParam(r, "approval_id")
+ fileIDStr := chi.URLParam(r, "file_id")
+
+ if approvalIDStr == "" || fileIDStr == "" {
+ return nil, fmt.Errorf("approval_id and file_id are required")
+ }
+
+ approvalID, err := parseUint64(approvalIDStr)
+ if err != nil {
+ return nil, fmt.Errorf("invalid approval_id: %w", err)
+ }
+
+ fileID, err := parseUint64(fileIDStr)
+ if err != nil {
+ return nil, fmt.Errorf("invalid file_id: %w", err)
+ }
+
+ approval, err := s.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID)
+ if err != nil {
+ return nil, fmt.Errorf("failed to get approval: %w", err)
+ }
+ if approval == nil {
+ return nil, fmt.Errorf("approval not found")
+ }
+
+ var targetFile *typescore.ApprovalFile
+ if approval.Files != nil {
+ for i := range approval.Files {
+ if approval.Files[i].ID != nil && *approval.Files[i].ID == fileID {
+ targetFile = approval.Files[i]
+ break
+ }
+ }
+ }
+
+ if targetFile == nil {
+ files, err := s.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, approvalID)
+ if err != nil {
+ return nil, fmt.Errorf("failed to get files: %w", err)
+ }
+
+ for i := range files {
+ if files[i].ID != nil && *files[i].ID == fileID {
+ targetFile = files[i]
+ break
+ }
+ }
+ }
+
+ if targetFile == nil {
+ return nil, fmt.Errorf("file not found")
+ }
+
+ if targetFile.FileBase64 == nil || *targetFile.FileBase64 == "" {
+ return nil, fmt.Errorf("file content is empty")
+ }
+
+ fileData, err := base64.StdEncoding.DecodeString(*targetFile.FileBase64)
+ if err != nil {
+ return nil, fmt.Errorf("failed to decode file: %w", err)
+ }
+
+ fileName := ""
+ if targetFile.FileName != nil {
+ fileName = *targetFile.FileName
+ }
+ mimeType := getMimeType(fileName)
+
+ w.Header().Set("Content-Type", mimeType)
+ w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
+ w.Header().Set("Content-Length", fmt.Sprintf("%d", len(fileData)))
+
+ w.WriteHeader(http.StatusOK)
+ _, err = w.Write(fileData)
+ if err != nil {
+ return nil, fmt.Errorf("failed to send file: %w", err)
+ }
+
+ return nil, nil
+}
+
+// getMimeType определяет MIME тип по расширению файла
+func getMimeType(fileName string) string {
+ ext := strings.ToLower(filepath.Ext(fileName))
+
+ mimeTypes := map[string]string{
+ // Images
+ ".jpg": "image/jpeg",
+ ".jpeg": "image/jpeg",
+ ".png": "image/png",
+ ".gif": "image/gif",
+ ".webp": "image/webp",
+ ".svg": "image/svg+xml",
+ ".bmp": "image/bmp",
+ ".ico": "image/x-icon",
+
+ // PDF
+ ".pdf": "application/pdf",
+
+ // Documents
+ ".txt": "text/plain",
+ ".doc": "application/msword",
+ ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
+ ".xls": "application/vnd.ms-excel",
+ ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
+ ".csv": "text/csv",
+
+ // Archives
+ ".zip": "application/zip",
+ ".rar": "application/vnd.rar",
+ ".7z": "application/x-7z-compressed",
+ ".tar": "application/x-tar",
+ ".gz": "application/gzip",
+
+ // Code
+ ".json": "application/json",
+ ".xml": "application/xml",
+ ".html": "text/html",
+ ".css": "text/css",
+ ".js": "application/javascript",
+
+ // Audio/Video
+ ".mp3": "audio/mpeg",
+ ".mp4": "video/mp4",
+ ".avi": "video/x-msvideo",
+ ".mov": "video/quicktime",
+ ".wmv": "video/x-ms-wmv",
+ ".flv": "video/x-flv",
+ ".webm": "video/webm",
+ }
+
+ if mimeType, ok := mimeTypes[ext]; ok {
+ return mimeType
+ }
+
+ return "application/octet-stream"
+}
+
+// parseUint64 парсит строку в uint64
+func parseUint64(s string) (uint64, error) {
+ var result uint64
+ _, err := fmt.Sscanf(s, "%d", &result)
+ return result, err
+}
+
+-----END handlers/approvals/files.go-----
+
+File: handlers/approvals/handlers.go
+Lines: 678
+-----BEGIN handlers/approvals/handlers.go-----
+package approvalshandler
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "context"
+ "encoding/json"
+ "errors"
+ "github.com/sirupsen/logrus"
+ "io"
+ "net/http"
+ "strconv"
+ "strings"
+ "sync"
+ "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 "Фильтр по статусу"
+// @Param initiator_id query integer false "Фильтр по инициатору"
+// @Param topic_id query integer false "Фильтр по теме (одна)"
+// @Param topic_ids query string false "Фильтр по темам (через запятую)"
+// @Param category_ids query string false "Фильтр по категориям (через запятую)"
+// @Param department_id query integer false "Фильтр по отделу"
+// @Param date_from query string false "Начальная дата (YYYY-MM-DD)"
+// @Param date_to query string false "Конечная дата (YYYY-MM-DD)"
+// @Param content query string 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()
+
+ filter := typescore.ApprovalFilter{}
+
+ if status := queryParams.Get("status"); status != "" {
+ filter.Status = &status
+ }
+ if initiatorIDStr := queryParams.Get("initiator_id"); initiatorIDStr != "" {
+ id, err := strconv.ParseUint(initiatorIDStr, 10, 64)
+ if err != nil {
+ return nil, errors.New("invalid initiator_id")
+ }
+ filter.InitiatorID = &id
+ }
+ if departmentIDStr := queryParams.Get("department_id"); departmentIDStr != "" {
+ id, err := strconv.ParseUint(departmentIDStr, 10, 64)
+ if err != nil {
+ return nil, errors.New("invalid department_id")
+ }
+ filter.DepartmentID = &id
+ }
+
+ contentSearch := queryParams.Get("content")
+ if contentSearch != "" {
+ if len(contentSearch) < 2 {
+ return nil, errors.New("search query must be at least 2 characters")
+ }
+ filter.Content = &contentSearch
+ }
+
+ if topicIDsStr := queryParams.Get("topic_ids"); topicIDsStr != "" {
+ ids, err := parseUint64Array(topicIDsStr)
+ if err != nil {
+ return nil, errors.New("invalid topic_ids")
+ }
+ filter.TopicIDs = ids
+ } else if topicIDStr := queryParams.Get("topic_id"); topicIDStr != "" {
+ id, err := strconv.ParseUint(topicIDStr, 10, 64)
+ if err != nil {
+ return nil, errors.New("invalid topic_id")
+ }
+ filter.TopicIDs = []uint64{id}
+ }
+
+ if categoryIDsStr := queryParams.Get("category_ids"); categoryIDsStr != "" {
+ ids, err := parseUint64Array(categoryIDsStr)
+ if err != nil {
+ return nil, errors.New("invalid category_ids")
+ }
+ filter.CategoryIDs = ids
+ }
+
+ 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
+ }
+
+ offset := uint64(0)
+ limit := uint64(100)
+ if offsetStr := queryParams.Get("offset"); offsetStr != "" {
+ if v, err := strconv.ParseUint(offsetStr, 10, 64); err == nil {
+ offset = v
+ }
+ }
+ if limitStr := queryParams.Get("limit"); limitStr != "" {
+ if v, err := strconv.ParseUint(limitStr, 10, 64); err == nil {
+ limit = v
+ }
+ }
+
+ ctx := r.Context()
+
+ approvalsDbLst, total, errW := s.ipc.Database.Approval.GetApprovalsListFilteredDB(ctx, filter, offset, limit)
+ if errW != nil {
+ logrus.Errorf("❌ GetApprovalsListHandler error: %v", errW)
+ return nil, errW
+ }
+
+ if approvalsDbLst == nil {
+ approvalsDbLst = []*typescore.Approval{}
+ }
+
+ s.enrichApprovalsBatch(ctx, approvalsDbLst, false)
+
+ return &typescore.ApiResponseBase{
+ TotalCount: total,
+ Data: approvalsDbLst,
+ }, nil
+}
+
+// parseUint64Array — парсит строку "1,2,3" в []uint64
+func parseUint64Array(s string) ([]uint64, error) {
+ parts := strings.Split(s, ",")
+ result := make([]uint64, 0, len(parts))
+ for _, p := range parts {
+ p = strings.TrimSpace(p)
+ if p == "" {
+ continue
+ }
+ v, err := strconv.ParseUint(p, 10, 64)
+ if err != nil {
+ return nil, err
+ }
+ result = append(result, v)
+ }
+ return result, 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 := r.Context()
+ 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 := r.Context()
+
+ // Проверяем, что заявка существует
+ 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 := r.Context()
+
+ // Проверяем, что заявка существует
+ 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{}
+
+ 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
+ }
+
+ if allAccessStr := queryParams.Get("all_access"); allAccessStr == "true" {
+ filter.AllAccess = true
+ }
+
+ ctx := r.Context()
+ approvals, err := s.ipc.Database.Approval.GetApprovalsForReportDB(ctx, filter)
+ if err != nil {
+ return nil, err
+ }
+
+ s.enrichApprovalsBatch(ctx, approvals, false)
+
+ return &typescore.ApiResponseBase{
+ TotalCount: uint64(len(approvals)),
+ Data: approvals,
+ }, nil
+}
+
+// enrichApproval подгружает связанные данные для заявки
+// enrichApproval подгружает связанные данные для ОДНОЙ заявки.
+// Независимые запросы выполняются параллельно, чтобы сократить суммарную задержку.
+func (s *ApprovalsReg) enrichApproval(ctx context.Context, approval *typescore.Approval, loadSteps bool) {
+ if approval == nil {
+ return
+ }
+
+ var wg sync.WaitGroup
+
+ if approval.InitiatorID != nil {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ if initiator, err := s.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID); err == nil && initiator != nil {
+ approval.Initiator = initiator
+ }
+ }()
+ }
+
+ if approval.TopicID != nil {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID)
+ if err == nil && topic != nil {
+ approval.Topic = topic
+ if topic.CategoryID != nil {
+ if category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *topic.CategoryID); err == nil && category != nil {
+ topic.Category = category
+ }
+ }
+ }
+ }()
+ }
+
+ if approval.DepartmentID != nil {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ if department, err := s.ipc.Database.Department.GetDepartmentByIDDB(ctx, *approval.DepartmentID); err == nil && department != nil {
+ approval.Department = department
+ }
+ }()
+ }
+
+ if approval.RevokedByID != nil {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ if revokedBy, err := s.ipc.Database.User.GetUserByIDDB(ctx, *approval.RevokedByID); err == nil && revokedBy != nil {
+ approval.RevokedBy = revokedBy
+ }
+ }()
+ }
+
+ if approval.ID != nil {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ if files, err := s.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID); err == nil {
+ approval.Files = files
+ }
+ }()
+ }
+
+ if loadSteps && approval.ID != nil {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ steps, _, err := s.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalStep{ApprovalID: approval.ID},
+ })
+ if err != nil {
+ return
+ }
+
+ // Согласующие подгружаются одним батч-запросом, а не по одному на шаг
+ approverIDsSet := make(map[uint64]struct{})
+ for _, step := range steps {
+ if step.ApproverID != nil {
+ approverIDsSet[*step.ApproverID] = struct{}{}
+ }
+ }
+ approverIDs := make([]uint64, 0, len(approverIDsSet))
+ for id := range approverIDsSet {
+ approverIDs = append(approverIDs, id)
+ }
+
+ if approvers, err := s.ipc.Database.User.GetUsersByIDsDB(ctx, approverIDs); err == nil {
+ approversMap := make(map[uint64]*typescore.User, len(approvers))
+ for _, u := range approvers {
+ if u.ID != nil {
+ approversMap[*u.ID] = u
+ }
+ }
+ for _, step := range steps {
+ if step.ApproverID != nil {
+ if approver, ok := approversMap[*step.ApproverID]; ok {
+ step.Approver = approver
+ }
+ }
+ }
+ }
+
+ approval.Steps = steps
+ }()
+ }
+
+ wg.Wait()
+}
+
+// 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
+}
+
+// enrichApprovalsBatch выполняет пакетную подгрузку связанных данных для СПИСКА заявок,
+// заменяя N+1 отдельных запросов (было: enrichApproval в цикле) несколькими батч-запросами.
+func (s *ApprovalsReg) enrichApprovalsBatch(ctx context.Context, approvals []*typescore.Approval, loadSteps bool) {
+ if len(approvals) == 0 {
+ return
+ }
+
+ userIDsSet := make(map[uint64]struct{})
+ topicIDsSet := make(map[uint64]struct{})
+ departmentIDsSet := make(map[uint64]struct{})
+ approvalIDs := make([]uint64, 0, len(approvals))
+
+ for _, a := range approvals {
+ if a.InitiatorID != nil {
+ userIDsSet[*a.InitiatorID] = struct{}{}
+ }
+ if a.RevokedByID != nil {
+ userIDsSet[*a.RevokedByID] = struct{}{}
+ }
+ if a.TopicID != nil {
+ topicIDsSet[*a.TopicID] = struct{}{}
+ }
+ if a.DepartmentID != nil {
+ departmentIDsSet[*a.DepartmentID] = struct{}{}
+ }
+ if a.ID != nil {
+ approvalIDs = append(approvalIDs, *a.ID)
+ }
+ }
+
+ userIDs := make([]uint64, 0, len(userIDsSet))
+ for id := range userIDsSet {
+ userIDs = append(userIDs, id)
+ }
+ topicIDs := make([]uint64, 0, len(topicIDsSet))
+ for id := range topicIDsSet {
+ topicIDs = append(topicIDs, id)
+ }
+ departmentIDs := make([]uint64, 0, len(departmentIDsSet))
+ for id := range departmentIDsSet {
+ departmentIDs = append(departmentIDs, id)
+ }
+
+ usersMap := make(map[uint64]*typescore.User)
+ if users, err := s.ipc.Database.User.GetUsersByIDsDB(ctx, userIDs); err == nil {
+ for _, u := range users {
+ if u.ID != nil {
+ usersMap[*u.ID] = u
+ }
+ }
+ }
+
+ topicsMap := make(map[uint64]*typescore.ApprovalTopic)
+ categoryIDsSet := make(map[uint64]struct{})
+ if topics, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicsByIDsDB(ctx, topicIDs); err == nil {
+ for _, t := range topics {
+ if t.ID != nil {
+ topicsMap[*t.ID] = t
+ }
+ if t.CategoryID != nil {
+ categoryIDsSet[*t.CategoryID] = struct{}{}
+ }
+ }
+ }
+
+ categoryIDs := make([]uint64, 0, len(categoryIDsSet))
+ for id := range categoryIDsSet {
+ categoryIDs = append(categoryIDs, id)
+ }
+ categoriesMap := make(map[uint64]*typescore.ApprovalTopicCategory)
+ if categories, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoriesByIDsDB(ctx, categoryIDs); err == nil {
+ for _, c := range categories {
+ if c.ID != nil {
+ categoriesMap[*c.ID] = c
+ }
+ }
+ }
+ for _, t := range topicsMap {
+ if t.CategoryID != nil {
+ if cat, ok := categoriesMap[*t.CategoryID]; ok {
+ t.Category = cat
+ }
+ }
+ }
+
+ departmentsMap := make(map[uint64]*typescore.Department)
+ if departments, err := s.ipc.Database.Department.GetDepartmentsByIDsDB(ctx, departmentIDs); err == nil {
+ for _, d := range departments {
+ if d.ID != nil {
+ departmentsMap[*d.ID] = d
+ }
+ }
+ }
+
+ filesMap := make(map[uint64][]*typescore.ApprovalFile)
+ if files, err := s.ipc.Database.ApprovalFile.GetFilesByApprovalIDsDB(ctx, approvalIDs); err == nil {
+ for _, f := range files {
+ if f.ApprovalID != nil {
+ filesMap[*f.ApprovalID] = append(filesMap[*f.ApprovalID], f)
+ }
+ }
+ }
+
+ var stepsMap map[uint64][]*typescore.ApprovalStep
+ if loadSteps {
+ stepsMap = make(map[uint64][]*typescore.ApprovalStep)
+ steps, err := s.ipc.Database.ApprovalStep.GetApprovalStepsByApprovalIDsDB(ctx, approvalIDs)
+ if err == nil {
+ approverIDsSet := make(map[uint64]struct{})
+ for _, st := range steps {
+ if st.ApprovalID != nil {
+ stepsMap[*st.ApprovalID] = append(stepsMap[*st.ApprovalID], st)
+ }
+ if st.ApproverID != nil {
+ approverIDsSet[*st.ApproverID] = struct{}{}
+ }
+ }
+
+ approverIDs := make([]uint64, 0, len(approverIDsSet))
+ for id := range approverIDsSet {
+ approverIDs = append(approverIDs, id)
+ }
+ approversMap := make(map[uint64]*typescore.User)
+ if approvers, err := s.ipc.Database.User.GetUsersByIDsDB(ctx, approverIDs); err == nil {
+ for _, u := range approvers {
+ if u.ID != nil {
+ approversMap[*u.ID] = u
+ }
+ }
+ }
+ for _, stepsForApproval := range stepsMap {
+ for _, st := range stepsForApproval {
+ if st.ApproverID != nil {
+ if approver, ok := approversMap[*st.ApproverID]; ok {
+ st.Approver = approver
+ }
+ }
+ }
+ }
+ }
+ }
+
+ for _, a := range approvals {
+ if a.InitiatorID != nil {
+ if u, ok := usersMap[*a.InitiatorID]; ok {
+ a.Initiator = u
+ }
+ }
+ if a.RevokedByID != nil {
+ if u, ok := usersMap[*a.RevokedByID]; ok {
+ a.RevokedBy = u
+ }
+ }
+ if a.TopicID != nil {
+ if t, ok := topicsMap[*a.TopicID]; ok {
+ a.Topic = t
+ }
+ }
+ if a.DepartmentID != nil {
+ if d, ok := departmentsMap[*a.DepartmentID]; ok {
+ a.Department = d
+ }
+ }
+ if a.ID != nil {
+ a.Files = filesMap[*a.ID]
+ if loadSteps {
+ a.Steps = stepsMap[*a.ID]
+ }
+ }
+ }
+}
+
+-----END handlers/approvals/handlers.go-----
+
+File: handlers/approvals/reports.go
+Lines: 73
+-----BEGIN handlers/approvals/reports.go-----
+package approvalshandler
+
+import (
+ "bitrix_balancer_api/core/reportcore"
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/rest_admin_service/handlers"
+ "fmt"
+ "net/http"
+ "time"
+)
+
+// DownloadApprovalsReportHandler Скачивание отчёта по заявкам в формате XLSX
+// @Summary Скачивание отчёта по заявкам
+// @Description Формирует и возвращает XLSX-файл отчёта по заявкам за указанный период
+// @Tags approvals
+// @Accept json
+// @Produce application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
+// @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 {file} binary "XLSX файл"
+// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос"
+// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера"
+// @Router /api/approvals/report/download [get]
+func (s *ApprovalsReg) DownloadApprovalsReportHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ queryParams := r.URL.Query()
+
+ filter := typescore.ReportFilter{}
+
+ // Парсим даты
+ if dateFromStr := queryParams.Get("date_from"); dateFromStr != "" {
+ dateFrom, err := time.Parse("2006-01-02", dateFromStr)
+ if err != nil {
+ return nil, fmt.Errorf("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, fmt.Errorf("invalid date_to format, use YYYY-MM-DD")
+ }
+ filter.DateTo = &dateTo
+ }
+
+ // В админке всегда all_access = true (админ видит все заявки)
+ filter.AllAccess = true
+
+ ctx := r.Context()
+
+ // Получаем заявки для отчёта
+ approvals, err := s.ipc.Database.Approval.GetApprovalsForReportDB(ctx, filter)
+ if err != nil {
+ return nil, fmt.Errorf("failed to get approvals for report: %w", err)
+ }
+
+ if len(approvals) == 0 {
+ return nil, fmt.Errorf("no approvals found for the specified period")
+ }
+
+ excelBytes, err := reportcore.BuildExcelApprovalsReport(ctx, s.ipc.Database, approvals)
+ if err != nil {
+ return nil, fmt.Errorf("failed to build excel report: %w", err)
+ }
+
+ fileName := fmt.Sprintf("Согласования_%s.xlsx", time.Now().Format("02.01.2006_15-04"))
+
+ return &handlers.ExcelFileResponse{
+ Data: excelBytes,
+ FileName: fileName,
+ }, nil
+}
+
+-----END handlers/approvals/reports.go-----
+
+File: handlers/approvals/routes.go
+Lines: 48
+-----BEGIN handlers/approvals/routes.go-----
+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)
+ handlers.RegisterRoute(r, http.MethodGet, "/report/download", s.DownloadApprovalsReportHandler)
+
+ r.Get("/{id}", handlers.WrapHandlerF(handlers.WrapHandlerParams{
+ HandlerFunc: s.GetApprovalByIDHandler,
+ }))
+ r.Get("/{approval_id}/files/{file_id}", handlers.WrapHandlerF(handlers.WrapHandlerParams{
+ HandlerFunc: s.GetApprovalFileHandler,
+ }))
+ r.Get("/{approval_id}/files/{file_id}/download", handlers.WrapHandlerF(handlers.WrapHandlerParams{
+ HandlerFunc: s.DownloadApprovalFileHandler,
+ }))
+ })
+
+ return nil
+}
+
+-----END handlers/approvals/routes.go-----
+
+File: handlers/auth/handlers.go
+Lines: 204
+-----BEGIN handlers/auth/handlers.go-----
+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"
+ "github.com/redis/go-redis/v9"
+ "io"
+ "net/http"
+ "time"
+
+ "github.com/sirupsen/logrus"
+)
+
+// GetServerTimeHandler возвращает текущее серверное время для синхронизации с клиентом
+// @Summary Получить серверное время
+// @Description Публичный endpoint для синхронизации часов клиента с сервером
+// @Tags public
+// @Produce json
+// @Success 200 {object} map[string]interface{}
+// @Router /api/time [get]
+func (s *AuthReg) GetServerTimeHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ now := time.Now().UTC()
+ return map[string]interface{}{
+ "timestamp": now.Unix(),
+ "iso": now.Format(time.RFC3339),
+ }, nil
+}
+
+// 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 && !errors.Is(err, redis.Nil) {
+ return nil, err
+ }
+
+ var session typescore.UsersSessions
+
+ if sessionJSON != "" {
+ 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,
+ })
+
+ sessionJSONBytes, err := json.Marshal(session)
+ if err != nil {
+ return nil, fmt.Errorf("failed to marshal session: %w", err)
+ }
+
+ err = s.ipc.RedisClient.Set(ctx, keyPath, string(sessionJSONBytes), 0)
+ if err != nil {
+ return nil, fmt.Errorf("failed to save session to Redis: %w", 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
+}
+
+-----END handlers/auth/handlers.go-----
+
+File: handlers/auth/routes.go
+Lines: 40
+-----BEGIN handlers/auth/routes.go-----
+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,
+ }
+
+ handlers.RegisterRoute(r, http.MethodGet, "/api/time", s.GetServerTimeHandler)
+
+ 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
+}
+
+-----END handlers/auth/routes.go-----
+
+File: handlers/dashboard/handlers.go
+Lines: 908
+-----BEGIN handlers/dashboard/handlers.go-----
+package dashboardhandler
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/core/utilscore"
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "regexp"
+ "strconv"
+ "strings"
+ "time"
+)
+
+// GetDashboardStatsHandler — возвращает все данные для дашборда одним запросом
+func (s *DashboardReg) GetDashboardStatsHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ ctx := r.Context()
+
+ // === 1. KPI: считаем сущности ===
+ totalUsers := s.countUsers(ctx, &typescore.User{})
+ activeUsers := s.countUsers(ctx, &typescore.User{IsBlocked: boolPtr(false), IsFired: boolPtr(false)})
+ blockedUsers := s.countUsers(ctx, &typescore.User{IsBlocked: boolPtr(true)})
+
+ totalApprovals := s.countApprovals(ctx, &typescore.Approval{})
+ pendingApprovals := s.countApprovalsByStatus(ctx, "pending")
+ revisionApprovals := s.countApprovalsByStatus(ctx, "revision")
+ approvedToday := s.countApprovalsByStatusAndDate(ctx, "approved", time.Now())
+
+ totalTopics := s.countTopics(ctx, &typescore.ApprovalTopic{})
+ activeTopics := s.countTopics(ctx, &typescore.ApprovalTopic{IsActive: boolPtr(true)})
+ totalCategories := s.countCategories(ctx)
+ totalDepartments := s.countDepartments(ctx)
+ totalRoles := s.countRoles(ctx)
+ totalExecutors := s.countExecutors(ctx)
+
+ // === 2. Распределение заявок по статусам ===
+ statuses := []string{"draft", "pending", "approved", "rejected", "revoked", "revision"}
+ statusData := make([]map[string]interface{}, 0, len(statuses))
+ for _, status := range statuses {
+ count := s.countApprovalsByStatus(ctx, status)
+ statusData = append(statusData, map[string]interface{}{
+ "status": status,
+ "count": count,
+ })
+ }
+
+ // === 3. Динамика за последние 7 дней ===
+ dailyData := make([]map[string]interface{}, 0, 7)
+ now := time.Now()
+ for i := 6; i >= 0; i-- {
+ date := now.AddDate(0, 0, -i)
+ created := s.countApprovalsCreatedOn(ctx, date)
+ approved := s.countApprovalsApprovedOn(ctx, date)
+
+ dailyData = append(dailyData, map[string]interface{}{
+ "date": date.Format("2006-01-02"),
+ "created": created,
+ "approved": approved,
+ })
+ }
+
+ // === 4. Разбивка по категориям (вместо топ-5 тем) ===
+ categoryBreakdown := s.getCategoryBreakdown(ctx)
+
+ // === 5. Узкие места: согласующие с просроченными заявками (вместо топ-5 по активности) ===
+ bottleneckApprovers := s.getBottleneckApprovers(ctx, 5, 7)
+
+ // === 6. Старые pending заявки (>7 дней) ===
+ oldPendingCount := s.countOldPendingApprovals(ctx, 7)
+
+ // === 7. 🆕 Задачи: распределение по статусам + динамика за 7 дней ===
+ taskStatusData := s.getTaskStatusData(ctx)
+ taskDailyData := s.getTaskDailyData(ctx)
+
+ // === 8. 🆕 Кто отсутствует сегодня (отгул/отпуск/больничный) ===
+ absentToday := s.getAbsentToday(ctx)
+
+ // === 9. 🆕 Проблемы конфигурации: темы без назначенного порядка
+ // согласования для конкретного пользователя + пользователи вообще
+ // без иерархии в своём отделе ===
+ topicGaps, usersWithoutHierarchy := s.getInitiatorConfigWarnings(ctx)
+
+ return map[string]interface{}{
+ "users": map[string]int{
+ "total": totalUsers,
+ "active": activeUsers,
+ "blocked": blockedUsers,
+ },
+ "approvals": map[string]int{
+ "total": totalApprovals,
+ "pending": pendingApprovals,
+ "revision": revisionApprovals,
+ "today": approvedToday,
+ },
+ "topics": map[string]int{
+ "total": totalTopics,
+ "active": activeTopics,
+ },
+ "categories": totalCategories,
+ "departments": totalDepartments,
+ "roles": totalRoles,
+ "executors": totalExecutors,
+ "statusData": statusData,
+ "dailyData": dailyData,
+ "categoryBreakdown": categoryBreakdown,
+ "bottleneckApprovers": bottleneckApprovers,
+ "oldPendingCount": oldPendingCount,
+ "oldPendingDays": 7,
+ "taskStatusData": taskStatusData,
+ "taskDailyData": taskDailyData,
+ "absentToday": absentToday,
+ "topicGaps": topicGaps,
+ "usersWithoutHierarchy": usersWithoutHierarchy,
+ }, nil
+}
+
+// ============================================================
+// Вспомогательные методы для подсчёта
+// ============================================================
+
+func (s *DashboardReg) countUsers(ctx context.Context, filter *typescore.User) int {
+ opts := typescore.ListDbOptions{
+ Filtering: filter,
+ Limit: utilscore.PointerToUint64(10000), // считаем через len
+ }
+ list, _, err := s.ipc.Database.User.GetUsersListDB(ctx, opts)
+ if err != nil {
+ return 0
+ }
+ return len(list)
+}
+
+func (s *DashboardReg) countApprovals(ctx context.Context, filter *typescore.Approval) int {
+ opts := typescore.ListDbOptions{
+ Filtering: filter,
+ Limit: utilscore.PointerToUint64(10000),
+ }
+ list, _, err := s.ipc.Database.Approval.GetApprovalsListDB(ctx, opts)
+ if err != nil {
+ return 0
+ }
+ return len(list)
+}
+
+func (s *DashboardReg) countApprovalsByStatus(ctx context.Context, status string) int {
+ return s.countApprovals(ctx, &typescore.Approval{Status: &status})
+}
+
+func (s *DashboardReg) countApprovalsByStatusAndDate(ctx context.Context, status string, date time.Time) int {
+ opts := typescore.ListDbOptions{
+ Filtering: &typescore.Approval{Status: &status},
+ Limit: utilscore.PointerToUint64(10000),
+ }
+ list, _, err := s.ipc.Database.Approval.GetApprovalsListDB(ctx, opts)
+ if err != nil {
+ return 0
+ }
+
+ count := 0
+ today := date.Format("2006-01-02")
+ for _, a := range list {
+ if a.CreatedAt != nil && a.CreatedAt.Format("2006-01-02") == today {
+ count++
+ }
+ }
+ return count
+}
+
+func (s *DashboardReg) countApprovalsCreatedOn(ctx context.Context, date time.Time) int {
+ opts := typescore.ListDbOptions{
+ Filtering: &typescore.Approval{},
+ Limit: utilscore.PointerToUint64(10000),
+ }
+ list, _, err := s.ipc.Database.Approval.GetApprovalsListDB(ctx, opts)
+ if err != nil {
+ return 0
+ }
+
+ count := 0
+ target := date.Format("2006-01-02")
+ for _, a := range list {
+ if a.CreatedAt != nil && a.CreatedAt.Format("2006-01-02") == target {
+ count++
+ }
+ }
+ return count
+}
+
+func (s *DashboardReg) countApprovalsApprovedOn(ctx context.Context, date time.Time) int {
+ opts := typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalStep{Status: strPtr("approved")},
+ Limit: utilscore.PointerToUint64(10000),
+ }
+ steps, _, err := s.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, opts)
+ if err != nil {
+ return 0
+ }
+
+ uniqueApprovals := make(map[uint64]bool)
+ target := date.Format("2006-01-02")
+ for _, step := range steps {
+ if step.ActedAt != nil && step.ActedAt.Format("2006-01-02") == target && step.ApprovalID != nil {
+ uniqueApprovals[*step.ApprovalID] = true
+ }
+ }
+ return len(uniqueApprovals)
+}
+
+func (s *DashboardReg) countTopics(ctx context.Context, filter *typescore.ApprovalTopic) int {
+ opts := typescore.ListDbOptions{
+ Filtering: filter,
+ Limit: utilscore.PointerToUint64(10000),
+ }
+ list, _, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, opts)
+ if err != nil {
+ return 0
+ }
+ return len(list)
+}
+
+func (s *DashboardReg) countCategories(ctx context.Context) int {
+ opts := typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalTopicCategory{},
+ Limit: utilscore.PointerToUint64(10000),
+ }
+ list, _, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryListDB(ctx, opts)
+ if err != nil {
+ return 0
+ }
+ return len(list)
+}
+
+func (s *DashboardReg) countDepartments(ctx context.Context) int {
+ opts := typescore.ListDbOptions{
+ Filtering: &typescore.Department{},
+ Limit: utilscore.PointerToUint64(10000),
+ }
+ list, _, err := s.ipc.Database.Department.GetDepartmentsListDB(ctx, opts)
+ if err != nil {
+ return 0
+ }
+ return len(list)
+}
+
+func (s *DashboardReg) countRoles(ctx context.Context) int {
+ opts := typescore.ListDbOptions{
+ Filtering: &typescore.Role{},
+ Limit: utilscore.PointerToUint64(10000),
+ }
+ list, _, err := s.ipc.Database.Role.GetRolesListDB(ctx, opts)
+ if err != nil {
+ return 0
+ }
+ return len(list)
+}
+
+func (s *DashboardReg) countExecutors(ctx context.Context) int {
+ opts := typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalTopicExecutor{},
+ Limit: utilscore.PointerToUint64(10000),
+ }
+ list, _, err := s.ipc.Database.ApprovalTopicExecutor.GetApprovalTopicExecutorListDB(ctx, opts)
+ if err != nil {
+ return 0
+ }
+ return len(list)
+}
+
+func (s *DashboardReg) countOldPendingApprovals(ctx context.Context, days int) int {
+ opts := typescore.ListDbOptions{
+ Filtering: &typescore.Approval{Status: strPtr("pending")},
+ Limit: utilscore.PointerToUint64(10000),
+ }
+ list, _, err := s.ipc.Database.Approval.GetApprovalsListDB(ctx, opts)
+ if err != nil {
+ return 0
+ }
+
+ cutoff := time.Now().AddDate(0, 0, -days)
+ count := 0
+ for _, a := range list {
+ if a.CreatedAt != nil && a.CreatedAt.Before(cutoff) {
+ count++
+ }
+ }
+ return count
+}
+
+// ============================================================
+// Разбивка заявок по категориям (заменяет прежний "топ-5 тем").
+// ============================================================
+
+func (s *DashboardReg) getCategoryBreakdown(ctx context.Context) []map[string]interface{} {
+ topicOpts := typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalTopic{},
+ Limit: utilscore.PointerToUint64(10000),
+ }
+ topics, _, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, topicOpts)
+ if err != nil {
+ return []map[string]interface{}{}
+ }
+ topicToCategory := make(map[uint64]uint64, len(topics))
+ for _, t := range topics {
+ if t.ID != nil && t.CategoryID != nil {
+ topicToCategory[*t.ID] = *t.CategoryID
+ }
+ }
+
+ categoryOpts := typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalTopicCategory{},
+ Limit: utilscore.PointerToUint64(10000),
+ }
+ categories, _, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryListDB(ctx, categoryOpts)
+ if err != nil {
+ return []map[string]interface{}{}
+ }
+ categoryNames := make(map[uint64]string, len(categories))
+ for _, c := range categories {
+ if c.ID != nil && c.Name != nil {
+ categoryNames[*c.ID] = *c.Name
+ }
+ }
+
+ approvalOpts := typescore.ListDbOptions{
+ Filtering: &typescore.Approval{},
+ Limit: utilscore.PointerToUint64(10000),
+ }
+ approvals, _, err := s.ipc.Database.Approval.GetApprovalsListDB(ctx, approvalOpts)
+ if err != nil {
+ return []map[string]interface{}{}
+ }
+
+ type catStat struct {
+ total int
+ pending int
+ }
+ byCategory := make(map[uint64]*catStat)
+ for _, a := range approvals {
+ if a.TopicID == nil {
+ continue
+ }
+ categoryID, ok := topicToCategory[*a.TopicID]
+ if !ok {
+ continue
+ }
+ if byCategory[categoryID] == nil {
+ byCategory[categoryID] = &catStat{}
+ }
+ byCategory[categoryID].total++
+ if a.Status != nil && *a.Status == "pending" {
+ byCategory[categoryID].pending++
+ }
+ }
+
+ type entry struct {
+ id uint64
+ total int
+ pending int
+ }
+ entries := make([]entry, 0, len(byCategory))
+ for id, st := range byCategory {
+ entries = append(entries, entry{id: id, total: st.total, pending: st.pending})
+ }
+ for i := 0; i < len(entries); i++ {
+ for j := i + 1; j < len(entries); j++ {
+ if entries[j].total > entries[i].total {
+ entries[i], entries[j] = entries[j], entries[i]
+ }
+ }
+ }
+
+ result := make([]map[string]interface{}, 0, len(entries))
+ for _, e := range entries {
+ name := categoryNames[e.id]
+ if name == "" {
+ continue
+ }
+ result = append(result, map[string]interface{}{
+ "id": e.id,
+ "name": name,
+ "total_count": e.total,
+ "pending_count": e.pending,
+ })
+ }
+
+ return result
+}
+
+// ============================================================
+// Узкие места: согласующие с просроченными (>days дней с подачи) заявками.
+// ============================================================
+
+func (s *DashboardReg) getBottleneckApprovers(ctx context.Context, limit int, days int) []map[string]interface{} {
+ stepOpts := typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalStep{Status: strPtr("pending")},
+ Limit: utilscore.PointerToUint64(10000),
+ }
+ steps, _, err := s.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, stepOpts)
+ if err != nil {
+ return []map[string]interface{}{}
+ }
+
+ cutoff := time.Now().AddDate(0, 0, -days)
+
+ type approverStat struct {
+ pendingTotal int
+ overdue int
+ }
+ stats := make(map[uint64]*approverStat)
+
+ for _, step := range steps {
+ if step.ApproverID == nil || step.ApprovalID == nil {
+ continue
+ }
+ approval, err := s.ipc.Database.Approval.GetApprovalByIDDB(ctx, *step.ApprovalID)
+ if err != nil || approval == nil || approval.CreatedAt == nil {
+ continue
+ }
+
+ id := *step.ApproverID
+ if stats[id] == nil {
+ stats[id] = &approverStat{}
+ }
+ stats[id].pendingTotal++
+ if approval.CreatedAt.Before(cutoff) {
+ stats[id].overdue++
+ }
+ }
+
+ type entry struct {
+ id uint64
+ pendingTotal int
+ overdue int
+ }
+ entries := make([]entry, 0, len(stats))
+ for id, st := range stats {
+ if st.overdue == 0 {
+ continue
+ }
+ entries = append(entries, entry{id: id, pendingTotal: st.pendingTotal, overdue: st.overdue})
+ }
+ for i := 0; i < len(entries); i++ {
+ for j := i + 1; j < len(entries); j++ {
+ if entries[j].overdue > entries[i].overdue {
+ entries[i], entries[j] = entries[j], entries[i]
+ }
+ }
+ }
+
+ result := make([]map[string]interface{}, 0, limit)
+ for i := 0; i < len(entries) && i < limit; i++ {
+ e := entries[i]
+ user, err := s.ipc.Database.User.GetUserByIDDB(ctx, e.id)
+ if err != nil || user == nil {
+ continue
+ }
+
+ fullName := ""
+ if user.FullName != nil {
+ fullName = *user.FullName
+ }
+
+ deptName := ""
+ if user.DepartmentID != nil {
+ dept, err := s.ipc.Database.Department.GetDepartmentByIDDB(ctx, *user.DepartmentID)
+ if err == nil && dept != nil && dept.Name != nil {
+ deptName = *dept.Name
+ }
+ }
+
+ result = append(result, map[string]interface{}{
+ "user_id": e.id,
+ "full_name": fullName,
+ "department_name": deptName,
+ "pending_total": e.pendingTotal,
+ "overdue_count": e.overdue,
+ })
+ }
+
+ return result
+}
+
+// ============================================================
+// 🆕 Задачи: распределение по статусам + динамика за 7 дней.
+// Полностью аналогично разделам про заявки — те же графики, другая
+// таблица (ApprovalTask вместо Approval).
+// ============================================================
+
+func (s *DashboardReg) getTaskStatusData(ctx context.Context) []map[string]interface{} {
+ statuses := []string{"pending", "waiting", "completed", "cancelled"}
+ result := make([]map[string]interface{}, 0, len(statuses))
+ for _, status := range statuses {
+ st := status
+ opts := typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalTask{Status: &st},
+ Limit: utilscore.PointerToUint64(10000),
+ }
+ list, _, err := s.ipc.Database.ApprovalTasks.GetApprovalTasksListDB(ctx, opts)
+ count := 0
+ if err == nil {
+ count = len(list)
+ }
+ result = append(result, map[string]interface{}{
+ "status": status,
+ "count": count,
+ })
+ }
+ return result
+}
+
+func (s *DashboardReg) getTaskDailyData(ctx context.Context) []map[string]interface{} {
+ opts := typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalTask{},
+ Limit: utilscore.PointerToUint64(10000),
+ }
+ tasks, _, err := s.ipc.Database.ApprovalTasks.GetApprovalTasksListDB(ctx, opts)
+ if err != nil {
+ tasks = nil
+ }
+
+ result := make([]map[string]interface{}, 0, 7)
+ now := time.Now()
+ for i := 6; i >= 0; i-- {
+ date := now.AddDate(0, 0, -i)
+ target := date.Format("2006-01-02")
+
+ created := 0
+ completed := 0
+ for _, t := range tasks {
+ if t.CreatedAt != nil && t.CreatedAt.Format("2006-01-02") == target {
+ created++
+ }
+ if t.CompletedAt != nil && t.CompletedAt.Format("2006-01-02") == target {
+ completed++
+ }
+ }
+
+ result = append(result, map[string]interface{}{
+ "date": target,
+ "created": created,
+ "completed": completed,
+ })
+ }
+ return result
+}
+
+// ============================================================
+// 🆕 Кто отсутствует сегодня (отгул/отпуск/больничный).
+//
+// 🩹 Логика разбора дат намеренно продублирована из
+// scheduler/daily_reminder.go (getAbsentEmployeesToday) — тот же самый
+// терпимый к опечаткам подход через regexp, т.к. у заявок на отсутствие
+// нет отдельного структурированного поля с датами. rest_admin_service
+// использует свой ipc-тип, отличный от telegram_service, поэтому
+// переиспользовать функцию напрямую нельзя — общий пакет пока не заводили.
+//
+// Упрощение по сравнению с ботом: здесь НЕ подмешивается контакт-делегат
+// (ApprovalDelegation) — просто список отсутствующих с описанием.
+// ============================================================
+
+type dashboardAbsenceMetadata struct {
+ Extra struct {
+ TimeType string `json:"time_type"`
+ AbsenceType string `json:"absence_type"`
+ } `json:"extra"`
+}
+
+var dashboardAbsenceDateRe = regexp.MustCompile(`(\d{1,2})[.,](\d{1,2})\.(\d{4})`)
+var dashboardAbsenceTimeRe = regexp.MustCompile(`(\d{1,2}):(\d{2}).*?(\d{1,2}):(\d{2})`)
+
+func (s *DashboardReg) getAbsentToday(ctx context.Context) []map[string]interface{} {
+ loc, err := time.LoadLocation("Europe/Moscow")
+ if err != nil {
+ loc = time.FixedZone("MSK", 3*3600)
+ }
+ today := time.Now().In(loc)
+ todayY, todayM, todayD := today.Date()
+
+ approvals, _, err := s.ipc.Database.Approval.GetApprovalsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.Approval{Status: strPtr("approved")},
+ Limit: utilscore.PointerToUint64(10000),
+ })
+ if err != nil {
+ return []map[string]interface{}{}
+ }
+
+ seenUsers := make(map[uint64]bool)
+ result := []map[string]interface{}{}
+
+ for _, a := range approvals {
+ if a.Metadata == nil || *a.Metadata == "" || a.Content == nil || a.InitiatorID == nil {
+ continue
+ }
+ if seenUsers[*a.InitiatorID] {
+ continue
+ }
+
+ var meta dashboardAbsenceMetadata
+ if err := json.Unmarshal([]byte(*a.Metadata), &meta); err != nil || meta.Extra.AbsenceType == "" {
+ continue
+ }
+
+ dates := parseDashboardAbsenceDates(*a.Content)
+ if len(dates) == 0 || !dashboardAbsenceCoversDate(dates, *a.Content, todayY, todayM, todayD) {
+ continue
+ }
+
+ name := ""
+ if user, uErr := s.ipc.Database.User.GetUserByIDDB(ctx, *a.InitiatorID); uErr == nil && user != nil && user.FullName != nil {
+ name = *user.FullName
+ }
+
+ var description string
+ switch meta.Extra.AbsenceType {
+ case "timeoff":
+ if meta.Extra.TimeType == "partial" {
+ if mm := dashboardAbsenceTimeRe.FindStringSubmatch(*a.Content); mm != nil {
+ description = "отгул с " + mm[1] + ":" + mm[2] + " до " + mm[3] + ":" + mm[4]
+ } else {
+ description = "отгул весь день"
+ }
+ } else {
+ description = "отгул весь день"
+ }
+ case "vacation":
+ description = "отпуск до " + maxDashboardAbsenceDate(dates).Format("02.01.2006")
+ case "sickleave":
+ description = "больничный до " + maxDashboardAbsenceDate(dates).Format("02.01.2006")
+ default:
+ description = "отсутствует"
+ }
+
+ seenUsers[*a.InitiatorID] = true
+ result = append(result, map[string]interface{}{
+ "name": name,
+ "description": description,
+ })
+ }
+
+ return result
+}
+
+func parseDashboardAbsenceDates(content string) []time.Time {
+ matches := dashboardAbsenceDateRe.FindAllStringSubmatch(content, -1)
+ var dates []time.Time
+ for _, m := range matches {
+ day, errD := strconv.Atoi(m[1])
+ month, errM := strconv.Atoi(m[2])
+ year, errY := strconv.Atoi(m[3])
+ if errD != nil || errM != nil || errY != nil {
+ continue
+ }
+ if month < 1 || month > 12 || day < 1 || day > 31 {
+ continue
+ }
+ dates = append(dates, time.Date(year, time.Month(month), day, 0, 0, 0, 0, time.UTC))
+ }
+ return dates
+}
+
+func dashboardAbsenceCoversDate(dates []time.Time, content string, y int, m time.Month, d int) bool {
+ target := time.Date(y, m, d, 0, 0, 0, 0, time.UTC)
+ if len(dates) == 2 && strings.Contains(content, "-") {
+ start, end := dates[0], dates[1]
+ if end.Before(start) {
+ start, end = end, start
+ }
+ return !target.Before(start) && !target.After(end)
+ }
+ for _, dt := range dates {
+ if dt.Equal(target) {
+ return true
+ }
+ }
+ return false
+}
+
+func maxDashboardAbsenceDate(dates []time.Time) time.Time {
+ max := dates[0]
+ for _, d := range dates[1:] {
+ if d.After(max) {
+ max = d
+ }
+ }
+ return max
+}
+
+// ============================================================
+// 🆕 Проблемы конфигурации инициаторов.
+//
+// Воспроизводит ТУ ЖЕ логику резолва согласующих, что и сам бот при
+// реальной отправке заявки (submitApproval → UserHierarchy по
+// SubordinateID+DepartmentID, с приоритетом TopicID → TopicCategoryID →
+// глобальное правило) — но заранее, для ВСЕХ пользователей и ВСЕХ тем,
+// на которые у них есть право "create", чтобы найти дыры ДО того, как
+// сотрудник наткнётся на них в боте ("⚠️ Для вас в данной теме не
+// настроены согласующие").
+//
+// Возвращает два среза:
+// 1. topicGaps — точечные пробелы: у пользователя ЕСТЬ право создавать
+// заявку по теме, но НИ ОДНО правило иерархии её не покрывает.
+// 2. usersWithoutHierarchy — более базовый случай: у пользователя нет
+// вообще ни одной строки UserHierarchy для его отдела (полностью
+// не настроен, даже глобального правила нет).
+//
+// ⚠️ Предположения, которые стоит проверить при первом запуске:
+// - Permission.GetUserPermissionsDB(ctx, userID, "create") доступен
+// из rest_admin_service так же, как используется ботом
+// (telegram_service/handlers/approval, getAllowedTopicCodes) —
+// сама структура Permission (поля TopicID/TopicCategoryID) взята
+// оттуда же, полностью структуру Permission я не видел.
+// - Пользователи без DepartmentID пропускаются целиком (это отдельная,
+// более базовая проблема — некому резолвить иерархию в принципе,
+// не про конкретные темы).
+// ============================================================
+
+func (s *DashboardReg) getInitiatorConfigWarnings(ctx context.Context) ([]map[string]interface{}, []map[string]interface{}) {
+ users, _, err := s.ipc.Database.User.GetUsersListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.User{IsBlocked: boolPtr(false), IsFired: boolPtr(false)},
+ Limit: utilscore.PointerToUint64(10000),
+ })
+ if err != nil {
+ return []map[string]interface{}{}, []map[string]interface{}{}
+ }
+
+ topics, _, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalTopic{IsActive: boolPtr(true)},
+ Limit: utilscore.PointerToUint64(10000),
+ })
+ if err != nil {
+ return []map[string]interface{}{}, []map[string]interface{}{}
+ }
+
+ categories, _, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryListDB(ctx, typescore.ListDbOptions{
+ Limit: utilscore.PointerToUint64(10000),
+ })
+ categoryNames := make(map[uint64]string, len(categories))
+ if err == nil {
+ for _, c := range categories {
+ if c.ID != nil && c.Name != nil {
+ categoryNames[*c.ID] = *c.Name
+ }
+ }
+ }
+
+ departments, _, err := s.ipc.Database.Department.GetDepartmentsListDB(ctx, typescore.ListDbOptions{
+ Limit: utilscore.PointerToUint64(10000),
+ })
+ departmentNames := make(map[uint64]string, len(departments))
+ if err == nil {
+ for _, d := range departments {
+ if d.ID != nil && d.Name != nil {
+ departmentNames[*d.ID] = *d.Name
+ }
+ }
+ }
+
+ topicByID := make(map[uint64]*typescore.ApprovalTopic, len(topics))
+ topicsByCategory := make(map[uint64][]*typescore.ApprovalTopic)
+ for _, t := range topics {
+ if t.ID == nil {
+ continue
+ }
+ topicByID[*t.ID] = t
+ if t.CategoryID != nil {
+ topicsByCategory[*t.CategoryID] = append(topicsByCategory[*t.CategoryID], t)
+ }
+ }
+
+ hierarchies, _, err := s.ipc.Database.UserHierarchy.GetUserHierarchyListDB(ctx, typescore.ListDbOptions{
+ Limit: utilscore.PointerToUint64(10000),
+ })
+ if err != nil {
+ return []map[string]interface{}{}, []map[string]interface{}{}
+ }
+
+ type coverage struct {
+ topics map[uint64]bool
+ categories map[uint64]bool
+ global bool
+ }
+ coverageKey := func(userID, deptID uint64) string {
+ return fmt.Sprintf("%d:%d", userID, deptID)
+ }
+ coverageByUserDept := make(map[string]*coverage)
+ for _, h := range hierarchies {
+ if h.SubordinateID == nil || h.DepartmentID == nil {
+ continue
+ }
+ k := coverageKey(*h.SubordinateID, *h.DepartmentID)
+ cov, ok := coverageByUserDept[k]
+ if !ok {
+ cov = &coverage{topics: map[uint64]bool{}, categories: map[uint64]bool{}}
+ coverageByUserDept[k] = cov
+ }
+ switch {
+ case h.TopicID != nil:
+ cov.topics[*h.TopicID] = true
+ case h.TopicCategoryID != nil:
+ cov.categories[*h.TopicCategoryID] = true
+ default:
+ cov.global = true
+ }
+ }
+
+ isCovered := func(userID, deptID, topicID uint64, categoryID *uint64) bool {
+ cov, ok := coverageByUserDept[coverageKey(userID, deptID)]
+ if !ok {
+ return false
+ }
+ if cov.global {
+ return true
+ }
+ if cov.topics[topicID] {
+ return true
+ }
+ if categoryID != nil && cov.categories[*categoryID] {
+ return true
+ }
+ return false
+ }
+
+ var topicGaps []map[string]interface{}
+ var usersWithoutHierarchy []map[string]interface{}
+
+ for _, user := range users {
+ if user.ID == nil || user.DepartmentID == nil {
+ continue
+ }
+
+ perms, err := s.ipc.Database.Permission.GetUserPermissionsDB(ctx, *user.ID, "create")
+ if err != nil || len(perms) == 0 {
+ continue // нет права создавать ничего — не наша забота здесь
+ }
+
+ userName := ""
+ if user.FullName != nil {
+ userName = *user.FullName
+ }
+ deptName := departmentNames[*user.DepartmentID]
+
+ // --- Проверка "вообще нет иерархии для этого отдела" ---
+ if _, hasAny := coverageByUserDept[coverageKey(*user.ID, *user.DepartmentID)]; !hasAny {
+ usersWithoutHierarchy = append(usersWithoutHierarchy, map[string]interface{}{
+ "user_id": *user.ID,
+ "full_name": userName,
+ "department_name": deptName,
+ })
+ continue // если вообще ничего нет — детальный разбор по темам избыточен
+ }
+
+ // --- Точечные пробелы по темам ---
+ allowedTopicIDs := make(map[uint64]bool)
+ for _, p := range perms {
+ if p.TopicID != nil {
+ allowedTopicIDs[*p.TopicID] = true
+ }
+ if p.TopicCategoryID != nil {
+ for _, t := range topicsByCategory[*p.TopicCategoryID] {
+ if t.ID != nil {
+ allowedTopicIDs[*t.ID] = true
+ }
+ }
+ }
+ }
+
+ for topicID := range allowedTopicIDs {
+ topic := topicByID[topicID]
+ if topic == nil {
+ continue
+ }
+ if isCovered(*user.ID, *user.DepartmentID, topicID, topic.CategoryID) {
+ continue
+ }
+
+ topicName := ""
+ if topic.Name != nil {
+ topicName = *topic.Name
+ }
+ categoryName := ""
+ if topic.CategoryID != nil {
+ categoryName = categoryNames[*topic.CategoryID]
+ }
+
+ topicGaps = append(topicGaps, map[string]interface{}{
+ "user_id": *user.ID,
+ "full_name": userName,
+ "department_name": deptName,
+ "topic_id": topicID,
+ "topic_name": topicName,
+ "category_name": categoryName,
+ })
+ }
+ }
+
+ if topicGaps == nil {
+ topicGaps = []map[string]interface{}{}
+ }
+ if usersWithoutHierarchy == nil {
+ usersWithoutHierarchy = []map[string]interface{}{}
+ }
+
+ return topicGaps, usersWithoutHierarchy
+}
+
+func boolPtr(b bool) *bool { return &b }
+func strPtr(s string) *string { return &s }
+
+-----END handlers/dashboard/handlers.go-----
+
+File: handlers/dashboard/routes.go
+Lines: 33
+-----BEGIN handlers/dashboard/routes.go-----
+package dashboardhandler
+
+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 DashboardReg struct {
+ ipc *typesm.InternalProviderControl
+}
+
+// RegisterDashboardRoutes регистрирует маршруты для дашборда
+func RegisterDashboardRoutes(
+ r chi.Router,
+ ipc *typesm.InternalProviderControl,
+) error {
+ s := &DashboardReg{
+ ipc: ipc,
+ }
+
+ r.Route("/api/dashboard", 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, "/stats", s.GetDashboardStatsHandler)
+ })
+
+ return nil
+}
+
+-----END handlers/dashboard/routes.go-----
+
+File: handlers/departments/handlers.go
+Lines: 344
+-----BEGIN handlers/departments/handlers.go-----
+package departmentshandler
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/core/utilscore"
+ "bitrix_balancer_api/rest_admin_service/handlers"
+ adminloghandler "bitrix_balancer_api/rest_admin_service/handlers/admin_actions"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "github.com/sirupsen/logrus"
+ "io"
+ "net/http"
+ "strconv"
+ "strings"
+
+ "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 := r.Context()
+ 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 := r.Context()
+ 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 := r.Context()
+ 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")
+ }
+
+ 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
+ }
+
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ snapshot := map[string]interface{}{
+ "name": utilscore.DerefStr(createdDept.Name),
+ "code": utilscore.DerefStr(createdDept.Code),
+ "is_active": utilscore.DerefBool(createdDept.IsActive),
+ }
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "create", "department", createdDept.ID,
+ fmt.Sprintf("Создан отдел «%s»", utilscore.DerefStr(createdDept.Name)),
+ map[string]interface{}{"snapshot": snapshot},
+ )
+ }
+
+ 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 := r.Context()
+ 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")
+ }
+ }
+ }
+
+ type fieldChange struct {
+ Field string `json:"field"`
+ Old interface{} `json:"old"`
+ New interface{} `json:"new"`
+ }
+ var changes []fieldChange
+ var summary []string
+
+ if req.Name != nil && !utilscore.StrEq(existingDept.Name, req.Name) {
+ changes = append(changes, fieldChange{"name", utilscore.DerefStr(existingDept.Name), *req.Name})
+ summary = append(summary, fmt.Sprintf("название: «%s» → «%s»", utilscore.DerefStr(existingDept.Name), *req.Name))
+ }
+ if req.Code != nil && !utilscore.StrEq(existingDept.Code, req.Code) {
+ changes = append(changes, fieldChange{"code", utilscore.DerefStr(existingDept.Code), *req.Code})
+ summary = append(summary, fmt.Sprintf("код: «%s» → «%s»", utilscore.DerefStr(existingDept.Code), *req.Code))
+ }
+ if req.IsActive != nil && !utilscore.BoolEq(existingDept.IsActive, req.IsActive) {
+ changes = append(changes, fieldChange{"is_active", utilscore.DerefBool(existingDept.IsActive), *req.IsActive})
+ if *req.IsActive {
+ summary = append(summary, "активирован")
+ } else {
+ summary = append(summary, "деактивирован")
+ }
+ }
+
+ updatedDept, _, err := s.ipc.Database.Department.UpdateDepartmentDB(ctx, nil, &req, true)
+ if err != nil {
+ return nil, err
+ }
+
+ if len(changes) > 0 {
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ description := fmt.Sprintf("Изменён отдел «%s»: %s", utilscore.DerefStr(existingDept.Name), strings.Join(summary, "; "))
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "update", "department", req.ID,
+ description,
+ map[string]interface{}{"changes": changes},
+ )
+ }
+ }
+
+ 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 := r.Context()
+ 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
+ }
+
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ snapshot := map[string]interface{}{
+ "name": utilscore.DerefStr(existingDept.Name),
+ "code": utilscore.DerefStr(existingDept.Code),
+ "is_active": utilscore.DerefBool(existingDept.IsActive),
+ }
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "delete", "department", req.ID,
+ fmt.Sprintf("Удалён отдел «%s»", utilscore.DerefStr(existingDept.Name)),
+ map[string]interface{}{"snapshot": snapshot},
+ )
+ }
+
+ return true, nil
+}
+
+func (s *DepartmentsReg) getCurrentAdmin(ctx context.Context) (*typescore.Admin, bool) {
+ currentUserID, err := handlers.GetIDFromContext(ctx)
+ if err != nil {
+ return nil, false
+ }
+
+ admins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{
+ Filtering: &typescore.Admin{ID: ¤tUserID},
+ })
+ if err != nil || len(admins) == 0 || admins[0] == nil || admins[0].ID == nil || admins[0].Login == nil {
+ return nil, false
+ }
+
+ return admins[0], true
+}
+
+-----END handlers/departments/handlers.go-----
+
+File: handlers/departments/routes.go
+Lines: 47
+-----BEGIN handlers/departments/routes.go-----
+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
+}
+
+-----END handlers/departments/routes.go-----
+
+File: handlers/flow_nodes/handler.go
+Lines: 837
+-----BEGIN handlers/flow_nodes/handler.go-----
+package nodeshandler
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/core/utilscore"
+ "bitrix_balancer_api/rest_admin_service/handlers"
+ adminloghandler "bitrix_balancer_api/rest_admin_service/handlers/admin_actions"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "strconv"
+
+ "github.com/go-chi/chi/v5"
+)
+
+func (s *FlowNodesReg) GetFlowNodesByCategoryIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ categoryIDStr := chi.URLParam(r, "category_id")
+ categoryID, err := strconv.ParseUint(categoryIDStr, 10, 64)
+ if err != nil {
+ return nil, errors.New("invalid category_id")
+ }
+
+ ctx := r.Context()
+
+ category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, categoryID)
+ if err != nil {
+ return nil, err
+ }
+ if category == nil {
+ return nil, errors.New("category not found")
+ }
+
+ nodes, _, err := s.ipc.Database.ApprovalFlowNode.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalFlowNode{CategoryID: &categoryID},
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ tree := s.buildTreeFromNodes(nodes)
+
+ return &typescore.ApiResponseBase{
+ TotalCount: uint64(len(nodes)),
+ Data: tree,
+ }, nil
+}
+
+func (s *FlowNodesReg) GetFlowNodeByIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ idStr := chi.URLParam(r, "id")
+ if idStr == "" {
+ return nil, errors.New("node id is required")
+ }
+
+ id, err := strconv.ParseUint(idStr, 10, 64)
+ if err != nil {
+ return nil, errors.New("invalid node id")
+ }
+
+ ctx := r.Context()
+ node, err := s.ipc.Database.ApprovalFlowNode.GetFlowNodeByIDDB(ctx, id)
+ if err != nil {
+ return nil, err
+ }
+ if node == nil {
+ return nil, errors.New("node not found")
+ }
+
+ return node, nil
+}
+
+func (s *FlowNodesReg) CreateFlowNodeHandler(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.ApprovalFlowNode
+ if err := json.Unmarshal(body, &req); err != nil {
+ return nil, errors.New("invalid request body")
+ }
+
+ if req.CategoryID == nil {
+ return nil, errors.New("category_id is required")
+ }
+ if req.Key == nil || *req.Key == "" {
+ return nil, errors.New("key is required")
+ }
+ if req.Label == nil || *req.Label == "" {
+ return nil, errors.New("label is required")
+ }
+
+ ctx := r.Context()
+
+ 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.ParentID != nil {
+ parent, err := s.ipc.Database.ApprovalFlowNode.GetFlowNodeByIDDB(ctx, *req.ParentID)
+ if err != nil {
+ return nil, err
+ }
+ if parent == nil {
+ return nil, errors.New("parent node not found")
+ }
+ if parent.CategoryID == nil || *parent.CategoryID != *req.CategoryID {
+ return nil, errors.New("parent node belongs to a different category")
+ }
+ }
+
+ existing, _, err := s.ipc.Database.ApprovalFlowNode.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalFlowNode{
+ CategoryID: req.CategoryID,
+ Key: req.Key,
+ },
+ })
+ if err != nil {
+ return nil, err
+ }
+ if len(existing) > 0 {
+ return nil, fmt.Errorf("node with key '%s' already exists in this category", *req.Key)
+ }
+
+ if req.IsInput == nil {
+ v := false
+ req.IsInput = &v
+ }
+ if req.IsMultiSelect == nil {
+ v := false
+ req.IsMultiSelect = &v
+ }
+ if req.SortOrder == nil {
+ v := 0
+ req.SortOrder = &v
+ }
+
+ created, _, err := s.ipc.Database.ApprovalFlowNode.CreateApprovalFlowNodeDB(ctx, nil, &req, true)
+ if err != nil {
+ return nil, err
+ }
+
+ s.bumpFlowVersion(ctx)
+
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ snapshot := map[string]interface{}{
+ "key": utilscore.DerefStr(created.Key),
+ "label": utilscore.DerefStr(created.Label),
+ "category_id": *req.CategoryID,
+ }
+ if created.ParentID != nil {
+ snapshot["parent_id"] = *created.ParentID
+ }
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "create", "flow_node", created.ID,
+ fmt.Sprintf("Создан узел «%s» (%s)", utilscore.DerefStr(created.Label), utilscore.DerefStr(created.Key)),
+ map[string]interface{}{"snapshot": snapshot},
+ )
+ }
+
+ return created, nil
+}
+
+func (s *FlowNodesReg) UpdateFlowNodeHandler(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.ApprovalFlowNode
+ if err := json.Unmarshal(body, &req); err != nil {
+ return nil, errors.New("invalid request body")
+ }
+
+ if req.ID == nil {
+ return nil, errors.New("id is required")
+ }
+
+ ctx := r.Context()
+
+ existing, err := s.ipc.Database.ApprovalFlowNode.GetFlowNodeByIDDB(ctx, *req.ID)
+ if err != nil {
+ return nil, err
+ }
+ if existing == nil {
+ return nil, errors.New("node not found")
+ }
+
+ if req.ParentID != nil && (existing.ParentID == nil || *existing.ParentID != *req.ParentID) {
+ parent, err := s.ipc.Database.ApprovalFlowNode.GetFlowNodeByIDDB(ctx, *req.ParentID)
+ if err != nil {
+ return nil, err
+ }
+ if parent == nil {
+ return nil, errors.New("parent node not found")
+ }
+ if parent.CategoryID == nil || existing.CategoryID == nil || *parent.CategoryID != *existing.CategoryID {
+ return nil, errors.New("parent node belongs to a different category")
+ }
+ if err := s.checkNoCyclicReference(ctx, *req.ID, *req.ParentID); err != nil {
+ return nil, err
+ }
+ }
+
+ if req.Key != nil && *req.Key != "" {
+ if existing.Key == nil || *existing.Key != *req.Key {
+ categoryID := existing.CategoryID
+ if req.CategoryID != nil {
+ categoryID = req.CategoryID
+ }
+ existingNodes, _, err := s.ipc.Database.ApprovalFlowNode.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalFlowNode{
+ CategoryID: categoryID,
+ Key: req.Key,
+ },
+ })
+ if err != nil {
+ return nil, err
+ }
+ if len(existingNodes) > 0 {
+ return nil, fmt.Errorf("node with key '%s' already exists in this category", *req.Key)
+ }
+ }
+ }
+
+ type fieldChange struct {
+ Field string `json:"field"`
+ Old interface{} `json:"old"`
+ New interface{} `json:"new"`
+ }
+ var changes []fieldChange
+
+ if req.Key != nil && !utilscore.StrEq(existing.Key, req.Key) {
+ changes = append(changes, fieldChange{"key", utilscore.DerefStr(existing.Key), *req.Key})
+ }
+ if req.Label != nil && !utilscore.StrEq(existing.Label, req.Label) {
+ changes = append(changes, fieldChange{"label", utilscore.DerefStr(existing.Label), *req.Label})
+ }
+ if req.DataKey != nil && !utilscore.StrEq(existing.DataKey, req.DataKey) {
+ changes = append(changes, fieldChange{"data_key", utilscore.DerefStr(existing.DataKey), *req.DataKey})
+ }
+ if req.DataValue != nil && !utilscore.StrEq(existing.DataValue, req.DataValue) {
+ changes = append(changes, fieldChange{"data_value", utilscore.DerefStr(existing.DataValue), *req.DataValue})
+ }
+ if req.MessageTemplate != nil && !utilscore.StrEq(existing.MessageTemplate, req.MessageTemplate) {
+ changes = append(changes, fieldChange{"message_template", utilscore.DerefStr(existing.MessageTemplate), *req.MessageTemplate})
+ }
+ if req.CodeTemplate != nil && !utilscore.StrEq(existing.CodeTemplate, req.CodeTemplate) {
+ changes = append(changes, fieldChange{"code_template", utilscore.DerefStr(existing.CodeTemplate), *req.CodeTemplate})
+ }
+ if req.SortOrder != nil && !utilscore.IntEq(existing.SortOrder, req.SortOrder) {
+ var oldVal interface{}
+ if existing.SortOrder != nil {
+ oldVal = *existing.SortOrder
+ }
+ changes = append(changes, fieldChange{"sort_order", oldVal, *req.SortOrder})
+ }
+ if req.ParentID != nil && !utilscore.Uint64Eq(existing.ParentID, req.ParentID) {
+ var oldVal interface{}
+ if existing.ParentID != nil {
+ oldVal = *existing.ParentID
+ }
+ changes = append(changes, fieldChange{"parent_id", oldVal, *req.ParentID})
+ }
+
+ updated, _, err := s.ipc.Database.ApprovalFlowNode.UpdateApprovalFlowNodeDB(ctx, nil, &req, true)
+ if err != nil {
+ return nil, err
+ }
+
+ s.bumpFlowVersion(ctx)
+
+ if len(changes) > 0 {
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "update", "flow_node", req.ID,
+ fmt.Sprintf("Изменён узел «%s»", utilscore.DerefStr(existing.Label)),
+ map[string]interface{}{"changes": changes},
+ )
+ }
+ }
+
+ return updated, nil
+}
+
+func (s *FlowNodesReg) DeleteFlowNodeHandler(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.ApprovalFlowNode
+ if err := json.Unmarshal(body, &req); err != nil {
+ return nil, errors.New("invalid request body")
+ }
+
+ if req.ID == nil {
+ return nil, errors.New("id is required")
+ }
+
+ ctx := r.Context()
+
+ existing, err := s.ipc.Database.ApprovalFlowNode.GetFlowNodeByIDDB(ctx, *req.ID)
+ if err != nil {
+ return nil, err
+ }
+ if existing == nil {
+ return nil, errors.New("node not found")
+ }
+
+ children, _, _ := s.ipc.Database.ApprovalFlowNode.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalFlowNode{ParentID: req.ID},
+ })
+
+ err = s.ipc.Database.ApprovalFlowNode.DeleteApprovalFlowNodeDB(ctx, &req)
+ if err != nil {
+ return nil, err
+ }
+
+ s.bumpFlowVersion(ctx)
+
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ snapshot := map[string]interface{}{
+ "key": utilscore.DerefStr(existing.Key),
+ "label": utilscore.DerefStr(existing.Label),
+ "direct_children": len(children),
+ }
+ if existing.CategoryID != nil {
+ snapshot["category_id"] = *existing.CategoryID
+ }
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "delete", "flow_node", req.ID,
+ fmt.Sprintf("Удалён узел «%s» (каскадно удалено дочерних: %d)", utilscore.DerefStr(existing.Label), len(children)),
+ map[string]interface{}{"snapshot": snapshot},
+ )
+ }
+
+ return true, nil
+}
+
+func (s *FlowNodesReg) SaveEntireTreeHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ categoryIDStr := chi.URLParam(r, "category_id")
+ categoryID, err := strconv.ParseUint(categoryIDStr, 10, 64)
+ if err != nil {
+ return nil, errors.New("invalid category_id")
+ }
+
+ defer r.Body.Close()
+ body, err := io.ReadAll(r.Body)
+ if err != nil {
+ return nil, err
+ }
+
+ var req struct {
+ Nodes []*typescore.ApprovalFlowNode `json:"nodes"`
+ }
+ if err := json.Unmarshal(body, &req); err != nil {
+ return nil, errors.New("invalid request body")
+ }
+
+ ctx := r.Context()
+
+ category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, categoryID)
+ if err != nil {
+ return nil, err
+ }
+ if category == nil {
+ return nil, errors.New("category not found")
+ }
+
+ oldNodes, _, _ := s.ipc.Database.ApprovalFlowNode.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalFlowNode{CategoryID: &categoryID},
+ })
+
+ if err := s.ipc.Database.ApprovalFlowNode.DeleteFlowNodesByCategoryIDDB(ctx, categoryID); err != nil {
+ return nil, err
+ }
+
+ if err := s.saveNodesRecursive(ctx, req.Nodes, categoryID, nil); err != nil {
+ return nil, err
+ }
+
+ s.bumpFlowVersion(ctx)
+
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ categoryName := utilscore.DerefStr(category.Name)
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "update", "flow_tree", &categoryID,
+ fmt.Sprintf("Пересохранено дерево категории «%s» (было узлов: %d, стало: %d)", categoryName, len(oldNodes), countNodesRecursive(req.Nodes)),
+ map[string]interface{}{
+ "category_id": categoryID,
+ "nodes_before": len(oldNodes),
+ "nodes_after": countNodesRecursive(req.Nodes),
+ },
+ )
+ }
+
+ return true, nil
+}
+
+func (s *FlowNodesReg) MoveFlowNodeHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ idStr := chi.URLParam(r, "id")
+ id, err := strconv.ParseUint(idStr, 10, 64)
+ if err != nil {
+ return nil, errors.New("invalid node id")
+ }
+
+ defer r.Body.Close()
+ body, err := io.ReadAll(r.Body)
+ if err != nil {
+ return nil, err
+ }
+
+ var req struct {
+ NewParentID *uint64 `json:"new_parent_id"`
+ NewSortOrder *int `json:"new_sort_order"`
+ }
+ if err := json.Unmarshal(body, &req); err != nil {
+ return nil, errors.New("invalid request body")
+ }
+
+ ctx := r.Context()
+
+ node, err := s.ipc.Database.ApprovalFlowNode.GetFlowNodeByIDDB(ctx, id)
+ if err != nil {
+ return nil, err
+ }
+ if node == nil {
+ return nil, errors.New("node not found")
+ }
+
+ if req.NewParentID != nil {
+ if *req.NewParentID == id {
+ return nil, errors.New("node cannot be its own parent")
+ }
+
+ parent, err := s.ipc.Database.ApprovalFlowNode.GetFlowNodeByIDDB(ctx, *req.NewParentID)
+ if err != nil {
+ return nil, err
+ }
+ if parent == nil {
+ return nil, errors.New("new parent node not found")
+ }
+
+ if parent.CategoryID == nil || node.CategoryID == nil || *parent.CategoryID != *node.CategoryID {
+ return nil, errors.New("new parent belongs to a different category")
+ }
+
+ if err := s.checkNoCyclicReference(ctx, id, *req.NewParentID); err != nil {
+ return nil, err
+ }
+ }
+
+ update := &typescore.ApprovalFlowNode{ID: &id}
+ if req.NewParentID != nil {
+ update.ParentID = req.NewParentID
+ }
+ if req.NewSortOrder != nil {
+ update.SortOrder = req.NewSortOrder
+ }
+
+ updated, _, err := s.ipc.Database.ApprovalFlowNode.UpdateApprovalFlowNodeDB(ctx, nil, update, true)
+ if err != nil {
+ return nil, err
+ }
+
+ s.bumpFlowVersion(ctx)
+
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ var oldParent interface{}
+ if node.ParentID != nil {
+ oldParent = *node.ParentID
+ }
+ metadata := map[string]interface{}{
+ "old_parent_id": oldParent,
+ "new_parent_id": req.NewParentID,
+ "new_sort_order": req.NewSortOrder,
+ }
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "update", "flow_node", &id,
+ fmt.Sprintf("Перемещён узел «%s»", utilscore.DerefStr(node.Label)),
+ metadata,
+ )
+ }
+
+ return updated, nil
+}
+
+func (s *FlowNodesReg) DuplicateFlowNodeHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ idStr := chi.URLParam(r, "id")
+ id, err := strconv.ParseUint(idStr, 10, 64)
+ if err != nil {
+ return nil, errors.New("invalid node id")
+ }
+
+ ctx := r.Context()
+
+ original, err := s.ipc.Database.ApprovalFlowNode.GetFlowNodeByIDDB(ctx, id)
+ if err != nil {
+ return nil, err
+ }
+ if original == nil {
+ return nil, errors.New("node not found")
+ }
+
+ allNodes, _, err := s.ipc.Database.ApprovalFlowNode.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalFlowNode{CategoryID: original.CategoryID},
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ descendants := s.collectDescendants(id, allNodes)
+ suffix := s.generateCopySuffix(ctx, original)
+
+ newKey := *original.Key + suffix
+ newLabel := *original.Label + " (копия)"
+
+ copyNode := &typescore.ApprovalFlowNode{
+ CategoryID: original.CategoryID,
+ TopicID: original.TopicID,
+ ParentID: original.ParentID,
+ Key: &newKey,
+ Label: &newLabel,
+ DataKey: original.DataKey,
+ DataValue: original.DataValue,
+ IsInput: original.IsInput,
+ InputKey: original.InputKey,
+ InputHint: original.InputHint,
+ IsMultiSelect: original.IsMultiSelect,
+ MultiSelectKey: original.MultiSelectKey,
+ MultiSelectValue: original.MultiSelectValue,
+ TopicCode: original.TopicCode,
+ SortOrder: original.SortOrder,
+ MessageTemplate: original.MessageTemplate,
+ CodeTemplate: original.CodeTemplate,
+ }
+
+ createdCopy, _, err := s.ipc.Database.ApprovalFlowNode.CreateApprovalFlowNodeDB(ctx, nil, copyNode, true)
+ if err != nil {
+ return nil, err
+ }
+
+ if len(descendants) > 0 {
+ idMapping := map[uint64]uint64{
+ id: *createdCopy.ID,
+ }
+
+ sortedDescendants := s.sortByDepth(id, descendants, allNodes)
+
+ for _, desc := range sortedDescendants {
+ descKey := *desc.Key + suffix
+ descCopy := &typescore.ApprovalFlowNode{
+ CategoryID: desc.CategoryID,
+ TopicID: desc.TopicID,
+ Key: &descKey,
+ Label: desc.Label,
+ DataKey: desc.DataKey,
+ DataValue: desc.DataValue,
+ IsInput: desc.IsInput,
+ InputKey: desc.InputKey,
+ InputHint: desc.InputHint,
+ IsMultiSelect: desc.IsMultiSelect,
+ MultiSelectKey: desc.MultiSelectKey,
+ MultiSelectValue: desc.MultiSelectValue,
+ TopicCode: desc.TopicCode,
+ SortOrder: desc.SortOrder,
+ MessageTemplate: desc.MessageTemplate,
+ CodeTemplate: desc.CodeTemplate,
+ }
+
+ if desc.ParentID != nil {
+ if newParentID, ok := idMapping[*desc.ParentID]; ok {
+ descCopy.ParentID = &newParentID
+ }
+ }
+
+ createdDesc, _, err := s.ipc.Database.ApprovalFlowNode.CreateApprovalFlowNodeDB(ctx, nil, descCopy, true)
+ if err != nil {
+ return nil, err
+ }
+ if desc.ID != nil && createdDesc != nil && createdDesc.ID != nil {
+ idMapping[*desc.ID] = *createdDesc.ID
+ }
+ }
+ }
+
+ s.bumpFlowVersion(ctx)
+
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "create", "flow_node", createdCopy.ID,
+ fmt.Sprintf("Продублирован узел «%s» (с потомками: %d)", utilscore.DerefStr(original.Label), len(descendants)),
+ map[string]interface{}{
+ "duplicated_from": id,
+ "descendants": len(descendants),
+ },
+ )
+ }
+
+ return createdCopy, nil
+}
+
+func (s *FlowNodesReg) buildTreeFromNodes(nodes []*typescore.ApprovalFlowNode) []*typescore.ApprovalFlowNode {
+ nodeMap := make(map[uint64]*typescore.ApprovalFlowNode)
+ var roots []*typescore.ApprovalFlowNode
+
+ for _, n := range nodes {
+ if n.ID != nil {
+ nodeMap[*n.ID] = n
+ }
+ }
+
+ for _, n := range nodes {
+ if n.ParentID == nil {
+ roots = append(roots, n)
+ } else if parent, ok := nodeMap[*n.ParentID]; ok {
+ parent.Children = append(parent.Children, n)
+ }
+ }
+
+ return roots
+}
+
+func (s *FlowNodesReg) saveNodesRecursive(ctx context.Context, nodes []*typescore.ApprovalFlowNode, categoryID uint64, parentID *uint64) error {
+ for i, node := range nodes {
+ node.CategoryID = &categoryID
+ node.ParentID = parentID
+
+ sortOrder := i
+ node.SortOrder = &sortOrder
+
+ created, _, err := s.ipc.Database.ApprovalFlowNode.CreateApprovalFlowNodeDB(ctx, nil, node, true)
+ if err != nil {
+ return err
+ }
+
+ if len(node.Children) > 0 {
+ if err := s.saveNodesRecursive(ctx, node.Children, categoryID, created.ID); err != nil {
+ return err
+ }
+ }
+ }
+ return nil
+}
+
+// checkNoCyclicReference идёт вверх по родителям от newParentID — если
+// встретит nodeID, значит перемещение создаёт цикл.
+func (s *FlowNodesReg) checkNoCyclicReference(ctx context.Context, nodeID, newParentID uint64) error {
+ currentID := newParentID
+ visited := make(map[uint64]bool)
+
+ for currentID != 0 {
+ if visited[currentID] {
+ break
+ }
+ visited[currentID] = true
+
+ if currentID == nodeID {
+ return errors.New("cyclic reference detected: cannot move node under its own descendant")
+ }
+
+ parent, err := s.ipc.Database.ApprovalFlowNode.GetFlowNodeByIDDB(ctx, currentID)
+ if err != nil || parent == nil {
+ break
+ }
+ if parent.ParentID == nil {
+ break
+ }
+ currentID = *parent.ParentID
+ }
+
+ return nil
+}
+
+func (s *FlowNodesReg) collectDescendants(rootID uint64, allNodes []*typescore.ApprovalFlowNode) []*typescore.ApprovalFlowNode {
+ childrenMap := make(map[uint64][]*typescore.ApprovalFlowNode)
+ for _, n := range allNodes {
+ if n.ParentID != nil {
+ childrenMap[*n.ParentID] = append(childrenMap[*n.ParentID], n)
+ }
+ }
+
+ var result []*typescore.ApprovalFlowNode
+ queue := []uint64{rootID}
+
+ for len(queue) > 0 {
+ current := queue[0]
+ queue = queue[1:]
+
+ for _, child := range childrenMap[current] {
+ result = append(result, child)
+ if child.ID != nil {
+ queue = append(queue, *child.ID)
+ }
+ }
+ }
+
+ return result
+}
+
+func (s *FlowNodesReg) sortByDepth(rootID uint64, descendants, allNodes []*typescore.ApprovalFlowNode) []*typescore.ApprovalFlowNode {
+ depthMap := make(map[uint64]int)
+ depthMap[rootID] = 0
+
+ nodeMap := make(map[uint64]*typescore.ApprovalFlowNode)
+ for _, n := range allNodes {
+ if n.ID != nil {
+ nodeMap[*n.ID] = n
+ }
+ }
+
+ for _, d := range descendants {
+ if d.ID == nil {
+ continue
+ }
+ depth := 0
+ currentID := d.ID
+ for {
+ node, ok := nodeMap[*currentID]
+ if !ok || node.ParentID == nil {
+ break
+ }
+ depth++
+ currentID = node.ParentID
+ if *currentID == rootID {
+ break
+ }
+ }
+ depthMap[*d.ID] = depth
+ }
+
+ sorted := make([]*typescore.ApprovalFlowNode, len(descendants))
+ copy(sorted, descendants)
+ for i := 0; i < len(sorted); i++ {
+ for j := i + 1; j < len(sorted); j++ {
+ depthI := 0
+ depthJ := 0
+ if sorted[i].ID != nil {
+ depthI = depthMap[*sorted[i].ID]
+ }
+ if sorted[j].ID != nil {
+ depthJ = depthMap[*sorted[j].ID]
+ }
+ if depthJ < depthI {
+ sorted[i], sorted[j] = sorted[j], sorted[i]
+ }
+ }
+ }
+
+ return sorted
+}
+
+func (s *FlowNodesReg) generateCopySuffix(ctx context.Context, original *typescore.ApprovalFlowNode) string {
+ if original.CategoryID == nil || original.Key == nil {
+ return "_copy"
+ }
+
+ existing, _, err := s.ipc.Database.ApprovalFlowNode.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalFlowNode{CategoryID: original.CategoryID},
+ })
+ if err != nil {
+ return "_copy"
+ }
+
+ baseKey := *original.Key
+ maxNum := 0
+
+ for _, n := range existing {
+ if n.Key == nil {
+ continue
+ }
+ key := *n.Key
+ if len(key) > len(baseKey) && key[:len(baseKey)] == baseKey {
+ suffix := key[len(baseKey):]
+ if len(suffix) >= 6 && suffix[:5] == "_copy" {
+ if len(suffix) > 5 {
+ numStr := suffix[6:]
+ if num, err := strconv.Atoi(numStr); err == nil && num > maxNum {
+ maxNum = num
+ }
+ } else if suffix == "_copy" {
+ if maxNum < 1 {
+ maxNum = 1
+ }
+ }
+ }
+ }
+ }
+
+ return fmt.Sprintf("_copy_%d", maxNum+1)
+}
+
+func countNodesRecursive(nodes []*typescore.ApprovalFlowNode) int {
+ count := len(nodes)
+ for _, n := range nodes {
+ count += countNodesRecursive(n.Children)
+ }
+ return count
+}
+
+func (s *FlowNodesReg) getCurrentAdmin(ctx context.Context) (*typescore.Admin, bool) {
+ currentUserID, err := handlers.GetIDFromContext(ctx)
+ if err != nil {
+ return nil, false
+ }
+
+ admins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{
+ Filtering: &typescore.Admin{ID: ¤tUserID},
+ })
+ if err != nil || len(admins) == 0 || admins[0] == nil || admins[0].ID == nil || admins[0].Login == nil {
+ return nil, false
+ }
+
+ return admins[0], true
+}
+
+-----END handlers/flow_nodes/handler.go-----
+
+File: handlers/flow_nodes/preview.go
+Lines: 111
+-----BEGIN handlers/flow_nodes/preview.go-----
+package nodeshandler
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/telegram_service/approvalflow"
+ "encoding/json"
+ "errors"
+ "io"
+ "net/http"
+ "strconv"
+
+ "github.com/go-chi/chi/v5"
+)
+
+type previewFlowRequest struct {
+ // Collected — все data_key/data_value, накопленные по пути от корня
+ // дерева категории до узла, для которого считаем предпросмотр.
+ Collected map[string]string `json:"collected"`
+ // InitiatorName — необязательно, для более живого предпросмотра
+ // сообщения (по умолчанию подставляется тестовое имя).
+ InitiatorName string `json:"initiator_name"`
+}
+
+type previewFlowResponse struct {
+ // Code — код темы, который реально будет использован для поиска
+ // ApprovalTopic при подаче заявки. Пусто, если по текущим данным
+ // код ещё нельзя посчитать (путь не завершён).
+ Code string `json:"code"`
+ // Message — как будет выглядеть уведомление согласующему (с HTML-разметкой,
+ // как оно уйдёт в Telegram).
+ Message string `json:"message"`
+ // Incomplete — true, если для расчёта кода не хватает данных
+ // (это не ошибка, а нормальная ситуация для промежуточного узла).
+ Incomplete bool `json:"incomplete"`
+ // TopicExists — есть ли уже в approval_topics тема с таким кодом.
+ TopicExists bool `json:"topic_exists"`
+ TopicID uint64 `json:"topic_id,omitempty"`
+ TopicName string `json:"topic_name,omitempty"`
+}
+
+func (s *FlowNodesReg) PreviewFlowHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ categoryIDStr := chi.URLParam(r, "category_id")
+ categoryID, err := strconv.ParseUint(categoryIDStr, 10, 64)
+ if err != nil {
+ return nil, errors.New("invalid category_id")
+ }
+
+ defer r.Body.Close()
+ body, err := io.ReadAll(r.Body)
+ if err != nil {
+ return nil, err
+ }
+
+ var req previewFlowRequest
+ if len(body) > 0 {
+ if err := json.Unmarshal(body, &req); err != nil {
+ return nil, errors.New("invalid request body")
+ }
+ }
+ if req.Collected == nil {
+ req.Collected = map[string]string{}
+ }
+ if req.InitiatorName == "" {
+ req.InitiatorName = "Иван Иванов"
+ }
+
+ ctx := r.Context()
+
+ category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, categoryID)
+ if err != nil {
+ return nil, err
+ }
+ if category == nil {
+ return nil, errors.New("category not found")
+ }
+
+ nodes, _, err := s.ipc.Database.ApprovalFlowNode.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalFlowNode{CategoryID: &categoryID},
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ dynamicTopic := approvalflow.NewDynamicTopic(category, nodes)
+
+ resp := &previewFlowResponse{}
+
+ code, err := dynamicTopic.TopicCodeFromCollected(req.Collected)
+ if err != nil {
+ // Ожидаемо для промежуточного узла: пути ещё не хватает данных.
+ resp.Incomplete = true
+ } else {
+ resp.Code = code
+
+ existingTopic, exErr := s.ipc.Database.ApprovalTopic.GetApprovalTopicByCodeDB(ctx, code)
+ if exErr == nil && existingTopic != nil {
+ resp.TopicExists = true
+ if existingTopic.ID != nil {
+ resp.TopicID = *existingTopic.ID
+ }
+ if existingTopic.Name != nil {
+ resp.TopicName = *existingTopic.Name
+ }
+ }
+ }
+
+ initiator := &typescore.User{FullName: &req.InitiatorName}
+ resp.Message = dynamicTopic.FormatApproverMessage(initiator, req.Collected)
+
+ return resp, nil
+}
+
+-----END handlers/flow_nodes/preview.go-----
+
+File: handlers/flow_nodes/router.go
+Lines: 61
+-----BEGIN handlers/flow_nodes/router.go-----
+package nodeshandler
+
+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 FlowNodesReg struct {
+ ipc *typesm.InternalProviderControl
+}
+
+// RegisterFlowNodesRoutes регистрирует маршруты для управления узлами дерева.
+// Дерево навигации принадлежит категории (category_id) — см. ApprovalFlowNode.CategoryID
+// и Registry.LoadFromDB, которые строят Topic-интерфейс по категории + узлам.
+func RegisterFlowNodesRoutes(
+ r chi.Router,
+ ipc *typesm.InternalProviderControl,
+) error {
+ s := &FlowNodesReg{
+ ipc: ipc,
+ }
+
+ r.Route("/api/flow-nodes", 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, "/category/{category_id}", s.GetFlowNodesByCategoryIDHandler)
+
+ // CRUD операции с узлами
+ handlers.RegisterRoute(r, http.MethodPost, "/", s.CreateFlowNodeHandler)
+ handlers.RegisterRoute(r, http.MethodPut, "/", s.UpdateFlowNodeHandler)
+ handlers.RegisterRoute(r, http.MethodDelete, "/", s.DeleteFlowNodeHandler)
+
+ // Сохранить всё дерево целиком (для UI конструктора)
+ handlers.RegisterRoute(r, http.MethodPost, "/category/{category_id}/tree", s.SaveEntireTreeHandler)
+
+ // Переместить узел (изменить порядок или родителя) — используется
+ // и обычным ↑/↓, и кнопками "поднять/опустить уровень" в новом UI.
+ handlers.RegisterRoute(r, http.MethodPost, "/{id}/move", s.MoveFlowNodeHandler)
+
+ // Дублировать узел с детьми
+ handlers.RegisterRoute(r, http.MethodPost, "/{id}/duplicate", s.DuplicateFlowNodeHandler)
+
+ // НОВОЕ: живой предпросмотр кода темы и сообщения согласующему
+ // для конкретного пути по дереву — см. preview.go
+ handlers.RegisterRoute(r, http.MethodPost, "/category/{category_id}/preview", s.PreviewFlowHandler)
+
+ // НОВОЕ: кнопка "Обновить бота" — форсирует бамп версии дерева тем,
+ // бот подхватит на ближайшем тике фонового воркера — см. reload.go
+ handlers.RegisterRoute(r, http.MethodPost, "/reload-bot", s.ReloadBotHandler)
+
+ // Получить узел по ID
+ handlers.RegisterRoute(r, http.MethodGet, "/{id}", s.GetFlowNodeByIDHandler)
+ })
+
+ return nil
+}
+
+-----END handlers/flow_nodes/router.go-----
+
+File: handlers/flow_nodes/utils.go
+Lines: 20
+-----BEGIN handlers/flow_nodes/utils.go-----
+package nodeshandler
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "time"
+)
+
+const flowVersionRedisKey = "approval_flow:version"
+
+func (s *FlowNodesReg) bumpFlowVersion(ctx context.Context) {
+ version := fmt.Sprintf("%d", time.Now().UnixNano())
+ _ = s.ipc.RedisClient.Set(ctx, flowVersionRedisKey, version, 24*time.Hour)
+}
+
+func (s *FlowNodesReg) ReloadBotHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ s.bumpFlowVersion(r.Context())
+ return true, nil
+}
+
+-----END handlers/flow_nodes/utils.go-----
+
+File: handlers/middleware.go
+Lines: 328
+-----BEGIN handlers/middleware.go-----
+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"
+ "net/http"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/sirupsen/logrus"
+)
+
+// 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 == "" {
+ logrus.WithFields(logrus.Fields{
+ "path": r.URL.Path,
+ }).Error("JWTVerifier: AdminSecret is empty")
+ http.Error(w, "Internal server error", http.StatusInternalServerError)
+ return
+ }
+
+ authHeader := r.Header.Get("Authorization")
+ if authHeader == "" {
+ logrus.WithFields(logrus.Fields{
+ "path": r.URL.Path,
+ }).Warn("JWTVerifier: Authorization header is empty")
+ http.Error(w, "Unauthorized", http.StatusUnauthorized)
+ return
+ }
+
+ deviceID := r.Header.Get("x-device-id")
+ if deviceID == "" {
+ logrus.WithFields(logrus.Fields{
+ "path": r.URL.Path,
+ }).Warn("JWTVerifier: x-device-id header is empty")
+ http.Error(w, "Unauthorized device", http.StatusUnauthorized)
+ return
+ }
+
+ if redisModule == nil {
+ logrus.Error("JWTVerifier: Redis storage not initialized")
+ http.Error(w, "Internal server error: Redis storage not initialized", http.StatusInternalServerError)
+ return
+ }
+
+ parts := strings.Split(authHeader, " ")
+ if len(parts) != 2 || parts[0] != "Bearer" {
+ logrus.WithFields(logrus.Fields{
+ "path": r.URL.Path,
+ "auth_header": authHeader,
+ }).Warn("JWTVerifier: Invalid authorization header format")
+ http.Error(w, "Invalid authorization header", http.StatusUnauthorized)
+ return
+ }
+ tokenString := parts[1]
+
+ _, claims, err := securecore.VerifyToken(tokenString, cfg.Secrets.AuthJWT.AdminSecret)
+ if err != nil {
+ logrus.WithFields(logrus.Fields{
+ "path": r.URL.Path,
+ "error": err.Error(),
+ }).Warn("JWTVerifier: Token verification failed")
+ http.Error(w, "Invalid token", http.StatusUnauthorized)
+ return
+ }
+
+ userIDFloat, ok := claims[securecore.IDContextKey.String()].(float64)
+ if !ok {
+ logrus.WithFields(logrus.Fields{
+ "path": r.URL.Path,
+ }).Warn("JWTVerifier: Missing user_id in token claims")
+ 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 {
+ logrus.WithFields(logrus.Fields{
+ "path": r.URL.Path,
+ "user_id": userID,
+ "error": errW,
+ }).Warn("JWTVerifier: Admin not found or blocked")
+ http.Error(w, "Admin not found or blocked", http.StatusUnauthorized)
+ return
+ }
+
+ if adminList[0].IsBlocked == nil || *adminList[0].IsBlocked {
+ logrus.WithFields(logrus.Fields{
+ "path": r.URL.Path,
+ "user_id": userID,
+ }).Warn("JWTVerifier: Account is blocked")
+ 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 == "" {
+ logrus.WithFields(logrus.Fields{
+ "path": r.URL.Path,
+ "user_id": userID,
+ "error": err,
+ }).Warn("JWTVerifier: User session not found in Redis")
+ 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 {
+ logrus.WithFields(logrus.Fields{
+ "path": r.URL.Path,
+ "user_id": userID,
+ "error": err.Error(),
+ }).Warn("JWTVerifier: Failed to unmarshal session")
+ http.Error(w, "Failed to get user session data. Please authorize again", http.StatusUnauthorized)
+ return
+ }
+
+ if !securecore.FindDeviceID(session.AuthorizedDevices, deviceID) {
+ logrus.WithFields(logrus.Fields{
+ "path": r.URL.Path,
+ "user_id": userID,
+ "device_id": deviceID,
+ }).Warn("JWTVerifier: Device not authorized")
+ http.Error(w, "Unauthorized device", http.StatusUnauthorized)
+ return
+ }
+
+ logrus.WithFields(logrus.Fields{
+ "path": r.URL.Path,
+ "user_id": userID,
+ "device_id": deviceID,
+ }).Debug("JWTVerifier: Request authorized")
+
+ 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) {
+ // 🆕 Логируем начало проверки
+ logrus.WithFields(logrus.Fields{
+ "path": r.URL.Path,
+ "method": r.Method,
+ "remote": r.RemoteAddr,
+ }).Debug("AccessCodeVerifier: Starting verification")
+
+ // Проверка 1: Секреты в конфиге
+ if cfg.Secrets.ApiPublicAdmin == "" || cfg.Secrets.ApiPrivateAdmin == "" {
+ logrus.WithFields(logrus.Fields{
+ "path": r.URL.Path,
+ "api_public_empty": cfg.Secrets.ApiPublicAdmin == "",
+ "api_private_empty": cfg.Secrets.ApiPrivateAdmin == "",
+ }).Error("AccessCodeVerifier: API secrets not configured")
+ http.Error(w, "Internal server error", http.StatusInternalServerError)
+ return
+ }
+
+ // Получаем заголовки
+ authHeader := r.Header.Get("ApiKey")
+ timestampStr := r.Header.Get("X-Timestamp")
+ deviceID := r.Header.Get("x-device-id")
+
+ logrus.WithFields(logrus.Fields{
+ "path": r.URL.Path,
+ "has_api_key": authHeader != "",
+ "has_timestamp": timestampStr != "",
+ "device_id": deviceID,
+ }).Debug("AccessCodeVerifier: Headers received")
+
+ // Проверка 2: Наличие заголовков
+ if authHeader == "" || timestampStr == "" {
+ logrus.WithFields(logrus.Fields{
+ "path": r.URL.Path,
+ "api_key_empty": authHeader == "",
+ "timestamp_empty": timestampStr == "",
+ "all_headers": r.Header,
+ }).Warn("AccessCodeVerifier: Missing required headers")
+ http.Error(w, "Unauthorized client", http.StatusUnauthorized)
+ return
+ }
+
+ // Проверка 3: Парсинг timestamp
+ timestampUnix, err := strconv.ParseInt(timestampStr, 10, 64)
+ if err != nil {
+ logrus.WithFields(logrus.Fields{
+ "path": r.URL.Path,
+ "timestamp": timestampStr,
+ "error": err.Error(),
+ }).Warn("AccessCodeVerifier: Invalid timestamp format")
+ http.Error(w, "Invalid timestamp", http.StatusBadRequest)
+ return
+ }
+
+ // Конвертируем Unix timestamp в time.Time
+ 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,
+ )
+
+ logrus.WithFields(logrus.Fields{
+ "path": r.URL.Path,
+ "timestamp_received": timestampTime.Format(time.RFC3339),
+ "timestamp_rounded": timestampTimeRounded.Format(time.RFC3339),
+ "now": now.Format(time.RFC3339),
+ "now_rounded": nowRounded.Format(time.RFC3339),
+ }).Debug("AccessCodeVerifier: Timestamp parsed")
+
+ // Проверка 4: Timestamp не старше 3 минут
+ threeMinutesAgo := nowRounded.Add(-3 * time.Minute)
+
+ if timestampTimeRounded.Before(threeMinutesAgo) {
+ logrus.WithFields(logrus.Fields{
+ "path": r.URL.Path,
+ "timestamp": timestampTimeRounded.Format(time.RFC3339),
+ "three_minutes_ago": threeMinutesAgo.Format(time.RFC3339),
+ "now": nowRounded.Format(time.RFC3339),
+ }).Warn("AccessCodeVerifier: Timestamp expired")
+ http.Error(w, "Timestamp expired", http.StatusUnauthorized)
+ return
+ }
+
+ // Проверка 5: Timestamp не в будущем
+ if timestampTimeRounded.After(nowRounded) {
+ logrus.WithFields(logrus.Fields{
+ "path": r.URL.Path,
+ "timestamp": timestampTimeRounded.Format(time.RFC3339),
+ "now": nowRounded.Format(time.RFC3339),
+ }).Warn("AccessCodeVerifier: Timestamp in future")
+ http.Error(w, "Timestamp in future", http.StatusUnauthorized)
+ return
+ }
+
+ // Проверка 6: Генерация и сравнение подписи
+ expectedSignature := utilscore.GenerateHMACSignature(
+ cfg.Secrets.ApiPublicAdmin,
+ timestampStr,
+ cfg.Secrets.ApiPrivateAdmin,
+ )
+
+ logrus.WithFields(logrus.Fields{
+ "path": r.URL.Path,
+ "public_key": cfg.Secrets.ApiPublicAdmin[:min(10, len(cfg.Secrets.ApiPublicAdmin))] + "...",
+ "timestamp": timestampStr,
+ "expected_signature": expectedSignature[:min(20, len(expectedSignature))] + "...",
+ "received_signature": authHeader[:min(20, len(authHeader))] + "...",
+ "signatures_match": expectedSignature == authHeader,
+ }).Debug("AccessCodeVerifier: Comparing signatures")
+
+ // Безопасное сравнение
+ if !utilscore.HmacEquals(expectedSignature, authHeader) {
+ logrus.WithFields(logrus.Fields{
+ "path": r.URL.Path,
+ "expected_signature": expectedSignature,
+ "received_signature": authHeader,
+ "expected_length": len(expectedSignature),
+ "received_length": len(authHeader),
+ }).Warn("AccessCodeVerifier: Signature mismatch")
+ http.Error(w, "Unauthorized client", http.StatusUnauthorized)
+ return
+ }
+
+ logrus.WithFields(logrus.Fields{
+ "path": r.URL.Path,
+ }).Debug("AccessCodeVerifier: Verification successful")
+
+ 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
+}
+
+// min возвращает минимальное из двух int
+func min(a, b int) int {
+ if a < b {
+ return a
+ }
+ return b
+}
+
+-----END handlers/middleware.go-----
+
+File: handlers/notification/handlers.go
+Lines: 306
+-----BEGIN handlers/notification/handlers.go-----
+package notificationshandler
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/core/utilscore"
+ "bitrix_balancer_api/rest_admin_service/handlers"
+ adminloghandler "bitrix_balancer_api/rest_admin_service/handlers/admin_actions"
+ typesm "bitrix_balancer_api/rest_admin_service/types"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "github.com/go-chi/chi/v5"
+ "github.com/sirupsen/logrus"
+ "io"
+ "net/http"
+ "strconv"
+)
+
+type NotificationReg struct {
+ ipc *typesm.InternalProviderControl
+}
+
+func (s *NotificationReg) CreateNotificationHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ body, err := io.ReadAll(r.Body)
+ if err != nil {
+ return nil, err
+ }
+ defer r.Body.Close()
+
+ var req typescore.CreateNotificationReq
+ if err := json.Unmarshal(body, &req); err != nil {
+ return nil, errors.New("invalid request body")
+ }
+ if req.Title == "" || req.MessageHTML == "" {
+ return nil, errors.New("title and message_html are required")
+ }
+
+ ctx := r.Context()
+
+ recipients, err := s.resolveRecipients(ctx, req.Targets)
+ if err != nil {
+ return nil, err
+ }
+ if len(recipients) == 0 {
+ return nil, errors.New("no recipients matched the given filters")
+ }
+
+ targetFiltersJSON, err := json.Marshal(req.Targets)
+ if err != nil {
+ return nil, err
+ }
+ targetFiltersStr := string(targetFiltersJSON)
+
+ status := "sending"
+ totalCount := len(recipients)
+ notification := &typescore.Notification{
+ Title: &req.Title,
+ MessageHTML: &req.MessageHTML,
+ PhotoBase64: req.PhotoBase64,
+ PhotoFileName: req.PhotoFileName,
+ TargetFilters: &targetFiltersStr,
+ Status: &status,
+ TotalCount: &totalCount,
+ }
+
+ notification, err = s.ipc.Database.Notification.CreateNotificationDB(ctx, notification)
+ if err != nil {
+ return nil, err
+ }
+
+ pendingStatus := "pending"
+ recipientRows := make([]*typescore.NotificationRecipient, 0, len(recipients))
+ for _, u := range recipients {
+ recipientRows = append(recipientRows, &typescore.NotificationRecipient{
+ NotificationID: notification.ID,
+ UserID: u.ID,
+ Status: &pendingStatus,
+ })
+ }
+ if err := s.ipc.Database.Notification.CreateNotificationRecipientsDB(ctx, recipientRows); err != nil {
+ return nil, err
+ }
+
+ sentCount, failedCount := s.sendToRecipients(ctx, notification, recipients)
+
+ finalStatus := "completed"
+ notification.Status = &finalStatus
+ notification.SentCount = &sentCount
+ notification.FailedCount = &failedCount
+ if err := s.ipc.Database.Notification.UpdateNotificationDB(ctx, notification); err != nil {
+ logrus.Warnf("CreateNotificationHandler: failed to update final status: %v", err)
+ }
+
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "create", "notification", notification.ID,
+ fmt.Sprintf("Отправлена рассылка «%s» (получателей: %d, отправлено: %d, ошибок: %d)",
+ req.Title, totalCount, sentCount, failedCount),
+ map[string]interface{}{
+ "title": req.Title,
+ "total_count": totalCount,
+ "sent_count": sentCount,
+ "failed_count": failedCount,
+ "target_filters": req.Targets,
+ },
+ )
+ }
+
+ return notification, nil
+}
+
+// resolveRecipients объединяет пользователей из всех критериев без дублей
+func (s *NotificationReg) resolveRecipients(ctx context.Context, filters typescore.TargetFilters) ([]*typescore.User, error) {
+ usersMap := make(map[uint64]*typescore.User)
+
+ addUsers := func(list []*typescore.User) {
+ for _, u := range list {
+ if u.ID != nil {
+ usersMap[*u.ID] = u
+ }
+ }
+ }
+
+ if len(filters.UserIDs) > 0 {
+ users, err := s.ipc.Database.User.GetUsersByIDsDB(ctx, filters.UserIDs)
+ if err != nil {
+ return nil, err
+ }
+ addUsers(users)
+ }
+
+ if len(filters.RoleIDs) > 0 {
+ users, _, err := s.ipc.Database.User.GetUsersListByRoleIDsDB(ctx, typescore.ListDbOptions{}, filters.RoleIDs)
+ if err != nil {
+ return nil, err
+ }
+ addUsers(users)
+ }
+
+ if len(filters.RoleTypeFlags) > 0 {
+ users, err := s.ipc.Database.User.GetUsersByRoleFlagsDB(ctx, filters.RoleTypeFlags)
+ if err != nil {
+ return nil, err
+ }
+ addUsers(users)
+ }
+
+ if len(filters.DepartmentIDs) > 0 {
+ users, err := s.ipc.Database.User.GetUsersByDepartmentIDsDB(ctx, filters.DepartmentIDs)
+ if err != nil {
+ return nil, err
+ }
+ addUsers(users)
+ }
+
+ result := make([]*typescore.User, 0, len(usersMap))
+ for _, u := range usersMap {
+ if u.IsBlocked != nil && *u.IsBlocked {
+ continue
+ }
+ result = append(result, u)
+ }
+ return result, nil
+}
+
+// sendToRecipients рассылает сообщение всем найденным пользователям и фиксирует результат по каждому
+func (s *NotificationReg) sendToRecipients(ctx context.Context, n *typescore.Notification, users []*typescore.User) (sent int, failed int) {
+ pendingRecipients, err := s.ipc.Database.Notification.GetNotificationRecipientsDB(ctx, *n.ID)
+ if err != nil {
+ logrus.Errorf("sendToRecipients: failed to load recipients: %v", err)
+ return 0, len(users)
+ }
+
+ recipientByUserID := make(map[uint64]*typescore.NotificationRecipient)
+ for _, r := range pendingRecipients {
+ if r.UserID != nil {
+ recipientByUserID[*r.UserID] = r
+ }
+ }
+
+ sentStatus := "sent"
+ failedStatus := "failed"
+
+ for _, u := range users {
+ if u.TelegramID == nil {
+ continue
+ }
+ rec, ok := recipientByUserID[*u.ID]
+ if !ok {
+ continue
+ }
+
+ var sendErr error
+ var msgID int
+
+ if n.PhotoBase64 != nil && *n.PhotoBase64 != "" {
+ fileName := "notification.jpg"
+ if n.PhotoFileName != nil {
+ fileName = *n.PhotoFileName
+ }
+ sentMsg, err := s.ipc.TGBotClient.SendPhoto(*u.TelegramID, *n.PhotoBase64, *n.MessageHTML)
+ if err != nil {
+ sendErr = err
+ } else {
+ msgID = sentMsg.MessageID
+ }
+ _ = fileName
+ } else {
+ sentMsg, err := s.ipc.TGBotClient.Send(*u.TelegramID, *n.MessageHTML)
+ if err != nil {
+ sendErr = err
+ } else {
+ msgID = sentMsg.MessageID
+ }
+ }
+
+ if sendErr != nil {
+ errStr := sendErr.Error()
+ rec.Status = &failedStatus
+ rec.ErrorMessage = &errStr
+ failed++
+ } else {
+ rec.Status = &sentStatus
+ rec.TelegramMessageID = &msgID
+ sent++
+ }
+
+ if err := s.ipc.Database.Notification.UpdateNotificationRecipientDB(ctx, rec); err != nil {
+ logrus.Warnf("sendToRecipients: failed to update recipient status: %v", err)
+ }
+ }
+
+ return sent, failed
+}
+
+// GetNotificationListHandler — история отправленных уведомлений
+func (s *NotificationReg) GetNotificationListHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ queryParams := r.URL.Query()
+
+ notificationParams := &typescore.Notification{}
+ offset, limit, likeFields, errW := utilscore.ParseParamsGetRequest(queryParams, notificationParams)
+ if errW != nil {
+ return nil, errW
+ }
+
+ options := typescore.ListDbOptions{
+ Filtering: notificationParams,
+ Offset: offset,
+ Limit: limit,
+ LikeFields: likeFields,
+ }
+
+ list, total, err := s.ipc.Database.Notification.GetNotificationsListDB(r.Context(), options)
+ if err != nil {
+ return nil, err
+ }
+
+ return &typescore.ApiResponseBase{
+ TotalCount: total,
+ Data: list,
+ }, nil
+}
+
+// GetNotificationByIDHandler — детали конкретной рассылки с постатейной историей доставки
+func (s *NotificationReg) GetNotificationByIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ idStr := chi.URLParam(r, "id")
+ id, err := strconv.ParseUint(idStr, 10, 64)
+ if err != nil {
+ return nil, errors.New("invalid notification id")
+ }
+
+ ctx := r.Context()
+ notification, err := s.ipc.Database.Notification.GetNotificationByIDDB(ctx, id)
+ if err != nil {
+ return nil, err
+ }
+ if notification == nil {
+ return nil, errors.New("notification not found")
+ }
+
+ recipients, err := s.ipc.Database.Notification.GetNotificationRecipientsDB(ctx, id)
+ if err == nil {
+ notification.Recipients = recipients
+ }
+
+ return notification, nil
+}
+
+func (s *NotificationReg) getCurrentAdmin(ctx context.Context) (*typescore.Admin, bool) {
+ currentUserID, err := handlers.GetIDFromContext(ctx)
+ if err != nil {
+ return nil, false
+ }
+
+ admins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{
+ Filtering: &typescore.Admin{ID: ¤tUserID},
+ })
+ if err != nil || len(admins) == 0 || admins[0] == nil || admins[0].ID == nil || admins[0].Login == nil {
+ return nil, false
+ }
+
+ return admins[0], true
+}
+
+-----END handlers/notification/handlers.go-----
+
+File: handlers/notification/routes.go
+Lines: 26
+-----BEGIN handlers/notification/routes.go-----
+package notificationshandler
+
+import (
+ "bitrix_balancer_api/rest_admin_service/handlers"
+ typesm "bitrix_balancer_api/rest_admin_service/types"
+ "net/http"
+
+ "github.com/go-chi/chi/v5"
+)
+
+func RegisterNotificationRoutes(r chi.Router, ipc *typesm.InternalProviderControl) error {
+ s := &NotificationReg{ipc: ipc}
+
+ r.Route("/api/notifications", 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.MethodPost, "/", s.CreateNotificationHandler)
+ handlers.RegisterRoute(r, http.MethodGet, "/", s.GetNotificationListHandler)
+ r.Get("/{id}", handlers.WrapHandlerF(handlers.WrapHandlerParams{
+ HandlerFunc: s.GetNotificationByIDHandler,
+ }))
+ })
+
+ return nil
+}
+
+-----END handlers/notification/routes.go-----
+
+File: handlers/permission/handlers.go
+Lines: 648
+-----BEGIN handlers/permission/handlers.go-----
+package permissionshandler
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/core/utilscore"
+ "bitrix_balancer_api/rest_admin_service/handlers"
+ adminloghandler "bitrix_balancer_api/rest_admin_service/handlers/admin_actions"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "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 := r.Context()
+ permissionsDbLst, total, errW := s.ipc.Database.Permission.GetPermissionsListDB(ctx, options)
+ if errW != nil {
+ return nil, errW
+ }
+
+ s.enrichPermissionsBatch(ctx, permissionsDbLst)
+
+ return &typescore.ApiResponseBase{
+ TotalCount: total,
+ Data: permissionsDbLst,
+ }, 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 := r.Context()
+
+ 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
+ }
+
+ s.enrichPermissionsBatch(ctx, permissions)
+
+ return &typescore.ApiResponseBase{
+ TotalCount: uint64(len(permissions)),
+ Data: permissions,
+ }, nil
+}
+
+// enrichPermissionsBatch пакетно подгружает роли, категории и темы для списка прав
+func (s *PermissionsReg) enrichPermissionsBatch(ctx context.Context, permissions []*typescore.Permission) {
+ if len(permissions) == 0 {
+ return
+ }
+
+ roleIDsSet := make(map[uint64]struct{})
+ categoryIDsSet := make(map[uint64]struct{})
+ topicIDsSet := make(map[uint64]struct{})
+
+ for _, p := range permissions {
+ if p.RoleID != nil {
+ roleIDsSet[*p.RoleID] = struct{}{}
+ }
+ if p.TopicCategoryID != nil {
+ categoryIDsSet[*p.TopicCategoryID] = struct{}{}
+ }
+ if p.TopicID != nil {
+ topicIDsSet[*p.TopicID] = struct{}{}
+ }
+ }
+
+ roleIDs := make([]uint64, 0, len(roleIDsSet))
+ for id := range roleIDsSet {
+ roleIDs = append(roleIDs, id)
+ }
+ categoryIDs := make([]uint64, 0, len(categoryIDsSet))
+ for id := range categoryIDsSet {
+ categoryIDs = append(categoryIDs, id)
+ }
+ topicIDs := make([]uint64, 0, len(topicIDsSet))
+ for id := range topicIDsSet {
+ topicIDs = append(topicIDs, id)
+ }
+
+ rolesMap := make(map[uint64]*typescore.Role)
+ if roles, err := s.ipc.Database.Role.GetRolesByIDsDB(ctx, roleIDs); err == nil {
+ for _, role := range roles {
+ if role.ID != nil {
+ rolesMap[*role.ID] = role
+ }
+ }
+ }
+
+ categoriesMap := make(map[uint64]*typescore.ApprovalTopicCategory)
+ if categories, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoriesByIDsDB(ctx, categoryIDs); err == nil {
+ for _, c := range categories {
+ if c.ID != nil {
+ categoriesMap[*c.ID] = c
+ }
+ }
+ }
+
+ topicsMap := make(map[uint64]*typescore.ApprovalTopic)
+ if topics, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicsByIDsDB(ctx, topicIDs); err == nil {
+ for _, t := range topics {
+ if t.ID != nil {
+ topicsMap[*t.ID] = t
+ }
+ }
+ }
+
+ for _, p := range permissions {
+ if p.RoleID != nil {
+ if role, ok := rolesMap[*p.RoleID]; ok {
+ p.Role = role
+ }
+ }
+ if p.TopicCategoryID != nil {
+ if cat, ok := categoriesMap[*p.TopicCategoryID]; ok {
+ p.TopicCategory = cat
+ }
+ }
+ if p.TopicID != nil {
+ if topic, ok := topicsMap[*p.TopicID]; ok {
+ p.Topic = topic
+ }
+ }
+ }
+}
+
+// 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 := r.Context()
+ 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
+}
+
+// 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")
+ }
+
+ if !isValidAction(*req.Action) {
+ return nil, errors.New("invalid action: must be one of create, read, update, delete, approve, revoke, observe")
+ }
+
+ ctx := r.Context()
+
+ 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)
+
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ snapshot := map[string]interface{}{
+ "role_id": *createdPermission.RoleID,
+ "action": utilscore.DerefStr(createdPermission.Action),
+ }
+ if createdPermission.TopicCategoryID != nil {
+ snapshot["topic_category_id"] = *createdPermission.TopicCategoryID
+ }
+ if createdPermission.TopicID != nil {
+ snapshot["topic_id"] = *createdPermission.TopicID
+ }
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "create", "permission", createdPermission.ID,
+ fmt.Sprintf("Выдано право «%s» роли «%s» на %s", utilscore.DerefStr(createdPermission.Action), roleLabel(createdPermission.Role), scopeLabel(createdPermission)),
+ map[string]interface{}{"snapshot": snapshot},
+ )
+ }
+
+ 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 := r.Context()
+
+ 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]
+
+ 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")
+ }
+ }
+
+ 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")
+ }
+ }
+ }
+
+ 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")
+ }
+ }
+ }
+
+ 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")
+ }
+ }
+ }
+
+ type fieldChange struct {
+ Field string `json:"field"`
+ Old interface{} `json:"old"`
+ New interface{} `json:"new"`
+ }
+ var changes []fieldChange
+
+ if req.Action != nil && !utilscore.StrEq(existing.Action, req.Action) {
+ changes = append(changes, fieldChange{"action", utilscore.DerefStr(existing.Action), *req.Action})
+ }
+ if req.RoleID != nil && !utilscore.Uint64Eq(existing.RoleID, req.RoleID) {
+ var oldVal interface{}
+ if existing.RoleID != nil {
+ oldVal = *existing.RoleID
+ }
+ changes = append(changes, fieldChange{"role_id", oldVal, *req.RoleID})
+ }
+ if req.TopicCategoryID != nil && !utilscore.Uint64Eq(existing.TopicCategoryID, req.TopicCategoryID) {
+ var oldVal interface{}
+ if existing.TopicCategoryID != nil {
+ oldVal = *existing.TopicCategoryID
+ }
+ changes = append(changes, fieldChange{"topic_category_id", oldVal, *req.TopicCategoryID})
+ }
+ if req.TopicID != nil && !utilscore.Uint64Eq(existing.TopicID, req.TopicID) {
+ var oldVal interface{}
+ if existing.TopicID != nil {
+ oldVal = *existing.TopicID
+ }
+ changes = append(changes, fieldChange{"topic_id", oldVal, *req.TopicID})
+ }
+
+ updatedPermission, _, err := s.ipc.Database.Permission.UpdatePermissionDB(ctx, nil, &req, true)
+ if err != nil {
+ return nil, err
+ }
+
+ s.enrichPermission(ctx, updatedPermission)
+
+ if len(changes) > 0 {
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "update", "permission", req.ID,
+ fmt.Sprintf("Изменено право роли «%s»", roleLabel(updatedPermission.Role)),
+ map[string]interface{}{"changes": changes},
+ )
+ }
+ }
+
+ 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 := r.Context()
+
+ 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]
+ s.enrichPermission(ctx, existing)
+
+ err = s.ipc.Database.Permission.DeletePermissionDB(ctx, &req)
+ if err != nil {
+ return nil, err
+ }
+
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ snapshot := map[string]interface{}{
+ "action": utilscore.DerefStr(existing.Action),
+ }
+ if existing.RoleID != nil {
+ snapshot["role_id"] = *existing.RoleID
+ }
+ if existing.TopicCategoryID != nil {
+ snapshot["topic_category_id"] = *existing.TopicCategoryID
+ }
+ if existing.TopicID != nil {
+ snapshot["topic_id"] = *existing.TopicID
+ }
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "delete", "permission", req.ID,
+ fmt.Sprintf("Отозвано право «%s» у роли «%s» на %s", utilscore.DerefStr(existing.Action), roleLabel(existing.Role), scopeLabel(existing)),
+ map[string]interface{}{"snapshot": snapshot},
+ )
+ }
+
+ 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]
+}
+
+func roleLabel(role *typescore.Role) string {
+ if role == nil || role.Name == nil {
+ return "—"
+ }
+ return *role.Name
+}
+
+func scopeLabel(perm *typescore.Permission) string {
+ if perm.Topic != nil && perm.Topic.Name != nil {
+ return "тему «" + *perm.Topic.Name + "»"
+ }
+ if perm.TopicCategory != nil && perm.TopicCategory.Name != nil {
+ return "категорию «" + *perm.TopicCategory.Name + "»"
+ }
+ return "все темы"
+}
+
+func (s *PermissionsReg) getCurrentAdmin(ctx context.Context) (*typescore.Admin, bool) {
+ currentUserID, err := handlers.GetIDFromContext(ctx)
+ if err != nil {
+ return nil, false
+ }
+
+ admins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{
+ Filtering: &typescore.Admin{ID: ¤tUserID},
+ })
+ if err != nil || len(admins) == 0 || admins[0] == nil || admins[0].ID == nil || admins[0].Login == nil {
+ return nil, false
+ }
+
+ return admins[0], true
+}
+
+-----END handlers/permission/handlers.go-----
+
+File: handlers/permission/routes.go
+Lines: 43
+-----BEGIN handlers/permission/routes.go-----
+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
+}
+
+-----END handlers/permission/routes.go-----
+
+File: handlers/profile/handlers.go
+Lines: 102
+-----BEGIN handlers/profile/handlers.go-----
+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
+}
+
+-----END handlers/profile/handlers.go-----
+
+File: handlers/profile/routes.go
+Lines: 36
+-----BEGIN handlers/profile/routes.go-----
+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
+}
+
+-----END handlers/profile/routes.go-----
+
+File: handlers/register.go
+Lines: 162
+-----BEGIN handlers/register.go-----
+package handlers
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "github.com/go-chi/chi/v5"
+ "io"
+ "net/http"
+ "strconv"
+)
+
+// ErrorResponse структура для возврата ошибок
+type ErrorResponse struct {
+ ErrorCode int `json:"error_code"`
+ ErrorDescription string `json:"error_description"`
+}
+
+// 🆕 ExcelFileResponse — специальный тип ответа для скачивания файлов
+type ExcelFileResponse struct {
+ Data []byte // Содержимое файла
+ FileName string // Имя файла для скачивания
+}
+
+// WrapHandlerParams структура для параметров обертки
+type WrapHandlerParams struct {
+ HandlerFunc func(http.ResponseWriter, *http.Request) (interface{}, error)
+}
+
+// responseWriterWrapper предотвращает повторный вызов WriteHeader
+type responseWriterWrapper struct {
+ http.ResponseWriter
+ wroteHeader bool
+}
+
+func (rw *responseWriterWrapper) WriteHeader(statusCode int) {
+ if !rw.wroteHeader {
+ rw.ResponseWriter.WriteHeader(statusCode)
+ rw.wroteHeader = true
+ }
+}
+
+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)
+
+ // 🆕 Проверяем, не файл ли это
+ if fileResp, ok := payload.(*ExcelFileResponse); ok && err == nil {
+ serveExcelFile(rw, fileResp)
+ return
+ }
+
+ // Обычный JSON ответ
+ respondWithJSON(rw, err, payload)
+ }
+}
+
+// 🆕 serveExcelFile отправляет файл как бинарный ответ
+func serveExcelFile(w http.ResponseWriter, fileResp *ExcelFileResponse) {
+ // Устанавливаем заголовки ДО отправки тела
+ w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
+ w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileResp.FileName))
+ w.Header().Set("Content-Length", strconv.Itoa(len(fileResp.Data)))
+ w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
+
+ w.WriteHeader(http.StatusOK)
+
+ // Отправляем содержимое файла
+ if _, err := w.Write(fileResp.Data); err != nil {
+ // Логируем ошибку, но заголовки уже отправлены
+ // Можно добавить логгер здесь
+ _ = err
+ }
+}
+
+// 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
+ }
+ }
+
+ if rw, ok := w.(*responseWriterWrapper); ok {
+ if !rw.wroteHeader {
+ rw.WriteHeader(status)
+ }
+ } else {
+ w.WriteHeader(status)
+ }
+
+ _, _ = w.Write(response)
+}
+
+-----END handlers/register.go-----
+
+File: handlers/roles/handlers.go
+Lines: 385
+-----BEGIN handlers/roles/handlers.go-----
+package roleshandler
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/core/utilscore"
+ "bitrix_balancer_api/rest_admin_service/handlers"
+ adminloghandler "bitrix_balancer_api/rest_admin_service/handlers/admin_actions"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "github.com/sirupsen/logrus"
+ "io"
+ "net/http"
+ "strconv"
+ "strings"
+
+ "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 := r.Context()
+ 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 := r.Context()
+ 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 := r.Context()
+ 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
+ }
+
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ snapshot := map[string]interface{}{
+ "name": utilscore.DerefStr(createdRole.Name),
+ "code": utilscore.DerefStr(createdRole.Code),
+ "is_default": utilscore.DerefBool(createdRole.IsDefault),
+ "is_director": utilscore.DerefBool(createdRole.IsDirector),
+ "is_approver": utilscore.DerefBool(createdRole.IsApprover),
+ "is_observer": utilscore.DerefBool(createdRole.IsObserver),
+ "is_executor": utilscore.DerefBool(createdRole.IsExecutor),
+ }
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "create", "role", createdRole.ID,
+ fmt.Sprintf("Создана роль «%s»", utilscore.DerefStr(createdRole.Name)),
+ map[string]interface{}{"snapshot": snapshot},
+ )
+ }
+
+ 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 := r.Context()
+ 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")
+ }
+ }
+ }
+
+ type fieldChange struct {
+ Field string `json:"field"`
+ Old interface{} `json:"old"`
+ New interface{} `json:"new"`
+ }
+ var changes []fieldChange
+ var summary []string
+
+ if req.Name != nil && !utilscore.StrEq(existingRole.Name, req.Name) {
+ changes = append(changes, fieldChange{"name", utilscore.DerefStr(existingRole.Name), *req.Name})
+ summary = append(summary, fmt.Sprintf("название: «%s» → «%s»", utilscore.DerefStr(existingRole.Name), *req.Name))
+ }
+ if req.Code != nil && !utilscore.StrEq(existingRole.Code, req.Code) {
+ changes = append(changes, fieldChange{"code", utilscore.DerefStr(existingRole.Code), *req.Code})
+ summary = append(summary, fmt.Sprintf("код: «%s» → «%s»", utilscore.DerefStr(existingRole.Code), *req.Code))
+ }
+
+ boolFields := []struct {
+ name string
+ old *bool
+ new *bool
+ flag string
+ }{
+ {"is_default", existingRole.IsDefault, req.IsDefault, "по умолчанию"},
+ {"is_director", existingRole.IsDirector, req.IsDirector, "директор"},
+ {"is_approver", existingRole.IsApprover, req.IsApprover, "согласующий"},
+ {"is_observer", existingRole.IsObserver, req.IsObserver, "наблюдатель"},
+ {"is_executor", existingRole.IsExecutor, req.IsExecutor, "исполнитель"},
+ }
+ for _, f := range boolFields {
+ if f.new != nil && !utilscore.BoolEq(f.old, f.new) {
+ changes = append(changes, fieldChange{f.name, utilscore.DerefBool(f.old), *f.new})
+ if *f.new {
+ summary = append(summary, fmt.Sprintf("включён флаг «%s»", f.flag))
+ } else {
+ summary = append(summary, fmt.Sprintf("выключен флаг «%s»", f.flag))
+ }
+ }
+ }
+
+ updatedRole, _, err := s.ipc.Database.Role.UpdateRoleDB(ctx, nil, &req, true)
+ if err != nil {
+ return nil, err
+ }
+
+ if len(changes) > 0 {
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ description := fmt.Sprintf("Изменена роль «%s»: %s", utilscore.DerefStr(existingRole.Name), strings.Join(summary, "; "))
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "update", "role", req.ID,
+ description,
+ map[string]interface{}{"changes": changes},
+ )
+ }
+ }
+
+ 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 := r.Context()
+ 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
+ }
+
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ snapshot := map[string]interface{}{
+ "name": utilscore.DerefStr(existingRole.Name),
+ "code": utilscore.DerefStr(existingRole.Code),
+ "is_director": utilscore.DerefBool(existingRole.IsDirector),
+ "is_approver": utilscore.DerefBool(existingRole.IsApprover),
+ "is_observer": utilscore.DerefBool(existingRole.IsObserver),
+ "is_executor": utilscore.DerefBool(existingRole.IsExecutor),
+ }
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "delete", "role", req.ID,
+ fmt.Sprintf("Удалена роль «%s»", utilscore.DerefStr(existingRole.Name)),
+ map[string]interface{}{"snapshot": snapshot},
+ )
+ }
+
+ return true, nil
+}
+
+func (s *RolesReg) getCurrentAdmin(ctx context.Context) (*typescore.Admin, bool) {
+ currentUserID, err := handlers.GetIDFromContext(ctx)
+ if err != nil {
+ return nil, false
+ }
+
+ admins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{
+ Filtering: &typescore.Admin{ID: ¤tUserID},
+ })
+ if err != nil || len(admins) == 0 || admins[0] == nil || admins[0].ID == nil || admins[0].Login == nil {
+ return nil, false
+ }
+
+ return admins[0], true
+}
+
+-----END handlers/roles/handlers.go-----
+
+File: handlers/roles/routes.go
+Lines: 39
+-----BEGIN handlers/roles/routes.go-----
+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
+}
+
+-----END handlers/roles/routes.go-----
+
+File: handlers/system_monitoring/handlers.go
+Lines: 259
+-----BEGIN handlers/system_monitoring/handlers.go-----
+package monitoringhandler
+
+import (
+ "bitrix_balancer_api/rest_admin_service/handlers"
+ typesm "bitrix_balancer_api/rest_admin_service/types"
+ "context"
+ "net/http"
+ "os"
+ "os/exec"
+ "strconv"
+ "strings"
+ "syscall"
+ "time"
+
+ "github.com/go-chi/chi/v5"
+)
+
+type MonitoringReg struct {
+ ipc *typesm.InternalProviderControl
+ // 🆕 ВАЖНО: впишите реальные имена systemd-юнитов ваших сервисов —
+ // я не знаю точных названий, использовал правдоподобные заглушки.
+ // Узнать реальные: `systemctl list-units --type=service | grep -i bitrix`
+ // (или как вы их называли при настройке systemd-юнитов).
+ monitoredUnits []monitoredUnit
+}
+
+type monitoredUnit struct {
+ Label string // как показывать в интерфейсе
+ Unit string // реальное имя systemd-юнита, например "bitrix-bot.service"
+}
+
+func RegisterMonitoringRoutes(r chi.Router, ipc *typesm.InternalProviderControl) error {
+ s := &MonitoringReg{
+ ipc: ipc,
+ monitoredUnits: []monitoredUnit{
+ {Label: "Telegram-бот", Unit: "bitrix-telegram-bot.service"},
+ {Label: "Admin REST API", Unit: "bitrix-rest-admin.service"},
+ {Label: "nginx", Unit: "nginx.service"},
+ {Label: "PostgreSQL", Unit: "postgresql.service"},
+ {Label: "Redis", Unit: "redis-server.service"},
+ },
+ }
+
+ r.Route("/api/monitoring", 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.GetMonitoringStatusHandler)
+ })
+
+ return nil
+}
+
+func (s *MonitoringReg) GetMonitoringStatusHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ ctx := r.Context()
+
+ services := make([]map[string]interface{}, 0, len(s.monitoredUnits))
+ for _, u := range s.monitoredUnits {
+ services = append(services, s.checkSystemdUnit(u))
+ }
+
+ resources := getHostResources()
+
+ dbHealthy, dbLatencyMs := s.checkDatabase(ctx)
+ redisHealthy, redisLatencyMs := s.checkRedis(ctx)
+
+ return map[string]interface{}{
+ "services": services,
+ "resources": resources,
+ "health": map[string]interface{}{
+ "database": map[string]interface{}{
+ "healthy": dbHealthy,
+ "latency_ms": dbLatencyMs,
+ },
+ "redis": map[string]interface{}{
+ "healthy": redisHealthy,
+ "latency_ms": redisLatencyMs,
+ },
+ },
+ "checked_at": time.Now().Format(time.RFC3339),
+ }, nil
+}
+
+func (s *MonitoringReg) checkSystemdUnit(u monitoredUnit) map[string]interface{} {
+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
+ defer cancel()
+
+ cmd := exec.CommandContext(ctx, "systemctl", "show", u.Unit,
+ "--property=ActiveState,SubState,ActiveEnterTimestamp", "--value")
+ output, err := cmd.Output()
+
+ result := map[string]interface{}{
+ "label": u.Label,
+ "unit": u.Unit,
+ }
+
+ if err != nil {
+ result["active"] = false
+ result["state"] = "unknown"
+ result["error"] = "не удалось получить статус (юнит не найден или нет прав)"
+ return result
+ }
+
+ lines := strings.Split(strings.TrimSpace(string(output)), "\n")
+ activeState := ""
+ subState := ""
+ since := ""
+ if len(lines) >= 1 {
+ activeState = strings.TrimSpace(lines[0])
+ }
+ if len(lines) >= 2 {
+ subState = strings.TrimSpace(lines[1])
+ }
+ if len(lines) >= 3 {
+ since = strings.TrimSpace(lines[2])
+ }
+
+ result["active"] = activeState == "active"
+ result["state"] = activeState + "/" + subState
+ if since != "" {
+ result["since"] = since
+ }
+
+ return result
+}
+
+func getHostResources() map[string]interface{} {
+ return map[string]interface{}{
+ "load_average": getLoadAverage(),
+ "memory": getMemoryInfo(),
+ "disk": getDiskInfo("/"),
+ "uptime_seconds": getUptimeSeconds(),
+ }
+}
+
+// getLoadAverage — /proc/loadavg: "0.52 0.58 0.59 1/234 5678"
+func getLoadAverage() map[string]interface{} {
+ data, err := readFile("/proc/loadavg")
+ if err != nil {
+ return map[string]interface{}{"error": "недоступно"}
+ }
+ fields := strings.Fields(data)
+ if len(fields) < 3 {
+ return map[string]interface{}{"error": "не удалось разобрать"}
+ }
+ l1, _ := strconv.ParseFloat(fields[0], 64)
+ l5, _ := strconv.ParseFloat(fields[1], 64)
+ l15, _ := strconv.ParseFloat(fields[2], 64)
+ return map[string]interface{}{"1m": l1, "5m": l5, "15m": l15}
+}
+
+// getMemoryInfo — /proc/meminfo, ключевые поля в килобайтах у ядра
+func getMemoryInfo() map[string]interface{} {
+ data, err := readFile("/proc/meminfo")
+ if err != nil {
+ return map[string]interface{}{"error": "недоступно"}
+ }
+
+ values := map[string]uint64{}
+ for _, line := range strings.Split(data, "\n") {
+ parts := strings.Fields(line)
+ if len(parts) < 2 {
+ continue
+ }
+ key := strings.TrimSuffix(parts[0], ":")
+ val, err := strconv.ParseUint(parts[1], 10, 64)
+ if err != nil {
+ continue
+ }
+ values[key] = val * 1024 // kB -> bytes
+ }
+
+ total := values["MemTotal"]
+ available := values["MemAvailable"]
+ used := uint64(0)
+ if total > available {
+ used = total - available
+ }
+
+ percent := 0.0
+ if total > 0 {
+ percent = float64(used) / float64(total) * 100
+ }
+
+ return map[string]interface{}{
+ "total_bytes": total,
+ "used_bytes": used,
+ "available_bytes": available,
+ "used_percent": percent,
+ }
+}
+
+// getDiskInfo — syscall.Statfs по корневой ФС (Linux)
+func getDiskInfo(path string) map[string]interface{} {
+ var stat syscall.Statfs_t
+ if err := syscall.Statfs(path, &stat); err != nil {
+ return map[string]interface{}{"error": "недоступно"}
+ }
+
+ total := stat.Blocks * uint64(stat.Bsize)
+ free := stat.Bavail * uint64(stat.Bsize)
+ used := total - free
+
+ percent := 0.0
+ if total > 0 {
+ percent = float64(used) / float64(total) * 100
+ }
+
+ return map[string]interface{}{
+ "path": path,
+ "total_bytes": total,
+ "used_bytes": used,
+ "free_bytes": free,
+ "used_percent": percent,
+ }
+}
+
+func getUptimeSeconds() float64 {
+ data, err := readFile("/proc/uptime")
+ if err != nil {
+ return 0
+ }
+ fields := strings.Fields(data)
+ if len(fields) < 1 {
+ return 0
+ }
+ seconds, _ := strconv.ParseFloat(fields[0], 64)
+ return seconds
+}
+
+func (s *MonitoringReg) checkDatabase(ctx context.Context) (bool, int64) {
+ start := time.Now()
+ timeoutCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
+ defer cancel()
+
+ _, _, err := s.ipc.Database.User.GetUsersListDB(timeoutCtx)
+ latency := time.Since(start).Milliseconds()
+
+ return err == nil, latency
+}
+
+func (s *MonitoringReg) checkRedis(ctx context.Context) (bool, int64) {
+ start := time.Now()
+ timeoutCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
+ defer cancel()
+
+ err := s.ipc.RedisClient.RedisClient.Ping(timeoutCtx)
+ latency := time.Since(start).Milliseconds()
+
+ return err == nil, latency
+}
+
+func readFile(path string) (string, error) {
+ data, err := os.ReadFile(path)
+ if err != nil {
+ return "", err
+ }
+ return string(data), nil
+}
+
+-----END handlers/system_monitoring/handlers.go-----
+
+File: handlers/topic_categories/handlers.go
+Lines: 361
+-----BEGIN handlers/topic_categories/handlers.go-----
+package categorieshandler
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/core/utilscore"
+ "bitrix_balancer_api/rest_admin_service/handlers"
+ adminloghandler "bitrix_balancer_api/rest_admin_service/handlers/admin_actions"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "github.com/sirupsen/logrus"
+ "io"
+ "net/http"
+ "strconv"
+ "strings"
+
+ "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 := r.Context()
+ 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 := r.Context()
+ 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 := r.Context()
+ 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")
+ }
+
+ 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
+ }
+
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ snapshot := map[string]interface{}{
+ "name": utilscore.DerefStr(createdCategory.Name),
+ "code": utilscore.DerefStr(createdCategory.Code),
+ "is_active": utilscore.DerefBool(createdCategory.IsActive),
+ }
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "create", "category", createdCategory.ID,
+ fmt.Sprintf("Создана категория «%s»", utilscore.DerefStr(createdCategory.Name)),
+ map[string]interface{}{"snapshot": snapshot},
+ )
+ }
+
+ 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 := r.Context()
+ 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")
+ }
+ }
+ }
+
+ type fieldChange struct {
+ Field string `json:"field"`
+ Old interface{} `json:"old"`
+ New interface{} `json:"new"`
+ }
+ var changes []fieldChange
+ var summary []string
+
+ if req.Name != nil && !utilscore.StrEq(existingCategory.Name, req.Name) {
+ changes = append(changes, fieldChange{"name", utilscore.DerefStr(existingCategory.Name), *req.Name})
+ summary = append(summary, fmt.Sprintf("название: «%s» → «%s»", utilscore.DerefStr(existingCategory.Name), *req.Name))
+ }
+ if req.Code != nil && !utilscore.StrEq(existingCategory.Code, req.Code) {
+ changes = append(changes, fieldChange{"code", utilscore.DerefStr(existingCategory.Code), *req.Code})
+ summary = append(summary, fmt.Sprintf("код: «%s» → «%s»", utilscore.DerefStr(existingCategory.Code), *req.Code))
+ }
+ if req.IsActive != nil && !utilscore.BoolEq(existingCategory.IsActive, req.IsActive) {
+ changes = append(changes, fieldChange{"is_active", utilscore.DerefBool(existingCategory.IsActive), *req.IsActive})
+ if *req.IsActive {
+ summary = append(summary, "активирована")
+ } else {
+ summary = append(summary, "деактивирована")
+ }
+ }
+
+ updatedCategory, _, err := s.ipc.Database.ApprovalTopicCategory.UpdateApprovalTopicCategoryDB(ctx, nil, &req, true)
+ if err != nil {
+ return nil, err
+ }
+
+ if len(changes) > 0 {
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ description := fmt.Sprintf("Изменена категория «%s»: %s", utilscore.DerefStr(existingCategory.Name), strings.Join(summary, "; "))
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "update", "category", req.ID,
+ description,
+ map[string]interface{}{"changes": changes},
+ )
+ }
+ }
+
+ 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 := r.Context()
+ 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
+ }
+
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ snapshot := map[string]interface{}{
+ "name": utilscore.DerefStr(existingCategory.Name),
+ "code": utilscore.DerefStr(existingCategory.Code),
+ }
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "delete", "category", req.ID,
+ fmt.Sprintf("Удалена категория «%s»", utilscore.DerefStr(existingCategory.Name)),
+ map[string]interface{}{"snapshot": snapshot},
+ )
+ }
+
+ return true, nil
+}
+
+func (s *CategoriesReg) getCurrentAdmin(ctx context.Context) (*typescore.Admin, bool) {
+ currentUserID, err := handlers.GetIDFromContext(ctx)
+ if err != nil {
+ return nil, false
+ }
+
+ admins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{
+ Filtering: &typescore.Admin{ID: ¤tUserID},
+ })
+ if err != nil || len(admins) == 0 || admins[0] == nil || admins[0].ID == nil || admins[0].Login == nil {
+ return nil, false
+ }
+
+ return admins[0], true
+}
+
+-----END handlers/topic_categories/handlers.go-----
+
+File: handlers/topic_categories/routes.go
+Lines: 39
+-----BEGIN handlers/topic_categories/routes.go-----
+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
+}
+
+-----END handlers/topic_categories/routes.go-----
+
+File: handlers/topic_executors/handlers.go
+Lines: 603
+-----BEGIN handlers/topic_executors/handlers.go-----
+package topicexecutorshandler
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/core/utilscore"
+ "bitrix_balancer_api/rest_admin_service/handlers"
+ adminloghandler "bitrix_balancer_api/rest_admin_service/handlers/admin_actions"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "github.com/go-chi/chi/v5"
+ "github.com/sirupsen/logrus"
+ "io"
+ "net/http"
+ "strconv"
+ "strings"
+)
+
+// 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 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/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
+ }
+
+ var categoryID *uint64
+ if categoryIDStr := queryParams.Get("category_id"); categoryIDStr != "" {
+ if id, err := strconv.ParseUint(categoryIDStr, 10, 64); err == nil {
+ categoryID = &id
+ }
+ }
+
+ options := typescore.ListDbOptions{
+ Filtering: executorParams,
+ Offset: offset,
+ Limit: limit,
+ LikeFields: likeFields,
+ }
+
+ ctx := r.Context()
+
+ var executorsDbLst []*typescore.ApprovalTopicExecutor
+ var total uint64
+ var err error
+
+ if categoryID != nil {
+ executorsDbLst, total, err = s.ipc.Database.ApprovalTopicExecutor.GetApprovalTopicExecutorListByCategoryDB(ctx, options, *categoryID)
+ } else {
+ executorsDbLst, total, err = s.ipc.Database.ApprovalTopicExecutor.GetApprovalTopicExecutorListDB(ctx, options)
+ }
+
+ if err != nil {
+ return nil, err
+ }
+
+ s.enrichExecutorsBatch(ctx, executorsDbLst)
+
+ return &typescore.ApiResponseBase{
+ TotalCount: total,
+ Data: executorsDbLst,
+ }, 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 := r.Context()
+
+ 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
+ }
+
+ s.enrichExecutorsBatch(ctx, executors)
+
+ return &typescore.ApiResponseBase{
+ TotalCount: uint64(len(executors)),
+ Data: executors,
+ }, nil
+}
+
+// enrichExecutorsBatch пакетно подгружает темы и пользователей для списка исполнителей
+func (s *TopicExecutorsReg) enrichExecutorsBatch(ctx context.Context, executors []*typescore.ApprovalTopicExecutor) {
+ if len(executors) == 0 {
+ return
+ }
+
+ topicIDsSet := make(map[uint64]struct{})
+ userIDsSet := make(map[uint64]struct{})
+ for _, e := range executors {
+ if e.TopicID != nil {
+ topicIDsSet[*e.TopicID] = struct{}{}
+ }
+ if e.UserID != nil {
+ userIDsSet[*e.UserID] = struct{}{}
+ }
+ }
+
+ topicIDs := make([]uint64, 0, len(topicIDsSet))
+ for id := range topicIDsSet {
+ topicIDs = append(topicIDs, id)
+ }
+ userIDs := make([]uint64, 0, len(userIDsSet))
+ for id := range userIDsSet {
+ userIDs = append(userIDs, id)
+ }
+
+ topicsMap := make(map[uint64]*typescore.ApprovalTopic)
+ if topics, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicsByIDsDB(ctx, topicIDs); err == nil {
+ for _, t := range topics {
+ if t.ID != nil {
+ topicsMap[*t.ID] = t
+ }
+ }
+ }
+
+ usersMap := make(map[uint64]*typescore.User)
+ if users, err := s.ipc.Database.User.GetUsersByIDsDB(ctx, userIDs); err == nil {
+ for _, u := range users {
+ if u.ID != nil {
+ usersMap[*u.ID] = u
+ }
+ }
+ }
+
+ for _, e := range executors {
+ if e.TopicID != nil {
+ if t, ok := topicsMap[*e.TopicID]; ok {
+ e.Topic = t
+ }
+ }
+ if e.UserID != nil {
+ if u, ok := usersMap[*e.UserID]; ok {
+ e.User = u
+ }
+ }
+ }
+}
+
+// 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 := r.Context()
+ 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
+}
+
+// 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 := r.Context()
+
+ 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)
+
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ snapshot := map[string]interface{}{
+ "topic_id": *req.TopicID,
+ "user_id": *req.UserID,
+ "step_order": utilscore.DerefInt(createdExecutor.StepOrder),
+ "require_file": utilscore.DerefBool(createdExecutor.RequireFile),
+ "is_active": utilscore.DerefBool(createdExecutor.IsActive),
+ }
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "create", "topic_executor", createdExecutor.ID,
+ fmt.Sprintf("Назначен исполнитель «%s» на тему «%s»", userLabel(createdExecutor.User), topicLabel(createdExecutor.Topic)),
+ map[string]interface{}{"snapshot": snapshot},
+ )
+ }
+
+ 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 := r.Context()
+
+ 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]
+ s.enrichExecutor(ctx, existing)
+
+ 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")
+ }
+ }
+ }
+
+ 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")
+ }
+ }
+ }
+
+ type fieldChange struct {
+ Field string `json:"field"`
+ Old interface{} `json:"old"`
+ New interface{} `json:"new"`
+ }
+ var changes []fieldChange
+ var summary []string
+
+ if req.UserID != nil && !utilscore.Uint64Eq(existing.UserID, req.UserID) {
+ var oldVal interface{}
+ if existing.UserID != nil {
+ oldVal = *existing.UserID
+ }
+ changes = append(changes, fieldChange{"user_id", oldVal, *req.UserID})
+ summary = append(summary, "заменён исполнитель")
+ }
+ if req.StepOrder != nil && !utilscore.IntEq(existing.StepOrder, req.StepOrder) {
+ var oldVal interface{}
+ if existing.StepOrder != nil {
+ oldVal = *existing.StepOrder
+ }
+ changes = append(changes, fieldChange{"step_order", oldVal, *req.StepOrder})
+ summary = append(summary, fmt.Sprintf("порядок шага: %v → %d", oldVal, *req.StepOrder))
+ }
+ if req.RequireFile != nil && !utilscore.BoolEq(existing.RequireFile, req.RequireFile) {
+ changes = append(changes, fieldChange{"require_file", utilscore.DerefBool(existing.RequireFile), *req.RequireFile})
+ if *req.RequireFile {
+ summary = append(summary, "включено обязательное вложение файла")
+ } else {
+ summary = append(summary, "отключено обязательное вложение файла")
+ }
+ }
+ if req.IsActive != nil && !utilscore.BoolEq(existing.IsActive, req.IsActive) {
+ changes = append(changes, fieldChange{"is_active", utilscore.DerefBool(existing.IsActive), *req.IsActive})
+ if *req.IsActive {
+ summary = append(summary, "активирован")
+ } else {
+ summary = append(summary, "деактивирован")
+ }
+ }
+
+ updatedExecutor, _, err := s.ipc.Database.ApprovalTopicExecutor.UpdateApprovalTopicExecutorDB(ctx, nil, &req, true)
+ if err != nil {
+ return nil, err
+ }
+
+ s.enrichExecutor(ctx, updatedExecutor)
+
+ if len(changes) > 0 {
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ description := fmt.Sprintf("Изменён исполнитель темы «%s»: %s", topicLabel(existing.Topic), strings.Join(summary, "; "))
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "update", "topic_executor", req.ID,
+ description,
+ map[string]interface{}{"changes": changes},
+ )
+ }
+ }
+
+ 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 := r.Context()
+
+ 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]
+ s.enrichExecutor(ctx, existing)
+
+ err = s.ipc.Database.ApprovalTopicExecutor.DeleteApprovalTopicExecutorDB(ctx, &req)
+ if err != nil {
+ return nil, err
+ }
+
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ snapshot := map[string]interface{}{
+ "step_order": utilscore.DerefInt(existing.StepOrder),
+ "require_file": utilscore.DerefBool(existing.RequireFile),
+ }
+ if existing.TopicID != nil {
+ snapshot["topic_id"] = *existing.TopicID
+ }
+ if existing.UserID != nil {
+ snapshot["user_id"] = *existing.UserID
+ }
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "delete", "topic_executor", req.ID,
+ fmt.Sprintf("Снят исполнитель «%s» с темы «%s»", userLabel(existing.User), topicLabel(existing.Topic)),
+ map[string]interface{}{"snapshot": snapshot},
+ )
+ }
+
+ 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
+ }
+ }
+}
+
+func topicLabel(topic *typescore.ApprovalTopic) string {
+ if topic == nil || topic.Name == nil {
+ return "—"
+ }
+ return *topic.Name
+}
+
+func userLabel(user *typescore.User) string {
+ if user == nil || user.FullName == nil {
+ return "—"
+ }
+ return *user.FullName
+}
+
+func (s *TopicExecutorsReg) getCurrentAdmin(ctx context.Context) (*typescore.Admin, bool) {
+ currentUserID, err := handlers.GetIDFromContext(ctx)
+ if err != nil {
+ return nil, false
+ }
+
+ admins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{
+ Filtering: &typescore.Admin{ID: ¤tUserID},
+ })
+ if err != nil || len(admins) == 0 || admins[0] == nil || admins[0].ID == nil || admins[0].Login == nil {
+ return nil, false
+ }
+
+ return admins[0], true
+}
+
+-----END handlers/topic_executors/handlers.go-----
+
+File: handlers/topic_executors/routes.go
+Lines: 43
+-----BEGIN handlers/topic_executors/routes.go-----
+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
+}
+
+-----END handlers/topic_executors/routes.go-----
+
+File: handlers/topics/handlers.go
+Lines: 519
+-----BEGIN handlers/topics/handlers.go-----
+package topicshandler
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/core/utilscore"
+ "bitrix_balancer_api/rest_admin_service/handlers"
+ adminloghandler "bitrix_balancer_api/rest_admin_service/handlers/admin_actions"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "github.com/sirupsen/logrus"
+ "io"
+ "net/http"
+ "strconv"
+ "strings"
+
+ "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 := r.Context()
+ topicsDbLst, total, errW := s.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, options)
+ if errW != nil {
+ return nil, errW
+ }
+
+ categoryIDsSet := make(map[uint64]struct{})
+ for _, topic := range topicsDbLst {
+ if topic.CategoryID != nil {
+ categoryIDsSet[*topic.CategoryID] = struct{}{}
+ }
+ }
+ categoryIDs := make([]uint64, 0, len(categoryIDsSet))
+ for id := range categoryIDsSet {
+ categoryIDs = append(categoryIDs, id)
+ }
+
+ categoriesMap := make(map[uint64]*typescore.ApprovalTopicCategory)
+ if categories, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoriesByIDsDB(ctx, categoryIDs); err == nil {
+ for _, c := range categories {
+ if c.ID != nil {
+ categoriesMap[*c.ID] = c
+ }
+ }
+ }
+
+ for _, topic := range topicsDbLst {
+ if topic.CategoryID != nil {
+ if cat, ok := categoriesMap[*topic.CategoryID]; ok {
+ topic.Category = cat
+ }
+ }
+ }
+
+ 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 := r.Context()
+ 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 := r.Context()
+ 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
+ }
+ }
+
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ snapshot := map[string]interface{}{
+ "name": utilscore.DerefStr(createdTopic.Name),
+ "code": utilscore.DerefStr(createdTopic.Code),
+ "category_id": *req.CategoryID,
+ "approval_mode": utilscore.DerefStr(createdTopic.ApprovalMode),
+ "allows_file": utilscore.DerefBool(createdTopic.AllowsFile),
+ "requires_file": utilscore.DerefBool(createdTopic.RequiresFile),
+ "allow_approver_selection": utilscore.DerefBool(createdTopic.AllowApproverSelection),
+ "allow_observer_selection": utilscore.DerefBool(createdTopic.AllowObserverSelection),
+ "require_observer_selection": utilscore.DerefBool(createdTopic.RequireObserverSelection),
+ "require_approver_comment": utilscore.DerefBool(createdTopic.RequireApproverComment),
+ "is_active": utilscore.DerefBool(createdTopic.IsActive),
+ }
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "create", "topic", createdTopic.ID,
+ fmt.Sprintf("Создана тема «%s» (%s)", utilscore.DerefStr(createdTopic.Name), categoryLabel(createdTopic.Category)),
+ map[string]interface{}{"snapshot": snapshot},
+ )
+ }
+
+ 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 := r.Context()
+ 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")
+ }
+
+ 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")
+ }
+ }
+ }
+
+ type fieldChange struct {
+ Field string `json:"field"`
+ Old interface{} `json:"old"`
+ New interface{} `json:"new"`
+ }
+ var changes []fieldChange
+ var summary []string
+
+ strFields := []struct {
+ name string
+ old *string
+ new *string
+ label string
+ }{
+ {"name", existingTopic.Name, req.Name, "название"},
+ {"code", existingTopic.Code, req.Code, "код"},
+ {"approval_mode", existingTopic.ApprovalMode, req.ApprovalMode, "режим согласования"},
+ {"duration_type", existingTopic.DurationType, req.DurationType, "тип длительности"},
+ {"time_type", existingTopic.TimeType, req.TimeType, "тип времени"},
+ {"payment_type", existingTopic.PaymentType, req.PaymentType, "тип оплаты"},
+ {"first_approver_role_code", existingTopic.FirstApproverRoleCode, req.FirstApproverRoleCode, "роль первого согласующего"},
+ }
+ for _, f := range strFields {
+ if f.new != nil && !utilscore.StrEq(f.old, f.new) {
+ changes = append(changes, fieldChange{f.name, utilscore.DerefStr(f.old), *f.new})
+ summary = append(summary, fmt.Sprintf("%s: «%s» → «%s»", f.label, utilscore.DerefStr(f.old), *f.new))
+ }
+ }
+
+ boolFields := []struct {
+ name string
+ old *bool
+ new *bool
+ label string
+ }{
+ {"is_active", existingTopic.IsActive, req.IsActive, "активна"},
+ {"allows_file", existingTopic.AllowsFile, req.AllowsFile, "разрешён файл"},
+ {"requires_file", existingTopic.RequiresFile, req.RequiresFile, "обязателен файл"},
+ {"allow_approver_selection", existingTopic.AllowApproverSelection, req.AllowApproverSelection, "выбор согласующего"},
+ {"allow_observer_selection", existingTopic.AllowObserverSelection, req.AllowObserverSelection, "выбор наблюдателя"},
+ {"require_observer_selection", existingTopic.RequireObserverSelection, req.RequireObserverSelection, "наблюдатель обязателен"},
+ {"require_approver_comment", existingTopic.RequireApproverComment, req.RequireApproverComment, "комментарий обязателен"},
+ {"allow_delegation_selection", existingTopic.AllowDelegationSelection, req.AllowDelegationSelection, "делегирование обязанностей"},
+ }
+ for _, f := range boolFields {
+ if f.new != nil && !utilscore.BoolEq(f.old, f.new) {
+ changes = append(changes, fieldChange{f.name, utilscore.DerefBool(f.old), *f.new})
+ if *f.new {
+ summary = append(summary, fmt.Sprintf("включено «%s»", f.label))
+ } else {
+ summary = append(summary, fmt.Sprintf("выключено «%s»", f.label))
+ }
+ }
+ }
+
+ if req.CategoryID != nil && !utilscore.Uint64Eq(existingTopic.CategoryID, req.CategoryID) {
+ var oldVal interface{}
+ if existingTopic.CategoryID != nil {
+ oldVal = *existingTopic.CategoryID
+ }
+ changes = append(changes, fieldChange{"category_id", oldVal, *req.CategoryID})
+ summary = append(summary, "изменена категория")
+ }
+
+ 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
+ }
+ }
+
+ if len(changes) > 0 {
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ description := fmt.Sprintf("Изменена тема «%s»: %s", utilscore.DerefStr(existingTopic.Name), strings.Join(summary, "; "))
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "update", "topic", req.ID,
+ description,
+ map[string]interface{}{"changes": changes},
+ )
+ }
+ }
+
+ 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 := r.Context()
+ 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")
+ }
+
+ if existingTopic.CategoryID != nil {
+ category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *existingTopic.CategoryID)
+ if err == nil && category != nil {
+ existingTopic.Category = category
+ }
+ }
+
+ err = s.ipc.Database.ApprovalTopic.DeleteApprovalTopicDB(ctx, &req)
+ if err != nil {
+ return nil, err
+ }
+
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ snapshot := map[string]interface{}{
+ "name": utilscore.DerefStr(existingTopic.Name),
+ "code": utilscore.DerefStr(existingTopic.Code),
+ }
+ if existingTopic.CategoryID != nil {
+ snapshot["category_id"] = *existingTopic.CategoryID
+ }
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "delete", "topic", req.ID,
+ fmt.Sprintf("Удалена тема «%s» (%s)", utilscore.DerefStr(existingTopic.Name), categoryLabel(existingTopic.Category)),
+ map[string]interface{}{"snapshot": snapshot},
+ )
+ }
+
+ return true, nil
+}
+
+func categoryLabel(category *typescore.ApprovalTopicCategory) string {
+ if category == nil || category.Name == nil {
+ return "—"
+ }
+ return *category.Name
+}
+
+func (s *TopicsReg) getCurrentAdmin(ctx context.Context) (*typescore.Admin, bool) {
+ currentUserID, err := handlers.GetIDFromContext(ctx)
+ if err != nil {
+ return nil, false
+ }
+
+ admins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{
+ Filtering: &typescore.Admin{ID: ¤tUserID},
+ })
+ if err != nil || len(admins) == 0 || admins[0] == nil || admins[0].ID == nil || admins[0].Login == nil {
+ return nil, false
+ }
+
+ return admins[0], true
+}
+
+-----END handlers/topics/handlers.go-----
+
+File: handlers/topics/routes.go
+Lines: 39
+-----BEGIN handlers/topics/routes.go-----
+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
+}
+
+-----END handlers/topics/routes.go-----
+
+File: handlers/user_hierarchy/handlers.go
+Lines: 531
+-----BEGIN handlers/user_hierarchy/handlers.go-----
+package hierarchieshandler
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/core/utilscore"
+ "bitrix_balancer_api/rest_admin_service/handlers"
+ adminloghandler "bitrix_balancer_api/rest_admin_service/handlers/admin_actions"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "github.com/sirupsen/logrus"
+ "io"
+ "net/http"
+ "strconv"
+ "strings"
+
+ "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 := r.Context()
+ hierarchiesDbLst, total, errW := s.ipc.Database.UserHierarchy.GetHierarchiesWithRelations(ctx, options)
+ if errW != nil {
+ return nil, errW
+ }
+
+ 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 := r.Context()
+ hierarchies, _, err := s.ipc.Database.UserHierarchy.GetHierarchiesWithRelations(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]
+ 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 := r.Context()
+
+ 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,
+ TargetSystem: req.TargetSystem,
+ },
+ })
+ if err != nil {
+ return nil, err
+ }
+ if len(existingHierarchies) > 0 {
+ return nil, errors.New("this hierarchy relation already exists")
+ }
+
+ 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
+ }
+
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ snapshot := map[string]interface{}{
+ "subordinate_id": *req.SubordinateID,
+ "approver_id": *req.ApproverID,
+ "department_id": *req.DepartmentID,
+ "priority": *req.Priority,
+ }
+ if req.TopicID != nil {
+ snapshot["topic_id"] = *req.TopicID
+ }
+ if req.TopicCategoryID != nil {
+ snapshot["topic_category_id"] = *req.TopicCategoryID
+ }
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "create", "hierarchy", createdHierarchy.ID,
+ fmt.Sprintf("Создана связь: «%s» → согласующий «%s» (%s)", userLabel(subordinate), userLabel(approver), utilscore.DerefStr(department.Name)),
+ map[string]interface{}{"snapshot": snapshot},
+ )
+ }
+
+ 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 := r.Context()
+
+ existingHierarchies, _, err := s.ipc.Database.UserHierarchy.GetHierarchiesWithRelations(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]
+
+ 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")
+ }
+ }
+ }
+
+ 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")
+ }
+ }
+ }
+
+ 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")
+ }
+ }
+ }
+
+ 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")
+ }
+ }
+ }
+
+ 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")
+ }
+ }
+ }
+
+ type fieldChange struct {
+ Field string `json:"field"`
+ Old interface{} `json:"old"`
+ New interface{} `json:"new"`
+ }
+ var changes []fieldChange
+ var summary []string
+
+ if req.SubordinateID != nil && !utilscore.Uint64Eq(existing.SubordinateID, req.SubordinateID) {
+ var oldVal interface{}
+ if existing.SubordinateID != nil {
+ oldVal = *existing.SubordinateID
+ }
+ changes = append(changes, fieldChange{"subordinate_id", oldVal, *req.SubordinateID})
+ summary = append(summary, "изменён подчинённый")
+ }
+ if req.ApproverID != nil && !utilscore.Uint64Eq(existing.ApproverID, req.ApproverID) {
+ var oldVal interface{}
+ if existing.ApproverID != nil {
+ oldVal = *existing.ApproverID
+ }
+ changes = append(changes, fieldChange{"approver_id", oldVal, *req.ApproverID})
+ summary = append(summary, "изменён согласующий")
+ }
+ if req.DepartmentID != nil && !utilscore.Uint64Eq(existing.DepartmentID, req.DepartmentID) {
+ var oldVal interface{}
+ if existing.DepartmentID != nil {
+ oldVal = *existing.DepartmentID
+ }
+ changes = append(changes, fieldChange{"department_id", oldVal, *req.DepartmentID})
+ summary = append(summary, "изменён отдел")
+ }
+ if req.TopicID != nil && !utilscore.Uint64Eq(existing.TopicID, req.TopicID) {
+ var oldVal interface{}
+ if existing.TopicID != nil {
+ oldVal = *existing.TopicID
+ }
+ changes = append(changes, fieldChange{"topic_id", oldVal, *req.TopicID})
+ summary = append(summary, "изменена тема")
+ }
+ if req.TopicCategoryID != nil && !utilscore.Uint64Eq(existing.TopicCategoryID, req.TopicCategoryID) {
+ var oldVal interface{}
+ if existing.TopicCategoryID != nil {
+ oldVal = *existing.TopicCategoryID
+ }
+ changes = append(changes, fieldChange{"topic_category_id", oldVal, *req.TopicCategoryID})
+ summary = append(summary, "изменена категория")
+ }
+ if req.Priority != nil && !utilscore.IntEq(existing.Priority, req.Priority) {
+ var oldVal interface{}
+ if existing.Priority != nil {
+ oldVal = *existing.Priority
+ }
+ changes = append(changes, fieldChange{"priority", oldVal, *req.Priority})
+ summary = append(summary, fmt.Sprintf("приоритет: %v → %d", oldVal, *req.Priority))
+ }
+
+ updatedHierarchy, _, err := s.ipc.Database.UserHierarchy.UpdateUserHierarchyDB(ctx, nil, &req, true)
+ if err != nil {
+ return nil, err
+ }
+
+ if len(changes) > 0 {
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ description := fmt.Sprintf("Изменена связь «%s» → «%s»: %s", userLabel(existing.Subordinate), userLabel(existing.Approver), strings.Join(summary, "; "))
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "update", "hierarchy", req.ID,
+ description,
+ map[string]interface{}{"changes": changes},
+ )
+ }
+ }
+
+ 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 := r.Context()
+
+ existingHierarchies, _, err := s.ipc.Database.UserHierarchy.GetHierarchiesWithRelations(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]
+
+ err = s.ipc.Database.UserHierarchy.DeleteUserHierarchyDB(ctx, &req)
+ if err != nil {
+ return nil, err
+ }
+
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ snapshot := map[string]interface{}{
+ "priority": utilscore.DerefInt(existing.Priority),
+ }
+ if existing.SubordinateID != nil {
+ snapshot["subordinate_id"] = *existing.SubordinateID
+ }
+ if existing.ApproverID != nil {
+ snapshot["approver_id"] = *existing.ApproverID
+ }
+ if existing.DepartmentID != nil {
+ snapshot["department_id"] = *existing.DepartmentID
+ }
+ if existing.TopicID != nil {
+ snapshot["topic_id"] = *existing.TopicID
+ }
+ if existing.TopicCategoryID != nil {
+ snapshot["topic_category_id"] = *existing.TopicCategoryID
+ }
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "delete", "hierarchy", req.ID,
+ fmt.Sprintf("Удалена связь: «%s» → согласующий «%s»", userLabel(existing.Subordinate), userLabel(existing.Approver)),
+ map[string]interface{}{"snapshot": snapshot},
+ )
+ }
+
+ return true, nil
+}
+
+func userLabel(user *typescore.User) string {
+ if user == nil || user.FullName == nil {
+ return "—"
+ }
+ return *user.FullName
+}
+
+func (s *HierarchiesReg) getCurrentAdmin(ctx context.Context) (*typescore.Admin, bool) {
+ currentUserID, err := handlers.GetIDFromContext(ctx)
+ if err != nil {
+ return nil, false
+ }
+
+ admins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{
+ Filtering: &typescore.Admin{ID: ¤tUserID},
+ })
+ if err != nil || len(admins) == 0 || admins[0] == nil || admins[0].ID == nil || admins[0].Login == nil {
+ return nil, false
+ }
+
+ return admins[0], true
+}
+
+-----END handlers/user_hierarchy/handlers.go-----
+
+File: handlers/user_hierarchy/routes.go
+Lines: 39
+-----BEGIN handlers/user_hierarchy/routes.go-----
+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
+}
+
+-----END handlers/user_hierarchy/routes.go-----
+
+File: handlers/user_roles/handlers.go
+Lines: 477
+-----BEGIN handlers/user_roles/handlers.go-----
+package userroleshandler
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/core/utilscore"
+ "bitrix_balancer_api/rest_admin_service/handlers"
+ adminloghandler "bitrix_balancer_api/rest_admin_service/handlers/admin_actions"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "github.com/sirupsen/logrus"
+ "io"
+ "net/http"
+ "strconv"
+ "strings"
+
+ "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
+ }
+
+ if roleParams.UserID == nil {
+ return nil, errors.New("user_id is required")
+ }
+
+ options := typescore.ListDbOptions{
+ Filtering: roleParams,
+ Offset: offset,
+ Limit: limit,
+ LikeFields: likeFields,
+ }
+
+ ctx := r.Context()
+ userRolesDbLst, total, errW := s.ipc.Database.UserRole.GetUserRolesListDB(ctx, options)
+ if errW != nil {
+ return nil, errW
+ }
+
+ s.enrichUserRolesBatch(ctx, userRolesDbLst)
+
+ 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 := r.Context()
+
+ 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
+ }
+
+ s.enrichUserRolesBatch(ctx, userRolesDbLst)
+
+ return &typescore.ApiResponseBase{
+ TotalCount: uint64(len(userRolesDbLst)),
+ Data: userRolesDbLst,
+ }, nil
+}
+
+// enrichUserRolesBatch пакетно подгружает роли для списка user_role
+func (s *UserRolesReg) enrichUserRolesBatch(ctx context.Context, userRoles []*typescore.UserRole) {
+ if len(userRoles) == 0 {
+ return
+ }
+
+ roleIDsSet := make(map[uint64]struct{})
+ for _, ur := range userRoles {
+ if ur.RoleID != nil {
+ roleIDsSet[*ur.RoleID] = struct{}{}
+ }
+ }
+
+ roleIDs := make([]uint64, 0, len(roleIDsSet))
+ for id := range roleIDsSet {
+ roleIDs = append(roleIDs, id)
+ }
+
+ rolesMap := make(map[uint64]*typescore.Role)
+ if roles, err := s.ipc.Database.Role.GetRolesByIDsDB(ctx, roleIDs); err == nil {
+ for _, role := range roles {
+ if role.ID != nil {
+ rolesMap[*role.ID] = role
+ }
+ }
+ }
+
+ for _, ur := range userRoles {
+ if ur.RoleID != nil {
+ if role, ok := rolesMap[*ur.RoleID]; ok {
+ ur.Role = role
+ }
+ }
+ }
+}
+
+// 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 := r.Context()
+
+ 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")
+ }
+
+ roleIDsSet := make(map[uint64]struct{})
+ roleIDs := make([]uint64, 0, len(req.RoleIDs))
+ for _, roleID := range req.RoleIDs {
+ if roleID == nil {
+ continue
+ }
+ if _, exists := roleIDsSet[*roleID]; exists {
+ continue
+ }
+ roleIDsSet[*roleID] = struct{}{}
+ roleIDs = append(roleIDs, *roleID)
+ }
+
+ if len(roleIDs) > 0 {
+ existingRoles, err := s.ipc.Database.Role.GetRolesByIDsDB(ctx, roleIDs)
+ if err != nil {
+ return nil, err
+ }
+ foundIDs := make(map[uint64]struct{}, len(existingRoles))
+ for _, role := range existingRoles {
+ if role.ID != nil {
+ foundIDs[*role.ID] = struct{}{}
+ }
+ }
+ for _, roleID := range roleIDs {
+ if _, ok := foundIDs[roleID]; !ok {
+ return nil, errors.New("role not found: " + strconv.FormatUint(roleID, 10))
+ }
+ }
+ }
+
+ // снимаем "было" до удаления — иначе после DeleteUserRolesByUserIDDB это уже не достать
+ previousRoles, _, _ := s.ipc.Database.UserRole.GetUserRolesListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.UserRole{UserID: req.UserID},
+ })
+ s.enrichUserRolesBatch(ctx, previousRoles)
+
+ if err := s.ipc.Database.UserRole.DeleteUserRolesByUserIDDB(ctx, *req.UserID); err != nil {
+ logrus.Errorf("BulkAssignRolesHandler: failed to delete user_roles for user_id=%d: %v", *req.UserID, err)
+ return nil, err
+ }
+
+ createdRoles, err := s.ipc.Database.UserRole.CreateUserRolesBulkDB(ctx, nil, *req.UserID, roleIDs)
+ if err != nil {
+ logrus.Errorf("BulkAssignRolesHandler: failed to bulk create user_roles: %v", err)
+ return nil, err
+ }
+
+ s.enrichUserRolesBatch(ctx, createdRoles)
+
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ oldNames := roleNames(previousRoles)
+ newNames := roleNames(createdRoles)
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "update", "user_roles", req.UserID,
+ fmt.Sprintf("Заменены роли «%s»: [%s] → [%s]", userLabel(user), strings.Join(oldNames, ", "), strings.Join(newNames, ", ")),
+ map[string]interface{}{
+ "user_id": *req.UserID,
+ "roles_before": oldNames,
+ "roles_after": newNames,
+ },
+ )
+ }
+
+ return &typescore.ApiResponseBase{
+ TotalCount: uint64(len(createdRoles)),
+ Data: createdRoles,
+ }, 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 := r.Context()
+
+ 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
+ }
+
+ createdUserRole.Role = role
+
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "create", "user_role", createdUserRole.ID,
+ fmt.Sprintf("Назначена роль «%s» пользователю «%s»", roleLabel(role), userLabel(user)),
+ map[string]interface{}{
+ "user_id": *req.UserID,
+ "role_id": *req.RoleID,
+ },
+ )
+ }
+
+ return createdUserRole, 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 := r.Context()
+
+ 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")
+ }
+ existing := existingRoles[0]
+ s.enrichUserRolesBatch(ctx, existingRoles)
+
+ var user *typescore.User
+ if existing.UserID != nil {
+ user, _ = s.ipc.Database.User.GetUserByIDDB(ctx, *existing.UserID)
+ }
+
+ err = s.ipc.Database.UserRole.DeleteUserRoleDB(ctx, &req)
+ if err != nil {
+ return nil, err
+ }
+
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ snapshot := map[string]interface{}{}
+ if existing.UserID != nil {
+ snapshot["user_id"] = *existing.UserID
+ }
+ if existing.RoleID != nil {
+ snapshot["role_id"] = *existing.RoleID
+ }
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "delete", "user_role", req.ID,
+ fmt.Sprintf("Снята роль «%s» с пользователя «%s»", roleLabel(existing.Role), userLabel(user)),
+ map[string]interface{}{"snapshot": snapshot},
+ )
+ }
+
+ return true, nil
+}
+
+func userLabel(user *typescore.User) string {
+ if user == nil || user.FullName == nil {
+ return "—"
+ }
+ return *user.FullName
+}
+
+func roleLabel(role *typescore.Role) string {
+ if role == nil || role.Name == nil {
+ return "—"
+ }
+ return *role.Name
+}
+
+func roleNames(userRoles []*typescore.UserRole) []string {
+ names := make([]string, 0, len(userRoles))
+ for _, ur := range userRoles {
+ names = append(names, roleLabel(ur.Role))
+ }
+ return names
+}
+
+func (s *UserRolesReg) getCurrentAdmin(ctx context.Context) (*typescore.Admin, bool) {
+ currentUserID, err := handlers.GetIDFromContext(ctx)
+ if err != nil {
+ return nil, false
+ }
+
+ admins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{
+ Filtering: &typescore.Admin{ID: ¤tUserID},
+ })
+ if err != nil || len(admins) == 0 || admins[0] == nil || admins[0].ID == nil || admins[0].Login == nil {
+ return nil, false
+ }
+
+ return admins[0], true
+}
+
+-----END handlers/user_roles/handlers.go-----
+
+File: handlers/user_roles/routes.go
+Lines: 53
+-----BEGIN handlers/user_roles/routes.go-----
+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
+}
+
+-----END handlers/user_roles/routes.go-----
+
+File: handlers/users/handlers.go
+Lines: 417
+-----BEGIN handlers/users/handlers.go-----
+package usershandler
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/core/utilscore"
+ "bitrix_balancer_api/rest_admin_service/handlers"
+ adminloghandler "bitrix_balancer_api/rest_admin_service/handlers/admin_actions"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "github.com/sirupsen/logrus"
+ "io"
+ "net/http"
+ "strconv"
+ "strings"
+
+ "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
+ }
+
+ search := queryParams.Get("full_name")
+ if search != "" {
+ if likeFields == nil {
+ likeFields = make(map[string]string)
+ }
+ likeFields["full_name"] = search
+ userParams.FullName = nil
+ }
+
+ var roleIDs []uint64
+ if roleIDsStr := queryParams["role_ids[]"]; len(roleIDsStr) > 0 {
+ for _, idStr := range roleIDsStr {
+ if id, err := strconv.ParseUint(idStr, 10, 64); err == nil {
+ roleIDs = append(roleIDs, id)
+ }
+ }
+ }
+
+ options := typescore.ListDbOptions{
+ Filtering: userParams,
+ Offset: offset,
+ Limit: limit,
+ LikeFields: likeFields,
+ }
+
+ ctx := r.Context()
+
+ var userDbLst []*typescore.User
+ var total uint64
+ var err error
+
+ if len(roleIDs) > 0 {
+ userDbLst, total, err = s.ipc.Database.User.GetUsersListByRoleIDsDB(ctx, options, roleIDs)
+ } else {
+ userDbLst, total, err = s.ipc.Database.User.GetUsersListDB(ctx, options)
+ }
+
+ if err != nil {
+ return nil, err
+ }
+
+ s.enrichUsersBatch(ctx, userDbLst)
+
+ return &typescore.ApiResponseBase{
+ TotalCount: total,
+ Data: userDbLst,
+ }, 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 := r.Context()
+ 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")
+ }
+
+ 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")
+ }
+ }
+ }
+
+ type fieldChange struct {
+ Field string `json:"field"`
+ Old interface{} `json:"old"`
+ New interface{} `json:"new"`
+ }
+ var changes []fieldChange
+ var summary []string
+
+ if req.DepartmentID != nil && !utilscore.Uint64Eq(existingUser.DepartmentID, req.DepartmentID) {
+ var oldVal interface{}
+ if existingUser.DepartmentID != nil {
+ oldVal = *existingUser.DepartmentID
+ }
+ changes = append(changes, fieldChange{"department_id", oldVal, *req.DepartmentID})
+ summary = append(summary, "изменён отдел")
+ }
+ if req.IsBlocked != nil && !utilscore.BoolEq(existingUser.IsBlocked, req.IsBlocked) {
+ changes = append(changes, fieldChange{"is_blocked", utilscore.DerefBool(existingUser.IsBlocked), *req.IsBlocked})
+ if *req.IsBlocked {
+ summary = append(summary, "заблокирован")
+ } else {
+ summary = append(summary, "разблокирован")
+ }
+ }
+ if req.IsFired != nil && !utilscore.BoolEq(existingUser.IsFired, req.IsFired) {
+ changes = append(changes, fieldChange{"is_fired", utilscore.DerefBool(existingUser.IsFired), *req.IsFired})
+ if *req.IsFired {
+ summary = append(summary, "уволен")
+ } else {
+ summary = append(summary, "восстановлен")
+ }
+ }
+
+ 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
+ }
+
+ s.enrichUsersBatch(ctx, []*typescore.User{upUser})
+
+ if len(changes) > 0 {
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ description := fmt.Sprintf("Изменён пользователь «%s»: %s", userLabel(existingUser), strings.Join(summary, "; "))
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "update", "user", req.ID,
+ description,
+ map[string]interface{}{"changes": changes},
+ )
+ }
+ }
+
+ return upUser, nil
+}
+
+// enrichUsersBatch пакетно подгружает отделы и роли для списка пользователей
+func (s *UserReg) enrichUsersBatch(ctx context.Context, users []*typescore.User) {
+ if len(users) == 0 {
+ return
+ }
+
+ departmentIDsSet := make(map[uint64]struct{})
+ userIDs := make([]uint64, 0, len(users))
+ for _, u := range users {
+ if u.ID != nil {
+ userIDs = append(userIDs, *u.ID)
+ }
+ if u.DepartmentID != nil {
+ departmentIDsSet[*u.DepartmentID] = struct{}{}
+ }
+ }
+
+ departmentIDs := make([]uint64, 0, len(departmentIDsSet))
+ for id := range departmentIDsSet {
+ departmentIDs = append(departmentIDs, id)
+ }
+
+ departmentsMap := make(map[uint64]*typescore.Department)
+ if departments, err := s.ipc.Database.Department.GetDepartmentsByIDsDB(ctx, departmentIDs); err == nil {
+ for _, d := range departments {
+ if d.ID != nil {
+ departmentsMap[*d.ID] = d
+ }
+ }
+ }
+
+ userRoles, err := s.ipc.Database.UserRole.GetUserRolesByUserIDsDB(ctx, userIDs)
+ roleIDsSet := make(map[uint64]struct{})
+ userRolesByUser := make(map[uint64][]*typescore.UserRole)
+ if err == nil {
+ for _, ur := range userRoles {
+ if ur.UserID != nil {
+ userRolesByUser[*ur.UserID] = append(userRolesByUser[*ur.UserID], ur)
+ }
+ if ur.RoleID != nil {
+ roleIDsSet[*ur.RoleID] = struct{}{}
+ }
+ }
+ }
+
+ roleIDs := make([]uint64, 0, len(roleIDsSet))
+ for id := range roleIDsSet {
+ roleIDs = append(roleIDs, id)
+ }
+ rolesMap := make(map[uint64]*typescore.Role)
+ if roles, err := s.ipc.Database.Role.GetRolesByIDsDB(ctx, roleIDs); err == nil {
+ for _, role := range roles {
+ if role.ID != nil {
+ rolesMap[*role.ID] = role
+ }
+ }
+ }
+
+ for _, u := range users {
+ if u.DepartmentID != nil {
+ if d, ok := departmentsMap[*u.DepartmentID]; ok {
+ u.Department = d
+ }
+ }
+ if u.ID == nil {
+ continue
+ }
+ userRolesForUser := userRolesByUser[*u.ID]
+ for _, ur := range userRolesForUser {
+ if ur.RoleID != nil {
+ if role, ok := rolesMap[*ur.RoleID]; ok {
+ ur.Role = role
+ }
+ }
+ }
+ if len(userRolesForUser) > 0 {
+ u.UserRoles = userRolesForUser
+ }
+ }
+}
+
+// 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 := r.Context()
+ 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
+}
+
+func (s *UserReg) DeleteUserHandler(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 := r.Context()
+
+ existingUser, err := s.ipc.Database.User.GetUserByIDDB(ctx, id)
+ if err != nil {
+ return nil, err
+ }
+ if existingUser == nil {
+ return nil, errors.New("user not found")
+ }
+
+ err = s.ipc.Database.User.DeleteUserDB(ctx, &typescore.User{ID: &id})
+ if err != nil {
+ return nil, err
+ }
+
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ snapshot := map[string]interface{}{
+ "full_name": utilscore.DerefStr(existingUser.FullName),
+ "is_blocked": utilscore.DerefBool(existingUser.IsBlocked),
+ "is_fired": utilscore.DerefBool(existingUser.IsFired),
+ }
+ if existingUser.TelegramID != nil {
+ snapshot["telegram_id"] = *existingUser.TelegramID
+ }
+ if existingUser.DepartmentID != nil {
+ snapshot["department_id"] = *existingUser.DepartmentID
+ }
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "delete", "user", &id,
+ fmt.Sprintf("Удалён пользователь «%s»", userLabel(existingUser)),
+ map[string]interface{}{"snapshot": snapshot},
+ )
+ }
+
+ return true, nil
+}
+
+func userLabel(user *typescore.User) string {
+ if user == nil || user.FullName == nil {
+ return "—"
+ }
+ return *user.FullName
+}
+
+func (s *UserReg) getCurrentAdmin(ctx context.Context) (*typescore.Admin, bool) {
+ currentUserID, err := handlers.GetIDFromContext(ctx)
+ if err != nil {
+ return nil, false
+ }
+
+ admins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{
+ Filtering: &typescore.Admin{ID: ¤tUserID},
+ })
+ if err != nil || len(admins) == 0 || admins[0] == nil || admins[0].ID == nil || admins[0].Login == nil {
+ return nil, false
+ }
+
+ return admins[0], true
+}
+
+-----END handlers/users/handlers.go-----
+
+File: handlers/users/routes.go
+Lines: 39
+-----BEGIN handlers/users/routes.go-----
+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)
+
+ handlers.RegisterRoute(r, http.MethodDelete, "/{id}", s.DeleteUserHandler)
+
+ r.Get("/{id}", handlers.WrapHandlerF(handlers.WrapHandlerParams{
+ HandlerFunc: s.GetUserByIDHandler,
+ }))
+ })
+
+ return nil
+}
+
+-----END handlers/users/routes.go-----
+
+File: types/module.go
+Lines: 15
+-----BEGIN types/module.go-----
+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
+}
+
+-----END types/module.go-----
+
+File: types/req.go
+Lines: 13
+-----BEGIN types/req.go-----
+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"`
+}
+
+-----END types/req.go-----
+
diff --git a/service/rest_admin_service/cmd/app.go b/service/rest_admin_service/cmd/app.go
index 2f98b2e..acb9335 100644
--- a/service/rest_admin_service/cmd/app.go
+++ b/service/rest_admin_service/cmd/app.go
@@ -5,12 +5,17 @@ import (
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"
+ adminloghandler "bitrix_balancer_api/rest_admin_service/handlers/admin_actions"
approvalstepshandler "bitrix_balancer_api/rest_admin_service/handlers/approval_steps"
approvaltaskshandler "bitrix_balancer_api/rest_admin_service/handlers/approval_tasks"
+ approvalextrashandler "bitrix_balancer_api/rest_admin_service/handlers/approvalextras"
approvalshandler "bitrix_balancer_api/rest_admin_service/handlers/approvals"
authhandler "bitrix_balancer_api/rest_admin_service/handlers/auth"
dashboardhandler "bitrix_balancer_api/rest_admin_service/handlers/dashboard"
departmentshandler "bitrix_balancer_api/rest_admin_service/handlers/departments"
+ nodeshandler "bitrix_balancer_api/rest_admin_service/handlers/flow_nodes"
+ monthlyorders "bitrix_balancer_api/rest_admin_service/handlers/monthly_orders"
+ notificationshandler "bitrix_balancer_api/rest_admin_service/handlers/notification"
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"
@@ -120,6 +125,7 @@ func getClientsExternal() (clientcontrollers.ClientsExternal, error) {
options := &configcore.ConfigLoadOptions{
Redis: true,
Database: true,
+ Telegram: true,
Secrets: configcore.SecretsOptions{
AuthJWT: configcore.AuthJWTOptions{
Admin: true,
@@ -139,6 +145,7 @@ func initInternalProvider(clientsExternal clientcontrollers.ClientsExternal) (*t
Config: clientsExternal.Config,
RedisClient: clientsExternal.Redis,
Database: clientsExternal.DB,
+ TGBotClient: clientsExternal.Telegram,
}, nil
}
@@ -217,6 +224,11 @@ func registerRoutes(router chi.Router, ipc *typesm.InternalProviderControl) erro
{"permissions", permissionshandler.RegisterPermissionRoutes},
{"approval-tasks", approvaltaskshandler.RegisterApprovalTasksRoutes},
{"dashboard", dashboardhandler.RegisterDashboardRoutes},
+ {"notifications", notificationshandler.RegisterNotificationRoutes},
+ {"flownodes", nodeshandler.RegisterFlowNodesRoutes},
+ {"approvalextras", approvalextrashandler.RegisterApprovalExtrasRoutes},
+ {"adminlog", adminloghandler.RegisterAdminLogRoutes},
+ {"monthlyorders", monthlyorders.RegisterMonthlyOrdersRoutes},
}
// Регистрация всех маршрутов
diff --git a/service/rest_admin_service/handlers/admin/handlers.go b/service/rest_admin_service/handlers/admin/handlers.go
index 3e228d1..4fb671f 100644
--- a/service/rest_admin_service/handlers/admin/handlers.go
+++ b/service/rest_admin_service/handlers/admin/handlers.go
@@ -4,13 +4,116 @@ 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"
+ adminloghandler "bitrix_balancer_api/rest_admin_service/handlers/admin_actions"
+ "bytes"
"encoding/json"
"errors"
+ "fmt"
+ "github.com/sirupsen/logrus"
"io"
"net/http"
+ "strings"
+ "time"
)
+// ProxyPayloadReq описывает тело запроса, которое мы ожидаем от клиента
+// и отправляем на Сервер 2.
+type ProxyPayloadReq struct {
+ URL string `json:"url"`
+ Method string `json:"method"`
+ Body map[string]interface{} `json:"body,omitempty"`
+}
+
+// ProxyForwardHandler Перенаправление запроса через внешний прокси-сервер
+// @Summary Отправка запроса через прокси
+// @Description Принимает url, method и body, и отправляет их на Сервер 2
+// @Tags admin
+// @Accept json
+// @Produce json
+// @Param request body ProxyPayloadReq true "Данные для проксирования"
+// @Success 200 {object} interface{} "Ответ от целевого сервера"
+// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос"
+// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера"
+// @Router /api/admin/proxy-forward [post]
+func (s *AdminsReg) ProxyForwardHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ defer r.Body.Close()
+
+ // 1. Читаем тело входящего запроса от клиента
+ body, err := io.ReadAll(r.Body)
+ if err != nil {
+ return nil, errors.New("failed to read request body")
+ }
+
+ var req ProxyPayloadReq
+ if err := json.Unmarshal(body, &req); err != nil {
+ return nil, errors.New("invalid request JSON format")
+ }
+
+ if req.URL == "" {
+ return nil, errors.New("field 'url' is required")
+ }
+ if req.Method == "" {
+ req.Method = http.MethodPost // По умолчанию POST
+ }
+
+ // 2. Упаковываем в JSON для Сервера 2
+ proxyBytes, err := json.Marshal(req)
+ if err != nil {
+ return nil, fmt.Errorf("failed to marshal proxy payload: %w", err)
+ }
+
+ // 3. Формируем HTTP-запрос к Серверу 2
+ proxyReq, err := http.NewRequestWithContext(
+ r.Context(),
+ http.MethodPost,
+ variables.ProxyForwardURL,
+ bytes.NewReader(proxyBytes),
+ )
+ if err != nil {
+ return nil, fmt.Errorf("failed to create request to proxy: %w", err)
+ }
+
+ // Устанавливаем заголовки, которые требует Сервер 2
+ proxyReq.Header.Set("Content-Type", "application/json")
+ proxyReq.Header.Set(variables.ProxySecretHeader, variables.ProxySecretKey)
+
+ // 4. Выполняем запрос
+ client := &http.Client{Timeout: 60 * time.Second}
+ resp, err := client.Do(proxyReq)
+ if err != nil {
+ logrus.Errorf("Proxy connection error: %v", err)
+ return nil, errors.New("failed to connect to proxy server")
+ }
+ defer resp.Body.Close()
+
+ // 5. Читаем ответ от прокси (от целевого сервера)
+ respBody, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return nil, errors.New("failed to read response from proxy")
+ }
+
+ // Если целевой сервер вернул ошибку, пробрасываем её
+ if resp.StatusCode >= 400 {
+ logrus.Warnf("Proxy returned status %d: %s", resp.StatusCode, string(respBody))
+ // Можно вернуть кастомную ошибку, чтобы фронтенд понял причину
+ return nil, fmt.Errorf("target server error (status %d): %s", resp.StatusCode, string(respBody))
+ }
+
+ // 6. Распаковываем ответ, чтобы вернуть его клиенту как объект (interface{}),
+ // так как роутер bitrix_balancer_api сам сериализует результат в JSON.
+ var result interface{}
+ if len(respBody) > 0 {
+ if err := json.Unmarshal(respBody, &result); err != nil {
+ // Если ответ не является JSON (например, plain text), возвращаем как строку
+ result = string(respBody)
+ }
+ }
+
+ return result, nil
+}
+
// GetAdminsListHandler Получение списка администраторов
// @Summary Получение списка администраторов
// @Description Получение списка администраторов
@@ -45,6 +148,16 @@ func (s *AdminsReg) GetAdminsListHandler(w http.ResponseWriter, r *http.Request)
return nil, errW
}
+ ctx := r.Context()
+ for _, admin := range adminsDbLst {
+ if admin.TelegramID != nil {
+ telegramUser, err := s.ipc.Database.User.GetUserByTelegramIDDB(ctx, *admin.TelegramID)
+ if err == nil && telegramUser != nil {
+ admin.TelegramUser = telegramUser
+ }
+ }
+ }
+
return &typescore.ApiResponseBase{
TotalCount: total,
Data: adminsDbLst,
@@ -68,7 +181,6 @@ func (s *AdminsReg) CreateAdminHandler(w http.ResponseWriter, r *http.Request) (
return nil, errors.New("current admin not found")
}
- // 🆕 Проверяем is_root, а не login
if currentAdmins[0].IsRoot == nil || !*currentAdmins[0].IsRoot {
return nil, errors.New("only_root_can_create_admins")
}
@@ -87,6 +199,16 @@ func (s *AdminsReg) CreateAdminHandler(w http.ResponseWriter, r *http.Request) (
return nil, errors.New("login is required")
}
+ if req.IsObserver != nil && *req.IsObserver {
+ if req.TelegramID == nil {
+ return nil, errors.New("telegram_id_required_for_observer")
+ }
+ telegramUser, err := s.ipc.Database.User.GetUserByTelegramIDDB(r.Context(), *req.TelegramID)
+ if err != nil || telegramUser == nil {
+ return nil, errors.New("telegram_user_not_found")
+ }
+ }
+
// Проверка уникальности логина
usersList, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{
Filtering: &typescore.Admin{Login: req.Login},
@@ -113,6 +235,9 @@ func (s *AdminsReg) CreateAdminHandler(w http.ResponseWriter, r *http.Request) (
Name: req.Name,
PasswordHash: tempPasswordHash,
IsRoot: req.IsRoot,
+ IsObserver: req.IsObserver,
+ IsAnalyst: req.IsAnalyst,
+ TelegramID: req.TelegramID,
}
newAdmin, _, err := s.ipc.Database.Admin.CreateAdminDB(nil, newAdminObj, true)
@@ -121,6 +246,40 @@ func (s *AdminsReg) CreateAdminHandler(w http.ResponseWriter, r *http.Request) (
}
newAdmin.Password = &tempPassword
+
+ userID, err := handlers.GetIDFromContext(r.Context())
+ if err != nil {
+ logrus.Errorf("Failed to get user id: %v", err)
+ } else {
+ admins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{
+ Filtering: &typescore.Admin{
+ ID: &userID,
+ },
+ })
+ if err != nil {
+ logrus.Errorf("get admin list error: %v", err)
+ }
+ if len(admins) > 0 && admins[0] != nil {
+ snapshot := map[string]interface{}{
+ "login": derefStr(newAdmin.Login),
+ "name": derefStr(newAdmin.Name),
+ "is_root": derefBool(newAdmin.IsRoot),
+ "is_observer": derefBool(newAdmin.IsObserver),
+ }
+ if newAdmin.TelegramID != nil {
+ snapshot["telegram_id"] = *newAdmin.TelegramID
+ }
+
+ adminloghandler.LogAdminActionWithMetadata(
+ r.Context(), s.ipc,
+ *admins[0].ID, *admins[0].Login,
+ "create", "admin", newAdmin.ID,
+ fmt.Sprintf("Создан администратор «%s»", *newAdmin.Login),
+ map[string]interface{}{"snapshot": snapshot},
+ )
+ }
+ }
+
return newAdmin, nil
}
@@ -164,11 +323,11 @@ func (s *AdminsReg) UpdateAdminHandler(w http.ResponseWriter, r *http.Request) (
}
currentIsRoot := currentAdmins[0].IsRoot != nil && *currentAdmins[0].IsRoot
+ // Проверки root-прав (как было)
if req.IsRoot != nil {
if !currentIsRoot {
return nil, errors.New("only_root_can_manage_root_rights")
}
-
if *req.ID == currentUserID && !*req.IsRoot {
return nil, errors.New("cannot_remove_root_from_self")
}
@@ -200,6 +359,71 @@ func (s *AdminsReg) UpdateAdminHandler(w http.ResponseWriter, r *http.Request) (
return nil, errors.New("cannot_block_self")
}
+ isObserver := existing.IsObserver
+ telegramID := existing.TelegramID
+
+ if req.IsObserver != nil {
+ isObserver = req.IsObserver
+ }
+ if req.TelegramID != nil {
+ telegramID = req.TelegramID
+ }
+
+ if isObserver != nil && *isObserver {
+ if telegramID == nil {
+ return nil, errors.New("telegram_id_required_for_observer")
+ }
+ telegramUser, err := s.ipc.Database.User.GetUserByTelegramIDDB(r.Context(), *telegramID)
+ if err != nil || telegramUser == nil {
+ return nil, errors.New("telegram_user_not_found")
+ }
+ }
+
+ type fieldChange struct {
+ Field string `json:"field"`
+ Old interface{} `json:"old"`
+ New interface{} `json:"new"`
+ }
+ var changes []fieldChange
+ var summary []string
+
+ if req.Name != nil && !strEq(existing.Name, req.Name) {
+ changes = append(changes, fieldChange{"name", derefStr(existing.Name), *req.Name})
+ summary = append(summary, fmt.Sprintf("имя: «%s» → «%s»", derefStr(existing.Name), *req.Name))
+ }
+ if req.IsBlocked != nil && !boolEq(existing.IsBlocked, req.IsBlocked) {
+ changes = append(changes, fieldChange{"is_blocked", derefBool(existing.IsBlocked), *req.IsBlocked})
+ if *req.IsBlocked {
+ summary = append(summary, "заблокирован")
+ } else {
+ summary = append(summary, "разблокирован")
+ }
+ }
+ if req.IsRoot != nil && !boolEq(existing.IsRoot, req.IsRoot) {
+ changes = append(changes, fieldChange{"is_root", derefBool(existing.IsRoot), *req.IsRoot})
+ if *req.IsRoot {
+ summary = append(summary, "выдана роль root")
+ } else {
+ summary = append(summary, "роль root снята")
+ }
+ }
+ if req.IsObserver != nil && !boolEq(existing.IsObserver, req.IsObserver) {
+ changes = append(changes, fieldChange{"is_observer", derefBool(existing.IsObserver), *req.IsObserver})
+ if *req.IsObserver {
+ summary = append(summary, "включён режим наблюдателя")
+ } else {
+ summary = append(summary, "режим наблюдателя выключен")
+ }
+ }
+ if req.TelegramID != nil && !int64Eq(existing.TelegramID, req.TelegramID) {
+ var oldVal interface{}
+ if existing.TelegramID != nil {
+ oldVal = *existing.TelegramID
+ }
+ changes = append(changes, fieldChange{"telegram_id", oldVal, *req.TelegramID})
+ summary = append(summary, fmt.Sprintf("telegram_id: %v → %d", oldVal, *req.TelegramID))
+ }
+
// Создаём объект для обновления
updateObj := &typescore.Admin{
ID: req.ID,
@@ -213,12 +437,35 @@ func (s *AdminsReg) UpdateAdminHandler(w http.ResponseWriter, r *http.Request) (
if req.IsRoot != nil {
updateObj.IsRoot = req.IsRoot
}
+ if req.IsAnalyst != nil {
+ updateObj.IsAnalyst = req.IsAnalyst
+ }
+ if req.IsObserver != nil {
+ updateObj.IsObserver = req.IsObserver
+ }
+ if req.TelegramID != nil {
+ updateObj.TelegramID = req.TelegramID
+ }
updated, _, err := s.ipc.Database.Admin.UpdateAdminDB(nil, updateObj, true)
if err != nil {
return nil, err
}
+ // 🆕 Логируем ПОСЛЕ успешного обновления, и только если реально что-то
+ // изменилось (пустой запрос на обновление без факта изменений в
+ // журнал не пишем — иначе он будет засоряться).
+ if len(changes) > 0 {
+ description := fmt.Sprintf("Изменён администратор «%s»: %s", derefStr(existing.Login), strings.Join(summary, "; "))
+ adminloghandler.LogAdminActionWithMetadata(
+ r.Context(), s.ipc,
+ *currentAdmins[0].ID, *currentAdmins[0].Login,
+ "update", "admin", req.ID,
+ description,
+ map[string]interface{}{"changes": changes},
+ )
+ }
+
return updated, nil
}
@@ -268,10 +515,91 @@ func (s *AdminsReg) DeleteAdminHandler(w http.ResponseWriter, r *http.Request) (
return nil, errors.New("cannot_delete_root")
}
+ // 🆕 Снапшот удаляемого администратора — берём ДО удаления (после
+ // DeleteAdminDB запись из БД уже не достать).
+ deletedSnapshot := map[string]interface{}{
+ "login": derefStr(admins[0].Login),
+ "name": derefStr(admins[0].Name),
+ "is_root": derefBool(admins[0].IsRoot),
+ "is_observer": derefBool(admins[0].IsObserver),
+ }
+ if admins[0].TelegramID != nil {
+ deletedSnapshot["telegram_id"] = *admins[0].TelegramID
+ }
+
err = s.ipc.Database.Admin.DeleteAdminDB(&req)
if err != nil {
return nil, err
}
+ if len(currentAdmins) > 0 && currentAdmins[0] != nil {
+ adminloghandler.LogAdminActionWithMetadata(
+ r.Context(), s.ipc,
+ *currentAdmins[0].ID, *currentAdmins[0].Login,
+ "delete", "admin", req.ID,
+ fmt.Sprintf("Удалён администратор «%s»", derefStr(admins[0].Login)),
+ map[string]interface{}{"snapshot": deletedSnapshot},
+ )
+ }
+
return true, nil
}
+
+// ============================================================
+// Небольшие помощники сравнения/разыменования — чтобы не плодить
+// одинаковые проверки "оба nil или оба равны" по всему файлу.
+// ============================================================
+
+func derefStr(s *string) string {
+ if s == nil {
+ return ""
+ }
+ return *s
+}
+
+func derefBool(b *bool) bool {
+ if b == nil {
+ return false
+ }
+ return *b
+}
+
+func strEq(a, b *string) bool {
+ if a == nil && b == nil {
+ return true
+ }
+ if a == nil || b == nil {
+ return false
+ }
+ return *a == *b
+}
+
+func boolEq(a, b *bool) bool {
+ if a == nil && b == nil {
+ return true
+ }
+ if a == nil || b == nil {
+ return false
+ }
+ return *a == *b
+}
+
+func uint64Eq(a, b *uint64) bool {
+ if a == nil && b == nil {
+ return true
+ }
+ if a == nil || b == nil {
+ return false
+ }
+ return *a == *b
+}
+
+func int64Eq(a, b *int64) bool {
+ if a == nil && b == nil {
+ return true
+ }
+ if a == nil || b == nil {
+ return false
+ }
+ return *a == *b
+}
diff --git a/service/rest_admin_service/handlers/admin/routes.go b/service/rest_admin_service/handlers/admin/routes.go
index 446cdb1..80a71ce 100644
--- a/service/rest_admin_service/handlers/admin/routes.go
+++ b/service/rest_admin_service/handlers/admin/routes.go
@@ -34,5 +34,7 @@ func RegisterAdminRoutes(
handlers.RegisterRoute(r, http.MethodPut, adminURL, s.UpdateAdminHandler)
})
+ handlers.RegisterRoute(r, http.MethodPost, "/api/proxy/forward", s.ProxyForwardHandler)
+
return nil
}
diff --git a/service/rest_admin_service/handlers/admin_actions/handlers.go b/service/rest_admin_service/handlers/admin_actions/handlers.go
new file mode 100644
index 0000000..7ffc35c
--- /dev/null
+++ b/service/rest_admin_service/handlers/admin_actions/handlers.go
@@ -0,0 +1,210 @@
+package adminloghandler
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/rest_admin_service/handlers"
+ typesm "bitrix_balancer_api/rest_admin_service/types"
+ "context"
+ "encoding/json"
+ "net/http"
+ "strconv"
+ "time"
+
+ "github.com/go-chi/chi/v5"
+ "github.com/sirupsen/logrus"
+)
+
+type AdminLogReg struct {
+ ipc *typesm.InternalProviderControl
+}
+
+func RegisterAdminLogRoutes(r chi.Router, ipc *typesm.InternalProviderControl) error {
+ s := &AdminLogReg{ipc: ipc}
+
+ r.Route("/api/admin-logs", 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.ListLogsHandler)
+ handlers.RegisterRoute(r, http.MethodDelete, "/{id}", s.DeleteLogEntryHandler)
+ })
+
+ return nil
+}
+
+// ListLogsHandler — теперь поддерживает:
+//
+// admin_id, admin_login (ILIKE), action, entity_type, entity_id,
+// date_from, date_to (YYYY-MM-DD, включительно на весь день),
+// search (ILIKE по description)
+func (s *AdminLogReg) ListLogsHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ ctx := r.Context()
+ q := r.URL.Query()
+
+ filter := typescore.AdminActionLogFilter{}
+
+ if v := q.Get("admin_id"); v != "" {
+ if id, err := strconv.ParseUint(v, 10, 64); err == nil {
+ filter.AdminID = &id
+ }
+ }
+ if v := q.Get("admin_login"); v != "" {
+ filter.AdminLogin = &v
+ }
+ if v := q.Get("action"); v != "" {
+ filter.Action = &v
+ }
+ if v := q.Get("entity_type"); v != "" {
+ filter.EntityType = &v
+ }
+ if v := q.Get("entity_id"); v != "" {
+ if id, err := strconv.ParseUint(v, 10, 64); err == nil {
+ filter.EntityID = &id
+ }
+ }
+ if v := q.Get("date_from"); v != "" {
+ if t, err := time.Parse("2006-01-02", v); err == nil {
+ filter.DateFrom = &t
+ }
+ }
+ if v := q.Get("date_to"); v != "" {
+ if t, err := time.Parse("2006-01-02", v); err == nil {
+ endOfDay := t.Add(24*time.Hour - time.Second)
+ filter.DateTo = &endOfDay
+ }
+ }
+ if v := q.Get("search"); v != "" {
+ filter.Search = &v
+ }
+
+ limit := parseUintPtr(q.Get("limit"), 50)
+ offset := parseUintPtr(q.Get("offset"), 0)
+
+ logs, totalCount, err := s.ipc.Database.AdminActionLogs.GetAdminActionLogsFilteredDB(ctx, filter, offset, limit)
+ if err != nil {
+ return nil, err
+ }
+
+ return map[string]interface{}{
+ "data": logs,
+ "total_count": totalCount,
+ }, nil
+}
+
+// DeleteLogEntryHandler — 🩹 восстановлена проверка is_root, потерянная
+// в промежуточной версии. Удалять записи журнала может только
+// root-администратор — без этой проверки endpoint открыт любому админу,
+// что сводит на нет саму цель журнала (неизменяемость для всех, кроме root).
+func (s *AdminLogReg) DeleteLogEntryHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ ctx := r.Context()
+
+ currentAdmin, ok := GetCurrentAdmin(ctx, s.ipc)
+ if !ok {
+ http.Error(w, "unauthorized", http.StatusUnauthorized)
+ return nil, nil
+ }
+ if currentAdmin.IsRoot == nil || !*currentAdmin.IsRoot {
+ http.Error(w, "только root-администратор может удалять записи журнала", http.StatusForbidden)
+ return nil, nil
+ }
+
+ id, err := strconv.ParseUint(chi.URLParam(r, "id"), 10, 64)
+ if err != nil {
+ return nil, err
+ }
+
+ if err := s.ipc.Database.AdminActionLogs.DeleteAdminActionLogDB(ctx, &typescore.AdminActionLog{ID: &id}); err != nil {
+ return nil, err
+ }
+
+ return map[string]interface{}{"success": true}, nil
+}
+
+func LogAdminAction(
+ ctx context.Context,
+ ipc *typesm.InternalProviderControl,
+ adminID uint64,
+ adminLogin string,
+ action string,
+ entityType string,
+ entityID *uint64,
+ description string,
+) {
+ LogAdminActionWithMetadata(ctx, ipc, adminID, adminLogin, action, entityType, entityID, description, nil)
+}
+
+func LogAdminActionWithMetadata(
+ ctx context.Context,
+ ipc *typesm.InternalProviderControl,
+ adminID uint64,
+ adminLogin string,
+ action string,
+ entityType string,
+ entityID *uint64,
+ description string,
+ metadata map[string]interface{},
+) {
+ var metadataJSON *string
+ if metadata != nil {
+ if b, err := json.Marshal(metadata); err == nil {
+ s := string(b)
+ metadataJSON = &s
+ } else {
+ logrus.Warnf("LogAdminActionWithMetadata: не удалось сериализовать metadata: %v", err)
+ }
+ }
+
+ now := time.Now()
+ entry := &typescore.AdminActionLog{
+ AdminID: &adminID,
+ AdminLogin: &adminLogin,
+ Action: &action,
+ EntityType: &entityType,
+ EntityID: entityID,
+ Description: &description,
+ Metadata: metadataJSON,
+ CreatedAt: &now,
+ }
+
+ if _, _, err := ipc.Database.AdminActionLogs.CreateAdminActionLogDB(ctx, nil, entry); err != nil {
+ logrus.Errorf("LogAdminActionWithMetadata: не удалось записать в журнал (admin=%s, action=%s, entity=%s:%v): %v",
+ adminLogin, action, entityType, entityID, err)
+ }
+}
+
+// GetCurrentAdmin — 🆕 вынесено сюда из 13 хендлеров, где было
+// продублировано один в один под именем getCurrentAdmin (локальная,
+// неэкспортируемая версия в каждом пакете отдельно). Экспортируемая
+// версия здесь, в "родном" пакете журнала — логичное место, раз уже
+// каждый из этих 13 хендлеров и так импортирует adminloghandler ради
+// LogAdminActionWithMetadata.
+//
+// Миграция существующих хендлеров не обязательна прямо сейчас (все они
+// рабочие как есть, с локальными копиями) — но при следующей правке
+// любого из них имеет смысл заменить его локальный getCurrentAdmin на
+// вызов adminloghandler.GetCurrentAdmin(ctx, s.ipc) и удалить дубликат.
+func GetCurrentAdmin(ctx context.Context, ipc *typesm.InternalProviderControl) (*typescore.Admin, bool) {
+ currentUserID, err := handlers.GetIDFromContext(ctx)
+ if err != nil {
+ return nil, false
+ }
+
+ admins, _, err := ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{
+ Filtering: &typescore.Admin{ID: ¤tUserID},
+ })
+ if err != nil || len(admins) == 0 || admins[0] == nil || admins[0].ID == nil || admins[0].Login == nil {
+ return nil, false
+ }
+
+ return admins[0], true
+}
+
+func parseUintPtr(v string, fallback uint64) *uint64 {
+ if v == "" {
+ return &fallback
+ }
+ n, err := strconv.ParseUint(v, 10, 64)
+ if err != nil {
+ return &fallback
+ }
+ return &n
+}
diff --git a/service/rest_admin_service/handlers/approval_tasks/handlers.go b/service/rest_admin_service/handlers/approval_tasks/handlers_tasks.go
similarity index 66%
rename from service/rest_admin_service/handlers/approval_tasks/handlers.go
rename to service/rest_admin_service/handlers/approval_tasks/handlers_tasks.go
index 9d97aad..a87f59a 100644
--- a/service/rest_admin_service/handlers/approval_tasks/handlers.go
+++ b/service/rest_admin_service/handlers/approval_tasks/handlers_tasks.go
@@ -3,6 +3,8 @@ package approvaltaskshandler
import (
"bitrix_balancer_api/core/typescore"
"bitrix_balancer_api/core/utilscore"
+ "bitrix_balancer_api/rest_admin_service/handlers"
+ adminloghandler "bitrix_balancer_api/rest_admin_service/handlers/admin_actions"
"context"
"encoding/base64"
"encoding/json"
@@ -28,6 +30,20 @@ func (s *ApprovalTasksReg) GetApprovalTasksListHandler(w http.ResponseWriter, r
return nil, errW
}
+ ctx := r.Context()
+
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok && currentAdmin.IsObserver != nil && *currentAdmin.IsObserver {
+ if currentAdmin.TelegramID != nil && *currentAdmin.TelegramID > 0 {
+ if tgUser, err := s.ipc.Database.User.GetUserByTelegramIDDB(ctx, *currentAdmin.TelegramID); err == nil && tgUser != nil && tgUser.ID != nil {
+ taskParams.ObserverUserID = tgUser.ID
+ } else {
+ return &typescore.ApiResponseBase{TotalCount: 0, Data: []*typescore.ApprovalTask{}}, nil
+ }
+ } else {
+ return &typescore.ApiResponseBase{TotalCount: 0, Data: []*typescore.ApprovalTask{}}, nil
+ }
+ }
+
options := typescore.ListDbOptions{
Filtering: taskParams,
Offset: offset,
@@ -35,13 +51,11 @@ func (s *ApprovalTasksReg) GetApprovalTasksListHandler(w http.ResponseWriter, r
LikeFields: likeFields,
}
- ctx := r.Context()
tasks, total, errW := s.ipc.Database.ApprovalTasks.GetApprovalTasksListDB(ctx, options)
if errW != nil {
return nil, errW
}
- // 🆕 Обогащаем данные
for _, task := range tasks {
s.enrichTask(ctx, task)
}
@@ -105,7 +119,6 @@ func (s *ApprovalTasksReg) UpdateApprovalTaskHandler(w http.ResponseWriter, r *h
return nil, errors.New("task not found")
}
- // 🆕 Валидация статуса
if req.Status != nil {
validStatuses := map[string]bool{
"pending": true,
@@ -118,6 +131,47 @@ func (s *ApprovalTasksReg) UpdateApprovalTaskHandler(w http.ResponseWriter, r *h
}
}
+ type fieldChange struct {
+ Field string `json:"field"`
+ Old interface{} `json:"old"`
+ New interface{} `json:"new"`
+ }
+ var changes []fieldChange
+ var summary []string
+
+ if req.Status != nil && !utilscore.StrEq(existingTask.Status, req.Status) {
+ changes = append(changes, fieldChange{"status", utilscore.DerefStr(existingTask.Status), *req.Status})
+ summary = append(summary, fmt.Sprintf("статус: «%s» → «%s»", utilscore.DerefStr(existingTask.Status), *req.Status))
+ }
+ if req.TaskText != nil && !utilscore.StrEq(existingTask.TaskText, req.TaskText) {
+ changes = append(changes, fieldChange{"task_text", utilscore.DerefStr(existingTask.TaskText), *req.TaskText})
+ summary = append(summary, "изменён текст задачи")
+ }
+ if req.ExecutorID != nil && !utilscore.Uint64Eq(existingTask.ExecutorID, req.ExecutorID) {
+ var oldVal interface{}
+ if existingTask.ExecutorID != nil {
+ oldVal = *existingTask.ExecutorID
+ }
+ changes = append(changes, fieldChange{"executor_id", oldVal, *req.ExecutorID})
+ summary = append(summary, fmt.Sprintf("исполнитель: %v → %d", oldVal, *req.ExecutorID))
+ }
+ if req.RequireFile != nil && !utilscore.BoolEq(existingTask.RequireFile, req.RequireFile) {
+ changes = append(changes, fieldChange{"require_file", utilscore.DerefBool(existingTask.RequireFile), *req.RequireFile})
+ if *req.RequireFile {
+ summary = append(summary, "включено обязательное вложение файла")
+ } else {
+ summary = append(summary, "отключено обязательное вложение файла")
+ }
+ }
+ if req.StepOrder != nil && !utilscore.IntEq(existingTask.StepOrder, req.StepOrder) {
+ var oldVal interface{}
+ if existingTask.StepOrder != nil {
+ oldVal = *existingTask.StepOrder
+ }
+ changes = append(changes, fieldChange{"step_order", oldVal, *req.StepOrder})
+ summary = append(summary, fmt.Sprintf("порядок шага: %v → %d", oldVal, *req.StepOrder))
+ }
+
updated, _, err := s.ipc.Database.ApprovalTasks.UpdateApprovalTaskDB(ctx, nil, &req, true)
if err != nil {
return nil, err
@@ -125,6 +179,23 @@ func (s *ApprovalTasksReg) UpdateApprovalTaskHandler(w http.ResponseWriter, r *h
s.enrichTask(ctx, updated)
+ if len(changes) > 0 {
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ approvalRef := ""
+ if existingTask.ApprovalID != nil {
+ approvalRef = fmt.Sprintf(" (заявка #%d)", *existingTask.ApprovalID)
+ }
+ description := fmt.Sprintf("Изменена задача #%d%s: %s", *req.ID, approvalRef, strings.Join(summary, "; "))
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "update", "approval_task", req.ID,
+ description,
+ map[string]interface{}{"changes": changes},
+ )
+ }
+ }
+
return updated, nil
}
@@ -147,14 +218,66 @@ func (s *ApprovalTasksReg) DeleteApprovalTaskHandler(w http.ResponseWriter, r *h
}
ctx := r.Context()
+
+ existingTask, err := s.ipc.Database.ApprovalTasks.GetApprovalTaskByIDDB(ctx, *req.ID)
+ if err != nil || existingTask == nil {
+ return nil, errors.New("task not found")
+ }
+ snapshot := map[string]interface{}{
+ "task_text": utilscore.DerefStr(existingTask.TaskText),
+ "status": utilscore.DerefStr(existingTask.Status),
+ "require_file": utilscore.DerefBool(existingTask.RequireFile),
+ }
+ if existingTask.ApprovalID != nil {
+ snapshot["approval_id"] = *existingTask.ApprovalID
+ }
+ if existingTask.ExecutorID != nil {
+ snapshot["executor_id"] = *existingTask.ExecutorID
+ }
+ if existingTask.StepOrder != nil {
+ snapshot["step_order"] = *existingTask.StepOrder
+ }
+
err = s.ipc.Database.ApprovalTasks.DeleteApprovalTaskDB(ctx, &req)
if err != nil {
return nil, err
}
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ approvalRef := ""
+ if existingTask.ApprovalID != nil {
+ approvalRef = fmt.Sprintf(" (заявка #%d)", *existingTask.ApprovalID)
+ }
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "delete", "approval_task", req.ID,
+ fmt.Sprintf("Удалена задача #%d%s", *req.ID, approvalRef),
+ map[string]interface{}{"snapshot": snapshot},
+ )
+ }
+
return true, nil
}
+func (s *ApprovalTasksReg) getCurrentAdmin(ctx context.Context) (*typescore.Admin, bool) {
+ currentUserID, err := handlers.GetIDFromContext(ctx)
+ if err != nil {
+ logrus.Warnf("getCurrentAdmin: GetIDFromContext err=%v", err)
+ return nil, false
+ }
+
+ admins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{
+ Filtering: &typescore.Admin{ID: ¤tUserID},
+ })
+ if err != nil || len(admins) == 0 || admins[0] == nil || admins[0].ID == nil || admins[0].Login == nil {
+ logrus.Warnf("getCurrentAdmin: admin not found for userID=%d err=%v", currentUserID, err)
+ return nil, false
+ }
+
+ return admins[0], true
+}
+
// enrichTask подгружает связанные данные для задачи
func (s *ApprovalTasksReg) enrichTask(ctx context.Context, task *typescore.ApprovalTask) {
if task == nil {
@@ -239,6 +362,11 @@ func (s *ApprovalTasksReg) enrichApproval(ctx context.Context, approval *typesco
}
// GetApprovalTaskFileHandler Получение файла задачи (для предпросмотра)
+//
+// 🆕 Не логирую просмотр/скачивание файлов — журнал задуман под
+// create/update/delete-действия, а не под чтение. Если захотите отслеживать
+// ещё и скачивания (например, для файлов с чувствительными данными) — это
+// отдельное решение, скажите, добавлю action="download" по тому же паттерну.
func (s *ApprovalTasksReg) GetApprovalTaskFileHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
ctx := r.Context()
diff --git a/service/rest_admin_service/handlers/approvalextras/handler.go b/service/rest_admin_service/handlers/approvalextras/handler.go
new file mode 100644
index 0000000..6d0fd00
--- /dev/null
+++ b/service/rest_admin_service/handlers/approvalextras/handler.go
@@ -0,0 +1,422 @@
+package approvalextrashandler
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/rest_admin_service/handlers"
+ typesm "bitrix_balancer_api/rest_admin_service/types"
+ "errors"
+ "net/http"
+ "strconv"
+ "time"
+
+ "github.com/go-chi/chi/v5"
+)
+
+type ApprovalExtrasReg struct {
+ ipc *typesm.InternalProviderControl
+}
+
+// RegisterApprovalExtrasRoutes регистрирует данные о заявке, которые НЕ
+// хранятся прямо на самой Approval (или пока не отдаются в основном ответе
+// GET /api/approvals/{id}) — доп. согласующие, комментарии, наблюдатели
+// (вычисляются динамически по категории/теме, не хранимая связь) и активный
+// запрос на отзыв.
+//
+// ⚠️ ВАЖНО: регистрируем через r.Get() с полными путями, а НЕ через
+// r.Route("/api/approvals/{id}", ...). r.Route создаёт отдельный вложенный
+// роутер, который занимает узел {id} целиком — из-за этого существующий
+// GET /api/approvals/{id} (без суффикса) становится недостижим и отдаёт 404,
+// хотя вложенные пути (/additional-approvers и т.п.) продолжают работать.
+// Проверено эмпирически на реальном chi.Router — с r.Route ломается, с
+// r.Get(полный путь) — нет.
+func RegisterApprovalExtrasRoutes(
+ r chi.Router,
+ ipc *typesm.InternalProviderControl,
+) error {
+ s := &ApprovalExtrasReg{ipc: ipc}
+
+ r.Group(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, "/api/approvals/{id}/additional-approvers", s.GetAdditionalApproversHandler)
+ handlers.RegisterRoute(r, http.MethodGet, "/api/approvals/{id}/comments", s.GetCommentsHandler)
+ handlers.RegisterRoute(r, http.MethodGet, "/api/approvals/{id}/observers", s.GetObserversHandler)
+ handlers.RegisterRoute(r, http.MethodGet, "/api/approvals/{id}/revocation-request", s.GetRevocationRequestHandler)
+ handlers.RegisterRoute(r, http.MethodGet, "/api/approvals/{id}/tasks", s.GetTasksHandler)
+ })
+
+ return nil
+}
+
+func parseApprovalID(r *http.Request) (uint64, error) {
+ idStr := chi.URLParam(r, "id")
+ id, err := strconv.ParseUint(idStr, 10, 64)
+ if err != nil {
+ return 0, errors.New("invalid approval id")
+ }
+ return id, nil
+}
+
+func userName(u *typescore.User) string {
+ if u != nil && u.FullName != nil {
+ return *u.FullName
+ }
+ return "—"
+}
+
+// ============================================================
+// GET /api/approvals/{id}/additional-approvers
+// ============================================================
+
+type additionalApproverDTO struct {
+ ID uint64 `json:"id"`
+ ApproverID uint64 `json:"approver_id"`
+ ApproverName string `json:"approver_name"`
+ Status string `json:"status"`
+ Comment string `json:"comment,omitempty"`
+ ActedAt *time.Time `json:"acted_at,omitempty"`
+}
+
+func (s *ApprovalExtrasReg) GetAdditionalApproversHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ approvalID, err := parseApprovalID(r)
+ if err != nil {
+ return nil, err
+ }
+ ctx := r.Context()
+
+ records, _, err := s.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalAdditionalApprover{ApprovalID: &approvalID},
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ result := make([]additionalApproverDTO, 0, len(records))
+ for _, rec := range records {
+ if rec.ApproverID == nil {
+ continue
+ }
+ approver, _ := s.ipc.Database.User.GetUserByIDDB(ctx, *rec.ApproverID)
+
+ dto := additionalApproverDTO{
+ ApproverID: *rec.ApproverID,
+ ApproverName: userName(approver),
+ Status: "pending",
+ ActedAt: rec.ActedAt,
+ }
+ if rec.ID != nil {
+ dto.ID = *rec.ID
+ }
+ if rec.Status != nil {
+ dto.Status = *rec.Status
+ }
+ if rec.Comment != nil {
+ dto.Comment = *rec.Comment
+ }
+ result = append(result, dto)
+ }
+
+ return &typescore.ApiResponseBase{
+ TotalCount: uint64(len(result)),
+ Data: result,
+ }, nil
+}
+
+// ============================================================
+// GET /api/approvals/{id}/comments
+// ============================================================
+
+type commentDTO struct {
+ ID uint64 `json:"id"`
+ UserID uint64 `json:"user_id"`
+ UserName string `json:"user_name"`
+ Comment string `json:"comment"`
+ CreatedAt *time.Time `json:"created_at,omitempty"`
+}
+
+func (s *ApprovalExtrasReg) GetCommentsHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ approvalID, err := parseApprovalID(r)
+ if err != nil {
+ return nil, err
+ }
+ ctx := r.Context()
+
+ records, _, err := s.ipc.Database.ApprovalComment.GetApprovalCommentsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalComment{ApprovalID: &approvalID},
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ result := make([]commentDTO, 0, len(records))
+ for _, rec := range records {
+ dto := commentDTO{CreatedAt: rec.CreatedAt}
+ if rec.ID != nil {
+ dto.ID = *rec.ID
+ }
+ if rec.UserID != nil {
+ dto.UserID = *rec.UserID
+ user, _ := s.ipc.Database.User.GetUserByIDDB(ctx, *rec.UserID)
+ dto.UserName = userName(user)
+ }
+ if rec.Comment != nil {
+ dto.Comment = *rec.Comment
+ }
+ result = append(result, dto)
+ }
+
+ return &typescore.ApiResponseBase{
+ TotalCount: uint64(len(result)),
+ Data: result,
+ }, nil
+}
+
+// ============================================================
+// GET /api/approvals/{id}/observers
+//
+// Наблюдатели НЕ хранятся как связь на самой заявке — они вычисляются по
+// категории/теме через права (см. GetObserversForApprovalDB в
+// telegram_service). Здесь та же логика: сначала получаем код категории
+// темы этой заявки, затем спрашиваем БД.
+// ============================================================
+
+type observerDTO struct {
+ ID uint64 `json:"id"`
+ FullName string `json:"full_name"`
+}
+
+func (s *ApprovalExtrasReg) GetObserversHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ approvalID, err := parseApprovalID(r)
+ if err != nil {
+ return nil, err
+ }
+ ctx := r.Context()
+
+ 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")
+ }
+
+ categoryCode := ""
+ if approval.TopicID != nil {
+ topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID)
+ if err == nil && topic != nil && topic.CategoryID != nil {
+ category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *topic.CategoryID)
+ if err == nil && category != nil && category.Code != nil {
+ categoryCode = *category.Code
+ }
+ }
+ }
+
+ observers, err := s.ipc.Database.User.GetObserversForApprovalDB(ctx, categoryCode, approval.TopicID)
+ if err != nil {
+ return nil, err
+ }
+
+ result := make([]observerDTO, 0, len(observers))
+ for _, obs := range observers {
+ if obs.ID == nil {
+ continue
+ }
+ result = append(result, observerDTO{
+ ID: *obs.ID,
+ FullName: userName(obs),
+ })
+ }
+
+ return &typescore.ApiResponseBase{
+ TotalCount: uint64(len(result)),
+ Data: result,
+ }, nil
+}
+
+// ============================================================
+// GET /api/approvals/{id}/revocation-request
+//
+// Возвращает {"data": null}, если активного (pending) запроса на отзыв нет —
+// это нормальный случай для большинства заявок, не ошибка.
+// ============================================================
+
+type revocationApproverDTO struct {
+ ApproverID uint64 `json:"approver_id"`
+ ApproverName string `json:"approver_name"`
+ Status string `json:"status"`
+}
+
+type revocationRequestDTO struct {
+ ID uint64 `json:"id"`
+ Status string `json:"status"`
+ Reason string `json:"reason,omitempty"`
+ RequestedByID uint64 `json:"requested_by_id"`
+ RequestedByName string `json:"requested_by_name"`
+ Approvers []revocationApproverDTO `json:"approvers"`
+}
+
+func (s *ApprovalExtrasReg) GetRevocationRequestHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ approvalID, err := parseApprovalID(r)
+ if err != nil {
+ return nil, err
+ }
+ ctx := r.Context()
+
+ request, err := s.ipc.Database.ApprovalRevocation.GetPendingRevocationRequestForApprovalDB(ctx, approvalID)
+ if err != nil {
+ return nil, err
+ }
+ if request == nil {
+ return &typescore.ApiResponseBase{Data: nil}, nil
+ }
+
+ dto := revocationRequestDTO{Status: "pending"}
+ if request.ID != nil {
+ dto.ID = *request.ID
+ }
+ if request.Status != nil {
+ dto.Status = *request.Status
+ }
+ if request.Reason != nil {
+ dto.Reason = *request.Reason
+ }
+ if request.RequestedByID != nil {
+ dto.RequestedByID = *request.RequestedByID
+ requestedBy, _ := s.ipc.Database.User.GetUserByIDDB(ctx, *request.RequestedByID)
+ dto.RequestedByName = userName(requestedBy)
+ }
+
+ if request.ID != nil {
+ approvers, err := s.ipc.Database.ApprovalRevocation.GetRevocationApproversByRequestIDDB(ctx, *request.ID)
+ if err == nil {
+ for _, a := range approvers {
+ if a.ApproverID == nil {
+ continue
+ }
+ approverUser, _ := s.ipc.Database.User.GetUserByIDDB(ctx, *a.ApproverID)
+ status := "pending"
+ if a.Status != nil {
+ status = *a.Status
+ }
+ dto.Approvers = append(dto.Approvers, revocationApproverDTO{
+ ApproverID: *a.ApproverID,
+ ApproverName: userName(approverUser),
+ Status: status,
+ })
+ }
+ }
+ }
+
+ return &typescore.ApiResponseBase{Data: dto}, nil
+}
+
+// ============================================================
+// GET /api/approvals/{id}/tasks
+//
+// Две вещи в одном ответе:
+// - topic_executors — что НАСТРОЕНО для темы этой заявки (ApprovalTopicExecutor),
+// нужно для превью "какие задачи будут поставлены после согласования"
+// на pending-заявках, ещё до их фактического создания.
+// - tasks — что РЕАЛЬНО создано (ApprovalTask), уже после согласования.
+// - has_task_error — та же логика, что в отчёте (reportcore.BuildExcelApprovalsReport):
+// если для темы настроены исполнители, заявка уже approved, а задач
+// по факту нет — это ошибка на этапе создания задач, а не "не предусмотрено".
+// ============================================================
+
+type plannedTaskDTO struct {
+ ID uint64 `json:"id"`
+ TaskText string `json:"task_text"`
+ ExecutorName string `json:"executor_name,omitempty"`
+ StepOrder int `json:"step_order"`
+}
+
+type taskDTO struct {
+ ID uint64 `json:"id"`
+ TaskText string `json:"task_text"`
+ ExecutorName string `json:"executor_name"`
+ Status string `json:"status"`
+ CompletedAt *time.Time `json:"completed_at,omitempty"`
+}
+
+type approvalTasksResponse struct {
+ TopicExecutors []plannedTaskDTO `json:"topic_executors"`
+ Tasks []taskDTO `json:"tasks"`
+ HasTaskError bool `json:"has_task_error"`
+}
+
+func (s *ApprovalExtrasReg) GetTasksHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ approvalID, err := parseApprovalID(r)
+ if err != nil {
+ return nil, err
+ }
+ ctx := r.Context()
+
+ 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")
+ }
+
+ resp := &approvalTasksResponse{}
+
+ if approval.TopicID == nil {
+ return &typescore.ApiResponseBase{Data: resp}, nil
+ }
+
+ topicExecutors, err := s.ipc.Database.ApprovalTopicExecutor.GetExecutorsByTopicIDDB(ctx, *approval.TopicID)
+ if err != nil {
+ return nil, err
+ }
+
+ for _, te := range topicExecutors {
+ if te.ID == nil {
+ continue
+ }
+ dto := plannedTaskDTO{ID: *te.ID}
+ if te.TaskText != nil {
+ dto.TaskText = *te.TaskText
+ }
+ if te.StepOrder != nil {
+ dto.StepOrder = *te.StepOrder
+ }
+ if te.UserID != nil {
+ executor, _ := s.ipc.Database.User.GetUserByIDDB(ctx, *te.UserID)
+ dto.ExecutorName = userName(executor)
+ }
+ resp.TopicExecutors = append(resp.TopicExecutors, dto)
+ }
+
+ tasks, _, err := s.ipc.Database.ApprovalTasks.GetApprovalTasksListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalTask{ApprovalID: &approvalID},
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ for _, t := range tasks {
+ if t.ID == nil {
+ continue
+ }
+ dto := taskDTO{ID: *t.ID, Status: "—", CompletedAt: t.CompletedAt}
+ if t.TaskText != nil {
+ dto.TaskText = *t.TaskText
+ }
+ if t.Status != nil {
+ dto.Status = *t.Status
+ }
+ if t.ExecutorID != nil {
+ executor, _ := s.ipc.Database.User.GetUserByIDDB(ctx, *t.ExecutorID)
+ dto.ExecutorName = userName(executor)
+ }
+ resp.Tasks = append(resp.Tasks, dto)
+ }
+
+ if len(topicExecutors) > 0 && len(tasks) == 0 && approval.Status != nil && *approval.Status == "approved" {
+ resp.HasTaskError = true
+ }
+
+ return &typescore.ApiResponseBase{Data: resp}, nil
+}
diff --git a/service/rest_admin_service/handlers/approvals/handlers.go b/service/rest_admin_service/handlers/approvals/handlers.go
index 111d64f..6ac016d 100644
--- a/service/rest_admin_service/handlers/approvals/handlers.go
+++ b/service/rest_admin_service/handlers/approvals/handlers.go
@@ -2,7 +2,7 @@ package approvalshandler
import (
"bitrix_balancer_api/core/typescore"
- "bitrix_balancer_api/core/utilscore"
+ "bitrix_balancer_api/rest_admin_service/handlers"
"context"
"encoding/json"
"errors"
@@ -10,23 +10,30 @@ import (
"io"
"net/http"
"strconv"
+ "strings"
+ "sync"
"time"
"github.com/go-chi/chi/v5"
)
-// GetApprovalsListHandler Получение списка заявок
+// GetApprovalsListHandler Получение списка заявок с расширенной фильтрацией
// @Summary Получение списка заявок
-// @Description Получение списка заявок с пагинацией и фильтрацией
+// @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 status query string false "Фильтр по статусу"
// @Param initiator_id query integer false "Фильтр по инициатору"
-// @Param topic_id query integer false "Фильтр по теме"
+// @Param topic_id query integer false "Фильтр по теме (одна)"
+// @Param topic_ids query string false "Фильтр по темам (через запятую)"
+// @Param category_ids query string false "Фильтр по категориям (через запятую)"
// @Param department_id query integer false "Фильтр по отделу"
+// @Param date_from query string false "Начальная дата (YYYY-MM-DD)"
+// @Param date_to query string false "Конечная дата (YYYY-MM-DD)"
+// @Param content query string false "Поиск по тексту заявки"
// @Success 200 {object} typescore.ApiResponseBase "Успех"
// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос"
// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера"
@@ -34,41 +41,106 @@ import (
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
- }
+ filter := typescore.ApprovalFilter{}
- logrus.Infof("📥 GetApprovalsListHandler params: content=%v, status=%v",
- queryParams.Get("content"), queryParams.Get("status"))
+ if status := queryParams.Get("status"); status != "" {
+ filter.Status = &status
+ }
+ if initiatorIDStr := queryParams.Get("initiator_id"); initiatorIDStr != "" {
+ id, err := strconv.ParseUint(initiatorIDStr, 10, 64)
+ if err != nil {
+ return nil, errors.New("invalid initiator_id")
+ }
+ filter.InitiatorID = &id
+ }
+ if departmentIDStr := queryParams.Get("department_id"); departmentIDStr != "" {
+ id, err := strconv.ParseUint(departmentIDStr, 10, 64)
+ if err != nil {
+ return nil, errors.New("invalid department_id")
+ }
+ filter.DepartmentID = &id
+ }
+ if idStr := queryParams.Get("id"); idStr != "" {
+ id, err := strconv.ParseUint(idStr, 10, 64)
+ if err != nil {
+ return nil, errors.New("invalid id")
+ }
+ filter.ID = &id
+ }
contentSearch := queryParams.Get("content")
-
- approvalParams.Content = nil
-
- if contentSearch != "" && len(contentSearch) < 2 {
- return nil, errors.New("search query must be at least 2 characters")
+ if contentSearch != "" {
+ if len(contentSearch) < 2 {
+ return nil, errors.New("search query must be at least 2 characters")
+ }
+ filter.Content = &contentSearch
}
- options := typescore.ListDbOptions{
- Filtering: approvalParams,
- Offset: offset,
- Limit: limit,
- LikeFields: likeFields,
+ if topicIDsStr := queryParams.Get("topic_ids"); topicIDsStr != "" {
+ ids, err := parseUint64Array(topicIDsStr)
+ if err != nil {
+ return nil, errors.New("invalid topic_ids")
+ }
+ filter.TopicIDs = ids
+ } else if topicIDStr := queryParams.Get("topic_id"); topicIDStr != "" {
+ id, err := strconv.ParseUint(topicIDStr, 10, 64)
+ if err != nil {
+ return nil, errors.New("invalid topic_id")
+ }
+ filter.TopicIDs = []uint64{id}
+ }
+
+ if categoryIDsStr := queryParams.Get("category_ids"); categoryIDsStr != "" {
+ ids, err := parseUint64Array(categoryIDsStr)
+ if err != nil {
+ return nil, errors.New("invalid category_ids")
+ }
+ filter.CategoryIDs = ids
+ }
+
+ 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
+ }
+
+ offset := uint64(0)
+ limit := uint64(100)
+ if offsetStr := queryParams.Get("offset"); offsetStr != "" {
+ if v, err := strconv.ParseUint(offsetStr, 10, 64); err == nil {
+ offset = v
+ }
+ }
+ if limitStr := queryParams.Get("limit"); limitStr != "" {
+ if v, err := strconv.ParseUint(limitStr, 10, 64); err == nil {
+ limit = v
+ }
}
ctx := r.Context()
- var approvalsDbLst []*typescore.Approval
- var total uint64
-
- if contentSearch != "" {
- approvalsDbLst, total, errW = s.ipc.Database.Approval.SearchApprovalsByContentDB(ctx, contentSearch, options)
- } else {
- approvalsDbLst, total, errW = s.ipc.Database.Approval.GetApprovalsListDB(ctx, options)
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok && currentAdmin.IsObserver != nil && *currentAdmin.IsObserver {
+ if currentAdmin.TelegramID != nil && *currentAdmin.TelegramID > 0 {
+ if tgUser, err := s.ipc.Database.User.GetUserByTelegramIDDB(ctx, *currentAdmin.TelegramID); err == nil && tgUser != nil && tgUser.ID != nil {
+ filter.ObserverUserID = tgUser.ID
+ } else {
+ return &typescore.ApiResponseBase{TotalCount: 0, Data: []*typescore.Approval{}}, nil
+ }
+ } else {
+ return &typescore.ApiResponseBase{TotalCount: 0, Data: []*typescore.Approval{}}, nil
+ }
}
+ approvalsDbLst, total, errW := s.ipc.Database.Approval.GetApprovalsListFilteredDB(ctx, filter, offset, limit)
if errW != nil {
logrus.Errorf("❌ GetApprovalsListHandler error: %v", errW)
return nil, errW
@@ -78,9 +150,7 @@ func (s *ApprovalsReg) GetApprovalsListHandler(w http.ResponseWriter, r *http.Re
approvalsDbLst = []*typescore.Approval{}
}
- for _, approval := range approvalsDbLst {
- s.enrichApproval(ctx, approval, false)
- }
+ s.enrichApprovalsBatch(ctx, approvalsDbLst, false)
return &typescore.ApiResponseBase{
TotalCount: total,
@@ -88,6 +158,24 @@ func (s *ApprovalsReg) GetApprovalsListHandler(w http.ResponseWriter, r *http.Re
}, nil
}
+// parseUint64Array — парсит строку "1,2,3" в []uint64
+func parseUint64Array(s string) ([]uint64, error) {
+ parts := strings.Split(s, ",")
+ result := make([]uint64, 0, len(parts))
+ for _, p := range parts {
+ p = strings.TrimSpace(p)
+ if p == "" {
+ continue
+ }
+ v, err := strconv.ParseUint(p, 10, 64)
+ if err != nil {
+ return nil, err
+ }
+ result = append(result, v)
+ }
+ return result, nil
+}
+
// GetApprovalByIDHandler Получение заявки по ID
// @Summary Получение заявки по ID
// @Description Получение детальной информации о заявке по её ID со всеми связанными данными
@@ -258,7 +346,6 @@ func (s *ApprovalsReg) GetApprovalsForReportHandler(w http.ResponseWriter, r *ht
filter := typescore.ReportFilter{}
- // Парсим user_id
if userIDStr := queryParams.Get("user_id"); userIDStr != "" {
userID, err := strconv.ParseUint(userIDStr, 10, 64)
if err != nil {
@@ -267,7 +354,6 @@ func (s *ApprovalsReg) GetApprovalsForReportHandler(w http.ResponseWriter, r *ht
filter.UserID = &userID
}
- // Парсим даты
if dateFromStr := queryParams.Get("date_from"); dateFromStr != "" {
dateFrom, err := time.Parse("2006-01-02", dateFromStr)
if err != nil {
@@ -284,7 +370,6 @@ func (s *ApprovalsReg) GetApprovalsForReportHandler(w http.ResponseWriter, r *ht
filter.DateTo = &dateTo
}
- // Парсим all_access
if allAccessStr := queryParams.Get("all_access"); allAccessStr == "true" {
filter.AllAccess = true
}
@@ -295,10 +380,7 @@ func (s *ApprovalsReg) GetApprovalsForReportHandler(w http.ResponseWriter, r *ht
return nil, err
}
- // Подгружаем связанные данные
- for _, approval := range approvals {
- s.enrichApproval(ctx, approval, false)
- }
+ s.enrichApprovalsBatch(ctx, approvals, false)
return &typescore.ApiResponseBase{
TotalCount: uint64(len(approvals)),
@@ -307,74 +389,115 @@ func (s *ApprovalsReg) GetApprovalsForReportHandler(w http.ResponseWriter, r *ht
}
// enrichApproval подгружает связанные данные для заявки
+// enrichApproval подгружает связанные данные для ОДНОЙ заявки.
+// Независимые запросы выполняются параллельно, чтобы сократить суммарную задержку.
func (s *ApprovalsReg) enrichApproval(ctx context.Context, approval *typescore.Approval, loadSteps bool) {
if approval == nil {
return
}
- // Подгружаем инициатора
+ var wg sync.WaitGroup
+
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 topic.CategoryID != nil {
- category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *topic.CategoryID)
- if err == nil && category != nil {
- topic.Category = category
- }
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ if initiator, err := s.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID); err == nil && initiator != nil {
+ approval.Initiator = initiator
}
- }
+ }()
}
- // Подгружаем отдел
- 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
+ if approval.TopicID != nil {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID)
+ if err == nil && topic != nil {
+ approval.Topic = topic
+ if topic.CategoryID != nil {
+ if category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *topic.CategoryID); err == nil && category != nil {
+ topic.Category = category
}
}
}
- approval.Steps = steps
- }
+ }()
}
+
+ if approval.DepartmentID != nil {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ if department, err := s.ipc.Database.Department.GetDepartmentByIDDB(ctx, *approval.DepartmentID); err == nil && department != nil {
+ approval.Department = department
+ }
+ }()
+ }
+
+ if approval.RevokedByID != nil {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ if revokedBy, err := s.ipc.Database.User.GetUserByIDDB(ctx, *approval.RevokedByID); err == nil && revokedBy != nil {
+ approval.RevokedBy = revokedBy
+ }
+ }()
+ }
+
+ if approval.ID != nil {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ if files, err := s.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID); err == nil {
+ approval.Files = files
+ }
+ }()
+ }
+
+ if loadSteps && approval.ID != nil {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ steps, _, err := s.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalStep{ApprovalID: approval.ID},
+ })
+ if err != nil {
+ return
+ }
+
+ // Согласующие подгружаются одним батч-запросом, а не по одному на шаг
+ approverIDsSet := make(map[uint64]struct{})
+ for _, step := range steps {
+ if step.ApproverID != nil {
+ approverIDsSet[*step.ApproverID] = struct{}{}
+ }
+ }
+ approverIDs := make([]uint64, 0, len(approverIDsSet))
+ for id := range approverIDsSet {
+ approverIDs = append(approverIDs, id)
+ }
+
+ if approvers, err := s.ipc.Database.User.GetUsersByIDsDB(ctx, approverIDs); err == nil {
+ approversMap := make(map[uint64]*typescore.User, len(approvers))
+ for _, u := range approvers {
+ if u.ID != nil {
+ approversMap[*u.ID] = u
+ }
+ }
+ for _, step := range steps {
+ if step.ApproverID != nil {
+ if approver, ok := approversMap[*step.ApproverID]; ok {
+ step.Approver = approver
+ }
+ }
+ }
+ }
+
+ approval.Steps = steps
+ }()
+ }
+
+ wg.Wait()
}
// isValidStatusTransition проверяет валидность перехода между статусами
@@ -401,3 +524,195 @@ func isValidStatusTransition(from, to string) bool {
return false
}
+
+// enrichApprovalsBatch выполняет пакетную подгрузку связанных данных для СПИСКА заявок,
+// заменяя N+1 отдельных запросов (было: enrichApproval в цикле) несколькими батч-запросами.
+func (s *ApprovalsReg) enrichApprovalsBatch(ctx context.Context, approvals []*typescore.Approval, loadSteps bool) {
+ if len(approvals) == 0 {
+ return
+ }
+
+ userIDsSet := make(map[uint64]struct{})
+ topicIDsSet := make(map[uint64]struct{})
+ departmentIDsSet := make(map[uint64]struct{})
+ approvalIDs := make([]uint64, 0, len(approvals))
+
+ for _, a := range approvals {
+ if a.InitiatorID != nil {
+ userIDsSet[*a.InitiatorID] = struct{}{}
+ }
+ if a.RevokedByID != nil {
+ userIDsSet[*a.RevokedByID] = struct{}{}
+ }
+ if a.TopicID != nil {
+ topicIDsSet[*a.TopicID] = struct{}{}
+ }
+ if a.DepartmentID != nil {
+ departmentIDsSet[*a.DepartmentID] = struct{}{}
+ }
+ if a.ID != nil {
+ approvalIDs = append(approvalIDs, *a.ID)
+ }
+ }
+
+ userIDs := make([]uint64, 0, len(userIDsSet))
+ for id := range userIDsSet {
+ userIDs = append(userIDs, id)
+ }
+ topicIDs := make([]uint64, 0, len(topicIDsSet))
+ for id := range topicIDsSet {
+ topicIDs = append(topicIDs, id)
+ }
+ departmentIDs := make([]uint64, 0, len(departmentIDsSet))
+ for id := range departmentIDsSet {
+ departmentIDs = append(departmentIDs, id)
+ }
+
+ usersMap := make(map[uint64]*typescore.User)
+ if users, err := s.ipc.Database.User.GetUsersByIDsDB(ctx, userIDs); err == nil {
+ for _, u := range users {
+ if u.ID != nil {
+ usersMap[*u.ID] = u
+ }
+ }
+ }
+
+ topicsMap := make(map[uint64]*typescore.ApprovalTopic)
+ categoryIDsSet := make(map[uint64]struct{})
+ if topics, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicsByIDsDB(ctx, topicIDs); err == nil {
+ for _, t := range topics {
+ if t.ID != nil {
+ topicsMap[*t.ID] = t
+ }
+ if t.CategoryID != nil {
+ categoryIDsSet[*t.CategoryID] = struct{}{}
+ }
+ }
+ }
+
+ categoryIDs := make([]uint64, 0, len(categoryIDsSet))
+ for id := range categoryIDsSet {
+ categoryIDs = append(categoryIDs, id)
+ }
+ categoriesMap := make(map[uint64]*typescore.ApprovalTopicCategory)
+ if categories, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoriesByIDsDB(ctx, categoryIDs); err == nil {
+ for _, c := range categories {
+ if c.ID != nil {
+ categoriesMap[*c.ID] = c
+ }
+ }
+ }
+ for _, t := range topicsMap {
+ if t.CategoryID != nil {
+ if cat, ok := categoriesMap[*t.CategoryID]; ok {
+ t.Category = cat
+ }
+ }
+ }
+
+ departmentsMap := make(map[uint64]*typescore.Department)
+ if departments, err := s.ipc.Database.Department.GetDepartmentsByIDsDB(ctx, departmentIDs); err == nil {
+ for _, d := range departments {
+ if d.ID != nil {
+ departmentsMap[*d.ID] = d
+ }
+ }
+ }
+
+ filesMap := make(map[uint64][]*typescore.ApprovalFile)
+ if files, err := s.ipc.Database.ApprovalFile.GetFilesByApprovalIDsDB(ctx, approvalIDs); err == nil {
+ for _, f := range files {
+ if f.ApprovalID != nil {
+ filesMap[*f.ApprovalID] = append(filesMap[*f.ApprovalID], f)
+ }
+ }
+ }
+
+ var stepsMap map[uint64][]*typescore.ApprovalStep
+ if loadSteps {
+ stepsMap = make(map[uint64][]*typescore.ApprovalStep)
+ steps, err := s.ipc.Database.ApprovalStep.GetApprovalStepsByApprovalIDsDB(ctx, approvalIDs)
+ if err == nil {
+ approverIDsSet := make(map[uint64]struct{})
+ for _, st := range steps {
+ if st.ApprovalID != nil {
+ stepsMap[*st.ApprovalID] = append(stepsMap[*st.ApprovalID], st)
+ }
+ if st.ApproverID != nil {
+ approverIDsSet[*st.ApproverID] = struct{}{}
+ }
+ }
+
+ approverIDs := make([]uint64, 0, len(approverIDsSet))
+ for id := range approverIDsSet {
+ approverIDs = append(approverIDs, id)
+ }
+ approversMap := make(map[uint64]*typescore.User)
+ if approvers, err := s.ipc.Database.User.GetUsersByIDsDB(ctx, approverIDs); err == nil {
+ for _, u := range approvers {
+ if u.ID != nil {
+ approversMap[*u.ID] = u
+ }
+ }
+ }
+ for _, stepsForApproval := range stepsMap {
+ for _, st := range stepsForApproval {
+ if st.ApproverID != nil {
+ if approver, ok := approversMap[*st.ApproverID]; ok {
+ st.Approver = approver
+ }
+ }
+ }
+ }
+ }
+ }
+
+ for _, a := range approvals {
+ if a.InitiatorID != nil {
+ if u, ok := usersMap[*a.InitiatorID]; ok {
+ a.Initiator = u
+ }
+ }
+ if a.RevokedByID != nil {
+ if u, ok := usersMap[*a.RevokedByID]; ok {
+ a.RevokedBy = u
+ }
+ }
+ if a.TopicID != nil {
+ if t, ok := topicsMap[*a.TopicID]; ok {
+ a.Topic = t
+ }
+ }
+ if a.DepartmentID != nil {
+ if d, ok := departmentsMap[*a.DepartmentID]; ok {
+ a.Department = d
+ }
+ }
+ if a.ID != nil {
+ a.Files = filesMap[*a.ID]
+ if loadSteps {
+ a.Steps = stepsMap[*a.ID]
+ }
+ }
+ }
+}
+
+// getCurrentAdmin извлекает ID из контекста и получает полные данные администратора из БД
+func (s *ApprovalsReg) getCurrentAdmin(ctx context.Context) (*typescore.Admin, bool) {
+ currentUserID, err := handlers.GetIDFromContext(ctx)
+ if err != nil {
+ logrus.Warnf("getCurrentAdmin: GetIDFromContext err=%v", err)
+ return nil, false
+ }
+
+ admins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{
+ Filtering: &typescore.Admin{ID: ¤tUserID},
+ })
+
+ if err != nil || len(admins) == 0 || admins[0] == nil || admins[0].ID == nil {
+ logrus.Warnf("getCurrentAdmin: admin not found for userID=%d err=%v", currentUserID, err)
+ return nil, false
+ }
+
+ return admins[0], true
+}
diff --git a/service/rest_admin_service/handlers/auth/handlers.go b/service/rest_admin_service/handlers/auth/handlers.go
index 91923b5..9625045 100644
--- a/service/rest_admin_service/handlers/auth/handlers.go
+++ b/service/rest_admin_service/handlers/auth/handlers.go
@@ -18,6 +18,21 @@ import (
"github.com/sirupsen/logrus"
)
+// GetServerTimeHandler возвращает текущее серверное время для синхронизации с клиентом
+// @Summary Получить серверное время
+// @Description Публичный endpoint для синхронизации часов клиента с сервером
+// @Tags public
+// @Produce json
+// @Success 200 {object} map[string]interface{}
+// @Router /api/time [get]
+func (s *AuthReg) GetServerTimeHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ now := time.Now().UTC()
+ return map[string]interface{}{
+ "timestamp": now.Unix(),
+ "iso": now.Format(time.RFC3339),
+ }, nil
+}
+
// TokenAuthHandler
// @Summary Авторизация при помощи JWT-токена
// @Description Авторизация при помощи JWT-токена
diff --git a/service/rest_admin_service/handlers/auth/routes.go b/service/rest_admin_service/handlers/auth/routes.go
index eb53fb9..97dd52d 100644
--- a/service/rest_admin_service/handlers/auth/routes.go
+++ b/service/rest_admin_service/handlers/auth/routes.go
@@ -24,9 +24,10 @@ func RegisterAuthRoutes(
ipc: ipc,
}
+ handlers.RegisterRoute(r, http.MethodGet, "/api/time", s.GetServerTimeHandler)
+
r.Route("/api", func(r chi.Router) {
r.Use(handlers.AccessCodeVerifier(ipc.Config))
-
handlers.RegisterRoute(r, http.MethodPost, oauthURLogin, s.LoginByPasswordHandler)
})
diff --git a/service/rest_admin_service/handlers/dashboard/handlers.go b/service/rest_admin_service/handlers/dashboard/handlers.go
index 4cc2cbe..b8b8cb8 100644
--- a/service/rest_admin_service/handlers/dashboard/handlers.go
+++ b/service/rest_admin_service/handlers/dashboard/handlers.go
@@ -4,7 +4,12 @@ import (
"bitrix_balancer_api/core/typescore"
"bitrix_balancer_api/core/utilscore"
"context"
+ "encoding/json"
+ "fmt"
"net/http"
+ "regexp"
+ "strconv"
+ "strings"
"time"
)
@@ -55,15 +60,27 @@ func (s *DashboardReg) GetDashboardStatsHandler(w http.ResponseWriter, r *http.R
})
}
- // === 4. Топ-5 тем по количеству заявок ===
- topTopics := s.getTopTopics(ctx, 5)
+ // === 4. Разбивка по категориям (вместо топ-5 тем) ===
+ categoryBreakdown := s.getCategoryBreakdown(ctx)
- // === 5. Топ-5 согласующих ===
- topApprovers := s.getTopApprovers(ctx, 5)
+ // === 5. Узкие места: согласующие с просроченными заявками (вместо топ-5 по активности) ===
+ bottleneckApprovers := s.getBottleneckApprovers(ctx, 5, 7)
// === 6. Старые pending заявки (>7 дней) ===
oldPendingCount := s.countOldPendingApprovals(ctx, 7)
+ // === 7. 🆕 Задачи: распределение по статусам + динамика за 7 дней ===
+ taskStatusData := s.getTaskStatusData(ctx)
+ taskDailyData := s.getTaskDailyData(ctx)
+
+ // === 8. 🆕 Кто отсутствует сегодня (отгул/отпуск/больничный) ===
+ absentToday := s.getAbsentToday(ctx)
+
+ // === 9. 🆕 Проблемы конфигурации: темы без назначенного порядка
+ // согласования для конкретного пользователя + пользователи вообще
+ // без иерархии в своём отделе ===
+ topicGaps, usersWithoutHierarchy := s.getInitiatorConfigWarnings(ctx)
+
return map[string]interface{}{
"users": map[string]int{
"total": totalUsers,
@@ -80,15 +97,21 @@ func (s *DashboardReg) GetDashboardStatsHandler(w http.ResponseWriter, r *http.R
"total": totalTopics,
"active": activeTopics,
},
- "categories": totalCategories,
- "departments": totalDepartments,
- "roles": totalRoles,
- "executors": totalExecutors,
- "statusData": statusData,
- "dailyData": dailyData,
- "topTopics": topTopics,
- "topApprovers": topApprovers,
- "oldPendingCount": oldPendingCount,
+ "categories": totalCategories,
+ "departments": totalDepartments,
+ "roles": totalRoles,
+ "executors": totalExecutors,
+ "statusData": statusData,
+ "dailyData": dailyData,
+ "categoryBreakdown": categoryBreakdown,
+ "bottleneckApprovers": bottleneckApprovers,
+ "oldPendingCount": oldPendingCount,
+ "oldPendingDays": 7,
+ "taskStatusData": taskStatusData,
+ "taskDailyData": taskDailyData,
+ "absentToday": absentToday,
+ "topicGaps": topicGaps,
+ "usersWithoutHierarchy": usersWithoutHierarchy,
}, nil
}
@@ -125,7 +148,6 @@ func (s *DashboardReg) countApprovalsByStatus(ctx context.Context, status string
}
func (s *DashboardReg) countApprovalsByStatusAndDate(ctx context.Context, status string, date time.Time) int {
- // Получаем все заявки со статусом за сегодня
opts := typescore.ListDbOptions{
Filtering: &typescore.Approval{Status: &status},
Limit: utilscore.PointerToUint64(10000),
@@ -166,7 +188,6 @@ func (s *DashboardReg) countApprovalsCreatedOn(ctx context.Context, date time.Ti
}
func (s *DashboardReg) countApprovalsApprovedOn(ctx context.Context, date time.Time) int {
- // Получаем все шаги согласования со статусом approved за день
opts := typescore.ListDbOptions{
Filtering: &typescore.ApprovalStep{Status: strPtr("approved")},
Limit: utilscore.PointerToUint64(10000),
@@ -176,7 +197,6 @@ func (s *DashboardReg) countApprovalsApprovedOn(ctx context.Context, date time.T
return 0
}
- // Считаем уникальные заявки
uniqueApprovals := make(map[uint64]bool)
target := date.Format("2006-01-02")
for _, step := range steps {
@@ -268,130 +288,79 @@ func (s *DashboardReg) countOldPendingApprovals(ctx context.Context, days int) i
}
// ============================================================
-// Топ-5 тем по количеству заявок
+// Разбивка заявок по категориям (заменяет прежний "топ-5 тем").
// ============================================================
-func (s *DashboardReg) getTopTopics(ctx context.Context, limit int) []map[string]interface{} {
- // Получаем все заявки
- opts := typescore.ListDbOptions{
+func (s *DashboardReg) getCategoryBreakdown(ctx context.Context) []map[string]interface{} {
+ topicOpts := typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalTopic{},
+ Limit: utilscore.PointerToUint64(10000),
+ }
+ topics, _, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, topicOpts)
+ if err != nil {
+ return []map[string]interface{}{}
+ }
+ topicToCategory := make(map[uint64]uint64, len(topics))
+ for _, t := range topics {
+ if t.ID != nil && t.CategoryID != nil {
+ topicToCategory[*t.ID] = *t.CategoryID
+ }
+ }
+
+ categoryOpts := typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalTopicCategory{},
+ Limit: utilscore.PointerToUint64(10000),
+ }
+ categories, _, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryListDB(ctx, categoryOpts)
+ if err != nil {
+ return []map[string]interface{}{}
+ }
+ categoryNames := make(map[uint64]string, len(categories))
+ for _, c := range categories {
+ if c.ID != nil && c.Name != nil {
+ categoryNames[*c.ID] = *c.Name
+ }
+ }
+
+ approvalOpts := typescore.ListDbOptions{
Filtering: &typescore.Approval{},
Limit: utilscore.PointerToUint64(10000),
}
- approvals, _, err := s.ipc.Database.Approval.GetApprovalsListDB(ctx, opts)
+ approvals, _, err := s.ipc.Database.Approval.GetApprovalsListDB(ctx, approvalOpts)
if err != nil {
return []map[string]interface{}{}
}
- // Считаем количество заявок по topic_id
- topicCounts := make(map[uint64]int)
- topicPending := make(map[uint64]int)
+ type catStat struct {
+ total int
+ pending int
+ }
+ byCategory := make(map[uint64]*catStat)
for _, a := range approvals {
if a.TopicID == nil {
continue
}
- topicCounts[*a.TopicID]++
+ categoryID, ok := topicToCategory[*a.TopicID]
+ if !ok {
+ continue
+ }
+ if byCategory[categoryID] == nil {
+ byCategory[categoryID] = &catStat{}
+ }
+ byCategory[categoryID].total++
if a.Status != nil && *a.Status == "pending" {
- topicPending[*a.TopicID]++
+ byCategory[categoryID].pending++
}
}
- // Сортируем по количеству (вручную, без import sort)
- type topicStat struct {
- id uint64
- count int
- pending int
- }
- stats := make([]topicStat, 0, len(topicCounts))
- for id, count := range topicCounts {
- stats = append(stats, topicStat{id: id, count: count, pending: topicPending[id]})
- }
- // Простая сортировка (bubble sort для небольшого N)
- for i := 0; i < len(stats); i++ {
- for j := i + 1; j < len(stats); j++ {
- if stats[j].count > stats[i].count {
- stats[i], stats[j] = stats[j], stats[i]
- }
- }
- }
-
- // Берём топ-N и обогащаем данными
- result := make([]map[string]interface{}, 0, limit)
- for i := 0; i < len(stats) && i < limit; i++ {
- stat := stats[i]
- topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, stat.id)
- if err != nil || topic == nil {
- continue
- }
-
- categoryName := ""
- if topic.CategoryID != nil {
- cat, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *topic.CategoryID)
- if err == nil && cat != nil && cat.Name != nil {
- categoryName = *cat.Name
- }
- }
-
- topicName := ""
- if topic.Name != nil {
- topicName = *topic.Name
- }
-
- result = append(result, map[string]interface{}{
- "id": stat.id,
- "name": topicName,
- "category_name": categoryName,
- "total_count": stat.count,
- "pending_count": stat.pending,
- })
- }
-
- return result
-}
-
-// ============================================================
-// Топ-5 согласующих
-// ============================================================
-
-func (s *DashboardReg) getTopApprovers(ctx context.Context, limit int) []map[string]interface{} {
- // Получаем все шаги согласования
- opts := typescore.ListDbOptions{
- Filtering: &typescore.ApprovalStep{},
- Limit: utilscore.PointerToUint64(10000),
- }
- steps, _, err := s.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, opts)
- if err != nil {
- return []map[string]interface{}{}
- }
-
- // Считаем по approver_id
- type approverStat struct {
- total int
- pending int
- }
- stats := make(map[uint64]*approverStat)
- for _, step := range steps {
- if step.ApproverID == nil {
- continue
- }
- id := *step.ApproverID
- if stats[id] == nil {
- stats[id] = &approverStat{}
- }
- stats[id].total++
- if step.Status != nil && *step.Status == "pending" {
- stats[id].pending++
- }
- }
-
- // Сортируем
- type approverEntry struct {
+ type entry struct {
id uint64
total int
pending int
}
- entries := make([]approverEntry, 0, len(stats))
- for id, st := range stats {
- entries = append(entries, approverEntry{id: id, total: st.total, pending: st.pending})
+ entries := make([]entry, 0, len(byCategory))
+ for id, st := range byCategory {
+ entries = append(entries, entry{id: id, total: st.total, pending: st.pending})
}
for i := 0; i < len(entries); i++ {
for j := i + 1; j < len(entries); j++ {
@@ -401,11 +370,88 @@ func (s *DashboardReg) getTopApprovers(ctx context.Context, limit int) []map[str
}
}
- // Берём топ-N
+ result := make([]map[string]interface{}, 0, len(entries))
+ for _, e := range entries {
+ name := categoryNames[e.id]
+ if name == "" {
+ continue
+ }
+ result = append(result, map[string]interface{}{
+ "id": e.id,
+ "name": name,
+ "total_count": e.total,
+ "pending_count": e.pending,
+ })
+ }
+
+ return result
+}
+
+// ============================================================
+// Узкие места: согласующие с просроченными (>days дней с подачи) заявками.
+// ============================================================
+
+func (s *DashboardReg) getBottleneckApprovers(ctx context.Context, limit int, days int) []map[string]interface{} {
+ stepOpts := typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalStep{Status: strPtr("pending")},
+ Limit: utilscore.PointerToUint64(10000),
+ }
+ steps, _, err := s.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, stepOpts)
+ if err != nil {
+ return []map[string]interface{}{}
+ }
+
+ cutoff := time.Now().AddDate(0, 0, -days)
+
+ type approverStat struct {
+ pendingTotal int
+ overdue int
+ }
+ stats := make(map[uint64]*approverStat)
+
+ for _, step := range steps {
+ if step.ApproverID == nil || step.ApprovalID == nil {
+ continue
+ }
+ approval, err := s.ipc.Database.Approval.GetApprovalByIDDB(ctx, *step.ApprovalID)
+ if err != nil || approval == nil || approval.CreatedAt == nil {
+ continue
+ }
+
+ id := *step.ApproverID
+ if stats[id] == nil {
+ stats[id] = &approverStat{}
+ }
+ stats[id].pendingTotal++
+ if approval.CreatedAt.Before(cutoff) {
+ stats[id].overdue++
+ }
+ }
+
+ type entry struct {
+ id uint64
+ pendingTotal int
+ overdue int
+ }
+ entries := make([]entry, 0, len(stats))
+ for id, st := range stats {
+ if st.overdue == 0 {
+ continue
+ }
+ entries = append(entries, entry{id: id, pendingTotal: st.pendingTotal, overdue: st.overdue})
+ }
+ for i := 0; i < len(entries); i++ {
+ for j := i + 1; j < len(entries); j++ {
+ if entries[j].overdue > entries[i].overdue {
+ entries[i], entries[j] = entries[j], entries[i]
+ }
+ }
+ }
+
result := make([]map[string]interface{}, 0, limit)
for i := 0; i < len(entries) && i < limit; i++ {
- entry := entries[i]
- user, err := s.ipc.Database.User.GetUserByIDDB(ctx, entry.id)
+ e := entries[i]
+ user, err := s.ipc.Database.User.GetUserByIDDB(ctx, e.id)
if err != nil || user == nil {
continue
}
@@ -424,16 +470,439 @@ func (s *DashboardReg) getTopApprovers(ctx context.Context, limit int) []map[str
}
result = append(result, map[string]interface{}{
- "user_id": entry.id,
+ "user_id": e.id,
"full_name": fullName,
"department_name": deptName,
- "total_steps": entry.total,
- "pending_steps": entry.pending,
+ "pending_total": e.pendingTotal,
+ "overdue_count": e.overdue,
})
}
return result
}
+// ============================================================
+// 🆕 Задачи: распределение по статусам + динамика за 7 дней.
+// Полностью аналогично разделам про заявки — те же графики, другая
+// таблица (ApprovalTask вместо Approval).
+// ============================================================
+
+func (s *DashboardReg) getTaskStatusData(ctx context.Context) []map[string]interface{} {
+ statuses := []string{"pending", "waiting", "completed", "cancelled"}
+ result := make([]map[string]interface{}, 0, len(statuses))
+ for _, status := range statuses {
+ st := status
+ opts := typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalTask{Status: &st},
+ Limit: utilscore.PointerToUint64(10000),
+ }
+ list, _, err := s.ipc.Database.ApprovalTasks.GetApprovalTasksListDB(ctx, opts)
+ count := 0
+ if err == nil {
+ count = len(list)
+ }
+ result = append(result, map[string]interface{}{
+ "status": status,
+ "count": count,
+ })
+ }
+ return result
+}
+
+func (s *DashboardReg) getTaskDailyData(ctx context.Context) []map[string]interface{} {
+ opts := typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalTask{},
+ Limit: utilscore.PointerToUint64(10000),
+ }
+ tasks, _, err := s.ipc.Database.ApprovalTasks.GetApprovalTasksListDB(ctx, opts)
+ if err != nil {
+ tasks = nil
+ }
+
+ result := make([]map[string]interface{}, 0, 7)
+ now := time.Now()
+ for i := 6; i >= 0; i-- {
+ date := now.AddDate(0, 0, -i)
+ target := date.Format("2006-01-02")
+
+ created := 0
+ completed := 0
+ for _, t := range tasks {
+ if t.CreatedAt != nil && t.CreatedAt.Format("2006-01-02") == target {
+ created++
+ }
+ if t.CompletedAt != nil && t.CompletedAt.Format("2006-01-02") == target {
+ completed++
+ }
+ }
+
+ result = append(result, map[string]interface{}{
+ "date": target,
+ "created": created,
+ "completed": completed,
+ })
+ }
+ return result
+}
+
+// ============================================================
+// 🆕 Кто отсутствует сегодня (отгул/отпуск/больничный).
+//
+// 🩹 Логика разбора дат намеренно продублирована из
+// scheduler/daily_reminder.go (getAbsentEmployeesToday) — тот же самый
+// терпимый к опечаткам подход через regexp, т.к. у заявок на отсутствие
+// нет отдельного структурированного поля с датами. rest_admin_service
+// использует свой ipc-тип, отличный от telegram_service, поэтому
+// переиспользовать функцию напрямую нельзя — общий пакет пока не заводили.
+//
+// Упрощение по сравнению с ботом: здесь НЕ подмешивается контакт-делегат
+// (ApprovalDelegation) — просто список отсутствующих с описанием.
+// ============================================================
+
+type dashboardAbsenceMetadata struct {
+ Extra struct {
+ TimeType string `json:"time_type"`
+ AbsenceType string `json:"absence_type"`
+ } `json:"extra"`
+}
+
+var dashboardAbsenceDateRe = regexp.MustCompile(`(\d{1,2})[.,](\d{1,2})\.(\d{4})`)
+var dashboardAbsenceTimeRe = regexp.MustCompile(`(?:с|от)\s*(\d{1,2})[:\.](\d{2})\s*(?:до|по|-|—|–)\s*(\d{1,2})[:\.](\d{2})`)
+
+func (s *DashboardReg) getAbsentToday(ctx context.Context) []map[string]interface{} {
+ loc, err := time.LoadLocation("Europe/Moscow")
+ if err != nil {
+ loc = time.FixedZone("MSK", 3*3600)
+ }
+ today := time.Now().In(loc)
+ todayY, todayM, todayD := today.Date()
+
+ approvals, _, err := s.ipc.Database.Approval.GetApprovalsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.Approval{Status: strPtr("approved")},
+ Limit: utilscore.PointerToUint64(10000),
+ })
+ if err != nil {
+ return []map[string]interface{}{}
+ }
+
+ seenUsers := make(map[uint64]bool)
+ result := []map[string]interface{}{}
+
+ for _, a := range approvals {
+ if a.Metadata == nil || *a.Metadata == "" || a.Content == nil || a.InitiatorID == nil {
+ continue
+ }
+ if seenUsers[*a.InitiatorID] {
+ continue
+ }
+
+ var meta dashboardAbsenceMetadata
+ if err := json.Unmarshal([]byte(*a.Metadata), &meta); err != nil || meta.Extra.AbsenceType == "" {
+ continue
+ }
+
+ dates := parseDashboardAbsenceDates(*a.Content)
+ if len(dates) == 0 || !dashboardAbsenceCoversDate(dates, *a.Content, todayY, todayM, todayD) {
+ continue
+ }
+
+ name := ""
+ if user, uErr := s.ipc.Database.User.GetUserByIDDB(ctx, *a.InitiatorID); uErr == nil && user != nil && user.FullName != nil {
+ name = *user.FullName
+ }
+
+ var description string
+ switch meta.Extra.AbsenceType {
+ case "timeoff":
+ if meta.Extra.TimeType == "partial" {
+ if mm := dashboardAbsenceTimeRe.FindStringSubmatch(*a.Content); mm != nil {
+ description = "отгул с " + mm[1] + ":" + mm[2] + " до " + mm[3] + ":" + mm[4]
+ } else {
+ description = "отгул весь день"
+ }
+ } else {
+ description = "отгул весь день"
+ }
+ case "vacation":
+ description = "отпуск до " + maxDashboardAbsenceDate(dates).Format("02.01.2006")
+ case "sickleave":
+ description = "больничный до " + maxDashboardAbsenceDate(dates).Format("02.01.2006")
+ default:
+ description = "отсутствует"
+ }
+
+ seenUsers[*a.InitiatorID] = true
+ result = append(result, map[string]interface{}{
+ "name": name,
+ "description": description,
+ })
+ }
+
+ return result
+}
+
+func parseDashboardAbsenceDates(content string) []time.Time {
+ matches := dashboardAbsenceDateRe.FindAllStringSubmatch(content, -1)
+ var dates []time.Time
+ for _, m := range matches {
+ day, errD := strconv.Atoi(m[1])
+ month, errM := strconv.Atoi(m[2])
+ year, errY := strconv.Atoi(m[3])
+ if errD != nil || errM != nil || errY != nil {
+ continue
+ }
+ if month < 1 || month > 12 || day < 1 || day > 31 {
+ continue
+ }
+ dates = append(dates, time.Date(year, time.Month(month), day, 0, 0, 0, 0, time.UTC))
+ }
+ return dates
+}
+
+func dashboardAbsenceCoversDate(dates []time.Time, content string, y int, m time.Month, d int) bool {
+ target := time.Date(y, m, d, 0, 0, 0, 0, time.UTC)
+ if len(dates) == 2 && strings.Contains(content, "-") {
+ start, end := dates[0], dates[1]
+ if end.Before(start) {
+ start, end = end, start
+ }
+ return !target.Before(start) && !target.After(end)
+ }
+ for _, dt := range dates {
+ if dt.Equal(target) {
+ return true
+ }
+ }
+ return false
+}
+
+func maxDashboardAbsenceDate(dates []time.Time) time.Time {
+ max := dates[0]
+ for _, d := range dates[1:] {
+ if d.After(max) {
+ max = d
+ }
+ }
+ return max
+}
+
+// ============================================================
+// 🆕 Проблемы конфигурации инициаторов.
+//
+// Воспроизводит ТУ ЖЕ логику резолва согласующих, что и сам бот при
+// реальной отправке заявки (submitApproval → UserHierarchy по
+// SubordinateID+DepartmentID, с приоритетом TopicID → TopicCategoryID →
+// глобальное правило) — но заранее, для ВСЕХ пользователей и ВСЕХ тем,
+// на которые у них есть право "create", чтобы найти дыры ДО того, как
+// сотрудник наткнётся на них в боте ("⚠️ Для вас в данной теме не
+// настроены согласующие").
+//
+// Возвращает два среза:
+// 1. topicGaps — точечные пробелы: у пользователя ЕСТЬ право создавать
+// заявку по теме, но НИ ОДНО правило иерархии её не покрывает.
+// 2. usersWithoutHierarchy — более базовый случай: у пользователя нет
+// вообще ни одной строки UserHierarchy для его отдела (полностью
+// не настроен, даже глобального правила нет).
+//
+// ⚠️ Предположения, которые стоит проверить при первом запуске:
+// - Permission.GetUserPermissionsDB(ctx, userID, "create") доступен
+// из rest_admin_service так же, как используется ботом
+// (telegram_service/handlers/approval, getAllowedTopicCodes) —
+// сама структура Permission (поля TopicID/TopicCategoryID) взята
+// оттуда же, полностью структуру Permission я не видел.
+// - Пользователи без DepartmentID пропускаются целиком (это отдельная,
+// более базовая проблема — некому резолвить иерархию в принципе,
+// не про конкретные темы).
+// ============================================================
+
+func (s *DashboardReg) getInitiatorConfigWarnings(ctx context.Context) ([]map[string]interface{}, []map[string]interface{}) {
+ users, _, err := s.ipc.Database.User.GetUsersListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.User{IsBlocked: boolPtr(false), IsFired: boolPtr(false)},
+ Limit: utilscore.PointerToUint64(10000),
+ })
+ if err != nil {
+ return []map[string]interface{}{}, []map[string]interface{}{}
+ }
+
+ topics, _, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalTopic{IsActive: boolPtr(true)},
+ Limit: utilscore.PointerToUint64(10000),
+ })
+ if err != nil {
+ return []map[string]interface{}{}, []map[string]interface{}{}
+ }
+
+ categories, _, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryListDB(ctx, typescore.ListDbOptions{
+ Limit: utilscore.PointerToUint64(10000),
+ })
+ categoryNames := make(map[uint64]string, len(categories))
+ if err == nil {
+ for _, c := range categories {
+ if c.ID != nil && c.Name != nil {
+ categoryNames[*c.ID] = *c.Name
+ }
+ }
+ }
+
+ departments, _, err := s.ipc.Database.Department.GetDepartmentsListDB(ctx, typescore.ListDbOptions{
+ Limit: utilscore.PointerToUint64(10000),
+ })
+ departmentNames := make(map[uint64]string, len(departments))
+ if err == nil {
+ for _, d := range departments {
+ if d.ID != nil && d.Name != nil {
+ departmentNames[*d.ID] = *d.Name
+ }
+ }
+ }
+
+ topicByID := make(map[uint64]*typescore.ApprovalTopic, len(topics))
+ topicsByCategory := make(map[uint64][]*typescore.ApprovalTopic)
+ for _, t := range topics {
+ if t.ID == nil {
+ continue
+ }
+ topicByID[*t.ID] = t
+ if t.CategoryID != nil {
+ topicsByCategory[*t.CategoryID] = append(topicsByCategory[*t.CategoryID], t)
+ }
+ }
+
+ hierarchies, _, err := s.ipc.Database.UserHierarchy.GetUserHierarchyListDB(ctx, typescore.ListDbOptions{
+ Limit: utilscore.PointerToUint64(10000),
+ })
+ if err != nil {
+ return []map[string]interface{}{}, []map[string]interface{}{}
+ }
+
+ type coverage struct {
+ topics map[uint64]bool
+ categories map[uint64]bool
+ global bool
+ }
+ coverageKey := func(userID, deptID uint64) string {
+ return fmt.Sprintf("%d:%d", userID, deptID)
+ }
+ coverageByUserDept := make(map[string]*coverage)
+ for _, h := range hierarchies {
+ if h.SubordinateID == nil || h.DepartmentID == nil {
+ continue
+ }
+ k := coverageKey(*h.SubordinateID, *h.DepartmentID)
+ cov, ok := coverageByUserDept[k]
+ if !ok {
+ cov = &coverage{topics: map[uint64]bool{}, categories: map[uint64]bool{}}
+ coverageByUserDept[k] = cov
+ }
+ switch {
+ case h.TopicID != nil:
+ cov.topics[*h.TopicID] = true
+ case h.TopicCategoryID != nil:
+ cov.categories[*h.TopicCategoryID] = true
+ default:
+ cov.global = true
+ }
+ }
+
+ isCovered := func(userID, deptID, topicID uint64, categoryID *uint64) bool {
+ cov, ok := coverageByUserDept[coverageKey(userID, deptID)]
+ if !ok {
+ return false
+ }
+ if cov.global {
+ return true
+ }
+ if cov.topics[topicID] {
+ return true
+ }
+ if categoryID != nil && cov.categories[*categoryID] {
+ return true
+ }
+ return false
+ }
+
+ var topicGaps []map[string]interface{}
+ var usersWithoutHierarchy []map[string]interface{}
+
+ for _, user := range users {
+ if user.ID == nil || user.DepartmentID == nil {
+ continue
+ }
+
+ perms, err := s.ipc.Database.Permission.GetUserPermissionsDB(ctx, *user.ID, "create")
+ if err != nil || len(perms) == 0 {
+ continue // нет права создавать ничего — не наша забота здесь
+ }
+
+ userName := ""
+ if user.FullName != nil {
+ userName = *user.FullName
+ }
+ deptName := departmentNames[*user.DepartmentID]
+
+ // --- Проверка "вообще нет иерархии для этого отдела" ---
+ if _, hasAny := coverageByUserDept[coverageKey(*user.ID, *user.DepartmentID)]; !hasAny {
+ usersWithoutHierarchy = append(usersWithoutHierarchy, map[string]interface{}{
+ "user_id": *user.ID,
+ "full_name": userName,
+ "department_name": deptName,
+ })
+ continue // если вообще ничего нет — детальный разбор по темам избыточен
+ }
+
+ // --- Точечные пробелы по темам ---
+ allowedTopicIDs := make(map[uint64]bool)
+ for _, p := range perms {
+ if p.TopicID != nil {
+ allowedTopicIDs[*p.TopicID] = true
+ }
+ if p.TopicCategoryID != nil {
+ for _, t := range topicsByCategory[*p.TopicCategoryID] {
+ if t.ID != nil {
+ allowedTopicIDs[*t.ID] = true
+ }
+ }
+ }
+ }
+
+ for topicID := range allowedTopicIDs {
+ topic := topicByID[topicID]
+ if topic == nil {
+ continue
+ }
+ if isCovered(*user.ID, *user.DepartmentID, topicID, topic.CategoryID) {
+ continue
+ }
+
+ topicName := ""
+ if topic.Name != nil {
+ topicName = *topic.Name
+ }
+ categoryName := ""
+ if topic.CategoryID != nil {
+ categoryName = categoryNames[*topic.CategoryID]
+ }
+
+ topicGaps = append(topicGaps, map[string]interface{}{
+ "user_id": *user.ID,
+ "full_name": userName,
+ "department_name": deptName,
+ "topic_id": topicID,
+ "topic_name": topicName,
+ "category_name": categoryName,
+ })
+ }
+ }
+
+ if topicGaps == nil {
+ topicGaps = []map[string]interface{}{}
+ }
+ if usersWithoutHierarchy == nil {
+ usersWithoutHierarchy = []map[string]interface{}{}
+ }
+
+ return topicGaps, usersWithoutHierarchy
+}
+
func boolPtr(b bool) *bool { return &b }
func strPtr(s string) *string { return &s }
diff --git a/service/rest_admin_service/handlers/departments/handlers.go b/service/rest_admin_service/handlers/departments/handlers.go
index e25c6ed..e5e2042 100644
--- a/service/rest_admin_service/handlers/departments/handlers.go
+++ b/service/rest_admin_service/handlers/departments/handlers.go
@@ -3,12 +3,17 @@ package departmentshandler
import (
"bitrix_balancer_api/core/typescore"
"bitrix_balancer_api/core/utilscore"
+ "bitrix_balancer_api/rest_admin_service/handlers"
+ adminloghandler "bitrix_balancer_api/rest_admin_service/handlers/admin_actions"
+ "context"
"encoding/json"
"errors"
+ "fmt"
"github.com/sirupsen/logrus"
"io"
"net/http"
"strconv"
+ "strings"
"github.com/go-chi/chi/v5"
)
@@ -115,7 +120,6 @@ func (s *DepartmentsReg) CreateDepartmentHandler(w http.ResponseWriter, r *http.
return nil, errors.New("invalid request body")
}
- // Валидация обязательных полей
if req.Name == nil || *req.Name == "" {
return nil, errors.New("department name is required")
}
@@ -123,7 +127,6 @@ func (s *DepartmentsReg) CreateDepartmentHandler(w http.ResponseWriter, r *http.
return nil, errors.New("department code is required")
}
- // Проверяем, что код уникален
ctx := r.Context()
existingDepts, _, err := s.ipc.Database.Department.GetDepartmentsListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.Department{Code: req.Code},
@@ -135,7 +138,6 @@ func (s *DepartmentsReg) CreateDepartmentHandler(w http.ResponseWriter, r *http.
return nil, errors.New("department code already exists")
}
- // Устанавливаем is_active по умолчанию, если не указано
if req.IsActive == nil {
isActive := true
req.IsActive = &isActive
@@ -146,6 +148,21 @@ func (s *DepartmentsReg) CreateDepartmentHandler(w http.ResponseWriter, r *http.
return nil, err
}
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ snapshot := map[string]interface{}{
+ "name": utilscore.DerefStr(createdDept.Name),
+ "code": utilscore.DerefStr(createdDept.Code),
+ "is_active": utilscore.DerefBool(createdDept.IsActive),
+ }
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "create", "department", createdDept.ID,
+ fmt.Sprintf("Создан отдел «%s»", utilscore.DerefStr(createdDept.Name)),
+ map[string]interface{}{"snapshot": snapshot},
+ )
+ }
+
return createdDept, nil
}
@@ -179,7 +196,6 @@ func (s *DepartmentsReg) UpdateDepartmentHandler(w http.ResponseWriter, r *http.
return nil, errors.New("department id is required")
}
- // Проверяем, что отдел существует
ctx := r.Context()
existingDept, err := s.ipc.Database.Department.GetDepartmentByIDDB(ctx, *req.ID)
if err != nil {
@@ -189,7 +205,6 @@ func (s *DepartmentsReg) UpdateDepartmentHandler(w http.ResponseWriter, r *http.
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{
@@ -204,11 +219,49 @@ func (s *DepartmentsReg) UpdateDepartmentHandler(w http.ResponseWriter, r *http.
}
}
+ type fieldChange struct {
+ Field string `json:"field"`
+ Old interface{} `json:"old"`
+ New interface{} `json:"new"`
+ }
+ var changes []fieldChange
+ var summary []string
+
+ if req.Name != nil && !utilscore.StrEq(existingDept.Name, req.Name) {
+ changes = append(changes, fieldChange{"name", utilscore.DerefStr(existingDept.Name), *req.Name})
+ summary = append(summary, fmt.Sprintf("название: «%s» → «%s»", utilscore.DerefStr(existingDept.Name), *req.Name))
+ }
+ if req.Code != nil && !utilscore.StrEq(existingDept.Code, req.Code) {
+ changes = append(changes, fieldChange{"code", utilscore.DerefStr(existingDept.Code), *req.Code})
+ summary = append(summary, fmt.Sprintf("код: «%s» → «%s»", utilscore.DerefStr(existingDept.Code), *req.Code))
+ }
+ if req.IsActive != nil && !utilscore.BoolEq(existingDept.IsActive, req.IsActive) {
+ changes = append(changes, fieldChange{"is_active", utilscore.DerefBool(existingDept.IsActive), *req.IsActive})
+ if *req.IsActive {
+ summary = append(summary, "активирован")
+ } else {
+ summary = append(summary, "деактивирован")
+ }
+ }
+
updatedDept, _, err := s.ipc.Database.Department.UpdateDepartmentDB(ctx, nil, &req, true)
if err != nil {
return nil, err
}
+ if len(changes) > 0 {
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ description := fmt.Sprintf("Изменён отдел «%s»: %s", utilscore.DerefStr(existingDept.Name), strings.Join(summary, "; "))
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "update", "department", req.ID,
+ description,
+ map[string]interface{}{"changes": changes},
+ )
+ }
+ }
+
return updatedDept, nil
}
@@ -242,7 +295,6 @@ func (s *DepartmentsReg) DeleteDepartmentHandler(w http.ResponseWriter, r *http.
return nil, errors.New("department id is required")
}
- // Проверяем, что отдел существует
ctx := r.Context()
existingDept, err := s.ipc.Database.Department.GetDepartmentByIDDB(ctx, *req.ID)
if err != nil {
@@ -257,5 +309,36 @@ func (s *DepartmentsReg) DeleteDepartmentHandler(w http.ResponseWriter, r *http.
return nil, err
}
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ snapshot := map[string]interface{}{
+ "name": utilscore.DerefStr(existingDept.Name),
+ "code": utilscore.DerefStr(existingDept.Code),
+ "is_active": utilscore.DerefBool(existingDept.IsActive),
+ }
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "delete", "department", req.ID,
+ fmt.Sprintf("Удалён отдел «%s»", utilscore.DerefStr(existingDept.Name)),
+ map[string]interface{}{"snapshot": snapshot},
+ )
+ }
+
return true, nil
}
+
+func (s *DepartmentsReg) getCurrentAdmin(ctx context.Context) (*typescore.Admin, bool) {
+ currentUserID, err := handlers.GetIDFromContext(ctx)
+ if err != nil {
+ return nil, false
+ }
+
+ admins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{
+ Filtering: &typescore.Admin{ID: ¤tUserID},
+ })
+ if err != nil || len(admins) == 0 || admins[0] == nil || admins[0].ID == nil || admins[0].Login == nil {
+ return nil, false
+ }
+
+ return admins[0], true
+}
diff --git a/service/rest_admin_service/handlers/flow_nodes/handler.go b/service/rest_admin_service/handlers/flow_nodes/handler.go
new file mode 100644
index 0000000..3d68369
--- /dev/null
+++ b/service/rest_admin_service/handlers/flow_nodes/handler.go
@@ -0,0 +1,837 @@
+package nodeshandler
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/core/utilscore"
+ "bitrix_balancer_api/rest_admin_service/handlers"
+ adminloghandler "bitrix_balancer_api/rest_admin_service/handlers/admin_actions"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "strconv"
+
+ "github.com/go-chi/chi/v5"
+)
+
+func (s *FlowNodesReg) GetFlowNodesByCategoryIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ categoryIDStr := chi.URLParam(r, "category_id")
+ categoryID, err := strconv.ParseUint(categoryIDStr, 10, 64)
+ if err != nil {
+ return nil, errors.New("invalid category_id")
+ }
+
+ ctx := r.Context()
+
+ category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, categoryID)
+ if err != nil {
+ return nil, err
+ }
+ if category == nil {
+ return nil, errors.New("category not found")
+ }
+
+ nodes, _, err := s.ipc.Database.ApprovalFlowNode.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalFlowNode{CategoryID: &categoryID},
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ tree := s.buildTreeFromNodes(nodes)
+
+ return &typescore.ApiResponseBase{
+ TotalCount: uint64(len(nodes)),
+ Data: tree,
+ }, nil
+}
+
+func (s *FlowNodesReg) GetFlowNodeByIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ idStr := chi.URLParam(r, "id")
+ if idStr == "" {
+ return nil, errors.New("node id is required")
+ }
+
+ id, err := strconv.ParseUint(idStr, 10, 64)
+ if err != nil {
+ return nil, errors.New("invalid node id")
+ }
+
+ ctx := r.Context()
+ node, err := s.ipc.Database.ApprovalFlowNode.GetFlowNodeByIDDB(ctx, id)
+ if err != nil {
+ return nil, err
+ }
+ if node == nil {
+ return nil, errors.New("node not found")
+ }
+
+ return node, nil
+}
+
+func (s *FlowNodesReg) CreateFlowNodeHandler(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.ApprovalFlowNode
+ if err := json.Unmarshal(body, &req); err != nil {
+ return nil, errors.New("invalid request body")
+ }
+
+ if req.CategoryID == nil {
+ return nil, errors.New("category_id is required")
+ }
+ if req.Key == nil || *req.Key == "" {
+ return nil, errors.New("key is required")
+ }
+ if req.Label == nil || *req.Label == "" {
+ return nil, errors.New("label is required")
+ }
+
+ ctx := r.Context()
+
+ 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.ParentID != nil {
+ parent, err := s.ipc.Database.ApprovalFlowNode.GetFlowNodeByIDDB(ctx, *req.ParentID)
+ if err != nil {
+ return nil, err
+ }
+ if parent == nil {
+ return nil, errors.New("parent node not found")
+ }
+ if parent.CategoryID == nil || *parent.CategoryID != *req.CategoryID {
+ return nil, errors.New("parent node belongs to a different category")
+ }
+ }
+
+ existing, _, err := s.ipc.Database.ApprovalFlowNode.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalFlowNode{
+ CategoryID: req.CategoryID,
+ Key: req.Key,
+ },
+ })
+ if err != nil {
+ return nil, err
+ }
+ if len(existing) > 0 {
+ return nil, fmt.Errorf("node with key '%s' already exists in this category", *req.Key)
+ }
+
+ if req.IsInput == nil {
+ v := false
+ req.IsInput = &v
+ }
+ if req.IsMultiSelect == nil {
+ v := false
+ req.IsMultiSelect = &v
+ }
+ if req.SortOrder == nil {
+ v := 0
+ req.SortOrder = &v
+ }
+
+ created, _, err := s.ipc.Database.ApprovalFlowNode.CreateApprovalFlowNodeDB(ctx, nil, &req, true)
+ if err != nil {
+ return nil, err
+ }
+
+ s.bumpFlowVersion(ctx)
+
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ snapshot := map[string]interface{}{
+ "key": utilscore.DerefStr(created.Key),
+ "label": utilscore.DerefStr(created.Label),
+ "category_id": *req.CategoryID,
+ }
+ if created.ParentID != nil {
+ snapshot["parent_id"] = *created.ParentID
+ }
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "create", "flow_node", created.ID,
+ fmt.Sprintf("Создан узел «%s» (%s)", utilscore.DerefStr(created.Label), utilscore.DerefStr(created.Key)),
+ map[string]interface{}{"snapshot": snapshot},
+ )
+ }
+
+ return created, nil
+}
+
+func (s *FlowNodesReg) UpdateFlowNodeHandler(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.ApprovalFlowNode
+ if err := json.Unmarshal(body, &req); err != nil {
+ return nil, errors.New("invalid request body")
+ }
+
+ if req.ID == nil {
+ return nil, errors.New("id is required")
+ }
+
+ ctx := r.Context()
+
+ existing, err := s.ipc.Database.ApprovalFlowNode.GetFlowNodeByIDDB(ctx, *req.ID)
+ if err != nil {
+ return nil, err
+ }
+ if existing == nil {
+ return nil, errors.New("node not found")
+ }
+
+ if req.ParentID != nil && (existing.ParentID == nil || *existing.ParentID != *req.ParentID) {
+ parent, err := s.ipc.Database.ApprovalFlowNode.GetFlowNodeByIDDB(ctx, *req.ParentID)
+ if err != nil {
+ return nil, err
+ }
+ if parent == nil {
+ return nil, errors.New("parent node not found")
+ }
+ if parent.CategoryID == nil || existing.CategoryID == nil || *parent.CategoryID != *existing.CategoryID {
+ return nil, errors.New("parent node belongs to a different category")
+ }
+ if err := s.checkNoCyclicReference(ctx, *req.ID, *req.ParentID); err != nil {
+ return nil, err
+ }
+ }
+
+ if req.Key != nil && *req.Key != "" {
+ if existing.Key == nil || *existing.Key != *req.Key {
+ categoryID := existing.CategoryID
+ if req.CategoryID != nil {
+ categoryID = req.CategoryID
+ }
+ existingNodes, _, err := s.ipc.Database.ApprovalFlowNode.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalFlowNode{
+ CategoryID: categoryID,
+ Key: req.Key,
+ },
+ })
+ if err != nil {
+ return nil, err
+ }
+ if len(existingNodes) > 0 {
+ return nil, fmt.Errorf("node with key '%s' already exists in this category", *req.Key)
+ }
+ }
+ }
+
+ type fieldChange struct {
+ Field string `json:"field"`
+ Old interface{} `json:"old"`
+ New interface{} `json:"new"`
+ }
+ var changes []fieldChange
+
+ if req.Key != nil && !utilscore.StrEq(existing.Key, req.Key) {
+ changes = append(changes, fieldChange{"key", utilscore.DerefStr(existing.Key), *req.Key})
+ }
+ if req.Label != nil && !utilscore.StrEq(existing.Label, req.Label) {
+ changes = append(changes, fieldChange{"label", utilscore.DerefStr(existing.Label), *req.Label})
+ }
+ if req.DataKey != nil && !utilscore.StrEq(existing.DataKey, req.DataKey) {
+ changes = append(changes, fieldChange{"data_key", utilscore.DerefStr(existing.DataKey), *req.DataKey})
+ }
+ if req.DataValue != nil && !utilscore.StrEq(existing.DataValue, req.DataValue) {
+ changes = append(changes, fieldChange{"data_value", utilscore.DerefStr(existing.DataValue), *req.DataValue})
+ }
+ if req.MessageTemplate != nil && !utilscore.StrEq(existing.MessageTemplate, req.MessageTemplate) {
+ changes = append(changes, fieldChange{"message_template", utilscore.DerefStr(existing.MessageTemplate), *req.MessageTemplate})
+ }
+ if req.CodeTemplate != nil && !utilscore.StrEq(existing.CodeTemplate, req.CodeTemplate) {
+ changes = append(changes, fieldChange{"code_template", utilscore.DerefStr(existing.CodeTemplate), *req.CodeTemplate})
+ }
+ if req.SortOrder != nil && !utilscore.IntEq(existing.SortOrder, req.SortOrder) {
+ var oldVal interface{}
+ if existing.SortOrder != nil {
+ oldVal = *existing.SortOrder
+ }
+ changes = append(changes, fieldChange{"sort_order", oldVal, *req.SortOrder})
+ }
+ if req.ParentID != nil && !utilscore.Uint64Eq(existing.ParentID, req.ParentID) {
+ var oldVal interface{}
+ if existing.ParentID != nil {
+ oldVal = *existing.ParentID
+ }
+ changes = append(changes, fieldChange{"parent_id", oldVal, *req.ParentID})
+ }
+
+ updated, _, err := s.ipc.Database.ApprovalFlowNode.UpdateApprovalFlowNodeDB(ctx, nil, &req, true)
+ if err != nil {
+ return nil, err
+ }
+
+ s.bumpFlowVersion(ctx)
+
+ if len(changes) > 0 {
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "update", "flow_node", req.ID,
+ fmt.Sprintf("Изменён узел «%s»", utilscore.DerefStr(existing.Label)),
+ map[string]interface{}{"changes": changes},
+ )
+ }
+ }
+
+ return updated, nil
+}
+
+func (s *FlowNodesReg) DeleteFlowNodeHandler(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.ApprovalFlowNode
+ if err := json.Unmarshal(body, &req); err != nil {
+ return nil, errors.New("invalid request body")
+ }
+
+ if req.ID == nil {
+ return nil, errors.New("id is required")
+ }
+
+ ctx := r.Context()
+
+ existing, err := s.ipc.Database.ApprovalFlowNode.GetFlowNodeByIDDB(ctx, *req.ID)
+ if err != nil {
+ return nil, err
+ }
+ if existing == nil {
+ return nil, errors.New("node not found")
+ }
+
+ children, _, _ := s.ipc.Database.ApprovalFlowNode.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalFlowNode{ParentID: req.ID},
+ })
+
+ err = s.ipc.Database.ApprovalFlowNode.DeleteApprovalFlowNodeDB(ctx, &req)
+ if err != nil {
+ return nil, err
+ }
+
+ s.bumpFlowVersion(ctx)
+
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ snapshot := map[string]interface{}{
+ "key": utilscore.DerefStr(existing.Key),
+ "label": utilscore.DerefStr(existing.Label),
+ "direct_children": len(children),
+ }
+ if existing.CategoryID != nil {
+ snapshot["category_id"] = *existing.CategoryID
+ }
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "delete", "flow_node", req.ID,
+ fmt.Sprintf("Удалён узел «%s» (каскадно удалено дочерних: %d)", utilscore.DerefStr(existing.Label), len(children)),
+ map[string]interface{}{"snapshot": snapshot},
+ )
+ }
+
+ return true, nil
+}
+
+func (s *FlowNodesReg) SaveEntireTreeHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ categoryIDStr := chi.URLParam(r, "category_id")
+ categoryID, err := strconv.ParseUint(categoryIDStr, 10, 64)
+ if err != nil {
+ return nil, errors.New("invalid category_id")
+ }
+
+ defer r.Body.Close()
+ body, err := io.ReadAll(r.Body)
+ if err != nil {
+ return nil, err
+ }
+
+ var req struct {
+ Nodes []*typescore.ApprovalFlowNode `json:"nodes"`
+ }
+ if err := json.Unmarshal(body, &req); err != nil {
+ return nil, errors.New("invalid request body")
+ }
+
+ ctx := r.Context()
+
+ category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, categoryID)
+ if err != nil {
+ return nil, err
+ }
+ if category == nil {
+ return nil, errors.New("category not found")
+ }
+
+ oldNodes, _, _ := s.ipc.Database.ApprovalFlowNode.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalFlowNode{CategoryID: &categoryID},
+ })
+
+ if err := s.ipc.Database.ApprovalFlowNode.DeleteFlowNodesByCategoryIDDB(ctx, categoryID); err != nil {
+ return nil, err
+ }
+
+ if err := s.saveNodesRecursive(ctx, req.Nodes, categoryID, nil); err != nil {
+ return nil, err
+ }
+
+ s.bumpFlowVersion(ctx)
+
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ categoryName := utilscore.DerefStr(category.Name)
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "update", "flow_tree", &categoryID,
+ fmt.Sprintf("Пересохранено дерево категории «%s» (было узлов: %d, стало: %d)", categoryName, len(oldNodes), countNodesRecursive(req.Nodes)),
+ map[string]interface{}{
+ "category_id": categoryID,
+ "nodes_before": len(oldNodes),
+ "nodes_after": countNodesRecursive(req.Nodes),
+ },
+ )
+ }
+
+ return true, nil
+}
+
+func (s *FlowNodesReg) MoveFlowNodeHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ idStr := chi.URLParam(r, "id")
+ id, err := strconv.ParseUint(idStr, 10, 64)
+ if err != nil {
+ return nil, errors.New("invalid node id")
+ }
+
+ defer r.Body.Close()
+ body, err := io.ReadAll(r.Body)
+ if err != nil {
+ return nil, err
+ }
+
+ var req struct {
+ NewParentID *uint64 `json:"new_parent_id"`
+ NewSortOrder *int `json:"new_sort_order"`
+ }
+ if err := json.Unmarshal(body, &req); err != nil {
+ return nil, errors.New("invalid request body")
+ }
+
+ ctx := r.Context()
+
+ node, err := s.ipc.Database.ApprovalFlowNode.GetFlowNodeByIDDB(ctx, id)
+ if err != nil {
+ return nil, err
+ }
+ if node == nil {
+ return nil, errors.New("node not found")
+ }
+
+ if req.NewParentID != nil {
+ if *req.NewParentID == id {
+ return nil, errors.New("node cannot be its own parent")
+ }
+
+ parent, err := s.ipc.Database.ApprovalFlowNode.GetFlowNodeByIDDB(ctx, *req.NewParentID)
+ if err != nil {
+ return nil, err
+ }
+ if parent == nil {
+ return nil, errors.New("new parent node not found")
+ }
+
+ if parent.CategoryID == nil || node.CategoryID == nil || *parent.CategoryID != *node.CategoryID {
+ return nil, errors.New("new parent belongs to a different category")
+ }
+
+ if err := s.checkNoCyclicReference(ctx, id, *req.NewParentID); err != nil {
+ return nil, err
+ }
+ }
+
+ update := &typescore.ApprovalFlowNode{ID: &id}
+ if req.NewParentID != nil {
+ update.ParentID = req.NewParentID
+ }
+ if req.NewSortOrder != nil {
+ update.SortOrder = req.NewSortOrder
+ }
+
+ updated, _, err := s.ipc.Database.ApprovalFlowNode.UpdateApprovalFlowNodeDB(ctx, nil, update, true)
+ if err != nil {
+ return nil, err
+ }
+
+ s.bumpFlowVersion(ctx)
+
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ var oldParent interface{}
+ if node.ParentID != nil {
+ oldParent = *node.ParentID
+ }
+ metadata := map[string]interface{}{
+ "old_parent_id": oldParent,
+ "new_parent_id": req.NewParentID,
+ "new_sort_order": req.NewSortOrder,
+ }
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "update", "flow_node", &id,
+ fmt.Sprintf("Перемещён узел «%s»", utilscore.DerefStr(node.Label)),
+ metadata,
+ )
+ }
+
+ return updated, nil
+}
+
+func (s *FlowNodesReg) DuplicateFlowNodeHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ idStr := chi.URLParam(r, "id")
+ id, err := strconv.ParseUint(idStr, 10, 64)
+ if err != nil {
+ return nil, errors.New("invalid node id")
+ }
+
+ ctx := r.Context()
+
+ original, err := s.ipc.Database.ApprovalFlowNode.GetFlowNodeByIDDB(ctx, id)
+ if err != nil {
+ return nil, err
+ }
+ if original == nil {
+ return nil, errors.New("node not found")
+ }
+
+ allNodes, _, err := s.ipc.Database.ApprovalFlowNode.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalFlowNode{CategoryID: original.CategoryID},
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ descendants := s.collectDescendants(id, allNodes)
+ suffix := s.generateCopySuffix(ctx, original)
+
+ newKey := *original.Key + suffix
+ newLabel := *original.Label + " (копия)"
+
+ copyNode := &typescore.ApprovalFlowNode{
+ CategoryID: original.CategoryID,
+ TopicID: original.TopicID,
+ ParentID: original.ParentID,
+ Key: &newKey,
+ Label: &newLabel,
+ DataKey: original.DataKey,
+ DataValue: original.DataValue,
+ IsInput: original.IsInput,
+ InputKey: original.InputKey,
+ InputHint: original.InputHint,
+ IsMultiSelect: original.IsMultiSelect,
+ MultiSelectKey: original.MultiSelectKey,
+ MultiSelectValue: original.MultiSelectValue,
+ TopicCode: original.TopicCode,
+ SortOrder: original.SortOrder,
+ MessageTemplate: original.MessageTemplate,
+ CodeTemplate: original.CodeTemplate,
+ }
+
+ createdCopy, _, err := s.ipc.Database.ApprovalFlowNode.CreateApprovalFlowNodeDB(ctx, nil, copyNode, true)
+ if err != nil {
+ return nil, err
+ }
+
+ if len(descendants) > 0 {
+ idMapping := map[uint64]uint64{
+ id: *createdCopy.ID,
+ }
+
+ sortedDescendants := s.sortByDepth(id, descendants, allNodes)
+
+ for _, desc := range sortedDescendants {
+ descKey := *desc.Key + suffix
+ descCopy := &typescore.ApprovalFlowNode{
+ CategoryID: desc.CategoryID,
+ TopicID: desc.TopicID,
+ Key: &descKey,
+ Label: desc.Label,
+ DataKey: desc.DataKey,
+ DataValue: desc.DataValue,
+ IsInput: desc.IsInput,
+ InputKey: desc.InputKey,
+ InputHint: desc.InputHint,
+ IsMultiSelect: desc.IsMultiSelect,
+ MultiSelectKey: desc.MultiSelectKey,
+ MultiSelectValue: desc.MultiSelectValue,
+ TopicCode: desc.TopicCode,
+ SortOrder: desc.SortOrder,
+ MessageTemplate: desc.MessageTemplate,
+ CodeTemplate: desc.CodeTemplate,
+ }
+
+ if desc.ParentID != nil {
+ if newParentID, ok := idMapping[*desc.ParentID]; ok {
+ descCopy.ParentID = &newParentID
+ }
+ }
+
+ createdDesc, _, err := s.ipc.Database.ApprovalFlowNode.CreateApprovalFlowNodeDB(ctx, nil, descCopy, true)
+ if err != nil {
+ return nil, err
+ }
+ if desc.ID != nil && createdDesc != nil && createdDesc.ID != nil {
+ idMapping[*desc.ID] = *createdDesc.ID
+ }
+ }
+ }
+
+ s.bumpFlowVersion(ctx)
+
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "create", "flow_node", createdCopy.ID,
+ fmt.Sprintf("Продублирован узел «%s» (с потомками: %d)", utilscore.DerefStr(original.Label), len(descendants)),
+ map[string]interface{}{
+ "duplicated_from": id,
+ "descendants": len(descendants),
+ },
+ )
+ }
+
+ return createdCopy, nil
+}
+
+func (s *FlowNodesReg) buildTreeFromNodes(nodes []*typescore.ApprovalFlowNode) []*typescore.ApprovalFlowNode {
+ nodeMap := make(map[uint64]*typescore.ApprovalFlowNode)
+ var roots []*typescore.ApprovalFlowNode
+
+ for _, n := range nodes {
+ if n.ID != nil {
+ nodeMap[*n.ID] = n
+ }
+ }
+
+ for _, n := range nodes {
+ if n.ParentID == nil {
+ roots = append(roots, n)
+ } else if parent, ok := nodeMap[*n.ParentID]; ok {
+ parent.Children = append(parent.Children, n)
+ }
+ }
+
+ return roots
+}
+
+func (s *FlowNodesReg) saveNodesRecursive(ctx context.Context, nodes []*typescore.ApprovalFlowNode, categoryID uint64, parentID *uint64) error {
+ for i, node := range nodes {
+ node.CategoryID = &categoryID
+ node.ParentID = parentID
+
+ sortOrder := i
+ node.SortOrder = &sortOrder
+
+ created, _, err := s.ipc.Database.ApprovalFlowNode.CreateApprovalFlowNodeDB(ctx, nil, node, true)
+ if err != nil {
+ return err
+ }
+
+ if len(node.Children) > 0 {
+ if err := s.saveNodesRecursive(ctx, node.Children, categoryID, created.ID); err != nil {
+ return err
+ }
+ }
+ }
+ return nil
+}
+
+// checkNoCyclicReference идёт вверх по родителям от newParentID — если
+// встретит nodeID, значит перемещение создаёт цикл.
+func (s *FlowNodesReg) checkNoCyclicReference(ctx context.Context, nodeID, newParentID uint64) error {
+ currentID := newParentID
+ visited := make(map[uint64]bool)
+
+ for currentID != 0 {
+ if visited[currentID] {
+ break
+ }
+ visited[currentID] = true
+
+ if currentID == nodeID {
+ return errors.New("cyclic reference detected: cannot move node under its own descendant")
+ }
+
+ parent, err := s.ipc.Database.ApprovalFlowNode.GetFlowNodeByIDDB(ctx, currentID)
+ if err != nil || parent == nil {
+ break
+ }
+ if parent.ParentID == nil {
+ break
+ }
+ currentID = *parent.ParentID
+ }
+
+ return nil
+}
+
+func (s *FlowNodesReg) collectDescendants(rootID uint64, allNodes []*typescore.ApprovalFlowNode) []*typescore.ApprovalFlowNode {
+ childrenMap := make(map[uint64][]*typescore.ApprovalFlowNode)
+ for _, n := range allNodes {
+ if n.ParentID != nil {
+ childrenMap[*n.ParentID] = append(childrenMap[*n.ParentID], n)
+ }
+ }
+
+ var result []*typescore.ApprovalFlowNode
+ queue := []uint64{rootID}
+
+ for len(queue) > 0 {
+ current := queue[0]
+ queue = queue[1:]
+
+ for _, child := range childrenMap[current] {
+ result = append(result, child)
+ if child.ID != nil {
+ queue = append(queue, *child.ID)
+ }
+ }
+ }
+
+ return result
+}
+
+func (s *FlowNodesReg) sortByDepth(rootID uint64, descendants, allNodes []*typescore.ApprovalFlowNode) []*typescore.ApprovalFlowNode {
+ depthMap := make(map[uint64]int)
+ depthMap[rootID] = 0
+
+ nodeMap := make(map[uint64]*typescore.ApprovalFlowNode)
+ for _, n := range allNodes {
+ if n.ID != nil {
+ nodeMap[*n.ID] = n
+ }
+ }
+
+ for _, d := range descendants {
+ if d.ID == nil {
+ continue
+ }
+ depth := 0
+ currentID := d.ID
+ for {
+ node, ok := nodeMap[*currentID]
+ if !ok || node.ParentID == nil {
+ break
+ }
+ depth++
+ currentID = node.ParentID
+ if *currentID == rootID {
+ break
+ }
+ }
+ depthMap[*d.ID] = depth
+ }
+
+ sorted := make([]*typescore.ApprovalFlowNode, len(descendants))
+ copy(sorted, descendants)
+ for i := 0; i < len(sorted); i++ {
+ for j := i + 1; j < len(sorted); j++ {
+ depthI := 0
+ depthJ := 0
+ if sorted[i].ID != nil {
+ depthI = depthMap[*sorted[i].ID]
+ }
+ if sorted[j].ID != nil {
+ depthJ = depthMap[*sorted[j].ID]
+ }
+ if depthJ < depthI {
+ sorted[i], sorted[j] = sorted[j], sorted[i]
+ }
+ }
+ }
+
+ return sorted
+}
+
+func (s *FlowNodesReg) generateCopySuffix(ctx context.Context, original *typescore.ApprovalFlowNode) string {
+ if original.CategoryID == nil || original.Key == nil {
+ return "_copy"
+ }
+
+ existing, _, err := s.ipc.Database.ApprovalFlowNode.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalFlowNode{CategoryID: original.CategoryID},
+ })
+ if err != nil {
+ return "_copy"
+ }
+
+ baseKey := *original.Key
+ maxNum := 0
+
+ for _, n := range existing {
+ if n.Key == nil {
+ continue
+ }
+ key := *n.Key
+ if len(key) > len(baseKey) && key[:len(baseKey)] == baseKey {
+ suffix := key[len(baseKey):]
+ if len(suffix) >= 6 && suffix[:5] == "_copy" {
+ if len(suffix) > 5 {
+ numStr := suffix[6:]
+ if num, err := strconv.Atoi(numStr); err == nil && num > maxNum {
+ maxNum = num
+ }
+ } else if suffix == "_copy" {
+ if maxNum < 1 {
+ maxNum = 1
+ }
+ }
+ }
+ }
+ }
+
+ return fmt.Sprintf("_copy_%d", maxNum+1)
+}
+
+func countNodesRecursive(nodes []*typescore.ApprovalFlowNode) int {
+ count := len(nodes)
+ for _, n := range nodes {
+ count += countNodesRecursive(n.Children)
+ }
+ return count
+}
+
+func (s *FlowNodesReg) getCurrentAdmin(ctx context.Context) (*typescore.Admin, bool) {
+ currentUserID, err := handlers.GetIDFromContext(ctx)
+ if err != nil {
+ return nil, false
+ }
+
+ admins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{
+ Filtering: &typescore.Admin{ID: ¤tUserID},
+ })
+ if err != nil || len(admins) == 0 || admins[0] == nil || admins[0].ID == nil || admins[0].Login == nil {
+ return nil, false
+ }
+
+ return admins[0], true
+}
diff --git a/service/rest_admin_service/handlers/flow_nodes/preview.go b/service/rest_admin_service/handlers/flow_nodes/preview.go
new file mode 100644
index 0000000..8e9d771
--- /dev/null
+++ b/service/rest_admin_service/handlers/flow_nodes/preview.go
@@ -0,0 +1,111 @@
+package nodeshandler
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/telegram_service/approvalflow"
+ "encoding/json"
+ "errors"
+ "io"
+ "net/http"
+ "strconv"
+
+ "github.com/go-chi/chi/v5"
+)
+
+type previewFlowRequest struct {
+ // Collected — все data_key/data_value, накопленные по пути от корня
+ // дерева категории до узла, для которого считаем предпросмотр.
+ Collected map[string]string `json:"collected"`
+ // InitiatorName — необязательно, для более живого предпросмотра
+ // сообщения (по умолчанию подставляется тестовое имя).
+ InitiatorName string `json:"initiator_name"`
+}
+
+type previewFlowResponse struct {
+ // Code — код темы, который реально будет использован для поиска
+ // ApprovalTopic при подаче заявки. Пусто, если по текущим данным
+ // код ещё нельзя посчитать (путь не завершён).
+ Code string `json:"code"`
+ // Message — как будет выглядеть уведомление согласующему (с HTML-разметкой,
+ // как оно уйдёт в Telegram).
+ Message string `json:"message"`
+ // Incomplete — true, если для расчёта кода не хватает данных
+ // (это не ошибка, а нормальная ситуация для промежуточного узла).
+ Incomplete bool `json:"incomplete"`
+ // TopicExists — есть ли уже в approval_topics тема с таким кодом.
+ TopicExists bool `json:"topic_exists"`
+ TopicID uint64 `json:"topic_id,omitempty"`
+ TopicName string `json:"topic_name,omitempty"`
+}
+
+func (s *FlowNodesReg) PreviewFlowHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ categoryIDStr := chi.URLParam(r, "category_id")
+ categoryID, err := strconv.ParseUint(categoryIDStr, 10, 64)
+ if err != nil {
+ return nil, errors.New("invalid category_id")
+ }
+
+ defer r.Body.Close()
+ body, err := io.ReadAll(r.Body)
+ if err != nil {
+ return nil, err
+ }
+
+ var req previewFlowRequest
+ if len(body) > 0 {
+ if err := json.Unmarshal(body, &req); err != nil {
+ return nil, errors.New("invalid request body")
+ }
+ }
+ if req.Collected == nil {
+ req.Collected = map[string]string{}
+ }
+ if req.InitiatorName == "" {
+ req.InitiatorName = "Иван Иванов"
+ }
+
+ ctx := r.Context()
+
+ category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, categoryID)
+ if err != nil {
+ return nil, err
+ }
+ if category == nil {
+ return nil, errors.New("category not found")
+ }
+
+ nodes, _, err := s.ipc.Database.ApprovalFlowNode.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalFlowNode{CategoryID: &categoryID},
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ dynamicTopic := approvalflow.NewDynamicTopic(category, nodes)
+
+ resp := &previewFlowResponse{}
+
+ code, err := dynamicTopic.TopicCodeFromCollected(req.Collected)
+ if err != nil {
+ // Ожидаемо для промежуточного узла: пути ещё не хватает данных.
+ resp.Incomplete = true
+ } else {
+ resp.Code = code
+
+ existingTopic, exErr := s.ipc.Database.ApprovalTopic.GetApprovalTopicByCodeDB(ctx, code)
+ if exErr == nil && existingTopic != nil {
+ resp.TopicExists = true
+ if existingTopic.ID != nil {
+ resp.TopicID = *existingTopic.ID
+ }
+ if existingTopic.Name != nil {
+ resp.TopicName = *existingTopic.Name
+ }
+ }
+ }
+
+ initiator := &typescore.User{FullName: &req.InitiatorName}
+ resp.Message = dynamicTopic.FormatApproverMessage(initiator, req.Collected)
+
+ return resp, nil
+}
diff --git a/service/rest_admin_service/handlers/flow_nodes/router.go b/service/rest_admin_service/handlers/flow_nodes/router.go
new file mode 100644
index 0000000..7e61936
--- /dev/null
+++ b/service/rest_admin_service/handlers/flow_nodes/router.go
@@ -0,0 +1,61 @@
+package nodeshandler
+
+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 FlowNodesReg struct {
+ ipc *typesm.InternalProviderControl
+}
+
+// RegisterFlowNodesRoutes регистрирует маршруты для управления узлами дерева.
+// Дерево навигации принадлежит категории (category_id) — см. ApprovalFlowNode.CategoryID
+// и Registry.LoadFromDB, которые строят Topic-интерфейс по категории + узлам.
+func RegisterFlowNodesRoutes(
+ r chi.Router,
+ ipc *typesm.InternalProviderControl,
+) error {
+ s := &FlowNodesReg{
+ ipc: ipc,
+ }
+
+ r.Route("/api/flow-nodes", 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, "/category/{category_id}", s.GetFlowNodesByCategoryIDHandler)
+
+ // CRUD операции с узлами
+ handlers.RegisterRoute(r, http.MethodPost, "/", s.CreateFlowNodeHandler)
+ handlers.RegisterRoute(r, http.MethodPut, "/", s.UpdateFlowNodeHandler)
+ handlers.RegisterRoute(r, http.MethodDelete, "/", s.DeleteFlowNodeHandler)
+
+ // Сохранить всё дерево целиком (для UI конструктора)
+ handlers.RegisterRoute(r, http.MethodPost, "/category/{category_id}/tree", s.SaveEntireTreeHandler)
+
+ // Переместить узел (изменить порядок или родителя) — используется
+ // и обычным ↑/↓, и кнопками "поднять/опустить уровень" в новом UI.
+ handlers.RegisterRoute(r, http.MethodPost, "/{id}/move", s.MoveFlowNodeHandler)
+
+ // Дублировать узел с детьми
+ handlers.RegisterRoute(r, http.MethodPost, "/{id}/duplicate", s.DuplicateFlowNodeHandler)
+
+ // НОВОЕ: живой предпросмотр кода темы и сообщения согласующему
+ // для конкретного пути по дереву — см. preview.go
+ handlers.RegisterRoute(r, http.MethodPost, "/category/{category_id}/preview", s.PreviewFlowHandler)
+
+ // НОВОЕ: кнопка "Обновить бота" — форсирует бамп версии дерева тем,
+ // бот подхватит на ближайшем тике фонового воркера — см. reload.go
+ handlers.RegisterRoute(r, http.MethodPost, "/reload-bot", s.ReloadBotHandler)
+
+ // Получить узел по ID
+ handlers.RegisterRoute(r, http.MethodGet, "/{id}", s.GetFlowNodeByIDHandler)
+ })
+
+ return nil
+}
diff --git a/service/rest_admin_service/handlers/flow_nodes/utils.go b/service/rest_admin_service/handlers/flow_nodes/utils.go
new file mode 100644
index 0000000..080e4ed
--- /dev/null
+++ b/service/rest_admin_service/handlers/flow_nodes/utils.go
@@ -0,0 +1,20 @@
+package nodeshandler
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "time"
+)
+
+const flowVersionRedisKey = "approval_flow:version"
+
+func (s *FlowNodesReg) bumpFlowVersion(ctx context.Context) {
+ version := fmt.Sprintf("%d", time.Now().UnixNano())
+ _ = s.ipc.RedisClient.Set(ctx, flowVersionRedisKey, version, 24*time.Hour)
+}
+
+func (s *FlowNodesReg) ReloadBotHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ s.bumpFlowVersion(r.Context())
+ return true, nil
+}
diff --git a/service/rest_admin_service/handlers/monthly_orders/google-creds.json b/service/rest_admin_service/handlers/monthly_orders/google-creds.json
new file mode 100644
index 0000000..91c875c
--- /dev/null
+++ b/service/rest_admin_service/handlers/monthly_orders/google-creds.json
@@ -0,0 +1,13 @@
+{
+ "type": "service_account",
+ "project_id": "ruspet",
+ "private_key_id": "37f429a3549be247a03a37cc3274e8d4ea9f7bde",
+ "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCwWSW8v4Tdp3US\nxLLJUTAlW0aMFEkbCbyf5U22jjzNhHPfgg019yvgJPSjm51oSH9kC5PYo/z2Tnxp\nUsxzAaBrKL7DfrGbNQkuQyLPUQj6w2Co5P4N1lRdYeli9fxXpbf496BbSyl8M2yf\nNjIO7L+9K+nRCqkMwzDfHFS8frJNhPy5u98w/eFSSiyHI14ocXzVYgt6w4bBWwht\nDGhjxAegpGtjgkXi9BZ9tKhcK3vlkQiG4UAqWQdA4gqfFXFis7xf1z4iHBOAvIXe\nJbKIsCpGNIDe5dROt5r7wGtgXjtKfWXjs+Te0NJ8om8f29wkan6hFX/QQ7uMJio9\ndE4iiO8fAgMBAAECggEABULQ7JByzcwM+D+JrUDbT1n+66HqoRW0HLm8t56xs1iU\nE7hvssr0x6NCmyOYLsAZm39O7K55Fv4LbyGgZilHww/8SkfG06sMODxE1xYt+ZEy\nRTJOXqpPalkdRdhcgV7jyK0r3wgJ16HkcobYN81vVkeaRPls8VZcvbiSJ0IeXqVK\n1h2QIKOrcb2RtWRgE9RMrmdgczAznlUU0Lg+WPV1CgAaiGeh9PwAw7qSsSI/z1nR\nTCn027JiByrdEXWFJQSAfPqctqKgeHwfoUOWnssp8IXTNK6PpZZhBfM8h2rXUfME\nXKwhshbySrBoULMIs+O2AcRIOxuWPgsT0fcsOyeqtQKBgQDeOWn+kBQFuBlwsX/B\nn2pkG9EXY9IKUMcecIBXG76TfkQ2xtLPQMLaALWEqL/WJl0VeCSzifialLVxBIIv\nfSJu/yJMaY16VczhlqN7rBU91dFv1+ySUPeRgTMzoZhh4hi4QliA9mqDVvnk3bQN\n2QUL5nBSbigq2grBLSYv6i2MwwKBgQDLJrrP3TxWBD79kaw8P9RK2K1zdYvAwvms\nx1B2HlgS8TwQJUA69JlzKr87Tr00oK2n8mZCmzHpwK4FNkoHfqe8LFdo1ulHYlTG\nKaB5uDYun8XOKYFuUKwe0lpwgdyDefAmHAWwTSK38WOfvVdvdr9C6zpbOZXVqOC/\nXbt9FVhedQKBgQDOx3Hfk8VtxO63NBMC4gmneVLIhvPM8Xk208w4QfLFX7qtlbhX\nbZViMUK2XCeVZ0E6Vv8fqQSRIkrrDRzuf2vpCLKrk5Q3/1qTlw4sZ+WkEi+9+JeD\nVp/m3uf75SPcAPyrh+C+r4xRBj+lPL7sG8JcXmKp8SKjLRzQv+hGsYsM7QKBgQDI\nTkDGceJrAbbGOJs1sM32mpyzikQo5VZfGQtp29OFodxSIxioyMKAvrZdmO6P9Jol\nTamspO9bBwPO2c+2ghiLPsFU+wp6uybRWPwE6DBsWlckRuJ6zgpYPZq08iZmcJXs\nTZcCVZwU+Gr9dyi+G7zME7mvdyEY0XIA3j/ePmyqfQKBgCd90yw1gJU6KnRUJS0U\ns4Z4hcnxRiar9LUk/GX/ELObd6ONs0BiN/GAVRWQl8tP3+J4jlF9XkQVGsGQdHdf\nannCbxcrMt3lHcKyOAOnjMsnWPfqWL5CJ0z+9Thg5L+GXZDCk1SJOu5vwCVVxiw2\nRs5O5K+U9K2xBZcpYhNlt7o2\n-----END PRIVATE KEY-----\n",
+ "client_email": "service-account@ruspet.iam.gserviceaccount.com",
+ "client_id": "117800311304874293466",
+ "auth_uri": "https://accounts.google.com/o/oauth2/auth",
+ "token_uri": "https://oauth2.googleapis.com/token",
+ "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
+ "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/service-account%40ruspet.iam.gserviceaccount.com",
+ "universe_domain": "googleapis.com"
+}
diff --git a/service/rest_admin_service/handlers/monthly_orders/routes.go b/service/rest_admin_service/handlers/monthly_orders/routes.go
new file mode 100644
index 0000000..89f39f1
--- /dev/null
+++ b/service/rest_admin_service/handlers/monthly_orders/routes.go
@@ -0,0 +1,377 @@
+package monthlyordershandler
+
+import (
+ "bitrix_balancer_api/core/lib/external/googlesheets"
+ "bitrix_balancer_api/core/lib/internally/monthly_orders"
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/rest_admin_service/handlers"
+ typesm "bitrix_balancer_api/rest_admin_service/types"
+ tgupdatehandler "bitrix_balancer_api/telegram_service/common/update"
+ "bitrix_balancer_api/telegram_service/types"
+ "context"
+ _ "embed" // Для вшивания ключей гугла
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "strconv"
+ "time"
+
+ "github.com/go-chi/chi/v5"
+ "github.com/sirupsen/logrus"
+)
+
+//go:embed google-creds.json
+var googleCredsJSON []byte
+
+type MonthlyOrdersReg struct {
+ ipc *typesm.InternalProviderControl
+ moService *monthly_orders.MonthlyOrderService
+}
+
+// RegisterMonthlyOrdersRoutes регистрирует маршруты для управления заказами на месяц.
+func RegisterMonthlyOrdersRoutes(
+ r chi.Router,
+ ipc *typesm.InternalProviderControl,
+) error {
+ // Инициализируем Google Client здесь, при регистрации роутов
+ gsClient, err := googlesheets.NewClient(context.Background(), googleCredsJSON)
+ if err != nil {
+ logrus.Errorf("Не удалось инициализировать Google Sheets API для MonthlyOrders: %v", err)
+ }
+
+ tgIpc := &types.InternalProviderControl{
+ Config: ipc.Config,
+ Database: ipc.Database,
+ RedisClient: ipc.RedisClient,
+ TGBotClient: ipc.TGBotClient,
+ }
+ updateHandler := tgupdatehandler.NewUpdateHandler(tgIpc)
+
+ moService := monthly_orders.NewMonthlyOrderService(
+ tgIpc,
+ gsClient,
+ "1F1ansQeSuAwhe3Y_mhfm4ja370k5hq67RruE-CVp83w", // Таблица Клиентов
+ "1C4Tl-AQRJENW4THzwH-7yP2Ni0ckMSdm3ndLCrdKr2Y", // Таблица Номенклатуры
+ updateHandler.GetApprovalHandler(),
+ )
+
+ s := &MonthlyOrdersReg{
+ ipc: ipc,
+ moService: moService,
+ }
+
+ moService.StartDeadlineWorker(context.Background())
+
+ r.Route("/api/monthly-orders", 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, "/matrix", s.GetMatrixHandler)
+
+ // Менеджер: сохранение таблицы
+ handlers.RegisterRoute(r, http.MethodPost, "/save", s.SaveOrdersHandler)
+
+ // Аналитик: настройки
+ handlers.RegisterRoute(r, http.MethodGet, "/settings", s.GetSettingsHandler)
+ handlers.RegisterRoute(r, http.MethodPost, "/settings", s.SaveSettingsHandler)
+
+ handlers.RegisterRoute(r, http.MethodPost, "/report/google", s.ExportReportHandler)
+ handlers.RegisterRoute(r, http.MethodPost, "/supplementary/submit", s.SubmitSupplementaryOrdersHandler)
+ })
+
+ return nil
+}
+
+// ==========================================
+// Вспомогательные методы
+// ==========================================
+
+func (s *MonthlyOrdersReg) getManagerUser(ctx context.Context, adminID uint64) (*typescore.User, *typescore.Admin, error) {
+ admins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{Filtering: &typescore.Admin{ID: &adminID}})
+ if err != nil || len(admins) == 0 {
+ return nil, nil, errors.New("admin account not found")
+ }
+ admin := admins[0]
+
+ if admin.TelegramID == nil {
+ return nil, admin, errors.New("ваш аккаунт не привязан к Telegram (ID пользователя). Обратитесь к администратору")
+ }
+
+ user, err := s.ipc.Database.User.GetUserByTelegramIDDB(ctx, *admin.TelegramID)
+ if err != nil || user == nil || user.ID == nil {
+ return nil, admin, errors.New("пользователь с таким Telegram ID не найден в системе")
+ }
+
+ return user, admin, nil
+}
+
+type ExportReportRequest struct {
+ Email string `json:"email"`
+}
+
+func (s *MonthlyOrdersReg) ExportReportHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ ctx := r.Context()
+ adminID, err := handlers.GetIDFromContext(ctx)
+ if err != nil {
+ return nil, errors.New("user not authenticated")
+ }
+
+ admins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{Filtering: &typescore.Admin{ID: &adminID}})
+ if err != nil || len(admins) == 0 {
+ return nil, errors.New("admin account not found")
+ }
+ admin := admins[0]
+
+ if admin.IsAnalyst == nil || !*admin.IsAnalyst {
+ return nil, errors.New("только аналитик может выгружать сводный отчет")
+ }
+
+ body, err := io.ReadAll(r.Body)
+ defer r.Body.Close()
+ if err != nil {
+ return nil, err
+ }
+
+ var req ExportReportRequest
+ if err := json.Unmarshal(body, &req); err != nil {
+ return nil, errors.New("некорректный формат JSON")
+ }
+
+ if s.moService == nil {
+ return nil, errors.New("сервис заказов не инициализирован")
+ }
+
+ // Генерируем отчет
+ url, err := s.moService.ExportGoogleReport(ctx)
+ if err != nil {
+ logrus.Errorf("Ошибка генерации отчета для %s: %v", req.Email, err)
+ return nil, fmt.Errorf("ошибка генерации отчета: %v", err)
+ }
+
+ return map[string]string{"url": url}, nil
+}
+
+func (s *MonthlyOrdersReg) SubmitSupplementaryOrdersHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ ctx := r.Context()
+ adminID, err := handlers.GetIDFromContext(ctx)
+ if err != nil {
+ return nil, errors.New("user not authenticated")
+ }
+
+ user, admin, err := s.getManagerUser(ctx, adminID)
+ if err != nil {
+ return nil, err
+ }
+
+ if admin.IsAnalyst != nil && *admin.IsAnalyst {
+ return nil, errors.New("аналитик не может отправлять доп. заказы")
+ }
+
+ body, err := io.ReadAll(r.Body)
+ defer r.Body.Close()
+ if err != nil {
+ return nil, err
+ }
+
+ var req SaveOrdersRequest
+ if err := json.Unmarshal(body, &req); err != nil {
+ return nil, errors.New("invalid request body")
+ }
+
+ now := time.Now()
+ month, year := int(now.Month()), now.Year()
+
+ // 1. Сохраняем пришедшие доп. заказы
+ for _, order := range req.Orders {
+ order.ManagerID = user.ID
+ order.Month = &month
+ order.Year = &year
+
+ if order.ClientName == nil || *order.ClientName == "" {
+ continue
+ }
+
+ suppType := "supplementary"
+ order.OrderType = &suppType
+
+ // Устанавливаем статус "draft", чтобы SaveClientOrder гарантированно
+ // создал НОВУЮ запись в БД (для истории), а не затирал старую "submitted".
+ st := "draft"
+ order.Status = &st
+
+ _, err := s.ipc.Database.MonthlyOrders.SaveClientOrder(ctx, nil, &order)
+ if err != nil {
+ logrus.Errorf("Не удалось сохранить доп. заказ для %s: %v", *order.ClientName, err)
+ return nil, err
+ }
+ }
+
+ // 2. Сразу же запускаем отправку в Telegram.
+ // Функция SubmitOrdersToTelegram сама найдет эти новые "draft" заказы
+ // (так как у них ApprovalID == nil) и отправит их на согласование.
+ err = s.moService.SubmitOrdersToTelegram(ctx, *user.ID)
+ if err != nil {
+ return nil, fmt.Errorf("сбой при отправке на согласование: %v", err)
+ }
+
+ return map[string]string{"status": "success"}, nil
+}
+
+func (s *MonthlyOrdersReg) GetMatrixHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ ctx := r.Context()
+ adminID, err := handlers.GetIDFromContext(ctx)
+ if err != nil {
+ return nil, errors.New("user not authenticated")
+ }
+
+ logrus.Info("🛑 GET MATRIX HANDLER ")
+ user, admin, err := s.getManagerUser(ctx, adminID)
+ targetManagerID := uint64(0)
+
+ // Если авторизовался АНАЛИТИК
+ if admin != nil && admin.IsAnalyst != nil && *admin.IsAnalyst {
+ logrus.Info("🛑 ANALYTIC ")
+
+ queryManagerID := r.URL.Query().Get("manager_id")
+ if queryManagerID != "" {
+ parsedID, _ := strconv.ParseUint(queryManagerID, 10, 64)
+ targetManagerID = parsedID
+ } else {
+ return nil, errors.New("аналитику необходимо передать manager_id для просмотра таблицы")
+ }
+ } else {
+ logrus.Info("🛑 MANAGER ")
+
+ // Если авторизовался МЕНЕДЖЕР
+ if err != nil {
+ return nil, err
+ }
+ targetManagerID = *user.ID
+ }
+
+ logrus.Info("🛑 MANAGER 2")
+
+ if s.moService == nil {
+ return nil, errors.New("сервис заказов не инициализирован (отсутствуют ключи Google)")
+ }
+
+ matrix, err := s.moService.GetMyOrderData(ctx, targetManagerID)
+ if err != nil {
+ return nil, err
+ }
+
+ return matrix, nil
+}
+
+type SaveOrdersRequest struct {
+ Orders []typescore.MonthlyOrderClient `json:"orders"`
+}
+
+func (s *MonthlyOrdersReg) SaveOrdersHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ ctx := r.Context()
+ adminID, err := handlers.GetIDFromContext(ctx)
+ if err != nil {
+ return nil, errors.New("user not authenticated")
+ }
+
+ user, admin, err := s.getManagerUser(ctx, adminID)
+ if err != nil {
+ return nil, err
+ }
+
+ if admin.IsAnalyst != nil && *admin.IsAnalyst {
+ return nil, errors.New("аналитик не может редактировать заказы менеджеров")
+ }
+
+ body, err := io.ReadAll(r.Body)
+ defer r.Body.Close()
+ if err != nil {
+ return nil, err
+ }
+
+ var req SaveOrdersRequest
+ if err := json.Unmarshal(body, &req); err != nil {
+ return nil, errors.New("invalid request body")
+ }
+
+ now := time.Now()
+ month, year := int(now.Month()), now.Year()
+
+ for _, order := range req.Orders {
+ order.ManagerID = user.ID
+ order.Month = &month
+ order.Year = &year
+
+ if order.ClientName == nil || *order.ClientName == "" {
+ continue
+ }
+
+ if order.OrderType == nil || *order.OrderType == "" {
+ mainType := "main"
+ order.OrderType = &mainType
+ }
+
+ if order.Status == nil {
+ st := "draft"
+ order.Status = &st
+ }
+
+ _, err := s.ipc.Database.MonthlyOrders.SaveClientOrder(ctx, nil, &order)
+ if err != nil {
+ logrus.Errorf("Не удалось сохранить заказ для клиента %s: %v", *order.ClientName, err)
+ return nil, err
+ }
+ }
+
+ return map[string]string{"status": "success"}, nil
+}
+
+func (s *MonthlyOrdersReg) GetSettingsHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ now := time.Now()
+ month, year := int(now.Month()), now.Year()
+
+ settings, err := s.ipc.Database.MonthlyOrders.GetCurrentSettings(r.Context(), month, year)
+ if err != nil {
+ return nil, err
+ }
+ return settings, nil
+}
+
+func (s *MonthlyOrdersReg) SaveSettingsHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ ctx := r.Context()
+ adminID, err := handlers.GetIDFromContext(ctx)
+ if err != nil {
+ return nil, errors.New("user not authenticated")
+ }
+
+ admins, _, _ := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{Filtering: &typescore.Admin{ID: &adminID}})
+ if len(admins) == 0 || admins[0].IsAnalyst == nil || !*admins[0].IsAnalyst {
+ return nil, errors.New("только аналитик может изменять настройки")
+ }
+
+ body, err := io.ReadAll(r.Body)
+ defer r.Body.Close()
+ if err != nil {
+ return nil, err
+ }
+
+ var settings typescore.MonthlyOrderSetting
+ if err := json.Unmarshal(body, &settings); err != nil {
+ return nil, errors.New("invalid request body")
+ }
+
+ now := time.Now()
+ month, year := int(now.Month()), now.Year()
+ settings.Month = &month
+ settings.Year = &year
+
+ err = s.ipc.Database.MonthlyOrders.SaveSettings(ctx, nil, &settings)
+ if err != nil {
+ return nil, err
+ }
+
+ return map[string]string{"status": "success"}, nil
+}
diff --git a/service/rest_admin_service/handlers/notification/handlers.go b/service/rest_admin_service/handlers/notification/handlers.go
new file mode 100644
index 0000000..dc1560d
--- /dev/null
+++ b/service/rest_admin_service/handlers/notification/handlers.go
@@ -0,0 +1,306 @@
+package notificationshandler
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/core/utilscore"
+ "bitrix_balancer_api/rest_admin_service/handlers"
+ adminloghandler "bitrix_balancer_api/rest_admin_service/handlers/admin_actions"
+ typesm "bitrix_balancer_api/rest_admin_service/types"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "github.com/go-chi/chi/v5"
+ "github.com/sirupsen/logrus"
+ "io"
+ "net/http"
+ "strconv"
+)
+
+type NotificationReg struct {
+ ipc *typesm.InternalProviderControl
+}
+
+func (s *NotificationReg) CreateNotificationHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ body, err := io.ReadAll(r.Body)
+ if err != nil {
+ return nil, err
+ }
+ defer r.Body.Close()
+
+ var req typescore.CreateNotificationReq
+ if err := json.Unmarshal(body, &req); err != nil {
+ return nil, errors.New("invalid request body")
+ }
+ if req.Title == "" || req.MessageHTML == "" {
+ return nil, errors.New("title and message_html are required")
+ }
+
+ ctx := r.Context()
+
+ recipients, err := s.resolveRecipients(ctx, req.Targets)
+ if err != nil {
+ return nil, err
+ }
+ if len(recipients) == 0 {
+ return nil, errors.New("no recipients matched the given filters")
+ }
+
+ targetFiltersJSON, err := json.Marshal(req.Targets)
+ if err != nil {
+ return nil, err
+ }
+ targetFiltersStr := string(targetFiltersJSON)
+
+ status := "sending"
+ totalCount := len(recipients)
+ notification := &typescore.Notification{
+ Title: &req.Title,
+ MessageHTML: &req.MessageHTML,
+ PhotoBase64: req.PhotoBase64,
+ PhotoFileName: req.PhotoFileName,
+ TargetFilters: &targetFiltersStr,
+ Status: &status,
+ TotalCount: &totalCount,
+ }
+
+ notification, err = s.ipc.Database.Notification.CreateNotificationDB(ctx, notification)
+ if err != nil {
+ return nil, err
+ }
+
+ pendingStatus := "pending"
+ recipientRows := make([]*typescore.NotificationRecipient, 0, len(recipients))
+ for _, u := range recipients {
+ recipientRows = append(recipientRows, &typescore.NotificationRecipient{
+ NotificationID: notification.ID,
+ UserID: u.ID,
+ Status: &pendingStatus,
+ })
+ }
+ if err := s.ipc.Database.Notification.CreateNotificationRecipientsDB(ctx, recipientRows); err != nil {
+ return nil, err
+ }
+
+ sentCount, failedCount := s.sendToRecipients(ctx, notification, recipients)
+
+ finalStatus := "completed"
+ notification.Status = &finalStatus
+ notification.SentCount = &sentCount
+ notification.FailedCount = &failedCount
+ if err := s.ipc.Database.Notification.UpdateNotificationDB(ctx, notification); err != nil {
+ logrus.Warnf("CreateNotificationHandler: failed to update final status: %v", err)
+ }
+
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "create", "notification", notification.ID,
+ fmt.Sprintf("Отправлена рассылка «%s» (получателей: %d, отправлено: %d, ошибок: %d)",
+ req.Title, totalCount, sentCount, failedCount),
+ map[string]interface{}{
+ "title": req.Title,
+ "total_count": totalCount,
+ "sent_count": sentCount,
+ "failed_count": failedCount,
+ "target_filters": req.Targets,
+ },
+ )
+ }
+
+ return notification, nil
+}
+
+// resolveRecipients объединяет пользователей из всех критериев без дублей
+func (s *NotificationReg) resolveRecipients(ctx context.Context, filters typescore.TargetFilters) ([]*typescore.User, error) {
+ usersMap := make(map[uint64]*typescore.User)
+
+ addUsers := func(list []*typescore.User) {
+ for _, u := range list {
+ if u.ID != nil {
+ usersMap[*u.ID] = u
+ }
+ }
+ }
+
+ if len(filters.UserIDs) > 0 {
+ users, err := s.ipc.Database.User.GetUsersByIDsDB(ctx, filters.UserIDs)
+ if err != nil {
+ return nil, err
+ }
+ addUsers(users)
+ }
+
+ if len(filters.RoleIDs) > 0 {
+ users, _, err := s.ipc.Database.User.GetUsersListByRoleIDsDB(ctx, typescore.ListDbOptions{}, filters.RoleIDs)
+ if err != nil {
+ return nil, err
+ }
+ addUsers(users)
+ }
+
+ if len(filters.RoleTypeFlags) > 0 {
+ users, err := s.ipc.Database.User.GetUsersByRoleFlagsDB(ctx, filters.RoleTypeFlags)
+ if err != nil {
+ return nil, err
+ }
+ addUsers(users)
+ }
+
+ if len(filters.DepartmentIDs) > 0 {
+ users, err := s.ipc.Database.User.GetUsersByDepartmentIDsDB(ctx, filters.DepartmentIDs)
+ if err != nil {
+ return nil, err
+ }
+ addUsers(users)
+ }
+
+ result := make([]*typescore.User, 0, len(usersMap))
+ for _, u := range usersMap {
+ if u.IsBlocked != nil && *u.IsBlocked {
+ continue
+ }
+ result = append(result, u)
+ }
+ return result, nil
+}
+
+// sendToRecipients рассылает сообщение всем найденным пользователям и фиксирует результат по каждому
+func (s *NotificationReg) sendToRecipients(ctx context.Context, n *typescore.Notification, users []*typescore.User) (sent int, failed int) {
+ pendingRecipients, err := s.ipc.Database.Notification.GetNotificationRecipientsDB(ctx, *n.ID)
+ if err != nil {
+ logrus.Errorf("sendToRecipients: failed to load recipients: %v", err)
+ return 0, len(users)
+ }
+
+ recipientByUserID := make(map[uint64]*typescore.NotificationRecipient)
+ for _, r := range pendingRecipients {
+ if r.UserID != nil {
+ recipientByUserID[*r.UserID] = r
+ }
+ }
+
+ sentStatus := "sent"
+ failedStatus := "failed"
+
+ for _, u := range users {
+ if u.TelegramID == nil {
+ continue
+ }
+ rec, ok := recipientByUserID[*u.ID]
+ if !ok {
+ continue
+ }
+
+ var sendErr error
+ var msgID int
+
+ if n.PhotoBase64 != nil && *n.PhotoBase64 != "" {
+ fileName := "notification.jpg"
+ if n.PhotoFileName != nil {
+ fileName = *n.PhotoFileName
+ }
+ sentMsg, err := s.ipc.TGBotClient.SendPhoto(*u.TelegramID, *n.PhotoBase64, *n.MessageHTML)
+ if err != nil {
+ sendErr = err
+ } else {
+ msgID = sentMsg.MessageID
+ }
+ _ = fileName
+ } else {
+ sentMsg, err := s.ipc.TGBotClient.Send(*u.TelegramID, *n.MessageHTML)
+ if err != nil {
+ sendErr = err
+ } else {
+ msgID = sentMsg.MessageID
+ }
+ }
+
+ if sendErr != nil {
+ errStr := sendErr.Error()
+ rec.Status = &failedStatus
+ rec.ErrorMessage = &errStr
+ failed++
+ } else {
+ rec.Status = &sentStatus
+ rec.TelegramMessageID = &msgID
+ sent++
+ }
+
+ if err := s.ipc.Database.Notification.UpdateNotificationRecipientDB(ctx, rec); err != nil {
+ logrus.Warnf("sendToRecipients: failed to update recipient status: %v", err)
+ }
+ }
+
+ return sent, failed
+}
+
+// GetNotificationListHandler — история отправленных уведомлений
+func (s *NotificationReg) GetNotificationListHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ queryParams := r.URL.Query()
+
+ notificationParams := &typescore.Notification{}
+ offset, limit, likeFields, errW := utilscore.ParseParamsGetRequest(queryParams, notificationParams)
+ if errW != nil {
+ return nil, errW
+ }
+
+ options := typescore.ListDbOptions{
+ Filtering: notificationParams,
+ Offset: offset,
+ Limit: limit,
+ LikeFields: likeFields,
+ }
+
+ list, total, err := s.ipc.Database.Notification.GetNotificationsListDB(r.Context(), options)
+ if err != nil {
+ return nil, err
+ }
+
+ return &typescore.ApiResponseBase{
+ TotalCount: total,
+ Data: list,
+ }, nil
+}
+
+// GetNotificationByIDHandler — детали конкретной рассылки с постатейной историей доставки
+func (s *NotificationReg) GetNotificationByIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ idStr := chi.URLParam(r, "id")
+ id, err := strconv.ParseUint(idStr, 10, 64)
+ if err != nil {
+ return nil, errors.New("invalid notification id")
+ }
+
+ ctx := r.Context()
+ notification, err := s.ipc.Database.Notification.GetNotificationByIDDB(ctx, id)
+ if err != nil {
+ return nil, err
+ }
+ if notification == nil {
+ return nil, errors.New("notification not found")
+ }
+
+ recipients, err := s.ipc.Database.Notification.GetNotificationRecipientsDB(ctx, id)
+ if err == nil {
+ notification.Recipients = recipients
+ }
+
+ return notification, nil
+}
+
+func (s *NotificationReg) getCurrentAdmin(ctx context.Context) (*typescore.Admin, bool) {
+ currentUserID, err := handlers.GetIDFromContext(ctx)
+ if err != nil {
+ return nil, false
+ }
+
+ admins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{
+ Filtering: &typescore.Admin{ID: ¤tUserID},
+ })
+ if err != nil || len(admins) == 0 || admins[0] == nil || admins[0].ID == nil || admins[0].Login == nil {
+ return nil, false
+ }
+
+ return admins[0], true
+}
diff --git a/service/rest_admin_service/handlers/notification/routes.go b/service/rest_admin_service/handlers/notification/routes.go
new file mode 100644
index 0000000..e10c850
--- /dev/null
+++ b/service/rest_admin_service/handlers/notification/routes.go
@@ -0,0 +1,26 @@
+package notificationshandler
+
+import (
+ "bitrix_balancer_api/rest_admin_service/handlers"
+ typesm "bitrix_balancer_api/rest_admin_service/types"
+ "net/http"
+
+ "github.com/go-chi/chi/v5"
+)
+
+func RegisterNotificationRoutes(r chi.Router, ipc *typesm.InternalProviderControl) error {
+ s := &NotificationReg{ipc: ipc}
+
+ r.Route("/api/notifications", 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.MethodPost, "/", s.CreateNotificationHandler)
+ handlers.RegisterRoute(r, http.MethodGet, "/", s.GetNotificationListHandler)
+ r.Get("/{id}", handlers.WrapHandlerF(handlers.WrapHandlerParams{
+ HandlerFunc: s.GetNotificationByIDHandler,
+ }))
+ })
+
+ return nil
+}
diff --git a/service/rest_admin_service/handlers/permission/handlers.go b/service/rest_admin_service/handlers/permission/handlers.go
index 63b0db7..0fea652 100644
--- a/service/rest_admin_service/handlers/permission/handlers.go
+++ b/service/rest_admin_service/handlers/permission/handlers.go
@@ -3,9 +3,12 @@ package permissionshandler
import (
"bitrix_balancer_api/core/typescore"
"bitrix_balancer_api/core/utilscore"
+ "bitrix_balancer_api/rest_admin_service/handlers"
+ adminloghandler "bitrix_balancer_api/rest_admin_service/handlers/admin_actions"
"context"
"encoding/json"
"errors"
+ "fmt"
"github.com/sirupsen/logrus"
"io"
"net/http"
@@ -52,10 +55,7 @@ func (s *PermissionsReg) GetPermissionsListHandler(w http.ResponseWriter, r *htt
return nil, errW
}
- // 🚀 Подгружаем связанные данные
- for _, perm := range permissionsDbLst {
- s.enrichPermission(ctx, perm)
- }
+ s.enrichPermissionsBatch(ctx, permissionsDbLst)
return &typescore.ApiResponseBase{
TotalCount: total,
@@ -63,6 +63,135 @@ func (s *PermissionsReg) GetPermissionsListHandler(w http.ResponseWriter, r *htt
}, 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 := r.Context()
+
+ 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
+ }
+
+ s.enrichPermissionsBatch(ctx, permissions)
+
+ return &typescore.ApiResponseBase{
+ TotalCount: uint64(len(permissions)),
+ Data: permissions,
+ }, nil
+}
+
+// enrichPermissionsBatch пакетно подгружает роли, категории и темы для списка прав
+func (s *PermissionsReg) enrichPermissionsBatch(ctx context.Context, permissions []*typescore.Permission) {
+ if len(permissions) == 0 {
+ return
+ }
+
+ roleIDsSet := make(map[uint64]struct{})
+ categoryIDsSet := make(map[uint64]struct{})
+ topicIDsSet := make(map[uint64]struct{})
+
+ for _, p := range permissions {
+ if p.RoleID != nil {
+ roleIDsSet[*p.RoleID] = struct{}{}
+ }
+ if p.TopicCategoryID != nil {
+ categoryIDsSet[*p.TopicCategoryID] = struct{}{}
+ }
+ if p.TopicID != nil {
+ topicIDsSet[*p.TopicID] = struct{}{}
+ }
+ }
+
+ roleIDs := make([]uint64, 0, len(roleIDsSet))
+ for id := range roleIDsSet {
+ roleIDs = append(roleIDs, id)
+ }
+ categoryIDs := make([]uint64, 0, len(categoryIDsSet))
+ for id := range categoryIDsSet {
+ categoryIDs = append(categoryIDs, id)
+ }
+ topicIDs := make([]uint64, 0, len(topicIDsSet))
+ for id := range topicIDsSet {
+ topicIDs = append(topicIDs, id)
+ }
+
+ rolesMap := make(map[uint64]*typescore.Role)
+ if roles, err := s.ipc.Database.Role.GetRolesByIDsDB(ctx, roleIDs); err == nil {
+ for _, role := range roles {
+ if role.ID != nil {
+ rolesMap[*role.ID] = role
+ }
+ }
+ }
+
+ categoriesMap := make(map[uint64]*typescore.ApprovalTopicCategory)
+ if categories, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoriesByIDsDB(ctx, categoryIDs); err == nil {
+ for _, c := range categories {
+ if c.ID != nil {
+ categoriesMap[*c.ID] = c
+ }
+ }
+ }
+
+ topicsMap := make(map[uint64]*typescore.ApprovalTopic)
+ if topics, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicsByIDsDB(ctx, topicIDs); err == nil {
+ for _, t := range topics {
+ if t.ID != nil {
+ topicsMap[*t.ID] = t
+ }
+ }
+ }
+
+ for _, p := range permissions {
+ if p.RoleID != nil {
+ if role, ok := rolesMap[*p.RoleID]; ok {
+ p.Role = role
+ }
+ }
+ if p.TopicCategoryID != nil {
+ if cat, ok := categoriesMap[*p.TopicCategoryID]; ok {
+ p.TopicCategory = cat
+ }
+ }
+ if p.TopicID != nil {
+ if topic, ok := topicsMap[*p.TopicID]; ok {
+ p.Topic = topic
+ }
+ }
+ }
+}
+
// GetPermissionByIDHandler Получение права по ID
// @Summary Получение права по ID
// @Description Получение детальной информации о праве по его ID
@@ -103,58 +232,6 @@ func (s *PermissionsReg) GetPermissionByIDHandler(w http.ResponseWriter, r *http
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 := r.Context()
-
- // Проверяем, что роль существует
- 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 Назначение права на действие для роли
@@ -182,7 +259,6 @@ func (s *PermissionsReg) CreatePermissionHandler(w http.ResponseWriter, r *http.
return nil, errors.New("invalid request body")
}
- // Валидация обязательных полей
if req.RoleID == nil {
return nil, errors.New("role_id is required")
}
@@ -190,14 +266,12 @@ func (s *PermissionsReg) CreatePermissionHandler(w http.ResponseWriter, r *http.
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 := r.Context()
- // Проверяем существование роли
role, err := s.ipc.Database.Role.GetRoleByIDDB(ctx, *req.RoleID)
if err != nil {
return nil, err
@@ -206,7 +280,6 @@ func (s *PermissionsReg) CreatePermissionHandler(w http.ResponseWriter, r *http.
return nil, errors.New("role not found")
}
- // Если указана категория — проверяем её существование
if req.TopicCategoryID != nil {
category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *req.TopicCategoryID)
if err != nil {
@@ -217,7 +290,6 @@ func (s *PermissionsReg) CreatePermissionHandler(w http.ResponseWriter, r *http.
}
}
- // Если указана тема — проверяем её существование
if req.TopicID != nil {
topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *req.TopicID)
if err != nil {
@@ -227,7 +299,6 @@ func (s *PermissionsReg) CreatePermissionHandler(w http.ResponseWriter, r *http.
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")
@@ -235,7 +306,6 @@ func (s *PermissionsReg) CreatePermissionHandler(w http.ResponseWriter, r *http.
}
}
- // 🛡 Проверяем, что такое право ещё не существует
existingPermissions, _, err := s.ipc.Database.Permission.GetPermissionsListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.Permission{
RoleID: req.RoleID,
@@ -258,6 +328,26 @@ func (s *PermissionsReg) CreatePermissionHandler(w http.ResponseWriter, r *http.
s.enrichPermission(ctx, createdPermission)
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ snapshot := map[string]interface{}{
+ "role_id": *createdPermission.RoleID,
+ "action": utilscore.DerefStr(createdPermission.Action),
+ }
+ if createdPermission.TopicCategoryID != nil {
+ snapshot["topic_category_id"] = *createdPermission.TopicCategoryID
+ }
+ if createdPermission.TopicID != nil {
+ snapshot["topic_id"] = *createdPermission.TopicID
+ }
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "create", "permission", createdPermission.ID,
+ fmt.Sprintf("Выдано право «%s» роли «%s» на %s", utilscore.DerefStr(createdPermission.Action), roleLabel(createdPermission.Role), scopeLabel(createdPermission)),
+ map[string]interface{}{"snapshot": snapshot},
+ )
+ }
+
return createdPermission, nil
}
@@ -293,7 +383,6 @@ func (s *PermissionsReg) UpdatePermissionHandler(w http.ResponseWriter, r *http.
ctx := r.Context()
- // Проверяем, что право существует
existingPermissions, _, err := s.ipc.Database.Permission.GetPermissionsListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.Permission{ID: req.ID},
})
@@ -305,14 +394,12 @@ func (s *PermissionsReg) UpdatePermissionHandler(w http.ResponseWriter, r *http.
}
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)
@@ -325,7 +412,6 @@ func (s *PermissionsReg) UpdatePermissionHandler(w http.ResponseWriter, r *http.
}
}
- // Если обновляется 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)
@@ -338,7 +424,6 @@ func (s *PermissionsReg) UpdatePermissionHandler(w http.ResponseWriter, r *http.
}
}
- // Если обновляется topic_id — проверяем существование и принадлежность категории
if req.TopicID != nil {
if existing.TopicID == nil || *existing.TopicID != *req.TopicID {
topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *req.TopicID)
@@ -349,7 +434,6 @@ func (s *PermissionsReg) UpdatePermissionHandler(w http.ResponseWriter, r *http.
return nil, errors.New("topic not found")
}
- // Проверяем соответствие категории
categoryIDToCheck := req.TopicCategoryID
if categoryIDToCheck == nil {
categoryIDToCheck = existing.TopicCategoryID
@@ -360,6 +444,38 @@ func (s *PermissionsReg) UpdatePermissionHandler(w http.ResponseWriter, r *http.
}
}
+ type fieldChange struct {
+ Field string `json:"field"`
+ Old interface{} `json:"old"`
+ New interface{} `json:"new"`
+ }
+ var changes []fieldChange
+
+ if req.Action != nil && !utilscore.StrEq(existing.Action, req.Action) {
+ changes = append(changes, fieldChange{"action", utilscore.DerefStr(existing.Action), *req.Action})
+ }
+ if req.RoleID != nil && !utilscore.Uint64Eq(existing.RoleID, req.RoleID) {
+ var oldVal interface{}
+ if existing.RoleID != nil {
+ oldVal = *existing.RoleID
+ }
+ changes = append(changes, fieldChange{"role_id", oldVal, *req.RoleID})
+ }
+ if req.TopicCategoryID != nil && !utilscore.Uint64Eq(existing.TopicCategoryID, req.TopicCategoryID) {
+ var oldVal interface{}
+ if existing.TopicCategoryID != nil {
+ oldVal = *existing.TopicCategoryID
+ }
+ changes = append(changes, fieldChange{"topic_category_id", oldVal, *req.TopicCategoryID})
+ }
+ if req.TopicID != nil && !utilscore.Uint64Eq(existing.TopicID, req.TopicID) {
+ var oldVal interface{}
+ if existing.TopicID != nil {
+ oldVal = *existing.TopicID
+ }
+ changes = append(changes, fieldChange{"topic_id", oldVal, *req.TopicID})
+ }
+
updatedPermission, _, err := s.ipc.Database.Permission.UpdatePermissionDB(ctx, nil, &req, true)
if err != nil {
return nil, err
@@ -367,6 +483,18 @@ func (s *PermissionsReg) UpdatePermissionHandler(w http.ResponseWriter, r *http.
s.enrichPermission(ctx, updatedPermission)
+ if len(changes) > 0 {
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "update", "permission", req.ID,
+ fmt.Sprintf("Изменено право роли «%s»", roleLabel(updatedPermission.Role)),
+ map[string]interface{}{"changes": changes},
+ )
+ }
+ }
+
return updatedPermission, nil
}
@@ -402,7 +530,6 @@ func (s *PermissionsReg) DeletePermissionHandler(w http.ResponseWriter, r *http.
ctx := r.Context()
- // Проверяем, что право существует
existingPermissions, _, err := s.ipc.Database.Permission.GetPermissionsListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.Permission{ID: req.ID},
})
@@ -412,12 +539,36 @@ func (s *PermissionsReg) DeletePermissionHandler(w http.ResponseWriter, r *http.
if len(existingPermissions) == 0 {
return nil, errors.New("permission not found")
}
+ existing := existingPermissions[0]
+ s.enrichPermission(ctx, existing)
err = s.ipc.Database.Permission.DeletePermissionDB(ctx, &req)
if err != nil {
return nil, err
}
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ snapshot := map[string]interface{}{
+ "action": utilscore.DerefStr(existing.Action),
+ }
+ if existing.RoleID != nil {
+ snapshot["role_id"] = *existing.RoleID
+ }
+ if existing.TopicCategoryID != nil {
+ snapshot["topic_category_id"] = *existing.TopicCategoryID
+ }
+ if existing.TopicID != nil {
+ snapshot["topic_id"] = *existing.TopicID
+ }
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "delete", "permission", req.ID,
+ fmt.Sprintf("Отозвано право «%s» у роли «%s» на %s", utilscore.DerefStr(existing.Action), roleLabel(existing.Role), scopeLabel(existing)),
+ map[string]interface{}{"snapshot": snapshot},
+ )
+ }
+
return true, nil
}
@@ -427,7 +578,6 @@ func (s *PermissionsReg) enrichPermission(ctx context.Context, perm *typescore.P
return
}
- // Подгружаем роль
if perm.RoleID != nil {
role, err := s.ipc.Database.Role.GetRoleByIDDB(ctx, *perm.RoleID)
if err == nil && role != nil {
@@ -435,7 +585,6 @@ func (s *PermissionsReg) enrichPermission(ctx context.Context, perm *typescore.P
}
}
- // Подгружаем категорию тем
if perm.TopicCategoryID != nil {
category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *perm.TopicCategoryID)
if err == nil && category != nil {
@@ -443,7 +592,6 @@ func (s *PermissionsReg) enrichPermission(ctx context.Context, perm *typescore.P
}
}
- // Подгружаем тему
if perm.TopicID != nil {
topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *perm.TopicID)
if err == nil && topic != nil {
@@ -465,3 +613,36 @@ func isValidAction(action string) bool {
}
return validActions[action]
}
+
+func roleLabel(role *typescore.Role) string {
+ if role == nil || role.Name == nil {
+ return "—"
+ }
+ return *role.Name
+}
+
+func scopeLabel(perm *typescore.Permission) string {
+ if perm.Topic != nil && perm.Topic.Name != nil {
+ return "тему «" + *perm.Topic.Name + "»"
+ }
+ if perm.TopicCategory != nil && perm.TopicCategory.Name != nil {
+ return "категорию «" + *perm.TopicCategory.Name + "»"
+ }
+ return "все темы"
+}
+
+func (s *PermissionsReg) getCurrentAdmin(ctx context.Context) (*typescore.Admin, bool) {
+ currentUserID, err := handlers.GetIDFromContext(ctx)
+ if err != nil {
+ return nil, false
+ }
+
+ admins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{
+ Filtering: &typescore.Admin{ID: ¤tUserID},
+ })
+ if err != nil || len(admins) == 0 || admins[0] == nil || admins[0].ID == nil || admins[0].Login == nil {
+ return nil, false
+ }
+
+ return admins[0], true
+}
diff --git a/service/rest_admin_service/handlers/roles/handlers.go b/service/rest_admin_service/handlers/roles/handlers.go
index 9cab5cb..b74e966 100644
--- a/service/rest_admin_service/handlers/roles/handlers.go
+++ b/service/rest_admin_service/handlers/roles/handlers.go
@@ -3,12 +3,17 @@ package roleshandler
import (
"bitrix_balancer_api/core/typescore"
"bitrix_balancer_api/core/utilscore"
+ "bitrix_balancer_api/rest_admin_service/handlers"
+ adminloghandler "bitrix_balancer_api/rest_admin_service/handlers/admin_actions"
+ "context"
"encoding/json"
"errors"
+ "fmt"
"github.com/sirupsen/logrus"
"io"
"net/http"
"strconv"
+ "strings"
"github.com/go-chi/chi/v5"
)
@@ -114,7 +119,6 @@ func (s *RolesReg) CreateRoleHandler(w http.ResponseWriter, r *http.Request) (in
return nil, errors.New("invalid request body")
}
- // Валидация обязательных полей
if req.Name == nil || *req.Name == "" {
return nil, errors.New("role name is required")
}
@@ -122,7 +126,6 @@ func (s *RolesReg) CreateRoleHandler(w http.ResponseWriter, r *http.Request) (in
return nil, errors.New("role code is required")
}
- // Проверяем, что код уникален
ctx := r.Context()
existingRoles, _, err := s.ipc.Database.Role.GetRolesListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.Role{Code: req.Code},
@@ -134,7 +137,6 @@ func (s *RolesReg) CreateRoleHandler(w http.ResponseWriter, r *http.Request) (in
return nil, errors.New("role code already exists")
}
- // Устанавливаем значения по умолчанию для булевых флагов
if req.IsDefault == nil {
v := false
req.IsDefault = &v
@@ -161,6 +163,25 @@ func (s *RolesReg) CreateRoleHandler(w http.ResponseWriter, r *http.Request) (in
return nil, err
}
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ snapshot := map[string]interface{}{
+ "name": utilscore.DerefStr(createdRole.Name),
+ "code": utilscore.DerefStr(createdRole.Code),
+ "is_default": utilscore.DerefBool(createdRole.IsDefault),
+ "is_director": utilscore.DerefBool(createdRole.IsDirector),
+ "is_approver": utilscore.DerefBool(createdRole.IsApprover),
+ "is_observer": utilscore.DerefBool(createdRole.IsObserver),
+ "is_executor": utilscore.DerefBool(createdRole.IsExecutor),
+ }
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "create", "role", createdRole.ID,
+ fmt.Sprintf("Создана роль «%s»", utilscore.DerefStr(createdRole.Name)),
+ map[string]interface{}{"snapshot": snapshot},
+ )
+ }
+
return createdRole, nil
}
@@ -194,7 +215,6 @@ func (s *RolesReg) UpdateRoleHandler(w http.ResponseWriter, r *http.Request) (in
return nil, errors.New("role id is required")
}
- // Проверяем, что роль существует
ctx := r.Context()
existingRole, err := s.ipc.Database.Role.GetRoleByIDDB(ctx, *req.ID)
if err != nil {
@@ -204,7 +224,6 @@ func (s *RolesReg) UpdateRoleHandler(w http.ResponseWriter, r *http.Request) (in
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{
@@ -219,11 +238,64 @@ func (s *RolesReg) UpdateRoleHandler(w http.ResponseWriter, r *http.Request) (in
}
}
+ type fieldChange struct {
+ Field string `json:"field"`
+ Old interface{} `json:"old"`
+ New interface{} `json:"new"`
+ }
+ var changes []fieldChange
+ var summary []string
+
+ if req.Name != nil && !utilscore.StrEq(existingRole.Name, req.Name) {
+ changes = append(changes, fieldChange{"name", utilscore.DerefStr(existingRole.Name), *req.Name})
+ summary = append(summary, fmt.Sprintf("название: «%s» → «%s»", utilscore.DerefStr(existingRole.Name), *req.Name))
+ }
+ if req.Code != nil && !utilscore.StrEq(existingRole.Code, req.Code) {
+ changes = append(changes, fieldChange{"code", utilscore.DerefStr(existingRole.Code), *req.Code})
+ summary = append(summary, fmt.Sprintf("код: «%s» → «%s»", utilscore.DerefStr(existingRole.Code), *req.Code))
+ }
+
+ boolFields := []struct {
+ name string
+ old *bool
+ new *bool
+ flag string
+ }{
+ {"is_default", existingRole.IsDefault, req.IsDefault, "по умолчанию"},
+ {"is_director", existingRole.IsDirector, req.IsDirector, "директор"},
+ {"is_approver", existingRole.IsApprover, req.IsApprover, "согласующий"},
+ {"is_observer", existingRole.IsObserver, req.IsObserver, "наблюдатель"},
+ {"is_executor", existingRole.IsExecutor, req.IsExecutor, "исполнитель"},
+ }
+ for _, f := range boolFields {
+ if f.new != nil && !utilscore.BoolEq(f.old, f.new) {
+ changes = append(changes, fieldChange{f.name, utilscore.DerefBool(f.old), *f.new})
+ if *f.new {
+ summary = append(summary, fmt.Sprintf("включён флаг «%s»", f.flag))
+ } else {
+ summary = append(summary, fmt.Sprintf("выключен флаг «%s»", f.flag))
+ }
+ }
+ }
+
updatedRole, _, err := s.ipc.Database.Role.UpdateRoleDB(ctx, nil, &req, true)
if err != nil {
return nil, err
}
+ if len(changes) > 0 {
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ description := fmt.Sprintf("Изменена роль «%s»: %s", utilscore.DerefStr(existingRole.Name), strings.Join(summary, "; "))
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "update", "role", req.ID,
+ description,
+ map[string]interface{}{"changes": changes},
+ )
+ }
+ }
+
return updatedRole, nil
}
@@ -257,7 +329,6 @@ func (s *RolesReg) DeleteRoleHandler(w http.ResponseWriter, r *http.Request) (in
return nil, errors.New("role id is required")
}
- // Проверяем, что роль существует
ctx := r.Context()
existingRole, err := s.ipc.Database.Role.GetRoleByIDDB(ctx, *req.ID)
if err != nil {
@@ -267,7 +338,6 @@ func (s *RolesReg) DeleteRoleHandler(w http.ResponseWriter, r *http.Request) (in
return nil, errors.New("role not found")
}
- // 🛡 Защита от удаления дефолтной роли
if existingRole.IsDefault != nil && *existingRole.IsDefault {
return nil, errors.New("cannot delete default role")
}
@@ -277,5 +347,39 @@ func (s *RolesReg) DeleteRoleHandler(w http.ResponseWriter, r *http.Request) (in
return nil, err
}
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ snapshot := map[string]interface{}{
+ "name": utilscore.DerefStr(existingRole.Name),
+ "code": utilscore.DerefStr(existingRole.Code),
+ "is_director": utilscore.DerefBool(existingRole.IsDirector),
+ "is_approver": utilscore.DerefBool(existingRole.IsApprover),
+ "is_observer": utilscore.DerefBool(existingRole.IsObserver),
+ "is_executor": utilscore.DerefBool(existingRole.IsExecutor),
+ }
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "delete", "role", req.ID,
+ fmt.Sprintf("Удалена роль «%s»", utilscore.DerefStr(existingRole.Name)),
+ map[string]interface{}{"snapshot": snapshot},
+ )
+ }
+
return true, nil
}
+
+func (s *RolesReg) getCurrentAdmin(ctx context.Context) (*typescore.Admin, bool) {
+ currentUserID, err := handlers.GetIDFromContext(ctx)
+ if err != nil {
+ return nil, false
+ }
+
+ admins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{
+ Filtering: &typescore.Admin{ID: ¤tUserID},
+ })
+ if err != nil || len(admins) == 0 || admins[0] == nil || admins[0].ID == nil || admins[0].Login == nil {
+ return nil, false
+ }
+
+ return admins[0], true
+}
diff --git a/service/rest_admin_service/handlers/system_monitoring/handlers.go b/service/rest_admin_service/handlers/system_monitoring/handlers.go
new file mode 100644
index 0000000..6b15eed
--- /dev/null
+++ b/service/rest_admin_service/handlers/system_monitoring/handlers.go
@@ -0,0 +1,259 @@
+package monitoringhandler
+
+import (
+ "bitrix_balancer_api/rest_admin_service/handlers"
+ typesm "bitrix_balancer_api/rest_admin_service/types"
+ "context"
+ "net/http"
+ "os"
+ "os/exec"
+ "strconv"
+ "strings"
+ "syscall"
+ "time"
+
+ "github.com/go-chi/chi/v5"
+)
+
+type MonitoringReg struct {
+ ipc *typesm.InternalProviderControl
+ // 🆕 ВАЖНО: впишите реальные имена systemd-юнитов ваших сервисов —
+ // я не знаю точных названий, использовал правдоподобные заглушки.
+ // Узнать реальные: `systemctl list-units --type=service | grep -i bitrix`
+ // (или как вы их называли при настройке systemd-юнитов).
+ monitoredUnits []monitoredUnit
+}
+
+type monitoredUnit struct {
+ Label string // как показывать в интерфейсе
+ Unit string // реальное имя systemd-юнита, например "bitrix-bot.service"
+}
+
+func RegisterMonitoringRoutes(r chi.Router, ipc *typesm.InternalProviderControl) error {
+ s := &MonitoringReg{
+ ipc: ipc,
+ monitoredUnits: []monitoredUnit{
+ {Label: "Telegram-бот", Unit: "bitrix-telegram-bot.service"},
+ {Label: "Admin REST API", Unit: "bitrix-rest-admin.service"},
+ {Label: "nginx", Unit: "nginx.service"},
+ {Label: "PostgreSQL", Unit: "postgresql.service"},
+ {Label: "Redis", Unit: "redis-server.service"},
+ },
+ }
+
+ r.Route("/api/monitoring", 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.GetMonitoringStatusHandler)
+ })
+
+ return nil
+}
+
+func (s *MonitoringReg) GetMonitoringStatusHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ ctx := r.Context()
+
+ services := make([]map[string]interface{}, 0, len(s.monitoredUnits))
+ for _, u := range s.monitoredUnits {
+ services = append(services, s.checkSystemdUnit(u))
+ }
+
+ resources := getHostResources()
+
+ dbHealthy, dbLatencyMs := s.checkDatabase(ctx)
+ redisHealthy, redisLatencyMs := s.checkRedis(ctx)
+
+ return map[string]interface{}{
+ "services": services,
+ "resources": resources,
+ "health": map[string]interface{}{
+ "database": map[string]interface{}{
+ "healthy": dbHealthy,
+ "latency_ms": dbLatencyMs,
+ },
+ "redis": map[string]interface{}{
+ "healthy": redisHealthy,
+ "latency_ms": redisLatencyMs,
+ },
+ },
+ "checked_at": time.Now().Format(time.RFC3339),
+ }, nil
+}
+
+func (s *MonitoringReg) checkSystemdUnit(u monitoredUnit) map[string]interface{} {
+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
+ defer cancel()
+
+ cmd := exec.CommandContext(ctx, "systemctl", "show", u.Unit,
+ "--property=ActiveState,SubState,ActiveEnterTimestamp", "--value")
+ output, err := cmd.Output()
+
+ result := map[string]interface{}{
+ "label": u.Label,
+ "unit": u.Unit,
+ }
+
+ if err != nil {
+ result["active"] = false
+ result["state"] = "unknown"
+ result["error"] = "не удалось получить статус (юнит не найден или нет прав)"
+ return result
+ }
+
+ lines := strings.Split(strings.TrimSpace(string(output)), "\n")
+ activeState := ""
+ subState := ""
+ since := ""
+ if len(lines) >= 1 {
+ activeState = strings.TrimSpace(lines[0])
+ }
+ if len(lines) >= 2 {
+ subState = strings.TrimSpace(lines[1])
+ }
+ if len(lines) >= 3 {
+ since = strings.TrimSpace(lines[2])
+ }
+
+ result["active"] = activeState == "active"
+ result["state"] = activeState + "/" + subState
+ if since != "" {
+ result["since"] = since
+ }
+
+ return result
+}
+
+func getHostResources() map[string]interface{} {
+ return map[string]interface{}{
+ "load_average": getLoadAverage(),
+ "memory": getMemoryInfo(),
+ "disk": getDiskInfo("/"),
+ "uptime_seconds": getUptimeSeconds(),
+ }
+}
+
+// getLoadAverage — /proc/loadavg: "0.52 0.58 0.59 1/234 5678"
+func getLoadAverage() map[string]interface{} {
+ data, err := readFile("/proc/loadavg")
+ if err != nil {
+ return map[string]interface{}{"error": "недоступно"}
+ }
+ fields := strings.Fields(data)
+ if len(fields) < 3 {
+ return map[string]interface{}{"error": "не удалось разобрать"}
+ }
+ l1, _ := strconv.ParseFloat(fields[0], 64)
+ l5, _ := strconv.ParseFloat(fields[1], 64)
+ l15, _ := strconv.ParseFloat(fields[2], 64)
+ return map[string]interface{}{"1m": l1, "5m": l5, "15m": l15}
+}
+
+// getMemoryInfo — /proc/meminfo, ключевые поля в килобайтах у ядра
+func getMemoryInfo() map[string]interface{} {
+ data, err := readFile("/proc/meminfo")
+ if err != nil {
+ return map[string]interface{}{"error": "недоступно"}
+ }
+
+ values := map[string]uint64{}
+ for _, line := range strings.Split(data, "\n") {
+ parts := strings.Fields(line)
+ if len(parts) < 2 {
+ continue
+ }
+ key := strings.TrimSuffix(parts[0], ":")
+ val, err := strconv.ParseUint(parts[1], 10, 64)
+ if err != nil {
+ continue
+ }
+ values[key] = val * 1024 // kB -> bytes
+ }
+
+ total := values["MemTotal"]
+ available := values["MemAvailable"]
+ used := uint64(0)
+ if total > available {
+ used = total - available
+ }
+
+ percent := 0.0
+ if total > 0 {
+ percent = float64(used) / float64(total) * 100
+ }
+
+ return map[string]interface{}{
+ "total_bytes": total,
+ "used_bytes": used,
+ "available_bytes": available,
+ "used_percent": percent,
+ }
+}
+
+// getDiskInfo — syscall.Statfs по корневой ФС (Linux)
+func getDiskInfo(path string) map[string]interface{} {
+ var stat syscall.Statfs_t
+ if err := syscall.Statfs(path, &stat); err != nil {
+ return map[string]interface{}{"error": "недоступно"}
+ }
+
+ total := stat.Blocks * uint64(stat.Bsize)
+ free := stat.Bavail * uint64(stat.Bsize)
+ used := total - free
+
+ percent := 0.0
+ if total > 0 {
+ percent = float64(used) / float64(total) * 100
+ }
+
+ return map[string]interface{}{
+ "path": path,
+ "total_bytes": total,
+ "used_bytes": used,
+ "free_bytes": free,
+ "used_percent": percent,
+ }
+}
+
+func getUptimeSeconds() float64 {
+ data, err := readFile("/proc/uptime")
+ if err != nil {
+ return 0
+ }
+ fields := strings.Fields(data)
+ if len(fields) < 1 {
+ return 0
+ }
+ seconds, _ := strconv.ParseFloat(fields[0], 64)
+ return seconds
+}
+
+func (s *MonitoringReg) checkDatabase(ctx context.Context) (bool, int64) {
+ start := time.Now()
+ timeoutCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
+ defer cancel()
+
+ _, _, err := s.ipc.Database.User.GetUsersListDB(timeoutCtx)
+ latency := time.Since(start).Milliseconds()
+
+ return err == nil, latency
+}
+
+func (s *MonitoringReg) checkRedis(ctx context.Context) (bool, int64) {
+ start := time.Now()
+ timeoutCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
+ defer cancel()
+
+ err := s.ipc.RedisClient.RedisClient.Ping(timeoutCtx)
+ latency := time.Since(start).Milliseconds()
+
+ return err == nil, latency
+}
+
+func readFile(path string) (string, error) {
+ data, err := os.ReadFile(path)
+ if err != nil {
+ return "", err
+ }
+ return string(data), nil
+}
diff --git a/service/rest_admin_service/handlers/topic_categories/handlers.go b/service/rest_admin_service/handlers/topic_categories/handlers.go
index 08b76ac..3f759f3 100644
--- a/service/rest_admin_service/handlers/topic_categories/handlers.go
+++ b/service/rest_admin_service/handlers/topic_categories/handlers.go
@@ -3,12 +3,17 @@ package categorieshandler
import (
"bitrix_balancer_api/core/typescore"
"bitrix_balancer_api/core/utilscore"
+ "bitrix_balancer_api/rest_admin_service/handlers"
+ adminloghandler "bitrix_balancer_api/rest_admin_service/handlers/admin_actions"
+ "context"
"encoding/json"
"errors"
+ "fmt"
"github.com/sirupsen/logrus"
"io"
"net/http"
"strconv"
+ "strings"
"github.com/go-chi/chi/v5"
)
@@ -87,7 +92,6 @@ func (s *CategoriesReg) GetCategoryByIDHandler(w http.ResponseWriter, r *http.Re
return nil, errors.New("category not found")
}
- // Подгружаем темы этой категории
topics, _, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.ApprovalTopic{CategoryID: &id},
})
@@ -123,7 +127,6 @@ func (s *CategoriesReg) CreateCategoryHandler(w http.ResponseWriter, r *http.Req
return nil, errors.New("invalid request body")
}
- // Валидация обязательных полей
if req.Name == nil || *req.Name == "" {
return nil, errors.New("category name is required")
}
@@ -131,7 +134,6 @@ func (s *CategoriesReg) CreateCategoryHandler(w http.ResponseWriter, r *http.Req
return nil, errors.New("category code is required")
}
- // Проверяем, что код уникален
ctx := r.Context()
existingCategories, _, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.ApprovalTopicCategory{Code: req.Code},
@@ -143,7 +145,6 @@ func (s *CategoriesReg) CreateCategoryHandler(w http.ResponseWriter, r *http.Req
return nil, errors.New("category code already exists")
}
- // Устанавливаем is_active по умолчанию
if req.IsActive == nil {
isActive := true
req.IsActive = &isActive
@@ -154,6 +155,21 @@ func (s *CategoriesReg) CreateCategoryHandler(w http.ResponseWriter, r *http.Req
return nil, err
}
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ snapshot := map[string]interface{}{
+ "name": utilscore.DerefStr(createdCategory.Name),
+ "code": utilscore.DerefStr(createdCategory.Code),
+ "is_active": utilscore.DerefBool(createdCategory.IsActive),
+ }
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "create", "category", createdCategory.ID,
+ fmt.Sprintf("Создана категория «%s»", utilscore.DerefStr(createdCategory.Name)),
+ map[string]interface{}{"snapshot": snapshot},
+ )
+ }
+
return createdCategory, nil
}
@@ -187,7 +203,6 @@ func (s *CategoriesReg) UpdateCategoryHandler(w http.ResponseWriter, r *http.Req
return nil, errors.New("category id is required")
}
- // Проверяем, что категория существует
ctx := r.Context()
existingCategory, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *req.ID)
if err != nil {
@@ -197,7 +212,6 @@ func (s *CategoriesReg) UpdateCategoryHandler(w http.ResponseWriter, r *http.Req
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{
@@ -212,11 +226,49 @@ func (s *CategoriesReg) UpdateCategoryHandler(w http.ResponseWriter, r *http.Req
}
}
+ type fieldChange struct {
+ Field string `json:"field"`
+ Old interface{} `json:"old"`
+ New interface{} `json:"new"`
+ }
+ var changes []fieldChange
+ var summary []string
+
+ if req.Name != nil && !utilscore.StrEq(existingCategory.Name, req.Name) {
+ changes = append(changes, fieldChange{"name", utilscore.DerefStr(existingCategory.Name), *req.Name})
+ summary = append(summary, fmt.Sprintf("название: «%s» → «%s»", utilscore.DerefStr(existingCategory.Name), *req.Name))
+ }
+ if req.Code != nil && !utilscore.StrEq(existingCategory.Code, req.Code) {
+ changes = append(changes, fieldChange{"code", utilscore.DerefStr(existingCategory.Code), *req.Code})
+ summary = append(summary, fmt.Sprintf("код: «%s» → «%s»", utilscore.DerefStr(existingCategory.Code), *req.Code))
+ }
+ if req.IsActive != nil && !utilscore.BoolEq(existingCategory.IsActive, req.IsActive) {
+ changes = append(changes, fieldChange{"is_active", utilscore.DerefBool(existingCategory.IsActive), *req.IsActive})
+ if *req.IsActive {
+ summary = append(summary, "активирована")
+ } else {
+ summary = append(summary, "деактивирована")
+ }
+ }
+
updatedCategory, _, err := s.ipc.Database.ApprovalTopicCategory.UpdateApprovalTopicCategoryDB(ctx, nil, &req, true)
if err != nil {
return nil, err
}
+ if len(changes) > 0 {
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ description := fmt.Sprintf("Изменена категория «%s»: %s", utilscore.DerefStr(existingCategory.Name), strings.Join(summary, "; "))
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "update", "category", req.ID,
+ description,
+ map[string]interface{}{"changes": changes},
+ )
+ }
+ }
+
return updatedCategory, nil
}
@@ -251,7 +303,6 @@ func (s *CategoriesReg) DeleteCategoryHandler(w http.ResponseWriter, r *http.Req
return nil, errors.New("category id is required")
}
- // Проверяем, что категория существует
ctx := r.Context()
existingCategory, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *req.ID)
if err != nil {
@@ -276,5 +327,35 @@ func (s *CategoriesReg) DeleteCategoryHandler(w http.ResponseWriter, r *http.Req
return nil, err
}
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ snapshot := map[string]interface{}{
+ "name": utilscore.DerefStr(existingCategory.Name),
+ "code": utilscore.DerefStr(existingCategory.Code),
+ }
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "delete", "category", req.ID,
+ fmt.Sprintf("Удалена категория «%s»", utilscore.DerefStr(existingCategory.Name)),
+ map[string]interface{}{"snapshot": snapshot},
+ )
+ }
+
return true, nil
}
+
+func (s *CategoriesReg) getCurrentAdmin(ctx context.Context) (*typescore.Admin, bool) {
+ currentUserID, err := handlers.GetIDFromContext(ctx)
+ if err != nil {
+ return nil, false
+ }
+
+ admins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{
+ Filtering: &typescore.Admin{ID: ¤tUserID},
+ })
+ if err != nil || len(admins) == 0 || admins[0] == nil || admins[0].ID == nil || admins[0].Login == nil {
+ return nil, false
+ }
+
+ return admins[0], true
+}
diff --git a/service/rest_admin_service/handlers/topic_executors/handlers.go b/service/rest_admin_service/handlers/topic_executors/handlers.go
index cc35b9a..462b27d 100644
--- a/service/rest_admin_service/handlers/topic_executors/handlers.go
+++ b/service/rest_admin_service/handlers/topic_executors/handlers.go
@@ -3,15 +3,18 @@ package topicexecutorshandler
import (
"bitrix_balancer_api/core/typescore"
"bitrix_balancer_api/core/utilscore"
+ "bitrix_balancer_api/rest_admin_service/handlers"
+ adminloghandler "bitrix_balancer_api/rest_admin_service/handlers/admin_actions"
"context"
"encoding/json"
"errors"
+ "fmt"
+ "github.com/go-chi/chi/v5"
"github.com/sirupsen/logrus"
"io"
"net/http"
"strconv"
-
- "github.com/go-chi/chi/v5"
+ "strings"
)
// GetTopicExecutorsListHandler Получение списка исполнителей тем
@@ -24,6 +27,7 @@ import (
// @Param limit query integer false "Количество записей на странице"
// @Param topic_id query integer false "Фильтр по теме"
// @Param user_id 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 "Некорректный запрос"
@@ -38,6 +42,13 @@ func (s *TopicExecutorsReg) GetTopicExecutorsListHandler(w http.ResponseWriter,
return nil, errW
}
+ var categoryID *uint64
+ if categoryIDStr := queryParams.Get("category_id"); categoryIDStr != "" {
+ if id, err := strconv.ParseUint(categoryIDStr, 10, 64); err == nil {
+ categoryID = &id
+ }
+ }
+
options := typescore.ListDbOptions{
Filtering: executorParams,
Offset: offset,
@@ -46,22 +57,133 @@ func (s *TopicExecutorsReg) GetTopicExecutorsListHandler(w http.ResponseWriter,
}
ctx := r.Context()
- executorsDbLst, total, errW := s.ipc.Database.ApprovalTopicExecutor.GetApprovalTopicExecutorListDB(ctx, options)
- if errW != nil {
- return nil, errW
+
+ var executorsDbLst []*typescore.ApprovalTopicExecutor
+ var total uint64
+ var err error
+
+ if categoryID != nil {
+ executorsDbLst, total, err = s.ipc.Database.ApprovalTopicExecutor.GetApprovalTopicExecutorListByCategoryDB(ctx, options, *categoryID)
+ } else {
+ executorsDbLst, total, err = s.ipc.Database.ApprovalTopicExecutor.GetApprovalTopicExecutorListDB(ctx, options)
}
- // 🚀 Подгружаем связанные данные
- for _, exec := range executorsDbLst {
- s.enrichExecutor(ctx, exec)
+ if err != nil {
+ return nil, err
}
+ s.enrichExecutorsBatch(ctx, executorsDbLst)
+
return &typescore.ApiResponseBase{
TotalCount: total,
Data: executorsDbLst,
}, 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 := r.Context()
+
+ 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
+ }
+
+ s.enrichExecutorsBatch(ctx, executors)
+
+ return &typescore.ApiResponseBase{
+ TotalCount: uint64(len(executors)),
+ Data: executors,
+ }, nil
+}
+
+// enrichExecutorsBatch пакетно подгружает темы и пользователей для списка исполнителей
+func (s *TopicExecutorsReg) enrichExecutorsBatch(ctx context.Context, executors []*typescore.ApprovalTopicExecutor) {
+ if len(executors) == 0 {
+ return
+ }
+
+ topicIDsSet := make(map[uint64]struct{})
+ userIDsSet := make(map[uint64]struct{})
+ for _, e := range executors {
+ if e.TopicID != nil {
+ topicIDsSet[*e.TopicID] = struct{}{}
+ }
+ if e.UserID != nil {
+ userIDsSet[*e.UserID] = struct{}{}
+ }
+ }
+
+ topicIDs := make([]uint64, 0, len(topicIDsSet))
+ for id := range topicIDsSet {
+ topicIDs = append(topicIDs, id)
+ }
+ userIDs := make([]uint64, 0, len(userIDsSet))
+ for id := range userIDsSet {
+ userIDs = append(userIDs, id)
+ }
+
+ topicsMap := make(map[uint64]*typescore.ApprovalTopic)
+ if topics, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicsByIDsDB(ctx, topicIDs); err == nil {
+ for _, t := range topics {
+ if t.ID != nil {
+ topicsMap[*t.ID] = t
+ }
+ }
+ }
+
+ usersMap := make(map[uint64]*typescore.User)
+ if users, err := s.ipc.Database.User.GetUsersByIDsDB(ctx, userIDs); err == nil {
+ for _, u := range users {
+ if u.ID != nil {
+ usersMap[*u.ID] = u
+ }
+ }
+ }
+
+ for _, e := range executors {
+ if e.TopicID != nil {
+ if t, ok := topicsMap[*e.TopicID]; ok {
+ e.Topic = t
+ }
+ }
+ if e.UserID != nil {
+ if u, ok := usersMap[*e.UserID]; ok {
+ e.User = u
+ }
+ }
+ }
+}
+
// GetTopicExecutorByIDHandler Получение исполнителя по ID
// @Summary Получение исполнителя по ID
// @Description Получение детальной информации об исполнителе по его ID
@@ -102,56 +224,6 @@ func (s *TopicExecutorsReg) GetTopicExecutorByIDHandler(w http.ResponseWriter, r
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 := r.Context()
-
- // Проверяем, что тема существует
- 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 Назначение исполнителя для конкретной темы согласования
@@ -179,7 +251,6 @@ func (s *TopicExecutorsReg) CreateTopicExecutorHandler(w http.ResponseWriter, r
return nil, errors.New("invalid request body")
}
- // Валидация обязательных полей
if req.TopicID == nil {
return nil, errors.New("topic_id is required")
}
@@ -189,7 +260,6 @@ func (s *TopicExecutorsReg) CreateTopicExecutorHandler(w http.ResponseWriter, r
ctx := r.Context()
- // Проверяем существование темы
topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *req.TopicID)
if err != nil {
return nil, err
@@ -198,7 +268,6 @@ func (s *TopicExecutorsReg) CreateTopicExecutorHandler(w http.ResponseWriter, r
return nil, errors.New("topic not found")
}
- // Проверяем существование пользователя
user, err := s.ipc.Database.User.GetUserByIDDB(ctx, *req.UserID)
if err != nil {
return nil, err
@@ -207,7 +276,6 @@ func (s *TopicExecutorsReg) CreateTopicExecutorHandler(w http.ResponseWriter, r
return nil, errors.New("user not found")
}
- // Проверяем, что пользователь не заблокирован и не уволен
if user.IsBlocked != nil && *user.IsBlocked {
return nil, errors.New("user is blocked")
}
@@ -215,7 +283,6 @@ func (s *TopicExecutorsReg) CreateTopicExecutorHandler(w http.ResponseWriter, r
return nil, errors.New("user is fired")
}
- // 🛡 Проверяем, что такой исполнитель на этом шаге ещё не существует
stepOrder := 0
if req.StepOrder != nil {
stepOrder = *req.StepOrder
@@ -234,7 +301,6 @@ func (s *TopicExecutorsReg) CreateTopicExecutorHandler(w http.ResponseWriter, r
return nil, errors.New("this executor is already assigned to this step for the topic")
}
- // Устанавливаем значения по умолчанию
if req.StepOrder == nil {
defaultStep := 0
req.StepOrder = &defaultStep
@@ -255,6 +321,23 @@ func (s *TopicExecutorsReg) CreateTopicExecutorHandler(w http.ResponseWriter, r
s.enrichExecutor(ctx, createdExecutor)
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ snapshot := map[string]interface{}{
+ "topic_id": *req.TopicID,
+ "user_id": *req.UserID,
+ "step_order": utilscore.DerefInt(createdExecutor.StepOrder),
+ "require_file": utilscore.DerefBool(createdExecutor.RequireFile),
+ "is_active": utilscore.DerefBool(createdExecutor.IsActive),
+ }
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "create", "topic_executor", createdExecutor.ID,
+ fmt.Sprintf("Назначен исполнитель «%s» на тему «%s»", userLabel(createdExecutor.User), topicLabel(createdExecutor.Topic)),
+ map[string]interface{}{"snapshot": snapshot},
+ )
+ }
+
return createdExecutor, nil
}
@@ -290,7 +373,6 @@ func (s *TopicExecutorsReg) UpdateTopicExecutorHandler(w http.ResponseWriter, r
ctx := r.Context()
- // Проверяем, что запись существует
existingExecutors, _, err := s.ipc.Database.ApprovalTopicExecutor.GetApprovalTopicExecutorListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.ApprovalTopicExecutor{ID: req.ID},
})
@@ -301,8 +383,8 @@ func (s *TopicExecutorsReg) UpdateTopicExecutorHandler(w http.ResponseWriter, r
return nil, errors.New("topic executor not found")
}
existing := existingExecutors[0]
+ s.enrichExecutor(ctx, existing)
- // Если обновляется topic_id — проверяем существование
if req.TopicID != nil {
if existing.TopicID == nil || *existing.TopicID != *req.TopicID {
topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *req.TopicID)
@@ -315,7 +397,6 @@ func (s *TopicExecutorsReg) UpdateTopicExecutorHandler(w http.ResponseWriter, r
}
}
- // Если обновляется user_id — проверяем существование и статус
if req.UserID != nil {
if existing.UserID == nil || *existing.UserID != *req.UserID {
user, err := s.ipc.Database.User.GetUserByIDDB(ctx, *req.UserID)
@@ -334,6 +415,47 @@ func (s *TopicExecutorsReg) UpdateTopicExecutorHandler(w http.ResponseWriter, r
}
}
+ type fieldChange struct {
+ Field string `json:"field"`
+ Old interface{} `json:"old"`
+ New interface{} `json:"new"`
+ }
+ var changes []fieldChange
+ var summary []string
+
+ if req.UserID != nil && !utilscore.Uint64Eq(existing.UserID, req.UserID) {
+ var oldVal interface{}
+ if existing.UserID != nil {
+ oldVal = *existing.UserID
+ }
+ changes = append(changes, fieldChange{"user_id", oldVal, *req.UserID})
+ summary = append(summary, "заменён исполнитель")
+ }
+ if req.StepOrder != nil && !utilscore.IntEq(existing.StepOrder, req.StepOrder) {
+ var oldVal interface{}
+ if existing.StepOrder != nil {
+ oldVal = *existing.StepOrder
+ }
+ changes = append(changes, fieldChange{"step_order", oldVal, *req.StepOrder})
+ summary = append(summary, fmt.Sprintf("порядок шага: %v → %d", oldVal, *req.StepOrder))
+ }
+ if req.RequireFile != nil && !utilscore.BoolEq(existing.RequireFile, req.RequireFile) {
+ changes = append(changes, fieldChange{"require_file", utilscore.DerefBool(existing.RequireFile), *req.RequireFile})
+ if *req.RequireFile {
+ summary = append(summary, "включено обязательное вложение файла")
+ } else {
+ summary = append(summary, "отключено обязательное вложение файла")
+ }
+ }
+ if req.IsActive != nil && !utilscore.BoolEq(existing.IsActive, req.IsActive) {
+ changes = append(changes, fieldChange{"is_active", utilscore.DerefBool(existing.IsActive), *req.IsActive})
+ if *req.IsActive {
+ summary = append(summary, "активирован")
+ } else {
+ summary = append(summary, "деактивирован")
+ }
+ }
+
updatedExecutor, _, err := s.ipc.Database.ApprovalTopicExecutor.UpdateApprovalTopicExecutorDB(ctx, nil, &req, true)
if err != nil {
return nil, err
@@ -341,6 +463,19 @@ func (s *TopicExecutorsReg) UpdateTopicExecutorHandler(w http.ResponseWriter, r
s.enrichExecutor(ctx, updatedExecutor)
+ if len(changes) > 0 {
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ description := fmt.Sprintf("Изменён исполнитель темы «%s»: %s", topicLabel(existing.Topic), strings.Join(summary, "; "))
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "update", "topic_executor", req.ID,
+ description,
+ map[string]interface{}{"changes": changes},
+ )
+ }
+ }
+
return updatedExecutor, nil
}
@@ -376,11 +511,43 @@ func (s *TopicExecutorsReg) DeleteTopicExecutorHandler(w http.ResponseWriter, r
ctx := r.Context()
+ 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]
+ s.enrichExecutor(ctx, existing)
+
err = s.ipc.Database.ApprovalTopicExecutor.DeleteApprovalTopicExecutorDB(ctx, &req)
if err != nil {
return nil, err
}
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ snapshot := map[string]interface{}{
+ "step_order": utilscore.DerefInt(existing.StepOrder),
+ "require_file": utilscore.DerefBool(existing.RequireFile),
+ }
+ if existing.TopicID != nil {
+ snapshot["topic_id"] = *existing.TopicID
+ }
+ if existing.UserID != nil {
+ snapshot["user_id"] = *existing.UserID
+ }
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "delete", "topic_executor", req.ID,
+ fmt.Sprintf("Снят исполнитель «%s» с темы «%s»", userLabel(existing.User), topicLabel(existing.Topic)),
+ map[string]interface{}{"snapshot": snapshot},
+ )
+ }
+
return true, nil
}
@@ -390,7 +557,6 @@ func (s *TopicExecutorsReg) enrichExecutor(ctx context.Context, exec *typescore.
return
}
- // Подгружаем тему
if exec.TopicID != nil {
topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *exec.TopicID)
if err == nil && topic != nil {
@@ -398,7 +564,6 @@ func (s *TopicExecutorsReg) enrichExecutor(ctx context.Context, exec *typescore.
}
}
- // Подгружаем пользователя
if exec.UserID != nil {
user, err := s.ipc.Database.User.GetUserByIDDB(ctx, *exec.UserID)
if err == nil && user != nil {
@@ -406,3 +571,33 @@ func (s *TopicExecutorsReg) enrichExecutor(ctx context.Context, exec *typescore.
}
}
}
+
+func topicLabel(topic *typescore.ApprovalTopic) string {
+ if topic == nil || topic.Name == nil {
+ return "—"
+ }
+ return *topic.Name
+}
+
+func userLabel(user *typescore.User) string {
+ if user == nil || user.FullName == nil {
+ return "—"
+ }
+ return *user.FullName
+}
+
+func (s *TopicExecutorsReg) getCurrentAdmin(ctx context.Context) (*typescore.Admin, bool) {
+ currentUserID, err := handlers.GetIDFromContext(ctx)
+ if err != nil {
+ return nil, false
+ }
+
+ admins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{
+ Filtering: &typescore.Admin{ID: ¤tUserID},
+ })
+ if err != nil || len(admins) == 0 || admins[0] == nil || admins[0].ID == nil || admins[0].Login == nil {
+ return nil, false
+ }
+
+ return admins[0], true
+}
diff --git a/service/rest_admin_service/handlers/topics/handlers.go b/service/rest_admin_service/handlers/topics/handlers.go
index df575a5..70672ac 100644
--- a/service/rest_admin_service/handlers/topics/handlers.go
+++ b/service/rest_admin_service/handlers/topics/handlers.go
@@ -3,12 +3,17 @@ package topicshandler
import (
"bitrix_balancer_api/core/typescore"
"bitrix_balancer_api/core/utilscore"
+ "bitrix_balancer_api/rest_admin_service/handlers"
+ adminloghandler "bitrix_balancer_api/rest_admin_service/handlers/admin_actions"
+ "context"
"encoding/json"
"errors"
+ "fmt"
"github.com/sirupsen/logrus"
"io"
"net/http"
"strconv"
+ "strings"
"github.com/go-chi/chi/v5"
)
@@ -49,12 +54,30 @@ func (s *TopicsReg) GetTopicsListHandler(w http.ResponseWriter, r *http.Request)
return nil, errW
}
- // Подгружаем информацию о категории для каждой темы
+ categoryIDsSet := make(map[uint64]struct{})
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
+ categoryIDsSet[*topic.CategoryID] = struct{}{}
+ }
+ }
+ categoryIDs := make([]uint64, 0, len(categoryIDsSet))
+ for id := range categoryIDsSet {
+ categoryIDs = append(categoryIDs, id)
+ }
+
+ categoriesMap := make(map[uint64]*typescore.ApprovalTopicCategory)
+ if categories, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoriesByIDsDB(ctx, categoryIDs); err == nil {
+ for _, c := range categories {
+ if c.ID != nil {
+ categoriesMap[*c.ID] = c
+ }
+ }
+ }
+
+ for _, topic := range topicsDbLst {
+ if topic.CategoryID != nil {
+ if cat, ok := categoriesMap[*topic.CategoryID]; ok {
+ topic.Category = cat
}
}
}
@@ -98,7 +121,6 @@ func (s *TopicsReg) GetTopicByIDHandler(w http.ResponseWriter, r *http.Request)
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 {
@@ -134,7 +156,6 @@ func (s *TopicsReg) CreateTopicHandler(w http.ResponseWriter, r *http.Request) (
return nil, errors.New("invalid request body")
}
- // Валидация обязательных полей
if req.Name == nil || *req.Name == "" {
return nil, errors.New("topic name is required")
}
@@ -145,7 +166,6 @@ func (s *TopicsReg) CreateTopicHandler(w http.ResponseWriter, r *http.Request) (
return nil, errors.New("category_id is required")
}
- // Проверяем, что категория существует
ctx := r.Context()
category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *req.CategoryID)
if err != nil {
@@ -155,7 +175,6 @@ func (s *TopicsReg) CreateTopicHandler(w http.ResponseWriter, r *http.Request) (
return nil, errors.New("category not found")
}
- // Проверяем, что код уникален
existingTopics, _, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.ApprovalTopic{Code: req.Code},
})
@@ -166,7 +185,6 @@ func (s *TopicsReg) CreateTopicHandler(w http.ResponseWriter, r *http.Request) (
return nil, errors.New("topic code already exists")
}
- // Устанавливаем значения по умолчанию
if req.IsActive == nil {
isActive := true
req.IsActive = &isActive
@@ -205,7 +223,6 @@ func (s *TopicsReg) CreateTopicHandler(w http.ResponseWriter, r *http.Request) (
return nil, err
}
- // Подгружаем информацию о категории
if createdTopic.CategoryID != nil {
category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *createdTopic.CategoryID)
if err == nil && category != nil {
@@ -213,6 +230,29 @@ func (s *TopicsReg) CreateTopicHandler(w http.ResponseWriter, r *http.Request) (
}
}
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ snapshot := map[string]interface{}{
+ "name": utilscore.DerefStr(createdTopic.Name),
+ "code": utilscore.DerefStr(createdTopic.Code),
+ "category_id": *req.CategoryID,
+ "approval_mode": utilscore.DerefStr(createdTopic.ApprovalMode),
+ "allows_file": utilscore.DerefBool(createdTopic.AllowsFile),
+ "requires_file": utilscore.DerefBool(createdTopic.RequiresFile),
+ "allow_approver_selection": utilscore.DerefBool(createdTopic.AllowApproverSelection),
+ "allow_observer_selection": utilscore.DerefBool(createdTopic.AllowObserverSelection),
+ "require_observer_selection": utilscore.DerefBool(createdTopic.RequireObserverSelection),
+ "require_approver_comment": utilscore.DerefBool(createdTopic.RequireApproverComment),
+ "is_active": utilscore.DerefBool(createdTopic.IsActive),
+ }
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "create", "topic", createdTopic.ID,
+ fmt.Sprintf("Создана тема «%s» (%s)", utilscore.DerefStr(createdTopic.Name), categoryLabel(createdTopic.Category)),
+ map[string]interface{}{"snapshot": snapshot},
+ )
+ }
+
return createdTopic, nil
}
@@ -246,7 +286,6 @@ func (s *TopicsReg) UpdateTopicHandler(w http.ResponseWriter, r *http.Request) (
return nil, errors.New("topic id is required")
}
- // Проверяем, что тема существует
ctx := r.Context()
existingTopic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *req.ID)
if err != nil {
@@ -256,7 +295,6 @@ func (s *TopicsReg) UpdateTopicHandler(w http.ResponseWriter, r *http.Request) (
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)
@@ -269,7 +307,6 @@ func (s *TopicsReg) UpdateTopicHandler(w http.ResponseWriter, r *http.Request) (
}
}
- // Если обновляется код, проверяем уникальность
if req.Code != nil && *req.Code != "" {
if existingTopic.Code == nil || *existingTopic.Code != *req.Code {
existingTopics, _, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{
@@ -284,12 +321,75 @@ func (s *TopicsReg) UpdateTopicHandler(w http.ResponseWriter, r *http.Request) (
}
}
+ type fieldChange struct {
+ Field string `json:"field"`
+ Old interface{} `json:"old"`
+ New interface{} `json:"new"`
+ }
+ var changes []fieldChange
+ var summary []string
+
+ strFields := []struct {
+ name string
+ old *string
+ new *string
+ label string
+ }{
+ {"name", existingTopic.Name, req.Name, "название"},
+ {"code", existingTopic.Code, req.Code, "код"},
+ {"approval_mode", existingTopic.ApprovalMode, req.ApprovalMode, "режим согласования"},
+ {"duration_type", existingTopic.DurationType, req.DurationType, "тип длительности"},
+ {"time_type", existingTopic.TimeType, req.TimeType, "тип времени"},
+ {"payment_type", existingTopic.PaymentType, req.PaymentType, "тип оплаты"},
+ {"first_approver_role_code", existingTopic.FirstApproverRoleCode, req.FirstApproverRoleCode, "роль первого согласующего"},
+ }
+ for _, f := range strFields {
+ if f.new != nil && !utilscore.StrEq(f.old, f.new) {
+ changes = append(changes, fieldChange{f.name, utilscore.DerefStr(f.old), *f.new})
+ summary = append(summary, fmt.Sprintf("%s: «%s» → «%s»", f.label, utilscore.DerefStr(f.old), *f.new))
+ }
+ }
+
+ boolFields := []struct {
+ name string
+ old *bool
+ new *bool
+ label string
+ }{
+ {"is_active", existingTopic.IsActive, req.IsActive, "активна"},
+ {"allows_file", existingTopic.AllowsFile, req.AllowsFile, "разрешён файл"},
+ {"requires_file", existingTopic.RequiresFile, req.RequiresFile, "обязателен файл"},
+ {"allow_approver_selection", existingTopic.AllowApproverSelection, req.AllowApproverSelection, "выбор согласующего"},
+ {"allow_observer_selection", existingTopic.AllowObserverSelection, req.AllowObserverSelection, "выбор наблюдателя"},
+ {"require_observer_selection", existingTopic.RequireObserverSelection, req.RequireObserverSelection, "наблюдатель обязателен"},
+ {"require_approver_comment", existingTopic.RequireApproverComment, req.RequireApproverComment, "комментарий обязателен"},
+ {"allow_delegation_selection", existingTopic.AllowDelegationSelection, req.AllowDelegationSelection, "делегирование обязанностей"},
+ }
+ for _, f := range boolFields {
+ if f.new != nil && !utilscore.BoolEq(f.old, f.new) {
+ changes = append(changes, fieldChange{f.name, utilscore.DerefBool(f.old), *f.new})
+ if *f.new {
+ summary = append(summary, fmt.Sprintf("включено «%s»", f.label))
+ } else {
+ summary = append(summary, fmt.Sprintf("выключено «%s»", f.label))
+ }
+ }
+ }
+
+ if req.CategoryID != nil && !utilscore.Uint64Eq(existingTopic.CategoryID, req.CategoryID) {
+ var oldVal interface{}
+ if existingTopic.CategoryID != nil {
+ oldVal = *existingTopic.CategoryID
+ }
+ changes = append(changes, fieldChange{"category_id", oldVal, *req.CategoryID})
+ summary = append(summary, "изменена категория")
+ }
+
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 {
@@ -297,6 +397,19 @@ func (s *TopicsReg) UpdateTopicHandler(w http.ResponseWriter, r *http.Request) (
}
}
+ if len(changes) > 0 {
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ description := fmt.Sprintf("Изменена тема «%s»: %s", utilscore.DerefStr(existingTopic.Name), strings.Join(summary, "; "))
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "update", "topic", req.ID,
+ description,
+ map[string]interface{}{"changes": changes},
+ )
+ }
+ }
+
return updatedTopic, nil
}
@@ -331,7 +444,6 @@ func (s *TopicsReg) DeleteTopicHandler(w http.ResponseWriter, r *http.Request) (
return nil, errors.New("topic id is required")
}
- // Проверяем, что тема существует
ctx := r.Context()
existingTopic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *req.ID)
if err != nil {
@@ -351,10 +463,57 @@ func (s *TopicsReg) DeleteTopicHandler(w http.ResponseWriter, r *http.Request) (
return nil, errors.New("cannot delete topic: it has existing approvals")
}
+ if existingTopic.CategoryID != nil {
+ category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *existingTopic.CategoryID)
+ if err == nil && category != nil {
+ existingTopic.Category = category
+ }
+ }
+
err = s.ipc.Database.ApprovalTopic.DeleteApprovalTopicDB(ctx, &req)
if err != nil {
return nil, err
}
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ snapshot := map[string]interface{}{
+ "name": utilscore.DerefStr(existingTopic.Name),
+ "code": utilscore.DerefStr(existingTopic.Code),
+ }
+ if existingTopic.CategoryID != nil {
+ snapshot["category_id"] = *existingTopic.CategoryID
+ }
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "delete", "topic", req.ID,
+ fmt.Sprintf("Удалена тема «%s» (%s)", utilscore.DerefStr(existingTopic.Name), categoryLabel(existingTopic.Category)),
+ map[string]interface{}{"snapshot": snapshot},
+ )
+ }
+
return true, nil
}
+
+func categoryLabel(category *typescore.ApprovalTopicCategory) string {
+ if category == nil || category.Name == nil {
+ return "—"
+ }
+ return *category.Name
+}
+
+func (s *TopicsReg) getCurrentAdmin(ctx context.Context) (*typescore.Admin, bool) {
+ currentUserID, err := handlers.GetIDFromContext(ctx)
+ if err != nil {
+ return nil, false
+ }
+
+ admins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{
+ Filtering: &typescore.Admin{ID: ¤tUserID},
+ })
+ if err != nil || len(admins) == 0 || admins[0] == nil || admins[0].ID == nil || admins[0].Login == nil {
+ return nil, false
+ }
+
+ return admins[0], true
+}
diff --git a/service/rest_admin_service/handlers/user_hierarchy/handlers.go b/service/rest_admin_service/handlers/user_hierarchy/handlers.go
index 4685006..e01a833 100644
--- a/service/rest_admin_service/handlers/user_hierarchy/handlers.go
+++ b/service/rest_admin_service/handlers/user_hierarchy/handlers.go
@@ -3,12 +3,17 @@ package hierarchieshandler
import (
"bitrix_balancer_api/core/typescore"
"bitrix_balancer_api/core/utilscore"
+ "bitrix_balancer_api/rest_admin_service/handlers"
+ adminloghandler "bitrix_balancer_api/rest_admin_service/handlers/admin_actions"
+ "context"
"encoding/json"
"errors"
+ "fmt"
"github.com/sirupsen/logrus"
"io"
"net/http"
"strconv"
+ "strings"
"github.com/go-chi/chi/v5"
)
@@ -30,6 +35,7 @@ import (
// @Router /api/hierarchies [get]
func (s *HierarchiesReg) GetHierarchiesListHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
queryParams := r.URL.Query()
+ userStatus := queryParams.Get("user_status")
hierarchyParams := &typescore.UserHierarchy{}
offset, limit, likeFields, errW := utilscore.ParseParamsGetRequest(queryParams, hierarchyParams)
@@ -45,7 +51,7 @@ func (s *HierarchiesReg) GetHierarchiesListHandler(w http.ResponseWriter, r *htt
}
ctx := r.Context()
- hierarchiesDbLst, total, errW := s.ipc.Database.UserHierarchy.GetHierarchiesWithRelations(ctx, options)
+ hierarchiesDbLst, total, errW := s.ipc.Database.UserHierarchy.GetHierarchiesWithRelations(ctx, options, userStatus)
if errW != nil {
return nil, errW
}
@@ -120,7 +126,6 @@ func (s *HierarchiesReg) CreateHierarchyHandler(w http.ResponseWriter, r *http.R
return nil, errors.New("invalid request body")
}
- // Валидация обязательных полей
if req.SubordinateID == nil {
return nil, errors.New("subordinate_id is required")
}
@@ -133,7 +138,6 @@ func (s *HierarchiesReg) CreateHierarchyHandler(w http.ResponseWriter, r *http.R
ctx := r.Context()
- // Проверяем существование подчинённого
subordinate, err := s.ipc.Database.User.GetUserByIDDB(ctx, *req.SubordinateID)
if err != nil {
return nil, err
@@ -142,7 +146,6 @@ func (s *HierarchiesReg) CreateHierarchyHandler(w http.ResponseWriter, r *http.R
return nil, errors.New("subordinate user not found")
}
- // Проверяем существование согласующего
approver, err := s.ipc.Database.User.GetUserByIDDB(ctx, *req.ApproverID)
if err != nil {
return nil, err
@@ -151,7 +154,6 @@ func (s *HierarchiesReg) CreateHierarchyHandler(w http.ResponseWriter, r *http.R
return nil, errors.New("approver user not found")
}
- // Проверяем существование отдела
department, err := s.ipc.Database.Department.GetDepartmentByIDDB(ctx, *req.DepartmentID)
if err != nil {
return nil, err
@@ -160,7 +162,6 @@ func (s *HierarchiesReg) CreateHierarchyHandler(w http.ResponseWriter, r *http.R
return nil, errors.New("department not found")
}
- // Если указана категория — проверяем её существование
if req.TopicCategoryID != nil {
category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *req.TopicCategoryID)
if err != nil {
@@ -171,7 +172,6 @@ func (s *HierarchiesReg) CreateHierarchyHandler(w http.ResponseWriter, r *http.R
}
}
- // Если указана тема — проверяем её существование
if req.TopicID != nil {
topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *req.TopicID)
if err != nil {
@@ -181,7 +181,6 @@ func (s *HierarchiesReg) CreateHierarchyHandler(w http.ResponseWriter, r *http.R
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")
@@ -196,6 +195,7 @@ func (s *HierarchiesReg) CreateHierarchyHandler(w http.ResponseWriter, r *http.R
DepartmentID: req.DepartmentID,
TopicID: req.TopicID,
TopicCategoryID: req.TopicCategoryID,
+ TargetSystem: req.TargetSystem,
},
})
if err != nil {
@@ -205,7 +205,6 @@ func (s *HierarchiesReg) CreateHierarchyHandler(w http.ResponseWriter, r *http.R
return nil, errors.New("this hierarchy relation already exists")
}
- // Устанавливаем priority по умолчанию
if req.Priority == nil {
defaultPriority := 1
req.Priority = &defaultPriority
@@ -216,6 +215,28 @@ func (s *HierarchiesReg) CreateHierarchyHandler(w http.ResponseWriter, r *http.R
return nil, err
}
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ snapshot := map[string]interface{}{
+ "subordinate_id": *req.SubordinateID,
+ "approver_id": *req.ApproverID,
+ "department_id": *req.DepartmentID,
+ "priority": *req.Priority,
+ }
+ if req.TopicID != nil {
+ snapshot["topic_id"] = *req.TopicID
+ }
+ if req.TopicCategoryID != nil {
+ snapshot["topic_category_id"] = *req.TopicCategoryID
+ }
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "create", "hierarchy", createdHierarchy.ID,
+ fmt.Sprintf("Создана связь: «%s» → согласующий «%s» (%s)", userLabel(subordinate), userLabel(approver), utilscore.DerefStr(department.Name)),
+ map[string]interface{}{"snapshot": snapshot},
+ )
+ }
+
return createdHierarchy, nil
}
@@ -251,8 +272,7 @@ func (s *HierarchiesReg) UpdateHierarchyHandler(w http.ResponseWriter, r *http.R
ctx := r.Context()
- // Проверяем, что запись существует
- existingHierarchies, _, err := s.ipc.Database.UserHierarchy.GetUserHierarchyListDB(ctx, typescore.ListDbOptions{
+ existingHierarchies, _, err := s.ipc.Database.UserHierarchy.GetHierarchiesWithRelations(ctx, typescore.ListDbOptions{
Filtering: &typescore.UserHierarchy{ID: req.ID},
})
if err != nil {
@@ -263,7 +283,6 @@ func (s *HierarchiesReg) UpdateHierarchyHandler(w http.ResponseWriter, r *http.R
}
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)
@@ -276,7 +295,6 @@ func (s *HierarchiesReg) UpdateHierarchyHandler(w http.ResponseWriter, r *http.R
}
}
- // Если обновляется approver_id — проверяем существование
if req.ApproverID != nil {
if existing.ApproverID == nil || *existing.ApproverID != *req.ApproverID {
approver, err := s.ipc.Database.User.GetUserByIDDB(ctx, *req.ApproverID)
@@ -289,7 +307,6 @@ func (s *HierarchiesReg) UpdateHierarchyHandler(w http.ResponseWriter, r *http.R
}
}
- // Если обновляется department_id — проверяем существование
if req.DepartmentID != nil {
if existing.DepartmentID == nil || *existing.DepartmentID != *req.DepartmentID {
department, err := s.ipc.Database.Department.GetDepartmentByIDDB(ctx, *req.DepartmentID)
@@ -302,7 +319,6 @@ func (s *HierarchiesReg) UpdateHierarchyHandler(w http.ResponseWriter, r *http.R
}
}
- // Если обновляется 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)
@@ -315,7 +331,6 @@ func (s *HierarchiesReg) UpdateHierarchyHandler(w http.ResponseWriter, r *http.R
}
}
- // Если обновляется topic_id — проверяем существование и принадлежность категории
if req.TopicID != nil {
if existing.TopicID == nil || *existing.TopicID != *req.TopicID {
topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *req.TopicID)
@@ -326,7 +341,6 @@ func (s *HierarchiesReg) UpdateHierarchyHandler(w http.ResponseWriter, r *http.R
return nil, errors.New("topic not found")
}
- // Проверяем соответствие категории
categoryIDToCheck := req.TopicCategoryID
if categoryIDToCheck == nil {
categoryIDToCheck = existing.TopicCategoryID
@@ -337,11 +351,81 @@ func (s *HierarchiesReg) UpdateHierarchyHandler(w http.ResponseWriter, r *http.R
}
}
+ type fieldChange struct {
+ Field string `json:"field"`
+ Old interface{} `json:"old"`
+ New interface{} `json:"new"`
+ }
+ var changes []fieldChange
+ var summary []string
+
+ if req.SubordinateID != nil && !utilscore.Uint64Eq(existing.SubordinateID, req.SubordinateID) {
+ var oldVal interface{}
+ if existing.SubordinateID != nil {
+ oldVal = *existing.SubordinateID
+ }
+ changes = append(changes, fieldChange{"subordinate_id", oldVal, *req.SubordinateID})
+ summary = append(summary, "изменён подчинённый")
+ }
+ if req.ApproverID != nil && !utilscore.Uint64Eq(existing.ApproverID, req.ApproverID) {
+ var oldVal interface{}
+ if existing.ApproverID != nil {
+ oldVal = *existing.ApproverID
+ }
+ changes = append(changes, fieldChange{"approver_id", oldVal, *req.ApproverID})
+ summary = append(summary, "изменён согласующий")
+ }
+ if req.DepartmentID != nil && !utilscore.Uint64Eq(existing.DepartmentID, req.DepartmentID) {
+ var oldVal interface{}
+ if existing.DepartmentID != nil {
+ oldVal = *existing.DepartmentID
+ }
+ changes = append(changes, fieldChange{"department_id", oldVal, *req.DepartmentID})
+ summary = append(summary, "изменён отдел")
+ }
+ if req.TopicID != nil && !utilscore.Uint64Eq(existing.TopicID, req.TopicID) {
+ var oldVal interface{}
+ if existing.TopicID != nil {
+ oldVal = *existing.TopicID
+ }
+ changes = append(changes, fieldChange{"topic_id", oldVal, *req.TopicID})
+ summary = append(summary, "изменена тема")
+ }
+ if req.TopicCategoryID != nil && !utilscore.Uint64Eq(existing.TopicCategoryID, req.TopicCategoryID) {
+ var oldVal interface{}
+ if existing.TopicCategoryID != nil {
+ oldVal = *existing.TopicCategoryID
+ }
+ changes = append(changes, fieldChange{"topic_category_id", oldVal, *req.TopicCategoryID})
+ summary = append(summary, "изменена категория")
+ }
+ if req.Priority != nil && !utilscore.IntEq(existing.Priority, req.Priority) {
+ var oldVal interface{}
+ if existing.Priority != nil {
+ oldVal = *existing.Priority
+ }
+ changes = append(changes, fieldChange{"priority", oldVal, *req.Priority})
+ summary = append(summary, fmt.Sprintf("приоритет: %v → %d", oldVal, *req.Priority))
+ }
+
updatedHierarchy, _, err := s.ipc.Database.UserHierarchy.UpdateUserHierarchyDB(ctx, nil, &req, true)
if err != nil {
return nil, err
}
+ if len(changes) > 0 {
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ description := fmt.Sprintf("Изменена связь «%s» → «%s»: %s", userLabel(existing.Subordinate), userLabel(existing.Approver), strings.Join(summary, "; "))
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "update", "hierarchy", req.ID,
+ description,
+ map[string]interface{}{"changes": changes},
+ )
+ }
+ }
+
return updatedHierarchy, nil
}
@@ -376,10 +460,73 @@ func (s *HierarchiesReg) DeleteHierarchyHandler(w http.ResponseWriter, r *http.R
}
ctx := r.Context()
+
+ existingHierarchies, _, err := s.ipc.Database.UserHierarchy.GetHierarchiesWithRelations(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]
+
err = s.ipc.Database.UserHierarchy.DeleteUserHierarchyDB(ctx, &req)
if err != nil {
return nil, err
}
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ snapshot := map[string]interface{}{
+ "priority": utilscore.DerefInt(existing.Priority),
+ }
+ if existing.SubordinateID != nil {
+ snapshot["subordinate_id"] = *existing.SubordinateID
+ }
+ if existing.ApproverID != nil {
+ snapshot["approver_id"] = *existing.ApproverID
+ }
+ if existing.DepartmentID != nil {
+ snapshot["department_id"] = *existing.DepartmentID
+ }
+ if existing.TopicID != nil {
+ snapshot["topic_id"] = *existing.TopicID
+ }
+ if existing.TopicCategoryID != nil {
+ snapshot["topic_category_id"] = *existing.TopicCategoryID
+ }
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "delete", "hierarchy", req.ID,
+ fmt.Sprintf("Удалена связь: «%s» → согласующий «%s»", userLabel(existing.Subordinate), userLabel(existing.Approver)),
+ map[string]interface{}{"snapshot": snapshot},
+ )
+ }
+
return true, nil
}
+
+func userLabel(user *typescore.User) string {
+ if user == nil || user.FullName == nil {
+ return "—"
+ }
+ return *user.FullName
+}
+
+func (s *HierarchiesReg) getCurrentAdmin(ctx context.Context) (*typescore.Admin, bool) {
+ currentUserID, err := handlers.GetIDFromContext(ctx)
+ if err != nil {
+ return nil, false
+ }
+
+ admins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{
+ Filtering: &typescore.Admin{ID: ¤tUserID},
+ })
+ if err != nil || len(admins) == 0 || admins[0] == nil || admins[0].ID == nil || admins[0].Login == nil {
+ return nil, false
+ }
+
+ return admins[0], true
+}
diff --git a/service/rest_admin_service/handlers/user_roles/handlers.go b/service/rest_admin_service/handlers/user_roles/handlers.go
index 821341c..070ddd3 100644
--- a/service/rest_admin_service/handlers/user_roles/handlers.go
+++ b/service/rest_admin_service/handlers/user_roles/handlers.go
@@ -3,12 +3,17 @@ package userroleshandler
import (
"bitrix_balancer_api/core/typescore"
"bitrix_balancer_api/core/utilscore"
+ "bitrix_balancer_api/rest_admin_service/handlers"
+ adminloghandler "bitrix_balancer_api/rest_admin_service/handlers/admin_actions"
+ "context"
"encoding/json"
"errors"
+ "fmt"
"github.com/sirupsen/logrus"
"io"
"net/http"
"strconv"
+ "strings"
"github.com/go-chi/chi/v5"
)
@@ -45,7 +50,6 @@ func (s *UserRolesReg) GetUserRolesListHandler(w http.ResponseWriter, r *http.Re
return nil, errW
}
- // user_id обязателен для этого эндпоинта
if roleParams.UserID == nil {
return nil, errors.New("user_id is required")
}
@@ -63,15 +67,7 @@ func (s *UserRolesReg) GetUserRolesListHandler(w http.ResponseWriter, r *http.Re
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
- }
- }
- }
+ s.enrichUserRolesBatch(ctx, userRolesDbLst)
return &typescore.ApiResponseBase{
TotalCount: total,
@@ -104,7 +100,6 @@ func (s *UserRolesReg) GetUserRolesByUserIDHandler(w http.ResponseWriter, r *htt
ctx := r.Context()
- // Проверяем, что пользователь существует
user, err := s.ipc.Database.User.GetUserByIDDB(ctx, userID)
if err != nil {
return nil, err
@@ -120,15 +115,7 @@ func (s *UserRolesReg) GetUserRolesByUserIDHandler(w http.ResponseWriter, r *htt
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
- }
- }
- }
+ s.enrichUserRolesBatch(ctx, userRolesDbLst)
return &typescore.ApiResponseBase{
TotalCount: uint64(len(userRolesDbLst)),
@@ -136,6 +123,154 @@ func (s *UserRolesReg) GetUserRolesByUserIDHandler(w http.ResponseWriter, r *htt
}, nil
}
+// enrichUserRolesBatch пакетно подгружает роли для списка user_role
+func (s *UserRolesReg) enrichUserRolesBatch(ctx context.Context, userRoles []*typescore.UserRole) {
+ if len(userRoles) == 0 {
+ return
+ }
+
+ roleIDsSet := make(map[uint64]struct{})
+ for _, ur := range userRoles {
+ if ur.RoleID != nil {
+ roleIDsSet[*ur.RoleID] = struct{}{}
+ }
+ }
+
+ roleIDs := make([]uint64, 0, len(roleIDsSet))
+ for id := range roleIDsSet {
+ roleIDs = append(roleIDs, id)
+ }
+
+ rolesMap := make(map[uint64]*typescore.Role)
+ if roles, err := s.ipc.Database.Role.GetRolesByIDsDB(ctx, roleIDs); err == nil {
+ for _, role := range roles {
+ if role.ID != nil {
+ rolesMap[*role.ID] = role
+ }
+ }
+ }
+
+ for _, ur := range userRoles {
+ if ur.RoleID != nil {
+ if role, ok := rolesMap[*ur.RoleID]; ok {
+ ur.Role = role
+ }
+ }
+ }
+}
+
+// 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 := r.Context()
+
+ 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")
+ }
+
+ roleIDsSet := make(map[uint64]struct{})
+ roleIDs := make([]uint64, 0, len(req.RoleIDs))
+ for _, roleID := range req.RoleIDs {
+ if roleID == nil {
+ continue
+ }
+ if _, exists := roleIDsSet[*roleID]; exists {
+ continue
+ }
+ roleIDsSet[*roleID] = struct{}{}
+ roleIDs = append(roleIDs, *roleID)
+ }
+
+ if len(roleIDs) > 0 {
+ existingRoles, err := s.ipc.Database.Role.GetRolesByIDsDB(ctx, roleIDs)
+ if err != nil {
+ return nil, err
+ }
+ foundIDs := make(map[uint64]struct{}, len(existingRoles))
+ for _, role := range existingRoles {
+ if role.ID != nil {
+ foundIDs[*role.ID] = struct{}{}
+ }
+ }
+ for _, roleID := range roleIDs {
+ if _, ok := foundIDs[roleID]; !ok {
+ return nil, errors.New("role not found: " + strconv.FormatUint(roleID, 10))
+ }
+ }
+ }
+
+ // снимаем "было" до удаления — иначе после DeleteUserRolesByUserIDDB это уже не достать
+ previousRoles, _, _ := s.ipc.Database.UserRole.GetUserRolesListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.UserRole{UserID: req.UserID},
+ })
+ s.enrichUserRolesBatch(ctx, previousRoles)
+
+ if err := s.ipc.Database.UserRole.DeleteUserRolesByUserIDDB(ctx, *req.UserID); err != nil {
+ logrus.Errorf("BulkAssignRolesHandler: failed to delete user_roles for user_id=%d: %v", *req.UserID, err)
+ return nil, err
+ }
+
+ createdRoles, err := s.ipc.Database.UserRole.CreateUserRolesBulkDB(ctx, nil, *req.UserID, roleIDs)
+ if err != nil {
+ logrus.Errorf("BulkAssignRolesHandler: failed to bulk create user_roles: %v", err)
+ return nil, err
+ }
+
+ s.enrichUserRolesBatch(ctx, createdRoles)
+
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ oldNames := roleNames(previousRoles)
+ newNames := roleNames(createdRoles)
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "update", "user_roles", req.UserID,
+ fmt.Sprintf("Заменены роли «%s»: [%s] → [%s]", userLabel(user), strings.Join(oldNames, ", "), strings.Join(newNames, ", ")),
+ map[string]interface{}{
+ "user_id": *req.UserID,
+ "roles_before": oldNames,
+ "roles_after": newNames,
+ },
+ )
+ }
+
+ return &typescore.ApiResponseBase{
+ TotalCount: uint64(len(createdRoles)),
+ Data: createdRoles,
+ }, nil
+}
+
// AssignUserRoleHandler Назначение роли пользователю
// @Summary Назначение роли пользователю
// @Description Назначение роли пользователю (создание связи user_id + role_id)
@@ -172,7 +307,6 @@ func (s *UserRolesReg) AssignUserRoleHandler(w http.ResponseWriter, r *http.Requ
ctx := r.Context()
- // Проверяем, что пользователь существует
user, err := s.ipc.Database.User.GetUserByIDDB(ctx, *req.UserID)
if err != nil {
return nil, err
@@ -181,7 +315,6 @@ func (s *UserRolesReg) AssignUserRoleHandler(w http.ResponseWriter, r *http.Requ
return nil, errors.New("user not found")
}
- // Проверяем, что роль существует
role, err := s.ipc.Database.Role.GetRoleByIDDB(ctx, *req.RoleID)
if err != nil {
return nil, err
@@ -190,7 +323,6 @@ func (s *UserRolesReg) AssignUserRoleHandler(w http.ResponseWriter, r *http.Requ
return nil, errors.New("role not found")
}
- // 🛡 Проверяем, что такая связь ещё не существует
existingRoles, _, err := s.ipc.Database.UserRole.GetUserRolesListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.UserRole{
UserID: req.UserID,
@@ -214,117 +346,24 @@ func (s *UserRolesReg) AssignUserRoleHandler(w http.ResponseWriter, r *http.Requ
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
- }
+ createdUserRole.Role = role
+
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "create", "user_role", createdUserRole.ID,
+ fmt.Sprintf("Назначена роль «%s» пользователю «%s»", roleLabel(role), userLabel(user)),
+ map[string]interface{}{
+ "user_id": *req.UserID,
+ "role_id": *req.RoleID,
+ },
+ )
}
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 := r.Context()
-
- // Проверяем, что пользователь существует
- 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 записи
@@ -357,7 +396,6 @@ func (s *UserRolesReg) RemoveUserRoleHandler(w http.ResponseWriter, r *http.Requ
ctx := r.Context()
- // Проверяем, что запись существует
existingRoles, _, err := s.ipc.Database.UserRole.GetUserRolesListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.UserRole{ID: req.ID},
})
@@ -367,11 +405,73 @@ func (s *UserRolesReg) RemoveUserRoleHandler(w http.ResponseWriter, r *http.Requ
if len(existingRoles) == 0 {
return nil, errors.New("user_role not found")
}
+ existing := existingRoles[0]
+ s.enrichUserRolesBatch(ctx, existingRoles)
+
+ var user *typescore.User
+ if existing.UserID != nil {
+ user, _ = s.ipc.Database.User.GetUserByIDDB(ctx, *existing.UserID)
+ }
err = s.ipc.Database.UserRole.DeleteUserRoleDB(ctx, &req)
if err != nil {
return nil, err
}
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ snapshot := map[string]interface{}{}
+ if existing.UserID != nil {
+ snapshot["user_id"] = *existing.UserID
+ }
+ if existing.RoleID != nil {
+ snapshot["role_id"] = *existing.RoleID
+ }
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "delete", "user_role", req.ID,
+ fmt.Sprintf("Снята роль «%s» с пользователя «%s»", roleLabel(existing.Role), userLabel(user)),
+ map[string]interface{}{"snapshot": snapshot},
+ )
+ }
+
return true, nil
}
+
+func userLabel(user *typescore.User) string {
+ if user == nil || user.FullName == nil {
+ return "—"
+ }
+ return *user.FullName
+}
+
+func roleLabel(role *typescore.Role) string {
+ if role == nil || role.Name == nil {
+ return "—"
+ }
+ return *role.Name
+}
+
+func roleNames(userRoles []*typescore.UserRole) []string {
+ names := make([]string, 0, len(userRoles))
+ for _, ur := range userRoles {
+ names = append(names, roleLabel(ur.Role))
+ }
+ return names
+}
+
+func (s *UserRolesReg) getCurrentAdmin(ctx context.Context) (*typescore.Admin, bool) {
+ currentUserID, err := handlers.GetIDFromContext(ctx)
+ if err != nil {
+ return nil, false
+ }
+
+ admins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{
+ Filtering: &typescore.Admin{ID: ¤tUserID},
+ })
+ if err != nil || len(admins) == 0 || admins[0] == nil || admins[0].ID == nil || admins[0].Login == nil {
+ return nil, false
+ }
+
+ return admins[0], true
+}
diff --git a/service/rest_admin_service/handlers/users/handlers.go b/service/rest_admin_service/handlers/users/handlers.go
index d628da9..6827975 100644
--- a/service/rest_admin_service/handlers/users/handlers.go
+++ b/service/rest_admin_service/handlers/users/handlers.go
@@ -3,12 +3,17 @@ package usershandler
import (
"bitrix_balancer_api/core/typescore"
"bitrix_balancer_api/core/utilscore"
+ "bitrix_balancer_api/rest_admin_service/handlers"
+ adminloghandler "bitrix_balancer_api/rest_admin_service/handlers/admin_actions"
+ "context"
"encoding/json"
"errors"
+ "fmt"
"github.com/sirupsen/logrus"
"io"
"net/http"
"strconv"
+ "strings"
"github.com/go-chi/chi/v5"
)
@@ -37,6 +42,24 @@ func (s *UserReg) GetUserListHandler(w http.ResponseWriter, r *http.Request) (in
return nil, errW
}
+ search := queryParams.Get("full_name")
+ if search != "" {
+ if likeFields == nil {
+ likeFields = make(map[string]string)
+ }
+ likeFields["full_name"] = search
+ userParams.FullName = nil
+ }
+
+ var roleIDs []uint64
+ if roleIDsStr := queryParams["role_ids[]"]; len(roleIDsStr) > 0 {
+ for _, idStr := range roleIDsStr {
+ if id, err := strconv.ParseUint(idStr, 10, 64); err == nil {
+ roleIDs = append(roleIDs, id)
+ }
+ }
+ }
+
options := typescore.ListDbOptions{
Filtering: userParams,
Offset: offset,
@@ -45,45 +68,223 @@ func (s *UserReg) GetUserListHandler(w http.ResponseWriter, r *http.Request) (in
}
ctx := r.Context()
- userDbLst, total, errW := s.ipc.Database.User.GetUsersListDB(ctx, options)
- if errW != nil {
- return nil, errW
+
+ var userDbLst []*typescore.User
+ var total uint64
+ var err error
+
+ if len(roleIDs) > 0 {
+ userDbLst, total, err = s.ipc.Database.User.GetUsersListByRoleIDsDB(ctx, options, roleIDs)
+ } else {
+ userDbLst, total, err = s.ipc.Database.User.GetUsersListDB(ctx, options)
}
- // 🚀 Подгружаем связанные данные для каждого пользователя
- 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
- }
+ if err != nil {
+ return nil, err
}
+ s.enrichUsersBatch(ctx, userDbLst)
+
return &typescore.ApiResponseBase{
TotalCount: total,
Data: userDbLst,
}, 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 := r.Context()
+ 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")
+ }
+
+ 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")
+ }
+ }
+ }
+
+ type fieldChange struct {
+ Field string `json:"field"`
+ Old interface{} `json:"old"`
+ New interface{} `json:"new"`
+ }
+ var changes []fieldChange
+ var summary []string
+
+ if req.DepartmentID != nil && !utilscore.Uint64Eq(existingUser.DepartmentID, req.DepartmentID) {
+ var oldVal interface{}
+ if existingUser.DepartmentID != nil {
+ oldVal = *existingUser.DepartmentID
+ }
+ changes = append(changes, fieldChange{"department_id", oldVal, *req.DepartmentID})
+ summary = append(summary, "изменён отдел")
+ }
+ if req.IsBlocked != nil && !utilscore.BoolEq(existingUser.IsBlocked, req.IsBlocked) {
+ changes = append(changes, fieldChange{"is_blocked", utilscore.DerefBool(existingUser.IsBlocked), *req.IsBlocked})
+ if *req.IsBlocked {
+ summary = append(summary, "заблокирован")
+ } else {
+ summary = append(summary, "разблокирован")
+ }
+ }
+ if req.IsFired != nil && !utilscore.BoolEq(existingUser.IsFired, req.IsFired) {
+ changes = append(changes, fieldChange{"is_fired", utilscore.DerefBool(existingUser.IsFired), *req.IsFired})
+ if *req.IsFired {
+ summary = append(summary, "уволен")
+ } else {
+ summary = append(summary, "восстановлен")
+ }
+ }
+
+ 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
+ }
+
+ s.enrichUsersBatch(ctx, []*typescore.User{upUser})
+
+ if len(changes) > 0 {
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ description := fmt.Sprintf("Изменён пользователь «%s»: %s", userLabel(existingUser), strings.Join(summary, "; "))
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "update", "user", req.ID,
+ description,
+ map[string]interface{}{"changes": changes},
+ )
+ }
+ }
+
+ return upUser, nil
+}
+
+// enrichUsersBatch пакетно подгружает отделы и роли для списка пользователей
+func (s *UserReg) enrichUsersBatch(ctx context.Context, users []*typescore.User) {
+ if len(users) == 0 {
+ return
+ }
+
+ departmentIDsSet := make(map[uint64]struct{})
+ userIDs := make([]uint64, 0, len(users))
+ for _, u := range users {
+ if u.ID != nil {
+ userIDs = append(userIDs, *u.ID)
+ }
+ if u.DepartmentID != nil {
+ departmentIDsSet[*u.DepartmentID] = struct{}{}
+ }
+ }
+
+ departmentIDs := make([]uint64, 0, len(departmentIDsSet))
+ for id := range departmentIDsSet {
+ departmentIDs = append(departmentIDs, id)
+ }
+
+ departmentsMap := make(map[uint64]*typescore.Department)
+ if departments, err := s.ipc.Database.Department.GetDepartmentsByIDsDB(ctx, departmentIDs); err == nil {
+ for _, d := range departments {
+ if d.ID != nil {
+ departmentsMap[*d.ID] = d
+ }
+ }
+ }
+
+ userRoles, err := s.ipc.Database.UserRole.GetUserRolesByUserIDsDB(ctx, userIDs)
+ roleIDsSet := make(map[uint64]struct{})
+ userRolesByUser := make(map[uint64][]*typescore.UserRole)
+ if err == nil {
+ for _, ur := range userRoles {
+ if ur.UserID != nil {
+ userRolesByUser[*ur.UserID] = append(userRolesByUser[*ur.UserID], ur)
+ }
+ if ur.RoleID != nil {
+ roleIDsSet[*ur.RoleID] = struct{}{}
+ }
+ }
+ }
+
+ roleIDs := make([]uint64, 0, len(roleIDsSet))
+ for id := range roleIDsSet {
+ roleIDs = append(roleIDs, id)
+ }
+ rolesMap := make(map[uint64]*typescore.Role)
+ if roles, err := s.ipc.Database.Role.GetRolesByIDsDB(ctx, roleIDs); err == nil {
+ for _, role := range roles {
+ if role.ID != nil {
+ rolesMap[*role.ID] = role
+ }
+ }
+ }
+
+ for _, u := range users {
+ if u.DepartmentID != nil {
+ if d, ok := departmentsMap[*u.DepartmentID]; ok {
+ u.Department = d
+ }
+ }
+ if u.ID == nil {
+ continue
+ }
+ userRolesForUser := userRolesByUser[*u.ID]
+ for _, ur := range userRolesForUser {
+ if ur.RoleID != nil {
+ if role, ok := rolesMap[*ur.RoleID]; ok {
+ ur.Role = role
+ }
+ }
+ }
+ if len(userRolesForUser) > 0 {
+ u.UserRoles = userRolesForUser
+ }
+ }
+}
+
// GetUserByIDHandler Получение пользователя по ID
// @Summary Получение пользователя по ID
// @Description Получение детальной информации о пользователе по его ID с подгрузкой связанных данных
@@ -117,7 +318,6 @@ func (s *UserReg) GetUserByIDHandler(w http.ResponseWriter, r *http.Request) (in
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 {
@@ -125,12 +325,10 @@ func (s *UserReg) GetUserByIDHandler(w http.ResponseWriter, r *http.Request) (in
}
}
- // 🚀 Подгружаем роли пользователя
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)
@@ -145,38 +343,20 @@ func (s *UserReg) GetUserByIDHandler(w http.ResponseWriter, r *http.Request) (in
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 {
+func (s *UserReg) DeleteUserHandler(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 := r.Context()
- existingUser, err := s.ipc.Database.User.GetUserByIDDB(ctx, *req.ID)
+
+ existingUser, err := s.ipc.Database.User.GetUserByIDDB(ctx, id)
if err != nil {
return nil, err
}
@@ -184,53 +364,54 @@ func (s *UserReg) UpdateUserHandler(w http.ResponseWriter, r *http.Request) (int
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")
- }
+ err = s.ipc.Database.User.DeleteUserDB(ctx, &typescore.User{ID: &id})
+ if err != nil {
+ return nil, err
+ }
+
+ if currentAdmin, ok := s.getCurrentAdmin(ctx); ok {
+ snapshot := map[string]interface{}{
+ "full_name": utilscore.DerefStr(existingUser.FullName),
+ "is_blocked": utilscore.DerefBool(existingUser.IsBlocked),
+ "is_fired": utilscore.DerefBool(existingUser.IsFired),
}
- }
-
- 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
+ if existingUser.TelegramID != nil {
+ snapshot["telegram_id"] = *existingUser.TelegramID
}
- }
-
- 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
- }
- }
+ if existingUser.DepartmentID != nil {
+ snapshot["department_id"] = *existingUser.DepartmentID
}
- upUser.UserRoles = userRoles
+ adminloghandler.LogAdminActionWithMetadata(
+ ctx, s.ipc,
+ *currentAdmin.ID, *currentAdmin.Login,
+ "delete", "user", &id,
+ fmt.Sprintf("Удалён пользователь «%s»", userLabel(existingUser)),
+ map[string]interface{}{"snapshot": snapshot},
+ )
}
- return upUser, nil
+ return true, nil
+}
+
+func userLabel(user *typescore.User) string {
+ if user == nil || user.FullName == nil {
+ return "—"
+ }
+ return *user.FullName
+}
+
+func (s *UserReg) getCurrentAdmin(ctx context.Context) (*typescore.Admin, bool) {
+ currentUserID, err := handlers.GetIDFromContext(ctx)
+ if err != nil {
+ return nil, false
+ }
+
+ admins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{
+ Filtering: &typescore.Admin{ID: ¤tUserID},
+ })
+ if err != nil || len(admins) == 0 || admins[0] == nil || admins[0].ID == nil || admins[0].Login == nil {
+ return nil, false
+ }
+
+ return admins[0], true
}
diff --git a/service/rest_admin_service/handlers/users/routes.go b/service/rest_admin_service/handlers/users/routes.go
index 159d165..c09b205 100644
--- a/service/rest_admin_service/handlers/users/routes.go
+++ b/service/rest_admin_service/handlers/users/routes.go
@@ -28,6 +28,8 @@ func RegisterUserRoutes(
handlers.RegisterRoute(r, http.MethodGet, "/", s.GetUserListHandler)
handlers.RegisterRoute(r, http.MethodPut, "/", s.UpdateUserHandler)
+ handlers.RegisterRoute(r, http.MethodDelete, "/{id}", s.DeleteUserHandler)
+
r.Get("/{id}", handlers.WrapHandlerF(handlers.WrapHandlerParams{
HandlerFunc: s.GetUserByIDHandler,
}))
diff --git a/service/rest_admin_service/types/module.go b/service/rest_admin_service/types/module.go
index 41ddded..de68da6 100644
--- a/service/rest_admin_service/types/module.go
+++ b/service/rest_admin_service/types/module.go
@@ -4,6 +4,7 @@ import (
configcore "bitrix_balancer_api/core/config"
database "bitrix_balancer_api/core/db"
"bitrix_balancer_api/core/lib/external/tgkit"
+ "bitrix_balancer_api/core/lib/internally/monthly_orders"
redismodule "bitrix_balancer_api/core/lib/internally/redis"
)
@@ -12,4 +13,5 @@ type InternalProviderControl struct {
RedisClient *redismodule.ModuleRedis
TGBotClient *tgkit.Client
Database *database.ModuleDB
+ MoService *monthly_orders.MonthlyOrderService
}
diff --git a/service/rest_telephony_service/cmd/app.go b/service/rest_telephony_service/cmd/app.go
new file mode 100644
index 0000000..fe12141
--- /dev/null
+++ b/service/rest_telephony_service/cmd/app.go
@@ -0,0 +1,151 @@
+package main
+
+import (
+ configcore "bitrix_balancer_api/core/config"
+ clientcontrollers "bitrix_balancer_api/core/lib/internally/client-controllers"
+ "errors"
+ "fmt"
+ "log"
+ "net/http"
+ "rest_telephony_service/handlers/telephony"
+ typesm "rest_telephony_service/types"
+ "time"
+
+ "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"
+)
+
+const (
+ readTimeout = 15 * time.Minute
+ writeTimeout = 15 * time.Minute
+ idleTimeout = 15 * time.Minute
+ rateLimit = 50
+ rateWindow = 1 * time.Second
+)
+
+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,
+ Server: configcore.ExposedServiceOptions{
+ RESTBaseService: 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,
+ TGBotClient: clientsExternal.Telegram,
+ }, nil
+}
+
+func startRestApiServer(ipc *typesm.InternalProviderControl, router *chi.Mux) error {
+ // Допустим, телефония живет на порту 15002. В будущем вынесем в config.yml
+ serverPort := "15002"
+
+ serverAddr := ":" + serverPort
+ httpServer := &http.Server{
+ Addr: serverAddr,
+ Handler: router,
+ ReadTimeout: readTimeout,
+ WriteTimeout: writeTimeout,
+ IdleTimeout: idleTimeout,
+ }
+
+ log.Printf("✅ Starting Telephony server on %s", serverAddr)
+ return httpServer.ListenAndServe()
+}
+
+func initBaseApiRouter(ipc *typesm.InternalProviderControl) (*chi.Mux, error) {
+ router := chi.NewRouter()
+ corsOptions := cors.New(cors.Options{
+ AllowedOrigins: []string{"*"},
+ AllowedMethods: []string{http.MethodGet, http.MethodPost, http.MethodOptions},
+ AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "ApiKey", "x-device-id"},
+ ExposedHeaders: []string{"Link", "Cache-Control"},
+ AllowCredentials: true,
+ MaxAge: 300,
+ })
+
+ router.Use(corsOptions.Handler)
+ router.Use(middleware.RealIP)
+ router.Use(middleware.Recoverer)
+ 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 {
+ // Подключаем наши маршруты
+ if err := telephonyservice.RegisterTelephonyRoutes(router, ipc); err != nil {
+ return errors.New(fmt.Sprintf("🔴 failed to register telephony routes: %v", err))
+ }
+
+ // Вывод зарегистрированных маршрутов
+ 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
+ })
+ return err
+}
diff --git a/service/rest_telephony_service/go.mod b/service/rest_telephony_service/go.mod
new file mode 100644
index 0000000..733ea24
--- /dev/null
+++ b/service/rest_telephony_service/go.mod
@@ -0,0 +1,57 @@
+module rest_telephony_service
+
+go 1.25.6
+
+require (
+ bitrix_balancer_api/core v0.0.0
+ github.com/go-chi/chi/v5 v5.3.1
+ github.com/go-chi/cors v1.2.2
+ github.com/go-chi/httprate v0.16.0
+ 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/go-telegram-bot-api/telegram-bot-api/v5 v5.5.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/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/zeebo/xxh3 v1.0.2 // indirect
+ go.uber.org/atomic v1.11.0 // indirect
+ golang.org/x/crypto v0.40.0 // indirect
+ golang.org/x/net v0.42.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
+ gopkg.in/yaml.v3 v3.0.1 // indirect
+ gorm.io/driver/postgres v1.6.0 // indirect
+ gorm.io/gorm v1.31.1 // indirect
+)
+
+replace bitrix_balancer_api/core => ../../core
diff --git a/service/rest_telephony_service/go.sum b/service/rest_telephony_service/go.sum
new file mode 100644
index 0000000..ef3db65
--- /dev/null
+++ b/service/rest_telephony_service/go.sum
@@ -0,0 +1,128 @@
+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.1 h1:3j4HZLGZQ3JpMCrPJF/Jl3mYJfWLKBfNJ6quurUGCf8=
+github.com/go-chi/chi/v5 v5.3.1/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.16.0 h1:8V5DH9j6pSK6UQoBsTpvMyFxycqaKEIToyPKzHJjUa8=
+github.com/go-chi/httprate v0.16.0/go.mod h1:A8lo+qRhk+s9LiuP5saS7XCGDXRXMcrueq0NfIuCa/I=
+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.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/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/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/service/rest_telephony_service/handlers/register.go b/service/rest_telephony_service/handlers/register.go
new file mode 100644
index 0000000..53f7495
--- /dev/null
+++ b/service/rest_telephony_service/handlers/register.go
@@ -0,0 +1,161 @@
+package handlers
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "github.com/go-chi/chi/v5"
+ "io"
+ "net/http"
+ "strconv"
+)
+
+// ErrorResponse структура для возврата ошибок
+type ErrorResponse struct {
+ ErrorCode int `json:"error_code"`
+ ErrorDescription string `json:"error_description"`
+}
+
+type ExcelFileResponse struct {
+ Data []byte // Содержимое файла
+ FileName string // Имя файла для скачивания
+}
+
+// WrapHandlerParams структура для параметров обертки
+type WrapHandlerParams struct {
+ HandlerFunc func(http.ResponseWriter, *http.Request) (interface{}, error)
+}
+
+// responseWriterWrapper предотвращает повторный вызов WriteHeader
+type responseWriterWrapper struct {
+ http.ResponseWriter
+ wroteHeader bool
+}
+
+func (rw *responseWriterWrapper) WriteHeader(statusCode int) {
+ if !rw.wroteHeader {
+ rw.ResponseWriter.WriteHeader(statusCode)
+ rw.wroteHeader = true
+ }
+}
+
+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)
+
+ // 🆕 Проверяем, не файл ли это
+ if fileResp, ok := payload.(*ExcelFileResponse); ok && err == nil {
+ serveExcelFile(rw, fileResp)
+ return
+ }
+
+ // Обычный JSON ответ
+ respondWithJSON(rw, err, payload)
+ }
+}
+
+// 🆕 serveExcelFile отправляет файл как бинарный ответ
+func serveExcelFile(w http.ResponseWriter, fileResp *ExcelFileResponse) {
+ // Устанавливаем заголовки ДО отправки тела
+ w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
+ w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileResp.FileName))
+ w.Header().Set("Content-Length", strconv.Itoa(len(fileResp.Data)))
+ w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
+
+ w.WriteHeader(http.StatusOK)
+
+ // Отправляем содержимое файла
+ if _, err := w.Write(fileResp.Data); err != nil {
+ // Логируем ошибку, но заголовки уже отправлены
+ // Можно добавить логгер здесь
+ _ = err
+ }
+}
+
+// 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
+ }
+ }
+
+ if rw, ok := w.(*responseWriterWrapper); ok {
+ if !rw.wroteHeader {
+ rw.WriteHeader(status)
+ }
+ } else {
+ w.WriteHeader(status)
+ }
+
+ _, _ = w.Write(response)
+}
diff --git a/service/rest_telephony_service/handlers/telephony/bitrix.go b/service/rest_telephony_service/handlers/telephony/bitrix.go
new file mode 100644
index 0000000..6b77faf
--- /dev/null
+++ b/service/rest_telephony_service/handlers/telephony/bitrix.go
@@ -0,0 +1,337 @@
+package telephonyservice
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "path"
+ "strconv"
+ "strings"
+ "time"
+)
+
+// URL входящего вебхука Битрикс24 (можно переопределить переменной BITRIX_WEBHOOK_URL).
+const bitrixWebhookURL = "https://thebest.bitrix24.ru/rest/292/paz20o3316e6cfe7/"
+
+// Максимальный размер записи, которую прикладываем файлом (в base64 станет ~на треть больше).
+const maxRecordingBytes = 20 << 20
+
+var errContactNotFound = errors.New("contact not found in Bitrix24")
+var errRecordingTooBig = errors.New("recording is too big to attach")
+
+// bxError — ошибка, которую вернул сам Битрикс24 (поле "error" в ответе).
+type bxError struct {
+ Code string
+ Desc string
+ HTTP int
+}
+
+func (e *bxError) Error() string {
+ return fmt.Sprintf("bitrix error %s: %s (http %d)", e.Code, e.Desc, e.HTTP)
+}
+
+// isPermanent — повторять запрос бессмысленно.
+func isPermanent(err error) bool {
+ if errors.Is(err, errContactNotFound) {
+ return true
+ }
+ var be *bxError
+ if errors.As(err, &be) {
+ switch be.Code {
+ case "OWNER_NOT_FOUND", "INVALID_ARG_VALUE", "100":
+ return true
+ }
+ }
+ return false
+}
+
+// BitrixClient — клиент входящего вебхука Битрикс24.
+type BitrixClient struct {
+ baseURL string
+ http *http.Client
+ dl *http.Client // скачивание записей
+}
+
+func NewBitrixClient(webhookURL string) *BitrixClient {
+ webhookURL = strings.TrimSpace(webhookURL)
+ if !strings.HasSuffix(webhookURL, "/") {
+ webhookURL += "/"
+ }
+ return &BitrixClient{
+ baseURL: webhookURL,
+ http: &http.Client{Timeout: 60 * time.Second},
+ dl: &http.Client{Timeout: 90 * time.Second},
+ }
+}
+
+type bxResponse struct {
+ Result json.RawMessage `json:"result"`
+ Error string `json:"error"`
+ ErrorDescription string `json:"error_description"`
+}
+
+func (c *BitrixClient) call(ctx context.Context, method string, params interface{}) (json.RawMessage, error) {
+ body, err := json.Marshal(params)
+ if err != nil {
+ return nil, err
+ }
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+method+".json", bytes.NewReader(body))
+ if err != nil {
+ return nil, errors.New("bitrix: bad request")
+ }
+ req.Header.Set("Content-Type", "application/json")
+
+ resp, err := c.http.Do(req)
+ if err != nil {
+ // url.Error содержит полный URL с секретом вебхука — не пропускаем его в логи.
+ var ue *url.Error
+ if errors.As(err, &ue) {
+ return nil, fmt.Errorf("bitrix %s: %w", method, ue.Err)
+ }
+ return nil, fmt.Errorf("bitrix %s: request failed", method)
+ }
+ defer resp.Body.Close()
+
+ raw, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
+ if err != nil {
+ return nil, fmt.Errorf("bitrix %s: read body: %w", method, err)
+ }
+
+ var r bxResponse
+ jsonErr := json.Unmarshal(raw, &r)
+ if r.Error != "" {
+ return nil, &bxError{Code: r.Error, Desc: r.ErrorDescription, HTTP: resp.StatusCode}
+ }
+ if resp.StatusCode != http.StatusOK {
+ return nil, fmt.Errorf("bitrix %s: http %d", method, resp.StatusCode)
+ }
+ if jsonErr != nil {
+ return nil, fmt.Errorf("bitrix %s: bad json: %w", method, jsonErr)
+ }
+ return r.Result, nil
+}
+
+// FindContact ищет контакт по номеру. Возвращает ID первого найденного.
+func (c *BitrixClient) FindContact(ctx context.Context, number string) (int, error) {
+ variants := phoneVariants(number)
+ if len(variants) == 0 {
+ return 0, errContactNotFound
+ }
+
+ // 1) crm.duplicate.findbycomm — ищет по телефону с учётом нормализации Битрикса.
+ raw, err := c.call(ctx, "crm.duplicate.findbycomm", map[string]interface{}{
+ "type": "PHONE",
+ "values": variants,
+ "entity_type": "CONTACT",
+ })
+ if err == nil {
+ // При пустом результате Битрикс возвращает [] вместо объекта — это не ошибка.
+ var m map[string][]FlexInt
+ if json.Unmarshal(raw, &m) == nil && len(m["CONTACT"]) > 0 {
+ return int(m["CONTACT"][0]), nil
+ }
+ } else {
+ var be *bxError
+ if !errors.As(err, &be) {
+ return 0, err // сеть/5xx — пусть вызывающий повторит
+ }
+ }
+
+ // 2) Запасной вариант: точное совпадение по каждому формату номера.
+ for _, v := range variants {
+ raw, err := c.call(ctx, "crm.contact.list", map[string]interface{}{
+ "filter": map[string]string{"PHONE": v},
+ "select": []string{"ID"},
+ "order": map[string]string{"ID": "ASC"},
+ })
+ if err != nil {
+ return 0, err
+ }
+ var list []struct {
+ ID FlexInt `json:"ID"`
+ }
+ if json.Unmarshal(raw, &list) == nil && len(list) > 0 {
+ return int(list[0].ID), nil
+ }
+ }
+ return 0, errContactNotFound
+}
+
+// AddComment добавляет комментарий в таймлайн контакта.
+// Если fileB64 не пуст, файл прикладывается к комментарию (FILES).
+func (c *BitrixClient) AddComment(ctx context.Context, contactID int, text, fileName, fileB64 string) error {
+ fields := map[string]interface{}{
+ "ENTITY_ID": contactID,
+ "ENTITY_TYPE": "contact",
+ "COMMENT": text,
+ }
+ if fileB64 != "" {
+ fields["FILES"] = [][]string{{fileName, fileB64}}
+ }
+ raw, err := c.call(ctx, "crm.timeline.comment.add", map[string]interface{}{"fields": fields})
+ if err != nil {
+ return err
+ }
+ id, convErr := strconv.Atoi(strings.TrimSpace(string(raw)))
+ if convErr != nil || id <= 0 {
+ return fmt.Errorf("bitrix crm.timeline.comment.add: unexpected result %q", string(raw))
+ }
+ return nil
+}
+
+// DownloadRecording скачивает запись разговора. Возвращает содержимое и имя файла с расширением.
+func (c *BitrixClient) DownloadRecording(ctx context.Context, recURL, baseName string) ([]byte, string, error) {
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, recURL, nil)
+ if err != nil {
+ return nil, "", errors.New("recording: bad url")
+ }
+ resp, err := c.dl.Do(req)
+ if err != nil {
+ // url.Error содержит адрес записи (возможно, с токеном) — не пускаем его в логи.
+ var ue *url.Error
+ if errors.As(err, &ue) {
+ return nil, "", fmt.Errorf("recording download: %w", ue.Err)
+ }
+ return nil, "", errors.New("recording download failed")
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK {
+ return nil, "", fmt.Errorf("recording download: http %d", resp.StatusCode)
+ }
+ if resp.ContentLength > maxRecordingBytes {
+ return nil, "", errRecordingTooBig
+ }
+ data, err := io.ReadAll(io.LimitReader(resp.Body, maxRecordingBytes+1))
+ if err != nil {
+ return nil, "", fmt.Errorf("recording download: %w", err)
+ }
+ if len(data) > maxRecordingBytes {
+ return nil, "", errRecordingTooBig
+ }
+ if len(data) == 0 {
+ return nil, "", errors.New("recording download: empty body")
+ }
+ return data, baseName + recordingExt(resp.Header.Get("Content-Type"), resp.Request.URL.Path), nil
+}
+
+func recordingExt(contentType, urlPath string) string {
+ ct := strings.ToLower(strings.TrimSpace(strings.SplitN(contentType, ";", 2)[0]))
+ switch ct {
+ case "audio/mpeg", "audio/mp3":
+ return ".mp3"
+ case "audio/wav", "audio/x-wav", "audio/wave":
+ return ".wav"
+ case "audio/mp4", "audio/x-m4a", "audio/aac":
+ return ".m4a"
+ case "audio/ogg":
+ return ".ogg"
+ case "audio/amr":
+ return ".amr"
+ }
+ switch ext := strings.ToLower(path.Ext(urlPath)); ext {
+ case ".mp3", ".wav", ".m4a", ".ogg", ".amr", ".aac":
+ return ext
+ }
+ return ".mp3"
+}
+
+// ---------- Телефоны ----------
+
+func digitsOnly(s string) string {
+ var b strings.Builder
+ for _, r := range s {
+ if r >= '0' && r <= '9' {
+ b.WriteRune(r)
+ }
+ }
+ return b.String()
+}
+
+// phoneVariants возвращает варианты записи номера, под которыми он может лежать в Битриксе.
+func phoneVariants(raw string) []string {
+ d := digitsOnly(raw)
+ if d == "" {
+ return nil
+ }
+ if len(d) == 11 && d[0] == '8' {
+ d = "7" + d[1:]
+ } else if len(d) == 10 {
+ d = "7" + d
+ }
+ if len(d) == 11 && d[0] == '7' {
+ return []string{"+" + d, d, "8" + d[1:]}
+ }
+ return []string{"+" + d, d}
+}
+
+func maskPhone(raw string) string {
+ d := digitsOnly(raw)
+ if len(d) <= 4 {
+ return "***"
+ }
+ return "***" + d[len(d)-4:]
+}
+
+// ---------- Тексты комментариев (BBCode) ----------
+
+func formatDuration(sec int64) string {
+ if sec < 0 {
+ sec = 0
+ }
+ return fmt.Sprintf("%d:%02d", sec/60, sec%60)
+}
+
+func formatTime(unix int64, loc *time.Location) string {
+ return time.Unix(unix, 0).In(loc).Format("02.01.2006 15:04")
+}
+
+func buildCallComment(e *callEvent, loc *time.Location) string {
+ answered := int64(e.Answered) == 1
+ incoming := int64(e.Direction) == 0
+
+ var title string
+ switch {
+ case incoming && answered:
+ title = "📞 Входящий звонок"
+ case incoming && !answered:
+ title = "📵 Пропущенный звонок"
+ case !incoming && answered:
+ title = "📤 Исходящий звонок"
+ default:
+ title = "📤 Исходящий звонок (без ответа)"
+ }
+
+ started := int64(e.StartTime)
+ if started == 0 {
+ started = int64(e.EventCreated)
+ }
+
+ var b strings.Builder
+ fmt.Fprintf(&b, "[b]%s[/b]\nНомер: %s\n", title, e.ClientNumber)
+ if e.ClientName != "" {
+ fmt.Fprintf(&b, "Имя в телефоне: %s\n", e.ClientName)
+ }
+ fmt.Fprintf(&b, "Время: %s\n", formatTime(started, loc))
+ if answered {
+ fmt.Fprintf(&b, "Длительность: %s\n", formatDuration(int64(e.Duration)))
+ }
+ if e.SrcNumber != "" {
+ fmt.Fprintf(&b, "Линия: %s\n", e.SrcNumber)
+ }
+ return strings.TrimRight(b.String(), "\n")
+}
+
+func buildSMSComment(e *callEvent, loc *time.Location) string {
+ title := "📥 Входящее SMS"
+ if int64(e.Direction) == 1 {
+ title = "📤 Исходящее SMS"
+ }
+ return fmt.Sprintf("[b]%s[/b]\nНомер: %s\nВремя: %s\n\n%s",
+ title, e.ClientNumber, formatTime(int64(e.EventCreated), loc), e.Text)
+}
diff --git a/service/rest_telephony_service/handlers/telephony/handlers.go b/service/rest_telephony_service/handlers/telephony/handlers.go
new file mode 100644
index 0000000..71342b1
--- /dev/null
+++ b/service/rest_telephony_service/handlers/telephony/handlers.go
@@ -0,0 +1,165 @@
+package telephonyservice
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ typesm "rest_telephony_service/types"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/sirupsen/logrus"
+)
+
+const (
+ eventCallStart = 1
+ eventCallAnswer = 2
+ eventCallFinish = 4
+ eventSMS = 32
+)
+
+func truncate(b []byte, n int) string {
+ if len(b) > n {
+ return string(b[:n]) + "..."
+ }
+ return string(b)
+}
+
+func smsKey(e *callEvent) string {
+ h := sha256.Sum256([]byte(fmt.Sprintf("%s|%d|%d|%s", e.ClientNumber, e.EventCreated, e.Direction, e.Text)))
+ return "sms:" + hex.EncodeToString(h[:12])
+}
+
+func callKey(e *callEvent) string {
+ if e.DBCallID != "" {
+ return "call:db:" + string(e.DBCallID)
+ }
+ return fmt.Sprintf("call:pbx:%s:%d", e.EventPbxCallID, e.EndTime)
+}
+
+// WebhookTelephonyHandler принимает события от «Мои Звонки» (call.finish, sms.message).
+func (s *TelephonyReg) WebhookTelephonyHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ defer r.Body.Close()
+ body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
+ if err != nil {
+ logrus.Errorf("webhook read error: %v", err)
+ return nil, errors.New("invalid request body")
+ }
+ if s.debugRaw {
+ logrus.Infof("webhook raw: %s", truncate(body, 4000))
+ }
+
+ var req webhookReq
+ if err := json.Unmarshal(body, &req); err != nil {
+ logrus.Errorf("webhook parse error: %v; body: %s", err, truncate(body, 500))
+ return nil, errors.New("invalid request body")
+ }
+ ev := &req.Event
+
+ switch int(ev.EventType) {
+ case eventSMS:
+ return s.handleSMS(&req, ev)
+ case eventCallFinish:
+ return s.handleCallFinish(ev)
+ case eventCallStart, eventCallAnswer:
+ // start/answer не нужны: call.finish содержит всю информацию о звонке
+ return map[string]string{"status": "ignored", "reason": "call start/answer are not used"}, nil
+ default:
+ return map[string]string{"status": "ignored", "reason": "unsupported event type"}, nil
+ }
+}
+
+func (s *TelephonyReg) handleSMS(req *webhookReq, ev *callEvent) (interface{}, error) {
+ accountID := string(req.Webhook.AccountID)
+ userID := string(req.Webhook.UserID)
+ number := string(ev.ClientNumber)
+ direction := int(ev.Direction)
+ text := ev.Text
+ eventTime := time.Unix(int64(ev.EventCreated), 0)
+
+ smsLog := &typescore.SmsLog{
+ AccountID: &accountID,
+ UserID: &userID,
+ ClientNumber: &number,
+ Direction: &direction,
+ Text: &text,
+ EventCreated: &eventTime,
+ }
+
+ // Ошибка БД не должна лишать клиента записи в Битриксе.
+ if err := s.ipc.Database.SMSLog.CreateSmsLogDB(context.Background(), nil, smsLog); err != nil {
+ logrus.Errorf("Failed to save SMS log: %v", err)
+ }
+
+ queued := s.sync.Enqueue(&syncJob{
+ Key: smsKey(ev),
+ Kind: "sms",
+ Number: number,
+ Comment: buildSMSComment(ev, s.loc),
+ })
+ logrus.Infof("SMS from %s accepted (queued=%v)", maskPhone(number), queued)
+ return map[string]interface{}{"status": "success", "queued": queued}, nil
+}
+
+func (s *TelephonyReg) handleCallFinish(ev *callEvent) (interface{}, error) {
+ number := string(ev.ClientNumber)
+
+ job := &syncJob{
+ Key: callKey(ev),
+ Kind: "call",
+ Number: number,
+ Comment: buildCallComment(ev, s.loc),
+ }
+ if int64(ev.Answered) == 1 && (strings.HasPrefix(ev.Recording, "https://") || strings.HasPrefix(ev.Recording, "http://")) {
+ started := int64(ev.StartTime)
+ if started == 0 {
+ started = int64(ev.EventCreated)
+ }
+ dir := "in"
+ if int64(ev.Direction) == 1 {
+ dir = "out"
+ }
+ job.RecordingURL = ev.Recording
+ job.FileBase = fmt.Sprintf("call_%s_%s_%s", dir, time.Unix(started, 0).In(s.loc).Format("20060102_1504"), digitsOnly(number))
+ }
+ queued := s.sync.Enqueue(job)
+ logrus.Infof("Call with %s accepted (answered=%d, queued=%v)", maskPhone(number), ev.Answered, queued)
+ return map[string]interface{}{"status": "success", "queued": queued}, nil
+}
+
+// GetSmsReportHandler отдает список SMS для Google Script
+func (s *TelephonyReg) GetSmsReportHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
+ startStr := r.URL.Query().Get("start")
+ endStr := r.URL.Query().Get("end")
+
+ if startStr == "" || endStr == "" {
+ return nil, errors.New("missing 'start' or 'end' query parameters")
+ }
+
+ startInt, err1 := strconv.ParseInt(startStr, 10, 64)
+ endInt, err2 := strconv.ParseInt(endStr, 10, 64)
+ if err1 != nil || err2 != nil {
+ return nil, errors.New("invalid timestamp format")
+ }
+
+ startDate := time.Unix(startInt, 0)
+ endDate := time.Unix(endInt, 0)
+
+ logs, err := s.ipc.Database.SMSLog.GetSmsLogsByDateRangeDB(context.Background(), startDate, endDate)
+ if err != nil {
+ logrus.Errorf("Failed to fetch SMS logs: %v", err)
+ return nil, errors.New("failed to fetch data")
+ }
+
+ return typesm.SmsReportResponse{
+ Success: true,
+ Data: logs,
+ }, nil
+}
diff --git a/service/rest_telephony_service/handlers/telephony/queue.go b/service/rest_telephony_service/handlers/telephony/queue.go
new file mode 100644
index 0000000..037c046
--- /dev/null
+++ b/service/rest_telephony_service/handlers/telephony/queue.go
@@ -0,0 +1,195 @@
+package telephonyservice
+
+import (
+ "context"
+ "encoding/base64"
+ "errors"
+ "fmt"
+ "sync"
+ "time"
+
+ "github.com/sirupsen/logrus"
+)
+
+const (
+ queueSize = 2000
+ maxAttempts = 8
+ dedupTTL = 48 * time.Hour
+ bitrixPause = 600 * time.Millisecond // у входящих вебхуков Битрикса лимит ~2 запроса/сек
+)
+
+var retryDelays = []time.Duration{
+ 10 * time.Second, 30 * time.Second, 2 * time.Minute,
+ 10 * time.Minute, 30 * time.Minute, time.Hour, 2 * time.Hour,
+}
+
+type syncJob struct {
+ Key string // ключ дедупликации
+ Kind string // "call" | "sms"
+ Number string
+ Comment string
+ ContactID int
+ Attempts int
+
+ // Запись разговора (только для звонков)
+ RecordingURL string
+ FileBase string // имя файла без расширения
+ fileName string
+ fileB64 string
+ linkFallback bool
+}
+
+// BitrixSync — очередь доставки в таймлайн Битрикс24: дедупликация, повторы с задержкой.
+// Очередь в памяти: при перезапуске сервиса недоставленные записи теряются.
+type BitrixSync struct {
+ bx *BitrixClient
+ queue chan *syncJob
+
+ mu sync.Mutex
+ seen map[string]time.Time
+}
+
+func NewBitrixSync(bx *BitrixClient) *BitrixSync {
+ s := &BitrixSync{
+ bx: bx,
+ queue: make(chan *syncJob, queueSize),
+ seen: make(map[string]time.Time),
+ }
+ go s.worker()
+ return s
+}
+
+// Enqueue возвращает false, если событие уже обрабатывалось или очередь переполнена.
+func (s *BitrixSync) Enqueue(job *syncJob) bool {
+ if !s.markSeen(job.Key) {
+ return false
+ }
+ select {
+ case s.queue <- job:
+ return true
+ default:
+ logrus.Errorf("bitrix: queue is full, dropping %s %s", job.Kind, job.Key)
+ s.forget(job.Key)
+ return false
+ }
+}
+
+func (s *BitrixSync) markSeen(key string) bool {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ now := time.Now()
+ if len(s.seen) > 5000 {
+ for k, t := range s.seen {
+ if now.Sub(t) > dedupTTL {
+ delete(s.seen, k)
+ }
+ }
+ }
+ if t, ok := s.seen[key]; ok && now.Sub(t) < dedupTTL {
+ return false
+ }
+ s.seen[key] = now
+ return true
+}
+
+func (s *BitrixSync) forget(key string) {
+ s.mu.Lock()
+ delete(s.seen, key)
+ s.mu.Unlock()
+}
+
+func (s *BitrixSync) worker() {
+ for job := range s.queue {
+ s.handle(job)
+ time.Sleep(bitrixPause)
+ }
+}
+
+func (s *BitrixSync) handle(job *syncJob) {
+ ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
+ defer cancel()
+
+ job.Attempts++
+ err := s.process(ctx, job)
+
+ switch {
+ case err == nil:
+ logrus.Infof("bitrix: %s delivered to contact %d (number %s, attempt %d)",
+ job.Kind, job.ContactID, maskPhone(job.Number), job.Attempts)
+
+ case isPermanent(err):
+ // ключ остаётся в дедупликации: тот же звонок/SMS повторно не обрабатываем
+ logrus.Warnf("bitrix: %s skipped (number %s): %v", job.Kind, maskPhone(job.Number), err)
+
+ case job.Attempts >= maxAttempts:
+ logrus.Errorf("bitrix: %s given up after %d attempts (number %s): %v",
+ job.Kind, job.Attempts, maskPhone(job.Number), err)
+ s.forget(job.Key)
+
+ default:
+ idx := job.Attempts - 1
+ if idx >= len(retryDelays) {
+ idx = len(retryDelays) - 1
+ }
+ delay := retryDelays[idx]
+ logrus.Warnf("bitrix: %s failed (number %s, attempt %d), retry in %s: %v",
+ job.Kind, maskPhone(job.Number), job.Attempts, delay, err)
+ time.AfterFunc(delay, func() {
+ select {
+ case s.queue <- job:
+ default:
+ logrus.Errorf("bitrix: queue is full, retry lost for %s %s", job.Kind, job.Key)
+ s.forget(job.Key)
+ }
+ })
+ }
+}
+
+func (s *BitrixSync) process(ctx context.Context, job *syncJob) error {
+ if job.ContactID == 0 {
+ id, err := s.bx.FindContact(ctx, job.Number)
+ if err != nil {
+ return err
+ }
+ job.ContactID = id
+ }
+ if err := s.prepareRecording(ctx, job); err != nil {
+ return err
+ }
+
+ comment := job.Comment
+ switch {
+ case job.fileB64 != "":
+ comment += "\n🎧 Запись разговора — во вложении"
+ case job.linkFallback:
+ comment += fmt.Sprintf("\n[url=%s]Запись разговора[/url]", job.RecordingURL)
+ }
+ return s.bx.AddComment(ctx, job.ContactID, comment, job.fileName, job.fileB64)
+}
+
+// prepareRecording скачивает запись один раз и держит её в задании на время повторов.
+// Если скачать не удалось за 3 попытки (или файл слишком большой), в комментарий
+// вставляется ссылка, чтобы звонок не потерялся.
+func (s *BitrixSync) prepareRecording(ctx context.Context, job *syncJob) error {
+ if job.RecordingURL == "" || job.fileB64 != "" || job.linkFallback {
+ return nil
+ }
+ data, name, err := s.bx.DownloadRecording(ctx, job.RecordingURL, job.FileBase)
+ switch {
+ case err == nil:
+ job.fileName = name
+ job.fileB64 = base64.StdEncoding.EncodeToString(data)
+ return nil
+ case errors.Is(err, errRecordingTooBig):
+ logrus.Warnf("bitrix: recording too big, posting link instead (number %s)", maskPhone(job.Number))
+ job.linkFallback = true
+ return nil
+ case job.Attempts >= 3:
+ logrus.Warnf("bitrix: recording unavailable (number %s): %v; posting link instead", maskPhone(job.Number), err)
+ job.linkFallback = true
+ return nil
+ default:
+ return err
+ }
+}
diff --git a/service/rest_telephony_service/handlers/telephony/routes.go b/service/rest_telephony_service/handlers/telephony/routes.go
new file mode 100644
index 0000000..a064579
--- /dev/null
+++ b/service/rest_telephony_service/handlers/telephony/routes.go
@@ -0,0 +1,88 @@
+package telephonyservice
+
+import (
+ "crypto/subtle"
+ "net/http"
+ "os"
+ "rest_telephony_service/handlers"
+ typesm "rest_telephony_service/types"
+ "time"
+
+ "github.com/go-chi/chi/v5"
+ "github.com/sirupsen/logrus"
+)
+
+type TelephonyReg struct {
+ ipc *typesm.InternalProviderControl
+ sync *BitrixSync
+ loc *time.Location
+ debugRaw bool
+}
+
+// tokenAuth проверяет ?token=... (у вебхуков «Мои Звонки» нет подписи).
+func tokenAuth(token string) func(http.Handler) http.Handler {
+ return func(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ got := r.URL.Query().Get("token")
+ if subtle.ConstantTimeCompare([]byte(got), []byte(token)) != 1 {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusUnauthorized)
+ _, _ = w.Write([]byte(`{"error_code":401,"error_description":"unauthorized"}`))
+ return
+ }
+ next.ServeHTTP(w, r)
+ })
+ }
+}
+
+// RegisterTelephonyRoutes регистрирует маршруты телефонии.
+//
+// Переменные окружения:
+//
+// BITRIX_WEBHOOK_URL необязательна: переопределяет константу bitrixWebhookURL из bitrix.go
+// TELEPHONY_WEBHOOK_TOKEN секрет в URL вебхука (?token=...); если пусто — проверка отключена
+// TELEPHONY_TZ часовой пояс для времени в комментариях (по умолчанию Europe/Moscow)
+// TELEPHONY_DEBUG_RAW "1" — логировать сырые тела вебхуков (содержат номера и тексты)
+func RegisterTelephonyRoutes(r chi.Router, ipc *typesm.InternalProviderControl) error {
+ bxURL := os.Getenv("BITRIX_WEBHOOK_URL")
+ if bxURL == "" {
+ bxURL = bitrixWebhookURL
+ }
+
+ tzName := os.Getenv("TELEPHONY_TZ")
+ if tzName == "" {
+ tzName = "Europe/Moscow"
+ }
+ loc, err := time.LoadLocation(tzName)
+ if err != nil {
+ logrus.Warnf("cannot load timezone %q (%v), using UTC+3", tzName, err)
+ loc = time.FixedZone("MSK", 3*60*60)
+ }
+
+ token := os.Getenv("TELEPHONY_WEBHOOK_TOKEN")
+ if token == "" {
+ logrus.Warn("⚠️ TELEPHONY_WEBHOOK_TOKEN is empty: webhook is open to anyone. Getting default token from constants")
+ token = "795ea01b3b195296ec53e35342deed0aa418b7630ce8ed31"
+ }
+
+ s := &TelephonyReg{
+ ipc: ipc,
+ sync: NewBitrixSync(NewBitrixClient(bxURL)),
+ loc: loc,
+ debugRaw: os.Getenv("TELEPHONY_DEBUG_RAW") == "1",
+ }
+
+ r.Route("/api/v1/telephony", func(r chi.Router) {
+ webhook := r
+ if token != "" {
+ webhook = r.With(tokenAuth(token))
+ }
+ handlers.RegisterRoute(webhook, http.MethodPost, "/webhook", s.WebhookTelephonyHandler)
+
+ // Отдача данных для Google Script. При необходимости закройте
+ // r.Use(handlers.AccessCodeVerifier(ipc.Config)).
+ handlers.RegisterRoute(r, http.MethodGet, "/sms-report", s.GetSmsReportHandler)
+ })
+
+ return nil
+}
diff --git a/service/rest_telephony_service/handlers/telephony/type.go b/service/rest_telephony_service/handlers/telephony/type.go
new file mode 100644
index 0000000..c790a16
--- /dev/null
+++ b/service/rest_telephony_service/handlers/telephony/type.go
@@ -0,0 +1,93 @@
+package telephonyservice
+
+import (
+ "encoding/json"
+ "strconv"
+ "strings"
+)
+
+// FlexString принимает и JSON-строку, и число (src_id, db_call_id и т.п.).
+type FlexString string
+
+func (f *FlexString) UnmarshalJSON(b []byte) error {
+ s := strings.TrimSpace(string(b))
+ if s == "null" {
+ return nil
+ }
+ if len(s) > 0 && s[0] == '"' {
+ var v string
+ if err := json.Unmarshal(b, &v); err != nil {
+ return err
+ }
+ *f = FlexString(v)
+ return nil
+ }
+ *f = FlexString(s)
+ return nil
+}
+
+func (f FlexString) String() string { return string(f) }
+
+// FlexInt принимает число, число в строке, true/false и null.
+type FlexInt int64
+
+func (f *FlexInt) UnmarshalJSON(b []byte) error {
+ s := strings.Trim(strings.TrimSpace(string(b)), `"`)
+ switch s {
+ case "", "null", "false":
+ *f = 0
+ return nil
+ case "true":
+ *f = 1
+ return nil
+ }
+ if n, err := strconv.ParseInt(s, 10, 64); err == nil {
+ *f = FlexInt(n)
+ return nil
+ }
+ fl, err := strconv.ParseFloat(s, 64)
+ if err != nil {
+ return err
+ }
+ *f = FlexInt(int64(fl))
+ return nil
+}
+
+// webhookReq — корневой объект POST-запроса от «Мои Звонки».
+type webhookReq struct {
+ Webhook webhookMeta `json:"webhook"`
+ Event callEvent `json:"event"`
+}
+
+type webhookMeta struct {
+ Action string `json:"action"`
+ AccountID FlexString `json:"account_id"`
+ AccountName string `json:"account_name"`
+ UserID FlexString `json:"user_id"`
+ UserLogin string `json:"user_login"`
+}
+
+// callEvent — событие звонка (тип 1, 2, 4) или SMS (тип 32).
+type callEvent struct {
+ EventType FlexInt `json:"event_type"` // 1 начало, 2 ответ, 4 окончание, 32 SMS
+ EventCreated FlexInt `json:"event_created"`
+ Direction FlexInt `json:"direction"` // 0 входящий, 1 исходящий
+ ClientNumber FlexString `json:"client_number"`
+ ClientName string `json:"client_name"`
+ EventPbxCallID FlexString `json:"event_pbx_call_id"`
+ SrcNumber FlexString `json:"src_number"`
+ SrcID FlexString `json:"src_id"`
+ SrcSlot FlexInt `json:"src_slot"`
+
+ // Только call.finish
+ StartTime FlexInt `json:"start_time"`
+ AnswerTime FlexInt `json:"answer_time"`
+ EndTime FlexInt `json:"end_time"`
+ Duration FlexInt `json:"duration"`
+ Answered FlexInt `json:"answered"`
+ Recording string `json:"recording"`
+ DBCallID FlexString `json:"db_call_id"`
+
+ // Только sms.message
+ Text string `json:"text"`
+}
diff --git a/service/rest_telephony_service/types/types.go b/service/rest_telephony_service/types/types.go
new file mode 100644
index 0000000..f5b3687
--- /dev/null
+++ b/service/rest_telephony_service/types/types.go
@@ -0,0 +1,34 @@
+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"
+ "bitrix_balancer_api/core/typescore"
+)
+
+type InternalProviderControl struct {
+ Config *configcore.Config
+ RedisClient *redismodule.ModuleRedis
+ TGBotClient *tgkit.Client
+ Database *database.ModuleDB
+}
+
+type TelephonyWebhookReq struct {
+ Webhook WebhookMeta `json:"webhook"`
+ Event typescore.CallEvent `json:"event"`
+}
+
+type WebhookMeta struct {
+ Action string `json:"action"`
+ AccountID string `json:"account_id"`
+ AccountName string `json:"account_name"`
+ UserID string `json:"user_id"`
+ UserLogin string `json:"user_login"`
+}
+
+type SmsReportResponse struct {
+ Success bool `json:"success"`
+ Data []*typescore.SmsLog `json:"data,omitempty"`
+}
diff --git a/service/system_service/cmd/app.go b/service/system_service/cmd/app.go
index ed1a2bb..d5f7b50 100644
--- a/service/system_service/cmd/app.go
+++ b/service/system_service/cmd/app.go
@@ -8,6 +8,8 @@ import (
"errors"
"fmt"
"github.com/sirupsen/logrus"
+ "os"
+ "time"
)
func main() {
@@ -16,7 +18,8 @@ func main() {
logrus.Error(errors.New(fmt.Sprintf("failed to init service: %v", err)))
return
}
- select {}
+ time.Sleep(1 * time.Second)
+ os.Exit(0)
}
func initService() error {
diff --git a/service/telegram_service/approvalflow/dynamic_topic.go b/service/telegram_service/approvalflow/dynamic_topic.go
new file mode 100644
index 0000000..af168d6
--- /dev/null
+++ b/service/telegram_service/approvalflow/dynamic_topic.go
@@ -0,0 +1,476 @@
+package approvalflow
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bytes"
+ "fmt"
+ "github.com/sirupsen/logrus"
+ "sort"
+ "strings"
+ "text/template"
+)
+
+// DynamicTopic — тема, соответствующая ОДНОЙ КАТЕГОРИИ (approval_topic_categories),
+// построенная из всех approval_flow_nodes всех тем (approval_topics), относящихся
+// к этой категории.
+type DynamicTopic struct {
+ category *typescore.ApprovalTopicCategory
+ nodes []*typescore.ApprovalFlowNode
+
+ codeTemplate string
+ messageTemplate string
+
+ dataValueLabels map[string]string
+}
+
+func NewDynamicTopic(category *typescore.ApprovalTopicCategory, nodes []*typescore.ApprovalFlowNode) *DynamicTopic {
+ d := &DynamicTopic{
+ category: category,
+ nodes: nodes,
+ dataValueLabels: make(map[string]string),
+ }
+
+ for _, n := range nodes {
+ if n.ParentID == nil {
+ if n.CodeTemplate != nil {
+ d.codeTemplate = *n.CodeTemplate
+ }
+ if n.MessageTemplate != nil {
+ d.messageTemplate = *n.MessageTemplate
+ }
+ }
+
+ label := safeString(n.Label)
+ if label == "" {
+ continue
+ }
+ if dk, dv := safeString(n.DataKey), safeString(n.DataValue); dk != "" && dv != "" {
+ d.dataValueLabels[dataValueLabelKey(dk, dv)] = label
+ }
+ if mk, mv := safeString(n.MultiSelectKey), safeString(n.MultiSelectValue); mk != "" && mv != "" {
+ d.dataValueLabels[dataValueLabelKey(mk, mv)] = label
+ }
+ }
+
+ return d
+}
+
+func dataValueLabelKey(key, value string) string {
+ return key + "\x00" + value
+}
+
+func (d *DynamicTopic) Code() string {
+ if d.category.Code != nil {
+ return *d.category.Code
+ }
+ return ""
+}
+
+func (d *DynamicTopic) Name() string {
+ if d.category.Name != nil {
+ return *d.category.Name
+ }
+ return ""
+}
+
+// BuildTree строит дерево FlowNode из плоского списка узлов БД.
+// ВАЖНО: ровно один узел на категорию должен иметь ParentID == nil,
+// иначе (как и раньше) переменная root будет молча перезаписана
+// и часть дерева станет недостижимой через FindNode.
+func (d *DynamicTopic) BuildTree() *FlowNode {
+ if len(d.nodes) == 0 {
+ return nil
+ }
+
+ nodeMap := make(map[uint64]*FlowNode)
+ var root *FlowNode
+
+ for _, dbNode := range d.nodes {
+ if dbNode.ID == nil {
+ continue
+ }
+
+ fn := &FlowNode{
+ Key: safeString(dbNode.Key),
+ Label: safeString(dbNode.Label),
+ DataKey: safeString(dbNode.DataKey),
+ DataValue: safeString(dbNode.DataValue),
+ IsInput: safeBool(dbNode.IsInput),
+ InputKey: safeString(dbNode.InputKey),
+ InputHint: safeString(dbNode.InputHint),
+ IsMultiSelect: safeBool(dbNode.IsMultiSelect),
+ MultiSelectKey: safeString(dbNode.MultiSelectKey),
+ MultiSelectValue: safeString(dbNode.MultiSelectValue),
+ TopicCode: safeString(dbNode.TopicCode),
+ }
+ nodeMap[*dbNode.ID] = fn
+ }
+
+ for _, dbNode := range d.nodes {
+ if dbNode.ID == nil {
+ continue
+ }
+ fn := nodeMap[*dbNode.ID]
+
+ if dbNode.ParentID == nil {
+ root = fn
+ } else if parent, ok := nodeMap[*dbNode.ParentID]; ok {
+ parent.Children = append(parent.Children, fn)
+ }
+ }
+
+ // Сортировка детей — БЕЗ ИЗМЕНЕНИЙ (известный баг: сортирует по Key,
+ // а не по SortOrder; договорились пока не трогать)
+ for _, fn := range nodeMap {
+ sort.Slice(fn.Children, func(i, j int) bool {
+ return fn.Children[i].Key < fn.Children[j].Key
+ })
+ }
+
+ return root
+}
+
+func (d *DynamicTopic) TopicCodeFromCollected(collected map[string]string) (string, error) {
+ baseCode := d.Code()
+
+ if d.codeTemplate != "" {
+ return d.applyCodeTemplate(d.codeTemplate, collected)
+ }
+
+ var parts []string
+ parts = append(parts, baseCode)
+
+ var keys []string
+ for k := range collected {
+ if k != "content" && k != "instructions" {
+ keys = append(keys, k)
+ }
+ }
+ sort.Strings(keys)
+
+ for _, k := range keys {
+ v := collected[k]
+ if v != "" {
+ parts = append(parts, v)
+ }
+ }
+
+ return strings.Join(parts, "_"), nil
+}
+
+func createTemplateFuncMap() template.FuncMap {
+ return template.FuncMap{
+ "trimPrefix": strings.TrimPrefix,
+ "trimSuffix": strings.TrimSuffix,
+ "toUpper": strings.ToUpper,
+ "toLower": strings.ToLower,
+ "replace": strings.ReplaceAll,
+
+ "join": func(items []string, sep string) string {
+ return strings.Join(items, sep)
+ },
+ "split": func(s, sep string) []string {
+ return strings.Split(s, sep)
+ },
+
+ "eq": func(a, b string) bool { return a == b },
+ "ne": func(a, b string) bool { return a != b },
+
+ "contains": strings.Contains,
+ "hasPrefix": strings.HasPrefix,
+ "hasSuffix": strings.HasSuffix,
+ }
+}
+
+func (d *DynamicTopic) applyCodeTemplate(tmpl string, data map[string]string) (string, error) {
+ logrus.Printf("🔍 DEBUG applyCodeTemplate: шаблон = %q", tmpl)
+
+ t, err := template.New("code").Option("missingkey=zero").Funcs(createTemplateFuncMap()).Parse(tmpl)
+ if err != nil {
+ return "", fmt.Errorf("parse code template: %w", err)
+ }
+
+ var buf bytes.Buffer
+ if err := t.Execute(&buf, data); err != nil {
+ return "", fmt.Errorf("execute code template: %w", err)
+ }
+
+ result := buf.String()
+
+ result = strings.ReplaceAll(result, "", "")
+
+ for strings.Contains(result, "__") {
+ result = strings.ReplaceAll(result, "__", "_")
+ }
+
+ result = strings.TrimSuffix(result, "_")
+
+ return strings.TrimSpace(result), nil
+}
+
+func (d *DynamicTopic) applyMessageTemplate(tmpl, initiatorName string, data map[string]string) string {
+ t, err := template.New("message").Funcs(createTemplateFuncMap()).Parse(tmpl)
+ if err != nil {
+ return d.defaultMessage(initiatorName, data)
+ }
+
+ templateData := make(map[string]interface{})
+ for k, v := range data {
+ templateData[k] = v
+ }
+ templateData["initiator_name"] = initiatorName
+ templateData["topic_name"] = d.Name()
+
+ d.addLabelMappings(templateData, data)
+ d.addTreeLabelMappings(templateData, data)
+
+ var buf bytes.Buffer
+ if err := t.Execute(&buf, templateData); err != nil {
+ return d.defaultMessage(initiatorName, data)
+ }
+
+ return buf.String()
+}
+
+func (d *DynamicTopic) addTreeLabelMappings(templateData map[string]interface{}, data map[string]string) {
+ for key, value := range data {
+ if value == "" {
+ continue
+ }
+ if label, ok := d.dataValueLabels[dataValueLabelKey(key, value)]; ok {
+ templateData[key+"_label"] = label
+ continue
+ }
+ // Мультивыбор хранится как "value1,value2" — если единого
+ // совпадения нет, пробуем разобрать по частям и подписать
+ // каждую по отдельности, объединив через запятую.
+ if strings.Contains(value, ",") {
+ parts := strings.Split(value, ",")
+ var labels []string
+ for _, p := range parts {
+ p = strings.TrimSpace(p)
+ if l, ok := d.dataValueLabels[dataValueLabelKey(key, p)]; ok {
+ labels = append(labels, l)
+ } else {
+ labels = append(labels, p)
+ }
+ }
+ if len(labels) > 0 {
+ templateData[key+"_label"] = strings.Join(labels, ", ")
+ }
+ }
+ }
+}
+
+// FormatApproverMessage форматирует сообщение для согласующего.
+// messageTemplate теперь берётся из корневого узла дерева категории.
+func (d *DynamicTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string {
+ initiatorName := "—"
+ if initiator != nil && initiator.FullName != nil {
+ initiatorName = *initiator.FullName
+ }
+
+ if d.messageTemplate != "" {
+ return d.applyMessageTemplate(d.messageTemplate, initiatorName, collected)
+ }
+
+ content := collected["content"]
+ if content == "" {
+ content = "—"
+ }
+
+ return fmt.Sprintf(
+ "📋 Заявка на согласование\n\n"+
+ "👤 От: %s\n"+
+ "📂 Тема: %s\n"+
+ "📝 Текст:\n%s",
+ initiatorName, d.Name(), content,
+ )
+}
+
+// addLabelMappings — БЕЗ ИЗМЕНЕНИЙ относительно предыдущей версии
+func (d *DynamicTopic) addLabelMappings(templateData map[string]interface{}, data map[string]string) {
+ if region, ok := data["region"]; ok {
+ regionLabels := map[string]string{"crimea": "Крым", "krasnodar": "Краснодар", "belarus": "Беларусь"}
+ if label, exists := regionLabels[region]; exists {
+ templateData["region_label"] = label
+ } else {
+ templateData["region_label"] = region
+ }
+ }
+
+ if absenceType, ok := data["absence_type"]; ok {
+ absenceLabels := map[string]string{"timeoff": "Отгул", "vacation": "Отпуск", "sickleave": "Официальный больничный"}
+ if label, exists := absenceLabels[absenceType]; exists {
+ templateData["absence_type_label"] = label
+ } else {
+ templateData["absence_type_label"] = absenceType
+ }
+ }
+
+ if changeType, ok := data["change_type"]; ok {
+ changeLabels := map[string]string{"rename": "Поменять название", "change_manager": "Сменить менеджера", "new_client": "Внести нового клиента"}
+ if label, exists := changeLabels[changeType]; exists {
+ templateData["change_type_label"] = label
+ } else {
+ templateData["change_type_label"] = changeType
+ }
+ }
+
+ if paymentType, ok := data["payment_type"]; ok {
+ paymentLabels := map[string]string{"own_expense": "за свой счёт", "vacation_account": "в счёт ежегодного отпуска", "official": "только официальный больничный"}
+ if label, exists := paymentLabels[paymentType]; exists {
+ templateData["payment_type_label"] = label
+ } else {
+ templateData["payment_type_label"] = paymentType
+ }
+ }
+
+ if branch, ok := data["branch"]; ok {
+ branchLabels := map[string]string{"f1": "Ф1", "f2": "Ф2"}
+ if label, exists := branchLabels[branch]; exists {
+ templateData["branch_label"] = label
+ } else {
+ templateData["branch_label"] = branch
+ }
+ }
+
+ if expenseType, ok := data["expense_type"]; ok {
+ expenseLabels := map[string]string{"tmc": "ТМЦ", "expense": "Расход"}
+ if label, exists := expenseLabels[expenseType]; exists {
+ templateData["expense_type_label"] = label
+ } else {
+ templateData["expense_type_label"] = expenseType
+ }
+ }
+
+ if ppRequired, ok := data["pp_required"]; ok {
+ ppLabels := map[string]string{"yes": "✅ Нужна ПП", "no": "❌ Не нужна ПП"}
+ if label, exists := ppLabels[ppRequired]; exists {
+ templateData["pp_required_label"] = label
+ } else {
+ templateData["pp_required_label"] = ppRequired
+ }
+ }
+
+ if returnType, ok := data["return_type"]; ok {
+ returnLabels := map[string]string{"supplier": "Возврат поставщику", "other_manager": "Продажа другим менеджером", "self_sale": "Самостоятельная продажа"}
+ if label, exists := returnLabels[returnType]; exists {
+ templateData["return_type_label"] = label
+ } else {
+ templateData["return_type_label"] = returnType
+ }
+ }
+
+ if orderType, ok := data["order_type"]; ok {
+ orderLabels := map[string]string{"monthly": "На месяц", "additional": "Дополнительный заказ"}
+ if label, exists := orderLabels[orderType]; exists {
+ templateData["order_type_label"] = label
+ } else {
+ templateData["order_type_label"] = orderType
+ }
+ }
+
+ if rateType, ok := data["rate_type"]; ok {
+ rateLabels := map[string]string{"once": "Разово", "long_term": "Надолго"}
+ if label, exists := rateLabels[rateType]; exists {
+ templateData["rate_type_label"] = label
+ } else {
+ templateData["rate_type_label"] = rateType
+ }
+ }
+
+ if shipmentType, ok := data["shipment_type"]; ok {
+ shipmentLabels := map[string]string{"real": "Реальная", "limit": "Для лимита"}
+ if label, exists := shipmentLabels[shipmentType]; exists {
+ templateData["shipment_type_label"] = label
+ } else {
+ templateData["shipment_type_label"] = shipmentType
+ }
+ }
+
+ if durationType, ok := data["duration_type"]; ok {
+ durationLabels := map[string]string{
+ "single_day": "На один день", "multi_day": "Несколько дней", "date_range": "Диапазон дат",
+ "sl_single_day": "На один день", "sl_date_range": "Диапазон дат",
+ }
+ if label, exists := durationLabels[durationType]; exists {
+ templateData["duration_type_label"] = label
+ } else {
+ templateData["duration_type_label"] = durationType
+ }
+ }
+
+ if timeType, ok := data["time_type"]; ok {
+ timeLabels := map[string]string{"full_day": "Весь день", "partial": "Частично"}
+ if label, exists := timeLabels[timeType]; exists {
+ templateData["time_type_label"] = label
+ } else {
+ templateData["time_type_label"] = timeType
+ }
+ }
+
+ if paymentCategory, ok := data["payment_category"]; ok {
+ categoryLabels := map[string]string{"goods": "Товар", "misc": "Разное"}
+ if label, exists := categoryLabels[paymentCategory]; exists {
+ templateData["payment_category_label"] = label
+ } else {
+ templateData["payment_category_label"] = paymentCategory
+ }
+ }
+
+ if systems, ok := data["systems"]; ok {
+ templateData["systems_label"] = d.mapSystems(systems)
+ }
+}
+
+func (d *DynamicTopic) mapSystems(systems string) string {
+ if systems == "" {
+ return "не указаны"
+ }
+ parts := strings.Split(systems, ",")
+ var labels []string
+ for _, p := range parts {
+ p = strings.TrimSpace(p)
+ switch p {
+ case "okb":
+ labels = append(labels, "ОКБ")
+ case "1c":
+ labels = append(labels, "1С")
+ default:
+ labels = append(labels, p)
+ }
+ }
+ if len(labels) == 0 {
+ return "не указаны"
+ }
+ return strings.Join(labels, ", ")
+}
+
+func (d *DynamicTopic) defaultMessage(initiatorName string, data map[string]string) string {
+ content := data["content"]
+ if content == "" {
+ content = "—"
+ }
+ return fmt.Sprintf(
+ "📋 Заявка на согласование\n\n"+
+ "👤 От: %s\n"+
+ "📂 Тема: %s\n"+
+ "📝 Текст:\n%s",
+ initiatorName, d.Name(), content,
+ )
+}
+
+func safeString(s *string) string {
+ if s == nil {
+ return ""
+ }
+ return *s
+}
+
+func safeBool(b *bool) bool {
+ if b == nil {
+ return false
+ }
+ return *b
+}
diff --git a/service/telegram_service/cmd/app.go b/service/telegram_service/cmd/app.go
index e79e65b..bf2b1c5 100644
--- a/service/telegram_service/cmd/app.go
+++ b/service/telegram_service/cmd/app.go
@@ -1,18 +1,24 @@
package main
import (
+ _ "embed"
+
configcore "bitrix_balancer_api/core/config"
- "bitrix_balancer_api/core/lib/external/tgkit"
+ "bitrix_balancer_api/core/lib/external/googlesheets"
clientcontrollers "bitrix_balancer_api/core/lib/internally/client-controllers"
+ "bitrix_balancer_api/core/lib/internally/monthly_orders"
tgupdatehandler "bitrix_balancer_api/telegram_service/common/update"
"bitrix_balancer_api/telegram_service/scheduler"
"bitrix_balancer_api/telegram_service/types"
+ "context"
"github.com/sirupsen/logrus"
"log"
- "net/url"
"runtime/debug"
)
+//go:embed google-creds.json
+var googleCredsJSON []byte
+
func main() {
err := initService()
if err != nil {
@@ -22,7 +28,6 @@ func main() {
}
func initService() error {
- // Получение конфигурации приложения
clientsExternal, err := getClientsExternal()
if err != nil {
return err
@@ -36,12 +41,34 @@ func initService() error {
delegationChecker := scheduler.NewDelegationChecker(ipc)
delegationChecker.Start()
+ dailyReminder := scheduler.NewDailyReminder(ipc)
+ dailyReminder.Start()
+
+ ctx := context.Background()
+ gsClient, err := googlesheets.NewClient(ctx, googleCredsJSON)
+ if err != nil {
+ logrus.Errorf("Не удалось инициализировать Google Sheets API: %v", err)
+ }
+
+ // НОВОЕ: Перенесли создание UpdateHandler ВЫШЕ
update := tgupdatehandler.NewUpdateHandler(ipc)
go func() {
- defer handlePanic("update.GetUpdateTelegram goroutine") // Обработка паник в горутине
+ defer handlePanic("update.GetUpdateTelegram goroutine")
update.GetUpdateTelegram()
}()
+ // НОВОЕ: Передаем update.GetApprovalHandler() как интерфейс
+ moService := monthly_orders.NewMonthlyOrderService(
+ ipc,
+ gsClient,
+ "1F1ansQeSuAwhe3Y_mhfm4ja370k5hq67RruE-CVp83w",
+ "1C4Tl-AQRJENW4THzwH-7yP2Ni0ckMSdm3ndLCrdKr2Y",
+ update.GetApprovalHandler(),
+ )
+
+ monthlyOrderChecker := scheduler.NewMonthlyOrderChecker(ipc, moService)
+ monthlyOrderChecker.Start()
+
return nil
}
@@ -59,29 +86,11 @@ func getClientsExternal() (clientcontrollers.ClientsExternal, error) {
}
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,
+ TGBotClient: clientsExternal.Telegram,
}, nil
}
diff --git a/service/telegram_service/cmd/google-creds.json b/service/telegram_service/cmd/google-creds.json
new file mode 100644
index 0000000..91c875c
--- /dev/null
+++ b/service/telegram_service/cmd/google-creds.json
@@ -0,0 +1,13 @@
+{
+ "type": "service_account",
+ "project_id": "ruspet",
+ "private_key_id": "37f429a3549be247a03a37cc3274e8d4ea9f7bde",
+ "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCwWSW8v4Tdp3US\nxLLJUTAlW0aMFEkbCbyf5U22jjzNhHPfgg019yvgJPSjm51oSH9kC5PYo/z2Tnxp\nUsxzAaBrKL7DfrGbNQkuQyLPUQj6w2Co5P4N1lRdYeli9fxXpbf496BbSyl8M2yf\nNjIO7L+9K+nRCqkMwzDfHFS8frJNhPy5u98w/eFSSiyHI14ocXzVYgt6w4bBWwht\nDGhjxAegpGtjgkXi9BZ9tKhcK3vlkQiG4UAqWQdA4gqfFXFis7xf1z4iHBOAvIXe\nJbKIsCpGNIDe5dROt5r7wGtgXjtKfWXjs+Te0NJ8om8f29wkan6hFX/QQ7uMJio9\ndE4iiO8fAgMBAAECggEABULQ7JByzcwM+D+JrUDbT1n+66HqoRW0HLm8t56xs1iU\nE7hvssr0x6NCmyOYLsAZm39O7K55Fv4LbyGgZilHww/8SkfG06sMODxE1xYt+ZEy\nRTJOXqpPalkdRdhcgV7jyK0r3wgJ16HkcobYN81vVkeaRPls8VZcvbiSJ0IeXqVK\n1h2QIKOrcb2RtWRgE9RMrmdgczAznlUU0Lg+WPV1CgAaiGeh9PwAw7qSsSI/z1nR\nTCn027JiByrdEXWFJQSAfPqctqKgeHwfoUOWnssp8IXTNK6PpZZhBfM8h2rXUfME\nXKwhshbySrBoULMIs+O2AcRIOxuWPgsT0fcsOyeqtQKBgQDeOWn+kBQFuBlwsX/B\nn2pkG9EXY9IKUMcecIBXG76TfkQ2xtLPQMLaALWEqL/WJl0VeCSzifialLVxBIIv\nfSJu/yJMaY16VczhlqN7rBU91dFv1+ySUPeRgTMzoZhh4hi4QliA9mqDVvnk3bQN\n2QUL5nBSbigq2grBLSYv6i2MwwKBgQDLJrrP3TxWBD79kaw8P9RK2K1zdYvAwvms\nx1B2HlgS8TwQJUA69JlzKr87Tr00oK2n8mZCmzHpwK4FNkoHfqe8LFdo1ulHYlTG\nKaB5uDYun8XOKYFuUKwe0lpwgdyDefAmHAWwTSK38WOfvVdvdr9C6zpbOZXVqOC/\nXbt9FVhedQKBgQDOx3Hfk8VtxO63NBMC4gmneVLIhvPM8Xk208w4QfLFX7qtlbhX\nbZViMUK2XCeVZ0E6Vv8fqQSRIkrrDRzuf2vpCLKrk5Q3/1qTlw4sZ+WkEi+9+JeD\nVp/m3uf75SPcAPyrh+C+r4xRBj+lPL7sG8JcXmKp8SKjLRzQv+hGsYsM7QKBgQDI\nTkDGceJrAbbGOJs1sM32mpyzikQo5VZfGQtp29OFodxSIxioyMKAvrZdmO6P9Jol\nTamspO9bBwPO2c+2ghiLPsFU+wp6uybRWPwE6DBsWlckRuJ6zgpYPZq08iZmcJXs\nTZcCVZwU+Gr9dyi+G7zME7mvdyEY0XIA3j/ePmyqfQKBgCd90yw1gJU6KnRUJS0U\ns4Z4hcnxRiar9LUk/GX/ELObd6ONs0BiN/GAVRWQl8tP3+J4jlF9XkQVGsGQdHdf\nannCbxcrMt3lHcKyOAOnjMsnWPfqWL5CJ0z+9Thg5L+GXZDCk1SJOu5vwCVVxiw2\nRs5O5K+U9K2xBZcpYhNlt7o2\n-----END PRIVATE KEY-----\n",
+ "client_email": "service-account@ruspet.iam.gserviceaccount.com",
+ "client_id": "117800311304874293466",
+ "auth_uri": "https://accounts.google.com/o/oauth2/auth",
+ "token_uri": "https://oauth2.googleapis.com/token",
+ "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
+ "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/service-account%40ruspet.iam.gserviceaccount.com",
+ "universe_domain": "googleapis.com"
+}
diff --git a/service/telegram_service/common/update/0_init.go b/service/telegram_service/common/update/0_init.go
index 7b80554..c1c2cf5 100644
--- a/service/telegram_service/common/update/0_init.go
+++ b/service/telegram_service/common/update/0_init.go
@@ -14,6 +14,10 @@ import (
"time"
)
+func (s *UpdateHandler) GetApprovalHandler() *approval.Handler {
+ return s.approvalHandler
+}
+
type UpdateHandler struct {
ipc *types.InternalProviderControl
approvalHandler *approval.Handler
@@ -39,7 +43,9 @@ func NewUpdateHandler(ipc *types.InternalProviderControl) *UpdateHandler {
}
// TODO: вызывается только после обновлений
- //go handler.broadcastBotUpdated()
+ //go handlers.broadcastBotUpdated()
+ //go handlers.sendNewSupportContactNotification()
+ //go handlers.broadcastCommentsFeatureUpdate()
return handler
}
@@ -78,3 +84,90 @@ func (s *UpdateHandler) broadcastBotUpdated() {
logrus.Infof("broadcastBotUpdated: отправлено %d пользователям", len(users))
}
+
+// sendNewSupportContactNotification отправляет уведомление о смене ответственного за настройку системы
+func (s *UpdateHandler) sendNewSupportContactNotification() {
+ ctx := context.Background()
+ bot := s.ipc.TGBotClient.Bot()
+
+ users, _, err := s.ipc.Database.User.GetUsersListDB(ctx, typescore.ListDbOptions{})
+ if err != nil {
+ logrus.Errorf("sendNewSupportContactNotification: GetUsersListDB err=%v", err)
+ return
+ }
+
+ newSupportURL := "https://t.me/ahsailmi"
+
+ text := "📢 Важное обновление!\n\n" +
+ "Изменился ответственный за настройку системы согласований.\n\n" +
+ "Теперь по всем вопросам настройки обращайтесь к новому администратору:\n\n" +
+ "• Изменение порядка согласования\n" +
+ "• Добавление или удаление согласующих\n" +
+ "• Изменение прав доступа\n"
+
+ keyboard := tgbotapi.NewInlineKeyboardMarkup(
+ tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonURL("👨💻 Написать администратору", newSupportURL),
+ ),
+ )
+
+ for _, user := range users {
+ if user.TelegramID == nil {
+ continue
+ }
+ msg := tgbotapi.NewMessage(*user.TelegramID, text)
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard
+ msg.DisableWebPagePreview = true
+ if _, err := bot.Send(msg); err != nil {
+ logrus.Warnf("sendNewSupportContactNotification: Send to telegramID=%d err=%v", *user.TelegramID, err)
+ }
+ time.Sleep(50 * time.Millisecond)
+ }
+
+ logrus.Infof("sendNewSupportContactNotification: отправлено %d пользователям", len(users))
+}
+
+// broadcastCommentsFeatureUpdate уведомляет всех пользователей о новой функции комментариев.
+func (s *UpdateHandler) broadcastCommentsFeatureUpdate() {
+ ctx := context.Background()
+ bot := s.ipc.TGBotClient.Bot()
+
+ users, _, err := s.ipc.Database.User.GetUsersListDB(ctx, typescore.ListDbOptions{})
+ if err != nil {
+ logrus.Errorf("broadcastCommentsFeatureUpdate: GetUsersListDB err=%v", err)
+ return
+ }
+
+ text := "🆕 Что нового в системе согласований\n\n" +
+ "Мы обновили работу с комментариями - теперь заявка стала похожа на общий чат:\n\n" +
+ "💬 Комментарии видят все участники\n" +
+ "Инициатор, согласующий, доп. согласующие, исполнители(только после согласования) и наблюдатели(только после согласования) теперь получают комментарии друг друга и могут сразу ответить.\n\n" +
+ "📋 Кнопка «Посмотреть все комментарии» в каждой карточке\n" +
+ "На карточке заявки сразу видно, сколько комментариев уже оставлено - можно открыть полную историю в один клик.\n\n" +
+ "Нажмите кнопку ниже, чтобы перезапустить бота:"
+
+ keyboard := tgbotapi.NewInlineKeyboardMarkup(
+ tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData("🚀 Перезапустить бота", "restart_bot"),
+ ),
+ )
+
+ sent := 0
+ 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("broadcastCommentsFeatureUpdate: Send to telegramID=%d err=%v", *user.TelegramID, err)
+ continue
+ }
+ sent++
+ time.Sleep(50 * time.Millisecond)
+ }
+
+ logrus.Infof("broadcastCommentsFeatureUpdate: отправлено %d из %d пользователям", sent, len(users))
+}
diff --git a/service/telegram_service/common/update/callback.go b/service/telegram_service/common/update/callback.go
index d637a2c..3fe3d51 100644
--- a/service/telegram_service/common/update/callback.go
+++ b/service/telegram_service/common/update/callback.go
@@ -39,6 +39,22 @@ func (s *UpdateHandler) handleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.Callba
logrus.Infof("handleCallback: appr_stage approvalID=%d", approvalID)
s.approvalHandler.HandleApprovalStages(bot, cq, approvalID)
+ case data == "appr_deleg_yes":
+ s.approvalHandler.HandleDelegationChoiceCallback(bot, cq, true)
+
+ case data == "appr_deleg_no":
+ s.approvalHandler.HandleDelegationChoiceCallback(bot, cq, false)
+
+ case strings.HasPrefix(data, "appr_deleg_sel:"):
+ idStr := strings.TrimPrefix(data, "appr_deleg_sel:")
+ delegateID, _ := strconv.ParseUint(idStr, 10, 64)
+ s.approvalHandler.HandleDelegateSelectionCallback(bot, cq, delegateID)
+
+ case strings.HasPrefix(data, "appr_deleg_pg:"):
+ pageStr := strings.TrimPrefix(data, "appr_deleg_pg:")
+ page, _ := strconv.Atoi(pageStr)
+ s.approvalHandler.HandleDelegateSelectionPageCallback(bot, cq, page)
+
// Мультиселект кнопок
case strings.HasPrefix(data, "appr_ms_toggle:"):
parts := strings.SplitN(strings.TrimPrefix(data, "appr_ms_toggle:"), ":", 3)
@@ -58,10 +74,12 @@ func (s *UpdateHandler) handleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.Callba
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
+ commentsCount := s.approvalHandler.GetCommentsCount(ctx, approvalID)
+
// Возвращаем меню доработки
optMsg := tgbotapi.NewMessage(cq.Message.Chat.ID, fmt.Sprintf("📋 Заявка #%d на доработке:", approvalID))
optMsg.ParseMode = "HTML"
- optMsg.ReplyMarkup = keyboard.BuildRevisionOptions(approvalID)
+ optMsg.ReplyMarkup = keyboard.BuildRevisionOptions(approvalID, commentsCount)
bot.Send(optMsg) //nolint:errcheck
case strings.HasPrefix(data, "appr_revision:"):
@@ -293,6 +311,57 @@ func (s *UpdateHandler) handleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.Callba
case data == "deleg_page_noop":
bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ // ── УВЕДОМЛЕНИЯ ДИРЕКТОРА ─────────────────────────────────────
+ case strings.HasPrefix(data, "dir_notif_toggle:"):
+ parts := strings.Split(strings.TrimPrefix(data, "dir_notif_toggle:"), ":")
+ if len(parts) == 2 {
+ var categoryID uint64
+ var page int
+ fmt.Sscanf(parts[0], "%d", &categoryID)
+ fmt.Sscanf(parts[1], "%d", &page)
+ s.approvalHandler.HandleDirectorNotificationToggle(bot, cq, categoryID, page)
+ }
+
+ case strings.HasPrefix(data, "dir_notif_page:"):
+ page := 0
+ fmt.Sscanf(strings.TrimPrefix(data, "dir_notif_page:"), "%d", &page)
+ s.approvalHandler.HandleDirectorNotificationPage(bot, cq, page)
+
+ case data == "dir_notif_page_noop":
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+
+ case data == "dir_notif_done":
+ s.approvalHandler.HandleDirectorNotificationDone(bot, cq)
+
+ // ── ПЕРЕДАЧА ЗАДАЧ ──────────────────────────────────────────
+ case strings.HasPrefix(data, "task_transfer_start:"):
+ taskID := parseID(data, "task_transfer_start:")
+ s.approvalHandler.HandleTransferTaskStart(bot, cq, taskID)
+
+ case strings.HasPrefix(data, "task_transfer_page:"):
+ page := 0
+ fmt.Sscanf(strings.TrimPrefix(data, "task_transfer_page:"), "%d", &page)
+ s.approvalHandler.HandleTransferTaskUserPage(bot, cq, page)
+
+ case data == "task_transfer_noop":
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+
+ case data == "task_transfer_cancel":
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck
+
+ case strings.HasPrefix(data, "task_transfer_user:"):
+ toUserID := parseID(data, "task_transfer_user:")
+ s.approvalHandler.HandleTransferTaskUserSelect(bot, cq, toUserID)
+
+ case strings.HasPrefix(data, "task_transfer_accept:"):
+ transferID := parseID(data, "task_transfer_accept:")
+ s.approvalHandler.HandleTransferTaskAccept(bot, cq, transferID)
+
+ case strings.HasPrefix(data, "task_transfer_decline:"):
+ transferID := parseID(data, "task_transfer_decline:")
+ s.approvalHandler.HandleTransferTaskDecline(bot, cq, transferID)
+
// ── ДОБАВЛЕНИЕ СОГЛАСУЮЩЕГО ───────────────────────────────────────────────────
case strings.HasPrefix(data, "add_appr_category_page:"):
page := 0
@@ -391,6 +460,20 @@ func (s *UpdateHandler) handleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.Callba
s.suggestionHandler.HandleViewSuggestion(bot, cq, suggestionID)
// КОММЕНТАРИИ К СОГЛАСОВАНИЯМ
+ case strings.HasPrefix(data, "comment_vis:"):
+ action := strings.TrimPrefix(data, "comment_vis:")
+ s.approvalHandler.HandleCommentVisibilityCallback(bot, cq, action)
+
+ case strings.HasPrefix(data, "comment_tgt:"):
+ targetIDStr := strings.TrimPrefix(data, "comment_tgt:")
+ s.approvalHandler.HandleCommentTargetToggle(bot, cq, targetIDStr)
+
+ case data == "comment_tgt_done":
+ s.approvalHandler.HandleCommentTargetDone(bot, cq)
+
+ case data == "comment_tgt_back":
+ s.approvalHandler.HandleCommentTargetBack(bot, cq)
+
case strings.HasPrefix(data, "appr_comment:"):
approvalID := parseID(data, "appr_comment:")
s.approvalHandler.HandleAddCommentCallback(bot, cq, approvalID)
@@ -399,6 +482,10 @@ func (s *UpdateHandler) handleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.Callba
approvalID := parseID(data, "comment_reply:")
s.approvalHandler.HandleCommentReplyCallback(bot, cq, approvalID)
+ case strings.HasPrefix(data, "appr_view_comments:"):
+ approvalID := parseID(data, "appr_view_comments:")
+ s.approvalHandler.HandleViewCommentsCallback(bot, cq, approvalID)
+
// ВЫБОР СОГЛАСУЮЩЕГО
case strings.HasPrefix(data, "select_approver:"):
approverID := parseID(data, "select_approver:")
@@ -412,16 +499,38 @@ func (s *UpdateHandler) handleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.Callba
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, "appr_show_card:"):
+ approvalID := parseID(data, "appr_show_card:")
+ s.approvalHandler.HandleShowApprovalCardCallback(bot, cq, approvalID)
+
+ // ── СОГЛАСОВАНИЕ ОТЗЫВА ────────────────────────────────────
+ case strings.HasPrefix(data, "revoke_appr_yes:"):
+ requestID := parseID(data, "revoke_appr_yes:")
+ s.approvalHandler.HandleRevocationApproverDecision(bot, cq, requestID, true)
+
+ case strings.HasPrefix(data, "revoke_appr_no:"):
+ requestID := parseID(data, "revoke_appr_no:")
+ s.approvalHandler.HandleRevocationApproverDecision(bot, cq, requestID, false)
+
// Мои заявки
case strings.HasPrefix(data, "my_appr_topic:"):
topicFilter := strings.TrimPrefix(data, "my_appr_topic:")
s.approvalHandler.HandleMyApprovalsTopicCallback(bot, cq, topicFilter)
+ case data == "reminder_revisions":
+ s.approvalHandler.HandleReminderRevisions(bot, cq)
+
+ case data == "reminder_tasks":
+ s.approvalHandler.HandleMyTasks(bot, cq.Message.Chat.ID, cq.From.ID)
+
+ case data == "reminder_approvals":
+ s.approvalHandler.HandleReminderApprovals(bot, cq)
+
case strings.HasPrefix(data, "my_appr_status:"):
// формат: my_appr_status:{status}:{topicFilter}
parts := strings.SplitN(strings.TrimPrefix(data, "my_appr_status:"), ":", 2)
@@ -432,6 +541,20 @@ func (s *UpdateHandler) handleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.Callba
}
s.approvalHandler.HandleMyApprovalsStatusCallback(bot, cq, status, topicFilter)
+ case strings.HasPrefix(data, "obs_status:"):
+ parts := strings.SplitN(strings.TrimPrefix(data, "obs_status:"), ":", 3)
+ if len(parts) == 3 {
+ status := parts[0]
+ topicCode := parts[1]
+ page, _ := strconv.Atoi(parts[2])
+ s.approvalHandler.HandleObserverStatusFilterCallback(bot, cq, status, topicCode, page)
+ }
+
+ case data == "obs_back_list":
+ s.approvalHandler.HandleObservedApprovals(bot, cq.Message.Chat.ID, cq.From.ID)
+ bot.Request(tgbotapi.NewCallback(cq.ID, ""))
+ bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID))
+
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
@@ -453,6 +576,9 @@ func (s *UpdateHandler) handleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.Callba
case data == "appr_appr_back":
s.approvalHandler.HandleApproverApprovals(bot, cq.Message.Chat.ID, cq.From.ID)
+ case data == "deleg_task_all":
+ s.approvalHandler.HandleTaskDelegationAllTasks(bot, cq)
+
case strings.HasPrefix(data, "obs_topic_page:"):
page := 0
fmt.Sscanf(strings.TrimPrefix(data, "obs_topic_page:"), "%d", &page)
@@ -521,6 +647,117 @@ func (s *UpdateHandler) handleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.Callba
case strings.HasPrefix(data, "attach_cancel:"):
s.approvalHandler.HandleAttachCancel(bot, cq)
+ // ── ФЛОУ ДЕЛЕГИРОВАНИЯ ЗАДАЧ ──────────────────────────────────────────
+ case data == "deleg_main_menu":
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck
+ s.approvalHandler.HandleDelegationMainMenu(bot, cq.Message.Chat.ID, cq.From.ID)
+
+ case data == "deleg_task_create":
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck
+ s.approvalHandler.HandleTaskDelegationMenu(bot, cq.Message.Chat.ID, cq.From.ID)
+
+ case strings.HasPrefix(data, "deleg_task_user_page:"):
+ parts := strings.Split(strings.TrimPrefix(data, "deleg_task_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.HandleTaskDelegationSelectUserPage(bot, cq, categoryID, topicID, int(page))
+ }
+
+ case strings.HasPrefix(data, "deleg_task_user:"):
+ delegateID := parseID(data, "deleg_task_user:")
+ s.approvalHandler.HandleTaskDelegationUserCallback(bot, cq, delegateID)
+
+ case data == "deleg_task_list":
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck
+ s.approvalHandler.HandleTaskDelegatedRightsList(bot, cq.Message.Chat.ID, cq.From.ID)
+
+ case strings.HasPrefix(data, "deleg_task_list_page:"):
+ page := 0
+ fmt.Sscanf(strings.TrimPrefix(data, "deleg_task_list_page:"), "%d", &page)
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ s.approvalHandler.HandleTaskDelegatedRightsListPage(bot, cq.Message.Chat.ID, cq.From.ID, page, cq.Message.MessageID)
+
+ case strings.HasPrefix(data, "deleg_task_detail:"):
+ delegationID := parseID(data, "deleg_task_detail:")
+ s.approvalHandler.HandleTaskDelegatedRightDetail(bot, cq, delegationID)
+
+ case strings.HasPrefix(data, "deleg_task_revoke:"):
+ delegationID := parseID(data, "deleg_task_revoke:")
+ s.approvalHandler.HandleTaskDelegationRevoke(bot, cq, delegationID)
+
+ case strings.HasPrefix(data, "deleg_task_extend:"):
+ delegationID := parseID(data, "deleg_task_extend:")
+ s.approvalHandler.HandleTaskDelegationExtendPrompt(bot, cq, delegationID)
+
+ case data == "appr_task_deleg_yes":
+ s.approvalHandler.HandleTaskDelegationChoiceAbsence(bot, cq, true)
+ case data == "appr_task_deleg_no":
+ s.approvalHandler.HandleTaskDelegationChoiceAbsence(bot, cq, false)
+ case strings.HasPrefix(data, "appr_task_deleg_sel:"):
+ id := parseID(data, "appr_task_deleg_sel:")
+ s.approvalHandler.HandleTaskDelegateSelectionAbsence(bot, cq, id)
+
+ case strings.HasPrefix(data, "appr_task_deleg_sel:"):
+ id := parseID(data, "appr_task_deleg_sel:")
+ s.approvalHandler.HandleTaskDelegateSelectionAbsence(bot, cq, id)
+
+ case strings.HasPrefix(data, "appr_task_deleg_pg:"):
+ page := 0
+ fmt.Sscanf(strings.TrimPrefix(data, "appr_task_deleg_pg:"), "%d", &page)
+ s.approvalHandler.HandleTaskDelegateSelectionPageAbsence(bot, cq, page)
+
+ // ── ФЛОУ ДЕЛЕГИРОВАНИЯ ЗАДАЧ ──────────────────────────────────────────
+ case strings.HasPrefix(data, "deleg_task_cat_page:"):
+ page := 0
+ fmt.Sscanf(strings.TrimPrefix(data, "deleg_task_cat_page:"), "%d", &page)
+ s.approvalHandler.HandleTaskDelegationMenuPage(bot, cq.Message.Chat.ID, cq.From.ID, page, cq.Message.MessageID)
+
+ case strings.HasPrefix(data, "deleg_task_category:"):
+ categoryID := parseID(data, "deleg_task_category:")
+ s.approvalHandler.HandleTaskDelegationCategoryCallback(bot, cq, categoryID)
+
+ case strings.HasPrefix(data, "deleg_task_all_cat:"):
+ categoryID := parseID(data, "deleg_task_all_cat:")
+ s.approvalHandler.HandleTaskDelegationAllCategoryCallback(bot, cq, categoryID)
+
+ case strings.HasPrefix(data, "deleg_task_top_page:"):
+ parts := strings.Split(strings.TrimPrefix(data, "deleg_task_top_page:"), ":")
+ if len(parts) == 2 {
+ var categoryID, page uint64
+ fmt.Sscanf(parts[0], "%d", &categoryID)
+ fmt.Sscanf(parts[1], "%d", &page)
+ s.approvalHandler.HandleTaskDelegationCategoryCallbackPage(bot, cq, categoryID, int(page))
+ }
+
+ case strings.HasPrefix(data, "deleg_task_topic:"):
+ topicID := parseID(data, "deleg_task_topic:")
+ s.approvalHandler.HandleTaskDelegationTopicCallback(bot, cq, topicID)
+
+ case strings.HasPrefix(data, "deleg_task_user_page:"):
+ parts := strings.Split(strings.TrimPrefix(data, "deleg_task_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.HandleTaskDelegationSelectUserPage(bot, cq, categoryID, topicID, int(page))
+ }
+
+ case strings.HasPrefix(data, "deleg_task_user:"):
+ delegateID := parseID(data, "deleg_task_user:")
+ s.approvalHandler.HandleTaskDelegationUserCallback(bot, cq, delegateID)
+
// ── ПРОЧЕЕ ──────────────────────────────────────────────────
case data == "restart_bot":
bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
diff --git a/service/telegram_service/common/update/update.go b/service/telegram_service/common/update/update.go
index 0148d32..7a4a1a1 100644
--- a/service/telegram_service/common/update/update.go
+++ b/service/telegram_service/common/update/update.go
@@ -68,6 +68,27 @@ func (s *UpdateHandler) handleMessage(bot *tgbotapi.BotAPI, msg *tgbotapi.Messag
})
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
+ }
+ isDirector, _ := s.ipc.Database.User.IsDirectorDB(ctx, *user.ID)
+ if !isDirector {
+ return
+ }
+ s.approvalHandler.HandleDirectorSubmenu(bot, msg.Chat.ID)
+ })
+ return
+
+ case "🔔 Настроить уведомления":
+ s.withDepartmentCheck(bot, msg, func() {
+ s.approvalHandler.HandleDirectorNotificationSettings(bot, msg.Chat.ID, msg.From.ID)
+ })
+ return
+
case "👁 Наблюдатель":
s.withDepartmentCheck(bot, msg, func() {
ctx := context.Background()
@@ -232,6 +253,14 @@ func (s *UpdateHandler) handleMessage(bot *tgbotapi.BotAPI, msg *tgbotapi.Messag
if s.approvalHandler.HandleDelegationExtendInput(bot, msg) {
return
}
+ // Перехват ввода даты для создания делегирования задач
+ if s.approvalHandler.HandleTaskDelegationDateInput(bot, msg) {
+ return
+ }
+ // Перехват ввода даты для продления делегирования задач
+ if s.approvalHandler.HandleTaskDelegationExtendInput(bot, msg) {
+ return
+ }
s.withDepartmentCheck(bot, msg, func() {
s.approvalHandler.HandleTextInput(bot, msg)
diff --git a/service/telegram_service/handlers/approval/absense_delegation.go b/service/telegram_service/handlers/approval/absense_delegation.go
new file mode 100644
index 0000000..841d14d
--- /dev/null
+++ b/service/telegram_service/handlers/approval/absense_delegation.go
@@ -0,0 +1,519 @@
+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"
+ "regexp"
+ "sort"
+ "strconv"
+ "strings"
+ "time"
+
+ tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
+ "github.com/sirupsen/logrus"
+)
+
+func (h *Handler) showDelegationChoice(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) {
+ text := "🔁 Шаг 1/2: Делегирование ЗАЯВОК\n\n" +
+ "Делегировать ваши права как согласующего по заявкам на время вашего отсутствия?"
+
+ msg := tgbotapi.NewMessage(chatID, text)
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildDelegationChoiceMenu()
+ bot.Send(msg) //nolint:errcheck
+}
+
+func (h *Handler) HandleDelegationChoiceCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, wantsDelegate bool) {
+ 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 || !flowState.AwaitDelegationChoice {
+ return
+ }
+
+ if !wantsDelegate {
+ flowState.DelegationSelectionDone = true
+ sendText(bot, chatID, "☑️ Хорошо — права по заявкам не делегируются.")
+ h.showTaskDelegationChoice(bot, chatID, telegramID, flowState)
+ return
+ }
+
+ candidates, err := h.getAvailableDelegateCandidates(ctx, telegramID)
+ if err != nil || len(candidates) == 0 {
+ sendText(bot, chatID, "⚠️ Нет доступных сотрудников для делегирования. Права остаются на вас.")
+ flowState.DelegationSelectionDone = true
+ h.showTaskDelegationChoice(bot, chatID, telegramID, flowState)
+ return
+ }
+
+ flowState.AwaitDelegationChoice = false
+ flowState.AwaitDelegateSelection = true
+ h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
+
+ msg := tgbotapi.NewMessage(chatID, "👤 Кому передать права по заявкам:")
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildDelegateSelectionMenu(candidates, 0)
+ bot.Send(msg) //nolint:errcheck
+}
+
+func (h *Handler) HandleDelegateSelectionPageCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, page int) {
+ ctx := context.Background()
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+
+ candidates, _ := h.getAvailableDelegateCandidates(ctx, cq.From.ID)
+ bot.Request(tgbotapi.NewEditMessageReplyMarkup(
+ cq.Message.Chat.ID,
+ cq.Message.MessageID,
+ keyboard.BuildDelegateSelectionMenu(candidates, page),
+ )) //nolint:errcheck
+}
+
+func (h *Handler) HandleDelegateSelectionCallback(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
+
+ flowState, err := h.States.Get(ctx, telegramID)
+ if err != nil || flowState == nil || !flowState.AwaitDelegateSelection {
+ return
+ }
+
+ delegate, _ := h.ipc.Database.User.GetUserByIDDB(ctx, delegateID)
+ delegateName := "—"
+ if delegate != nil && delegate.FullName != nil {
+ delegateName = *delegate.FullName
+ }
+
+ flowState.DelegationSelectionDone = true
+ flowState.SelectedDelegateID = delegateID
+
+ sendText(bot, chatID, fmt.Sprintf("🔁 Права по заявкам будут делегированы: %s", delegateName))
+
+ h.showTaskDelegationChoice(bot, chatID, telegramID, flowState)
+}
+
+// ============================================================
+// Делегирование ЗАДАЧ на время отсутствия (НОВЫЙ БЛОК)
+// ============================================================
+
+func (h *Handler) showTaskDelegationChoice(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, flowState *state.ApprovalFlowState) {
+ ctx := context.Background()
+ flowState.AwaitDelegationChoice = false
+ flowState.AwaitDelegateSelection = false
+ flowState.AwaitTaskDelegationChoice = true
+ h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
+
+ text := "🔁 Шаг 2/2: Делегирование ЗАДАЧ\n\n" +
+ "Хотите также передать исполнение ваших задач другому сотруднику на время отсутствия?\n\n" +
+ "Делегирование (и заявок, и задач) вступит в силу автоматически после согласования отпуска."
+
+ msg := tgbotapi.NewMessage(chatID, text)
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildTaskDelegationChoiceMenu() // Кнопки appr_task_deleg_yes / no
+ bot.Send(msg) //nolint:errcheck
+}
+
+func (h *Handler) HandleTaskDelegationChoiceAbsence(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, wantsDelegate bool) {
+ 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 || !flowState.AwaitTaskDelegationChoice {
+ return
+ }
+
+ if !wantsDelegate {
+ flowState.TaskDelegationSelectionDone = true
+ flowState.AwaitTaskDelegationChoice = false
+ h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
+
+ sendText(bot, chatID, "☑️ Хорошо — задачи не делегируются.")
+ h.continueFlowAfterInput(bot, ctx, chatID, telegramID, flowState)
+ return
+ }
+
+ candidates, err := h.getAvailableDelegateCandidates(ctx, telegramID)
+ if err != nil || len(candidates) == 0 {
+ sendText(bot, chatID, "⚠️ Нет доступных сотрудников для делегирования. Задачи остаются на вас.")
+ flowState.TaskDelegationSelectionDone = true
+ flowState.AwaitTaskDelegationChoice = false
+ h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
+ h.continueFlowAfterInput(bot, ctx, chatID, telegramID, flowState)
+ return
+ }
+
+ flowState.AwaitTaskDelegationChoice = false
+ flowState.AwaitTaskDelegateSelection = true
+ h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
+
+ msg := tgbotapi.NewMessage(chatID, "👤 Кому передать исполнение задач:")
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildAbsenceTaskDelegateMenu(candidates, 0)
+ bot.Send(msg) //nolint:errcheck
+}
+
+func (h *Handler) HandleTaskDelegateSelectionAbsence(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
+
+ flowState, err := h.States.Get(ctx, telegramID)
+ if err != nil || flowState == nil || !flowState.AwaitTaskDelegateSelection {
+ return
+ }
+
+ delegate, _ := h.ipc.Database.User.GetUserByIDDB(ctx, delegateID)
+ delegateName := "—"
+ if delegate != nil && delegate.FullName != nil {
+ delegateName = *delegate.FullName
+ }
+
+ flowState.TaskDelegationSelectionDone = true
+ flowState.AwaitTaskDelegateSelection = false
+ flowState.SelectedTaskDelegateID = delegateID
+ h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
+
+ sendText(bot, chatID, fmt.Sprintf("🔁 Исполнение задач будет делегировано: %s", delegateName))
+
+ h.continueFlowAfterInput(bot, ctx, chatID, telegramID, flowState)
+}
+
+// ============================================================
+// Вспомогательные методы и логика БД
+// ============================================================
+
+// getAvailableDelegateCandidates возвращает список активных сотрудников,
+// ОТСОРТИРОВАННЫХ ПО АЛФАВИТУ.
+func (h *Handler) getAvailableDelegateCandidates(ctx context.Context, telegramID int64) ([]*typescore.User, error) {
+ me, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
+ if err != nil || me == nil || me.ID == nil {
+ return nil, err
+ }
+
+ users, _, err := h.ipc.Database.User.GetUsersListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.User{IsBlocked: utilscore.PointerToBool(false)},
+ Limit: utilscore.PointerToUint64(1000), // На случай большого штата
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ var result []*typescore.User
+ for _, u := range users {
+ if u.ID == nil || *u.ID == *me.ID || u.TelegramID == nil {
+ continue
+ }
+ if u.IsFired != nil && *u.IsFired {
+ continue
+ }
+ result = append(result, u)
+ }
+
+ // 🚀 Сортировка списка по алфавиту (по FullName)
+ sort.Slice(result, func(i, j int) bool {
+ nameI, nameJ := "", ""
+ if result[i].FullName != nil {
+ nameI = *result[i].FullName
+ }
+ if result[j].FullName != nil {
+ nameJ = *result[j].FullName
+ }
+ return nameI < nameJ
+ })
+
+ return result, nil
+}
+
+func (h *Handler) createPendingDelegation(ctx context.Context, initiator *typescore.User, flowState *state.ApprovalFlowState, approval *typescore.Approval) {
+ if initiator == nil || initiator.ID == nil || approval == nil || approval.ID == nil {
+ return
+ }
+
+ validUntil, datesFound := delegationValidUntil(flowState.Collected)
+ if !datesFound {
+ logrus.Warnf("createPendingDelegation: дата окончания не найдена approvalID=%d", *approval.ID)
+ }
+
+ inactive := false
+ notifiedFalse := false
+
+ // 1. Создаем отложенное делегирование ЗАЯВОК (только по тем категориям, где инициатор — согласующий)
+ if flowState.SelectedDelegateID != 0 {
+ // Получаем реальные категории, где этот пользователь является согласующим
+ approverCategories, err := h.getApproverCategories(ctx, *initiator.ID)
+ if err == nil {
+ for _, cat := range approverCategories {
+ if cat == nil || cat.ID == nil {
+ continue
+ }
+ catID := *cat.ID
+ delegation := &typescore.ApprovalDelegation{
+ DelegatorID: initiator.ID,
+ DelegateID: &flowState.SelectedDelegateID,
+ CategoryID: &catID,
+ ApprovalID: approval.ID,
+ ValidUntil: &validUntil,
+ IsActive: &inactive,
+ NotifiedDay: ¬ifiedFalse,
+ Notified2h: ¬ifiedFalse,
+ }
+ h.ipc.Database.ApprovalDelegation.CreateApprovalDelegationDB(ctx, nil, delegation) //nolint:errcheck
+ }
+ }
+ }
+
+ // 2. Создаем отложенное делегирование ЗАДАЧ
+ if flowState.SelectedTaskDelegateID != 0 {
+ taskDelegation := &typescore.TaskDelegation{
+ DelegatorID: initiator.ID,
+ DelegateID: &flowState.SelectedTaskDelegateID,
+ ApprovalID: approval.ID,
+ ValidUntil: &validUntil,
+ IsActive: &inactive,
+ NotifiedDay: ¬ifiedFalse,
+ Notified2h: ¬ifiedFalse,
+ }
+ h.ipc.Database.TaskDelegation.CreateTaskDelegationDB(ctx, nil, taskDelegation) //nolint:errcheck
+ }
+}
+
+func (h *Handler) activatePendingDelegation(bot *tgbotapi.BotAPI, ctx context.Context, approval *typescore.Approval) {
+ if approval == nil || approval.ID == nil {
+ return
+ }
+
+ initiatorName := "Сотрудник"
+ if approval.InitiatorID != nil {
+ if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID); u != nil && u.FullName != nil {
+ initiatorName = *u.FullName
+ }
+ }
+
+ active := true
+
+ apprDelegations, _, _ := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalDelegation{ApprovalID: approval.ID},
+ })
+
+ delegateCategories := make(map[uint64]map[string]struct{})
+ delegateValidUntil := make(map[uint64]string)
+
+ for _, d := range apprDelegations {
+ d.IsActive = &active
+ h.ipc.Database.ApprovalDelegation.UpdateApprovalDelegationDB(ctx, nil, d) //nolint:errcheck
+
+ if d.DelegateID != nil {
+ if delegateCategories[*d.DelegateID] == nil {
+ delegateCategories[*d.DelegateID] = make(map[string]struct{})
+ }
+
+ scopeName := "Неизвестная категория"
+ if d.TopicID != nil {
+ topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *d.TopicID)
+ if topic != nil && topic.Name != nil {
+ scopeName = *topic.Name
+ }
+ } else if d.CategoryID != nil {
+ category, _ := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *d.CategoryID)
+ if category != nil && category.Name != nil {
+ scopeName = *category.Name
+ }
+ }
+
+ delegateCategories[*d.DelegateID][scopeName] = struct{}{}
+
+ if d.ValidUntil != nil {
+ delegateValidUntil[*d.DelegateID] = d.ValidUntil.Format("02.01.2006")
+ } else if delegateValidUntil[*d.DelegateID] == "" {
+ delegateValidUntil[*d.DelegateID] = "—"
+ }
+ }
+ }
+
+ for delegateID, categoriesMap := range delegateCategories {
+ delegateUser, _ := h.ipc.Database.User.GetUserByIDDB(ctx, delegateID)
+ if delegateUser != nil && delegateUser.TelegramID != nil {
+ var catNames []string
+ for catName := range categoriesMap {
+ catNames = append(catNames, "• "+catName)
+ }
+
+ catListStr := strings.Join(catNames, "\n")
+ validStr := delegateValidUntil[delegateID]
+
+ msg := tgbotapi.NewMessage(*delegateUser.TelegramID, fmt.Sprintf(
+ "🔄 Вам делегированы права согласования заявок\n\n"+
+ "👤 От кого: %s\n"+
+ "📅 Действует до: %s\n\n"+
+ "📋 Переданные категории:\n%s\n\n"+
+ "Заявка на отсутствие сотрудника согласована, делегирование вступило в силу.",
+ initiatorName, validStr, catListStr,
+ ))
+ msg.ParseMode = "HTML"
+ bot.Send(msg) //nolint:errcheck
+ }
+ }
+
+ // ==========================================
+ // 2. Активируем задачи и собираем их области (Категории/Темы)
+ // ==========================================
+ taskDelegations, _, _ := h.ipc.Database.TaskDelegation.GetTaskDelegationsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.TaskDelegation{ApprovalID: approval.ID},
+ })
+
+ taskDelegateScopes := make(map[uint64]map[string]struct{})
+ taskDelegateValidUntil := make(map[uint64]string)
+
+ for _, td := range taskDelegations {
+ td.IsActive = &active
+ h.ipc.Database.TaskDelegation.UpdateTaskDelegationDB(ctx, nil, td) //nolint:errcheck
+
+ if td.DelegateID != nil {
+ if taskDelegateScopes[*td.DelegateID] == nil {
+ taskDelegateScopes[*td.DelegateID] = make(map[string]struct{})
+ }
+
+ scopeName := "🌍 Все задачи (Глобально)"
+ if td.TopicID != nil {
+ if topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *td.TopicID); topic != nil && topic.Name != nil {
+ scopeName = "Тема: " + *topic.Name
+ }
+ } else if td.CategoryID != nil {
+ if category, _ := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *td.CategoryID); category != nil && category.Name != nil {
+ scopeName = "Категория: " + *category.Name
+ }
+ }
+
+ taskDelegateScopes[*td.DelegateID][scopeName] = struct{}{}
+
+ if td.ValidUntil != nil {
+ taskDelegateValidUntil[*td.DelegateID] = td.ValidUntil.Format("02.01.2006")
+ } else if taskDelegateValidUntil[*td.DelegateID] == "" {
+ taskDelegateValidUntil[*td.DelegateID] = "—"
+ }
+ }
+ }
+
+ // Рассылаем детальные уведомления по задачам
+ for delegateID, scopesMap := range taskDelegateScopes {
+ delegateUser, _ := h.ipc.Database.User.GetUserByIDDB(ctx, delegateID)
+ if delegateUser != nil && delegateUser.TelegramID != nil {
+ var scopeNames []string
+ for scopeName := range scopesMap {
+ scopeNames = append(scopeNames, "• "+scopeName)
+ }
+
+ scopeListStr := strings.Join(scopeNames, "\n")
+ validStr := taskDelegateValidUntil[delegateID]
+
+ msg := tgbotapi.NewMessage(*delegateUser.TelegramID, fmt.Sprintf(
+ "🔄 Вам делегировано исполнение задач\n\n"+
+ "👤 От кого: %s\n"+
+ "📅 Действует до: %s\n\n"+
+ "📋 Переданные области задач:\n%s\n\n"+
+ "Заявка на отсутствие сотрудника согласована, делегирование вступило в силу.",
+ initiatorName, validStr, scopeListStr,
+ ))
+ msg.ParseMode = "HTML"
+ bot.Send(msg) //nolint:errcheck
+ }
+ }
+}
+
+func (h *Handler) deactivatePendingDelegation(ctx context.Context, approval *typescore.Approval) {
+ if approval == nil || approval.ID == nil {
+ return
+ }
+ inactive := false
+
+ // Деактивируем заявки
+ apprDelegations, _, _ := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalDelegation{ApprovalID: approval.ID},
+ })
+ for _, d := range apprDelegations {
+ d.IsActive = &inactive
+ h.ipc.Database.ApprovalDelegation.UpdateApprovalDelegationDB(ctx, nil, d) //nolint:errcheck
+ }
+
+ // Деактивируем задачи
+ taskDelegations, _, _ := h.ipc.Database.TaskDelegation.GetTaskDelegationsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.TaskDelegation{ApprovalID: approval.ID},
+ })
+ for _, td := range taskDelegations {
+ td.IsActive = &inactive
+ h.ipc.Database.TaskDelegation.UpdateTaskDelegationDB(ctx, nil, td) //nolint:errcheck
+ }
+}
+
+var delegationDateRe = regexp.MustCompile(`(\d{1,2})[.,](\d{1,2})\.(\d{4})`)
+
+func delegationValidUntil(collected map[string]string) (time.Time, bool) {
+ var dates []time.Time
+ for _, v := range collected {
+ matches := delegationDateRe.FindAllStringSubmatch(v, -1)
+ for _, m := range matches {
+ day, errD := strconv.Atoi(m[1])
+ month, errM := strconv.Atoi(m[2])
+ year, errY := strconv.Atoi(m[3])
+ if errD != nil || errM != nil || errY != nil {
+ continue
+ }
+ if month < 1 || month > 12 || day < 1 || day > 31 {
+ continue
+ }
+ dates = append(dates, time.Date(year, time.Month(month), day, 23, 59, 59, 0, time.UTC))
+ }
+ }
+
+ if len(dates) == 0 {
+ return time.Now().AddDate(0, 0, 30), false
+ }
+
+ maxDate := dates[0]
+ for _, d := range dates[1:] {
+ if d.After(maxDate) {
+ maxDate = d
+ }
+ }
+ return maxDate, true
+}
+
+// HandleTaskDelegateSelectionPageAbsence — пагинация списка кандидатов для делегирования задач (отпуск)
+func (h *Handler) HandleTaskDelegateSelectionPageAbsence(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, page int) {
+ ctx := context.Background()
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+
+ flowState, err := h.States.Get(ctx, cq.From.ID)
+ if err != nil || flowState == nil || !flowState.AwaitTaskDelegateSelection {
+ return
+ }
+
+ candidates, _ := h.getAvailableDelegateCandidates(ctx, cq.From.ID)
+
+ editMsg := tgbotapi.NewEditMessageReplyMarkup(
+ cq.Message.Chat.ID,
+ cq.Message.MessageID,
+ // Убедитесь, что эта функция у вас возвращает tgbotapi.InlineKeyboardMarkup
+ keyboard.BuildAbsenceTaskDelegateMenu(candidates, page).(tgbotapi.InlineKeyboardMarkup),
+ )
+ bot.Request(editMsg) //nolint:errcheck
+}
diff --git a/service/telegram_service/handlers/approval/approval_revocation.go b/service/telegram_service/handlers/approval/approval_revocation.go
new file mode 100644
index 0000000..c7a78c4
--- /dev/null
+++ b/service/telegram_service/handlers/approval/approval_revocation.go
@@ -0,0 +1,271 @@
+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"
+)
+
+// getDistinctApprovedApproverIDs — все, кто реально одобрил хотя бы один шаг этой заявки.
+func (h *Handler) getDistinctApprovedApproverIDs(ctx context.Context, approvalID uint64) []uint64 {
+ steps, _, err := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalStep{ApprovalID: &approvalID},
+ })
+ if err != nil {
+ return nil
+ }
+
+ seen := make(map[uint64]bool)
+ var ids []uint64
+ for _, s := range steps {
+ if s.Status == nil || *s.Status != "approved" || s.ApproverID == nil {
+ continue
+ }
+ if !seen[*s.ApproverID] {
+ seen[*s.ApproverID] = true
+ ids = append(ids, *s.ApproverID)
+ }
+ }
+ return ids
+}
+
+// startApprovalRevocationRequest создаёт запрос на отзыв уже согласованной заявки
+// и рассылает его всем, кто участвовал в согласовании, для получения их согласия.
+func (h *Handler) startApprovalRevocationRequest(
+ bot *tgbotapi.BotAPI,
+ chatID int64,
+ approval *typescore.Approval,
+ initiator *typescore.User,
+ comment string,
+) {
+ ctx := context.Background()
+ approvalID := *approval.ID
+
+ if existing, _ := h.ipc.Database.ApprovalRevocation.GetPendingRevocationRequestForApprovalDB(ctx, approvalID); existing != nil {
+ sendText(bot, chatID, "⚠️ По этой заявке уже есть ожидающий рассмотрения запрос на отзыв.")
+ return
+ }
+
+ approverIDs := h.getDistinctApprovedApproverIDs(ctx, approvalID)
+ if len(approverIDs) == 0 {
+ // Заявку никто не одобрял (странный случай, но не блокируем инициатора навсегда)
+ h.HandleRevokeWithComment(bot, chatID, *initiator.TelegramID, approvalID, comment)
+ return
+ }
+
+ pendingStatus := "pending"
+ var reasonPtr *string
+ if comment != "" {
+ reasonPtr = &comment
+ }
+
+ request := &typescore.ApprovalRevocationRequest{
+ ApprovalID: &approvalID,
+ RequestedByID: initiator.ID,
+ Reason: reasonPtr,
+ Status: &pendingStatus,
+ }
+ created, err := h.ipc.Database.ApprovalRevocation.CreateRevocationRequestDB(ctx, request, true)
+ if err != nil || created == nil || created.ID == nil {
+ logrus.Errorf("startApprovalRevocationRequest: CreateRevocationRequestDB err=%v", err)
+ sendText(bot, chatID, "⚠️ Ошибка при создании запроса на отзыв.")
+ return
+ }
+
+ var approvers []*typescore.ApprovalRevocationApprover
+ for _, id := range approverIDs {
+ id := id
+ approvers = append(approvers, &typescore.ApprovalRevocationApprover{
+ RevocationRequestID: created.ID,
+ ApproverID: &id,
+ Status: &pendingStatus,
+ })
+ }
+ if err := h.ipc.Database.ApprovalRevocation.CreateRevocationApproversDB(ctx, approvers); err != nil {
+ logrus.Errorf("startApprovalRevocationRequest: CreateRevocationApproversDB err=%v", err)
+ sendText(bot, chatID, "⚠️ Ошибка при создании списка согласующих.")
+ return
+ }
+
+ initiatorName := "—"
+ if initiator.FullName != nil {
+ initiatorName = *initiator.FullName
+ }
+ topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID)
+ content := "—"
+ if approval.Content != nil {
+ content = *approval.Content
+ }
+ reasonLine := ""
+ if comment != "" {
+ reasonLine = fmt.Sprintf("\n💬 Причина: %s", comment)
+ }
+
+ notifyText := fmt.Sprintf(
+ "⚠️ Запрос на отзыв согласованной заявки #%d\n\n"+
+ "👤 Инициатор: %s\n"+
+ "📋 Тема: %s\n"+
+ "📝 Текст: %s%s\n\n"+
+ "Требуется согласие всех, кто участвовал в согласовании. Ваше решение:",
+ approvalID, initiatorName, topicFullName, content, reasonLine,
+ )
+
+ for _, id := range approverIDs {
+ approver, err := h.ipc.Database.User.GetUserByIDDB(ctx, id)
+ if err != nil || approver == nil || approver.TelegramID == nil {
+ continue
+ }
+ msg := tgbotapi.NewMessage(*approver.TelegramID, notifyText)
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildRevocationApprovalDecision(approvalID, *created.ID, h.GetCommentsCount(ctx, approvalID))
+ bot.Send(msg) //nolint:errcheck
+ }
+
+ sendText(bot, chatID, fmt.Sprintf(
+ "📤 Запрос на отзыв заявки #%d отправлен\n\n"+
+ "Ожидаем согласия от всех согласующих (%d чел.). Заявка будет отозвана только после единодушного согласия.",
+ approvalID, len(approverIDs),
+ ))
+}
+
+// HandleRevocationApproverDecision — согласующий дал ответ на запрос отзыва.
+func (h *Handler) HandleRevocationApproverDecision(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, requestID uint64, approved bool) {
+ 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
+
+ user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, cq.From.ID)
+ if err != nil || user == nil || user.ID == nil {
+ return
+ }
+
+ request, err := h.ipc.Database.ApprovalRevocation.GetRevocationRequestByIDDB(ctx, requestID)
+ if err != nil || request == nil {
+ sendText(bot, chatID, "⚠️ Запрос не найден.")
+ return
+ }
+ if request.Status == nil || *request.Status != "pending" {
+ sendText(bot, chatID, "⚠️ Этот запрос уже обработан.")
+ return
+ }
+
+ approverRecord, err := h.ipc.Database.ApprovalRevocation.GetRevocationApproverForUserDB(ctx, requestID, *user.ID)
+ if err != nil || approverRecord == nil {
+ sendText(bot, chatID, "⚠️ Вы не являетесь участником этого согласования.")
+ return
+ }
+ if approverRecord.Status == nil || *approverRecord.Status != "pending" {
+ sendText(bot, chatID, "⚠️ Вы уже дали ответ на этот запрос.")
+ return
+ }
+
+ now := time.Now()
+ newStatus := "approved"
+ if !approved {
+ newStatus = "rejected"
+ }
+ approverRecord.Status = &newStatus
+ approverRecord.ActedAt = &now
+ if err := h.ipc.Database.ApprovalRevocation.UpdateRevocationApproverDB(ctx, approverRecord); err != nil {
+ logrus.Errorf("HandleRevocationApproverDecision: UpdateRevocationApproverDB err=%v", err)
+ return
+ }
+
+ responderName := "—"
+ if user.FullName != nil {
+ responderName = *user.FullName
+ }
+
+ if !approved {
+ // Один отказ — отклоняем весь запрос сразу
+ rejectedStatus := "rejected"
+ request.Status = &rejectedStatus
+ h.ipc.Database.ApprovalRevocation.UpdateRevocationRequestDB(ctx, request) //nolint:errcheck
+
+ sendText(bot, chatID, fmt.Sprintf("❌ Вы отклонили отзыв заявки #%d.", *request.ApprovalID))
+ h.notifyRevocationRequestClosed(bot, ctx, request, false, responderName)
+ return
+ }
+
+ sendText(bot, chatID, fmt.Sprintf("✅ Вы согласились на отзыв заявки #%d.", *request.ApprovalID))
+
+ // Проверяем, все ли уже согласились
+ allApprovers, err := h.ipc.Database.ApprovalRevocation.GetRevocationApproversByRequestIDDB(ctx, requestID)
+ if err != nil {
+ return
+ }
+ allApproved := true
+ for _, a := range allApprovers {
+ if a.Status == nil || *a.Status != "approved" {
+ allApproved = false
+ break
+ }
+ }
+
+ if !allApproved {
+ return
+ }
+
+ approvedStatus := "approved"
+ request.Status = &approvedStatus
+ if _, err := h.ipc.Database.ApprovalRevocation.UpdateRevocationRequestDB(ctx, request); err != nil {
+ logrus.Errorf("HandleRevocationApproverDecision: UpdateRevocationRequestDB err=%v", err)
+ return
+ }
+
+ // Все согласились — выполняем фактический отзыв
+ approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, *request.ApprovalID)
+ if err != nil || approval == nil || request.RequestedByID == nil {
+ return
+ }
+ initiator, err := h.ipc.Database.User.GetUserByIDDB(ctx, *request.RequestedByID)
+ if err != nil || initiator == nil || initiator.TelegramID == nil {
+ return
+ }
+
+ reason := ""
+ if request.Reason != nil {
+ reason = *request.Reason
+ }
+
+ // В этой ветке отзывающий — инициатор (запрос был именно от него),
+ // isDirectorRevoking всегда false, т.к. в этот путь директор не попадает
+ steps, _, _ := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalStep{ApprovalID: request.ApprovalID},
+ })
+
+ h.performActualRevoke(bot, ctx, approval, initiator, "инициатором", reason, steps, true, false)
+ h.notifyRevocationRequestClosed(bot, ctx, request, true, "")
+}
+
+// notifyRevocationRequestClosed уведомляет инициатора об итоге запроса на отзыв.
+func (h *Handler) notifyRevocationRequestClosed(bot *tgbotapi.BotAPI, ctx context.Context, request *typescore.ApprovalRevocationRequest, approved bool, rejectorName string) {
+ if request.RequestedByID == nil {
+ return
+ }
+ initiator, err := h.ipc.Database.User.GetUserByIDDB(ctx, *request.RequestedByID)
+ if err != nil || initiator == nil || initiator.TelegramID == nil {
+ return
+ }
+
+ if approved {
+ sendText(bot, *initiator.TelegramID, fmt.Sprintf(
+ "✅ Заявка #%d отозвана\n\nВсе согласующие дали согласие на отзыв.",
+ *request.ApprovalID,
+ ))
+ return
+ }
+
+ sendText(bot, *initiator.TelegramID, fmt.Sprintf(
+ "❌ Отзыв заявки #%d отклонён\n\n"+
+ "👤 Отклонил: %s\n\n"+
+ "Заявка остаётся согласованной.",
+ *request.ApprovalID, rejectorName,
+ ))
+}
diff --git a/service/telegram_service/handlers/approval/approval_task_transfer.go b/service/telegram_service/handlers/approval/approval_task_transfer.go
new file mode 100644
index 0000000..cf04caf
--- /dev/null
+++ b/service/telegram_service/handlers/approval/approval_task_transfer.go
@@ -0,0 +1,316 @@
+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"
+ "time"
+)
+
+// HandleTransferTaskStart — исполнитель начинает передачу задачи, показываем список пользователей
+func (h *Handler) HandleTransferTaskStart(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, taskID uint64) {
+ h.showTransferTaskUserPage(bot, cq, taskID, 0, false)
+}
+
+func (h *Handler) HandleTransferTaskUserPage(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, page int) {
+ ctx := context.Background()
+ taskIDKey := fmt.Sprintf("task_transfer_pending:%d", cq.From.ID)
+ taskIDStr, err := h.ipc.RedisClient.Get(ctx, taskIDKey)
+ if err != nil || taskIDStr == "" {
+ bot.Request(tgbotapi.NewCallback(cq.ID, "Сессия истекла, начните заново")) //nolint:errcheck
+ return
+ }
+ var taskID uint64
+ fmt.Sscanf(taskIDStr, "%d", &taskID)
+ h.showTransferTaskUserPage(bot, cq, taskID, page, true)
+}
+
+func (h *Handler) showTransferTaskUserPage(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, taskID uint64, page int, isEdit bool) {
+ ctx := context.Background()
+ chatID := cq.Message.Chat.ID
+ telegramID := cq.From.ID
+
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+
+ currentUser, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
+ if err != nil || currentUser == nil || currentUser.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 != *currentUser.ID {
+ sendText(bot, chatID, "⚠️ Это не ваша задача.")
+ return
+ }
+ if task.Status == nil || *task.Status != "pending" {
+ sendText(bot, chatID, "⚠️ Передать можно только активную задачу.")
+ return
+ }
+
+ if existing, _ := h.ipc.Database.ApprovalTaskTransfer.GetPendingTransferForTaskDB(ctx, taskID); existing != nil {
+ sendText(bot, chatID, "⚠️ По этой задаче уже есть ожидающий подтверждения запрос на передачу.")
+ return
+ }
+
+ allUsers, _, err := h.ipc.Database.User.GetUsersListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.User{IsBlocked: utilscore.PointerToBool(false)},
+ Limit: utilscore.PointerToUint64(500),
+ })
+ if err != nil {
+ logrus.Errorf("showTransferTaskUserPage: GetUsersListDB err=%v", err)
+ return
+ }
+
+ var candidates []*typescore.User
+ for _, u := range allUsers {
+ if u.ID != nil && currentUser.ID != nil && *u.ID != *currentUser.ID {
+ candidates = append(candidates, u)
+ }
+ }
+
+ taskIDKey := fmt.Sprintf("task_transfer_pending:%d", telegramID)
+ h.ipc.RedisClient.Set(ctx, taskIDKey, fmt.Sprintf("%d", taskID), 10*time.Minute) //nolint:errcheck
+
+ markup := keyboard.BuildTaskTransferUserMenu(candidates, page)
+
+ if isEdit {
+ edit := tgbotapi.NewEditMessageReplyMarkup(chatID, cq.Message.MessageID, markup)
+ bot.Request(edit) //nolint:errcheck
+ return
+ }
+
+ msg := tgbotapi.NewMessage(chatID, "🔁 Кому передать задачу?\n\nВыберите пользователя из списка:")
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = markup
+ bot.Send(msg) //nolint:errcheck
+}
+
+// HandleTransferTaskUserSelect — исполнитель выбрал получателя
+func (h *Handler) HandleTransferTaskUserSelect(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, toUserID 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
+
+ taskIDKey := fmt.Sprintf("task_transfer_pending:%d", telegramID)
+ taskIDStr, err := h.ipc.RedisClient.Get(ctx, taskIDKey)
+ if err != nil || taskIDStr == "" {
+ sendText(bot, chatID, "⚠️ Сессия истекла, начните заново.")
+ return
+ }
+ var taskID uint64
+ fmt.Sscanf(taskIDStr, "%d", &taskID)
+ h.ipc.RedisClient.Del(ctx, taskIDKey) //nolint:errcheck
+
+ fromUser, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
+ if err != nil || fromUser == nil || fromUser.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 != *fromUser.ID {
+ sendText(bot, chatID, "⚠️ Это не ваша задача.")
+ return
+ }
+ if task.Status == nil || *task.Status != "pending" {
+ sendText(bot, chatID, "⚠️ Задача больше не активна — передача невозможна.")
+ return
+ }
+ if existing, _ := h.ipc.Database.ApprovalTaskTransfer.GetPendingTransferForTaskDB(ctx, taskID); existing != nil {
+ sendText(bot, chatID, "⚠️ По этой задаче уже есть ожидающий запрос.")
+ return
+ }
+
+ toUser, err := h.ipc.Database.User.GetUserByIDDB(ctx, toUserID)
+ if err != nil || toUser == nil || toUser.TelegramID == nil {
+ sendText(bot, chatID, "⚠️ У выбранного пользователя не привязан Telegram, передача невозможна.")
+ return
+ }
+
+ pendingStatus := "pending"
+ transfer := &typescore.ApprovalTaskTransfer{
+ TaskID: taskID2Ptr(taskID),
+ FromExecutorID: fromUser.ID,
+ ToExecutorID: toUser.ID,
+ Status: &pendingStatus,
+ }
+ created, err := h.ipc.Database.ApprovalTaskTransfer.CreateApprovalTaskTransferDB(ctx, transfer)
+ if err != nil || created == nil || created.ID == nil {
+ logrus.Errorf("HandleTransferTaskUserSelect: CreateApprovalTaskTransferDB err=%v", err)
+ sendText(bot, chatID, "⚠️ Ошибка при создании запроса.")
+ return
+ }
+
+ fromName := "—"
+ if fromUser.FullName != nil {
+ fromName = *fromUser.FullName
+ }
+
+ approval, _ := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, *task.ApprovalID)
+ topicFullName := "—"
+ taskText := "—"
+ if approval != nil {
+ topicFullName = getTopicFullName(ctx, h.ipc, approval.TopicID)
+ }
+ if task.TaskText != nil {
+ taskText = *task.TaskText
+ }
+
+ notifyText := fmt.Sprintf(
+ "🔁 Вам предлагают принять задачу\n\n"+
+ "👤 От: %s\n"+
+ "📋 Тема: %s\n"+
+ "🎯 Задача:\n%s\n\n"+
+ "Подтвердите, что принимаете задачу на себя:",
+ fromName, topicFullName, taskText,
+ )
+
+ notifyMsg := tgbotapi.NewMessage(*toUser.TelegramID, notifyText)
+ notifyMsg.ParseMode = "HTML"
+ notifyMsg.ReplyMarkup = keyboard.BuildTaskTransferConfirmation(*created.ID)
+ bot.Send(notifyMsg) //nolint:errcheck
+
+ toName := "—"
+ if toUser.FullName != nil {
+ toName = *toUser.FullName
+ }
+ sendText(bot, chatID, fmt.Sprintf(
+ "📤 Запрос отправлен\n\nОжидаем подтверждения от %s.", toName,
+ ))
+}
+
+// HandleTransferTaskAccept — получатель принял задачу
+func (h *Handler) HandleTransferTaskAccept(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, transferID 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
+
+ transfer, err := h.ipc.Database.ApprovalTaskTransfer.GetApprovalTaskTransferByIDDB(ctx, transferID)
+ if err != nil || transfer == nil {
+ sendText(bot, chatID, "⚠️ Запрос не найден.")
+ return
+ }
+ if transfer.Status == nil || *transfer.Status != "pending" {
+ sendText(bot, chatID, "⚠️ Этот запрос уже обработан.")
+ return
+ }
+
+ acceptor, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, cq.From.ID)
+ if err != nil || acceptor == nil || acceptor.ID == nil {
+ return
+ }
+ if transfer.ToExecutorID == nil || *transfer.ToExecutorID != *acceptor.ID {
+ sendText(bot, chatID, "⚠️ Этот запрос адресован не вам.")
+ return
+ }
+
+ task, err := h.ipc.Database.ApprovalTasks.GetApprovalTaskByIDDB(ctx, *transfer.TaskID)
+ if err != nil || task == nil {
+ sendText(bot, chatID, "⚠️ Задача не найдена.")
+ return
+ }
+
+ // 🚀 Ключевая защита от гонки: перепроверяем, что задача всё ещё активна
+ // и всё ещё принадлежит тому, кто инициировал передачу
+ if task.Status == nil || *task.Status != "pending" ||
+ task.ExecutorID == nil || transfer.FromExecutorID == nil || *task.ExecutorID != *transfer.FromExecutorID {
+
+ declinedStatus := "declined"
+ transfer.Status = &declinedStatus
+ now := time.Now()
+ transfer.RespondedAt = &now
+ h.ipc.Database.ApprovalTaskTransfer.UpdateApprovalTaskTransferDB(ctx, transfer) //nolint:errcheck
+
+ sendText(bot, chatID, "⚠️ Задача уже была выполнена или передана другому — принять не удалось.")
+ return
+ }
+
+ acceptedStatus := "accepted"
+ transfer.Status = &acceptedStatus
+ now := time.Now()
+ transfer.RespondedAt = &now
+ if _, err := h.ipc.Database.ApprovalTaskTransfer.UpdateApprovalTaskTransferDB(ctx, transfer); err != nil {
+ logrus.Errorf("HandleTransferTaskAccept: UpdateApprovalTaskTransferDB err=%v", err)
+ return
+ }
+
+ task.ExecutorID = acceptor.ID
+ if _, _, err := h.ipc.Database.ApprovalTasks.UpdateApprovalTaskDB(ctx, nil, task); err != nil {
+ logrus.Errorf("HandleTransferTaskAccept: UpdateApprovalTaskDB err=%v", err)
+ return
+ }
+
+ acceptorName := "—"
+ if acceptor.FullName != nil {
+ acceptorName = *acceptor.FullName
+ }
+
+ // Уведомляем исходного исполнителя
+ if transfer.FromExecutorID != nil {
+ fromUser, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *transfer.FromExecutorID)
+ if fromUser != nil && fromUser.TelegramID != nil {
+ sendText(bot, *fromUser.TelegramID, fmt.Sprintf(
+ "✅ %s принял(а) задачу\n\nЗадача больше не числится за вами.", acceptorName,
+ ))
+ }
+ }
+
+ sendText(bot, chatID, "✅ Задача принята\n\nОна теперь ваша.")
+
+ // Отправляем получателю полную карточку задачи с кнопками действий
+ approval, _ := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, *task.ApprovalID)
+ if approval != nil {
+ h.sendTaskCard(bot, chatID, approval, task)
+ }
+}
+
+// HandleTransferTaskDecline — получатель отклонил задачу
+func (h *Handler) HandleTransferTaskDecline(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, transferID 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
+
+ transfer, err := h.ipc.Database.ApprovalTaskTransfer.GetApprovalTaskTransferByIDDB(ctx, transferID)
+ if err != nil || transfer == nil || transfer.Status == nil || *transfer.Status != "pending" {
+ sendText(bot, chatID, "⚠️ Запрос не найден или уже обработан.")
+ return
+ }
+
+ declinedStatus := "declined"
+ transfer.Status = &declinedStatus
+ now := time.Now()
+ transfer.RespondedAt = &now
+ if _, err := h.ipc.Database.ApprovalTaskTransfer.UpdateApprovalTaskTransferDB(ctx, transfer); err != nil {
+ logrus.Errorf("HandleTransferTaskDecline: UpdateApprovalTaskTransferDB err=%v", err)
+ return
+ }
+
+ sendText(bot, chatID, "❌ Вы отклонили передачу задачи.")
+
+ if transfer.FromExecutorID != nil {
+ fromUser, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *transfer.FromExecutorID)
+ if fromUser != nil && fromUser.TelegramID != nil {
+ sendText(bot, *fromUser.TelegramID, "❌ Получатель отклонил передачу задачи\n\nЗадача осталась за вами.")
+ }
+ }
+}
+
+func taskID2Ptr(id uint64) *uint64 { return &id }
diff --git a/service/telegram_service/handlers/approval/db_watcher.go b/service/telegram_service/handlers/approval/db_watcher.go
new file mode 100644
index 0000000..abb148a
--- /dev/null
+++ b/service/telegram_service/handlers/approval/db_watcher.go
@@ -0,0 +1,53 @@
+package approval
+
+import (
+ "bitrix_balancer_api/core/variables"
+ "context"
+ "time"
+
+ "github.com/sirupsen/logrus"
+)
+
+const flowVersionRedisKey = "approval_flow:version"
+
+// watchRegistryReload — фоновый воркер: раз в pollInterval проверяет, менялась
+// ли версия дерева тем/категорий (её бампает rest_admin_service при любом
+// изменении дерева/категорий/тем — см. bumpFlowVersion в nodeshandler), и если
+// да — перечитывает Registry из БД.
+//
+// Зачем это нужно: h.Registry.LoadFromDB вызывается один раз в NewHandler,
+// при старте процесса бота. Без этого воркера Registry — снимок на момент
+// старта, и всё, что создано в конструкторе после этого (новые категории,
+// деревья, темы), в боте не появится до перезапуска процесса.
+//
+// Почему через Redis, а не прямой HTTP-вызов между сервисами: rest_admin_service
+// и telegram_service — разные процессы, у telegram_service нет гарантированного
+// входящего HTTP-порта (он может работать через long polling к Telegram API),
+// а Redis у обоих сервисов уже общий (см. ipc.RedisClient в NewHandler).
+func (h *Handler) watchRegistryReload() {
+ const pollInterval = 5 * time.Second
+ ticker := time.NewTicker(pollInterval)
+ defer ticker.Stop()
+
+ lastVersion := ""
+ for range ticker.C {
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ version, err := h.ipc.RedisClient.Get(ctx, flowVersionRedisKey)
+ cancel()
+ if err != nil {
+ continue
+ }
+ if version == "" || version == lastVersion {
+ continue
+ }
+ lastVersion = version
+
+ reloadCtx, reloadCancel := context.WithTimeout(context.Background(), variables.ContextTimeoutLong)
+ if err := h.Registry.Reload(reloadCtx); err != nil {
+ logrus.Errorf("watchRegistryReload: Registry.Reload err=%v", err)
+ } else {
+ logrus.Infof("watchRegistryReload: дерево тем перечитано, версия=%s", version)
+ }
+ reloadCancel()
+ }
+}
diff --git a/service/telegram_service/handlers/approval/director_notification_settings.go b/service/telegram_service/handlers/approval/director_notification_settings.go
new file mode 100644
index 0000000..a2bf258
--- /dev/null
+++ b/service/telegram_service/handlers/approval/director_notification_settings.go
@@ -0,0 +1,118 @@
+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"
+ "sort"
+)
+
+// HandleDirectorNotificationSettings — показывает мультиселект категорий уведомлений (страница 0)
+func (h *Handler) HandleDirectorNotificationSettings(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) {
+ h.showDirectorNotificationPage(bot, chatID, 0, telegramID, 0)
+}
+
+// showDirectorNotificationPage — общая логика показа/перерисовки страницы категорий.
+// prevMessageID != 0 — редактируем существующее сообщение вместо отправки нового.
+func (h *Handler) showDirectorNotificationPage(bot *tgbotapi.BotAPI, chatID int64, page int, telegramID int64, prevMessageID int) {
+ ctx := context.Background()
+
+ director, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
+ if err != nil || director == nil || director.ID == nil {
+ sendText(bot, chatID, "⚠️ Пользователь не найден.")
+ return
+ }
+
+ isDirector, err := h.ipc.Database.User.IsDirectorDB(ctx, *director.ID)
+ if err != nil || !isDirector {
+ sendText(bot, chatID, "⚠️ У вас нет прав директора.")
+ return
+ }
+
+ isActive := true
+ categories, _, err := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalTopicCategory{IsActive: &isActive},
+ })
+ if err != nil {
+ logrus.Errorf("showDirectorNotificationPage: GetApprovalTopicCategoryListDB err=%v", err)
+ sendText(bot, chatID, "⚠️ Ошибка загрузки категорий.")
+ return
+ }
+
+ sort.Slice(categories, func(i, j int) bool {
+ if categories[i].Name == nil || categories[j].Name == nil {
+ return false
+ }
+ return *categories[i].Name < *categories[j].Name
+ })
+
+ subscribedIDs, err := h.ipc.Database.DirectorNotifications.GetSubscribedCategoryIDsDB(ctx, *director.ID)
+ if err != nil {
+ logrus.Errorf("showDirectorNotificationPage: GetSubscribedCategoryIDsDB err=%v", err)
+ }
+
+ markup := keyboard.BuildDirectorNotificationCategoriesMenu(categories, subscribedIDs, page)
+
+ if prevMessageID != 0 {
+ edit := tgbotapi.NewEditMessageReplyMarkup(chatID, prevMessageID, markup)
+ bot.Request(edit) //nolint:errcheck
+ return
+ }
+
+ msg := tgbotapi.NewMessage(chatID, "🔔 Уведомления по категориям\n\nВыберите категории, по которым хотите получать уведомления о финально согласованных заявках. По умолчанию все выключены.")
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = markup
+ bot.Send(msg) //nolint:errcheck
+}
+
+// HandleDirectorNotificationToggle — обрабатывает нажатие на категорию (callback dir_notif_toggle:{categoryID}:{page})
+func (h *Handler) HandleDirectorNotificationToggle(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, categoryID uint64, page int) {
+ ctx := context.Background()
+ chatID := cq.Message.Chat.ID
+ telegramID := cq.From.ID
+
+ director, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
+ if err != nil || director == nil || director.ID == nil {
+ bot.Request(tgbotapi.NewCallback(cq.ID, "Пользователь не найден")) //nolint:errcheck
+ return
+ }
+
+ enabled, err := h.ipc.Database.DirectorNotifications.ToggleSubscriptionDB(ctx, *director.ID, categoryID)
+ if err != nil {
+ logrus.Errorf("HandleDirectorNotificationToggle: ToggleSubscriptionDB err=%v", err)
+ bot.Request(tgbotapi.NewCallback(cq.ID, "Ошибка сохранения")) //nolint:errcheck
+ return
+ }
+
+ statusText := "выключены"
+ if enabled {
+ statusText = "включены"
+ }
+ bot.Request(tgbotapi.NewCallback(cq.ID, fmt.Sprintf("Уведомления %s", statusText))) //nolint:errcheck
+
+ // Перерисовываем ту же страницу, где был клик
+ h.showDirectorNotificationPage(bot, chatID, page, telegramID, cq.Message.MessageID)
+}
+
+// HandleDirectorNotificationPage — переключение страниц пагинации
+func (h *Handler) HandleDirectorNotificationPage(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, page int) {
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ h.showDirectorNotificationPage(bot, cq.Message.Chat.ID, page, cq.From.ID, cq.Message.MessageID)
+}
+
+// HandleDirectorNotificationDone — закрывает меню настройки уведомлений
+func (h *Handler) HandleDirectorNotificationDone(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
+}
+
+// HandleDirectorSubmenu — подменю директора
+func (h *Handler) HandleDirectorSubmenu(bot *tgbotapi.BotAPI, chatID int64) {
+ msg := tgbotapi.NewMessage(chatID, "Директор\n\nВыберите действие:")
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildDirectorSubmenu()
+ bot.Send(msg) //nolint:errcheck
+}
diff --git a/service/telegram_service/handlers/approval/handle_files.go b/service/telegram_service/handlers/approval/handle_files.go
index 900b678..b245768 100644
--- a/service/telegram_service/handlers/approval/handle_files.go
+++ b/service/telegram_service/handlers/approval/handle_files.go
@@ -120,7 +120,7 @@ func (h *Handler) HandleAttachFileInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Mess
return true
}
- base64Data, err := fetchFileAsBase64(fileURL, h.ipc.Config.Telegram)
+ base64Data, err := fetchFileAsBase64(fileURL)
if err != nil {
logrus.Errorf("HandleAttachFileInput: fetchFileAsBase64 err=%v", err)
sendText(bot, chatID, "Ошибка при обработке файла.")
@@ -247,7 +247,7 @@ func (h *Handler) HandleAttachSubmit(bot *tgbotapi.BotAPI, cq *tgbotapi.Callback
// Уведомляем всех участников с отправкой самих файлов медиагруппами
fileDesc := fmt.Sprintf("%d файл(ов)", savedCount)
- h.notifyAllParticipantsAboutFile(bot, approvalID, user, fileDesc)
+ go h.notifyAllParticipantsAboutFile(bot, approvalID, user, fileDesc)
}
// HandleAttachClear — очистить список файлов
@@ -329,7 +329,7 @@ func (h *Handler) HandleFileInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) b
return true
}
- base64Data, err := fetchFileAsBase64(fileURL, h.ipc.Config.Telegram)
+ base64Data, err := fetchFileAsBase64(fileURL)
if err != nil {
logrus.Errorf("HandleFileInput: fetchFileAsBase64 url=%s err=%v", fileURL, err)
sendText(bot, chatID, "Ошибка при обработке файла. Попробуйте ещё раз.")
diff --git a/service/telegram_service/handlers/approval/handle_multiselect.go b/service/telegram_service/handlers/approval/handle_multiselect.go
index fb0908e..11f3164 100644
--- a/service/telegram_service/handlers/approval/handle_multiselect.go
+++ b/service/telegram_service/handlers/approval/handle_multiselect.go
@@ -76,8 +76,8 @@ func (h *Handler) HandleMultiSelectConfirm(bot *tgbotapi.BotAPI, cq *tgbotapi.Ca
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
+ bot.Request(tgbotapi.NewCallback(cq.ID, ""))
+ bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID))
flowState, err := h.States.Get(ctx, telegramID)
if err != nil || flowState == nil {
@@ -87,12 +87,10 @@ func (h *Handler) HandleMultiSelectConfirm(bot *tgbotapi.BotAPI, cq *tgbotapi.Ca
selected := flowState.MultiSelected[flowState.MultiSelectNodeKey]
if len(selected) == 0 {
- // Напоминаем что нужно выбрать хотя бы один вариант
- bot.Request(tgbotapi.NewCallback(cq.ID, "⚠️ Выберите хотя бы один вариант")) //nolint:errcheck
+ bot.Request(tgbotapi.NewCallback(cq.ID, "⚠️ Выберите хотя бы один вариант"))
return
}
- // Сохраняем выбранные значения как строку через запятую в Collected
topic, _ := h.Registry.Get(topicCode)
if topic == nil {
return
@@ -103,19 +101,28 @@ func (h *Handler) HandleMultiSelectConfirm(bot *tgbotapi.BotAPI, cq *tgbotapi.Ca
return
}
- // Берём MultiSelectKey из первого дочернего узла
if len(node.Children) > 0 {
msKey := node.Children[0].MultiSelectKey
if msKey != "" {
flowState.Collected[msKey] = strings.Join(selected, ",")
+
+ var labels []string
+ for _, child := range node.Children {
+ for _, sel := range selected {
+ if child.MultiSelectValue == sel {
+ labels = append(labels, child.Label)
+ break
+ }
+ }
+ }
+ flowState.Collected[msKey+"_label"] = strings.Join(labels, ", ")
}
}
flowState.AwaitMultiSelectConfirm = false
flowState.MultiSelectNodeKey = ""
- // Переходим к вводу текста — находим первый input среди детей выбранных узлов
- // (InputHint берём из первого выбранного)
+ // Переходим к вводу текста
var inputNode *approvalflow.FlowNode
for _, child := range node.Children {
for _, sel := range selected {
@@ -134,16 +141,16 @@ func (h *Handler) HandleMultiSelectConfirm(bot *tgbotapi.BotAPI, cq *tgbotapi.Ca
flowState.InputKey = inputNode.InputKey
flowState.NodeKey = flowState.MultiSelectNodeKey
- h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
+ h.States.Set(ctx, telegramID, flowState)
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
+ bot.Send(msg)
return
}
- h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
+ h.States.Set(ctx, telegramID, flowState)
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
index 8080329..b525451 100644
--- a/service/telegram_service/handlers/approval/handler.go
+++ b/service/telegram_service/handlers/approval/handler.go
@@ -2,6 +2,7 @@ package approval
import (
"bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/core/variables"
"bitrix_balancer_api/telegram_service/approvalflow"
"bitrix_balancer_api/telegram_service/keyboard"
"bitrix_balancer_api/telegram_service/state"
@@ -9,10 +10,10 @@ import (
"context"
"encoding/base64"
"fmt"
- "time"
-
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"github.com/sirupsen/logrus"
+ "html"
+ "time"
)
type Handler struct {
@@ -22,11 +23,24 @@ type Handler struct {
}
func NewHandler(ipc *types.InternalProviderControl) *Handler {
- return &Handler{
+ h := &Handler{
ipc: ipc,
- Registry: NewRegistry(),
+ Registry: NewRegistry(ipc),
States: state.NewStateManager(ipc.RedisClient),
}
+
+ // Загружаем темы из БД при старте
+ ctx, cancel := context.WithTimeout(context.Background(), variables.ContextTimeoutLong)
+ if err := h.Registry.LoadFromDB(ctx); err != nil {
+ logrus.Errorf("Failed to load topics from DB: %v", err)
+ }
+ cancel()
+
+ // Фоновая проверка изменений дерева тем/категорий из конструктора —
+ // см. reload_watcher.go (новый файл, package approval).
+ go h.watchRegistryReload()
+
+ return h
}
// HandleMenu — первая страница меню.
@@ -289,11 +303,9 @@ func (h *Handler) HandleRevokeWithComment(bot *tgbotapi.BotAPI, chatID int64, te
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},
@@ -305,7 +317,6 @@ func (h *Handler) HandleRevokeWithComment(bot *tgbotapi.BotAPI, chatID int64, te
}
}
- // Проверка прав в зависимости от статуса
switch *approval.Status {
case "revoked":
sendText(bot, chatID, "Заявка уже отозвана.")
@@ -323,6 +334,13 @@ func (h *Handler) HandleRevokeWithComment(bot *tgbotapi.BotAPI, chatID int64, te
sendText(bot, chatID, "⚠️ У вас нет прав для отзыва этой заявки.")
return
}
+
+ // Инициатор (не директор) отзывает уже согласованную заявку —
+ // требуется согласие всех, кто участвовал в согласовании
+ if isInitiator && !isDirector {
+ h.startApprovalRevocationRequest(bot, chatID, approval, revoker, comment)
+ return
+ }
default:
if !isInitiator && !isDirector {
sendText(bot, chatID, "⚠️ У вас нет прав для отзыва этой заявки.")
@@ -330,32 +348,6 @@ func (h *Handler) HandleRevokeWithComment(bot *tgbotapi.BotAPI, chatID int64, te
}
}
- 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)
-
- 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:
@@ -366,6 +358,73 @@ func (h *Handler) HandleRevokeWithComment(bot *tgbotapi.BotAPI, chatID int64, te
revokerRole = "согласующим"
}
+ h.performActualRevoke(bot, ctx, approval, revoker, revokerRole, comment, steps, isInitiator, isDirector)
+
+ // Обратная связь тому, кто выполнил отзыв
+ topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID)
+ content := "—"
+ if approval.Content != nil {
+ content = html.EscapeString(*approval.Content)
+ }
+ approvalCard := fmt.Sprintf(
+ "📋 Тема: %s\n📝 Текст: %s\n💬 Причина отзыва: %s",
+ topicFullName, content, comment,
+ )
+ feedbackMsg := tgbotapi.NewMessage(chatID, fmt.Sprintf(
+ "↩️ Заявка #%d отозвана\n\n%s",
+ approvalID, approvalCard,
+ ))
+ feedbackMsg.ParseMode = "HTML"
+ feedbackMsg.ReplyMarkup = keyboard.BuildCommentNotificationKeyboard(approvalID, h.GetCommentsCount(ctx, approvalID))
+ bot.Send(feedbackMsg) //nolint:errcheck
+}
+
+// performActualRevoke выполняет отзыв заявки в БД и уведомляет всех участников
+// с возможностью комментирования. Вызывается либо напрямую (директор/согласующий/
+// инициатор для pending), либо после того как все согласующие подтвердили согласие
+// на отзыв уже одобренной заявки.
+func (h *Handler) performActualRevoke(
+ bot *tgbotapi.BotAPI,
+ ctx context.Context,
+ approval *typescore.Approval,
+ revoker *typescore.User,
+ revokerRole string,
+ comment string,
+ steps []*typescore.ApprovalStep,
+ isInitiatorRevoking bool,
+ isDirectorRevoking bool,
+) {
+ if approval.ID == nil {
+ return
+ }
+ approvalID := *approval.ID
+
+ 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("performActualRevoke: UpdateApprovalDB err=%v", err)
+ return
+ }
+
+ h.deactivatePendingDelegation(ctx, approval)
+
+ h.handleRevokeCancellationTask(bot, ctx, approval)
+
+ revokerName := "—"
+ if revoker.FullName != nil {
+ revokerName = *revoker.FullName
+ }
+
+ topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID)
+ content := "—"
+ if approval.Content != nil {
+ content = html.EscapeString(*approval.Content)
+ }
+
approvalCard := fmt.Sprintf(
"📋 Тема: %s\n"+
"📝 Текст: %s\n"+
@@ -373,23 +432,31 @@ func (h *Handler) HandleRevokeWithComment(bot *tgbotapi.BotAPI, chatID int64, te
topicFullName, content, comment,
)
- // Уведомление тому, кто отзывает
- sendText(bot, chatID, fmt.Sprintf(
- "↩️ Заявка #%d отозвана\n\n%s",
- approvalID, approvalCard,
- ))
+ commentsCount := h.GetCommentsCount(ctx, approvalID)
+ commentKeyboard := keyboard.BuildCommentNotificationKeyboard(approvalID, commentsCount)
- if !isInitiator && approval.InitiatorID != nil {
+ notify := func(chatID int64, text string) {
+ go func() {
+ msg := tgbotapi.NewMessage(chatID, text)
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = commentKeyboard
+ bot.Send(msg) //nolint:errcheck
+ }()
+ }
+
+ // Инициатор (если не сам отзывал)
+ if !isInitiatorRevoking && 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(
+ notify(*initiator.TelegramID, fmt.Sprintf(
"↩️ Ваша заявка #%d отозвана %s %s\n\n%s",
approvalID, revokerRole, revokerName, approvalCard,
))
}
}
- if !isDirector {
+ // Директора (если не сам отзывал)
+ if !isDirectorRevoking {
directors, _ := h.ipc.Database.User.GetDirectorsDB(ctx)
for _, director := range directors {
if director.TelegramID == nil {
@@ -398,13 +465,15 @@ func (h *Handler) HandleRevokeWithComment(bot *tgbotapi.BotAPI, chatID int64, te
if revoker.ID != nil && director.ID != nil && *director.ID == *revoker.ID {
continue
}
- sendText(bot, *director.TelegramID, fmt.Sprintf(
+ notify(*director.TelegramID, fmt.Sprintf(
"↩️ Заявка #%d отозвана %s %s\n\n%s",
approvalID, revokerRole, revokerName, approvalCard,
))
}
}
+ // Согласующие (кроме самого отозвавшего)
+ notifiedApprovers := make(map[uint64]bool)
for _, step := range steps {
if step.ApproverID == nil {
continue
@@ -412,31 +481,35 @@ func (h *Handler) HandleRevokeWithComment(bot *tgbotapi.BotAPI, chatID int64, te
if revoker.ID != nil && *step.ApproverID == *revoker.ID {
continue
}
+ if notifiedApprovers[*step.ApproverID] {
+ continue
+ }
+ notifiedApprovers[*step.ApproverID] = true
+
approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *step.ApproverID)
if approver == nil || approver.TelegramID == nil {
continue
}
- sendText(bot, *approver.TelegramID, fmt.Sprintf(
+ notify(*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,
- ))
+ // Наблюдатели
+ categoryCode := h.getTopicCodeByApproval(ctx, approval)
+ observers, _ := h.ipc.Database.User.GetObserversForApprovalDB(ctx, categoryCode, approval.TopicID)
+ for _, obs := range observers {
+ if obs.TelegramID == nil {
+ continue
}
+ if revoker.ID != nil && obs.ID != nil && *obs.ID == *revoker.ID {
+ continue
+ }
+ notify(*obs.TelegramID, fmt.Sprintf(
+ "↩️ Заявка #%d отозвана %s %s\n\n%s",
+ approvalID, revokerRole, revokerName, approvalCard,
+ ))
}
}
@@ -585,6 +658,17 @@ func (h *Handler) continueFlowAfterInput(
return
}
+ if approvalTopic != nil &&
+ approvalTopic.AllowDelegationSelection != nil &&
+ *approvalTopic.AllowDelegationSelection &&
+ !flowState.DelegationSelectionDone {
+
+ flowState.AwaitDelegationChoice = true
+ h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
+ h.showDelegationChoice(bot, chatID, telegramID)
+ return
+ }
+
if approvalTopic != nil &&
approvalTopic.AllowObserverSelection != nil &&
*approvalTopic.AllowObserverSelection &&
@@ -613,21 +697,157 @@ func (h *Handler) HandleViewFilesCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.Cal
return
}
- sendText(bot, chatID, fmt.Sprintf("📎 Файлы к заявке #%d (%d шт.):", approvalID, len(files)))
+ caption := fmt.Sprintf("📎 Файлы к заявке #%d (%d шт.):", approvalID, len(files))
- for _, f := range files {
+ for i, 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
+
+ go func(fileBase64 string, fileName string, isFirst bool) {
+ data, err := base64.StdEncoding.DecodeString(fileBase64)
+ if err != nil {
+ logrus.Errorf("HandleViewFilesCallback: decode err=%v", err)
+ return
+ }
+ doc := tgbotapi.NewDocument(chatID, tgbotapi.FileBytes{
+ Name: fileName,
+ Bytes: data,
+ })
+ doc.ParseMode = "HTML"
+ if isFirst {
+ doc.Caption = caption
+ }
+ if _, err := bot.Send(doc); err != nil {
+ logrus.Errorf("HandleViewFilesCallback: Send err=%v", err)
+ }
+ }(*f.FileBase64, *f.FileName, i == 0)
}
}
+
+// HandleShowApprovalCardCallback показывает карточку заявки с кнопками,
+// соответствующими роли нажавшего пользователя именно в этой заявке.
+// Порядок проверки важен: сначала более специфичные роли (исполнитель активной
+// задачи, активный согласующий), затем инициатор, затем директор/наблюдатель.
+func (h *Handler) HandleShowApprovalCardCallback(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 || user == nil || user.ID == nil {
+ sendText(bot, chatID, "⚠️ Пользователь не найден.")
+ return
+ }
+ currentUserID := *user.ID
+
+ approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID)
+ if err != nil || approval == nil {
+ sendText(bot, chatID, "⚠️ Заявка не найдена.")
+ return
+ }
+
+ files, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, approvalID)
+ approval.Files = files
+ filesCount := len(files)
+ commentsCount := h.GetCommentsCount(ctx, approvalID)
+
+ status := ""
+ if approval.Status != nil {
+ status = *approval.Status
+ }
+
+ collected := h.getCollectedFromApproval(ctx, approval)
+ card := h.buildApprovalCard(ctx, approval, collected)
+
+ // 1. Исполнитель активной задачи по этой заявке
+ tasks, _, err := h.ipc.Database.ApprovalTasks.GetApprovalTasksListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalTask{ApprovalID: &approvalID, ExecutorID: ¤tUserID},
+ })
+ if err == nil {
+ for _, task := range tasks {
+ if task.Status != nil && *task.Status == "pending" {
+ h.sendTaskCard(bot, chatID, approval, task)
+ return
+ }
+ }
+ }
+
+ // 2. Активный согласующий (включая делегатов) по этой заявке
+ categoryCode := h.getTopicCodeByApproval(ctx, approval)
+ approvalTopic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID)
+ isAnyOf := approvalTopic != nil && approvalTopic.ApprovalMode != nil && *approvalTopic.ApprovalMode == "any_of"
+
+ if status == "pending" {
+ if step := h.findStepForCurrentApprover(ctx, approvalID, currentUserID, approval, isAnyOf); step != nil {
+ msg := tgbotapi.NewMessage(chatID, card)
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildApproverDecision(approvalID, status, filesCount > 0, filesCount, commentsCount)
+ bot.Send(msg) //nolint:errcheck
+ return
+ }
+ }
+
+ // 3. Дополнительный согласующий (pending) по этой заявке
+ additionalApprovers, _, _ := h.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalAdditionalApprover{ApprovalID: &approvalID},
+ })
+ for _, aa := range additionalApprovers {
+ if aa.ApproverID != nil && *aa.ApproverID == currentUserID && aa.Status != nil && *aa.Status == "pending" {
+ msg := tgbotapi.NewMessage(chatID, card)
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildApproverDecision(approvalID, status, filesCount > 0, filesCount, commentsCount)
+ bot.Send(msg) //nolint:errcheck
+ return
+ }
+ }
+
+ // 4. Инициатор заявки
+ if approval.InitiatorID != nil && *approval.InitiatorID == currentUserID {
+ msg := tgbotapi.NewMessage(chatID, card)
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildRevokeButton(approvalID, status, filesCount, commentsCount)
+ bot.Send(msg) //nolint:errcheck
+ return
+ }
+
+ // 5. Директор
+ if isDirector, _ := h.ipc.Database.User.IsDirectorDB(ctx, currentUserID); isDirector {
+ msg := tgbotapi.NewMessage(chatID, card)
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildRevokeButton(approvalID, status, filesCount, commentsCount)
+ bot.Send(msg) //nolint:errcheck
+ return
+ }
+
+ // 6. Наблюдатель категории/темы
+ if h.canUserAccessObserverView(ctx, currentUserID, categoryCode, approval.TopicID) {
+ msg := tgbotapi.NewMessage(chatID, card)
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildObserverActions(approvalID, "", status, filesCount, commentsCount)
+ bot.Send(msg) //nolint:errcheck
+ return
+ }
+
+ // 7. Ни одна роль не подошла — показываем карточку без действий (просмотр)
+ msg := tgbotapi.NewMessage(chatID, card)
+ msg.ParseMode = "HTML"
+ bot.Send(msg) //nolint:errcheck
+}
+
+// canUserAccessObserverView проверяет, входит ли пользователь в список наблюдателей
+// для категории/темы этой заявки.
+func (h *Handler) canUserAccessObserverView(ctx context.Context, userID uint64, categoryCode string, topicID *uint64) bool {
+ observers, err := h.ipc.Database.User.GetObserversForApprovalDB(ctx, categoryCode, topicID)
+ if err != nil {
+ return false
+ }
+ for _, obs := range observers {
+ if obs.ID != nil && *obs.ID == userID {
+ return true
+ }
+ }
+ return false
+}
diff --git a/service/telegram_service/handlers/approval/handler_add_approver.go b/service/telegram_service/handlers/approval/handler_add_approver.go
index 4800c9b..f7cd638 100644
--- a/service/telegram_service/handlers/approval/handler_add_approver.go
+++ b/service/telegram_service/handlers/approval/handler_add_approver.go
@@ -347,15 +347,17 @@ func (h *Handler) HandleAddApproverUserCallback(bot *tgbotapi.BotAPI, cq *tgbota
}
files, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID)
+ commentsSection := h.formatCommentsSection(ctx, addApproverState.ApprovalID, 4)
+
notifyMsg := tgbotapi.NewMessage(*addedApprover.TelegramID, fmt.Sprintf(
"➕ Вас добавили к согласованию заявки #%d\n\n"+
"👤 Инициатор: %s\n"+
"📋 Тема: %s\n"+
- "📝 Текст: %s",
- addApproverState.ApprovalID, initiatorName, topicFullName, content,
+ "📝 Текст: %s%s",
+ addApproverState.ApprovalID, initiatorName, topicFullName, content, commentsSection,
))
notifyMsg.ParseMode = "HTML"
- notifyMsg.ReplyMarkup = keyboard.BuildApproverDecision(addApproverState.ApprovalID, status, len(files) > 0, len(files))
+ notifyMsg.ReplyMarkup = keyboard.BuildApproverDecision(addApproverState.ApprovalID, status, len(files) > 0, len(files), h.GetCommentsCount(ctx, *approval.ID))
bot.Send(notifyMsg) //nolint:errcheck
}
}
@@ -460,10 +462,28 @@ func (h *Handler) HandleAddedApproverDetail(bot *tgbotapi.BotAPI, cq *tgbotapi.C
bot.Send(msg) //nolint:errcheck
}
+// getApproverCategoriesWithPendingApprovals возвращает категории, в которых у
+// пользователя ЕСТЬ реальные pending-шаги согласования прямо сейчас.
+//
+// 🩹 ФИКС: раньше эта функция шла от UserHierarchy (правил "кто чей
+// согласующий") и имела два независимых бага:
+// 1. Учитывала только topic-scoped записи иерархии (hier.TopicID != nil) —
+// category-scoped и глобальные правила игнорировались полностью, такой
+// согласующий никогда не видел эти категории в меню добавления.
+// 2. Проверка "есть ли pending" делала запрос БЕЗ фильтра по категории —
+// "есть ли у меня вообще хоть один pending-шаг где угодно" — и если да,
+// помечала ЛЮБУЮ категорию из иерархии как имеющую pending, даже если
+// реальный pending-шаг был совсем в другой категории.
+//
+// Теперь функция просто берёт реальные pending ApprovalStep пользователя и
+// смотрит, в каких категориях лежат их темы — точно то же самое, что уже
+// корректно делает соседняя getPendingApprovalsByCategory, только не для
+// одной категории, а сгруппированно.
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{
+ steps, _, err := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalStep{
ApproverID: &userID,
+ Status: utilscore.PointerToString(typescore.ApprovalStatusPending.String()),
},
})
if err != nil {
@@ -471,22 +491,19 @@ func (h *Handler) getApproverCategoriesWithPendingApprovals(ctx context.Context,
}
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
- }
- }
+ 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 {
+ continue
+ }
+ categoryIDs[*topic.CategoryID] = true
}
var categories []*typescore.ApprovalTopicCategory
diff --git a/service/telegram_service/handlers/approval/handler_comment.go b/service/telegram_service/handlers/approval/handler_comment.go
index b6d3dc6..2ee6479 100644
--- a/service/telegram_service/handlers/approval/handler_comment.go
+++ b/service/telegram_service/handlers/approval/handler_comment.go
@@ -8,6 +8,7 @@ import (
"fmt"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"github.com/sirupsen/logrus"
+ "strings"
)
func (h *Handler) HandleAddCommentCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64) {
@@ -108,13 +109,21 @@ func (h *Handler) canUserCommentApproval(ctx context.Context, userID uint64, app
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
- }
+ isFinal := approval.Status != nil &&
+ (*approval.Status == "approved" || *approval.Status == "rejected" || *approval.Status == "revoked")
+
+ var relevant []*typescore.User
+ if isFinal {
+ // после завершения — комментировать может любой наблюдатель темы
+ relevant, _ = h.ipc.Database.User.GetObserversForApprovalDB(ctx, *topic.Code, topic.ID)
+ } else {
+ // в процессе — только контролёр
+ relevant, _ = h.ipc.Database.User.GetControllerObserversForApprovalDB(ctx, *topic.Code, topic.ID)
+ }
+
+ for _, obs := range relevant {
+ if obs.ID != nil && *obs.ID == userID {
+ return true, nil
}
}
}
@@ -133,7 +142,8 @@ func (h *Handler) canUserCommentApproval(ctx context.Context, userID uint64, app
return isDirector, nil
}
-func (h *Handler) formatCommentsSection(ctx context.Context, approvalID uint64) string {
+// formatCommentsSection возвращает секцию с последними limit комментариями.
+func (h *Handler) formatCommentsSection(ctx context.Context, approvalID uint64, limit int) string {
comments, err := h.ipc.Database.ApprovalComment.GetCommentsByApprovalIDDB(ctx, approvalID)
if err != nil {
logrus.Errorf("formatCommentsSection: GetCommentsByApprovalIDDB err=%v", err)
@@ -144,26 +154,25 @@ func (h *Handler) formatCommentsSection(ctx context.Context, approvalID uint64)
return ""
}
- result := "\n\n💬 Комментарии:"
+ total := len(comments)
+ if limit > 0 && total > limit {
+ comments = comments[total-limit:]
+ }
+
+ header := "\n\n💬 Комментарии:"
+ if limit > 0 && total > limit {
+ header = fmt.Sprintf("\n\n💬 Последние %d комментариев (из %d):", limit, total)
+ }
+
+ result := header
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)
+ if comment == nil || comment.UserID == nil || comment.Comment == nil {
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)
+ if err != nil || user == nil {
continue
}
@@ -209,48 +218,17 @@ func (h *Handler) HandleCommentTextInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Mes
return false
}
- user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
- if err != nil || user == nil || user.ID == nil {
- return false
- }
+ commentState.Stage = "await_visibility"
+ commentState.Text = msg.Text
+ commentState.Targets = make(map[uint64]bool)
+ h.States.SetCommentFlow(ctx, telegramID, commentState) //nolint:errcheck
- 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
- }
+ bot.Request(tgbotapi.NewDeleteMessage(chatID, msg.MessageID)) // Удаляем сообщение с текстом для чистоты
- 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)
+ replyMsg := tgbotapi.NewMessage(chatID, "💬 Комментарий сохранен.\n\nВыберите, кому отправить уведомление:")
+ replyMsg.ParseMode = "HTML"
+ replyMsg.ReplyMarkup = keyboard.BuildCommentVisibilityMenu()
+ bot.Send(replyMsg) //nolint:errcheck
return true
}
@@ -287,71 +265,18 @@ func (h *Handler) notifyAllParticipantsAboutComment(
*approval.ID, topicName, content, commenterName, *comment.Comment,
)
- // 🚀 Определяем, является ли статус финальным
- isFinalStatus := approval.Status != nil &&
- (*approval.Status == "approved" || *approval.Status == "rejected" || *approval.Status == "revoked")
+ commentsCount := h.GetCommentsCount(ctx, *approval.ID)
- 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
+ participants := h.getChatParticipants(ctx, approval)
+ for _, u := range participants {
+ if u.TelegramID == nil || *u.TelegramID == skipTelegramID {
+ continue
}
- }
-
- // Текущий согласующий — всегда получает
- 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 := tgbotapi.NewMessage(*u.TelegramID, text)
msg.ParseMode = "HTML"
- msg.ReplyMarkup = keyboard.BuildCommentReplyKeyboard(*approval.ID)
+ msg.ReplyMarkup = keyboard.BuildCommentReplyKeyboard(*approval.ID, commentsCount)
if _, err := bot.Send(msg); err != nil {
- logrus.Errorf("notifyAllParticipantsAboutComment: Send to %d err=%v", telegramID, err)
+ logrus.Errorf("notifyAllParticipantsAboutComment: Send to %d err=%v", *u.TelegramID, err)
}
}
}
@@ -384,14 +309,406 @@ func (h *Handler) HandleCommentReplyInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Me
UserID: user.ID,
Comment: &msg.Text,
}
- created, _, err := h.ipc.Database.ApprovalComment.CreateApprovalCommentDB(ctx, nil, comment, true) //nolint:errcheck
+ _, _, err = h.ipc.Database.ApprovalComment.CreateApprovalCommentDB(ctx, nil, comment)
if err != nil {
sendText(bot, chatID, "⚠️ Ошибка при создании комментария: "+err.Error())
return false
}
sendText(bot, chatID, "✅ Ответ отправлен.")
- h.notifyAllParticipantsAboutComment(bot, ctx, approval, user, created, telegramID)
+ h.notifyAllParticipantsAboutComment(bot, ctx, approval, user, comment, telegramID)
return true
}
+
+func (h *Handler) HandleViewCommentsCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64) {
+ ctx := context.Background()
+ chatID := cq.Message.Chat.ID
+
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+
+ comments, err := h.ipc.Database.ApprovalComment.GetCommentsByApprovalIDDB(ctx, approvalID)
+ if err != nil {
+ logrus.Errorf("HandleViewCommentsCallback: GetCommentsByApprovalIDDB err=%v", err)
+ sendText(bot, chatID, "⚠️ Ошибка при получении комментариев.")
+ return
+ }
+
+ if len(comments) == 0 {
+ sendText(bot, chatID, fmt.Sprintf("📭 По заявке #%d пока нет комментариев.", approvalID))
+ return
+ }
+
+ var sb strings.Builder
+ sb.WriteString(fmt.Sprintf("💬 Комментарии по заявке #%d (%d):\n", approvalID, len(comments)))
+
+ for _, c := range comments {
+ if c.UserID == nil || c.Comment == nil {
+ continue
+ }
+ user, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *c.UserID)
+ name := "—"
+ if user != nil && user.FullName != nil {
+ name = *user.FullName
+ }
+ timestamp := "—"
+ if c.CreatedAt != nil {
+ timestamp = c.CreatedAt.Format("02.01.2006 15:04")
+ }
+ sb.WriteString(fmt.Sprintf("\n👤 %s (%s):\n%s\n", name, timestamp, *c.Comment))
+ }
+
+ msg := tgbotapi.NewMessage(chatID, sb.String())
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildCommentNotificationKeyboard(approvalID, h.GetCommentsCount(ctx, approvalID))
+ bot.Send(msg) //nolint:errcheck
+}
+
+// getChatParticipants собирает всех участников "виртуального чата" заявки:
+// инициатор, активный согласующий, доп. согласующие, исполнители,
+// наблюдатели категории/темы, доп. наблюдатели.
+// getChatParticipants собирает всех участников "виртуального чата" заявки:
+// инициатор, ПРОШЛЫЕ и текущий согласующие, доп. согласующие, исполнители,
+// наблюдатели категории/темы, доп. наблюдатели.
+func (h *Handler) getChatParticipants(ctx context.Context, approval *typescore.Approval) []*typescore.User {
+ if approval == nil || approval.ID == nil {
+ return nil
+ }
+
+ seen := make(map[uint64]bool)
+ var result []*typescore.User
+
+ add := func(u *typescore.User) {
+ if u == nil || u.ID == nil || u.TelegramID == nil {
+ return
+ }
+ if seen[*u.ID] {
+ return
+ }
+ seen[*u.ID] = true
+ result = append(result, u)
+ }
+
+ // 1. Инициатор
+ if approval.InitiatorID != nil {
+ initiator, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID)
+ add(initiator)
+ }
+
+ // 2. ПРОШЛЫЕ и ТЕКУЩИЕ согласующие (все пройденные и активные шаги)
+ steps, _, _ := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalStep{ApprovalID: approval.ID},
+ })
+ for _, step := range steps {
+ if step.ApproverID == nil || step.Status == nil {
+ continue
+ }
+ // Добавляем тех, кто уже принял решение (approved/rejected) и кто думает сейчас (pending)
+ if *step.Status == "approved" || *step.Status == "pending" || *step.Status == "rejected" {
+ approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *step.ApproverID)
+ add(approver)
+ }
+ }
+
+ // 3. Дополнительные согласующие (ручные)
+ additionalApprovers, _, _ := h.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalAdditionalApprover{ApprovalID: approval.ID},
+ })
+ for _, aa := range additionalApprovers {
+ if aa.ApproverID == nil {
+ continue
+ }
+ u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *aa.ApproverID)
+ add(u)
+ }
+
+ // 4. Исполнители задач
+ tasks, _, _ := h.ipc.Database.ApprovalTasks.GetApprovalTasksListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalTask{ApprovalID: approval.ID},
+ })
+ for _, t := range tasks {
+ if t.ExecutorID == nil {
+ continue
+ }
+ u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *t.ExecutorID)
+ add(u)
+ }
+
+ // 5. Наблюдатели и контролёры
+ categoryCode := h.getTopicCodeByApproval(ctx, approval)
+ isFinal := approval.Status != nil &&
+ (*approval.Status == "approved" || *approval.Status == "rejected" || *approval.Status == "revoked")
+
+ if isFinal {
+ observers, _ := h.ipc.Database.User.GetObserversForApprovalDB(ctx, categoryCode, approval.TopicID)
+ for _, obs := range observers {
+ add(obs)
+ }
+ } else {
+ controllers, _ := h.ipc.Database.User.GetControllerObserversForApprovalDB(ctx, categoryCode, approval.TopicID)
+ for _, c := range controllers {
+ add(c)
+ }
+ }
+
+ // 6. Дополнительные наблюдатели (ручные)
+ additionalObservers, _, _ := h.ipc.Database.ApprovalAdditionalObserver.GetApprovalAdditionalObserversListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalAdditionalObserver{
+ ApprovalID: approval.ID,
+ },
+ })
+ for _, ao := range additionalObservers {
+ if ao.UserID == nil {
+ continue
+ }
+ u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *ao.UserID)
+ add(u)
+ }
+
+ return result
+}
+
+func (h *Handler) GetCommentsCount(ctx context.Context, approvalID uint64) int {
+ comments, err := h.ipc.Database.ApprovalComment.GetCommentsByApprovalIDDB(ctx, approvalID)
+ if err != nil {
+ return 0
+ }
+ return len(comments)
+}
+func (h *Handler) HandleCommentVisibilityCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, action string) {
+ ctx := context.Background()
+ telegramID := cq.From.ID
+ chatID := cq.Message.Chat.ID
+
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+
+ if action == "cancel" {
+ bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck
+ h.States.ClearCommentFlow(ctx, telegramID) //nolint:errcheck
+ sendText(bot, chatID, "❌ Добавление комментария отменено.")
+ return
+ }
+
+ state, err := h.States.GetCommentFlow(ctx, telegramID)
+ if err != nil || state == nil || state.Stage != "await_visibility" {
+ bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck
+ return
+ }
+
+ user, _ := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
+ approval, _ := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, state.ApprovalID)
+
+ // Если выбрали "Конкретным" -> показываем меню мультиселекта
+ if action == "specific" {
+ state.Stage = "await_targets"
+ h.States.SetCommentFlow(ctx, telegramID, state) //nolint:errcheck
+
+ participants := h.getFilteredParticipants(ctx, approval, user)
+ editMsg := tgbotapi.NewEditMessageTextAndMarkup(chatID, cq.Message.MessageID,
+ "👤 Выберите, кого нужно уведомить:",
+ keyboard.BuildCommentTargetsMenu(participants, state.Targets),
+ )
+ editMsg.ParseMode = "HTML"
+ bot.Request(editMsg) //nolint:errcheck
+ return
+ }
+
+ // ─── Если "Всем" или "Без пушей" ───
+ bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck
+
+ // Создаем коммент в базе
+ comment := &typescore.ApprovalComment{
+ ApprovalID: &state.ApprovalID,
+ UserID: user.ID,
+ Comment: &state.Text,
+ }
+ h.ipc.Database.ApprovalComment.CreateApprovalCommentDB(ctx, nil, comment) //nolint:errcheck
+
+ userName := "—"
+ if user.FullName != nil {
+ userName = *user.FullName
+ }
+
+ statusText := "оставлен как дополнение"
+ if action == "all" {
+ statusText = "отправлен всем участникам"
+ h.notifyAllParticipantsAboutComment(bot, ctx, approval, user, comment, telegramID)
+ }
+
+ sendText(bot, chatID, fmt.Sprintf(
+ "✅ Комментарий %s\n\n"+
+ "📋 Заявка: #%d\n"+
+ "👤 Автор: %s\n"+
+ "💬 Текст: %s",
+ statusText, state.ApprovalID, userName, state.Text,
+ ))
+
+ h.States.ClearCommentFlow(ctx, telegramID) //nolint:errcheck
+}
+
+func (h *Handler) HandleCommentTargetToggle(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, targetIDStr string) {
+ ctx := context.Background()
+ telegramID := cq.From.ID
+
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+
+ state, err := h.States.GetCommentFlow(ctx, telegramID)
+ if err != nil || state == nil || state.Stage != "await_targets" {
+ return
+ }
+
+ targetID := parseID("id:"+targetIDStr, "id:") // Используем вашу функцию parseID
+ if state.Targets == nil {
+ state.Targets = make(map[uint64]bool)
+ }
+
+ if state.Targets[targetID] {
+ delete(state.Targets, targetID)
+ } else {
+ state.Targets[targetID] = true
+ }
+
+ h.States.SetCommentFlow(ctx, telegramID, state) //nolint:errcheck
+
+ user, _ := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
+ approval, _ := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, state.ApprovalID)
+ participants := h.getFilteredParticipants(ctx, approval, user)
+
+ edit := tgbotapi.NewEditMessageReplyMarkup(cq.Message.Chat.ID, cq.Message.MessageID,
+ keyboard.BuildCommentTargetsMenu(participants, state.Targets),
+ )
+ bot.Request(edit) //nolint:errcheck
+}
+
+func (h *Handler) HandleCommentTargetDone(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
+
+ state, err := h.States.GetCommentFlow(ctx, telegramID)
+ if err != nil || state == nil || state.Stage != "await_targets" {
+ return
+ }
+
+ if len(state.Targets) == 0 {
+ sendText(bot, chatID, "⚠️ Вы не выбрали ни одного участника. Выберите хотя бы одного или нажмите «Назад».")
+ return
+ }
+
+ bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck
+
+ user, _ := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
+ approval, _ := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, state.ApprovalID)
+
+ // Записываем комментарий
+ comment := &typescore.ApprovalComment{
+ ApprovalID: &state.ApprovalID,
+ UserID: user.ID,
+ Comment: &state.Text,
+ }
+ h.ipc.Database.ApprovalComment.CreateApprovalCommentDB(ctx, nil, comment) //nolint:errcheck
+
+ userName := "—"
+ if user.FullName != nil {
+ userName = *user.FullName
+ }
+
+ sendText(bot, chatID, fmt.Sprintf(
+ "✅ Комментарий отправлен выбранным участникам\n\n"+
+ "📋 Заявка: #%d\n"+
+ "👤 Автор: %s\n"+
+ "💬 Текст: %s",
+ state.ApprovalID, userName, state.Text,
+ ))
+
+ h.notifySpecificParticipantsAboutComment(bot, ctx, approval, user, comment, state.Targets)
+
+ h.States.ClearCommentFlow(ctx, telegramID) //nolint:errcheck
+}
+
+func (h *Handler) HandleCommentTargetBack(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery) {
+ ctx := context.Background()
+ telegramID := cq.From.ID
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+
+ state, err := h.States.GetCommentFlow(ctx, telegramID)
+ if err == nil && state != nil {
+ state.Stage = "await_visibility"
+ h.States.SetCommentFlow(ctx, telegramID, state) //nolint:errcheck
+
+ msg := tgbotapi.NewEditMessageTextAndMarkup(cq.Message.Chat.ID, cq.Message.MessageID,
+ "💬 Комментарий сохранен.\n\nВыберите, кому отправить уведомление:",
+ keyboard.BuildCommentVisibilityMenu())
+ msg.ParseMode = "HTML"
+ bot.Request(msg) //nolint:errcheck
+ }
+}
+
+// ── Вспомогательные функции ──
+
+// getFilteredParticipants возвращает участников чата заявки, исключая самого комментатора
+func (h *Handler) getFilteredParticipants(ctx context.Context, approval *typescore.Approval, excludeUser *typescore.User) []*typescore.User {
+ all := h.getChatParticipants(ctx, approval)
+ var filtered []*typescore.User
+ for _, u := range all {
+ if excludeUser != nil && excludeUser.ID != nil && u.ID != nil && *u.ID == *excludeUser.ID {
+ continue // Пропускаем автора
+ }
+ filtered = append(filtered, u)
+ }
+ return filtered
+}
+
+// notifySpecificParticipantsAboutComment рассылает комментарий только тем, чьи ID есть в мапе targets
+func (h *Handler) notifySpecificParticipantsAboutComment(
+ bot *tgbotapi.BotAPI,
+ ctx context.Context,
+ approval *typescore.Approval,
+ commenter *typescore.User,
+ comment *typescore.ApprovalComment,
+ targets map[uint64]bool,
+) {
+ 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,
+ )
+
+ commentsCount := h.GetCommentsCount(ctx, *approval.ID)
+ participants := h.getChatParticipants(ctx, approval)
+
+ for _, u := range participants {
+ if u.ID == nil || u.TelegramID == nil {
+ continue
+ }
+ if !targets[*u.ID] { // Проверяем, отмечен ли участник
+ continue
+ }
+ msg := tgbotapi.NewMessage(*u.TelegramID, text)
+ msg.ParseMode = "HTML"
+
+ // Используем клавиатуру для возможности быстро ответить, как и в общей рассылке
+ msg.ReplyMarkup = keyboard.BuildCommentReplyKeyboard(*approval.ID, commentsCount)
+ bot.Send(msg) //nolint:errcheck
+ }
+}
diff --git a/service/telegram_service/handlers/approval/handler_decision.go b/service/telegram_service/handlers/approval/handler_decision.go
index b1606f0..2dc7626 100644
--- a/service/telegram_service/handlers/approval/handler_decision.go
+++ b/service/telegram_service/handlers/approval/handler_decision.go
@@ -8,6 +8,7 @@ import (
"fmt"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"github.com/sirupsen/logrus"
+ "html"
"strings"
"time"
)
@@ -47,15 +48,16 @@ func (h *Handler) processNextStepOrComplete(bot *tgbotapi.BotAPI, ctx context.Co
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 {
+ 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 {
+ // ⏳ ПРОВЕРКА ДАТЫ ТУТ
+ if deleg.ValidUntil != nil && deleg.ValidUntil.After(time.Now()) {
delegate, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *deleg.DelegateID)
if delegate != nil && delegate.TelegramID != nil {
actualApprover = delegate
@@ -64,15 +66,19 @@ func (h *Handler) processNextStepOrComplete(bot *tgbotapi.BotAPI, ctx context.Co
}
}
}
- 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 {
+ }
+
+ 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 {
+ // ⏳ И ТУТ
+ if deleg.ValidUntil != nil && deleg.ValidUntil.After(time.Now()) {
delegate, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *deleg.DelegateID)
if delegate != nil && delegate.TelegramID != nil {
actualApprover = delegate
@@ -85,23 +91,23 @@ func (h *Handler) processNextStepOrComplete(bot *tgbotapi.BotAPI, ctx context.Co
}
}
+ currentApproverName := "—"
+ if currentStep.ApproverNameSnapshot != nil {
+ currentApproverName = *currentStep.ApproverNameSnapshot
+ }
+
+ nextApproverName := "—"
+ if actualApprover != nil && actualApprover.FullName != nil {
+ nextApproverName = *actualApprover.FullName
+ }
+
// Уведомляем инициатора о прогрессе
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
+ content = html.EscapeString(*approval.Content)
}
progressText := fmt.Sprintf(
@@ -159,6 +165,31 @@ func (h *Handler) processNextStepOrComplete(bot *tgbotapi.BotAPI, ctx context.Co
notifier.NotifyApprover(bot, actualApprover, initiator, approval, collected)
}
+ // Уведомляем наблюдателей-контролёров о прогрессе согласования
+ if controllers, cErr := h.ipc.Database.User.GetControllerObserversForApprovalDB(ctx, categoryCode, approval.TopicID); cErr != nil {
+ logrus.Warnf("processNextStepOrComplete: GetControllerObserversForApprovalDB err=%v", cErr)
+ } else if len(controllers) > 0 {
+ commentsCount := h.GetCommentsCount(ctx, approvalID)
+ commentsSection := h.formatCommentsSection(ctx, approvalID, 4)
+
+ controllerText := fmt.Sprintf(
+ "👁 Заявка #%d передана следующему согласующему\n\n"+
+ "✅ Согласовал: %s\n"+
+ "⏳ Передано: %s\n\n%s%s",
+ approvalID, currentApproverName, nextApproverName, approvalCard, commentsSection,
+ )
+
+ for _, controller := range controllers {
+ if controller.TelegramID == nil {
+ continue
+ }
+ controllerMsg := tgbotapi.NewMessage(*controller.TelegramID, controllerText)
+ controllerMsg.ParseMode = "HTML"
+ controllerMsg.ReplyMarkup = keyboard.BuildObserverActions(approvalID, "", "pending", len(approval.Files), commentsCount)
+ bot.Send(controllerMsg) //nolint:errcheck
+ }
+ }
+
if actualApprover != nextApprover && nextApprover != nil && nextApprover.TelegramID != nil {
delegateName := "—"
if actualApprover != nil && actualApprover.FullName != nil {
@@ -180,6 +211,8 @@ func (h *Handler) processNextStepOrComplete(bot *tgbotapi.BotAPI, ctx context.Co
approval.Status = &approvedStatus
h.ipc.Database.Approval.UpdateApprovalDB(ctx, nil, approval) //nolint:errcheck
+ h.activatePendingDelegation(bot, ctx, approval)
+
lastStepIsDelegate := currentStep.ApproverID != nil && *currentStep.ApproverID != actualExecutorID
if currentStep.ApproverID != nil {
@@ -243,16 +276,38 @@ func (h *Handler) processNextStepOrComplete(bot *tgbotapi.BotAPI, ctx context.Co
}
}
- directors, _ := h.ipc.Database.User.GetDirectorsDB(ctx)
- for _, director := range directors {
+ var subscribedDirectors []*typescore.User
+ if approval.TopicID != nil {
+ topicForCategory, err := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID)
+ if err == nil && topicForCategory != nil && topicForCategory.CategoryID != nil {
+ subscribedDirectors, err = h.ipc.Database.DirectorNotifications.GetDirectorsSubscribedToCategoryDB(ctx, *topicForCategory.CategoryID)
+ if err != nil {
+ logrus.Warnf("processNextStepOrComplete: GetDirectorsSubscribedToCategoryDB err=%v", err)
+ }
+ }
+ }
+
+ for _, director := range subscribedDirectors {
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)
+ observers, obsErr := h.ipc.Database.User.GetObserversForApprovalDB(ctx, categoryCode, approval.TopicID)
+ if obsErr != nil {
+ logrus.Errorf("❌ processNextStepOrComplete: GetObserversForApprovalDB err=%v (categoryCode=%s, topicID=%v)",
+ obsErr, categoryCode, approval.TopicID)
+ } else {
+ logrus.Infof("👁 processNextStepOrComplete: found %d observers for approvalID=%d categoryCode=%s topicID=%v",
+ len(observers), approvalID, categoryCode, approval.TopicID)
+
+ if len(observers) > 0 {
+ stepApprover, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *currentStep.ApproverID)
+ notifier.NotifyObserversDecision(bot, observers, initiator, stepApprover, approval, collected)
+ } else {
+ logrus.Warnf("⚠️ processNextStepOrComplete: no observers found for categoryCode=%s topicID=%v",
+ categoryCode, approval.TopicID)
+ }
}
}
@@ -339,7 +394,7 @@ func (h *Handler) handleDecision(
topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID)
content := "—"
if approval.Content != nil {
- content = *approval.Content
+ content = html.EscapeString(*approval.Content)
}
approvalCard := fmt.Sprintf(
@@ -355,7 +410,7 @@ func (h *Handler) handleDecision(
}
notifier := NewNotifier(h.ipc, topic)
collected := h.getCollectedFromApproval(ctx, approval)
- now := time.Now()
+ now := time.Now().UTC()
// 🚀 Вспомогательная функция: сохранить решение/комментарий в общую таблицу комментариев
saveCommentToApproval := func(commentText string) {
@@ -406,7 +461,7 @@ func (h *Handler) handleDecision(
}
notifier.NotifyInitiatorRejected(bot, initiator, stepApprover, approval, collected, comment)
}
- if observers, err := h.ipc.Database.User.GetObserversForCategoryDB(ctx, categoryCode); err == nil && len(observers) > 0 {
+ if observers, err := h.ipc.Database.User.GetObserversForApprovalDB(ctx, categoryCode, approval.TopicID); err == nil && len(observers) > 0 {
var stepApprover *typescore.User
if stepApproverID != nil {
stepApprover, _ = h.ipc.Database.User.GetUserByIDDB(ctx, *stepApproverID)
@@ -417,9 +472,6 @@ func (h *Handler) handleDecision(
}
}
- // ==========================================
- // === БЛОК ОТКЛОНЕНИЯ ===
- // ==========================================
if !approved {
if isAdditionalApprover {
rejectedStatus := "rejected"
@@ -533,7 +585,7 @@ func (h *Handler) handleDecision(
// ==========================================
// Запрос обязательного комментария для первого шага
- if requireComment && comment == "" {
+ if requireComment && comment == "" && !isAdditionalApprover {
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)
@@ -580,9 +632,40 @@ func (h *Handler) handleDecision(
saveCommentToApproval(commentText)
}
- mainStep, _ := h.ipc.Database.ApprovalStep.GetActiveStepDB(ctx, approvalID)
+ allSteps, _, _ := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalStep{ApprovalID: &approvalID},
+ })
- if mainStep != nil && mainStep.ApproverID != nil && *mainStep.ApproverID != currentUserID {
+ var mainStep *typescore.ApprovalStep
+
+ for _, s := range allSteps {
+ if s.Status != nil && *s.Status == "pending" {
+ mainStep = s
+ break
+ }
+ }
+
+ if mainStep == nil {
+ var highestApproved *typescore.ApprovalStep
+ for _, s := range allSteps {
+ if s.Status != nil && *s.Status == "approved" {
+ if highestApproved == nil || (s.StepOrder != nil && highestApproved.StepOrder != nil && *s.StepOrder > *highestApproved.StepOrder) {
+ highestApproved = s
+ }
+ }
+ }
+ mainStep = highestApproved
+ }
+
+ if mainStep == nil {
+ logrus.Warnf("handleDecision: active step not found approvalID=%d (доп. согласующий userID=%d)", approvalID, currentUserID)
+ if approverChatID != 0 {
+ sendText(bot, approverChatID, "⚠️ Шаг согласования не найден или уже обработан.")
+ }
+ return
+ }
+
+ if mainStep.ApproverID != nil && *mainStep.ApproverID != currentUserID {
mainApprover, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *mainStep.ApproverID)
if mainApprover != nil && mainApprover.TelegramID != nil {
addApproverName := "—"
@@ -599,15 +682,6 @@ func (h *Handler) handleDecision(
}
}
- 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 {
@@ -623,7 +697,7 @@ func (h *Handler) handleDecision(
}
}
- mainApproverApproved := step.Status != nil && *step.Status == "approved"
+ mainApproverApproved := mainStep.Status != nil && *mainStep.Status == "approved"
if approverChatID != 0 {
pendingCount, pendingNames := getPendingAdditionalInfo()
@@ -640,8 +714,8 @@ func (h *Handler) handleDecision(
} else {
// 🚀 Все доп. согласующие одобрили, но нужно проверить, последний ли это шаг
var currentOrder int
- if step.StepOrder != nil {
- currentOrder = *step.StepOrder
+ if mainStep.StepOrder != nil {
+ currentOrder = *mainStep.StepOrder
}
if isLastStep(currentOrder) {
sendText(bot, approverChatID, fmt.Sprintf("✅ Вы одобрили заявку #%d\n\n%s\n\nВсе согласующие одобрили заявку.", approvalID, approvalCard))
@@ -652,7 +726,16 @@ func (h *Handler) handleDecision(
}
if mainApproverApproved && allAdditionalApproved {
- h.processNextStepOrComplete(bot, ctx, approval, step, approvalCard, categoryCode, notifier, initiator, collected, currentUserID)
+ // 🩹 ФИКС 2: передаём исполнителя ОСНОВНОГО шага (mainStep.ApproverID),
+ // а не currentUserID (доп. согласующего). Иначе
+ // processNextStepOrComplete считает доп. согласующего "делегатом"
+ // основного согласующего только из-за разных ID — и рассылает
+ // неверные уведомления вида "ваш делегат согласовал заявку".
+ mainExecutorID := currentUserID
+ if mainStep.ApproverID != nil {
+ mainExecutorID = *mainStep.ApproverID
+ }
+ h.processNextStepOrComplete(bot, ctx, approval, mainStep, approvalCard, categoryCode, notifier, initiator, collected, mainExecutorID)
}
return
}
diff --git a/service/telegram_service/handlers/approval/handler_delegation.go b/service/telegram_service/handlers/approval/handler_delegation.go
index f52077c..cb31431 100644
--- a/service/telegram_service/handlers/approval/handler_delegation.go
+++ b/service/telegram_service/handlers/approval/handler_delegation.go
@@ -278,8 +278,6 @@ func (h *Handler) HandleDelegationDateInput(bot *tgbotapi.BotAPI, msg *tgbotapi.
return true
}
- // ИСПРАВЛЕНИЕ 1: Проверяем, является ли текущий пользователь делегатом
- // Если да - создаём делегирование от имени оригинального согласующего
actualDelegatorID := user.ID
if delegationState.TopicID > 0 {
@@ -648,21 +646,45 @@ func (h *Handler) HandleDelegationExtendInput(bot *tgbotapi.BotAPI, msg *tgbotap
}
func (h *Handler) getApproverCategories(ctx context.Context, userID uint64) ([]*typescore.ApprovalTopicCategory, error) {
+ categoryIDs := make(map[uint64]bool)
+
hierarchies, _, err := h.ipc.Database.UserHierarchy.GetUserHierarchyListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.UserHierarchy{
ApproverID: &userID,
},
})
- if err != nil {
- return nil, err
+ if err == nil {
+ 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
+ }
+ }
+ // Если в UserHierarchy права могут выдаваться сразу на категорию (при наличии такого поля):
+ if hier.TopicCategoryID != nil {
+ categoryIDs[*hier.TopicCategoryID] = true
+ }
+ }
}
- 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
+ isActive := true
+ delegations, _, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalDelegation{
+ DelegateID: &userID,
+ IsActive: &isActive,
+ },
+ })
+ if err == nil {
+ for _, del := range delegations {
+ if del.TopicID != nil {
+ topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *del.TopicID)
+ if topic != nil && topic.CategoryID != nil {
+ categoryIDs[*topic.CategoryID] = true
+ }
+ }
+ if del.CategoryID != nil {
+ categoryIDs[*del.CategoryID] = true
}
}
}
diff --git a/service/telegram_service/handlers/approval/handler_delegation_tasks.go b/service/telegram_service/handlers/approval/handler_delegation_tasks.go
new file mode 100644
index 0000000..71edf58
--- /dev/null
+++ b/service/telegram_service/handlers/approval/handler_delegation_tasks.go
@@ -0,0 +1,633 @@
+package approval
+
+import (
+ "bitrix_balancer_api/core/lib/external/tgkit"
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/core/utilscore"
+ "bitrix_balancer_api/telegram_service/keyboard"
+ "bitrix_balancer_api/telegram_service/state"
+ "context"
+ "fmt"
+ "sort"
+ "strings"
+ "time"
+
+ tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
+ "github.com/sirupsen/logrus"
+)
+
+func (h *Handler) HandleTaskDelegatedRightsList(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) {
+ h.HandleTaskDelegatedRightsListPage(bot, chatID, telegramID, 0, 0)
+}
+
+func (h *Handler) HandleTaskDelegatedRightsListPage(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.TaskDelegation.GetTaskDelegationsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.TaskDelegation{
+ DelegatorID: user.ID,
+ IsActive: &isActive,
+ },
+ })
+ if err != nil {
+ logrus.Errorf("HandleTaskDelegatedRightsList: GetTaskDelegationsListDB 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.BuildTaskDelegatedRightsList(delegations, page, ctx, h.ipc)
+ bot.Send(msg) //nolint:errcheck
+}
+
+func (h *Handler) HandleTaskDelegatedRightDetail(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.TaskDelegation.GetTaskDelegationByIDDB(ctx, delegationID)
+ if err != nil || delegation == nil {
+ sendText(bot, chatID, "⚠️ Делегирование не найдено.")
+ return
+ }
+
+ 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",
+ delegationID, delegateName, validUntil,
+ )
+
+ msg := tgbotapi.NewMessage(chatID, text)
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildTaskDelegationActions(delegationID)
+ bot.Send(msg) //nolint:errcheck
+}
+
+func (h *Handler) HandleTaskDelegationRevoke(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.TaskDelegation.GetTaskDelegationByIDDB(ctx, delegationID)
+ if err != nil || delegation == nil {
+ sendText(bot, chatID, "⚠️ Делегирование не найдено.")
+ return
+ }
+
+ now := time.Now()
+ isActive := false
+ delegation.ValidUntil = &now
+ delegation.IsActive = &isActive
+
+ _, _, err = h.ipc.Database.TaskDelegation.UpdateTaskDelegationDB(ctx, nil, delegation)
+ if err != nil {
+ logrus.Errorf("HandleTaskDelegationRevoke: UpdateTaskDelegationDB err=%v", err)
+ sendText(bot, chatID, "Ошибка при отзыве делегирования.")
+ return
+ }
+
+ sendText(bot, chatID, "✅ Делегирование задач досрочно отозвано.\nТеперь новые задачи будут приходить вам.")
+
+ // Уведомляем делегата
+ if delegation.DelegateID != nil {
+ delegate, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *delegation.DelegateID)
+ if delegate != nil && delegate.TelegramID != nil {
+ notifyMsg := tgbotapi.NewMessage(*delegate.TelegramID, "⚠️ Делегирование задач отозвано\n\nВам больше не будут приходить задачи этого пользователя.")
+ notifyMsg.ParseMode = "HTML"
+ bot.Send(notifyMsg) //nolint:errcheck
+ }
+ }
+}
+
+func (h *Handler) HandleTaskDelegationExtendPrompt(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.TaskDelegation.GetTaskDelegationByIDDB(ctx, delegationID)
+ if err != nil || delegation == nil {
+ sendText(bot, chatID, "⚠️ Делегирование не найдено.")
+ return
+ }
+
+ // Сохраняем ID делегирования для продления (с другим ключом, чтобы не пересекаться с заявками)
+ extendKey := fmt.Sprintf("task_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.BuildTaskDelegationExtendCancel(delegationID)
+ bot.Send(msg) //nolint:errcheck
+}
+
+func (h *Handler) HandleTaskDelegationExtendInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) bool {
+ ctx := context.Background()
+ telegramID := msg.From.ID
+ chatID := msg.Chat.ID
+
+ extendKey := fmt.Sprintf("task_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.TaskDelegation.GetTaskDelegationByIDDB(ctx, delegationID)
+ if err != nil || delegation == nil {
+ 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.TaskDelegation.UpdateTaskDelegationDB(ctx, nil, delegation)
+ if err != nil {
+ logrus.Errorf("HandleTaskDelegationExtendInput: UpdateTaskDelegationDB err=%v", err)
+ sendText(bot, chatID, "Ошибка при продлении делегирования задач.")
+ h.ipc.RedisClient.Del(ctx, extendKey) //nolint:errcheck
+ return true
+ }
+
+ h.ipc.RedisClient.Del(ctx, extendKey) //nolint:errcheck
+
+ sendText(bot, chatID, fmt.Sprintf(
+ "✅ Срок делегирования задач изменён.\n\n"+
+ "📅 Новый срок: %s",
+ 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",
+ validUntil.Format("02.01.2006 15:04"),
+ ))
+ notifyMsg.ParseMode = "HTML"
+ bot.Send(notifyMsg) //nolint:errcheck
+ }
+ }
+
+ return true
+}
+
+func (h *Handler) HandleTaskDelegationMenu(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) {
+ h.HandleTaskDelegationMenuPage(bot, chatID, telegramID, 0, 0)
+}
+
+func (h *Handler) HandleTaskDelegationMenuPage(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.ipc.Database.ApprovalTopicExecutor.GetExecutorCategoriesDB(ctx, *user.ID)
+ if err != nil || 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.BuildTaskDelegationCategoryMenu(categories, page)
+ bot.Send(msg) //nolint:errcheck
+}
+
+// HandleTaskDelegationAllTasks — выбор "Глобально (Все задачи)"
+func (h *Handler) HandleTaskDelegationAllTasks(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery) {
+ h.HandleTaskDelegationSelectUserPage(bot, cq, 0, 0, 0)
+}
+
+func (h *Handler) HandleTaskDelegationCategoryCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, categoryID uint64) {
+ h.HandleTaskDelegationCategoryCallbackPage(bot, cq, categoryID, 0)
+}
+
+func (h *Handler) HandleTaskDelegationCategoryCallbackPage(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
+ }
+
+ category, _ := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, categoryID)
+ categoryName := "—"
+ if category != nil && category.Name != nil {
+ categoryName = *category.Name
+ }
+
+ topics, err := h.ipc.Database.ApprovalTopicExecutor.GetExecutorTopicsByCategoryDB(ctx, *user.ID, categoryID)
+ if err != nil || len(topics) == 0 {
+ sendText(bot, chatID, "В этой категории нет доступных вам тем с задачами.")
+ return
+ }
+
+ msg := tgbotapi.NewMessage(chatID, fmt.Sprintf("📋 Категория: %s\n\nВыберите тему или делегируйте всю категорию целиком:", categoryName))
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildTaskDelegationTopicMenu(topics, categoryID, page)
+ bot.Send(msg) //nolint:errcheck
+}
+
+func (h *Handler) HandleTaskDelegationAllCategoryCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, categoryID uint64) {
+ h.HandleTaskDelegationSelectUserPage(bot, cq, categoryID, 0, 0)
+}
+
+func (h *Handler) HandleTaskDelegationTopicCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, topicID uint64) {
+ ctx := context.Background()
+ topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, topicID)
+ if topic == nil || topic.CategoryID == nil {
+ return
+ }
+ h.HandleTaskDelegationSelectUserPage(bot, cq, *topic.CategoryID, topicID, 0)
+}
+
+func (h *Handler) HandleTaskDelegationSelectUserPage(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
+ }
+
+ // Сохраняем стейт выбора (Глобально/Категория/Тема)
+ h.States.SetDelegation(ctx, telegramID, &state.DelegationFlowState{
+ CategoryID: categoryID,
+ TopicID: topicID,
+ Stage: "task_select_user",
+ }) //nolint:errcheck
+
+ users, _, err := h.ipc.Database.User.GetUsersListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.User{IsBlocked: utilscore.PointerToBool(false)},
+ Limit: utilscore.PointerToUint64(1000),
+ })
+ if err != nil {
+ 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
+ }
+
+ // 🚀 СОРТИРОВКА ПО АЛФАВИТУ
+ sort.Slice(availableUsers, func(i, j int) bool {
+ nameI, nameJ := "", ""
+ if availableUsers[i].FullName != nil {
+ nameI = *availableUsers[i].FullName
+ }
+ if availableUsers[j].FullName != nil {
+ nameJ = *availableUsers[j].FullName
+ }
+ return nameI < nameJ
+ })
+
+ scopeName := "🌍 Все задачи"
+ if topicID > 0 {
+ topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, topicID)
+ if topic != nil && topic.Name != nil {
+ scopeName = "Тема: " + *topic.Name
+ }
+ } else if categoryID > 0 {
+ 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.BuildTaskDelegationUserMenu(availableUsers, page)
+ // Обратите внимание: если ваша кнопка возврата в UserMenu ведет в меню, нужно чтобы она корректно работала
+ // (в BuildTaskDelegationUserMenu можно сделать кнопку Назад: "deleg_task_create").
+ bot.Send(msg) //nolint:errcheck
+}
+
+func (h *Handler) HandleTaskDelegationUserCallback(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
+ }
+
+ // 🚀 ПРОВЕРКА КОНФЛИКТОВ ДЕЛЕГИРОВАНИЯ ЗАДАЧ
+ existingDelegations, _, err := h.ipc.Database.TaskDelegation.GetTaskDelegationsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.TaskDelegation{
+ DelegatorID: user.ID,
+ IsActive: utilscore.PointerToBool(true),
+ },
+ })
+ if err == nil {
+ for _, d := range existingDelegations {
+ if h.isTaskDelegationConflict(ctx, d, delegationState.CategoryID, delegationState.TopicID) {
+ h.sendTaskDelegationConflictMessage(bot, chatID, d, telegramID)
+ return
+ }
+ }
+ }
+
+ delegationState.DelegateID = delegateID
+ delegationState.Stage = "task_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",
+ delegateName,
+ ))
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = tgkit.NewInlineKeyboard().Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "Отмена", "deleg_task_create")).Build()
+ bot.Send(msg) //nolint:errcheck
+}
+
+func (h *Handler) HandleTaskDelegationDateInput(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 != "task_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, _ := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
+ if user == nil || user.ID == nil {
+ return true
+ }
+
+ isActive := true
+ notifiedFalse := false
+ delegation := &typescore.TaskDelegation{
+ DelegatorID: user.ID,
+ DelegateID: &delegationState.DelegateID,
+ ValidUntil: &validUntil,
+ IsActive: &isActive,
+ NotifiedDay: ¬ifiedFalse,
+ Notified2h: ¬ifiedFalse,
+ }
+
+ if delegationState.TopicID > 0 {
+ delegation.TopicID = &delegationState.TopicID
+ }
+ if delegationState.CategoryID > 0 {
+ delegation.CategoryID = &delegationState.CategoryID
+ }
+
+ _, _, err = h.ipc.Database.TaskDelegation.CreateTaskDelegationDB(ctx, nil, delegation)
+ if err != nil {
+ sendText(bot, chatID, "Ошибка при создании делегирования задач.")
+ return true
+ }
+
+ h.States.ClearDelegation(ctx, telegramID)
+
+ scopeName := "🌍 Все задачи"
+ if delegationState.TopicID > 0 {
+ topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, delegationState.TopicID)
+ if topic != nil && topic.Name != nil {
+ scopeName = "Тема: " + *topic.Name
+ }
+ } else if delegationState.CategoryID > 0 {
+ 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
+}
+
+// isTaskDelegationConflict определяет, есть ли конфликт между существующим делегированием и новым
+func (h *Handler) isTaskDelegationConflict(ctx context.Context, d *typescore.TaskDelegation, newCategoryID, newTopicID uint64) bool {
+ // 1. Если существующее делегирование Глобальное (все задачи) -> оно конфликтует с чем угодно.
+ if d.TopicID == nil && d.CategoryID == nil {
+ return true
+ }
+ // 2. Если мы пытаемся создать Глобальное делегирование -> оно конфликтует, если есть ХОТЬ ЧТО-ТО активное.
+ if newTopicID == 0 && newCategoryID == 0 {
+ return true
+ }
+ // 3. Если существующее делегирование - Категория
+ if d.TopicID == nil && d.CategoryID != nil {
+ if *d.CategoryID == newCategoryID {
+ return true // пытаемся делегировать ту же категорию или тему в ней
+ }
+ if newTopicID > 0 {
+ topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, newTopicID)
+ if topic != nil && topic.CategoryID != nil && *topic.CategoryID == *d.CategoryID {
+ return true // пытаемся делегировать тему, категория которой уже делегирована
+ }
+ }
+ }
+ // 4. Если существующее делегирование - Тема
+ if d.TopicID != nil {
+ if newTopicID > 0 && *d.TopicID == newTopicID {
+ return true // Делегирована та же тема
+ }
+ if newTopicID == 0 && newCategoryID > 0 {
+ topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *d.TopicID)
+ if topic != nil && topic.CategoryID != nil && *topic.CategoryID == newCategoryID {
+ return true // Пытаемся делегировать всю категорию, но одна из тем в ней уже делегирована
+ }
+ }
+ }
+ return false
+}
+
+// sendTaskDelegationConflictMessage отправляет сообщение о конфликте
+func (h *Handler) sendTaskDelegationConflictMessage(bot *tgbotapi.BotAPI, chatID int64, existing *typescore.TaskDelegation, 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"+
+ "Эти задачи (или их часть) уже делегированы:\n"+
+ "📋 Объем: %s\n"+
+ "👤 Делегат: %s\n"+
+ "📅 Действует до: %s\n\n"+
+ "Сначала отзовите текущее делегирование в меню «Мои делегирования (Задачи)».",
+ scopeName, delegateName, validUntil,
+ ))
+ msg.ParseMode = "HTML"
+ bot.Send(msg) //nolint:errcheck
+ h.States.ClearDelegation(ctx, telegramID) //nolint:errcheck
+}
diff --git a/service/telegram_service/handlers/approval/handler_executor.go b/service/telegram_service/handlers/approval/handler_executor.go
index ee130d9..f2ee3b7 100644
--- a/service/telegram_service/handlers/approval/handler_executor.go
+++ b/service/telegram_service/handlers/approval/handler_executor.go
@@ -59,6 +59,34 @@ func (h *Handler) HandleMyTasks(bot *tgbotapi.BotAPI, chatID int64, telegramID i
}
}
+// formatTaskWithApprovalContext дополняет текст задачи номером и текстом заявки,
+// если они ещё не включены в сам TaskText.
+func formatTaskWithApprovalContext(approval *typescore.Approval, task *typescore.ApprovalTask) string {
+ taskText := "—"
+ if task != nil && task.TaskText != nil && *task.TaskText != "" {
+ taskText = *task.TaskText
+ }
+ if approval == nil || approval.ID == nil {
+ return taskText
+ }
+
+ content := "—"
+ if approval.Content != nil && *approval.Content != "" {
+ content = *approval.Content
+ }
+
+ // Если в тексте задачи уже записана шапка заявки — не дублируем
+ headerCheck := fmt.Sprintf("Заявка #%d", *approval.ID)
+ if strings.Contains(taskText, headerCheck) {
+ return taskText
+ }
+
+ return fmt.Sprintf(
+ "📌 Заявка #%d\n📝 Текст заявки: %s\n\nОписание задачи:\n%s",
+ *approval.ID, content, taskText,
+ )
+}
+
func (h *Handler) sendTaskCard(bot *tgbotapi.BotAPI, chatID int64, approval *typescore.Approval, task *typescore.ApprovalTask) {
ctx := context.Background()
@@ -76,29 +104,21 @@ func (h *Handler) sendTaskCard(bot *tgbotapi.BotAPI, chatID int64, approval *typ
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")
}
+ // Состав задачи теперь включает номер и текст заявки
+ fullTaskComposition := formatTaskWithApprovalContext(approval, task)
+
text := fmt.Sprintf(
- "📋 Задача по заявке #%d\n\n"+
+ "📋 Задача #%d (по заявке #%d)\n\n"+
"👤 Инициатор: %s\n"+
"📋 Тема: %s\n"+
- "📝 Текст заявки: %s\n"+
"📅 Создана: %s\n\n"+
- "🎯 Задача:\n%s",
- *approval.ID, initiatorName, topicFullName, content, createdAt, taskText,
+ "🎯 Состав задачи:\n%s",
+ *task.ID, *approval.ID, initiatorName, topicFullName, createdAt, fullTaskComposition,
)
allFiles, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID)
@@ -115,12 +135,12 @@ func (h *Handler) sendTaskCard(bot *tgbotapi.BotAPI, chatID int64, approval *typ
}
}
- commentsSection := h.formatCommentsSection(ctx, *approval.ID)
+ commentsSection := h.formatCommentsSection(ctx, *approval.ID, 4)
text += commentsSection
msg := tgbotapi.NewMessage(chatID, text)
msg.ParseMode = "HTML"
- msg.ReplyMarkup = keyboard.BuildExecutorTaskActions(*task.ID, *approval.ID, len(allFiles))
+ msg.ReplyMarkup = keyboard.BuildExecutorTaskActions(*task.ID, *approval.ID, len(allFiles), h.GetCommentsCount(ctx, *approval.ID))
bot.Send(msg) //nolint:errcheck
}
@@ -180,7 +200,7 @@ func (h *Handler) HandleCompleteTask(bot *tgbotapi.BotAPI, cq *tgbotapi.Callback
"⚠️ Для завершения необходимо прикрепить файл.\n\n"+
"Нажмите «📎 Прикрепить файл», прикрепите документ, затем нажмите «Выполнено».")
msg.ParseMode = "HTML"
- msg.ReplyMarkup = keyboard.BuildExecutorTaskActions(*task.ID, *approval.ID, len(files))
+ msg.ReplyMarkup = keyboard.BuildExecutorTaskActions(*task.ID, *approval.ID, len(files), h.GetCommentsCount(ctx, *approval.ID))
bot.Send(msg) //nolint:errcheck
return
}
@@ -198,11 +218,22 @@ func (h *Handler) HandleCompleteTask(bot *tgbotapi.BotAPI, cq *tgbotapi.Callback
return
}
+ content := "—"
+ if approval != nil && approval.Content != nil {
+ content = *approval.Content
+ }
+ taskText := "—"
+ if task.TaskText != nil {
+ taskText = *task.TaskText
+ }
+
sendText(bot, chatID, fmt.Sprintf(
"✅ Задача выполнена\n\n"+
- "📋 Заявка: #%d — %s\n\n"+
+ "📋 Заявка: #%d — %s\n"+
+ "📝 Текст заявки: %s\n"+
+ "🎯 Задача: %s\n\n"+
"Инициатор уведомлён.",
- *task.ApprovalID, topicName,
+ *task.ApprovalID, topicName, content, taskText,
))
h.activateNextTask(bot, ctx, approval, task)
@@ -221,12 +252,21 @@ func (h *Handler) HandleCompleteTask(bot *tgbotapi.BotAPI, cq *tgbotapi.Callback
content = *approval.Content
}
+ // 🆕 Текст самой выполненной задачи (task.TaskText) — раньше в
+ // уведомлении был только текст заявки целиком (approval.Content),
+ // а что конкретно исполнитель делал — нет.
+ completedTaskText := "—"
+ if task.TaskText != nil {
+ completedTaskText = *task.TaskText
+ }
+
notifyMsg := tgbotapi.NewMessage(*initiator.TelegramID, fmt.Sprintf(
"✅ Исполнитель завершил задачу\n\n"+
"📋 Заявка #%d — %s\n"+
"👤 Исполнитель: %s\n"+
- "📝 Текст: %s",
- *task.ApprovalID, topicName, executorName, content,
+ "📝 Текст: %s\n"+
+ "🎯 Задача: %s",
+ *task.ApprovalID, topicName, executorName, content, completedTaskText,
))
notifyMsg.ParseMode = "HTML"
bot.Send(notifyMsg) //nolint:errcheck
@@ -274,21 +314,38 @@ func (h *Handler) activateNextTask(bot *tgbotapi.BotAPI, ctx context.Context, ap
return
}
+ originalExecutor, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *nextTask.ExecutorID)
+ var actualExecutor *typescore.User
+
+ if originalExecutor != nil {
+ actual, isDelegated, orig := h.getActualTaskExecutor(ctx, originalExecutor, approval.TopicID)
+ actualExecutor = actual
+
+ // Если за время ожидания задачи человек ушел в отпуск/делегировал права,
+ // перезаписываем ExecutorID и текст задачи
+ if isDelegated && orig != nil && orig.FullName != nil {
+ nextTask.ExecutorID = actual.ID
+ newText := fmt.Sprintf("[Делегировано от: %s]\n%s", *orig.FullName, *nextTask.TaskText)
+ nextTask.TaskText = &newText
+ }
+ }
+
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 {
+ // Уведомляем АКТУАЛЬНОГО исполнителя
+ if actualExecutor != nil && actualExecutor.TelegramID != nil {
initiator, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID)
if initiator == nil {
return
}
- h.notifyExecutor(bot, ctx, executor, initiator, approval, nextTask)
+ h.notifyExecutor(bot, ctx, actualExecutor, initiator, approval, nextTask)
}
}
@@ -300,6 +357,37 @@ func (h *Handler) handleRevokeCancellationTask(bot *tgbotapi.BotAPI, ctx context
return
}
+ allSteps, _, err := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalStep{ApprovalID: approval.ID},
+ })
+ if err != nil {
+ logrus.Errorf("handleRevokeCancellationTask: GetApprovalStepsListDB err=%v", err)
+ }
+
+ cancelledStepStatus := "cancelled"
+ for _, s := range allSteps {
+ if s.Status == nil {
+ continue
+ }
+ if *s.Status == "pending" || *s.Status == "waiting" {
+ s.Status = &cancelledStepStatus
+ if _, _, err := h.ipc.Database.ApprovalStep.UpdateApprovalStepDB(ctx, nil, s); err != nil {
+ logrus.Errorf("handleRevokeCancellationTask: UpdateApprovalStepDB stepID=%v err=%v", s.ID, err)
+ }
+ }
+ }
+
+ additionalApprovers, _, _ := h.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalAdditionalApprover{ApprovalID: approval.ID},
+ })
+ cancelledAAStatus := "cancelled"
+ for _, aa := range additionalApprovers {
+ if aa.Status != nil && *aa.Status == "pending" {
+ aa.Status = &cancelledAAStatus
+ h.ipc.Database.ApprovalAdditionalApprover.UpdateApprovalAdditionalApproverDB(ctx, nil, aa) //nolint:errcheck
+ }
+ }
+
tasks, _, err := h.ipc.Database.ApprovalTasks.GetApprovalTasksListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.ApprovalTask{ApprovalID: approval.ID},
})
@@ -370,8 +458,11 @@ func (h *Handler) createReversalTask(
}
reversalText := fmt.Sprintf(
- "Обратить изменения по заявке #%d\n\nТема: %s\nИсходная задача: %s",
- *approval.ID, topicFullName, originalTaskText,
+ "Обратить изменения по заявке #%d\n"+
+ "Тема: %s\n"+
+ "Текст заявки: %s\n"+
+ "Исходная задача: %s",
+ *approval.ID, topicFullName, content, originalTaskText,
)
pendingStatus := "pending"
@@ -398,7 +489,7 @@ func (h *Handler) createReversalTask(
*approval.ID, topicFullName, content, reversalText,
))
msg.ParseMode = "HTML"
- msg.ReplyMarkup = keyboard.BuildExecutorTaskActions(*created.ID, *approval.ID, len(files))
+ msg.ReplyMarkup = keyboard.BuildExecutorTaskActions(*created.ID, *approval.ID, len(files), h.GetCommentsCount(ctx, *approval.ID))
bot.Send(msg) //nolint:errcheck
}
@@ -547,3 +638,55 @@ func (h *Handler) HandleExecutorAttachStart(bot *tgbotapi.BotAPI, cq *tgbotapi.C
msg.ReplyMarkup = keyboard.BuildAttachSessionKeyboard(approvalID, 0)
bot.Send(msg) //nolint:errcheck
}
+
+func (h *Handler) getExecutorCategories(ctx context.Context, userID uint64) ([]*typescore.ApprovalTopicCategory, error) {
+ categoryIDs := make(map[uint64]bool)
+
+ // 1. Проверяем напрямую через исполнителей тем (ApprovalTopicExecutor)
+ executors, _, err := h.ipc.Database.ApprovalTopicExecutor.GetApprovalTopicExecutorListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalTopicExecutor{
+ UserID: &userID,
+ IsActive: utilscore.PointerToBool(true),
+ },
+ })
+ if err == nil {
+ for _, exec := range executors {
+ if exec.TopicID != nil {
+ topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *exec.TopicID)
+ if topic != nil && topic.CategoryID != nil {
+ categoryIDs[*topic.CategoryID] = true
+ }
+ }
+ }
+ }
+
+ // 2. Проверяем через иерархию (UserHierarchy)
+ hierarchies, _, err := h.ipc.Database.UserHierarchy.GetUserHierarchyListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.UserHierarchy{
+ ApproverID: &userID,
+ },
+ })
+ if err == nil {
+ 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
+ }
+ }
+ if hier.TopicCategoryID != nil {
+ categoryIDs[*hier.TopicCategoryID] = 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
+}
diff --git a/service/telegram_service/handlers/approval/handler_observer.go b/service/telegram_service/handlers/approval/handler_observer.go
index 16b9b04..6fd39ab 100644
--- a/service/telegram_service/handlers/approval/handler_observer.go
+++ b/service/telegram_service/handlers/approval/handler_observer.go
@@ -2,6 +2,7 @@ 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"
"context"
@@ -30,7 +31,6 @@ func (h *Handler) HandleObservedApprovalsPage(bot *tgbotapi.BotAPI, chatID int64
return
}
- // Получаем все категории на которые у пользователя есть права наблюдателя
perms, err := h.ipc.Database.Permission.GetUserPermissionsDB(ctx, *user.ID, "observe")
if err != nil {
logrus.Errorf("HandleObservedApprovalsPage: GetUserPermissionsDB err=%v", err)
@@ -42,28 +42,38 @@ func (h *Handler) HandleObservedApprovalsPage(bot *tgbotapi.BotAPI, chatID int64
return
}
- // Собираем коды категорий
- var visibleTopics []approvalflow.Topic
- seenCodes := make(map[string]bool)
+ var visibleTopics []*typescore.ApprovalTopic
+ seenTopicIDs := make(map[uint64]bool)
for _, p := range perms {
- if p.TopicCategoryID == nil {
- continue
+ if p.TopicID != nil && !seenTopicIDs[*p.TopicID] {
+ topicDB, err := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *p.TopicID)
+ if err != nil || topicDB == nil || !*topicDB.IsActive {
+ continue
+ }
+ seenTopicIDs[*p.TopicID] = true
+ visibleTopics = append(visibleTopics, topicDB)
}
- 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
+ if p.TopicCategoryID != nil {
+ topics, _, err := h.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalTopic{
+ CategoryID: p.TopicCategoryID,
+ IsActive: utilscore.PointerToBool(true),
+ },
+ })
+ if err != nil {
+ logrus.Warnf("HandleObservedApprovalsPage: GetApprovalTopicsListDB err=%v", err)
+ continue
+ }
+ for _, t := range topics {
+ if t.ID == nil || seenTopicIDs[*t.ID] {
+ continue
+ }
+ seenTopicIDs[*t.ID] = true
+ visibleTopics = append(visibleTopics, t)
+ }
}
- visibleTopics = append(visibleTopics, topic)
}
if len(visibleTopics) == 0 {
@@ -71,13 +81,14 @@ func (h *Handler) HandleObservedApprovalsPage(bot *tgbotapi.BotAPI, chatID int64
return
}
+ logrus.Infof("👁 HandleObservedApprovalsPage: found %d topics for user %d", len(visibleTopics), *user.ID)
+
msg := tgbotapi.NewMessage(chatID, "👁 Наблюдение за согласованиями\n\nВыберите тему:")
msg.ParseMode = "HTML"
- msg.ReplyMarkup = keyboard.BuildObserverTopicMenu(visibleTopics, page)
+ msg.ReplyMarkup = keyboard.BuildObserverTopicMenuFromDB(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
@@ -86,32 +97,41 @@ func (h *Handler) HandleObserverTopicCallback(bot *tgbotapi.BotAPI, cq *tgbotapi
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)
+ msg := tgbotapi.NewMessage(chatID, "👁 Выберите статус заявок для отображения:")
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildObserverStatusFilterMenu(topicCode)
+ bot.Send(msg) //nolint:errcheck
+}
+
+func (h *Handler) HandleObserverStatusFilterCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, status, topicCode string, page int) {
+ 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
+
+ h.sendObserverTopicApprovals(bot, ctx, chatID, topicCode, status, page)
}
-// 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)
+
+ h.sendObserverTopicApprovals(bot, ctx, cq.Message.Chat.ID, topicCode, "all", 0)
}
-// 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
@@ -136,16 +156,6 @@ func (h *Handler) HandleObserverApprovalCallback(bot *tgbotapi.BotAPI, cq *tgbot
}
}
- // 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 := "—"
@@ -164,6 +174,15 @@ func (h *Handler) HandleObserverApprovalCallback(bot *tgbotapi.BotAPI, cq *tgbot
content = *approval.Content
}
+ // Получаем код темы для кнопки "Назад"
+ topicCode := ""
+ if approval.TopicID != nil {
+ if topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID); topic != nil && topic.Code != nil {
+ topicCode = *topic.Code
+ }
+ }
+
+ // ✅ ИСПРАВЛЕНО: approverName теперь используется в тексте
text := fmt.Sprintf(
"📄 Заявка #%d\n\n"+
"📋 Тема: %s\n"+
@@ -171,17 +190,48 @@ func (h *Handler) HandleObserverApprovalCallback(bot *tgbotapi.BotAPI, cq *tgbot
"🏢 Отдел: %s\n"+
"📅 Создана: %s\n"+
"📝 Содержание: %s\n\n"+
- "⏳ Ожидает решения: %s",
- approvalID, topicFullName, initiatorName, deptName, createdAt, content, approverName,
+ "🔄 У согласующего: %s\n"+
+ "📊 Статус: %s",
+ approvalID, topicFullName, initiatorName, deptName, createdAt, content, approverName, h.getStatusLabel(approval.Status),
)
msg := tgbotapi.NewMessage(chatID, text)
msg.ParseMode = "HTML"
- msg.ReplyMarkup = keyboard.BuildObserverApprovalDetail(approvalID, categoryCode)
+
+ // ✅ ИСПРАВЛЕНО: правильные аргументы (approvalID, topicCode, commentsCount)
+ msg.ReplyMarkup = keyboard.BuildObserverApprovalDetail(approvalID, topicCode, h.getCommentsCount(ctx, *approval.ID))
bot.Send(msg) //nolint:errcheck
}
-// HandleObserverReminderCallback — напоминание согласующему от наблюдателя.
+// ✅ ИСПРАВЛЕНО: добавлен вспомогательный метод
+func (h *Handler) getCommentsCount(ctx context.Context, approvalID uint64) int {
+ comments, err := h.ipc.Database.ApprovalComment.GetCommentsByApprovalIDDB(ctx, approvalID)
+ if err != nil {
+ return 0
+ }
+ return len(comments)
+}
+
+func (h *Handler) getStatusLabel(status *string) string {
+ if status == nil {
+ return "Неизвестно"
+ }
+ switch *status {
+ case "pending":
+ return "⏳ На согласовании"
+ case "approved":
+ return "✅ Согласована"
+ case "rejected":
+ return "❌ Отклонена"
+ case "revoked":
+ return "↩️ Отозвана"
+ case "revision":
+ return "🛠 На доработке"
+ default:
+ return *status
+ }
+}
+
func (h *Handler) HandleObserverReminderCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64) {
ctx := context.Background()
chatID := cq.Message.Chat.ID
@@ -240,7 +290,9 @@ func (h *Handler) HandleObserverReminderCallback(bot *tgbotapi.BotAPI, cq *tgbot
reminderMsg := tgbotapi.NewMessage(*approver.TelegramID, reminder)
reminderMsg.ParseMode = "HTML"
- reminderMsg.ReplyMarkup = keyboard.BuildApproverDecision(approvalID, status, len(files) > 0, len(files))
+
+ // ✅ ИСПРАВЛЕНО: добавлен 5-й аргумент commentsCount
+ reminderMsg.ReplyMarkup = keyboard.BuildApproverDecision(approvalID, status, len(files) > 0, len(files), h.getCommentsCount(ctx, *approval.ID))
bot.Send(reminderMsg) //nolint:errcheck
approverName := "согласующему"
@@ -250,41 +302,70 @@ func (h *Handler) HandleObserverReminderCallback(bot *tgbotapi.BotAPI, cq *tgbot
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)
+func (h *Handler) sendObserverTopicApprovals(bot *tgbotapi.BotAPI, ctx context.Context, chatID int64, topicCode, statusFilter string, page int) {
+ var approvals []*typescore.Approval
+ var err error
+ var topicName string
+
+ category, catErr := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByCodeDB(ctx, topicCode)
+ if catErr == nil && category != nil {
+ topicName = *category.Name
+ approvals, err = h.ipc.Database.Approval.GetApprovalsByCategoryDB(ctx, topicCode)
+ } else {
+ topic, topicErr := h.ipc.Database.ApprovalTopic.GetApprovalTopicByCodeDB(ctx, topicCode)
+ if topicErr != nil || topic == nil || topic.ID == nil {
+ sendText(bot, chatID, "⚠️ Тема не найдена.")
+ return
+ }
+ topicName = *topic.Name
+ approvals, _, err = h.ipc.Database.Approval.GetApprovalsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.Approval{
+ TopicID: topic.ID,
+ },
+ })
+ }
+
if err != nil {
- logrus.Errorf("sendObserverTopicApprovals: GetApprovalsByCategoryDB err=%v", err)
+ logrus.Errorf("sendObserverTopicApprovals: err=%v", err)
sendText(bot, chatID, "Ошибка при получении заявок.")
return
}
- // Только pending
- var pending []*typescore.Approval
+ var filtered []*typescore.Approval
for _, a := range approvals {
- if a.Status != nil && *a.Status == "pending" {
- pending = append(pending, a)
+ if a.Status == nil {
+ continue
+ }
+
+ if statusFilter == "all" {
+ if *a.Status == "pending" || *a.Status == "approved" {
+ filtered = append(filtered, a)
+ }
+ } else {
+ if *a.Status == statusFilter {
+ filtered = append(filtered, a)
+ }
}
}
- topic, _ := h.Registry.Get(topicCode)
- topicName := topicCode
- if topic != nil {
- topicName = topic.Name()
- }
+ if len(filtered) == 0 {
+ statusText := "ожидающих согласования"
+ if statusFilter == "approved" {
+ statusText = "согласованных"
+ } else if statusFilter == "all" {
+ statusText = "активных или согласованных"
+ }
- if len(pending) == 0 {
- msg := tgbotapi.NewMessage(chatID, fmt.Sprintf("👁 %s\n\nНет заявок, ожидающих согласования.", topicName))
+ msg := tgbotapi.NewMessage(chatID, fmt.Sprintf("👁 %s\n\nНет %s заявок.", topicName, statusText))
msg.ParseMode = "HTML"
- msg.ReplyMarkup = keyboard.BuildObserverApprovalList(nil, nil, nil)
+ msg.ReplyMarkup = keyboard.BuildObserverApprovalList(nil, nil, nil, statusFilter, topicCode, page)
bot.Send(msg) //nolint:errcheck
return
}
- // Пакетная загрузка инициаторов и отделов
initiators := make(map[uint64]*typescore.User)
departments := make(map[uint64]*typescore.Department)
- for _, a := range pending {
+ for _, a := range filtered {
if a.InitiatorID != nil {
if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *a.InitiatorID); u != nil {
initiators[*a.InitiatorID] = u
@@ -297,15 +378,21 @@ func (h *Handler) sendObserverTopicApprovals(bot *tgbotapi.BotAPI, ctx context.C
}
}
+ statusText := "Ожидают согласования"
+ if statusFilter == "approved" {
+ statusText = "Согласованные заявки"
+ } else if statusFilter == "all" {
+ statusText = "Активные и согласованные заявки"
+ }
+
msg := tgbotapi.NewMessage(chatID, fmt.Sprintf(
- "👁 %s\n\nОжидают согласования: %d", topicName, len(pending),
+ "👁 %s\n\n%s: %d", topicName, statusText, len(filtered),
))
msg.ParseMode = "HTML"
- msg.ReplyMarkup = keyboard.BuildObserverApprovalList(pending, initiators, departments)
+ msg.ReplyMarkup = keyboard.BuildObserverApprovalList(filtered, initiators, departments, statusFilter, topicCode, page)
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 {
diff --git a/service/telegram_service/handlers/approval/handler_report.go b/service/telegram_service/handlers/approval/handler_report.go
index 14bf7f8..5ad64c7 100644
--- a/service/telegram_service/handlers/approval/handler_report.go
+++ b/service/telegram_service/handlers/approval/handler_report.go
@@ -30,11 +30,10 @@ func (h *Handler) getTopicCodeByApproval(ctx context.Context, a *typescore.Appro
const reportDateLayout = "02.01.2006"
-// HandleReportMenu — первый шаг: показываем выбор типа отчёта.
// HandleReportMenu — сразу показываем выбор периода (тип отчёта один — согласования).
func (h *Handler) HandleReportMenu(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) {
ctx, cancel := context.WithTimeout(context.Background(), variables.ContextTimeoutBase)
- cancel()
+ defer cancel()
user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
if err != nil || user == nil || user.ID == nil {
diff --git a/service/telegram_service/handlers/approval/helper.go b/service/telegram_service/handlers/approval/helper.go
index e7ae3c5..8c8410f 100644
--- a/service/telegram_service/handlers/approval/helper.go
+++ b/service/telegram_service/handlers/approval/helper.go
@@ -12,6 +12,7 @@ import (
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"github.com/sirupsen/logrus"
"strings"
+ "time"
)
func sendText(bot *tgbotapi.BotAPI, chatID int64, text string) {
@@ -21,7 +22,47 @@ func sendText(bot *tgbotapi.BotAPI, chatID int64, text string) {
}
// submitApproval создаёт запись в БД и уведомляет согласующих.
-func (h *Handler) submitApproval(ctx context.Context, bot *tgbotapi.BotAPI, telegramID int64, flowState *state.ApprovalFlowState) (*typescore.Approval, error) {
+// submitApproval — точка входа. Если инициатор выбрал несколько систем
+// (мультиселект "systems"), создаёт по ОТДЕЛЬНОЙ заявке на каждую систему,
+// каждая — со своим порядком согласования. Если система одна или не задана —
+// поведение как раньше, одна заявка.
+func (h *Handler) submitApproval(ctx context.Context, bot *tgbotapi.BotAPI, telegramID int64, flowState *state.ApprovalFlowState) ([]*typescore.Approval, error) {
+ var systems []string
+ if s := flowState.Collected["systems"]; s != "" {
+ systems = strings.Split(s, ",")
+ for i := range systems {
+ systems[i] = strings.TrimSpace(systems[i])
+ }
+ }
+
+ if len(systems) <= 1 {
+ approval, err := h.submitApprovalForSystem(ctx, bot, telegramID, flowState, systems)
+ if err != nil {
+ return nil, err
+ }
+ return []*typescore.Approval{approval}, nil
+ }
+
+ var created []*typescore.Approval
+ for _, system := range systems {
+ approval, err := h.submitApprovalForSystem(ctx, bot, telegramID, flowState, []string{system})
+ if err != nil {
+ // Частичный отказ — откатываем уже созданные заявки по другим системам,
+ // чтобы не оставлять пользователя с "половиной" мультизаявки.
+ for _, a := range created {
+ h.ipc.Database.Approval.DeleteApprovalDB(ctx, a) //nolint:errcheck
+ }
+ return nil, fmt.Errorf("система %s: %w", system, err)
+ }
+ created = append(created, approval)
+ }
+
+ return created, nil
+}
+
+// submitApprovalForSystem создаёт ровно одну заявку для ровно одной системы
+// (или без привязки к системе, если systems пуст). Раньше это было телом
+func (h *Handler) submitApprovalForSystem(ctx context.Context, bot *tgbotapi.BotAPI, telegramID int64, flowState *state.ApprovalFlowState, systems []string) (*typescore.Approval, error) {
topic, err := h.Registry.Get(flowState.TopicCode)
if err != nil {
return nil, err
@@ -66,8 +107,9 @@ func (h *Handler) submitApproval(ctx context.Context, bot *tgbotapi.BotAPI, tele
Extra: make(map[string]string),
}
- if systems := flowState.Collected["systems"]; systems != "" {
- metadata.SelectedSystems = strings.Split(systems, ",")
+ // В отличие от старой версии — тут максимум одна система (эта заявка = эта система).
+ if len(systems) > 0 {
+ metadata.SelectedSystems = systems
}
for k, v := range flowState.Collected {
@@ -78,7 +120,7 @@ func (h *Handler) submitApproval(ctx context.Context, bot *tgbotapi.BotAPI, tele
metadataJSON, err := metadata.ToJSON()
if err != nil {
- logrus.Warnf("submitApproval: metadata marshal err=%v", err)
+ logrus.Warnf("submitApprovalForSystem: metadata marshal err=%v", err)
}
approval := &typescore.Approval{
@@ -104,7 +146,7 @@ func (h *Handler) submitApproval(ctx context.Context, bot *tgbotapi.BotAPI, tele
nameCopy := f.FileName
if base64Copy == "" || nameCopy == "" {
- logrus.Warnf("submitApproval: skipping empty file name=%q base64_len=%d", nameCopy, len(base64Copy))
+ logrus.Warnf("submitApprovalForSystem: skipping empty file name=%q base64_len=%d", nameCopy, len(base64Copy))
continue
}
@@ -115,23 +157,23 @@ func (h *Handler) submitApproval(ctx context.Context, bot *tgbotapi.BotAPI, tele
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)
+ logrus.Errorf("submitApprovalForSystem: CreateApprovalFileDB name=%s err=%v", nameCopy, err)
} else {
- logrus.Infof("submitApproval: saved file=%s approvalID=%d attachedByID=%d",
+ logrus.Infof("submitApprovalForSystem: 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)
+ logrus.Warnf("submitApprovalForSystem: GetFilesByApprovalIDDB err=%v", err)
}
created.Files = files
+ h.createPendingDelegation(ctx, initiator, flowState, created)
+
var approvers []*typescore.User
- // Если выбран первый согласующий по роли — он будет шагом 0
var firstRoleApprover *typescore.User
if flowState.SelectedFirstApproverID > 0 {
firstRoleApprover, err = h.ipc.Database.User.GetUserByIDDB(ctx, flowState.SelectedFirstApproverID)
@@ -140,46 +182,67 @@ func (h *Handler) submitApproval(ctx context.Context, bot *tgbotapi.BotAPI, tele
}
}
- // Если согласующий был выбран вручную - используем его
- if flowState.SelectedApproverID > 0 {
+ // ИСПРАВЛЕНО: раньше flowState.SelectedApproverID (ОДИН согласующий,
+ // выбранный вручную ДО разбивки заявки по системам) применялся
+ // одинаково в каждой итерации цикла по системам в submitApproval.
+ // Он подбирался из списка, отфильтрованного (после фикса
+ // getAvailableApproversForTopic) под ВСЕ выбранные системы сразу —
+ // но нет гарантии, что конкретно этот человек валиден именно для
+ // текущей system в этой итерации: например, при override
+ // "okb -> Иванов, 1c -> Петров" пользователь мог выбрать Иванова,
+ // и Иванов стал бы согласующим и по заявке на 1С тоже.
+ //
+ // flowState хранит только один ID на весь флоу, поэтому корректно
+ // "угадать" per-system выбор здесь невозможно без изменения модели
+ // состояния. Безопасное решение: ручной выбор применяем только когда
+ // заявка одна на одну систему (или система не важна). При мультисистемном
+ // сабмите ручной выбор игнорируется и согласующие резолвятся
+ // автоматически по иерархии для каждой системы отдельно — это не даёт
+ // назначить не подходящего человека согласующим по системе, для которой
+ // его не выбирали.
+ if flowState.SelectedApproverID > 0 && len(systems) <= 1 {
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 {
- // Получаем согласующих автоматически через иерархию
+ if flowState.SelectedApproverID > 0 {
+ logrus.Warnf(
+ "submitApprovalForSystem: ignoring manually selected approverID=%d for multi-system submission (systems=%v) — falling back to automatic hierarchy resolution to avoid assigning an approver not validated for this specific system",
+ flowState.SelectedApproverID, systems,
+ )
+ }
approvers, err = h.ipc.Database.UserHierarchy.GetApproversDB(ctx,
*initiator.ID,
*initiator.DepartmentID,
*approvalTopic.ID,
*approvalTopic.CategoryID,
+ systems,
)
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)
+ logrus.Warnf("submitApprovalForSystem: no approvers found for userID=%d deptID=%d topicID=%d systems=%v",
+ *initiator.ID, *initiator.DepartmentID, *approvalTopic.ID, systems)
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)
+ logrus.Infof("submitApprovalForSystem: approvalMode=%s for topicID=%d", *approvalTopic.ApprovalMode, *approvalTopic.ID)
} else {
- logrus.Warnf("submitApproval: approvalMode is NIL for topicID=%d — будет использован sequential!", *approvalTopic.ID)
+ logrus.Warnf("submitApprovalForSystem: approvalMode is NIL for topicID=%d — будет использован sequential!", *approvalTopic.ID)
}
for i, approver := range approvers {
@@ -197,7 +260,7 @@ func (h *Handler) submitApproval(ctx context.Context, bot *tgbotapi.BotAPI, tele
ids = append(ids, fmt.Sprintf("%d", *a.ID))
}
}
- logrus.Infof("submitApproval: priorityGroup[%d] contains approvers: %s (count=%d)", p, strings.Join(ids, ","), len(group))
+ logrus.Infof("submitApprovalForSystem: priorityGroup[%d] contains approvers: %s (count=%d)", p, strings.Join(ids, ","), len(group))
}
stepOrder := 0
@@ -212,7 +275,7 @@ func (h *Handler) submitApproval(ctx context.Context, bot *tgbotapi.BotAPI, tele
}
stepStatus := "waiting"
if priority == 0 {
- stepStatus = "pending" // первая группа активна сразу
+ stepStatus = "pending"
}
order := stepOrder
approverName := ""
@@ -232,12 +295,18 @@ func (h *Handler) submitApproval(ctx context.Context, bot *tgbotapi.BotAPI, tele
}
}
- // Сохраняем выбранных наблюдателей
if len(flowState.SelectedObserverIDs) > 0 {
h.saveSelectedObservers(ctx, *created.ID, *initiator.ID, flowState.SelectedObserverIDs)
}
- // === НОВЫЙ БЛОК: УВЕДОМЛЕНИЕ ВСЕХ ИЗ ПЕРВОЙ ГРУППЫ ===
+ controllers, cErr := h.ipc.Database.User.GetControllerObserversForApprovalDB(ctx, topic.Code(), approvalTopic.ID)
+ if cErr != nil {
+ logrus.Warnf("submitApprovalForSystem: GetControllerObserversForApprovalDB err=%v", cErr)
+ }
+ for _, controller := range controllers {
+ h.notifyControllerAboutCreation(bot, ctx, controller, initiator, created, flowState.Collected)
+ }
+
firstGroup := priorityGroups[0]
notifier := NewNotifier(h.ipc, topic)
@@ -246,39 +315,47 @@ func (h *Handler) submitApproval(ctx context.Context, bot *tgbotapi.BotAPI, tele
if actualApprover.TelegramID == nil {
if actualApprover.ID != nil {
- logrus.Warnf("submitApproval: approver.TelegramID is nil, userID=%d", *actualApprover.ID)
+ logrus.Warnf("submitApprovalForSystem: approver.TelegramID is nil, userID=%d", *actualApprover.ID)
}
continue
}
- // Проверяем делегирование для каждого согласующего
if approvalTopic.CategoryID != nil {
+ var foundDelegation bool
+
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 {
+ }}); err == nil {
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
+ if deleg.ValidUntil != nil && deleg.ValidUntil.After(time.Now()) {
+ delegate, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *deleg.DelegateID)
+ if delegate != nil && delegate.TelegramID != nil {
+ actualApprover = delegate
+ foundDelegation = true
+ break
+ }
}
}
}
- } else {
+ }
+
+ if !foundDelegation {
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 {
+ }}); err == nil {
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
+ if deleg.ValidUntil != nil && deleg.ValidUntil.After(time.Now()) {
+ delegate, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *deleg.DelegateID)
+ if delegate != nil && delegate.TelegramID != nil {
+ actualApprover = delegate
+ break
+ }
}
}
}
@@ -286,7 +363,16 @@ func (h *Handler) submitApproval(ctx context.Context, bot *tgbotapi.BotAPI, tele
}
}
- notifier.NotifyApprover(bot, actualApprover, initiator, created, flowState.Collected)
+ collectedForMessage := flowState.Collected
+ if len(systems) > 0 {
+ collectedForMessage = make(map[string]string, len(flowState.Collected))
+ for k, v := range flowState.Collected {
+ collectedForMessage[k] = v
+ }
+ collectedForMessage["systems"] = strings.Join(systems, ",")
+ }
+
+ notifier.NotifyApprover(bot, actualApprover, initiator, created, collectedForMessage)
}
return created, nil
@@ -624,17 +710,6 @@ func (h *Handler) buildApprovalCard(ctx context.Context, approval *typescore.App
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{
@@ -666,7 +741,7 @@ func (h *Handler) buildApprovalCard(ctx context.Context, approval *typescore.App
}
// Добавляем комментарии
- commentsSection := h.formatCommentsSection(ctx, approvalID)
+ commentsSection := h.formatCommentsSection(ctx, approvalID, 4)
card += commentsSection
return card
@@ -760,7 +835,9 @@ func (h *Handler) findStepForCurrentApprover(ctx context.Context, approvalID uin
for _, deleg := range allDelegations {
if deleg.DelegatorID != nil && *deleg.DelegatorID == *s.ApproverID &&
deleg.DelegateID != nil && *deleg.DelegateID == currentUserID {
- return s
+ if deleg.ValidUntil != nil && deleg.ValidUntil.After(time.Now()) {
+ return s
+ }
}
}
}
@@ -769,3 +846,9 @@ func (h *Handler) findStepForCurrentApprover(ctx context.Context, approvalID uin
return nil
}
+
+func parseID(data, prefix string) uint64 {
+ var id uint64
+ fmt.Sscanf(strings.TrimPrefix(data, prefix), "%d", &id)
+ return id
+}
diff --git a/service/telegram_service/handlers/approval/http_fetch.go b/service/telegram_service/handlers/approval/http_fetch.go
index 33677b5..c21b984 100644
--- a/service/telegram_service/handlers/approval/http_fetch.go
+++ b/service/telegram_service/handlers/approval/http_fetch.go
@@ -1,16 +1,23 @@
package approval
import (
- configcore "bitrix_balancer_api/core/config"
+ "bitrix_balancer_api/core/variables"
+ "bytes"
"context"
+ "crypto/tls"
"encoding/base64"
+ "encoding/json"
"errors"
"fmt"
- "github.com/sirupsen/logrus"
"io"
+ "net"
"net/http"
+ "net/url"
+ "strings"
"sync"
"time"
+
+ "github.com/sirupsen/logrus"
)
var (
@@ -18,21 +25,234 @@ var (
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")
+// APIProxyRequest описывает структуру тела запроса к прокси-сервису
+type APIProxyRequest struct {
+ URL string `json:"url"`
+ Method string `json:"method"`
+ Body interface{} `json:"body"`
+}
+
+// FileProxyTransport перехватывает GET-запросы на скачивание файлов и заворачивает их в API-прокси
+type FileProxyTransport struct {
+ wrapped http.RoundTripper
+
+ // Поля для fallback-механизма на бесплатные прокси
+ mu sync.RWMutex
+ fallbackMode bool
+ fallbackProxyURL string
+ fallbackTransport http.RoundTripper
+}
+
+func (t *FileProxyTransport) RoundTrip(req *http.Request) (*http.Response, error) {
+ t.mu.RLock()
+ fallbackMode := t.fallbackMode
+ fallbackTrans := t.fallbackTransport
+ currentFallbackURL := t.fallbackProxyURL
+ t.mu.RUnlock()
+
+ if fallbackMode && fallbackTrans != nil {
+ return t.executeFallback(req, fallbackTrans, currentFallbackURL)
}
+ proxyReqPayload := APIProxyRequest{
+ URL: req.URL.String(),
+ Method: req.Method,
+ Body: map[string]interface{}{},
+ }
+
+ proxyJsonBytes, err := json.Marshal(proxyReqPayload)
+ if err != nil {
+ return nil, fmt.Errorf("file proxy transport: failed to marshal payload: %w", err)
+ }
+
+ proxyReq, err := http.NewRequestWithContext(req.Context(), "POST", variables.ProxyForwardURL, bytes.NewReader(proxyJsonBytes))
+ if err != nil {
+ return nil, fmt.Errorf("file proxy transport: failed to create request: %w", err)
+ }
+
+ proxyReq.Header.Set("Content-Type", "application/json")
+ proxyReq.Header.Set(variables.ProxySecretHeader, variables.ProxySecretKey)
+
+ resp, err := t.wrapped.RoundTrip(proxyReq)
+ if err != nil {
+ logrus.Warnf("approval: custom gateway failed (%v), switching to free fallback proxies for files.", err)
+ return t.switchToFallbackAndExecute(req, "")
+ }
+
+ if resp.StatusCode != http.StatusOK {
+ defer resp.Body.Close()
+ errorBody, _ := io.ReadAll(resp.Body)
+ return nil, fmt.Errorf("file proxy returned status %d (%s): %s", resp.StatusCode, resp.Status, string(errorBody))
+ }
+
+ return resp, nil
+}
+
+func (t *FileProxyTransport) executeFallback(req *http.Request, trans http.RoundTripper, currentProxyURL string) (*http.Response, error) {
+ newReq := req.Clone(req.Context())
+
+ resp, err := trans.RoundTrip(newReq)
+ if err != nil {
+ // КРИТИЧНОЕ ИСПРАВЛЕНИЕ: Если ошибка вызвана таймаутом в функции скачивания
+ // (context deadline exceeded или canceled), то прокси жив, просто файл качался слишком долго.
+ // Не бракуем прокси и не ищем новый!
+ if errors.Is(req.Context().Err(), context.DeadlineExceeded) || errors.Is(req.Context().Err(), context.Canceled) || strings.Contains(err.Error(), "canceled") {
+ return nil, err
+ }
+
+ logrus.Warnf("approval: fallback proxy %s disconnected (%v), searching for a new one...", currentProxyURL, err)
+ return t.switchToFallbackAndExecute(req, currentProxyURL)
+ }
+ return resp, nil
+}
+
+func (t *FileProxyTransport) switchToFallbackAndExecute(req *http.Request, failedProxyURL string) (*http.Response, error) {
+ t.mu.Lock()
+ if t.fallbackMode && t.fallbackProxyURL != failedProxyURL {
+ savedTrans := t.fallbackTransport
+ currentURL := t.fallbackProxyURL
+ t.mu.Unlock()
+ return t.executeFallback(req, savedTrans, currentURL)
+ }
+
+ logrus.Infof("approval: searching for the fastest free proxy for file downloads...")
+ newProxyURL, err := findFastestFreeProxy()
+ if err != nil {
+ t.mu.Unlock()
+ return nil, fmt.Errorf("failed to find a working free proxy: %w", err)
+ }
+
+ parsedURL, _ := url.Parse(newProxyURL)
+ newTrans := &http.Transport{
+ Proxy: http.ProxyURL(parsedURL),
+ DialContext: (&net.Dialer{
+ Timeout: 10 * time.Second,
+ KeepAlive: 30 * time.Second,
+ }).DialContext,
+ TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
+ }
+
+ t.fallbackMode = true
+ t.fallbackProxyURL = newProxyURL
+ t.fallbackTransport = newTrans
+ savedTrans := newTrans
+ t.mu.Unlock()
+
+ logrus.Infof("approval: successfully switched to free proxy: %s", newProxyURL)
+ return t.executeFallback(req, savedTrans, newProxyURL)
+}
+
+func findFastestFreeProxy() (string, error) {
+ sources := []string{
+ "https://raw.githubusercontent.com/TheSpeedX/SOCKS-List/master/http.txt",
+ "https://raw.githubusercontent.com/ShiftyTR/Proxy-List/master/http.txt",
+ "https://api.proxyscrape.com/v2/?request=displayproxies&protocol=http&timeout=5000&country=all&ssl=all&anonymity=all",
+ }
+
+ var proxies []string
+ for _, src := range sources {
+ resp, err := http.Get(src)
+ if err == nil {
+ body, _ := io.ReadAll(resp.Body)
+ _ = resp.Body.Close()
+ lines := strings.Split(string(body), "\n")
+ for _, line := range lines {
+ line = strings.TrimSpace(line)
+ if line != "" {
+ proxies = append(proxies, line)
+ }
+ }
+ }
+ // Увеличили лимит пула до 200, чтобы повысить шансы быстро найти живой прокси
+ if len(proxies) > 200 {
+ break
+ }
+ }
+
+ if len(proxies) == 0 {
+ return "", fmt.Errorf("could not fetch proxies from public sources")
+ }
+
+ resultCh := make(chan string, 1)
+ var wg sync.WaitGroup
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+
+ limit := 200
+ if len(proxies) < limit {
+ limit = len(proxies)
+ }
+
+ for i := 0; i < limit; i++ {
+ p := proxies[i]
+ if !strings.HasPrefix(p, "http") && !strings.HasPrefix(p, "socks") {
+ p = "http://" + p
+ }
+ wg.Add(1)
+ go func(proxyUrl string) {
+ defer wg.Done()
+ u, err := url.Parse(proxyUrl)
+ if err != nil {
+ return
+ }
+
+ req, _ := http.NewRequestWithContext(ctx, "GET", "https://api.telegram.org/bot123456:invalid_token/getMe", nil)
+ client := &http.Client{
+ Transport: &http.Transport{
+ Proxy: http.ProxyURL(u),
+ DialContext: (&net.Dialer{Timeout: 3 * time.Second}).DialContext,
+ TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
+ },
+ Timeout: 4 * time.Second,
+ }
+
+ resp, err := client.Do(req)
+ if err == nil {
+ body, _ := io.ReadAll(resp.Body)
+ _ = resp.Body.Close()
+
+ if bytes.Contains(body, []byte(`"ok":`)) {
+ select {
+ case resultCh <- proxyUrl:
+ cancel()
+ default:
+ }
+ }
+ }
+ }(p)
+ }
+
+ go func() {
+ wg.Wait()
+ close(resultCh)
+ }()
+
+ select {
+ case best, ok := <-resultCh:
+ if !ok {
+ return "", fmt.Errorf("all %d tested proxies failed", limit)
+ }
+ return best, nil
+ case <-time.After(8 * time.Second):
+ return "", fmt.Errorf("timeout waiting for a valid proxy")
+ }
+}
+
+func buildFileHTTPClient() (*http.Client, error) {
fileHTTPClientOnce.Do(func() {
+ baseTransport := &http.Transport{
+ TLSHandshakeTimeout: 10 * time.Second,
+ ResponseHeaderTimeout: 30 * time.Second, // Даем больше времени на ожидание заголовков от Telegram
+ MaxIdleConns: 100,
+ MaxIdleConnsPerHost: 10,
+ IdleConnTimeout: 90 * time.Second,
+ }
+
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),
+ // Увеличили общий таймаут HTTP клиента с 30 до 120 секунд
+ Timeout: 120 * time.Second,
+ Transport: &FileProxyTransport{
+ wrapped: baseTransport,
},
}
})
@@ -40,9 +260,8 @@ func buildFileHTTPClient(tgConfig configcore.TelegramConfig) (*http.Client, erro
return fileHTTPClient, nil
}
-// fetchFileAsBase64 скачивает файл по URL и возвращает base64-строку.
-func fetchFileAsBase64(url string, tgConfig configcore.TelegramConfig) (string, error) {
- client, err := buildFileHTTPClient(tgConfig)
+func fetchFileAsBase64(url string) (string, error) {
+ client, err := buildFileHTTPClient()
if err != nil {
return "", err
}
@@ -52,7 +271,8 @@ func fetchFileAsBase64(url string, tgConfig configcore.TelegramConfig) (string,
var lastErr error
for attempt := 1; attempt <= maxRetries; attempt++ {
- ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ // Увеличили время на скачивание одного файла через бесплатный прокси с 30 до 60 секунд
+ ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
cancel()
@@ -76,9 +296,12 @@ func fetchFileAsBase64(url string, tgConfig configcore.TelegramConfig) (string,
}
cancel()
- lastErr = err
if err != nil {
+ lastErr = err
logrus.Warnf("fetchFileAsBase64: attempt %d/%d failed: %v", attempt, maxRetries, err)
+ } else if resp != nil {
+ lastErr = fmt.Errorf("bad status code: %s", resp.Status)
+ logrus.Warnf("fetchFileAsBase64: attempt %d/%d bad status: %s", attempt, maxRetries, resp.Status)
}
if attempt < maxRetries {
diff --git a/service/telegram_service/handlers/approval/integration.go b/service/telegram_service/handlers/approval/integration.go
new file mode 100644
index 0000000..48fdca8
--- /dev/null
+++ b/service/telegram_service/handlers/approval/integration.go
@@ -0,0 +1,161 @@
+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"
+)
+
+// StartFlowForOrder реализует интерфейс monthly_orders.ApprovalFlowStarter
+func (h *Handler) StartFlowForOrder(ctx context.Context, approval *typescore.Approval) error {
+ if approval == nil || approval.ID == nil {
+ return fmt.Errorf("invalid approval")
+ }
+
+ initiator, err := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID)
+ if err != nil || initiator == nil {
+ return fmt.Errorf("initiator not found")
+ }
+
+ topic, err := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID)
+ if err != nil || topic == nil || topic.CategoryID == nil {
+ return fmt.Errorf("topic or category not found")
+ }
+
+ // 1. Получаем согласующих из матрицы по иерархии (systems = nil)
+ approvers, err := h.ipc.Database.UserHierarchy.GetApproversDB(
+ ctx,
+ *initiator.ID,
+ *initiator.DepartmentID,
+ *topic.ID,
+ *topic.CategoryID,
+ nil,
+ )
+ if err != nil {
+ return fmt.Errorf("GetApproversDB err: %w", err)
+ }
+ if len(approvers) == 0 {
+ return fmt.Errorf("нет согласующих в иерархии для пользователя %d", *initiator.ID)
+ }
+
+ // 2. Распределяем по приоритетам (учитывая режим any_of)
+ priorityGroups := make(map[int][]*typescore.User)
+ for i, approver := range approvers {
+ p := i
+ if topic.ApprovalMode != nil && *topic.ApprovalMode == "any_of" {
+ p = 0
+ }
+ priorityGroups[p] = append(priorityGroups[p], approver)
+ }
+
+ // 3. Создаем шаги согласования (ApprovalStep) в БД
+ 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: approval.ID,
+ ApproverID: approver.ID,
+ StepOrder: &order,
+ Status: &stepStatus,
+ ApproverNameSnapshot: &approverName,
+ }
+ h.ipc.Database.ApprovalStep.CreateApprovalStepDB(ctx, nil, step) //nolint:errcheck
+ stepOrder++
+ }
+ }
+
+ // Подготавливаем данные для рассылки
+ bot := h.ipc.TGBotClient.Bot()
+ if bot == nil {
+ return fmt.Errorf("bot client is nil")
+ }
+
+ topicCode := "monthly_order"
+ if topic.Code != nil {
+ topicCode = *topic.Code
+ }
+
+ flowTopic, _ := h.Registry.Get(topicCode)
+ if flowTopic == nil {
+ logrus.Warnf("StartFlowForOrder: тема %s не найдена в Registry", topicCode)
+ return nil
+ }
+
+ notifier := NewNotifier(h.ipc, flowTopic)
+ collected := h.getCollectedFromApproval(ctx, approval)
+
+ // 4. Уведомляем первых согласующих
+ firstGroup := priorityGroups[0]
+ for _, approver := range firstGroup {
+ actualApprover := approver
+
+ if actualApprover.TelegramID == nil && actualApprover.ID != nil {
+ continue
+ }
+
+ if delegations, _, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalDelegation{
+ IsActive: utilscore.PointerToBool(true),
+ TopicID: topic.ID,
+ }}); err == nil && len(delegations) > 0 {
+ for _, deleg := range delegations {
+ if deleg.DelegatorID != nil && *deleg.DelegatorID == *actualApprover.ID && deleg.DelegateID != nil {
+ if delegate, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *deleg.DelegateID); delegate != nil && delegate.TelegramID != nil {
+ actualApprover = delegate
+ break
+ }
+ }
+ }
+ }
+
+ // Вызов Notifier сам соберет клавиатуру BuildApproverDecision
+ notifier.NotifyApprover(bot, actualApprover, initiator, approval, collected)
+ }
+
+ // 5. Уведомляем контроллеров
+ controllers, _ := h.ipc.Database.User.GetControllerObserversForApprovalDB(ctx, topicCode, topic.ID)
+ for _, controller := range controllers {
+ h.notifyControllerAboutCreation(bot, ctx, controller, initiator, approval, collected)
+ }
+
+ // 6. УВЕДОМЛЯЕМ МЕНЕДЖЕРА (ИНИЦИАТОРА) с его родной клавиатурой
+ if initiator.TelegramID != nil {
+ files, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID)
+ filesCount := len(files)
+ commentsCount := h.GetCommentsCount(ctx, *approval.ID)
+
+ // Собираем текст карточки с помощью уже существующего метода
+ cardText := fmt.Sprintf("✅ Ваш заказ на месяц автоматически отправлен на согласование!\n\n%s", h.buildApprovalCard(ctx, approval, collected))
+
+ msg := tgbotapi.NewMessage(*initiator.TelegramID, cardText)
+ msg.ParseMode = "HTML"
+
+ // Прикрепляем существующую клавиатуру для инициатора
+ msg.ReplyMarkup = keyboard.BuildInitiatorCard(*approval.ID, "pending", filesCount > 0, filesCount, commentsCount)
+
+ bot.Send(msg) //nolint:errcheck
+ }
+
+ return nil
+}
diff --git a/service/telegram_service/handlers/approval/list.go b/service/telegram_service/handlers/approval/list.go
index 7d7a65c..70ae1e5 100644
--- a/service/telegram_service/handlers/approval/list.go
+++ b/service/telegram_service/handlers/approval/list.go
@@ -156,7 +156,7 @@ func (h *Handler) HandleMyApprovalsStatusCallback(bot *tgbotapi.BotAPI, cq *tgbo
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))
+ msg.ReplyMarkup = keyboard.BuildInitiatorCard(*approval.ID, approvalStatus, len(files) > 0, len(files), h.GetCommentsCount(ctx, *approval.ID))
bot.Send(msg) //nolint:errcheck
}
}
@@ -185,7 +185,6 @@ func buildMyApprovalsTopicFilter(categories []*typescore.ApprovalTopicCategory)
return tgbotapi.NewInlineKeyboardMarkup(rows...)
}
-// HandleIncomingApprovals — список заявок ожидающих действия согласующего
func (h *Handler) HandleIncomingApprovals(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) {
ctx := context.Background()
@@ -206,7 +205,39 @@ func (h *Handler) HandleIncomingApprovals(bot *tgbotapi.BotAPI, chatID int64, te
return
}
- // Дополнительные согласования
+ type validStep struct {
+ step *typescore.ApprovalStep
+ approval *typescore.Approval
+ }
+ var validSteps []validStep
+ for _, step := range steps {
+ if step.ApprovalID == nil {
+ continue
+ }
+ approval, aErr := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, *step.ApprovalID)
+ if aErr != nil || approval == nil {
+ continue
+ }
+ if approval.Status == nil || (*approval.Status != "pending" && *approval.Status != "revision") {
+ approvalStatus := "nil"
+ if approval.Status != nil {
+ approvalStatus = *approval.Status
+ }
+ stepID := uint64(0)
+ if step.ID != nil {
+ stepID = *step.ID
+ }
+ logrus.Warnf(
+ "HandleIncomingApprovals: осиротевший шаг stepID=%d approvalID=%d approverID=%d — статус шага=pending, статус заявки=%s; шаг пропущен из выдачи. Похоже на рассинхронизацию между ApprovalStep и Approval — стоит проверить эту заявку вручную",
+ stepID, *step.ApprovalID, *user.ID, approvalStatus,
+ )
+ continue
+ }
+ validSteps = append(validSteps, validStep{step: step, approval: approval})
+ }
+
+ // Дополнительные согласования — та же логика: не доверяем одному только
+ // статусу ApprovalAdditionalApprover, сверяем со статусом заявки.
additionalApprovers, _, err := h.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.ApprovalAdditionalApprover{
ApproverID: user.ID,
@@ -217,7 +248,34 @@ func (h *Handler) HandleIncomingApprovals(bot *tgbotapi.BotAPI, chatID int64, te
logrus.Warnf("HandleIncomingApprovals: GetPendingAdditionalApprovalsByApproverDB err=%v", err)
}
- totalCount := len(steps) + len(additionalApprovers)
+ type validAdditional struct {
+ aa *typescore.ApprovalAdditionalApprover
+ approval *typescore.Approval
+ }
+ var validAdditionals []validAdditional
+ for _, aa := range additionalApprovers {
+ if aa.ApprovalID == nil {
+ continue
+ }
+ approval, aErr := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, *aa.ApprovalID)
+ if aErr != nil || approval == nil {
+ continue
+ }
+ if approval.Status == nil || (*approval.Status != "pending" && *approval.Status != "revision") {
+ approvalStatus := "nil"
+ if approval.Status != nil {
+ approvalStatus = *approval.Status
+ }
+ logrus.Warnf(
+ "HandleIncomingApprovals: осиротевший доп.согласующий approvalID=%d approverID=%d — статус=pending, статус заявки=%s; пропущен из выдачи",
+ *aa.ApprovalID, *user.ID, approvalStatus,
+ )
+ continue
+ }
+ validAdditionals = append(validAdditionals, validAdditional{aa: aa, approval: approval})
+ }
+
+ totalCount := len(validSteps) + len(validAdditionals)
if totalCount == 0 {
sendText(bot, chatID, "📭 Нет заявок для согласования.")
return
@@ -226,35 +284,19 @@ func (h *Handler) HandleIncomingApprovals(bot *tgbotapi.BotAPI, chatID int64, te
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
- }
-
- // Проверяем добавленных согласующих
+ for _, vs := range validSteps {
addedApprovers, _, _ := h.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.ApprovalAdditionalApprover{
- ApprovalID: step.ApprovalID,
+ ApprovalID: vs.step.ApprovalID,
Status: utilscore.PointerToString("pending"),
},
})
- h.sendApprovalCard(bot, chatID, approval, true, true, addedApprovers)
+ h.sendApprovalCard(bot, chatID, vs.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)
+ for _, va := range validAdditionals {
+ h.sendAdditionalApprovalCard(bot, chatID, va.approval, va.aa)
}
}
@@ -329,7 +371,7 @@ func (h *Handler) sendApprovalCard(bot *tgbotapi.BotAPI, chatID int64, approval
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))
+ markup := keyboard.BuildApproverDecision(*approval.ID, *approval.Status, len(files) > 0, len(files), h.GetCommentsCount(ctx, *approval.ID))
//if showAddApprover {
// addBtn := tgbotapi.NewInlineKeyboardButtonData(
@@ -346,7 +388,7 @@ func (h *Handler) sendApprovalCard(bot *tgbotapi.BotAPI, chatID int64, approval
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))
+ markup := keyboard.BuildInitiatorCard(*approval.ID, *approval.Status, len(files) > 0, len(files), h.GetCommentsCount(ctx, *approval.ID))
msg.ReplyMarkup = markup
}
@@ -354,7 +396,6 @@ func (h *Handler) sendApprovalCard(bot *tgbotapi.BotAPI, chatID int64, approval
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
@@ -415,6 +456,47 @@ func (h *Handler) HandleApprovalStages(bot *tgbotapi.BotAPI, cq *tgbotapi.Callba
}
}
+ // НОВОЕ: доп. согласующие — отдельная сущность от основной цепочки шагов,
+ // без своего StepOrder (все они назначаются параллельно, независимо от
+ // того, в каком порядке идут ApprovalStep), поэтому выводим отдельным
+ // блоком, а не пытаемся встроить в нумерованный список выше.
+ additionalApprovers, _, err := h.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalAdditionalApprover{ApprovalID: &approvalID},
+ })
+ if err != nil {
+ logrus.Warnf("HandleApprovalStages: GetApprovalAdditionalApproversListDB approvalID=%d err=%v", approvalID, err)
+ }
+
+ if len(additionalApprovers) > 0 {
+ text += "\n➕ Дополнительные согласующие:\n"
+ additionalStatusIcons := map[string]string{
+ "pending": "⏳",
+ "approved": "✅",
+ "rejected": "❌",
+ }
+ for _, aa := range additionalApprovers {
+ icon := "⏳"
+ if aa.Status != nil {
+ if ic, ok := additionalStatusIcons[*aa.Status]; ok {
+ icon = ic
+ }
+ }
+ name := "—"
+ if aa.ApproverID != nil {
+ if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *aa.ApproverID); u != nil && u.FullName != nil {
+ name = *u.FullName
+ }
+ }
+ text += fmt.Sprintf("%s %s\n", icon, name)
+ if aa.ActedAt != nil {
+ text += fmt.Sprintf(" 📅 %s\n", aa.ActedAt.Format("02.01.2006 15:04"))
+ }
+ if aa.Comment != nil && *aa.Comment != "" {
+ text += fmt.Sprintf(" 💬 %s\n", *aa.Comment)
+ }
+ }
+ }
+
// Статус задач
tasks, _, _ := h.ipc.Database.ApprovalTasks.GetApprovalTasksListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.ApprovalTask{ApprovalID: &approvalID},
diff --git a/service/telegram_service/handlers/approval/notify.go b/service/telegram_service/handlers/approval/notify.go
index c558430..35512d2 100644
--- a/service/telegram_service/handlers/approval/notify.go
+++ b/service/telegram_service/handlers/approval/notify.go
@@ -2,6 +2,7 @@ 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/types"
@@ -9,6 +10,7 @@ import (
"encoding/base64"
"fmt"
"github.com/sirupsen/logrus"
+ "time"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)
@@ -22,6 +24,65 @@ func NewNotifier(ipc *types.InternalProviderControl, topic approvalflow.Topic) *
return &Notifier{ipc: ipc, topic: topic}
}
+// getDisplayName проверяет активные делегирования и формирует строку "Делегат (Делегат от Оригинал)",
+// если права были переданы, либо просто "Оригинал", если делегирования нет.
+func (n *Notifier) getDisplayName(ctx context.Context, originalApproverID uint64, topicID *uint64) string {
+ originalApprover, err := n.ipc.Database.User.GetUserByIDDB(ctx, originalApproverID)
+ if err != nil || originalApprover == nil {
+ return "—"
+ }
+
+ origName := "—"
+ if originalApprover.FullName != nil {
+ origName = *originalApprover.FullName
+ }
+
+ if topicID == nil {
+ return origName
+ }
+
+ // 1. Проверяем делегирование по теме
+ delegations, _, err := n.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalDelegation{
+ DelegatorID: &originalApproverID,
+ TopicID: topicID,
+ IsActive: utilscore.PointerToBool(true),
+ },
+ })
+ if err == nil {
+ for _, d := range delegations {
+ if d.ValidUntil != nil && d.ValidUntil.After(time.Now()) && d.DelegateID != nil {
+ if delegate, _ := n.ipc.Database.User.GetUserByIDDB(ctx, *d.DelegateID); delegate != nil && delegate.FullName != nil {
+ return fmt.Sprintf("%s (Временно исполняющий обязанности от: %s)", *delegate.FullName, origName)
+ }
+ }
+ }
+ }
+
+ // 2. Проверяем делегирование по категории
+ topic, _ := n.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *topicID)
+ if topic != nil && topic.CategoryID != nil {
+ delegationsCat, _, err := n.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalDelegation{
+ DelegatorID: &originalApproverID,
+ CategoryID: topic.CategoryID,
+ IsActive: utilscore.PointerToBool(true),
+ },
+ })
+ if err == nil {
+ for _, d := range delegationsCat {
+ if d.ValidUntil != nil && d.ValidUntil.After(time.Now()) && d.DelegateID != nil {
+ if delegate, _ := n.ipc.Database.User.GetUserByIDDB(ctx, *d.DelegateID); delegate != nil && delegate.FullName != nil {
+ return fmt.Sprintf("%s (Делегат от %s)", *delegate.FullName, origName)
+ }
+ }
+ }
+ }
+ }
+
+ return origName
+}
+
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
@@ -34,34 +95,25 @@ func (h *Handler) notifyExecutor(bot *tgbotapi.BotAPI, ctx context.Context, exec
topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID)
- content := "—"
- if approval.Content != nil {
- content = *approval.Content
- }
-
- taskText := "—"
- if task.TaskText != nil {
- taskText = *task.TaskText
- }
+ fullTaskComposition := formatTaskWithApprovalContext(approval, task)
text := fmt.Sprintf(
- "📋 Новая задача по заявке #%d\n\n"+
+ "📋 Новая задача #%d (по заявке #%d)\n\n"+
"👤 Инициатор: %s\n"+
- "📋 Тема: %s\n"+
- "📝 Текст заявки: %s\n\n"+
- "🎯 Задача:\n%s",
- *approval.ID, initiatorName, topicFullName, content, taskText,
+ "📋 Тема: %s\n\n"+
+ "🎯 Состав задачи:\n%s",
+ *task.ID, *approval.ID, initiatorName, topicFullName, fullTaskComposition,
)
// Добавляем комментарии
- commentsSection := h.formatCommentsSection(ctx, *approval.ID)
+ commentsSection := h.formatCommentsSection(ctx, *approval.ID, 4)
text += commentsSection
- // 🆕 Получаем все файлы заявки
+ // Получаем все файлы заявки
allFiles, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID)
filesCount := len(allFiles)
- // 🆕 Информация о файлах, приложенных к этой задаче
+ // Информация о файлах, приложенных к этой задаче
var taskFiles []string
for _, f := range allFiles {
if f.TaskID != nil && *f.TaskID == *task.ID && f.FileName != nil {
@@ -74,14 +126,12 @@ func (h *Handler) notifyExecutor(bot *tgbotapi.BotAPI, ctx context.Context, exec
text += fmt.Sprintf("%d. %s\n", i+1, name)
}
} else if filesCount > 0 {
- // 🆕 Если есть файлы заявки, но не к этой задаче — показываем кнопку
text += fmt.Sprintf("\n\n📂 В заявке есть файлы (%d шт.) — см. кнопку ниже", filesCount)
}
- // 🆕 Передаём filesCount в клавиатуру
msg := tgbotapi.NewMessage(*executor.TelegramID, text)
msg.ParseMode = "HTML"
- msg.ReplyMarkup = keyboard.BuildExecutorTaskActions(*task.ID, *approval.ID, filesCount)
+ msg.ReplyMarkup = keyboard.BuildExecutorTaskActions(*task.ID, *approval.ID, filesCount, h.GetCommentsCount(ctx, *approval.ID))
bot.Send(msg) //nolint:errcheck
}
@@ -126,27 +176,7 @@ func (n *Notifier) NotifyApprover(
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)
- }
- }
+ msgText += n.formatCommentsSection(ctx, *approval.ID, 4)
// Отправляем с файлами или без
if len(approval.Files) == 0 {
@@ -166,7 +196,7 @@ func (n *Notifier) NotifyApprover(
*approver.TelegramID,
approval,
msgText,
- keyboard.BuildApproverDecision(*approval.ID, status, len(files) > 0, len(files)),
+ keyboard.BuildApproverDecision(*approval.ID, status, len(files) > 0, len(files), n.GetCommentsCount(ctx, *approval.ID)),
)
}
@@ -180,7 +210,7 @@ func (n *Notifier) sendTextToApprover(bot *tgbotapi.BotAPI, approver *typescore.
msg := tgbotapi.NewMessage(*approver.TelegramID, text)
msg.ParseMode = "HTML"
- msg.ReplyMarkup = keyboard.BuildApproverDecision(*approval.ID, status, len(files) > 0, len(files))
+ msg.ReplyMarkup = keyboard.BuildApproverDecision(*approval.ID, status, len(files) > 0, len(files), n.GetCommentsCount(ctx, *approval.ID))
bot.Send(msg) //nolint:errcheck
}
@@ -196,16 +226,10 @@ func (n *Notifier) NotifyInitiatorApproved(
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 = "—"
+ if lastApprover != nil && lastApprover.ID != nil {
+ approverName = n.getDisplayName(context.Background(), *lastApprover.ID, approval.TopicID)
}
status := ""
@@ -215,13 +239,20 @@ func (n *Notifier) NotifyInitiatorApproved(
ctx := context.Background()
- topicFullName := getTopicFullName(ctx, n.ipc, approval.TopicID)
+ initiatorCollected := make(map[string]string, len(collected))
+ for k, v := range collected {
+ if k == "instructions" {
+ continue
+ }
+ initiatorCollected[k] = v
+ }
+
+ card := n.topic.FormatApproverMessage(initiator, initiatorCollected)
+
text := fmt.Sprintf(
- "✅ Заявка #%d согласована\n\n"+
- "👤 Последний согласующий: %s\n"+
- "📋 Тема: %s\n"+
- "📝 Текст: %s",
- *approval.ID, approverName, topicFullName, content,
+ "✅ Заявка #%d согласована\n"+
+ "👤 Последний согласующий: %s\n\n%s",
+ *approval.ID, approverName, card,
)
filesCount := len(approval.Files)
@@ -232,7 +263,7 @@ func (n *Notifier) NotifyInitiatorApproved(
msg := tgbotapi.NewMessage(*initiator.TelegramID, text)
msg.ParseMode = "HTML"
- msg.ReplyMarkup = keyboard.BuildRevokeButton(*approval.ID, status, filesCount)
+ msg.ReplyMarkup = keyboard.BuildRevokeButton(*approval.ID, status, filesCount, n.GetCommentsCount(ctx, *approval.ID))
if _, err := bot.Send(msg); err != nil {
logrus.Errorf("NotifyInitiatorApproved: Send err=%v", err)
}
@@ -252,22 +283,25 @@ func (n *Notifier) NotifyInitiatorRejected(
}
approverName := "—"
- if approver != nil && approver.FullName != nil {
- approverName = *approver.FullName
+ if approver != nil && approver.ID != nil {
+ ctx := context.Background()
+ approverName = n.getDisplayName(ctx, *approver.ID, approval.TopicID)
}
- content := collected["content"]
- if content == "" {
- content = "—"
+ initiatorCollected := make(map[string]string, len(collected))
+ for k, v := range collected {
+ if k == "instructions" {
+ continue
+ }
+ initiatorCollected[k] = v
}
- ctx := context.Background()
- topicFullName := getTopicFullName(ctx, n.ipc, approval.TopicID)
+
+ card := n.topic.FormatApproverMessage(initiator, initiatorCollected)
+
text := fmt.Sprintf(
"❌ Заявка #%d отклонена\n\n"+
- "👤 Согласующий: %s\n"+
- "📋 Тема: %s\n"+
- "📝 Текст: %s",
- *approval.ID, approverName, topicFullName, content,
+ "👤 Согласующий: %s\n\n%s",
+ *approval.ID, approverName, card,
)
if comment != "" {
@@ -286,7 +320,6 @@ func (n *Notifier) NotifyDirector(bot *tgbotapi.BotAPI, director *typescore.User
}
ctx := context.Background()
- // 🚀 Передаем initiator и collected для построения ПОЛНОЙ карточки
card := n.buildApprovalCard(ctx, approval, initiator, collected)
text := "📌 Финально согласовано\n\n" + card
@@ -306,10 +339,11 @@ func (n *Notifier) NotifyDirector(bot *tgbotapi.BotAPI, director *typescore.User
msg := tgbotapi.NewMessage(*director.TelegramID, text)
msg.ParseMode = "HTML"
// 🚀 Передаем filesCount в клавиатуру
- msg.ReplyMarkup = keyboard.BuildRevokeButton(*approval.ID, status, filesCount)
+ msg.ReplyMarkup = keyboard.BuildRevokeButton(*approval.ID, status, filesCount, n.GetCommentsCount(ctx, *approval.ID))
bot.Send(msg) //nolint:errcheck
}
+// NotifyObserversDecision — кто, кому и что согласовал/отклонил.
// NotifyObserversDecision — кто, кому и что согласовал/отклонил.
func (n *Notifier) NotifyObserversDecision(
bot *tgbotapi.BotAPI,
@@ -319,17 +353,30 @@ func (n *Notifier) NotifyObserversDecision(
approval *typescore.Approval,
collected map[string]string,
) {
+ // 🔍 Логирование входа
+ statusStr := "nil"
+ if approval.Status != nil {
+ statusStr = *approval.Status
+ }
+ logrus.Infof("📢 NotifyObserversDecision: status=%s, observers=%d, approvalID=%v",
+ statusStr, len(observers), approval.ID)
+
if approval.Status == nil || *approval.Status != "approved" {
+ logrus.Warnf("⚠️ NotifyObserversDecision: skipped — status is not 'approved' (got: %s)", statusStr)
+ return
+ }
+
+ if len(observers) == 0 {
+ logrus.Warnf("⚠️ NotifyObserversDecision: no observers to notify")
return
}
ctx := context.Background()
- // 🚀 Передаем initiator и collected
card := n.buildApprovalCard(ctx, approval, initiator, collected)
approverName := "—"
- if approver != nil && approver.FullName != nil {
- approverName = *approver.FullName
+ if approver != nil && approver.ID != nil {
+ approverName = n.getDisplayName(ctx, *approver.ID, approval.TopicID)
}
header := fmt.Sprintf(
"✅ %s согласовал(а) заявку\n\n",
@@ -338,7 +385,6 @@ func (n *Notifier) NotifyObserversDecision(
text := header + card
- // Считаем файлы для кнопки
filesCount := len(approval.Files)
if filesCount == 0 {
files, _ := n.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID)
@@ -349,14 +395,27 @@ func (n *Notifier) NotifyObserversDecision(
if approval.Status != nil {
status = *approval.Status
}
+
for _, obs := range observers {
if obs.TelegramID == nil {
+ logrus.Warnf("⚠️ NotifyObserversDecision: observer %v (id=%v) has no TelegramID, skipping",
+ obs.FullName, obs.ID)
continue
}
+
+ logrus.Infof("📨 NotifyObserversDecision: sending to observer %s (telegramID=%d)",
+ *obs.FullName, *obs.TelegramID)
+
msg := tgbotapi.NewMessage(*obs.TelegramID, text)
msg.ParseMode = "HTML"
- msg.ReplyMarkup = keyboard.BuildObserverActions(*approval.ID, "", status, filesCount)
- bot.Send(msg) //nolint:errcheck
+ msg.ReplyMarkup = keyboard.BuildObserverActions(*approval.ID, "", status, filesCount, n.GetCommentsCount(ctx, *approval.ID))
+
+ if _, err := bot.Send(msg); err != nil {
+ logrus.Errorf("❌ NotifyObserversDecision: Send to %d err=%v", *obs.TelegramID, err)
+ } else {
+ logrus.Infof("✅ NotifyObserversDecision: sent to %s (telegramID=%d)",
+ *obs.FullName, *obs.TelegramID)
+ }
}
}
@@ -534,7 +593,7 @@ func (h *Handler) sendAdditionalApprovalCard(bot *tgbotapi.BotAPI, chatID int64,
if len(files) == 0 {
msg := tgbotapi.NewMessage(chatID, text)
msg.ParseMode = "HTML"
- msg.ReplyMarkup = keyboard.BuildApproverDecision(*approval.ID, status, len(files) > 0, len(files))
+ msg.ReplyMarkup = keyboard.BuildApproverDecision(*approval.ID, status, len(files) > 0, len(files), h.GetCommentsCount(ctx, *approval.ID))
bot.Send(msg) //nolint:errcheck
return
}
@@ -543,7 +602,7 @@ func (h *Handler) sendAdditionalApprovalCard(bot *tgbotapi.BotAPI, chatID int64,
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)))
+ notifier.sendFilesToRecipient(bot, chatID, approval, text, keyboard.BuildApproverDecision(*approval.ID, status, len(files) > 0, len(files), h.GetCommentsCount(ctx, *approval.ID)))
}
}
@@ -568,7 +627,7 @@ func (h *Handler) notifyObserversAboutNewFile(
return
}
- observers, err := h.ipc.Database.User.GetObserversForCategoryDB(ctx, *topic.Code)
+ observers, err := h.ipc.Database.User.GetObserversForApprovalDB(ctx, *topic.Code, topic.ID)
if err != nil {
logrus.Warnf("notifyObserversAboutNewFile: GetObserversForCategoryDB err=%v", err)
return
@@ -666,7 +725,7 @@ func (h *Handler) notifyAllParticipantsAboutFile(
}
categoryCode := h.getTopicCodeByApproval(ctx, approval)
- observers, _ := h.ipc.Database.User.GetObserversForCategoryDB(ctx, categoryCode)
+ observers, _ := h.ipc.Database.User.GetObserversForApprovalDB(ctx, categoryCode, approval.TopicID)
recipients = append(recipients, observers...)
// Получаем нотифайер для sendFilesToRecipient
@@ -788,13 +847,13 @@ func (n *Notifier) buildApprovalCard(ctx context.Context, approval *typescore.Ap
}
// Добавляем комментарии
- commentsSection := n.formatCommentsSection(ctx, approvalID)
+ commentsSection := n.formatCommentsSection(ctx, approvalID, 4)
card += commentsSection
return card
}
-func (n *Notifier) formatCommentsSection(ctx context.Context, approvalID uint64) string {
+func (n *Notifier) formatCommentsSection(ctx context.Context, approvalID uint64, limit int) string {
comments, _, _ := n.ipc.Database.ApprovalComment.GetApprovalCommentsListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.ApprovalComment{ApprovalID: &approvalID},
})
@@ -802,7 +861,16 @@ func (n *Notifier) formatCommentsSection(ctx context.Context, approvalID uint64)
return ""
}
+ total := len(comments)
+ if limit > 0 && total > limit {
+ comments = comments[total-limit:]
+ }
+
section := "\n\n💬 Комментарии:"
+ if limit > 0 && total > limit {
+ section = fmt.Sprintf("\n\n💬 Последние %d комментариев (из %d):", limit, total)
+ }
+
for _, c := range comments {
authorName := "—"
if c.UserID != nil {
@@ -823,3 +891,52 @@ func (n *Notifier) formatCommentsSection(ctx context.Context, approvalID uint64)
}
return section
}
+
+func (n *Notifier) GetCommentsCount(ctx context.Context, approvalID uint64) int {
+ comments, err := n.ipc.Database.ApprovalComment.GetCommentsByApprovalIDDB(ctx, approvalID)
+ if err != nil {
+ return 0
+ }
+ return len(comments)
+}
+
+func (h *Handler) notifyControllerAboutCreation(
+ bot *tgbotapi.BotAPI,
+ ctx context.Context,
+ controller *typescore.User,
+ initiator *typescore.User,
+ approval *typescore.Approval,
+ collected map[string]string,
+) {
+ if controller.TelegramID == nil || approval.ID == nil {
+ return
+ }
+
+ initiatorName := "—"
+ if initiator.FullName != nil {
+ initiatorName = *initiator.FullName
+ }
+ topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID)
+ content := collected["content"]
+ if content == "" {
+ content = "—"
+ }
+
+ text := fmt.Sprintf(
+ "👁 Создана заявка на согласование #%d\n\n"+
+ "👤 Инициатор: %s\n"+
+ "📋 Тема: %s\n"+
+ "📝 Текст: %s",
+ *approval.ID, initiatorName, topicFullName, content,
+ )
+
+ status := ""
+ if approval.Status != nil {
+ status = *approval.Status
+ }
+
+ msg := tgbotapi.NewMessage(*controller.TelegramID, text)
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildObserverActions(*approval.ID, "", status, len(approval.Files), h.GetCommentsCount(ctx, *approval.ID))
+ bot.Send(msg) //nolint:errcheck
+}
diff --git a/service/telegram_service/handlers/approval/registry.go b/service/telegram_service/handlers/approval/registry.go
index 795f87e..469c9d4 100644
--- a/service/telegram_service/handlers/approval/registry.go
+++ b/service/telegram_service/handlers/approval/registry.go
@@ -1,90 +1,88 @@
package approval
import (
+ "bitrix_balancer_api/core/typescore"
"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"
+ "bitrix_balancer_api/telegram_service/types"
+ "context"
"fmt"
+ "github.com/sirupsen/logrus"
+ "sync"
)
type Registry struct {
+ ipc *types.InternalProviderControl
topics map[string]approvalflow.Topic
order []string
topicCodeToCategory map[string]string
+
+ mu sync.RWMutex
}
-func NewRegistry() *Registry {
+func NewRegistry(ipc *types.InternalProviderControl) *Registry {
r := &Registry{
+ ipc: ipc,
topics: make(map[string]approvalflow.Topic),
topicCodeToCategory: make(map[string]string),
}
- r.registerAll()
+
+ r.topicCodeToCategory["timeoff"] = "absence"
+ r.topicCodeToCategory["vacation"] = "absence"
+ r.topicCodeToCategory["sickleave"] = "absence"
+
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())
+func (r *Registry) LoadFromDB(ctx context.Context) error {
+ r.mu.Lock()
+ defer r.mu.Unlock()
- r.mapTopicToCategory("timeoff", "absence")
- r.mapTopicToCategory("vacation", "absence")
- r.mapTopicToCategory("sickleave", "absence")
+ r.topics = make(map[string]approvalflow.Topic)
+ r.order = nil
- 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", ""},
+ categories, _, err := r.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalTopicCategory{IsActive: boolPtr(true)},
+ })
+ if err != nil {
+ return fmt.Errorf("load categories: %w", err)
}
- for _, t := range freeTopics {
- r.register(free.NewFreeTopic(t.code, t.name, t.template))
+
+ for _, category := range categories {
+ if category.ID == nil || category.Code == nil {
+ continue
+ }
+
+ nodes, err := r.loadFlowNodes(ctx, *category.ID)
+ if err != nil {
+ logrus.Warnf("LoadFromDB: loadFlowNodes categoryID=%d err=%v", *category.ID, err)
+ continue
+ }
+ if len(nodes) == 0 {
+ // категория ещё не мигрирована / дерево не настроено — пропускаем молча
+ continue
+ }
+
+ dynamicTopic := approvalflow.NewDynamicTopic(category, nodes)
+ code := *category.Code
+ r.topics[code] = dynamicTopic
+ r.order = append(r.order, code)
}
+
+ return nil
}
-func (r *Registry) mapTopicToCategory(topicCode, categoryCode string) {
- r.topicCodeToCategory[topicCode] = categoryCode
-}
-
-func (r *Registry) register(t approvalflow.Topic) {
- r.topics[t.Code()] = t
- r.order = append(r.order, t.Code())
+func (r *Registry) loadFlowNodes(ctx context.Context, categoryID uint64) ([]*typescore.ApprovalFlowNode, error) {
+ nodes, _, err := r.ipc.Database.ApprovalFlowNode.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalFlowNode{CategoryID: &categoryID},
+ })
+ return nodes, err
}
func (r *Registry) Get(code string) (approvalflow.Topic, error) {
+ r.mu.RLock()
+ defer r.mu.RUnlock()
+
if t, ok := r.topics[code]; ok {
return t, nil
}
@@ -99,9 +97,21 @@ func (r *Registry) Get(code string) (approvalflow.Topic, error) {
}
func (r *Registry) All() []approvalflow.Topic {
+ r.mu.RLock()
+ defer r.mu.RUnlock()
+
result := make([]approvalflow.Topic, 0, len(r.order))
for _, code := range r.order {
result = append(result, r.topics[code])
}
return result
}
+
+// Reload перезагружает темы из БД
+func (r *Registry) Reload(ctx context.Context) error {
+ return r.LoadFromDB(ctx)
+}
+
+func boolPtr(b bool) *bool {
+ return &b
+}
diff --git a/service/telegram_service/handlers/approval/reminder.go b/service/telegram_service/handlers/approval/reminder.go
new file mode 100644
index 0000000..da97496
--- /dev/null
+++ b/service/telegram_service/handlers/approval/reminder.go
@@ -0,0 +1,167 @@
+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"
+)
+
+// HandleReminderRevisions показывает список заявок на доработке
+func (h *Handler) HandleReminderRevisions(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery) {
+ ctx := context.Background()
+ chatID := cq.Message.Chat.ID
+ telegramID := cq.From.ID
+
+ bot.Request(tgbotapi.NewCallback(cq.ID, ""))
+
+ user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
+ if err != nil || user == nil || user.ID == nil {
+ sendText(bot, chatID, "⚠️ Пользователь не найден.")
+ return
+ }
+
+ revisions, _, err := h.ipc.Database.Approval.GetApprovalsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.Approval{
+ InitiatorID: user.ID,
+ Status: utilscore.PointerToString("revision"),
+ },
+ })
+ if err != nil || len(revisions) == 0 {
+ sendText(bot, chatID, "📭 Нет заявок на доработке.")
+ return
+ }
+
+ sendText(bot, chatID, fmt.Sprintf("📝 Заявки на доработке (%d):", len(revisions)))
+
+ for _, approval := range revisions {
+ if approval.ID == nil {
+ continue
+ }
+
+ topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID)
+ content := "—"
+ if approval.Content != nil {
+ content = *approval.Content
+ }
+
+ text := fmt.Sprintf(
+ "🔄 Заявка #%d на доработке\n\n"+
+ "📋 Тема: %s\n"+
+ "📝 Текст: %s",
+ *approval.ID, topicFullName, content,
+ )
+
+ if approval.RevisionComment != nil && *approval.RevisionComment != "" {
+ text += fmt.Sprintf("\n💬 Причина: %s", *approval.RevisionComment)
+ }
+
+ msg := tgbotapi.NewMessage(chatID, text)
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildRevisionOptions(*approval.ID, h.GetCommentsCount(ctx, *approval.ID))
+ bot.Send(msg) //nolint:errcheck
+ }
+}
+
+// HandleReminderApprovals показывает список согласований к принятию
+func (h *Handler) HandleReminderApprovals(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery) {
+ ctx := context.Background()
+ chatID := cq.Message.Chat.ID
+ telegramID := cq.From.ID
+
+ bot.Request(tgbotapi.NewCallback(cq.ID, ""))
+
+ user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
+ if err != nil || user == nil || user.ID == nil {
+ sendText(bot, chatID, "⚠️ Пользователь не найден.")
+ return
+ }
+
+ currentUserID := *user.ID
+
+ // Получаем основные шаги согласования
+ steps, _, err := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalStep{
+ ApproverID: ¤tUserID,
+ Status: utilscore.PointerToString("pending"),
+ },
+ })
+ if err != nil {
+ logrus.Errorf("HandleReminderApprovals: GetApprovalStepsListDB err=%v", err)
+ }
+
+ // Получаем дополнительные согласования
+ additionalApprovers, _, err := h.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalAdditionalApprover{
+ ApproverID: ¤tUserID,
+ Status: utilscore.PointerToString("pending"),
+ },
+ })
+ if err != nil {
+ logrus.Errorf("HandleReminderApprovals: GetApprovalAdditionalApproversListDB 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
+ }
+ if approval.Status == nil && *approval.Status != "pending" {
+ continue
+ }
+ h.sendApprovalCardForReminder(bot, chatID, approval)
+ }
+
+ // Показываем дополнительные согласования
+ for _, aa := range additionalApprovers {
+ if aa.ApprovalID == nil {
+ continue
+ }
+ approval, _ := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, *aa.ApprovalID)
+ if approval == nil {
+ continue
+ }
+ h.sendApprovalCardForReminder(bot, chatID, approval)
+ }
+}
+
+// sendApprovalCardForReminder отправляет карточку заявки для напоминания
+func (h *Handler) sendApprovalCardForReminder(bot *tgbotapi.BotAPI, chatID int64, approval *typescore.Approval) {
+ ctx := context.Background()
+
+ if approval.ID == nil {
+ return
+ }
+
+ files, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID)
+ filesCount := len(files)
+ commentsCount := h.GetCommentsCount(ctx, *approval.ID)
+
+ status := ""
+ if approval.Status != nil {
+ status = *approval.Status
+ }
+
+ collected := h.getCollectedFromApproval(ctx, approval)
+ card := h.buildApprovalCard(ctx, approval, collected)
+
+ msg := tgbotapi.NewMessage(chatID, card)
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildApproverDecision(*approval.ID, status, filesCount > 0, filesCount, commentsCount)
+ bot.Send(msg) //nolint:errcheck
+}
diff --git a/service/telegram_service/handlers/approval/revision.go b/service/telegram_service/handlers/approval/revision.go
index 329340a..38d93fa 100644
--- a/service/telegram_service/handlers/approval/revision.go
+++ b/service/telegram_service/handlers/approval/revision.go
@@ -163,7 +163,7 @@ func (h *Handler) notifyInitiatorRevision(
msg := tgbotapi.NewMessage(*initiator.TelegramID, text)
msg.ParseMode = "HTML"
- msg.ReplyMarkup = keyboard.BuildRevisionOptions(*approval.ID)
+ msg.ReplyMarkup = keyboard.BuildRevisionOptions(*approval.ID, h.GetCommentsCount(context.Background(), *approval.ID))
bot.Send(msg) //nolint:errcheck
}
@@ -256,7 +256,7 @@ func (h *Handler) HandleRevisionTextInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Me
// Показываем опции снова
optMsg := tgbotapi.NewMessage(chatID, fmt.Sprintf("📋 Заявка #%d на доработке:", revisionState.ApprovalID))
optMsg.ParseMode = "HTML"
- optMsg.ReplyMarkup = keyboard.BuildRevisionOptions(revisionState.ApprovalID)
+ optMsg.ReplyMarkup = keyboard.BuildRevisionOptions(revisionState.ApprovalID, h.GetCommentsCount(ctx, *approval.ID))
bot.Send(optMsg) //nolint:errcheck
return true
@@ -364,15 +364,15 @@ func (h *Handler) HandleRevisionResubmit(bot *tgbotapi.BotAPI, cq *tgbotapi.Call
if len(files) == 0 {
msg := tgbotapi.NewMessage(*approver.TelegramID, fullText)
msg.ParseMode = "HTML"
- msg.ReplyMarkup = keyboard.BuildApproverDecision(approvalID, status, len(files) > 0, len(files))
+ msg.ReplyMarkup = keyboard.BuildApproverDecision(approvalID, status, len(files) > 0, len(files), h.GetCommentsCount(ctx, *approval.ID))
bot.Send(msg) //nolint:errcheck
} else {
- notifier.sendFilesToRecipient(bot, *approver.TelegramID, approval, fullText, keyboard.BuildApproverDecision(approvalID, status, len(files) > 0, len(files)))
+ notifier.sendFilesToRecipient(bot, *approver.TelegramID, approval, fullText, keyboard.BuildApproverDecision(approvalID, status, len(files) > 0, len(files), h.GetCommentsCount(ctx, *approval.ID)))
}
} else {
msg := tgbotapi.NewMessage(*approver.TelegramID, text)
msg.ParseMode = "HTML"
- msg.ReplyMarkup = keyboard.BuildApproverDecision(approvalID, status, len(files) > 0, len(files))
+ msg.ReplyMarkup = keyboard.BuildApproverDecision(approvalID, status, len(files) > 0, len(files), h.GetCommentsCount(ctx, *approval.ID))
bot.Send(msg) //nolint:errcheck
}
}
@@ -456,7 +456,7 @@ func (h *Handler) HandleRevisionFileInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Me
return true
}
- base64Data, err := fetchFileAsBase64(fileURL, h.ipc.Config.Telegram) // используем существующую функцию
+ base64Data, err := fetchFileAsBase64(fileURL) // используем существующую функцию
if err != nil {
logrus.Errorf("HandleRevisionFileInput: fetchFileAsBase64 err=%v", err)
sendText(bot, chatID, "Ошибка при обработке файла.")
@@ -488,7 +488,7 @@ func (h *Handler) HandleRevisionFileInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Me
// Показываем опции снова
optMsg := tgbotapi.NewMessage(chatID, fmt.Sprintf("📋 Заявка #%d на доработке:", approvalID))
optMsg.ParseMode = "HTML"
- optMsg.ReplyMarkup = keyboard.BuildRevisionOptions(approvalID)
+ optMsg.ReplyMarkup = keyboard.BuildRevisionOptions(approvalID, h.GetCommentsCount(ctx, 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
index ba11a5e..83829c3 100644
--- a/service/telegram_service/handlers/approval/selection_approver.go
+++ b/service/telegram_service/handlers/approval/selection_approver.go
@@ -2,11 +2,13 @@ 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"
@@ -18,8 +20,16 @@ func (h *Handler) showApproverSelection(bot *tgbotapi.BotAPI, ctx context.Contex
return
}
- // Получаем список согласующих для этой темы
- approvers, err := h.getAvailableApproversForTopic(ctx, *user.ID, *user.DepartmentID, approvalTopic)
+ flowState, err := h.States.Get(ctx, telegramID)
+ if err != nil || flowState == nil {
+ sendText(bot, chatID, "⚠️ Состояние утеряно. Начните заново.")
+ return
+ }
+ var systems []string
+ if s := flowState.Collected["systems"]; s != "" {
+ systems = strings.Split(s, ",")
+ }
+ approvers, err := h.getAvailableApproversForTopic(ctx, *user.ID, *user.DepartmentID, approvalTopic, systems)
if err != nil {
logrus.Errorf("showApproverSelection: getAvailableApproversForTopic err=%v", err)
sendText(bot, chatID, "Ошибка при получении списка согласующих.")
@@ -107,7 +117,11 @@ func (h *Handler) HandleApproverSelectionPageCallback(bot *tgbotapi.BotAPI, cq *
return
}
- approvers, err := h.getAvailableApproversForTopic(ctx, *user.ID, *user.DepartmentID, approvalTopic)
+ var systems []string
+ if s := flowState.Collected["systems"]; s != "" {
+ systems = strings.Split(s, ",")
+ }
+ approvers, err := h.getAvailableApproversForTopic(ctx, *user.ID, *user.DepartmentID, approvalTopic, systems)
if err != nil {
logrus.Errorf("HandleApproverSelectionPageCallback: getAvailableApproversForTopic err=%v", err)
return
@@ -119,12 +133,34 @@ func (h *Handler) HandleApproverSelectionPageCallback(bot *tgbotapi.BotAPI, cq *
bot.Send(msg) //nolint:errcheck
}
-func (h *Handler) getAvailableApproversForTopic(ctx context.Context, userID, departmentID uint64, approvalTopic *typescore.ApprovalTopic) ([]*typescore.User, error) {
+// getAvailableApproversForTopic возвращает кандидатов в согласующие для ручного
+// выбора.
+//
+// ИСПРАВЛЕНО (было 2 самостоятельных бага, из-за которых поведение расходилось
+// с SQL-версией GetApproversDB):
+//
+// 1. Не было приоритета специфичности. Раньше запись, подходящая по topic_id,
+// и запись, подходящая только по topic_category_id, учитывались ОДНОВРЕМЕННО.
+// В SQL-версии всегда побеждает самый специфичный уровень: topic > category > global.
+// Теперь здесь та же логика: сначала вычисляем минимальную специфичность
+// среди подходящих записей, затем используем только записи этого уровня.
+//
+// 2. Полностью игнорировались "глобальные" записи иерархии — те, где
+// TopicID и TopicCategoryID оба NULL (уровень specGlobal / specificity=3
+// в SQL). В автоматическом резолве (GetApproversDB) такие записи
+// учитываются как fallback, а здесь для ручного выбора — нет, то есть
+// в ручном списке мог быть пустой результат там, где автоматика
+// нашла бы согласующего.
+//
+// Также раньше учитывалась только systems[0] — при мультивыборе систем
+// (например "okb,1c") override по системе, отличной от первой, никогда не
+// применялся. Теперь запись считается override, если её target_system
+// совпадает с ЛЮБОЙ из выбранных систем.
+func (h *Handler) getAvailableApproversForTopic(ctx context.Context, userID, departmentID uint64, approvalTopic *typescore.ApprovalTopic, systems []string) ([]*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,
@@ -135,23 +171,82 @@ func (h *Handler) getAvailableApproversForTopic(ctx context.Context, userID, dep
return nil, err
}
- // Собираем уникальных согласующих для этой темы или категории
- approverIDs := make(map[uint64]bool)
+ const (
+ specTopic = iota
+ specCategory
+ specGlobal
+ specNone // не подходит вообще
+ )
+
+ type candidate struct {
+ approverID uint64
+ targetSystem string
+ spec int
+ }
+
+ var candidates []candidate
+ minSpec := specNone
for _, hier := range hierarchies {
if hier.ApproverID == nil {
continue
}
- // Проверяем совпадение по теме
- if hier.TopicID != nil && *hier.TopicID == *approvalTopic.ID {
- approverIDs[*hier.ApproverID] = true
+ spec := specNone
+ switch {
+ case hier.TopicID != nil && *hier.TopicID == *approvalTopic.ID:
+ spec = specTopic
+ case hier.TopicCategoryID != nil && *hier.TopicCategoryID == *approvalTopic.CategoryID:
+ spec = specCategory
+ case hier.TopicID == nil && hier.TopicCategoryID == nil:
+ spec = specGlobal
+ default:
continue
}
- // Проверяем совпадение по категории
- if hier.TopicCategoryID != nil && *hier.TopicCategoryID == *approvalTopic.CategoryID {
- approverIDs[*hier.ApproverID] = true
+ ts := ""
+ if hier.TargetSystem != nil {
+ ts = *hier.TargetSystem
}
+
+ candidates = append(candidates, candidate{
+ approverID: *hier.ApproverID,
+ targetSystem: ts,
+ spec: spec,
+ })
+ if spec < minSpec {
+ minSpec = spec
+ }
+ }
+
+ // Набор выбранных систем — override применяется, если запись целится в
+ // любую из них (а не только в systems[0], как было раньше).
+ systemSet := make(map[string]bool, len(systems))
+ for _, s := range systems {
+ s = strings.TrimSpace(s)
+ if s != "" {
+ systemSet[s] = true
+ }
+ }
+
+ var overrideIDs, commonIDs = make(map[uint64]bool), make(map[uint64]bool)
+ for _, c := range candidates {
+ if c.spec != minSpec {
+ continue // берём только самый специфичный уровень
+ }
+
+ switch {
+ case c.targetSystem != "" && c.targetSystem != "all" && systemSet[c.targetSystem]:
+ overrideIDs[c.approverID] = true
+ case c.targetSystem == "" || c.targetSystem == "all":
+ commonIDs[c.approverID] = true
+ }
+ }
+
+ // Если для выбранной системы (систем) настроен override — показываем
+ // только его состав, иначе — общий список (как раньше).
+ approverIDs := commonIDs
+ if len(overrideIDs) > 0 {
+ approverIDs = overrideIDs
}
var approvers []*typescore.User
@@ -166,7 +261,7 @@ func (h *Handler) getAvailableApproversForTopic(ctx context.Context, userID, dep
}
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)
+ approvals, err := h.submitApproval(ctx, bot, telegramID, flowState)
if err != nil {
logrus.Errorf("finalizeAndSubmit: submitApproval error: %v", err)
@@ -181,12 +276,76 @@ func (h *Handler) finalizeAndSubmit(bot *tgbotapi.BotAPI, ctx context.Context, c
return
}
- if approval == nil || approval.ID == nil {
- logrus.Error("finalizeAndSubmit: approval is nil after submitApproval")
+ if len(approvals) == 0 {
+ logrus.Error("finalizeAndSubmit: no approvals returned by submitApproval")
bot.Send(tgbotapi.NewMessage(chatID, "📤 Отправлено на согласование")) //nolint:errcheck
return
}
+ for _, approval := range approvals {
+ h.sendConfirmationCard(bot, ctx, chatID, telegramID, flowState, approval)
+ }
+}
+
+// getActualApprover проверяет, нет ли активного делегирования у назначенного согласующего
+// по конкретной теме или её категории. Возвращает актуального пользователя.
+func (h *Handler) getActualApprover(ctx context.Context, originalApprover *typescore.User, topicID *uint64) *typescore.User {
+ if originalApprover == nil || originalApprover.ID == nil || topicID == nil {
+ return originalApprover
+ }
+
+ topic, err := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *topicID)
+ if err != nil || topic == nil {
+ return originalApprover
+ }
+
+ // 1. Проверяем делегирование конкретно по этой теме
+ if delegations, _, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalDelegation{
+ DelegatorID: originalApprover.ID,
+ TopicID: topicID,
+ IsActive: utilscore.PointerToBool(true),
+ },
+ }); err == nil {
+ for _, deleg := range delegations {
+ if deleg.ValidUntil != nil && deleg.ValidUntil.After(time.Now()) && deleg.DelegateID != nil {
+ if delegateUser, err := h.ipc.Database.User.GetUserByIDDB(ctx, *deleg.DelegateID); err == nil && delegateUser != nil {
+ return delegateUser // Нашли делегата по теме
+ }
+ }
+ }
+ }
+
+ // 2. Если по теме нет, проверяем делегирование по всей категории
+ if topic.CategoryID != nil {
+ if delegations, _, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalDelegation{
+ DelegatorID: originalApprover.ID,
+ CategoryID: topic.CategoryID,
+ IsActive: utilscore.PointerToBool(true),
+ },
+ }); err == nil {
+ for _, deleg := range delegations {
+ if deleg.ValidUntil != nil && deleg.ValidUntil.After(time.Now()) && deleg.DelegateID != nil {
+ if delegateUser, err := h.ipc.Database.User.GetUserByIDDB(ctx, *deleg.DelegateID); err == nil && delegateUser != nil {
+ return delegateUser
+ }
+ }
+ }
+ }
+ }
+
+ return originalApprover
+}
+
+// sendConfirmationCard формирует и отправляет карточку подтверждения для ОДНОЙ
+// заявки. Раньше это был "хвост" finalizeAndSubmit — логика не менялась,
+// просто вынесена в отдельную функцию, чтобы вызываться в цикле по заявкам.
+func (h *Handler) sendConfirmationCard(bot *tgbotapi.BotAPI, ctx context.Context, chatID int64, telegramID int64, flowState *state.ApprovalFlowState, approval *typescore.Approval) {
+ if approval == nil || approval.ID == nil {
+ return
+ }
+
var approvalTopic *typescore.ApprovalTopic
if approval.TopicID != nil {
approvalTopic, _ = h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID)
@@ -206,8 +365,18 @@ func (h *Handler) finalizeAndSubmit(bot *tgbotapi.BotAPI, ctx context.Context, c
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 originalApprover, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *s.ApproverID); originalApprover != nil {
+ // 🚀 Проверяем делегирование
+ actualApprover := h.getActualApprover(ctx, originalApprover, approval.TopicID)
+
+ if actualApprover != nil && actualApprover.FullName != nil {
+ name := *actualApprover.FullName
+ // Добавляем пометку, если сработало делегирование
+ if actualApprover.ID != nil && originalApprover.ID != nil && *actualApprover.ID != *originalApprover.ID {
+ name += fmt.Sprintf(" (Делегат от %s)", *originalApprover.FullName)
+ }
+ names = append(names, name)
+ }
}
}
}
@@ -227,36 +396,68 @@ func (h *Handler) finalizeAndSubmit(bot *tgbotapi.BotAPI, ctx context.Context, c
}
if firstStep != nil && firstStep.ApproverID != nil {
- if approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *firstStep.ApproverID); approver != nil && approver.FullName != nil {
- approverLine = *approver.FullName
+ if originalApprover, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *firstStep.ApproverID); originalApprover != nil {
+ actualApprover := h.getActualApprover(ctx, originalApprover, approval.TopicID)
+
+ if actualApprover != nil && actualApprover.FullName != nil {
+ approverLine = *actualApprover.FullName
+ if actualApprover.ID != nil && originalApprover.ID != nil && *actualApprover.ID != *originalApprover.ID {
+ approverLine += fmt.Sprintf(" (Временно исполняющий обязанности за: %s)", *originalApprover.FullName)
+ }
+ }
}
}
}
}
- topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID)
+ topic, err := h.Registry.Get(flowState.TopicCode)
+ if err != nil || topic == nil {
+ logrus.Errorf("sendConfirmationCard: Registry.Get(%s) err=%v", flowState.TopicCode, err)
+ }
- content := "—"
- if approval.Content != nil {
- content = *approval.Content
+ initiator, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, int64(telegramID))
+ if err != nil || initiator == nil {
+ logrus.Errorf("sendConfirmationCard: GetUserByTelegramIDDB err=%v", err)
+ }
+
+ // Метаданные заявки уже содержат её собственную (единственную) систему —
+ // восстанавливаем collected именно из meta, а не из flowState.Collected
+ // (там всё ещё общий "okb,1c" по всем заявкам мультивыбора).
+ collectedForCard := make(map[string]string, len(flowState.Collected))
+ for k, v := range flowState.Collected {
+ if k == "instructions" {
+ continue
+ }
+ collectedForCard[k] = v
+ }
+ if meta, mErr := typescore.ParseApprovalMetadata(approval.Metadata); mErr == nil && meta != nil && len(meta.SelectedSystems) > 0 {
+ collectedForCard["systems"] = strings.Join(meta.SelectedSystems, ",")
+ }
+
+ var card string
+ if topic != nil {
+ card = topic.FormatApproverMessage(initiator, collectedForCard)
+ } else {
+ topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID)
+ content := "—"
+ if approval.Content != nil {
+ content = *approval.Content
+ }
+ card = fmt.Sprintf("📋 Тема: %s\n📝 Текст: %s", topicFullName, content)
}
var confirmMsg string
if isAnyOf {
confirmMsg = fmt.Sprintf(
- "📤 Заявка #%d отправлена на согласование\n\n"+
- "👤 Согласует один из: %s\n\n"+
- "📋 Тема: %s\n"+
- "📝 Текст: %s",
- *approval.ID, approverLine, topicFullName, content,
+ "📤 Заявка #%d отправлена на согласование\n"+
+ "👤 Согласует один из: %s\n\n%s",
+ *approval.ID, approverLine, card,
)
} else {
confirmMsg = fmt.Sprintf(
- "📤 Заявка #%d отправлена на согласование\n\n"+
- "👤 Согласующий: %s\n\n"+
- "📋 Тема: %s\n"+
- "📝 Текст: %s",
- *approval.ID, approverLine, topicFullName, content,
+ "📤 Заявка #%d отправлена на согласование\n"+
+ "👤 Согласующий: %s\n\n%s",
+ *approval.ID, approverLine, card,
)
}
@@ -267,11 +468,78 @@ func (h *Handler) finalizeAndSubmit(bot *tgbotapi.BotAPI, ctx context.Context, c
if approval.Status != nil {
approvalStatus = *approval.Status
}
- msgChat.ReplyMarkup = keyboard.BuildInitiatorCard(*approval.ID, approvalStatus, len(approval.Files) > 0, len(approval.Files))
+ msgChat.ReplyMarkup = keyboard.BuildInitiatorCard(*approval.ID, approvalStatus, len(approval.Files) > 0, len(approval.Files), h.GetCommentsCount(ctx, *approval.ID))
bot.Send(msgChat) //nolint:errcheck
}
+// getActualTaskExecutor проверяет, не делегировал ли оригинальный исполнитель свои задачи.
+// Возвращает: (Актуальный исполнитель, Было ли делегирование, Оригинальный исполнитель)
+func (h *Handler) getActualTaskExecutor(ctx context.Context, originalExecutor *typescore.User, topicID *uint64) (*typescore.User, bool, *typescore.User) {
+ if originalExecutor == nil || originalExecutor.ID == nil || topicID == nil {
+ return originalExecutor, false, nil
+ }
+
+ topic, err := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *topicID)
+ if err != nil || topic == nil {
+ return originalExecutor, false, nil
+ }
+
+ // Функция для поиска активного делегата по фильтру
+ findDelegate := func(filter *typescore.TaskDelegation) *typescore.User {
+ delegations, _, err := h.ipc.Database.TaskDelegation.GetTaskDelegationsListDB(ctx, typescore.ListDbOptions{
+ Filtering: filter,
+ })
+ if err == nil && len(delegations) > 0 {
+ deleg := delegations[0]
+ if deleg.ValidUntil != nil && deleg.ValidUntil.After(time.Now()) && deleg.DelegateID != nil {
+ if delegateUser, err := h.ipc.Database.User.GetUserByIDDB(ctx, *deleg.DelegateID); err == nil && delegateUser != nil {
+ return delegateUser
+ }
+ }
+ }
+ return nil
+ }
+
+ if delegate := findDelegate(&typescore.TaskDelegation{
+ DelegatorID: originalExecutor.ID,
+ TopicID: topicID,
+ IsActive: utilscore.PointerToBool(true),
+ }); delegate != nil {
+ return delegate, true, originalExecutor
+ }
+
+ if topic.CategoryID != nil {
+ if delegate := findDelegate(&typescore.TaskDelegation{
+ DelegatorID: originalExecutor.ID,
+ CategoryID: topic.CategoryID,
+ IsActive: utilscore.PointerToBool(true),
+ }); delegate != nil {
+ return delegate, true, originalExecutor
+ }
+ }
+
+ globalDelegations, _, err := h.ipc.Database.TaskDelegation.GetTaskDelegationsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.TaskDelegation{
+ DelegatorID: originalExecutor.ID,
+ IsActive: utilscore.PointerToBool(true),
+ },
+ })
+ if err == nil {
+ for _, deleg := range globalDelegations {
+ if deleg.TopicID == nil && deleg.CategoryID == nil && deleg.ValidUntil != nil && deleg.ValidUntil.After(time.Now()) {
+ if deleg.DelegateID != nil {
+ if delegateUser, err := h.ipc.Database.User.GetUserByIDDB(ctx, *deleg.DelegateID); err == nil && delegateUser != nil {
+ return delegateUser, true, originalExecutor
+ }
+ }
+ }
+ }
+ }
+
+ return originalExecutor, false, nil
+}
+
// createTasksForApproval создаёт задачи для исполнителей на основе конфигурации темы
func (h *Handler) createTasksForApproval(
bot *tgbotapi.BotAPI,
@@ -324,12 +592,20 @@ func (h *Handler) createTasksForApproval(
continue
}
- executor, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *topicExec.UserID)
- if executor == nil || executor.ID == nil {
+ originalExecutor, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *topicExec.UserID)
+ if originalExecutor == nil || originalExecutor.ID == nil {
continue
}
+ actualExecutor, isDelegated, origExec := h.getActualTaskExecutor(ctx, originalExecutor, approval.TopicID)
+
taskText := *topicExec.TaskText
+
+ // Если задача делегирована, добавляем пометку в текст задачи
+ if isDelegated && origExec != nil && origExec.FullName != nil {
+ taskText = fmt.Sprintf("[Делегировано от: %s]\n%s", *origExec.FullName, taskText)
+ }
+
systemLabel := ""
if system != "all" && system != "" {
switch system {
@@ -352,22 +628,25 @@ func (h *Handler) createTasksForApproval(
requireFile = *topicExec.RequireFile
}
+ // Создаем задачу на АКТУАЛЬНОГО исполнителя
createdTask, _, err := h.ipc.Database.ApprovalTasks.CreateApprovalTaskDB(ctx, nil, &typescore.ApprovalTask{
ApprovalID: approval.ID,
- ExecutorID: executor.ID,
+ ExecutorID: actualExecutor.ID, // <--- Подменённый 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)
+ logrus.Errorf("createTasksForApproval: CreateApprovalTask system=%s executor=%d err=%v", system, *actualExecutor.ID, err)
continue
}
- if createdTask != nil && taskStatus == "pending" && executor.TelegramID != nil {
- h.notifyExecutor(bot, ctx, executor, initiator, approval, createdTask)
+ // Уведомляем АКТУАЛЬНОГО исполнителя
+ if createdTask != nil && taskStatus == "pending" && actualExecutor.TelegramID != nil {
+ h.notifyExecutor(bot, ctx, actualExecutor, initiator, approval, createdTask)
}
taskCounter++
diff --git a/service/telegram_service/handlers/approval/topics/dealautoapproval/topic.go b/service/telegram_service/handlers/approval/topics/dealautoapproval/topic.go
new file mode 100644
index 0000000..7411f74
--- /dev/null
+++ b/service/telegram_service/handlers/approval/topics/dealautoapproval/topic.go
@@ -0,0 +1,92 @@
+package dealautoapproval
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/telegram_service/approvalflow"
+ "fmt"
+)
+
+type DealAutoApprovalTopic struct{}
+
+func NewDealAutoApprovalTopic() *DealAutoApprovalTopic { return &DealAutoApprovalTopic{} }
+
+func (d *DealAutoApprovalTopic) Code() string { return "deal_auto_approval_conditions" }
+func (d *DealAutoApprovalTopic) Name() string {
+ return "Смена условий автосогласования сделок"
+}
+
+func (d *DealAutoApprovalTopic) BuildTree() *approvalflow.FlowNode {
+ return &approvalflow.FlowNode{
+ Key: "deal_auto_approval_conditions",
+ Label: "Смена условий автосогласования сделок",
+ Children: []*approvalflow.FlowNode{
+ {
+ Key: "receivable_limit_vladimir", Label: "📈 Повысить лимит ДЗ (Владимир)",
+ DataKey: "condition_type", DataValue: "receivable_limit_vladimir",
+ Children: []*approvalflow.FlowNode{
+ {
+ Key: "receivable_limit_vladimir_input",
+ IsInput: true,
+ InputKey: "content",
+ InputHint: "Прошу повысить лимит дебиторской задолженности клиенту ___ до ___ руб. Основание: ___",
+ },
+ },
+ },
+ {
+ Key: "document_limits", Label: "📄 Расширить лимиты по документам",
+ DataKey: "condition_type", DataValue: "document_limits",
+ Children: []*approvalflow.FlowNode{
+ {
+ Key: "document_limits_input",
+ IsInput: true,
+ InputKey: "content",
+ InputHint: "Прошу увеличить: кол-во возможных долгов по документам до ___, сумму документов до ___ руб., кол-во дней просрочки оплаты до ___",
+ },
+ },
+ },
+ },
+ }
+}
+
+func (d *DealAutoApprovalTopic) TopicCodeFromCollected(collected map[string]string) (string, error) {
+ conditionType := collected["condition_type"]
+ if conditionType == "" {
+ return "", fmt.Errorf("неполные данные: condition_type пуст")
+ }
+
+ switch conditionType {
+ case "receivable_limit_vladimir":
+ return "deal_auto_approval_receivable_limit_vladimir", nil
+ case "document_limits":
+ return "deal_auto_approval_document_limits", nil
+ default:
+ return "", fmt.Errorf("неизвестный condition_type: %s", conditionType)
+ }
+}
+
+func (d *DealAutoApprovalTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string {
+ name := "—"
+ if initiator != nil && initiator.FullName != nil {
+ name = *initiator.FullName
+ }
+
+ var typeLabel string
+ switch collected["condition_type"] {
+ case "receivable_limit_vladimir":
+ typeLabel = "Повышение лимита ДЗ (от Владимира лично)"
+ case "document_limits":
+ typeLabel = "Расширение лимитов по документам и просрочке"
+ default:
+ typeLabel = "Смена условий автосогласования сделок"
+ }
+
+ content := "—"
+ if collected["content"] != "" {
+ content = collected["content"]
+ }
+
+ return fmt.Sprintf(
+ "📋 Смена условий автосогласования сделок - %s\n\n👤 Инициатор: %s\n📝 Текст:\n%s",
+ typeLabel, name, content,
+ )
+}
diff --git a/service/telegram_service/handlers/approval/topics/deliveryclients/topic.go b/service/telegram_service/handlers/approval/topics/deliveryclients/topic.go
new file mode 100644
index 0000000..cfc3653
--- /dev/null
+++ b/service/telegram_service/handlers/approval/topics/deliveryclients/topic.go
@@ -0,0 +1,113 @@
+package deliveryclients
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/telegram_service/approvalflow"
+ "fmt"
+)
+
+type DeliveryClientsTopic struct{}
+
+func NewDeliveryClientsTopic() *DeliveryClientsTopic { return &DeliveryClientsTopic{} }
+
+func (d *DeliveryClientsTopic) Code() string { return "delivery_clients" }
+func (d *DeliveryClientsTopic) Name() string {
+ return "Доставка клиентам/на склад"
+}
+
+func (d *DeliveryClientsTopic) BuildTree() *approvalflow.FlowNode {
+ directHint := "Иванов Иван Иванович\nТел 89781234567\nПаспорт 1234 567890\nДАФ н862нн46 п/п АА8473|46\n\n61 бц с ад - 52 кор\nЧП000001676\n\nЕПР-СтройКрым"
+ warehouseHint := "Иванов Иван Иванович\nТел 89781234567\nПаспорт 1234 567890\n61 бц с ад - 52 кор\nЧП000001676"
+
+ return &approvalflow.FlowNode{
+ Key: "delivery_clients",
+ Label: "Доставка клиентам/на склад",
+ Children: []*approvalflow.FlowNode{
+ {
+ Key: "direct", Label: "Напрямую клиенту",
+ DataKey: "delivery_type", DataValue: "direct",
+ Children: []*approvalflow.FlowNode{
+ {
+ Key: "direct_input",
+ IsInput: true,
+ InputKey: "content",
+ InputHint: directHint,
+ },
+ },
+ },
+ {
+ Key: "warehouse", Label: "На склад",
+ DataKey: "delivery_type", DataValue: "warehouse",
+ Children: []*approvalflow.FlowNode{
+ d.buildRegion("warehouse", "crimea", "Крым", warehouseHint),
+ d.buildRegion("warehouse", "krasnodar", "Краснодар", warehouseHint),
+ },
+ },
+ },
+ }
+}
+
+func (d *DeliveryClientsTopic) buildRegion(parentKey, regionKey, regionLabel, hint string) *approvalflow.FlowNode {
+ return &approvalflow.FlowNode{
+ Key: parentKey + "_" + regionKey,
+ Label: regionLabel,
+ DataKey: "region",
+ DataValue: regionKey,
+ Children: []*approvalflow.FlowNode{
+ {
+ Key: parentKey + "_" + regionKey + "_input",
+ IsInput: true,
+ InputKey: "content",
+ InputHint: hint,
+ },
+ },
+ }
+}
+
+func (d *DeliveryClientsTopic) TopicCodeFromCollected(collected map[string]string) (string, error) {
+ deliveryType := collected["delivery_type"]
+ if deliveryType == "" {
+ return "", fmt.Errorf("неполные данные: delivery_type пуст")
+ }
+
+ if deliveryType == "direct" {
+ return "delivery_clients_direct", nil
+ }
+
+ region := collected["region"]
+ if region == "" {
+ return "", fmt.Errorf("неполные данные: region пуст")
+ }
+ return fmt.Sprintf("delivery_clients_warehouse_%s", region), nil
+}
+
+func (d *DeliveryClientsTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string {
+ name := "—"
+ if initiator != nil && initiator.FullName != nil {
+ name = *initiator.FullName
+ }
+
+ var label string
+ if collected["delivery_type"] == "direct" {
+ label = "Доставка: Напрямую клиенту"
+ } else {
+ regionLabel := "—"
+ switch collected["region"] {
+ case "crimea":
+ regionLabel = "Крым"
+ case "krasnodar":
+ regionLabel = "Краснодар"
+ }
+ label = fmt.Sprintf("Доставка: На склад, %s", regionLabel)
+ }
+
+ content := "—"
+ if collected["content"] != "" {
+ content = collected["content"]
+ }
+
+ return fmt.Sprintf(
+ "📋 %s\n\n👤 Инициатор: %s\n📝 Текст:\n%s",
+ label, name, content,
+ )
+}
diff --git a/service/telegram_service/handlers/approval/topics/inventory/topic.go b/service/telegram_service/handlers/approval/topics/inventory/topic.go
new file mode 100644
index 0000000..cdd40dc
--- /dev/null
+++ b/service/telegram_service/handlers/approval/topics/inventory/topic.go
@@ -0,0 +1,111 @@
+package inventory
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/telegram_service/approvalflow"
+ "fmt"
+)
+
+type InventoryTopic struct{}
+
+func NewInventoryTopic() *InventoryTopic { return &InventoryTopic{} }
+
+func (i *InventoryTopic) Code() string { return "inventory" }
+func (i *InventoryTopic) Name() string { return "Инвентаризация" }
+
+func (i *InventoryTopic) BuildTree() *approvalflow.FlowNode {
+ return &approvalflow.FlowNode{
+ Key: "inventory",
+ Label: "Инвентаризация",
+ Children: []*approvalflow.FlowNode{
+ {
+ Key: "crimea", Label: "Крым",
+ DataKey: "region", DataValue: "crimea",
+ Children: []*approvalflow.FlowNode{
+ i.buildLocation("crimea", "19l", "19л"),
+ i.buildLocation("crimea", "gvardeyskoe", "Гвардейское"),
+ },
+ },
+ {
+ // Краснодар без развилки — сразу ввод
+ Key: "krasnodar", Label: "Краснодар",
+ DataKey: "region", DataValue: "krasnodar",
+ Children: []*approvalflow.FlowNode{
+ {
+ Key: "krasnodar_input",
+ IsInput: true,
+ InputKey: "content",
+ InputHint: "Прошу согласовать проведение инвентаризации по складу (Наименование склада\\Филиал склада) 25.06.2026, 27.06.2026. \nШироков Михаил, Жеребцов Виктор",
+ },
+ },
+ },
+ },
+ }
+}
+
+func (i *InventoryTopic) buildLocation(regionKey, locKey, locLabel string) *approvalflow.FlowNode {
+ return &approvalflow.FlowNode{
+ Key: regionKey + "_" + locKey,
+ Label: locLabel,
+ DataKey: "location",
+ DataValue: locKey,
+ Children: []*approvalflow.FlowNode{
+ {
+ Key: regionKey + "_" + locKey + "_input",
+ IsInput: true,
+ InputKey: "content",
+ InputHint: "Прошу согласовать проведение инвентаризации по складу (Наименование склада\\Филиал склада) 25.06.2026, 27.06.2026. \nХалилов Дамур, Анисимов Виталий, Романов Александр",
+ },
+ },
+ }
+}
+
+func (i *InventoryTopic) TopicCodeFromCollected(collected map[string]string) (string, error) {
+ region := collected["region"]
+ if region == "" {
+ return "", fmt.Errorf("неполные данные: region пуст")
+ }
+
+ if region == "krasnodar" {
+ return "inventory_krasnodar", nil
+ }
+
+ location := collected["location"]
+ if location == "" {
+ return "", fmt.Errorf("неполные данные: location пуст")
+ }
+ return fmt.Sprintf("inventory_%s_%s", region, location), nil
+}
+
+func (i *InventoryTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string {
+ name := "—"
+ if initiator != nil && initiator.FullName != nil {
+ name = *initiator.FullName
+ }
+
+ regionLabel := "—"
+ switch collected["region"] {
+ case "crimea":
+ regionLabel = "Крым"
+ case "krasnodar":
+ regionLabel = "Краснодар"
+ }
+
+ locationLabel := ""
+ switch collected["location"] {
+ case "19l":
+ locationLabel = ", 19л"
+ case "gvardeyskoe":
+ locationLabel = ", Гвардейское"
+ }
+
+ content := "—"
+ if collected["content"] != "" {
+ content = collected["content"]
+ }
+
+ return fmt.Sprintf(
+ "📋 Инвентаризация: %s%s\n\n👤 Инициатор: %s\n📝 Текст:\n%s",
+ regionLabel, locationLabel, 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
index 54220a5..6231b1e 100644
--- a/service/telegram_service/handlers/approval/topics/payments_cashless/topic.go
+++ b/service/telegram_service/handlers/approval/topics/payments_cashless/topic.go
@@ -84,7 +84,7 @@ func (p *PaymentsCashlessTopic) FormatApproverMessage(initiator *typescore.User,
}
return fmt.Sprintf(
- "📋 Оплата безнал — %s%s\n\n%s:\n%s",
+ "📋 Утверждение оплат безнал — %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
index 72cd3bf..517a10d 100644
--- a/service/telegram_service/handlers/approval/topics/rates_logistics/topic.go
+++ b/service/telegram_service/handlers/approval/topics/rates_logistics/topic.go
@@ -13,12 +13,14 @@ func NewRatesLogisticsTopic() *RatesLogisticsTopic {
}
func (r *RatesLogisticsTopic) Code() string { return "rates_logistics" }
-func (r *RatesLogisticsTopic) Name() string { return "Ставки логистика" }
+func (r *RatesLogisticsTopic) Name() string {
+ return "Утверждение ставок логистики"
+}
func (r *RatesLogisticsTopic) BuildTree() *approvalflow.FlowNode {
return &approvalflow.FlowNode{
Key: "rates_logistics",
- Label: "Ставки логистика",
+ Label: "Утверждение ставок логистики",
Children: []*approvalflow.FlowNode{
{
Key: "once",
@@ -48,6 +50,20 @@ func (r *RatesLogisticsTopic) BuildTree() *approvalflow.FlowNode {
},
},
},
+ {
+ Key: "once_head_approval",
+ Label: "Разово согласовать с рук. отдела логистики",
+ DataKey: "rate_type",
+ DataValue: "once_head_approval",
+ Children: []*approvalflow.FlowNode{
+ {
+ Key: "once_head_approval_input",
+ IsInput: true,
+ InputKey: "content",
+ InputHint: "№ПП из таблицы транспорт и доставка клиенту\nНаправление\nЦена",
+ },
+ },
+ },
},
}
}
@@ -66,13 +82,18 @@ func (r *RatesLogisticsTopic) FormatApproverMessage(initiator *typescore.User, c
name = *initiator.FullName
}
- typeLabel := "Разово"
- if collected["rate_type"] == "long_term" {
+ var typeLabel string
+ switch collected["rate_type"] {
+ case "long_term":
typeLabel = "Надолго"
+ case "once_head_approval":
+ typeLabel = "Разово (с рук. отдела логистики)"
+ default:
+ typeLabel = "Разово"
}
return fmt.Sprintf(
- "📋 Ставки логистика — %s\n\n"+
+ "📋 Утверждение ставок логистики — %s\n\n"+
"%s:\n%s",
typeLabel, 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
index ba6977c..d9fa684 100644
--- a/service/telegram_service/handlers/approval/topics/returns/topic.go
+++ b/service/telegram_service/handlers/approval/topics/returns/topic.go
@@ -170,7 +170,7 @@ func (r *ReturnsTopic) FormatApproverMessage(initiator *typescore.User, collecte
}
return fmt.Sprintf(
- "📋 %s — %s\n\n"+
+ "📋 Возвраты: %s — %s\n\n"+
"%s:\n%s",
typeLabel, regionLabel, name, collected["content"],
)
diff --git a/service/telegram_service/handlers/approval/topics/vshipments/topic.go b/service/telegram_service/handlers/approval/topics/vshipments/topic.go
new file mode 100644
index 0000000..0cee386
--- /dev/null
+++ b/service/telegram_service/handlers/approval/topics/vshipments/topic.go
@@ -0,0 +1,127 @@
+package vshipments
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/telegram_service/approvalflow"
+ "fmt"
+)
+
+type VShipmentsTopic struct{}
+
+func NewVShipmentsTopic() *VShipmentsTopic { return &VShipmentsTopic{} }
+
+func (v *VShipmentsTopic) Code() string { return "v_shipments" }
+func (v *VShipmentsTopic) Name() string { return "В. Отгрузки" }
+
+func (v *VShipmentsTopic) BuildTree() *approvalflow.FlowNode {
+ return &approvalflow.FlowNode{
+ Key: "v_shipments",
+ Label: "В. Отгрузки",
+ Children: []*approvalflow.FlowNode{
+ v.buildLeaf("shipment", "В. Отгрузки",
+ "ООО Аква на сумму 1 000 000 руб. под 15%"),
+ {
+ Key: "advance",
+ Label: "Авансовая отгрузка",
+ DataKey: "subtype",
+ DataValue: "advance",
+ Children: []*approvalflow.FlowNode{
+ v.buildAdvanceLeaf("amount", "По сумме",
+ "ООО Аква на сумму 1 000 000 руб. от 30.06.2026"),
+ v.buildAdvanceLeaf("goods", "По товару",
+ "ООО Аква 29,2 гр.1810 бесцветная (8800) ОП - 52 кор - по 5,2 руб. итого на сумму 1 000 000 руб. от 30.06.2026"),
+ },
+ },
+ v.buildLeaf("receipt", "В. Поступления",
+ "ООО Нива на 370 тыс. руб. — поступление под 19%"),
+ },
+ }
+}
+
+func (v *VShipmentsTopic) buildLeaf(key, label, hint string) *approvalflow.FlowNode {
+ return &approvalflow.FlowNode{
+ Key: key,
+ Label: label,
+ DataKey: "subtype",
+ DataValue: key,
+ Children: []*approvalflow.FlowNode{
+ {
+ Key: key + "_input",
+ IsInput: true,
+ InputKey: "content",
+ InputHint: hint,
+ },
+ },
+ }
+}
+
+// buildAdvanceLeaf — под-развилка внутри "Авансовая отгрузка": по сумме / по товару
+func (v *VShipmentsTopic) buildAdvanceLeaf(key, label, hint string) *approvalflow.FlowNode {
+ return &approvalflow.FlowNode{
+ Key: "advance_" + key,
+ Label: label,
+ DataKey: "advance_type",
+ DataValue: key,
+ Children: []*approvalflow.FlowNode{
+ {
+ Key: "advance_" + key + "_input",
+ IsInput: true,
+ InputKey: "content",
+ InputHint: hint,
+ },
+ },
+ }
+}
+
+func (v *VShipmentsTopic) TopicCodeFromCollected(collected map[string]string) (string, error) {
+ subtype := collected["subtype"]
+ if subtype == "" {
+ return "", fmt.Errorf("неполные данные: subtype пуст")
+ }
+
+ if subtype == "advance" {
+ advanceType := collected["advance_type"]
+ if advanceType == "" {
+ return "", fmt.Errorf("неполные данные: advance_type пуст")
+ }
+ return fmt.Sprintf("v_shipments_advance_%s", advanceType), nil
+ }
+
+ return fmt.Sprintf("v_shipments_%s", subtype), nil
+}
+
+func (v *VShipmentsTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string {
+ name := "—"
+ if initiator != nil && initiator.FullName != nil {
+ name = *initiator.FullName
+ }
+
+ var label string
+ switch collected["subtype"] {
+ case "shipment":
+ label = "В. Отгрузки"
+ case "receipt":
+ label = "В. Поступления"
+ case "advance":
+ switch collected["advance_type"] {
+ case "amount":
+ label = "Авансовая отгрузка (по сумме)"
+ case "goods":
+ label = "Авансовая отгрузка (по товару)"
+ default:
+ label = "Авансовая отгрузка"
+ }
+ default:
+ label = "В. Отгрузки"
+ }
+
+ content := "—"
+ if collected["content"] != "" {
+ content = collected["content"]
+ }
+
+ return fmt.Sprintf(
+ "📋 В. Отгрузки - %s\n\n👤 Инициатор: %s\n📝 Текст:\n%s",
+ label, name, content,
+ )
+}
diff --git a/service/telegram_service/keyboard/absense_delegation_keyboard.go b/service/telegram_service/keyboard/absense_delegation_keyboard.go
new file mode 100644
index 0000000..9438161
--- /dev/null
+++ b/service/telegram_service/keyboard/absense_delegation_keyboard.go
@@ -0,0 +1,107 @@
+package keyboard
+
+import (
+ "bitrix_balancer_api/core/lib/external/tgkit"
+ "bitrix_balancer_api/core/typescore"
+ "fmt"
+
+ tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
+)
+
+// BuildDelegationChoiceMenu — клавиатура Да/Нет для вопроса о делегировании.
+func BuildDelegationChoiceMenu() tgbotapi.InlineKeyboardMarkup {
+ return tgbotapi.NewInlineKeyboardMarkup(
+ tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData("✅ Да", "appr_deleg_yes"),
+ tgbotapi.NewInlineKeyboardButtonData("❌ Нет", "appr_deleg_no"),
+ ),
+ )
+}
+
+const delegateCandidatesPerPage = 8
+
+// BuildDelegateSelectionMenu — постраничный список кандидатов на
+// делегирование (одиночный выбор, без toggle — в отличие от наблюдателей).
+func BuildDelegateSelectionMenu(candidates []*typescore.User, page int) tgbotapi.InlineKeyboardMarkup {
+ start := page * delegateCandidatesPerPage
+ if start > len(candidates) {
+ start = len(candidates)
+ }
+ end := start + delegateCandidatesPerPage
+ if end > len(candidates) {
+ end = len(candidates)
+ }
+
+ var rows [][]tgbotapi.InlineKeyboardButton
+ for _, u := range candidates[start:end] {
+ if u.ID == nil {
+ continue
+ }
+ name := "Без имени"
+ if u.FullName != nil {
+ name = *u.FullName
+ }
+ rows = append(rows, tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData(name, fmt.Sprintf("appr_deleg_sel:%d", *u.ID)),
+ ))
+ }
+
+ var navRow []tgbotapi.InlineKeyboardButton
+ if page > 0 {
+ navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData("⬅️ Назад", fmt.Sprintf("appr_deleg_pg:%d", page-1)))
+ }
+ if end < len(candidates) {
+ navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData("Вперёд ➡️", fmt.Sprintf("appr_deleg_pg:%d", page+1)))
+ }
+ if len(navRow) > 0 {
+ rows = append(rows, navRow)
+ }
+
+ return tgbotapi.NewInlineKeyboardMarkup(rows...)
+}
+
+func BuildTaskDelegationChoiceMenu() tgbotapi.InlineKeyboardMarkup {
+ return tgkit.NewInlineKeyboard().
+ Row(
+ tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "Да", "appr_task_deleg_yes"),
+ tgkit.BtnStyled(tgkit.ButtonStyleDanger, "Нет", "appr_task_deleg_no"),
+ ).Build()
+}
+
+func BuildAbsenceTaskDelegateMenu(candidates []*typescore.User, page int) interface{} {
+ start := page * delegateCandidatesPerPage
+ if start > len(candidates) {
+ start = len(candidates)
+ }
+ end := start + delegateCandidatesPerPage
+ if end > len(candidates) {
+ end = len(candidates)
+ }
+
+ var rows [][]tgbotapi.InlineKeyboardButton
+ for _, u := range candidates[start:end] {
+ if u.ID == nil {
+ continue
+ }
+ name := "Без имени"
+ if u.FullName != nil {
+ name = *u.FullName
+ }
+ rows = append(rows, tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData(name, fmt.Sprintf("appr_task_deleg_sel:%d", *u.ID)),
+ ))
+ }
+
+ var navRow []tgbotapi.InlineKeyboardButton
+ if page > 0 {
+ navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData("⬅️ Назад", fmt.Sprintf("appr_task_deleg_pg:%d", page-1)))
+ }
+ if end < len(candidates) {
+ navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData("Вперёд ➡️", fmt.Sprintf("appr_task_deleg_pg:%d", page+1)))
+ }
+ if len(navRow) > 0 {
+ rows = append(rows, navRow)
+ }
+
+ return tgbotapi.NewInlineKeyboardMarkup(rows...)
+}
diff --git a/service/telegram_service/keyboard/add_approver.go b/service/telegram_service/keyboard/add_approver.go
index 2ae5a3e..6cac8ae 100644
--- a/service/telegram_service/keyboard/add_approver.go
+++ b/service/telegram_service/keyboard/add_approver.go
@@ -1,5 +1,3 @@
-// telegram_service/keyboard/add_approver.go - ПОЛНОСТЬЮ ЗАМЕНИТЬ
-
package keyboard
import (
diff --git a/service/telegram_service/keyboard/approval.go b/service/telegram_service/keyboard/approval.go
index 10d1844..4ea6116 100644
--- a/service/telegram_service/keyboard/approval.go
+++ b/service/telegram_service/keyboard/approval.go
@@ -2,6 +2,7 @@ package keyboard
import (
"bitrix_balancer_api/core/lib/external/tgkit"
+ "bitrix_balancer_api/core/typescore"
"bitrix_balancer_api/core/utilscore"
"bitrix_balancer_api/telegram_service/approvalflow"
"bitrix_balancer_api/telegram_service/state"
@@ -10,12 +11,13 @@ import (
)
// BuildApproverDecision — кнопки для согласующего
-func BuildApproverDecision(approvalID uint64, status string, hasFiles bool, filesCount int) tgbotapi.InlineKeyboardMarkup {
+func BuildApproverDecision(approvalID uint64, status string, hasFiles bool, filesCount int, commentsCount 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)))
+ kb.Row(buildCommentsButton(approvalID, commentsCount))
return kb.Build()
}
@@ -24,7 +26,6 @@ func BuildApproverDecision(approvalID uint64, status string, hasFiles bool, file
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)),
@@ -32,6 +33,9 @@ func BuildApproverDecision(approvalID uint64, status string, hasFiles bool, file
Row(tgkit.Btn("🔄 Вернуть на доработку", fmt.Sprintf("appr_revision:%d", approvalID))).
Row(
tgkit.Btn("💬 Комментировать", fmt.Sprintf("appr_comment:%d", approvalID)),
+ buildCommentsButton(approvalID, commentsCount),
+ ).
+ Row(
tgkit.Btn("📎 Прикрепить файл", fmt.Sprintf("appr_attach:%d", approvalID)),
).
Row(
@@ -43,7 +47,7 @@ func BuildApproverDecision(approvalID uint64, status string, hasFiles bool, file
}
// BuildInitiatorCard — кнопки инициатора на карточке заявки
-func BuildInitiatorCard(approvalID uint64, status string, hasFiles bool, filesCount int) interface{} {
+func BuildInitiatorCard(approvalID uint64, status string, hasFiles bool, filesCount int, commentsCount int) interface{} {
kb := tgkit.NewInlineKeyboard()
if hasFiles {
@@ -54,6 +58,9 @@ func BuildInitiatorCard(approvalID uint64, status string, hasFiles bool, filesCo
if status != "approved" {
kb.Row(tgkit.Btn("💬 Комментировать", fmt.Sprintf("appr_comment:%d", approvalID)))
}
+ if commentsCount > 0 {
+ buildCommentsButton(approvalID, commentsCount)
+ }
if status == "pending" || status == "revision" || status == "approved" {
kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleRevision, "Отозвать", fmt.Sprintf("appr_revoke:%d", approvalID)))
@@ -64,13 +71,18 @@ func BuildInitiatorCard(approvalID uint64, status string, hasFiles bool, filesCo
}
// BuildRevokeButton — кнопка отзыва (для директора и инициатора)
-func BuildRevokeButton(approvalID uint64, status string, filesCount int) interface{} {
+func BuildRevokeButton(approvalID uint64, status string, filesCount int, commentsCount int) interface{} {
kb := tgkit.NewInlineKeyboard()
if filesCount > 0 {
kb.Row(tgkit.Btn(fmt.Sprintf("📎 Просмотреть файлы (%d)", filesCount), fmt.Sprintf("appr_view_files:%d", approvalID)))
}
+ kb.Row(
+ tgkit.Btn("💬 Комментировать", fmt.Sprintf("appr_comment:%d", approvalID)),
+ buildCommentsButton(approvalID, commentsCount),
+ )
+
if status == "pending" || status == "revision" || status == "approved" {
kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleRevision, "Отозвать заявку", fmt.Sprintf("appr_revoke:%d", approvalID)))
}
@@ -80,18 +92,19 @@ func BuildRevokeButton(approvalID uint64, status string, filesCount int) interfa
}
// BuildObserverActions — кнопки наблюдателя
-func BuildObserverActions(approvalID uint64, topicCode string, status string, filesCount int) interface{} {
+func BuildObserverActions(approvalID uint64, topicCode string, status string, filesCount, commentsCount int) tgbotapi.InlineKeyboardMarkup {
kb := tgkit.NewInlineKeyboard()
if filesCount > 0 {
- kb.Row(tgkit.Btn(fmt.Sprintf("📎 Просмотреть файлы (%d)", filesCount), fmt.Sprintf("appr_view_files:%d", approvalID)))
+ 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.Btn("💬 Комментировать", fmt.Sprintf("appr_comment:%d", approvalID)))
+ buildCommentsButton(approvalID, commentsCount)
- kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "К списку", fmt.Sprintf("obs_back:%s", topicCode)))
return kb.Build()
}
@@ -328,7 +341,7 @@ func BuildAttachSessionKeyboard(approvalID uint64, fileCount int) tgbotapi.Inlin
}
// BuildExecutorTaskActions — кнопки исполнителя
-func BuildExecutorTaskActions(taskID, approvalID uint64, filesCount int) interface{} {
+func BuildExecutorTaskActions(taskID, approvalID uint64, filesCount int, commentsCount int) interface{} {
kb := tgkit.NewInlineKeyboard()
if filesCount > 0 {
@@ -340,7 +353,41 @@ func BuildExecutorTaskActions(taskID, approvalID uint64, filesCount int) interfa
kb.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)))
+ Row(tgkit.Btn("🔁 Передать задачу", fmt.Sprintf("task_transfer_start:%d", taskID))). // 🆕
+ Row(
+ tgkit.Btn("💬 Комментировать", fmt.Sprintf("appr_comment:%d", approvalID)),
+ buildCommentsButton(approvalID, commentsCount),
+ )
return kb.Build()
}
+
+func BuildCommentVisibilityMenu() tgbotapi.InlineKeyboardMarkup {
+ return tgkit.NewInlineKeyboard().
+ Row(tgkit.Btn("📢 Отправить всем участникам", "comment_vis:all")).
+ Row(tgkit.Btn("👤 Выбрать конкретных", "comment_vis:specific")).
+ Row(tgkit.Btn("🔇 Заметка к заявке", "comment_vis:silent")).
+ Row(tgkit.BtnStyled(tgkit.ButtonStyleDanger, "Отмена", "comment_vis:cancel")).
+ Build()
+}
+
+func BuildCommentTargetsMenu(participants []*typescore.User, selected map[uint64]bool) tgbotapi.InlineKeyboardMarkup {
+ kb := tgkit.NewInlineKeyboard()
+
+ for _, p := range participants {
+ if p.ID == nil || p.FullName == nil {
+ continue
+ }
+ label := *p.FullName
+ if selected[*p.ID] {
+ label = "✅ " + label
+ } else {
+ label = "⬜ " + label
+ }
+ kb.Row(tgkit.Btn(label, fmt.Sprintf("comment_tgt:%d", *p.ID)))
+ }
+
+ kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "Отправить выбранным", "comment_tgt_done"))
+ kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "Назад", "comment_tgt_back"))
+ return kb.Build()
+}
diff --git a/service/telegram_service/keyboard/builder.go b/service/telegram_service/keyboard/builder.go
index 419a008..5d68d06 100644
--- a/service/telegram_service/keyboard/builder.go
+++ b/service/telegram_service/keyboard/builder.go
@@ -49,16 +49,29 @@ func ApprovalsListSubmenuKeyboard() tgbotapi.ReplyKeyboardMarkup {
}
// BuildCommentNotificationKeyboard — для уведомления инициатора о комментарии
-func BuildCommentNotificationKeyboard(approvalID uint64) interface{} {
+func BuildCommentNotificationKeyboard(approvalID uint64, commentsCount int) interface{} {
+ viewLabel := "💬 Посмотреть все комментарии"
+ if commentsCount > 0 {
+ viewLabel = fmt.Sprintf("💬 Посмотреть все комментарии (%d)", commentsCount)
+ }
+
return tgkit.NewInlineKeyboard().
Row(tgkit.Btn("↩️ Ответить на комментарий", fmt.Sprintf("comment_reply:%d", approvalID))).
+ Row(tgkit.Btn("💬 Добавить комментарий", fmt.Sprintf("appr_comment:%d", approvalID))).
+ Row(tgkit.Btn(viewLabel, fmt.Sprintf("appr_view_comments:%d", approvalID))).
Build()
}
// BuildCommentReplyKeyboard — для согласующего/наблюдателя при получении ответа
-func BuildCommentReplyKeyboard(approvalID uint64) interface{} {
+func BuildCommentReplyKeyboard(approvalID uint64, commentsCount int) interface{} {
+ viewLabel := "💬 Посмотреть все комментарии"
+ if commentsCount > 0 {
+ viewLabel = fmt.Sprintf("💬 Посмотреть все комментарии (%d)", commentsCount)
+ }
+
return tgkit.NewInlineKeyboard().
Row(tgkit.Btn("↩️ Ответить на комментарий", fmt.Sprintf("comment_reply:%d", approvalID))).
Row(tgkit.Btn("💬 Добавить комментарий", fmt.Sprintf("appr_comment:%d", approvalID))).
+ Row(tgkit.Btn(viewLabel, fmt.Sprintf("appr_view_comments:%d", approvalID))).
Build()
}
diff --git a/service/telegram_service/keyboard/delegation.go b/service/telegram_service/keyboard/delegation.go
index 75e6cd4..88e76f2 100644
--- a/service/telegram_service/keyboard/delegation.go
+++ b/service/telegram_service/keyboard/delegation.go
@@ -15,8 +15,10 @@ const delegationPerPage = 6
func BuildDelegationMainMenu() interface{} {
return tgkit.NewInlineKeyboard().
- Row(tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "Делегировать права", "deleg_create")).
- Row(tgkit.Btn("📋 Делегированные права", "deleg_list")).
+ Row(tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "Делегировать заявки", "deleg_create")).
+ Row(tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "Делегировать задачи", "deleg_task_create")).
+ Row(tgkit.Btn("📋 Мои делегирования (Заявки)", "deleg_list")).
+ Row(tgkit.Btn("📋 Мои делегирования (Задачи)", "deleg_task_list")).
Build()
}
@@ -170,3 +172,151 @@ func BuildDelegationBackToUsers(categoryID, topicID uint64) tgbotapi.InlineKeybo
Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "Назад", callback)).
Build()
}
+
+// --- КЛАВИАТУРЫ ДЛЯ ДЕЛЕГИРОВАНИЯ ЗАДАЧ ---
+
+// BuildTaskDelegationUserMenu выводит список пользователей для передачи задач
+func BuildTaskDelegationUserMenu(users []*typescore.User, 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_task_user:%d", *u.ID)))
+ }
+ if totalPages > 1 {
+ kb.Rows = append(kb.Rows, buildPageRow(page, totalPages, "deleg_task_user_page", "deleg_page_noop"))
+ }
+ // Кнопка возврата в главное меню делегирования
+ kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "Назад", "deleg_main_menu"))
+ return kb.Build()
+}
+
+// BuildTaskDelegatedRightsList выводит список ваших активных делегирований задач
+func BuildTaskDelegatedRightsList(delegations []*typescore.TaskDelegation, 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 || d.DelegateID == nil {
+ continue
+ }
+ delegateName := "Неизвестно"
+ if u, _ := ipc.Database.User.GetUserByIDDB(ctx, *d.DelegateID); u != nil && u.FullName != nil {
+ delegateName = *u.FullName
+ }
+
+ kb.Row(tgkit.Btn(fmt.Sprintf("Задачи ➡️ %s", delegateName), fmt.Sprintf("deleg_task_detail:%d", *d.ID)))
+ }
+ if totalPages > 1 {
+ kb.Rows = append(kb.Rows, buildPageRow(page, totalPages, "deleg_task_list_page", "deleg_page_noop"))
+ }
+ kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "В главное меню", "deleg_main_menu"))
+ return kb.Build()
+}
+
+// BuildTaskDelegationActions выводит кнопки управления (Отозвать/Продлить) конкретным делегированием задач
+func BuildTaskDelegationActions(delegationID uint64) interface{} {
+ return tgkit.NewInlineKeyboard().
+ Row(tgkit.Btn("📅 Изменить срок", fmt.Sprintf("deleg_task_extend:%d", delegationID))).
+ Row(tgkit.BtnStyled(tgkit.ButtonStyleDanger, "Отозвать делегирование", fmt.Sprintf("deleg_task_revoke:%d", delegationID))).
+ Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "К списку", "deleg_task_list")).
+ Build()
+}
+
+// BuildTaskDelegationExtendCancel кнопка отмены при вводе новой даты
+func BuildTaskDelegationExtendCancel(delegationID uint64) interface{} {
+ return tgkit.NewInlineKeyboard().
+ Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "Отмена", fmt.Sprintf("deleg_task_detail:%d", delegationID))).
+ Build()
+}
+
+func BuildTaskDelegationCategoryMenu(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()
+ // Кнопка для делегирования ВСЕХ задач разом
+ kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "🌍 Все задачи (Глобально)", "deleg_task_all"))
+
+ for _, c := range categories[start:end] {
+ if c.ID == nil || c.Name == nil {
+ continue
+ }
+ kb.Row(tgkit.Btn(*c.Name, fmt.Sprintf("deleg_task_category:%d", *c.ID)))
+ }
+ if totalPages > 1 {
+ kb.Rows = append(kb.Rows, buildPageRow(page, totalPages, "deleg_task_cat_page", "deleg_page_noop"))
+ }
+ kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "В главное меню", "deleg_main_menu"))
+ return kb.Build()
+}
+
+func BuildTaskDelegationTopicMenu(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.ButtonStylePrimary, "📂 Вся категория", fmt.Sprintf("deleg_task_all_cat:%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_task_topic:%d", *t.ID)))
+ }
+ if totalPages > 1 {
+ kb.Rows = append(kb.Rows, buildPageRow(page, totalPages, fmt.Sprintf("deleg_task_top_page:%d", categoryID), "deleg_page_noop"))
+ }
+ kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "К категориям", "deleg_task_create"))
+ return kb.Build()
+}
diff --git a/service/telegram_service/keyboard/menu.go b/service/telegram_service/keyboard/menu.go
index df8dffd..b0f4a28 100644
--- a/service/telegram_service/keyboard/menu.go
+++ b/service/telegram_service/keyboard/menu.go
@@ -30,6 +30,10 @@ func BuildMainMenu(roles UserRole) tgbotapi.ReplyKeyboardMarkup {
kb.Row("👁 Наблюдатель")
}
+ if roles.IsDirector {
+ kb.Row("Директор")
+ }
+
// Раздел: Исполнитель
if roles.IsExecutor {
kb.Row("Задачи к исполнению")
@@ -69,3 +73,11 @@ func BuildObserverSubmenu() tgbotapi.ReplyKeyboardMarkup {
Row("← Назад").
Build()
}
+
+// BuildDirectorSubmenu — подменю для директора
+func BuildDirectorSubmenu() tgbotapi.ReplyKeyboardMarkup {
+ return tgkit.NewReplyKeyboard().
+ Row("🔔 Настроить уведомления").
+ Row("← Назад").
+ Build()
+}
diff --git a/service/telegram_service/keyboard/misc.go b/service/telegram_service/keyboard/misc.go
index 1508b00..601bf8c 100644
--- a/service/telegram_service/keyboard/misc.go
+++ b/service/telegram_service/keyboard/misc.go
@@ -8,7 +8,52 @@ import (
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)
-// ── Выбор согласующего ──────────────────────────────────────────
+// BuildDirectorNotificationCategoriesMenu — мультиселект категорий с галочками.
+// subscribedIDs — те category_id, на которые директор уже подписан.
+func BuildDirectorNotificationCategoriesMenu(categories []*typescore.ApprovalTopicCategory, subscribedIDs []uint64, page int) tgbotapi.InlineKeyboardMarkup {
+ const perPage = 8
+
+ subscribed := make(map[uint64]bool, len(subscribedIDs))
+ for _, id := range subscribedIDs {
+ subscribed[id] = true
+ }
+
+ total := len(categories)
+ 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 _, c := range categories[start:end] {
+ if c.ID == nil || c.Name == nil {
+ continue
+ }
+ label := *c.Name
+ if subscribed[*c.ID] {
+ label = "✅ " + label
+ } else {
+ label = "⬜ " + label
+ }
+ // page передаём в callback, чтобы после тоггла вернуться на ту же страницу
+ kb.Row(tgkit.Btn(label, fmt.Sprintf("dir_notif_toggle:%d:%d", *c.ID, page)))
+ }
+
+ if totalPages > 1 {
+ kb.Rows = append(kb.Rows, buildPageRow(page, totalPages, "dir_notif_page", "dir_notif_page_noop"))
+ }
+
+ kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "Готово", "dir_notif_done"))
+ return kb.Build()
+}
func BuildApproverSelectionMenu(approvers []*typescore.User, page int) interface{} {
const perPage = 8
@@ -136,6 +181,45 @@ func BuildObserverSelectionMenu(observers []*typescore.User, selectedIDs []uint6
return kb.Build()
}
+// BuildObserverTopicMenuFromDB — строит меню тем наблюдения из БД
+func BuildObserverTopicMenuFromDB(topics []*typescore.ApprovalTopic, 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] {
+ if t.ID == nil || t.Name == nil || t.Code == nil {
+ continue
+ }
+ 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 BuildObserverTopicMenu(topics []approvalflow.Topic, page int) tgbotapi.InlineKeyboardMarkup {
const perPage = 6
total := len(topics)
@@ -171,41 +255,23 @@ func BuildObserverTopicMenu(topics []approvalflow.Topic, page int) tgbotapi.Inli
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")).
+ Row(tgkit.Btn("Указать даты", "report_set_dates")).
Build()
}
-// ── Доработка ───────────────────────────────────────────────────
+func BuildRevisionOptions(approvalID uint64, commentsCount int) interface{} {
+ viewLabel := "💬 Посмотреть все комментарии"
+ if commentsCount > 0 {
+ viewLabel = fmt.Sprintf("💬 Посмотреть все комментарии (%d)", commentsCount)
+ }
-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.Btn(viewLabel, fmt.Sprintf("appr_view_comments:%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()
@@ -240,3 +306,84 @@ func BuildRevokeTaskConfirmation(taskID uint64, approvalID uint64) tgbotapi.Inli
),
)
}
+
+func buildCommentsButton(approvalID uint64, commentsCount int) tgkit.InlineButton {
+ label := "💬 Посмотреть все комментарии"
+ if commentsCount > 0 {
+ label = fmt.Sprintf("💬 Посмотреть все комментарии (%d)", commentsCount)
+ }
+ return tgkit.Btn(label, fmt.Sprintf("appr_view_comments:%d", approvalID))
+}
+
+// BuildTaskTransferUserMenu — список пользователей для передачи задачи
+func BuildTaskTransferUserMenu(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("task_transfer_user:%d", *u.ID)))
+ }
+ if totalPages > 1 {
+ kb.Rows = append(kb.Rows, buildPageRow(page, totalPages, "task_transfer_page", "task_transfer_noop"))
+ }
+ kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "Отмена", "task_transfer_cancel"))
+ return kb.Build()
+}
+
+// BuildTaskTransferConfirmation — кнопки Принять/Отклонить для получателя запроса
+func BuildTaskTransferConfirmation(transferID uint64) tgbotapi.InlineKeyboardMarkup {
+ return tgkit.NewInlineKeyboard().
+ Row(
+ tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "✅ Принять", fmt.Sprintf("task_transfer_accept:%d", transferID)),
+ tgkit.BtnStyled(tgkit.ButtonStyleDanger, "❌ Отклонить", fmt.Sprintf("task_transfer_decline:%d", transferID)),
+ ).
+ Build()
+}
+
+// BuildRevocationApprovalDecision — Да/Нет для согласующего, дающего согласие на отзыв
+func BuildRevocationApprovalDecision(approvalID uint64, requestID uint64, commentsCount int) tgbotapi.InlineKeyboardMarkup {
+ return tgkit.NewInlineKeyboard().
+ Row(
+ tgkit.BtnStyled(tgkit.ButtonStyleSuccess, " Да", fmt.Sprintf("revoke_appr_yes:%d", requestID)),
+ tgkit.BtnStyled(tgkit.ButtonStyleDanger, " Нет", fmt.Sprintf("revoke_appr_no:%d", requestID)),
+ ).
+ Row(
+ tgkit.Btn("💬 Добавить комментарий", fmt.Sprintf("appr_comment:%d", approvalID)),
+ buildCommentsButton(approvalID, commentsCount),
+ ).
+ Build()
+}
+
+func BuildDailyReminderKeyboard(hasRevisions, hasTasks, hasApprovals bool) tgbotapi.InlineKeyboardMarkup {
+ kb := tgkit.NewInlineKeyboard()
+
+ if hasRevisions {
+ kb.Row(tgkit.Btn("К доработкам", "reminder_revisions"))
+ }
+
+ if hasTasks {
+ kb.Row(tgkit.Btn("К задачам", "reminder_tasks"))
+ }
+
+ if hasApprovals {
+ kb.Row(tgkit.Btn("К заявкам", "reminder_approvals"))
+ }
+
+ return kb.Build()
+}
diff --git a/service/telegram_service/keyboard/observer.go b/service/telegram_service/keyboard/observer.go
index 7bb207b..144fb8b 100644
--- a/service/telegram_service/keyboard/observer.go
+++ b/service/telegram_service/keyboard/observer.go
@@ -1,22 +1,97 @@
package keyboard
import (
+ "bitrix_balancer_api/core/lib/external/tgkit"
+ "bitrix_balancer_api/core/typescore"
"fmt"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)
// BuildObserverApprovalDetail — карточка заявки с кнопками наблюдателя.
-func BuildObserverApprovalDetail(approvalID uint64, topicCode string) tgbotapi.InlineKeyboardMarkup {
+func BuildObserverApprovalDetail(approvalID uint64, topicCode string, commentsCount int) 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),
- ),
+ buildCommentsButtonData(approvalID, commentsCount),
+ ),
+ tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData("← К фильтрам", fmt.Sprintf("obs_topic:%s", topicCode)),
),
)
}
+
+func buildCommentsButtonData(approvalID uint64, commentsCount int) tgbotapi.InlineKeyboardButton {
+ label := "💬 Посмотреть все комментарии"
+ if commentsCount > 0 {
+ label = fmt.Sprintf("💬 Посмотреть все комментарии (%d)", commentsCount)
+ }
+ return tgbotapi.NewInlineKeyboardButtonData(label, fmt.Sprintf("appr_view_comments:%d", approvalID))
+}
+
+// BuildObserverStatusFilterMenu — выбор статуса заявок для просмотра в рамках темы/категории
+func BuildObserverStatusFilterMenu(topicCode string) tgbotapi.InlineKeyboardMarkup {
+ return tgkit.NewInlineKeyboard().
+ Row(tgkit.Btn("⏳ На согласовании", fmt.Sprintf("obs_status:pending:%s:0", topicCode))).
+ Row(tgkit.Btn("✅ Согласованные", fmt.Sprintf("obs_status:approved:%s:0", topicCode))).
+ Row(tgkit.Btn("📋 Все", fmt.Sprintf("obs_status:all:%s:0", topicCode))).
+ Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "Назад к темам", "obs_back_topics")).
+ Build()
+}
+
+// BuildObserverApprovalList — список заявок с пагинацией и учётом текущего фильтра.
+// Кнопка "К фильтрам" возвращает на экран выбора статуса, "К темам" — к списку тем.
+func BuildObserverApprovalList(
+ approvals []*typescore.Approval,
+ initiators map[uint64]*typescore.User,
+ departments map[uint64]*typescore.Department,
+ status, topicCode string,
+ page int,
+) tgbotapi.InlineKeyboardMarkup {
+ const perPage = 8
+
+ total := len(approvals)
+ 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 _, a := range approvals[start:end] {
+ 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)))
+ }
+
+ if totalPages > 1 {
+ prevCB := fmt.Sprintf("obs_status:%s:%s:%d", status, topicCode, page-1)
+ nextCB := fmt.Sprintf("obs_status:%s:%s:%d", status, topicCode, page+1)
+ kb.Rows = append(kb.Rows, tgkit.PaginationRow(page, totalPages, prevCB, nextCB, "obs_status_noop"))
+ }
+
+ kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "К фильтрам", fmt.Sprintf("obs_topic:%s", topicCode)))
+ kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "К темам", "obs_back_topics"))
+ return kb.Build()
+}
diff --git a/service/telegram_service/scheduler/daily_reminder.go b/service/telegram_service/scheduler/daily_reminder.go
new file mode 100644
index 0000000..aad50dd
--- /dev/null
+++ b/service/telegram_service/scheduler/daily_reminder.go
@@ -0,0 +1,580 @@
+package scheduler
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/core/utilscore"
+ "bitrix_balancer_api/telegram_service/keyboard"
+ "bitrix_balancer_api/telegram_service/types"
+ "context"
+ "encoding/json"
+ "fmt"
+ tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
+ "github.com/sirupsen/logrus"
+ "html"
+ "regexp"
+ "strconv"
+ "time"
+)
+
+const (
+ maxDBFetchLimit = uint64(10000)
+ telegramMaxMessageLen = 4000 // Запас от лимита 4096 символов Telegram
+)
+
+type DailyReminder struct {
+ ipc *types.InternalProviderControl
+}
+
+func NewDailyReminder(ipc *types.InternalProviderControl) *DailyReminder {
+ return &DailyReminder{ipc: ipc}
+}
+
+// Start запускает планировщик ежедневных напоминаний
+func (dr *DailyReminder) Start() {
+ logrus.Infof("DailyReminder: Start() вызван — планировщик запускается")
+
+ go dr.scheduleLoop()
+}
+
+// scheduleLoop бесконечный цикл, который ждет 9:00 МСК каждый день
+func (dr *DailyReminder) scheduleLoop() {
+ mskLocation, err := time.LoadLocation("Europe/Moscow")
+ if err != nil {
+ logrus.Errorf("DailyReminder: не удалось загрузить часовой пояс МСК: %v", err)
+ mskLocation = time.FixedZone("MSK", 3*3600) // Fallback: UTC+3
+ }
+
+ for {
+ now := time.Now().In(mskLocation)
+
+ // Вычисляем следующее 9:00 МСК
+ next := time.Date(now.Year(), now.Month(), now.Day(), 9, 0, 0, 0, mskLocation)
+
+ // Если сегодня уже прошло 9:00, планируем на завтра
+ if now.After(next) {
+ next = next.AddDate(0, 0, 1)
+ }
+
+ next = dr.skipWeekends(next)
+
+ duration := time.Until(next)
+ logrus.Infof("DailyReminder: следующее напоминание запланировано на %s (через %v)",
+ next.Format("02.01.2006 15:04 MSK"), duration.Round(time.Second))
+
+ // Ждем до следующего 9:00
+ time.Sleep(duration)
+
+ // Отправляем напоминания
+ dr.sendReminders()
+ }
+}
+
+// skipWeekends переносит дату на ближайший будний день,
+// если она выпадает на субботу или воскресенье
+func (dr *DailyReminder) skipWeekends(t time.Time) time.Time {
+ switch t.Weekday() {
+ case time.Saturday:
+ return t.AddDate(0, 0, 2)
+ case time.Sunday:
+ // Воскресенье → понедельник (+1 день)
+ return t.AddDate(0, 0, 1)
+ }
+ return t
+}
+
+// isUserActive проверяет, что пользователь не уволен и не заблокирован.
+// Учитывает NULL в БД: если поле nil (NULL) или false — пользователь считается активным.
+func isUserActive(u *typescore.User) bool {
+ if u == nil {
+ return false
+ }
+ if u.IsBlocked != nil && *u.IsBlocked {
+ return false
+ }
+ if u.IsFired != nil && *u.IsFired {
+ return false
+ }
+ return true
+}
+
+// sendReminders отправляет напоминания всем активным пользователям
+func (dr *DailyReminder) sendReminders() {
+ logrus.Infof("DailyReminder: sendReminders() запущен")
+
+ ctx := context.Background()
+ bot := dr.ipc.TGBotClient.Bot()
+
+ mskLocation, err := time.LoadLocation("Europe/Moscow")
+ if err != nil {
+ logrus.Errorf("DailyReminder: не удалось загрузить часовой пояс МСК: %v", err)
+ mskLocation = time.FixedZone("MSK", 3*3600)
+ }
+ logrus.Infof("DailyReminder: сегодняшняя дата (МСК) = %s", time.Now().In(mskLocation).Format("02.01.2006"))
+
+ // Запрашиваем всех пользователей без фильтра IsBlocked/IsFired в SQL,
+ // чтобы не потерять записи со значением NULL в БД.
+ allUsers, _, err := dr.ipc.Database.User.GetUsersListDB(ctx, typescore.ListDbOptions{
+ Limit: utilscore.PointerToUint64(maxDBFetchLimit),
+ })
+ if err != nil {
+ logrus.Errorf("DailyReminder: GetUsersListDB err=%v", err)
+ return
+ }
+
+ // Фильтруем уволенных и заблокированных на уровне Go (корректно обрабатывая NULL как false)
+ var users []*typescore.User
+ skippedBlockedOrFired := 0
+ skippedNoTgID := 0
+
+ for _, u := range allUsers {
+ if !isUserActive(u) {
+ skippedBlockedOrFired++
+ continue
+ }
+ if u.ID == nil || u.TelegramID == nil || *u.TelegramID == 0 {
+ skippedNoTgID++
+ logrus.Warnf("DailyReminder: пропуск активного пользователя без TelegramID/ID (ID=%v, FullName=%v)",
+ u.ID, derefString(u.FullName))
+ continue
+ }
+ users = append(users, u)
+ }
+
+ logrus.Infof("DailyReminder: всего в БД=%d, активных к отправке=%d (пропущено уволенных/заблокированных=%d, без TelegramID=%d)",
+ len(allUsers), len(users), skippedBlockedOrFired, skippedNoTgID)
+
+ absentToday := dr.getAbsentEmployeesToday(ctx, mskLocation)
+
+ logrus.Infof("DailyReminder: начинаем отправку напоминаний для %d пользователей (отсутствующих сегодня: %d)",
+ len(users), len(absentToday))
+
+ sentCount := 0
+ for _, user := range users {
+ sent := dr.sendReminderToUser(bot, ctx, user, absentToday)
+ if sent {
+ sentCount++
+ }
+
+ time.Sleep(100 * time.Millisecond)
+ }
+
+ logrus.Infof("DailyReminder: отправлено напоминаний: %d из %d", sentCount, len(users))
+}
+
+// sendReminderToUser отправляет напоминание конкретному пользователю
+// Возвращает true, если сообщение было отправлено
+func (dr *DailyReminder) sendReminderToUser(bot *tgbotapi.BotAPI, ctx context.Context, user *typescore.User, absentToday []AbsentEmployeeInfo) bool {
+ userID := *user.ID
+ telegramID := *user.TelegramID
+
+ revisions, _, err := dr.ipc.Database.Approval.GetApprovalsListDB(ctx, typescore.ListDbOptions{
+ Limit: utilscore.PointerToUint64(maxDBFetchLimit),
+ Filtering: &typescore.Approval{
+ InitiatorID: &userID,
+ Status: utilscore.PointerToString("revision"),
+ },
+ })
+ if err != nil {
+ logrus.Errorf("DailyReminder: GetApprovalsListDB (revisions) for user=%d err=%v", userID, err)
+ }
+ revisionsCount := len(revisions)
+
+ myPendingApprovals, _, err := dr.ipc.Database.Approval.GetApprovalsListDB(ctx, typescore.ListDbOptions{
+ Limit: utilscore.PointerToUint64(maxDBFetchLimit),
+ Filtering: &typescore.Approval{
+ InitiatorID: &userID,
+ Status: utilscore.PointerToString("pending"),
+ },
+ })
+ if err != nil {
+ logrus.Errorf("DailyReminder: GetApprovalsListDB (my pending) for user=%d err=%v", userID, err)
+ }
+ myPendingCount := len(myPendingApprovals)
+
+ tasks, _, err := dr.ipc.Database.ApprovalTasks.GetApprovalTasksListDB(ctx, typescore.ListDbOptions{
+ Limit: utilscore.PointerToUint64(maxDBFetchLimit),
+ Filtering: &typescore.ApprovalTask{
+ ExecutorID: &userID,
+ Status: utilscore.PointerToString("pending"),
+ },
+ })
+ if err != nil {
+ logrus.Errorf("DailyReminder: GetApprovalTasksListDB for user=%d err=%v", userID, err)
+ }
+ tasksCount := len(tasks)
+
+ steps, _, err := dr.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{
+ Limit: utilscore.PointerToUint64(maxDBFetchLimit),
+ Filtering: &typescore.ApprovalStep{
+ ApproverID: &userID,
+ Status: utilscore.PointerToString("pending"),
+ },
+ })
+ if err != nil {
+ logrus.Errorf("DailyReminder: GetApprovalStepsListDB for user=%d err=%v", userID, err)
+ }
+
+ // Также проверяем дополнительные согласования
+ additionalApprovers, _, err := dr.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{
+ Limit: utilscore.PointerToUint64(maxDBFetchLimit),
+ Filtering: &typescore.ApprovalAdditionalApprover{
+ ApproverID: &userID,
+ Status: utilscore.PointerToString("pending"),
+ },
+ })
+ if err != nil {
+ logrus.Errorf("DailyReminder: GetApprovalAdditionalApproversListDB for user=%d err=%v", userID, err)
+ }
+
+ approvalsCount := dr.countPendingApprovals(ctx, steps, additionalApprovers)
+
+ hasPersonalItems := revisionsCount > 0 || tasksCount > 0 || approvalsCount > 0 || myPendingCount > 0
+
+ logrus.Infof("DailyReminder: userID=%d telegramID=%d — myPending=%d revisions=%d tasks=%d approvals=%d hasPersonalItems=%v absentTodayCount=%d",
+ userID, telegramID, myPendingCount, revisionsCount, tasksCount, approvalsCount, hasPersonalItems, len(absentToday))
+
+ text := "☀️ Доброе утро! Ежедневная сводка\n\n"
+
+ if hasPersonalItems {
+ if myPendingCount > 0 {
+ text += fmt.Sprintf("Ваших заявок на согласовании: %d\n", myPendingCount)
+ }
+ if revisionsCount > 0 {
+ text += fmt.Sprintf("Заявок на доработке: %d\n", revisionsCount)
+ }
+ if tasksCount > 0 {
+ text += fmt.Sprintf("Задач к исполнению: %d\n", tasksCount)
+ }
+ if approvalsCount > 0 {
+ text += fmt.Sprintf("Согласований к принятию: %d\n", approvalsCount)
+ }
+ text += "\nНажмите на кнопку для перехода к нужному разделу"
+ } else {
+ text += "✅ У вас нет активных заявок или задач, для которых требуются активные действия."
+ }
+
+ if len(absentToday) > 0 {
+ text += "\n\n👥 Сотрудники в отгуле/больничном/отпуске:\n"
+ for _, a := range absentToday {
+ line := fmt.Sprintf("• %s — %s, по срочным вопросам обращаться: %s\n",
+ html.EscapeString(a.Name),
+ html.EscapeString(a.TimeDescription),
+ html.EscapeString(a.Contact),
+ )
+ text += line
+ }
+ }
+
+ msg := tgbotapi.NewMessage(telegramID, text)
+ msg.ParseMode = "HTML"
+ if hasPersonalItems {
+ msg.ReplyMarkup = keyboard.BuildDailyReminderKeyboard(
+ revisionsCount > 0,
+ tasksCount > 0,
+ approvalsCount > 0,
+ )
+ }
+
+ if _, err := bot.Send(msg); err != nil {
+ logrus.Errorf("DailyReminder: не удалось отправить сообщение пользователю userID=%d (telegramID=%d): %v", userID, telegramID, err)
+ return false
+ }
+
+ logrus.Infof("DailyReminder: сообщение успешно отправлено userID=%d telegramID=%d (длина=%d байт)", userID, telegramID, len(text))
+
+ return true
+}
+
+// countPendingApprovals считает количество заявок со статусом "pending"
+// из списка шагов и дополнительных согласующих
+func (dr *DailyReminder) countPendingApprovals(
+ ctx context.Context,
+ steps []*typescore.ApprovalStep,
+ additionalApprovers []*typescore.ApprovalAdditionalApprover,
+) int {
+ approvalIDs := make(map[uint64]bool)
+
+ for _, step := range steps {
+ if step.ApprovalID != nil {
+ approvalIDs[*step.ApprovalID] = true
+ }
+ }
+ for _, aa := range additionalApprovers {
+ if aa.ApprovalID != nil {
+ approvalIDs[*aa.ApprovalID] = true
+ }
+ }
+
+ if len(approvalIDs) == 0 {
+ return 0
+ }
+
+ count := 0
+ for approvalID := range approvalIDs {
+ id := approvalID
+ approval, err := dr.ipc.Database.Approval.GetApprovalByIDDB(ctx, id)
+ if err != nil || approval == nil {
+ continue
+ }
+ if approval.Status != nil && *approval.Status == "pending" {
+ count++
+ }
+ }
+
+ return count
+}
+
+type absenceMetadata struct {
+ Extra struct {
+ TimeType string `json:"time_type"`
+ AbsenceType string `json:"absence_type"`
+ } `json:"extra"`
+}
+
+type AbsentEmployeeInfo struct {
+ Name string
+ TimeDescription string
+ Contact string
+}
+
+var absenceDateRe = regexp.MustCompile(`(\d{1,2})[.,](\d{1,2})\.(\d{4})`)
+
+var absenceTimeRe = regexp.MustCompile(`(?:с|от)\s*(\d{1,2})[:\.](\d{2})\s*(?:до|по|-|—|–)\s*(\d{1,2})[:\.](\d{2})`)
+
+func (dr *DailyReminder) getAbsentEmployeesToday(ctx context.Context, mskLocation *time.Location) []AbsentEmployeeInfo {
+ today := time.Now().In(mskLocation)
+ todayY, todayM, todayD := today.Date()
+
+ activeCategories, _, errCat := dr.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryListDB(ctx, typescore.ListDbOptions{
+ Limit: utilscore.PointerToUint64(maxDBFetchLimit),
+ Filtering: &typescore.ApprovalTopicCategory{IsActive: utilscore.PointerToBool(true)},
+ })
+ if errCat != nil {
+ logrus.Errorf("DailyReminder: getAbsentEmployeesToday: не удалось получить список категорий: %v", errCat)
+ }
+
+ approvals, _, err := dr.ipc.Database.Approval.GetApprovalsListDB(ctx, typescore.ListDbOptions{
+ Limit: utilscore.PointerToUint64(maxDBFetchLimit),
+ Filtering: &typescore.Approval{
+ Status: utilscore.PointerToString("approved"),
+ },
+ })
+ if err != nil {
+ logrus.Errorf("DailyReminder: getAbsentEmployeesToday: GetApprovalsListDB err=%v", err)
+ return nil
+ }
+ logrus.Infof("DailyReminder: getAbsentEmployeesToday: заявок со статусом approved найдено: %d (сегодня %04d-%02d-%02d)",
+ len(approvals), todayY, todayM, todayD)
+
+ seenUsers := make(map[uint64]bool)
+ var result []AbsentEmployeeInfo
+
+ for _, approval := range approvals {
+ approvalID := derefApprovalID(approval)
+
+ if approval.Metadata == nil || *approval.Metadata == "" || approval.Content == nil {
+ continue
+ }
+
+ var meta absenceMetadata
+ if err := json.Unmarshal([]byte(*approval.Metadata), &meta); err != nil {
+ logrus.Warnf("DailyReminder: заявка #%d — не удалось распарсить Metadata как JSON: %v (metadata=%q)",
+ approvalID, err, *approval.Metadata)
+ continue
+ }
+ if meta.Extra.AbsenceType == "" {
+ continue
+ }
+
+ if approval.InitiatorID == nil {
+ logrus.Warnf("DailyReminder: заявка #%d пропущена — InitiatorID nil", approvalID)
+ continue
+ }
+ if seenUsers[*approval.InitiatorID] {
+ continue
+ }
+
+ dates := parseAbsenceDates(*approval.Content)
+ if len(dates) == 0 {
+ logrus.Warnf("DailyReminder: заявка #%d — не удалось разобрать даты в content: %q",
+ approvalID, *approval.Content)
+ continue
+ }
+
+ if !absenceCoversDate(dates, todayY, todayM, todayD) {
+ continue
+ }
+
+ // Проверяем, что сам инициатор заявки не уволен и не заблокирован
+ initiatorUser, uErr := dr.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID)
+ if uErr == nil && initiatorUser != nil && !isUserActive(initiatorUser) {
+ logrus.Infof("DailyReminder: заявка #%d пропущена — инициатор (userID=%d) уволен или заблокирован", approvalID, *approval.InitiatorID)
+ continue
+ }
+
+ name := "—"
+ if approval.Initiator != nil && approval.Initiator.FullName != nil {
+ name = *approval.Initiator.FullName
+ } else if initiatorUser != nil && initiatorUser.FullName != nil {
+ name = *initiatorUser.FullName
+ }
+
+ var timeDescription string
+ switch meta.Extra.AbsenceType {
+ case "timeoff":
+ if meta.Extra.TimeType == "partial" {
+ if m := absenceTimeRe.FindStringSubmatch(*approval.Content); m != nil {
+ timeDescription = fmt.Sprintf("отгул с %s:%s до %s:%s", m[1], m[2], m[3], m[4])
+ } else {
+ timeDescription = "отгул весь день"
+ }
+ } else {
+ timeDescription = "отгул весь день"
+ }
+ case "vacation":
+ timeDescription = fmt.Sprintf("отпуск до %s", maxDate(dates).Format("02.01.2006"))
+ case "sickleave":
+ timeDescription = fmt.Sprintf("больничный до %s", maxDate(dates).Format("02.01.2006"))
+ default:
+ timeDescription = "отсутствует"
+ }
+
+ contact := name
+
+ if len(activeCategories) > 0 {
+ if delegations, _, dErr := dr.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{
+ Limit: utilscore.PointerToUint64(maxDBFetchLimit),
+ Filtering: &typescore.ApprovalDelegation{
+ DelegatorID: approval.InitiatorID,
+ IsActive: utilscore.PointerToBool(true),
+ },
+ }); dErr == nil {
+ now := time.Now()
+
+ activeDelegationsMap := make(map[uint64]uint64)
+ for _, d := range delegations {
+ if d.DelegateID == nil || d.CategoryID == nil {
+ continue
+ }
+ if d.ValidUntil != nil && d.ValidUntil.Before(now) {
+ continue // срок вышел
+ }
+ activeDelegationsMap[*d.CategoryID] = *d.DelegateID
+ }
+
+ var primaryDelegateID uint64
+ allDelegatedToSamePerson := true
+ isFirstCategory := true
+
+ for _, cat := range activeCategories {
+ if cat.ID == nil {
+ continue
+ }
+
+ delegateID, hasDelegation := activeDelegationsMap[*cat.ID]
+ if !hasDelegation {
+ allDelegatedToSamePerson = false
+ break
+ }
+
+ if isFirstCategory {
+ primaryDelegateID = delegateID
+ isFirstCategory = false
+ } else if primaryDelegateID != delegateID {
+ allDelegatedToSamePerson = false
+ break
+ }
+ }
+
+ if allDelegatedToSamePerson && primaryDelegateID != 0 {
+ delegateUser, dUserErr := dr.ipc.Database.User.GetUserByIDDB(ctx, primaryDelegateID)
+ if dUserErr == nil && delegateUser != nil && delegateUser.FullName != nil {
+ contact = *delegateUser.FullName
+ }
+ }
+ }
+ }
+
+ seenUsers[*approval.InitiatorID] = true
+ result = append(result, AbsentEmployeeInfo{
+ Name: name,
+ TimeDescription: timeDescription,
+ Contact: contact,
+ })
+ }
+
+ logrus.Infof("DailyReminder: getAbsentEmployeesToday: итоговый список отсутствующих сегодня (%d): %+v", len(result), result)
+
+ return result
+}
+
+func derefApprovalID(a *typescore.Approval) uint64 {
+ if a == nil || a.ID == nil {
+ return 0
+ }
+ return *a.ID
+}
+
+func derefString(s *string) string {
+ if s == nil {
+ return ""
+ }
+ return *s
+}
+
+func parseAbsenceDates(content string) []time.Time {
+ matches := absenceDateRe.FindAllStringSubmatch(content, -1)
+ var dates []time.Time
+ for _, m := range matches {
+ day, errD := strconv.Atoi(m[1])
+ month, errM := strconv.Atoi(m[2])
+ year, errY := strconv.Atoi(m[3])
+ if errD != nil || errM != nil || errY != nil {
+ continue
+ }
+ if month < 1 || month > 12 || day < 1 || day > 31 {
+ continue
+ }
+ dates = append(dates, time.Date(year, time.Month(month), day, 0, 0, 0, 0, time.UTC))
+ }
+ return dates
+}
+
+func minDate(dates []time.Time) time.Time {
+ min := dates[0]
+ for _, d := range dates[1:] {
+ if d.Before(min) {
+ min = d
+ }
+ }
+ return min
+}
+
+func maxDate(dates []time.Time) time.Time {
+ max := dates[0]
+ for _, d := range dates[1:] {
+ if d.After(max) {
+ max = d
+ }
+ }
+ return max
+}
+
+// absenceCoversDate проверяет, попадает ли сегодняшняя дата в период отсутствия.
+// Если в тексте найдено 2 или более дат (начало и конец отпуска/больничного/отгула),
+// проверяется вхождение даты в диапазон [minDate, maxDate] вне зависимости от типа тире или предлогов.
+func absenceCoversDate(dates []time.Time, y int, m time.Month, d int) bool {
+ if len(dates) == 0 {
+ return false
+ }
+
+ target := time.Date(y, m, d, 0, 0, 0, 0, time.UTC)
+
+ if len(dates) >= 2 {
+ start := minDate(dates)
+ end := maxDate(dates)
+ return !target.Before(start) && !target.After(end)
+ }
+
+ return dates[0].Equal(target)
+}
diff --git a/service/telegram_service/scheduler/monthly_order_checker.go b/service/telegram_service/scheduler/monthly_order_checker.go
new file mode 100644
index 0000000..2178bff
--- /dev/null
+++ b/service/telegram_service/scheduler/monthly_order_checker.go
@@ -0,0 +1,63 @@
+package scheduler
+
+import (
+ "bitrix_balancer_api/core/lib/internally/monthly_orders"
+ "bitrix_balancer_api/telegram_service/types"
+ "context"
+ "github.com/sirupsen/logrus"
+ "time"
+)
+
+type MonthlyOrderChecker struct {
+ ipc *types.InternalProviderControl
+ service *monthly_orders.MonthlyOrderService
+}
+
+func NewMonthlyOrderChecker(ipc *types.InternalProviderControl, service *monthly_orders.MonthlyOrderService) *MonthlyOrderChecker {
+ return &MonthlyOrderChecker{ipc: ipc, service: service}
+}
+
+func (c *MonthlyOrderChecker) Start() {
+ go c.loop()
+}
+
+func (c *MonthlyOrderChecker) loop() {
+ logrus.Info("🚀 [MonthlyOrderChecker] Воркер автоотправки заказов запущен. Интервал проверки: 15 минут")
+
+ // Используем Ticker вместо time.Sleep
+ ticker := time.NewTicker(15 * time.Minute)
+ defer ticker.Stop()
+
+ // Бесконечный цикл, который блокируется до следующего тика
+ for range ticker.C {
+ now := time.Now()
+ month, year := int(now.Month()), now.Year()
+ ctx := context.Background()
+
+ logrus.Debugf("🔍 [MonthlyOrderChecker] Проверка дедлайна за %02d.%d...", month, year)
+
+ settings, err := c.ipc.Database.MonthlyOrders.GetCurrentSettings(ctx, month, year)
+ if err != nil || settings == nil || settings.DeadlineDate == nil {
+ logrus.Debugf("⚠️ [MonthlyOrderChecker] Настройки дедлайна на %02d.%d не заданы. Пропуск.", month, year)
+ // Теперь continue безопасно вернет нас к ожиданию следующего тика таймера
+ continue
+ }
+
+ if now.After(*settings.DeadlineDate) {
+ logrus.Infof("⏰ [MonthlyOrderChecker] ДЕДЛАЙН НАСТУПИЛ (%s). Запуск автоотправки...", settings.DeadlineDate.Format("02.01.2006 15:04"))
+
+ managers, _ := c.ipc.Database.MonthlyOrders.GetManagersWithDraftsDB(ctx, month, year)
+ logrus.Infof("👥 [MonthlyOrderChecker] Найдено менеджеров с черновиками: %d", len(managers))
+
+ for _, managerID := range managers {
+ logrus.Infof("🔄 [MonthlyOrderChecker] Обработка менеджера ID: %d", managerID)
+
+ if err := c.service.SubmitOrdersToTelegram(ctx, managerID); err != nil {
+ logrus.Errorf("❌ [MonthlyOrderChecker] Ошибка отправки для менеджера %d: %v", managerID, err)
+ }
+ }
+ } else {
+ logrus.Debugf("⏳ [MonthlyOrderChecker] Дедлайн (%s) еще не наступил. Спим дальше.", settings.DeadlineDate.Format("02.01.2006 15:04"))
+ }
+ }
+}
diff --git a/service/telegram_service/state/comment.go b/service/telegram_service/state/comment.go
index 393f06d..c138017 100644
--- a/service/telegram_service/state/comment.go
+++ b/service/telegram_service/state/comment.go
@@ -11,8 +11,10 @@ import (
)
type CommentFlowState struct {
- ApprovalID uint64 `json:"approval_id"`
- Stage string `json:"stage"` // "await_text"
+ ApprovalID uint64 `json:"approval_id"`
+ Stage string `json:"stage"` // "await_text", "await_visibility", "await_targets"
+ Text string `json:"text"`
+ Targets map[uint64]bool `json:"targets"`
}
type CommentReplyState struct {
diff --git a/service/telegram_service/state/state.go b/service/telegram_service/state/state.go
index dc336bd..f347014 100644
--- a/service/telegram_service/state/state.go
+++ b/service/telegram_service/state/state.go
@@ -20,19 +20,23 @@ type FileAttachment struct {
// 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"`
+ 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"`
+ AwaitTaskDelegationChoice bool `json:"await_task_delegation_choice,omitempty"`
+ AwaitTaskDelegateSelection bool `json:"await_task_delegate_selection,omitempty"`
+ TaskDelegationSelectionDone bool `json:"task_delegation_selection_done,omitempty"`
+ SelectedTaskDelegateID uint64 `json:"selected_task_delegate_id,omitempty"`
// Выбор первого согласующего по роли
AwaitFirstApproverSelection bool `json:"await_first_approver_selection"`
@@ -46,6 +50,14 @@ type ApprovalFlowState struct {
AwaitObserverSelection bool `json:"await_observer_selection"`
ObserverSelectionDone bool `json:"observer_selection_done"`
SelectedObserverIDs []uint64 `json:"selected_observer_ids,omitempty"`
+
+ // 🆕 Делегирование обязанностей на время отсутствия (отгул/отпуск/
+ // больничный) — см. handlers/approval/delegation.go. Тот же паттерн,
+ // что у наблюдателей: Await*/ *Done флаги + выбранное значение.
+ AwaitDelegationChoice bool `json:"await_delegation_choice,omitempty"`
+ AwaitDelegateSelection bool `json:"await_delegate_selection,omitempty"`
+ DelegationSelectionDone bool `json:"delegation_selection_done,omitempty"`
+ SelectedDelegateID uint64 `json:"selected_delegate_id,omitempty"`
}
type StateManager struct {