feat(captain): align preferences payloads
This commit is contained in:
@@ -567,7 +567,7 @@ func Bootstrap(env string) (*App, error) {
|
||||
copilotContextService := service.NewCopilotContextService(messageRepo, conversationRepo, contactRepo, llmProvider)
|
||||
captainTaskService := service.NewCaptainTaskService(captainAssistantRepo, captainAssistantResponseRepo, captainCustomToolRepo, conversationRepo, messageRepo, llmProvider, copilotContextService)
|
||||
conversationInsightService := service.NewConversationInsightService(conversationRepo, messageRepo, captainAssistantRepo, llmProvider)
|
||||
captainPreferenceService := service.NewCaptainPreferenceService(captainPreferenceRepo)
|
||||
captainPreferenceService := service.NewCaptainPreferenceService(captainPreferenceRepo, accountRepo)
|
||||
captainTaskExtendedService := service.NewCaptainTaskExtendedService(conversationRepo, messageRepo, captainAssistantRepo, captainPreferenceRepo, llmProvider)
|
||||
captainAssistantResponseService := service.NewCaptainAssistantResponseService(captainAssistantRepo, captainAssistantResponseRepo, conversationRepo, messageRepo, captainPreferenceRepo, llmProvider)
|
||||
captainBulkActionService := service.NewCaptainBulkActionService(conversationRepo, messageRepo, captainAssistantRepo, captainPreferenceRepo, llmProvider, captainTaskExtendedService, captainAssistantResponseService)
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
|
||||
+15
-11
@@ -1,19 +1,23 @@
|
||||
package model
|
||||
|
||||
import "gorm.io/datatypes"
|
||||
|
||||
// Account represents a tenant/organization in the system.
|
||||
type Account struct {
|
||||
Base
|
||||
Name string `gorm:"size:255;not null" json:"name"`
|
||||
Domain string `gorm:"size:255" json:"domain,omitempty"`
|
||||
Locale string `gorm:"size:10;default:en" json:"locale"`
|
||||
Timezone string `gorm:"size:50;default:UTC" json:"timezone"`
|
||||
Active bool `gorm:"default:true" json:"active"`
|
||||
Status string `gorm:"size:50;default:active" json:"status"`
|
||||
OnboardingStep string `gorm:"size:100" json:"onboarding_step,omitempty"`
|
||||
FeatureFlags string `gorm:"type:text" json:"feature_flags,omitempty"` // JSON-encoded feature flags
|
||||
AutoResolveDuration int `gorm:"default:0" json:"auto_resolve_duration,omitempty"` // days
|
||||
AgentLimit int `gorm:"default:0" json:"agent_limit,omitempty"` // max agents allowed (0 = unlimited), Chatwoot usage_limits[:agents]
|
||||
InboxLimit int `gorm:"default:0" json:"inbox_limit,omitempty"` // max inboxes allowed (0 = unlimited), Chatwoot usage_limits[:inboxes]
|
||||
Name string `gorm:"size:255;not null" json:"name"`
|
||||
Domain string `gorm:"size:255" json:"domain,omitempty"`
|
||||
Locale string `gorm:"size:10;default:en" json:"locale"`
|
||||
Timezone string `gorm:"size:50;default:UTC" json:"timezone"`
|
||||
Active bool `gorm:"default:true" json:"active"`
|
||||
Status string `gorm:"size:50;default:active" json:"status"`
|
||||
OnboardingStep string `gorm:"size:100" json:"onboarding_step,omitempty"`
|
||||
FeatureFlags string `gorm:"type:text" json:"feature_flags,omitempty"` // JSON-encoded feature flags
|
||||
AutoResolveDuration int `gorm:"default:0" json:"auto_resolve_duration,omitempty"` // days
|
||||
AgentLimit int `gorm:"default:0" json:"agent_limit,omitempty"` // max agents allowed (0 = unlimited), Chatwoot usage_limits[:agents]
|
||||
InboxLimit int `gorm:"default:0" json:"inbox_limit,omitempty"` // max inboxes allowed (0 = unlimited), Chatwoot usage_limits[:inboxes]
|
||||
CaptainModels datatypes.JSON `gorm:"type:jsonb;default:'{}'" json:"captain_models,omitempty"`
|
||||
CaptainFeatures datatypes.JSON `gorm:"type:jsonb;default:'{}'" json:"captain_features,omitempty"`
|
||||
}
|
||||
|
||||
func (Account) TableName() string { return "accounts" }
|
||||
|
||||
@@ -1265,10 +1265,10 @@ func registerV1Routes(g *gin.RouterGroup, h *Handlers) {
|
||||
// Reference: Chatwoot Captain::PreferencesController
|
||||
preferences := captain.Group("/preferences")
|
||||
{
|
||||
preferences.POST("/", h.CaptainPreference.Create)
|
||||
preferences.GET("", h.CaptainPreference.Get)
|
||||
preferences.GET("/", h.CaptainPreference.Get)
|
||||
preferences.PUT("", h.CaptainPreference.Update)
|
||||
preferences.PUT("/", h.CaptainPreference.Update)
|
||||
preferences.DELETE("/", h.CaptainPreference.Delete)
|
||||
}
|
||||
|
||||
// M12: Label Suggestion + Follow Up (GET endpoints)
|
||||
|
||||
@@ -2,22 +2,30 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/gochat/gochat/internal/model"
|
||||
"github.com/gochat/gochat/internal/repository"
|
||||
pkgvalidator "github.com/gochat/gochat/pkg/validator"
|
||||
applogger "github.com/gochat/gochat/pkg/logger"
|
||||
pkgvalidator "github.com/gochat/gochat/pkg/validator"
|
||||
"gorm.io/datatypes"
|
||||
)
|
||||
|
||||
// CaptainPreferenceService implements business logic for CaptainPreference operations.
|
||||
// Reference: Chatwoot enterprise/app/controllers/api/v1/captain/preferences_controller.rb
|
||||
type CaptainPreferenceService struct {
|
||||
repo *repository.CaptainPreferenceRepo
|
||||
repo *repository.CaptainPreferenceRepo
|
||||
accountRepo *repository.AccountRepo
|
||||
}
|
||||
|
||||
func NewCaptainPreferenceService(repo *repository.CaptainPreferenceRepo) *CaptainPreferenceService {
|
||||
return &CaptainPreferenceService{repo: repo}
|
||||
func NewCaptainPreferenceService(repo *repository.CaptainPreferenceRepo, accountRepo ...*repository.AccountRepo) *CaptainPreferenceService {
|
||||
svc := &CaptainPreferenceService{repo: repo}
|
||||
if len(accountRepo) > 0 {
|
||||
svc.accountRepo = accountRepo[0]
|
||||
}
|
||||
return svc
|
||||
}
|
||||
|
||||
// --- Request DTOs ---
|
||||
@@ -25,29 +33,106 @@ func NewCaptainPreferenceService(repo *repository.CaptainPreferenceRepo) *Captai
|
||||
// CreatePreferenceRequest is the DTO for creating a preference.
|
||||
// Reference: Chatwoot enterprise/app/models/captain/preference.rb
|
||||
type CreatePreferenceRequest struct {
|
||||
Tone string `json:"tone" validate:"omitempty,oneof=professional casual friendly formal"`
|
||||
Language string `json:"language" validate:"omitempty,min=1,max=10"`
|
||||
ResponseGuidelines string `json:"response_guidelines" validate:"omitempty,max=2000"`
|
||||
AutoLabelEnabled bool `json:"auto_label_enabled"`
|
||||
AutoFollowUpEnabled bool `json:"auto_follow_up_enabled"`
|
||||
AutoReplyEnabled bool `json:"auto_reply_enabled"`
|
||||
MaxResponseLength int `json:"max_response_length" validate:"omitempty,min=50,max=5000"`
|
||||
CustomPromptSuffix string `json:"custom_prompt_suffix" validate:"omitempty,max=1000"`
|
||||
Tone string `json:"tone" validate:"omitempty,oneof=professional casual friendly formal"`
|
||||
Language string `json:"language" validate:"omitempty,min=1,max=10"`
|
||||
ResponseGuidelines string `json:"response_guidelines" validate:"omitempty,max=2000"`
|
||||
AutoLabelEnabled bool `json:"auto_label_enabled"`
|
||||
AutoFollowUpEnabled bool `json:"auto_follow_up_enabled"`
|
||||
AutoReplyEnabled bool `json:"auto_reply_enabled"`
|
||||
MaxResponseLength int `json:"max_response_length" validate:"omitempty,min=50,max=5000"`
|
||||
CustomPromptSuffix string `json:"custom_prompt_suffix" validate:"omitempty,max=1000"`
|
||||
}
|
||||
|
||||
// UpdatePreferenceRequest is the DTO for updating a preference.
|
||||
// Reference: Chatwoot enterprise/app/models/captain/preference.rb
|
||||
type UpdatePreferenceRequest struct {
|
||||
Tone string `json:"tone,omitempty" validate:"omitempty,oneof=professional casual friendly formal"`
|
||||
Language string `json:"language,omitempty" validate:"omitempty,min=1,max=10"`
|
||||
ResponseGuidelines string `json:"response_guidelines,omitempty" validate:"omitempty,max=2000"`
|
||||
AutoLabelEnabled *bool `json:"auto_label_enabled,omitempty"`
|
||||
AutoFollowUpEnabled *bool `json:"auto_follow_up_enabled,omitempty"`
|
||||
AutoReplyEnabled *bool `json:"auto_reply_enabled,omitempty"`
|
||||
MaxResponseLength *int `json:"max_response_length,omitempty" validate:"omitempty,min=50,max=5000"`
|
||||
CustomPromptSuffix string `json:"custom_prompt_suffix,omitempty" validate:"omitempty,max=1000"`
|
||||
Tone string `json:"tone,omitempty" validate:"omitempty,oneof=professional casual friendly formal"`
|
||||
Language string `json:"language,omitempty" validate:"omitempty,min=1,max=10"`
|
||||
ResponseGuidelines string `json:"response_guidelines,omitempty" validate:"omitempty,max=2000"`
|
||||
AutoLabelEnabled *bool `json:"auto_label_enabled,omitempty"`
|
||||
AutoFollowUpEnabled *bool `json:"auto_follow_up_enabled,omitempty"`
|
||||
AutoReplyEnabled *bool `json:"auto_reply_enabled,omitempty"`
|
||||
MaxResponseLength *int `json:"max_response_length,omitempty" validate:"omitempty,min=50,max=5000"`
|
||||
CustomPromptSuffix string `json:"custom_prompt_suffix,omitempty" validate:"omitempty,max=1000"`
|
||||
}
|
||||
|
||||
// UpdateCaptainConfigRequest matches Chatwoot's Captain::PreferencesController params.
|
||||
type UpdateCaptainConfigRequest struct {
|
||||
CaptainModels map[string]string `json:"captain_models"`
|
||||
CaptainFeatures map[string]bool `json:"captain_features"`
|
||||
}
|
||||
|
||||
// CaptainConfigPayload is the raw payload returned by Chatwoot preferences show/update.
|
||||
type CaptainConfigPayload struct {
|
||||
Providers map[string]map[string]string `json:"providers"`
|
||||
Models map[string]CaptainModelConfig `json:"models"`
|
||||
Features map[string]CaptainFeatureConfig `json:"features"`
|
||||
}
|
||||
|
||||
type CaptainModelConfig struct {
|
||||
Provider string `json:"provider"`
|
||||
DisplayName string `json:"display_name"`
|
||||
ComingSoon *bool `json:"coming_soon,omitempty"`
|
||||
CreditMultiplier int `json:"credit_multiplier"`
|
||||
}
|
||||
|
||||
type CaptainFeatureConfig struct {
|
||||
Models []CaptainFeatureModel `json:"models"`
|
||||
Default string `json:"default"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Selected string `json:"selected"`
|
||||
}
|
||||
|
||||
type CaptainFeatureModel struct {
|
||||
ID string `json:"id"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Provider string `json:"provider"`
|
||||
ComingSoon *bool `json:"coming_soon"`
|
||||
CreditMultiplier int `json:"credit_multiplier"`
|
||||
}
|
||||
|
||||
var captainProviders = map[string]map[string]string{
|
||||
"openai": {"display_name": "OpenAI"},
|
||||
"anthropic": {"display_name": "Anthropic"},
|
||||
"gemini": {"display_name": "Gemini"},
|
||||
}
|
||||
|
||||
var captainModels = map[string]CaptainModelConfig{
|
||||
"gpt-4.1": {Provider: "openai", DisplayName: "GPT-4.1", CreditMultiplier: 3},
|
||||
"gpt-4.1-mini": {Provider: "openai", DisplayName: "GPT-4.1 Mini", CreditMultiplier: 1},
|
||||
"gpt-4.1-nano": {Provider: "openai", DisplayName: "GPT-4.1 Nano", CreditMultiplier: 1},
|
||||
"gpt-5.1": {Provider: "openai", DisplayName: "GPT-5.1", CreditMultiplier: 2},
|
||||
"gpt-5-mini": {Provider: "openai", DisplayName: "GPT-5 Mini", CreditMultiplier: 1},
|
||||
"gpt-5-nano": {Provider: "openai", DisplayName: "GPT-5 Nano", CreditMultiplier: 1},
|
||||
"gpt-5.2": {Provider: "openai", DisplayName: "GPT-5.2", CreditMultiplier: 3},
|
||||
"claude-haiku-4.5": {Provider: "anthropic", DisplayName: "Claude Haiku 4.5", ComingSoon: boolPtr(true), CreditMultiplier: 2},
|
||||
"claude-sonnet-4.5": {Provider: "anthropic", DisplayName: "Claude Sonnet 4.5", ComingSoon: boolPtr(true), CreditMultiplier: 3},
|
||||
"gemini-3-flash": {Provider: "gemini", DisplayName: "Gemini 3 Flash", ComingSoon: boolPtr(true), CreditMultiplier: 1},
|
||||
"gemini-3-pro": {Provider: "gemini", DisplayName: "Gemini 3 Pro", ComingSoon: boolPtr(true), CreditMultiplier: 3},
|
||||
"whisper-1": {Provider: "openai", DisplayName: "Whisper", CreditMultiplier: 1},
|
||||
"text-embedding-3-small": {Provider: "openai", DisplayName: "Text Embedding 3 Small", CreditMultiplier: 1},
|
||||
}
|
||||
|
||||
var captainFeatureModels = map[string][]string{
|
||||
"editor": {"gpt-4.1-mini", "gpt-4.1-nano", "gpt-5-mini", "gpt-4.1", "gpt-5.1", "gpt-5.2", "claude-haiku-4.5", "gemini-3-flash", "gemini-3-pro"},
|
||||
"assistant": {"gpt-5-mini", "gpt-4.1", "gpt-5.1", "gpt-5.2", "claude-haiku-4.5", "claude-sonnet-4.5", "gemini-3-flash", "gemini-3-pro"},
|
||||
"copilot": {"gpt-5-mini", "gpt-4.1", "gpt-5.1", "gpt-5.2", "claude-haiku-4.5", "claude-sonnet-4.5", "gemini-3-flash", "gemini-3-pro"},
|
||||
"label_suggestion": {"gpt-4.1-nano", "gpt-4.1-mini", "gpt-5-mini", "gemini-3-flash", "claude-haiku-4.5"},
|
||||
"audio_transcription": {"whisper-1"},
|
||||
"help_center_search": {"text-embedding-3-small"},
|
||||
}
|
||||
|
||||
var captainFeatureDefaults = map[string]string{
|
||||
"editor": "gpt-4.1-mini",
|
||||
"assistant": "gpt-5.1",
|
||||
"copilot": "gpt-5.1",
|
||||
"label_suggestion": "gpt-4.1-nano",
|
||||
"audio_transcription": "whisper-1",
|
||||
"help_center_search": "text-embedding-3-small",
|
||||
}
|
||||
|
||||
var captainFeatureOrder = []string{"editor", "assistant", "copilot", "label_suggestion", "audio_transcription", "help_center_search"}
|
||||
|
||||
// --- Business logic ---
|
||||
|
||||
// validTones are the allowed tone values for captain preferences.
|
||||
@@ -64,6 +149,138 @@ func isValidTone(tone string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// GetConfig returns Chatwoot's raw Captain preferences payload for an account.
|
||||
func (s *CaptainPreferenceService) GetConfig(ctx context.Context, accountID uint) (*CaptainConfigPayload, error) {
|
||||
account, err := s.findAccount(ctx, accountID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return captainConfigPayload(account), nil
|
||||
}
|
||||
|
||||
// UpdateConfig merges captain_models/captain_features into account settings and returns the raw payload.
|
||||
func (s *CaptainPreferenceService) UpdateConfig(ctx context.Context, accountID uint, req *UpdateCaptainConfigRequest) (*CaptainConfigPayload, error) {
|
||||
account, err := s.findAccount(ctx, accountID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
models := jsonMapString(account.CaptainModels)
|
||||
features := jsonMapBool(account.CaptainFeatures)
|
||||
|
||||
for key, value := range req.CaptainModels {
|
||||
if !isCaptainFeature(key) {
|
||||
continue
|
||||
}
|
||||
if strings.TrimSpace(value) == "" {
|
||||
models[key] = ""
|
||||
continue
|
||||
}
|
||||
if !validCaptainModelFor(key, value) {
|
||||
return nil, fmt.Errorf("'%s' is not a valid model for %s. Allowed: %s", value, key, strings.Join(captainFeatureModels[key], ", "))
|
||||
}
|
||||
models[key] = value
|
||||
}
|
||||
for key, value := range req.CaptainFeatures {
|
||||
if !isCaptainFeature(key) {
|
||||
continue
|
||||
}
|
||||
features[key] = value
|
||||
}
|
||||
|
||||
account.CaptainModels = marshalJSONMap(models)
|
||||
account.CaptainFeatures = marshalJSONMap(features)
|
||||
if err := s.accountRepo.Update(ctx, account); err != nil {
|
||||
return nil, fmt.Errorf("update captain preferences: %w", err)
|
||||
}
|
||||
return captainConfigPayload(account), nil
|
||||
}
|
||||
|
||||
func (s *CaptainPreferenceService) findAccount(ctx context.Context, accountID uint) (*model.Account, error) {
|
||||
if s.accountRepo == nil {
|
||||
return nil, fmt.Errorf("account repository is required for captain preferences")
|
||||
}
|
||||
account, err := s.accountRepo.FindByID(ctx, accountID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("account not found: %w", err)
|
||||
}
|
||||
return account, nil
|
||||
}
|
||||
|
||||
func captainConfigPayload(account *model.Account) *CaptainConfigPayload {
|
||||
accountModels := jsonMapString(account.CaptainModels)
|
||||
accountFeatures := jsonMapBool(account.CaptainFeatures)
|
||||
features := make(map[string]CaptainFeatureConfig, len(captainFeatureOrder))
|
||||
for _, key := range captainFeatureOrder {
|
||||
models := make([]CaptainFeatureModel, 0, len(captainFeatureModels[key]))
|
||||
for _, modelName := range captainFeatureModels[key] {
|
||||
modelConfig := captainModels[modelName]
|
||||
models = append(models, CaptainFeatureModel{
|
||||
ID: modelName,
|
||||
DisplayName: modelConfig.DisplayName,
|
||||
Provider: modelConfig.Provider,
|
||||
ComingSoon: modelConfig.ComingSoon,
|
||||
CreditMultiplier: modelConfig.CreditMultiplier,
|
||||
})
|
||||
}
|
||||
selected := accountModels[key]
|
||||
if !validCaptainModelFor(key, selected) {
|
||||
selected = captainFeatureDefaults[key]
|
||||
}
|
||||
features[key] = CaptainFeatureConfig{
|
||||
Models: models,
|
||||
Default: captainFeatureDefaults[key],
|
||||
Enabled: accountFeatures[key],
|
||||
Selected: selected,
|
||||
}
|
||||
}
|
||||
return &CaptainConfigPayload{Providers: captainProviders, Models: captainModels, Features: features}
|
||||
}
|
||||
|
||||
func isCaptainFeature(key string) bool {
|
||||
_, ok := captainFeatureModels[key]
|
||||
return ok
|
||||
}
|
||||
|
||||
func validCaptainModelFor(feature, modelName string) bool {
|
||||
if modelName == "" {
|
||||
return false
|
||||
}
|
||||
for _, allowed := range captainFeatureModels[feature] {
|
||||
if allowed == modelName {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func jsonMapString(raw datatypes.JSON) map[string]string {
|
||||
result := map[string]string{}
|
||||
if len(raw) == 0 || string(raw) == "null" {
|
||||
return result
|
||||
}
|
||||
_ = json.Unmarshal(raw, &result)
|
||||
return result
|
||||
}
|
||||
|
||||
func jsonMapBool(raw datatypes.JSON) map[string]bool {
|
||||
result := map[string]bool{}
|
||||
if len(raw) == 0 || string(raw) == "null" {
|
||||
return result
|
||||
}
|
||||
_ = json.Unmarshal(raw, &result)
|
||||
return result
|
||||
}
|
||||
|
||||
func marshalJSONMap(value any) datatypes.JSON {
|
||||
raw, _ := json.Marshal(value)
|
||||
return datatypes.JSON(raw)
|
||||
}
|
||||
|
||||
func boolPtr(value bool) *bool {
|
||||
return &value
|
||||
}
|
||||
|
||||
// Create creates a new preference for an account.
|
||||
func (s *CaptainPreferenceService) Create(ctx context.Context, accountID uint, req *CreatePreferenceRequest) (*model.CaptainPreference, error) {
|
||||
// Validate request
|
||||
@@ -78,15 +295,15 @@ func (s *CaptainPreferenceService) Create(ctx context.Context, accountID uint, r
|
||||
}
|
||||
|
||||
pref := &model.CaptainPreference{
|
||||
AccountID: accountID,
|
||||
Tone: req.Tone,
|
||||
Language: req.Language,
|
||||
ResponseGuidelines: req.ResponseGuidelines,
|
||||
AutoLabelEnabled: req.AutoLabelEnabled,
|
||||
AccountID: accountID,
|
||||
Tone: req.Tone,
|
||||
Language: req.Language,
|
||||
ResponseGuidelines: req.ResponseGuidelines,
|
||||
AutoLabelEnabled: req.AutoLabelEnabled,
|
||||
AutoFollowUpEnabled: req.AutoFollowUpEnabled,
|
||||
AutoReplyEnabled: req.AutoReplyEnabled,
|
||||
MaxResponseLength: req.MaxResponseLength,
|
||||
CustomPromptSuffix: req.CustomPromptSuffix,
|
||||
AutoReplyEnabled: req.AutoReplyEnabled,
|
||||
MaxResponseLength: req.MaxResponseLength,
|
||||
CustomPromptSuffix: req.CustomPromptSuffix,
|
||||
}
|
||||
|
||||
// Apply defaults
|
||||
|
||||
Reference in New Issue
Block a user