/
assets.go
116 lines (99 loc) · 2.67 KB
/
assets.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package database
import (
"encoding/json"
edb "github.com/Varunram/essentials/database"
globals "github.com/YaleOpenLab/openclimate/globals"
"github.com/pkg/errors"
"log"
)
type Asset struct {
Index int
Title string
Subtitle string
CompanyID int
Name string
Location string
State string
Type string
ActionType []string
Capacity float64
Reports []ReportsByYear
}
type ReportsByYear struct {
Year int
GWh int
MitigationOutcomes int
}
func NewAsset(name string, companyID int, location string, state string, type_ string) (Asset, error) {
var asset Asset
asset.Name = name
asset.CompanyID = companyID
asset.Location = location
asset.State = state
asset.Type = type_
return asset, asset.Save()
}
func UpdateAsset(key int, info Asset) error {
asset, err := RetrieveAsset(key)
if err != nil {
return errors.Wrap(err, "UpdateAsset() failed (likely because asset doesn't exist)")
}
asset.Name = info.Name
asset.Location = info.Location
asset.State = info.State
asset.Type = info.Type
asset.ActionType = info.ActionType
return asset.Save()
}
func (a *Asset) ReportAssetData(year int, gwh int, mitOut int) error {
var data ReportsByYear
data.Year = year
data.GWh = gwh
data.MitigationOutcomes = mitOut
a.Reports = append(a.Reports, data)
return a.Save()
}
// Given a key of type int, retrieves the corresponding asset object
// from the database assets bucket.
func RetrieveAsset(key int) (Asset, error) {
var asset Asset
assetBytes, err := edb.Retrieve(globals.DbPath, AssetBucket, key)
if err != nil {
return asset, errors.Wrap(err, "error while retrieving key from bucket")
}
err = json.Unmarshal(assetBytes, &asset)
return asset, err
}
// Given a name and company, retrieves the corresponding asset object
// from the database assets bucket.
func RetrieveAssetByName(name string, companyID int) (Asset, error) {
var asset Asset
allAssets, err := RetrieveAllAssets()
if err != nil {
return asset, errors.Wrap(err, "error while retrieving all users from database")
}
for _, asset := range allAssets {
if asset.Name == name && asset.CompanyID == companyID {
return asset, nil
}
}
return asset, errors.New("asset not found, quitting")
}
// RetrieveAllAssets gets a list of all assets in the database
func RetrieveAllAssets() ([]Asset, error) {
var assets []Asset
keys, err := edb.RetrieveAllKeys(globals.DbPath, AssetBucket)
if err != nil {
log.Println(err)
return assets, errors.Wrap(err, "could not retrieve all user keys")
}
for _, val := range keys {
var x Asset
err = json.Unmarshal(val, &x)
if err != nil {
break
}
assets = append(assets, x)
}
return assets, nil
}