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
@@ -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
}