budget-go/backend/controller/bank_account/controller.go
2025-02-08 20:19:26 +01:00

103 lines
2.3 KiB
Go

package bank_account
import (
"github.com/labstack/echo/v4"
"gitnet.fr/deblan/budget/database/model"
"gitnet.fr/deblan/budget/backend/controller/crud"
"gorm.io/gorm"
)
type Controller struct {
crud *crud.Controller
}
func (ctrl *Controller) Config() crud.Configuration {
return crud.Configuration{
Table: "bank_accounts",
Model: model.BankAccount{},
Models: []model.BankAccount{},
ValidOrders: []string{"id", "label"},
DefaultLimit: 20,
CreateModel: func() interface{} {
return new(model.BankAccount)
},
}
}
func New(e *echo.Echo) *Controller {
c := Controller{
crud: crud.New(),
}
e.GET("/api/bank_account", c.List)
e.POST("/api/bank_account", c.Create)
e.GET("/api/bank_account/:id", c.Show)
e.POST("/api/bank_account/:id", c.Update)
e.DELETE("/api/bank_account/:id", c.Delete)
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) Delete(c echo.Context) error {
if nil == model.LoadSessionUser(c) {
return c.Redirect(302, "/login")
}
return ctrl.crud.With(ctrl.Config()).Delete(c)
}
func (ctrl *Controller) Create(c echo.Context) error {
if nil == model.LoadSessionUser(c) {
return c.Redirect(302, "/login")
}
type body struct {
Label string `json:"label" form:"label" validate:"required"`
}
return ctrl.crud.With(ctrl.Config()).Create(c, new(body), func(db *gorm.DB, v interface{}) (interface{}, error) {
value := v.(*body)
item := model.NewBankAccount(value.Label)
db.Model(ctrl.crud.Config.Model).Create(&item)
return item, nil
})
}
func (ctrl *Controller) Update(c echo.Context) error {
if nil == model.LoadSessionUser(c) {
return c.Redirect(302, "/login")
}
type body struct {
Label string `json:"label" form:"label" validate:"required"`
}
return ctrl.crud.With(ctrl.Config()).Update(c, new(body), func(db *gorm.DB, a, b interface{}) (interface{}, error) {
item := a.(*model.BankAccount)
update := b.(*body)
item.Label = update.Label
db.Model(ctrl.crud.Config.Model).Where("id = ?", item.ID).Save(&item)
return item, nil
})
}