From 79042add0187e4b496995052c3372749d2f21f2b Mon Sep 17 00:00:00 2001 From: Rogee Date: Thu, 4 Jun 2026 22:57:15 +0800 Subject: [PATCH] feat(public): implement chatwoot csat survey flow --- docs/CHATWOOT_PARITY_DEVELOPMENT_PLAN.md | 5 +- internal/automation/csat_survey_service.go | 229 ++++++++++++++++++ internal/automation/model.go | 37 +-- .../handler/api/v1/csat_survey_handler.go | 49 ++-- .../api/v1/csat_survey_handler_test.go | 120 ++++++++- internal/handler/widget/widget_handler.go | 3 + .../handler/widget/widget_handler_test.go | 61 +++++ internal/service/widget_service.go | 9 + 8 files changed, 474 insertions(+), 39 deletions(-) diff --git a/docs/CHATWOOT_PARITY_DEVELOPMENT_PLAN.md b/docs/CHATWOOT_PARITY_DEVELOPMENT_PLAN.md index 8e0726a6..64114472 100644 --- a/docs/CHATWOOT_PARITY_DEVELOPMENT_PLAN.md +++ b/docs/CHATWOOT_PARITY_DEVELOPMENT_PLAN.md @@ -402,7 +402,7 @@ Tracking table: | P6.3 | Conversation APIs | `docs/ROUTE_GAP_ANALYSIS.md`, conversation handlers/services | Implement frontend-critical filters, assignment, status, snooze, merge, bulk actions. | Todo | | P6.4 | Message APIs | `docs/ROUTE_GAP_ANALYSIS.md`, message handlers/services | Implement create/list/delete, private notes, attachments, source attribution, events. | Todo | | P6.5 | Inbox APIs | `docs/ROUTE_GAP_ANALYSIS.md`, inbox handlers/services | Implement CRUD, assignable agents, avatar, campaigns, channel settings, reset secret. | Todo | -| P6.6 | Widget/public APIs | `docs/ROUTE_GAP_ANALYSIS.md`, widget/channel provider code, `chatwootParityStub` routes | Finish deeper public CSAT parity; public inbox/contact/conversation/message core flow and widget direct uploads/attachments are now handler-backed. | Doing | +| P6.6 | Widget/public APIs | `docs/ROUTE_GAP_ANALYSIS.md`, widget/channel provider code, `chatwootParityStub` routes | Widget/public frontend-critical route behavior is handler-backed, including public inbox flow, direct uploads/attachments, and public CSAT survey submission. | Done | | P6.7 | Webhook ingress | `internal/router/router.go`, `internal/handler/webhook/*`, channel providers | Replace generic placeholder with provider-specific verified ingestion and dispatch. | Todo | Widget/public subtracking: @@ -414,7 +414,7 @@ Widget/public subtracking: | P6.6c | `/api/v1/widget` message update, transcript, `contact/set_user`, Dyte participant | Chatwoot widget message/contact/transcript/integration behavior | Done | | P6.6d | `/public/api/v1/inboxes` contact/conversation/message core flow | `reference/chatwoot/app/controllers/public/api/v1/inboxes/*` and matching jbuilder views | Done | | P6.6e | Widget direct uploads and attachments | Chatwoot active storage/direct upload and attachment payloads | Done | -| P6.6f | Public CSAT deep behavior | Chatwoot CSAT survey controller/listener and message locking rules | Todo | +| P6.6f | Public CSAT deep behavior | Chatwoot CSAT survey controller/listener and message locking rules | Done | ## Phase 7: Verification Harness @@ -479,3 +479,4 @@ Verification milestone gates: - 2026-06-04: Completed the remaining `/api/v1/widget` stub burn-down. Message update now persists submitted email/form values and identifies the contact; `contact/set_user` validates identifier HMAC, supports verified contact identification, and returns `widget_auth_token` when the contact context changes; conversation transcript returns Chatwoot-compatible status behavior around missing conversations; Dyte participant endpoint validates integration messages and returns a meeting token payload. Added model/repository support for contact inbox HMAC verification and identifier lookup. Public inbox/contact/conversation/message routes remain the next P6.6 placeholder group. - 2026-06-04: Replaced `/public/api/v1/inboxes` contact/conversation/message placeholders with real Chatwoot public API handlers. API inboxes now resolve through `Channel::Api` identifiers, public contacts create/update by `source_id` with optional identifier HMAC verification, public conversations enforce the same verified-contact visibility split, and public messages support create/list/update submitted values. Added focused public API handler flow coverage. Verified `go test ./...`, regenerated `docs/parity/gochat_routes.txt` (`TOTAL: 791`), and regenerated `docs/parity/route_parity.md` (`251 exact, 0 missing`). Remaining P6.6 work is direct uploads/attachments and deeper public CSAT behavior. - 2026-06-04: Completed P6.6e widget direct upload/attachment parity for the reused Chatwoot widget frontend. `/api/v1/widget/direct_uploads` now accepts ActiveStorage metadata with `website_token` + `X-Auth-Token`, returns the raw `signed_id/direct_upload` blob shape expected by `DirectUpload`, supports the follow-up PUT body upload, and attaches `message[attachments][]` signed IDs to incoming widget messages. Message create/list payloads now include Chatwoot-style attachment fields (`data_url`, `thumb_url`, `file_type`, extension, size). Added focused handler coverage for ActiveStorage create/PUT and multipart attachment-only message send/list. Verified focused package tests and regenerated route artifacts; route dump now reports `TOTAL: 793`, while tracked parity remains `251 exact, 0 missing`. Remaining P6.6 work is deeper public CSAT behavior. +- 2026-06-04: Completed P6.6f public CSAT deep behavior. `/public/api/v1/csat_survey/:id` now resolves the conversation UUID to the `input_csat` message and returns the Chatwoot public survey payload (`csat_survey_response`, display type, inbox avatar/name, locale, conversation/message IDs). Public CSAT submit now accepts nested `message.submitted_values`, updates the survey message content attributes, upserts a message-linked CSAT response, and enforces Chatwoot's 14-day lock with `422`. Public inbox message update now applies the same lock/response-builder path for `input_csat` messages. Added handler coverage for public CSAT show/update/lock and public inbox CSAT message update/lock. Focused package tests passed. diff --git a/internal/automation/csat_survey_service.go b/internal/automation/csat_survey_service.go index f202d052..ef35aab3 100644 --- a/internal/automation/csat_survey_service.go +++ b/internal/automation/csat_survey_service.go @@ -2,9 +2,14 @@ package automation import ( "context" + "encoding/json" + "errors" "fmt" + "strconv" "time" + "github.com/gochat/gochat/internal/model" + "gorm.io/datatypes" "gorm.io/gorm" ) @@ -49,6 +54,18 @@ type CsatMetrics struct { AverageRating float64 `json:"average_rating"` } +type PublicCsatSurvey struct { + ID uint `json:"id"` + CsatSurveyResponse *CsatSurveyResponse `json:"csat_survey_response"` + DisplayType string `json:"display_type"` + Content string `json:"content"` + InboxAvatarURL string `json:"inbox_avatar_url"` + InboxName string `json:"inbox_name"` + Locale string `json:"locale"` + ConversationID uint `json:"conversation_id"` + CreatedAt time.Time `json:"created_at"` +} + // GetByID retrieves a CSAT survey response by ID. func (s *CsatSurveyService) GetByID(ctx context.Context, id uint) (*CsatSurveyResponse, error) { var resp CsatSurveyResponse @@ -79,6 +96,28 @@ func (s *CsatSurveyService) GetByConversationUUID(ctx context.Context, conversat return &resp, nil } +func (s *CsatSurveyService) GetPublicSurveyByConversationUUID(ctx context.Context, conversationUUID string) (*PublicCsatSurvey, error) { + message, conversation, inbox, account, err := s.findPublicCsatMessage(ctx, conversationUUID) + if err != nil { + return nil, err + } + return s.publicCsatPayload(ctx, message, conversation, inbox, account) +} + +func (s *CsatSurveyService) SubmitPublicSurveyByConversationUUID(ctx context.Context, conversationUUID string, submittedValues []map[string]any) (*PublicCsatSurvey, error) { + message, conversation, inbox, account, err := s.findPublicCsatMessage(ctx, conversationUUID) + if err != nil { + return nil, err + } + if IsCsatSurveyLocked(message.CreatedAt, time.Now()) { + return nil, ErrCsatSurveyLocked + } + if _, err := ApplyCsatSubmission(ctx, s.db.DB(), message, conversation, submittedValues); err != nil { + return nil, err + } + return s.publicCsatPayload(ctx, message, conversation, inbox, account) +} + // ListByAccount retrieves CSAT survey responses for an account with optional filters. func (s *CsatSurveyService) ListByAccount(ctx context.Context, accountID uint, filter CsatListFilter) ([]CsatSurveyResponse, int, error) { var responses []CsatSurveyResponse @@ -147,6 +186,120 @@ func (s *CsatSurveyService) UpdateResponse(ctx context.Context, id uint, rating }).Error } +var ErrCsatSurveyLocked = errors.New("You cannot update the CSAT survey after 14 days") + +func ApplyCsatSubmission(ctx context.Context, db *gorm.DB, message *model.Message, conversation *model.Conversation, submittedValues []map[string]any) (*CsatSurveyResponse, error) { + if message.ContentType != "input_csat" { + return nil, errors.New("invalid CSAT survey message") + } + rating, feedback, ok := ExtractCsatSubmittedValues(submittedValues) + if !ok { + return nil, errors.New("csat rating is required") + } + if rating < 1 || rating > 5 { + return nil, fmt.Errorf("rating must be between 1 and 5") + } + + attrs := jsonMap(message.ContentAttributes) + attrs["submitted_values"] = submittedValues + message.ContentAttributes = mustJSON(attrs) + if err := db.WithContext(ctx).Save(message).Error; err != nil { + return nil, err + } + + var resp CsatSurveyResponse + messageID := message.ID + err := db.WithContext(ctx).Where("message_id = ?", message.ID).First(&resp).Error + if err != nil { + if !errors.Is(err, gorm.ErrRecordNotFound) { + return nil, err + } + resp = CsatSurveyResponse{ + AccountID: message.AccountID, + ConversationID: message.ConversationID, + ContactID: conversation.ContactID, + MessageID: &messageID, + AssignedAgentID: conversation.AssigneeID, + } + } + resp.Rating = rating + resp.FeedbackMessage = feedback + if err := db.WithContext(ctx).Save(&resp).Error; err != nil { + return nil, err + } + return &resp, nil +} + +func ExtractCsatSubmittedValues(submittedValues []map[string]any) (int, string, bool) { + for _, value := range submittedValues { + if raw, ok := value["csat_survey_response"]; ok { + if rating, feedback, ok := extractCsatResponse(raw); ok { + return rating, feedback, true + } + } + if rating, ok := intValue(value["rating"]); ok { + feedback, _ := value["feedback_message"].(string) + return rating, feedback, true + } + } + return 0, "", false +} + +func IsCsatSurveyLocked(createdAt, now time.Time) bool { + createdDate := dateOnly(createdAt) + nowDate := dateOnly(now.In(createdAt.Location())) + return nowDate.Sub(createdDate) > 14*24*time.Hour +} + +func (s *CsatSurveyService) findPublicCsatMessage(ctx context.Context, conversationUUID string) (*model.Message, *model.Conversation, *model.Inbox, *model.Account, error) { + var conversation model.Conversation + if err := s.db.DB().WithContext(ctx).Where("uuid = ?", conversationUUID).First(&conversation).Error; err != nil { + return nil, nil, nil, nil, fmt.Errorf("conversation not found: %w", err) + } + var message model.Message + if err := s.db.DB().WithContext(ctx). + Where("conversation_id = ? AND content_type = ?", conversation.ID, "input_csat"). + Order("id ASC").First(&message).Error; err != nil { + return nil, nil, nil, nil, fmt.Errorf("csat survey message not found: %w", err) + } + var inbox model.Inbox + if err := s.db.DB().WithContext(ctx).First(&inbox, conversation.InboxID).Error; err != nil { + return nil, nil, nil, nil, err + } + var account model.Account + if err := s.db.DB().WithContext(ctx).First(&account, conversation.AccountID).Error; err != nil { + return nil, nil, nil, nil, err + } + return &message, &conversation, &inbox, &account, nil +} + +func (s *CsatSurveyService) publicCsatPayload(ctx context.Context, message *model.Message, conversation *model.Conversation, inbox *model.Inbox, account *model.Account) (*PublicCsatSurvey, error) { + var resp CsatSurveyResponse + var responsePtr *CsatSurveyResponse + if err := s.db.DB().WithContext(ctx).Where("message_id = ?", message.ID).First(&resp).Error; err == nil { + responsePtr = &resp + } else if !errors.Is(err, gorm.ErrRecordNotFound) { + return nil, err + } + config := csatConfigMap(inbox.CsatConfig) + displayType, _ := config["display_type"].(string) + if displayType == "" { + displayType = "emoji" + } + content, _ := config["message"].(string) + return &PublicCsatSurvey{ + ID: message.ID, + CsatSurveyResponse: responsePtr, + DisplayType: displayType, + Content: content, + InboxAvatarURL: inbox.AvatarURL, + InboxName: inbox.Name, + Locale: account.Locale, + ConversationID: message.ConversationID, + CreatedAt: message.CreatedAt, + }, nil +} + // UpdateReviewNotes updates internal review notes on a CSAT response. // Reference: Chatwoot csat_review_notes update by agent func (s *CsatSurveyService) UpdateReviewNotes(ctx context.Context, id uint, notes string, updatedBy uint) error { @@ -223,3 +376,79 @@ func (s *CsatSurveyService) Metrics(ctx context.Context, accountID uint, filter return metrics, nil } + +func extractCsatResponse(raw any) (int, string, bool) { + response, ok := raw.(map[string]any) + if !ok { + return 0, "", false + } + rating, ok := intValue(response["rating"]) + if !ok { + return 0, "", false + } + feedback, _ := response["feedback_message"].(string) + return rating, feedback, true +} + +func intValue(raw any) (int, bool) { + switch value := raw.(type) { + case int: + return value, true + case int64: + return int(value), true + case uint: + return int(value), true + case uint64: + return int(value), true + case float64: + return int(value), true + case json.Number: + parsed, err := value.Int64() + return int(parsed), err == nil + case string: + parsed, err := strconv.Atoi(value) + return parsed, err == nil + default: + return 0, false + } +} + +func jsonMap(raw datatypes.JSON) map[string]any { + out := map[string]any{} + if len(raw) == 0 { + return out + } + _ = json.Unmarshal(raw, &out) + if out == nil { + out = map[string]any{} + } + return out +} + +func mustJSON(value map[string]any) datatypes.JSON { + if value == nil { + value = map[string]any{} + } + data, err := json.Marshal(value) + if err != nil { + return datatypes.JSON(`{}`) + } + return datatypes.JSON(data) +} + +func csatConfigMap(raw string) map[string]any { + out := map[string]any{} + if raw == "" { + return out + } + _ = json.Unmarshal([]byte(raw), &out) + if out == nil { + out = map[string]any{} + } + return out +} + +func dateOnly(value time.Time) time.Time { + year, month, day := value.Date() + return time.Date(year, month, day, 0, 0, 0, 0, value.Location()) +} diff --git a/internal/automation/model.go b/internal/automation/model.go index c31129b1..ff9455c5 100644 --- a/internal/automation/model.go +++ b/internal/automation/model.go @@ -47,7 +47,7 @@ func (c *Conditions) Scan(value interface{}) error { // Action represents a single action to execute when an automation rule matches. // Reference: Chatwoot automation_rule actions — {action_name, action_params} type Action struct { - ActionName string `json:"action_name"` + ActionName string `json:"action_name"` ActionParams map[string]interface{} `json:"action_params"` } @@ -111,13 +111,13 @@ const ( // Reference: Chatwoot Macro — account_id, name, actions, visibility, created_by_id, updated_by_id type Macro struct { model.Base - AccountID uint `gorm:"index;not null" json:"account_id"` - Name string `gorm:"size:255;not null" json:"name"` - Actions Actions `gorm:"type:jsonb;default:'[]'" json:"actions"` - Visibility MacroVisibility `gorm:"default:0" json:"visibility"` // 0=personal, 1=global - Active bool `gorm:"not null" json:"active"` // enable/disable macro execution - CreatedByID uint `gorm:"index;not null" json:"created_by_id"` - UpdatedByID uint `gorm:"index;not null" json:"updated_by_id"` + AccountID uint `gorm:"index;not null" json:"account_id"` + Name string `gorm:"size:255;not null" json:"name"` + Actions Actions `gorm:"type:jsonb;default:'[]'" json:"actions"` + Visibility MacroVisibility `gorm:"default:0" json:"visibility"` // 0=personal, 1=global + Active bool `gorm:"not null" json:"active"` // enable/disable macro execution + CreatedByID uint `gorm:"index;not null" json:"created_by_id"` + UpdatedByID uint `gorm:"index;not null" json:"updated_by_id"` } func (Macro) TableName() string { return "macros" } @@ -130,15 +130,16 @@ func (Macro) TableName() string { return "macros" } // Reference: Chatwoot CsatSurveyResponse — rating, feedback_message, conversation_id, account_id, assigned_agent_id type CsatSurveyResponse struct { model.Base - AccountID uint `gorm:"index;not null" json:"account_id"` - ConversationID uint `gorm:"index;not null" json:"conversation_id"` - ContactID uint `gorm:"index" json:"contact_id"` - AssignedAgentID *uint `gorm:"index" json:"assigned_agent_id,omitempty"` - Rating int `gorm:"not null" json:"rating"` // 1-5 scale - FeedbackMessage string `gorm:"type:text" json:"feedback_message,omitempty"` - CsatReviewNotes string `gorm:"type:text" json:"csat_review_notes,omitempty"` - ReviewNotesUpdatedByID *uint `gorm:"index" json:"review_notes_updated_by_id,omitempty"` - ReviewNotesUpdatedAt *time.Time `json:"review_notes_updated_at,omitempty"` + AccountID uint `gorm:"index;not null" json:"account_id"` + ConversationID uint `gorm:"index;not null" json:"conversation_id"` + ContactID uint `gorm:"index" json:"contact_id"` + MessageID *uint `gorm:"uniqueIndex" json:"message_id,omitempty"` + AssignedAgentID *uint `gorm:"index" json:"assigned_agent_id,omitempty"` + Rating int `gorm:"not null" json:"rating"` // 1-5 scale + FeedbackMessage string `gorm:"type:text" json:"feedback_message,omitempty"` + CsatReviewNotes string `gorm:"type:text" json:"csat_review_notes,omitempty"` + ReviewNotesUpdatedByID *uint `gorm:"index" json:"review_notes_updated_by_id,omitempty"` + ReviewNotesUpdatedAt *time.Time `json:"review_notes_updated_at,omitempty"` } func (CsatSurveyResponse) TableName() string { return "csat_survey_responses" } @@ -161,4 +162,4 @@ type AutomationExecution struct { ErrorMessage string `gorm:"type:text" json:"error_message,omitempty"` } -func (AutomationExecution) TableName() string { return "automation_executions" } \ No newline at end of file +func (AutomationExecution) TableName() string { return "automation_executions" } diff --git a/internal/handler/api/v1/csat_survey_handler.go b/internal/handler/api/v1/csat_survey_handler.go index 7a24e315..34610fb7 100644 --- a/internal/handler/api/v1/csat_survey_handler.go +++ b/internal/handler/api/v1/csat_survey_handler.go @@ -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. diff --git a/internal/handler/api/v1/csat_survey_handler_test.go b/internal/handler/api/v1/csat_survey_handler_test.go index 2a5a489a..e10e901d 100644 --- a/internal/handler/api/v1/csat_survey_handler_test.go +++ b/internal/handler/api/v1/csat_survey_handler_test.go @@ -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) -} \ No newline at end of file +} + +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 +} diff --git a/internal/handler/widget/widget_handler.go b/internal/handler/widget/widget_handler.go index c3e9c8e1..94c64d5a 100644 --- a/internal/handler/widget/widget_handler.go +++ b/internal/handler/widget/widget_handler.go @@ -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 } diff --git a/internal/handler/widget/widget_handler_test.go b/internal/handler/widget/widget_handler_test.go index 1b757f14..6bd1cdeb 100644 --- a/internal/handler/widget/widget_handler_test.go +++ b/internal/handler/widget/widget_handler_test.go @@ -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") +} diff --git a/internal/service/widget_service.go b/internal/service/widget_service.go index 362b9be3..a91fcd9f 100644 --- a/internal/service/widget_service.go +++ b/internal/service/widget_service.go @@ -12,6 +12,7 @@ import ( "strings" "time" + "github.com/gochat/gochat/internal/automation" "github.com/gochat/gochat/internal/model" channelmodel "github.com/gochat/gochat/internal/model/channel" "github.com/gochat/gochat/internal/repository" @@ -807,12 +808,20 @@ func (s *WidgetService) PublicUpdateMessage(ctx context.Context, inboxIdentifier } attrs := jsonMap(message.ContentAttributes) if req.SubmittedValues != nil { + if message.ContentType == "input_csat" && automation.IsCsatSurveyLocked(message.CreatedAt, time.Now()) { + return nil, nil, automation.ErrCsatSurveyLocked + } attrs["submitted_values"] = req.SubmittedValues message.ContentAttributes = mustJSON(attrs) } if err := s.messageRepo.Update(ctx, message); err != nil { return nil, nil, err } + if message.ContentType == "input_csat" && req.SubmittedValues != nil { + if _, err := automation.ApplyCsatSubmission(ctx, s.messageRepo.DB(), message, conversation, req.SubmittedValues); err != nil { + return nil, nil, err + } + } return message, conversation, nil }