fix-permissions #179

Merged
romanskijdev merged 2 commits from fix-permissions into main 2026-10-13 14:51:33 +03:00
6 changed files with 336 additions and 201 deletions

View File

@ -12,6 +12,7 @@ type TaskDelegation struct {
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"`
ApprovalID *uint64 `gorm:"type:bigint;index;column:approval_id" json:"approval_id,omitempty" db:"approval_id"`
Delegator *User `gorm:"-" json:"delegator,omitempty"`
Delegate *User `gorm:"-" json:"delegate,omitempty"`

View File

@ -675,6 +675,14 @@ func (s *UpdateHandler) handleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.Callba
delegationID := parseID(data, "deleg_task_extend:")
s.approvalHandler.HandleTaskDelegationExtendPrompt(bot, cq, delegationID)
case data == "appr_task_deleg_yes":
s.approvalHandler.HandleTaskDelegationChoiceAbsence(bot, cq, true)
case data == "appr_task_deleg_no":
s.approvalHandler.HandleTaskDelegationChoiceAbsence(bot, cq, false)
case strings.HasPrefix(data, "appr_task_deleg_sel:"):
id := parseID(data, "appr_task_deleg_sel:")
s.approvalHandler.HandleTaskDelegateSelectionAbsence(bot, cq, id)
// ── ПРОЧЕЕ ──────────────────────────────────────────────────
case data == "restart_bot":
bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck

View File

@ -8,6 +8,7 @@ import (
"context"
"fmt"
"regexp"
"sort"
"strconv"
"time"
@ -16,29 +17,12 @@ import (
)
// ============================================================
// Делегирование обязанностей на время отсутствия (отгул/отпуск/
// больничный). Включается флагом ApprovalTopic.AllowDelegationSelection
// (тот же паттерн, что AllowObserverSelection) — см. DELEGATION_PATCHES.txt.
//
// 🩹 Жизненный цикл делегирования (важное отличие от первой версии):
// запись ApprovalDelegation создаётся СРАЗУ при подаче заявки на
// отсутствие, но НЕАКТИВНОЙ (IsActive=false) — см. createPendingDelegation,
// вызывается из submitApproval. Активируется она ТОЛЬКО когда сама заявка
// будет полностью согласована — activatePendingDelegation, вызывается из
// processNextStepOrComplete в момент финального approved. Если заявку
// впоследствии отзовут — deactivatePendingDelegation (вызывается из
// performActualRevoke) выключает делегирование обратно, независимо от
// того, успело оно активироваться или нет.
//
// Здесь, в диалоге с ботом, происходит только ВЫБОР делегата — реальная
// запись в БД появляется позже, вместе с самой заявкой.
// Делегирование ЗАЯВОК на время отсутствия
// ============================================================
// showDelegationChoice — экран "делегировать все обязанности?" (Да/Нет).
func (h *Handler) showDelegationChoice(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) {
text := "🔁 <b>Делегировать все обязанности по согласованию на другого человека на время вашего отсутствия?</b>\n\n" +
"<i>Делегирование начнёт действовать только после того, как эта заявка будет согласована, " +
"и автоматически отменится, если заявку впоследствии отзовут.</i>"
text := "🔁 <b>Шаг 1/2: Делегирование ЗАЯВОК</b>\n\n" +
"Делегировать ваши права как согласующего по заявкам на время вашего отсутствия?"
msg := tgbotapi.NewMessage(chatID, text)
msg.ParseMode = "HTML"
@ -46,7 +30,6 @@ func (h *Handler) showDelegationChoice(bot *tgbotapi.BotAPI, chatID int64, teleg
bot.Send(msg) //nolint:errcheck
}
// HandleDelegationChoiceCallback — пользователь ответил Да/Нет на вопрос о делегировании.
func (h *Handler) HandleDelegationChoiceCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, wantsDelegate bool) {
ctx := context.Background()
chatID := cq.Message.Chat.ID
@ -61,25 +44,17 @@ func (h *Handler) HandleDelegationChoiceCallback(bot *tgbotapi.BotAPI, cq *tgbot
}
if !wantsDelegate {
flowState.AwaitDelegationChoice = false
flowState.DelegationSelectionDone = true
h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
sendText(bot, chatID, "☑️ Хорошо — обязанности не делегируются, вы решаете вопросы согласования самостоятельно.")
h.continueFlowAfterInput(bot, ctx, chatID, telegramID, flowState)
sendText(bot, chatID, "☑️ Хорошо — права по заявкам не делегируются.")
h.showTaskDelegationChoice(bot, chatID, telegramID, flowState)
return
}
candidates, err := h.getAvailableDelegateCandidates(ctx, telegramID)
if err != nil {
logrus.Errorf("HandleDelegationChoiceCallback: getAvailableDelegateCandidates err=%v", err)
}
if len(candidates) == 0 {
sendText(bot, chatID, "⚠️ Нет доступных сотрудников для делегирования. Обязанности остаются на вас.")
flowState.AwaitDelegationChoice = false
if err != nil || len(candidates) == 0 {
sendText(bot, chatID, "⚠️ Нет доступных сотрудников для делегирования. Права остаются на вас.")
flowState.DelegationSelectionDone = true
h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
h.continueFlowAfterInput(bot, ctx, chatID, telegramID, flowState)
h.showTaskDelegationChoice(bot, chatID, telegramID, flowState)
return
}
@ -87,46 +62,24 @@ func (h *Handler) HandleDelegationChoiceCallback(bot *tgbotapi.BotAPI, cq *tgbot
flowState.AwaitDelegateSelection = true
h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
msg := tgbotapi.NewMessage(chatID, "👤 <b>Выберите, кому передать обязанности:</b>")
msg := tgbotapi.NewMessage(chatID, "👤 <b>Кому передать права по заявкам:</b>")
msg.ParseMode = "HTML"
msg.ReplyMarkup = keyboard.BuildDelegateSelectionMenu(candidates, 0)
bot.Send(msg) //nolint:errcheck
}
// HandleDelegateSelectionPageCallback — пагинация списка кандидатов.
func (h *Handler) HandleDelegateSelectionPageCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, page int) {
ctx := context.Background()
chatID := cq.Message.Chat.ID
telegramID := cq.From.ID
bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
flowState, err := h.States.Get(ctx, telegramID)
if err != nil || flowState == nil || !flowState.AwaitDelegateSelection {
return
}
candidates, err := h.getAvailableDelegateCandidates(ctx, telegramID)
if err != nil {
return
}
editMsg := tgbotapi.NewEditMessageReplyMarkup(
chatID,
candidates, _ := h.getAvailableDelegateCandidates(ctx, cq.From.ID)
bot.Request(tgbotapi.NewEditMessageReplyMarkup(
cq.Message.Chat.ID,
cq.Message.MessageID,
keyboard.BuildDelegateSelectionMenu(candidates, page),
)
bot.Request(editMsg) //nolint:errcheck
)) //nolint:errcheck
}
// HandleDelegateSelectionCallback — пользователь выбрал конкретного делегата.
//
// 🩹 ВАЖНО: здесь запись в ApprovalDelegation больше НЕ создаётся. Мы
// только запоминаем выбор в flowState.SelectedDelegateID — реальная
// (неактивная) запись появится в submitApproval/createPendingDelegation,
// когда заявка будет фактически отправлена (это происходит сразу вслед
// за этим шагом в том же диалоге, так что 30-минутный TTL состояния в
// Redis не успевает истечь).
func (h *Handler) HandleDelegateSelectionCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, delegateID uint64) {
ctx := context.Background()
chatID := cq.Message.Chat.ID
@ -140,37 +93,119 @@ func (h *Handler) HandleDelegateSelectionCallback(bot *tgbotapi.BotAPI, cq *tgbo
return
}
delegate, err := h.ipc.Database.User.GetUserByIDDB(ctx, delegateID)
if err != nil || delegate == nil {
sendText(bot, chatID, "⚠️ Сотрудник не найден.")
return
}
flowState.AwaitDelegateSelection = false
flowState.DelegationSelectionDone = true
flowState.SelectedDelegateID = delegateID
h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
delegate, _ := h.ipc.Database.User.GetUserByIDDB(ctx, delegateID)
delegateName := "—"
if delegate.FullName != nil {
if delegate != nil && delegate.FullName != nil {
delegateName = *delegate.FullName
}
// Дата — только для информации в этом сообщении, реальное значение
// пересчитывается и сохраняется в createPendingDelegation.
validUntil, _ := delegationValidUntil(flowState.Collected)
flowState.DelegationSelectionDone = true
flowState.SelectedDelegateID = delegateID
sendText(bot, chatID, fmt.Sprintf(
"🔁 <b>Обязанности будут делегированы: %s</b>\n"+
"📅 <b>Ориентировочно до:</b> %s\n\n"+
"<i>Начнёт действовать после согласования этой заявки и отменится, если её впоследствии отзовут.</i>",
delegateName, validUntil.Format("02.01.2006"),
))
sendText(bot, chatID, fmt.Sprintf("🔁 <b>Права по заявкам будут делегированы:</b> %s", delegateName))
h.showTaskDelegationChoice(bot, chatID, telegramID, flowState)
}
// ============================================================
// Делегирование ЗАДАЧ на время отсутствия (НОВЫЙ БЛОК)
// ============================================================
func (h *Handler) showTaskDelegationChoice(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, flowState *state.ApprovalFlowState) {
ctx := context.Background()
flowState.AwaitDelegationChoice = false
flowState.AwaitDelegateSelection = false
flowState.AwaitTaskDelegationChoice = true
h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
text := "🔁 <b>Шаг 2/2: Делегирование ЗАДАЧ</b>\n\n" +
"Хотите также передать исполнение ваших задач другому сотруднику на время отсутствия?\n\n" +
"<i>Делегирование (и заявок, и задач) вступит в силу автоматически после согласования отпуска.</i>"
msg := tgbotapi.NewMessage(chatID, text)
msg.ParseMode = "HTML"
msg.ReplyMarkup = keyboard.BuildTaskDelegationChoiceMenu() // Кнопки appr_task_deleg_yes / no
bot.Send(msg) //nolint:errcheck
}
func (h *Handler) HandleTaskDelegationChoiceAbsence(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, wantsDelegate bool) {
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
flowState, err := h.States.Get(ctx, telegramID)
if err != nil || flowState == nil || !flowState.AwaitTaskDelegationChoice {
return
}
if !wantsDelegate {
flowState.TaskDelegationSelectionDone = true
flowState.AwaitTaskDelegationChoice = false
h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
sendText(bot, chatID, "☑️ Хорошо — задачи не делегируются.")
h.continueFlowAfterInput(bot, ctx, chatID, telegramID, flowState)
return
}
candidates, err := h.getAvailableDelegateCandidates(ctx, telegramID)
if err != nil || len(candidates) == 0 {
sendText(bot, chatID, "⚠️ Нет доступных сотрудников для делегирования. Задачи остаются на вас.")
flowState.TaskDelegationSelectionDone = true
flowState.AwaitTaskDelegationChoice = false
h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
h.continueFlowAfterInput(bot, ctx, chatID, telegramID, flowState)
return
}
flowState.AwaitTaskDelegationChoice = false
flowState.AwaitTaskDelegateSelection = true
h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
msg := tgbotapi.NewMessage(chatID, "👤 <b>Кому передать исполнение задач:</b>")
msg.ParseMode = "HTML"
msg.ReplyMarkup = keyboard.BuildAbsenceTaskDelegateMenu(candidates, 0)
bot.Send(msg) //nolint:errcheck
}
func (h *Handler) HandleTaskDelegateSelectionAbsence(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
flowState, err := h.States.Get(ctx, telegramID)
if err != nil || flowState == nil || !flowState.AwaitTaskDelegateSelection {
return
}
delegate, _ := h.ipc.Database.User.GetUserByIDDB(ctx, delegateID)
delegateName := "—"
if delegate != nil && delegate.FullName != nil {
delegateName = *delegate.FullName
}
flowState.TaskDelegationSelectionDone = true
flowState.AwaitTaskDelegateSelection = false
flowState.SelectedTaskDelegateID = delegateID
h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
sendText(bot, chatID, fmt.Sprintf("🔁 <b>Исполнение задач будет делегировано:</b> %s", delegateName))
h.continueFlowAfterInput(bot, ctx, chatID, telegramID, flowState)
}
// getAvailableDelegateCandidates — все активные сотрудники, кроме самого пользователя.
// ============================================================
// Вспомогательные методы и логика БД
// ============================================================
// getAvailableDelegateCandidates возвращает список активных сотрудников,
// ОТСОРТИРОВАННЫХ ПО АЛФАВИТУ.
func (h *Handler) getAvailableDelegateCandidates(ctx context.Context, telegramID int64) ([]*typescore.User, error) {
me, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
if err != nil || me == nil || me.ID == nil {
@ -179,6 +214,7 @@ func (h *Handler) getAvailableDelegateCandidates(ctx context.Context, telegramID
users, _, err := h.ipc.Database.User.GetUsersListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.User{IsBlocked: utilscore.PointerToBool(false)},
Limit: utilscore.PointerToUint64(1000), // На случай большого штата
})
if err != nil {
return nil, err
@ -194,156 +230,127 @@ func (h *Handler) getAvailableDelegateCandidates(ctx context.Context, telegramID
}
result = append(result, u)
}
// 🚀 Сортировка списка по алфавиту (по FullName)
sort.Slice(result, func(i, j int) bool {
nameI, nameJ := "", ""
if result[i].FullName != nil {
nameI = *result[i].FullName
}
if result[j].FullName != nil {
nameJ = *result[j].FullName
}
return nameI < nameJ
})
return result, nil
}
// ============================================================
// Создание / активация / деактивация делегирования, привязанного к
// конкретной заявке (approval_id — см. DELEGATION_PATCHES.txt).
// ============================================================
// createPendingDelegation вызывается из submitApproval сразу после
// создания заявки. Создаёт по одной НЕАКТИВНОЙ записи ApprovalDelegation
// на каждую активную категорию согласований (поиск делегата в
// processNextStepOrComplete/handleDecision матчит строго по конкретному
// TopicID либо конкретному CategoryID — запись "на всё сразу" с обоими
// NULL никогда бы не нашлась).
func (h *Handler) createPendingDelegation(ctx context.Context, initiator *typescore.User, flowState *state.ApprovalFlowState, approval *typescore.Approval) {
if flowState.SelectedDelegateID == 0 {
return
}
if initiator == nil || initiator.ID == nil || approval == nil || approval.ID == nil {
return
}
delegate, err := h.ipc.Database.User.GetUserByIDDB(ctx, flowState.SelectedDelegateID)
if err != nil || delegate == nil || delegate.ID == nil {
logrus.Errorf("createPendingDelegation: delegate not found id=%d err=%v", flowState.SelectedDelegateID, err)
return
}
validUntil, datesFound := delegationValidUntil(flowState.Collected)
if !datesFound {
logrus.Warnf("createPendingDelegation: не удалось определить дату окончания отсутствия approvalID=%d — используется запасной срок 30 дней", *approval.ID)
}
categories, _, err := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.ApprovalTopicCategory{IsActive: utilscore.PointerToBool(true)},
})
if err != nil {
logrus.Errorf("createPendingDelegation: GetApprovalTopicCategoriesListDB err=%v", err)
return
logrus.Warnf("createPendingDelegation: дата окончания не найдена approvalID=%d", *approval.ID)
}
inactive := false
notifiedFalse := false
created := 0
for _, cat := range categories {
if cat.ID == nil {
continue
// 1. Создаем отложенное делегирование ЗАЯВОК
if flowState.SelectedDelegateID != 0 {
categories, _, _ := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.ApprovalTopicCategory{IsActive: utilscore.PointerToBool(true)},
})
for _, cat := range categories {
if cat.ID == nil {
continue
}
catID := *cat.ID
delegation := &typescore.ApprovalDelegation{
DelegatorID: initiator.ID,
DelegateID: &flowState.SelectedDelegateID,
CategoryID: &catID,
ApprovalID: approval.ID,
ValidUntil: &validUntil,
IsActive: &inactive,
NotifiedDay: &notifiedFalse,
Notified2h: &notifiedFalse,
}
h.ipc.Database.ApprovalDelegation.CreateApprovalDelegationDB(ctx, nil, delegation) //nolint:errcheck
}
catID := *cat.ID
delegation := &typescore.ApprovalDelegation{
}
// 2. Создаем отложенное делегирование ЗАДАЧ
if flowState.SelectedTaskDelegateID != 0 {
taskDelegation := &typescore.TaskDelegation{
DelegatorID: initiator.ID,
DelegateID: delegate.ID,
CategoryID: &catID,
DelegateID: &flowState.SelectedTaskDelegateID,
ApprovalID: approval.ID,
ValidUntil: &validUntil,
IsActive: &inactive, // включится только после одобрения заявки
IsActive: &inactive,
NotifiedDay: &notifiedFalse,
Notified2h: &notifiedFalse,
}
if _, _, err := h.ipc.Database.ApprovalDelegation.CreateApprovalDelegationDB(ctx, nil, delegation); err != nil {
logrus.Errorf("createPendingDelegation: CreateApprovalDelegationDB categoryID=%d approvalID=%d err=%v", catID, *approval.ID, err)
continue
}
created++
h.ipc.Database.TaskDelegation.CreateTaskDelegationDB(ctx, nil, taskDelegation) //nolint:errcheck
}
logrus.Infof("createPendingDelegation: создано неактивных делегирований=%d approvalID=%d delegatorID=%d delegateID=%d",
created, *approval.ID, *initiator.ID, *delegate.ID)
}
// activatePendingDelegation включает делегирование, привязанное к этой
// заявке (см. createPendingDelegation), в момент её полного одобрения.
// Вызывается из processNextStepOrComplete строго в ветке финального
// approved (не при передаче на следующий шаг).
func (h *Handler) activatePendingDelegation(ctx context.Context, approval *typescore.Approval) {
if approval == nil || approval.ID == nil {
return
}
active := true
delegations, _, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{
// Активируем заявки
apprDelegations, _, _ := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.ApprovalDelegation{ApprovalID: approval.ID},
})
if err != nil {
logrus.Errorf("activatePendingDelegation: GetApprovalDelegationsListDB approvalID=%d err=%v", *approval.ID, err)
return
}
if len(delegations) == 0 {
return // делегирование при подаче этой заявки не настраивалось
for _, d := range apprDelegations {
d.IsActive = &active
h.ipc.Database.ApprovalDelegation.UpdateApprovalDelegationDB(ctx, nil, d) //nolint:errcheck
}
active := true
for _, d := range delegations {
d.IsActive = &active
if _, _, err := h.ipc.Database.ApprovalDelegation.UpdateApprovalDelegationDB(ctx, nil, d); err != nil {
logrus.Errorf("activatePendingDelegation: UpdateApprovalDelegationDB id=%v err=%v", d.ID, err)
}
// Активируем задачи
taskDelegations, _, _ := h.ipc.Database.TaskDelegation.GetTaskDelegationsListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.TaskDelegation{ApprovalID: approval.ID},
})
for _, td := range taskDelegations {
td.IsActive = &active
h.ipc.Database.TaskDelegation.UpdateTaskDelegationDB(ctx, nil, td) //nolint:errcheck
}
logrus.Infof("activatePendingDelegation: активировано делегирований=%d approvalID=%d", len(delegations), *approval.ID)
}
// deactivatePendingDelegation отменяет делегирование, привязанное к этой
// заявке, при её отзыве — независимо от того, успело оно активироваться
// (заявка уже была одобрена) или ещё оставалось неактивным (заявку
// отозвали прямо во время согласования). Вызывается из performActualRevoke.
func (h *Handler) deactivatePendingDelegation(ctx context.Context, approval *typescore.Approval) {
if approval == nil || approval.ID == nil {
return
}
inactive := false
delegations, _, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{
// Деактивируем заявки
apprDelegations, _, _ := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.ApprovalDelegation{ApprovalID: approval.ID},
})
if err != nil {
logrus.Errorf("deactivatePendingDelegation: GetApprovalDelegationsListDB approvalID=%d err=%v", *approval.ID, err)
return
}
if len(delegations) == 0 {
return
}
inactive := false
changed := 0
for _, d := range delegations {
if d.IsActive != nil && !*d.IsActive {
continue // уже неактивно
}
for _, d := range apprDelegations {
d.IsActive = &inactive
if _, _, err := h.ipc.Database.ApprovalDelegation.UpdateApprovalDelegationDB(ctx, nil, d); err != nil {
logrus.Errorf("deactivatePendingDelegation: UpdateApprovalDelegationDB id=%v err=%v", d.ID, err)
continue
}
changed++
h.ipc.Database.ApprovalDelegation.UpdateApprovalDelegationDB(ctx, nil, d) //nolint:errcheck
}
logrus.Infof("deactivatePendingDelegation: отменено делегирований=%d approvalID=%d", changed, *approval.ID)
}
// ============================================================
// Разбор дат из flowState.Collected — тот же терпимый к опечаткам
// подход, что в scheduler/daily_reminder.go (getAbsentEmployeesToday),
// намеренно продублирован здесь, а не вынесен в общий пакет.
// ============================================================
// Деактивируем задачи
taskDelegations, _, _ := h.ipc.Database.TaskDelegation.GetTaskDelegationsListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.TaskDelegation{ApprovalID: approval.ID},
})
for _, td := range taskDelegations {
td.IsActive = &inactive
h.ipc.Database.TaskDelegation.UpdateTaskDelegationDB(ctx, nil, td) //nolint:errcheck
}
}
var delegationDateRe = regexp.MustCompile(`(\d{1,2})[.,](\d{1,2})\.(\d{4})`)
// delegationValidUntil ищет во ВСЕХ собранных на этом шаге значениях
// (обычно дата лежит под ключом "content" — стандартный input_key
// текстового шага, но на случай нестандартной настройки дерева
// проверяем все значения) самую позднюю дату. Если ничего не нашлось —
// возвращает запасной срок в 30 дней от текущего момента, чтобы не
// оставить not-null колонку без значения вовсе.
func delegationValidUntil(collected map[string]string) (time.Time, bool) {
var dates []time.Time
for _, v := range collected {

View File

@ -287,6 +287,57 @@ func (h *Handler) finalizeAndSubmit(bot *tgbotapi.BotAPI, ctx context.Context, c
}
}
// getActualApprover проверяет, нет ли активного делегирования у назначенного согласующего
// по конкретной теме или её категории. Возвращает актуального пользователя.
func (h *Handler) getActualApprover(ctx context.Context, originalApprover *typescore.User, topicID *uint64) *typescore.User {
if originalApprover == nil || originalApprover.ID == nil || topicID == nil {
return originalApprover
}
topic, err := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *topicID)
if err != nil || topic == nil {
return originalApprover
}
// 1. Проверяем делегирование конкретно по этой теме
if delegations, _, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.ApprovalDelegation{
DelegatorID: originalApprover.ID,
TopicID: topicID,
IsActive: utilscore.PointerToBool(true),
},
}); err == nil {
for _, deleg := range delegations {
if deleg.ValidUntil != nil && deleg.ValidUntil.After(time.Now()) && deleg.DelegateID != nil {
if delegateUser, err := h.ipc.Database.User.GetUserByIDDB(ctx, *deleg.DelegateID); err == nil && delegateUser != nil {
return delegateUser // Нашли делегата по теме
}
}
}
}
// 2. Если по теме нет, проверяем делегирование по всей категории
if topic.CategoryID != nil {
if delegations, _, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.ApprovalDelegation{
DelegatorID: originalApprover.ID,
CategoryID: topic.CategoryID,
IsActive: utilscore.PointerToBool(true),
},
}); err == nil {
for _, deleg := range delegations {
if deleg.ValidUntil != nil && deleg.ValidUntil.After(time.Now()) && deleg.DelegateID != nil {
if delegateUser, err := h.ipc.Database.User.GetUserByIDDB(ctx, *deleg.DelegateID); err == nil && delegateUser != nil {
return delegateUser
}
}
}
}
}
return originalApprover
}
// sendConfirmationCard формирует и отправляет карточку подтверждения для ОДНОЙ
// заявки. Раньше это был "хвост" finalizeAndSubmit — логика не менялась,
// просто вынесена в отдельную функцию, чтобы вызываться в цикле по заявкам.
@ -314,8 +365,18 @@ func (h *Handler) sendConfirmationCard(bot *tgbotapi.BotAPI, ctx context.Context
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 originalApprover, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *s.ApproverID); originalApprover != nil {
// 🚀 Проверяем делегирование
actualApprover := h.getActualApprover(ctx, originalApprover, approval.TopicID)
if actualApprover != nil && actualApprover.FullName != nil {
name := *actualApprover.FullName
// Добавляем пометку, если сработало делегирование
if actualApprover.ID != nil && originalApprover.ID != nil && *actualApprover.ID != *originalApprover.ID {
name += fmt.Sprintf(" (Делегат от %s)", *originalApprover.FullName)
}
names = append(names, name)
}
}
}
}
@ -335,8 +396,15 @@ func (h *Handler) sendConfirmationCard(bot *tgbotapi.BotAPI, ctx context.Context
}
if firstStep != nil && firstStep.ApproverID != nil {
if approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *firstStep.ApproverID); approver != nil && approver.FullName != nil {
approverLine = *approver.FullName
if originalApprover, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *firstStep.ApproverID); originalApprover != nil {
actualApprover := h.getActualApprover(ctx, originalApprover, approval.TopicID)
if actualApprover != nil && actualApprover.FullName != nil {
approverLine = *actualApprover.FullName
if actualApprover.ID != nil && originalApprover.ID != nil && *actualApprover.ID != *originalApprover.ID {
approverLine += fmt.Sprintf(" (Временно исполняющий обязанности %s)", *originalApprover.FullName)
}
}
}
}
}

