Files
old-backend/database/device/device.go
2023-10-19 08:48:01 +02:00

173 lines
5.8 KiB
Go

package device
import (
"errors"
"fmt"
"log"
"net/http"
"strconv"
"strings"
"github.com/jinzhu/gorm"
"gitlab.com/pactual1/backend/models"
"gitlab.com/pactual1/backend/services/messaging"
"gitlab.com/pactual1/backend/shared"
)
func GetDevicesForContract(contractID uint64) ([]models.Device, int, error) {
// Fetch the contract from the database
var contract models.Contract
if err := shared.GetDb().Where("id = ?", contractID).First(&contract).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
log.Printf("GetDevicesByContract Error: No contract found: %v", err)
return nil, http.StatusNotFound, err
} else {
log.Printf("GetDevicesByContract Error: Database error: %v", err)
return nil, http.StatusInternalServerError, err
}
}
log.Printf("This is the device IDS ID: %v", contract.DeviceIDs)
return GetDevicesByID(contract.DeviceIDs)
}
func GetDevicesByID(deviceIDs []int64) ([]models.Device, int, error) {
// Create a slice to hold the devices
var devices []models.Device
// Convert the integer array to a comma-separated string
idStrings := []string{}
for _, id := range deviceIDs {
idStrings = append(idStrings, strconv.FormatInt(id, 10))
}
idStr := strings.Join(idStrings, ",")
// Construct the SQL query manually
sqlQuery := fmt.Sprintf("SELECT * FROM devices WHERE id IN (%s)", idStr)
// Fetch devices from the database based on DeviceIDs in the contract
// Execute the query
if err := shared.GetDb().Raw(sqlQuery).Scan(&devices).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
log.Printf("GetDevicesByContract Error: No devices found: %v", err)
return devices, http.StatusNotFound, err
} else {
log.Printf("GetDevicesByContract Error: Database error: %v", err)
return devices, http.StatusInternalServerError, err
}
}
return devices, http.StatusOK, nil
}
func GetDeviceInfoForContract(deviceID uint64, contract models.Contract) (models.GeoJSONFeatureCollection, int, error) {
var deviceInfos []models.DeviceInfo
// Create a GeoJSON feature collection
var featureCollection models.GeoJSONFeatureCollection
featureCollection.Type = "FeatureCollection"
featureCollection.Features = []models.GeoJSONFeature{}
// Modify your query to include filtering based on the contract's creation date
query := shared.GetDb().Where("device_id = ?", deviceID).Where("created_at >= ? AND created_at <= ?", contract.StartTime, contract.EndTime)
if err := query.Find(&deviceInfos).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
log.Printf("GetDeviceData Error: No device info found: %v", err)
return featureCollection, http.StatusNotFound, err
} else {
log.Printf("GetDeviceData Error: Database error: %v", err)
return featureCollection, http.StatusNotFound, err
}
}
deviceInfosResponse := models.ConvertDeviceInfoToResponse(deviceInfos)
// Loop through each deviceInfo to create GeoJSON features
for _, info := range deviceInfosResponse {
info.RawJSON = ""
feature := models.GeoJSONFeature{
Type: "Feature",
DeviceInfoResponse: &info,
Geometry: models.GeoJSONGeometry{
Type: "Point",
Coordinates: []float64{info.Lon, info.Lat},
},
Properties: map[string]interface{}{},
}
featureCollection.Features = append(featureCollection.Features, feature)
}
return featureCollection, 0, nil
}
func SaveDeviceInfoToDB(deviceInfo models.DeviceInfo, rawData []byte) (models.DeviceInfo, models.Device, error) {
deviceInfo.RawJSON = string(rawData)
deviceInfo.X = deviceInfo.AccInfo.X
deviceInfo.Y = deviceInfo.AccInfo.Y
deviceInfo.Z = deviceInfo.AccInfo.Z
var device models.Device
if err := shared.GetDb().Unscoped().Where("device_id = ?", deviceInfo.ExternalDeviceID).First(&device).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
newDevice := models.Device{
IMEI: deviceInfo.IMEI,
IMSI: deviceInfo.IMSI,
DeviceID: deviceInfo.ExternalDeviceID,
DeviceConfiguration: string(rawData),
}
if err := shared.GetDb().Create(&newDevice).Error; err != nil {
return deviceInfo, device, fmt.Errorf("CREATE -Device DB Error: %v", err)
}
deviceInfo.DeviceID = newDevice.ID
} else {
return deviceInfo, device, fmt.Errorf("CREATE -Device DB Error: %v", err)
}
} else {
if device.DeletedAt.Valid {
if err := shared.GetDb().Exec("UPDATE devices SET deleted_at = NULL, company_id = NULL WHERE id = ?", device.ID).Error; err != nil {
return deviceInfo, device, fmt.Errorf("UNDELETE -Device DB Error: %v", err)
}
}
deviceInfo.DeviceID = device.ID
}
if err := shared.GetDb().Create(&deviceInfo).Error; err != nil {
return deviceInfo, device, fmt.Errorf("SaveDeviceInfo CREATE -DeviceInfo DB Error: %v", err)
}
go func(deviceInfo models.DeviceInfo) {
var contract models.Contract
if err := shared.GetDb().Where("device_ids @> ARRAY[?]::integer[]", deviceInfo.DeviceID).First(&contract).Error; err != nil {
log.Printf("could not find associated contract: %v", err)
}
messagingChannel:= messaging.GetMessagingChannel()
if deviceInfo.Temperature > contract.MaxTemp || deviceInfo.Temperature < contract.MinTemp {
notification := models.Notification{
Title: "Temperature Alert",
NotificationType: "Temperature",
Text: fmt.Sprintf("Device %s has a temperature outside the permitted range.", deviceInfo.ExternalDeviceID),
CompanyID: int(contract.BuyerID),
}
sellerNotification := models.Notification{
Title: "Temperature Alert",
NotificationType: "Temperature",
Text: fmt.Sprintf("Device %s has a temperature outside the permitted range.", deviceInfo.ExternalDeviceID),
CompanyID: int(contract.SellerID),
}
messagingChannel <- notification
messagingChannel <- sellerNotification
}
}(deviceInfo)
return deviceInfo, device, nil
}