Added telephony service, updated deploy.yml && deploy.sh, updated nginx for new service. Added DB flow for SMS && Calls #112

Merged
romanskijdev merged 1 commits from fix-permissions into main 2026-08-12 12:00:15 +03:00
18 changed files with 54543 additions and 159 deletions

View File

@ -6,7 +6,6 @@ on:
env:
REPO_DIR: "/workspace/ruspet_portal_back"
# Встраиваем токен авторизации прямо в URL
REPO_URL: "https://${{ github.actor }}:${{ github.token }}@72.56.235.246.nip.io/gitea/romanskijdev/ruspet_portal_back.git"
BACKUP_DIR: "/tmp/deploy_backups"
@ -14,6 +13,7 @@ env:
BALANCER_SERVICE: "rest_balancer_service"
ADMIN_SERVICE: "rest_admin_service"
MIGRATIONS_SERVICE: "system_service"
TELEPHONY_SERVICE: "rest_telephony_service" # 🆕 Добавлен сервис телефонии
jobs:
deploy:
@ -38,12 +38,6 @@ jobs:
echo "User: $(whoami)"
echo "════════════════════════════════════════"
# ═══════════════════════════════════════════════════════════════
# ШАГ 2: Checkout
# ═══════════════════════════════════════════════════════════════
# ═══════════════════════════════════════════════════════════════
# ШАГ 2: Checkout
# ═══════════════════════════════════════════════════════════════
# ═══════════════════════════════════════════════════════════════
# ШАГ 2: Checkout
# ═══════════════════════════════════════════════════════════════
@ -52,19 +46,18 @@ jobs:
run: |
mkdir -p "$BACKUP_DIR"
chown -R $(whoami):$(whoami) "$REPO_DIR/service/rest_admin_service/docs" || true
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"
# ОБНОВЛЯЕМ URL С НОВЫМ ТОКЕНОМ
git remote set-url origin "$REPO_URL"
OLD_COMMIT=$(git rev-parse HEAD)
@ -80,6 +73,7 @@ jobs:
DEPLOY_TELEGRAM=true
DEPLOY_BALANCER=true
DEPLOY_ADMIN=true
DEPLOY_TELEPHONY=true
else
echo "📝 Changed files:"
echo "$CHANGED_FILES" | sed 's/^/ /'
@ -91,6 +85,7 @@ jobs:
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"
@ -108,6 +103,11 @@ jobs:
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
@ -121,6 +121,7 @@ jobs:
DEPLOY_TELEGRAM=true
DEPLOY_BALANCER=true
DEPLOY_ADMIN=true
DEPLOY_TELEPHONY=true
fi
{
@ -128,6 +129,7 @@ jobs:
echo "DEPLOY_TELEGRAM=$DEPLOY_TELEGRAM"
echo "DEPLOY_BALANCER=$DEPLOY_BALANCER"
echo "DEPLOY_ADMIN=$DEPLOY_ADMIN"
echo "DEPLOY_TELEPHONY=$DEPLOY_TELEPHONY" # 🆕 Проброс в ENV
} >> $GITHUB_ENV
echo ""
@ -136,6 +138,7 @@ jobs:
echo " 🤖 Telegram: $DEPLOY_TELEGRAM"
echo " ⚖️ Balancer: $DEPLOY_BALANCER"
echo " 🔧 Admin: $DEPLOY_ADMIN"
echo " 📞 Telephony: $DEPLOY_TELEPHONY"
# ═══════════════════════════════════════════════════════════════
# ШАГ 3: Проверка плана
@ -146,7 +149,8 @@ jobs:
if [ "$DEPLOY_MIGRATIONS" = "false" ] && \
[ "$DEPLOY_TELEGRAM" = "false" ] && \
[ "$DEPLOY_BALANCER" = "false" ] && \
[ "$DEPLOY_ADMIN" = "false" ]; then
[ "$DEPLOY_ADMIN" = "false" ] && \
[ "$DEPLOY_TELEPHONY" = "false" ]; then # 🆕
echo "⏭️ No services need to be deployed — skipping"
echo "SKIP_DEPLOY=true" >> $GITHUB_ENV
else
@ -168,7 +172,7 @@ jobs:
echo "✅ Config injected"
# ═══════════════════════════════════════════════════════════════
# ШАГ 5: Создание backup-ов (безопасное)
# ШАГ 5: Создание backup-ов
# ═══════════════════════════════════════════════════════════════
- name: 💾 Create Backups
if: env.SKIP_DEPLOY == 'false'
@ -191,19 +195,11 @@ jobs:
fi
}
if [ "$DEPLOY_TELEGRAM" = "true" ]; then
create_backup "$TELEGRAM_SERVICE"
fi
if [ "$DEPLOY_TELEGRAM" = "true" ]; then create_backup "$TELEGRAM_SERVICE"; fi
if [ "$DEPLOY_BALANCER" = "true" ]; then create_backup "$BALANCER_SERVICE"; fi
if [ "$DEPLOY_ADMIN" = "true" ]; then create_backup "$ADMIN_SERVICE"; fi
if [ "$DEPLOY_TELEPHONY" = "true" ]; then create_backup "$TELEPHONY_SERVICE"; fi # 🆕
if [ "$DEPLOY_BALANCER" = "true" ]; then
create_backup "$BALANCER_SERVICE"
fi
if [ "$DEPLOY_ADMIN" = "true" ]; then
create_backup "$ADMIN_SERVICE"
fi
# Очистка старых backup-ов (оставляем последние 10)
echo "🧹 Cleaning old backups..."
ls -t "$BACKUP_DIR"/* 2>/dev/null | tail -n +11 | xargs -r rm -- || true
echo "✅ Backups ready"
@ -225,83 +221,71 @@ jobs:
exit 1
fi
# ═══════════════════════════════════════════════════════════════
# ШАГ 7: Деплой Telegram бота
# ═══════════════════════════════════════════════════════════════
# (ШАГИ 7, 8, 9 - Telegram, Balancer, Admin остаются без изменений)
- name: 🤖 Deploy Telegram Bot
if: env.DEPLOY_TELEGRAM == 'true' && env.SKIP_DEPLOY == 'false'
id: deploy_telegram
run: |
echo "🤖 Deploying Telegram bot..."
if sudo /usr/bin/bash "$REPO_DIR/deploy.sh" telegram; then
echo "✅ Telegram bot deployed"
echo "TELEGRAM_DEPLOYED=true" >> $GITHUB_ENV
sleep 3
if sudo /usr/bin/systemctl is-active --quiet "$TELEGRAM_SERVICE"; then
echo "✅ Telegram bot is running"
else
echo "❌ Telegram bot failed to start"
sudo /usr/bin/journalctl -u "$TELEGRAM_SERVICE" -n 30 --no-pager
if ! sudo /usr/bin/systemctl is-active --quiet "$TELEGRAM_SERVICE"; then
exit 1
fi
else
echo "❌ Telegram bot deployment failed"
echo "TELEGRAM_DEPLOYED=false" >> $GITHUB_ENV
exit 1
fi
# ═══════════════════════════════════════════════════════════════
# ШАГ 8: Деплой балансировщика
# ═══════════════════════════════════════════════════════════════
- name: ⚖️ Deploy Balancer Service
if: env.DEPLOY_BALANCER == 'true' && env.SKIP_DEPLOY == 'false' && false
id: deploy_balancer
run: |
echo "⚖️ Deploying balancer service..."
if sudo /usr/bin/bash "$REPO_DIR/deploy.sh" balancer; then
echo "✅ Balancer service deployed"
echo "BALANCER_DEPLOYED=true" >> $GITHUB_ENV
sleep 3
if sudo /usr/bin/systemctl is-active --quiet "$BALANCER_SERVICE"; then
echo "✅ Balancer service is running"
else
echo "❌ Balancer service failed to start"
sudo /usr/bin/journalctl -u "$BALANCER_SERVICE" -n 30 --no-pager
if ! sudo /usr/bin/systemctl is-active --quiet "$BALANCER_SERVICE"; then
exit 1
fi
else
echo "❌ Admin deployment failed"
echo "BALANCER_DEPLOYED=false" >> $GITHUB_ENV
exit 1
fi
# ═══════════════════════════════════════════════════════════════
# ШАГ 9: Деплой админки
# ═══════════════════════════════════════════════════════════════
- name: 🔧 Deploy Admin Service
if: env.DEPLOY_ADMIN == 'true' && env.SKIP_DEPLOY == 'false'
id: deploy_admin
run: |
echo "🔧 Deploying admin service..."
if sudo /usr/bin/bash "$REPO_DIR/deploy.sh" admin swagger; then
echo "✅ Admin service deployed with Swagger"
echo "ADMIN_DEPLOYED=true" >> $GITHUB_ENV
sleep 3
if sudo /usr/bin/systemctl is-active --quiet "$ADMIN_SERVICE"; then
echo "✅ Admin service is running"
else
echo "❌ Admin service failed to start"
sudo /usr/bin/journalctl -u "$ADMIN_SERVICE" -n 30 --no-pager
if ! sudo /usr/bin/systemctl is-active --quiet "$ADMIN_SERVICE"; then
exit 1
fi
if [ -f "$REPO_DIR/service/rest_admin_service/docs/swagger.json" ]; then
echo "✅ Swagger documentation generated"
else
exit 1
fi
# ═══════════════════════════════════════════════════════════════
# ШАГ 9.5: Деплой телефонии (НОВЫЙ)
# ═══════════════════════════════════════════════════════════════
- 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 "❌ Admin deployment failed"
echo "ADMIN_DEPLOYED=false" >> $GITHUB_ENV
echo "❌ Telephony deployment failed"
echo "TELEPHONY_DEPLOYED=false" >> $GITHUB_ENV
exit 1
fi
@ -326,28 +310,15 @@ jobs:
sudo chmod +x "/usr/local/bin/$service"
sudo systemctl restart "$service"
sleep 2
if sudo systemctl is-active --quiet "$service"; then
echo "✅ $service rolled back successfully"
else
echo "❌ $service rollback failed"
fi
else
echo "⚠️ No backup available for $service"
fi
}
if [ "$DEPLOY_TELEGRAM" = "true" ]; then
rollback_service "$TELEGRAM_SERVICE"
fi
if [ "$DEPLOY_BALANCER" = "true" ]; then
rollback_service "$BALANCER_SERVICE"
fi
if [ "$DEPLOY_ADMIN" = "true" ]; then
rollback_service "$ADMIN_SERVICE"
fi
if [ "$DEPLOY_TELEGRAM" = "true" ]; then rollback_service "$TELEGRAM_SERVICE"; fi
if [ "$DEPLOY_BALANCER" = "true" ]; then rollback_service "$BALANCER_SERVICE"; fi
if [ "$DEPLOY_ADMIN" = "true" ]; then rollback_service "$ADMIN_SERVICE"; fi
if [ "$DEPLOY_TELEPHONY" = "true" ]; then rollback_service "$TELEPHONY_SERVICE"; fi # 🆕
echo "✅ Rollback completed"
@ -358,36 +329,27 @@ jobs:
if: env.SKIP_DEPLOY == 'false' && success()
run: |
echo "🔍 Verifying services..."
ALL_OK=true
verify_service() {
local service=$1
local should_deploy=$2
if [ "$should_deploy" = "true" ]; then
if sudo systemctl is-active --quiet "$service"; then
UPTIME=$(systemctl show "$service" --property=ActiveEnterTimestamp --value)
echo "✅ $service: running (since $UPTIME)"
echo "✅ $service: running"
else
echo "❌ $service: NOT RUNNING"
ALL_OK=false
fi
else
echo "⏭️ $service: skipped"
fi
}
verify_service "$TELEGRAM_SERVICE" "$DEPLOY_TELEGRAM"
verify_service "$BALANCER_SERVICE" "$DEPLOY_BALANCER"
verify_service "$ADMIN_SERVICE" "$DEPLOY_ADMIN"
verify_service "$TELEPHONY_SERVICE" "$DEPLOY_TELEPHONY" # 🆕
if [ "$ALL_OK" = "true" ]; then
echo "✅ All services verified successfully"
else
echo "❌ Some services are not running"
exit 1
fi
if [ "$ALL_OK" != "true" ]; then exit 1; fi
# ═══════════════════════════════════════════════════════════════
# ШАГ 12: Уведомление об успехе
@ -395,33 +357,21 @@ jobs:
- name: 📢 Notify Success
if: success()
run: |
echo "✅ Deployment completed successfully!"
if [ -n "${{ secrets.TELEGRAM_BOT_TOKEN }}" ] && [ -n "${{ secrets.TELEGRAM_CHAT_ID }}" ]; then
MESSAGE="✅ <b>Deployment successful</b>%0A%0A"
MESSAGE+="🌿 Branch: <code>${{ github.ref_name }}</code>%0A"
MESSAGE+="📝 Commit: <code>${{ github.sha }}</code>%0A"
MESSAGE+="👤 Author: ${{ github.actor }}%0A%0A"
if [ "$DEPLOY_MIGRATIONS" = "true" ]; then
MESSAGE+="🗄️ 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+="🗄️ 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_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
# ═══════════════════════════════════════════════════════════════
@ -430,26 +380,17 @@ jobs:
- name: 🚨 Notify Failure
if: failure()
run: |
echo "❌ Deployment failed!"
for service in "$TELEGRAM_SERVICE" "$BALANCER_SERVICE" "$ADMIN_SERVICE"; do
echo ""
echo "📜 $service logs (last 20 lines):"
for service in "$TELEGRAM_SERVICE" "$BALANCER_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
# ═══════════════════════════════════════════════════════════════
@ -461,14 +402,9 @@ jobs:
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 "Telephony: ${DEPLOY_TELEPHONY:-false}" # 🆕
echo "════════════════════════════════════════"

View File

@ -40,6 +40,7 @@ type ModuleDB struct {
ApprovalRevocation *dbcore.ApprovalRevocationDB
ApprovalFlowNode *dbcore.ApprovalFlowNodeDB
AdminActionLogs *dbcore.AdminActionLogDB
SMSLog *dbcore.SmsLogDB
}
func NewModuleDB(
@ -96,6 +97,7 @@ func initDBModules(modules *ModuleDB, redisClient *redismodule.ModuleRedis) *Mod
modules.ApprovalRevocation = dbcore.NewApprovalRevocationDB(modules.Pool)
modules.ApprovalFlowNode = dbcore.NewApprovalFlowNodeDB(modules.Pool)
modules.AdminActionLogs = dbcore.NewAdminActionLogDB(modules.Pool)
modules.SMSLog = dbcore.NewSmsLogDB(modules.Pool)
return modules
}

View File

@ -45,6 +45,8 @@ func (m *MigrationFunctions) migrateTables() error {
tablesmigration.ApprovalRevocationTablesMigrate,
tablesmigration.ApprovalFlowNodesTableMigrate,
tablesmigration.AdminActionLogsTableMigrate,
tablesmigration.SmsLogsTableMigrate,
}
for _, migrate := range migrations {

View File

@ -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
}

View File

@ -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
}

View File

@ -0,0 +1,55 @@
package typescore
import "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"`
EventPbxCallID string `json:"event_pbx_call_id"`
SrcNumber string `json:"src_number"`
SrcID string `json:"src_id"`
SrcSlot int `json:"src_slot"`
// Поля, которые приходят только в событии окончания звонка (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"` // Ссылка на запись разговора
DBCallID string `json:"db_call_id,omitempty"`
// Поле, которое приходит только для SMS (event_type == 32)
Text string `json:"text,omitempty"`
}

View File

@ -34,14 +34,14 @@ GENERATE_SWAGGER="${2:-false}"
validate_service_type() {
case "$1" in
bot|telegram|balancer|admin|migrations|all) return 0 ;;
bot|telegram|balancer|admin|migrations|telephony|all) return 0 ;; # 🆕 Добавлен telephony
*) return 1 ;;
esac
}
if ! validate_service_type "$SERVICE_TYPE"; then
log_error "Unknown service type: $SERVICE_TYPE"
echo "Usage: $0 [telegram|balancer|admin|migrations|all] [swagger]"
echo "Usage: $0 [telegram|balancer|admin|migrations|telephony|all] [swagger]"
exit 1
fi
@ -54,20 +54,25 @@ if [ "$SERVICE_TYPE" = "all" ]; then
SELF="$THIS_PATH/deploy.sh"
log_service "Step 1/4: Database migrations"
log_service "Step 1/5: Database migrations"
bash "$SELF" migrations
echo ""
log_service "Step 2/4: Telegram bot"
log_service "Step 2/5: Telegram bot"
bash "$SELF" telegram
echo ""
# log_service "Step 3/4: REST balancer"
# log_service "Step 3/5: REST balancer"
# bash "$SELF" balancer
# echo ""
log_service "Step 4/4: REST admin"
log_service "Step 4/5: REST admin"
bash "$SELF" admin "$GENERATE_SWAGGER"
echo ""
log_service "Step 5/5: REST telephony" # 🆕 Добавлен шаг деплоя телефонии
bash "$SELF" telephony
echo ""
echo ""
log_success "All services deployed successfully!"
@ -96,6 +101,11 @@ case "$SERVICE_TYPE" in
migrations)
SERVICE_NAME="system_service"
DESCRIPTION="Database Migrations"
SERVICE_KIND="oneshot" # 🔧 ИСПРАВЛЕНИЕ: здесь раньше ошибочно стояло "daemon"
;;
telephony) # 🆕 Конфигурация для нового сервиса
SERVICE_NAME="rest_telephony_service"
DESCRIPTION="REST Telephony Service"
SERVICE_KIND="daemon"
;;
esac
@ -142,7 +152,7 @@ if [ "$SERVICE_TYPE" = "admin" ] && [ "$GENERATE_SWAGGER" = "swagger" ]; then
cd "$MAIN_DIR"
# Исправлено: Явно передаем имя файла через -g, так как оно отличается от main.go
# Явно передаем имя файла через -g, так как оно отличается от main.go
swag init -g "$FILE_NAME" --parseDependency --parseInternal
# Если мы генерировали в подпапке, переносим папку docs в корень сервиса
@ -151,7 +161,9 @@ if [ "$SERVICE_TYPE" = "admin" ] && [ "$GENERATE_SWAGGER" = "swagger" ]; then
mv ./docs "$SERVICE_PATH/docs"
log_success "Swagger documentation moved to service root"
fi
sudo chown -R git:git "$SERVICE_PATH/docs"
# 🔧 ИСПРАВЛЕНИЕ: Отдаем права пользователю rom4ik, чтобы GitHub Actions не падал!
chown -R rom4ik:rom4ik "$SERVICE_PATH/docs"
cd "$SERVICE_PATH"
else
@ -200,7 +212,7 @@ if [ "$SERVICE_KIND" = "daemon" ]; then
log_warning "Systemd unit not found: /etc/systemd/system/$SERVICE_NAME.service"
log_info "Creating systemd unit..."
sudo tee /etc/systemd/system/$SERVICE_NAME.service > /dev/null <<EOF
tee /etc/systemd/system/$SERVICE_NAME.service > /dev/null <<EOF
[Unit]
Description=$DESCRIPTION
After=network.target
@ -219,18 +231,18 @@ StandardError=journal
WantedBy=multi-user.target
EOF
sudo systemctl daemon-reload
sudo systemctl enable "$SERVICE_NAME"
systemctl daemon-reload
systemctl enable "$SERVICE_NAME"
log_success "Systemd unit created and enabled"
fi
log_info "Restarting systemd service..."
sudo systemctl restart "$SERVICE_NAME"
systemctl restart "$SERVICE_NAME"
sleep 3
if sudo systemctl is-active --quiet "$SERVICE_NAME"; then
if systemctl is-active --quiet "$SERVICE_NAME"; then
log_success "Service is running"
SERVICE_STATUS=$(sudo systemctl is-active "$SERVICE_NAME")
SERVICE_STATUS=$(systemctl is-active "$SERVICE_NAME")
log_info "Status: $SERVICE_STATUS"
else
log_error "Service failed to start"
@ -243,7 +255,7 @@ elif [ "$SERVICE_KIND" = "oneshot" ]; then
log_warning "Systemd unit not found: /etc/systemd/system/$SERVICE_NAME.service"
log_info "Creating systemd unit for migrations..."
sudo tee /etc/systemd/system/$SERVICE_NAME.service > /dev/null <<EOF
tee /etc/systemd/system/$SERVICE_NAME.service > /dev/null <<EOF
[Unit]
Description=$DESCRIPTION
After=network.target
@ -261,36 +273,31 @@ RemainAfterExit=no
WantedBy=multi-user.target
EOF
sudo systemctl daemon-reload
systemctl daemon-reload
log_success "Systemd unit created"
fi
log_info "Running migrations..."
# Исправлено: Запуск в неблокирующем режиме для systemd, управление возвращается в скрипт мгновенно
sudo systemctl start "$SERVICE_NAME" --no-block
systemctl start "$SERVICE_NAME" --no-block
TIMEOUT=300
ELAPSED=0
log_info "Waiting for migrations to complete successfully..."
while true; do
# Анализируем логи на успешное окончание
if sudo journalctl -u "$SERVICE_NAME" --since "2 minutes ago" --no-pager | grep -q "Database migration completed successfully"; then
if journalctl -u "$SERVICE_NAME" --since "2 minutes ago" --no-pager | grep -q "Database migration completed successfully"; then
echo ""
log_success "Migrations completed successfully (detected via logs)!"
# Принудительно гасим юнит, если процесс "завис" в памяти после выполнения логики
sudo systemctl stop "$SERVICE_NAME" --quiet || true
systemctl stop "$SERVICE_NAME" --quiet || true
break
fi
# Исправлено: Добавлен sudo для проверки стейта
if sudo systemctl show "$SERVICE_NAME" --property=ActiveState --value | grep -q "failed"; then
if systemctl show "$SERVICE_NAME" --property=ActiveState --value | grep -q "failed"; then
echo ""
RESULT=$(sudo systemctl show "$SERVICE_NAME" --property=ExecMainStatus --value)
RESULT=$(systemctl show "$SERVICE_NAME" --property=ExecMainStatus --value)
log_error "Migrations failed with exit code: $RESULT"
sudo journalctl -u "$SERVICE_NAME" -n 50 --no-pager
journalctl -u "$SERVICE_NAME" -n 50 --no-pager
exit 1
fi
@ -301,7 +308,7 @@ EOF
if [ $ELAPSED -ge $TIMEOUT ]; then
echo ""
log_error "Migrations timed out after ${TIMEOUT}s"
sudo journalctl -u "$SERVICE_NAME" -n 50 --no-pager
journalctl -u "$SERVICE_NAME" -n 50 --no-pager
exit 1
fi
done

View File

@ -6,4 +6,5 @@ use (
service/telegram_service
service/system_service
service/rest_admin_service
service/rest_telephony_service
)

View File

@ -8,6 +8,7 @@ github.com/PuerkitoBio/purell v1.1.1 h1:WEQqlqaGbrPkxLJWfBwQmfEAE1Z7ONdDLqrN38tN
github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0=
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 h1:d+Bc7a5rLufV/sSk/8dngufqelfh6jnri85riMAaF/M=
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE=
github.com/andybalholm/brotli v1.0.5/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=
github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310 h1:BUAU3CGlLvorLI26FmByPp2eC2qla6E1Tw+scpcg/to=
github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8=
github.com/bgentry/speakeasy v0.1.0 h1:ByYyxL9InA1OWqxJqqp2A5pYHUrCiAL6K3J+LKSsQkY=
@ -24,14 +25,17 @@ github.com/go-openapi/swag/mangling v0.26.1 h1:gpYI4WuPKFJJVjV5cDLGlDVJhFIxYjQc7
github.com/go-openapi/swag/mangling v0.26.1/go.mod h1:POETDH01hqAdASXfw7ISEd9bCOE6xBHOt8NHmGZRmYM=
github.com/go-openapi/swag/netutils v0.26.1 h1:BNctoc39WTAUMxyAs355fExOPzMZtPbZ0ZZ1Am2FR5M=
github.com/go-openapi/swag/netutils v0.26.1/go.mod h1:y02vByhZhQPAVwOX+0KipXFZ/hUbk6G/Enhf5rGaOkQ=
github.com/gofiber/fiber/v2 v2.52.0/go.mod h1:KEOE+cXMhXG0zHc9d8+E38hoX+ZN7bhOtgeF2oT6jrQ=
github.com/huandu/xstrings v1.3.2 h1:L18LIDzqlW6xN2rEkpdV8+oL/IXWJ1APd+vsdYy4Wdw=
github.com/huandu/xstrings v1.3.2/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE=
github.com/imdario/mergo v0.3.11 h1:3tnifQM4i+fbajXKBHXWEH+KvNHqojZ778UH75j3bGA=
github.com/imdario/mergo v0.3.11/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA=
github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
github.com/klauspost/compress v1.17.0/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE=
github.com/mailru/easyjson v0.7.6 h1:8yTIVnZgCoiM1TgqoeTl+LfU5Jg6/xL3QhGQnimLYnA=
github.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/mitchellh/cli v1.1.5 h1:OxRIeJXpAMztws/XHlN2vu6imG5Dpq+j61AzAX5fLng=
@ -44,19 +48,27 @@ github.com/mitchellh/reflectwalk v1.0.0 h1:9D+8oIskB4VJBN5SFlmc27fSlIBZaov1Wpk/I
github.com/mitchellh/reflectwalk v1.0.0/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=
github.com/natefinch/atomic v1.0.1 h1:ZPYKxkqQOx3KZ+RsbnP/YsgvxWQPGxjC0oBt2AhwV0A=
github.com/natefinch/atomic v1.0.1/go.mod h1:N/D/ELrljoqDyT3rZrsUmtsuzvHkeB/wWjHV22AZRbM=
github.com/philhofer/fwd v1.1.2/go.mod h1:qkPdfjR2SIEbspLqpe1tO4n5yICnr2DY7mqEx2tUTP0=
github.com/posener/complete v1.1.1 h1:ccV59UEOTzVDnDUEFdT95ZzHVZ+5+158q8+SJb2QV5w=
github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/russross/blackfriday/v2 v2.0.1 h1:lPqVAte+HuHNfhJ/0LC98ESWRz8afy9tM/0RK8m9o+Q=
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/ryanuber/columnize v2.1.2+incompatible h1:C89EOx/XBWwIXl8wm8OPJBd7kPF25UfsK2X7Ph/zCAk=
github.com/ryanuber/columnize v2.1.2+incompatible/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts=
github.com/shurcooL/sanitized_anchor_name v1.0.0 h1:PdmoCO6wvbs+7yrJyMORt4/BmY5IYyJwS/kOiWx8mHo=
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/spf13/cast v1.3.1 h1:nFm6S0SMdyzrzcmThSipiEubIDy8WEXKNZ0UOgiRpng=
github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
github.com/stretchr/objx v0.1.0 h1:4G4v2dO3VZwixGIRoQ5Lfboy6nUhCyYzaqnIAPPhYs4=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/tinylib/msgp v1.1.8/go.mod h1:qkpG+2ldGg4xRFmx+jfTvZPxfGFhi64BcnL9vkCm/Tw=
github.com/urfave/cli/v2 v2.3.0 h1:qph92Y649prgesehzOrQjdWyxFOp/QVM+6imKHad91M=
github.com/urfave/cli/v2 v2.3.0/go.mod h1:LJmUH05zAU44vOAcrfzZQKsZbVcdbOG8rtL3/XcUArI=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasthttp v1.51.0/go.mod h1:oI2XroL+lI7vdXyYoQk03bXBThfFl2cVdIA3Xl7cH8g=
github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc=
github.com/yuin/goldmark v1.4.13 h1:fVcFKWvrslecOb/tg+Cc05dkeYx540o0FuFt3nUVDoE=
golang.org/x/crypto v0.41.0 h1:WKYxWedPGCTVVl5+WHSSrOBT0O8lx32+zxmHxijgXp4=
golang.org/x/crypto v0.41.0/go.mod h1:pO5AFd7FA68rFak7rOAGVuygIISepHftHnr8dr6+sUc=
@ -72,6 +84,8 @@ golang.org/x/net v0.43.0/go.mod h1:vhO1fvI4dGsIjh73sWfUVjj3N7CA9WkKJNQm2svM6Jg=
golang.org/x/net v0.49.0/go.mod h1:/ysNB2EvaqvesRkuLAyjI1ycPZlQHM3q01F02UY/MV8=
golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww=
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/telemetry v0.0.0-20250807160809-1a19826ec488 h1:3doPGa+Gg4snce233aCWnbZVFsyFMo/dR40KK/6skyE=
golang.org/x/telemetry v0.0.0-20250807160809-1a19826ec488/go.mod h1:fGb/2+tgXXjhjHsTNdVEEMZNWA0quBnfrO+AfoDSAKw=

View File

@ -0,0 +1,151 @@
package main
import (
configcore "bitrix_balancer_api/core/config"
clientcontrollers "bitrix_balancer_api/core/lib/internally/client-controllers"
"errors"
"fmt"
"log"
"net/http"
"rest_telephony_service/handlers/telephony"
typesm "rest_telephony_service/types"
"time"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/cors"
"github.com/go-chi/httprate"
"github.com/sirupsen/logrus"
)
const (
readTimeout = 15 * time.Minute
writeTimeout = 15 * time.Minute
idleTimeout = 15 * time.Minute
rateLimit = 50
rateWindow = 1 * time.Second
)
func main() {
err := initService()
if err != nil {
logrus.Errorln("🔴 failed to init common: ", err)
}
select {} // блокируем завершение горутины
}
func initService() error {
clientsExternal, err := getClientsExternal()
if err != nil {
logrus.Errorln("🔴 failed to load config: ", err)
return err
}
ipc, err := initInternalProvider(clientsExternal)
if err != nil {
logrus.Errorln("🔴 failed to init internal provider: ", err)
return err
}
router, err := initBaseApiRouter(ipc)
if err != nil {
logrus.Errorln("🔴 failed to init base api router: ", err)
return err
}
if err := startRestApiServer(ipc, router); err != nil {
logrus.Errorln("🔴 failed to start server: ", err)
return err
}
return nil
}
func getClientsExternal() (clientcontrollers.ClientsExternal, error) {
options := &configcore.ConfigLoadOptions{
Redis: true,
Database: true,
Server: configcore.ExposedServiceOptions{
RESTBaseService: true, // Берем конфиг для портов из базы
},
}
return clientcontrollers.ReturnClientsExternal(options)
}
func initInternalProvider(clientsExternal clientcontrollers.ClientsExternal) (*typesm.InternalProviderControl, error) {
return &typesm.InternalProviderControl{
Config: clientsExternal.Config,
RedisClient: clientsExternal.Redis,
Database: clientsExternal.DB,
TGBotClient: clientsExternal.Telegram,
}, nil
}
func startRestApiServer(ipc *typesm.InternalProviderControl, router *chi.Mux) error {
// Допустим, телефония живет на порту 15002. В будущем вынесем в config.yml
serverPort := "15002"
serverAddr := ":" + serverPort
httpServer := &http.Server{
Addr: serverAddr,
Handler: router,
ReadTimeout: readTimeout,
WriteTimeout: writeTimeout,
IdleTimeout: idleTimeout,
}
log.Printf("✅ Starting Telephony server on %s", serverAddr)
return httpServer.ListenAndServe()
}
func initBaseApiRouter(ipc *typesm.InternalProviderControl) (*chi.Mux, error) {
router := chi.NewRouter()
corsOptions := cors.New(cors.Options{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{http.MethodGet, http.MethodPost, http.MethodOptions},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "ApiKey", "x-device-id"},
ExposedHeaders: []string{"Link", "Cache-Control"},
AllowCredentials: true,
MaxAge: 300,
})
router.Use(corsOptions.Handler)
router.Use(middleware.RealIP)
router.Use(middleware.Recoverer)
router.Use(httprate.LimitByIP(rateLimit, rateWindow))
if ipc.Database == nil {
return nil, errors.New("failed_to_connect_db")
}
err := registerRoutes(router, ipc)
if err != nil {
return nil, err
}
return router, nil
}
// регистрирует маршруты
func registerRoutes(router chi.Router, ipc *typesm.InternalProviderControl) error {
// Подключаем наши маршруты
if err := telephony.RegisterTelephonyRoutes(router, ipc); err != nil {
return errors.New(fmt.Sprintf("🔴 failed to register telephony routes: %v", err))
}
// Вывод зарегистрированных маршрутов
if err := printRoutes(router, ipc); err != nil {
return errors.New(fmt.Sprintf("🔴 failed to print routes: %v", err))
}
return nil
}
func printRoutes(r chi.Router, ipc *typesm.InternalProviderControl) error {
err := chi.Walk(r, func(method, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error {
logrus.Info(fmt.Sprintf("🩵 [ %s ] %s\n", method, route))
return nil
})
return err
}

View File

@ -0,0 +1,57 @@
module rest_telephony_service
go 1.25.6
require (
bitrix_balancer_api/core v0.0.0
github.com/go-chi/chi/v5 v5.3.1
github.com/go-chi/cors v1.2.2
github.com/go-chi/httprate v0.16.0
github.com/sirupsen/logrus v1.9.4
)
require (
github.com/Masterminds/squirrel v1.5.4 // indirect
github.com/cenkalti/backoff/v4 v4.3.0 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/go-jose/go-jose/v4 v4.1.1 // indirect
github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1 // indirect
github.com/hashicorp/errwrap v1.1.0 // indirect
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
github.com/hashicorp/go-multierror v1.1.1 // indirect
github.com/hashicorp/go-retryablehttp v0.7.8 // indirect
github.com/hashicorp/go-rootcerts v1.0.2 // indirect
github.com/hashicorp/go-secure-stdlib/parseutil v0.2.0 // indirect
github.com/hashicorp/go-secure-stdlib/strutil v0.1.2 // indirect
github.com/hashicorp/go-sockaddr v1.0.7 // indirect
github.com/hashicorp/hcl v1.0.1-vault-7 // indirect
github.com/hashicorp/vault/api v1.22.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/pgx/v5 v5.8.0 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/klauspost/cpuid/v2 v2.2.10 // indirect
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 // indirect
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 // indirect
github.com/mitchellh/go-homedir v1.1.0 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/redis/go-redis/v9 v9.18.0 // indirect
github.com/ryanuber/go-glob v1.0.0 // indirect
github.com/shopspring/decimal v1.4.0 // indirect
github.com/zeebo/xxh3 v1.0.2 // indirect
go.uber.org/atomic v1.11.0 // indirect
golang.org/x/crypto v0.40.0 // indirect
golang.org/x/net v0.42.0 // indirect
golang.org/x/sync v0.17.0 // indirect
golang.org/x/sys v0.41.0 // indirect
golang.org/x/text v0.29.0 // indirect
golang.org/x/time v0.12.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
gorm.io/driver/postgres v1.6.0 // indirect
gorm.io/gorm v1.31.1 // indirect
)
replace bitrix_balancer_api/core => ../../core

View File

@ -0,0 +1,128 @@
github.com/Masterminds/squirrel v1.5.4 h1:uUcX/aBc8O7Fg9kaISIUsHXdKuqehiXAMQTYX8afzqM=
github.com/Masterminds/squirrel v1.5.4/go.mod h1:NNaOrjSoIDfDA40n7sr2tPNZRfjzjA400rg+riTZj10=
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8=
github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM=
github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU=
github.com/go-chi/chi/v5 v5.3.1 h1:3j4HZLGZQ3JpMCrPJF/Jl3mYJfWLKBfNJ6quurUGCf8=
github.com/go-chi/chi/v5 v5.3.1/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto=
github.com/go-chi/cors v1.2.2 h1:Jmey33TE+b+rB7fT8MUy1u0I4L+NARQlK6LhzKPSyQE=
github.com/go-chi/cors v1.2.2/go.mod h1:sSbTewc+6wYHBBCW7ytsFSn836hqM7JxpglAy2Vzc58=
github.com/go-chi/httprate v0.16.0 h1:8V5DH9j6pSK6UQoBsTpvMyFxycqaKEIToyPKzHJjUa8=
github.com/go-chi/httprate v0.16.0/go.mod h1:A8lo+qRhk+s9LiuP5saS7XCGDXRXMcrueq0NfIuCa/I=
github.com/go-jose/go-jose/v4 v4.1.1 h1:JYhSgy4mXXzAdF3nUx3ygx347LRXJRrpgyU3adRmkAI=
github.com/go-jose/go-jose/v4 v4.1.1/go.mod h1:BdsZGqgdO3b6tTc6LSE56wcDbMMLuPsw5d4ZD5f94kA=
github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1 h1:wG8n/XJQ07TmjbITcGiUaOtXxdrINDz1b0J1w0SzqDc=
github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1/go.mod h1:A2S0CWkNylc2phvKXWBBdD3K0iGnDBGbzRpISP2zBl8=
github.com/go-test/deep v1.1.1 h1:0r/53hagsehfO4bzD2Pgr/+RgHqhmf+k1Bpse2cTu1U=
github.com/go-test/deep v1.1.1/go.mod h1:5C2ZWiW0ErCdrYzpqxLbTX7MG14M9iiw8DgHncVwcsE=
github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I=
github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ=
github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48=
github.com/hashicorp/go-hclog v1.6.3 h1:Qr2kF+eVWjTiYmU7Y31tYlP1h0q/X3Nl3tPGdaB11/k=
github.com/hashicorp/go-hclog v1.6.3/go.mod h1:W4Qnvbt70Wk/zYJryRzDRU/4r0kIg0PVHBcfoyhpF5M=
github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo=
github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM=
github.com/hashicorp/go-retryablehttp v0.7.8 h1:ylXZWnqa7Lhqpk0L1P1LzDtGcCR0rPVUrx/c8Unxc48=
github.com/hashicorp/go-retryablehttp v0.7.8/go.mod h1:rjiScheydd+CxvumBsIrFKlx3iS0jrZ7LvzFGFmuKbw=
github.com/hashicorp/go-rootcerts v1.0.2 h1:jzhAVGtqPKbwpyCPELlgNWhE1znq+qwJtW5Oi2viEzc=
github.com/hashicorp/go-rootcerts v1.0.2/go.mod h1:pqUvnprVnM5bf7AOirdbb01K4ccR319Vf4pU3K5EGc8=
github.com/hashicorp/go-secure-stdlib/parseutil v0.2.0 h1:U+kC2dOhMFQctRfhK0gRctKAPTloZdMU5ZJxaesJ/VM=
github.com/hashicorp/go-secure-stdlib/parseutil v0.2.0/go.mod h1:Ll013mhdmsVDuoIXVfBtvgGJsXDYkTw1kooNcoCXuE0=
github.com/hashicorp/go-secure-stdlib/strutil v0.1.2 h1:kes8mmyCpxJsI7FTwtzRqEy9CdjCtrXrXGuOpxEA7Ts=
github.com/hashicorp/go-secure-stdlib/strutil v0.1.2/go.mod h1:Gou2R9+il93BqX25LAKCLuM+y9U2T4hlwvT1yprcna4=
github.com/hashicorp/go-sockaddr v1.0.7 h1:G+pTkSO01HpR5qCxg7lxfsFEZaG+C0VssTy/9dbT+Fw=
github.com/hashicorp/go-sockaddr v1.0.7/go.mod h1:FZQbEYa1pxkQ7WLpyXJ6cbjpT8q0YgQaK/JakXqGyWw=
github.com/hashicorp/hcl v1.0.1-vault-7 h1:ag5OxFVy3QYTFTJODRzTKVZ6xvdfLLCA1cy/Y6xGI0I=
github.com/hashicorp/hcl v1.0.1-vault-7/go.mod h1:XYhtn6ijBSAj6n4YqAaf7RBPS4I06AItNorpy+MoQNM=
github.com/hashicorp/vault/api v1.22.0 h1:+HYFquE35/B74fHoIeXlZIP2YADVboaPjaSicHEZiH0=
github.com/hashicorp/vault/api v1.22.0/go.mod h1:IUZA2cDvr4Ok3+NtK2Oq/r+lJeXkeCrHRmqdyWfpmGM=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.8.0 h1:TYPDoleBBme0xGSAX3/+NujXXtpZn9HBONkQC7IEZSo=
github.com/jackc/pgx/v5 v5.8.0/go.mod h1:QVeDInX2m9VyzvNeiCJVjCkNFqzsNb43204HshNSZKw=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE=
github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 h1:SOEGU9fKiNWd/HOJuq6+3iTQz8KNCLtVX6idSoTLdUw=
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0/go.mod h1:dXGbAdH5GtBTC4WfIxhKZfyBF/HBFgRZSWwZ9g/He9o=
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 h1:P6pPBnrTSX3DEVR4fDembhRWSsG5rVo6hYhAB/ADZrk=
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0/go.mod h1:vmVJ0l/dxyfGW6FmdpVm2joNMFikkuWg0EoCKLGUMNw=
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y=
github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/redis/go-redis/v9 v9.18.0 h1:pMkxYPkEbMPwRdenAzUNyFNrDgHx9U+DrBabWNfSRQs=
github.com/redis/go-redis/v9 v9.18.0/go.mod h1:k3ufPphLU5YXwNTUcCRXGxUoF1fqxnhFQmscfkCoDA0=
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
github.com/ryanuber/go-glob v1.0.0 h1:iQh3xXAumdQ+4Ufa5b25cRpC5TYKlno6hsv6Cb3pkBk=
github.com/ryanuber/go-glob v1.0.0/go.mod h1:807d1WSdnB0XRJzKNil9Om6lcp/3a0v4qIHxIXzX/Yc=
github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp81k=
github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME=
github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w=
github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/zeebo/assert v1.3.0 h1:g7C04CbJuIDKNPFHmsk4hwZDO5O+kntRxzaUoNXj+IQ=
github.com/zeebo/assert v1.3.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0=
github.com/zeebo/xxh3 v1.0.2 h1:xZmwmqxHZA8AI603jOQ0tMqmBr9lPeFwGg6d+xy9DC0=
github.com/zeebo/xxh3 v1.0.2/go.mod h1:5NWz9Sef7zIDm2JHfFlcQvNekmcEl9ekUZQQKCYaDcA=
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
golang.org/x/crypto v0.40.0 h1:r4x+VvoG5Fm+eJcxMaY8CQM7Lb0l1lsmjGBQ6s8BfKM=
golang.org/x/crypto v0.40.0/go.mod h1:Qr1vMER5WyS2dfPHAlsOj01wgLbsyWtFn/aY+5+ZdxY=
golang.org/x/net v0.42.0 h1:jzkYrhi3YQWD6MLBJcsklgQsoAcw89EcZbJw8Z614hs=
golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8=
golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug=
golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk=
golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4=
golang.org/x/time v0.12.0 h1:ScB/8o8olJvc+CQPWrK3fPZNfh7qgwCrY0zJmoEQLSE=
golang.org/x/time v0.12.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/driver/postgres v1.6.0 h1:2dxzU8xJ+ivvqTRph34QX+WrRaJlmfyPqXmoGVjMBa4=
gorm.io/driver/postgres v1.6.0/go.mod h1:vUw0mrGgrTK+uPHEhAdV4sfFELrByKVGnaVRkXDhtWo=
gorm.io/gorm v1.31.1 h1:7CA8FTFz/gRfgqgpeKIBcervUn3xSyPUmr6B2WXJ7kg=
gorm.io/gorm v1.31.1/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs=

View File

@ -0,0 +1,161 @@
package handlers
import (
"encoding/json"
"errors"
"fmt"
"github.com/go-chi/chi/v5"
"io"
"net/http"
"strconv"
)
// ErrorResponse структура для возврата ошибок
type ErrorResponse struct {
ErrorCode int `json:"error_code"`
ErrorDescription string `json:"error_description"`
}
type ExcelFileResponse struct {
Data []byte // Содержимое файла
FileName string // Имя файла для скачивания
}
// WrapHandlerParams структура для параметров обертки
type WrapHandlerParams struct {
HandlerFunc func(http.ResponseWriter, *http.Request) (interface{}, error)
}
// responseWriterWrapper предотвращает повторный вызов WriteHeader
type responseWriterWrapper struct {
http.ResponseWriter
wroteHeader bool
}
func (rw *responseWriterWrapper) WriteHeader(statusCode int) {
if !rw.wroteHeader {
rw.ResponseWriter.WriteHeader(statusCode)
rw.wroteHeader = true
}
}
func (rw *responseWriterWrapper) Write(b []byte) (int, error) {
if !rw.wroteHeader {
rw.WriteHeader(http.StatusOK)
}
return rw.ResponseWriter.Write(b)
}
// WrapHandlerF обертка для обработчиков
func WrapHandlerF(p WrapHandlerParams) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
rw := &responseWriterWrapper{ResponseWriter: w}
payload, err := p.HandlerFunc(rw, r)
// 🆕 Проверяем, не файл ли это
if fileResp, ok := payload.(*ExcelFileResponse); ok && err == nil {
serveExcelFile(rw, fileResp)
return
}
// Обычный JSON ответ
respondWithJSON(rw, err, payload)
}
}
// 🆕 serveExcelFile отправляет файл как бинарный ответ
func serveExcelFile(w http.ResponseWriter, fileResp *ExcelFileResponse) {
// Устанавливаем заголовки ДО отправки тела
w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileResp.FileName))
w.Header().Set("Content-Length", strconv.Itoa(len(fileResp.Data)))
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
w.WriteHeader(http.StatusOK)
// Отправляем содержимое файла
if _, err := w.Write(fileResp.Data); err != nil {
// Логируем ошибку, но заголовки уже отправлены
// Можно добавить логгер здесь
_ = err
}
}
// RegisterRoute вспомогательная функция для регистрации маршрутов
func RegisterRoute(r chi.Router, method, path string, handlerFunc func(http.ResponseWriter, *http.Request) (interface{}, error)) {
wrappedHandler := WrapHandlerF(WrapHandlerParams{
HandlerFunc: handlerFunc,
})
switch method {
case http.MethodGet:
r.Get(path, wrappedHandler)
case http.MethodPost:
r.Post(path, wrappedHandler)
case http.MethodPatch:
r.Patch(path, wrappedHandler)
case http.MethodPut:
r.Put(path, wrappedHandler)
case http.MethodDelete:
r.Delete(path, wrappedHandler)
}
}
// ParseRequestBodyPost обрабатывает тело запроса
func ParseRequestBodyPost(r *http.Request, v interface{}) error {
defer r.Body.Close()
if r.ContentLength == 0 {
return errors.New("body content is empty")
}
body, err := io.ReadAll(r.Body)
if err != nil {
return err
}
if err := json.Unmarshal(body, v); err != nil {
return err
}
return nil
}
// respondWithJSON отправляет ответ в формате JSON
func respondWithJSON(w http.ResponseWriter, err error, payload interface{}) {
w.Header().Set("Content-Type", "application/json")
var status int
var response []byte
if err != nil {
status = http.StatusInternalServerError
errorResponse := ErrorResponse{
ErrorCode: status,
ErrorDescription: err.Error(),
}
response, _ = json.Marshal(errorResponse)
} else {
response, err = json.Marshal(payload)
if err != nil {
status = http.StatusInternalServerError
errorResponse := ErrorResponse{
ErrorCode: status,
ErrorDescription: err.Error(),
}
response, _ = json.Marshal(errorResponse)
} else {
status = http.StatusOK
}
}
if rw, ok := w.(*responseWriterWrapper); ok {
if !rw.wroteHeader {
rw.WriteHeader(status)
}
} else {
w.WriteHeader(status)
}
_, _ = w.Write(response)
}

View File

@ -0,0 +1,80 @@
package telephony
import (
"bitrix_balancer_api/core/typescore"
"context"
"errors"
"net/http"
"rest_telephony_service/handlers"
typesm "rest_telephony_service/types"
"strconv"
"time"
"github.com/sirupsen/logrus"
)
// WebhookTelephonyHandler принимает события от АТС
func (s *TelephonyReg) WebhookTelephonyHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
var req typesm.TelephonyWebhookReq
// Используем ваш стандартный парсер тела запроса
if err := handlers.ParseRequestBodyPost(r, &req); err != nil {
return nil, errors.New("invalid request body")
}
// Игнорируем всё, кроме SMS (event_type == 32)
if req.Event.EventType != 32 {
return map[string]string{"status": "ignored", "reason": "not an SMS event"}, nil
}
eventTime := time.Unix(req.Event.EventCreated, 0)
smsLog := &typescore.SmsLog{
AccountID: &req.Webhook.AccountID,
UserID: &req.Webhook.UserID,
ClientNumber: &req.Event.ClientNumber,
Direction: &req.Event.Direction,
Text: &req.Event.Text,
EventCreated: &eventTime,
}
// Сохраняем SMS в БД
err := s.ipc.Database.SMSLog.CreateSmsLogDB(context.Background(), nil, smsLog)
if err != nil {
logrus.Errorf("Failed to save SMS log: %v", err)
return nil, errors.New("database error")
}
logrus.Infof("Successfully logged SMS from client %s", req.Event.ClientNumber)
return map[string]string{"status": "success"}, nil
}
// GetSmsReportHandler отдает список SMS для Google Script
func (s *TelephonyReg) GetSmsReportHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
startStr := r.URL.Query().Get("start")
endStr := r.URL.Query().Get("end")
if startStr == "" || endStr == "" {
return nil, errors.New("missing 'start' or 'end' query parameters")
}
startInt, err1 := strconv.ParseInt(startStr, 10, 64)
endInt, err2 := strconv.ParseInt(endStr, 10, 64)
if err1 != nil || err2 != nil {
return nil, errors.New("invalid timestamp format")
}
startDate := time.Unix(startInt, 0)
endDate := time.Unix(endInt, 0)
logs, err := s.ipc.Database.SMSLog.GetSmsLogsByDateRangeDB(context.Background(), startDate, endDate)
if err != nil {
logrus.Errorf("Failed to fetch SMS logs: %v", err)
return nil, errors.New("failed to fetch data")
}
return typesm.SmsReportResponse{
Success: true,
Data: logs,
}, nil
}

View File

@ -0,0 +1,30 @@
package telephony
import (
"github.com/go-chi/chi/v5"
"net/http"
"rest_telephony_service/handlers"
typesm "rest_telephony_service/types"
)
type TelephonyReg struct {
ipc *typesm.InternalProviderControl
}
// RegisterTelephonyRoutes регистрирует маршруты телефонии
func RegisterTelephonyRoutes(r chi.Router, ipc *typesm.InternalProviderControl) error {
s := &TelephonyReg{
ipc: ipc,
}
r.Route("/api/v1/telephony", func(r chi.Router) {
// Вебхук открыт для провайдера
handlers.RegisterRoute(r, http.MethodPost, "/webhook", s.WebhookTelephonyHandler)
// Отдача данных. Если скрипту Google нужен доступ,
// здесь можно добавить r.Use(handlers.AccessCodeVerifier(ipc.Config))
handlers.RegisterRoute(r, http.MethodGet, "/sms-report", s.GetSmsReportHandler)
})
return nil
}

View File

@ -0,0 +1,34 @@
package typesm
import (
configcore "bitrix_balancer_api/core/config"
database "bitrix_balancer_api/core/db"
"bitrix_balancer_api/core/lib/external/tgkit"
redismodule "bitrix_balancer_api/core/lib/internally/redis"
"bitrix_balancer_api/core/typescore"
)
type InternalProviderControl struct {
Config *configcore.Config
RedisClient *redismodule.ModuleRedis
TGBotClient *tgkit.Client
Database *database.ModuleDB
}
type TelephonyWebhookReq struct {
Webhook WebhookMeta `json:"webhook"`
Event typescore.CallEvent `json:"event"`
}
type WebhookMeta struct {
Action string `json:"action"`
AccountID string `json:"account_id"`
AccountName string `json:"account_name"`
UserID string `json:"user_id"`
UserLogin string `json:"user_login"`
}
type SmsReportResponse struct {
Success bool `json:"success"`
Data []*typescore.SmsLog `json:"data,omitempty"`
}

View File

@ -39,9 +39,9 @@ func NewUpdateHandler(ipc *types.InternalProviderControl) *UpdateHandler {
}
// TODO: вызывается только после обновлений
//go handler.broadcastBotUpdated()
//go handler.sendNewSupportContactNotification()
//go handler.broadcastCommentsFeatureUpdate()
//go handlers.broadcastBotUpdated()
//go handlers.sendNewSupportContactNotification()
//go handlers.broadcastCommentsFeatureUpdate()
return handler
}

53619
services.txt Normal file

File diff suppressed because it is too large Load Diff