Files

79 lines
2.0 KiB
Go

package api
import (
"net/http"
"strconv"
"household-book/service"
"github.com/gin-gonic/gin"
)
type ReportHandler struct {
svc *service.ReportService
}
func NewReportHandler(svc *service.ReportService) *ReportHandler {
return &ReportHandler{svc: svc}
}
func (h *ReportHandler) Overview(c *gin.Context) {
year, month, ok := parseReportYearMonth(c)
if !ok {
return
}
typ := c.DefaultQuery("type", "expense")
if typ != "income" && typ != "expense" {
c.JSON(http.StatusBadRequest, gin.H{"error": "类型必须是 income 或 expense"})
return
}
data, err := h.svc.Overview(c.Request.Context(), year, month, typ)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "获取报表失败"})
return
}
c.JSON(http.StatusOK, data)
}
func (h *ReportHandler) CategoryRanking(c *gin.Context) {
year, month, ok := parseReportYearMonth(c)
if !ok {
return
}
typ := c.DefaultQuery("type", "expense")
data, err := h.svc.CategoryRanking(c.Request.Context(), year, month, typ, 10)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "获取分类排行失败"})
return
}
c.JSON(http.StatusOK, data)
}
func (h *ReportHandler) Trend(c *gin.Context) {
year, err := strconv.Atoi(c.Query("year"))
if err != nil || year < 2000 {
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的年份"})
return
}
data, err := h.svc.Trend(c.Request.Context(), year)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "获取收支趋势失败"})
return
}
c.JSON(http.StatusOK, data)
}
func parseReportYearMonth(c *gin.Context) (int, int, bool) {
year, err := strconv.Atoi(c.Query("year"))
if err != nil || year < 2000 {
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的年份"})
return 0, 0, false
}
month, err := strconv.Atoi(c.Query("month"))
if err != nil || month < 1 || month > 12 {
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的月份"})
return 0, 0, false
}
return year, month, true
}