feat(captain): align assistant resources
This commit is contained in:
@@ -1,15 +1,17 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gochat/gochat/internal/model"
|
||||
"github.com/gochat/gochat/internal/service"
|
||||
applogger "github.com/gochat/gochat/pkg/logger"
|
||||
"github.com/gochat/gochat/pkg/pagination"
|
||||
"github.com/gochat/gochat/pkg/response"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// CaptainAssistantHandler handles CaptainAssistant REST API endpoints.
|
||||
@@ -26,83 +28,106 @@ func NewCaptainAssistantHandler(svc *service.CaptainAssistantService) *CaptainAs
|
||||
// Create creates a new captain assistant.
|
||||
// POST /api/v1/accounts/:account_id/captain_assistants
|
||||
func (h *CaptainAssistantHandler) 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
|
||||
}
|
||||
|
||||
var req service.CreateAssistantRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
if err := bindCaptainAssistantPayload(c, &req); err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
assistant, err := h.svc.Create(c.Request.Context(), uint(accountID), &req)
|
||||
assistant, err := h.svc.Create(c.Request.Context(), accountID, &req)
|
||||
if err != nil {
|
||||
applogger.L().Errorf("Create captain assistant: %v", err)
|
||||
response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "failed to create assistant")
|
||||
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
response.Created(c, assistant)
|
||||
c.JSON(http.StatusOK, captainAssistantPayload(assistant))
|
||||
}
|
||||
|
||||
// Get retrieves a captain assistant by ID.
|
||||
// GET /api/v1/accounts/:account_id/captain_assistants/:id
|
||||
func (h *CaptainAssistantHandler) Get(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
accountID := parseAccountIDParam(c)
|
||||
if accountID == 0 {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
|
||||
return
|
||||
}
|
||||
id, err := parseUintParam(c, "assistant_id")
|
||||
if err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid id")
|
||||
return
|
||||
}
|
||||
|
||||
assistant, err := h.svc.Get(c.Request.Context(), uint(id))
|
||||
assistant, err := h.svc.Get(c.Request.Context(), accountID, id)
|
||||
if err != nil {
|
||||
applogger.L().Errorf("Get captain assistant: %v", err)
|
||||
response.AbortWithStatusError(c, http.StatusNotFound, response.ErrNotFound, "assistant not found")
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, assistant)
|
||||
c.JSON(http.StatusOK, captainAssistantPayload(assistant))
|
||||
}
|
||||
|
||||
// Update updates an existing captain assistant.
|
||||
// PUT /api/v1/accounts/:account_id/captain_assistants/:id
|
||||
func (h *CaptainAssistantHandler) Update(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
accountID := parseAccountIDParam(c)
|
||||
if accountID == 0 {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
|
||||
return
|
||||
}
|
||||
id, err := parseUintParam(c, "assistant_id")
|
||||
if err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid id")
|
||||
return
|
||||
}
|
||||
|
||||
var req service.UpdateAssistantRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
if err := bindCaptainAssistantPayload(c, &req); err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
assistant, err := h.svc.Update(c.Request.Context(), uint(id), &req)
|
||||
assistant, err := h.svc.Update(c.Request.Context(), accountID, id, &req)
|
||||
if err != nil {
|
||||
applogger.L().Errorf("Update captain assistant: %v", err)
|
||||
if captainAssistantErrorStatus(err) == http.StatusNotFound {
|
||||
response.AbortWithStatusError(c, http.StatusNotFound, response.ErrNotFound, "assistant not found")
|
||||
return
|
||||
}
|
||||
response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "failed to update assistant")
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, assistant)
|
||||
c.JSON(http.StatusOK, captainAssistantPayload(assistant))
|
||||
}
|
||||
|
||||
// Delete deletes a captain assistant.
|
||||
// DELETE /api/v1/accounts/:account_id/captain_assistants/:id
|
||||
func (h *CaptainAssistantHandler) Delete(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
accountID := parseAccountIDParam(c)
|
||||
if accountID == 0 {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
|
||||
return
|
||||
}
|
||||
id, err := parseUintParam(c, "assistant_id")
|
||||
if err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid id")
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.svc.Delete(c.Request.Context(), uint(id)); err != nil {
|
||||
if err := h.svc.Delete(c.Request.Context(), accountID, id); err != nil {
|
||||
applogger.L().Errorf("Delete captain assistant: %v", err)
|
||||
if captainAssistantErrorStatus(err) == http.StatusNotFound {
|
||||
response.AbortWithStatusError(c, http.StatusNotFound, response.ErrNotFound, "assistant not found")
|
||||
return
|
||||
}
|
||||
response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "failed to delete assistant")
|
||||
return
|
||||
}
|
||||
@@ -113,33 +138,36 @@ func (h *CaptainAssistantHandler) Delete(c *gin.Context) {
|
||||
// List retrieves captain assistants for an account.
|
||||
// GET /api/v1/accounts/:account_id/captain_assistants
|
||||
func (h *CaptainAssistantHandler) List(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
|
||||
}
|
||||
|
||||
p := pagination.Parse(c)
|
||||
assistants, count, err := h.svc.List(c.Request.Context(), uint(accountID), p.Offset, p.PerPage)
|
||||
assistants, count, err := h.svc.List(c.Request.Context(), accountID, 0, 1000)
|
||||
if err != nil {
|
||||
applogger.L().Errorf("List captain assistants: %v", err)
|
||||
response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "failed to list assistants")
|
||||
return
|
||||
}
|
||||
|
||||
response.OKWithMeta(c, assistants, p.Page, p.PerPage, count)
|
||||
payload := make([]gin.H, 0, len(assistants))
|
||||
for i := range assistants {
|
||||
payload = append(payload, captainAssistantPayload(&assistants[i]))
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"payload": payload, "meta": gin.H{"total_count": count, "page": 1}})
|
||||
}
|
||||
|
||||
// GetConfig retrieves the assistant's JSONB config.
|
||||
// GET /api/v1/accounts/:account_id/captain_assistants/:id/config
|
||||
func (h *CaptainAssistantHandler) GetConfig(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
id, err := parseUintAnyParam(c, "assistant_id", "id")
|
||||
if err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid id")
|
||||
return
|
||||
}
|
||||
|
||||
cfg, err := h.svc.GetConfig(c.Request.Context(), uint(id))
|
||||
cfg, err := h.svc.GetConfig(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
applogger.L().Errorf("GetConfig captain assistant: %v", err)
|
||||
response.AbortWithStatusError(c, http.StatusNotFound, response.ErrNotFound, "assistant not found")
|
||||
@@ -152,7 +180,7 @@ func (h *CaptainAssistantHandler) GetConfig(c *gin.Context) {
|
||||
// SetConfig updates the assistant's JSONB config.
|
||||
// PUT /api/v1/accounts/:account_id/captain_assistants/:id/config
|
||||
func (h *CaptainAssistantHandler) SetConfig(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
id, err := parseUintAnyParam(c, "assistant_id", "id")
|
||||
if err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid id")
|
||||
return
|
||||
@@ -164,7 +192,7 @@ func (h *CaptainAssistantHandler) SetConfig(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.svc.SetConfig(c.Request.Context(), uint(id), &cfg); err != nil {
|
||||
if err := h.svc.SetConfig(c.Request.Context(), id, &cfg); err != nil {
|
||||
applogger.L().Errorf("SetConfig captain assistant: %v", err)
|
||||
response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "failed to update config")
|
||||
return
|
||||
@@ -176,80 +204,191 @@ func (h *CaptainAssistantHandler) SetConfig(c *gin.Context) {
|
||||
// AssociateInbox binds an assistant to an inbox.
|
||||
// POST /api/v1/accounts/:account_id/captain_assistants/:id/inboxes
|
||||
func (h *CaptainAssistantHandler) AssociateInbox(c *gin.Context) {
|
||||
assistantID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
assistantID, err := parseUintParam(c, "assistant_id")
|
||||
if err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid assistant id")
|
||||
return
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
var req struct {
|
||||
InboxID uint `json:"inbox_id" validate:"required"`
|
||||
Inbox struct {
|
||||
InboxID uint `json:"inbox_id"`
|
||||
} `json:"inbox"`
|
||||
InboxID uint `json:"inbox_id"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, err.Error())
|
||||
return
|
||||
}
|
||||
inboxID := req.InboxID
|
||||
if inboxID == 0 {
|
||||
inboxID = req.Inbox.InboxID
|
||||
}
|
||||
|
||||
if err := h.svc.AssociateInbox(c.Request.Context(), uint(assistantID), req.InboxID, uint(accountID)); err != nil {
|
||||
inbox, err := h.svc.AssociateInbox(c.Request.Context(), assistantID, inboxID, accountID)
|
||||
if err != nil {
|
||||
applogger.L().Errorf("AssociateInbox: %v", err)
|
||||
if captainAssistantErrorStatus(err) == http.StatusNotFound {
|
||||
response.AbortWithStatusError(c, http.StatusNotFound, response.ErrNotFound, "captain inbox not found")
|
||||
return
|
||||
}
|
||||
response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "failed to associate inbox")
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, gin.H{"associated": true})
|
||||
c.JSON(http.StatusOK, serializeInbox(inbox))
|
||||
}
|
||||
|
||||
// DissociateInbox unbinds an assistant from an inbox.
|
||||
// DELETE /api/v1/accounts/:account_id/captain_assistants/:id/inboxes/:inbox_id
|
||||
func (h *CaptainAssistantHandler) DissociateInbox(c *gin.Context) {
|
||||
assistantID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
accountID := parseAccountIDParam(c)
|
||||
if accountID == 0 {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
|
||||
return
|
||||
}
|
||||
assistantID, err := parseUintParam(c, "assistant_id")
|
||||
if err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid assistant id")
|
||||
return
|
||||
}
|
||||
inboxID, err := strconv.ParseUint(c.Param("inbox_id"), 10, 64)
|
||||
inboxID, err := parseUintParam(c, "inbox_id")
|
||||
if err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid inbox_id")
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.svc.DissociateInbox(c.Request.Context(), uint(assistantID), uint(inboxID)); err != nil {
|
||||
if err := h.svc.DissociateInbox(c.Request.Context(), accountID, assistantID, inboxID); err != nil {
|
||||
applogger.L().Errorf("DissociateInbox: %v", err)
|
||||
response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "failed to dissociate inbox")
|
||||
response.AbortWithStatusError(c, http.StatusNotFound, response.ErrNotFound, "captain inbox not found")
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, gin.H{"dissociated": true})
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (h *CaptainAssistantHandler) ListInboxes(c *gin.Context) {
|
||||
accountID := parseAccountIDParam(c)
|
||||
if accountID == 0 {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
|
||||
return
|
||||
}
|
||||
assistantID, err := parseUintParam(c, "assistant_id")
|
||||
if err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid assistant id")
|
||||
return
|
||||
}
|
||||
inboxes, err := h.svc.ListInboxes(c.Request.Context(), accountID, assistantID)
|
||||
if err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusNotFound, response.ErrNotFound, "assistant not found")
|
||||
return
|
||||
}
|
||||
payload := make([]gin.H, 0, len(inboxes))
|
||||
for i := range inboxes {
|
||||
payload = append(payload, serializeInbox(&inboxes[i]))
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"payload": payload, "meta": gin.H{"total_count": len(payload), "page": 1}})
|
||||
}
|
||||
|
||||
func (h *CaptainAssistantHandler) Tools(c *gin.Context) {
|
||||
accountID := parseAccountIDParam(c)
|
||||
c.JSON(http.StatusOK, h.svc.AvailableTools(c.Request.Context(), accountID))
|
||||
}
|
||||
|
||||
// GenerateResponse generates an AI response via RAG.
|
||||
// POST /api/v1/accounts/:account_id/captain_assistants/:id/generate_response
|
||||
func (h *CaptainAssistantHandler) GenerateResponse(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
id, err := parseUintAnyParam(c, "assistant_id", "id")
|
||||
if err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid id")
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
Query string `json:"query" validate:"required"`
|
||||
Assistant struct {
|
||||
MessageContent string `json:"message_content"`
|
||||
Query string `json:"query"`
|
||||
} `json:"assistant"`
|
||||
MessageContent string `json:"message_content"`
|
||||
Query string `json:"query"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, err.Error())
|
||||
return
|
||||
}
|
||||
query := req.Query
|
||||
if query == "" {
|
||||
query = req.MessageContent
|
||||
}
|
||||
if query == "" {
|
||||
query = req.Assistant.Query
|
||||
}
|
||||
if query == "" {
|
||||
query = req.Assistant.MessageContent
|
||||
}
|
||||
if query == "" {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, "message_content is required")
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.svc.GenerateResponse(c.Request.Context(), uint(id), req.Query)
|
||||
result, err := h.svc.GenerateResponse(c.Request.Context(), id, query)
|
||||
if err != nil {
|
||||
applogger.L().Errorf("GenerateResponse: %v", err)
|
||||
response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "failed to generate response")
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, gin.H{"response": result})
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"response": result})
|
||||
}
|
||||
|
||||
func bindCaptainAssistantPayload(c *gin.Context, dst any) error {
|
||||
var raw map[string]json.RawMessage
|
||||
if err := c.ShouldBindJSON(&raw); err != nil {
|
||||
return err
|
||||
}
|
||||
if nested, ok := raw["assistant"]; ok {
|
||||
return json.Unmarshal(nested, dst)
|
||||
}
|
||||
body, err := json.Marshal(raw)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return json.Unmarshal(body, dst)
|
||||
}
|
||||
|
||||
func captainAssistantPayload(assistant *model.CaptainAssistant) gin.H {
|
||||
return gin.H{
|
||||
"account_id": assistant.AccountID,
|
||||
"config": rawJSONValue(assistant.Config),
|
||||
"created_at": assistant.CreatedAt.Unix(),
|
||||
"description": assistant.Description,
|
||||
"guardrails": rawJSONValue(assistant.Guardrails),
|
||||
"id": assistant.ID,
|
||||
"name": assistant.Name,
|
||||
"response_guidelines": rawJSONValue(assistant.ResponseGuidelines),
|
||||
"updated_at": assistant.UpdatedAt.Unix(),
|
||||
}
|
||||
}
|
||||
|
||||
func rawJSONValue(raw json.RawMessage) any {
|
||||
if len(raw) == 0 || string(raw) == "null" {
|
||||
return nil
|
||||
}
|
||||
var value any
|
||||
if err := json.Unmarshal(raw, &value); err != nil {
|
||||
return fmt.Sprintf("%s", raw)
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func captainAssistantErrorStatus(err error) int {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return http.StatusNotFound
|
||||
}
|
||||
return http.StatusInternalServerError
|
||||
}
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
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/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func setupCaptainAssistantHandlerTest(t *testing.T) (*gin.Engine, *gorm.DB) {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
dbName := fmt.Sprintf("file:%s?mode=memory&cache=private", t.Name())
|
||||
db, err := gorm.Open(sqlite.Open(dbName), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.AutoMigrate(
|
||||
&model.Account{},
|
||||
&model.Inbox{},
|
||||
&model.CaptainAssistant{},
|
||||
&model.CaptainInbox{},
|
||||
))
|
||||
t.Cleanup(func() {
|
||||
sqlDB, _ := db.DB()
|
||||
sqlDB.Close()
|
||||
})
|
||||
|
||||
assistantRepo := repository.NewCaptainAssistantRepo(db)
|
||||
inboxRepo := repository.NewCaptainInboxRepo(db)
|
||||
documentRepo := repository.NewCaptainDocumentRepo(db)
|
||||
responseRepo := repository.NewCaptainAssistantResponseRepo(db)
|
||||
svc := service.NewCaptainAssistantService(assistantRepo, inboxRepo, documentRepo, responseRepo, nil)
|
||||
handler := NewCaptainAssistantHandler(svc)
|
||||
|
||||
router := gin.New()
|
||||
assistants := router.Group("/api/v1/accounts/:account_id/captain/assistants")
|
||||
assistants.GET("/", handler.List)
|
||||
assistants.POST("/", handler.Create)
|
||||
assistants.GET("/tools", handler.Tools)
|
||||
assistants.GET("/:assistant_id", handler.Get)
|
||||
assistants.PUT("/:assistant_id", handler.Update)
|
||||
assistants.DELETE("/:assistant_id", handler.Delete)
|
||||
assistants.GET("/:assistant_id/inboxes", handler.ListInboxes)
|
||||
assistants.POST("/:assistant_id/inboxes", handler.AssociateInbox)
|
||||
assistants.DELETE("/:assistant_id/inboxes/:inbox_id", handler.DissociateInbox)
|
||||
return router, db
|
||||
}
|
||||
|
||||
func seedCaptainAssistantAccount(t *testing.T, db *gorm.DB, name string) *model.Account {
|
||||
t.Helper()
|
||||
account := &model.Account{Name: name, Locale: "en", Active: true}
|
||||
require.NoError(t, db.Create(account).Error)
|
||||
return account
|
||||
}
|
||||
|
||||
func captainAssistantJSONRequest(t *testing.T, router *gin.Engine, method, path string, body any) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
var reader *bytes.Reader
|
||||
if body == nil {
|
||||
reader = bytes.NewReader(nil)
|
||||
} else {
|
||||
payload, err := json.Marshal(body)
|
||||
require.NoError(t, err)
|
||||
reader = bytes.NewReader(payload)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(method, path, reader)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
router.ServeHTTP(w, req)
|
||||
return w
|
||||
}
|
||||
|
||||
func TestCaptainAssistantHandler_CRUDUsesChatwootPayloadShape(t *testing.T) {
|
||||
router, db := setupCaptainAssistantHandlerTest(t)
|
||||
account := seedCaptainAssistantAccount(t, db, "Captain Org")
|
||||
basePath := "/api/v1/accounts/" + strconv.FormatUint(uint64(account.ID), 10) + "/captain/assistants"
|
||||
|
||||
createBody := map[string]any{
|
||||
"assistant": map[string]any{
|
||||
"name": "Fin",
|
||||
"description": "Support copilot",
|
||||
"config": map[string]any{
|
||||
"product_name": "GoChat",
|
||||
"temperature": 0.2,
|
||||
},
|
||||
"guardrails": []string{"never ask for passwords"},
|
||||
"response_guidelines": []string{"be concise"},
|
||||
},
|
||||
}
|
||||
w := captainAssistantJSONRequest(t, router, http.MethodPost, basePath+"/", createBody)
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
|
||||
var created map[string]any
|
||||
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &created))
|
||||
assert.NotContains(t, created, "success")
|
||||
assert.NotContains(t, created, "data")
|
||||
assert.Equal(t, float64(account.ID), created["account_id"])
|
||||
assert.Equal(t, "Fin", created["name"])
|
||||
assert.Equal(t, "Support copilot", created["description"])
|
||||
assert.Equal(t, "GoChat", created["config"].(map[string]any)["product_name"])
|
||||
assistantID := uint(created["id"].(float64))
|
||||
|
||||
w = captainAssistantJSONRequest(t, router, http.MethodGet, basePath+"/", nil)
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
var listResp map[string]any
|
||||
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &listResp))
|
||||
assert.Len(t, listResp["payload"], 1)
|
||||
assert.Equal(t, float64(1), listResp["meta"].(map[string]any)["total_count"])
|
||||
assert.Equal(t, float64(1), listResp["meta"].(map[string]any)["page"])
|
||||
|
||||
updateBody := map[string]any{"assistant": map[string]any{"name": "Fin Prime", "description": "Updated"}}
|
||||
w = captainAssistantJSONRequest(t, router, http.MethodPut, fmt.Sprintf("%s/%d", basePath, assistantID), updateBody)
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
var updated map[string]any
|
||||
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &updated))
|
||||
assert.Equal(t, "Fin Prime", updated["name"])
|
||||
assert.Equal(t, "Updated", updated["description"])
|
||||
|
||||
w = captainAssistantJSONRequest(t, router, http.MethodGet, fmt.Sprintf("%s/%d", basePath, assistantID), nil)
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
|
||||
w = captainAssistantJSONRequest(t, router, http.MethodDelete, fmt.Sprintf("%s/%d", basePath, assistantID), nil)
|
||||
assert.Equal(t, http.StatusNoContent, w.Code)
|
||||
}
|
||||
|
||||
func TestCaptainAssistantHandler_AccountScopedShowAndInboxBinding(t *testing.T) {
|
||||
router, db := setupCaptainAssistantHandlerTest(t)
|
||||
account := seedCaptainAssistantAccount(t, db, "Account One")
|
||||
otherAccount := seedCaptainAssistantAccount(t, db, "Account Two")
|
||||
assistant := &model.CaptainAssistant{AccountID: account.ID, Name: "Fin", Description: "Support", Config: json.RawMessage(`{}`), Status: model.AssistantStatusActive}
|
||||
require.NoError(t, db.Create(assistant).Error)
|
||||
inbox := &model.Inbox{AccountID: account.ID, Name: "Primary", ChannelType: "web_widget"}
|
||||
require.NoError(t, db.Create(inbox).Error)
|
||||
otherInbox := &model.Inbox{AccountID: otherAccount.ID, Name: "Other", ChannelType: "web_widget"}
|
||||
require.NoError(t, db.Create(otherInbox).Error)
|
||||
|
||||
basePath := "/api/v1/accounts/" + strconv.FormatUint(uint64(account.ID), 10) + "/captain/assistants"
|
||||
otherBasePath := "/api/v1/accounts/" + strconv.FormatUint(uint64(otherAccount.ID), 10) + "/captain/assistants"
|
||||
|
||||
w := captainAssistantJSONRequest(t, router, http.MethodGet, fmt.Sprintf("%s/%d", otherBasePath, assistant.ID), nil)
|
||||
assert.Equal(t, http.StatusNotFound, w.Code)
|
||||
|
||||
w = captainAssistantJSONRequest(t, router, http.MethodGet, basePath+"/tools", nil)
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
var tools []map[string]any
|
||||
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &tools))
|
||||
assert.Len(t, tools, 7)
|
||||
assert.Equal(t, "add_contact_note", tools[0]["id"])
|
||||
|
||||
bindBody := map[string]any{"inbox": map[string]any{"inbox_id": inbox.ID}}
|
||||
w = captainAssistantJSONRequest(t, router, http.MethodPost, fmt.Sprintf("%s/%d/inboxes", basePath, assistant.ID), bindBody)
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
var bound map[string]any
|
||||
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &bound))
|
||||
assert.Equal(t, float64(inbox.ID), bound["id"])
|
||||
assert.NotContains(t, bound, "success")
|
||||
|
||||
w = captainAssistantJSONRequest(t, router, http.MethodGet, fmt.Sprintf("%s/%d/inboxes", basePath, assistant.ID), nil)
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
var inboxList map[string]any
|
||||
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &inboxList))
|
||||
assert.Len(t, inboxList["payload"], 1)
|
||||
|
||||
wrongBindBody := map[string]any{"inbox": map[string]any{"inbox_id": otherInbox.ID}}
|
||||
w = captainAssistantJSONRequest(t, router, http.MethodPost, fmt.Sprintf("%s/%d/inboxes", basePath, assistant.ID), wrongBindBody)
|
||||
assert.Equal(t, http.StatusNotFound, w.Code)
|
||||
|
||||
w = captainAssistantJSONRequest(t, router, http.MethodDelete, fmt.Sprintf("%s/%d/inboxes/%d", otherBasePath, assistant.ID, inbox.ID), nil)
|
||||
assert.Equal(t, http.StatusNotFound, w.Code)
|
||||
|
||||
w = captainAssistantJSONRequest(t, router, http.MethodDelete, fmt.Sprintf("%s/%d/inboxes/%d", basePath, assistant.ID, inbox.ID), nil)
|
||||
assert.Equal(t, http.StatusNoContent, w.Code)
|
||||
}
|
||||
Reference in New Issue
Block a user