Upstream sync

This commit is contained in:
Senad Uka
2023-10-31 07:35:23 +01:00
parent 06aec8c900
commit 75692d7b20
6 changed files with 930 additions and 186 deletions

View File

@@ -15,6 +15,7 @@ import (
"gitlab.com/pactual1/backend/database/device"
"gitlab.com/pactual1/backend/models"
"gitlab.com/pactual1/backend/services/blockchain"
"gitlab.com/pactual1/backend/services/messaging"
"gitlab.com/pactual1/backend/shared"
)
@@ -167,21 +168,42 @@ func UpdateContract(contract models.Contract) (models.Contract, int, error) {
}
// Create contract in blockchain only when it is signed
if oldContract.Status != contract.Status && contract.Status == models.ContractStatusSigned {
err = blockchain.NewService(config.AppConfig.Blockchain).CreateContract(context.Background(), shared.CovertUintToByte32(contract.ID))
if err != nil {
log.Printf("UpdateContract Error: Could not create contract in blockchain: %v", err)
return contract, http.StatusInternalServerError, err
}
if oldContract.Status != contract.Status {
// Register devices in blockchain when contract is signed
for _, device := range devices {
err = blockchain.NewService(config.AppConfig.Blockchain).RegisterNewDeviceID(context.Background(), shared.CovertUintToByte32(contract.ID), shared.CovertUintToByte32(device.ID))
if contract.Status == models.ContractStatusSigned {
err = blockchain.NewService(config.AppConfig.Blockchain).CreateContract(context.Background(), shared.CovertUintToByte32(contract.ID))
if err != nil {
log.Printf("UpdateContract Error: Could not register contract device in blockchain: %v", err)
log.Printf("UpdateContract Error: Could not create contract in blockchain: %v", err)
return contract, http.StatusInternalServerError, err
}
// Register devices in blockchain when contract is signed
for _, device := range devices {
err = blockchain.NewService(config.AppConfig.Blockchain).RegisterNewDeviceID(context.Background(), shared.CovertUintToByte32(contract.ID), shared.CovertUintToByte32(device.ID))
if err != nil {
log.Printf("UpdateContract Error: Could not register contract device in blockchain: %v", err)
return contract, http.StatusInternalServerError, err
}
}
}
messagingChannel := messaging.GetMessagingChannel()
notification := models.Notification{
Title: "Contract Alert",
NotificationType: "Contract",
Text: fmt.Sprintf("Contract %s status updated to %s", contract.Name, contract.Status),
CompanyID: int(contract.BuyerID),
}
messagingChannel <- notification
sellerNotification := models.Notification{
Title: "Contract Alert",
NotificationType: "Contract",
Text: fmt.Sprintf("Contract %s status updated to %s", contract.Name, contract.Status),
CompanyID: int(contract.SellerID),
}
messagingChannel <- sellerNotification
}
return contract, status, err
@@ -243,59 +265,59 @@ func GetContractByID(contractID uint) (models.Contract, int, error) {
}
func CountContractsByMultipleStatusesAndTotal(companyID uint, startTime, endTime time.Time) (int64, int64, int64, map[string]map[string]int64, error) {
var activeCount, executedCount, totalCount int64
monthlyCounts := make(map[string]map[string]int64)
var activeCount, executedCount, totalCount int64
monthlyCounts := make(map[string]map[string]int64)
var contract models.Contract
var contract models.Contract
// 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
}
// 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
}
// Initialize monthlyCounts for the current month
monthKey := dt.Format("2006-01")
monthlyCounts[monthKey] = map[string]int64{"active": 0, "executed": 0, "total": 0}
// Initialize monthlyCounts for the current month
monthKey := dt.Format("2006-01")
monthlyCounts[monthKey] = map[string]int64{"active": 0, "executed": 0, "total": 0}
// Query for 'active' contracts for the current month
var active int64
err := shared.GetDb().Model(&contract).
Where("status = ? AND (buyer_id = ? OR seller_id = ?) AND start_time >= ? AND end_time <= ?", "active", companyID, companyID, dt, monthEnd).
Count(&active).Error
if err != nil {
return 0, 0, 0, nil, err
}
// Query for 'active' contracts for the current month
var active int64
err := shared.GetDb().Model(&contract).
Where("status = ? AND (buyer_id = ? OR seller_id = ?) AND start_time >= ? AND end_time <= ?", "active", companyID, companyID, dt, monthEnd).
Count(&active).Error
if err != nil {
return 0, 0, 0, nil, err
}
// Query for 'executed' contracts for the current month
var executed int64
err = shared.GetDb().Model(&contract).
Where("status = ? AND (buyer_id = ? OR seller_id = ?) AND start_time >= ? AND end_time <= ?", "executed", companyID, companyID, dt, monthEnd).
Count(&executed).Error
if err != nil {
return 0, 0, 0, nil, err
}
// Query for 'executed' contracts for the current month
var executed int64
err = shared.GetDb().Model(&contract).
Where("status = ? AND (buyer_id = ? OR seller_id = ?) AND start_time >= ? AND end_time <= ?", "executed", companyID, companyID, dt, monthEnd).
Count(&executed).Error
if err != nil {
return 0, 0, 0, nil, err
}
// Query for total contracts for the current month
var total int64
err = shared.GetDb().Model(&contract).
Where("(buyer_id = ? OR seller_id = ?) AND start_time >= ? AND end_time <= ?", companyID, companyID, dt, monthEnd).
Count(&total).Error
if err != nil {
return 0, 0, 0, nil, err
}
// Query for total contracts for the current month
var total int64
err = shared.GetDb().Model(&contract).
Where("(buyer_id = ? OR seller_id = ?) AND start_time >= ? AND end_time <= ?", companyID, companyID, dt, monthEnd).
Count(&total).Error
if err != nil {
return 0, 0, 0, nil, err
}
// Update the counts for the current month
monthlyCounts[monthKey]["active"] = active
monthlyCounts[monthKey]["executed"] = executed
monthlyCounts[monthKey]["total"] = total
// Update the counts for the current month
monthlyCounts[monthKey]["active"] = active
monthlyCounts[monthKey]["executed"] = executed
monthlyCounts[monthKey]["total"] = total
// Update the total counts
activeCount += active
executedCount += executed
totalCount += total
}
// Update the total counts
activeCount += active
executedCount += executed
totalCount += total
}
return activeCount, executedCount, totalCount, monthlyCounts, nil
return activeCount, executedCount, totalCount, monthlyCounts, nil
}

