Compare commits
2 Commits
main
...
test-deplo
| Author | SHA1 | Date |
|---|---|---|
|
|
bd471f8628 | |
|
|
e3fffbeddc |
|
|
@ -6,13 +6,13 @@ on:
|
|||
|
||||
env:
|
||||
REPO_DIR: "/workspace/ruspet_portal_back"
|
||||
REPO_URL: "https://${{ github.actor }}:${{ github.token }}@72.56.235.246.nip.io/gitea/romanskijdev/ruspet_portal_back.git"
|
||||
REPO_URL: "https://72.56.235.246.nip.io/gitea/romanskijdev/ruspet_portal_back.git"
|
||||
BACKUP_DIR: "/tmp/deploy_backups"
|
||||
|
||||
TELEGRAM_SERVICE: "telegram_service"
|
||||
BALANCER_SERVICE: "rest_balancer_service"
|
||||
ADMIN_SERVICE: "rest_admin_service"
|
||||
MIGRATIONS_SERVICE: "system_service"
|
||||
TELEPHONY_SERVICE: "rest_telephony_service"
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
|
|
@ -20,6 +20,9 @@ jobs:
|
|||
timeout-minutes: 30
|
||||
|
||||
steps:
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
# ШАГ 1: Информация о деплое
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
- name: 📋 Deployment Info
|
||||
run: |
|
||||
echo "════════════════════════════════════════"
|
||||
|
|
@ -34,24 +37,23 @@ 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"
|
||||
|
||||
|
|
@ -63,8 +65,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/^/ /'
|
||||
|
|
@ -74,8 +76,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"
|
||||
|
|
@ -85,14 +87,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
|
||||
|
||||
|
|
@ -104,34 +106,43 @@ 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_ADMIN" = "false" ] && [ "$DEPLOY_TELEPHONY" = "false" ]; then
|
||||
if [ "$DEPLOY_MIGRATIONS" = "false" ] && \
|
||||
[ "$DEPLOY_TELEGRAM" = "false" ] && \
|
||||
[ "$DEPLOY_BALANCER" = "false" ] && \
|
||||
[ "$DEPLOY_ADMIN" = "false" ]; then
|
||||
echo "⏭️ No services need to be deployed — skipping"
|
||||
echo "SKIP_DEPLOY=true" >> $GITHUB_ENV
|
||||
else
|
||||
echo "SKIP_DEPLOY=false" >> $GITHUB_ENV
|
||||
fi
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
# ШАГ 4: Inject config
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
- name: 🔐 Inject Config
|
||||
if: env.SKIP_DEPLOY == 'false'
|
||||
run: |
|
||||
|
|
@ -143,6 +154,9 @@ 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: |
|
||||
|
|
@ -164,88 +178,121 @@ jobs:
|
|||
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_TELEGRAM" = "true" ]; then
|
||||
create_backup "$TELEGRAM_SERVICE"
|
||||
fi
|
||||
|
||||
if [ "$DEPLOY_BALANCER" = "true" ]; then
|
||||
create_backup "$BALANCER_SERVICE"
|
||||
fi
|
||||
|
||||
if [ "$DEPLOY_ADMIN" = "true" ]; then
|
||||
create_backup "$ADMIN_SERVICE"
|
||||
fi
|
||||
|
||||
# Очистка старых backup-ов (оставляем последние 10)
|
||||
echo "🧹 Cleaning old backups..."
|
||||
ls -t "$BACKUP_DIR"/* 2>/dev/null | tail -n +11 | xargs -r rm -- || true
|
||||
echo "✅ Backups ready"
|
||||
|
||||
- name: 🗄️ Deploy System Service (Migrations & Background Tasks)
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
# ШАГ 6: Миграции БД
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
- name: 🗄️ Run Database Migrations
|
||||
if: env.DEPLOY_MIGRATIONS == 'true' && env.SKIP_DEPLOY == 'false'
|
||||
id: deploy_migrations
|
||||
run: |
|
||||
echo "🗄️ Deploying system service..."
|
||||
echo "🗄️ Running database migrations..."
|
||||
if sudo /usr/bin/bash "$REPO_DIR/deploy.sh" migrations; then
|
||||
echo "✅ System service deployed"
|
||||
echo "✅ Migrations completed successfully"
|
||||
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 "❌ System deployment failed"
|
||||
echo "❌ Migrations 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
|
||||
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
|
||||
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
|
||||
exit 1
|
||||
fi
|
||||
else
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- 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"
|
||||
if sudo /usr/bin/systemctl is-active --quiet "$ADMIN_SERVICE"; then
|
||||
echo "✅ Admin service is running"
|
||||
else
|
||||
echo "❌ Telephony service failed to start"
|
||||
sudo /usr/bin/journalctl -u "$TELEPHONY_SERVICE" -n 30 --no-pager
|
||||
echo "❌ Admin service failed to start"
|
||||
sudo /usr/bin/journalctl -u "$ADMIN_SERVICE" -n 30 --no-pager
|
||||
exit 1
|
||||
fi
|
||||
if [ -f "$REPO_DIR/service/rest_admin_service/docs/swagger.json" ]; then
|
||||
echo "✅ Swagger documentation generated"
|
||||
fi
|
||||
else
|
||||
echo "❌ Telephony deployment failed"
|
||||
echo "TELEPHONY_DEPLOYED=false" >> $GITHUB_ENV
|
||||
echo "❌ Admin deployment failed"
|
||||
echo "ADMIN_DEPLOYED=false" >> $GITHUB_ENV
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
# ШАГ 10: Rollback при ошибке
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
- name: ⏮️ Rollback on Failure
|
||||
if: failure()
|
||||
run: |
|
||||
|
|
@ -264,87 +311,149 @@ 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_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
|
||||
if [ "$DEPLOY_TELEGRAM" = "true" ]; then
|
||||
rollback_service "$TELEGRAM_SERVICE"
|
||||
fi
|
||||
|
||||
if [ "$DEPLOY_BALANCER" = "true" ]; then
|
||||
rollback_service "$BALANCER_SERVICE"
|
||||
fi
|
||||
|
||||
if [ "$DEPLOY_ADMIN" = "true" ]; then
|
||||
rollback_service "$ADMIN_SERVICE"
|
||||
fi
|
||||
|
||||
echo "✅ 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
|
||||
echo "✅ $service: running"
|
||||
UPTIME=$(systemctl show "$service" --property=ActiveEnterTimestamp --value)
|
||||
echo "✅ $service: running (since $UPTIME)"
|
||||
else
|
||||
echo "❌ $service: NOT RUNNING"
|
||||
ALL_OK=false
|
||||
fi
|
||||
else
|
||||
echo "⏭️ $service: skipped"
|
||||
fi
|
||||
}
|
||||
|
||||
verify_service "$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 exit 1; fi
|
||||
if [ "$ALL_OK" = "true" ]; then
|
||||
echo "✅ All services verified successfully"
|
||||
else
|
||||
echo "❌ Some services are not running"
|
||||
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="✅ <b>Deployment successful</b>%0A%0A"
|
||||
MESSAGE+="🌿 Branch: <code>${{ github.ref_name }}</code>%0A"
|
||||
MESSAGE+="📝 Commit: <code>${{ github.sha }}</code>%0A"
|
||||
MESSAGE+="👤 Author: ${{ github.actor }}%0A%0A"
|
||||
|
||||
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
|
||||
if [ "$DEPLOY_MIGRATIONS" = "true" ]; then
|
||||
MESSAGE+="🗄️ Migrations: applied%0A"
|
||||
fi
|
||||
if [ "$DEPLOY_TELEGRAM" = "true" ]; then
|
||||
MESSAGE+="🤖 Telegram: deployed%0A"
|
||||
fi
|
||||
if [ "$DEPLOY_BALANCER" = "true" ]; then
|
||||
MESSAGE+="⚖️ Balancer: deployed%0A"
|
||||
fi
|
||||
if [ "$DEPLOY_ADMIN" = "true" ]; then
|
||||
MESSAGE+="🔧 Admin: deployed%0A"
|
||||
fi
|
||||
|
||||
MESSAGE+="%0A⏰ $(date '+%Y-%m-%d %H:%M:%S')"
|
||||
|
||||
curl -s -X POST "https://api.telegram.org/bot${{ secrets.TELEGRAM_BOT_TOKEN }}/sendMessage" \
|
||||
-d "chat_id=${{ secrets.TELEGRAM_CHAT_ID }}" -d "parse_mode=HTML" -d "text=$MESSAGE"
|
||||
-d "chat_id=${{ secrets.TELEGRAM_CHAT_ID }}" \
|
||||
-d "parse_mode=HTML" \
|
||||
-d "text=$MESSAGE" || echo "⚠️ Telegram notification failed"
|
||||
fi
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
# ШАГ 13: Уведомление об ошибке
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
- name: 🚨 Notify Failure
|
||||
if: failure()
|
||||
run: |
|
||||
for service in "$MIGRATIONS_SERVICE" "$TELEGRAM_SERVICE" "$ADMIN_SERVICE" "$TELEPHONY_SERVICE"; do
|
||||
echo "📜 $service logs:"
|
||||
echo "❌ Deployment failed!"
|
||||
|
||||
for service in "$TELEGRAM_SERVICE" "$BALANCER_SERVICE" "$ADMIN_SERVICE"; do
|
||||
echo ""
|
||||
echo "📜 $service logs (last 20 lines):"
|
||||
sudo journalctl -u "$service" -n 20 --no-pager || true
|
||||
done
|
||||
|
||||
if [ -n "${{ secrets.TELEGRAM_BOT_TOKEN }}" ] && [ -n "${{ secrets.TELEGRAM_CHAT_ID }}" ]; then
|
||||
MESSAGE="❌ <b>Deployment failed</b>%0A%0A"
|
||||
MESSAGE+="🌿 Branch: <code>${{ github.ref_name }}</code>%0A"
|
||||
MESSAGE+="📝 Commit: <code>${{ github.sha }}</code>%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"
|
||||
-d "chat_id=${{ secrets.TELEGRAM_CHAT_ID }}" \
|
||||
-d "parse_mode=HTML" \
|
||||
-d "text=$MESSAGE" || echo "⚠️ Telegram notification failed"
|
||||
fi
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
# ШАГ 14: Итоговая сводка
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
- name: 📊 Deployment Summary
|
||||
if: always()
|
||||
run: |
|
||||
echo "════════════════════════════════════════"
|
||||
echo "📊 DEPLOYMENT SUMMARY"
|
||||
echo "════════════════════════════════════════"
|
||||
echo "System (Migrations): ${DEPLOY_MIGRATIONS:-false}"
|
||||
echo "Telegram bot: ${DEPLOY_TELEGRAM:-false}"
|
||||
echo "Admin: ${DEPLOY_ADMIN:-false}"
|
||||
echo "Telephony: ${DEPLOY_TELEPHONY:-false}"
|
||||
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 "════════════════════════════════════════"
|
||||
31
code2text.py
31
code2text.py
|
|
@ -1,31 +0,0 @@
|
|||
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")
|
||||
|
|
@ -1,5 +1,7 @@
|
|||
package configcore
|
||||
|
||||
import "net/url"
|
||||
|
||||
// RedisConfig конфигурация Redis
|
||||
type RedisConfig struct {
|
||||
Host string `yaml:"host" env-required:"true"`
|
||||
|
|
@ -20,8 +22,12 @@ type DatabaseConfig struct {
|
|||
|
||||
// TelegramConfig конфигурация Telegram
|
||||
type TelegramConfig struct {
|
||||
BotToken string `yaml:"bot_token"`
|
||||
WebAppUrl string `yaml:"web_app_url"`
|
||||
BotToken string `yaml:"bot_token"`
|
||||
WebAppUrl string `yaml:"web_app_url"`
|
||||
ProxyURL string `yaml:"proxy_url"`
|
||||
ProxyUsername string `yaml:"proxy_username"`
|
||||
ProxyPassword string `yaml:"proxy_password"`
|
||||
ParsedProxy *url.URL // кэшированный распарсенный прокси
|
||||
}
|
||||
|
||||
// ServiceConfig конфигурация сервиса
|
||||
|
|
|
|||
|
|
@ -34,15 +34,7 @@ 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(
|
||||
|
|
@ -93,15 +85,7 @@ 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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
package dbmigration
|
||||
|
||||
import (
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
_ "embed"
|
||||
"encoding/csv"
|
||||
"encoding/json"
|
||||
|
|
@ -19,6 +20,12 @@ 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_]`)
|
||||
|
||||
|
|
@ -40,7 +47,10 @@ 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
|
||||
var defaultDataEntries = []dataEntry{
|
||||
{"approval_topic_categories", &typescore.ApprovalTopicCategory{}, approvalCategoriesCSV},
|
||||
{"approval_topics", &typescore.ApprovalTopic{}, approvalTopicsCSV},
|
||||
}
|
||||
|
||||
// DefaultDataSet seeds every table defined in defaultDataEntries.
|
||||
// It attempts all tables and returns a combined error if any fail.
|
||||
|
|
|
|||
|
|
@ -0,0 +1,29 @@
|
|||
id,name,code,description,is_active,created_at,updated_at
|
||||
1,Отгул,timeoff,Отгул,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
2,Отпуск,vacation,Отпуск,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
3,Больничный,sickleave,Больничный,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
4,Внебюджетные расходы,non_budget_expenses,Внебюджетные расходы с выбором филиала и типа,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
5,Внебюджетные расходы ПЭТ Лайн,non_budget_expenses_pet_line,Внебюджетные расходы ПЭТ Лайн с выбором филиала и типа,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
6,Возвраты,returns,Возвраты товаров с выбором типа и региона,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
7,Изменение клиента в ОКБ и 1С,client_changes,Изменение данных клиента в системах,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
8,Заказ товаров,goods_order,Заказ товаров на месяц или дополнительно,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
9,Отгрузки на СОХ,shipments_soh,Отгрузки на СОХ реальные или для лимита,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
10,Паспорт сделки,transaction_passport,Паспорт сделки по регионам,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
11,Ставки логистика,rates_logistics,Ставки логистики разово или надолго,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
12,Поступления по приходным документам,receipts,Поступления по филиалам,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
13,Доставка клиентам/на склад,delivery_clients,Доставка с выбором согласующего,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
14,В. Отгрузки,v_shipments,Внутренние отгрузки,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
15,Менеджерские расходы,manager_expenses,Расходы менеджеров,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
16,Отгрузки,shipments,Обычные отгрузки,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
17,Нестандартные условия договора поставки,nonstandard_contract,Нестандартные условия договоров,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
18,Вакансии,vacancies,Согласование вакансий,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
19,Ставки доставки АП,delivery_rates_ap,Ставки доставки Альфапэт,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
20,Утверждение фрилансеров,freelancers_approval,Согласование фрилансеров,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
21,Выход в нерабочий день,non_working_day,Выход в выходной или праздничный день,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
22,Предложения и пожелания,suggestions,Предложения по улучшению работы,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
23,Долгосрочные условия ОТК,otk_conditions,Долгосрочные условия отсрочки,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
24,Остаток в кассах,cash_balance,Остатки в кассах с выбором согласующего,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
25,Продажи по клиенту,client_sales,Информация о продажах по клиенту,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
26,Проведенные расходы по менеджеру,manager_expenses_report,Отчет о расходах менеджера,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
27,Заведение новых клиентов,new_clients,Добавление новых клиентов в базу,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
28,Утверждение оплат безнал,payments_cashless,Согласование безналичных оплат,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
|
|
|
@ -0,0 +1,148 @@
|
|||
id,category_id,name,code,duration_type,time_type,payment_type,template,allows_file,is_active,created_at,updated_at,allow_approver_selection,first_approver_role_code,allow_observer_selection,approval_mode,require_approver_comment,requires_file,require_observer_selection,instructions
|
||||
70,15,Менеджерские расходы: Крым,manager_expenses_crimea,,,,Оплата платной дороги Краснодар-Темрюк-Краснодар в сумме 1420 руб. (клиент РУСМолоко) (расход Макаренко),false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
590,15,Менеджерские расходы: Краснодар,manager_expenses_krasnodar,,,,,false,true,2026-06-03 08:55:52.439479,2026-06-03 08:55:52.439479,false,,false,sequential,false,false,false,
|
||||
49,7,Сменить менеджера Битрикс Краснодар,client_changes_change_manager_bitrix_krasnodar,,,,Опишите смену менеджера в Битрикс (Краснодар),false,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
586,9,Отгрузка на СОХ — Крым (реальная),shipments_soh_crimea_real,,,,Опишите отгрузку,false,true,2026-06-02 07:10:13.844873,2026-06-02 07:10:13.844873,false,,false,sequential,true,false,false,
|
||||
4,1,Отгул — диапазон частично,timeoff_date_range_partial_own_expense,date_range,partial,own_expense,22.02.2022 - 25.02.2022 с 16:00 по 18:00,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
65,11,Ставки Логистика: Надолго,rates_logistics_long_term,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
592,17,Нестандартные условия поставки: Беларусь,nonstandard_contract_belarus,,,,,true,true,2026-06-03 09:20:00.662572,2026-06-03 09:20:00.662572,false,,false,sequential,true,false,false,
|
||||
591,17,Нестандартные условия поставки: Краснодар,nonstandard_contract_krasnodar,,,,,true,true,2026-06-03 09:20:00.662572,2026-06-03 09:20:00.662572,false,,false,sequential,true,false,false,
|
||||
594,23,ОТК: Краснодар,otk_conditions_krasnodar,,,,,false,true,2026-06-03 09:29:10.377976,2026-06-03 09:29:10.377976,false,,false,sequential,false,false,false,
|
||||
595,23,ОТК: Беларусь,otk_conditions_belarus,,,,,false,true,2026-06-03 09:29:10.377976,2026-06-03 09:29:10.377976,false,,false,sequential,false,false,false,
|
||||
5,1,Отгул — диапазон весь день в счёт отпуска,timeoff_date_range_full_day_vacation_account,date_range,full_day,vacation_account,22.02.2022 - 25.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
6,1,Отгул — диапазон весь день за свой счёт,timeoff_date_range_full_day_own_expense,date_range,full_day,own_expense,22.02.2022 - 25.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
16,3,Больничный — несколько дней официальный,sickleave_multi_day_full_day_official,multi_day,full_day,official,"22.02.2022, 24.02.2022, 26.02.2022",true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
17,3,Больничный — несколько дней в счёт отпуска,sickleave_multi_day_full_day_vacation_account,multi_day,full_day,vacation_account,"22.02.2022, 24.02.2022, 26.02.2022",false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
589,9,Отгрузка на СОХ — Краснодар (лимит),shipments_soh_krasnodar_limit,,,,Опишите отгрузку,false,true,2026-06-02 07:10:13.915061,2026-06-02 07:10:13.915061,false,,false,sequential,true,false,false,
|
||||
587,9,Отгрузка на СОХ — Крым (лимит),shipments_soh_crimea_limit,,,,Опишите отгрузку,false,true,2026-06-02 07:10:13.868383,2026-06-02 07:10:13.868383,false,,false,sequential,true,false,false,
|
||||
21,3,Больничный — диапазон за свой счёт,sickleave_date_range_full_day_own_expense,date_range,full_day,own_expense,22.02.2022 - 25.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
24,3,Больничный — один день за свой счёт,sickleave_single_day_full_day_own_expense,single_day,full_day,own_expense,22.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
588,9,Отгрузка на СОХ — Краснодар (реальная),shipments_soh_krasnodar_real,,,,Опишите отгрузку,false,true,2026-06-02 07:10:13.892797,2026-06-02 07:10:13.892797,false,,false,sequential,true,false,false,
|
||||
18,3,Больничный — несколько дней за свой счёт,sickleave_multi_day_full_day_own_expense,multi_day,full_day,own_expense,"22.02.2022, 24.02.2022, 26.02.2022",false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
59,9,Отгрузки на СОХ реальная,shipments_soh_real,,,,Опишите реальную отгрузку на СОХ,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
43,7,Поменять название Битрикс Краснодар,client_changes_rename_bitrix_krasnodar,,,,Опишите изменение названия клиента в Битрикс (Краснодар),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
27,4,Внебюджетные расходы: Ф2 ТМЦ,non_budget_expenses_f2_tmc,,,,Прошу согласовать оплату за зарядку для телефона (руководителю отдела логистики) в сумме 293 руб.,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
60,9,Отгрузки на СОХ для лимита,shipments_soh_limit,,,,Опишите отгрузку для лимита на СОХ,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
19,3,Больничный — диапазон официальный,sickleave_date_range_full_day_official,date_range,full_day,official,22.02.2022 - 25.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
22,3,Больничный — один день официальный,sickleave_single_day_full_day_official,single_day,full_day,official,22.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
82,27,Заведение новых клиентов,new_clients,,,,,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
83,28,Утверждение оплат безнал,payments_cashless,,,,,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
1,1,Отгул — несколько дней частично,timeoff_multi_day_partial_own_expense,multi_day,partial,own_expense,"22.02.2022 с 10:00 по 14:00, 24.02.2022 с 09:00 по 12:00",false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
2,1,Отгул — несколько дней весь день в счёт отпуска,timeoff_multi_day_full_day_vacation_account,multi_day,full_day,vacation_account,"22.02.2022, 24.02.2022, 26.02.2022",false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
3,1,Отгул — несколько дней весь день за свой счёт,timeoff_multi_day_full_day_own_expense,multi_day,full_day,own_expense,"22.02.2022, 24.02.2022, 26.02.2022",false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
7,1,Отгул — один день частично,timeoff_single_day_partial_own_expense,single_day,partial,own_expense,22.02.2022 с 16:00 по 18:00,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
8,1,Отгул — один день весь день в счёт отпуска,timeoff_single_day_full_day_vacation_account,single_day,full_day,vacation_account,22.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
9,1,Отгул — один день весь день за свой счёт,timeoff_single_day_full_day_own_expense,single_day,full_day,own_expense,22.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
10,2,Отпуск — несколько дней в счёт отпуска,vacation_multi_day_full_day_vacation_account,multi_day,full_day,vacation_account,"22.02.2022, 24.02.2022, 26.02.2022",false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
11,2,Отпуск — несколько дней за свой счёт,vacation_multi_day_full_day_own_expense,multi_day,full_day,own_expense,"22.02.2022, 24.02.2022, 26.02.2022",false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
12,2,Отпуск — диапазон в счёт отпуска,vacation_date_range_full_day_vacation_account,date_range,full_day,vacation_account,22.02.2022 - 25.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
13,2,Отпуск — диапазон за свой счёт,vacation_date_range_full_day_own_expense,date_range,full_day,own_expense,22.02.2022 - 25.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
14,2,Отпуск — один день в счёт отпуска,vacation_single_day_full_day_vacation_account,single_day,full_day,vacation_account,22.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
15,2,Отпуск — один день за свой счёт,vacation_single_day_full_day_own_expense,single_day,full_day,own_expense,22.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
20,3,Больничный — диапазон в счёт отпуска,sickleave_date_range_full_day_vacation_account,date_range,full_day,vacation_account,22.02.2022 - 25.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
23,3,Больничный — один день в счёт отпуска,sickleave_single_day_full_day_vacation_account,single_day,full_day,vacation_account,22.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
61,10,ПС: Краснодар,transaction_passport_krasnodar,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,true,false,
|
||||
580,8,Заказ на месяц — Крым,goods_order_monthly_crimea,,,,"Опишите Скилур заказ:
|
||||
22 гр.38 мм бесцветная (10176) ЕПМ - 5кор.
|
||||
ф1, на склад Гвардейское, 2я декада.",true,true,2026-05-27 07:32:42.878447,2026-05-27 07:32:42.878447,false,,false,sequential,true,true,false,
|
||||
58,8,Заказ товаров дополнительный,goods_order_additional,,,,Опишите дополнительный заказ,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,true,false,
|
||||
582,8,Дополнительный заказ — Крым,goods_order_additional_crimea,,,,"Опишите Скилур заказ:
|
||||
22 гр.38 мм бесцветная (10176) ЕПМ - 5кор.
|
||||
ф1, на склад Гвардейское, 2я декада.",true,true,2026-05-27 07:32:42.959177,2026-05-27 07:32:42.959177,false,,false,sequential,true,true,false,
|
||||
57,8,Заказ товаров на месяц,goods_order_monthly,,,,Опишите заказ на месяц,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,true,false,
|
||||
597,4,Внебюджетные расходы: Ф1 ТМЦ (без ПП),non_budget_expenses_f1_tmc_pp_no,,,,,false,true,2026-06-10 09:06:59.648658,2026-06-10 09:06:59.648658,false,,false,sequential,false,false,false,
|
||||
599,4,Внебюджетные расходы: Ф1 Расход (без ПП),non_budget_expenses_f1_expense_pp_no,,,,,false,true,2026-06-10 09:06:59.684144,2026-06-10 09:06:59.684144,false,,false,sequential,false,false,false,
|
||||
42,7,Поменять название ОКБ Краснодар,client_changes_rename_okb_krasnodar,,,,Опишите изменение названия клиента в ОКБ (Краснодар),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
602,28,Оплата безнал — Разное (нужна ПП),payments_cashless_misc_pp_yes,,,,,true,true,2026-06-10 09:06:59.730960,2026-06-10 09:06:59.730960,false,,false,sequential,false,true,false,
|
||||
603,28,Оплата безнал — Разное (без ПП),payments_cashless_misc_pp_no,,,,,true,true,2026-06-10 09:06:59.746484,2026-06-10 09:06:59.746484,false,,false,sequential,false,true,false,
|
||||
600,28,Оплата безнал — Товар (нужна ПП),payments_cashless_goods_pp_yes,,,,,true,true,2026-06-10 09:06:59.699401,2026-06-10 09:06:59.699401,false,,false,sequential,false,true,false,
|
||||
601,28,Оплата безнал — Товар (без ПП),payments_cashless_goods_pp_no,,,,,true,true,2026-06-10 09:06:59.716456,2026-06-10 09:06:59.716456,false,,false,sequential,false,true,false,
|
||||
598,4,Внебюджетные расходы: Ф1 Расход (нужна ПП),non_budget_expenses_f1_expense_pp_yes,,,,,true,true,2026-06-10 09:06:59.666345,2026-06-10 09:06:59.666345,false,,false,sequential,false,true,false,
|
||||
596,4,Внебюджетные расходы: Ф1 ТМЦ (нужна ПП),non_budget_expenses_f1_tmc_pp_yes,,,,,true,true,2026-06-10 09:06:59.628993,2026-06-10 09:06:59.628993,false,,false,sequential,false,true,false,
|
||||
37,6,Самостоятельная продажа Крым,returns_self_sale_crimea,,,,"ТД Крымэколайф
|
||||
40,5 гр.1881 бесцветная (7808) ПФ - 52 короба
|
||||
Реализация товаров и услуг ЧП000003123 от 4.08.25
|
||||
Ф1
|
||||
|
||||
Причина: для сокращения долга клиента
|
||||
|
||||
Действия: продам ООО Нива",false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
34,6,Возврат поставщику Краснодар,returns_supplier_krasnodar,,,,,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
38,6,Самостоятельная продажа Краснодар,returns_self_sale_krasnodar,,,,,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
33,6,Возврат поставщику Крым,returns_supplier_crimea,,,,"Бишули
|
||||
28 гр.1881 бесцветная (9504) ПФ - 2 короба
|
||||
Реализация товаров и услуг ЧП000001326 от 20.04.2026 8:00:01
|
||||
Ф1
|
||||
|
||||
Причина: Короб приехал с завода и сильно порвался в дороге, клиент не может на свою продукцию использовать его",false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
62,10,ПС: Крым,transaction_passport_crimea,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,true,false,
|
||||
73,18,Вакансии,vacancies,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,supervisor,false,sequential,false,false,false,
|
||||
80,25,Продажи по клиенту,client_sales,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,manager,false,sequential,false,true,false,
|
||||
78,23,ОТК: Крым,otk_conditions_crimea,,,,Опишите долгосрочные условия ОТК,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
605,7,Внести нового клиента - Краснодар,client_changes_new_client_krasnodar,,,,,false,true,2026-06-11 04:33:53.266045,2026-06-11 04:33:53.266045,false,,false,sequential,false,false,false,
|
||||
607,7,Внести нового клиента - Крым,client_changes_new_client_crimea,,,,,false,true,2026-06-11 04:33:53.266045,2026-06-11 04:33:53.266045,false,,false,sequential,false,false,false,
|
||||
609,7,Поменять название - Краснодар,client_changes_rename_krasnodar,,,,,false,true,2026-06-11 04:33:53.266045,2026-06-11 04:33:53.266045,false,,false,sequential,false,false,false,
|
||||
611,7,Поменять название - Крым,client_changes_rename_crimea,,,,,false,true,2026-06-11 04:33:53.266045,2026-06-11 04:33:53.266045,false,,false,sequential,false,false,false,
|
||||
613,7,Сменить менеджера - Краснодар,client_changes_change_manager_krasnodar,,,,,false,true,2026-06-11 04:33:53.266045,2026-06-11 04:33:53.266045,false,,false,sequential,false,false,false,
|
||||
615,7,Сменить менеджера - Крым,client_changes_change_manager_crimea,,,,,false,true,2026-06-11 04:33:53.266045,2026-06-11 04:33:53.266045,false,,false,sequential,false,false,false,
|
||||
53,7,Внести нового клиента 1С Крым,client_changes_new_client_1c_crimea,,,,Опишите данные нового клиента для 1С (Крым),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
50,7,Сменить менеджера 1С Краснодар,client_changes_change_manager_1c_krasnodar,,,,Опишите смену менеджера в 1С (Краснодар),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
72,17,Нестандартные условия поставки: Крым,nonstandard_contract_crimea,,,,Прошу согласовать отсрочку 21 день для клиента ООО Роса (другое юрлицо ООО Аквариум) (менеджер Петров),true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,true,false,false,
|
||||
36,6,Продажа другим менеджером Краснодар,returns_other_manager_krasnodar,,,,,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,manager,false,sequential,false,false,false,
|
||||
64,11,Ставки Логистика: Разово,rates_logistics_once,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
67,12,Приходные документы Ф2,receipts_f2,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,true,true,false,
|
||||
66,12,Приходные документы Ф1,receipts_f1,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,true,true,false,
|
||||
51,7,Внести нового клиента ОКБ Крым,client_changes_new_client_okb_crimea,,,,Опишите данные нового клиента для ОКБ (Крым),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
54,7,Внести нового клиента ОКБ Краснодар,client_changes_new_client_okb_krasnodar,,,,Опишите данные нового клиента для ОКБ (Краснодар),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
47,7,Сменить менеджера 1С Крым,client_changes_change_manager_1c_crimea,,,,Опишите смену менеджера в 1С (Крым),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
41,7,Поменять название 1С Крым,client_changes_rename_1c_crimea,,,,Опишите изменение названия клиента в 1С (Крым),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
29,5,ПЭТ Лайн Ф1 ТМЦ,non_budget_expenses_pet_line_f1_tmc,,,,,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
31,5,ПЭТ Лайн Ф2 ТМЦ,non_budget_expenses_pet_line_f2_tmc,,,,,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
26,4,Внебюджетные расходы: Ф1 Расход,non_budget_expenses_f1_expense,,,,"Прошу оплатить счет ИП Гулякина на сумму 3180,00 руб (без НДС) за продление 1С-Отчетность на 1 год",true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
28,4,Внебюджетные расходы: Ф2 Расход,non_budget_expenses_f2_expense,,,,Прошу согласовать 1000 руб на покупку контактов резюме грузчиков на платформе Авито,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
75,20,Утверждение фрилансеров,freelancers_approval,,,,Одного помощника на выгрузку полной фуры с крышкой ручкой с КТ на 23.04.2026 на весь день,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
35,6,Продажа другим менеджером Крым,returns_other_manager_crimea,,,,"Бишули
|
||||
61 гр.38 мм бесцветная (3888) ЕП - 11 коробов
|
||||
Реализация товаров и услуг ЧП000000584 от 05.03.2026 8:00:01
|
||||
Ф1
|
||||
|
||||
Причина: Часть заказа отвалилась, будут переходить на эту позицию не раньше, чем через 3 мес
|
||||
|
||||
Продаст Чекальский на Бойко",false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,manager,false,sequential,false,false,false,
|
||||
77,22,Предложения и пожелания,suggestions,,,,,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
63,10,ПС: Беларусь,transaction_passport_belarus,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,true,false,
|
||||
74,19,Ставки доставки АП,delivery_rates_ap,,,,Прошу согласовать доставку 14 кор преформы клиенту Олег-Выдув-Сочи за 34 000 руб.,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
71,16,Отгрузки,shipments,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,true,sequential,false,true,true,"Если не входит в рамки согласованного лимита, добавь руководителя соответствующего филиала к согласованию через кнопку 'Добавить согласующего'"
|
||||
584,28,Оплата безнал — Товар,payments_cashless_goods,,,,Опишите оплату,false,true,2026-06-02 06:14:34.876867,2026-06-02 06:14:34.876867,false,,false,sequential,false,false,false,
|
||||
585,28,Оплата безнал — Разное,payments_cashless_misc,,,,Опишите оплату,false,true,2026-06-02 06:14:34.926542,2026-06-02 06:14:34.926542,false,,false,sequential,false,false,false,
|
||||
583,8,Дополнительный заказ — Краснодар,goods_order_additional_krasnodar,,,,"Опишите Скилур заказ:
|
||||
22 гр.38 мм бесцветная (10176) ЕПМ - 5кор.
|
||||
ф1, на склад Гвардейское, 2я декада.",true,true,2026-05-27 07:32:42.987951,2026-05-27 07:32:42.987951,false,,false,sequential,true,true,false,
|
||||
581,8,Заказ на месяц — Краснодар,goods_order_monthly_krasnodar,,,,"Скилур заказ:
|
||||
22 гр.38 мм бесцветная (10176) ЕПМ - 5кор.
|
||||
ф1, на склад Гвардейское, 2я декада.",true,true,2026-05-27 07:32:42.929341,2026-05-27 07:32:42.929341,false,,false,sequential,true,true,false,
|
||||
79,24,Остаток в кассах,cash_balance,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,supervisor,false,sequential,false,false,false,
|
||||
55,7,Внести нового клиента Битрикс Краснодар,client_changes_new_client_bitrix_krasnodar,,,,Опишите данные нового клиента для Битрикс (Краснодар),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
25,4,Внебюджетные расходы: Ф1 ТМЦ,non_budget_expenses_f1_tmc,,,,Прошу согласовать и оплатить Счет от ООО Интернет Решения (Озон) за ноутбук и мышь для закупщика в сумме 31 335 руб. С НДС,true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
30,5,ПЭТ Лайн Ф1 Расход,non_budget_expenses_pet_line_f1_expense,,,,,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
76,21,Выход в нерабочий день,non_working_day,,,,Прошу вывести склад для учета c 25.04 по 26.04,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
68,13,Доставка клиентам/на склад,delivery_clients,,,,"Иванов Иван Иванович
|
||||
Тел 89781234567
|
||||
Паспорт 1234 567890
|
||||
ДАФ н862нн46 п/п АА8473|46
|
||||
|
||||
61 бц с ад - 52 кор
|
||||
ЧП000001676
|
||||
|
||||
ЕПР-СтройКрым",true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,manager,false,sequential,false,false,false,
|
||||
32,5,ПЭТ Лайн Ф2 Расход,non_budget_expenses_pet_line_f2_expense,,,,,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
40,7,Поменять название Битрикс Крым,client_changes_rename_bitrix_crimea,,,,Опишите изменение названия клиента в Битрикс (Крым),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
44,7,Поменять название 1С Краснодар,client_changes_rename_1c_krasnodar,,,,Опишите изменение названия клиента в 1С (Краснодар),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
46,7,Сменить менеджера Битрикс Крым,client_changes_change_manager_bitrix_crimea,,,,Опишите смену менеджера в Битрикс (Крым),false,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
56,7,Внести нового клиента 1С Краснодар,client_changes_new_client_1c_krasnodar,,,,Опишите данные нового клиента для 1С (Краснодар),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
52,7,Внести нового клиента Битрикс Крым,client_changes_new_client_bitrix_crimea,,,,Опишите данные нового клиента для Битрикс (Крым),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
45,7,Сменить менеджера ОКБ Крым,client_changes_change_manager_okb_crimea,,,,Опишите смену менеджера в ОКБ (Крым),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
48,7,Сменить менеджера ОКБ Краснодар,client_changes_change_manager_okb_krasnodar,,,,Опишите смену менеджера в ОКБ (Краснодар),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
69,14,В. Отгрузки,v_shipments,,,,ООО Нива на 370 тыс. руб. под 19%,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
81,26,Проведенные расходы по менеджеру,manager_expenses_report,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,manager,false,sequential,false,false,false,
|
||||
39,7,Поменять название ОКБ Крым,client_changes_rename_okb_crimea,,,,Опишите изменение названия клиента в ОКБ (Крым),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
|
|
|
@ -38,17 +38,7 @@ 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 {
|
||||
|
|
|
|||
|
|
@ -1,36 +0,0 @@
|
|||
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
|
||||
}
|
||||
|
|
@ -36,20 +36,5 @@ 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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,10 +15,12 @@ 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 'Внутренний уникальный идентификатор записи';
|
||||
|
|
@ -32,13 +34,5 @@ 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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,10 +15,12 @@ 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 'Внутренний уникальный идентификатор записи';
|
||||
|
|
@ -28,10 +30,5 @@ 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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,10 +28,5 @@ 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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,10 +15,12 @@ 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 'Внутренний уникальный идентификатор записи делегирования';
|
||||
|
|
@ -33,13 +35,5 @@ 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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -26,9 +26,5 @@ 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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,77 +0,0 @@
|
|||
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
|
||||
}
|
||||
|
|
@ -33,12 +33,5 @@ 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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,9 +15,11 @@ 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 задачи';
|
||||
|
|
@ -31,9 +33,5 @@ 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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,38 +0,0 @@
|
|||
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
|
||||
}
|
||||
|
|
@ -33,12 +33,5 @@ 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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,10 +28,5 @@ 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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -31,14 +31,5 @@ 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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -26,9 +26,5 @@ 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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,33 +0,0 @@
|
|||
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
|
||||
}
|
||||
|
|
@ -1,51 +0,0 @@
|
|||
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
|
||||
}
|
||||
|
|
@ -1,66 +0,0 @@
|
|||
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
|
||||
}
|
||||
|
|
@ -31,16 +31,5 @@ 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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -24,18 +24,8 @@ 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()
|
||||
}
|
||||
|
|
@ -93,12 +83,6 @@ 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()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,15 +28,5 @@ 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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,31 +0,0 @@
|
|||
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
|
||||
}
|
||||
|
|
@ -30,9 +30,5 @@ 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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -30,9 +30,5 @@ 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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,56 +0,0 @@
|
|||
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
|
||||
}
|
||||
|
|
@ -31,20 +31,5 @@ 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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -30,11 +30,5 @@ 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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -27,13 +27,5 @@ 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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,7 +9,6 @@ import (
|
|||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
|
@ -88,8 +87,6 @@ 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())
|
||||
|
||||
|
|
|
|||
|
|
@ -1,195 +0,0 @@
|
|||
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
|
||||
}
|
||||
|
|
@ -44,100 +44,6 @@ 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 — поиск заявок по частичному совпадению в тексте
|
||||
|
|
@ -243,8 +149,6 @@ 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())
|
||||
|
|
@ -277,8 +181,6 @@ 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)
|
||||
|
|
@ -513,7 +415,6 @@ 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.*").
|
||||
|
|
@ -525,19 +426,14 @@ 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) UNION (%s) UNION (%s)", s1, s2, s3, s4, s5, s6)
|
||||
|
||||
allArgs := append(append(append(append(append(a1, a2...), a3...), a4...), a5...), a6...)
|
||||
unionSQL := fmt.Sprintf("(%s) UNION (%s) UNION (%s) UNION (%s)", s1, s2, s3, s4)
|
||||
allArgs := append(append(append(a1, a2...), a3...), a4...)
|
||||
|
||||
q = q.Where(squirrel.Expr("a.id IN ("+unionSQL+")", allArgs...))
|
||||
}
|
||||
|
|
@ -575,28 +471,15 @@ 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.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"),
|
||||
Join(dbcoretablenames.TableNameApprovalTopics.ToString() + " t ON t.id = a.topic_id").
|
||||
Join(dbcoretablenames.TableNameApprovalTopicCategories.ToString() + " c ON c.id = t.category_id").
|
||||
Join(dbcoretablenames.TableNamePermissions.ToString() + " p ON p.topic_category_id = c.id").
|
||||
Join("user_roles ur ON ur.role_id = p.role_id").
|
||||
Where(squirrel.And{
|
||||
squirrel.Eq{"ur.user_id": userID},
|
||||
squirrel.Eq{"p.action": "observe"},
|
||||
})
|
||||
|
||||
default:
|
||||
|
|
|
|||
|
|
@ -10,7 +10,6 @@ import (
|
|||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/sirupsen/logrus"
|
||||
"time"
|
||||
)
|
||||
|
||||
type ApprovalAdditionalApproverDB struct {
|
||||
|
|
@ -77,8 +76,6 @@ 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())
|
||||
|
|
|
|||
|
|
@ -10,7 +10,6 @@ import (
|
|||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/sirupsen/logrus"
|
||||
"time"
|
||||
)
|
||||
|
||||
type ApprovalAdditionalObserverDB struct {
|
||||
|
|
@ -77,8 +76,6 @@ 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())
|
||||
|
|
|
|||
|
|
@ -10,7 +10,6 @@ import (
|
|||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/sirupsen/logrus"
|
||||
"time"
|
||||
)
|
||||
|
||||
type ApprovalCommentDB struct {
|
||||
|
|
@ -78,8 +77,6 @@ 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())
|
||||
|
|
@ -95,23 +92,18 @@ func (u *ApprovalCommentDB) CreateApprovalCommentDB(ctx context.Context, tx pgx.
|
|||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
return nil, tx, err
|
||||
}
|
||||
|
||||
returnObjBool := len(returnObj) > 0 && returnObj[0]
|
||||
if returnObjBool {
|
||||
if insertedID == 0 {
|
||||
return nil, nil, errors.New("inserted ID is 0 after insert")
|
||||
}
|
||||
if returnObjBool && insertedID > 0 {
|
||||
created, err := u.GetApprovalCommentByIDDB(ctx, insertedID)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return created, nil, nil
|
||||
return created, tx, err
|
||||
}
|
||||
|
||||
return nil, nil, nil
|
||||
return nil, tx, nil
|
||||
}
|
||||
|
||||
func (u *ApprovalCommentDB) UpdateApprovalCommentDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalComment, returnObj ...bool) (*typescore.ApprovalComment, pgx.Tx, error) {
|
||||
if paramsUpdate.ID == nil {
|
||||
return nil, nil, errors.New("ApprovalComment obj is nil")
|
||||
|
|
|
|||
|
|
@ -10,7 +10,6 @@ import (
|
|||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/sirupsen/logrus"
|
||||
"time"
|
||||
)
|
||||
|
||||
type ApprovalFileDB struct {
|
||||
|
|
@ -31,7 +30,6 @@ 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) {
|
||||
|
|
@ -80,8 +78,6 @@ 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())
|
||||
|
|
@ -230,42 +226,3 @@ 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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ type ApprovalFlowNodeDBI interface {
|
|||
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
|
||||
DeleteFlowNodesByTopicIDDB(ctx context.Context, topicID uint64) error
|
||||
GetFlowNodeByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalFlowNode, error)
|
||||
}
|
||||
|
||||
|
|
@ -148,10 +148,10 @@ func (u *ApprovalFlowNodeDB) DeleteApprovalFlowNodeDB(ctx context.Context, node
|
|||
return err
|
||||
}
|
||||
|
||||
func (u *ApprovalFlowNodeDB) DeleteFlowNodesByCategoryIDDB(ctx context.Context, catID uint64) error {
|
||||
func (u *ApprovalFlowNodeDB) DeleteFlowNodesByTopicIDDB(ctx context.Context, topicID uint64) error {
|
||||
query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Delete(dbcoretablenames.TableNameApprovalFlowNodes.ToString()).
|
||||
Where(squirrel.Eq{"category_id": catID}).
|
||||
Where(squirrel.Eq{"topic_id": topicID}).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return err
|
||||
|
|
|
|||
|
|
@ -1,215 +0,0 @@
|
|||
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
|
||||
}
|
||||
|
|
@ -7,7 +7,6 @@ import (
|
|||
"context"
|
||||
"errors"
|
||||
"github.com/sirupsen/logrus"
|
||||
"time"
|
||||
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
|
@ -32,7 +31,6 @@ 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) {
|
||||
|
|
@ -79,8 +77,6 @@ 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())
|
||||
|
||||
|
|
@ -123,8 +119,6 @@ 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)
|
||||
|
|
@ -238,43 +232,3 @@ 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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,7 +11,6 @@ import (
|
|||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/sirupsen/logrus"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
|
|
@ -46,28 +45,6 @@ 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()
|
||||
|
|
@ -94,6 +71,7 @@ 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")
|
||||
|
|
@ -101,44 +79,7 @@ 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())
|
||||
|
||||
|
|
|
|||
|
|
@ -1,151 +0,0 @@
|
|||
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
|
||||
}
|
||||
|
|
@ -31,7 +31,6 @@ 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) {
|
||||
|
|
@ -209,42 +208,3 @@ 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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -35,7 +35,6 @@ 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 — категории тем, по которым у инициатора есть заявки
|
||||
|
|
@ -287,42 +286,3 @@ 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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,156 +28,6 @@ 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) {
|
||||
|
|
|
|||
|
|
@ -29,7 +29,6 @@ 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) {
|
||||
|
|
@ -190,42 +189,3 @@ 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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,126 +0,0 @@
|
|||
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
|
||||
}
|
||||
|
|
@ -1,508 +0,0 @@
|
|||
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
|
||||
}
|
||||
|
|
@ -1,169 +0,0 @@
|
|||
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
|
||||
}
|
||||
|
|
@ -184,6 +184,7 @@ 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).
|
||||
|
|
|
|||
|
|
@ -29,7 +29,6 @@ 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) {
|
||||
|
|
@ -190,42 +189,3 @@ 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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,76 +0,0 @@
|
|||
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
|
||||
}
|
||||
|
|
@ -1,186 +0,0 @@
|
|||
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
|
||||
}
|
||||
|
|
@ -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,14 +37,6 @@ 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) {
|
||||
|
|
@ -56,27 +48,9 @@ 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()
|
||||
|
|
@ -84,8 +58,6 @@ 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
|
||||
|
|
@ -386,74 +358,6 @@ 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.*").
|
||||
|
|
@ -485,303 +389,3 @@ 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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,7 +6,6 @@ import (
|
|||
dbutils "bitrix_balancer_api/core/utilscore/db"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/Masterminds/squirrel"
|
||||
|
|
@ -29,8 +28,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, departmentID, topicID, categoryID uint64, systems []string) ([]*typescore.User, error)
|
||||
GetHierarchiesWithRelations(ctx context.Context, opts typescore.ListDbOptions, userStatuses ...string) ([]*typescore.UserHierarchy, uint64, error)
|
||||
|
||||
GetApproversDB(ctx context.Context, subordinateID uint64, departmentID uint64) ([]*typescore.User, error)
|
||||
}
|
||||
|
||||
func (u *UserHierarchyDB) GetUserHierarchyListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.UserHierarchy, uint64, error) {
|
||||
|
|
@ -182,76 +181,36 @@ func (u *UserHierarchyDB) DeleteUserHierarchyDB(ctx context.Context, params *typ
|
|||
return nil
|
||||
}
|
||||
|
||||
// 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]
|
||||
}
|
||||
|
||||
func (u *UserHierarchyDB) GetApproversDB(ctx context.Context, subordinateID, departmentID, topicID, categoryID uint64) ([]*typescore.User, error) {
|
||||
rawSQL := `
|
||||
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 (
|
||||
WITH ranked AS (
|
||||
SELECT
|
||||
uh.approver_id,
|
||||
uh.priority,
|
||||
uh.target_system,
|
||||
CASE
|
||||
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
|
||||
WHEN uh.topic_id = $3 THEN 1
|
||||
WHEN uh.topic_category_id = $4 THEN 2
|
||||
WHEN uh.topic_id IS NULL
|
||||
AND uh.topic_category_id IS NULL THEN 3
|
||||
END AS specificity
|
||||
FROM user_hierarchy uh
|
||||
LEFT JOIN matching_topics mt ON uh.topic_id = mt.id
|
||||
WHERE uh.subordinate_id = $1
|
||||
AND uh.department_id = $2
|
||||
AND (
|
||||
mt.id IS NOT NULL
|
||||
OR (uh.topic_category_id = $4 AND uh.topic_id IS NULL)
|
||||
uh.topic_id = $3
|
||||
OR uh.topic_category_id = $4
|
||||
OR (uh.topic_id IS NULL AND uh.topic_category_id IS NULL)
|
||||
)
|
||||
),
|
||||
best AS (
|
||||
-- берём только уровень с наивысшей специфичностью
|
||||
SELECT MIN(specificity) AS min_spec FROM ranked
|
||||
),
|
||||
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 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
|
||||
FROM ranked r
|
||||
JOIN best b ON r.specificity = b.min_spec
|
||||
JOIN users u ON u.id = r.approver_id
|
||||
ORDER BY r.priority ASC
|
||||
`
|
||||
|
||||
rows, err := u.pool.Query(ctx, rawSQL,
|
||||
|
|
@ -259,62 +218,37 @@ func (u *UserHierarchyDB) GetApproversDB(
|
|||
departmentID,
|
||||
topicID,
|
||||
categoryID,
|
||||
system,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var approvers []*typescore.User
|
||||
seen := make(map[uint64]bool)
|
||||
var result []*typescore.User
|
||||
for rows.Next() {
|
||||
usr := &typescore.User{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, usr, nil); err != nil {
|
||||
logrus.Warn("GetApproversDB:ScanRowsToStructRows", err)
|
||||
continue
|
||||
}
|
||||
if usr.ID == nil || seen[*usr.ID] {
|
||||
continue
|
||||
}
|
||||
seen[*usr.ID] = true
|
||||
approvers = append(approvers, usr)
|
||||
result = append(result, usr)
|
||||
}
|
||||
|
||||
logrus.Infof("✅ GetApproversDB DONE: Найдено уникальных согласующих: %d", len(approvers))
|
||||
return approvers, nil
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// 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) {
|
||||
func (u *UserHierarchyDB) GetHierarchiesWithRelations(ctx context.Context, opts typescore.ListDbOptions) ([]*typescore.UserHierarchy, uint64, error) {
|
||||
options, filter, err := dbutils.GetOptionsDB[typescore.UserHierarchy](opts)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
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",
|
||||
).
|
||||
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").
|
||||
From("user_hierarchy uh").
|
||||
LeftJoin("users sub ON uh.subordinate_id = sub.id").
|
||||
LeftJoin("users app ON uh.approver_id = app.id").
|
||||
|
|
@ -323,52 +257,8 @@ 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)
|
||||
|
||||
// 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")
|
||||
query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameUserHierarchy.ToString())
|
||||
query = query.OrderBy("created_at DESC")
|
||||
|
||||
sql, args, err := query.PlaceholderFormat(squirrel.Dollar).ToSql()
|
||||
if err != nil {
|
||||
|
|
@ -385,28 +275,25 @@ func (u *UserHierarchyDB) GetHierarchiesWithRelations(ctx context.Context, opts
|
|||
var totalCount uint64
|
||||
|
||||
for rows.Next() {
|
||||
h := &typescore.UserHierarchy{
|
||||
Subordinate: &typescore.User{},
|
||||
Approver: &typescore.User{},
|
||||
Department: &typescore.Department{},
|
||||
TopicCategory: &typescore.ApprovalTopicCategory{},
|
||||
Topic: &typescore.ApprovalTopic{},
|
||||
}
|
||||
h := &typescore.UserHierarchy{}
|
||||
h.Subordinate = &typescore.User{}
|
||||
h.Approver = &typescore.User{}
|
||||
h.Department = &typescore.Department{}
|
||||
h.TopicCategory = &typescore.ApprovalTopicCategory{}
|
||||
h.Topic = &typescore.ApprovalTopic{}
|
||||
|
||||
// Сканируем все поля в соответствующие структуры
|
||||
err := rows.Scan(
|
||||
&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.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.Department.ID, &h.Department.Name,
|
||||
&h.TopicCategory.ID, &h.TopicCategory.Name,
|
||||
&h.Topic.ID, &h.Topic.Name,
|
||||
&totalCount,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, 0, fmt.Errorf("scan error: %w", err)
|
||||
continue
|
||||
}
|
||||
results = append(results, h)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,7 +28,6 @@ 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) {
|
||||
|
|
@ -179,86 +178,3 @@ 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})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,39 +3,27 @@ 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"
|
||||
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"
|
||||
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"
|
||||
TableNameApprovalFlowNodes TableName = "approval_flow_nodes"
|
||||
)
|
||||
|
||||
func (t TableName) ToString() string {
|
||||
|
|
|
|||
33
core/go.mod
33
core/go.mod
|
|
@ -13,27 +13,18 @@ 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.54.0
|
||||
golang.org/x/net v0.57.0
|
||||
golang.org/x/crypto v0.40.0
|
||||
golang.org/x/net v0.42.0
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
gorm.io/driver/postgres v1.6.0
|
||||
gorm.io/gorm v1.31.1
|
||||
)
|
||||
|
||||
require (
|
||||
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/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/go-jose/go-jose/v4 v4.1.1 // indirect
|
||||
github.com/hashicorp/errwrap v1.1.0 // indirect
|
||||
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
|
||||
github.com/hashicorp/go-multierror v1.1.1 // indirect
|
||||
|
|
@ -54,19 +45,9 @@ 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/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
|
||||
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
|
||||
)
|
||||
|
|
|
|||
52
core/go.sum
52
core/go.sum
|
|
@ -1,9 +1,3 @@
|
|||
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=
|
||||
|
|
@ -22,30 +16,16 @@ 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=
|
||||
|
|
@ -119,52 +99,20 @@ 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=
|
||||
|
|
|
|||
|
|
@ -1,200 +0,0 @@
|
|||
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
|
||||
}
|
||||
|
|
@ -1,403 +1,18 @@
|
|||
package tgkit
|
||||
|
||||
import (
|
||||
"bitrix_balancer_api/core/variables"
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime"
|
||||
"mime/multipart"
|
||||
"net"
|
||||
"github.com/sirupsen/logrus"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
|
||||
"github.com/sirupsen/logrus"
|
||||
"golang.org/x/net/proxy"
|
||||
)
|
||||
|
||||
// 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
|
||||
|
|
@ -405,124 +20,163 @@ type Client struct {
|
|||
}
|
||||
|
||||
// ClientConfig — конфигурация клиента
|
||||
type ProxyConfig struct{} // Заглушка, если структура была в другом файле
|
||||
type ClientConfig struct {
|
||||
Token string
|
||||
Proxy *ProxyConfig
|
||||
Timeout time.Duration
|
||||
Timeout time.Duration // по умолчанию 30s
|
||||
Debug bool
|
||||
}
|
||||
|
||||
var (
|
||||
mu sync.Mutex
|
||||
instance *Client
|
||||
)
|
||||
|
||||
func GetClient(cfg ClientConfig) (*Client, error) {
|
||||
if instance != nil {
|
||||
return instance, nil
|
||||
}
|
||||
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
|
||||
if instance != nil {
|
||||
return instance, nil
|
||||
}
|
||||
|
||||
client, err := newClient(cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
instance = client
|
||||
return instance, nil
|
||||
}
|
||||
|
||||
// New создаёт нового клиента
|
||||
func newClient(cfg ClientConfig) (*Client, error) {
|
||||
if cfg.Token == "" {
|
||||
return nil, fmt.Errorf("tgkit: token is required")
|
||||
}
|
||||
if cfg.Timeout == 0 {
|
||||
cfg.Timeout = defaultTimeout
|
||||
cfg.Timeout = 30 * time.Second
|
||||
}
|
||||
|
||||
if cfg.Proxy != nil {
|
||||
logrus.Debugf("tgkit: custom API proxy is enabled")
|
||||
logrus.Debugf("tgkit: proxy is configured: url: %s, username: %s, pass: %s", cfg.Proxy.URL, cfg.Proxy.Username, cfg.Proxy.Password)
|
||||
}
|
||||
|
||||
httpClient, err := buildHTTPClient(cfg.Proxy, cfg.Timeout)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("tgkit: build http client: %w", err)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
bot, err := tgbotapi.NewBotAPIWithClient(cfg.Token, tgbotapi.APIEndpoint, httpClient)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("tgkit: init bot after %d attempts: %w", maxStartupAttempts, err)
|
||||
return nil, fmt.Errorf("tgkit: init bot: %w", 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: defaultTimeout}
|
||||
return &Client{bot: bot, timeout: 30 * time.Second}
|
||||
}
|
||||
|
||||
// Bot возвращает сырой *tgbotapi.BotAPI для обратной совместимости
|
||||
func (c *Client) Bot() *tgbotapi.BotAPI {
|
||||
return c.bot
|
||||
}
|
||||
|
||||
// Self возвращает информацию о боте
|
||||
func (c *Client) Self() tgbotapi.User {
|
||||
return c.bot.Self
|
||||
}
|
||||
|
||||
// GetUpdates возвращает канал обновлений
|
||||
func (c *Client) GetUpdates(timeout int) tgbotapi.UpdatesChannel {
|
||||
u := tgbotapi.NewUpdate(0)
|
||||
u.Timeout = timeout
|
||||
return c.bot.GetUpdatesChan(u)
|
||||
}
|
||||
|
||||
// AnswerCallback отвечает на callback query
|
||||
func (c *Client) AnswerCallback(callbackID string, text string) error {
|
||||
cb := tgbotapi.NewCallback(callbackID, text)
|
||||
_, err := c.bot.Request(cb)
|
||||
return err
|
||||
}
|
||||
|
||||
// DeleteMessage удаляет сообщение
|
||||
func (c *Client) DeleteMessage(chatID int64, messageID int) error {
|
||||
_, err := c.bot.Request(tgbotapi.NewDeleteMessage(chatID, messageID))
|
||||
return err
|
||||
}
|
||||
|
||||
// GetFileDirectURL возвращает прямую ссылку на файл
|
||||
func (c *Client) GetFileDirectURL(fileID string) (string, error) {
|
||||
return c.bot.GetFileDirectURL(fileID)
|
||||
}
|
||||
|
||||
// Request выполняет произвольный запрос к API (для edge cases)
|
||||
func (c *Client) Request(cfg tgbotapi.Chattable) (*tgbotapi.APIResponse, error) {
|
||||
return c.bot.Request(cfg)
|
||||
}
|
||||
|
||||
// buildHTTPClient создаёт http.Client с поддержкой прокси
|
||||
func buildHTTPClient(proxyCfg *ProxyConfig, timeout time.Duration) (*http.Client, error) {
|
||||
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},
|
||||
transport := &http.Transport{
|
||||
TLSClientConfig: &tls.Config{InsecureSkipVerify: false},
|
||||
}
|
||||
|
||||
var finalTransport http.RoundTripper = baseTransport
|
||||
if proxyCfg != nil {
|
||||
finalTransport = &CustomAPIProxyTransport{wrapped: baseTransport}
|
||||
if proxyCfg != nil && proxyCfg.URL != "" {
|
||||
proxyURL, err := url.Parse(proxyCfg.URL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse proxy url: %w", err)
|
||||
}
|
||||
|
||||
scheme := proxyURL.Scheme
|
||||
|
||||
switch scheme {
|
||||
case "socks5", "socks5h":
|
||||
var auth *proxy.Auth
|
||||
|
||||
if proxyCfg.Username != "" {
|
||||
auth = &proxy.Auth{
|
||||
User: proxyCfg.Username,
|
||||
Password: proxyCfg.Password,
|
||||
}
|
||||
} else if proxyURL.User != nil {
|
||||
pass, _ := proxyURL.User.Password()
|
||||
auth = &proxy.Auth{
|
||||
User: proxyURL.User.Username(),
|
||||
Password: pass,
|
||||
}
|
||||
}
|
||||
|
||||
dialer, err := proxy.SOCKS5("tcp", proxyURL.Host, auth, proxy.Direct)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create socks5 dialer: %w", err)
|
||||
}
|
||||
|
||||
transport.Dial = dialer.Dial //nolint:staticcheck
|
||||
|
||||
case "http", "https":
|
||||
transport.Proxy = http.ProxyURL(proxyURL)
|
||||
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported proxy scheme: %s", scheme)
|
||||
}
|
||||
}
|
||||
|
||||
return &http.Client{
|
||||
Transport: finalTransport,
|
||||
Transport: transport,
|
||||
Timeout: timeout,
|
||||
}, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,22 +11,6 @@ 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
|
||||
|
|
@ -39,8 +23,7 @@ func (c *Client) SendPhoto(chatID int64, source string, caption string, opts ...
|
|||
if err != nil {
|
||||
return nil, fmt.Errorf("tgkit: decode base64: %w", err)
|
||||
}
|
||||
fileName := detectImageExtension(data)
|
||||
photo = tgbotapi.FileBytes{Name: fileName, Bytes: data}
|
||||
photo = tgbotapi.FileBytes{Name: "photo.jpg", Bytes: data}
|
||||
default:
|
||||
photo = tgbotapi.FilePath(source)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -43,6 +43,13 @@ 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
|
||||
|
|
|
|||
|
|
@ -3,17 +3,15 @@ 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
|
||||
Telegram *tgkit.Client
|
||||
Config *configcore.Config
|
||||
Redis *redismodule.ModuleRedis
|
||||
DB *database.ModuleDB
|
||||
}
|
||||
|
||||
func ReturnClientsExternal(cfgOptions *configcore.ConfigLoadOptions) (ClientsExternal, error) {
|
||||
|
|
@ -45,16 +43,5 @@ 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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,492 +0,0 @@
|
|||
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📦 <b>Позиции:</b>\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
|
||||
}
|
||||
|
|
@ -1,63 +0,0 @@
|
|||
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
|
||||
}
|
||||
|
|
@ -1,90 +0,0 @@
|
|||
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
|
||||
|
|
@ -14,6 +14,7 @@ import (
|
|||
)
|
||||
|
||||
// BuildExcelApprovalsReport — строит xlsx-файл отчёта по согласованиям и возвращает байты.
|
||||
// Универсальная функция, используется и из админки, и из телеграм-бота.
|
||||
func BuildExcelApprovalsReport(ctx context.Context, db *database.ModuleDB, approvals []*typescore.Approval) ([]byte, error) {
|
||||
f := excelize.NewFile()
|
||||
sheet := "Согласования"
|
||||
|
|
@ -21,34 +22,30 @@ func BuildExcelApprovalsReport(ctx context.Context, db *database.ModuleDB, appro
|
|||
return nil, fmt.Errorf("set sheet name: %w", err)
|
||||
}
|
||||
|
||||
// 1. Обновленные заголовки (добавлены Доп. согласующие и Доп. наблюдатели)
|
||||
headers := []string{
|
||||
"ID", // A
|
||||
"ФИО инициатора", // B
|
||||
"Тема согласования", // C
|
||||
"Дата создания", // D
|
||||
"Согласующие", // E
|
||||
"Наблюдатели", // F
|
||||
"Доп. согласующие", // G 🆕
|
||||
"Доп. наблюдатели", // H 🆕
|
||||
"Статус", // I
|
||||
"Текст согласования", // J
|
||||
"Отдел сотрудника", // K
|
||||
"Комментарии", // L
|
||||
"Дата согласования", // M
|
||||
"Текст задачи", // N
|
||||
"Исполнитель", // O
|
||||
"Статус задачи", // P
|
||||
"Дата исполнения", // Q
|
||||
"ФИО инициатора", // 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"}
|
||||
cols := []string{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N"}
|
||||
|
||||
colWidths := map[string]float64{
|
||||
"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,
|
||||
"A": 25, "B": 40, "C": 18, "D": 30,
|
||||
"E": 30, "F": 16, "G": 40, "H": 25,
|
||||
"I": 30, "J": 18, "K": 40, "L": 25,
|
||||
"M": 18, "N": 18,
|
||||
}
|
||||
|
||||
headerStyle, err := f.NewStyle(&excelize.Style{
|
||||
|
|
@ -129,11 +126,6 @@ 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 {
|
||||
|
|
@ -211,11 +203,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.GetObserversForApprovalDB(ctx, categoryCode, a.TopicID)
|
||||
observers, _ := db.User.GetObserversForCategoryDB(ctx, categoryCode)
|
||||
for _, obs := range observers {
|
||||
if obs.FullName != nil {
|
||||
observerParts = append(observerParts, *obs.FullName)
|
||||
|
|
@ -224,68 +216,6 @@ 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 {
|
||||
|
|
@ -430,23 +360,22 @@ 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 {
|
||||
|
|
@ -455,8 +384,7 @@ func BuildExcelApprovalsReport(ctx context.Context, db *database.ModuleDB, appro
|
|||
}
|
||||
|
||||
cellStyle := style
|
||||
// 🆕 Индексы колонок задач сместились из-за двух новых колонок (было 11-13, стало 13-15)
|
||||
if hasTaskError && colIdx >= 13 && colIdx <= 15 {
|
||||
if hasTaskError && colIdx >= 10 && colIdx <= 12 {
|
||||
cellStyle = errorStyle
|
||||
}
|
||||
if err := f.SetCellStyle(sheet, cell, cell, cellStyle); err != nil {
|
||||
|
|
@ -464,6 +392,7 @@ func BuildExcelApprovalsReport(ctx context.Context, db *database.ModuleDB, appro
|
|||
}
|
||||
}
|
||||
|
||||
// Высота строки
|
||||
rowHeight := 20.0
|
||||
maxLines := len(approverParts)
|
||||
if len(strings.Split(taskText, "\n")) > maxLines {
|
||||
|
|
@ -492,8 +421,6 @@ 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)
|
||||
|
|
|
|||
|
|
@ -11,24 +11,17 @@ 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"`
|
||||
TelegramUser *User `gorm:"-" json:"telegram_user,omitempty"`
|
||||
Password *string `gorm:"-" json:"password,omitempty"`
|
||||
}
|
||||
|
||||
type AdminReq struct {
|
||||
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"`
|
||||
Login *string `json:"login"`
|
||||
Name *string `json:"name"`
|
||||
Password *string `json:"password"` // Пароль пользователя
|
||||
IsRoot *bool `json:"is_root"`
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,28 +0,0 @@
|
|||
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
|
||||
}
|
||||
|
|
@ -20,20 +20,6 @@ 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.
|
||||
|
|
@ -71,7 +57,8 @@ type ApprovalMetadata struct {
|
|||
// Тип изменения
|
||||
ChangeType string `json:"change_type,omitempty"`
|
||||
// Любые другие поля из collected которые нужно сохранить
|
||||
Extra map[string]string `json:"extra,omitempty"`
|
||||
Extra map[string]string `json:"extra,omitempty"`
|
||||
Labels map[string]string `json:"labels,omitempty"`
|
||||
}
|
||||
|
||||
func (m *ApprovalMetadata) ToJSON() (*string, error) {
|
||||
|
|
|
|||
|
|
@ -12,7 +12,6 @@ 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"`
|
||||
|
||||
|
|
|
|||
|
|
@ -4,34 +4,37 @@ 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"`
|
||||
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;not null;index;column:topic_id" json:"topic_id" 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"`
|
||||
|
||||
// Идентификация узла
|
||||
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"`
|
||||
|
||||
// Не сохраняется в БД — для построения дерева в API
|
||||
Children []*ApprovalFlowNode `gorm:"-" json:"children,omitempty"`
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,23 +0,0 @@
|
|||
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"`
|
||||
}
|
||||
|
|
@ -15,8 +15,7 @@ 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"`
|
||||
|
||||
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"`
|
||||
Approval *Approval `gorm:"-" json:"approval,omitempty"`
|
||||
Executor *User `gorm:"-" json:"executor,omitempty"`
|
||||
Files []*ApprovalFile `gorm:"-" json:"files,omitempty"`
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,13 +0,0 @@
|
|||
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"`
|
||||
}
|
||||
|
|
@ -26,10 +26,14 @@ type ApprovalTopic struct {
|
|||
AllowApproverSelection *bool `gorm:"type:boolean;not null;default:false;column:allow_approver_selection" json:"allow_approver_selection,omitempty" db:"allow_approver_selection" mapstructure:"allow_approver_selection"`
|
||||
AllowObserverSelection *bool `gorm:"type:boolean;not null;default:false;column:allow_observer_selection" json:"allow_observer_selection,omitempty" db:"allow_observer_selection" mapstructure:"allow_observer_selection"`
|
||||
|
||||
IsTreeRoot *bool `gorm:"type:boolean;default:false;column:is_tree_root" json:"is_tree_root" db:"is_tree_root" mapstructure:"is_tree_root"`
|
||||
|
||||
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"`
|
||||
|
||||
MessageTemplate *string `gorm:"type:text;column:message_template" json:"message_template,omitempty" db:"message_template" mapstructure:"message_template"`
|
||||
CodeTemplate *string `gorm:"type:text;column:code_template" json:"code_template,omitempty" db:"code_template" mapstructure:"code_template"`
|
||||
|
||||
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"`
|
||||
|
|
|
|||
|
|
@ -1,10 +0,0 @@
|
|||
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"`
|
||||
}
|
||||
|
|
@ -1,62 +0,0 @@
|
|||
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"`
|
||||
}
|
||||
|
|
@ -1,54 +0,0 @@
|
|||
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"`
|
||||
}
|
||||
|
|
@ -3,18 +3,17 @@ 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"`
|
||||
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"`
|
||||
ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"`
|
||||
Name *string `gorm:"type:text;not null;column:name" json:"name" db:"name" mapstructure:"name"`
|
||||
Code *string `gorm:"type:text;not null;unique;column:code" json:"code" db:"code" mapstructure:"code"`
|
||||
IsDefault *bool `gorm:"type:boolean;not null;default:false;column:is_default" json:"is_default" db:"is_default" mapstructure:"is_default"`
|
||||
IsDirector *bool `gorm:"type:boolean;not null;default:false;column:is_director" json:"is_director" db:"is_director" mapstructure:"is_director"`
|
||||
IsApprover *bool `gorm:"type:boolean;not null;default:false;column:is_approver" json:"is_approver" db:"is_approver" mapstructure:"is_approver"`
|
||||
IsObserver *bool `gorm:"type:boolean;not null;default:false;column:is_observer" json:"is_observer" db:"is_observer" mapstructure:"is_observer"`
|
||||
IsExecutor *bool `gorm:"type:boolean;not null;default:false;column:is_executor" json:"is_executor" db:"is_executor" mapstructure:"is_executor"`
|
||||
Description *string `gorm:"type:text;column:description" json:"description,omitempty" db:"description" mapstructure:"description"`
|
||||
CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"`
|
||||
UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at"`
|
||||
|
||||
Permissions []*Permission `gorm:"-" json:"permissions,omitempty"`
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,21 +0,0 @@
|
|||
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"`
|
||||
}
|
||||
|
|
@ -1,78 +0,0 @@
|
|||
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
|
||||
}
|
||||
|
|
@ -15,7 +15,6 @@ 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"`
|
||||
|
|
|
|||
|
|
@ -1,62 +0,0 @@
|
|||
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
|
||||
}
|
||||
|
|
@ -8,10 +8,3 @@ 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"
|
||||
)
|
||||
|
|
|
|||
94
deploy.sh
94
deploy.sh
|
|
@ -34,14 +34,14 @@ GENERATE_SWAGGER="${2:-false}"
|
|||
|
||||
validate_service_type() {
|
||||
case "$1" in
|
||||
bot|telegram|balancer|admin|migrations|telephony|all) return 0 ;; # 🆕 Добавлен telephony
|
||||
bot|telegram|balancer|admin|migrations|all) return 0 ;;
|
||||
*) return 1 ;;
|
||||
esac
|
||||
}
|
||||
|
||||
if ! validate_service_type "$SERVICE_TYPE"; then
|
||||
log_error "Unknown service type: $SERVICE_TYPE"
|
||||
echo "Usage: $0 [telegram|balancer|admin|migrations|telephony|all] [swagger]"
|
||||
echo "Usage: $0 [telegram|balancer|admin|migrations|all] [swagger]"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
|
|
@ -54,25 +54,20 @@ if [ "$SERVICE_TYPE" = "all" ]; then
|
|||
|
||||
SELF="$THIS_PATH/deploy.sh"
|
||||
|
||||
log_service "Step 1/5: Database migrations"
|
||||
log_service "Step 1/4: Database migrations"
|
||||
bash "$SELF" migrations
|
||||
echo ""
|
||||
|
||||
log_service "Step 2/5: Telegram bot"
|
||||
log_service "Step 2/4: Telegram bot"
|
||||
bash "$SELF" telegram
|
||||
echo ""
|
||||
|
||||
# log_service "Step 3/5: REST balancer"
|
||||
# log_service "Step 3/4: REST balancer"
|
||||
# bash "$SELF" balancer
|
||||
# echo ""
|
||||
|
||||
log_service "Step 4/5: REST admin"
|
||||
log_service "Step 4/4: 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!"
|
||||
|
|
@ -101,11 +96,6 @@ 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
|
||||
|
|
@ -152,7 +142,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 в корень сервиса
|
||||
|
|
@ -161,9 +151,7 @@ if [ "$SERVICE_TYPE" = "admin" ] && [ "$GENERATE_SWAGGER" = "swagger" ]; then
|
|||
mv ./docs "$SERVICE_PATH/docs"
|
||||
log_success "Swagger documentation moved to service root"
|
||||
fi
|
||||
|
||||
# 🔧 ИСПРАВЛЕНИЕ: Отдаем права пользователю rom4ik, чтобы GitHub Actions не падал!
|
||||
chown -R rom4ik:rom4ik "$SERVICE_PATH/docs"
|
||||
sudo chown -R git:git "$SERVICE_PATH/docs"
|
||||
|
||||
cd "$SERVICE_PATH"
|
||||
else
|
||||
|
|
@ -212,7 +200,7 @@ if [ "$SERVICE_KIND" = "daemon" ]; then
|
|||
log_warning "Systemd unit not found: /etc/systemd/system/$SERVICE_NAME.service"
|
||||
log_info "Creating systemd unit..."
|
||||
|
||||
tee /etc/systemd/system/$SERVICE_NAME.service > /dev/null <<EOF
|
||||
sudo tee /etc/systemd/system/$SERVICE_NAME.service > /dev/null <<EOF
|
||||
[Unit]
|
||||
Description=$DESCRIPTION
|
||||
After=network.target
|
||||
|
|
@ -231,18 +219,18 @@ StandardError=journal
|
|||
WantedBy=multi-user.target
|
||||
EOF
|
||||
|
||||
systemctl daemon-reload
|
||||
systemctl enable "$SERVICE_NAME"
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl enable "$SERVICE_NAME"
|
||||
log_success "Systemd unit created and enabled"
|
||||
fi
|
||||
|
||||
log_info "Restarting systemd service..."
|
||||
systemctl restart "$SERVICE_NAME"
|
||||
sudo systemctl restart "$SERVICE_NAME"
|
||||
sleep 3
|
||||
|
||||
if systemctl is-active --quiet "$SERVICE_NAME"; then
|
||||
if sudo systemctl is-active --quiet "$SERVICE_NAME"; then
|
||||
log_success "Service is running"
|
||||
SERVICE_STATUS=$(systemctl is-active "$SERVICE_NAME")
|
||||
SERVICE_STATUS=$(sudo systemctl is-active "$SERVICE_NAME")
|
||||
log_info "Status: $SERVICE_STATUS"
|
||||
else
|
||||
log_error "Service failed to start"
|
||||
|
|
@ -255,7 +243,7 @@ elif [ "$SERVICE_KIND" = "oneshot" ]; then
|
|||
log_warning "Systemd unit not found: /etc/systemd/system/$SERVICE_NAME.service"
|
||||
log_info "Creating systemd unit for migrations..."
|
||||
|
||||
tee /etc/systemd/system/$SERVICE_NAME.service > /dev/null <<EOF
|
||||
sudo tee /etc/systemd/system/$SERVICE_NAME.service > /dev/null <<EOF
|
||||
[Unit]
|
||||
Description=$DESCRIPTION
|
||||
After=network.target
|
||||
|
|
@ -267,29 +255,57 @@ WorkingDirectory=/workspace/ruspet_portal_back
|
|||
ExecStart=$BINARY_PATH
|
||||
StandardOutput=journal
|
||||
StandardError=journal
|
||||
RemainAfterExit=yes
|
||||
RemainAfterExit=no
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
EOF
|
||||
|
||||
systemctl daemon-reload
|
||||
sudo systemctl daemon-reload
|
||||
log_success "Systemd unit created"
|
||||
fi
|
||||
|
||||
log_info "Running migrations..."
|
||||
|
||||
# Сбрасываем старые состояния юнита
|
||||
systemctl reset-failed "$SERVICE_NAME" || true
|
||||
# Исправлено: Запуск в неблокирующем режиме для systemd, управление возвращается в скрипт мгновенно
|
||||
sudo systemctl start "$SERVICE_NAME" --no-block
|
||||
|
||||
# Запускаем и ждем завершения (так как Type=oneshot, команда block вернет код выхода программы)
|
||||
if systemctl start "$SERVICE_NAME"; then
|
||||
log_success "Migrations completed successfully!"
|
||||
else
|
||||
log_error "Migrations failed!"
|
||||
journalctl -u "$SERVICE_NAME" -n 50 --no-pager
|
||||
exit 1
|
||||
fi
|
||||
TIMEOUT=300
|
||||
ELAPSED=0
|
||||
|
||||
log_info "Waiting for migrations to complete successfully..."
|
||||
while true; do
|
||||
# Анализируем логи на успешное окончание
|
||||
if sudo journalctl -u "$SERVICE_NAME" --since "2 minutes ago" --no-pager | grep -q "Database migration completed successfully"; then
|
||||
echo ""
|
||||
log_success "Migrations completed successfully (detected via logs)!"
|
||||
|
||||
# Принудительно гасим юнит, если процесс "завис" в памяти после выполнения логики
|
||||
sudo systemctl stop "$SERVICE_NAME" --quiet || true
|
||||
break
|
||||
fi
|
||||
|
||||
# Исправлено: Добавлен sudo для проверки стейта
|
||||
if sudo systemctl show "$SERVICE_NAME" --property=ActiveState --value | grep -q "failed"; then
|
||||
echo ""
|
||||
RESULT=$(sudo systemctl show "$SERVICE_NAME" --property=ExecMainStatus --value)
|
||||
log_error "Migrations failed with exit code: $RESULT"
|
||||
sudo journalctl -u "$SERVICE_NAME" -n 50 --no-pager
|
||||
exit 1
|
||||
fi
|
||||
|
||||
sleep 5
|
||||
ELAPSED=$((ELAPSED + 5))
|
||||
printf "."
|
||||
|
||||
if [ $ELAPSED -ge $TIMEOUT ]; then
|
||||
echo ""
|
||||
log_error "Migrations timed out after ${TIMEOUT}s"
|
||||
sudo journalctl -u "$SERVICE_NAME" -n 50 --no-pager
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
echo ""
|
||||
fi
|
||||
|
||||
echo "════════════════════════════════════════"
|
||||
|
|
|
|||
1
go.work
1
go.work
|
|
@ -6,5 +6,4 @@ use (
|
|||
service/telegram_service
|
||||
service/system_service
|
||||
service/rest_admin_service
|
||||
service/rest_telephony_service
|
||||
)
|
||||
|
|
|
|||
81
go.work.sum
81
go.work.sum
|
|
@ -1,13 +1,3 @@
|
|||
cel.dev/expr v0.25.2 h1:K6j46C81hXtZQfuX60cVWQFBJahKSE2gfRbNuvr5bFs=
|
||||
cel.dev/expr v0.25.2/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4=
|
||||
cloud.google.com/go v0.112.2 h1:ZaGT6LiG7dBzi6zNOvVZwacaXlmf3lRqnC4DQzqyRQw=
|
||||
cloud.google.com/go v0.112.2/go.mod h1:iEqjp//KquGIJV/m+Pk3xecgKNhV+ry+vVTsy4TbDms=
|
||||
cloud.google.com/go/longrunning v0.5.6 h1:xAe8+0YaWoCKr9t1+aWe+OeQgN/iJK1fEgZSXmjuEaE=
|
||||
cloud.google.com/go/longrunning v0.5.6/go.mod h1:vUaDrWYOMKRuhiv6JBnn49YxCPz2Ayn9GqyjaBT8/mA=
|
||||
cloud.google.com/go/translate v1.10.3 h1:g+B29z4gtRGsiKDoTF+bNeH25bLRokAaElygX2FcZkE=
|
||||
cloud.google.com/go/translate v1.10.3/go.mod h1:GW0vC1qvPtd3pgtypCv4k4U8B7EdgK9/QEF2aJEUovs=
|
||||
github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.33.0 h1:l7+6kwRMJNwdCvYdDl7Eax+wzEYHSnNY7zrrfbhDdTA=
|
||||
github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.33.0/go.mod h1:pJTkW8hEUIIi3Pf65lPZOnn4Y81yCllX6IWk2jNXdkM=
|
||||
github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI=
|
||||
github.com/Masterminds/goutils v1.1.1/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU=
|
||||
github.com/Masterminds/semver/v3 v3.1.1 h1:hLg3sBzpNErnxhQtUy/mmLR2I9foDujNK030IGemrRc=
|
||||
|
|
@ -18,27 +8,13 @@ github.com/PuerkitoBio/purell v1.1.1 h1:WEQqlqaGbrPkxLJWfBwQmfEAE1Z7ONdDLqrN38tN
|
|||
github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0=
|
||||
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 h1:d+Bc7a5rLufV/sSk/8dngufqelfh6jnri85riMAaF/M=
|
||||
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE=
|
||||
github.com/andybalholm/brotli v1.0.5/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=
|
||||
github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310 h1:BUAU3CGlLvorLI26FmByPp2eC2qla6E1Tw+scpcg/to=
|
||||
github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8=
|
||||
github.com/bgentry/speakeasy v0.1.0 h1:ByYyxL9InA1OWqxJqqp2A5pYHUrCiAL6K3J+LKSsQkY=
|
||||
github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs=
|
||||
github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2 h1:aBangftG7EVZoUb69Os8IaYg++6uMOdKK83QtkkvJik=
|
||||
github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2/go.mod h1:qwXFYgsP6T7XnJtbKlf1HP8AjxZZyzxMmc+Lq5GjlU4=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d h1:U+s90UTSYgptZMwQh2aRr3LuazLJIa+Pg3Kc1ylSYVY=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
|
||||
github.com/creack/pty v1.1.9 h1:uDmaGzcdjhF4i/plgjmEsriH11Y0o7RKapEf/LDaM3w=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/envoyproxy/go-control-plane v0.14.0 h1:hbG2kr4RuFj222B6+7T83thSPqLjwBIfQawTkC++2HA=
|
||||
github.com/envoyproxy/go-control-plane v0.14.0/go.mod h1:NcS5X47pLl/hfqxU70yPwL9ZMkUlwlKxtAohpi2wBEU=
|
||||
github.com/envoyproxy/go-control-plane/envoy v1.37.0 h1:u3riX6BoYRfF4Dr7dwSOroNfdSbEPe9Yyl09/B6wBrQ=
|
||||
github.com/envoyproxy/go-control-plane/envoy v1.37.0/go.mod h1:DReE9MMrmecPy+YvQOAOHNYMALuowAnbjjEMkkWOi6A=
|
||||
github.com/envoyproxy/go-control-plane/ratelimit v0.1.0 h1:/G9QYbddjL25KvtKTv3an9lx6VBE2cnb8wp1vEGNYGI=
|
||||
github.com/envoyproxy/go-control-plane/ratelimit v0.1.0/go.mod h1:Wk+tMFAFbCXaJPzVVHnPgRKdUdwW/KdbRt94AzgRee4=
|
||||
github.com/envoyproxy/protoc-gen-validate v1.3.3 h1:MVQghNeW+LZcmXe7SY1V36Z+WFMDjpqGAGacLe2T0ds=
|
||||
github.com/envoyproxy/protoc-gen-validate v1.3.3/go.mod h1:TsndJ/ngyIdQRhMcVVGDDHINPLWB7C82oDArY51KfB0=
|
||||
github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA=
|
||||
github.com/go-openapi/swag v0.19.15/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ=
|
||||
github.com/go-openapi/swag/cmdutils v0.26.1 h1:f2iE1ijYaJ3nuu5PaEMx3zpEhzhZFgivCJObWEObLIQ=
|
||||
github.com/go-openapi/swag/cmdutils v0.26.1/go.mod h1:Sm1MVFMkF6guJJ+pQqHnQA3N0j9qALV3NxzDSv6bETM=
|
||||
|
|
@ -48,29 +24,14 @@ github.com/go-openapi/swag/mangling v0.26.1 h1:gpYI4WuPKFJJVjV5cDLGlDVJhFIxYjQc7
|
|||
github.com/go-openapi/swag/mangling v0.26.1/go.mod h1:POETDH01hqAdASXfw7ISEd9bCOE6xBHOt8NHmGZRmYM=
|
||||
github.com/go-openapi/swag/netutils v0.26.1 h1:BNctoc39WTAUMxyAs355fExOPzMZtPbZ0ZZ1Am2FR5M=
|
||||
github.com/go-openapi/swag/netutils v0.26.1/go.mod h1:y02vByhZhQPAVwOX+0KipXFZ/hUbk6G/Enhf5rGaOkQ=
|
||||
github.com/gofiber/fiber/v2 v2.52.0/go.mod h1:KEOE+cXMhXG0zHc9d8+E38hoX+ZN7bhOtgeF2oT6jrQ=
|
||||
github.com/golang/glog v1.2.5 h1:DrW6hGnjIhtvhOIiAKT6Psh/Kd/ldepEa81DKeiRJ5I=
|
||||
github.com/golang/glog v1.2.5/go.mod h1:6AhwSGph0fcJtXVM/PEHPqZlFeoLxhs7/t5UDAwmO+w=
|
||||
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE=
|
||||
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
|
||||
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/go-pkcs11 v0.3.0 h1:PVRnTgtArZ3QQqTGtbtjtnIkzl2iY2kt24yqbrf7td8=
|
||||
github.com/google/go-pkcs11 v0.3.0/go.mod h1:6eQoGcuNJpa7jnd5pMGdkSaQpNDYvPlXWMcjXXThLlY=
|
||||
github.com/huandu/xstrings v1.3.2 h1:L18LIDzqlW6xN2rEkpdV8+oL/IXWJ1APd+vsdYy4Wdw=
|
||||
github.com/huandu/xstrings v1.3.2/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE=
|
||||
github.com/imdario/mergo v0.3.11 h1:3tnifQM4i+fbajXKBHXWEH+KvNHqojZ778UH75j3bGA=
|
||||
github.com/imdario/mergo v0.3.11/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA=
|
||||
github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
|
||||
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
|
||||
github.com/klauspost/compress v1.17.0/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/mailru/easyjson v0.7.6 h1:8yTIVnZgCoiM1TgqoeTl+LfU5Jg6/xL3QhGQnimLYnA=
|
||||
github.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
|
||||
github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
||||
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
|
||||
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||
github.com/mitchellh/cli v1.1.5 h1:OxRIeJXpAMztws/XHlN2vu6imG5Dpq+j61AzAX5fLng=
|
||||
|
|
@ -83,44 +44,20 @@ github.com/mitchellh/reflectwalk v1.0.0 h1:9D+8oIskB4VJBN5SFlmc27fSlIBZaov1Wpk/I
|
|||
github.com/mitchellh/reflectwalk v1.0.0/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=
|
||||
github.com/natefinch/atomic v1.0.1 h1:ZPYKxkqQOx3KZ+RsbnP/YsgvxWQPGxjC0oBt2AhwV0A=
|
||||
github.com/natefinch/atomic v1.0.1/go.mod h1:N/D/ELrljoqDyT3rZrsUmtsuzvHkeB/wWjHV22AZRbM=
|
||||
github.com/philhofer/fwd v1.1.2/go.mod h1:qkPdfjR2SIEbspLqpe1tO4n5yICnr2DY7mqEx2tUTP0=
|
||||
github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 h1:GFCKgmp0tecUJ0sJuv4pzYCqS9+RGSn52M3FUwPs+uo=
|
||||
github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10/go.mod h1:t/avpk3KcrXxUnYOhZhMXJlSEyie6gQbtLq5NM3loB8=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/posener/complete v1.1.1 h1:ccV59UEOTzVDnDUEFdT95ZzHVZ+5+158q8+SJb2QV5w=
|
||||
github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI=
|
||||
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||
github.com/russross/blackfriday/v2 v2.0.1 h1:lPqVAte+HuHNfhJ/0LC98ESWRz8afy9tM/0RK8m9o+Q=
|
||||
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
github.com/ryanuber/columnize v2.1.2+incompatible h1:C89EOx/XBWwIXl8wm8OPJBd7kPF25UfsK2X7Ph/zCAk=
|
||||
github.com/ryanuber/columnize v2.1.2+incompatible/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts=
|
||||
github.com/shurcooL/sanitized_anchor_name v1.0.0 h1:PdmoCO6wvbs+7yrJyMORt4/BmY5IYyJwS/kOiWx8mHo=
|
||||
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
|
||||
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
|
||||
github.com/spf13/cast v1.3.1 h1:nFm6S0SMdyzrzcmThSipiEubIDy8WEXKNZ0UOgiRpng=
|
||||
github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
|
||||
github.com/spiffe/go-spiffe/v2 v2.7.0 h1:uXe1MflJoHw58wAUvxVlcM7WpKtijWG7I1UidcGh6g4=
|
||||
github.com/spiffe/go-spiffe/v2 v2.7.0/go.mod h1:47Q0Q9/AqGha8QLHp+kxpH4Wca7X7EnOtlIJy3mxZ3U=
|
||||
github.com/stretchr/objx v0.1.0 h1:4G4v2dO3VZwixGIRoQ5Lfboy6nUhCyYzaqnIAPPhYs4=
|
||||
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
|
||||
github.com/tinylib/msgp v1.1.8/go.mod h1:qkpG+2ldGg4xRFmx+jfTvZPxfGFhi64BcnL9vkCm/Tw=
|
||||
github.com/urfave/cli/v2 v2.3.0 h1:qph92Y649prgesehzOrQjdWyxFOp/QVM+6imKHad91M=
|
||||
github.com/urfave/cli/v2 v2.3.0/go.mod h1:LJmUH05zAU44vOAcrfzZQKsZbVcdbOG8rtL3/XcUArI=
|
||||
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
|
||||
github.com/valyala/fasthttp v1.51.0/go.mod h1:oI2XroL+lI7vdXyYoQk03bXBThfFl2cVdIA3Xl7cH8g=
|
||||
github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc=
|
||||
github.com/yuin/goldmark v1.4.13 h1:fVcFKWvrslecOb/tg+Cc05dkeYx540o0FuFt3nUVDoE=
|
||||
go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0=
|
||||
go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo=
|
||||
go.opentelemetry.io/contrib/detectors/gcp v1.44.0 h1:NmLfL734pJhM0JKaYd2Y28+nY9dPRWYAAbxhRCrKXPw=
|
||||
go.opentelemetry.io/contrib/detectors/gcp v1.44.0/go.mod h1:tNAsgd8avTGke1+MndXlU5Cru4PQ9Ai/cCNWQv/ZJ/s=
|
||||
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.67.0 h1:yI1/OhfEPy7J9eoa6Sj051C7n5dvpj0QX8g4sRchg04=
|
||||
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.67.0/go.mod h1:NoUCKYWK+3ecatC4HjkRktREheMeEtrXoQxrqYFeHSc=
|
||||
go.opentelemetry.io/otel/sdk v1.44.0 h1:nHYwb9lK+fJPU/dnT6s7W7Z8itMWyqrnVfbheVYrZ58=
|
||||
go.opentelemetry.io/otel/sdk v1.44.0/go.mod h1:Osuydd3Se74nqjAKxid74N5eC+jfEqfTegHRnq58oK0=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRks6si09iEfI=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA=
|
||||
golang.org/x/crypto v0.41.0 h1:WKYxWedPGCTVVl5+WHSSrOBT0O8lx32+zxmHxijgXp4=
|
||||
golang.org/x/crypto v0.41.0/go.mod h1:pO5AFd7FA68rFak7rOAGVuygIISepHftHnr8dr6+sUc=
|
||||
golang.org/x/image v0.25.0 h1:Y6uW6rH1y5y/LK1J8BPWZtr6yZ7hrsy6hFrXjgsc2fQ=
|
||||
|
|
@ -135,8 +72,6 @@ golang.org/x/net v0.43.0/go.mod h1:vhO1fvI4dGsIjh73sWfUVjj3N7CA9WkKJNQm2svM6Jg=
|
|||
golang.org/x/net v0.49.0/go.mod h1:/ysNB2EvaqvesRkuLAyjI1ycPZlQHM3q01F02UY/MV8=
|
||||
golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww=
|
||||
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
|
||||
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||
golang.org/x/telemetry v0.0.0-20250807160809-1a19826ec488 h1:3doPGa+Gg4snce233aCWnbZVFsyFMo/dR40KK/6skyE=
|
||||
golang.org/x/telemetry v0.0.0-20250807160809-1a19826ec488/go.mod h1:fGb/2+tgXXjhjHsTNdVEEMZNWA0quBnfrO+AfoDSAKw=
|
||||
|
|
@ -144,8 +79,6 @@ golang.org/x/telemetry v0.0.0-20260109210033-bd525da824e2 h1:O1cMQHRfwNpDfDJerqR
|
|||
golang.org/x/telemetry v0.0.0-20260109210033-bd525da824e2/go.mod h1:b7fPSJ0pKZ3ccUh8gnTONJxhn3c/PS6tyzQvyqw4iA8=
|
||||
golang.org/x/telemetry v0.0.0-20260610154732-fb80ec83bdd9 h1:FjUup8XrRy7lv+XHONi6KKUSizeF2NnVrTnz/HhbohQ=
|
||||
golang.org/x/telemetry v0.0.0-20260610154732-fb80ec83bdd9/go.mod h1:3AWMyWHS+caVoiEXpiq6+tzKA40J4vQT3MYr80ZtQpc=
|
||||
golang.org/x/telemetry v0.0.0-20260625142307-59b4966ccb57 h1:nwGZBCt+FnXUrGsj5vjzAsEmkcaFvd82BbOjECiFYZc=
|
||||
golang.org/x/telemetry v0.0.0-20260625142307-59b4966ccb57/go.mod h1:3AWMyWHS+caVoiEXpiq6+tzKA40J4vQT3MYr80ZtQpc=
|
||||
golang.org/x/term v0.33.0 h1:NuFncQrRcaRvVmgRkvM3j/F00gWIAlcmlB8ACEKmGIg=
|
||||
golang.org/x/term v0.33.0/go.mod h1:s18+ql9tYWp1IfpV9DmCtQDDSRBUjKaw9M1eAv5UeF0=
|
||||
golang.org/x/term v0.34.0 h1:O/2T7POpk0ZZ7MAzMeWFSg6S5IpWd/RXDlM9hgM3DR4=
|
||||
|
|
@ -154,27 +87,13 @@ golang.org/x/term v0.40.0 h1:36e4zGLqU4yhjlmxEaagx2KuYbJq3EwY8K943ZsHcvg=
|
|||
golang.org/x/term v0.40.0/go.mod h1:w2P8uVp06p2iyKKuvXIm7N/y0UCRt3UfJTfZ7oOpglM=
|
||||
golang.org/x/term v0.44.0 h1:0rLvDRCtNj0gZkyIXhCyOb2OAzEhLVqc4B+hrsBhrmc=
|
||||
golang.org/x/term v0.44.0/go.mod h1:7ze4MdzUzLXpSAoFP1H0bOI9aXDqveSvatT5vKcFh2Y=
|
||||
golang.org/x/term v0.45.0 h1:NwWyBmoJCbfTHpxrWoZ9C6/VxOf7ic219I8xZZFdrf0=
|
||||
golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w=
|
||||
golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU=
|
||||
golang.org/x/tools v0.36.0 h1:kWS0uv/zsvHEle1LbV5LE8QujrxB3wfQyxHfhOk0Qkg=
|
||||
golang.org/x/tools v0.36.0/go.mod h1:WBDiHKJK8YgLHlcQPYQzNCkUxUypCaa5ZegCVutKm+s=
|
||||
golang.org/x/tools v0.41.0 h1:a9b8iMweWG+S0OBnlU36rzLp20z1Rp10w+IY2czHTQc=
|
||||
golang.org/x/tools v0.41.0/go.mod h1:XSY6eDqxVNiYgezAVqqCeihT4j1U2CCsqvH3WhQpnlg=
|
||||
golang.org/x/tools v0.45.0/go.mod h1:LuUGqqaXcXMEFEruIVJVm5mgDD8vww/z/SR1gQ4uE/0=
|
||||
golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q=
|
||||
golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7 h1:9zdDQZ7Thm29KFXgAX/+yaf3eVbP7djjWp/dXAppNCc=
|
||||
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
|
||||
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
|
||||
google.golang.org/appengine v1.6.8 h1:IhEN5q69dyKagZPYMSdIjS2HqprW324FRQZJcGqPAsM=
|
||||
google.golang.org/appengine v1.6.8/go.mod h1:1jJ3jBArFh5pcgW8gCtRJnepW8FzD1V44FJffLiz/Ds=
|
||||
google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7 h1:XzmzkmB14QhVhgnawEVsOn6OFsnpyxNPRY9QV01dNB0=
|
||||
google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7/go.mod h1:L43LFes82YgSonw6iTXTxXUX1OlULt4AQtkik4ULL/I=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260630182238-925bb5da69e7 h1:jQ9p21COKWjP3VwuFrNRiiOTMh3mPpN45R7SLrH/HUU=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260630182238-925bb5da69e7/go.mod h1:KqHwBx2upmfa1XSi1WuRvC+2VGCLtooKkfmyvRbUmqA=
|
||||
google.golang.org/genproto/googleapis/bytestream v0.0.0-20260807164820-c8921c73eeea h1:UWZWShWaGCxLql7oakxNzRXXaGjb0pm+K2zMzw0azz0=
|
||||
google.golang.org/genproto/googleapis/bytestream v0.0.0-20260807164820-c8921c73eeea/go.mod h1:zpqRtTwVou7odpidkkHm+GTCum9L4nuS3SvU5rrEeik=
|
||||
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
|
||||
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
||||
gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ=
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
|
|
@ -5,17 +5,13 @@ 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"
|
||||
|
|
@ -125,7 +121,6 @@ func getClientsExternal() (clientcontrollers.ClientsExternal, error) {
|
|||
options := &configcore.ConfigLoadOptions{
|
||||
Redis: true,
|
||||
Database: true,
|
||||
Telegram: true,
|
||||
Secrets: configcore.SecretsOptions{
|
||||
AuthJWT: configcore.AuthJWTOptions{
|
||||
Admin: true,
|
||||
|
|
@ -145,7 +140,6 @@ func initInternalProvider(clientsExternal clientcontrollers.ClientsExternal) (*t
|
|||
Config: clientsExternal.Config,
|
||||
RedisClient: clientsExternal.Redis,
|
||||
Database: clientsExternal.DB,
|
||||
TGBotClient: clientsExternal.Telegram,
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
|
@ -224,11 +218,7 @@ 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},
|
||||
{"nodes", nodeshandler.RegisterFlowNodesRoutes},
|
||||
}
|
||||
|
||||
// Регистрация всех маршрутов
|
||||
|
|
|
|||
|
|
@ -4,116 +4,13 @@ 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 Получение списка администраторов
|
||||
|
|
@ -148,16 +45,6 @@ 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,
|
||||
|
|
@ -181,6 +68,7 @@ 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")
|
||||
}
|
||||
|
|
@ -199,16 +87,6 @@ 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},
|
||||
|
|
@ -235,9 +113,6 @@ 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)
|
||||
|
|
@ -246,40 +121,6 @@ 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
|
||||
}
|
||||
|
||||
|
|
@ -323,11 +164,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")
|
||||
}
|
||||
|
|
@ -359,71 +200,6 @@ 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,
|
||||
|
|
@ -437,35 +213,12 @@ 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
|
||||
}
|
||||
|
||||
|
|
@ -515,91 +268,10 @@ 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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -34,7 +34,5 @@ func RegisterAdminRoutes(
|
|||
handlers.RegisterRoute(r, http.MethodPut, adminURL, s.UpdateAdminHandler)
|
||||
})
|
||||
|
||||
handlers.RegisterRoute(r, http.MethodPost, "/api/proxy/forward", s.ProxyForwardHandler)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue