diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml index ff79913..d2e52a3 100644 --- a/.gitea/workflows/deploy.yml +++ b/.gitea/workflows/deploy.yml @@ -6,7 +6,7 @@ on: env: REPO_DIR: "/workspace/ruspet_portal_back" - REPO_URL: "https://${{ github.actor }}:${{ github.token }}@72.56.235.246.nip.io/gitea/romanskijdev/ruspet_portal_back.git" + REPO_URL: "https://${{ github.actor }}:${{ github.token }}@git.ruspet-preforma.ru/romanskijdev/ruspet_portal_back.git" BACKUP_DIR: "/tmp/deploy_backups" TELEGRAM_SERVICE: "telegram_service" @@ -28,7 +28,6 @@ jobs: echo "Branch: ${{ github.ref }}" echo "Commit: ${{ github.sha }}" echo "Author: ${{ github.actor }}" - echo "Message: ${{ github.event.head_commit.message }}" echo "Time: $(date '+%Y-%m-%d %H:%M:%S')" echo "Runner: $(hostname)" echo "User: $(whoami)" @@ -182,7 +181,6 @@ jobs: echo "✅ System service deployed" echo "MIGRATIONS_DEPLOYED=true" >> $GITHUB_ENV sleep 3 - # Check if the service FAILED, rather than if it is ACTIVE if ! sudo /usr/bin/systemctl is-failed --quiet "$MIGRATIONS_SERVICE"; then echo "✅ System service executed successfully" else diff --git a/core/db/methods/monthly_orders.go b/core/db/methods/monthly_orders.go index 25fc5eb..7bae48b 100644 --- a/core/db/methods/monthly_orders.go +++ b/core/db/methods/monthly_orders.go @@ -141,12 +141,23 @@ func (db *MonthlyOrderDB) SaveSettings(ctx context.Context, tx pgx.Tx, setting * return errors.New("setting is nil") } + // Оставляем вашу логику обработки указателей (хотя для pgx можно было бы передавать указатели напрямую, чтобы писался реальный NULL) + marketStage := "" + marketStageComment := "" + + if setting.MarketStageComment != nil { + marketStageComment = *setting.MarketStageComment + } + if setting.MarketStage != nil { + marketStage = *setting.MarketStage + } + return dbutils.ExecuteTx(ctx, db.pool, tx, func(tx pgx.Tx) error { query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). Insert(string(dbcoretablenames.TableNameMonthlyOrderSettings)). - Columns("month", "year", "deadline_date", "assembly_time_days"). - Values(*setting.Month, *setting.Year, *setting.DeadlineDate, *setting.AssemblyTimeDays). - Suffix("ON CONFLICT (month, year) DO UPDATE SET deadline_date = EXCLUDED.deadline_date, assembly_time_days = EXCLUDED.assembly_time_days, updated_at = NOW()") + Columns("month", "year", "deadline_date", "assembly_time_days", "market_stage", "market_stage_comment"). + Values(*setting.Month, *setting.Year, *setting.DeadlineDate, *setting.AssemblyTimeDays, marketStage, marketStageComment). + Suffix("ON CONFLICT (month, year) DO UPDATE SET deadline_date = EXCLUDED.deadline_date, assembly_time_days = EXCLUDED.assembly_time_days, market_stage = EXCLUDED.market_stage, market_stage_comment = EXCLUDED.market_stage_comment, updated_at = NOW()") sqlV, args, err := query.ToSql() if err != nil { diff --git a/core/db/methods/user_hierarchy.go b/core/db/methods/user_hierarchy.go index 15fb563..65f132f 100644 --- a/core/db/methods/user_hierarchy.go +++ b/core/db/methods/user_hierarchy.go @@ -208,7 +208,7 @@ func (u *UserHierarchyDB) GetApproversDB( SELECT t.id, LENGTH(t.code) as spec_score FROM approval_topics t CROSS JOIN target_topic tt - WHERE strpos(tt.code || '_', t.code || '_') = 1 + WHERE string_to_array(t.code, '_') <@ string_to_array(tt.code, '_') AND t.category_id = tt.category_id ), ranked AS ( @@ -285,7 +285,6 @@ func (u *UserHierarchyDB) GetApproversDB( return approvers, nil } -// GetHierarchiesWithRelations(ctx context.Context, opts typescore.ListDbOptions, userStatus string) ([]*typescore.UserHierarchy, uint64, error) func (u *UserHierarchyDB) GetHierarchiesWithRelations(ctx context.Context, opts typescore.ListDbOptions, userStatuses ...string) ([]*typescore.UserHierarchy, uint64, error) { options, filter, err := dbutils.GetOptionsDB[typescore.UserHierarchy](opts) if err != nil { diff --git a/core/typescore/monthly_orders.go b/core/typescore/monthly_orders.go index 44fd618..999ec2b 100644 --- a/core/typescore/monthly_orders.go +++ b/core/typescore/monthly_orders.go @@ -4,13 +4,15 @@ import "time" // MonthlyOrderSetting — настройки периода заказа (задаются аналитиком) type MonthlyOrderSetting struct { - ID *uint64 `json:"id" db:"id" gorm:"primaryKey;autoIncrement"` - Month *int `json:"month" db:"month"` - Year *int `json:"year" db:"year"` - DeadlineDate *time.Time `json:"deadline_date" db:"deadline_date"` // Дата закрытия доступа - AssemblyTimeDays *int `json:"assembly_time_days" db:"assembly_time_days"` // Срок сборки заказа (задается аналитиком) - CreatedAt *time.Time `json:"created_at" db:"created_at"` - UpdatedAt *time.Time `json:"updated_at" db:"updated_at"` + ID *uint64 `json:"id" db:"id" gorm:"primaryKey;autoIncrement"` + Month *int `json:"month" db:"month"` + Year *int `json:"year" db:"year"` + DeadlineDate *time.Time `json:"deadline_date" db:"deadline_date"` // Дата закрытия доступа + MarketStage *string `json:"market_stage" db:"market_stage"` // Стадия рынка (растущий, падающий, стоячий) + MarketStageComment *string `json:"market_stage_comment" db:"market_stage_comment"` // Комментарий к стадии рынка (растущий, падающий, стоячий) + AssemblyTimeDays *int `json:"assembly_time_days" db:"assembly_time_days"` // Срок сборки заказа (задается аналитиком) + CreatedAt *time.Time `json:"created_at" db:"created_at"` + UpdatedAt *time.Time `json:"updated_at" db:"updated_at"` } // MonthlyOrderClient — заказ конкретного клиента у менеджера diff --git a/core/variables/const.go b/core/variables/const.go index ef00c5e..b9f6885 100644 --- a/core/variables/const.go +++ b/core/variables/const.go @@ -11,7 +11,7 @@ const ( // Константы для нового API-прокси const ( - ProxyForwardURL = "https://37.252.5.229.nip.io/forward" + ProxyForwardURL = "https://38.180.230.177.nip.io/forward" ProxySecretHeader = "X-Proxy-Secret" ProxySecretKey = "9cb0a2655bde593de45b2f3fd17f39e5" ) diff --git a/go.work b/go.work index ad95d52..75b0c10 100644 --- a/go.work +++ b/go.work @@ -1,10 +1,10 @@ -go 1.25.6 +go 1.26.10 use ( - core ./service/rest_balancer_service - service/telegram_service - service/system_service + core service/rest_admin_service service/rest_telephony_service + service/system_service + service/telegram_service ) diff --git a/service/rest_admin_service/cmd/app.go b/service/rest_admin_service/cmd/app.go index acb9335..d183188 100644 --- a/service/rest_admin_service/cmd/app.go +++ b/service/rest_admin_service/cmd/app.go @@ -170,7 +170,7 @@ func initBaseApiRouter(ipc *typesm.InternalProviderControl) (*chi.Mux, error) { corsOptions := cors.New(cors.Options{ AllowedOrigins: ipc.Config.Server.RESTAdminService.Cors.AllowedOrigins, // Список разрешенных origin AllowedMethods: []string{http.MethodGet, http.MethodPost, http.MethodPut, http.MethodDelete, http.MethodPatch, http.MethodOptions}, - AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "ApiKey", "x-device-id"}, + AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "ApiKey", "x-device-id", "X-Timestamp"}, ExposedHeaders: []string{"Link", "Cache-Control"}, AllowCredentials: false, MaxAge: 300, // Максимальное время жизни предварительных запросов в секундах diff --git a/service/rest_admin_service/handlers/flow_nodes/handler.go b/service/rest_admin_service/handlers/flow_nodes/handler.go index 3d68369..aef573d 100644 --- a/service/rest_admin_service/handlers/flow_nodes/handler.go +++ b/service/rest_admin_service/handlers/flow_nodes/handler.go @@ -383,16 +383,65 @@ func (s *FlowNodesReg) SaveEntireTreeHandler(w http.ResponseWriter, r *http.Requ return nil, errors.New("category not found") } + // Получаем текущие узлы из БД oldNodes, _, _ := s.ipc.Database.ApprovalFlowNode.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{ Filtering: &typescore.ApprovalFlowNode{CategoryID: &categoryID}, }) + oldNodesMap := make(map[uint64]*typescore.ApprovalFlowNode) + for _, n := range oldNodes { + oldNodesMap[*n.ID] = n + } - if err := s.ipc.Database.ApprovalFlowNode.DeleteFlowNodesByCategoryIDDB(ctx, categoryID); err != nil { + activeIDs := make(map[uint64]bool) + + // Рекурсивная функция синхронизации + var syncNodes func(nodes []*typescore.ApprovalFlowNode, parentID *uint64) error + syncNodes = func(nodes []*typescore.ApprovalFlowNode, parentID *uint64) error { + for i, node := range nodes { + node.CategoryID = &categoryID + node.ParentID = parentID + sortOrder := i + node.SortOrder = &sortOrder + + var currentID uint64 + + if node.ID != nil && oldNodesMap[*node.ID] != nil { + // Обновляем существующий (ID сохраняется) + updated, _, err := s.ipc.Database.ApprovalFlowNode.UpdateApprovalFlowNodeDB(ctx, nil, node, true) + if err != nil { + return err + } + currentID = *updated.ID + } else { + // Создаем новый + created, _, err := s.ipc.Database.ApprovalFlowNode.CreateApprovalFlowNodeDB(ctx, nil, node, true) + if err != nil { + return err + } + currentID = *created.ID + } + + activeIDs[currentID] = true + + if len(node.Children) > 0 { + if err := syncNodes(node.Children, ¤tID); err != nil { + return err + } + } + } + return nil + } + + // Запускаем синхронизацию + if err := syncNodes(req.Nodes, nil); err != nil { return nil, err } - if err := s.saveNodesRecursive(ctx, req.Nodes, categoryID, nil); err != nil { - return nil, err + // Удаляем только те узлы, которых больше нет в новом дереве + for _, oldNode := range oldNodes { + if !activeIDs[*oldNode.ID] { + s.ipc.Database.ApprovalFlowNode.DeleteApprovalFlowNodeDB(ctx, oldNode) //nolint:errcheck + } } s.bumpFlowVersion(ctx) @@ -403,11 +452,11 @@ func (s *FlowNodesReg) SaveEntireTreeHandler(w http.ResponseWriter, r *http.Requ ctx, s.ipc, *currentAdmin.ID, *currentAdmin.Login, "update", "flow_tree", &categoryID, - fmt.Sprintf("Пересохранено дерево категории «%s» (было узлов: %d, стало: %d)", categoryName, len(oldNodes), countNodesRecursive(req.Nodes)), + fmt.Sprintf("Пересохранено дерево категории «%s» (было узлов: %d, стало: %d)", categoryName, len(oldNodes), len(activeIDs)), map[string]interface{}{ "category_id": categoryID, "nodes_before": len(oldNodes), - "nodes_after": countNodesRecursive(req.Nodes), + "nodes_after": len(activeIDs), }, ) } diff --git a/service/rest_admin_service/handlers/monthly_orders/routes.go b/service/rest_admin_service/handlers/monthly_orders/routes.go index 89f39f1..7636235 100644 --- a/service/rest_admin_service/handlers/monthly_orders/routes.go +++ b/service/rest_admin_service/handlers/monthly_orders/routes.go @@ -227,14 +227,10 @@ func (s *MonthlyOrdersReg) GetMatrixHandler(w http.ResponseWriter, r *http.Reque return nil, errors.New("user not authenticated") } - logrus.Info("🛑 GET MATRIX HANDLER ") user, admin, err := s.getManagerUser(ctx, adminID) targetManagerID := uint64(0) - // Если авторизовался АНАЛИТИК if admin != nil && admin.IsAnalyst != nil && *admin.IsAnalyst { - logrus.Info("🛑 ANALYTIC ") - queryManagerID := r.URL.Query().Get("manager_id") if queryManagerID != "" { parsedID, _ := strconv.ParseUint(queryManagerID, 10, 64) @@ -243,17 +239,12 @@ func (s *MonthlyOrdersReg) GetMatrixHandler(w http.ResponseWriter, r *http.Reque return nil, errors.New("аналитику необходимо передать manager_id для просмотра таблицы") } } else { - logrus.Info("🛑 MANAGER ") - - // Если авторизовался МЕНЕДЖЕР if err != nil { return nil, err } targetManagerID = *user.ID } - logrus.Info("🛑 MANAGER 2") - if s.moService == nil { return nil, errors.New("сервис заказов не инициализирован (отсутствуют ключи Google)") } @@ -263,6 +254,16 @@ func (s *MonthlyOrdersReg) GetMatrixHandler(w http.ResponseWriter, r *http.Reque return nil, err } + now := time.Now() + month, year := int(now.Month()), now.Year() + + settings, errSettings := s.ipc.Database.MonthlyOrders.GetCurrentSettings(ctx, month, year) + if errSettings == nil && settings != nil { + matrix.Settings = settings + } else if errSettings != nil { + logrus.Warnf("Не удалось получить настройки заказов для матрицы (менеджер %d): %v", targetManagerID, errSettings) + } + return matrix, nil } diff --git a/service/system_service/go.mod b/service/system_service/go.mod index 7047d1e..5f2a8f2 100644 --- a/service/system_service/go.mod +++ b/service/system_service/go.mod @@ -1,6 +1,6 @@ module bitrix_balancer_api/system_service -go 1.25.6 +go 1.26.10 replace bitrix_balancer_api/core => ../../core 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/handler_decision.go b/service/telegram_service/handlers/approval/handler_decision.go index 2dc7626..7fc727c 100644 --- a/service/telegram_service/handlers/approval/handler_decision.go +++ b/service/telegram_service/handlers/approval/handler_decision.go @@ -557,6 +557,22 @@ func (h *Handler) handleDecision( return } + // Отменяем все последующие шаги при последовательном согласовании + allSteps, _, _ := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalStep{ApprovalID: &approvalID}, + }) + for _, s := range allSteps { + if s.ID == nil || (step.ID != nil && *s.ID == *step.ID) { + continue + } + if s.Status != nil && *s.Status == "waiting" { + cancelledStatus := "cancelled" + s.Status = &cancelledStatus + h.ipc.Database.ApprovalStep.UpdateApprovalStepDB(ctx, nil, s) //nolint:errcheck + } + } + + // Сохраняем статус и отправляем уведомления только ОДИН раз approval.Status = &rejectedStatus h.ipc.Database.Approval.UpdateApprovalDB(ctx, nil, approval) //nolint:errcheck notifyRejection(step.ApproverID) @@ -703,8 +719,7 @@ func (h *Handler) handleDecision( pendingCount, pendingNames := getPendingAdditionalInfo() pendingText := "" if pendingCount > 0 { - pendingText = fmt.Sprintf("\n\n⏳ Ожидается решение других дополнительных согласующих (%d):\n• %s", - pendingCount, strings.Join(pendingNames, "\n• ")) + pendingText = fmt.Sprintf("\n\n⏳ Ожидается решение дополнительных согласующих (%d):\n• %s", pendingCount, strings.Join(pendingNames, "\n• ")) } if !mainApproverApproved { @@ -726,11 +741,6 @@ func (h *Handler) handleDecision( } if mainApproverApproved && allAdditionalApproved { - // 🩹 ФИКС 2: передаём исполнителя ОСНОВНОГО шага (mainStep.ApproverID), - // а не currentUserID (доп. согласующего). Иначе - // processNextStepOrComplete считает доп. согласующего "делегатом" - // основного согласующего только из-за разных ID — и рассылает - // неверные уведомления вида "ваш делегат согласовал заявку". mainExecutorID := currentUserID if mainStep.ApproverID != nil { mainExecutorID = *mainStep.ApproverID diff --git a/service/telegram_service/handlers/approval/helper.go b/service/telegram_service/handlers/approval/helper.go index 8c8410f..cbc58ec 100644 --- a/service/telegram_service/handlers/approval/helper.go +++ b/service/telegram_service/handlers/approval/helper.go @@ -542,22 +542,116 @@ 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 // не можем проверить — показываем всё + perms, err := h.ipc.Database.Permission.GetUserPermissionsDB(ctx, *user.ID, "create") + if err != nil { + return nodes + } + + allowedCategoryIDs := map[uint64]bool{} + allowedTopicIDs := map[uint64]bool{} + for _, p := range perms { + if p.TopicCategoryID != nil { + allowedCategoryIDs[*p.TopicCategoryID] = true + } + if p.TopicID != nil { + allowedTopicIDs[*p.TopicID] = true + } + } + + categoryCode := topic.Code() + category, err := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByCodeDB(ctx, categoryCode) + if err != nil || category == nil || category.ID == nil { + return nodes + } + + var allowedTopicCodes []string + + if allowedCategoryIDs[*category.ID] { + 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.ID != nil && t.Code != nil && allowedTopicIDs[*t.ID] { + allowedTopicCodes = append(allowedTopicCodes, *t.Code) + } + } + } + + isCodePermitted := func(targetCode string) bool { + // If the user has access to the whole category, permit it + if allowedCategoryIDs[*category.ID] { + return true + } + + 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 + } + + 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 + } + + isLeaf := len(n.Children) == 0 + isInputLeaf := len(n.Children) == 1 && n.Children[0].IsInput + + // Only generate and check the code if we are at a leaf node + // OR if the category doesn't use a complex template. + // For template categories, intermediate codes are malformed. + if isLeaf || isInputLeaf { + code, err := topic.TopicCodeFromCollected(newCollected) + if err == nil && code != "" { + return isCodePermitted(code) + } + return false + } + + // It's an intermediate node, so we must check all children + for _, child := range n.Children { + if hasValidLeaf(child, newCollected) { + return true + } + } + return false } var filtered []*approvalflow.FlowNode @@ -565,10 +659,19 @@ func (h *Handler) filterNodesByAccess(ctx context.Context, telegramID int64, nod 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 }