chore: initial commit of HouseholdBudgetBook (backend, frontend, desktop)
This commit is contained in:
commit
4a5db3f1f9
167 files changed
+21732
No files matched your search
@@ -0,0 +1,88 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"household-book/model"
|
||||
"household-book/service"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type BudgetHandler struct {
|
||||
svc *service.BudgetService
|
||||
}
|
||||
|
||||
func NewBudgetHandler(svc *service.BudgetService) *BudgetHandler {
|
||||
return &BudgetHandler{svc: svc}
|
||||
}
|
||||
|
||||
func (h *BudgetHandler) Overview(c *gin.Context) {
|
||||
year, err := strconv.Atoi(c.Param("year"))
|
||||
if err != nil || year < 2000 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的年份"})
|
||||
return
|
||||
}
|
||||
month, err := strconv.Atoi(c.Param("month"))
|
||||
if err != nil || month < 1 || month > 12 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的月份"})
|
||||
return
|
||||
}
|
||||
|
||||
overview, err := h.svc.Overview(c.Request.Context(), year, month)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "获取预算看板失败"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, overview)
|
||||
}
|
||||
|
||||
func (h *BudgetHandler) Upsert(c *gin.Context) {
|
||||
var req model.UpsertBudgetRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数格式错误"})
|
||||
return
|
||||
}
|
||||
if req.Year < 2000 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的年份"})
|
||||
return
|
||||
}
|
||||
if req.Month != nil && (*req.Month < 1 || *req.Month > 12) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的月份"})
|
||||
return
|
||||
}
|
||||
if req.Amount < 0 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "预算金额不能为负数"})
|
||||
return
|
||||
}
|
||||
|
||||
budget, err := h.svc.Upsert(c.Request.Context(), 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, budget)
|
||||
}
|
||||
|
||||
func (h *BudgetHandler) Delete(c *gin.Context) {
|
||||
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||
if err != nil || id <= 0 {
|
||||
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
|
||||
}
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "删除预算失败"})
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
Reference in new issue
Block a user