feat(canned-responses): align chatwoot payloads

This commit is contained in:
2026-06-06 13:36:44 +08:00
parent e8d08bb38e
commit 4e0113a394
9 changed files with 422 additions and 72 deletions
@@ -1,7 +1,9 @@
package v1
import (
"encoding/json"
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/gochat/gochat/internal/canned"
@@ -15,11 +17,72 @@ type CannedResponseHandler struct {
svc *canned.CannedResponseService
}
type cannedResponseInput struct {
ShortCode *string `json:"short_code"`
Content *string `json:"content"`
}
type cannedResponsePayload struct {
ID uint `json:"id"`
AccountID uint `json:"account_id"`
ShortCode string `json:"short_code"`
Content string `json:"content"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// NewCannedResponseHandler creates a new CannedResponseHandler.
func NewCannedResponseHandler(svc *canned.CannedResponseService) *CannedResponseHandler {
return &CannedResponseHandler{svc: svc}
}
func bindCannedResponseInput(c *gin.Context) (cannedResponseInput, error) {
var body map[string]json.RawMessage
if err := c.ShouldBindJSON(&body); err != nil {
return cannedResponseInput{}, err
}
if raw, ok := body["canned_response"]; ok {
var wrapped cannedResponseInput
if err := json.Unmarshal(raw, &wrapped); err != nil {
return cannedResponseInput{}, err
}
return wrapped, nil
}
var input cannedResponseInput
if raw, ok := body["short_code"]; ok {
if err := json.Unmarshal(raw, &input.ShortCode); err != nil {
return cannedResponseInput{}, err
}
}
if raw, ok := body["content"]; ok {
if err := json.Unmarshal(raw, &input.Content); err != nil {
return cannedResponseInput{}, err
}
}
return input, nil
}
func serializeCannedResponse(cr canned.CannedResponse) cannedResponsePayload {
return cannedResponsePayload{
ID: cr.ID,
AccountID: cr.AccountID,
ShortCode: cr.ShortCode,
Content: cr.Content,
CreatedAt: cr.CreatedAt,
UpdatedAt: cr.UpdatedAt,
}
}
func serializeCannedResponses(responses []canned.CannedResponse) []cannedResponsePayload {
payload := make([]cannedResponsePayload, 0, len(responses))
for _, cr := range responses {
payload = append(payload, serializeCannedResponse(cr))
}
return payload
}
// Create creates a new canned response.
// POST /api/v1/accounts/:account_id/canned_responses
// Reference: Chatwoot CannedResponsesController#create
@@ -30,23 +93,20 @@ func (h *CannedResponseHandler) Create(c *gin.Context) {
return
}
// Chatwoot: params.require(:canned_response) → {"canned_response": {...}}
var wrapper struct {
CannedResponse struct {
ShortCode string `json:"short_code" binding:"required"`
Content string `json:"content" binding:"required"`
} `json:"canned_response"`
}
if err := c.ShouldBindJSON(&wrapper); err != nil {
req, err := bindCannedResponseInput(c)
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, err.Error())
return
}
req := wrapper.CannedResponse
if req.ShortCode == nil || *req.ShortCode == "" || req.Content == nil || *req.Content == "" {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, "short_code and content are required")
return
}
cr := &canned.CannedResponse{
AccountID: accountID,
ShortCode: req.ShortCode,
Content: req.Content,
ShortCode: *req.ShortCode,
Content: *req.Content,
}
if err := h.svc.Create(c.Request.Context(), cr); err != nil {
@@ -55,7 +115,7 @@ func (h *CannedResponseHandler) Create(c *gin.Context) {
return
}
response.Created(c, cr)
c.JSON(http.StatusOK, serializeCannedResponse(*cr))
}
// Get retrieves a canned response by ID.
@@ -67,14 +127,19 @@ func (h *CannedResponseHandler) Get(c *gin.Context) {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid id")
return
}
accountID, err := parseUintParam(c, "account_id")
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
return
}
cr, svcErr := h.svc.GetByID(c.Request.Context(), id)
cr, svcErr := h.svc.GetByAccountAndID(c.Request.Context(), accountID, id)
if svcErr != nil {
handleServiceError(c, svcErr)
return
}
response.OK(c, cr)
c.JSON(http.StatusOK, serializeCannedResponse(*cr))
}
// Update updates a canned response.
@@ -86,26 +151,24 @@ func (h *CannedResponseHandler) Update(c *gin.Context) {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid id")
return
}
// Chatwoot: params.require(:canned_response) → {"canned_response": {...}}
var wrapper struct {
CannedResponse struct {
ShortCode string `json:"short_code"`
Content string `json:"content"`
} `json:"canned_response"`
accountID, err := parseUintParam(c, "account_id")
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
return
}
if err := c.ShouldBindJSON(&wrapper); err != nil {
req, err := bindCannedResponseInput(c)
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, err.Error())
return
}
req := wrapper.CannedResponse
updates := map[string]interface{}{}
if req.ShortCode != "" {
updates["short_code"] = req.ShortCode
if req.ShortCode != nil {
updates["short_code"] = *req.ShortCode
}
if req.Content != "" {
updates["content"] = req.Content
if req.Content != nil {
updates["content"] = *req.Content
}
if len(updates) == 0 {
@@ -113,20 +176,19 @@ func (h *CannedResponseHandler) Update(c *gin.Context) {
return
}
if svcErr := h.svc.Update(c.Request.Context(), id, updates); svcErr != nil {
if svcErr := h.svc.UpdateByAccountAndID(c.Request.Context(), accountID, id, updates); svcErr != nil {
applogger.L().Errorf("Update canned response: %v", svcErr)
handleServiceError(c, svcErr)
return
}
// Fetch updated record to return
cr, svcErr := h.svc.GetByID(c.Request.Context(), id)
cr, svcErr := h.svc.GetByAccountAndID(c.Request.Context(), accountID, id)
if svcErr != nil {
handleServiceError(c, svcErr)
return
}
response.OK(c, cr)
c.JSON(http.StatusOK, serializeCannedResponse(*cr))
}
// Delete soft-deletes a canned response.
@@ -138,14 +200,19 @@ func (h *CannedResponseHandler) Delete(c *gin.Context) {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid id")
return
}
accountID, err := parseUintParam(c, "account_id")
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
return
}
if svcErr := h.svc.Delete(c.Request.Context(), id); svcErr != nil {
if svcErr := h.svc.DeleteByAccountAndID(c.Request.Context(), accountID, id); svcErr != nil {
applogger.L().Errorf("Delete canned response: %v", svcErr)
handleServiceError(c, svcErr)
return
}
response.NoContent(c)
c.Status(http.StatusOK)
}
// List returns all canned responses for an account.
@@ -158,17 +225,17 @@ func (h *CannedResponseHandler) List(c *gin.Context) {
return
}
// If a search query is provided, use Search instead of ListByAccount
searchQuery := c.Query("q")
searchQuery := c.Query("search")
if searchQuery == "" {
searchQuery = c.Query("q")
}
if searchQuery != "" {
responses, svcErr := h.svc.Search(c.Request.Context(), accountID, searchQuery)
if svcErr != nil {
handleServiceError(c, svcErr)
return
}
response.OK(c, gin.H{
"canned_responses": responses,
})
c.JSON(http.StatusOK, serializeCannedResponses(responses))
return
}
@@ -178,9 +245,7 @@ func (h *CannedResponseHandler) List(c *gin.Context) {
return
}
response.OK(c, gin.H{
"canned_responses": responses,
})
c.JSON(http.StatusOK, serializeCannedResponses(responses))
}
// Search performs a ranked search over canned responses.
@@ -193,14 +258,15 @@ func (h *CannedResponseHandler) Search(c *gin.Context) {
return
}
searchQuery := c.Query("q")
searchQuery := c.Query("search")
if searchQuery == "" {
searchQuery = c.Query("q")
}
responses, svcErr := h.svc.Search(c.Request.Context(), accountID, searchQuery)
if svcErr != nil {
handleServiceError(c, svcErr)
return
}
response.OK(c, gin.H{
"canned_responses": responses,
})
c.JSON(http.StatusOK, serializeCannedResponses(responses))
}
@@ -2,6 +2,7 @@ package v1
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
@@ -58,6 +59,30 @@ func TestCannedResponseHandlerSuite(t *testing.T) {
suite.Run(t, new(CannedResponseHandlerTestSuite))
}
func (s *CannedResponseHandlerTestSuite) SetupTest() {
s.Require().NoError(s.db.Exec("DELETE FROM canned_responses").Error)
}
func (s *CannedResponseHandlerTestSuite) router() *gin.Engine {
r := gin.New()
r.GET("/api/v1/accounts/:account_id/canned_responses", s.handler.List)
r.GET("/api/v1/accounts/:account_id/canned_responses/", s.handler.List)
r.POST("/api/v1/accounts/:account_id/canned_responses", s.handler.Create)
r.POST("/api/v1/accounts/:account_id/canned_responses/", s.handler.Create)
r.GET("/api/v1/accounts/:account_id/canned_responses/search", s.handler.Search)
r.GET("/api/v1/accounts/:account_id/canned_responses/:id", s.handler.Get)
r.PATCH("/api/v1/accounts/:account_id/canned_responses/:id", s.handler.Update)
r.PUT("/api/v1/accounts/:account_id/canned_responses/:id", s.handler.Update)
r.DELETE("/api/v1/accounts/:account_id/canned_responses/:id", s.handler.Delete)
return r
}
func (s *CannedResponseHandlerTestSuite) seedCannedResponse(shortCode, content string) *canned.CannedResponse {
cr := &canned.CannedResponse{AccountID: s.account.ID, ShortCode: shortCode, Content: content}
s.Require().NoError(s.db.Create(cr).Error)
return cr
}
func (s *CannedResponseHandlerTestSuite) TestList_BadRequest_InvalidAccountID() {
r := gin.New()
r.GET("/api/v1/accounts/:account_id/canned_responses", s.handler.List)
@@ -70,14 +95,114 @@ func (s *CannedResponseHandlerTestSuite) TestList_BadRequest_InvalidAccountID()
}
func (s *CannedResponseHandlerTestSuite) TestList_Success() {
r := gin.New()
r.GET("/api/v1/accounts/:account_id/canned_responses", s.handler.List)
s.seedCannedResponse("hello", "Hello there")
r := s.router()
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/%d/canned_responses", s.account.ID), nil)
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusOK, w.Code)
var payload []map[string]interface{}
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &payload))
s.Require().Len(payload, 1)
assert.Equal(s.T(), "hello", payload[0]["short_code"])
assert.NotContains(s.T(), payload[0], "deleted_at")
}
func (s *CannedResponseHandlerTestSuite) TestList_SearchParamReturnsRawRankedArray() {
s.seedCannedResponse("hey_start", "Generic content")
s.seedCannedResponse("say_hey", "Generic content")
s.seedCannedResponse("body_match", "Please say hey to the customer")
r := s.router()
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/%d/canned_responses?search=hey", s.account.ID), nil)
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusOK, w.Code)
var payload []map[string]interface{}
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &payload))
s.Require().Len(payload, 3)
assert.Equal(s.T(), "hey_start", payload[0]["short_code"])
assert.Equal(s.T(), "say_hey", payload[1]["short_code"])
assert.Equal(s.T(), "body_match", payload[2]["short_code"])
}
func (s *CannedResponseHandlerTestSuite) TestCreate_RawFrontendBodyReturnsRawPayload() {
r := s.router()
w := httptest.NewRecorder()
body := bytes.NewBufferString(`{"short_code":"welcome","content":"Welcome!"}`)
req, _ := http.NewRequest("POST", fmt.Sprintf("/api/v1/accounts/%d/canned_responses", s.account.ID), body)
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusOK, w.Code)
var payload map[string]interface{}
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &payload))
assert.Equal(s.T(), "welcome", payload["short_code"])
assert.Equal(s.T(), "Welcome!", payload["content"])
assert.Equal(s.T(), float64(s.account.ID), payload["account_id"])
assert.NotContains(s.T(), payload, "success")
assert.NotContains(s.T(), payload, "data")
}
func (s *CannedResponseHandlerTestSuite) TestUpdate_PatchRawBodyIsAccountScoped() {
cr := s.seedCannedResponse("old", "Old content")
r := s.router()
w := httptest.NewRecorder()
body := bytes.NewBufferString(`{"short_code":"new","content":"New content"}`)
req, _ := http.NewRequest("PATCH", fmt.Sprintf("/api/v1/accounts/%d/canned_responses/%d", s.account.ID, cr.ID), body)
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusOK, w.Code)
var payload map[string]interface{}
s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &payload))
assert.Equal(s.T(), "new", payload["short_code"])
assert.Equal(s.T(), "New content", payload["content"])
}
func (s *CannedResponseHandlerTestSuite) TestUpdate_CrossAccountReturnsNotFound() {
cr := s.seedCannedResponse("private", "Private content")
otherAccount := &model.Account{Name: "other-canned-account"}
s.Require().NoError(s.db.Create(otherAccount).Error)
r := s.router()
w := httptest.NewRecorder()
body := bytes.NewBufferString(`{"content":"Nope"}`)
req, _ := http.NewRequest("PATCH", fmt.Sprintf("/api/v1/accounts/%d/canned_responses/%d", otherAccount.ID, cr.ID), body)
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusNotFound, w.Code)
}
func (s *CannedResponseHandlerTestSuite) TestDelete_ReturnsOKEmptyAndScopesAccount() {
cr := s.seedCannedResponse("delete_me", "Delete me")
r := s.router()
w := httptest.NewRecorder()
req, _ := http.NewRequest("DELETE", fmt.Sprintf("/api/v1/accounts/%d/canned_responses/%d", s.account.ID, cr.ID), nil)
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusOK, w.Code)
assert.Empty(s.T(), w.Body.String())
}
func (s *CannedResponseHandlerTestSuite) TestDelete_CrossAccountReturnsNotFound() {
cr := s.seedCannedResponse("private_delete", "Private content")
otherAccount := &model.Account{Name: "other-delete-account"}
s.Require().NoError(s.db.Create(otherAccount).Error)
r := s.router()
w := httptest.NewRecorder()
req, _ := http.NewRequest("DELETE", fmt.Sprintf("/api/v1/accounts/%d/canned_responses/%d", otherAccount.ID, cr.ID), nil)
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusNotFound, w.Code)
}
func (s *CannedResponseHandlerTestSuite) TestCreate_BadRequest_EmptyBody() {
@@ -135,4 +260,4 @@ func (s *CannedResponseHandlerTestSuite) TestSearch_BadRequest_InvalidAccountID(
r.ServeHTTP(w, req)
assert.Equal(s.T(), http.StatusBadRequest, w.Code)
}
}