Files
gochat/internal/handler/api/v1/reporting_event_handler_test.go
T

179 lines
6.2 KiB
Go

package v1
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/suite"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"github.com/gochat/gochat/internal/model"
"github.com/gochat/gochat/internal/repository"
"github.com/gochat/gochat/internal/service"
)
type ReportingEventHandlerTestSuite struct {
suite.Suite
db *gorm.DB
handler *ReportingEventHandler
router *gin.Engine
}
func (s *ReportingEventHandlerTestSuite) SetupSuite() {
s.db, _ = gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
s.db.AutoMigrate(&model.ReportingEvent{}, &model.ReportingEventsRollup{})
repo := repository.NewReportingEventRepo(s.db)
svc := service.NewReportingEventService(repo)
s.handler = NewReportingEventHandler(svc)
gin.SetMode(gin.TestMode)
r := gin.New()
accountGroup := r.Group("/api/v1/accounts/:account_id")
accountGroup.GET("/reporting_events", s.handler.List)
s.router = r
}
func TestReportingEventHandlerTestSuite(t *testing.T) {
suite.Run(t, new(ReportingEventHandlerTestSuite))
}
func (s *ReportingEventHandlerTestSuite) TearDownTest() {
s.db.Exec("DELETE FROM reporting_events")
}
func (s *ReportingEventHandlerTestSuite) TestList_InvalidAccountID() {
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/v1/accounts/abc/reporting_events?since=2024-01-01T00:00:00Z&until=2024-12-31T23:59:59Z", nil)
s.router.ServeHTTP(w, req)
s.Equal(http.StatusBadRequest, w.Code)
}
func (s *ReportingEventHandlerTestSuite) TestList_ReturnsChatwootPayloadSortedByCreatedAtDesc() {
baseTime := time.Now().Add(-3 * time.Hour).UTC()
oldEvent := s.createEvent(1, "first_response", baseTime, nil, nil)
_ = s.createEvent(1, "resolution", baseTime.Add(time.Hour), nil, nil)
newEvent := s.createEvent(1, "reply_time", baseTime.Add(2*time.Hour), nil, nil)
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/v1/accounts/1/reporting_events", nil)
s.router.ServeHTTP(w, req)
s.Equal(http.StatusOK, w.Code, w.Body.String())
var resp map[string]any
s.NoError(json.Unmarshal(w.Body.Bytes(), &resp))
s.Contains(resp, "payload")
s.Contains(resp, "meta")
s.NotContains(resp, "success")
meta := resp["meta"].(map[string]any)
s.Equal(float64(3), meta["count"])
s.Equal(float64(1), meta["current_page"])
s.Equal(float64(1), meta["total_pages"])
payload := resp["payload"].([]any)
s.Len(payload, 3)
first := payload[0].(map[string]any)
last := payload[2].(map[string]any)
s.Equal(float64(newEvent.ID), first["id"])
s.Equal("reply_time", first["name"])
s.Equal(float64(oldEvent.ID), last["id"])
s.Equal("first_response", last["name"])
s.Contains(first, "value_in_business_hours")
s.Contains(first, "event_start_time")
s.Contains(first, "event_end_time")
}
func (s *ReportingEventHandlerTestSuite) TestList_FiltersByUnixDateRangeInboxUserAndName() {
baseTime := time.Now().Add(-4 * time.Hour).UTC().Truncate(time.Second)
inboxID := uint(10)
otherInboxID := uint(11)
userID := uint(20)
otherUserID := uint(21)
matched := s.createEvent(1, "first_response", baseTime.Add(2*time.Hour), &inboxID, &userID)
s.createEvent(1, "first_response", baseTime.Add(2*time.Hour), &otherInboxID, &userID)
s.createEvent(1, "first_response", baseTime.Add(2*time.Hour), &inboxID, &otherUserID)
s.createEvent(1, "reply_time", baseTime.Add(2*time.Hour), &inboxID, &userID)
s.createEvent(1, "first_response", baseTime.Add(30*time.Minute), &inboxID, &userID)
s.createEvent(2, "first_response", baseTime.Add(2*time.Hour), &inboxID, &userID)
w := httptest.NewRecorder()
url := fmt.Sprintf(
"/api/v1/accounts/1/reporting_events?since=%d&until=%d&inbox_id=%d&user_id=%d&name=first_response",
baseTime.Add(time.Hour).Unix(), baseTime.Add(3*time.Hour).Unix(), inboxID, userID,
)
req := httptest.NewRequest(http.MethodGet, url, nil)
s.router.ServeHTTP(w, req)
s.Equal(http.StatusOK, w.Code, w.Body.String())
var resp map[string]any
s.NoError(json.Unmarshal(w.Body.Bytes(), &resp))
payload := resp["payload"].([]any)
s.Len(payload, 1)
s.Equal(float64(matched.ID), payload[0].(map[string]any)["id"])
meta := resp["meta"].(map[string]any)
s.Equal(float64(1), meta["count"])
}
func (s *ReportingEventHandlerTestSuite) TestList_PaginatesAtChatwootFixedPageSize() {
baseTime := time.Now().Add(-40 * time.Hour).UTC()
for i := 0; i < 30; i++ {
s.createEvent(1, fmt.Sprintf("event_%02d", i), baseTime.Add(time.Duration(i)*time.Hour), nil, nil)
}
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/v1/accounts/1/reporting_events?page=2", nil)
s.router.ServeHTTP(w, req)
s.Equal(http.StatusOK, w.Code, w.Body.String())
var resp map[string]any
s.NoError(json.Unmarshal(w.Body.Bytes(), &resp))
payload := resp["payload"].([]any)
s.Len(payload, 5)
meta := resp["meta"].(map[string]any)
s.Equal(float64(30), meta["count"])
s.Equal(float64(2), meta["current_page"])
s.Equal(float64(2), meta["total_pages"])
}
func (s *ReportingEventHandlerTestSuite) TestList_InvalidFilters() {
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/v1/accounts/1/reporting_events?inbox_id=abc", nil)
s.router.ServeHTTP(w, req)
s.Equal(http.StatusBadRequest, w.Code)
w = httptest.NewRecorder()
req = httptest.NewRequest(http.MethodGet, "/api/v1/accounts/1/reporting_events?user_id=abc", nil)
s.router.ServeHTTP(w, req)
s.Equal(http.StatusBadRequest, w.Code)
w = httptest.NewRecorder()
req = httptest.NewRequest(http.MethodGet, "/api/v1/accounts/1/reporting_events?since=not-a-date&until=123", nil)
s.router.ServeHTTP(w, req)
s.Equal(http.StatusBadRequest, w.Code)
}
func (s *ReportingEventHandlerTestSuite) createEvent(accountID uint, name string, createdAt time.Time, inboxID, userID *uint) *model.ReportingEvent {
conversationID := uint(100 + createdAt.Unix()%1000)
event := &model.ReportingEvent{
Base: model.Base{CreatedAt: createdAt, UpdatedAt: createdAt},
AccountID: accountID,
Name: name,
Value: 12,
ValueInBusinessHours: 6,
ConversationID: &conversationID,
InboxID: inboxID,
UserID: userID,
EventStartTime: createdAt.Add(-time.Minute),
EventEndTime: createdAt,
}
s.Require().NoError(s.db.Create(event).Error)
return event
}