Added tasks delegation #178

Merged
romanskijdev merged 1 commits from fix-permissions into main 2026-10-13 13:00:08 +03:00
13 changed files with 896 additions and 13 deletions

View File

@ -42,6 +42,7 @@ type ModuleDB struct {
AdminActionLogs *dbcore.AdminActionLogDB
SMSLog *dbcore.SmsLogDB
MonthlyOrders *dbcore.MonthlyOrderDB
TaskDelegation *dbcore.TaskDelegationDB
}
func NewModuleDB(
@ -100,6 +101,7 @@ func initDBModules(modules *ModuleDB, redisClient *redismodule.ModuleRedis) *Mod
modules.AdminActionLogs = dbcore.NewAdminActionLogDB(modules.Pool)
modules.SMSLog = dbcore.NewSmsLogDB(modules.Pool)
modules.MonthlyOrders = dbcore.NewMonthlyOrderDB(modules.Pool)
modules.TaskDelegation = dbcore.NewTaskDelegationDB(modules.Pool)
return modules
}

View File

@ -48,6 +48,7 @@ func (m *MigrationFunctions) migrateTables() error {
tablesmigration.SmsLogsTableMigrate,
tablesmigration.MonthlyOrdersTablesMigrate,
tablesmigration.TaskDelegationsTableMigrate,
}
for _, migrate := range migrations {

View File

@ -0,0 +1,63 @@
package tablesmigration
import (
"gorm.io/gorm"
"time"
)
// Вспомогательная структура для автомиграции, чтобы не тянуть зависимости
type LocalTaskDelegation struct {
ID *uint64 `gorm:"column:id;primaryKey;autoIncrement"`
DelegatorID *uint64 `gorm:"column:delegator_id;not null"`
DelegateID *uint64 `gorm:"column:delegate_id;not null"`
ValidUntil *time.Time `gorm:"column:valid_until;not null"`
IsActive *bool `gorm:"column:is_active;not null;default:true"`
NotifiedDay *bool `gorm:"column:notified_day;not null;default:false"`
Notified2h *bool `gorm:"column:notified_2h;not null;default:false"`
CreatedAt *time.Time `gorm:"column:created_at;default:CURRENT_TIMESTAMP"`
UpdatedAt *time.Time `gorm:"column:updated_at;default:CURRENT_TIMESTAMP"`
}
func (LocalTaskDelegation) TableName() string {
return "task_delegations"
}
func TaskDelegationsTableMigrate(db *gorm.DB) error {
hasTable := db.Migrator().HasTable(&LocalTaskDelegation{})
if err := db.AutoMigrate(&LocalTaskDelegation{}); err != nil {
return err
}
if !hasTable {
time.Sleep(5 * time.Second)
// Внешние ключи для связи с таблицей пользователей
db.Exec(`ALTER TABLE task_delegations ADD CONSTRAINT fk_task_delegator FOREIGN KEY (delegator_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
db.Exec(`ALTER TABLE task_delegations ADD CONSTRAINT fk_task_delegate FOREIGN KEY (delegate_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
execComments(db, `
COMMENT ON TABLE "task_delegations" IS 'Делегирование прав на задачи';
COMMENT ON COLUMN "task_delegations".id IS 'Внутренний ID записи делегирования';
COMMENT ON COLUMN "task_delegations".delegator_id IS 'ID пользователя, который передает свои задачи (делегатор)';
COMMENT ON COLUMN "task_delegations".delegate_id IS 'ID пользователя, которому передаются задачи (делегат)';
COMMENT ON COLUMN "task_delegations".valid_until IS 'Дата и время окончания делегирования';
COMMENT ON COLUMN "task_delegations".is_active IS 'Активно ли данное делегирование';
COMMENT ON COLUMN "task_delegations".notified_day IS 'Отправлено ли уведомление за день до окончания';
COMMENT ON COLUMN "task_delegations".notified_2h IS 'Отправлено ли уведомление за 2 часа до окончания';
COMMENT ON COLUMN "task_delegations".created_at IS 'Дата создания записи';
COMMENT ON COLUMN "task_delegations".updated_at IS 'Дата последнего обновления записи';
`)
}
// 🚀 Индексы для быстрого поиска активных делегирований по делегатору
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_task_delegations_delegator_active ON task_delegations (delegator_id, is_active)`)
// Индекс для поиска активных делегирований по делегату (чтобы делегат мог видеть переданные ему права)
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_task_delegations_delegate_active ON task_delegations (delegate_id, is_active)`)
// Индекс для крона/воркеров, которые будут проверять истекшие сроки и рассылать уведомления
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_task_delegations_valid_until_active ON task_delegations (valid_until, is_active)`)
return nil
}

View File

@ -0,0 +1,186 @@
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/Masterminds/squirrel"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/sirupsen/logrus"
)
type TaskDelegationDB struct {
pool *pgxpool.Pool
}
func NewTaskDelegationDB(pool *pgxpool.Pool) *TaskDelegationDB {
return &TaskDelegationDB{
pool: pool,
}
}
type TaskDelegationDBI interface {
GetTaskDelegationsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.TaskDelegation, uint64, error)
CreateTaskDelegationDB(ctx context.Context, tx pgx.Tx, TaskDelegationObj *typescore.TaskDelegation, returnObj ...bool) (*typescore.TaskDelegation, pgx.Tx, error)
UpdateTaskDelegationDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.TaskDelegation, returnObj ...bool) (*typescore.TaskDelegation, pgx.Tx, error)
DeleteTaskDelegationDB(ctx context.Context, params *typescore.TaskDelegation) error
GetTaskDelegationByIDDB(ctx context.Context, id uint64) (*typescore.TaskDelegation, error)
}
func (u *TaskDelegationDB) GetTaskDelegationsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.TaskDelegation, uint64, error) {
fields := dbutils.GetStructFieldsDB(&typescore.TaskDelegation{}, dbcoretablenames.TableNameTaskDelegations.ToString())
selectFields := append(fields, "COUNT(*) OVER() AS total_count")
options, filter, err := dbutils.GetOptionsDB[typescore.TaskDelegation](opts...)
if err != nil {
return nil, 0, err
}
query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameTaskDelegations.ToString(), selectFields)
query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameTaskDelegations.ToString())
query = query.OrderBy("created_at DESC")
sql, args, err := query.ToSql()
if err != nil {
return nil, 0, err
}
rows, err := u.pool.Query(ctx, sql, args...)
if err != nil {
return nil, 0, err
}
defer rows.Close()
var taskDelegations []*typescore.TaskDelegation
var totalCount uint64
for rows.Next() {
taskDelegation := &typescore.TaskDelegation{}
if err := dbutils.ScanRowsToStructRows(rows, taskDelegation, &totalCount); err != nil {
logrus.Warn("GetTaskDelegationsListDB:ScanRowsToStructRows", err)
continue
}
taskDelegations = append(taskDelegations, taskDelegation)
}
return taskDelegations, totalCount, nil
}
func (u *TaskDelegationDB) CreateTaskDelegationDB(ctx context.Context, tx pgx.Tx, taskDelegationObj *typescore.TaskDelegation, returnObj ...bool) (*typescore.TaskDelegation, pgx.Tx, error) {
if taskDelegationObj == nil {
return nil, nil, errors.New("TaskDelegation obj is nil")
}
var insertedID uint64
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
Insert(dbcoretablenames.TableNameTaskDelegations.ToString())
sqlV, args, err := dbutils.GenerateInsertRequest(query, taskDelegationObj)
if err != nil {
return err
}
*sqlV = *sqlV + " RETURNING id"
return tx.QueryRow(ctx, *sqlV, args...).Scan(&insertedID)
})
if err != nil {
return nil, tx, err
}
returnObjBool := len(returnObj) > 0 && returnObj[0]
if returnObjBool && insertedID > 0 {
created, err := u.GetTaskDelegationByIDDB(ctx, insertedID)
return created, tx, err
}
return nil, tx, nil
}
func (u *TaskDelegationDB) UpdateTaskDelegationDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.TaskDelegation, returnObj ...bool) (*typescore.TaskDelegation, pgx.Tx, error) {
if paramsUpdate.ID == nil {
return nil, nil, errors.New("TaskDelegation obj is nil")
}
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameTaskDelegations.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...)
if err != nil {
return err
}
return nil
})
if err != nil {
return nil, tx, err
}
returnObjBool := false
if len(returnObj) > 0 {
returnObjBool = returnObj[0]
}
if returnObjBool {
options := typescore.ListDbOptions{Filtering: &typescore.TaskDelegation{ID: paramsUpdate.ID}}
getInfoUp, _, err := u.GetTaskDelegationsListDB(ctx, options)
if err != nil {
return nil, nil, err
}
if len(getInfoUp) > 0 {
return getInfoUp[0], tx, nil
}
}
return nil, tx, nil
}
func (u *TaskDelegationDB) DeleteTaskDelegationDB(ctx context.Context, params *typescore.TaskDelegation) error {
if params != nil && params.ID != nil {
query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
Delete(dbcoretablenames.TableNameTaskDelegations.ToString()).
Where(squirrel.Eq{"id": *params.ID}).
ToSql()
if err != nil {
return err
}
rows, err := u.pool.Query(ctx, query, args...)
if err != nil {
return err
}
defer rows.Close()
return nil
} else {
return errors.New("TaskDelegation obj is nil")
}
}
func (u *TaskDelegationDB) GetTaskDelegationByIDDB(ctx context.Context, id uint64) (*typescore.TaskDelegation, error) {
taskDelegations, _, err := u.GetTaskDelegationsListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.TaskDelegation{ID: &id},
})
if err != nil {
return nil, err
}
if len(taskDelegations) == 0 {
return nil, nil
}
return taskDelegations[0], nil
}

View File

@ -35,6 +35,7 @@ const (
TableNameMonthlyOrderClients TableName = "monthly_order_clients"
TableNameMonthlyOrderItems TableName = "monthly_order_items"
TableNameMonthlyOrderFiles TableName = "monthly_order_files"
TableNameTaskDelegations TableName = "task_delegations"
)
func (t TableName) ToString() string {

View File

@ -0,0 +1,18 @@
package typescore
import "time"
type TaskDelegation struct {
ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" json:"id" db:"id"`
DelegatorID *uint64 `gorm:"type:bigint;not null;index;column:delegator_id" json:"delegator_id" db:"delegator_id"`
DelegateID *uint64 `gorm:"type:bigint;not null;index;column:delegate_id" json:"delegate_id" db:"delegate_id"`
ValidUntil *time.Time `gorm:"type:timestamp;not null;column:valid_until" json:"valid_until" db:"valid_until"`
IsActive *bool `gorm:"type:boolean;not null;default:true;column:is_active" json:"is_active" db:"is_active"`
NotifiedDay *bool `gorm:"type:boolean;not null;default:false;column:notified_day" json:"notified_day" db:"notified_day"`
Notified2h *bool `gorm:"type:boolean;not null;default:false;column:notified_2h" json:"notified_2h" db:"notified_2h"`
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"`
Delegator *User `gorm:"-" json:"delegator,omitempty"`
Delegate *User `gorm:"-" json:"delegate,omitempty"`
}

View File

@ -630,6 +630,51 @@ func (s *UpdateHandler) handleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.Callba
case strings.HasPrefix(data, "attach_cancel:"):
s.approvalHandler.HandleAttachCancel(bot, cq)
// ── ФЛОУ ДЕЛЕГИРОВАНИЯ ЗАДАЧ ──────────────────────────────────────────
case data == "deleg_main_menu":
bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck
s.approvalHandler.HandleDelegationMainMenu(bot, cq.Message.Chat.ID, cq.From.ID)
case data == "deleg_task_create":
bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck
s.approvalHandler.HandleTaskDelegationSelectUserPage(bot, cq, 0)
case strings.HasPrefix(data, "deleg_task_user_page:"):
page := 0
fmt.Sscanf(strings.TrimPrefix(data, "deleg_task_user_page:"), "%d", &page)
bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck
s.approvalHandler.HandleTaskDelegationSelectUserPage(bot, cq, page)
case strings.HasPrefix(data, "deleg_task_user:"):
delegateID := parseID(data, "deleg_task_user:")
s.approvalHandler.HandleTaskDelegationUserCallback(bot, cq, delegateID)
case data == "deleg_task_list":
bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck
s.approvalHandler.HandleTaskDelegatedRightsList(bot, cq.Message.Chat.ID, cq.From.ID)
case strings.HasPrefix(data, "deleg_task_list_page:"):
page := 0
fmt.Sscanf(strings.TrimPrefix(data, "deleg_task_list_page:"), "%d", &page)
bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
s.approvalHandler.HandleTaskDelegatedRightsListPage(bot, cq.Message.Chat.ID, cq.From.ID, page, cq.Message.MessageID)
case strings.HasPrefix(data, "deleg_task_detail:"):
delegationID := parseID(data, "deleg_task_detail:")
s.approvalHandler.HandleTaskDelegatedRightDetail(bot, cq, delegationID)
case strings.HasPrefix(data, "deleg_task_revoke:"):
delegationID := parseID(data, "deleg_task_revoke:")
s.approvalHandler.HandleTaskDelegationRevoke(bot, cq, delegationID)
case strings.HasPrefix(data, "deleg_task_extend:"):
delegationID := parseID(data, "deleg_task_extend:")
s.approvalHandler.HandleTaskDelegationExtendPrompt(bot, cq, delegationID)
// ── ПРОЧЕЕ ──────────────────────────────────────────────────
case data == "restart_bot":
bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck

View File

@ -253,6 +253,14 @@ func (s *UpdateHandler) handleMessage(bot *tgbotapi.BotAPI, msg *tgbotapi.Messag
if s.approvalHandler.HandleDelegationExtendInput(bot, msg) {
return
}
// Перехват ввода даты для создания делегирования задач
if s.approvalHandler.HandleTaskDelegationDateInput(bot, msg) {
return
}
// Перехват ввода даты для продления делегирования задач
if s.approvalHandler.HandleTaskDelegationExtendInput(bot, msg) {
return
}
s.withDepartmentCheck(bot, msg, func() {
s.approvalHandler.HandleTextInput(bot, msg)

View File

@ -278,8 +278,6 @@ func (h *Handler) HandleDelegationDateInput(bot *tgbotapi.BotAPI, msg *tgbotapi.
return true
}
// ИСПРАВЛЕНИЕ 1: Проверяем, является ли текущий пользователь делегатом
// Если да - создаём делегирование от имени оригинального согласующего
actualDelegatorID := user.ID
if delegationState.TopicID > 0 {

View File

@ -0,0 +1,414 @@
package approval
import (
"bitrix_balancer_api/core/lib/external/tgkit"
"bitrix_balancer_api/core/typescore"
"bitrix_balancer_api/core/utilscore"
"bitrix_balancer_api/telegram_service/keyboard"
"bitrix_balancer_api/telegram_service/state"
"context"
"fmt"
"strings"
"time"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"github.com/sirupsen/logrus"
)
// HandleTaskDelegationSelectUserPage показывает список сотрудников для делегирования задач
func (h *Handler) HandleTaskDelegationSelectUserPage(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, page int) {
ctx := context.Background()
chatID := cq.Message.Chat.ID
telegramID := cq.From.ID
user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
if err != nil || user == nil || user.ID == nil {
return
}
users, _, err := h.ipc.Database.User.GetUsersListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.User{
IsBlocked: utilscore.PointerToBool(false),
},
})
if err != nil {
logrus.Errorf("HandleTaskDelegationSelectUserPage: GetUsersListDB err=%v", err)
return
}
var availableUsers []*typescore.User
for _, u := range users {
if u.ID != nil && *u.ID != *user.ID {
availableUsers = append(availableUsers, u)
}
}
if len(availableUsers) == 0 {
sendText(bot, chatID, "Нет доступных пользователей для делегирования.")
return
}
msg := tgbotapi.NewMessage(chatID, "📋 <b>Делегирование задач</b>\n\nВыберите пользователя, которому хотите передать свои задачи:")
msg.ParseMode = "HTML"
msg.ReplyMarkup = keyboard.BuildTaskDelegationUserMenu(availableUsers, page)
bot.Send(msg) //nolint:errcheck
}
// HandleTaskDelegationUserCallback сохраняет выбранного делегата и запрашивает дату
func (h *Handler) HandleTaskDelegationUserCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, delegateID uint64) {
ctx := context.Background()
chatID := cq.Message.Chat.ID
telegramID := cq.From.ID
bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck
user, _ := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
if user == nil || user.ID == nil {
return
}
// Проверяем, нет ли уже активного делегирования всех задач (можно передать только одному человеку)
existingDelegations, _, err := h.ipc.Database.TaskDelegation.GetTaskDelegationsListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.TaskDelegation{
DelegatorID: user.ID,
IsActive: utilscore.PointerToBool(true),
},
})
if err == nil && len(existingDelegations) > 0 {
sendText(bot, chatID, "⚠️ <b>У вас уже есть активное делегирование задач.</b>\nСначала отзовите его в меню «Мои делегирования (Задачи)».")
return
}
// Сохраняем стейт (переиспользуем DelegationFlowState, но с особым Stage)
h.States.SetDelegation(ctx, telegramID, &state.DelegationFlowState{
DelegateID: delegateID,
Stage: "task_input_date",
}) //nolint:errcheck
delegate, _ := h.ipc.Database.User.GetUserByIDDB(ctx, delegateID)
delegateName := "—"
if delegate != nil && delegate.FullName != nil {
delegateName = *delegate.FullName
}
msg := tgbotapi.NewMessage(chatID, fmt.Sprintf(
"👤 <b>Делегат для задач:</b> %s\n\n"+
"Введите дату и время окончания делегирования в формате:\n"+
"<code>ДД.ММ.ГГГГ ЧЧ:ММ</code> или <code>ДД.ММ.ГГГГ</code>\n\n"+
"Например: <code>31.12.2024 18:00</code> или <code>31.12.2024</code>",
delegateName,
))
msg.ParseMode = "HTML"
msg.ReplyMarkup = tgkit.NewInlineKeyboard().
Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "Отмена", "deleg_task_create")).
Build()
bot.Send(msg) //nolint:errcheck
}
// HandleTaskDelegationDateInput перехватывает ввод текста с датой
func (h *Handler) HandleTaskDelegationDateInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) bool {
ctx := context.Background()
telegramID := msg.From.ID
chatID := msg.Chat.ID
delegationState, err := h.States.GetDelegation(ctx, telegramID)
if err != nil || delegationState == nil || delegationState.Stage != "task_input_date" {
return false // Не наше состояние, отдаем дальше по цепочке
}
dateStr := strings.TrimSpace(msg.Text)
var validUntil time.Time
if t, err := time.Parse("02.01.2006 15:04", dateStr); err == nil {
validUntil = t
} else if t, err := time.Parse("02.01.2006", dateStr); err == nil {
validUntil = time.Date(t.Year(), t.Month(), t.Day(), 23, 59, 59, 0, t.Location())
} else {
sendText(bot, chatID, "⚠️ Неверный формат даты. Используйте <code>ДД.ММ.ГГГГ ЧЧ:ММ</code> или <code>ДД.ММ.ГГГГ</code>")
return true // Состояние наше, но ошибка ввода
}
if validUntil.Before(time.Now()) {
sendText(bot, chatID, "⚠️ Дата окончания не может быть в прошлом.")
return true
}
user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
if err != nil || user == nil || user.ID == nil {
return true
}
isActive := true
notifiedFalse := false
delegation := &typescore.TaskDelegation{
DelegatorID: user.ID,
DelegateID: &delegationState.DelegateID,
ValidUntil: &validUntil,
IsActive: &isActive,
NotifiedDay: &notifiedFalse,
Notified2h: &notifiedFalse,
}
_, _, err = h.ipc.Database.TaskDelegation.CreateTaskDelegationDB(ctx, nil, delegation)
if err != nil {
logrus.Errorf("HandleTaskDelegationDateInput: CreateTaskDelegationDB err=%v", err)
sendText(bot, chatID, "Ошибка при создании делегирования задач.")
return true
}
h.States.ClearDelegation(ctx, telegramID) // Очищаем состояние
delegate, _ := h.ipc.Database.User.GetUserByIDDB(ctx, delegationState.DelegateID)
delegateName := "—"
if delegate != nil && delegate.FullName != nil {
delegateName = *delegate.FullName
}
sendText(bot, chatID, fmt.Sprintf(
"✅ <b>Задачи делегированы</b>\n\n"+
"👤 <b>Кому:</b> %s\n"+
"📅 <b>Действует до:</b> %s\n\n"+
"<i>Теперь все новые задачи будут приходить этому сотруднику.</i>",
delegateName, validUntil.Format("02.01.2006 15:04"),
))
// Уведомляем делегата
if delegate != nil && delegate.TelegramID != nil {
delegatorName := "—"
if user.FullName != nil {
delegatorName = *user.FullName
}
notifyMsg := tgbotapi.NewMessage(*delegate.TelegramID, fmt.Sprintf(
"🔄 <b>Вам делегировано исполнение задач</b>\n\n"+
"👤 <b>От:</b> %s\n"+
"📅 <b>До:</b> %s\n\n"+
"<i>В этот период все задачи этого пользователя будут поступать вам.</i>",
delegatorName, validUntil.Format("02.01.2006 15:04"),
))
notifyMsg.ParseMode = "HTML"
bot.Send(notifyMsg) //nolint:errcheck
}
return true
}
func (h *Handler) HandleTaskDelegatedRightsList(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) {
h.HandleTaskDelegatedRightsListPage(bot, chatID, telegramID, 0, 0)
}
func (h *Handler) HandleTaskDelegatedRightsListPage(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, page int, prevMessageID int) {
ctx := context.Background()
user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
if err != nil || user == nil || user.ID == nil {
return
}
isActive := true
delegations, _, err := h.ipc.Database.TaskDelegation.GetTaskDelegationsListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.TaskDelegation{
DelegatorID: user.ID,
IsActive: &isActive,
},
})
if err != nil {
logrus.Errorf("HandleTaskDelegatedRightsList: GetTaskDelegationsListDB err=%v", err)
sendText(bot, chatID, "Ошибка при получении списка делегирований задач.")
return
}
if len(delegations) == 0 {
sendText(bot, chatID, "У вас нет активных делегирований задач.")
return
}
if prevMessageID != 0 {
bot.Request(tgbotapi.NewDeleteMessage(chatID, prevMessageID)) //nolint:errcheck
}
msg := tgbotapi.NewMessage(chatID, fmt.Sprintf("📋 <b>Делегированные задачи (%d)</b>\n\nВыберите запись:", len(delegations)))
msg.ParseMode = "HTML"
msg.ReplyMarkup = keyboard.BuildTaskDelegatedRightsList(delegations, page, ctx, h.ipc)
bot.Send(msg) //nolint:errcheck
}
func (h *Handler) HandleTaskDelegatedRightDetail(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, delegationID 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
delegation, err := h.ipc.Database.TaskDelegation.GetTaskDelegationByIDDB(ctx, delegationID)
if err != nil || delegation == nil {
sendText(bot, chatID, "⚠️ Делегирование не найдено.")
return
}
delegateName := "—"
if delegation.DelegateID != nil {
delegate, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *delegation.DelegateID)
if delegate != nil && delegate.FullName != nil {
delegateName = *delegate.FullName
}
}
validUntil := "—"
if delegation.ValidUntil != nil {
validUntil = delegation.ValidUntil.Format("02.01.2006 15:04")
}
text := fmt.Sprintf(
"📋 <b>Делегирование задач #%d</b>\n\n"+
"👤 <b>Делегат:</b> %s\n"+
"📅 <b>Действует до:</b> %s",
delegationID, delegateName, validUntil,
)
msg := tgbotapi.NewMessage(chatID, text)
msg.ParseMode = "HTML"
msg.ReplyMarkup = keyboard.BuildTaskDelegationActions(delegationID)
bot.Send(msg) //nolint:errcheck
}
func (h *Handler) HandleTaskDelegationRevoke(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, delegationID 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
delegation, err := h.ipc.Database.TaskDelegation.GetTaskDelegationByIDDB(ctx, delegationID)
if err != nil || delegation == nil {
sendText(bot, chatID, "⚠️ Делегирование не найдено.")
return
}
now := time.Now()
isActive := false
delegation.ValidUntil = &now
delegation.IsActive = &isActive
_, _, err = h.ipc.Database.TaskDelegation.UpdateTaskDelegationDB(ctx, nil, delegation)
if err != nil {
logrus.Errorf("HandleTaskDelegationRevoke: UpdateTaskDelegationDB err=%v", err)
sendText(bot, chatID, "Ошибка при отзыве делегирования.")
return
}
sendText(bot, chatID, "✅ <b>Делегирование задач досрочно отозвано.</b>\nТеперь новые задачи будут приходить вам.")
// Уведомляем делегата
if delegation.DelegateID != nil {
delegate, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *delegation.DelegateID)
if delegate != nil && delegate.TelegramID != nil {
notifyMsg := tgbotapi.NewMessage(*delegate.TelegramID, "⚠️ <b>Делегирование задач отозвано</b>\n\nВам больше не будут приходить задачи этого пользователя.")
notifyMsg.ParseMode = "HTML"
bot.Send(notifyMsg) //nolint:errcheck
}
}
}
func (h *Handler) HandleTaskDelegationExtendPrompt(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, delegationID 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
delegation, err := h.ipc.Database.TaskDelegation.GetTaskDelegationByIDDB(ctx, delegationID)
if err != nil || delegation == nil {
sendText(bot, chatID, "⚠️ Делегирование не найдено.")
return
}
// Сохраняем ID делегирования для продления (с другим ключом, чтобы не пересекаться с заявками)
extendKey := fmt.Sprintf("task_deleg_extend:%d", telegramID)
h.ipc.RedisClient.Set(ctx, extendKey, fmt.Sprintf("%d", delegationID), 10*time.Minute) //nolint:errcheck
msg := tgbotapi.NewMessage(chatID,
"Введите новую дату окончания в формате:\n"+
"<code>ДД.ММ.ГГГГ ЧЧ:ММ</code> или <code>ДД.ММ.ГГГГ</code>")
msg.ParseMode = "HTML"
msg.ReplyMarkup = keyboard.BuildTaskDelegationExtendCancel(delegationID)
bot.Send(msg) //nolint:errcheck
}
func (h *Handler) HandleTaskDelegationExtendInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) bool {
ctx := context.Background()
telegramID := msg.From.ID
chatID := msg.Chat.ID
extendKey := fmt.Sprintf("task_deleg_extend:%d", telegramID)
raw, err := h.ipc.RedisClient.Get(ctx, extendKey)
if err != nil || raw == "" {
return false
}
var delegationID uint64
fmt.Sscanf(raw, "%d", &delegationID)
dateStr := strings.TrimSpace(msg.Text)
var validUntil time.Time
if t, err := time.Parse("02.01.2006 15:04", dateStr); err == nil {
validUntil = t
} else if t, err := time.Parse("02.01.2006", dateStr); err == nil {
validUntil = time.Date(t.Year(), t.Month(), t.Day(), 23, 59, 59, 0, t.Location())
} else {
sendText(bot, chatID, "⚠️ Неверный формат даты. Используйте <code>ДД.ММ.ГГГГ ЧЧ:ММ</code> или <code>ДД.ММ.ГГГГ</code>")
return true
}
if validUntil.Before(time.Now()) {
sendText(bot, chatID, "⚠️ Дата окончания не может быть в прошлом.")
return true
}
delegation, err := h.ipc.Database.TaskDelegation.GetTaskDelegationByIDDB(ctx, delegationID)
if err != nil || delegation == nil {
sendText(bot, chatID, "⚠️ Делегирование не найдено.")
h.ipc.RedisClient.Del(ctx, extendKey) //nolint:errcheck
return true
}
delegation.ValidUntil = &validUntil
notifiedDay := false
notified2h := false
delegation.NotifiedDay = &notifiedDay
delegation.Notified2h = &notified2h
_, _, err = h.ipc.Database.TaskDelegation.UpdateTaskDelegationDB(ctx, nil, delegation)
if err != nil {
logrus.Errorf("HandleTaskDelegationExtendInput: UpdateTaskDelegationDB err=%v", err)
sendText(bot, chatID, "Ошибка при продлении делегирования задач.")
h.ipc.RedisClient.Del(ctx, extendKey) //nolint:errcheck
return true
}
h.ipc.RedisClient.Del(ctx, extendKey) //nolint:errcheck
sendText(bot, chatID, fmt.Sprintf(
"✅ <b>Срок делегирования задач изменён.</b>\n\n"+
"📅 <b>Новый срок:</b> %s",
validUntil.Format("02.01.2006 15:04"),
))
// Уведомляем делегата
if delegation.DelegateID != nil {
delegate, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *delegation.DelegateID)
if delegate != nil && delegate.TelegramID != nil {
notifyMsg := tgbotapi.NewMessage(*delegate.TelegramID, fmt.Sprintf(
"🔄 <b>Срок делегирования задач изменён.</b>\n\n"+
"📅 <b>Новый срок:</b> %s",
validUntil.Format("02.01.2006 15:04"),
))
notifyMsg.ParseMode = "HTML"
bot.Send(notifyMsg) //nolint:errcheck
}
}
return true
}

