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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions internal/cmd/products/additional_detail_flags.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package products

import (
"fmt"
"net/url"
"regexp"
"strings"

"github.com/antiwork/gumroad-cli/internal/cmdutil"
"github.com/spf13/cobra"
)

// One row of the product editor's Additional details.
type additionalDetail struct {
Name string
Value string
}

// The keys setAdditionalDetailParams writes, read back when a JSON body has to carry the rows.
var additionalDetailParamPattern = regexp.MustCompile(`^additional_details\[(\d+)\]\[(name|value)\]$`)

func registerAdditionalDetailFlags(cmd *cobra.Command, additionalDetails *[]string) {
cmd.Flags().StringArrayVar(additionalDetails, "additional-detail", nil, "Additional detail as \"Name: value\" (repeatable; replaces the whole list, and \"\" clears it)")
}

// parseAdditionalDetailFlags reads the repeatable --additional-detail values ("Pages: 40").
// The flag replaces the whole list, so a single empty value is the clear signal. The editor keeps a
// row by its name, so a value with no name is refused here as the API refuses it.
func parseAdditionalDetailFlags(c *cobra.Command, values []string) ([]additionalDetail, error) {
rows := make([]additionalDetail, 0, len(values))
for _, value := range values {
name, val, _ := strings.Cut(value, ":")
name, val = strings.TrimSpace(name), strings.TrimSpace(val)
if name == "" {
if val != "" {
return nil, cmdutil.UsageErrorf(c, "--additional-detail %q needs a name, e.g. \"Pages: 40\"", value)
}
continue
}
rows = append(rows, additionalDetail{Name: name, Value: val})
}
return rows, nil
}

// setAdditionalDetailParams writes each row under its own index, Rails' collection encoding
// (additional_details[0][name]). The index is in the key, so the rows arrive in order however the
// client emits them. An empty list still sends one empty row, because the param replaces the whole
// list and that row is what drops the existing ones.
func setAdditionalDetailParams(params url.Values, rows []additionalDetail) {
if len(rows) == 0 {
rows = []additionalDetail{{}}
}
for i, row := range rows {
params.Set(fmt.Sprintf("additional_details[%d][name]", i), row.Name)
params.Set(fmt.Sprintf("additional_details[%d][value]", i), row.Value)
}
}
183 changes: 183 additions & 0 deletions internal/cmd/products/additional_detail_flags_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
package products

import (
"fmt"
"net/http"
"net/url"
"reflect"
"strings"
"testing"

"github.com/antiwork/gumroad-cli/internal/testutil"
)

func TestCreate_AdditionalDetailsSendRows(t *testing.T) {
var gotMethod, gotPath string
var gotForm url.Values
testutil.Setup(t, func(w http.ResponseWriter, r *http.Request) {
gotMethod, gotPath = r.Method, r.URL.Path
_ = r.ParseForm()
gotForm = r.PostForm
testutil.JSON(t, w, map[string]any{
"product": map[string]any{"id": "p1", "name": "E-Book", "formatted_price": "$5"},
})
})

cmd := testutil.Command(newCreateCmd(), testutil.Quiet(false))
cmd.SetArgs([]string{"--name", "E-Book", "--price", "5", "--additional-detail", "Pages: 40", "--additional-detail", "Format: PDF"})
testutil.CaptureStdout(func() { testutil.MustExecute(t, cmd) })

if gotMethod != "POST" || gotPath != "/products" {
t.Errorf("got %s %s, want POST /products", gotMethod, gotPath)
}
assertAdditionalDetailForm(t, gotForm, []string{"Pages", "Format"}, []string{"40", "PDF"})
}

func TestCreate_AdditionalDetailNameWithoutValueIsSent(t *testing.T) {
var gotForm url.Values
testutil.Setup(t, func(w http.ResponseWriter, r *http.Request) {
_ = r.ParseForm()
gotForm = r.PostForm
testutil.JSON(t, w, map[string]any{
"product": map[string]any{"id": "p1", "name": "E-Book", "formatted_price": "$5"},
})
})

cmd := testutil.Command(newCreateCmd(), testutil.Quiet(false))
cmd.SetArgs([]string{"--name", "E-Book", "--additional-detail", "Pages:"})
testutil.CaptureStdout(func() { testutil.MustExecute(t, cmd) })

assertAdditionalDetailForm(t, gotForm, []string{"Pages"}, []string{""})
}

