Added notifications routes && 2 new db tables #56
|
|
@ -34,6 +34,7 @@ type ModuleDB struct {
|
|||
ApprovalAdditionalObserver *dbcore.ApprovalAdditionalObserverDB
|
||||
ApprovalTopicExecutor *dbcore.ApprovalTopicExecutorDB
|
||||
Admin *dbcore.AdminDB
|
||||
Notification *dbcore.NotificationDB
|
||||
}
|
||||
|
||||
func NewModuleDB(
|
||||
|
|
@ -84,6 +85,7 @@ func initDBModules(modules *ModuleDB, redisClient *redismodule.ModuleRedis) *Mod
|
|||
modules.ApprovalAdditionalObserver = dbcore.NewApprovalAdditionalObserverDB(modules.Pool)
|
||||
modules.ApprovalTopicExecutor = dbcore.NewApprovalTopicExecutorDB(modules.Pool)
|
||||
modules.Admin = dbcore.NewAdminDB(modules.Pool)
|
||||
modules.Notification = dbcore.NewNotificationDB(modules.Pool)
|
||||
|
||||
return modules
|
||||
}
|
||||
|
|
|
|||
|
|
@ -38,6 +38,8 @@ func (m *MigrationFunctions) migrateTables() error {
|
|||
tablesmigration.ApprovalAdditionalObserverTableMigrate,
|
||||
tablesmigration.ApprovalTopicExecutorsTableMigrate,
|
||||
tablesmigration.AdminsTableMigrate,
|
||||
|
||||
tablesmigration.NotificationsTableMigrate,
|
||||
}
|
||||
|
||||
for _, migrate := range migrations {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,66 @@
|
|||
package tablesmigration
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
"time"
|
||||
)
|
||||
|
||||
func NotificationsTableMigrate(db *gorm.DB) error {
|
||||
hasNotificationsTable := db.Migrator().HasTable(&LocalNotificationProvider{})
|
||||
hasRecipientsTable := db.Migrator().HasTable(&LocalNotificationRecipientProvider{})
|
||||
|
||||
if err := db.AutoMigrate(&LocalNotificationProvider{}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := db.AutoMigrate(&LocalNotificationRecipientProvider{}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !hasNotificationsTable || !hasRecipientsTable {
|
||||
time.Sleep(5 * time.Second)
|
||||
|
||||
db.Exec(`ALTER TABLE notifications ADD CONSTRAINT fk_notifications_created_by_id FOREIGN KEY (created_by_id) REFERENCES users(id) ON DELETE SET NULL ON UPDATE CASCADE`)
|
||||
|
||||
db.Exec(`ALTER TABLE notification_recipients ADD CONSTRAINT fk_notification_recipients_notification_id FOREIGN KEY (notification_id) REFERENCES notifications(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
db.Exec(`ALTER TABLE notification_recipients ADD CONSTRAINT fk_notification_recipients_user_id FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
|
||||
execComments(db, `
|
||||
COMMENT ON TABLE "notifications" IS 'Уведомления/рассылки, отправляемые администратором через Telegram-бота';
|
||||
COMMENT ON COLUMN "notifications".id IS 'Внутренний ID уведомления';
|
||||
COMMENT ON COLUMN "notifications".title IS 'Заголовок рассылки (для админки, не отправляется в Telegram)';
|
||||
COMMENT ON COLUMN "notifications".message_html IS 'Текст сообщения в HTML-разметке, совместимой с Telegram ParseMode=HTML';
|
||||
COMMENT ON COLUMN "notifications".photo_base64 IS 'Прикреплённое фото в формате base64, опционально';
|
||||
COMMENT ON COLUMN "notifications".photo_file_name IS 'Оригинальное имя прикреплённого файла фото';
|
||||
COMMENT ON COLUMN "notifications".target_filters IS 'Критерии выбора получателей (user_ids, role_ids, role_type_flags, department_ids) в формате JSON, для аудита';
|
||||
COMMENT ON COLUMN "notifications".status IS 'Статус рассылки: pending | sending | completed | failed';
|
||||
COMMENT ON COLUMN "notifications".total_count IS 'Общее число подобранных получателей';
|
||||
COMMENT ON COLUMN "notifications".sent_count IS 'Число успешно доставленных сообщений';
|
||||
COMMENT ON COLUMN "notifications".failed_count IS 'Число сообщений с ошибкой доставки';
|
||||
COMMENT ON COLUMN "notifications".created_by_id IS 'Администратор, инициировавший рассылку';
|
||||
COMMENT ON COLUMN "notifications".created_at IS 'Дата создания рассылки';
|
||||
COMMENT ON COLUMN "notifications".updated_at IS 'Дата последнего изменения статуса рассылки';
|
||||
COMMENT ON COLUMN "notifications".sent_at IS 'Дата фактической отправки рассылки получателям';
|
||||
|
||||
COMMENT ON TABLE "notification_recipients" IS 'История доставки уведомления конкретным пользователям';
|
||||
COMMENT ON COLUMN "notification_recipients".id IS 'Внутренний ID записи истории доставки';
|
||||
COMMENT ON COLUMN "notification_recipients".notification_id IS 'Уведомление, к которому относится доставка';
|
||||
COMMENT ON COLUMN "notification_recipients".user_id IS 'Получатель уведомления';
|
||||
COMMENT ON COLUMN "notification_recipients".status IS 'Статус доставки: pending | sent | failed';
|
||||
COMMENT ON COLUMN "notification_recipients".error_message IS 'Текст ошибки при неудачной отправке';
|
||||
COMMENT ON COLUMN "notification_recipients".telegram_message_id IS 'ID отправленного сообщения в Telegram, если доставка успешна';
|
||||
COMMENT ON COLUMN "notification_recipients".sent_at IS 'Дата и время фактической отправки этому получателю';
|
||||
COMMENT ON COLUMN "notification_recipients".created_at IS 'Дата создания записи (постановка в очередь на отправку)';
|
||||
`)
|
||||
}
|
||||
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_notifications_status ON notifications (status)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_notifications_created_at ON notifications (created_at DESC)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_notifications_created_by_id ON notifications (created_by_id)`)
|
||||
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_notification_recipients_notification_id ON notification_recipients (notification_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_notification_recipients_user_id ON notification_recipients (user_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_notification_recipients_status ON notification_recipients (status)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_notification_recipients_notification_status ON notification_recipients (notification_id, status)`)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
@ -24,6 +24,8 @@ type ApprovalCommentsProvider typescore.ApprovalComment
|
|||
type LocalSuggestionProvider typescore.Suggestion
|
||||
type LocalSuggestionMessagesProvider typescore.SuggestionMessage
|
||||
type LocalApprovalTopicExecutorProvider typescore.ApprovalTopicExecutor
|
||||
type LocalNotificationProvider typescore.Notification
|
||||
type LocalNotificationRecipientProvider typescore.NotificationRecipient
|
||||
|
||||
func (LocalUserProvider) TableName() string {
|
||||
return dbcoretablenames.TableNameUsers.ToString()
|
||||
|
|
@ -82,3 +84,11 @@ func (ApprovalAdditionalObserver) TableName() string {
|
|||
func (LocalApprovalTopicExecutorProvider) TableName() string {
|
||||
return dbcoretablenames.TableNameApprovalTopicExecutor.ToString()
|
||||
}
|
||||
|
||||
func (LocalNotificationProvider) TableName() string {
|
||||
return dbcoretablenames.TableNameNotifications.ToString()
|
||||
}
|
||||
|
||||
func (LocalNotificationRecipientProvider) TableName() string {
|
||||
return dbcoretablenames.TableNameNotificationsRecipients.ToString()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,169 @@
|
|||
package dbcore
|
||||
|
||||
import (
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
dbutils "bitrix_balancer_api/core/utilscore/db"
|
||||
"context"
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type NotificationDB struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewNotificationDB(pool *pgxpool.Pool) *NotificationDB {
|
||||
return &NotificationDB{pool: pool}
|
||||
}
|
||||
|
||||
type NotificationDBI interface {
|
||||
CreateNotificationDB(ctx context.Context, n *typescore.Notification) (*typescore.Notification, error)
|
||||
UpdateNotificationDB(ctx context.Context, n *typescore.Notification) error
|
||||
GetNotificationsListDB(ctx context.Context, opts typescore.ListDbOptions) ([]*typescore.Notification, uint64, error)
|
||||
GetNotificationByIDDB(ctx context.Context, id uint64) (*typescore.Notification, error)
|
||||
|
||||
CreateNotificationRecipientsDB(ctx context.Context, recipients []*typescore.NotificationRecipient) error
|
||||
UpdateNotificationRecipientDB(ctx context.Context, r *typescore.NotificationRecipient) error
|
||||
GetNotificationRecipientsDB(ctx context.Context, notificationID uint64) ([]*typescore.NotificationRecipient, error)
|
||||
}
|
||||
|
||||
func (n *NotificationDB) CreateNotificationDB(ctx context.Context, obj *typescore.Notification) (*typescore.Notification, error) {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Insert("notifications")
|
||||
|
||||
sqlV, args, err := dbutils.GenerateInsertRequest(query, obj)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var newID uint64
|
||||
sqlStr := *sqlV + " RETURNING id"
|
||||
err = n.pool.QueryRow(ctx, sqlStr, args...).Scan(&newID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
obj.ID = &newID
|
||||
return obj, nil
|
||||
}
|
||||
|
||||
func (n *NotificationDB) UpdateNotificationDB(ctx context.Context, obj *typescore.Notification) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Update("notifications")
|
||||
query = dbutils.AddNonNullFieldsToQueryUpdate(query, *obj)
|
||||
query = query.Where(squirrel.Eq{"id": obj.ID})
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = n.pool.Exec(ctx, sql, args...)
|
||||
return err
|
||||
}
|
||||
|
||||
func (n *NotificationDB) GetNotificationsListDB(ctx context.Context, opts typescore.ListDbOptions) ([]*typescore.Notification, uint64, error) {
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.Notification{}, "notifications")
|
||||
selectFields := append(fields, "COUNT(*) OVER() AS total_count")
|
||||
|
||||
query := dbutils.BuildSelectQuery("notifications", selectFields)
|
||||
query = dbutils.SetterLimitAndOffsetQuery(query, opts.Offset, opts.Limit)
|
||||
query = query.OrderBy("created_at DESC")
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
rows, err := n.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var result []*typescore.Notification
|
||||
var total uint64
|
||||
for rows.Next() {
|
||||
obj := &typescore.Notification{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, obj, &total); err != nil {
|
||||
continue
|
||||
}
|
||||
result = append(result, obj)
|
||||
}
|
||||
return result, total, nil
|
||||
}
|
||||
|
||||
func (n *NotificationDB) GetNotificationByIDDB(ctx context.Context, id uint64) (*typescore.Notification, error) {
|
||||
list, _, err := n.GetNotificationsListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.Notification{ID: &id},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(list) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return list[0], nil
|
||||
}
|
||||
|
||||
func (n *NotificationDB) CreateNotificationRecipientsDB(ctx context.Context, recipients []*typescore.NotificationRecipient) error {
|
||||
if len(recipients) == 0 {
|
||||
return nil
|
||||
}
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Insert("notification_recipients").
|
||||
Columns("notification_id", "user_id", "status")
|
||||
|
||||
for _, r := range recipients {
|
||||
query = query.Values(*r.NotificationID, *r.UserID, *r.Status)
|
||||
}
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = n.pool.Exec(ctx, sql, args...)
|
||||
return err
|
||||
}
|
||||
|
||||
func (n *NotificationDB) UpdateNotificationRecipientDB(ctx context.Context, r *typescore.NotificationRecipient) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Update("notification_recipients")
|
||||
query = dbutils.AddNonNullFieldsToQueryUpdate(query, *r)
|
||||
query = query.Where(squirrel.Eq{"id": r.ID})
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = n.pool.Exec(ctx, sql, args...)
|
||||
return err
|
||||
}
|
||||
|
||||
func (n *NotificationDB) GetNotificationRecipientsDB(ctx context.Context, notificationID uint64) ([]*typescore.NotificationRecipient, error) {
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.NotificationRecipient{}, "notification_recipients")
|
||||
|
||||
sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select(fields...).
|
||||
From("notification_recipients").
|
||||
Where(squirrel.Eq{"notification_id": notificationID}).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err := n.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var result []*typescore.NotificationRecipient
|
||||
for rows.Next() {
|
||||
obj := &typescore.NotificationRecipient{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, obj, nil); err != nil {
|
||||
continue
|
||||
}
|
||||
result = append(result, obj)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
|
@ -43,6 +43,8 @@ type UserDBI interface {
|
|||
|
||||
IsControllerDB(ctx context.Context, userID uint64) (bool, error)
|
||||
GetControllerObserversForApprovalDB(ctx context.Context, categoryCode string, topicID *uint64) ([]*typescore.User, error)
|
||||
GetUsersByRoleFlagsDB(ctx context.Context, flags []string) ([]*typescore.User, error)
|
||||
GetUsersByDepartmentIDsDB(ctx context.Context, departmentIDs []uint64) ([]*typescore.User, error)
|
||||
}
|
||||
|
||||
func (u *UserDB) GetUsersListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.User, uint64, error) {
|
||||
|
|
@ -692,3 +694,94 @@ func (u *UserDB) GetControllerObserversForApprovalDB(
|
|||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// GetUsersByRoleFlagsDB — пользователи, у которых есть роль с любым из указанных флагов
|
||||
// (is_director, is_approver, is_observer, is_executor, is_controller)
|
||||
func (u *UserDB) GetUsersByRoleFlagsDB(ctx context.Context, flags []string) ([]*typescore.User, error) {
|
||||
if len(flags) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
allowedFlags := map[string]string{
|
||||
"director": "r.is_director",
|
||||
"approver": "r.is_approver",
|
||||
"observer": "r.is_observer",
|
||||
"executor": "r.is_executor",
|
||||
"controller": "r.is_controller",
|
||||
}
|
||||
|
||||
var orConds squirrel.Or
|
||||
for _, f := range flags {
|
||||
if col, ok := allowedFlags[f]; ok {
|
||||
orConds = append(orConds, squirrel.Expr(col+" = true"))
|
||||
}
|
||||
}
|
||||
if len(orConds) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select("DISTINCT u.*").
|
||||
From(dbcoretablenames.TableNameUsers.ToString() + " u").
|
||||
Join(dbcoretablenames.TableNameUserRoles.ToString() + " ur ON ur.user_id = u.id").
|
||||
Join(dbcoretablenames.TableNameRoles.ToString() + " r ON r.id = ur.role_id").
|
||||
Where(orConds).
|
||||
Where(squirrel.Eq{"u.is_blocked": false}).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var users []*typescore.User
|
||||
for rows.Next() {
|
||||
user := &typescore.User{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, user, nil); err != nil {
|
||||
logrus.Warn("GetUsersByRoleFlagsDB:ScanRowsToStructRows", err)
|
||||
continue
|
||||
}
|
||||
users = append(users, user)
|
||||
}
|
||||
return users, nil
|
||||
}
|
||||
|
||||
// GetUsersByDepartmentIDsDB — пользователи из списка отделов
|
||||
func (u *UserDB) GetUsersByDepartmentIDsDB(ctx context.Context, departmentIDs []uint64) ([]*typescore.User, error) {
|
||||
if len(departmentIDs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.User{}, dbcoretablenames.TableNameUsers.ToString())
|
||||
|
||||
sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select(fields...).
|
||||
From(dbcoretablenames.TableNameUsers.ToString()).
|
||||
Where(squirrel.Eq{"department_id": departmentIDs}).
|
||||
Where(squirrel.Eq{"is_blocked": false}).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var users []*typescore.User
|
||||
for rows.Next() {
|
||||
user := &typescore.User{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, user, nil); err != nil {
|
||||
logrus.Warn("GetUsersByDepartmentIDsDB:ScanRowsToStructRows", err)
|
||||
continue
|
||||
}
|
||||
users = append(users, user)
|
||||
}
|
||||
return users, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -23,6 +23,8 @@ const (
|
|||
TableNameSuggestionMessages TableName = "suggestion_messages"
|
||||
TableNameApprovalTopicExecutor TableName = "approval_topic_executor"
|
||||
TableNameAdmin TableName = "admin"
|
||||
TableNameNotifications TableName = "notifications"
|
||||
TableNameNotificationsRecipients TableName = "notification_recipients"
|
||||
)
|
||||
|
||||
func (t TableName) ToString() string {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,54 @@
|
|||
package typescore
|
||||
|
||||
import "time"
|
||||
|
||||
// Notification — рассылка/уведомление
|
||||
type Notification struct {
|
||||
ID *uint64 `gorm:"column:id" json:"id" db:"id"`
|
||||
Title *string `gorm:"column:title" json:"title" db:"title"`
|
||||
MessageHTML *string `gorm:"column:message_html" json:"message_html" db:"message_html"`
|
||||
PhotoBase64 *string `gorm:"column:photo_base64" json:"photo_base64,omitempty" db:"photo_base64"`
|
||||
PhotoFileName *string `gorm:"column:photo_file_name" json:"photo_file_name,omitempty" db:"photo_file_name"`
|
||||
TargetFilters *string `gorm:"column:target_filters" json:"target_filters" db:"target_filters"` // JSON-строка
|
||||
Status *string `gorm:"column:status" json:"status" db:"status"`
|
||||
TotalCount *int `gorm:"column:total_count" json:"total_count" db:"total_count"`
|
||||
SentCount *int `gorm:"column:sent_count" json:"sent_count" db:"sent_count"`
|
||||
FailedCount *int `gorm:"column:failed_count" json:"failed_count" db:"failed_count"`
|
||||
CreatedByID *uint64 `gorm:"column:created_by_id" json:"created_by_id,omitempty" db:"created_by_id"`
|
||||
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"`
|
||||
SentAt *time.Time `gorm:"column:sent_at" json:"sent_at,omitempty" db:"sent_at"`
|
||||
|
||||
Recipients []*NotificationRecipient `gorm:"-" json:"recipients,omitempty"`
|
||||
}
|
||||
|
||||
// NotificationRecipient — история доставки конкретному пользователю
|
||||
type NotificationRecipient struct {
|
||||
ID *uint64 `gorm:"column:id" json:"id" db:"id"`
|
||||
NotificationID *uint64 `gorm:"column:notification_id" json:"notification_id" db:"notification_id"`
|
||||
UserID *uint64 `gorm:"column:user_id" json:"user_id" db:"user_id"`
|
||||
Status *string `gorm:"column:status" json:"status" db:"status"`
|
||||
ErrorMessage *string `gorm:"column:error_message" json:"error_message,omitempty" db:"error_message"`
|
||||
TelegramMessageID *int `gorm:"column:telegram_message_id" json:"telegram_message_id,omitempty" db:"telegram_message_id"`
|
||||
SentAt *time.Time `gorm:"column:sent_at" json:"sent_at,omitempty" db:"sent_at"`
|
||||
CreatedAt *time.Time `gorm:"column:created_at" json:"created_at" db:"created_at"`
|
||||
|
||||
User *User `gorm:"-" json:"user,omitempty"`
|
||||
}
|
||||
|
||||
// TargetFilters — критерии выбора получателей, приходят из админки и сохраняются как есть в JSONB
|
||||
type TargetFilters struct {
|
||||
UserIDs []uint64 `json:"user_ids,omitempty"` // 1. конкретные пользователи
|
||||
RoleIDs []uint64 `json:"role_ids,omitempty"` // 2. конкретные роли (по id)
|
||||
RoleTypeFlags []string `json:"role_type_flags,omitempty"` // 3. типы ролей: director|approver|observer|executor|controller
|
||||
DepartmentIDs []uint64 `json:"department_ids,omitempty"` // 4. отделы
|
||||
}
|
||||
|
||||
// CreateNotificationReq — тело запроса на создание+отправку рассылки
|
||||
type CreateNotificationReq struct {
|
||||
Title string `json:"title"`
|
||||
MessageHTML string `json:"message_html"`
|
||||
PhotoBase64 *string `json:"photo_base64,omitempty"`
|
||||
PhotoFileName *string `json:"photo_file_name,omitempty"`
|
||||
Targets TargetFilters `json:"targets"`
|
||||
}
|
||||
|
|
@ -11,6 +11,7 @@ import (
|
|||
authhandler "bitrix_balancer_api/rest_admin_service/handlers/auth"
|
||||
dashboardhandler "bitrix_balancer_api/rest_admin_service/handlers/dashboard"
|
||||
departmentshandler "bitrix_balancer_api/rest_admin_service/handlers/departments"
|
||||
notificationshandler "bitrix_balancer_api/rest_admin_service/handlers/notification"
|
||||
permissionshandler "bitrix_balancer_api/rest_admin_service/handlers/permission"
|
||||
profilehandler "bitrix_balancer_api/rest_admin_service/handlers/profile"
|
||||
roleshandler "bitrix_balancer_api/rest_admin_service/handlers/roles"
|
||||
|
|
@ -217,6 +218,7 @@ func registerRoutes(router chi.Router, ipc *typesm.InternalProviderControl) erro
|
|||
{"permissions", permissionshandler.RegisterPermissionRoutes},
|
||||
{"approval-tasks", approvaltaskshandler.RegisterApprovalTasksRoutes},
|
||||
{"dashboard", dashboardhandler.RegisterDashboardRoutes},
|
||||
{"notifications", notificationshandler.RegisterNotificationRoutes},
|
||||
}
|
||||
|
||||
// Регистрация всех маршрутов
|
||||
|
|
|
|||
|
|
@ -0,0 +1,278 @@
|
|||
package notificationshandler
|
||||
|
||||
import (
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
"bitrix_balancer_api/core/utilscore"
|
||||
typesm "bitrix_balancer_api/rest_admin_service/types"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/sirupsen/logrus"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type NotificationReg struct {
|
||||
ipc *typesm.InternalProviderControl
|
||||
}
|
||||
|
||||
func (s *NotificationReg) CreateNotificationHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer r.Body.Close()
|
||||
|
||||
var req typescore.CreateNotificationReq
|
||||
if err := json.Unmarshal(body, &req); err != nil {
|
||||
return nil, errors.New("invalid request body")
|
||||
}
|
||||
if req.Title == "" || req.MessageHTML == "" {
|
||||
return nil, errors.New("title and message_html are required")
|
||||
}
|
||||
|
||||
ctx := r.Context()
|
||||
|
||||
// 1. Резолвим получателей по всем критериям, объединяем через map по user.ID (дедупликация)
|
||||
recipients, err := s.resolveRecipients(ctx, req.Targets)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(recipients) == 0 {
|
||||
return nil, errors.New("no recipients matched the given filters")
|
||||
}
|
||||
|
||||
targetFiltersJSON, err := json.Marshal(req.Targets)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
targetFiltersStr := string(targetFiltersJSON)
|
||||
|
||||
status := "sending"
|
||||
totalCount := len(recipients)
|
||||
notification := &typescore.Notification{
|
||||
Title: &req.Title,
|
||||
MessageHTML: &req.MessageHTML,
|
||||
PhotoBase64: req.PhotoBase64,
|
||||
PhotoFileName: req.PhotoFileName,
|
||||
TargetFilters: &targetFiltersStr,
|
||||
Status: &status,
|
||||
TotalCount: &totalCount,
|
||||
}
|
||||
|
||||
notification, err = s.ipc.Database.Notification.CreateNotificationDB(ctx, notification)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 2. Создаём строки истории со статусом pending для каждого получателя
|
||||
pendingStatus := "pending"
|
||||
recipientRows := make([]*typescore.NotificationRecipient, 0, len(recipients))
|
||||
for _, u := range recipients {
|
||||
recipientRows = append(recipientRows, &typescore.NotificationRecipient{
|
||||
NotificationID: notification.ID,
|
||||
UserID: u.ID,
|
||||
Status: &pendingStatus,
|
||||
})
|
||||
}
|
||||
if err := s.ipc.Database.Notification.CreateNotificationRecipientsDB(ctx, recipientRows); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 3. Отправляем синхронно (для больших рассылок стоит вынести в очередь/горутину с ограничением по rate)
|
||||
sentCount, failedCount := s.sendToRecipients(ctx, notification, recipients)
|
||||
|
||||
finalStatus := "completed"
|
||||
notification.Status = &finalStatus
|
||||
notification.SentCount = &sentCount
|
||||
notification.FailedCount = &failedCount
|
||||
if err := s.ipc.Database.Notification.UpdateNotificationDB(ctx, notification); err != nil {
|
||||
logrus.Warnf("CreateNotificationHandler: failed to update final status: %v", err)
|
||||
}
|
||||
|
||||
return notification, nil
|
||||
}
|
||||
|
||||
// resolveRecipients объединяет пользователей из всех критериев без дублей
|
||||
func (s *NotificationReg) resolveRecipients(ctx context.Context, filters typescore.TargetFilters) ([]*typescore.User, error) {
|
||||
usersMap := make(map[uint64]*typescore.User)
|
||||
|
||||
addUsers := func(list []*typescore.User) {
|
||||
for _, u := range list {
|
||||
if u.ID != nil {
|
||||
usersMap[*u.ID] = u
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 1. Конкретные пользователи
|
||||
if len(filters.UserIDs) > 0 {
|
||||
users, err := s.ipc.Database.User.GetUsersByIDsDB(ctx, filters.UserIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
addUsers(users)
|
||||
}
|
||||
|
||||
// 2. По ролям (id)
|
||||
if len(filters.RoleIDs) > 0 {
|
||||
users, _, err := s.ipc.Database.User.GetUsersListByRoleIDsDB(ctx, typescore.ListDbOptions{}, filters.RoleIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
addUsers(users)
|
||||
}
|
||||
|
||||
// 3. По типу роли (флаги)
|
||||
if len(filters.RoleTypeFlags) > 0 {
|
||||
users, err := s.ipc.Database.User.GetUsersByRoleFlagsDB(ctx, filters.RoleTypeFlags)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
addUsers(users)
|
||||
}
|
||||
|
||||
// 4. По отделу
|
||||
if len(filters.DepartmentIDs) > 0 {
|
||||
users, err := s.ipc.Database.User.GetUsersByDepartmentIDsDB(ctx, filters.DepartmentIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
addUsers(users)
|
||||
}
|
||||
|
||||
result := make([]*typescore.User, 0, len(usersMap))
|
||||
for _, u := range usersMap {
|
||||
// не шлём заблокированным/уволенным, даже если попали через явный user_id
|
||||
if u.IsBlocked != nil && *u.IsBlocked {
|
||||
continue
|
||||
}
|
||||
result = append(result, u)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// sendToRecipients рассылает сообщение всем найденным пользователям и фиксирует результат по каждому
|
||||
func (s *NotificationReg) sendToRecipients(ctx context.Context, n *typescore.Notification, users []*typescore.User) (sent int, failed int) {
|
||||
pendingRecipients, err := s.ipc.Database.Notification.GetNotificationRecipientsDB(ctx, *n.ID)
|
||||
if err != nil {
|
||||
logrus.Errorf("sendToRecipients: failed to load recipients: %v", err)
|
||||
return 0, len(users)
|
||||
}
|
||||
|
||||
recipientByUserID := make(map[uint64]*typescore.NotificationRecipient)
|
||||
for _, r := range pendingRecipients {
|
||||
if r.UserID != nil {
|
||||
recipientByUserID[*r.UserID] = r
|
||||
}
|
||||
}
|
||||
|
||||
sentStatus := "sent"
|
||||
failedStatus := "failed"
|
||||
|
||||
for _, u := range users {
|
||||
if u.TelegramID == nil {
|
||||
continue
|
||||
}
|
||||
rec, ok := recipientByUserID[*u.ID]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
var sendErr error
|
||||
var msgID int
|
||||
|
||||
if n.PhotoBase64 != nil && *n.PhotoBase64 != "" {
|
||||
fileName := "notification.jpg"
|
||||
if n.PhotoFileName != nil {
|
||||
fileName = *n.PhotoFileName
|
||||
}
|
||||
sentMsg, err := s.ipc.TGBotClient.SendPhoto(*u.TelegramID, *n.PhotoBase64, *n.MessageHTML)
|
||||
if err != nil {
|
||||
sendErr = err
|
||||
} else {
|
||||
msgID = sentMsg.MessageID
|
||||
}
|
||||
_ = fileName // caption уже ушёл через SendPhoto
|
||||
} else {
|
||||
sentMsg, err := s.ipc.TGBotClient.Send(*u.TelegramID, *n.MessageHTML)
|
||||
if err != nil {
|
||||
sendErr = err
|
||||
} else {
|
||||
msgID = sentMsg.MessageID
|
||||
}
|
||||
}
|
||||
|
||||
if sendErr != nil {
|
||||
errStr := sendErr.Error()
|
||||
rec.Status = &failedStatus
|
||||
rec.ErrorMessage = &errStr
|
||||
failed++
|
||||
} else {
|
||||
rec.Status = &sentStatus
|
||||
rec.TelegramMessageID = &msgID
|
||||
sent++
|
||||
}
|
||||
|
||||
if err := s.ipc.Database.Notification.UpdateNotificationRecipientDB(ctx, rec); err != nil {
|
||||
logrus.Warnf("sendToRecipients: failed to update recipient status: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
return sent, failed
|
||||
}
|
||||
|
||||
// GetNotificationListHandler — история отправленных уведомлений
|
||||
func (s *NotificationReg) GetNotificationListHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
|
||||
queryParams := r.URL.Query()
|
||||
|
||||
notificationParams := &typescore.Notification{}
|
||||
offset, limit, likeFields, errW := utilscore.ParseParamsGetRequest(queryParams, notificationParams)
|
||||
if errW != nil {
|
||||
return nil, errW
|
||||
}
|
||||
|
||||
options := typescore.ListDbOptions{
|
||||
Filtering: notificationParams,
|
||||
Offset: offset,
|
||||
Limit: limit,
|
||||
LikeFields: likeFields,
|
||||
}
|
||||
|
||||
list, total, err := s.ipc.Database.Notification.GetNotificationsListDB(r.Context(), options)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &typescore.ApiResponseBase{
|
||||
TotalCount: total,
|
||||
Data: list,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// GetNotificationByIDHandler — детали конкретной рассылки с постатейной историей доставки
|
||||
func (s *NotificationReg) GetNotificationByIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
|
||||
idStr := chi.URLParam(r, "id")
|
||||
id, err := strconv.ParseUint(idStr, 10, 64)
|
||||
if err != nil {
|
||||
return nil, errors.New("invalid notification id")
|
||||
}
|
||||
|
||||
ctx := r.Context()
|
||||
notification, err := s.ipc.Database.Notification.GetNotificationByIDDB(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if notification == nil {
|
||||
return nil, errors.New("notification not found")
|
||||
}
|
||||
|
||||
recipients, err := s.ipc.Database.Notification.GetNotificationRecipientsDB(ctx, id)
|
||||
if err == nil {
|
||||
notification.Recipients = recipients
|
||||
}
|
||||
|
||||
return notification, nil
|
||||
}
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
package notificationshandler
|
||||
|
||||
import (
|
||||
"bitrix_balancer_api/rest_admin_service/handlers"
|
||||
typesm "bitrix_balancer_api/rest_admin_service/types"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
func RegisterNotificationRoutes(r chi.Router, ipc *typesm.InternalProviderControl) error {
|
||||
s := &NotificationReg{ipc: ipc}
|
||||
|
||||
r.Route("/api/notifications", func(r chi.Router) {
|
||||
r.Use(handlers.AccessCodeVerifier(ipc.Config))
|
||||
r.Use(handlers.JWTVerifier(ipc.Config, ipc.Database.Admin, ipc.RedisClient))
|
||||
|
||||
handlers.RegisterRoute(r, http.MethodPost, "/", s.CreateNotificationHandler)
|
||||
handlers.RegisterRoute(r, http.MethodGet, "/", s.GetNotificationListHandler)
|
||||
r.Get("/{id}", handlers.WrapHandlerF(handlers.WrapHandlerParams{
|
||||
HandlerFunc: s.GetNotificationByIDHandler,
|
||||
}))
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
Loading…
Reference in New Issue