feat(captain): align scenario and tool payloads

This commit is contained in:
2026-06-05 12:05:53 +08:00
parent 41a1b0c47e
commit fc2cb12e63
13 changed files with 588 additions and 107 deletions
@@ -347,11 +347,15 @@ func (h *CaptainAssistantHandler) GenerateResponse(c *gin.Context) {
}
func bindCaptainAssistantPayload(c *gin.Context, dst any) error {
return bindNestedJSONPayload(c, "assistant", dst)
}
func bindNestedJSONPayload(c *gin.Context, key string, dst any) error {
var raw map[string]json.RawMessage
if err := c.ShouldBindJSON(&raw); err != nil {
return err
}
if nested, ok := raw["assistant"]; ok {
if nested, ok := raw[key]; ok {
return json.Unmarshal(nested, dst)
}
body, err := json.Marshal(raw)
@@ -115,12 +115,11 @@ func (s *CaptainCustomToolCRUDTestSuite) createToolAndGetID(title, slug, endpoin
"endpoint_url": endpointURL,
}
w := s.makeRequest("POST", s.accountPath()+"/captain/custom_tools/", body)
s.Require().Equal(http.StatusCreated, w.Code)
s.Require().Equal(http.StatusOK, w.Code)
var resp map[string]interface{}
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &resp))
data := resp["data"].(map[string]interface{})
return strconv.FormatFloat(data["id"].(float64), 'f', -1, 64)
return strconv.FormatFloat(resp["id"].(float64), 'f', -1, 64)
}
// ========== 创建自定义工具测试 ==========
@@ -135,18 +134,16 @@ func (s *CaptainCustomToolCRUDTestSuite) TestCreate_成功创建自定义工具(
w := s.makeRequest("POST", s.accountPath()+"/captain/custom_tools/", body)
assert.Equal(s.T(), http.StatusCreated, w.Code)
assert.Equal(s.T(), http.StatusOK, w.Code)
var resp map[string]interface{}
json.Unmarshal(w.Body.Bytes(), &resp)
assert.True(s.T(), resp["success"].(bool))
data := resp["data"].(map[string]interface{})
assert.Equal(s.T(), "测试工具", data["title"])
assert.Equal(s.T(), "test-tool", data["slug"])
assert.Equal(s.T(), "https://example.com/api", data["endpoint_url"])
assert.Equal(s.T(), "POST", data["http_method"])
assert.Equal(s.T(), true, data["enabled"]) // default true
assert.NotContains(s.T(), resp, "success")
assert.Equal(s.T(), "测试工具", resp["title"])
assert.Equal(s.T(), "test-tool", resp["slug"])
assert.Equal(s.T(), "https://example.com/api", resp["endpoint_url"])
assert.Equal(s.T(), "POST", resp["http_method"])
assert.Equal(s.T(), true, resp["enabled"]) // default true
}
func (s *CaptainCustomToolCRUDTestSuite) TestCreate_默认GET方法() {
@@ -158,12 +155,11 @@ func (s *CaptainCustomToolCRUDTestSuite) TestCreate_默认GET方法() {
w := s.makeRequest("POST", s.accountPath()+"/captain/custom_tools/", body)
assert.Equal(s.T(), http.StatusCreated, w.Code)
assert.Equal(s.T(), http.StatusOK, w.Code)
var resp map[string]interface{}
json.Unmarshal(w.Body.Bytes(), &resp)
data := resp["data"].(map[string]interface{})
assert.Equal(s.T(), "GET", data["http_method"]) // default HTTP method
assert.Equal(s.T(), "GET", resp["http_method"]) // default HTTP method
}
func (s *CaptainCustomToolCRUDTestSuite) TestCreate_无效JSON返回400() {
@@ -195,11 +191,9 @@ func (s *CaptainCustomToolCRUDTestSuite) TestGet_成功获取自定义工具() {
var getResp map[string]interface{}
json.Unmarshal(w.Body.Bytes(), &getResp)
assert.True(s.T(), getResp["success"].(bool))
data := getResp["data"].(map[string]interface{})
assert.Equal(s.T(), "获取测试工具", data["title"])
assert.Equal(s.T(), "get-test-tool", data["slug"])
assert.NotContains(s.T(), getResp, "success")
assert.Equal(s.T(), "获取测试工具", getResp["title"])
assert.Equal(s.T(), "get-test-tool", getResp["slug"])
}
func (s *CaptainCustomToolCRUDTestSuite) TestGet_不存在的ID返回404() {
@@ -218,7 +212,7 @@ func (s *CaptainCustomToolCRUDTestSuite) TestList_成功列出自定义工具()
"endpoint_url": "https://example.com/list" + strconv.Itoa(i),
}
w := s.makeRequest("POST", s.accountPath()+"/captain/custom_tools/", body)
s.Require().Equal(http.StatusCreated, w.Code)
s.Require().Equal(http.StatusOK, w.Code)
}
// 列出工具 — 使用 accountRouter
@@ -227,14 +221,12 @@ func (s *CaptainCustomToolCRUDTestSuite) TestList_成功列出自定义工具()
var listResp map[string]interface{}
json.Unmarshal(w.Body.Bytes(), &listResp)
assert.True(s.T(), listResp["success"].(bool))
data := listResp["data"].([]interface{})
assert.NotContains(s.T(), listResp, "success")
data := listResp["payload"].([]interface{})
assert.Equal(s.T(), 3, len(data))
meta := listResp["meta"].(map[string]interface{})
assert.Equal(s.T(), float64(1), meta["page"])
assert.Equal(s.T(), float64(25), meta["per_page"]) // DefaultPerPage = 25
assert.Equal(s.T(), float64(3), meta["total_count"])
}
@@ -257,11 +249,9 @@ func (s *CaptainCustomToolCRUDTestSuite) TestUpdate_成功更新自定义工具(
var updateResp map[string]interface{}
json.Unmarshal(w.Body.Bytes(), &updateResp)
assert.True(s.T(), updateResp["success"].(bool))
data := updateResp["data"].(map[string]interface{})
assert.Equal(s.T(), "更新后标题", data["title"])
assert.Equal(s.T(), "https://example.com/after", data["endpoint_url"])
assert.NotContains(s.T(), updateResp, "success")
assert.Equal(s.T(), "更新后标题", updateResp["title"])
assert.Equal(s.T(), "https://example.com/after", updateResp["endpoint_url"])
}
func (s *CaptainCustomToolCRUDTestSuite) TestUpdate_更新enabled字段() {
@@ -276,8 +266,7 @@ func (s *CaptainCustomToolCRUDTestSuite) TestUpdate_更新enabled字段() {
var updateResp map[string]interface{}
json.Unmarshal(w.Body.Bytes(), &updateResp)
data := updateResp["data"].(map[string]interface{})
assert.Equal(s.T(), false, data["enabled"])
assert.Equal(s.T(), false, updateResp["enabled"])
}
func (s *CaptainCustomToolCRUDTestSuite) TestUpdate_不存在的ID返回500() {
@@ -307,8 +296,7 @@ func (s *CaptainCustomToolCRUDTestSuite) TestDelete_成功删除自定义工具(
func (s *CaptainCustomToolCRUDTestSuite) TestDelete_不存在的ID() {
w := s.makeRequest("DELETE", s.accountPath()+"/captain/custom_tools/999999", nil)
// Delete of non-existent tool: handler returns 500 or 204 depending on service behavior
assert.True(s.T(), w.Code == http.StatusUnprocessableEntity || w.Code == http.StatusNoContent,
"expected 500 or 204 for non-existent tool delete, got %d", w.Code)
assert.Equal(s.T(), http.StatusNotFound, w.Code)
}
func TestCaptainCustomToolCRUDSuite(t *testing.T) {
@@ -4,9 +4,9 @@ import (
"net/http"
"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"
)
@@ -31,7 +31,7 @@ func (h *CaptainCustomToolHandler) Create(c *gin.Context) {
}
var req service.CreateCustomToolRequest
if err := c.ShouldBindJSON(&req); err != nil {
if err := bindNestedJSONPayload(c, "custom_tool", &req); err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, err.Error())
return
}
@@ -43,31 +43,41 @@ func (h *CaptainCustomToolHandler) Create(c *gin.Context) {
return
}
response.Created(c, tool)
c.JSON(http.StatusOK, captainCustomToolPayload(tool))
}
// Get retrieves a custom tool by ID.
// GET /api/v1/accounts/:account_id/captain_custom_tools/:id
func (h *CaptainCustomToolHandler) Get(c *gin.Context) {
accountID := parseAccountIDParam(c)
if accountID == 0 {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
return
}
id, err := parseUintAnyParam(c, "tool_id", "id")
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid id")
return
}
tool, err := h.svc.Get(c.Request.Context(), id)
tool, err := h.svc.GetByAccount(c.Request.Context(), accountID, id)
if err != nil {
applogger.L().Errorf("Get captain custom tool: %v", err)
response.AbortWithStatusError(c, http.StatusNotFound, response.ErrNotFound, "custom tool not found")
return
}
response.OK(c, tool)
c.JSON(http.StatusOK, captainCustomToolPayload(tool))
}
// Update updates an existing custom tool.
// PUT /api/v1/accounts/:account_id/captain_custom_tools/:id
func (h *CaptainCustomToolHandler) Update(c *gin.Context) {
accountID := parseAccountIDParam(c)
if accountID == 0 {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
return
}
id, err := parseUintAnyParam(c, "tool_id", "id")
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid id")
@@ -75,33 +85,38 @@ func (h *CaptainCustomToolHandler) Update(c *gin.Context) {
}
var req service.UpdateCustomToolRequest
if err := c.ShouldBindJSON(&req); err != nil {
if err := bindNestedJSONPayload(c, "custom_tool", &req); err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, err.Error())
return
}
tool, err := h.svc.Update(c.Request.Context(), id, &req)
tool, err := h.svc.UpdateByAccount(c.Request.Context(), accountID, id, &req)
if err != nil {
applogger.L().Errorf("Update captain custom tool: %v", err)
handleServiceError(c, err)
return
}
response.OK(c, tool)
c.JSON(http.StatusOK, captainCustomToolPayload(tool))
}
// Delete deletes a custom tool.
// DELETE /api/v1/accounts/:account_id/captain_custom_tools/:id
func (h *CaptainCustomToolHandler) Delete(c *gin.Context) {
accountID := parseAccountIDParam(c)
if accountID == 0 {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
return
}
id, err := parseUintAnyParam(c, "tool_id", "id")
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid id")
return
}
if err := h.svc.Delete(c.Request.Context(), id); err != nil {
if err := h.svc.DeleteByAccount(c.Request.Context(), accountID, id); err != nil {
applogger.L().Errorf("Delete captain custom tool: %v", err)
response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "failed to delete custom tool")
response.AbortWithStatusError(c, captainAssistantErrorStatus(err), response.ErrInternal, "failed to delete custom tool")
return
}
@@ -117,15 +132,18 @@ func (h *CaptainCustomToolHandler) List(c *gin.Context) {
return
}
p := pagination.Parse(c)
tools, count, err := h.svc.List(c.Request.Context(), accountID, p.Offset, p.PerPage)
tools, count, err := h.svc.List(c.Request.Context(), accountID, 0, 1000)
if err != nil {
applogger.L().Errorf("List captain custom tools: %v", err)
response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "failed to list custom tools")
return
}
response.OKWithMeta(c, tools, p.Page, p.PerPage, count)
payload := make([]gin.H, 0, len(tools))
for i := range tools {
payload = append(payload, captainCustomToolPayload(&tools[i]))
}
c.JSON(http.StatusOK, gin.H{"payload": payload, "meta": gin.H{"total_count": count, "page": 1}})
}
// ExecuteTool calls the external HTTP endpoint of a custom tool.
@@ -163,7 +181,7 @@ func (h *CaptainCustomToolHandler) TestTool(c *gin.Context) {
}
var req service.TestToolRequest
if err := c.ShouldBindJSON(&req); err != nil {
if err := bindNestedJSONPayload(c, "custom_tool", &req); err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, err.Error())
return
}
@@ -175,5 +193,25 @@ func (h *CaptainCustomToolHandler) TestTool(c *gin.Context) {
return
}
response.OK(c, result)
c.JSON(http.StatusOK, result)
}
func captainCustomToolPayload(tool *model.CaptainCustomTool) gin.H {
return gin.H{
"id": tool.ID,
"slug": tool.Slug,
"title": tool.Title,
"description": tool.Description,
"endpoint_url": tool.EndpointURL,
"http_method": tool.HTTPMethod,
"request_template": tool.RequestTemplate,
"response_template": tool.ResponseTemplate,
"auth_type": tool.AuthType,
"auth_config": rawJSONValue(tool.AuthConfig),
"param_schema": rawJSONValue(tool.ParamSchema),
"enabled": tool.Enabled,
"account_id": tool.AccountID,
"created_at": tool.CreatedAt.Unix(),
"updated_at": tool.UpdatedAt.Unix(),
}
}
@@ -113,9 +113,7 @@ func (s *CaptainCustomToolTestHandlerTestSuite) TestTestTool_成功测试工具(
if w.Code == http.StatusOK {
var resp map[string]interface{}
json.Unmarshal(w.Body.Bytes(), &resp)
assert.True(s.T(), resp["success"].(bool))
data := resp["data"].(map[string]interface{})
assert.Contains(s.T(), data, "success")
assert.Contains(s.T(), resp, "success")
} else {
// 即使外部请求失败,也应该返回 InternalServerError 格式
assert.Equal(s.T(), http.StatusUnprocessableEntity, w.Code)
@@ -199,7 +197,7 @@ func (s *CaptainCustomToolTestHandlerTestSuite) TestTestTool_带POST方法和参
if w.Code == http.StatusOK {
var resp map[string]interface{}
json.Unmarshal(w.Body.Bytes(), &resp)
assert.True(s.T(), resp["success"].(bool))
assert.Contains(s.T(), resp, "success")
}
}
@@ -0,0 +1,181 @@
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 setupCaptainResourceParityTest(t *testing.T) (*gin.Engine, *gorm.DB, *model.Account, *model.Account, *model.CaptainAssistant) {
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.CaptainAssistant{},
&model.CaptainScenario{},
&model.CaptainCustomTool{},
))
t.Cleanup(func() {
sqlDB, _ := db.DB()
sqlDB.Close()
})
account := &model.Account{Name: "Captain Account", Locale: "en", Active: true}
otherAccount := &model.Account{Name: "Other Account", Locale: "en", Active: true}
require.NoError(t, db.Create(account).Error)
require.NoError(t, db.Create(otherAccount).Error)
assistant := &model.CaptainAssistant{AccountID: account.ID, Name: "Fin", Description: "Support", Config: json.RawMessage(`{}`), Status: model.AssistantStatusActive}
require.NoError(t, db.Create(assistant).Error)
assistantRepo := repository.NewCaptainAssistantRepo(db)
scenarioRepo := repository.NewCaptainScenarioRepo(db)
scenarioSvc := service.NewCaptainScenarioService(scenarioRepo, assistantRepo)
scenarioHandler := NewCaptainScenarioHandler(scenarioSvc)
toolRepo := repository.NewCaptainCustomToolRepo(db)
toolSvc := service.NewCaptainCustomToolService(toolRepo)
toolHandler := NewCaptainCustomToolHandler(toolSvc)
router := gin.New()
accountGroup := router.Group("/api/v1/accounts/:account_id/captain")
assistantScenarios := accountGroup.Group("/assistants/:assistant_id/scenarios")
assistantScenarios.GET("/", scenarioHandler.List)
assistantScenarios.POST("/", scenarioHandler.Create)
assistantScenarios.GET("/:scenario_id", scenarioHandler.Get)
assistantScenarios.PUT("/:scenario_id", scenarioHandler.Update)
assistantScenarios.DELETE("/:scenario_id", scenarioHandler.Delete)
customTools := accountGroup.Group("/custom_tools")
customTools.GET("/", toolHandler.List)
customTools.POST("/", toolHandler.Create)
customTools.GET("/:tool_id", toolHandler.Get)
customTools.PUT("/:tool_id", toolHandler.Update)
customTools.DELETE("/:tool_id", toolHandler.Delete)
return router, db, account, otherAccount, assistant
}
func captainResourceJSONRequest(t *testing.T, router *gin.Engine, method, path string, body any) *httptest.ResponseRecorder {
t.Helper()
var payload []byte
if body != nil {
data, err := json.Marshal(body)
require.NoError(t, err)
payload = data
}
w := httptest.NewRecorder()
req := httptest.NewRequest(method, path, bytes.NewReader(payload))
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
router.ServeHTTP(w, req)
return w
}
func TestCaptainScenarioHandler_ChatwootScenarioPayloadsAndScope(t *testing.T) {
router, db, account, otherAccount, assistant := setupCaptainResourceParityTest(t)
basePath := "/api/v1/accounts/" + strconv.FormatUint(uint64(account.ID), 10) + "/captain/assistants/" + strconv.FormatUint(uint64(assistant.ID), 10) + "/scenarios"
otherBasePath := "/api/v1/accounts/" + strconv.FormatUint(uint64(otherAccount.ID), 10) + "/captain/assistants/" + strconv.FormatUint(uint64(assistant.ID), 10) + "/scenarios"
body := map[string]any{"scenario": map[string]any{
"title": "Escalate billing",
"description": "Billing handoff",
"instruction": "Ask for invoice ID",
"tools": []string{"handoff"},
}}
w := captainResourceJSONRequest(t, router, http.MethodPost, basePath+"/", body)
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.Equal(t, "Escalate billing", created["title"])
assert.Equal(t, float64(account.ID), created["account_id"])
assert.Equal(t, float64(assistant.ID), created["assistant_id"])
assert.Equal(t, "Fin", created["assistant"].(map[string]any)["name"])
scenarioID := uint(created["id"].(float64))
disabled := &model.CaptainScenario{AccountID: account.ID, AssistantID: assistant.ID, Title: "Disabled", Enabled: false}
require.NoError(t, db.Create(disabled).Error)
require.NoError(t, db.Model(disabled).Update("enabled", false).Error)
w = captainResourceJSONRequest(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"])
w = captainResourceJSONRequest(t, router, http.MethodGet, fmt.Sprintf("%s/%d", otherBasePath, scenarioID), nil)
assert.Equal(t, http.StatusNotFound, w.Code)
updateBody := map[string]any{"scenario": map[string]any{"enabled": false, "instruction": "Updated"}}
w = captainResourceJSONRequest(t, router, http.MethodPut, fmt.Sprintf("%s/%d", basePath, scenarioID), 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, false, updated["enabled"])
assert.Equal(t, "Updated", updated["instruction"])
w = captainResourceJSONRequest(t, router, http.MethodDelete, fmt.Sprintf("%s/%d", basePath, scenarioID), nil)
assert.Equal(t, http.StatusNoContent, w.Code)
}
func TestCaptainCustomToolHandler_ChatwootToolPayloadsAndScope(t *testing.T) {
router, _, account, otherAccount, _ := setupCaptainResourceParityTest(t)
basePath := "/api/v1/accounts/" + strconv.FormatUint(uint64(account.ID), 10) + "/captain/custom_tools"
otherBasePath := "/api/v1/accounts/" + strconv.FormatUint(uint64(otherAccount.ID), 10) + "/captain/custom_tools"
body := map[string]any{"custom_tool": map[string]any{
"title": "Lookup Order",
"description": "Fetch order status",
"endpoint_url": "https://example.com/orders",
"http_method": "POST",
"auth_type": "none",
"param_schema": []map[string]any{{"name": "order_id", "type": "string", "required": true}},
"request_template": "{\"id\":\"{{.order_id}}\"}",
}}
w := captainResourceJSONRequest(t, router, http.MethodPost, basePath+"/", body)
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.Equal(t, "lookup-order", created["slug"])
assert.Equal(t, "POST", created["http_method"])
toolID := uint(created["id"].(float64))
w = captainResourceJSONRequest(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)["page"])
w = captainResourceJSONRequest(t, router, http.MethodGet, fmt.Sprintf("%s/%d", otherBasePath, toolID), nil)
assert.Equal(t, http.StatusNotFound, w.Code)
updateBody := map[string]any{"custom_tool": map[string]any{"enabled": false, "title": "Lookup Order V2"}}
w = captainResourceJSONRequest(t, router, http.MethodPut, fmt.Sprintf("%s/%d", basePath, toolID), 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, false, updated["enabled"])
assert.Equal(t, "Lookup Order V2", updated["title"])
w = captainResourceJSONRequest(t, router, http.MethodDelete, fmt.Sprintf("%s/%d", basePath, toolID), nil)
assert.Equal(t, http.StatusNoContent, w.Code)
}
@@ -2,12 +2,11 @@ package v1
import (
"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"
)
@@ -25,89 +24,119 @@ func NewCaptainScenarioHandler(svc *service.CaptainScenarioService) *CaptainScen
// Create creates a new scenario under an assistant.
// POST /api/v1/accounts/:account_id/captain_assistants/:assistant_id/scenarios
func (h *CaptainScenarioHandler) 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
}
assistantID, err := strconv.ParseUint(c.Param("assistant_id"), 10, 64)
assistantID, err := parseUintParam(c, "assistant_id")
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid assistant_id")
return
}
var req service.CreateScenarioRequest
if err := c.ShouldBindJSON(&req); err != nil {
if err := bindNestedJSONPayload(c, "scenario", &req); err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, err.Error())
return
}
scenario, err := h.svc.Create(c.Request.Context(), uint(accountID), uint(assistantID), &req)
scenario, err := h.svc.Create(c.Request.Context(), accountID, assistantID, &req)
if err != nil {
applogger.L().Errorf("Create captain scenario: %v", err)
response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "failed to create scenario")
response.AbortWithStatusError(c, captainAssistantErrorStatus(err), response.ErrInternal, "failed to create scenario")
return
}
response.Created(c, scenario)
c.JSON(http.StatusOK, captainScenarioPayload(scenario))
}
// Get retrieves a scenario by ID.
// GET /api/v1/accounts/:account_id/captain_assistants/:assistant_id/scenarios/:id
func (h *CaptainScenarioHandler) 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
}
assistantID, err := parseUintParam(c, "assistant_id")
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid assistant_id")
return
}
id, err := parseUintAnyParam(c, "scenario_id", "id")
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid id")
return
}
scenario, err := h.svc.GetByID(c.Request.Context(), uint(id))
scenario, err := h.svc.Get(c.Request.Context(), accountID, assistantID, id)
if err != nil {
applogger.L().Errorf("Get captain scenario: %v", err)
response.AbortWithStatusError(c, http.StatusNotFound, response.ErrNotFound, "scenario not found")
return
}
response.OK(c, scenario)
c.JSON(http.StatusOK, captainScenarioPayload(scenario))
}
// Update updates an existing scenario.
// PUT /api/v1/accounts/:account_id/captain_assistants/:assistant_id/scenarios/:id
func (h *CaptainScenarioHandler) 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
}
assistantID, err := parseUintParam(c, "assistant_id")
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid assistant_id")
return
}
id, err := parseUintAnyParam(c, "scenario_id", "id")
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid id")
return
}
var req service.UpdateScenarioRequest
if err := c.ShouldBindJSON(&req); err != nil {
if err := bindNestedJSONPayload(c, "scenario", &req); err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, err.Error())
return
}
scenario, err := h.svc.Update(c.Request.Context(), uint(id), &req)
scenario, err := h.svc.UpdateScoped(c.Request.Context(), accountID, assistantID, id, &req)
if err != nil {
applogger.L().Errorf("Update captain scenario: %v", err)
response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "failed to update scenario")
response.AbortWithStatusError(c, captainAssistantErrorStatus(err), response.ErrInternal, "failed to update scenario")
return
}
response.OK(c, scenario)
c.JSON(http.StatusOK, captainScenarioPayload(scenario))
}
// Delete deletes a scenario.
// DELETE /api/v1/accounts/:account_id/captain_assistants/:assistant_id/scenarios/:id
func (h *CaptainScenarioHandler) 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
}
assistantID, err := parseUintParam(c, "assistant_id")
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid assistant_id")
return
}
id, err := parseUintAnyParam(c, "scenario_id", "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.DeleteScoped(c.Request.Context(), accountID, assistantID, id); err != nil {
applogger.L().Errorf("Delete captain scenario: %v", err)
response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "failed to delete scenario")
response.AbortWithStatusError(c, captainAssistantErrorStatus(err), response.ErrInternal, "failed to delete scenario")
return
}
@@ -117,19 +146,46 @@ func (h *CaptainScenarioHandler) Delete(c *gin.Context) {
// List retrieves scenarios for an assistant.
// GET /api/v1/accounts/:account_id/captain_assistants/:assistant_id/scenarios
func (h *CaptainScenarioHandler) List(c *gin.Context) {
assistantID, err := strconv.ParseUint(c.Param("assistant_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
}
p := pagination.Parse(c)
scenarios, count, err := h.svc.ListByAssistant(c.Request.Context(), uint(assistantID), p.Offset, p.PerPage)
scenarios, count, err := h.svc.ListByAccountAssistant(c.Request.Context(), accountID, assistantID)
if err != nil {
applogger.L().Errorf("List captain scenarios: %v", err)
response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "failed to list scenarios")
response.AbortWithStatusError(c, captainAssistantErrorStatus(err), response.ErrInternal, "failed to list scenarios")
return
}
response.OKWithMeta(c, scenarios, p.Page, p.PerPage, count)
}
payload := make([]gin.H, 0, len(scenarios))
for i := range scenarios {
payload = append(payload, captainScenarioPayload(&scenarios[i]))
}
c.JSON(http.StatusOK, gin.H{"payload": payload, "meta": gin.H{"total_count": count, "page": 1}})
}
func captainScenarioPayload(scenario *model.CaptainScenario) gin.H {
payload := gin.H{
"id": scenario.ID,
"title": scenario.Title,
"description": scenario.Description,
"instruction": scenario.Instruction,
"tools": rawJSONValue(scenario.Tools),
"enabled": scenario.Enabled,
"assistant_id": scenario.AssistantID,
"account_id": scenario.AccountID,
"created_at": scenario.CreatedAt,
"updated_at": scenario.UpdatedAt,
}
if scenario.Assistant.ID != 0 {
payload["assistant"] = gin.H{"id": scenario.Assistant.ID, "name": scenario.Assistant.Name}
}
return payload
}