-
Notifications
You must be signed in to change notification settings - Fork 0
/
warranty.go
126 lines (108 loc) · 2.65 KB
/
warranty.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
117
118
119
120
121
122
123
124
125
126
package lenovo
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
)
const (
warrantyURL = "https://supportapi.lenovo.com/v2.5/warranty"
InvalidCountry = "**INVALID**"
)
var (
ErrNotEnoughSerials = errors.New("not enough serials provided require at least two")
ErrRequestFailed = errors.New("request failed")
ErrInvalidResponse = errors.New("invalid response")
)
type Warranty struct {
Serial string
ErrorCode int
ErrorMessage string
Product string
InWarranty bool
Purchased *Time
Shipped *Time
Country string
UpgradeURL string `json:"UpgradeUrl"`
Warranty []WarrantyWarranty
Contract []WarrantyContract
}
type WarrantyWarranty struct {
ID string
Name string
Description string
Type string
Start Time
End Time
}
type WarrantyContract struct {
Contract string
Quantity int
ItemNumber string
ChargeCode string
SLA string
EntitlementCode string
Status string
Start Time
End Time
}
func (c *Client) WarrantyBySerial(serial string) (*Warranty, error) {
data := url.Values{}
data.Set("Serial", serial)
dataEncoded := data.Encode()
r, err := http.NewRequest(http.MethodPost, warrantyURL, strings.NewReader(dataEncoded))
if err != nil {
return nil, err
}
r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
r.Header.Add("Content-Length", strconv.Itoa(len(dataEncoded)))
resp, err := c.sendRequest(r)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%w: %s", ErrRequestFailed, resp.Status)
}
if resp.ContentLength == 2 {
return nil, ErrInvalidResponse
}
var w Warranty
err = json.NewDecoder(resp.Body).Decode(&w)
if err != nil {
return nil, err
}
return &w, nil
}
func (c *Client) WarrantiesBySerials(serials []string) ([]Warranty, error) {
if len(serials) <= 1 {
return nil, ErrNotEnoughSerials
}
data := url.Values{}
data.Set("Serial", serials[0])
for _, v := range serials[1:] {
data.Add("Serial", v)
}
dataEncoded := data.Encode()
r, err := http.NewRequest(http.MethodPost, warrantyURL, strings.NewReader(dataEncoded))
if err != nil {
return nil, err
}
r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
r.Header.Add("Content-Length", strconv.Itoa(len(dataEncoded)))
resp, err := c.sendRequest(r)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%w: %s", ErrRequestFailed, resp.Status)
}
var w []Warranty
err = json.NewDecoder(resp.Body).Decode(&w)
if err != nil {
return nil, err
}
return w, nil
}