feat(public): implement chatwoot csat survey flow

This commit is contained in:
2026-06-04 22:57:15 +08:00
parent 8cd564e1da
commit 79042add01
8 changed files with 474 additions and 39 deletions
+32 -17
View File
@@ -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
}
@@ -1278,5 +1278,8 @@ func widgetErrorStatus(err error) int {
if strings.Contains(msg, "not found") {
return http.StatusNotFound
}
if strings.Contains(msg, "CSAT survey after 14 days") {
return http.StatusUnprocessableEntity
}
return http.StatusBadRequest
}
@@ -22,6 +22,7 @@ import (
"gorm.io/gorm"
"gorm.io/gorm/logger"
"github.com/gochat/gochat/internal/automation"
"github.com/gochat/gochat/internal/campaign"
"github.com/gochat/gochat/internal/model"
channelmodel "github.com/gochat/gochat/internal/model/channel"
@@ -59,6 +60,7 @@ func setupWidgetHandlerTest(t *testing.T) (*gorm.DB, *gin.Engine, *WidgetHandler
&model.Message{},
&model.Attachment{},
&model.DirectUpload{},
&automation.CsatSurveyResponse{},
&model.WidgetThemeConfig{},
&model.PreChatForm{},
&model.WidgetFileUpload{},
@@ -1286,3 +1288,62 @@ func TestWidgetHandler_PublicAPIInboxContactConversationMessageFlow(t *testing.T
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
}
func TestWidgetHandler_PublicAPIMessageUpdate_CsatSubmission(t *testing.T) {
db, router, _ := setupWidgetHandlerTest(t)
account, inbox, _ := seedPublicAPIInbox(t, db)
contact := &model.Contact{AccountID: account.ID, Name: "CSAT Public Visitor"}
require.NoError(t, db.Create(contact).Error)
contactInbox := &model.ContactInbox{ContactID: contact.ID, InboxID: inbox.ID, SourceID: "csat-source", PubsubToken: "csat-pubsub"}
require.NoError(t, db.Create(contactInbox).Error)
conversation := &model.Conversation{AccountID: account.ID, InboxID: inbox.ID, ContactID: contact.ID, ContactInboxID: &contactInbox.ID, Status: "resolved", ChannelType: inbox.ChannelType, Channel: inbox.ChannelType}
require.NoError(t, db.Create(conversation).Error)
message := &model.Message{
ConversationID: conversation.ID,
AccountID: account.ID,
InboxID: inbox.ID,
Content: "Rate this conversation",
ContentType: "input_csat",
MessageType: "outgoing",
ContentAttributes: datatypes.JSON(`{}`),
}
require.NoError(t, db.Create(message).Error)
body := `{"submitted_values":[{"csat_survey_response":{"rating":3,"feedback_message":"Okay"}}]}`
w := httptest.NewRecorder()
url := "/public/api/v1/inboxes/public-api-inbox/contacts/csat-source/conversations/" + strconv.FormatUint(uint64(conversation.ID), 10) + "/messages/" + strconv.FormatUint(uint64(message.ID), 10)
req, _ := http.NewRequest("PATCH", url, bytes.NewReader([]byte(body)))
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(w, req)
require.Equal(t, http.StatusOK, w.Code)
var stored automation.CsatSurveyResponse
require.NoError(t, db.Where("message_id = ?", message.ID).First(&stored).Error)
assert.Equal(t, 3, stored.Rating)
assert.Equal(t, "Okay", stored.FeedbackMessage)
assert.Equal(t, contact.ID, stored.ContactID)
}
func TestWidgetHandler_PublicAPIMessageUpdate_CsatLocked(t *testing.T) {
db, router, _ := setupWidgetHandlerTest(t)
account, inbox, _ := seedPublicAPIInbox(t, db)
contact := &model.Contact{AccountID: account.ID, Name: "Late CSAT Visitor"}
require.NoError(t, db.Create(contact).Error)
contactInbox := &model.ContactInbox{ContactID: contact.ID, InboxID: inbox.ID, SourceID: "late-csat-source", PubsubToken: "late-csat-pubsub"}
require.NoError(t, db.Create(contactInbox).Error)
conversation := &model.Conversation{AccountID: account.ID, InboxID: inbox.ID, ContactID: contact.ID, ContactInboxID: &contactInbox.ID, Status: "resolved", ChannelType: inbox.ChannelType, Channel: inbox.ChannelType}
require.NoError(t, db.Create(conversation).Error)
message := &model.Message{ConversationID: conversation.ID, AccountID: account.ID, InboxID: inbox.ID, Content: "Rate this conversation", ContentType: "input_csat", MessageType: "outgoing", ContentAttributes: datatypes.JSON(`{}`)}
require.NoError(t, db.Create(message).Error)
old := time.Now().AddDate(0, 0, -15)
require.NoError(t, db.Model(message).Updates(map[string]any{"created_at": old, "updated_at": old}).Error)
body := `{"submitted_values":[{"csat_survey_response":{"rating":5,"feedback_message":"Late"}}]}`
w := httptest.NewRecorder()
url := "/public/api/v1/inboxes/public-api-inbox/contacts/late-csat-source/conversations/" + strconv.FormatUint(uint64(conversation.ID), 10) + "/messages/" + strconv.FormatUint(uint64(message.ID), 10)
req, _ := http.NewRequest("PATCH", url, bytes.NewReader([]byte(body)))
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(w, req)
require.Equal(t, http.StatusUnprocessableEntity, w.Code)
assert.Contains(t, w.Body.String(), "You cannot update the CSAT survey after 14 days")
}