fix-permissions #61
|
|
@ -36,6 +36,8 @@ type ModuleDB struct {
|
|||
Admin *dbcore.AdminDB
|
||||
Notification *dbcore.NotificationDB
|
||||
DirectorNotifications *dbcore.DirectorNotificationDB
|
||||
ApprovalTaskTransfer *dbcore.ApprovalTaskTransferDB
|
||||
ApprovalRevocation *dbcore.ApprovalRevocationDB
|
||||
}
|
||||
|
||||
func NewModuleDB(
|
||||
|
|
@ -88,6 +90,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,8 @@ func (m *MigrationFunctions) migrateTables() error {
|
|||
|
||||
tablesmigration.NotificationsTableMigrate,
|
||||
tablesmigration.DirectorNotificationSubscriptionsTableMigrate,
|
||||
tablesmigration.ApprovalTaskTransfersTableMigrate,
|
||||
tablesmigration.ApprovalRevocationTablesMigrate,
|
||||
}
|
||||
|
||||
for _, migrate := range migrations {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,77 @@
|
|||
package tablesmigration
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
"time"
|
||||
)
|
||||
|
||||
type LocalApprovalRevocationRequestProvider struct {
|
||||
ID uint64 `gorm:"column:id;primaryKey;autoIncrement"`
|
||||
ApprovalID uint64 `gorm:"column:approval_id;not null"`
|
||||
RequestedByID uint64 `gorm:"column:requested_by_id;not null"`
|
||||
Reason *string `gorm:"column:reason;type:text"`
|
||||
Status string `gorm:"column:status;type:text;not null;default:'pending'"`
|
||||
CreatedAt time.Time `gorm:"column:created_at;default:CURRENT_TIMESTAMP"`
|
||||
UpdatedAt time.Time `gorm:"column:updated_at;default:CURRENT_TIMESTAMP"`
|
||||
}
|
||||
|
||||
func (LocalApprovalRevocationRequestProvider) TableName() string {
|
||||
return "approval_revocation_requests"
|
||||
}
|
||||
|
||||
type LocalApprovalRevocationApproverProvider struct {
|
||||
ID uint64 `gorm:"column:id;primaryKey;autoIncrement"`
|
||||
RevocationRequestID uint64 `gorm:"column:revocation_request_id;not null"`
|
||||
ApproverID uint64 `gorm:"column:approver_id;not null"`
|
||||
Status string `gorm:"column:status;type:text;not null;default:'pending'"`
|
||||
Comment *string `gorm:"column:comment;type:text"`
|
||||
ActedAt *time.Time `gorm:"column:acted_at"`
|
||||
CreatedAt time.Time `gorm:"column:created_at;default:CURRENT_TIMESTAMP"`
|
||||
}
|
||||
|
||||
func (LocalApprovalRevocationApproverProvider) TableName() string {
|
||||
return "approval_revocation_approvers"
|
||||
}
|
||||
|
||||
func ApprovalRevocationTablesMigrate(db *gorm.DB) error {
|
||||
hasReqTable := db.Migrator().HasTable(&LocalApprovalRevocationRequestProvider{})
|
||||
hasApprTable := db.Migrator().HasTable(&LocalApprovalRevocationApproverProvider{})
|
||||
|
||||
if err := db.AutoMigrate(&LocalApprovalRevocationRequestProvider{}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := db.AutoMigrate(&LocalApprovalRevocationApproverProvider{}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !hasReqTable || !hasApprTable {
|
||||
time.Sleep(5 * time.Second)
|
||||
|
||||
db.Exec(`ALTER TABLE approval_revocation_requests ADD CONSTRAINT fk_arr_approval_id FOREIGN KEY (approval_id) REFERENCES approvals(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
db.Exec(`ALTER TABLE approval_revocation_requests ADD CONSTRAINT fk_arr_requested_by_id FOREIGN KEY (requested_by_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
|
||||
db.Exec(`ALTER TABLE approval_revocation_approvers ADD CONSTRAINT fk_ara_request_id FOREIGN KEY (revocation_request_id) REFERENCES approval_revocation_requests(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
db.Exec(`ALTER TABLE approval_revocation_approvers ADD CONSTRAINT fk_ara_approver_id FOREIGN KEY (approver_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
|
||||
execComments(db, `
|
||||
COMMENT ON TABLE "approval_revocation_requests" IS 'Запрос инициатора на отзыв уже согласованной заявки, требующий согласия всех согласующих';
|
||||
COMMENT ON COLUMN "approval_revocation_requests".approval_id IS 'Заявка, которую пытаются отозвать';
|
||||
COMMENT ON COLUMN "approval_revocation_requests".requested_by_id IS 'Инициатор, запросивший отзыв';
|
||||
COMMENT ON COLUMN "approval_revocation_requests".reason IS 'Причина отзыва, указанная инициатором';
|
||||
COMMENT ON COLUMN "approval_revocation_requests".status IS 'pending | approved | rejected | cancelled';
|
||||
|
||||
COMMENT ON TABLE "approval_revocation_approvers" IS 'Согласующие, чьё согласие требуется для отзыва уже согласованной заявки';
|
||||
COMMENT ON COLUMN "approval_revocation_approvers".revocation_request_id IS 'Запрос на отзыв';
|
||||
COMMENT ON COLUMN "approval_revocation_approvers".approver_id IS 'Согласующий, участвовавший в первоначальном согласовании';
|
||||
COMMENT ON COLUMN "approval_revocation_approvers".status IS 'pending | approved | rejected';
|
||||
`)
|
||||
}
|
||||
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_arr_approval_id ON approval_revocation_requests (approval_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_arr_status ON approval_revocation_requests (status)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_ara_request_id ON approval_revocation_approvers (revocation_request_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_ara_approver_id ON approval_revocation_approvers (approver_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_ara_request_status ON approval_revocation_approvers (revocation_request_id, status)`)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
@ -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,215 @@
|
|||
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 ApprovalRevocationDB struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewApprovalRevocationDB(pool *pgxpool.Pool) *ApprovalRevocationDB {
|
||||
return &ApprovalRevocationDB{pool: pool}
|
||||
}
|
||||
|
||||
type ApprovalRevocationDBI interface {
|
||||
CreateRevocationRequestDB(ctx context.Context, obj *typescore.ApprovalRevocationRequest, returnObj ...bool) (*typescore.ApprovalRevocationRequest, error)
|
||||
UpdateRevocationRequestDB(ctx context.Context, obj *typescore.ApprovalRevocationRequest, returnObj ...bool) (*typescore.ApprovalRevocationRequest, error)
|
||||
GetRevocationRequestByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalRevocationRequest, error)
|
||||
GetPendingRevocationRequestForApprovalDB(ctx context.Context, approvalID uint64) (*typescore.ApprovalRevocationRequest, error)
|
||||
|
||||
CreateRevocationApproversDB(ctx context.Context, approvers []*typescore.ApprovalRevocationApprover) error
|
||||
UpdateRevocationApproverDB(ctx context.Context, obj *typescore.ApprovalRevocationApprover) error
|
||||
GetRevocationApproversByRequestIDDB(ctx context.Context, requestID uint64) ([]*typescore.ApprovalRevocationApprover, error)
|
||||
GetRevocationApproverForUserDB(ctx context.Context, requestID uint64, approverID uint64) (*typescore.ApprovalRevocationApprover, error)
|
||||
}
|
||||
|
||||
func (d *ApprovalRevocationDB) CreateRevocationRequestDB(ctx context.Context, obj *typescore.ApprovalRevocationRequest, returnObj ...bool) (*typescore.ApprovalRevocationRequest, error) {
|
||||
if obj == nil {
|
||||
return nil, errors.New("revocation request obj is nil")
|
||||
}
|
||||
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Insert(dbcoretablenames.TableNameApprovalRevocationRequests.ToString())
|
||||
|
||||
sqlV, args, err := dbutils.GenerateInsertRequest(query, obj)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
*sqlV = *sqlV + " RETURNING id"
|
||||
|
||||
var insertedID uint64
|
||||
if err := d.pool.QueryRow(ctx, *sqlV, args...).Scan(&insertedID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if len(returnObj) > 0 && returnObj[0] {
|
||||
return d.GetRevocationRequestByIDDB(ctx, insertedID)
|
||||
}
|
||||
obj.ID = &insertedID
|
||||
return obj, nil
|
||||
}
|
||||
|
||||
func (d *ApprovalRevocationDB) UpdateRevocationRequestDB(ctx context.Context, obj *typescore.ApprovalRevocationRequest, returnObj ...bool) (*typescore.ApprovalRevocationRequest, error) {
|
||||
if obj.ID == nil {
|
||||
return nil, errors.New("revocation request id is nil")
|
||||
}
|
||||
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Update(dbcoretablenames.TableNameApprovalRevocationRequests.ToString())
|
||||
query = dbutils.AddNonNullFieldsToQueryUpdate(query, *obj)
|
||||
query = query.Where(squirrel.Eq{"id": obj.ID})
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := d.pool.Exec(ctx, sql, args...); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if len(returnObj) > 0 && returnObj[0] {
|
||||
return d.GetRevocationRequestByIDDB(ctx, *obj.ID)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (d *ApprovalRevocationDB) getRevocationRequestListDB(ctx context.Context, opts typescore.ListDbOptions) ([]*typescore.ApprovalRevocationRequest, error) {
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.ApprovalRevocationRequest{}, dbcoretablenames.TableNameApprovalRevocationRequests.ToString())
|
||||
query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovalRevocationRequests.ToString(), fields)
|
||||
|
||||
options, filter, err := dbutils.GetOptionsDB[typescore.ApprovalRevocationRequest](opts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovalRevocationRequests.ToString())
|
||||
query = query.OrderBy("created_at DESC")
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err := d.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var result []*typescore.ApprovalRevocationRequest
|
||||
for rows.Next() {
|
||||
obj := &typescore.ApprovalRevocationRequest{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, obj, nil); err != nil {
|
||||
logrus.Warn("getRevocationRequestListDB:ScanRowsToStructRows", err)
|
||||
continue
|
||||
}
|
||||
result = append(result, obj)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (d *ApprovalRevocationDB) GetRevocationRequestByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalRevocationRequest, error) {
|
||||
list, err := d.getRevocationRequestListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.ApprovalRevocationRequest{ID: &id},
|
||||
})
|
||||
if err != nil || len(list) == 0 {
|
||||
return nil, err
|
||||
}
|
||||
return list[0], nil
|
||||
}
|
||||
|
||||
func (d *ApprovalRevocationDB) GetPendingRevocationRequestForApprovalDB(ctx context.Context, approvalID uint64) (*typescore.ApprovalRevocationRequest, error) {
|
||||
pendingStatus := "pending"
|
||||
list, err := d.getRevocationRequestListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.ApprovalRevocationRequest{ApprovalID: &approvalID, Status: &pendingStatus},
|
||||
})
|
||||
if err != nil || len(list) == 0 {
|
||||
return nil, err
|
||||
}
|
||||
return list[0], nil
|
||||
}
|
||||
|
||||
func (d *ApprovalRevocationDB) CreateRevocationApproversDB(ctx context.Context, approvers []*typescore.ApprovalRevocationApprover) error {
|
||||
if len(approvers) == 0 {
|
||||
return nil
|
||||
}
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Insert(dbcoretablenames.TableNameApprovalRevocationApprovers.ToString()).
|
||||
Columns("revocation_request_id", "approver_id", "status")
|
||||
|
||||
for _, a := range approvers {
|
||||
query = query.Values(*a.RevocationRequestID, *a.ApproverID, *a.Status)
|
||||
}
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = d.pool.Exec(ctx, sql, args...)
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *ApprovalRevocationDB) UpdateRevocationApproverDB(ctx context.Context, obj *typescore.ApprovalRevocationApprover) error {
|
||||
if obj.ID == nil {
|
||||
return errors.New("revocation approver id is nil")
|
||||
}
|
||||
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Update(dbcoretablenames.TableNameApprovalRevocationApprovers.ToString())
|
||||
query = dbutils.AddNonNullFieldsToQueryUpdate(query, *obj)
|
||||
query = query.Where(squirrel.Eq{"id": obj.ID})
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = d.pool.Exec(ctx, sql, args...)
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *ApprovalRevocationDB) GetRevocationApproversByRequestIDDB(ctx context.Context, requestID uint64) ([]*typescore.ApprovalRevocationApprover, error) {
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.ApprovalRevocationApprover{}, dbcoretablenames.TableNameApprovalRevocationApprovers.ToString())
|
||||
query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovalRevocationApprovers.ToString(), fields).
|
||||
Where(squirrel.Eq{"revocation_request_id": requestID})
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err := d.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var result []*typescore.ApprovalRevocationApprover
|
||||
for rows.Next() {
|
||||
obj := &typescore.ApprovalRevocationApprover{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, obj, nil); err != nil {
|
||||
continue
|
||||
}
|
||||
result = append(result, obj)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (d *ApprovalRevocationDB) GetRevocationApproverForUserDB(ctx context.Context, requestID uint64, approverID uint64) (*typescore.ApprovalRevocationApprover, error) {
|
||||
all, err := d.GetRevocationApproversByRequestIDDB(ctx, requestID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, a := range all {
|
||||
if a.ApproverID != nil && *a.ApproverID == approverID {
|
||||
return a, nil
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
|
@ -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,9 @@ const (
|
|||
TableNameNotifications TableName = "notifications"
|
||||
TableNameNotificationsRecipients TableName = "notification_recipients"
|
||||
TableNameDirectorNotificationSubscriptions TableName = "director_notification_subscriptions"
|
||||
TableNameApprovalTaskTransfers TableName = "approval_task_transfers"
|
||||
TableNameApprovalRevocationRequests TableName = "approval_revocation_requests"
|
||||
TableNameApprovalRevocationApprovers TableName = "approval_revocation_approvers"
|
||||
)
|
||||
|
||||
func (t TableName) ToString() string {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,23 @@
|
|||
package typescore
|
||||
|
||||
import "time"
|
||||
|
||||
type ApprovalRevocationRequest struct {
|
||||
ID *uint64 `gorm:"column:id" json:"id" db:"id"`
|
||||
ApprovalID *uint64 `gorm:"column:approval_id" json:"approval_id" db:"approval_id"`
|
||||
RequestedByID *uint64 `gorm:"column:requested_by_id" json:"requested_by_id" db:"requested_by_id"`
|
||||
Reason *string `gorm:"column:reason" json:"reason,omitempty" db:"reason"`
|
||||
Status *string `gorm:"column:status" json:"status" db:"status"`
|
||||
CreatedAt *time.Time `gorm:"column:created_at" json:"created_at" db:"created_at"`
|
||||
UpdatedAt *time.Time `gorm:"column:updated_at" json:"updated_at" db:"updated_at"`
|
||||
}
|
||||
|
||||
type ApprovalRevocationApprover struct {
|
||||
ID *uint64 `gorm:"column:id" json:"id" db:"id"`
|
||||
RevocationRequestID *uint64 `gorm:"column:revocation_request_id" json:"revocation_request_id" db:"revocation_request_id"`
|
||||
ApproverID *uint64 `gorm:"column:approver_id" json:"approver_id" db:"approver_id"`
|
||||
Status *string `gorm:"column:status" json:"status" db:"status"`
|
||||
Comment *string `gorm:"column:comment" json:"comment,omitempty" db:"comment"`
|
||||
ActedAt *time.Time `gorm:"column:acted_at" json:"acted_at,omitempty" db:"acted_at"`
|
||||
CreatedAt *time.Time `gorm:"column:created_at" json:"created_at" db:"created_at"`
|
||||
}
|
||||
|
|
@ -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
|
||||
|
|
@ -440,11 +469,24 @@ func (s *UpdateHandler) handleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.Callba
|
|||
case data == "select_approver_noop":
|
||||
bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
|
||||
|
||||
// ПРОСМОТР ФАЙЛОВ В ЗАЯВКЕ
|
||||
// ПРОСМОТР ФАЙЛОВ В ЗАЯВКЕ
|
||||
case strings.HasPrefix(data, "appr_view_files:"):
|
||||
approvalID := parseID(data, "appr_view_files:")
|
||||
s.approvalHandler.HandleViewFilesCallback(bot, cq, approvalID)
|
||||
|
||||
case strings.HasPrefix(data, "appr_show_card:"):
|
||||
approvalID := parseID(data, "appr_show_card:")
|
||||
s.approvalHandler.HandleShowApprovalCardCallback(bot, cq, approvalID)
|
||||
|
||||
// ── СОГЛАСОВАНИЕ ОТЗЫВА ────────────────────────────────────
|
||||
case strings.HasPrefix(data, "revoke_appr_yes:"):
|
||||
requestID := parseID(data, "revoke_appr_yes:")
|
||||
s.approvalHandler.HandleRevocationApproverDecision(bot, cq, requestID, true)
|
||||
|
||||
case strings.HasPrefix(data, "revoke_appr_no:"):
|
||||
requestID := parseID(data, "revoke_appr_no:")
|
||||
s.approvalHandler.HandleRevocationApproverDecision(bot, cq, requestID, false)
|
||||
|
||||
// Мои заявки
|
||||
case strings.HasPrefix(data, "my_appr_topic:"):
|
||||
topicFilter := strings.TrimPrefix(data, "my_appr_topic:")
|
||||
|
|
|
|||
|
|
@ -0,0 +1,271 @@
|
|||
package approval
|
||||
|
||||
import (
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
"bitrix_balancer_api/telegram_service/keyboard"
|
||||
"context"
|
||||
"fmt"
|
||||
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
|
||||
"github.com/sirupsen/logrus"
|
||||
"time"
|
||||
)
|
||||
|
||||
// getDistinctApprovedApproverIDs — все, кто реально одобрил хотя бы один шаг этой заявки.
|
||||
func (h *Handler) getDistinctApprovedApproverIDs(ctx context.Context, approvalID uint64) []uint64 {
|
||||
steps, _, err := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.ApprovalStep{ApprovalID: &approvalID},
|
||||
})
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
seen := make(map[uint64]bool)
|
||||
var ids []uint64
|
||||
for _, s := range steps {
|
||||
if s.Status == nil || *s.Status != "approved" || s.ApproverID == nil {
|
||||
continue
|
||||
}
|
||||
if !seen[*s.ApproverID] {
|
||||
seen[*s.ApproverID] = true
|
||||
ids = append(ids, *s.ApproverID)
|
||||
}
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
// startApprovalRevocationRequest создаёт запрос на отзыв уже согласованной заявки
|
||||
// и рассылает его всем, кто участвовал в согласовании, для получения их согласия.
|
||||
func (h *Handler) startApprovalRevocationRequest(
|
||||
bot *tgbotapi.BotAPI,
|
||||
chatID int64,
|
||||
approval *typescore.Approval,
|
||||
initiator *typescore.User,
|
||||
comment string,
|
||||
) {
|
||||
ctx := context.Background()
|
||||
approvalID := *approval.ID
|
||||
|
||||
if existing, _ := h.ipc.Database.ApprovalRevocation.GetPendingRevocationRequestForApprovalDB(ctx, approvalID); existing != nil {
|
||||
sendText(bot, chatID, "⚠️ По этой заявке уже есть ожидающий рассмотрения запрос на отзыв.")
|
||||
return
|
||||
}
|
||||
|
||||
approverIDs := h.getDistinctApprovedApproverIDs(ctx, approvalID)
|
||||
if len(approverIDs) == 0 {
|
||||
// Заявку никто не одобрял (странный случай, но не блокируем инициатора навсегда)
|
||||
h.HandleRevokeWithComment(bot, chatID, *initiator.TelegramID, approvalID, comment)
|
||||
return
|
||||
}
|
||||
|
||||
pendingStatus := "pending"
|
||||
var reasonPtr *string
|
||||
if comment != "" {
|
||||
reasonPtr = &comment
|
||||
}
|
||||
|
||||
request := &typescore.ApprovalRevocationRequest{
|
||||
ApprovalID: &approvalID,
|
||||
RequestedByID: initiator.ID,
|
||||
Reason: reasonPtr,
|
||||
Status: &pendingStatus,
|
||||
}
|
||||
created, err := h.ipc.Database.ApprovalRevocation.CreateRevocationRequestDB(ctx, request, true)
|
||||
if err != nil || created == nil || created.ID == nil {
|
||||
logrus.Errorf("startApprovalRevocationRequest: CreateRevocationRequestDB err=%v", err)
|
||||
sendText(bot, chatID, "⚠️ Ошибка при создании запроса на отзыв.")
|
||||
return
|
||||
}
|
||||
|
||||
var approvers []*typescore.ApprovalRevocationApprover
|
||||
for _, id := range approverIDs {
|
||||
id := id
|
||||
approvers = append(approvers, &typescore.ApprovalRevocationApprover{
|
||||
RevocationRequestID: created.ID,
|
||||
ApproverID: &id,
|
||||
Status: &pendingStatus,
|
||||
})
|
||||
}
|
||||
if err := h.ipc.Database.ApprovalRevocation.CreateRevocationApproversDB(ctx, approvers); err != nil {
|
||||
logrus.Errorf("startApprovalRevocationRequest: CreateRevocationApproversDB err=%v", err)
|
||||
sendText(bot, chatID, "⚠️ Ошибка при создании списка согласующих.")
|
||||
return
|
||||
}
|
||||
|
||||
initiatorName := "—"
|
||||
if initiator.FullName != nil {
|
||||
initiatorName = *initiator.FullName
|
||||
}
|
||||
topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID)
|
||||
content := "—"
|
||||
if approval.Content != nil {
|
||||
content = *approval.Content
|
||||
}
|
||||
reasonLine := ""
|
||||
if comment != "" {
|
||||
reasonLine = fmt.Sprintf("\n💬 <b>Причина:</b> %s", comment)
|
||||
}
|
||||
|
||||
notifyText := fmt.Sprintf(
|
||||
"⚠️ <b>Запрос на отзыв согласованной заявки #%d</b>\n\n"+
|
||||
"👤 <b>Инициатор:</b> %s\n"+
|
||||
"📋 <b>Тема:</b> %s\n"+
|
||||
"📝 <b>Текст:</b> %s%s\n\n"+
|
||||
"Требуется согласие всех, кто участвовал в согласовании. Ваше решение:",
|
||||
approvalID, initiatorName, topicFullName, content, reasonLine,
|
||||
)
|
||||
|
||||
for _, id := range approverIDs {
|
||||
approver, err := h.ipc.Database.User.GetUserByIDDB(ctx, id)
|
||||
if err != nil || approver == nil || approver.TelegramID == nil {
|
||||
continue
|
||||
}
|
||||
msg := tgbotapi.NewMessage(*approver.TelegramID, notifyText)
|
||||
msg.ParseMode = "HTML"
|
||||
msg.ReplyMarkup = keyboard.BuildRevocationApprovalDecision(approvalID, *created.ID, h.GetCommentsCount(ctx, approvalID))
|
||||
bot.Send(msg) //nolint:errcheck
|
||||
}
|
||||
|
||||
sendText(bot, chatID, fmt.Sprintf(
|
||||
"📤 <b>Запрос на отзыв заявки #%d отправлен</b>\n\n"+
|
||||
"Ожидаем согласия от всех согласующих (%d чел.). Заявка будет отозвана только после единодушного согласия.",
|
||||
approvalID, len(approverIDs),
|
||||
))
|
||||
}
|
||||
|
||||
// HandleRevocationApproverDecision — согласующий дал ответ на запрос отзыва.
|
||||
func (h *Handler) HandleRevocationApproverDecision(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, requestID uint64, approved bool) {
|
||||
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
|
||||
|
||||
user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, cq.From.ID)
|
||||
if err != nil || user == nil || user.ID == nil {
|
||||
return
|
||||
}
|
||||
|
||||
request, err := h.ipc.Database.ApprovalRevocation.GetRevocationRequestByIDDB(ctx, requestID)
|
||||
if err != nil || request == nil {
|
||||
sendText(bot, chatID, "⚠️ Запрос не найден.")
|
||||
return
|
||||
}
|
||||
if request.Status == nil || *request.Status != "pending" {
|
||||
sendText(bot, chatID, "⚠️ Этот запрос уже обработан.")
|
||||
return
|
||||
}
|
||||
|
||||
approverRecord, err := h.ipc.Database.ApprovalRevocation.GetRevocationApproverForUserDB(ctx, requestID, *user.ID)
|
||||
if err != nil || approverRecord == nil {
|
||||
sendText(bot, chatID, "⚠️ Вы не являетесь участником этого согласования.")
|
||||
return
|
||||
}
|
||||
if approverRecord.Status == nil || *approverRecord.Status != "pending" {
|
||||
sendText(bot, chatID, "⚠️ Вы уже дали ответ на этот запрос.")
|
||||
return
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
newStatus := "approved"
|
||||
if !approved {
|
||||
newStatus = "rejected"
|
||||
}
|
||||
approverRecord.Status = &newStatus
|
||||
approverRecord.ActedAt = &now
|
||||
if err := h.ipc.Database.ApprovalRevocation.UpdateRevocationApproverDB(ctx, approverRecord); err != nil {
|
||||
logrus.Errorf("HandleRevocationApproverDecision: UpdateRevocationApproverDB err=%v", err)
|
||||
return
|
||||
}
|
||||
|
||||
responderName := "—"
|
||||
if user.FullName != nil {
|
||||
responderName = *user.FullName
|
||||
}
|
||||
|
||||
if !approved {
|
||||
// Один отказ — отклоняем весь запрос сразу
|
||||
rejectedStatus := "rejected"
|
||||
request.Status = &rejectedStatus
|
||||
h.ipc.Database.ApprovalRevocation.UpdateRevocationRequestDB(ctx, request) //nolint:errcheck
|
||||
|
||||
sendText(bot, chatID, fmt.Sprintf("❌ Вы отклонили отзыв заявки #%d.", *request.ApprovalID))
|
||||
h.notifyRevocationRequestClosed(bot, ctx, request, false, responderName)
|
||||
return
|
||||
}
|
||||
|
||||
sendText(bot, chatID, fmt.Sprintf("✅ Вы согласились на отзыв заявки #%d.", *request.ApprovalID))
|
||||
|
||||
// Проверяем, все ли уже согласились
|
||||
allApprovers, err := h.ipc.Database.ApprovalRevocation.GetRevocationApproversByRequestIDDB(ctx, requestID)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
allApproved := true
|
||||
for _, a := range allApprovers {
|
||||
if a.Status == nil || *a.Status != "approved" {
|
||||
allApproved = false
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if !allApproved {
|
||||
return
|
||||
}
|
||||
|
||||
approvedStatus := "approved"
|
||||
request.Status = &approvedStatus
|
||||
if _, err := h.ipc.Database.ApprovalRevocation.UpdateRevocationRequestDB(ctx, request); err != nil {
|
||||
logrus.Errorf("HandleRevocationApproverDecision: UpdateRevocationRequestDB err=%v", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Все согласились — выполняем фактический отзыв
|
||||
approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, *request.ApprovalID)
|
||||
if err != nil || approval == nil || request.RequestedByID == nil {
|
||||
return
|
||||
}
|
||||
initiator, err := h.ipc.Database.User.GetUserByIDDB(ctx, *request.RequestedByID)
|
||||
if err != nil || initiator == nil || initiator.TelegramID == nil {
|
||||
return
|
||||
}
|
||||
|
||||
reason := ""
|
||||
if request.Reason != nil {
|
||||
reason = *request.Reason
|
||||
}
|
||||
|
||||
// В этой ветке отзывающий — инициатор (запрос был именно от него),
|
||||
// isDirectorRevoking всегда false, т.к. в этот путь директор не попадает
|
||||
steps, _, _ := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.ApprovalStep{ApprovalID: request.ApprovalID},
|
||||
})
|
||||
|
||||
h.performActualRevoke(bot, ctx, approval, initiator, "инициатором", reason, steps, true, false)
|
||||
h.notifyRevocationRequestClosed(bot, ctx, request, true, "")
|
||||
}
|
||||
|
||||
// notifyRevocationRequestClosed уведомляет инициатора об итоге запроса на отзыв.
|
||||
func (h *Handler) notifyRevocationRequestClosed(bot *tgbotapi.BotAPI, ctx context.Context, request *typescore.ApprovalRevocationRequest, approved bool, rejectorName string) {
|
||||
if request.RequestedByID == nil {
|
||||
return
|
||||
}
|
||||
initiator, err := h.ipc.Database.User.GetUserByIDDB(ctx, *request.RequestedByID)
|
||||
if err != nil || initiator == nil || initiator.TelegramID == nil {
|
||||
return
|
||||
}
|
||||
|
||||
if approved {
|
||||
sendText(bot, *initiator.TelegramID, fmt.Sprintf(
|
||||
"✅ <b>Заявка #%d отозвана</b>\n\nВсе согласующие дали согласие на отзыв.",
|
||||
*request.ApprovalID,
|
||||
))
|
||||
return
|
||||
}
|
||||
|
||||
sendText(bot, *initiator.TelegramID, fmt.Sprintf(
|
||||
"❌ <b>Отзыв заявки #%d отклонён</b>\n\n"+
|
||||
"👤 <b>Отклонил:</b> %s\n\n"+
|
||||
"Заявка остаётся согласованной.",
|
||||
*request.ApprovalID, rejectorName,
|
||||
))
|
||||
}
|
||||
|
|
@ -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 }
|
||||
|
|
@ -1,6 +1,7 @@
|
|||
package approval
|
||||
|
||||
import (
|
||||
"bitrix_balancer_api/core/lib/external/tgkit"
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
"bitrix_balancer_api/telegram_service/approvalflow"
|
||||
"bitrix_balancer_api/telegram_service/keyboard"
|
||||
|
|
@ -9,10 +10,9 @@ import (
|
|||
"context"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
|
||||
"github.com/sirupsen/logrus"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
|
|
@ -289,11 +289,9 @@ func (h *Handler) HandleRevokeWithComment(bot *tgbotapi.BotAPI, chatID int64, te
|
|||
return
|
||||
}
|
||||
|
||||
// Определяем роли пользователя
|
||||
isInitiator := approval.InitiatorID != nil && *approval.InitiatorID == *revoker.ID
|
||||
isDirector, _ := h.ipc.Database.User.IsDirectorDB(ctx, *revoker.ID)
|
||||
|
||||
// 🚀 НОВОЕ: Проверяем, является ли пользователь согласующим по этой заявке
|
||||
isApprover := false
|
||||
steps, _, _ := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.ApprovalStep{ApprovalID: &approvalID},
|
||||
|
|
@ -305,7 +303,6 @@ func (h *Handler) HandleRevokeWithComment(bot *tgbotapi.BotAPI, chatID int64, te
|
|||
}
|
||||
}
|
||||
|
||||
// Проверка прав в зависимости от статуса
|
||||
switch *approval.Status {
|
||||
case "revoked":
|
||||
sendText(bot, chatID, "Заявка уже отозвана.")
|
||||
|
|
@ -323,6 +320,13 @@ func (h *Handler) HandleRevokeWithComment(bot *tgbotapi.BotAPI, chatID int64, te
|
|||
sendText(bot, chatID, "⚠️ У вас нет прав для отзыва этой заявки.")
|
||||
return
|
||||
}
|
||||
|
||||
// Инициатор (не директор) отзывает уже согласованную заявку —
|
||||
// требуется согласие всех, кто участвовал в согласовании
|
||||
if isInitiator && !isDirector {
|
||||
h.startApprovalRevocationRequest(bot, chatID, approval, revoker, comment)
|
||||
return
|
||||
}
|
||||
default:
|
||||
if !isInitiator && !isDirector {
|
||||
sendText(bot, chatID, "⚠️ У вас нет прав для отзыва этой заявки.")
|
||||
|
|
@ -330,32 +334,6 @@ func (h *Handler) HandleRevokeWithComment(bot *tgbotapi.BotAPI, chatID int64, te
|
|||
}
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
revokedStatus := "revoked"
|
||||
approval.Status = &revokedStatus
|
||||
approval.RevokedByID = revoker.ID
|
||||
approval.RevokedAt = &now
|
||||
|
||||
if _, _, err := h.ipc.Database.Approval.UpdateApprovalDB(ctx, nil, approval); err != nil {
|
||||
logrus.Errorf("HandleRevokeWithComment: UpdateApprovalDB err=%v", err)
|
||||
sendText(bot, chatID, "Ошибка при отзыве заявки.")
|
||||
return
|
||||
}
|
||||
|
||||
h.handleRevokeCancellationTask(bot, ctx, approval)
|
||||
|
||||
revokerName := "—"
|
||||
if revoker.FullName != nil {
|
||||
revokerName = *revoker.FullName
|
||||
}
|
||||
|
||||
topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID)
|
||||
|
||||
content := "—"
|
||||
if approval.Content != nil {
|
||||
content = *approval.Content
|
||||
}
|
||||
|
||||
revokerRole := ""
|
||||
switch {
|
||||
case isInitiator:
|
||||
|
|
@ -366,6 +344,71 @@ func (h *Handler) HandleRevokeWithComment(bot *tgbotapi.BotAPI, chatID int64, te
|
|||
revokerRole = "согласующим"
|
||||
}
|
||||
|
||||
h.performActualRevoke(bot, ctx, approval, revoker, revokerRole, comment, steps, isInitiator, isDirector)
|
||||
|
||||
// Обратная связь тому, кто выполнил отзыв
|
||||
topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID)
|
||||
content := "—"
|
||||
if approval.Content != nil {
|
||||
content = *approval.Content
|
||||
}
|
||||
approvalCard := fmt.Sprintf(
|
||||
"📋 <b>Тема:</b> %s\n📝 <b>Текст:</b> %s\n💬 <b>Причина отзыва:</b> %s",
|
||||
topicFullName, content, comment,
|
||||
)
|
||||
feedbackMsg := tgbotapi.NewMessage(chatID, fmt.Sprintf(
|
||||
"↩️ <b>Заявка #%d отозвана</b>\n\n%s",
|
||||
approvalID, approvalCard,
|
||||
))
|
||||
feedbackMsg.ParseMode = "HTML"
|
||||
feedbackMsg.ReplyMarkup = keyboard.BuildCommentNotificationKeyboard(approvalID, h.GetCommentsCount(ctx, approvalID))
|
||||
bot.Send(feedbackMsg) //nolint:errcheck
|
||||
}
|
||||
|
||||
// performActualRevoke выполняет отзыв заявки в БД и уведомляет всех участников
|
||||
// с возможностью комментирования. Вызывается либо напрямую (директор/согласующий/
|
||||
// инициатор для pending), либо после того как все согласующие подтвердили согласие
|
||||
// на отзыв уже одобренной заявки.
|
||||
func (h *Handler) performActualRevoke(
|
||||
bot *tgbotapi.BotAPI,
|
||||
ctx context.Context,
|
||||
approval *typescore.Approval,
|
||||
revoker *typescore.User,
|
||||
revokerRole string,
|
||||
comment string,
|
||||
steps []*typescore.ApprovalStep,
|
||||
isInitiatorRevoking bool,
|
||||
isDirectorRevoking bool,
|
||||
) {
|
||||
if approval.ID == nil {
|
||||
return
|
||||
}
|
||||
approvalID := *approval.ID
|
||||
|
||||
now := time.Now().UTC()
|
||||
revokedStatus := "revoked"
|
||||
approval.Status = &revokedStatus
|
||||
approval.RevokedByID = revoker.ID
|
||||
approval.RevokedAt = &now
|
||||
|
||||
if _, _, err := h.ipc.Database.Approval.UpdateApprovalDB(ctx, nil, approval); err != nil {
|
||||
logrus.Errorf("performActualRevoke: UpdateApprovalDB err=%v", err)
|
||||
return
|
||||
}
|
||||
|
||||
h.handleRevokeCancellationTask(bot, ctx, approval)
|
||||
|
||||
revokerName := "—"
|
||||
if revoker.FullName != nil {
|
||||
revokerName = *revoker.FullName
|
||||
}
|
||||
|
||||
topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID)
|
||||
content := "—"
|
||||
if approval.Content != nil {
|
||||
content = *approval.Content
|
||||
}
|
||||
|
||||
approvalCard := fmt.Sprintf(
|
||||
"📋 <b>Тема:</b> %s\n"+
|
||||
"📝 <b>Текст:</b> %s\n"+
|
||||
|
|
@ -373,23 +416,29 @@ func (h *Handler) HandleRevokeWithComment(bot *tgbotapi.BotAPI, chatID int64, te
|
|||
topicFullName, content, comment,
|
||||
)
|
||||
|
||||
// Уведомление тому, кто отзывает
|
||||
sendText(bot, chatID, fmt.Sprintf(
|
||||
"↩️ <b>Заявка #%d отозвана</b>\n\n%s",
|
||||
approvalID, approvalCard,
|
||||
))
|
||||
commentsCount := h.GetCommentsCount(ctx, approvalID)
|
||||
commentKeyboard := keyboard.BuildCommentNotificationKeyboard(approvalID, commentsCount)
|
||||
|
||||
if !isInitiator && approval.InitiatorID != nil {
|
||||
notify := func(chatID int64, text string) {
|
||||
msg := tgbotapi.NewMessage(chatID, text)
|
||||
msg.ParseMode = "HTML"
|
||||
msg.ReplyMarkup = commentKeyboard
|
||||
bot.Send(msg) //nolint:errcheck
|
||||
}
|
||||
|
||||
// Инициатор (если не сам отзывал)
|
||||
if !isInitiatorRevoking && approval.InitiatorID != nil {
|
||||
initiator, err := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID)
|
||||
if err == nil && initiator != nil && initiator.TelegramID != nil {
|
||||
sendText(bot, *initiator.TelegramID, fmt.Sprintf(
|
||||
notify(*initiator.TelegramID, fmt.Sprintf(
|
||||
"↩️ <b>Ваша заявка #%d отозвана %s %s</b>\n\n%s",
|
||||
approvalID, revokerRole, revokerName, approvalCard,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
if !isDirector {
|
||||
// Директора (если не сам отзывал)
|
||||
if !isDirectorRevoking {
|
||||
directors, _ := h.ipc.Database.User.GetDirectorsDB(ctx)
|
||||
for _, director := range directors {
|
||||
if director.TelegramID == nil {
|
||||
|
|
@ -398,13 +447,15 @@ func (h *Handler) HandleRevokeWithComment(bot *tgbotapi.BotAPI, chatID int64, te
|
|||
if revoker.ID != nil && director.ID != nil && *director.ID == *revoker.ID {
|
||||
continue
|
||||
}
|
||||
sendText(bot, *director.TelegramID, fmt.Sprintf(
|
||||
notify(*director.TelegramID, fmt.Sprintf(
|
||||
"↩️ <b>Заявка #%d отозвана %s %s</b>\n\n%s",
|
||||
approvalID, revokerRole, revokerName, approvalCard,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
// Согласующие (кроме самого отозвавшего)
|
||||
notifiedApprovers := make(map[uint64]bool)
|
||||
for _, step := range steps {
|
||||
if step.ApproverID == nil {
|
||||
continue
|
||||
|
|
@ -412,31 +463,35 @@ func (h *Handler) HandleRevokeWithComment(bot *tgbotapi.BotAPI, chatID int64, te
|
|||
if revoker.ID != nil && *step.ApproverID == *revoker.ID {
|
||||
continue
|
||||
}
|
||||
if notifiedApprovers[*step.ApproverID] {
|
||||
continue
|
||||
}
|
||||
notifiedApprovers[*step.ApproverID] = true
|
||||
|
||||
approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *step.ApproverID)
|
||||
if approver == nil || approver.TelegramID == nil {
|
||||
continue
|
||||
}
|
||||
sendText(bot, *approver.TelegramID, fmt.Sprintf(
|
||||
notify(*approver.TelegramID, fmt.Sprintf(
|
||||
"↩️ <b>Заявка #%d отозвана %s %s</b>\n\n%s",
|
||||
approvalID, revokerRole, revokerName, approvalCard,
|
||||
))
|
||||
}
|
||||
|
||||
if *approval.Status == "revoked" {
|
||||
categoryCode := h.getTopicCodeByApproval(ctx, approval)
|
||||
observers, _ := h.ipc.Database.User.GetObserversForApprovalDB(ctx, categoryCode, approval.TopicID)
|
||||
for _, obs := range observers {
|
||||
if obs.TelegramID == nil {
|
||||
continue
|
||||
}
|
||||
if revoker.ID != nil && obs.ID != nil && *obs.ID == *revoker.ID {
|
||||
continue
|
||||
}
|
||||
sendText(bot, *obs.TelegramID, fmt.Sprintf(
|
||||
"↩️ <b>Заявка #%d отозвана %s %s</b>\n\n%s",
|
||||
approvalID, revokerRole, revokerName, approvalCard,
|
||||
))
|
||||
// Наблюдатели
|
||||
categoryCode := h.getTopicCodeByApproval(ctx, approval)
|
||||
observers, _ := h.ipc.Database.User.GetObserversForApprovalDB(ctx, categoryCode, approval.TopicID)
|
||||
for _, obs := range observers {
|
||||
if obs.TelegramID == nil {
|
||||
continue
|
||||
}
|
||||
if revoker.ID != nil && obs.ID != nil && *obs.ID == *revoker.ID {
|
||||
continue
|
||||
}
|
||||
notify(*obs.TelegramID, fmt.Sprintf(
|
||||
"↩️ <b>Заявка #%d отозвана %s %s</b>\n\n%s",
|
||||
approvalID, revokerRole, revokerName, approvalCard,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -613,9 +668,13 @@ func (h *Handler) HandleViewFilesCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.Cal
|
|||
return
|
||||
}
|
||||
|
||||
sendText(bot, chatID, fmt.Sprintf("📎 <b>Файлы к заявке #%d (%d шт.):</b>", approvalID, len(files)))
|
||||
cardButton := tgkit.NewInlineKeyboard().
|
||||
Row(tgkit.Btn("📋 Показать заявку", fmt.Sprintf("appr_show_card:%d", approvalID))).
|
||||
Build()
|
||||
|
||||
for _, f := range files {
|
||||
caption := fmt.Sprintf("📎 <b>Файлы к заявке #%d (%d шт.):</b>", approvalID, len(files))
|
||||
|
||||
for i, f := range files {
|
||||
if f.FileBase64 == nil || f.FileName == nil {
|
||||
continue
|
||||
}
|
||||
|
|
@ -628,6 +687,148 @@ func (h *Handler) HandleViewFilesCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.Cal
|
|||
Name: *f.FileName,
|
||||
Bytes: data,
|
||||
})
|
||||
bot.Send(doc) //nolint:errcheck
|
||||
doc.ParseMode = "HTML"
|
||||
|
||||
isLast := i == len(files)-1
|
||||
|
||||
// Подпись — на первом файле, чтобы сразу было видно к какой заявке относится
|
||||
if i == 0 {
|
||||
doc.Caption = caption
|
||||
}
|
||||
// Кнопка возврата к карточке — на последнем файле
|
||||
if isLast {
|
||||
doc.ReplyMarkup = cardButton
|
||||
}
|
||||
|
||||
if _, err := bot.Send(doc); err != nil {
|
||||
logrus.Errorf("HandleViewFilesCallback: Send err=%v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// HandleShowApprovalCardCallback показывает карточку заявки с кнопками,
|
||||
// соответствующими роли нажавшего пользователя именно в этой заявке.
|
||||
// Порядок проверки важен: сначала более специфичные роли (исполнитель активной
|
||||
// задачи, активный согласующий), затем инициатор, затем директор/наблюдатель.
|
||||
func (h *Handler) HandleShowApprovalCardCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64) {
|
||||
ctx := context.Background()
|
||||
chatID := cq.Message.Chat.ID
|
||||
telegramID := cq.From.ID
|
||||
|
||||
bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
|
||||
|
||||
user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
|
||||
if err != nil || user == nil || user.ID == nil {
|
||||
sendText(bot, chatID, "⚠️ Пользователь не найден.")
|
||||
return
|
||||
}
|
||||
currentUserID := *user.ID
|
||||
|
||||
approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID)
|
||||
if err != nil || approval == nil {
|
||||
sendText(bot, chatID, "⚠️ Заявка не найдена.")
|
||||
return
|
||||
}
|
||||
|
||||
files, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, approvalID)
|
||||
approval.Files = files
|
||||
filesCount := len(files)
|
||||
commentsCount := h.GetCommentsCount(ctx, approvalID)
|
||||
|
||||
status := ""
|
||||
if approval.Status != nil {
|
||||
status = *approval.Status
|
||||
}
|
||||
|
||||
collected := h.getCollectedFromApproval(ctx, approval)
|
||||
card := h.buildApprovalCard(ctx, approval, collected)
|
||||
|
||||
// 1. Исполнитель активной задачи по этой заявке
|
||||
tasks, _, err := h.ipc.Database.ApprovalTasks.GetApprovalTasksListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.ApprovalTask{ApprovalID: &approvalID, ExecutorID: ¤tUserID},
|
||||
})
|
||||
if err == nil {
|
||||
for _, task := range tasks {
|
||||
if task.Status != nil && *task.Status == "pending" {
|
||||
h.sendTaskCard(bot, chatID, approval, task)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Активный согласующий (включая делегатов) по этой заявке
|
||||
categoryCode := h.getTopicCodeByApproval(ctx, approval)
|
||||
approvalTopic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID)
|
||||
isAnyOf := approvalTopic != nil && approvalTopic.ApprovalMode != nil && *approvalTopic.ApprovalMode == "any_of"
|
||||
|
||||
if status == "pending" {
|
||||
if step := h.findStepForCurrentApprover(ctx, approvalID, currentUserID, approval, isAnyOf); step != nil {
|
||||
msg := tgbotapi.NewMessage(chatID, card)
|
||||
msg.ParseMode = "HTML"
|
||||
msg.ReplyMarkup = keyboard.BuildApproverDecision(approvalID, status, filesCount > 0, filesCount, commentsCount)
|
||||
bot.Send(msg) //nolint:errcheck
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Дополнительный согласующий (pending) по этой заявке
|
||||
additionalApprovers, _, _ := h.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.ApprovalAdditionalApprover{ApprovalID: &approvalID},
|
||||
})
|
||||
for _, aa := range additionalApprovers {
|
||||
if aa.ApproverID != nil && *aa.ApproverID == currentUserID && aa.Status != nil && *aa.Status == "pending" {
|
||||
msg := tgbotapi.NewMessage(chatID, card)
|
||||
msg.ParseMode = "HTML"
|
||||
msg.ReplyMarkup = keyboard.BuildApproverDecision(approvalID, status, filesCount > 0, filesCount, commentsCount)
|
||||
bot.Send(msg) //nolint:errcheck
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Инициатор заявки
|
||||
if approval.InitiatorID != nil && *approval.InitiatorID == currentUserID {
|
||||
msg := tgbotapi.NewMessage(chatID, card)
|
||||
msg.ParseMode = "HTML"
|
||||
msg.ReplyMarkup = keyboard.BuildRevokeButton(approvalID, status, filesCount, commentsCount)
|
||||
bot.Send(msg) //nolint:errcheck
|
||||
return
|
||||
}
|
||||
|
||||
// 5. Директор
|
||||
if isDirector, _ := h.ipc.Database.User.IsDirectorDB(ctx, currentUserID); isDirector {
|
||||
msg := tgbotapi.NewMessage(chatID, card)
|
||||
msg.ParseMode = "HTML"
|
||||
msg.ReplyMarkup = keyboard.BuildRevokeButton(approvalID, status, filesCount, commentsCount)
|
||||
bot.Send(msg) //nolint:errcheck
|
||||
return
|
||||
}
|
||||
|
||||
// 6. Наблюдатель категории/темы
|
||||
if h.canUserAccessObserverView(ctx, currentUserID, categoryCode, approval.TopicID) {
|
||||
msg := tgbotapi.NewMessage(chatID, card)
|
||||
msg.ParseMode = "HTML"
|
||||
msg.ReplyMarkup = keyboard.BuildObserverActions(approvalID, "", status, filesCount, commentsCount)
|
||||
bot.Send(msg) //nolint:errcheck
|
||||
return
|
||||
}
|
||||
|
||||
// 7. Ни одна роль не подошла — показываем карточку без действий (просмотр)
|
||||
msg := tgbotapi.NewMessage(chatID, card)
|
||||
msg.ParseMode = "HTML"
|
||||
bot.Send(msg) //nolint:errcheck
|
||||
}
|
||||
|
||||
// canUserAccessObserverView проверяет, входит ли пользователь в список наблюдателей
|
||||
// для категории/темы этой заявки.
|
||||
func (h *Handler) canUserAccessObserverView(ctx context.Context, userID uint64, categoryCode string, topicID *uint64) bool {
|
||||
observers, err := h.ipc.Database.User.GetObserversForApprovalDB(ctx, categoryCode, topicID)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
for _, obs := range observers {
|
||||
if obs.ID != nil && *obs.ID == userID {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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,58 @@ 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()
|
||||
}
|
||||
|
||||
// BuildRevocationApprovalDecision — Да/Нет для согласующего, дающего согласие на отзыв
|
||||
func BuildRevocationApprovalDecision(approvalID uint64, requestID uint64, commentsCount int) tgbotapi.InlineKeyboardMarkup {
|
||||
return tgkit.NewInlineKeyboard().
|
||||
Row(
|
||||
tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "✅ Да", fmt.Sprintf("revoke_appr_yes:%d", requestID)),
|
||||
tgkit.BtnStyled(tgkit.ButtonStyleDanger, "❌ Нет", fmt.Sprintf("revoke_appr_no:%d", requestID)),
|
||||
).
|
||||
Row(
|
||||
tgkit.Btn("💬 Добавить комментарий", fmt.Sprintf("appr_comment:%d", approvalID)),
|
||||
buildCommentsButton(approvalID, commentsCount),
|
||||
).
|
||||
Build()
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue