Files
gochat/internal/handler/api/v1/captain_custom_tool_handler.go
T

298 lines
9.3 KiB
Go

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
}
if !h.ensureCustomToolAdmin(c) {
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
}
if renderCaptainCustomToolValidationError(c, err) {
return
}
response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "failed to create custom tool")
return
}
c.JSON(http.StatusOK, captainCustomToolPayload(c, 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(c, 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
}
if !h.ensureCustomToolAdmin(c) {
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)
if renderCaptainCustomToolValidationError(c, err) {
return
}
handleServiceError(c, err)
return
}
c.JSON(http.StatusOK, captainCustomToolPayload(c, 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
}
if !h.ensureCustomToolAdmin(c) {
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(c, &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(&params); 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
}
if !h.ensureCustomToolAdmin(c) {
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 (h *CaptainCustomToolHandler) ensureCustomToolAdmin(c *gin.Context) bool {
if role, exists := c.Get("role"); exists {
if role == "administrator" || role == "super_admin" {
return true
}
c.JSON(http.StatusForbidden, gin.H{"error": "You are not authorized to do this action"})
return false
}
return true
}
func renderCaptainCustomToolValidationError(c *gin.Context, err error) bool {
var validationErr *service.CaptainCustomToolValidationError
if !errors.As(err, &validationErr) {
return false
}
c.JSON(http.StatusUnprocessableEntity, gin.H{
"message": validationErr.Message,
"attributes": validationErr.Attributes,
})
return true
}
func captainCustomToolPayload(c *gin.Context, tool *model.CaptainCustomTool) gin.H {
payload := 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,
"param_schema": rawJSONValue(tool.ParamSchema),
"enabled": tool.Enabled,
"account_id": tool.AccountID,
"created_at": tool.CreatedAt.Unix(),
"updated_at": tool.UpdatedAt.Unix(),
}
if captainCustomToolShowAuthConfig(c) {
payload["auth_config"] = rawJSONValue(tool.AuthConfig)
}
return payload
}
func captainCustomToolShowAuthConfig(c *gin.Context) bool {
role, exists := c.Get("role")
return exists && (role == "administrator" || role == "super_admin")
}