package v1 import ( "errors" "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/response" ) // CaptainCustomToolHandler handles CaptainCustomTool REST API endpoints. // Reference: Chatwoot enterprise/app/controllers/api/v1/captain/custom_tools_controller.rb type CaptainCustomToolHandler struct { svc *service.CaptainCustomToolService } // NewCaptainCustomToolHandler creates a new CaptainCustomToolHandler. func NewCaptainCustomToolHandler(svc *service.CaptainCustomToolService) *CaptainCustomToolHandler { return &CaptainCustomToolHandler{svc: svc} } // Create creates a new custom tool. // POST /api/v1/accounts/:account_id/captain_custom_tools func (h *CaptainCustomToolHandler) Create(c *gin.Context) { accountID := parseAccountIDParam(c) if accountID == 0 { response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id") return } if !h.ensureCustomToolsEnabled(c, accountID) { return } var req service.CreateCustomToolRequest if err := bindNestedJSONPayload(c, "custom_tool", &req); err != nil { response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, err.Error()) return } tool, err := h.svc.Create(c.Request.Context(), accountID, &req) if err != nil { applogger.L().Errorf("Create captain custom tool: %v", err) if errors.Is(err, service.ErrCaptainCustomToolLimitExceeded) { c.JSON(http.StatusUnprocessableEntity, gin.H{"error": service.ErrCaptainCustomToolLimitExceeded.Error()}) return } response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "failed to create custom tool") return } 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 } if !h.ensureCustomToolsEnabled(c, accountID) { 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.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 } 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 } if !h.ensureCustomToolsEnabled(c, accountID) { return } id, err := parseUintAnyParam(c, "tool_id", "id") if err != nil { response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid id") return } var req service.UpdateCustomToolRequest if err := bindNestedJSONPayload(c, "custom_tool", &req); err != nil { response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, err.Error()) return } 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 } 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 } if !h.ensureCustomToolsEnabled(c, accountID) { 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.DeleteByAccount(c.Request.Context(), accountID, id); err != nil { applogger.L().Errorf("Delete captain custom tool: %v", err) response.AbortWithStatusError(c, captainAssistantErrorStatus(err), response.ErrInternal, "failed to delete custom tool") return } response.NoContent(c) } // List retrieves custom tools for an account. // GET /api/v1/accounts/:account_id/captain_custom_tools func (h *CaptainCustomToolHandler) List(c *gin.Context) { accountID := parseAccountIDParam(c) if accountID == 0 { response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id") return } if !h.ensureCustomToolsEnabled(c, accountID) { return } 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 } 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. // POST /api/v1/accounts/:account_id/captain_custom_tools/:id/execute func (h *CaptainCustomToolHandler) ExecuteTool(c *gin.Context) { id, err := parseUintAnyParam(c, "tool_id", "id") if err != nil { response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid id") return } var params map[string]interface{} if err := c.ShouldBindJSON(¶ms); err != nil { // Empty body is acceptable (use nil params) params = nil } result, err := h.svc.ExecuteTool(c.Request.Context(), id, params) if err != nil { applogger.L().Errorf("ExecuteTool: %v", err) response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "failed to execute tool") return } response.OK(c, result) } // TestTool tests a custom tool with given parameters. // POST /api/v1/accounts/:account_id/captain/custom_tools/test func (h *CaptainCustomToolHandler) TestTool(c *gin.Context) { accountID := parseAccountIDParam(c) if accountID == 0 { response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id") return } if !h.ensureCustomToolsEnabled(c, accountID) { return } var req service.TestToolRequest if err := bindNestedJSONPayload(c, "custom_tool", &req); err != nil { response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, err.Error()) return } result, err := h.svc.TestTool(c.Request.Context(), accountID, &req) if err != nil { applogger.L().Errorf("TestTool: %v", err) c.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()}) return } c.JSON(http.StatusOK, result) } func (h *CaptainCustomToolHandler) ensureCustomToolsEnabled(c *gin.Context, accountID uint) bool { if h.svc.CustomToolsEnabled(c.Request.Context(), accountID) { return true } c.JSON(http.StatusForbidden, gin.H{"error": "Custom tools are not enabled for this account"}) return false } 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(), } }