69 lines
2.3 KiB
Go
69 lines
2.3 KiB
Go
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
|
|
|
|
} |