package service import ( "fmt" "strings" "github.com/QuantumNous/new-api/model" "github.com/gin-gonic/gin" ) // RecordOperation 便捷方法:记录操作日志。 func RecordOperation(c *gin.Context, action string, targetType string, targetId int, targetName string, content string, requestBody string) { userId := c.GetInt("id") if userId == 0 { return } sanitizedBody := model.SanitizeRequestBody(requestBody) model.RecordOperationLog(c, userId, action, targetType, targetId, targetName, content, sanitizedBody) // 设置标记,防止中间件重复记录同一操作 c.Set("_operation_logged", true) } // RecordCreateOperation 记录创建操作。 func RecordCreateOperation(c *gin.Context, targetType string, targetId int, targetName string, content string, requestBody string) { RecordOperation(c, model.OperationActionCreate, targetType, targetId, targetName, content, requestBody) } // RecordUpdateOperation 记录更新操作。 func RecordUpdateOperation(c *gin.Context, targetType string, targetId int, targetName string, content string, requestBody string) { RecordOperation(c, model.OperationActionUpdate, targetType, targetId, targetName, content, requestBody) } // RecordDeleteOperation 记录删除操作。 func RecordDeleteOperation(c *gin.Context, targetType string, targetId int, targetName string, content string, requestBody string) { RecordOperation(c, model.OperationActionDelete, targetType, targetId, targetName, content, requestBody) } // FieldChange 表示单个字段的变更信息。 type FieldChange struct { Field string // 字段中文名 OldValue string // 变更前的值 NewValue string // 变更后的值 } // FormatUpdateDiff 将字段变更列表格式化为操作描述。 // 仅记录实际发生变化的字段,生成形如 "邮箱: old@a.com → new@b.com; 额度: 100 → 500" 的描述。 func FormatUpdateDiff(changes []FieldChange) string { if len(changes) == 0 { return "" } var parts []string for _, c := range changes { if c.OldValue == c.NewValue { continue } if c.OldValue == "" { parts = append(parts, fmt.Sprintf("%s: 设置为「%s」", c.Field, c.NewValue)) } else if c.NewValue == "" { parts = append(parts, fmt.Sprintf("%s: 清空(原「%s」)", c.Field, c.OldValue)) } else { parts = append(parts, fmt.Sprintf("%s: 「%s」→「%s」", c.Field, c.OldValue, c.NewValue)) } } if len(parts) == 0 { return "" } return strings.Join(parts, "; ") } // RecordUpdateWithDiff 记录更新操作并附带字段级变更详情。 // baseContent 为基础描述(如 "更新用户: xxx"),changes 为变更字段列表。 func RecordUpdateWithDiff(c *gin.Context, targetType string, targetId int, targetName string, baseContent string, changes []FieldChange, requestBody string) { diffStr := FormatUpdateDiff(changes) if diffStr != "" { baseContent = baseContent + " | " + diffStr } RecordUpdateOperation(c, targetType, targetId, targetName, baseContent, requestBody) }