diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b9af8cb..3b026dc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -9,7 +9,6 @@ on: pull_request: env: - DEVELOPER_NODE: 1 RETAILCRM_URL: https://test.retailcrm.pro RETAILCRM_KEY: key @@ -41,7 +40,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - go-version: ['1.11', '1.12', '1.13', '1.14', '1.15', '1.16', '1.17'] + go-version: ['1.13', '1.14', '1.15', '1.16', '1.17'] include: - go-version: '1.17' coverage: 1 diff --git a/.gitignore b/.gitignore index 2650cf3..e1ba55c 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,7 @@ # Folders _obj +vendor # Architecture specific extensions/prefixes *.[568vq] diff --git a/.golangci.yml b/.golangci.yml index 887c5ee..c9b3570 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -146,9 +146,9 @@ linters-settings: gocyclo: min-complexity: 25 goimports: - local-prefixes: github.com/retailcrm/api-client-go + local-prefixes: github.com/retailcrm/api-client-go/v2 lll: - line-length: 120 + line-length: 160 maligned: suggest-new: true misspell: @@ -180,6 +180,9 @@ issues: - gocognit - gocyclo - godot + - gocritic + - gosec + - staticcheck exclude-use-default: true exclude-case-sensitive: false max-issues-per-linter: 0 diff --git a/README.md b/README.md index e73f535..9ebb481 100644 --- a/README.md +++ b/README.md @@ -10,51 +10,51 @@ This is golang RetailCRM API client. -## Install +## Installation ```bash -go get -x github.com/retailcrm/api-client-go +go get -u github.com/retailcrm/api-client-go/v2 ``` ## Usage -```golang +Example: + +```go package main import ( - "fmt" - "net/http" + "log" - "github.com/retailcrm/api-client-go/v5" + "github.com/retailcrm/api-client-go/v2" ) func main() { - var client = v5.New("https://demo.retailcrm.pro", "09jIJ09j0JKhgyfvyuUIKhiugF") + var client = retailcrm.New("https://demo.retailcrm.pro", "09jIJ09j0JKhgyfvyuUIKhiugF") - data, status, err := client.Orders(v5.OrdersRequest{ - Filter: v5.OrdersFilter{}, + data, status, err := client.Orders(retailcrm.OrdersRequest{ + Filter: retailcrm.OrdersFilter{}, Limit: 20, Page: 1, - },) + }) if err != nil { - fmt.Printf("%v", err.Error()) - } + if apiErr, ok := retailcrm.AsAPIError(err); ok { + log.Fatalf("http status: %d, %s", status, apiErr.String()) + } - if status >= http.StatusBadRequest { - fmt.Printf("%v", err.ApiError()) + log.Fatalf("http status: %d, error: %s", status, err) } for _, value := range data.Orders { - fmt.Printf("%v\n", value.Email) + log.Printf("%v\n", value.Email) } - fmt.Println(data.Orders[1].FirstName) + log.Println(data.Orders[1].FirstName) - idata, status, err := c.InventoriesUpload( - []InventoryUpload{ + inventories, status, err := client.InventoriesUpload([]retailcrm.InventoryUpload{ { XMLID: "pTKIKAeghYzX21HTdzFCe1", - Stores: []InventoryUploadStore{ + Stores: []retailcrm.InventoryUploadStore{ { Code: "test-store-v5", Available: 10, @@ -74,7 +74,7 @@ func main() { }, { XMLID: "JQIvcrCtiSpOV3AAfMiQB3", - Stores: []InventoryUploadStore{ + Stores: []retailcrm.InventoryUploadStore{ { Code: "test-store-v5", Available: 45, @@ -95,13 +95,70 @@ func main() { }, ) if err != nil { - fmt.Printf("%v", err.Error()) + if apiErr, ok := retailcrm.AsAPIError(err); ok { + log.Fatalf("http status: %d, %s", status, apiErr.String()) + } + + log.Fatalf("http status: %d, error: %s", status, err) } - if status >= http.StatusBadRequest { - fmt.Printf("%v", err.ApiError()) - } - - fmt.Println(idata.processedOffersCount) + log.Println(inventories.ProcessedOffersCount) } ``` + +You can use different error types and `retailcrm.AsAPIError` to process client errors. Example: + +```go +package retailcrm + +import ( + "errors" + "log" + "os" + "strings" + + "github.com/retailcrm/api-client-go/v2" +) + +func main() { + var client = retailcrm.New("https://demo.retailcrm.pro", "09jIJ09j0JKhgyfvyuUIKhiugF") + + resp, status, err := client.APICredentials() + if err != nil { + apiErr, ok := retailcrm.AsAPIError(err) + if !ok { + log.Fatalf("http status: %d, error: %s", status, err) + } + + switch { + case errors.Is(apiErr, retailcrm.ErrMissingCredentials): + log.Fatalln("No API key provided.") + case errors.Is(apiErr, retailcrm.ErrInvalidCredentials): + log.Fatalln("Invalid API key.") + case errors.Is(apiErr, retailcrm.ErrAccessDenied): + log.Fatalln("Access denied. Please check that the provided key has access to the credentials info.") + case errors.Is(apiErr, retailcrm.ErrAccountDoesNotExist): + log.Fatalln("There is no RetailCRM at the provided URL.") + case errors.Is(apiErr, retailcrm.ErrMissingParameter): + // retailcrm.APIError in this case will always contain "Name" key in the errors list with the parameter name. + log.Fatalln("This parameter should be present:", apiErr.Errors()["Name"]) + case errors.Is(apiErr, retailcrm.ErrValidation): + log.Println("Validation errors from the API:") + + for name, value := range apiErr.Errors() { + log.Printf(" - %s: %s\n", name, value) + } + + os.Exit(1) + case errors.Is(apiErr, retailcrm.ErrGeneric): + log.Fatalf("failure from the API. %s", apiErr.String()) + } + } + + log.Println("Available scopes:", strings.Join(resp.Scopes, ", ")) +} +``` + +## Upgrading + +Please check the [UPGRADING.md](UPGRADING.md) to learn how to upgrade to the new version. diff --git a/UPGRADING.md b/UPGRADING.md new file mode 100644 index 0000000..ba68226 --- /dev/null +++ b/UPGRADING.md @@ -0,0 +1,70 @@ +# Upgrading to the v2 + +### Install the new version + +```bash +go get -u github.com/retailcrm/api-client-go/v2 +``` + +### Update all imports + +Before: +```go +package main + +import v5 "github.com/retailcrm/api-client-go/v5" +``` + +After: +```go +package main + +import "github.com/retailcrm/api-client-go/v2" +``` + +You can use package alias `v5` to skip the second step. + +### Replace package name for all imported symbols + +Before: + +```go +package main + +import v5 "github.com/retailcrm/api-client-go/v5" + +func main() { + client := v5.New("https://test.retailcrm.pro", "key") + data, status, err := client.Orders(v5.OrdersRequest{ + Filter: v5.OrdersFilter{ + City: "Moscow", + }, + Page: 1, + }) + ... +} +``` + +After: + +```go +package main + +import "github.com/retailcrm/api-client-go/v2" + +func main() { + client := retailcrm.New("https://test.retailcrm.pro", "key") + data, status, err := client.Orders(retailcrm.OrdersRequest{ + Filter: retailcrm.OrdersFilter{ + City: "Moscow", + }, + Page: 1, + }) + ... +} +``` + +### Upgrade client usages + +This major release contains some breaking changes regarding field names and fully redesigned error handling. Use the second example from +the readme to learn how to process errors correctly. diff --git a/v5/client.go b/client.go similarity index 65% rename from v5/client.go rename to client.go index 122e200..89c56a8 100644 --- a/v5/client.go +++ b/client.go @@ -1,4 +1,4 @@ -package v5 +package retailcrm import ( "bytes" @@ -26,16 +26,29 @@ func New(url string, key string) *Client { } } +// WithLogger sets the provided logger instance into the Client. +func (c *Client) WithLogger(logger BasicLogger) *Client { + c.logger = logger + return c +} + +// writeLog writes to the log. +func (c *Client) writeLog(format string, v ...interface{}) { + if c.logger != nil { + c.logger.Printf(format, v...) + return + } + + log.Printf(format, v...) +} + // GetRequest implements GET Request. func (c *Client) GetRequest(urlWithParameters string, versioned ...bool) ([]byte, int, error) { var res []byte var prefix = "/api/v5" - apiError := &APIError{} if len(versioned) > 0 { - s := versioned[0] - - if s == false { + if !versioned[0] { prefix = "/api" } } @@ -48,7 +61,7 @@ func (c *Client) GetRequest(urlWithParameters string, versioned ...bool) ([]byte req.Header.Set("X-API-KEY", c.Key) if c.Debug { - log.Printf("API Request: %s %s", fmt.Sprintf("%s%s%s", c.URL, prefix, urlWithParameters), c.Key) + c.writeLog("API Request: %s %s", fmt.Sprintf("%s%s%s", c.URL, prefix, urlWithParameters), c.Key) } resp, err := c.httpClient.Do(req) @@ -57,8 +70,8 @@ func (c *Client) GetRequest(urlWithParameters string, versioned ...bool) ([]byte } if resp.StatusCode >= http.StatusInternalServerError { - apiError.ErrorMsg = fmt.Sprintf("HTTP request error. Status code: %d.\n", resp.StatusCode) - return res, resp.StatusCode, apiError + return res, resp.StatusCode, CreateGenericAPIError( + fmt.Sprintf("HTTP request error. Status code: %d.", resp.StatusCode)) } res, err = buildRawResponse(resp) @@ -67,11 +80,11 @@ func (c *Client) GetRequest(urlWithParameters string, versioned ...bool) ([]byte } if resp.StatusCode >= http.StatusBadRequest && resp.StatusCode < http.StatusInternalServerError { - return res, resp.StatusCode, NewAPIError(res) + return res, resp.StatusCode, CreateAPIError(res) } if c.Debug { - log.Printf("API Response: %s", res) + c.writeLog("API Response: %s", res) } return res, resp.StatusCode, nil @@ -89,7 +102,6 @@ func (c *Client) PostRequest( ) prefix := "/api/v5" - apiError := &APIError{} if len(contType) > 0 { contentType = contType[0] @@ -111,7 +123,7 @@ func (c *Client) PostRequest( req.Header.Set("X-API-KEY", c.Key) if c.Debug { - log.Printf("API Request: %s %s", uri, c.Key) + c.writeLog("API Request: %s %s", uri, c.Key) } resp, err := c.httpClient.Do(req) @@ -120,8 +132,8 @@ func (c *Client) PostRequest( } if resp.StatusCode >= http.StatusInternalServerError { - apiError.ErrorMsg = fmt.Sprintf("HTTP request error. Status code: %d.\n", resp.StatusCode) - return res, resp.StatusCode, apiError + return res, resp.StatusCode, CreateGenericAPIError( + fmt.Sprintf("HTTP request error. Status code: %d.", resp.StatusCode)) } res, err = buildRawResponse(resp) @@ -130,11 +142,11 @@ func (c *Client) PostRequest( } if resp.StatusCode >= http.StatusBadRequest && resp.StatusCode < http.StatusInternalServerError { - return res, resp.StatusCode, NewAPIError(res) + return res, resp.StatusCode, CreateAPIError(res) } if c.Debug { - log.Printf("API Response: %s", res) + c.writeLog("API Response: %s", res) } return res, resp.StatusCode, nil @@ -197,20 +209,20 @@ func fillSite(p *url.Values, site []string) { // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // // data, status, err := client.APIVersions() // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // for _, value := range data.versions { -// fmt.Printf("%v\n", value) +// log.Printf("%v\n", value) // } func (c *Client) APIVersions() (VersionResponse, int, error) { var resp VersionResponse @@ -220,7 +232,10 @@ func (c *Client) APIVersions() (VersionResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -231,20 +246,20 @@ func (c *Client) APIVersions() (VersionResponse, int, error) { // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // // data, status, err := client.APICredentials() // // if err != nil { -// fmt.Printf("%v", err.Error()) +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } +// +// log.Fatalf("http status: %d, error: %s", status, err) // } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) -// } -// -// for _, value := range data.credentials { -// fmt.Printf("%v\n", value) +// for _, value := range data.Scopes { +// log.Printf("%v\n", value) // } func (c *Client) APICredentials() (CredentialResponse, int, error) { var resp CredentialResponse @@ -254,7 +269,10 @@ func (c *Client) APICredentials() (CredentialResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -265,9 +283,9 @@ func (c *Client) APICredentials() (CredentialResponse, int, error) { // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.Customers(v5.CustomersRequest{ +// data, status, err := client.Customers(retailcrm.CustomersRequest{ // Filter: CustomersFilter{ // City: "Moscow", // }, @@ -275,15 +293,15 @@ func (c *Client) APICredentials() (CredentialResponse, int, error) { // }) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // for _, value := range data.Customers { -// fmt.Printf("%v\n", value) +// log.Printf("%v\n", value) // } func (c *Client) Customers(parameters CustomersRequest) (CustomersResponse, int, error) { var resp CustomersResponse @@ -295,7 +313,10 @@ func (c *Client) Customers(parameters CustomersRequest) (CustomersResponse, int, return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -306,16 +327,16 @@ func (c *Client) Customers(parameters CustomersRequest) (CustomersResponse, int, // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.CustomersCombine([]v5.Customer{{ID: 1}, {ID: 2}}, Customer{ID: 3}) +// data, status, err := client.CustomersCombine([]retailcrm.Customer{{ID: 1}, {ID: 2}}, Customer{ID: 3}) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } func (c *Client) CustomersCombine(customers []Customer, resultCustomer Customer) (SuccessfulResponse, int, error) { var resp SuccessfulResponse @@ -324,8 +345,8 @@ func (c *Client) CustomersCombine(customers []Customer, resultCustomer Customer) combineJSONOut, _ := json.Marshal(&resultCustomer) p := url.Values{ - "customers": {string(combineJSONIn[:])}, - "resultCustomer": {string(combineJSONOut[:])}, + "customers": {string(combineJSONIn)}, + "resultCustomer": {string(combineJSONOut)}, } data, status, err := c.PostRequest("/customers/combine", p) @@ -333,7 +354,10 @@ func (c *Client) CustomersCombine(customers []Customer, resultCustomer Customer) return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -344,30 +368,30 @@ func (c *Client) CustomersCombine(customers []Customer, resultCustomer Customer) // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.CustomersCombine(v5.Customer{ +// data, status, err := client.CustomersCombine(retailcrm.Customer{ // FirstName: "Ivan", // LastName: "Ivanov", // Patronymic: "Ivanovich", // ExternalID: 1, // Email: "ivanov@example.com", -// Address: &v5.Address{ +// Address: &retailcrm.Address{ // City: "Moscow", // Street: "Kutuzovsky", // }, // }) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // if data.Success == true { -// fmt.Printf("%v", err.Id) +// fmt.Printf("%v", data.ID) // } func (c *Client) CustomerCreate(customer Customer, site ...string) (CustomerChangeResponse, int, error) { var resp CustomerChangeResponse @@ -375,7 +399,7 @@ func (c *Client) CustomerCreate(customer Customer, site ...string) (CustomerChan customerJSON, _ := json.Marshal(&customer) p := url.Values{ - "customer": {string(customerJSON[:])}, + "customer": {string(customerJSON)}, } fillSite(&p, site) @@ -385,7 +409,10 @@ func (c *Client) CustomerCreate(customer Customer, site ...string) (CustomerChan return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -396,19 +423,19 @@ func (c *Client) CustomerCreate(customer Customer, site ...string) (CustomerChan // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.CustomersFixExternalIds([]v5.IdentifiersPair{{ +// data, status, err := client.CustomersFixExternalIds([]retailcrm.IdentifiersPair{{ // ID: 1, // ExternalID: 12, // }}) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } func (c *Client) CustomersFixExternalIds(customers []IdentifiersPair) (SuccessfulResponse, int, error) { var resp SuccessfulResponse @@ -416,7 +443,7 @@ func (c *Client) CustomersFixExternalIds(customers []IdentifiersPair) (Successfu customersJSON, _ := json.Marshal(&customers) p := url.Values{ - "customers": {string(customersJSON[:])}, + "customers": {string(customersJSON)}, } data, status, err := c.PostRequest("/customers/fix-external-ids", p) @@ -424,7 +451,10 @@ func (c *Client) CustomersFixExternalIds(customers []IdentifiersPair) (Successfu return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -435,24 +465,24 @@ func (c *Client) CustomersFixExternalIds(customers []IdentifiersPair) (Successfu // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.CustomersHistory(v5.CustomersHistoryRequest{ -// Filter: v5.CustomersHistoryFilter{ +// data, status, err := client.CustomersHistory(retailcrm.CustomersHistoryRequest{ +// Filter: retailcrm.CustomersHistoryFilter{ // SinceID: 20, // }, // }) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // for _, value := range data.History { -// fmt.Printf("%v\n", value) +// log.Printf("%v\n", value) // } func (c *Client) CustomersHistory(parameters CustomersHistoryRequest) (CustomersHistoryResponse, int, error) { var resp CustomersHistoryResponse @@ -464,7 +494,10 @@ func (c *Client) CustomersHistory(parameters CustomersHistoryRequest) (Customers return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -475,25 +508,25 @@ func (c *Client) CustomersHistory(parameters CustomersHistoryRequest) (Customers // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.CustomerNotes(v5.NotesRequest{ -// Filter: v5.NotesFilter{ +// data, status, err := client.CustomerNotes(retailcrm.NotesRequest{ +// Filter: retailcrm.NotesFilter{ // CustomerIds: []int{1,2,3} // }, // Page: 1, // }) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // for _, value := range data.Notes { -// fmt.Printf("%v\n", value) +// log.Printf("%v\n", value) // } func (c *Client) CustomerNotes(parameters NotesRequest) (NotesResponse, int, error) { var resp NotesResponse @@ -505,7 +538,10 @@ func (c *Client) CustomerNotes(parameters NotesRequest) (NotesResponse, int, err return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -516,26 +552,26 @@ func (c *Client) CustomerNotes(parameters NotesRequest) (NotesResponse, int, err // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.CustomerNoteCreate(v5.Note{ +// data, status, err := client.CustomerNoteCreate(retailcrm.Note{ // Text: "some text", // ManagerID: 12, -// Customer: &v5.Customer{ +// Customer: &retailcrm.Customer{ // ID: 1, // }, // }) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // if data.Success == true { -// fmt.Printf("%v\n", data.ID) +// log.Printf("%v\n", data.ID) // } func (c *Client) CustomerNoteCreate(note Note, site ...string) (CreateResponse, int, error) { var resp CreateResponse @@ -543,7 +579,7 @@ func (c *Client) CustomerNoteCreate(note Note, site ...string) (CreateResponse, noteJSON, _ := json.Marshal(¬e) p := url.Values{ - "note": {string(noteJSON[:])}, + "note": {string(noteJSON)}, } fillSite(&p, site) @@ -553,7 +589,10 @@ func (c *Client) CustomerNoteCreate(note Note, site ...string) (CreateResponse, return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -564,15 +603,15 @@ func (c *Client) CustomerNoteCreate(note Note, site ...string) (CreateResponse, // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // // data, status, err := client.CustomerNoteDelete(12) // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } func (c *Client) CustomerNoteDelete(id int) (SuccessfulResponse, int, error) { var resp SuccessfulResponse @@ -586,7 +625,10 @@ func (c *Client) CustomerNoteDelete(id int) (SuccessfulResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -597,9 +639,9 @@ func (c *Client) CustomerNoteDelete(id int) (SuccessfulResponse, int, error) { // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.CustomersUpload([]v5.Customer{ +// data, status, err := client.CustomersUpload([]retailcrm.Customer{ // { // FirstName: "Ivan", // LastName: "Ivanov", @@ -617,15 +659,15 @@ func (c *Client) CustomerNoteDelete(id int) (SuccessfulResponse, int, error) { // }} // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // if data.Success == true { -// fmt.Printf("%v\n", data.UploadedCustomers) +// log.Printf("%v\n", data.UploadedCustomers) // } func (c *Client) CustomersUpload(customers []Customer, site ...string) (CustomersUploadResponse, int, error) { var resp CustomersUploadResponse @@ -633,7 +675,7 @@ func (c *Client) CustomersUpload(customers []Customer, site ...string) (Customer uploadJSON, _ := json.Marshal(&customers) p := url.Values{ - "customers": {string(uploadJSON[:])}, + "customers": {string(uploadJSON)}, } fillSite(&p, site) @@ -643,7 +685,10 @@ func (c *Client) CustomersUpload(customers []Customer, site ...string) (Customer return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -654,20 +699,20 @@ func (c *Client) CustomersUpload(customers []Customer, site ...string) (Customer // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.Customer(12, v5.ByExternalID, "") +// data, status, err := client.Customer(12, retailcrm.ByExternalID, "") // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // if data.Success == true { -// fmt.Printf("%v\n", data.Customer) +// log.Printf("%v\n", data.Customer) // } func (c *Client) Customer(id, by, site string) (CustomerResponse, int, error) { var resp CustomerResponse @@ -681,7 +726,10 @@ func (c *Client) Customer(id, by, site string) (CustomerResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -692,29 +740,29 @@ func (c *Client) Customer(id, by, site string) (CustomerResponse, int, error) { // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // // data, status, err := client.CustomerEdit( -// v5.Customer{ +// retailcrm.Customer{ // FirstName: "Ivan", // LastName: "Ivanov", // Patronymic: "Ivanovich", // ID: 1, // Email: "ivanov@example.com", // }, -// v5.ByID, +// retailcrm.ByID, // ) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // if data.Success == true { -// fmt.Printf("%v\n", data.Customer) +// log.Printf("%v\n", data.Customer) // } func (c *Client) CustomerEdit(customer Customer, by string, site ...string) (CustomerChangeResponse, int, error) { var resp CustomerChangeResponse @@ -728,8 +776,8 @@ func (c *Client) CustomerEdit(customer Customer, by string, site ...string) (Cus customerJSON, _ := json.Marshal(&customer) p := url.Values{ - "by": {string(context)}, - "customer": {string(customerJSON[:])}, + "by": {context}, + "customer": {string(customerJSON)}, } fillSite(&p, site) @@ -739,7 +787,10 @@ func (c *Client) CustomerEdit(customer Customer, by string, site ...string) (Cus return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -750,9 +801,9 @@ func (c *Client) CustomerEdit(customer Customer, by string, site ...string) (Cus // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.CorporateCustomers(v5.CorporateCustomersRequest{ +// data, status, err := client.CorporateCustomers(retailcrm.CorporateCustomersRequest{ // Filter: CorporateCustomersFilter{ // City: "Moscow", // }, @@ -760,15 +811,15 @@ func (c *Client) CustomerEdit(customer Customer, by string, site ...string) (Cus // }) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // for _, value := range data.CustomersCorporate { -// fmt.Printf("%v\n", value) +// log.Printf("%v\n", value) // } func (c *Client) CorporateCustomers(parameters CorporateCustomersRequest) (CorporateCustomersResponse, int, error) { var resp CorporateCustomersResponse @@ -780,7 +831,10 @@ func (c *Client) CorporateCustomers(parameters CorporateCustomersRequest) (Corpo return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -791,22 +845,22 @@ func (c *Client) CorporateCustomers(parameters CorporateCustomersRequest) (Corpo // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.CorporateCustomerCreate(v5.CorporateCustomer{ +// data, status, err := client.CorporateCustomerCreate(retailcrm.CorporateCustomer{ // Nickname: "Company", // }) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // if data.Success == true { -// fmt.Printf("%v", err.Id) +// fmt.Printf("%v", data.ID) // } func (c *Client) CorporateCustomerCreate(customer CorporateCustomer, site ...string) ( CorporateCustomerChangeResponse, int, error, @@ -816,7 +870,7 @@ func (c *Client) CorporateCustomerCreate(customer CorporateCustomer, site ...str customerJSON, _ := json.Marshal(&customer) p := url.Values{ - "customerCorporate": {string(customerJSON[:])}, + "customerCorporate": {string(customerJSON)}, } fillSite(&p, site) @@ -826,30 +880,33 @@ func (c *Client) CorporateCustomerCreate(customer CorporateCustomer, site ...str return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } // CorporateCustomersFixExternalIds will fix corporate customers external ID's // -// For more information see http://help.retailcrm.pro/Developers/ApiVersion5#post--api-v5-customers-corporate-fix-external-ids +// For more information see http://help.retailcrm.pro/Developers/ApiVersion5#post--api-v5-customers-corporate-fix-external-ids // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.CorporateCustomersFixExternalIds([]v5.IdentifiersPair{{ +// data, status, err := client.CorporateCustomersFixExternalIds([]retailcrm.IdentifiersPair{{ // ID: 1, // ExternalID: 12, // }}) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } func (c *Client) CorporateCustomersFixExternalIds(customers []IdentifiersPair) (SuccessfulResponse, int, error) { var resp SuccessfulResponse @@ -857,7 +914,7 @@ func (c *Client) CorporateCustomersFixExternalIds(customers []IdentifiersPair) ( customersJSON, _ := json.Marshal(&customers) p := url.Values{ - "customersCorporate": {string(customersJSON[:])}, + "customersCorporate": {string(customersJSON)}, } data, status, err := c.PostRequest("/customers-corporate/fix-external-ids", p) @@ -865,7 +922,10 @@ func (c *Client) CorporateCustomersFixExternalIds(customers []IdentifiersPair) ( return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -876,24 +936,24 @@ func (c *Client) CorporateCustomersFixExternalIds(customers []IdentifiersPair) ( // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.CorporateCustomersHistory(v5.CorporateCustomersHistoryRequest{ -// Filter: v5.CorporateCustomersHistoryFilter{ +// data, status, err := client.CorporateCustomersHistory(retailcrm.CorporateCustomersHistoryRequest{ +// Filter: retailcrm.CorporateCustomersHistoryFilter{ // SinceID: 20, // }, // }) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // for _, value := range data.History { -// fmt.Printf("%v\n", value) +// log.Printf("%v\n", value) // } func (c *Client) CorporateCustomersHistory(parameters CorporateCustomersHistoryRequest) ( CorporateCustomersHistoryResponse, int, error, @@ -907,20 +967,23 @@ func (c *Client) CorporateCustomersHistory(parameters CorporateCustomersHistoryR return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } -// CorporateCustomers returns list of corporate customers matched the specified filter +// CorporateCustomersNotes returns list of corporate customers notes matched the specified filter // // For more information see http://help.retailcrm.pro/Developers/ApiVersion5#get--api-v5-customers-corporate-notes // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.CorporateCustomersNotes(v5.CorporateCustomersNotesRequest{ +// data, status, err := client.CorporateCustomersNotes(retailcrm.CorporateCustomersNotesRequest{ // Filter: CorporateCustomersNotesFilter{ // Text: "text", // }, @@ -928,15 +991,15 @@ func (c *Client) CorporateCustomersHistory(parameters CorporateCustomersHistoryR // }) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // for _, value := range data.Notes { -// fmt.Printf("%v\n", value) +// log.Printf("%v\n", value) // } func (c *Client) CorporateCustomersNotes(parameters CorporateCustomersNotesRequest) ( CorporateCustomersNotesResponse, int, error, @@ -950,7 +1013,10 @@ func (c *Client) CorporateCustomersNotes(parameters CorporateCustomersNotesReque return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -961,25 +1027,25 @@ func (c *Client) CorporateCustomersNotes(parameters CorporateCustomersNotesReque // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.CorporateCustomerNoteCreate(v5.CorporateCustomerNote{ +// data, status, err := client.CorporateCustomerNoteCreate(retailcrm.CorporateCustomerNote{ // Text: "text", -// Customer: &v5.IdentifiersPair{ +// Customer: &retailcrm.IdentifiersPair{ // ID: 1, // } // }) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // if data.Success == true { -// fmt.Printf("%v", err.Id) +// fmt.Printf("%v", data.ID) // } func (c *Client) CorporateCustomerNoteCreate(note CorporateCustomerNote, site ...string) (CreateResponse, int, error) { var resp CreateResponse @@ -987,7 +1053,7 @@ func (c *Client) CorporateCustomerNoteCreate(note CorporateCustomerNote, site .. noteJSON, _ := json.Marshal(¬e) p := url.Values{ - "note": {string(noteJSON[:])}, + "note": {string(noteJSON)}, } fillSite(&p, site) @@ -997,7 +1063,10 @@ func (c *Client) CorporateCustomerNoteCreate(note CorporateCustomerNote, site .. return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -1008,16 +1077,16 @@ func (c *Client) CorporateCustomerNoteCreate(note CorporateCustomerNote, site .. // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // // data, status, err := client.CorporateCustomerNoteDelete(12) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } func (c *Client) CorporateCustomerNoteDelete(id int) (SuccessfulResponse, int, error) { var resp SuccessfulResponse @@ -1031,7 +1100,10 @@ func (c *Client) CorporateCustomerNoteDelete(id int) (SuccessfulResponse, int, e return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -1042,9 +1114,9 @@ func (c *Client) CorporateCustomerNoteDelete(id int) (SuccessfulResponse, int, e // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.CorporateCustomersUpload([]v5.CorporateCustomer{ +// data, status, err := client.CorporateCustomersUpload([]retailcrm.CorporateCustomer{ // { // Nickname: "Company", // ExternalID: 1, @@ -1056,15 +1128,15 @@ func (c *Client) CorporateCustomerNoteDelete(id int) (SuccessfulResponse, int, e // }} // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // if data.Success == true { -// fmt.Printf("%v\n", data.UploadedCustomers) +// log.Printf("%v\n", data.UploadedCustomers) // } func (c *Client) CorporateCustomersUpload( customers []CorporateCustomer, site ...string, @@ -1074,7 +1146,7 @@ func (c *Client) CorporateCustomersUpload( uploadJSON, _ := json.Marshal(&customers) p := url.Values{ - "customersCorporate": {string(uploadJSON[:])}, + "customersCorporate": {string(uploadJSON)}, } fillSite(&p, site) @@ -1084,7 +1156,10 @@ func (c *Client) CorporateCustomersUpload( return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -1095,20 +1170,20 @@ func (c *Client) CorporateCustomersUpload( // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.CorporateCustomer(12, v5.ByExternalID, "") +// data, status, err := client.CorporateCustomer(12, retailcrm.ByExternalID, "") // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // if data.Success == true { -// fmt.Printf("%v\n", data.CorporateCustomer) +// log.Printf("%v\n", data.CorporateCustomer) // } func (c *Client) CorporateCustomer(id, by, site string) (CorporateCustomerResponse, int, error) { var resp CorporateCustomerResponse @@ -1122,7 +1197,10 @@ func (c *Client) CorporateCustomer(id, by, site string) (CorporateCustomerRespon return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -1133,28 +1211,28 @@ func (c *Client) CorporateCustomer(id, by, site string) (CorporateCustomerRespon // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.CorporateCustomerAddresses("ext-id", v5.CorporateCustomerAddressesRequest{ +// data, status, err := client.CorporateCustomerAddresses("ext-id", retailcrm.CorporateCustomerAddressesRequest{ // Filter: v5,CorporateCustomerAddressesFilter{ // Name: "Main Address", // }, -// By: v5.ByExternalID, +// By: retailcrm.ByExternalID, // Site: "site", // Limit: 20, // Page: 1, // }) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // if data.Success == true { -// fmt.Printf("%v\n", data.Addresses) +// log.Printf("%v\n", data.Addresses) // } func (c *Client) CorporateCustomerAddresses( id string, parameters CorporateCustomerAddressesRequest, @@ -1169,7 +1247,10 @@ func (c *Client) CorporateCustomerAddresses( return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -1180,19 +1261,19 @@ func (c *Client) CorporateCustomerAddresses( // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := c.CorporateCustomerAddressesCreate("ext-id", v5.ByExternalID, v5.CorporateCustomerAddress{ +// data, status, err := c.CorporateCustomerAddressesCreate("ext-id", retailcrm.ByExternalID, retailcrm.CorporateCustomerAddress{ // Text: "this is new address", // Name: "New Address", // }) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // if data.Success == true { @@ -1206,8 +1287,8 @@ func (c *Client) CorporateCustomerAddressesCreate( addressJSON, _ := json.Marshal(&address) p := url.Values{ - "address": {string(addressJSON[:])}, - "by": {string(checkBy(by))}, + "address": {string(addressJSON)}, + "by": {checkBy(by)}, } fillSite(&p, site) @@ -1217,23 +1298,26 @@ func (c *Client) CorporateCustomerAddressesCreate( return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } -// CorporateCustomersAddressesEdit edit exact corporate customer address +// CorporateCustomerAddressesEdit edit exact corporate customer address // // For more information see http://help.retailcrm.pro/Developers/ApiVersion5#post--api-v5-customers-corporate-externalId-addresses-entityExternalId-edit // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // // data, status, err := c.CorporateCustomerAddressesEdit( // "customer-ext-id", -// v5.ByExternalID, -// v5.ByExternalID, +// retailcrm.ByExternalID, +// retailcrm.ByExternalID, // CorporateCustomerAddress{ // ExternalID: "addr-ext-id", // Name: "Main Address 2", @@ -1241,15 +1325,15 @@ func (c *Client) CorporateCustomerAddressesCreate( // ) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // if data.Success == true { -// fmt.Printf("%v\n", data.Customer) +// log.Printf("%v\n", data.Customer) // } func (c *Client) CorporateCustomerAddressesEdit( customerID, customerBy, entityBy string, address CorporateCustomerAddress, site ...string, @@ -1263,18 +1347,18 @@ func (c *Client) CorporateCustomerAddressesEdit( entityBy = checkBy(entityBy) switch entityBy { - case "id": + case ByID: uid = strconv.Itoa(address.ID) - case "externalId": + case ByExternalID: uid = address.ExternalID } addressJSON, _ := json.Marshal(&address) p := url.Values{ - "by": {string(customerBy)}, - "entityBy": {string(entityBy)}, - "address": {string(addressJSON[:])}, + "by": {customerBy}, + "entityBy": {entityBy}, + "address": {string(addressJSON)}, } fillSite(&p, site) @@ -1284,7 +1368,10 @@ func (c *Client) CorporateCustomerAddressesEdit( return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -1295,28 +1382,28 @@ func (c *Client) CorporateCustomerAddressesEdit( // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.CorporateCustomerCompanies("ext-id", v5.IdentifiersPairRequest{ +// data, status, err := client.CorporateCustomerCompanies("ext-id", retailcrm.IdentifiersPairRequest{ // Filter: v5,IdentifiersPairFilter{ // Ids: []string{"1"}, // }, -// By: v5.ByExternalID, +// By: retailcrm.ByExternalID, // Site: "site", // Limit: 20, // Page: 1, // }) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // if data.Success == true { -// fmt.Printf("%v\n", data.Companies) +// log.Printf("%v\n", data.Companies) // } func (c *Client) CorporateCustomerCompanies( id string, parameters IdentifiersPairRequest, @@ -1331,7 +1418,10 @@ func (c *Client) CorporateCustomerCompanies( return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -1342,18 +1432,18 @@ func (c *Client) CorporateCustomerCompanies( // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := c.CorporateCustomerCompaniesCreate("ext-id", v5.ByExternalID, v5.Company{ +// data, status, err := c.CorporateCustomerCompaniesCreate("ext-id", retailcrm.ByExternalID, retailcrm.Company{ // Name: "Company name", // }) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // if data.Success == true { @@ -1367,8 +1457,8 @@ func (c *Client) CorporateCustomerCompaniesCreate( companyJSON, _ := json.Marshal(&company) p := url.Values{ - "company": {string(companyJSON[:])}, - "by": {string(checkBy(by))}, + "company": {string(companyJSON)}, + "by": {checkBy(by)}, } fillSite(&p, site) @@ -1378,7 +1468,10 @@ func (c *Client) CorporateCustomerCompaniesCreate( return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -1389,12 +1482,12 @@ func (c *Client) CorporateCustomerCompaniesCreate( // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // // data, status, err := c.CorporateCustomerCompaniesEdit( // "customer-ext-id", -// v5.ByExternalID, -// v5.ByExternalID, +// retailcrm.ByExternalID, +// retailcrm.ByExternalID, // Company{ // ExternalID: "company-ext-id", // Name: "New Company Name", @@ -1402,15 +1495,15 @@ func (c *Client) CorporateCustomerCompaniesCreate( // ) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // if data.Success == true { -// fmt.Printf("%v\n", data.ID) +// log.Printf("%v\n", data.ID) // } func (c *Client) CorporateCustomerCompaniesEdit( customerID, customerBy, entityBy string, company Company, site ...string, @@ -1424,18 +1517,18 @@ func (c *Client) CorporateCustomerCompaniesEdit( entityBy = checkBy(entityBy) switch entityBy { - case "id": + case ByID: uid = strconv.Itoa(company.ID) - case "externalId": + case ByExternalID: uid = company.ExternalID } addressJSON, _ := json.Marshal(&company) p := url.Values{ - "by": {string(customerBy)}, - "entityBy": {string(entityBy)}, - "company": {string(addressJSON[:])}, + "by": {customerBy}, + "entityBy": {entityBy}, + "company": {string(addressJSON)}, } fillSite(&p, site) @@ -1445,7 +1538,10 @@ func (c *Client) CorporateCustomerCompaniesEdit( return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -1456,28 +1552,28 @@ func (c *Client) CorporateCustomerCompaniesEdit( // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.CorporateCustomerContacts("ext-id", v5.IdentifiersPairRequest{ -// Filter: v5.IdentifiersPairFilter{ +// data, status, err := client.CorporateCustomerContacts("ext-id", retailcrm.IdentifiersPairRequest{ +// Filter: retailcrm.IdentifiersPairFilter{ // Ids: []string{"1"}, // }, -// By: v5.ByExternalID, +// By: retailcrm.ByExternalID, // Site: "site", // Limit: 20, // Page: 1, // }) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // if data.Success == true { -// fmt.Printf("%v\n", data.Contacts) +// log.Printf("%v\n", data.Contacts) // } func (c *Client) CorporateCustomerContacts( id string, parameters IdentifiersPairRequest, @@ -1492,7 +1588,10 @@ func (c *Client) CorporateCustomerContacts( return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -1503,11 +1602,11 @@ func (c *Client) CorporateCustomerContacts( // // Example (customer with specified id or externalId should exist in specified site): // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := c.CorporateCustomerContactsCreate("ext-id", v5.ByExternalID, v5.CorporateCustomerContact{ +// data, status, err := c.CorporateCustomerContactsCreate("ext-id", retailcrm.ByExternalID, retailcrm.CorporateCustomerContact{ // IsMain: false, -// Customer: v5.CorporateCustomerContactCustomer{ +// Customer: retailcrm.CorporateCustomerContactCustomer{ // ExternalID: "external_id", // Site: "site", // }, @@ -1515,11 +1614,11 @@ func (c *Client) CorporateCustomerContacts( // }, "site") // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // if data.Success == true { @@ -1533,8 +1632,8 @@ func (c *Client) CorporateCustomerContactsCreate( companyJSON, _ := json.Marshal(&contact) p := url.Values{ - "contact": {string(companyJSON[:])}, - "by": {string(checkBy(by))}, + "contact": {string(companyJSON)}, + "by": {checkBy(by)}, } fillSite(&p, site) @@ -1544,7 +1643,10 @@ func (c *Client) CorporateCustomerContactsCreate( return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -1555,25 +1657,25 @@ func (c *Client) CorporateCustomerContactsCreate( // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := c.CorporateCustomerContactsEdit("ext-id", v5.ByExternalID, v5.ByID, v5.CorporateCustomerContact{ +// data, status, err := c.CorporateCustomerContactsEdit("ext-id", retailcrm.ByExternalID, retailcrm.ByID, retailcrm.CorporateCustomerContact{ // IsMain: false, -// Customer: v5.CorporateCustomerContactCustomer{ +// Customer: retailcrm.CorporateCustomerContactCustomer{ // ID: 2350, // }, // }, "site") // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // if data.Success == true { -// fmt.Printf("%v\n", data.ID) +// log.Printf("%v\n", data.ID) // } func (c *Client) CorporateCustomerContactsEdit( customerID, customerBy, entityBy string, contact CorporateCustomerContact, site ...string, @@ -1587,18 +1689,18 @@ func (c *Client) CorporateCustomerContactsEdit( entityBy = checkBy(entityBy) switch entityBy { - case "id": + case ByID: uid = strconv.Itoa(contact.Customer.ID) - case "externalId": + case ByExternalID: uid = contact.Customer.ExternalID } addressJSON, _ := json.Marshal(&contact) p := url.Values{ - "by": {string(customerBy)}, - "entityBy": {string(entityBy)}, - "contact": {string(addressJSON[:])}, + "by": {customerBy}, + "entityBy": {entityBy}, + "contact": {string(addressJSON)}, } fillSite(&p, site) @@ -1608,7 +1710,10 @@ func (c *Client) CorporateCustomerContactsEdit( return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -1619,29 +1724,29 @@ func (c *Client) CorporateCustomerContactsEdit( // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // // data, status, err := client.CorporateCustomerEdit( -// v5.CorporateCustomer{ +// retailcrm.CorporateCustomer{ // FirstName: "Ivan", // LastName: "Ivanov", // Patronymic: "Ivanovich", // ID: 1, // Email: "ivanov@example.com", // }, -// v5.ByID, +// retailcrm.ByID, // ) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // if data.Success == true { -// fmt.Printf("%v\n", data.Customer) +// log.Printf("%v\n", data.Customer) // } func (c *Client) CorporateCustomerEdit(customer CorporateCustomer, by string, site ...string) ( CustomerChangeResponse, int, error, @@ -1657,8 +1762,8 @@ func (c *Client) CorporateCustomerEdit(customer CorporateCustomer, by string, si customerJSON, _ := json.Marshal(&customer) p := url.Values{ - "by": {string(context)}, - "customerCorporate": {string(customerJSON[:])}, + "by": {context}, + "customerCorporate": {string(customerJSON)}, } fillSite(&p, site) @@ -1668,7 +1773,10 @@ func (c *Client) CorporateCustomerEdit(customer CorporateCustomer, by string, si return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -1679,14 +1787,14 @@ func (c *Client) CorporateCustomerEdit(customer CorporateCustomer, by string, si // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // t, _ := time.Parse("2006-01-02 15:04:05", "2012-12-12 12:12:12") // // data, status, err := client.DeliveryTracking( -// []v5.DeliveryTrackingRequest{{ +// []retailcrm.DeliveryTrackingRequest{{ // DeliveryID: "1", // TrackNumber: "123", -// History: []v5.DeliveryHistoryRecord{ +// History: []retailcrm.DeliveryHistoryRecord{ // { // Code: "cancel", // UpdatedAt: t.Format(time.RFC3339), @@ -1697,11 +1805,11 @@ func (c *Client) CorporateCustomerEdit(customer CorporateCustomer, by string, si // ) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // func (c *Client) DeliveryTracking(parameters []DeliveryTrackingRequest, subcode string) ( @@ -1712,7 +1820,7 @@ func (c *Client) DeliveryTracking(parameters []DeliveryTrackingRequest, subcode updateJSON, _ := json.Marshal(¶meters) p := url.Values{ - "statusUpdate": {string(updateJSON[:])}, + "statusUpdate": {string(updateJSON)}, } data, status, err := c.PostRequest(fmt.Sprintf("/delivery/generic/%s/tracking", subcode), p) @@ -1720,7 +1828,10 @@ func (c *Client) DeliveryTracking(parameters []DeliveryTrackingRequest, subcode return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -1731,25 +1842,25 @@ func (c *Client) DeliveryTracking(parameters []DeliveryTrackingRequest, subcode // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.DeliveryShipments(v5.DeliveryShipmentsRequest{ +// data, status, err := client.DeliveryShipments(retailcrm.DeliveryShipmentsRequest{ // Limit: 12, -// Filter: v5.ShipmentFilter{ +// Filter: retailcrm.ShipmentFilter{ // DateFrom: "2012-12-12", // }, // }) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // for _, value := range data.DeliveryShipments { -// fmt.Printf("%v\n", value) +// log.Printf("%v\n", value) // } func (c *Client) DeliveryShipments(parameters DeliveryShipmentsRequest) (DeliveryShipmentsResponse, int, error) { var resp DeliveryShipmentsResponse @@ -1761,7 +1872,10 @@ func (c *Client) DeliveryShipments(parameters DeliveryShipmentsRequest) (Deliver return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -1772,30 +1886,30 @@ func (c *Client) DeliveryShipments(parameters DeliveryShipmentsRequest) (Deliver // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // // data, status, err := client.DeliveryShipmentCreate( -// v5.DeliveryShipment{ +// retailcrm.DeliveryShipment{ // Date: "2012-12-12", -// Time: v5.DeliveryTime{ +// Time: retailcrm.DeliveryTime{ // From: "18:00", // To: "20:00", // }, -// Orders: []v5.Order{{Number: "12"}}, +// Orders: []retailcrm.Order{{Number: "12"}}, // }, // "sdek", // ) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // if data.Success == true { -// fmt.Printf("%v\n", data.ID) +// log.Printf("%v\n", data.ID) // } func (c *Client) DeliveryShipmentCreate( shipment DeliveryShipment, deliveryType string, site ...string, @@ -1804,8 +1918,8 @@ func (c *Client) DeliveryShipmentCreate( updateJSON, _ := json.Marshal(&shipment) p := url.Values{ - "deliveryType": {string(deliveryType)}, - "deliveryShipment": {string(updateJSON[:])}, + "deliveryType": {deliveryType}, + "deliveryShipment": {string(updateJSON)}, } fillSite(&p, site) @@ -1815,7 +1929,10 @@ func (c *Client) DeliveryShipmentCreate( return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -1826,20 +1943,20 @@ func (c *Client) DeliveryShipmentCreate( // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // // data, status, err := client.DeliveryShipment(12) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // if data.Success == true { -// fmt.Printf("%v\n", data.DeliveryShipment) +// log.Printf("%v\n", data.DeliveryShipment) // } func (c *Client) DeliveryShipment(id int) (DeliveryShipmentResponse, int, error) { var resp DeliveryShipmentResponse @@ -1849,7 +1966,10 @@ func (c *Client) DeliveryShipment(id int) (DeliveryShipmentResponse, int, error) return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -1860,22 +1980,22 @@ func (c *Client) DeliveryShipment(id int) (DeliveryShipmentResponse, int, error) // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.DeliveryShipmentEdit(v5.DeliveryShipment{ +// data, status, err := client.DeliveryShipmentEdit(retailcrm.DeliveryShipment{ // ID: "12", -// Time: v5.DeliveryTime{ +// Time: retailcrm.DeliveryTime{ // From: "14:00", // To: "18:00", // }, // }) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } func (c *Client) DeliveryShipmentEdit(shipment DeliveryShipment, site ...string) ( DeliveryShipmentUpdateResponse, int, error, @@ -1884,7 +2004,7 @@ func (c *Client) DeliveryShipmentEdit(shipment DeliveryShipment, site ...string) updateJSON, _ := json.Marshal(&shipment) p := url.Values{ - "deliveryShipment": {string(updateJSON[:])}, + "deliveryShipment": {string(updateJSON)}, } fillSite(&p, site) @@ -1894,7 +2014,10 @@ func (c *Client) DeliveryShipmentEdit(shipment DeliveryShipment, site ...string) return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -1905,20 +2028,20 @@ func (c *Client) DeliveryShipmentEdit(shipment DeliveryShipment, site ...string) // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // // data, status, err := client.IntegrationModule("moysklad3") // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // if data.Success == true { -// fmt.Printf("%v\n", data.IntegrationModule) +// log.Printf("%v\n", data.IntegrationModule) // } func (c *Client) IntegrationModule(code string) (IntegrationModuleResponse, int, error) { var resp IntegrationModuleResponse @@ -1928,7 +2051,10 @@ func (c *Client) IntegrationModule(code string) (IntegrationModuleResponse, int, return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -1939,12 +2065,12 @@ func (c *Client) IntegrationModule(code string) (IntegrationModuleResponse, int, // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // // name := "MS" // code := "moysklad3" // -// data, status, err := client.IntegrationModuleEdit(v5.IntegrationModule{ +// data, status, err := client.IntegrationModuleEdit(retailcrm.IntegrationModule{ // Code: code, // IntegrationCode: code, // Active: false, @@ -1972,14 +2098,17 @@ func (c *Client) IntegrationModuleEdit(integrationModule IntegrationModule) ( var resp IntegrationModuleEditResponse updateJSON, _ := json.Marshal(&integrationModule) - p := url.Values{"integrationModule": {string(updateJSON[:])}} + p := url.Values{"integrationModule": {string(updateJSON)}} data, status, err := c.PostRequest(fmt.Sprintf("/integration-modules/%s/edit", integrationModule.Code), p) if err != nil { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -1990,20 +2119,20 @@ func (c *Client) IntegrationModuleEdit(integrationModule IntegrationModule) ( // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.Orders(v5.OrdersRequest{Filter: v5.OrdersFilter{City: "Moscow"}, Page: 1}) +// data, status, err := client.Orders(retailcrm.OrdersRequest{Filter: retailcrm.OrdersFilter{City: "Moscow"}, Page: 1}) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // for _, value := range data.Orders { -// fmt.Printf("%v\n", value) +// log.Printf("%v\n", value) // } func (c *Client) Orders(parameters OrdersRequest) (OrdersResponse, int, error) { var resp OrdersResponse @@ -2015,7 +2144,10 @@ func (c *Client) Orders(parameters OrdersRequest) (OrdersResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -2026,16 +2158,16 @@ func (c *Client) Orders(parameters OrdersRequest) (OrdersResponse, int, error) { // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.OrdersCombine("ours", v5.Order{ID: 1}, v5.Order{ID: 1}) +// data, status, err := client.OrdersCombine("ours", retailcrm.Order{ID: 1}, retailcrm.Order{ID: 1}) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } func (c *Client) OrdersCombine(technique string, order, resultOrder Order) (OperationResponse, int, error) { var resp OperationResponse @@ -2045,8 +2177,8 @@ func (c *Client) OrdersCombine(technique string, order, resultOrder Order) (Oper p := url.Values{ "technique": {technique}, - "order": {string(combineJSONIn[:])}, - "resultOrder": {string(combineJSONOut[:])}, + "order": {string(combineJSONIn)}, + "resultOrder": {string(combineJSONOut)}, } data, status, err := c.PostRequest("/orders/combine", p) @@ -2054,7 +2186,10 @@ func (c *Client) OrdersCombine(technique string, order, resultOrder Order) (Oper return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -2065,33 +2200,33 @@ func (c *Client) OrdersCombine(technique string, order, resultOrder Order) (Oper // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.OrderCreate(v5.Order{ +// data, status, err := client.OrderCreate(retailcrm.Order{ // FirstName: "Ivan", // LastName: "Ivanov", // Patronymic: "Ivanovich", // Email: "ivanov@example.com", -// Items: []v5.OrderItem{{Offer: v5.Offer{ID: 12}, Quantity: 5}}, +// Items: []retailcrm.OrderItem{{Offer: retailcrm.Offer{ID: 12}, Quantity: 5}}, // }) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // if data.Success == true { -// fmt.Printf("%v\n", data.ID) +// log.Printf("%v\n", data.ID) // } func (c *Client) OrderCreate(order Order, site ...string) (OrderCreateResponse, int, error) { var resp OrderCreateResponse orderJSON, _ := json.Marshal(&order) p := url.Values{ - "order": {string(orderJSON[:])}, + "order": {string(orderJSON)}, } fillSite(&p, site) @@ -2101,7 +2236,10 @@ func (c *Client) OrderCreate(order Order, site ...string) (OrderCreateResponse, return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -2112,9 +2250,9 @@ func (c *Client) OrderCreate(order Order, site ...string) (OrderCreateResponse, // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.OrdersFixExternalIds(([]v5.IdentifiersPair{{ +// data, status, err := client.OrdersFixExternalIds(([]retailcrm.IdentifiersPair{{ // ID: 1, // ExternalID: 12, // }}) @@ -2136,7 +2274,7 @@ func (c *Client) OrdersFixExternalIds(orders []IdentifiersPair) (SuccessfulRespo ordersJSON, _ := json.Marshal(&orders) p := url.Values{ - "orders": {string(ordersJSON[:])}, + "orders": {string(ordersJSON)}, } data, status, err := c.PostRequest("/orders/fix-external-ids", p) @@ -2144,7 +2282,10 @@ func (c *Client) OrdersFixExternalIds(orders []IdentifiersPair) (SuccessfulRespo return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -2155,20 +2296,20 @@ func (c *Client) OrdersFixExternalIds(orders []IdentifiersPair) (SuccessfulRespo // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.OrdersHistory(v5.OrdersHistoryRequest{Filter: v5.OrdersHistoryFilter{SinceID: 20}}) +// data, status, err := client.OrdersHistory(retailcrm.OrdersHistoryRequest{Filter: retailcrm.OrdersHistoryFilter{SinceID: 20}}) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // for _, value := range data.History { -// fmt.Printf("%v\n", value) +// log.Printf("%v\n", value) // } func (c *Client) OrdersHistory(parameters OrdersHistoryRequest) (OrdersHistoryResponse, int, error) { var resp OrdersHistoryResponse @@ -2180,7 +2321,10 @@ func (c *Client) OrdersHistory(parameters OrdersHistoryRequest) (OrdersHistoryRe return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -2191,10 +2335,10 @@ func (c *Client) OrdersHistory(parameters OrdersHistoryRequest) (OrdersHistoryRe // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.OrderPaymentCreate(v5.Payment{ -// Order: &v5.Order{ +// data, status, err := client.OrderPaymentCreate(retailcrm.Payment{ +// Order: &retailcrm.Order{ // ID: 12, // }, // Amount: 300, @@ -2202,15 +2346,15 @@ func (c *Client) OrdersHistory(parameters OrdersHistoryRequest) (OrdersHistoryRe // }) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // if data.Success == true { -// fmt.Printf("%v\n", data.ID) +// log.Printf("%v\n", data.ID) // } func (c *Client) OrderPaymentCreate(payment Payment, site ...string) (CreateResponse, int, error) { var resp CreateResponse @@ -2218,7 +2362,7 @@ func (c *Client) OrderPaymentCreate(payment Payment, site ...string) (CreateResp paymentJSON, _ := json.Marshal(&payment) p := url.Values{ - "payment": {string(paymentJSON[:])}, + "payment": {string(paymentJSON)}, } fillSite(&p, site) @@ -2228,7 +2372,10 @@ func (c *Client) OrderPaymentCreate(payment Payment, site ...string) (CreateResp return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -2239,16 +2386,16 @@ func (c *Client) OrderPaymentCreate(payment Payment, site ...string) (CreateResp // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // // data, status, err := client.OrderPaymentDelete(12) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } func (c *Client) OrderPaymentDelete(id int) (SuccessfulResponse, int, error) { var resp SuccessfulResponse @@ -2262,7 +2409,10 @@ func (c *Client) OrderPaymentDelete(id int) (SuccessfulResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -2273,22 +2423,22 @@ func (c *Client) OrderPaymentDelete(id int) (SuccessfulResponse, int, error) { // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // // data, status, err := client.OrderPaymentEdit( -// v5.Payment{ +// retailcrm.Payment{ // ID: 12, // Amount: 500, // }, -// v5.ByID, +// retailcrm.ByID, // ) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } func (c *Client) OrderPaymentEdit(payment Payment, by string, site ...string) (SuccessfulResponse, int, error) { var resp SuccessfulResponse @@ -2303,7 +2453,7 @@ func (c *Client) OrderPaymentEdit(payment Payment, by string, site ...string) (S p := url.Values{ "by": {context}, - "payment": {string(paymentJSON[:])}, + "payment": {string(paymentJSON)}, } fillSite(&p, site) @@ -2313,7 +2463,10 @@ func (c *Client) OrderPaymentEdit(payment Payment, by string, site ...string) (S return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -2324,19 +2477,19 @@ func (c *Client) OrderPaymentEdit(payment Payment, by string, site ...string) (S // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.OrdersStatuses(v5.OrdersStatusesRequest{ +// data, status, err := client.OrdersStatuses(retailcrm.OrdersStatusesRequest{ // IDs: []int{1}, // ExternalIDs: []string{"2"}, // }) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } func (c *Client) OrdersStatuses(request OrdersStatusesRequest) (OrdersStatusesResponse, int, error) { var resp OrdersStatusesResponse @@ -2348,7 +2501,10 @@ func (c *Client) OrdersStatuses(request OrdersStatusesRequest) (OrdersStatusesRe return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -2359,35 +2515,35 @@ func (c *Client) OrdersStatuses(request OrdersStatusesRequest) (OrdersStatusesRe // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.OrdersUpload([]v5.Order{ +// data, status, err := client.OrdersUpload([]retailcrm.Order{ // { // FirstName: "Ivan", // LastName: "Ivanov", // Patronymic: "Ivanovich", // Email: "ivanov@example.com", -// Items: []v5.OrderItem{{Offer: v5.Offer{ID: 12}, Quantity: 5}}, +// Items: []retailcrm.OrderItem{{Offer: retailcrm.Offer{ID: 12}, Quantity: 5}}, // }, // { // FirstName: "Pert", // LastName: "Petrov", // Patronymic: "Petrovich", // Email: "petrov@example.com", -// Items: []v5.OrderItem{{Offer: v5.Offer{ID: 13}, Quantity: 1}}, +// Items: []retailcrm.OrderItem{{Offer: retailcrm.Offer{ID: 13}, Quantity: 1}}, // } // }) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // if data.Success == true { -// fmt.Printf("%v\n", data.UploadedOrders) +// log.Printf("%v\n", data.UploadedOrders) // } func (c *Client) OrdersUpload(orders []Order, site ...string) (OrdersUploadResponse, int, error) { var resp OrdersUploadResponse @@ -2395,7 +2551,7 @@ func (c *Client) OrdersUpload(orders []Order, site ...string) (OrdersUploadRespo uploadJSON, _ := json.Marshal(&orders) p := url.Values{ - "orders": {string(uploadJSON[:])}, + "orders": {string(uploadJSON)}, } fillSite(&p, site) @@ -2405,7 +2561,10 @@ func (c *Client) OrdersUpload(orders []Order, site ...string) (OrdersUploadRespo return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -2416,20 +2575,20 @@ func (c *Client) OrdersUpload(orders []Order, site ...string) (OrdersUploadRespo // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.Order(12, v5.ByExternalID, "") +// data, status, err := client.Order(12, retailcrm.ByExternalID, "") // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // if data.Success == true { -// fmt.Printf("%v\n", data.Order) +// log.Printf("%v\n", data.Order) // } func (c *Client) Order(id, by, site string) (OrderResponse, int, error) { var resp OrderResponse @@ -2443,7 +2602,10 @@ func (c *Client) Order(id, by, site string) (OrderResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -2454,22 +2616,22 @@ func (c *Client) Order(id, by, site string) (OrderResponse, int, error) { // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // // data, status, err := client.OrderEdit( -// v5.Order{ +// retailcrm.Order{ // ID: 12, -// Items: []v5.OrderItem{{Offer: v5.Offer{ID: 13}, Quantity: 6}}, +// Items: []retailcrm.OrderItem{{Offer: retailcrm.Offer{ID: 13}, Quantity: 6}}, // }, -// v5.ByID, +// retailcrm.ByID, // ) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } func (c *Client) OrderEdit(order Order, by string, site ...string) (CreateResponse, int, error) { var resp CreateResponse @@ -2483,8 +2645,8 @@ func (c *Client) OrderEdit(order Order, by string, site ...string) (CreateRespon orderJSON, _ := json.Marshal(&order) p := url.Values{ - "by": {string(context)}, - "order": {string(orderJSON[:])}, + "by": {context}, + "order": {string(orderJSON)}, } fillSite(&p, site) @@ -2494,7 +2656,10 @@ func (c *Client) OrderEdit(order Order, by string, site ...string) (CreateRespon return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -2505,20 +2670,20 @@ func (c *Client) OrderEdit(order Order, by string, site ...string) (CreateRespon // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.Packs(v5.PacksRequest{Filter: v5.PacksFilter{OrderID: 12}}) +// data, status, err := client.Packs(retailcrm.PacksRequest{Filter: retailcrm.PacksFilter{OrderID: 12}}) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // for _, value := range data.Packs { -// fmt.Printf("%v\n", value) +// log.Printf("%v\n", value) // } func (c *Client) Packs(parameters PacksRequest) (PacksResponse, int, error) { var resp PacksResponse @@ -2530,7 +2695,10 @@ func (c *Client) Packs(parameters PacksRequest) (PacksResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -2541,7 +2709,7 @@ func (c *Client) Packs(parameters PacksRequest) (PacksResponse, int, error) { // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // // data, status, err := client.PackCreate(Pack{ // Store: "store-1", @@ -2550,22 +2718,22 @@ func (c *Client) Packs(parameters PacksRequest) (PacksResponse, int, error) { // }) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // if data.Success == true { -// fmt.Printf("%v\n", data.ID) +// log.Printf("%v\n", data.ID) // } func (c *Client) PackCreate(pack Pack) (CreateResponse, int, error) { var resp CreateResponse packJSON, _ := json.Marshal(&pack) p := url.Values{ - "pack": {string(packJSON[:])}, + "pack": {string(packJSON)}, } data, status, err := c.PostRequest("/orders/packs/create", p) @@ -2573,7 +2741,10 @@ func (c *Client) PackCreate(pack Pack) (CreateResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -2584,20 +2755,20 @@ func (c *Client) PackCreate(pack Pack) (CreateResponse, int, error) { // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.PacksHistory(v5.PacksHistoryRequest{Filter: v5.OrdersHistoryFilter{SinceID: 5}}) +// data, status, err := client.PacksHistory(retailcrm.PacksHistoryRequest{Filter: retailcrm.OrdersHistoryFilter{SinceID: 5}}) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // for _, value := range data.History { -// fmt.Printf("%v\n", value) +// log.Printf("%v\n", value) // } func (c *Client) PacksHistory(parameters PacksHistoryRequest) (PacksHistoryResponse, int, error) { var resp PacksHistoryResponse @@ -2609,7 +2780,10 @@ func (c *Client) PacksHistory(parameters PacksHistoryRequest) (PacksHistoryRespo return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -2620,20 +2794,20 @@ func (c *Client) PacksHistory(parameters PacksHistoryRequest) (PacksHistoryRespo // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // // data, status, err := client.Pack(112) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // if data.Success == true { -// fmt.Printf("%v\n", data.Pack) +// log.Printf("%v\n", data.Pack) // } func (c *Client) Pack(id int) (PackResponse, int, error) { var resp PackResponse @@ -2643,7 +2817,10 @@ func (c *Client) Pack(id int) (PackResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -2654,16 +2831,16 @@ func (c *Client) Pack(id int) (PackResponse, int, error) { // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // // data, status, err := client.PackDelete(112) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } func (c *Client) PackDelete(id int) (SuccessfulResponse, int, error) { var resp SuccessfulResponse @@ -2673,7 +2850,10 @@ func (c *Client) PackDelete(id int) (SuccessfulResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -2684,16 +2864,16 @@ func (c *Client) PackDelete(id int) (SuccessfulResponse, int, error) { // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // // data, status, err := client.PackEdit(Pack{ID: 12, Quantity: 2}) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } func (c *Client) PackEdit(pack Pack) (CreateResponse, int, error) { var resp CreateResponse @@ -2701,7 +2881,7 @@ func (c *Client) PackEdit(pack Pack) (CreateResponse, int, error) { packJSON, _ := json.Marshal(&pack) p := url.Values{ - "pack": {string(packJSON[:])}, + "pack": {string(packJSON)}, } data, status, err := c.PostRequest(fmt.Sprintf("/orders/packs/%d/edit", pack.ID), p) @@ -2709,7 +2889,10 @@ func (c *Client) PackEdit(pack Pack) (CreateResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -2725,7 +2908,10 @@ func (c *Client) Countries() (CountriesResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -2741,7 +2927,10 @@ func (c *Client) CostGroups() (CostGroupsResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -2752,19 +2941,19 @@ func (c *Client) CostGroups() (CostGroupsResponse, int, error) { // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.CostGroupEdit(v5.CostGroup{ +// data, status, err := client.CostGroupEdit(retailcrm.CostGroup{ // Code: "group-1", // Color: "#da5c98", // }) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } func (c *Client) CostGroupEdit(costGroup CostGroup) (SuccessfulResponse, int, error) { var resp SuccessfulResponse @@ -2772,7 +2961,7 @@ func (c *Client) CostGroupEdit(costGroup CostGroup) (SuccessfulResponse, int, er objJSON, _ := json.Marshal(&costGroup) p := url.Values{ - "costGroup": {string(objJSON[:])}, + "costGroup": {string(objJSON)}, } data, status, err := c.PostRequest(fmt.Sprintf("/reference/cost-groups/%s/edit", costGroup.Code), p) @@ -2780,7 +2969,10 @@ func (c *Client) CostGroupEdit(costGroup CostGroup) (SuccessfulResponse, int, er return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -2796,7 +2988,10 @@ func (c *Client) CostItems() (CostItemsResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -2807,19 +3002,19 @@ func (c *Client) CostItems() (CostItemsResponse, int, error) { // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.CostItemEdit(v5.CostItem{ +// data, status, err := client.CostItemEdit(retailcrm.CostItem{ // Code: "seo", // Active: false, // }) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } func (c *Client) CostItemEdit(costItem CostItem) (SuccessfulResponse, int, error) { var resp SuccessfulResponse @@ -2827,7 +3022,7 @@ func (c *Client) CostItemEdit(costItem CostItem) (SuccessfulResponse, int, error objJSON, _ := json.Marshal(&costItem) p := url.Values{ - "costItem": {string(objJSON[:])}, + "costItem": {string(objJSON)}, } data, status, err := c.PostRequest(fmt.Sprintf("/reference/cost-items/%s/edit", costItem.Code), p) @@ -2835,7 +3030,10 @@ func (c *Client) CostItemEdit(costItem CostItem) (SuccessfulResponse, int, error return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -2851,7 +3049,10 @@ func (c *Client) Couriers() (CouriersResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -2862,9 +3063,9 @@ func (c *Client) Couriers() (CouriersResponse, int, error) { // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.CostItemEdit(v5.Courier{ +// data, status, err := client.CostItemEdit(retailcrm.Courier{ // Active: true, // Email: "courier1@example.com", // FirstName: "Ivan", @@ -2872,15 +3073,15 @@ func (c *Client) Couriers() (CouriersResponse, int, error) { // }) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // if data.Success == true { -// fmt.Printf("%v", data.ID) +// log.Printf("%v", data.ID) // } func (c *Client) CourierCreate(courier Courier) (CreateResponse, int, error) { var resp CreateResponse @@ -2888,7 +3089,7 @@ func (c *Client) CourierCreate(courier Courier) (CreateResponse, int, error) { objJSON, _ := json.Marshal(&courier) p := url.Values{ - "courier": {string(objJSON[:])}, + "courier": {string(objJSON)}, } data, status, err := c.PostRequest("/reference/couriers/create", p) @@ -2896,7 +3097,10 @@ func (c *Client) CourierCreate(courier Courier) (CreateResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -2907,19 +3111,19 @@ func (c *Client) CourierCreate(courier Courier) (CreateResponse, int, error) { // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.CostItemEdit(v5.Courier{ +// data, status, err := client.CostItemEdit(retailcrm.Courier{ // ID: 1, // Patronymic: "Ivanovich", // }) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } func (c *Client) CourierEdit(courier Courier) (SuccessfulResponse, int, error) { var resp SuccessfulResponse @@ -2927,7 +3131,7 @@ func (c *Client) CourierEdit(courier Courier) (SuccessfulResponse, int, error) { objJSON, _ := json.Marshal(&courier) p := url.Values{ - "courier": {string(objJSON[:])}, + "courier": {string(objJSON)}, } data, status, err := c.PostRequest(fmt.Sprintf("/reference/couriers/%d/edit", courier.ID), p) @@ -2935,7 +3139,10 @@ func (c *Client) CourierEdit(courier Courier) (SuccessfulResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -2951,7 +3158,10 @@ func (c *Client) DeliveryServices() (DeliveryServiceResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -2962,19 +3172,19 @@ func (c *Client) DeliveryServices() (DeliveryServiceResponse, int, error) { // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.DeliveryServiceEdit(v5.DeliveryService{ +// data, status, err := client.DeliveryServiceEdit(retailcrm.DeliveryService{ // Active: false, // Code: "delivery-1", // }) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } func (c *Client) DeliveryServiceEdit(deliveryService DeliveryService) (SuccessfulResponse, int, error) { var resp SuccessfulResponse @@ -2982,7 +3192,7 @@ func (c *Client) DeliveryServiceEdit(deliveryService DeliveryService) (Successfu objJSON, _ := json.Marshal(&deliveryService) p := url.Values{ - "deliveryService": {string(objJSON[:])}, + "deliveryService": {string(objJSON)}, } data, status, err := c.PostRequest(fmt.Sprintf("/reference/delivery-services/%s/edit", deliveryService.Code), p) @@ -2990,7 +3200,10 @@ func (c *Client) DeliveryServiceEdit(deliveryService DeliveryService) (Successfu return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -3006,7 +3219,10 @@ func (c *Client) DeliveryTypes() (DeliveryTypesResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -3017,9 +3233,9 @@ func (c *Client) DeliveryTypes() (DeliveryTypesResponse, int, error) { // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.DeliveryTypeEdit(v5.DeliveryType{ +// data, status, err := client.DeliveryTypeEdit(retailcrm.DeliveryType{ // Active: false, // Code: "type-1", // DefaultCost: 300, @@ -3027,11 +3243,11 @@ func (c *Client) DeliveryTypes() (DeliveryTypesResponse, int, error) { // } // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } func (c *Client) DeliveryTypeEdit(deliveryType DeliveryType) (SuccessfulResponse, int, error) { var resp SuccessfulResponse @@ -3039,7 +3255,7 @@ func (c *Client) DeliveryTypeEdit(deliveryType DeliveryType) (SuccessfulResponse objJSON, _ := json.Marshal(&deliveryType) p := url.Values{ - "deliveryType": {string(objJSON[:])}, + "deliveryType": {string(objJSON)}, } data, status, err := c.PostRequest(fmt.Sprintf("/reference/delivery-types/%s/edit", deliveryType.Code), p) @@ -3047,7 +3263,10 @@ func (c *Client) DeliveryTypeEdit(deliveryType DeliveryType) (SuccessfulResponse return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -3063,7 +3282,10 @@ func (c *Client) LegalEntities() (LegalEntitiesResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -3074,19 +3296,19 @@ func (c *Client) LegalEntities() (LegalEntitiesResponse, int, error) { // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.LegalEntityEdit(v5.LegalEntity{ +// data, status, err := client.LegalEntityEdit(retailcrm.LegalEntity{ // Code: "legal-entity-1", // CertificateDate: "2012-12-12", // } // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } func (c *Client) LegalEntityEdit(legalEntity LegalEntity) (SuccessfulResponse, int, error) { var resp SuccessfulResponse @@ -3094,7 +3316,7 @@ func (c *Client) LegalEntityEdit(legalEntity LegalEntity) (SuccessfulResponse, i objJSON, _ := json.Marshal(&legalEntity) p := url.Values{ - "legalEntity": {string(objJSON[:])}, + "legalEntity": {string(objJSON)}, } data, status, err := c.PostRequest(fmt.Sprintf("/reference/legal-entities/%s/edit", legalEntity.Code), p) @@ -3102,7 +3324,10 @@ func (c *Client) LegalEntityEdit(legalEntity LegalEntity) (SuccessfulResponse, i return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -3118,7 +3343,10 @@ func (c *Client) OrderMethods() (OrderMethodsResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -3129,20 +3357,20 @@ func (c *Client) OrderMethods() (OrderMethodsResponse, int, error) { // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.OrderMethodEdit(v5.OrderMethod{ +// data, status, err := client.OrderMethodEdit(retailcrm.OrderMethod{ // Code: "method-1", // Active: false, // DefaultForCRM: false, // }) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } func (c *Client) OrderMethodEdit(orderMethod OrderMethod) (SuccessfulResponse, int, error) { var resp SuccessfulResponse @@ -3150,7 +3378,7 @@ func (c *Client) OrderMethodEdit(orderMethod OrderMethod) (SuccessfulResponse, i objJSON, _ := json.Marshal(&orderMethod) p := url.Values{ - "orderMethod": {string(objJSON[:])}, + "orderMethod": {string(objJSON)}, } data, status, err := c.PostRequest(fmt.Sprintf("/reference/order-methods/%s/edit", orderMethod.Code), p) @@ -3158,7 +3386,10 @@ func (c *Client) OrderMethodEdit(orderMethod OrderMethod) (SuccessfulResponse, i return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -3174,7 +3405,10 @@ func (c *Client) OrderTypes() (OrderTypesResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -3185,20 +3419,20 @@ func (c *Client) OrderTypes() (OrderTypesResponse, int, error) { // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.OrderTypeEdit(v5.OrderType{ +// data, status, err := client.OrderTypeEdit(retailcrm.OrderType{ // Code: "order-type-1", // Active: false, // DefaultForCRM: false, // }) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } func (c *Client) OrderTypeEdit(orderType OrderType) (SuccessfulResponse, int, error) { var resp SuccessfulResponse @@ -3206,7 +3440,7 @@ func (c *Client) OrderTypeEdit(orderType OrderType) (SuccessfulResponse, int, er objJSON, _ := json.Marshal(&orderType) p := url.Values{ - "orderType": {string(objJSON[:])}, + "orderType": {string(objJSON)}, } data, status, err := c.PostRequest(fmt.Sprintf("/reference/order-types/%s/edit", orderType.Code), p) @@ -3214,7 +3448,10 @@ func (c *Client) OrderTypeEdit(orderType OrderType) (SuccessfulResponse, int, er return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -3230,7 +3467,10 @@ func (c *Client) PaymentStatuses() (PaymentStatusesResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -3244,7 +3484,7 @@ func (c *Client) PaymentStatusEdit(paymentStatus PaymentStatus) (SuccessfulRespo objJSON, _ := json.Marshal(&paymentStatus) p := url.Values{ - "paymentStatus": {string(objJSON[:])}, + "paymentStatus": {string(objJSON)}, } data, status, err := c.PostRequest(fmt.Sprintf("/reference/payment-statuses/%s/edit", paymentStatus.Code), p) @@ -3252,7 +3492,10 @@ func (c *Client) PaymentStatusEdit(paymentStatus PaymentStatus) (SuccessfulRespo return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -3268,7 +3511,10 @@ func (c *Client) PaymentTypes() (PaymentTypesResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -3282,7 +3528,7 @@ func (c *Client) PaymentTypeEdit(paymentType PaymentType) (SuccessfulResponse, i objJSON, _ := json.Marshal(&paymentType) p := url.Values{ - "paymentType": {string(objJSON[:])}, + "paymentType": {string(objJSON)}, } data, status, err := c.PostRequest(fmt.Sprintf("/reference/payment-types/%s/edit", paymentType.Code), p) @@ -3290,7 +3536,10 @@ func (c *Client) PaymentTypeEdit(paymentType PaymentType) (SuccessfulResponse, i return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -3306,7 +3555,10 @@ func (c *Client) PriceTypes() (PriceTypesResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -3320,7 +3572,7 @@ func (c *Client) PriceTypeEdit(priceType PriceType) (SuccessfulResponse, int, er objJSON, _ := json.Marshal(&priceType) p := url.Values{ - "priceType": {string(objJSON[:])}, + "priceType": {string(objJSON)}, } data, status, err := c.PostRequest(fmt.Sprintf("/reference/price-types/%s/edit", priceType.Code), p) @@ -3328,7 +3580,10 @@ func (c *Client) PriceTypeEdit(priceType PriceType) (SuccessfulResponse, int, er return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -3344,7 +3599,10 @@ func (c *Client) ProductStatuses() (ProductStatusesResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -3358,7 +3616,7 @@ func (c *Client) ProductStatusEdit(productStatus ProductStatus) (SuccessfulRespo objJSON, _ := json.Marshal(&productStatus) p := url.Values{ - "productStatus": {string(objJSON[:])}, + "productStatus": {string(objJSON)}, } data, status, err := c.PostRequest(fmt.Sprintf("/reference/product-statuses/%s/edit", productStatus.Code), p) @@ -3366,7 +3624,10 @@ func (c *Client) ProductStatusEdit(productStatus ProductStatus) (SuccessfulRespo return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -3382,7 +3643,10 @@ func (c *Client) Sites() (SitesResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -3396,7 +3660,7 @@ func (c *Client) SiteEdit(site Site) (SuccessfulResponse, int, error) { objJSON, _ := json.Marshal(&site) p := url.Values{ - "site": {string(objJSON[:])}, + "site": {string(objJSON)}, } data, status, err := c.PostRequest(fmt.Sprintf("/reference/sites/%s/edit", site.Code), p) @@ -3404,7 +3668,10 @@ func (c *Client) SiteEdit(site Site) (SuccessfulResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -3420,7 +3687,10 @@ func (c *Client) StatusGroups() (StatusGroupsResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -3436,7 +3706,10 @@ func (c *Client) Statuses() (StatusesResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -3450,7 +3723,7 @@ func (c *Client) StatusEdit(st Status) (SuccessfulResponse, int, error) { objJSON, _ := json.Marshal(&st) p := url.Values{ - "status": {string(objJSON[:])}, + "status": {string(objJSON)}, } data, status, err := c.PostRequest(fmt.Sprintf("/reference/statuses/%s/edit", st.Code), p) @@ -3458,7 +3731,10 @@ func (c *Client) StatusEdit(st Status) (SuccessfulResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -3474,7 +3750,10 @@ func (c *Client) Stores() (StoresResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -3488,7 +3767,7 @@ func (c *Client) StoreEdit(store Store) (SuccessfulResponse, int, error) { objJSON, _ := json.Marshal(&store) p := url.Values{ - "store": {string(objJSON[:])}, + "store": {string(objJSON)}, } data, status, err := c.PostRequest(fmt.Sprintf("/reference/stores/%s/edit", store.Code), p) @@ -3496,7 +3775,10 @@ func (c *Client) StoreEdit(store Store) (SuccessfulResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -3512,7 +3794,10 @@ func (c *Client) Units() (UnitsResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -3526,7 +3811,7 @@ func (c *Client) UnitEdit(unit Unit) (SuccessfulResponse, int, error) { objJSON, _ := json.Marshal(&unit) p := url.Values{ - "unit": {string(objJSON[:])}, + "unit": {string(objJSON)}, } data, status, err := c.PostRequest(fmt.Sprintf("/reference/units/%s/edit", unit.Code), p) @@ -3534,7 +3819,10 @@ func (c *Client) UnitEdit(unit Unit) (SuccessfulResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -3545,10 +3833,10 @@ func (c *Client) UnitEdit(unit Unit) (SuccessfulResponse, int, error) { // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // // data, status, err := client.Segments(SegmentsRequest{ -// Filter: v5.SegmentsFilter{ +// Filter: retailcrm.SegmentsFilter{ // Ids: []int{1,2,3} // } // }) @@ -3574,7 +3862,10 @@ func (c *Client) Segments(parameters SegmentsRequest) (SegmentsResponse, int, er return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -3585,7 +3876,7 @@ func (c *Client) Segments(parameters SegmentsRequest) (SegmentsResponse, int, er // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // // data, status, err := client.Settings() // @@ -3606,7 +3897,10 @@ func (c *Client) Settings() (SettingsResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -3617,20 +3911,20 @@ func (c *Client) Settings() (SettingsResponse, int, error) { // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.Inventories(v5.InventoriesRequest{Filter: v5.InventoriesFilter{Details: 1, ProductActive: 1}, Page: 1}) +// data, status, err := client.Inventories(retailcrm.InventoriesRequest{Filter: retailcrm.InventoriesFilter{Details: 1, ProductActive: 1}, Page: 1}) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // for _, value := range data.Offers { -// fmt.Printf("%v\n", value) +// log.Printf("%v\n", value) // } func (c *Client) Inventories(parameters InventoriesRequest) (InventoriesResponse, int, error) { var resp InventoriesResponse @@ -3642,7 +3936,10 @@ func (c *Client) Inventories(parameters InventoriesRequest) (InventoriesResponse return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -3653,10 +3950,10 @@ func (c *Client) Inventories(parameters InventoriesRequest) (InventoriesResponse // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // // data, status, err := client.InventoriesUpload( -// []v5.InventoryUpload{ +// []retailcrm.InventoryUpload{ // { // XMLID: "pT22K9YzX21HTdzFCe1", // Stores: []InventoryUploadStore{ @@ -3691,7 +3988,7 @@ func (c *Client) InventoriesUpload(inventories []InventoryUpload, site ...string uploadJSON, _ := json.Marshal(&inventories) p := url.Values{ - "offers": {string(uploadJSON[:])}, + "offers": {string(uploadJSON)}, } fillSite(&p, site) @@ -3701,7 +3998,10 @@ func (c *Client) InventoriesUpload(inventories []InventoryUpload, site ...string return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -3712,9 +4012,9 @@ func (c *Client) InventoriesUpload(inventories []InventoryUpload, site ...string // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.PricesUpload([]v5.OfferPriceUpload{ +// data, status, err := client.PricesUpload([]retailcrm.OfferPriceUpload{ // { // ID 1 // Site "store-1" @@ -3742,7 +4042,7 @@ func (c *Client) PricesUpload(prices []OfferPriceUpload) (StoreUploadResponse, i uploadJSON, _ := json.Marshal(&prices) p := url.Values{ - "prices": {string(uploadJSON[:])}, + "prices": {string(uploadJSON)}, } data, status, err := c.PostRequest("/store/prices/upload", p) @@ -3750,7 +4050,10 @@ func (c *Client) PricesUpload(prices []OfferPriceUpload) (StoreUploadResponse, i return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -3761,24 +4064,24 @@ func (c *Client) PricesUpload(prices []OfferPriceUpload) (StoreUploadResponse, i // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.ProductsGroup(v5.ProductsGroupsRequest{ -// Filter: v5.ProductsGroupsFilter{ +// data, status, err := client.ProductsGroup(retailcrm.ProductsGroupsRequest{ +// Filter: retailcrm.ProductsGroupsFilter{ // Active: 1, // }, // }) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // for _, value := range data.ProductGroup { -// fmt.Printf("%v\n", value) +// log.Printf("%v\n", value) // } func (c *Client) ProductsGroup(parameters ProductsGroupsRequest) (ProductsGroupsResponse, int, error) { var resp ProductsGroupsResponse @@ -3790,7 +4093,10 @@ func (c *Client) ProductsGroup(parameters ProductsGroupsRequest) (ProductsGroups return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -3801,25 +4107,25 @@ func (c *Client) ProductsGroup(parameters ProductsGroupsRequest) (ProductsGroups // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.Products(v5.ProductsRequest{ -// Filter: v5.ProductsFilter{ +// data, status, err := client.Products(retailcrm.ProductsRequest{ +// Filter: retailcrm.ProductsFilter{ // Active: 1, // MinPrice: 1000, // }, // }) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // for _, value := range data.Products { -// fmt.Printf("%v\n", value) +// log.Printf("%v\n", value) // } func (c *Client) Products(parameters ProductsRequest) (ProductsResponse, int, error) { var resp ProductsResponse @@ -3831,7 +4137,10 @@ func (c *Client) Products(parameters ProductsRequest) (ProductsResponse, int, er return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -3842,24 +4151,24 @@ func (c *Client) Products(parameters ProductsRequest) (ProductsResponse, int, er // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.ProductsProperties(v5.ProductsPropertiesRequest{ -// Filter: v5.ProductsPropertiesFilter{ +// data, status, err := client.ProductsProperties(retailcrm.ProductsPropertiesRequest{ +// Filter: retailcrm.ProductsPropertiesFilter{ // Sites: []string["store"], // }, // }) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // for _, value := range data.Properties { -// fmt.Printf("%v\n", value) +// log.Printf("%v\n", value) // } func (c *Client) ProductsProperties(parameters ProductsPropertiesRequest) (ProductsPropertiesResponse, int, error) { var resp ProductsPropertiesResponse @@ -3871,7 +4180,10 @@ func (c *Client) ProductsProperties(parameters ProductsPropertiesRequest) (Produ return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -3882,24 +4194,24 @@ func (c *Client) ProductsProperties(parameters ProductsPropertiesRequest) (Produ // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.Tasks(v5.TasksRequest{ +// data, status, err := client.Tasks(retailcrm.TasksRequest{ // Filter: TasksFilter{ // DateFrom: "2012-12-12", // }, // }) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // for _, value := range data.Tasks { -// fmt.Printf("%v\n", value) +// log.Printf("%v\n", value) // } func (c *Client) Tasks(parameters TasksRequest) (TasksResponse, int, error) { var resp TasksResponse @@ -3911,7 +4223,10 @@ func (c *Client) Tasks(parameters TasksRequest) (TasksResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -3922,30 +4237,30 @@ func (c *Client) Tasks(parameters TasksRequest) (TasksResponse, int, error) { // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.Tasks(v5.Task{ +// data, status, err := client.Tasks(retailcrm.Task{ // Text: "task №1", // PerformerID: 12, // }) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // if data.Success == true { -// fmt.Printf("%v\n", data.ID) +// log.Printf("%v\n", data.ID) // } func (c *Client) TaskCreate(task Task, site ...string) (CreateResponse, int, error) { var resp CreateResponse taskJSON, _ := json.Marshal(&task) p := url.Values{ - "task": {string(taskJSON[:])}, + "task": {string(taskJSON)}, } fillSite(&p, site) @@ -3955,7 +4270,10 @@ func (c *Client) TaskCreate(task Task, site ...string) (CreateResponse, int, err return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -3966,20 +4284,20 @@ func (c *Client) TaskCreate(task Task, site ...string) (CreateResponse, int, err // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // // data, status, err := client.Task(12) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // if data.Success == true { -// fmt.Printf("%v\n", data.Task) +// log.Printf("%v\n", data.Task) // } func (c *Client) Task(id int) (TaskResponse, int, error) { var resp TaskResponse @@ -3989,7 +4307,10 @@ func (c *Client) Task(id int) (TaskResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -4000,19 +4321,19 @@ func (c *Client) Task(id int) (TaskResponse, int, error) { // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.Task(v5.Task{ +// data, status, err := client.Task(retailcrm.Task{ // ID: 12 // Text: "task №2", // }) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } func (c *Client) TaskEdit(task Task, site ...string) (SuccessfulResponse, int, error) { var resp SuccessfulResponse @@ -4021,7 +4342,7 @@ func (c *Client) TaskEdit(task Task, site ...string) (SuccessfulResponse, int, e taskJSON, _ := json.Marshal(&task) p := url.Values{ - "task": {string(taskJSON[:])}, + "task": {string(taskJSON)}, } fillSite(&p, site) @@ -4031,10 +4352,13 @@ func (c *Client) TaskEdit(task Task, site ...string) (SuccessfulResponse, int, e return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } - if resp.Success == false { - a := NewAPIError(data) + if !resp.Success { + a := CreateAPIError(data) return resp, status, a } @@ -4047,20 +4371,20 @@ func (c *Client) TaskEdit(task Task, site ...string) (SuccessfulResponse, int, e // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.UserGroups(v5.UserGroupsRequest{Page: 1}) +// data, status, err := client.UserGroups(retailcrm.UserGroupsRequest{Page: 1}) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // for _, value := range data.Groups { -// fmt.Printf("%v\n", value) +// log.Printf("%v\n", value) // } func (c *Client) UserGroups(parameters UserGroupsRequest) (UserGroupsResponse, int, error) { var resp UserGroupsResponse @@ -4072,7 +4396,10 @@ func (c *Client) UserGroups(parameters UserGroupsRequest) (UserGroupsResponse, i return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -4083,20 +4410,20 @@ func (c *Client) UserGroups(parameters UserGroupsRequest) (UserGroupsResponse, i // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.Users(v5.UsersRequest{Filter: v5.UsersFilter{Active: 1}, Page: 1}) +// data, status, err := client.Users(retailcrm.UsersRequest{Filter: retailcrm.UsersFilter{Active: 1}, Page: 1}) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // for _, value := range data.Users { -// fmt.Printf("%v\n", value) +// log.Printf("%v\n", value) // } func (c *Client) Users(parameters UsersRequest) (UsersResponse, int, error) { var resp UsersResponse @@ -4108,7 +4435,10 @@ func (c *Client) Users(parameters UsersRequest) (UsersResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -4119,20 +4449,20 @@ func (c *Client) Users(parameters UsersRequest) (UsersResponse, int, error) { // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // // data, status, err := client.User(12) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // if data.Success == true { -// fmt.Printf("%v\n", data.User) +// log.Printf("%v\n", data.User) // } func (c *Client) User(id int) (UserResponse, int, error) { var resp UserResponse @@ -4142,7 +4472,10 @@ func (c *Client) User(id int) (UserResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -4153,22 +4486,22 @@ func (c *Client) User(id int) (UserResponse, int, error) { // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // // data, status, err := client.UserStatus(12, "busy") // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } func (c *Client) UserStatus(id int, status string) (SuccessfulResponse, int, error) { var resp SuccessfulResponse p := url.Values{ - "status": {string(status)}, + "status": {status}, } data, st, err := c.PostRequest(fmt.Sprintf("/users/%d/status", id), p) @@ -4176,10 +4509,13 @@ func (c *Client) UserStatus(id int, status string) (SuccessfulResponse, int, err return resp, st, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, st, err + } - if resp.Success == false { - return resp, st, NewAPIError(data) + if !resp.Success { + return resp, st, CreateAPIError(data) } return resp, st, nil @@ -4196,7 +4532,10 @@ func (c *Client) StaticticsUpdate() (SuccessfulResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -4207,7 +4546,7 @@ func (c *Client) StaticticsUpdate() (SuccessfulResponse, int, error) { // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // // data, status, err := client.Costs(CostsRequest{ // Filter: CostsFilter{ @@ -4217,15 +4556,15 @@ func (c *Client) StaticticsUpdate() (SuccessfulResponse, int, error) { // }) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // for _, value := range data.Costs { -// fmt.Printf("%v\n", value.Summ) +// log.Printf("%v\n", value.Summ) // } func (c *Client) Costs(costs CostsRequest) (CostsResponse, int, error) { var resp CostsResponse @@ -4238,21 +4577,24 @@ func (c *Client) Costs(costs CostsRequest) (CostsResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } -// CostCreate create an cost +// CostCreate create the cost // // For more information see http://www.retailcrm.pro/docs/Developers/ApiVersion5#post--api-v5-costs-create // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // // data, status, err := client.CostCreate( -// v5.CostRecord{ +// retailcrm.CostRecord{ // DateFrom: "2012-12-12", // DateTo: "2012-12-12", // Summ: 12, @@ -4266,15 +4608,15 @@ func (c *Client) Costs(costs CostsRequest) (CostsResponse, int, error) { // ) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // If data.Success == true { -// fmt.Printf("%v", data.ID) +// log.Printf("%v", data.ID) // } func (c *Client) CostCreate(cost CostRecord, site ...string) (CreateResponse, int, error) { var resp CreateResponse @@ -4282,7 +4624,7 @@ func (c *Client) CostCreate(cost CostRecord, site ...string) (CreateResponse, in costJSON, _ := json.Marshal(&cost) p := url.Values{ - "cost": {string(costJSON[:])}, + "cost": {string(costJSON)}, } fillSite(&p, site) @@ -4292,7 +4634,10 @@ func (c *Client) CostCreate(cost CostRecord, site ...string) (CreateResponse, in return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -4303,20 +4648,20 @@ func (c *Client) CostCreate(cost CostRecord, site ...string) (CreateResponse, in // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // // data, status, err := client.client.CostsDelete([]int{1, 2, 3, 48, 49, 50}) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // If data.Success == true { -// fmt.Printf("Not removed costs: %v", data.NotRemovedIds) +// log.Printf("Not removed costs: %v", data.NotRemovedIds) // } func (c *Client) CostsDelete(ids []int) (CostsDeleteResponse, int, error) { var resp CostsDeleteResponse @@ -4324,7 +4669,7 @@ func (c *Client) CostsDelete(ids []int) (CostsDeleteResponse, int, error) { costJSON, _ := json.Marshal(&ids) p := url.Values{ - "ids": {string(costJSON[:])}, + "ids": {string(costJSON)}, } data, status, err := c.PostRequest("/costs/delete", p) @@ -4332,7 +4677,10 @@ func (c *Client) CostsDelete(ids []int) (CostsDeleteResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -4343,9 +4691,9 @@ func (c *Client) CostsDelete(ids []int) (CostsDeleteResponse, int, error) { // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.CostCreate([]v5.CostRecord{ +// data, status, err := client.CostCreate([]retailcrm.CostRecord{ // { // DateFrom: "2012-12-12", // DateTo: "2012-12-12", @@ -4365,15 +4713,15 @@ func (c *Client) CostsDelete(ids []int) (CostsDeleteResponse, int, error) { // }) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // If data.Success == true { -// fmt.Printf("Uploaded costs: %v", data.UploadedCosts) +// log.Printf("Uploaded costs: %v", data.UploadedCosts) // } func (c *Client) CostsUpload(cost []CostRecord) (CostsUploadResponse, int, error) { var resp CostsUploadResponse @@ -4381,7 +4729,7 @@ func (c *Client) CostsUpload(cost []CostRecord) (CostsUploadResponse, int, error costJSON, _ := json.Marshal(&cost) p := url.Values{ - "costs": {string(costJSON[:])}, + "costs": {string(costJSON)}, } data, status, err := c.PostRequest("/costs/upload", p) @@ -4389,7 +4737,10 @@ func (c *Client) CostsUpload(cost []CostRecord) (CostsUploadResponse, int, error return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -4400,20 +4751,20 @@ func (c *Client) CostsUpload(cost []CostRecord) (CostsUploadResponse, int, error // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // // data, status, err := client.Cost(1) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // If data.Success == true { -// fmt.Printf("%v", data.Cost) +// log.Printf("%v", data.Cost) // } func (c *Client) Cost(id int) (CostResponse, int, error) { var resp CostResponse @@ -4424,7 +4775,10 @@ func (c *Client) Cost(id int) (CostResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -4435,16 +4789,16 @@ func (c *Client) Cost(id int) (CostResponse, int, error) { // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // // data, status, err := client.CostDelete(1) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } func (c *Client) CostDelete(id int) (SuccessfulResponse, int, error) { var resp SuccessfulResponse @@ -4452,7 +4806,7 @@ func (c *Client) CostDelete(id int) (SuccessfulResponse, int, error) { costJSON, _ := json.Marshal(&id) p := url.Values{ - "costs": {string(costJSON[:])}, + "costs": {string(costJSON)}, } data, status, err := c.PostRequest(fmt.Sprintf("/costs/%d/delete", id), p) @@ -4461,7 +4815,10 @@ func (c *Client) CostDelete(id int) (SuccessfulResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -4472,9 +4829,9 @@ func (c *Client) CostDelete(id int) (SuccessfulResponse, int, error) { // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.CostEdit(1, v5.Cost{ +// data, status, err := client.CostEdit(1, retailcrm.Cost{ // DateFrom: "2012-12-12", // DateTo: "2018-12-13", // Summ: 321, @@ -4482,15 +4839,15 @@ func (c *Client) CostDelete(id int) (SuccessfulResponse, int, error) { // }) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // If data.Success == true { -// fmt.Printf("%v", data.Id) +// log.Printf("%v", data.ID) // } func (c *Client) CostEdit(id int, cost CostRecord, site ...string) (CreateResponse, int, error) { var resp CreateResponse @@ -4498,7 +4855,7 @@ func (c *Client) CostEdit(id int, cost CostRecord, site ...string) (CreateRespon costJSON, _ := json.Marshal(&cost) p := url.Values{ - "cost": {string(costJSON[:])}, + "cost": {string(costJSON)}, } fillSite(&p, site) @@ -4508,7 +4865,10 @@ func (c *Client) CostEdit(id int, cost CostRecord, site ...string) (CreateRespon return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -4519,7 +4879,7 @@ func (c *Client) CostEdit(id int, cost CostRecord, site ...string) (CreateRespon // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // // data, status, err := client.Files(FilesRequest{ // Filter: FilesFilter{ @@ -4528,11 +4888,11 @@ func (c *Client) CostEdit(id int, cost CostRecord, site ...string) (CreateRespon // }) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } func (c *Client) Files(files FilesRequest) (FilesResponse, int, error) { var resp FilesResponse @@ -4545,7 +4905,10 @@ func (c *Client) Files(files FilesRequest) (FilesResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -4556,7 +4919,7 @@ func (c *Client) Files(files FilesRequest) (FilesResponse, int, error) { // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // // file, err := os.Open("file.jpg") // if err != nil { @@ -4581,7 +4944,10 @@ func (c *Client) FileUpload(reader io.Reader) (FileUploadResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -4592,20 +4958,20 @@ func (c *Client) FileUpload(reader io.Reader) (FileUploadResponse, int, error) { // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // // data, status, err := client.File(112) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // if data.Success == true { -// fmt.Printf("%v\n", data.File) +// log.Printf("%v\n", data.File) // } func (c *Client) File(id int) (FileResponse, int, error) { var resp FileResponse @@ -4615,7 +4981,10 @@ func (c *Client) File(id int) (FileResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -4626,7 +4995,7 @@ func (c *Client) File(id int) (FileResponse, int, error) { // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // // data, status, err := client.FileDelete(123) // @@ -4646,7 +5015,10 @@ func (c *Client) FileDelete(id int) (SuccessfulResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -4657,7 +5029,7 @@ func (c *Client) FileDelete(id int) (SuccessfulResponse, int, error) { // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // // fileData, status, err := client.FileDownload(123) // @@ -4684,7 +5056,7 @@ func (c *Client) FileDownload(id int) (io.ReadCloser, int, error) { // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // // data, status, err := client.FileEdit(123, File{Filename: "image2.jpg"}) // @@ -4709,7 +5081,10 @@ func (c *Client) FileEdit(id int, file File) (FileResponse, int, error) { return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -4720,19 +5095,19 @@ func (c *Client) FileEdit(id int, file File) (FileResponse, int, error) { // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.CustomFields(v5.CustomFieldsRequest{ +// data, status, err := client.CustomFields(retailcrm.CustomFieldsRequest{ // Type: "string", // Entity: "customer", // }) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // for _, value := range data.CustomFields { @@ -4749,7 +5124,10 @@ func (c *Client) CustomFields(customFields CustomFieldsRequest) (CustomFieldsRes return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -4760,10 +5138,10 @@ func (c *Client) CustomFields(customFields CustomFieldsRequest) (CustomFieldsRes // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.CustomDictionaries(v5.CustomDictionariesRequest{ -// Filter: v5.CustomDictionariesFilter{ +// data, status, err := client.CustomDictionaries(retailcrm.CustomDictionariesRequest{ +// Filter: retailcrm.CustomDictionariesFilter{ // Name: "Dictionary-1", // }, // }) @@ -4792,7 +5170,10 @@ func (c *Client) CustomDictionaries(customDictionaries CustomDictionariesRequest return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -4803,9 +5184,9 @@ func (c *Client) CustomDictionaries(customDictionaries CustomDictionariesRequest // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.CustomDictionariesCreate(v5.CustomDictionary{ +// data, status, err := client.CustomDictionariesCreate(retailcrm.CustomDictionary{ // Name: "Courier profiles", // Code: "courier-profiles", // Elements: []Element{ @@ -4837,7 +5218,7 @@ func (c *Client) CustomDictionariesCreate(customDictionary CustomDictionary) (Cu costJSON, _ := json.Marshal(&customDictionary) p := url.Values{ - "customDictionary": {string(costJSON[:])}, + "customDictionary": {string(costJSON)}, } data, status, err := c.PostRequest("/custom-fields/dictionaries/create", p) @@ -4846,7 +5227,10 @@ func (c *Client) CustomDictionariesCreate(customDictionary CustomDictionary) (Cu return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -4857,20 +5241,20 @@ func (c *Client) CustomDictionariesCreate(customDictionary CustomDictionary) (Cu // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // // data, status, err := client.CustomDictionary("courier-profiles") // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // If data.Success == true { -// fmt.Printf("%v", data.CustomDictionary.Name) +// log.Printf("%v", data.CustomDictionary.Name) // } func (c *Client) CustomDictionary(code string) (CustomDictionaryResponse, int, error) { var resp CustomDictionaryResponse @@ -4881,7 +5265,10 @@ func (c *Client) CustomDictionary(code string) (CustomDictionaryResponse, int, e return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -4892,9 +5279,9 @@ func (c *Client) CustomDictionary(code string) (CustomDictionaryResponse, int, e // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // -// data, status, err := client.CustomDictionaryEdit(v5.CustomDictionary{ +// data, status, err := client.CustomDictionaryEdit(retailcrm.CustomDictionary{ // Name: "Courier profiles", // Code: "courier-profiles", // Elements: []Element{ @@ -4926,7 +5313,7 @@ func (c *Client) CustomDictionaryEdit(customDictionary CustomDictionary) (Custom costJSON, _ := json.Marshal(&customDictionary) p := url.Values{ - "customDictionary": {string(costJSON[:])}, + "customDictionary": {string(costJSON)}, } data, status, err := c.PostRequest(fmt.Sprintf("/custom-fields/dictionaries/%s/edit", customDictionary.Code), p) @@ -4934,7 +5321,10 @@ func (c *Client) CustomDictionaryEdit(customDictionary CustomDictionary) (Custom return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -4945,7 +5335,7 @@ func (c *Client) CustomDictionaryEdit(customDictionary CustomDictionary) (Custom // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // // data, status, err := client.CustomFieldsCreate(CustomFields{ // Name: "First order", @@ -4956,15 +5346,15 @@ func (c *Client) CustomDictionaryEdit(customDictionary CustomDictionary) (Custom // }) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // If data.Success == true { -// fmt.Printf("%v", data.Code) +// log.Printf("%v", data.Code) // } func (c *Client) CustomFieldsCreate(customFields CustomFields) (CustomResponse, int, error) { var resp CustomResponse @@ -4972,7 +5362,7 @@ func (c *Client) CustomFieldsCreate(customFields CustomFields) (CustomResponse, costJSON, _ := json.Marshal(&customFields) p := url.Values{ - "customField": {string(costJSON[:])}, + "customField": {string(costJSON)}, } data, status, err := c.PostRequest(fmt.Sprintf("/custom-fields/%s/create", customFields.Entity), p) @@ -4981,7 +5371,10 @@ func (c *Client) CustomFieldsCreate(customFields CustomFields) (CustomResponse, return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -4992,20 +5385,20 @@ func (c *Client) CustomFieldsCreate(customFields CustomFields) (CustomResponse, // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // // data, status, err := client.CustomField("order", "first-order") // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // If data.Success == true { -// fmt.Printf("%v", data.CustomField) +// log.Printf("%v", data.CustomField) // } func (c *Client) CustomField(entity, code string) (CustomFieldResponse, int, error) { var resp CustomFieldResponse @@ -5016,7 +5409,10 @@ func (c *Client) CustomField(entity, code string) (CustomFieldResponse, int, err return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } @@ -5027,7 +5423,7 @@ func (c *Client) CustomField(entity, code string) (CustomFieldResponse, int, err // // Example: // -// var client = v5.New("https://demo.url", "09jIJ") +// var client = retailcrm.New("https://demo.url", "09jIJ") // // data, status, err := client.CustomFieldEdit(CustomFields{ // Code: "first-order", @@ -5036,15 +5432,15 @@ func (c *Client) CustomField(entity, code string) (CustomFieldResponse, int, err // }) // // if err != nil { -// fmt.Printf("%v", err.Error()) -// } +// if apiErr, ok := retailcrm.AsAPIError(err); ok { +// log.Fatalf("http status: %d, %s", status, apiErr.String()) +// } // -// if status >= http.StatusBadRequest { -// fmt.Printf("%v", err.ApiError()) +// log.Fatalf("http status: %d, error: %s", status, err) // } // // If data.Success == true { -// fmt.Printf("%v", data.Code) +// log.Printf("%v", data.Code) // } func (c *Client) CustomFieldEdit(customFields CustomFields) (CustomResponse, int, error) { var resp CustomResponse @@ -5052,7 +5448,7 @@ func (c *Client) CustomFieldEdit(customFields CustomFields) (CustomResponse, int costJSON, _ := json.Marshal(&customFields) p := url.Values{ - "customField": {string(costJSON[:])}, + "customField": {string(costJSON)}, } data, status, err := c.PostRequest( @@ -5063,7 +5459,10 @@ func (c *Client) CustomFieldEdit(customFields CustomFields) (CustomResponse, int return resp, status, err } - json.Unmarshal(data, &resp) + err = json.Unmarshal(data, &resp) + if err != nil { + return resp, status, err + } return resp, status, nil } diff --git a/v5/client_test.go b/client_test.go similarity index 98% rename from v5/client_test.go rename to client_test.go index c8687d7..3f102a2 100644 --- a/v5/client_test.go +++ b/client_test.go @@ -1,4 +1,4 @@ -package v5 +package retailcrm import ( "encoding/json" @@ -20,14 +20,12 @@ import ( ) func TestMain(m *testing.M) { - if os.Getenv("DEVELOPER_NODE") == "1" { - err := godotenv.Load("../.env") - if err != nil { - log.Fatal("Error loading .env file") - } - - os.Exit(m.Run()) + err := godotenv.Load(".env") + if err != nil { + log.Fatal("Error loading .env file") } + + os.Exit(m.Run()) } func init() { @@ -494,7 +492,7 @@ func TestClient_CustomersUpload_Fail(t *testing.T) { MatchType("url"). BodyString(p.Encode()). Reply(460). - BodyString(`{"success": false, "errorMsg": "Customers are loaded with errors"}`) + BodyString(`{"success": false, "errorMsg": "Customers are loaded with ErrorsList"}`) data, _, err := c.CustomersUpload(customers) if err == nil { @@ -631,7 +629,7 @@ func TestClient_CustomersFixExternalIds_Fail(t *testing.T) { MatchType("url"). BodyString(p.Encode()). Reply(400). - BodyString(`{"success": false, "errorMsg": "Errors in the input parameters", "errors": {"id": "ID must be an integer"}}`) + BodyString(`{"success": false, "errorMsg": "Errors in the input parameters", "ErrorsList": {"id": "ID must be an integer"}}`) data, _, err := c.CustomersFixExternalIds(customers) if err == nil { @@ -690,7 +688,7 @@ func TestClient_CustomersHistory_Fail(t *testing.T) { Get("/customers/history"). MatchParam("filter[startDate]", "2020-13-12"). Reply(400). - BodyString(`{"success": false, "errorMsg": "Errors in the input parameters", "errors": {"children[startDate]": "Значение недопустимо."}}`) + BodyString(`{"success": false, "errorMsg": "Errors in the input parameters", "ErrorsList": {"children[startDate]": "Значение недопустимо."}}`) data, _, err := c.CustomersHistory(f) if err == nil { @@ -885,7 +883,7 @@ func TestClient_CorporateCustomersFixExternalIds_Fail(t *testing.T) { MatchType("url"). BodyString(p.Encode()). Reply(400). - BodyString(`{"success": false, "errorMsg": "Errors in the input parameters", "errors": {"id": "ID must be an integer"}}`) + BodyString(`{"success": false, "errorMsg": "Errors in the input parameters", "ErrorsList": {"id": "ID must be an integer"}}`) data, _, err := c.CorporateCustomersFixExternalIds(customers) if err == nil { @@ -944,7 +942,7 @@ func TestClient_CorporateCustomersHistory_Fail(t *testing.T) { Get("/customers-corporate/history"). MatchParam("filter[startDate]", "2020-13-12"). Reply(400). - BodyString(`{"success": false, "errorMsg": "Errors in the input parameters", "errors": {"children[startDate]": "Значение недопустимо."}}`) + BodyString(`{"success": false, "errorMsg": "Errors in the input parameters", "ErrorsList": {"children[startDate]": "Значение недопустимо."}}`) data, _, err := c.CorporateCustomersHistory(f) if err == nil { @@ -1130,7 +1128,7 @@ func TestClient_CorporateCustomersUpload_Fail(t *testing.T) { MatchType("url"). BodyString(p.Encode()). Reply(460). - BodyString(`{"success": false, "errorMsg": "Customers are loaded with errors"}`) + BodyString(`{"success": false, "errorMsg": "Customers are loaded with ErrorsList"}`) data, _, err := c.CorporateCustomersUpload(customers) if err == nil { @@ -1703,7 +1701,7 @@ func TestClient_NotesNotes_Fail(t *testing.T) { Get("/customers/notes"). MatchParam("filter[createdAtFrom]", "2020-13-12"). Reply(400). - BodyString(`{"success": false, "errorMsg": "Errors in the input parameters", "errors": {"children[createdAtFrom]": "This value is not valid."}}`) + BodyString(`{"success": false, "errorMsg": "Errors in the input parameters", "ErrorsList": {"children[createdAtFrom]": "This value is not valid."}}`) data, _, err := c.CustomerNotes(NotesRequest{ Filter: NotesFilter{CreatedAtFrom: "2020-13-12"}, @@ -1803,7 +1801,7 @@ func TestClient_NotesCreateDelete_Fail(t *testing.T) { MatchType("url"). BodyString(p.Encode()). Reply(400). - BodyString(`{"success": false, "errorMsg": "Errors in the entity format", "errors": {"customer": "Set one of the following fields: id, externalId"}}`) + BodyString(`{"success": false, "errorMsg": "Errors in the entity format", "ErrorsList": {"customer": "Set one of the following fields: id, externalId"}}`) data, _, err := c.CustomerNoteCreate(note) if err == nil { @@ -1875,7 +1873,7 @@ func TestClient_OrdersOrders_Fail(t *testing.T) { Get("/orders"). MatchParam("filter[attachments]", "7"). Reply(400). - BodyString(`{"success": false, "errorMsg": "Errors in the input parameters", "errors": {"children[attachments]": "SThis value is not valid."}}`) + BodyString(`{"success": false, "errorMsg": "Errors in the input parameters", "ErrorsList": {"children[attachments]": "SThis value is not valid."}}`) data, _, err := c.Orders(OrdersRequest{Filter: OrdersFilter{Attachments: 7}}) if err == nil { @@ -2166,7 +2164,7 @@ func TestClient_OrdersUpload_Fail(t *testing.T) { MatchType("url"). BodyString(p.Encode()). Reply(460). - BodyString(`{"success": false, "errorMsg": "Orders are loaded with errors"}`) + BodyString(`{"success": false, "errorMsg": "Orders are loaded with ErrorsList"}`) data, _, err := c.OrdersUpload(orders) if err == nil { @@ -2395,7 +2393,7 @@ func TestClient_OrdersHistory_Fail(t *testing.T) { Get("/orders/history"). MatchParam("filter[startDate]", "2020-13-12"). Reply(400). - BodyString(`{"success": false, "errorMsg": "Errors in the input parameters", "errors": {"children[startDate]": "Значение недопустимо."}}`) + BodyString(`{"success": false, "errorMsg": "Errors in the input parameters", "ErrorsList": {"children[startDate]": "Значение недопустимо."}}`) data, _, err := c.OrdersHistory(OrdersHistoryRequest{Filter: OrdersHistoryFilter{StartDate: "2020-13-12"}}) if err == nil { @@ -2521,7 +2519,7 @@ func TestClient_PaymentCreateEditDelete_Fail(t *testing.T) { MatchType("url"). BodyString(p.Encode()). Reply(400). - BodyString(`{"success": false, "errorMsg": "Errors in the entity format", "errors": {"order": "Set one of the following fields: id, externalId, number"}}`) + BodyString(`{"success": false, "errorMsg": "Errors in the entity format", "ErrorsList": {"order": "Set one of the following fields: id, externalId, number"}}`) data, _, err := c.OrderPaymentCreate(f) if err == nil { @@ -2743,7 +2741,7 @@ func TestClient_TaskChange_Fail(t *testing.T) { MatchType("url"). BodyString(p.Encode()). Reply(400). - BodyString(`{"success": false, "errorMsg": "Task is not loaded", "errors": {"performerId": "This value should not be blank."}}`) + BodyString(`{"success": false, "errorMsg": "Task is not loaded", "ErrorsList": {"performerId": "This value should not be blank."}}`) data, _, err := c.TaskEdit(f) if err == nil { @@ -2792,7 +2790,7 @@ func TestClient_UsersUsers_Fail(t *testing.T) { MatchParam("filter[active]", "3"). MatchParam("page", "1"). Reply(400). - BodyString(`{"success": false, "errorMsg": "Errors in the input parameters", "errors": {"active": "he value you selected is not a valid choice."}}`) + BodyString(`{"success": false, "errorMsg": "Errors in the input parameters", "ErrorsList": {"active": "he value you selected is not a valid choice."}}`) data, _, err := c.Users(UsersRequest{Filter: UsersFilter{Active: 3}, Page: 1}) if err == nil { @@ -3550,8 +3548,8 @@ func TestClient_Courier(t *testing.T) { cur := Courier{ Active: true, Email: fmt.Sprintf("%s@example.com", RandomString(5)), - FirstName: fmt.Sprintf("%s", RandomString(5)), - LastName: fmt.Sprintf("%s", RandomString(5)), + FirstName: RandomString(5), + LastName: RandomString(5), } defer gock.Off() @@ -3583,7 +3581,7 @@ func TestClient_Courier(t *testing.T) { } cur.ID = data.ID - cur.Patronymic = fmt.Sprintf("%s", RandomString(5)) + cur.Patronymic = RandomString(5) jr, _ = json.Marshal(&cur) @@ -3629,7 +3627,7 @@ func TestClient_Courier_Fail(t *testing.T) { MatchType("url"). BodyString(p.Encode()). Reply(400). - BodyString(`{"success": false, "errorMsg": "Errors in the entity format", "errors": {"firstName": "Specify the first name"}}`) + BodyString(`{"success": false, "errorMsg": "Errors in the entity format", "ErrorsList": {"firstName": "Specify the first name"}}`) data, st, err := c.CourierCreate(Courier{}) if err == nil { @@ -3644,7 +3642,7 @@ func TestClient_Courier_Fail(t *testing.T) { t.Error(successFail) } - cur := Courier{Patronymic: fmt.Sprintf("%s", RandomString(5))} + cur := Courier{Patronymic: RandomString(5)} jr, _ = json.Marshal(&cur) p = url.Values{ @@ -5793,7 +5791,7 @@ func TestClient_CostsUpload_Fail(t *testing.T) { MatchType("url"). BodyString(p.Encode()). Reply(460). - BodyString(`{"success": false, "errorMsg": "Costs are loaded with errors"}`) + BodyString(`{"success": false, "errorMsg": "Costs are loaded with ErrorsList"}`) data, _, err := c.CostsUpload(costsUpload) if err == nil { diff --git a/error.go b/error.go new file mode 100644 index 0000000..01e946e --- /dev/null +++ b/error.go @@ -0,0 +1,192 @@ +package retailcrm + +import ( + "encoding/json" + "fmt" + "regexp" + "strings" +) + +var missingParameterMatcher = regexp.MustCompile(`^Parameter \'([\w\]\[\_\-]+)\' is missing$`) +var ( + // ErrMissingCredentials will be returned if no API key was provided to the API. + ErrMissingCredentials = NewAPIError(`apiKey is missing`) + // ErrInvalidCredentials will be returned if provided API key is invalid. + ErrInvalidCredentials = NewAPIError(`wrong "apiKey" value`) + // ErrAccessDenied will be returned in case of "Access denied" error. + ErrAccessDenied = NewAPIError("access denied") + // ErrAccountDoesNotExist will be returned if target system does not exist. + ErrAccountDoesNotExist = NewAPIError("account does not exist") + // ErrValidation will be returned in case of validation errors. + ErrValidation = NewAPIError("validation error") + // ErrMissingParameter will be returned if parameter is missing. + // Underlying error messages list will contain parameter name in the "Name" key. + ErrMissingParameter = NewAPIError("missing parameter") + // ErrGeneric will be returned if error cannot be classified as one of the errors above. + ErrGeneric = NewAPIError("API error") +) + +// APIErrorsList struct. +type APIErrorsList map[string]string + +// APIError returns when an API error was occurred. +type APIError interface { + error + fmt.Stringer + withWrapped(error) APIError + withErrors(APIErrorsList) APIError + Unwrap() error + Errors() APIErrorsList +} + +type apiError struct { + ErrorMsg string `json:"errorMsg,omitempty"` + ErrorsList APIErrorsList `json:"errors,omitempty"` + wrapped error +} + +// CreateAPIError from the provided response data. Different error types will be returned depending on the response, +// all of them can be matched using errors.Is. APi errors will always implement APIError interface. +func CreateAPIError(dataResponse []byte) error { + a := &apiError{} + + if len(dataResponse) > 0 && dataResponse[0] == '<' { + return ErrAccountDoesNotExist + } + + if err := json.Unmarshal(dataResponse, &a); err != nil { + return err + } + + var found APIError + switch a.ErrorMsg { + case `"apiKey" is missing.`: + found = ErrMissingCredentials + case `Wrong "apiKey" value.`: + found = ErrInvalidCredentials + case "Access denied.": + found = ErrAccessDenied + case "Account does not exist.": + found = ErrAccountDoesNotExist + case "Errors in the entity format": + fallthrough + case "Validation error": + found = ErrValidation + default: + if param, ok := asMissingParameterErr(a.ErrorMsg); ok { + return a.withWrapped(ErrMissingParameter).withErrors(APIErrorsList{"Name": param}) + } + found = ErrGeneric + } + + result := NewAPIError(a.ErrorMsg).withWrapped(found) + if len(a.ErrorsList) > 0 { + return result.withErrors(a.ErrorsList) + } + + return result +} + +// CreateGenericAPIError for the situations when API response cannot be processed, but response was actually received. +func CreateGenericAPIError(message string) APIError { + return NewAPIError(message).withWrapped(ErrGeneric) +} + +// NewAPIError returns API error with the provided message. +func NewAPIError(message string) APIError { + return &apiError{ErrorMsg: message} +} + +// AsAPIError returns APIError and true if provided error is an APIError or contains wrapped APIError. +// Returns (nil, false) otherwise. +func AsAPIError(err error) (APIError, bool) { + apiErr := unwrapAPIError(err) + return apiErr, apiErr != nil +} + +func unwrapAPIError(err error) APIError { + if err == nil { + return nil + } + + if apiErr, ok := err.(APIError); ok { // nolint:errorlint + return apiErr + } + + wrapper, ok := err.(interface { // nolint:errorlint + Unwrap() error + }) + if ok { + return unwrapAPIError(wrapper.Unwrap()) + } + + return nil +} + +// asMissingParameterErr returns true if "Parameter 'name' is missing" error message is provided. +func asMissingParameterErr(message string) (string, bool) { + matches := missingParameterMatcher.FindAllStringSubmatch(message, -1) + if len(matches) == 1 && len(matches[0]) == 2 { + return matches[0][1], true + } + return "", false +} + +// Error returns errorMsg field from the response. +func (e *apiError) Error() string { + return e.ErrorMsg +} + +// Unwrap returns wrapped error. It is usually one of the predefined types like ErrGeneric or ErrValidation. +// It can be used directly, but it's main purpose is to make errors matchable via errors.Is call. +func (e *apiError) Unwrap() error { + return e.wrapped +} + +// Errors returns errors field from the response. +func (e *apiError) Errors() APIErrorsList { + return e.ErrorsList +} + +// String returns string representation of an APIError. +func (e *apiError) String() string { + var sb strings.Builder + sb.Grow(256) // nolint:gomnd + sb.WriteString(fmt.Sprintf(`errorMsg: "%s"`, e.Error())) + + if len(e.Errors()) > 0 { + i := 0 + useIndex := true + errorList := make([]string, len(e.Errors())) + + for index, errText := range e.Errors() { + if i == 0 && index == "0" { + useIndex = false + } + + if useIndex { + errorList[i] = fmt.Sprintf(`%s: "%s"`, index, errText) + } else { + errorList[i] = errText + } + + i++ + } + + sb.WriteString(", errors: [" + strings.Join(errorList, ", ") + "]") + } + + return sb.String() +} + +// withWrapped is a wrapped setter. +func (e *apiError) withWrapped(err error) APIError { + e.wrapped = err + return e +} + +// withErrors is an ErrorsList setter. +func (e *apiError) withErrors(m APIErrorsList) APIError { + e.ErrorsList = m + return e +} diff --git a/error_test.go b/error_test.go new file mode 100644 index 0000000..c860f27 --- /dev/null +++ b/error_test.go @@ -0,0 +1,171 @@ +package retailcrm + +import ( + "testing" + + "github.com/stretchr/testify/suite" +) + +type ErrorTest struct { + suite.Suite +} + +func TestError(t *testing.T) { + suite.Run(t, new(ErrorTest)) +} + +func (t *ErrorTest) TestFailure_ApiErrorsSlice() { + b := []byte(`{"success": false, + "errorMsg": "Failed to activate module", + "errors": [ + "Your account has insufficient funds to activate integration module", + "Test error" + ]}`) + expected := APIErrorsList{ + "0": "Your account has insufficient funds to activate integration module", + "1": "Test error", + } + + e := CreateAPIError(b) + apiErr, ok := AsAPIError(e) + + t.Require().ErrorIs(e, ErrGeneric) + t.Require().NotNil(apiErr) + t.Require().True(ok) + t.Assert().Equal(expected, apiErr.Errors()) +} + +func (t *ErrorTest) TestFailure_ApiErrorsMap() { + b := []byte(`{"success": false, + "errorMsg": "Failed to activate module", + "errors": {"id": "ID must be an integer", "test": "Test error"}}`, + ) + expected := APIErrorsList{ + "id": "ID must be an integer", + "test": "Test error", + } + + e := CreateAPIError(b) + apiErr, ok := AsAPIError(e) + + t.Require().ErrorIs(e, ErrGeneric) + t.Require().NotNil(apiErr) + t.Require().True(ok) + t.Assert().Equal(expected, apiErr.Errors()) +} + +func (t *ErrorTest) TestFailure_APIKeyMissing() { + b := []byte(`{"success": false, + "errorMsg": "\"apiKey\" is missing."}`, + ) + + e := CreateAPIError(b) + apiErr, ok := AsAPIError(e) + + t.Require().NotNil(apiErr) + t.Require().True(ok) + t.Require().ErrorIs(e, ErrMissingCredentials) +} + +func (t *ErrorTest) TestFailure_APIKeyWrong() { + b := []byte(`{"success": false, + "errorMsg": "Wrong \"apiKey\" value."}`, + ) + + e := CreateAPIError(b) + apiErr, ok := AsAPIError(e) + + t.Require().NotNil(apiErr) + t.Require().True(ok) + t.Require().ErrorIs(e, ErrInvalidCredentials) +} + +func (t *ErrorTest) TestFailure_AccessDenied() { + b := []byte(`{"success": false, + "errorMsg": "Access denied."}`, + ) + + e := CreateAPIError(b) + apiErr, ok := AsAPIError(e) + + t.Require().NotNil(apiErr) + t.Require().True(ok) + t.Require().ErrorIs(e, ErrAccessDenied) +} + +func (t *ErrorTest) TestFailure_AccountDoesNotExist() { + b := []byte(`{"success": false, + "errorMsg": "Account does not exist."}`, + ) + + e := CreateAPIError(b) + apiErr, ok := AsAPIError(e) + + t.Require().NotNil(apiErr) + t.Require().True(ok) + t.Require().ErrorIs(e, ErrAccountDoesNotExist) +} + +func (t *ErrorTest) TestFailure_Validation() { + b := []byte(`{"success": false, + "errorMsg": "Errors in the entity format", + "errors": {"name": "name must be provided"}}`, + ) + + e := CreateAPIError(b) + apiErr, ok := AsAPIError(e) + + t.Require().NotNil(apiErr) + t.Require().True(ok) + t.Require().ErrorIs(e, ErrValidation) + t.Assert().Equal("name must be provided", apiErr.Errors()["name"]) +} + +func (t *ErrorTest) TestFailure_Validation2() { + b := []byte(`{"success": false, + "errorMsg": "Validation error", + "errors": {"name": "name must be provided"}}`, + ) + + e := CreateAPIError(b) + apiErr, ok := AsAPIError(e) + + t.Require().NotNil(apiErr) + t.Require().True(ok) + t.Require().ErrorIs(e, ErrValidation) + t.Assert().Equal("name must be provided", apiErr.Errors()["name"]) + t.Assert().Equal("errorMsg: \"Validation error\", errors: [name: \"name must be provided\"]", apiErr.String()) +} + +func (t *ErrorTest) TestFailure_MissingParameter() { + b := []byte(`{"success": false, + "errorMsg": "Parameter 'item' is missing"}`, + ) + + e := CreateAPIError(b) + apiErr, ok := AsAPIError(e) + + t.Require().NotNil(apiErr) + t.Require().True(ok) + t.Require().ErrorIs(e, ErrMissingParameter) + t.Assert().Equal("item", apiErr.Errors()["Name"]) +} + +func (t *ErrorTest) Test_CreateGenericAPIError() { + e := CreateGenericAPIError("generic error message") + apiErr, ok := AsAPIError(e) + + t.Require().NotNil(apiErr) + t.Require().True(ok) + t.Assert().ErrorIs(apiErr, ErrGeneric) + t.Assert().Equal("generic error message", e.Error()) +} + +func (t *ErrorTest) TestFailure_HTML() { + e := CreateAPIError([]byte{'<'}) + apiErr, ok := AsAPIError(e) + + t.Require().NotNil(apiErr) + t.Require().True(ok) + t.Assert().ErrorIs(apiErr, ErrAccountDoesNotExist) +} diff --git a/v5/filters.go b/filters.go similarity index 99% rename from v5/filters.go rename to filters.go index 1956ac8..b393f9f 100644 --- a/v5/filters.go +++ b/filters.go @@ -1,4 +1,4 @@ -package v5 +package retailcrm // CustomersFilter type. type CustomersFilter struct { diff --git a/go.mod b/go.mod index 5b744cd..2d1f311 100644 --- a/go.mod +++ b/go.mod @@ -1,12 +1,10 @@ -module github.com/retailcrm/api-client-go +module github.com/retailcrm/api-client-go/v2 go 1.13 require ( github.com/google/go-querystring v1.1.0 github.com/joho/godotenv v1.3.0 - golang.org/x/net v0.0.0-20191021144547-ec77196f6094 // indirect - golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 - gopkg.in/h2non/gentleman.v1 v1.0.4 // indirect + github.com/stretchr/testify v1.7.0 gopkg.in/h2non/gock.v1 v1.1.2 ) diff --git a/go.sum b/go.sum index 96ce52e..0fc530c 100644 --- a/go.sum +++ b/go.sum @@ -1,3 +1,5 @@ +github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/google/go-cmp v0.5.2 h1:X2ev0eStA3AbceY54o37/0PQ/UWqKEiiO2dKL5OPaFM= github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8= @@ -8,14 +10,16 @@ github.com/joho/godotenv v1.3.0 h1:Zjp+RcGpHhGlrMbJzXTrZZPrWj+1vfm90La1wgB6Bhc= github.com/joho/godotenv v1.3.0/go.mod h1:7hK45KPybAkOC6peb+G5yklZfMxEjkZhHbwpqxOKXbg= github.com/nbio/st v0.0.0-20140626010706-e9e8d9816f32 h1:W6apQkHrMkS0Muv8G/TipAy/FJl/rCYT0+EuS8+Z0z4= github.com/nbio/st v0.0.0-20140626010706-e9e8d9816f32/go.mod h1:9wM+0iRr9ahx58uYLpLIr5fm8diHn0JbqRycJi6w0Ms= -golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/net v0.0.0-20191021144547-ec77196f6094/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -gopkg.in/h2non/gentleman.v1 v1.0.4/go.mod h1:JYuHVdFzS4MKOXe0o+chKJ4hCe6tqKKw9XH9YP6WFrg= -gopkg.in/h2non/gock.v1 v1.0.16 h1:F11k+OafeuFENsjei5t2vMTSTs9L62AdyTe4E1cgdG8= -gopkg.in/h2non/gock.v1 v1.0.16/go.mod h1:XVuDAssexPLwgxCLMvDTWNU5eqklsydR6I5phZ9oPB8= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/h2non/gock.v1 v1.1.2 h1:jBbHXgGBK/AoPVfJh5x4r/WxIrElvbLel8TCZkkZJoY= gopkg.in/h2non/gock.v1 v1.1.2/go.mod h1:n7UGz/ckNChHiK05rDoiC4MYSunEC/lyaUm2WWaDva0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/log.go b/log.go new file mode 100644 index 0000000..9ec3dff --- /dev/null +++ b/log.go @@ -0,0 +1,25 @@ +package retailcrm + +// BasicLogger provides basic functionality for logging. +type BasicLogger interface { + Printf(string, ...interface{}) +} + +// DebugLogger can be used to easily wrap any logger with Debugf method into the BasicLogger instance. +type DebugLogger interface { + Debugf(string, ...interface{}) +} + +type debugLoggerAdapter struct { + logger DebugLogger +} + +// DebugLoggerAdapter returns BasicLogger that calls underlying DebugLogger.Debugf. +func DebugLoggerAdapter(logger DebugLogger) BasicLogger { + return &debugLoggerAdapter{logger: logger} +} + +// Printf data in the log using DebugLogger.Debugf. +func (l *debugLoggerAdapter) Printf(format string, v ...interface{}) { + l.logger.Debugf(format, v...) +} diff --git a/log_test.go b/log_test.go new file mode 100644 index 0000000..8697dc9 --- /dev/null +++ b/log_test.go @@ -0,0 +1,24 @@ +package retailcrm + +import ( + "fmt" + "testing" + + "github.com/stretchr/testify/assert" +) + +type wrappedLogger struct { + lastMessage string +} + +func (w *wrappedLogger) Debugf(msg string, v ...interface{}) { + w.lastMessage = fmt.Sprintf(msg, v...) +} + +func TestDebugLoggerAdapter_Printf(t *testing.T) { + wrapped := &wrappedLogger{} + logger := DebugLoggerAdapter(wrapped) + logger.Printf("Test message #%d", 1) + + assert.Equal(t, "Test message #1", wrapped.lastMessage) +} diff --git a/marshaling.go b/marshaling.go new file mode 100644 index 0000000..06841e2 --- /dev/null +++ b/marshaling.go @@ -0,0 +1,102 @@ +package retailcrm + +import ( + "encoding/json" + "fmt" + "strconv" +) + +func (t Tag) MarshalJSON() ([]byte, error) { + return json.Marshal(t.Name) +} + +func (a *APIErrorsList) UnmarshalJSON(data []byte) error { + var i interface{} + var m APIErrorsList + if err := json.Unmarshal(data, &i); err != nil { + return err + } + + switch e := i.(type) { + case map[string]interface{}: + m = make(APIErrorsList, len(e)) + for idx, val := range e { + m[idx] = fmt.Sprint(val) + } + case []interface{}: + m = make(APIErrorsList, len(e)) + for idx, val := range e { + m[strconv.Itoa(idx)] = fmt.Sprint(val) + } + } + + *a = m + return nil +} + +func (l *CustomFieldsList) UnmarshalJSON(data []byte) error { + var i interface{} + var m CustomFieldsList + if err := json.Unmarshal(data, &i); err != nil { + return err + } + + switch e := i.(type) { + case map[string]interface{}: + m = make(CustomFieldsList, len(e)) + for idx, val := range e { + m[idx] = fmt.Sprint(val) + } + case []interface{}: + m = make(CustomFieldsList, len(e)) + for idx, val := range e { + m[strconv.Itoa(idx)] = fmt.Sprint(val) + } + } + + *l = m + return nil +} + +func (p *OrderPayments) UnmarshalJSON(data []byte) error { + var i interface{} + var m OrderPayments + if err := json.Unmarshal(data, &i); err != nil { + return err + } + + switch e := i.(type) { + case map[string]interface{}: + m = make(OrderPayments, len(e)) + for idx, val := range e { + var res OrderPayment + err := unmarshalMap(val.(map[string]interface{}), &res) + if err != nil { + return err + } + m[idx] = res + } + case []interface{}: + m = make(OrderPayments, len(e)) + for idx, val := range e { + var res OrderPayment + err := unmarshalMap(val.(map[string]interface{}), &res) + if err != nil { + return err + } + m[strconv.Itoa(idx)] = res + } + } + + *p = m + return nil +} + +func unmarshalMap(m map[string]interface{}, v interface{}) (err error) { + var data []byte + data, err = json.Marshal(m) + if err != nil { + return err + } + return json.Unmarshal(data, v) +} diff --git a/marshaling_test.go b/marshaling_test.go new file mode 100644 index 0000000..256236e --- /dev/null +++ b/marshaling_test.go @@ -0,0 +1,69 @@ +package retailcrm + +import ( + "encoding/json" + "reflect" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestTag_MarshalJSON(t *testing.T) { + tags := []Tag{ + {"first", "#3e89b6", false}, + {"second", "#ffa654", false}, + } + names := []byte(`["first","second"]`) + str, err := json.Marshal(tags) + + if err != nil { + t.Errorf("%v", err.Error()) + } + + if !reflect.DeepEqual(str, names) { + t.Errorf("Marshaled: %#v\nExpected: %#v\n", str, names) + } +} + +func TestAPIErrorsList_UnmarshalJSON(t *testing.T) { + var list APIErrorsList + + require.NoError(t, json.Unmarshal([]byte(`["first", "second"]`), &list)) + assert.Len(t, list, 2) + assert.Equal(t, list["0"], "first") + assert.Equal(t, list["1"], "second") + + require.NoError(t, json.Unmarshal([]byte(`{"a": "first", "b": "second"}`), &list)) + assert.Len(t, list, 2) + assert.Equal(t, list["a"], "first") + assert.Equal(t, list["b"], "second") +} + +func TestCustomFieldsList_UnmarshalJSON(t *testing.T) { + var list CustomFieldsList + + require.NoError(t, json.Unmarshal([]byte(`["first", "second"]`), &list)) + assert.Len(t, list, 2) + assert.Equal(t, list["0"], "first") + assert.Equal(t, list["1"], "second") + + require.NoError(t, json.Unmarshal([]byte(`{"a": "first", "b": "second"}`), &list)) + assert.Len(t, list, 2) + assert.Equal(t, list["a"], "first") + assert.Equal(t, list["b"], "second") +} + +func TestOrderPayments_UnmarshalJSON(t *testing.T) { + var list OrderPayments + + require.NoError(t, json.Unmarshal([]byte(`[{"id": 1}, {"id": 2}]`), &list)) + assert.Len(t, list, 2) + assert.Equal(t, list["0"], OrderPayment{ID: 1}) + assert.Equal(t, list["1"], OrderPayment{ID: 2}) + + require.NoError(t, json.Unmarshal([]byte(`{"a": {"id": 1}, "b": {"id": 2}}`), &list)) + assert.Len(t, list, 2) + assert.Equal(t, list["a"], OrderPayment{ID: 1}) + assert.Equal(t, list["b"], OrderPayment{ID: 2}) +} diff --git a/v5/request.go b/request.go similarity index 97% rename from v5/request.go rename to request.go index 8899845..d0616fe 100644 --- a/v5/request.go +++ b/request.go @@ -1,4 +1,4 @@ -package v5 +package retailcrm // CustomerRequest type. type CustomerRequest struct { @@ -177,8 +177,8 @@ type ProductsPropertiesRequest struct { type DeliveryTrackingRequest struct { DeliveryID string `json:"deliveryId,omitempty"` TrackNumber string `json:"trackNumber,omitempty"` - History []DeliveryHistoryRecord `json:"history,omitempty,brackets"` - ExtraData map[string]string `json:"extraData,omitempty,brackets"` + History []DeliveryHistoryRecord `json:"history,omitempty"` + ExtraData map[string]string `json:"extraData,omitempty"` } // DeliveryShipmentsRequest type. diff --git a/v5/response.go b/response.go similarity index 98% rename from v5/response.go rename to response.go index 3dde1ea..5b753c9 100644 --- a/v5/response.go +++ b/response.go @@ -1,4 +1,4 @@ -package v5 +package retailcrm // SuccessfulResponse type. type SuccessfulResponse struct { @@ -20,7 +20,7 @@ type OrderCreateResponse struct { // OperationResponse type. type OperationResponse struct { Success bool `json:"success"` - Errors map[string]string `json:"errors,omitempty"` + Errors map[string]string `json:"ErrorsList,omitempty"` } // VersionResponse return available API versions. @@ -31,7 +31,7 @@ type VersionResponse struct { // CredentialResponse return available API methods. type CredentialResponse struct { - Success bool `json:"success,omitempty"` + Success bool `json:"success,omitempty"` // deprecated Credentials []string `json:"credentials,omitempty"` Scopes []string `json:"scopes,omitempty"` @@ -409,7 +409,7 @@ type ResponseInfo struct { // MgInfo type. type MgInfo struct { - EndpointUrl string `json:"endpointUrl"` + EndpointURL string `json:"endpointUrl"` Token string `json:"token"` } diff --git a/v5/types.go b/types.go similarity index 83% rename from v5/types.go rename to types.go index bbeae59..ca9b2b4 100644 --- a/v5/types.go +++ b/types.go @@ -1,4 +1,4 @@ -package v5 +package retailcrm import ( "encoding/json" @@ -19,6 +19,7 @@ type Client struct { Key string Debug bool httpClient *http.Client + logger BasicLogger } // Pagination type. @@ -121,41 +122,41 @@ Customer related types // Customer type. type Customer struct { - ID int `json:"id,omitempty"` - ExternalID string `json:"externalId,omitempty"` - FirstName string `json:"firstName,omitempty"` - LastName string `json:"lastName,omitempty"` - Patronymic string `json:"patronymic,omitempty"` - Sex string `json:"sex,omitempty"` - Email string `json:"email,omitempty"` - Phones []Phone `json:"phones,omitempty"` - Address *Address `json:"address,omitempty"` - CreatedAt string `json:"createdAt,omitempty"` - Birthday string `json:"birthday,omitempty"` - ManagerID int `json:"managerId,omitempty"` - Vip bool `json:"vip,omitempty"` - Bad bool `json:"bad,omitempty"` - Site string `json:"site,omitempty"` - Source *Source `json:"source,omitempty"` - Contragent *Contragent `json:"contragent,omitempty"` - PersonalDiscount float32 `json:"personalDiscount,omitempty"` - CumulativeDiscount float32 `json:"cumulativeDiscount,omitempty"` - DiscountCardNumber string `json:"discountCardNumber,omitempty"` - EmailMarketingUnsubscribedAt string `json:"emailMarketingUnsubscribedAt,omitempty"` - AvgMarginSumm float32 `json:"avgMarginSumm,omitempty"` - MarginSumm float32 `json:"marginSumm,omitempty"` - TotalSumm float32 `json:"totalSumm,omitempty"` - AverageSumm float32 `json:"averageSumm,omitempty"` - OrdersCount int `json:"ordersCount,omitempty"` - CostSumm float32 `json:"costSumm,omitempty"` - MaturationTime int `json:"maturationTime,omitempty"` - FirstClientID string `json:"firstClientId,omitempty"` - LastClientID string `json:"lastClientId,omitempty"` - BrowserID string `json:"browserId,omitempty"` - MgCustomerID string `json:"mgCustomerId,omitempty"` - PhotoURL string `json:"photoUrl,omitempty"` - CustomFields map[string]string `json:"customFields,omitempty"` - Tags []Tag `json:"tags,omitempty"` + ID int `json:"id,omitempty"` + ExternalID string `json:"externalId,omitempty"` + FirstName string `json:"firstName,omitempty"` + LastName string `json:"lastName,omitempty"` + Patronymic string `json:"patronymic,omitempty"` + Sex string `json:"sex,omitempty"` + Email string `json:"email,omitempty"` + Phones []Phone `json:"phones,omitempty"` + Address *Address `json:"address,omitempty"` + CreatedAt string `json:"createdAt,omitempty"` + Birthday string `json:"birthday,omitempty"` + ManagerID int `json:"managerId,omitempty"` + Vip bool `json:"vip,omitempty"` + Bad bool `json:"bad,omitempty"` + Site string `json:"site,omitempty"` + Source *Source `json:"source,omitempty"` + Contragent *Contragent `json:"contragent,omitempty"` + PersonalDiscount float32 `json:"personalDiscount,omitempty"` + CumulativeDiscount float32 `json:"cumulativeDiscount,omitempty"` + DiscountCardNumber string `json:"discountCardNumber,omitempty"` + EmailMarketingUnsubscribedAt string `json:"emailMarketingUnsubscribedAt,omitempty"` + AvgMarginSumm float32 `json:"avgMarginSumm,omitempty"` + MarginSumm float32 `json:"marginSumm,omitempty"` + TotalSumm float32 `json:"totalSumm,omitempty"` + AverageSumm float32 `json:"averageSumm,omitempty"` + OrdersCount int `json:"ordersCount,omitempty"` + CostSumm float32 `json:"costSumm,omitempty"` + MaturationTime int `json:"maturationTime,omitempty"` + FirstClientID string `json:"firstClientId,omitempty"` + LastClientID string `json:"lastClientId,omitempty"` + BrowserID string `json:"browserId,omitempty"` + MgCustomerID string `json:"mgCustomerId,omitempty"` + PhotoURL string `json:"photoUrl,omitempty"` + CustomFields CustomFieldsList `json:"customFields,omitempty"` + Tags []Tag `json:"tags,omitempty"` } // CorporateCustomer type. @@ -166,7 +167,7 @@ type CorporateCustomer struct { CreatedAt string `json:"createdAt,omitempty"` Vip bool `json:"vip,omitempty"` Bad bool `json:"bad,omitempty"` - CustomFields map[string]string `json:"customFields,omitempty"` + CustomFields CustomFieldsList `json:"customFields,omitempty"` PersonalDiscount float32 `json:"personalDiscount,omitempty"` DiscountCardNumber string `json:"discountCardNumber,omitempty"` ManagerID int `json:"managerId,omitempty"` @@ -217,17 +218,17 @@ type CorporateCustomerContactCustomer struct { } type Company struct { - ID int `json:"id,omitempty"` - IsMain bool `json:"isMain,omitempty"` - ExternalID string `json:"externalId,omitempty"` - Active bool `json:"active,omitempty"` - Name string `json:"name,omitempty"` - Brand string `json:"brand,omitempty"` - Site string `json:"site,omitempty"` - CreatedAt string `json:"createdAt,omitempty"` - Contragent *Contragent `json:"contragent,omitempty"` - Address *IdentifiersPair `json:"address,omitempty"` - CustomFields map[string]string `json:"customFields,omitempty"` + ID int `json:"id,omitempty"` + IsMain bool `json:"isMain,omitempty"` + ExternalID string `json:"externalId,omitempty"` + Active bool `json:"active,omitempty"` + Name string `json:"name,omitempty"` + Brand string `json:"brand,omitempty"` + Site string `json:"site,omitempty"` + CreatedAt string `json:"createdAt,omitempty"` + Contragent *Contragent `json:"contragent,omitempty"` + Address *IdentifiersPair `json:"address,omitempty"` + CustomFields CustomFieldsList `json:"customFields,omitempty"` } // CorporateCustomerNote type. @@ -272,57 +273,60 @@ type CorporateCustomerHistoryRecord struct { Order related types */ +type OrderPayments map[string]OrderPayment +type CustomFieldsList map[string]string + // Order type. type Order struct { - ID int `json:"id,omitempty"` - ExternalID string `json:"externalId,omitempty"` - Number string `json:"number,omitempty"` - FirstName string `json:"firstName,omitempty"` - LastName string `json:"lastName,omitempty"` - Patronymic string `json:"patronymic,omitempty"` - Email string `json:"email,omitempty"` - Phone string `json:"phone,omitempty"` - AdditionalPhone string `json:"additionalPhone,omitempty"` - CreatedAt string `json:"createdAt,omitempty"` - StatusUpdatedAt string `json:"statusUpdatedAt,omitempty"` - ManagerID int `json:"managerId,omitempty"` - Mark int `json:"mark,omitempty"` - Call bool `json:"call,omitempty"` - Expired bool `json:"expired,omitempty"` - FromAPI bool `json:"fromApi,omitempty"` - MarkDatetime string `json:"markDatetime,omitempty"` - CustomerComment string `json:"customerComment,omitempty"` - ManagerComment string `json:"managerComment,omitempty"` - Status string `json:"status,omitempty"` - StatusComment string `json:"statusComment,omitempty"` - FullPaidAt string `json:"fullPaidAt,omitempty"` - Site string `json:"site,omitempty"` - OrderType string `json:"orderType,omitempty"` - OrderMethod string `json:"orderMethod,omitempty"` - CountryIso string `json:"countryIso,omitempty"` - Summ float32 `json:"summ,omitempty"` - TotalSumm float32 `json:"totalSumm,omitempty"` - PrepaySum float32 `json:"prepaySum,omitempty"` - PurchaseSumm float32 `json:"purchaseSumm,omitempty"` - DiscountManualAmount float32 `json:"discountManualAmount,omitempty"` - DiscountManualPercent float32 `json:"discountManualPercent,omitempty"` - Weight float32 `json:"weight,omitempty"` - Length int `json:"length,omitempty"` - Width int `json:"width,omitempty"` - Height int `json:"height,omitempty"` - ShipmentStore string `json:"shipmentStore,omitempty"` - ShipmentDate string `json:"shipmentDate,omitempty"` - ClientID string `json:"clientId,omitempty"` - Shipped bool `json:"shipped,omitempty"` - UploadedToExternalStoreSystem bool `json:"uploadedToExternalStoreSystem,omitempty"` - Source *Source `json:"source,omitempty"` - Contragent *Contragent `json:"contragent,omitempty"` - Customer *Customer `json:"customer,omitempty"` - Delivery *OrderDelivery `json:"delivery,omitempty"` - Marketplace *OrderMarketplace `json:"marketplace,omitempty"` - Items []OrderItem `json:"items,omitempty"` - CustomFields map[string]string `json:"customFields,omitempty"` - Payments map[string]OrderPayment `json:"payments,omitempty"` + ID int `json:"id,omitempty"` + ExternalID string `json:"externalId,omitempty"` + Number string `json:"number,omitempty"` + FirstName string `json:"firstName,omitempty"` + LastName string `json:"lastName,omitempty"` + Patronymic string `json:"patronymic,omitempty"` + Email string `json:"email,omitempty"` + Phone string `json:"phone,omitempty"` + AdditionalPhone string `json:"additionalPhone,omitempty"` + CreatedAt string `json:"createdAt,omitempty"` + StatusUpdatedAt string `json:"statusUpdatedAt,omitempty"` + ManagerID int `json:"managerId,omitempty"` + Mark int `json:"mark,omitempty"` + Call bool `json:"call,omitempty"` + Expired bool `json:"expired,omitempty"` + FromAPI bool `json:"fromApi,omitempty"` + MarkDatetime string `json:"markDatetime,omitempty"` + CustomerComment string `json:"customerComment,omitempty"` + ManagerComment string `json:"managerComment,omitempty"` + Status string `json:"status,omitempty"` + StatusComment string `json:"statusComment,omitempty"` + FullPaidAt string `json:"fullPaidAt,omitempty"` + Site string `json:"site,omitempty"` + OrderType string `json:"orderType,omitempty"` + OrderMethod string `json:"orderMethod,omitempty"` + CountryIso string `json:"countryIso,omitempty"` + Summ float32 `json:"summ,omitempty"` + TotalSumm float32 `json:"totalSumm,omitempty"` + PrepaySum float32 `json:"prepaySum,omitempty"` + PurchaseSumm float32 `json:"purchaseSumm,omitempty"` + DiscountManualAmount float32 `json:"discountManualAmount,omitempty"` + DiscountManualPercent float32 `json:"discountManualPercent,omitempty"` + Weight float32 `json:"weight,omitempty"` + Length int `json:"length,omitempty"` + Width int `json:"width,omitempty"` + Height int `json:"height,omitempty"` + ShipmentStore string `json:"shipmentStore,omitempty"` + ShipmentDate string `json:"shipmentDate,omitempty"` + ClientID string `json:"clientId,omitempty"` + Shipped bool `json:"shipped,omitempty"` + UploadedToExternalStoreSystem bool `json:"uploadedToExternalStoreSystem,omitempty"` + Source *Source `json:"source,omitempty"` + Contragent *Contragent `json:"contragent,omitempty"` + Customer *Customer `json:"customer,omitempty"` + Delivery *OrderDelivery `json:"delivery,omitempty"` + Marketplace *OrderMarketplace `json:"marketplace,omitempty"` + Items []OrderItem `json:"items,omitempty"` + CustomFields CustomFieldsList `json:"customFields,omitempty"` + Payments OrderPayments `json:"payments,omitempty"` } // OrdersStatus type. @@ -378,8 +382,14 @@ type OrderDeliveryData struct { // UnmarshalJSON method. func (v *OrderDeliveryData) UnmarshalJSON(b []byte) error { var additionalData map[string]interface{} - json.Unmarshal(b, &additionalData) - json.Unmarshal(b, &v.OrderDeliveryDataBasic) + err := json.Unmarshal(b, &additionalData) + if err != nil { + return err + } + err = json.Unmarshal(b, &v.OrderDeliveryDataBasic) + if err != nil { + return err + } object := reflect.TypeOf(v.OrderDeliveryDataBasic) for i := 0; i < object.NumField(); i++ { @@ -401,7 +411,10 @@ func (v *OrderDeliveryData) UnmarshalJSON(b []byte) error { func (v OrderDeliveryData) MarshalJSON() ([]byte, error) { result := map[string]interface{}{} data, _ := json.Marshal(v.OrderDeliveryDataBasic) - json.Unmarshal(data, &result) + err := json.Unmarshal(data, &result) + if err != nil { + return nil, err + } for key, value := range v.AdditionalFields { result[key] = value @@ -587,7 +600,7 @@ type User struct { Phone string `json:"phone,omitempty"` Status string `json:"status,omitempty"` Groups []UserGroup `json:"groups,omitempty"` - MgUserId uint64 `json:"mgUserId,omitempty"` + MGUserID uint64 `json:"mgUserId,omitempty"` } // UserGroup type. @@ -1054,7 +1067,7 @@ type Action struct { // MgTransport type. type MgTransport struct { - WebhookUrl string `json:"webhookUrl,omitempty"` + WebhookURL string `json:"webhookUrl,omitempty"` } // MgBot type. @@ -1072,7 +1085,7 @@ type CostRecord struct { DateTo string `json:"dateTo,omitempty"` Summ float32 `json:"summ,omitempty"` CostItem string `json:"costItem,omitempty"` - UserId int `json:"userId,omitempty"` + UserID int `json:"userId,omitempty"` Order *Order `json:"order,omitempty"` Sites []string `json:"sites,omitempty"` } @@ -1089,7 +1102,7 @@ type Cost struct { CreatedAt string `json:"createdAt,omitempty"` CreatedBy string `json:"createdBy,omitempty"` Order *Order `json:"order,omitempty"` - UserId int `json:"userId,omitempty"` + UserID int `json:"userId,omitempty"` Sites []string `json:"sites,omitempty"` } diff --git a/v5/types_test.go b/types_test.go similarity index 98% rename from v5/types_test.go rename to types_test.go index dc9e6db..93f1f94 100644 --- a/v5/types_test.go +++ b/types_test.go @@ -1,4 +1,4 @@ -package v5 +package retailcrm import ( "encoding/json" diff --git a/v5/error.go b/v5/error.go deleted file mode 100644 index cbdc9df..0000000 --- a/v5/error.go +++ /dev/null @@ -1,32 +0,0 @@ -package v5 - -import "encoding/json" - -// APIErrorsList struct. -type APIErrorsList map[string]string - -// APIError struct. -type APIError struct { - SuccessfulResponse - ErrorMsg string `json:"errorMsg,omitempty"` - Errors APIErrorsList `json:"errors,omitempty"` -} - -func (e *APIError) Error() string { - return e.ErrorMsg -} - -func NewAPIError(dataResponse []byte) error { - a := &APIError{} - - if len(dataResponse) > 0 && dataResponse[0] == '<' { - a.ErrorMsg = "Account does not exist." - return a - } - - if err := json.Unmarshal(dataResponse, a); err != nil { - return err - } - - return a -} diff --git a/v5/error_test.go b/v5/error_test.go deleted file mode 100644 index 989b8e3..0000000 --- a/v5/error_test.go +++ /dev/null @@ -1,54 +0,0 @@ -package v5 - -import ( - "reflect" - "testing" - - "golang.org/x/xerrors" -) - -func TestFailure_ApiErrorsSlice(t *testing.T) { - b := []byte(`{"success": false, - "errorMsg": "Failed to activate module", - "errors": [ - "Your account has insufficient funds to activate integration module", - "Test error" - ]}`) - expected := APIErrorsList{ - "0": "Your account has insufficient funds to activate integration module", - "1": "Test error", - } - - var expEr *APIError - e := NewAPIError(b) - - if xerrors.As(e, &expEr) { - if eq := reflect.DeepEqual(expEr.Errors, expected); eq != true { - t.Errorf("%+v", eq) - } - } else { - t.Errorf("Error must be type of APIError: %v", e) - } -} - -func TestFailure_ApiErrorsMap(t *testing.T) { - b := []byte(`{"success": false, - "errorMsg": "Failed to activate module", - "errors": {"id": "ID must be an integer", "test": "Test error"}}`, - ) - expected := APIErrorsList{ - "id": "ID must be an integer", - "test": "Test error", - } - - var expEr *APIError - e := NewAPIError(b) - - if xerrors.As(e, &expEr) { - if eq := reflect.DeepEqual(expEr.Errors, expected); eq != true { - t.Errorf("%+v", eq) - } - } else { - t.Errorf("Error must be type of APIError: %v", e) - } -} diff --git a/v5/marshaling.go b/v5/marshaling.go deleted file mode 100644 index 15cfd50..0000000 --- a/v5/marshaling.go +++ /dev/null @@ -1,35 +0,0 @@ -package v5 - -import ( - "encoding/json" - "fmt" - "strconv" -) - -func (t Tag) MarshalJSON() ([]byte, error) { - return json.Marshal(t.Name) -} - -func (a *APIErrorsList) UnmarshalJSON(data []byte) error { - var i interface{} - var m map[string]string - if err := json.Unmarshal(data, &i); err != nil { - return err - } - - switch e := i.(type) { - case map[string]interface{}: - m = make(map[string]string, len(e)) - for idx, val := range e { - m[idx] = fmt.Sprint(val) - } - case []interface{}: - m = make(map[string]string, len(e)) - for idx, val := range e { - m[strconv.Itoa(idx)] = fmt.Sprint(val) - } - } - - *a = m - return nil -} diff --git a/v5/marshaling_test.go b/v5/marshaling_test.go deleted file mode 100644 index 199b22a..0000000 --- a/v5/marshaling_test.go +++ /dev/null @@ -1,24 +0,0 @@ -package v5 - -import ( - "encoding/json" - "reflect" - "testing" -) - -func TestTag_MarshalJSON(t *testing.T) { - tags := []Tag{ - {"first", "#3e89b6", false}, - {"second", "#ffa654", false}, - } - names := []byte(`["first","second"]`) - str, err := json.Marshal(tags) - - if err != nil { - t.Errorf("%v", err.Error()) - } - - if !reflect.DeepEqual(str, names) { - t.Errorf("Marshaled: %#v\nExpected: %#v\n", str, names) - } -}