feat(captain): align preferences payloads
This commit is contained in:
@@ -2,7 +2,6 @@ package v1
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gochat/gochat/internal/service"
|
||||
@@ -23,8 +22,8 @@ func NewCaptainPreferenceHandler(svc *service.CaptainPreferenceService) *Captain
|
||||
// Create creates a new captain preference for an account.
|
||||
// POST /api/v1/accounts/:id/captain/preferences
|
||||
func (h *CaptainPreferenceHandler) Create(c *gin.Context) {
|
||||
accountID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
accountID := parseAccountIDParam(c)
|
||||
if accountID == 0 {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
|
||||
return
|
||||
}
|
||||
@@ -35,7 +34,7 @@ func (h *CaptainPreferenceHandler) Create(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
pref, err := h.svc.Create(c.Request.Context(), uint(accountID), &req)
|
||||
pref, err := h.svc.Create(c.Request.Context(), accountID, &req)
|
||||
if err != nil {
|
||||
applogger.L().Errorf("Create captain preference: %v", err)
|
||||
response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "failed to create preference")
|
||||
@@ -48,57 +47,61 @@ func (h *CaptainPreferenceHandler) Create(c *gin.Context) {
|
||||
// Get retrieves the captain preference for an account.
|
||||
// GET /api/v1/accounts/:id/captain/preferences
|
||||
func (h *CaptainPreferenceHandler) Get(c *gin.Context) {
|
||||
accountID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
accountID := parseAccountIDParam(c)
|
||||
if accountID == 0 {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
|
||||
return
|
||||
}
|
||||
|
||||
pref, err := h.svc.Get(c.Request.Context(), uint(accountID))
|
||||
pref, err := h.svc.GetConfig(c.Request.Context(), accountID)
|
||||
if err != nil {
|
||||
applogger.L().Errorf("Get captain preference: %v", err)
|
||||
response.AbortWithStatusError(c, http.StatusNotFound, response.ErrNotFound, "preference not found")
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, pref)
|
||||
c.JSON(http.StatusOK, pref)
|
||||
}
|
||||
|
||||
// Update updates the captain preference for an account.
|
||||
// PUT /api/v1/accounts/:id/captain/preferences
|
||||
func (h *CaptainPreferenceHandler) Update(c *gin.Context) {
|
||||
accountID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
accountID := parseAccountIDParam(c)
|
||||
if accountID == 0 {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
|
||||
return
|
||||
}
|
||||
if !captainPreferencesCanUpdate(c) {
|
||||
response.AbortWithStatusError(c, http.StatusUnauthorized, response.ErrUnauthorized, "administrator role required")
|
||||
return
|
||||
}
|
||||
|
||||
var req service.UpdatePreferenceRequest
|
||||
var req service.UpdateCaptainConfigRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
pref, err := h.svc.Update(c.Request.Context(), uint(accountID), &req)
|
||||
pref, err := h.svc.UpdateConfig(c.Request.Context(), accountID, &req)
|
||||
if err != nil {
|
||||
applogger.L().Errorf("Update captain preference: %v", err)
|
||||
response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "failed to update preference")
|
||||
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, pref)
|
||||
c.JSON(http.StatusOK, pref)
|
||||
}
|
||||
|
||||
// Delete removes the captain preference for an account.
|
||||
// DELETE /api/v1/accounts/:id/captain/preferences
|
||||
func (h *CaptainPreferenceHandler) Delete(c *gin.Context) {
|
||||
accountID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
accountID := parseAccountIDParam(c)
|
||||
if accountID == 0 {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.svc.Delete(c.Request.Context(), uint(accountID)); err != nil {
|
||||
if err := h.svc.Delete(c.Request.Context(), accountID); err != nil {
|
||||
applogger.L().Errorf("Delete captain preference: %v", err)
|
||||
response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "failed to delete preference")
|
||||
return
|
||||
@@ -106,3 +109,8 @@ func (h *CaptainPreferenceHandler) Delete(c *gin.Context) {
|
||||
|
||||
response.OK(c, gin.H{"message": "preference deleted"})
|
||||
}
|
||||
|
||||
func captainPreferencesCanUpdate(c *gin.Context) bool {
|
||||
role := getRole(c)
|
||||
return role == "administrator" || role == "super_admin"
|
||||
}
|
||||
|
||||
@@ -3,131 +3,149 @@ package v1
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gochat/gochat/internal/model"
|
||||
"github.com/gochat/gochat/internal/repository"
|
||||
"github.com/gochat/gochat/internal/service"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/suite"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/datatypes"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
type CaptainPreferenceHandlerTestSuite struct {
|
||||
suite.Suite
|
||||
type captainPreferenceFixture struct {
|
||||
db *gorm.DB
|
||||
handler *CaptainPreferenceHandler
|
||||
router *gin.Engine
|
||||
account *model.Account
|
||||
}
|
||||
|
||||
func (s *CaptainPreferenceHandlerTestSuite) SetupSuite() {
|
||||
func newCaptainPreferenceFixture(t *testing.T) *captainPreferenceFixture {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
db, err := gorm.Open(sqlite.Open("file::memory:"), &gorm.Config{
|
||||
Logger: logger.Default.LogMode(logger.Silent),
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.AutoMigrate(&model.Account{}, &model.CaptainPreference{}))
|
||||
|
||||
account := &model.Account{Name: "Captain Preferences", Active: true, CaptainModels: datatypes.JSON(`{}`), CaptainFeatures: datatypes.JSON(`{}`)}
|
||||
require.NoError(t, db.Create(account).Error)
|
||||
|
||||
prefRepo := repository.NewCaptainPreferenceRepo(db)
|
||||
accountRepo := repository.NewAccountRepo(db)
|
||||
handler := NewCaptainPreferenceHandler(service.NewCaptainPreferenceService(prefRepo, accountRepo))
|
||||
router := gin.New()
|
||||
router.GET("/api/v1/accounts/:account_id/captain/preferences", handler.Get)
|
||||
router.PUT("/api/v1/accounts/:account_id/captain/preferences", func(c *gin.Context) {
|
||||
c.Set("role", "administrator")
|
||||
handler.Update(c)
|
||||
})
|
||||
router.PUT("/api/v1/accounts/:account_id/captain/preferences/as-agent", func(c *gin.Context) {
|
||||
c.Set("role", "agent")
|
||||
handler.Update(c)
|
||||
})
|
||||
s.Require().NoError(err)
|
||||
s.Require().NoError(db.AutoMigrate(&model.Account{}, &model.CaptainPreference{}))
|
||||
s.db = db
|
||||
|
||||
repo := repository.NewCaptainPreferenceRepo(db)
|
||||
svc := service.NewCaptainPreferenceService(repo)
|
||||
s.handler = NewCaptainPreferenceHandler(svc)
|
||||
|
||||
s.account = &model.Account{Name: "test-captain-pref-account"}
|
||||
s.Require().NoError(db.Create(s.account).Error)
|
||||
t.Cleanup(func() {
|
||||
sqlDB, dbErr := db.DB()
|
||||
require.NoError(t, dbErr)
|
||||
require.NoError(t, sqlDB.Close())
|
||||
})
|
||||
return &captainPreferenceFixture{db: db, router: router, account: account}
|
||||
}
|
||||
|
||||
func (s *CaptainPreferenceHandlerTestSuite) TearDownSuite() {
|
||||
if s.db != nil {
|
||||
sqlDB, _ := s.db.DB()
|
||||
sqlDB.Close()
|
||||
func (f *captainPreferenceFixture) path(suffix string) string {
|
||||
return "/api/v1/accounts/" + strconv.FormatUint(uint64(f.account.ID), 10) + "/captain/preferences" + suffix
|
||||
}
|
||||
|
||||
func (f *captainPreferenceFixture) request(method, path string, body any) *httptest.ResponseRecorder {
|
||||
var raw []byte
|
||||
if body != nil {
|
||||
raw, _ = json.Marshal(body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCaptainPreferenceHandlerSuite(t *testing.T) {
|
||||
suite.Run(t, new(CaptainPreferenceHandlerTestSuite))
|
||||
}
|
||||
|
||||
func (s *CaptainPreferenceHandlerTestSuite) TestCreate_BadRequest_InvalidAccountID() {
|
||||
r := gin.New()
|
||||
r.POST("/api/v1/accounts/:id/captain/preferences", s.handler.Create)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
req, _ := http.NewRequest("POST", "/api/v1/accounts/abc/captain/preferences", nil)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
assert.Equal(s.T(), http.StatusBadRequest, w.Code)
|
||||
}
|
||||
|
||||
func (s *CaptainPreferenceHandlerTestSuite) TestCreate_BadRequest_EmptyBody() {
|
||||
r := gin.New()
|
||||
r.POST("/api/v1/accounts/:id/captain/preferences", s.handler.Create)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
req, _ := http.NewRequest("POST", fmt.Sprintf("/api/v1/accounts/%d/captain/preferences", s.account.ID), nil)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
assert.Equal(s.T(), http.StatusBadRequest, w.Code)
|
||||
}
|
||||
|
||||
func (s *CaptainPreferenceHandlerTestSuite) TestCreate_Success() {
|
||||
r := gin.New()
|
||||
r.POST("/api/v1/accounts/:id/captain/preferences", s.handler.Create)
|
||||
|
||||
body := map[string]interface{}{
|
||||
"tone": "professional",
|
||||
"language": "en",
|
||||
"auto_label_enabled": true,
|
||||
"auto_follow_up_enabled": false,
|
||||
recorder := httptest.NewRecorder()
|
||||
req, _ := http.NewRequest(method, path, bytes.NewReader(raw))
|
||||
if body != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
b, _ := json.Marshal(body)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
req, _ := http.NewRequest("POST", fmt.Sprintf("/api/v1/accounts/%d/captain/preferences", s.account.ID), bytes.NewBuffer(b))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
assert.Equal(s.T(), http.StatusOK, w.Code)
|
||||
f.router.ServeHTTP(recorder, req)
|
||||
return recorder
|
||||
}
|
||||
|
||||
func (s *CaptainPreferenceHandlerTestSuite) TestGet_BadRequest_InvalidAccountID() {
|
||||
r := gin.New()
|
||||
r.GET("/api/v1/accounts/:id/captain/preferences", s.handler.Get)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
req, _ := http.NewRequest("GET", "/api/v1/accounts/abc/captain/preferences", nil)
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
assert.Equal(s.T(), http.StatusBadRequest, w.Code)
|
||||
func decodeCaptainPreferencePayload(t *testing.T, recorder *httptest.ResponseRecorder) map[string]any {
|
||||
t.Helper()
|
||||
var payload map[string]any
|
||||
require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &payload))
|
||||
return payload
|
||||
}
|
||||
|
||||
func (s *CaptainPreferenceHandlerTestSuite) TestUpdate_BadRequest_InvalidAccountID() {
|
||||
r := gin.New()
|
||||
r.PUT("/api/v1/accounts/:id/captain/preferences", s.handler.Update)
|
||||
func TestCaptainPreferencesGetReturnsRawChatwootConfig(t *testing.T) {
|
||||
f := newCaptainPreferenceFixture(t)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
req, _ := http.NewRequest("PUT", "/api/v1/accounts/abc/captain/preferences", nil)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
r.ServeHTTP(w, req)
|
||||
w := f.request(http.MethodGet, f.path(""), nil)
|
||||
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
|
||||
payload := decodeCaptainPreferencePayload(t, w)
|
||||
require.Nil(t, payload["success"])
|
||||
require.Contains(t, payload, "providers")
|
||||
require.Contains(t, payload, "models")
|
||||
require.Contains(t, payload, "features")
|
||||
|
||||
assert.Equal(s.T(), http.StatusBadRequest, w.Code)
|
||||
features := payload["features"].(map[string]any)
|
||||
editor := features["editor"].(map[string]any)
|
||||
require.Equal(t, false, editor["enabled"])
|
||||
require.Equal(t, "gpt-4.1-mini", editor["default"])
|
||||
require.Equal(t, "gpt-4.1-mini", editor["selected"])
|
||||
require.NotEmpty(t, editor["models"].([]any))
|
||||
}
|
||||
|
||||
func (s *CaptainPreferenceHandlerTestSuite) TestDelete_BadRequest_InvalidAccountID() {
|
||||
r := gin.New()
|
||||
r.DELETE("/api/v1/accounts/:id/captain/preferences", s.handler.Delete)
|
||||
func TestCaptainPreferencesUpdateMergesAccountModelsAndFeatures(t *testing.T) {
|
||||
f := newCaptainPreferenceFixture(t)
|
||||
require.NoError(t, f.db.Model(&model.Account{}).Where("id = ?", f.account.ID).Updates(map[string]any{
|
||||
"captain_models": datatypes.JSON(`{"editor":"gpt-4.1-mini","assistant":"gpt-5.1"}`),
|
||||
"captain_features": datatypes.JSON(`{"editor":true,"assistant":false}`),
|
||||
}).Error)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
req, _ := http.NewRequest("DELETE", "/api/v1/accounts/abc/captain/preferences", nil)
|
||||
r.ServeHTTP(w, req)
|
||||
w := f.request(http.MethodPut, f.path(""), map[string]any{
|
||||
"captain_models": map[string]any{"editor": "gpt-4.1"},
|
||||
"captain_features": map[string]any{"editor": false},
|
||||
})
|
||||
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
|
||||
payload := decodeCaptainPreferencePayload(t, w)
|
||||
features := payload["features"].(map[string]any)
|
||||
require.Equal(t, "gpt-4.1", features["editor"].(map[string]any)["selected"])
|
||||
require.Equal(t, false, features["editor"].(map[string]any)["enabled"])
|
||||
require.Equal(t, "gpt-5.1", features["assistant"].(map[string]any)["selected"])
|
||||
require.Equal(t, false, features["assistant"].(map[string]any)["enabled"])
|
||||
|
||||
assert.Equal(s.T(), http.StatusBadRequest, w.Code)
|
||||
}
|
||||
var account model.Account
|
||||
require.NoError(t, f.db.First(&account, f.account.ID).Error)
|
||||
var models map[string]string
|
||||
var featureValues map[string]bool
|
||||
require.NoError(t, json.Unmarshal(account.CaptainModels, &models))
|
||||
require.NoError(t, json.Unmarshal(account.CaptainFeatures, &featureValues))
|
||||
require.Equal(t, "gpt-4.1", models["editor"])
|
||||
require.Equal(t, "gpt-5.1", models["assistant"])
|
||||
require.False(t, featureValues["editor"])
|
||||
require.False(t, featureValues["assistant"])
|
||||
}
|
||||
|
||||
func TestCaptainPreferencesUpdateRejectsNonAdminAndInvalidModel(t *testing.T) {
|
||||
f := newCaptainPreferenceFixture(t)
|
||||
|
||||
w := f.request(http.MethodPut, f.path("/as-agent"), map[string]any{"captain_models": map[string]any{"editor": "gpt-4.1"}})
|
||||
require.Equal(t, http.StatusUnauthorized, w.Code, w.Body.String())
|
||||
|
||||
w = f.request(http.MethodPut, f.path(""), map[string]any{"captain_models": map[string]any{"editor": "not-a-model"}})
|
||||
require.Equal(t, http.StatusUnprocessableEntity, w.Code, w.Body.String())
|
||||
require.Contains(t, decodeCaptainPreferencePayload(t, w)["error"], "not a valid model")
|
||||
}
|
||||
|
||||
func TestCaptainPreferencesInvalidAccountID(t *testing.T) {
|
||||
f := newCaptainPreferenceFixture(t)
|
||||
|
||||
w := f.request(http.MethodGet, "/api/v1/accounts/abc/captain/preferences", nil)
|
||||
require.Equal(t, http.StatusBadRequest, w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user