forked from hiscaler/woocommerce-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
order.go
206 lines (184 loc) · 6.24 KB
/
order.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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
package woocommerce
import (
"errors"
"fmt"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/hiscaler/woocommerce-go/entity"
jsoniter "github.com/json-iterator/go"
)
type orderService service
// OrdersQueryParams orders query params
type OrdersQueryParams struct {
queryParams
Search string `url:"search,omitempty"`
After string `url:"after,omitempty"`
Before string `url:"before,omitempty"`
Exclude []int `url:"exclude,omitempty"`
Include []int `url:"include,omitempty"`
Parent []int `url:"parent,omitempty"`
ParentExclude []int `url:"parent_exclude,omitempty"`
Status []string `url:"status,omitempty"`
Customer int `url:"customer,omitempty"`
Product int `url:"product,omitempty"`
DecimalPoint int `url:"dp,omitempty"`
}
func (m OrdersQueryParams) Validate() error {
return validation.ValidateStruct(&m,
validation.Field(&m.Before, validation.When(m.Before != "", validation.By(func(value interface{}) error {
dateStr, _ := value.(string)
return IsValidateTime(dateStr)
}))),
validation.Field(&m.After, validation.When(m.After != "", validation.By(func(value interface{}) error {
dateStr, _ := value.(string)
return IsValidateTime(dateStr)
}))),
validation.Field(&m.OrderBy, validation.When(m.OrderBy != "", validation.In("id", "date", "include", "title", "slug").Error("无效的排序字段"))),
validation.Field(&m.Status, validation.When(len(m.Status) > 0, validation.By(func(value interface{}) error {
statuses, ok := value.([]string)
if !ok {
return errors.New("无效的状态值")
}
validStatuses := []string{"any", "pending", "processing", "on-hold", "completed", "cancelled", "refunded", "failed ", "trash"}
for _, status := range statuses {
valid := false
for _, validStatus := range validStatuses {
if status == validStatus {
valid = true
break
}
}
if !valid {
return fmt.Errorf("无效的状态值:%s", status)
}
}
return nil
}))),
)
}
// All list all orders
//
// Usage:
// params := OrdersQueryParams{
// After: "2022-06-10",
// }
// params.PerPage = 100
// for {
// orders, total, totalPages, isLastPage, err := wooClient.Services.Order.All(params)
// if err != nil {
// break
// }
// fmt.Println(fmt.Sprintf("Page %d/%d", total, totalPages))
// // read orders
// for _, order := range orders {
// _ = order
// }
// if err != nil || isLastPage {
// break
// }
// params.Page++
// }
func (s orderService) All(params OrdersQueryParams) (items []entity.Order, total, totalPages int, isLastPage bool, err error) {
if err = params.Validate(); err != nil {
return
}
params.TidyVars()
params.After = ToISOTimeString(params.After, false, true)
params.Before = ToISOTimeString(params.Before, true, false)
resp, err := s.httpClient.R().SetQueryParamsFromValues(toValues(params)).Get("/orders")
if err != nil {
return
}
if resp.IsSuccess() {
err = jsoniter.Unmarshal(resp.Body(), &items)
total, totalPages, isLastPage = parseResponseTotal(params.Page, resp)
} else {
err = ErrorWrap(resp.StatusCode(), "")
}
return
}
// One retrieve an order
func (s orderService) One(id int) (item entity.Order, err error) {
resp, err := s.httpClient.R().Get(fmt.Sprintf("/orders/%d", id))
if err != nil {
return
}
if resp.IsSuccess() {
err = jsoniter.Unmarshal(resp.Body(), &item)
} else {
err = ErrorWrap(resp.StatusCode(), "")
}
return
}
// Create order
type CreateOrderRequest struct {
Status string `json:"status,omitempty"`
Currency string `json:"currency,omitempty"`
CurrencySymbol string `json:"currency_symbol,omitempty"`
PricesIncludeTax bool `json:"prices_include_tax,omitempty"`
CustomerId int `json:"customer_id,omitempty"`
CustomerNote string `json:"customer_note,omitempty"`
Billing *entity.Billing `json:"billing,omitempty"`
Shipping *entity.Shipping `json:"shipping,omitempty"`
PaymentMethod string `json:"payment_method,omitempty"`
PaymentMethodTitle string `json:"payment_method_title,omitempty"`
TransactionId string `json:"transaction_id,omitempty"`
MetaData []entity.Meta `json:"meta_data,omitempty"`
LineItems []entity.LineItem `json:"line_items,omitempty"`
TaxLines []entity.TaxLine `json:"tax_lines,omitempty"`
ShippingLines []entity.ShippingLine `json:"shipping_lines,omitempty"`
FeeLines []entity.FeeLine `json:"fee_lines,omitempty"`
CouponLines []entity.CouponLine `json:"coupon_lines,omitempty"`
SetPaid bool `json:"set_paid,omitempty"`
}
func (m CreateOrderRequest) Validate() error {
return validation.ValidateStruct(&m,
validation.Field(&m.Status, validation.When(m.Status != "", validation.In("pending", "processing", "on-hold", "completed", "cancelled", "refunded", "failed", "trash").Error("无效的状态"))),
)
}
func (s orderService) Create(req CreateOrderRequest) (item entity.Order, err error) {
if err = req.Validate(); err != nil {
return
}
resp, err := s.httpClient.R().SetBody(req).Post("/orders")
if err != nil {
return
}
if resp.IsSuccess() {
err = jsoniter.Unmarshal(resp.Body(), &item)
} else {
err = ErrorWrap(resp.StatusCode(), "")
}
return
}
// Update order
type UpdateOrderRequest = CreateOrderRequest
func (s orderService) Update(id int, req UpdateOrderRequest) (item entity.Order, err error) {
if err = req.Validate(); err != nil {
return
}
resp, err := s.httpClient.R().SetBody(req).Put(fmt.Sprintf("/orders/%d", id))
if err != nil {
return
}
if resp.IsSuccess() {
err = jsoniter.Unmarshal(resp.Body(), &item)
} else {
err = ErrorWrap(resp.StatusCode(), "")
}
return
}
// Delete delete an order
func (s orderService) Delete(id int, force bool) (item entity.Order, err error) {
resp, err := s.httpClient.R().
SetBody(map[string]bool{"force": force}).
Delete(fmt.Sprintf("/orders/%d", id))
if err != nil {
return
}
if resp.IsSuccess() {
err = jsoniter.Unmarshal(resp.Body(), &item)
} else {
err = ErrorWrap(resp.StatusCode(), "")
}
return
}