func TestCreate_AdditionalDetailsOmittedWhenFlagUnset(t *testing.T) {
var hasRows bool
testutil.Setup(t, func(w http.ResponseWriter, r *http.Request) {
_ = r.ParseForm()
for key := range r.PostForm {
if additionalDetailParamPattern.MatchString(key) {
hasRows = true
}
}
testutil.JSON(t, w, map[string]any{
"product": map[string]any{"id": "p1", "name": "Art Pack", "formatted_price": "$10"},
})
})

cmd := testutil.Command(newCreateCmd(), testutil.Quiet(false))
cmd.SetArgs([]string{"--name", "Art Pack", "--price", "10"})
testutil.CaptureStdout(func() { testutil.MustExecute(t, cmd) })

if hasRows {
t.Errorf("additional detail params should not be sent when the flag is unset")
}
}

func TestCreate_AdditionalDetailWithoutNameIsRejected(t *testing.T) {
reached := false
testutil.Setup(t, func(w http.ResponseWriter, r *http.Request) {
reached = true
testutil.JSON(t, w, map[string]any{})
})

cmd := testutil.Command(newCreateCmd(), testutil.Quiet(false))
cmd.SetArgs([]string{"--name", "E-Book", "--additional-detail", ": 40"})
err := cmd.Execute()
if err == nil {
t.Fatalf("expected an error for a value with no name")
}
if !strings.Contains(err.Error(), "--additional-detail \": 40\" needs a name") {
t.Errorf("unexpected error: %v", err)
}
if reached {
t.Errorf("API should not be reached when a row is refused")
}
}

func TestUpdate_AdditionalDetailsReplaceRows(t *testing.T) {
var gotMethod, gotPath string
var gotForm url.Values
testutil.Setup(t, func(w http.ResponseWriter, r *http.Request) {
gotMethod, gotPath = r.Method, r.URL.Path
_ = r.ParseForm()
gotForm = r.PostForm
testutil.JSON(t, w, map[string]any{})
})

cmd := testutil.Command(newUpdateCmd(), testutil.Quiet(false))
cmd.SetArgs([]string{"prod1", "--additional-detail", "Format: PDF"})
testutil.CaptureStdout(func() { testutil.MustExecute(t, cmd) })

if gotMethod != "PUT" || gotPath != "/products/prod1" {
t.Errorf("got %s %s, want PUT /products/prod1", gotMethod, gotPath)
}
assertAdditionalDetailForm(t, gotForm, []string{"Format"}, []string{"PDF"})
}

func TestUpdate_AdditionalDetailEmptyValueClears(t *testing.T) {
var gotForm url.Values
testutil.Setup(t, func(w http.ResponseWriter, r *http.Request) {
_ = r.ParseForm()
gotForm = r.PostForm
testutil.JSON(t, w, map[string]any{})
})

cmd := testutil.Command(newUpdateCmd(), testutil.Quiet(false))
cmd.SetArgs([]string{"prod1", "--additional-detail", ""})
testutil.CaptureStdout(func() { testutil.MustExecute(t, cmd) })

assertAdditionalDetailForm(t, gotForm, []string{""}, []string{""})
}

func TestUpdate_AdditionalDetailAloneSatisfiesRequireAnyFlag(t *testing.T) {
testutil.Setup(t, func(w http.ResponseWriter, r *http.Request) {
testutil.JSON(t, w, map[string]any{})
})

cmd := testutil.Command(newUpdateCmd(), testutil.Quiet(false))
cmd.SetArgs([]string{"prod1", "--additional-detail", "Pages: 40"})
testutil.CaptureStdout(func() { testutil.MustExecute(t, cmd) })
}

func TestBuildProductJSONBody_FoldsAdditionalDetailRows(t *testing.T) {
params := url.Values{}
setAdditionalDetailParams(params, []additionalDetail{{Name: "Pages", Value: "40"}, {Name: "Format", Value: "PDF"}})

body := buildProductJSONBody(params, nil)

for key := range body {
if additionalDetailParamPattern.MatchString(key) {
t.Fatalf("the form keys should not reach the body: %v", body)
}
}
want := []map[string]any{{"name": "Pages", "value": "40"}, {"name": "Format", "value": "PDF"}}
if !reflect.DeepEqual(body["additional_details"], want) {
t.Errorf("got %v, want %v", body["additional_details"], want)
}
}

