diff --git a/cmd/billing.go b/cmd/billing.go index ea83bf6..e025617 100644 --- a/cmd/billing.go +++ b/cmd/billing.go @@ -6,12 +6,13 @@ import ( var billingCmd = &cobra.Command{ Use: "billing", - Short: "Add funds to a Flex account", + Short: "Check and add funds on a Flex account", // Hidden until the Flex plan launches. The commands still run. Hidden: true, Long: `Billing commands for Flex accounts, which pay for usage from a prepaid balance. Examples: + cio billing status cio billing add-funds`, RunE: func(cmd *cobra.Command, args []string) error { return cmd.Help() diff --git a/cmd/billing_status.go b/cmd/billing_status.go new file mode 100644 index 0000000..0476652 --- /dev/null +++ b/cmd/billing_status.go @@ -0,0 +1,533 @@ +package cmd + +import ( + "cmp" + "encoding/json" + "errors" + "fmt" + "math" + "net/http" + "net/url" + "slices" + "strings" + "time" + + "github.com/customerio/cli/internal/client" + "github.com/customerio/cli/internal/output" + "github.com/customerio/cli/internal/validate" + "github.com/spf13/cobra" +) + +var billingStatusCmd = &cobra.Command{ + Use: "status", + Short: "Show Flex funds, free grants, forecasts and plan limits", + Long: `Show what a Flex account has left this billing period, when funds or a free +grant will run out at the current rate, and how close each workspace is to its +plan limits. Read-only, so it runs under --read-only. + +Forecasts use the average daily usage so far this period and stop at the +period end, when the free grants renew. When a meter's free grant runs out, its +usage is paid for from funds, so the funds forecast speeds up from that day. +Agent usage is the exception: it can't draw on funds, so it stops instead. + +Flex accounts only. The login needs access to the account's billing. + +Output: + period the billing period's first and last day + funds balance_usd, spent_usd this period, daily_spend_usd, and + runs_out_on (today when the balance is zero, null when funds + last the period) + meters per meter: usage, free grant left, grant_runs_out_on (today + once it's used up, null when it lasts the period), and + rate_usd per unit + limits workspaces, and custom object types and data-driven segments + per workspace (allowed is null when there's no limit). Counts + cover the workspaces this login can see. A workspace whose + settings can't be read gets an error on its segments entry, + with used and allowed null, and the rest still reports. + warnings FUNDS_LOW, GRANT_LOW, LIMIT_NEAR or LIMIT_REACHED, each with a + message to pass on + +Examples: + cio billing status + cio billing status --jq .warnings + cio billing status --jq .funds.runs_out_on -r`, + Args: cobra.NoArgs, + RunE: runBillingStatus, +} + +func init() { + billingCmd.AddCommand(billingStatusCmd) +} + +// agentUsageMeter only draws on its own grant, never on funds. +const agentUsageMeter = "agent_usage" + +type billingAccount struct { + ID json.Number `json:"id"` + BillingVendor string `json:"billing_vendor"` + GatedFeatures map[string]gatedFeature `json:"gated_features"` +} + +type gatedFeature struct { + Limit int `json:"limit"` +} + +type walletUsage struct { + Start string `json:"start"` + End string `json:"end"` + Balance walletBalance `json:"balance"` + Meters map[string]walletMeter `json:"meters"` +} + +type walletBalance struct { + Used float64 `json:"used"` + Remaining float64 `json:"remaining"` +} + +type walletMeter struct { + GrantTotal int64 `json:"grant_total"` + GrantUsed int64 `json:"grant_used"` + GrantRemaining int64 `json:"grant_remaining"` + BalanceUsed int64 `json:"balance_used"` + BalanceCost float64 `json:"balance_cost"` + TotalUsed int64 `json:"total_used"` +} + +type billingStatus struct { + Period billingPeriod `json:"period"` + Funds fundsStatus `json:"funds"` + Meters map[string]meterStatus `json:"meters"` + Limits []limitStatus `json:"limits"` + Warnings []billingWarning `json:"warnings"` +} + +type billingPeriod struct { + Start string `json:"start"` + End string `json:"end"` +} + +type fundsStatus struct { + BalanceUSD float64 `json:"balance_usd"` + SpentUSD float64 `json:"spent_usd"` + DailySpendUSD float64 `json:"daily_spend_usd"` + RunsOutOn *string `json:"runs_out_on"` +} + +type meterStatus struct { + TotalUsed int64 `json:"total_used"` + GrantTotal int64 `json:"grant_total"` + GrantUsed int64 `json:"grant_used"` + GrantRemaining int64 `json:"grant_remaining"` + GrantRunsOutOn *string `json:"grant_runs_out_on"` + BalanceUsed int64 `json:"balance_used"` + BalanceCostUSD float64 `json:"balance_cost_usd"` + RateUSD *float64 `json:"rate_usd"` +} + +type limitStatus struct { + Limit string `json:"limit"` + WorkspaceID string `json:"workspace_id,omitempty"` + Workspace string `json:"workspace,omitempty"` + Used *int `json:"used"` + Allowed *int `json:"allowed"` + Error string `json:"error,omitempty"` + // limitMessage is the server's own wording for reaching this limit. + limitMessage string +} + +type billingWarning struct { + Code string `json:"code"` + Message string `json:"message"` + Meter string `json:"meter,omitempty"` + Limit string `json:"limit,omitempty"` + WorkspaceID string `json:"workspace_id,omitempty"` +} + +type workspaceRef struct { + ID json.Number `json:"id"` + Name string `json:"name"` +} + +func runBillingStatus(cmd *cobra.Command, args []string) error { + c := clientFromCmd(cmd) + if c == nil { + return errNoClient(cmd) + } + + if GetDryRun(cmd) { + urls := []string{"/v1/accounts/current"} + for _, p := range billingStatusAccountPaths { + urls = append(urls, "/v1/accounts/{account_id}"+p) + } + urls = append(urls, "/v1/environments/{environment_id}/settings/workspace") + for i := range urls { + urls[i] = c.BaseURL() + urls[i] + } + return output.FprintJSON(cmd.OutOrStdout(), map[string]any{ + "dry_run": true, + "method": "GET", + "urls": urls, + }) + } + + ctx := cmd.Context() + get := func(path string, into any) error { + raw, err := c.Do(ctx, "GET", path, nil, nil) + if err != nil { + return handleBillingStatusError(err) + } + if err := json.Unmarshal(raw, into); err != nil { + output.PrintError(output.CodeGeneralError, "failed to parse the response from "+path, nil) + return err + } + return nil + } + + var current struct { + Account billingAccount `json:"account"` + // The workspaces this login can see, which for an admin is all of them. + Environments []workspaceRef `json:"environments"` + } + if err := get("/v1/accounts/current", ¤t); err != nil { + return err + } + account := current.Account + if account.BillingVendor != flexBillingVendor { + err := fmt.Errorf("billing status is only available on the Flex plan") + output.PrintError(output.CodeValidationError, err.Error(), map[string]any{ + "hint": "This account isn't on Flex, so it has no balance or free grants. Its plan is under Settings → Billing in Customer.io.", + }) + return err + } + accountID := account.ID.String() + if err := validate.ValidateResourceID(accountID); err != nil { + output.PrintError(output.CodeGeneralError, "the account read returned an invalid account id", nil) + return err + } + accountPath := "/v1/accounts/" + url.PathEscape(accountID) + + var usage walletUsage + if err := get(accountPath+"/billing/wallet/usage", &usage); err != nil { + return err + } + var rates struct { + Rates map[string]float64 `json:"rates"` + } + if err := get(accountPath+"/billing/wallet/rates", &rates); err != nil { + return err + } + var accountUsage struct { + AccountUsage struct { + EnvironmentUsages []struct { + EnvironmentID json.Number `json:"environment_id"` + ObjectTypesTotal int `json:"object_types_total"` + ObjectTypesAllotted int `json:"object_types_allotted"` + } `json:"environment_usages"` + } `json:"account_usage"` + } + if err := get(accountPath+"/usage_v2", &accountUsage); err != nil { + return err + } + + objectTypesLimit := account.GatedFeatures["object_types"].Limit + objectTypes := map[string]limitStatus{} + for _, u := range accountUsage.AccountUsage.EnvironmentUsages { + allowed := objectTypesLimit + if allowed <= 0 { + allowed = u.ObjectTypesAllotted + } + objectTypes[u.EnvironmentID.String()] = limitStatus{Used: intPtr(u.ObjectTypesTotal), Allowed: positiveLimit(allowed)} + } + + limits := []limitStatus{{ + Limit: "workspaces", + Used: intPtr(len(current.Environments)), + Allowed: positiveLimit(account.GatedFeatures["workspaces"].Limit), + }} + for _, env := range current.Environments { + envID := env.ID.String() + if err := validate.ValidateResourceID(envID); err != nil { + output.PrintError(output.CodeGeneralError, "the workspace list returned an invalid workspace id", nil) + return err + } + objects, ok := objectTypes[envID] + if !ok { + objects = limitStatus{Used: intPtr(0), Allowed: positiveLimit(objectTypesLimit)} + } + objects.Limit, objects.WorkspaceID, objects.Workspace = "object_types", envID, env.Name + + segments := limitStatus{Limit: "data_driven_segments", WorkspaceID: envID, Workspace: env.Name} + path := "/v1/environments/" + url.PathEscape(envID) + "/settings/workspace" + raw, err := c.Do(ctx, "GET", path, nil, nil) + var apiErr *client.APIError + switch { + case errors.As(err, &apiErr): + // One workspace the login can't read shouldn't cost the rest of + // the report, so its segment limit is left unknown. + segments.Error = workspaceSettingsError(apiErr.StatusCode) + printWarning(cmd, "LIMIT_UNREADABLE", fmt.Sprintf("Workspace %q's data-driven segment limit is missing from limits: %s.", env.Name, segments.Error)) + case err != nil: + return handleBillingStatusError(err) + default: + var settings struct { + Settings struct { + DataDrivenSegmentsUsed int `json:"data_driven_segments_used"` + DataDrivenSegmentsAllotted int `json:"data_driven_segments_allotted"` + DataDrivenSegmentsLimitMessage string `json:"data_driven_segments_limit_message"` + } `json:"settings"` + } + if err := json.Unmarshal(raw, &settings); err != nil { + output.PrintError(output.CodeGeneralError, "failed to parse the response from "+path, nil) + return err + } + segments.Used = intPtr(settings.Settings.DataDrivenSegmentsUsed) + segments.Allowed = positiveLimit(settings.Settings.DataDrivenSegmentsAllotted) + segments.limitMessage = strings.TrimSpace(settings.Settings.DataDrivenSegmentsLimitMessage) + } + limits = append(limits, objects, segments) + } + + period, funds, meters, warnings, err := forecastWallet(time.Now(), usage, rates.Rates) + if err != nil { + output.PrintError(output.CodeGeneralError, err.Error(), nil) + return err + } + status := billingStatus{ + Period: period, + Funds: funds, + Meters: meters, + Limits: limits, + Warnings: append(append([]billingWarning{}, warnings...), limitWarnings(limits)...), + } + data, _ := json.Marshal(status) + return output.FprintProcess(cmd.OutOrStdout(), data, GetJQFlag(cmd), GetRawFlag(cmd)) +} + +// billingStatusAccountPaths are the account reads after /v1/accounts/current, +// in the order the command makes them. +var billingStatusAccountPaths = []string{ + "/billing/wallet/usage", + "/billing/wallet/rates", + "/usage_v2", +} + +// handleBillingStatusError passes on the wallet's reason for refusing a read, +// such as an account that isn't on the Flex plan, and says plainly when the +// login can't read billing. +func handleBillingStatusError(err error) error { + var apiErr *client.APIError + if errors.As(err, &apiErr) { + switch apiErr.StatusCode { + case http.StatusForbidden: + msg := "this login can't read this account's billing and usage" + output.PrintError(output.CodeAuthzError, msg, map[string]any{ + "status_code": apiErr.StatusCode, + "hint": "Ask an account admin for access to billing, or sign in as someone who has it.", + }) + return errors.New(msg) + case http.StatusBadRequest: + if detail := apiErrorDetail(apiErr.Body); detail != "" { + output.PrintError(output.CodeValidationError, detail, map[string]any{ + "status_code": apiErr.StatusCode, + }) + return errors.New(detail) + } + } + } + return handleAPIError(err) +} + +// forecastWallet projects this period's usage forward at its average daily +// rate. Funds drain at the balance's daily spend, and each meter whose grant +// runs out adds the rate its grant was covering from that day on. +func forecastWallet(now time.Time, usage walletUsage, rates map[string]float64) (billingPeriod, fundsStatus, map[string]meterStatus, []billingWarning, error) { + period := billingPeriod{Start: usage.Start, End: usage.End} + start, err := time.Parse(time.DateOnly, usage.Start) + if err != nil { + return period, fundsStatus{}, nil, nil, fmt.Errorf("the wallet usage read returned an invalid period start %q", usage.Start) + } + lastDay, err := time.Parse(time.DateOnly, usage.End) + if err != nil { + return period, fundsStatus{}, nil, nil, fmt.Errorf("the wallet usage read returned an invalid period end %q", usage.End) + } + now = now.UTC() + periodEnd := lastDay.Add(24 * time.Hour) + // A few hours into a period are too few to extrapolate from. + elapsed := max(now.Sub(start).Hours()/24, 1) + daysLeft := max(periodEnd.Sub(now).Hours()/24, 0) + at := func(days float64) time.Time { return now.Add(time.Duration(days * 24 * float64(time.Hour))) } + + type rollover struct{ day, perDay float64 } + dailySpend := usage.Balance.Used / elapsed + var later []rollover + var warnings []billingWarning + meters := make(map[string]meterStatus, len(usage.Meters)) + + names := make([]string, 0, len(usage.Meters)) + for name := range usage.Meters { + names = append(names, name) + } + slices.Sort(names) + for _, name := range names { + m := usage.Meters[name] + status := meterStatus{ + TotalUsed: m.TotalUsed, + GrantTotal: m.GrantTotal, + GrantUsed: m.GrantUsed, + GrantRemaining: m.GrantRemaining, + BalanceUsed: m.BalanceUsed, + BalanceCostUSD: roundCents(m.BalanceCost), + } + rate, priced := rates[name] + if priced { + status.RateUSD = &rate + } + + grantPerDay := float64(m.GrantUsed) / elapsed + if m.GrantTotal > 0 && grantPerDay > 0 { + day := max(float64(m.GrantRemaining)/grantPerDay, 0) + if day < daysLeft { + runsOut := at(day) + status.GrantRunsOutOn = dateOf(runsOut) + // A used-up grant's usage is already in the funds forecast, so + // only agent usage, which stops instead, still warns about it. + if day > 0 || name == agentUsageMeter { + warnings = append(warnings, grantWarning(name, day == 0, runsOut, lastDay)) + } + if name != agentUsageMeter && priced { + if day == 0 { + dailySpend += grantPerDay * rate + } else { + later = append(later, rollover{day, grantPerDay * rate}) + } + } + } + } + meters[name] = status + } + + funds := fundsStatus{ + BalanceUSD: roundCents(usage.Balance.Remaining), + SpentUSD: roundCents(usage.Balance.Used), + DailySpendUSD: roundCents(dailySpend), + } + var fundsWarning *billingWarning + if usage.Balance.Remaining <= 0 { + funds.RunsOutOn = dateOf(now) + fundsWarning = &billingWarning{ + Code: "FUNDS_LOW", + Message: "No funds left. Usage beyond the free grants fails: metered sends are undeliverable and new active profiles are dropped. Run 'cio billing add-funds' to add funds.", + } + } else { + slices.SortFunc(later, func(a, b rollover) int { return cmp.Compare(a.day, b.day) }) + later = append(later, rollover{day: daysLeft}) + balance, day, rate := usage.Balance.Remaining, 0.0, dailySpend + for _, next := range later { + if rate > 0 && day+balance/rate < next.day { + runsOut := at(day + balance/rate) + funds.RunsOutOn = dateOf(runsOut) + fundsWarning = &billingWarning{ + Code: "FUNDS_LOW", + Message: fmt.Sprintf("Funds run out around %s at the current rate, before the period ends %s. Run 'cio billing add-funds' to add funds.", + runsOut.Format("Jan 2"), lastDay.Format("Jan 2")), + } + break + } + balance -= rate * (next.day - day) + day, rate = next.day, rate+next.perDay + } + } + if fundsWarning != nil { + warnings = append([]billingWarning{*fundsWarning}, warnings...) + } + return period, funds, meters, warnings, nil +} + +func grantWarning(meter string, usedUp bool, runsOut, lastDay time.Time) billingWarning { + label := strings.ReplaceAll(meter, "_", " ") + var msg string + switch { + case meter == agentUsageMeter && usedUp: + msg = fmt.Sprintf("The free %s grant is used up, and %s can't be paid for from funds.", label, label) + case meter == agentUsageMeter: + msg = fmt.Sprintf("The free %s grant runs out around %s, before the period ends %s. %s can't be paid for from funds, so it stops then.", + label, runsOut.Format("Jan 2"), lastDay.Format("Jan 2"), capitalize(label)) + default: + msg = fmt.Sprintf("The free %s grant runs out around %s, before the period ends %s. After that, %s are paid for from funds.", + label, runsOut.Format("Jan 2"), lastDay.Format("Jan 2"), label) + } + return billingWarning{Code: "GRANT_LOW", Message: msg, Meter: meter} +} + +// limitWarnings flags each limit that is reached, or one below. Workspaces +// only warn once reached: every account has at least one, so with a limit of +// two the near warning would never go away. +func limitWarnings(limits []limitStatus) []billingWarning { + var warnings []billingWarning + for _, l := range limits { + if l.Allowed == nil || l.Used == nil { + continue + } + used, allowed := *l.Used, *l.Allowed + var code string + switch { + case used >= allowed: + code = "LIMIT_REACHED" + case used == allowed-1 && l.Limit != "workspaces": + code = "LIMIT_NEAR" + default: + continue + } + + msg := l.limitMessage + if code != "LIMIT_REACHED" || msg == "" { + switch l.Limit { + case "workspaces": + msg = fmt.Sprintf("This account uses %d of its %d workspaces.", used, allowed) + case "object_types": + msg = fmt.Sprintf("Workspace %q uses %d of its %d custom object types.", l.Workspace, used, allowed) + default: + msg = fmt.Sprintf("Workspace %q uses %d of its %d data-driven segments.", l.Workspace, used, allowed) + } + } + warnings = append(warnings, billingWarning{Code: code, Message: msg, Limit: l.Limit, WorkspaceID: l.WorkspaceID}) + } + return warnings +} + +// workspaceSettingsError says why a workspace's settings couldn't be read. +func workspaceSettingsError(status int) string { + if status == http.StatusForbidden { + return "this login can't read this workspace's settings" + } + return fmt.Sprintf("reading this workspace's settings failed with status %d", status) +} + +func intPtr(n int) *int { + return &n +} + +// positiveLimit reads a limit of 0 as no limit. +func positiveLimit(n int) *int { + if n <= 0 { + return nil + } + return &n +} + +func dateOf(t time.Time) *string { + s := t.UTC().Format(time.DateOnly) + return &s +} + +func roundCents(usd float64) float64 { + return math.Round(usd*100) / 100 +} + +func capitalize(s string) string { + if s == "" { + return s + } + return strings.ToUpper(s[:1]) + s[1:] +} diff --git a/cmd/billing_status_test.go b/cmd/billing_status_test.go new file mode 100644 index 0000000..1289e27 --- /dev/null +++ b/cmd/billing_status_test.go @@ -0,0 +1,438 @@ +package cmd + +import ( + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "slices" + "strings" + "testing" + "time" +) + +// statusNow is six days into an October billing period, with 25 days left. +var statusNow = time.Date(2026, 10, 7, 0, 0, 0, 0, time.UTC) + +func octoberUsage(used, remaining float64, meters map[string]walletMeter) walletUsage { + return walletUsage{ + Start: "2026-10-01", + End: "2026-10-31", + Balance: walletBalance{Used: used, Remaining: remaining}, + Meters: meters, + } +} + +func warningCodes(warnings []billingWarning) []string { + codes := make([]string, len(warnings)) + for i, w := range warnings { + codes[i] = w.Code + } + return codes +} + +func deref(s *string) string { + if s == nil { + return "" + } + return *s +} + +func TestForecastWallet_FundsRunOutBeforeThePeriodEnds(t *testing.T) { + _, funds, _, warnings, err := forecastWallet(statusNow, octoberUsage(38.40, 51.20, nil), nil) + if err != nil { + t.Fatal(err) + } + if funds.DailySpendUSD != 6.4 { + t.Errorf("expected daily spend 6.40, got %v", funds.DailySpendUSD) + } + if got := deref(funds.RunsOutOn); got != "2026-10-15" { + t.Errorf("expected funds to run out on 2026-10-15, got %s", got) + } + if len(warnings) != 1 || warnings[0].Code != "FUNDS_LOW" || !strings.Contains(warnings[0].Message, "around Oct 15") { + t.Errorf("expected one FUNDS_LOW warning naming Oct 15, got %+v", warnings) + } +} + +func TestForecastWallet_FundsThatLastThePeriodDontWarn(t *testing.T) { + cases := map[string]walletUsage{ + "slow spend": octoberUsage(6, 500, nil), + "no spend": octoberUsage(0, 20, nil), + // Exactly the 25 days left in the period. + "lasts to the last second": octoberUsage(6, 25, nil), + } + for name, usage := range cases { + t.Run(name, func(t *testing.T) { + _, funds, _, warnings, err := forecastWallet(statusNow, usage, nil) + if err != nil { + t.Fatal(err) + } + if funds.RunsOutOn != nil { + t.Errorf("expected no run-out date, got %s", *funds.RunsOutOn) + } + if len(warnings) != 0 { + t.Errorf("expected no warnings, got %+v", warnings) + } + }) + } +} + +func TestForecastWallet_ZeroBalanceIsLowNow(t *testing.T) { + _, funds, _, warnings, err := forecastWallet(statusNow, octoberUsage(12, 0, nil), nil) + if err != nil { + t.Fatal(err) + } + if got := deref(funds.RunsOutOn); got != "2026-10-07" { + t.Errorf("expected run-out today, got %s", got) + } + if len(warnings) != 1 || warnings[0].Code != "FUNDS_LOW" || !strings.HasPrefix(warnings[0].Message, "No funds left.") { + t.Errorf("expected the no-funds warning, got %+v", warnings) + } +} + +func TestForecastWallet_GrantRunningOutSpeedsUpTheFundsForecast(t *testing.T) { + // $1 a day from the balance alone would last exactly to the period end. + // The active profiles grant covers 20 a day and runs out after 4.5 more + // days, adding $1 a day, so funds now run out first. + usage := octoberUsage(6, 25, map[string]walletMeter{ + "active_profiles": {GrantTotal: 210, GrantUsed: 120, GrantRemaining: 90, TotalUsed: 120}, + }) + _, funds, meters, warnings, err := forecastWallet(statusNow, usage, map[string]float64{"active_profiles": 0.05}) + if err != nil { + t.Fatal(err) + } + if got := deref(meters["active_profiles"].GrantRunsOutOn); got != "2026-10-11" { + t.Errorf("expected the grant to run out on 2026-10-11, got %s", got) + } + // 4.5 days at $1 leaves $20.50, which lasts 10.25 days at $2. + if got := deref(funds.RunsOutOn); got != "2026-10-21" { + t.Errorf("expected funds to run out on 2026-10-21, got %s", got) + } + if funds.DailySpendUSD != 1 { + t.Errorf("expected today's daily spend to stay $1 until the grant runs out, got %v", funds.DailySpendUSD) + } + if !slices.Equal(warningCodes(warnings), []string{"FUNDS_LOW", "GRANT_LOW"}) { + t.Fatalf("expected FUNDS_LOW then GRANT_LOW, got %+v", warnings) + } + if warnings[1].Meter != "active_profiles" || !strings.Contains(warnings[1].Message, "paid for from funds") { + t.Errorf("expected the grant warning to say usage moves to funds, got %+v", warnings[1]) + } +} + +func TestForecastWallet_UsedUpGrantAddsItsRateWithoutWarning(t *testing.T) { + // The grant covered 300 profiles in 6 days, so its $2.50 a day now comes + // from funds on top of the $1 the balance already spends. + usage := octoberUsage(6, 500, map[string]walletMeter{ + "active_profiles": {GrantTotal: 300, GrantUsed: 300, GrantRemaining: 0, BalanceUsed: 120, BalanceCost: 6, TotalUsed: 420}, + }) + _, funds, meters, warnings, err := forecastWallet(statusNow, usage, map[string]float64{"active_profiles": 0.05}) + if err != nil { + t.Fatal(err) + } + if funds.DailySpendUSD != 3.5 { + t.Errorf("expected daily spend $3.50, got %v", funds.DailySpendUSD) + } + if got := deref(meters["active_profiles"].GrantRunsOutOn); got != "2026-10-07" { + t.Errorf("expected a used-up grant to report today, got %s", got) + } + if len(warnings) != 0 { + t.Errorf("expected no warning for a grant already in the funds forecast, got %+v", warnings) + } +} + +func TestForecastWallet_AgentUsageNeverDrawsOnFunds(t *testing.T) { + usage := octoberUsage(6, 30, map[string]walletMeter{ + "agent_usage": {GrantTotal: 600, GrantUsed: 600, GrantRemaining: 0, TotalUsed: 600}, + "ai_credits": {GrantTotal: 1000, GrantUsed: 600, GrantRemaining: 400, TotalUsed: 600}, + }) + // Both meters would add $5 a day if their usage moved to funds. + _, funds, _, warnings, err := forecastWallet(statusNow, usage, map[string]float64{"agent_usage": 0.05, "ai_credits": 0.05}) + if err != nil { + t.Fatal(err) + } + if funds.DailySpendUSD != 1 { + t.Errorf("expected agent usage to stay out of daily spend, got %v", funds.DailySpendUSD) + } + // ai_credits runs out on Oct 11 and adds $5 a day: $26 left lasts 4.3 days. + if got := deref(funds.RunsOutOn); got != "2026-10-15" { + t.Errorf("expected funds to run out on 2026-10-15, got %s", got) + } + if !slices.Equal(warningCodes(warnings), []string{"FUNDS_LOW", "GRANT_LOW", "GRANT_LOW"}) { + t.Fatalf("expected FUNDS_LOW and two GRANT_LOW, got %+v", warnings) + } + if warnings[1].Meter != "agent_usage" || !strings.Contains(warnings[1].Message, "can't be paid for from funds") { + t.Errorf("expected the agent usage warning to say it can't use funds, got %+v", warnings[1]) + } +} + +func TestForecastWallet_EarlyPeriodCountsAsADay(t *testing.T) { + now := time.Date(2026, 10, 1, 2, 0, 0, 0, time.UTC) + _, funds, _, _, err := forecastWallet(now, octoberUsage(10, 1000, nil), nil) + if err != nil { + t.Fatal(err) + } + if funds.DailySpendUSD != 10 { + t.Errorf("expected two hours of spend to count as one day, got %v", funds.DailySpendUSD) + } +} + +func TestForecastWallet_RejectsAnInvalidPeriod(t *testing.T) { + usage := octoberUsage(1, 1, nil) + usage.End = "October" + if _, _, _, _, err := forecastWallet(statusNow, usage, nil); err == nil { + t.Fatal("expected an error for an invalid period end") + } +} + +func TestLimitWarnings(t *testing.T) { + limit := func(n int) *int { return &n } + cases := []struct { + name string + limit limitStatus + want string + text string + }{ + {"workspaces one below", limitStatus{Limit: "workspaces", Used: limit(1), Allowed: limit(2)}, "", ""}, + {"workspaces reached", limitStatus{Limit: "workspaces", Used: limit(2), Allowed: limit(2)}, "LIMIT_REACHED", "This account uses 2 of its 2 workspaces."}, + {"object types one below", limitStatus{Limit: "object_types", Workspace: "Prod", Used: limit(1), Allowed: limit(2)}, "LIMIT_NEAR", `Workspace "Prod" uses 1 of its 2 custom object types.`}, + {"object types under", limitStatus{Limit: "object_types", Workspace: "Prod", Used: limit(0), Allowed: limit(2)}, "", ""}, + {"segments one below", limitStatus{Limit: "data_driven_segments", Workspace: "Prod", Used: limit(9), Allowed: limit(10), limitMessage: "Upgrade for more."}, "LIMIT_NEAR", `Workspace "Prod" uses 9 of its 10 data-driven segments.`}, + {"segments reached", limitStatus{Limit: "data_driven_segments", Workspace: "Prod", Used: limit(10), Allowed: limit(10), limitMessage: "Upgrade for more."}, "LIMIT_REACHED", "Upgrade for more."}, + {"no limit", limitStatus{Limit: "data_driven_segments", Workspace: "Prod", Used: limit(400)}, "", ""}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + warnings := limitWarnings([]limitStatus{tc.limit}) + if tc.want == "" { + if len(warnings) != 0 { + t.Errorf("expected no warning, got %+v", warnings) + } + return + } + if len(warnings) != 1 || warnings[0].Code != tc.want || warnings[0].Message != tc.text { + t.Errorf("expected %s %q, got %+v", tc.want, tc.text, warnings) + } + }) + } +} + +// statusServer answers the reads billing status makes, and records each path. +type statusServer struct { + *httptest.Server + paths []string + responses map[string]string + statuses map[string]int +} + +func newStatusServer(t *testing.T, account string) *statusServer { + t.Helper() + today := time.Now().UTC() + s := &statusServer{ + statuses: map[string]int{}, + responses: map[string]string{ + "/v1/accounts/current": `{"account":` + account + `,"environments":[{"id":"101","name":"Production"},{"id":102,"name":"Staging"}]}`, + "/v1/accounts/1/billing/wallet/usage": fmt.Sprintf(`{"start":%q,"end":%q,"balance":{"used":10,"remaining":51.2},"meters":{ + "email_sends":{"grant_total":0,"grant_used":0,"grant_remaining":0,"balance_used":5000,"balance_cost":10,"total_used":5000}}}`, + today.AddDate(0, 0, -9).Format(time.DateOnly), today.AddDate(0, 0, 20).Format(time.DateOnly)), + "/v1/accounts/1/billing/wallet/rates": `{"rates":{"email_sends":0.002}}`, + "/v1/accounts/1/usage_v2": `{"account_usage":{"environment_usages":[{"environment_id":101,"object_types_total":1,"object_types_allotted":2}]}}`, + "/v1/environments/101/settings/workspace": `{"settings":{"data_driven_segments_used":10,"data_driven_segments_allotted":10, + "data_driven_segments_limit_message":"You've reached your plan's data-driven segment limit."}}`, + "/v1/environments/102/settings/workspace": `{"settings":{"data_driven_segments_used":2,"data_driven_segments_allotted":10}}`, + }, + } + s.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/v1/service_accounts/oauth/token" { + _, _ = w.Write([]byte(`{"access_token":"jwt-test-session","token_type":"Bearer","expires_in":3600,"scope":"read_only"}`)) + return + } + s.paths = append(s.paths, r.URL.Path) + if r.Method != http.MethodGet { + t.Errorf("expected only GETs, got %s %s", r.Method, r.URL.Path) + } + body, ok := s.responses[r.URL.Path] + if !ok { + t.Errorf("unexpected request to %s", r.URL.Path) + w.WriteHeader(http.StatusNotFound) + return + } + if status := s.statuses[r.URL.Path]; status != 0 { + w.WriteHeader(status) + } + _, _ = w.Write([]byte(body)) + })) + t.Cleanup(s.Close) + return s +} + +const flexStatusAccount = `{"id":1,"billing_vendor":"modern_stripe","gated_features":{"workspaces":{"limit":2},"object_types":{"limit":2},"messaging":{}}}` + +func TestBillingStatus_ReportsFundsMetersAndLimits(t *testing.T) { + setupAddFunds(t) + server := newStatusServer(t, flexStatusAccount) + + stdout, stderr, err := executeCommand("billing", "status", "--api-url", server.URL, "--read-only") + if err != nil { + t.Fatalf("unexpected error: %v\nstderr: %s", err, stderr) + } + + var status billingStatus + if err := json.Unmarshal([]byte(stdout), &status); err != nil { + t.Fatalf("invalid JSON output: %v\nstdout: %s", err, stdout) + } + if status.Funds.BalanceUSD != 51.2 || status.Funds.SpentUSD != 10 || status.Funds.RunsOutOn != nil { + t.Errorf("unexpected funds: %+v", status.Funds) + } + if rate := status.Meters["email_sends"].RateUSD; rate == nil || *rate != 0.002 { + t.Errorf("expected the email rate from wallet/rates, got %v", rate) + } + + type key struct{ limit, workspace string } + got := map[key]limitStatus{} + for _, l := range status.Limits { + got[key{l.Limit, l.WorkspaceID}] = l + } + if l := got[key{"workspaces", ""}]; l.Used == nil || *l.Used != 2 || l.Allowed == nil || *l.Allowed != 2 { + t.Errorf("expected 2 of 2 workspaces, got %+v", l) + } + if l := got[key{"object_types", "102"}]; l.Used == nil || *l.Used != 0 || l.Allowed == nil || *l.Allowed != 2 || l.Workspace != "Staging" { + t.Errorf("expected a workspace missing from usage_v2 to use 0 of the gated 2 object types, got %+v", l) + } + if len(status.Limits) != 5 { + t.Errorf("expected workspaces plus two limits per workspace, got %+v", status.Limits) + } + + if !slices.Equal(warningCodes(status.Warnings), []string{"LIMIT_REACHED", "LIMIT_NEAR", "LIMIT_REACHED"}) { + t.Fatalf("expected workspaces reached, object types near and segments reached, got %+v", status.Warnings) + } + if w := status.Warnings[2]; w.WorkspaceID != "101" || w.Message != "You've reached your plan's data-driven segment limit." { + t.Errorf("expected the server's segment limit message, got %+v", w) + } +} + +func TestBillingStatus_NoWarningsIsAnEmptyList(t *testing.T) { + setupAddFunds(t) + server := newStatusServer(t, `{"id":1,"billing_vendor":"modern_stripe","gated_features":{}}`) + server.responses["/v1/accounts/current"] = `{"account":{"id":1,"billing_vendor":"modern_stripe","gated_features":{}},"environments":[]}` + + stdout, stderr, err := executeCommand("billing", "status", "--api-url", server.URL, "--jq", ".warnings") + if err != nil { + t.Fatalf("unexpected error: %v\nstderr: %s", err, stderr) + } + if stdout != "[]\n" { + t.Errorf("expected an empty warnings list, got %q", stdout) + } +} + +func TestBillingStatus_JQReadsAField(t *testing.T) { + setupAddFunds(t) + server := newStatusServer(t, flexStatusAccount) + + stdout, stderr, err := executeCommand("billing", "status", "--api-url", server.URL, "--jq", ".funds.balance_usd", "-r") + if err != nil { + t.Fatalf("unexpected error: %v\nstderr: %s", err, stderr) + } + if stdout != "51.2\n" { + t.Errorf("expected 51.2, got %q", stdout) + } +} + +func TestBillingStatus_RefusesOtherPlans(t *testing.T) { + setupAddFunds(t) + server := newStatusServer(t, `{"id":1,"billing_vendor":"ordway"}`) + + stdout, _, err := executeCommand("billing", "status", "--api-url", server.URL) + if err == nil { + t.Fatalf("expected an error, got stdout: %s", stdout) + } + if !strings.Contains(err.Error(), "Flex") { + t.Errorf("expected the error to name the Flex plan, got %q", err) + } + if !slices.Equal(server.paths, []string{"/v1/accounts/current"}) { + t.Errorf("expected only the account read, got %v", server.paths) + } +} + +func TestBillingStatus_PassesOnTheWalletRefusal(t *testing.T) { + cases := map[string]struct { + status int + body string + want string + }{ + "not on the Flex plan": {http.StatusBadRequest, `{"errors":[{"detail":"the wallet is only available to Flex plan accounts","status":"400"}]}`, "the wallet is only available to Flex plan accounts"}, + "no billing access": {http.StatusForbidden, `{"errors":[{"detail":"missing account/billing/view","status":"403"}]}`, "can't read this account's billing"}, + } + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + setupAddFunds(t) + server := newStatusServer(t, flexStatusAccount) + server.statuses["/v1/accounts/1/billing/wallet/usage"] = tc.status + server.responses["/v1/accounts/1/billing/wallet/usage"] = tc.body + + stdout, _, err := executeCommand("billing", "status", "--api-url", server.URL) + if err == nil { + t.Fatalf("expected an error, got stdout: %s", stdout) + } + if !strings.Contains(err.Error(), tc.want) { + t.Errorf("expected %q in the error, got %q", tc.want, err) + } + if strings.Contains(err.Error(), "account/billing") { + t.Errorf("expected the error not to name the permission, got %q", err) + } + }) + } +} + +func TestBillingStatus_ReportsTheRestWhenAWorkspaceIsUnreadable(t *testing.T) { + setupAddFunds(t) + server := newStatusServer(t, flexStatusAccount) + server.statuses["/v1/environments/102/settings/workspace"] = http.StatusForbidden + server.responses["/v1/environments/102/settings/workspace"] = `{"errors":[{"detail":"forbidden","status":"403"}]}` + + stdout, stderr, err := executeCommand("billing", "status", "--api-url", server.URL) + if err != nil { + t.Fatalf("unexpected error: %v\nstderr: %s", err, stderr) + } + var status billingStatus + if err := json.Unmarshal([]byte(stdout), &status); err != nil { + t.Fatalf("invalid JSON output: %v\nstdout: %s", err, stdout) + } + if status.Funds.BalanceUSD != 51.2 || len(status.Limits) != 5 { + t.Fatalf("expected the full report, got funds %+v and limits %+v", status.Funds, status.Limits) + } + var segments *limitStatus + for i, l := range status.Limits { + if l.Limit == "data_driven_segments" && l.WorkspaceID == "102" { + segments = &status.Limits[i] + } + } + if segments == nil || segments.Used != nil || segments.Allowed != nil || segments.Error != "this login can't read this workspace's settings" { + t.Errorf("expected the unreadable workspace's segments entry to carry the error, got %+v", segments) + } + if strings.Contains(stderr, "billing and usage") || !strings.Contains(stderr, `"code":"LIMIT_UNREADABLE"`) || !strings.Contains(stderr, `Workspace \"Staging\"`) { + t.Errorf("expected a LIMIT_UNREADABLE warning naming the workspace, got stderr: %s", stderr) + } +} + +func TestBillingStatus_DryRunReadsNothing(t *testing.T) { + setupAddFunds(t) + server := newStatusServer(t, flexStatusAccount) + + stdout, stderr, err := executeCommand("billing", "status", "--api-url", server.URL, "--dry-run") + if err != nil { + t.Fatalf("unexpected error: %v\nstderr: %s", err, stderr) + } + if len(server.paths) != 0 { + t.Errorf("expected no requests, got %v", server.paths) + } + var result struct { + DryRun bool `json:"dry_run"` + URLs []string `json:"urls"` + } + if err := json.Unmarshal([]byte(stdout), &result); err != nil { + t.Fatalf("invalid JSON output: %v\nstdout: %s", err, stdout) + } + if !result.DryRun || len(result.URLs) != 5 || result.URLs[1] != server.URL+"/v1/accounts/{account_id}/billing/wallet/usage" { + t.Errorf("expected the five reads, got %+v", result) + } +} diff --git a/cmd/prime.go b/cmd/prime.go index 52f0a66..84aadd3 100644 --- a/cmd/prime.go +++ b/cmd/prime.go @@ -3,6 +3,7 @@ package cmd import ( _ "embed" "fmt" + "strings" "github.com/spf13/cobra" ) @@ -10,6 +11,11 @@ import ( //go:embed prime_context.md var primeContext string +// defaultCLILoginURL is the token page URL written into prime_context.md. +// prime swaps it for the resolved URL so non-production profiles see their +// own token page. +const defaultCLILoginURL = "https://fly.customer.io/cli" + var primeCmd = &cobra.Command{ Use: "prime", Short: "Print LLM-ready instructions for using this CLI", @@ -22,7 +28,8 @@ Example: cio prime >> system_prompt.txt`, Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { - _, err := fmt.Fprint(cmd.OutOrStdout(), primeContext) + loginURL := resolveCLILoginURL(resolveLoginBaseURL(cmd)) + _, err := fmt.Fprint(cmd.OutOrStdout(), strings.ReplaceAll(primeContext, defaultCLILoginURL, loginURL)) return err }, } diff --git a/cmd/prime_context.md b/cmd/prime_context.md index 7667e2e..57f233c 100644 --- a/cmd/prime_context.md +++ b/cmd/prime_context.md @@ -16,9 +16,24 @@ Auth uses service account tokens exchanged for JWTs. Check status with: cio auth status ``` -If auth fails or there is no token yet, read `cio skills read cio/auth.md` -and follow its login flow. Never have the user paste a token into the -conversation or pass one as a shell argument. +If `cio auth status` fails, read `cio skills read cio/auth.md` before acting. +It decides between signup (no account yet) and login (account exists, no +usable token). Run either flow yourself; don't ask the user to run commands. + +For login, run the waiting login and, in the same message, give the user +these steps (they may not see the command's output): + +```bash +cio auth login --from-clipboard --wait +``` + +1. I've started a login command that watches your clipboard. +2. Open https://fly.customer.io/cli and sign in. +3. Copy the token shown. It's picked up automatically. + +The command waits up to 90 seconds. On timeout, re-run it right away without +ending your turn. Never have the user paste a token into the conversation or +pass one as a shell argument. ## Profiles diff --git a/cmd/prime_test.go b/cmd/prime_test.go new file mode 100644 index 0000000..58a6704 --- /dev/null +++ b/cmd/prime_test.go @@ -0,0 +1,37 @@ +package cmd + +import ( + "strings" + "testing" +) + +func TestPrime_UsesDefaultTokenPageURL(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + t.Setenv("CIO_API_URL", "") + t.Setenv("CIO_UI_URL", "") + + stdout, _, err := executeCommand("prime") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if !strings.Contains(stdout, "Open https://fly.customer.io/cli and sign in.") { + t.Errorf("expected the production token page in prime output") + } +} + +func TestPrime_UsesResolvedTokenPageURL(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + t.Setenv("CIO_API_URL", "") + t.Setenv("CIO_UI_URL", "https://ui.example.com") + + stdout, _, err := executeCommand("prime") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if !strings.Contains(stdout, "Open https://ui.example.com/cli and sign in.") { + t.Errorf("expected the CIO_UI_URL token page in prime output") + } + if strings.Contains(stdout, defaultCLILoginURL) { + t.Errorf("prime output still names the production token page") + } +}