From bece903b4d626b6bd54e9e803b03a8834bb73391 Mon Sep 17 00:00:00 2001 From: romanskijdev Date: Tue, 13 Oct 2026 15:49:55 +0300 Subject: [PATCH] Update task delegation table migration --- .../db/db_migration/tables/task_delegation.go | 2 + core/typescore/task_delegations.go | 2 + .../common/update/callback.go | 66 +- .../handlers/approval/handler_decision.go | 2 +- .../approval/handler_delegation_tasks.go | 570 ++++++++++++------ .../handlers/approval/selection_approver.go | 63 +- .../telegram_service/keyboard/delegation.go | 64 ++ service/telegram_service/keyboard/misc.go | 4 +- 8 files changed, 573 insertions(+), 200 deletions(-) diff --git a/core/db/db_migration/tables/task_delegation.go b/core/db/db_migration/tables/task_delegation.go index f6349e6..7c07f5b 100644 --- a/core/db/db_migration/tables/task_delegation.go +++ b/core/db/db_migration/tables/task_delegation.go @@ -26,6 +26,8 @@ func TaskDelegationsTableMigrate(db *gorm.DB) error { // Внешние ключи для связи с таблицей пользователей db.Exec(`ALTER TABLE task_delegations ADD CONSTRAINT fk_task_delegator FOREIGN KEY (delegator_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`) db.Exec(`ALTER TABLE task_delegations ADD CONSTRAINT fk_task_delegate FOREIGN KEY (delegate_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`) + db.Exec(`ALTER TABLE task_delegations ADD CONSTRAINT fk_task_category FOREIGN KEY (category_id) REFERENCES approval_topic_categories(id) ON DELETE CASCADE ON UPDATE CASCADE`) + db.Exec(`ALTER TABLE task_delegations ADD CONSTRAINT fk_task_topic FOREIGN KEY (topic_id) REFERENCES approval_topics(id) ON DELETE CASCADE ON UPDATE CASCADE`) execComments(db, ` COMMENT ON TABLE "task_delegations" IS 'Делегирование прав на задачи'; diff --git a/core/typescore/task_delegations.go b/core/typescore/task_delegations.go index c59db92..58317a0 100644 --- a/core/typescore/task_delegations.go +++ b/core/typescore/task_delegations.go @@ -13,6 +13,8 @@ type TaskDelegation struct { CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"` UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at"` ApprovalID *uint64 `gorm:"type:bigint;index;column:approval_id" json:"approval_id,omitempty" db:"approval_id"` + CategoryID *uint64 `gorm:"type:bigint;index;column:category_id" json:"category_id,omitempty" db:"category_id"` + TopicID *uint64 `gorm:"type:bigint;index;column:topic_id" json:"topic_id,omitempty" db:"topic_id"` Delegator *User `gorm:"-" json:"delegator,omitempty"` Delegate *User `gorm:"-" json:"delegate,omitempty"` diff --git a/service/telegram_service/common/update/callback.go b/service/telegram_service/common/update/callback.go index 20c909e..283b43e 100644 --- a/service/telegram_service/common/update/callback.go +++ b/service/telegram_service/common/update/callback.go @@ -562,6 +562,9 @@ func (s *UpdateHandler) handleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.Callba case data == "appr_appr_back": s.approvalHandler.HandleApproverApprovals(bot, cq.Message.Chat.ID, cq.From.ID) + case data == "deleg_task_all": + s.approvalHandler.HandleTaskDelegationAllTasks(bot, cq) + case strings.HasPrefix(data, "obs_topic_page:"): page := 0 fmt.Sscanf(strings.TrimPrefix(data, "obs_topic_page:"), "%d", &page) @@ -639,14 +642,20 @@ func (s *UpdateHandler) handleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.Callba case data == "deleg_task_create": bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck - s.approvalHandler.HandleTaskDelegationSelectUserPage(bot, cq, 0) + s.approvalHandler.HandleTaskDelegationMenu(bot, cq.Message.Chat.ID, cq.From.ID) case strings.HasPrefix(data, "deleg_task_user_page:"): - page := 0 - fmt.Sscanf(strings.TrimPrefix(data, "deleg_task_user_page:"), "%d", &page) - bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck - bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck - s.approvalHandler.HandleTaskDelegationSelectUserPage(bot, cq, page) + parts := strings.Split(strings.TrimPrefix(data, "deleg_task_user_page:"), ":") + if len(parts) == 3 { + var categoryID, topicID, page uint64 + fmt.Sscanf(parts[0], "%d", &categoryID) + fmt.Sscanf(parts[1], "%d", &topicID) + fmt.Sscanf(parts[2], "%d", &page) + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck + // Передаем все необходимые аргументы + s.approvalHandler.HandleTaskDelegationSelectUserPage(bot, cq, categoryID, topicID, int(page)) + } case strings.HasPrefix(data, "deleg_task_user:"): delegateID := parseID(data, "deleg_task_user:") @@ -687,11 +696,54 @@ func (s *UpdateHandler) handleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.Callba id := parseID(data, "appr_task_deleg_sel:") s.approvalHandler.HandleTaskDelegateSelectionAbsence(bot, cq, id) - // ДОБАВИТЬ ЭТОТ БЛОК: case strings.HasPrefix(data, "appr_task_deleg_pg:"): page := 0 fmt.Sscanf(strings.TrimPrefix(data, "appr_task_deleg_pg:"), "%d", &page) s.approvalHandler.HandleTaskDelegateSelectionPageAbsence(bot, cq, page) + + // ── ФЛОУ ДЕЛЕГИРОВАНИЯ ЗАДАЧ ────────────────────────────────────────── + case strings.HasPrefix(data, "deleg_task_cat_page:"): + page := 0 + fmt.Sscanf(strings.TrimPrefix(data, "deleg_task_cat_page:"), "%d", &page) + s.approvalHandler.HandleTaskDelegationMenuPage(bot, cq.Message.Chat.ID, cq.From.ID, page, cq.Message.MessageID) + + case strings.HasPrefix(data, "deleg_task_category:"): + categoryID := parseID(data, "deleg_task_category:") + s.approvalHandler.HandleTaskDelegationCategoryCallback(bot, cq, categoryID) + + case strings.HasPrefix(data, "deleg_task_all_cat:"): + categoryID := parseID(data, "deleg_task_all_cat:") + s.approvalHandler.HandleTaskDelegationAllCategoryCallback(bot, cq, categoryID) + + case strings.HasPrefix(data, "deleg_task_top_page:"): + parts := strings.Split(strings.TrimPrefix(data, "deleg_task_top_page:"), ":") + if len(parts) == 2 { + var categoryID, page uint64 + fmt.Sscanf(parts[0], "%d", &categoryID) + fmt.Sscanf(parts[1], "%d", &page) + s.approvalHandler.HandleTaskDelegationCategoryCallbackPage(bot, cq, categoryID, int(page)) + } + + case strings.HasPrefix(data, "deleg_task_topic:"): + topicID := parseID(data, "deleg_task_topic:") + s.approvalHandler.HandleTaskDelegationTopicCallback(bot, cq, topicID) + + case strings.HasPrefix(data, "deleg_task_user_page:"): + parts := strings.Split(strings.TrimPrefix(data, "deleg_task_user_page:"), ":") + if len(parts) == 3 { + var categoryID, topicID, page uint64 + fmt.Sscanf(parts[0], "%d", &categoryID) + fmt.Sscanf(parts[1], "%d", &topicID) + fmt.Sscanf(parts[2], "%d", &page) + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck + s.approvalHandler.HandleTaskDelegationSelectUserPage(bot, cq, categoryID, topicID, int(page)) + } + + case strings.HasPrefix(data, "deleg_task_user:"): + delegateID := parseID(data, "deleg_task_user:") + s.approvalHandler.HandleTaskDelegationUserCallback(bot, cq, delegateID) + // ── ПРОЧЕЕ ────────────────────────────────────────────────── case data == "restart_bot": bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck diff --git a/service/telegram_service/handlers/approval/handler_decision.go b/service/telegram_service/handlers/approval/handler_decision.go index 92a7ceb..9caaaf6 100644 --- a/service/telegram_service/handlers/approval/handler_decision.go +++ b/service/telegram_service/handlers/approval/handler_decision.go @@ -210,7 +210,7 @@ func (h *Handler) processNextStepOrComplete(bot *tgbotapi.BotAPI, ctx context.Co approval.Status = &approvedStatus h.ipc.Database.Approval.UpdateApprovalDB(ctx, nil, approval) //nolint:errcheck - h.activatePendingDelegation(ctx, approval) + h.activatePendingDelegation(bot, ctx, approval) lastStepIsDelegate := currentStep.ApproverID != nil && *currentStep.ApproverID != actualExecutorID diff --git a/service/telegram_service/handlers/approval/handler_delegation_tasks.go b/service/telegram_service/handlers/approval/handler_delegation_tasks.go index 28e53f0..bedbe02 100644 --- a/service/telegram_service/handlers/approval/handler_delegation_tasks.go +++ b/service/telegram_service/handlers/approval/handler_delegation_tasks.go @@ -8,6 +8,7 @@ import ( "bitrix_balancer_api/telegram_service/state" "context" "fmt" + "sort" "strings" "time" @@ -15,184 +16,6 @@ import ( "github.com/sirupsen/logrus" ) -// HandleTaskDelegationSelectUserPage показывает список сотрудников для делегирования задач -func (h *Handler) HandleTaskDelegationSelectUserPage(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, page int) { - ctx := context.Background() - chatID := cq.Message.Chat.ID - telegramID := cq.From.ID - - user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) - if err != nil || user == nil || user.ID == nil { - return - } - - users, _, err := h.ipc.Database.User.GetUsersListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.User{ - IsBlocked: utilscore.PointerToBool(false), - }, - }) - if err != nil { - logrus.Errorf("HandleTaskDelegationSelectUserPage: GetUsersListDB err=%v", err) - return - } - - var availableUsers []*typescore.User - for _, u := range users { - if u.ID != nil && *u.ID != *user.ID { - availableUsers = append(availableUsers, u) - } - } - - if len(availableUsers) == 0 { - sendText(bot, chatID, "Нет доступных пользователей для делегирования.") - return - } - - msg := tgbotapi.NewMessage(chatID, "📋 Делегирование задач\n\nВыберите пользователя, которому хотите передать свои задачи:") - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildTaskDelegationUserMenu(availableUsers, page) - bot.Send(msg) //nolint:errcheck -} - -// HandleTaskDelegationUserCallback сохраняет выбранного делегата и запрашивает дату -func (h *Handler) HandleTaskDelegationUserCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, delegateID 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 - - user, _ := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) - if user == nil || user.ID == nil { - return - } - - // Проверяем, нет ли уже активного делегирования всех задач (можно передать только одному человеку) - existingDelegations, _, err := h.ipc.Database.TaskDelegation.GetTaskDelegationsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.TaskDelegation{ - DelegatorID: user.ID, - IsActive: utilscore.PointerToBool(true), - }, - }) - if err == nil && len(existingDelegations) > 0 { - sendText(bot, chatID, "⚠️ У вас уже есть активное делегирование задач.\nСначала отзовите его в меню «Мои делегирования (Задачи)».") - return - } - - // Сохраняем стейт (переиспользуем DelegationFlowState, но с особым Stage) - h.States.SetDelegation(ctx, telegramID, &state.DelegationFlowState{ - DelegateID: delegateID, - Stage: "task_input_date", - }) //nolint:errcheck - - delegate, _ := h.ipc.Database.User.GetUserByIDDB(ctx, delegateID) - delegateName := "—" - if delegate != nil && delegate.FullName != nil { - delegateName = *delegate.FullName - } - - msg := tgbotapi.NewMessage(chatID, fmt.Sprintf( - "👤 Делегат для задач: %s\n\n"+ - "Введите дату и время окончания делегирования в формате:\n"+ - "ДД.ММ.ГГГГ ЧЧ:ММ или ДД.ММ.ГГГГ\n\n"+ - "Например: 31.12.2024 18:00 или 31.12.2024", - delegateName, - )) - msg.ParseMode = "HTML" - msg.ReplyMarkup = tgkit.NewInlineKeyboard(). - Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "Отмена", "deleg_task_create")). - Build() - bot.Send(msg) //nolint:errcheck -} - -// HandleTaskDelegationDateInput перехватывает ввод текста с датой -func (h *Handler) HandleTaskDelegationDateInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) bool { - ctx := context.Background() - telegramID := msg.From.ID - chatID := msg.Chat.ID - - delegationState, err := h.States.GetDelegation(ctx, telegramID) - if err != nil || delegationState == nil || delegationState.Stage != "task_input_date" { - return false // Не наше состояние, отдаем дальше по цепочке - } - - dateStr := strings.TrimSpace(msg.Text) - var validUntil time.Time - - if t, err := time.Parse("02.01.2006 15:04", dateStr); err == nil { - validUntil = t - } else if t, err := time.Parse("02.01.2006", dateStr); err == nil { - validUntil = time.Date(t.Year(), t.Month(), t.Day(), 23, 59, 59, 0, t.Location()) - } else { - sendText(bot, chatID, "⚠️ Неверный формат даты. Используйте ДД.ММ.ГГГГ ЧЧ:ММ или ДД.ММ.ГГГГ") - return true // Состояние наше, но ошибка ввода - } - - if validUntil.Before(time.Now()) { - sendText(bot, chatID, "⚠️ Дата окончания не может быть в прошлом.") - return true - } - - user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) - if err != nil || user == nil || user.ID == nil { - return true - } - - isActive := true - notifiedFalse := false - delegation := &typescore.TaskDelegation{ - DelegatorID: user.ID, - DelegateID: &delegationState.DelegateID, - ValidUntil: &validUntil, - IsActive: &isActive, - NotifiedDay: ¬ifiedFalse, - Notified2h: ¬ifiedFalse, - } - - _, _, err = h.ipc.Database.TaskDelegation.CreateTaskDelegationDB(ctx, nil, delegation) - if err != nil { - logrus.Errorf("HandleTaskDelegationDateInput: CreateTaskDelegationDB err=%v", err) - sendText(bot, chatID, "Ошибка при создании делегирования задач.") - return true - } - - h.States.ClearDelegation(ctx, telegramID) // Очищаем состояние - - delegate, _ := h.ipc.Database.User.GetUserByIDDB(ctx, delegationState.DelegateID) - delegateName := "—" - if delegate != nil && delegate.FullName != nil { - delegateName = *delegate.FullName - } - - sendText(bot, chatID, fmt.Sprintf( - "✅ Задачи делегированы\n\n"+ - "👤 Кому: %s\n"+ - "📅 Действует до: %s\n\n"+ - "Теперь все новые задачи будут приходить этому сотруднику.", - delegateName, validUntil.Format("02.01.2006 15:04"), - )) - - // Уведомляем делегата - if delegate != nil && delegate.TelegramID != nil { - delegatorName := "—" - if user.FullName != nil { - delegatorName = *user.FullName - } - notifyMsg := tgbotapi.NewMessage(*delegate.TelegramID, fmt.Sprintf( - "🔄 Вам делегировано исполнение задач\n\n"+ - "👤 От: %s\n"+ - "📅 До: %s\n\n"+ - "В этот период все задачи этого пользователя будут поступать вам.", - delegatorName, validUntil.Format("02.01.2006 15:04"), - )) - notifyMsg.ParseMode = "HTML" - bot.Send(notifyMsg) //nolint:errcheck - } - - return true -} - func (h *Handler) HandleTaskDelegatedRightsList(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) { h.HandleTaskDelegatedRightsListPage(bot, chatID, telegramID, 0, 0) } @@ -412,3 +235,394 @@ func (h *Handler) HandleTaskDelegationExtendInput(bot *tgbotapi.BotAPI, msg *tgb return true } + +func (h *Handler) HandleTaskDelegationMenu(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) { + h.HandleTaskDelegationMenuPage(bot, chatID, telegramID, 0, 0) +} + +func (h *Handler) HandleTaskDelegationMenuPage(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, page int, prevMessageID int) { + ctx := context.Background() + + // Получаем список всех активных категорий + categories, _, err := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalTopicCategory{IsActive: utilscore.PointerToBool(true)}, + }) + if err != nil { + logrus.Errorf("HandleTaskDelegationMenuPage: GetApprovalTopicCategoryListDB err=%v", err) + sendText(bot, chatID, "Ошибка при получении списка категорий.") + return + } + + if prevMessageID != 0 { + bot.Request(tgbotapi.NewCallback(fmt.Sprintf("%d", prevMessageID), "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(chatID, prevMessageID)) //nolint:errcheck + } + + msg := tgbotapi.NewMessage(chatID, "📋 Делегирование задач\n\nВыберите, какие задачи вы хотите делегировать:") + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildTaskDelegationCategoryMenu(categories, page) + bot.Send(msg) //nolint:errcheck +} + +// HandleTaskDelegationAllTasks — выбор "Глобально (Все задачи)" +func (h *Handler) HandleTaskDelegationAllTasks(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery) { + h.HandleTaskDelegationSelectUserPage(bot, cq, 0, 0, 0) +} + +func (h *Handler) HandleTaskDelegationCategoryCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, categoryID uint64) { + h.HandleTaskDelegationCategoryCallbackPage(bot, cq, categoryID, 0) +} + +func (h *Handler) HandleTaskDelegationCategoryCallbackPage(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, categoryID uint64, page int) { + ctx := context.Background() + chatID := cq.Message.Chat.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck + + category, _ := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, categoryID) + categoryName := "—" + if category != nil && category.Name != nil { + categoryName = *category.Name + } + + topics, _, err := h.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalTopic{CategoryID: &categoryID}, + }) + if err != nil { + return + } + + msg := tgbotapi.NewMessage(chatID, fmt.Sprintf("📋 Категория: %s\n\nВыберите тему или делегируйте всю категорию целиком:", categoryName)) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildTaskDelegationTopicMenu(topics, categoryID, page) + bot.Send(msg) //nolint:errcheck +} + +func (h *Handler) HandleTaskDelegationAllCategoryCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, categoryID uint64) { + h.HandleTaskDelegationSelectUserPage(bot, cq, categoryID, 0, 0) +} + +func (h *Handler) HandleTaskDelegationTopicCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, topicID uint64) { + ctx := context.Background() + topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, topicID) + if topic == nil || topic.CategoryID == nil { + return + } + h.HandleTaskDelegationSelectUserPage(bot, cq, *topic.CategoryID, topicID, 0) +} + +func (h *Handler) HandleTaskDelegationSelectUserPage(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, categoryID, topicID uint64, page int) { + 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 + + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || user == nil || user.ID == nil { + return + } + + // Сохраняем стейт выбора (Глобально/Категория/Тема) + h.States.SetDelegation(ctx, telegramID, &state.DelegationFlowState{ + CategoryID: categoryID, + TopicID: topicID, + Stage: "task_select_user", + }) //nolint:errcheck + + users, _, err := h.ipc.Database.User.GetUsersListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.User{IsBlocked: utilscore.PointerToBool(false)}, + Limit: utilscore.PointerToUint64(1000), + }) + if err != nil { + return + } + + var availableUsers []*typescore.User + for _, u := range users { + if u.ID != nil && *u.ID != *user.ID { + availableUsers = append(availableUsers, u) + } + } + + if len(availableUsers) == 0 { + sendText(bot, chatID, "Нет доступных пользователей для делегирования.") + return + } + + // 🚀 СОРТИРОВКА ПО АЛФАВИТУ + sort.Slice(availableUsers, func(i, j int) bool { + nameI, nameJ := "", "" + if availableUsers[i].FullName != nil { + nameI = *availableUsers[i].FullName + } + if availableUsers[j].FullName != nil { + nameJ = *availableUsers[j].FullName + } + return nameI < nameJ + }) + + scopeName := "🌍 Все задачи" + if topicID > 0 { + topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, topicID) + if topic != nil && topic.Name != nil { + scopeName = "Тема: " + *topic.Name + } + } else if categoryID > 0 { + category, _ := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, categoryID) + if category != nil && category.Name != nil { + scopeName = "Категория: " + *category.Name + " (все задачи)" + } + } + + msg := tgbotapi.NewMessage(chatID, fmt.Sprintf("📋 Объем: %s\n\nВыберите сотрудника:", scopeName)) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildTaskDelegationUserMenu(availableUsers, page) + // Обратите внимание: если ваша кнопка возврата в UserMenu ведет в меню, нужно чтобы она корректно работала + // (в BuildTaskDelegationUserMenu можно сделать кнопку Назад: "deleg_task_create"). + bot.Send(msg) //nolint:errcheck +} + +func (h *Handler) HandleTaskDelegationUserCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, delegateID 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 + + delegationState, err := h.States.GetDelegation(ctx, telegramID) + if err != nil || delegationState == nil { + sendText(bot, chatID, "⚠️ Состояние делегирования утеряно. Начните заново.") + return + } + + user, _ := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if user == nil || user.ID == nil { + return + } + + // 🚀 ПРОВЕРКА КОНФЛИКТОВ ДЕЛЕГИРОВАНИЯ ЗАДАЧ + existingDelegations, _, err := h.ipc.Database.TaskDelegation.GetTaskDelegationsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.TaskDelegation{ + DelegatorID: user.ID, + IsActive: utilscore.PointerToBool(true), + }, + }) + if err == nil { + for _, d := range existingDelegations { + if h.isTaskDelegationConflict(ctx, d, delegationState.CategoryID, delegationState.TopicID) { + h.sendTaskDelegationConflictMessage(bot, chatID, d, telegramID) + return + } + } + } + + delegationState.DelegateID = delegateID + delegationState.Stage = "task_input_date" + h.States.SetDelegation(ctx, telegramID, delegationState) //nolint:errcheck + + delegate, _ := h.ipc.Database.User.GetUserByIDDB(ctx, delegateID) + delegateName := "—" + if delegate != nil && delegate.FullName != nil { + delegateName = *delegate.FullName + } + + msg := tgbotapi.NewMessage(chatID, fmt.Sprintf( + "👤 Делегат для задач: %s\n\n"+ + "Введите дату и время окончания делегирования в формате:\n"+ + "ДД.ММ.ГГГГ ЧЧ:ММ или ДД.ММ.ГГГГ\n\n"+ + "Например: 31.12.2024 18:00", + delegateName, + )) + msg.ParseMode = "HTML" + msg.ReplyMarkup = tgkit.NewInlineKeyboard().Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "Отмена", "deleg_task_create")).Build() + bot.Send(msg) //nolint:errcheck +} + +func (h *Handler) HandleTaskDelegationDateInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) bool { + ctx := context.Background() + telegramID := msg.From.ID + chatID := msg.Chat.ID + + delegationState, err := h.States.GetDelegation(ctx, telegramID) + if err != nil || delegationState == nil || delegationState.Stage != "task_input_date" { + return false + } + + dateStr := strings.TrimSpace(msg.Text) + var validUntil time.Time + + if t, err := time.Parse("02.01.2006 15:04", dateStr); err == nil { + validUntil = t + } else if t, err := time.Parse("02.01.2006", dateStr); err == nil { + validUntil = time.Date(t.Year(), t.Month(), t.Day(), 23, 59, 59, 0, t.Location()) + } else { + sendText(bot, chatID, "⚠️ Неверный формат даты. Используйте ДД.ММ.ГГГГ ЧЧ:ММ или ДД.ММ.ГГГГ") + return true + } + + if validUntil.Before(time.Now()) { + sendText(bot, chatID, "⚠️ Дата окончания не может быть в прошлом.") + return true + } + + user, _ := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if user == nil || user.ID == nil { + return true + } + + isActive := true + notifiedFalse := false + delegation := &typescore.TaskDelegation{ + DelegatorID: user.ID, + DelegateID: &delegationState.DelegateID, + ValidUntil: &validUntil, + IsActive: &isActive, + NotifiedDay: ¬ifiedFalse, + Notified2h: ¬ifiedFalse, + } + + if delegationState.TopicID > 0 { + delegation.TopicID = &delegationState.TopicID + } + if delegationState.CategoryID > 0 { + delegation.CategoryID = &delegationState.CategoryID + } + + _, _, err = h.ipc.Database.TaskDelegation.CreateTaskDelegationDB(ctx, nil, delegation) + if err != nil { + sendText(bot, chatID, "Ошибка при создании делегирования задач.") + return true + } + + h.States.ClearDelegation(ctx, telegramID) + + scopeName := "🌍 Все задачи" + if delegationState.TopicID > 0 { + topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, delegationState.TopicID) + if topic != nil && topic.Name != nil { + scopeName = "Тема: " + *topic.Name + } + } else if delegationState.CategoryID > 0 { + category, _ := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, delegationState.CategoryID) + if category != nil && category.Name != nil { + scopeName = "Категория: " + *category.Name + } + } + + delegate, _ := h.ipc.Database.User.GetUserByIDDB(ctx, delegationState.DelegateID) + delegateName := "—" + if delegate != nil && delegate.FullName != nil { + delegateName = *delegate.FullName + } + + sendText(bot, chatID, fmt.Sprintf( + "✅ Задачи делегированы\n\n"+ + "📋 Объем: %s\n"+ + "👤 Кому: %s\n"+ + "📅 Действует до: %s", + scopeName, delegateName, validUntil.Format("02.01.2006 15:04"), + )) + + if delegate != nil && delegate.TelegramID != nil { + delegatorName := "—" + if user.FullName != nil { + delegatorName = *user.FullName + } + notifyMsg := tgbotapi.NewMessage(*delegate.TelegramID, fmt.Sprintf( + "🔄 Вам делегировано исполнение задач\n\n"+ + "👤 От: %s\n"+ + "📋 Объем: %s\n"+ + "📅 До: %s", + delegatorName, scopeName, validUntil.Format("02.01.2006 15:04"), + )) + notifyMsg.ParseMode = "HTML" + bot.Send(notifyMsg) //nolint:errcheck + } + + return true +} + +// isTaskDelegationConflict определяет, есть ли конфликт между существующим делегированием и новым +func (h *Handler) isTaskDelegationConflict(ctx context.Context, d *typescore.TaskDelegation, newCategoryID, newTopicID uint64) bool { + // 1. Если существующее делегирование Глобальное (все задачи) -> оно конфликтует с чем угодно. + if d.TopicID == nil && d.CategoryID == nil { + return true + } + // 2. Если мы пытаемся создать Глобальное делегирование -> оно конфликтует, если есть ХОТЬ ЧТО-ТО активное. + if newTopicID == 0 && newCategoryID == 0 { + return true + } + // 3. Если существующее делегирование - Категория + if d.TopicID == nil && d.CategoryID != nil { + if *d.CategoryID == newCategoryID { + return true // пытаемся делегировать ту же категорию или тему в ней + } + if newTopicID > 0 { + topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, newTopicID) + if topic != nil && topic.CategoryID != nil && *topic.CategoryID == *d.CategoryID { + return true // пытаемся делегировать тему, категория которой уже делегирована + } + } + } + // 4. Если существующее делегирование - Тема + if d.TopicID != nil { + if newTopicID > 0 && *d.TopicID == newTopicID { + return true // Делегирована та же тема + } + if newTopicID == 0 && newCategoryID > 0 { + topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *d.TopicID) + if topic != nil && topic.CategoryID != nil && *topic.CategoryID == newCategoryID { + return true // Пытаемся делегировать всю категорию, но одна из тем в ней уже делегирована + } + } + } + return false +} + +// sendTaskDelegationConflictMessage отправляет сообщение о конфликте +func (h *Handler) sendTaskDelegationConflictMessage(bot *tgbotapi.BotAPI, chatID int64, existing *typescore.TaskDelegation, telegramID int64) { + ctx := context.Background() + + scopeName := "🌍 Все задачи" + if existing.TopicID != nil { + topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *existing.TopicID) + if topic != nil && topic.Name != nil { + scopeName = "Тема: " + *topic.Name + } + } else if existing.CategoryID != nil { + category, _ := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *existing.CategoryID) + if category != nil && category.Name != nil { + scopeName = "Категория: " + *category.Name + } + } + + delegateName := "—" + if existing.DelegateID != nil { + delegate, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *existing.DelegateID) + if delegate != nil && delegate.FullName != nil { + delegateName = *delegate.FullName + } + } + + validUntil := "—" + if existing.ValidUntil != nil { + validUntil = existing.ValidUntil.Format("02.01.2006 15:04") + } + + msg := tgbotapi.NewMessage(chatID, fmt.Sprintf( + "⚠️ Конфликт делегирования задач\n\n"+ + "Эти задачи (или их часть) уже делегированы:\n"+ + "📋 Объем: %s\n"+ + "👤 Делегат: %s\n"+ + "📅 Действует до: %s\n\n"+ + "Сначала отзовите текущее делегирование в меню «Мои делегирования (Задачи)».", + scopeName, delegateName, validUntil, + )) + msg.ParseMode = "HTML" + bot.Send(msg) //nolint:errcheck + h.States.ClearDelegation(ctx, telegramID) //nolint:errcheck +} diff --git a/service/telegram_service/handlers/approval/selection_approver.go b/service/telegram_service/handlers/approval/selection_approver.go index bf85214..804cf7c 100644 --- a/service/telegram_service/handlers/approval/selection_approver.go +++ b/service/telegram_service/handlers/approval/selection_approver.go @@ -475,24 +475,64 @@ func (h *Handler) sendConfirmationCard(bot *tgbotapi.BotAPI, ctx context.Context // getActualTaskExecutor проверяет, не делегировал ли оригинальный исполнитель свои задачи. // Возвращает: (Актуальный исполнитель, Было ли делегирование, Оригинальный исполнитель) -func (h *Handler) getActualTaskExecutor(ctx context.Context, originalExecutor *typescore.User) (*typescore.User, bool, *typescore.User) { - if originalExecutor == nil || originalExecutor.ID == nil { +func (h *Handler) getActualTaskExecutor(ctx context.Context, originalExecutor *typescore.User, topicID *uint64) (*typescore.User, bool, *typescore.User) { + if originalExecutor == nil || originalExecutor.ID == nil || topicID == nil { return originalExecutor, false, nil } - delegations, _, err := h.ipc.Database.TaskDelegation.GetTaskDelegationsListDB(ctx, typescore.ListDbOptions{ + topic, err := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *topicID) + if err != nil || topic == nil { + return originalExecutor, false, nil + } + + // Функция для поиска активного делегата по фильтру + findDelegate := func(filter *typescore.TaskDelegation) *typescore.User { + delegations, _, err := h.ipc.Database.TaskDelegation.GetTaskDelegationsListDB(ctx, typescore.ListDbOptions{ + Filtering: filter, + }) + if err == nil && len(delegations) > 0 { + deleg := delegations[0] + if deleg.ValidUntil != nil && deleg.ValidUntil.After(time.Now()) && deleg.DelegateID != nil { + if delegateUser, err := h.ipc.Database.User.GetUserByIDDB(ctx, *deleg.DelegateID); err == nil && delegateUser != nil { + return delegateUser + } + } + } + return nil + } + + if delegate := findDelegate(&typescore.TaskDelegation{ + DelegatorID: originalExecutor.ID, + TopicID: topicID, + IsActive: utilscore.PointerToBool(true), + }); delegate != nil { + return delegate, true, originalExecutor + } + + if topic.CategoryID != nil { + if delegate := findDelegate(&typescore.TaskDelegation{ + DelegatorID: originalExecutor.ID, + CategoryID: topic.CategoryID, + IsActive: utilscore.PointerToBool(true), + }); delegate != nil { + return delegate, true, originalExecutor + } + } + + globalDelegations, _, err := h.ipc.Database.TaskDelegation.GetTaskDelegationsListDB(ctx, typescore.ListDbOptions{ Filtering: &typescore.TaskDelegation{ DelegatorID: originalExecutor.ID, IsActive: utilscore.PointerToBool(true), }, }) - - if err == nil && len(delegations) > 0 { - deleg := delegations[0] - if deleg.ValidUntil != nil && deleg.ValidUntil.After(time.Now()) && deleg.DelegateID != nil { - delegateUser, err := h.ipc.Database.User.GetUserByIDDB(ctx, *deleg.DelegateID) - if err == nil && delegateUser != nil { - return delegateUser, true, originalExecutor + if err == nil { + for _, deleg := range globalDelegations { + if deleg.TopicID == nil && deleg.CategoryID == nil && deleg.ValidUntil != nil && deleg.ValidUntil.After(time.Now()) { + if deleg.DelegateID != nil { + if delegateUser, err := h.ipc.Database.User.GetUserByIDDB(ctx, *deleg.DelegateID); err == nil && delegateUser != nil { + return delegateUser, true, originalExecutor + } + } } } } @@ -559,8 +599,7 @@ func (h *Handler) createTasksForApproval( continue } - // 🚀 ПРОВЕРКА ДЕЛЕГИРОВАНИЯ - actualExecutor, isDelegated, origExec := h.getActualTaskExecutor(ctx, originalExecutor) + actualExecutor, isDelegated, origExec := h.getActualTaskExecutor(ctx, originalExecutor, approval.TopicID) taskText := *topicExec.TaskText diff --git a/service/telegram_service/keyboard/delegation.go b/service/telegram_service/keyboard/delegation.go index 918068f..88e76f2 100644 --- a/service/telegram_service/keyboard/delegation.go +++ b/service/telegram_service/keyboard/delegation.go @@ -256,3 +256,67 @@ func BuildTaskDelegationExtendCancel(delegationID uint64) interface{} { Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "Отмена", fmt.Sprintf("deleg_task_detail:%d", delegationID))). Build() } + +func BuildTaskDelegationCategoryMenu(categories []*typescore.ApprovalTopicCategory, page int) interface{} { + const perPage = 6 + total := len(categories) + totalPages := (total + perPage - 1) / perPage + if page < 0 { + page = 0 + } + if page >= totalPages && totalPages > 0 { + page = totalPages - 1 + } + start, end := page*perPage, page*perPage+perPage + if end > total { + end = total + } + + kb := tgkit.NewInlineKeyboard() + // Кнопка для делегирования ВСЕХ задач разом + kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "🌍 Все задачи (Глобально)", "deleg_task_all")) + + for _, c := range categories[start:end] { + if c.ID == nil || c.Name == nil { + continue + } + kb.Row(tgkit.Btn(*c.Name, fmt.Sprintf("deleg_task_category:%d", *c.ID))) + } + if totalPages > 1 { + kb.Rows = append(kb.Rows, buildPageRow(page, totalPages, "deleg_task_cat_page", "deleg_page_noop")) + } + kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "В главное меню", "deleg_main_menu")) + return kb.Build() +} + +func BuildTaskDelegationTopicMenu(topics []*typescore.ApprovalTopic, categoryID uint64, page int) interface{} { + const perPage = 6 + total := len(topics) + totalPages := (total + perPage - 1) / perPage + if page < 0 { + page = 0 + } + if page >= totalPages && totalPages > 0 { + page = totalPages - 1 + } + start, end := page*perPage, page*perPage+perPage + if end > total { + end = total + } + + kb := tgkit.NewInlineKeyboard() + // Кнопка для делегирования всех задач внутри конкретной категории + kb.Row(tgkit.BtnStyled(tgkit.ButtonStylePrimary, "📂 Вся категория", fmt.Sprintf("deleg_task_all_cat:%d", categoryID))) + + for _, t := range topics[start:end] { + if t.ID == nil || t.Name == nil { + continue + } + kb.Row(tgkit.Btn(*t.Name, fmt.Sprintf("deleg_task_topic:%d", *t.ID))) + } + if totalPages > 1 { + kb.Rows = append(kb.Rows, buildPageRow(page, totalPages, fmt.Sprintf("deleg_task_top_page:%d", categoryID), "deleg_page_noop")) + } + kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "К категориям", "deleg_task_create")) + return kb.Build() +} diff --git a/service/telegram_service/keyboard/misc.go b/service/telegram_service/keyboard/misc.go index 9327b83..601bf8c 100644 --- a/service/telegram_service/keyboard/misc.go +++ b/service/telegram_service/keyboard/misc.go @@ -360,8 +360,8 @@ func BuildTaskTransferConfirmation(transferID uint64) tgbotapi.InlineKeyboardMar func BuildRevocationApprovalDecision(approvalID uint64, requestID uint64, commentsCount int) tgbotapi.InlineKeyboardMarkup { return tgkit.NewInlineKeyboard(). Row( - tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "✅ Да", fmt.Sprintf("revoke_appr_yes:%d", requestID)), - tgkit.BtnStyled(tgkit.ButtonStyleDanger, "❌ Нет", fmt.Sprintf("revoke_appr_no:%d", requestID)), + tgkit.BtnStyled(tgkit.ButtonStyleSuccess, " Да", fmt.Sprintf("revoke_appr_yes:%d", requestID)), + tgkit.BtnStyled(tgkit.ButtonStyleDanger, " Нет", fmt.Sprintf("revoke_appr_no:%d", requestID)), ). Row( tgkit.Btn("💬 Добавить комментарий", fmt.Sprintf("appr_comment:%d", approvalID)), -- 2.43.0