59 lines
1.6 KiB
Go
59 lines
1.6 KiB
Go
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)
|
|
}
|