chore: initial commit of HouseholdBudgetBook (backend, frontend, desktop)

This commit is contained in:
mapleferry committed 2026-11-29 21:29:06 +08:00
commit 4a5db3f1f9
167 files changed
+21732

No files matched your search

+159
View File
@@ -0,0 +1,159 @@
package api
import (
"errors"
"net/http"
"strconv"
"household-book/model"
"household-book/service"
"github.com/gin-gonic/gin"
)
type AccountHandler struct {
svc *service.AccountService
}
func (h *AccountHandler) Reconcile(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.ReconcileAccountRequest
if c.ShouldBindJSON(&req) != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数格式错误"})
return
}
v, e := h.svc.Reconcile(c.Request.Context(), id, req)
if e != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "账户对账失败"})
return
}
c.JSON(http.StatusCreated, v)
}
func (h *AccountHandler) ListReconciliations(c *gin.Context) {
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的ID"})
return
}
v, e := h.svc.ListReconciliations(c.Request.Context(), id)
if e != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "获取对账记录失败"})
return
}
c.JSON(http.StatusOK, v)
}
func NewAccountHandler(svc *service.AccountService) *AccountHandler {
return &AccountHandler{svc: svc}
}
func (h *AccountHandler) List(c *gin.Context) {
accounts, err := h.svc.List(c.Request.Context())
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "获取账户列表失败"})
return
}
c.JSON(http.StatusOK, accounts)
}
func (h *AccountHandler) Create(c *gin.Context) {
var req model.CreateAccountRequest
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 == "" {
req.Type = "other"
}
if req.Type == "bank_card" {
req.Type = "debit_card"
}
if !validAccountType(req.Type) {
c.JSON(http.StatusBadRequest, gin.H{"error": "账户类型无效"})
return
}
account, err := h.svc.Create(c.Request.Context(), req)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "添加账户失败"})
return
}
c.JSON(http.StatusCreated, account)
}
func (h *AccountHandler) 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.UpdateAccountRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数格式错误"})
return
}
if req.Name != nil && *req.Name == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "账户名称不能为空"})
return
}
if req.Type != nil {
if *req.Type == "bank_card" {
*req.Type = "debit_card"
}
if !validAccountType(*req.Type) {
c.JSON(http.StatusBadRequest, gin.H{"error": "账户类型无效"})
return
}
}
account, 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, account)
}
func (h *AccountHandler) 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
}
c.JSON(http.StatusInternalServerError, gin.H{"error": "删除账户失败"})
return
}
c.Status(http.StatusNoContent)
}
func validAccountType(typ string) bool {
switch typ {
case "alipay", "wechat", "debit_card", "credit_card", "cash", "other":
return true
default:
return false
}
}
+173
View File
@@ -0,0 +1,173 @@
package api
import (
"errors"
"net/http"
"strconv"
"household-book/model"
"household-book/service"
"github.com/gin-gonic/gin"
)
type AssetHandler struct{ svc *service.AssetService }
func NewAssetHandler(svc *service.AssetService) *AssetHandler { return &AssetHandler{svc: svc} }
func (h *AssetHandler) ListAssets(c *gin.Context) {
items, err := h.svc.ListAssets(c.Request.Context())
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "获取资产列表失败"})
return
}
c.JSON(http.StatusOK, items)
}
func (h *AssetHandler) CreateAsset(c *gin.Context) {
var req model.CreateAssetRequest
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
}
item, err := h.svc.CreateAsset(c.Request.Context(), req)
if err != nil {
if errors.Is(err, service.ErrAccountAlreadyBound) {
c.JSON(http.StatusConflict, gin.H{"error": "该账户已绑定其他资产"})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": "添加资产失败"})
return
}
c.JSON(http.StatusCreated, item)
}
func (h *AssetHandler) UpdateAsset(c *gin.Context) {
id, ok := parseID(c)
if !ok {
return
}
var req model.UpdateAssetRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数格式错误"})
return
}
item, err := h.svc.UpdateAsset(c.Request.Context(), id, req)
if err != nil {
if errors.Is(err, service.ErrAccountAlreadyBound) {
c.JSON(http.StatusConflict, gin.H{"error": "该账户已绑定其他资产"})
return
}
writeEntityError(c, err, "更新资产失败", "资产不存在")
return
}
c.JSON(http.StatusOK, item)
}
func (h *AssetHandler) DeleteAsset(c *gin.Context) {
id, ok := parseID(c)
if !ok {
return
}
if err := h.svc.DeleteAsset(c.Request.Context(), id); err != nil {
writeEntityError(c, err, "删除资产失败", "资产不存在")
return
}
c.Status(http.StatusNoContent)
}
func (h *AssetHandler) ListLiabilities(c *gin.Context) {
items, err := h.svc.ListLiabilities(c.Request.Context())
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "获取负债列表失败"})
return
}
c.JSON(http.StatusOK, items)
}
func (h *AssetHandler) CreateLiability(c *gin.Context) {
var req model.CreateLiabilityRequest
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
}
item, err := h.svc.CreateLiability(c.Request.Context(), req)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "添加负债失败"})
return
}
c.JSON(http.StatusCreated, item)
}
func (h *AssetHandler) UpdateLiability(c *gin.Context) {
id, ok := parseID(c)
if !ok {
return
}
var req model.UpdateLiabilityRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数格式错误"})
return
}
item, err := h.svc.UpdateLiability(c.Request.Context(), id, req)
if err != nil {
writeEntityError(c, err, "更新负债失败", "负债不存在")
return
}
c.JSON(http.StatusOK, item)
}
func (h *AssetHandler) DeleteLiability(c *gin.Context) {
id, ok := parseID(c)
if !ok {
return
}
if err := h.svc.DeleteLiability(c.Request.Context(), id); err != nil {
writeEntityError(c, err, "删除负债失败", "负债不存在")
return
}
c.Status(http.StatusNoContent)
}
func (h *AssetHandler) NetWorth(c *gin.Context) {
data, err := h.svc.NetWorth(c.Request.Context())
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "计算净值失败"})
return
}
c.JSON(http.StatusOK, data)
}
func (h *AssetHandler) ListSnapshots(c *gin.Context) {
data, err := h.svc.ListSnapshots(c.Request.Context())
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "获取净值快照失败"})
return
}
c.JSON(http.StatusOK, data)
}
func parseID(c *gin.Context) (int64, bool) {
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的ID"})
return 0, false
}
return id, true
}
func writeEntityError(c *gin.Context, err error, generic, notFound string) {
if errors.Is(err, service.ErrNotFound) {
c.JSON(http.StatusNotFound, gin.H{"error": notFound})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": generic})
}
+27
View File
@@ -0,0 +1,27 @@
package api
import (
"github.com/gin-gonic/gin"
"household-book/service"
"net/http"
)
type BackupHandler struct{ svc *service.BackupService }
func NewBackupHandler(s *service.BackupService) *BackupHandler { return &BackupHandler{svc: s} }
func (h *BackupHandler) Status(c *gin.Context) {
v, e := h.svc.Status()
if e != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "获取备份状态失败"})
return
}
c.JSON(http.StatusOK, v)
}
func (h *BackupHandler) Create(c *gin.Context) {
v, e := h.svc.Create(c.Request.Context())
if e != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "创建备份失败"})
return
}
c.JSON(http.StatusOK, v)
}
+88
View File
@@ -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)
}
+104
View File
@@ -0,0 +1,104 @@
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)
}
+46
View File
@@ -0,0 +1,46 @@
package api
import (
"net/http"
"strconv"
"household-book/service"
"github.com/gin-gonic/gin"
)
type DashboardHandler struct {
svc *service.DashboardService
}
func NewDashboardHandler(svc *service.DashboardService) *DashboardHandler {
return &DashboardHandler{svc: svc}
}
func (h *DashboardHandler) Summary(c *gin.Context) {
year := c.Query("year")
month := c.Query("month")
summary, err := h.svc.Summary(c.Request.Context(), year, month)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "获取摘要数据失败"})
return
}
c.JSON(http.StatusOK, summary)
}
func (h *DashboardHandler) Recent(c *gin.Context) {
limit := 5
if l := c.Query("limit"); l != "" {
if parsed, err := strconv.Atoi(l); err == nil && parsed > 0 && parsed <= 50 {
limit = parsed
}
}
items, err := h.svc.Recent(c.Request.Context(), limit)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "获取最近记录失败"})
return
}
c.JSON(http.StatusOK, items)
}
+73
View File
@@ -0,0 +1,73 @@
package api
import (
"net/http"
"household-book/model"
"household-book/service"
"github.com/gin-gonic/gin"
)
type LifecycleHandler struct{ svc *service.LifecycleService }
func NewLifecycleHandler(svc *service.LifecycleService) *LifecycleHandler {
return &LifecycleHandler{svc: svc}
}
func (h *LifecycleHandler) List(c *gin.Context) {
items, err := h.svc.List(c.Request.Context())
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "获取人生周期失败"})
return
}
c.JSON(http.StatusOK, items)
}
func (h *LifecycleHandler) Create(c *gin.Context) {
var req model.CreateLifecycleEventRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数格式错误"})
return
}
if req.Year < 1900 || req.Event == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "年份和事件不能为空"})
return
}
item, err := h.svc.Create(c.Request.Context(), req)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "添加事件失败"})
return
}
c.JSON(http.StatusCreated, item)
}
func (h *LifecycleHandler) Update(c *gin.Context) {
id, ok := parseID(c)
if !ok {
return
}
var req model.UpdateLifecycleEventRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数格式错误"})
return
}
item, err := h.svc.Update(c.Request.Context(), id, req)
if err != nil {
writeEntityError(c, err, "更新事件失败", "事件不存在")
return
}
c.JSON(http.StatusOK, item)
}
func (h *LifecycleHandler) Delete(c *gin.Context) {
id, ok := parseID(c)
if !ok {
return
}
if err := h.svc.Delete(c.Request.Context(), id); err != nil {
writeEntityError(c, err, "删除事件失败", "事件不存在")
return
}
c.Status(http.StatusNoContent)
}
+99
View File
@@ -0,0 +1,99 @@
package api
import (
"errors"
"net/http"
"strconv"
"household-book/model"
"household-book/service"
"github.com/gin-gonic/gin"
)
type MemberHandler struct {
svc *service.MemberService
}
func NewMemberHandler(svc *service.MemberService) *MemberHandler {
return &MemberHandler{svc: svc}
}
func (h *MemberHandler) List(c *gin.Context) {
members, err := h.svc.List(c.Request.Context())
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "获取成员列表失败"})
return
}
c.JSON(http.StatusOK, members)
}
func (h *MemberHandler) Create(c *gin.Context) {
var req model.CreateMemberRequest
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 len(req.Name) > 50 {
c.JSON(http.StatusBadRequest, gin.H{"error": "姓名不能超过50个字符"})
return
}
member, err := h.svc.Create(c.Request.Context(), req)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "添加成员失败"})
return
}
c.JSON(http.StatusCreated, member)
}
func (h *MemberHandler) 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.UpdateMemberRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数格式错误"})
return
}
member, 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, member)
}
func (h *MemberHandler) 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
}
c.JSON(http.StatusInternalServerError, gin.H{"error": "删除成员失败"})
return
}
c.Status(http.StatusNoContent)
}
+157
View File
@@ -0,0 +1,157 @@
package api
import (
"errors"
"net/http"
"strconv"
"household-book/model"
"household-book/service"
"github.com/gin-gonic/gin"
)
type PolicyHandler struct{ svc *service.PolicyService }
func NewPolicyHandler(svc *service.PolicyService) *PolicyHandler { return &PolicyHandler{svc: svc} }
func (h *PolicyHandler) List(c *gin.Context) {
items, err := h.svc.List(c.Request.Context())
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "获取保单列表失败"})
return
}
c.JSON(http.StatusOK, items)
}
func (h *PolicyHandler) ListPayments(c *gin.Context) {
id, ok := parseID(c)
if !ok {
return
}
v, e := h.svc.ListPayments(c.Request.Context(), id)
if e != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "获取缴费记录失败"})
return
}
c.JSON(http.StatusOK, v)
}
func (h *PolicyHandler) CreatePayment(c *gin.Context) {
id, ok := parseID(c)
if !ok {
return
}
var req model.CreatePolicyPaymentRequest
if c.ShouldBindJSON(&req) != nil || req.DueDate == "" || req.Amount < 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": "缴费日期或金额无效"})
return
}
v, e := h.svc.CreatePayment(c.Request.Context(), id, req)
if e != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "创建缴费记录失败"})
return
}
c.JSON(http.StatusCreated, v)
}
func (h *PolicyHandler) UpdatePayment(c *gin.Context) {
id, ok := parseID(c)
if !ok {
return
}
var req model.UpdatePolicyPaymentRequest
if c.ShouldBindJSON(&req) != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数格式错误"})
return
}
v, e := h.svc.UpdatePayment(c.Request.Context(), id, req)
if errors.Is(e, service.ErrInvalidPaymentStatus) {
c.JSON(http.StatusBadRequest, gin.H{"error": "缴费状态无效"})
return
}
if e != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "更新缴费记录失败"})
return
}
c.JSON(http.StatusOK, v)
}
func (h *PolicyHandler) Upcoming(c *gin.Context) {
days, _ := strconv.Atoi(c.DefaultQuery("days", "30"))
items, err := h.svc.Upcoming(c.Request.Context(), days)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "获取续费提醒失败"})
return
}
c.JSON(http.StatusOK, items)
}
func (h *PolicyHandler) Create(c *gin.Context) {
var req model.CreatePolicyRequest
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.Status == "" {
req.Status = "active"
}
if req.PaymentFrequency == "" {
req.PaymentFrequency = "annual"
}
if !validPaymentFrequency(req.PaymentFrequency) {
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的缴费频率"})
return
}
item, err := h.svc.Create(c.Request.Context(), req)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "添加保单失败"})
return
}
c.JSON(http.StatusCreated, item)
}
func (h *PolicyHandler) Update(c *gin.Context) {
id, ok := parseID(c)
if !ok {
return
}
var req model.UpdatePolicyRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数格式错误"})
return
}
if req.PaymentFrequency != nil && !validPaymentFrequency(*req.PaymentFrequency) {
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的缴费频率"})
return
}
item, err := h.svc.Update(c.Request.Context(), id, req)
if err != nil {
writeEntityError(c, err, "更新保单失败", "保单不存在")
return
}
c.JSON(http.StatusOK, item)
}
func validPaymentFrequency(value string) bool {
switch value {
case "monthly", "quarterly", "semiannual", "annual", "single":
return true
default:
return false
}
}
func (h *PolicyHandler) Delete(c *gin.Context) {
id, ok := parseID(c)
if !ok {
return
}
if err := h.svc.Delete(c.Request.Context(), id); err != nil {
writeEntityError(c, err, "删除保单失败", "保单不存在")
return
}
c.Status(http.StatusNoContent)
}
+78
View File
@@ -0,0 +1,78 @@
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
}
+262
View File
@@ -0,0 +1,262 @@
package api
import (
"database/sql"
"io"
"mime"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"household-book/middleware"
"household-book/service"
"github.com/gin-gonic/gin"
)
func SetupRouter(db *sql.DB, dbPath string, mode string, staticDir string, corsOrigins string) *gin.Engine {
if mode == "prod" {
gin.SetMode(gin.ReleaseMode)
} else {
gin.SetMode(gin.DebugMode)
}
r := gin.New()
middleware.Setup(r, mode, corsOrigins)
memberSvc := service.NewMemberService(db)
categorySvc := service.NewCategoryService(db)
accountSvc := service.NewAccountService(db)
transactionSvc := service.NewTransactionService(db)
dashboardSvc := service.NewDashboardService(db)
budgetSvc := service.NewBudgetService(db)
reportSvc := service.NewReportService(db)
assetSvc := service.NewAssetService(db)
policySvc := service.NewPolicyService(db)
lifecycleSvc := service.NewLifecycleService(db)
backupSvc := service.NewBackupService(db, dbPath)
memberH := NewMemberHandler(memberSvc)
categoryH := NewCategoryHandler(categorySvc)
accountH := NewAccountHandler(accountSvc)
transactionH := NewTransactionHandler(transactionSvc)
dashboardH := NewDashboardHandler(dashboardSvc)
budgetH := NewBudgetHandler(budgetSvc)
reportH := NewReportHandler(reportSvc)
assetH := NewAssetHandler(assetSvc)
policyH := NewPolicyHandler(policySvc)
lifecycleH := NewLifecycleHandler(lifecycleSvc)
backupH := NewBackupHandler(backupSvc)
api := r.Group("/api")
{
api.GET("/members", memberH.List)
api.POST("/members", memberH.Create)
api.PUT("/members/:id", memberH.Update)
api.DELETE("/members/:id", memberH.Delete)
api.GET("/categories", categoryH.List)
api.POST("/categories", categoryH.Create)
api.PUT("/categories/:id", categoryH.Update)
api.DELETE("/categories/:id", categoryH.Delete)
api.GET("/accounts", accountH.List)
api.POST("/accounts", accountH.Create)
api.PUT("/accounts/:id", accountH.Update)
api.DELETE("/accounts/:id", accountH.Delete)
api.POST("/accounts/:id/reconcile", accountH.Reconcile)
api.GET("/accounts/:id/reconciliations", accountH.ListReconciliations)
api.GET("/transactions", transactionH.List)
api.GET("/transactions/import-batches", transactionH.ListImportBatches)
api.POST("/transactions/import/preview", transactionH.PreviewImport)
api.POST("/transactions/import", transactionH.Import)
api.POST("/transactions/batch-delete", transactionH.DeleteBatch)
api.POST("/transactions", transactionH.Create)
api.PUT("/transactions/:id", transactionH.Update)
api.DELETE("/transactions/:id", transactionH.Delete)
api.DELETE("/transactions/import-batches/:id", transactionH.DeleteImportBatch)
api.GET("/dashboard/summary", dashboardH.Summary)
api.GET("/dashboard/recent", dashboardH.Recent)
api.GET("/budgets/:year/:month", budgetH.Overview)
api.PUT("/budgets", budgetH.Upsert)
api.DELETE("/budgets/:id", budgetH.Delete)
api.GET("/reports/overview", reportH.Overview)
api.GET("/reports/category-ranking", reportH.CategoryRanking)
api.GET("/reports/trend", reportH.Trend)
api.GET("/assets", assetH.ListAssets)
api.POST("/assets", assetH.CreateAsset)
api.PUT("/assets/:id", assetH.UpdateAsset)
api.DELETE("/assets/:id", assetH.DeleteAsset)
api.GET("/assets/net-worth", assetH.NetWorth)
api.GET("/assets/snapshots", assetH.ListSnapshots)
api.GET("/liabilities", assetH.ListLiabilities)
api.POST("/liabilities", assetH.CreateLiability)
api.PUT("/liabilities/:id", assetH.UpdateLiability)
api.DELETE("/liabilities/:id", assetH.DeleteLiability)
api.GET("/policies", policyH.List)
api.POST("/policies", policyH.Create)
api.PUT("/policies/:id", policyH.Update)
api.DELETE("/policies/:id", policyH.Delete)
api.GET("/policies/upcoming", policyH.Upcoming)
api.GET("/policies/:id/payments", policyH.ListPayments)
api.POST("/policies/:id/payments", policyH.CreatePayment)
api.PUT("/policy-payments/:id", policyH.UpdatePayment)
api.GET("/lifecycle", lifecycleH.List)
api.POST("/lifecycle/events", lifecycleH.Create)
api.PUT("/lifecycle/events/:id", lifecycleH.Update)
api.DELETE("/lifecycle/events/:id", lifecycleH.Delete)
api.GET("/backups/status", backupH.Status)
api.POST("/backups", backupH.Create)
}
// Production: serve static files
if staticDir != "" {
r.Use(staticFileMiddleware(staticDir))
}
return r
}
// immutableAssetPrefix 是 Vite 构建产物目录,文件名自带内容 hash,可长期强缓存。
const immutableAssetPrefix = "/assets/"
func staticFileMiddleware(staticDir string) gin.HandlerFunc {
fs := http.FileServer(http.Dir(staticDir))
root, err := filepath.Abs(staticDir)
if err != nil {
root = staticDir
}
indexPath := filepath.Join(root, "index.html")
return func(c *gin.Context) {
requestPath := c.Request.URL.Path
if strings.HasPrefix(requestPath, "/api") {
c.Next()
return
}
// 根路径与入口页直接返回 index.html,省掉文件服务器的目录重定向;
// 入口页必须每次协商,否则前端发版后用户会继续使用旧 bundle。
if requestPath == "/" || requestPath == "/index.html" {
if serveIndexHTML(c, indexPath) {
c.Abort()
return
}
c.Next()
return
}
clean := filepath.Clean("/" + requestPath)
candidate := filepath.Join(root, clean)
if !strings.HasPrefix(candidate, root) {
c.Next()
return
}
if info, err := os.Stat(candidate); err == nil && !info.IsDir() {
setStaticCacheHeaders(c, requestPath)
if servePrecompressed(c, candidate) {
c.Abort()
return
}
fs.ServeHTTP(c.Writer, c.Request)
c.Abort()
return
}
// SPA fallback
if serveIndexHTML(c, indexPath) {
c.Abort()
return
}
c.Next()
}
}
// serveIndexHTML 返回入口页;文件不存在时返回 false,交回路由继续处理。
func serveIndexHTML(c *gin.Context, indexPath string) bool {
if _, err := os.Stat(indexPath); err != nil {
return false
}
c.Header("Cache-Control", "no-cache, must-revalidate")
c.File(indexPath)
return true
}
func setStaticCacheHeaders(c *gin.Context, requestPath string) {
if strings.HasPrefix(requestPath, immutableAssetPrefix) {
c.Header("Cache-Control", "public, max-age=31536000, immutable")
return
}
c.Header("Cache-Control", "public, max-age=3600")
}
// servePrecompressed 在存在 .br/.gz 预压缩副本时直接返回;返回 true 表示已写入响应。
func servePrecompressed(c *gin.Context, filePath string) bool {
encoding := preferredEncoding(c.GetHeader("Accept-Encoding"))
if encoding == "" {
return false
}
compressedPath := filePath + "." + compressedSuffix(encoding)
info, err := os.Stat(compressedPath)
if err != nil || info.IsDir() {
return false
}
file, err := os.Open(compressedPath)
if err != nil {
return false
}
defer file.Close()
if contentType := mime.TypeByExtension(filepath.Ext(filePath)); contentType != "" {
c.Header("Content-Type", contentType)
}
c.Header("Content-Encoding", encoding)
c.Header("Vary", "Accept-Encoding")
c.Header("Content-Length", strconv.FormatInt(info.Size(), 10))
c.Status(http.StatusOK)
_, _ = io.Copy(c.Writer, file)
return true
}
func preferredEncoding(header string) string {
if header == "" {
return ""
}
accepted := make(map[string]bool, 4)
for _, part := range strings.Split(header, ",") {
token := strings.TrimSpace(strings.SplitN(part, ";", 2)[0])
accepted[strings.ToLower(token)] = true
}
switch {
case accepted["br"]:
return "br"
case accepted["gzip"]:
return "gzip"
default:
return ""
}
}
// compressedSuffix 把 Content-Encoding 映射到预压缩副本的扩展名(br / gz)。
func compressedSuffix(encoding string) string {
if encoding == "br" {
return "br"
}
return "gz"
}
+140
View File
@@ -0,0 +1,140 @@
package api
import (
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"github.com/gin-gonic/gin"
)
func newStaticTestEngine(t *testing.T) *gin.Engine {
t.Helper()
gin.SetMode(gin.TestMode)
dir := t.TempDir()
writeTestFile(t, filepath.Join(dir, "index.html"), "<!doctype html><div id=\"root\"></div>")
writeTestFile(t, filepath.Join(dir, "assets", "app.js"), "console.log('raw')")
writeTestFile(t, filepath.Join(dir, "assets", "app.js.br"), "br-payload")
writeTestFile(t, filepath.Join(dir, "assets", "app.js.gz"), "gz-payload")
engine := gin.New()
engine.Use(staticFileMiddleware(dir))
return engine
}
func writeTestFile(t *testing.T, path string, content string) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatalf("mkdir %s: %v", filepath.Dir(path), err)
}
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
t.Fatalf("write %s: %v", path, err)
}
}
func getWithHeaders(engine *gin.Engine, target string, headers map[string]string) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodGet, target, nil)
for key, value := range headers {
req.Header.Set(key, value)
}
recorder := httptest.NewRecorder()
engine.ServeHTTP(recorder, req)
return recorder
}
func TestStaticIndexIsNotCached(t *testing.T) {
recorder := getWithHeaders(newStaticTestEngine(t), "/", nil)
if recorder.Code != http.StatusOK {
t.Fatalf("GET / status = %d, want 200", recorder.Code)
}
if got := recorder.Header().Get("Cache-Control"); got != "no-cache, must-revalidate" {
t.Fatalf("Cache-Control = %q, want no-cache, must-revalidate", got)
}
if !strings.Contains(recorder.Body.String(), "id=\"root\"") {
t.Fatalf("index body = %q", recorder.Body.String())
}
}
func TestStaticAssetsAreImmutable(t *testing.T) {
recorder := getWithHeaders(newStaticTestEngine(t), "/assets/app.js", nil)
if recorder.Code != http.StatusOK {
t.Fatalf("GET /assets/app.js status = %d, want 200", recorder.Code)
}
if got := recorder.Header().Get("Cache-Control"); got != "public, max-age=31536000, immutable" {
t.Fatalf("Cache-Control = %q, want immutable asset cache", got)
}
if got := recorder.Body.String(); got != "console.log('raw')" {
t.Fatalf("body = %q, want raw file without precompression", got)
}
if got := recorder.Header().Get("Content-Encoding"); got != "" {
t.Fatalf("Content-Encoding = %q, want empty", got)
}
}
func TestStaticServesBrotliWhenAccepted(t *testing.T) {
recorder := getWithHeaders(newStaticTestEngine(t), "/assets/app.js", map[string]string{
"Accept-Encoding": "gzip, deflate, br",
})
if recorder.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", recorder.Code)
}
if got := recorder.Header().Get("Content-Encoding"); got != "br" {
t.Fatalf("Content-Encoding = %q, want br", got)
}
if got := recorder.Body.String(); got != "br-payload" {
t.Fatalf("body = %q, want brotli payload", got)
}
if got := recorder.Header().Get("Vary"); !strings.Contains(got, "Accept-Encoding") {
t.Fatalf("Vary = %q, want it to include Accept-Encoding", got)
}
}
func TestStaticFallsBackToGzip(t *testing.T) {
recorder := getWithHeaders(newStaticTestEngine(t), "/assets/app.js", map[string]string{
"Accept-Encoding": "gzip",
})
if got := recorder.Header().Get("Content-Encoding"); got != "gzip" {
t.Fatalf("Content-Encoding = %q, want gzip", got)
}
if got := recorder.Body.String(); got != "gz-payload" {
t.Fatalf("body = %q, want gzip payload", got)
}
}
func TestStaticSPAFallbackServesIndex(t *testing.T) {
recorder := getWithHeaders(newStaticTestEngine(t), "/transactions", nil)
if recorder.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", recorder.Code)
}
if !strings.Contains(recorder.Body.String(), "id=\"root\"") {
t.Fatalf("fallback body = %q, want index.html", recorder.Body.String())
}
}
func TestPreferredEncodingPrefersBrotli(t *testing.T) {
cases := map[string]string{
"": "",
"gzip": "gzip",
"deflate, gzip": "gzip",
"br": "br",
"gzip, br": "br",
"identity": "",
"gzip;q=1, br;q=0.5": "br",
"deflate": "",
}
for header, want := range cases {
if got := preferredEncoding(header); got != want {
t.Errorf("preferredEncoding(%q) = %q, want %q", header, got, want)
}
}
}
+354
View File
@@ -0,0 +1,354 @@
package api
import (
"encoding/csv"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strconv"
"household-book/model"
"household-book/service"
"github.com/gin-gonic/gin"
)
type TransactionHandler struct {
svc *service.TransactionService
}
func NewTransactionHandler(svc *service.TransactionService) *TransactionHandler {
return &TransactionHandler{svc: svc}
}
func (h *TransactionHandler) List(c *gin.Context) {
var req model.TransactionListRequest
req.Month = c.Query("month")
req.DateFrom = c.Query("date_from")
req.DateTo = c.Query("date_to")
if catID := c.Query("category_id"); catID != "" {
id, err := strconv.ParseInt(catID, 10, 64)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的分类ID"})
return
}
req.CategoryID = &id
}
req.Type = c.Query("type")
req.Keyword = c.Query("keyword")
if mID := c.Query("member_id"); mID != "" {
id, err := strconv.ParseInt(mID, 10, 64)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的成员ID"})
return
}
req.MemberID = &id
}
if aID := c.Query("account_id"); aID != "" {
id, err := strconv.ParseInt(aID, 10, 64)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的账户ID"})
return
}
req.AccountID = &id
}
if batchID := c.Query("import_batch_id"); batchID != "" {
id, err := strconv.ParseInt(batchID, 10, 64)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的导入批次ID"})
return
}
req.ImportBatchID = &id
}
if p := c.Query("page"); p != "" {
page, err := strconv.Atoi(p)
if err != nil || page < 1 {
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的页码"})
return
}
req.Page = page
} else {
req.Page = 1
}
if ps := c.Query("page_size"); ps != "" {
pageSize, err := strconv.Atoi(ps)
if err != nil || pageSize < 1 || pageSize > 100 {
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的每页条数(1-100)"})
return
}
req.PageSize = pageSize
} else {
req.PageSize = 20
}
if c.Query("format") == "csv" {
req.Page = 1
req.PageSize = 1000000
}
result, err := h.svc.List(c.Request.Context(), req)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "获取收支记录失败"})
return
}
if c.Query("format") == "csv" {
writeTransactionsCSV(c, result.Items)
return
}
c.JSON(http.StatusOK, result)
}
func writeTransactionsCSV(c *gin.Context, items []model.TransactionListItem) {
c.Header("Content-Type", "text/csv; charset=utf-8")
c.Header("Content-Disposition", `attachment; filename="transactions.csv"`)
_, _ = c.Writer.Write([]byte{0xEF, 0xBB, 0xBF})
w := csv.NewWriter(c.Writer)
_ = w.Write([]string{"日期", "类型", "金额(元)", "分类", "账户", "转入账户", "成员", "对手方", "描述", "导入文件"})
for _, item := range items {
_ = w.Write([]string{item.Date, item.Type, fmt.Sprintf("%.2f", float64(item.Amount)/100), item.CategoryName, item.AccountName, item.ToAccountName, item.MemberName, item.Counterparty, item.Description, item.ImportFilename})
}
w.Flush()
}
func (h *TransactionHandler) ListImportBatches(c *gin.Context) {
batches, err := h.svc.ListImportBatches(c.Request.Context())
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "获取导入文件列表失败"})
return
}
c.JSON(http.StatusOK, batches)
}
func (h *TransactionHandler) Import(c *gin.Context) {
req, ok := parseImportMultipart(c)
if !ok {
return
}
result, err := h.svc.Import(c.Request.Context(), req)
if err != nil {
writeImportError(c, err, "导入收支记录失败")
return
}
c.JSON(http.StatusOK, result)
}
func (h *TransactionHandler) PreviewImport(c *gin.Context) {
req, ok := parseImportMultipart(c)
if !ok {
return
}
result, err := h.svc.PreviewImport(c.Request.Context(), req)
if err != nil {
writeImportError(c, err, "解析账单预览失败")
return
}
c.JSON(http.StatusOK, result)
}
func parseImportMultipart(c *gin.Context) (model.ImportTransactionsRequest, bool) {
file, err := c.FormFile("file")
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "请选择要导入的账单文件"})
return model.ImportTransactionsRequest{}, false
}
if file.Size <= 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": "账单文件为空"})
return model.ImportTransactionsRequest{}, false
}
if file.Size > 10*1024*1024 {
c.JSON(http.StatusBadRequest, gin.H{"error": "账单文件不能超过10MB"})
return model.ImportTransactionsRequest{}, false
}
opened, err := file.Open()
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "读取账单文件失败"})
return model.ImportTransactionsRequest{}, false
}
defer opened.Close()
content, err := io.ReadAll(opened)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "读取账单文件失败"})
return model.ImportTransactionsRequest{}, false
}
req := model.ImportTransactionsRequest{
Filename: file.Filename,
Content: content,
SourceKind: c.PostForm("source_kind"),
BankName: c.PostForm("bank_name"),
CardType: c.PostForm("card_type"),
}
if accountID := c.PostForm("account_id"); accountID != "" {
id, err := strconv.ParseInt(accountID, 10, 64)
if err != nil || id <= 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的账户ID"})
return model.ImportTransactionsRequest{}, false
}
req.AccountID = &id
}
if raw := c.PostForm("category_overrides"); raw != "" {
if err := json.Unmarshal([]byte(raw), &req.CategoryOverrides); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "分类修正格式无效"})
return model.ImportTransactionsRequest{}, false
}
}
return req, true
}
func writeImportError(c *gin.Context, err error, generic string) {
if errors.Is(err, service.ErrNoImportableTransactions) {
c.JSON(http.StatusBadRequest, gin.H{"error": "未从账单中识别到可导入的收支明细"})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": generic})
}
func (h *TransactionHandler) Create(c *gin.Context) {
var req model.CreateTransactionRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数格式错误"})
return
}
if req.Type != "income" && req.Type != "expense" && req.Type != "transfer" {
c.JSON(http.StatusBadRequest, gin.H{"error": "类型必须是 income、expense 或 transfer"})
return
}
if req.Amount <= 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": "金额必须大于0"})
return
}
if req.Date == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "日期不能为空"})
return
}
if req.Type == "transfer" {
if req.AccountID == nil || req.ToAccountID == nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "转账必须同时选择转出账户和转入账户"})
return
}
if *req.AccountID == *req.ToAccountID {
c.JSON(http.StatusBadRequest, gin.H{"error": "转出账户与转入账户不能相同"})
return
}
req.CategoryID = nil
} else {
if req.CategoryID == nil || *req.CategoryID <= 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": "必须选择分类"})
return
}
req.ToAccountID = nil
}
t, err := h.svc.Create(c.Request.Context(), req)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "添加收支记录失败"})
return
}
c.JSON(http.StatusCreated, t)
}
func (h *TransactionHandler) 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.UpdateTransactionRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数格式错误"})
return
}
if req.Amount != nil && *req.Amount <= 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": "金额必须大于0"})
return
}
if req.Type != nil && *req.Type != "income" && *req.Type != "expense" && *req.Type != "transfer" {
c.JSON(http.StatusBadRequest, gin.H{"error": "类型必须是 income、expense 或 transfer"})
return
}
if req.CategoryID.Set && req.CategoryID.Valid && req.CategoryID.Value <= 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": "必须选择分类"})
return
}
if req.Type != nil && *req.Type == "transfer" {
if req.ToAccountID.Set && !req.ToAccountID.Valid {
c.JSON(http.StatusBadRequest, gin.H{"error": "转账必须选择转入账户"})
return
}
}
t, 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
}
if errors.Is(err, service.ErrInvalidTransaction) {
c.JSON(http.StatusBadRequest, gin.H{"error": "交易类型、分类和转账账户组合不合法"})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": "更新收支记录失败"})
return
}
c.JSON(http.StatusOK, t)
}
func (h *TransactionHandler) DeleteBatch(c *gin.Context) {
var req model.DeleteTransactionsRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数格式错误"})
return
}
if len(req.IDs) == 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": "请选择要删除的收支记录"})
return
}
if len(req.IDs) > 500 {
c.JSON(http.StatusBadRequest, gin.H{"error": "单次最多删除500条记录"})
return
}
deleted, err := h.svc.DeleteBatch(c.Request.Context(), req.IDs)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "批量删除收支记录失败"})
return
}
c.JSON(http.StatusOK, model.DeleteTransactionsResult{DeletedCount: deleted})
}
func (h *TransactionHandler) DeleteImportBatch(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
}
deleted, err := h.svc.DeleteImportBatch(c.Request.Context(), id)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "按导入文件删除失败"})
return
}
c.JSON(http.StatusOK, model.DeleteTransactionsResult{DeletedCount: deleted})
}
func (h *TransactionHandler) 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
}
c.JSON(http.StatusInternalServerError, gin.H{"error": "删除收支记录失败"})
return
}
c.Status(http.StatusNoContent)
}