diff --git a/core/db/methods/user.go b/core/db/methods/user.go
index 1d849da..82347e9 100644
--- a/core/db/methods/user.go
+++ b/core/db/methods/user.go
@@ -36,6 +36,7 @@ type UserDBI interface {
IsApproverDB(ctx context.Context, userID uint64) (bool, error)
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)
}
func (u *UserDB) GetUsersListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.User, uint64, error) {
@@ -357,3 +358,35 @@ func (u *UserDB) GetObserversForCategoryDB(ctx context.Context, categoryCode str
}
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.*").
+ 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(squirrel.Eq{"r.code": roleCode}).
+ Where(squirrel.Eq{"u.is_blocked": false}).
+ OrderBy("u.full_name ASC").
+ 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("GetUsersByRoleCodeDB:ScanRowsToStruct", err)
+ continue
+ }
+ users = append(users, user)
+ }
+ return users, nil
+}
diff --git a/service/telegram_service/common/update/callback.go b/service/telegram_service/common/update/callback.go
index a68906c..f1e17ba 100644
--- a/service/telegram_service/common/update/callback.go
+++ b/service/telegram_service/common/update/callback.go
@@ -356,6 +356,35 @@ func (s *UpdateHandler) handleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.Callba
case data == "select_approver_noop":
bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ // ВЫБОР ПЕРВОГО НАБЛДАТЕЛЯ
+ case strings.HasPrefix(data, "obs_select_toggle:"):
+ observerID := parseID(data, "obs_select_toggle:")
+ s.approvalHandler.HandleObserverToggleCallback(bot, cq, observerID)
+
+ case strings.HasPrefix(data, "obs_select_page:"):
+ page := 0
+ fmt.Sscanf(strings.TrimPrefix(data, "obs_select_page:"), "%d", &page)
+ s.approvalHandler.HandleObserverPageCallback(bot, cq, page)
+
+ case data == "obs_select_confirm":
+ s.approvalHandler.HandleObserverConfirmCallback(bot, cq)
+
+ case data == "obs_select_noop":
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+
+ // ВЫБОР ПЕРВОГО СОГЛАСУЮЩеГО
+ case strings.HasPrefix(data, "first_approver_select:"):
+ userID := parseID(data, "first_approver_select:")
+ s.approvalHandler.HandleFirstApproverSelectCallback(bot, cq, userID)
+
+ case strings.HasPrefix(data, "first_approver_page:"):
+ page := 0
+ fmt.Sscanf(strings.TrimPrefix(data, "first_approver_page:"), "%d", &page)
+ s.approvalHandler.HandleFirstApproverPageCallback(bot, cq, page)
+
+ case data == "first_approver_noop":
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+
// ── ПРОЧЕЕ ──────────────────────────────────────────────────
case data == "restart_bot":
bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
diff --git a/service/telegram_service/handlers/approval/handle_files.go b/service/telegram_service/handlers/approval/handle_files.go
index 2783713..d6bfdab 100644
--- a/service/telegram_service/handlers/approval/handle_files.go
+++ b/service/telegram_service/handlers/approval/handle_files.go
@@ -203,23 +203,8 @@ func (h *Handler) HandleSubmitFiles(bot *tgbotapi.BotAPI, chatID int64, telegram
flowState.FileStatusMsgID = 0
}
- // Проверяем, нужно ли выбирать согласующего
- topic, _ := h.registry.Get(flowState.TopicCode)
- if topic != nil {
- topicCode, _ := topic.TopicCodeFromCollected(flowState.Collected)
- approvalTopic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByCodeDB(ctx, topicCode)
- if approvalTopic != nil && approvalTopic.AllowApproverSelection != nil && *approvalTopic.AllowApproverSelection {
- // Нужно выбрать согласующего
- flowState.AwaitApproverSelection = true
- h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
- h.showApproverSelection(bot, ctx, chatID, telegramID, approvalTopic)
- return
- }
- }
-
- // Если выбор согласующего не нужен - отправляем заявку
- h.States.Clear(ctx, telegramID) //nolint:errcheck
- h.finalizeAndSubmit(bot, ctx, chatID, telegramID, flowState)
+ h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
+ h.continueFlowAfterInput(bot, ctx, chatID, telegramID, flowState)
}
// fetchFileAsBase64 скачивает файл по URL и возвращает base64-строку.
diff --git a/service/telegram_service/handlers/approval/handler.go b/service/telegram_service/handlers/approval/handler.go
index acb0276..79bb9cd 100644
--- a/service/telegram_service/handlers/approval/handler.go
+++ b/service/telegram_service/handlers/approval/handler.go
@@ -169,30 +169,16 @@ func (h *Handler) HandleTextInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) b
flowState.Collected[flowState.InputKey] = msg.Text
flowState.AwaitInput = false
- // Проверяем, нужно ли загружать файлы
+ // Файлы для официального больничного
if flowState.Collected["payment_type"] == "official" {
flowState.AwaitFileInput = true
+ h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
h.showFileStatus(bot, chatID, int64(telegramID), flowState)
return true
}
- // Проверяем, нужно ли выбирать согласующего
- topic, _ := h.registry.Get(flowState.TopicCode)
- if topic != nil {
- topicCode, _ := topic.TopicCodeFromCollected(flowState.Collected)
- approvalTopic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByCodeDB(ctx, topicCode)
- if approvalTopic != nil && approvalTopic.AllowApproverSelection != nil && *approvalTopic.AllowApproverSelection {
- // Нужно выбрать согласующего
- flowState.AwaitApproverSelection = true
- h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
- h.showApproverSelection(bot, ctx, chatID, telegramID, approvalTopic)
- return true
- }
- }
-
- // Если выбор согласующего не нужен - отправляем заявку
- h.States.Clear(ctx, telegramID) //nolint:errcheck
- h.finalizeAndSubmit(bot, ctx, chatID, telegramID, flowState)
+ h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
+ h.continueFlowAfterInput(bot, ctx, chatID, telegramID, flowState)
return true
}
@@ -373,3 +359,62 @@ func (h *Handler) HandleBackCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.Callback
msg.ReplyMarkup = keyboard.BuildApprovalStep(topicCode, node.Children)
bot.Send(msg) //nolint:errcheck
}
+
+func (h *Handler) continueFlowAfterInput(
+ bot *tgbotapi.BotAPI,
+ ctx context.Context,
+ chatID int64,
+ telegramID int64,
+ flowState *state.ApprovalFlowState,
+) {
+ topic, _ := h.registry.Get(flowState.TopicCode)
+ if topic == nil {
+ h.States.Clear(ctx, telegramID) //nolint:errcheck
+ return
+ }
+
+ topicCode, _ := topic.TopicCodeFromCollected(flowState.Collected)
+ approvalTopic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByCodeDB(ctx, topicCode)
+
+ // Выбор первого согласующего по роли
+ if approvalTopic != nil &&
+ approvalTopic.FirstApproverRoleCode != nil &&
+ *approvalTopic.FirstApproverRoleCode != "" &&
+ flowState.SelectedFirstApproverID == 0 {
+
+ flowState.AwaitFirstApproverSelection = true
+ h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
+
+ _, roleCode, roleLabel := h.getFirstApproverRoleForFlow(ctx, flowState)
+ h.showFirstApproverSelection(bot, ctx, chatID, telegramID, roleCode, roleLabel)
+ return
+ }
+
+ // Выбор основного согласующего
+ if approvalTopic != nil &&
+ approvalTopic.AllowApproverSelection != nil &&
+ *approvalTopic.AllowApproverSelection &&
+ flowState.SelectedApproverID == 0 {
+
+ flowState.AwaitApproverSelection = true
+ h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
+ h.showApproverSelection(bot, ctx, chatID, telegramID, approvalTopic)
+ return
+ }
+
+ // Выбор наблюдателей
+ if approvalTopic != nil &&
+ approvalTopic.AllowObserverSelection != nil &&
+ *approvalTopic.AllowObserverSelection &&
+ !flowState.AwaitObserverSelection {
+
+ flowState.AwaitObserverSelection = true
+ h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
+ h.showObserverSelection(bot, ctx, chatID, telegramID, flowState)
+ return
+ }
+
+ // Все шаги пройдены — отправляем заявку
+ h.States.Clear(ctx, telegramID) //nolint:errcheck
+ h.finalizeAndSubmit(bot, ctx, chatID, telegramID, flowState)
+}
diff --git a/service/telegram_service/handlers/approval/comment.go b/service/telegram_service/handlers/approval/handler_comment.go
similarity index 100%
rename from service/telegram_service/handlers/approval/comment.go
rename to service/telegram_service/handlers/approval/handler_comment.go
diff --git a/service/telegram_service/handlers/approval/decision.go b/service/telegram_service/handlers/approval/handler_decision.go
similarity index 100%
rename from service/telegram_service/handlers/approval/decision.go
rename to service/telegram_service/handlers/approval/handler_decision.go
diff --git a/service/telegram_service/handlers/approval/delegation.go b/service/telegram_service/handlers/approval/handler_delegation.go
similarity index 100%
rename from service/telegram_service/handlers/approval/delegation.go
rename to service/telegram_service/handlers/approval/handler_delegation.go
diff --git a/service/telegram_service/handlers/approval/executor.go b/service/telegram_service/handlers/approval/handler_executor.go
similarity index 100%
rename from service/telegram_service/handlers/approval/executor.go
rename to service/telegram_service/handlers/approval/handler_executor.go
diff --git a/service/telegram_service/handlers/approval/helper.go b/service/telegram_service/handlers/approval/helper.go
index 5b18a3d..a01abee 100644
--- a/service/telegram_service/handlers/approval/helper.go
+++ b/service/telegram_service/handlers/approval/helper.go
@@ -99,6 +99,15 @@ func (h *Handler) submitApproval(ctx context.Context, bot *tgbotapi.BotAPI, tele
var approvers []*typescore.User
+ // Если выбран первый согласующий по роли — он будет шагом 0
+ var firstRoleApprover *typescore.User
+ if flowState.SelectedFirstApproverID > 0 {
+ firstRoleApprover, err = h.ipc.Database.User.GetUserByIDDB(ctx, flowState.SelectedFirstApproverID)
+ if err != nil || firstRoleApprover == nil {
+ return nil, fmt.Errorf("selected first approver not found: %d", flowState.SelectedFirstApproverID)
+ }
+ }
+
// Если согласующий был выбран вручную - используем его
if flowState.SelectedApproverID > 0 {
selectedApprover, err := h.ipc.Database.User.GetUserByIDDB(ctx, flowState.SelectedApproverID)
@@ -119,6 +128,11 @@ func (h *Handler) submitApproval(ctx context.Context, bot *tgbotapi.BotAPI, tele
}
}
+ // Если есть первый согласующий по роли — вставляем его перед остальными
+ if firstRoleApprover != nil {
+ approvers = append([]*typescore.User{firstRoleApprover}, approvers...)
+ }
+
if len(approvers) == 0 {
logrus.Warnf("submitApproval: no approvers found for userID=%d deptID=%d", *initiator.ID, *initiator.DepartmentID)
@@ -171,10 +185,10 @@ func (h *Handler) submitApproval(ctx context.Context, bot *tgbotapi.BotAPI, tele
continue
}
- order := i + 1
+ order := i
stepStatus := "waiting"
if i == 0 {
- stepStatus = "pending" // первый активен сразу
+ stepStatus = "pending"
}
// Снимок имени и отдела согласующего
@@ -198,6 +212,11 @@ func (h *Handler) submitApproval(ctx context.Context, bot *tgbotapi.BotAPI, tele
}
}
+ // Сохраняем выбранных наблюдателей
+ if len(flowState.SelectedObserverIDs) > 0 {
+ h.saveSelectedObservers(ctx, *created.ID, *initiator.ID, flowState.SelectedObserverIDs)
+ }
+
// Уведомляем первого согласующего (или делегата)
firstApprover := approvers[0]
if firstApprover.TelegramID == nil {
@@ -246,7 +265,6 @@ func (h *Handler) submitApproval(ctx context.Context, bot *tgbotapi.BotAPI, tele
notifier := NewNotifier(h.ipc, topic)
notifier.NotifyApprover(bot, firstApprover, initiator, created, flowState.Collected)
- // Уведомляем наблюдателей о новой заявке
observers, err := h.ipc.Database.User.GetObserversForCategoryDB(ctx, flowState.TopicCode)
if err != nil {
logrus.Warnf("submitApproval: GetObserversForCategoryDB err=%v", err)
@@ -254,6 +272,14 @@ func (h *Handler) submitApproval(ctx context.Context, bot *tgbotapi.BotAPI, tele
notifier.NotifyObserversNewApproval(bot, observers, initiator, created, flowState.Collected)
}
+ // Уведомляем дополнительных наблюдателей выбранных вручную
+ if len(flowState.SelectedObserverIDs) > 0 {
+ additionalObservers := h.getAdditionalObserversForApproval(ctx, *created.ID)
+ if len(additionalObservers) > 0 {
+ notifier.NotifyObserversNewApproval(bot, additionalObservers, initiator, created, flowState.Collected)
+ }
+ }
+
return created, nil
}
diff --git a/service/telegram_service/handlers/approval/approver_selection.go b/service/telegram_service/handlers/approval/selection_approver.go
similarity index 98%
rename from service/telegram_service/handlers/approval/approver_selection.go
rename to service/telegram_service/handlers/approval/selection_approver.go
index a589824..c39f591 100644
--- a/service/telegram_service/handlers/approval/approver_selection.go
+++ b/service/telegram_service/handlers/approval/selection_approver.go
@@ -54,8 +54,8 @@ func (h *Handler) HandleApproverSelectionCallback(bot *tgbotapi.BotAPI, cq *tgbo
flowState.SelectedApproverID = approverID
flowState.AwaitApproverSelection = false
- h.States.Clear(ctx, telegramID) //nolint:errcheck
- h.finalizeAndSubmit(bot, ctx, chatID, telegramID, flowState)
+ h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
+ h.continueFlowAfterInput(bot, ctx, chatID, telegramID, flowState)
}
func (h *Handler) HandleApproverSelectionPageCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, page int) {
diff --git a/service/telegram_service/handlers/approval/selection_first_approver.go b/service/telegram_service/handlers/approval/selection_first_approver.go
new file mode 100644
index 0000000..2e00432
--- /dev/null
+++ b/service/telegram_service/handlers/approval/selection_first_approver.go
@@ -0,0 +1,141 @@
+package approval
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "context"
+ "fmt"
+
+ tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
+ "github.com/sirupsen/logrus"
+
+ "bitrix_balancer_api/telegram_service/keyboard"
+ "bitrix_balancer_api/telegram_service/state"
+)
+
+// showFirstApproverSelection показывает список пользователей с нужной ролью
+func (h *Handler) showFirstApproverSelection(bot *tgbotapi.BotAPI, ctx context.Context, chatID int64, telegramID int64, roleCode string, roleLabel string) {
+ users, err := h.ipc.Database.User.GetUsersByRoleCodeDB(ctx, roleCode)
+ if err != nil {
+ logrus.Errorf("showFirstApproverSelection: GetUsersByRoleCodeDB err=%v", err)
+ sendText(bot, chatID, "Ошибка при получении списка пользователей.")
+ return
+ }
+
+ if len(users) == 0 {
+ sendText(bot, chatID, fmt.Sprintf("⚠️ Нет пользователей с ролью «%s».", roleLabel))
+ h.States.Clear(ctx, telegramID) //nolint:errcheck
+ return
+ }
+
+ msg := tgbotapi.NewMessage(chatID, fmt.Sprintf(
+ "👤 Выберите %s\n"+
+ "Этот пользователь станет первым согласующим в цепочке.",
+ roleLabel,
+ ))
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildFirstApproverSelectionMenu(users, roleLabel, 0)
+ bot.Send(msg) //nolint:errcheck
+}
+
+// HandleFirstApproverSelectCallback — пользователь выбрал первого согласующего
+func (h *Handler) HandleFirstApproverSelectCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, userID uint64) {
+ ctx := context.Background()
+ chatID := cq.Message.Chat.ID
+ telegramID := cq.From.ID
+
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck
+
+ flowState, err := h.States.Get(ctx, telegramID)
+ if err != nil || flowState == nil || !flowState.AwaitFirstApproverSelection {
+ sendText(bot, chatID, "⚠️ Состояние утеряно. Начните заново.")
+ return
+ }
+
+ selected, err := h.ipc.Database.User.GetUserByIDDB(ctx, userID)
+ if err != nil || selected == nil || selected.FullName == nil {
+ sendText(bot, chatID, "⚠️ Пользователь не найден.")
+ return
+ }
+
+ flowState.SelectedFirstApproverID = userID
+ flowState.AwaitFirstApproverSelection = false
+
+ // Следующий шаг — выбор основного согласующего или наблюдателей
+ h.continueFlowAfterInput(bot, ctx, chatID, telegramID, flowState)
+}
+
+// HandleFirstApproverPageCallback — пагинация списка
+func (h *Handler) HandleFirstApproverPageCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, page int) {
+ ctx := context.Background()
+ chatID := cq.Message.Chat.ID
+ telegramID := cq.From.ID
+
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+
+ flowState, err := h.States.Get(ctx, telegramID)
+ if err != nil || flowState == nil || !flowState.AwaitFirstApproverSelection {
+ return
+ }
+
+ approvalTopic, roleCode, roleLabel := h.getFirstApproverRoleForFlow(ctx, flowState)
+ if approvalTopic == nil {
+ return
+ }
+ _ = approvalTopic
+
+ users, err := h.ipc.Database.User.GetUsersByRoleCodeDB(ctx, roleCode)
+ if err != nil {
+ return
+ }
+
+ editMsg := tgbotapi.NewEditMessageReplyMarkup(
+ chatID,
+ cq.Message.MessageID,
+ keyboard.BuildFirstApproverSelectionMenu(users, roleLabel, page),
+ )
+ bot.Request(editMsg) //nolint:errcheck
+}
+
+// getFirstApproverRoleForFlow возвращает тему и код роли для первого согласующего
+func (h *Handler) getFirstApproverRoleForFlow(
+ ctx context.Context,
+ flowState *state.ApprovalFlowState,
+) (*typescore.ApprovalTopic, string, string) {
+ topic, _ := h.registry.Get(flowState.TopicCode)
+ if topic == nil {
+ return nil, "", ""
+ }
+
+ topicCode, _ := topic.TopicCodeFromCollected(flowState.Collected)
+ approvalTopic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByCodeDB(ctx, topicCode)
+ if approvalTopic == nil || approvalTopic.FirstApproverRoleCode == nil {
+ return nil, "", ""
+ }
+
+ // Получаем название роли для отображения
+ roleList, _, err := h.ipc.Database.Role.GetRolesListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.Role{
+ Code: approvalTopic.FirstApproverRoleCode,
+ },
+ })
+ if err != nil {
+ logrus.Errorf("getFirstApproverRoleForFlow err=%v", err)
+ return nil, "", ""
+ }
+ if roleList == nil || len(roleList) == 0 {
+ logrus.Errorf("getFirstApproverRoleForFlow. Role not found err=%v", err)
+ return nil, "", ""
+ }
+ role := roleList[0]
+ if role == nil || role.Code == nil {
+ logrus.Errorf("getFirstApproverRoleForFlow. Role not found err=%v", err)
+ return nil, "", ""
+ }
+ roleLabel := *role.Code
+ if role.Name != nil {
+ roleLabel = *role.Name
+ }
+
+ return approvalTopic, *role.Code, roleLabel
+}
diff --git a/service/telegram_service/handlers/approval/selection_observer.go b/service/telegram_service/handlers/approval/selection_observer.go
new file mode 100644
index 0000000..08a0c45
--- /dev/null
+++ b/service/telegram_service/handlers/approval/selection_observer.go
@@ -0,0 +1,180 @@
+package approval
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "context"
+ tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
+ "github.com/sirupsen/logrus"
+
+ "bitrix_balancer_api/telegram_service/keyboard"
+ "bitrix_balancer_api/telegram_service/state"
+)
+
+// showObserverSelection показывает экран выбора наблюдателей
+func (h *Handler) showObserverSelection(
+ bot *tgbotapi.BotAPI,
+ ctx context.Context,
+ chatID int64,
+ telegramID int64,
+ flowState *state.ApprovalFlowState,
+) {
+ observers, err := h.getAvailableObservers(ctx)
+ if err != nil || len(observers) == 0 {
+ // Нет наблюдателей — пропускаем шаг и сразу отправляем
+ flowState.AwaitObserverSelection = false
+ h.States.Clear(ctx, telegramID) //nolint:errcheck
+ h.finalizeAndSubmit(bot, ctx, chatID, telegramID, flowState)
+ return
+ }
+
+ msg := tgbotapi.NewMessage(chatID,
+ "👁 Выберите наблюдателей для заявки\n"+
+ "Они получат уведомления, но не смогут влиять на решение.\n"+
+ "Можно выбрать несколько или пропустить.",
+ )
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildObserverSelectionMenu(observers, flowState.SelectedObserverIDs, 0)
+ bot.Send(msg) //nolint:errcheck
+}
+
+// HandleObserverToggleCallback — пользователь нажал на наблюдателя (toggle)
+func (h *Handler) HandleObserverToggleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, observerID uint64) {
+ ctx := context.Background()
+ chatID := cq.Message.Chat.ID
+ telegramID := cq.From.ID
+
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+
+ flowState, err := h.States.Get(ctx, telegramID)
+ if err != nil || flowState == nil || !flowState.AwaitObserverSelection {
+ return
+ }
+
+ // Toggle: добавляем или убираем наблюдателя
+ found := false
+ newIDs := make([]uint64, 0, len(flowState.SelectedObserverIDs))
+ for _, id := range flowState.SelectedObserverIDs {
+ if id == observerID {
+ found = true // убираем — просто не добавляем
+ } else {
+ newIDs = append(newIDs, id)
+ }
+ }
+ if !found {
+ newIDs = append(newIDs, observerID)
+ }
+ flowState.SelectedObserverIDs = newIDs
+
+ if err := h.States.Set(ctx, telegramID, flowState); err != nil {
+ logrus.Errorf("HandleObserverToggleCallback: Set state err=%v", err)
+ return
+ }
+
+ // Обновляем сообщение с новым состоянием кнопок
+ observers, _ := h.getAvailableObservers(ctx)
+ editMsg := tgbotapi.NewEditMessageReplyMarkup(
+ chatID,
+ cq.Message.MessageID,
+ keyboard.BuildObserverSelectionMenu(observers, flowState.SelectedObserverIDs, 0),
+ )
+ bot.Request(editMsg) //nolint:errcheck
+}
+
+// HandleObserverPageCallback — пагинация
+func (h *Handler) HandleObserverPageCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, page int) {
+ ctx := context.Background()
+ chatID := cq.Message.Chat.ID
+ telegramID := cq.From.ID
+
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+
+ flowState, err := h.States.Get(ctx, telegramID)
+ if err != nil || flowState == nil || !flowState.AwaitObserverSelection {
+ return
+ }
+
+ observers, err := h.getAvailableObservers(ctx)
+ if err != nil {
+ return
+ }
+
+ editMsg := tgbotapi.NewEditMessageReplyMarkup(
+ chatID,
+ cq.Message.MessageID,
+ keyboard.BuildObserverSelectionMenu(observers, flowState.SelectedObserverIDs, page),
+ )
+ bot.Request(editMsg) //nolint:errcheck
+}
+
+// HandleObserverConfirmCallback — пользователь подтвердил выбор наблюдателей
+func (h *Handler) HandleObserverConfirmCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery) {
+ ctx := context.Background()
+ chatID := cq.Message.Chat.ID
+ telegramID := cq.From.ID
+
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+ bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck
+
+ flowState, err := h.States.Get(ctx, telegramID)
+ if err != nil || flowState == nil {
+ sendText(bot, chatID, "⚠️ Состояние утеряно. Начните заново.")
+ return
+ }
+
+ flowState.AwaitObserverSelection = false
+ h.States.Clear(ctx, telegramID) //nolint:errcheck
+ h.finalizeAndSubmit(bot, ctx, chatID, telegramID, flowState)
+}
+
+// getAvailableObservers — возвращает всех пользователей с ролью наблюдателя
+func (h *Handler) getAvailableObservers(ctx context.Context) ([]*typescore.User, error) {
+ return h.ipc.Database.User.GetUsersByRoleCodeDB(ctx, "observer")
+}
+
+// saveSelectedObservers сохраняет выбранных наблюдателей после создания заявки
+func (h *Handler) saveSelectedObservers(
+ ctx context.Context,
+ approvalID uint64,
+ addedByID uint64,
+ observerIDs []uint64,
+) {
+ for _, observerID := range observerIDs {
+ id := observerID // копия для замыкания
+ addedBy := addedByID
+ aID := approvalID
+
+ obj := &typescore.ApprovalAdditionalObserver{
+ ApprovalID: &aID,
+ UserID: &id,
+ AddedByID: &addedBy,
+ }
+ if _, _, err := h.ipc.Database.ApprovalAdditionalObserver.CreateApprovalAdditionalObserverDB(ctx, nil, obj); err != nil {
+ logrus.Errorf("saveSelectedObservers: err observerID=%d err=%v", id, err)
+ }
+ }
+}
+
+// getAdditionalObserversForApproval возвращает всех дополнительных наблюдателей заявки
+func (h *Handler) getAdditionalObserversForApproval(ctx context.Context, approvalID uint64) []*typescore.User {
+ records, _, err := h.ipc.Database.ApprovalAdditionalObserver.GetApprovalAdditionalObserversListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalAdditionalObserver{
+ ApprovalID: &approvalID,
+ },
+ })
+ if err != nil {
+ logrus.Errorf("failed to get additional observers list. %v", err)
+ return nil
+ }
+
+ var users []*typescore.User
+ for _, r := range records {
+ if r.UserID == nil {
+ continue
+ }
+ u, err := h.ipc.Database.User.GetUserByIDDB(ctx, *r.UserID)
+ if err == nil && u != nil {
+ users = append(users, u)
+ }
+ }
+ return users
+}
diff --git a/service/telegram_service/keyboard/delegation.go b/service/telegram_service/keyboard/delegation.go
index edfd35a..62478b0 100644
--- a/service/telegram_service/keyboard/delegation.go
+++ b/service/telegram_service/keyboard/delegation.go
@@ -1,4 +1,4 @@
-// telegram_service/keyboard/delegation.go - полностью переписать
+// telegram_service/keyboard/handler_delegation.go - полностью переписать
package keyboard
diff --git a/service/telegram_service/keyboard/first_approver_select.go b/service/telegram_service/keyboard/first_approver_select.go
new file mode 100644
index 0000000..7f00817
--- /dev/null
+++ b/service/telegram_service/keyboard/first_approver_select.go
@@ -0,0 +1,61 @@
+package keyboard
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "fmt"
+ tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
+)
+
+const firstApproverPerPage = 8
+
+func BuildFirstApproverSelectionMenu(
+ users []*typescore.User,
+ roleLabel string,
+ page int,
+) tgbotapi.InlineKeyboardMarkup {
+ total := len(users)
+ totalPages := (total + firstApproverPerPage - 1) / firstApproverPerPage
+ if page < 0 {
+ page = 0
+ }
+ if page >= totalPages && totalPages > 0 {
+ page = totalPages - 1
+ }
+
+ start := page * firstApproverPerPage
+ end := min(start+firstApproverPerPage, total)
+
+ var rows [][]tgbotapi.InlineKeyboardButton
+
+ for _, u := range users[start:end] {
+ if u.ID == nil || u.FullName == nil {
+ continue
+ }
+ rows = append(rows, tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData(
+ *u.FullName,
+ fmt.Sprintf("first_approver_select:%d", *u.ID),
+ ),
+ ))
+ }
+
+ if totalPages > 1 {
+ var navRow []tgbotapi.InlineKeyboardButton
+ if page > 0 {
+ navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
+ "← Назад", fmt.Sprintf("first_approver_page:%d", page-1),
+ ))
+ }
+ navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
+ fmt.Sprintf("%d / %d", page+1, totalPages), "first_approver_noop",
+ ))
+ if page < totalPages-1 {
+ navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
+ "→ Вперёд", fmt.Sprintf("first_approver_page:%d", page+1),
+ ))
+ }
+ rows = append(rows, navRow)
+ }
+
+ return tgbotapi.NewInlineKeyboardMarkup(rows...)
+}
diff --git a/service/telegram_service/keyboard/observer_select.go b/service/telegram_service/keyboard/observer_select.go
new file mode 100644
index 0000000..193e511
--- /dev/null
+++ b/service/telegram_service/keyboard/observer_select.go
@@ -0,0 +1,96 @@
+package keyboard
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "fmt"
+ tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
+)
+
+const observerSelectionPerPage = 8
+
+func BuildObserverSelectionMenu(
+ observers []*typescore.User,
+ selectedIDs []uint64,
+ page int,
+) tgbotapi.InlineKeyboardMarkup {
+ total := len(observers)
+ if total == 0 {
+ return tgbotapi.NewInlineKeyboardMarkup(
+ tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData("✅ Подтвердить без наблюдателей", "obs_select_confirm"),
+ ),
+ )
+ }
+
+ totalPages := (total + observerSelectionPerPage - 1) / observerSelectionPerPage
+ if page < 0 {
+ page = 0
+ }
+ if page >= totalPages {
+ page = totalPages - 1
+ }
+
+ start := page * observerSelectionPerPage
+ end := min(start+observerSelectionPerPage, total)
+
+ // Множество выбранных для быстрой проверки
+ selectedSet := make(map[uint64]bool, len(selectedIDs))
+ for _, id := range selectedIDs {
+ selectedSet[id] = true
+ }
+
+ var rows [][]tgbotapi.InlineKeyboardButton
+
+ for _, u := range observers[start:end] {
+ if u.ID == nil || u.FullName == nil {
+ continue
+ }
+
+ label := *u.FullName
+ if selectedSet[*u.ID] {
+ label = "✅ " + label
+ }
+
+ rows = append(rows, tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData(label, fmt.Sprintf("obs_select_toggle:%d", *u.ID)),
+ ))
+ }
+
+ // Навигация
+ if totalPages > 1 {
+ var navRow []tgbotapi.InlineKeyboardButton
+ if page > 0 {
+ navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
+ "← Назад", fmt.Sprintf("obs_select_page:%d", page-1),
+ ))
+ }
+ pageBtn := tgbotapi.NewInlineKeyboardButtonData(
+ fmt.Sprintf("%d / %d", page+1, totalPages), "obs_select_noop",
+ )
+ navRow = append(navRow, pageBtn)
+ if page < totalPages-1 {
+ navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
+ "→ Вперёд", fmt.Sprintf("obs_select_page:%d", page+1),
+ ))
+ }
+ rows = append(rows, navRow)
+ }
+
+ // Кнопка подтверждения
+ confirmLabel := "✅ Подтвердить"
+ if len(selectedIDs) > 0 {
+ confirmLabel = fmt.Sprintf("✅ Подтвердить (%d выбрано)", len(selectedIDs))
+ }
+ rows = append(rows, tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData(confirmLabel, "obs_select_confirm"),
+ ))
+
+ return tgbotapi.NewInlineKeyboardMarkup(rows...)
+}
+
+func min(a, b int) int {
+ if a < b {
+ return a
+ }
+ return b
+}
diff --git a/service/telegram_service/state/delegation.go b/service/telegram_service/state/delegation.go
index 5ebe297..db2c54d 100644
--- a/service/telegram_service/state/delegation.go
+++ b/service/telegram_service/state/delegation.go
@@ -1,4 +1,4 @@
-// telegram_service/state/delegation.go - новый файл
+// telegram_service/state/handler_delegation.go - новый файл
package state
diff --git a/service/telegram_service/state/state.go b/service/telegram_service/state/state.go
index cdf9779..3d13611 100644
--- a/service/telegram_service/state/state.go
+++ b/service/telegram_service/state/state.go
@@ -19,17 +19,27 @@ type FileAttachment struct {
// ApprovalFlowState — состояние пользователя внутри флоу согласования.
// Хранится в Redis, сбрасывается по TTL или после отправки заявки.
type ApprovalFlowState struct {
- TopicCode string `json:"topic_code"`
- NodeKey string `json:"node_key"`
- Collected map[string]string `json:"collected"`
- AwaitInput bool `json:"await_input"`
- InputKey string `json:"input_key"`
- History []string `json:"history"`
- AwaitFileInput bool `json:"await_file_input"`
- Files []FileAttachment `json:"files"`
- FileStatusMsgID int `json:"file_status_msg_id"`
- SelectedApproverID uint64 `json:"selected_approver_id,omitempty"`
- AwaitApproverSelection bool `json:"await_approver_selection"`
+ TopicCode string `json:"topic_code"`
+ NodeKey string `json:"node_key"`
+ Collected map[string]string `json:"collected"`
+ AwaitInput bool `json:"await_input"`
+ InputKey string `json:"input_key"`
+ History []string `json:"history"`
+ AwaitFileInput bool `json:"await_file_input"`
+ Files []FileAttachment `json:"files"`
+ FileStatusMsgID int `json:"file_status_msg_id"`
+
+ // Выбор первого согласующего по роли
+ AwaitFirstApproverSelection bool `json:"await_first_approver_selection"`
+ SelectedFirstApproverID uint64 `json:"selected_first_approver_id,omitempty"`
+
+ // Выбор основного согласующего
+ AwaitApproverSelection bool `json:"await_approver_selection"`
+ SelectedApproverID uint64 `json:"selected_approver_id,omitempty"`
+
+ // Выбор наблюдателей (мультиселект)
+ AwaitObserverSelection bool `json:"await_observer_selection"`
+ SelectedObserverIDs []uint64 `json:"selected_observer_ids,omitempty"`
}
type StateManager struct {