Added task transfer for executor
This commit is contained in:
parent
dee1c04cb3
commit
4178933149
|
|
@ -36,6 +36,7 @@ type ModuleDB struct {
|
|||
Admin *dbcore.AdminDB
|
||||
Notification *dbcore.NotificationDB
|
||||
DirectorNotifications *dbcore.DirectorNotificationDB
|
||||
ApprovalTaskTransfer *dbcore.ApprovalTaskTransferDB
|
||||
}
|
||||
|
||||
func NewModuleDB(
|
||||
|
|
@ -88,6 +89,7 @@ func initDBModules(modules *ModuleDB, redisClient *redismodule.ModuleRedis) *Mod
|
|||
modules.Admin = dbcore.NewAdminDB(modules.Pool)
|
||||
modules.Notification = dbcore.NewNotificationDB(modules.Pool)
|
||||
modules.DirectorNotifications = dbcore.NewDirectorNotificationDB(modules.Pool)
|
||||
modules.ApprovalTaskTransfer = dbcore.NewApprovalTaskTransferDB(modules.Pool)
|
||||
|
||||
return modules
|
||||
}
|
||||
|
|
|
|||
|
|
@ -41,6 +41,7 @@ func (m *MigrationFunctions) migrateTables() error {
|
|||
|
||||
tablesmigration.NotificationsTableMigrate,
|
||||
tablesmigration.DirectorNotificationSubscriptionsTableMigrate,
|
||||
tablesmigration.ApprovalTaskTransfersTableMigrate,
|
||||
}
|
||||
|
||||
for _, migrate := range migrations {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,38 @@
|
|||
package tablesmigration
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
"time"
|
||||
)
|
||||
|
||||
func ApprovalTaskTransfersTableMigrate(db *gorm.DB) error {
|
||||
hasTable := db.Migrator().HasTable(&LocalApprovalTaskTransferProvider{})
|
||||
|
||||
if err := db.AutoMigrate(&LocalApprovalTaskTransferProvider{}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !hasTable {
|
||||
time.Sleep(5 * time.Second)
|
||||
|
||||
db.Exec(`ALTER TABLE approval_task_transfers ADD CONSTRAINT fk_att_task_id FOREIGN KEY (task_id) REFERENCES approval_tasks(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
db.Exec(`ALTER TABLE approval_task_transfers ADD CONSTRAINT fk_att_from_executor_id FOREIGN KEY (from_executor_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
db.Exec(`ALTER TABLE approval_task_transfers ADD CONSTRAINT fk_att_to_executor_id FOREIGN KEY (to_executor_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
|
||||
execComments(db, `
|
||||
COMMENT ON TABLE "approval_task_transfers" IS 'История запросов на передачу задач исполнения между пользователями';
|
||||
COMMENT ON COLUMN "approval_task_transfers".task_id IS 'Передаваемая задача';
|
||||
COMMENT ON COLUMN "approval_task_transfers".from_executor_id IS 'Исполнитель, инициировавший передачу';
|
||||
COMMENT ON COLUMN "approval_task_transfers".to_executor_id IS 'Пользователь, которому предлагается принять задачу';
|
||||
COMMENT ON COLUMN "approval_task_transfers".status IS 'Статус: pending | accepted | declined | cancelled';
|
||||
COMMENT ON COLUMN "approval_task_transfers".responded_at IS 'Когда получатель ответил на запрос';
|
||||
`)
|
||||
}
|
||||
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_att_task_id ON approval_task_transfers (task_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_att_to_executor_id ON approval_task_transfers (to_executor_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_att_status ON approval_task_transfers (status)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_att_task_status ON approval_task_transfers (task_id, status)`)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
@ -27,7 +27,11 @@ type LocalApprovalTopicExecutorProvider typescore.ApprovalTopicExecutor
|
|||
type LocalNotificationProvider typescore.Notification
|
||||
type LocalNotificationRecipientProvider typescore.NotificationRecipient
|
||||
type LocalDirectorNotificationSubscriptionProvider typescore.DirectorNotificationSubscription
|
||||
type LocalApprovalTaskTransferProvider typescore.ApprovalTaskTransfer
|
||||
|
||||
func (LocalApprovalTaskTransferProvider) TableName() string {
|
||||
return dbcoretablenames.TableNameApprovalTaskTransfers.ToString()
|
||||
}
|
||||
func (LocalDirectorNotificationSubscriptionProvider) TableName() string {
|
||||
return dbcoretablenames.TableNameDirectorNotificationSubscriptions.ToString()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,151 @@
|
|||
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/pgxpool"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type ApprovalTaskTransferDB struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewApprovalTaskTransferDB(pool *pgxpool.Pool) *ApprovalTaskTransferDB {
|
||||
return &ApprovalTaskTransferDB{pool: pool}
|
||||
}
|
||||
|
||||
type ApprovalTaskTransferDBI interface {
|
||||
GetApprovalTaskTransferListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalTaskTransfer, uint64, error)
|
||||
CreateApprovalTaskTransferDB(ctx context.Context, obj *typescore.ApprovalTaskTransfer, returnObj ...bool) (*typescore.ApprovalTaskTransfer, error)
|
||||
UpdateApprovalTaskTransferDB(ctx context.Context, paramsUpdate *typescore.ApprovalTaskTransfer, returnObj ...bool) (*typescore.ApprovalTaskTransfer, error)
|
||||
GetApprovalTaskTransferByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalTaskTransfer, error)
|
||||
GetPendingTransferForTaskDB(ctx context.Context, taskID uint64) (*typescore.ApprovalTaskTransfer, error)
|
||||
}
|
||||
|
||||
func (u *ApprovalTaskTransferDB) GetApprovalTaskTransferListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalTaskTransfer, uint64, error) {
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.ApprovalTaskTransfer{}, dbcoretablenames.TableNameApprovalTaskTransfers.ToString())
|
||||
selectFields := append(fields, "COUNT(*) OVER() AS total_count")
|
||||
|
||||
options, filter, err := dbutils.GetOptionsDB[typescore.ApprovalTaskTransfer](opts...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovalTaskTransfers.ToString(), selectFields)
|
||||
query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
|
||||
query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovalTaskTransfers.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 result []*typescore.ApprovalTaskTransfer
|
||||
var totalCount uint64
|
||||
for rows.Next() {
|
||||
obj := &typescore.ApprovalTaskTransfer{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, obj, &totalCount); err != nil {
|
||||
logrus.Warn("GetApprovalTaskTransferListDB:ScanRowsToStructRows", err)
|
||||
continue
|
||||
}
|
||||
result = append(result, obj)
|
||||
}
|
||||
|
||||
return result, totalCount, nil
|
||||
}
|
||||
|
||||
func (u *ApprovalTaskTransferDB) CreateApprovalTaskTransferDB(ctx context.Context, obj *typescore.ApprovalTaskTransfer, returnObj ...bool) (*typescore.ApprovalTaskTransfer, error) {
|
||||
if obj == nil {
|
||||
return nil, errors.New("approval task transfer obj is nil")
|
||||
}
|
||||
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Insert(dbcoretablenames.TableNameApprovalTaskTransfers.ToString())
|
||||
|
||||
sqlV, args, err := dbutils.GenerateInsertRequest(query, obj)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
*sqlV = *sqlV + " RETURNING id"
|
||||
|
||||
var insertedID uint64
|
||||
if err := u.pool.QueryRow(ctx, *sqlV, args...).Scan(&insertedID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
returnObjBool := len(returnObj) > 0 && returnObj[0]
|
||||
if returnObjBool && insertedID > 0 {
|
||||
return u.GetApprovalTaskTransferByIDDB(ctx, insertedID)
|
||||
}
|
||||
|
||||
obj.ID = &insertedID
|
||||
return obj, nil
|
||||
}
|
||||
|
||||
func (u *ApprovalTaskTransferDB) UpdateApprovalTaskTransferDB(ctx context.Context, paramsUpdate *typescore.ApprovalTaskTransfer, returnObj ...bool) (*typescore.ApprovalTaskTransfer, error) {
|
||||
if paramsUpdate.ID == nil {
|
||||
return nil, errors.New("approval task transfer obj is nil")
|
||||
}
|
||||
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Update(dbcoretablenames.TableNameApprovalTaskTransfers.ToString())
|
||||
query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate)
|
||||
query = query.Where(squirrel.Eq{"id": paramsUpdate.ID})
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if _, err := u.pool.Exec(ctx, sql, args...); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
returnObjBool := len(returnObj) > 0 && returnObj[0]
|
||||
if returnObjBool {
|
||||
return u.GetApprovalTaskTransferByIDDB(ctx, *paramsUpdate.ID)
|
||||
}
|
||||
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (u *ApprovalTaskTransferDB) GetApprovalTaskTransferByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalTaskTransfer, error) {
|
||||
list, _, err := u.GetApprovalTaskTransferListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.ApprovalTaskTransfer{ID: &id},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(list) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return list[0], nil
|
||||
}
|
||||
|
||||
// GetPendingTransferForTaskDB — есть ли уже незакрытый запрос по этой задаче (защита от дублей)
|
||||
func (u *ApprovalTaskTransferDB) GetPendingTransferForTaskDB(ctx context.Context, taskID uint64) (*typescore.ApprovalTaskTransfer, error) {
|
||||
pendingStatus := "pending"
|
||||
list, _, err := u.GetApprovalTaskTransferListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.ApprovalTaskTransfer{TaskID: &taskID, Status: &pendingStatus},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(list) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return list[0], nil
|
||||
}
|
||||
|
|
@ -26,6 +26,7 @@ const (
|
|||
TableNameNotifications TableName = "notifications"
|
||||
TableNameNotificationsRecipients TableName = "notification_recipients"
|
||||
TableNameDirectorNotificationSubscriptions TableName = "director_notification_subscriptions"
|
||||
TableNameApprovalTaskTransfers TableName = "approval_task_transfers"
|
||||
)
|
||||
|
||||
func (t TableName) ToString() string {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,13 @@
|
|||
package typescore
|
||||
|
||||
import "time"
|
||||
|
||||
type ApprovalTaskTransfer struct {
|
||||
ID *uint64 `gorm:"column:id;primaryKey;autoIncrement" json:"id" db:"id"`
|
||||
TaskID *uint64 `gorm:"column:task_id;not null" json:"task_id" db:"task_id"`
|
||||
FromExecutorID *uint64 `gorm:"column:from_executor_id;not null" json:"from_executor_id" db:"from_executor_id"`
|
||||
ToExecutorID *uint64 `gorm:"column:to_executor_id;not null" json:"to_executor_id" db:"to_executor_id"`
|
||||
Status *string `gorm:"column:status;type:text;not null;default:'pending'" json:"status" db:"status"`
|
||||
CreatedAt *time.Time `gorm:"column:created_at;default:CURRENT_TIMESTAMP" json:"created_at" db:"created_at"`
|
||||
RespondedAt *time.Time `gorm:"column:responded_at" json:"responded_at,omitempty" db:"responded_at"`
|
||||
}
|
||||
|
|
@ -317,6 +317,35 @@ func (s *UpdateHandler) handleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.Callba
|
|||
case data == "dir_notif_done":
|
||||
s.approvalHandler.HandleDirectorNotificationDone(bot, cq)
|
||||
|
||||
// ── ПЕРЕДАЧА ЗАДАЧ ──────────────────────────────────────────
|
||||
case strings.HasPrefix(data, "task_transfer_start:"):
|
||||
taskID := parseID(data, "task_transfer_start:")
|
||||
s.approvalHandler.HandleTransferTaskStart(bot, cq, taskID)
|
||||
|
||||
case strings.HasPrefix(data, "task_transfer_page:"):
|
||||
page := 0
|
||||
fmt.Sscanf(strings.TrimPrefix(data, "task_transfer_page:"), "%d", &page)
|
||||
s.approvalHandler.HandleTransferTaskUserPage(bot, cq, page)
|
||||
|
||||
case data == "task_transfer_noop":
|
||||
bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
|
||||
|
||||
case data == "task_transfer_cancel":
|
||||
bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
|
||||
bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck
|
||||
|
||||
case strings.HasPrefix(data, "task_transfer_user:"):
|
||||
toUserID := parseID(data, "task_transfer_user:")
|
||||
s.approvalHandler.HandleTransferTaskUserSelect(bot, cq, toUserID)
|
||||
|
||||
case strings.HasPrefix(data, "task_transfer_accept:"):
|
||||
transferID := parseID(data, "task_transfer_accept:")
|
||||
s.approvalHandler.HandleTransferTaskAccept(bot, cq, transferID)
|
||||
|
||||
case strings.HasPrefix(data, "task_transfer_decline:"):
|
||||
transferID := parseID(data, "task_transfer_decline:")
|
||||
s.approvalHandler.HandleTransferTaskDecline(bot, cq, transferID)
|
||||
|
||||
// ── ДОБАВЛЕНИЕ СОГЛАСУЮЩЕГО ───────────────────────────────────────────────────
|
||||
case strings.HasPrefix(data, "add_appr_category_page:"):
|
||||
page := 0
|
||||
|
|
|
|||
|
|
@ -0,0 +1,316 @@
|
|||
package approval
|
||||
|
||||
import (
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
"bitrix_balancer_api/core/utilscore"
|
||||
"bitrix_balancer_api/telegram_service/keyboard"
|
||||
"context"
|
||||
"fmt"
|
||||
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
|
||||
"github.com/sirupsen/logrus"
|
||||
"time"
|
||||
)
|
||||
|
||||
// HandleTransferTaskStart — исполнитель начинает передачу задачи, показываем список пользователей
|
||||
func (h *Handler) HandleTransferTaskStart(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, taskID uint64) {
|
||||
h.showTransferTaskUserPage(bot, cq, taskID, 0, false)
|
||||
}
|
||||
|
||||
func (h *Handler) HandleTransferTaskUserPage(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, page int) {
|
||||
ctx := context.Background()
|
||||
taskIDKey := fmt.Sprintf("task_transfer_pending:%d", cq.From.ID)
|
||||
taskIDStr, err := h.ipc.RedisClient.Get(ctx, taskIDKey)
|
||||
if err != nil || taskIDStr == "" {
|
||||
bot.Request(tgbotapi.NewCallback(cq.ID, "Сессия истекла, начните заново")) //nolint:errcheck
|
||||
return
|
||||
}
|
||||
var taskID uint64
|
||||
fmt.Sscanf(taskIDStr, "%d", &taskID)
|
||||
h.showTransferTaskUserPage(bot, cq, taskID, page, true)
|
||||
}
|
||||
|
||||
func (h *Handler) showTransferTaskUserPage(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, taskID uint64, page int, isEdit bool) {
|
||||
ctx := context.Background()
|
||||
chatID := cq.Message.Chat.ID
|
||||
telegramID := cq.From.ID
|
||||
|
||||
bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
|
||||
|
||||
currentUser, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
|
||||
if err != nil || currentUser == nil || currentUser.ID == nil {
|
||||
return
|
||||
}
|
||||
|
||||
task, err := h.ipc.Database.ApprovalTasks.GetApprovalTaskByIDDB(ctx, taskID)
|
||||
if err != nil || task == nil {
|
||||
sendText(bot, chatID, "⚠️ Задача не найдена.")
|
||||
return
|
||||
}
|
||||
if task.ExecutorID == nil || *task.ExecutorID != *currentUser.ID {
|
||||
sendText(bot, chatID, "⚠️ Это не ваша задача.")
|
||||
return
|
||||
}
|
||||
if task.Status == nil || *task.Status != "pending" {
|
||||
sendText(bot, chatID, "⚠️ Передать можно только активную задачу.")
|
||||
return
|
||||
}
|
||||
|
||||
if existing, _ := h.ipc.Database.ApprovalTaskTransfer.GetPendingTransferForTaskDB(ctx, taskID); existing != nil {
|
||||
sendText(bot, chatID, "⚠️ По этой задаче уже есть ожидающий подтверждения запрос на передачу.")
|
||||
return
|
||||
}
|
||||
|
||||
allUsers, _, err := h.ipc.Database.User.GetUsersListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.User{IsBlocked: utilscore.PointerToBool(false)},
|
||||
Limit: utilscore.PointerToUint64(500),
|
||||
})
|
||||
if err != nil {
|
||||
logrus.Errorf("showTransferTaskUserPage: GetUsersListDB err=%v", err)
|
||||
return
|
||||
}
|
||||
|
||||
var candidates []*typescore.User
|
||||
for _, u := range allUsers {
|
||||
if u.ID != nil && currentUser.ID != nil && *u.ID != *currentUser.ID {
|
||||
candidates = append(candidates, u)
|
||||
}
|
||||
}
|
||||
|
||||
taskIDKey := fmt.Sprintf("task_transfer_pending:%d", telegramID)
|
||||
h.ipc.RedisClient.Set(ctx, taskIDKey, fmt.Sprintf("%d", taskID), 10*time.Minute) //nolint:errcheck
|
||||
|
||||
markup := keyboard.BuildTaskTransferUserMenu(candidates, page)
|
||||
|
||||
if isEdit {
|
||||
edit := tgbotapi.NewEditMessageReplyMarkup(chatID, cq.Message.MessageID, markup)
|
||||
bot.Request(edit) //nolint:errcheck
|
||||
return
|
||||
}
|
||||
|
||||
msg := tgbotapi.NewMessage(chatID, "🔁 <b>Кому передать задачу?</b>\n\nВыберите пользователя из списка:")
|
||||
msg.ParseMode = "HTML"
|
||||
msg.ReplyMarkup = markup
|
||||
bot.Send(msg) //nolint:errcheck
|
||||
}
|
||||
|
||||
// HandleTransferTaskUserSelect — исполнитель выбрал получателя
|
||||
func (h *Handler) HandleTransferTaskUserSelect(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, toUserID 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
|
||||
|
||||
taskIDKey := fmt.Sprintf("task_transfer_pending:%d", telegramID)
|
||||
taskIDStr, err := h.ipc.RedisClient.Get(ctx, taskIDKey)
|
||||
if err != nil || taskIDStr == "" {
|
||||
sendText(bot, chatID, "⚠️ Сессия истекла, начните заново.")
|
||||
return
|
||||
}
|
||||
var taskID uint64
|
||||
fmt.Sscanf(taskIDStr, "%d", &taskID)
|
||||
h.ipc.RedisClient.Del(ctx, taskIDKey) //nolint:errcheck
|
||||
|
||||
fromUser, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
|
||||
if err != nil || fromUser == nil || fromUser.ID == nil {
|
||||
return
|
||||
}
|
||||
|
||||
task, err := h.ipc.Database.ApprovalTasks.GetApprovalTaskByIDDB(ctx, taskID)
|
||||
if err != nil || task == nil {
|
||||
sendText(bot, chatID, "⚠️ Задача не найдена.")
|
||||
return
|
||||
}
|
||||
if task.ExecutorID == nil || *task.ExecutorID != *fromUser.ID {
|
||||
sendText(bot, chatID, "⚠️ Это не ваша задача.")
|
||||
return
|
||||
}
|
||||
if task.Status == nil || *task.Status != "pending" {
|
||||
sendText(bot, chatID, "⚠️ Задача больше не активна — передача невозможна.")
|
||||
return
|
||||
}
|
||||
if existing, _ := h.ipc.Database.ApprovalTaskTransfer.GetPendingTransferForTaskDB(ctx, taskID); existing != nil {
|
||||
sendText(bot, chatID, "⚠️ По этой задаче уже есть ожидающий запрос.")
|
||||
return
|
||||
}
|
||||
|
||||
toUser, err := h.ipc.Database.User.GetUserByIDDB(ctx, toUserID)
|
||||
if err != nil || toUser == nil || toUser.TelegramID == nil {
|
||||
sendText(bot, chatID, "⚠️ У выбранного пользователя не привязан Telegram, передача невозможна.")
|
||||
return
|
||||
}
|
||||
|
||||
pendingStatus := "pending"
|
||||
transfer := &typescore.ApprovalTaskTransfer{
|
||||
TaskID: taskID2Ptr(taskID),
|
||||
FromExecutorID: fromUser.ID,
|
||||
ToExecutorID: toUser.ID,
|
||||
Status: &pendingStatus,
|
||||
}
|
||||
created, err := h.ipc.Database.ApprovalTaskTransfer.CreateApprovalTaskTransferDB(ctx, transfer)
|
||||
if err != nil || created == nil || created.ID == nil {
|
||||
logrus.Errorf("HandleTransferTaskUserSelect: CreateApprovalTaskTransferDB err=%v", err)
|
||||
sendText(bot, chatID, "⚠️ Ошибка при создании запроса.")
|
||||
return
|
||||
}
|
||||
|
||||
fromName := "—"
|
||||
if fromUser.FullName != nil {
|
||||
fromName = *fromUser.FullName
|
||||
}
|
||||
|
||||
approval, _ := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, *task.ApprovalID)
|
||||
topicFullName := "—"
|
||||
taskText := "—"
|
||||
if approval != nil {
|
||||
topicFullName = getTopicFullName(ctx, h.ipc, approval.TopicID)
|
||||
}
|
||||
if task.TaskText != nil {
|
||||
taskText = *task.TaskText
|
||||
}
|
||||
|
||||
notifyText := fmt.Sprintf(
|
||||
"🔁 <b>Вам предлагают принять задачу</b>\n\n"+
|
||||
"👤 <b>От:</b> %s\n"+
|
||||
"📋 <b>Тема:</b> %s\n"+
|
||||
"🎯 <b>Задача:</b>\n%s\n\n"+
|
||||
"Подтвердите, что принимаете задачу на себя:",
|
||||
fromName, topicFullName, taskText,
|
||||
)
|
||||
|
||||
notifyMsg := tgbotapi.NewMessage(*toUser.TelegramID, notifyText)
|
||||
notifyMsg.ParseMode = "HTML"
|
||||
notifyMsg.ReplyMarkup = keyboard.BuildTaskTransferConfirmation(*created.ID)
|
||||
bot.Send(notifyMsg) //nolint:errcheck
|
||||
|
||||
toName := "—"
|
||||
if toUser.FullName != nil {
|
||||
toName = *toUser.FullName
|
||||
}
|
||||
sendText(bot, chatID, fmt.Sprintf(
|
||||
"📤 <b>Запрос отправлен</b>\n\nОжидаем подтверждения от %s.", toName,
|
||||
))
|
||||
}
|
||||
|
||||
// HandleTransferTaskAccept — получатель принял задачу
|
||||
func (h *Handler) HandleTransferTaskAccept(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, transferID 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
|
||||
|
||||
transfer, err := h.ipc.Database.ApprovalTaskTransfer.GetApprovalTaskTransferByIDDB(ctx, transferID)
|
||||
if err != nil || transfer == nil {
|
||||
sendText(bot, chatID, "⚠️ Запрос не найден.")
|
||||
return
|
||||
}
|
||||
if transfer.Status == nil || *transfer.Status != "pending" {
|
||||
sendText(bot, chatID, "⚠️ Этот запрос уже обработан.")
|
||||
return
|
||||
}
|
||||
|
||||
acceptor, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, cq.From.ID)
|
||||
if err != nil || acceptor == nil || acceptor.ID == nil {
|
||||
return
|
||||
}
|
||||
if transfer.ToExecutorID == nil || *transfer.ToExecutorID != *acceptor.ID {
|
||||
sendText(bot, chatID, "⚠️ Этот запрос адресован не вам.")
|
||||
return
|
||||
}
|
||||
|
||||
task, err := h.ipc.Database.ApprovalTasks.GetApprovalTaskByIDDB(ctx, *transfer.TaskID)
|
||||
if err != nil || task == nil {
|
||||
sendText(bot, chatID, "⚠️ Задача не найдена.")
|
||||
return
|
||||
}
|
||||
|
||||
// 🚀 Ключевая защита от гонки: перепроверяем, что задача всё ещё активна
|
||||
// и всё ещё принадлежит тому, кто инициировал передачу
|
||||
if task.Status == nil || *task.Status != "pending" ||
|
||||
task.ExecutorID == nil || transfer.FromExecutorID == nil || *task.ExecutorID != *transfer.FromExecutorID {
|
||||
|
||||
declinedStatus := "declined"
|
||||
transfer.Status = &declinedStatus
|
||||
now := time.Now()
|
||||
transfer.RespondedAt = &now
|
||||
h.ipc.Database.ApprovalTaskTransfer.UpdateApprovalTaskTransferDB(ctx, transfer) //nolint:errcheck
|
||||
|
||||
sendText(bot, chatID, "⚠️ Задача уже была выполнена или передана другому — принять не удалось.")
|
||||
return
|
||||
}
|
||||
|
||||
acceptedStatus := "accepted"
|
||||
transfer.Status = &acceptedStatus
|
||||
now := time.Now()
|
||||
transfer.RespondedAt = &now
|
||||
if _, err := h.ipc.Database.ApprovalTaskTransfer.UpdateApprovalTaskTransferDB(ctx, transfer); err != nil {
|
||||
logrus.Errorf("HandleTransferTaskAccept: UpdateApprovalTaskTransferDB err=%v", err)
|
||||
return
|
||||
}
|
||||
|
||||
task.ExecutorID = acceptor.ID
|
||||
if _, _, err := h.ipc.Database.ApprovalTasks.UpdateApprovalTaskDB(ctx, nil, task); err != nil {
|
||||
logrus.Errorf("HandleTransferTaskAccept: UpdateApprovalTaskDB err=%v", err)
|
||||
return
|
||||
}
|
||||
|
||||
acceptorName := "—"
|
||||
if acceptor.FullName != nil {
|
||||
acceptorName = *acceptor.FullName
|
||||
}
|
||||
|
||||
// Уведомляем исходного исполнителя
|
||||
if transfer.FromExecutorID != nil {
|
||||
fromUser, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *transfer.FromExecutorID)
|
||||
if fromUser != nil && fromUser.TelegramID != nil {
|
||||
sendText(bot, *fromUser.TelegramID, fmt.Sprintf(
|
||||
"✅ <b>%s принял(а) задачу</b>\n\nЗадача больше не числится за вами.", acceptorName,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
sendText(bot, chatID, "✅ <b>Задача принята</b>\n\nОна теперь ваша.")
|
||||
|
||||
// Отправляем получателю полную карточку задачи с кнопками действий
|
||||
approval, _ := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, *task.ApprovalID)
|
||||
if approval != nil {
|
||||
h.sendTaskCard(bot, chatID, approval, task)
|
||||
}
|
||||
}
|
||||
|
||||
// HandleTransferTaskDecline — получатель отклонил задачу
|
||||
func (h *Handler) HandleTransferTaskDecline(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, transferID 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
|
||||
|
||||
transfer, err := h.ipc.Database.ApprovalTaskTransfer.GetApprovalTaskTransferByIDDB(ctx, transferID)
|
||||
if err != nil || transfer == nil || transfer.Status == nil || *transfer.Status != "pending" {
|
||||
sendText(bot, chatID, "⚠️ Запрос не найден или уже обработан.")
|
||||
return
|
||||
}
|
||||
|
||||
declinedStatus := "declined"
|
||||
transfer.Status = &declinedStatus
|
||||
now := time.Now()
|
||||
transfer.RespondedAt = &now
|
||||
if _, err := h.ipc.Database.ApprovalTaskTransfer.UpdateApprovalTaskTransferDB(ctx, transfer); err != nil {
|
||||
logrus.Errorf("HandleTransferTaskDecline: UpdateApprovalTaskTransferDB err=%v", err)
|
||||
return
|
||||
}
|
||||
|
||||
sendText(bot, chatID, "❌ Вы отклонили передачу задачи.")
|
||||
|
||||
if transfer.FromExecutorID != nil {
|
||||
fromUser, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *transfer.FromExecutorID)
|
||||
if fromUser != nil && fromUser.TelegramID != nil {
|
||||
sendText(bot, *fromUser.TelegramID, "❌ <b>Получатель отклонил передачу задачи</b>\n\nЗадача осталась за вами.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func taskID2Ptr(id uint64) *uint64 { return &id }
|
||||
|
|
@ -349,6 +349,7 @@ func BuildExecutorTaskActions(taskID, approvalID uint64, filesCount int, comment
|
|||
|
||||
kb.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("task_transfer_start:%d", taskID))). // 🆕
|
||||
Row(
|
||||
tgkit.Btn("💬 Комментировать", fmt.Sprintf("appr_comment:%d", approvalID)),
|
||||
buildCommentsButton(approvalID, commentsCount),
|
||||
|
|
|
|||
|
|
@ -337,3 +337,44 @@ func buildCommentsButton(approvalID uint64, commentsCount int) tgkit.InlineButto
|
|||
}
|
||||
return tgkit.Btn(label, fmt.Sprintf("appr_view_comments:%d", approvalID))
|
||||
}
|
||||
|
||||
// BuildTaskTransferUserMenu — список пользователей для передачи задачи
|
||||
func BuildTaskTransferUserMenu(users []*typescore.User, page int) tgbotapi.InlineKeyboardMarkup {
|
||||
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 := page * perPage
|
||||
end := start + 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("task_transfer_user:%d", *u.ID)))
|
||||
}
|
||||
if totalPages > 1 {
|
||||
kb.Rows = append(kb.Rows, buildPageRow(page, totalPages, "task_transfer_page", "task_transfer_noop"))
|
||||
}
|
||||
kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "Отмена", "task_transfer_cancel"))
|
||||
return kb.Build()
|
||||
}
|
||||
|
||||
// BuildTaskTransferConfirmation — кнопки Принять/Отклонить для получателя запроса
|
||||
func BuildTaskTransferConfirmation(transferID uint64) tgbotapi.InlineKeyboardMarkup {
|
||||
return tgkit.NewInlineKeyboard().
|
||||
Row(
|
||||
tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "✅ Принять", fmt.Sprintf("task_transfer_accept:%d", transferID)),
|
||||
tgkit.BtnStyled(tgkit.ButtonStyleDanger, "❌ Отклонить", fmt.Sprintf("task_transfer_decline:%d", transferID)),
|
||||
).
|
||||
Build()
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue