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/gochat/gochat/internal/repository" "github.com/gochat/gochat/internal/service" "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{}, &model.Audit{}, &automation.CsatSurveyResponse{}, &model.ReportingEventsRollup{}, )) s.db = db svc := automation.NewCsatSurveyService(&csatSurveyTestDBProvider{db: db}) auditSvc := service.NewAuditService(repository.NewAuditRepo(db)) s.handler = NewCsatSurveyHandler(svc).WithAuditService(auditSvc) 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 audits") 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) TestCSATFrontendContractShapes() { 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", s.handler.List) r.GET("/api/v1/accounts/:account_id/csat_survey_responses/metrics", s.handler.Metrics) r.GET("/api/v1/accounts/:account_id/csat_survey_responses/download", s.handler.Download) r.GET("/public/api/v1/csat_survey/:id", s.handler.PublicGet) r.PATCH("/public/api/v1/csat_survey/:id", s.handler.PublicUpdate) listURL := fmt.Sprintf("/api/v1/accounts/%d/csat_survey_responses?page=1&since=%d&until=%d&user_ids=%d&inbox_id=%d&team_id=%d&rating=5&sort=-created_at", s.account.ID, createdAt.Add(-time.Hour).Unix(), createdAt.Add(time.Hour).Unix(), agent.ID, conversation.InboxID, *conversation.TeamID) list := httptest.NewRecorder() reqList, _ := http.NewRequest(http.MethodGet, listURL, nil) r.ServeHTTP(list, reqList) assert.Equal(s.T(), http.StatusOK, list.Code) listPayload := decodeCSATArray(s.T(), list.Body.String()) s.Require().Len(listPayload, 1) assertChatwootCSATListItemShape(s.T(), listPayload[0]) assert.Equal(s.T(), float64(42), listPayload[0]["conversation_id"]) metricsURL := fmt.Sprintf("/api/v1/accounts/%d/csat_survey_responses/metrics?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, *conversation.TeamID) metrics := httptest.NewRecorder() reqMetrics, _ := http.NewRequest(http.MethodGet, metricsURL, nil) r.ServeHTTP(metrics, reqMetrics) assert.Equal(s.T(), http.StatusOK, metrics.Code) metricsPayload := decodeCSATObject(s.T(), metrics.Body.String()) assertChatwootCSATMetricsShape(s.T(), metricsPayload) assert.Equal(s.T(), float64(1), metricsPayload["total_count"]) download := httptest.NewRecorder() reqDownload, _ := http.NewRequest(http.MethodGet, metricsURL[:strings.Index(metricsURL, "/metrics")]+"/download"+metricsURL[strings.Index(metricsURL, "?"):], nil) reqDownload.Host = "gochat.test" reqDownload.Header.Set("X-Forwarded-Proto", "https") r.ServeHTTP(download, reqDownload) assert.Equal(s.T(), http.StatusOK, download.Code) assertChatwootCSATCSVShape(s.T(), download, []string{"Agent Name", "Rating", "Feedback Comment", "Contact Name", "Contact Email Address", "Contact Phone Number", "Link to the conversation", "Recorded date", "Review Notes"}) publicConversation, _ := s.seedPublicCsatSurvey(createdAt) show := httptest.NewRecorder() reqShow, _ := http.NewRequest(http.MethodGet, "/public/api/v1/csat_survey/"+publicConversation.UUID, nil) r.ServeHTTP(show, reqShow) assert.Equal(s.T(), http.StatusOK, show.Code) showPayload := decodeCSATObject(s.T(), show.Body.String()) assertChatwootPublicCSATShape(s.T(), showPayload) assert.Nil(s.T(), showPayload["csat_survey_response"]) update := httptest.NewRecorder() body := `{"message":{"submitted_values":{"csat_survey_response":{"rating":4,"feedback_message":"Helpful"}}}}` reqUpdate, _ := http.NewRequest(http.MethodPatch, "/public/api/v1/csat_survey/"+publicConversation.UUID, bytes.NewBufferString(body)) reqUpdate.Header.Set("Content-Type", "application/json") r.ServeHTTP(update, reqUpdate) assert.Equal(s.T(), http.StatusOK, update.Code) updatePayload := decodeCSATObject(s.T(), update.Body.String()) assertChatwootPublicCSATShape(s.T(), updatePayload) csatResponse := updatePayload["csat_survey_response"].(map[string]any) assert.Equal(s.T(), float64(4), csatResponse["rating"]) assert.Equal(s.T(), "Helpful", csatResponse["feedback_message"]) } func (s *CsatSurveyHandlerTestSuite) TestList_IgnoresPerPageAndUsesChatwootFixedPageSize() { createdAt := time.Now().Add(-2 * time.Hour).Truncate(time.Second) _, _, contact, conversation, _ := s.seedAccountCsatResponseGraph(createdAt, 5) for i := 0; i < 29; i++ { response := &automation.CsatSurveyResponse{ AccountID: s.account.ID, ConversationID: conversation.ID, ContactID: contact.ID, Rating: 4, } s.Require().NoError(s.db.Create(response).Error) recordedAt := createdAt.Add(time.Duration(i+1) * time.Minute) s.Require().NoError(s.db.Model(response).Updates(map[string]any{"created_at": recordedAt, "updated_at": recordedAt}).Error) } r := gin.New() r.GET("/api/v1/accounts/:account_id/csat_survey_responses", s.handler.List) w := httptest.NewRecorder() req, _ := http.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/%d/csat_survey_responses?page=1&per_page=5", s.account.ID), 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, 25) } func (s *CsatSurveyHandlerTestSuite) TestList_UsesChatwootDateRangeBoundary() { baseTime := time.Now().Add(-2 * time.Hour).Truncate(time.Second) _, _, contact, conversation, _ := s.seedAccountCsatResponseGraph(baseTime.Add(30*time.Minute), 5) onUntil := &automation.CsatSurveyResponse{AccountID: s.account.ID, ConversationID: conversation.ID, ContactID: contact.ID, Rating: 4} s.Require().NoError(s.db.Create(onUntil).Error) s.Require().NoError(s.db.Model(onUntil).Updates(map[string]any{"created_at": baseTime.Add(time.Hour), "updated_at": baseTime.Add(time.Hour)}).Error) r := gin.New() r.GET("/api/v1/accounts/:account_id/csat_survey_responses", s.handler.List) w := httptest.NewRecorder() req, _ := http.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/%d/csat_survey_responses?since=%d", s.account.ID, baseTime.Add(30*time.Minute).Unix()), 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, 2) w = httptest.NewRecorder() req, _ = http.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/%d/csat_survey_responses?since=%d&until=%d", s.account.ID, baseTime.Unix(), baseTime.Add(time.Hour).Unix()), nil) r.ServeHTTP(w, req) assert.Equal(s.T(), http.StatusOK, w.Code) payload = nil s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &payload)) s.Require().Len(payload, 1) assert.Equal(s.T(), float64(5), payload[0]["rating"]) } 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) TestMetrics_DashboardValueDriftFiltersMatchChatwootFrontend() { baseTime := time.Now().Add(-6 * time.Hour).Truncate(time.Second) agent, _, contact, conversation, _ := s.seedAccountCsatResponseGraph(baseTime.Add(10*time.Minute), 5) s.Require().NoError(s.db.Create(&automation.CsatSurveyResponse{ AccountID: s.account.ID, ConversationID: conversation.ID, ContactID: contact.ID, AssignedAgentID: &agent.ID, Rating: 4, FeedbackMessage: "Good enough", }).Error) s.Require().NoError(s.db.Model(&automation.CsatSurveyResponse{}).Where("rating = ?", 4).Updates(map[string]any{"created_at": baseTime.Add(20 * time.Minute), "updated_at": baseTime.Add(20 * time.Minute)}).Error) otherAgent := &model.User{AccountID: s.account.ID, Name: "Other CSAT Agent", Email: "other-csat-agent@example.com", Role: "agent", Active: true} s.Require().NoError(s.db.Create(otherAgent).Error) s.Require().NoError(s.db.Create(&model.AccountUser{AccountID: s.account.ID, UserID: otherAgent.ID, Role: "agent"}).Error) otherContact := &model.Contact{AccountID: s.account.ID, Name: "Other CSAT Contact"} s.Require().NoError(s.db.Create(otherContact).Error) otherInbox := &model.Inbox{AccountID: s.account.ID, Name: "Other CSAT Inbox", ChannelType: "web_widget", Enabled: true} s.Require().NoError(s.db.Create(otherInbox).Error) otherTeamID := uint(99) otherConversation := &model.Conversation{AccountID: s.account.ID, InboxID: otherInbox.ID, ContactID: otherContact.ID, AssigneeID: &otherAgent.ID, TeamID: &otherTeamID, Status: "resolved", ChannelType: "web_widget", Channel: "web_widget"} s.Require().NoError(s.db.Create(otherConversation).Error) otherMessage := &model.Message{ConversationID: otherConversation.ID, AccountID: s.account.ID, InboxID: otherInbox.ID, ContentType: "input_csat", MessageType: "outgoing", Content: "Rate other"} s.Require().NoError(s.db.Create(otherMessage).Error) s.Require().NoError(s.db.Model(otherMessage).Updates(map[string]any{"created_at": baseTime.Add(25 * time.Minute), "updated_at": baseTime.Add(25 * time.Minute)}).Error) s.Require().NoError(s.db.Create(&automation.CsatSurveyResponse{AccountID: s.account.ID, ConversationID: otherConversation.ID, ContactID: otherContact.ID, AssignedAgentID: &otherAgent.ID, Rating: 1}).Error) s.Require().NoError(s.db.Model(&automation.CsatSurveyResponse{}).Where("rating = ?", 1).Updates(map[string]any{"created_at": baseTime.Add(25 * time.Minute), "updated_at": baseTime.Add(25 * time.Minute)}).Error) outOfRange := &automation.CsatSurveyResponse{AccountID: s.account.ID, ConversationID: conversation.ID, ContactID: contact.ID, AssignedAgentID: &agent.ID, Rating: 3} s.Require().NoError(s.db.Create(outOfRange).Error) s.Require().NoError(s.db.Model(outOfRange).Updates(map[string]any{"created_at": baseTime.Add(3 * time.Hour), "updated_at": baseTime.Add(3 * time.Hour)}).Error) 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&team_id=%d", s.account.ID, baseTime.Unix(), baseTime.Add(time.Hour).Unix(), agent.ID, conversation.InboxID, *conversation.TeamID) w := httptest.NewRecorder() req, _ := http.NewRequest(http.MethodGet, 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(2), payload["total_count"]) assert.Equal(s.T(), float64(2), payload["total_sent_messages_count"]) ratings := payload["ratings_count"].(map[string]any) assert.Equal(s.T(), float64(1), ratings["5"]) assert.Equal(s.T(), float64(1), ratings["4"]) assert.NotContains(s.T(), ratings, "1") assert.NotContains(s.T(), ratings, "3") ratingURL := url + "&rating=4" w = httptest.NewRecorder() req, _ = http.NewRequest(http.MethodGet, ratingURL, nil) r.ServeHTTP(w, req) assert.Equal(s.T(), http.StatusOK, w.Code) payload = nil s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &payload)) assert.Equal(s.T(), float64(1), payload["total_count"]) assert.Equal(s.T(), float64(2), payload["total_sent_messages_count"]) ratings = payload["ratings_count"].(map[string]any) assert.Equal(s.T(), float64(1), ratings["4"]) assert.NotContains(s.T(), 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(), "2026-06-05 10:30:00 UTC", 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) TestDownload_FormatsRecordedAtLikeChatwootCSV() { recordedAt := time.Date(2026, 6, 5, 10, 30, 0, 0, time.UTC) assert.Equal(s.T(), "2026-06-05 10:30:00 UTC", formatCsatCSVTimestamp(recordedAt)) } 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() { _, reviewer, _, _, _ := s.seedAccountCsatResponseGraph(time.Now().Add(-time.Hour), 5) var survey automation.CsatSurveyResponse s.Require().NoError(s.db.First(&survey).Error) originalRating := survey.Rating r := gin.New() r.PATCH("/api/v1/accounts/:account_id/csat_survey_responses/:id", func(c *gin.Context) { c.Set("user_id", float64(reviewer.ID)) s.handler.Update(c) }) w := httptest.NewRecorder() body := `{"csat_review_notes":"updated notes","rating":1,"feedback_message":"ignored"}` req, _ := http.NewRequest("PATCH", fmt.Sprintf("/api/v1/accounts/%d/csat_survey_responses/%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) var payload map[string]any s.Require().NoError(json.Unmarshal(w.Body.Bytes(), &payload)) assert.Equal(s.T(), "updated notes", payload["csat_review_notes"]) assert.Equal(s.T(), float64(originalRating), payload["rating"]) reviewerPayload := payload["review_notes_updated_by"].(map[string]any) assert.Equal(s.T(), reviewer.Name, reviewerPayload["name"]) } func (s *CsatSurveyHandlerTestSuite) TestUpdate_ChatwootReviewNotesAuditAndSerializerParity() { _, reviewer, _, conversation, _ := s.seedAccountCsatResponseGraph(time.Now().Add(-time.Hour), 5) var survey automation.CsatSurveyResponse s.Require().NoError(s.db.First(&survey).Error) r := gin.New() r.PATCH("/api/v1/accounts/:account_id/csat_survey_responses/:id", func(c *gin.Context) { c.Set("account_id", s.account.ID) c.Set("user_id", reviewer.ID) s.handler.Update(c) }) w := httptest.NewRecorder() body := `{"csat_review_notes":"dashboard review note","rating":1,"feedback_message":"must stay unchanged"}` req, _ := http.NewRequest(http.MethodPatch, fmt.Sprintf("/api/v1/accounts/%d/csat_survey_responses/%d", s.account.ID, survey.ID), bytes.NewBufferString(body)) req.Header.Set("Content-Type", "application/json") req.Header.Set("X-Request-ID", "csat-review-note-audit") req.RemoteAddr = "203.0.113.44:1234" 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(), "dashboard review note", payload["csat_review_notes"]) assert.Equal(s.T(), float64(survey.Rating), payload["rating"]) assert.Equal(s.T(), survey.FeedbackMessage, payload["feedback_message"]) assert.Equal(s.T(), float64(*conversation.DisplayID), payload["conversation_id"]) assert.NotNil(s.T(), payload["review_notes_updated_at"]) reviewerPayload := payload["review_notes_updated_by"].(map[string]any) assert.Equal(s.T(), reviewer.Name, reviewerPayload["name"]) var persisted automation.CsatSurveyResponse s.Require().NoError(s.db.First(&persisted, survey.ID).Error) assert.Equal(s.T(), "dashboard review note", persisted.CsatReviewNotes) assert.Equal(s.T(), survey.Rating, persisted.Rating) assert.Equal(s.T(), survey.FeedbackMessage, persisted.FeedbackMessage) s.Require().NotNil(persisted.ReviewNotesUpdatedByID) assert.Equal(s.T(), reviewer.ID, *persisted.ReviewNotesUpdatedByID) s.Require().NotNil(persisted.ReviewNotesUpdatedAt) var audits []model.Audit s.Require().NoError(s.db.Order("id ASC").Find(&audits).Error) s.Require().Len(audits, 1) audit := audits[0] s.Require().NotNil(audit.AccountID) assert.Equal(s.T(), s.account.ID, *audit.AccountID) assert.Equal(s.T(), "CsatSurveyResponse", audit.AuditableType) assert.Equal(s.T(), survey.ID, audit.AuditableID) assert.Equal(s.T(), "update", audit.Action) assert.Equal(s.T(), "csat-review-note-audit", audit.RequestUUID) s.Require().NotNil(audit.UserID) assert.Equal(s.T(), reviewer.ID, *audit.UserID) var changes map[string]any s.Require().NoError(json.Unmarshal(audit.AuditedChanges, &changes)) assert.Equal(s.T(), "dashboard review note", changes["csat_review_notes"]) } func (s *CsatSurveyHandlerTestSuite) TestUpdate_NotFoundAcrossAccountScope() { survey := &automation.CsatSurveyResponse{AccountID: s.account.ID + 1, ConversationID: 1, ContactID: 1, Rating: 5} s.Require().NoError(s.db.Create(survey).Error) r := gin.New() r.PATCH("/api/v1/accounts/:account_id/csat_survey_responses/:id", func(c *gin.Context) { c.Set("user_id", float64(1)) s.handler.Update(c) }) w := httptest.NewRecorder() body := `{"csat_review_notes":"updated notes"}` req, _ := http.NewRequest("PATCH", fmt.Sprintf("/api/v1/accounts/%d/csat_survey_responses/%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.StatusNotFound, 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, message := 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") var count int64 s.Require().NoError(s.db.Model(&automation.CsatSurveyResponse{}).Where("message_id = ?", message.ID).Count(&count).Error) assert.Equal(s.T(), int64(0), count) var storedMessage model.Message s.Require().NoError(s.db.First(&storedMessage, message.ID).Error) assert.JSONEq(s.T(), `{}`, string(storedMessage.ContentAttributes)) } func (s *CsatSurveyHandlerTestSuite) TestPublicCsatUpdate_ChatwootPutPersistsShowPayload() { conversation, message := s.seedPublicCsatSurvey(time.Now().Add(-time.Hour)) r := gin.New() r.PUT("/public/api/v1/csat_survey/:id", s.handler.PublicUpdate) r.GET("/public/api/v1/csat_survey/:id", s.handler.PublicGet) var count int64 s.Require().NoError(s.db.Model(&automation.CsatSurveyResponse{}).Where("message_id = ?", message.ID).Count(&count).Error) assert.Equal(s.T(), int64(0), count) valid := httptest.NewRecorder() validBody := `{"message":{"submitted_values":{"csat_survey_response":{"rating":5,"feedback_message":"great via put"}}}}` validReq, _ := http.NewRequest(http.MethodPut, "/public/api/v1/csat_survey/"+conversation.UUID, bytes.NewBufferString(validBody)) validReq.Header.Set("Content-Type", "application/json") r.ServeHTTP(valid, validReq) assert.Equal(s.T(), http.StatusOK, valid.Code) var updatePayload map[string]any s.Require().NoError(json.Unmarshal(valid.Body.Bytes(), &updatePayload)) assertChatwootPublicCSATShape(s.T(), updatePayload) csatResp := updatePayload["csat_survey_response"].(map[string]any) assert.Equal(s.T(), float64(5), csatResp["rating"]) assert.Equal(s.T(), "great via put", csatResp["feedback_message"]) show := httptest.NewRecorder() showReq, _ := http.NewRequest(http.MethodGet, "/public/api/v1/csat_survey/"+conversation.UUID, nil) r.ServeHTTP(show, showReq) assert.Equal(s.T(), http.StatusOK, show.Code) var showPayload map[string]any s.Require().NoError(json.Unmarshal(show.Body.Bytes(), &showPayload)) assertChatwootPublicCSATShape(s.T(), showPayload) showResp := showPayload["csat_survey_response"].(map[string]any) assert.Equal(s.T(), float64(5), showResp["rating"]) assert.Equal(s.T(), "great via put", showResp["feedback_message"]) } 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 } func decodeCSATObject(t *testing.T, body string) map[string]any { t.Helper() payload := map[string]any{} if err := json.Unmarshal([]byte(body), &payload); err != nil { t.Fatalf("expected JSON object: %v\n%s", err, body) } return payload } func decodeCSATArray(t *testing.T, body string) []map[string]any { t.Helper() payload := []map[string]any{} if err := json.Unmarshal([]byte(body), &payload); err != nil { t.Fatalf("expected JSON array: %v\n%s", err, body) } return payload } func assertChatwootCSATListItemShape(t *testing.T, payload map[string]any) { t.Helper() for _, key := range []string{"id", "rating", "feedback_message", "csat_review_notes", "review_notes_updated_at", "account_id", "message_id", "conversation_id", "created_at", "contact", "assigned_agent", "review_notes_updated_by"} { if _, ok := payload[key]; !ok { t.Fatalf("expected CSAT list item to include %q, got %#v", key, payload) } } assertNestedKeys(t, payload["contact"], []string{"id", "name", "email"}) assertNestedKeys(t, payload["assigned_agent"], []string{"id", "name", "email"}) assertNestedKeys(t, payload["review_notes_updated_by"], []string{"id", "name"}) } func assertChatwootCSATMetricsShape(t *testing.T, payload map[string]any) { t.Helper() for _, key := range []string{"total_count", "ratings_count", "total_sent_messages_count"} { if _, ok := payload[key]; !ok { t.Fatalf("expected CSAT metrics to include %q, got %#v", key, payload) } } } func assertChatwootCSATCSVShape(t *testing.T, recorder *httptest.ResponseRecorder, expectedHeaders []string) { t.Helper() if contentType := recorder.Header().Get("Content-Type"); !strings.Contains(contentType, "text/csv") { t.Fatalf("expected CSV content type, got %q", contentType) } if disposition := recorder.Header().Get("Content-Disposition"); !strings.Contains(disposition, "csat_report.csv") { t.Fatalf("expected CSAT CSV attachment, got %q", disposition) } rows := readCSATCSVRows(t, recorder.Body.String()) if len(rows) < 2 { t.Fatalf("expected CSAT CSV header and data rows, got %#v", rows) } if len(rows[0]) != len(expectedHeaders) { t.Fatalf("expected CSAT CSV headers %#v, got %#v", expectedHeaders, rows[0]) } for idx, expected := range expectedHeaders { if rows[0][idx] != expected { t.Fatalf("expected CSAT CSV headers %#v, got %#v", expectedHeaders, rows[0]) } } } func readCSATCSVRows(t *testing.T, body string) [][]string { t.Helper() reader := csv.NewReader(strings.NewReader(body)) reader.FieldsPerRecord = -1 rows, err := reader.ReadAll() if err != nil { t.Fatalf("failed to read CSAT CSV: %v\n%s", err, body) } return rows } func assertChatwootPublicCSATShape(t *testing.T, payload map[string]any) { t.Helper() for _, key := range []string{"id", "content", "display_type", "inbox_name", "inbox_avatar_url", "locale", "conversation_id", "created_at", "csat_survey_response"} { if _, ok := payload[key]; !ok { t.Fatalf("expected public CSAT payload to include %q, got %#v", key, payload) } } if payload["csat_survey_response"] != nil { assertNestedKeys(t, payload["csat_survey_response"], []string{"rating", "feedback_message"}) } } func assertNestedKeys(t *testing.T, payload any, keys []string) { t.Helper() object, ok := payload.(map[string]any) if !ok { t.Fatalf("expected nested object, got %#v", payload) } for _, key := range keys { if _, ok := object[key]; !ok { t.Fatalf("expected nested object to include %q, got %#v", key, object) } } }