feat(public): implement chatwoot csat survey flow
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
@@ -146,13 +147,13 @@ func (h *CsatSurveyHandler) PublicGet(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
resp, svcErr := h.svc.GetByConversationUUID(c.Request.Context(), conversationUUID)
|
||||
resp, svcErr := h.svc.GetPublicSurveyByConversationUUID(c.Request.Context(), conversationUUID)
|
||||
if svcErr != nil {
|
||||
handleServiceError(c, svcErr)
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, resp)
|
||||
c.JSON(http.StatusOK, resp)
|
||||
}
|
||||
|
||||
// PublicUpdate updates a CSAT survey response via conversation UUID (no auth required).
|
||||
@@ -167,32 +168,46 @@ func (h *CsatSurveyHandler) PublicUpdate(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
var body struct {
|
||||
Rating int `json:"rating"`
|
||||
FeedbackMessage string `json:"feedback_message"`
|
||||
}
|
||||
var body publicCsatUpdateBody
|
||||
if err := c.ShouldBindJSON(&body); err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Find existing response by UUID
|
||||
resp, svcErr := h.svc.GetByConversationUUID(c.Request.Context(), conversationUUID)
|
||||
resp, svcErr := h.svc.SubmitPublicSurveyByConversationUUID(c.Request.Context(), conversationUUID, body.submittedValues())
|
||||
if errors.Is(svcErr, automation.ErrCsatSurveyLocked) {
|
||||
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": automation.ErrCsatSurveyLocked.Error()})
|
||||
return
|
||||
}
|
||||
if svcErr != nil {
|
||||
handleServiceError(c, svcErr)
|
||||
return
|
||||
}
|
||||
|
||||
if svcErr := h.svc.UpdateResponse(c.Request.Context(), resp.ID, body.Rating, body.FeedbackMessage); svcErr != nil {
|
||||
handleServiceError(c, svcErr)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, resp)
|
||||
}
|
||||
|
||||
response.OK(c, gin.H{
|
||||
"id": resp.ID,
|
||||
"rating": body.Rating,
|
||||
"feedback_message": body.FeedbackMessage,
|
||||
})
|
||||
type publicCsatUpdateBody struct {
|
||||
Rating int `json:"rating"`
|
||||
FeedbackMessage string `json:"feedback_message"`
|
||||
Message struct {
|
||||
SubmittedValues []map[string]any `json:"submitted_values"`
|
||||
} `json:"message"`
|
||||
}
|
||||
|
||||
func (b publicCsatUpdateBody) submittedValues() []map[string]any {
|
||||
if len(b.Message.SubmittedValues) > 0 {
|
||||
return b.Message.SubmittedValues
|
||||
}
|
||||
if b.Rating != 0 || b.FeedbackMessage != "" {
|
||||
return []map[string]any{{
|
||||
"csat_survey_response": map[string]any{
|
||||
"rating": b.Rating,
|
||||
"feedback_message": b.FeedbackMessage,
|
||||
},
|
||||
}}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// buildCsatFilter constructs a CsatListFilter from Gin query parameters.
|
||||
|
||||
@@ -2,16 +2,19 @@ package v1
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gochat/gochat/internal/automation"
|
||||
"github.com/gochat/gochat/internal/model"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/suite"
|
||||
"gorm.io/datatypes"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
@@ -38,7 +41,15 @@ func (s *CsatSurveyHandlerTestSuite) SetupSuite() {
|
||||
Logger: logger.Default.LogMode(logger.Silent),
|
||||
})
|
||||
s.Require().NoError(err)
|
||||
s.Require().NoError(db.AutoMigrate(&model.Account{}, &model.Conversation{}, &automation.CsatSurveyResponse{}, &model.ReportingEventsRollup{}))
|
||||
s.Require().NoError(db.AutoMigrate(
|
||||
&model.Account{},
|
||||
&model.Inbox{},
|
||||
&model.Contact{},
|
||||
&model.Conversation{},
|
||||
&model.Message{},
|
||||
&automation.CsatSurveyResponse{},
|
||||
&model.ReportingEventsRollup{},
|
||||
))
|
||||
s.db = db
|
||||
|
||||
svc := automation.NewCsatSurveyService(&csatSurveyTestDBProvider{db: db})
|
||||
@@ -50,6 +61,10 @@ func (s *CsatSurveyHandlerTestSuite) SetupSuite() {
|
||||
|
||||
func (s *CsatSurveyHandlerTestSuite) SetupTest() {
|
||||
s.db.Exec("DELETE FROM csat_survey_responses")
|
||||
s.db.Exec("DELETE FROM messages")
|
||||
s.db.Exec("DELETE FROM conversations")
|
||||
s.db.Exec("DELETE FROM contacts")
|
||||
s.db.Exec("DELETE FROM inboxes")
|
||||
}
|
||||
|
||||
func (s *CsatSurveyHandlerTestSuite) TearDownSuite() {
|
||||
@@ -123,6 +138,69 @@ func (s *CsatSurveyHandlerTestSuite) TestUpdate_Success() {
|
||||
assert.Equal(s.T(), http.StatusOK, w.Code)
|
||||
}
|
||||
|
||||
func (s *CsatSurveyHandlerTestSuite) TestPublicCsatShowAndUpdate_Success() {
|
||||
conversation, message := s.seedPublicCsatSurvey(time.Now())
|
||||
|
||||
r := gin.New()
|
||||
r.GET("/public/api/v1/csat_survey/:id", s.handler.PublicGet)
|
||||
r.PATCH("/public/api/v1/csat_survey/:id", s.handler.PublicUpdate)
|
||||
|
||||
wShow := httptest.NewRecorder()
|
||||
reqShow, _ := http.NewRequest("GET", "/public/api/v1/csat_survey/"+conversation.UUID, nil)
|
||||
r.ServeHTTP(wShow, reqShow)
|
||||
assert.Equal(s.T(), http.StatusOK, wShow.Code)
|
||||
|
||||
var showResp map[string]any
|
||||
s.Require().NoError(json.Unmarshal(wShow.Body.Bytes(), &showResp))
|
||||
assert.Equal(s.T(), float64(message.ID), showResp["id"])
|
||||
assert.Nil(s.T(), showResp["csat_survey_response"])
|
||||
assert.Equal(s.T(), "emoji", showResp["display_type"])
|
||||
assert.Equal(s.T(), "Rate this chat", showResp["content"])
|
||||
assert.Equal(s.T(), "CSAT Inbox", showResp["inbox_name"])
|
||||
|
||||
body := `{"message":{"submitted_values":[{"csat_survey_response":{"rating":4,"feedback_message":"Helpful"}}]}}`
|
||||
wUpdate := httptest.NewRecorder()
|
||||
reqUpdate, _ := http.NewRequest("PATCH", "/public/api/v1/csat_survey/"+conversation.UUID, bytes.NewBufferString(body))
|
||||
reqUpdate.Header.Set("Content-Type", "application/json")
|
||||
r.ServeHTTP(wUpdate, reqUpdate)
|
||||
assert.Equal(s.T(), http.StatusOK, wUpdate.Code)
|
||||
|
||||
var updateResp map[string]any
|
||||
s.Require().NoError(json.Unmarshal(wUpdate.Body.Bytes(), &updateResp))
|
||||
csatResp := updateResp["csat_survey_response"].(map[string]any)
|
||||
assert.Equal(s.T(), float64(4), csatResp["rating"])
|
||||
assert.Equal(s.T(), "Helpful", csatResp["feedback_message"])
|
||||
|
||||
var stored automation.CsatSurveyResponse
|
||||
s.Require().NoError(s.db.Where("message_id = ?", message.ID).First(&stored).Error)
|
||||
assert.Equal(s.T(), 4, stored.Rating)
|
||||
assert.Equal(s.T(), "Helpful", stored.FeedbackMessage)
|
||||
assert.Equal(s.T(), conversation.ContactID, stored.ContactID)
|
||||
s.Require().NotNil(stored.MessageID)
|
||||
assert.Equal(s.T(), message.ID, *stored.MessageID)
|
||||
|
||||
var storedMessage model.Message
|
||||
s.Require().NoError(s.db.First(&storedMessage, message.ID).Error)
|
||||
var attrs map[string]any
|
||||
s.Require().NoError(json.Unmarshal(storedMessage.ContentAttributes, &attrs))
|
||||
assert.NotEmpty(s.T(), attrs["submitted_values"])
|
||||
}
|
||||
|
||||
func (s *CsatSurveyHandlerTestSuite) TestPublicCsatUpdate_LockedAfter14Days() {
|
||||
conversation, _ := s.seedPublicCsatSurvey(time.Now().AddDate(0, 0, -15))
|
||||
|
||||
r := gin.New()
|
||||
r.PATCH("/public/api/v1/csat_survey/:id", s.handler.PublicUpdate)
|
||||
|
||||
body := `{"message":{"submitted_values":[{"csat_survey_response":{"rating":5,"feedback_message":"Too late"}}]}}`
|
||||
w := httptest.NewRecorder()
|
||||
req, _ := http.NewRequest("PATCH", "/public/api/v1/csat_survey/"+conversation.UUID, bytes.NewBufferString(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
r.ServeHTTP(w, req)
|
||||
assert.Equal(s.T(), http.StatusUnprocessableEntity, w.Code)
|
||||
assert.Contains(s.T(), w.Body.String(), "You cannot update the CSAT survey after 14 days")
|
||||
}
|
||||
|
||||
func (s *CsatSurveyHandlerTestSuite) TestList_BadRequest_InvalidAccountID() {
|
||||
r := gin.New()
|
||||
r.GET("/api/v1/accounts/:account_id/csats", s.handler.List)
|
||||
@@ -132,4 +210,42 @@ func (s *CsatSurveyHandlerTestSuite) TestList_BadRequest_InvalidAccountID() {
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
assert.Equal(s.T(), http.StatusBadRequest, w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *CsatSurveyHandlerTestSuite) seedPublicCsatSurvey(createdAt time.Time) (*model.Conversation, *model.Message) {
|
||||
contact := &model.Contact{AccountID: s.account.ID, Name: "CSAT Contact"}
|
||||
s.Require().NoError(s.db.Create(contact).Error)
|
||||
inbox := &model.Inbox{
|
||||
AccountID: s.account.ID,
|
||||
Name: "CSAT Inbox",
|
||||
ChannelType: "web_widget",
|
||||
Enabled: true,
|
||||
CsatSurveyEnabled: true,
|
||||
CsatConfig: `{"display_type":"emoji","message":"Rate this chat"}`,
|
||||
AvatarURL: "https://example.test/avatar.png",
|
||||
}
|
||||
s.Require().NoError(s.db.Create(inbox).Error)
|
||||
conversation := &model.Conversation{
|
||||
AccountID: s.account.ID,
|
||||
InboxID: inbox.ID,
|
||||
ContactID: contact.ID,
|
||||
Status: "resolved",
|
||||
ChannelType: inbox.ChannelType,
|
||||
Channel: inbox.ChannelType,
|
||||
}
|
||||
s.Require().NoError(s.db.Create(conversation).Error)
|
||||
message := &model.Message{
|
||||
ConversationID: conversation.ID,
|
||||
AccountID: s.account.ID,
|
||||
InboxID: inbox.ID,
|
||||
Content: "Please rate this conversation",
|
||||
ContentType: "input_csat",
|
||||
MessageType: "outgoing",
|
||||
Status: "sent",
|
||||
ContentAttributes: datatypes.JSON(`{}`),
|
||||
}
|
||||
s.Require().NoError(s.db.Create(message).Error)
|
||||
s.Require().NoError(s.db.Model(message).Updates(map[string]any{"created_at": createdAt, "updated_at": createdAt}).Error)
|
||||
s.Require().NoError(s.db.First(message, message.ID).Error)
|
||||
return conversation, message
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user