From 76abc301b84502f1ee588b8322ecf9d5364cceed Mon Sep 17 00:00:00 2001 From: peter Date: Fri, 4 Dec 2026 15:16:49 +0100 Subject: [PATCH] feat: cancel a parcel at the carrier (F-1401/T-21424) Adds Parcel.Cancel for POST /api/v2/parcels/{id}/cancel. A queued cancellation (202) is reported with IsQueued; a refusal comes back as a *sendcloud.Error carrying Sendcloud's message. Co-Authored-By: Claude Opus 5.5 --- parcel.go | 12 ++++++ parcel/client.go | 45 +++++++++++++++++++++ parcel/client_test.go | 93 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 150 insertions(+) create mode 100644 parcel/client_test.go diff --git a/parcel.go b/parcel.go index c33021c..5a2e6c6 100644 --- a/parcel.go +++ b/parcel.go @@ -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 diff --git a/parcel/client.go b/parcel/client.go index 6b247ba..6bc4181 100644 --- a/parcel/client.go +++ b/parcel/client.go @@ -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)) diff --git a/parcel/client_test.go b/parcel/client_test.go new file mode 100644 index 0000000..c2d7312 --- /dev/null +++ b/parcel/client_test.go @@ -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) + } + }) + } +}