feat(reports): align year in review
This commit is contained in:
@@ -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)
|
||||
}
|
||||
Reference in New Issue
Block a user