feat(integrations): align slack parity

This commit is contained in:
2026-06-06 16:41:49 +08:00
parent c6dd78d60c
commit 7b28f9227d
8 changed files with 482 additions and 65 deletions
@@ -1,10 +1,12 @@
package v1
import (
"errors"
"net/http"
"github.com/gin-gonic/gin"
"github.com/gochat/gochat/internal/model"
"github.com/gochat/gochat/internal/service"
"github.com/gochat/gochat/pkg/response"
)
@@ -30,7 +32,7 @@ func (h *SlackIntegrationHandler) Create(c *gin.Context) {
}
var req service.CreateSlackRequest
if err := c.ShouldBindJSON(&req); err != nil {
if err := c.ShouldBind(&req); err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, err.Error())
return
}
@@ -40,7 +42,7 @@ func (h *SlackIntegrationHandler) Create(c *gin.Context) {
handleServiceError(c, svcErr)
return
}
response.OK(c, hook)
c.JSON(http.StatusOK, h.slackAppPayload(c, accountID, []model.IntegrationHook{*hook}))
}
// Update updates a Slack integration for an account.
@@ -53,17 +55,21 @@ func (h *SlackIntegrationHandler) Update(c *gin.Context) {
}
var req service.UpdateSlackRequest
if err := c.ShouldBindJSON(&req); err != nil {
if err := c.ShouldBind(&req); err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, err.Error())
return
}
hook, svcErr := h.svc.Update(c.Request.Context(), accountID, req)
if svcErr != nil {
if errors.Is(svcErr, service.ErrSlackInvalidChannel) {
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Invalid slack channel. Please try again"})
return
}
handleServiceError(c, svcErr)
return
}
response.OK(c, hook)
c.JSON(http.StatusOK, h.slackAppPayload(c, accountID, []model.IntegrationHook{*hook}))
}
// Delete removes a Slack integration for an account.
@@ -79,7 +85,7 @@ func (h *SlackIntegrationHandler) Delete(c *gin.Context) {
handleServiceError(c, svcErr)
return
}
response.OK(c, gin.H{"message": "Slack integration deleted"})
c.Status(http.StatusOK)
}
// ListAllChannels lists available Slack channels.
@@ -96,16 +102,45 @@ func (h *SlackIntegrationHandler) ListAllChannels(c *gin.Context) {
handleServiceError(c, svcErr)
return
}
response.OK(c, channels)
c.JSON(http.StatusOK, channels)
}
// RegisterSlackIntegrationRoutes registers Slack integration routes.
func RegisterSlackIntegrationRoutes(g *gin.RouterGroup, h *SlackIntegrationHandler) {
g.POST("/slack", h.Create)
g.PATCH("/slack", h.Update)
g.PUT("/slack", h.Update)
g.DELETE("/slack", h.Delete)
slack := g.Group("/slack")
{
slack.POST("/", h.Create)
slack.PATCH("/", h.Update)
slack.PUT("/", h.Update)
slack.DELETE("/", h.Delete)
slack.GET("/list_all_channels", h.ListAllChannels)
}
}
func (h *SlackIntegrationHandler) slackAppPayload(c *gin.Context, accountID uint, fallback []model.IntegrationHook) gin.H {
hooks, err := h.svc.ListHooks(c.Request.Context(), accountID)
if err != nil || len(hooks) == 0 {
hooks = fallback
}
serializedHooks := make([]gin.H, 0, len(hooks))
for _, hook := range hooks {
serializedHooks = append(serializedHooks, serializeIntegrationHook(hook))
}
return gin.H{
"id": "slack",
"name": "Slack",
"description": "Connect Slack channels for real-time notifications",
"short_description": "Connect Slack channels for real-time notifications",
"enabled": len(serializedHooks) > 0,
"hooks": serializedHooks,
"hook_type": integrationAppHookType("slack"),
"allow_multiple_hooks": integrationAppAllowsMultipleHooks("slack"),
"settings_form_schema": integrationAppSettingsFormSchema("slack"),
"visible_properties": integrationAppVisibleProperties("slack"),
}
}
@@ -9,6 +9,14 @@ import (
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"github.com/gochat/gochat/internal/model"
"github.com/gochat/gochat/internal/repository"
"github.com/gochat/gochat/internal/service"
)
func setupSlackIntegrationRouter() *gin.Engine {
@@ -24,6 +32,31 @@ func setupSlackIntegrationRouter() *gin.Engine {
return r
}
func setupSlackIntegrationRouterWithService(svc *service.SlackIntegrationService) *gin.Engine {
gin.SetMode(gin.TestMode)
r := gin.New()
r.RedirectTrailingSlash = false
handler := NewSlackIntegrationHandler(svc)
integrations := r.Group("/api/v1/accounts/:account_id/integrations")
RegisterSlackIntegrationRoutes(integrations, handler)
return r
}
func setupSlackIntegrationHandlerDB(t *testing.T) (*gorm.DB, uint) {
t.Helper()
db, err := gorm.Open(sqlite.Open("file::memory:"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
require.NoError(t, err)
require.NoError(t, db.AutoMigrate(&model.Account{}, &model.IntegrationHook{}))
account := &model.Account{Name: "Slack Handler Account"}
require.NoError(t, db.Create(account).Error)
t.Cleanup(func() {
sqlDB, _ := db.DB()
_ = sqlDB.Close()
})
return db, account.ID
}
// ========================================
// SlackIntegration — param validation tests
// ========================================
@@ -117,3 +150,51 @@ func TestSlackIntegration_ListAllChannels_BadAccountID(t *testing.T) {
errBody := resp["error"].(map[string]interface{})
assert.Contains(t, errBody["message"], "invalid account_id")
}
func TestSlackIntegration_Create_NoTrailingSlash_ReturnsRawAppPayload(t *testing.T) {
db, accountID := setupSlackIntegrationHandlerDB(t)
svc := service.NewSlackIntegrationService(repository.NewIntegrationHookRepo(db))
r := setupSlackIntegrationRouterWithService(svc)
w := httptest.NewRecorder()
body := bytes.NewReader([]byte(`{"slack_token":"xoxb-handler-token"}`))
req, _ := http.NewRequest("POST", "/api/v1/accounts/1/integrations/slack", body)
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
var resp map[string]interface{}
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &resp))
assert.Equal(t, "slack", resp["id"])
assert.NotContains(t, resp, "success")
hooks := resp["hooks"].([]interface{})
require.Len(t, hooks, 1)
hook := hooks[0].(map[string]interface{})
assert.Equal(t, "slack", hook["app_id"])
assert.Equal(t, accountID, uint(hook["account_id"].(float64)))
assert.Equal(t, false, hook["status"])
}
func TestSlackIntegration_Delete_NoTrailingSlash_ReturnsEmptyOK(t *testing.T) {
db, accountID := setupSlackIntegrationHandlerDB(t)
require.NoError(t, db.Create(&model.IntegrationHook{AccountID: accountID, AppID: "slack", HookType: model.HookTypeSlack}).Error)
svc := service.NewSlackIntegrationService(repository.NewIntegrationHookRepo(db))
r := setupSlackIntegrationRouterWithService(svc)
w := httptest.NewRecorder()
req, _ := http.NewRequest("DELETE", "/api/v1/accounts/1/integrations/slack", nil)
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
assert.Empty(t, w.Body.String())
}
func TestSlackIntegration_Update_PutNoTrailingSlash_BadAccountID(t *testing.T) {
r := setupSlackIntegrationRouter()
w := httptest.NewRecorder()
req, _ := http.NewRequest("PUT", "/api/v1/accounts/abc/integrations/slack", nil)
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusBadRequest, w.Code)
}