alarm_rule_controller.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. package controllers
  2. import (
  3. "ems-backend/models"
  4. "github.com/gin-gonic/gin"
  5. "github.com/google/uuid"
  6. "gorm.io/gorm"
  7. "net/http"
  8. "strconv"
  9. )
  10. // AlarmRuleRequest 用于接收前端参数,包含绑定信息
  11. type AlarmRuleRequest struct {
  12. models.AlarmRule
  13. BindingIds []string `json:"binding_ids"` // 绑定的 ID 列表 (DeviceID 或 LocationID)
  14. BindingType string `json:"binding_type"` // DEVICE or SPACE
  15. }
  16. // BatchDeleteRequest 批量删除请求
  17. type BatchDeleteRequest struct {
  18. Ids []string `json:"ids"`
  19. }
  20. // CreateAlarmRule 创建告警规则
  21. func CreateAlarmRule(c *gin.Context) {
  22. var req AlarmRuleRequest
  23. if err := c.ShouldBindJSON(&req); err != nil {
  24. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  25. return
  26. }
  27. // 1. Check for duplicate name
  28. var count int64
  29. models.DB.Model(&models.AlarmRule{}).Where("name = ?", req.Name).Count(&count)
  30. if count > 0 {
  31. c.JSON(http.StatusBadRequest, gin.H{"error": "Rule name already exists"})
  32. return
  33. }
  34. // 2. Create Rule
  35. // Ensure ID is generated
  36. if req.AlarmRule.ID == uuid.Nil {
  37. req.AlarmRule.ID = uuid.New()
  38. }
  39. err := models.DB.Transaction(func(tx *gorm.DB) error {
  40. if err := tx.Create(&req.AlarmRule).Error; err != nil {
  41. return err
  42. }
  43. // 2. Create Bindings
  44. if len(req.BindingIds) > 0 {
  45. var bindings []models.AlarmRuleBinding
  46. for _, bid := range req.BindingIds {
  47. targetUUID, err := uuid.Parse(bid)
  48. if err != nil {
  49. continue
  50. }
  51. bindings = append(bindings, models.AlarmRuleBinding{
  52. RuleID: req.AlarmRule.ID,
  53. TargetID: targetUUID,
  54. TargetType: req.BindingType,
  55. })
  56. }
  57. if len(bindings) > 0 {
  58. if err := tx.Create(&bindings).Error; err != nil {
  59. return err
  60. }
  61. }
  62. }
  63. return nil
  64. })
  65. if err != nil {
  66. c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create alarm rule: " + err.Error()})
  67. return
  68. }
  69. c.JSON(http.StatusOK, req.AlarmRule)
  70. }
  71. // GetAlarmRules 获取告警规则列表
  72. func GetAlarmRules(c *gin.Context) {
  73. var rules []models.AlarmRule
  74. var total int64
  75. // Parse Pagination
  76. page := 1
  77. if c.Query("page") != "" {
  78. if p, err := strconv.ParseInt(c.Query("page"), 10, 64); err == nil && p > 0 {
  79. page = int(p)
  80. }
  81. }
  82. pageSize := 10
  83. if c.Query("page_size") != "" {
  84. if ps, err := strconv.ParseInt(c.Query("page_size"), 10, 64); err == nil && ps > 0 {
  85. pageSize = int(ps)
  86. }
  87. }
  88. offset := (page - 1) * pageSize
  89. // Query
  90. query := models.DB.Model(&models.AlarmRule{})
  91. // Search by name
  92. if name := c.Query("name"); name != "" {
  93. query = query.Where("name LIKE ?", "%"+name+"%")
  94. }
  95. // Search by enabled
  96. if enabled := c.Query("enabled"); enabled != "" {
  97. if b, err := strconv.ParseBool(enabled); err == nil {
  98. query = query.Where("enabled = ?", b)
  99. }
  100. }
  101. // Count total
  102. query.Count(&total)
  103. // Fetch data with pagination
  104. if err := query.Offset(offset).Limit(pageSize).Preload("Bindings").Find(&rules).Error; err != nil {
  105. c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch alarm rules"})
  106. return
  107. }
  108. if rules == nil {
  109. rules = []models.AlarmRule{}
  110. }
  111. c.JSON(http.StatusOK, gin.H{
  112. "data": rules,
  113. "total": total,
  114. })
  115. }
  116. // UpdateAlarmRule 更新告警规则
  117. func UpdateAlarmRule(c *gin.Context) {
  118. id := c.Param("id")
  119. var req AlarmRuleRequest
  120. // Check exist
  121. var existingRule models.AlarmRule
  122. if err := models.DB.First(&existingRule, "id = ?", id).Error; err != nil {
  123. c.JSON(http.StatusNotFound, gin.H{"error": "Alarm rule not found"})
  124. return
  125. }
  126. if err := c.ShouldBindJSON(&req); err != nil {
  127. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  128. return
  129. }
  130. // Don't modify bindings if BindingIds is empty/nil?
  131. // Issue: "Update Enable" only sends {enabled: false}, so BindingIds is empty/nil.
  132. // But "Edit Config" sends empty array if clearing selection.
  133. // We need to distinguish between "Update Fields Only" vs "Update Config with Bindings".
  134. // Simple fix: If BindingIds is nil (not present in JSON), don't update bindings?
  135. // But Go structs default to nil/empty slice.
  136. // Better: Check if we are only patching. For now, let's assume if it's a PATCH-like behavior (e.g. toggle enable), we should preserve bindings.
  137. // But here we are using PUT.
  138. // Let's reload existing bindings if req.BindingIds is empty AND we want to preserve them?
  139. // Actually, the toggle in frontend calls updateAlarmRule(id, {enabled: val}). It DOES NOT send binding_ids.
  140. // So req.BindingIds will be empty slice. This causes bindings to be deleted.
  141. // FIX: If we detect this is a partial update (e.g. only enabled is set, or binding_ids is missing/nil), handle gracefully.
  142. // However, standard Update usually implies full replace or we need logic.
  143. // Let's recover existing bindings if the request didn't explicitly include them?
  144. // Limitation: Go struct doesn't easily show "missing" vs "empty".
  145. // We can check binding_type. If binding_type is empty, assume we are not updating bindings.
  146. // 1. Check for duplicate name (exclude self)
  147. if req.Name != "" { // Only check if name is being updated
  148. var count int64
  149. models.DB.Model(&models.AlarmRule{}).Where("name = ? AND id != ?", req.Name, existingRule.ID).Count(&count)
  150. if count > 0 {
  151. c.JSON(http.StatusBadRequest, gin.H{"error": "Rule name already exists"})
  152. return
  153. }
  154. }
  155. err := models.DB.Transaction(func(tx *gorm.DB) error {
  156. // 1. Update Rule Fields
  157. updateData := req.AlarmRule
  158. updateData.ID = existingRule.ID
  159. updateData.CreatedAt = existingRule.CreatedAt // preserve
  160. if err := tx.Save(&updateData).Error; err != nil {
  161. return err
  162. }
  163. // 2. Update Bindings ONLY if BindingType is provided (indicating a config update)
  164. // Or if we specifically want to support clearing bindings, we need a flag.
  165. // For the toggle enable case, BindingType will be empty string.
  166. if req.BindingType != "" {
  167. // Delete old bindings
  168. if err := tx.Delete(&models.AlarmRuleBinding{}, "rule_id = ?", existingRule.ID).Error; err != nil {
  169. return err
  170. }
  171. // Create new bindings
  172. if len(req.BindingIds) > 0 {
  173. var bindings []models.AlarmRuleBinding
  174. for _, bid := range req.BindingIds {
  175. targetUUID, err := uuid.Parse(bid)
  176. if err != nil {
  177. continue
  178. }
  179. bindings = append(bindings, models.AlarmRuleBinding{
  180. RuleID: existingRule.ID,
  181. TargetID: targetUUID,
  182. TargetType: req.BindingType,
  183. })
  184. }
  185. if len(bindings) > 0 {
  186. if err := tx.Create(&bindings).Error; err != nil {
  187. return err
  188. }
  189. }
  190. }
  191. }
  192. return nil
  193. })
  194. if err != nil {
  195. c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update alarm rule: " + err.Error()})
  196. return
  197. }
  198. c.JSON(http.StatusOK, req.AlarmRule)
  199. }
  200. // DeleteAlarmRule 删除告警规则
  201. func DeleteAlarmRule(c *gin.Context) {
  202. id := c.Param("id")
  203. err := models.DB.Transaction(func(tx *gorm.DB) error {
  204. // 1. Delete Bindings
  205. if err := tx.Delete(&models.AlarmRuleBinding{}, "rule_id = ?", id).Error; err != nil {
  206. return err
  207. }
  208. // 2. Delete Rule
  209. if err := tx.Delete(&models.AlarmRule{}, "id = ?", id).Error; err != nil {
  210. return err
  211. }
  212. return nil
  213. })
  214. if err != nil {
  215. c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to delete alarm rule: " + err.Error()})
  216. return
  217. }
  218. c.JSON(http.StatusOK, gin.H{"message": "Alarm rule deleted successfully"})
  219. }
  220. // BatchDeleteAlarmRules 批量删除告警规则
  221. func BatchDeleteAlarmRules(c *gin.Context) {
  222. var req BatchDeleteRequest
  223. if err := c.ShouldBindJSON(&req); err != nil {
  224. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  225. return
  226. }
  227. if len(req.Ids) == 0 {
  228. c.JSON(http.StatusBadRequest, gin.H{"error": "No IDs provided"})
  229. return
  230. }
  231. err := models.DB.Transaction(func(tx *gorm.DB) error {
  232. // 1. Delete Bindings
  233. if err := tx.Delete(&models.AlarmRuleBinding{}, "rule_id IN ?", req.Ids).Error; err != nil {
  234. return err
  235. }
  236. // 2. Delete Rules
  237. if err := tx.Delete(&models.AlarmRule{}, "id IN ?", req.Ids).Error; err != nil {
  238. return err
  239. }
  240. return nil
  241. })
  242. if err != nil {
  243. c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to batch delete alarm rules: " + err.Error()})
  244. return
  245. }
  246. c.JSON(http.StatusOK, gin.H{"message": "Alarm rules deleted successfully"})
  247. }