budget-go/web/controller/transaction/controller.go
2024-09-18 15:18:16 +02:00

112 lines
2.2 KiB
Go

package transaction
import (
"bytes"
"fmt"
"io"
"strconv"
"github.com/labstack/echo/v4"
"gitnet.fr/deblan/budget/database/manager"
"gitnet.fr/deblan/budget/database/model"
"gitnet.fr/deblan/budget/web/controller/crud"
"gorm.io/gorm"
)
type Controller struct {
crud *crud.Controller
}
func (ctrl *Controller) Config() crud.Configuration {
return crud.Configuration{
Model: model.Transaction{},
Models: []model.Transaction{},
ValidOrders: []string{"accounted_at", "short_label", "label", "reference", "information", "operation_type", "debit", "credit", "date"},
DefaultLimit: 20,
DefaultOrder: "date",
DefaultSort: "desc",
CreateModel: func() interface{} {
return new(model.Transaction)
},
ListQuery: func(db *gorm.DB) {
db.Joins("BankAccount")
db.Joins("Category")
},
}
}
func New(e *echo.Echo) *Controller {
c := Controller{
crud: crud.New(),
}
e.GET("/api/transaction", c.List)
e.POST("/api/transactions", c.Create)
e.GET("/api/transaction/:id", c.Show)
return &c
}
func (ctrl *Controller) List(c echo.Context) error {
if nil == model.LoadSessionUser(c) {
return c.Redirect(302, "/login")
}
return ctrl.crud.With(ctrl.Config()).List(c)
}
func (ctrl *Controller) Show(c echo.Context) error {
if nil == model.LoadSessionUser(c) {
return c.Redirect(302, "/login")
}
return ctrl.crud.With(ctrl.Config()).Show(c)
}
func (ctrl *Controller) Create(c echo.Context) error {
if nil == model.LoadSessionUser(c) {
return c.Redirect(302, "/login")
}
db := manager.Get().Db
bankAccountID, err := strconv.Atoi(c.FormValue("bank_account_id"))
fmt.Printf("%+v\n", c.FormValue("bank_account_id"))
if err != nil {
return err
}
var count int64
db.Model(model.BankAccount{}).Where("id = ?", bankAccountID).Count(&count)
if count == 0 {
return c.JSON(400, crud.Error{
Code: 404,
Message: "Invalid bank account",
})
}
file, err := c.FormFile("file")
if err != nil {
return err
}
src, err := file.Open()
if err != nil {
return err
}
defer src.Close()
var buf bytes.Buffer
io.Copy(&buf, src)
datas, err := model.ImportTransactions(string(buf.Bytes()), bankAccountID)
if err != nil {
return err
}
return c.JSON(200, datas)
}