From b42fce17468a9f00a8388f3c7d47f1800cd188cf Mon Sep 17 00:00:00 2001 From: Maciej Walusiak Date: Fri, 20 Nov 2026 13:55:21 +0100 Subject: [PATCH 01/10] add subscription-topics list and get commands Decisions: - token-scoped like email-campaigns: /api/subscription_topics needs no account ID - copy templates' page-token pagination, repeating --per-page in the next-page hint - get adds a DELETED AT column, since it also returns deleted topics Co-Authored-By: Claude Opus 5.5 --- cmd/root.go | 2 + internal/commands/subscriptiontopics/get.go | 49 +++ internal/commands/subscriptiontopics/list.go | 69 ++++ .../subscriptiontopics/subscriptiontopics.go | 22 ++ .../subscriptiontopics_test.go | 333 ++++++++++++++++++ 5 files changed, 475 insertions(+) create mode 100644 internal/commands/subscriptiontopics/get.go create mode 100644 internal/commands/subscriptiontopics/list.go create mode 100644 internal/commands/subscriptiontopics/subscriptiontopics.go create mode 100644 internal/commands/subscriptiontopics/subscriptiontopics_test.go diff --git a/cmd/root.go b/cmd/root.go index 9b4f1d4..513742a 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -28,6 +28,7 @@ import ( "github.com/mailtrap/mailtrap-cli/internal/commands/sandboxes" "github.com/mailtrap/mailtrap-cli/internal/commands/send" "github.com/mailtrap/mailtrap-cli/internal/commands/stats" + "github.com/mailtrap/mailtrap-cli/internal/commands/subscriptiontopics" "github.com/mailtrap/mailtrap-cli/internal/commands/suppressions" "github.com/mailtrap/mailtrap-cli/internal/commands/templates" "github.com/mailtrap/mailtrap-cli/internal/commands/tokens" @@ -80,6 +81,7 @@ func NewRootCmd(f *cmdutil.Factory) *cobra.Command { cmd.AddCommand(contact_lists.NewCmdContactLists(f)) cmd.AddCommand(contact_fields.NewCmdContactFields(f)) cmd.AddCommand(emailcampaigns.NewCmdEmailCampaigns(f)) + cmd.AddCommand(subscriptiontopics.NewCmdSubscriptionTopics(f)) // Account Management cmd.AddCommand(accounts.NewCmdAccounts(f)) diff --git a/internal/commands/subscriptiontopics/get.go b/internal/commands/subscriptiontopics/get.go new file mode 100644 index 0000000..9e40a1b --- /dev/null +++ b/internal/commands/subscriptiontopics/get.go @@ -0,0 +1,49 @@ +package subscriptiontopics + +import ( + "context" + "encoding/json" + "fmt" + "slices" + + "github.com/mailtrap/mailtrap-cli/internal/client" + "github.com/mailtrap/mailtrap-cli/internal/cmdutil" + "github.com/mailtrap/mailtrap-cli/internal/output" + "github.com/spf13/cobra" +) + +// topicResponse keeps the topic as raw JSON so --output json prints every field. +type topicResponse struct { + Data json.RawMessage `json:"data"` +} + +// A deleted topic is still returned by get, with deleted_at set. +var topicDetailColumns = slices.Concat(topicColumns, []output.Column{{Header: "DELETED AT", Field: "deleted_at"}}) + +func NewCmdGet(f *cmdutil.Factory) *cobra.Command { + var id int + + cmd := &cobra.Command{ + Use: "get", + Short: "Get a subscription topic by ID", + Long: "Get a subscription topic by ID. Deleted topics are returned too, with DELETED AT set.", + RunE: func(cmd *cobra.Command, args []string) error { + c, err := f.NewClient() + if err != nil { + return err + } + + var resp topicResponse + if err := c.Get(context.Background(), client.BaseGeneral, fmt.Sprintf("%s/%d", basePath, id), nil, &resp); err != nil { + return err + } + + return output.Print(f.IOStreams.Out, cmdutil.GetOutputFormat(), resp.Data, topicDetailColumns) + }, + } + + cmd.Flags().IntVar(&id, "id", 0, "Subscription topic ID (required)") + _ = cmd.MarkFlagRequired("id") + + return cmd +} diff --git a/internal/commands/subscriptiontopics/list.go b/internal/commands/subscriptiontopics/list.go new file mode 100644 index 0000000..8ce8ad9 --- /dev/null +++ b/internal/commands/subscriptiontopics/list.go @@ -0,0 +1,69 @@ +package subscriptiontopics + +import ( + "context" + "encoding/json" + "fmt" + "net/url" + + "github.com/mailtrap/mailtrap-cli/internal/client" + "github.com/mailtrap/mailtrap-cli/internal/cmdutil" + "github.com/mailtrap/mailtrap-cli/internal/output" + "github.com/spf13/cobra" +) + +var topicColumns = []output.Column{ + {Header: "ID", Field: "id"}, + {Header: "NAME", Field: "name"}, + {Header: "DESCRIPTION", Field: "description"}, + {Header: "DOMAIN ID", Field: "domain_id"}, + {Header: "CREATED AT", Field: "created_at"}, +} + +var topicsPage = output.Page{ + Items: "data", + Cursor: []string{"pagination", "next_token"}, + CursorFlag: "token", +} + +func NewCmdList(f *cmdutil.Factory) *cobra.Command { + var ( + perPage int + token int + ) + + cmd := &cobra.Command{ + Use: "list", + Short: "List subscription topics, one page at a time", + Long: "List the account's subscription topics, one page at a time. Deleted topics are left out. An empty DOMAIN ID means the topic covers every domain.", + RunE: func(cmd *cobra.Command, args []string) error { + c, err := f.NewClient() + if err != nil { + return err + } + + query := url.Values{} + page := topicsPage + if cmd.Flags().Changed("per-page") { + query.Set("per_page", fmt.Sprintf("%d", perPage)) + // Without per_page the API reads the next token at its default page size. + page.NextArgs = fmt.Sprintf("--per-page %d", perPage) + } + if cmd.Flags().Changed("token") { + query.Set("token", fmt.Sprintf("%d", token)) + } + + var resp json.RawMessage + if err := c.Get(context.Background(), client.BaseGeneral, basePath, query, &resp); err != nil { + return err + } + + return output.PrintPage(f.IOStreams.Out, cmdutil.GetOutputFormat(), resp, page, topicColumns) + }, + } + + cmd.Flags().IntVar(&perPage, "per-page", 50, "Number of topics per page (max 100)") + cmd.Flags().IntVar(&token, "token", 0, "Page number to retrieve (page-token pagination)") + + return cmd +} diff --git a/internal/commands/subscriptiontopics/subscriptiontopics.go b/internal/commands/subscriptiontopics/subscriptiontopics.go new file mode 100644 index 0000000..0e615a7 --- /dev/null +++ b/internal/commands/subscriptiontopics/subscriptiontopics.go @@ -0,0 +1,22 @@ +package subscriptiontopics + +import ( + "github.com/mailtrap/mailtrap-cli/internal/cmdutil" + "github.com/spf13/cobra" +) + +// Subscription topics are token-scoped: the account is resolved from the API token, so +// commands in this package do not call config.RequireAccountID(). +const basePath = "/api/subscription_topics" + +func NewCmdSubscriptionTopics(f *cmdutil.Factory) *cobra.Command { + cmd := &cobra.Command{ + Use: "subscription-topics", + Short: "List and inspect subscription topics", + } + + cmd.AddCommand(NewCmdList(f)) + cmd.AddCommand(NewCmdGet(f)) + + return cmd +} diff --git a/internal/commands/subscriptiontopics/subscriptiontopics_test.go b/internal/commands/subscriptiontopics/subscriptiontopics_test.go new file mode 100644 index 0000000..8147ce6 --- /dev/null +++ b/internal/commands/subscriptiontopics/subscriptiontopics_test.go @@ -0,0 +1,333 @@ +package subscriptiontopics_test + +import ( + "bytes" + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "reflect" + "strings" + "testing" + + "github.com/mailtrap/mailtrap-cli/internal/client" + "github.com/mailtrap/mailtrap-cli/internal/cmdutil" + "github.com/mailtrap/mailtrap-cli/internal/commands/subscriptiontopics" + "github.com/mailtrap/mailtrap-cli/internal/config" + "github.com/spf13/viper" +) + +func setupTest(handler http.HandlerFunc) (*cmdutil.Factory, *bytes.Buffer, func()) { + server := httptest.NewServer(handler) + c := client.New("test-token") + c.SetBaseURL(client.BaseGeneral, server.URL) + buf := &bytes.Buffer{} + f := &cmdutil.Factory{ + Config: func() *config.Config { + return &config.Config{APIToken: "test-token", AccountID: "123"} + }, + IOStreams: &cmdutil.IOStreams{ + Out: buf, + ErrOut: &bytes.Buffer{}, + }, + ClientOverride: c, + } + viper.Set("api-token", "test-token") + viper.Set("account-id", "123") + viper.Set("output", "table") + return f, buf, func() { + server.Close() + viper.Reset() + } +} + +func listBody() map[string]interface{} { + return map[string]interface{}{ + "data": []map[string]interface{}{ + {"id": 7, "name": "Product updates", "description": "News about the product", "domain_id": 4321, "deleted_at": nil, "created_at": "2026-11-01T10:00:00Z", "updated_at": "2026-11-02T10:00:00Z"}, + {"id": 8, "name": "Newsletter", "description": nil, "domain_id": nil, "deleted_at": nil, "created_at": "2026-11-03T10:00:00Z", "updated_at": "2026-11-03T10:00:00Z"}, + }, + "pagination": map[string]interface{}{"token": 1, "prev_token": nil, "next_token": 2}, + } +} + +func TestSubscriptionTopicsList(t *testing.T) { + f, buf, cleanup := setupTest(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + t.Errorf("expected GET, got %s", r.Method) + } + // Token-scoped: no /api/accounts/{id} prefix. + if r.URL.Path != "/api/subscription_topics" { + t.Errorf("unexpected path: %s", r.URL.Path) + } + if r.Header.Get("Api-Token") != "test-token" { + t.Errorf("expected Api-Token header 'test-token', got %q", r.Header.Get("Api-Token")) + } + + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(listBody()) + }) + defer cleanup() + + cmd := subscriptiontopics.NewCmdSubscriptionTopics(f) + cmd.SetArgs([]string{"list"}) + cmd.SetOut(buf) + + if err := cmd.Execute(); err != nil { + t.Fatalf("unexpected error: %v", err) + } + + output := buf.String() + for _, want := range []string{"DOMAIN ID", "Product updates", "News about the product", "4321", "Newsletter"} { + if !strings.Contains(output, want) { + t.Errorf("expected output to contain %q, got:\n%s", want, output) + } + } +} + +func TestSubscriptionTopicsListJSON(t *testing.T) { + f, buf, cleanup := setupTest(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(listBody()) + }) + defer cleanup() + + viper.Set("output", "json") + + cmd := subscriptiontopics.NewCmdSubscriptionTopics(f) + cmd.SetArgs([]string{"list"}) + cmd.SetOut(buf) + + if err := cmd.Execute(); err != nil { + t.Fatalf("unexpected error: %v", err) + } + + var result struct { + Data []map[string]interface{} `json:"data"` + Pagination map[string]interface{} `json:"pagination"` + } + if err := json.Unmarshal(buf.Bytes(), &result); err != nil { + t.Fatalf("output is not a JSON object: %v\noutput:\n%s", err, buf.String()) + } + if len(result.Data) != 2 { + t.Fatalf("expected 2 topics, got %d", len(result.Data)) + } + if result.Data[0]["name"] != "Product updates" { + t.Errorf("expected name 'Product updates', got %v", result.Data[0]["name"]) + } + if domainID, ok := result.Data[1]["domain_id"]; !ok || domainID != nil { + t.Errorf("expected domain_id null to be kept, got %v (present: %v)", domainID, ok) + } + if result.Pagination["next_token"] != float64(2) { + t.Errorf("expected pagination.next_token 2, got %v", result.Pagination["next_token"]) + } +} + +func TestSubscriptionTopicsListNextPage(t *testing.T) { + f, buf, cleanup := setupTest(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(listBody()) + }) + defer cleanup() + + cmd := subscriptiontopics.NewCmdSubscriptionTopics(f) + cmd.SetArgs([]string{"list"}) + cmd.SetOut(buf) + + if err := cmd.Execute(); err != nil { + t.Fatalf("unexpected error: %v", err) + } + + if !strings.Contains(buf.String(), "Next page: --token 2") { + t.Errorf("expected next page footer, got:\n%s", buf.String()) + } +} + +func TestSubscriptionTopicsListNextPageRunsWithSamePerPage(t *testing.T) { + var requests []string + f, buf, cleanup := setupTest(func(w http.ResponseWriter, r *http.Request) { + requests = append(requests, r.URL.RawQuery) + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(listBody()) + }) + defer cleanup() + + cmd := subscriptiontopics.NewCmdSubscriptionTopics(f) + cmd.SetArgs([]string{"list", "--per-page", "1"}) + cmd.SetOut(buf) + if err := cmd.Execute(); err != nil { + t.Fatalf("unexpected error: %v", err) + } + + _, hint, found := strings.Cut(buf.String(), "Next page: ") + if !found { + t.Fatalf("expected next page footer, got:\n%s", buf.String()) + } + + cmd = subscriptiontopics.NewCmdSubscriptionTopics(f) + cmd.SetArgs(append([]string{"list"}, strings.Fields(hint)...)) + cmd.SetOut(buf) + if err := cmd.Execute(); err != nil { + t.Fatalf("unexpected error running the footer's command: %v", err) + } + + if want := []string{"per_page=1", "per_page=1&token=2"}; !reflect.DeepEqual(requests, want) { + t.Errorf("expected queries %v, got %v", want, requests) + } +} + +func TestSubscriptionTopicsListQuery(t *testing.T) { + f, buf, cleanup := setupTest(func(w http.ResponseWriter, r *http.Request) { + if got := r.URL.Query().Get("per_page"); got != "10" { + t.Errorf("expected per_page=10, got %q", got) + } + if got := r.URL.Query().Get("token"); got != "2" { + t.Errorf("expected token=2, got %q", got) + } + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(listBody()) + }) + defer cleanup() + + cmd := subscriptiontopics.NewCmdSubscriptionTopics(f) + cmd.SetArgs([]string{"list", "--per-page", "10", "--token", "2"}) + cmd.SetOut(buf) + + if err := cmd.Execute(); err != nil { + t.Fatalf("unexpected error: %v", err) + } +} + +func TestSubscriptionTopicsListOmitsUnsetQuery(t *testing.T) { + f, buf, cleanup := setupTest(func(w http.ResponseWriter, r *http.Request) { + if r.URL.RawQuery != "" { + t.Errorf("expected no query, got %q", r.URL.RawQuery) + } + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(listBody()) + }) + defer cleanup() + + cmd := subscriptiontopics.NewCmdSubscriptionTopics(f) + cmd.SetArgs([]string{"list"}) + cmd.SetOut(buf) + + if err := cmd.Execute(); err != nil { + t.Fatalf("unexpected error: %v", err) + } +} + +func TestSubscriptionTopicsListNoAccountID(t *testing.T) { + f, buf, cleanup := setupTest(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(listBody()) + }) + defer cleanup() + + viper.Set("account-id", "") + + cmd := subscriptiontopics.NewCmdSubscriptionTopics(f) + cmd.SetArgs([]string{"list"}) + cmd.SetOut(buf) + + if err := cmd.Execute(); err != nil { + t.Fatalf("expected list to work without an account ID, got: %v", err) + } +} + +// Accounts without subscription topics get a 403 with an empty body. +func TestSubscriptionTopicsListForbidden(t *testing.T) { + f, buf, cleanup := setupTest(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusForbidden) + }) + defer cleanup() + + cmd := subscriptiontopics.NewCmdSubscriptionTopics(f) + cmd.SetArgs([]string{"list"}) + cmd.SetOut(buf) + + err := cmd.Execute() + var apiErr *client.APIError + if !errors.As(err, &apiErr) || apiErr.StatusCode != http.StatusForbidden { + t.Fatalf("expected an API error 403, got: %v", err) + } +} + +func TestSubscriptionTopicsGet(t *testing.T) { + f, buf, cleanup := setupTest(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + t.Errorf("expected GET, got %s", r.Method) + } + if r.URL.Path != "/api/subscription_topics/7" { + t.Errorf("unexpected path: %s", r.URL.Path) + } + + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"data":{"id":7,"name":"Product updates","description":null,"domain_id":null,`+ + `"deleted_at":"2026-11-10T10:00:00Z","created_at":"2026-11-01T10:00:00Z","updated_at":"2026-11-10T10:00:00Z"}}`) + }) + defer cleanup() + + cmd := subscriptiontopics.NewCmdSubscriptionTopics(f) + cmd.SetArgs([]string{"get", "--id", "7"}) + cmd.SetOut(buf) + + if err := cmd.Execute(); err != nil { + t.Fatalf("unexpected error: %v", err) + } + + output := buf.String() + for _, want := range []string{"DELETED AT", "Product updates", "2026-11-10T10:00:00Z"} { + if !strings.Contains(output, want) { + t.Errorf("expected output to contain %q, got:\n%s", want, output) + } + } +} + +func TestSubscriptionTopicsGetJSONKeepsTopicAsIs(t *testing.T) { + topic := `{"id":7,"name":"Product updates","description":null,"domain_id":4321,` + + `"deleted_at":null,"created_at":"2026-11-01T10:00:00Z","updated_at":"2026-11-02T10:00:00Z"}` + + f, buf, cleanup := setupTest(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"data":`+topic+`}`) + }) + defer cleanup() + + viper.Set("output", "json") + + cmd := subscriptiontopics.NewCmdSubscriptionTopics(f) + cmd.SetArgs([]string{"get", "--id", "7"}) + cmd.SetOut(buf) + + if err := cmd.Execute(); err != nil { + t.Fatalf("unexpected error: %v", err) + } + + var got, want map[string]interface{} + if err := json.Unmarshal(buf.Bytes(), &got); err != nil { + t.Fatalf("output is not valid JSON: %v\noutput:\n%s", err, buf.String()) + } + json.Unmarshal([]byte(topic), &want) + if !reflect.DeepEqual(got, want) { + t.Errorf("expected the topic unchanged\nwant: %v\ngot: %v", want, got) + } +} + +func TestSubscriptionTopicsGetMissingID(t *testing.T) { + f, _, cleanup := setupTest(func(w http.ResponseWriter, r *http.Request) { + t.Error("unexpected request") + }) + defer cleanup() + + cmd := subscriptiontopics.NewCmdSubscriptionTopics(f) + cmd.SetArgs([]string{"get"}) + cmd.SilenceUsage = true + cmd.SilenceErrors = true + + err := cmd.Execute() + if err == nil || !strings.Contains(err.Error(), `required flag(s) "id" not set`) { + t.Fatalf("expected a required --id error, got: %v", err) + } +} From d4a695d2e14769ca52e9bd179a34eef018e236df Mon Sep 17 00:00:00 2001 From: Maciej Walusiak Date: Fri, 20 Nov 2026 13:55:21 +0100 Subject: [PATCH 02/10] add --subscription-topic-id to email-campaigns create and update Decisions: - sent only when the flag is given, since the API rejects a null topic - TOPIC ID column so table output shows the campaign's topic Co-Authored-By: Claude Opus 5.5 --- .../commands/emailcampaigns/attributes.go | 35 +++++++++------- .../emailcampaigns/emailcampaigns_test.go | 41 +++++++++++++++++++ internal/commands/emailcampaigns/list.go | 1 + 3 files changed, 62 insertions(+), 15 deletions(-) diff --git a/internal/commands/emailcampaigns/attributes.go b/internal/commands/emailcampaigns/attributes.go index 271be1c..81f9c78 100644 --- a/internal/commands/emailcampaigns/attributes.go +++ b/internal/commands/emailcampaigns/attributes.go @@ -6,21 +6,22 @@ import ( // campaignAttrs holds the writable campaign attributes shared by create and update. type campaignAttrs struct { - Name string - DomainID int64 - FromDisplayName string - FromLocalPart string - ReplyToDisplayName string - ReplyToLocalPart string - ReplyToDomain string - Subject string - BodyHTML string - BodyText string - MergeTags []string - DeliveryMode string - EmailsPerHour int64 - ContactListIDs []int64 - ContactSegmentIDs []int64 + Name string + DomainID int64 + FromDisplayName string + FromLocalPart string + ReplyToDisplayName string + ReplyToLocalPart string + ReplyToDomain string + Subject string + BodyHTML string + BodyText string + MergeTags []string + DeliveryMode string + EmailsPerHour int64 + ContactListIDs []int64 + ContactSegmentIDs []int64 + SubscriptionTopicID int64 } func addAttributeFlags(cmd *cobra.Command, attrs *campaignAttrs) { @@ -39,6 +40,7 @@ func addAttributeFlags(cmd *cobra.Command, attrs *campaignAttrs) { cmd.Flags().Int64Var(&attrs.EmailsPerHour, "emails-per-hour", 0, "Emails per hour when delivery mode is gradual") cmd.Flags().Int64SliceVar(&attrs.ContactListIDs, "contact-list-ids", nil, "Contact list IDs to send to (comma-separated)") cmd.Flags().Int64SliceVar(&attrs.ContactSegmentIDs, "contact-segment-ids", nil, "Contact segment IDs to send to (comma-separated)") + cmd.Flags().Int64Var(&attrs.SubscriptionTopicID, "subscription-topic-id", 0, "Subscription topic ID (see subscription-topics list)") } // buildAttributesBody builds the flat request body (no wrapper key) from the flags @@ -102,6 +104,9 @@ func buildAttributesBody(cmd *cobra.Command, attrs *campaignAttrs) map[string]in if cmd.Flags().Changed("contact-segment-ids") { body["contact_segment_ids"] = attrs.ContactSegmentIDs } + if cmd.Flags().Changed("subscription-topic-id") { + body["subscription_topic_id"] = attrs.SubscriptionTopicID + } return body } diff --git a/internal/commands/emailcampaigns/emailcampaigns_test.go b/internal/commands/emailcampaigns/emailcampaigns_test.go index bf9f2bb..f8716f5 100644 --- a/internal/commands/emailcampaigns/emailcampaigns_test.go +++ b/internal/commands/emailcampaigns/emailcampaigns_test.go @@ -59,6 +59,7 @@ func sampleCampaign() map[string]interface{} { "recipient_total_count": 1500, "contact_list_ids": []int{55, 56}, "delivery_mode": "rapid", + "subscription_topic_id": 77, "template": map[string]interface{}{ "id": 789, "subject": "Spring is here", @@ -308,6 +309,9 @@ func TestEmailCampaignsCreate(t *testing.T) { if segments, ok := reqBody["contact_segment_ids"].([]interface{}); !ok || len(segments) != 1 { t.Errorf("expected 1 contact_segment_id, got %v", reqBody["contact_segment_ids"]) } + if reqBody["subscription_topic_id"] != float64(77) { + t.Errorf("expected subscription_topic_id 77, got %v", reqBody["subscription_topic_id"]) + } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusCreated) @@ -329,6 +333,7 @@ func TestEmailCampaignsCreate(t *testing.T) { "--emails-per-hour", "1000", "--contact-list-ids", "55,56", "--contact-segment-ids", "12", + "--subscription-topic-id", "77", }) cmd.SetOut(buf) @@ -343,6 +348,9 @@ func TestEmailCampaignsCreate(t *testing.T) { if !strings.Contains(output, "draft") { t.Errorf("expected output to contain 'draft', got:\n%s", output) } + if !strings.Contains(output, "TOPIC ID") || !strings.Contains(output, "77") { + t.Errorf("expected output to show the subscription topic ID, got:\n%s", output) + } } func TestEmailCampaignsCreateMissingName(t *testing.T) { @@ -400,6 +408,9 @@ func TestEmailCampaignsUpdate(t *testing.T) { if _, ok := reqBody["reply_to"]; ok { t.Errorf("did not expect reply_to to be set, got %v", reqBody["reply_to"]) } + if _, ok := reqBody["subscription_topic_id"]; ok { + t.Errorf("did not expect subscription_topic_id to be set, got %v", reqBody["subscription_topic_id"]) + } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(map[string]interface{}{"data": sampleCampaign()}) @@ -479,6 +490,36 @@ func TestEmailCampaignsUpdateClearConflictsWithIDs(t *testing.T) { } } +func TestEmailCampaignsUpdateSubscriptionTopic(t *testing.T) { + f, buf, cleanup := setupTest(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + var reqBody map[string]interface{} + json.Unmarshal(body, &reqBody) + + if want := map[string]interface{}{"subscription_topic_id": float64(78)}; !reflect.DeepEqual(reqBody, want) { + t.Errorf("expected body %v, got %v", want, reqBody) + } + + campaign := sampleCampaign() + campaign["subscription_topic_id"] = nil + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(map[string]interface{}{"data": campaign}) + }) + defer cleanup() + + cmd := emailcampaigns.NewCmdEmailCampaigns(f) + cmd.SetArgs([]string{"update", "--id", "4567", "--subscription-topic-id", "78"}) + cmd.SetOut(buf) + + // A null topic (accounts without subscription topics) prints as an empty cell. + if err := cmd.Execute(); err != nil { + t.Fatalf("unexpected error: %v", err) + } + if !strings.Contains(buf.String(), "Spring Sale") { + t.Errorf("expected output to contain 'Spring Sale', got:\n%s", buf.String()) + } +} + func TestEmailCampaignsUpdateNoAttributes(t *testing.T) { f, buf, cleanup := setupTest(func(w http.ResponseWriter, r *http.Request) { t.Error("request should not be sent when no attribute flags are provided") diff --git a/internal/commands/emailcampaigns/list.go b/internal/commands/emailcampaigns/list.go index c1568e4..33e1838 100644 --- a/internal/commands/emailcampaigns/list.go +++ b/internal/commands/emailcampaigns/list.go @@ -24,6 +24,7 @@ var campaignColumns = []output.Column{ {Header: "STATE", Field: "current_state"}, {Header: "DOMAIN", Field: "domain_name"}, {Header: "RECIPIENTS", Field: "recipient_total_count"}, + {Header: "TOPIC ID", Field: "subscription_topic_id"}, {Header: "CREATED", Field: "created_at"}, } From f7130b888cec5f377417e1f3f34f63af48d261ae Mon Sep 17 00:00:00 2001 From: Maciej Walusiak Date: Fri, 20 Nov 2026 13:55:21 +0100 Subject: [PATCH 03/10] add --subscription-topics to contacts create and update Decisions: - keep the contact as raw JSON, so -o json no longer drops subscription_topics - validate the JSON array locally like forward-rules --conditions, so a typo fails before the request Co-Authored-By: Claude Opus 5.5 --- internal/commands/contacts/contacts_test.go | 214 ++++++++++++++++++ internal/commands/contacts/create.go | 15 ++ internal/commands/contacts/get.go | 15 +- .../commands/contacts/subscription_topics.go | 50 ++++ internal/commands/contacts/update.go | 15 ++ 5 files changed, 298 insertions(+), 11 deletions(-) create mode 100644 internal/commands/contacts/subscription_topics.go diff --git a/internal/commands/contacts/contacts_test.go b/internal/commands/contacts/contacts_test.go index 7f92f90..feca6e3 100644 --- a/internal/commands/contacts/contacts_test.go +++ b/internal/commands/contacts/contacts_test.go @@ -6,6 +6,7 @@ import ( "io" "net/http" "net/http/httptest" + "reflect" "strings" "testing" @@ -498,3 +499,216 @@ func TestContactsExportStatus(t *testing.T) { t.Errorf("expected output to contain 'completed', got:\n%s", output) } } + +func TestContactsCreateWithSubscriptionTopics(t *testing.T) { + f, buf, cleanup := setupTest(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + var payload map[string]interface{} + if err := json.Unmarshal(body, &payload); err != nil { + t.Fatalf("failed to unmarshal body: %v", err) + } + + contact, _ := payload["contact"].(map[string]interface{}) + want := []interface{}{ + map[string]interface{}{"subscription_topic_id": float64(7), "domain_id": float64(4321), "status": "unsubscribed"}, + map[string]interface{}{"subscription_topic_id": float64(8), "domain_id": float64(4322), "status": "subscribed"}, + } + if !reflect.DeepEqual(contact["subscription_topics"], want) { + t.Errorf("expected subscription_topics %v, got %v", want, contact["subscription_topics"]) + } + + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(`{"data":{"id":"new-id","email":"new@test.com","status":"subscribed","created_at":"2024-01-01","updated_at":"2024-01-01"}}`)) + }) + defer cleanup() + + cmd := contacts.NewCmdContacts(f) + cmd.SetArgs([]string{"create", "--email", "new@test.com", "--subscription-topics", + `[{"subscription_topic_id":7,"domain_id":4321,"status":"unsubscribed"},{"subscription_topic_id":8,"domain_id":4322,"status":"subscribed"}]`}) + cmd.SetOut(buf) + + if err := cmd.Execute(); err != nil { + t.Fatalf("unexpected error: %v", err) + } +} + +func TestContactsUpdateSubscriptionTopicsOnly(t *testing.T) { + f, buf, cleanup := setupTest(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + var payload map[string]interface{} + if err := json.Unmarshal(body, &payload); err != nil { + t.Fatalf("failed to unmarshal body: %v", err) + } + + want := map[string]interface{}{"contact": map[string]interface{}{ + "email": "x@y.com", + "subscription_topics": []interface{}{ + map[string]interface{}{"subscription_topic_id": float64(7), "domain_id": float64(4321), "status": "subscribed"}, + }, + }} + if !reflect.DeepEqual(payload, want) { + t.Errorf("expected body %v, got %v", want, payload) + } + + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(`{"data":{"id":"abc-123","email":"x@y.com","status":"subscribed","created_at":"2024-01-01","updated_at":"2024-01-02"},"action":"updated"}`)) + }) + defer cleanup() + + cmd := contacts.NewCmdContacts(f) + cmd.SetArgs([]string{"update", "--id", "abc-123", "--email", "x@y.com", "--subscription-topics", + `[{"subscription_topic_id":7,"domain_id":4321,"status":"subscribed"}]`}) + cmd.SetOut(buf) + + if err := cmd.Execute(); err != nil { + t.Fatalf("unexpected error: %v", err) + } +} + +func TestContactsOmitSubscriptionTopicsWhenUnset(t *testing.T) { + for _, args := range [][]string{ + {"create", "--email", "x@y.com"}, + {"update", "--id", "abc-123", "--email", "x@y.com"}, + } { + t.Run(args[0], func(t *testing.T) { + f, buf, cleanup := setupTest(func(w http.ResponseWriter, r *http.Request) { + var payload map[string]map[string]interface{} + json.NewDecoder(r.Body).Decode(&payload) + if _, ok := payload["contact"]["subscription_topics"]; ok { + t.Errorf("did not expect subscription_topics, got %v", payload["contact"]) + } + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(`{"data":{"id":"abc-123","email":"x@y.com"}}`)) + }) + defer cleanup() + + cmd := contacts.NewCmdContacts(f) + cmd.SetArgs(args) + cmd.SetOut(buf) + + if err := cmd.Execute(); err != nil { + t.Fatalf("unexpected error: %v", err) + } + }) + } +} + +func TestContactsInvalidSubscriptionTopics(t *testing.T) { + cases := []struct { + name string + value string + want string + }{ + {"not an array", `{"subscription_topic_id":7,"domain_id":4321,"status":"subscribed"}`, "must be a JSON array"}, + {"malformed", `[{"subscription_topic_id":7`, "invalid --subscription-topics JSON"}, + {"unknown key", `[{"subscription_topic_id":7,"domain_id":4321,"status":"subscribed","name":"News"}]`, `unknown field "name"`}, + {"trailing data", `[{"subscription_topic_id":7,"domain_id":4321,"status":"subscribed"}] []`, "unexpected data after the array"}, + {"string id", `[{"subscription_topic_id":"7","domain_id":4321,"status":"subscribed"}]`, "invalid --subscription-topics JSON"}, + {"missing topic", `[{"domain_id":4321,"status":"subscribed"}]`, "entry 1: subscription_topic_id must be greater than 0"}, + {"missing domain", `[{"subscription_topic_id":7,"domain_id":4321,"status":"subscribed"},{"subscription_topic_id":7,"status":"subscribed"}]`, "entry 2: domain_id must be greater than 0"}, + {"bad status", `[{"subscription_topic_id":7,"domain_id":4321,"status":"active"}]`, "entry 1: status must be one of subscribed, unsubscribed"}, + {"null entry", `[null]`, "entry 1: subscription_topic_id must be greater than 0"}, + } + + for _, command := range [][]string{ + {"create", "--email", "x@y.com"}, + {"update", "--id", "abc-123", "--email", "x@y.com"}, + } { + for _, tc := range cases { + t.Run(command[0]+"/"+tc.name, func(t *testing.T) { + f, _, cleanup := setupTest(func(w http.ResponseWriter, r *http.Request) { + t.Error("unexpected request") + }) + defer cleanup() + + cmd := contacts.NewCmdContacts(f) + cmd.SetArgs(append(append([]string{}, command...), "--subscription-topics", tc.value)) + cmd.SilenceUsage = true + cmd.SilenceErrors = true + + err := cmd.Execute() + if err == nil || !strings.Contains(err.Error(), tc.want) { + t.Fatalf("expected error containing %q, got: %v", tc.want, err) + } + }) + } + } +} + +func TestContactsJSONKeepsContactAsIs(t *testing.T) { + contactsByCase := map[string]string{ + "with topics": `{"id":"abc-123","email":"x@y.com","created_at":1700000000000,"updated_at":1700000000000,` + + `"list_ids":[],"status":"subscribed","fields":{"first_name":null},` + + `"subscription_topics":[{"subscription_topic_id":7,"domain_id":4321,"status":"unsubscribed"}]}`, + "unreadable topics": `{"id":"abc-123","email":"x@y.com","list_ids":[],"status":"subscribed","fields":{},"subscription_topics":null}`, + "topics off": `{"id":"abc-123","email":"x@y.com","list_ids":[],"status":"subscribed","fields":{}}`, + } + + for name, contact := range contactsByCase { + for _, args := range [][]string{ + {"get", "--id", "abc-123"}, + {"create", "--email", "x@y.com"}, + {"update", "--id", "abc-123", "--email", "x@y.com"}, + } { + t.Run(name+"/"+args[0], func(t *testing.T) { + f, buf, cleanup := setupTest(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"data":`+contact+`}`) + }) + defer cleanup() + + viper.Set("output", "json") + + cmd := contacts.NewCmdContacts(f) + cmd.SetArgs(args) + cmd.SetOut(buf) + + if err := cmd.Execute(); err != nil { + t.Fatalf("unexpected error: %v", err) + } + + var got, want map[string]interface{} + if err := json.Unmarshal(buf.Bytes(), &got); err != nil { + t.Fatalf("output is not valid JSON: %v\noutput:\n%s", err, buf.String()) + } + json.Unmarshal([]byte(contact), &want) + if !reflect.DeepEqual(got, want) { + t.Errorf("expected the contact unchanged\nwant: %v\ngot: %v", want, got) + } + }) + } + } +} + +func TestContactsSubscriptionTopicsErrorsKeepMessage(t *testing.T) { + cases := []struct { + name string + status int + body string + want string + }{ + {"topics off", http.StatusUnprocessableEntity, `{"errors":{"subscription_topics":["are not available for this account"]}}`, "are not available for this account"}, + {"topics not saved", http.StatusServiceUnavailable, `{"errors":"The contact was saved, but its subscription topic preferences were not. Send them again in an update of contact abc-123."}`, "Send them again in an update of contact abc-123"}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + f, _, cleanup := setupTest(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(tc.status) + io.WriteString(w, tc.body) + }) + defer cleanup() + + cmd := contacts.NewCmdContacts(f) + cmd.SetArgs([]string{"create", "--email", "x@y.com", "--subscription-topics", `[{"subscription_topic_id":7,"domain_id":4321,"status":"subscribed"}]`}) + cmd.SilenceUsage = true + cmd.SilenceErrors = true + + err := cmd.Execute() + if err == nil || !strings.Contains(err.Error(), tc.want) { + t.Fatalf("expected error containing %q, got: %v", tc.want, err) + } + }) + } +} diff --git a/internal/commands/contacts/create.go b/internal/commands/contacts/create.go index 8a542a5..33a15ff 100644 --- a/internal/commands/contacts/create.go +++ b/internal/commands/contacts/create.go @@ -15,6 +15,7 @@ func NewCmdCreate(f *cmdutil.Factory) *cobra.Command { var firstName string var lastName string var listIDs []int + var subscriptionTopics string cmd := &cobra.Command{ Use: "create", @@ -24,6 +25,15 @@ func NewCmdCreate(f *cmdutil.Factory) *cobra.Command { return err } + var topics []subscriptionTopicInput + if cmd.Flags().Changed("subscription-topics") { + parsed, err := parseSubscriptionTopics(subscriptionTopics) + if err != nil { + return err + } + topics = parsed + } + c, err := f.NewClient() if err != nil { return err @@ -55,6 +65,10 @@ func NewCmdCreate(f *cmdutil.Factory) *cobra.Command { contactData["list_ids"] = listIDs } + if topics != nil { + contactData["subscription_topics"] = topics + } + body := map[string]interface{}{ "contact": contactData, } @@ -73,6 +87,7 @@ func NewCmdCreate(f *cmdutil.Factory) *cobra.Command { cmd.Flags().StringVar(&firstName, "first-name", "", "Contact first name") cmd.Flags().StringVar(&lastName, "last-name", "", "Contact last name") cmd.Flags().IntSliceVar(&listIDs, "list-ids", nil, "List IDs to add the contact to") + cmd.Flags().StringVar(&subscriptionTopics, "subscription-topics", "", subscriptionTopicsUsage) return cmd } diff --git a/internal/commands/contacts/get.go b/internal/commands/contacts/get.go index 61ce5cd..7071358 100644 --- a/internal/commands/contacts/get.go +++ b/internal/commands/contacts/get.go @@ -2,6 +2,7 @@ package contacts import ( "context" + "encoding/json" "fmt" "github.com/mailtrap/mailtrap-cli/internal/client" @@ -11,18 +12,10 @@ import ( "github.com/spf13/cobra" ) -type Contact struct { - ID string `json:"id"` - Email string `json:"email"` - Fields map[string]interface{} `json:"fields,omitempty"` - ListIDs []int `json:"list_ids,omitempty"` - Status string `json:"status,omitempty"` - CreatedAt interface{} `json:"created_at"` - UpdatedAt interface{} `json:"updated_at"` -} - +// contactResponse keeps the contact as raw JSON so --output json prints every +// field, including subscription_topics. type contactResponse struct { - Data Contact `json:"data"` + Data json.RawMessage `json:"data"` } var contactColumns = []output.Column{ diff --git a/internal/commands/contacts/subscription_topics.go b/internal/commands/contacts/subscription_topics.go new file mode 100644 index 0000000..8ea2f97 --- /dev/null +++ b/internal/commands/contacts/subscription_topics.go @@ -0,0 +1,50 @@ +package contacts + +import ( + "encoding/json" + "fmt" + "io" + "slices" + "strings" +) + +const subscriptionTopicsUsage = `Subscription topic preferences as a JSON array, e.g. '[{"subscription_topic_id":7,"domain_id":4321,"status":"unsubscribed"}]'; topic and domain pairs left out keep their status` + +var validTopicStatuses = []string{"subscribed", "unsubscribed"} + +type subscriptionTopicInput struct { + SubscriptionTopicID int64 `json:"subscription_topic_id"` + DomainID int64 `json:"domain_id"` + Status string `json:"status"` +} + +func parseSubscriptionTopics(raw string) ([]subscriptionTopicInput, error) { + if !strings.HasPrefix(strings.TrimSpace(raw), "[") { + return nil, fmt.Errorf("invalid --subscription-topics: must be a JSON array") + } + + dec := json.NewDecoder(strings.NewReader(raw)) + dec.DisallowUnknownFields() + + topics := []subscriptionTopicInput{} + if err := dec.Decode(&topics); err != nil { + return nil, fmt.Errorf("invalid --subscription-topics JSON: %w", err) + } + if _, err := dec.Token(); err != io.EOF { + return nil, fmt.Errorf("invalid --subscription-topics JSON: unexpected data after the array") + } + + for i, topic := range topics { + if topic.SubscriptionTopicID <= 0 { + return nil, fmt.Errorf("invalid --subscription-topics: entry %d: subscription_topic_id must be greater than 0", i+1) + } + if topic.DomainID <= 0 { + return nil, fmt.Errorf("invalid --subscription-topics: entry %d: domain_id must be greater than 0", i+1) + } + if !slices.Contains(validTopicStatuses, topic.Status) { + return nil, fmt.Errorf("invalid --subscription-topics: entry %d: status must be one of %s", i+1, strings.Join(validTopicStatuses, ", ")) + } + } + + return topics, nil +} diff --git a/internal/commands/contacts/update.go b/internal/commands/contacts/update.go index aac42d3..12d0829 100644 --- a/internal/commands/contacts/update.go +++ b/internal/commands/contacts/update.go @@ -19,6 +19,7 @@ func NewCmdUpdate(f *cmdutil.Factory) *cobra.Command { var listIDsIncluded []int var listIDsExcluded []int var unsubscribed bool + var subscriptionTopics string cmd := &cobra.Command{ Use: "update", @@ -31,6 +32,15 @@ func NewCmdUpdate(f *cmdutil.Factory) *cobra.Command { return err } + var topics []subscriptionTopicInput + if cmd.Flags().Changed("subscription-topics") { + parsed, err := parseSubscriptionTopics(subscriptionTopics) + if err != nil { + return err + } + topics = parsed + } + c, err := f.NewClient() if err != nil { return err @@ -68,6 +78,10 @@ func NewCmdUpdate(f *cmdutil.Factory) *cobra.Command { contactData["unsubscribed"] = unsubscribed } + if topics != nil { + contactData["subscription_topics"] = topics + } + body := map[string]interface{}{ "contact": contactData, } @@ -89,6 +103,7 @@ func NewCmdUpdate(f *cmdutil.Factory) *cobra.Command { cmd.Flags().IntSliceVar(&listIDsIncluded, "list-ids-included", nil, "List IDs to subscribe to") cmd.Flags().IntSliceVar(&listIDsExcluded, "list-ids-excluded", nil, "List IDs to unsubscribe from") cmd.Flags().BoolVar(&unsubscribed, "unsubscribed", false, "Set contact as unsubscribed") + cmd.Flags().StringVar(&subscriptionTopics, "subscription-topics", "", subscriptionTopicsUsage) return cmd } From d1c2cfdf87554ae3aa90940a2e6710565dd4366e Mon Sep 17 00:00:00 2001 From: Maciej Walusiak Date: Fri, 20 Nov 2026 13:55:22 +0100 Subject: [PATCH 04/10] add --include-topic-unsubscriptions to suppressions list Decisions: - the API opts in only on the literal string true - keep suppressions as raw JSON, so -o json shows subscription_topic_id Co-Authored-By: Claude Opus 5.5 --- internal/commands/suppressions/create.go | 3 +- internal/commands/suppressions/list.go | 19 ++-- .../suppressions/suppressions_test.go | 90 +++++++++++++++++++ 3 files changed, 101 insertions(+), 11 deletions(-) diff --git a/internal/commands/suppressions/create.go b/internal/commands/suppressions/create.go index 851ad79..f9ad8bc 100644 --- a/internal/commands/suppressions/create.go +++ b/internal/commands/suppressions/create.go @@ -2,6 +2,7 @@ package suppressions import ( "context" + "encoding/json" "fmt" "github.com/mailtrap/mailtrap-cli/internal/client" @@ -12,7 +13,7 @@ import ( ) type suppressionResponse struct { - Data Suppression `json:"data"` + Data json.RawMessage `json:"data"` } func NewCmdCreate(f *cmdutil.Factory) *cobra.Command { diff --git a/internal/commands/suppressions/list.go b/internal/commands/suppressions/list.go index aab5a90..74186c9 100644 --- a/internal/commands/suppressions/list.go +++ b/internal/commands/suppressions/list.go @@ -2,6 +2,7 @@ package suppressions import ( "context" + "encoding/json" "net/url" "github.com/mailtrap/mailtrap-cli/internal/client" @@ -11,21 +12,13 @@ import ( "github.com/spf13/cobra" ) -type Suppression struct { - ID string `json:"id"` - Email string `json:"email"` - Type string `json:"type"` - SendingStream string `json:"sending_stream,omitempty"` - DomainName string `json:"domain_name,omitempty"` - CreatedAt string `json:"created_at"` -} - var suppressionColumns = []output.Column{ {Header: "ID", Field: "id"}, {Header: "EMAIL", Field: "email"}, {Header: "TYPE", Field: "type"}, {Header: "SENDING_STREAM", Field: "sending_stream"}, {Header: "DOMAIN_NAME", Field: "domain_name"}, + {Header: "TOPIC_ID", Field: "subscription_topic_id"}, {Header: "CREATED_AT", Field: "created_at"}, } @@ -34,6 +27,7 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command { var startTime string var endTime string var lastID string + var includeTopicUnsubscriptions bool cmd := &cobra.Command{ Use: "list", @@ -64,8 +58,12 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command { if lastID != "" { query.Set("last_id", lastID) } + if includeTopicUnsubscriptions { + query.Set("include_topic_unsubscriptions", "true") + } - var suppressions []Suppression + // Raw JSON keeps every field the API returns in --output json. + var suppressions json.RawMessage if err := c.Get(context.Background(), client.BaseGeneral, path, query, &suppressions); err != nil { return err } @@ -79,6 +77,7 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command { cmd.Flags().StringVar(&startTime, "start-time", "", "Filter by start time") cmd.Flags().StringVar(&endTime, "end-time", "", "Filter by end time") cmd.Flags().StringVar(&lastID, "last-id", "", "Pagination cursor (id of the last record from the previous response)") + cmd.Flags().BoolVar(&includeTopicUnsubscriptions, "include-topic-unsubscriptions", false, "Also list unsubscriptions from single subscription topics (type 'topic unsubscription')") return cmd } diff --git a/internal/commands/suppressions/suppressions_test.go b/internal/commands/suppressions/suppressions_test.go index bc1b76c..92e9c5e 100644 --- a/internal/commands/suppressions/suppressions_test.go +++ b/internal/commands/suppressions/suppressions_test.go @@ -3,8 +3,10 @@ package suppressions_test import ( "bytes" "encoding/json" + "io" "net/http" "net/http/httptest" + "reflect" "strings" "testing" @@ -367,3 +369,91 @@ func TestSuppressionsListPagination(t *testing.T) { t.Errorf("expected output to contain 'next@example.com', got:\n%s", buf.String()) } } + +func TestSuppressionsListIncludeTopicUnsubscriptions(t *testing.T) { + f, buf, cleanup := setupTest(func(w http.ResponseWriter, r *http.Request) { + if r.URL.RawQuery != "include_topic_unsubscriptions=true" { + t.Errorf("expected query 'include_topic_unsubscriptions=true', got %q", r.URL.RawQuery) + } + + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `[{"id":"uuid-3","email":"reader@example.com","type":"topic unsubscription","created_at":"2026-11-01T10:00:00Z",`+ + `"sending_stream":"bulk","domain_name":"example.com","subscription_topic_id":77,"message_bounce_category":null}]`) + }) + defer cleanup() + + cmd := suppressions.NewCmdSuppressions(f) + cmd.SetArgs([]string{"list", "--include-topic-unsubscriptions"}) + cmd.SetOut(buf) + + if err := cmd.Execute(); err != nil { + t.Fatalf("unexpected error: %v", err) + } + + output := buf.String() + for _, want := range []string{"TOPIC_ID", "topic unsubscription", "77"} { + if !strings.Contains(output, want) { + t.Errorf("expected output to contain %q, got:\n%s", want, output) + } + } +} + +func TestSuppressionsListOmitsTopicUnsubscriptionsByDefault(t *testing.T) { + f, buf, cleanup := setupTest(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Query().Has("include_topic_unsubscriptions") { + t.Errorf("did not expect include_topic_unsubscriptions, got %q", r.URL.RawQuery) + } + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `[]`) + }) + defer cleanup() + + cmd := suppressions.NewCmdSuppressions(f) + cmd.SetArgs([]string{"list", "--email", "test@example.com"}) + cmd.SetOut(buf) + + if err := cmd.Execute(); err != nil { + t.Fatalf("unexpected error: %v", err) + } +} + +func TestSuppressionsJSONKeepsSuppressionsAsIs(t *testing.T) { + suppression := `{"id":"uuid-3","email":"reader@example.com","type":"topic unsubscription","created_at":"2026-11-01T10:00:00Z",` + + `"sending_stream":"bulk","domain_name":"example.com","subscription_topic_id":77,"message_bounce_category":null}` + + for _, tc := range []struct { + args []string + body string + want string + }{ + {[]string{"list"}, `[` + suppression + `]`, `[` + suppression + `]`}, + {[]string{"create", "--email", "reader@example.com", "--domain-id", "4321", "--sending-stream", "bulk"}, `{"data":` + suppression + `}`, suppression}, + } { + t.Run(tc.args[0], func(t *testing.T) { + f, buf, cleanup := setupTest(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, tc.body) + }) + defer cleanup() + + viper.Set("output", "json") + + cmd := suppressions.NewCmdSuppressions(f) + cmd.SetArgs(tc.args) + cmd.SetOut(buf) + + if err := cmd.Execute(); err != nil { + t.Fatalf("unexpected error: %v", err) + } + + var got, want interface{} + if err := json.Unmarshal(buf.Bytes(), &got); err != nil { + t.Fatalf("output is not valid JSON: %v\noutput:\n%s", err, buf.String()) + } + json.Unmarshal([]byte(tc.want), &want) + if !reflect.DeepEqual(got, want) { + t.Errorf("expected the response unchanged\nwant: %v\ngot: %v", want, got) + } + }) + } +} From 6201feacf1bdd706d3300d203937449ac9e0ce45 Mon Sep 17 00:00:00 2001 From: Maciej Walusiak Date: Fri, 20 Nov 2026 13:55:22 +0100 Subject: [PATCH 05/10] list subscription_preferences_update in the webhooks event types help Decisions: - help only: the API is the authority on which webhooks accept it Co-Authored-By: Claude Opus 5.5 --- internal/commands/webhooks/create.go | 5 +- internal/commands/webhooks/update.go | 2 +- internal/commands/webhooks/webhooks_test.go | 52 +++++++++++++++++++++ 3 files changed, 57 insertions(+), 2 deletions(-) diff --git a/internal/commands/webhooks/create.go b/internal/commands/webhooks/create.go index 8a5b197..7aabfdb 100644 --- a/internal/commands/webhooks/create.go +++ b/internal/commands/webhooks/create.go @@ -21,6 +21,9 @@ type webhookCreateResponse struct { var webhookCreateColumns = append(append([]output.Column{}, webhookColumns...), output.Column{Header: "SIGNING SECRET", Field: "signing_secret"}) +const eventTypesUsage = "Event types (comma-separated): delivery, soft_bounce, bounce, suspension, unsubscribe, open, spam_complaint, click, reject, " + + "subscription_preferences_update (bulk email_sending and campaigns webhooks only)" + func NewCmdCreate(f *cmdutil.Factory) *cobra.Command { var ( webhookURL string @@ -95,7 +98,7 @@ func NewCmdCreate(f *cmdutil.Factory) *cobra.Command { cmd.Flags().BoolVar(&active, "active", true, "Whether the webhook is active") cmd.Flags().StringVar(&payloadFormat, "payload-format", "", "Payload format: json, jsonlines") cmd.Flags().StringVar(&sendingStream, "sending-stream", "", "Sending stream: transactional, bulk") - cmd.Flags().StringSliceVar(&eventTypes, "event-types", nil, "Event types (comma-separated): delivery, soft_bounce, bounce, suspension, unsubscribe, open, spam_complaint, click, reject") + cmd.Flags().StringSliceVar(&eventTypes, "event-types", nil, eventTypesUsage) cmd.Flags().IntVar(&domainID, "domain-id", 0, "Domain ID to scope the webhook to (email_sending and campaigns)") cmd.Flags().IntVar(&inboundInboxID, "inbound-inbox-id", 0, "Email Inbound inbox ID to scope the webhook to (inbound_receiving only; omit to apply to all inboxes)") diff --git a/internal/commands/webhooks/update.go b/internal/commands/webhooks/update.go index 331d815..d3f8fe6 100644 --- a/internal/commands/webhooks/update.go +++ b/internal/commands/webhooks/update.go @@ -72,7 +72,7 @@ func NewCmdUpdate(f *cmdutil.Factory) *cobra.Command { cmd.Flags().StringVar(&webhookURL, "url", "", "Webhook URL") cmd.Flags().BoolVar(&active, "active", true, "Whether the webhook is active") cmd.Flags().StringVar(&payloadFormat, "payload-format", "", "Payload format: json, jsonlines") - cmd.Flags().StringSliceVar(&eventTypes, "event-types", nil, "Event types (comma-separated): delivery, soft_bounce, bounce, suspension, unsubscribe, open, spam_complaint, click, reject") + cmd.Flags().StringSliceVar(&eventTypes, "event-types", nil, eventTypesUsage) cmd.Flags().IntVar(&inboundInboxID, "inbound-inbox-id", 0, "Email Inbound inbox ID to scope the webhook to (inbound_receiving only)") return cmd diff --git a/internal/commands/webhooks/webhooks_test.go b/internal/commands/webhooks/webhooks_test.go index ef1daa4..7f9eea6 100644 --- a/internal/commands/webhooks/webhooks_test.go +++ b/internal/commands/webhooks/webhooks_test.go @@ -364,3 +364,55 @@ func TestWebhooksDelete(t *testing.T) { t.Errorf("expected success message, got:\n%s", buf.String()) } } + +func TestWebhooksCreateSubscriptionPreferencesUpdate(t *testing.T) { + f, buf, cleanup := setupTest(func(w http.ResponseWriter, r *http.Request) { + var reqBody map[string]map[string]interface{} + json.NewDecoder(r.Body).Decode(&reqBody) + + webhook := reqBody["webhook"] + if webhook["webhook_type"] != "campaigns" { + t.Errorf("unexpected webhook_type: %v", webhook["webhook_type"]) + } + if events, ok := webhook["event_types"].([]interface{}); !ok || len(events) != 1 || events[0] != "subscription_preferences_update" { + t.Errorf("expected event_types [subscription_preferences_update], got %v", webhook["event_types"]) + } + + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"data":{"id":11,"url":"https://example.com/hooks","active":true,"webhook_type":"campaigns",`+ + `"payload_format":"json","event_types":["subscription_preferences_update"],"signing_secret":"abc123secret"}}`) + }) + defer cleanup() + + cmd := webhooks.NewCmdWebhooks(f) + cmd.SetArgs([]string{ + "create", + "--url", "https://example.com/hooks", + "--type", "campaigns", + "--event-types", "subscription_preferences_update", + }) + cmd.SetOut(buf) + + if err := cmd.Execute(); err != nil { + t.Fatalf("unexpected error: %v", err) + } + + if !strings.Contains(buf.String(), "subscription_preferences_update") { + t.Errorf("expected output to contain the event type, got:\n%s", buf.String()) + } +} + +func TestWebhooksEventTypesHelpListsSubscriptionPreferencesUpdate(t *testing.T) { + f, _, cleanup := setupTest(func(w http.ResponseWriter, r *http.Request) {}) + defer cleanup() + + for _, name := range []string{"create", "update"} { + cmd, _, err := webhooks.NewCmdWebhooks(f).Find([]string{name}) + if err != nil { + t.Fatalf("find %s: %v", name, err) + } + if usage := cmd.Flags().Lookup("event-types").Usage; !strings.Contains(usage, "subscription_preferences_update") { + t.Errorf("expected %s --event-types help to list subscription_preferences_update, got %q", name, usage) + } + } +} From b78450150f7d1d1d3679e5178a7b0f23a512a7b9 Mon Sep 17 00:00:00 2001 From: Maciej Walusiak Date: Fri, 20 Nov 2026 13:55:22 +0100 Subject: [PATCH 06/10] document subscription topics in the README, skill and test plan Co-Authored-By: Claude Opus 5.5 --- README.md | 11 +++- docs/TEST_PLAN.md | 31 +++++++++- skills/mailtrap-cli/SKILL.md | 4 +- skills/mailtrap-cli/references/contacts.md | 17 ++++++ skills/mailtrap-cli/references/domains.md | 3 + .../references/subscription-topics.md | 61 +++++++++++++++++++ 6 files changed, 124 insertions(+), 3 deletions(-) create mode 100644 skills/mailtrap-cli/references/subscription-topics.md diff --git a/README.md b/README.md index c122cb2..4a03083 100644 --- a/README.md +++ b/README.md @@ -123,6 +123,7 @@ mailtrap company-info update --domain-id 123 --city "New York" --zip-code 10001 # Suppressions mailtrap suppressions list --email "bounced@example.com" +mailtrap suppressions list --include-topic-unsubscriptions mailtrap suppressions create --email "bounced@example.com" --domain-id 123 --sending-stream transactional mailtrap suppressions delete --id "2fe148b8-b019-431f-ab3f-107663fdf868" @@ -162,6 +163,8 @@ mailtrap tokens reset --id 42 --expires-at never # Contacts mailtrap contacts create --email "user@example.com" --first-name "John" +mailtrap contacts update --id --email "user@example.com" \ + --subscription-topics '[{"subscription_topic_id":7,"domain_id":4321,"status":"unsubscribed"}]' mailtrap contact-lists list mailtrap contact-lists list --search news mailtrap contact-fields create --name "Company" --data-type text --merge-tag "{{company}}" @@ -171,9 +174,14 @@ mailtrap email-campaigns list --search spring mailtrap email-campaigns create --name "Spring Sale" --domain-id 4321 --from-local-part news --subject "Spring is here" mailtrap email-campaigns update --id 4567 --body-html '

Hi {{first_name}}!

Unsubscribe' --contact-list-ids 55,56 mailtrap email-campaigns update --id 4567 --clear-contact-lists +mailtrap email-campaigns update --id 4567 --subscription-topic-id 7 mailtrap email-campaigns schedule --id 4567 --datetime "2030-01-01T09:00:00Z" mailtrap email-campaigns stats --id 4567 --start-date 2026-05-01 --end-date 2026-05-31 +# Subscription topics +mailtrap subscription-topics list +mailtrap subscription-topics get --id 7 + # Sandboxes & projects mailtrap projects list mailtrap sandboxes list @@ -195,7 +203,7 @@ mailtrap domains list --output text export MAILTRAP_OUTPUT=json ``` -With `--output json`, commands print the API response as returned. Paginated lists (`inbound messages list`, `inbound threads list`, `email-logs list`, `email-campaigns list`, `templates list`, `tracking-opt-outs list`) print the full response object, so the next-page cursor and, where the API provides one, the total count are available to scripts: +With `--output json`, commands print the API response as returned. Paginated lists (`inbound messages list`, `inbound threads list`, `email-logs list`, `email-campaigns list`, `subscription-topics list`, `templates list`, `tracking-opt-outs list`) print the full response object, so the next-page cursor and, where the API provides one, the total count are available to scripts: ```bash mailtrap inbound messages list --inbox-id 735 -o json | jq -r '.last_id // empty' @@ -220,6 +228,7 @@ mailtrap inbound messages list --inbox-id 735 -o json | jq -r '.last_id // empty | **Contact Lists** | `contact-lists list`, `contact-lists get`, `contact-lists create`, `contact-lists update`, `contact-lists delete` | | **Contact Fields** | `contact-fields list`, `contact-fields get`, `contact-fields create`, `contact-fields update`, `contact-fields delete` | | **Email Campaigns** | `email-campaigns list`, `email-campaigns get`, `email-campaigns create`, `email-campaigns update`, `email-campaigns delete`, `email-campaigns start`, `email-campaigns schedule`, `email-campaigns cancel`, `email-campaigns terminate`, `email-campaigns reset`, `email-campaigns stats` | +| **Subscription Topics** | `subscription-topics list`, `subscription-topics get` | | **Projects** | `projects list`, `projects get`, `projects create`, `projects update`, `projects delete` | | **Sandboxes** | `sandboxes list`, `sandboxes get`, `sandboxes create`, `sandboxes update`, `sandboxes delete`, `sandboxes clean`, `sandboxes mark-read`, `sandboxes reset-credentials`, `sandboxes toggle-email`, `sandboxes reset-email` | | **Messages** | `messages list`, `messages get`, `messages update`, `messages delete`, `messages forward`, `messages spam-score`, `messages html-analysis`, `messages headers`, `messages html`, `messages text`, `messages source`, `messages raw`, `messages eml` | diff --git a/docs/TEST_PLAN.md b/docs/TEST_PLAN.md index d83931b..5b6d718 100644 --- a/docs/TEST_PLAN.md +++ b/docs/TEST_PLAN.md @@ -53,6 +53,7 @@ These were discovered during integration testing and are important for correct i | `GET /contacts` | 404 (HTML page) | Endpoint may not exist or requires different path | | `GET /suppressions` | `[...]` | Flat array | | `GET /templates` | `{"data": [...], "pagination": {...}}` | Page-token pagination, no total | +| `GET /api/subscription_topics` | `{"data": [...], "pagination": {...}}` | Token-scoped (no account ID); page-token pagination, no total; `403` with an empty body on accounts without subscription topics | | `GET /contacts/lists` | `[...]` | Flat array | | `GET /contacts/fields` | `[...]` | Flat array | | `GET /account_accesses` | `[...]` | Flat array | @@ -379,6 +380,32 @@ Prerequisite: Send an email with an attachment to the sandbox. **Cleanup:** Delete created forward rules, inbox and folder (`inbound forward-rules delete`, `inbound inboxes delete`, `inbound folders delete`). +## 23. Subscription Topics + +**Note:** `subscription-topics` commands take no `--account-id` (requests go to `/api/subscription_topics`). Run 23.1–23.12 on an account with subscription topics, two domains, a topic for every domain and a topic for one domain, and 23.13–23.17 on an account without them. Topics are created in the Mailtrap app. + +| # | Test | Command | Expected | +|---|------|---------|----------| +| 23.1 | List topics | `mailtrap subscription-topics list` | Table with ID, NAME, DESCRIPTION, DOMAIN ID, CREATED AT; DOMAIN ID empty for the every-domain topic | +| 23.2 | List topics (JSON) | `mailtrap subscription-topics list --output json` | Valid JSON object with `data` and `pagination` | +| 23.3 | Next page keeps page size | `mailtrap subscription-topics list --per-page 1`, then run the `Next page:` hint | Hint is `--token 2 --per-page 1`; it prints the other topic | +| 23.4 | Get topic | `mailtrap subscription-topics get --id ` | Single topic with an empty DELETED AT | +| 23.5 | Get deleted topic | Delete a topic in the app, then `mailtrap subscription-topics get --id ` | Topic with DELETED AT set; it is gone from 23.1 | +| 23.6 | Get missing ID | `mailtrap subscription-topics get` | Error: `required flag(s) "id" not set` | +| 23.7 | Campaign with topic | `mailtrap email-campaigns create --name "topic-test" --domain-id --from-local-part news --subject "Hi" --subscription-topic-id ` | TOPIC ID column shows the topic; `email-campaigns get --id -o json` has `subscription_topic_id` | +| 23.8 | Campaign with uncovered topic | `mailtrap email-campaigns update --id --subscription-topic-id ` | `API error 422`, campaign unchanged | +| 23.9 | Contact topic preferences | `mailtrap contacts update --id --email --subscription-topics '[{"subscription_topic_id":,"domain_id":,"status":"unsubscribed"}]' -o json` | `subscription_topics` lists the topic as `unsubscribed` on that domain and `subscribed` on the other | +| 23.10 | Invalid topic entry | `mailtrap contacts update --id --email --subscription-topics '[{"subscription_topic_id":,"status":"unsubscribed"}]'` | Error: `entry 1: domain_id must be greater than 0`; no request sent | +| 23.11 | Import with topics | `mailtrap contacts import --file contacts.json` with a contact carrying `subscription_topics` | Import completes; `contacts get` shows the preference | +| 23.12 | Topic unsubscriptions | `mailtrap suppressions list --include-topic-unsubscriptions` after 23.9 | A `topic unsubscription` row with TOPIC_ID and DOMAIN_NAME; without the flag the row is absent | +| 23.13 | Topics off: list | `mailtrap subscription-topics list` | `API error 403` | +| 23.14 | Topics off: campaign | `mailtrap email-campaigns create ... --subscription-topic-id 1` | Campaign saved; TOPIC ID empty | +| 23.15 | Topics off: contact read | `mailtrap contacts get --id -o json` | No `subscription_topics` key, no error | +| 23.16 | Topics off: contact write | `mailtrap contacts update --id --email --subscription-topics '[{"subscription_topic_id":1,"domain_id":,"status":"subscribed"}]'` | `API error 422` naming `subscription_topics` ("are not available for this account") | +| 23.17 | Topics off: suppressions | `mailtrap suppressions list --include-topic-unsubscriptions` | No `topic unsubscription` rows | + +**Cleanup:** Delete the campaign created in 23.7 and the contacts imported in 23.11. + --- ## Discovered Bugs / Issues @@ -421,6 +448,7 @@ Run tests in dependency order so earlier tests create resources needed by later 20. **Organizations** (read-only, skip create/delete unless safe – delete only the sub-account created in 20.2) 21. **Configure** (local config only) 22. **Inbound** (CRUD for folders/inboxes/forward rules; messages/threads need received mail) +23. **Subscription Topics** (read-only topics; campaign, contact and suppression topic fields on accounts with and without topics) --- @@ -450,4 +478,5 @@ Run tests in dependency order so earlier tests create resources needed by later | Organizations | 3 | 5 | | Configure | 1 | 2 | | Inbound | 24 | 30 | -| **Total** | **~115** | **~139** | +| Subscription Topics | 2 | 17 | +| **Total** | **~117** | **~156** | diff --git a/skills/mailtrap-cli/SKILL.md b/skills/mailtrap-cli/SKILL.md index 1c74014..1e55f2f 100644 --- a/skills/mailtrap-cli/SKILL.md +++ b/skills/mailtrap-cli/SKILL.md @@ -38,6 +38,7 @@ Table and text output show a summary and, for paginated lists, a `Next page: --< | `inbound threads list` | `.data` | `.total_count` | `.last_id` → `--last-id` | | `email-logs list` | `.messages` | `.total_count` | `.next_page_cursor` → `--cursor` | | `email-campaigns list` | `.data` | — | `.pagination.next_token` → `--token` | +| `subscription-topics list` | `.data` | — | `.pagination.next_token` → `--token` (repeat `--per-page`) | | `templates list` | `.data` | — | `.pagination.next_token` → `--token` (repeat `--per-page`) | | `tracking-opt-outs list` | `.data` | — | `.last_id` → `--last-id` | @@ -51,7 +52,7 @@ A `null` cursor means there are no more pages. `suppressions list` and `messages - **Config priority**: CLI flags > environment variables > config file - **Exit codes**: 0 on success, 1 on error (with descriptive message) - **Naming**: sandboxes were formerly called inboxes, and domains were sending domains. A user asking about an "inbox" usually means a sandbox (`sandboxes`, `--sandbox-id`) unless they mean Email Inbound (`inbound`). API paths, JSON keys and token resource types keep the old names (`/inboxes`, `sending_domain_id`, `"inbox"`, `"sending_domain"`) -- **API base**: most requests go to `https://mailtrap.io/api/accounts/{account-id}/...`. Several groups do not and take no `--account-id`: `inbound` (`/api/inbound/...`), `company-info` (`/api/domains/{domain-id}/company_info`), `tracking-opt-outs` (`/api/tracking_opt_outs`), `email-campaigns` (`/api/email_campaigns`) and `organizations` (`/api/organizations/...`). `send` and `sandbox-send` go to their own hosts entirely. +- **API base**: most requests go to `https://mailtrap.io/api/accounts/{account-id}/...`. Several groups do not and take no `--account-id`: `inbound` (`/api/inbound/...`), `company-info` (`/api/domains/{domain-id}/company_info`), `tracking-opt-outs` (`/api/tracking_opt_outs`), `email-campaigns` (`/api/email_campaigns`), `subscription-topics` (`/api/subscription_topics`) and `organizations` (`/api/organizations/...`). `send` and `sandbox-send` go to their own hosts entirely. ## Command Groups @@ -67,6 +68,7 @@ A `null` cursor means there are no more pages. `suppressions list` and `messages | `contacts` | Contact management & import/export | [contacts.md](references/contacts.md) | | `contact-lists` | Contact list CRUD | [contacts.md](references/contacts.md) | | `contact-fields` | Custom contact fields | [contacts.md](references/contacts.md) | +| `subscription-topics` | Subscription topics, and the topic fields on campaigns, contacts and suppressions | [subscription-topics.md](references/subscription-topics.md) | | `sandbox-send` | Sending emails to a sandbox | [sandbox.md](references/sandbox.md) | | `projects` | Sandbox project management | [sandbox.md](references/sandbox.md) | | `sandboxes` | Sandbox management | [sandbox.md](references/sandbox.md) | diff --git a/skills/mailtrap-cli/references/contacts.md b/skills/mailtrap-cli/references/contacts.md index 1c4d7fe..48d7efb 100644 --- a/skills/mailtrap-cli/references/contacts.md +++ b/skills/mailtrap-cli/references/contacts.md @@ -12,6 +12,8 @@ Get a specific contact. |------|------|----------|-------------| | `--id` | string | Yes | Contact ID | +**Output:** With `--output json`, the contact as the API returns it. `subscription_topics` holds the contact's subscription topic preferences, one `{subscription_topic_id, domain_id, status}` entry per topic and domain; it is `null` when they couldn't be read (retry), and absent on accounts without subscription topics. `create` and `update` return the same shape. + --- ## contacts create @@ -24,6 +26,14 @@ Create a new contact. | `--first-name` | string | No | First name | | `--last-name` | string | No | Last name | | `--list-ids` | int[] | No | List IDs to add the contact to | +| `--subscription-topics` | string | No | Subscription topic preferences as a JSON array (see below) | + +`--subscription-topics` takes one entry per topic and domain: `subscription_topic_id` and `domain_id` (both required, from `subscription-topics list` and `domains list`) and `status` (`subscribed` or `unsubscribed`). Topic and domain pairs left out keep their status. On accounts without subscription topics the API rejects the flag with `422` ("are not available for this account"). If the contact is saved but its preferences are not, the API returns `503`; send them again with `contacts update`. + +```bash +mailtrap contacts create --email user@example.com \ + --subscription-topics '[{"subscription_topic_id":7,"domain_id":4321,"status":"unsubscribed"}]' +``` --- @@ -37,6 +47,7 @@ Update an existing contact. | `--email` | string | No | New email address | | `--first-name` | string | No | New first name | | `--last-name` | string | No | New last name | +| `--subscription-topics` | string | No | Subscription topic preferences as a JSON array, as for `contacts create`; pairs left out keep their status | --- @@ -59,6 +70,12 @@ Import contacts from a JSON file. | `--file` | string | Yes | Path to JSON file with contact data | | `--list-id` | int | No | List ID to import contacts into | +The file is posted as is. Each contact may carry `subscription_topics`, with the same entries as `contacts create --subscription-topics`: + +```json +{"contacts": [{"email": "user@example.com", "subscription_topics": [{"subscription_topic_id": 7, "domain_id": 4321, "status": "unsubscribed"}]}]} +``` + --- ## contacts export diff --git a/skills/mailtrap-cli/references/domains.md b/skills/mailtrap-cli/references/domains.md index 42a06d5..35154f2 100644 --- a/skills/mailtrap-cli/references/domains.md +++ b/skills/mailtrap-cli/references/domains.md @@ -113,9 +113,12 @@ List all suppressions (bounced/unsubscribed addresses). | `--start-time` | string | No | Filter by start time | | `--end-time` | string | No | Filter by end time | | `--last-id` | string | No | Pagination cursor: id of the last record from the previous response | +| `--include-topic-unsubscriptions` | bool | No | Also list unsubscriptions from single subscription topics | **Note:** The endpoint returns up to 1000 suppressions per request. Page through larger result sets with `--last-id`. +With `--include-topic-unsubscriptions`, rows of type `topic unsubscription` carry the topic in `subscription_topic_id` (TOPIC_ID column); other rows have `null` there. Topic unsubscriptions can't be created or deleted with `suppressions create` / `delete`. See [subscription-topics.md](subscription-topics.md). + --- ## suppressions create diff --git a/skills/mailtrap-cli/references/subscription-topics.md b/skills/mailtrap-cli/references/subscription-topics.md new file mode 100644 index 0000000..b4942c3 --- /dev/null +++ b/skills/mailtrap-cli/references/subscription-topics.md @@ -0,0 +1,61 @@ +# subscription-topics + +Detailed flag specifications for `mailtrap subscription-topics` commands, and the subscription topic flags of other groups. + +Subscription topics let contacts unsubscribe from one kind of marketing email (for example "Product updates") instead of from everything. Topics are created and edited in the Mailtrap app; the API and the CLI only read them. A topic covers one domain (`domain_id`), or every domain when `domain_id` is `null`. + +`subscription-topics` commands are token-scoped: they take no `--account-id`. On an account without subscription topics they fail with `API error 403`. + +--- + +## subscription-topics list + +List the account's subscription topics, one page at a time. Deleted topics are left out. + +| Flag | Type | Required | Description | +|------|------|----------|-------------| +| `--per-page` | int | No | Number of topics per page (default 50, max 100) | +| `--token` | int | No | Page number to retrieve (page-token pagination) | + +**Output:** Table of topics with ID, name, description, domain ID (empty for every domain) and creation time, followed by `Next page: --token N` when more pages exist (`Next page: --token N --per-page M` when `--per-page` was set). With `--output json`, the full response object is printed: `.data` holds the topics and `.pagination.next_token` the next page (`null` on the last page). + +--- + +## subscription-topics get + +Get a subscription topic. Deleted topics are returned too, with `deleted_at` set (DELETED AT column). + +| Flag | Type | Required | Description | +|------|------|----------|-------------| +| `--id` | int | Yes | Subscription topic ID | + +--- + +## Topics on campaigns + +`email-campaigns create` and `email-campaigns update` take `--subscription-topic-id `: recipients who unsubscribed from that topic don't get the campaign. The topic must cover the campaign's domain. Responses carry `subscription_topic_id` (TOPIC ID column), `null` when the campaign has none. + +```bash +mailtrap email-campaigns update --id 4567 --subscription-topic-id 7 +``` + +A campaign's topic can be changed but not removed. On an account without subscription topics the flag is ignored and the campaign reads back with `subscription_topic_id: null`. + +--- + +## Topics on contacts + +`contacts create` and `contacts update` take `--subscription-topics`, a JSON array with one entry per topic and domain. See [contacts.md](contacts.md). + +```bash +mailtrap contacts update --id --email user@example.com \ + --subscription-topics '[{"subscription_topic_id":7,"domain_id":4321,"status":"unsubscribed"}]' +``` + +`contacts get`, `create` and `update` return the contact's preferences in `subscription_topics` (JSON output only): a list of `{subscription_topic_id, domain_id, status}`, `null` when they couldn't be read (retry), or no key at all on an account without subscription topics. + +--- + +## Topic unsubscriptions + +`suppressions list --include-topic-unsubscriptions` adds the contacts' unsubscriptions from single topics, with type `topic unsubscription` and the topic in `subscription_topic_id` (TOPIC_ID column). See [domains.md](domains.md). From 0af871265fa3f46500c8275efeb7eefc3630225c Mon Sep 17 00:00:00 2001 From: Maciej Walusiak Date: Fri, 20 Nov 2026 13:59:46 +0100 Subject: [PATCH 07/10] share strict JSON array flag parsing and trim topic tests Decisions: - --subscription-topics and forward-rules --conditions decoded the same way; one cmdutil helper keeps their rules and messages in sync - set subscription_topics on the contact directly instead of a second nil check - merge near-duplicate tests and drop ones that only re-tested a help string or pass-through Co-Authored-By: Claude Opus 5.5 --- internal/cmdutil/json_array.go | 29 +++ internal/commands/contacts/contacts_test.go | 219 ++++++++---------- internal/commands/contacts/create.go | 14 +- .../commands/contacts/subscription_topics.go | 20 +- internal/commands/contacts/update.go | 14 +- .../emailcampaigns/emailcampaigns_test.go | 5 +- .../commands/inbound/forwardrules/create.go | 19 +- internal/commands/webhooks/webhooks_test.go | 37 --- 8 files changed, 147 insertions(+), 210 deletions(-) create mode 100644 internal/cmdutil/json_array.go diff --git a/internal/cmdutil/json_array.go b/internal/cmdutil/json_array.go new file mode 100644 index 0000000..f40596f --- /dev/null +++ b/internal/cmdutil/json_array.go @@ -0,0 +1,29 @@ +package cmdutil + +import ( + "encoding/json" + "fmt" + "io" + "strings" +) + +// ParseJSONArrayFlag strictly decodes the JSON array given to --flag: unknown +// keys and data after the array are errors. Callers validate the entries. +func ParseJSONArrayFlag[T any](flag, raw string) ([]T, error) { + if !strings.HasPrefix(strings.TrimSpace(raw), "[") { + return nil, fmt.Errorf("invalid --%s: must be a JSON array", flag) + } + + dec := json.NewDecoder(strings.NewReader(raw)) + dec.DisallowUnknownFields() + + entries := []T{} + if err := dec.Decode(&entries); err != nil { + return nil, fmt.Errorf("invalid --%s JSON: %w", flag, err) + } + if _, err := dec.Token(); err != io.EOF { + return nil, fmt.Errorf("invalid --%s JSON: unexpected data after the array", flag) + } + + return entries, nil +} diff --git a/internal/commands/contacts/contacts_test.go b/internal/commands/contacts/contacts_test.go index feca6e3..e48696f 100644 --- a/internal/commands/contacts/contacts_test.go +++ b/internal/commands/contacts/contacts_test.go @@ -500,68 +500,45 @@ func TestContactsExportStatus(t *testing.T) { } } -func TestContactsCreateWithSubscriptionTopics(t *testing.T) { - f, buf, cleanup := setupTest(func(w http.ResponseWriter, r *http.Request) { - body, _ := io.ReadAll(r.Body) - var payload map[string]interface{} - if err := json.Unmarshal(body, &payload); err != nil { - t.Fatalf("failed to unmarshal body: %v", err) - } - - contact, _ := payload["contact"].(map[string]interface{}) - want := []interface{}{ - map[string]interface{}{"subscription_topic_id": float64(7), "domain_id": float64(4321), "status": "unsubscribed"}, - map[string]interface{}{"subscription_topic_id": float64(8), "domain_id": float64(4322), "status": "subscribed"}, - } - if !reflect.DeepEqual(contact["subscription_topics"], want) { - t.Errorf("expected subscription_topics %v, got %v", want, contact["subscription_topics"]) - } - - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(`{"data":{"id":"new-id","email":"new@test.com","status":"subscribed","created_at":"2024-01-01","updated_at":"2024-01-01"}}`)) - }) - defer cleanup() - - cmd := contacts.NewCmdContacts(f) - cmd.SetArgs([]string{"create", "--email", "new@test.com", "--subscription-topics", - `[{"subscription_topic_id":7,"domain_id":4321,"status":"unsubscribed"},{"subscription_topic_id":8,"domain_id":4322,"status":"subscribed"}]`}) - cmd.SetOut(buf) +func TestContactsSendSubscriptionTopics(t *testing.T) { + topics := `[{"subscription_topic_id":7,"domain_id":4321,"status":"unsubscribed"},{"subscription_topic_id":8,"domain_id":4322,"status":"subscribed"}]` - if err := cmd.Execute(); err != nil { - t.Fatalf("unexpected error: %v", err) - } -} - -func TestContactsUpdateSubscriptionTopicsOnly(t *testing.T) { - f, buf, cleanup := setupTest(func(w http.ResponseWriter, r *http.Request) { - body, _ := io.ReadAll(r.Body) - var payload map[string]interface{} - if err := json.Unmarshal(body, &payload); err != nil { - t.Fatalf("failed to unmarshal body: %v", err) - } + // A topic-only update: the CLI still requires --email. + for _, args := range [][]string{ + {"create", "--email", "x@y.com", "--subscription-topics", topics}, + {"update", "--id", "abc-123", "--email", "x@y.com", "--subscription-topics", topics}, + } { + t.Run(args[0], func(t *testing.T) { + f, buf, cleanup := setupTest(func(w http.ResponseWriter, r *http.Request) { + var payload map[string]interface{} + if err := json.NewDecoder(r.Body).Decode(&payload); err != nil { + t.Fatalf("failed to decode body: %v", err) + } - want := map[string]interface{}{"contact": map[string]interface{}{ - "email": "x@y.com", - "subscription_topics": []interface{}{ - map[string]interface{}{"subscription_topic_id": float64(7), "domain_id": float64(4321), "status": "subscribed"}, - }, - }} - if !reflect.DeepEqual(payload, want) { - t.Errorf("expected body %v, got %v", want, payload) - } + want := map[string]interface{}{"contact": map[string]interface{}{ + "email": "x@y.com", + "subscription_topics": []interface{}{ + map[string]interface{}{"subscription_topic_id": float64(7), "domain_id": float64(4321), "status": "unsubscribed"}, + map[string]interface{}{"subscription_topic_id": float64(8), "domain_id": float64(4322), "status": "subscribed"}, + }, + }} + if !reflect.DeepEqual(payload, want) { + t.Errorf("expected body %v, got %v", want, payload) + } - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(`{"data":{"id":"abc-123","email":"x@y.com","status":"subscribed","created_at":"2024-01-01","updated_at":"2024-01-02"},"action":"updated"}`)) - }) - defer cleanup() + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(`{"data":{"id":"abc-123","email":"x@y.com","status":"subscribed"}}`)) + }) + defer cleanup() - cmd := contacts.NewCmdContacts(f) - cmd.SetArgs([]string{"update", "--id", "abc-123", "--email", "x@y.com", "--subscription-topics", - `[{"subscription_topic_id":7,"domain_id":4321,"status":"subscribed"}]`}) - cmd.SetOut(buf) + cmd := contacts.NewCmdContacts(f) + cmd.SetArgs(args) + cmd.SetOut(buf) - if err := cmd.Execute(); err != nil { - t.Fatalf("unexpected error: %v", err) + if err := cmd.Execute(); err != nil { + t.Fatalf("unexpected error: %v", err) + } + }) } } @@ -610,73 +587,79 @@ func TestContactsInvalidSubscriptionTopics(t *testing.T) { {"null entry", `[null]`, "entry 1: subscription_topic_id must be greater than 0"}, } - for _, command := range [][]string{ - {"create", "--email", "x@y.com"}, - {"update", "--id", "abc-123", "--email", "x@y.com"}, - } { - for _, tc := range cases { - t.Run(command[0]+"/"+tc.name, func(t *testing.T) { - f, _, cleanup := setupTest(func(w http.ResponseWriter, r *http.Request) { - t.Error("unexpected request") - }) - defer cleanup() - - cmd := contacts.NewCmdContacts(f) - cmd.SetArgs(append(append([]string{}, command...), "--subscription-topics", tc.value)) - cmd.SilenceUsage = true - cmd.SilenceErrors = true - - err := cmd.Execute() - if err == nil || !strings.Contains(err.Error(), tc.want) { - t.Fatalf("expected error containing %q, got: %v", tc.want, err) - } - }) + run := func(t *testing.T, args []string, want string) { + f, _, cleanup := setupTest(func(w http.ResponseWriter, r *http.Request) { + t.Error("unexpected request") + }) + defer cleanup() + + cmd := contacts.NewCmdContacts(f) + cmd.SetArgs(args) + cmd.SilenceUsage = true + cmd.SilenceErrors = true + + err := cmd.Execute() + if err == nil || !strings.Contains(err.Error(), want) { + t.Fatalf("expected error containing %q, got: %v", want, err) } } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + run(t, []string{"create", "--email", "x@y.com", "--subscription-topics", tc.value}, tc.want) + }) + } + // update shares the parser; one case shows it is wired in. + t.Run("update", func(t *testing.T) { + run(t, []string{"update", "--id", "abc-123", "--email", "x@y.com", "--subscription-topics", `[{"subscription_topic_id":7}]`}, + "entry 1: domain_id must be greater than 0") + }) } func TestContactsJSONKeepsContactAsIs(t *testing.T) { - contactsByCase := map[string]string{ - "with topics": `{"id":"abc-123","email":"x@y.com","created_at":1700000000000,"updated_at":1700000000000,` + - `"list_ids":[],"status":"subscribed","fields":{"first_name":null},` + - `"subscription_topics":[{"subscription_topic_id":7,"domain_id":4321,"status":"unsubscribed"}]}`, - "unreadable topics": `{"id":"abc-123","email":"x@y.com","list_ids":[],"status":"subscribed","fields":{},"subscription_topics":null}`, - "topics off": `{"id":"abc-123","email":"x@y.com","list_ids":[],"status":"subscribed","fields":{}}`, - } - - for name, contact := range contactsByCase { - for _, args := range [][]string{ - {"get", "--id", "abc-123"}, - {"create", "--email", "x@y.com"}, - {"update", "--id", "abc-123", "--email", "x@y.com"}, - } { - t.Run(name+"/"+args[0], func(t *testing.T) { - f, buf, cleanup := setupTest(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - io.WriteString(w, `{"data":`+contact+`}`) - }) - defer cleanup() - - viper.Set("output", "json") - - cmd := contacts.NewCmdContacts(f) - cmd.SetArgs(args) - cmd.SetOut(buf) - - if err := cmd.Execute(); err != nil { - t.Fatalf("unexpected error: %v", err) - } - - var got, want map[string]interface{} - if err := json.Unmarshal(buf.Bytes(), &got); err != nil { - t.Fatalf("output is not valid JSON: %v\noutput:\n%s", err, buf.String()) - } - json.Unmarshal([]byte(contact), &want) - if !reflect.DeepEqual(got, want) { - t.Errorf("expected the contact unchanged\nwant: %v\ngot: %v", want, got) - } + withTopics := `{"id":"abc-123","email":"x@y.com","created_at":1700000000000,"updated_at":1700000000000,` + + `"list_ids":[],"status":"subscribed","fields":{"first_name":null},` + + `"subscription_topics":[{"subscription_topic_id":7,"domain_id":4321,"status":"unsubscribed"}]}` + unreadable := `{"id":"abc-123","email":"x@y.com","list_ids":[],"status":"subscribed","fields":{},"subscription_topics":null}` + topicsOff := `{"id":"abc-123","email":"x@y.com","list_ids":[],"status":"subscribed","fields":{}}` + + for _, tc := range []struct { + name string + contact string + args []string + }{ + {"get with topics", withTopics, []string{"get", "--id", "abc-123"}}, + {"get unreadable topics", unreadable, []string{"get", "--id", "abc-123"}}, + {"get topics off", topicsOff, []string{"get", "--id", "abc-123"}}, + {"create", withTopics, []string{"create", "--email", "x@y.com"}}, + {"update", withTopics, []string{"update", "--id", "abc-123", "--email", "x@y.com"}}, + } { + t.Run(tc.name, func(t *testing.T) { + f, buf, cleanup := setupTest(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"data":`+tc.contact+`}`) }) - } + defer cleanup() + + viper.Set("output", "json") + + cmd := contacts.NewCmdContacts(f) + cmd.SetArgs(tc.args) + cmd.SetOut(buf) + + if err := cmd.Execute(); err != nil { + t.Fatalf("unexpected error: %v", err) + } + + var got, want map[string]interface{} + if err := json.Unmarshal(buf.Bytes(), &got); err != nil { + t.Fatalf("output is not valid JSON: %v\noutput:\n%s", err, buf.String()) + } + json.Unmarshal([]byte(tc.contact), &want) + if !reflect.DeepEqual(got, want) { + t.Errorf("expected the contact unchanged\nwant: %v\ngot: %v", want, got) + } + }) } } diff --git a/internal/commands/contacts/create.go b/internal/commands/contacts/create.go index 33a15ff..fac8b0b 100644 --- a/internal/commands/contacts/create.go +++ b/internal/commands/contacts/create.go @@ -25,13 +25,15 @@ func NewCmdCreate(f *cmdutil.Factory) *cobra.Command { return err } - var topics []subscriptionTopicInput + contactData := map[string]interface{}{ + "email": email, + } if cmd.Flags().Changed("subscription-topics") { parsed, err := parseSubscriptionTopics(subscriptionTopics) if err != nil { return err } - topics = parsed + contactData["subscription_topics"] = parsed } c, err := f.NewClient() @@ -46,10 +48,6 @@ func NewCmdCreate(f *cmdutil.Factory) *cobra.Command { path := cmdutil.AccountPath("contacts") - contactData := map[string]interface{}{ - "email": email, - } - fields := map[string]interface{}{} if firstName != "" { fields["first_name"] = firstName @@ -65,10 +63,6 @@ func NewCmdCreate(f *cmdutil.Factory) *cobra.Command { contactData["list_ids"] = listIDs } - if topics != nil { - contactData["subscription_topics"] = topics - } - body := map[string]interface{}{ "contact": contactData, } diff --git a/internal/commands/contacts/subscription_topics.go b/internal/commands/contacts/subscription_topics.go index 8ea2f97..fe31527 100644 --- a/internal/commands/contacts/subscription_topics.go +++ b/internal/commands/contacts/subscription_topics.go @@ -1,11 +1,11 @@ package contacts import ( - "encoding/json" "fmt" - "io" "slices" "strings" + + "github.com/mailtrap/mailtrap-cli/internal/cmdutil" ) const subscriptionTopicsUsage = `Subscription topic preferences as a JSON array, e.g. '[{"subscription_topic_id":7,"domain_id":4321,"status":"unsubscribed"}]'; topic and domain pairs left out keep their status` @@ -19,19 +19,9 @@ type subscriptionTopicInput struct { } func parseSubscriptionTopics(raw string) ([]subscriptionTopicInput, error) { - if !strings.HasPrefix(strings.TrimSpace(raw), "[") { - return nil, fmt.Errorf("invalid --subscription-topics: must be a JSON array") - } - - dec := json.NewDecoder(strings.NewReader(raw)) - dec.DisallowUnknownFields() - - topics := []subscriptionTopicInput{} - if err := dec.Decode(&topics); err != nil { - return nil, fmt.Errorf("invalid --subscription-topics JSON: %w", err) - } - if _, err := dec.Token(); err != io.EOF { - return nil, fmt.Errorf("invalid --subscription-topics JSON: unexpected data after the array") + topics, err := cmdutil.ParseJSONArrayFlag[subscriptionTopicInput]("subscription-topics", raw) + if err != nil { + return nil, err } for i, topic := range topics { diff --git a/internal/commands/contacts/update.go b/internal/commands/contacts/update.go index 12d0829..f17e94f 100644 --- a/internal/commands/contacts/update.go +++ b/internal/commands/contacts/update.go @@ -32,13 +32,15 @@ func NewCmdUpdate(f *cmdutil.Factory) *cobra.Command { return err } - var topics []subscriptionTopicInput + contactData := map[string]interface{}{ + "email": email, + } if cmd.Flags().Changed("subscription-topics") { parsed, err := parseSubscriptionTopics(subscriptionTopics) if err != nil { return err } - topics = parsed + contactData["subscription_topics"] = parsed } c, err := f.NewClient() @@ -53,10 +55,6 @@ func NewCmdUpdate(f *cmdutil.Factory) *cobra.Command { path := cmdutil.AccountPath("contacts", fmt.Sprintf("%s", contactID)) - contactData := map[string]interface{}{ - "email": email, - } - fields := map[string]interface{}{} if firstName != "" { fields["first_name"] = firstName @@ -78,10 +76,6 @@ func NewCmdUpdate(f *cmdutil.Factory) *cobra.Command { contactData["unsubscribed"] = unsubscribed } - if topics != nil { - contactData["subscription_topics"] = topics - } - body := map[string]interface{}{ "contact": contactData, } diff --git a/internal/commands/emailcampaigns/emailcampaigns_test.go b/internal/commands/emailcampaigns/emailcampaigns_test.go index f8716f5..db75d2e 100644 --- a/internal/commands/emailcampaigns/emailcampaigns_test.go +++ b/internal/commands/emailcampaigns/emailcampaigns_test.go @@ -500,10 +500,8 @@ func TestEmailCampaignsUpdateSubscriptionTopic(t *testing.T) { t.Errorf("expected body %v, got %v", want, reqBody) } - campaign := sampleCampaign() - campaign["subscription_topic_id"] = nil w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(map[string]interface{}{"data": campaign}) + json.NewEncoder(w).Encode(map[string]interface{}{"data": sampleCampaign()}) }) defer cleanup() @@ -511,7 +509,6 @@ func TestEmailCampaignsUpdateSubscriptionTopic(t *testing.T) { cmd.SetArgs([]string{"update", "--id", "4567", "--subscription-topic-id", "78"}) cmd.SetOut(buf) - // A null topic (accounts without subscription topics) prints as an empty cell. if err := cmd.Execute(); err != nil { t.Fatalf("unexpected error: %v", err) } diff --git a/internal/commands/inbound/forwardrules/create.go b/internal/commands/inbound/forwardrules/create.go index 1622648..a24decb 100644 --- a/internal/commands/inbound/forwardrules/create.go +++ b/internal/commands/inbound/forwardrules/create.go @@ -1,11 +1,8 @@ package forwardrules import ( - "bytes" "context" - "encoding/json" "fmt" - "io" "slices" "strings" @@ -32,19 +29,9 @@ type conditionInput struct { } func parseConditions(raw string) ([]conditionInput, error) { - if !strings.HasPrefix(strings.TrimSpace(raw), "[") { - return nil, fmt.Errorf("invalid --conditions: must be a JSON array") - } - - dec := json.NewDecoder(bytes.NewReader([]byte(raw))) - dec.DisallowUnknownFields() - - conditions := []conditionInput{} - if err := dec.Decode(&conditions); err != nil { - return nil, fmt.Errorf("invalid --conditions JSON: %w", err) - } - if _, err := dec.Token(); err != io.EOF { - return nil, fmt.Errorf("invalid --conditions JSON: unexpected data after the array") + conditions, err := cmdutil.ParseJSONArrayFlag[conditionInput]("conditions", raw) + if err != nil { + return nil, err } for i, cond := range conditions { diff --git a/internal/commands/webhooks/webhooks_test.go b/internal/commands/webhooks/webhooks_test.go index 7f9eea6..4432119 100644 --- a/internal/commands/webhooks/webhooks_test.go +++ b/internal/commands/webhooks/webhooks_test.go @@ -365,43 +365,6 @@ func TestWebhooksDelete(t *testing.T) { } } -func TestWebhooksCreateSubscriptionPreferencesUpdate(t *testing.T) { - f, buf, cleanup := setupTest(func(w http.ResponseWriter, r *http.Request) { - var reqBody map[string]map[string]interface{} - json.NewDecoder(r.Body).Decode(&reqBody) - - webhook := reqBody["webhook"] - if webhook["webhook_type"] != "campaigns" { - t.Errorf("unexpected webhook_type: %v", webhook["webhook_type"]) - } - if events, ok := webhook["event_types"].([]interface{}); !ok || len(events) != 1 || events[0] != "subscription_preferences_update" { - t.Errorf("expected event_types [subscription_preferences_update], got %v", webhook["event_types"]) - } - - w.Header().Set("Content-Type", "application/json") - io.WriteString(w, `{"data":{"id":11,"url":"https://example.com/hooks","active":true,"webhook_type":"campaigns",`+ - `"payload_format":"json","event_types":["subscription_preferences_update"],"signing_secret":"abc123secret"}}`) - }) - defer cleanup() - - cmd := webhooks.NewCmdWebhooks(f) - cmd.SetArgs([]string{ - "create", - "--url", "https://example.com/hooks", - "--type", "campaigns", - "--event-types", "subscription_preferences_update", - }) - cmd.SetOut(buf) - - if err := cmd.Execute(); err != nil { - t.Fatalf("unexpected error: %v", err) - } - - if !strings.Contains(buf.String(), "subscription_preferences_update") { - t.Errorf("expected output to contain the event type, got:\n%s", buf.String()) - } -} - func TestWebhooksEventTypesHelpListsSubscriptionPreferencesUpdate(t *testing.T) { f, _, cleanup := setupTest(func(w http.ResponseWriter, r *http.Request) {}) defer cleanup() From 099f0dbb41c4c5d0c41475f8fa3837bf317e9c05 Mon Sep 17 00:00:00 2001 From: Maciej Walusiak Date: Mon, 23 Nov 2026 06:22:40 +0100 Subject: [PATCH 08/10] say topic unsubscriptions need a token that can read contacts Decisions: - the API leaves topic rows out without an error for other tokens, which reads the same as having none Co-Authored-By: Claude Opus 5.5 --- docs/TEST_PLAN.md | 2 +- internal/commands/suppressions/list.go | 3 ++- skills/mailtrap-cli/references/domains.md | 2 +- skills/mailtrap-cli/references/subscription-topics.md | 2 +- 4 files changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/TEST_PLAN.md b/docs/TEST_PLAN.md index 5b6d718..8758f65 100644 --- a/docs/TEST_PLAN.md +++ b/docs/TEST_PLAN.md @@ -397,7 +397,7 @@ Prerequisite: Send an email with an attachment to the sandbox. | 23.9 | Contact topic preferences | `mailtrap contacts update --id --email --subscription-topics '[{"subscription_topic_id":,"domain_id":,"status":"unsubscribed"}]' -o json` | `subscription_topics` lists the topic as `unsubscribed` on that domain and `subscribed` on the other | | 23.10 | Invalid topic entry | `mailtrap contacts update --id --email --subscription-topics '[{"subscription_topic_id":,"status":"unsubscribed"}]'` | Error: `entry 1: domain_id must be greater than 0`; no request sent | | 23.11 | Import with topics | `mailtrap contacts import --file contacts.json` with a contact carrying `subscription_topics` | Import completes; `contacts get` shows the preference | -| 23.12 | Topic unsubscriptions | `mailtrap suppressions list --include-topic-unsubscriptions` after 23.9 | A `topic unsubscription` row with TOPIC_ID and DOMAIN_NAME; without the flag the row is absent | +| 23.12 | Topic unsubscriptions | `mailtrap suppressions list --include-topic-unsubscriptions` after 23.9 | A `topic unsubscription` row with TOPIC_ID and DOMAIN_NAME; without the flag, or with a token limited to one domain, the row is absent | | 23.13 | Topics off: list | `mailtrap subscription-topics list` | `API error 403` | | 23.14 | Topics off: campaign | `mailtrap email-campaigns create ... --subscription-topic-id 1` | Campaign saved; TOPIC ID empty | | 23.15 | Topics off: contact read | `mailtrap contacts get --id -o json` | No `subscription_topics` key, no error | diff --git a/internal/commands/suppressions/list.go b/internal/commands/suppressions/list.go index 74186c9..eb4bc43 100644 --- a/internal/commands/suppressions/list.go +++ b/internal/commands/suppressions/list.go @@ -77,7 +77,8 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command { cmd.Flags().StringVar(&startTime, "start-time", "", "Filter by start time") cmd.Flags().StringVar(&endTime, "end-time", "", "Filter by end time") cmd.Flags().StringVar(&lastID, "last-id", "", "Pagination cursor (id of the last record from the previous response)") - cmd.Flags().BoolVar(&includeTopicUnsubscriptions, "include-topic-unsubscriptions", false, "Also list unsubscriptions from single subscription topics (type 'topic unsubscription')") + cmd.Flags().BoolVar(&includeTopicUnsubscriptions, "include-topic-unsubscriptions", false, "Also list unsubscriptions from single subscription topics (type 'topic unsubscription'); "+ + "they are left out without an error unless the API token can read contacts") return cmd } diff --git a/skills/mailtrap-cli/references/domains.md b/skills/mailtrap-cli/references/domains.md index 35154f2..4a19e62 100644 --- a/skills/mailtrap-cli/references/domains.md +++ b/skills/mailtrap-cli/references/domains.md @@ -117,7 +117,7 @@ List all suppressions (bounced/unsubscribed addresses). **Note:** The endpoint returns up to 1000 suppressions per request. Page through larger result sets with `--last-id`. -With `--include-topic-unsubscriptions`, rows of type `topic unsubscription` carry the topic in `subscription_topic_id` (TOPIC_ID column); other rows have `null` there. Topic unsubscriptions can't be created or deleted with `suppressions create` / `delete`. See [subscription-topics.md](subscription-topics.md). +With `--include-topic-unsubscriptions`, rows of type `topic unsubscription` carry the topic in `subscription_topic_id` (TOPIC_ID column); other rows have `null` there. Topic rows come back only when the API token can read contacts (account-level access); a token limited to domains gets the plain suppressions with no error. Topic unsubscriptions can't be created or deleted with `suppressions create` / `delete`. See [subscription-topics.md](subscription-topics.md). --- diff --git a/skills/mailtrap-cli/references/subscription-topics.md b/skills/mailtrap-cli/references/subscription-topics.md index b4942c3..91fa2ea 100644 --- a/skills/mailtrap-cli/references/subscription-topics.md +++ b/skills/mailtrap-cli/references/subscription-topics.md @@ -58,4 +58,4 @@ mailtrap contacts update --id --email user@example.com \ ## Topic unsubscriptions -`suppressions list --include-topic-unsubscriptions` adds the contacts' unsubscriptions from single topics, with type `topic unsubscription` and the topic in `subscription_topic_id` (TOPIC_ID column). See [domains.md](domains.md). +`suppressions list --include-topic-unsubscriptions` adds the contacts' unsubscriptions from single topics, with type `topic unsubscription` and the topic in `subscription_topic_id` (TOPIC_ID column). They are left out, with no error, unless the API token can read contacts. See [domains.md](domains.md). From 1697487a85ca72008b012f063ed22c7949d78b2e Mon Sep 17 00:00:00 2001 From: Maciej Walusiak Date: Mon, 23 Nov 2026 07:29:53 +0100 Subject: [PATCH 09/10] fold contacts topic tests into shared table rows and an error helper Decisions: - the unset-flag case is a row of the payload test, as campaigns checks it inline - generic JSON array decoding is the shared parser's, already covered with --conditions - one expectError helper replaces two copies of the run-and-match-error block Co-Authored-By: Claude Opus 5.5 --- internal/commands/contacts/contacts_test.go | 110 ++++++++------------ 1 file changed, 42 insertions(+), 68 deletions(-) diff --git a/internal/commands/contacts/contacts_test.go b/internal/commands/contacts/contacts_test.go index e48696f..c8f61db 100644 --- a/internal/commands/contacts/contacts_test.go +++ b/internal/commands/contacts/contacts_test.go @@ -502,26 +502,34 @@ func TestContactsExportStatus(t *testing.T) { func TestContactsSendSubscriptionTopics(t *testing.T) { topics := `[{"subscription_topic_id":7,"domain_id":4321,"status":"unsubscribed"},{"subscription_topic_id":8,"domain_id":4322,"status":"subscribed"}]` + withTopics := map[string]interface{}{ + "email": "x@y.com", + "subscription_topics": []interface{}{ + map[string]interface{}{"subscription_topic_id": float64(7), "domain_id": float64(4321), "status": "unsubscribed"}, + map[string]interface{}{"subscription_topic_id": float64(8), "domain_id": float64(4322), "status": "subscribed"}, + }, + } + withoutTopics := map[string]interface{}{"email": "x@y.com"} // A topic-only update: the CLI still requires --email. - for _, args := range [][]string{ - {"create", "--email", "x@y.com", "--subscription-topics", topics}, - {"update", "--id", "abc-123", "--email", "x@y.com", "--subscription-topics", topics}, + for _, tc := range []struct { + name string + args []string + contact map[string]interface{} + }{ + {"create", []string{"create", "--email", "x@y.com", "--subscription-topics", topics}, withTopics}, + {"update", []string{"update", "--id", "abc-123", "--email", "x@y.com", "--subscription-topics", topics}, withTopics}, + {"create without topics", []string{"create", "--email", "x@y.com"}, withoutTopics}, + {"update without topics", []string{"update", "--id", "abc-123", "--email", "x@y.com"}, withoutTopics}, } { - t.Run(args[0], func(t *testing.T) { + t.Run(tc.name, func(t *testing.T) { f, buf, cleanup := setupTest(func(w http.ResponseWriter, r *http.Request) { var payload map[string]interface{} if err := json.NewDecoder(r.Body).Decode(&payload); err != nil { t.Fatalf("failed to decode body: %v", err) } - want := map[string]interface{}{"contact": map[string]interface{}{ - "email": "x@y.com", - "subscription_topics": []interface{}{ - map[string]interface{}{"subscription_topic_id": float64(7), "domain_id": float64(4321), "status": "unsubscribed"}, - map[string]interface{}{"subscription_topic_id": float64(8), "domain_id": float64(4322), "status": "subscribed"}, - }, - }} + want := map[string]interface{}{"contact": tc.contact} if !reflect.DeepEqual(payload, want) { t.Errorf("expected body %v, got %v", want, payload) } @@ -532,7 +540,7 @@ func TestContactsSendSubscriptionTopics(t *testing.T) { defer cleanup() cmd := contacts.NewCmdContacts(f) - cmd.SetArgs(args) + cmd.SetArgs(tc.args) cmd.SetOut(buf) if err := cmd.Execute(); err != nil { @@ -542,44 +550,33 @@ func TestContactsSendSubscriptionTopics(t *testing.T) { } } -func TestContactsOmitSubscriptionTopicsWhenUnset(t *testing.T) { - for _, args := range [][]string{ - {"create", "--email", "x@y.com"}, - {"update", "--id", "abc-123", "--email", "x@y.com"}, - } { - t.Run(args[0], func(t *testing.T) { - f, buf, cleanup := setupTest(func(w http.ResponseWriter, r *http.Request) { - var payload map[string]map[string]interface{} - json.NewDecoder(r.Body).Decode(&payload) - if _, ok := payload["contact"]["subscription_topics"]; ok { - t.Errorf("did not expect subscription_topics, got %v", payload["contact"]) - } - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(`{"data":{"id":"abc-123","email":"x@y.com"}}`)) - }) - defer cleanup() +// expectError runs the contacts command against handler and checks it fails with want. +func expectError(t *testing.T, handler http.HandlerFunc, args []string, want string) { + t.Helper() - cmd := contacts.NewCmdContacts(f) - cmd.SetArgs(args) - cmd.SetOut(buf) + f, _, cleanup := setupTest(handler) + defer cleanup() - if err := cmd.Execute(); err != nil { - t.Fatalf("unexpected error: %v", err) - } - }) + cmd := contacts.NewCmdContacts(f) + cmd.SetArgs(args) + cmd.SilenceUsage = true + cmd.SilenceErrors = true + + err := cmd.Execute() + if err == nil || !strings.Contains(err.Error(), want) { + t.Fatalf("expected error containing %q, got: %v", want, err) } } func TestContactsInvalidSubscriptionTopics(t *testing.T) { + // Malformed JSON, unknown keys and trailing data are cmdutil.ParseJSONArrayFlag's, + // covered with --conditions in the forwardrules tests. cases := []struct { name string value string want string }{ - {"not an array", `{"subscription_topic_id":7,"domain_id":4321,"status":"subscribed"}`, "must be a JSON array"}, - {"malformed", `[{"subscription_topic_id":7`, "invalid --subscription-topics JSON"}, - {"unknown key", `[{"subscription_topic_id":7,"domain_id":4321,"status":"subscribed","name":"News"}]`, `unknown field "name"`}, - {"trailing data", `[{"subscription_topic_id":7,"domain_id":4321,"status":"subscribed"}] []`, "unexpected data after the array"}, + {"not an array", `{"subscription_topic_id":7,"domain_id":4321,"status":"subscribed"}`, "invalid --subscription-topics: must be a JSON array"}, {"string id", `[{"subscription_topic_id":"7","domain_id":4321,"status":"subscribed"}]`, "invalid --subscription-topics JSON"}, {"missing topic", `[{"domain_id":4321,"status":"subscribed"}]`, "entry 1: subscription_topic_id must be greater than 0"}, {"missing domain", `[{"subscription_topic_id":7,"domain_id":4321,"status":"subscribed"},{"subscription_topic_id":7,"status":"subscribed"}]`, "entry 2: domain_id must be greater than 0"}, @@ -587,31 +584,18 @@ func TestContactsInvalidSubscriptionTopics(t *testing.T) { {"null entry", `[null]`, "entry 1: subscription_topic_id must be greater than 0"}, } - run := func(t *testing.T, args []string, want string) { - f, _, cleanup := setupTest(func(w http.ResponseWriter, r *http.Request) { - t.Error("unexpected request") - }) - defer cleanup() - - cmd := contacts.NewCmdContacts(f) - cmd.SetArgs(args) - cmd.SilenceUsage = true - cmd.SilenceErrors = true - - err := cmd.Execute() - if err == nil || !strings.Contains(err.Error(), want) { - t.Fatalf("expected error containing %q, got: %v", want, err) - } + noRequest := func(w http.ResponseWriter, r *http.Request) { + t.Error("unexpected request") } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - run(t, []string{"create", "--email", "x@y.com", "--subscription-topics", tc.value}, tc.want) + expectError(t, noRequest, []string{"create", "--email", "x@y.com", "--subscription-topics", tc.value}, tc.want) }) } // update shares the parser; one case shows it is wired in. t.Run("update", func(t *testing.T) { - run(t, []string{"update", "--id", "abc-123", "--email", "x@y.com", "--subscription-topics", `[{"subscription_topic_id":7}]`}, + expectError(t, noRequest, []string{"update", "--id", "abc-123", "--email", "x@y.com", "--subscription-topics", `[{"subscription_topic_id":7}]`}, "entry 1: domain_id must be greater than 0") }) } @@ -676,22 +660,12 @@ func TestContactsSubscriptionTopicsErrorsKeepMessage(t *testing.T) { for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - f, _, cleanup := setupTest(func(w http.ResponseWriter, r *http.Request) { + handler := func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(tc.status) io.WriteString(w, tc.body) - }) - defer cleanup() - - cmd := contacts.NewCmdContacts(f) - cmd.SetArgs([]string{"create", "--email", "x@y.com", "--subscription-topics", `[{"subscription_topic_id":7,"domain_id":4321,"status":"subscribed"}]`}) - cmd.SilenceUsage = true - cmd.SilenceErrors = true - - err := cmd.Execute() - if err == nil || !strings.Contains(err.Error(), tc.want) { - t.Fatalf("expected error containing %q, got: %v", tc.want, err) } + expectError(t, handler, []string{"create", "--email", "x@y.com", "--subscription-topics", `[{"subscription_topic_id":7,"domain_id":4321,"status":"subscribed"}]`}, tc.want) }) } } From 08480fc459d30dcad36d0418c92fa7bc952f86d8 Mon Sep 17 00:00:00 2001 From: Maciej Walusiak Date: Mon, 23 Nov 2026 07:41:06 +0100 Subject: [PATCH 10/10] note that contacts update needs --email and topic rows need contacts read Decisions: - contacts update rejects a call without --email, so a topic-only update and the 503 retry hint need it documented as required - the README example would list suppressions without topic rows, and no error, when the token can't read contacts Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- docs/TEST_PLAN.md | 2 +- skills/mailtrap-cli/references/contacts.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 4a03083..1bd07da 100644 --- a/README.md +++ b/README.md @@ -121,7 +121,7 @@ mailtrap company-info create --domain-id 123 --name "Your Company" --address "12 --city "San Francisco" --country US --zip-code 94105 --website-url "https://yourdomain.com" mailtrap company-info update --domain-id 123 --city "New York" --zip-code 10001 -# Suppressions +# Suppressions (--include-topic-unsubscriptions needs a token that can read contacts; without it, topic rows are left out silently) mailtrap suppressions list --email "bounced@example.com" mailtrap suppressions list --include-topic-unsubscriptions mailtrap suppressions create --email "bounced@example.com" --domain-id 123 --sending-stream transactional diff --git a/docs/TEST_PLAN.md b/docs/TEST_PLAN.md index 8758f65..7cbc6f6 100644 --- a/docs/TEST_PLAN.md +++ b/docs/TEST_PLAN.md @@ -199,7 +199,7 @@ Tests are organized by endpoint group. Each test specifies: |---|------|---------|----------| | 10.1 | Create contact | `mailtrap contacts create --email "test@integration.com"` | New contact in output | | 10.2 | Get contact | `mailtrap contacts get --id ` | Single contact details | -| 10.3 | Update contact | `mailtrap contacts update --id --first-name "Test"` | Updated contact | +| 10.3 | Update contact | `mailtrap contacts update --id --email "test@integration.com" --first-name "Test"` | Updated contact | | 10.4 | List contacts | `mailtrap contacts list` | Table with contacts (may 404 — investigate) | | 10.5 | Import contacts | `mailtrap contacts import --file contacts.csv` | Import initiated | | 10.6 | Import status | `mailtrap contacts import-status --id ` | Status details | diff --git a/skills/mailtrap-cli/references/contacts.md b/skills/mailtrap-cli/references/contacts.md index 48d7efb..2d42763 100644 --- a/skills/mailtrap-cli/references/contacts.md +++ b/skills/mailtrap-cli/references/contacts.md @@ -44,7 +44,7 @@ Update an existing contact. | Flag | Type | Required | Description | |------|------|----------|-------------| | `--id` | string | Yes | Contact ID | -| `--email` | string | No | New email address | +| `--email` | string | Yes | Contact email address, also for a topic-only update (pass the current one to keep it) | | `--first-name` | string | No | New first name | | `--last-name` | string | No | New last name | | `--subscription-topics` | string | No | Subscription topic preferences as a JSON array, as for `contacts create`; pairs left out keep their status |