package handlers import ( "database/sql" "net/http" "strings" "time" "github.com/gin-gonic/gin" "query-database/api/internal/auth" ) type switchModuleReq struct { ModuleKey string `json:"moduleKey"` ActivateRecommendedMock *bool `json:"activateRecommendedMock"` } func (h *Handlers) SwitchModule(c *gin.Context) { userID := auth.UserID(c) var req switchModuleReq if err := c.ShouldBindJSON(&req); err != nil { c.JSON(http.StatusBadRequest, gin.H{"message": "参数错误"}) return } newKey := strings.TrimSpace(req.ModuleKey) if newKey != "shop" && newKey != "hr" { c.JSON(http.StatusBadRequest, gin.H{"message": "模块不合法"}) return } var prevKey string if err := h.sqlite.QueryRow(`SELECT module_key FROM users WHERE id = ?`, userID).Scan(&prevKey); err != nil { if err == sql.ErrNoRows { c.JSON(http.StatusUnauthorized, gin.H{"message": "未登录"}) return } c.JSON(http.StatusInternalServerError, gin.H{"message": "服务异常"}) return } before, _ := h.getActiveDatabase(userID) if _, err := h.sqlite.Exec(`UPDATE users SET module_key = ? WHERE id = ?`, newKey, userID); err != nil { c.JSON(http.StatusInternalServerError, gin.H{"message": "服务异常"}) return } shouldActivate := false if req.ActivateRecommendedMock != nil { shouldActivate = *req.ActivateRecommendedMock } else { if before == nil || before.Source == "mock" { shouldActivate = true } } didActivate := false if shouldActivate { now := time.Now().UTC().Format(time.RFC3339) if err := h.activateMockForUser(userID, newKey, now); err != nil { _, _ = h.sqlite.Exec(`UPDATE users SET module_key = ? WHERE id = ?`, prevKey, userID) c.JSON(http.StatusInternalServerError, gin.H{"message": "设置数据库失败"}) return } didActivate = true } after, _ := h.getActiveDatabase(userID) md, _ := moduleDatabaseByKey(newKey) var beforeDB any = nil if before != nil { beforeDB = gin.H{"id": before.ID, "name": before.Name, "source": before.Source, "schemaName": before.SchemaName} } var afterDB any = nil if after != nil { afterDB = gin.H{"id": after.ID, "name": after.Name, "source": after.Source, "schemaName": after.SchemaName} } out := gin.H{ "previousModuleKey": prevKey, "moduleKey": newKey, "didActivateRecommendedMock": didActivate, "activeDatabaseBefore": beforeDB, "activeDatabaseAfter": afterDB, } if md != nil { out["recommendedMock"] = gin.H{"key": md.Key, "name": md.Name, "schemaName": md.SchemaName} } c.JSON(http.StatusOK, out) }