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
+35 -3
View File
@@ -2,7 +2,6 @@ package canned
import (
"context"
"fmt"
"strings"
"gorm.io/gorm"
@@ -39,16 +38,45 @@ func (s *CannedResponseService) GetByID(ctx context.Context, id uint) (*CannedRe
return &resp, nil
}
// GetByAccountAndID retrieves a canned response scoped through its account.
func (s *CannedResponseService) GetByAccountAndID(ctx context.Context, accountID, id uint) (*CannedResponse, error) {
var resp CannedResponse
if err := s.db.DB().WithContext(ctx).
Where("account_id = ? AND id = ?", accountID, id).
First(&resp).Error; err != nil {
return nil, err
}
return &resp, nil
}
// Update updates a canned response.
func (s *CannedResponseService) Update(ctx context.Context, id uint, updates map[string]interface{}) error {
return s.db.DB().WithContext(ctx).Model(&CannedResponse{}).Where("id = ?", id).Updates(updates).Error
}
// UpdateByAccountAndID updates a canned response scoped through its account.
func (s *CannedResponseService) UpdateByAccountAndID(ctx context.Context, accountID, id uint, updates map[string]interface{}) error {
resp, err := s.GetByAccountAndID(ctx, accountID, id)
if err != nil {
return err
}
return s.db.DB().WithContext(ctx).Model(resp).Updates(updates).Error
}
// Delete soft-deletes a canned response.
func (s *CannedResponseService) Delete(ctx context.Context, id uint) error {
return s.db.DB().WithContext(ctx).Delete(&CannedResponse{}, id).Error
}
// DeleteByAccountAndID deletes a canned response scoped through its account.
func (s *CannedResponseService) DeleteByAccountAndID(ctx context.Context, accountID, id uint) error {
resp, err := s.GetByAccountAndID(ctx, accountID, id)
if err != nil {
return err
}
return s.db.DB().WithContext(ctx).Unscoped().Delete(resp).Error
}
// ListByAccount returns all canned responses for an account.
func (s *CannedResponseService) ListByAccount(ctx context.Context, accountID uint) ([]CannedResponse, error) {
var responses []CannedResponse
@@ -71,10 +99,14 @@ func (s *CannedResponseService) Search(ctx context.Context, accountID uint, quer
// Use a CASE-based ordering: short_code matches rank higher than content matches.
// This mirrors Chatwoot's order_by_search scope.
// The search is case-insensitive.
likePattern := fmt.Sprintf("%%%s%%", strings.ToLower(query))
lowerQuery := strings.ToLower(query)
prefixPattern := lowerQuery + "%"
likePattern := "%" + lowerQuery + "%"
err := s.db.DB().WithContext(ctx).
Select("canned_responses.*, CASE WHEN LOWER(short_code) LIKE ? THEN 1.0 WHEN LOWER(short_code) LIKE ? THEN 0.5 WHEN LOWER(content) LIKE ? THEN 0.2 ELSE 0 END AS search_rank", prefixPattern, likePattern, likePattern).
Where("account_id = ? AND (LOWER(short_code) LIKE ? OR LOWER(content) LIKE ?)", accountID, likePattern, likePattern).
Order(fmt.Sprintf("CASE WHEN LOWER(short_code) LIKE '%s' THEN 0 ELSE 1 END, short_code ASC", likePattern)).
Order("search_rank DESC").
Order("short_code ASC").
Find(&responses).Error
return responses, err
}
+120 -1
View File
@@ -97,6 +97,33 @@ func TestCannedResponseService_GetByID_NotFound(t *testing.T) {
}
}
func TestCannedResponseService_GetByAccountAndID(t *testing.T) {
provider := setupCannedTestDBProvider(t)
accountID, _ := seedTestAccount(provider.DB(), t)
otherAccount := &model.Account{Name: "Other Scoped Account"}
if err := provider.DB().Create(otherAccount).Error; err != nil {
t.Fatalf("failed to create other account: %v", err)
}
svc := NewCannedResponseService(provider)
cr := &CannedResponse{AccountID: accountID, ShortCode: "scoped", Content: "Scoped content"}
if err := svc.Create(context.Background(), cr); err != nil {
t.Fatalf("Create failed: %v", err)
}
found, err := svc.GetByAccountAndID(context.Background(), accountID, cr.ID)
if err != nil {
t.Fatalf("GetByAccountAndID failed: %v", err)
}
if found.ID != cr.ID {
t.Fatalf("expected ID %d, got %d", cr.ID, found.ID)
}
if _, err := svc.GetByAccountAndID(context.Background(), otherAccount.ID, cr.ID); err == nil {
t.Fatal("expected cross-account lookup to fail")
}
}
func TestCannedResponseService_Update(t *testing.T) {
provider := setupCannedTestDBProvider(t)
accountID, _ := seedTestAccount(provider.DB(), t)
@@ -131,6 +158,36 @@ func TestCannedResponseService_Update(t *testing.T) {
}
}
func TestCannedResponseService_UpdateByAccountAndID(t *testing.T) {
provider := setupCannedTestDBProvider(t)
accountID, _ := seedTestAccount(provider.DB(), t)
otherAccount := &model.Account{Name: "Other Update Account"}
if err := provider.DB().Create(otherAccount).Error; err != nil {
t.Fatalf("failed to create other account: %v", err)
}
svc := NewCannedResponseService(provider)
cr := &CannedResponse{AccountID: accountID, ShortCode: "account_update", Content: "Original"}
if err := svc.Create(context.Background(), cr); err != nil {
t.Fatalf("Create failed: %v", err)
}
if err := svc.UpdateByAccountAndID(context.Background(), otherAccount.ID, cr.ID, map[string]interface{}{"content": "Wrong"}); err == nil {
t.Fatal("expected cross-account update to fail")
}
if err := svc.UpdateByAccountAndID(context.Background(), accountID, cr.ID, map[string]interface{}{"content": "Updated"}); err != nil {
t.Fatalf("UpdateByAccountAndID failed: %v", err)
}
found, err := svc.GetByAccountAndID(context.Background(), accountID, cr.ID)
if err != nil {
t.Fatalf("GetByAccountAndID after update failed: %v", err)
}
if found.Content != "Updated" {
t.Fatalf("expected updated content, got %q", found.Content)
}
}
func TestCannedResponseService_Delete(t *testing.T) {
provider := setupCannedTestDBProvider(t)
accountID, _ := seedTestAccount(provider.DB(), t)
@@ -156,6 +213,40 @@ func TestCannedResponseService_Delete(t *testing.T) {
}
}
func TestCannedResponseService_DeleteByAccountAndID(t *testing.T) {
provider := setupCannedTestDBProvider(t)
accountID, _ := seedTestAccount(provider.DB(), t)
otherAccount := &model.Account{Name: "Other Delete Account"}
if err := provider.DB().Create(otherAccount).Error; err != nil {
t.Fatalf("failed to create other account: %v", err)
}
svc := NewCannedResponseService(provider)
cr := &CannedResponse{AccountID: accountID, ShortCode: "account_delete", Content: "Delete"}
if err := svc.Create(context.Background(), cr); err != nil {
t.Fatalf("Create failed: %v", err)
}
if err := svc.DeleteByAccountAndID(context.Background(), otherAccount.ID, cr.ID); err == nil {
t.Fatal("expected cross-account delete to fail")
}
if _, err := svc.GetByAccountAndID(context.Background(), accountID, cr.ID); err != nil {
t.Fatalf("record should still exist after failed cross-account delete: %v", err)
}
if err := svc.DeleteByAccountAndID(context.Background(), accountID, cr.ID); err != nil {
t.Fatalf("DeleteByAccountAndID failed: %v", err)
}
if _, err := svc.GetByAccountAndID(context.Background(), accountID, cr.ID); err == nil {
t.Fatal("expected account-scoped lookup to fail after delete")
}
recreated := &CannedResponse{AccountID: accountID, ShortCode: "account_delete", Content: "Recreated"}
if err := svc.Create(context.Background(), recreated); err != nil {
t.Fatalf("expected hard-deleted short_code to be reusable: %v", err)
}
}
func TestCannedResponseService_ListByAccount(t *testing.T) {
provider := setupCannedTestDBProvider(t)
accountID, _ := seedTestAccount(provider.DB(), t)
@@ -266,6 +357,34 @@ func TestCannedResponseService_Search(t *testing.T) {
}
}
func TestCannedResponseService_Search_RanksLikeChatwoot(t *testing.T) {
provider := setupCannedTestDBProvider(t)
accountID, _ := seedTestAccount(provider.DB(), t)
svc := NewCannedResponseService(provider)
items := []CannedResponse{
{AccountID: accountID, ShortCode: "body_only", Content: "Please mention help in the body"},
{AccountID: accountID, ShortCode: "say_help", Content: "Generic"},
{AccountID: accountID, ShortCode: "help_start", Content: "Generic"},
}
for i := range items {
if err := svc.Create(context.Background(), &items[i]); err != nil {
t.Fatalf("Create #%d failed: %v", i, err)
}
}
results, err := svc.Search(context.Background(), accountID, "help")
if err != nil {
t.Fatalf("Search failed: %v", err)
}
if len(results) != 3 {
t.Fatalf("expected 3 results, got %d", len(results))
}
if results[0].ShortCode != "help_start" || results[1].ShortCode != "say_help" || results[2].ShortCode != "body_only" {
t.Fatalf("unexpected ranking: %s, %s, %s", results[0].ShortCode, results[1].ShortCode, results[2].ShortCode)
}
}
func TestCannedResponseService_GetByShortCode(t *testing.T) {
provider := setupCannedTestDBProvider(t)
accountID, _ := seedTestAccount(provider.DB(), t)
@@ -296,4 +415,4 @@ func TestCannedResponseService_GetByShortCode(t *testing.T) {
if err == nil {
t.Fatal("expected error for non-existent short_code, got nil")
}
}
}
@@ -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)
}
}
+4 -1
View File
@@ -1639,12 +1639,15 @@ func registerV1Routes(g *gin.RouterGroup, h *Handlers) {
// Reference: Chatwoot namespace :canned_responses
cannedResponses := accountScoped.Group("/canned_responses")
{
cannedResponses.GET("", h.CannedResponse.List)
cannedResponses.GET("/", h.CannedResponse.List)
cannedResponses.POST("", h.CannedResponse.Create)
cannedResponses.POST("/", h.CannedResponse.Create)
cannedResponses.GET("/search", h.CannedResponse.Search)
cannedResponses.GET("/:id", h.CannedResponse.Get)
cannedResponses.PATCH("/:id", h.CannedResponse.Update)
cannedResponses.PUT("/:id", h.CannedResponse.Update)
cannedResponses.DELETE("/:id", h.CannedResponse.Delete)
cannedResponses.GET("/search", h.CannedResponse.Search)
}
// Integration hooks (Chatwoot: resources :hooks)