105 lines
2.7 KiB
Go
105 lines
2.7 KiB
Go
package api
|
|
|
|
import (
|
|
"errors"
|
|
"net/http"
|
|
"strconv"
|
|
|
|
"household-book/model"
|
|
"household-book/service"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
type CategoryHandler struct {
|
|
svc *service.CategoryService
|
|
}
|
|
|
|
func NewCategoryHandler(svc *service.CategoryService) *CategoryHandler {
|
|
return &CategoryHandler{svc: svc}
|
|
}
|
|
|
|
func (h *CategoryHandler) List(c *gin.Context) {
|
|
typ := c.Query("type")
|
|
categories, err := h.svc.List(c.Request.Context(), typ)
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "获取分类列表失败"})
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, categories)
|
|
}
|
|
|
|
func (h *CategoryHandler) Create(c *gin.Context) {
|
|
var req model.CreateCategoryRequest
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数格式错误"})
|
|
return
|
|
}
|
|
if req.Name == "" {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "分类名称不能为空"})
|
|
return
|
|
}
|
|
if req.Type != "income" && req.Type != "expense" {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "类型必须是 income 或 expense"})
|
|
return
|
|
}
|
|
|
|
cat, err := h.svc.Create(c.Request.Context(), req)
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "添加分类失败"})
|
|
return
|
|
}
|
|
c.JSON(http.StatusCreated, cat)
|
|
}
|
|
|
|
func (h *CategoryHandler) Update(c *gin.Context) {
|
|
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的ID"})
|
|
return
|
|
}
|
|
|
|
var req model.UpdateCategoryRequest
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数格式错误"})
|
|
return
|
|
}
|
|
|
|
cat, err := h.svc.Update(c.Request.Context(), id, req)
|
|
if err != nil {
|
|
if errors.Is(err, service.ErrNotFound) {
|
|
c.JSON(http.StatusNotFound, gin.H{"error": "分类不存在"})
|
|
return
|
|
}
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "更新分类失败"})
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, cat)
|
|
}
|
|
|
|
func (h *CategoryHandler) Delete(c *gin.Context) {
|
|
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的ID"})
|
|
return
|
|
}
|
|
|
|
if err := h.svc.Delete(c.Request.Context(), id); err != nil {
|
|
if errors.Is(err, service.ErrNotFound) {
|
|
c.JSON(http.StatusNotFound, gin.H{"error": "分类不存在"})
|
|
return
|
|
}
|
|
if errors.Is(err, service.ErrHasTransactions) {
|
|
c.JSON(http.StatusConflict, gin.H{"error": "该分类有关联的收支记录,无法删除"})
|
|
return
|
|
}
|
|
if errors.Is(err, service.ErrHasChildren) {
|
|
c.JSON(http.StatusConflict, gin.H{"error": "该分类下有子分类,无法删除"})
|
|
return
|
|
}
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "删除分类失败"})
|
|
return
|
|
}
|
|
c.Status(http.StatusNoContent)
|
|
}
|