118 lines
2.4 KiB
Go
118 lines
2.4 KiB
Go
package handlers
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"github.com/dusiburg/kotosoft-id/internal/models"
|
|
"github.com/dusiburg/kotosoft-id/internal/services"
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
type PositionsHandler struct {
|
|
svc *services.Service
|
|
}
|
|
|
|
func NewPositionsHandler(svc *services.Service) *PositionsHandler {
|
|
return &PositionsHandler{svc: svc}
|
|
}
|
|
|
|
func localeFromRequest(c *gin.Context) string {
|
|
if l := c.GetHeader("X-Locale"); l != "" {
|
|
return l
|
|
}
|
|
if l := c.GetHeader("Accept-Language"); l != "" {
|
|
return l
|
|
}
|
|
return "ru"
|
|
}
|
|
|
|
func userIDFromContext(c *gin.Context) (uuid.UUID, bool) {
|
|
v, ok := c.Get("user_id")
|
|
if !ok {
|
|
return uuid.Nil, false
|
|
}
|
|
id, ok := v.(uuid.UUID)
|
|
return id, ok
|
|
}
|
|
|
|
func (h *PositionsHandler) GetMyPositions(c *gin.Context) {
|
|
userID, ok := userIDFromContext(c)
|
|
if !ok {
|
|
c.Error(models.ErrUnauthorized)
|
|
return
|
|
}
|
|
|
|
positions, err := h.svc.GetUserPositions(c.Request.Context(), userID, localeFromRequest(c))
|
|
if err != nil {
|
|
c.Error(models.ErrInternal)
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, positions)
|
|
}
|
|
|
|
type upsertPositionRequest struct {
|
|
Code string `json:"code" binding:"required"`
|
|
Name string `json:"name" binding:"required"`
|
|
Description *string `json:"description"`
|
|
}
|
|
|
|
func (h *PositionsHandler) ListPositions(c *gin.Context) {
|
|
userID, ok := userIDFromContext(c)
|
|
if !ok {
|
|
c.Error(models.ErrUnauthorized)
|
|
return
|
|
}
|
|
|
|
isAdmin, err := h.svc.UserIsPositionsAdmin(c.Request.Context(), userID)
|
|
if err != nil {
|
|
c.Error(models.ErrInternal)
|
|
return
|
|
}
|
|
if !isAdmin {
|
|
c.Error(models.ErrForbidden)
|
|
return
|
|
}
|
|
|
|
positions, err := h.svc.GetAllPositions(c.Request.Context(), localeFromRequest(c))
|
|
if err != nil {
|
|
c.Error(models.ErrInternal)
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, positions)
|
|
}
|
|
|
|
func (h *PositionsHandler) UpsertPosition(c *gin.Context) {
|
|
userID, ok := userIDFromContext(c)
|
|
if !ok {
|
|
c.Error(models.ErrUnauthorized)
|
|
return
|
|
}
|
|
|
|
isAdmin, err := h.svc.UserIsPositionsAdmin(c.Request.Context(), userID)
|
|
if err != nil {
|
|
c.Error(models.ErrInternal)
|
|
return
|
|
}
|
|
if !isAdmin {
|
|
c.Error(models.ErrForbidden)
|
|
return
|
|
}
|
|
|
|
var req upsertPositionRequest
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
c.Error(models.ErrBadRequest)
|
|
return
|
|
}
|
|
|
|
if err := h.svc.UpsertPositionForLocale(c.Request.Context(), req.Code, localeFromRequest(c), req.Name, req.Description); err != nil {
|
|
c.Error(models.ErrInternal)
|
|
return
|
|
}
|
|
|
|
c.Status(http.StatusNoContent)
|
|
}
|
|
|