View File

@ -256,6 +256,7 @@ func (h *Handler) HandleCompleteTask(bot *tgbotapi.BotAPI, cq *tgbotapi.Callback
}
}
// activateNextTask активирует следующую задачу в очереди после завершения текущей
// 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 {
@ -283,21 +284,38 @@ func (h *Handler) activateNextTask(bot *tgbotapi.BotAPI, ctx context.Context, ap
return
}
originalExecutor, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *nextTask.ExecutorID)
var actualExecutor *typescore.User
if originalExecutor != nil {
actual, isDelegated, orig := h.getActualTaskExecutor(ctx, originalExecutor)
actualExecutor = actual
// Если за время ожидания задачи человек ушел в отпуск/делегировал права,
// перезаписываем ExecutorID и текст задачи
if isDelegated && orig != nil && orig.FullName != nil {
nextTask.ExecutorID = actual.ID
newText := fmt.Sprintf("[Делегировано от: %s]\n%s", *orig.FullName, *nextTask.TaskText)
nextTask.TaskText = &newText
}
}
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 {
// Уведомляем АКТУАЛЬНОГО исполнителя
if actualExecutor != nil && actualExecutor.TelegramID != nil {
initiator, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID)
if initiator == nil {
return
}
h.notifyExecutor(bot, ctx, executor, initiator, approval, nextTask)
h.notifyExecutor(bot, ctx, actualExecutor, initiator, approval, nextTask)
}
}

