102 lines
2.5 KiB
Go
102 lines
2.5 KiB
Go
package handler
|
|
|
|
import (
|
|
"net/http"
|
|
"strconv"
|
|
|
|
"github.com/1024XEngineer/xinfra/server/internal/service"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
type MachineHandler struct {
|
|
machines *service.MachineService
|
|
}
|
|
|
|
func NewMachineHandler(machines *service.MachineService) *MachineHandler {
|
|
return &MachineHandler{machines: machines}
|
|
}
|
|
|
|
func (h *MachineHandler) Overview(c *gin.Context) {
|
|
claims, ok := CurrentClaims(c)
|
|
if !ok {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "missing current user"})
|
|
return
|
|
}
|
|
businessLineID, ok := queryUint(c, "business_line_id")
|
|
if !ok {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "business_line_id is required"})
|
|
return
|
|
}
|
|
overview, err := h.machines.Overview(c.Request.Context(), claims.UserID, claims.IsAdmin, businessLineID)
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, overview)
|
|
}
|
|
|
|
func (h *MachineHandler) List(c *gin.Context) {
|
|
claims, ok := CurrentClaims(c)
|
|
if !ok {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "missing current user"})
|
|
return
|
|
}
|
|
businessLineID, ok := queryUint(c, "business_line_id")
|
|
if !ok {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "business_line_id is required"})
|
|
return
|
|
}
|
|
resources, err := h.machines.List(c.Request.Context(), claims.UserID, claims.IsAdmin, service.MachineListQuery{
|
|
BusinessLineID: businessLineID,
|
|
Page: queryInt(c, "page", 1),
|
|
Size: queryInt(c, "size", 20),
|
|
Hostname: c.Query("hostname"),
|
|
AssetNumber: c.Query("assetNumber"),
|
|
Type: c.Query("type"),
|
|
Location: c.Query("location"),
|
|
IP: c.Query("ip"),
|
|
Spec: c.Query("spec"),
|
|
Source: c.Query("source"),
|
|
Status: c.Query("status"),
|
|
})
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, resources)
|
|
}
|
|
|
|
func (h *MachineHandler) Sync(c *gin.Context) {
|
|
state, err := h.machines.SyncNow(c.Request.Context())
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error(), "state": state})
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, state)
|
|
}
|
|
|
|
func queryInt(c *gin.Context, key string, fallback int) int {
|
|
value := c.Query(key)
|
|
if value == "" {
|
|
return fallback
|
|
}
|
|
n, err := strconv.Atoi(value)
|
|
if err != nil {
|
|
return fallback
|
|
}
|
|
return n
|
|
}
|
|
|
|
func queryUint(c *gin.Context, key string) (uint64, bool) {
|
|
value := c.Query(key)
|
|
if value == "" {
|
|
return 0, false
|
|
}
|
|
n, err := strconv.ParseUint(value, 10, 64)
|
|
if err != nil || n == 0 {
|
|
return 0, false
|
|
}
|
|
return n, true
|
|
}
|