75 lines
2.4 KiB
Go
75 lines
2.4 KiB
Go
package controllers
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"log"
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/jinzhu/gorm"
|
|
"gitlab.com/pactual1/backend/models"
|
|
"gitlab.com/pactual1/backend/shared"
|
|
)
|
|
|
|
func SaveDeviceInfo(c *gin.Context) {
|
|
var deviceInfo models.DeviceInfo
|
|
rawData, _ := c.GetRawData()
|
|
|
|
// Unmarshal to the important info structure
|
|
err := json.Unmarshal(rawData, &deviceInfo)
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid JSON payload"})
|
|
log.Printf("Invalid json pyload : %v", err)
|
|
return
|
|
}
|
|
|
|
deviceInfo.RawJSON = string(rawData)
|
|
|
|
// Attempt to find the device by IMEI; if not found, create a new device
|
|
var device models.Device
|
|
if err := shared.GetDb().Unscoped().Where("imei = ?", deviceInfo.IMEI).First(&device).Error; err != nil {
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
// Create new device
|
|
newDevice := models.Device{
|
|
IMEI: deviceInfo.IMEI,
|
|
IMSI: deviceInfo.IMSI,
|
|
DeviceConfiguration: string(rawData),
|
|
}
|
|
if err := shared.GetDb().Create(&newDevice).Error; err != nil {
|
|
log.Printf("CREATE -Device DB Error: %v", err)
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Could not create new device"})
|
|
return
|
|
}
|
|
deviceInfo.DeviceID = newDevice.ID
|
|
} else {
|
|
log.Printf("CREATE -Device DB Error: %v", err)
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Database error"})
|
|
return
|
|
}
|
|
} else {
|
|
log.Printf("Current device deleted at: %v", device.DeletedAt)
|
|
|
|
if device.DeletedAt != nil {
|
|
// Use raw SQL to update the record
|
|
if err := shared.GetDb().Exec("UPDATE devices SET deleted_at = NULL, company_id = NULL WHERE id = ?", device.ID).Error; err != nil {
|
|
log.Printf("UNDELETE -Device DB Error: %v", err)
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Could not revive deleted device"})
|
|
return
|
|
} else {
|
|
log.Printf("Device undeleted successfuly : %v", device.DeletedAt)
|
|
}
|
|
}
|
|
deviceInfo.DeviceID = device.ID
|
|
}
|
|
|
|
// Save deviceInfo to your database
|
|
if err := shared.GetDb().Create(&deviceInfo).Error; err != nil {
|
|
log.Printf("SaveDeviceInfo CREATE -DeviceInfo DB Error: %v", err)
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Could not save device info"})
|
|
return
|
|
}
|
|
log.Printf("Successfully received and saved device info: %v", deviceInfo)
|
|
c.JSON(http.StatusOK, gin.H{"message": "Successfully received and saved device info", "data": deviceInfo})
|
|
}
|