feat: 迁移预警处理审核与备注附件流程
This commit is contained in:
@@ -0,0 +1,87 @@
|
||||
package business
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"slices"
|
||||
"strconv"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// 旧迁移 SQL 保留日志附件 JSON。只转换有原始备份且尚未变更的旧日志,避免误映射新文件 ID。
|
||||
func migrateAlertAttachments(db *gorm.DB) error {
|
||||
tables, err := db.Migrator().GetTables()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, name := range []string{"sys_alert_operation_log", "sw_kra_id_map", "bak_sw2kra_20261103_sys_alert_operation_log"} {
|
||||
if !slices.Contains(tables, name) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
var lastID uint64
|
||||
for {
|
||||
var rows []struct {
|
||||
ID uint64
|
||||
Current *string
|
||||
Legacy *string
|
||||
}
|
||||
if err := db.Table("sys_alert_operation_log l").Select("l.id,l.attachment_ids AS current,b.attachment_ids AS legacy").Joins("JOIN bak_sw2kra_20261103_sys_alert_operation_log b ON b.id=l.id").Where("l.id > ?", lastID).Order("l.id").Limit(500).Scan(&rows).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return nil
|
||||
}
|
||||
pending := map[uint64][]int64{}
|
||||
oldIDs := []string{}
|
||||
for _, row := range rows {
|
||||
lastID = row.ID
|
||||
current, ids := decodeAlertAttachments(row.Current)
|
||||
legacy, legacyIDs := decodeAlertAttachments(row.Legacy)
|
||||
if len(ids) == 0 || len(legacyIDs) == 0 || !slices.Equal(current, legacy) {
|
||||
continue
|
||||
}
|
||||
pending[row.ID] = ids
|
||||
for _, id := range ids {
|
||||
oldIDs = append(oldIDs, strconv.FormatInt(id, 10))
|
||||
}
|
||||
}
|
||||
if len(pending) == 0 {
|
||||
continue
|
||||
}
|
||||
mapped := map[int64]int64{}
|
||||
for start := 0; start < len(oldIDs); start += 500 {
|
||||
var mappings []struct {
|
||||
OldID string
|
||||
NewID int64
|
||||
}
|
||||
if err := db.Table("sw_kra_id_map").Select("old_id,new_id").Where("entity = ? AND old_id IN ?", "file", oldIDs[start:min(start+500, len(oldIDs))]).Scan(&mappings).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
for _, m := range mappings {
|
||||
id, err := strconv.ParseInt(m.OldID, 10, 64)
|
||||
if err == nil {
|
||||
mapped[id] = m.NewID
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := db.Transaction(func(tx *gorm.DB) error {
|
||||
for logID, ids := range pending {
|
||||
newIDs := []int64{}
|
||||
for _, id := range ids {
|
||||
// 缺失旧文件原本不展示,不能把旧 ID 当成同号的新文件;原始引用仍保留在备份中。
|
||||
if newID, ok := mapped[id]; ok {
|
||||
newIDs = append(newIDs, newID)
|
||||
}
|
||||
}
|
||||
raw, _ := json.Marshal(newIDs)
|
||||
if err := tx.Table("sys_alert_operation_log").Where("id = ?", logID).Update("attachment_ids", string(raw)).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,329 @@
|
||||
package business
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
"kra/internal/biz/business"
|
||||
)
|
||||
|
||||
type alertRecordRepo struct{ data Provider }
|
||||
|
||||
func NewAlertRecordRepo(data Provider) business.AlertRecordRepo { return &alertRecordRepo{data: data} }
|
||||
|
||||
func toBizAlertRecord(po alertRecordPO) *business.AlertRecord {
|
||||
return &business.AlertRecord{ID: po.ID, RuleID: po.RuleID, PlatformCode: po.PlatformCode, PlatformName: po.PlatformName, RuleName: po.RuleName, RuleType: po.RuleType, MonitorMetric: po.MonitorMetric, TargetPromoteID: po.TargetPromoteID, TargetPromoteName: po.TargetPromoteName, BusinessID: po.BusinessID, BusinessName: po.BusinessName, AlertContent: po.AlertContent, Status: po.Status, CreatedAt: po.CreatedAt, UpdatedAt: po.UpdatedAt}
|
||||
}
|
||||
|
||||
func alertBindingQuery(db *gorm.DB, scope business.UserScope) *gorm.DB {
|
||||
q := db.Table("sys_user_bind_platform b").Where("b.status = ? AND b.source_db IN ? AND b.platform_busier_id IS NOT NULL", "0", []string{"lx", "hw", "yq"})
|
||||
if !scope.All {
|
||||
q = q.Joins("JOIN sys_users u ON u.id=b.user_id AND u.deleted_at IS NULL")
|
||||
q = applyUserScope(q, scope, "u.")
|
||||
}
|
||||
return q
|
||||
}
|
||||
|
||||
func alertChannelScopes(scope business.AlertRecordScope) []business.UserScope {
|
||||
var scopes []business.UserScope
|
||||
if !scope.Viewer.All {
|
||||
scopes = append(scopes, scope.Viewer)
|
||||
}
|
||||
if scope.Selected != nil {
|
||||
scopes = append(scopes, *scope.Selected)
|
||||
}
|
||||
return scopes
|
||||
}
|
||||
|
||||
// 先判断没有绑定的确定空集,再检查渠道表;缺表不能放宽权限或伪造统计。
|
||||
func prepareAlertScope(db *gorm.DB, scope business.AlertRecordScope) (empty, available bool, err error) {
|
||||
if scope.Owner.Empty {
|
||||
return true, true, nil
|
||||
}
|
||||
scopes := alertChannelScopes(scope)
|
||||
for _, s := range scopes {
|
||||
if s.Empty {
|
||||
return true, true, nil
|
||||
}
|
||||
var count int64
|
||||
if err := alertBindingQuery(db, s).Count(&count).Error; err != nil {
|
||||
return false, false, business.ErrStorage
|
||||
}
|
||||
if count == 0 {
|
||||
return true, true, nil
|
||||
}
|
||||
}
|
||||
if len(scopes) == 0 {
|
||||
return false, true, nil
|
||||
}
|
||||
available, err = businessTableAvailable(db, "tab_promote")
|
||||
return false, available, err
|
||||
}
|
||||
|
||||
func alertScopedQuery(db *gorm.DB, scope business.AlertRecordScope) *gorm.DB {
|
||||
q := applyOwnerScope(db.Table("sys_alert_record r"), scope.Owner, "r.business_id")
|
||||
for _, s := range alertChannelScopes(scope) {
|
||||
bindings := alertBindingQuery(db, s).Select("1").Where("b.source_db=p.source_db AND b.platform_busier_id=p.busier_id")
|
||||
// 两个范围独立取交集;只限制一级渠道,停用渠道的历史预警仍可见。
|
||||
channels := db.Table("tab_promote p").Select("1").Where("p.id=r.target_promote_id AND p.source_db=r.platform_code AND p.promote_level = ?", 1).Where("EXISTS (?)", bindings)
|
||||
q = q.Where("EXISTS (?)", channels)
|
||||
}
|
||||
return q
|
||||
}
|
||||
|
||||
func (r *alertRecordRepo) List(ctx context.Context, scope business.AlertRecordScope, filter business.AlertRecordFilter, options ...business.ListOption) (*business.AlertRecordPage, error) {
|
||||
db := r.data.DB().WithContext(ctx)
|
||||
page := &business.AlertRecordPage{Rows: []*business.AlertRecord{}, StatusCount: map[int]int64{}, Available: true}
|
||||
empty, available, err := prepareAlertScope(db, scope)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
page.Available = available
|
||||
if empty || !available {
|
||||
return page, nil
|
||||
}
|
||||
base := func() *gorm.DB {
|
||||
q := alertScopedQuery(db, scope)
|
||||
if len(filter.PlatformCodes) > 0 {
|
||||
q = q.Where("r.platform_code IN ?", filter.PlatformCodes)
|
||||
}
|
||||
if filter.TargetPromoteID != nil {
|
||||
q = q.Where("r.target_promote_id = ?", *filter.TargetPromoteID)
|
||||
}
|
||||
return q
|
||||
}
|
||||
q := base()
|
||||
for _, f := range []struct{ column, value string }{{"target_promote_name", filter.TargetPromoteName}, {"rule_name", filter.RuleName}, {"business_name", filter.BusinessName}} {
|
||||
if f.value != "" {
|
||||
q = q.Where("r."+f.column+" LIKE ?", "%"+f.value+"%")
|
||||
}
|
||||
}
|
||||
if filter.RuleType != "" {
|
||||
q = q.Where("r.rule_type = ?", filter.RuleType)
|
||||
}
|
||||
if filter.MonitorMetric != nil {
|
||||
q = q.Where("r.monitor_metric = ?", *filter.MonitorMetric)
|
||||
}
|
||||
if filter.Status != nil {
|
||||
q = q.Where("r.status = ?", *filter.Status)
|
||||
}
|
||||
if err := q.Count(&page.Total).Error; err != nil {
|
||||
return nil, business.ErrStorage
|
||||
}
|
||||
o := business.NewListOptions(options...)
|
||||
var pos []alertRecordPO
|
||||
if err := q.Select("r.*").Order("r.created_at DESC,r.id DESC").Offset(o.Offset).Limit(o.Limit).Scan(&pos).Error; err != nil {
|
||||
return nil, business.ErrStorage
|
||||
}
|
||||
for _, po := range pos {
|
||||
page.Rows = append(page.Rows, toBizAlertRecord(po))
|
||||
}
|
||||
// 顶部汇总忽略名称、类型、指标与状态筛选,只保留数据范围、平台和指定渠道。
|
||||
var counts []struct {
|
||||
Status int
|
||||
Count int64
|
||||
}
|
||||
if err := base().Select("r.status,COUNT(*) AS count").Group("r.status").Scan(&counts).Error; err != nil {
|
||||
return nil, business.ErrStorage
|
||||
}
|
||||
for _, c := range counts {
|
||||
page.StatusCount[c.Status] = c.Count
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func findScopedAlert(db *gorm.DB, scope business.AlertRecordScope, id uint64, lock bool) (*alertRecordPO, error) {
|
||||
empty, available, err := prepareAlertScope(db, scope)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if empty {
|
||||
return nil, business.ErrAlertRecordScope
|
||||
}
|
||||
if !available {
|
||||
return nil, business.ErrAlertChannelsUnavailable
|
||||
}
|
||||
// 锁定读取本身带权限条件,避免先读旧快照的权限再锁到已换归属的记录。
|
||||
q := alertScopedQuery(db, scope).Select("r.*")
|
||||
if lock {
|
||||
q = q.Clauses(clause.Locking{Strength: "UPDATE"})
|
||||
}
|
||||
var po alertRecordPO
|
||||
if err := q.Where("r.id = ?", id).Take(&po).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
var count int64
|
||||
if err := db.Model(&alertRecordPO{}).Where("id = ?", id).Count(&count).Error; err != nil {
|
||||
return nil, business.ErrStorage
|
||||
}
|
||||
if count > 0 {
|
||||
return nil, business.ErrAlertRecordScope
|
||||
}
|
||||
return nil, business.ErrAlertRecordNotFound
|
||||
}
|
||||
return nil, business.ErrStorage
|
||||
}
|
||||
return &po, nil
|
||||
}
|
||||
|
||||
func (r *alertRecordRepo) Detail(ctx context.Context, scope business.AlertRecordScope, id uint64) (*business.AlertRecordDetail, error) {
|
||||
var detail *business.AlertRecordDetail
|
||||
err := r.data.DB().WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
po, err := findScopedAlert(tx, scope, id, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
logs, err := alertLogs(tx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
detail = &business.AlertRecordDetail{Record: toBizAlertRecord(*po), Logs: logs}
|
||||
return nil
|
||||
})
|
||||
return detail, storageError(err)
|
||||
}
|
||||
|
||||
func (r *alertRecordRepo) WithRecord(ctx context.Context, scope business.AlertRecordScope, id uint64, fn func(*business.AlertRecord) ([]*business.AlertLog, error)) error {
|
||||
return storageError(r.data.DB().WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
po, err := findScopedAlert(tx, scope, id, true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
record := toBizAlertRecord(*po)
|
||||
logs, err := fn(record)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
now := time.Now()
|
||||
if record.Status != po.Status {
|
||||
result := tx.Model(&alertRecordPO{}).Where("id = ? AND status = ?", id, po.Status).Updates(map[string]any{"status": record.Status, "updated_at": now})
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
if result.RowsAffected != 1 {
|
||||
return business.ErrAlertRecordChanged
|
||||
}
|
||||
}
|
||||
for _, log := range logs {
|
||||
attachments := encodeAlertAttachments(log.AttachmentIDs)
|
||||
row := alertLogPO{AlertID: id, OperatorID: log.OperatorID, OperatorName: log.OperatorName, LogType: log.LogType, ActionDetail: log.ActionDetail, NoteContent: log.NoteContent, AttachmentIDs: attachments, CreatedAt: now}
|
||||
if err := tx.Create(&row).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}))
|
||||
}
|
||||
|
||||
func encodeAlertAttachments(values []string) *string {
|
||||
if len(values) == 0 {
|
||||
return nil
|
||||
}
|
||||
ids := make([]int64, 0, len(values))
|
||||
for _, value := range values {
|
||||
id, err := strconv.ParseInt(value, 10, 64)
|
||||
if err != nil {
|
||||
ids = nil
|
||||
break
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
var raw []byte
|
||||
if ids != nil {
|
||||
raw, _ = json.Marshal(ids)
|
||||
} else {
|
||||
raw, _ = json.Marshal(values)
|
||||
}
|
||||
value := string(raw)
|
||||
return &value
|
||||
}
|
||||
|
||||
func decodeAlertAttachments(raw *string) (values []string, ids []int64) {
|
||||
if raw == nil {
|
||||
return nil, nil
|
||||
}
|
||||
var entries []json.RawMessage
|
||||
if json.Unmarshal([]byte(*raw), &entries) != nil {
|
||||
return nil, nil
|
||||
}
|
||||
allNumeric := true
|
||||
for _, entry := range entries {
|
||||
var value string
|
||||
if json.Unmarshal(entry, &value) != nil {
|
||||
var n json.Number
|
||||
if json.Unmarshal(entry, &n) != nil || n == "" {
|
||||
return nil, nil
|
||||
}
|
||||
value = n.String()
|
||||
}
|
||||
values = append(values, value)
|
||||
id, err := strconv.ParseInt(value, 10, 64)
|
||||
if err != nil {
|
||||
allNumeric = false
|
||||
} else {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
}
|
||||
if !allNumeric {
|
||||
ids = nil
|
||||
}
|
||||
return values, ids
|
||||
}
|
||||
|
||||
func alertLogs(db *gorm.DB, alertID uint64) ([]*business.AlertLog, error) {
|
||||
var pos []alertLogPO
|
||||
if err := db.Where("alert_id = ?", alertID).Order("created_at DESC,id DESC").Find(&pos).Error; err != nil {
|
||||
return nil, business.ErrStorage
|
||||
}
|
||||
logs := make([]*business.AlertLog, 0, len(pos))
|
||||
idsByLog := map[uint64][]int64{}
|
||||
ids := map[int64]bool{}
|
||||
for _, po := range pos {
|
||||
values, numeric := decodeAlertAttachments(po.AttachmentIDs)
|
||||
log := &business.AlertLog{ID: po.ID, AlertID: po.AlertID, OperatorID: po.OperatorID, OperatorName: po.OperatorName, LogType: po.LogType, ActionDetail: po.ActionDetail, NoteContent: po.NoteContent, CreatedAt: po.CreatedAt, Attachments: []string{}}
|
||||
if len(numeric) > 0 {
|
||||
idsByLog[po.ID] = numeric
|
||||
for _, id := range numeric {
|
||||
ids[id] = true
|
||||
}
|
||||
} else if len(values) > 0 {
|
||||
log.Attachments = values
|
||||
}
|
||||
logs = append(logs, log)
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return logs, nil
|
||||
}
|
||||
keys := make([]int64, 0, len(ids))
|
||||
for id := range ids {
|
||||
keys = append(keys, id)
|
||||
}
|
||||
// 一次批量查询代替旧实现逐日志、逐附件查询。
|
||||
urls := map[int64]string{}
|
||||
for start := 0; start < len(keys); start += 500 {
|
||||
var files []struct {
|
||||
ID int64
|
||||
URL string
|
||||
}
|
||||
if err := db.Table("media_file_upload_and_downloads").Select("id,url").Where("id IN ? AND deleted_at IS NULL", keys[start:min(start+500, len(keys))]).Scan(&files).Error; err != nil {
|
||||
return nil, business.ErrStorage
|
||||
}
|
||||
for _, file := range files {
|
||||
urls[file.ID] = file.URL
|
||||
}
|
||||
}
|
||||
for _, log := range logs {
|
||||
seen := map[int64]bool{}
|
||||
for _, id := range idsByLog[log.ID] {
|
||||
if url, exists := urls[id]; exists && !seen[id] {
|
||||
log.Attachments = append(log.Attachments, url)
|
||||
seen[id] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
return logs, nil
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
package business
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"kra/internal/biz/business"
|
||||
)
|
||||
|
||||
func prepareAlertRecords(t *testing.T) (*gorm.DB, business.AlertRecordRepo) {
|
||||
t.Helper()
|
||||
db := prepareAccounts(t)
|
||||
for _, sql := range []string{
|
||||
"INSERT INTO sys_users(id,username,level,parent_id,id_path) VALUES(7,'owner',1,0,'0'),(8,'child',2,7,'0,7'),(9,'leaf',3,8,'0,7,8'),(10,'sibling',2,7,'0,7'),(99,'other',1,0,'0')",
|
||||
"INSERT INTO sys_user_bind_platform(user_id,source_db,platform_busier_id,status) VALUES(9,'lx',14,'0'),(10,'hw',14,'0'),(9,'hw',15,'3'),(99,'yq',14,'0')",
|
||||
"INSERT INTO tab_promote VALUES(100,'lx',14,1,0),(101,'lx',14,2,1),(100,'hw',14,1,1),(102,'hw',15,1,1),(100,'yq',14,1,1)",
|
||||
"CREATE TABLE media_file_upload_and_downloads(id INTEGER PRIMARY KEY,url TEXT,deleted_at DATETIME)",
|
||||
"INSERT INTO media_file_upload_and_downloads(id,url) VALUES(1,'/files/one.png'),(2,'/files/two.png')",
|
||||
} {
|
||||
if err := db.Exec(sql).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
stamp := time.Date(2026, 11, 3, 10, 0, 0, 0, time.UTC)
|
||||
pos := []alertRecordPO{
|
||||
{ID: 1, PlatformCode: "lx", TargetPromoteID: 100, BusinessID: 7, RuleName: "注册", RuleType: "register_anomaly", Status: 1, CreatedAt: stamp, UpdatedAt: stamp},
|
||||
{ID: 2, PlatformCode: "lx", TargetPromoteID: 100, BusinessID: 7, RuleName: "充值", RuleType: "recharge_anomaly", Status: 3, CreatedAt: stamp, UpdatedAt: stamp},
|
||||
{ID: 3, PlatformCode: "hw", TargetPromoteID: 100, BusinessID: 7, Status: 2, CreatedAt: stamp},
|
||||
{ID: 4, PlatformCode: "yq", TargetPromoteID: 100, BusinessID: 99, Status: 5, CreatedAt: stamp},
|
||||
{ID: 5, PlatformCode: "lx", TargetPromoteID: 100, BusinessID: 99, Status: 1, CreatedAt: stamp},
|
||||
{ID: 6, PlatformCode: "lx", TargetPromoteID: 101, BusinessID: 7, Status: 1, CreatedAt: stamp},
|
||||
{ID: 7, PlatformCode: "hw", TargetPromoteID: 102, BusinessID: 7, Status: 1, CreatedAt: stamp},
|
||||
}
|
||||
if err := db.Create(&pos).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return db, NewAlertRecordRepo(testData{db})
|
||||
}
|
||||
|
||||
func alertTestScope(id uint) business.AlertRecordScope {
|
||||
return business.AlertRecordScope{Owner: business.LevelOneScope{UserID: 7}, Viewer: business.UserScope{SelfID: id, IncludeSelf: true, OnlySelf: id == 9, DescendantPath: map[uint]string{7: "0,7", 8: "0,7,8", 9: "0,7,8,9"}[id]}}
|
||||
}
|
||||
|
||||
func TestAlertRecordsScopeAndSummaryUseDifferentFilters(t *testing.T) {
|
||||
_, repo := prepareAlertRecords(t)
|
||||
ctx := context.Background()
|
||||
for _, id := range []uint{8, 9} {
|
||||
page, err := repo.List(ctx, alertTestScope(id), business.AlertRecordFilter{})
|
||||
if err != nil || page.Total != 2 || len(page.Rows) != 2 || page.Rows[0].ID != 2 || page.Rows[1].ID != 1 {
|
||||
t.Fatalf("渠道状态、平台隔离、一级归属或排序错误: %+v %v", page, err)
|
||||
}
|
||||
}
|
||||
scope := alertTestScope(7)
|
||||
status := 1
|
||||
page, err := repo.List(ctx, scope, business.AlertRecordFilter{RuleName: "注册", Status: &status})
|
||||
if err != nil || page.Total != 1 || len(page.StatusCount) != 3 || page.StatusCount[3] != 1 || page.StatusCount[2] != 1 {
|
||||
t.Fatalf("汇总错误继承名称或状态筛选: %+v %v", page, err)
|
||||
}
|
||||
selected := alertTestScope(8).Viewer
|
||||
scope.Selected = &selected
|
||||
page, err = repo.List(ctx, scope, business.AlertRecordFilter{})
|
||||
if err != nil || page.Total != 2 {
|
||||
t.Fatalf("二级商务筛选误用了 record.business_id: %+v %v", page, err)
|
||||
}
|
||||
outside := business.UserScope{SelfID: 99, OnlySelf: true}
|
||||
scope.Selected = &outside
|
||||
page, err = repo.List(ctx, scope, business.AlertRecordFilter{})
|
||||
if err != nil || page.Total != 0 || len(page.StatusCount) != 0 {
|
||||
t.Fatalf("指定其他商务绕过查看范围: %+v %v", page, err)
|
||||
}
|
||||
root := business.AlertRecordScope{Owner: business.LevelOneScope{All: true}, Viewer: business.UserScope{All: true}, Selected: &selected}
|
||||
page, err = repo.List(ctx, root, business.AlertRecordFilter{})
|
||||
if err != nil || page.Total != 3 {
|
||||
t.Fatalf("超管指定商务须收窄渠道但不增加一级归属约束: %+v %v", page, err)
|
||||
}
|
||||
if _, err := repo.Detail(ctx, alertTestScope(8), 3); err != business.ErrAlertRecordScope {
|
||||
t.Fatal("同号不同平台详情被放行")
|
||||
}
|
||||
if _, err := repo.Detail(ctx, alertTestScope(8), 5); err != business.ErrAlertRecordScope {
|
||||
t.Fatal("异常归属预警跨一级商务泄漏")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAlertRecordsMissingChannelsFailClosed(t *testing.T) {
|
||||
db, repo := prepareAlertRecords(t)
|
||||
if err := db.Exec("DROP TABLE tab_promote").Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := context.Background()
|
||||
page, err := repo.List(ctx, alertTestScope(8), business.AlertRecordFilter{})
|
||||
if err != nil || page.Available || page.Total != 0 {
|
||||
t.Fatalf("缺渠道表未明确不可用: %+v %v", page, err)
|
||||
}
|
||||
if _, err := repo.Detail(ctx, alertTestScope(8), 1); err != business.ErrAlertChannelsUnavailable {
|
||||
t.Fatalf("详情应拒绝未知范围: %v", err)
|
||||
}
|
||||
root := business.AlertRecordScope{Owner: business.LevelOneScope{All: true}, Viewer: business.UserScope{All: true}}
|
||||
page, err = repo.List(ctx, root, business.AlertRecordFilter{})
|
||||
if err != nil || !page.Available || page.Total != 7 {
|
||||
t.Fatal("不限范围的超管查询不应依赖渠道表")
|
||||
}
|
||||
root.Selected = &business.UserScope{SelfID: 500, OnlySelf: true}
|
||||
page, err = repo.List(ctx, root, business.AlertRecordFilter{})
|
||||
if err != nil || !page.Available || page.Total != 0 {
|
||||
t.Fatal("无绑定应是确定空集")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAlertRecordTransactionRollsBackWhenLogFails(t *testing.T) {
|
||||
db, repo := prepareAlertRecords(t)
|
||||
if err := db.Exec("CREATE TRIGGER reject_note BEFORE INSERT ON sys_alert_operation_log WHEN NEW.log_type = 2 BEGIN SELECT RAISE(ABORT, 'test failure'); END").Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
err := repo.WithRecord(context.Background(), alertTestScope(8), 1, func(r *business.AlertRecord) ([]*business.AlertLog, error) {
|
||||
r.Status = 2
|
||||
return []*business.AlertLog{{LogType: 1, ActionDetail: "start"}, {LogType: 2, NoteContent: "备注"}}, nil
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("日志失败应回滚")
|
||||
}
|
||||
var record alertRecordPO
|
||||
if err := db.First(&record, 1).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var count int64
|
||||
db.Model(&alertLogPO{}).Count(&count)
|
||||
if record.Status != 1 || count != 0 {
|
||||
t.Fatal("留下半次状态流转或日志")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAlertRecordRepeatedConcurrentActionCreatesOneLog(t *testing.T) {
|
||||
db, repo := prepareAlertRecords(t)
|
||||
pool, _ := db.DB()
|
||||
// SQLite 用单连接串行事务;生产 MySQL 使用同一行锁回调,状态必须在锁内校验。
|
||||
pool.SetMaxOpenConns(1)
|
||||
var success atomic.Int32
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < 12; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
err := repo.WithRecord(context.Background(), alertTestScope(8), 1, func(r *business.AlertRecord) ([]*business.AlertLog, error) {
|
||||
if r.Status != 1 {
|
||||
return nil, business.ErrAlertRecordChanged
|
||||
}
|
||||
r.Status = 2
|
||||
return []*business.AlertLog{{LogType: 1, ActionDetail: "start"}}, nil
|
||||
})
|
||||
if err == nil {
|
||||
success.Add(1)
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
var count int64
|
||||
db.Model(&alertLogPO{}).Count(&count)
|
||||
if success.Load() != 1 || count != 1 {
|
||||
t.Fatalf("重复请求写入多次: successes=%d logs=%d", success.Load(), count)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAlertRecordLogAttachmentsAndStableOrder(t *testing.T) {
|
||||
db, repo := prepareAlertRecords(t)
|
||||
stamp := time.Now()
|
||||
for i, raw := range []string{`[2,"1",999,2]`, `["/legacy/a.png","https://files.invalid/b.png"]`, `{"bad":true}`} {
|
||||
value := raw
|
||||
if err := db.Create(&alertLogPO{ID: uint64(i + 1), AlertID: 1, LogType: 2, AttachmentIDs: &value, CreatedAt: stamp}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
detail, err := repo.Detail(context.Background(), alertTestScope(8), 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(detail.Logs) != 3 || detail.Logs[0].ID != 3 || len(detail.Logs[0].Attachments) != 0 || len(detail.Logs[1].Attachments) != 2 || len(detail.Logs[2].Attachments) != 2 || detail.Logs[2].Attachments[0] != "/files/two.png" {
|
||||
t.Fatalf("附件或顺序错误: %+v", detail.Logs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAlertAttachmentMigrationUsesLegacyBackupAndIsIdempotent(t *testing.T) {
|
||||
db, _ := prepareAlertRecords(t)
|
||||
for _, sql := range []string{
|
||||
"CREATE TABLE bak_sw2kra_20261103_sys_alert_operation_log(id INTEGER,attachment_ids TEXT)",
|
||||
"INSERT INTO sw_kra_id_map(entity,old_id,new_id) VALUES('file','9007199254740993',2),('file','1',1)",
|
||||
`INSERT INTO sys_alert_operation_log(id,alert_id,attachment_ids) VALUES(10,1,'[9007199254740993,999]'),(11,1,'["/legacy.png"]'),(12,1,'[1]'),(13,1,'[2]')`,
|
||||
`INSERT INTO bak_sw2kra_20261103_sys_alert_operation_log VALUES(10,'[9007199254740993,999]'),(11,'["/legacy.png"]'),(13,'[9007199254740993]')`,
|
||||
} {
|
||||
if err := db.Exec(sql).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for i := 0; i < 2; i++ {
|
||||
if err := migrateAlertAttachments(db); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
var rows []alertLogPO
|
||||
db.Order("id").Find(&rows)
|
||||
if len(rows) != 4 {
|
||||
t.Fatal("日志丢失")
|
||||
}
|
||||
var ids []int64
|
||||
if json.Unmarshal([]byte(*rows[0].AttachmentIDs), &ids) != nil || len(ids) != 1 || ids[0] != 2 {
|
||||
t.Fatal("大 ID 映射或失效引用处理错误")
|
||||
}
|
||||
if *rows[1].AttachmentIDs != `["/legacy.png"]` || *rows[2].AttachmentIDs != `[1]` || *rows[3].AttachmentIDs != `[2]` {
|
||||
t.Fatal("改动了 URL、新日志或已经转换的附件")
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import (
|
||||
)
|
||||
|
||||
func Migrations() []migration.Step {
|
||||
return []migration.Step{{ID: "202611030006_business_alert_schema", Migrate: migrateAlertSchema}, {ID: "202611030005_business_password_reset", Migrate: func(db *gorm.DB) error {
|
||||
return []migration.Step{{ID: "202611030007_business_alert_attachments", Migrate: migrateAlertAttachments}, {ID: "202611030006_business_alert_schema", Migrate: migrateAlertSchema}, {ID: "202611030005_business_password_reset", Migrate: func(db *gorm.DB) error {
|
||||
return migration.CreateMissingTables(db, &resetCodePO{}, &resetTokenPO{})
|
||||
}}, {ID: "202611030004_business_binding_locks", Migrate: func(db *gorm.DB) error {
|
||||
return migration.CreateMissingTables(db, &bindingLockPO{})
|
||||
|
||||
@@ -35,6 +35,7 @@ var ProviderSet = wire.NewSet(
|
||||
databusiness.NewPasswordResetRepo,
|
||||
databusiness.NewBusinessPromoteRepo,
|
||||
databusiness.NewAlertRuleRepo,
|
||||
databusiness.NewAlertRecordRepo,
|
||||
NewIntegrationRuntime,
|
||||
wire.Bind(new(datasystem.Provider), new(*Data)),
|
||||
wire.Bind(new(datasystem.DatabaseProvider), new(*Data)),
|
||||
|
||||
@@ -34,8 +34,8 @@ func TestMigrateAllRunsModuleSchemasWithoutBootstrapSeed(t *testing.T) {
|
||||
if err = db.Table(migration.TableName).Count(&versions).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if versions != 20 {
|
||||
t.Fatalf("migration versions = %d, want 20", versions)
|
||||
if versions != 21 {
|
||||
t.Fatalf("migration versions = %d, want 21", versions)
|
||||
}
|
||||
var communicationRows []dataintegration.ConfigPO
|
||||
if err = db.Where("kind IN ?", []string{"mq", "websocket"}).Order("kind, provider").Find(&communicationRows).Error; err != nil {
|
||||
|
||||
Reference in New Issue
Block a user