View File

@@ -4,7 +4,6 @@ import (
"errors"
"fmt"
"log"
"math"
"net/http"
"strconv"
"strings"
@@ -138,38 +137,35 @@ func SaveDeviceInfoToDB(deviceInfo models.DeviceInfo, rawData []byte) (models.De
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)
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 := messaging.GetMessagingChannel()
messagingChannel <- notification
messagingChannel <- sellerNotification
}
}(deviceInfo)
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
}
@@ -192,136 +188,127 @@ func CountDeviceInfoByCompany(companyID uint) (int64, error) {
// 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
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)
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
}
// 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...)
}
// 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
}
// 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()
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}
// 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
}
// 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
}
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 counts for the current month
monthlyCounts[monthKey]["inRange"] += inRange
monthlyCounts[monthKey]["outOfRange"] += outOfRange
// Update the total counts
inRangeCount += inRange
outOfRangeCount += outOfRange
}
}
// Update the total counts
inRangeCount += inRange
outOfRangeCount += outOfRange
}
}
return inRangeCount, outOfRangeCount, monthlyCounts, nil
return inRangeCount, outOfRangeCount, monthlyCounts, nil
}
type ContractLocationMatch struct {
ContractID uint
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
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
//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
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
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)
if err != nil {
return nil, err
}
err := shared.GetDb().
Where(queryString, contract.StartTime, contract.EndTime).
Find(&deviceInfos).Error
// 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 err != nil {
return nil, err
}
if isWithinOneKm(contract.StartLat, contract.StartLon, deviceInfo.Lat, deviceInfo.Lon) ||
isWithinOneKm(contract.EndLat, contract.EndLon, deviceInfo.Lat, deviceInfo.Lon) {
// 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
}
results = append(results, ContractLocationMatch{
ContractID: contract.ID,
DeviceInfoID: deviceInfo.ID,
})
registeredDevices[deviceInfo.DeviceID] = true // Mark this device as registered
}
}
}
if shared.DistanceKm(contract.StartLat, contract.StartLon, deviceInfo.Lat, deviceInfo.Lon) <= 1 ||
shared.DistanceKm(contract.EndLat, contract.EndLon, deviceInfo.Lat, deviceInfo.Lon) <= 1 {
return results, nil
results = append(results, ContractLocationMatch{
ContractID: contract.ID,
DeviceInfoID: deviceInfo.ID,
})
registeredDevices[deviceInfo.DeviceID] = true // Mark this device as registered
}
}
}
return results, nil
}