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" ) type CsatSurveyHandlerTestSuite struct { suite.Suite db *gorm.DB handler *CsatSurveyHandler account *model.Account } type csatSurveyTestDBProvider struct { db *gorm.DB } func (p *csatSurveyTestDBProvider) DB() *gorm.DB { return p.db } func (s *CsatSurveyHandlerTestSuite) SetupSuite() { gin.SetMode(gin.TestMode) db, err := gorm.Open(sqlite.Open("file::memory:"), &gorm.Config{ Logger: logger.Default.LogMode(logger.Silent), }) s.Require().NoError(err) 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}) s.handler = NewCsatSurveyHandler(svc) s.account = &model.Account{Name: "test-csat-survey-account"} s.Require().NoError(db.Create(s.account).Error) } 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() { if s.db != nil { sqlDB, _ := s.db.DB() sqlDB.Close() } } func TestCsatSurveyHandlerSuite(t *testing.T) { suite.Run(t, new(CsatSurveyHandlerTestSuite)) } func (s *CsatSurveyHandlerTestSuite) TestList_Success() { r := gin.New() r.GET("/api/v1/accounts/:account_id/csats", s.handler.List) w := httptest.NewRecorder() req, _ := http.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/%d/csats", s.account.ID), nil) r.ServeHTTP(w, req) assert.Equal(s.T(), http.StatusOK, w.Code) } func (s *CsatSurveyHandlerTestSuite) TestMetrics_Success() { r := gin.New() r.GET("/api/v1/accounts/:account_id/csat_metrics", s.handler.Metrics) w := httptest.NewRecorder() req, _ := http.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/%d/csat_metrics", s.account.ID), nil) r.ServeHTTP(w, req) assert.Equal(s.T(), http.StatusOK, w.Code) } func (s *CsatSurveyHandlerTestSuite) TestUpdateReviewNotes_Success() { survey := &automation.CsatSurveyResponse{AccountID: s.account.ID, ConversationID: 1, Rating: 5} s.Require().NoError(s.db.Create(survey).Error) r := gin.New() r.PUT("/api/v1/accounts/:account_id/csats/:id/review_notes", func(c *gin.Context) { c.Set("user_id", float64(1)) s.handler.UpdateReviewNotes(c) }) w := httptest.NewRecorder() body := `{"review_notes":"good conversation"}` req, _ := http.NewRequest("PUT", fmt.Sprintf("/api/v1/accounts/%d/csats/%d/review_notes", s.account.ID, survey.ID), bytes.NewBufferString(body)) req.Header.Set("Content-Type", "application/json") r.ServeHTTP(w, req) assert.Equal(s.T(), http.StatusOK, w.Code) } func (s *CsatSurveyHandlerTestSuite) TestUpdate_Success() { survey := &automation.CsatSurveyResponse{AccountID: s.account.ID, ConversationID: 1, Rating: 5} s.Require().NoError(s.db.Create(survey).Error) r := gin.New() r.PUT("/api/v1/accounts/:account_id/csats/:id", func(c *gin.Context) { c.Set("user_id", float64(1)) s.handler.Update(c) }) w := httptest.NewRecorder() body := `{"review_notes":"updated notes"}` req, _ := http.NewRequest("PUT", fmt.Sprintf("/api/v1/accounts/%d/csats/%d", s.account.ID, survey.ID), bytes.NewBufferString(body)) req.Header.Set("Content-Type", "application/json") r.ServeHTTP(w, req) 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) w := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/api/v1/accounts/abc/csats", nil) 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 }