Compare commits
310 Commits
| Author | SHA1 | Date |
|---|---|---|
|
|
aa75f62a39 | |
|
|
045b9035d3 | |
|
|
851c06064f | |
|
|
489666bc9a | |
|
|
d466ee0b12 | |
|
|
d17a15218f | |
|
|
f932b90273 | |
|
|
745b5b6853 | |
|
|
d18b984aa7 | |
|
|
ac6a408edd | |
|
|
579793ece7 | |
|
|
554cfc2518 | |
|
|
0120ad58a2 | |
|
|
9930d568af | |
|
|
c2600f1f66 | |
|
|
1f43e90578 | |
|
|
27c57dc5ec | |
|
|
607cf71688 | |
|
|
eef27bfdf5 | |
|
|
d84d17189f | |
|
|
a2d4cd8f96 | |
|
|
f730e6841e | |
|
|
aa37e330ef | |
|
|
172a7266c5 | |
|
|
310c6b2cae | |
|
|
677409cac4 | |
|
|
74e06c12da | |
|
|
b53af43220 | |
|
|
e8655015c3 | |
|
|
1ffa8d1770 | |
|
|
5efbe6b26a | |
|
|
dca0552530 | |
|
|
49152c6cb2 | |
|
|
bb6dc67b9c | |
|
|
fb894c8bd8 | |
|
|
d9263e7764 | |
|
|
2a804ecd34 | |
|
|
66ef682813 | |
|
|
f95ecfa02c | |
|
|
490ae10b7a | |
|
|
e00cc424d3 | |
|
|
f2f0f79880 | |
|
|
152a187fc6 | |
|
|
e3a299acd4 | |
|
|
a9c6eb13a2 | |
|
|
177cdca824 | |
|
|
67cdf9ec02 | |
|
|
3171938ca6 | |
|
|
bece903b4d | |
|
|
f14666f9cf | |
|
|
49baab6b16 | |
|
|
5ae0905c5d | |
|
|
ab43b90f62 | |
|
|
7b205d8a4c | |
|
|
5b4cc47369 | |
|
|
0fe7e28326 | |
|
|
518efa3377 | |
|
|
25073dfcfd | |
|
|
3fea1621cb | |
|
|
8c3c4ff74a | |
|
|
a3b054b24b | |
|
|
037858c015 | |
|
|
d4ede71cc7 | |
|
|
00bff669c9 | |
|
|
6f02987303 | |
|
|
fd51ff6410 | |
|
|
2e5dec8fbe | |
|
|
9c995f54ef | |
|
|
4f7bb68b18 | |
|
|
35d33d78fc | |
|
|
d516439cb4 | |
|
|
eb8d8a6edb | |
|
|
bce6504dbb | |
|
|
113c046a59 | |
|
|
7063b24291 | |
|
|
f2577463cd | |
|
|
e64df28bed | |
|
|
6cd0a07b19 | |
|
|
73419277ea | |
|
|
c1e2e4d655 | |
|
|
1f99b961d8 | |
|
|
cf78d4df85 | |
|
|
afee3e02ec | |
|
|
7ab42525d3 | |
|
|
62f054c741 | |
|
|
a8149bf103 | |
|
|
169e273236 | |
|
|
3dc6b88712 | |
|
|
e1b9b3c07d | |
|
|
c64eb6c0a3 | |
|
|
b4f5fc15c0 | |
|
|
4ccb4d337d | |
|
|
fb98400418 | |
|
|
f9e2dd1fcb | |
|
|
edb945b5e0 | |
|
|
a2949e818c | |
|
|
e384fdba97 | |
|
|
29b759901a | |
|
|
71b466a0e9 | |
|
|
f406b82a0b | |
|
|
25d8ad37b9 | |
|
|
8f33b668fc | |
|
|
774d7006ff | |
|
|
97229182a7 | |
|
|
1b01111553 | |
|
|
de3a83f00a | |
|
|
b6d0051223 | |
|
|
98cbcc27b1 | |
|
|
d410b94baa | |
|
|
82e4d043a2 | |
|
|
c4cc32b817 | |
|
|
5a053754ba | |
|
|
ff66ad7719 | |
|
|
c72d36f556 | |
|
|
ed1b306de0 | |
|
|
42a168c34b | |
|
|
86cf1117f1 | |
|
|
ae08bfabe5 | |
|
|
17eaa929c4 | |
|
|
8a8881503d | |
|
|
438e60178b | |
|
|
b218b9ade3 | |
|
|
5dbfc940f6 | |
|
|
a8d45bab20 | |
|
|
bb80ec34cd | |
|
|
976358ee98 | |
|
|
2e60183c1f | |
|
|
2d45e039fe | |
|
|
88644eded8 | |
|
|
97197f91f5 | |
|
|
a8d20d58d9 | |
|
|
3306d2e9a1 | |
|
|
7dd246b585 | |
|
|
9dd96638a3 | |
|
|
d94a61f9ac | |
|
|
e7f3e4604b | |
|
|
3a147729ef | |
|
|
722d8a03d1 | |
|
|
999a489af8 | |
|
|
25b2ce1f04 | |
|
|
87675d0f88 | |
|
|
4096895f7d | |
|
|
40c33aa9d5 | |
|
|
62c5bfb53b | |
|
|
2ff0325d44 | |
|
|
19ceea64b2 | |
|
|
c16ff4abd6 | |
|
|
ddb52ae6d6 | |
|
|
3e44b87217 | |
|
|
04ac7807f1 | |
|
|
e003acec45 | |
|
|
26019d7cd5 | |
|
|
7c30287071 | |
|
|
a6e928a6a4 | |
|
|
790c8bd82f | |
|
|
38820b69e4 | |
|
|
8e66b19bad | |
|
|
6663bfcac2 | |
|
|
a780dfdf0e | |
|
|
ac60034484 | |
|
|
6de8b93ace | |
|
|
a8b4787fee | |
|
|
dbf289c12c | |
|
|
ecc7c69c26 | |
|
|
eb53b436b6 | |
|
|
a89f8336d6 | |
|
|
3d5349427f | |
|
|
00b40945de | |
|
|
cb08319861 | |
|
|
0405d8574b | |
|
|
9c4216797e | |
|
|
e370d2dd04 | |
|
|
0dda29a4d2 | |
|
|
dcf4552401 | |
|
|
4f60be047c | |
|
|
8e3f87773c | |
|
|
4fbd3d11bc | |
|
|
c9c48a8a01 | |
|
|
0946dd439f | |
|
|
1465988a1e | |
|
|
a68cd9a4e0 | |
|
|
50b86244a0 | |
|
|
364bc616fb | |
|
|
c6ff3d1490 | |
|
|
3986ce4c89 | |
|
|
8c7707f35f | |
|
|
402a6a6d90 | |
|
|
5d724d276b | |
|
|
e96f301350 | |
|
|
e11acda672 | |
|
|
e1766893fd | |
|
|
f2730e47c7 | |
|
|
1eb9b15ac1 | |
|
|
4ae65dc5fa | |
|
|
3d14bc8797 | |
|
|
1ee05d40cb | |
|
|
48042a8122 | |
|
|
1cabe3605b | |
|
|
b0eebdc8c4 | |
|
|
86f3b34f71 | |
|
|
fbb0ac3f19 | |
|
|
e4bdee2956 | |
|
|
fbdff1f7f8 | |
|
|
b348c95623 | |
|
|
1b1f6fb00f | |
|
|
6d6228d941 | |
|
|
73fbeaccc4 | |
|
|
cc6c63a005 | |
|
|
e32a59da3a | |
|
|
e92507d4ac | |
|
|
d7f0596eac | |
|
|
6555717ac7 | |
|
|
2160a97747 | |
|
|
0db4e20c93 | |
|
|
8254447e7e | |
|
|
19d55a4774 | |
|
|
0f854bfaa4 | |
|
|
668ba393ba | |
|
|
9e41c9edd7 | |
|
|
e51757cc2b | |
|
|
c6c1bdae67 | |
|
|
983e9d0bc2 | |
|
|
521d87113e | |
|
|
cdbf1eeb0b | |
|
|
43af69b57b | |
|
|
fb24876125 | |
|
|
4178933149 | |
|
|
dee1c04cb3 | |
|
|
83739e4ba9 | |
|
|
5ab3ff4afa | |
|
|
0438e4a753 | |
|
|
6d22672e91 | |
|
|
b0a849d4f9 | |
|
|
1aeb368ef9 | |
|
|
b9a835038a | |
|
|
6326ed546d | |
|
|
003e9fe0c2 | |
|
|
7b3a7ac401 | |
|
|
1e2abc8552 | |
|
|
71a6b0959c | |
|
|
e0d9b4d16c | |
|
|
4f2159c4c0 | |
|
|
e2933f87fc | |
|
|
1774c0fe70 | |
|
|
837e83dc0e | |
|
|
8d67b222b1 | |
|
|
1faecbe942 | |
|
|
b31ae6fb16 | |
|
|
15915ad44f | |
|
|
a7da5cdebc | |
|
|
9a0572e893 | |
|
|
9fb9106091 | |
|
|
f98df61162 | |
|
|
431dca5bf4 | |
|
|
df1294a514 | |
|
|
0901c8712e | |
|
|
3ed876fe2d | |
|
|
d4309ecf73 | |
|
|
2c44cff102 | |
|
|
480c309f5c | |
|
|
e33363811f | |
|
|
4a811109ff | |
|
|
3bd59dfcd8 | |
|
|
2bf68bc76f | |
|
|
1ae6f8fc63 | |
|
|
da22d0135a | |
|
|
29f0776549 | |
|
|
7189fc073d | |
|
|
461b0d35e4 | |
|
|
382a86b0b2 | |
|
|
d64e6373ee | |
|
|
247c142b8d | |
|
|
afd944b3ca | |
|
|
328b2ff7dd | |
|
|
a726911eaa | |
|
|
0ea6588561 | |
|
|
f7787a2f65 | |
|
|
95bfcb936b | |
|
|
c195d91d1f | |
|
|
c07cb3eccf | |
|
|
46d93bc2d6 | |
|
|
30aa9531ec | |
|
|
b5dc328422 | |
|
|
039ad926dc | |
|
|
769efe4226 | |
|
|
c56eae98f8 | |
|
|
4bc3706689 | |
|
|
4543df136b | |
|
|
fc8c90e43b | |
|
|
7b4f167d0f | |
|
|
5d7797c1cb | |
|
|
302d8974c8 | |
|
|
8873b7a930 | |
|
|
225f7c6bd1 | |
|
|
9034eed116 | |
|
|
62772c036a | |
|
|
d435440adb | |
|
|
a94127d299 | |
|
|
9bee797aff | |
|
|
0765ec640e | |
|
|
46c9177fff | |
|
|
fd1f0ab9e1 | |
|
|
f3d7fa7b81 | |
|
|
54ef55b41f | |
|
|
a2d6fa7989 | |
|
|
00b990118a | |
|
|
d985fe2bdf | |
|
|
08b349c0be | |
|
|
189eb8761b | |
|
|
668eb7b862 |
|
|
@ -6,24 +6,20 @@ on:
|
|||
|
||||
env:
|
||||
REPO_DIR: "/workspace/ruspet_portal_back"
|
||||
REPO_URL: "https://72.56.235.246.nip.io/gitea/romanskijdev/ruspet_portal_back.git"
|
||||
REPO_URL: "https://${{ github.actor }}:${{ github.token }}@72.56.235.246.nip.io/gitea/romanskijdev/ruspet_portal_back.git"
|
||||
BACKUP_DIR: "/tmp/deploy_backups"
|
||||
|
||||
# Имена сервисов
|
||||
TELEGRAM_SERVICE: "telegram_service"
|
||||
BALANCER_SERVICE: "rest_balancer_service"
|
||||
ADMIN_SERVICE: "rest_admin_service"
|
||||
MIGRATIONS_SERVICE: "system_service"
|
||||
TELEPHONY_SERVICE: "rest_telephony_service"
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
runs-on: self-hosted
|
||||
timeout-minutes: 20
|
||||
timeout-minutes: 30
|
||||
|
||||
steps:
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
# ШАГ 1: Информация о деплое
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
- name: 📋 Deployment Info
|
||||
run: |
|
||||
echo "════════════════════════════════════════"
|
||||
|
|
@ -35,122 +31,107 @@ jobs:
|
|||
echo "Message: ${{ github.event.head_commit.message }}"
|
||||
echo "Time: $(date '+%Y-%m-%d %H:%M:%S')"
|
||||
echo "Runner: $(hostname)"
|
||||
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"
|
||||
|
||||
git fetch origin
|
||||
|
||||
# Получаем список изменённых файлов
|
||||
CHANGED_FILES=$(git diff --name-only $OLD_COMMIT origin/develop 2>/dev/null || echo "")
|
||||
CHANGED_FILES=$(git diff --name-only $OLD_COMMIT origin/main 2>/dev/null || echo "")
|
||||
|
||||
if [ -z "$CHANGED_FILES" ]; then
|
||||
echo "⚠️ No changes detected, deploying all services..."
|
||||
DEPLOY_MIGRATIONS=true
|
||||
DEPLOY_TELEGRAM=true
|
||||
DEPLOY_BALANCER=true
|
||||
DEPLOY_ADMIN=true
|
||||
DEPLOY_TELEPHONY=true
|
||||
else
|
||||
echo "📝 Changed files:"
|
||||
echo "$CHANGED_FILES" | sed 's/^/ /'
|
||||
echo ""
|
||||
|
||||
# Изменения в core или deploy.sh влияют на все сервисы
|
||||
if echo "$CHANGED_FILES" | grep -qE "^(core/|deploy\.sh)"; then
|
||||
echo "🔄 Core or deploy.sh changed — deploying ALL services"
|
||||
DEPLOY_MIGRATIONS=true
|
||||
DEPLOY_TELEGRAM=true
|
||||
DEPLOY_BALANCER=true
|
||||
DEPLOY_ADMIN=true
|
||||
DEPLOY_TELEPHONY=true
|
||||
else
|
||||
# Проверяем изменения в конкретных сервисах
|
||||
if echo "$CHANGED_FILES" | grep -q "^service/system_service/"; then
|
||||
echo "🗄️ Migrations service changed"
|
||||
DEPLOY_MIGRATIONS=true
|
||||
fi
|
||||
|
||||
if echo "$CHANGED_FILES" | grep -q "^service/telegram_service/"; then
|
||||
echo "🤖 Telegram bot changed"
|
||||
DEPLOY_TELEGRAM=true
|
||||
fi
|
||||
|
||||
if echo "$CHANGED_FILES" | grep -q "^service/rest_balancer_service/"; then
|
||||
echo "⚖️ Balancer service changed"
|
||||
DEPLOY_BALANCER=true
|
||||
fi
|
||||
|
||||
if echo "$CHANGED_FILES" | grep -q "^service/rest_admin_service/"; then
|
||||
echo "🔧 Admin service changed"
|
||||
DEPLOY_ADMIN=true
|
||||
fi
|
||||
if echo "$CHANGED_FILES" | grep -q "^service/rest_telephony_service/"; then
|
||||
echo "📞 Telephony service changed"
|
||||
DEPLOY_TELEPHONY=true
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
git reset --hard origin/develop
|
||||
git reset --hard origin/main
|
||||
NEW_COMMIT=$(git rev-parse HEAD)
|
||||
echo "New commit: $NEW_COMMIT"
|
||||
else
|
||||
echo "📦 Cloning repo..."
|
||||
git clone -b develop "$REPO_URL" "$REPO_DIR"
|
||||
git clone -b main "$REPO_URL" "$REPO_DIR"
|
||||
DEPLOY_MIGRATIONS=true
|
||||
DEPLOY_TELEGRAM=true
|
||||
DEPLOY_BALANCER=true
|
||||
DEPLOY_ADMIN=true
|
||||
DEPLOY_TELEPHONY=true
|
||||
fi
|
||||
|
||||
# Сохраняем переменные
|
||||
{
|
||||
echo "DEPLOY_MIGRATIONS=$DEPLOY_MIGRATIONS"
|
||||
echo "DEPLOY_TELEGRAM=$DEPLOY_TELEGRAM"
|
||||
echo "DEPLOY_BALANCER=$DEPLOY_BALANCER"
|
||||
echo "DEPLOY_ADMIN=$DEPLOY_ADMIN"
|
||||
echo "DEPLOY_TELEPHONY=$DEPLOY_TELEPHONY"
|
||||
} >> $GITHUB_ENV
|
||||
|
||||
echo ""
|
||||
echo "📊 Deployment plan:"
|
||||
echo " 🗄️ Migrations: $DEPLOY_MIGRATIONS"
|
||||
echo " 🤖 Telegram: $DEPLOY_TELEGRAM"
|
||||
echo " ⚖️ Balancer: $DEPLOY_BALANCER"
|
||||
echo " 🔧 Admin: $DEPLOY_ADMIN"
|
||||
echo " 📞 Telephony: $DEPLOY_TELEPHONY"
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
# ШАГ 3: Проверка плана деплоя
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
- name: 🔍 Check Deployment Plan
|
||||
id: check_plan
|
||||
run: |
|
||||
if [ "$DEPLOY_MIGRATIONS" = "false" ] && \
|
||||
[ "$DEPLOY_TELEGRAM" = "false" ] && \
|
||||
[ "$DEPLOY_BALANCER" = "false" ] && \
|
||||
[ "$DEPLOY_ADMIN" = "false" ]; then
|
||||
if [ "$DEPLOY_MIGRATIONS" = "false" ] && [ "$DEPLOY_TELEGRAM" = "false" ] && [ "$DEPLOY_ADMIN" = "false" ] && [ "$DEPLOY_TELEPHONY" = "false" ]; then
|
||||
echo "⏭️ No services need to be deployed — skipping"
|
||||
echo "SKIP_DEPLOY=true" >> $GITHUB_ENV
|
||||
else
|
||||
echo "SKIP_DEPLOY=false" >> $GITHUB_ENV
|
||||
fi
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
# ШАГ 4: Inject config
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
- name: 🔐 Inject Config
|
||||
if: env.SKIP_DEPLOY == 'false'
|
||||
run: |
|
||||
|
|
@ -162,32 +143,12 @@ jobs:
|
|||
cp /etc/ruspet/config.yml "$REPO_DIR/core/config/config.yml"
|
||||
echo "✅ Config injected"
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
# ШАГ 5: Кэширование Go модулей
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
- name: 💾 Cache Go Modules
|
||||
if: env.SKIP_DEPLOY == 'false'
|
||||
uses: actions/cache@v3
|
||||
with:
|
||||
path: |
|
||||
~/.cache/go-build
|
||||
~/go/pkg/mod
|
||||
/root/.cache/go-build
|
||||
/root/go/pkg/mod
|
||||
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-go-
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
# ШАГ 6: Создание backup-ов перед деплоем
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
- name: 💾 Create Backups
|
||||
if: env.SKIP_DEPLOY == 'false'
|
||||
run: |
|
||||
BACKUP_TIMESTAMP=$(date +%Y%m%d_%H%M%S)
|
||||
echo "BACKUP_TIMESTAMP=$BACKUP_TIMESTAMP" >> $GITHUB_ENV
|
||||
|
||||
# Функция для создания backup
|
||||
create_backup() {
|
||||
local service=$1
|
||||
local binary="/usr/local/bin/$service"
|
||||
|
|
@ -196,138 +157,95 @@ jobs:
|
|||
local backup_file="$BACKUP_DIR/${service}_${BACKUP_TIMESTAMP}"
|
||||
cp "$binary" "$backup_file"
|
||||
echo "💾 Backup created: $backup_file"
|
||||
# Сохраняем путь к backup в env (в верхнем регистре)
|
||||
local var_name="${service^^}_BACKUP"
|
||||
var_name=$(echo "$var_name" | tr '-' '_')
|
||||
local var_name=$(echo "${service}" | tr '[:lower:]' '[:upper:]' | tr '-' '_')_BACKUP
|
||||
echo "$var_name=$backup_file" >> $GITHUB_ENV
|
||||
else
|
||||
echo "⚠️ No binary for $service (first deploy?)"
|
||||
fi
|
||||
}
|
||||
|
||||
# Создаём backup-ы для долгоживущих сервисов
|
||||
if [ "$DEPLOY_TELEGRAM" = "true" ]; then
|
||||
create_backup "$TELEGRAM_SERVICE"
|
||||
fi
|
||||
if [ "$DEPLOY_MIGRATIONS" = "true" ]; then create_backup "$MIGRATIONS_SERVICE"; fi
|
||||
if [ "$DEPLOY_TELEGRAM" = "true" ]; then create_backup "$TELEGRAM_SERVICE"; fi
|
||||
if [ "$DEPLOY_ADMIN" = "true" ]; then create_backup "$ADMIN_SERVICE"; fi
|
||||
if [ "$DEPLOY_TELEPHONY" = "true" ]; then create_backup "$TELEPHONY_SERVICE"; fi
|
||||
|
||||
if [ "$DEPLOY_BALANCER" = "true" ]; then
|
||||
create_backup "$BALANCER_SERVICE"
|
||||
fi
|
||||
|
||||
if [ "$DEPLOY_ADMIN" = "true" ]; then
|
||||
create_backup "$ADMIN_SERVICE"
|
||||
fi
|
||||
|
||||
# Очистка старых backup-ов (оставляем последние 10)
|
||||
echo "🧹 Cleaning old backups..."
|
||||
ls -t "$BACKUP_DIR"/* 2>/dev/null | tail -n +11 | xargs -r rm --
|
||||
ls -t "$BACKUP_DIR"/* 2>/dev/null | tail -n +11 | xargs -r rm -- || true
|
||||
echo "✅ Backups ready"
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
# ШАГ 7: Миграции БД (ВСЕГДА ПЕРВЫМ!)
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
- name: 🗄️ Run Database Migrations
|
||||
- name: 🗄️ Deploy System Service (Migrations & Background Tasks)
|
||||
if: env.DEPLOY_MIGRATIONS == 'true' && env.SKIP_DEPLOY == 'false'
|
||||
id: deploy_migrations
|
||||
run: |
|
||||
cd "$REPO_DIR"
|
||||
echo "🗄️ Running database migrations..."
|
||||
|
||||
if bash deploy.sh migrations; then
|
||||
echo "✅ Migrations completed successfully"
|
||||
echo "🗄️ Deploying system service..."
|
||||
if sudo /usr/bin/bash "$REPO_DIR/deploy.sh" migrations; then
|
||||
echo "✅ System service deployed"
|
||||
echo "MIGRATIONS_DEPLOYED=true" >> $GITHUB_ENV
|
||||
sleep 3
|
||||
# Check if the service FAILED, rather than if it is ACTIVE
|
||||
if ! sudo /usr/bin/systemctl is-failed --quiet "$MIGRATIONS_SERVICE"; then
|
||||
echo "✅ System service executed successfully"
|
||||
else
|
||||
echo "❌ System service failed during execution"
|
||||
sudo /usr/bin/journalctl -u "$MIGRATIONS_SERVICE" -n 30 --no-pager
|
||||
exit 1
|
||||
fi
|
||||
else
|
||||
echo "❌ Migrations failed"
|
||||
echo "❌ System deployment failed"
|
||||
echo "MIGRATIONS_DEPLOYED=false" >> $GITHUB_ENV
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
# ШАГ 8: Деплой Telegram бота
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
- name: 🤖 Deploy Telegram Bot
|
||||
if: env.DEPLOY_TELEGRAM == 'true' && env.SKIP_DEPLOY == 'false'
|
||||
id: deploy_telegram
|
||||
run: |
|
||||
cd "$REPO_DIR"
|
||||
echo "🤖 Deploying Telegram bot..."
|
||||
|
||||
if bash deploy.sh telegram; then
|
||||
if sudo /usr/bin/bash "$REPO_DIR/deploy.sh" telegram; then
|
||||
echo "✅ Telegram bot deployed"
|
||||
echo "TELEGRAM_DEPLOYED=true" >> $GITHUB_ENV
|
||||
|
||||
sleep 3
|
||||
if systemctl is-active --quiet "$TELEGRAM_SERVICE"; then
|
||||
echo "✅ Telegram bot is running"
|
||||
else
|
||||
echo "❌ Telegram bot failed to start"
|
||||
if ! sudo /usr/bin/systemctl is-active --quiet "$TELEGRAM_SERVICE"; then
|
||||
exit 1
|
||||
fi
|
||||
else
|
||||
echo "❌ Telegram bot deployment failed"
|
||||
echo "TELEGRAM_DEPLOYED=false" >> $GITHUB_ENV
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
# ШАГ 9: Деплой балансировщика
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
- name: ⚖️ Deploy Balancer Service
|
||||
if: env.DEPLOY_BALANCER == 'true' && env.SKIP_DEPLOY == 'false'
|
||||
id: deploy_balancer
|
||||
run: |
|
||||
cd "$REPO_DIR"
|
||||
echo "⚖️ Deploying balancer service..."
|
||||
|
||||
if bash deploy.sh balancer; then
|
||||
echo "✅ Balancer service deployed"
|
||||
echo "BALANCER_DEPLOYED=true" >> $GITHUB_ENV
|
||||
|
||||
sleep 3
|
||||
if systemctl is-active --quiet "$BALANCER_SERVICE"; then
|
||||
echo "✅ Balancer service is running"
|
||||
else
|
||||
echo "❌ Balancer service failed to start"
|
||||
exit 1
|
||||
fi
|
||||
else
|
||||
echo "❌ Balancer deployment failed"
|
||||
echo "BALANCER_DEPLOYED=false" >> $GITHUB_ENV
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
# ШАГ 10: Деплой админки
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
- name: 🔧 Deploy Admin Service
|
||||
if: env.DEPLOY_ADMIN == 'true' && env.SKIP_DEPLOY == 'false'
|
||||
id: deploy_admin
|
||||
run: |
|
||||
cd "$REPO_DIR"
|
||||
echo "🔧 Deploying admin service..."
|
||||
|
||||
if bash deploy.sh admin swagger; then
|
||||
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 systemctl is-active --quiet "$ADMIN_SERVICE"; then
|
||||
echo "✅ Admin service is running"
|
||||
else
|
||||
echo "❌ Admin service failed to start"
|
||||
if ! sudo /usr/bin/systemctl is-active --quiet "$ADMIN_SERVICE"; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -f "$REPO_DIR/service/rest_admin_service/docs/swagger.json" ]; then
|
||||
echo "✅ Swagger documentation generated"
|
||||
fi
|
||||
else
|
||||
echo "❌ Admin deployment failed"
|
||||
echo "ADMIN_DEPLOYED=false" >> $GITHUB_ENV
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
# ШАГ 11: Rollback при ошибке
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
- name: 📞 Deploy Telephony Service
|
||||
if: env.DEPLOY_TELEPHONY == 'true' && env.SKIP_DEPLOY == 'false'
|
||||
id: deploy_telephony
|
||||
run: |
|
||||
echo "📞 Deploying telephony service..."
|
||||
if sudo /usr/bin/bash "$REPO_DIR/deploy.sh" telephony; then
|
||||
echo "✅ Telephony service deployed"
|
||||
echo "TELEPHONY_DEPLOYED=true" >> $GITHUB_ENV
|
||||
sleep 3
|
||||
if sudo /usr/bin/systemctl is-active --quiet "$TELEPHONY_SERVICE"; then
|
||||
echo "✅ Telephony service is running"
|
||||
else
|
||||
echo "❌ Telephony service failed to start"
|
||||
sudo /usr/bin/journalctl -u "$TELEPHONY_SERVICE" -n 30 --no-pager
|
||||
exit 1
|
||||
fi
|
||||
else
|
||||
echo "❌ Telephony deployment failed"
|
||||
echo "TELEPHONY_DEPLOYED=false" >> $GITHUB_ENV
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: ⏮️ Rollback on Failure
|
||||
if: failure()
|
||||
run: |
|
||||
|
|
@ -335,12 +253,10 @@ jobs:
|
|||
echo "⏮️ Starting rollback..."
|
||||
echo "════════════════════════════════════════"
|
||||
|
||||
# Функция для rollback сервиса
|
||||
rollback_service() {
|
||||
local service=$1
|
||||
local backup_var="${service^^}_BACKUP"
|
||||
backup_var=$(echo "$backup_var" | tr '-' '_')
|
||||
local backup_file="${!backup_var}"
|
||||
local var_name=$(echo "${service}" | tr '[:lower:]' '[:upper:]' | tr '-' '_')_BACKUP
|
||||
local backup_file="${!var_name}"
|
||||
|
||||
if [ -n "$backup_file" ] && [ -f "$backup_file" ]; then
|
||||
echo "⏮️ Rolling back $service..."
|
||||
|
|
@ -348,160 +264,87 @@ jobs:
|
|||
sudo chmod +x "/usr/local/bin/$service"
|
||||
sudo systemctl restart "$service"
|
||||
sleep 2
|
||||
|
||||
if systemctl is-active --quiet "$service"; then
|
||||
echo "✅ $service rolled back successfully"
|
||||
else
|
||||
echo "❌ $service rollback failed"
|
||||
fi
|
||||
else
|
||||
echo "⚠️ No backup available for $service"
|
||||
fi
|
||||
}
|
||||
|
||||
# Rollback всех задеплоенных сервисов
|
||||
if [ "$DEPLOY_TELEGRAM" = "true" ]; then
|
||||
rollback_service "$TELEGRAM_SERVICE"
|
||||
fi
|
||||
if [ "$DEPLOY_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_BALANCER" = "true" ]; then
|
||||
rollback_service "$BALANCER_SERVICE"
|
||||
fi
|
||||
|
||||
if [ "$DEPLOY_ADMIN" = "true" ]; then
|
||||
rollback_service "$ADMIN_SERVICE"
|
||||
fi
|
||||
|
||||
echo "════════════════════════════════════════"
|
||||
echo "✅ Rollback completed"
|
||||
echo "════════════════════════════════════════"
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
# ШАГ 12: Финальная верификация
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
- name: ✅ Verify Services
|
||||
if: env.SKIP_DEPLOY == 'false' && success()
|
||||
run: |
|
||||
echo "🔍 Verifying services..."
|
||||
echo ""
|
||||
|
||||
ALL_OK=true
|
||||
|
||||
verify_service() {
|
||||
local service=$1
|
||||
local should_deploy=$2
|
||||
|
||||
if [ "$should_deploy" = "true" ]; then
|
||||
if systemctl is-active --quiet "$service"; then
|
||||
UPTIME=$(systemctl show "$service" --property=ActiveEnterTimestamp --value)
|
||||
echo "✅ $service: running (since $UPTIME)"
|
||||
if sudo systemctl is-active --quiet "$service"; then
|
||||
echo "✅ $service: running"
|
||||
else
|
||||
echo "❌ $service: NOT RUNNING"
|
||||
ALL_OK=false
|
||||
fi
|
||||
else
|
||||
echo "⏭️ $service: skipped"
|
||||
fi
|
||||
}
|
||||
|
||||
verify_service "$MIGRATIONS_SERVICE" "$DEPLOY_MIGRATIONS"
|
||||
verify_service "$TELEGRAM_SERVICE" "$DEPLOY_TELEGRAM"
|
||||
verify_service "$BALANCER_SERVICE" "$DEPLOY_BALANCER"
|
||||
verify_service "$ADMIN_SERVICE" "$DEPLOY_ADMIN"
|
||||
verify_service "$TELEPHONY_SERVICE" "$DEPLOY_TELEPHONY"
|
||||
|
||||
echo ""
|
||||
if [ "$ALL_OK" = "true" ]; then
|
||||
echo "✅ All services verified successfully"
|
||||
else
|
||||
echo "❌ Some services are not running"
|
||||
exit 1
|
||||
fi
|
||||
if [ "$ALL_OK" != "true" ]; then exit 1; fi
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
# ШАГ 13: Уведомление об успехе
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
- name: 📢 Notify Success
|
||||
if: success()
|
||||
run: |
|
||||
echo "════════════════════════════════════════"
|
||||
echo "✅ Deployment completed successfully!"
|
||||
echo "════════════════════════════════════════"
|
||||
|
||||
if [ -n "${{ secrets.TELEGRAM_BOT_TOKEN }}" ] && [ -n "${{ secrets.TELEGRAM_CHAT_ID }}" ]; then
|
||||
MESSAGE="✅ <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+="🗄️ Migrations: applied%0A"
|
||||
fi
|
||||
if [ "$DEPLOY_TELEGRAM" = "true" ]; then
|
||||
MESSAGE+="🤖 Telegram: deployed%0A"
|
||||
fi
|
||||
if [ "$DEPLOY_BALANCER" = "true" ]; then
|
||||
MESSAGE+="⚖️ Balancer: deployed%0A"
|
||||
fi
|
||||
if [ "$DEPLOY_ADMIN" = "true" ]; then
|
||||
MESSAGE+="🔧 Admin: deployed%0A"
|
||||
fi
|
||||
if [ "$DEPLOY_MIGRATIONS" = "true" ]; then MESSAGE+="🗄️ System (Migrations): deployed%0A"; fi
|
||||
if [ "$DEPLOY_TELEGRAM" = "true" ]; then MESSAGE+="🤖 Telegram: deployed%0A"; fi
|
||||
if [ "$DEPLOY_ADMIN" = "true" ]; then MESSAGE+="🔧 Admin: deployed%0A"; fi
|
||||
if [ "$DEPLOY_TELEPHONY" = "true" ]; then MESSAGE+="📞 Telephony: deployed%0A"; fi
|
||||
|
||||
MESSAGE+="%0A⏰ $(date '+%Y-%m-%d %H:%M:%S')"
|
||||
|
||||
curl -s -X POST "https://api.telegram.org/bot${{ secrets.TELEGRAM_BOT_TOKEN }}/sendMessage" \
|
||||
-d "chat_id=${{ secrets.TELEGRAM_CHAT_ID }}" \
|
||||
-d "parse_mode=HTML" \
|
||||
-d "text=$MESSAGE" || echo "⚠️ Telegram notification failed"
|
||||
-d "chat_id=${{ secrets.TELEGRAM_CHAT_ID }}" -d "parse_mode=HTML" -d "text=$MESSAGE"
|
||||
fi
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
# ШАГ 14: Уведомление об ошибке
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
- name: 🚨 Notify Failure
|
||||
if: failure()
|
||||
run: |
|
||||
echo "════════════════════════════════════════"
|
||||
echo "❌ Deployment failed!"
|
||||
echo "════════════════════════════════════════"
|
||||
|
||||
# Показываем логи сервисов
|
||||
for service in "$TELEGRAM_SERVICE" "$BALANCER_SERVICE" "$ADMIN_SERVICE"; do
|
||||
echo ""
|
||||
echo "📜 $service logs (last 20 lines):"
|
||||
for service in "$MIGRATIONS_SERVICE" "$TELEGRAM_SERVICE" "$ADMIN_SERVICE" "$TELEPHONY_SERVICE"; do
|
||||
echo "📜 $service logs:"
|
||||
sudo journalctl -u "$service" -n 20 --no-pager || true
|
||||
done
|
||||
|
||||
if [ -n "${{ secrets.TELEGRAM_BOT_TOKEN }}" ] && [ -n "${{ secrets.TELEGRAM_CHAT_ID }}" ]; then
|
||||
MESSAGE="❌ <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" || echo "⚠️ Telegram notification failed"
|
||||
-d "chat_id=${{ secrets.TELEGRAM_CHAT_ID }}" -d "parse_mode=HTML" -d "text=$MESSAGE"
|
||||
fi
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
# ШАГ 15: Итоговая сводка
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
- name: 📊 Deployment Summary
|
||||
if: always()
|
||||
run: |
|
||||
echo "════════════════════════════════════════"
|
||||
echo "📊 DEPLOYMENT SUMMARY"
|
||||
echo "════════════════════════════════════════"
|
||||
echo "Status: ${{ job.status }}"
|
||||
echo "Branch: ${{ github.ref }}"
|
||||
echo "Commit: ${{ github.sha }}"
|
||||
echo "Author: ${{ github.actor }}"
|
||||
echo "Duration: $SECONDS seconds"
|
||||
echo "────────────────────────────────────────"
|
||||
echo "Migrations: ${DEPLOY_MIGRATIONS:-false}"
|
||||
echo "Telegram bot: ${DEPLOY_TELEGRAM:-false}"
|
||||
echo "Balancer: ${DEPLOY_BALANCER:-false}"
|
||||
echo "Admin: ${DEPLOY_ADMIN:-false}"
|
||||
echo "Skip deploy: ${SKIP_DEPLOY:-false}"
|
||||
echo "System (Migrations): ${DEPLOY_MIGRATIONS:-false}"
|
||||
echo "Telegram bot: ${DEPLOY_TELEGRAM:-false}"
|
||||
echo "Admin: ${DEPLOY_ADMIN:-false}"
|
||||
echo "Telephony: ${DEPLOY_TELEPHONY:-false}"
|
||||
echo "════════════════════════════════════════"
|
||||
|
|
@ -655,4 +655,4 @@ golangci-lint run ./...
|
|||
|
||||
<div align="center">
|
||||
<sub>Разработано для внутреннего использования · RuspetPortal</sub>
|
||||
</div>
|
||||
</div># Test deploy
|
||||
|
|
|
|||
|
|
@ -0,0 +1,31 @@
|
|||
import os
|
||||
|
||||
def generate_codebase(root_dir, output_file):
|
||||
# Папки, которые мы игнорируем
|
||||
ignore_dirs = {'.git', 'vendor', '__pycache__', 'node_modules', '.idea', '.vscode'}
|
||||
# Расширения файлов, которые нам не нужны (бинарники и контрольные суммы)
|
||||
ignore_exts = {'.pyc', '.sum', '.exe', '.dll', '.so', '.pdf', '.png', '.jpg'}
|
||||
|
||||
with open(output_file, 'w', encoding='utf-8') as outfile:
|
||||
for root, dirs, files in os.walk(root_dir):
|
||||
# Исключаем игнорируемые директории, модифицируя список dirs на месте
|
||||
dirs[:] = [d for d in dirs if d not in ignore_dirs]
|
||||
|
||||
for file in files:
|
||||
# Пропускаем сам выходной файл, этот скрипт и файлы с ненужными расширениями
|
||||
if file == output_file or file == "code2text.py" or any(file.endswith(ext) for ext in ignore_exts):
|
||||
continue
|
||||
|
||||
filepath = os.path.join(root, file)
|
||||
try:
|
||||
with open(filepath, 'r', encoding='utf-8') as infile:
|
||||
outfile.write(f"\n\n=== ФАЙЛ: {filepath} ===\n")
|
||||
outfile.write(infile.read())
|
||||
except Exception as e:
|
||||
# Если файл нельзя прочитать как текст (например, это картинка без расширения), просто запишем ошибку и пойдем дальше
|
||||
outfile.write(f"\n\n=== ПРОПУЩЕН БИНАРНЫЙ ФАЙЛ ИЛИ ОШИБКА ЧТЕНИЯ: {filepath} ===\n")
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Меняем '.' на './service/telegram_service' (или как у вас называется эта папка)
|
||||
generate_codebase('./service/telegram_service', 'telegram_codebase.txt')
|
||||
print("Готово! Код собран в файл telegram_codebase.txt")
|
||||
|
|
@ -1,7 +1,5 @@
|
|||
package configcore
|
||||
|
||||
import "net/url"
|
||||
|
||||
// RedisConfig конфигурация Redis
|
||||
type RedisConfig struct {
|
||||
Host string `yaml:"host" env-required:"true"`
|
||||
|
|
@ -22,12 +20,8 @@ type DatabaseConfig struct {
|
|||
|
||||
// TelegramConfig конфигурация Telegram
|
||||
type TelegramConfig struct {
|
||||
BotToken string `yaml:"bot_token"`
|
||||
WebAppUrl string `yaml:"web_app_url"`
|
||||
ProxyURL string `yaml:"proxy_url"`
|
||||
ProxyUsername string `yaml:"proxy_username"`
|
||||
ProxyPassword string `yaml:"proxy_password"`
|
||||
ParsedProxy *url.URL // кэшированный распарсенный прокси
|
||||
BotToken string `yaml:"bot_token"`
|
||||
WebAppUrl string `yaml:"web_app_url"`
|
||||
}
|
||||
|
||||
// ServiceConfig конфигурация сервиса
|
||||
|
|
@ -81,7 +75,7 @@ type GrpcServiceConfig struct {
|
|||
}
|
||||
|
||||
type Server struct {
|
||||
RESTBaseService RestServiceConfig `yaml:"rest_balancer_service"`
|
||||
RESTBaseService RestServiceConfig `yaml:"rest_base_service"`
|
||||
RESTAdminService RestServiceConfig `yaml:"rest_admin_service"`
|
||||
Telegram GrpcServiceConfig `yaml:"telegram_service"`
|
||||
}
|
||||
|
|
@ -114,8 +108,8 @@ type SecretsConfig struct {
|
|||
AuthJWT AuthJWTConfig `yaml:"auth_jwt"`
|
||||
ApiPublicUser string `yaml:"access_code_user"`
|
||||
ApiPrivateUser string
|
||||
ApiPublicAdmin string `yaml:"access_code_admin"`
|
||||
ApiPrivateAdmin string
|
||||
ApiPublicAdmin string `yaml:"api_public_admin"`
|
||||
ApiPrivateAdmin string `yaml:"api_private_admin"`
|
||||
ApiPublicBase string `yaml:"api_public_base"`
|
||||
ApiPrivateBase string `yaml:"api_private_base"`
|
||||
}
|
||||
|
|
|
|||
|
|
@ -80,6 +80,7 @@ func copyConfigFields(options *ConfigLoadOptions, source, target *Config) {
|
|||
}
|
||||
if options.Secrets.AdminAccessCode {
|
||||
target.Secrets.ApiPublicAdmin = source.Secrets.ApiPublicAdmin
|
||||
target.Secrets.ApiPrivateAdmin = source.Secrets.ApiPrivateAdmin
|
||||
}
|
||||
if options.Secrets.UserAccessCode {
|
||||
target.Secrets.ApiPublicUser = source.Secrets.ApiPublicUser
|
||||
|
|
|
|||
|
|
@ -34,6 +34,15 @@ type ModuleDB struct {
|
|||
ApprovalAdditionalObserver *dbcore.ApprovalAdditionalObserverDB
|
||||
ApprovalTopicExecutor *dbcore.ApprovalTopicExecutorDB
|
||||
Admin *dbcore.AdminDB
|
||||
Notification *dbcore.NotificationDB
|
||||
DirectorNotifications *dbcore.DirectorNotificationDB
|
||||
ApprovalTaskTransfer *dbcore.ApprovalTaskTransferDB
|
||||
ApprovalRevocation *dbcore.ApprovalRevocationDB
|
||||
ApprovalFlowNode *dbcore.ApprovalFlowNodeDB
|
||||
AdminActionLogs *dbcore.AdminActionLogDB
|
||||
SMSLog *dbcore.SmsLogDB
|
||||
MonthlyOrders *dbcore.MonthlyOrderDB
|
||||
TaskDelegation *dbcore.TaskDelegationDB
|
||||
}
|
||||
|
||||
func NewModuleDB(
|
||||
|
|
@ -84,6 +93,15 @@ func initDBModules(modules *ModuleDB, redisClient *redismodule.ModuleRedis) *Mod
|
|||
modules.ApprovalAdditionalObserver = dbcore.NewApprovalAdditionalObserverDB(modules.Pool)
|
||||
modules.ApprovalTopicExecutor = dbcore.NewApprovalTopicExecutorDB(modules.Pool)
|
||||
modules.Admin = dbcore.NewAdminDB(modules.Pool)
|
||||
modules.Notification = dbcore.NewNotificationDB(modules.Pool)
|
||||
modules.DirectorNotifications = dbcore.NewDirectorNotificationDB(modules.Pool)
|
||||
modules.ApprovalTaskTransfer = dbcore.NewApprovalTaskTransferDB(modules.Pool)
|
||||
modules.ApprovalRevocation = dbcore.NewApprovalRevocationDB(modules.Pool)
|
||||
modules.ApprovalFlowNode = dbcore.NewApprovalFlowNodeDB(modules.Pool)
|
||||
modules.AdminActionLogs = dbcore.NewAdminActionLogDB(modules.Pool)
|
||||
modules.SMSLog = dbcore.NewSmsLogDB(modules.Pool)
|
||||
modules.MonthlyOrders = dbcore.NewMonthlyOrderDB(modules.Pool)
|
||||
modules.TaskDelegation = dbcore.NewTaskDelegationDB(modules.Pool)
|
||||
|
||||
return modules
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
package dbmigration
|
||||
|
||||
import (
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
_ "embed"
|
||||
"encoding/csv"
|
||||
"encoding/json"
|
||||
|
|
@ -20,12 +19,6 @@ import (
|
|||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
//go:embed default_data/approval_topic_categories.csv
|
||||
var approvalCategoriesCSV string
|
||||
|
||||
//go:embed default_data/approval_topics.csv
|
||||
var approvalTopicsCSV string
|
||||
|
||||
// identifierRe is compiled once and reused across all sanitizeIdentifier calls.
|
||||
var identifierRe = regexp.MustCompile(`[^a-z0-9_]`)
|
||||
|
||||
|
|
@ -47,10 +40,7 @@ type dataEntry struct {
|
|||
|
||||
// defaultDataEntries defines the ordered list of tables to seed.
|
||||
// Adding a new table only requires appending one entry here.
|
||||
var defaultDataEntries = []dataEntry{
|
||||
{"approval_topic_categories", &typescore.ApprovalTopicCategory{}, approvalCategoriesCSV},
|
||||
{"approval_topics", &typescore.ApprovalTopic{}, approvalTopicsCSV},
|
||||
}
|
||||
var defaultDataEntries []dataEntry
|
||||
|
||||
// DefaultDataSet seeds every table defined in defaultDataEntries.
|
||||
// It attempts all tables and returns a combined error if any fail.
|
||||
|
|
|
|||
|
|
@ -1,29 +0,0 @@
|
|||
id,name,code,description,is_active,created_at,updated_at
|
||||
1,Отгул,timeoff,Отгул,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
2,Отпуск,vacation,Отпуск,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
3,Больничный,sickleave,Больничный,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
4,Внебюджетные расходы,non_budget_expenses,Внебюджетные расходы с выбором филиала и типа,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
5,Внебюджетные расходы ПЭТ Лайн,non_budget_expenses_pet_line,Внебюджетные расходы ПЭТ Лайн с выбором филиала и типа,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
6,Возвраты,returns,Возвраты товаров с выбором типа и региона,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
7,Изменение клиента в ОКБ и 1С,client_changes,Изменение данных клиента в системах,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
8,Заказ товаров,goods_order,Заказ товаров на месяц или дополнительно,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
9,Отгрузки на СОХ,shipments_soh,Отгрузки на СОХ реальные или для лимита,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
10,Паспорт сделки,transaction_passport,Паспорт сделки по регионам,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
11,Ставки логистика,rates_logistics,Ставки логистики разово или надолго,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
12,Поступления по приходным документам,receipts,Поступления по филиалам,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
13,Доставка клиентам/на склад,delivery_clients,Доставка с выбором согласующего,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
14,В. Отгрузки,v_shipments,Внутренние отгрузки,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
15,Менеджерские расходы,manager_expenses,Расходы менеджеров,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
16,Отгрузки,shipments,Обычные отгрузки,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
17,Нестандартные условия договора поставки,nonstandard_contract,Нестандартные условия договоров,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
18,Вакансии,vacancies,Согласование вакансий,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
19,Ставки доставки АП,delivery_rates_ap,Ставки доставки Альфапэт,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
20,Утверждение фрилансеров,freelancers_approval,Согласование фрилансеров,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
21,Выход в нерабочий день,non_working_day,Выход в выходной или праздничный день,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
22,Предложения и пожелания,suggestions,Предложения по улучшению работы,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
23,Долгосрочные условия ОТК,otk_conditions,Долгосрочные условия отсрочки,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
24,Остаток в кассах,cash_balance,Остатки в кассах с выбором согласующего,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
25,Продажи по клиенту,client_sales,Информация о продажах по клиенту,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
26,Проведенные расходы по менеджеру,manager_expenses_report,Отчет о расходах менеджера,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
27,Заведение новых клиентов,new_clients,Добавление новых клиентов в базу,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
28,Утверждение оплат безнал,payments_cashless,Согласование безналичных оплат,true,2026-04-23 10:00:00,2026-04-23 10:00:00
|
||||
|
|
|
@ -1,148 +0,0 @@
|
|||
id,category_id,name,code,duration_type,time_type,payment_type,template,allows_file,is_active,created_at,updated_at,allow_approver_selection,first_approver_role_code,allow_observer_selection,approval_mode,require_approver_comment,requires_file,require_observer_selection,instructions
|
||||
70,15,Менеджерские расходы: Крым,manager_expenses_crimea,,,,Оплата платной дороги Краснодар-Темрюк-Краснодар в сумме 1420 руб. (клиент РУСМолоко) (расход Макаренко),false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
590,15,Менеджерские расходы: Краснодар,manager_expenses_krasnodar,,,,,false,true,2026-06-03 08:55:52.439479,2026-06-03 08:55:52.439479,false,,false,sequential,false,false,false,
|
||||
49,7,Сменить менеджера Битрикс Краснодар,client_changes_change_manager_bitrix_krasnodar,,,,Опишите смену менеджера в Битрикс (Краснодар),false,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
586,9,Отгрузка на СОХ — Крым (реальная),shipments_soh_crimea_real,,,,Опишите отгрузку,false,true,2026-06-02 07:10:13.844873,2026-06-02 07:10:13.844873,false,,false,sequential,true,false,false,
|
||||
4,1,Отгул — диапазон частично,timeoff_date_range_partial_own_expense,date_range,partial,own_expense,22.02.2022 - 25.02.2022 с 16:00 по 18:00,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
65,11,Ставки Логистика: Надолго,rates_logistics_long_term,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
592,17,Нестандартные условия поставки: Беларусь,nonstandard_contract_belarus,,,,,true,true,2026-06-03 09:20:00.662572,2026-06-03 09:20:00.662572,false,,false,sequential,true,false,false,
|
||||
591,17,Нестандартные условия поставки: Краснодар,nonstandard_contract_krasnodar,,,,,true,true,2026-06-03 09:20:00.662572,2026-06-03 09:20:00.662572,false,,false,sequential,true,false,false,
|
||||
594,23,ОТК: Краснодар,otk_conditions_krasnodar,,,,,false,true,2026-06-03 09:29:10.377976,2026-06-03 09:29:10.377976,false,,false,sequential,false,false,false,
|
||||
595,23,ОТК: Беларусь,otk_conditions_belarus,,,,,false,true,2026-06-03 09:29:10.377976,2026-06-03 09:29:10.377976,false,,false,sequential,false,false,false,
|
||||
5,1,Отгул — диапазон весь день в счёт отпуска,timeoff_date_range_full_day_vacation_account,date_range,full_day,vacation_account,22.02.2022 - 25.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
6,1,Отгул — диапазон весь день за свой счёт,timeoff_date_range_full_day_own_expense,date_range,full_day,own_expense,22.02.2022 - 25.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
16,3,Больничный — несколько дней официальный,sickleave_multi_day_full_day_official,multi_day,full_day,official,"22.02.2022, 24.02.2022, 26.02.2022",true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
17,3,Больничный — несколько дней в счёт отпуска,sickleave_multi_day_full_day_vacation_account,multi_day,full_day,vacation_account,"22.02.2022, 24.02.2022, 26.02.2022",false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
589,9,Отгрузка на СОХ — Краснодар (лимит),shipments_soh_krasnodar_limit,,,,Опишите отгрузку,false,true,2026-06-02 07:10:13.915061,2026-06-02 07:10:13.915061,false,,false,sequential,true,false,false,
|
||||
587,9,Отгрузка на СОХ — Крым (лимит),shipments_soh_crimea_limit,,,,Опишите отгрузку,false,true,2026-06-02 07:10:13.868383,2026-06-02 07:10:13.868383,false,,false,sequential,true,false,false,
|
||||
21,3,Больничный — диапазон за свой счёт,sickleave_date_range_full_day_own_expense,date_range,full_day,own_expense,22.02.2022 - 25.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
24,3,Больничный — один день за свой счёт,sickleave_single_day_full_day_own_expense,single_day,full_day,own_expense,22.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
588,9,Отгрузка на СОХ — Краснодар (реальная),shipments_soh_krasnodar_real,,,,Опишите отгрузку,false,true,2026-06-02 07:10:13.892797,2026-06-02 07:10:13.892797,false,,false,sequential,true,false,false,
|
||||
18,3,Больничный — несколько дней за свой счёт,sickleave_multi_day_full_day_own_expense,multi_day,full_day,own_expense,"22.02.2022, 24.02.2022, 26.02.2022",false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
59,9,Отгрузки на СОХ реальная,shipments_soh_real,,,,Опишите реальную отгрузку на СОХ,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
43,7,Поменять название Битрикс Краснодар,client_changes_rename_bitrix_krasnodar,,,,Опишите изменение названия клиента в Битрикс (Краснодар),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
27,4,Внебюджетные расходы: Ф2 ТМЦ,non_budget_expenses_f2_tmc,,,,Прошу согласовать оплату за зарядку для телефона (руководителю отдела логистики) в сумме 293 руб.,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
60,9,Отгрузки на СОХ для лимита,shipments_soh_limit,,,,Опишите отгрузку для лимита на СОХ,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
19,3,Больничный — диапазон официальный,sickleave_date_range_full_day_official,date_range,full_day,official,22.02.2022 - 25.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
22,3,Больничный — один день официальный,sickleave_single_day_full_day_official,single_day,full_day,official,22.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
82,27,Заведение новых клиентов,new_clients,,,,,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
83,28,Утверждение оплат безнал,payments_cashless,,,,,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
1,1,Отгул — несколько дней частично,timeoff_multi_day_partial_own_expense,multi_day,partial,own_expense,"22.02.2022 с 10:00 по 14:00, 24.02.2022 с 09:00 по 12:00",false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
2,1,Отгул — несколько дней весь день в счёт отпуска,timeoff_multi_day_full_day_vacation_account,multi_day,full_day,vacation_account,"22.02.2022, 24.02.2022, 26.02.2022",false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
3,1,Отгул — несколько дней весь день за свой счёт,timeoff_multi_day_full_day_own_expense,multi_day,full_day,own_expense,"22.02.2022, 24.02.2022, 26.02.2022",false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
7,1,Отгул — один день частично,timeoff_single_day_partial_own_expense,single_day,partial,own_expense,22.02.2022 с 16:00 по 18:00,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
8,1,Отгул — один день весь день в счёт отпуска,timeoff_single_day_full_day_vacation_account,single_day,full_day,vacation_account,22.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
9,1,Отгул — один день весь день за свой счёт,timeoff_single_day_full_day_own_expense,single_day,full_day,own_expense,22.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
10,2,Отпуск — несколько дней в счёт отпуска,vacation_multi_day_full_day_vacation_account,multi_day,full_day,vacation_account,"22.02.2022, 24.02.2022, 26.02.2022",false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
11,2,Отпуск — несколько дней за свой счёт,vacation_multi_day_full_day_own_expense,multi_day,full_day,own_expense,"22.02.2022, 24.02.2022, 26.02.2022",false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
12,2,Отпуск — диапазон в счёт отпуска,vacation_date_range_full_day_vacation_account,date_range,full_day,vacation_account,22.02.2022 - 25.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
13,2,Отпуск — диапазон за свой счёт,vacation_date_range_full_day_own_expense,date_range,full_day,own_expense,22.02.2022 - 25.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
14,2,Отпуск — один день в счёт отпуска,vacation_single_day_full_day_vacation_account,single_day,full_day,vacation_account,22.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
15,2,Отпуск — один день за свой счёт,vacation_single_day_full_day_own_expense,single_day,full_day,own_expense,22.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
20,3,Больничный — диапазон в счёт отпуска,sickleave_date_range_full_day_vacation_account,date_range,full_day,vacation_account,22.02.2022 - 25.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
23,3,Больничный — один день в счёт отпуска,sickleave_single_day_full_day_vacation_account,single_day,full_day,vacation_account,22.02.2022,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
61,10,ПС: Краснодар,transaction_passport_krasnodar,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,true,false,
|
||||
580,8,Заказ на месяц — Крым,goods_order_monthly_crimea,,,,"Опишите Скилур заказ:
|
||||
22 гр.38 мм бесцветная (10176) ЕПМ - 5кор.
|
||||
ф1, на склад Гвардейское, 2я декада.",true,true,2026-05-27 07:32:42.878447,2026-05-27 07:32:42.878447,false,,false,sequential,true,true,false,
|
||||
58,8,Заказ товаров дополнительный,goods_order_additional,,,,Опишите дополнительный заказ,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,true,false,
|
||||
582,8,Дополнительный заказ — Крым,goods_order_additional_crimea,,,,"Опишите Скилур заказ:
|
||||
22 гр.38 мм бесцветная (10176) ЕПМ - 5кор.
|
||||
ф1, на склад Гвардейское, 2я декада.",true,true,2026-05-27 07:32:42.959177,2026-05-27 07:32:42.959177,false,,false,sequential,true,true,false,
|
||||
57,8,Заказ товаров на месяц,goods_order_monthly,,,,Опишите заказ на месяц,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,true,false,
|
||||
597,4,Внебюджетные расходы: Ф1 ТМЦ (без ПП),non_budget_expenses_f1_tmc_pp_no,,,,,false,true,2026-06-10 09:06:59.648658,2026-06-10 09:06:59.648658,false,,false,sequential,false,false,false,
|
||||
599,4,Внебюджетные расходы: Ф1 Расход (без ПП),non_budget_expenses_f1_expense_pp_no,,,,,false,true,2026-06-10 09:06:59.684144,2026-06-10 09:06:59.684144,false,,false,sequential,false,false,false,
|
||||
42,7,Поменять название ОКБ Краснодар,client_changes_rename_okb_krasnodar,,,,Опишите изменение названия клиента в ОКБ (Краснодар),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
602,28,Оплата безнал — Разное (нужна ПП),payments_cashless_misc_pp_yes,,,,,true,true,2026-06-10 09:06:59.730960,2026-06-10 09:06:59.730960,false,,false,sequential,false,true,false,
|
||||
603,28,Оплата безнал — Разное (без ПП),payments_cashless_misc_pp_no,,,,,true,true,2026-06-10 09:06:59.746484,2026-06-10 09:06:59.746484,false,,false,sequential,false,true,false,
|
||||
600,28,Оплата безнал — Товар (нужна ПП),payments_cashless_goods_pp_yes,,,,,true,true,2026-06-10 09:06:59.699401,2026-06-10 09:06:59.699401,false,,false,sequential,false,true,false,
|
||||
601,28,Оплата безнал — Товар (без ПП),payments_cashless_goods_pp_no,,,,,true,true,2026-06-10 09:06:59.716456,2026-06-10 09:06:59.716456,false,,false,sequential,false,true,false,
|
||||
598,4,Внебюджетные расходы: Ф1 Расход (нужна ПП),non_budget_expenses_f1_expense_pp_yes,,,,,true,true,2026-06-10 09:06:59.666345,2026-06-10 09:06:59.666345,false,,false,sequential,false,true,false,
|
||||
596,4,Внебюджетные расходы: Ф1 ТМЦ (нужна ПП),non_budget_expenses_f1_tmc_pp_yes,,,,,true,true,2026-06-10 09:06:59.628993,2026-06-10 09:06:59.628993,false,,false,sequential,false,true,false,
|
||||
37,6,Самостоятельная продажа Крым,returns_self_sale_crimea,,,,"ТД Крымэколайф
|
||||
40,5 гр.1881 бесцветная (7808) ПФ - 52 короба
|
||||
Реализация товаров и услуг ЧП000003123 от 4.08.25
|
||||
Ф1
|
||||
|
||||
Причина: для сокращения долга клиента
|
||||
|
||||
Действия: продам ООО Нива",false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
34,6,Возврат поставщику Краснодар,returns_supplier_krasnodar,,,,,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
38,6,Самостоятельная продажа Краснодар,returns_self_sale_krasnodar,,,,,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
33,6,Возврат поставщику Крым,returns_supplier_crimea,,,,"Бишули
|
||||
28 гр.1881 бесцветная (9504) ПФ - 2 короба
|
||||
Реализация товаров и услуг ЧП000001326 от 20.04.2026 8:00:01
|
||||
Ф1
|
||||
|
||||
Причина: Короб приехал с завода и сильно порвался в дороге, клиент не может на свою продукцию использовать его",false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
62,10,ПС: Крым,transaction_passport_crimea,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,true,false,
|
||||
73,18,Вакансии,vacancies,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,supervisor,false,sequential,false,false,false,
|
||||
80,25,Продажи по клиенту,client_sales,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,manager,false,sequential,false,true,false,
|
||||
78,23,ОТК: Крым,otk_conditions_crimea,,,,Опишите долгосрочные условия ОТК,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
605,7,Внести нового клиента - Краснодар,client_changes_new_client_krasnodar,,,,,false,true,2026-06-11 04:33:53.266045,2026-06-11 04:33:53.266045,false,,false,sequential,false,false,false,
|
||||
607,7,Внести нового клиента - Крым,client_changes_new_client_crimea,,,,,false,true,2026-06-11 04:33:53.266045,2026-06-11 04:33:53.266045,false,,false,sequential,false,false,false,
|
||||
609,7,Поменять название - Краснодар,client_changes_rename_krasnodar,,,,,false,true,2026-06-11 04:33:53.266045,2026-06-11 04:33:53.266045,false,,false,sequential,false,false,false,
|
||||
611,7,Поменять название - Крым,client_changes_rename_crimea,,,,,false,true,2026-06-11 04:33:53.266045,2026-06-11 04:33:53.266045,false,,false,sequential,false,false,false,
|
||||
613,7,Сменить менеджера - Краснодар,client_changes_change_manager_krasnodar,,,,,false,true,2026-06-11 04:33:53.266045,2026-06-11 04:33:53.266045,false,,false,sequential,false,false,false,
|
||||
615,7,Сменить менеджера - Крым,client_changes_change_manager_crimea,,,,,false,true,2026-06-11 04:33:53.266045,2026-06-11 04:33:53.266045,false,,false,sequential,false,false,false,
|
||||
53,7,Внести нового клиента 1С Крым,client_changes_new_client_1c_crimea,,,,Опишите данные нового клиента для 1С (Крым),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
50,7,Сменить менеджера 1С Краснодар,client_changes_change_manager_1c_krasnodar,,,,Опишите смену менеджера в 1С (Краснодар),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
72,17,Нестандартные условия поставки: Крым,nonstandard_contract_crimea,,,,Прошу согласовать отсрочку 21 день для клиента ООО Роса (другое юрлицо ООО Аквариум) (менеджер Петров),true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,true,false,false,
|
||||
36,6,Продажа другим менеджером Краснодар,returns_other_manager_krasnodar,,,,,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,manager,false,sequential,false,false,false,
|
||||
64,11,Ставки Логистика: Разово,rates_logistics_once,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
67,12,Приходные документы Ф2,receipts_f2,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,true,true,false,
|
||||
66,12,Приходные документы Ф1,receipts_f1,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,true,true,false,
|
||||
51,7,Внести нового клиента ОКБ Крым,client_changes_new_client_okb_crimea,,,,Опишите данные нового клиента для ОКБ (Крым),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
54,7,Внести нового клиента ОКБ Краснодар,client_changes_new_client_okb_krasnodar,,,,Опишите данные нового клиента для ОКБ (Краснодар),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
47,7,Сменить менеджера 1С Крым,client_changes_change_manager_1c_crimea,,,,Опишите смену менеджера в 1С (Крым),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
41,7,Поменять название 1С Крым,client_changes_rename_1c_crimea,,,,Опишите изменение названия клиента в 1С (Крым),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
29,5,ПЭТ Лайн Ф1 ТМЦ,non_budget_expenses_pet_line_f1_tmc,,,,,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
31,5,ПЭТ Лайн Ф2 ТМЦ,non_budget_expenses_pet_line_f2_tmc,,,,,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
26,4,Внебюджетные расходы: Ф1 Расход,non_budget_expenses_f1_expense,,,,"Прошу оплатить счет ИП Гулякина на сумму 3180,00 руб (без НДС) за продление 1С-Отчетность на 1 год",true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
28,4,Внебюджетные расходы: Ф2 Расход,non_budget_expenses_f2_expense,,,,Прошу согласовать 1000 руб на покупку контактов резюме грузчиков на платформе Авито,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
75,20,Утверждение фрилансеров,freelancers_approval,,,,Одного помощника на выгрузку полной фуры с крышкой ручкой с КТ на 23.04.2026 на весь день,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
35,6,Продажа другим менеджером Крым,returns_other_manager_crimea,,,,"Бишули
|
||||
61 гр.38 мм бесцветная (3888) ЕП - 11 коробов
|
||||
Реализация товаров и услуг ЧП000000584 от 05.03.2026 8:00:01
|
||||
Ф1
|
||||
|
||||
Причина: Часть заказа отвалилась, будут переходить на эту позицию не раньше, чем через 3 мес
|
||||
|
||||
Продаст Чекальский на Бойко",false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,manager,false,sequential,false,false,false,
|
||||
77,22,Предложения и пожелания,suggestions,,,,,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
63,10,ПС: Беларусь,transaction_passport_belarus,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,true,false,
|
||||
74,19,Ставки доставки АП,delivery_rates_ap,,,,Прошу согласовать доставку 14 кор преформы клиенту Олег-Выдув-Сочи за 34 000 руб.,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
71,16,Отгрузки,shipments,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,true,sequential,false,true,true,"Если не входит в рамки согласованного лимита, добавь руководителя соответствующего филиала к согласованию через кнопку 'Добавить согласующего'"
|
||||
584,28,Оплата безнал — Товар,payments_cashless_goods,,,,Опишите оплату,false,true,2026-06-02 06:14:34.876867,2026-06-02 06:14:34.876867,false,,false,sequential,false,false,false,
|
||||
585,28,Оплата безнал — Разное,payments_cashless_misc,,,,Опишите оплату,false,true,2026-06-02 06:14:34.926542,2026-06-02 06:14:34.926542,false,,false,sequential,false,false,false,
|
||||
583,8,Дополнительный заказ — Краснодар,goods_order_additional_krasnodar,,,,"Опишите Скилур заказ:
|
||||
22 гр.38 мм бесцветная (10176) ЕПМ - 5кор.
|
||||
ф1, на склад Гвардейское, 2я декада.",true,true,2026-05-27 07:32:42.987951,2026-05-27 07:32:42.987951,false,,false,sequential,true,true,false,
|
||||
581,8,Заказ на месяц — Краснодар,goods_order_monthly_krasnodar,,,,"Скилур заказ:
|
||||
22 гр.38 мм бесцветная (10176) ЕПМ - 5кор.
|
||||
ф1, на склад Гвардейское, 2я декада.",true,true,2026-05-27 07:32:42.929341,2026-05-27 07:32:42.929341,false,,false,sequential,true,true,false,
|
||||
79,24,Остаток в кассах,cash_balance,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,supervisor,false,sequential,false,false,false,
|
||||
55,7,Внести нового клиента Битрикс Краснодар,client_changes_new_client_bitrix_krasnodar,,,,Опишите данные нового клиента для Битрикс (Краснодар),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
25,4,Внебюджетные расходы: Ф1 ТМЦ,non_budget_expenses_f1_tmc,,,,Прошу согласовать и оплатить Счет от ООО Интернет Решения (Озон) за ноутбук и мышь для закупщика в сумме 31 335 руб. С НДС,true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
30,5,ПЭТ Лайн Ф1 Расход,non_budget_expenses_pet_line_f1_expense,,,,,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
76,21,Выход в нерабочий день,non_working_day,,,,Прошу вывести склад для учета c 25.04 по 26.04,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
68,13,Доставка клиентам/на склад,delivery_clients,,,,"Иванов Иван Иванович
|
||||
Тел 89781234567
|
||||
Паспорт 1234 567890
|
||||
ДАФ н862нн46 п/п АА8473|46
|
||||
|
||||
61 бц с ад - 52 кор
|
||||
ЧП000001676
|
||||
|
||||
ЕПР-СтройКрым",true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,manager,false,sequential,false,false,false,
|
||||
32,5,ПЭТ Лайн Ф2 Расход,non_budget_expenses_pet_line_f2_expense,,,,,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
40,7,Поменять название Битрикс Крым,client_changes_rename_bitrix_crimea,,,,Опишите изменение названия клиента в Битрикс (Крым),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
44,7,Поменять название 1С Краснодар,client_changes_rename_1c_krasnodar,,,,Опишите изменение названия клиента в 1С (Краснодар),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
46,7,Сменить менеджера Битрикс Крым,client_changes_change_manager_bitrix_crimea,,,,Опишите смену менеджера в Битрикс (Крым),false,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
56,7,Внести нового клиента 1С Краснодар,client_changes_new_client_1c_krasnodar,,,,Опишите данные нового клиента для 1С (Краснодар),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
52,7,Внести нового клиента Битрикс Крым,client_changes_new_client_bitrix_crimea,,,,Опишите данные нового клиента для Битрикс (Крым),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
45,7,Сменить менеджера ОКБ Крым,client_changes_change_manager_okb_crimea,,,,Опишите смену менеджера в ОКБ (Крым),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
48,7,Сменить менеджера ОКБ Краснодар,client_changes_change_manager_okb_krasnodar,,,,Опишите смену менеджера в ОКБ (Краснодар),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
69,14,В. Отгрузки,v_shipments,,,,ООО Нива на 370 тыс. руб. под 19%,false,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
81,26,Проведенные расходы по менеджеру,manager_expenses_report,,,,,true,true,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,manager,false,sequential,false,false,false,
|
||||
39,7,Поменять название ОКБ Крым,client_changes_rename_okb_crimea,,,,Опишите изменение названия клиента в ОКБ (Крым),true,false,2026-04-23 10:00:00.000000,2026-04-23 10:00:00.000000,false,,false,sequential,false,false,false,
|
||||
|
|
|
@ -38,6 +38,17 @@ func (m *MigrationFunctions) migrateTables() error {
|
|||
tablesmigration.ApprovalAdditionalObserverTableMigrate,
|
||||
tablesmigration.ApprovalTopicExecutorsTableMigrate,
|
||||
tablesmigration.AdminsTableMigrate,
|
||||
|
||||
tablesmigration.NotificationsTableMigrate,
|
||||
tablesmigration.DirectorNotificationSubscriptionsTableMigrate,
|
||||
tablesmigration.ApprovalTaskTransfersTableMigrate,
|
||||
tablesmigration.ApprovalRevocationTablesMigrate,
|
||||
tablesmigration.ApprovalFlowNodesTableMigrate,
|
||||
tablesmigration.AdminActionLogsTableMigrate,
|
||||
|
||||
tablesmigration.SmsLogsTableMigrate,
|
||||
tablesmigration.MonthlyOrdersTablesMigrate,
|
||||
tablesmigration.TaskDelegationsTableMigrate,
|
||||
}
|
||||
|
||||
for _, migrate := range migrations {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,36 @@
|
|||
package tablesmigration
|
||||
|
||||
import (
|
||||
dbcoretablenames "bitrix_balancer_api/core/db/table_names"
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
"gorm.io/gorm"
|
||||
"time"
|
||||
)
|
||||
|
||||
// LocalAdminProvider - локальная структура для миграции
|
||||
type LocalAdminActionProvider typescore.AdminActionLog
|
||||
|
||||
func (LocalAdminActionProvider) TableName() string {
|
||||
return dbcoretablenames.TableNameAdminActionLogs.ToString()
|
||||
}
|
||||
|
||||
// AdminsTableMigrate - миграция таблицы Admins
|
||||
func AdminActionLogsTableMigrate(db *gorm.DB) error {
|
||||
hasTable := db.Migrator().HasTable(&LocalAdminActionProvider{})
|
||||
|
||||
// Выполняем автосоздание таблицы
|
||||
err := db.AutoMigrate(&LocalAdminActionProvider{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !hasTable {
|
||||
time.Sleep(5 * time.Second) // Добавляем задержку
|
||||
|
||||
// Add comments to table and columns
|
||||
db.Exec(`
|
||||
COMMENT ON TABLE admin_action_logs IS 'Таблица для хранения данных о действиях администратора';
|
||||
`)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
@ -36,5 +36,20 @@ func ApprovalsTableMigrate(db *gorm.DB) error {
|
|||
COMMENT ON COLUMN "approvals".updated_at IS 'Дата последнего изменения заявки';
|
||||
`)
|
||||
}
|
||||
|
||||
// 🚀 Индексы: покрывают фильтры GetApprovalsListHandler, JOIN'ы enrichApprovalsBatch и сортировку
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approvals_initiator_id ON approvals (initiator_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approvals_topic_id ON approvals (topic_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approvals_department_id ON approvals (department_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approvals_revoked_by_id ON approvals (revoked_by_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approvals_status ON approvals (status)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approvals_created_at ON approvals (created_at DESC)`)
|
||||
// Композитный индекс под самый частый сценарий: список заявок конкретного статуса, отсортированный по дате
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approvals_status_created_at ON approvals (status, created_at DESC)`)
|
||||
// Под фильтр report по инициатору + период
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approvals_initiator_created_at ON approvals (initiator_id, created_at DESC)`)
|
||||
// Под DeleteTopicHandler / проверку "есть ли заявки по теме"
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approvals_topic_status ON approvals (topic_id, status)`)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,12 +15,10 @@ func ApprovalAdditionalApproverTableMigrate(db *gorm.DB) error {
|
|||
if !hasTable {
|
||||
time.Sleep(5 * time.Second)
|
||||
|
||||
// Foreign key constraints
|
||||
db.Exec(`ALTER TABLE approval_additional_approvers ADD CONSTRAINT fk_approval_additional_approvers_approval_id FOREIGN KEY (approval_id) REFERENCES approvals(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
db.Exec(`ALTER TABLE approval_additional_approvers ADD CONSTRAINT fk_approval_additional_approvers_approver_id FOREIGN KEY (approver_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
db.Exec(`ALTER TABLE approval_additional_approvers ADD CONSTRAINT fk_approval_additional_approvers_added_by_id FOREIGN KEY (added_by_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
|
||||
// Comments
|
||||
execComments(db, `
|
||||
COMMENT ON TABLE "approval_additional_approvers" IS 'Дополнительные согласующие заявки: кто добавлен для согласования конкретной заявки';
|
||||
COMMENT ON COLUMN "approval_additional_approvers".id IS 'Внутренний уникальный идентификатор записи';
|
||||
|
|
@ -34,5 +32,13 @@ func ApprovalAdditionalApproverTableMigrate(db *gorm.DB) error {
|
|||
COMMENT ON COLUMN "approval_additional_approvers".updated_at IS 'Дата и время последнего изменения записи';
|
||||
`)
|
||||
}
|
||||
|
||||
// 🚀 approval_id — джойн при обогащении заявки; approver_id — "мои задачи на согласование";
|
||||
// композит approval_id+status — фильтр pending-согласующих конкретной заявки
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_add_approvers_approval_id ON approval_additional_approvers (approval_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_add_approvers_approver_id ON approval_additional_approvers (approver_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_add_approvers_added_by_id ON approval_additional_approvers (added_by_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_add_approvers_approval_status ON approval_additional_approvers (approval_id, status)`)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,12 +15,10 @@ func ApprovalAdditionalObserverTableMigrate(db *gorm.DB) error {
|
|||
if !hasTable {
|
||||
time.Sleep(5 * time.Second)
|
||||
|
||||
// Foreign key constraints
|
||||
db.Exec(`ALTER TABLE approval_additional_observers ADD CONSTRAINT fk_approval_additional_approvers_approval_id FOREIGN KEY (approval_id) REFERENCES approvals(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
db.Exec(`ALTER TABLE approval_additional_observers ADD CONSTRAINT fk_approval_additional_approvers_observer_id FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
db.Exec(`ALTER TABLE approval_additional_observers ADD CONSTRAINT fk_approval_additional_approvers_added_by_id FOREIGN KEY (added_by_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
|
||||
// Comments
|
||||
execComments(db, `
|
||||
COMMENT ON TABLE "approval_additional_observers" IS 'Дополнительные наблюдатели заявки: кто добавлен для согласования конкретной заявки';
|
||||
COMMENT ON COLUMN "approval_additional_observers".id IS 'Внутренний уникальный идентификатор записи';
|
||||
|
|
@ -30,5 +28,10 @@ func ApprovalAdditionalObserverTableMigrate(db *gorm.DB) error {
|
|||
COMMENT ON COLUMN "approval_additional_observers".created_at IS 'Дата и время создания записи';
|
||||
`)
|
||||
}
|
||||
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_add_observers_approval_id ON approval_additional_observers (approval_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_add_observers_user_id ON approval_additional_observers (user_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_add_observers_added_by_id ON approval_additional_observers (added_by_id)`)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,5 +28,10 @@ func ApprovalCommentsTableMigrate(db *gorm.DB) error {
|
|||
COMMENT ON COLUMN "approval_comments".updated_at IS 'Дата последнего изменения комментария';
|
||||
`)
|
||||
}
|
||||
|
||||
// 🚀 Композит покрывает типичный запрос "комментарии заявки в хронологическом порядке"
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_comments_approval_id_created_at ON approval_comments (approval_id, created_at)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_comments_user_id ON approval_comments (user_id)`)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,12 +15,10 @@ func ApprovalDelegationTableMigrate(db *gorm.DB) error {
|
|||
if !hasTable {
|
||||
time.Sleep(5 * time.Second)
|
||||
|
||||
// Foreign key constraints
|
||||
db.Exec(`ALTER TABLE approval_delegations ADD CONSTRAINT fk_approval_delegations_delegator_id FOREIGN KEY (delegator_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
db.Exec(`ALTER TABLE approval_delegations ADD CONSTRAINT fk_approval_delegations_delegate_id FOREIGN KEY (delegate_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
db.Exec(`ALTER TABLE approval_delegations ADD CONSTRAINT fk_approval_delegations_topic_id FOREIGN KEY (topic_id) REFERENCES approval_topics(id) ON DELETE RESTRICT ON UPDATE CASCADE`)
|
||||
|
||||
// Comments
|
||||
execComments(db, `
|
||||
COMMENT ON TABLE "approval_delegations" IS 'Делегирование прав согласования: кто кому может согласовывать заявки по определённым темам';
|
||||
COMMENT ON COLUMN "approval_delegations".id IS 'Внутренний уникальный идентификатор записи делегирования';
|
||||
|
|
@ -35,5 +33,13 @@ func ApprovalDelegationTableMigrate(db *gorm.DB) error {
|
|||
COMMENT ON COLUMN "approval_delegations".updated_at IS 'Дата и время последнего изменения записи';
|
||||
`)
|
||||
}
|
||||
|
||||
// 🚀 Композит под самый вероятный запрос: "активные делегирования делегата по теме, ещё не истёкшие"
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_delegations_delegator_id ON approval_delegations (delegator_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_delegations_delegate_id ON approval_delegations (delegate_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_delegations_topic_id ON approval_delegations (topic_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_delegations_active_valid_until ON approval_delegations (is_active, valid_until) WHERE is_active = true`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_delegations_delegator_topic_active ON approval_delegations (delegator_id, topic_id) WHERE is_active = true`)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -26,5 +26,9 @@ func ApprovalsFilesTableMigrate(db *gorm.DB) error {
|
|||
COMMENT ON COLUMN "approval_files".created_at IS 'Дата создания файла';
|
||||
`)
|
||||
}
|
||||
|
||||
// 🚀 Ключевой индекс под GetFilesByApprovalIDsDB (батч IN по approval_id)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_files_approval_id ON approval_files (approval_id)`)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,52 @@
|
|||
package tablesmigration
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ApprovalFlowNodesTableMigrate создаёт таблицу узлов дерева навигации
|
||||
func ApprovalFlowNodesTableMigrate(db *gorm.DB) error {
|
||||
hasTable := db.Migrator().HasTable(&LocalApprovalFlowNodeProvider{})
|
||||
|
||||
if err := db.AutoMigrate(&LocalApprovalFlowNodeProvider{}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !hasTable {
|
||||
time.Sleep(5 * time.Second)
|
||||
|
||||
// Foreign key на approval_topics
|
||||
db.Exec(`ALTER TABLE approval_flow_nodes ADD CONSTRAINT fk_approval_flow_nodes_topic_id FOREIGN KEY (topic_id) REFERENCES approval_topics(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
|
||||
// Самореференсный foreign key (parent_id -> id)
|
||||
db.Exec(`ALTER TABLE approval_flow_nodes ADD CONSTRAINT fk_approval_flow_nodes_parent_id FOREIGN KEY (parent_id) REFERENCES approval_flow_nodes(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
|
||||
// Уникальный индекс (topic_id, key) — чтобы ключи узлов были уникальны в рамках одной темы
|
||||
db.Exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_flow_nodes_topic_key ON approval_flow_nodes(topic_id, key)`)
|
||||
|
||||
// Комментарии
|
||||
execComments(db, `
|
||||
COMMENT ON TABLE "approval_flow_nodes" IS 'Узлы дерева навигации темы согласования: описывают структуру кнопок, шагов ввода и мультиселекта для динамического построения флоу';
|
||||
COMMENT ON COLUMN "approval_flow_nodes".id IS 'Внутренний уникальный идентификатор узла';
|
||||
COMMENT ON COLUMN "approval_flow_nodes".topic_id IS 'ID темы согласования, к которой принадлежит узел (ссылка на approval_topics.id)';
|
||||
COMMENT ON COLUMN "approval_flow_nodes".parent_id IS 'ID родительского узла (ссылка на approval_flow_nodes.id). NULL для корневого узла';
|
||||
COMMENT ON COLUMN "approval_flow_nodes".key IS 'Уникальный ключ узла в рамках темы (используется для навигации и идентификации)';
|
||||
COMMENT ON COLUMN "approval_flow_nodes".label IS 'Отображаемое название узла (текст на кнопке)';
|
||||
COMMENT ON COLUMN "approval_flow_nodes".data_key IS 'Ключ в map collected, куда сохраняется значение при выборе этого узла';
|
||||
COMMENT ON COLUMN "approval_flow_nodes".data_value IS 'Значение, сохраняемое в collected[data_key] при выборе этого узла';
|
||||
COMMENT ON COLUMN "approval_flow_nodes".is_input IS 'Флаг: является ли узел шагом текстового ввода';
|
||||
COMMENT ON COLUMN "approval_flow_nodes".input_key IS 'Ключ в collected, куда сохраняется введённый пользователем текст';
|
||||
COMMENT ON COLUMN "approval_flow_nodes".input_hint IS 'Подсказка/шаблон для пользователя при текстовом вводе';
|
||||
COMMENT ON COLUMN "approval_flow_nodes".is_multi_select IS 'Флаг: является ли узел узлом мультиселекта (выбор нескольких значений)';
|
||||
COMMENT ON COLUMN "approval_flow_nodes".multi_select_key IS 'Ключ в collected, куда сохраняется результат мультиселекта (через запятую)';
|
||||
COMMENT ON COLUMN "approval_flow_nodes".multi_select_value IS 'Значение этого варианта в мультиселекте';
|
||||
COMMENT ON COLUMN "approval_flow_nodes".topic_code IS 'Код темы для проверки прав доступа (если задан — кнопка показывается только при наличии права create на эту тему)';
|
||||
COMMENT ON COLUMN "approval_flow_nodes".sort_order IS 'Порядок сортировки узла среди братьев (0, 1, 2, ...)';
|
||||
COMMENT ON COLUMN "approval_flow_nodes".created_at IS 'Дата и время создания узла';
|
||||
COMMENT ON COLUMN "approval_flow_nodes".updated_at IS 'Дата и время последнего изменения узла';
|
||||
`)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
@ -0,0 +1,77 @@
|
|||
package tablesmigration
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
"time"
|
||||
)
|
||||
|
||||
type LocalApprovalRevocationRequestProvider struct {
|
||||
ID uint64 `gorm:"column:id;primaryKey;autoIncrement"`
|
||||
ApprovalID uint64 `gorm:"column:approval_id;not null"`
|
||||
RequestedByID uint64 `gorm:"column:requested_by_id;not null"`
|
||||
Reason *string `gorm:"column:reason;type:text"`
|
||||
Status string `gorm:"column:status;type:text;not null;default:'pending'"`
|
||||
CreatedAt time.Time `gorm:"column:created_at;default:CURRENT_TIMESTAMP"`
|
||||
UpdatedAt time.Time `gorm:"column:updated_at;default:CURRENT_TIMESTAMP"`
|
||||
}
|
||||
|
||||
func (LocalApprovalRevocationRequestProvider) TableName() string {
|
||||
return "approval_revocation_requests"
|
||||
}
|
||||
|
||||
type LocalApprovalRevocationApproverProvider struct {
|
||||
ID uint64 `gorm:"column:id;primaryKey;autoIncrement"`
|
||||
RevocationRequestID uint64 `gorm:"column:revocation_request_id;not null"`
|
||||
ApproverID uint64 `gorm:"column:approver_id;not null"`
|
||||
Status string `gorm:"column:status;type:text;not null;default:'pending'"`
|
||||
Comment *string `gorm:"column:comment;type:text"`
|
||||
ActedAt *time.Time `gorm:"column:acted_at"`
|
||||
CreatedAt time.Time `gorm:"column:created_at;default:CURRENT_TIMESTAMP"`
|
||||
}
|
||||
|
||||
func (LocalApprovalRevocationApproverProvider) TableName() string {
|
||||
return "approval_revocation_approvers"
|
||||
}
|
||||
|
||||
func ApprovalRevocationTablesMigrate(db *gorm.DB) error {
|
||||
hasReqTable := db.Migrator().HasTable(&LocalApprovalRevocationRequestProvider{})
|
||||
hasApprTable := db.Migrator().HasTable(&LocalApprovalRevocationApproverProvider{})
|
||||
|
||||
if err := db.AutoMigrate(&LocalApprovalRevocationRequestProvider{}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := db.AutoMigrate(&LocalApprovalRevocationApproverProvider{}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !hasReqTable || !hasApprTable {
|
||||
time.Sleep(5 * time.Second)
|
||||
|
||||
db.Exec(`ALTER TABLE approval_revocation_requests ADD CONSTRAINT fk_arr_approval_id FOREIGN KEY (approval_id) REFERENCES approvals(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
db.Exec(`ALTER TABLE approval_revocation_requests ADD CONSTRAINT fk_arr_requested_by_id FOREIGN KEY (requested_by_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
|
||||
db.Exec(`ALTER TABLE approval_revocation_approvers ADD CONSTRAINT fk_ara_request_id FOREIGN KEY (revocation_request_id) REFERENCES approval_revocation_requests(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
db.Exec(`ALTER TABLE approval_revocation_approvers ADD CONSTRAINT fk_ara_approver_id FOREIGN KEY (approver_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
|
||||
execComments(db, `
|
||||
COMMENT ON TABLE "approval_revocation_requests" IS 'Запрос инициатора на отзыв уже согласованной заявки, требующий согласия всех согласующих';
|
||||
COMMENT ON COLUMN "approval_revocation_requests".approval_id IS 'Заявка, которую пытаются отозвать';
|
||||
COMMENT ON COLUMN "approval_revocation_requests".requested_by_id IS 'Инициатор, запросивший отзыв';
|
||||
COMMENT ON COLUMN "approval_revocation_requests".reason IS 'Причина отзыва, указанная инициатором';
|
||||
COMMENT ON COLUMN "approval_revocation_requests".status IS 'pending | approved | rejected | cancelled';
|
||||
|
||||
COMMENT ON TABLE "approval_revocation_approvers" IS 'Согласующие, чьё согласие требуется для отзыва уже согласованной заявки';
|
||||
COMMENT ON COLUMN "approval_revocation_approvers".revocation_request_id IS 'Запрос на отзыв';
|
||||
COMMENT ON COLUMN "approval_revocation_approvers".approver_id IS 'Согласующий, участвовавший в первоначальном согласовании';
|
||||
COMMENT ON COLUMN "approval_revocation_approvers".status IS 'pending | approved | rejected';
|
||||
`)
|
||||
}
|
||||
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_arr_approval_id ON approval_revocation_requests (approval_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_arr_status ON approval_revocation_requests (status)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_ara_request_id ON approval_revocation_approvers (revocation_request_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_ara_approver_id ON approval_revocation_approvers (approver_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_ara_request_status ON approval_revocation_approvers (revocation_request_id, status)`)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
@ -33,5 +33,12 @@ func ApprovalStepsTableMigrate(db *gorm.DB) error {
|
|||
COMMENT ON COLUMN "approval_steps".updated_at IS 'Дата последнего обновления шага';
|
||||
`)
|
||||
}
|
||||
|
||||
// 🚀 Композит покрывает GetApprovalStepsByApprovalIDsDB (IN approval_id + ORDER BY step_order)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_steps_approval_id_step_order ON approval_steps (approval_id, step_order)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_steps_approver_id ON approval_steps (approver_id)`)
|
||||
// Под "мои pending-согласования"
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_steps_approver_status ON approval_steps (approver_id, status)`)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,11 +15,9 @@ func ApprovalTasksTableMigrate(db *gorm.DB) error {
|
|||
if !hasTable {
|
||||
time.Sleep(5 * time.Second)
|
||||
|
||||
// Внешние ключи
|
||||
db.Exec(`ALTER TABLE approval_tasks ADD CONSTRAINT fk_approval_tasks_approval_id FOREIGN KEY (approval_id) REFERENCES approvals(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
db.Exec(`ALTER TABLE approval_tasks ADD CONSTRAINT fk_approval_tasks_executor_id FOREIGN KEY (executor_id) REFERENCES users(id) ON DELETE RESTRICT ON UPDATE CASCADE`)
|
||||
|
||||
// Комментарии к таблице и колонкам
|
||||
execComments(db, `
|
||||
COMMENT ON TABLE "approval_tasks" IS 'Задачи согласования, назначенные исполнителям';
|
||||
COMMENT ON COLUMN "approval_tasks".id IS 'Внутренний ID задачи';
|
||||
|
|
@ -33,5 +31,9 @@ func ApprovalTasksTableMigrate(db *gorm.DB) error {
|
|||
`)
|
||||
}
|
||||
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_tasks_approval_id ON approval_tasks (approval_id)`)
|
||||
// Под "мои задачи исполнителя, отфильтрованные по статусу"
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_tasks_executor_status ON approval_tasks (executor_id, status)`)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,38 @@
|
|||
package tablesmigration
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
"time"
|
||||
)
|
||||
|
||||
func ApprovalTaskTransfersTableMigrate(db *gorm.DB) error {
|
||||
hasTable := db.Migrator().HasTable(&LocalApprovalTaskTransferProvider{})
|
||||
|
||||
if err := db.AutoMigrate(&LocalApprovalTaskTransferProvider{}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !hasTable {
|
||||
time.Sleep(5 * time.Second)
|
||||
|
||||
db.Exec(`ALTER TABLE approval_task_transfers ADD CONSTRAINT fk_att_task_id FOREIGN KEY (task_id) REFERENCES approval_tasks(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
db.Exec(`ALTER TABLE approval_task_transfers ADD CONSTRAINT fk_att_from_executor_id FOREIGN KEY (from_executor_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
db.Exec(`ALTER TABLE approval_task_transfers ADD CONSTRAINT fk_att_to_executor_id FOREIGN KEY (to_executor_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
|
||||
execComments(db, `
|
||||
COMMENT ON TABLE "approval_task_transfers" IS 'История запросов на передачу задач исполнения между пользователями';
|
||||
COMMENT ON COLUMN "approval_task_transfers".task_id IS 'Передаваемая задача';
|
||||
COMMENT ON COLUMN "approval_task_transfers".from_executor_id IS 'Исполнитель, инициировавший передачу';
|
||||
COMMENT ON COLUMN "approval_task_transfers".to_executor_id IS 'Пользователь, которому предлагается принять задачу';
|
||||
COMMENT ON COLUMN "approval_task_transfers".status IS 'Статус: pending | accepted | declined | cancelled';
|
||||
COMMENT ON COLUMN "approval_task_transfers".responded_at IS 'Когда получатель ответил на запрос';
|
||||
`)
|
||||
}
|
||||
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_att_task_id ON approval_task_transfers (task_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_att_to_executor_id ON approval_task_transfers (to_executor_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_att_status ON approval_task_transfers (status)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_att_task_status ON approval_task_transfers (task_id, status)`)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
@ -33,5 +33,12 @@ func ApprovalTopicsTableMigrate(db *gorm.DB) error {
|
|||
COMMENT ON COLUMN "approval_topics".updated_at IS 'Дата последнего обновления записи';
|
||||
`)
|
||||
}
|
||||
|
||||
// 🚀 code — уникальность/поиск при создании темы; category_id — под GetTopicsListHandler фильтр и enrich;
|
||||
// композит category_id+is_active — под список активных тем категории (частый сценарий в боте)
|
||||
db.Exec(`CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_approval_topics_code ON approval_topics (code)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_topics_category_id ON approval_topics (category_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_topics_category_active ON approval_topics (category_id, is_active)`)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,5 +28,10 @@ func ApprovalTopicCategoriesTableMigrate(db *gorm.DB) error {
|
|||
COMMENT ON COLUMN "approval_topic_categories".updated_at IS 'Дата последнего обновления записи';
|
||||
`)
|
||||
}
|
||||
|
||||
// 🚀 code используется в GetApprovalTopicCategoryByCodeDB и в JOIN'ах GetObserversForApprovalDB/GetUserPermissionsDB
|
||||
db.Exec(`CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_approval_topic_categories_code ON approval_topic_categories (code)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_topic_categories_active ON approval_topic_categories (is_active)`)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -31,5 +31,14 @@ func ApprovalTopicExecutorsTableMigrate(db *gorm.DB) error {
|
|||
COMMENT ON COLUMN "approval_topic_executor".updated_at IS 'Дата последнего обновления записи';
|
||||
`)
|
||||
}
|
||||
|
||||
// 🚀 Композит покрывает GetExecutorsByTopicIDDB (topic_id + is_active + ORDER BY step_order)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_topic_executor_topic_active_step ON approval_topic_executor (topic_id, is_active, step_order)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_topic_executor_user_id ON approval_topic_executor (user_id)`)
|
||||
// Уникальность под проверку "исполнитель уже назначен на этот шаг" в CreateTopicExecutorHandler
|
||||
db.Exec(`CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_approval_topic_executor_topic_user_step ON approval_topic_executor (topic_id, user_id, step_order)`)
|
||||
// Под фильтрацию GetApprovalTopicExecutorListByCategoryDB (JOIN approval_topics ON t.category_id)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_topic_executor_id_step ON approval_topic_executor (id, step_order)`)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -26,5 +26,9 @@ func DepartmentsTableMigrate(db *gorm.DB) error {
|
|||
COMMENT ON COLUMN "departments".updated_at IS 'Дата последнего обновления записи';
|
||||
`)
|
||||
}
|
||||
|
||||
db.Exec(`CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_departments_code ON departments (code)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_departments_active ON departments (is_active)`)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,33 @@
|
|||
package tablesmigration
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
"time"
|
||||
)
|
||||
|
||||
func DirectorNotificationSubscriptionsTableMigrate(db *gorm.DB) error {
|
||||
hasTable := db.Migrator().HasTable(&LocalDirectorNotificationSubscriptionProvider{})
|
||||
|
||||
if err := db.AutoMigrate(&LocalDirectorNotificationSubscriptionProvider{}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !hasTable {
|
||||
time.Sleep(5 * time.Second)
|
||||
|
||||
db.Exec(`ALTER TABLE director_notification_subscriptions ADD CONSTRAINT fk_dns_director_id FOREIGN KEY (director_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
db.Exec(`ALTER TABLE director_notification_subscriptions ADD CONSTRAINT fk_dns_category_id FOREIGN KEY (category_id) REFERENCES approval_topic_categories(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
db.Exec(`ALTER TABLE director_notification_subscriptions ADD CONSTRAINT uq_dns_director_category UNIQUE (director_id, category_id)`)
|
||||
|
||||
execComments(db, `
|
||||
COMMENT ON TABLE "director_notification_subscriptions" IS 'Подписки директоров на уведомления по категориям тем согласования. Наличие строки = подписка включена, по умолчанию для всех категорий выключено';
|
||||
COMMENT ON COLUMN "director_notification_subscriptions".director_id IS 'Директор, оформивший подписку';
|
||||
COMMENT ON COLUMN "director_notification_subscriptions".category_id IS 'Категория тем, на которую подписан директор';
|
||||
`)
|
||||
}
|
||||
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_dns_director_id ON director_notification_subscriptions (director_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_dns_category_id ON director_notification_subscriptions (category_id)`)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
@ -0,0 +1,51 @@
|
|||
package tablesmigration
|
||||
|
||||
import (
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
"gorm.io/gorm"
|
||||
"time"
|
||||
)
|
||||
|
||||
type LocalMonthlyOrderSetting typescore.MonthlyOrderSetting
|
||||
type LocalMonthlyOrderClient typescore.MonthlyOrderClient
|
||||
type LocalMonthlyOrderItem typescore.MonthlyOrderItem
|
||||
type LocalMonthlyOrderFile typescore.MonthlyOrderFile
|
||||
|
||||
func (LocalMonthlyOrderSetting) TableName() string { return "monthly_order_settings" }
|
||||
func (LocalMonthlyOrderClient) TableName() string { return "monthly_order_clients" }
|
||||
func (LocalMonthlyOrderItem) TableName() string { return "monthly_order_items" }
|
||||
func (LocalMonthlyOrderFile) TableName() string { return "monthly_order_files" }
|
||||
|
||||
func MonthlyOrdersTablesMigrate(db *gorm.DB) error {
|
||||
tables := []interface{}{
|
||||
&LocalMonthlyOrderSetting{},
|
||||
&LocalMonthlyOrderClient{},
|
||||
&LocalMonthlyOrderItem{},
|
||||
&LocalMonthlyOrderFile{},
|
||||
}
|
||||
|
||||
for _, table := range tables {
|
||||
if err := db.AutoMigrate(table); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// Устанавливаем внешние ключи (Foreign Keys)
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
db.Exec(`ALTER TABLE monthly_order_clients ADD CONSTRAINT fk_moc_manager_id FOREIGN KEY (manager_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
db.Exec(`ALTER TABLE monthly_order_clients ADD CONSTRAINT fk_moc_approval_id FOREIGN KEY (approval_id) REFERENCES approvals(id) ON DELETE SET NULL ON UPDATE CASCADE`)
|
||||
|
||||
db.Exec(`ALTER TABLE monthly_order_items ADD CONSTRAINT fk_moi_order_client_id FOREIGN KEY (order_client_id) REFERENCES monthly_order_clients(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
|
||||
db.Exec(`ALTER TABLE monthly_order_files ADD CONSTRAINT fk_mof_order_client_id FOREIGN KEY (order_client_id) REFERENCES monthly_order_clients(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
|
||||
// Индексы для быстрого поиска
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_moc_manager_month_year ON monthly_order_clients (manager_id, month, year)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_moi_order_client_id ON monthly_order_items (order_client_id)`)
|
||||
|
||||
db.Exec(`CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_moc_unique_client_order ON monthly_order_clients (manager_id, month, year, client_name)`)
|
||||
db.Exec(`CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_mos_unique_settings ON monthly_order_settings (month, year)`)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
@ -0,0 +1,66 @@
|
|||
package tablesmigration
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
"time"
|
||||
)
|
||||
|
||||
func NotificationsTableMigrate(db *gorm.DB) error {
|
||||
hasNotificationsTable := db.Migrator().HasTable(&LocalNotificationProvider{})
|
||||
hasRecipientsTable := db.Migrator().HasTable(&LocalNotificationRecipientProvider{})
|
||||
|
||||
if err := db.AutoMigrate(&LocalNotificationProvider{}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := db.AutoMigrate(&LocalNotificationRecipientProvider{}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !hasNotificationsTable || !hasRecipientsTable {
|
||||
time.Sleep(5 * time.Second)
|
||||
|
||||
db.Exec(`ALTER TABLE notifications ADD CONSTRAINT fk_notifications_created_by_id FOREIGN KEY (created_by_id) REFERENCES users(id) ON DELETE SET NULL ON UPDATE CASCADE`)
|
||||
|
||||
db.Exec(`ALTER TABLE notification_recipients ADD CONSTRAINT fk_notification_recipients_notification_id FOREIGN KEY (notification_id) REFERENCES notifications(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
db.Exec(`ALTER TABLE notification_recipients ADD CONSTRAINT fk_notification_recipients_user_id FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
|
||||
execComments(db, `
|
||||
COMMENT ON TABLE "notifications" IS 'Уведомления/рассылки, отправляемые администратором через Telegram-бота';
|
||||
COMMENT ON COLUMN "notifications".id IS 'Внутренний ID уведомления';
|
||||
COMMENT ON COLUMN "notifications".title IS 'Заголовок рассылки (для админки, не отправляется в Telegram)';
|
||||
COMMENT ON COLUMN "notifications".message_html IS 'Текст сообщения в HTML-разметке, совместимой с Telegram ParseMode=HTML';
|
||||
COMMENT ON COLUMN "notifications".photo_base64 IS 'Прикреплённое фото в формате base64, опционально';
|
||||
COMMENT ON COLUMN "notifications".photo_file_name IS 'Оригинальное имя прикреплённого файла фото';
|
||||
COMMENT ON COLUMN "notifications".target_filters IS 'Критерии выбора получателей (user_ids, role_ids, role_type_flags, department_ids) в формате JSON, для аудита';
|
||||
COMMENT ON COLUMN "notifications".status IS 'Статус рассылки: pending | sending | completed | failed';
|
||||
COMMENT ON COLUMN "notifications".total_count IS 'Общее число подобранных получателей';
|
||||
COMMENT ON COLUMN "notifications".sent_count IS 'Число успешно доставленных сообщений';
|
||||
COMMENT ON COLUMN "notifications".failed_count IS 'Число сообщений с ошибкой доставки';
|
||||
COMMENT ON COLUMN "notifications".created_by_id IS 'Администратор, инициировавший рассылку';
|
||||
COMMENT ON COLUMN "notifications".created_at IS 'Дата создания рассылки';
|
||||
COMMENT ON COLUMN "notifications".updated_at IS 'Дата последнего изменения статуса рассылки';
|
||||
COMMENT ON COLUMN "notifications".sent_at IS 'Дата фактической отправки рассылки получателям';
|
||||
|
||||
COMMENT ON TABLE "notification_recipients" IS 'История доставки уведомления конкретным пользователям';
|
||||
COMMENT ON COLUMN "notification_recipients".id IS 'Внутренний ID записи истории доставки';
|
||||
COMMENT ON COLUMN "notification_recipients".notification_id IS 'Уведомление, к которому относится доставка';
|
||||
COMMENT ON COLUMN "notification_recipients".user_id IS 'Получатель уведомления';
|
||||
COMMENT ON COLUMN "notification_recipients".status IS 'Статус доставки: pending | sent | failed';
|
||||
COMMENT ON COLUMN "notification_recipients".error_message IS 'Текст ошибки при неудачной отправке';
|
||||
COMMENT ON COLUMN "notification_recipients".telegram_message_id IS 'ID отправленного сообщения в Telegram, если доставка успешна';
|
||||
COMMENT ON COLUMN "notification_recipients".sent_at IS 'Дата и время фактической отправки этому получателю';
|
||||
COMMENT ON COLUMN "notification_recipients".created_at IS 'Дата создания записи (постановка в очередь на отправку)';
|
||||
`)
|
||||
}
|
||||
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_notifications_status ON notifications (status)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_notifications_created_at ON notifications (created_at DESC)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_notifications_created_by_id ON notifications (created_by_id)`)
|
||||
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_notification_recipients_notification_id ON notification_recipients (notification_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_notification_recipients_user_id ON notification_recipients (user_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_notification_recipients_status ON notification_recipients (status)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_notification_recipients_notification_status ON notification_recipients (notification_id, status)`)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
@ -31,5 +31,16 @@ func PermissionsTableMigrate(db *gorm.DB) error {
|
|||
COMMENT ON COLUMN "permissions".updated_at IS 'Дата последнего обновления записи';
|
||||
`)
|
||||
}
|
||||
|
||||
// 🚀 role_id — под GetUserPermissionsDB JOIN с user_roles; композит role_id+action — под UserCanCreateTopicDB;
|
||||
// topic_id/topic_category_id — под enrichPermissionsBatch и JOIN'ы наблюдателей
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_permissions_role_id ON permissions (role_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_permissions_role_id_action ON permissions (role_id, action)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_permissions_topic_id ON permissions (topic_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_permissions_topic_category_id ON permissions (topic_category_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_permissions_action ON permissions (action)`)
|
||||
// Под GetObserversForCategoryDB / GetObserversForApprovalDB: action='observe' + topic_category_id
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_permissions_action_category ON permissions (action, topic_category_id)`)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -24,7 +24,18 @@ type ApprovalCommentsProvider typescore.ApprovalComment
|
|||
type LocalSuggestionProvider typescore.Suggestion
|
||||
type LocalSuggestionMessagesProvider typescore.SuggestionMessage
|
||||
type LocalApprovalTopicExecutorProvider typescore.ApprovalTopicExecutor
|
||||
type LocalNotificationProvider typescore.Notification
|
||||
type LocalNotificationRecipientProvider typescore.NotificationRecipient
|
||||
type LocalDirectorNotificationSubscriptionProvider typescore.DirectorNotificationSubscription
|
||||
type LocalApprovalTaskTransferProvider typescore.ApprovalTaskTransfer
|
||||
type LocalApprovalFlowNodeProvider typescore.ApprovalFlowNode
|
||||
|
||||
func (LocalApprovalTaskTransferProvider) TableName() string {
|
||||
return dbcoretablenames.TableNameApprovalTaskTransfers.ToString()
|
||||
}
|
||||
func (LocalDirectorNotificationSubscriptionProvider) TableName() string {
|
||||
return dbcoretablenames.TableNameDirectorNotificationSubscriptions.ToString()
|
||||
}
|
||||
func (LocalUserProvider) TableName() string {
|
||||
return dbcoretablenames.TableNameUsers.ToString()
|
||||
}
|
||||
|
|
@ -82,3 +93,12 @@ func (ApprovalAdditionalObserver) TableName() string {
|
|||
func (LocalApprovalTopicExecutorProvider) TableName() string {
|
||||
return dbcoretablenames.TableNameApprovalTopicExecutor.ToString()
|
||||
}
|
||||
func (LocalNotificationProvider) TableName() string {
|
||||
return dbcoretablenames.TableNameNotifications.ToString()
|
||||
}
|
||||
func (LocalNotificationRecipientProvider) TableName() string {
|
||||
return dbcoretablenames.TableNameNotificationsRecipients.ToString()
|
||||
}
|
||||
func (LocalApprovalFlowNodeProvider) TableName() string {
|
||||
return dbcoretablenames.TableNameApprovalFlowNodes.ToString()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,5 +28,15 @@ func RolesTableMigrate(db *gorm.DB) error {
|
|||
COMMENT ON COLUMN "roles".updated_at IS 'Дата последнего обновления записи';
|
||||
`)
|
||||
}
|
||||
|
||||
// 🚀 code — под GetUsersByRoleCodeDB; флаги is_director/is_approver/is_observer используются
|
||||
// как условия в JOIN'ах GetDirectorsDB/IsDirectorDB/IsApproverDB/IsObserverDB/GetObserversForCategoryDB —
|
||||
// частичные индексы дают максимальную выборочность, т.к. флаг true встречается редко
|
||||
db.Exec(`CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_roles_code ON roles (code)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_roles_is_director ON roles (id) WHERE is_director = true`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_roles_is_approver ON roles (id) WHERE is_approver = true`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_roles_is_observer ON roles (id) WHERE is_observer = true`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_roles_is_default ON roles (id) WHERE is_default = true`)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,31 @@
|
|||
package tablesmigration
|
||||
|
||||
import (
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
"gorm.io/gorm"
|
||||
"time"
|
||||
)
|
||||
|
||||
type LocalSmsLogProvider typescore.SmsLog
|
||||
|
||||
func (LocalSmsLogProvider) TableName() string {
|
||||
return "sms_logs"
|
||||
}
|
||||
|
||||
func SmsLogsTableMigrate(db *gorm.DB) error {
|
||||
hasTable := db.Migrator().HasTable(&LocalSmsLogProvider{})
|
||||
|
||||
err := db.AutoMigrate(&LocalSmsLogProvider{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !hasTable {
|
||||
time.Sleep(5 * time.Second)
|
||||
db.Exec(`
|
||||
COMMENT ON TABLE sms_logs IS 'Таблица для хранения логов SMS из внешней телефонии';
|
||||
COMMENT ON COLUMN sms_logs.direction IS '0 - входящее, 1 - исходящее';
|
||||
`)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
@ -30,5 +30,9 @@ func SuggestionMessagesTableMigrate(db *gorm.DB) error {
|
|||
`)
|
||||
}
|
||||
|
||||
// 🚀 Композит покрывает "переписка по предложению в хронологическом порядке"
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_suggestion_messages_suggestion_id_created_at ON suggestion_messages (suggestion_id, created_at)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_suggestion_messages_user_id ON suggestion_messages (user_id)`)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -30,5 +30,9 @@ func SuggestionsTableMigrate(db *gorm.DB) error {
|
|||
`)
|
||||
}
|
||||
|
||||
// 🚀 Композиты под "мои открытые предложения" / "предложения, адресованные директору"
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_suggestions_initiator_status ON suggestions (initiator_id, status)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_suggestions_director_status ON suggestions (director_id, status)`)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,56 @@
|
|||
package tablesmigration
|
||||
|
||||
import (
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
"gorm.io/gorm"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Вспомогательная структура для автомиграции, чтобы не тянуть зависимости
|
||||
type LocalTaskDelegation typescore.TaskDelegation
|
||||
|
||||
func (LocalTaskDelegation) TableName() string {
|
||||
return "task_delegations"
|
||||
}
|
||||
|
||||
func TaskDelegationsTableMigrate(db *gorm.DB) error {
|
||||
hasTable := db.Migrator().HasTable(&LocalTaskDelegation{})
|
||||
|
||||
if err := db.AutoMigrate(&LocalTaskDelegation{}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !hasTable {
|
||||
time.Sleep(5 * time.Second)
|
||||
|
||||
// Внешние ключи для связи с таблицей пользователей
|
||||
db.Exec(`ALTER TABLE task_delegations ADD CONSTRAINT fk_task_delegator FOREIGN KEY (delegator_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
db.Exec(`ALTER TABLE task_delegations ADD CONSTRAINT fk_task_delegate FOREIGN KEY (delegate_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
db.Exec(`ALTER TABLE task_delegations ADD CONSTRAINT fk_task_category FOREIGN KEY (category_id) REFERENCES approval_topic_categories(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
db.Exec(`ALTER TABLE task_delegations ADD CONSTRAINT fk_task_topic FOREIGN KEY (topic_id) REFERENCES approval_topics(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
|
||||
execComments(db, `
|
||||
COMMENT ON TABLE "task_delegations" IS 'Делегирование прав на задачи';
|
||||
COMMENT ON COLUMN "task_delegations".id IS 'Внутренний ID записи делегирования';
|
||||
COMMENT ON COLUMN "task_delegations".delegator_id IS 'ID пользователя, который передает свои задачи (делегатор)';
|
||||
COMMENT ON COLUMN "task_delegations".delegate_id IS 'ID пользователя, которому передаются задачи (делегат)';
|
||||
COMMENT ON COLUMN "task_delegations".valid_until IS 'Дата и время окончания делегирования';
|
||||
COMMENT ON COLUMN "task_delegations".is_active IS 'Активно ли данное делегирование';
|
||||
COMMENT ON COLUMN "task_delegations".notified_day IS 'Отправлено ли уведомление за день до окончания';
|
||||
COMMENT ON COLUMN "task_delegations".notified_2h IS 'Отправлено ли уведомление за 2 часа до окончания';
|
||||
COMMENT ON COLUMN "task_delegations".created_at IS 'Дата создания записи';
|
||||
COMMENT ON COLUMN "task_delegations".updated_at IS 'Дата последнего обновления записи';
|
||||
`)
|
||||
}
|
||||
|
||||
// 🚀 Индексы для быстрого поиска активных делегирований по делегатору
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_task_delegations_delegator_active ON task_delegations (delegator_id, is_active)`)
|
||||
|
||||
// Индекс для поиска активных делегирований по делегату (чтобы делегат мог видеть переданные ему права)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_task_delegations_delegate_active ON task_delegations (delegate_id, is_active)`)
|
||||
|
||||
// Индекс для крона/воркеров, которые будут проверять истекшие сроки и рассылать уведомления
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_task_delegations_valid_until_active ON task_delegations (valid_until, is_active)`)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
@ -15,8 +15,7 @@ func UsersTableMigrate(db *gorm.DB) error {
|
|||
if !hasTable {
|
||||
time.Sleep(5 * time.Second)
|
||||
|
||||
db.Exec(`ALTER TABLE users ADD CONSTRAINT fk_users_department_id FOREIGN KEY (department_id) REFERENCES departments(id) ON DELETE SET NULL ON UPDATE CASCADE`)
|
||||
|
||||
db.Exec(`ALTER TABLE users ADD CONSTRAINT fk_users_department_id FOREIGN KEY (department_id) REFERENCES departments(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
execComments(db, `
|
||||
COMMENT ON TABLE "users" IS 'Сотрудники компании РусПЭТ';
|
||||
COMMENT ON COLUMN "users".id IS 'Внутренний ID пользователя';
|
||||
|
|
@ -32,5 +31,20 @@ func UsersTableMigrate(db *gorm.DB) error {
|
|||
COMMENT ON COLUMN "users".updated_at IS 'Дата последнего обновления записи';
|
||||
`)
|
||||
}
|
||||
|
||||
// 🚀 telegram_id — под GetUserByTelegramIDDB (уникальный лукап при каждом сообщении в бота);
|
||||
// department_id — под фильтр users и JOIN'ы в enrichUsersBatch;
|
||||
// pg_trgm-индекс под LIKE-поиск по full_name (GetUserListHandler search)
|
||||
db.Exec(`CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_users_telegram_id ON users (telegram_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_users_department_id ON users (department_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_users_is_blocked ON users (is_blocked)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_users_is_fired ON users (is_fired)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_users_created_at ON users (created_at DESC)`)
|
||||
// Композит под самый частый вызов фильтра списка: не заблокирован + не уволен
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_users_blocked_fired ON users (is_blocked, is_fired)`)
|
||||
// Требует расширения pg_trgm: CREATE EXTENSION IF NOT EXISTS pg_trgm;
|
||||
db.Exec(`CREATE EXTENSION IF NOT EXISTS pg_trgm`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_users_full_name_trgm ON users USING gin (full_name gin_trgm_ops)`)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -30,5 +30,11 @@ func UserHierarchyTableMigrate(db *gorm.DB) error {
|
|||
COMMENT ON COLUMN "user_hierarchy".updated_at IS 'Дата последнего обновления записи';
|
||||
`)
|
||||
}
|
||||
|
||||
// 🚀 Композит покрывает основной сценарий: "цепочка согласующих подчинённого в отделе по приоритету"
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_user_hierarchy_subordinate_dept_priority ON user_hierarchy (subordinate_id, department_id, priority)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_user_hierarchy_approver_id ON user_hierarchy (approver_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_user_hierarchy_department_id ON user_hierarchy (department_id)`)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -27,5 +27,13 @@ func UserRolesTableMigrate(db *gorm.DB) error {
|
|||
COMMENT ON COLUMN "user_roles".updated_at IS 'Дата последнего обновления записи';
|
||||
`)
|
||||
}
|
||||
|
||||
// 🚀 Индексы: user_id — под GetUserRolesByUserIDsDB/DeleteUserRolesByUserIDDB,
|
||||
// role_id — под GetPermissionsByRoleIDHandler JOIN'ы,
|
||||
// уникальный композит — защита от дублей роли у пользователя + быстрый lookup в AssignUserRoleHandler
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_user_roles_user_id ON user_roles (user_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_user_roles_role_id ON user_roles (role_id)`)
|
||||
db.Exec(`CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_user_roles_user_role ON user_roles (user_id, role_id)`)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ import (
|
|||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
|
@ -87,6 +88,8 @@ func (u *AdminDB) CreateAdminDB(tx pgx.Tx, adminObj *typescore.Admin, returnObj
|
|||
ctx, cancel := context.WithTimeout(context.Background(), variables.ContextTimeoutBase)
|
||||
defer cancel()
|
||||
|
||||
now := time.Now().UTC()
|
||||
adminObj.CreatedAt = &now
|
||||
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Insert(dbcoretablenames.TableNameAdmin.ToString())
|
||||
|
||||
|
|
@ -192,24 +195,23 @@ func (u *AdminDB) UpdateAdminDB(tx pgx.Tx, paramsUpdate *typescore.Admin, return
|
|||
}
|
||||
|
||||
func (u *AdminDB) DeleteAdminDB(params *typescore.Admin) error {
|
||||
if params != nil && params.Login != nil {
|
||||
if params != nil && params.ID != nil {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), variables.ContextTimeoutBase)
|
||||
defer cancel()
|
||||
|
||||
query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Delete(dbcoretablenames.TableNameAdmin.ToString()).
|
||||
Where(squirrel.Eq{"email": *params.Login}).
|
||||
Where(squirrel.Eq{"id": *params.ID}).
|
||||
ToSql()
|
||||
|
||||
if err != nil {
|
||||
return errors.New(fmt.Sprintf("error_delete: failed to create DELETE %s SQL: %v", dbcoretablenames.TableNameAdmin.ToString(), err))
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, query, args...)
|
||||
_, err = u.pool.Exec(ctx, query, args...)
|
||||
if err != nil {
|
||||
return errors.New(fmt.Sprintf("error_delete: failed to create DELETE %s SQL: %v", dbcoretablenames.TableNameAdmin.ToString(), err))
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
return nil
|
||||
} else {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,195 @@
|
|||
package dbcore
|
||||
|
||||
import (
|
||||
dbcoretablenames "bitrix_balancer_api/core/db/table_names"
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
dbutils "bitrix_balancer_api/core/utilscore/db"
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type AdminActionLogDB struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewAdminActionLogDB(pool *pgxpool.Pool) *AdminActionLogDB {
|
||||
return &AdminActionLogDB{pool: pool}
|
||||
}
|
||||
|
||||
type AdminActionLogDBI interface {
|
||||
GetAdminActionLogsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.AdminActionLog, uint64, error)
|
||||
CreateAdminActionLogDB(ctx context.Context, tx pgx.Tx, obj *typescore.AdminActionLog, returnObj ...bool) (*typescore.AdminActionLog, pgx.Tx, error)
|
||||
DeleteAdminActionLogDB(ctx context.Context, params *typescore.AdminActionLog) error
|
||||
GetAdminActionLogByIDDB(ctx context.Context, id uint64) (*typescore.AdminActionLog, error)
|
||||
GetAdminActionLogsFilteredDB(ctx context.Context, filter typescore.AdminActionLogFilter, offset, limit *uint64) ([]*typescore.AdminActionLog, uint64, error)
|
||||
}
|
||||
|
||||
func (u *AdminActionLogDB) GetAdminActionLogsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.AdminActionLog, uint64, error) {
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.AdminActionLog{}, dbcoretablenames.TableNameAdminActionLogs.ToString())
|
||||
selectFields := append(fields, "COUNT(*) OVER() AS total_count")
|
||||
|
||||
options, filter, err := dbutils.GetOptionsDB[typescore.AdminActionLog](opts...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameAdminActionLogs.ToString(), selectFields)
|
||||
query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
|
||||
query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameAdminActionLogs.ToString())
|
||||
query = query.OrderBy("created_at DESC") // самые свежие действия первыми
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var logs []*typescore.AdminActionLog
|
||||
var totalCount uint64
|
||||
for rows.Next() {
|
||||
entry := &typescore.AdminActionLog{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, entry, &totalCount); err != nil {
|
||||
logrus.Warn("GetAdminActionLogsListDB:ScanRowsToStructRows", err)
|
||||
continue
|
||||
}
|
||||
logs = append(logs, entry)
|
||||
}
|
||||
|
||||
return logs, totalCount, nil
|
||||
}
|
||||
|
||||
func (u *AdminActionLogDB) GetAdminActionLogsFilteredDB(ctx context.Context, filter typescore.AdminActionLogFilter, offset, limit *uint64) ([]*typescore.AdminActionLog, uint64, error) {
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.AdminActionLog{}, dbcoretablenames.TableNameAdminActionLogs.ToString())
|
||||
selectFields := append(fields, "COUNT(*) OVER() AS total_count")
|
||||
|
||||
query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameAdminActionLogs.ToString(), selectFields)
|
||||
|
||||
if filter.AdminID != nil {
|
||||
query = query.Where(squirrel.Eq{"admin_id": *filter.AdminID})
|
||||
}
|
||||
if filter.AdminLogin != nil && *filter.AdminLogin != "" {
|
||||
query = query.Where(squirrel.ILike{"admin_login": "%" + *filter.AdminLogin + "%"})
|
||||
}
|
||||
if filter.Action != nil {
|
||||
query = query.Where(squirrel.Eq{"action": *filter.Action})
|
||||
}
|
||||
if filter.EntityType != nil {
|
||||
query = query.Where(squirrel.Eq{"entity_type": *filter.EntityType})
|
||||
}
|
||||
if filter.EntityID != nil {
|
||||
query = query.Where(squirrel.Eq{"entity_id": *filter.EntityID})
|
||||
}
|
||||
if filter.DateFrom != nil {
|
||||
query = query.Where(squirrel.GtOrEq{"created_at": *filter.DateFrom})
|
||||
}
|
||||
if filter.DateTo != nil {
|
||||
query = query.Where(squirrel.LtOrEq{"created_at": *filter.DateTo})
|
||||
}
|
||||
if filter.Search != nil && *filter.Search != "" {
|
||||
query = query.Where(squirrel.ILike{"description": "%" + *filter.Search + "%"})
|
||||
}
|
||||
|
||||
query = dbutils.SetterLimitAndOffsetQuery(query, offset, limit)
|
||||
query = query.OrderBy("created_at DESC")
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var logs []*typescore.AdminActionLog
|
||||
var totalCount uint64
|
||||
for rows.Next() {
|
||||
entry := &typescore.AdminActionLog{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, entry, &totalCount); err != nil {
|
||||
logrus.Warn("GetAdminActionLogsFilteredDB:ScanRowsToStructRows", err)
|
||||
continue
|
||||
}
|
||||
logs = append(logs, entry)
|
||||
}
|
||||
|
||||
return logs, totalCount, nil
|
||||
}
|
||||
|
||||
func (u *AdminActionLogDB) CreateAdminActionLogDB(ctx context.Context, tx pgx.Tx, obj *typescore.AdminActionLog, returnObj ...bool) (*typescore.AdminActionLog, pgx.Tx, error) {
|
||||
if obj == nil {
|
||||
return nil, nil, errors.New("AdminActionLog obj is nil")
|
||||
}
|
||||
|
||||
var insertedID uint64
|
||||
|
||||
now := time.Now().UTC()
|
||||
obj.CreatedAt = &now
|
||||
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Insert(dbcoretablenames.TableNameAdminActionLogs.ToString())
|
||||
|
||||
sqlV, args, err := dbutils.GenerateInsertRequest(query, obj)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*sqlV = *sqlV + " RETURNING id"
|
||||
return tx.QueryRow(ctx, *sqlV, args...).Scan(&insertedID)
|
||||
})
|
||||
if err != nil {
|
||||
return nil, tx, err
|
||||
}
|
||||
|
||||
returnObjBool := len(returnObj) > 0 && returnObj[0]
|
||||
if returnObjBool && insertedID > 0 {
|
||||
created, err := u.GetAdminActionLogByIDDB(ctx, insertedID)
|
||||
return created, tx, err
|
||||
}
|
||||
return nil, tx, nil
|
||||
}
|
||||
|
||||
func (u *AdminActionLogDB) DeleteAdminActionLogDB(ctx context.Context, params *typescore.AdminActionLog) error {
|
||||
if params == nil || params.ID == nil {
|
||||
return errors.New("AdminActionLog obj is nil")
|
||||
}
|
||||
|
||||
query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Delete(dbcoretablenames.TableNameAdminActionLogs.ToString()).
|
||||
Where(squirrel.Eq{"id": *params.ID}).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (u *AdminActionLogDB) GetAdminActionLogByIDDB(ctx context.Context, id uint64) (*typescore.AdminActionLog, error) {
|
||||
logs, _, err := u.GetAdminActionLogsListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.AdminActionLog{ID: &id},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(logs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return logs[0], nil
|
||||
}
|
||||
|
|
@ -5,6 +5,7 @@ import (
|
|||
"bitrix_balancer_api/core/typescore"
|
||||
dbutils "bitrix_balancer_api/core/utilscore/db"
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/sirupsen/logrus"
|
||||
|
|
@ -37,6 +38,163 @@ type ApprovalDBI interface {
|
|||
GetPendingApprovalsByApproverAndCategoryDB(ctx context.Context, approverID uint64, categoryCode string) ([]*typescore.Approval, error)
|
||||
GetApprovalsByCategoryDB(ctx context.Context, categoryCode string) ([]*typescore.Approval, error)
|
||||
GetClosedApprovalsByInitiatorDB(ctx context.Context, initiatorID uint64) ([]*typescore.Approval, error)
|
||||
SearchApprovalsByContentDB(ctx context.Context, content string, opts ...typescore.ListDbOptions) ([]*typescore.Approval, uint64, error)
|
||||
GetOldPendingApprovalsDB(ctx context.Context, since time.Time, limit int) ([]*typescore.Approval, error)
|
||||
CountApprovalsDB(ctx context.Context, filter *typescore.Approval) (int, error)
|
||||
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 — поиск заявок по частичному совпадению в тексте
|
||||
func (u *ApprovalDB) SearchApprovalsByContentDB(ctx context.Context, content string, opts ...typescore.ListDbOptions) ([]*typescore.Approval, uint64, error) {
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.Approval{}, "approvals")
|
||||
selectFields := append(fields, "COUNT(*) OVER() AS total_count")
|
||||
|
||||
options, filter, err := dbutils.GetOptionsDB[typescore.Approval](opts...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
query := dbutils.BuildSelectQuery("approvals", selectFields)
|
||||
query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
|
||||
|
||||
// 🆕 Для collation "C" используем явное приведение
|
||||
// Вариант 1: Через CAST с collation
|
||||
query = query.Where(
|
||||
squirrel.Expr(
|
||||
"approvals.content::text ILIKE ? COLLATE \"ru_RU.UTF-8\"",
|
||||
"%"+content+"%",
|
||||
),
|
||||
)
|
||||
|
||||
// Применяем остальные фильтры
|
||||
query = dbutils.ApplyFilters(query, filter, nil, "approvals")
|
||||
query = query.OrderBy("approvals.created_at DESC")
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
logrus.Infof("🔍 SearchApprovalsByContentDB SQL: %s", sql)
|
||||
logrus.Infof("🔍 SearchApprovalsByContentDB Args: %v", args)
|
||||
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
logrus.Errorf("❌ SearchApprovalsByContentDB error: %v", err)
|
||||
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("SearchApprovalsByContentDB:ScanRowsToStructRows", err)
|
||||
continue
|
||||
}
|
||||
approvals = append(approvals, approval)
|
||||
}
|
||||
|
||||
logrus.Infof("✅ SearchApprovalsByContentDB found: %d approvals, total: %d", len(approvals), totalCount)
|
||||
|
||||
return approvals, totalCount, nil
|
||||
}
|
||||
|
||||
func (u *ApprovalDB) GetApprovalsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.Approval, uint64, error) {
|
||||
|
|
@ -85,6 +243,8 @@ func (u *ApprovalDB) CreateApprovalDB(ctx context.Context, tx pgx.Tx, ApprovalOb
|
|||
|
||||
var insertedID uint64
|
||||
|
||||
now := time.Now().UTC()
|
||||
ApprovalObj.CreatedAt = &now
|
||||
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Insert(dbcoretablenames.TableNameApprovals.ToString())
|
||||
|
|
@ -117,6 +277,8 @@ func (u *ApprovalDB) UpdateApprovalDB(ctx context.Context, tx pgx.Tx, paramsUpda
|
|||
return nil, nil, errors.New("approval obj is nil")
|
||||
}
|
||||
|
||||
now := time.Now().UTC()
|
||||
paramsUpdate.CreatedAt = &now
|
||||
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameApprovals.ToString())
|
||||
query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate)
|
||||
|
|
@ -351,6 +513,7 @@ func (u *ApprovalDB) GetClosedApprovalsByInitiatorDB(ctx context.Context, initia
|
|||
|
||||
// GetApprovalsForReportDB — получение согласований для отчёта с учётом всех ролей пользователя.
|
||||
// Пользователь видит согласования где он: инициатор, согласующий, наблюдатель или исполнитель.
|
||||
// GetApprovalsForReportDB — получение согласований для отчёта с учётом всех ролей пользователя.
|
||||
func (u *ApprovalDB) GetApprovalsForReportDB(ctx context.Context, filter typescore.ReportFilter) ([]*typescore.Approval, error) {
|
||||
q := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select("DISTINCT a.*").
|
||||
|
|
@ -362,14 +525,19 @@ func (u *ApprovalDB) GetApprovalsForReportDB(ctx context.Context, filter typesco
|
|||
subQ2 := buildApprovalIdSubquery("approver", filter.UserID)
|
||||
subQ3 := buildApprovalIdSubquery("observer", filter.UserID)
|
||||
subQ4 := buildApprovalIdSubquery("executor", filter.UserID)
|
||||
subQ5 := buildApprovalIdSubquery("additional_approver", filter.UserID) // 🆕 Доп. согласующий
|
||||
subQ6 := buildApprovalIdSubquery("additional_observer", filter.UserID) // 🆕 Доп. наблюдатель
|
||||
|
||||
s1, a1, _ := subQ1.PlaceholderFormat(squirrel.Question).ToSql()
|
||||
s2, a2, _ := subQ2.PlaceholderFormat(squirrel.Question).ToSql()
|
||||
s3, a3, _ := subQ3.PlaceholderFormat(squirrel.Question).ToSql()
|
||||
s4, a4, _ := subQ4.PlaceholderFormat(squirrel.Question).ToSql()
|
||||
s5, a5, _ := subQ5.PlaceholderFormat(squirrel.Question).ToSql() // 🆕
|
||||
s6, a6, _ := subQ6.PlaceholderFormat(squirrel.Question).ToSql() // 🆕
|
||||
|
||||
unionSQL := fmt.Sprintf("(%s) UNION (%s) UNION (%s) UNION (%s)", s1, s2, s3, s4)
|
||||
allArgs := append(append(append(a1, a2...), a3...), a4...)
|
||||
unionSQL := fmt.Sprintf("(%s) UNION (%s) UNION (%s) UNION (%s) UNION (%s) UNION (%s)", s1, s2, s3, s4, s5, s6)
|
||||
|
||||
allArgs := append(append(append(append(append(a1, a2...), a3...), a4...), a5...), a6...)
|
||||
|
||||
q = q.Where(squirrel.Expr("a.id IN ("+unionSQL+")", allArgs...))
|
||||
}
|
||||
|
|
@ -407,18 +575,167 @@ func buildApprovalIdSubquery(role string, userID *uint64) squirrel.SelectBuilder
|
|||
Join(dbcoretablenames.TableNameApprovalTasks.ToString() + " task ON task.approval_id = a.id").
|
||||
Where(squirrel.Eq{"task.executor_id": userID})
|
||||
|
||||
case "additional_approver":
|
||||
return q.
|
||||
Join(dbcoretablenames.TableNameApprovalAdditionalApprovers.ToString() + " aaa ON aaa.approval_id = a.id").
|
||||
Where(squirrel.Eq{"aaa.approver_id": userID})
|
||||
|
||||
case "additional_observer":
|
||||
return q.
|
||||
Join(dbcoretablenames.TableNameApprovalAdditionalObservers.ToString() + " ao ON ao.approval_id = a.id").
|
||||
Where(squirrel.Eq{"ao.user_id": userID})
|
||||
|
||||
case "observer":
|
||||
return q.
|
||||
Join(dbcoretablenames.TableNameApprovalTopics.ToString() + " t ON t.id = a.topic_id").
|
||||
Join(dbcoretablenames.TableNameApprovalTopicCategories.ToString() + " c ON c.id = t.category_id").
|
||||
Join(dbcoretablenames.TableNamePermissions.ToString() + " p ON p.topic_category_id = c.id").
|
||||
Join("user_roles ur ON ur.role_id = p.role_id").
|
||||
Where(squirrel.And{
|
||||
squirrel.Eq{"ur.user_id": userID},
|
||||
squirrel.Eq{"p.action": "observe"},
|
||||
Join(dbcoretablenames.TableNameApprovalTopics.ToString()+" t ON t.id = a.topic_id").
|
||||
Join(dbcoretablenames.TableNameApprovalTopicCategories.ToString()+" c ON c.id = t.category_id").
|
||||
Join(dbcoretablenames.TableNamePermissions.ToString()+" p ON p.role_id IN (SELECT ur.role_id FROM user_roles ur WHERE ur.user_id = ?)", userID).
|
||||
Where(squirrel.Eq{"p.action": "observe"}).
|
||||
Where(squirrel.Or{
|
||||
squirrel.And{
|
||||
squirrel.Expr("p.topic_id IS NULL"),
|
||||
squirrel.Expr("p.topic_category_id = c.id"),
|
||||
},
|
||||
squirrel.Expr("p.topic_id = t.id"),
|
||||
})
|
||||
|
||||
default:
|
||||
return q.Where(squirrel.Expr("false"))
|
||||
}
|
||||
}
|
||||
|
||||
// CountApprovalsDB — подсчёт заявок с фильтром
|
||||
func (u *ApprovalDB) CountApprovalsDB(ctx context.Context, filter *typescore.Approval) (int, error) {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select("COUNT(*)").
|
||||
From(dbcoretablenames.TableNameApprovals.ToString())
|
||||
|
||||
if filter != nil {
|
||||
if filter.Status != nil {
|
||||
query = query.Where(squirrel.Eq{"status": *filter.Status})
|
||||
}
|
||||
}
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
var count int
|
||||
err = u.pool.QueryRow(ctx, sql, args...).Scan(&count)
|
||||
return count, err
|
||||
}
|
||||
|
||||
// CountApprovalsCreatedOnDB — заявки, созданные в определённый день
|
||||
func (u *ApprovalDB) CountApprovalsCreatedOnDB(ctx context.Context, date time.Time) (int, error) {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select("COUNT(*)").
|
||||
From(dbcoretablenames.TableNameApprovals.ToString()).
|
||||
Where("DATE(created_at) = ?", date.Format("2006-01-02"))
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
var count int
|
||||
err = u.pool.QueryRow(ctx, sql, args...).Scan(&count)
|
||||
return count, err
|
||||
}
|
||||
|
||||
// CountApprovalsApprovedOnDB — заявки, согласованные в определённый день
|
||||
func (u *ApprovalDB) CountApprovalsApprovedOnDB(ctx context.Context, date time.Time) (int, error) {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select("COUNT(DISTINCT approval_id)").
|
||||
From(dbcoretablenames.TableNameApprovalSteps.ToString()).
|
||||
Where("DATE(acted_at) = ? AND status = 'approved'", date.Format("2006-01-02"))
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
var count int
|
||||
err = u.pool.QueryRow(ctx, sql, args...).Scan(&count)
|
||||
return count, err
|
||||
}
|
||||
|
||||
// GetTopTopicsDB — топ тем по количеству заявок
|
||||
func (u *ApprovalDB) GetTopTopicsDB(ctx context.Context, limit int) ([]map[string]interface{}, error) {
|
||||
query := `
|
||||
SELECT
|
||||
t.id,
|
||||
t.name,
|
||||
c.name as category_name,
|
||||
COUNT(a.id) as total_count,
|
||||
COUNT(CASE WHEN a.status = 'pending' THEN 1 END) as pending_count
|
||||
FROM approval_topics t
|
||||
LEFT JOIN approval_topic_categories c ON t.category_id = c.id
|
||||
LEFT JOIN approvals a ON a.topic_id = t.id
|
||||
GROUP BY t.id, t.name, c.name
|
||||
ORDER BY total_count DESC
|
||||
LIMIT $1
|
||||
`
|
||||
|
||||
rows, err := u.pool.Query(ctx, query, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var result []map[string]interface{}
|
||||
for rows.Next() {
|
||||
var id uint64
|
||||
var name, categoryName sql.NullString
|
||||
var totalCount, pendingCount int
|
||||
|
||||
if err := rows.Scan(&id, &name, &categoryName, &totalCount, &pendingCount); err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
result = append(result, map[string]interface{}{
|
||||
"id": id,
|
||||
"name": name.String,
|
||||
"category_name": categoryName.String,
|
||||
"total_count": totalCount,
|
||||
"pending_count": pendingCount,
|
||||
})
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// GetOldPendingApprovalsDB — заявки, которые давно висят в pending
|
||||
func (u *ApprovalDB) GetOldPendingApprovalsDB(ctx context.Context, since time.Time, limit int) ([]*typescore.Approval, error) {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select("*").
|
||||
From(dbcoretablenames.TableNameApprovals.ToString()).
|
||||
Where(squirrel.And{
|
||||
squirrel.Eq{"status": "pending"},
|
||||
squirrel.Lt{"created_at": since},
|
||||
}).
|
||||
OrderBy("created_at ASC").
|
||||
Limit(uint64(limit))
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var result []*typescore.Approval
|
||||
for rows.Next() {
|
||||
a := &typescore.Approval{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, a, nil); err != nil {
|
||||
continue
|
||||
}
|
||||
result = append(result, a)
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ import (
|
|||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/sirupsen/logrus"
|
||||
"time"
|
||||
)
|
||||
|
||||
type ApprovalAdditionalApproverDB struct {
|
||||
|
|
@ -76,6 +77,8 @@ func (u *ApprovalAdditionalApproverDB) CreateApprovalAdditionalApproverDB(ctx co
|
|||
|
||||
var insertedID uint64
|
||||
|
||||
now := time.Now().UTC()
|
||||
ApprovalAdditionalApproverObj.CreatedAt = &now
|
||||
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Insert(dbcoretablenames.TableNameApprovalAdditionalApprovers.ToString())
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ import (
|
|||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/sirupsen/logrus"
|
||||
"time"
|
||||
)
|
||||
|
||||
type ApprovalAdditionalObserverDB struct {
|
||||
|
|
@ -76,6 +77,8 @@ func (u *ApprovalAdditionalObserverDB) CreateApprovalAdditionalObserverDB(ctx co
|
|||
|
||||
var insertedID uint64
|
||||
|
||||
now := time.Now().UTC()
|
||||
ApprovalAdditionalObserverObj.CreatedAt = &now
|
||||
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Insert(dbcoretablenames.TableNameApprovalAdditionalObservers.ToString())
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ import (
|
|||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/sirupsen/logrus"
|
||||
"time"
|
||||
)
|
||||
|
||||
type ApprovalCommentDB struct {
|
||||
|
|
@ -77,6 +78,8 @@ func (u *ApprovalCommentDB) CreateApprovalCommentDB(ctx context.Context, tx pgx.
|
|||
|
||||
var insertedID uint64
|
||||
|
||||
now := time.Now().UTC()
|
||||
ApprovalCommentObj.CreatedAt = &now
|
||||
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Insert(dbcoretablenames.TableNameApprovalComments.ToString())
|
||||
|
|
@ -92,18 +95,23 @@ func (u *ApprovalCommentDB) CreateApprovalCommentDB(ctx context.Context, tx pgx.
|
|||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, tx, err
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
returnObjBool := len(returnObj) > 0 && returnObj[0]
|
||||
if returnObjBool && insertedID > 0 {
|
||||
if returnObjBool {
|
||||
if insertedID == 0 {
|
||||
return nil, nil, errors.New("inserted ID is 0 after insert")
|
||||
}
|
||||
created, err := u.GetApprovalCommentByIDDB(ctx, insertedID)
|
||||
return created, tx, err
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return created, nil, nil
|
||||
}
|
||||
|
||||
return nil, tx, nil
|
||||
return nil, nil, nil
|
||||
}
|
||||
|
||||
func (u *ApprovalCommentDB) UpdateApprovalCommentDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalComment, returnObj ...bool) (*typescore.ApprovalComment, pgx.Tx, error) {
|
||||
if paramsUpdate.ID == nil {
|
||||
return nil, nil, errors.New("ApprovalComment obj is nil")
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ import (
|
|||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/sirupsen/logrus"
|
||||
"time"
|
||||
)
|
||||
|
||||
type ApprovalFileDB struct {
|
||||
|
|
@ -29,6 +30,8 @@ type ApprovalFileDBI interface {
|
|||
DeleteApprovalFileDB(ctx context.Context, params *typescore.ApprovalFile) error
|
||||
GetFilesByApprovalIDDB(ctx context.Context, id uint64) ([]*typescore.ApprovalFile, error)
|
||||
GetApprovalFileByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalFile, error)
|
||||
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) {
|
||||
|
|
@ -77,6 +80,8 @@ func (u *ApprovalFileDB) CreateApprovalFileDB(ctx context.Context, tx pgx.Tx, Ap
|
|||
|
||||
var insertedID uint64
|
||||
|
||||
now := time.Now().UTC()
|
||||
ApprovalFileObj.CreatedAt = &now
|
||||
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Insert(dbcoretablenames.TableNameApprovalFiles.ToString())
|
||||
|
|
@ -184,16 +189,16 @@ func (u *ApprovalFileDB) GetFilesByApprovalIDDB(ctx context.Context, id uint64)
|
|||
}
|
||||
|
||||
func (u *ApprovalFileDB) GetApprovalFileByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalFile, error) {
|
||||
approvals, _, err := u.GetApprovalFilesListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.Approval{ID: &id},
|
||||
files, _, err := u.GetApprovalFilesListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.ApprovalFile{ID: &id},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(approvals) == 0 {
|
||||
if len(files) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return approvals[0], nil
|
||||
return files[0], nil
|
||||
}
|
||||
|
||||
// queryApprovalFiles — общий сканер строк
|
||||
|
|
@ -215,3 +220,52 @@ func (u *ApprovalFileDB) queryApprovalFiles(ctx context.Context, sql string, arg
|
|||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (u *ApprovalFileDB) GetFilesByTaskIDDB(ctx context.Context, taskID uint64) ([]*typescore.ApprovalFile, error) {
|
||||
files, _, err := u.GetApprovalFilesListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.ApprovalFile{TaskID: &taskID},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,175 @@
|
|||
package dbcore
|
||||
|
||||
import (
|
||||
dbcoretablenames "bitrix_balancer_api/core/db/table_names"
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
dbutils "bitrix_balancer_api/core/utilscore/db"
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type ApprovalFlowNodeDB struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewApprovalFlowNodeDB(pool *pgxpool.Pool) *ApprovalFlowNodeDB {
|
||||
return &ApprovalFlowNodeDB{pool: pool}
|
||||
}
|
||||
|
||||
type ApprovalFlowNodeDBI interface {
|
||||
GetApprovalFlowNodesListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.ApprovalFlowNode, uint64, error)
|
||||
CreateApprovalFlowNodeDB(ctx context.Context, tx pgx.Tx, node *typescore.ApprovalFlowNode, returnObj ...bool) (*typescore.ApprovalFlowNode, pgx.Tx, error)
|
||||
UpdateApprovalFlowNodeDB(ctx context.Context, tx pgx.Tx, node *typescore.ApprovalFlowNode, returnObj ...bool) (*typescore.ApprovalFlowNode, pgx.Tx, error)
|
||||
DeleteApprovalFlowNodeDB(ctx context.Context, node *typescore.ApprovalFlowNode) error
|
||||
DeleteFlowNodesByCategoryIDDB(ctx context.Context, catID uint64) error
|
||||
GetFlowNodeByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalFlowNode, error)
|
||||
}
|
||||
|
||||
func (u *ApprovalFlowNodeDB) GetApprovalFlowNodesListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalFlowNode, uint64, error) {
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.ApprovalFlowNode{}, dbcoretablenames.TableNameApprovalFlowNodes.ToString())
|
||||
selectFields := append(fields, "COUNT(*) OVER() AS total_count")
|
||||
|
||||
options, filter, err := dbutils.GetOptionsDB[typescore.ApprovalFlowNode](opts...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovalFlowNodes.ToString(), selectFields)
|
||||
query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
|
||||
query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovalFlowNodes.ToString())
|
||||
query = query.OrderBy("sort_order ASC, id ASC")
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var nodes []*typescore.ApprovalFlowNode
|
||||
var totalCount uint64
|
||||
for rows.Next() {
|
||||
node := &typescore.ApprovalFlowNode{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, node, &totalCount); err != nil {
|
||||
continue
|
||||
}
|
||||
nodes = append(nodes, node)
|
||||
}
|
||||
|
||||
return nodes, totalCount, nil
|
||||
}
|
||||
|
||||
func (u *ApprovalFlowNodeDB) CreateApprovalFlowNodeDB(ctx context.Context, tx pgx.Tx, node *typescore.ApprovalFlowNode, returnObj ...bool) (*typescore.ApprovalFlowNode, pgx.Tx, error) {
|
||||
if node == nil {
|
||||
return nil, nil, errors.New("node is nil")
|
||||
}
|
||||
|
||||
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Insert(dbcoretablenames.TableNameApprovalFlowNodes.ToString())
|
||||
|
||||
sqlV, args, err := dbutils.GenerateInsertRequest(query, node)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, *sqlV, args...)
|
||||
return err
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, tx, err
|
||||
}
|
||||
|
||||
if len(returnObj) > 0 && returnObj[0] {
|
||||
nodes, _, _ := u.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{Filtering: node})
|
||||
if len(nodes) > 0 {
|
||||
return nodes[0], tx, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, tx, nil
|
||||
}
|
||||
|
||||
func (u *ApprovalFlowNodeDB) UpdateApprovalFlowNodeDB(ctx context.Context, tx pgx.Tx, node *typescore.ApprovalFlowNode, returnObj ...bool) (*typescore.ApprovalFlowNode, pgx.Tx, error) {
|
||||
if node == nil || node.ID == nil {
|
||||
return nil, nil, errors.New("node or node.ID is nil")
|
||||
}
|
||||
|
||||
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Update(dbcoretablenames.TableNameApprovalFlowNodes.ToString())
|
||||
query = dbutils.AddNonNullFieldsToQueryUpdate(query, *node)
|
||||
query = query.Where(squirrel.Eq{"id": node.ID})
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, sql, args...)
|
||||
return err
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, tx, err
|
||||
}
|
||||
|
||||
if len(returnObj) > 0 && returnObj[0] {
|
||||
updated, _ := u.GetFlowNodeByIDDB(ctx, *node.ID)
|
||||
return updated, tx, nil
|
||||
}
|
||||
|
||||
return nil, tx, nil
|
||||
}
|
||||
|
||||
func (u *ApprovalFlowNodeDB) DeleteApprovalFlowNodeDB(ctx context.Context, node *typescore.ApprovalFlowNode) error {
|
||||
if node == nil || node.ID == nil {
|
||||
return errors.New("node or node.ID is nil")
|
||||
}
|
||||
|
||||
query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Delete(dbcoretablenames.TableNameApprovalFlowNodes.ToString()).
|
||||
Where(squirrel.Eq{"id": *node.ID}).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = u.pool.Exec(ctx, query, args...)
|
||||
return err
|
||||
}
|
||||
|
||||
func (u *ApprovalFlowNodeDB) DeleteFlowNodesByCategoryIDDB(ctx context.Context, catID uint64) error {
|
||||
query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Delete(dbcoretablenames.TableNameApprovalFlowNodes.ToString()).
|
||||
Where(squirrel.Eq{"category_id": catID}).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = u.pool.Exec(ctx, query, args...)
|
||||
return err
|
||||
}
|
||||
|
||||
func (u *ApprovalFlowNodeDB) GetFlowNodeByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalFlowNode, error) {
|
||||
nodes, _, err := u.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.ApprovalFlowNode{ID: &id},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(nodes) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return nodes[0], nil
|
||||
}
|
||||
|
|
@ -0,0 +1,215 @@
|
|||
package dbcore
|
||||
|
||||
import (
|
||||
dbcoretablenames "bitrix_balancer_api/core/db/table_names"
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
dbutils "bitrix_balancer_api/core/utilscore/db"
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type ApprovalRevocationDB struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewApprovalRevocationDB(pool *pgxpool.Pool) *ApprovalRevocationDB {
|
||||
return &ApprovalRevocationDB{pool: pool}
|
||||
}
|
||||
|
||||
type ApprovalRevocationDBI interface {
|
||||
CreateRevocationRequestDB(ctx context.Context, obj *typescore.ApprovalRevocationRequest, returnObj ...bool) (*typescore.ApprovalRevocationRequest, error)
|
||||
UpdateRevocationRequestDB(ctx context.Context, obj *typescore.ApprovalRevocationRequest, returnObj ...bool) (*typescore.ApprovalRevocationRequest, error)
|
||||
GetRevocationRequestByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalRevocationRequest, error)
|
||||
GetPendingRevocationRequestForApprovalDB(ctx context.Context, approvalID uint64) (*typescore.ApprovalRevocationRequest, error)
|
||||
|
||||
CreateRevocationApproversDB(ctx context.Context, approvers []*typescore.ApprovalRevocationApprover) error
|
||||
UpdateRevocationApproverDB(ctx context.Context, obj *typescore.ApprovalRevocationApprover) error
|
||||
GetRevocationApproversByRequestIDDB(ctx context.Context, requestID uint64) ([]*typescore.ApprovalRevocationApprover, error)
|
||||
GetRevocationApproverForUserDB(ctx context.Context, requestID uint64, approverID uint64) (*typescore.ApprovalRevocationApprover, error)
|
||||
}
|
||||
|
||||
func (d *ApprovalRevocationDB) CreateRevocationRequestDB(ctx context.Context, obj *typescore.ApprovalRevocationRequest, returnObj ...bool) (*typescore.ApprovalRevocationRequest, error) {
|
||||
if obj == nil {
|
||||
return nil, errors.New("revocation request obj is nil")
|
||||
}
|
||||
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Insert(dbcoretablenames.TableNameApprovalRevocationRequests.ToString())
|
||||
|
||||
sqlV, args, err := dbutils.GenerateInsertRequest(query, obj)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
*sqlV = *sqlV + " RETURNING id"
|
||||
|
||||
var insertedID uint64
|
||||
if err := d.pool.QueryRow(ctx, *sqlV, args...).Scan(&insertedID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if len(returnObj) > 0 && returnObj[0] {
|
||||
return d.GetRevocationRequestByIDDB(ctx, insertedID)
|
||||
}
|
||||
obj.ID = &insertedID
|
||||
return obj, nil
|
||||
}
|
||||
|
||||
func (d *ApprovalRevocationDB) UpdateRevocationRequestDB(ctx context.Context, obj *typescore.ApprovalRevocationRequest, returnObj ...bool) (*typescore.ApprovalRevocationRequest, error) {
|
||||
if obj.ID == nil {
|
||||
return nil, errors.New("revocation request id is nil")
|
||||
}
|
||||
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Update(dbcoretablenames.TableNameApprovalRevocationRequests.ToString())
|
||||
query = dbutils.AddNonNullFieldsToQueryUpdate(query, *obj)
|
||||
query = query.Where(squirrel.Eq{"id": obj.ID})
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := d.pool.Exec(ctx, sql, args...); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if len(returnObj) > 0 && returnObj[0] {
|
||||
return d.GetRevocationRequestByIDDB(ctx, *obj.ID)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (d *ApprovalRevocationDB) getRevocationRequestListDB(ctx context.Context, opts typescore.ListDbOptions) ([]*typescore.ApprovalRevocationRequest, error) {
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.ApprovalRevocationRequest{}, dbcoretablenames.TableNameApprovalRevocationRequests.ToString())
|
||||
query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovalRevocationRequests.ToString(), fields)
|
||||
|
||||
options, filter, err := dbutils.GetOptionsDB[typescore.ApprovalRevocationRequest](opts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovalRevocationRequests.ToString())
|
||||
query = query.OrderBy("created_at DESC")
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err := d.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var result []*typescore.ApprovalRevocationRequest
|
||||
for rows.Next() {
|
||||
obj := &typescore.ApprovalRevocationRequest{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, obj, nil); err != nil {
|
||||
logrus.Warn("getRevocationRequestListDB:ScanRowsToStructRows", err)
|
||||
continue
|
||||
}
|
||||
result = append(result, obj)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (d *ApprovalRevocationDB) GetRevocationRequestByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalRevocationRequest, error) {
|
||||
list, err := d.getRevocationRequestListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.ApprovalRevocationRequest{ID: &id},
|
||||
})
|
||||
if err != nil || len(list) == 0 {
|
||||
return nil, err
|
||||
}
|
||||
return list[0], nil
|
||||
}
|
||||
|
||||
func (d *ApprovalRevocationDB) GetPendingRevocationRequestForApprovalDB(ctx context.Context, approvalID uint64) (*typescore.ApprovalRevocationRequest, error) {
|
||||
pendingStatus := "pending"
|
||||
list, err := d.getRevocationRequestListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.ApprovalRevocationRequest{ApprovalID: &approvalID, Status: &pendingStatus},
|
||||
})
|
||||
if err != nil || len(list) == 0 {
|
||||
return nil, err
|
||||
}
|
||||
return list[0], nil
|
||||
}
|
||||
|
||||
func (d *ApprovalRevocationDB) CreateRevocationApproversDB(ctx context.Context, approvers []*typescore.ApprovalRevocationApprover) error {
|
||||
if len(approvers) == 0 {
|
||||
return nil
|
||||
}
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Insert(dbcoretablenames.TableNameApprovalRevocationApprovers.ToString()).
|
||||
Columns("revocation_request_id", "approver_id", "status")
|
||||
|
||||
for _, a := range approvers {
|
||||
query = query.Values(*a.RevocationRequestID, *a.ApproverID, *a.Status)
|
||||
}
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = d.pool.Exec(ctx, sql, args...)
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *ApprovalRevocationDB) UpdateRevocationApproverDB(ctx context.Context, obj *typescore.ApprovalRevocationApprover) error {
|
||||
if obj.ID == nil {
|
||||
return errors.New("revocation approver id is nil")
|
||||
}
|
||||
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Update(dbcoretablenames.TableNameApprovalRevocationApprovers.ToString())
|
||||
query = dbutils.AddNonNullFieldsToQueryUpdate(query, *obj)
|
||||
query = query.Where(squirrel.Eq{"id": obj.ID})
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = d.pool.Exec(ctx, sql, args...)
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *ApprovalRevocationDB) GetRevocationApproversByRequestIDDB(ctx context.Context, requestID uint64) ([]*typescore.ApprovalRevocationApprover, error) {
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.ApprovalRevocationApprover{}, dbcoretablenames.TableNameApprovalRevocationApprovers.ToString())
|
||||
query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovalRevocationApprovers.ToString(), fields).
|
||||
Where(squirrel.Eq{"revocation_request_id": requestID})
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err := d.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var result []*typescore.ApprovalRevocationApprover
|
||||
for rows.Next() {
|
||||
obj := &typescore.ApprovalRevocationApprover{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, obj, nil); err != nil {
|
||||
continue
|
||||
}
|
||||
result = append(result, obj)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (d *ApprovalRevocationDB) GetRevocationApproverForUserDB(ctx context.Context, requestID uint64, approverID uint64) (*typescore.ApprovalRevocationApprover, error) {
|
||||
all, err := d.GetRevocationApproversByRequestIDDB(ctx, requestID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, a := range all {
|
||||
if a.ApproverID != nil && *a.ApproverID == approverID {
|
||||
return a, nil
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
|
@ -7,6 +7,7 @@ import (
|
|||
"context"
|
||||
"errors"
|
||||
"github.com/sirupsen/logrus"
|
||||
"time"
|
||||
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
|
@ -31,6 +32,7 @@ type ApprovalStepDBI interface {
|
|||
|
||||
GetActiveStepDB(ctx context.Context, approvalID uint64) (*typescore.ApprovalStep, error)
|
||||
GetNextStepDB(ctx context.Context, approvalID uint64, currentOrder int) (*typescore.ApprovalStep, error)
|
||||
GetApprovalStepsByApprovalIDsDB(ctx context.Context, approvalIDs []uint64) ([]*typescore.ApprovalStep, error)
|
||||
}
|
||||
|
||||
func (u *ApprovalStepDB) GetApprovalStepsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalStep, uint64, error) {
|
||||
|
|
@ -77,6 +79,8 @@ func (u *ApprovalStepDB) CreateApprovalStepDB(ctx context.Context, tx pgx.Tx, Ap
|
|||
return nil, nil, errors.New("ApprovalStep obj is nil")
|
||||
}
|
||||
|
||||
now := time.Now().UTC()
|
||||
ApprovalStepObj.CreatedAt = &now
|
||||
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Insert(dbcoretablenames.TableNameApprovalSteps.ToString())
|
||||
|
||||
|
|
@ -119,6 +123,8 @@ func (u *ApprovalStepDB) UpdateApprovalStepDB(ctx context.Context, tx pgx.Tx, pa
|
|||
return nil, nil, errors.New("ApprovalStep obj is nil")
|
||||
}
|
||||
|
||||
now := time.Now().UTC()
|
||||
paramsUpdate.UpdatedAt = &now
|
||||
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameApprovalSteps.ToString())
|
||||
query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate)
|
||||
|
|
@ -232,3 +238,43 @@ func (u *ApprovalStepDB) GetNextStepDB(ctx context.Context, approvalID uint64, c
|
|||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// GetApprovalStepsByApprovalIDsDB — пакетное получение шагов сразу для нескольких заявок (устраняет N+1)
|
||||
func (a *ApprovalStepDB) GetApprovalStepsByApprovalIDsDB(ctx context.Context, approvalIDs []uint64) ([]*typescore.ApprovalStep, error) {
|
||||
if len(approvalIDs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.ApprovalStep{}, dbcoretablenames.TableNameApprovalSteps.ToString())
|
||||
|
||||
sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select(fields...).
|
||||
From(dbcoretablenames.TableNameApprovalSteps.ToString()).
|
||||
Where(squirrel.Eq{"approval_id": approvalIDs}).
|
||||
OrderBy("step_order ASC").
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err := a.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var steps []*typescore.ApprovalStep
|
||||
for rows.Next() {
|
||||
st := &typescore.ApprovalStep{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, st, nil); err != nil {
|
||||
logrus.Warn("GetApprovalStepsByApprovalIDsDB:ScanRowsToStructRows", err)
|
||||
continue
|
||||
}
|
||||
steps = append(steps, st)
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return steps, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ import (
|
|||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/sirupsen/logrus"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
|
|
@ -45,6 +46,28 @@ func (u *ApprovalTaskDB) GetApprovalTasksListDB(ctx context.Context, opts ...typ
|
|||
query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovalTasks.ToString(), selectFields)
|
||||
query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
|
||||
query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovalTasks.ToString())
|
||||
|
||||
if filter != nil && filter.ObserverUserID != nil {
|
||||
subQ1 := buildApprovalIdSubquery("initiator", filter.ObserverUserID)
|
||||
subQ2 := buildApprovalIdSubquery("approver", filter.ObserverUserID)
|
||||
subQ3 := buildApprovalIdSubquery("observer", filter.ObserverUserID)
|
||||
subQ4 := buildApprovalIdSubquery("executor", filter.ObserverUserID)
|
||||
subQ5 := buildApprovalIdSubquery("additional_approver", filter.ObserverUserID)
|
||||
subQ6 := buildApprovalIdSubquery("additional_observer", filter.ObserverUserID)
|
||||
|
||||
s1, a1, _ := subQ1.PlaceholderFormat(squirrel.Question).ToSql()
|
||||
s2, a2, _ := subQ2.PlaceholderFormat(squirrel.Question).ToSql()
|
||||
s3, a3, _ := subQ3.PlaceholderFormat(squirrel.Question).ToSql()
|
||||
s4, a4, _ := subQ4.PlaceholderFormat(squirrel.Question).ToSql()
|
||||
s5, a5, _ := subQ5.PlaceholderFormat(squirrel.Question).ToSql()
|
||||
s6, a6, _ := subQ6.PlaceholderFormat(squirrel.Question).ToSql()
|
||||
|
||||
unionSQL := fmt.Sprintf("(%s) UNION (%s) UNION (%s) UNION (%s) UNION (%s) UNION (%s)", s1, s2, s3, s4, s5, s6)
|
||||
allArgs := append(append(append(append(append(a1, a2...), a3...), a4...), a5...), a6...)
|
||||
|
||||
query = query.Where(squirrel.Expr(dbcoretablenames.TableNameApprovalTasks.ToString()+".approval_id IN ("+unionSQL+")", allArgs...))
|
||||
}
|
||||
|
||||
query = query.OrderBy("created_at DESC")
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
|
|
@ -71,7 +94,6 @@ func (u *ApprovalTaskDB) GetApprovalTasksListDB(ctx context.Context, opts ...typ
|
|||
|
||||
return ApprovalTasks, totalCount, nil
|
||||
}
|
||||
|
||||
func (u *ApprovalTaskDB) CreateApprovalTaskDB(ctx context.Context, tx pgx.Tx, ApprovalTaskObj *typescore.ApprovalTask, returnObj ...bool) (*typescore.ApprovalTask, pgx.Tx, error) {
|
||||
if ApprovalTaskObj == nil {
|
||||
return nil, nil, errors.New("ApprovalTask obj is nil")
|
||||
|
|
@ -79,7 +101,44 @@ func (u *ApprovalTaskDB) CreateApprovalTaskDB(ctx context.Context, tx pgx.Tx, Ap
|
|||
|
||||
var insertedID uint64
|
||||
|
||||
now := time.Now().UTC()
|
||||
ApprovalTaskObj.CreatedAt = &now
|
||||
|
||||
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
|
||||
// Автоматически дополняем текст задачи номером и текстом заявки перед сохранением в БД
|
||||
if ApprovalTaskObj.ApprovalID != nil {
|
||||
var approvalContent *string
|
||||
err := tx.QueryRow(
|
||||
ctx,
|
||||
"SELECT content FROM approvals WHERE id = $1",
|
||||
*ApprovalTaskObj.ApprovalID,
|
||||
).Scan(&approvalContent)
|
||||
|
||||
if err == nil {
|
||||
contentStr := "—"
|
||||
if approvalContent != nil && *approvalContent != "" {
|
||||
contentStr = *approvalContent
|
||||
}
|
||||
|
||||
origTaskText := ""
|
||||
if ApprovalTaskObj.TaskText != nil {
|
||||
origTaskText = *ApprovalTaskObj.TaskText
|
||||
}
|
||||
|
||||
// Проверяем, чтобы не задублировать, если номер заявки уже есть в тексте
|
||||
checkHeader := fmt.Sprintf("Заявка #%d", *ApprovalTaskObj.ApprovalID)
|
||||
if !strings.Contains(origTaskText, checkHeader) {
|
||||
enrichedText := fmt.Sprintf(
|
||||
"Заявка #%d\nТекст заявки: %s\n\nЗадача:\n%s",
|
||||
*ApprovalTaskObj.ApprovalID,
|
||||
contentStr,
|
||||
origTaskText,
|
||||
)
|
||||
ApprovalTaskObj.TaskText = &enrichedText
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Insert(dbcoretablenames.TableNameApprovalTasks.ToString())
|
||||
|
||||
|
|
@ -163,11 +222,10 @@ func (u *ApprovalTaskDB) DeleteApprovalTaskDB(ctx context.Context, params *types
|
|||
return err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, query, args...)
|
||||
_, err = u.pool.Exec(ctx, query, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
return nil
|
||||
} else {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,151 @@
|
|||
package dbcore
|
||||
|
||||
import (
|
||||
dbcoretablenames "bitrix_balancer_api/core/db/table_names"
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
dbutils "bitrix_balancer_api/core/utilscore/db"
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type ApprovalTaskTransferDB struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewApprovalTaskTransferDB(pool *pgxpool.Pool) *ApprovalTaskTransferDB {
|
||||
return &ApprovalTaskTransferDB{pool: pool}
|
||||
}
|
||||
|
||||
type ApprovalTaskTransferDBI interface {
|
||||
GetApprovalTaskTransferListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalTaskTransfer, uint64, error)
|
||||
CreateApprovalTaskTransferDB(ctx context.Context, obj *typescore.ApprovalTaskTransfer, returnObj ...bool) (*typescore.ApprovalTaskTransfer, error)
|
||||
UpdateApprovalTaskTransferDB(ctx context.Context, paramsUpdate *typescore.ApprovalTaskTransfer, returnObj ...bool) (*typescore.ApprovalTaskTransfer, error)
|
||||
GetApprovalTaskTransferByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalTaskTransfer, error)
|
||||
GetPendingTransferForTaskDB(ctx context.Context, taskID uint64) (*typescore.ApprovalTaskTransfer, error)
|
||||
}
|
||||
|
||||
func (u *ApprovalTaskTransferDB) GetApprovalTaskTransferListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalTaskTransfer, uint64, error) {
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.ApprovalTaskTransfer{}, dbcoretablenames.TableNameApprovalTaskTransfers.ToString())
|
||||
selectFields := append(fields, "COUNT(*) OVER() AS total_count")
|
||||
|
||||
options, filter, err := dbutils.GetOptionsDB[typescore.ApprovalTaskTransfer](opts...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovalTaskTransfers.ToString(), selectFields)
|
||||
query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
|
||||
query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovalTaskTransfers.ToString())
|
||||
query = query.OrderBy("created_at DESC")
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var result []*typescore.ApprovalTaskTransfer
|
||||
var totalCount uint64
|
||||
for rows.Next() {
|
||||
obj := &typescore.ApprovalTaskTransfer{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, obj, &totalCount); err != nil {
|
||||
logrus.Warn("GetApprovalTaskTransferListDB:ScanRowsToStructRows", err)
|
||||
continue
|
||||
}
|
||||
result = append(result, obj)
|
||||
}
|
||||
|
||||
return result, totalCount, nil
|
||||
}
|
||||
|
||||
func (u *ApprovalTaskTransferDB) CreateApprovalTaskTransferDB(ctx context.Context, obj *typescore.ApprovalTaskTransfer, returnObj ...bool) (*typescore.ApprovalTaskTransfer, error) {
|
||||
if obj == nil {
|
||||
return nil, errors.New("approval task transfer obj is nil")
|
||||
}
|
||||
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Insert(dbcoretablenames.TableNameApprovalTaskTransfers.ToString())
|
||||
|
||||
sqlV, args, err := dbutils.GenerateInsertRequest(query, obj)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
*sqlV = *sqlV + " RETURNING id"
|
||||
|
||||
var insertedID uint64
|
||||
if err := u.pool.QueryRow(ctx, *sqlV, args...).Scan(&insertedID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
returnObjBool := len(returnObj) > 0 && returnObj[0]
|
||||
if returnObjBool && insertedID > 0 {
|
||||
return u.GetApprovalTaskTransferByIDDB(ctx, insertedID)
|
||||
}
|
||||
|
||||
obj.ID = &insertedID
|
||||
return obj, nil
|
||||
}
|
||||
|
||||
func (u *ApprovalTaskTransferDB) UpdateApprovalTaskTransferDB(ctx context.Context, paramsUpdate *typescore.ApprovalTaskTransfer, returnObj ...bool) (*typescore.ApprovalTaskTransfer, error) {
|
||||
if paramsUpdate.ID == nil {
|
||||
return nil, errors.New("approval task transfer obj is nil")
|
||||
}
|
||||
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Update(dbcoretablenames.TableNameApprovalTaskTransfers.ToString())
|
||||
query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate)
|
||||
query = query.Where(squirrel.Eq{"id": paramsUpdate.ID})
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if _, err := u.pool.Exec(ctx, sql, args...); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
returnObjBool := len(returnObj) > 0 && returnObj[0]
|
||||
if returnObjBool {
|
||||
return u.GetApprovalTaskTransferByIDDB(ctx, *paramsUpdate.ID)
|
||||
}
|
||||
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (u *ApprovalTaskTransferDB) GetApprovalTaskTransferByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalTaskTransfer, error) {
|
||||
list, _, err := u.GetApprovalTaskTransferListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.ApprovalTaskTransfer{ID: &id},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(list) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return list[0], nil
|
||||
}
|
||||
|
||||
// GetPendingTransferForTaskDB — есть ли уже незакрытый запрос по этой задаче (защита от дублей)
|
||||
func (u *ApprovalTaskTransferDB) GetPendingTransferForTaskDB(ctx context.Context, taskID uint64) (*typescore.ApprovalTaskTransfer, error) {
|
||||
pendingStatus := "pending"
|
||||
list, _, err := u.GetApprovalTaskTransferListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.ApprovalTaskTransfer{TaskID: &taskID, Status: &pendingStatus},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(list) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return list[0], nil
|
||||
}
|
||||
|
|
@ -31,6 +31,7 @@ type ApprovalTopicDBI interface {
|
|||
|
||||
GetApprovalTopicByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalTopic, error)
|
||||
GetApprovalTopicByCodeDB(ctx context.Context, code string) (*typescore.ApprovalTopic, error)
|
||||
GetApprovalTopicsByIDsDB(ctx context.Context, ids []uint64) ([]*typescore.ApprovalTopic, error)
|
||||
}
|
||||
|
||||
func (u *ApprovalTopicDB) GetApprovalTopicsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalTopic, uint64, error) {
|
||||
|
|
@ -208,3 +209,42 @@ func (u *ApprovalTopicDB) GetApprovalTopicByCodeDB(ctx context.Context, code str
|
|||
}
|
||||
return topics[0], nil
|
||||
}
|
||||
|
||||
// GetApprovalTopicsByIDsDB — пакетное получение тем по списку ID (устраняет N+1)
|
||||
func (u *ApprovalTopicDB) GetApprovalTopicsByIDsDB(ctx context.Context, ids []uint64) ([]*typescore.ApprovalTopic, error) {
|
||||
if len(ids) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.ApprovalTopic{}, dbcoretablenames.TableNameApprovalTopics.ToString())
|
||||
|
||||
sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select(fields...).
|
||||
From(dbcoretablenames.TableNameApprovalTopics.ToString()).
|
||||
Where(squirrel.Eq{"id": ids}).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var topics []*typescore.ApprovalTopic
|
||||
for rows.Next() {
|
||||
topic := &typescore.ApprovalTopic{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, topic, nil); err != nil {
|
||||
logrus.Warn("GetApprovalTopicsByIDsDB:ScanRowsToStructRows", err)
|
||||
continue
|
||||
}
|
||||
topics = append(topics, topic)
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return topics, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -35,6 +35,7 @@ type ApprovalTopicCategoryDBI interface {
|
|||
initiatorID uint64,
|
||||
) ([]*typescore.ApprovalTopicCategory, error)
|
||||
GetCategoriesWithApprovalsByApproverDB(ctx context.Context, approverID uint64) ([]*typescore.ApprovalTopicCategory, error)
|
||||
GetApprovalTopicCategoriesByIDsDB(ctx context.Context, ids []uint64) ([]*typescore.ApprovalTopicCategory, error)
|
||||
}
|
||||
|
||||
// GetCategoriesWithApprovalsByInitiatorDB — категории тем, по которым у инициатора есть заявки
|
||||
|
|
@ -286,3 +287,42 @@ func (u *ApprovalTopicCategoryDB) GetApprovalTopicCategoryByCodeDB(ctx context.C
|
|||
}
|
||||
return categories[0], nil
|
||||
}
|
||||
|
||||
// GetApprovalTopicCategoriesByIDsDB — пакетное получение категорий по списку ID (устраняет N+1)
|
||||
func (u *ApprovalTopicCategoryDB) GetApprovalTopicCategoriesByIDsDB(ctx context.Context, ids []uint64) ([]*typescore.ApprovalTopicCategory, error) {
|
||||
if len(ids) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.ApprovalTopicCategory{}, dbcoretablenames.TableNameApprovalTopicCategories.ToString())
|
||||
|
||||
sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select(fields...).
|
||||
From(dbcoretablenames.TableNameApprovalTopicCategories.ToString()).
|
||||
Where(squirrel.Eq{"id": ids}).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var categories []*typescore.ApprovalTopicCategory
|
||||
for rows.Next() {
|
||||
category := &typescore.ApprovalTopicCategory{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, category, nil); err != nil {
|
||||
logrus.Warn("GetApprovalTopicCategoriesByIDsDB:ScanRowsToStructRows", err)
|
||||
continue
|
||||
}
|
||||
categories = append(categories, category)
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return categories, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -27,6 +27,210 @@ type ApprovalTopicExecutorDBI interface {
|
|||
UpdateApprovalTopicExecutorDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalTopicExecutor, returnObj ...bool) (*typescore.ApprovalTopicExecutor, pgx.Tx, error)
|
||||
DeleteApprovalTopicExecutorDB(ctx context.Context, params *typescore.ApprovalTopicExecutor) error
|
||||
GetExecutorsByTopicIDDB(ctx context.Context, topicID uint64) ([]*typescore.ApprovalTopicExecutor, error)
|
||||
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) {
|
||||
options, filter, err := dbutils.GetOptionsDB[typescore.ApprovalTopicExecutor](opts)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
query := squirrel.Select(
|
||||
"ate.*",
|
||||
"u.id", "u.full_name", "u.username",
|
||||
"t.id", "t.name",
|
||||
"COUNT(*) OVER() AS total_count",
|
||||
).
|
||||
From("approval_topic_executors ate").
|
||||
LeftJoin("users u ON ate.user_id = u.id").
|
||||
LeftJoin("approval_topics t ON ate.topic_id = t.id")
|
||||
|
||||
query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
|
||||
query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovalTopicExecutor.ToString())
|
||||
query = query.OrderBy("step_order ASC, id ASC")
|
||||
|
||||
sql, args, err := query.PlaceholderFormat(squirrel.Dollar).ToSql()
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
rows, err := d.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var results []*typescore.ApprovalTopicExecutor
|
||||
var totalCount uint64
|
||||
|
||||
for rows.Next() {
|
||||
exec := &typescore.ApprovalTopicExecutor{}
|
||||
exec.User = &typescore.User{}
|
||||
exec.Topic = &typescore.ApprovalTopic{}
|
||||
|
||||
err := rows.Scan(
|
||||
&exec.ID, &exec.TopicID, &exec.UserID, &exec.StepOrder, &exec.RequireFile, &exec.IsActive, &exec.CreatedAt, &exec.UpdatedAt,
|
||||
&exec.User.ID, &exec.User.FullName, &exec.User.Username,
|
||||
&exec.Topic.ID, &exec.Topic.Name,
|
||||
&totalCount,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
results = append(results, exec)
|
||||
}
|
||||
|
||||
return results, totalCount, nil
|
||||
}
|
||||
|
||||
func (d *ApprovalTopicExecutorDB) GetApprovalTopicExecutorListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalTopicExecutor, uint64, error) {
|
||||
|
|
@ -161,7 +365,7 @@ func (d *ApprovalTopicExecutorDB) DeleteApprovalTopicExecutorDB(ctx context.Cont
|
|||
return err
|
||||
}
|
||||
|
||||
_, err = d.pool.Query(ctx, query, args...)
|
||||
_, err = d.pool.Exec(ctx, query, args...)
|
||||
return err
|
||||
}
|
||||
return errors.New("ApprovalTopicExecutor obj is nil")
|
||||
|
|
|
|||
|
|
@ -29,6 +29,7 @@ type DepartmentDBI interface {
|
|||
UpdateDepartmentDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.Department, returnObj ...bool) (*typescore.Department, pgx.Tx, error)
|
||||
DeleteDepartmentDB(ctx context.Context, params *typescore.Department) error
|
||||
GetDepartmentByIDDB(ctx context.Context, id uint64) (*typescore.Department, error)
|
||||
GetDepartmentsByIDsDB(ctx context.Context, ids []uint64) ([]*typescore.Department, error)
|
||||
}
|
||||
|
||||
func (u *DepartmentDB) GetDepartmentsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.Department, uint64, error) {
|
||||
|
|
@ -169,11 +170,10 @@ func (u *DepartmentDB) DeleteDepartmentDB(ctx context.Context, params *typescore
|
|||
return err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, query, args...)
|
||||
_, err = u.pool.Exec(ctx, query, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
return nil
|
||||
} else {
|
||||
|
|
@ -190,3 +190,42 @@ func (u *DepartmentDB) GetDepartmentByIDDB(ctx context.Context, id uint64) (*typ
|
|||
}
|
||||
return deps[0], nil
|
||||
}
|
||||
|
||||
// GetDepartmentsByIDsDB — пакетное получение отделов по списку ID (устраняет N+1)
|
||||
func (d *DepartmentDB) GetDepartmentsByIDsDB(ctx context.Context, ids []uint64) ([]*typescore.Department, error) {
|
||||
if len(ids) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.Department{}, dbcoretablenames.TableNameDepartments.ToString())
|
||||
|
||||
sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select(fields...).
|
||||
From(dbcoretablenames.TableNameDepartments.ToString()).
|
||||
Where(squirrel.Eq{"id": ids}).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err := d.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var departments []*typescore.Department
|
||||
for rows.Next() {
|
||||
dep := &typescore.Department{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, dep, nil); err != nil {
|
||||
logrus.Warn("GetDepartmentsByIDsDB:ScanRowsToStructRows", err)
|
||||
continue
|
||||
}
|
||||
departments = append(departments, dep)
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return departments, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,126 @@
|
|||
package dbcore
|
||||
|
||||
import (
|
||||
dbcoretablenames "bitrix_balancer_api/core/db/table_names"
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
dbutils "bitrix_balancer_api/core/utilscore/db"
|
||||
"context"
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type DirectorNotificationDB struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewDirectorNotificationDB(pool *pgxpool.Pool) *DirectorNotificationDB {
|
||||
return &DirectorNotificationDB{pool: pool}
|
||||
}
|
||||
|
||||
type DirectorNotificationDBI interface {
|
||||
GetSubscribedCategoryIDsDB(ctx context.Context, directorID uint64) ([]uint64, error)
|
||||
ToggleSubscriptionDB(ctx context.Context, directorID, categoryID uint64) (enabled bool, err error)
|
||||
GetDirectorsSubscribedToCategoryDB(ctx context.Context, categoryID uint64) ([]*typescore.User, error)
|
||||
}
|
||||
|
||||
// GetSubscribedCategoryIDsDB — список ID категорий, на которые подписан директор
|
||||
func (d *DirectorNotificationDB) GetSubscribedCategoryIDsDB(ctx context.Context, directorID uint64) ([]uint64, error) {
|
||||
sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select("category_id").
|
||||
From("director_notification_subscriptions").
|
||||
Where(squirrel.Eq{"director_id": directorID}).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err := d.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var ids []uint64
|
||||
for rows.Next() {
|
||||
var id uint64
|
||||
if err := rows.Scan(&id); err != nil {
|
||||
continue
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
// ToggleSubscriptionDB — переключает подписку директора на категорию.
|
||||
// Если подписки не было — создаёт (enabled=true). Если была — удаляет (enabled=false).
|
||||
func (d *DirectorNotificationDB) ToggleSubscriptionDB(ctx context.Context, directorID, categoryID uint64) (bool, error) {
|
||||
checkSQL, checkArgs, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select("id").
|
||||
From("director_notification_subscriptions").
|
||||
Where(squirrel.Eq{"director_id": directorID, "category_id": categoryID}).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
var existingID uint64
|
||||
err = d.pool.QueryRow(ctx, checkSQL, checkArgs...).Scan(&existingID)
|
||||
|
||||
if err == nil {
|
||||
// Подписка есть — удаляем (выключаем)
|
||||
delSQL, delArgs, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Delete("director_notification_subscriptions").
|
||||
Where(squirrel.Eq{"id": existingID}).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
_, err = d.pool.Exec(ctx, delSQL, delArgs...)
|
||||
return false, err
|
||||
}
|
||||
|
||||
// Подписки нет — создаём (включаем)
|
||||
insSQL, insArgs, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Insert("director_notification_subscriptions").
|
||||
Columns("director_id", "category_id").
|
||||
Values(directorID, categoryID).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
_, err = d.pool.Exec(ctx, insSQL, insArgs...)
|
||||
return true, err
|
||||
}
|
||||
|
||||
// GetDirectorsSubscribedToCategoryDB — все директора, подписанные на указанную категорию
|
||||
func (d *DirectorNotificationDB) GetDirectorsSubscribedToCategoryDB(ctx context.Context, categoryID uint64) ([]*typescore.User, error) {
|
||||
sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select("DISTINCT u.*").
|
||||
From(dbcoretablenames.TableNameUsers.ToString() + " u").
|
||||
Join(dbcoretablenames.TableNameUserRoles.ToString() + " ur ON ur.user_id = u.id").
|
||||
Join(dbcoretablenames.TableNameRoles.ToString() + " r ON r.id = ur.role_id").
|
||||
Join("director_notification_subscriptions dns ON dns.director_id = u.id").
|
||||
Where(squirrel.Eq{"r.is_director": true}).
|
||||
Where(squirrel.Eq{"u.is_blocked": false}).
|
||||
Where(squirrel.Eq{"dns.category_id": categoryID}).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err := d.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var users []*typescore.User
|
||||
for rows.Next() {
|
||||
user := &typescore.User{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, user, nil); err != nil {
|
||||
continue
|
||||
}
|
||||
users = append(users, user)
|
||||
}
|
||||
return users, nil
|
||||
}
|
||||
|
|
@ -0,0 +1,508 @@
|
|||
package dbcore
|
||||
|
||||
import (
|
||||
dbcoretablenames "bitrix_balancer_api/core/db/table_names"
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
dbutils "bitrix_balancer_api/core/utilscore/db"
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type MonthlyOrderDB struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewMonthlyOrderDB(pool *pgxpool.Pool) *MonthlyOrderDB {
|
||||
return &MonthlyOrderDB{pool: pool}
|
||||
}
|
||||
|
||||
type OrderFilterOptions struct {
|
||||
ManagerID *uint64
|
||||
Month *int
|
||||
Year *int
|
||||
Status *string
|
||||
OrderType *string
|
||||
}
|
||||
|
||||
// GetFilteredClientOrdersDB получает заказы с опциональной фильтрацией в SQL
|
||||
func (db *MonthlyOrderDB) GetFilteredClientOrdersDB(ctx context.Context, opts OrderFilterOptions) ([]*typescore.MonthlyOrderClient, error) {
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.MonthlyOrderClient{}, string(dbcoretablenames.TableNameMonthlyOrderClients))
|
||||
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select(fields...).
|
||||
From(string(dbcoretablenames.TableNameMonthlyOrderClients))
|
||||
|
||||
if opts.ManagerID != nil {
|
||||
query = query.Where(squirrel.Eq{"manager_id": *opts.ManagerID})
|
||||
}
|
||||
if opts.Month != nil {
|
||||
query = query.Where(squirrel.Eq{"month": *opts.Month})
|
||||
}
|
||||
if opts.Year != nil {
|
||||
query = query.Where(squirrel.Eq{"year": *opts.Year})
|
||||
}
|
||||
if opts.Status != nil {
|
||||
query = query.Where(squirrel.Eq{"status": *opts.Status})
|
||||
}
|
||||
if opts.OrderType != nil {
|
||||
query = query.Where(squirrel.Eq{"order_type": *opts.OrderType})
|
||||
}
|
||||
|
||||
sqlStr, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err := db.pool.Query(ctx, sqlStr, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var orders []*typescore.MonthlyOrderClient
|
||||
for rows.Next() {
|
||||
order := &typescore.MonthlyOrderClient{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, order, nil); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
orders = append(orders, order)
|
||||
}
|
||||
|
||||
return orders, nil
|
||||
}
|
||||
|
||||
func (db *MonthlyOrderDB) GetFilesByOrderIDDB(ctx context.Context, orderID uint64) ([]*typescore.MonthlyOrderFile, error) {
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.MonthlyOrderFile{}, "monthly_order_files")
|
||||
|
||||
sqlStr, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select(fields...).
|
||||
From("monthly_order_files").
|
||||
Where(squirrel.Eq{"order_client_id": orderID}).
|
||||
ToSql()
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err := db.pool.Query(ctx, sqlStr, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var files []*typescore.MonthlyOrderFile
|
||||
for rows.Next() {
|
||||
file := &typescore.MonthlyOrderFile{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, file, nil); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
files = append(files, file)
|
||||
}
|
||||
|
||||
return files, nil
|
||||
}
|
||||
|
||||
// GetCurrentSettings получает настройки заказа для указанного месяца и года
|
||||
func (db *MonthlyOrderDB) GetCurrentSettings(ctx context.Context, month, year int) (*typescore.MonthlyOrderSetting, error) {
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.MonthlyOrderSetting{}, string(dbcoretablenames.TableNameMonthlyOrderSettings))
|
||||
sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select(fields...).
|
||||
From(string(dbcoretablenames.TableNameMonthlyOrderSettings)).
|
||||
Where(squirrel.Eq{"month": month, "year": year}).
|
||||
Limit(1).
|
||||
ToSql()
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err := db.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
if rows.Next() {
|
||||
setting := &typescore.MonthlyOrderSetting{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, setting, nil); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return setting, nil
|
||||
}
|
||||
return nil, nil // Настройки еще не заданы
|
||||
}
|
||||
|
||||
// SaveSettings сохраняет или обновляет настройки (для аналитика)
|
||||
func (db *MonthlyOrderDB) SaveSettings(ctx context.Context, tx pgx.Tx, setting *typescore.MonthlyOrderSetting) error {
|
||||
if setting == nil {
|
||||
return errors.New("setting is nil")
|
||||
}
|
||||
|
||||
return dbutils.ExecuteTx(ctx, db.pool, tx, func(tx pgx.Tx) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Insert(string(dbcoretablenames.TableNameMonthlyOrderSettings)).
|
||||
Columns("month", "year", "deadline_date", "assembly_time_days").
|
||||
Values(*setting.Month, *setting.Year, *setting.DeadlineDate, *setting.AssemblyTimeDays).
|
||||
Suffix("ON CONFLICT (month, year) DO UPDATE SET deadline_date = EXCLUDED.deadline_date, assembly_time_days = EXCLUDED.assembly_time_days, updated_at = NOW()")
|
||||
|
||||
sqlV, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, sqlV, args...)
|
||||
return err
|
||||
})
|
||||
}
|
||||
|
||||
// SaveClientOrder сохраняет черновик или обновляет заказ менеджера с использованием UPSERT
|
||||
// SaveClientOrder сохраняет черновик или перезаписывает существующий заказ менеджера
|
||||
func (db *MonthlyOrderDB) SaveClientOrder(ctx context.Context, tx pgx.Tx, order *typescore.MonthlyOrderClient) (*typescore.MonthlyOrderClient, error) {
|
||||
if order == nil {
|
||||
return nil, errors.New("order is nil")
|
||||
}
|
||||
|
||||
// 1. Проверяем обязательные поля
|
||||
if order.ClientName == nil || *order.ClientName == "" {
|
||||
return nil, errors.New("client_name is required")
|
||||
}
|
||||
if order.ManagerID == nil {
|
||||
return nil, errors.New("manager_id is required")
|
||||
}
|
||||
if order.Month == nil || order.Year == nil {
|
||||
return nil, errors.New("month and year are required")
|
||||
}
|
||||
if order.Status == nil {
|
||||
defaultStatus := "draft"
|
||||
order.Status = &defaultStatus
|
||||
}
|
||||
|
||||
var insertedID uint64
|
||||
err := dbutils.ExecuteTx(ctx, db.pool, tx, func(tx pgx.Tx) error {
|
||||
var existingID uint64
|
||||
|
||||
// 2. Ищем существующую запись (по ID, если пришел, либо по уникальным полям заказа)
|
||||
if order.ID != nil && *order.ID > 0 {
|
||||
existingID = *order.ID
|
||||
} else {
|
||||
// ВАЖНО: убрали фильтр по status = "draft", чтобы находить уже существующие записи в любом статусе
|
||||
querySelect := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select("id").
|
||||
From(string(dbcoretablenames.TableNameMonthlyOrderClients)).
|
||||
Where(squirrel.Eq{
|
||||
"manager_id": *order.ManagerID,
|
||||
"month": *order.Month,
|
||||
"year": *order.Year,
|
||||
"client_name": *order.ClientName,
|
||||
"order_type": order.OrderType,
|
||||
})
|
||||
|
||||
sqlS, argsS, _ := querySelect.ToSql()
|
||||
err := tx.QueryRow(ctx, sqlS, argsS...).Scan(&existingID)
|
||||
if err != nil && err != pgx.ErrNoRows {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if existingID == 0 {
|
||||
// Записи нет — создаем новую
|
||||
queryInsert := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Insert(string(dbcoretablenames.TableNameMonthlyOrderClients)).
|
||||
Columns(
|
||||
"manager_id",
|
||||
"month",
|
||||
"year",
|
||||
"client_name",
|
||||
"order_type",
|
||||
"manager_comment",
|
||||
"custom_reason",
|
||||
"free_form_comment",
|
||||
"decade",
|
||||
"delivery",
|
||||
"conditions",
|
||||
"payment_form",
|
||||
"status",
|
||||
).
|
||||
Values(
|
||||
*order.ManagerID,
|
||||
*order.Month,
|
||||
*order.Year,
|
||||
*order.ClientName,
|
||||
order.OrderType,
|
||||
order.ManagerComment,
|
||||
order.CustomReason,
|
||||
order.FreeFormComment,
|
||||
order.Decade,
|
||||
order.Delivery,
|
||||
order.Conditions,
|
||||
order.PaymentForm,
|
||||
*order.Status,
|
||||
).
|
||||
Suffix("RETURNING id")
|
||||
|
||||
sqlI, argsI, _ := queryInsert.ToSql()
|
||||
if err := tx.QueryRow(ctx, sqlI, argsI...).Scan(&insertedID); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
// Запись есть — обновляем ее новыми значениями
|
||||
queryUpdate := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Update(string(dbcoretablenames.TableNameMonthlyOrderClients)).
|
||||
Set("order_type", order.OrderType).
|
||||
Set("manager_comment", order.ManagerComment).
|
||||
Set("custom_reason", order.CustomReason).
|
||||
Set("free_form_comment", order.FreeFormComment).
|
||||
Set("decade", order.Decade).
|
||||
Set("delivery", order.Delivery).
|
||||
Set("conditions", order.Conditions).
|
||||
Set("payment_form", order.PaymentForm).
|
||||
Set("approval_id", order.ApprovalID).
|
||||
Set("status", *order.Status).
|
||||
Set("updated_at", squirrel.Expr("NOW()")).
|
||||
Where(squirrel.Eq{"id": existingID})
|
||||
|
||||
sqlU, argsU, _ := queryUpdate.ToSql()
|
||||
if _, err := tx.Exec(ctx, sqlU, argsU...); err != nil {
|
||||
return err
|
||||
}
|
||||
insertedID = existingID
|
||||
}
|
||||
|
||||
order.ID = &insertedID
|
||||
|
||||
// 3. Перезаписываем товары
|
||||
delSQL, delArgs, _ := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Delete(string(dbcoretablenames.TableNameMonthlyOrderItems)).
|
||||
Where(squirrel.Eq{"order_client_id": insertedID}).
|
||||
ToSql()
|
||||
|
||||
if _, err := tx.Exec(ctx, delSQL, delArgs...); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(order.Items) > 0 {
|
||||
insertItems := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Insert(string(dbcoretablenames.TableNameMonthlyOrderItems)).
|
||||
Columns("order_client_id", "nomenclature_name", "nomenclature_type", "quantity")
|
||||
|
||||
hasValidItems := false
|
||||
for _, item := range order.Items {
|
||||
if item.Quantity != nil && *item.Quantity > 0 {
|
||||
insertItems = insertItems.Values(insertedID, item.NomenclatureName, item.NomenclatureType, item.Quantity)
|
||||
hasValidItems = true
|
||||
}
|
||||
}
|
||||
|
||||
if hasValidItems {
|
||||
iSQL, iArgs, err := insertItems.ToSql()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = tx.Exec(ctx, iSQL, iArgs...); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Перезаписываем файлы
|
||||
delFilesSQL, delFilesArgs, _ := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Delete("monthly_order_files").
|
||||
Where(squirrel.Eq{"order_client_id": insertedID}).
|
||||
ToSql()
|
||||
|
||||
if _, err := tx.Exec(ctx, delFilesSQL, delFilesArgs...); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(order.Files) > 0 {
|
||||
insertFiles := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Insert("monthly_order_files").
|
||||
Columns("order_client_id", "file_name", "file_base64")
|
||||
|
||||
hasValidFiles := false
|
||||
for _, f := range order.Files {
|
||||
if f.FileBase64 != nil && *f.FileBase64 != "" {
|
||||
insertFiles = insertFiles.Values(insertedID, f.FileName, f.FileBase64)
|
||||
hasValidFiles = true
|
||||
}
|
||||
}
|
||||
|
||||
if hasValidFiles {
|
||||
fSQL, fArgs, err := insertFiles.ToSql()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = tx.Exec(ctx, fSQL, fArgs...); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return order, nil
|
||||
}
|
||||
|
||||
// GetAllOrdersForMonthDB получает абсолютно все заказы за указанный месяц и год без фильтрации по менеджеру
|
||||
func (db *MonthlyOrderDB) GetAllOrdersForMonthDB(ctx context.Context, month, year int) ([]*typescore.MonthlyOrderClient, error) {
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.MonthlyOrderClient{}, string(dbcoretablenames.TableNameMonthlyOrderClients))
|
||||
|
||||
sqlStr, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select(fields...).
|
||||
From(string(dbcoretablenames.TableNameMonthlyOrderClients)).
|
||||
Where(squirrel.Eq{"month": month, "year": year}).
|
||||
ToSql()
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err := db.pool.Query(ctx, sqlStr, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var orders []*typescore.MonthlyOrderClient
|
||||
for rows.Next() {
|
||||
order := &typescore.MonthlyOrderClient{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, order, nil); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
orders = append(orders, order)
|
||||
}
|
||||
|
||||
return orders, nil
|
||||
}
|
||||
|
||||
// GetClientOrdersByManagerDB получает все заказы менеджера за указанный месяц и год
|
||||
func (db *MonthlyOrderDB) GetClientOrdersByManagerDB(ctx context.Context, managerID uint64, month, year int) ([]*typescore.MonthlyOrderClient, error) {
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.MonthlyOrderClient{}, string(dbcoretablenames.TableNameMonthlyOrderClients))
|
||||
|
||||
sqlStr, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select(fields...).
|
||||
From(string(dbcoretablenames.TableNameMonthlyOrderClients)).
|
||||
Where(squirrel.Eq{"manager_id": managerID, "month": month, "year": year}).
|
||||
ToSql()
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err := db.pool.Query(ctx, sqlStr, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var orders []*typescore.MonthlyOrderClient
|
||||
for rows.Next() {
|
||||
order := &typescore.MonthlyOrderClient{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, order, nil); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
orders = append(orders, order)
|
||||
}
|
||||
|
||||
return orders, nil
|
||||
}
|
||||
|
||||
// GetItemsForMonthDB - получает все товары для всех заказов месяца одним запросом
|
||||
func (db *MonthlyOrderDB) GetItemsForMonthDB(ctx context.Context, month, year int) (map[uint64][]*typescore.MonthlyOrderItem, error) {
|
||||
// Делаем JOIN таблиц Items и Clients, чтобы вытащить только товары текущего месяца
|
||||
sqlStr := `
|
||||
SELECT i.id, i.order_client_id, i.nomenclature_name, i.nomenclature_type, i.quantity
|
||||
FROM monthly_order_items i
|
||||
JOIN monthly_order_clients c ON i.order_client_id = c.id
|
||||
WHERE c.month = $1 AND c.year = $2
|
||||
`
|
||||
rows, err := db.pool.Query(ctx, sqlStr, month, year)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
itemsMap := make(map[uint64][]*typescore.MonthlyOrderItem)
|
||||
for rows.Next() {
|
||||
item := &typescore.MonthlyOrderItem{}
|
||||
// Сканируем поля вручную (в порядке SELECT)
|
||||
err := rows.Scan(&item.ID, &item.OrderClientID, &item.NomenclatureName, &item.NomenclatureType, &item.Quantity)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if item.OrderClientID != nil {
|
||||
itemsMap[*item.OrderClientID] = append(itemsMap[*item.OrderClientID], item)
|
||||
}
|
||||
}
|
||||
return itemsMap, nil
|
||||
}
|
||||
|
||||
// GetItemsByOrderIDDB получает позиции конкретного заказа (номенклатуру и количество)
|
||||
func (db *MonthlyOrderDB) GetItemsByOrderIDDB(ctx context.Context, orderID uint64) ([]*typescore.MonthlyOrderItem, error) {
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.MonthlyOrderItem{}, string(dbcoretablenames.TableNameMonthlyOrderItems))
|
||||
|
||||
sqlStr, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select(fields...).
|
||||
From(string(dbcoretablenames.TableNameMonthlyOrderItems)).
|
||||
Where(squirrel.Eq{"order_client_id": orderID}).
|
||||
ToSql()
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err := db.pool.Query(ctx, sqlStr, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var items []*typescore.MonthlyOrderItem
|
||||
for rows.Next() {
|
||||
item := &typescore.MonthlyOrderItem{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, item, nil); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
|
||||
return items, nil
|
||||
}
|
||||
|
||||
// GetManagersWithDraftsDB получает список ID менеджеров, у которых есть черновики за указанный период
|
||||
func (db *MonthlyOrderDB) GetManagersWithDraftsDB(ctx context.Context, month, year int) ([]uint64, error) {
|
||||
sqlStr, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select("DISTINCT manager_id").
|
||||
From(string(dbcoretablenames.TableNameMonthlyOrderClients)).
|
||||
Where(squirrel.Eq{"month": month, "year": year, "status": "draft"}).
|
||||
ToSql()
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err := db.pool.Query(ctx, sqlStr, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var managerIDs []uint64
|
||||
for rows.Next() {
|
||||
var id uint64
|
||||
if err := rows.Scan(&id); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
managerIDs = append(managerIDs, id)
|
||||
}
|
||||
|
||||
return managerIDs, nil
|
||||
}
|
||||
|
|
@ -0,0 +1,169 @@
|
|||
package dbcore
|
||||
|
||||
import (
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
dbutils "bitrix_balancer_api/core/utilscore/db"
|
||||
"context"
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type NotificationDB struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewNotificationDB(pool *pgxpool.Pool) *NotificationDB {
|
||||
return &NotificationDB{pool: pool}
|
||||
}
|
||||
|
||||
type NotificationDBI interface {
|
||||
CreateNotificationDB(ctx context.Context, n *typescore.Notification) (*typescore.Notification, error)
|
||||
UpdateNotificationDB(ctx context.Context, n *typescore.Notification) error
|
||||
GetNotificationsListDB(ctx context.Context, opts typescore.ListDbOptions) ([]*typescore.Notification, uint64, error)
|
||||
GetNotificationByIDDB(ctx context.Context, id uint64) (*typescore.Notification, error)
|
||||
|
||||
CreateNotificationRecipientsDB(ctx context.Context, recipients []*typescore.NotificationRecipient) error
|
||||
UpdateNotificationRecipientDB(ctx context.Context, r *typescore.NotificationRecipient) error
|
||||
GetNotificationRecipientsDB(ctx context.Context, notificationID uint64) ([]*typescore.NotificationRecipient, error)
|
||||
}
|
||||
|
||||
func (n *NotificationDB) CreateNotificationDB(ctx context.Context, obj *typescore.Notification) (*typescore.Notification, error) {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Insert("notifications")
|
||||
|
||||
sqlV, args, err := dbutils.GenerateInsertRequest(query, obj)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var newID uint64
|
||||
sqlStr := *sqlV + " RETURNING id"
|
||||
err = n.pool.QueryRow(ctx, sqlStr, args...).Scan(&newID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
obj.ID = &newID
|
||||
return obj, nil
|
||||
}
|
||||
|
||||
func (n *NotificationDB) UpdateNotificationDB(ctx context.Context, obj *typescore.Notification) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Update("notifications")
|
||||
query = dbutils.AddNonNullFieldsToQueryUpdate(query, *obj)
|
||||
query = query.Where(squirrel.Eq{"id": obj.ID})
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = n.pool.Exec(ctx, sql, args...)
|
||||
return err
|
||||
}
|
||||
|
||||
func (n *NotificationDB) GetNotificationsListDB(ctx context.Context, opts typescore.ListDbOptions) ([]*typescore.Notification, uint64, error) {
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.Notification{}, "notifications")
|
||||
selectFields := append(fields, "COUNT(*) OVER() AS total_count")
|
||||
|
||||
query := dbutils.BuildSelectQuery("notifications", selectFields)
|
||||
query = dbutils.SetterLimitAndOffsetQuery(query, opts.Offset, opts.Limit)
|
||||
query = query.OrderBy("created_at DESC")
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
rows, err := n.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var result []*typescore.Notification
|
||||
var total uint64
|
||||
for rows.Next() {
|
||||
obj := &typescore.Notification{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, obj, &total); err != nil {
|
||||
continue
|
||||
}
|
||||
result = append(result, obj)
|
||||
}
|
||||
return result, total, nil
|
||||
}
|
||||
|
||||
func (n *NotificationDB) GetNotificationByIDDB(ctx context.Context, id uint64) (*typescore.Notification, error) {
|
||||
list, _, err := n.GetNotificationsListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.Notification{ID: &id},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(list) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return list[0], nil
|
||||
}
|
||||
|
||||
func (n *NotificationDB) CreateNotificationRecipientsDB(ctx context.Context, recipients []*typescore.NotificationRecipient) error {
|
||||
if len(recipients) == 0 {
|
||||
return nil
|
||||
}
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Insert("notification_recipients").
|
||||
Columns("notification_id", "user_id", "status")
|
||||
|
||||
for _, r := range recipients {
|
||||
query = query.Values(*r.NotificationID, *r.UserID, *r.Status)
|
||||
}
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = n.pool.Exec(ctx, sql, args...)
|
||||
return err
|
||||
}
|
||||
|
||||
func (n *NotificationDB) UpdateNotificationRecipientDB(ctx context.Context, r *typescore.NotificationRecipient) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Update("notification_recipients")
|
||||
query = dbutils.AddNonNullFieldsToQueryUpdate(query, *r)
|
||||
query = query.Where(squirrel.Eq{"id": r.ID})
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = n.pool.Exec(ctx, sql, args...)
|
||||
return err
|
||||
}
|
||||
|
||||
func (n *NotificationDB) GetNotificationRecipientsDB(ctx context.Context, notificationID uint64) ([]*typescore.NotificationRecipient, error) {
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.NotificationRecipient{}, "notification_recipients")
|
||||
|
||||
sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select(fields...).
|
||||
From("notification_recipients").
|
||||
Where(squirrel.Eq{"notification_id": notificationID}).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err := n.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var result []*typescore.NotificationRecipient
|
||||
for rows.Next() {
|
||||
obj := &typescore.NotificationRecipient{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, obj, nil); err != nil {
|
||||
continue
|
||||
}
|
||||
result = append(result, obj)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
|
@ -170,11 +170,10 @@ func (u *PermissionDB) DeletePermissionDB(ctx context.Context, params *typescore
|
|||
return err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, query, args...)
|
||||
_, err = u.pool.Exec(ctx, query, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
return nil
|
||||
} else {
|
||||
|
|
@ -185,7 +184,6 @@ func (u *PermissionDB) DeletePermissionDB(ctx context.Context, params *typescore
|
|||
// GetUserPermissionsDB возвращает все permissions для пользователя через его роли.
|
||||
// action — фильтр: create | approve | revoke | "" (все)
|
||||
func (u *PermissionDB) GetUserPermissionsDB(ctx context.Context, userID uint64, action string) ([]*typescore.Permission, error) {
|
||||
// Используем алиас "p" и в GetStructFieldsDB тоже
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.Permission{}, "p")
|
||||
|
||||
q := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
|
|
|
|||
|
|
@ -29,6 +29,7 @@ type RoleDBI interface {
|
|||
UpdateRoleDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.Role, returnObj ...bool) (*typescore.Role, pgx.Tx, error)
|
||||
DeleteRoleDB(ctx context.Context, params *typescore.Role) error
|
||||
GetRoleByIDDB(ctx context.Context, id uint64) (*typescore.Role, error)
|
||||
GetRolesByIDsDB(ctx context.Context, ids []uint64) ([]*typescore.Role, error)
|
||||
}
|
||||
|
||||
func (u *RoleDB) GetRolesListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.Role, uint64, error) {
|
||||
|
|
@ -169,11 +170,10 @@ func (u *RoleDB) DeleteRoleDB(ctx context.Context, params *typescore.Role) error
|
|||
return err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, query, args...)
|
||||
_, err = u.pool.Exec(ctx, query, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
return nil
|
||||
} else {
|
||||
|
|
@ -190,3 +190,42 @@ func (u *RoleDB) GetRoleByIDDB(ctx context.Context, id uint64) (*typescore.Role,
|
|||
}
|
||||
return roles[0], nil
|
||||
}
|
||||
|
||||
// GetRolesByIDsDB — пакетное получение ролей по списку ID (устраняет N+1)
|
||||
func (u *RoleDB) GetRolesByIDsDB(ctx context.Context, ids []uint64) ([]*typescore.Role, error) {
|
||||
if len(ids) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.Role{}, dbcoretablenames.TableNameRoles.ToString())
|
||||
|
||||
sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select(fields...).
|
||||
From(dbcoretablenames.TableNameRoles.ToString()).
|
||||
Where(squirrel.Eq{"id": ids}).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var roles []*typescore.Role
|
||||
for rows.Next() {
|
||||
role := &typescore.Role{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, role, nil); err != nil {
|
||||
logrus.Warn("GetRolesByIDsDB:ScanRowsToStructRows", err)
|
||||
continue
|
||||
}
|
||||
roles = append(roles, role)
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return roles, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,76 @@
|
|||
package dbcore
|
||||
|
||||
import (
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
dbutils "bitrix_balancer_api/core/utilscore/db"
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"time"
|
||||
)
|
||||
|
||||
type SmsLogDB struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewSmsLogDB(pool *pgxpool.Pool) *SmsLogDB {
|
||||
return &SmsLogDB{pool: pool}
|
||||
}
|
||||
|
||||
// CreateSmsLogDB сохраняет новую SMS в базу
|
||||
func (s *SmsLogDB) CreateSmsLogDB(ctx context.Context, tx pgx.Tx, obj *typescore.SmsLog) error {
|
||||
if obj == nil {
|
||||
return errors.New("SmsLog obj is nil")
|
||||
}
|
||||
|
||||
err := dbutils.ExecuteTx(ctx, s.pool, tx, func(tx pgx.Tx) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Insert("sms_logs")
|
||||
|
||||
sqlV, args, err := dbutils.GenerateInsertRequest(query, obj)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, *sqlV, args...)
|
||||
return err
|
||||
})
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// GetSmsLogsByDateRangeDB получает список SMS за период (для Google Script)
|
||||
func (s *SmsLogDB) GetSmsLogsByDateRangeDB(ctx context.Context, startDate, endDate time.Time) ([]*typescore.SmsLog, error) {
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.SmsLog{}, "sms_logs")
|
||||
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select(fields...).
|
||||
From("sms_logs").
|
||||
Where(squirrel.GtOrEq{"event_created": startDate}).
|
||||
Where(squirrel.LtOrEq{"event_created": endDate}).
|
||||
OrderBy("event_created DESC")
|
||||
|
||||
sqlStr, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err := s.pool.Query(ctx, sqlStr, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var logs []*typescore.SmsLog
|
||||
for rows.Next() {
|
||||
log := &typescore.SmsLog{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, log, nil); err != nil {
|
||||
continue
|
||||
}
|
||||
logs = append(logs, log)
|
||||
}
|
||||
|
||||
return logs, nil
|
||||
}
|
||||
|
|
@ -169,11 +169,10 @@ func (u *SuggestionDB) DeleteSuggestionDB(ctx context.Context, params *typescore
|
|||
return err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, query, args...)
|
||||
_, err = u.pool.Exec(ctx, query, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
return nil
|
||||
} else {
|
||||
|
|
|
|||
|
|
@ -169,11 +169,10 @@ func (u *SuggestionMessageDB) DeleteSuggestionMessageDB(ctx context.Context, par
|
|||
return err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, query, args...)
|
||||
_, err = u.pool.Exec(ctx, query, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
return nil
|
||||
} else {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,186 @@
|
|||
package dbcore
|
||||
|
||||
import (
|
||||
dbcoretablenames "bitrix_balancer_api/core/db/table_names"
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
dbutils "bitrix_balancer_api/core/utilscore/db"
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type TaskDelegationDB struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewTaskDelegationDB(pool *pgxpool.Pool) *TaskDelegationDB {
|
||||
return &TaskDelegationDB{
|
||||
pool: pool,
|
||||
}
|
||||
}
|
||||
|
||||
type TaskDelegationDBI interface {
|
||||
GetTaskDelegationsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.TaskDelegation, uint64, error)
|
||||
CreateTaskDelegationDB(ctx context.Context, tx pgx.Tx, TaskDelegationObj *typescore.TaskDelegation, returnObj ...bool) (*typescore.TaskDelegation, pgx.Tx, error)
|
||||
UpdateTaskDelegationDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.TaskDelegation, returnObj ...bool) (*typescore.TaskDelegation, pgx.Tx, error)
|
||||
DeleteTaskDelegationDB(ctx context.Context, params *typescore.TaskDelegation) error
|
||||
GetTaskDelegationByIDDB(ctx context.Context, id uint64) (*typescore.TaskDelegation, error)
|
||||
}
|
||||
|
||||
func (u *TaskDelegationDB) GetTaskDelegationsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.TaskDelegation, uint64, error) {
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.TaskDelegation{}, dbcoretablenames.TableNameTaskDelegations.ToString())
|
||||
selectFields := append(fields, "COUNT(*) OVER() AS total_count")
|
||||
|
||||
options, filter, err := dbutils.GetOptionsDB[typescore.TaskDelegation](opts...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameTaskDelegations.ToString(), selectFields)
|
||||
query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
|
||||
query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameTaskDelegations.ToString())
|
||||
query = query.OrderBy("created_at DESC")
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var taskDelegations []*typescore.TaskDelegation
|
||||
var totalCount uint64
|
||||
for rows.Next() {
|
||||
taskDelegation := &typescore.TaskDelegation{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, taskDelegation, &totalCount); err != nil {
|
||||
logrus.Warn("GetTaskDelegationsListDB:ScanRowsToStructRows", err)
|
||||
continue
|
||||
}
|
||||
taskDelegations = append(taskDelegations, taskDelegation)
|
||||
}
|
||||
|
||||
return taskDelegations, totalCount, nil
|
||||
}
|
||||
|
||||
func (u *TaskDelegationDB) CreateTaskDelegationDB(ctx context.Context, tx pgx.Tx, taskDelegationObj *typescore.TaskDelegation, returnObj ...bool) (*typescore.TaskDelegation, pgx.Tx, error) {
|
||||
if taskDelegationObj == nil {
|
||||
return nil, nil, errors.New("TaskDelegation obj is nil")
|
||||
}
|
||||
|
||||
var insertedID uint64
|
||||
|
||||
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Insert(dbcoretablenames.TableNameTaskDelegations.ToString())
|
||||
|
||||
sqlV, args, err := dbutils.GenerateInsertRequest(query, taskDelegationObj)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
*sqlV = *sqlV + " RETURNING id"
|
||||
|
||||
return tx.QueryRow(ctx, *sqlV, args...).Scan(&insertedID)
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, tx, err
|
||||
}
|
||||
|
||||
returnObjBool := len(returnObj) > 0 && returnObj[0]
|
||||
if returnObjBool && insertedID > 0 {
|
||||
created, err := u.GetTaskDelegationByIDDB(ctx, insertedID)
|
||||
return created, tx, err
|
||||
}
|
||||
|
||||
return nil, tx, nil
|
||||
}
|
||||
|
||||
func (u *TaskDelegationDB) UpdateTaskDelegationDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.TaskDelegation, returnObj ...bool) (*typescore.TaskDelegation, pgx.Tx, error) {
|
||||
if paramsUpdate.ID == nil {
|
||||
return nil, nil, errors.New("TaskDelegation obj is nil")
|
||||
}
|
||||
|
||||
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameTaskDelegations.ToString())
|
||||
query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate)
|
||||
query = query.Where(squirrel.Eq{"id": paramsUpdate.ID})
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, tx, err
|
||||
}
|
||||
|
||||
returnObjBool := false
|
||||
if len(returnObj) > 0 {
|
||||
returnObjBool = returnObj[0]
|
||||
}
|
||||
|
||||
if returnObjBool {
|
||||
options := typescore.ListDbOptions{Filtering: &typescore.TaskDelegation{ID: paramsUpdate.ID}}
|
||||
getInfoUp, _, err := u.GetTaskDelegationsListDB(ctx, options)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if len(getInfoUp) > 0 {
|
||||
return getInfoUp[0], tx, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, tx, nil
|
||||
}
|
||||
|
||||
func (u *TaskDelegationDB) DeleteTaskDelegationDB(ctx context.Context, params *typescore.TaskDelegation) error {
|
||||
if params != nil && params.ID != nil {
|
||||
query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Delete(dbcoretablenames.TableNameTaskDelegations.ToString()).
|
||||
Where(squirrel.Eq{"id": *params.ID}).
|
||||
ToSql()
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
return nil
|
||||
} else {
|
||||
return errors.New("TaskDelegation obj is nil")
|
||||
}
|
||||
}
|
||||
|
||||
func (u *TaskDelegationDB) GetTaskDelegationByIDDB(ctx context.Context, id uint64) (*typescore.TaskDelegation, error) {
|
||||
taskDelegations, _, err := u.GetTaskDelegationsListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.TaskDelegation{ID: &id},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(taskDelegations) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return taskDelegations[0], nil
|
||||
}
|
||||
|
|
@ -6,10 +6,10 @@ import (
|
|||
dbutils "bitrix_balancer_api/core/utilscore/db"
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
|
|
@ -37,6 +37,14 @@ type UserDBI interface {
|
|||
IsExecutorDB(ctx context.Context, userID uint64) (bool, error)
|
||||
GetObserversForCategoryDB(ctx context.Context, categoryCode string) ([]*typescore.User, error)
|
||||
GetUsersByRoleCodeDB(ctx context.Context, roleCode string) ([]*typescore.User, error)
|
||||
GetObserversForApprovalDB(ctx context.Context, categoryCode string, topicID *uint64) ([]*typescore.User, error)
|
||||
GetUsersListByRoleIDsDB(ctx context.Context, opts typescore.ListDbOptions, roleIDs []uint64) ([]*typescore.User, uint64, error)
|
||||
GetUsersByIDsDB(ctx context.Context, ids []uint64) ([]*typescore.User, error)
|
||||
|
||||
IsControllerDB(ctx context.Context, userID uint64) (bool, error)
|
||||
GetControllerObserversForApprovalDB(ctx context.Context, categoryCode string, topicID *uint64) ([]*typescore.User, error)
|
||||
GetUsersByRoleFlagsDB(ctx context.Context, flags []string) ([]*typescore.User, error)
|
||||
GetUsersByDepartmentIDsDB(ctx context.Context, departmentIDs []uint64) ([]*typescore.User, error)
|
||||
}
|
||||
|
||||
func (u *UserDB) GetUsersListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.User, uint64, error) {
|
||||
|
|
@ -48,9 +56,27 @@ func (u *UserDB) GetUsersListDB(ctx context.Context, opts ...typescore.ListDbOpt
|
|||
return nil, 0, err
|
||||
}
|
||||
|
||||
// ✅ Сохраняем значение поиска и удаляем из LikeFields
|
||||
searchName := ""
|
||||
if options.LikeFields != nil && options.LikeFields["full_name"] != "" {
|
||||
searchName = options.LikeFields["full_name"]
|
||||
delete(options.LikeFields, "full_name")
|
||||
}
|
||||
|
||||
// ✅ Обнуляем FullName в filter
|
||||
filter.FullName = nil
|
||||
|
||||
query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameUsers.ToString(), selectFields)
|
||||
query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
|
||||
|
||||
// ✅ Сначала добавляем условие поиска
|
||||
if searchName != "" {
|
||||
query = query.Where("LOWER(full_name) LIKE LOWER(?)", "%"+searchName+"%")
|
||||
}
|
||||
|
||||
// ✅ Потом применяем остальные фильтры
|
||||
query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameUsers.ToString())
|
||||
|
||||
query = query.OrderBy("created_at DESC")
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
|
|
@ -58,6 +84,8 @@ func (u *UserDB) GetUsersListDB(ctx context.Context, opts ...typescore.ListDbOpt
|
|||
return nil, 0, err
|
||||
}
|
||||
|
||||
logrus.Debugf("GetUsersListDB SQL: %s, Args: %v", sql, args)
|
||||
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
|
|
@ -177,11 +205,10 @@ func (u *UserDB) DeleteUserDB(ctx context.Context, params *typescore.User) error
|
|||
return err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, query, args...)
|
||||
_, err = u.pool.Exec(ctx, query, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
return nil
|
||||
} else {
|
||||
|
|
@ -359,6 +386,74 @@ func (u *UserDB) GetObserversForCategoryDB(ctx context.Context, categoryCode str
|
|||
return result, nil
|
||||
}
|
||||
|
||||
// GetObserversForApprovalDB — возвращает наблюдателей для конкретной заявки.
|
||||
// Учитывает права как на категорию темы, так и на саму тему (topic_id).
|
||||
// Дубли устраняются через DISTINCT.
|
||||
func (u *UserDB) GetObserversForApprovalDB(
|
||||
ctx context.Context,
|
||||
categoryCode string,
|
||||
topicID *uint64,
|
||||
) ([]*typescore.User, error) {
|
||||
q := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select("DISTINCT u.*").
|
||||
From(dbcoretablenames.TableNameUsers.ToString() + " u").
|
||||
Join(dbcoretablenames.TableNameUserRoles.ToString() + " ur ON ur.user_id = u.id").
|
||||
Join(dbcoretablenames.TableNameRoles.ToString() + " r ON r.id = ur.role_id").
|
||||
Join(dbcoretablenames.TableNamePermissions.ToString() + " p ON p.role_id = r.id").
|
||||
Where(squirrel.Eq{"r.is_observer": true}).
|
||||
Where(squirrel.Eq{"p.action": "observe"}).
|
||||
Where(squirrel.Eq{"u.is_blocked": false})
|
||||
|
||||
if topicID != nil {
|
||||
// Логика:
|
||||
// 1. Наблюдатели категории: topic_id IS NULL И category_id совпадает
|
||||
// 2. Наблюдатели конкретной темы: topic_id совпадает (category игнорируем)
|
||||
q = q.Where(squirrel.Or{
|
||||
squirrel.And{
|
||||
squirrel.Expr("p.topic_id IS NULL"),
|
||||
squirrel.Expr(
|
||||
"p.topic_category_id IN (SELECT id FROM approval_topic_categories WHERE code = ?)",
|
||||
categoryCode,
|
||||
),
|
||||
},
|
||||
squirrel.Eq{"p.topic_id": *topicID},
|
||||
})
|
||||
} else {
|
||||
// Если topicID не передан — fallback на старую логику (только по категории)
|
||||
q = q.Join(
|
||||
dbcoretablenames.TableNameApprovalTopicCategories.ToString() +
|
||||
" c ON c.id = p.topic_category_id",
|
||||
).Where(squirrel.Eq{"c.code": categoryCode})
|
||||
}
|
||||
|
||||
sql, args, err := q.ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
logrus.Infof("🔍 GetObserversForApprovalDB SQL: %s", sql)
|
||||
logrus.Infof("🔍 GetObserversForApprovalDB Args: %v", args)
|
||||
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var result []*typescore.User
|
||||
for rows.Next() {
|
||||
usr := &typescore.User{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, usr, nil); err != nil {
|
||||
logrus.Warn("GetObserversForApprovalDB:ScanRowsToStruct", err)
|
||||
continue
|
||||
}
|
||||
result = append(result, usr)
|
||||
}
|
||||
|
||||
logrus.Infof("✅ GetObserversForApprovalDB found %d observers", len(result))
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (u *UserDB) GetUsersByRoleCodeDB(ctx context.Context, roleCode string) ([]*typescore.User, error) {
|
||||
sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select("DISTINCT u.*").
|
||||
|
|
@ -390,3 +485,303 @@ func (u *UserDB) GetUsersByRoleCodeDB(ctx context.Context, roleCode string) ([]*
|
|||
}
|
||||
return users, nil
|
||||
}
|
||||
|
||||
// GetUsersListByRoleIDsDB - фильтрация пользователей по массиву ID ролей
|
||||
func (u *UserDB) GetUsersListByRoleIDsDB(ctx context.Context, opts typescore.ListDbOptions, roleIDs []uint64) ([]*typescore.User, uint64, error) {
|
||||
if len(roleIDs) == 0 {
|
||||
return u.GetUsersListDB(ctx, opts)
|
||||
}
|
||||
|
||||
options, filter, err := dbutils.GetOptionsDB[typescore.User](opts)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
searchName := ""
|
||||
if options.LikeFields != nil && options.LikeFields["full_name"] != "" {
|
||||
searchName = options.LikeFields["full_name"]
|
||||
delete(options.LikeFields, "full_name")
|
||||
}
|
||||
|
||||
filter.FullName = nil
|
||||
|
||||
logrus.Infof("🔍 GetUsersListByRoleIDsDB: searchName='%s', filter.FullName=%v, options.Offset=%d, options.Limit=%d",
|
||||
searchName, filter.FullName, options.Offset, options.Limit)
|
||||
|
||||
countQuery := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select("COUNT(DISTINCT u.id)").
|
||||
From(dbcoretablenames.TableNameUsers.ToString() + " u").
|
||||
Join(dbcoretablenames.TableNameUserRoles.ToString() + " ur ON ur.user_id = u.id").
|
||||
Where(squirrel.Eq{"ur.role_id": roleIDs})
|
||||
|
||||
if searchName != "" {
|
||||
countQuery = countQuery.Where("LOWER(u.full_name) LIKE LOWER(?)", "%"+searchName+"%")
|
||||
}
|
||||
countQuery = dbutils.ApplyFilters(countQuery, filter, options.LikeFields, dbcoretablenames.TableNameUsers.ToString())
|
||||
|
||||
countSQL, countArgs, err := countQuery.ToSql()
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
var totalCount uint64
|
||||
err = u.pool.QueryRow(ctx, countSQL, countArgs...).Scan(&totalCount)
|
||||
if err != nil {
|
||||
logrus.Errorf("🔍 GetUsersListByRoleIDsDB Count error: %v", err)
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select("u.*").
|
||||
From(dbcoretablenames.TableNameUsers.ToString() + " u").
|
||||
Join(dbcoretablenames.TableNameUserRoles.ToString() + " ur ON ur.user_id = u.id").
|
||||
Where(squirrel.Eq{"ur.role_id": roleIDs}).
|
||||
GroupBy("u.id")
|
||||
|
||||
if searchName != "" {
|
||||
query = query.Where("LOWER(u.full_name) LIKE LOWER(?)", "%"+searchName+"%")
|
||||
}
|
||||
|
||||
query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameUsers.ToString())
|
||||
|
||||
query = query.OrderBy("u.created_at DESC")
|
||||
query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
logrus.Errorf("🔍 GetUsersListByRoleIDsDB Query error: %v", err)
|
||||
return nil, 0, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var users []*typescore.User
|
||||
for rows.Next() {
|
||||
user := &typescore.User{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, user, nil); err != nil {
|
||||
logrus.Warn("GetUsersListByRoleIDsDB:ScanRowsToStructRows", err)
|
||||
continue
|
||||
}
|
||||
users = append(users, user)
|
||||
}
|
||||
|
||||
if err = rows.Err(); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
return users, totalCount, nil
|
||||
}
|
||||
|
||||
// GetUsersByIDsDB — пакетное получение пользователей по списку ID (устраняет N+1)
|
||||
func (u *UserDB) GetUsersByIDsDB(ctx context.Context, ids []uint64) ([]*typescore.User, error) {
|
||||
if len(ids) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.User{}, dbcoretablenames.TableNameUsers.ToString())
|
||||
|
||||
sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select(fields...).
|
||||
From(dbcoretablenames.TableNameUsers.ToString()).
|
||||
Where(squirrel.Eq{"id": ids}).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var users []*typescore.User
|
||||
for rows.Next() {
|
||||
user := &typescore.User{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, user, nil); err != nil {
|
||||
logrus.Warn("GetUsersByIDsDB:ScanRowsToStructRows", err)
|
||||
continue
|
||||
}
|
||||
users = append(users, user)
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return users, nil
|
||||
}
|
||||
|
||||
// IsControllerDB проверяет, есть ли у пользователя роль наблюдателя с флагом is_controller = true.
|
||||
func (u *UserDB) IsControllerDB(ctx context.Context, userID uint64) (bool, error) {
|
||||
sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select("COUNT(*)").
|
||||
From(dbcoretablenames.TableNameUserRoles.ToString() + " ur").
|
||||
Join(dbcoretablenames.TableNameRoles.ToString() + " r ON r.id = ur.role_id").
|
||||
Where(squirrel.Eq{"ur.user_id": userID}).
|
||||
Where(squirrel.Eq{"r.is_observer": true}).
|
||||
Where(squirrel.Eq{"r.is_controller": true}).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
var count int
|
||||
if err := u.pool.QueryRow(ctx, sql, args...).Scan(&count); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return count > 0, nil
|
||||
}
|
||||
|
||||
// GetControllerObserversForApprovalDB — то же самое, что GetObserversForApprovalDB,
|
||||
// но только пользователи, у которых роль имеет флаг is_controller = true.
|
||||
func (u *UserDB) GetControllerObserversForApprovalDB(
|
||||
ctx context.Context,
|
||||
categoryCode string,
|
||||
topicID *uint64,
|
||||
) ([]*typescore.User, error) {
|
||||
q := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select("DISTINCT u.*").
|
||||
From(dbcoretablenames.TableNameUsers.ToString() + " u").
|
||||
Join(dbcoretablenames.TableNameUserRoles.ToString() + " ur ON ur.user_id = u.id").
|
||||
Join(dbcoretablenames.TableNameRoles.ToString() + " r ON r.id = ur.role_id").
|
||||
Join(dbcoretablenames.TableNamePermissions.ToString() + " p ON p.role_id = r.id").
|
||||
Where(squirrel.Eq{"r.is_observer": true}).
|
||||
Where(squirrel.Eq{"r.is_controller": true}).
|
||||
Where(squirrel.Eq{"p.action": "observe"}).
|
||||
Where(squirrel.Eq{"u.is_blocked": false})
|
||||
|
||||
if topicID != nil {
|
||||
q = q.Where(squirrel.Or{
|
||||
squirrel.And{
|
||||
squirrel.Expr("p.topic_id IS NULL"),
|
||||
squirrel.Expr(
|
||||
"p.topic_category_id IN (SELECT id FROM approval_topic_categories WHERE code = ?)",
|
||||
categoryCode,
|
||||
),
|
||||
},
|
||||
squirrel.Eq{"p.topic_id": *topicID},
|
||||
})
|
||||
} else {
|
||||
q = q.Join(
|
||||
dbcoretablenames.TableNameApprovalTopicCategories.ToString() +
|
||||
" c ON c.id = p.topic_category_id",
|
||||
).Where(squirrel.Eq{"c.code": categoryCode})
|
||||
}
|
||||
|
||||
sql, args, err := q.ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var result []*typescore.User
|
||||
for rows.Next() {
|
||||
usr := &typescore.User{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, usr, nil); err != nil {
|
||||
logrus.Warn("GetControllerObserversForApprovalDB:ScanRowsToStruct", err)
|
||||
continue
|
||||
}
|
||||
result = append(result, usr)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// GetUsersByRoleFlagsDB — пользователи, у которых есть роль с любым из указанных флагов
|
||||
// (is_director, is_approver, is_observer, is_executor, is_controller)
|
||||
func (u *UserDB) GetUsersByRoleFlagsDB(ctx context.Context, flags []string) ([]*typescore.User, error) {
|
||||
if len(flags) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
allowedFlags := map[string]string{
|
||||
"director": "r.is_director",
|
||||
"approver": "r.is_approver",
|
||||
"observer": "r.is_observer",
|
||||
"executor": "r.is_executor",
|
||||
"controller": "r.is_controller",
|
||||
}
|
||||
|
||||
var orConds squirrel.Or
|
||||
for _, f := range flags {
|
||||
if col, ok := allowedFlags[f]; ok {
|
||||
orConds = append(orConds, squirrel.Expr(col+" = true"))
|
||||
}
|
||||
}
|
||||
if len(orConds) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select("DISTINCT u.*").
|
||||
From(dbcoretablenames.TableNameUsers.ToString() + " u").
|
||||
Join(dbcoretablenames.TableNameUserRoles.ToString() + " ur ON ur.user_id = u.id").
|
||||
Join(dbcoretablenames.TableNameRoles.ToString() + " r ON r.id = ur.role_id").
|
||||
Where(orConds).
|
||||
Where(squirrel.Eq{"u.is_blocked": false}).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var users []*typescore.User
|
||||
for rows.Next() {
|
||||
user := &typescore.User{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, user, nil); err != nil {
|
||||
logrus.Warn("GetUsersByRoleFlagsDB:ScanRowsToStructRows", err)
|
||||
continue
|
||||
}
|
||||
users = append(users, user)
|
||||
}
|
||||
return users, nil
|
||||
}
|
||||
|
||||
// GetUsersByDepartmentIDsDB — пользователи из списка отделов
|
||||
func (u *UserDB) GetUsersByDepartmentIDsDB(ctx context.Context, departmentIDs []uint64) ([]*typescore.User, error) {
|
||||
if len(departmentIDs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.User{}, dbcoretablenames.TableNameUsers.ToString())
|
||||
|
||||
sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select(fields...).
|
||||
From(dbcoretablenames.TableNameUsers.ToString()).
|
||||
Where(squirrel.Eq{"department_id": departmentIDs}).
|
||||
Where(squirrel.Eq{"is_blocked": false}).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var users []*typescore.User
|
||||
for rows.Next() {
|
||||
user := &typescore.User{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, user, nil); err != nil {
|
||||
logrus.Warn("GetUsersByDepartmentIDsDB:ScanRowsToStructRows", err)
|
||||
continue
|
||||
}
|
||||
users = append(users, user)
|
||||
}
|
||||
return users, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import (
|
|||
dbutils "bitrix_balancer_api/core/utilscore/db"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/Masterminds/squirrel"
|
||||
|
|
@ -28,8 +29,8 @@ type UserHierarchyDBI interface {
|
|||
CreateUserHierarchyDB(ctx context.Context, tx pgx.Tx, UserHierarchyObj *typescore.UserHierarchy, returnObj ...bool) (*typescore.UserHierarchy, pgx.Tx, error)
|
||||
UpdateUserHierarchyDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.UserHierarchy, returnObj ...bool) (*typescore.UserHierarchy, pgx.Tx, error)
|
||||
DeleteUserHierarchyDB(ctx context.Context, params *typescore.UserHierarchy) error
|
||||
|
||||
GetApproversDB(ctx context.Context, subordinateID uint64, departmentID uint64) ([]*typescore.User, error)
|
||||
GetApproversDB(ctx context.Context, subordinateID, departmentID, topicID, categoryID uint64, systems []string) ([]*typescore.User, error)
|
||||
GetHierarchiesWithRelations(ctx context.Context, opts typescore.ListDbOptions, userStatuses ...string) ([]*typescore.UserHierarchy, uint64, error)
|
||||
}
|
||||
|
||||
func (u *UserHierarchyDB) GetUserHierarchyListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.UserHierarchy, uint64, error) {
|
||||
|
|
@ -101,7 +102,7 @@ func (u *UserHierarchyDB) CreateUserHierarchyDB(ctx context.Context, tx pgx.Tx,
|
|||
returnObjBool = returnObj[0]
|
||||
}
|
||||
if returnObjBool {
|
||||
UserHierarchy, _, err := u.GetUserHierarchyListDB(ctx, typescore.ListDbOptions{Filtering: UserHierarchyObj})
|
||||
UserHierarchy, _, err := u.GetHierarchiesWithRelations(ctx, typescore.ListDbOptions{Filtering: UserHierarchyObj})
|
||||
if err != nil {
|
||||
return nil, tx, err
|
||||
}
|
||||
|
|
@ -147,7 +148,7 @@ func (u *UserHierarchyDB) UpdateUserHierarchyDB(ctx context.Context, tx pgx.Tx,
|
|||
|
||||
if returnObjBool {
|
||||
options := typescore.ListDbOptions{Filtering: &typescore.UserHierarchy{ID: paramsUpdate.ID}}
|
||||
getInfoUp, _, err := u.GetUserHierarchyListDB(ctx, options)
|
||||
getInfoUp, _, err := u.GetHierarchiesWithRelations(ctx, options)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
|
@ -160,58 +161,97 @@ func (u *UserHierarchyDB) UpdateUserHierarchyDB(ctx context.Context, tx pgx.Tx,
|
|||
}
|
||||
|
||||
func (u *UserHierarchyDB) DeleteUserHierarchyDB(ctx context.Context, params *typescore.UserHierarchy) error {
|
||||
if params != nil && params.ID != nil {
|
||||
query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Delete(dbcoretablenames.TableNameUserHierarchy.ToString()).
|
||||
Where(squirrel.Eq{"id": *params.ID}).
|
||||
ToSql()
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
return nil
|
||||
} else {
|
||||
return errors.New("userHierarchy obj is nil")
|
||||
if params == nil || params.ID == nil {
|
||||
return errors.New("userHierarchy obj or id is nil")
|
||||
}
|
||||
|
||||
query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Delete(dbcoretablenames.TableNameUserHierarchy.ToString()).
|
||||
Where(squirrel.Eq{"id": *params.ID}).
|
||||
ToSql()
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = u.pool.Exec(ctx, query, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (u *UserHierarchyDB) GetApproversDB(ctx context.Context, subordinateID, departmentID, topicID, categoryID uint64) ([]*typescore.User, error) {
|
||||
// GetApproversDB возвращает список согласующих для (subordinateID, departmentID,
|
||||
// topicID, categoryID), с учётом целевой системы (systems[0], если задана).
|
||||
// GetApproversDB возвращает список согласующих для (subordinateID, departmentID,
|
||||
// topicID, categoryID), с учётом целевой системы (systems[0], если задана).
|
||||
// ИСПОЛЬЗУЕТ КАСКАДНЫЙ ПОИСК: Точная тема -> Родительская тема -> Категория -> Глобальное правило
|
||||
// GetApproversDB возвращает список согласующих для (subordinateID, departmentID,
|
||||
// topicID, categoryID), с учётом целевой системы (systems[0], если задана).
|
||||
// ИСПОЛЬЗУЕТ КАСКАДНЫЙ ПОИСК: Точная тема -> Родительская тема -> Категория -> Глобальное правило
|
||||
func (u *UserHierarchyDB) GetApproversDB(
|
||||
ctx context.Context,
|
||||
subordinateID, departmentID, topicID, categoryID uint64,
|
||||
systems []string,
|
||||
) ([]*typescore.User, error) {
|
||||
system := ""
|
||||
if len(systems) > 0 {
|
||||
system = systems[0]
|
||||
}
|
||||
|
||||
rawSQL := `
|
||||
WITH ranked AS (
|
||||
WITH target_topic AS (
|
||||
SELECT code, category_id FROM approval_topics WHERE id = $3
|
||||
),
|
||||
matching_topics AS (
|
||||
SELECT t.id, LENGTH(t.code) as spec_score
|
||||
FROM approval_topics t
|
||||
CROSS JOIN target_topic tt
|
||||
WHERE strpos(tt.code || '_', t.code || '_') = 1
|
||||
AND t.category_id = tt.category_id
|
||||
),
|
||||
ranked AS (
|
||||
SELECT
|
||||
uh.approver_id,
|
||||
uh.priority,
|
||||
uh.target_system,
|
||||
CASE
|
||||
WHEN uh.topic_id = $3 THEN 1
|
||||
WHEN uh.topic_category_id = $4 THEN 2
|
||||
WHEN uh.topic_id IS NULL
|
||||
AND uh.topic_category_id IS NULL THEN 3
|
||||
WHEN mt.id IS NOT NULL THEN 1000 - mt.spec_score
|
||||
WHEN uh.topic_category_id = $4 AND uh.topic_id IS NULL THEN 2000
|
||||
WHEN uh.topic_id IS NULL AND uh.topic_category_id IS NULL THEN 3000
|
||||
END AS specificity
|
||||
FROM user_hierarchy uh
|
||||
LEFT JOIN matching_topics mt ON uh.topic_id = mt.id
|
||||
WHERE uh.subordinate_id = $1
|
||||
AND uh.department_id = $2
|
||||
AND (
|
||||
uh.topic_id = $3
|
||||
OR uh.topic_category_id = $4
|
||||
mt.id IS NOT NULL
|
||||
OR (uh.topic_category_id = $4 AND uh.topic_id IS NULL)
|
||||
OR (uh.topic_id IS NULL AND uh.topic_category_id IS NULL)
|
||||
)
|
||||
),
|
||||
best AS (
|
||||
-- берём только уровень с наивысшей специфичностью
|
||||
SELECT MIN(specificity) AS min_spec FROM ranked
|
||||
),
|
||||
candidates AS (
|
||||
SELECT r.approver_id, r.priority, r.target_system
|
||||
FROM ranked r
|
||||
JOIN best b ON r.specificity = b.min_spec
|
||||
),
|
||||
system_choice AS (
|
||||
SELECT EXISTS (
|
||||
SELECT 1 FROM candidates c WHERE c.target_system = $5
|
||||
) AS has_override
|
||||
)
|
||||
SELECT u.*
|
||||
FROM ranked r
|
||||
JOIN best b ON r.specificity = b.min_spec
|
||||
JOIN users u ON u.id = r.approver_id
|
||||
ORDER BY r.priority ASC
|
||||
FROM candidates c
|
||||
CROSS JOIN system_choice sc
|
||||
JOIN users u ON u.id = c.approver_id
|
||||
WHERE
|
||||
(sc.has_override AND c.target_system = $5)
|
||||
OR (NOT sc.has_override AND (c.target_system IS NULL OR c.target_system = 'all'))
|
||||
ORDER BY c.priority ASC
|
||||
`
|
||||
|
||||
rows, err := u.pool.Query(ctx, rawSQL,
|
||||
|
|
@ -219,20 +259,157 @@ func (u *UserHierarchyDB) GetApproversDB(ctx context.Context, subordinateID, dep
|
|||
departmentID,
|
||||
topicID,
|
||||
categoryID,
|
||||
system,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var result []*typescore.User
|
||||
var approvers []*typescore.User
|
||||
seen := make(map[uint64]bool)
|
||||
for rows.Next() {
|
||||
usr := &typescore.User{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, usr, nil); err != nil {
|
||||
logrus.Warn("GetApproversDB:ScanRowsToStructRows", err)
|
||||
continue
|
||||
}
|
||||
result = append(result, usr)
|
||||
if usr.ID == nil || seen[*usr.ID] {
|
||||
continue
|
||||
}
|
||||
seen[*usr.ID] = true
|
||||
approvers = append(approvers, usr)
|
||||
}
|
||||
return result, nil
|
||||
|
||||
logrus.Infof("✅ GetApproversDB DONE: Найдено уникальных согласующих: %d", len(approvers))
|
||||
return approvers, nil
|
||||
}
|
||||
|
||||
// GetHierarchiesWithRelations(ctx context.Context, opts typescore.ListDbOptions, userStatus string) ([]*typescore.UserHierarchy, uint64, error)
|
||||
func (u *UserHierarchyDB) GetHierarchiesWithRelations(ctx context.Context, opts typescore.ListDbOptions, userStatuses ...string) ([]*typescore.UserHierarchy, uint64, error) {
|
||||
options, filter, err := dbutils.GetOptionsDB[typescore.UserHierarchy](opts)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
userStatus := ""
|
||||
if len(userStatuses) > 0 {
|
||||
userStatus = userStatuses[0]
|
||||
}
|
||||
|
||||
query := squirrel.Select(
|
||||
"uh.id",
|
||||
"uh.subordinate_id",
|
||||
"uh.approver_id",
|
||||
"uh.department_id",
|
||||
"uh.topic_category_id",
|
||||
"uh.topic_id",
|
||||
"uh.priority",
|
||||
"uh.target_system",
|
||||
"uh.created_at",
|
||||
"uh.updated_at",
|
||||
"sub.id", "sub.full_name", "sub.username", "sub.is_blocked", "sub.is_fired",
|
||||
"app.id", "app.full_name", "app.username", "app.is_blocked", "app.is_fired",
|
||||
"dep.id", "dep.name",
|
||||
"cat.id", "cat.name",
|
||||
"top.id", "top.name",
|
||||
"COUNT(*) OVER() AS total_count",
|
||||
).
|
||||
From("user_hierarchy uh").
|
||||
LeftJoin("users sub ON uh.subordinate_id = sub.id").
|
||||
LeftJoin("users app ON uh.approver_id = app.id").
|
||||
LeftJoin("departments dep ON uh.department_id = dep.id").
|
||||
LeftJoin("approval_topic_categories cat ON uh.topic_category_id = cat.id").
|
||||
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")
|
||||
|
||||
sql, args, err := query.PlaceholderFormat(squirrel.Dollar).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 results []*typescore.UserHierarchy
|
||||
var totalCount uint64
|
||||
|
||||
for rows.Next() {
|
||||
h := &typescore.UserHierarchy{
|
||||
Subordinate: &typescore.User{},
|
||||
Approver: &typescore.User{},
|
||||
Department: &typescore.Department{},
|
||||
TopicCategory: &typescore.ApprovalTopicCategory{},
|
||||
Topic: &typescore.ApprovalTopic{},
|
||||
}
|
||||
|
||||
err := rows.Scan(
|
||||
&h.ID, &h.SubordinateID, &h.ApproverID, &h.DepartmentID,
|
||||
&h.TopicCategoryID, &h.TopicID, &h.Priority,
|
||||
&h.TargetSystem,
|
||||
&h.CreatedAt, &h.UpdatedAt,
|
||||
&h.Subordinate.ID, &h.Subordinate.FullName, &h.Subordinate.Username, &h.Subordinate.IsBlocked, &h.Subordinate.IsFired,
|
||||
&h.Approver.ID, &h.Approver.FullName, &h.Approver.Username, &h.Approver.IsBlocked, &h.Approver.IsFired,
|
||||
&h.Department.ID, &h.Department.Name,
|
||||
&h.TopicCategory.ID, &h.TopicCategory.Name,
|
||||
&h.Topic.ID, &h.Topic.Name,
|
||||
&totalCount,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, 0, fmt.Errorf("scan error: %w", err)
|
||||
}
|
||||
results = append(results, h)
|
||||
}
|
||||
|
||||
return results, totalCount, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,6 +28,7 @@ type UserRoleDBI interface {
|
|||
CreateUserRoleDB(ctx context.Context, tx pgx.Tx, UserRoleObj *typescore.UserRole, returnObj ...bool) (*typescore.UserRole, pgx.Tx, error)
|
||||
UpdateUserRoleDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.UserRole, returnObj ...bool) (*typescore.UserRole, pgx.Tx, error)
|
||||
DeleteUserRoleDB(ctx context.Context, params *typescore.UserRole) error
|
||||
CreateUserRolesBulkDB(ctx context.Context, tx pgx.Tx, userID uint64, roleIDs []uint64) ([]*typescore.UserRole, error)
|
||||
}
|
||||
|
||||
func (u *UserRoleDB) GetUserRolesListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.UserRole, uint64, error) {
|
||||
|
|
@ -168,14 +169,96 @@ func (u *UserRoleDB) DeleteUserRoleDB(ctx context.Context, params *typescore.Use
|
|||
return err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, query, args...)
|
||||
_, err = u.pool.Exec(ctx, query, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
return nil
|
||||
} else {
|
||||
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,26 +3,39 @@ package dbcoretablenames
|
|||
type TableName string
|
||||
|
||||
const (
|
||||
TableNameApprovals TableName = "approvals"
|
||||
TableNameApprovalSteps TableName = "approval_steps"
|
||||
TableNameApprovalTopics TableName = "approval_topics"
|
||||
TableNameApprovalTopicCategories TableName = "approval_topic_categories"
|
||||
TableNameDepartments TableName = "departments"
|
||||
TableNamePermissions TableName = "permissions"
|
||||
TableNameRoles TableName = "roles"
|
||||
TableNameUsers TableName = "users"
|
||||
TableNameUserHierarchy TableName = "user_hierarchy"
|
||||
TableNameUserRoles TableName = "user_roles"
|
||||
TableNameApprovalFiles TableName = "approval_files"
|
||||
TableNameApprovalDelegations TableName = "approval_delegations"
|
||||
TableNameApprovalAdditionalApprovers TableName = "approval_additional_approvers"
|
||||
TableNameApprovalAdditionalObservers TableName = "approval_additional_observers"
|
||||
TableNameApprovalTasks TableName = "approval_tasks"
|
||||
TableNameApprovalComments TableName = "approval_comments"
|
||||
TableNameSuggestions TableName = "suggestions"
|
||||
TableNameSuggestionMessages TableName = "suggestion_messages"
|
||||
TableNameApprovalTopicExecutor TableName = "approval_topic_executor"
|
||||
TableNameAdmin TableName = "admin"
|
||||
TableNameApprovals TableName = "approvals"
|
||||
TableNameApprovalSteps TableName = "approval_steps"
|
||||
TableNameApprovalTopics TableName = "approval_topics"
|
||||
TableNameApprovalTopicCategories TableName = "approval_topic_categories"
|
||||
TableNameDepartments TableName = "departments"
|
||||
TableNamePermissions TableName = "permissions"
|
||||
TableNameRoles TableName = "roles"
|
||||
TableNameUsers TableName = "users"
|
||||
TableNameUserHierarchy TableName = "user_hierarchy"
|
||||
TableNameUserRoles TableName = "user_roles"
|
||||
TableNameApprovalFiles TableName = "approval_files"
|
||||
TableNameApprovalDelegations TableName = "approval_delegations"
|
||||
TableNameApprovalAdditionalApprovers TableName = "approval_additional_approvers"
|
||||
TableNameApprovalAdditionalObservers TableName = "approval_additional_observers"
|
||||
TableNameApprovalTasks TableName = "approval_tasks"
|
||||
TableNameApprovalComments TableName = "approval_comments"
|
||||
TableNameSuggestions TableName = "suggestions"
|
||||
TableNameSuggestionMessages TableName = "suggestion_messages"
|
||||
TableNameApprovalTopicExecutor TableName = "approval_topic_executor"
|
||||
TableNameAdmin TableName = "admin"
|
||||
TableNameNotifications TableName = "notifications"
|
||||
TableNameNotificationsRecipients TableName = "notification_recipients"
|
||||
TableNameDirectorNotificationSubscriptions TableName = "director_notification_subscriptions"
|
||||
TableNameApprovalTaskTransfers TableName = "approval_task_transfers"
|
||||
TableNameApprovalRevocationRequests TableName = "approval_revocation_requests"
|
||||
TableNameApprovalRevocationApprovers TableName = "approval_revocation_approvers"
|
||||
TableNameApprovalFlowNodes TableName = "approval_flow_nodes"
|
||||
TableNameAdminActionLogs TableName = "admin_action_logs"
|
||||
TableNameMonthlyOrderSettings TableName = "monthly_order_settings"
|
||||
TableNameMonthlyOrderClients TableName = "monthly_order_clients"
|
||||
TableNameMonthlyOrderItems TableName = "monthly_order_items"
|
||||
TableNameMonthlyOrderFiles TableName = "monthly_order_files"
|
||||
TableNameTaskDelegations TableName = "task_delegations"
|
||||
)
|
||||
|
||||
func (t TableName) ToString() string {
|
||||
|
|
|
|||
33
core/go.mod
33
core/go.mod
|
|
@ -13,18 +13,27 @@ require (
|
|||
github.com/redis/go-redis/v9 v9.18.0
|
||||
github.com/shopspring/decimal v1.4.0
|
||||
github.com/sirupsen/logrus v1.9.4
|
||||
golang.org/x/crypto v0.40.0
|
||||
golang.org/x/net v0.42.0
|
||||
golang.org/x/crypto v0.54.0
|
||||
golang.org/x/net v0.57.0
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
gorm.io/driver/postgres v1.6.0
|
||||
gorm.io/gorm v1.31.1
|
||||
)
|
||||
|
||||
require (
|
||||
cloud.google.com/go/auth v0.23.0 // indirect
|
||||
cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect
|
||||
cloud.google.com/go/compute/metadata v0.9.0 // indirect
|
||||
github.com/cenkalti/backoff/v4 v4.3.0 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||
github.com/go-jose/go-jose/v4 v4.1.1 // indirect
|
||||
github.com/felixge/httpsnoop v1.0.4 // indirect
|
||||
github.com/go-jose/go-jose/v4 v4.1.4 // indirect
|
||||
github.com/go-logr/logr v1.4.3 // indirect
|
||||
github.com/go-logr/stdr v1.2.2 // indirect
|
||||
github.com/google/s2a-go v0.1.9 // indirect
|
||||
github.com/googleapis/enterprise-certificate-proxy v0.3.20 // indirect
|
||||
github.com/googleapis/gax-go/v2 v2.23.0 // indirect
|
||||
github.com/hashicorp/errwrap v1.1.0 // indirect
|
||||
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
|
||||
github.com/hashicorp/go-multierror v1.1.1 // indirect
|
||||
|
|
@ -45,9 +54,19 @@ require (
|
|||
github.com/mitchellh/go-homedir v1.1.0 // indirect
|
||||
github.com/rogpeppe/go-internal v1.14.1 // indirect
|
||||
github.com/ryanuber/go-glob v1.0.0 // indirect
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0 // indirect
|
||||
go.opentelemetry.io/otel v1.44.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.44.0 // indirect
|
||||
go.opentelemetry.io/otel/trace v1.44.0 // indirect
|
||||
go.uber.org/atomic v1.11.0 // indirect
|
||||
golang.org/x/sync v0.17.0 // indirect
|
||||
golang.org/x/sys v0.41.0 // indirect
|
||||
golang.org/x/text v0.29.0 // indirect
|
||||
golang.org/x/time v0.12.0 // indirect
|
||||
golang.org/x/oauth2 v0.36.0 // indirect
|
||||
golang.org/x/sync v0.22.0 // indirect
|
||||
golang.org/x/sys v0.47.0 // indirect
|
||||
golang.org/x/text v0.40.0 // indirect
|
||||
golang.org/x/time v0.15.0 // indirect
|
||||
google.golang.org/api v0.293.0 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260807164820-c8921c73eeea // indirect
|
||||
google.golang.org/grpc v1.83.0 // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
)
|
||||
|
|
|
|||
52
core/go.sum
52
core/go.sum
|
|
@ -1,3 +1,9 @@
|
|||
cloud.google.com/go/auth v0.23.0 h1:6Gg1CMgpgubRG7DGz5Vf1pcoNo8RfiRiRAPS4crTp54=
|
||||
cloud.google.com/go/auth v0.23.0/go.mod h1:4DhBRcqvtljQN3dJ57qtqbib5ZGCYE5f2crfiiC2EM0=
|
||||
cloud.google.com/go/auth/oauth2adapt v0.2.8 h1:keo8NaayQZ6wimpNSmW5OPc283g65QNIiLpZnkHRbnc=
|
||||
cloud.google.com/go/auth/oauth2adapt v0.2.8/go.mod h1:XQ9y31RkqZCcwJWNSx2Xvric3RrU88hAYYbjDWYDL+c=
|
||||
cloud.google.com/go/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdBtwLoEkH9Zs=
|
||||
cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10=
|
||||
github.com/Masterminds/squirrel v1.5.4 h1:uUcX/aBc8O7Fg9kaISIUsHXdKuqehiXAMQTYX8afzqM=
|
||||
github.com/Masterminds/squirrel v1.5.4/go.mod h1:NNaOrjSoIDfDA40n7sr2tPNZRfjzjA400rg+riTZj10=
|
||||
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
|
||||
|
|
@ -16,16 +22,30 @@ github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/r
|
|||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
|
||||
github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM=
|
||||
github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU=
|
||||
github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
|
||||
github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
|
||||
github.com/go-jose/go-jose/v4 v4.1.1 h1:JYhSgy4mXXzAdF3nUx3ygx347LRXJRrpgyU3adRmkAI=
|
||||
github.com/go-jose/go-jose/v4 v4.1.1/go.mod h1:BdsZGqgdO3b6tTc6LSE56wcDbMMLuPsw5d4ZD5f94kA=
|
||||
github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
|
||||
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
|
||||
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
|
||||
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||
github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1 h1:wG8n/XJQ07TmjbITcGiUaOtXxdrINDz1b0J1w0SzqDc=
|
||||
github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1/go.mod h1:A2S0CWkNylc2phvKXWBBdD3K0iGnDBGbzRpISP2zBl8=
|
||||
github.com/go-test/deep v1.1.1 h1:0r/53hagsehfO4bzD2Pgr/+RgHqhmf+k1Bpse2cTu1U=
|
||||
github.com/go-test/deep v1.1.1/go.mod h1:5C2ZWiW0ErCdrYzpqxLbTX7MG14M9iiw8DgHncVwcsE=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
||||
github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0=
|
||||
github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/googleapis/enterprise-certificate-proxy v0.3.20 h1:t/xL64VUoN69MuMRQuJETqYGOw4Z9mSRJK9epIEtwFk=
|
||||
github.com/googleapis/enterprise-certificate-proxy v0.3.20/go.mod h1:L3D/IQExI6LqEjBdXcZQ1WluSgigQmSwBboFstVPM4w=
|
||||
github.com/googleapis/gax-go/v2 v2.23.0 h1:Tchl7qkvE7Ip3y+ztvNufYFvkfqTe7NfLTYGIdJRLuE=
|
||||
github.com/googleapis/gax-go/v2 v2.23.0/go.mod h1:rBQKOVJCdb8IFEzg+FCwlt1LP/xMDGuqUXhUG+XMXEg=
|
||||
github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
|
||||
github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I=
|
||||
github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
|
||||
|
|
@ -99,20 +119,52 @@ github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu
|
|||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/zeebo/xxh3 v1.0.2 h1:xZmwmqxHZA8AI603jOQ0tMqmBr9lPeFwGg6d+xy9DC0=
|
||||
github.com/zeebo/xxh3 v1.0.2/go.mod h1:5NWz9Sef7zIDm2JHfFlcQvNekmcEl9ekUZQQKCYaDcA=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0 h1:OyrsyzuttWTSur2qN/Lm0m2a8yqyIjUVBZcxFPuXq2o=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0/go.mod h1:C2NGBr+kAB4bk3xtMXfZ94gqFDtg/GkI7e9zqGh5Beg=
|
||||
go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU=
|
||||
go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc=
|
||||
go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc=
|
||||
go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo=
|
||||
go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk=
|
||||
go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE=
|
||||
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
|
||||
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
|
||||
golang.org/x/crypto v0.40.0 h1:r4x+VvoG5Fm+eJcxMaY8CQM7Lb0l1lsmjGBQ6s8BfKM=
|
||||
golang.org/x/crypto v0.40.0/go.mod h1:Qr1vMER5WyS2dfPHAlsOj01wgLbsyWtFn/aY+5+ZdxY=
|
||||
golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
|
||||
golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
|
||||
golang.org/x/net v0.42.0 h1:jzkYrhi3YQWD6MLBJcsklgQsoAcw89EcZbJw8Z614hs=
|
||||
golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8=
|
||||
golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE=
|
||||
golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=
|
||||
golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs=
|
||||
golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
|
||||
golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug=
|
||||
golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
||||
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
|
||||
golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
|
||||
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk=
|
||||
golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4=
|
||||
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
|
||||
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
|
||||
golang.org/x/time v0.12.0 h1:ScB/8o8olJvc+CQPWrK3fPZNfh7qgwCrY0zJmoEQLSE=
|
||||
golang.org/x/time v0.12.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
|
||||
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
|
||||
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
|
||||
google.golang.org/api v0.293.0 h1:p9XIWOf63U4OgYx120ZwVU8+vl4XTPmWfgVPnmOAS9w=
|
||||
google.golang.org/api v0.293.0/go.mod h1:6n5tjEB1gzwniZTepZ0g5u+wM7Bof5GeULCx/zh8ZE0=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260807164820-c8921c73eeea h1:kVhQEPTpKQahD5+JSBTfBB19wcgQTTjAIn45MBqnyHk=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260807164820-c8921c73eeea/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
|
||||
google.golang.org/grpc v1.83.0 h1:JeNZEKJFbQxArAMl+hiytHauacDNqJUllNfmIMmpqnQ=
|
||||
google.golang.org/grpc v1.83.0/go.mod h1:kDyl6SKsiHKt0uylY5gtn5cEjkrIOhQOGDgIc4JGwzQ=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
|
|
|
|||
|
|
@ -0,0 +1,200 @@
|
|||
package googlesheets
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"google.golang.org/api/drive/v3"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/oauth2/google"
|
||||
"google.golang.org/api/option"
|
||||
"google.golang.org/api/sheets/v4"
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
srv *sheets.Service
|
||||
driveSrv *drive.Service
|
||||
}
|
||||
|
||||
func NewClient(ctx context.Context, credentialsJSON []byte) (*Client, error) {
|
||||
if len(credentialsJSON) == 0 {
|
||||
return nil, fmt.Errorf("google-creds.json is empty")
|
||||
}
|
||||
|
||||
creds, err := google.CredentialsFromJSON(ctx, credentialsJSON, sheets.SpreadsheetsScope, drive.DriveScope)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid google-creds.json format: %v", err)
|
||||
}
|
||||
|
||||
srv, err := sheets.NewService(ctx, option.WithCredentials(creds))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
driveSrv, err := drive.NewService(ctx, option.WithCredentials(creds))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &Client{srv: srv, driveSrv: driveSrv}, nil
|
||||
}
|
||||
|
||||
func (c *Client) ExportMonthlyReportToMasterSheet(ctx context.Context, spreadsheetID string, sheet1Data, sheet2Data [][]interface{}) (string, error) {
|
||||
monthYearTitle := time.Now().Format("January 2006") // Например: "August 2026"
|
||||
ordersSheetName := "Заказы - " + monthYearTitle
|
||||
commentsSheetName := "Комментарии - " + monthYearTitle
|
||||
|
||||
// 1. Получаем структуру мастер-таблицы
|
||||
spreadsheet, err := c.srv.Spreadsheets.Get(spreadsheetID).Context(ctx).Do()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("не удалось получить доступ к мастер-таблице: %v", err)
|
||||
}
|
||||
|
||||
existingSheets := make(map[string]int64)
|
||||
for _, sheet := range spreadsheet.Sheets {
|
||||
existingSheets[sheet.Properties.Title] = sheet.Properties.SheetId
|
||||
}
|
||||
|
||||
// 2. Создаем или очищаем листы текущего месяца
|
||||
ensureSheet := func(title string) error {
|
||||
if _, exists := existingSheets[title]; exists {
|
||||
clearReq := &sheets.ClearValuesRequest{}
|
||||
_, err := c.srv.Spreadsheets.Values.Clear(spreadsheetID, title+"!A1:Z10000", clearReq).Context(ctx).Do()
|
||||
return err
|
||||
} else {
|
||||
addReq := &sheets.AddSheetRequest{
|
||||
Properties: &sheets.SheetProperties{Title: title},
|
||||
}
|
||||
batchReq := &sheets.BatchUpdateSpreadsheetRequest{
|
||||
Requests: []*sheets.Request{{AddSheet: addReq}},
|
||||
}
|
||||
_, err := c.srv.Spreadsheets.BatchUpdate(spreadsheetID, batchReq).Context(ctx).Do()
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if err := ensureSheet(ordersSheetName); err != nil {
|
||||
return "", fmt.Errorf("ошибка подготовки листа заказов: %v", err)
|
||||
}
|
||||
if err := ensureSheet(commentsSheetName); err != nil {
|
||||
return "", fmt.Errorf("ошибка подготовки листа комментариев: %v", err)
|
||||
}
|
||||
|
||||
// 3. Заливаем данные
|
||||
var data []*sheets.ValueRange
|
||||
data = append(data, &sheets.ValueRange{Range: ordersSheetName + "!A1", Values: sheet1Data})
|
||||
data = append(data, &sheets.ValueRange{Range: commentsSheetName + "!A1", Values: sheet2Data})
|
||||
|
||||
batchUpdateReq := &sheets.BatchUpdateValuesRequest{
|
||||
ValueInputOption: "USER_ENTERED",
|
||||
Data: data,
|
||||
}
|
||||
|
||||
_, err = c.srv.Spreadsheets.Values.BatchUpdate(spreadsheetID, batchUpdateReq).Context(ctx).Do()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("ошибка записи данных в таблицу: %v", err)
|
||||
}
|
||||
|
||||
// Возвращаем постоянную ссылку на таблицу
|
||||
return fmt.Sprintf("https://docs.google.com/spreadsheets/d/%s", spreadsheetID), nil
|
||||
}
|
||||
|
||||
// FetchNomenclature вытягивает справочник товаров
|
||||
func (c *Client) FetchNomenclature(spreadsheetID string) ([]NomenclatureItem, error) {
|
||||
resp, err := c.srv.Spreadsheets.Values.Get(spreadsheetID, "A:B").Do()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var items []NomenclatureItem
|
||||
for i, row := range resp.Values {
|
||||
if i == 0 {
|
||||
continue // Пропускаем заголовок
|
||||
}
|
||||
if len(row) > 0 {
|
||||
name := fmt.Sprintf("%v", row[0])
|
||||
itemType := ""
|
||||
if len(row) > 1 {
|
||||
itemType = fmt.Sprintf("%v", row[1])
|
||||
}
|
||||
if strings.TrimSpace(name) != "" {
|
||||
items = append(items, NomenclatureItem{Name: name, Type: itemType})
|
||||
}
|
||||
}
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
// FetchActiveClientsForManager вытягивает действующих клиентов для конкретного менеджера
|
||||
func (c *Client) FetchActiveClientsForManager(spreadsheetID, managerName string) ([]ClientItem, error) {
|
||||
// Расширяем диапазон до DB, чтобы захватить столбец филиала
|
||||
resp, err := c.srv.Spreadsheets.Values.Get(spreadsheetID, "A:DB").Do()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var clients []ClientItem
|
||||
for i, row := range resp.Values {
|
||||
if i == 0 {
|
||||
continue // Пропускаем заголовок
|
||||
}
|
||||
|
||||
// Убеждаемся, что строка достаточно длинная (индекс 74 для Status)
|
||||
if len(row) > 74 {
|
||||
clientName := fmt.Sprintf("%v", row[1]) // Столбец B
|
||||
manager := fmt.Sprintf("%v", row[24]) // Столбец Y
|
||||
status := fmt.Sprintf("%v", row[74]) // Столбец BW
|
||||
|
||||
// Пытаемся достать филиал из столбца DB (индекс 105).
|
||||
// Проверяем длину строки, так как в Go Sheets API пустые ячейки в конце строки обрезаются.
|
||||
branch := ""
|
||||
if len(row) > 105 {
|
||||
branch = fmt.Sprintf("%v", row[105])
|
||||
}
|
||||
|
||||
if strings.Contains(strings.ToLower(status), "действующий") &&
|
||||
strings.EqualFold(strings.TrimSpace(manager), strings.TrimSpace(managerName)) {
|
||||
clients = append(clients, ClientItem{
|
||||
Name: clientName,
|
||||
Manager: manager,
|
||||
Status: status,
|
||||
Branch: branch,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
return clients, nil
|
||||
}
|
||||
|
||||
// NomenclatureItem представляет одну строку из таблицы номенклатуры
|
||||
type NomenclatureItem struct {
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
}
|
||||
|
||||
// ClientItem представляет клиента из таблицы клиентов
|
||||
type ClientItem struct {
|
||||
Name string `json:"name"`
|
||||
Manager string `json:"manager"`
|
||||
Status string `json:"status"`
|
||||
Branch string `json:"branch"`
|
||||
}
|
||||
|
||||
// IsMonthReportExist проверяет, есть ли уже лист с отчетом за этот месяц в мастер-таблице
|
||||
func (c *Client) IsMonthReportExist(ctx context.Context, spreadsheetID string, targetDate time.Time) (bool, error) {
|
||||
monthYearTitle := targetDate.Format("January 2006")
|
||||
ordersSheetName := "Заказы - " + monthYearTitle
|
||||
|
||||
spreadsheet, err := c.srv.Spreadsheets.Get(spreadsheetID).Context(ctx).Do()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
for _, sheet := range spreadsheet.Sheets {
|
||||
if sheet.Properties.Title == ordersSheetName {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
|
@ -1,18 +1,403 @@
|
|||
package tgkit
|
||||
|
||||
import (
|
||||
"bitrix_balancer_api/core/variables"
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/sirupsen/logrus"
|
||||
"io"
|
||||
"mime"
|
||||
"mime/multipart"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
|
||||
"golang.org/x/net/proxy"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// APIProxyRequest описывает структуру тела запроса к твоему прокси-сервису
|
||||
type APIProxyRequest struct {
|
||||
URL string `json:"url"`
|
||||
Method string `json:"method"`
|
||||
Body interface{} `json:"body,omitempty"`
|
||||
}
|
||||
|
||||
type CustomAPIProxyTransport struct {
|
||||
wrapped http.RoundTripper
|
||||
|
||||
// Поля для fallback-механизма на бесплатные прокси
|
||||
fallbackSince time.Time
|
||||
mu sync.RWMutex
|
||||
fallbackMode bool
|
||||
fallbackProxyURL string
|
||||
fallbackTransport http.RoundTripper
|
||||
}
|
||||
|
||||
const (
|
||||
maxProxyConnectAttempts = 2
|
||||
proxyConnectRetryDelay = 500 * time.Millisecond
|
||||
defaultTimeout = 120 * time.Second
|
||||
maxStartupAttempts = 3
|
||||
startupRetryDelay = 3 * time.Second
|
||||
fallbackRetryInterval = 2 * time.Minute
|
||||
)
|
||||
|
||||
var (
|
||||
mu sync.Mutex
|
||||
instance *Client
|
||||
)
|
||||
|
||||
func (t *CustomAPIProxyTransport) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
// 1. Сразу считываем оригинальное тело запроса в память.
|
||||
// Это критично, так как при падении шлюза нам нужно будет отправить
|
||||
// эти же оригинальные данные через резервный бесплатный прокси.
|
||||
var rawOriginalBody []byte
|
||||
if req.Body != nil {
|
||||
rawOriginalBody, _ = io.ReadAll(req.Body)
|
||||
_ = req.Body.Close()
|
||||
}
|
||||
|
||||
t.mu.Lock()
|
||||
useFallback := t.fallbackMode && t.fallbackTransport != nil
|
||||
if useFallback && time.Since(t.fallbackSince) >= fallbackRetryInterval {
|
||||
t.fallbackSince = time.Now()
|
||||
useFallback = false
|
||||
logrus.Infof("tgkit: trying to return to the main gateway...")
|
||||
}
|
||||
fallbackTrans := t.fallbackTransport
|
||||
currentFallbackURL := t.fallbackProxyURL
|
||||
t.mu.Unlock()
|
||||
|
||||
if useFallback {
|
||||
return t.executeFallback(req, rawOriginalBody, fallbackTrans, currentFallbackURL)
|
||||
}
|
||||
|
||||
// === Стандартный путь через приватный шлюз ===
|
||||
targetURL := req.URL.String()
|
||||
method := req.Method
|
||||
var proxyReq *http.Request
|
||||
var bodyBytesForRetry []byte
|
||||
|
||||
contentType := req.Header.Get("Content-Type")
|
||||
mediaType, params, _ := mime.ParseMediaType(contentType)
|
||||
|
||||
if mediaType == "multipart/form-data" && len(rawOriginalBody) > 0 {
|
||||
var buf bytes.Buffer
|
||||
writer := multipart.NewWriter(&buf)
|
||||
|
||||
_ = writer.WriteField("url", targetURL)
|
||||
_ = writer.WriteField("method", method)
|
||||
|
||||
boundary := params["boundary"]
|
||||
mr := multipart.NewReader(bytes.NewReader(rawOriginalBody), boundary)
|
||||
for {
|
||||
part, err := mr.NextPart()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("proxy transport: parse incoming multipart: %w", err)
|
||||
}
|
||||
|
||||
partBytes, _ := io.ReadAll(part)
|
||||
|
||||
if part.FileName() != "" {
|
||||
filePart, err := writer.CreateFormFile(part.FormName(), part.FileName())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("proxy transport: create form file: %w", err)
|
||||
}
|
||||
_, _ = filePart.Write(partBytes)
|
||||
} else {
|
||||
fieldPart, err := writer.CreateFormField(part.FormName())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("proxy transport: create form field: %w", err)
|
||||
}
|
||||
_, _ = fieldPart.Write(partBytes)
|
||||
}
|
||||
}
|
||||
_ = writer.Close()
|
||||
bodyBytesForRetry = buf.Bytes()
|
||||
|
||||
var err error
|
||||
proxyReq, err = http.NewRequestWithContext(req.Context(), "POST", variables.ProxyForwardURL, bytes.NewReader(bodyBytesForRetry))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("proxy transport: failed to create multipart request: %w", err)
|
||||
}
|
||||
proxyReq.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
} else {
|
||||
var originalBody interface{} = map[string]interface{}{}
|
||||
|
||||
if len(rawOriginalBody) > 0 {
|
||||
var raw json.RawMessage
|
||||
if err := json.Unmarshal(rawOriginalBody, &raw); err == nil {
|
||||
originalBody = raw
|
||||
} else {
|
||||
values, err := url.ParseQuery(string(rawOriginalBody))
|
||||
if err == nil && len(values) > 0 {
|
||||
bodyMap := make(map[string]interface{})
|
||||
for key, val := range values {
|
||||
if len(val) == 1 {
|
||||
bodyMap[key] = val[0]
|
||||
} else if len(val) > 1 {
|
||||
bodyMap[key] = val
|
||||
}
|
||||
}
|
||||
originalBody = bodyMap
|
||||
} else {
|
||||
originalBody = string(rawOriginalBody)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
proxyReqPayload := APIProxyRequest{
|
||||
URL: targetURL,
|
||||
Method: method,
|
||||
Body: originalBody,
|
||||
}
|
||||
|
||||
proxyJsonBytes, err := json.Marshal(proxyReqPayload)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("proxy transport: failed to marshal proxy payload: %w", err)
|
||||
}
|
||||
bodyBytesForRetry = proxyJsonBytes
|
||||
|
||||
proxyReq, err = http.NewRequestWithContext(req.Context(), "POST", variables.ProxyForwardURL, bytes.NewReader(bodyBytesForRetry))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("proxy transport: failed to create json request: %w", err)
|
||||
}
|
||||
proxyReq.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
|
||||
proxyReq.Header.Set(variables.ProxySecretHeader, variables.ProxySecretKey)
|
||||
|
||||
resp, err := t.roundTripWithRetry(proxyReq, bodyBytesForRetry)
|
||||
if err == nil {
|
||||
resp, err = readJSONResponse(resp) // функция из пункта 1 прошлого ответа
|
||||
}
|
||||
if err != nil {
|
||||
logrus.Warnf("tgkit: custom gateway failed (%v), switching to free fallback proxies.", err)
|
||||
return t.switchToFallbackAndExecute(req, rawOriginalBody, "")
|
||||
}
|
||||
|
||||
t.mu.Lock()
|
||||
if t.fallbackMode {
|
||||
t.fallbackMode = false
|
||||
logrus.Infof("tgkit: main gateway is back, fallback proxy disabled")
|
||||
}
|
||||
t.mu.Unlock()
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func looksLikeJSON(b []byte) bool {
|
||||
b = bytes.TrimSpace(b)
|
||||
return len(b) > 0 && b[0] == '{'
|
||||
}
|
||||
|
||||
// readJSONResponse читает тело, проверяет что это JSON, и возвращает тело обратно в resp
|
||||
func readJSONResponse(resp *http.Response) (*http.Response, error) {
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
_ = resp.Body.Close()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !looksLikeJSON(body) {
|
||||
return nil, fmt.Errorf("non-JSON response (status %d): %.200q", resp.StatusCode, body)
|
||||
}
|
||||
resp.Body = io.NopCloser(bytes.NewReader(body))
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (t *CustomAPIProxyTransport) roundTripWithRetry(req *http.Request, bodyBytes []byte) (*http.Response, error) {
|
||||
var lastErr error
|
||||
for attempt := 1; attempt <= maxProxyConnectAttempts; attempt++ {
|
||||
req.Body = io.NopCloser(bytes.NewReader(bodyBytes))
|
||||
req.ContentLength = int64(len(bodyBytes))
|
||||
|
||||
resp, err := t.wrapped.RoundTrip(req)
|
||||
if err != nil {
|
||||
lastErr = err
|
||||
logrus.Warnf("tgkit: gateway connect attempt %d/%d failed: %v", attempt, maxProxyConnectAttempts, err)
|
||||
if attempt < maxProxyConnectAttempts {
|
||||
time.Sleep(proxyConnectRetryDelay)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if resp.StatusCode >= 500 {
|
||||
defer resp.Body.Close()
|
||||
errorBody, _ := io.ReadAll(resp.Body)
|
||||
return nil, fmt.Errorf("proxy returned status %d (%s): %s", resp.StatusCode, resp.Status, string(errorBody))
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
return nil, lastErr
|
||||
}
|
||||
|
||||
// executeFallback перенаправляет оригинальный запрос напрямую в Telegram через найденный бесплатный прокси
|
||||
func (t *CustomAPIProxyTransport) executeFallback(req *http.Request, body []byte, trans http.RoundTripper, currentProxyURL string) (*http.Response, error) {
|
||||
newReq := req.Clone(req.Context())
|
||||
if len(body) > 0 {
|
||||
newReq.Body = io.NopCloser(bytes.NewReader(body))
|
||||
newReq.ContentLength = int64(len(body))
|
||||
}
|
||||
|
||||
resp, err := trans.RoundTrip(newReq)
|
||||
if err == nil {
|
||||
resp, err = readJSONResponse(resp)
|
||||
}
|
||||
if err != nil {
|
||||
logrus.Warnf("tgkit: fallback proxy %s failed (%v), searching for a new one...", currentProxyURL, err)
|
||||
return t.switchToFallbackAndExecute(req, body, currentProxyURL)
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// switchToFallbackAndExecute блокирует транспорт, находит самый быстрый прокси и обновляет конфигурацию
|
||||
func (t *CustomAPIProxyTransport) switchToFallbackAndExecute(req *http.Request, body []byte, failedProxyURL string) (*http.Response, error) {
|
||||
t.mu.Lock()
|
||||
// Если другая горутина уже нашла новый прокси, пока мы ждали мьютекс, используем его
|
||||
if t.fallbackMode && t.fallbackProxyURL != failedProxyURL {
|
||||
savedTrans := t.fallbackTransport
|
||||
currentURL := t.fallbackProxyURL
|
||||
t.mu.Unlock()
|
||||
return t.executeFallback(req, body, savedTrans, currentURL)
|
||||
}
|
||||
|
||||
logrus.Infof("tgkit: searching for the fastest free proxy...")
|
||||
newProxyURL, err := findFastestFreeProxy()
|
||||
if err != nil {
|
||||
t.mu.Unlock()
|
||||
return nil, fmt.Errorf("failed to find a working free proxy: %w", err)
|
||||
}
|
||||
|
||||
parsedURL, _ := url.Parse(newProxyURL)
|
||||
newTrans := &http.Transport{
|
||||
Proxy: http.ProxyURL(parsedURL),
|
||||
DialContext: (&net.Dialer{
|
||||
Timeout: 10 * time.Second,
|
||||
KeepAlive: 30 * time.Second,
|
||||
}).DialContext,
|
||||
TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // Бесплатные прокси часто имеют кривые сертификаты
|
||||
}
|
||||
|
||||
t.fallbackMode = true
|
||||
t.fallbackProxyURL = newProxyURL
|
||||
t.fallbackTransport = newTrans
|
||||
savedTrans := newTrans
|
||||
t.fallbackSince = time.Now()
|
||||
t.mu.Unlock()
|
||||
|
||||
logrus.Infof("tgkit: successfully switched to free proxy: %s", newProxyURL)
|
||||
return t.executeFallback(req, body, savedTrans, newProxyURL)
|
||||
}
|
||||
|
||||
// findFastestFreeProxy скачивает списки бесплатных прокси, конкурентно пингует их и возвращает первый успешный
|
||||
func findFastestFreeProxy() (string, error) {
|
||||
sources := []string{
|
||||
"https://raw.githubusercontent.com/TheSpeedX/SOCKS-List/master/http.txt",
|
||||
"https://raw.githubusercontent.com/ShiftyTR/Proxy-List/master/http.txt",
|
||||
"https://api.proxyscrape.com/v2/?request=displayproxies&protocol=http&timeout=5000&country=all&ssl=all&anonymity=all",
|
||||
}
|
||||
|
||||
var proxies []string
|
||||
for _, src := range sources {
|
||||
resp, err := http.Get(src)
|
||||
if err == nil {
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
_ = resp.Body.Close()
|
||||
lines := strings.Split(string(body), "\n")
|
||||
for _, line := range lines {
|
||||
line = strings.TrimSpace(line)
|
||||
if line != "" {
|
||||
proxies = append(proxies, line)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(proxies) > 100 {
|
||||
break // Собрали достаточное количество для тестирования
|
||||
}
|
||||
}
|
||||
|
||||
if len(proxies) == 0 {
|
||||
return "", fmt.Errorf("could not fetch proxies from public sources")
|
||||
}
|
||||
|
||||
resultCh := make(chan string, 1)
|
||||
var wg sync.WaitGroup
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
limit := 100
|
||||
if len(proxies) < limit {
|
||||
limit = len(proxies)
|
||||
}
|
||||
|
||||
for i := 0; i < limit; i++ {
|
||||
p := proxies[i]
|
||||
if !strings.HasPrefix(p, "http") && !strings.HasPrefix(p, "socks") {
|
||||
p = "http://" + p
|
||||
}
|
||||
wg.Add(1)
|
||||
go func(proxyUrl string) {
|
||||
defer wg.Done()
|
||||
u, err := url.Parse(proxyUrl)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
// Делаем запрос к Telegram API с фейковым токеном.
|
||||
// Реальный сервер Telegram обязательно ответит JSON: {"ok":false,"error_code":401,"description":"Unauthorized"}
|
||||
req, _ := http.NewRequestWithContext(ctx, "GET", "https://api.telegram.org/bot123456:invalid_token/getMe", nil)
|
||||
client := &http.Client{
|
||||
Transport: &http.Transport{
|
||||
Proxy: http.ProxyURL(u),
|
||||
DialContext: (&net.Dialer{Timeout: 3 * time.Second}).DialContext,
|
||||
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
|
||||
},
|
||||
Timeout: 4 * time.Second,
|
||||
}
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err == nil {
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
_ = resp.Body.Close()
|
||||
|
||||
// Если в ответе есть маркер структуры Telegram API - прокси действительно пропускает трафик
|
||||
if bytes.Contains(body, []byte(`"ok":`)) {
|
||||
select {
|
||||
case resultCh <- proxyUrl:
|
||||
cancel() // Отменяем проверки остальных прокси, победитель найден
|
||||
default:
|
||||
}
|
||||
}
|
||||
}
|
||||
}(p)
|
||||
}
|
||||
|
||||
go func() {
|
||||
wg.Wait()
|
||||
close(resultCh)
|
||||
}()
|
||||
|
||||
select {
|
||||
case best, ok := <-resultCh:
|
||||
if !ok {
|
||||
return "", fmt.Errorf("all %d tested proxies failed to reach Telegram properly", limit)
|
||||
}
|
||||
return best, nil
|
||||
case <-time.After(8 * time.Second):
|
||||
return "", fmt.Errorf("timeout waiting for a valid proxy (tested %d proxies)", limit)
|
||||
}
|
||||
}
|
||||
|
||||
// Client — основной клиент библиотеки
|
||||
type Client struct {
|
||||
bot *tgbotapi.BotAPI
|
||||
|
|
@ -20,163 +405,124 @@ type Client struct {
|
|||
}
|
||||
|
||||
// ClientConfig — конфигурация клиента
|
||||
type ProxyConfig struct{} // Заглушка, если структура была в другом файле
|
||||
type ClientConfig struct {
|
||||
Token string
|
||||
Proxy *ProxyConfig
|
||||
Timeout time.Duration // по умолчанию 30s
|
||||
Timeout time.Duration
|
||||
Debug bool
|
||||
}
|
||||
|
||||
var (
|
||||
mu sync.Mutex
|
||||
instance *Client
|
||||
)
|
||||
|
||||
func GetClient(cfg ClientConfig) (*Client, error) {
|
||||
if instance != nil {
|
||||
return instance, nil
|
||||
}
|
||||
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
|
||||
if instance != nil {
|
||||
return instance, nil
|
||||
}
|
||||
|
||||
client, err := newClient(cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
instance = client
|
||||
return instance, nil
|
||||
}
|
||||
|
||||
// New создаёт нового клиента
|
||||
func newClient(cfg ClientConfig) (*Client, error) {
|
||||
if cfg.Token == "" {
|
||||
return nil, fmt.Errorf("tgkit: token is required")
|
||||
}
|
||||
if cfg.Timeout == 0 {
|
||||
cfg.Timeout = 30 * time.Second
|
||||
cfg.Timeout = defaultTimeout
|
||||
}
|
||||
|
||||
if cfg.Proxy != nil {
|
||||
logrus.Debugf("tgkit: proxy is configured: url: %s, username: %s, pass: %s", cfg.Proxy.URL, cfg.Proxy.Username, cfg.Proxy.Password)
|
||||
logrus.Debugf("tgkit: custom API proxy is enabled")
|
||||
}
|
||||
|
||||
httpClient, err := buildHTTPClient(cfg.Proxy, cfg.Timeout)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("tgkit: build http client: %w", err)
|
||||
}
|
||||
|
||||
bot, err := tgbotapi.NewBotAPIWithClient(cfg.Token, tgbotapi.APIEndpoint, httpClient)
|
||||
var bot *tgbotapi.BotAPI
|
||||
for attempt := 1; attempt <= maxStartupAttempts; attempt++ {
|
||||
bot, err = tgbotapi.NewBotAPIWithClient(cfg.Token, tgbotapi.APIEndpoint, httpClient)
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
logrus.Warnf("tgkit: init bot attempt %d/%d failed: %v", attempt, maxStartupAttempts, err)
|
||||
if attempt < maxStartupAttempts {
|
||||
time.Sleep(time.Duration(attempt) * startupRetryDelay)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("tgkit: init bot: %w", err)
|
||||
return nil, fmt.Errorf("tgkit: init bot after %d attempts: %w", maxStartupAttempts, err)
|
||||
}
|
||||
|
||||
bot.Debug = cfg.Debug
|
||||
|
||||
return &Client{
|
||||
bot: bot,
|
||||
timeout: cfg.Timeout,
|
||||
}, nil
|
||||
return &Client{bot: bot, timeout: cfg.Timeout}, nil
|
||||
}
|
||||
|
||||
// NewFromExisting оборачивает существующий *tgbotapi.BotAPI
|
||||
// Используется для постепенной миграции без переписывания всего кода
|
||||
func NewFromExisting(bot *tgbotapi.BotAPI) *Client {
|
||||
return &Client{bot: bot, timeout: 30 * time.Second}
|
||||
return &Client{bot: bot, timeout: defaultTimeout}
|
||||
}
|
||||
|
||||
// Bot возвращает сырой *tgbotapi.BotAPI для обратной совместимости
|
||||
func (c *Client) Bot() *tgbotapi.BotAPI {
|
||||
return c.bot
|
||||
}
|
||||
|
||||
// Self возвращает информацию о боте
|
||||
func (c *Client) Self() tgbotapi.User {
|
||||
return c.bot.Self
|
||||
}
|
||||
|
||||
// GetUpdates возвращает канал обновлений
|
||||
func (c *Client) GetUpdates(timeout int) tgbotapi.UpdatesChannel {
|
||||
u := tgbotapi.NewUpdate(0)
|
||||
u.Timeout = timeout
|
||||
return c.bot.GetUpdatesChan(u)
|
||||
}
|
||||
|
||||
// AnswerCallback отвечает на callback query
|
||||
func (c *Client) AnswerCallback(callbackID string, text string) error {
|
||||
cb := tgbotapi.NewCallback(callbackID, text)
|
||||
_, err := c.bot.Request(cb)
|
||||
return err
|
||||
}
|
||||
|
||||
// DeleteMessage удаляет сообщение
|
||||
func (c *Client) DeleteMessage(chatID int64, messageID int) error {
|
||||
_, err := c.bot.Request(tgbotapi.NewDeleteMessage(chatID, messageID))
|
||||
return err
|
||||
}
|
||||
|
||||
// GetFileDirectURL возвращает прямую ссылку на файл
|
||||
func (c *Client) GetFileDirectURL(fileID string) (string, error) {
|
||||
return c.bot.GetFileDirectURL(fileID)
|
||||
}
|
||||
|
||||
// Request выполняет произвольный запрос к API (для edge cases)
|
||||
func (c *Client) Request(cfg tgbotapi.Chattable) (*tgbotapi.APIResponse, error) {
|
||||
return c.bot.Request(cfg)
|
||||
}
|
||||
|
||||
// buildHTTPClient создаёт http.Client с поддержкой прокси
|
||||
func buildHTTPClient(proxyCfg *ProxyConfig, timeout time.Duration) (*http.Client, error) {
|
||||
transport := &http.Transport{
|
||||
TLSClientConfig: &tls.Config{InsecureSkipVerify: false},
|
||||
baseTransport := &http.Transport{
|
||||
DialContext: (&net.Dialer{
|
||||
Timeout: 10 * time.Second,
|
||||
KeepAlive: 30 * time.Second,
|
||||
}).DialContext,
|
||||
MaxIdleConns: 100,
|
||||
MaxIdleConnsPerHost: 100,
|
||||
TLSHandshakeTimeout: 10 * time.Second,
|
||||
ResponseHeaderTimeout: 60 * time.Second,
|
||||
TLSClientConfig: &tls.Config{InsecureSkipVerify: false},
|
||||
}
|
||||
|
||||
if proxyCfg != nil && proxyCfg.URL != "" {
|
||||
proxyURL, err := url.Parse(proxyCfg.URL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse proxy url: %w", err)
|
||||
}
|
||||
|
||||
scheme := proxyURL.Scheme
|
||||
|
||||
switch scheme {
|
||||
case "socks5", "socks5h":
|
||||
var auth *proxy.Auth
|
||||
|
||||
if proxyCfg.Username != "" {
|
||||
auth = &proxy.Auth{
|
||||
User: proxyCfg.Username,
|
||||
Password: proxyCfg.Password,
|
||||
}
|
||||
} else if proxyURL.User != nil {
|
||||
pass, _ := proxyURL.User.Password()
|
||||
auth = &proxy.Auth{
|
||||
User: proxyURL.User.Username(),
|
||||
Password: pass,
|
||||
}
|
||||
}
|
||||
|
||||
dialer, err := proxy.SOCKS5("tcp", proxyURL.Host, auth, proxy.Direct)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create socks5 dialer: %w", err)
|
||||
}
|
||||
|
||||
transport.Dial = dialer.Dial //nolint:staticcheck
|
||||
|
||||
case "http", "https":
|
||||
transport.Proxy = http.ProxyURL(proxyURL)
|
||||
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported proxy scheme: %s", scheme)
|
||||
}
|
||||
var finalTransport http.RoundTripper = baseTransport
|
||||
if proxyCfg != nil {
|
||||
finalTransport = &CustomAPIProxyTransport{wrapped: baseTransport}
|
||||
}
|
||||
|
||||
return &http.Client{
|
||||
Transport: transport,
|
||||
Transport: finalTransport,
|
||||
Timeout: timeout,
|
||||
}, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,6 +11,22 @@ import (
|
|||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func detectImageExtension(data []byte) string {
|
||||
contentType := http.DetectContentType(data)
|
||||
switch contentType {
|
||||
case "image/png":
|
||||
return "photo.png"
|
||||
case "image/jpeg":
|
||||
return "photo.jpg"
|
||||
case "image/webp":
|
||||
return "photo.webp"
|
||||
case "image/gif":
|
||||
return "photo.gif"
|
||||
default:
|
||||
return "photo.jpg"
|
||||
}
|
||||
}
|
||||
|
||||
// SendPhoto отправляет фото по URL, пути к файлу или base64
|
||||
func (c *Client) SendPhoto(chatID int64, source string, caption string, opts ...MessageOptions) (*SentMessage, error) {
|
||||
var photo tgbotapi.RequestFileData
|
||||
|
|
@ -23,7 +39,8 @@ func (c *Client) SendPhoto(chatID int64, source string, caption string, opts ...
|
|||
if err != nil {
|
||||
return nil, fmt.Errorf("tgkit: decode base64: %w", err)
|
||||
}
|
||||
photo = tgbotapi.FileBytes{Name: "photo.jpg", Bytes: data}
|
||||
fileName := detectImageExtension(data)
|
||||
photo = tgbotapi.FileBytes{Name: fileName, Bytes: data}
|
||||
default:
|
||||
photo = tgbotapi.FilePath(source)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -43,13 +43,6 @@ type MessageOptions struct {
|
|||
Silent bool
|
||||
}
|
||||
|
||||
// ProxyConfig — настройки прокси
|
||||
type ProxyConfig struct {
|
||||
URL string // socks5://user:pass@host:port или http://host:port
|
||||
Username string
|
||||
Password string
|
||||
}
|
||||
|
||||
// SentMessage — результат отправки
|
||||
type SentMessage struct {
|
||||
MessageID int
|
||||
|
|
|
|||
|
|
@ -3,15 +3,17 @@ package clientcontrollers
|
|||
import (
|
||||
configcore "bitrix_balancer_api/core/config"
|
||||
database "bitrix_balancer_api/core/db"
|
||||
"bitrix_balancer_api/core/lib/external/tgkit"
|
||||
redismodule "bitrix_balancer_api/core/lib/internally/redis"
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type ClientsExternal struct {
|
||||
Config *configcore.Config
|
||||
Redis *redismodule.ModuleRedis
|
||||
DB *database.ModuleDB
|
||||
Config *configcore.Config
|
||||
Redis *redismodule.ModuleRedis
|
||||
DB *database.ModuleDB
|
||||
Telegram *tgkit.Client
|
||||
}
|
||||
|
||||
func ReturnClientsExternal(cfgOptions *configcore.ConfigLoadOptions) (ClientsExternal, error) {
|
||||
|
|
@ -43,5 +45,16 @@ func ReturnClientsExternal(cfgOptions *configcore.ConfigLoadOptions) (ClientsExt
|
|||
clientsExternal.DB = dbClient
|
||||
}
|
||||
|
||||
if cfgOptions.Telegram {
|
||||
tgKitClient, err := tgkit.GetClient(tgkit.ClientConfig{
|
||||
Token: cfg.Telegram.BotToken,
|
||||
Proxy: &tgkit.ProxyConfig{},
|
||||
})
|
||||
if err != nil {
|
||||
return clientsExternal, errors.New(fmt.Sprintf("failed to get tg client: %v", err))
|
||||
}
|
||||
clientsExternal.Telegram = tgKitClient
|
||||
}
|
||||
|
||||
return clientsExternal, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,492 @@
|
|||
package monthly_orders
|
||||
|
||||
import (
|
||||
dbcore "bitrix_balancer_api/core/db/methods"
|
||||
"bitrix_balancer_api/core/lib/external/googlesheets"
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
"bitrix_balancer_api/telegram_service/types"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/sirupsen/logrus"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const MasterReportSpreadsheetID = "1wMyQIA-ShXE0TzHcjadMxkN1eu_637SflFHrUJjRuQw"
|
||||
|
||||
type ApprovalFlowStarter interface {
|
||||
StartFlowForOrder(ctx context.Context, approval *typescore.Approval) error
|
||||
}
|
||||
|
||||
type MonthlyOrderService struct {
|
||||
ipc *types.InternalProviderControl
|
||||
gsClient *googlesheets.Client
|
||||
clientsSheet string
|
||||
nomSheet string
|
||||
flowStarter ApprovalFlowStarter // 2. НОВОЕ: Добавляем зависимость
|
||||
}
|
||||
|
||||
func NewMonthlyOrderService(
|
||||
ipc *types.InternalProviderControl,
|
||||
gsClient *googlesheets.Client,
|
||||
clientsSheetID, nomSheetID string,
|
||||
flowStarter ApprovalFlowStarter,
|
||||
) *MonthlyOrderService {
|
||||
return &MonthlyOrderService{
|
||||
ipc: ipc,
|
||||
gsClient: gsClient,
|
||||
clientsSheet: clientsSheetID,
|
||||
nomSheet: nomSheetID,
|
||||
flowStarter: flowStarter,
|
||||
}
|
||||
}
|
||||
|
||||
type FrontendOrderMatrix struct {
|
||||
Settings *typescore.MonthlyOrderSetting `json:"settings"`
|
||||
Nomenclatures []googlesheets.NomenclatureItem `json:"nomenclatures"`
|
||||
Clients []FrontendClientData `json:"clients"`
|
||||
IsLocked bool `json:"is_locked"`
|
||||
}
|
||||
|
||||
type FrontendClientData struct {
|
||||
GoogleData googlesheets.ClientItem `json:"google_data"`
|
||||
DBOrder *typescore.MonthlyOrderClient `json:"db_order"` // Черновик или отправленный заказ (если есть)
|
||||
}
|
||||
|
||||
// GetMyOrderData собирает "матрицу" для менеджера: тянет Google Sheets + БД
|
||||
func (s *MonthlyOrderService) GetMyOrderData(ctx context.Context, managerID uint64) (*FrontendOrderMatrix, error) {
|
||||
logrus.Info("🛑 GET MY ORDER ")
|
||||
|
||||
manager, err := s.ipc.Database.User.GetUserByIDDB(ctx, managerID)
|
||||
if err != nil || manager == nil || manager.FullName == nil {
|
||||
return nil, errors.New("менеджер не найден")
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
month, year := int(now.Month()), now.Year()
|
||||
|
||||
// 1. Получаем настройки месяца
|
||||
settings, err := s.ipc.Database.MonthlyOrders.GetCurrentSettings(ctx, month, year)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
isLocked := true
|
||||
if settings != nil && settings.DeadlineDate != nil {
|
||||
// Открыто с 15-го числа И до дедлайна включительно
|
||||
if now.Day() >= 15 && now.Before(*settings.DeadlineDate) {
|
||||
isLocked = false
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Идем в Google Sheets за свежими данными
|
||||
noms, err := s.gsClient.FetchNomenclature(s.nomSheet)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ошибка парсинга номенклатуры: %v", err)
|
||||
}
|
||||
|
||||
gsClients, err := s.gsClient.FetchActiveClientsForManager(s.clientsSheet, *manager.FullName)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ошибка парсинга клиентов: %v", err)
|
||||
}
|
||||
|
||||
ordersMap := make(map[string]*typescore.MonthlyOrderClient)
|
||||
|
||||
// Определяем, какой статус и тип заказа нам нужен в зависимости от блокировки (дедлайна)
|
||||
statusDraft := "draft"
|
||||
suppType := "supplementary"
|
||||
mainType := "main"
|
||||
|
||||
filterOpts := dbcore.OrderFilterOptions{
|
||||
ManagerID: &managerID,
|
||||
Month: &month,
|
||||
Year: &year,
|
||||
Status: &statusDraft, // Берем только черновики!
|
||||
}
|
||||
|
||||
if isLocked {
|
||||
filterOpts.OrderType = &suppType
|
||||
} else {
|
||||
filterOpts.OrderType = &mainType
|
||||
}
|
||||
|
||||
logrus.Infof("🛑 Период: %s", *filterOpts.OrderType)
|
||||
|
||||
dbOrders, err := s.ipc.Database.MonthlyOrders.GetFilteredClientOrdersDB(ctx, filterOpts)
|
||||
if err != nil {
|
||||
logrus.Errorf("🚨 ОШИБКА ЧТЕНИЯ ЗАКАЗОВ ИЗ БД: %v", err)
|
||||
}
|
||||
|
||||
for _, o := range dbOrders {
|
||||
if o.ID != nil {
|
||||
// Достаем позиции
|
||||
items, err := s.ipc.Database.MonthlyOrders.GetItemsByOrderIDDB(ctx, *o.ID)
|
||||
if err == nil && len(items) > 0 {
|
||||
for _, item := range items {
|
||||
o.Items = append(o.Items, *item)
|
||||
}
|
||||
}
|
||||
|
||||
// Достаем файлы
|
||||
files, err := s.ipc.Database.MonthlyOrders.GetFilesByOrderIDDB(ctx, *o.ID)
|
||||
if err == nil && len(files) > 0 {
|
||||
for _, file := range files {
|
||||
o.Files = append(o.Files, *file)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if o.ClientName != nil {
|
||||
cleanName := strings.TrimSpace(*o.ClientName)
|
||||
ordersMap[cleanName] = o
|
||||
}
|
||||
}
|
||||
|
||||
var clientDataList []FrontendClientData
|
||||
for _, gsc := range gsClients {
|
||||
cleanName := strings.TrimSpace(gsc.Name)
|
||||
|
||||
clientDataList = append(clientDataList, FrontendClientData{
|
||||
GoogleData: gsc,
|
||||
DBOrder: ordersMap[cleanName],
|
||||
})
|
||||
}
|
||||
|
||||
return &FrontendOrderMatrix{
|
||||
Settings: settings,
|
||||
Nomenclatures: noms,
|
||||
Clients: clientDataList,
|
||||
IsLocked: isLocked,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ExportGoogleReport собирает все заказы за текущий месяц и пушит в гугл
|
||||
func (s *MonthlyOrderService) ExportGoogleReport(ctx context.Context) (string, error) {
|
||||
if s.gsClient == nil {
|
||||
return "", errors.New("google sheets client не инициализирован (проверьте google-creds.json)")
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
month, year := int(now.Month()), now.Year()
|
||||
|
||||
allOrders, err := s.ipc.Database.MonthlyOrders.GetAllOrdersForMonthDB(ctx, month, year)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("ошибка получения заказов из БД: %v", err)
|
||||
}
|
||||
|
||||
// 1. Сортируем заказы по ID, чтобы сохранить хронологию (сначала старые/основные)
|
||||
sort.Slice(allOrders, func(i, j int) bool {
|
||||
if allOrders[i].ID != nil && allOrders[j].ID != nil {
|
||||
return *allOrders[i].ID < *allOrders[j].ID
|
||||
}
|
||||
return false
|
||||
})
|
||||
|
||||
var mainOrders []*typescore.MonthlyOrderClient
|
||||
var suppOrders []*typescore.MonthlyOrderClient
|
||||
|
||||
// 2. Строго разделяем на основные и доп. заказы по полю OrderType
|
||||
for _, o := range allOrders {
|
||||
if o.ClientName == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
if o.OrderType != nil && *o.OrderType == "supplementary" {
|
||||
suppOrders = append(suppOrders, o)
|
||||
} else {
|
||||
// Всё, что не помечено как supplementary, уходит в основные
|
||||
mainOrders = append(mainOrders, o)
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Формируем заголовки
|
||||
sheet1Data := [][]interface{}{{"Клиент", "Номенклатура", "Количество", "Итог (Формула)", "Тип заказа"}}
|
||||
sheet2Data := [][]interface{}{{"Клиент", "Тип заказа", "Комментарий менеджера", "Декада", "Доставка", "Оплата", "Условия"}}
|
||||
|
||||
currentRow := 2
|
||||
|
||||
processOrderList := func(orders []*typescore.MonthlyOrderClient, orderTypeLabel string) {
|
||||
for _, o := range orders {
|
||||
clientName := strings.TrimSpace(*o.ClientName)
|
||||
|
||||
// --- СБОРКА ЛИСТА КОММЕНТАРИЕВ ---
|
||||
comment, decade, delivery, payment, conditions := "", "", "", "", ""
|
||||
if o.ManagerComment != nil {
|
||||
comment = *o.ManagerComment
|
||||
}
|
||||
if o.Decade != nil {
|
||||
decade = *o.Decade
|
||||
}
|
||||
if o.Delivery != nil {
|
||||
delivery = *o.Delivery
|
||||
}
|
||||
if o.PaymentForm != nil {
|
||||
payment = *o.PaymentForm
|
||||
}
|
||||
if o.Conditions != nil {
|
||||
conditions = *o.Conditions
|
||||
}
|
||||
|
||||
if comment != "" || decade != "" || delivery != "" || payment != "" || conditions != "" {
|
||||
sheet2Data = append(sheet2Data, []interface{}{
|
||||
clientName,
|
||||
orderTypeLabel, // Для основных здесь пустая строка или "Основной", для доп — "Доп заказ"
|
||||
comment,
|
||||
decade,
|
||||
delivery,
|
||||
payment,
|
||||
conditions,
|
||||
})
|
||||
}
|
||||
|
||||
if o.ID != nil {
|
||||
items, _ := s.ipc.Database.MonthlyOrders.GetItemsByOrderIDDB(ctx, *o.ID)
|
||||
for _, item := range items {
|
||||
if item == nil || item.Quantity == nil || *item.Quantity <= 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
nomName := ""
|
||||
if item.NomenclatureName != nil {
|
||||
nomName = *item.NomenclatureName
|
||||
}
|
||||
|
||||
formula := fmt.Sprintf(`=VALUE(REGEXEXTRACT(B%d; "\((\d+)\)[^()]*$"))*C%d`, currentRow, currentRow)
|
||||
|
||||
sheet1Data = append(sheet1Data, []interface{}{
|
||||
clientName,
|
||||
nomName,
|
||||
*item.Quantity,
|
||||
formula,
|
||||
orderTypeLabel,
|
||||
})
|
||||
|
||||
currentRow++
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Запускаем формирование: сначала основные (с пустым метки типа или "Основной"), затем доп. заказы
|
||||
processOrderList(mainOrders, "")
|
||||
processOrderList(suppOrders, "Доп заказ")
|
||||
|
||||
return s.gsClient.ExportMonthlyReportToMasterSheet(ctx, MasterReportSpreadsheetID, sheet1Data, sheet2Data)
|
||||
}
|
||||
|
||||
// SubmitOrdersToTelegram превращает отправленные заказы в Telegram-заявки
|
||||
func (s *MonthlyOrderService) SubmitOrdersToTelegram(ctx context.Context, managerID uint64) error {
|
||||
now := time.Now()
|
||||
month, year := int(now.Month()), now.Year()
|
||||
|
||||
statusDraft := "draft"
|
||||
filterOpts := dbcore.OrderFilterOptions{
|
||||
ManagerID: &managerID,
|
||||
Month: &month,
|
||||
Year: &year,
|
||||
Status: &statusDraft,
|
||||
}
|
||||
dbOrders, err := s.ipc.Database.MonthlyOrders.GetFilteredClientOrdersDB(ctx, filterOpts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
manager, err := s.ipc.Database.User.GetUserByIDDB(ctx, managerID)
|
||||
if err != nil || manager == nil || manager.FullName == nil {
|
||||
return errors.New("менеджер не найден")
|
||||
}
|
||||
|
||||
gsClients, err := s.gsClient.FetchActiveClientsForManager(s.clientsSheet, *manager.FullName)
|
||||
if err != nil {
|
||||
return fmt.Errorf("ошибка получения клиентов из Google Sheets: %v", err)
|
||||
}
|
||||
|
||||
branchMap := make(map[string]string)
|
||||
for _, c := range gsClients {
|
||||
branchMap[strings.TrimSpace(c.Name)] = strings.TrimSpace(c.Branch)
|
||||
}
|
||||
|
||||
submittedCount := 0
|
||||
skippedEmpty := 0
|
||||
skippedAlreadyDone := 0
|
||||
|
||||
for _, order := range dbOrders {
|
||||
if order.ClientName == nil {
|
||||
continue
|
||||
}
|
||||
clientNameClean := strings.TrimSpace(*order.ClientName)
|
||||
|
||||
// 1. Получаем номенклатуру (позиции) заказа
|
||||
items, err := s.ipc.Database.MonthlyOrders.GetItemsByOrderIDDB(ctx, *order.ID)
|
||||
if err != nil || len(items) == 0 {
|
||||
logrus.Warnf("⚠️ [SubmitOrders] У клиента '%s' (OrderID: %v) не найдено позиций в БД.", clientNameClean, order.ID)
|
||||
skippedEmpty++
|
||||
continue
|
||||
}
|
||||
|
||||
hasActualQuantity := false
|
||||
for _, item := range items {
|
||||
if item.Quantity != nil && *item.Quantity > 0 {
|
||||
hasActualQuantity = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if !hasActualQuantity {
|
||||
logrus.Warnf("⚠️ [SubmitOrders] У клиента '%s' позиции имеют нулевое количество.", clientNameClean)
|
||||
skippedEmpty++
|
||||
continue
|
||||
}
|
||||
|
||||
if order.ApprovalID != nil && *order.ApprovalID > 0 {
|
||||
skippedAlreadyDone++
|
||||
continue
|
||||
}
|
||||
|
||||
// 2. Получаем прикрепленные файлы (скрины) из БД
|
||||
files, err := s.ipc.Database.MonthlyOrders.GetFilesByOrderIDDB(ctx, *order.ID)
|
||||
if err != nil {
|
||||
logrus.Warnf("⚠️ [SubmitOrders] Ошибка получения файлов для клиента '%s': %v", clientNameClean, err)
|
||||
}
|
||||
|
||||
branch := ""
|
||||
for gsName, gsBranch := range branchMap {
|
||||
if strings.EqualFold(gsName, clientNameClean) {
|
||||
branch = gsBranch
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
isSupplementary := order.OrderType != nil && *order.OrderType == "supplementary"
|
||||
|
||||
var topicID uint64
|
||||
branchLower := strings.ToLower(branch)
|
||||
|
||||
if strings.Contains(branchLower, "краснодар") {
|
||||
if isSupplementary {
|
||||
topicID = 583
|
||||
} else {
|
||||
topicID = 581
|
||||
}
|
||||
} else if strings.Contains(branchLower, "крым") {
|
||||
if isSupplementary {
|
||||
topicID = 582
|
||||
} else {
|
||||
topicID = 580
|
||||
}
|
||||
} else {
|
||||
continue
|
||||
}
|
||||
|
||||
var contentBuilder strings.Builder
|
||||
contentBuilder.WriteString(fmt.Sprintf("Клиент: %s\n", *order.ClientName))
|
||||
|
||||
if order.Decade != nil {
|
||||
contentBuilder.WriteString(fmt.Sprintf("Декада: %s\n", *order.Decade))
|
||||
}
|
||||
if order.Delivery != nil {
|
||||
contentBuilder.WriteString(fmt.Sprintf("Доставка: %s\n", *order.Delivery))
|
||||
}
|
||||
if order.Conditions != nil {
|
||||
contentBuilder.WriteString(fmt.Sprintf("Условия: %s\n", *order.Conditions))
|
||||
}
|
||||
if order.PaymentForm != nil {
|
||||
contentBuilder.WriteString(fmt.Sprintf("Оплата: %s\n", *order.PaymentForm))
|
||||
}
|
||||
|
||||
contentBuilder.WriteString("\n📦 <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
|
||||
}
|
||||
|
|
@ -0,0 +1,63 @@
|
|||
package monthly_orders
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// StartDeadlineWorker запускает фоновый процесс проверки дедлайна заказов
|
||||
func (s *MonthlyOrderService) StartDeadlineWorker(ctx context.Context) {
|
||||
logrus.Infof("Фоновая задача по дедлайну заказов на месяц запущена")
|
||||
// Проверяем статус каждые 3 часа (или можно настроить под твои нужды)
|
||||
ticker := time.NewTicker(3 * time.Hour)
|
||||
go func() {
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
logrus.Info("🛑 Deadline worker остановлен")
|
||||
return
|
||||
case <-ticker.C:
|
||||
s.checkAndExportByDeadline(ctx)
|
||||
}
|
||||
}
|
||||
}()
|
||||
logrus.Info("🚀 Deadline worker успешно запущен")
|
||||
}
|
||||
|
||||
func (s *MonthlyOrderService) checkAndExportByDeadline(ctx context.Context) {
|
||||
now := time.Now()
|
||||
month, year := int(now.Month()), now.Year()
|
||||
|
||||
// 1. Получаем настройки текущего месяца (где хранится DeadlineDate)
|
||||
settings, err := s.ipc.Database.MonthlyOrders.GetCurrentSettings(ctx, month, year)
|
||||
if err != nil || settings == nil || settings.DeadlineDate == nil {
|
||||
return // Настройки еще не заданы аналитиком
|
||||
}
|
||||
|
||||
deadline := *settings.DeadlineDate
|
||||
if now.After(deadline) || sameDay(now, deadline) {
|
||||
alreadyExported, err := s.gsClient.IsMonthReportExist(ctx, MasterReportSpreadsheetID, deadline)
|
||||
if err == nil && alreadyExported {
|
||||
return // Отчет за этот период уже сформирован
|
||||
}
|
||||
|
||||
logrus.Infof("⏰ Наступил дедлайн заказов (%s). Автоматически выгружаем отчет...", deadline.Format("02.01.2006"))
|
||||
|
||||
_, err = s.ExportGoogleReport(ctx)
|
||||
if err != nil {
|
||||
logrus.Errorf("❌ Ошибка автовыгрузки отчета по дедлайну: %v", err)
|
||||
} else {
|
||||
logrus.Infof("✅ Отчет за %s успешно автовыгружен в мастер-таблицу", deadline.Format("January 2006"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Вспомогательная функция для сравнения дат (день, месяц, год)
|
||||
func sameDay(t1, t2 time.Time) bool {
|
||||
y1, m1, d1 := t1.Date()
|
||||
y2, m2, d2 := t2.Date()
|
||||
return y1 == y2 && m1 == m2 && d1 == d2
|
||||
}
|
||||
|
|
@ -0,0 +1,90 @@
|
|||
package reportcore
|
||||
|
||||
import (
|
||||
"github.com/xuri/excelize/v2"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// autoFitColumns автоматически подгоняет ширину колонок под содержимое.
|
||||
// Учитывает длину заголовка и всех ячеек, добавляет небольшой отступ.
|
||||
func autoFitColumns(f *excelize.File, sheetName string, headers []string, dataRowCount int) {
|
||||
for colIdx, header := range headers {
|
||||
colLetter, _ := excelize.ColumnNumberToName(colIdx + 1)
|
||||
|
||||
// Начинаем с длины заголовка
|
||||
maxWidth := stringWidth(header)
|
||||
|
||||
// Проверяем все строки данных в этой колонке
|
||||
for row := 2; row <= dataRowCount+1; row++ {
|
||||
cellName, _ := excelize.CoordinatesToCellName(colIdx+1, row)
|
||||
cellValue, _ := f.GetCellValue(sheetName, cellName)
|
||||
w := stringWidth(cellValue)
|
||||
if w > maxWidth {
|
||||
maxWidth = w
|
||||
}
|
||||
}
|
||||
|
||||
// Добавляем небольшой отступ для красоты
|
||||
finalWidth := float64(maxWidth) + 2
|
||||
|
||||
// Ограничиваем минимальную и максимальную ширину
|
||||
if finalWidth < 10 {
|
||||
finalWidth = 10
|
||||
}
|
||||
if finalWidth > 60 {
|
||||
finalWidth = 60
|
||||
}
|
||||
|
||||
_ = f.SetColWidth(sheetName, colLetter, colLetter, finalWidth)
|
||||
}
|
||||
}
|
||||
|
||||
// stringWidth вычисляет "визуальную" ширину строки.
|
||||
// Кириллица и другие широкие символы занимают больше места, чем латиница.
|
||||
func stringWidth(s string) int {
|
||||
width := 0
|
||||
for _, r := range s {
|
||||
if isWideRune(r) {
|
||||
width += 2 // широкие символы (кириллица, CJK)
|
||||
} else {
|
||||
width += 1
|
||||
}
|
||||
}
|
||||
// Учитываем переносы строк — берём самую длинную строку
|
||||
lines := strings.Split(s, "\n")
|
||||
maxLine := 0
|
||||
for _, line := range lines {
|
||||
lw := 0
|
||||
for _, r := range line {
|
||||
if isWideRune(r) {
|
||||
lw += 2
|
||||
} else {
|
||||
lw += 1
|
||||
}
|
||||
}
|
||||
if lw > maxLine {
|
||||
maxLine = lw
|
||||
}
|
||||
}
|
||||
if maxLine > width {
|
||||
width = maxLine
|
||||
}
|
||||
return width
|
||||
}
|
||||
|
||||
// isWideRune определяет, является ли символ "широким"
|
||||
func isWideRune(r rune) bool {
|
||||
// Кириллица
|
||||
if r >= 0x0400 && r <= 0x04FF {
|
||||
return true
|
||||
}
|
||||
// CJK (китайские, японские, корейские)
|
||||
if r >= 0x4E00 && r <= 0x9FFF {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// _ используется, чтобы убрать предупреждение о неиспользуемом импорте
|
||||
var _ = utf8.RuneCountInString
|
||||
|
|
@ -0,0 +1,502 @@
|
|||
package reportcore
|
||||
|
||||
import (
|
||||
database "bitrix_balancer_api/core/db"
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
"github.com/xuri/excelize/v2"
|
||||
)
|
||||
|
||||
// BuildExcelApprovalsReport — строит xlsx-файл отчёта по согласованиям и возвращает байты.
|
||||
func BuildExcelApprovalsReport(ctx context.Context, db *database.ModuleDB, approvals []*typescore.Approval) ([]byte, error) {
|
||||
f := excelize.NewFile()
|
||||
sheet := "Согласования"
|
||||
if err := f.SetSheetName("Sheet1", sheet); err != nil {
|
||||
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
|
||||
}
|
||||
|
||||
cols := []string{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q"}
|
||||
|
||||
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,
|
||||
}
|
||||
|
||||
headerStyle, err := f.NewStyle(&excelize.Style{
|
||||
Font: &excelize.Font{Bold: true, Color: "FFFFFF"},
|
||||
Fill: excelize.Fill{Type: "pattern", Color: []string{"2E75B6"}, Pattern: 1},
|
||||
Border: []excelize.Border{
|
||||
{Type: "left", Color: "000000", Style: 1},
|
||||
{Type: "right", Color: "000000", Style: 1},
|
||||
{Type: "top", Color: "000000", Style: 1},
|
||||
{Type: "bottom", Color: "000000", Style: 1},
|
||||
},
|
||||
Alignment: &excelize.Alignment{Horizontal: "center", Vertical: "center", WrapText: true},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create header style: %w", err)
|
||||
}
|
||||
|
||||
dataStyle, err := f.NewStyle(&excelize.Style{
|
||||
Border: []excelize.Border{
|
||||
{Type: "left", Color: "CCCCCC", Style: 1},
|
||||
{Type: "right", Color: "CCCCCC", Style: 1},
|
||||
{Type: "top", Color: "CCCCCC", Style: 1},
|
||||
{Type: "bottom", Color: "CCCCCC", Style: 1},
|
||||
},
|
||||
Alignment: &excelize.Alignment{Vertical: "center", WrapText: true},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create data style: %w", err)
|
||||
}
|
||||
|
||||
rejectedStyle, err := f.NewStyle(&excelize.Style{
|
||||
Fill: excelize.Fill{Type: "pattern", Color: []string{"FFE0E0"}, Pattern: 1},
|
||||
Border: []excelize.Border{
|
||||
{Type: "left", Color: "CCCCCC", Style: 1},
|
||||
{Type: "right", Color: "CCCCCC", Style: 1},
|
||||
{Type: "top", Color: "CCCCCC", Style: 1},
|
||||
{Type: "bottom", Color: "CCCCCC", Style: 1},
|
||||
},
|
||||
Alignment: &excelize.Alignment{Vertical: "center", WrapText: true},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create rejected style: %w", err)
|
||||
}
|
||||
|
||||
errorStyle, err := f.NewStyle(&excelize.Style{
|
||||
Fill: excelize.Fill{Type: "pattern", Color: []string{"FFCCCC"}, Pattern: 1},
|
||||
Border: []excelize.Border{
|
||||
{Type: "left", Color: "CCCCCC", Style: 1},
|
||||
{Type: "right", Color: "CCCCCC", Style: 1},
|
||||
{Type: "top", Color: "CCCCCC", Style: 1},
|
||||
{Type: "bottom", Color: "CCCCCC", Style: 1},
|
||||
},
|
||||
Alignment: &excelize.Alignment{Vertical: "center", WrapText: true},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create error style: %w", err)
|
||||
}
|
||||
|
||||
for col, width := range colWidths {
|
||||
if err := f.SetColWidth(sheet, col, col, width); err != nil {
|
||||
return nil, fmt.Errorf("set col width %s: %w", col, err)
|
||||
}
|
||||
}
|
||||
|
||||
for i, header := range headers {
|
||||
cell := fmt.Sprintf("%s1", cols[i])
|
||||
if err := f.SetCellValue(sheet, cell, header); err != nil {
|
||||
return nil, fmt.Errorf("set cell value %s: %w", cell, err)
|
||||
}
|
||||
if err := f.SetCellStyle(sheet, cell, cell, headerStyle); err != nil {
|
||||
return nil, fmt.Errorf("set cell style %s: %w", cell, err)
|
||||
}
|
||||
}
|
||||
if err := f.SetRowHeight(sheet, 1, 36); err != nil {
|
||||
return nil, fmt.Errorf("set row height: %w", err)
|
||||
}
|
||||
|
||||
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 {
|
||||
initiatorName = *a.Initiator.FullName
|
||||
} else if a.InitiatorID != nil {
|
||||
if u, err := db.User.GetUserByIDDB(ctx, *a.InitiatorID); err == nil && u != nil && u.FullName != nil {
|
||||
initiatorName = *u.FullName
|
||||
}
|
||||
}
|
||||
|
||||
// === Тема согласования ===
|
||||
topicName := ""
|
||||
if a.Topic != nil {
|
||||
if a.Topic.Category != nil && a.Topic.Category.Name != nil {
|
||||
topicName = *a.Topic.Category.Name + ": "
|
||||
} else if a.Topic.CategoryID != nil {
|
||||
if c, err := db.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *a.Topic.CategoryID); err == nil && c != nil && c.Name != nil {
|
||||
topicName = *c.Name + ": "
|
||||
}
|
||||
}
|
||||
if a.Topic.Name != nil {
|
||||
topicName += *a.Topic.Name
|
||||
}
|
||||
} else if a.TopicID != nil {
|
||||
if t, err := db.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *a.TopicID); err == nil && t != nil {
|
||||
if t.CategoryID != nil {
|
||||
if c, err := db.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *t.CategoryID); err == nil && c != nil && c.Name != nil {
|
||||
topicName = *c.Name + ": "
|
||||
}
|
||||
}
|
||||
if t.Name != nil {
|
||||
topicName += *t.Name
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// === Дата создания ===
|
||||
createdAt := ""
|
||||
if a.CreatedAt != nil {
|
||||
createdAt = a.CreatedAt.Format("02.01.2006 15:04")
|
||||
}
|
||||
|
||||
// === Согласующие и комментарии ===
|
||||
var approverParts []string
|
||||
var commentFromStep string
|
||||
lastApprovedAt := ""
|
||||
|
||||
steps, _, _ := db.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.ApprovalStep{ApprovalID: a.ID},
|
||||
})
|
||||
sort.Slice(steps, func(i, j int) bool {
|
||||
if steps[i].StepOrder == nil || steps[j].StepOrder == nil {
|
||||
return false
|
||||
}
|
||||
return *steps[i].StepOrder < *steps[j].StepOrder
|
||||
})
|
||||
for _, s := range steps {
|
||||
name := ""
|
||||
if s.ApproverNameSnapshot != nil && *s.ApproverNameSnapshot != "" {
|
||||
name = *s.ApproverNameSnapshot
|
||||
} else if s.ApproverID != nil {
|
||||
if u, err := db.User.GetUserByIDDB(ctx, *s.ApproverID); err == nil && u != nil && u.FullName != nil {
|
||||
name = *u.FullName
|
||||
}
|
||||
}
|
||||
if name != "" {
|
||||
approverParts = append(approverParts, name)
|
||||
}
|
||||
if s.Status != nil && *s.Status == "rejected" && s.Comment != nil && *s.Comment != "" {
|
||||
commentFromStep = *s.Comment
|
||||
}
|
||||
if s.Status != nil && *s.Status == "approved" && s.ActedAt != nil {
|
||||
lastApprovedAt = s.ActedAt.Format("02.01.2006 15:04")
|
||||
}
|
||||
}
|
||||
approversCell := strings.Join(approverParts, "\n")
|
||||
|
||||
// === Наблюдатели (Базовые) ===
|
||||
var observerParts []string
|
||||
categoryCode := GetTopicCategoryCodeByApproval(ctx, db, a)
|
||||
if categoryCode != "" {
|
||||
observers, _ := db.User.GetObserversForApprovalDB(ctx, categoryCode, a.TopicID)
|
||||
for _, obs := range observers {
|
||||
if obs.FullName != nil {
|
||||
observerParts = append(observerParts, *obs.FullName)
|
||||
}
|
||||
}
|
||||
}
|
||||
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 {
|
||||
switch *a.Status {
|
||||
case "pending":
|
||||
status = "На согласовании"
|
||||
case "approved":
|
||||
status = "Согласовано"
|
||||
case "rejected":
|
||||
status = "Отклонено"
|
||||
case "revoked":
|
||||
status = "Отозвано"
|
||||
case "revision":
|
||||
status = "На доработке"
|
||||
case "draft":
|
||||
status = "Черновик"
|
||||
}
|
||||
}
|
||||
|
||||
// === Текст заявки ===
|
||||
content := ""
|
||||
if a.Content != nil {
|
||||
content = *a.Content
|
||||
}
|
||||
|
||||
// === Отдел ===
|
||||
deptName := ""
|
||||
if a.Department != nil && a.Department.Name != nil {
|
||||
deptName = *a.Department.Name
|
||||
} else if a.DepartmentID != nil {
|
||||
if d, err := db.Department.GetDepartmentByIDDB(ctx, *a.DepartmentID); err == nil && d != nil && d.Name != nil {
|
||||
deptName = *d.Name
|
||||
}
|
||||
}
|
||||
|
||||
// === Комментарий ===
|
||||
comment := ""
|
||||
if a.Status != nil && *a.Status == "rejected" {
|
||||
comment = commentFromStep
|
||||
}
|
||||
|
||||
// === Задачи и исполнители ===
|
||||
taskText := "Не предусмотрено"
|
||||
executorName := "Не предусмотрено"
|
||||
taskStatus := "Не предусмотрено"
|
||||
taskCompletedAt := ""
|
||||
hasTaskError := false
|
||||
|
||||
if a.TopicID != nil {
|
||||
topicExecutors, _ := db.ApprovalTopicExecutor.GetExecutorsByTopicIDDB(ctx, *a.TopicID)
|
||||
|
||||
if len(topicExecutors) == 0 {
|
||||
taskText = "Не предусмотрено"
|
||||
executorName = "Не предусмотрено"
|
||||
taskStatus = "Не предусмотрено"
|
||||
} else {
|
||||
tasks, _, _ := db.ApprovalTasks.GetApprovalTasksListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.ApprovalTask{ApprovalID: a.ID},
|
||||
})
|
||||
|
||||
if len(tasks) == 0 {
|
||||
if a.Status == nil {
|
||||
taskText = "Не предусмотрено"
|
||||
executorName = "Не предусмотрено"
|
||||
taskStatus = "Не предусмотрено"
|
||||
} else {
|
||||
switch *a.Status {
|
||||
case "approved":
|
||||
taskText = "Ошибка: задачи не созданы"
|
||||
executorName = "Ошибка"
|
||||
taskStatus = "Ошибка"
|
||||
hasTaskError = true
|
||||
case "pending":
|
||||
taskText = "Ожидает согласования"
|
||||
executorName = "Ожидает согласования"
|
||||
taskStatus = "Ожидает согласования"
|
||||
case "rejected":
|
||||
taskText = "Не выполнено (заявка отклонена)"
|
||||
executorName = "Не выполнено (заявка отклонена)"
|
||||
taskStatus = "Не выполнено (заявка отклонена)"
|
||||
case "revoked":
|
||||
taskText = "Не выполнено (заявка отозвана)"
|
||||
executorName = "Не выполнено (заявка отозвана)"
|
||||
taskStatus = "Не выполнено (заявка отозвана)"
|
||||
default:
|
||||
taskText = "Не предусмотрено"
|
||||
executorName = "Не предусмотрено"
|
||||
taskStatus = "Не предусмотрено"
|
||||
}
|
||||
}
|
||||
} else {
|
||||
var taskTexts []string
|
||||
var executorNames []string
|
||||
var taskStatuses []string
|
||||
|
||||
sort.Slice(tasks, func(i, j int) bool {
|
||||
if tasks[i].StepOrder == nil || tasks[j].StepOrder == nil {
|
||||
return false
|
||||
}
|
||||
return *tasks[i].StepOrder < *tasks[j].StepOrder
|
||||
})
|
||||
|
||||
for _, task := range tasks {
|
||||
if task.TaskText != nil {
|
||||
taskTexts = append(taskTexts, *task.TaskText)
|
||||
} else {
|
||||
taskTexts = append(taskTexts, "—")
|
||||
}
|
||||
|
||||
eName := ""
|
||||
if task.ExecutorID != nil {
|
||||
if u, err := db.User.GetUserByIDDB(ctx, *task.ExecutorID); err == nil && u != nil && u.FullName != nil {
|
||||
eName = *u.FullName
|
||||
}
|
||||
}
|
||||
executorNames = append(executorNames, eName)
|
||||
|
||||
ts := "—"
|
||||
if task.Status != nil {
|
||||
switch *task.Status {
|
||||
case "pending":
|
||||
ts = "В работе"
|
||||
case "waiting":
|
||||
ts = "Ожидает"
|
||||
case "completed":
|
||||
ts = "Выполнено"
|
||||
case "cancelled":
|
||||
ts = "Отменено"
|
||||
}
|
||||
}
|
||||
taskStatuses = append(taskStatuses, ts)
|
||||
|
||||
if taskCompletedAt == "" && task.CompletedAt != nil {
|
||||
taskCompletedAt = task.CompletedAt.Format("02.01.2006 15:04")
|
||||
}
|
||||
}
|
||||
|
||||
taskText = strings.Join(taskTexts, "\n")
|
||||
executorName = strings.Join(executorNames, "\n")
|
||||
taskStatus = strings.Join(taskStatuses, "\n")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 🆕 Добавлены две новые переменные в массив
|
||||
values := []interface{}{
|
||||
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 {
|
||||
logrus.Warnf("reportcore: set cell value %s: %v", cell, err)
|
||||
continue
|
||||
}
|
||||
|
||||
cellStyle := style
|
||||
// 🆕 Индексы колонок задач сместились из-за двух новых колонок (было 11-13, стало 13-15)
|
||||
if hasTaskError && colIdx >= 13 && colIdx <= 15 {
|
||||
cellStyle = errorStyle
|
||||
}
|
||||
if err := f.SetCellStyle(sheet, cell, cell, cellStyle); err != nil {
|
||||
logrus.Warnf("reportcore: set cell style %s: %v", cell, err)
|
||||
}
|
||||
}
|
||||
|
||||
rowHeight := 20.0
|
||||
maxLines := len(approverParts)
|
||||
if len(strings.Split(taskText, "\n")) > maxLines {
|
||||
maxLines = len(strings.Split(taskText, "\n"))
|
||||
}
|
||||
if maxLines > 1 {
|
||||
rowHeight = float64(maxLines) * 18
|
||||
}
|
||||
if err := f.SetRowHeight(sheet, row, rowHeight); err != nil {
|
||||
logrus.Warnf("reportcore: set row height %d: %v", row, err)
|
||||
}
|
||||
}
|
||||
|
||||
lastCol := cols[len(headers)-1]
|
||||
lastRow := len(approvals) + 1
|
||||
if err := f.AutoFilter(sheet, fmt.Sprintf("A1:%s%d", lastCol, lastRow), []excelize.AutoFilterOptions{}); err != nil {
|
||||
logrus.Warnf("reportcore: auto filter: %v", err)
|
||||
}
|
||||
|
||||
if err := f.SetPanes(sheet, &excelize.Panes{
|
||||
Freeze: true,
|
||||
YSplit: 1,
|
||||
TopLeftCell: "A2",
|
||||
ActivePane: "bottomLeft",
|
||||
}); err != nil {
|
||||
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)
|
||||
}
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
|
@ -0,0 +1,74 @@
|
|||
package reportcore
|
||||
|
||||
import (
|
||||
database "bitrix_balancer_api/core/db"
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
"context"
|
||||
)
|
||||
|
||||
// GetTopicCategoryCodeByApproval возвращает код категории темы для заявки.
|
||||
func GetTopicCategoryCodeByApproval(ctx context.Context, db *database.ModuleDB, a *typescore.Approval) string {
|
||||
if a == nil || a.TopicID == nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
// Если тема уже загружена
|
||||
if a.Topic != nil && a.Topic.CategoryID != nil {
|
||||
if a.Topic.Category != nil && a.Topic.Category.Code != nil {
|
||||
return *a.Topic.Category.Code
|
||||
}
|
||||
if cat, err := db.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *a.Topic.CategoryID); err == nil && cat != nil && cat.Code != nil {
|
||||
return *cat.Code
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Загружаем тему
|
||||
topic, err := db.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *a.TopicID)
|
||||
if err != nil || topic == nil || topic.CategoryID == nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
cat, err := db.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *topic.CategoryID)
|
||||
if err != nil || cat == nil || cat.Code == nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
return *cat.Code
|
||||
}
|
||||
|
||||
// GetReportCategoryCodes — объединяет категории согласующего и наблюдателя.
|
||||
// Используется для определения, какие категории доступны пользователю для отчёта.
|
||||
func GetReportCategoryCodes(ctx context.Context, db *database.ModuleDB, user *typescore.User) []string {
|
||||
if user == nil || user.ID == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
seen := map[string]bool{}
|
||||
var codes []string
|
||||
|
||||
addCodes := func(action string) {
|
||||
perms, err := db.Permission.GetUserPermissionsDB(ctx, *user.ID, action)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, p := range perms {
|
||||
if p.TopicCategoryID == nil {
|
||||
continue
|
||||
}
|
||||
cat, err := db.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *p.TopicCategoryID)
|
||||
if err != nil || cat == nil || cat.Code == nil {
|
||||
continue
|
||||
}
|
||||
if !seen[*cat.Code] {
|
||||
seen[*cat.Code] = true
|
||||
codes = append(codes, *cat.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
addCodes("create") // согласующий
|
||||
addCodes("observe") // наблюдатель
|
||||
|
||||
return codes
|
||||
}
|
||||
|
|
@ -6,16 +6,29 @@ import (
|
|||
|
||||
// Admin - структура для хранения данных о администраторах.
|
||||
type Admin struct {
|
||||
ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"` // Автоматически заполняемое уникальное поле для большого числа записей
|
||||
Login *string `gorm:"type:text;not null;unique;column:login" json:"login" db:"login" mapstructure:"login"` // Логин администратора
|
||||
PasswordHash *string `gorm:"type:text;not null;column:password_hash" json:"-" db:"password_hash" mapstructure:"password_hash"` // Пароль администратора
|
||||
CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"` // Дата создания записи
|
||||
LastLogin *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:last_login" json:"last_login" db:"last_login"` // Дата входа
|
||||
LastIPLogin *string `gorm:"type:text;column:last_ip_login" json:"last_ip_login" db:"last_ip_login" mapstructure:"last_ip_login"` // Последний IP входа
|
||||
IsBlocked *bool `gorm:"type:boolean;not null;index;default:false;column:is_blocked" json:"is_blocked" db:"is_blocked" mapstructure:"is_blocked"` // Заблокирован ли администратор
|
||||
ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"`
|
||||
Login *string `gorm:"type:text;not null;unique;column:login" json:"login" db:"login" mapstructure:"login"`
|
||||
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"`
|
||||
}
|
||||
|
||||
type AdminReq struct {
|
||||
Login *string `json:"login"`
|
||||
Password *string `json:"password"` // Пароль пользователя
|
||||
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"`
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,28 @@
|
|||
package typescore
|
||||
|
||||
import "time"
|
||||
|
||||
type AdminActionLog struct {
|
||||
ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" json:"id" db:"id"`
|
||||
AdminID *uint64 `gorm:"type:bigint;not null;index;column:admin_id" json:"admin_id" db:"admin_id"`
|
||||
AdminLogin *string `gorm:"type:text;not null;column:admin_login" json:"admin_login" db:"admin_login"`
|
||||
Action *string `gorm:"type:text;not null;column:action" json:"action" db:"action"`
|
||||
EntityType *string `gorm:"type:text;not null;column:entity_type" json:"entity_type" db:"entity_type"`
|
||||
EntityID *uint64 `gorm:"type:bigint;column:entity_id" json:"entity_id,omitempty" db:"entity_id"`
|
||||
Description *string `gorm:"type:text;not null;column:description" json:"description" db:"description"`
|
||||
Metadata *string `gorm:"type:jsonb;column:metadata" json:"metadata,omitempty" db:"metadata"`
|
||||
CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"`
|
||||
|
||||
Admin *Admin `gorm:"-" json:"admin,omitempty"`
|
||||
}
|
||||
|
||||
type AdminActionLogFilter struct {
|
||||
AdminID *uint64
|
||||
AdminLogin *string // ILIKE-подстрока
|
||||
Action *string
|
||||
EntityType *string
|
||||
EntityID *uint64
|
||||
DateFrom *time.Time
|
||||
DateTo *time.Time
|
||||
Search *string // ILIKE-подстрока по Description
|
||||
}
|
||||
|
|
@ -20,6 +20,20 @@ func (status ApprovalStatus) String() string {
|
|||
return string(status)
|
||||
}
|
||||
|
||||
// ApprovalFilter — расширенный фильтр для списка заявок
|
||||
type ApprovalFilter struct {
|
||||
ID *uint64 `json:"id"`
|
||||
Status *string `json:"status,omitempty"`
|
||||
InitiatorID *uint64 `json:"initiator_id,omitempty"`
|
||||
DepartmentID *uint64 `json:"department_id,omitempty"`
|
||||
Content *string `json:"content,omitempty"`
|
||||
DateFrom *time.Time `json:"date_from,omitempty"`
|
||||
DateTo *time.Time `json:"date_to,omitempty"`
|
||||
CategoryIDs []uint64 `json:"category_ids,omitempty"` // множественный выбор категорий
|
||||
TopicIDs []uint64 `json:"topic_ids,omitempty"` // множественный выбор тем
|
||||
ObserverUserID *uint64 `json:"observer_user_id"`
|
||||
}
|
||||
|
||||
// Approval — заявка на согласование.
|
||||
// Status: draft | pending | approved | rejected | revoked
|
||||
// DepartmentID копируется с инициатора в момент создания — для отчётов и изоляции без JOIN.
|
||||
|
|
@ -29,7 +43,7 @@ type Approval struct {
|
|||
InitiatorID *uint64 `gorm:"type:bigint;not null;index;column:initiator_id" json:"initiator_id" db:"initiator_id" mapstructure:"initiator_id"`
|
||||
TopicID *uint64 `gorm:"type:bigint;not null;index;column:topic_id" json:"topic_id" db:"topic_id" mapstructure:"topic_id"`
|
||||
DepartmentID *uint64 `gorm:"type:bigint;not null;index;column:department_id" json:"department_id" db:"department_id" mapstructure:"department_id"` // снимок отдела на момент создания
|
||||
Content *string `gorm:"type:text;not null;column:content" json:"content" db:"content" mapstructure:"content"` // введённые пользователем данные по шаблону
|
||||
Content *string `gorm:"type:text;not null;column:content" json:"content" db:"content" mapstructure:"content" mapstructure:"content"` // введённые пользователем данные по шаблону
|
||||
Status *string `gorm:"type:text;not null;default:'pending';index;column:status" json:"status" db:"status" mapstructure:"status"`
|
||||
RevokedByID *uint64 `gorm:"type:bigint;index;column:revoked_by_id" json:"revoked_by_id,omitempty" db:"revoked_by_id" mapstructure:"revoked_by_id"`
|
||||
RevokedAt *time.Time `gorm:"type:timestamp;column:revoked_at" json:"revoked_at,omitempty" db:"revoked_at"`
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ type ApprovalDelegation struct {
|
|||
IsActive *bool `gorm:"type:boolean;not null;default:true;column:is_active" json:"is_active" db:"is_active"`
|
||||
NotifiedDay *bool `gorm:"type:boolean;not null;default:false;column:notified_day" json:"notified_day" db:"notified_day"`
|
||||
Notified2h *bool `gorm:"type:boolean;not null;default:false;column:notified_2h" json:"notified_2h" db:"notified_2h"`
|
||||
ApprovalID *uint64 `gorm:"type:bigint;index;column:approval_id" json:"approval_id,omitempty" db:"approval_id" mapstructure:"approval_id"`
|
||||
CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"`
|
||||
UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at"`
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,37 @@
|
|||
package typescore
|
||||
|
||||
import "time"
|
||||
|
||||
// ApprovalFlowNode — узел дерева навигации темы согласования
|
||||
type ApprovalFlowNode struct {
|
||||
ID *uint64 `gorm:"column:id;type:bigserial;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"`
|
||||
TopicID *uint64 `gorm:"type:bigint;index;column:topic_id" json:"topic_id,omitempty" db:"topic_id" mapstructure:"topic_id"`
|
||||
ParentID *uint64 `gorm:"type:bigint;index;column:parent_id" json:"parent_id,omitempty" db:"parent_id" mapstructure:"parent_id"`
|
||||
CategoryID *uint64 `gorm:"type:bigint;not null;index;column:category_id" json:"category_id" db:"category_id" mapstructure:"category_id"`
|
||||
|
||||
Key *string `gorm:"type:text;not null;column:key" json:"key" db:"key" mapstructure:"key"`
|
||||
Label *string `gorm:"type:text;not null;column:label" json:"label" db:"label" mapstructure:"label"`
|
||||
|
||||
DataKey *string `gorm:"type:text;column:data_key" json:"data_key,omitempty" db:"data_key" mapstructure:"data_key"`
|
||||
DataValue *string `gorm:"type:text;column:data_value" json:"data_value,omitempty" db:"data_value" mapstructure:"data_value"`
|
||||
|
||||
IsInput *bool `gorm:"type:boolean;default:false;column:is_input" json:"is_input" db:"is_input" mapstructure:"is_input"`
|
||||
InputKey *string `gorm:"type:text;column:input_key" json:"input_key,omitempty" db:"input_key" mapstructure:"input_key"`
|
||||
InputHint *string `gorm:"type:text;column:input_hint" json:"input_hint,omitempty" db:"input_hint" mapstructure:"input_hint"`
|
||||
|
||||
IsMultiSelect *bool `gorm:"type:boolean;default:false;column:is_multi_select" json:"is_multi_select" db:"is_multi_select" mapstructure:"is_multi_select"`
|
||||
MultiSelectKey *string `gorm:"type:text;column:multi_select_key" json:"multi_select_key,omitempty" db:"multi_select_key" mapstructure:"multi_select_key"`
|
||||
MultiSelectValue *string `gorm:"type:text;column:multi_select_value" json:"multi_select_value,omitempty" db:"multi_select_value" mapstructure:"multi_select_value"`
|
||||
|
||||
TopicCode *string `gorm:"type:text;column:topic_code" json:"topic_code,omitempty" db:"topic_code" mapstructure:"topic_code"`
|
||||
|
||||
SortOrder *int `gorm:"type:integer;default:0;column:sort_order" json:"sort_order" db:"sort_order" mapstructure:"sort_order"`
|
||||
|
||||
CodeTemplate *string `gorm:"type:text;column:code_template" json:"code_template,omitempty" db:"code_template" mapstructure:"code_template"`
|
||||
MessageTemplate *string `gorm:"type:text;column:message_template" json:"message_template,omitempty" db:"message_template" mapstructure:"message_template"`
|
||||
|
||||
CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at" mapstructure:"created_at"`
|
||||
UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at" mapstructure:"updated_at"`
|
||||
|
||||
Children []*ApprovalFlowNode `gorm:"-" json:"children,omitempty"`
|
||||
}
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
package typescore
|
||||
|
||||
import "time"
|
||||
|
||||
type ApprovalRevocationRequest struct {
|
||||
ID *uint64 `gorm:"column:id" json:"id" db:"id"`
|
||||
ApprovalID *uint64 `gorm:"column:approval_id" json:"approval_id" db:"approval_id"`
|
||||
RequestedByID *uint64 `gorm:"column:requested_by_id" json:"requested_by_id" db:"requested_by_id"`
|
||||
Reason *string `gorm:"column:reason" json:"reason,omitempty" db:"reason"`
|
||||
Status *string `gorm:"column:status" json:"status" db:"status"`
|
||||
CreatedAt *time.Time `gorm:"column:created_at" json:"created_at" db:"created_at"`
|
||||
UpdatedAt *time.Time `gorm:"column:updated_at" json:"updated_at" db:"updated_at"`
|
||||
}
|
||||
|
||||
type ApprovalRevocationApprover struct {
|
||||
ID *uint64 `gorm:"column:id" json:"id" db:"id"`
|
||||
RevocationRequestID *uint64 `gorm:"column:revocation_request_id" json:"revocation_request_id" db:"revocation_request_id"`
|
||||
ApproverID *uint64 `gorm:"column:approver_id" json:"approver_id" db:"approver_id"`
|
||||
Status *string `gorm:"column:status" json:"status" db:"status"`
|
||||
Comment *string `gorm:"column:comment" json:"comment,omitempty" db:"comment"`
|
||||
ActedAt *time.Time `gorm:"column:acted_at" json:"acted_at,omitempty" db:"acted_at"`
|
||||
CreatedAt *time.Time `gorm:"column:created_at" json:"created_at" db:"created_at"`
|
||||
}
|
||||
|
|
@ -3,18 +3,20 @@ package typescore
|
|||
import "time"
|
||||
|
||||
type ApprovalTask struct {
|
||||
ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" json:"id" db:"id"`
|
||||
ApprovalID *uint64 `gorm:"type:bigint;not null;index;column:approval_id" json:"approval_id" db:"approval_id"`
|
||||
ExecutorID *uint64 `gorm:"type:bigint;not null;index;column:executor_id" json:"executor_id" db:"executor_id"`
|
||||
ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" json:"id" db:"id" mapstructure:"id"`
|
||||
ApprovalID *uint64 `gorm:"type:bigint;not null;index;column:approval_id" json:"approval_id" db:"approval_id" mapstructure:"approval_id"`
|
||||
ExecutorID *uint64 `gorm:"type:bigint;not null;index;column:executor_id" json:"executor_id" db:"executor_id" mapstructure:"executor_id"`
|
||||
TaskText *string `gorm:"type:text;not null;column:task_text" json:"task_text" db:"task_text"`
|
||||
Status *string `gorm:"type:text;not null;default:'pending';index;column:status" json:"status" db:"status"`
|
||||
Status *string `gorm:"type:text;not null;default:'pending';index;column:status" json:"status" db:"status" mapstructure:"status"`
|
||||
StepOrder *int `gorm:"type:int;default:0;column:step_order" json:"step_order" db:"step_order"`
|
||||
RequireFile *bool `gorm:"type:boolean;default:false;column:require_file" json:"require_file" db:"require_file"`
|
||||
TopicExecutorID *uint64 `gorm:"type:bigint;column:topic_executor_id" json:"topic_executor_id,omitempty" db:"topic_executor_id"`
|
||||
RequireFile *bool `gorm:"type:boolean;default:false;column:require_file" json:"require_file" db:"require_file" mapstructure:"require_file"`
|
||||
TopicExecutorID *uint64 `gorm:"type:bigint;column:topic_executor_id" json:"topic_executor_id,omitempty" db:"topic_executor_id" mapstructure:"topic_executor_id"`
|
||||
CompletedAt *time.Time `gorm:"type:timestamp;column:completed_at" json:"completed_at,omitempty" db:"completed_at"`
|
||||
CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"`
|
||||
UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at"`
|
||||
|
||||
Approval *Approval `gorm:"-" json:"approval,omitempty"`
|
||||
Executor *User `gorm:"-" json:"executor,omitempty"`
|
||||
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"`
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,13 @@
|
|||
package typescore
|
||||
|
||||
import "time"
|
||||
|
||||
type ApprovalTaskTransfer struct {
|
||||
ID *uint64 `gorm:"column:id;primaryKey;autoIncrement" json:"id" db:"id"`
|
||||
TaskID *uint64 `gorm:"column:task_id;not null" json:"task_id" db:"task_id"`
|
||||
FromExecutorID *uint64 `gorm:"column:from_executor_id;not null" json:"from_executor_id" db:"from_executor_id"`
|
||||
ToExecutorID *uint64 `gorm:"column:to_executor_id;not null" json:"to_executor_id" db:"to_executor_id"`
|
||||
Status *string `gorm:"column:status;type:text;not null;default:'pending'" json:"status" db:"status"`
|
||||
CreatedAt *time.Time `gorm:"column:created_at;default:CURRENT_TIMESTAMP" json:"created_at" db:"created_at"`
|
||||
RespondedAt *time.Time `gorm:"column:responded_at" json:"responded_at,omitempty" db:"responded_at"`
|
||||
}
|
||||
|
|
@ -29,6 +29,7 @@ type ApprovalTopic struct {
|
|||
RequireApproverComment *bool `gorm:"type:boolean;default:false;column:require_approver_comment" json:"require_approver_comment" db:"require_approver_comment"`
|
||||
RequiresFile *bool `gorm:"type:boolean;not null;default:false;column:requires_file" json:"requires_file" db:"requires_file"`
|
||||
RequireObserverSelection *bool `gorm:"type:boolean;not null;default:false;column:require_observer_selection" json:"require_observer_selection" db:"require_observer_selection"`
|
||||
AllowDelegationSelection *bool `gorm:"type:boolean;not null;default:false;column:allow_delegation_selection" json:"allow_delegation_selection,omitempty" db:"allow_delegation_selection" mapstructure:"allow_delegation_selection"`
|
||||
|
||||
IsActive *bool `gorm:"type:boolean;not null;default:true;column:is_active" json:"is_active" db:"is_active" mapstructure:"is_active"`
|
||||
CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"`
|
||||
|
|
|
|||
|
|
@ -0,0 +1,10 @@
|
|||
package typescore
|
||||
|
||||
import "time"
|
||||
|
||||
type DirectorNotificationSubscription struct {
|
||||
ID *uint64 `gorm:"column:id" json:"id" db:"id"`
|
||||
DirectorID *uint64 `gorm:"column:director_id" json:"director_id" db:"director_id"`
|
||||
CategoryID *uint64 `gorm:"column:category_id" json:"category_id" db:"category_id"`
|
||||
CreatedAt *time.Time `gorm:"column:created_at" json:"created_at" db:"created_at"`
|
||||
}
|
||||
|
|
@ -0,0 +1,62 @@
|
|||
package typescore
|
||||
|
||||
import "time"
|
||||
|
||||
// MonthlyOrderSetting — настройки периода заказа (задаются аналитиком)
|
||||
type MonthlyOrderSetting struct {
|
||||
ID *uint64 `json:"id" db:"id" gorm:"primaryKey;autoIncrement"`
|
||||
Month *int `json:"month" db:"month"`
|
||||
Year *int `json:"year" db:"year"`
|
||||
DeadlineDate *time.Time `json:"deadline_date" db:"deadline_date"` // Дата закрытия доступа
|
||||
AssemblyTimeDays *int `json:"assembly_time_days" db:"assembly_time_days"` // Срок сборки заказа (задается аналитиком)
|
||||
CreatedAt *time.Time `json:"created_at" db:"created_at"`
|
||||
UpdatedAt *time.Time `json:"updated_at" db:"updated_at"`
|
||||
}
|
||||
|
||||
// MonthlyOrderClient — заказ конкретного клиента у менеджера
|
||||
type MonthlyOrderClient struct {
|
||||
ID *uint64 `json:"id" db:"id" gorm:"primaryKey;autoIncrement"`
|
||||
ManagerID *uint64 `json:"manager_id" db:"manager_id"`
|
||||
Month *int `json:"month" db:"month"`
|
||||
Year *int `json:"year" db:"year"`
|
||||
ClientName *string `json:"client_name" db:"client_name"`
|
||||
|
||||
OrderType *string `json:"order_type" db:"order_type"`
|
||||
|
||||
// Комментарии
|
||||
ManagerComment *string `json:"manager_comment" db:"manager_comment"` // Основной из списка
|
||||
CustomReason *string `json:"custom_reason" db:"custom_reason"` // Причина, если "Заказа не будет"
|
||||
FreeFormComment *string `json:"free_form_comment" db:"free_form_comment"` // Свободный текст в конце
|
||||
|
||||
// Сопроводительная информация
|
||||
Decade *string `json:"decade" db:"decade"`
|
||||
Delivery *string `json:"delivery" db:"delivery"`
|
||||
Conditions *string `json:"conditions" db:"conditions"`
|
||||
PaymentForm *string `json:"payment_form" db:"payment_form"`
|
||||
|
||||
Status *string `json:"status" db:"status"` // draft, submitted, approved
|
||||
ApprovalID *uint64 `json:"approval_id" db:"approval_id"` // ID созданной заявки в боте (если уже отправлено)
|
||||
CreatedAt *time.Time `json:"created_at" db:"created_at"`
|
||||
UpdatedAt *time.Time `json:"updated_at" db:"updated_at"`
|
||||
|
||||
// Связи (не хранятся напрямую в этой таблице)
|
||||
Items []MonthlyOrderItem `json:"items,omitempty" gorm:"-"`
|
||||
Files []MonthlyOrderFile `json:"files,omitempty" gorm:"-"`
|
||||
}
|
||||
|
||||
// MonthlyOrderItem — конкретная номенклатура и ее количество в заказе клиента
|
||||
type MonthlyOrderItem struct {
|
||||
ID *uint64 `json:"id" db:"id" gorm:"primaryKey;autoIncrement"`
|
||||
OrderClientID *uint64 `json:"order_client_id" db:"order_client_id"`
|
||||
NomenclatureName *string `json:"nomenclature_name" db:"nomenclature_name"`
|
||||
NomenclatureType *string `json:"nomenclature_type" db:"nomenclature_type"`
|
||||
Quantity *int `json:"quantity" db:"quantity"`
|
||||
}
|
||||
|
||||
// MonthlyOrderFile — приложенные файлы к заказе клиента
|
||||
type MonthlyOrderFile struct {
|
||||
ID *uint64 `json:"id" db:"id" gorm:"primaryKey;autoIncrement"`
|
||||
OrderClientID *uint64 `json:"order_client_id" db:"order_client_id"`
|
||||
FileBase64 *string `json:"file_base64" db:"file_base64"`
|
||||
FileName *string `json:"file_name" db:"file_name"`
|
||||
}
|
||||
|
|
@ -0,0 +1,54 @@
|
|||
package typescore
|
||||
|
||||
import "time"
|
||||
|
||||
// Notification — рассылка/уведомление
|
||||
type Notification struct {
|
||||
ID *uint64 `gorm:"column:id" json:"id" db:"id"`
|
||||
Title *string `gorm:"column:title" json:"title" db:"title"`
|
||||
MessageHTML *string `gorm:"column:message_html" json:"message_html" db:"message_html"`
|
||||
PhotoBase64 *string `gorm:"column:photo_base64" json:"photo_base64,omitempty" db:"photo_base64"`
|
||||
PhotoFileName *string `gorm:"column:photo_file_name" json:"photo_file_name,omitempty" db:"photo_file_name"`
|
||||
TargetFilters *string `gorm:"column:target_filters" json:"target_filters" db:"target_filters"` // JSON-строка
|
||||
Status *string `gorm:"column:status" json:"status" db:"status"`
|
||||
TotalCount *int `gorm:"column:total_count" json:"total_count" db:"total_count"`
|
||||
SentCount *int `gorm:"column:sent_count" json:"sent_count" db:"sent_count"`
|
||||
FailedCount *int `gorm:"column:failed_count" json:"failed_count" db:"failed_count"`
|
||||
CreatedByID *uint64 `gorm:"column:created_by_id" json:"created_by_id,omitempty" db:"created_by_id"`
|
||||
CreatedAt *time.Time `gorm:"column:created_at" json:"created_at" db:"created_at"`
|
||||
UpdatedAt *time.Time `gorm:"column:updated_at" json:"updated_at" db:"updated_at"`
|
||||
SentAt *time.Time `gorm:"column:sent_at" json:"sent_at,omitempty" db:"sent_at"`
|
||||
|
||||
Recipients []*NotificationRecipient `gorm:"-" json:"recipients,omitempty"`
|
||||
}
|
||||
|
||||
// NotificationRecipient — история доставки конкретному пользователю
|
||||
type NotificationRecipient struct {
|
||||
ID *uint64 `gorm:"column:id" json:"id" db:"id"`
|
||||
NotificationID *uint64 `gorm:"column:notification_id" json:"notification_id" db:"notification_id"`
|
||||
UserID *uint64 `gorm:"column:user_id" json:"user_id" db:"user_id"`
|
||||
Status *string `gorm:"column:status" json:"status" db:"status"`
|
||||
ErrorMessage *string `gorm:"column:error_message" json:"error_message,omitempty" db:"error_message"`
|
||||
TelegramMessageID *int `gorm:"column:telegram_message_id" json:"telegram_message_id,omitempty" db:"telegram_message_id"`
|
||||
SentAt *time.Time `gorm:"column:sent_at" json:"sent_at,omitempty" db:"sent_at"`
|
||||
CreatedAt *time.Time `gorm:"column:created_at" json:"created_at" db:"created_at"`
|
||||
|
||||
User *User `gorm:"-" json:"user,omitempty"`
|
||||
}
|
||||
|
||||
// TargetFilters — критерии выбора получателей, приходят из админки и сохраняются как есть в JSONB
|
||||
type TargetFilters struct {
|
||||
UserIDs []uint64 `json:"user_ids,omitempty"` // 1. конкретные пользователи
|
||||
RoleIDs []uint64 `json:"role_ids,omitempty"` // 2. конкретные роли (по id)
|
||||
RoleTypeFlags []string `json:"role_type_flags,omitempty"` // 3. типы ролей: director|approver|observer|executor|controller
|
||||
DepartmentIDs []uint64 `json:"department_ids,omitempty"` // 4. отделы
|
||||
}
|
||||
|
||||
// CreateNotificationReq — тело запроса на создание+отправку рассылки
|
||||
type CreateNotificationReq struct {
|
||||
Title string `json:"title"`
|
||||
MessageHTML string `json:"message_html"`
|
||||
PhotoBase64 *string `json:"photo_base64,omitempty"`
|
||||
PhotoFileName *string `json:"photo_file_name,omitempty"`
|
||||
Targets TargetFilters `json:"targets"`
|
||||
}
|
||||
|
|
@ -3,17 +3,18 @@ package typescore
|
|||
import "time"
|
||||
|
||||
type Role struct {
|
||||
ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"`
|
||||
Name *string `gorm:"type:text;not null;column:name" json:"name" db:"name" mapstructure:"name"`
|
||||
Code *string `gorm:"type:text;not null;unique;column:code" json:"code" db:"code" mapstructure:"code"`
|
||||
IsDefault *bool `gorm:"type:boolean;not null;default:false;column:is_default" json:"is_default" db:"is_default" mapstructure:"is_default"`
|
||||
IsDirector *bool `gorm:"type:boolean;not null;default:false;column:is_director" json:"is_director" db:"is_director" mapstructure:"is_director"`
|
||||
IsApprover *bool `gorm:"type:boolean;not null;default:false;column:is_approver" json:"is_approver" db:"is_approver" mapstructure:"is_approver"`
|
||||
IsObserver *bool `gorm:"type:boolean;not null;default:false;column:is_observer" json:"is_observer" db:"is_observer" mapstructure:"is_observer"`
|
||||
IsExecutor *bool `gorm:"type:boolean;not null;default:false;column:is_executor" json:"is_executor" db:"is_executor" mapstructure:"is_executor"`
|
||||
Description *string `gorm:"type:text;column:description" json:"description,omitempty" db:"description" mapstructure:"description"`
|
||||
CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"`
|
||||
UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at"`
|
||||
ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"`
|
||||
Name *string `gorm:"type:text;not null;column:name" json:"name" db:"name" mapstructure:"name"`
|
||||
Code *string `gorm:"type:text;not null;unique;column:code" json:"code" db:"code" mapstructure:"code"`
|
||||
IsDefault *bool `gorm:"type:boolean;not null;default:false;column:is_default" json:"is_default" db:"is_default" mapstructure:"is_default"`
|
||||
IsDirector *bool `gorm:"type:boolean;not null;default:false;column:is_director" json:"is_director" db:"is_director" mapstructure:"is_director"`
|
||||
IsApprover *bool `gorm:"type:boolean;not null;default:false;column:is_approver" json:"is_approver" db:"is_approver" mapstructure:"is_approver"`
|
||||
IsObserver *bool `gorm:"type:boolean;not null;default:false;column:is_observer" json:"is_observer" db:"is_observer" mapstructure:"is_observer"`
|
||||
IsExecutor *bool `gorm:"type:boolean;not null;default:false;column:is_executor" json:"is_executor" db:"is_executor" mapstructure:"is_executor"`
|
||||
IsController *bool `gorm:"type:boolean;not null;default:false;column:is_controller" json:"is_controller" db:"is_controller" mapstructure:"is_controller"`
|
||||
Description *string `gorm:"type:text;column:description" json:"description,omitempty" db:"description" mapstructure:"description"`
|
||||
CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"`
|
||||
UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at"`
|
||||
|
||||
Permissions []*Permission `gorm:"-" json:"permissions,omitempty"`
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,21 @@
|
|||
package typescore
|
||||
|
||||
import "time"
|
||||
|
||||
type TaskDelegation struct {
|
||||
ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" json:"id" db:"id"`
|
||||
DelegatorID *uint64 `gorm:"type:bigint;not null;index;column:delegator_id" json:"delegator_id" db:"delegator_id"`
|
||||
DelegateID *uint64 `gorm:"type:bigint;not null;index;column:delegate_id" json:"delegate_id" db:"delegate_id"`
|
||||
ValidUntil *time.Time `gorm:"type:timestamp;not null;column:valid_until" json:"valid_until" db:"valid_until"`
|
||||
IsActive *bool `gorm:"type:boolean;not null;default:true;column:is_active" json:"is_active" db:"is_active"`
|
||||
NotifiedDay *bool `gorm:"type:boolean;not null;default:false;column:notified_day" json:"notified_day" db:"notified_day"`
|
||||
Notified2h *bool `gorm:"type:boolean;not null;default:false;column:notified_2h" json:"notified_2h" db:"notified_2h"`
|
||||
CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"`
|
||||
UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at"`
|
||||
ApprovalID *uint64 `gorm:"type:bigint;index;column:approval_id" json:"approval_id,omitempty" db:"approval_id"`
|
||||
CategoryID *uint64 `gorm:"type:bigint;index;column:category_id" json:"category_id,omitempty" db:"category_id"`
|
||||
TopicID *uint64 `gorm:"type:bigint;index;column:topic_id" json:"topic_id,omitempty" db:"topic_id"`
|
||||
|
||||
Delegator *User `gorm:"-" json:"delegator,omitempty"`
|
||||
Delegate *User `gorm:"-" json:"delegate,omitempty"`
|
||||
}
|
||||
|
|
@ -0,0 +1,78 @@
|
|||
package typescore
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
// SmsLog - модель для хранения истории SMS
|
||||
type SmsLog struct {
|
||||
ID *uint64 `json:"id" db:"id" gorm:"column:id;primaryKey;autoIncrement"`
|
||||
AccountID *string `json:"account_id" db:"account_id" gorm:"column:account_id"`
|
||||
UserID *string `json:"user_id" db:"user_id" gorm:"column:user_id"`
|
||||
ClientNumber *string `json:"client_number" db:"client_number" gorm:"column:client_number;index"`
|
||||
Direction *int `json:"direction" db:"direction" gorm:"column:direction"`
|
||||
Text *string `json:"text" db:"text" gorm:"column:text"`
|
||||
EventCreated *time.Time `json:"event_created" db:"event_created" gorm:"column:event_created;index"`
|
||||
CreatedAt *time.Time `json:"created_at" db:"created_at" gorm:"column:created_at;default:CURRENT_TIMESTAMP"`
|
||||
}
|
||||
|
||||
// TelephonyWebhookReq описывает корневой объект POST-запроса от Webhook API
|
||||
type TelephonyWebhookReq struct {
|
||||
Webhook WebhookMeta `json:"webhook"`
|
||||
Event CallEvent `json:"event"`
|
||||
}
|
||||
|
||||
// WebhookMeta содержит метаданные о том, кто и где сгенерировал событие
|
||||
type WebhookMeta struct {
|
||||
Action string `json:"action"`
|
||||
AccountID string `json:"account_id"`
|
||||
AccountName string `json:"account_name"`
|
||||
UserID string `json:"user_id"`
|
||||
UserLogin string `json:"user_login"`
|
||||
}
|
||||
|
||||
// CallEvent описывает полезную нагрузку события (звонок или SMS)
|
||||
type CallEvent struct {
|
||||
EventType int `json:"event_type"` // 1 - начало; 2 - ответ; 4 - окончание; 32 - SMS
|
||||
EventCreated int64 `json:"event_created"`
|
||||
Direction int `json:"direction"` // 0 - входящий, 1 - исходящий
|
||||
ClientNumber string `json:"client_number"`
|
||||
ClientName string `json:"client_name"`
|
||||
SrcNumber string `json:"src_number"`
|
||||
SrcSlot int `json:"src_slot"`
|
||||
|
||||
EventPbxCallID FlexString `json:"event_pbx_call_id"`
|
||||
SrcID FlexString `json:"src_id"`
|
||||
DBCallID FlexString `json:"db_call_id,omitempty"`
|
||||
|
||||
// Поля, которые приходят только в событии окончания звонка (event_type == 4)
|
||||
StartTime int64 `json:"start_time,omitempty"`
|
||||
AnswerTime int64 `json:"answer_time,omitempty"`
|
||||
EndTime int64 `json:"end_time,omitempty"`
|
||||
Duration int `json:"duration,omitempty"`
|
||||
Answered int `json:"answered,omitempty"` // 0 - не отвечен, 1 - отвечен
|
||||
Recording string `json:"recording,omitempty"` // Ссылка на запись разговора
|
||||
|
||||
// Поле, которое приходит только для SMS (event_type == 32)
|
||||
Text string `json:"text,omitempty"`
|
||||
}
|
||||
|
||||
// FlexString принимает JSON-строку или число.
|
||||
type FlexString string
|
||||
|
||||
func (f *FlexString) UnmarshalJSON(b []byte) error {
|
||||
if string(b) == "null" {
|
||||
return nil
|
||||
}
|
||||
if len(b) > 0 && b[0] == '"' {
|
||||
var s string
|
||||
if err := json.Unmarshal(b, &s); err != nil {
|
||||
return err
|
||||
}
|
||||
*f = FlexString(s)
|
||||
return nil
|
||||
}
|
||||
*f = FlexString(b) // число как есть
|
||||
return nil
|
||||
}
|
||||
|
|
@ -15,8 +15,11 @@ 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"`
|
||||
Department *Department `gorm:"-" json:"department,omitempty"`
|
||||
Subordinate *User `gorm:"-" json:"subordinate,omitempty"`
|
||||
Approver *User `gorm:"-" json:"approver,omitempty"`
|
||||
Department *Department `gorm:"-" json:"department,omitempty"`
|
||||
TopicCategory *ApprovalTopicCategory `gorm:"-" json:"topic_category,omitempty"`
|
||||
Topic *ApprovalTopic `gorm:"-" json:"topic,omitempty"`
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,62 @@
|
|||
package utilscore
|
||||
|
||||
func DerefStr(s *string) string {
|
||||
if s == nil {
|
||||
return ""
|
||||
}
|
||||
return *s
|
||||
}
|
||||
|
||||
func DerefBool(b *bool) bool {
|
||||
if b == nil {
|
||||
return false
|
||||
}
|
||||
return *b
|
||||
}
|
||||
|
||||
func StrEq(a, b *string) bool {
|
||||
if a == nil && b == nil {
|
||||
return true
|
||||
}
|
||||
if a == nil || b == nil {
|
||||
return false
|
||||
}
|
||||
return *a == *b
|
||||
}
|
||||
|
||||
func BoolEq(a, b *bool) bool {
|
||||
if a == nil && b == nil {
|
||||
return true
|
||||
}
|
||||
if a == nil || b == nil {
|
||||
return false
|
||||
}
|
||||
return *a == *b
|
||||
}
|
||||
|
||||
func Uint64Eq(a, b *uint64) bool {
|
||||
if a == nil && b == nil {
|
||||
return true
|
||||
}
|
||||
if a == nil || b == nil {
|
||||
return false
|
||||
}
|
||||
return *a == *b
|
||||
}
|
||||
|
||||
func IntEq(a, b *int) bool {
|
||||
if a == nil && b == nil {
|
||||
return true
|
||||
}
|
||||
if a == nil || b == nil {
|
||||
return false
|
||||
}
|
||||
return *a == *b
|
||||
}
|
||||
|
||||
func DerefInt(i *int) int {
|
||||
if i == nil {
|
||||
return 0
|
||||
}
|
||||
return *i
|
||||
}
|
||||
|
|
@ -8,3 +8,10 @@ const (
|
|||
ContextTimeoutBase = 15 * time.Second
|
||||
ContextTimeoutLong = 30 * time.Second
|
||||
)
|
||||
|
||||
// Константы для нового API-прокси
|
||||
const (
|
||||
ProxyForwardURL = "https://37.252.5.229.nip.io/forward"
|
||||
ProxySecretHeader = "X-Proxy-Secret"
|
||||
ProxySecretKey = "9cb0a2655bde593de45b2f3fd17f39e5"
|
||||
)
|
||||
|
|
|
|||
245
deploy.sh
245
deploy.sh
|
|
@ -1,6 +1,7 @@
|
|||
#!/bin/bash
|
||||
|
||||
set -e
|
||||
set -E # Гарантирует, что trap ERR будет работать внутри всех подфункций
|
||||
trap 'echo "🔴 Deploy failed at line $LINENO"; exit 1' ERR
|
||||
|
||||
THIS_PATH=$(dirname "$(realpath "$0")")
|
||||
|
|
@ -15,6 +16,10 @@ BLUE='\033[0;34m'
|
|||
MAGENTA='\033[0;35m'
|
||||
NC='\033[0m'
|
||||
|
||||
# Окружение Go для сборки под sudo / root
|
||||
export GOPATH=/home/git/.go
|
||||
export PATH=$PATH:/usr/local/go/bin:$GOPATH/bin
|
||||
|
||||
log_info() { echo -e "${BLUE}ℹ️ $1${NC}"; }
|
||||
log_success() { echo -e "${GREEN}✅ $1${NC}"; }
|
||||
log_warning() { echo -e "${YELLOW}⚠️ $1${NC}"; }
|
||||
|
|
@ -24,65 +29,50 @@ log_service() { echo -e "${MAGENTA}📦 $1${NC}"; }
|
|||
# ═══════════════════════════════════════════════════════════════
|
||||
# Парсинг аргументов
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
SERVICE_TYPE="${1:-all}" # bot | admin | balancer | telegram | migrations | all
|
||||
GENERATE_SWAGGER="${2:-false}" # swagger
|
||||
SERVICE_TYPE="${1:-all}"
|
||||
GENERATE_SWAGGER="${2:-false}"
|
||||
|
||||
# Валидация
|
||||
validate_service_type() {
|
||||
case "$1" in
|
||||
bot|telegram|balancer|admin|migrations|all) return 0 ;;
|
||||
bot|telegram|balancer|admin|migrations|telephony|all) return 0 ;; # 🆕 Добавлен telephony
|
||||
*) return 1 ;;
|
||||
esac
|
||||
}
|
||||
|
||||
if ! validate_service_type "$SERVICE_TYPE"; then
|
||||
log_error "Unknown service type: $SERVICE_TYPE"
|
||||
echo ""
|
||||
echo "Usage: $0 [service] [swagger]"
|
||||
echo ""
|
||||
echo "Services:"
|
||||
echo " telegram - Telegram bot service"
|
||||
echo " balancer - REST balancer service"
|
||||
echo " admin - REST admin service"
|
||||
echo " migrations - Run database migrations only"
|
||||
echo " all - Deploy all services (default)"
|
||||
echo ""
|
||||
echo "Options:"
|
||||
echo " swagger - Generate Swagger docs (for admin)"
|
||||
echo ""
|
||||
echo "Examples:"
|
||||
echo " $0 # Deploy all services"
|
||||
echo " $0 telegram # Deploy only bot"
|
||||
echo " $0 admin swagger # Deploy admin with Swagger"
|
||||
echo " $0 migrations # Run migrations only"
|
||||
echo "Usage: $0 [telegram|balancer|admin|migrations|telephony|all] [swagger]"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
# Обработка 'all' — деплоим всё последовательно
|
||||
# Обработка 'all'
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
if [ "$SERVICE_TYPE" = "all" ]; then
|
||||
log_info "Deploying all services..."
|
||||
echo ""
|
||||
|
||||
# 1. Сначала миграции
|
||||
log_service "Step 1/4: Database migrations"
|
||||
"$0" migrations
|
||||
SELF="$THIS_PATH/deploy.sh"
|
||||
|
||||
log_service "Step 1/5: Database migrations"
|
||||
bash "$SELF" migrations
|
||||
echo ""
|
||||
|
||||
# 2. Потом Telegram бот
|
||||
log_service "Step 2/4: Telegram bot"
|
||||
"$0" telegram
|
||||
log_service "Step 2/5: Telegram bot"
|
||||
bash "$SELF" telegram
|
||||
echo ""
|
||||
|
||||
# 3. Потом балансировщик
|
||||
log_service "Step 3/4: REST balancer"
|
||||
"$0" balancer
|
||||
# log_service "Step 3/5: REST balancer"
|
||||
# bash "$SELF" balancer
|
||||
# echo ""
|
||||
|
||||
log_service "Step 4/5: REST admin"
|
||||
bash "$SELF" admin "$GENERATE_SWAGGER"
|
||||
echo ""
|
||||
|
||||
# 4. В конце админка (с Swagger если нужно)
|
||||
log_service "Step 4/4: REST admin"
|
||||
"$0" admin "$GENERATE_SWAGGER"
|
||||
log_service "Step 5/5: REST telephony" # 🆕 Добавлен шаг деплоя телефонии
|
||||
bash "$SELF" telephony
|
||||
echo ""
|
||||
|
||||
echo ""
|
||||
log_success "All services deployed successfully!"
|
||||
|
|
@ -111,7 +101,12 @@ case "$SERVICE_TYPE" in
|
|||
migrations)
|
||||
SERVICE_NAME="system_service"
|
||||
DESCRIPTION="Database Migrations"
|
||||
SERVICE_KIND="oneshot"
|
||||
SERVICE_KIND="oneshot" # 🔧 ИСПРАВЛЕНИЕ: здесь раньше ошибочно стояло "daemon"
|
||||
;;
|
||||
telephony) # 🆕 Конфигурация для нового сервиса
|
||||
SERVICE_NAME="rest_telephony_service"
|
||||
DESCRIPTION="REST Telephony Service"
|
||||
SERVICE_KIND="daemon"
|
||||
;;
|
||||
esac
|
||||
|
||||
|
|
@ -127,14 +122,13 @@ log_info "Binary: $BINARY_PATH"
|
|||
echo "════════════════════════════════════════"
|
||||
echo ""
|
||||
|
||||
# Проверка существования директории сервиса
|
||||
if [ ! -d "$SERVICE_PATH" ]; then
|
||||
log_error "Service directory not found: $SERVICE_PATH"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
# Генерация Swagger документации (только для админки)
|
||||
# Генерация Swagger (только для админки)
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
if [ "$SERVICE_TYPE" = "admin" ] && [ "$GENERATE_SWAGGER" = "swagger" ]; then
|
||||
log_info "Generating Swagger documentation..."
|
||||
|
|
@ -146,10 +140,38 @@ if [ "$SERVICE_TYPE" = "admin" ] && [ "$GENERATE_SWAGGER" = "swagger" ]; then
|
|||
fi
|
||||
|
||||
cd "$SERVICE_PATH"
|
||||
mkdir -p ./docs
|
||||
swag init -g main.go --parseDependency --parseInternal -o ./docs
|
||||
|
||||
log_success "Swagger documentation generated"
|
||||
# Автоматически ищем, где лежит app.go или main.go внутри папки сервиса
|
||||
MAIN_PATH=$(find . -maxdepth 3 \( -name "app.go" -o -name "main.go" \) -print -quit)
|
||||
|
||||
if [ -n "$MAIN_PATH" ]; then
|
||||
# Получаем имя файла (например, app.go) и директорию, где он лежит
|
||||
FILE_NAME=$(basename "$MAIN_PATH")
|
||||
MAIN_DIR=$(dirname "$MAIN_PATH")
|
||||
log_info "Found entry point '$FILE_NAME' inside '$MAIN_DIR'. Generating Swagger..."
|
||||
|
||||
cd "$MAIN_DIR"
|
||||
|
||||
# Явно передаем имя файла через -g, так как оно отличается от main.go
|
||||
swag init -g "$FILE_NAME" --parseDependency --parseInternal
|
||||
|
||||
# Если мы генерировали в подпапке, переносим папку docs в корень сервиса
|
||||
if [ "$MAIN_DIR" != "." ] && [ -d "./docs" ]; then
|
||||
rm -rf "$SERVICE_PATH/docs"
|
||||
mv ./docs "$SERVICE_PATH/docs"
|
||||
log_success "Swagger documentation moved to service root"
|
||||
fi
|
||||
|
||||
# 🔧 ИСПРАВЛЕНИЕ: Отдаем права пользователю rom4ik, чтобы GitHub Actions не падал!
|
||||
chown -R rom4ik:rom4ik "$SERVICE_PATH/docs"
|
||||
|
||||
cd "$SERVICE_PATH"
|
||||
else
|
||||
log_error "Neither app.go nor main.go found inside $SERVICE_PATH"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
log_success "Swagger documentation generated successfully"
|
||||
cd "$THIS_PATH"
|
||||
echo ""
|
||||
fi
|
||||
|
|
@ -170,93 +192,112 @@ echo ""
|
|||
log_info "Building $SERVICE_NAME..."
|
||||
cd "$SERVICE_PATH"
|
||||
|
||||
BUILD_TARGET="."
|
||||
if [ -d "./cmd" ]; then
|
||||
log_info "Found 'cmd' directory, building from ./cmd"
|
||||
BUILD_TARGET="./cmd"
|
||||
fi
|
||||
|
||||
gofmt -w .
|
||||
go vet ./...
|
||||
|
||||
# Сборка с оптимизациями (убираем отладочную информацию)
|
||||
go build -ldflags="-s -w" -o "$BINARY_PATH" .
|
||||
|
||||
go build -ldflags="-s -w" -o "$BINARY_PATH" "$BUILD_TARGET"
|
||||
log_success "Binary deployed to $BINARY_PATH"
|
||||
|
||||
BINARY_SIZE=$(du -h "$BINARY_PATH" | cut -f1)
|
||||
log_info "Binary size: $BINARY_SIZE"
|
||||
echo ""
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
# Управление сервисом в зависимости от типа
|
||||
# Управление сервисом
|
||||
# ═══════════════════════════════════════════════════════════════
|
||||
if [ "$SERVICE_KIND" = "daemon" ]; then
|
||||
# ─── Долгоживущий сервис: перезапускаем ───
|
||||
if systemctl is-active --quiet "$SERVICE_NAME"; then
|
||||
log_info "Restarting systemd service..."
|
||||
sudo systemctl restart "$SERVICE_NAME"
|
||||
sleep 2
|
||||
if [ ! -f "/etc/systemd/system/$SERVICE_NAME.service" ]; then
|
||||
log_warning "Systemd unit not found: /etc/systemd/system/$SERVICE_NAME.service"
|
||||
log_info "Creating systemd unit..."
|
||||
|
||||
if systemctl is-active --quiet "$SERVICE_NAME"; then
|
||||
log_success "Service restarted successfully"
|
||||
SERVICE_STATUS=$(systemctl is-active "$SERVICE_NAME")
|
||||
log_info "Status: $SERVICE_STATUS"
|
||||
else
|
||||
log_error "Service failed to restart"
|
||||
log_info "Check logs: sudo journalctl -u $SERVICE_NAME -n 50"
|
||||
exit 1
|
||||
fi
|
||||
tee /etc/systemd/system/$SERVICE_NAME.service > /dev/null <<EOF
|
||||
[Unit]
|
||||
Description=$DESCRIPTION
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=root
|
||||
WorkingDirectory=/workspace/ruspet_portal_back
|
||||
ExecStart=$BINARY_PATH
|
||||
Restart=always
|
||||
RestartSec=10
|
||||
StandardOutput=journal
|
||||
StandardError=journal
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
EOF
|
||||
|
||||
systemctl daemon-reload
|
||||
systemctl enable "$SERVICE_NAME"
|
||||
log_success "Systemd unit created and enabled"
|
||||
fi
|
||||
|
||||
log_info "Restarting systemd service..."
|
||||
systemctl restart "$SERVICE_NAME"
|
||||
sleep 3
|
||||
|
||||
if systemctl is-active --quiet "$SERVICE_NAME"; then
|
||||
log_success "Service is running"
|
||||
SERVICE_STATUS=$(systemctl is-active "$SERVICE_NAME")
|
||||
log_info "Status: $SERVICE_STATUS"
|
||||
else
|
||||
log_warning "Service not running"
|
||||
log_info "Start with: sudo systemctl start $SERVICE_NAME"
|
||||
log_info "Enable on boot: sudo systemctl enable $SERVICE_NAME"
|
||||
log_error "Service failed to start"
|
||||
log_info "Check logs: sudo journalctl -u $SERVICE_NAME -n 50"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
elif [ "$SERVICE_KIND" = "oneshot" ]; then
|
||||
# ─── Одноразовый сервис (миграции): запускаем и ждём ───
|
||||
if [ ! -f "/etc/systemd/system/$SERVICE_NAME.service" ]; 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
|
||||
[Unit]
|
||||
Description=$DESCRIPTION
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
User=root
|
||||
WorkingDirectory=/workspace/ruspet_portal_back
|
||||
ExecStart=$BINARY_PATH
|
||||
StandardOutput=journal
|
||||
StandardError=journal
|
||||
RemainAfterExit=yes
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
EOF
|
||||
|
||||
systemctl daemon-reload
|
||||
log_success "Systemd unit created"
|
||||
fi
|
||||
|
||||
log_info "Running migrations..."
|
||||
|
||||
# Запускаем сервис
|
||||
sudo systemctl start "$SERVICE_NAME"
|
||||
# Сбрасываем старые состояния юнита
|
||||
systemctl reset-failed "$SERVICE_NAME" || true
|
||||
|
||||
# Ждём завершения (максимум 5 минут)
|
||||
TIMEOUT=300
|
||||
ELAPSED=0
|
||||
|
||||
while systemctl is-active --quiet "$SERVICE_NAME"; do
|
||||
sleep 2
|
||||
ELAPSED=$((ELAPSED + 2))
|
||||
|
||||
if [ $ELAPSED -ge $TIMEOUT ]; then
|
||||
log_error "Migrations timed out after ${TIMEOUT}s"
|
||||
sudo journalctl -u "$SERVICE_NAME" -n 50 --no-pager
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Показываем прогресс
|
||||
printf "."
|
||||
done
|
||||
echo ""
|
||||
|
||||
# Проверяем статус завершения
|
||||
RESULT=$(systemctl show "$SERVICE_NAME" --property=ExecMainStatus --value)
|
||||
|
||||
if [ "$RESULT" = "0" ]; then
|
||||
log_success "Migrations completed successfully"
|
||||
# Показываем последние строки лога
|
||||
log_info "Migration log:"
|
||||
sudo journalctl -u "$SERVICE_NAME" -n 20 --no-pager
|
||||
# Запускаем и ждем завершения (так как Type=oneshot, команда block вернет код выхода программы)
|
||||
if systemctl start "$SERVICE_NAME"; then
|
||||
log_success "Migrations completed successfully!"
|
||||
else
|
||||
log_error "Migrations failed with exit code: $RESULT"
|
||||
sudo journalctl -u "$SERVICE_NAME" -n 50 --no-pager
|
||||
log_error "Migrations failed!"
|
||||
journalctl -u "$SERVICE_NAME" -n 50 --no-pager
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "════════════════════════════════════════"
|
||||
log_success "Deployment of $SERVICE_NAME completed!"
|
||||
echo "════════════════════════════════════════"
|
||||
|
||||
# Дополнительная информация для админки
|
||||
if [ "$SERVICE_TYPE" = "admin" ]; then
|
||||
echo ""
|
||||
log_info "Admin panel info:"
|
||||
echo " - Swagger UI: http://localhost:<PORT>/swagger/index.html"
|
||||
echo " - API docs: http://localhost:<PORT>/swagger/doc.json"
|
||||
echo " - Swagger UI: https://api.ruspet.tw1.ru/swagger/index.html"
|
||||
fi
|
||||
1
go.work
1
go.work
|
|
@ -6,4 +6,5 @@ use (
|
|||
service/telegram_service
|
||||
service/system_service
|
||||
service/rest_admin_service
|
||||
service/rest_telephony_service
|
||||
)
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue