feat(reporting): align account events
This commit is contained in:
@@ -2,6 +2,8 @@ package v1
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
@@ -20,8 +22,10 @@ func NewReportingEventHandler(svc *service.ReportingEventService) *ReportingEven
|
||||
return &ReportingEventHandler{svc: svc}
|
||||
}
|
||||
|
||||
// List retrieves reporting events for an account with optional date range filtering.
|
||||
// GET /api/v1/accounts/:account_id/reporting_events?since=2024-01-01T00:00:00Z&until=2024-12-31T23:59:59Z&metric=message_created
|
||||
const chatwootReportingEventsPerPage = 25
|
||||
|
||||
// List retrieves reporting events for an account with Chatwoot filters and pagination.
|
||||
// GET /api/v1/accounts/:account_id/reporting_events?since=...&until=...&inbox_id=...&user_id=...&name=...&page=...
|
||||
func (h *ReportingEventHandler) List(c *gin.Context) {
|
||||
accountID, err := parseUintParam(c, "account_id")
|
||||
if err != nil {
|
||||
@@ -29,29 +33,81 @@ func (h *ReportingEventHandler) List(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
since, until, ok := parseDateRange(c)
|
||||
filter, ok := parseReportingEventListFilter(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
// Check for optional metric filter
|
||||
metric := c.Query("metric")
|
||||
|
||||
if metric != "" {
|
||||
events, svcErr := h.svc.GetByMetric(c.Request.Context(), accountID, metric, since, until)
|
||||
if svcErr != nil {
|
||||
handleServiceError(c, svcErr)
|
||||
return
|
||||
}
|
||||
response.OK(c, gin.H{"reporting_events": events})
|
||||
return
|
||||
}
|
||||
|
||||
events, svcErr := h.svc.ListByAccount(c.Request.Context(), accountID, since, until)
|
||||
result, svcErr := h.svc.ListAccountEvents(c.Request.Context(), accountID, filter)
|
||||
if svcErr != nil {
|
||||
handleServiceError(c, svcErr)
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, gin.H{"reporting_events": events})
|
||||
}
|
||||
payload := make([]gin.H, 0, len(result.Events))
|
||||
for i := range result.Events {
|
||||
payload = append(payload, serializeReportingEvent(result.Events[i]))
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"payload": payload,
|
||||
"meta": gin.H{
|
||||
"count": result.Total,
|
||||
"current_page": result.CurrentPage,
|
||||
"total_pages": result.TotalPages,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func parseReportingEventListFilter(c *gin.Context) (service.ReportingEventListFilter, bool) {
|
||||
page, err := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
if err != nil || page < 1 {
|
||||
page = 1
|
||||
}
|
||||
|
||||
inboxID, err := parseOptionalUintQueryParam(c, "inbox_id")
|
||||
if err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid inbox_id")
|
||||
return service.ReportingEventListFilter{}, false
|
||||
}
|
||||
userID, err := parseOptionalUintQueryParam(c, "user_id")
|
||||
if err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid user_id")
|
||||
return service.ReportingEventListFilter{}, false
|
||||
}
|
||||
|
||||
filter := service.ReportingEventListFilter{
|
||||
InboxID: inboxID,
|
||||
UserID: userID,
|
||||
Name: c.Query("name"),
|
||||
Page: page,
|
||||
PerPage: chatwootReportingEventsPerPage,
|
||||
}
|
||||
|
||||
sinceStr := c.Query("since")
|
||||
untilStr := c.Query("until")
|
||||
if sinceStr == "" || untilStr == "" {
|
||||
return filter, true
|
||||
}
|
||||
|
||||
since, err := parseUnixTimestamp(sinceStr)
|
||||
if err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid since date format")
|
||||
return service.ReportingEventListFilter{}, false
|
||||
}
|
||||
until, err := parseUnixTimestamp(untilStr)
|
||||
if err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid until date format")
|
||||
return service.ReportingEventListFilter{}, false
|
||||
}
|
||||
filter.Since = &since
|
||||
filter.Until = &until
|
||||
return filter, true
|
||||
}
|
||||
|
||||
func parseUnixTimestamp(value string) (time.Time, error) {
|
||||
seconds, err := strconv.ParseInt(value, 10, 64)
|
||||
if err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
return time.Unix(seconds, 0).UTC(), nil
|
||||
}
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/suite"
|
||||
@@ -41,6 +44,10 @@ 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)
|
||||
@@ -48,26 +55,124 @@ func (s *ReportingEventHandlerTestSuite) TestList_InvalidAccountID() {
|
||||
s.Equal(http.StatusBadRequest, w.Code)
|
||||
}
|
||||
|
||||
func (s *ReportingEventHandlerTestSuite) TestList_MissingDateRange() {
|
||||
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) TestList_WithMetric() {
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/accounts/1/reporting_events?since=2024-01-01T00:00:00Z&until=2024-12-31T23:59:59Z&metric=message_created", nil)
|
||||
s.router.ServeHTTP(w, req)
|
||||
// PG-specific SQL on SQLite may fail; accept both 200 and 500
|
||||
code := w.Code
|
||||
s.True(code == http.StatusOK || code == http.StatusUnprocessableEntity, "expected 200 or 500, got %d", 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
|
||||
}
|
||||
|
||||
func (s *ReportingEventHandlerTestSuite) TestList_NoMetric() {
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/accounts/1/reporting_events?since=2024-01-01T00:00:00Z&until=2024-12-31T23:59:59Z", nil)
|
||||
s.router.ServeHTTP(w, req)
|
||||
code := w.Code
|
||||
s.True(code == http.StatusOK || code == http.StatusUnprocessableEntity, "expected 200 or 500, got %d", code)
|
||||
}
|
||||
Reference in New Issue
Block a user