180 lines
6.3 KiB
Go
180 lines
6.3 KiB
Go
package start
|
||
|
||
import (
|
||
"bitrix_balancer_api/core/typescore"
|
||
"bitrix_balancer_api/core/utilscore"
|
||
"bitrix_balancer_api/telegram_service/handlers/approval"
|
||
"bitrix_balancer_api/telegram_service/keyboard"
|
||
"bitrix_balancer_api/telegram_service/types"
|
||
"context"
|
||
"fmt"
|
||
|
||
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
|
||
"github.com/sirupsen/logrus"
|
||
)
|
||
|
||
type Handler struct {
|
||
approvalHandler *approval.Handler
|
||
ipc *types.InternalProviderControl
|
||
}
|
||
|
||
func NewHandler(ipc *types.InternalProviderControl, approvalHandler *approval.Handler) *Handler {
|
||
return &Handler{
|
||
ipc: ipc,
|
||
approvalHandler: approvalHandler,
|
||
}
|
||
}
|
||
|
||
// Handle — точка входа для команды /start.
|
||
// Если пользователь уже зарегистрирован — приветствуем.
|
||
// Если нет — запускаем флоу регистрации.
|
||
func (h *Handler) Handle(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) {
|
||
ctx := context.Background()
|
||
|
||
existing, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, msg.From.ID)
|
||
if err != nil {
|
||
logrus.Error("start.Handle: GetUserByTelegramIDDB: ", err)
|
||
return
|
||
}
|
||
|
||
// Пользователь уже есть — показываем главное меню или сообщение об ожидании отдела
|
||
if existing != nil {
|
||
h.sendWelcomeBack(bot, msg.Chat.ID, msg.From.ID, existing)
|
||
return
|
||
}
|
||
|
||
// Новый пользователь — сохраняем состояние "ожидаем ФИО"
|
||
stateKey := registrationStateKey(msg.From.ID)
|
||
if err := h.ipc.RedisClient.Set(ctx, stateKey, stateAwaitingFullName, registrationTTL); err != nil {
|
||
logrus.Error("start.Handle: Set redis state: ", err)
|
||
return
|
||
}
|
||
|
||
utilscore.SendBotMessage(bot, msg.Chat.ID,
|
||
"👋 Добро пожаловать в Портал сотрудника РусПЭТ!\n\n"+
|
||
"Для регистрации введите ваше <b>полное имя</b> (Фамилию Имя).\n\n"+
|
||
"<i>Например: Иванов Иван</i>",
|
||
)
|
||
}
|
||
|
||
// HandleTextInput обрабатывает текстовый ввод в рамках флоу регистрации.
|
||
// Возвращает true если сообщение было обработано (пользователь в процессе регистрации).
|
||
func (h *Handler) HandleTextInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) bool {
|
||
ctx := context.Background()
|
||
stateKey := registrationStateKey(msg.From.ID)
|
||
|
||
state, err := h.ipc.RedisClient.Get(ctx, stateKey)
|
||
if err != nil || state == "" {
|
||
return false // не наш ввод
|
||
}
|
||
|
||
switch state {
|
||
case stateAwaitingFullName:
|
||
h.handleFullNameInput(ctx, bot, msg, stateKey)
|
||
return true
|
||
}
|
||
|
||
return false
|
||
}
|
||
|
||
func (h *Handler) handleFullNameInput(ctx context.Context, bot *tgbotapi.BotAPI, msg *tgbotapi.Message, stateKey string) {
|
||
fullName := sanitizeFullName(msg.Text)
|
||
|
||
if !isValidFullName(fullName) {
|
||
utilscore.SendBotMessage(bot, msg.Chat.ID,
|
||
"⚠️ Пожалуйста, введите корректное ФИО.\n\n"+
|
||
"<i>Например: Иванов Иван</i>",
|
||
)
|
||
return
|
||
}
|
||
|
||
// Создаём пользователя
|
||
telegramID := msg.From.ID
|
||
username := msg.From.UserName
|
||
langCode := msg.From.LanguageCode
|
||
|
||
user := &typescore.User{
|
||
TelegramID: &telegramID,
|
||
FullName: &fullName,
|
||
LanguageCode: &langCode,
|
||
}
|
||
if username != "" {
|
||
user.Username = &username
|
||
}
|
||
|
||
created, _, err := h.ipc.Database.User.CreateUserDB(ctx, nil, user, true)
|
||
if err != nil {
|
||
logrus.Error("start.handleFullNameInput: CreateUserDB: ", err)
|
||
utilscore.SendBotMessage(bot, msg.Chat.ID, "Произошла ошибка при регистрации. Попробуйте ещё раз — /start")
|
||
return
|
||
}
|
||
|
||
// Сбрасываем состояние регистрации
|
||
h.ipc.RedisClient.Del(ctx, stateKey) //nolint:errcheck
|
||
|
||
logrus.Infof("✅ Новый пользователь зарегистрирован: %s (tg_id=%d)", fullName, telegramID)
|
||
|
||
h.sendRegistrationDone(bot, msg.Chat.ID, created)
|
||
}
|
||
|
||
// sendWelcomeBack — приветствие для уже зарегистрированного пользователя.
|
||
func (h *Handler) sendWelcomeBack(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, user *typescore.User) {
|
||
ctx := context.Background()
|
||
name := ""
|
||
if user.FullName != nil {
|
||
name = *user.FullName
|
||
}
|
||
|
||
if user.DepartmentID == nil {
|
||
utilscore.SendBotMessage(bot, chatID, fmt.Sprintf(
|
||
"👋 Здравствуйте, <b>%s</b>!\n\n"+
|
||
"⏳ Ваша учётная запись ожидает назначения в отдел.\n"+
|
||
"Обратитесь к администратору.", name,
|
||
))
|
||
return
|
||
}
|
||
|
||
// Определяем клавиатуру по роли
|
||
replyMarkup := h.buildMenuKeyboard(ctx, user)
|
||
|
||
msg := tgbotapi.NewMessage(chatID, fmt.Sprintf("👋 Здравствуйте, <b>%s</b>!", name))
|
||
msg.ParseMode = "HTML"
|
||
msg.ReplyMarkup = replyMarkup
|
||
bot.Send(msg) //nolint:errcheck
|
||
}
|
||
|
||
// buildMenuKeyboard возвращает клавиатуру в зависимости от роли пользователя
|
||
func (h *Handler) buildMenuKeyboard(ctx context.Context, user *typescore.User) tgbotapi.ReplyKeyboardMarkup {
|
||
if user.ID == nil {
|
||
return keyboard.BuildMainMenu(keyboard.UserRole{})
|
||
}
|
||
|
||
// Получаем все роли пользователя
|
||
isApprover, _ := h.ipc.Database.User.IsApproverDB(ctx, *user.ID)
|
||
isObserver, _ := h.ipc.Database.User.IsObserverDB(ctx, *user.ID)
|
||
isExecutor, _ := h.ipc.Database.User.IsExecutorDB(ctx, *user.ID)
|
||
isDirector, _ := h.ipc.Database.User.IsDirectorDB(ctx, *user.ID)
|
||
|
||
return keyboard.BuildMainMenu(keyboard.UserRole{
|
||
IsApprover: isApprover,
|
||
IsObserver: isObserver,
|
||
IsExecutor: isExecutor,
|
||
IsDirector: isDirector,
|
||
})
|
||
}
|
||
|
||
// sendRegistrationDone — подтверждение успешной регистрации.
|
||
func (h *Handler) sendRegistrationDone(bot *tgbotapi.BotAPI, chatID int64, user *typescore.User) {
|
||
name := ""
|
||
if user.FullName != nil {
|
||
name = *user.FullName
|
||
}
|
||
|
||
utilscore.SendBotMessage(bot, chatID, fmt.Sprintf(
|
||
"✅ Вы успешно зарегистрированы!\n\n"+
|
||
"<b>Имя:</b> %s\n\n"+
|
||
"⏳ Ожидайте назначения в отдел. После этого вам станут доступны функции портала.\n",
|
||
name,
|
||
))
|
||
}
|