package v1 import ( "bytes" "encoding/csv" "encoding/json" "fmt" "net/http" "net/http/httptest" "strings" "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.User{}, &model.AccountUser{}, &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") s.db.Exec("DELETE FROM account_users") s.db.Exec("DELETE FROM users") } 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) TestList_ChatwootPayloadAndFilters() { createdAt := time.Now().Add(-2 * time.Hour).Truncate(time.Second) agent, reviewer, contact, conversation, message := s.seedAccountCsatResponseGraph(createdAt, 5) otherContact := &model.Contact{AccountID: s.account.ID, Name: "Other Contact"} s.Require().NoError(s.db.Create(otherContact).Error) otherInbox := &model.Inbox{AccountID: s.account.ID, Name: "Other Inbox", ChannelType: "web_widget", Enabled: true} s.Require().NoError(s.db.Create(otherInbox).Error) otherConversation := &model.Conversation{AccountID: s.account.ID, InboxID: otherInbox.ID, ContactID: otherContact.ID, Status: "resolved", ChannelType: "web_widget", Channel: "web_widget"} s.Require().NoError(s.db.Create(otherConversation).Error) s.Require().NoError(s.db.Create(&automation.CsatSurveyResponse{AccountID: s.account.ID, ConversationID: otherConversation.ID, ContactID: otherContact.ID, Rating: 3}).Error) r := gin.New() r.GET("/api/v1/accounts/:account_id/csat_survey_responses", s.handler.List) teamID := *conversation.TeamID url := fmt.Sprintf("/api/v1/accounts/%d/csat_survey_responses?since=%d&until=%d&user_ids=%d&inbox_id=%d&team_id=%d&rating=5", s.account.ID, createdAt.Add(-time.Hour).Unix(), createdAt.Add(time.Hour).Unix(), agent.ID, conversation.InboxID, teamID) w := httptest.NewRecorder() req, _ := http.NewRequest("GET", url, nil) r.ServeHTTP(w, req) assert.Equal(s.T(), http.StatusOK, w.Code) var payload []map[string]any s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &payload)) s.Require().Len(payload, 1) item := payload[0] assert.Equal(s.T(), float64(5), item["rating"]) assert.Equal(s.T(), "Great", item["feedback_message"]) assert.Equal(s.T(), "Needs follow up", item["csat_review_notes"]) assert.Equal(s.T(), float64(42), item["conversation_id"]) assert.Equal(s.T(), float64(message.ID), item["message_id"]) assert.Equal(s.T(), float64(createdAt.Unix()), item["created_at"]) contactPayload := item["contact"].(map[string]any) assert.Equal(s.T(), contact.Name, contactPayload["name"]) assert.Equal(s.T(), contact.Email, contactPayload["email"]) agentPayload := item["assigned_agent"].(map[string]any) assert.Equal(s.T(), agent.Email, agentPayload["email"]) reviewerPayload := item["review_notes_updated_by"].(map[string]any) assert.Equal(s.T(), reviewer.Name, reviewerPayload["name"]) } func (s *CsatSurveyHandlerTestSuite) TestMetrics_ChatwootPayloadAndFilters() { createdAt := time.Now().Add(-2 * time.Hour).Truncate(time.Second) agent, _, _, conversation, _ := s.seedAccountCsatResponseGraph(createdAt, 5) r := gin.New() r.GET("/api/v1/accounts/:account_id/csat_survey_responses/metrics", s.handler.Metrics) url := fmt.Sprintf("/api/v1/accounts/%d/csat_survey_responses/metrics?since=%d&until=%d&user_ids=%d&inbox_id=%d&rating=5", s.account.ID, createdAt.Add(-time.Hour).Unix(), createdAt.Add(time.Hour).Unix(), agent.ID, conversation.InboxID) w := httptest.NewRecorder() req, _ := http.NewRequest("GET", url, nil) r.ServeHTTP(w, req) assert.Equal(s.T(), http.StatusOK, w.Code) var payload map[string]any s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &payload)) assert.Equal(s.T(), float64(1), payload["total_count"]) assert.Equal(s.T(), float64(1), payload["total_sent_messages_count"]) ratings := payload["ratings_count"].(map[string]any) assert.Equal(s.T(), float64(1), ratings["5"]) } func (s *CsatSurveyHandlerTestSuite) TestDownload_ChatwootCSVAndFilters() { createdAt := time.Date(2026, 6, 5, 10, 30, 0, 0, time.UTC) agent, _, contact, conversation, _ := s.seedAccountCsatResponseGraph(createdAt, 5) otherContact := &model.Contact{AccountID: s.account.ID, Name: "Other Contact"} s.Require().NoError(s.db.Create(otherContact).Error) otherConversation := &model.Conversation{AccountID: s.account.ID, InboxID: conversation.InboxID, ContactID: otherContact.ID, Status: "resolved", ChannelType: "web_widget", Channel: "web_widget"} s.Require().NoError(s.db.Create(otherConversation).Error) s.Require().NoError(s.db.Create(&automation.CsatSurveyResponse{AccountID: s.account.ID, ConversationID: otherConversation.ID, ContactID: otherContact.ID, Rating: 3}).Error) r := gin.New() r.GET("/api/v1/accounts/:account_id/csat_survey_responses/download", s.handler.Download) since := int64(0) until := int64(32503680000) url := fmt.Sprintf("/api/v1/accounts/%d/csat_survey_responses/download?since=%d&until=%d&user_ids=%d&inbox_id=%d&team_id=%d&rating=5", s.account.ID, since, until, agent.ID, conversation.InboxID, *conversation.TeamID) w := httptest.NewRecorder() req, _ := http.NewRequest("GET", url, nil) req.Host = "app.example.test" req.Header.Set("X-Forwarded-Proto", "https") r.ServeHTTP(w, req) assert.Equal(s.T(), http.StatusOK, w.Code) assert.Equal(s.T(), "attachment; filename=csat_report.csv", w.Header().Get("Content-Disposition")) reader := csv.NewReader(strings.NewReader(w.Body.String())) reader.FieldsPerRecord = -1 rows, err := reader.ReadAll() s.Require().NoError(err) s.Require().Len(rows, 3) assert.Equal(s.T(), []string{"Agent Name", "Rating", "Feedback Comment", "Contact Name", "Contact Email Address", "Contact Phone Number", "Link to the conversation", "Recorded date", "Review Notes"}, rows[0]) assert.Equal(s.T(), "CSAT Agent (csat-agent@example.com)", rows[1][0]) assert.Equal(s.T(), "5", rows[1][1]) assert.Equal(s.T(), "Great", rows[1][2]) assert.Equal(s.T(), contact.Name, rows[1][3]) assert.Equal(s.T(), contact.Email, rows[1][4]) assert.Equal(s.T(), contact.PhoneNumber, rows[1][5]) assert.Equal(s.T(), fmt.Sprintf("https://app.example.test/app/accounts/%d/conversations/42", s.account.ID), rows[1][6]) assert.Equal(s.T(), createdAt.Format(time.RFC3339), rows[1][7]) assert.Equal(s.T(), "Needs follow up", rows[1][8]) assert.Equal(s.T(), "Reporting period 1970-01-01 to 3000-01-01", rows[2][0]) } func (s *CsatSurveyHandlerTestSuite) TestUpdateReviewNotes_Success() { _, reviewer, _, _, _ := s.seedAccountCsatResponseGraph(time.Now().Add(-time.Hour), 5) var survey automation.CsatSurveyResponse s.Require().NoError(s.db.First(&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(reviewer.ID)) 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) var payload map[string]any s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &payload)) assert.Equal(s.T(), "good conversation", payload["csat_review_notes"]) reviewerPayload := payload["review_notes_updated_by"].(map[string]any) assert.Equal(s.T(), reviewer.Name, reviewerPayload["name"]) } 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)) submittedValues := attrs["submitted_values"].(map[string]any) assert.Contains(s.T(), submittedValues, "csat_survey_response") secondBody := `{"message":{"submitted_values":{"csat_survey_response":{"rating":2,"feedback_message":"Could be better"}}}}` wSecondUpdate := httptest.NewRecorder() reqSecondUpdate, _ := http.NewRequest("PATCH", "/public/api/v1/csat_survey/"+conversation.UUID, bytes.NewBufferString(secondBody)) reqSecondUpdate.Header.Set("Content-Type", "application/json") r.ServeHTTP(wSecondUpdate, reqSecondUpdate) assert.Equal(s.T(), http.StatusOK, wSecondUpdate.Code) var count int64 s.Require().NoError(s.db.Model(&automation.CsatSurveyResponse{}).Where("message_id = ?", message.ID).Count(&count).Error) assert.Equal(s.T(), int64(1), count) s.Require().NoError(s.db.Where("message_id = ?", message.ID).First(&stored).Error) assert.Equal(s.T(), 2, stored.Rating) assert.Equal(s.T(), "Could be better", stored.FeedbackMessage) } 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 } func (s *CsatSurveyHandlerTestSuite) seedAccountCsatResponseGraph(createdAt time.Time, rating int) (*model.User, *model.User, *model.Contact, *model.Conversation, *model.Message) { agent := &model.User{AccountID: s.account.ID, Name: "CSAT Agent", Email: "csat-agent@example.com", Role: "agent", Active: true} reviewer := &model.User{AccountID: s.account.ID, Name: "CSAT Reviewer", Email: "csat-reviewer@example.com", Role: "administrator", Active: true} s.Require().NoError(s.db.Create(agent).Error) s.Require().NoError(s.db.Create(reviewer).Error) s.Require().NoError(s.db.Create(&model.AccountUser{AccountID: s.account.ID, UserID: agent.ID, Role: "agent"}).Error) s.Require().NoError(s.db.Create(&model.AccountUser{AccountID: s.account.ID, UserID: reviewer.ID, Role: "administrator"}).Error) contact := &model.Contact{AccountID: s.account.ID, Name: "CSAT Contact", Email: "csat@example.com", PhoneNumber: "+15550000"} s.Require().NoError(s.db.Create(contact).Error) inbox := &model.Inbox{AccountID: s.account.ID, Name: "CSAT Inbox", ChannelType: "web_widget", Enabled: true} s.Require().NoError(s.db.Create(inbox).Error) displayID := uint(42) teamID := uint(7) conversation := &model.Conversation{ AccountID: s.account.ID, DisplayID: &displayID, InboxID: inbox.ID, ContactID: contact.ID, AssigneeID: &agent.ID, TeamID: &teamID, Status: "resolved", ChannelType: "web_widget", Channel: "web_widget", } s.Require().NoError(s.db.Create(conversation).Error) message := &model.Message{ConversationID: conversation.ID, AccountID: s.account.ID, InboxID: inbox.ID, ContentType: "input_csat", MessageType: "outgoing", Content: "Rate this"} 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) reviewerID := reviewer.ID updatedAt := createdAt.Add(30 * time.Minute) response := &automation.CsatSurveyResponse{ AccountID: s.account.ID, ConversationID: conversation.ID, ContactID: contact.ID, MessageID: &message.ID, AssignedAgentID: &agent.ID, Rating: rating, FeedbackMessage: "Great", CsatReviewNotes: "Needs follow up", ReviewNotesUpdatedByID: &reviewerID, ReviewNotesUpdatedAt: &updatedAt, } s.Require().NoError(s.db.Create(response).Error) s.Require().NoError(s.db.Model(response).Updates(map[string]any{"created_at": createdAt, "updated_at": createdAt}).Error) return agent, reviewer, contact, conversation, message }