97 lines
2.6 KiB
Go
97 lines
2.6 KiB
Go
package controllers
|
|
|
|
import (
|
|
"net/http"
|
|
"s-class-backend/config"
|
|
"s-class-backend/models"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// GET ALL ROOMS
|
|
func GetRooms(c *gin.Context) {
|
|
var rooms []models.Room
|
|
if err := config.DB.Find(&rooms).Error; err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Gagal mengambil data ruangan"})
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, gin.H{"data": rooms})
|
|
}
|
|
|
|
// CREATE ROOM
|
|
func CreateRoom(c *gin.Context) {
|
|
var input models.Room
|
|
if err := c.ShouldBindJSON(&input); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
if err := config.DB.Create(&input).Error; err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Gagal membuat ruangan"})
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, gin.H{"message": "Ruangan berhasil ditambahkan!", "data": input})
|
|
}
|
|
|
|
// --- STRUKTUR DATA UNTUK MENERIMA JSON ---
|
|
|
|
type UpdateRoomStatusInput struct {
|
|
Status string `json:"status" binding:"required"`
|
|
}
|
|
|
|
type EnergySensorInput struct {
|
|
RoomID int `json:"room_id" binding:"required"`
|
|
Power float64 `json:"power" binding:"required"`
|
|
}
|
|
|
|
// --- FUNGSI HANDLER ---
|
|
|
|
// UPDATE ROOM STATUS (Admin: Available <-> Maintenance)
|
|
func UpdateRoomStatus(c *gin.Context) {
|
|
roomID := c.Param("id")
|
|
var input UpdateRoomStatusInput
|
|
|
|
if err := c.ShouldBindJSON(&input); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
var room models.Room
|
|
// Karena model sudah di-tag dengan benar, pencarian ini pasti akan berhasil
|
|
if err := config.DB.Where("room_id = ?", roomID).First(&room).Error; err != nil {
|
|
c.JSON(http.StatusNotFound, gin.H{"error": "Ruangan tidak ditemukan"})
|
|
return
|
|
}
|
|
|
|
room.Status = input.Status
|
|
if err := config.DB.Save(&room).Error; err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Gagal menyimpan perubahan"})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, gin.H{
|
|
"message": "Status ruangan berhasil diperbarui",
|
|
"data": room,
|
|
})
|
|
}
|
|
|
|
// UPDATE ROOM POWER (Menerima data Watt dari ESP32)
|
|
func UpdateRoomPower(c *gin.Context) {
|
|
var input EnergySensorInput
|
|
|
|
if err := c.ShouldBindJSON(&input); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "Format data sensor salah"})
|
|
return
|
|
}
|
|
|
|
var room models.Room
|
|
// Tetap gunakan room_id agar GORM tidak bingung
|
|
if err := config.DB.Where("room_id = ?", input.RoomID).First(&room).Error; err != nil {
|
|
c.JSON(http.StatusNotFound, gin.H{"error": "Ruangan tidak ditemukan"})
|
|
return
|
|
}
|
|
|
|
room.PowerConsumption = input.Power
|
|
config.DB.Save(&room)
|
|
|
|
c.JSON(http.StatusOK, gin.H{"message": "Data daya ESP32 berhasil disimpan"})
|
|
} |