355 lines
10 KiB
Go
355 lines
10 KiB
Go
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)
|
||
}
|