setting.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package handler
  2. import (
  3. "encoding/json"
  4. "github.com/gin-gonic/gin"
  5. "spider/internal/model"
  6. "spider/internal/store"
  7. )
  8. // SettingHandler handles system settings.
  9. type SettingHandler struct {
  10. store *store.Store
  11. }
  12. // GetGrading handles GET /settings/grading
  13. func (h *SettingHandler) GetGrading(c *gin.Context) {
  14. cfg, err := h.store.GetGradingConfig()
  15. if err != nil {
  16. Fail(c, 500, err.Error())
  17. return
  18. }
  19. OK(c, cfg)
  20. }
  21. // UpdateGrading handles PUT /settings/grading
  22. func (h *SettingHandler) UpdateGrading(c *gin.Context) {
  23. var cfg model.GradingConfig
  24. if err := c.ShouldBindJSON(&cfg); err != nil {
  25. Fail(c, 400, err.Error())
  26. return
  27. }
  28. // Validate: must have at least one level
  29. if len(cfg.Levels) == 0 {
  30. Fail(c, 400, "至少需要一个等级")
  31. return
  32. }
  33. if err := h.store.SetSetting("grading", cfg); err != nil {
  34. Fail(c, 500, err.Error())
  35. return
  36. }
  37. LogAudit(h.store, c, "update", "setting", "grading", nil)
  38. OK(c, cfg)
  39. }
  40. // ResetGrading handles POST /settings/grading/reset
  41. func (h *SettingHandler) ResetGrading(c *gin.Context) {
  42. cfg := model.DefaultGradingConfig()
  43. if err := h.store.SetSetting("grading", cfg); err != nil {
  44. Fail(c, 500, err.Error())
  45. return
  46. }
  47. LogAudit(h.store, c, "update", "setting", "grading", gin.H{"action": "reset"})
  48. OK(c, cfg)
  49. }
  50. // GetLevelMap handles GET /settings/level-map — returns key→label mapping for frontend display.
  51. func (h *SettingHandler) GetLevelMap(c *gin.Context) {
  52. cfg, err := h.store.GetGradingConfig()
  53. if err != nil {
  54. Fail(c, 500, err.Error())
  55. return
  56. }
  57. m := make(map[string]map[string]string)
  58. for _, level := range cfg.Levels {
  59. m[level.Key] = map[string]string{
  60. "label": level.Label,
  61. "color": level.Color,
  62. "description": level.Description,
  63. }
  64. }
  65. OK(c, m)
  66. }
  67. // GetAllSettings handles GET /settings — returns all settings keys.
  68. func (h *SettingHandler) GetAllSettings(c *gin.Context) {
  69. var settings []model.Setting
  70. h.store.DB.Find(&settings)
  71. result := make(map[string]json.RawMessage)
  72. for _, s := range settings {
  73. result[s.Key] = json.RawMessage(s.Value)
  74. }
  75. OK(c, result)
  76. }