-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathusage.go
95 lines (83 loc) · 2.41 KB
/
usage.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
package platform
import (
"encoding/json"
"errors"
"fmt"
http "github.com/bogdanfinn/fhttp"
"io"
"net/url"
"time"
)
type DailyCost struct {
Timestamp float64 `json:"timestamp"`
LineItems []struct {
Name string `json:"name"`
Cost float64 `json:"cost"`
} `json:"line_items"`
}
type UsageResponse struct {
Object string `json:"object"`
DailyCosts []DailyCost `json:"daily_costs"`
TotalUsage float64 `json:"total_usage"`
}
func (u *UserClient) UsageWithSecretKey(sk, StartDate, EndDate string) (UsageResponse, error) {
if sk == "" {
return UsageResponse{}, errors.New("GetUsage with no access token is defined")
}
return u.usageWithCustomToken(sk, StartDate, EndDate)
}
func (u *UserClient) UsageWithSessionToken(StartDate, EndDate string) (UsageResponse, error) {
if u.SessionKey() == "" {
return UsageResponse{}, errors.New("GetUsage get empty session key")
}
return u.usageWithCustomToken(u.SessionKey(), StartDate, EndDate)
}
func (u *UserClient) usageWithCustomToken(token, StartDate, EndDate string) (UsageResponse, error) {
Params := url.Values{
"end_date": {EndDate},
"start_date": {StartDate},
}
req, err := http.NewRequest(http.MethodGet, PlatformApiUrlPrefix+"/dashboard/billing/usage?"+Params.Encode(), nil)
req.Header.Set("User-Agent", UserAgent)
req.Header.Set(AuthorizationHeader, "Bearer "+token)
resp, err := u.client.Do(req)
if err != nil {
return UsageResponse{}, errors.Join(
errors.New("usage error"),
err,
)
}
u.lastResponse = resp
if resp.StatusCode != http.StatusOK {
return UsageResponse{}, errors.Join(
errors.New(fmt.Sprintf("Usage found non 200 response, StatusCode: %v", resp.StatusCode)),
err)
}
data, _ := io.ReadAll(resp.Body)
var response UsageResponse
err = json.Unmarshal(data, &response)
if err != nil {
return UsageResponse{}, errors.Join(
errors.New("usage Unmarshal error"),
err)
}
return response, nil
}
func GetLastMonth() (string, string) {
Now := time.Now()
year := Now.Year()
month := Now.Month()
lastMonth := month - 1
lastYear := year
if month == time.January {
lastYear = year - 1
lastMonth = time.December
}
return fmt.Sprintf("%v-%02d-01", lastYear, lastMonth),
fmt.Sprintf("%v-%02d-01", year, month)
}
func GetCurrentMonth() (string, string) {
End := time.Now().AddDate(0, 0, 1)
return fmt.Sprintf("%v-%02d-01", End.Year(), End.Month()),
fmt.Sprintf("%v-%02d-%v", End.Year(), End.Month(), End.Day())
}