func TestBuildProductJSONBody_CarriesTheClearingRow(t *testing.T) {
params := url.Values{}
setAdditionalDetailParams(params, nil)

body := buildProductJSONBody(params, nil)

want := []map[string]any{{"name": "", "value": ""}}
if !reflect.DeepEqual(body["additional_details"], want) {
t.Errorf("got %v, want %v", body["additional_details"], want)
}
}

func assertAdditionalDetailForm(t *testing.T, form url.Values, names, values []string) {
t.Helper()
for i := range names {
nameKey := fmt.Sprintf("additional_details[%d][name]", i)
valueKey := fmt.Sprintf("additional_details[%d][value]", i)
if got := form.Get(nameKey); got != names[i] {
t.Errorf("%s: got %q, want %q", nameKey, got, names[i])
}
if got := form.Get(valueKey); got != values[i] {
t.Errorf("%s: got %q, want %q", valueKey, got, values[i])
}
}
}
12 changes: 11 additions & 1 deletion internal/cmd/products/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ func newCreateCmd() *cobra.Command {
var previewImages []string
var previewVideos []string
var refundPeriod, refundFinePrint string
var additionalDetails []string

cmd := &cobra.Command{
Use: "create",
Expand All @@ -108,7 +109,8 @@ func newCreateCmd() *cobra.Command {
gumroad products create --name "Figma Kit" --category design/ui-and-web/figma
gumroad products create --name "Newsletter" --type membership --subscription-duration monthly
gumroad products create --name "E-Book" --type ebook --price 5 --tag art --tag digital
gumroad products create --name "Art Pack" --price 10 --refund-period none --refund-fine-print "No refunds once downloaded."`,
gumroad products create --name "Art Pack" --price 10 --refund-period none --refund-fine-print "No refunds once downloaded."
gumroad products create --name "E-Book" --price 5 --additional-detail "Pages: 40" --additional-detail "Format: PDF"`,
Args: cmdutil.ExactArgs(0),
RunE: func(c *cobra.Command, args []string) error {
opts := cmdutil.OptionsFrom(c)
Expand Down Expand Up @@ -140,6 +142,10 @@ func newCreateCmd() *cobra.Command {
if err := validateProductRefundPolicyFlags(c, refundPeriod); err != nil {
return err
}
additionalDetailList, err := parseAdditionalDetailFlags(c, additionalDetails)
if err != nil {
return err
}

plannedUploads, err := planCreateUploads(c, files, fileNames, fileDescriptions)
if err != nil {
Expand Down Expand Up @@ -208,6 +214,9 @@ func newCreateCmd() *cobra.Command {
params.Add("tags[]", t)
}
setProductRefundPolicyParams(c, params, refundPeriod, refundFinePrint)
if flags.Changed("additional-detail") {
setAdditionalDetailParams(params, additionalDetailList)
}

if len(plannedUploads) > 0 || len(media) > 0 {
fileRefs, err := newRichContentFileRefs(len(plannedUploads))
Expand Down Expand Up @@ -318,6 +327,7 @@ func newCreateCmd() *cobra.Command {
cmd.Flags().StringArrayVar(&previewVideos, "preview-video", nil, "Local MP4, MOV, M4V, MPEG, WMV, or WebM preview video to upload as a product cover (repeatable)")
cmd.Flags().StringVar(&thumbnail, "thumbnail", "", "Local JPEG, PNG, or GIF thumbnail image to upload after creating the product")
registerProductRefundPolicyFlags(cmd, &refundPeriod, &refundFinePrint)
registerAdditionalDetailFlags(cmd, &additionalDetails)

return cmd
}
Expand Down
23 changes: 23 additions & 0 deletions internal/cmd/products/products_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1731,6 +1731,29 @@ func TestView_WithDescription(t *testing.T) {
}
}

func TestView_AdditionalDetails(t *testing.T) {
testutil.Setup(t, func(w http.ResponseWriter, r *http.Request) {
testutil.JSON(t, w, map[string]any{
"product": map[string]any{
"id": "p1", "name": "Book", "published": true,
"formatted_price": "$20", "sales_count": 5, "sales_usd_cents": 10000,
"additional_details": []map[string]any{
{"name": "Pages", "value": "40"},
{"name": "Format", "value": "PDF"},
},
},
})
})

cmd := newViewCmd()
out := testutil.CaptureStdout(func() { _ = cmd.RunE(cmd, []string{"p1"}) })
for _, want := range []string{"Additional details", "Pages: 40", "Format: PDF"} {
if !strings.Contains(out, want) {
t.Errorf("missing %q: %q", want, out)
}
}
}

func TestList_DraftStatus(t *testing.T) {
testutil.Setup(t, func(w http.ResponseWriter, r *http.Request) {
testutil.JSON(t, w, map[string]any{
Expand Down
15 changes: 14 additions & 1 deletion internal/cmd/products/update.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ func newUpdateCmd() *cobra.Command {
var previewVideos []string
var customHTML string
var refundPeriod, refundFinePrint string
var additionalDetails []string

cmd := &cobra.Command{
Use: "update <product_id>",
Expand All @@ -45,7 +46,9 @@ func newUpdateCmd() *cobra.Command {
gumroad products update <id> --custom-html ./landing.html
gumroad products update <id> --custom-html ''
gumroad products update <id> --refund-period none --refund-fine-print "No refunds once downloaded."
gumroad products update <id> --refund-period inherit`,
gumroad products update <id> --refund-period inherit
gumroad products update <id> --additional-detail "Pages: 40" --additional-detail "Format: PDF"
gumroad products update <id> --additional-detail ''`,
Args: cmdutil.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
opts := cmdutil.OptionsFrom(c)
Expand All @@ -54,6 +57,7 @@ func newUpdateCmd() *cobra.Command {
if err := cmdutil.RequireAnyFlagChanged(c,
"name", "price", "currency", "description",
"custom-permalink", "custom-summary", "custom-receipt",
"additional-detail",
"pay-what-you-want", "suggested-price", "max-purchase-count",
"category", "taxonomy-id", "tag",
"file", "file-name", "file-description", "page",
Expand All @@ -67,6 +71,10 @@ func newUpdateCmd() *cobra.Command {
if err := validateProductRefundPolicyFlags(c, refundPeriod); err != nil {
return err
}
additionalDetailList, err := parseAdditionalDetailFlags(c, additionalDetails)
if err != nil {
return err
}

if flags.Changed("name") && name == "" {
return cmdutil.UsageErrorf(c, "--name cannot be empty")
Expand Down Expand Up @@ -155,6 +163,9 @@ func newUpdateCmd() *cobra.Command {
params.Add("tags[]", t)
}
setProductRefundPolicyParams(c, params, refundPeriod, refundFinePrint)
if flags.Changed("additional-detail") {
setAdditionalDetailParams(params, additionalDetailList)
}
fileFlagsChanged := flags.Changed("file") ||
flags.Changed("file-name") ||
flags.Changed("file-description") ||
Expand Down Expand Up @@ -322,6 +333,7 @@ func newUpdateCmd() *cobra.Command {
cmd.Flags().StringVar(&thumbnail, "thumbnail", "", "Local JPEG, PNG, or GIF thumbnail image to upload")
cmd.Flags().StringVar(&customHTML, "custom-html", "", "Path to an HTML file for the product's custom landing page, up to 500,000 characters (empty string clears it)")
registerProductRefundPolicyFlags(cmd, &refundPeriod, &refundFinePrint)
registerAdditionalDetailFlags(cmd, &additionalDetails)

return cmd
}
Expand All @@ -330,6 +342,7 @@ func productUpdateFieldFlagsChanged(cmd *cobra.Command) bool {
for _, flag := range []string{
"name", "price", "currency", "description",
"custom-permalink", "custom-summary", "custom-receipt",
"additional-detail",
"pay-what-you-want", "suggested-price", "max-purchase-count",
"category", "taxonomy-id", "tag", "custom-html",
"refund-period", "refund-fine-print",
Expand Down
Loading
Loading