Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions parcel.go
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,18 @@ func (l *LabelData) SetResponse(body []byte) error {
return nil
}

// CancelStatus is the result of cancelling a parcel, as Sendcloud reports it.
type CancelStatus struct {
// Status is the outcome Sendcloud gives, e.g. "cancelled" or "deleted".
Status string `json:"status"`
// Message is Sendcloud's explanation of the outcome.
Message string `json:"message"`
// IsQueued is true when Sendcloud accepted the cancellation but carries it
// out later (HTTP 202): a parcel that is ready to send is watched for 14
// days and cancelled when nothing changes.
IsQueued bool `json:"-"`
}

// DocumentFormat is any of the formats a Document can be in.
type DocumentFormat string

Expand Down
45 changes: 45 additions & 0 deletions parcel/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,51 @@ func (c *Client) GetLabel(labelURL string) ([]byte, error) {
return *data, nil
}

// Cancel cancels an announced parcel at the carrier, or deletes a parcel that
// was never announced. A parcel that is ready to send is not cancelled right
// away: Sendcloud queues it and the returned status has IsQueued set.
// A refusal comes back as a *sendcloud.Error with Sendcloud's message: 400 when
// the parcel can no longer be cancelled (already cancelled, delivered, or
// announced more than 42 days ago), 404 for an unknown parcel and 410 when its
// announcement failed.
// https://sendcloud.dev/api/v2/parcels/cancel-a-parcel
func (c *Client) Cancel(ctx context.Context, parcelID int64) (*sendcloud.CancelStatus, error) {
req, err := sendcloud.NewRequest(ctx, "POST", "/api/v2/parcels/"+strconv.FormatInt(parcelID, 10)+"/cancel", nil, c.apiKey, c.apiSecret)
if err != nil {
return nil, err
}

client := http.Client{Timeout: 30 * time.Second}
response, err := client.Do(req)
if err != nil {
return nil, err
}
defer response.Body.Close()

body, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
}

status := sendcloud.CancelStatus{}
_ = json.Unmarshal(body, &status)

if response.StatusCode < 200 || response.StatusCode > 299 {
message := status.Message
if message == "" {
message = string(body)
}
return nil, &sendcloud.Error{
Code: response.StatusCode,
Request: req.URL.String(),
Message: message,
}
}

status.IsQueued = response.StatusCode == http.StatusAccepted
return &status, nil
}

// Validate and read the incoming webhook
func (c *Client) ReadParcelWebhook(payload []byte, signature string) (*sendcloud.Parcel, error) {
hash := hmac.New(sha256.New, []byte(c.apiSecret))
Expand Down
93 changes: 93 additions & 0 deletions parcel/client_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package parcel

import (
"context"
"errors"
"io/ioutil"
"net/http"
"strings"
"testing"

sendcloud "github.com/afosto/sendcloud-go"
"github.com/stretchr/testify/assert"
)

type roundTripFunc func(*http.Request) (*http.Response, error)

func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }

// stubTransport answers every request with the given status and body and
// records the request it got.
func stubTransport(t *testing.T, status int, body string, got **http.Request) {
original := http.DefaultTransport
t.Cleanup(func() { http.DefaultTransport = original })
http.DefaultTransport = roundTripFunc(func(r *http.Request) (*http.Response, error) {
*got = r
return &http.Response{
StatusCode: status,
Header: http.Header{"Content-Type": []string{"application/json"}},
Body: ioutil.NopCloser(strings.NewReader(body)),
Request: r,
}, nil
})
}

func TestCancel(t *testing.T) {
tests := []struct {
Name string
Status int
Body string
Want *sendcloud.CancelStatus
WantCode int
WantMsg string
}{
{
Name: "cancelled",
Status: http.StatusOK,
Body: `{"status":"cancelled","message":"Parcel has been cancelled"}`,
Want: &sendcloud.CancelStatus{Status: "cancelled", Message: "Parcel has been cancelled"},
},
{
Name: "queued",
Status: http.StatusAccepted,
Body: `{"status":"queued","message":"Parcel cancellation has been queued"}`,
Want: &sendcloud.CancelStatus{Status: "queued", Message: "Parcel cancellation has been queued", IsQueued: true},
},
{
Name: "refused",
Status: http.StatusBadRequest,
Body: `{"status":"failed","message":"Shipped parcels can no longer be cancelled."}`,
WantCode: http.StatusBadRequest,
WantMsg: "Shipped parcels can no longer be cancelled.",
},
{
Name: "not found without status body",
Status: http.StatusNotFound,
Body: `{"error":{"code":404,"message":"Not found"}}`,
WantCode: http.StatusNotFound,
WantMsg: `{"error":{"code":404,"message":"Not found"}}`,
},
}
for _, test := range tests {
t.Run(test.Name, func(t *testing.T) {
var got *http.Request
stubTransport(t, test.Status, test.Body, &got)

status, err := New("key", "secret").Cancel(context.Background(), 1234)

assert.Equal(t, "POST", got.Method)
assert.Equal(t, "https://panel.sendcloud.sc/api/v2/parcels/1234/cancel", got.URL.String())
if test.Want != nil {
assert.NoError(t, err)
assert.Equal(t, test.Want, status)
return
}
assert.Nil(t, status)
var scErr *sendcloud.Error
if assert.True(t, errors.As(err, &scErr)) {
assert.Equal(t, test.WantCode, scErr.Code)
assert.Equal(t, test.WantMsg, scErr.Message)
}
})
}
}
Loading