Files
astra-users/handler/position.go
2023-08-17 17:08:34 +03:00

118 lines
2.3 KiB
Go

package handler
import (
"astra-users/model"
"astra-users/pkg/utils"
"errors"
"github.com/labstack/echo/v4"
"net/http"
)
func (h *Handler) GetPositionHandler(c echo.Context) error {
id := c.Param("id")
position, err := h.GetPosition(id)
if err != nil {
return err
}
return c.JSON(http.StatusOK, position)
}
func (h *Handler) GetPositions(c echo.Context) error {
var positions []model.Position
h.DB.Find(&positions)
return c.JSON(http.StatusOK, positions)
}
func (h *Handler) GetPositionsByOrg(c echo.Context) error {
id := c.Param("id")
var positions []model.Position
h.DB.Where("organization_id = ?", id).Find(&positions)
return c.JSON(http.StatusOK, positions)
}
func (h *Handler) GetPosition(id string) (*model.Position, error) {
var position model.Position
r := h.DB.Find(&position, id)
if r.RowsAffected == 0 {
return nil, errors.New("position not found")
}
return &position, nil
}
func (h *Handler) CreatePosition(c echo.Context) (err error) {
position := new(model.PositionApi)
if err = c.Bind(position); err != nil {
return c.NoContent(http.StatusBadRequest)
}
newPosition, err := utils.TypeConverter[model.Position](position)
tx := h.DB.Create(&newPosition)
if tx.RowsAffected == 0 {
return c.NoContent(http.StatusBadGateway)
}
return c.JSON(http.StatusCreated, newPosition)
}
func (h *Handler) DeletePosition(c echo.Context) error {
id := c.Param("id")
tx := h.DB.Model(model.Position{}).Delete(id)
if tx.RowsAffected == 0 {
return c.NoContent(http.StatusNotFound)
}
return c.NoContent(http.StatusOK)
}
func (h *Handler) UpdatePosition(c echo.Context) (err error) {
position := new(model.PositionApi)
var newPosition model.Position
id := c.Param("id")
if err = c.Bind(position); err != nil {
return c.NoContent(http.StatusBadRequest)
}
tx := h.DB.Find(&newPosition, id)
if tx.RowsAffected == 0 {
return c.NoContent(http.StatusNotFound)
}
if position.RightMask != 0 {
newPosition.RightMask = position.RightMask
}
if position.Name != "" {
newPosition.Name = position.Name
}
if position.OrganizationID.ID() != 0 {
newPosition.OrganizationID = position.OrganizationID
}
tx = tx.Save(&newPosition)
if tx.RowsAffected == 0 {
return c.NoContent(http.StatusBadGateway)
}
return c.JSON(http.StatusCreated, newPosition)
}