feat(reports): align year in review

This commit is contained in:
2026-06-06 20:36:13 +08:00
parent e2fdb8a171
commit 4a7df91556
11 changed files with 504 additions and 9 deletions
+2
View File
@@ -609,6 +609,7 @@ func Bootstrap(env string) (*App, error) {
// Analytics services (P11 — Reports/Analytics)
analyticsService := service.NewAnalyticsService(reportingEventRepo, reportingEventsRollupRepo)
analyticsService.SetWorkerPool(workerPool)
yearInReviewService := service.NewYearInReviewService(db)
summaryReportService := service.NewSummaryReportService(reportingEventsRollupRepo)
dashboardAppService := service.NewDashboardAppService(dashboardAppRepo)
platformAppService := service.NewPlatformAppService(platformAppRepo, accessTokenRepo, permissibleRepo)
@@ -772,6 +773,7 @@ func Bootstrap(env string) (*App, error) {
Copilot: v1.NewCopilotHandler(copilotService),
Analytics: v1.NewAnalyticsHandler(analyticsService),
LiveReport: v1.NewLiveReportHandler(analyticsService),
YearInReview: v1.NewYearInReviewHandler(yearInReviewService),
DashboardApp: v1.NewDashboardAppHandler(dashboardAppService),
Portal: v1.NewPortalHandler(portalService),
Category: v1.NewCategoryHandler(categoryService, portalService),
@@ -0,0 +1,58 @@
package v1
import (
"errors"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"github.com/gochat/gochat/internal/service"
"github.com/gochat/gochat/pkg/response"
"gorm.io/gorm"
)
// YearInReviewHandler serves Chatwoot API v2 year_in_review.
// Reference: app/controllers/api/v2/accounts/year_in_reviews_controller.rb.
type YearInReviewHandler struct {
svc *service.YearInReviewService
}
func NewYearInReviewHandler(svc *service.YearInReviewService) *YearInReviewHandler {
return &YearInReviewHandler{svc: svc}
}
// Show returns the current user's cached or freshly built yearly review payload.
// GET /api/v2/accounts/:account_id/year_in_review?year=YYYY
func (h *YearInReviewHandler) Show(c *gin.Context) {
accountID, ok := parseAccountID(c)
if !ok {
return
}
userID := getUserID(c)
if userID == 0 {
response.AbortWithStatusError(c, http.StatusUnauthorized, response.ErrUnauthorized, "user not authenticated")
return
}
year := service.DefaultYearInReviewYear()
if rawYear := c.Query("year"); rawYear != "" {
parsed, err := strconv.Atoi(rawYear)
if err != nil {
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid year")
return
}
year = parsed
}
data, err := h.svc.Show(c.Request.Context(), accountID, userID, year)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
response.AbortWithStatusError(c, http.StatusNotFound, response.ErrNotFound, "record not found")
return
}
response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "failed to build year in review")
return
}
c.JSON(http.StatusOK, data)
}
@@ -0,0 +1,115 @@
package v1
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strconv"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/gochat/gochat/internal/model"
"github.com/gochat/gochat/internal/service"
"github.com/stretchr/testify/require"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
func TestYearInReviewShowReturnsRawChatwootPayload(t *testing.T) {
db, handler, account, user, inbox, contact := setupYearInReviewHandlerTest(t)
createdAt := time.Date(2026, time.April, 4, 8, 0, 0, 0, time.UTC)
require.NoError(t, db.Create(&model.Conversation{Base: model.Base{CreatedAt: createdAt}, AccountID: account.ID, InboxID: inbox.ID, ContactID: contact.ID, AssigneeID: &user.ID, Status: string(model.ConversationStatusOpen), ChannelType: "web_widget", Channel: "web_widget"}).Error)
require.NoError(t, db.Create(&model.ReportingEvent{Base: model.Base{CreatedAt: createdAt}, AccountID: account.ID, Name: model.MetricNameFirstResponse, UserID: &user.ID, Value: 91.8}).Error)
router := yearInReviewTestRouter(handler, user.ID)
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/v2/accounts/"+strconv.Itoa(int(account.ID))+"/year_in_review?year=2026", nil)
router.ServeHTTP(w, req)
require.Equal(t, http.StatusOK, w.Code)
var body map[string]any
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body))
require.NotContains(t, body, "success")
require.Equal(t, float64(2026), body["year"])
require.Equal(t, float64(1), body["total_conversations"])
require.Equal(t, "Apr 04", body["busiest_day"].(map[string]any)["date"])
require.Equal(t, float64(91), body["support_personality"].(map[string]any)["avg_response_time_seconds"])
}
func TestYearInReviewShowDefaultsMissingYearTo2025(t *testing.T) {
db, handler, account, user, inbox, contact := setupYearInReviewHandlerTest(t)
createdAt := time.Date(2025, time.December, 31, 8, 0, 0, 0, time.UTC)
require.NoError(t, db.Create(&model.Conversation{Base: model.Base{CreatedAt: createdAt}, AccountID: account.ID, InboxID: inbox.ID, ContactID: contact.ID, AssigneeID: &user.ID, Status: string(model.ConversationStatusOpen), ChannelType: "web_widget", Channel: "web_widget"}).Error)
router := yearInReviewTestRouter(handler, user.ID)
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/v2/accounts/"+strconv.Itoa(int(account.ID))+"/year_in_review", nil)
router.ServeHTTP(w, req)
require.Equal(t, http.StatusOK, w.Code)
var body map[string]any
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body))
require.Equal(t, float64(2025), body["year"])
require.Equal(t, float64(1), body["total_conversations"])
}
func TestYearInReviewShowRequiresUser(t *testing.T) {
_, handler, account, _, _, _ := setupYearInReviewHandlerTest(t)
router := yearInReviewTestRouter(handler, 0)
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/v2/accounts/"+strconv.Itoa(int(account.ID))+"/year_in_review", nil)
router.ServeHTTP(w, req)
require.Equal(t, http.StatusUnauthorized, w.Code)
}
func TestYearInReviewShowRejectsInvalidYear(t *testing.T) {
_, handler, account, user, _, _ := setupYearInReviewHandlerTest(t)
router := yearInReviewTestRouter(handler, user.ID)
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/v2/accounts/"+strconv.Itoa(int(account.ID))+"/year_in_review?year=nope", nil)
router.ServeHTTP(w, req)
require.Equal(t, http.StatusBadRequest, w.Code)
}
func setupYearInReviewHandlerTest(t *testing.T) (*gorm.DB, *YearInReviewHandler, *model.Account, *model.User, *model.Inbox, *model.Contact) {
t.Helper()
db, err := gorm.Open(sqlite.Open("file:"+t.Name()+"?mode=memory&cache=private"), &gorm.Config{})
require.NoError(t, err)
require.NoError(t, db.AutoMigrate(
&model.Account{},
&model.User{},
&model.Inbox{},
&model.Contact{},
&model.Conversation{},
&model.ReportingEvent{},
))
t.Cleanup(func() {
sqlDB, _ := db.DB()
_ = sqlDB.Close()
})
account := &model.Account{Name: "Review API", Timezone: "UTC"}
require.NoError(t, db.Create(account).Error)
user := &model.User{AccountID: account.ID, Name: "Agent", Email: "agent-year-api@example.com", Password: "secret", Active: true}
require.NoError(t, db.Create(user).Error)
inbox := &model.Inbox{AccountID: account.ID, Name: "Web", ChannelType: "web_widget", ChannelID: 1, Enabled: true}
require.NoError(t, db.Create(inbox).Error)
contact := &model.Contact{AccountID: account.ID, Name: "Customer", Email: "customer-year-api@example.com"}
require.NoError(t, db.Create(contact).Error)
return db, NewYearInReviewHandler(service.NewYearInReviewService(db)), account, user, inbox, contact
}
func yearInReviewTestRouter(handler *YearInReviewHandler, userID uint) *gin.Engine {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(func(c *gin.Context) {
if userID != 0 {
c.Set("user_id", userID)
}
c.Next()
})
r.GET("/api/v2/accounts/:account_id/year_in_review", handler.Show)
return r
}
+3
View File
@@ -68,6 +68,7 @@ type Handlers struct {
WebWidgetOffline *v1.WebWidgetOfflineHandler
Analytics *v1.AnalyticsHandler
LiveReport *v1.LiveReportHandler
YearInReview *v1.YearInReviewHandler
DashboardApp *v1.DashboardAppHandler
Portal *v1.PortalHandler
Category *v1.CategoryHandler
@@ -1877,6 +1878,8 @@ func registerV2Routes(g *gin.RouterGroup, h *Handlers) {
liveReports.GET("/conversation_metrics", h.LiveReport.ConversationMetrics)
liveReports.GET("/grouped_conversation_metrics", h.LiveReport.GroupedConversationMetrics)
}
accountScoped.GET("/year_in_review", h.YearInReview.Show)
}
}
}
+1
View File
@@ -72,6 +72,7 @@ func TestRegisterRoutesBootsWithChatwootParityConflictGroups(t *testing.T) {
"GET /hc/:slug/:locale/categories/:category_slug",
"GET /hc/:slug/articles/:article_slug",
"GET /api/v2/accounts/:account_id/reports/summary",
"GET /api/v2/accounts/:account_id/year_in_review",
"GET /api/v2/accounts/:account_id/live_reports/grouped_conversation_metrics",
"GET /webhooks/twitter",
"POST /webhooks/twitter",
+202
View File
@@ -0,0 +1,202 @@
package service
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"sort"
"time"
"github.com/gochat/gochat/internal/model"
"gorm.io/datatypes"
"gorm.io/gorm"
)
const defaultYearInReviewYear = 2025
// YearInReviewData mirrors Chatwoot's YearInReviewBuilder response shape.
type YearInReviewData struct {
Year int `json:"year"`
TotalConversations int64 `json:"total_conversations"`
BusiestDay *YearInReviewBusiestDay `json:"busiest_day"`
SupportPersonality YearInReviewSupportPerson `json:"support_personality"`
}
type YearInReviewBusiestDay struct {
Date string `json:"date"`
Count int64 `json:"count"`
}
type YearInReviewSupportPerson struct {
AvgResponseTimeSeconds int64 `json:"avg_response_time_seconds"`
}
// YearInReviewService builds and caches the API v2 year-in-review payload.
type YearInReviewService struct {
db *gorm.DB
}
func NewYearInReviewService(db *gorm.DB) *YearInReviewService {
return &YearInReviewService{db: db}
}
func DefaultYearInReviewYear() int { return defaultYearInReviewYear }
// Show returns cached Current.user.ui_settings data when present, otherwise builds
// the same aggregate payload as Chatwoot's YearInReviewBuilder and stores it.
func (s *YearInReviewService) Show(ctx context.Context, accountID, userID uint, year int) (*YearInReviewData, error) {
if s == nil || s.db == nil {
return nil, errors.New("year in review service unavailable")
}
if year == 0 {
year = defaultYearInReviewYear
}
var user model.User
if err := s.db.WithContext(ctx).Where("id = ? AND account_id = ?", userID, accountID).First(&user).Error; err != nil {
return nil, err
}
cacheKey := fmt.Sprintf("year_in_review_%d_%d", accountID, year)
uiSettings, err := decodeUISettings(user.UISettings)
if err != nil {
return nil, err
}
if cached, ok := uiSettings[cacheKey]; ok && cached != nil {
var data YearInReviewData
encoded, err := json.Marshal(cached)
if err != nil {
return nil, err
}
if err := json.Unmarshal(encoded, &data); err != nil {
return nil, err
}
return &data, nil
}
data, err := s.Build(ctx, accountID, userID, year)
if err != nil {
return nil, err
}
uiSettings[cacheKey] = data
encoded, err := json.Marshal(uiSettings)
if err != nil {
return nil, err
}
if err := s.db.WithContext(ctx).Model(&model.User{}).Where("id = ? AND account_id = ?", userID, accountID).Update("ui_settings", datatypes.JSON(encoded)).Error; err != nil {
return nil, err
}
return data, nil
}
func (s *YearInReviewService) Build(ctx context.Context, accountID, userID uint, year int) (*YearInReviewData, error) {
loc, err := s.accountLocation(ctx, accountID)
if err != nil {
return nil, err
}
start, end := yearBoundsUTC(year, loc)
var conversations []model.Conversation
if err := s.db.WithContext(ctx).
Where("account_id = ? AND assignee_id = ? AND created_at >= ? AND created_at < ?", accountID, userID, start, end).
Find(&conversations).Error; err != nil {
return nil, err
}
avg, err := s.averageFirstResponse(ctx, accountID, userID, start, end)
if err != nil {
return nil, err
}
return &YearInReviewData{
Year: year,
TotalConversations: int64(len(conversations)),
BusiestDay: busiestDay(conversations, loc),
SupportPersonality: YearInReviewSupportPerson{AvgResponseTimeSeconds: int64(avg)},
}, nil
}
func (s *YearInReviewService) accountLocation(ctx context.Context, accountID uint) (*time.Location, error) {
var account model.Account
if err := s.db.WithContext(ctx).Select("id", "timezone").Where("id = ?", accountID).First(&account).Error; err != nil {
return nil, err
}
if account.Timezone == "" {
return time.UTC, nil
}
loc, err := time.LoadLocation(account.Timezone)
if err != nil {
return time.UTC, nil
}
return loc, nil
}
func (s *YearInReviewService) averageFirstResponse(ctx context.Context, accountID, userID uint, start, end time.Time) (float64, error) {
var avg sql.NullFloat64
if err := s.db.WithContext(ctx).
Model(&model.ReportingEvent{}).
Where("account_id = ? AND name = ? AND user_id = ? AND created_at >= ? AND created_at < ?", accountID, model.MetricNameFirstResponse, userID, start, end).
Select("AVG(value)").
Scan(&avg).Error; err != nil {
return 0, err
}
if !avg.Valid {
return 0, nil
}
return avg.Float64, nil
}
func yearBoundsUTC(year int, loc *time.Location) (time.Time, time.Time) {
if loc == nil {
loc = time.UTC
}
start := time.Date(year, time.January, 1, 0, 0, 0, 0, loc)
end := start.AddDate(1, 0, 0)
return start.UTC(), end.UTC()
}
func busiestDay(conversations []model.Conversation, loc *time.Location) *YearInReviewBusiestDay {
if len(conversations) == 0 {
return nil
}
counts := make(map[time.Time]int64)
for _, conversation := range conversations {
localDay := conversation.CreatedAt.In(loc)
bucket := time.Date(localDay.Year(), localDay.Month(), localDay.Day(), 0, 0, 0, 0, loc)
counts[bucket]++
}
days := make([]time.Time, 0, len(counts))
for day := range counts {
days = append(days, day)
}
sort.Slice(days, func(i, j int) bool { return days[i].Before(days[j]) })
var busiest time.Time
var max int64
for _, day := range days {
if counts[day] > max {
busiest = day
max = counts[day]
}
}
if max == 0 {
return nil
}
return &YearInReviewBusiestDay{Date: busiest.Format("Jan 02"), Count: max}
}
func decodeUISettings(raw datatypes.JSON) (map[string]any, error) {
settings := map[string]any{}
if len(raw) == 0 || string(raw) == "null" {
return settings, nil
}
if err := json.Unmarshal(raw, &settings); err != nil {
return nil, err
}
if settings == nil {
settings = map[string]any{}
}
return settings, nil
}
@@ -0,0 +1,107 @@
package service
import (
"context"
"encoding/json"
"testing"
"time"
"github.com/gochat/gochat/internal/model"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
func setupYearInReviewServiceTest(t *testing.T) (*gorm.DB, *YearInReviewService, *model.Account, *model.User, *model.Inbox, *model.Contact) {
t.Helper()
db, err := gorm.Open(sqlite.Open("file:"+t.Name()+"?mode=memory&cache=private"), &gorm.Config{})
require.NoError(t, err)
require.NoError(t, db.AutoMigrate(
&model.Account{},
&model.User{},
&model.Inbox{},
&model.Contact{},
&model.Conversation{},
&model.ReportingEvent{},
))
t.Cleanup(func() {
sqlDB, _ := db.DB()
_ = sqlDB.Close()
})
account := &model.Account{Name: "Review", Timezone: "UTC"}
require.NoError(t, db.Create(account).Error)
user := &model.User{AccountID: account.ID, Name: "Agent", Email: "agent-review@example.com", Password: "secret", Active: true}
require.NoError(t, db.Create(user).Error)
inbox := &model.Inbox{AccountID: account.ID, Name: "Web", ChannelType: "web_widget", ChannelID: 1, Enabled: true}
require.NoError(t, db.Create(inbox).Error)
contact := &model.Contact{AccountID: account.ID, Name: "Customer", Email: "customer-review@example.com"}
require.NoError(t, db.Create(contact).Error)
return db, NewYearInReviewService(db), account, user, inbox, contact
}
func TestYearInReviewBuildsAndCachesChatwootPayload(t *testing.T) {
db, svc, account, user, inbox, contact := setupYearInReviewServiceTest(t)
dayOne := time.Date(2026, time.January, 2, 10, 0, 0, 0, time.UTC)
dayTwo := time.Date(2026, time.March, 5, 12, 0, 0, 0, time.UTC)
otherYear := time.Date(2025, time.January, 2, 10, 0, 0, 0, time.UTC)
otherUserID := user.ID + 99
createReviewConversation(t, db, account.ID, inbox.ID, contact.ID, user.ID, dayOne)
createReviewConversation(t, db, account.ID, inbox.ID, contact.ID, user.ID, dayOne.Add(2*time.Hour))
createReviewConversation(t, db, account.ID, inbox.ID, contact.ID, user.ID, dayTwo)
createReviewConversation(t, db, account.ID, inbox.ID, contact.ID, user.ID, otherYear)
createReviewConversation(t, db, account.ID, inbox.ID, contact.ID, otherUserID, dayOne)
require.NoError(t, db.Create(&model.ReportingEvent{Base: model.Base{CreatedAt: dayOne}, AccountID: account.ID, Name: model.MetricNameFirstResponse, UserID: &user.ID, Value: 120.9}).Error)
require.NoError(t, db.Create(&model.ReportingEvent{Base: model.Base{CreatedAt: dayTwo}, AccountID: account.ID, Name: model.MetricNameFirstResponse, UserID: &user.ID, Value: 240.1}).Error)
require.NoError(t, db.Create(&model.ReportingEvent{Base: model.Base{CreatedAt: otherYear}, AccountID: account.ID, Name: model.MetricNameFirstResponse, UserID: &user.ID, Value: 999}).Error)
data, err := svc.Show(context.Background(), account.ID, user.ID, 2026)
require.NoError(t, err)
require.NotNil(t, data)
assert.Equal(t, 2026, data.Year)
assert.Equal(t, int64(3), data.TotalConversations)
require.NotNil(t, data.BusiestDay)
assert.Equal(t, "Jan 02", data.BusiestDay.Date)
assert.Equal(t, int64(2), data.BusiestDay.Count)
assert.Equal(t, int64(180), data.SupportPersonality.AvgResponseTimeSeconds)
var refreshed model.User
require.NoError(t, db.First(&refreshed, user.ID).Error)
var uiSettings map[string]any
require.NoError(t, json.Unmarshal(refreshed.UISettings, &uiSettings))
assert.Contains(t, uiSettings, "year_in_review_1_2026")
createReviewConversation(t, db, account.ID, inbox.ID, contact.ID, user.ID, dayTwo.Add(time.Hour))
cached, err := svc.Show(context.Background(), account.ID, user.ID, 2026)
require.NoError(t, err)
assert.Equal(t, int64(3), cached.TotalConversations)
}
func TestYearInReviewReturnsEmptyPersonalityWithoutEvents(t *testing.T) {
_, svc, account, user, _, _ := setupYearInReviewServiceTest(t)
data, err := svc.Show(context.Background(), account.ID, user.ID, 2026)
require.NoError(t, err)
assert.Equal(t, int64(0), data.TotalConversations)
assert.Nil(t, data.BusiestDay)
assert.Equal(t, int64(0), data.SupportPersonality.AvgResponseTimeSeconds)
}
func createReviewConversation(t *testing.T, db *gorm.DB, accountID, inboxID, contactID, assigneeID uint, createdAt time.Time) {
t.Helper()
conversation := &model.Conversation{
Base: model.Base{CreatedAt: createdAt},
AccountID: accountID,
InboxID: inboxID,
ContactID: contactID,
AssigneeID: &assigneeID,
Status: string(model.ConversationStatusOpen),
ChannelType: "web_widget",
Channel: "web_widget",
}
require.NoError(t, db.Create(conversation).Error)
}