From d789e4f230b3d0c3c4a5711ed5ac60ef94440eda Mon Sep 17 00:00:00 2001 From: romanskijdev Date: Fri, 13 Nov 2026 11:54:09 +0300 Subject: [PATCH] Update button visability permissions --- .../handlers/approval/handle_multiselect.go | 2 +- .../handlers/approval/handler.go | 6 +- .../handlers/approval/helper.go | 118 +++++++++++++++--- 3 files changed, 108 insertions(+), 18 deletions(-) diff --git a/service/telegram_service/handlers/approval/handle_multiselect.go b/service/telegram_service/handlers/approval/handle_multiselect.go index 11f3164..02ec67d 100644 --- a/service/telegram_service/handlers/approval/handle_multiselect.go +++ b/service/telegram_service/handlers/approval/handle_multiselect.go @@ -60,7 +60,7 @@ func (h *Handler) HandleMultiSelectToggle(bot *tgbotapi.BotAPI, cq *tgbotapi.Cal return } - _ = h.filterNodesByAccess(ctx, telegramID, node.Children) + _ = h.filterNodesByAccess(ctx, telegramID, node.Children, topic, flowState.Collected) editMsg := tgbotapi.NewEditMessageReplyMarkup( chatID, diff --git a/service/telegram_service/handlers/approval/handler.go b/service/telegram_service/handlers/approval/handler.go index b525451..c4ea73a 100644 --- a/service/telegram_service/handlers/approval/handler.go +++ b/service/telegram_service/handlers/approval/handler.go @@ -186,7 +186,7 @@ func (h *Handler) HandleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuer flowState.NodeKey = nodeKey h.States.Set(ctx, telegramID, flowState) //nolint:errcheck - visibleChildren := h.filterNodesByAccess(ctx, telegramID, node.Children) + visibleChildren := h.filterNodesByAccess(ctx, telegramID, node.Children, topic, flowState.Collected) if len(visibleChildren) == 0 { sendText(bot, chatID, "⚠️ У вас нет доступа к подкатегориям этого раздела.") h.States.Clear(ctx, telegramID) @@ -259,7 +259,7 @@ func (h *Handler) HandleTextInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) b if parentNode != nil && len(parentNode.Children) == 1 && parentNode.Children[0].IsInput { inputNode := parentNode.Children[0] if len(inputNode.Children) > 0 { - visibleChildren := h.filterNodesByAccess(ctx, telegramID, inputNode.Children) + visibleChildren := h.filterNodesByAccess(ctx, telegramID, inputNode.Children, topic, flowState.Collected) if len(visibleChildren) == 0 { sendText(bot, chatID, "⚠️ У вас нет доступа к подкатегориям этого раздела.") h.States.Clear(ctx, telegramID) //nolint:errcheck @@ -578,7 +578,7 @@ func (h *Handler) HandleBackCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.Callback h.States.Set(ctx, telegramID, flowState) //nolint:errcheck // Фильтруем по правам - visibleChildren := h.filterNodesByAccess(ctx, telegramID, node.Children) + visibleChildren := h.filterNodesByAccess(ctx, telegramID, node.Children, topic, flowState.Collected) msg := tgbotapi.NewMessage(chatID, "Выберите:") msg.ParseMode = "HTML" diff --git a/service/telegram_service/handlers/approval/helper.go b/service/telegram_service/handlers/approval/helper.go index 8c8410f..fce772d 100644 --- a/service/telegram_service/handlers/approval/helper.go +++ b/service/telegram_service/handlers/approval/helper.go @@ -542,33 +542,123 @@ func (h *Handler) canUserAccessNode(ctx context.Context, userID uint64, topicCod return allowed } -func (h *Handler) filterNodesByAccess(ctx context.Context, telegramID int64, nodes []*approvalflow.FlowNode) []*approvalflow.FlowNode { - // Проверяем нужна ли фильтрация вообще - needsFilter := false - for _, n := range nodes { - if n != nil && n.TopicCode != "" { - needsFilter = true - break - } - } - if !needsFilter { +func (h *Handler) filterNodesByAccess( + ctx context.Context, + telegramID int64, + nodes []*approvalflow.FlowNode, + topic approvalflow.Topic, + currentCollected map[string]string, +) []*approvalflow.FlowNode { + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || user == nil || user.ID == nil { return nodes } - user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) - if err != nil || user == nil || user.ID == nil { - return nodes // не можем проверить — показываем всё + // 1. Собираем все разрешенные коды тем для этого пользователя + categoryCode := topic.Code() + category, err := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByCodeDB(ctx, categoryCode) + if err != nil || category == nil { + return nodes } + var allowedTopicCodes []string + + // Проверяем доступ ко всей категории целиком + if h.canUserAccessNode(ctx, *user.ID, categoryCode) { + allowedTopicCodes = append(allowedTopicCodes, categoryCode) + } + + // Проверяем доступ к отдельным темам внутри категории + allTopics, _, err := h.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalTopic{CategoryID: category.ID}, + }) + if err == nil { + for _, t := range allTopics { + if t.Code != nil && h.canUserAccessNode(ctx, *user.ID, *t.Code) { + allowedTopicCodes = append(allowedTopicCodes, *t.Code) + } + } + } + + // Вспомогательная функция: содержит ли targetCode все элементы хотя бы одного разрешенного кода + isCodePermitted := func(targetCode string) bool { + targetParts := strings.Split(targetCode, "_") + targetMap := make(map[string]bool, len(targetParts)) + for _, p := range targetParts { + targetMap[p] = true + } + + for _, allowedCode := range allowedTopicCodes { + allowedParts := strings.Split(allowedCode, "_") + match := true + for _, p := range allowedParts { + if !targetMap[p] { + match = false + break + } + } + if match { + return true + } + } + return false + } + + // 2. Рекурсивный Lookahead с наследованием + var hasValidLeaf func(n *approvalflow.FlowNode, collected map[string]string) bool + hasValidLeaf = func(n *approvalflow.FlowNode, collected map[string]string) bool { + newCollected := make(map[string]string, len(collected)) + for k, v := range collected { + newCollected[k] = v + } + if n.DataKey != "" { + newCollected[n.DataKey] = n.DataValue + } + + // Проверяем текущий промежуточный узел (если он разрешен, разрешено и все внутри него) + code, err := topic.TopicCodeFromCollected(newCollected) + if err == nil && code != "" { + if isCodePermitted(code) { + return true + } + } + + isLeaf := len(n.Children) == 0 + isInputLeaf := len(n.Children) == 1 && n.Children[0].IsInput + + if isLeaf || isInputLeaf { + return false // Дошли до финала, но ни он сам, ни его родители не разрешены + } + + for _, child := range n.Children { + if hasValidLeaf(child, newCollected) { + return true + } + } + return false + } + + // 3. Итоговая фильтрация var filtered []*approvalflow.FlowNode for _, n := range nodes { if n == nil { continue } - if h.canUserAccessNode(ctx, *user.ID, n.TopicCode) { + + // Статичные коды (например, "Доставка") + if n.TopicCode != "" { + if isCodePermitted(n.TopicCode) { + filtered = append(filtered, n) + } + continue + } + + // Динамические узлы + if hasValidLeaf(n, currentCollected) { filtered = append(filtered, n) } } + return filtered }