View File

@ -2,11 +2,13 @@ package approval
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"
"strings"
"time"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"github.com/sirupsen/logrus"
@ -403,6 +405,33 @@ func (h *Handler) sendConfirmationCard(bot *tgbotapi.BotAPI, ctx context.Context
bot.Send(msgChat) //nolint:errcheck
}
// getActualTaskExecutor проверяет, не делегировал ли оригинальный исполнитель свои задачи.
// Возвращает: (Актуальный исполнитель, Было ли делегирование, Оригинальный исполнитель)
func (h *Handler) getActualTaskExecutor(ctx context.Context, originalExecutor *typescore.User) (*typescore.User, bool, *typescore.User) {
if originalExecutor == nil || originalExecutor.ID == nil {
return originalExecutor, false, nil
}
delegations, _, err := h.ipc.Database.TaskDelegation.GetTaskDelegationsListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.TaskDelegation{
DelegatorID: originalExecutor.ID,
IsActive: utilscore.PointerToBool(true),
},
})
if err == nil && len(delegations) > 0 {
deleg := delegations[0]
if deleg.ValidUntil != nil && deleg.ValidUntil.After(time.Now()) && deleg.DelegateID != nil {
delegateUser, err := h.ipc.Database.User.GetUserByIDDB(ctx, *deleg.DelegateID)
if err == nil && delegateUser != nil {
return delegateUser, true, originalExecutor
}
}
}
return originalExecutor, false, nil
}
// createTasksForApproval создаёт задачи для исполнителей на основе конфигурации темы
func (h *Handler) createTasksForApproval(
bot *tgbotapi.BotAPI,
@ -441,6 +470,8 @@ func (h *Handler) createTasksForApproval(
taskCounter := 0
// ... (начало метода createTasksForApproval остается без изменений) ...
for _, system := range systemsToProcess {
for _, topicExec := range topicExecutors {
if topicExec.UserID == nil {
@ -455,12 +486,21 @@ func (h *Handler) createTasksForApproval(
continue
}
executor, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *topicExec.UserID)
if executor == nil || executor.ID == nil {
originalExecutor, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *topicExec.UserID)
if originalExecutor == nil || originalExecutor.ID == nil {
continue
}
// 🚀 ПРОВЕРКА ДЕЛЕГИРОВАНИЯ
actualExecutor, isDelegated, origExec := h.getActualTaskExecutor(ctx, originalExecutor)
taskText := *topicExec.TaskText
// Если задача делегирована, добавляем пометку в текст задачи
if isDelegated && origExec != nil && origExec.FullName != nil {
taskText = fmt.Sprintf("[Делегировано от: %s]\n%s", *origExec.FullName, taskText)
}
systemLabel := ""
if system != "all" && system != "" {
switch system {
@ -483,22 +523,25 @@ func (h *Handler) createTasksForApproval(
requireFile = *topicExec.RequireFile
}
// Создаем задачу на АКТУАЛЬНОГО исполнителя
createdTask, _, err := h.ipc.Database.ApprovalTasks.CreateApprovalTaskDB(ctx, nil, &typescore.ApprovalTask{
ApprovalID: approval.ID,
ExecutorID: executor.ID,
ExecutorID: actualExecutor.ID, // <--- Подменённый 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)
logrus.Errorf("createTasksForApproval: CreateApprovalTask system=%s executor=%d err=%v", system, *actualExecutor.ID, err)
continue
}
if createdTask != nil && taskStatus == "pending" && executor.TelegramID != nil {
h.notifyExecutor(bot, ctx, executor, initiator, approval, createdTask)
// Уведомляем АКТУАЛЬНОГО исполнителя
if createdTask != nil && taskStatus == "pending" && actualExecutor.TelegramID != nil {
h.notifyExecutor(bot, ctx, actualExecutor, initiator, approval, createdTask)
}
taskCounter++

View File

@ -15,8 +15,10 @@ const delegationPerPage = 6
func BuildDelegationMainMenu() interface{} {
return tgkit.NewInlineKeyboard().
Row(tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "Делегировать права", "deleg_create")).
Row(tgkit.Btn("📋 Делегированные права", "deleg_list")).
Row(tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "Делегировать заявки", "deleg_create")).
Row(tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "Делегировать задачи", "deleg_task_create")).
Row(tgkit.Btn("📋 Мои делегирования (Заявки)", "deleg_list")).
Row(tgkit.Btn("📋 Мои делегирования (Задачи)", "deleg_task_list")).
Build()
}
@ -170,3 +172,87 @@ func BuildDelegationBackToUsers(categoryID, topicID uint64) tgbotapi.InlineKeybo
Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "Назад", callback)).
Build()
}
// --- КЛАВИАТУРЫ ДЛЯ ДЕЛЕГИРОВАНИЯ ЗАДАЧ ---
// BuildTaskDelegationUserMenu выводит список пользователей для передачи задач
func BuildTaskDelegationUserMenu(users []*typescore.User, page int) interface{} {
const perPage = 8
total := len(users)
totalPages := (total + perPage - 1) / perPage
if page < 0 {
page = 0
}
if page >= totalPages && totalPages > 0 {
page = totalPages - 1
}
start, end := page*perPage, page*perPage+perPage
if end > total {
end = total
}
kb := tgkit.NewInlineKeyboard()
for _, u := range users[start:end] {
if u.ID == nil || u.FullName == nil {
continue
}
kb.Row(tgkit.Btn(*u.FullName, fmt.Sprintf("deleg_task_user:%d", *u.ID)))
}
if totalPages > 1 {
kb.Rows = append(kb.Rows, buildPageRow(page, totalPages, "deleg_task_user_page", "deleg_page_noop"))
}
// Кнопка возврата в главное меню делегирования
kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "Назад", "deleg_main_menu"))
return kb.Build()
}
// BuildTaskDelegatedRightsList выводит список ваших активных делегирований задач
func BuildTaskDelegatedRightsList(delegations []*typescore.TaskDelegation, page int, ctx context.Context, ipc *types.InternalProviderControl) interface{} {
const perPage = 6
total := len(delegations)
totalPages := (total + perPage - 1) / perPage
if page < 0 {
page = 0
}
if page >= totalPages && totalPages > 0 {
page = totalPages - 1
}
start, end := page*perPage, page*perPage+perPage
if end > total {
end = total
}
kb := tgkit.NewInlineKeyboard()
for _, d := range delegations[start:end] {
if d.ID == nil || d.DelegateID == nil {
continue
}
delegateName := "Неизвестно"
if u, _ := ipc.Database.User.GetUserByIDDB(ctx, *d.DelegateID); u != nil && u.FullName != nil {
delegateName = *u.FullName
}
kb.Row(tgkit.Btn(fmt.Sprintf("Задачи ➡️ %s", delegateName), fmt.Sprintf("deleg_task_detail:%d", *d.ID)))
}
if totalPages > 1 {
kb.Rows = append(kb.Rows, buildPageRow(page, totalPages, "deleg_task_list_page", "deleg_page_noop"))
}
kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "В главное меню", "deleg_main_menu"))
return kb.Build()
}
// BuildTaskDelegationActions выводит кнопки управления (Отозвать/Продлить) конкретным делегированием задач
func BuildTaskDelegationActions(delegationID uint64) interface{} {
return tgkit.NewInlineKeyboard().
Row(tgkit.Btn("📅 Изменить срок", fmt.Sprintf("deleg_task_extend:%d", delegationID))).
Row(tgkit.BtnStyled(tgkit.ButtonStyleDanger, "Отозвать делегирование", fmt.Sprintf("deleg_task_revoke:%d", delegationID))).
Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "К списку", "deleg_task_list")).
Build()
}
// BuildTaskDelegationExtendCancel кнопка отмены при вводе новой даты
func BuildTaskDelegationExtendCancel(delegationID uint64) interface{} {
return tgkit.NewInlineKeyboard().
Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "Отмена", fmt.Sprintf("deleg_task_detail:%d", delegationID))).
Build()
}