Added search params for get contract

This commit is contained in:
Nedim
2023-09-22 11:38:32 +02:00
parent 4779c32a56
commit 045d349c86
4 changed files with 218 additions and 99 deletions

View File

@@ -0,0 +1,69 @@
package contract
import (
"errors"
"log"
"net/http"
"time"
"github.com/jinzhu/gorm"
"gitlab.com/pactual1/backend/models"
"gitlab.com/pactual1/backend/shared"
)
func GetContracts(status string, companyName string, startTime time.Time, deviceIDs []int64,limit, offset int) ([]models.Contract, int64, int, error) {
// Create a slice to hold the contracts
var contracts []models.Contract
// Initialize the query
db := shared.GetDb().Where("status = ?", status)
countDb := db
if companyName != "" {
db = db.Joins("left join companies on companies.id = contracts.buyer_id").Where("companies.name LIKE ?", "%"+companyName+"%")
countDb = countDb.Joins("left join companies on companies.id = contracts.buyer_id").Where("companies.name LIKE ?", "%"+companyName+"%")
}
if !startTime.IsZero() {
db = db.Where("start_time >= ?", startTime)
countDb = countDb.Where("start_time >= ?", startTime)
}
if len(deviceIDs) > 0 {
db = db.Where("device_ids && ARRAY[?]::int8[]", deviceIDs)
countDb = countDb.Where("device_ids && ARRAY[?]::int8[]", deviceIDs)
}
// Count the total number of contracts
var total int64
if err := countDb.Model(&models.Contract{}).Count(&total).Error; err != nil {
log.Printf("GetLatestContracts Error: Database error: %v", err)
return contracts, total, http.StatusInternalServerError, err
}
// Fetch the latest contracts from the database with LIMIT and OFFSET
if err := db.Order("created_at desc").Limit(limit).Offset(offset).Find(&contracts).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
log.Printf("GetLatestContracts Error: No contracts found: %v", err)
return contracts, total, http.StatusNotFound, err
} else {
log.Printf("GetLatestContracts Error: Database error: %v", err)
return contracts, total, http.StatusInternalServerError, err
}
}
return contracts, total, http.StatusOK, nil
}
func GetContractByID(contractID uint64) (models.Contract, int ,error) {
// Fetch the contract creation date based on contractID
var contract models.Contract
if err := shared.GetDb().Where("id = ?", contractID).First(&contract).Error; err != nil {
log.Printf("GetDeviceData Error: Could not fetch contract: %v", err)
return contract, http.StatusInternalServerError, err
}
return contract , http.StatusOK, nil
}

101
database/device/device.go Normal file
View File

@@ -0,0 +1,101 @@
package device
import (
"errors"
"fmt"
"log"
"net/http"
"strconv"
"strings"
"github.com/jinzhu/gorm"
"gitlab.com/pactual1/backend/models"
"gitlab.com/pactual1/backend/shared"
)
func GetDevicesForContract(contractID uint64) ([]models.Device , int, error) {
// Create a slice to hold the devices
var devices []models.Device
// 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 devices, http.StatusNotFound ,err
} else {
log.Printf("GetDevicesByContract Error: Database error: %v", err)
return devices, http.StatusInternalServerError, err
}
}
log.Printf("This is the device IDS ID: %v", contract.DeviceIDs)
// Convert the integer array to a comma-separated string
idStrings := []string{}
for _, id := range contract.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
}
}
// Loop through each deviceInfo to create GeoJSON features
for _, info := range deviceInfos {
info.RawJSON = ""
feature := models.GeoJSONFeature{
Type: "Feature",
DeviceInfo: &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
}