Added measurements, and devices statsh

Added stats endpoints
This commit is contained in:
Nedim
2023-10-20 12:03:59 +02:00
parent 6892c56c1e
commit d40b225e4e
12 changed files with 1120 additions and 5 deletions

View File

@@ -4,9 +4,11 @@ import (
"errors"
"fmt"
"log"
"math"
"net/http"
"strconv"
"strings"
"time"
"github.com/jinzhu/gorm"
"gitlab.com/pactual1/backend/models"
@@ -170,4 +172,156 @@ func SaveDeviceInfoToDB(deviceInfo models.DeviceInfo, rawData []byte) (models.De
return deviceInfo, device, nil
}
}
func CountDeviceInfoByCompany(companyID uint) (int64, error) {
var contracts []models.Contract
var allDeviceIDs []int64
var count int64
// Find all contracts where the company is either a buyer or a seller
if err := shared.GetDb().Where("buyer_id = ? OR seller_id = ?", companyID, companyID).Find(&contracts).Error; err != nil {
log.Printf("CountDeviceInfoByCompany Error: Database error: %v", err)
return 0, err
}
// Aggregate all DeviceIDs from these contracts
for _, contract := range contracts {
allDeviceIDs = append(allDeviceIDs, contract.DeviceIDs...)
}
// Count DeviceInfo entries related to these DeviceIDs
if err := shared.GetDb().Model(&models.DeviceInfo{}).Where("device_id IN (?)", allDeviceIDs).Count(&count).Error; err != nil {
log.Printf("CountDeviceInfoByCompany Error: Database error: %v", err)
return 0, err
}
return count, nil
}
func CountDeviceBreachedAndNormalDevicesByCompany(companyID uint, startTime, endTime time.Time) (int64, int64, map[string]map[string]int64, error) {
var contracts []models.Contract
var allDeviceIDs []int64
var inRangeCount, outOfRangeCount int64
monthlyCounts := make(map[string]map[string]int64)
// Fetch all contracts related to the company
if err := shared.GetDb().Where("buyer_id = ? OR seller_id = ?", companyID, companyID).Find(&contracts).Error; err != nil {
log.Printf("CountDeviceInfoByCompany Error: Database error: %v", err)
return 0, 0, nil, err
}
// Aggregate all DeviceIDs
for _, contract := range contracts {
allDeviceIDs = append(allDeviceIDs, contract.DeviceIDs...)
}
// Iterate through each month within the specified date range
for dt := startTime; dt.Before(endTime); dt = dt.AddDate(0, 1, 0) {
monthEnd := dt.AddDate(0, 1, 0)
if monthEnd.After(endTime) {
monthEnd = endTime
}
startUnix := dt.Unix()
endUnix := monthEnd.Unix()
// Initialize monthlyCounts for the current month
monthKey := dt.Format("2006-01")
monthlyCounts[monthKey] = map[string]int64{"inRange": 0, "outOfRange": 0}
// Count DeviceInfo entries with temperatures in range and out of range for the current month
for _, contract := range contracts {
var inRange, outOfRange int64
err := shared.GetDb().Model(&models.DeviceInfo{}).
Where("device_id IN (?) AND temperature >= ? AND temperature <= ? AND timestamp >= ? AND timestamp <= ?",
allDeviceIDs, contract.MinTemp, contract.MaxTemp, startUnix, endUnix).
Count(&inRange).Error
if err != nil {
return 0, 0, nil, err
}
err = shared.GetDb().Model(&models.DeviceInfo{}).
Where("device_id IN (?) AND (temperature < ? OR temperature > ?) AND timestamp >= ? AND timestamp <= ?",
allDeviceIDs, contract.MinTemp, contract.MaxTemp, startUnix, endUnix).
Count(&outOfRange).Error
if err != nil {
return 0, 0, nil, err
}
// Update the counts for the current month
monthlyCounts[monthKey]["inRange"] += inRange
monthlyCounts[monthKey]["outOfRange"] += outOfRange
// Update the total counts
inRangeCount += inRange
outOfRangeCount += outOfRange
}
}
return inRangeCount, outOfRangeCount, monthlyCounts, nil
}
type ContractLocationMatch struct {
ContractID uint
DeviceInfoID uint
}
const oneKmInDegrees = 0.009 // Approximately 1 km in degrees for lat/lon
func isWithinOneKm(lat1, lon1, lat2, lon2 float64) bool {
return math.Abs(lat1-lat2) <= oneKmInDegrees && math.Abs(lon1-lon2) <= oneKmInDegrees
}
func FetchMatchingContractsAndDeviceInfo(companyID uint64, startTime, endTime time.Time) ([]ContractLocationMatch, error) {
var contracts []models.Contract
var results []ContractLocationMatch
registeredDevices := make(map[uint]bool) // Map to keep track of registered devices
//Fetch contracts
err := shared.GetDb().
Where("start_time >= ? AND end_time <= ? AND (buyer_id = ? OR seller_id = ?) ", startTime, endTime, companyID, companyID).
Find(&contracts).Error
if err != nil {
return nil, err
}
//Loop through each contract to find matching DeviceInfo
for _, contract := range contracts {
var deviceInfos []models.DeviceInfo
deviceIDStr := strings.Trim(strings.Join(strings.Fields(fmt.Sprint(contract.DeviceIDs)), ","), "[]")
queryString := fmt.Sprintf("device_id IN (%s) AND created_at >= ? AND created_at <= ?", deviceIDStr)
err := shared.GetDb().
Where(queryString, contract.StartTime, contract.EndTime).
Find(&deviceInfos).Error
if err != nil {
return nil, err
}
// Compare locations and created_at
for _, deviceInfo := range deviceInfos {
// Continue to the next iteration if this device has already been registered
if registeredDevices[deviceInfo.DeviceID] {
continue
}
if isWithinOneKm(contract.StartLat, contract.StartLon, deviceInfo.Lat, deviceInfo.Lon) ||
isWithinOneKm(contract.EndLat, contract.EndLon, deviceInfo.Lat, deviceInfo.Lon) {
results = append(results, ContractLocationMatch{
ContractID: contract.ID,
DeviceInfoID: deviceInfo.ID,
})
registeredDevices[deviceInfo.DeviceID] = true // Mark this device as registered
}
}
}
return results, nil
}