diff --git a/core/config/config-load-options.go b/core/config/config-load-options.go index 35e0991..4d44a85 100644 --- a/core/config/config-load-options.go +++ b/core/config/config-load-options.go @@ -12,7 +12,7 @@ type ConfigLoadOptions struct { Redis bool Database bool Bitrix bool - Secrets bool + Secrets SecretsOptions Telegram bool Server ExposedServiceOptions } diff --git a/core/config/config-types.go b/core/config/config-types.go index 2083d17..9df48cf 100644 --- a/core/config/config-types.go +++ b/core/config/config-types.go @@ -1,5 +1,7 @@ package configcore +import "net/url" + // RedisConfig конфигурация Redis type RedisConfig struct { Host string `yaml:"host" env-required:"true"` @@ -20,11 +22,12 @@ type DatabaseConfig struct { // TelegramConfig конфигурация Telegram type TelegramConfig struct { - BotToken string `yaml:"bot_token"` - WebAppUrl string `yaml:"web_app_url"` - ProxyURL string `yaml:"proxy_url"` - ProxyUsername string `yaml:"proxy_username"` - ProxyPassword string `yaml:"proxy_password"` + BotToken string `yaml:"bot_token"` + WebAppUrl string `yaml:"web_app_url"` + ProxyURL string `yaml:"proxy_url"` + ProxyUsername string `yaml:"proxy_username"` + ProxyPassword string `yaml:"proxy_password"` + ParsedProxy *url.URL // кэшированный распарсенный прокси } // ServiceConfig конфигурация сервиса @@ -44,6 +47,21 @@ type SwaggerConfig struct { Pass string `yaml:"pass" env-required:"true"` } +// AuthJWTOptions определяет, какие JWT секреты нужно загружать +type AuthJWTOptions struct { + Admin bool + User bool +} + +type SecretsOptions struct { + AuthJWT AuthJWTOptions + OAuthConfig bool + WebAuth bool + AdminAccessCode bool + UserAccessCode bool + TonProofConfig bool +} + // RestServiceConfig конфигурация REST сервиса type RestServiceConfig struct { PortRest int `yaml:"port_rest" env-required:"true"` @@ -63,8 +81,9 @@ type GrpcServiceConfig struct { } type Server struct { - RESTBaseService RestServiceConfig `yaml:"rest_balancer_service"` - Telegram GrpcServiceConfig `yaml:"telegram_service"` + RESTBaseService RestServiceConfig `yaml:"rest_balancer_service"` + RESTAdminService RestServiceConfig `yaml:"rest_admin_service"` + Telegram GrpcServiceConfig `yaml:"telegram_service"` } type Bitrix struct { @@ -80,10 +99,25 @@ type Service struct { MessageTimeout int64 `yaml:"message_timeout"` } +// AuthJWTConfig конфигурация JWT аутентификации +type AuthJWTConfig struct { + AdminSecret string `yaml:"admin_secret"` + UserSecret string `yaml:"user_secret"` + TempSecret string `yaml:"temp_secret"` + TemporaryPasswordLifeMinute int `yaml:"temporary_password_life_minute"` + JwtAdminSessionLengthHours int `yaml:"jwt_admin_session_length_hours"` + JwtUserSessionLengthHours int `yaml:"jwt_user_session_length_hours"` +} + // SecretsConfig конфигурация секретов type SecretsConfig struct { - ApiPublicBase string `yaml:"api_public_base"` - ApiPrivateBase string `yaml:"api_private_base"` + AuthJWT AuthJWTConfig `yaml:"auth_jwt"` + ApiPublicUser string `yaml:"access_code_user"` + ApiPrivateUser string + ApiPublicAdmin string `yaml:"access_code_admin"` + ApiPrivateAdmin string + ApiPublicBase string `yaml:"api_public_base"` + ApiPrivateBase string `yaml:"api_private_base"` } type Config struct { diff --git a/core/config/configcore.go b/core/config/configcore.go index 29a8c45..80aab71 100644 --- a/core/config/configcore.go +++ b/core/config/configcore.go @@ -59,10 +59,6 @@ func copyConfigFields(options *ConfigLoadOptions, source, target *Config) { target.Bitrix = source.Bitrix } - if options.Secrets { - target.Secrets = source.Secrets - } - // Копируем ExposedServiceConfig if options.Server.RESTBaseService { target.Server.RESTBaseService = source.Server.RESTBaseService @@ -70,4 +66,19 @@ func copyConfigFields(options *ConfigLoadOptions, source, target *Config) { if options.Server.TelegramService { target.Server.Telegram = source.Server.Telegram } + + if options.Secrets.AuthJWT.Admin { + target.Secrets.AuthJWT.AdminSecret = source.Secrets.AuthJWT.AdminSecret + target.Secrets.AuthJWT.JwtAdminSessionLengthHours = source.Secrets.AuthJWT.JwtAdminSessionLengthHours + } + if options.Secrets.AuthJWT.User { + target.Secrets.AuthJWT.UserSecret = source.Secrets.AuthJWT.UserSecret + target.Secrets.AuthJWT.JwtUserSessionLengthHours = source.Secrets.AuthJWT.JwtUserSessionLengthHours + } + if options.Secrets.AdminAccessCode { + target.Secrets.ApiPublicAdmin = source.Secrets.ApiPublicAdmin + } + if options.Secrets.UserAccessCode { + target.Secrets.ApiPublicUser = source.Secrets.ApiPublicUser + } } diff --git a/core/db/db.go b/core/db/db.go index 6a5ecfa..f6601eb 100644 --- a/core/db/db.go +++ b/core/db/db.go @@ -32,6 +32,7 @@ type ModuleDB struct { Suggestion *dbcore.SuggestionDB SuggestionMessage *dbcore.SuggestionMessageDB ApprovalAdditionalObserver *dbcore.ApprovalAdditionalObserverDB + ApprovalTopicExecutor *dbcore.ApprovalTopicExecutorDB } func NewModuleDB( @@ -80,6 +81,7 @@ func initDBModules(modules *ModuleDB, redisClient *redismodule.ModuleRedis) *Mod modules.SuggestionMessage = dbcore.NewSuggestionMessageDB(modules.Pool) modules.Suggestion = dbcore.NewSuggestionDB(modules.Pool) modules.ApprovalAdditionalObserver = dbcore.NewApprovalAdditionalObserverDB(modules.Pool) + modules.ApprovalTopicExecutor = dbcore.NewApprovalTopicExecutorDB(modules.Pool) return modules } diff --git a/core/db/db_migration/tables.go b/core/db/db_migration/tables.go index 40bff0f..70793f7 100644 --- a/core/db/db_migration/tables.go +++ b/core/db/db_migration/tables.go @@ -36,6 +36,7 @@ func (m *MigrationFunctions) migrateTables() error { tablesmigration.SuggestionsTableMigrate, tablesmigration.SuggestionMessagesTableMigrate, tablesmigration.ApprovalAdditionalObserverTableMigrate, + tablesmigration.ApprovalTopicExecutorsTableMigrate, } for _, migrate := range migrations { diff --git a/core/db/db_migration/tables/approval_topic_category.go b/core/db/db_migration/tables/approval_topic_category.go index 1089852..6bb154f 100644 --- a/core/db/db_migration/tables/approval_topic_category.go +++ b/core/db/db_migration/tables/approval_topic_category.go @@ -12,6 +12,8 @@ func ApprovalTopicCategoriesTableMigrate(db *gorm.DB) error { return err } + db.Exec(`ALTER TABLE approval_topics ADD CONSTRAINT fk_approval_topics_category_id FOREIGN KEY (category_id) REFERENCES approval_topic_categories(id) ON DELETE CASCADE ON UPDATE CASCADE`) + if !hasTable { time.Sleep(5 * time.Second) diff --git a/core/db/db_migration/tables/approval_topic_executor.go b/core/db/db_migration/tables/approval_topic_executor.go new file mode 100644 index 0000000..2a2d799 --- /dev/null +++ b/core/db/db_migration/tables/approval_topic_executor.go @@ -0,0 +1,35 @@ +package tablesmigration + +import ( + "gorm.io/gorm" + "time" +) + +func ApprovalTopicExecutorsTableMigrate(db *gorm.DB) error { + hasTable := db.Migrator().HasTable(&LocalApprovalTopicExecutorProvider{}) + + if err := db.AutoMigrate(&LocalApprovalTopicExecutorProvider{}); err != nil { + return err + } + + if !hasTable { + time.Sleep(5 * time.Second) + + db.Exec(`ALTER TABLE approval_topic_executor ADD CONSTRAINT fk_users FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL ON UPDATE CASCADE`) + db.Exec(`ALTER TABLE approval_topic_executor ADD CONSTRAINT fk_topic_id FOREIGN KEY (topic_id) REFERENCES approval_topics(id) ON DELETE SET NULL ON UPDATE CASCADE`) + + execComments(db, ` + COMMENT ON TABLE "approval_topic_executor" IS 'Исполнители шагов согласования по темам'; + COMMENT ON COLUMN "approval_topic_executor".id IS 'Внутренний ID записи исполнителя'; + COMMENT ON COLUMN "approval_topic_executor".topic_id IS 'ID темы согласования, к которой относится шаг'; + COMMENT ON COLUMN "approval_topic_executor".user_id IS 'ID пользователя, назначенного исполнителем на данном шаге'; + COMMENT ON COLUMN "approval_topic_executor".step_order IS 'Порядковый номер шага согласования'; + COMMENT ON COLUMN "approval_topic_executor".require_file IS 'Требуется ли от исполнителя прикрепление файла'; + COMMENT ON COLUMN "approval_topic_executor".task_text IS 'Текст задачи или комментарий для исполнителя'; + COMMENT ON COLUMN "approval_topic_executor".is_active IS 'Активен ли данный шаг/исполнитель в маршруте согласования'; + COMMENT ON COLUMN "approval_topic_executor".created_at IS 'Дата создания записи'; + COMMENT ON COLUMN "approval_topic_executor".updated_at IS 'Дата последнего обновления записи'; + `) + } + return nil +} diff --git a/core/db/db_migration/tables/providers.go b/core/db/db_migration/tables/providers.go index a65887a..29b3b6f 100644 --- a/core/db/db_migration/tables/providers.go +++ b/core/db/db_migration/tables/providers.go @@ -23,6 +23,7 @@ type ApprovalTaskProvider typescore.ApprovalTask type ApprovalCommentsProvider typescore.ApprovalComment type LocalSuggestionProvider typescore.Suggestion type LocalSuggestionMessagesProvider typescore.SuggestionMessage +type LocalApprovalTopicExecutorProvider typescore.ApprovalTopicExecutor func (LocalUserProvider) TableName() string { return dbcoretablenames.TableNameUsers.ToString() @@ -78,3 +79,6 @@ func (LocalSuggestionMessagesProvider) TableName() string { func (ApprovalAdditionalObserver) TableName() string { return dbcoretablenames.TableNameApprovalAdditionalObservers.ToString() } +func (LocalApprovalTopicExecutorProvider) TableName() string { + return dbcoretablenames.TableNameApprovalTopicExecutor.ToString() +} diff --git a/core/db/methods/approval_topic_category.go b/core/db/methods/approval_topic_category.go index e78310d..7a7d8d2 100644 --- a/core/db/methods/approval_topic_category.go +++ b/core/db/methods/approval_topic_category.go @@ -30,6 +30,85 @@ type ApprovalTopicCategoryDBI interface { DeleteApprovalTopicCategoryDB(ctx context.Context, params *typescore.ApprovalTopicCategory) error GetApprovalTopicCategoryByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalTopicCategory, error) GetApprovalTopicCategoryByCodeDB(ctx context.Context, code string) (*typescore.ApprovalTopicCategory, error) + GetCategoriesWithApprovalsByInitiatorDB( + ctx context.Context, + initiatorID uint64, + ) ([]*typescore.ApprovalTopicCategory, error) + GetCategoriesWithApprovalsByApproverDB(ctx context.Context, approverID uint64) ([]*typescore.ApprovalTopicCategory, error) +} + +// GetCategoriesWithApprovalsByInitiatorDB — категории тем, по которым у инициатора есть заявки +func (u *ApprovalTopicCategoryDB) GetCategoriesWithApprovalsByInitiatorDB( + ctx context.Context, + initiatorID uint64, +) ([]*typescore.ApprovalTopicCategory, error) { + sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Select("DISTINCT c.*"). + From(dbcoretablenames.TableNameApprovalTopicCategories.ToString() + " c"). + Join(dbcoretablenames.TableNameApprovalTopics.ToString() + " t ON t.category_id = c.id"). + Join(dbcoretablenames.TableNameApprovals.ToString() + " a ON a.topic_id = t.id"). + Where(squirrel.Eq{"a.initiator_id": initiatorID}). + Where(squirrel.Eq{"c.is_active": true}). + OrderBy("c.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 result []*typescore.ApprovalTopicCategory + for rows.Next() { + obj := &typescore.ApprovalTopicCategory{} + if err := dbutils.ScanRowsToStructRows(rows, obj, nil); err != nil { + logrus.Warn("GetCategoriesWithApprovalsByInitiatorDB:Scan", err) + continue + } + result = append(result, obj) + } + return result, nil +} + +// GetCategoriesWithApprovalsByApproverDB — категории тем, в которых +// пользователь участвовал как согласующий (через approval_steps). +func (u *ApprovalTopicCategoryDB) GetCategoriesWithApprovalsByApproverDB( + ctx context.Context, + approverID uint64, +) ([]*typescore.ApprovalTopicCategory, error) { + sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Select("DISTINCT c.*"). + From(dbcoretablenames.TableNameApprovalTopicCategories.ToString() + " c"). + Join(dbcoretablenames.TableNameApprovalTopics.ToString() + " t ON t.category_id = c.id"). + Join(dbcoretablenames.TableNameApprovals.ToString() + " a ON a.topic_id = t.id"). + Join(dbcoretablenames.TableNameApprovalSteps.ToString() + " s ON s.approval_id = a.id"). + Where(squirrel.Eq{"s.approver_id": approverID}). + Where(squirrel.Eq{"c.is_active": true}). + OrderBy("c.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 result []*typescore.ApprovalTopicCategory + for rows.Next() { + obj := &typescore.ApprovalTopicCategory{} + if err := dbutils.ScanRowsToStructRows(rows, obj, nil); err != nil { + logrus.Warn("GetCategoriesWithApprovalsByApproverDB:Scan", err) + continue + } + result = append(result, obj) + } + return result, nil } func (u *ApprovalTopicCategoryDB) GetApprovalTopicCategoryListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalTopicCategory, uint64, error) { diff --git a/core/db/methods/approval_topic_executor.go b/core/db/methods/approval_topic_executor.go new file mode 100644 index 0000000..681026e --- /dev/null +++ b/core/db/methods/approval_topic_executor.go @@ -0,0 +1,199 @@ +package dbcore + +import ( + dbcoretablenames "bitrix_balancer_api/core/db/table_names" + "bitrix_balancer_api/core/typescore" + dbutils "bitrix_balancer_api/core/utilscore/db" + "context" + "errors" + "github.com/sirupsen/logrus" + + "github.com/Masterminds/squirrel" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" +) + +type ApprovalTopicExecutorDB struct { + pool *pgxpool.Pool +} + +func NewApprovalTopicExecutorDB(pool *pgxpool.Pool) *ApprovalTopicExecutorDB { + return &ApprovalTopicExecutorDB{pool: pool} +} + +type ApprovalTopicExecutorDBI interface { + GetApprovalTopicExecutorListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.ApprovalTopicExecutor, uint64, error) + CreateApprovalTopicExecutorDB(ctx context.Context, tx pgx.Tx, obj *typescore.ApprovalTopicExecutor, returnObj ...bool) (*typescore.ApprovalTopicExecutor, pgx.Tx, error) + UpdateApprovalTopicExecutorDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalTopicExecutor, returnObj ...bool) (*typescore.ApprovalTopicExecutor, pgx.Tx, error) + DeleteApprovalTopicExecutorDB(ctx context.Context, params *typescore.ApprovalTopicExecutor) error + GetExecutorsByTopicIDDB(ctx context.Context, topicID uint64) ([]*typescore.ApprovalTopicExecutor, error) +} + +func (d *ApprovalTopicExecutorDB) GetApprovalTopicExecutorListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalTopicExecutor, uint64, error) { + fields := dbutils.GetStructFieldsDB(&typescore.ApprovalTopicExecutor{}, dbcoretablenames.TableNameApprovalTopicExecutor.ToString()) + selectFields := append(fields, "COUNT(*) OVER() AS total_count") + + options, filter, err := dbutils.GetOptionsDB[typescore.ApprovalTopicExecutor](opts...) + if err != nil { + return nil, 0, err + } + + query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovalTopicExecutor.ToString(), selectFields) + query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit) + query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovalTopicExecutor.ToString()) + query = query.OrderBy("step_order ASC, id ASC") + + sql, args, err := query.ToSql() + if err != nil { + return nil, 0, err + } + + rows, err := d.pool.Query(ctx, sql, args...) + if err != nil { + return nil, 0, err + } + defer rows.Close() + + var result []*typescore.ApprovalTopicExecutor + var totalCount uint64 + for rows.Next() { + item := &typescore.ApprovalTopicExecutor{} + if err := dbutils.ScanRowsToStructRows(rows, item, &totalCount); err != nil { + logrus.Warn("GetApprovalTopicExecutorListDB:ScanRowsToStructRows", err) + continue + } + result = append(result, item) + } + + return result, totalCount, nil +} + +func (d *ApprovalTopicExecutorDB) CreateApprovalTopicExecutorDB(ctx context.Context, tx pgx.Tx, obj *typescore.ApprovalTopicExecutor, returnObj ...bool) (*typescore.ApprovalTopicExecutor, pgx.Tx, error) { + if obj == nil { + return nil, nil, errors.New("ApprovalTopicExecutor obj is nil") + } + + err := dbutils.ExecuteTx(ctx, d.pool, tx, func(tx pgx.Tx) error { + query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Insert(dbcoretablenames.TableNameApprovalTopicExecutor.ToString()) + + sqlV, args, err := dbutils.GenerateInsertRequest(query, obj) + if err != nil { + return err + } + + _, err = tx.Exec(ctx, *sqlV, args...) + return err + }) + + if err != nil { + return nil, tx, err + } + + returnObjBool := false + if len(returnObj) > 0 { + returnObjBool = returnObj[0] + } + if returnObjBool { + items, _, err := d.GetApprovalTopicExecutorListDB(ctx, typescore.ListDbOptions{Filtering: obj}) + if err != nil { + return nil, tx, err + } + if len(items) > 0 { + return items[0], tx, nil + } + } + + return nil, tx, nil +} + +func (d *ApprovalTopicExecutorDB) UpdateApprovalTopicExecutorDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalTopicExecutor, returnObj ...bool) (*typescore.ApprovalTopicExecutor, pgx.Tx, error) { + if paramsUpdate.ID == nil { + return nil, nil, errors.New("ApprovalTopicExecutor obj is nil") + } + + err := dbutils.ExecuteTx(ctx, d.pool, tx, func(tx pgx.Tx) error { + query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Update(dbcoretablenames.TableNameApprovalTopicExecutor.ToString()) + query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate) + query = query.Where(squirrel.Eq{"id": paramsUpdate.ID}) + + sql, args, err := query.ToSql() + if err != nil { + return err + } + + _, err = tx.Exec(ctx, sql, args...) + return err + }) + + if err != nil { + return nil, tx, err + } + + returnObjBool := false + if len(returnObj) > 0 { + returnObjBool = returnObj[0] + } + + if returnObjBool { + options := typescore.ListDbOptions{Filtering: &typescore.ApprovalTopicExecutor{ID: paramsUpdate.ID}} + items, _, err := d.GetApprovalTopicExecutorListDB(ctx, options) + if err != nil { + return nil, nil, err + } + if len(items) > 0 { + return items[0], tx, nil + } + } + + return nil, tx, nil +} + +func (d *ApprovalTopicExecutorDB) DeleteApprovalTopicExecutorDB(ctx context.Context, params *typescore.ApprovalTopicExecutor) error { + if params != nil && params.ID != nil { + query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Delete(dbcoretablenames.TableNameApprovalTopicExecutor.ToString()). + Where(squirrel.Eq{"id": *params.ID}). + ToSql() + + if err != nil { + return err + } + + _, err = d.pool.Query(ctx, query, args...) + return err + } + return errors.New("ApprovalTopicExecutor obj is nil") +} + +// GetExecutorsByTopicIDDB возвращает всех исполнителей для темы, отсортированных по step_order +func (d *ApprovalTopicExecutorDB) GetExecutorsByTopicIDDB(ctx context.Context, topicID uint64) ([]*typescore.ApprovalTopicExecutor, error) { + sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Select("ate.*"). + From(dbcoretablenames.TableNameApprovalTopicExecutor.ToString() + " ate"). + Where(squirrel.Eq{"ate.topic_id": topicID}). + Where(squirrel.Eq{"ate.is_active": true}). + OrderBy("ate.step_order ASC, ate.id ASC"). + ToSql() + if err != nil { + return nil, err + } + + rows, err := d.pool.Query(ctx, sql, args...) + if err != nil { + return nil, err + } + defer rows.Close() + + var result []*typescore.ApprovalTopicExecutor + for rows.Next() { + item := &typescore.ApprovalTopicExecutor{} + if err := dbutils.ScanRowsToStructRows(rows, item, nil); err != nil { + logrus.Warn("GetExecutorsByTopicIDDB:ScanRowsToStructRows", err) + continue + } + result = append(result, item) + } + return result, nil +} diff --git a/core/db/methods/user_hierarchy.go b/core/db/methods/user_hierarchy.go index 324ddc4..b1ecd4b 100644 --- a/core/db/methods/user_hierarchy.go +++ b/core/db/methods/user_hierarchy.go @@ -30,7 +30,6 @@ type UserHierarchyDBI interface { DeleteUserHierarchyDB(ctx context.Context, params *typescore.UserHierarchy) error GetApproversDB(ctx context.Context, subordinateID uint64, departmentID uint64) ([]*typescore.User, error) - GetExecutorDB(ctx context.Context, subordinateID, departmentID, topicID, categoryID uint64) (*typescore.User, error) } func (u *UserHierarchyDB) GetUserHierarchyListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.UserHierarchy, uint64, error) { @@ -183,17 +182,7 @@ func (u *UserHierarchyDB) DeleteUserHierarchyDB(ctx context.Context, params *typ } } -func (u *UserHierarchyDB) GetApproversDB( - ctx context.Context, - subordinateID uint64, - departmentID uint64, - topicID uint64, - topicCategoryID uint64, -) ([]*typescore.User, error) { - - // Ищем наиболее специфичное правило для этой тройки (subordinate, dept, тема). - // Приоритет: topic_id > topic_category_id > общее правило (оба NULL). - // Берём только правила одного уровня специфичности — наиболее точного. +func (u *UserHierarchyDB) GetApproversDB(ctx context.Context, subordinateID, departmentID, topicID, categoryID uint64) ([]*typescore.User, error) { rawSQL := ` WITH ranked AS ( SELECT @@ -229,7 +218,7 @@ func (u *UserHierarchyDB) GetApproversDB( subordinateID, departmentID, topicID, - topicCategoryID, + categoryID, ) if err != nil { return nil, err @@ -247,56 +236,3 @@ func (u *UserHierarchyDB) GetApproversDB( } return result, nil } - -func (u *UserHierarchyDB) GetExecutorDB(ctx context.Context, subordinateID, departmentID, topicID, categoryID uint64) (*typescore.User, error) { - fields := dbutils.GetStructFieldsDB(&typescore.User{}, "u") - - queryUser := func(where squirrel.Sqlizer) (*typescore.User, error) { - baseQuery := squirrel.Select(fields...). - From(dbcoretablenames.TableNameUserHierarchy.ToString() + " uh"). - Join(dbcoretablenames.TableNameUsers.ToString() + " u ON u.id = uh.executor_id"). - Where(squirrel.Eq{"uh.subordinate_id": subordinateID}). - Where(squirrel.Eq{"uh.department_id": departmentID}). - Where(squirrel.Expr("uh.executor_id IS NOT NULL")). - Where(where). - Limit(1) - - sql, args, err := baseQuery.PlaceholderFormat(squirrel.Dollar).ToSql() - if err != nil { - return nil, err - } - logrus.Debugf("Generated SQL: %s, Args: %v", sql, args) // <-- добавь это - - rows, err := u.pool.Query(ctx, sql, args...) - if err != nil { - return nil, err - } - defer rows.Close() - - if !rows.Next() { - return nil, rows.Err() - } - - user := &typescore.User{} - var totalCount uint64 - if err := dbutils.ScanRowsToStructRows(rows, user, &totalCount); err != nil { - return nil, err - } - - return user, nil - } - - if topicID > 0 { - user, err := queryUser(squirrel.Eq{"uh.topic_id": topicID}) - if err == nil && user != nil { - return user, nil - } - } - - user, err := queryUser(squirrel.Eq{"uh.topic_category_id": categoryID}) - if err != nil { - return nil, err - } - - return user, nil -} diff --git a/core/db/table_names/table_names.go b/core/db/table_names/table_names.go index ca22321..b7184e8 100644 --- a/core/db/table_names/table_names.go +++ b/core/db/table_names/table_names.go @@ -21,6 +21,7 @@ const ( TableNameApprovalComments TableName = "approval_comments" TableNameSuggestions TableName = "suggestions" TableNameSuggestionMessages TableName = "suggestion_messages" + TableNameApprovalTopicExecutor TableName = "approval_topic_executor" ) func (t TableName) ToString() string { diff --git a/core/go.mod b/core/go.mod index c958840..bcc1b46 100644 --- a/core/go.mod +++ b/core/go.mod @@ -5,6 +5,7 @@ go 1.25.6 require ( github.com/Masterminds/squirrel v1.5.4 github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1 + github.com/golang-jwt/jwt/v5 v5.3.1 github.com/google/uuid v1.6.0 github.com/hashicorp/vault/api v1.22.0 github.com/jackc/pgx/v5 v5.8.0 @@ -12,6 +13,8 @@ require ( github.com/redis/go-redis/v9 v9.18.0 github.com/shopspring/decimal v1.4.0 github.com/sirupsen/logrus v1.9.4 + golang.org/x/crypto v0.40.0 + golang.org/x/net v0.42.0 gopkg.in/yaml.v3 v3.0.1 gorm.io/driver/postgres v1.6.0 gorm.io/gorm v1.31.1 @@ -42,10 +45,7 @@ require ( github.com/mitchellh/go-homedir v1.1.0 // indirect github.com/rogpeppe/go-internal v1.14.1 // indirect github.com/ryanuber/go-glob v1.0.0 // indirect - github.com/temoon/telegram-bots-api v1.960.1 // indirect go.uber.org/atomic v1.11.0 // indirect - golang.org/x/crypto v0.40.0 // indirect - golang.org/x/net v0.42.0 // indirect golang.org/x/sync v0.17.0 // indirect golang.org/x/sys v0.41.0 // indirect golang.org/x/text v0.29.0 // indirect diff --git a/core/go.sum b/core/go.sum index 3a333c2..34ff3d7 100644 --- a/core/go.sum +++ b/core/go.sum @@ -22,6 +22,8 @@ github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1 h1:wG8n/XJQ07TmjbITcGi github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1/go.mod h1:A2S0CWkNylc2phvKXWBBdD3K0iGnDBGbzRpISP2zBl8= github.com/go-test/deep v1.1.1 h1:0r/53hagsehfO4bzD2Pgr/+RgHqhmf+k1Bpse2cTu1U= github.com/go-test/deep v1.1.1/go.mod h1:5C2ZWiW0ErCdrYzpqxLbTX7MG14M9iiw8DgHncVwcsE= +github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY= +github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= @@ -95,8 +97,6 @@ github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UV github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= -github.com/temoon/telegram-bots-api v1.960.1 h1:TgokOkJ3Fcb0ABErjdjKUc3x+n1gACfXOTYhuyhFhao= -github.com/temoon/telegram-bots-api v1.960.1/go.mod h1:abg+fx+e22CTPO8XG9gG2BEF2w2L8RXKpZ2bHv+3f/I= github.com/zeebo/xxh3 v1.0.2 h1:xZmwmqxHZA8AI603jOQ0tMqmBr9lPeFwGg6d+xy9DC0= github.com/zeebo/xxh3 v1.0.2/go.mod h1:5NWz9Sef7zIDm2JHfFlcQvNekmcEl9ekUZQQKCYaDcA= go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= diff --git a/core/lib/external/tgkit/types.go b/core/lib/external/tgkit/types.go index a4065d4..cbdfdf7 100644 --- a/core/lib/external/tgkit/types.go +++ b/core/lib/external/tgkit/types.go @@ -24,14 +24,15 @@ const ( type ButtonStyle string const ( - ButtonStyleDefault ButtonStyle = "" - ButtonStyleSuccess ButtonStyle = "✅ " - ButtonStyleDanger ButtonStyle = "❌ " - ButtonStyleWarning ButtonStyle = "⚠️ " - ButtonStyleInfo ButtonStyle = "ℹ️ " - ButtonStylePrimary ButtonStyle = "🔵 " - ButtonStyleBack ButtonStyle = "← " - ButtonStyleForward ButtonStyle = "→ " + ButtonStyleDefault ButtonStyle = "" + ButtonStyleSuccess ButtonStyle = "✅ " + ButtonStyleDanger ButtonStyle = "❌ " + ButtonStyleWarning ButtonStyle = "⚠️ " + ButtonStyleInfo ButtonStyle = "ℹ️ " + ButtonStylePrimary ButtonStyle = "🔵 " + ButtonStyleBack ButtonStyle = "← " + ButtonStyleForward ButtonStyle = "→ " + ButtonStyleRevision ButtonStyle = "↩️ " ) // MessageOptions — опции отправки сообщения diff --git a/core/securecore/hashing.go b/core/securecore/hashing.go new file mode 100644 index 0000000..6deb914 --- /dev/null +++ b/core/securecore/hashing.go @@ -0,0 +1,50 @@ +package securecore + +import ( + "encoding/hex" + "errors" + "golang.org/x/crypto/bcrypt" + "golang.org/x/crypto/sha3" +) + +// HashStringSHA3_256 вычисляет SHA‑3 (256 бит) хэш от входной строки. +func HashStringSHA3_256(input string) string { + sum := sha3.Sum256([]byte(input)) + res := hex.EncodeToString(sum[:]) + return res + // return input +} + +// HexEncode - кодирует строку в hex +func HexEncode(data []byte) string { + return hex.EncodeToString(data) + // return string(data) +} + +// HexDecode - декодирует строку из hex +func HexDecode(content string) ([]byte, error) { + return hex.DecodeString(content) + // return []byte(content), nil +} + +// Функция для проверки пароля +func CheckPasswordHash(password, hash *string) bool { + if password == nil || hash == nil { + println("CheckPasswordHash(): password or hash is nil") + return false + } + + err := bcrypt.CompareHashAndPassword([]byte(*hash), []byte(*password)) + return err == nil +} + +// Функция для хэширования пароля +func HashPassword(password *string) (*string, error) { + if password == nil { + return nil, errors.New("missed password") + } + + bytes, err := bcrypt.GenerateFromPassword([]byte(*password), bcrypt.DefaultCost) + hashedPass := string(bytes) + return &hashedPass, err +} diff --git a/core/securecore/jwt-methods.go b/core/securecore/jwt-methods.go new file mode 100644 index 0000000..c0891cc --- /dev/null +++ b/core/securecore/jwt-methods.go @@ -0,0 +1,95 @@ +package securecore + +import ( + "bitrix_balancer_api/core/typescore" + "errors" + "github.com/golang-jwt/jwt/v5" + + "time" +) + +// Определить пользовательский тип для контекстных ключей +type contextKey string + +func (c contextKey) String() string { + return string(c) +} + +const AddressContextKey contextKey = "raw_user_address" +const IDContextKey contextKey = "user_id" +const AccessContextKey contextKey = "access_code" +const IpContextKey contextKey = "user_ip" +const expContextKey contextKey = "exp" + +func GenerateTokenJWT( + userAddr string, + userID uint64, + userIP string, + secretJWT string, + sessionTime int, +) (string, error) { + duration := time.Duration(72) + if sessionTime > 0 { + duration = time.Duration(sessionTime) + } + // Создаем новый токен + token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ + AddressContextKey.String(): userAddr, + IDContextKey.String(): float64(userID), + IpContextKey.String(): userIP, + expContextKey.String(): time.Now().Add(time.Hour * duration).Unix(), // срок действия токена 72 часа + }) + + t, err := token.SignedString([]byte(secretJWT)) + if err != nil { + return "", err + } + + return t, nil +} + +// VerifyToken верифицирует JWT токен и возвращает данные по токену или ошибку +func VerifyToken(tokenString string, jwtSecret string) (*jwt.Token, jwt.MapClaims, error) { + token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { + if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { + return nil, errors.New("unexpected signing method") + } + return []byte(jwtSecret), nil + }) + + if err != nil || !token.Valid { + return nil, nil, errors.New("invalid token") + } + + claims, ok := token.Claims.(jwt.MapClaims) + if !ok { + return nil, nil, errors.New("invalid token claims") + } + + if exp, ok := claims[expContextKey.String()].(float64); ok { + if time.Unix(int64(exp), 0).Before(time.Now()) { + return nil, nil, errors.New("token expired") + } + } + + return token, claims, nil +} + +func IsSameIP(ip1, ip2 string) bool { + // Простое сравнение для начала + return ip1 == ip2 +} + +func FindDeviceID(deviceList []typescore.DeviceList, deviceID string) bool { + if len(deviceList) == 0 { + return false + } + + for _, device := range deviceList { + if device.DeviceID == deviceID { + return true + } + } + + return false +} diff --git a/core/typescore/approval_file.go b/core/typescore/approval_file.go index 9a9b6e8..fe9d03e 100644 --- a/core/typescore/approval_file.go +++ b/core/typescore/approval_file.go @@ -7,6 +7,7 @@ type ApprovalFile struct { ApprovalID *uint64 `gorm:"type:bigint;not null;index;column:approval_id" json:"approval_id" db:"approval_id"` FileBase64 *string `gorm:"type:text;not null;column:file_base64" json:"file_base64" db:"file_base64"` FileName *string `gorm:"type:text;not null;column:file_name" json:"file_name" db:"file_name"` - AttachedByID *uint64 `gorm:"type:bigint;index;column:attached_by_id" json:"attached_by_id"` + AttachedByID *uint64 `gorm:"type:bigint;index;column:attached_by_id" json:"attached_by_id" db:"attached_by_id"` + TaskID *uint64 `gorm:"type:bigint;index;column:task_id" json:"task_id,omitempty" db:"task_id"` CreatedAt *time.Time `gorm:"default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"` } diff --git a/core/typescore/approval_task.go b/core/typescore/approval_task.go index d8ae972..afc36f8 100644 --- a/core/typescore/approval_task.go +++ b/core/typescore/approval_task.go @@ -3,14 +3,17 @@ package typescore import "time" type ApprovalTask struct { - ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" json:"id" db:"id"` - ApprovalID *uint64 `gorm:"type:bigint;not null;index;column:approval_id" json:"approval_id" db:"approval_id"` - ExecutorID *uint64 `gorm:"type:bigint;not null;index;column:executor_id" json:"executor_id" db:"executor_id"` - TaskText *string `gorm:"type:text;not null;column:task_text" json:"task_text" db:"task_text"` - Status *string `gorm:"type:text;not null;default:'pending';column:status" json:"status" db:"status"` - CompletedAt *time.Time `gorm:"type:timestamp;column:completed_at" json:"completed_at,omitempty" db:"completed_at"` - 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"` + ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" json:"id" db:"id"` + ApprovalID *uint64 `gorm:"type:bigint;not null;index;column:approval_id" json:"approval_id" db:"approval_id"` + ExecutorID *uint64 `gorm:"type:bigint;not null;index;column:executor_id" json:"executor_id" db:"executor_id"` + TaskText *string `gorm:"type:text;not null;column:task_text" json:"task_text" db:"task_text"` + Status *string `gorm:"type:text;not null;default:'pending';index;column:status" json:"status" db:"status"` + StepOrder *int `gorm:"type:int;default:0;column:step_order" json:"step_order" db:"step_order"` + RequireFile *bool `gorm:"type:boolean;default:false;column:require_file" json:"require_file" db:"require_file"` + TopicExecutorID *uint64 `gorm:"type:bigint;column:topic_executor_id" json:"topic_executor_id,omitempty" db:"topic_executor_id"` + CompletedAt *time.Time `gorm:"type:timestamp;column:completed_at" json:"completed_at,omitempty" db:"completed_at"` + 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"` Approval *Approval `gorm:"-" json:"approval,omitempty"` Executor *User `gorm:"-" json:"executor,omitempty"` diff --git a/core/typescore/approval_task_assigment.go b/core/typescore/approval_task_assigment.go new file mode 100644 index 0000000..0a805db --- /dev/null +++ b/core/typescore/approval_task_assigment.go @@ -0,0 +1,14 @@ +package typescore + +import "time" + +type ApprovalTaskAssignment struct { + ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique"` + ApprovalID *uint64 `gorm:"type:bigint;not null;index;column:approval_id"` + ExecutorID *uint64 `gorm:"type:bigint;not null;index;column:executor_id"` + TaskText *string `gorm:"type:text;not null;column:task_text"` + Status *string `gorm:"type:text;not null;default:'pending';column:status"` // pending|completed|cancelled + CompletedAt *time.Time `gorm:"type:timestamp;column:completed_at"` + CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at"` + UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at"` +} diff --git a/core/typescore/approval_topic.go b/core/typescore/approval_topic.go index b93b7d7..5294fd1 100644 --- a/core/typescore/approval_topic.go +++ b/core/typescore/approval_topic.go @@ -8,24 +8,31 @@ import "time" // PaymentType: own_expense | vacation_account | not_applicable (для partial) // Template хранит шаблон строки для подсказки пользователю при вводе. type ApprovalTopic struct { - ID *uint64 `gorm:"column:id;index;type:bigserial;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"` - CategoryID *uint64 `gorm:"type:bigint;not null;index;column:category_id" json:"category_id" db:"category_id" mapstructure:"category_id"` - Name *string `gorm:"type:text;not null;column:name" json:"name" db:"name" mapstructure:"name"` - Code *string `gorm:"type:text;not null;unique;column:code" json:"code" db:"code" mapstructure:"code"` + ID *uint64 `gorm:"column:id;index;type:bigserial;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"` + CategoryID *uint64 `gorm:"type:bigint;not null;index;column:category_id" json:"category_id" db:"category_id" mapstructure:"category_id"` + Name *string `gorm:"type:text;not null;column:name" json:"name" db:"name" mapstructure:"name"` + Code *string `gorm:"type:text;not null;unique;column:code" json:"code" db:"code" mapstructure:"code"` + ApprovalMode *string `gorm:"type:text;default:'sequential';column:approval_mode" db:"approval_mode"` + // sequential — последовательно (текущее поведение) + // any_of — любой из согласующих (задача 10) + DurationType *string `gorm:"type:text;column:duration_type" json:"duration_type,omitempty" db:"duration_type" mapstructure:"duration_type"` TimeType *string `gorm:"type:text;column:time_type" json:"time_type,omitempty" db:"time_type" mapstructure:"time_type"` PaymentType *string `gorm:"type:text;column:payment_type" json:"payment_type,omitempty" db:"payment_type" mapstructure:"payment_type"` Template *string `gorm:"type:text;column:template" json:"template" db:"template" mapstructure:"template"` - TaskTemplate *string `gorm:"type:text;column:task_template" json:"task_template,omitempty" db:"task_template" mapstructure:"task_template"` FirstApproverRoleCode *string `gorm:"type:text;column:first_approver_role_code" json:"first_approver_role_code,omitempty" db:"first_approver_role_code" mapstructure:"first_approver_role_code"` // если задан — первый согласующий выбирается из этой роли AllowsFile *bool `gorm:"type:boolean;not null;default:false;column:allows_file" json:"allows_file,omitempty" db:"allows_file" mapstructure:"allows_file"` AllowApproverSelection *bool `gorm:"type:boolean;not null;default:false;column:allow_approver_selection" json:"allow_approver_selection,omitempty" db:"allow_approver_selection" mapstructure:"allow_approver_selection"` AllowObserverSelection *bool `gorm:"type:boolean;not null;default:false;column:allow_observer_selection" json:"allow_observer_selection,omitempty" db:"allow_observer_selection" mapstructure:"allow_observer_selection"` - IsActive *bool `gorm:"type:boolean;not null;default:true;column:is_active" json:"is_active" db:"is_active" mapstructure:"is_active"` - 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"` + RequireApproverComment *bool `gorm:"type:boolean;default:false;column:require_approver_comment" json:"require_approver_comment" db:"require_approver_comment"` + RequiresFile *bool `gorm:"type:boolean;not null;default:false;column:requires_file" json:"requires_file" db:"requires_file"` + RequireObserverSelection *bool `gorm:"type:boolean;not null;default:false;column:require_observer_selection" json:"require_observer_selection" db:"require_observer_selection"` - Category *ApprovalTopicCategory `gorm:"-" json:"category,omitempty"` + IsActive *bool `gorm:"type:boolean;not null;default:true;column:is_active" json:"is_active" db:"is_active" mapstructure:"is_active"` + 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"` + Instructions *string `gorm:"type:text;column:instructions" json:"instructions,omitempty" db:"instructions"` + Category *ApprovalTopicCategory `gorm:"-" json:"category,omitempty"` } diff --git a/core/typescore/approval_topic_executor.go b/core/typescore/approval_topic_executor.go new file mode 100644 index 0000000..c377da3 --- /dev/null +++ b/core/typescore/approval_topic_executor.go @@ -0,0 +1,19 @@ +package typescore + +import "time" + +type ApprovalTopicExecutor struct { + ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"` + TopicID *uint64 `gorm:"type:bigint;not null;index;column:topic_id" json:"topic_id" db:"topic_id" mapstructure:"topic_id"` + UserID *uint64 `gorm:"type:bigint;not null;index;column:user_id" json:"user_id" db:"user_id" mapstructure:"user_id"` + StepOrder *int `gorm:"type:int;not null;default:0;column:step_order" json:"step_order" db:"step_order" mapstructure:"step_order"` + RequireFile *bool `gorm:"type:boolean;default:false;column:require_file" json:"require_file" db:"require_file" mapstructure:"require_file"` + TargetSystem *string `gorm:"type:text;column:target_system" json:"target_system,omitempty" db:"target_system" mapstructure:"target_system"` + TaskText *string `gorm:"type:text;column:task_text" json:"task_text,omitempty" db:"task_text" mapstructure:"task_text"` + IsActive *bool `gorm:"type:boolean;default:true;column:is_active" json:"is_active" db:"is_active" mapstructure:"is_active"` + 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"` + + Topic *ApprovalTopic `gorm:"-" json:"topic,omitempty"` + User *User `gorm:"-" json:"user,omitempty"` +} diff --git a/core/typescore/user_hierarchy.go b/core/typescore/user_hierarchy.go index 4aeea13..1583145 100644 --- a/core/typescore/user_hierarchy.go +++ b/core/typescore/user_hierarchy.go @@ -9,7 +9,6 @@ type UserHierarchy struct { ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"` SubordinateID *uint64 `gorm:"type:bigint;not null;index;column:subordinate_id" json:"subordinate_id" db:"subordinate_id" mapstructure:"subordinate_id"` ApproverID *uint64 `gorm:"type:bigint;not null;index;column:approver_id" json:"approver_id" db:"approver_id" mapstructure:"approver_id"` - ExecutorID *uint64 `gorm:"type:bigint;index;column:executor_id" json:"executor_id,omitempty" db:"executor_id" mapstructure:"executor_id"` DepartmentID *uint64 `gorm:"type:bigint;not null;index;column:department_id" json:"department_id" db:"department_id" mapstructure:"department_id"` TopicCategoryID *uint64 `gorm:"type:bigint;index;column:topic_category_id" json:"topic_category_id,omitempty" db:"topic_category_id" mapstructure:"topic_category_id"` TopicID *uint64 `gorm:"type:bigint;index;column:topic_id" json:"topic_id,omitempty" db:"topic_id" mapstructure:"topic_id"` diff --git a/core/typescore/user_sessions.go b/core/typescore/user_sessions.go new file mode 100644 index 0000000..8f6f3ad --- /dev/null +++ b/core/typescore/user_sessions.go @@ -0,0 +1,14 @@ +package typescore + +import "time" + +type DeviceList struct { + DeviceID string `json:"device_id"` + CreatedAt *time.Time `json:"created_at"` +} + +type UsersSessions struct { + UserID *uint64 `json:"user_id,omitempty"` + AuthorizedDevices []DeviceList `json:"authorized_devices"` + LastIP string `json:"last_ip"` +} diff --git a/go.work b/go.work index 2aae1c7..e758a7c 100644 --- a/go.work +++ b/go.work @@ -5,4 +5,5 @@ use ( ./service/rest_balancer_service service/telegram_service service/system_service + service/rest_admin_service ) diff --git a/service/rest_admin_service/.gitignore b/service/rest_admin_service/.gitignore new file mode 100644 index 0000000..89c0c75 --- /dev/null +++ b/service/rest_admin_service/.gitignore @@ -0,0 +1,5 @@ +.env +user-service_app +config.yml +vendor +app \ No newline at end of file diff --git a/service/rest_admin_service/.golangci.yml b/service/rest_admin_service/.golangci.yml new file mode 100644 index 0000000..ea1405d --- /dev/null +++ b/service/rest_admin_service/.golangci.yml @@ -0,0 +1,52 @@ +linters-settings: + errcheck: # Настройки для линтера errcheck, который проверяет, что ошибки не игнорируются + check-type-assertions: true # Не проверять утверждения типов на ошибки + check-blank: true # Проверять игнорирование ошибок через присваивание в _ + prealloc: # Настройки для линтера prealloc, который предлагает предварительное выделение памяти для срезов + simple: true # Простой режим, предлагает предварительное выделение для простых циклов + range-loops: true # Предлагает предварительное выделение для циклов range + for-loops: false # Не предлагает предварительное выделение для обычных for-циклов + gocyclo: # Настройки для линтера gocyclo, который проверяет сложность функций + min-complexity: 15 # Установите порог сложности, который считаете приемлемым + +linters: + enable: # Список линтеров, которые будут включены + - noctx # Находит отправку HTTP-запроса без контекста.Контекст. + - protogetter # Сообщает о прямом чтении из полей прото-сообщения, когда следует использовать геттеры. + - reassign # Проверяет, что переменные пакета не переназначаются. + - rowserrcheck # Проверяет, успешно ли проверен Rows.Err строк. + - sqlclosecheck # Проверяет, что sql.Rows, sql.Stmt, sqlx.NamedStmt, pgx.Query закрыты. + - ineffassign # Обнаруживает, когда назначения существующим переменным не используются. + - nilerr # Находит код, который возвращает ноль, даже если он проверяет, что ошибка не равна нулю. + - makezero # Проверяет, что нулевые значения создаются правильно + - gochecksumtype # Проверяет, что тип контрольной суммы в go.sum соответствует содержимому + - copyloopvar # Проверяет, что циклические зависимости пакетов не имеют экспортируемых идентификаторов + - exhaustive # Проверьте полноту операторов перечисления. + - errchkjson # Проверяет типы, передаваемые функциям кодирования JSON. Сообщает о неподдерживаемых типах и событиях, при которых проверку возвращаемой ошибки можно опустить. + - durationcheck # Проверяет, что длительность таймаута не равна 0 + - contextcheck # Проверяет, что контекст не игнорируется + - bodyclose # Проверяет, что тело запроса закрывается + - bidichk # Проверяет, что строки в исходном коде не содержат символов из разных языков + - govet # Проверяет код на наличие конструкций, которые могут быть ошибочными + - errcheck # Проверяет, что ошибки не игнорируются + - staticcheck # Статический анализ кода, находит ошибки, неэффективные конструкции и т.д. + - unused # Проверяет на неиспользуемые переменные, функции, константы + - gocritic # Линтер, основанный на проверке кода на соответствие определенным критериям качества и стиля + - stylecheck # Проверяет стиль кодирования + - whitespace # Проверяет проблемы с пробелами в коде + - gosec # Линтер gosec, который проверяет код на наличие потенциальных уязвимостей + - prealloc # Предлагает предварительное выделение памяти для срезов + + - dupl # Находит дублирующийся код + - gocyclo # Проверяет сложность функций + - ineffassign # Обнаруживает неэффективные присваивания + - unparam # Находит неиспользуемые параметры функций + + - gosimple # Предлагает упрощения кода + + disable: # Список линтеров, которые будут отключены + - gofumpt # Более строгая версия gofmt, применяет дополнительные правила форматирования + # - golint # Отключает golint, который проверяет стиль написания кода на Go + +run: + timeout: 15m # Устанавливает тайм-аут для выполнения всех линтеров \ No newline at end of file diff --git a/service/rest_admin_service/README.MD b/service/rest_admin_service/README.MD new file mode 100644 index 0000000..f201b6d --- /dev/null +++ b/service/rest_admin_service/README.MD @@ -0,0 +1,33 @@ +0.0.2 +# rest_admin_service + +### Инициализация проекта +```bash +go mod init sveves-team/fusionai-aggregator-backend/rest_admin_service +go mod tidy +go mod edit -replace sveves-team/fusionai-aggregator-backend/core=../../core +``` + + + +### Локальный старт +```bash +go run cmd/app.go +``` + +### Старт автотестов +``` bash +go test ./... +``` + +``` bash +go vet ./... +``` + +```bash +gofmt -w . +``` + +```bash +swag init -g cmd/app.go --dir ./,../../core +``` diff --git a/service/rest_admin_service/cmd/app.go b/service/rest_admin_service/cmd/app.go new file mode 100644 index 0000000..0ca3aeb --- /dev/null +++ b/service/rest_admin_service/cmd/app.go @@ -0,0 +1,164 @@ +package main + +import ( + configcore "bitrix_balancer_api/core/config" + clientcontrollers "bitrix_balancer_api/core/lib/internally/client-controllers" + typesm "bitrix_balancer_api/rest_admin_service/types" + "errors" + "fmt" + "github.com/go-chi/chi/v5" + "github.com/go-chi/chi/v5/middleware" + "github.com/go-chi/cors" + "github.com/go-chi/httprate" + "github.com/sirupsen/logrus" + "log" + "net/http" + "time" +) + +const ( + readTimeout = 15 * time.Minute // Таймаут чтения + writeTimeout = 15 * time.Minute // Таймаут записи + idleTimeout = 15 * time.Minute // Таймаут бездействия + rateLimit = 15 // Лимит запросов + rateWindow = 1 * time.Second // Окно времени для лимита запросов +) + +func main() { + err := initService() + if err != nil { + logrus.Errorln("🔴 failed to init common: ", err) + } + select {} +} + +func initService() error { + clientsExternal, err := getClientsExternal() + if err != nil { + logrus.Errorln("🔴 failed to load config: ", err) + return err + } + + ipc, err := initInternalProvider(clientsExternal) + if err != nil { + logrus.Errorln("🔴 failed to init internal provider: ", err) + return err + } + + router, err := initBaseApiRouter(ipc) + if err != nil { + logrus.Errorln("🔴 failed to init base api router: ", err) + return err + } + + if err := startRestApiServer(ipc, router); err != nil { + logrus.Errorln("🔴 failed to start server: ", err) + return err + } + + return nil +} + +func getClientsExternal() (clientcontrollers.ClientsExternal, error) { + options := &configcore.ConfigLoadOptions{ + Redis: true, + Database: true, + Secrets: configcore.SecretsOptions{ + AuthJWT: configcore.AuthJWTOptions{ + Admin: true, + }, + AdminAccessCode: true, + }, + } + + return clientcontrollers.ReturnClientsExternal(options) +} + +func initInternalProvider(clientsExternal clientcontrollers.ClientsExternal) (*typesm.InternalProviderControl, error) { + return &typesm.InternalProviderControl{ + Config: clientsExternal.Config, + RedisClient: clientsExternal.Redis, + Database: clientsExternal.DB, + }, nil +} + +func startRestApiServer(ipc *typesm.InternalProviderControl, router *chi.Mux) error { + serverPort := fmt.Sprintf("%d", ipc.Config.Server.RESTAdminService.PortRest) + + serverAddr := ":" + serverPort + httpServer := &http.Server{ + Addr: serverAddr, + Handler: router, + ReadTimeout: readTimeout, + WriteTimeout: writeTimeout, + IdleTimeout: idleTimeout, + } + + log.Printf("✅ Starting server on %s", serverAddr) + return httpServer.ListenAndServe() +} + +func initBaseApiRouter(ipc *typesm.InternalProviderControl) (*chi.Mux, error) { + router := chi.NewRouter() + 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"}, + ExposedHeaders: []string{"Link", "Cache-Control"}, + AllowCredentials: false, + MaxAge: 300, // Максимальное время жизни предварительных запросов в секундах + }) + + router.Use(corsOptions.Handler) + router.Use(middleware.RealIP) + + // Добавляем ограничение по IP + router.Use(httprate.LimitByIP(rateLimit, rateWindow)) + + if ipc.Database == nil { + return nil, errors.New("failed_to_connect_db") + } + + err := registerRoutes(router, ipc) + if err != nil { + return nil, err + } + + return router, nil +} + +// регистрирует маршруты +func registerRoutes(router chi.Router, ipc *typesm.InternalProviderControl) error { + // Слайс обработчиков маршрутов + routeHandlers := []struct { + name string + handler func(chi.Router, *typesm.InternalProviderControl) error + }{ + {"admin", adminhandler.RegisterAdminRoutes}, + } + + // Регистрация всех маршрутов + for _, rh := range routeHandlers { + if errObj := rh.handler(router, ipc); errObj != nil { + return errors.New(fmt.Sprintf("🔴 failed to register %s routes", rh.name)) + } + } + + // Вывод зарегистрированных маршрутов + if err := printRoutes(router, ipc); err != nil { + return errors.New(fmt.Sprintf("🔴 failed to print routes: %v", err)) + } + + return nil +} + +func printRoutes(r chi.Router, ipc *typesm.InternalProviderControl) error { + err := chi.Walk(r, func(method, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error { + logrus.Info(fmt.Sprintf("🩵 [ %s ] %s\n", method, route)) + return nil + }) + if err != nil { + return err + } + return nil +} diff --git a/service/rest_admin_service/go.mod b/service/rest_admin_service/go.mod new file mode 100644 index 0000000..38f492d --- /dev/null +++ b/service/rest_admin_service/go.mod @@ -0,0 +1,5 @@ +module bitrix_balancer_api/rest_admin_service + +replace bitrix_balancer_api/core => ../../core + +go 1.25.6 diff --git a/service/rest_admin_service/handlers/middleware.go b/service/rest_admin_service/handlers/middleware.go new file mode 100644 index 0000000..0b7da34 --- /dev/null +++ b/service/rest_admin_service/handlers/middleware.go @@ -0,0 +1,217 @@ +package handlers + +import ( + configcore "bitrix_balancer_api/core/config" + dbcore "bitrix_balancer_api/core/db/methods" + redismodule "bitrix_balancer_api/core/lib/internally/redis" + "bitrix_balancer_api/core/securecore" + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/core/utilscore" + "bitrix_balancer_api/core/variables" + "context" + "encoding/json" + "errors" + "fmt" + "log" + "net/http" + "strconv" + "strings" + "time" +) + +func BasicAuthMiddleware(username, password string) func(http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + user, pass, ok := r.BasicAuth() + if !ok || !validateCredentials(user, pass, username, password) { + w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`) + http.Error(w, "Unauthorized", http.StatusUnauthorized) + return + } + next.ServeHTTP(w, r) + }) + } +} + +func validateCredentials(username, password, validUsername, validPassword string) bool { + return username == validUsername && password == validPassword +} + +// JWTVerifier middleware для проверки JWT токена и соответствия IP +func JWTVerifier(cfg *configcore.Config, adminDB dbcore.AdminDBI, redisModule *redismodule.ModuleRedis) func(http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if cfg.Secrets.AuthJWT.AdminSecret == "" { + http.Error(w, "Internal server error", http.StatusInternalServerError) + return + } + + authHeader := r.Header.Get("Authorization") + if authHeader == "" { + http.Error(w, "Unauthorized", http.StatusUnauthorized) + return + } + + deviceID := r.Header.Get("x-device-id") + if deviceID == "" { + http.Error(w, "Unauthorized device", http.StatusUnauthorized) + return + } + + if redisModule == nil { + http.Error(w, "Internal server error: Redis storage not initialized", http.StatusInternalServerError) + return + } + + parts := strings.Split(authHeader, " ") + if len(parts) != 2 || parts[0] != "Bearer" { + http.Error(w, "Invalid authorization header", http.StatusUnauthorized) + return + } + tokenString := parts[1] + + _, claims, err := securecore.VerifyToken(tokenString, cfg.Secrets.AuthJWT.AdminSecret) + if err != nil { + http.Error(w, "Invalid token", http.StatusUnauthorized) + return + } + + userIDFloat, ok := claims[securecore.IDContextKey.String()].(float64) + if !ok { + http.Error(w, "Invalid token: missing user_id", http.StatusUnauthorized) + return + } + userID := uint64(userIDFloat) + + adminList, _, errW := adminDB.GetAdminsListDB(typescore.ListDbOptions{ + Filtering: &typescore.Admin{ + ID: &userID, + IsBlocked: utilscore.PointerToBool(false), + }, + }) + if errW != nil || len(adminList) == 0 { + http.Error(w, "Admin not found or blocked", http.StatusUnauthorized) + return + } + + if adminList[0].IsBlocked == nil || *adminList[0].IsBlocked { + http.Error(w, "Forbidden: account is blocked", http.StatusUnauthorized) + return + } + + ctx := context.WithValue(r.Context(), securecore.IDContextKey, userID) + + sessionJSON, err := redisModule.Get(ctx, fmt.Sprintf("%s:admin:%d", variables.RedisPathUserAuthSessions, userID)) + if err != nil || sessionJSON == "" { + http.Error(w, "User session not found. Please authorize again", http.StatusUnauthorized) + return + } + + var session typescore.UsersSessions + if err := json.Unmarshal([]byte(sessionJSON), &session); err != nil { + http.Error(w, "Failed to get user session data. Please authorize again", http.StatusUnauthorized) + return + } + + if !securecore.FindDeviceID(session.AuthorizedDevices, deviceID) { + http.Error(w, "Unauthorized device", http.StatusUnauthorized) + return + } + + next.ServeHTTP(w, r.WithContext(ctx)) + }) + } +} + +// AccessCodeVerifier middleware для проверки Access Code для валидного фронта +func AccessCodeVerifier(cfg *configcore.Config) func(http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if cfg.Secrets.ApiPublicAdmin == "" || cfg.Secrets.ApiPrivateAdmin == "" { + http.Error(w, "Internal server error", http.StatusInternalServerError) + return + } + + authHeader := r.Header.Get("ApiKey") + timestampStr := r.Header.Get("X-Timestamp") + + if authHeader == "" || timestampStr == "" { + http.Error(w, "Unauthorized client", http.StatusUnauthorized) + return + } + + // Парсим timestamp как Unix timestamp + timestampUnix, err := strconv.ParseInt(timestampStr, 10, 64) + if err != nil { + http.Error(w, "Invalid timestamp", http.StatusBadRequest) + return + } + + // Конвертируем Unix timestamp в time.Time + // Unix timestamp всегда представляет время в UTC + timestampTime := time.Unix(timestampUnix, 0).UTC() + now := time.Now().UTC() + + // Округляем время до минут, игнорируя секунды и миллисекунды + // Используем time.Date для явного обнуления секунд и наносекунд + timestampTimeRounded := time.Date( + timestampTime.Year(), timestampTime.Month(), timestampTime.Day(), + timestampTime.Hour(), timestampTime.Minute(), 0, 0, time.UTC, + ) + nowRounded := time.Date( + now.Year(), now.Month(), now.Day(), + now.Hour(), now.Minute(), 0, 0, time.UTC, + ) + + // Проверяем, что timestamp не старше 3 минут и не в будущем + // Используем Before/After для более точной проверки времени + threeMinutesAgo := nowRounded.Add(-3 * time.Minute) + + // Проверяем, что timestamp не не старше 3 минут + if timestampTimeRounded.Before(threeMinutesAgo) { + log.Printf("Timestamp expired - received: %v (rounded: %v), current: %v (rounded: %v), 3min ago: %v", + timestampTime, timestampTimeRounded, now, nowRounded, threeMinutesAgo) + http.Error(w, "Timestamp expired", http.StatusUnauthorized) + return + } + + // Проверяем, что timestamp не в будущем + if timestampTimeRounded.After(nowRounded) { + log.Printf("Timestamp in future - received: %v (rounded: %v), current: %v (rounded: %v)", + timestampTime, timestampTimeRounded, now, nowRounded) + http.Error(w, "Timestamp in future", http.StatusUnauthorized) + return + } + + // Генерируем ожидаемую подпись + expectedSignature := utilscore.GenerateHMACSignature(cfg.Secrets.ApiPublicAdmin, timestampStr, cfg.Secrets.ApiPrivateAdmin) + + // Сравниваем безопасно + if !utilscore.HmacEquals(expectedSignature, authHeader) { + http.Error(w, "Unauthorized client", http.StatusUnauthorized) + return + } + + ctx := context.WithValue(r.Context(), securecore.AccessContextKey, authHeader) + next.ServeHTTP(w, r.WithContext(ctx)) + }) + } +} + +// GetIDFromContext извлекает user id из контекста +func GetIDFromContext(ctx context.Context) (uint64, error) { + address, ok := ctx.Value(securecore.IDContextKey).(uint64) + if !ok { + return 0, errors.New("no id found in context") + } + return address, nil +} + +// GetIPFromContext извлекает user ip из контекста +func GetIPFromContext(ctx context.Context) (string, error) { + address, ok := ctx.Value(securecore.IpContextKey).(string) + if !ok { + return "", errors.New("no ip found in context") + } + return address, nil +} diff --git a/service/rest_admin_service/handlers/register.go b/service/rest_admin_service/handlers/register.go new file mode 100644 index 0000000..88e93fc --- /dev/null +++ b/service/rest_admin_service/handlers/register.go @@ -0,0 +1,131 @@ +package handlers + +import ( + "encoding/json" + "errors" + "github.com/go-chi/chi/v5" + "io" + "net/http" +) + +// ErrorResponse структура для возврата ошибок +type ErrorResponse struct { + ErrorCode int `json:"error_code"` // Код ошибки + ErrorDescription string `json:"error_description"` // Описание ошибки +} + +// WrapHandlerParams структура для параметров обертки +type WrapHandlerParams struct { + HandlerFunc func(http.ResponseWriter, *http.Request) (interface{}, error) +} + +// responseWriterWrapper предотвращает повторный вызов WriteHeader +type responseWriterWrapper struct { + http.ResponseWriter + wroteHeader bool +} + +// WriteHeader перехватывает вызов WriteHeader +func (rw *responseWriterWrapper) WriteHeader(statusCode int) { + if !rw.wroteHeader { + rw.ResponseWriter.WriteHeader(statusCode) + rw.wroteHeader = true + } +} + +// Write перехватывает вызов Write +func (rw *responseWriterWrapper) Write(b []byte) (int, error) { + if !rw.wroteHeader { + rw.WriteHeader(http.StatusOK) // Устанавливаем статус по умолчанию + } + return rw.ResponseWriter.Write(b) +} + +// WrapHandlerF обертка для обработчиков +func WrapHandlerF(p WrapHandlerParams) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + rw := &responseWriterWrapper{ResponseWriter: w} + payload, err := p.HandlerFunc(rw, r) + respondWithJSON(rw, err, payload) + } +} + +// RegisterRoute вспомогательная функция для регистрации маршрутов +func RegisterRoute(r chi.Router, method, path string, handlerFunc func(http.ResponseWriter, *http.Request) (interface{}, error)) { + wrappedHandler := WrapHandlerF(WrapHandlerParams{ + HandlerFunc: handlerFunc, + }) + + switch method { + case http.MethodGet: + r.Get(path, wrappedHandler) + case http.MethodPost: + r.Post(path, wrappedHandler) + case http.MethodPatch: + r.Patch(path, wrappedHandler) + case http.MethodPut: + r.Put(path, wrappedHandler) + case http.MethodDelete: + r.Delete(path, wrappedHandler) + } +} + +// ParseRequestBodyPost обрабатывает тело запроса и заполняет структуру запроса +func ParseRequestBodyPost(r *http.Request, v interface{}) error { + defer r.Body.Close() + + if r.ContentLength == 0 { + return errors.New("body content is empty") + } + + body, err := io.ReadAll(r.Body) + if err != nil { + return err + } + + if err := json.Unmarshal(body, v); err != nil { + return err + } + + return nil +} + +// respondWithJSON отправляет ответ в формате JSON +func respondWithJSON(w http.ResponseWriter, err error, payload interface{}) { + w.Header().Set("Content-Type", "application/json") + + var status int + var response []byte + + if err != nil { + status = http.StatusInternalServerError + errorResponse := ErrorResponse{ + ErrorCode: status, + ErrorDescription: err.Error(), + } + response, _ = json.Marshal(errorResponse) + } else { + response, err = json.Marshal(payload) + if err != nil { + status = http.StatusInternalServerError + errorResponse := ErrorResponse{ + ErrorCode: status, + ErrorDescription: err.Error(), + } + response, _ = json.Marshal(errorResponse) + } else { + status = http.StatusOK + } + } + + // Проверяем, является ли w нашим responseWriterWrapper + if rw, ok := w.(*responseWriterWrapper); ok { + if !rw.wroteHeader { + rw.WriteHeader(status) + } + } else { + w.WriteHeader(status) + } + + _, _ = w.Write(response) +} diff --git a/service/rest_admin_service/types/module.go b/service/rest_admin_service/types/module.go new file mode 100644 index 0000000..41ddded --- /dev/null +++ b/service/rest_admin_service/types/module.go @@ -0,0 +1,15 @@ +package typesm + +import ( + configcore "bitrix_balancer_api/core/config" + database "bitrix_balancer_api/core/db" + "bitrix_balancer_api/core/lib/external/tgkit" + redismodule "bitrix_balancer_api/core/lib/internally/redis" +) + +type InternalProviderControl struct { + Config *configcore.Config + RedisClient *redismodule.ModuleRedis + TGBotClient *tgkit.Client + Database *database.ModuleDB +} diff --git a/service/rest_admin_service/types/req.go b/service/rest_admin_service/types/req.go new file mode 100644 index 0000000..23e7112 --- /dev/null +++ b/service/rest_admin_service/types/req.go @@ -0,0 +1,13 @@ +package typesm + +type LimitRequest struct { + Limit uint64 `json:"limit"` + Offset uint64 `json:"offset"` +} + +type Response struct { + TotalCount *uint64 `json:"total_count,omitempty"` + Count int `json:"count,omitempty"` + Error *string `json:"error,omitempty"` + Data interface{} `json:"data,omitempty"` +} diff --git a/service/rest_admin_service/version b/service/rest_admin_service/version new file mode 100644 index 0000000..be26007 --- /dev/null +++ b/service/rest_admin_service/version @@ -0,0 +1 @@ +v-0.0.3 \ No newline at end of file diff --git a/service/telegram_service/cmd/app.go b/service/telegram_service/cmd/app.go index 953fa28..e79e65b 100644 --- a/service/telegram_service/cmd/app.go +++ b/service/telegram_service/cmd/app.go @@ -7,7 +7,9 @@ import ( tgupdatehandler "bitrix_balancer_api/telegram_service/common/update" "bitrix_balancer_api/telegram_service/scheduler" "bitrix_balancer_api/telegram_service/types" + "github.com/sirupsen/logrus" "log" + "net/url" "runtime/debug" ) @@ -57,6 +59,14 @@ func getClientsExternal() (clientcontrollers.ClientsExternal, error) { } func initInternalProvider(cfg *configcore.Config, clientsExternal clientcontrollers.ClientsExternal) (*types.InternalProviderControl, error) { + if cfg.Telegram.ProxyURL != "" { + parsed, err := url.Parse(cfg.Telegram.ProxyURL) + if err != nil { + logrus.Fatalf("Invalid proxy URL '%s': %v", cfg.Telegram.ProxyURL, err) + } + cfg.Telegram.ParsedProxy = parsed + logrus.Infof("Proxy configured: %s", cfg.Telegram.ProxyURL) + } tgKitClient, err := tgkit.GetClient(tgkit.ClientConfig{ Token: cfg.Telegram.BotToken, Proxy: &tgkit.ProxyConfig{ diff --git a/service/telegram_service/common/update/callback.go b/service/telegram_service/common/update/callback.go index 2579004..31461ec 100644 --- a/service/telegram_service/common/update/callback.go +++ b/service/telegram_service/common/update/callback.go @@ -192,12 +192,7 @@ func (s *UpdateHandler) handleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.Callba s.approvalHandler.HandleAttachFileStart(bot, cq, approvalID) case strings.HasPrefix(data, "appr_attach_cancel:"): - ctx := context.Background() - key := fmt.Sprintf("appr_attach_file:%d", cq.From.ID) - s.ipc.RedisClient.Del(ctx, key) //nolint:errcheck - bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck - bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck - bot.Send(tgbotapi.NewMessage(cq.Message.Chat.ID, "❌ Отменено")) //nolint:errcheck + s.approvalHandler.HandleAttachCancel(bot, cq) // ── НАВИГАЦИЯ ФЛОУ ────────────────────────────────────────── case strings.HasPrefix(data, "appr_back:"): @@ -374,12 +369,6 @@ func (s *UpdateHandler) handleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.Callba bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck // ── ОТЧЁТ ─────────────────────────────────────────────────── - case data == "report_type_approvals": - s.approvalHandler.HandleReportTypeSelection(bot, cq, "approvals") - - case data == "report_type_tasks": - s.approvalHandler.HandleReportTypeSelection(bot, cq, "tasks") - case data == "report_set_dates": s.approvalHandler.HandleReportSetDates(bot, cq) @@ -403,6 +392,10 @@ func (s *UpdateHandler) handleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.Callba approvalID := parseID(data, "appr_comment:") s.approvalHandler.HandleAddCommentCallback(bot, cq, approvalID) + case strings.HasPrefix(data, "comment_reply:"): + approvalID := parseID(data, "comment_reply:") + s.approvalHandler.HandleCommentReplyCallback(bot, cq, approvalID) + // ВЫБОР СОГЛАСУЮЩЕГО case strings.HasPrefix(data, "select_approver:"): approverID := parseID(data, "select_approver:") @@ -416,6 +409,57 @@ 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, "appr_view_files:"): + approvalID := parseID(data, "appr_view_files:") + s.approvalHandler.HandleViewFilesCallback(bot, cq, approvalID) + + // Мои заявки + case strings.HasPrefix(data, "my_appr_topic:"): + topicFilter := strings.TrimPrefix(data, "my_appr_topic:") + s.approvalHandler.HandleMyApprovalsTopicCallback(bot, cq, topicFilter) + + case strings.HasPrefix(data, "my_appr_status:"): + // формат: my_appr_status:{status}:{topicFilter} + parts := strings.SplitN(strings.TrimPrefix(data, "my_appr_status:"), ":", 2) + status := parts[0] + topicFilter := "all" + if len(parts) > 1 { + topicFilter = parts[1] + } + s.approvalHandler.HandleMyApprovalsStatusCallback(bot, cq, status, topicFilter) + + case data == "my_appr_back": + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck + s.approvalHandler.HandleMyApprovals(bot, cq.Message.Chat.ID, cq.From.ID) + + case strings.HasPrefix(data, "appr_appr_topic:"): + topicFilter := strings.TrimPrefix(data, "appr_appr_topic:") + s.approvalHandler.HandleApproverApprovalsTopicCallback(bot, cq, topicFilter) + + case strings.HasPrefix(data, "appr_appr_status:"): + // формат: appr_appr_status:{status}:{topicFilter} + parts := strings.SplitN(strings.TrimPrefix(data, "appr_appr_status:"), ":", 2) + status, topicFilter := parts[0], "all" + if len(parts) == 2 { + topicFilter = parts[1] + } + s.approvalHandler.HandleApproverApprovalsStatusCallback(bot, cq, status, topicFilter) + + case data == "appr_appr_back": + s.approvalHandler.HandleApproverApprovals(bot, cq.Message.Chat.ID, cq.From.ID) + + case strings.HasPrefix(data, "obs_topic_page:"): + page := 0 + fmt.Sscanf(strings.TrimPrefix(data, "obs_topic_page:"), "%d", &page) + bot.Request(tgbotapi.NewCallback(cq.ID, "")) + bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) + s.approvalHandler.HandleObservedApprovalsPage(bot, cq.Message.Chat.ID, cq.From.ID, page) + + case data == "obs_topic_noop": + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + // ВЫБОР ПЕРВОГО НАБЛДАТЕЛЯ case strings.HasPrefix(data, "obs_select_toggle:"): observerID := parseID(data, "obs_select_toggle:") @@ -426,7 +470,7 @@ func (s *UpdateHandler) handleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.Callba fmt.Sscanf(strings.TrimPrefix(data, "obs_select_page:"), "%d", &page) s.approvalHandler.HandleObserverPageCallback(bot, cq, page) - case data == "obs_select_confirm": + case strings.HasPrefix(data, "obs_confirm"): s.approvalHandler.HandleObserverConfirmCallback(bot, cq) case data == "obs_select_noop": @@ -445,6 +489,35 @@ func (s *UpdateHandler) handleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.Callba case data == "first_approver_noop": bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + case strings.HasPrefix(data, "revoke_task_no_changes:"): + var taskID, approvalID uint64 + fmt.Sscanf(strings.TrimPrefix(data, "revoke_task_no_changes:"), "%d:%d", &taskID, &approvalID) + s.approvalHandler.HandleRevokeTaskNoChanges(bot, cq, taskID, approvalID) + + case strings.HasPrefix(data, "revoke_task_has_changes:"): + var taskID, approvalID uint64 + fmt.Sscanf(strings.TrimPrefix(data, "revoke_task_has_changes:"), "%d:%d", &taskID, &approvalID) + s.approvalHandler.HandleRevokeTaskHasChanges(bot, cq, taskID, approvalID) + + case strings.HasPrefix(data, "executor_attach:"): + parts := strings.Split(data, ":") + if len(parts) >= 3 { + taskID, _ := strconv.ParseUint(parts[1], 10, 64) + approvalID, _ := strconv.ParseUint(parts[2], 10, 64) + s.approvalHandler.HandleExecutorAttachStart(bot, cq, approvalID, taskID) + } + + case strings.HasPrefix(data, "attach_submit:"): + approvalID := parseID(data, "attach_submit:") + s.approvalHandler.HandleAttachSubmit(bot, cq, approvalID) + + case strings.HasPrefix(data, "attach_clear:"): + approvalID := parseID(data, "attach_clear:") + s.approvalHandler.HandleAttachClear(bot, cq, approvalID) + + case strings.HasPrefix(data, "attach_cancel:"): + s.approvalHandler.HandleAttachCancel(bot, cq) + // ── ПРОЧЕЕ ────────────────────────────────────────────────── case data == "restart_bot": bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck diff --git a/service/telegram_service/common/update/update.go b/service/telegram_service/common/update/update.go index 73c32be..0148d32 100644 --- a/service/telegram_service/common/update/update.go +++ b/service/telegram_service/common/update/update.go @@ -1,14 +1,11 @@ package tgupdatehandler import ( - "bitrix_balancer_api/telegram_service/keyboard" "context" "fmt" - "strings" - "time" - tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" "github.com/sirupsen/logrus" + "strings" ) func (s *UpdateHandler) GetUpdateTelegram() { @@ -47,11 +44,8 @@ func (s *UpdateHandler) handleMessage(bot *tgbotapi.BotAPI, msg *tgbotapi.Messag return } - // Постоянные кнопки меню + // ── Постоянные кнопки меню ─────────────────────────────────────────────── switch msg.Text { - // ═══════════════════════════════════════════════════════════ - // ГЛАВНОЕ МЕНЮ - // ═══════════════════════════════════════════════════════════ case "👤 Инициатор": s.withDepartmentCheck(bot, msg, func() { s.approvalHandler.HandleInitiatorSubmenu(bot, msg.Chat.ID) @@ -89,31 +83,18 @@ func (s *UpdateHandler) handleMessage(bot *tgbotapi.BotAPI, msg *tgbotapi.Messag }) return - // ═══════════════════════════════════════════════════════════ - // ПОДМЕНЮ ИНИЦИАТОРА - // ═══════════════════════════════════════════════════════════ case "➕ Создать согласование": s.withDepartmentCheck(bot, msg, func() { - s.approvalHandler.HandleMenu(bot, msg.Chat.ID, msg.From.ID) // показ тем + s.approvalHandler.HandleMenu(bot, msg.Chat.ID, msg.From.ID) }) return case "Ранее созданные согласования": s.withDepartmentCheck(bot, msg, func() { - // Сохраняем контекст: фильтр для инициатора (без "Добавить согласующего") - ctx := context.Background() - filterKey := fmt.Sprintf("filter_context:%d", msg.From.ID) - s.ipc.RedisClient.Set(ctx, filterKey, "initiator", 5*time.Minute) //nolint:errcheck - // Показываем подменю фильтров - menuMsg := tgbotapi.NewMessage(msg.Chat.ID, "🔍 Выберите статус заявок:") - menuMsg.ReplyMarkup = keyboard.BuildFilterSubmenu(false) // withoutAddApprover - bot.Send(menuMsg) //nolint:errcheck + s.approvalHandler.HandleMyApprovals(bot, msg.Chat.ID, msg.From.ID) }) return - // ═══════════════════════════════════════════════════════════ - // ПОДМЕНЮ СОГЛАСУЮЩЕГО - // ═══════════════════════════════════════════════════════════ case "Принять согласование в работу": s.withDepartmentCheck(bot, msg, func() { s.approvalHandler.HandleIncomingApprovals(bot, msg.Chat.ID, msg.From.ID) @@ -128,14 +109,7 @@ func (s *UpdateHandler) handleMessage(bot *tgbotapi.BotAPI, msg *tgbotapi.Messag case "Список согласований": s.withDepartmentCheck(bot, msg, func() { - // Сохраняем контекст: фильтр для согласующего (с "Добавить согласующего") - ctx := context.Background() - filterKey := fmt.Sprintf("filter_context:%d", msg.From.ID) - s.ipc.RedisClient.Set(ctx, filterKey, "approver", 5*time.Minute) //nolint:errcheck - // Показываем подменю фильтров - menuMsg := tgbotapi.NewMessage(msg.Chat.ID, "🔍 Выберите статус заявок:") - menuMsg.ReplyMarkup = keyboard.BuildFilterSubmenu(true) // withAddApprover - bot.Send(menuMsg) //nolint:errcheck + s.approvalHandler.HandleApproverApprovals(bot, msg.Chat.ID, msg.From.ID) }) return @@ -151,37 +125,26 @@ func (s *UpdateHandler) handleMessage(bot *tgbotapi.BotAPI, msg *tgbotapi.Messag }) return - // ═══════════════════════════════════════════════════════════ - // ПОДМЕНЮ НАБЛЮДАТЕЛЯ - // ═══════════════════════════════════════════════════════════ case "Наблюдать за согласованием": s.withDepartmentCheck(bot, msg, func() { s.approvalHandler.HandleObservedApprovals(bot, msg.Chat.ID, msg.From.ID) }) return - // ═══════════════════════════════════════════════════════════ - // ПОДМЕНЮ ИСПОЛНИТЕЛЯ - // ═══════════════════════════════════════════════════════════ case "Задачи к исполнению": s.withDepartmentCheck(bot, msg, func() { s.approvalHandler.HandleMyTasks(bot, msg.Chat.ID, msg.From.ID) }) return - // ═══════════════════════════════════════════════════════════ - // ФИЛЬТРЫ (универсальная обработка с контекстом) - // ═══════════════════════════════════════════════════════════ case "Все", "Согласованные", "Не согласованные", "Ожидают согласования": statusMap := map[string]string{ "Все": "all", "Согласованные": "approved", "Не согласованные": "rejected", "Ожидают согласования": "pending", } s.approvalHandler.HandleMyApprovalsByStatus(bot, msg.Chat.ID, msg.From.ID, statusMap[msg.Text]) + return - // ═══════════════════════════════════════════════════════════ - // ОБЩИЕ КНОПКИ (всегда доступны) - // ═══════════════════════════════════════════════════════════ case "❓ Как создать согласование?": s.withDepartmentCheck(bot, msg, func() { s.faqHandler.Handle(bot, msg) @@ -194,9 +157,6 @@ func (s *UpdateHandler) handleMessage(bot *tgbotapi.BotAPI, msg *tgbotapi.Messag }) return - // ═══════════════════════════════════════════════════════════ - // НАВИГАЦИЯ "НАЗАД" - // ═══════════════════════════════════════════════════════════ case "← Назад": s.withDepartmentCheck(bot, msg, func() { s.approvalHandler.HandleBackNavigation(bot, msg.Chat.ID, msg.From.ID) @@ -213,15 +173,33 @@ func (s *UpdateHandler) handleMessage(bot *tgbotapi.BotAPI, msg *tgbotapi.Messag return } - // Обработка текста/файлов инициатором при доработке + approveCommentKey := fmt.Sprintf("appr_approve_comment_pending:%d", msg.From.ID) + if val, err := s.ipc.RedisClient.Get(ctx, approveCommentKey); err == nil && val != "" { + var approvalID uint64 + fmt.Sscanf(val, "%d", &approvalID) + s.ipc.RedisClient.Del(ctx, approveCommentKey) //nolint:errcheck + s.approvalHandler.HandleDecisionWithChat(bot, msg.Chat.ID, msg.From.ID, approvalID, true, strings.TrimSpace(msg.Text)) + return + } + + rejectKey := fmt.Sprintf("appr_reject_pending:%d", msg.From.ID) + if val, err := s.ipc.RedisClient.Get(ctx, rejectKey); err == nil && val != "" { + var approvalID uint64 + fmt.Sscanf(val, "%d", &approvalID) + s.ipc.RedisClient.Del(ctx, rejectKey) //nolint:errcheck + s.approvalHandler.HandleDecisionWithChat(bot, msg.Chat.ID, msg.From.ID, approvalID, false, strings.TrimSpace(msg.Text)) + return + } + if s.approvalHandler.HandleRevisionTextInput(bot, msg) { return } + if s.approvalHandler.HandleAttachFileInput(bot, msg) { + return + } if s.approvalHandler.HandleRevisionFileInput(bot, msg) { return } - - // Обработка pending состояний if s.approvalHandler.HandlePendingCommentInput(bot, msg) { return } @@ -231,32 +209,16 @@ func (s *UpdateHandler) handleMessage(bot *tgbotapi.BotAPI, msg *tgbotapi.Messag if s.startHandler.HandleTextInput(bot, msg) { return } + if s.approvalHandler.HandleCommentReplyInput(bot, msg) { + return + } if s.approvalHandler.HandleCommentTextInput(bot, msg) { return } - // Проверяем состояние предложения if s.suggestionHandler.HandleSuggestionTextInput(bot, msg) { return } - // Проверка pending состояния для отказа - rejectKey := fmt.Sprintf("appr_reject_pending:%d", msg.From.ID) - if val, err := s.ipc.RedisClient.Get(ctx, rejectKey); err == nil && val != "" { - var approvalID uint64 - fmt.Sscanf(val, "%d", &approvalID) - s.ipc.RedisClient.Del(ctx, rejectKey) //nolint:errcheck - s.approvalHandler.HandleDecisionWithChat(bot, msg.Chat.ID, approvalID, false, strings.TrimSpace(msg.Text)) - return - } - - if s.approvalHandler.HandleRevisionFileInput(bot, msg) { - return - } - - if s.approvalHandler.HandleAttachFileInput(bot, msg) { - return - } - if msg.Photo != nil || msg.Document != nil { s.withDepartmentCheck(bot, msg, func() { s.approvalHandler.HandleFileInput(bot, msg) @@ -271,15 +233,6 @@ func (s *UpdateHandler) handleMessage(bot *tgbotapi.BotAPI, msg *tgbotapi.Messag return } - // Обработка файлов - if msg.Photo != nil || msg.Document != nil { - s.withDepartmentCheck(bot, msg, func() { - s.approvalHandler.HandleFileInput(bot, msg) - }) - return - } - - // Обработка текстового ввода s.withDepartmentCheck(bot, msg, func() { s.approvalHandler.HandleTextInput(bot, msg) }) diff --git a/service/telegram_service/handlers/approval/approver_approvals.go b/service/telegram_service/handlers/approval/approver_approvals.go new file mode 100644 index 0000000..5c68e3b --- /dev/null +++ b/service/telegram_service/handlers/approval/approver_approvals.go @@ -0,0 +1,211 @@ +package approval + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/core/utilscore" + "context" + "fmt" + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" + "github.com/sirupsen/logrus" +) + +// HandleApproverApprovals — вход в флоу: показываем темы, по которым +// пользователь участвовал как согласующий. +func (h *Handler) HandleApproverApprovals(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) { + ctx := context.Background() + + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || user == nil || user.ID == nil { + return + } + + // Категории, в которых пользователь был согласующим + categories, err := h.ipc.Database.ApprovalTopicCategory.GetCategoriesWithApprovalsByApproverDB(ctx, *user.ID) + if err != nil || len(categories) == 0 { + // Сразу показываем все без фильтра по теме + h.HandleApproverApprovalsStatusCallback( + bot, + &tgbotapi.CallbackQuery{ + Message: &tgbotapi.Message{Chat: &tgbotapi.Chat{ID: chatID}}, + From: &tgbotapi.User{ID: telegramID}, + }, + "all", "all", + ) + return + } + + msg := tgbotapi.NewMessage(chatID, "📂 Согласования в работе\n\nВыберите тему:") + msg.ParseMode = "HTML" + msg.ReplyMarkup = buildApproverApprovalsTopicFilter(categories) + bot.Send(msg) //nolint:errcheck +} + +// HandleApproverApprovalsTopicCallback — пользователь выбрал тему. +func (h *Handler) HandleApproverApprovalsTopicCallback( + bot *tgbotapi.BotAPI, + cq *tgbotapi.CallbackQuery, + topicFilter string, +) { + ctx := context.Background() + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck + + header := "Все темы" + if topicFilter != "all" && topicFilter != "" { + cat, _ := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByCodeDB(ctx, topicFilter) + if cat != nil && cat.Name != nil { + header = *cat.Name + } + } + + msg := tgbotapi.NewMessage(cq.Message.Chat.ID, + fmt.Sprintf("📂 %s\n\nВыберите статус:", header), + ) + msg.ParseMode = "HTML" + msg.ReplyMarkup = buildApproverApprovalsStatusFilter(topicFilter) + bot.Send(msg) //nolint:errcheck +} + +// HandleApproverApprovalsStatusCallback — пользователь выбрал статус, +// показываем список согласований, где он был согласующим. +func (h *Handler) HandleApproverApprovalsStatusCallback( + bot *tgbotapi.BotAPI, + cq *tgbotapi.CallbackQuery, + status, topicFilter string, +) { + ctx := context.Background() + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck + + 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 + } + + stepStatus := status + if stepStatus == "all" { + stepStatus = "" + } + + stepFilter := &typescore.ApprovalStep{ + ApproverID: user.ID, + } + if stepStatus != "" { + stepFilter.Status = utilscore.PointerToString(stepStatus) + } + + steps, _, err := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ + Filtering: stepFilter, + }) + if err != nil { + logrus.Errorf("HandleApproverApprovalsStatusCallback: GetApprovalStepsListDB err=%v", err) + sendText(bot, chatID, "Ошибка при получении заявок.") + return + } + + allowedTopicIDs := make(map[uint64]bool) + if topicFilter != "" && topicFilter != "all" { + cat, _ := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByCodeDB(ctx, topicFilter) + if cat != nil && cat.ID != nil { + topics, _, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalTopic{CategoryID: cat.ID}, + }) + for _, t := range topics { + if t.ID != nil { + allowedTopicIDs[*t.ID] = true + } + } + } + } + + // Дедублируем approvalID + seen := make(map[uint64]struct{}) + var filtered []*typescore.ApprovalStep + for _, step := range steps { + if step.ApprovalID == nil { + continue + } + if _, ok := seen[*step.ApprovalID]; ok { + continue + } + seen[*step.ApprovalID] = struct{}{} + filtered = append(filtered, step) + } + + if len(filtered) == 0 { + sendText(bot, chatID, "📭 Заявок по выбранным фильтрам не найдено.") + return + } + + sent := 0 + for _, step := range filtered { + approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, *step.ApprovalID) + if err != nil || approval == nil { + continue + } + + // 🚀 Фильтр по теме через map разрешённых ID + if len(allowedTopicIDs) > 0 { + if approval.TopicID == nil || !allowedTopicIDs[*approval.TopicID] { + continue + } + } + + h.sendApprovalCard(bot, chatID, approval, false, false) + sent++ + } + + if sent == 0 { + sendText(bot, chatID, "📭 Заявок по выбранным фильтрам не найдено.") + } +} + +// ─── inline-клавиатуры ─────────────────────────────────────────────────────── + +func buildApproverApprovalsTopicFilter( + categories []*typescore.ApprovalTopicCategory, +) tgbotapi.InlineKeyboardMarkup { + var rows [][]tgbotapi.InlineKeyboardButton + + rows = append(rows, tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData("📋 Все темы", "appr_appr_topic:all"), + )) + + for _, c := range categories { + if c.ID == nil || c.Name == nil || c.Code == nil { + continue + } + rows = append(rows, tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData( + *c.Name, + fmt.Sprintf("appr_appr_topic:%s", *c.Code), + ), + )) + } + + return tgbotapi.NewInlineKeyboardMarkup(rows...) +} + +func buildApproverApprovalsStatusFilter(topicFilter string) tgbotapi.InlineKeyboardMarkup { + cb := func(status string) string { + return fmt.Sprintf("appr_appr_status:%s:%s", status, topicFilter) + } + return tgbotapi.NewInlineKeyboardMarkup( + tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData("Все", cb("all")), + ), + tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData("✅ Согласованные", cb("approved")), + tgbotapi.NewInlineKeyboardButtonData("❌ Отклонённые", cb("rejected")), + ), + tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData("⏳ Ожидают", cb("pending")), + ), + tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData("← Назад", "appr_appr_back"), + ), + ) +} diff --git a/service/telegram_service/handlers/approval/handle_attachment.go b/service/telegram_service/handlers/approval/handle_attachment.go new file mode 100644 index 0000000..0b731a0 --- /dev/null +++ b/service/telegram_service/handlers/approval/handle_attachment.go @@ -0,0 +1,4 @@ +// telegram_service/handlers/approval/attachment.go - ЗАМЕНИТЬ полностью + +package approval + diff --git a/service/telegram_service/handlers/approval/handle_files.go b/service/telegram_service/handlers/approval/handle_files.go index 6a7622f..900b678 100644 --- a/service/telegram_service/handlers/approval/handle_files.go +++ b/service/telegram_service/handlers/approval/handle_files.go @@ -5,161 +5,380 @@ import ( "bitrix_balancer_api/telegram_service/keyboard" "bitrix_balancer_api/telegram_service/state" "context" - "encoding/base64" "fmt" tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" "github.com/sirupsen/logrus" - "io" - "net/http" + "sync" "time" ) -// HandleAttachFileInput обрабатывает файл, который согласующий/исполнитель прикрепляет к заявке +const maxAttachFiles = 10 + +var ( + albumDebounce = make(map[int64]*time.Timer) + albumDebounceMu sync.Mutex +) + +var ( + fileInputMu = make(map[int64]*sync.Mutex) + fileInputMuMu sync.Mutex +) + +func getFileInputMutex(telegramID int64) *sync.Mutex { + fileInputMuMu.Lock() + defer fileInputMuMu.Unlock() + + if _, ok := fileInputMu[telegramID]; !ok { + fileInputMu[telegramID] = &sync.Mutex{} + } + return fileInputMu[telegramID] +} + +// HandleAttachFileStart — начало прикрепления файлов (согласующий/исполнитель) +func (h *Handler) HandleAttachFileStart(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64) { + ctx := context.Background() + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, cq.From.ID) + if err != nil || user == nil || user.ID == nil { + return + } + + approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID) + if err != nil || approval == nil { + sendText(bot, cq.Message.Chat.ID, "⚠️ Заявка не найдена.") + return + } + + canAttach, _ := h.canUserCommentApproval(ctx, *user.ID, approval) + if !canAttach { + sendText(bot, cq.Message.Chat.ID, "⚠️ Нет прав на прикрепление файлов.") + return + } + + session := &state.AttachmentSession{ + ApprovalID: approvalID, + Files: []state.FileAttachment{}, + Stage: "collecting", + } + h.States.SetAttachmentSession(ctx, cq.From.ID, session) //nolint:errcheck + + msg := tgbotapi.NewMessage(cq.Message.Chat.ID, + fmt.Sprintf( + "📎 Прикрепление файлов к заявке #%d\n\n"+ + "Отправляйте файлы по одному или альбомом.\n"+ + "Максимум %d файлов за раз.\n\n"+ + "Когда закончите — нажмите «Отправить».", + approvalID, maxAttachFiles, + ), + ) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildAttachSessionKeyboard(approvalID, 0) + bot.Send(msg) //nolint:errcheck +} + +// HandleAttachFileInput — пользователь отправил файл в режиме прикрепления func (h *Handler) HandleAttachFileInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) bool { ctx := context.Background() telegramID := msg.From.ID chatID := msg.Chat.ID - // Проверяем режим прикрепления - key := fmt.Sprintf("appr_attach_file:%d", telegramID) - val, err := h.ipc.RedisClient.Get(ctx, key) - if err != nil || val == "" { - return false // не в режиме прикрепления + mu := getFileInputMutex(telegramID) + mu.Lock() + defer mu.Unlock() + + session, err := h.States.GetAttachmentSession(ctx, telegramID) + if err != nil || session == nil || session.Stage != "collecting" { + return false } - var approvalID uint64 - fmt.Sscanf(val, "%d", &approvalID) + if len(session.Files) >= maxAttachFiles { + sendText(bot, chatID, fmt.Sprintf("⚠️ Максимум %d файлов. Сначала отправьте текущие.", maxAttachFiles)) + return true + } var fileID, fileName string switch { - case msg.Photo != nil && len(msg.Photo) > 0: - best := msg.Photo[len(msg.Photo)-1] - fileID = best.FileID - fileName = fmt.Sprintf("photo_%s.jpg", time.Now().Format("20060102_150405")) - case msg.Document != nil: fileID = msg.Document.FileID fileName = msg.Document.FileName - + if fileName == "" { + fileName = fmt.Sprintf("document_%s", time.Now().Format("20060102_150405")) + } + case msg.Photo != nil && len(msg.Photo) > 0: + fileID = msg.Photo[len(msg.Photo)-1].FileID + fileName = fmt.Sprintf("photo_%s.jpg", time.Now().Format("20060102_150405.000")) default: - bot.Send(tgbotapi.NewMessage(chatID, "⚠️ Пожалуйста, отправьте фото или документ.")) //nolint:errcheck + sendText(bot, chatID, "⚠️ Отправьте фото или документ.") return true } fileURL, err := bot.GetFileDirectURL(fileID) if err != nil { logrus.Errorf("HandleAttachFileInput: GetFileDirectURL err=%v", err) - bot.Send(tgbotapi.NewMessage(chatID, "Ошибка при получении файла.")) //nolint:errcheck + sendText(bot, chatID, "Ошибка при получении файла.") return true } - base64Data, err := fetchFileAsBase64(fileURL) + base64Data, err := fetchFileAsBase64(fileURL, h.ipc.Config.Telegram) if err != nil { logrus.Errorf("HandleAttachFileInput: fetchFileAsBase64 err=%v", err) - bot.Send(tgbotapi.NewMessage(chatID, "Ошибка при обработке файла.")) //nolint:errcheck + sendText(bot, chatID, "Ошибка при обработке файла.") return true } - // Получаем пользователя - user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) - if err != nil || user == nil || user.ID == nil { - logrus.Errorf("HandleAttachFileInput: GetUserByTelegramIDDB err=%v", err) - return true + session.Files = append(session.Files, state.FileAttachment{ + Base64: base64Data, + FileName: fileName, + }) + h.States.SetAttachmentSession(ctx, telegramID, session) //nolint:errcheck + + if msg.MediaGroupID != "" { + albumDebounceMu.Lock() + if t, ok := albumDebounce[telegramID]; ok { + t.Stop() + } + albumDebounce[telegramID] = time.AfterFunc(500*time.Millisecond, func() { + albumDebounceMu.Lock() + delete(albumDebounce, telegramID) + albumDebounceMu.Unlock() + + mu := getFileInputMutex(telegramID) + mu.Lock() + defer mu.Unlock() + + fresh, err := h.States.GetAttachmentSession(ctx, telegramID) + if err != nil || fresh == nil { + return + } + h.sendAttachStatusMessage(bot, chatID, fresh) + }) + albumDebounceMu.Unlock() + } else { + h.sendAttachStatusMessage(bot, chatID, session) } - // Сохраняем файл в БД - file := &typescore.ApprovalFile{ - ApprovalID: &approvalID, - FileBase64: &base64Data, - FileName: &fileName, - AttachedByID: user.ID, - } - - if _, _, err := h.ipc.Database.ApprovalFile.CreateApprovalFileDB(ctx, nil, file); err != nil { - logrus.Errorf("HandleAttachFileInput: CreateApprovalFileDB err=%v", err) - bot.Send(tgbotapi.NewMessage(chatID, "Ошибка при сохранении файла.")) //nolint:errcheck - return true - } - - // Очищаем режим прикрепления - h.ipc.RedisClient.Del(ctx, key) //nolint:errcheck - - bot.Send(tgbotapi.NewMessage(chatID, "✅ Файл прикреплён к заявке")) //nolint:errcheck - - // Уведомляем наблюдателей - h.notifyObserversAboutNewFile(bot, approvalID, user, fileName, base64Data) - return true } +func (h *Handler) sendAttachStatusMessage(bot *tgbotapi.BotAPI, chatID int64, session *state.AttachmentSession) { + fileListText := fmt.Sprintf( + "📎 Прикрепление файлов к заявке #%d\n\n"+ + "✅ Добавлено файлов: %d/%d\n\n", + session.ApprovalID, len(session.Files), maxAttachFiles, + ) + for i, f := range session.Files { + fileListText += fmt.Sprintf("%d. %s\n", i+1, f.FileName) + } + fileListText += "\nОтправьте ещё или нажмите «Отправить»." + + statusMsg := tgbotapi.NewMessage(chatID, fileListText) + statusMsg.ParseMode = "HTML" + statusMsg.ReplyMarkup = keyboard.BuildAttachSessionKeyboard(session.ApprovalID, len(session.Files)) + bot.Send(statusMsg) //nolint:errcheck +} + +// HandleAttachSubmit — пользователь нажал "Отправить файлы" +func (h *Handler) HandleAttachSubmit(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID 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 + + session, err := h.States.GetAttachmentSession(ctx, telegramID) + if err != nil || session == nil { + sendText(bot, chatID, "⚠️ Сессия истекла. Начните заново.") + return + } + + if len(session.Files) == 0 { + sendText(bot, chatID, "⚠️ Нет файлов для отправки.") + return + } + + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || user == nil || user.ID == nil { + return + } + + // 🚀 Если это прикрепление к задаче — получаем taskID из сессии + var taskIDPtr *uint64 + if session.TaskID > 0 { + taskIDPtr = &session.TaskID + } + + // Сохраняем все файлы пакетом + savedCount := 0 + for _, f := range session.Files { + fileCopy := f + file := &typescore.ApprovalFile{ + ApprovalID: &approvalID, + FileBase64: &fileCopy.Base64, + FileName: &fileCopy.FileName, + AttachedByID: user.ID, + TaskID: taskIDPtr, // 🚀 НОВОЕ: связываем с задачей + } + if _, _, err := h.ipc.Database.ApprovalFile.CreateApprovalFileDB(ctx, nil, file); err != nil { + logrus.Errorf("HandleAttachSubmit: CreateApprovalFileDB file=%s err=%v", f.FileName, err) + continue + } + savedCount++ + } + + h.States.ClearAttachmentSession(ctx, telegramID) //nolint:errcheck + + sendText(bot, chatID, fmt.Sprintf( + "✅ Файлы прикреплены к заявке #%d\n\n📎 Сохранено файлов: %d", + approvalID, savedCount, + )) + + // Если это было прикрепление к задаче — показываем карточку задачи + if session.TaskID > 0 { + task, _ := h.ipc.Database.ApprovalTasks.GetApprovalTaskByIDDB(ctx, session.TaskID) + if task != nil { + approval, _ := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID) + if approval != nil { + h.sendTaskCard(bot, chatID, approval, task) + } + } + } + + // Уведомляем всех участников с отправкой самих файлов медиагруппами + fileDesc := fmt.Sprintf("%d файл(ов)", savedCount) + h.notifyAllParticipantsAboutFile(bot, approvalID, user, fileDesc) +} + +// HandleAttachClear — очистить список файлов +func (h *Handler) HandleAttachClear(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64) { + ctx := context.Background() + telegramID := cq.From.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + + session, _ := h.States.GetAttachmentSession(ctx, telegramID) + if session != nil { + session.Files = []state.FileAttachment{} + h.States.SetAttachmentSession(ctx, telegramID, session) //nolint:errcheck + } + + editMsg := tgbotapi.NewEditMessageReplyMarkup( + cq.Message.Chat.ID, + cq.Message.MessageID, + keyboard.BuildAttachSessionKeyboard(approvalID, 0), + ) + bot.Request(editMsg) //nolint:errcheck + + sendText(bot, cq.Message.Chat.ID, "🗑 Список файлов очищен. Отправьте новые файлы.") +} + +// HandleAttachCancel — отмена прикрепления +func (h *Handler) HandleAttachCancel(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery) { + ctx := context.Background() + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck + + h.States.ClearAttachmentSession(ctx, cq.From.ID) //nolint:errcheck + sendText(bot, cq.Message.Chat.ID, "❌ Прикрепление файлов отменено.") +} + // HandleFileInput обрабатывает прикреплённый файл (фото или документ) во время флоу. func (h *Handler) HandleFileInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) bool { ctx := context.Background() telegramID := msg.From.ID chatID := msg.Chat.ID + mu := getFileInputMutex(telegramID) + mu.Lock() + defer mu.Unlock() + flowState, err := h.States.Get(ctx, telegramID) if err != nil || flowState == nil || !flowState.AwaitFileInput { return false } var fileID, fileName string - switch { - case msg.Photo != nil && len(msg.Photo) > 0: - best := msg.Photo[len(msg.Photo)-1] - fileID = best.FileID + switch { case msg.Document != nil: fileID = msg.Document.FileID - fileName = msg.Document.FileName // оригинальное имя - + fileName = msg.Document.FileName + if fileName == "" { + fileName = fmt.Sprintf("document_%s", time.Now().Format("20060102_150405")) + } + case msg.Photo != nil && len(msg.Photo) > 0: + fileID = msg.Photo[len(msg.Photo)-1].FileID + fileName = fmt.Sprintf("photo_%s.jpg", time.Now().Format("20060102_150405.000")) default: - bot.Send(tgbotapi.NewMessage(chatID, "⚠️ Пожалуйста, отправьте фото или PDF-документ.")) //nolint:errcheck + sendText(bot, chatID, "⚠️ Пожалуйста, отправьте фото или документ.") return true } fileURL, err := bot.GetFileDirectURL(fileID) if err != nil { - logrus.Errorf("HandleFileInput: GetFileDirectURL err=%v", err) - bot.Send(tgbotapi.NewMessage(chatID, "Ошибка при получении файла. Попробуйте ещё раз.")) //nolint:errcheck + logrus.Errorf("HandleFileInput: GetFileDirectURL fileID=%s err=%v", fileID, err) + sendText(bot, chatID, "Ошибка при получении файла. Попробуйте ещё раз.") return true } - base64Data, err := fetchFileAsBase64(fileURL) + if fileURL == "" { + logrus.Errorf("HandleFileInput: empty fileURL for fileID=%s", fileID) + sendText(bot, chatID, "Ошибка: не удалось получить ссылку на файл.") + return true + } + + base64Data, err := fetchFileAsBase64(fileURL, h.ipc.Config.Telegram) if err != nil { - logrus.Errorf("HandleFileInput: fetchFileAsBase64 err=%v", err) - bot.Send(tgbotapi.NewMessage(chatID, "Ошибка при обработке файла. Попробуйте ещё раз.")) //nolint:errcheck + logrus.Errorf("HandleFileInput: fetchFileAsBase64 url=%s err=%v", fileURL, err) + sendText(bot, chatID, "Ошибка при обработке файла. Попробуйте ещё раз.") + return true + } + + if base64Data == "" { + logrus.Errorf("HandleFileInput: empty base64 for fileID=%s", fileID) + sendText(bot, chatID, "Ошибка: файл пустой. Попробуйте ещё раз.") return true } flowState.Files = append(flowState.Files, state.FileAttachment{ - Base64: base64Data, - FileName: fileName, + Base64: base64Data, + FileName: fileName, + MessageID: msg.MessageID, }) + h.States.Set(ctx, telegramID, flowState) //nolint:errcheck - h.showFileStatus(bot, chatID, int64(telegramID), flowState) - return true -} + logrus.Infof("HandleFileInput: attached file=%s size=%d telegramID=%d total=%d", + fileName, len(base64Data), telegramID, len(flowState.Files)) -func (h *Handler) HandleAttachFileStart(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64) { - ctx := context.Background() + // Дебаунс для альбомов + if msg.MediaGroupID != "" { + albumDebounceMu.Lock() + if t, ok := albumDebounce[telegramID]; ok { + t.Stop() + } + albumDebounce[telegramID] = time.AfterFunc(500*time.Millisecond, func() { + albumDebounceMu.Lock() + delete(albumDebounce, telegramID) + albumDebounceMu.Unlock() - bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + mu := getFileInputMutex(telegramID) + mu.Lock() + defer mu.Unlock() - // Сохраняем в Redis режим прикрепления - key := fmt.Sprintf("appr_attach_file:%d", cq.From.ID) - if err := h.ipc.RedisClient.Set(ctx, key, fmt.Sprintf("%d", approvalID), 10*time.Minute); err != nil { - logrus.Errorf("HandleAttachFileStart: Redis.Set err=%v", err) - return + fresh, err := h.States.Get(ctx, telegramID) + if err != nil || fresh == nil { + return + } + h.showFileStatus(bot, chatID, telegramID, fresh, false) + }) + albumDebounceMu.Unlock() + } else { + h.showFileStatus(bot, chatID, telegramID, flowState, false) } - msg := tgbotapi.NewMessage(cq.Message.Chat.ID, - "📎 Прикрепление файла к заявке\n\n"+ - "Отправьте фото или документ, который нужно добавить к согласованию.") - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildAttachFileCancel(approvalID) - - bot.Send(msg) //nolint:errcheck + return true } // HandleDetachFile удаляет файл из списка по индексу и обновляет статусное сообщение. @@ -176,11 +395,27 @@ func (h *Handler) HandleDetachFile(bot *tgbotapi.BotAPI, chatID int64, telegramI return } - removed := flowState.Files[index].FileName - flowState.Files = append(flowState.Files[:index], flowState.Files[index+1:]...) - logrus.Infof("HandleDetachFile: removed file %q, remaining=%d", removed, len(flowState.Files)) + removed := flowState.Files[index] - h.showFileStatus(bot, chatID, telegramID, flowState) + // Удаляем сообщение с файлом из чата + if removed.MessageID != 0 { + bot.Request(tgbotapi.NewDeleteMessage(chatID, removed.MessageID)) //nolint:errcheck + } + + flowState.Files = append(flowState.Files[:index], flowState.Files[index+1:]...) + logrus.Infof("HandleDetachFile: removed file %q, remaining=%d", removed.FileName, len(flowState.Files)) + + h.States.Set(ctx, telegramID, flowState) //nolint:errcheck + isRequired := false + if topic, err := h.Registry.Get(flowState.TopicCode); err == nil { + if code, err := topic.TopicCodeFromCollected(flowState.Collected); err == nil { + if at, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByCodeDB(ctx, code); at != nil { + isRequired = (at.RequiresFile != nil && *at.RequiresFile) || + flowState.Collected["payment_type"] == "official" + } + } + } + h.showFileStatus(bot, chatID, telegramID, flowState, isRequired) } // HandleSubmitFiles финализирует заявку. withFiles=false очищает список файлов перед отправкой. @@ -192,6 +427,28 @@ func (h *Handler) HandleSubmitFiles(bot *tgbotapi.BotAPI, chatID int64, telegram return } + // Проверяем обязательность файла + if withFiles == false { + topic, _ := h.Registry.Get(flowState.TopicCode) + if topic != nil { + topicCode, _ := topic.TopicCodeFromCollected(flowState.Collected) + approvalTopic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByCodeDB(ctx, topicCode) + + isRequired := (approvalTopic != nil && approvalTopic.RequiresFile != nil && *approvalTopic.RequiresFile) || + flowState.Collected["payment_type"] == "official" + + if isRequired { + // Нельзя отправить без файла — показываем предупреждение + sendText(bot, chatID, + "⚠️ Файл обязателен для этой темы.\n\n"+ + "Прикрепите файл чтобы продолжить.") + // Перерисовываем экран файлов + h.showFileStatus(bot, chatID, telegramID, flowState, true) + return + } + } + } + if !withFiles { flowState.Files = nil } @@ -201,21 +458,9 @@ func (h *Handler) HandleSubmitFiles(bot *tgbotapi.BotAPI, chatID int64, telegram flowState.FileStatusMsgID = 0 } + flowState.AwaitFileInput = false + flowState.FilesStepCompleted = true + h.States.Set(ctx, telegramID, flowState) //nolint:errcheck h.continueFlowAfterInput(bot, ctx, chatID, telegramID, flowState) } - -// fetchFileAsBase64 скачивает файл по URL и возвращает base64-строку. -func fetchFileAsBase64(url string) (string, error) { - resp, err := http.Get(url) //nolint:gosec - if err != nil { - return "", err - } - defer resp.Body.Close() - - data, err := io.ReadAll(resp.Body) - if err != nil { - return "", err - } - return base64.StdEncoding.EncodeToString(data), nil -} diff --git a/service/telegram_service/handlers/approval/handle_multiselect.go b/service/telegram_service/handlers/approval/handle_multiselect.go index 0086847..fb0908e 100644 --- a/service/telegram_service/handlers/approval/handle_multiselect.go +++ b/service/telegram_service/handlers/approval/handle_multiselect.go @@ -45,7 +45,7 @@ func (h *Handler) HandleMultiSelectToggle(bot *tgbotapi.BotAPI, cq *tgbotapi.Cal h.States.Set(ctx, telegramID, flowState) //nolint:errcheck // Перестраиваем клавиатуру - topic, _ := h.registry.Get(topicCode) + topic, _ := h.Registry.Get(topicCode) if topic == nil { return } @@ -93,7 +93,7 @@ func (h *Handler) HandleMultiSelectConfirm(bot *tgbotapi.BotAPI, cq *tgbotapi.Ca } // Сохраняем выбранные значения как строку через запятую в Collected - topic, _ := h.registry.Get(topicCode) + topic, _ := h.Registry.Get(topicCode) if topic == nil { return } diff --git a/service/telegram_service/handlers/approval/handler.go b/service/telegram_service/handlers/approval/handler.go index 2ae3ba7..3d298c1 100644 --- a/service/telegram_service/handlers/approval/handler.go +++ b/service/telegram_service/handlers/approval/handler.go @@ -1,11 +1,13 @@ package approval import ( + "bitrix_balancer_api/core/typescore" "bitrix_balancer_api/telegram_service/approvalflow" "bitrix_balancer_api/telegram_service/keyboard" "bitrix_balancer_api/telegram_service/state" "bitrix_balancer_api/telegram_service/types" "context" + "encoding/base64" "fmt" "time" @@ -15,14 +17,14 @@ import ( type Handler struct { ipc *types.InternalProviderControl - registry *Registry + Registry *Registry States *state.StateManager } func NewHandler(ipc *types.InternalProviderControl) *Handler { return &Handler{ ipc: ipc, - registry: NewRegistry(), + Registry: NewRegistry(), States: state.NewStateManager(ipc.RedisClient), } } @@ -72,7 +74,7 @@ func (h *Handler) HandleMenuPage(bot *tgbotapi.BotAPI, chatID int64, telegramID } var visibleTopics []approvalflow.Topic - for _, t := range h.registry.All() { + for _, t := range h.Registry.All() { if allowed[t.Code()] { visibleTopics = append(visibleTopics, t) } @@ -106,7 +108,7 @@ func (h *Handler) HandleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuer bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck - topic, err := h.registry.Get(topicCode) + topic, err := h.Registry.Get(topicCode) if err != nil { logrus.Warnf("HandleCallback: unknown topic %s", topicCode) return @@ -205,6 +207,29 @@ func (h *Handler) HandleTextInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) b telegramID := msg.From.ID chatID := msg.Chat.ID + commentKey := fmt.Sprintf("appr_approve_comment_pending:%d", telegramID) + commentApprovalIDStr, err := h.ipc.RedisClient.Get(ctx, commentKey) + if err == nil && commentApprovalIDStr != "" { + var approvalID uint64 + if _, scanErr := fmt.Sscanf(commentApprovalIDStr, "%d", &approvalID); scanErr == nil { + h.ipc.RedisClient.Del(ctx, commentKey) //nolint:errcheck + + h.HandleDecisionWithChat(bot, chatID, telegramID, approvalID, true, msg.Text) + return true + } + } + + commentState, _ := h.States.GetCommentFlow(ctx, telegramID) + if commentState != nil && commentState.Stage == "await_text" { + // Делегируем в HandleCommentTextInput + return h.HandleCommentTextInput(bot, msg) + } + + replyState, _ := h.States.GetCommentReply(ctx, telegramID) + if replyState != nil && replyState.Stage == "await_text" { + return h.HandleCommentReplyInput(bot, msg) + } + flowState, err := h.States.Get(ctx, telegramID) if err != nil || flowState == nil || !flowState.AwaitInput { return false @@ -213,12 +238,30 @@ 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 { + tree := topic.BuildTree() + parentNode := approvalflow.FindNode(tree, flowState.NodeKey) + 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) + if len(visibleChildren) == 0 { + sendText(bot, chatID, "⚠️ У вас нет доступа к подкатегориям этого раздела.") + h.States.Clear(ctx, telegramID) //nolint:errcheck + return true + } + + flowState.NodeKey = inputNode.Key + h.States.Set(ctx, telegramID, flowState) //nolint:errcheck + + msg := tgbotapi.NewMessage(chatID, "Выберите:") + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildApprovalStep(flowState.TopicCode, visibleChildren) + bot.Send(msg) //nolint:errcheck + return true + } + } } h.States.Set(ctx, telegramID, flowState) //nolint:errcheck @@ -241,18 +284,28 @@ func (h *Handler) HandleRevokeWithComment(bot *tgbotapi.BotAPI, chatID int64, te return } - isInitiator := approval.InitiatorID != nil && *approval.InitiatorID == *revoker.ID - isDirector, _ := h.ipc.Database.User.IsDirectorDB(ctx, *revoker.ID) - - if !isInitiator && !isDirector { - sendText(bot, chatID, "У вас нет прав для отзыва этой заявки.") - return - } - if approval.Status == nil { sendText(bot, chatID, "⚠️ Статус заявки не определён.") return } + + // Определяем роли пользователя + isInitiator := approval.InitiatorID != nil && *approval.InitiatorID == *revoker.ID + isDirector, _ := h.ipc.Database.User.IsDirectorDB(ctx, *revoker.ID) + + // 🚀 НОВОЕ: Проверяем, является ли пользователь согласующим по этой заявке + isApprover := false + steps, _, _ := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalStep{ApprovalID: &approvalID}, + }) + for _, step := range steps { + if step.ApproverID != nil && *step.ApproverID == *revoker.ID { + isApprover = true + break + } + } + + // Проверка прав в зависимости от статуса switch *approval.Status { case "revoked": sendText(bot, chatID, "Заявка уже отозвана.") @@ -260,6 +313,21 @@ func (h *Handler) HandleRevokeWithComment(bot *tgbotapi.BotAPI, chatID int64, te case "rejected": sendText(bot, chatID, "Нельзя отозвать отклонённую заявку.") return + case "pending", "revision": + if !isInitiator && !isDirector { + sendText(bot, chatID, "⚠️ В процессе согласования заявку может отозвать только инициатор или директор.") + return + } + case "approved": + if !isInitiator && !isDirector && !isApprover { + sendText(bot, chatID, "⚠️ У вас нет прав для отзыва этой заявки.") + return + } + default: + if !isInitiator && !isDirector { + sendText(bot, chatID, "⚠️ У вас нет прав для отзыва этой заявки.") + return + } } now := time.Now() @@ -274,6 +342,8 @@ func (h *Handler) HandleRevokeWithComment(bot *tgbotapi.BotAPI, chatID int64, te return } + h.handleRevokeCancellationTask(bot, ctx, approval, revoker, comment) + revokerName := "—" if revoker.FullName != nil { revokerName = *revoker.FullName @@ -286,6 +356,16 @@ func (h *Handler) HandleRevokeWithComment(bot *tgbotapi.BotAPI, chatID int64, te content = *approval.Content } + revokerRole := "" + switch { + case isInitiator: + revokerRole = "инициатором" + case isDirector: + revokerRole = "директором" + case isApprover: + revokerRole = "согласующим" + } + approvalCard := fmt.Sprintf( "📋 Тема: %s\n"+ "📝 Текст: %s\n"+ @@ -293,34 +373,69 @@ func (h *Handler) HandleRevokeWithComment(bot *tgbotapi.BotAPI, chatID int64, te topicFullName, content, comment, ) + // Уведомление тому, кто отзывает sendText(bot, chatID, fmt.Sprintf( "↩️ Заявка #%d отозвана\n\n%s", approvalID, approvalCard, )) - if isDirector && !isInitiator && approval.InitiatorID != nil { + if !isInitiator && approval.InitiatorID != nil { initiator, err := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID) if err == nil && initiator != nil && initiator.TelegramID != nil { sendText(bot, *initiator.TelegramID, fmt.Sprintf( - "↩️ Ваша заявка #%d отозвана директором %s\n\n%s", - approvalID, revokerName, approvalCard, + "↩️ Ваша заявка #%d отозвана %s %s\n\n%s", + approvalID, revokerRole, revokerName, approvalCard, )) } } - if isInitiator { - if activeStep, _ := h.ipc.Database.ApprovalStep.GetActiveStepDB(ctx, approvalID); activeStep != nil && activeStep.ApproverID != nil { - approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *activeStep.ApproverID) - if approver != nil && approver.TelegramID != nil { - initiatorName := "—" - if revoker.FullName != nil { - initiatorName = *revoker.FullName - } - sendText(bot, *approver.TelegramID, fmt.Sprintf( - "↩️ Заявка #%d отозвана инициатором %s\n\n%s", - approvalID, initiatorName, approvalCard, - )) + if !isDirector { + directors, _ := h.ipc.Database.User.GetDirectorsDB(ctx) + for _, director := range directors { + if director.TelegramID == nil { + continue } + if revoker.ID != nil && director.ID != nil && *director.ID == *revoker.ID { + continue + } + sendText(bot, *director.TelegramID, fmt.Sprintf( + "↩️ Заявка #%d отозвана %s %s\n\n%s", + approvalID, revokerRole, revokerName, approvalCard, + )) + } + } + + for _, step := range steps { + if step.ApproverID == nil { + continue + } + if revoker.ID != nil && *step.ApproverID == *revoker.ID { + continue + } + approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *step.ApproverID) + if approver == nil || approver.TelegramID == nil { + continue + } + sendText(bot, *approver.TelegramID, fmt.Sprintf( + "↩️ Заявка #%d отозвана %s %s\n\n%s", + approvalID, revokerRole, revokerName, approvalCard, + )) + } + + if *approval.Status == "revoked" { + categoryCode := h.getTopicCodeByApproval(ctx, approval) + observers, _ := h.ipc.Database.User.GetObserversForCategoryDB(ctx, categoryCode) + for _, obs := range observers { + if obs.TelegramID == nil { + continue + } + if revoker.ID != nil && obs.ID != nil && *obs.ID == *revoker.ID { + continue + } + sendText(bot, *obs.TelegramID, fmt.Sprintf( + "↩️ Заявка #%d отозвана %s %s\n\n%s", + approvalID, revokerRole, revokerName, approvalCard, + )) } } } @@ -374,7 +489,7 @@ func (h *Handler) HandleBackCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.Callback flowState.History = flowState.History[:len(flowState.History)-1] flowState.NodeKey = prevNodeKey - topic, err := h.registry.Get(topicCode) + topic, err := h.Registry.Get(topicCode) if err != nil { logrus.Errorf("HandleBackCallback: unknown topic %s", topicCode) return @@ -405,8 +520,7 @@ func (h *Handler) continueFlowAfterInput( telegramID int64, flowState *state.ApprovalFlowState, ) { - println("continueFlowAfterInput") - topic, _ := h.registry.Get(flowState.TopicCode) + topic, _ := h.Registry.Get(flowState.TopicCode) if topic == nil { h.States.Clear(ctx, telegramID) //nolint:errcheck return @@ -424,6 +538,22 @@ func (h *Handler) continueFlowAfterInput( logrus.Errorf("continueFlowAfterInput: GetApprovalTopicByCodeDB topicCode=%s err=%v", topicCode, err) } + if approvalTopic != nil && !flowState.FilesStepCompleted { + requiresFile := approvalTopic.RequiresFile != nil && *approvalTopic.RequiresFile + allowsFile := approvalTopic.AllowsFile != nil && *approvalTopic.AllowsFile + isOfficial := flowState.Collected["payment_type"] == "official" + + needFileStep := requiresFile || allowsFile || isOfficial + + if needFileStep && !flowState.AwaitFileInput { + flowState.AwaitFileInput = true + flowState.FilesStepCompleted = false + h.States.Set(ctx, telegramID, flowState) //nolint:errcheck + h.showFileStatus(bot, chatID, telegramID, flowState, requiresFile || isOfficial) + return + } + } + if approvalTopic != nil && approvalTopic.FirstApproverRoleCode != nil && *approvalTopic.FirstApproverRoleCode != "" && @@ -463,10 +593,41 @@ func (h *Handler) continueFlowAfterInput( flowState.ObserverSelectionDone = true flowState.AwaitObserverSelection = true h.States.Set(ctx, telegramID, flowState) - h.showObserverSelection(bot, ctx, chatID, telegramID, flowState) + h.showObserverSelection(bot, ctx, chatID, telegramID, flowState, approvalTopic) return } h.States.Clear(ctx, telegramID) //nolint:errcheck h.finalizeAndSubmit(bot, ctx, chatID, telegramID, flowState) } + +func (h *Handler) HandleViewFilesCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64) { + ctx := context.Background() + chatID := cq.Message.Chat.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + + files, err := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, approvalID) + if err != nil || len(files) == 0 { + sendText(bot, chatID, "📭 Файлы не найдены.") + return + } + + sendText(bot, chatID, fmt.Sprintf("📎 Файлы к заявке #%d (%d шт.):", approvalID, len(files))) + + for _, f := range files { + if f.FileBase64 == nil || f.FileName == nil { + continue + } + data, err := base64.StdEncoding.DecodeString(*f.FileBase64) + if err != nil { + logrus.Errorf("HandleViewFilesCallback: decode err=%v", err) + continue + } + doc := tgbotapi.NewDocument(chatID, tgbotapi.FileBytes{ + Name: *f.FileName, + Bytes: data, + }) + bot.Send(doc) //nolint:errcheck + } +} diff --git a/service/telegram_service/handlers/approval/handler_add_approver.go b/service/telegram_service/handlers/approval/handler_add_approver.go index c3dba91..4800c9b 100644 --- a/service/telegram_service/handlers/approval/handler_add_approver.go +++ b/service/telegram_service/handlers/approval/handler_add_approver.go @@ -341,6 +341,12 @@ func (h *Handler) HandleAddApproverUserCallback(bot *tgbotapi.BotAPI, cq *tgbota content = *approval.Content } + status := "" + if approval.Status != nil { + status = *approval.Status + } + + files, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID) notifyMsg := tgbotapi.NewMessage(*addedApprover.TelegramID, fmt.Sprintf( "➕ Вас добавили к согласованию заявки #%d\n\n"+ "👤 Инициатор: %s\n"+ @@ -349,7 +355,7 @@ func (h *Handler) HandleAddApproverUserCallback(bot *tgbotapi.BotAPI, cq *tgbota addApproverState.ApprovalID, initiatorName, topicFullName, content, )) notifyMsg.ParseMode = "HTML" - notifyMsg.ReplyMarkup = keyboard.BuildApproverDecision(addApproverState.ApprovalID) + notifyMsg.ReplyMarkup = keyboard.BuildApproverDecision(addApproverState.ApprovalID, status, len(files) > 0, len(files)) bot.Send(notifyMsg) //nolint:errcheck } } diff --git a/service/telegram_service/handlers/approval/handler_comment.go b/service/telegram_service/handlers/approval/handler_comment.go index 057f603..b6d3dc6 100644 --- a/service/telegram_service/handlers/approval/handler_comment.go +++ b/service/telegram_service/handlers/approval/handler_comment.go @@ -2,6 +2,7 @@ package approval import ( "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/telegram_service/keyboard" "bitrix_balancer_api/telegram_service/state" "context" "fmt" @@ -70,71 +71,6 @@ func (h *Handler) HandleAddCommentCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.Ca sendText(bot, chatID, "💬 Введите текст комментария:") } -func (h *Handler) HandleCommentTextInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) bool { - ctx := context.Background() - telegramID := msg.From.ID - chatID := msg.Chat.ID - - commentState, err := h.States.GetCommentFlow(ctx, telegramID) - if err != nil || commentState == nil || commentState.Stage != "await_text" { - return false - } - - user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) - if err != nil || user == nil || user.ID == nil { - return false - } - - approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, commentState.ApprovalID) - if err != nil || approval == nil { - sendText(bot, chatID, "⚠️ Заявка не найдена.") - h.States.ClearCommentFlow(ctx, telegramID) //nolint:errcheck - return true - } - - comment := &typescore.ApprovalComment{ - ApprovalID: &commentState.ApprovalID, - UserID: user.ID, - Comment: &msg.Text, - } - - // Вызываем БЕЗ returnObj=true, чтобы не делать повторный SELECT - _, _, err = h.ipc.Database.ApprovalComment.CreateApprovalCommentDB(ctx, nil, comment) - if err != nil { - logrus.Errorf("HandleCommentTextInput: CreateApprovalCommentDB err=%v", err) - sendText(bot, chatID, "Ошибка при сохранении комментария.") - h.States.ClearCommentFlow(ctx, telegramID) //nolint:errcheck - return true - } - - h.States.ClearCommentFlow(ctx, telegramID) //nolint:errcheck - - userName := "—" - if user.FullName != nil { - userName = *user.FullName - } - - sendText(bot, chatID, fmt.Sprintf( - "✅ Комментарий добавлен\n\n"+ - "📋 Заявка: #%d\n"+ - "👤 Автор: %s\n"+ - "💬 Текст: %s", - commentState.ApprovalID, userName, msg.Text, - )) - - // Уведомляем инициатора - передаём comment напрямую без повторного запроса - if approval.InitiatorID != nil { - initiator, err := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID) - if err != nil { - logrus.Errorf("HandleCommentTextInput: GetUserByIDDB initiator err=%v", err) - } else if initiator != nil && initiator.TelegramID != nil { - h.notifyInitiatorAboutComment(bot, ctx, initiator, approval, user, comment) - } - } - - return true -} - func (h *Handler) canUserCommentApproval(ctx context.Context, userID uint64, approval *typescore.Approval) (bool, error) { if approval == nil || approval.ID == nil { return false, fmt.Errorf("approval or approval ID is nil") @@ -197,67 +133,6 @@ func (h *Handler) canUserCommentApproval(ctx context.Context, userID uint64, app return isDirector, nil } -func (h *Handler) notifyInitiatorAboutComment( - bot *tgbotapi.BotAPI, - ctx context.Context, - initiator *typescore.User, - approval *typescore.Approval, - commenter *typescore.User, - comment *typescore.ApprovalComment, -) { - if initiator == nil || initiator.TelegramID == nil { - logrus.Warn("notifyInitiatorAboutComment: initiator or TelegramID is nil") - return - } - - if approval == nil || approval.ID == nil { - logrus.Warn("notifyInitiatorAboutComment: approval or ID is nil") - return - } - - if commenter == nil { - logrus.Warn("notifyInitiatorAboutComment: commenter is nil") - return - } - - if comment == nil || comment.Comment == nil { - logrus.Warn("notifyInitiatorAboutComment: comment or Comment text is nil") - return - } - - commenterName := "—" - if commenter.FullName != nil { - commenterName = *commenter.FullName - } - - topicName := "—" - if approval.TopicID != nil { - topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID) - if topic != nil && topic.Name != nil { - topicName = *topic.Name - } - } - - content := "—" - if approval.Content != nil { - content = *approval.Content - } - - msg := tgbotapi.NewMessage(*initiator.TelegramID, fmt.Sprintf( - "💬 Новый комментарий к вашей заявке\n\n"+ - "📋 Заявка #%d — %s\n"+ - "📝 Текст заявки: %s\n\n"+ - "👤 Автор комментария: %s\n"+ - "💬 Комментарий:\n%s", - *approval.ID, topicName, content, commenterName, *comment.Comment, - )) - msg.ParseMode = "HTML" - - if _, err := bot.Send(msg); err != nil { - logrus.Errorf("notifyInitiatorAboutComment: Send err=%v", err) - } -} - func (h *Handler) formatCommentsSection(ctx context.Context, approvalID uint64) string { comments, err := h.ipc.Database.ApprovalComment.GetCommentsByApprovalIDDB(ctx, approvalID) if err != nil { @@ -307,3 +182,216 @@ func (h *Handler) formatCommentsSection(ctx context.Context, approvalID uint64) return result } + +func (h *Handler) HandleCommentReplyCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64) { + ctx := context.Background() + chatID := cq.Message.Chat.ID + telegramID := cq.From.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + + replyState := &state.CommentReplyState{ + ApprovalID: approvalID, + Stage: "await_text", + } + h.States.SetCommentReply(ctx, telegramID, replyState) //nolint:errcheck + + sendText(bot, chatID, "↩️ Введите текст ответа:") +} + +func (h *Handler) HandleCommentTextInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) bool { + ctx := context.Background() + telegramID := msg.From.ID + chatID := msg.Chat.ID + + commentState, err := h.States.GetCommentFlow(ctx, telegramID) + if err != nil || commentState == nil || commentState.Stage != "await_text" { + return false + } + + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || user == nil || user.ID == nil { + return false + } + + approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, commentState.ApprovalID) + if err != nil || approval == nil { + sendText(bot, chatID, "⚠️ Заявка не найдена.") + h.States.ClearCommentFlow(ctx, telegramID) //nolint:errcheck + return true + } + + comment := &typescore.ApprovalComment{ + ApprovalID: &commentState.ApprovalID, + UserID: user.ID, + Comment: &msg.Text, + } + + _, _, err = h.ipc.Database.ApprovalComment.CreateApprovalCommentDB(ctx, nil, comment) + if err != nil { + logrus.Errorf("HandleCommentTextInput: CreateApprovalCommentDB err=%v", err) + sendText(bot, chatID, "Ошибка при сохранении комментария.") + h.States.ClearCommentFlow(ctx, telegramID) //nolint:errcheck + return true + } + + h.States.ClearCommentFlow(ctx, telegramID) //nolint:errcheck + + userName := "—" + if user.FullName != nil { + userName = *user.FullName + } + + sendText(bot, chatID, fmt.Sprintf( + "✅ Комментарий добавлен\n\n"+ + "📋 Заявка: #%d\n"+ + "👤 Автор: %s\n"+ + "💬 Текст: %s", + commentState.ApprovalID, userName, msg.Text, + )) + + h.notifyAllParticipantsAboutComment(bot, ctx, approval, user, comment, telegramID) + + return true +} + +func (h *Handler) notifyAllParticipantsAboutComment( + bot *tgbotapi.BotAPI, + ctx context.Context, + approval *typescore.Approval, + commenter *typescore.User, + comment *typescore.ApprovalComment, + skipTelegramID int64, +) { + if approval == nil || approval.ID == nil { + return + } + + commenterName := "—" + if commenter != nil && commenter.FullName != nil { + commenterName = *commenter.FullName + } + + topicName := h.getTopicNameByApproval(ctx, approval) + content := "—" + if approval.Content != nil { + content = *approval.Content + } + + text := fmt.Sprintf( + "💬 Новый комментарий к заявке #%d\n\n"+ + "📋 Тема: %s\n"+ + "📝 Текст заявки: %s\n\n"+ + "👤 Автор комментария: %s\n"+ + "💬 Комментарий:\n%s", + *approval.ID, topicName, content, commenterName, *comment.Comment, + ) + + // 🚀 Определяем, является ли статус финальным + isFinalStatus := approval.Status != nil && + (*approval.Status == "approved" || *approval.Status == "rejected" || *approval.Status == "revoked") + + recipients := make(map[int64]bool) + + // Инициатор — всегда получает уведомления о комментариях + if approval.InitiatorID != nil { + initiator, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID) + if initiator != nil && initiator.TelegramID != nil && *initiator.TelegramID != skipTelegramID { + recipients[*initiator.TelegramID] = true + } + } + + // Текущий согласующий — всегда получает + activeStep, _ := h.ipc.Database.ApprovalStep.GetActiveStepDB(ctx, *approval.ID) + if activeStep != nil && activeStep.ApproverID != nil { + approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *activeStep.ApproverID) + if approver != nil && approver.TelegramID != nil && *approver.TelegramID != skipTelegramID { + recipients[*approver.TelegramID] = true + } + } + + // Дополнительные согласующие — всегда получают + additionalApprovers, _, _ := h.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalAdditionalApprover{ + ApprovalID: approval.ID, + }, + }) + for _, aa := range additionalApprovers { + if aa.ApproverID != nil { + addApprover, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *aa.ApproverID) + if addApprover != nil && addApprover.TelegramID != nil && *addApprover.TelegramID != skipTelegramID { + recipients[*addApprover.TelegramID] = true + } + } + } + + if isFinalStatus && approval.TopicID != nil { + categoryCode := h.getTopicCodeByApproval(ctx, approval) + if categoryCode != "" { + observers, _ := h.ipc.Database.User.GetObserversForCategoryDB(ctx, categoryCode) + for _, obs := range observers { + if obs.TelegramID != nil && *obs.TelegramID != skipTelegramID { + recipients[*obs.TelegramID] = true + } + } + } + } + + if isFinalStatus { + directors, _ := h.ipc.Database.User.GetDirectorsDB(ctx) + for _, dir := range directors { + if dir.TelegramID != nil && *dir.TelegramID != skipTelegramID { + recipients[*dir.TelegramID] = true + } + } + } + + for telegramID := range recipients { + msg := tgbotapi.NewMessage(telegramID, text) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildCommentReplyKeyboard(*approval.ID) + if _, err := bot.Send(msg); err != nil { + logrus.Errorf("notifyAllParticipantsAboutComment: Send to %d err=%v", telegramID, err) + } + } +} + +func (h *Handler) HandleCommentReplyInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) bool { + ctx := context.Background() + telegramID := msg.From.ID + chatID := msg.Chat.ID + + replyState, err := h.States.GetCommentReply(ctx, telegramID) + if err != nil || replyState == nil || replyState.Stage != "await_text" { + return false + } + + h.States.ClearCommentReply(ctx, telegramID) //nolint:errcheck + + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || user == nil || user.ID == nil { + return false + } + + approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, replyState.ApprovalID) + if err != nil || approval == nil { + sendText(bot, chatID, "⚠️ Заявка не найдена.") + return true + } + + comment := &typescore.ApprovalComment{ + ApprovalID: &replyState.ApprovalID, + UserID: user.ID, + Comment: &msg.Text, + } + created, _, err := h.ipc.Database.ApprovalComment.CreateApprovalCommentDB(ctx, nil, comment, true) //nolint:errcheck + if err != nil { + sendText(bot, chatID, "⚠️ Ошибка при создании комментария: "+err.Error()) + return false + } + sendText(bot, chatID, "✅ Ответ отправлен.") + + h.notifyAllParticipantsAboutComment(bot, ctx, approval, user, created, telegramID) + + return true +} diff --git a/service/telegram_service/handlers/approval/handler_decision.go b/service/telegram_service/handlers/approval/handler_decision.go index f183edb..b1606f0 100644 --- a/service/telegram_service/handlers/approval/handler_decision.go +++ b/service/telegram_service/handlers/approval/handler_decision.go @@ -12,6 +12,26 @@ import ( "time" ) +// HandleDecision — вызывается при нажатии inline-кнопки. +func (h *Handler) HandleDecision( + bot *tgbotapi.BotAPI, + cq *tgbotapi.CallbackQuery, + approvalID uint64, + approved bool, + comment string, +) { + var approverChatID int64 + if cq != nil { + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + approverChatID = cq.Message.Chat.ID + } + var telegramID int64 + if cq != nil { + telegramID = cq.From.ID + } + h.handleDecision(bot, cq, approverChatID, telegramID, approvalID, approved, comment) +} + func (h *Handler) processNextStepOrComplete(bot *tgbotapi.BotAPI, ctx context.Context, approval *typescore.Approval, currentStep *typescore.ApprovalStep, approvalCard string, categoryCode string, notifier *Notifier, initiator *typescore.User, collected map[string]string, actualExecutorID uint64) { approvalID := *approval.ID @@ -156,7 +176,6 @@ func (h *Handler) processNextStepOrComplete(bot *tgbotapi.BotAPI, ctx context.Co return } - // Последний шаг - все остальное без изменений approvedStatus := "approved" approval.Status = &approvedStatus h.ipc.Database.Approval.UpdateApprovalDB(ctx, nil, approval) //nolint:errcheck @@ -179,11 +198,6 @@ func (h *Handler) processNextStepOrComplete(bot *tgbotapi.BotAPI, ctx context.Co "%s\n\nИнициатор уведомлён.", approvalID, executorName, approvalCard, ) - } else { - messageText = fmt.Sprintf( - "🎉 Заявка #%d полностью согласована\n\n%s\n\nИнициатор уведомлён.", - approvalID, approvalCard, - ) } notifyMsg := tgbotapi.NewMessage(*mainApprover.TelegramID, messageText) @@ -192,56 +206,7 @@ func (h *Handler) processNextStepOrComplete(bot *tgbotapi.BotAPI, ctx context.Co } } - if approval.TopicID != nil { - topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID) - if topic != nil && topic.TaskTemplate != nil && *topic.TaskTemplate != "" { - meta, _ := typescore.ParseApprovalMetadata(approval.Metadata) - - systems := []string{""} - if len(meta.SelectedSystems) > 0 { - systems = meta.SelectedSystems - } - - for _, system := range systems { - taskText := *topic.TaskTemplate - - // Добавляем систему в текст задачи если она указана - if system != "" { - systemLabel := system - switch system { - case "okb": - systemLabel = "ОКБ" - case "bitrix": - systemLabel = "Битрикс" - case "1c": - systemLabel = "1С" - } - taskText = fmt.Sprintf("[%s] %s", systemLabel, taskText) - } - - executor, _ := h.ipc.Database.UserHierarchy.GetExecutorDB( - ctx, *initiator.ID, *initiator.DepartmentID, *approval.TopicID, *topic.CategoryID, - ) - if executor == nil || executor.ID == nil { - continue - } - - createdTask, _, err := h.ipc.Database.ApprovalTasks.CreateApprovalTaskDB(ctx, nil, &typescore.ApprovalTask{ - ApprovalID: approval.ID, - ExecutorID: executor.ID, - TaskText: &taskText, - Status: utilscore.PointerToString("pending"), - }, true) - if err != nil { - logrus.Errorf("processNextStepOrComplete: CreateApprovalTask system=%s err=%v", system, err) - continue - } - if createdTask != nil && executor.TelegramID != nil { - h.notifyExecutor(bot, ctx, executor, initiator, approval, createdTask) - } - } - } - } + h.createTasksForApproval(bot, ctx, approval, initiator) if initiator.TelegramID != nil { lastApprover, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *currentStep.ApproverID) @@ -287,49 +252,44 @@ func (h *Handler) processNextStepOrComplete(bot *tgbotapi.BotAPI, ctx context.Co if observers, err := h.ipc.Database.User.GetObserversForCategoryDB(ctx, categoryCode); err == nil && len(observers) > 0 { stepApprover, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *currentStep.ApproverID) - notifier.NotifyObserversDecision(bot, observers, stepApprover, initiator, approval, collected, true) + notifier.NotifyObserversDecision(bot, observers, initiator, stepApprover, approval, collected) } } // HandleDecisionWithChat — вызывается при текстовом вводе комментария. // chatID — чат согласующего для отправки обратной связи. -func (h *Handler) HandleDecisionWithChat(bot *tgbotapi.BotAPI, approverChatID int64, approvalID uint64, approved bool, comment string) { - h.handleDecision(bot, nil, approverChatID, approvalID, approved, comment) -} - -// HandleDecision — вызывается при нажатии inline-кнопки. -func (h *Handler) HandleDecision(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64, approved bool, comment string) { - var approverChatID int64 - if cq != nil { - bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck - approverChatID = cq.Message.Chat.ID - } - h.handleDecision(bot, cq, approverChatID, approvalID, approved, comment) +func (h *Handler) HandleDecisionWithChat( + bot *tgbotapi.BotAPI, + chatID int64, + telegramID int64, + approvalID uint64, + approved bool, + comment string, +) { + h.handleDecision(bot, nil, chatID, telegramID, approvalID, approved, comment) } // handleDecision — основная логика, принимает chatID явно. -func (h *Handler) handleDecision(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approverChatID int64, approvalID uint64, approved bool, comment string) { +func (h *Handler) handleDecision( + bot *tgbotapi.BotAPI, + cq *tgbotapi.CallbackQuery, + approverChatID int64, + telegramID int64, + approvalID uint64, + approved bool, + comment string, +) { ctx := context.Background() if cq != nil { bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck } - var currentUserID uint64 - if cq != nil { - user, _ := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, cq.From.ID) - if user == nil || user.ID == nil { - return - } - currentUserID = *user.ID - } else { - user, _ := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, approverChatID) - if user == nil || user.ID == nil { - return - } - currentUserID = *user.ID + user, _ := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if user == nil || user.ID == nil { + return } - + currentUserID := *user.ID actualExecutor, _ := h.ipc.Database.User.GetUserByIDDB(ctx, currentUserID) approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID) @@ -348,11 +308,14 @@ func (h *Handler) handleDecision(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuer return } + approvalTopic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID) + requireComment := approvalTopic != nil && approvalTopic.RequireApproverComment != nil && *approvalTopic.RequireApproverComment + isAnyOf := approvalTopic != nil && approvalTopic.ApprovalMode != nil && *approvalTopic.ApprovalMode == "any_of" + additionalApprovers, _, _ := h.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalAdditionalApprover{ - ApprovalID: &approvalID, - }, + Filtering: &typescore.ApprovalAdditionalApprover{ApprovalID: &approvalID}, }) + var isAdditionalApprover bool var additionalApproverRecord *typescore.ApprovalAdditionalApprover for _, aa := range additionalApprovers { @@ -373,33 +336,90 @@ func (h *Handler) handleDecision(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuer if initiator.FullName != nil { initiatorName = *initiator.FullName } - topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID) - content := "—" if approval.Content != nil { content = *approval.Content } approvalCard := fmt.Sprintf( - "👤 Инициатор: %s\n"+ - "📋 Тема: %s\n"+ - "📝 Текст: %s", + "👤 Инициатор: %s\n📋 Тема: %s\n📝 Текст: %s", initiatorName, topicFullName, content, ) categoryCode := h.getTopicCodeByApproval(ctx, approval) - topic, err := h.registry.Get(categoryCode) + topic, err := h.Registry.Get(categoryCode) if err != nil { logrus.Errorf("handleDecision: topic not found code=%s err=%v", categoryCode, err) return } notifier := NewNotifier(h.ipc, topic) collected := h.getCollectedFromApproval(ctx, approval) - now := time.Now() - // ОБРАБОТКА ОТКЛОНЕНИЯ + // 🚀 Вспомогательная функция: сохранить решение/комментарий в общую таблицу комментариев + saveCommentToApproval := func(commentText string) { + if strings.TrimSpace(commentText) == "" || user.ID == nil { + return + } + approvalComment := &typescore.ApprovalComment{ + ApprovalID: &approvalID, + UserID: user.ID, + Comment: &commentText, + } + if _, _, err := h.ipc.Database.ApprovalComment.CreateApprovalCommentDB(ctx, nil, approvalComment); err != nil { + logrus.Errorf("handleDecision: CreateApprovalCommentDB err=%v", err) + } + } + + // 🚀 Вспомогательная функция: проверить, является ли текущий шаг последним + isLastStep := func(currentStepOrder int) bool { + allSteps, _, _ := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalStep{ApprovalID: &approvalID}, + }) + for _, s := range allSteps { + if s.StepOrder == nil { + continue + } + if *s.StepOrder > currentStepOrder { + // Есть следующий шаг — значит текущий не последний + return false + } + } + return true + } + + notifyRejection := func(stepApproverID *uint64) { + if approverChatID != 0 { + commentText := "" + if comment != "" { + commentText = fmt.Sprintf("\n💬 Комментарий: %s", comment) + } + sendText(bot, approverChatID, fmt.Sprintf("❌ Заявка #%d отклонена\n\n%s%s", approvalID, approvalCard, commentText)) + } + if initiator.TelegramID != nil { + var stepApprover *typescore.User + if stepApproverID != nil { + stepApprover, _ = h.ipc.Database.User.GetUserByIDDB(ctx, *stepApproverID) + } else { + stepApprover = actualExecutor + } + notifier.NotifyInitiatorRejected(bot, initiator, stepApprover, approval, collected, comment) + } + if observers, err := h.ipc.Database.User.GetObserversForCategoryDB(ctx, categoryCode); err == nil && len(observers) > 0 { + var stepApprover *typescore.User + if stepApproverID != nil { + stepApprover, _ = h.ipc.Database.User.GetUserByIDDB(ctx, *stepApproverID) + } else { + stepApprover = actualExecutor + } + notifier.NotifyObserversDecision(bot, observers, initiator, stepApprover, approval, collected) + } + } + + // ========================================== + // === БЛОК ОТКЛОНЕНИЯ === + // ========================================== if !approved { if isAdditionalApprover { rejectedStatus := "rejected" @@ -408,43 +428,27 @@ func (h *Handler) handleDecision(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuer additionalApproverRecord.ActedAt = &now h.ipc.Database.ApprovalAdditionalApprover.UpdateApprovalAdditionalApproverDB(ctx, nil, additionalApproverRecord) //nolint:errcheck - rejectedStatus = "rejected" + // 🚀 Сохраняем комментарий отклонения в общую таблицу + if comment != "" { + commentText := fmt.Sprintf("❌ Отклонение (доп. согласующий): %s", comment) + saveCommentToApproval(commentText) + } + approval.Status = &rejectedStatus h.ipc.Database.Approval.UpdateApprovalDB(ctx, nil, approval) //nolint:errcheck - - if approverChatID != 0 { - commentText := "" - if comment != "" { - commentText = fmt.Sprintf("\n💬 Комментарий: %s", comment) - } - sendText(bot, approverChatID, fmt.Sprintf( - "❌ Заявка #%d отклонена\n\n%s%s", - approvalID, approvalCard, commentText, - )) - } - - if initiator.TelegramID != nil { - currentApprover, _ := h.ipc.Database.User.GetUserByIDDB(ctx, currentUserID) - notifier.NotifyInitiatorRejected(bot, initiator, currentApprover, approval, collected, comment) - } - - if observers, err := h.ipc.Database.User.GetObserversForCategoryDB(ctx, categoryCode); err == nil && len(observers) > 0 { - currentApprover, _ := h.ipc.Database.User.GetUserByIDDB(ctx, currentUserID) - notifier.NotifyObserversDecision(bot, observers, currentApprover, initiator, approval, collected, false) - } + notifyRejection(nil) return } - step, err := h.ipc.Database.ApprovalStep.GetActiveStepDB(ctx, approvalID) - if err != nil || step == nil { - logrus.Warnf("handleDecision: active step not found approvalID=%d err=%v", approvalID, err) + step := h.findStepForCurrentApprover(ctx, approvalID, currentUserID, approval, isAnyOf) + if step == nil { + logrus.Warnf("handleDecision: active step not found for user approvalID=%d userID=%d", approvalID, currentUserID) if approverChatID != 0 { sendText(bot, approverChatID, "⚠️ Шаг согласования не найден или уже обработан.") } return } - // ИСПРАВЛЕНИЕ 2: Проверяем, является ли исполнитель делегатом isDelegate := step.ApproverID != nil && *step.ApproverID != currentUserID var originalApprover *typescore.User if isDelegate { @@ -455,29 +459,56 @@ func (h *Handler) handleDecision(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuer step.Status = &rejectedStatus step.Comment = &comment step.ActedAt = &now - - // Сохраняем имя фактического исполнителя (делегата) if actualExecutor != nil && actualExecutor.FullName != nil { step.ApproverNameSnapshot = actualExecutor.FullName } h.ipc.Database.ApprovalStep.UpdateApprovalStepDB(ctx, nil, step) //nolint:errcheck - rejectedStatus = "rejected" - approval.Status = &rejectedStatus - h.ipc.Database.Approval.UpdateApprovalDB(ctx, nil, approval) //nolint:errcheck - - if approverChatID != 0 { - commentText := "" - if comment != "" { - commentText = fmt.Sprintf("\n💬 Комментарий: %s", comment) - } - sendText(bot, approverChatID, fmt.Sprintf( - "❌ Заявка #%d отклонена\n\n%s%s", - approvalID, approvalCard, commentText, - )) + // 🚀 Сохраняем комментарий отклонения в общую таблицу + if comment != "" { + commentText := fmt.Sprintf("❌ Отклонение: %s", comment) + saveCommentToApproval(commentText) } - // ИСПРАВЛЕНИЕ 2: Уведомляем оригинального согласующего если решение принял делегат + if isAnyOf { + 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" && *s.Status != "pending") { + continue + } + cancelledStatus := "cancelled_any_of" + s.Status = &cancelledStatus + h.ipc.Database.ApprovalStep.UpdateApprovalStepDB(ctx, nil, s) //nolint:errcheck + + if s.ApproverID != nil { + approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *s.ApproverID) + if approver != nil && approver.TelegramID != nil { + deciderName := "—" + if actualExecutor != nil && actualExecutor.FullName != nil { + deciderName = *actualExecutor.FullName + } + sendText(bot, *approver.TelegramID, fmt.Sprintf( + "ℹ️ Заявка #%d отклонена\n\n👤 Отклонил: %s\n\nВаше участие в согласовании больше не требуется.", + approvalID, deciderName, + )) + } + } + } + approval.Status = &rejectedStatus + h.ipc.Database.Approval.UpdateApprovalDB(ctx, nil, approval) //nolint:errcheck + notifyRejection(step.ApproverID) + return + } + + approval.Status = &rejectedStatus + h.ipc.Database.Approval.UpdateApprovalDB(ctx, nil, approval) //nolint:errcheck + notifyRejection(step.ApproverID) + if isDelegate && originalApprover != nil && originalApprover.TelegramID != nil { executorName := "—" if actualExecutor != nil && actualExecutor.FullName != nil { @@ -488,37 +519,92 @@ func (h *Handler) handleDecision(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuer commentText = fmt.Sprintf("\n💬 Комментарий: %s", comment) } notifyMsg := tgbotapi.NewMessage(*originalApprover.TelegramID, fmt.Sprintf( - "ℹ️ Ваш делегат отклонил заявку #%d\n\n"+ - "👤 Делегат: %s\n"+ - "%s%s", + "ℹ️ Ваш делегат отклонил заявку #%d\n\n👤 Делегат: %s\n%s%s", approvalID, executorName, approvalCard, commentText, )) notifyMsg.ParseMode = "HTML" bot.Send(notifyMsg) //nolint:errcheck } - - if initiator.TelegramID != nil { - stepApprover, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *step.ApproverID) - notifier.NotifyInitiatorRejected(bot, initiator, stepApprover, approval, collected, comment) - } - - if observers, err := h.ipc.Database.User.GetObserversForCategoryDB(ctx, categoryCode); err == nil && len(observers) > 0 { - stepApprover, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *step.ApproverID) - notifier.NotifyObserversDecision(bot, observers, stepApprover, initiator, approval, collected, false) - } return } - // ОБРАБОТКА ОДОБРЕНИЯ + // ========================================== + // === БЛОК ОДОБРЕНИЯ === + // ========================================== + + // Запрос обязательного комментария для первого шага + if requireComment && comment == "" { + activeStep, _ := h.ipc.Database.ApprovalStep.GetActiveStepDB(ctx, approvalID) + if activeStep != nil && activeStep.StepOrder != nil && *activeStep.StepOrder == 0 { + commentKey := fmt.Sprintf("appr_approve_comment_pending:%d", telegramID) + h.ipc.RedisClient.Set(ctx, commentKey, fmt.Sprintf("%d", approvalID), 10*time.Minute) //nolint:errcheck + + if approverChatID != 0 { + msg := tgbotapi.NewMessage(approverChatID, + "💬 Для согласования этой заявки необходимо оставить комментарий.\n\nВведите комментарий:") + msg.ParseMode = "HTML" + bot.Send(msg) //nolint:errcheck + } + return + } + } + + getPendingAdditionalInfo := func() (int, []string) { + var pendingNames []string + count := 0 + for _, aa := range additionalApprovers { + if isAdditionalApprover && additionalApproverRecord != nil && aa.ID != nil && additionalApproverRecord.ID != nil && *aa.ID == *additionalApproverRecord.ID { + continue + } + if aa.Status != nil && *aa.Status == "pending" && aa.ApproverID != nil { + count++ + approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *aa.ApproverID) + if approver != nil && approver.FullName != nil { + pendingNames = append(pendingNames, *approver.FullName) + } + } + } + return count, pendingNames + } + + // --- Дополнительный согласующий --- if isAdditionalApprover { approvedStatus := "approved" additionalApproverRecord.Status = &approvedStatus additionalApproverRecord.ActedAt = &now h.ipc.Database.ApprovalAdditionalApprover.UpdateApprovalAdditionalApproverDB(ctx, nil, additionalApproverRecord) //nolint:errcheck - step, err := h.ipc.Database.ApprovalStep.GetActiveStepDB(ctx, approvalID) - if err != nil || step == nil { - logrus.Warnf("handleDecision: active step not found approvalID=%d err=%v", approvalID, err) + // 🚀 Сохраняем одобрение доп. согласующего в комментарии (если есть комментарий) + if comment != "" { + commentText := fmt.Sprintf("✅ Одобрение (доп. согласующий): %s", comment) + saveCommentToApproval(commentText) + } + + mainStep, _ := h.ipc.Database.ApprovalStep.GetActiveStepDB(ctx, approvalID) + + if mainStep != nil && mainStep.ApproverID != nil && *mainStep.ApproverID != currentUserID { + mainApprover, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *mainStep.ApproverID) + if mainApprover != nil && mainApprover.TelegramID != nil { + addApproverName := "—" + if actualExecutor != nil && actualExecutor.FullName != nil { + addApproverName = *actualExecutor.FullName + } + notifyMsg := tgbotapi.NewMessage(*mainApprover.TelegramID, fmt.Sprintf( + "✅ Дополнительный согласующий одобрил заявку #%d\n\n"+ + "👤 Согласующий: %s\n%s", + approvalID, addApproverName, approvalCard, + )) + notifyMsg.ParseMode = "HTML" + bot.Send(notifyMsg) //nolint:errcheck + } + } + + step := h.findStepForCurrentApprover(ctx, approvalID, currentUserID, approval, isAnyOf) + if step == nil { + logrus.Warnf("handleDecision: active step not found for user approvalID=%d userID=%d", approvalID, currentUserID) + if approverChatID != 0 { + sendText(bot, approverChatID, "⚠️ Шаг согласования не найден или уже обработан.") + } return } @@ -531,69 +617,47 @@ func (h *Handler) handleDecision(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuer allAdditionalApproved = false break } + if aa.Status != nil && *aa.Status == "rejected" { + allAdditionalApproved = false + break + } } mainApproverApproved := step.Status != nil && *step.Status == "approved" if approverChatID != 0 { + pendingCount, pendingNames := getPendingAdditionalInfo() + pendingText := "" + if pendingCount > 0 { + pendingText = fmt.Sprintf("\n\n⏳ Ожидается решение других дополнительных согласующих (%d):\n• %s", + pendingCount, strings.Join(pendingNames, "\n• ")) + } + if !mainApproverApproved { - sendText(bot, approverChatID, fmt.Sprintf( - "✅ Вы одобрили заявку #%d\n\n%s\n\nОжидается решение основного согласующего.", - approvalID, approvalCard, - )) + sendText(bot, approverChatID, fmt.Sprintf("✅ Вы одобрили заявку #%d\n\n%s\n\nОжидается решение основного согласующего.", approvalID, approvalCard)) } else if !allAdditionalApproved { - pendingCount := 0 - var pendingNames []string - for _, aa := range additionalApprovers { - if aa.ID != nil && additionalApproverRecord.ID != nil && *aa.ID == *additionalApproverRecord.ID { - continue - } - if aa.Status != nil && *aa.Status == "pending" && aa.ApproverID != nil { - pendingCount++ - approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *aa.ApproverID) - if approver != nil && approver.FullName != nil { - pendingNames = append(pendingNames, *approver.FullName) - } - } - } - - pendingText := "" - if pendingCount > 0 { - pendingText = fmt.Sprintf("\n\n⏳ Ожидается решение других дополнительных согласующих (%d):\n• %s", - pendingCount, strings.Join(pendingNames, "\n• ")) - } - - sendText(bot, approverChatID, fmt.Sprintf( - "✅ Вы одобрили заявку #%d\n\n%s%s", - approvalID, approvalCard, pendingText, - )) + sendText(bot, approverChatID, fmt.Sprintf("✅ Вы одобрили заявку #%d\n\n%s%s", approvalID, approvalCard, pendingText)) } else { - sendText(bot, approverChatID, fmt.Sprintf( - "✅ Вы одобрили заявку #%d\n\n%s\n\nВсе согласующие одобрили заявку.", - approvalID, approvalCard, - )) + // 🚀 Все доп. согласующие одобрили, но нужно проверить, последний ли это шаг + var currentOrder int + if step.StepOrder != nil { + currentOrder = *step.StepOrder + } + if isLastStep(currentOrder) { + sendText(bot, approverChatID, fmt.Sprintf("✅ Вы одобрили заявку #%d\n\n%s\n\nВсе согласующие одобрили заявку.", approvalID, approvalCard)) + } else { + sendText(bot, approverChatID, fmt.Sprintf("✅ Вы одобрили заявку #%d\n\n%s\n\nЗаявка передана следующему согласующему.", approvalID, approvalCard)) + } } } if mainApproverApproved && allAdditionalApproved { - if step.ApproverID != nil { - mainApprover, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *step.ApproverID) - if mainApprover != nil && mainApprover.TelegramID != nil { - notifyMsg := tgbotapi.NewMessage(*mainApprover.TelegramID, fmt.Sprintf( - "✅ Все дополнительные согласующие одобрили заявку #%d\n\n%s", - approvalID, approvalCard, - )) - notifyMsg.ParseMode = "HTML" - bot.Send(notifyMsg) //nolint:errcheck - } - } - h.processNextStepOrComplete(bot, ctx, approval, step, approvalCard, categoryCode, notifier, initiator, collected, currentUserID) } - return } + // --- Основной согласующий --- step, err := h.ipc.Database.ApprovalStep.GetActiveStepDB(ctx, approvalID) if err != nil || step == nil { logrus.Warnf("handleDecision: active step not found approvalID=%d err=%v", approvalID, err) @@ -603,7 +667,6 @@ func (h *Handler) handleDecision(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuer return } - // ИСПРАВЛЕНИЕ 2: Проверяем, является ли исполнитель делегатом isDelegate := step.ApproverID != nil && *step.ApproverID != currentUserID var originalApprover *typescore.User if isDelegate { @@ -617,18 +680,62 @@ func (h *Handler) handleDecision(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuer step.ApproverNameSnapshot = actualExecutor.FullName } - // Атомарное обновление с проверкой предыдущего статуса updated, _, err := h.ipc.Database.ApprovalStep.UpdateApprovalStepDB(ctx, nil, step, true) if err != nil || updated == nil { - sendText(bot, approverChatID, "⚠️ Ошибка при сохранении решения.") + if approverChatID != 0 { + sendText(bot, approverChatID, "⚠️ Ошибка при сохранении решения.") + } + return + } + + // 🚀 Сохраняем одобрение/комментарий в общую таблицу комментариев + if comment != "" { + commentText := fmt.Sprintf("✅ Одобрение: %s", comment) + saveCommentToApproval(commentText) + } + + // --- Режим any_of --- + if isAnyOf { + allSteps, _, _ := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalStep{ApprovalID: &approvalID}, + }) + for _, s := range allSteps { + if s.ID == nil || s.Status == nil || (*s.Status != "waiting" && *s.Status != "pending") { + continue + } + if s.ID != nil && step.ID != nil && *s.ID == *step.ID { + continue + } + cancelledStatus := "cancelled_any_of" + s.Status = &cancelledStatus + h.ipc.Database.ApprovalStep.UpdateApprovalStepDB(ctx, nil, s) //nolint:errcheck + + if s.ApproverID != nil { + approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *s.ApproverID) + if approver != nil && approver.TelegramID != nil { + deciderName := "—" + if actualExecutor != nil && actualExecutor.FullName != nil { + deciderName = *actualExecutor.FullName + } + sendText(bot, *approver.TelegramID, fmt.Sprintf( + "ℹ️ Заявка #%d уже согласована\n\n"+ + "👤 Согласовал: %s\n\n"+ + "Ваше участие в согласовании больше не требуется.", + approvalID, deciderName, + )) + } + } + } + + h.processNextStepOrComplete(bot, ctx, approval, step, approvalCard, categoryCode, notifier, initiator, collected, currentUserID) return } - // Перечитываем из БД чтобы убедиться что ОБА условия актуальны freshApproval, _ := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID) if freshApproval != nil && freshApproval.Status != nil && *freshApproval.Status != "pending" { - // уже обработано другим участником — не продолжаем - sendText(bot, approverChatID, fmt.Sprintf("✅ Заявка #%d уже обработана.", approvalID)) + if approverChatID != 0 { + sendText(bot, approverChatID, fmt.Sprintf("✅ Заявка #%d уже обработана.", approvalID)) + } return } @@ -645,41 +752,32 @@ func (h *Handler) handleDecision(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuer } } + // Ожидаются дополнительные согласующие if !allAdditionalApproved { if approverChatID != 0 { - if len(pendingAdditional) > 0 { - var pendingNames []string - for _, aa := range pendingAdditional { - if aa.ApproverID != nil { - approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *aa.ApproverID) - if approver != nil && approver.FullName != nil { - pendingNames = append(pendingNames, *approver.FullName) - } - } - } - + pendingCount, pendingNames := getPendingAdditionalInfo() + if pendingCount > 0 { pendingText := fmt.Sprintf("\n\n⏳ Ожидается решение дополнительных согласующих (%d):\n• %s", - len(pendingAdditional), strings.Join(pendingNames, "\n• ")) - - sendText(bot, approverChatID, fmt.Sprintf( - "✅ Вы одобрили заявку #%d\n\n%s%s", - approvalID, approvalCard, pendingText, - )) + pendingCount, strings.Join(pendingNames, "\n• ")) + sendText(bot, approverChatID, fmt.Sprintf("✅ Вы одобрили заявку #%d\n\n%s%s", approvalID, approvalCard, pendingText)) } else { - sendText(bot, approverChatID, fmt.Sprintf( - "✅ Вы одобрили заявку #%d\n\n%s", - approvalID, approvalCard, - )) + sendText(bot, approverChatID, fmt.Sprintf("✅ Вы одобрили заявку #%d\n\n%s", approvalID, approvalCard)) } } return } + // 🚀 Все доп. согласующие одобрили — проверяем, последний ли это шаг if approverChatID != 0 { - sendText(bot, approverChatID, fmt.Sprintf( - "✅ Вы одобрили заявку #%d\n\n%s\n\nВсе согласующие одобрили заявку.", - approvalID, approvalCard, - )) + var currentOrder int + if step.StepOrder != nil { + currentOrder = *step.StepOrder + } + if isLastStep(currentOrder) { + sendText(bot, approverChatID, fmt.Sprintf("✅ Вы одобрили заявку #%d\n\n%s\n\nВсе согласующие одобрили заявку.", approvalID, approvalCard)) + } else { + sendText(bot, approverChatID, fmt.Sprintf("✅ Вы одобрили заявку #%d\n\n%s\n\nЗаявка передана следующему согласующему.", approvalID, approvalCard)) + } } if isDelegate && originalApprover != nil && originalApprover.TelegramID != nil { @@ -688,9 +786,7 @@ func (h *Handler) handleDecision(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuer executorName = *actualExecutor.FullName } notifyMsg := tgbotapi.NewMessage(*originalApprover.TelegramID, fmt.Sprintf( - "ℹ️ Ваш делегат одобрил заявку #%d\n\n"+ - "👤 Делегат: %s\n"+ - "%s", + "ℹ️ Ваш делегат одобрил заявку #%d\n\n👤 Делегат: %s\n%s", approvalID, executorName, approvalCard, )) notifyMsg.ParseMode = "HTML" @@ -699,3 +795,12 @@ func (h *Handler) handleDecision(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuer h.processNextStepOrComplete(bot, ctx, approval, step, approvalCard, categoryCode, notifier, initiator, collected, currentUserID) } + +// Вспомогательный метод рядом: +func (h *Handler) getApproverName(ctx context.Context, userID uint64) string { + user, _ := h.ipc.Database.User.GetUserByIDDB(ctx, userID) + if user != nil && user.FullName != nil { + return *user.FullName + } + return "—" +} diff --git a/service/telegram_service/handlers/approval/handler_executor.go b/service/telegram_service/handlers/approval/handler_executor.go index 64f0a7f..e8f53ff 100644 --- a/service/telegram_service/handlers/approval/handler_executor.go +++ b/service/telegram_service/handlers/approval/handler_executor.go @@ -4,10 +4,13 @@ import ( "bitrix_balancer_api/core/typescore" "bitrix_balancer_api/core/utilscore" "bitrix_balancer_api/telegram_service/keyboard" + "bitrix_balancer_api/telegram_service/state" "context" "fmt" tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" "github.com/sirupsen/logrus" + "sort" + "strings" "time" ) @@ -98,7 +101,20 @@ func (h *Handler) sendTaskCard(bot *tgbotapi.BotAPI, chatID int64, approval *typ *approval.ID, initiatorName, topicFullName, content, createdAt, taskText, ) - // Добавляем комментарии + allFiles, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID) + var taskFiles []string + for _, f := range allFiles { + if f.TaskID != nil && *f.TaskID == *task.ID && f.FileName != nil { + taskFiles = append(taskFiles, *f.FileName) + } + } + if len(taskFiles) > 0 { + text += "\n\n📎 Прикреплённые файлы:\n" + for i, name := range taskFiles { + text += fmt.Sprintf("%d. %s\n", i+1, name) + } + } + commentsSection := h.formatCommentsSection(ctx, *approval.ID) text += commentsSection @@ -133,19 +149,7 @@ func (h *Handler) HandleCompleteTask(bot *tgbotapi.BotAPI, cq *tgbotapi.Callback } if task.Status != nil && *task.Status != "pending" { - sendText(bot, chatID, "⚠️ Задача уже выполнена.") - return - } - - now := time.Now() - completedStatus := "completed" - task.Status = &completedStatus - task.CompletedAt = &now - - _, _, err = h.ipc.Database.ApprovalTasks.UpdateApprovalTaskDB(ctx, nil, task) - if err != nil { - logrus.Errorf("HandleCompleteTask: UpdateApprovalTaskDB err=%v", err) - sendText(bot, chatID, "Ошибка при выполнении задачи.") + sendText(bot, chatID, "⚠️ Задача уже выполнена или не активна.") return } @@ -158,6 +162,42 @@ func (h *Handler) HandleCompleteTask(bot *tgbotapi.BotAPI, cq *tgbotapi.Callback } } + // 🚀 Проверка обязательности файла — ищем файлы, привязанные именно к этой задаче + requireFile := task.RequireFile != nil && *task.RequireFile + if requireFile { + files, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *task.ApprovalID) + hasExecutorFile := false + for _, f := range files { + if f.AttachedByID != nil && *f.AttachedByID == *user.ID && + f.TaskID != nil && *f.TaskID == *task.ID { + hasExecutorFile = true + break + } + } + if !hasExecutorFile { + msg := tgbotapi.NewMessage(chatID, + "⚠️ Для завершения необходимо прикрепить файл.\n\n"+ + "Нажмите «📎 Прикрепить файл», прикрепите документ, затем нажмите «Выполнено».") + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildExecutorTaskActions(*task.ID, *approval.ID) + bot.Send(msg) //nolint:errcheck + return + } + } + + // Обновляем статус текущей задачи + now := time.Now() + completedStatus := "completed" + task.Status = &completedStatus + task.CompletedAt = &now + + _, _, err = h.ipc.Database.ApprovalTasks.UpdateApprovalTaskDB(ctx, nil, task) + if err != nil { + logrus.Errorf("HandleCompleteTask: UpdateApprovalTaskDB err=%v", err) + sendText(bot, chatID, "Ошибка при выполнении задачи.") + return + } + sendText(bot, chatID, fmt.Sprintf( "✅ Задача выполнена\n\n"+ "📋 Заявка: #%d — %s\n\n"+ @@ -165,6 +205,8 @@ func (h *Handler) HandleCompleteTask(bot *tgbotapi.BotAPI, cq *tgbotapi.Callback *task.ApprovalID, topicName, )) + h.activateNextTask(bot, ctx, approval, task) + // Уведомляем инициатора if approval != nil && approval.InitiatorID != nil { initiator, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID) @@ -188,6 +230,327 @@ func (h *Handler) HandleCompleteTask(bot *tgbotapi.BotAPI, cq *tgbotapi.Callback )) notifyMsg.ParseMode = "HTML" bot.Send(notifyMsg) //nolint:errcheck + + if approval.TopicID != nil { + approvalTopic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID) + if approvalTopic != nil && approvalTopic.Code != nil { + topicCode := *approvalTopic.Code + // Проверяем, что тема относится к "Заказу товаров" + if strings.HasPrefix(topicCode, "goods_order_") { + hintMsg := tgbotapi.NewMessage(*initiator.TelegramID, + "📦 Следи за выполнением заказа") + hintMsg.ParseMode = "HTML" + bot.Send(hintMsg) //nolint:errcheck + } + } + } } } } + +// activateNextTask активирует следующую задачу в очереди после завершения текущей +func (h *Handler) activateNextTask(bot *tgbotapi.BotAPI, ctx context.Context, approval *typescore.Approval, completedTask *typescore.ApprovalTask) { + if approval == nil || approval.ID == nil || completedTask.StepOrder == nil { + return + } + + allTasks, _, err := h.ipc.Database.ApprovalTasks.GetApprovalTasksListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalTask{ApprovalID: approval.ID}, + }) + if err != nil || len(allTasks) == 0 { + return + } + + var nextTask *typescore.ApprovalTask + for _, t := range allTasks { + if t.Status != nil && *t.Status == "waiting" && t.StepOrder != nil && completedTask.StepOrder != nil { + if *t.StepOrder == *completedTask.StepOrder+1 { + nextTask = t + break + } + } + } + + if nextTask == nil || nextTask.ExecutorID == nil { + return + } + + pendingStatus := "pending" + nextTask.Status = &pendingStatus + _, _, err = h.ipc.Database.ApprovalTasks.UpdateApprovalTaskDB(ctx, nil, nextTask) + if err != nil { + logrus.Errorf("activateNextTask: UpdateApprovalTaskDB err=%v", err) + return + } + + executor, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *nextTask.ExecutorID) + if executor != nil && executor.TelegramID != nil { + initiator, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID) + if initiator == nil { + return + } + h.notifyExecutor(bot, ctx, executor, initiator, approval, nextTask) + } +} + +// handleRevokeCancellationTask — вызывается при отзыве заявки. +// Если задача выполнена — создаём задачу на обращение изменений. +// Если задача ожидает — спрашиваем исполнителя, вносил ли он изменения. +func (h *Handler) handleRevokeCancellationTask( + bot *tgbotapi.BotAPI, + ctx context.Context, + approval *typescore.Approval, + revoker *typescore.User, + revokeComment string, +) { + if approval.ID == nil { + return + } + + tasks, _, err := h.ipc.Database.ApprovalTasks.GetApprovalTasksListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalTask{ApprovalID: approval.ID}, + }) + if err != nil || len(tasks) == 0 { + return + } + + sort.Slice(tasks, func(i, j int) bool { + if tasks[i].StepOrder == nil || tasks[j].StepOrder == nil { + return false + } + return *tasks[i].StepOrder < *tasks[j].StepOrder + }) + + for _, task := range tasks { + if task.Status == nil || task.ExecutorID == nil || task.ID == nil { + continue + } + + executor, err := h.ipc.Database.User.GetUserByIDDB(ctx, *task.ExecutorID) + if err != nil || executor == nil || executor.TelegramID == nil { + continue + } + + switch *task.Status { + case "completed": + h.createReversalTask(bot, ctx, approval, task, executor) + + case "pending": + h.askExecutorAboutChanges(bot, ctx, approval, task, executor) + + case "waiting": + cancelledStatus := "cancelled" + task.Status = &cancelledStatus + h.ipc.Database.ApprovalTasks.UpdateApprovalTaskDB(ctx, nil, task) //nolint:errcheck + + if executor.TelegramID != nil { + sendText(bot, *executor.TelegramID, fmt.Sprintf( + "↩️ Заявка #%d отозвана\n\nВаша задача отменена.", + *approval.ID, + )) + } + } + } +} + +// createReversalTask — создаёт задачу "обратить изменения" и уведомляет исполнителя. +func (h *Handler) createReversalTask( + bot *tgbotapi.BotAPI, + ctx context.Context, + approval *typescore.Approval, + originalTask *typescore.ApprovalTask, + executor *typescore.User, +) { + if approval.ID == nil || executor.TelegramID == nil { + return + } + + originalTaskText := "—" + if originalTask.TaskText != nil { + originalTaskText = *originalTask.TaskText + } + + topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID) + content := "—" + if approval.Content != nil { + content = *approval.Content + } + + reversalText := fmt.Sprintf( + "Обратить изменения по заявке #%d\n\nТема: %s\nИсходная задача: %s", + *approval.ID, topicFullName, originalTaskText, + ) + + pendingStatus := "pending" + reversalTask := &typescore.ApprovalTask{ + ApprovalID: approval.ID, + ExecutorID: originalTask.ExecutorID, + TaskText: &reversalText, + Status: &pendingStatus, + } + + created, _, err := h.ipc.Database.ApprovalTasks.CreateApprovalTaskDB(ctx, nil, reversalTask, true) + if err != nil || created == nil || created.ID == nil { + logrus.Errorf("createReversalTask: CreateApprovalTaskDB err=%v", err) + return + } + + msg := tgbotapi.NewMessage(*executor.TelegramID, fmt.Sprintf( + "⚠️ Заявка #%d отозвана — требуется обратить изменения\n\n"+ + "📋 Тема: %s\n"+ + "📝 Текст заявки: %s\n\n"+ + "🔄 Новая задача:\n%s", + *approval.ID, topicFullName, content, reversalText, + )) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildExecutorTaskActions(*created.ID, *approval.ID) + bot.Send(msg) //nolint:errcheck +} + +// askExecutorAboutChanges — спрашивает исполнителя, вносил ли он изменения +// по задаче, которая ещё не выполнена на момент отзыва заявки. +func (h *Handler) askExecutorAboutChanges( + bot *tgbotapi.BotAPI, + ctx context.Context, + approval *typescore.Approval, + task *typescore.ApprovalTask, + executor *typescore.User, +) { + if approval.ID == nil || task.ID == nil || executor.TelegramID == nil { + return + } + + topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID) + content := "—" + if approval.Content != nil { + content = *approval.Content + } + taskText := "—" + if task.TaskText != nil { + taskText = *task.TaskText + } + + msg := tgbotapi.NewMessage(*executor.TelegramID, fmt.Sprintf( + "↩️ Заявка #%d отозвана\n\n"+ + "📋 Тема: %s\n"+ + "📝 Текст заявки: %s\n\n"+ + "🎯 Ваша задача: %s\n\n"+ + "Вы уже вносили какие-либо изменения по этой задаче?", + *approval.ID, topicFullName, content, taskText, + )) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildRevokeTaskConfirmation(*task.ID, *approval.ID) + bot.Send(msg) //nolint:errcheck +} + +// HandleRevokeTaskNoChanges — исполнитель подтвердил, что изменений не вносил. +// Задача отменяется. +func (h *Handler) HandleRevokeTaskNoChanges(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, taskID uint64, approvalID uint64) { + 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 + + task, err := h.ipc.Database.ApprovalTasks.GetApprovalTaskByIDDB(ctx, taskID) + if err != nil || task == nil { + sendText(bot, chatID, "⚠️ Задача не найдена.") + return + } + + cancelledStatus := "cancelled" + task.Status = &cancelledStatus + if _, _, err := h.ipc.Database.ApprovalTasks.UpdateApprovalTaskDB(ctx, nil, task); err != nil { + logrus.Errorf("HandleRevokeTaskNoChanges: UpdateApprovalTaskDB err=%v", err) + sendText(bot, chatID, "Ошибка при отмене задачи.") + return + } + + sendText(bot, chatID, fmt.Sprintf( + "✅ Подтверждено\n\n"+ + "Задача по заявке #%d отменена.\n"+ + "Спасибо за подтверждение.", + approvalID, + )) +} + +// HandleRevokeTaskHasChanges — исполнитель подтвердил, что уже вносил изменения. +// Исходная задача отменяется, создаётся задача на обращение изменений. +func (h *Handler) HandleRevokeTaskHasChanges(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, taskID uint64, approvalID uint64) { + 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 + + approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID) + if err != nil || approval == nil { + sendText(bot, chatID, "⚠️ Заявка не найдена.") + return + } + + task, err := h.ipc.Database.ApprovalTasks.GetApprovalTaskByIDDB(ctx, taskID) + if err != nil || task == nil { + sendText(bot, chatID, "⚠️ Задача не найдена.") + return + } + + // Отменяем исходную задачу + cancelledStatus := "cancelled" + task.Status = &cancelledStatus + if _, _, err := h.ipc.Database.ApprovalTasks.UpdateApprovalTaskDB(ctx, nil, task); err != nil { + logrus.Errorf("HandleRevokeTaskHasChanges: UpdateApprovalTaskDB err=%v", err) + } + + // Получаем исполнителя для уведомления + executor, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, cq.From.ID) + if err != nil || executor == nil { + sendText(bot, chatID, "⚠️ Пользователь не найден.") + return + } + + // Создаём задачу на обращение изменений + h.createReversalTask(bot, ctx, approval, task, executor) + + sendText(bot, chatID, fmt.Sprintf( + "📋 Создана задача на обращение изменений по заявке #%d.", + approvalID, + )) +} + +func (h *Handler) HandleExecutorAttachStart(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID, taskID uint64) { + ctx := context.Background() + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + + user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, cq.From.ID) + if err != nil || user == nil || user.ID == nil { + return + } + + approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID) + if err != nil || approval == nil { + sendText(bot, cq.Message.Chat.ID, "⚠️ Заявка не найдена.") + return + } + + // Создаём сессию прикрепления (как в HandleAttachFileStart) + session := &state.AttachmentSession{ + ApprovalID: approvalID, + TaskID: taskID, + Files: []state.FileAttachment{}, + Stage: "collecting", + } + h.States.SetAttachmentSession(ctx, cq.From.ID, session) //nolint:errcheck + + msg := tgbotapi.NewMessage(cq.Message.Chat.ID, + fmt.Sprintf( + "📎 Прикрепление файла к задаче по заявке #%d\n\n"+ + "Отправьте фото или документ.\n"+ + "Когда закончите — нажмите «Отправить».", + approvalID, + ), + ) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildAttachSessionKeyboard(approvalID, 0) + bot.Send(msg) //nolint:errcheck +} diff --git a/service/telegram_service/handlers/approval/handler_observer.go b/service/telegram_service/handlers/approval/handler_observer.go index f420e8a..16b9b04 100644 --- a/service/telegram_service/handlers/approval/handler_observer.go +++ b/service/telegram_service/handlers/approval/handler_observer.go @@ -18,8 +18,11 @@ func observerTopicKey(telegramID int64) string { return fmt.Sprintf("obs_topic:%d", telegramID) } -// HandleObservedApprovals — точка входа: список тем для наблюдателя. func (h *Handler) HandleObservedApprovals(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) { + h.HandleObservedApprovalsPage(bot, chatID, telegramID, 0) +} + +func (h *Handler) HandleObservedApprovalsPage(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, page int) { ctx := context.Background() user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) @@ -27,24 +30,50 @@ func (h *Handler) HandleObservedApprovals(bot *tgbotapi.BotAPI, chatID int64, te return } - isObserver, _ := h.ipc.Database.User.IsObserverDB(ctx, *user.ID) - if !isObserver { - return - } - - topics, err := h.getAllowedObserverTopics(ctx, user) + // Получаем все категории на которые у пользователя есть права наблюдателя + perms, err := h.ipc.Database.Permission.GetUserPermissionsDB(ctx, *user.ID, "observe") if err != nil { - logrus.Error("HandleObservedApprovals: getAllowedObserverTopics: ", err) - return - } - if len(topics) == 0 { - sendText(bot, chatID, "👁 Нет тем, доступных для наблюдения.") + logrus.Errorf("HandleObservedApprovalsPage: GetUserPermissionsDB err=%v", err) return } - msg := tgbotapi.NewMessage(chatID, "👁 Наблюдаемые согласования\n\nВыберите тему:") + if len(perms) == 0 { + sendText(bot, chatID, "У вас нет прав наблюдателя ни по одной теме.") + return + } + + // Собираем коды категорий + var visibleTopics []approvalflow.Topic + seenCodes := make(map[string]bool) + + for _, p := range perms { + if p.TopicCategoryID == nil { + continue + } + category, err := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *p.TopicCategoryID) + if err != nil || category == nil || category.Code == nil { + continue + } + if seenCodes[*category.Code] { + continue + } + seenCodes[*category.Code] = true + + topic, err := h.Registry.Get(*category.Code) + if err != nil { + continue + } + visibleTopics = append(visibleTopics, topic) + } + + if len(visibleTopics) == 0 { + sendText(bot, chatID, "Нет доступных тем для наблюдения.") + return + } + + msg := tgbotapi.NewMessage(chatID, "👁 Наблюдение за согласованиями\n\nВыберите тему:") msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildObserverTopicMenu(topics) + msg.ReplyMarkup = keyboard.BuildObserverTopicMenu(visibleTopics, page) bot.Send(msg) //nolint:errcheck } @@ -196,6 +225,10 @@ func (h *Handler) HandleObserverReminderCallback(bot *tgbotapi.BotAPI, cq *tgbot content = *approval.Content } + status := "" + if approval.Status != nil { + status = *approval.Status + } reminder := fmt.Sprintf( "🔔 Напоминание о заявке #%d\n\n"+ "👤 Инициатор: %s\n"+ @@ -203,9 +236,11 @@ func (h *Handler) HandleObserverReminderCallback(bot *tgbotapi.BotAPI, cq *tgbot "Заявка ожидает вашего решения.", approvalID, initiatorName, content, ) + files, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID) + reminderMsg := tgbotapi.NewMessage(*approver.TelegramID, reminder) reminderMsg.ParseMode = "HTML" - reminderMsg.ReplyMarkup = keyboard.BuildApproverDecision(approvalID) + reminderMsg.ReplyMarkup = keyboard.BuildApproverDecision(approvalID, status, len(files) > 0, len(files)) bot.Send(reminderMsg) //nolint:errcheck approverName := "согласующему" @@ -232,7 +267,7 @@ func (h *Handler) sendObserverTopicApprovals(bot *tgbotapi.BotAPI, ctx context.C } } - topic, _ := h.registry.Get(topicCode) + topic, _ := h.Registry.Get(topicCode) topicName := topicCode if topic != nil { topicName = topic.Name() @@ -292,7 +327,7 @@ func (h *Handler) getAllowedObserverTopics(ctx context.Context, user *typescore. } var result []approvalflow.Topic - for _, t := range h.registry.All() { + for _, t := range h.Registry.All() { category, err := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByCodeDB(ctx, t.Code()) if err != nil || category == nil || category.ID == nil { continue diff --git a/service/telegram_service/handlers/approval/handler_pending_comments.go b/service/telegram_service/handlers/approval/handler_pending_comments.go index fc626ee..ed8fd17 100644 --- a/service/telegram_service/handlers/approval/handler_pending_comments.go +++ b/service/telegram_service/handlers/approval/handler_pending_comments.go @@ -5,6 +5,7 @@ import ( "bitrix_balancer_api/telegram_service/state" "context" "fmt" + "strings" tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" "github.com/sirupsen/logrus" @@ -34,7 +35,7 @@ func (h *Handler) HandlePendingCommentInput(bot *tgbotapi.BotAPI, msg *tgbotapi. h.ipc.RedisClient.Del(ctx, rejectKey) //nolint:errcheck h.States.RemovePendingComment(ctx, telegramID, approvalID) //nolint:errcheck - h.HandleDecisionWithChat(bot, chatID, approvalID, false, msg.Text) + h.HandleDecisionWithChat(bot, msg.Chat.ID, msg.From.ID, approvalID, false, strings.TrimSpace(msg.Text)) return true } @@ -67,13 +68,15 @@ func (h *Handler) HandlePendingCommentsList(bot *tgbotapi.BotAPI, chatID int64, items, err := h.States.GetPendingComments(ctx, telegramID) if err != nil { - logrus.Errorf("HandlePendingCommentsList: err=%v", err) + logrus.Errorf("HandlePendingCommentsList: GetPendingComments err=%v", err) + sendText(bot, chatID, "Ошибка при получении отложенных согласований.") return } + + logrus.Infof("HandlePendingCommentsList: telegramID=%d items=%d", telegramID, len(items)) + if len(items) == 0 { - reply := tgbotapi.NewMessage(chatID, "✅ Нет заявок, ожидающих комментария.") - reply.ParseMode = "HTML" - bot.Send(reply) //nolint:errcheck + sendText(bot, chatID, "📭 Нет отложенных согласований.") return } diff --git a/service/telegram_service/handlers/approval/handler_report.go b/service/telegram_service/handlers/approval/handler_report.go index e483f15..ca9f11e 100644 --- a/service/telegram_service/handlers/approval/handler_report.go +++ b/service/telegram_service/handlers/approval/handler_report.go @@ -16,232 +16,6 @@ import ( "github.com/sirupsen/logrus" ) -// buildExcelReport — строит xlsx-файл и возвращает байты. -func (h *Handler) buildExcelReport(ctx context.Context, approvals []*typescore.Approval) ([]byte, error) { - f := excelize.NewFile() - sheet := "Согласования" - f.SetSheetName("Sheet1", sheet) - - // Заголовки - headers := []string{ - "ФИО инициатора", - "Тема согласования", - "Дата создания", - "Согласующие", - "Наблюдатели", - "Статус", - "Текст согласования", - "Отдел сотрудника", - "Комментарий", - } - - cols := []string{"A", "B", "C", "D", "E", "F", "G", "H", "I"} - - colWidths := map[string]float64{ - "A": 25, "B": 35, "C": 18, "D": 30, - "E": 30, "F": 16, "G": 40, "H": 25, "I": 30, - } - - // Стиль заголовка - headerStyle, _ := f.NewStyle(&excelize.Style{ - Font: &excelize.Font{Bold: true, Color: "FFFFFF"}, - Fill: excelize.Fill{Type: "pattern", Color: []string{"2E75B6"}, Pattern: 1}, - Border: []excelize.Border{ - {Type: "left", Color: "000000", Style: 1}, - {Type: "right", Color: "000000", Style: 1}, - {Type: "top", Color: "000000", Style: 1}, - {Type: "bottom", Color: "000000", Style: 1}, - }, - Alignment: &excelize.Alignment{Horizontal: "center", Vertical: "center", WrapText: true}, - }) - - // Стиль данных - dataStyle, _ := f.NewStyle(&excelize.Style{ - Border: []excelize.Border{ - {Type: "left", Color: "CCCCCC", Style: 1}, - {Type: "right", Color: "CCCCCC", Style: 1}, - {Type: "top", Color: "CCCCCC", Style: 1}, - {Type: "bottom", Color: "CCCCCC", Style: 1}, - }, - Alignment: &excelize.Alignment{Vertical: "center", WrapText: true}, - }) - - // Стиль отклонённых строк - rejectedStyle, _ := f.NewStyle(&excelize.Style{ - Fill: excelize.Fill{Type: "pattern", Color: []string{"FFE0E0"}, Pattern: 1}, - Border: []excelize.Border{ - {Type: "left", Color: "CCCCCC", Style: 1}, - {Type: "right", Color: "CCCCCC", Style: 1}, - {Type: "top", Color: "CCCCCC", Style: 1}, - {Type: "bottom", Color: "CCCCCC", Style: 1}, - }, - Alignment: &excelize.Alignment{Vertical: "center", WrapText: true}, - }) - - for col, width := range colWidths { - f.SetColWidth(sheet, col, col, width) //nolint:errcheck - } - - // Заголовки - for i, h := range headers { - cell := fmt.Sprintf("%s1", cols[i]) - f.SetCellValue(sheet, cell, h) //nolint:errcheck - f.SetCellStyle(sheet, cell, cell, headerStyle) //nolint:errcheck - } - f.SetRowHeight(sheet, 1, 36) //nolint:errcheck - - for rowIdx, a := range approvals { - row := rowIdx + 2 - - initiatorName := "" - if a.InitiatorID != nil { - if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *a.InitiatorID); u != nil && u.FullName != nil { - initiatorName = *u.FullName - } - } - - topicName := "" - if a.TopicID != nil { - if t, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *a.TopicID); t != nil && t.Name != nil { - topicName = *t.Name - } - } - - createdAt := "" - if a.CreatedAt != nil { - createdAt = a.CreatedAt.Format("02.01.2006 15:04") - } - - var approverParts []string - var commentFromStep string - steps, _, _ := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalStep{ApprovalID: a.ID}, - }) - // Сортируем по StepOrder - sort.Slice(steps, func(i, j int) bool { - if steps[i].StepOrder == nil || steps[j].StepOrder == nil { - return false - } - return *steps[i].StepOrder < *steps[j].StepOrder - }) - for _, s := range steps { - name := "" - // Сначала snapshot, если нет — тянем из БД - if s.ApproverNameSnapshot != nil && *s.ApproverNameSnapshot != "" { - name = *s.ApproverNameSnapshot - } else if s.ApproverID != nil { - if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *s.ApproverID); u != nil && u.FullName != nil { - name = *u.FullName - } - } - - if name != "" { - approverParts = append(approverParts, name) - } - - // Комментарий отклонения - if s.Status != nil && *s.Status == "rejected" && s.Comment != nil && *s.Comment != "" { - commentFromStep = *s.Comment - } - } - approversCell := strings.Join(approverParts, "\n") - - // Наблюдатели по категории темы - var observerParts []string - categoryCode := h.getTopicCodeByApproval(ctx, a) - if categoryCode != "" { - observers, _ := h.ipc.Database.User.GetObserversForCategoryDB(ctx, categoryCode) - for _, obs := range observers { - if obs.FullName != nil { - observerParts = append(observerParts, *obs.FullName) - } - } - } - observersCell := strings.Join(observerParts, "\n") - - // Статус - status := "—" - if a.Status != nil { - switch *a.Status { - case "pending": - status = "На согласовании" - case "approved": - status = "Согласовано" - case "rejected": - status = "Отклонено" - case "revoked": - status = "Отозвано" - } - } - - // Текст согласования - content := "" - if a.Content != nil { - content = *a.Content - } - - // Отдел - deptName := "" - if a.DepartmentID != nil { - if d, _ := h.ipc.Database.Department.GetDepartmentByIDDB(ctx, *a.DepartmentID); d != nil && d.Name != nil { - deptName = *d.Name - } - } - - // Комментарий только для отклонённых - comment := "" - if a.Status != nil && *a.Status == "rejected" { - comment = commentFromStep - } - - values := []interface{}{ - initiatorName, topicName, createdAt, - approversCell, observersCell, - status, content, deptName, comment, - } - - style := dataStyle - if a.Status != nil && *a.Status == "rejected" { - style = rejectedStyle - } - - for colIdx, val := range values { - cell := fmt.Sprintf("%s%d", cols[colIdx], row) - f.SetCellValue(sheet, cell, val) //nolint:errcheck - f.SetCellStyle(sheet, cell, cell, style) //nolint:errcheck - } - - // Высота строки зависит от числа согласующих - rowHeight := 20.0 - if len(approverParts) > 1 { - rowHeight = float64(len(approverParts)) * 18 - } - f.SetRowHeight(sheet, row, rowHeight) //nolint:errcheck - } - - // Автофильтр на все столбцы - lastCol := cols[len(headers)-1] - lastRow := len(approvals) + 1 - f.AutoFilter(sheet, //nolint:errcheck - fmt.Sprintf("A1:%s%d", lastCol, lastRow), - []excelize.AutoFilterOptions{}, - ) - - // Закрепить первую строку - f.SetPanes(sheet, &excelize.Panes{ //nolint:errcheck - Freeze: true, - YSplit: 1, - TopLeftCell: "A2", - ActivePane: "bottomLeft", - }) - - var buf bytes.Buffer - if err := f.Write(&buf); err != nil { - return nil, err - } - return buf.Bytes(), nil -} - // getReportCategoryCodes — объединяет категории согласующего и наблюдателя. func (h *Handler) getReportCategoryCodes(ctx context.Context, user *typescore.User) []string { seen := map[string]bool{} @@ -279,31 +53,32 @@ func (h *Handler) buildExcelApprovalsReport(ctx context.Context, approvals []*ty sheet := "Согласования" f.SetSheetName("Sheet1", sheet) - // Заголовки (добавлены колонки по задачам) headers := []string{ - "ФИО инициатора", - "Тема согласования", - "Дата создания", - "Согласующие", - "Наблюдатели", - "Статус", - "Текст согласования", - "Отдел сотрудника", - "Комментарий", - "Текст задачи", - "Исполнитель", - "Статус задачи", + "ФИО инициатора", // A + "Тема согласования", // B + "Дата создания", // C + "Согласующие", // D + "Наблюдатели", // E + "Статус", // F + "Текст согласования", // G + "Отдел сотрудника", // H + "Комментарии", // I + "Дата согласования", // J + "Текст задачи", // K + "Исполнитель", // L + "Статус задачи", // M + "Дата исполнения", // N } - cols := []string{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"} + cols := []string{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N"} colWidths := map[string]float64{ - "A": 25, "B": 35, "C": 18, "D": 30, + "A": 25, "B": 40, "C": 18, "D": 30, "E": 30, "F": 16, "G": 40, "H": 25, - "I": 30, "J": 40, "K": 25, "L": 18, + "I": 30, "J": 18, "K": 40, "L": 25, + "M": 18, "N": 18, } - // Стиль заголовка headerStyle, _ := f.NewStyle(&excelize.Style{ Font: &excelize.Font{Bold: true, Color: "FFFFFF"}, Fill: excelize.Fill{Type: "pattern", Color: []string{"2E75B6"}, Pattern: 1}, @@ -316,7 +91,6 @@ func (h *Handler) buildExcelApprovalsReport(ctx context.Context, approvals []*ty Alignment: &excelize.Alignment{Horizontal: "center", Vertical: "center", WrapText: true}, }) - // Стиль данных dataStyle, _ := f.NewStyle(&excelize.Style{ Border: []excelize.Border{ {Type: "left", Color: "CCCCCC", Style: 1}, @@ -327,7 +101,6 @@ func (h *Handler) buildExcelApprovalsReport(ctx context.Context, approvals []*ty Alignment: &excelize.Alignment{Vertical: "center", WrapText: true}, }) - // Стиль отклонённых строк rejectedStyle, _ := f.NewStyle(&excelize.Style{ Fill: excelize.Fill{Type: "pattern", Color: []string{"FFE0E0"}, Pattern: 1}, Border: []excelize.Border{ @@ -339,14 +112,24 @@ func (h *Handler) buildExcelApprovalsReport(ctx context.Context, approvals []*ty Alignment: &excelize.Alignment{Vertical: "center", WrapText: true}, }) + errorStyle, _ := f.NewStyle(&excelize.Style{ + Fill: excelize.Fill{Type: "pattern", Color: []string{"FFCCCC"}, Pattern: 1}, + Border: []excelize.Border{ + {Type: "left", Color: "CCCCCC", Style: 1}, + {Type: "right", Color: "CCCCCC", Style: 1}, + {Type: "top", Color: "CCCCCC", Style: 1}, + {Type: "bottom", Color: "CCCCCC", Style: 1}, + }, + Alignment: &excelize.Alignment{Vertical: "center", WrapText: true}, + }) + for col, width := range colWidths { f.SetColWidth(sheet, col, col, width) //nolint:errcheck } - // Заголовки - for i, h := range headers { + for i, header := range headers { cell := fmt.Sprintf("%s1", cols[i]) - f.SetCellValue(sheet, cell, h) //nolint:errcheck + f.SetCellValue(sheet, cell, header) //nolint:errcheck f.SetCellStyle(sheet, cell, cell, headerStyle) //nolint:errcheck } f.SetRowHeight(sheet, 1, 36) //nolint:errcheck @@ -363,8 +146,15 @@ func (h *Handler) buildExcelApprovalsReport(ctx context.Context, approvals []*ty topicName := "" if a.TopicID != nil { - if t, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *a.TopicID); t != nil && t.Name != nil { - topicName = *t.Name + if t, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *a.TopicID); t != nil { + if t.CategoryID != nil { + if c, _ := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *t.CategoryID); c != nil && c.Name != nil { + topicName = *c.Name + ": " + } + } + if t.Name != nil { + topicName += *t.Name + } } } @@ -375,10 +165,11 @@ func (h *Handler) buildExcelApprovalsReport(ctx context.Context, approvals []*ty var approverParts []string var commentFromStep string + lastApprovedAt := "" + steps, _, _ := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ Filtering: &typescore.ApprovalStep{ApprovalID: a.ID}, }) - // Сортируем по StepOrder sort.Slice(steps, func(i, j int) bool { if steps[i].StepOrder == nil || steps[j].StepOrder == nil { return false @@ -387,7 +178,6 @@ func (h *Handler) buildExcelApprovalsReport(ctx context.Context, approvals []*ty }) for _, s := range steps { name := "" - // Сначала snapshot, если нет — тянем из БД if s.ApproverNameSnapshot != nil && *s.ApproverNameSnapshot != "" { name = *s.ApproverNameSnapshot } else if s.ApproverID != nil { @@ -395,19 +185,18 @@ func (h *Handler) buildExcelApprovalsReport(ctx context.Context, approvals []*ty name = *u.FullName } } - if name != "" { approverParts = append(approverParts, name) } - - // Комментарий отклонения if s.Status != nil && *s.Status == "rejected" && s.Comment != nil && *s.Comment != "" { commentFromStep = *s.Comment } + if s.Status != nil && *s.Status == "approved" && s.ActedAt != nil { + lastApprovedAt = s.ActedAt.Format("02.01.2006 15:04") + } } approversCell := strings.Join(approverParts, "\n") - // Наблюдатели по категории темы var observerParts []string categoryCode := h.getTopicCodeByApproval(ctx, a) if categoryCode != "" { @@ -420,7 +209,6 @@ func (h *Handler) buildExcelApprovalsReport(ctx context.Context, approvals []*ty } observersCell := strings.Join(observerParts, "\n") - // Статус status := "—" if a.Status != nil { switch *a.Status { @@ -435,13 +223,11 @@ func (h *Handler) buildExcelApprovalsReport(ctx context.Context, approvals []*ty } } - // Текст согласования content := "" if a.Content != nil { content = *a.Content } - // Отдел deptName := "" if a.DepartmentID != nil { if d, _ := h.ipc.Database.Department.GetDepartmentByIDDB(ctx, *a.DepartmentID); d != nil && d.Name != nil { @@ -449,77 +235,146 @@ func (h *Handler) buildExcelApprovalsReport(ctx context.Context, approvals []*ty } } - // Комментарий только для отклонённых comment := "" if a.Status != nil && *a.Status == "rejected" { comment = commentFromStep } - // Получаем задачи для этого согласования - tasks, _, _ := h.ipc.Database.ApprovalTasks.GetApprovalTasksListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalTask{ApprovalID: a.ID}, - }) + taskText := "Не предусмотрено" + executorName := "Не предусмотрено" + taskStatus := "Не предусмотрено" + taskCompletedAt := "" + hasTaskError := false - var taskTexts []string - var executorNames []string - var taskStatuses []string + if a.TopicID != nil { + topicExecutors, _ := h.ipc.Database.ApprovalTopicExecutor.GetExecutorsByTopicIDDB(ctx, *a.TopicID) - for _, task := range tasks { - if task.TaskText != nil { - taskTexts = append(taskTexts, *task.TaskText) + if len(topicExecutors) == 0 { + taskText = "Не предусмотрено" + executorName = "Не предусмотрено" + taskStatus = "Не предусмотрено" } else { - taskTexts = append(taskTexts, "—") - } + tasks, _, _ := h.ipc.Database.ApprovalTasks.GetApprovalTasksListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalTask{ApprovalID: a.ID}, + }) - executorName := "" - if task.ExecutorID != nil { - if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *task.ExecutorID); u != nil && u.FullName != nil { - executorName = *u.FullName + if len(tasks) == 0 { + if a.Status == nil { + taskText = "Не предусмотрено" + executorName = "Не предусмотрено" + taskStatus = "Не предусмотрено" + } else { + switch *a.Status { + case "approved": + taskText = "Ошибка: задачи не созданы" + executorName = "Ошибка" + taskStatus = "Ошибка" + hasTaskError = true + case "pending": + taskText = "Ожидает согласования" + executorName = "Ожидает согласования" + taskStatus = "Ожидает согласования" + case "rejected": + taskText = "Не выполнено (заявка отклонена)" + executorName = "Не выполнено (заявка отклонена)" + taskStatus = "Не выполнено (заявка отклонена)" + case "revoked": + taskText = "Не выполнено (заявка отозвана)" + executorName = "Не выполнено (заявка отозвана)" + taskStatus = "Не выполнено (заявка отозвана)" + default: + taskText = "Не предусмотрено" + executorName = "Не предусмотрено" + taskStatus = "Не предусмотрено" + } + } + } else { + var taskTexts []string + var executorNames []string + var taskStatuses []string + + sort.Slice(tasks, func(i, j int) bool { + if tasks[i].StepOrder == nil || tasks[j].StepOrder == nil { + return false + } + return *tasks[i].StepOrder < *tasks[j].StepOrder + }) + + for _, task := range tasks { + if task.TaskText != nil { + taskTexts = append(taskTexts, *task.TaskText) + } else { + taskTexts = append(taskTexts, "—") + } + + eName := "" + if task.ExecutorID != nil { + if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *task.ExecutorID); u != nil && u.FullName != nil { + eName = *u.FullName + } + } + executorNames = append(executorNames, eName) + + ts := "—" + if task.Status != nil { + switch *task.Status { + case "pending": + ts = "В работе" + case "waiting": + ts = "Ожидает" + case "completed": + ts = "Выполнено" + case "cancelled": + ts = "Отменено" + } + } + taskStatuses = append(taskStatuses, ts) + + if taskCompletedAt == "" && task.CompletedAt != nil { + taskCompletedAt = task.CompletedAt.Format("02.01.2006 15:04") + } + } + + taskText = strings.Join(taskTexts, "\n") + executorName = strings.Join(executorNames, "\n") + taskStatus = strings.Join(taskStatuses, "\n") } } - executorNames = append(executorNames, executorName) - - taskStatus := "—" - if task.Status != nil { - switch *task.Status { - case "pending": - taskStatus = "В работе" - case "completed": - taskStatus = "Выполнено" - case "cancelled": - taskStatus = "Отменено" - } - } - taskStatuses = append(taskStatuses, taskStatus) } - taskText := strings.Join(taskTexts, "\n") - executorName := strings.Join(executorNames, "\n") - taskStatus := strings.Join(taskStatuses, "\n") - values := []interface{}{ initiatorName, topicName, createdAt, approversCell, observersCell, status, content, deptName, comment, + lastApprovedAt, taskText, executorName, taskStatus, + taskCompletedAt, } + // Базовый стиль строки style := dataStyle if a.Status != nil && *a.Status == "rejected" { style = rejectedStyle } + // 🚀 Заполняем ячейки с индивидуальными стилями для задач for colIdx, val := range values { cell := fmt.Sprintf("%s%d", cols[colIdx], row) - f.SetCellValue(sheet, cell, val) //nolint:errcheck - f.SetCellStyle(sheet, cell, cell, style) //nolint:errcheck + f.SetCellValue(sheet, cell, val) //nolint:errcheck + + // 🚀 Для ячеек задач (K, L, M) применяем errorStyle при ошибке + cellStyle := style + if hasTaskError && colIdx >= 10 && colIdx <= 12 { + cellStyle = errorStyle + } + f.SetCellStyle(sheet, cell, cell, cellStyle) //nolint:errcheck } - // Высота строки зависит от числа согласующих и задач + // Высота строки rowHeight := 20.0 maxLines := len(approverParts) - if len(taskTexts) > maxLines { - maxLines = len(taskTexts) + if len(strings.Split(taskText, "\n")) > maxLines { + maxLines = len(strings.Split(taskText, "\n")) } if maxLines > 1 { rowHeight = float64(maxLines) * 18 @@ -527,7 +382,6 @@ func (h *Handler) buildExcelApprovalsReport(ctx context.Context, approvals []*ty f.SetRowHeight(sheet, row, rowHeight) //nolint:errcheck } - // Автофильтр на все столбцы lastCol := cols[len(headers)-1] lastRow := len(approvals) + 1 f.AutoFilter(sheet, //nolint:errcheck @@ -535,227 +389,6 @@ func (h *Handler) buildExcelApprovalsReport(ctx context.Context, approvals []*ty []excelize.AutoFilterOptions{}, ) - // Закрепить первую строку - f.SetPanes(sheet, &excelize.Panes{ //nolint:errcheck - Freeze: true, - YSplit: 1, - TopLeftCell: "A2", - ActivePane: "bottomLeft", - }) - - var buf bytes.Buffer - if err := f.Write(&buf); err != nil { - return nil, err - } - return buf.Bytes(), nil -} - -// buildExcelTasksReport — строит xlsx-файл отчёта по задачам и возвращает байты. -func (h *Handler) buildExcelTasksReport(ctx context.Context, tasks []*typescore.ApprovalTask) ([]byte, error) { - f := excelize.NewFile() - sheet := "Задачи" - f.SetSheetName("Sheet1", sheet) - - // Заголовки - headers := []string{ - "Текст задачи", - "Исполнитель", - "Статус задачи", - "Дата создания задачи", - "Дата завершения", - "Тема согласования", - "ФИО инициатора", - "Дата создания согласования", - "Статус согласования", - "Текст согласования", - "Отдел", - } - - cols := []string{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"} - - colWidths := map[string]float64{ - "A": 40, "B": 25, "C": 18, "D": 18, - "E": 18, "F": 35, "G": 25, "H": 18, - "I": 20, "J": 40, "K": 25, - } - - // Стиль заголовка - headerStyle, _ := f.NewStyle(&excelize.Style{ - Font: &excelize.Font{Bold: true, Color: "FFFFFF"}, - Fill: excelize.Fill{Type: "pattern", Color: []string{"4472C4"}, Pattern: 1}, - Border: []excelize.Border{ - {Type: "left", Color: "000000", Style: 1}, - {Type: "right", Color: "000000", Style: 1}, - {Type: "top", Color: "000000", Style: 1}, - {Type: "bottom", Color: "000000", Style: 1}, - }, - Alignment: &excelize.Alignment{Horizontal: "center", Vertical: "center", WrapText: true}, - }) - - // Стиль данных - dataStyle, _ := f.NewStyle(&excelize.Style{ - Border: []excelize.Border{ - {Type: "left", Color: "CCCCCC", Style: 1}, - {Type: "right", Color: "CCCCCC", Style: 1}, - {Type: "top", Color: "CCCCCC", Style: 1}, - {Type: "bottom", Color: "CCCCCC", Style: 1}, - }, - Alignment: &excelize.Alignment{Vertical: "center", WrapText: true}, - }) - - // Стиль выполненных задач - completedStyle, _ := f.NewStyle(&excelize.Style{ - Fill: excelize.Fill{Type: "pattern", Color: []string{"E2EFDA"}, Pattern: 1}, - Border: []excelize.Border{ - {Type: "left", Color: "CCCCCC", Style: 1}, - {Type: "right", Color: "CCCCCC", Style: 1}, - {Type: "top", Color: "CCCCCC", Style: 1}, - {Type: "bottom", Color: "CCCCCC", Style: 1}, - }, - Alignment: &excelize.Alignment{Vertical: "center", WrapText: true}, - }) - - for col, width := range colWidths { - f.SetColWidth(sheet, col, col, width) //nolint:errcheck - } - - // Заголовки - for i, h := range headers { - cell := fmt.Sprintf("%s1", cols[i]) - f.SetCellValue(sheet, cell, h) //nolint:errcheck - f.SetCellStyle(sheet, cell, cell, headerStyle) //nolint:errcheck - } - f.SetRowHeight(sheet, 1, 36) //nolint:errcheck - - for rowIdx, task := range tasks { - row := rowIdx + 2 - - // Текст задачи - taskText := "" - if task.TaskText != nil { - taskText = *task.TaskText - } - - // Исполнитель - executorName := "" - if task.ExecutorID != nil { - if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *task.ExecutorID); u != nil && u.FullName != nil { - executorName = *u.FullName - } - } - - // Статус задачи - taskStatus := "—" - if task.Status != nil { - switch *task.Status { - case "pending": - taskStatus = "В работе" - case "completed": - taskStatus = "Выполнено" - case "cancelled": - taskStatus = "Отменено" - } - } - - // Дата создания задачи - taskCreatedAt := "" - if task.CreatedAt != nil { - taskCreatedAt = task.CreatedAt.Format("02.01.2006 15:04") - } - - // Дата завершения - taskCompletedAt := "" - if task.CompletedAt != nil { - taskCompletedAt = task.CompletedAt.Format("02.01.2006 15:04") - } - - // Получаем согласование - var approval *typescore.Approval - if task.ApprovalID != nil { - approval, _ = h.ipc.Database.Approval.GetApprovalByIDDB(ctx, *task.ApprovalID) - } - - // Тема согласования - topicName := "" - if approval != nil && approval.TopicID != nil { - if t, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID); t != nil && t.Name != nil { - topicName = *t.Name - } - } - - // ФИО инициатора - initiatorName := "" - if approval != nil && approval.InitiatorID != nil { - if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID); u != nil && u.FullName != nil { - initiatorName = *u.FullName - } - } - - // Дата создания согласования - approvalCreatedAt := "" - if approval != nil && approval.CreatedAt != nil { - approvalCreatedAt = approval.CreatedAt.Format("02.01.2006 15:04") - } - - // Статус согласования - approvalStatus := "—" - if approval != nil && approval.Status != nil { - switch *approval.Status { - case "pending": - approvalStatus = "На согласовании" - case "approved": - approvalStatus = "Согласовано" - case "rejected": - approvalStatus = "Отклонено" - case "revoked": - approvalStatus = "Отозвано" - } - } - - // Текст согласования - approvalContent := "" - if approval != nil && approval.Content != nil { - approvalContent = *approval.Content - } - - // Отдел - deptName := "" - if approval != nil && approval.DepartmentID != nil { - if d, _ := h.ipc.Database.Department.GetDepartmentByIDDB(ctx, *approval.DepartmentID); d != nil && d.Name != nil { - deptName = *d.Name - } - } - - values := []interface{}{ - taskText, executorName, taskStatus, - taskCreatedAt, taskCompletedAt, - topicName, initiatorName, approvalCreatedAt, - approvalStatus, approvalContent, deptName, - } - - style := dataStyle - if task.Status != nil && *task.Status == "completed" { - style = completedStyle - } - - for colIdx, val := range values { - cell := fmt.Sprintf("%s%d", cols[colIdx], row) - f.SetCellValue(sheet, cell, val) //nolint:errcheck - f.SetCellStyle(sheet, cell, cell, style) //nolint:errcheck - } - - f.SetRowHeight(sheet, row, 20) //nolint:errcheck - } - - // Автофильтр на все столбцы - lastCol := cols[len(headers)-1] - lastRow := len(tasks) + 1 - f.AutoFilter(sheet, //nolint:errcheck - fmt.Sprintf("A1:%s%d", lastCol, lastRow), - []excelize.AutoFilterOptions{}, - ) - - // Закрепить первую строку f.SetPanes(sheet, &excelize.Panes{ //nolint:errcheck Freeze: true, YSplit: 1, @@ -773,6 +406,7 @@ func (h *Handler) buildExcelTasksReport(ctx context.Context, tasks []*typescore. const reportDateLayout = "02.01.2006" // HandleReportMenu — первый шаг: показываем выбор типа отчёта. +// HandleReportMenu — сразу показываем выбор периода (тип отчёта один — согласования). func (h *Handler) HandleReportMenu(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) { ctx := context.Background() @@ -781,7 +415,6 @@ func (h *Handler) HandleReportMenu(bot *tgbotapi.BotAPI, chatID int64, telegramI return } - // Проверяем что у пользователя есть роль согласующего или наблюдателя isApprover, _ := h.ipc.Database.User.IsApproverDB(ctx, *user.ID) isObserver, _ := h.ipc.Database.User.IsObserverDB(ctx, *user.ID) isDirector, _ := h.ipc.Database.User.IsDirectorDB(ctx, *user.ID) @@ -791,41 +424,13 @@ func (h *Handler) HandleReportMenu(bot *tgbotapi.BotAPI, chatID int64, telegramI return } - // Сбрасываем предыдущий фильтр h.States.ClearReport(ctx, telegramID) //nolint:errcheck msg := tgbotapi.NewMessage(chatID, - "📊 Выгрузка отчёта\n\n"+ - "Выберите тип отчёта:") + "📊 Выгрузка отчёта по согласованиям\n\n"+ + "Выберите период или выгрузите за всё время:") msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildReportTypeMenu() - bot.Send(msg) //nolint:errcheck -} - -// HandleReportTypeSelection — выбор типа отчёта (согласования или задачи). -func (h *Handler) HandleReportTypeSelection(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, reportType string) { - ctx := context.Background() - telegramID := cq.From.ID - chatID := cq.Message.Chat.ID - - bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck - bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck - - // Сохраняем тип отчёта в state - h.States.SetReport(ctx, telegramID, &state.ReportFilterState{ //nolint:errcheck - ReportType: reportType, - }) - - title := "согласований" - if reportType == "tasks" { - title = "задач" - } - - msg := tgbotapi.NewMessage(chatID, - fmt.Sprintf("📊 Выгрузка отчёта %s\n\n"+ - "Выберите период или выгрузите за всё время:", title)) - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildReportFilterMenu() + msg.ReplyMarkup = keyboard.BuildReportDateToMenu() bot.Send(msg) //nolint:errcheck } @@ -977,63 +582,32 @@ func (h *Handler) generateAndSendReport( var fileName string var caption string - if reportType == "tasks" { - // Отчёт по задачам - tasks, err := h.getTasksForReport(ctx, user, isDirector, dateFrom, dateTo) - if err != nil { - logrus.Errorf("generateAndSendReport: getTasksForReport err=%v", err) - sendText(bot, chatID, "Ошибка при получении данных. Попробуйте позже.") - return - } - - if len(tasks) == 0 { - sendText(bot, chatID, "📭 Нет задач за выбранный период.") - return - } - - buf, err = h.buildExcelTasksReport(ctx, tasks) - if err != nil { - logrus.Errorf("generateAndSendReport: buildExcelTasksReport err=%v", err) - sendText(bot, chatID, "Ошибка при формировании файла. Попробуйте позже.") - return - } - - now := time.Now() - fileName = fmt.Sprintf("Задачи %s %s.xlsx", - now.Format("02.01.2006"), - now.Format("15-04"), - ) - caption = fmt.Sprintf("📋 Отчёт по задачам сформирован: %s %s", now.Format("02.01.2006"), now.Format("15:04")) - - } else { - // Отчёт по согласованиям (по умолчанию) - approvals, err := h.getApprovalsForReport(ctx, user, isDirector, dateFrom, dateTo) - if err != nil { - logrus.Errorf("generateAndSendReport: getApprovalsForReport err=%v", err) - sendText(bot, chatID, "Ошибка при получении данных. Попробуйте позже.") - return - } - - if len(approvals) == 0 { - sendText(bot, chatID, "📭 Нет согласований за выбранный период.") - return - } - - buf, err = h.buildExcelApprovalsReport(ctx, approvals) - if err != nil { - logrus.Errorf("generateAndSendReport: buildExcelApprovalsReport err=%v", err) - sendText(bot, chatID, "Ошибка при формировании файла. Попробуйте позже.") - return - } - - now := time.Now() - fileName = fmt.Sprintf("Согласования %s %s.xlsx", - now.Format("02.01.2006"), - now.Format("15-04"), - ) - caption = fmt.Sprintf("📊 Отчёт по согласованиям сформирован: %s %s", now.Format("02.01.2006"), now.Format("15:04")) + approvals, err := h.getApprovalsForReport(ctx, user, isDirector, dateFrom, dateTo) + if err != nil { + logrus.Errorf("generateAndSendReport: getApprovalsForReport err=%v", err) + sendText(bot, chatID, "Ошибка при получении данных. Попробуйте позже.") + return } + if len(approvals) == 0 { + sendText(bot, chatID, "📭 Нет согласований за выбранный период.") + return + } + + buf, err = h.buildExcelApprovalsReport(ctx, approvals) + if err != nil { + logrus.Errorf("generateAndSendReport: buildExcelApprovalsReport err=%v", err) + sendText(bot, chatID, "Ошибка при формировании файла. Попробуйте позже.") + return + } + + now := time.Now() + fileName = fmt.Sprintf("Согласования %s %s.xlsx", + now.Format("02.01.2006"), + now.Format("15-04"), + ) + caption = fmt.Sprintf("📊 Отчёт по согласованиям сформирован: %s %s", now.Format("02.01.2006"), now.Format("15:04")) + fileBytes := tgbotapi.FileBytes{Name: fileName, Bytes: buf} doc := tgbotapi.NewDocument(chatID, fileBytes) doc.Caption = caption @@ -1065,24 +639,3 @@ func (h *Handler) getApprovalsForReport( return h.ipc.Database.Approval.GetApprovalsForReportDB(ctx, filter) } - -// getTasksForReport — получение задач для отчёта. -func (h *Handler) getTasksForReport( - ctx context.Context, - user *typescore.User, - isDirector bool, - dateFrom *time.Time, - dateTo *time.Time, -) ([]*typescore.ApprovalTask, error) { - filter := typescore.TaskReportFilter{ - AllAccess: isDirector, - DateFrom: dateFrom, - DateTo: dateTo, - } - - if !isDirector { - filter.UserID = user.ID - } - - return h.ipc.Database.ApprovalTasks.GetTasksForReportDB(ctx, filter) -} diff --git a/service/telegram_service/handlers/approval/helper.go b/service/telegram_service/handlers/approval/helper.go index 81dfe6e..fb98f25 100644 --- a/service/telegram_service/handlers/approval/helper.go +++ b/service/telegram_service/handlers/approval/helper.go @@ -22,7 +22,7 @@ func sendText(bot *tgbotapi.BotAPI, chatID int64, text string) { // submitApproval создаёт запись в БД и уведомляет согласующих. func (h *Handler) submitApproval(ctx context.Context, bot *tgbotapi.BotAPI, telegramID int64, flowState *state.ApprovalFlowState) (*typescore.Approval, error) { - topic, err := h.registry.Get(flowState.TopicCode) + topic, err := h.Registry.Get(flowState.TopicCode) if err != nil { return nil, err } @@ -98,11 +98,16 @@ func (h *Handler) submitApproval(ctx context.Context, bot *tgbotapi.BotAPI, tele return nil, fmt.Errorf("created approval is nil or has no ID") } - // Сохраняем файлы если есть for _, f := range flowState.Files { - f := f // захват переменной + f := f base64Copy := f.Base64 nameCopy := f.FileName + + if base64Copy == "" || nameCopy == "" { + logrus.Warnf("submitApproval: skipping empty file name=%q base64_len=%d", nameCopy, len(base64Copy)) + continue + } + file := &typescore.ApprovalFile{ ApprovalID: created.ID, FileBase64: &base64Copy, @@ -110,8 +115,10 @@ func (h *Handler) submitApproval(ctx context.Context, bot *tgbotapi.BotAPI, tele AttachedByID: initiator.ID, } if _, _, err := h.ipc.Database.ApprovalFile.CreateApprovalFileDB(ctx, nil, file); err != nil { - logrus.Errorf("submitApproval: CreateApprovalFileDB err=%v", err) - // Не фатально — продолжаем, заявка уже создана + logrus.Errorf("submitApproval: CreateApprovalFileDB name=%s err=%v", nameCopy, err) + } else { + logrus.Infof("submitApproval: saved file=%s approvalID=%d attachedByID=%d", + nameCopy, *created.ID, *initiator.ID) } } @@ -159,81 +166,69 @@ func (h *Handler) submitApproval(ctx context.Context, bot *tgbotapi.BotAPI, tele } if len(approvers) == 0 { - logrus.Warnf("submitApproval: no approvers found for userID=%d deptID=%d", *initiator.ID, *initiator.DepartmentID) + logrus.Warnf("submitApproval: no approvers found for userID=%d deptID=%d topicID=%d", + *initiator.ID, *initiator.DepartmentID, *approvalTopic.ID) - approvedStatus := "approved" - created.Status = &approvedStatus - if _, _, err := h.ipc.Database.Approval.UpdateApprovalDB(ctx, nil, created); err != nil { - logrus.Errorf("submitApproval: auto-approve UpdateApprovalDB err=%v", err) - } + h.ipc.Database.Approval.DeleteApprovalDB(ctx, created) //nolint:errcheck + return nil, fmt.Errorf("⚠️ Для вас в данной теме не настроены согласующие. Пожалуйста, обратитесь к руководителю с просьбой о настройке прав в системе согласований") + } - if initiator.TelegramID != nil { - tName := "" - if approvalTopic.Name != nil { - tName = *approvalTopic.Name - } - text := fmt.Sprintf( - "✅ Заявка #%d автоматически согласована\n\n"+ - "📋 Тема: %s\n"+ - "📝 Текст: %s\n\n"+ - "Согласующий не назначен — заявка принята автоматически.", - *created.ID, tName, content, - ) - msg := tgbotapi.NewMessage(*initiator.TelegramID, text) - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildRevokeButton(*created.ID) - bot.Send(msg) //nolint:errcheck - } + // === НОВЫЙ БЛОК: ГРУППИРОВКА ПО ПРИОРИТЕТУ === + priorityGroups := make(map[int][]*typescore.User) - notifier := NewNotifier(h.ipc, topic) - - directors, _ := h.ipc.Database.User.GetDirectorsDB(ctx) - for _, director := range directors { - if director.TelegramID != nil { - notifier.NotifyDirector(bot, director, initiator, created, flowState.Collected) - } - } - - observers, _ := h.ipc.Database.User.GetObserversForCategoryDB(ctx, flowState.TopicCode) - for _, obs := range observers { - if obs.TelegramID != nil { - notifier.NotifyObserversNewApproval(bot, []*typescore.User{obs}, initiator, created, flowState.Collected) - } - } - - return created, nil + if approvalTopic.ApprovalMode != nil { + logrus.Infof("submitApproval: approvalMode=%s for topicID=%d", *approvalTopic.ApprovalMode, *approvalTopic.ID) + } else { + logrus.Warnf("submitApproval: approvalMode is NIL for topicID=%d — будет использован sequential!", *approvalTopic.ID) } for i, approver := range approvers { - if approver.ID == nil { - logrus.Warnf("submitApproval: approver.ID is nil at index=%d", i) + p := i + if approvalTopic.ApprovalMode != nil && *approvalTopic.ApprovalMode == "any_of" { + p = 0 + } + priorityGroups[p] = append(priorityGroups[p], approver) + } + + for p, group := range priorityGroups { + var ids []string + for _, a := range group { + if a.ID != nil { + ids = append(ids, fmt.Sprintf("%d", *a.ID)) + } + } + logrus.Infof("submitApproval: priorityGroup[%d] contains approvers: %s (count=%d)", p, strings.Join(ids, ","), len(group)) + } + + stepOrder := 0 + for priority := 0; priority <= len(priorityGroups); priority++ { + group, ok := priorityGroups[priority] + if !ok { continue } + for _, approver := range group { + if approver.ID == nil { + continue + } + stepStatus := "waiting" + if priority == 0 { + stepStatus = "pending" // первая группа активна сразу + } + order := stepOrder + approverName := "" + if approver.FullName != nil { + approverName = *approver.FullName + } - order := i - stepStatus := "waiting" - if i == 0 { - stepStatus = "pending" - } - - // Снимок имени и отдела согласующего - approverName := "" - if approver.FullName != nil { - approverName = *approver.FullName - } - approverDept := "" - - step := &typescore.ApprovalStep{ - ApprovalID: created.ID, - ApproverID: approver.ID, - StepOrder: &order, - Status: &stepStatus, - ApproverNameSnapshot: &approverName, - ApproverDepartmentSnapshot: &approverDept, - } - - if _, _, err := h.ipc.Database.ApprovalStep.CreateApprovalStepDB(ctx, nil, step); err != nil { - logrus.Errorf("submitApproval: CreateApprovalStepDB err=%v", err) + step := &typescore.ApprovalStep{ + ApprovalID: created.ID, + ApproverID: approver.ID, + StepOrder: &order, + Status: &stepStatus, + ApproverNameSnapshot: &approverName, + } + h.ipc.Database.ApprovalStep.CreateApprovalStepDB(ctx, nil, step) //nolint:errcheck + stepOrder++ } } @@ -242,73 +237,61 @@ func (h *Handler) submitApproval(ctx context.Context, bot *tgbotapi.BotAPI, tele h.saveSelectedObservers(ctx, *created.ID, *initiator.ID, flowState.SelectedObserverIDs) } - // Уведомляем первого согласующего (или делегата) - firstApprover := approvers[0] - if firstApprover.TelegramID == nil { - logrus.Warnf("submitApproval: firstApprover.TelegramID is nil, userID=%d", *firstApprover.ID) - return created, nil - } + // === НОВЫЙ БЛОК: УВЕДОМЛЕНИЕ ВСЕХ ИЗ ПЕРВОЙ ГРУППЫ === + firstGroup := priorityGroups[0] + notifier := NewNotifier(h.ipc, topic) - // Проверяем делегирование - if approvalTopic.CategoryID != nil { - // Сначала проверяем делегирование конкретной темы - if delegations, _, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalDelegation{ - IsActive: utilscore.PointerToBool(true), - TopicID: approvalTopic.ID, - }}); err == nil && len(delegations) > 0 { - for _, deleg := range delegations { - if deleg.DelegatorID != nil && *deleg.DelegatorID == *firstApprover.ID && deleg.DelegateID != nil { - delegate, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *deleg.DelegateID) - if delegate != nil && delegate.TelegramID != nil { + for _, approver := range firstGroup { + actualApprover := approver - firstApprover = delegate - break - } - } + if actualApprover.TelegramID == nil { + if actualApprover.ID != nil { + logrus.Warnf("submitApproval: approver.TelegramID is nil, userID=%d", *actualApprover.ID) } - } else { - // Проверяем делегирование всей категории + continue + } + + // Проверяем делегирование для каждого согласующего + if approvalTopic.CategoryID != nil { if delegations, _, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{ Filtering: &typescore.ApprovalDelegation{ - IsActive: utilscore.PointerToBool(true), - CategoryID: approvalTopic.CategoryID, + IsActive: utilscore.PointerToBool(true), + TopicID: approvalTopic.ID, }}); err == nil && len(delegations) > 0 { for _, deleg := range delegations { - if deleg.DelegatorID != nil && *deleg.DelegatorID == *firstApprover.ID && deleg.DelegateID != nil { + if deleg.DelegatorID != nil && *deleg.DelegatorID == *actualApprover.ID && deleg.DelegateID != nil { delegate, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *deleg.DelegateID) if delegate != nil && delegate.TelegramID != nil { - firstApprover = delegate + actualApprover = delegate break } } } + } else { + if delegations, _, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalDelegation{ + IsActive: utilscore.PointerToBool(true), + CategoryID: approvalTopic.CategoryID, + }}); err == nil && len(delegations) > 0 { + for _, deleg := range delegations { + if deleg.DelegatorID != nil && *deleg.DelegatorID == *actualApprover.ID && deleg.DelegateID != nil { + delegate, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *deleg.DelegateID) + if delegate != nil && delegate.TelegramID != nil { + actualApprover = delegate + break + } + } + } + } } } - } - 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) - } else if len(observers) > 0 { - 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) - } + notifier.NotifyApprover(bot, actualApprover, initiator, created, flowState.Collected) } return created, nil } -// getTopicCodeByApproval возвращает category code по заявке — для получения Topic из реестра. func (h *Handler) getTopicCodeByApproval(ctx context.Context, approval *typescore.Approval) string { if approval.TopicID == nil { return "" @@ -318,13 +301,36 @@ func (h *Handler) getTopicCodeByApproval(ctx context.Context, approval *typescor return "" } category, err := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *topic.CategoryID) - if err != nil || category == nil { + if err != nil || category == nil || category.Code == nil { return "" } - if category.Code == nil { - return "" + + categoryCode := *category.Code + + _, err = h.Registry.Get(categoryCode) + if err == nil { + return categoryCode } - return *category.Code + + absenceCategories := map[string]bool{ + "timeoff": true, "vacation": true, "sickleave": true, + } + if absenceCategories[categoryCode] { + return "absence" + } + + return categoryCode +} + +func (h *Handler) getTopicNameByApproval(ctx context.Context, approval *typescore.Approval) string { + if approval.TopicID == nil { + return "—" + } + topic, err := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID) + if err != nil || topic == nil || topic.Name == nil { + return "—" + } + return *topic.Name } // getCollectedFromApproval восстанавливает map collected из сохранённого контента заявки. @@ -346,7 +352,34 @@ func (h *Handler) getCollectedFromApproval(ctx context.Context, approval *typesc if topic.TimeType != nil { collected["time_type"] = *topic.TimeType } + if topic.Instructions != nil && *topic.Instructions != "" { + collected["instructions"] = *topic.Instructions + } } + + if approval.Metadata != nil { + if meta, err := typescore.ParseApprovalMetadata(approval.Metadata); err == nil && meta != nil { + if meta.Region != "" { + collected["region"] = meta.Region + } + if meta.ChangeType != "" { + collected["change_type"] = meta.ChangeType + } + + if len(meta.SelectedSystems) > 0 { + systemsStr := strings.Join(meta.SelectedSystems, ", ") + collected["target_system"] = systemsStr + collected["target_systems"] = systemsStr + collected["systems"] = systemsStr + collected["selected_systems"] = systemsStr + } + + for k, v := range meta.Extra { + collected[k] = v + } + } + } + return collected } @@ -361,7 +394,6 @@ func (h *Handler) getAllowedTopicCodes(ctx context.Context, user *typescore.User if err != nil { return nil, err } - logrus.Infof("getAllowedTopicCodes: userID=%d perms count=%d", *user.ID, len(perms)) if len(perms) == 0 { return allowed, nil @@ -372,16 +404,13 @@ func (h *Handler) getAllowedTopicCodes(ctx context.Context, user *typescore.User for _, p := range perms { if p.TopicCategoryID != nil { allowedCategoryIDs[*p.TopicCategoryID] = true - logrus.Infof("getAllowedTopicCodes: allowed category_id=%d", *p.TopicCategoryID) } if p.TopicID != nil { allowedTopicIDs[*p.TopicID] = true } } - for _, t := range h.registry.All() { - logrus.Infof("getAllowedTopicCodes: checking topic code=%s", t.Code()) - + for _, t := range h.Registry.All() { category, err := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByCodeDB(ctx, t.Code()) if err != nil { logrus.Warnf("getAllowedTopicCodes: GetApprovalTopicCategoryByCodeDB err=%v", err) @@ -391,9 +420,36 @@ func (h *Handler) getAllowedTopicCodes(ctx context.Context, user *typescore.User logrus.Warnf("getAllowedTopicCodes: category not found for code=%s", t.Code()) continue } - logrus.Infof("getAllowedTopicCodes: category found id=%d code=%s", *category.ID, *category.Code) - logrus.Infof("getAllowedTopicCodes: allowedCategoryIDs=%v match=%v", allowedCategoryIDs, allowedCategoryIDs[*category.ID]) + if !allowed[t.Code()] && t.Code() == "absence" { + childCodes := []string{"timeoff", "vacation", "sickleave"} + for _, childCode := range childCodes { + childCategory, err := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByCodeDB(ctx, childCode) + if err != nil || childCategory == nil || childCategory.ID == nil { + continue + } + if allowedCategoryIDs[*childCategory.ID] { + allowed[t.Code()] = true + break + } + // Или по конкретным подтемам + childTopics, _, err := h.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalTopic{CategoryID: childCategory.ID}, + }) + if err != nil { + continue + } + for _, ct := range childTopics { + if ct.ID != nil && allowedTopicIDs[*ct.ID] { + allowed[t.Code()] = true + break + } + } + if allowed[t.Code()] { + break + } + } + } if allowedCategoryIDs[*category.ID] { allowed[t.Code()] = true continue @@ -460,12 +516,9 @@ func (h *Handler) filterNodesByAccess(ctx context.Context, telegramID int64, nod return filtered } -// showFileStatus удаляет предыдущее статусное сообщение и отправляет новое -// с текущим списком файлов и клавиатурой управления. -func (h *Handler) showFileStatus(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, flowState *state.ApprovalFlowState) { +func (h *Handler) showFileStatus(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, flowState *state.ApprovalFlowState, required bool) { ctx := context.Background() - // Удаляем старое статусное сообщение if flowState.FileStatusMsgID != 0 { bot.Request(tgbotapi.NewDeleteMessage(chatID, flowState.FileStatusMsgID)) //nolint:errcheck flowState.FileStatusMsgID = 0 @@ -473,8 +526,14 @@ func (h *Handler) showFileStatus(bot *tgbotapi.BotAPI, chatID int64, telegramID var sb strings.Builder if len(flowState.Files) == 0 { - sb.WriteString("📎 Файлы не прикреплены\n\n") - sb.WriteString("Отправьте файл или нажмите «Отправить на согласование».") + if required { + sb.WriteString("📎 Необходимо прикрепить файл\n\n") + sb.WriteString("⚠️ Для этой темы прикрепление файла обязательно.\n") + sb.WriteString("Отправьте файл или фото.") + } else { + sb.WriteString("📎 Файлы не прикреплены\n\n") + sb.WriteString("Отправьте файл или нажмите «Отправить без файлов».") + } } else { sb.WriteString(fmt.Sprintf("📎 Прикреплённые файлы (%s):\n\n", utilscore.PluralFiles(len(flowState.Files)))) for i, f := range flowState.Files { @@ -485,7 +544,7 @@ func (h *Handler) showFileStatus(bot *tgbotapi.BotAPI, chatID int64, telegramID msg := tgbotapi.NewMessage(chatID, sb.String()) msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildFileInputKeyboard(flowState.TopicCode, flowState.Files) + msg.ReplyMarkup = keyboard.BuildFileInputKeyboard(flowState.TopicCode, flowState.Files, required) sent, err := bot.Send(msg) if err != nil { @@ -493,7 +552,6 @@ func (h *Handler) showFileStatus(bot *tgbotapi.BotAPI, chatID int64, telegramID return } - // Сохраняем ID нового статусного сообщения flowState.FileStatusMsgID = sent.MessageID h.States.Set(ctx, telegramID, flowState) //nolint:errcheck } @@ -512,19 +570,61 @@ func (h *Handler) buildApprovalCard(ctx context.Context, approval *typescore.App } } - topicName := "—" - if approval.TopicID != nil { - topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID) - if topic != nil && topic.Name != nil { - topicName = *topic.Name - } - } + topicName := getTopicFullName(ctx, h.ipc, approval.TopicID) content := "—" if approval.Content != nil { content = *approval.Content } + paymentLabel := "" + if approval.TopicID != nil { + topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID) + if topic != nil { + switch { + case topic.PaymentType != nil && *topic.PaymentType == "own_expense": + paymentLabel = "За свой счёт" + case topic.PaymentType != nil && *topic.PaymentType == "vacation_account": + paymentLabel = "В счёт ежегодного отпуска" + case topic.PaymentType != nil && *topic.PaymentType == "official": + paymentLabel = "Официальный больничный" + } + } + } + + files, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, approvalID) + filesLabel := "Без файлов" + if len(files) > 0 { + filesLabel = fmt.Sprintf("📎 %d файл(ов)", len(files)) + } + + paymentLine := "" + if paymentLabel != "" { + paymentLine = fmt.Sprintf("\nДоп. информация: %s", paymentLabel) + } + + region := "" + if approval.Metadata != nil { + meta, err := typescore.ParseApprovalMetadata(approval.Metadata) + if err == nil && meta != nil { + switch meta.Region { + case "crimea": + region = "Крым" + case "krasnodar": + region = "Краснодар" + case "belarus": + region = "Беларусь" + default: + region = meta.Region + } + } + } + + regionLine := "" + if region != "" { + regionLine = fmt.Sprintf("\n🌍 Регион: %s", region) + } + status := "⏳ ожидает" if approval.Status != nil { switch *approval.Status { @@ -546,10 +646,12 @@ func (h *Handler) buildApprovalCard(ctx context.Context, approval *typescore.App "📋 Заявка #%d\n\n"+ "👤 Инициатор: %s\n"+ "📂 Тема: %s\n"+ - "📝 Текст: %s\n"+ + "📝 Текст: %s%s%s\n"+ + "📎 Файлы: %s\n"+ "📅 Создана: %s\n"+ "📊 Статус: %s", - approvalID, initiatorName, topicName, content, createdAt, status, + approvalID, initiatorName, topicName, content, regionLine, paymentLine, + filesLabel, createdAt, status, ) // Добавляем информацию о текущем согласующем если заявка в процессе @@ -630,3 +732,70 @@ func getTopicFullName(ctx context.Context, ipc *types.InternalProviderControl, t } return fmt.Sprintf("%s: %s", *category.Name, *topic.Name) } + +// findStepForCurrentApprover находит активный шаг, принадлежащий текущему пользователю +func (h *Handler) findStepForCurrentApprover(ctx context.Context, approvalID uint64, currentUserID uint64, approval *typescore.Approval, isAnyOf bool) *typescore.ApprovalStep { + allSteps, _, _ := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalStep{ApprovalID: &approvalID}, + }) + + if !isAnyOf { + for _, s := range allSteps { + if s.Status != nil && (*s.Status == "pending" || *s.Status == "waiting") { + return s + } + } + return nil + } + + for _, s := range allSteps { + if s.Status == nil || (*s.Status != "pending" && *s.Status != "waiting") { + continue + } + if s.ApproverID != nil && *s.ApproverID == currentUserID { + return s + } + } + + if approval.TopicID != nil { + topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID) + if topic != nil && topic.CategoryID != nil { + var allDelegations []*typescore.ApprovalDelegation + + if delegations, _, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalDelegation{ + IsActive: utilscore.PointerToBool(true), + TopicID: approval.TopicID, + }, + }); err == nil { + allDelegations = append(allDelegations, delegations...) + } + + if delegations, _, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalDelegation{ + IsActive: utilscore.PointerToBool(true), + CategoryID: topic.CategoryID, + }, + }); err == nil { + allDelegations = append(allDelegations, delegations...) + } + + for _, s := range allSteps { + if s.Status == nil || (*s.Status != "pending" && *s.Status != "waiting") { + continue + } + if s.ApproverID == nil { + continue + } + for _, deleg := range allDelegations { + if deleg.DelegatorID != nil && *deleg.DelegatorID == *s.ApproverID && + deleg.DelegateID != nil && *deleg.DelegateID == currentUserID { + return s + } + } + } + } + } + + return nil +} diff --git a/service/telegram_service/handlers/approval/http_fetch.go b/service/telegram_service/handlers/approval/http_fetch.go new file mode 100644 index 0000000..33677b5 --- /dev/null +++ b/service/telegram_service/handlers/approval/http_fetch.go @@ -0,0 +1,91 @@ +package approval + +import ( + configcore "bitrix_balancer_api/core/config" + "context" + "encoding/base64" + "errors" + "fmt" + "github.com/sirupsen/logrus" + "io" + "net/http" + "sync" + "time" +) + +var ( + fileHTTPClient *http.Client + fileHTTPClientOnce sync.Once +) + +func buildFileHTTPClient(tgConfig configcore.TelegramConfig) (*http.Client, error) { + if tgConfig.ProxyURL == "" || tgConfig.ParsedProxy == nil { + return nil, errors.New("proxy url is empty or not configured") + } + + fileHTTPClientOnce.Do(func() { + fileHTTPClient = &http.Client{ + Timeout: 30 * time.Second, + Transport: &http.Transport{ + TLSHandshakeTimeout: 10 * time.Second, + ResponseHeaderTimeout: 10 * time.Second, + MaxIdleConns: 100, + MaxIdleConnsPerHost: 10, + IdleConnTimeout: 90 * time.Second, + Proxy: http.ProxyURL(tgConfig.ParsedProxy), + }, + } + }) + + return fileHTTPClient, nil +} + +// fetchFileAsBase64 скачивает файл по URL и возвращает base64-строку. +func fetchFileAsBase64(url string, tgConfig configcore.TelegramConfig) (string, error) { + client, err := buildFileHTTPClient(tgConfig) + if err != nil { + return "", err + } + + const maxRetries = 3 + const baseDelay = 500 * time.Millisecond + + var lastErr error + for attempt := 1; attempt <= maxRetries; attempt++ { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + cancel() + return "", fmt.Errorf("create request: %w", err) + } + + resp, err := client.Do(req) + if err == nil && resp.StatusCode == http.StatusOK { + data, readErr := io.ReadAll(resp.Body) + resp.Body.Close() + cancel() + + if readErr != nil { + return "", fmt.Errorf("read body: %w", readErr) + } + return base64.StdEncoding.EncodeToString(data), nil + } + + if resp != nil { + resp.Body.Close() + } + cancel() + + lastErr = err + if err != nil { + logrus.Warnf("fetchFileAsBase64: attempt %d/%d failed: %v", attempt, maxRetries, err) + } + + if attempt < maxRetries { + delay := baseDelay * time.Duration(1<<(attempt-1)) + time.Sleep(delay) + } + } + + return "", fmt.Errorf("all retries failed: %w", lastErr) +} diff --git a/service/telegram_service/handlers/approval/list.go b/service/telegram_service/handlers/approval/list.go index f365a57..7d7a65c 100644 --- a/service/telegram_service/handlers/approval/list.go +++ b/service/telegram_service/handlers/approval/list.go @@ -8,6 +8,7 @@ import ( "fmt" tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" "github.com/sirupsen/logrus" + "sort" ) // HandleMyApprovals — список активных заявок инициатора @@ -16,29 +17,174 @@ func (h *Handler) HandleMyApprovals(bot *tgbotapi.BotAPI, chatID int64, telegram user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) if err != nil || user == nil || user.ID == nil { - logrus.Warnf("HandleMyApprovals: user not found telegramID=%d", telegramID) return } - approvals, err := h.ipc.Database.Approval.GetActiveApprovalsByInitiatorDB(ctx, *user.ID) - if err != nil { - logrus.Errorf("HandleMyApprovals: GetActiveApprovalsByInitiatorDB err=%v", err) - sendText(bot, chatID, "Ошибка при получении списка заявок.") + // Получаем только те категории, по которым у пользователя есть заявки + categories, err := h.ipc.Database.ApprovalTopicCategory.GetCategoriesWithApprovalsByInitiatorDB(ctx, *user.ID) + if err != nil || len(categories) == 0 { + // Нет заявок вообще — сразу показываем все + h.HandleMyApprovalsStatusCallback( + bot, + &tgbotapi.CallbackQuery{ + Message: &tgbotapi.Message{Chat: &tgbotapi.Chat{ID: chatID}}, + From: &tgbotapi.User{ID: telegramID}, + }, + "all", + "all", + ) return } + msg := tgbotapi.NewMessage(chatID, "📂 Инициированные согласования\n\nВыберите тему:") + msg.ParseMode = "HTML" + msg.ReplyMarkup = buildMyApprovalsTopicFilter(categories) + bot.Send(msg) //nolint:errcheck +} + +func (h *Handler) HandleMyApprovalsTopicCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, topicFilter string) { + ctx := context.Background() + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck + + // Получаем название выбранной категории + header := "Все темы" + if topicFilter != "all" && topicFilter != "" { + cat, _ := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByCodeDB(ctx, topicFilter) + if cat != nil && cat.Name != nil { + header = *cat.Name + } + } + + msg := tgbotapi.NewMessage(cq.Message.Chat.ID, + fmt.Sprintf("📂 %s\n\nВыберите статус:", header), + ) + msg.ParseMode = "HTML" + msg.ReplyMarkup = buildMyApprovalStatusFilter(topicFilter) + bot.Send(msg) //nolint:errcheck +} + +func buildMyApprovalStatusFilter(topicFilter string) tgbotapi.InlineKeyboardMarkup { + cb := func(status string) string { + return fmt.Sprintf("my_appr_status:%s:%s", status, topicFilter) + } + return tgbotapi.NewInlineKeyboardMarkup( + tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData("Все", cb("all")), + ), + tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData("✅ Согласованные", cb("approved")), + tgbotapi.NewInlineKeyboardButtonData("❌ Отклонённые", cb("rejected")), + ), + tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData("⏳ Ожидают", cb("pending")), + ), + tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData("← Назад", "my_appr_back"), + ), + ) +} + +func (h *Handler) HandleMyApprovalsStatusCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, status, topicFilter string) { + ctx := context.Background() + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck + + 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 + } + + var filterStatus *string + if status != "" && status != "all" { + filterStatus = &status + } + + approvals, _, err := h.ipc.Database.Approval.GetApprovalsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.Approval{ + Status: filterStatus, + InitiatorID: user.ID, + }, + }) + if err != nil { + logrus.Errorf("HandleMyApprovalsStatusCallback: err=%v", err) + sendText(bot, chatID, "Ошибка при получении заявок.") + return + } + + if topicFilter != "" && topicFilter != "all" { + cat, _ := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByCodeDB(ctx, topicFilter) + if cat != nil && cat.ID != nil { + topics, _, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalTopic{CategoryID: cat.ID}, + }) + // Собираем ID разрешённых тем + allowedTopicIDs := make(map[uint64]bool) + for _, t := range topics { + if t.ID != nil { + allowedTopicIDs[*t.ID] = true + } + } + // Фильтруем заявки + var filtered []*typescore.Approval + for _, a := range approvals { + if a.TopicID != nil && allowedTopicIDs[*a.TopicID] { + filtered = append(filtered, a) + } + } + approvals = filtered + } + } + if len(approvals) == 0 { - sendText(bot, chatID, "📂 У вас нет активных заявок.") + sendText(bot, chatID, "📭 Заявок по выбранным фильтрам не найдено.") return } - sendText(bot, chatID, fmt.Sprintf("📂 Ваши активные заявки (%d):", len(approvals))) - - for _, a := range approvals { - h.sendApprovalCard(bot, chatID, a, false, false) + for _, approval := range approvals { + if approval.ID == nil { + continue + } + card := h.buildApprovalCard(ctx, approval, h.getCollectedFromApproval(ctx, approval)) + approvalStatus := "" + if approval.Status != nil { + approvalStatus = *approval.Status + } + files, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID) + msg := tgbotapi.NewMessage(chatID, card) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildInitiatorCard(*approval.ID, approvalStatus, len(files) > 0, len(files)) + bot.Send(msg) //nolint:errcheck } } +func buildMyApprovalsTopicFilter(categories []*typescore.ApprovalTopicCategory) tgbotapi.InlineKeyboardMarkup { + var rows [][]tgbotapi.InlineKeyboardButton + + // Кнопка "Все" + rows = append(rows, tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData("📋 Все темы", "my_appr_topic:all"), + )) + + // Кнопки по категориям из БД + for _, c := range categories { + if c.ID == nil || c.Name == nil { + continue + } + rows = append(rows, tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData( + *c.Name, + fmt.Sprintf("my_appr_topic:%s", *c.Code), + ), + )) + } + + return tgbotapi.NewInlineKeyboardMarkup(rows...) +} + // HandleIncomingApprovals — список заявок ожидающих действия согласующего func (h *Handler) HandleIncomingApprovals(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) { ctx := context.Background() @@ -93,6 +239,7 @@ func (h *Handler) HandleIncomingApprovals(bot *tgbotapi.BotAPI, chatID int64, te addedApprovers, _, _ := h.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{ Filtering: &typescore.ApprovalAdditionalApprover{ ApprovalID: step.ApprovalID, + Status: utilscore.PointerToString("pending"), }, }) h.sendApprovalCard(bot, chatID, approval, true, true, addedApprovers) @@ -181,7 +328,8 @@ func (h *Handler) sendApprovalCard(bot *tgbotapi.BotAPI, chatID int64, approval msg.ParseMode = "HTML" if withButtons && approval.Status != nil && *approval.Status == "pending" { - markup := keyboard.BuildApproverDecision(*approval.ID) + files, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID) + markup := keyboard.BuildApproverDecision(*approval.ID, *approval.Status, len(files) > 0, len(files)) //if showAddApprover { // addBtn := tgbotapi.NewInlineKeyboardButtonData( @@ -194,7 +342,11 @@ func (h *Handler) sendApprovalCard(bot *tgbotapi.BotAPI, chatID int64, approval msg.ReplyMarkup = markup } else if approval.Status != nil && (*approval.Status == "pending" || *approval.Status == "approved") { - markup := keyboard.BuildInitiatorCard(*approval.ID) + files, err := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID) + if err != nil { + logrus.Errorf("failed to load files for approval, %v", err) + } + markup := keyboard.BuildInitiatorCard(*approval.ID, *approval.Status, len(files) > 0, len(files)) msg.ReplyMarkup = markup } @@ -205,160 +357,99 @@ func (h *Handler) sendApprovalCard(bot *tgbotapi.BotAPI, chatID int64, approval // HandleApprovalStages показывает все стадии согласования заявки func (h *Handler) HandleApprovalStages(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64) { ctx := context.Background() - chatID := cq.Message.Chat.ID - bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID) if err != nil || approval == nil { - sendText(bot, chatID, "⚠️ Заявка не найдена.") + sendText(bot, cq.Message.Chat.ID, "⚠️ Заявка не найдена.") return } - // Получаем все шаги заявки steps, _, err := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalStep{ - ApprovalID: &approvalID, - }, + Filtering: &typescore.ApprovalStep{ApprovalID: &approvalID}, }) - if err != nil || len(steps) == 0 { - sendText(bot, chatID, "⚠️ Нет информации о стадиях согласования.") + if err != nil { return } - - // Сортируем по порядку - sortedSteps := make([]*typescore.ApprovalStep, len(steps)) - copy(sortedSteps, steps) - for i := 0; i < len(sortedSteps)-1; i++ { - for j := i + 1; j < len(sortedSteps); j++ { - if sortedSteps[i].StepOrder != nil && sortedSteps[j].StepOrder != nil && *sortedSteps[i].StepOrder > *sortedSteps[j].StepOrder { - sortedSteps[i], sortedSteps[j] = sortedSteps[j], sortedSteps[i] - } + sort.Slice(steps, func(i, j int) bool { + if steps[i].StepOrder == nil || steps[j].StepOrder == nil { + return false } - } - - topicName := "—" - if approval.TopicID != nil { - if t, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID); t != nil && t.Name != nil { - topicName = *t.Name - } - } - - content := "—" - if approval.Content != nil { - content = *approval.Content - } - - text := fmt.Sprintf( - "📊 Стадии согласования заявки #%d\n\n"+ - "📋 Тема: %s\n"+ - "📝 Текст: %s\n\n"+ - "Этапы согласования:\n", - approvalID, topicName, content, - ) - - for i, step := range sortedSteps { - stepNum := i + 1 - - approverName := "—" - if step.ApproverNameSnapshot != nil { - approverName = *step.ApproverNameSnapshot - } else if step.ApproverID != nil { - approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *step.ApproverID) - if approver != nil && approver.FullName != nil { - approverName = *approver.FullName - } - } - - statusEmoji := "" - statusText := "" - timeInfo := "" - - if step.Status != nil { - switch *step.Status { - case "approved": - statusEmoji = "✅" - statusText = "Согласовано" - if step.ActedAt != nil { - timeInfo = fmt.Sprintf(" (%s)", step.ActedAt.Format("02.01 15:04")) - } - case "rejected": - statusEmoji = "❌" - statusText = "Отклонено" - if step.ActedAt != nil { - timeInfo = fmt.Sprintf(" (%s)", step.ActedAt.Format("02.01 15:04")) - } - if step.Comment != nil && *step.Comment != "" { - timeInfo += fmt.Sprintf("\n 💬 %s", *step.Comment) - } - case "pending": - statusEmoji = "⏳" - statusText = "Ожидает решения" - default: - statusEmoji = "⏸" - statusText = "Не начато" - } - } - - text += fmt.Sprintf( - "\n%d. %s %s\n %s%s\n", - stepNum, statusEmoji, approverName, statusText, timeInfo, - ) - } - - // Проверяем дополнительных согласующих - additionalApprovers, _, _ := h.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalAdditionalApprover{ - ApprovalID: &approvalID, - }, + return *steps[i].StepOrder < *steps[j].StepOrder }) - if len(additionalApprovers) > 0 { - text += "\n➕ Дополнительные согласующие:\n" - for _, aa := range additionalApprovers { - approverName := "—" - if aa.ApproverID != nil { - approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *aa.ApproverID) - if approver != nil && approver.FullName != nil { - approverName = *approver.FullName + text := fmt.Sprintf("📊 Стадии согласования заявки #%d\n\n", approvalID) + + if len(steps) == 0 { + if approval.Status != nil && *approval.Status == "approved" { + text += "✅ Заявка согласована автоматически\n\n" + text += "Согласующие не были назначены для этой темы.\n" + text += "Заявка принята без этапа согласования.\n" + } else { + text += "⚠️ Этапы согласования отсутствуют\n\n" + text += "Для этой заявки не созданы этапы согласования.\n" + } + } else { + statusIcons := map[string]string{ + "pending": "⏳", + "approved": "✅", + "rejected": "❌", + "waiting": "🔜", + } + + for i, step := range steps { + icon := "🔜" + if step.Status != nil { + if ic, ok := statusIcons[*step.Status]; ok { + icon = ic } } - - statusEmoji := "" - statusText := "" - timeInfo := "" - - if aa.Status != nil { - switch *aa.Status { - case "approved": - statusEmoji = "✅" - statusText = "Согласовано" - if aa.ActedAt != nil { - timeInfo = fmt.Sprintf(" (%s)", aa.ActedAt.Format("02.01 15:04")) - } - case "rejected": - statusEmoji = "❌" - statusText = "Отклонено" - if aa.ActedAt != nil { - timeInfo = fmt.Sprintf(" (%s)", aa.ActedAt.Format("02.01 15:04")) - } - if aa.Comment != nil && *aa.Comment != "" { - timeInfo += fmt.Sprintf("\n 💬 %s", *aa.Comment) - } - case "pending": - statusEmoji = "⏳" - statusText = "Ожидает решения" - } + name := "—" + if step.ApproverNameSnapshot != nil { + name = *step.ApproverNameSnapshot + } + text += fmt.Sprintf("%d. %s %s\n", i+1, icon, name) + if step.ActedAt != nil { + text += fmt.Sprintf(" 📅 %s\n", step.ActedAt.Format("02.01.2006 15:04")) } - - text += fmt.Sprintf( - "\n• %s %s\n %s%s\n", - statusEmoji, approverName, statusText, timeInfo, - ) } } - msg := tgbotapi.NewMessage(chatID, text) + // Статус задач + tasks, _, _ := h.ipc.Database.ApprovalTasks.GetApprovalTasksListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalTask{ApprovalID: &approvalID}, + }) + + if len(tasks) > 0 { + text += "\n🎯 Задачи:\n" + taskStatusLabels := map[string]string{ + "pending": "⏳ Ожидает выполнения", + "completed": "✅ Выполнена", + "cancelled": "❌ Отменена", + "cancellation": "⚠️ Требует отмены изменений", + } + for _, task := range tasks { + statusLabel := "—" + if task.Status != nil { + if l, ok := taskStatusLabels[*task.Status]; ok { + statusLabel = l + } + } + executorName := "—" + if task.ExecutorID != nil { + if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *task.ExecutorID); u != nil && u.FullName != nil { + executorName = *u.FullName + } + } + text += fmt.Sprintf("• %s — %s", executorName, statusLabel) + if task.CompletedAt != nil { + text += fmt.Sprintf(" (%s)", task.CompletedAt.Format("02.01.2006 15:04")) + } + text += "\n" + } + } + + msg := tgbotapi.NewMessage(cq.Message.Chat.ID, text) msg.ParseMode = "HTML" bot.Send(msg) //nolint:errcheck } diff --git a/service/telegram_service/handlers/approval/notify.go b/service/telegram_service/handlers/approval/notify.go index 770c72f..5a055bf 100644 --- a/service/telegram_service/handlers/approval/notify.go +++ b/service/telegram_service/handlers/approval/notify.go @@ -32,23 +32,7 @@ func (h *Handler) notifyExecutor(bot *tgbotapi.BotAPI, ctx context.Context, exec initiatorName = *initiator.FullName } - topicName := "—" - topicCategory := "—" - if approval.TopicID != nil { - topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID) - if topic != nil && topic.Name != nil { - topicName = *topic.Name - } - if topic != nil && topic.CategoryID != nil { - approvalCategory, err := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *topic.CategoryID) - if err != nil { - logrus.Errorf("get approval topic category error: %v", err) - } - if approvalCategory != nil && approvalCategory.Name != nil { - topicCategory = *approvalCategory.Name - } - } - } + topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID) content := "—" if approval.Content != nil { @@ -63,10 +47,10 @@ func (h *Handler) notifyExecutor(bot *tgbotapi.BotAPI, ctx context.Context, exec text := fmt.Sprintf( "📋 Новая задача по заявке #%d\n\n"+ "👤 Инициатор: %s\n"+ - "📋 Тема: %s: %s\n"+ + "📋 Тема: %s\n"+ "📝 Текст заявки: %s\n\n"+ "🎯 Задача:\n%s", - *approval.ID, initiatorName, topicCategory, topicName, content, taskText, + *approval.ID, initiatorName, topicFullName, content, taskText, ) // Добавляем комментарии @@ -126,19 +110,33 @@ func (n *Notifier) NotifyApprover( return } + status := "" + if approval.Status != nil { + status = *approval.Status + } + + files, _ := n.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID) + n.sendFilesToRecipient( bot, *approver.TelegramID, approval, msgText, - keyboard.BuildApproverDecision(*approval.ID), + keyboard.BuildApproverDecision(*approval.ID, status, len(files) > 0, len(files)), ) } func (n *Notifier) sendTextToApprover(bot *tgbotapi.BotAPI, approver *typescore.User, approval *typescore.Approval, text string) { + status := "" + if approval.Status != nil { + status = *approval.Status + } + ctx := context.Background() + files, _ := n.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID) + msg := tgbotapi.NewMessage(*approver.TelegramID, text) msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildApproverDecision(*approval.ID) + msg.ReplyMarkup = keyboard.BuildApproverDecision(*approval.ID, status, len(files) > 0, len(files)) bot.Send(msg) //nolint:errcheck } @@ -166,20 +164,31 @@ func (n *Notifier) NotifyInitiatorApproved( content = "—" } + status := "" + if approval.Status != nil { + status = *approval.Status + } + ctx := context.Background() topicFullName := getTopicFullName(ctx, n.ipc, approval.TopicID) text := fmt.Sprintf( - "✅ Заявка #%d полностью согласована\n\n"+ + "✅ Заявка #%d согласована\n\n"+ "👤 Последний согласующий: %s\n"+ "📋 Тема: %s\n"+ "📝 Текст: %s", *approval.ID, approverName, topicFullName, content, ) + filesCount := len(approval.Files) + if filesCount == 0 { + files, _ := n.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID) + filesCount = len(files) + } + msg := tgbotapi.NewMessage(*initiator.TelegramID, text) msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildRevokeButton(*approval.ID) + msg.ReplyMarkup = keyboard.BuildRevokeButton(*approval.ID, status, filesCount) if _, err := bot.Send(msg); err != nil { logrus.Errorf("NotifyInitiatorApproved: Send err=%v", err) } @@ -231,78 +240,78 @@ func (n *Notifier) NotifyDirector(bot *tgbotapi.BotAPI, director *typescore.User if director.TelegramID == nil { return } - text := "📌 Финальное согласование\n\n" + n.topic.FormatApproverMessage(initiator, collected) + + ctx := context.Background() + // 🚀 Передаем initiator и collected для построения ПОЛНОЙ карточки + card := n.buildApprovalCard(ctx, approval, initiator, collected) + + text := "📌 Финально согласовано\n\n" + card + + status := "" + if approval.Status != nil { + status = *approval.Status + } + + // Считаем файлы для кнопки + filesCount := len(approval.Files) + if filesCount == 0 { + files, _ := n.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID) + filesCount = len(files) + } + msg := tgbotapi.NewMessage(*director.TelegramID, text) msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildRevokeButton(*approval.ID) + // 🚀 Передаем filesCount в клавиатуру + msg.ReplyMarkup = keyboard.BuildRevokeButton(*approval.ID, status, filesCount) bot.Send(msg) //nolint:errcheck } -// NotifyObserversNewApproval — новая заявка отправлена на согласование. -func (n *Notifier) NotifyObserversNewApproval( - bot *tgbotapi.BotAPI, - observers []*typescore.User, - initiator *typescore.User, - approval *typescore.Approval, - collected map[string]string, -) { - for _, obs := range observers { - if obs.TelegramID == nil { - continue - } - - text := fmt.Sprintf("👁 Новая заявка #%d\n\n", *approval.ID) + - n.topic.FormatApproverMessage(initiator, collected) - - if len(approval.Files) == 0 { - msg := tgbotapi.NewMessage(*obs.TelegramID, text) - msg.ParseMode = "HTML" - bot.Send(msg) //nolint:errcheck - continue - } - - n.sendFilesToRecipient(bot, *obs.TelegramID, approval, text, nil) // без кнопок - } -} - // NotifyObserversDecision — кто, кому и что согласовал/отклонил. func (n *Notifier) NotifyObserversDecision( bot *tgbotapi.BotAPI, observers []*typescore.User, - approver *typescore.User, initiator *typescore.User, + approver *typescore.User, approval *typescore.Approval, collected map[string]string, - approved bool, ) { + if approval.Status == nil || *approval.Status != "approved" { + return + } + + ctx := context.Background() + // 🚀 Передаем initiator и collected + card := n.buildApprovalCard(ctx, approval, initiator, collected) + approverName := "—" if approver != nil && approver.FullName != nil { approverName = *approver.FullName } - initiatorName := "—" - if initiator != nil && initiator.FullName != nil { - initiatorName = *initiator.FullName - } - content := collected["content"] - - action := "✅ согласовал(а)" - if !approved { - action = "❌ отклонил(а)" - } - - text := fmt.Sprintf( - "👁 Решение по заявке #%d\n\n"+ - "%s %s заявку %s\n"+ - "📝 %s", - *approval.ID, approverName, action, initiatorName, content, + header := fmt.Sprintf( + "✅ %s согласовал(а) заявку\n\n", + approverName, ) + text := header + card + + // Считаем файлы для кнопки + filesCount := len(approval.Files) + if filesCount == 0 { + files, _ := n.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID) + filesCount = len(files) + } + + status := "" + if approval.Status != nil { + status = *approval.Status + } for _, obs := range observers { if obs.TelegramID == nil { continue } msg := tgbotapi.NewMessage(*obs.TelegramID, text) msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildObserverActions(*approval.ID, "", status, filesCount) bot.Send(msg) //nolint:errcheck } } @@ -317,13 +326,12 @@ func (n *Notifier) sendFilesToRecipient( text string, replyMarkup interface{}, ) { - // Декодируем все файлы заранее, чтобы не слать половину при ошибке - type decoded struct { + type decodedFile struct { name string bytes []byte } - var validFiles []decoded + var validFiles []decodedFile for _, f := range approval.Files { if f.FileBase64 == nil || f.FileName == nil { continue @@ -333,11 +341,10 @@ func (n *Notifier) sendFilesToRecipient( logrus.Errorf("sendFilesToRecipient: base64 decode file=%s err=%v", *f.FileName, err) continue } - validFiles = append(validFiles, decoded{name: *f.FileName, bytes: data}) + validFiles = append(validFiles, decodedFile{name: *f.FileName, bytes: data}) } if len(validFiles) == 0 { - // Все файлы битые — шлём хотя бы текст msg := tgbotapi.NewMessage(chatID, text) msg.ParseMode = "HTML" if replyMarkup != nil { @@ -347,28 +354,71 @@ func (n *Notifier) sendFilesToRecipient( return } - for i, f := range validFiles { - doc := tgbotapi.NewDocument(chatID, tgbotapi.FileBytes{ - Name: f.name, - Bytes: f.bytes, - }) - doc.ParseMode = "HTML" + const batchSize = 10 + batches := splitIntoBatches(validFiles, batchSize) - // Текст — только к первому файлу - if i == 0 { - doc.Caption = text - } - // Клавиатура — только к последнему файлу - if i == len(validFiles)-1 && replyMarkup != nil { - doc.ReplyMarkup = replyMarkup + for batchIdx, batch := range batches { + isLastBatch := batchIdx == len(batches)-1 + + if len(batch) == 1 { + // Один файл — отправляем как документ с текстом и кнопками + doc := tgbotapi.NewDocument(chatID, tgbotapi.FileBytes{ + Name: batch[0].name, + Bytes: batch[0].bytes, + }) + doc.ParseMode = "HTML" + if batchIdx == 0 { + doc.Caption = text + } + if isLastBatch && replyMarkup != nil { + doc.ReplyMarkup = replyMarkup + } + if _, err := bot.Send(doc); err != nil { + logrus.Errorf("sendFilesToRecipient: Send doc err=%v", err) + } + continue } - if _, err := bot.Send(doc); err != nil { - logrus.Errorf("sendFilesToRecipient: Send file=%s err=%v", f.name, err) + var mediaGroup []interface{} + for i, f := range batch { + photo := tgbotapi.NewInputMediaDocument(tgbotapi.FileBytes{ + Name: f.name, + Bytes: f.bytes, + }) + if i == 0 && batchIdx == 0 { + photo.Caption = text + photo.ParseMode = "HTML" + } + mediaGroup = append(mediaGroup, photo) + } + + mg := tgbotapi.NewMediaGroup(chatID, mediaGroup) + if _, err := bot.Request(mg); err != nil { + logrus.Errorf("sendFilesToRecipient: SendMediaGroup batch=%d err=%v", batchIdx, err) + } + + if isLastBatch && replyMarkup != nil { + btnMsg := tgbotapi.NewMessage(chatID, "⬆️ Файлы выше") + btnMsg.ParseMode = "HTML" + btnMsg.ReplyMarkup = replyMarkup + bot.Send(btnMsg) //nolint:errcheck } } } +// splitIntoBatches делит слайс на батчи размером size +func splitIntoBatches[T any](items []T, size int) [][]T { + if len(items) == 0 { + return nil + } + var batches [][]T + for len(items) > size { + batches = append(batches, items[:size]) + items = items[size:] + } + return append(batches, items) +} + func (h *Handler) sendDelegationAlreadyExists(bot *tgbotapi.BotAPI, chatID int64, existing *typescore.ApprovalDelegation, telegramID int64) { ctx := context.Background() @@ -412,57 +462,56 @@ func (h *Handler) sendDelegationAlreadyExists(bot *tgbotapi.BotAPI, chatID int64 func (h *Handler) sendAdditionalApprovalCard(bot *tgbotapi.BotAPI, chatID int64, approval *typescore.Approval, additionalApprover *typescore.ApprovalAdditionalApprover) { ctx := context.Background() - if approval.ID == nil { return } - initiatorName := "—" - if approval.InitiatorID != nil { - initiator, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID) - if initiator != nil && initiator.FullName != nil { - initiatorName = *initiator.FullName - } - } - - topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID) - - content := "—" - if approval.Content != nil { - content = *approval.Content - } + // Подгружаем актуальные файлы + files, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID) + approval.Files = files addedByName := "—" if additionalApprover.AddedByID != nil { - addedBy, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *additionalApprover.AddedByID) - if addedBy != nil && addedBy.FullName != nil { - addedByName = *addedBy.FullName + if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *additionalApprover.AddedByID); u != nil && u.FullName != nil { + addedByName = *u.FullName } } - text := fmt.Sprintf( - "📄 Заявка #%d (добавлен: %s)\n\n"+ - "👤 Инициатор: %s\n"+ - "📋 Тема: %s\n"+ - "📝 Текст: %s", - *approval.ID, addedByName, initiatorName, topicFullName, content, - ) + // Используем единую карточку + card := h.buildApprovalCard(ctx, approval, h.getCollectedFromApproval(ctx, approval)) - // Добавляем комментарии - commentsSection := h.formatCommentsSection(ctx, *approval.ID) - text += commentsSection + text := fmt.Sprintf("📄 Добавлен пользователем: %s\n\n%s", addedByName, card) - msg := tgbotapi.NewMessage(chatID, text) - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildApproverDecision(*approval.ID) - bot.Send(msg) //nolint:errcheck + status := "" + if approval.Status != nil { + status = *approval.Status + } + + if len(files) == 0 { + msg := tgbotapi.NewMessage(chatID, text) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildApproverDecision(*approval.ID, status, len(files) > 0, len(files)) + bot.Send(msg) //nolint:errcheck + return + } + + categoryCode := h.getTopicCodeByApproval(ctx, approval) + topic, _ := h.Registry.Get(categoryCode) + if topic != nil { + notifier := NewNotifier(h.ipc, topic) + notifier.sendFilesToRecipient(bot, chatID, approval, text, keyboard.BuildApproverDecision(*approval.ID, status, len(files) > 0, len(files))) + } } // notifyObserversAboutNewFile уведомляет наблюдателей о прикреплённом файле -func (h *Handler) notifyObserversAboutNewFile(bot *tgbotapi.BotAPI, approvalID uint64, attachedBy *typescore.User, fileName, fileBase64 string) { +func (h *Handler) notifyObserversAboutNewFile( + bot *tgbotapi.BotAPI, + approvalID uint64, + attachedBy *typescore.User, + fileName, fileBase64 string, +) { ctx := context.Background() - // Получаем заявку для topicCode approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID) if err != nil || approval == nil { logrus.Errorf("notifyObserversAboutNewFile: GetApprovalByIDDB err=%v", err) @@ -486,6 +535,8 @@ func (h *Handler) notifyObserversAboutNewFile(bot *tgbotapi.BotAPI, approvalID u userName = *attachedBy.FullName } + fileData, decodeErr := base64.StdEncoding.DecodeString(fileBase64) + for _, obs := range observers { if obs.TelegramID == nil { continue @@ -498,11 +549,8 @@ func (h *Handler) notifyObserversAboutNewFile(bot *tgbotapi.BotAPI, approvalID u approvalID, userName, fileName, ) - // Декодируем и отправляем файл - fileData, err := base64.StdEncoding.DecodeString(fileBase64) - if err != nil { - logrus.Errorf("notifyObserversAboutNewFile: base64 decode err=%v", err) - // Отправляем хотя бы текст + if decodeErr != nil { + logrus.Errorf("notifyObserversAboutNewFile: base64 decode err=%v", decodeErr) msg := tgbotapi.NewMessage(*obs.TelegramID, text) msg.ParseMode = "HTML" bot.Send(msg) //nolint:errcheck @@ -522,6 +570,212 @@ func (h *Handler) notifyObserversAboutNewFile(bot *tgbotapi.BotAPI, approvalID u } } +func (h *Handler) notifyAllParticipantsAboutFile( + bot *tgbotapi.BotAPI, + approvalID uint64, + attachedBy *typescore.User, + fileDescription string, +) { + ctx := context.Background() + + approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID) + if err != nil || approval == nil { + logrus.Errorf("notifyAllParticipantsAboutFile: GetApprovalByIDDB err=%v", err) + return + } + + files, err := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, approvalID) + if err != nil { + logrus.Warnf("notifyAllParticipantsAboutFile: GetFilesByApprovalIDDB err=%v", err) + } + approval.Files = files + + senderID := uint64(0) + if attachedBy != nil && attachedBy.ID != nil { + senderID = *attachedBy.ID + } + + senderName := "—" + if attachedBy != nil && attachedBy.FullName != nil { + senderName = *attachedBy.FullName + } + + text := fmt.Sprintf( + "📎 Файлы прикреплены к заявке #%d\n\n"+ + "👤 Кем: %s\n"+ + "📄 Количество: %s", + approvalID, senderName, fileDescription, + ) + + var recipients []*typescore.User + + if approval.InitiatorID != nil { + if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID); u != nil { + recipients = append(recipients, u) + } + } + + if step, _ := h.ipc.Database.ApprovalStep.GetActiveStepDB(ctx, approvalID); step != nil && step.ApproverID != nil { + if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *step.ApproverID); u != nil { + recipients = append(recipients, u) + } + } + + categoryCode := h.getTopicCodeByApproval(ctx, approval) + observers, _ := h.ipc.Database.User.GetObserversForCategoryDB(ctx, categoryCode) + recipients = append(recipients, observers...) + + // Получаем нотифайер для sendFilesToRecipient + topic, err := h.Registry.Get(categoryCode) + if err != nil { + logrus.Errorf("notifyAllParticipantsAboutFile: Registry.Get err=%v", err) + return + } + notifier := NewNotifier(h.ipc, topic) + + seen := make(map[uint64]bool) + for _, r := range recipients { + if r == nil || r.ID == nil || r.TelegramID == nil { + continue + } + if *r.ID == senderID || seen[*r.ID] { + continue + } + seen[*r.ID] = true + + if len(approval.Files) == 0 { + msg := tgbotapi.NewMessage(*r.TelegramID, text) + msg.ParseMode = "HTML" + bot.Send(msg) //nolint:errcheck + } else { + notifier.sendFilesToRecipient(bot, *r.TelegramID, approval, text, nil) + } + } +} + func (n *Notifier) formatApprovalMessage(initiator *typescore.User, collected map[string]string) string { return n.topic.FormatApproverMessage(initiator, collected) } + +func (n *Notifier) buildApprovalCard(ctx context.Context, approval *typescore.Approval, initiator *typescore.User, collected map[string]string) string { + if approval.ID == nil { + return "" + } + approvalID := *approval.ID + + topicInfo := n.topic.FormatApproverMessage(initiator, collected) + + filesCount := len(approval.Files) + if filesCount == 0 { + files, _ := n.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, approvalID) + filesCount = len(files) + } + + filesLabel := "Без файлов" + if filesCount > 0 { + filesLabel = fmt.Sprintf("📎 %d файл(ов)", filesCount) + } + + status := "⏳ ожидает" + if approval.Status != nil { + switch *approval.Status { + case "approved": + status = "✅ согласована" + case "rejected": + status = "❌ отклонена" + case "revoked": + status = "🔙 отозвана" + } + } + + createdAt := "—" + if approval.CreatedAt != nil { + createdAt = approval.CreatedAt.Format("02.01.2006 15:04") + } + + card := fmt.Sprintf( + "📋 Заявка #%d\n\n"+ + "%s\n\n"+ // 🚀 Сюда вставляется полное тело заявки из topicInfo + "📎 Файлы: %s\n"+ + "📅 Создана: %s\n"+ + "📊 Статус: %s", + approvalID, topicInfo, filesLabel, createdAt, status, + ) + + // Добавляем информацию о текущем согласующем если заявка в процессе + if approval.Status != nil && *approval.Status == "pending" { + activeStep, _ := n.ipc.Database.ApprovalStep.GetActiveStepDB(ctx, approvalID) + if activeStep != nil && activeStep.ApproverID != nil { + approver, _ := n.ipc.Database.User.GetUserByIDDB(ctx, *activeStep.ApproverID) + if approver != nil && approver.FullName != nil { + card += fmt.Sprintf("\n🔄 У согласующего: %s", *approver.FullName) + } + } + } + + // Добавляем информацию о дополнительных согласующих + additionalApprovers, _, _ := n.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalAdditionalApprover{ + ApprovalID: &approvalID, + }, + }) + if len(additionalApprovers) > 0 { + card += "\n\n👥 Дополнительные согласующие:" + for _, aa := range additionalApprovers { + if aa.ApproverID == nil { + continue + } + approver, _ := n.ipc.Database.User.GetUserByIDDB(ctx, *aa.ApproverID) + if approver == nil || approver.FullName == nil { + continue + } + + statusIcon := "⏳" + if aa.Status != nil { + switch *aa.Status { + case "approved": + statusIcon = "✅" + case "rejected": + statusIcon = "❌" + } + } + card += fmt.Sprintf("\n• %s %s", statusIcon, *approver.FullName) + } + } + + // Добавляем комментарии + commentsSection := n.formatCommentsSection(ctx, approvalID) + card += commentsSection + + return card +} + +func (n *Notifier) formatCommentsSection(ctx context.Context, approvalID uint64) string { + comments, _, _ := n.ipc.Database.ApprovalComment.GetApprovalCommentsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalComment{ApprovalID: &approvalID}, + }) + if len(comments) == 0 { + return "" + } + + section := "\n\n💬 Комментарии:" + for _, c := range comments { + authorName := "—" + if c.UserID != nil { + author, _ := n.ipc.Database.User.GetUserByIDDB(ctx, *c.UserID) + if author != nil && author.FullName != nil { + authorName = *author.FullName + } + } + createdAt := "" + if c.CreatedAt != nil { + createdAt = c.CreatedAt.Format("02.01 15:04") + } + comment := "-" + if c.Comment != nil { + comment = *c.Comment + } + section += fmt.Sprintf("\n• %s (%s): %s", authorName, createdAt, comment) + } + return section +} diff --git a/service/telegram_service/handlers/approval/registry.go b/service/telegram_service/handlers/approval/registry.go index 4c554ac..80f7163 100644 --- a/service/telegram_service/handlers/approval/registry.go +++ b/service/telegram_service/handlers/approval/registry.go @@ -6,8 +6,12 @@ import ( clientchanges "bitrix_balancer_api/telegram_service/handlers/approval/topics/client_changes" "bitrix_balancer_api/telegram_service/handlers/approval/topics/free" goodsorder "bitrix_balancer_api/telegram_service/handlers/approval/topics/goods_order" + managerexpenses "bitrix_balancer_api/telegram_service/handlers/approval/topics/manager_expenses" nonbudgetexpenses "bitrix_balancer_api/telegram_service/handlers/approval/topics/non_budget_expenses" nonbudgetexpensespetline "bitrix_balancer_api/telegram_service/handlers/approval/topics/non_budget_expenses_pet_line" + nonstandardcontract "bitrix_balancer_api/telegram_service/handlers/approval/topics/nonstandard_contract" + otkconditions "bitrix_balancer_api/telegram_service/handlers/approval/topics/otk_conditions" + paymentscashless "bitrix_balancer_api/telegram_service/handlers/approval/topics/payments_cashless" rateslogistics "bitrix_balancer_api/telegram_service/handlers/approval/topics/rates_logistics" "bitrix_balancer_api/telegram_service/handlers/approval/topics/receipts" "bitrix_balancer_api/telegram_service/handlers/approval/topics/returns" @@ -38,28 +42,28 @@ func (r *Registry) registerAll() { r.register(transactionpassport.NewTransactionPassportTopic()) r.register(rateslogistics.NewRatesLogisticsTopic()) r.register(receipts.NewReceiptsTopic()) + r.register(paymentscashless.NewPaymentsCashlessTopic()) + r.register(managerexpenses.NewManagerExpensesTopic()) + r.register(nonstandardcontract.NewNonstandardContractTopic()) + r.register(otkconditions.NewOtkConditionsTopic()) // Свободные темы (без подтем) - freeTopics := []struct{ code, name string }{ - {"delivery_clients", "Доставка клиентам/на склад"}, - {"v_shipments", "В. Отгрузки"}, - {"manager_expenses", "Менеджерские расходы"}, - {"shipments", "Отгрузки"}, - {"nonstandard_contract", "Нестандартные условия договора поставки"}, - {"vacancies", "Вакансии"}, - {"delivery_rates_ap", "Ставки доставки АП"}, - {"freelancers_approval", "Утверждение фрилансеров"}, - {"non_working_day", "Выход в нерабочий день"}, - {"suggestions", "Предложения и пожелания"}, - {"otk_conditions", "Долгосрочные условия ОТК"}, - {"cash_balance", "Остаток в кассах"}, - {"client_sales", "Продажи по клиенту"}, - {"manager_expenses_report", "Проведенные расходы по менеджеру"}, - {"new_clients", "Заведение новых клиентов"}, - {"payments_cashless", "Утверждение оплат безнал"}, + freeTopics := []struct{ code, name, template, instructions string }{ + {"delivery_clients", "Доставка клиентам/на склад", "Иванов Иван Иванович\nТел 89781234567\nПаспорт 1234 567890\nДАФ н862нн46 п/п АА8473|46\n\n61 бц с ад - 52 кор\nЧП000001676\n\nЕПР-СтройКрым", ""}, + {"v_shipments", "В. Отгрузки", "ООО Нива на 370 тыс. руб. под 19%", ""}, + {"shipments", "Отгрузки", "", "Если не входит в рамки согласованного лимита, добавь руководителя соответствующего филиала к согласованию через кнопку 'Добавить согласующего'"}, + {"vacancies", "Вакансии", "", ""}, + {"delivery_rates_ap", "Ставки доставки АП", "Прошу согласовать доставку 14 кор преформы клиенту Олег-Выдув-Сочи за 34 000 руб.", ""}, + {"freelancers_approval", "Утверждение фрилансеров", "Одного помощника на выгрузку полной фуры с крышкой ручкой с КТ на 23.04.2026 на весь день", ""}, + {"non_working_day", "Выход в нерабочий день", "Прошу вывести склад для учета c 25.04 по 26.04", ""}, + {"suggestions", "Предложения и пожелания", "", ""}, + {"cash_balance", "Остаток в кассах", "", ""}, + {"client_sales", "Продажи по клиенту", "", ""}, + {"manager_expenses_report", "Проведенные расходы по менеджеру", "", ""}, + {"remote_access", "Согласование удаленной работы", "Прошу согласовать удалённый выход на работу 06.06.2026", ""}, } for _, t := range freeTopics { - r.register(free.NewFreeTopic(t.code, t.name)) + r.register(free.NewFreeTopic(t.code, t.name, t.template)) } } diff --git a/service/telegram_service/handlers/approval/revision.go b/service/telegram_service/handlers/approval/revision.go index 30c87d1..329340a 100644 --- a/service/telegram_service/handlers/approval/revision.go +++ b/service/telegram_service/handlers/approval/revision.go @@ -107,11 +107,11 @@ func (h *Handler) HandleRevisionWithComment(bot *tgbotapi.BotAPI, approverChatID commentText = fmt.Sprintf("\n💬 Причина: %s", comment) } + approvalCard := h.buildApprovalCard(ctx, approval, h.getCollectedFromApproval(ctx, approval)) + sendText(bot, approverChatID, fmt.Sprintf( - "🔄 Заявка #%d возвращена на доработку\n\n"+ - "📋 Тема: %s\n"+ - "📝 Текст: %s%s", - approvalID, topicFullName, content, commentText, + "🔄 Заявка #%d возвращена на доработку\n\n%s%s", + approvalID, approvalCard, commentText, )) if approval.InitiatorID != nil { @@ -327,7 +327,7 @@ func (h *Handler) HandleRevisionResubmit(bot *tgbotapi.BotAPI, cq *tgbotapi.Call approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *activeStep.ApproverID) if approver != nil && approver.TelegramID != nil { topicCode := h.getTopicCodeByApproval(ctx, approval) - topic, _ := h.registry.Get(topicCode) + topic, _ := h.Registry.Get(topicCode) collected := h.getCollectedFromApproval(ctx, approval) @@ -351,6 +351,11 @@ func (h *Handler) HandleRevisionResubmit(bot *tgbotapi.BotAPI, cq *tgbotapi.Call approvalID, revisionCount, initiatorName, ) + status := "" + if approval.Status != nil { + status = *approval.Status + } + if topic != nil { notifier := NewNotifier(h.ipc, topic) // Добавляем заголовок о доработке к стандартному сообщению @@ -359,15 +364,15 @@ func (h *Handler) HandleRevisionResubmit(bot *tgbotapi.BotAPI, cq *tgbotapi.Call if len(files) == 0 { msg := tgbotapi.NewMessage(*approver.TelegramID, fullText) msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildApproverDecision(approvalID) + msg.ReplyMarkup = keyboard.BuildApproverDecision(approvalID, status, len(files) > 0, len(files)) bot.Send(msg) //nolint:errcheck } else { - notifier.sendFilesToRecipient(bot, *approver.TelegramID, approval, fullText, keyboard.BuildApproverDecision(approvalID)) + notifier.sendFilesToRecipient(bot, *approver.TelegramID, approval, fullText, keyboard.BuildApproverDecision(approvalID, status, len(files) > 0, len(files))) } } else { msg := tgbotapi.NewMessage(*approver.TelegramID, text) msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildApproverDecision(approvalID) + msg.ReplyMarkup = keyboard.BuildApproverDecision(approvalID, status, len(files) > 0, len(files)) bot.Send(msg) //nolint:errcheck } } @@ -451,7 +456,7 @@ func (h *Handler) HandleRevisionFileInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Me return true } - base64Data, err := fetchFileAsBase64(fileURL) // используем существующую функцию + base64Data, err := fetchFileAsBase64(fileURL, h.ipc.Config.Telegram) // используем существующую функцию if err != nil { logrus.Errorf("HandleRevisionFileInput: fetchFileAsBase64 err=%v", err) sendText(bot, chatID, "Ошибка при обработке файла.") diff --git a/service/telegram_service/handlers/approval/selection_approver.go b/service/telegram_service/handlers/approval/selection_approver.go index bc11da3..ba11a5e 100644 --- a/service/telegram_service/handlers/approval/selection_approver.go +++ b/service/telegram_service/handlers/approval/selection_approver.go @@ -6,6 +6,7 @@ import ( "bitrix_balancer_api/telegram_service/state" "context" "fmt" + "strings" tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" "github.com/sirupsen/logrus" @@ -95,7 +96,7 @@ func (h *Handler) HandleApproverSelectionPageCallback(bot *tgbotapi.BotAPI, cq * return } - topic, _ := h.registry.Get(flowState.TopicCode) + topic, _ := h.Registry.Get(flowState.TopicCode) if topic == nil { return } @@ -153,7 +154,6 @@ func (h *Handler) getAvailableApproversForTopic(ctx context.Context, userID, dep } } - // Получаем полную информацию о согласующих var approvers []*typescore.User for approverID := range approverIDs { approver, err := h.ipc.Database.User.GetUserByIDDB(ctx, approverID) @@ -168,21 +168,69 @@ func (h *Handler) getAvailableApproversForTopic(ctx context.Context, userID, dep func (h *Handler) finalizeAndSubmit(bot *tgbotapi.BotAPI, ctx context.Context, chatID int64, telegramID int64, flowState *state.ApprovalFlowState) { approval, err := h.submitApproval(ctx, bot, telegramID, flowState) if err != nil { - logrus.Error("finalizeAndSubmit: submitApproval error", err) - bot.Send(tgbotapi.NewMessage(chatID, "Произошла ошибка при отправке заявки. Попробуйте позже.")) //nolint:errcheck + logrus.Errorf("finalizeAndSubmit: submitApproval error: %v", err) + + errMsg := err.Error() + if !strings.HasPrefix(errMsg, "⚠️") { + errMsg = "Произошла ошибка при отправке заявки. Попробуйте позже." + } + + msg := tgbotapi.NewMessage(chatID, errMsg) + msg.ParseMode = "HTML" + bot.Send(msg) //nolint:errcheck return } if approval == nil || approval.ID == nil { logrus.Error("finalizeAndSubmit: approval is nil after submitApproval") - bot.Send(tgbotapi.NewMessage(chatID, "✅ Отправлено на согласование")) //nolint:errcheck + bot.Send(tgbotapi.NewMessage(chatID, "📤 Отправлено на согласование")) //nolint:errcheck return } - approverName := "—" - if activeStep, _ := h.ipc.Database.ApprovalStep.GetActiveStepDB(ctx, *approval.ID); activeStep != nil && activeStep.ApproverID != nil { - if approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *activeStep.ApproverID); approver != nil && approver.FullName != nil { - approverName = *approver.FullName + var approvalTopic *typescore.ApprovalTopic + if approval.TopicID != nil { + approvalTopic, _ = h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID) + } + isAnyOf := approvalTopic != nil && approvalTopic.ApprovalMode != nil && *approvalTopic.ApprovalMode == "any_of" + + approverLine := "—" + + allSteps, _, _ := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalStep{ApprovalID: approval.ID}, + }) + + if isAnyOf { + var names []string + for _, s := range allSteps { + if s.Status == nil || (*s.Status != "pending" && *s.Status != "waiting") { + continue + } + if s.ApproverID != nil { + if approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *s.ApproverID); approver != nil && approver.FullName != nil { + names = append(names, *approver.FullName) + } + } + } + if len(names) > 0 { + approverLine = strings.Join(names, " или ") + } + } else { + if len(allSteps) > 0 { + var firstStep *typescore.ApprovalStep + for _, s := range allSteps { + if s.StepOrder == nil { + continue + } + if firstStep == nil || *s.StepOrder < *firstStep.StepOrder { + firstStep = s + } + } + + if firstStep != nil && firstStep.ApproverID != nil { + if approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *firstStep.ApproverID); approver != nil && approver.FullName != nil { + approverLine = *approver.FullName + } + } } } @@ -193,15 +241,138 @@ func (h *Handler) finalizeAndSubmit(bot *tgbotapi.BotAPI, ctx context.Context, c content = *approval.Content } - confirmMsg := fmt.Sprintf( - "✅ Заявка #%d отправлена на согласование\n\n"+ - "👤 Согласующий: %s\n"+ - "📋 Тема: %s\n"+ - "📝 Текст: %s", - *approval.ID, approverName, topicFullName, content, - ) + var confirmMsg string + if isAnyOf { + confirmMsg = fmt.Sprintf( + "📤 Заявка #%d отправлена на согласование\n\n"+ + "👤 Согласует один из: %s\n\n"+ + "📋 Тема: %s\n"+ + "📝 Текст: %s", + *approval.ID, approverLine, topicFullName, content, + ) + } else { + confirmMsg = fmt.Sprintf( + "📤 Заявка #%d отправлена на согласование\n\n"+ + "👤 Согласующий: %s\n\n"+ + "📋 Тема: %s\n"+ + "📝 Текст: %s", + *approval.ID, approverLine, topicFullName, content, + ) + } msgChat := tgbotapi.NewMessage(chatID, confirmMsg) msgChat.ParseMode = "HTML" + + approvalStatus := "pending" + if approval.Status != nil { + approvalStatus = *approval.Status + } + msgChat.ReplyMarkup = keyboard.BuildInitiatorCard(*approval.ID, approvalStatus, len(approval.Files) > 0, len(approval.Files)) + bot.Send(msgChat) //nolint:errcheck } + +// createTasksForApproval создаёт задачи для исполнителей на основе конфигурации темы +func (h *Handler) createTasksForApproval( + bot *tgbotapi.BotAPI, + ctx context.Context, + approval *typescore.Approval, + initiator *typescore.User, +) { + if approval == nil || approval.TopicID == nil { + return + } + + topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID) + if topic == nil { + return + } + + topicExecutors, err := h.ipc.Database.ApprovalTopicExecutor.GetExecutorsByTopicIDDB(ctx, *approval.TopicID) + if err != nil { + logrus.Errorf("createTasksForApproval: GetExecutorsByTopicIDDB err=%v", err) + return + } + + if len(topicExecutors) == 0 { + logrus.Infof("createTasksForApproval: no executors configured for topicID=%d", *approval.TopicID) + return + } + + meta, _ := typescore.ParseApprovalMetadata(approval.Metadata) + systemsToProcess := meta.SelectedSystems + if len(systemsToProcess) == 0 { + systemsToProcess = []string{"all"} + } + + logrus.Infof("createTasksForApproval: topicID=%d systems=%v executors=%d", + *approval.TopicID, systemsToProcess, len(topicExecutors)) + + taskCounter := 0 + + for _, system := range systemsToProcess { + for _, topicExec := range topicExecutors { + if topicExec.UserID == nil { + continue + } + + if topicExec.TargetSystem != nil && *topicExec.TargetSystem != "all" && *topicExec.TargetSystem != system { + continue + } + + if topicExec.TaskText == nil || *topicExec.TaskText == "" { + continue + } + + executor, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *topicExec.UserID) + if executor == nil || executor.ID == nil { + continue + } + + taskText := *topicExec.TaskText + systemLabel := "" + if system != "all" && system != "" { + switch system { + case "okb": + systemLabel = "[ОКБ] " + case "1c": + systemLabel = "[1С] " + } + taskText = systemLabel + taskText + } + + taskStatus := "waiting" + if taskCounter == 0 { + taskStatus = "pending" + } + + stepOrder := taskCounter + requireFile := false + if topicExec.RequireFile != nil { + requireFile = *topicExec.RequireFile + } + + createdTask, _, err := h.ipc.Database.ApprovalTasks.CreateApprovalTaskDB(ctx, nil, &typescore.ApprovalTask{ + ApprovalID: approval.ID, + ExecutorID: executor.ID, + TaskText: &taskText, + Status: &taskStatus, + StepOrder: &stepOrder, + RequireFile: &requireFile, + TopicExecutorID: topicExec.ID, + }, true) + if err != nil { + logrus.Errorf("createTasksForApproval: CreateApprovalTask system=%s executor=%d err=%v", system, *executor.ID, err) + continue + } + + if createdTask != nil && taskStatus == "pending" && executor.TelegramID != nil { + h.notifyExecutor(bot, ctx, executor, initiator, approval, createdTask) + } + + taskCounter++ + } + } + + logrus.Infof("createTasksForApproval: created %d tasks for approvalID=%d", taskCounter, *approval.ID) +} diff --git a/service/telegram_service/handlers/approval/selection_first_approver.go b/service/telegram_service/handlers/approval/selection_first_approver.go index 3d81420..22c42ec 100644 --- a/service/telegram_service/handlers/approval/selection_first_approver.go +++ b/service/telegram_service/handlers/approval/selection_first_approver.go @@ -117,7 +117,7 @@ func (h *Handler) HandleFirstApproverPageCallback(bot *tgbotapi.BotAPI, cq *tgbo return } - topic, _ := h.registry.Get(flowState.TopicCode) + topic, _ := h.Registry.Get(flowState.TopicCode) if topic == nil { return } @@ -146,7 +146,7 @@ func (h *Handler) getFirstApproverRoleForFlow( ctx context.Context, flowState *state.ApprovalFlowState, ) (*typescore.ApprovalTopic, string, string) { - topic, _ := h.registry.Get(flowState.TopicCode) + topic, _ := h.Registry.Get(flowState.TopicCode) if topic == nil { return nil, "", "" } diff --git a/service/telegram_service/handlers/approval/selection_observer.go b/service/telegram_service/handlers/approval/selection_observer.go index 98430e0..4441ecf 100644 --- a/service/telegram_service/handlers/approval/selection_observer.go +++ b/service/telegram_service/handlers/approval/selection_observer.go @@ -17,23 +17,50 @@ func (h *Handler) showObserverSelection( chatID int64, telegramID int64, flowState *state.ApprovalFlowState, + approvalTopic *typescore.ApprovalTopic, ) { observers, err := h.getAvailableObservers(ctx) if err != nil || len(observers) == 0 { + // Если выбор обязателен, но наблюдателей нет — блокируем создание заявки + isRequired := approvalTopic != nil && + approvalTopic.RequireObserverSelection != nil && + *approvalTopic.RequireObserverSelection + + if isRequired { + sendText(bot, chatID, + "⚠️ Для этой темы обязательно выбрать наблюдателя,\n"+ + "но в системе нет пользователей с ролью наблюдателя.\n\n"+ + "Обратитесь к администратору.") + flowState.AwaitObserverSelection = false + flowState.ObserverSelectionDone = false // не помечаем как выполненное + h.States.Set(ctx, telegramID, flowState) //nolint:errcheck + return + } + flowState.AwaitObserverSelection = false flowState.ObserverSelectionDone = true - h.States.Clear(ctx, telegramID) + h.States.Clear(ctx, telegramID) //nolint:errcheck h.finalizeAndSubmit(bot, ctx, chatID, telegramID, flowState) return } - msg := tgbotapi.NewMessage(chatID, - "👁 Выберите наблюдателей для заявки\n"+ - "Они получат уведомления, но не смогут влиять на решение.\n"+ - "Можно выбрать несколько или пропустить.", - ) + isRequired := approvalTopic != nil && + approvalTopic.RequireObserverSelection != nil && + *approvalTopic.RequireObserverSelection + + var text string + if isRequired { + text = "👁 Выберите наблюдателей для заявки\n\n" + + "⚠️ Выберите менеджера, чья это отгрузка." + } else { + text = "👁 Выберите наблюдателей для заявки\n" + + "Они получат уведомления, но не смогут влиять на решение.\n" + + "Можно выбрать несколько или пропустить." + } + + msg := tgbotapi.NewMessage(chatID, text) msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildObserverSelectionMenu(observers, flowState.SelectedObserverIDs, 0) + msg.ReplyMarkup = keyboard.BuildObserverSelectionMenu(observers, flowState.SelectedObserverIDs, 0, isRequired) bot.Send(msg) //nolint:errcheck } @@ -50,12 +77,11 @@ func (h *Handler) HandleObserverToggleCallback(bot *tgbotapi.BotAPI, cq *tgbotap return } - // Toggle: добавляем или убираем наблюдателя found := false newIDs := make([]uint64, 0, len(flowState.SelectedObserverIDs)) for _, id := range flowState.SelectedObserverIDs { if id == observerID { - found = true // убираем — просто не добавляем + found = true } else { newIDs = append(newIDs, id) } @@ -70,17 +96,27 @@ func (h *Handler) HandleObserverToggleCallback(bot *tgbotapi.BotAPI, cq *tgbotap return } - // Обновляем сообщение с новым состоянием кнопок + var approvalTopic *typescore.ApprovalTopic + if flowState.TopicCode != "" { + topic, _ := h.Registry.Get(flowState.TopicCode) + if topic != nil { + topicCode, _ := topic.TopicCodeFromCollected(flowState.Collected) + approvalTopic, _ = h.ipc.Database.ApprovalTopic.GetApprovalTopicByCodeDB(ctx, topicCode) + } + } + isRequired := approvalTopic != nil && + approvalTopic.RequireObserverSelection != nil && + *approvalTopic.RequireObserverSelection + observers, _ := h.getAvailableObservers(ctx) editMsg := tgbotapi.NewEditMessageReplyMarkup( chatID, cq.Message.MessageID, - keyboard.BuildObserverSelectionMenu(observers, flowState.SelectedObserverIDs, 0), + keyboard.BuildObserverSelectionMenu(observers, flowState.SelectedObserverIDs, 0, isRequired), ) 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 @@ -93,6 +129,18 @@ func (h *Handler) HandleObserverPageCallback(bot *tgbotapi.BotAPI, cq *tgbotapi. return } + var approvalTopic *typescore.ApprovalTopic + if flowState.TopicCode != "" { + topic, _ := h.Registry.Get(flowState.TopicCode) + if topic != nil { + topicCode, _ := topic.TopicCodeFromCollected(flowState.Collected) + approvalTopic, _ = h.ipc.Database.ApprovalTopic.GetApprovalTopicByCodeDB(ctx, topicCode) + } + } + isRequired := approvalTopic != nil && + approvalTopic.RequireObserverSelection != nil && + *approvalTopic.RequireObserverSelection + observers, err := h.getAvailableObservers(ctx) if err != nil { return @@ -101,7 +149,7 @@ func (h *Handler) HandleObserverPageCallback(bot *tgbotapi.BotAPI, cq *tgbotapi. editMsg := tgbotapi.NewEditMessageReplyMarkup( chatID, cq.Message.MessageID, - keyboard.BuildObserverSelectionMenu(observers, flowState.SelectedObserverIDs, page), + keyboard.BuildObserverSelectionMenu(observers, flowState.SelectedObserverIDs, page, isRequired), ) bot.Request(editMsg) //nolint:errcheck } @@ -112,8 +160,7 @@ func (h *Handler) HandleObserverConfirmCallback(bot *tgbotapi.BotAPI, cq *tgbota 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 + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck flowState, err := h.States.Get(ctx, telegramID) if err != nil || flowState == nil { @@ -121,6 +168,26 @@ func (h *Handler) HandleObserverConfirmCallback(bot *tgbotapi.BotAPI, cq *tgbota return } + var approvalTopic *typescore.ApprovalTopic + if flowState.TopicCode != "" { + topic, _ := h.Registry.Get(flowState.TopicCode) + if topic != nil { + topicCode, _ := topic.TopicCodeFromCollected(flowState.Collected) + approvalTopic, _ = h.ipc.Database.ApprovalTopic.GetApprovalTopicByCodeDB(ctx, topicCode) + } + } + + isRequired := approvalTopic != nil && + approvalTopic.RequireObserverSelection != nil && + *approvalTopic.RequireObserverSelection + + if isRequired && len(flowState.SelectedObserverIDs) == 0 { + bot.Request(tgbotapi.NewCallback(cq.ID, "⚠️ Выберите хотя бы одного наблюдателя")) //nolint:errcheck + return + } + + bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck + h.States.Clear(ctx, telegramID) //nolint:errcheck h.finalizeAndSubmit(bot, ctx, chatID, telegramID, flowState) } diff --git a/service/telegram_service/handlers/approval/topics/absence/topic.go b/service/telegram_service/handlers/approval/topics/absence/topic.go index 2699ba2..826d7c7 100644 --- a/service/telegram_service/handlers/approval/topics/absence/topic.go +++ b/service/telegram_service/handlers/approval/topics/absence/topic.go @@ -1,5 +1,3 @@ -// telegram_service/handlers/approval/topics/absence/topic.go - НОВЫЙ ФАЙЛ - package absence import ( @@ -11,18 +9,17 @@ import ( "fmt" ) -// AbsenceTopic — объединяет отгул, отпуск и больничный в одну кнопку type AbsenceTopic struct { - timeoff *timeoff.TimeOffTopic - vacation *vacation.VacationTopic - sickleave *sickleave.SickLeaveTopic + timeoffTopic *timeoff.TimeOffTopic + vacationTopic *vacation.VacationTopic + sickleaveTopic *sickleave.SickLeaveTopic } func NewAbsenceTopic() *AbsenceTopic { return &AbsenceTopic{ - timeoff: timeoff.NewTimeOffTopic(), - vacation: vacation.NewVacationTopic(), - sickleave: sickleave.NewSickLeaveTopic(), + timeoffTopic: timeoff.NewTimeOffTopic(), + vacationTopic: vacation.NewVacationTopic(), + sickleaveTopic: sickleave.NewSickLeaveTopic(), } } @@ -41,21 +38,22 @@ func (a *AbsenceTopic) BuildTree() *approvalflow.FlowNode { Label: "Отгул", DataKey: "absence_type", DataValue: "timeoff", - Children: a.timeoff.BuildTree().Children, + // Копируем детей из оригинального дерева timeoff + Children: a.timeoffTopic.BuildTree().Children, }, { Key: "absence_vacation", Label: "Отпуск", DataKey: "absence_type", DataValue: "vacation", - Children: a.vacation.BuildTree().Children, + Children: a.vacationTopic.BuildTree().Children, }, { Key: "absence_sickleave", - Label: "Больничный", + Label: "Официальный больничный", DataKey: "absence_type", DataValue: "sickleave", - Children: a.sickleave.BuildTree().Children, + Children: a.sickleaveTopic.BuildTree().Children, }, }, } @@ -65,24 +63,24 @@ func (a *AbsenceTopic) TopicCodeFromCollected(collected map[string]string) (stri absenceType := collected["absence_type"] switch absenceType { case "timeoff": - return a.timeoff.TopicCodeFromCollected(collected) + return a.timeoffTopic.TopicCodeFromCollected(collected) case "vacation": - return a.vacation.TopicCodeFromCollected(collected) + return a.vacationTopic.TopicCodeFromCollected(collected) case "sickleave": - return a.sickleave.TopicCodeFromCollected(collected) + return a.sickleaveTopic.TopicCodeFromCollected(collected) default: - return "", fmt.Errorf("absence_type не указан: %v", collected) + return "", fmt.Errorf("absence_type не указан в collected: %v", collected) } } func (a *AbsenceTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { switch collected["absence_type"] { case "timeoff": - return a.timeoff.FormatApproverMessage(initiator, collected) + return a.timeoffTopic.FormatApproverMessage(initiator, collected) case "vacation": - return a.vacation.FormatApproverMessage(initiator, collected) + return a.vacationTopic.FormatApproverMessage(initiator, collected) case "sickleave": - return a.sickleave.FormatApproverMessage(initiator, collected) + return a.sickleaveTopic.FormatApproverMessage(initiator, collected) default: name := "" if initiator.FullName != nil { diff --git a/service/telegram_service/handlers/approval/topics/client_changes/topic.go b/service/telegram_service/handlers/approval/topics/client_changes/topic.go index 6480348..2a2ce4b 100644 --- a/service/telegram_service/handlers/approval/topics/client_changes/topic.go +++ b/service/telegram_service/handlers/approval/topics/client_changes/topic.go @@ -18,8 +18,6 @@ func (c *ClientChangesTopic) Name() string { return "Изменение клиента в ОКБ и 1С" } -// BuildTree: Тип изменения → Регион → Система → Ввод -// Примечание: Множественный выбор систем будет добавлен позже func (c *ClientChangesTopic) BuildTree() *approvalflow.FlowNode { return &approvalflow.FlowNode{ Key: "client_changes", @@ -46,10 +44,6 @@ func (c *ClientChangesTopic) buildChangeType(changeKey, changeLabel string) *app } func (c *ClientChangesTopic) buildRegion(changeKey, regionKey, regionLabel string) *approvalflow.FlowNode { - okbCode := fmt.Sprintf("client_changes_%s_okb_%s", changeKey, regionKey) - bitrixCode := fmt.Sprintf("client_changes_%s_bitrix_%s", changeKey, regionKey) - oneСCode := fmt.Sprintf("client_changes_%s_1c_%s", changeKey, regionKey) - return &approvalflow.FlowNode{ Key: changeKey + "_" + regionKey, Label: regionLabel, @@ -57,11 +51,10 @@ func (c *ClientChangesTopic) buildRegion(changeKey, regionKey, regionLabel strin DataValue: regionKey, Children: []*approvalflow.FlowNode{ { - Key: changeKey + "_" + regionKey + "_systems", + Key: changeKey + "_" + regionKey + "_okb", IsMultiSelect: true, MultiSelectKey: "systems", MultiSelectValue: "okb", - TopicCode: okbCode, Label: "ОКБ", Children: []*approvalflow.FlowNode{ { @@ -72,28 +65,11 @@ func (c *ClientChangesTopic) buildRegion(changeKey, regionKey, regionLabel strin }, }, }, - { - Key: changeKey + "_" + regionKey + "_bitrix", - IsMultiSelect: true, - MultiSelectKey: "systems", - MultiSelectValue: "bitrix", - TopicCode: bitrixCode, - Label: "Битрикс", - Children: []*approvalflow.FlowNode{ - { - Key: changeKey + "_" + regionKey + "_bitrix_input", - IsInput: true, - InputKey: "content", - InputHint: "Опишите изменения: текущие данные → новые данные", - }, - }, - }, { Key: changeKey + "_" + regionKey + "_1c", IsMultiSelect: true, MultiSelectKey: "systems", MultiSelectValue: "1c", - TopicCode: oneСCode, Label: "1С", Children: []*approvalflow.FlowNode{ { @@ -111,18 +87,12 @@ func (c *ClientChangesTopic) buildRegion(changeKey, regionKey, regionLabel strin func (c *ClientChangesTopic) TopicCodeFromCollected(collected map[string]string) (string, error) { changeType := collected["change_type"] region := collected["region"] - systems := collected["systems"] if changeType == "" || region == "" { return "", fmt.Errorf("неполные данные: change_type=%s, region=%s", changeType, region) } - if systems == "" { - return fmt.Sprintf("client_changes_%s_%s", changeType, region), nil - } - - firstSystem := strings.SplitN(systems, ",", 2)[0] - return fmt.Sprintf("client_changes_%s_%s_%s", changeType, firstSystem, region), nil + return fmt.Sprintf("client_changes_%s_%s", changeType, region), nil } func (c *ClientChangesTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { @@ -143,30 +113,34 @@ func (c *ClientChangesTopic) FormatApproverMessage(initiator *typescore.User, co changeLabel = "Изменение клиента" } - regionLabel := "Крым" - if collected["region"] == "krasnodar" { + regionLabel := "—" + switch collected["region"] { + case "crimea": + regionLabel = "Крым" + case "krasnodar": regionLabel = "Краснодар" } - // Формируем список всех выбранных систем var systemLabels []string - for _, s := range strings.Split(collected["systems"], ",") { - switch strings.TrimSpace(s) { - case "okb": - systemLabels = append(systemLabels, "ОКБ") - case "bitrix": - systemLabels = append(systemLabels, "Битрикс") - case "1c": - systemLabels = append(systemLabels, "1С") + systems := collected["systems"] + if systems != "" { + for _, s := range strings.Split(systems, ",") { + switch strings.TrimSpace(s) { + case "okb": + systemLabels = append(systemLabels, "ОКБ") + case "1c": + systemLabels = append(systemLabels, "1С") + } } } + systemsStr := "не указаны" if len(systemLabels) > 0 { systemsStr = strings.Join(systemLabels, ", ") } return fmt.Sprintf( - "📋 %s\n"+ + "📋 Изменение клиентов в ОКБ и 1С: – %s\n"+ "🖥 Системы: %s\n"+ "📍 Регион: %s\n\n"+ "%s:\n%s", diff --git a/service/telegram_service/handlers/approval/topics/free/topic.go b/service/telegram_service/handlers/approval/topics/free/topic.go index 3d7b73c..bd8c505 100644 --- a/service/telegram_service/handlers/approval/topics/free/topic.go +++ b/service/telegram_service/handlers/approval/topics/free/topic.go @@ -9,18 +9,27 @@ import ( // FreeTopic — тема с единственным шагом: свободный текстовый ввод. // Подходит для всех тем без разветвлённой логики. type FreeTopic struct { - code string - name string + code string + name string + template string } -func NewFreeTopic(code, name string) *FreeTopic { - return &FreeTopic{code: code, name: name} +func NewFreeTopic(code, name, template string) *FreeTopic { + return &FreeTopic{ + code: code, + name: name, + template: template, + } } func (o *FreeTopic) Code() string { return o.code } func (o *FreeTopic) Name() string { return o.name } func (o *FreeTopic) BuildTree() *approvalflow.FlowNode { + tmp := "Напишите текст согласования" + if o.template != "" { + tmp = o.template + } return &approvalflow.FlowNode{ Key: o.code, Label: o.name, @@ -29,7 +38,7 @@ func (o *FreeTopic) BuildTree() *approvalflow.FlowNode { Key: o.code + "_input", IsInput: true, InputKey: "content", - InputHint: "Напишите текст согласования", + InputHint: tmp, }, }, } @@ -39,14 +48,28 @@ func (o *FreeTopic) TopicCodeFromCollected(_ map[string]string) (string, error) return o.code, nil } -func (o *FreeTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { - name := "" - if initiator.FullName != nil { - name = *initiator.FullName +func (t *FreeTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { + initiatorName := "—" + if initiator != nil && initiator.FullName != nil { + initiatorName = *initiator.FullName } - return fmt.Sprintf( - "📋 %s\n\n"+ - "%s:\n%s", - o.name, name, collected["content"], + + content := collected["content"] + if content == "" { + content = "—" + } + + text := fmt.Sprintf( + "📋 Заявка на согласование\n\n"+ + "👤 От: %s\n"+ + "📂 Тема: %s\n"+ + "📝 Текст:\n%s", + initiatorName, t.Name(), content, ) + + if instructions, ok := collected["instructions"]; ok && instructions != "" { + text += fmt.Sprintf("\n\n💡 Инструкция:\n%s", instructions) + } + + return text } diff --git a/service/telegram_service/handlers/approval/topics/goods_order/topic.go b/service/telegram_service/handlers/approval/topics/goods_order/topic.go index 7e918b6..211414c 100644 --- a/service/telegram_service/handlers/approval/topics/goods_order/topic.go +++ b/service/telegram_service/handlers/approval/topics/goods_order/topic.go @@ -25,38 +25,58 @@ func (g *GoodsOrderTopic) BuildTree() *approvalflow.FlowNode { Label: "На месяц", DataKey: "order_type", DataValue: "monthly", - Children: []*approvalflow.FlowNode{ - { - Key: "monthly_input", - IsInput: true, - InputKey: "content", - InputHint: "Опишите заказ на месяц: товары, количество, сроки", - }, - }, + Children: g.buildRegions("monthly"), }, { Key: "additional", Label: "Дополнительный заказ", DataKey: "order_type", DataValue: "additional", - Children: []*approvalflow.FlowNode{ - { - Key: "additional_input", - IsInput: true, - InputKey: "content", - InputHint: "Опишите дополнительный заказ: товары, количество, причина", - }, - }, + Children: g.buildRegions("additional"), }, }, } } +func (g *GoodsOrderTopic) buildRegions(orderType string) []*approvalflow.FlowNode { + return []*approvalflow.FlowNode{ + { + Key: orderType + "_crimea", + Label: "Крым", + DataKey: "region", + DataValue: "crimea", + Children: []*approvalflow.FlowNode{{ + Key: orderType + "_crimea_input", + IsInput: true, + InputKey: "content", + InputHint: "Скилур заказ:\n22 гр.38 мм бесцветная (10176) ЕПМ - 5кор.\nф1, на склад Гвардейское, 2я декада.", + }}, + }, + { + Key: orderType + "_krasnodar", + Label: "Краснодар", + DataKey: "region", + DataValue: "krasnodar", + Children: []*approvalflow.FlowNode{{ + Key: orderType + "_krasnodar_input", + IsInput: true, + InputKey: "content", + InputHint: "Скилур заказ:\n22 гр.38 мм бесцветная (10176) ЕПМ - 5кор.\nф1, на склад Гвардейское, 2я декада.", + }}, + }, + } +} + func (g *GoodsOrderTopic) TopicCodeFromCollected(collected map[string]string) (string, error) { orderType := collected["order_type"] + region := collected["region"] if orderType == "" { return "", fmt.Errorf("order_type не указан") } + // region опционален для обратной совместимости + if region != "" { + return fmt.Sprintf("goods_order_%s_%s", orderType, region), nil + } return fmt.Sprintf("goods_order_%s", orderType), nil } @@ -71,9 +91,18 @@ func (g *GoodsOrderTopic) FormatApproverMessage(initiator *typescore.User, colle typeLabel = "Дополнительный заказ" } + regionLabel := "—" + switch collected["region"] { + case "crimea": + regionLabel = "Крым" + case "krasnodar": + regionLabel = "Краснодар" + } + return fmt.Sprintf( - "📋 Заказ товаров — %s\n\n"+ + "📋 Заказ товаров — %s\n"+ + "📍 Регион: %s\n\n"+ "%s:\n%s", - typeLabel, name, collected["content"], + typeLabel, regionLabel, name, collected["content"], ) } diff --git a/service/telegram_service/handlers/approval/topics/manager_expenses/topic.go b/service/telegram_service/handlers/approval/topics/manager_expenses/topic.go new file mode 100644 index 0000000..4e030bd --- /dev/null +++ b/service/telegram_service/handlers/approval/topics/manager_expenses/topic.go @@ -0,0 +1,70 @@ +package managerexpenses + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/telegram_service/approvalflow" + "fmt" +) + +type ManagerExpensesTopic struct{} + +func NewManagerExpensesTopic() *ManagerExpensesTopic { return &ManagerExpensesTopic{} } + +func (s *ManagerExpensesTopic) Code() string { return "manager_expenses" } +func (s *ManagerExpensesTopic) Name() string { return "Менеджерские расходы" } + +func (s *ManagerExpensesTopic) BuildTree() *approvalflow.FlowNode { + return &approvalflow.FlowNode{ + Key: "manager_expenses", + Label: "Менеджерские расходы", + Children: []*approvalflow.FlowNode{ + s.buildRegion("crimea", "Крым"), + s.buildRegion("krasnodar", "Краснодар"), + }, + } +} + +func (s *ManagerExpensesTopic) buildRegion(regionKey, regionLabel string) *approvalflow.FlowNode { + return &approvalflow.FlowNode{ + Key: regionKey, + Label: regionLabel, + DataKey: "region", + DataValue: regionKey, + Children: []*approvalflow.FlowNode{ + { + Key: regionKey + "_input", + IsInput: true, + InputKey: "content", + InputHint: "Оплата платной дороги Краснодар-Темрюк-Краснодар в сумме 1420 руб. (клиент РУСМолоко) (расход Макаренко)", + }, + }, + } +} + +func (s *ManagerExpensesTopic) TopicCodeFromCollected(collected map[string]string) (string, error) { + region := collected["region"] + if region == "" { + return "", fmt.Errorf("неполные данные: region пуст") + } + return fmt.Sprintf("manager_expenses_%s", region), nil +} + +func (s *ManagerExpensesTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { + name := "" + if initiator.FullName != nil { + name = *initiator.FullName + } + + regionLabel := collected["region"] + switch regionLabel { + case "crimea": + regionLabel = "Крым" + case "krasnodar": + regionLabel = "Краснодар" + } + + return fmt.Sprintf( + "📋 Менеджерские расходы — %s\n\n%s:\n%s", + regionLabel, name, collected["content"], + ) +} diff --git a/service/telegram_service/handlers/approval/topics/non_budget_expenses/topic.go b/service/telegram_service/handlers/approval/topics/non_budget_expenses/topic.go index 6c0b817..3a5cc82 100644 --- a/service/telegram_service/handlers/approval/topics/non_budget_expenses/topic.go +++ b/service/telegram_service/handlers/approval/topics/non_budget_expenses/topic.go @@ -15,96 +15,90 @@ func NewNonBudgetExpensesTopic() *NonBudgetExpensesTopic { func (n *NonBudgetExpensesTopic) Code() string { return "non_budget_expenses" } func (n *NonBudgetExpensesTopic) Name() string { return "Внебюджетные расходы" } -// BuildTree: Филиал (Ф1/Ф2) → Тип (ТМЦ/Расход) → Ввод func (n *NonBudgetExpensesTopic) BuildTree() *approvalflow.FlowNode { return &approvalflow.FlowNode{ Key: "non_budget_expenses", Label: "Внебюджетные расходы", Children: []*approvalflow.FlowNode{ { - Key: "f1", - Label: "Ф1", - DataKey: "branch", - DataValue: "f1", + Key: "f1", Label: "Ф1", + DataKey: "branch", DataValue: "f1", Children: []*approvalflow.FlowNode{ - { - Key: "f1_tmc", - Label: "ТМЦ", - DataKey: "expense_type", - DataValue: "tmc", - Children: []*approvalflow.FlowNode{ - { - Key: "f1_tmc_input", - IsInput: true, - InputKey: "content", - InputHint: "Опишите расход ТМЦ: наименование, количество, сумма", - }, - }, - }, - { - Key: "f1_expense", - Label: "Расход", - DataKey: "expense_type", - DataValue: "expense", - Children: []*approvalflow.FlowNode{ - { - Key: "f1_expense_input", - IsInput: true, - InputKey: "content", - InputHint: "Опишите расход: назначение, сумма, детали", - }, - }, - }, + // 🚀 Ф1 — с развилкой ПП (разные подтемы) + n.buildExpenseTypeWithPP("f1_tmc", "tmc", "ТМЦ", + "Прошу согласовать и оплатить Счет от ООО Интернет Решения (Озон) за ноутбук и мышь для закупщика в сумме 31 335 руб. С НДС"), + n.buildExpenseTypeWithPP("f1_expense", "expense", "Расход", + "Прошу оплатить счет ИП Гулякина на сумму 3180,00 руб (без НДС) за продление 1С-Отчетность на 1 год"), }, }, { - Key: "f2", - Label: "Ф2", - DataKey: "branch", - DataValue: "f2", + Key: "f2", Label: "Ф2", + DataKey: "branch", DataValue: "f2", Children: []*approvalflow.FlowNode{ - { - Key: "f2_tmc", - Label: "ТМЦ", - DataKey: "expense_type", - DataValue: "tmc", - Children: []*approvalflow.FlowNode{ - { - Key: "f2_tmc_input", - IsInput: true, - InputKey: "content", - InputHint: "Опишите расход ТМЦ: наименование, количество, сумма", - }, - }, - }, - { - Key: "f2_expense", - Label: "Расход", - DataKey: "expense_type", - DataValue: "expense", - Children: []*approvalflow.FlowNode{ - { - Key: "f2_expense_input", - IsInput: true, - InputKey: "content", - InputHint: "Опишите расход: назначение, сумма, детали", - }, - }, - }, + // Ф2 — без развилки ПП (одна подтема) + n.buildExpenseTypeSimple("f2_tmc", "tmc", "ТМЦ", + "Прошу согласовать и оплатить Счет от ООО Интернет Решения (Озон) за ноутбук и мышь для закупщика в сумме 31 335 руб. С НДС"), + n.buildExpenseTypeSimple("f2_expense", "expense", "Расход", + "Прошу оплатить счет ИП Гулякина на сумму 3180,00 руб (без НДС) за продление 1С-Отчетность на 1 год"), }, }, }, } } +// buildExpenseTypeWithPP создаёт узел с выбором "Нужна ПП" / "Не нужна ПП" +// Каждый выбор ведёт к СВОЕЙ подтеме +func (n *NonBudgetExpensesTopic) buildExpenseTypeWithPP(key, typeVal, label, hint string) *approvalflow.FlowNode { + return &approvalflow.FlowNode{ + Key: key, Label: label, + DataKey: "expense_type", DataValue: typeVal, + Children: []*approvalflow.FlowNode{ + { + Key: key + "_pp_yes", Label: "✅ Нужна ПП", + DataKey: "pp_required", DataValue: "yes", + Children: []*approvalflow.FlowNode{{ + Key: key + "_pp_yes_input", IsInput: true, + InputKey: "content", InputHint: hint, + }}, + }, + { + Key: key + "_pp_no", Label: "❌ Не нужна ПП", + DataKey: "pp_required", DataValue: "no", + Children: []*approvalflow.FlowNode{{ + Key: key + "_pp_no_input", IsInput: true, + InputKey: "content", InputHint: hint, + }}, + }, + }, + } +} + +func (n *NonBudgetExpensesTopic) buildExpenseTypeSimple(key, typeVal, label, hint string) *approvalflow.FlowNode { + return &approvalflow.FlowNode{ + Key: key, Label: label, + DataKey: "expense_type", DataValue: typeVal, + Children: []*approvalflow.FlowNode{{ + Key: key + "_input", IsInput: true, + InputKey: "content", InputHint: hint, + }}, + } +} + +// 🚀 TopicCodeFromCollected теперь включает pp_required в код темы func (n *NonBudgetExpensesTopic) TopicCodeFromCollected(collected map[string]string) (string, error) { branch := collected["branch"] expenseType := collected["expense_type"] + ppRequired := collected["pp_required"] if branch == "" || expenseType == "" { return "", fmt.Errorf("неполные данные: branch=%s, expense_type=%s", branch, expenseType) } + // 🚀 Если pp_required указан — добавляем его в код темы + if ppRequired != "" { + return fmt.Sprintf("non_budget_expenses_%s_%s_pp_%s", branch, expenseType, ppRequired), nil + } + // Для Ф2 (без ПП) — старый формат return fmt.Sprintf("non_budget_expenses_%s_%s", branch, expenseType), nil } @@ -114,21 +108,18 @@ func (n *NonBudgetExpensesTopic) FormatApproverMessage(initiator *typescore.User name = *initiator.FullName } - branchLabel := collected["branch"] - if branchLabel == "f1" { - branchLabel = "Ф1" - } else if branchLabel == "f2" { - branchLabel = "Ф2" - } + branchLabel := map[string]string{"f1": "Ф1", "f2": "Ф2"}[collected["branch"]] + typeLabel := map[string]string{"tmc": "ТМЦ", "expense": "Расход"}[collected["expense_type"]] - typeLabel := "Расход" - if collected["expense_type"] == "tmc" { - typeLabel = "ТМЦ" + // 🚀 Информация о ПП теперь в названии темы, не дублируем + ppLine := "" + if pp := collected["pp_required"]; pp != "" { + ppLabel := map[string]string{"yes": "✅ Нужна ПП", "no": "❌ Не нужна ПП"}[pp] + ppLine = fmt.Sprintf("\n💳 ПП: %s", ppLabel) } return fmt.Sprintf( - "📋 Внебюджетные расходы — %s (%s)\n\n"+ - "%s:\n%s", - branchLabel, typeLabel, name, collected["content"], + "📋 Внебюджетные расходы — %s (%s)%s\n\n%s:\n%s", + branchLabel, typeLabel, ppLine, name, collected["content"], ) } diff --git a/service/telegram_service/handlers/approval/topics/nonstandard_contract/topic.go b/service/telegram_service/handlers/approval/topics/nonstandard_contract/topic.go new file mode 100644 index 0000000..b4b46bb --- /dev/null +++ b/service/telegram_service/handlers/approval/topics/nonstandard_contract/topic.go @@ -0,0 +1,75 @@ +package nonstandardcontract + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/telegram_service/approvalflow" + "fmt" +) + +type NonstandardContractTopic struct{} + +func NewNonstandardContractTopic() *NonstandardContractTopic { return &NonstandardContractTopic{} } + +func (s *NonstandardContractTopic) Code() string { return "nonstandard_contract" } +func (s *NonstandardContractTopic) Name() string { + return "Нестандартные условия договора поставки" +} + +func (s *NonstandardContractTopic) BuildTree() *approvalflow.FlowNode { + return &approvalflow.FlowNode{ + Key: "nonstandard_contract", + Label: "Нестандартные условия договора поставки", + Children: []*approvalflow.FlowNode{ + s.buildRegion("crimea", "Крым"), + s.buildRegion("krasnodar", "Краснодар"), + s.buildRegion("belarus", "Беларусь"), + }, + } +} + +func (s *NonstandardContractTopic) buildRegion(regionKey, regionLabel string) *approvalflow.FlowNode { + return &approvalflow.FlowNode{ + Key: regionKey, + Label: regionLabel, + DataKey: "region", + DataValue: regionKey, + Children: []*approvalflow.FlowNode{ + { + Key: regionKey + "_input", + IsInput: true, + InputKey: "content", + InputHint: "Прошу согласовать отсрочку 21 день для клиента ООО Роса (другое юрлицо ООО Аквариум) (менеджер Петров)", + }, + }, + } +} + +func (s *NonstandardContractTopic) TopicCodeFromCollected(collected map[string]string) (string, error) { + region := collected["region"] + if region == "" { + return "", fmt.Errorf("неполные данные: region пуст") + } + return fmt.Sprintf("nonstandard_contract_%s", region), nil +} + +func (s *NonstandardContractTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { + name := "" + if initiator.FullName != nil { + name = *initiator.FullName + } + + regionLabel := collected["region"] + switch regionLabel { + case "crimea": + regionLabel = "Крым" + case "krasnodar": + regionLabel = "Краснодар" + case "belarus": + regionLabel = "Беларусь" + } + + return fmt.Sprintf( + "📋 Нестандартные условия договора поставки — %s\n\n%s:\n%s", + regionLabel, name, collected["content"], + ) +} diff --git a/service/telegram_service/handlers/approval/topics/otk_conditions/topic.go b/service/telegram_service/handlers/approval/topics/otk_conditions/topic.go new file mode 100644 index 0000000..573ec2d --- /dev/null +++ b/service/telegram_service/handlers/approval/topics/otk_conditions/topic.go @@ -0,0 +1,82 @@ +package otkconditions + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/telegram_service/approvalflow" + "fmt" +) + +type OtkConditionsTopic struct{} + +func NewOtkConditionsTopic() *OtkConditionsTopic { return &OtkConditionsTopic{} } + +func (s *OtkConditionsTopic) Code() string { return "otk_conditions" } +func (s *OtkConditionsTopic) Name() string { return "Долгосрочные условия ОТК" } + +func (s *OtkConditionsTopic) BuildTree() *approvalflow.FlowNode { + return &approvalflow.FlowNode{ + Key: "otk_conditions", + Label: "Долгосрочные условия ОТК", + Children: []*approvalflow.FlowNode{ + s.buildRegion("crimea", "Крым"), + s.buildRegion("krasnodar", "Краснодар"), + s.buildRegion("belarus", "Беларусь"), + }, + } +} + +func (s *OtkConditionsTopic) buildRegion(regionKey, regionLabel string) *approvalflow.FlowNode { + return &approvalflow.FlowNode{ + Key: regionKey, + Label: regionLabel, + DataKey: "region", + DataValue: regionKey, + Children: []*approvalflow.FlowNode{ + { + Key: regionKey + "_input", + IsInput: true, + InputKey: "content", + InputHint: "Опишите долгосрочные условия ОТК", + }, + }, + } +} + +func (s *OtkConditionsTopic) TopicCodeFromCollected(collected map[string]string) (string, error) { + region := collected["region"] + if region == "" { + return "", fmt.Errorf("неполные данные: region пуст") + } + return fmt.Sprintf("otk_conditions_%s", region), nil +} + +func (s *OtkConditionsTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { + name := "—" + if initiator != nil && initiator.FullName != nil { + name = *initiator.FullName + } + + regionLabel := "—" + if collected != nil { + switch collected["region"] { + case "crimea": + regionLabel = "Крым" + case "krasnodar": + regionLabel = "Краснодар" + case "belarus": + regionLabel = "Беларусь" + } + } + + content := "—" + if collected != nil && collected["content"] != "" { + content = collected["content"] + } + + return fmt.Sprintf( + "📋 Долгосрочные условия ОТК — %s\n\n"+ + "👤 Инициатор: %s\n"+ + "📝 Текст:\n%s", + regionLabel, name, content, + ) +} diff --git a/service/telegram_service/handlers/approval/topics/payments_cashless/topic.go b/service/telegram_service/handlers/approval/topics/payments_cashless/topic.go new file mode 100644 index 0000000..54220a5 --- /dev/null +++ b/service/telegram_service/handlers/approval/topics/payments_cashless/topic.go @@ -0,0 +1,90 @@ +package paymentscashless + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/telegram_service/approvalflow" + "fmt" +) + +type PaymentsCashlessTopic struct{} + +func NewPaymentsCashlessTopic() *PaymentsCashlessTopic { return &PaymentsCashlessTopic{} } + +func (p *PaymentsCashlessTopic) Code() string { return "payments_cashless" } +func (p *PaymentsCashlessTopic) Name() string { + return "Утверждение оплат безнал" +} + +func (p *PaymentsCashlessTopic) BuildTree() *approvalflow.FlowNode { + return &approvalflow.FlowNode{ + Key: "payments_cashless", + Label: "Утверждение оплат безнал", + Children: []*approvalflow.FlowNode{ + p.buildCategoryWithPP("goods", "Товар", + "Счет 2838 от 12.05.2026 от ООО Упаковка на сумму 2 464 700,16 руб."), + p.buildCategoryWithPP("misc", "Разное", + "Счет 2838 от 12.05.2026 от ООО Упаковка на сумму 2 464 700,16 руб."), + }, + } +} + +func (p *PaymentsCashlessTopic) buildCategoryWithPP(key, label, hint string) *approvalflow.FlowNode { + return &approvalflow.FlowNode{ + Key: key, Label: label, + DataKey: "payment_category", DataValue: key, + Children: []*approvalflow.FlowNode{ + { + Key: key + "_pp_yes", Label: "✅ Нужна ПП", + DataKey: "pp_required", DataValue: "yes", + Children: []*approvalflow.FlowNode{{ + Key: key + "_pp_yes_input", IsInput: true, + InputKey: "content", InputHint: hint, + }}, + }, + { + Key: key + "_pp_no", Label: "❌ Не нужна ПП", + DataKey: "pp_required", DataValue: "no", + Children: []*approvalflow.FlowNode{{ + Key: key + "_pp_no_input", IsInput: true, + InputKey: "content", InputHint: hint, + }}, + }, + }, + } +} + +// 🚀 TopicCodeFromCollected теперь включает pp_required в код темы +func (p *PaymentsCashlessTopic) TopicCodeFromCollected(collected map[string]string) (string, error) { + cat := collected["payment_category"] + ppRequired := collected["pp_required"] + + if cat == "" { + return "", fmt.Errorf("payment_category не указан") + } + + // 🚀 Если pp_required указан — добавляем его в код темы + if ppRequired != "" { + return fmt.Sprintf("payments_cashless_%s_pp_%s", cat, ppRequired), nil + } + return fmt.Sprintf("payments_cashless_%s", cat), nil +} + +func (p *PaymentsCashlessTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { + name := "" + if initiator.FullName != nil { + name = *initiator.FullName + } + + catLabel := map[string]string{"goods": "Товар", "misc": "Разное"}[collected["payment_category"]] + + ppLine := "" + if pp := collected["pp_required"]; pp != "" { + ppLabel := map[string]string{"yes": "✅ Нужна ПП", "no": "❌ Не нужна ПП"}[pp] + ppLine = fmt.Sprintf("\n💳 ПП: %s", ppLabel) + } + + return fmt.Sprintf( + "📋 Оплата безнал — %s%s\n\n%s:\n%s", + catLabel, ppLine, name, collected["content"], + ) +} diff --git a/service/telegram_service/handlers/approval/topics/returns/topic.go b/service/telegram_service/handlers/approval/topics/returns/topic.go index 4d89b24..ba6977c 100644 --- a/service/telegram_service/handlers/approval/topics/returns/topic.go +++ b/service/telegram_service/handlers/approval/topics/returns/topic.go @@ -39,7 +39,7 @@ func (r *ReturnsTopic) BuildTree() *approvalflow.FlowNode { Key: "supplier_crimea_input", IsInput: true, InputKey: "content", - InputHint: "Опишите возврат поставщику: товар, количество, причина", + InputHint: "Бишули\n28 гр.1881 бесцветная (9504) ПФ - 2 короба\nРеализация товаров и услуг ЧП000001326 от 20.04.2026 8:00:01\nФ1\n\nПричина: Короб приехал с завода и сильно порвался в дороге, клиент не может на свою продукцию использовать его", }, }, }, @@ -53,7 +53,7 @@ func (r *ReturnsTopic) BuildTree() *approvalflow.FlowNode { Key: "supplier_krasnodar_input", IsInput: true, InputKey: "content", - InputHint: "Опишите возврат поставщику: товар, количество, причина", + InputHint: "Бишули\n28 гр.1881 бесцветная (9504) ПФ - 2 короба\nРеализация товаров и услуг ЧП000001326 от 20.04.2026 8:00:01\nФ1\n\nПричина: Короб приехал с завода и сильно порвался в дороге, клиент не может на свою продукцию использовать его", }, }, }, @@ -75,7 +75,7 @@ func (r *ReturnsTopic) BuildTree() *approvalflow.FlowNode { Key: "other_manager_crimea_input", IsInput: true, InputKey: "content", - InputHint: "Опишите продажу другим менеджером: товар, количество, менеджер", + InputHint: "Бишули\n61 гр.38 мм бесцветная (3888) ЕП - 11 коробов\nРеализация товаров и услуг ЧП000000584 от 05.03.2026 8:00:01\nФ1\n\nПричина: Часть заказа отвалилась, будут переходить на эту позицию не раньше, чем через 3 мес\n\nПродаст выбранный менеджер на Бойко", }, }, }, @@ -89,7 +89,7 @@ func (r *ReturnsTopic) BuildTree() *approvalflow.FlowNode { Key: "other_manager_krasnodar_input", IsInput: true, InputKey: "content", - InputHint: "Опишите продажу другим менеджером: товар, количество, менеджер", + InputHint: "Бишули\n61 гр.38 мм бесцветная (3888) ЕП - 11 коробов\nРеализация товаров и услуг ЧП000000584 от 05.03.2026 8:00:01\nФ1\n\nПричина: Часть заказа отвалилась, будут переходить на эту позицию не раньше, чем через 3 мес\n\nПродаст выбранный менеджер на Бойко", }, }, }, @@ -111,7 +111,7 @@ func (r *ReturnsTopic) BuildTree() *approvalflow.FlowNode { Key: "self_sale_crimea_input", IsInput: true, InputKey: "content", - InputHint: "Опишите самостоятельную продажу: товар, количество, клиент", + InputHint: "ТД Крымэколайф\n40,5 гр.1881 бесцветная (7808) ПФ - 52 короба\nРеализация товаров и услуг ЧП000003123 от 4.08.25\nФ1\n\nПричина: для сокращения долга клиента\n\nДействия: продам ООО Нива", }, }, }, @@ -125,7 +125,7 @@ func (r *ReturnsTopic) BuildTree() *approvalflow.FlowNode { Key: "self_sale_krasnodar_input", IsInput: true, InputKey: "content", - InputHint: "Опишите самостоятельную продажу: товар, количество, клиент", + InputHint: "ТД Крымэколайф\n40,5 гр.1881 бесцветная (7808) ПФ - 52 короба\nРеализация товаров и услуг ЧП000003123 от 4.08.25\nФ1\n\nПричина: для сокращения долга клиента\n\nДействия: продам ООО Нива", }, }, }, diff --git a/service/telegram_service/handlers/approval/topics/shipments_soh/topic.go b/service/telegram_service/handlers/approval/topics/shipments_soh/topic.go index 0390df1..fa5b796 100644 --- a/service/telegram_service/handlers/approval/topics/shipments_soh/topic.go +++ b/service/telegram_service/handlers/approval/topics/shipments_soh/topic.go @@ -1,4 +1,4 @@ -package shipmentssoh +package shipments_soh import ( "bitrix_balancer_api/core/typescore" @@ -8,9 +8,7 @@ import ( type ShipmentsSOHTopic struct{} -func NewShipmentsSOHTopic() *ShipmentsSOHTopic { - return &ShipmentsSOHTopic{} -} +func NewShipmentsSOHTopic() *ShipmentsSOHTopic { return &ShipmentsSOHTopic{} } func (s *ShipmentsSOHTopic) Code() string { return "shipments_soh" } func (s *ShipmentsSOHTopic) Name() string { return "Отгрузки на СОХ" } @@ -19,45 +17,55 @@ func (s *ShipmentsSOHTopic) BuildTree() *approvalflow.FlowNode { return &approvalflow.FlowNode{ Key: "shipments_soh", Label: "Отгрузки на СОХ", + Children: []*approvalflow.FlowNode{ + s.buildRegion("crimea", "Крым"), + s.buildRegion("krasnodar", "Краснодар"), + }, + } +} + +func (s *ShipmentsSOHTopic) buildRegion(regionKey, regionLabel string) *approvalflow.FlowNode { + return &approvalflow.FlowNode{ + Key: regionKey, + Label: regionLabel, + DataKey: "region", + DataValue: regionKey, Children: []*approvalflow.FlowNode{ { - Key: "real", + Key: regionKey + "_real", Label: "Реальная", DataKey: "shipment_type", DataValue: "real", - Children: []*approvalflow.FlowNode{ - { - Key: "real_input", - IsInput: true, - InputKey: "content", - InputHint: "Опишите реальную отгрузку: товар, количество, получатель", - }, - }, + Children: []*approvalflow.FlowNode{{ + Key: regionKey + "_real_input", + IsInput: true, + InputKey: "content", + InputHint: "Прошу согласовать перемещение на СОХ\nНива ООО \n31,6 гр. 1810 бесцветная (8352) АТФ 5 кор. 7,21 руб.\n81 гр.48 мм бесцветная (2464) ОП 10 кор. 18,23 руб.\nна сумму 750 276,8 руб.\nОстаток лимита у клиента с учётом текущей задолженности 2 656 689,12 руб.", + }}, }, { - Key: "limit", + Key: regionKey + "_limit", Label: "Для лимита", DataKey: "shipment_type", DataValue: "limit", - Children: []*approvalflow.FlowNode{ - { - Key: "limit_input", - IsInput: true, - InputKey: "content", - InputHint: "Опишите отгрузку для лимита: товар, количество, цель", - }, - }, + Children: []*approvalflow.FlowNode{{ + Key: regionKey + "_limit_input", + IsInput: true, + InputKey: "content", + InputHint: "ЭКОИЛЬИЧПРОДУКТ ООО\nна сумму 750 276,8 руб\nОстаток лимита у клиента с учётом текущей задолженности 2 656 689,12 руб", + }}, }, }, } } func (s *ShipmentsSOHTopic) TopicCodeFromCollected(collected map[string]string) (string, error) { + region := collected["region"] shipmentType := collected["shipment_type"] - if shipmentType == "" { - return "", fmt.Errorf("shipment_type не указан") + if region == "" || shipmentType == "" { + return "", fmt.Errorf("неполные данные: region=%s, shipment_type=%s", region, shipmentType) } - return fmt.Sprintf("shipments_soh_%s", shipmentType), nil + return fmt.Sprintf("shipments_soh_%s_%s", region, shipmentType), nil } func (s *ShipmentsSOHTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { @@ -66,14 +74,24 @@ func (s *ShipmentsSOHTopic) FormatApproverMessage(initiator *typescore.User, col name = *initiator.FullName } - typeLabel := "Реальная" - if collected["shipment_type"] == "limit" { + regionLabel := collected["region"] + switch regionLabel { + case "crimea": + regionLabel = "Крым" + case "krasnodar": + regionLabel = "Краснодар" + } + + typeLabel := collected["shipment_type"] + switch typeLabel { + case "real": + typeLabel = "Реальная" + case "limit": typeLabel = "Для лимита" } return fmt.Sprintf( - "📋 Отгрузки на СОХ — %s\n\n"+ - "%s:\n%s", - typeLabel, name, collected["content"], + "📋 Отгрузки на СОХ — %s (%s)\n\n%s:\n%s", + regionLabel, typeLabel, name, collected["content"], ) } diff --git a/service/telegram_service/handlers/approval/topics/sick_leave/topic.go b/service/telegram_service/handlers/approval/topics/sick_leave/topic.go index ab81c27..2a4bf41 100644 --- a/service/telegram_service/handlers/approval/topics/sick_leave/topic.go +++ b/service/telegram_service/handlers/approval/topics/sick_leave/topic.go @@ -11,69 +11,56 @@ type SickLeaveTopic struct{} func NewSickLeaveTopic() *SickLeaveTopic { return &SickLeaveTopic{} } func (o *SickLeaveTopic) Code() string { return "sickleave" } -func (o *SickLeaveTopic) Name() string { return "Больничный" } +func (o *SickLeaveTopic) Name() string { return "Официальный больничный" } -// BuildTree: длительность → тип (за свой счёт / в счёт отпуска / официальный больничный). -// Официальный больничный требует прикрепить справку. func (o *SickLeaveTopic) BuildTree() *approvalflow.FlowNode { return &approvalflow.FlowNode{ Key: "sickleave", - Label: "Больничный", + Label: "Официальный больничный", Children: []*approvalflow.FlowNode{ - o.buildDuration("single_day", "На один день", - "22.02.2022"), - o.buildDuration("date_range", "Диапазон дат", - "22.02.2022 - 25.02.2022"), - o.buildDuration("multi_day", "Несколько дней", - "22.02.2022, 24.02.2022, 26.02.2022"), + { + // 🚀 Уникальный ключ: sl_open_date + Key: "sl_open_date", + IsInput: true, + InputKey: "open_date", + InputHint: "Введите дату открытия больничного листа (например: 22.02.2022)", + Children: []*approvalflow.FlowNode{ + { + // 🚀 Уникальный ключ: sl_vacation (не конфликтует с vacation-темой) + Key: "sl_vacation", Label: "В счёт отпуска", + DataKey: "payment_type", DataValue: "vacation_account", + Children: []*approvalflow.FlowNode{ + o.buildDuration("sl_single_day", "На один день", "22.02.2022"), + o.buildDuration("sl_date_range", "Диапазон дат", "22.02.2022 - 25.02.2022"), + }, + }, + { + // 🚀 Уникальный ключ: sl_official + Key: "sl_official", Label: "Только оф. больничный", + DataKey: "payment_type", DataValue: "official", + Children: []*approvalflow.FlowNode{ + o.buildDuration("sl_single_day", "На один день", "22.02.2022"), + o.buildDuration("sl_date_range", "Диапазон дат", "22.02.2022 - 25.02.2022"), + }, + }, + }, + }, }, } } +// 🚀 Все ключи теперь с префиксом sl_ func (o *SickLeaveTopic) buildDuration(durKey, durLabel, hint string) *approvalflow.FlowNode { return &approvalflow.FlowNode{ Key: durKey, Label: durLabel, - DataKey: "duration_type", DataValue: durKey, + DataKey: "duration_type", DataValue: durKey, // ⚠️ DataValue тоже с префиксом — нужно учесть в TopicCodeFromCollected Children: []*approvalflow.FlowNode{ { - Key: durKey + "_own", Label: "За свой счёт", - DataKey: "payment_type", DataValue: "own_expense", - Children: []*approvalflow.FlowNode{ - { - Key: durKey + "_own_input", - IsInput: true, - InputKey: "content", - InputHint: hint, - DataKey: "time_type", DataValue: "full_day", - }, - }, - }, - { - Key: durKey + "_vac", Label: "В счёт отпуска", - DataKey: "payment_type", DataValue: "vacation_account", - Children: []*approvalflow.FlowNode{ - { - Key: durKey + "_vac_input", - IsInput: true, - InputKey: "content", - InputHint: hint, - DataKey: "time_type", DataValue: "full_day", - }, - }, - }, - { - // Официальный больничный: сначала вводят даты, потом прикрепляют справку - Key: durKey + "_official", Label: "Официальный больничный", - DataKey: "payment_type", DataValue: "official", - Children: []*approvalflow.FlowNode{ - { - Key: durKey + "_official_input", - IsInput: true, - InputKey: "content", - InputHint: hint, - DataKey: "time_type", DataValue: "full_day", - }, - }, + Key: durKey + "_input", + IsInput: true, + InputKey: "content", + InputHint: hint, + DataKey: "time_type", DataValue: "full_day", }, }, } @@ -85,7 +72,14 @@ func (o *SickLeaveTopic) TopicCodeFromCollected(collected map[string]string) (st if dur == "" || payment == "" { return "", fmt.Errorf("неполные данные для определения темы: %v", collected) } - return fmt.Sprintf("sickleave_%s_full_day_%s", dur, payment), nil + + // 🚀 Убираем префикс sl_ из duration_type, т.к. код темы в БД без префикса + durClean := dur + if len(durClean) > 3 && durClean[:3] == "sl_" { + durClean = durClean[3:] + } + + return fmt.Sprintf("sickleave_%s_full_day_%s", durClean, payment), nil } func (o *SickLeaveTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { @@ -99,20 +93,24 @@ func (o *SickLeaveTopic) FormatApproverMessage(initiator *typescore.User, collec case "vacation_account": paymentLabel = "в счёт ежегодного отпуска" case "official": - paymentLabel = "официальный больничный (со справкой)" + paymentLabel = "только официальный больничный" default: - paymentLabel = "за свой счёт" + paymentLabel = collected["payment_type"] + } + + content := collected["content"] + openDate := collected["open_date"] + if openDate != "" { + content = fmt.Sprintf("Дата открытия больничного листа - %s.\n%s", openDate, content) } msg := fmt.Sprintf( - "📋 Тип: Больничный\n\n"+ + "📋 Тип: Официальный больничный\n\n"+ "%s: прошу согласовать больничный\n"+ "%s\n"+ "%s", - name, collected["content"], paymentLabel, + name, content, paymentLabel, ) - if collected["file_name"] != "" { - msg += fmt.Sprintf("\n📎 Справка: %s", collected["file_name"]) - } + return msg } diff --git a/service/telegram_service/handlers/approval/topics/time_off/time_off.go b/service/telegram_service/handlers/approval/topics/time_off/time_off.go index a935726..339944f 100644 --- a/service/telegram_service/handlers/approval/topics/time_off/time_off.go +++ b/service/telegram_service/handlers/approval/topics/time_off/time_off.go @@ -23,9 +23,6 @@ func (o *TimeOffTopic) BuildTree() *approvalflow.FlowNode { o.buildDuration("single_day", "На один день", "22.02.2022", "22.02.2022 с 16:00 по 18:00"), - o.buildDuration("date_range", "Диапазон дат", - "22.02.2022 - 25.02.2022", - "22.02.2022 - 25.02.2022 с 16:00 по 18:00"), o.buildDuration("multi_day", "Несколько дней", "22.02.2022, 24.02.2022, 26.02.2022", "22.02.2022 с 10:00 по 14:00, 24.02.2022 с 09:00 по 12:00"), diff --git a/service/telegram_service/handlers/approval/topics/vacation/topic.go b/service/telegram_service/handlers/approval/topics/vacation/topic.go index 21b926a..3b849af 100644 --- a/service/telegram_service/handlers/approval/topics/vacation/topic.go +++ b/service/telegram_service/handlers/approval/topics/vacation/topic.go @@ -13,32 +13,29 @@ func NewVacationTopic() *VacationTopic { return &VacationTopic{} } func (o *VacationTopic) Code() string { return "vacation" } func (o *VacationTopic) Name() string { return "Отпуск" } -// BuildTree: длительность → тип оплаты → ввод. -// Время всегда "весь день", частичный вариант недоступен. func (o *VacationTopic) BuildTree() *approvalflow.FlowNode { return &approvalflow.FlowNode{ Key: "vacation", Label: "Отпуск", Children: []*approvalflow.FlowNode{ - o.buildDuration("single_day", "На один день", "22.02.2022"), - o.buildDuration("date_range", "Диапазон дат", "22.02.2022 - 25.02.2022"), - o.buildDuration("multi_day", "Несколько дней", "22.02.2022, 24.02.2022, 26.02.2022"), + o.buildDuration("vac_single_day", "На один день", "22.02.2022", "single_day"), + o.buildDuration("vac_date_range", "Диапазон дат", "22.02.2022 - 25.02.2022", "date_range"), + o.buildDuration("vac_multi_day", "Несколько дней", "22.02.2022, 24.02.2022, 26.02.2022", "multi_day"), }, } } -func (o *VacationTopic) buildDuration(durKey, durLabel, hint string) *approvalflow.FlowNode { +func (o *VacationTopic) buildDuration(key, durLabel, hint, dataValue string) *approvalflow.FlowNode { return &approvalflow.FlowNode{ - Key: durKey, Label: durLabel, - DataKey: "duration_type", DataValue: durKey, - // time_type всегда full_day — проставляем сразу, не показываем выбор + Key: key, Label: durLabel, + DataKey: "duration_type", DataValue: dataValue, Children: []*approvalflow.FlowNode{ { - Key: durKey + "_own", Label: "За свой счёт", + Key: key + "_own", Label: "За свой счёт", DataKey: "payment_type", DataValue: "own_expense", Children: []*approvalflow.FlowNode{ { - Key: durKey + "_own_input", + Key: key + "_own_input", IsInput: true, InputKey: "content", InputHint: hint, @@ -47,11 +44,11 @@ func (o *VacationTopic) buildDuration(durKey, durLabel, hint string) *approvalfl }, }, { - Key: durKey + "_vac", Label: "В счёт отпуска", + Key: key + "_vac", Label: "В счёт отпуска", DataKey: "payment_type", DataValue: "vacation_account", Children: []*approvalflow.FlowNode{ { - Key: durKey + "_vac_input", + Key: key + "_vac_input", IsInput: true, InputKey: "content", InputHint: hint, @@ -69,6 +66,7 @@ func (o *VacationTopic) TopicCodeFromCollected(collected map[string]string) (str if dur == "" || payment == "" { return "", fmt.Errorf("неполные данные для определения темы: %v", collected) } + // 🚀 DataValue уже без префикса — ничего убирать не нужно return fmt.Sprintf("vacation_%s_full_day_%s", dur, payment), nil } diff --git a/service/telegram_service/keyboard/approval.go b/service/telegram_service/keyboard/approval.go index e52dcc3..4f7c252 100644 --- a/service/telegram_service/keyboard/approval.go +++ b/service/telegram_service/keyboard/approval.go @@ -1,5 +1,3 @@ -// telegram_service/keyboard/approval.go - ПОЛНОСТЬЮ ЗАМЕНИТЬ - package keyboard import ( @@ -12,12 +10,25 @@ import ( ) // BuildApproverDecision — кнопки для согласующего -func BuildApproverDecision(approvalID uint64) tgbotapi.InlineKeyboardMarkup { - return tgkit.NewInlineKeyboard(). - Row( - tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "Согласовать", fmt.Sprintf("appr_yes:%d", approvalID)), - tgkit.BtnStyled(tgkit.ButtonStyleDanger, "Отклонить", fmt.Sprintf("appr_no:%d", approvalID)), - ). +func BuildApproverDecision(approvalID uint64, status string, hasFiles bool, filesCount int) tgbotapi.InlineKeyboardMarkup { + kb := tgkit.NewInlineKeyboard() + + if status == "approved" { + kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleRevision, "Отозвать", fmt.Sprintf("appr_revoke:%d", approvalID))) + kb.Row(tgkit.Btn("📊 Стадия согласования", fmt.Sprintf("appr_stage:%d", approvalID))) + return kb.Build() + } + + if hasFiles { + buttonTitle := fmt.Sprintf("📎 Просмотреть файлы (%d)", filesCount) + kb.Row(tgkit.Btn(buttonTitle, fmt.Sprintf("appr_view_files:%d", approvalID))) + } + + // Для всех остальных статусов — полный набор кнопок + kb.Row( + tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "Да", fmt.Sprintf("appr_yes:%d", approvalID)), + tgkit.BtnStyled(tgkit.ButtonStyleDanger, "Нет", fmt.Sprintf("appr_no:%d", approvalID)), + ). Row(tgkit.Btn("🔄 Вернуть на доработку", fmt.Sprintf("appr_revision:%d", approvalID))). Row( tgkit.Btn("💬 Комментировать", fmt.Sprintf("appr_comment:%d", approvalID)), @@ -26,46 +37,69 @@ func BuildApproverDecision(approvalID uint64) tgbotapi.InlineKeyboardMarkup { Row( tgkit.Btn("➕ Добавить согласующего", fmt.Sprintf("add_appr_to_approval:%d", approvalID)), ). - Row(tgkit.Btn("📊 Стадия согласования", fmt.Sprintf("appr_stage:%d", approvalID))). - Build() + Row(tgkit.Btn("📊 Стадия согласования", fmt.Sprintf("appr_stage:%d", approvalID))) + + return kb.Build() } // BuildInitiatorCard — кнопки инициатора на карточке заявки -func BuildInitiatorCard(approvalID uint64) interface{} { - return tgkit.NewInlineKeyboard(). - Row( - tgkit.Btn("💬 Комментировать", fmt.Sprintf("appr_comment:%d", approvalID)), - tgkit.BtnStyled(tgkit.ButtonStyleDanger, "Отозвать", fmt.Sprintf("appr_revoke:%d", approvalID)), - ). - Row(tgkit.Btn("📊 Стадия согласования", fmt.Sprintf("appr_stage:%d", approvalID))). - Build() +func BuildInitiatorCard(approvalID uint64, status string, hasFiles bool, filesCount int) interface{} { + kb := tgkit.NewInlineKeyboard() + + if hasFiles { + buttonTitle := fmt.Sprintf("📎 Просмотреть файлы (%d)", filesCount) + kb.Row(tgkit.Btn(buttonTitle, fmt.Sprintf("appr_view_files:%d", approvalID))) + } + + if status != "approved" { + kb.Row(tgkit.Btn("💬 Комментировать", fmt.Sprintf("appr_comment:%d", approvalID))) + } + + if status == "pending" || status == "revision" || status == "approved" { + kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleRevision, "Отозвать", fmt.Sprintf("appr_revoke:%d", approvalID))) + } + + kb.Row(tgkit.Btn("📊 Стадия согласования", fmt.Sprintf("appr_stage:%d", approvalID))) + return kb.Build() } // BuildRevokeButton — кнопка отзыва (для директора и инициатора) -func BuildRevokeButton(approvalID uint64) interface{} { - return tgkit.NewInlineKeyboard(). - Row(tgkit.BtnStyled(tgkit.ButtonStyleDanger, "Отозвать заявку", fmt.Sprintf("appr_revoke:%d", approvalID))). - Row(tgkit.Btn("📊 Стадия согласования", fmt.Sprintf("appr_stage:%d", approvalID))). - Build() +func BuildRevokeButton(approvalID uint64, status string, filesCount int) interface{} { + kb := tgkit.NewInlineKeyboard() + + if filesCount > 0 { + kb.Row(tgkit.Btn(fmt.Sprintf("📎 Просмотреть файлы (%d)", filesCount), fmt.Sprintf("appr_view_files:%d", approvalID))) + } + + if status == "pending" || status == "revision" || status == "approved" { + kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleRevision, "Отозвать заявку", fmt.Sprintf("appr_revoke:%d", approvalID))) + } + + kb.Row(tgkit.Btn("📊 Стадия согласования", fmt.Sprintf("appr_stage:%d", approvalID))) + return kb.Build() } // BuildObserverActions — кнопки наблюдателя -func BuildObserverActions(approvalID uint64, topicCode string) interface{} { - return tgkit.NewInlineKeyboard(). - Row( - tgkit.Btn("🔔 Напомнить согласующему", fmt.Sprintf("obs_remind:%d", approvalID)), - ). - Row( - tgkit.Btn("💬 Комментировать", fmt.Sprintf("appr_comment:%d", approvalID)), - ). - Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "К списку", fmt.Sprintf("obs_back:%s", topicCode))). - Build() +func BuildObserverActions(approvalID uint64, topicCode string, status string, filesCount int) interface{} { + kb := tgkit.NewInlineKeyboard() + + if filesCount > 0 { + kb.Row(tgkit.Btn(fmt.Sprintf("📎 Просмотреть файлы (%d)", filesCount), fmt.Sprintf("appr_view_files:%d", approvalID))) + } + + if status != "approved" { + kb.Row(tgkit.Btn("💬 Комментировать", fmt.Sprintf("appr_comment:%d", approvalID))) + } + + kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "К списку", fmt.Sprintf("obs_back:%s", topicCode))) + return kb.Build() } // BuildExecutorTaskActions — кнопки исполнителя func BuildExecutorTaskActions(taskID, approvalID uint64) interface{} { return tgkit.NewInlineKeyboard(). Row(tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "Выполнено", fmt.Sprintf("task_complete:%d", taskID))). + Row(tgkit.Btn("📎 Прикрепить файл", fmt.Sprintf("executor_attach:%d:%d", taskID, approvalID))). Row(tgkit.Btn("💬 Комментировать", fmt.Sprintf("appr_comment:%d", approvalID))). Build() } @@ -157,29 +191,42 @@ func BuildApprovalStagesButton(approvalID uint64) interface{} { } // BuildFileInputKeyboard — управление файлами в процессе флоу -func BuildFileInputKeyboard(topicCode string, files []state.FileAttachment) interface{} { - kb := tgkit.NewInlineKeyboard() +func BuildFileInputKeyboard(topicCode string, files []state.FileAttachment, required bool) tgbotapi.InlineKeyboardMarkup { + var rows [][]tgbotapi.InlineKeyboardButton for i, f := range files { label := []rune(f.FileName) if len(label) > 25 { label = append(label[:22], []rune("...")...) } - kb.Row(tgkit.Btn("🗑 "+string(label), fmt.Sprintf("appr_file_detach:%d", i))) + rows = append(rows, tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData("🗑 "+string(label), fmt.Sprintf("appr_file_detach:%d", i)), + )) } - submitLabel := "✅ Отправить на согласование (без файлов)" - if n := len(files); n > 0 { - submitLabel = fmt.Sprintf("✅ Отправить (%s)", utilscore.PluralFiles(n)) - } - kb.Row(tgkit.Btn(submitLabel, "appr_file_submit:"+topicCode)) - if len(files) > 0 { - kb.Row(tgkit.Btn("📤 Отправить без файлов", "appr_file_skip:"+topicCode)) + submitLabel := fmt.Sprintf("✅ Отправить (%s)", utilscore.PluralFiles(len(files))) + rows = append(rows, tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData(submitLabel, "appr_file_submit:"+topicCode), + )) } - kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "Назад", "appr_back:"+topicCode)) - return kb.Build() + // Кнопка "без файлов" только если прикрепление НЕ обязательно + if !required { + skipLabel := "📤 Отправить без файлов" + if len(files) == 0 { + skipLabel = "✅ Отправить на согласование (без файлов)" + } + rows = append(rows, tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData(skipLabel, "appr_file_skip:"+topicCode), + )) + } + + rows = append(rows, tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData("← Назад", "appr_back:"+topicCode), + )) + + return tgbotapi.NewInlineKeyboardMarkup(rows...) } // BuildPendingCommentsList — список отложенных заявок @@ -265,3 +312,26 @@ func buildPageRow(page, totalPages int, prefix, noop string) []tgbotapi.InlineKe } return row } + +func BuildAttachSessionKeyboard(approvalID uint64, fileCount int) tgbotapi.InlineKeyboardMarkup { + kb := tgkit.NewInlineKeyboard() + + if fileCount > 0 { + kb.Row(tgkit.Btn( + fmt.Sprintf("✅ Отправить файлы (%d)", fileCount), + fmt.Sprintf("attach_submit:%d", approvalID), + )) + kb.Row(tgkit.Btn( + "🗑 Очистить все", + fmt.Sprintf("attach_clear:%d", approvalID), + )) + } + + kb.Row(tgkit.BtnStyled( + tgkit.ButtonStyleDanger, + "Отмена", + fmt.Sprintf("attach_cancel:%d", approvalID), + )) + + return kb.Build() +} diff --git a/service/telegram_service/keyboard/builder.go b/service/telegram_service/keyboard/builder.go index 36a4737..419a008 100644 --- a/service/telegram_service/keyboard/builder.go +++ b/service/telegram_service/keyboard/builder.go @@ -1,6 +1,10 @@ package keyboard -import tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" +import ( + "bitrix_balancer_api/core/lib/external/tgkit" + "fmt" + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" +) // ApprovalsSubmenuKeyboard - подменю "Согласования" func ApprovalsSubmenuKeyboard(isObserver, isApprover bool) tgbotapi.ReplyKeyboardMarkup { @@ -43,3 +47,18 @@ func ApprovalsListSubmenuKeyboard() tgbotapi.ReplyKeyboardMarkup { ), ) } + +// BuildCommentNotificationKeyboard — для уведомления инициатора о комментарии +func BuildCommentNotificationKeyboard(approvalID uint64) interface{} { + return tgkit.NewInlineKeyboard(). + Row(tgkit.Btn("↩️ Ответить на комментарий", fmt.Sprintf("comment_reply:%d", approvalID))). + Build() +} + +// BuildCommentReplyKeyboard — для согласующего/наблюдателя при получении ответа +func BuildCommentReplyKeyboard(approvalID uint64) interface{} { + return tgkit.NewInlineKeyboard(). + Row(tgkit.Btn("↩️ Ответить на комментарий", fmt.Sprintf("comment_reply:%d", approvalID))). + Row(tgkit.Btn("💬 Добавить комментарий", fmt.Sprintf("appr_comment:%d", approvalID))). + Build() +} diff --git a/service/telegram_service/keyboard/menu.go b/service/telegram_service/keyboard/menu.go index 8d9afb0..df8dffd 100644 --- a/service/telegram_service/keyboard/menu.go +++ b/service/telegram_service/keyboard/menu.go @@ -69,20 +69,3 @@ func BuildObserverSubmenu() tgbotapi.ReplyKeyboardMarkup { Row("← Назад"). Build() } - -func BuildFilterSubmenu(withAddApprover bool) tgbotapi.ReplyKeyboardMarkup { - kb := tgkit.NewReplyKeyboard() - - if withAddApprover { - kb.Row("Все") - kb.Row("Согласованные") - kb.Row("Не согласованные") - kb.Row("Ожидают согласования") - } else { - kb.Row("Все", "Согласованные") - kb.Row("Не согласованные", "Ожидают согласования") - } - - kb.Row("← Назад") - return kb.Build() -} diff --git a/service/telegram_service/keyboard/misc.go b/service/telegram_service/keyboard/misc.go index 35e330c..1508b00 100644 --- a/service/telegram_service/keyboard/misc.go +++ b/service/telegram_service/keyboard/misc.go @@ -67,14 +67,17 @@ func BuildFirstApproverSelectionMenu(users []*typescore.User, page int) tgbotapi return kb.Build() } -// ── Выбор наблюдателей ────────────────────────────────────────── - -func BuildObserverSelectionMenu(observers []*typescore.User, selectedIDs []uint64, page int) tgbotapi.InlineKeyboardMarkup { +func BuildObserverSelectionMenu(observers []*typescore.User, selectedIDs []uint64, page int, isRequired bool) tgbotapi.InlineKeyboardMarkup { const perPage = 8 + if len(observers) == 0 { - return tgkit.NewInlineKeyboard(). - Row(tgkit.Btn("✅ Подтвердить без наблюдателей", "obs_select_confirm")). - Build() + kb := tgkit.NewInlineKeyboard() + if isRequired { + kb.Row(tgkit.Btn("⚠️ Нет доступных наблюдателей", "obs_select_noop")) + } else { + kb.Row(tgkit.Btn("✅ Подтвердить без наблюдателей", "obs_select_confirm")) + } + return kb.Build() } total := len(observers) @@ -110,22 +113,62 @@ func BuildObserverSelectionMenu(observers []*typescore.User, selectedIDs []uint6 if totalPages > 1 { kb.Rows = append(kb.Rows, buildPageRow(page, totalPages, "obs_select_page", "obs_select_noop")) } - confirmLabel := "✅ Подтвердить" - if len(selectedIDs) > 0 { - confirmLabel = fmt.Sprintf("✅ Подтвердить (%d выбрано)", len(selectedIDs)) + + if isRequired { + if len(selectedIDs) == 0 { + kb.Row(tgkit.Btn("⚠️ Выберите хотя бы одного наблюдателя", "obs_select_confirm")) + } else { + kb.Row(tgkit.Btn( + fmt.Sprintf("✅ Подтвердить (%d выбрано)", len(selectedIDs)), + "obs_select_confirm", + )) + } + } else { + confirmLabel := "✅ Подтвердить" + if len(selectedIDs) > 0 { + confirmLabel = fmt.Sprintf("✅ Подтвердить (%d выбрано)", len(selectedIDs)) + } else { + confirmLabel = "✅ Подтвердить без наблюдателей" + } + kb.Row(tgkit.Btn(confirmLabel, "obs_select_confirm")) } - kb.Row(tgkit.Btn(confirmLabel, "obs_select_confirm")) + return kb.Build() } -// ── Наблюдатель ───────────────────────────────────────────────── - -func BuildObserverTopicMenu(topics []approvalflow.Topic) interface{} { - kb := tgkit.NewInlineKeyboard() - for _, t := range topics { - kb.Row(tgkit.Btn(t.Name(), fmt.Sprintf("obs_topic:%s", t.Code()))) +func BuildObserverTopicMenu(topics []approvalflow.Topic, page int) tgbotapi.InlineKeyboardMarkup { + const perPage = 6 + total := len(topics) + totalPages := (total + perPage - 1) / perPage + if page < 0 { + page = 0 } - return kb.Build() + if page >= totalPages && totalPages > 0 { + page = totalPages - 1 + } + start := page * perPage + end := start + perPage + if end > total { + end = total + } + + var rows [][]tgbotapi.InlineKeyboardButton + for _, t := range topics[start:end] { + rows = append(rows, tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData(t.Name(), fmt.Sprintf("obs_topic:%s", t.Code())), + )) + } + + if totalPages > 1 { + rows = append(rows, tgkit.PaginationRow( + page, totalPages, + fmt.Sprintf("obs_topic_page:%d", page-1), + fmt.Sprintf("obs_topic_page:%d", page+1), + "obs_topic_noop", + )) + } + + return tgbotapi.NewInlineKeyboardMarkup(rows...) } func BuildObserverApprovalList(approvals []*typescore.Approval, initiators map[uint64]*typescore.User, departments map[uint64]*typescore.Department) interface{} { @@ -151,22 +194,6 @@ func BuildObserverApprovalList(approvals []*typescore.Approval, initiators map[u return kb.Build() } -// ── Отчёты ────────────────────────────────────────────────────── - -func BuildReportTypeMenu() interface{} { - return tgkit.NewInlineKeyboard(). - Row(tgkit.Btn("📊 Согласования", "report_type_approvals")). - Row(tgkit.Btn("📋 Задачи", "report_type_tasks")). - Build() -} - -func BuildReportFilterMenu() interface{} { - return tgkit.NewInlineKeyboard(). - Row(tgkit.Btn("📅 Указать период", "report_set_dates")). - Row(tgkit.Btn("📤 Выгрузить за всё время", "report_all_time")). - Build() -} - func BuildReportDateToMenu() interface{} { return tgkit.NewInlineKeyboard(). Row(tgkit.Btn("📤 Выгрузить (по сегодня)", "report_generate")). @@ -196,3 +223,20 @@ func BuildRevisionAttachCancel(approvalID uint64) interface{} { Row(tgkit.BtnStyled(tgkit.ButtonStyleDanger, "Отмена", fmt.Sprintf("revision_attach_cancel:%d", approvalID))). Build() } + +func BuildRevokeTaskConfirmation(taskID uint64, approvalID uint64) tgbotapi.InlineKeyboardMarkup { + return tgbotapi.NewInlineKeyboardMarkup( + tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData( + "✅ Нет, изменений не вносил", + fmt.Sprintf("revoke_task_no_changes:%d:%d", taskID, approvalID), + ), + ), + tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData( + "⚠️ Да, изменения были", + fmt.Sprintf("revoke_task_has_changes:%d:%d", taskID, approvalID), + ), + ), + ) +} diff --git a/service/telegram_service/state/attachment.go b/service/telegram_service/state/attachment.go new file mode 100644 index 0000000..7c30522 --- /dev/null +++ b/service/telegram_service/state/attachment.go @@ -0,0 +1,46 @@ +package state + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "github.com/redis/go-redis/v9" + "time" +) + +type AttachmentSession struct { + ApprovalID uint64 `json:"approval_id"` + TaskID uint64 `json:"task_id,omitempty"` + Files []FileAttachment `json:"files"` // накапливаем + Stage string `json:"stage"` // "collecting" +} + +func (s *StateManager) SetAttachmentSession(ctx context.Context, telegramID int64, session *AttachmentSession) error { + key := fmt.Sprintf("attach_session:%d", telegramID) + data, err := json.Marshal(session) + if err != nil { + return err + } + return s.redis.Set(ctx, key, data, 30*time.Minute) +} + +func (s *StateManager) GetAttachmentSession(ctx context.Context, telegramID int64) (*AttachmentSession, error) { + key := fmt.Sprintf("attach_session:%d", telegramID) + data, err := s.redis.Get(ctx, key) + if errors.Is(err, redis.Nil) { + return nil, nil + } + if err != nil { + return nil, err + } + var session AttachmentSession + if err := json.Unmarshal([]byte(data), &session); err != nil { + return nil, err + } + return &session, nil +} + +func (s *StateManager) ClearAttachmentSession(ctx context.Context, telegramID int64) error { + return s.redis.Del(ctx, fmt.Sprintf("attach_session:%d", telegramID)) +} diff --git a/service/telegram_service/state/comment.go b/service/telegram_service/state/comment.go index a41a750..393f06d 100644 --- a/service/telegram_service/state/comment.go +++ b/service/telegram_service/state/comment.go @@ -15,6 +15,11 @@ type CommentFlowState struct { Stage string `json:"stage"` // "await_text" } +type CommentReplyState struct { + ApprovalID uint64 `json:"approval_id"` + Stage string `json:"stage"` // "await_text" +} + func (s *StateManager) SetCommentFlow(ctx context.Context, telegramID int64, state *CommentFlowState) error { key := fmt.Sprintf("comment_flow:%d", telegramID) data, err := json.Marshal(state) @@ -45,3 +50,27 @@ func (s *StateManager) ClearCommentFlow(ctx context.Context, telegramID int64) e key := fmt.Sprintf("comment_flow:%d", telegramID) return s.redis.Del(ctx, key) } + +func (s *StateManager) SetCommentReply(ctx context.Context, telegramID int64, state *CommentReplyState) error { + key := fmt.Sprintf("comment_reply:%d", telegramID) + data, _ := json.Marshal(state) + return s.redis.Set(ctx, key, data, 30*time.Minute) +} + +func (s *StateManager) GetCommentReply(ctx context.Context, telegramID int64) (*CommentReplyState, error) { + key := fmt.Sprintf("comment_reply:%d", telegramID) + data, err := s.redis.Get(ctx, key) + if errors.Is(err, redis.Nil) { + return nil, nil + } + if err != nil { + return nil, err + } + var state CommentReplyState + json.Unmarshal([]byte(data), &state) + return &state, nil +} + +func (s *StateManager) ClearCommentReply(ctx context.Context, telegramID int64) error { + return s.redis.Del(ctx, fmt.Sprintf("comment_reply:%d", telegramID)) +} diff --git a/service/telegram_service/state/state.go b/service/telegram_service/state/state.go index f2a69cb..dc336bd 100644 --- a/service/telegram_service/state/state.go +++ b/service/telegram_service/state/state.go @@ -12,23 +12,24 @@ import ( const stateTTL = 30 * time.Minute type FileAttachment struct { - Base64 string - FileName string + Base64 string + FileName string + MessageID int } // 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"` - + 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"` + FilesStepCompleted bool `json:"files_step_completed"` MultiSelected map[string][]string `json:"multi_selected,omitempty"` AwaitMultiSelectConfirm bool `json:"await_multi_select_confirm,omitempty"` MultiSelectNodeKey string `json:"multi_select_node_key,omitempty"`