View File

@ -1,6 +1,7 @@
package keyboard
import (
"bitrix_balancer_api/core/lib/external/tgkit"
"bitrix_balancer_api/core/typescore"
"fmt"
@ -58,3 +59,49 @@ func BuildDelegateSelectionMenu(candidates []*typescore.User, page int) tgbotapi
return tgbotapi.NewInlineKeyboardMarkup(rows...)
}
func BuildTaskDelegationChoiceMenu() tgbotapi.InlineKeyboardMarkup {
return tgkit.NewInlineKeyboard().
Row(
tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "Да", "appr_task_deleg_yes"),
tgkit.BtnStyled(tgkit.ButtonStyleDanger, "Нет", "appr_task_deleg_no"),
).Build()
}
func BuildAbsenceTaskDelegateMenu(candidates []*typescore.User, page int) interface{} {
start := page * delegateCandidatesPerPage
if start > len(candidates) {
start = len(candidates)
}
end := start + delegateCandidatesPerPage
if end > len(candidates) {
end = len(candidates)
}
var rows [][]tgbotapi.InlineKeyboardButton
for _, u := range candidates[start:end] {
if u.ID == nil {
continue
}
name := "Без имени"
if u.FullName != nil {
name = *u.FullName
}
rows = append(rows, tgbotapi.NewInlineKeyboardRow(
tgbotapi.NewInlineKeyboardButtonData(name, fmt.Sprintf("appr_task_deleg_sel:%d", *u.ID)),
))
}
var navRow []tgbotapi.InlineKeyboardButton
if page > 0 {
navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData("⬅️ Назад", fmt.Sprintf("appr_task_deleg_pg:%d", page-1)))
}
if end < len(candidates) {
navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData("Вперёд ➡️", fmt.Sprintf("appr_task_deleg_pg:%d", page+1)))
}
if len(navRow) > 0 {
rows = append(rows, navRow)
}
return tgbotapi.NewInlineKeyboardMarkup(rows...)
}

View File

@ -20,19 +20,23 @@ type FileAttachment struct {
// 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"`
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"`
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"`
AwaitTaskDelegationChoice bool `json:"await_task_delegation_choice,omitempty"`
AwaitTaskDelegateSelection bool `json:"await_task_delegate_selection,omitempty"`
TaskDelegationSelectionDone bool `json:"task_delegation_selection_done,omitempty"`
SelectedTaskDelegateID uint64 `json:"selected_task_delegate_id,omitempty"`
// Выбор первого согласующего по роли
AwaitFirstApproverSelection bool `json:"await_first_approver_selection"`