From 8d897ebfa53fd040188a05a6f02ecc5fe604e966 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Frank=20La=CC=88mmer?= Date: Sat, 28 Nov 2026 17:10:28 +0100 Subject: [PATCH] FR-7293: price components update with the API dry run Drops the CLI's own price calculation, the catalog and app lookups and --region. Adds --dry-run. Co-Authored-By: Claude Opus 5.5 --- docs/cli.md | 3 +- internal/cmd/environments/settings.go | 170 +------------- internal/cmd/environments/settings_test.go | 243 +++++++-------------- internal/cmd/environments/target_test.go | 4 +- internal/cmd/root/root_test.go | 2 +- internal/cmdutil/billing.go | 73 ++++++- 6 files changed, 153 insertions(+), 342 deletions(-) diff --git a/docs/cli.md b/docs/cli.md index 7134a61..1424143 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -380,6 +380,7 @@ frbit environments firewall-rules create en-a1b2c3 --description "Metrics export frbit environments firewall-rules delete fr-a1b2c3 --confirm fr-a1b2c3 frbit environments components get en-a1b2c3 +frbit environments components update en-a1b2c3 --component php=md --dry-run frbit environments components update en-a1b2c3 --component php=md --component database=off --yes ``` @@ -387,7 +388,7 @@ frbit environments components update en-a1b2c3 --component php=md --component da - The basic auth password is read as one line from stdin and is never a flag or part of any output. Pipe it in; a password typed on a terminal is echoed. Omit `--password-stdin` to keep the current password. - `--port N` opens one port, `--port N-M` a range of at most 1000 ports, within 1-65535. - `firewall-rules delete` needs the exact rule ID: typed on a terminal, or `--confirm ` without one. -- `components update` looks up each size in the catalog first (an unknown size is an error before any request; a changed component whose old or new price is unknown fails with `price for unknown; check frbit plans list or change it in the dashboard`, before the question and also with `--yes`, so nothing is booked at an unseen price), prints `slug: old (price) -> new (price)` per changed component and the signed `Monthly change` to stderr (priced in the region of the environment's app; `--region` overrides, and the command fails before any change if the region can't be resolved), skips components already at the requested size (nothing changes: `No component plan changes.`), and asks `Change component plans? [y/N]`, also for a downsize. Without a terminal it fails with `billed change needs --yes`. The change is applied asynchronously (202). +- `components update` sends the change as a dry run first: the API checks it like the real change (an unknown size or a refused change is an error before anything changes) and returns the monthly price after the change and the payment method, printed to stderr. A billed change asks `Change and bill the new price? [y/N]`, also for a downsize; a trial app or a free environment does not ask. Without a terminal it fails with `billed change needs --yes`. `--dry-run` prints the price and changes nothing (with `--json`, the API response). The change is applied asynchronously (202). ### Metrics diff --git a/internal/cmd/environments/settings.go b/internal/cmd/environments/settings.go index cfb775b..a5d056d 100644 --- a/internal/cmd/environments/settings.go +++ b/internal/cmd/environments/settings.go @@ -5,7 +5,6 @@ import ( "fmt" "io" "net/url" - "sort" "strconv" "strings" "text/tabwriter" @@ -363,12 +362,11 @@ func newCmdComponentsGet(factory *app.Factory) *cobra.Command { func newCmdComponentsUpdate(factory *app.Factory) *cobra.Command { var componentValues []string - var region string - var yes, printJSON bool + var yes, dryRun, printJSON bool command := &cobra.Command{ Use: "update --component SLUG=SIZE", Short: "Change component sizes (billed)", - Long: "Change component sizes (billed). Slugs: php, database, storage, traffic, key-value-store, backups, jobs. Sizes: 'frbit plans list'; optional components accept off. Shows old -> new price per changed component and the monthly change, priced in the environment's region, and asks first, also for a downsize. Components already at the requested size are skipped; if nothing changes, nothing is sent.", + Long: "Change component sizes (billed). Slugs: php, database, storage, traffic, key-value-store, backups, jobs. Sizes: 'frbit plans list'; optional components accept off. The API checks the change and prices it first: the monthly price after the change and the payment method are shown, and a billed change asks before it applies, also for a downsize. A trial app or a change to a free environment does not ask.", Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { components, err := cmdutil.ParseAssignments(componentValues) @@ -386,45 +384,22 @@ func newCmdComponentsUpdate(factory *app.Factory) *cobra.Command { if err != nil { return err } - current, err := client.GetResource(cmd.Context(), "/v1/environments/"+url.PathEscape(env)+"/components") - if err != nil { - return err - } - components, err = changedComponents(current.Resource, components) - if err != nil { - return err - } - if len(components) == 0 { - if _, err := fmt.Fprintln(cmd.ErrOrStderr(), "No component plan changes."); err != nil || !printJSON { - return err - } - return resource.WriteRaw(cmd, current.Raw) - } - if region == "" { - if region, err = environmentRegion(cmd, client, env); err != nil { - return err - } - } - plans, err := client.ListResources(cmd.Context(), "/v1/catalog/component-plans", 0, nil, map[string]string{"currency": currentCurrency(current.Resource), "region": region}) - if err != nil { - return err + path := "/v1/environments/" + url.PathEscape(env) + "/components" + payload := make(map[string]any, len(components)) + for slug, size := range components { + payload[slug] = size } - summary, err := componentChangeSummary(current.Resource, plans.Resources, components) - if err != nil { - return err + if dryRun { + return cmdutil.DryRunBilledChange(cmd, client, path, payload, printJSON) } - confirmed, err := cmdutil.AskBilled(cmd, factory, summary, "Change component plans? [y/N] ", yes) + confirmed, err := cmdutil.ConfirmBilledChange(cmd, factory, client, path, payload, yes) if err != nil { return err } if !confirmed { return cmdutil.Aborted(cmd.ErrOrStderr()) } - payload := make(map[string]any, len(components)) - for slug, size := range components { - payload[slug] = size - } - response, err := client.UpdateResource(cmd.Context(), "/v1/environments/"+url.PathEscape(env)+"/components", payload) + response, err := client.UpdateResource(cmd.Context(), path, payload) if err != nil { return err } @@ -435,131 +410,8 @@ func newCmdComponentsUpdate(factory *app.Factory) *cobra.Command { }, } command.Flags().StringArrayVar(&componentValues, "component", nil, "Component as SLUG=SIZE (repeatable)") - command.Flags().StringVar(®ion, "region", "", "Region identifier to price the plans in (default: the region of the environment's app)") command.Flags().BoolVar(&yes, "yes", false, "Confirm billing without asking") + command.Flags().BoolVar(&dryRun, "dry-run", false, "Show the monthly price after the change and change nothing (with --json, the API response)") command.Flags().BoolVar(&printJSON, "json", false, "Print the API response as JSON") return command } - -// environmentRegion finds the app that lists the environment and returns its region. -func environmentRegion(cmd *cobra.Command, client *api.Client, environmentID string) (string, error) { - apps, err := client.ListAll(cmd.Context(), "/v1/apps", nil, 0) - if err != nil { - return "", err - } - for _, appResource := range apps.Resources { - environments, _ := appResource["environments"].([]any) - for _, raw := range environments { - id, _ := raw.(string) - if id == environmentID || strings.HasSuffix(id, "/"+environmentID) { - if region, _ := appResource["region"].(string); region != "" { - return region, nil - } - } - } - } - return "", fmt.Errorf("could not resolve the environment's region; pass --region") -} - -// changedComponents keeps only the requested components whose size differs from the booked one. -func changedComponents(current api.Resource, components map[string]string) (map[string]string, error) { - booked := map[string]string{} - items, _ := current["components"].([]any) - for _, raw := range items { - item, _ := raw.(map[string]any) - slug, _ := item["slug"].(string) - size, _ := item["size"].(string) - booked[slug] = size - } - changed := map[string]string{} - for slug, size := range components { - old, ok := booked[slug] - if !ok { - return nil, fmt.Errorf("environment has no component %s", slug) - } - if old != size { - changed[slug] = size - } - } - return changed, nil -} - -func currentCurrency(current api.Resource) string { - items, _ := current["components"].([]any) - for _, raw := range items { - item, _ := raw.(map[string]any) - if currency, _ := item["currency"].(string); currency != "" { - return currency - } - } - return "EUR" -} - -// componentChangeSummary shows old and new price per named component and the signed monthly delta; an unknown slug, size or price is an error. -func componentChangeSummary(current api.Resource, plans []api.Resource, components map[string]string) (string, error) { - type booked struct { - size string - cents float64 - known bool - } - bookedPlans := map[string]booked{} - items, _ := current["components"].([]any) - for _, raw := range items { - item, _ := raw.(map[string]any) - slug, _ := item["slug"].(string) - size, _ := item["size"].(string) - cents, known := item["priceInCents"].(float64) - bookedPlans[slug] = booked{size, cents, known || size == "off"} - } - slugs := make([]string, 0, len(components)) - for slug := range components { - slugs = append(slugs, slug) - } - sort.Strings(slugs) - currency := currentCurrency(current) - var lines []string - var delta float64 - for _, slug := range slugs { - size := components[slug] - old, isBooked := bookedPlans[slug] - if !isBooked { - return "", fmt.Errorf("environment has no component %s", slug) - } - found := false - for _, plan := range plans { - if plan["slug"] != slug { - continue - } - sizes, _ := plan["sizes"].([]any) - for _, raw := range sizes { - entry, _ := raw.(map[string]any) - if entry["size"] != size { - continue - } - found = true - cents, known := entry["priceInCents"].(float64) - known = known || size == "off" - if entryCurrency, _ := entry["currency"].(string); entryCurrency != "" && entryCurrency != currency { - return "", fmt.Errorf("catalog prices %s in %s but the environment is billed in %s", slug, entryCurrency, currency) - } - // A billed change never goes through on a price nobody has seen, as with billed creates. - if !old.known { - return "", unknownPrice(slug, old.size) - } - if !known { - return "", unknownPrice(slug, size) - } - delta += cents - old.cents - lines = append(lines, fmt.Sprintf("%s: %s (%.2f %s) -> %s (%.2f %s)", slug, old.size, old.cents/100, currency, size, cents/100, currency)) - } - } - if !found { - return "", fmt.Errorf("component %s has no size %q in the catalog; see 'frbit plans list'", slug, size) - } - } - return fmt.Sprintf("%s\nMonthly change: %+.2f %s", strings.Join(lines, "\n"), delta/100, currency), nil -} - -func unknownPrice(slug, size string) error { - return fmt.Errorf("price for %s %s unknown; check frbit plans list or change it in the dashboard", slug, size) -} diff --git a/internal/cmd/environments/settings_test.go b/internal/cmd/environments/settings_test.go index 9ecf752..fdbae22 100644 --- a/internal/cmd/environments/settings_test.go +++ b/internal/cmd/environments/settings_test.go @@ -11,7 +11,6 @@ import ( "strings" "testing" - "github.com/fortrabbit/frbit-cli/internal/api" "github.com/fortrabbit/frbit-cli/internal/app" "github.com/fortrabbit/frbit-cli/internal/iostreams" "github.com/spf13/cobra" @@ -199,86 +198,103 @@ func TestFirewallRuleDeleteNeedsConfirm(t *testing.T) { } } -const catalog = `[{"slug":"php","optional":false,"sizes":[{"size":"sm","priceInCents":1200,"currency":"EUR"},{"size":"md","priceInCents":2400,"currency":"EUR"}]},{"slug":"database","optional":true,"sizes":[{"size":"off","priceInCents":null,"currency":"EUR"},{"size":"sm","priceInCents":800,"currency":"EUR"}]}]` +const billedPricing = `{"monthlyPriceInCents":2400,"currency":"EUR","billed":true,"trialEndsAt":null,"components":[{"slug":"php","size":"md","priceInCents":2400}]}` -const current = `{"components":[{"slug":"php","size":"sm","priceInCents":1200,"currency":"EUR"},{"slug":"database","size":"sm","priceInCents":800,"currency":"EUR"}]}` +const trialPricing = `{"monthlyPriceInCents":2400,"currency":"EUR","billed":false,"trialEndsAt":"2026-12-01T00:00:00+00:00","components":[{"slug":"php","size":"md","priceInCents":2400}]}` -func componentsHandler(r request, w http.ResponseWriter) { - if r.method == "GET" && r.path == "/v1/environments/en-a1b2c3/components" { - echo(w, 200, current) - return - } - if r.path == "/v1/apps" { - echo(w, 200, `[{"publicId":"ap-1","region":"eu-w1a","environments":["en-zzz","en-a1b2c3"]}]`) - return +// componentsAPI answers a read with the booked plans, a dry run with pricing and a change with the new state, as the API does. +func componentsAPI(pricing string) func(r request, w http.ResponseWriter) { + return func(r request, w http.ResponseWriter) { + if r.method == "GET" { + echo(w, 200, `{"components":[{"slug":"php","size":"sm","priceInCents":1200,"currency":"EUR"}]}`) + return + } + if r.body["dryRun"] == true { + echo(w, 200, `{"pricing":`+pricing+`,"paymentMethod":"pm-a1b2c3"}`) + return + } + echo(w, 202, `{"components":[{"slug":"php","size":"md","priceInCents":2400,"currency":"EUR"}],"pricing":`+pricing+`}`) } - if r.path == "/v1/catalog/component-plans" { - echo(w, 200, catalog) - return +} + +// applied reports a component change other than a dry run. +func applied(seen []request) bool { + for _, r := range seen { + if r.method == "PATCH" && r.body["dryRun"] != true { + return true + } } - echo(w, 202, `{"components":[{"slug":"php","size":"md","priceInCents":2400,"currency":"EUR"}],"pricing":{"monthlyPriceInCents":2400,"currency":"EUR"}}`) + return false } func TestComponentsUpdateWithoutTTYRequiresYes(t *testing.T) { - _, seen, err := run(t, "", componentsHandler, "components", "update", "en-a1b2c3", "--component", "php=md") - if err == nil || !strings.Contains(err.Error(), "--yes") { - t.Fatalf("err = %v", err) + _, seen, err := run(t, "", componentsAPI(billedPricing), "components", "update", "en-a1b2c3", "--component", "php=md") + if err == nil || !strings.Contains(err.Error(), "--yes") || applied(seen) { + t.Fatalf("err = %v, seen = %+v", err, seen) } - for _, r := range seen { - if r.method == "PATCH" { - t.Fatal("PATCH sent without consent") + + out, stderr, seen, err := runStreams(t, context.Background(), "", componentsAPI(billedPricing), "components", "update", "en-a1b2c3", "--component", "php=md", "--component", "database=off", "--yes") + if err != nil || len(seen) != 2 { + t.Fatalf("err = %v, seen = %+v", err, seen) + } + if first := seen[0]; first.body["dryRun"] != true || first.body["php"] != "md" || first.body["database"] != "off" { + t.Fatalf("dry run = %+v", first) + } + if last := seen[1]; last.body["dryRun"] != nil || last.body["php"] != "md" || last.body["database"] != "off" { + t.Fatalf("change = %+v", last) + } + for _, want := range []string{"Monthly price: 24.00 EUR", "Payment method: pm-a1b2c3"} { + if !strings.Contains(stderr, want) { + t.Fatalf("stderr = %q, want %q", stderr, want) } } + if !strings.Contains(out, "Total: 24.00 EUR per month") { + t.Fatalf("out = %q", out) + } +} - _, seen, err = run(t, "", componentsHandler, "components", "update", "en-a1b2c3", "--component", "php=md", "--component", "database=off", "--yes") - if err != nil { - t.Fatal(err) +func TestComponentsUpdateOnTerminalAsksAndAbortsOnNo(t *testing.T) { + _, stderr, seen, err := runStreamsTTY(t, true, "n\n", componentsAPI(billedPricing), "components", "update", "en-a1b2c3", "--component", "php=md") + if err == nil || applied(seen) || !strings.Contains(stderr, "Change and bill the new price? [y/N]") { + t.Fatalf("err = %v, stderr = %q, seen = %+v", err, stderr, seen) } - last := seen[len(seen)-1] - if last.method != "PATCH" || last.body["php"] != "md" || last.body["database"] != "off" { - t.Fatalf("last = %+v", last) +} + +func TestComponentsUpdateInTrialDoesNotAsk(t *testing.T) { + _, seen, err := run(t, "", componentsAPI(trialPricing), "components", "update", "en-a1b2c3", "--component", "php=md") + if err != nil || !applied(seen) { + t.Fatalf("err = %v, seen = %+v", err, seen) } +} - _, seen, err = run(t, "", func(r request, w http.ResponseWriter) { - if r.path == "/v1/catalog/component-plans" { - echo(w, 500, `{"title":"boom"}`) - return - } - componentsHandler(r, w) - }, "components", "update", "en-a1b2c3", "--component", "php=md", "--yes") - if err == nil { - t.Fatal("catalog failure must fail") +func TestComponentsUpdateDryRunChangesNothing(t *testing.T) { + out, seen, err := run(t, "", componentsAPI(billedPricing), "components", "update", "en-a1b2c3", "--component", "php=md", "--dry-run") + if err != nil || applied(seen) || len(seen) != 1 { + t.Fatalf("err = %v, seen = %+v", err, seen) } - for _, r := range seen { - if r.method == "PATCH" { - t.Fatal("PATCH sent after catalog failure") + for _, want := range []string{"Monthly price: 24.00 EUR", "Payment method: pm-a1b2c3", "Dry run: nothing was changed."} { + if !strings.Contains(out, want) { + t.Fatalf("out = %q, want %q", out, want) } } - _, seen, err = run(t, "", componentsHandler, "components", "update", "en-a1b2c3", "--component", "php=xl", "--yes") - if err == nil || !strings.Contains(err.Error(), "no size") { - t.Fatalf("err = %v", err) + out, _, err = run(t, "", componentsAPI(trialPricing), "components", "update", "en-a1b2c3", "--component", "php=md", "--dry-run") + if err != nil || !strings.Contains(out, "The change is free during the trial until 2026-12-01T00:00:00+00:00; after the trial: 24.00 EUR/month.") { + t.Fatalf("trial: err = %v, out = %q", err, out) } - for _, r := range seen { - if r.method == "PATCH" { - t.Fatal("PATCH sent for unknown size") - } + + out, _, err = run(t, "", componentsAPI(billedPricing), "components", "update", "en-a1b2c3", "--component", "php=md", "--dry-run", "--json") + if err != nil || !strings.HasPrefix(out, `{"pricing":`) { + t.Fatalf("json: err = %v, out = %q", err, out) } } -func TestComponentChangeSummaryShowsDelta(t *testing.T) { - var plans []api.Resource - _ = json.Unmarshal([]byte(catalog), &plans) - var currentResource api.Resource - _ = json.Unmarshal([]byte(current), ¤tResource) - summary, err := componentChangeSummary(currentResource, plans, map[string]string{"php": "md", "database": "off"}) - for _, want := range []string{"php: sm (12.00 EUR) -> md (24.00 EUR)", "database: sm (8.00 EUR) -> off (0.00 EUR", "Monthly change: +4.00 EUR"} { - if err != nil || !strings.Contains(summary, want) { - t.Fatalf("summary = %q, err = %v, want %q", summary, err, want) - } - } - if strings.Contains(summary, "Total") { - t.Fatalf("summary = %q", summary) +func TestComponentsUpdateRejectedDryRunChangesNothing(t *testing.T) { + _, seen, err := run(t, "", func(r request, w http.ResponseWriter) { + echo(w, 422, `{"title":"Validation failed","violations":[{"propertyPath":"php","message":"Unknown size"}]}`) + }, "components", "update", "en-a1b2c3", "--component", "php=xl", "--yes") + if err == nil || applied(seen) || len(seen) != 1 { + t.Fatalf("err = %v, seen = %+v", err, seen) } } @@ -317,112 +333,3 @@ func TestEnvironmentUpdateVersions(t *testing.T) { t.Fatalf("err = %v, seen = %+v", err, seen) } } - -// changedAnything reports a request other than a read. -func changedAnything(seen []request) bool { - for _, r := range seen { - if r.method != "GET" { - return true - } - } - return false -} - -func patched(seen []request) bool { - for _, r := range seen { - if r.method == "PATCH" { - return true - } - } - return false -} - -func TestComponentsUpdateSkipsUnchanged(t *testing.T) { - out, stderr, seen, err := runStreams(t, context.Background(), "", componentsHandler, "components", "update", "en-a1b2c3", "--component", "php=sm") - if err != nil || out != "" || !strings.Contains(stderr, "No component plan changes.") || patched(seen) { - t.Fatalf("out = %q, stderr = %q, err = %v, seen = %+v", out, stderr, err, seen) - } - out, _, seen, err = runStreams(t, context.Background(), "", componentsHandler, "components", "update", "en-a1b2c3", "--component", "php=sm", "--json") - if err != nil || !strings.HasPrefix(out, "{") || patched(seen) { - t.Fatalf("json: out = %q, err = %v", out, err) - } -} - -func TestComponentsUpdateResolvesRegion(t *testing.T) { - var catalogQuery string - handler := func(r request, w http.ResponseWriter) { - if r.path == "/v1/catalog/component-plans" { - catalogQuery = r.query - } - componentsHandler(r, w) - } - if _, seen, err := run(t, "", handler, "components", "update", "en-a1b2c3", "--component", "php=md", "--yes"); err != nil || !patched(seen) || !strings.Contains(catalogQuery, "region=eu-w1a") || !strings.Contains(catalogQuery, "currency=EUR") { - t.Fatalf("err = %v, query = %q", err, catalogQuery) - } - - _, seen, err := run(t, "", handler, "components", "update", "en-a1b2c3", "--component", "php=md", "--yes", "--region", "us-e1a") - if err != nil || !patched(seen) || !strings.Contains(catalogQuery, "region=us-e1a") { - t.Fatalf("override: err = %v, query = %q", err, catalogQuery) - } - for _, r := range seen { - if r.path == "/v1/apps" { - t.Fatal("--region must skip the app lookup") - } - } - - _, seen, err = run(t, "", func(r request, w http.ResponseWriter) { - if r.path == "/v1/apps" { - echo(w, 200, `[{"publicId":"ap-1","region":"eu-w1a","environments":["en-other"]}]`) - return - } - componentsHandler(r, w) - }, "components", "update", "en-a1b2c3", "--component", "php=md", "--yes") - if err == nil || !strings.Contains(err.Error(), "pass --region") || patched(seen) { - t.Fatalf("no match: err = %v", err) - } -} - -func TestComponentChangeSummaryRejectsCurrencyMismatch(t *testing.T) { - var plans []api.Resource - _ = json.Unmarshal([]byte(strings.ReplaceAll(catalog, "EUR", "USD")), &plans) - var currentResource api.Resource - _ = json.Unmarshal([]byte(current), ¤tResource) - if _, err := componentChangeSummary(currentResource, plans, map[string]string{"php": "md"}); err == nil || !strings.Contains(err.Error(), "USD") { - t.Fatalf("err = %v", err) - } -} - -func TestComponentChangeSummaryMissingPriceFails(t *testing.T) { - var plans []api.Resource - _ = json.Unmarshal([]byte(`[{"slug":"php","sizes":[{"size":"sm","priceInCents":1200,"currency":"EUR"},{"size":"xl","priceInCents":null,"currency":"EUR"}]}]`), &plans) - var currentResource api.Resource - _ = json.Unmarshal([]byte(current), ¤tResource) - _, err := componentChangeSummary(currentResource, plans, map[string]string{"php": "xl"}) - if err == nil || err.Error() != "price for php xl unknown; check frbit plans list or change it in the dashboard" { - t.Fatalf("err = %v", err) - } - _ = json.Unmarshal([]byte(`{"components":[{"slug":"php","size":"md","priceInCents":null,"currency":"EUR"}]}`), ¤tResource) - if _, err := componentChangeSummary(currentResource, plans, map[string]string{"php": "sm"}); err == nil || err.Error() != "price for php md unknown; check frbit plans list or change it in the dashboard" { - t.Fatalf("booked: %v", err) - } -} - -func TestComponentsUpdateRefusesUnknownPrice(t *testing.T) { - handler := func(r request, w http.ResponseWriter) { - if r.path == "/v1/catalog/component-plans" { - echo(w, 200, `[{"slug":"php","optional":false,"sizes":[{"size":"sm","priceInCents":1200,"currency":"EUR"},{"size":"md","priceInCents":null,"currency":"EUR"}]}]`) - return - } - componentsHandler(r, w) - } - for name, tty := range map[string]bool{"--yes": false, "terminal": true} { - args := []string{"components", "update", "en-a1b2c3", "--component", "php=md"} - if !tty { - args = append(args, "--yes") - } - _, stderr, seen, err := runStreamsTTY(t, tty, "y\n", handler, args...) - if err == nil || err.Error() != "price for php md unknown; check frbit plans list or change it in the dashboard" || changedAnything(seen) || strings.Contains(stderr, "[y/N]") { - t.Fatalf("%s: err %v, stderr %q, seen %+v", name, err, stderr, seen) - } - } -} diff --git a/internal/cmd/environments/target_test.go b/internal/cmd/environments/target_test.go index aae1ac2..d7b2e6d 100644 --- a/internal/cmd/environments/target_test.go +++ b/internal/cmd/environments/target_test.go @@ -61,7 +61,7 @@ var targetCases = []targetCase{ {args: []string{"php-settings", "get"}}, {args: []string{"basic-auth", "get"}}, {args: []string{"firewall-rules", "list"}}, - {args: []string{"components", "get"}, handler: componentsHandler}, + {args: []string{"components", "get"}, handler: componentsAPI(billedPricing)}, {args: []string{"update"}, flags: []string{"--name", "x"}, write: true}, {args: []string{"variables", "update"}, flags: []string{"--set", "A=1"}, write: true}, {args: []string{"restart"}, write: true}, @@ -69,7 +69,7 @@ var targetCases = []targetCase{ {args: []string{"php-settings", "update"}, flags: []string{"--set", "memory_limit=256M"}, write: true}, {args: []string{"basic-auth", "update"}, flags: []string{"--enabled=false"}, write: true}, {args: []string{"firewall-rules", "create"}, flags: []string{"--description", "x", "--port", "8080"}, write: true}, - {args: []string{"components", "update"}, flags: []string{"--component", "php=md", "--yes"}, write: true, handler: componentsHandler}, + {args: []string{"components", "update"}, flags: []string{"--component", "php=md", "--yes"}, write: true, handler: componentsAPI(billedPricing)}, } func hitsEnvironment(seen []request) bool { diff --git a/internal/cmd/root/root_test.go b/internal/cmd/root/root_test.go index 3001a51..ee0d19c 100644 --- a/internal/cmd/root/root_test.go +++ b/internal/cmd/root/root_test.go @@ -1023,7 +1023,7 @@ func TestAppsCreateRefusesWithoutPrice(t *testing.T) { var calls []dryRunCall server := billingServer(t, pricing, &calls) _, err := runAppsCreate(t, server, false, "", "--yes") - if err == nil || !strings.Contains(err.Error(), "dry run returned no price; refusing to create") { + if err == nil || !strings.Contains(err.Error(), "dry run returned no price; refusing to continue") { t.Fatalf("err = %v", err) } if len(calls) != 1 || !calls[0].dryRun { diff --git a/internal/cmdutil/billing.go b/internal/cmdutil/billing.go index 7d0562f..22197e8 100644 --- a/internal/cmdutil/billing.go +++ b/internal/cmdutil/billing.go @@ -1,6 +1,7 @@ package cmdutil import ( + "context" "encoding/json" "fmt" @@ -9,22 +10,66 @@ import ( "github.com/spf13/cobra" ) +// billedAction is a billed create (POST) or change (PATCH) that the API prices when the body carries dryRun: true. +type billedAction struct { + send func(ctx context.Context, path string, payload any) (api.ResourceResponse, error) + prompt string + trialLead string + unchanged string +} + +func creation(client *api.Client, noun string) billedAction { + return billedAction{ + send: client.DryRunCreate, + prompt: "Create and start billing? [y/N] ", + trialLead: fmt.Sprintf("The %s would be created as a trial at no cost", noun), + unchanged: "Dry run: nothing was created.", + } +} + +func change(client *api.Client) billedAction { + return billedAction{ + send: client.UpdateResource, + prompt: "Change and bill the new price? [y/N] ", + trialLead: "The change is free during the trial", + unchanged: "Dry run: nothing was changed.", + } +} + // ConfirmBilled runs a dry-run POST of payload to path, prints the monthly price and asks before a billed create. // Prices and the question go to stderr so --json output stays clean. func ConfirmBilled(cmd *cobra.Command, f *app.Factory, client *api.Client, path string, payload any, yes bool) (bool, error) { - quote, err := priceQuote(cmd, client, path, payload) + return confirmBilled(cmd, f, creation(client, ""), path, payload, yes) +} + +// ConfirmBilledChange runs a dry-run PATCH of payload to path, prints the monthly price after the change and asks before a billed change. +func ConfirmBilledChange(cmd *cobra.Command, f *app.Factory, client *api.Client, path string, payload any, yes bool) (bool, error) { + return confirmBilled(cmd, f, change(client), path, payload, yes) +} + +func confirmBilled(cmd *cobra.Command, f *app.Factory, action billedAction, path string, payload any, yes bool) (bool, error) { + quote, err := priceQuote(cmd, action, path, payload) if err != nil { return false, err } if quote.cents == 0 || quote.trial { return true, nil } - return AskBilled(cmd, f, quote.summary(), "Create and start billing? [y/N] ", yes) + return AskBilled(cmd, f, quote.summary(), action.prompt, yes) } // DryRunBilled sends only the dry-run POST and prints the price, or the API response with asJSON; noun names what would be created. func DryRunBilled(cmd *cobra.Command, client *api.Client, path string, payload any, noun string, asJSON bool) error { - quote, err := priceQuote(cmd, client, path, payload) + return dryRunBilled(cmd, creation(client, noun), path, payload, asJSON) +} + +// DryRunBilledChange sends only the dry-run PATCH and prints the price after the change, or the API response with asJSON. +func DryRunBilledChange(cmd *cobra.Command, client *api.Client, path string, payload any, asJSON bool) error { + return dryRunBilled(cmd, change(client), path, payload, asJSON) +} + +func dryRunBilled(cmd *cobra.Command, action billedAction, path string, payload any, asJSON bool) error { + quote, err := priceQuote(cmd, action, path, payload) if err != nil { return err } @@ -35,7 +80,7 @@ func DryRunBilled(cmd *cobra.Command, client *api.Client, path string, payload a } text := quote.summary() if quote.trial { - text = fmt.Sprintf("The %s would be created as a trial at no cost", noun) + text = action.trialLead if until, ok := quote.trialEndsAt.(string); ok && until != "" { text += " until " + until } @@ -44,7 +89,7 @@ func DryRunBilled(cmd *cobra.Command, client *api.Client, path string, payload a } text += "." } - _, err = fmt.Fprintf(out, "%s\nDry run: nothing was created.\n", text) + _, err = fmt.Fprintf(out, "%s\n%s\n", text, action.unchanged) return err } @@ -62,12 +107,12 @@ func (q quote) summary() string { } // priceQuote sends payload with dryRun: true and without an Idempotency-Key, and reads the price. -func priceQuote(cmd *cobra.Command, client *api.Client, path string, payload any) (quote, error) { +func priceQuote(cmd *cobra.Command, action billedAction, path string, payload any) (quote, error) { body, err := dryRunBody(payload) if err != nil { return quote{}, err } - response, err := client.DryRunCreate(cmd.Context(), path, body) + response, err := action.send(cmd.Context(), path, body) if err != nil { return quote{}, err } @@ -77,7 +122,7 @@ func priceQuote(cmd *cobra.Command, client *api.Client, path string, payload any cents, isNumber = pricing["monthlyPriceInCents"].(float64) } if !ok || !isNumber { - return quote{}, fmt.Errorf("dry run returned no price; refusing to create") + return quote{}, fmt.Errorf("dry run returned no price; refusing to continue") } currency, _ := pricing["currency"].(string) billed, billedKnown := pricing["billed"].(bool) @@ -86,7 +131,7 @@ func priceQuote(cmd *cobra.Command, client *api.Client, path string, payload any currency: currency, trial: billedKnown && !billed && pricing["trialEndsAt"] != nil, trialEndsAt: pricing["trialEndsAt"], - paymentMethod: paymentMethodLabel(body), + paymentMethod: paymentMethodLabel(response.Resource, body), raw: response.Raw, }, nil } @@ -119,8 +164,14 @@ func dryRunBody(payload any) (map[string]any, error) { return body, nil } -// The dry run names no payment method, so show the one chosen in the request or the default. -func paymentMethodLabel(body map[string]any) string { +// paymentMethodLabel prefers the payment method the dry run names, then the one chosen in the request, else the default. +func paymentMethodLabel(response api.Resource, body map[string]any) string { + if named, present := response["paymentMethod"]; present { + if id, _ := named.(string); id != "" { + return id + } + return "none" + } if id, _ := body["paymentMethodId"].(string); id != "" { return id }