console, cli: operators list and close billing problems (plans 6a)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
12 files changed,
+558
−0
billing_cli.go+148 −0billing_cli_copy.go+15 −0billing_cli_test.go+76 −0internal/console/apibilling.go+159 −0internal/console/apibilling_copy.go+12 −0internal/console/apibilling_test.go+104 −0internal/console/authcli.go+2 −0internal/console/claim_invariant_fixtures_test.go+2 −0internal/console/claim_invariant_probes_nonapp_test.go+34 −0internal/console/claim_invariant_probes_read_test.go+1 −0internal/console/testdata/claim-routes.txt+2 −0main.go+3 −0
diff --git a/billing_cli.go b/billing_cli.go| new file mode 100644 |
| index 000000000..cd070527e |
| --- /dev/null |
| +++ b/billing_cli.go |
| @@ -0,0 +1,148 @@ |
| +package main |
| + |
| +// `carlos billing`: a deployment operator lists the billing problems the |
| +// console could not settle, and closes one once it is settled at the |
| +// provider (internal/console/apibilling.go; plans 6a). |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "flag" |
| + "fmt" |
| + "io" |
| + "log" |
| + "net/http" |
| + "strconv" |
| + "strings" |
| + "time" |
| +) |
| + |
| +// billingProblemReply mirrors the console door's wire shape. |
| +type billingProblemReply struct { |
| + ID int64 `json:"id"` |
| + Account string `json:"account"` |
| + Subscription string `json:"subscription"` |
| + Reason string `json:"reason"` |
| + Detail string `json:"detail"` |
| + OpenedAt time.Time `json:"opened_at"` |
| + ClosedAt *time.Time `json:"closed_at,omitempty"` |
| + ClosedBy string `json:"closed_by,omitempty"` |
| + Note string `json:"note,omitempty"` |
| +} |
| + |
| +func runBilling(args []string) { |
| + if err := runBillingWithSession(context.Background(), nil, args, stdout); err != nil { |
| + if errors.Is(err, flag.ErrHelp) { |
| + return |
| + } |
| + log.Fatalf("billing: %v", err) |
| + } |
| +} |
| + |
| +func runBillingWithSession(ctx context.Context, sess *apiSession, args []string, out io.Writer) error { |
| + if len(args) == 0 { |
| + return errors.New(cliBillingCopyUsage) |
| + } |
| + verb, rest := args[0], args[1:] |
| + fs := flag.NewFlagSet("billing "+verb, flag.ContinueOnError) |
| + fs.SetOutput(out) |
| + consoleFlag := consoleOption(fs, "console origin to use") |
| + fs.Usage = flagUsage(fs, "") |
| + switch verb { |
| + case "problems": |
| + all := fs.Bool("all", false, cliBillingCopyFlagAll) |
| + if err := fs.Parse(rest); err != nil { |
| + return err |
| + } |
| + if fs.NArg() != 0 { |
| + return fmt.Errorf("unexpected argument %q", fs.Arg(0)) |
| + } |
| + if sess == nil { |
| + sess = requireBillingAPISession(*consoleFlag) |
| + printUsing(out, sess) |
| + } |
| + path := "/api/cli/billing/problems" |
| + if *all { |
| + path += "?all=1" |
| + } |
| + status, body, err := sess.getJSON(ctx, path) |
| + if err != nil { |
| + return err |
| + } |
| + if status != http.StatusOK { |
| + return apiErrorFromBody(status, body) |
| + } |
| + var list []billingProblemReply |
| + if err := json.Unmarshal(body, &list); err != nil { |
| + return fmt.Errorf("billing problems: unreadable response: %w", err) |
| + } |
| + printBillingProblems(out, list) |
| + return nil |
| + case "close": |
| + id := fs.Int64("id", 0, cliBillingCopyFlagID) |
| + note := fs.String("note", "", cliBillingCopyFlagNote) |
| + if err := fs.Parse(rest); err != nil { |
| + return err |
| + } |
| + if fs.NArg() != 0 { |
| + return fmt.Errorf("unexpected argument %q", fs.Arg(0)) |
| + } |
| + if *id <= 0 { |
| + return errors.New(cliBillingCopyIDRequired) |
| + } |
| + if strings.TrimSpace(*note) == "" { |
| + return errors.New(cliBillingCopyNoteRequired) |
| + } |
| + if sess == nil { |
| + sess = requireBillingAPISession(*consoleFlag) |
| + printUsing(out, sess) |
| + } |
| + status, body, err := sess.postJSON(ctx, "/api/cli/billing/problems/"+strconv.FormatInt(*id, 10)+"/close", map[string]string{"note": *note}) |
| + if err != nil { |
| + return err |
| + } |
| + if status != http.StatusOK { |
| + return apiErrorFromBody(status, body) |
| + } |
| + fmt.Fprintln(out, colorFor(out).ok(fmt.Sprintf(cliBillingCopyClosed, *id))) |
| + return nil |
| + default: |
| + return errors.New(cliBillingCopyUsage) |
| + } |
| +} |
| + |
| +// printBillingProblems prints one line per problem: id, account, reason, |
| +// subscription, when it opened (UTC) and the detail. |
| +func printBillingProblems(w io.Writer, list []billingProblemReply) { |
| + if len(list) == 0 { |
| + fmt.Fprintln(w, cliBillingCopyNoProblems) |
| + return |
| + } |
| + for _, p := range list { |
| + account := p.Account |
| + if account == "" { |
| + account = "-" |
| + } |
| + line := fmt.Sprintf("%d %s %s %s %s %s", p.ID, account, p.Reason, p.Subscription, |
| + p.OpenedAt.UTC().Format("2006-01-02 15:04"), p.Detail) |
| + if p.ClosedAt != nil { |
| + line += fmt.Sprintf(" (closed %s by %s: %s)", p.ClosedAt.UTC().Format("2006-01-02 15:04"), p.ClosedBy, p.Note) |
| + } |
| + fmt.Fprintln(w, line) |
| + } |
| +} |
| + |
| +// requireBillingAPISession is the console session the billing doors need. |
| +// Billing lives in the console's database, so direct bucket mode has no |
| +// equivalent. |
| +func requireBillingAPISession(consoleFlag string) *apiSession { |
| + sess, err := resolveMode(consoleFlag) |
| + if err != nil { |
| + log.Fatal(err) |
| + } |
| + if sess == nil { |
| + log.Fatal(cliBillingCopyNeedsConsole) |
| + } |
| + return sess |
| +} |
diff --git a/billing_cli_copy.go b/billing_cli_copy.go| new file mode 100644 |
| index 000000000..074f43bbb |
| --- /dev/null |
| +++ b/billing_cli_copy.go |
| @@ -0,0 +1,15 @@ |
| +package main |
| + |
| +// `carlos billing` strings (billing_cli.go). Draft copy: the Luna pass |
| +// (plans 6a Task 9) replaces these. |
| +const ( |
| + cliBillingCopyUsage = "usage: carlos billing problems [-all] | close -id N -note \"...\"" |
| + cliBillingCopyFlagAll = "include closed problems" |
| + cliBillingCopyFlagID = "the problem to close, from carlos billing problems" |
| + cliBillingCopyFlagNote = "what you did in stripe. it is kept with the problem" |
| + cliBillingCopyNoteRequired = "say what you did in stripe with -note" |
| + cliBillingCopyIDRequired = "say which problem to close with -id" |
| + cliBillingCopyNoProblems = "no open billing problems" |
| + cliBillingCopyClosed = "problem %d closed" |
| + cliBillingCopyNeedsConsole = "carlos billing works through a console, and this shell is in direct bucket mode\n(CARLOS_DEPLOYMENT_BUCKET/CARLOS_DEPLOYMENT_DIR is set). billing is kept by the console.\nunset the store env and run: carlos auth login --console <url>" |
| +) |
diff --git a/billing_cli_test.go b/billing_cli_test.go| new file mode 100644 |
| index 000000000..aa1733b25 |
| --- /dev/null |
| +++ b/billing_cli_test.go |
| @@ -0,0 +1,76 @@ |
| +package main |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +func TestBillingCLIProblemsAndClose(t *testing.T) { |
| + var paths []string |
| + var closeBody map[string]string |
| + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + paths = append(paths, r.Method+" "+r.URL.RequestURI()) |
| + switch { |
| + case r.Method == http.MethodGet: |
| + io.WriteString(w, `[{"id":7,"account":"bab","subscription":"sub_1","reason":"unrecognised","detail":"price x is not in the price map","opened_at":"2026-10-25T12:00:00Z"}]`) |
| + case r.Method == http.MethodPost: |
| + _ = json.NewDecoder(r.Body).Decode(&closeBody) |
| + io.WriteString(w, `{"id":7,"account":"bab","subscription":"sub_1","reason":"unrecognised","detail":"","opened_at":"2026-10-25T12:00:00Z","closed_at":"2026-10-25T13:00:00Z","closed_by":"ops@example.com","note":"refunded"}`) |
| + } |
| + })) |
| + defer ts.Close() |
| + s := newTestSession(ts.URL) |
| + |
| + var out bytes.Buffer |
| + if err := runBillingWithSession(context.Background(), s, []string{"problems"}, &out); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, want := range []string{"7", "bab", "unrecognised", "sub_1", "2026-10-25 12:00", "price x is not in the price map"} { |
| + if !strings.Contains(out.String(), want) { |
| + t.Errorf("problems output lacks %q:\n%s", want, out.String()) |
| + } |
| + } |
| + if err := runBillingWithSession(context.Background(), s, []string{"problems", "-all"}, io.Discard); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := runBillingWithSession(context.Background(), s, []string{"close", "-id", "7", "-note", "refunded"}, io.Discard); err != nil { |
| + t.Fatal(err) |
| + } |
| + want := []string{"GET /api/cli/billing/problems", "GET /api/cli/billing/problems?all=1", "POST /api/cli/billing/problems/7/close"} |
| + if strings.Join(paths, "|") != strings.Join(want, "|") { |
| + t.Fatalf("paths %v, want %v", paths, want) |
| + } |
| + if closeBody["note"] != "refunded" { |
| + t.Fatalf("close body %v", closeBody) |
| + } |
| + |
| + hits := len(paths) |
| + err := runBillingWithSession(context.Background(), s, []string{"close", "-id", "7"}, io.Discard) |
| + if err == nil || err.Error() != cliBillingCopyNoteRequired { |
| + t.Fatalf("missing -note: %v, want %q", err, cliBillingCopyNoteRequired) |
| + } |
| + if err := runBillingWithSession(context.Background(), s, []string{"close", "-note", "x"}, io.Discard); err == nil { |
| + t.Fatal("missing -id accepted") |
| + } |
| + if len(paths) != hits { |
| + t.Fatal("a refused command reached the console") |
| + } |
| +} |
| + |
| +func TestBillingCLINoProblems(t *testing.T) { |
| + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, `[]`) })) |
| + defer ts.Close() |
| + var out bytes.Buffer |
| + if err := runBillingWithSession(context.Background(), newTestSession(ts.URL), []string{"problems"}, &out); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !strings.Contains(out.String(), cliBillingCopyNoProblems) { |
| + t.Fatalf("output %q", out.String()) |
| + } |
| +} |
diff --git a/internal/console/apibilling.go b/internal/console/apibilling.go| new file mode 100644 |
| index 000000000..e4e426aad |
| --- /dev/null |
| +++ b/internal/console/apibilling.go |
| @@ -0,0 +1,159 @@ |
| +package console |
| + |
| +import ( |
| + "errors" |
| + "log" |
| + "net/http" |
| + "strconv" |
| + "strings" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/billing" |
| +) |
| + |
| +// The operator's billing problem doors (plans 6a, Calls 1 to 3): list the |
| +// problems the sync opened, and close one with a note once it is settled |
| +// at the provider. |
| + |
| +// billingProblemReply is one problem on the wire. |
| +type billingProblemReply struct { |
| + ID int64 `json:"id"` |
| + Account string `json:"account"` |
| + Subscription string `json:"subscription"` |
| + Reason string `json:"reason"` |
| + Detail string `json:"detail"` |
| + OpenedAt time.Time `json:"opened_at"` |
| + ClosedAt *time.Time `json:"closed_at,omitempty"` |
| + ClosedBy string `json:"closed_by,omitempty"` |
| + Note string `json:"note,omitempty"` |
| +} |
| + |
| +// billingDoor gates both doors in accountPlanDoor's order: signed in, then |
| +// an operator (the stdlib 404 otherwise), then billing configured (409). |
| +func (s *Server) billingDoor(w http.ResponseWriter, r *http.Request) (string, bool) { |
| + addr, ok := s.cliUser(w, r) |
| + if !ok { |
| + return "", false |
| + } |
| + isOperator, err := s.store.IsOperator(addr) |
| + if err != nil { |
| + log.Printf("console: api billing: is-operator: %v", err) |
| + http.NotFound(w, r) |
| + return "", false |
| + } |
| + if !isOperator { |
| + http.NotFound(w, r) |
| + return "", false |
| + } |
| + if s.billing == nil { |
| + jsonError(w, http.StatusConflict, billingCopyOff) |
| + return "", false |
| + } |
| + return addr, true |
| +} |
| + |
| +func (s *Server) billingProblemReplyFor(p billingProblem) billingProblemReply { |
| + out := billingProblemReply{ID: p.ID, Subscription: p.Subscription, Reason: p.Reason, Detail: p.Detail, |
| + OpenedAt: p.OpenedAt.UTC(), ClosedBy: p.ClosedBy, Note: p.Note} |
| + if p.AccountID != 0 { |
| + if a, err := s.store.AccountByID(p.AccountID); err == nil && a != nil { |
| + out.Account = a.Sqid |
| + } |
| + } |
| + if !p.ClosedAt.IsZero() { |
| + c := p.ClosedAt.UTC() |
| + out.ClosedAt = &c |
| + } |
| + return out |
| +} |
| + |
| +// handleAPIBillingProblems is GET /api/cli/billing/problems: open problems, |
| +// newest first; ?all=1 includes closed ones. |
| +func (s *Server) handleAPIBillingProblems(w http.ResponseWriter, r *http.Request) { |
| + if _, ok := s.billingDoor(w, r); !ok { |
| + return |
| + } |
| + list, err := s.store.BillingProblems(r.URL.Query().Get("all") == "1") |
| + if err != nil { |
| + log.Printf("console: api billing problems: %v", err) |
| + jsonError(w, http.StatusInternalServerError, billingCopyFailed) |
| + return |
| + } |
| + out := make([]billingProblemReply, 0, len(list)) |
| + for _, p := range list { |
| + out = append(out, s.billingProblemReplyFor(p)) |
| + } |
| + writeJSON(w, http.StatusOK, out) |
| +} |
| + |
| +// handleAPIBillingProblemClose is POST /api/cli/billing/problems/{id}/close |
| +// with {"note": "..."}. The console cannot see refunds, so the note is the |
| +// operator's record of what they did. It refuses while a fresh read shows |
| +// the subscription still live. |
| +func (s *Server) handleAPIBillingProblemClose(w http.ResponseWriter, r *http.Request) { |
| + addr, ok := s.billingDoor(w, r) |
| + if !ok { |
| + return |
| + } |
| + var req struct { |
| + Note string `json:"note"` |
| + } |
| + if !readJSONStrictLimit(w, r, &req, 8<<10) { |
| + return |
| + } |
| + note := strings.TrimSpace(req.Note) |
| + if note == "" { |
| + jsonError(w, http.StatusBadRequest, billingCopyNoteRequired) |
| + return |
| + } |
| + id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) |
| + if err != nil { |
| + http.NotFound(w, r) |
| + return |
| + } |
| + p, err := s.store.BillingProblem(id) |
| + if err != nil { |
| + log.Printf("console: api billing close %d: %v", id, err) |
| + jsonError(w, http.StatusInternalServerError, billingCopyFailed) |
| + return |
| + } |
| + if p == nil { |
| + http.NotFound(w, r) |
| + return |
| + } |
| + if !p.ClosedAt.IsZero() { |
| + jsonError(w, http.StatusConflict, billingCopyClosed) |
| + return |
| + } |
| + if p.Subscription != "" { |
| + sub, err := s.billing.cfg.Provider.Subscription(r.Context(), p.Subscription) |
| + switch { |
| + case errors.Is(err, billing.ErrNotFound): |
| + case err != nil: |
| + log.Printf("console: api billing close %d: reading subscription: %v", id, err) |
| + jsonError(w, http.StatusServiceUnavailable, billingCopyProviderDown) |
| + return |
| + case liveState(sub.State): |
| + jsonError(w, http.StatusConflict, billingCopyStillLive) |
| + return |
| + } |
| + } |
| + now := time.Now() |
| + if err := s.store.CloseBillingProblem(id, addr, note, now); err != nil { |
| + if errors.Is(err, errBillingProblemClosed) { |
| + jsonError(w, http.StatusConflict, billingCopyClosed) |
| + return |
| + } |
| + log.Printf("console: api billing close %d: %v", id, err) |
| + jsonError(w, http.StatusInternalServerError, billingCopyFailed) |
| + return |
| + } |
| + log.Printf("console: billing problem %d closed by %s", id, addr) |
| + closed, err := s.store.BillingProblem(id) |
| + if err != nil || closed == nil { |
| + log.Printf("console: api billing close %d: reread: %v", id, err) |
| + jsonError(w, http.StatusInternalServerError, billingCopyFailed) |
| + return |
| + } |
| + writeJSON(w, http.StatusOK, s.billingProblemReplyFor(*closed)) |
| +} |
diff --git a/internal/console/apibilling_copy.go b/internal/console/apibilling_copy.go| new file mode 100644 |
| index 000000000..1355963de |
| --- /dev/null |
| +++ b/internal/console/apibilling_copy.go |
| @@ -0,0 +1,12 @@ |
| +package console |
| + |
| +// Door errors for the billing problem doors (apibilling.go). Draft copy: |
| +// the Luna pass (plans 6a Task 9) replaces these. |
| +const ( |
| + billingCopyOff = "billing is off on this deployment. set CARLOS_BILLING on the console to turn it on" |
| + billingCopyStillLive = "the subscription is still live at the provider. cancel it there, then close the problem" |
| + billingCopyNoteRequired = "say what you did in stripe with -note" |
| + billingCopyClosed = "this problem is already closed" |
| + billingCopyProviderDown = "the billing provider did not answer. try again in a minute" |
| + billingCopyFailed = "could not read or save billing problems. try again" |
| +) |
diff --git a/internal/console/apibilling_test.go b/internal/console/apibilling_test.go| new file mode 100644 |
| index 000000000..147790088 |
| --- /dev/null |
| +++ b/internal/console/apibilling_test.go |
| @@ -0,0 +1,104 @@ |
| +package console |
| + |
| +import ( |
| + "encoding/json" |
| + "net/http" |
| + "strconv" |
| + "testing" |
| +) |
| + |
| +func billingProblemsURL(fx *consoleFixture) string { return fx.ts.URL + "/api/cli/billing/problems" } |
| + |
| +func billingCloseURL(fx *consoleFixture, id int64) string { |
| + return fx.ts.URL + "/api/cli/billing/problems/" + strconv.FormatInt(id, 10) + "/close" |
| +} |
| + |
| +func TestBillingProblemsDoorIsOperatorOnly(t *testing.T) { |
| + bf := newBillingFixture(t) |
| + if _, err := bf.st.OpenBillingProblem(bf.acct.ID, "sub_1", problemUnrecognised, "price x is not in the price map", billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + owner := "owner" + bf.acct.Sqid + "@example.com" |
| + member := cliToken(t, bf.consoleFixture, owner, "code-billing-owner") |
| + if status, body := getRaw(t, billingProblemsURL(bf.consoleFixture), member); status != http.StatusNotFound || body != "404 page not found\n" { |
| + t.Fatalf("member: %d %q, want the stdlib 404", status, body) |
| + } |
| + op := planOperatorToken(t, bf.consoleFixture, "ops@keymail.dev", "code-billing-op") |
| + status, body := getRaw(t, billingProblemsURL(bf.consoleFixture), op) |
| + if status != http.StatusOK { |
| + t.Fatalf("operator: %d %s", status, body) |
| + } |
| + var got []billingProblemReply |
| + if err := json.Unmarshal([]byte(body), &got); err != nil { |
| + t.Fatalf("decode %q: %v", body, err) |
| + } |
| + if len(got) != 1 || got[0].Account != bf.acct.Sqid || got[0].Reason != problemUnrecognised || got[0].Subscription != "sub_1" || got[0].ClosedAt != nil { |
| + t.Fatalf("problems = %+v", got) |
| + } |
| + |
| + off := newConsoleFixture(t) |
| + opOff := planOperatorToken(t, off, "ops@keymail.dev", "code-billing-off") |
| + if status, out := getJSON(t, billingProblemsURL(off), opOff); status != http.StatusConflict || out["error"] != billingCopyOff { |
| + t.Fatalf("billing off: %d %v, want 409 %q", status, out, billingCopyOff) |
| + } |
| +} |
| + |
| +func TestCloseRefusedWhileLive(t *testing.T) { |
| + bf := newBillingFixture(t) |
| + bf.put(bf.personalSub("sub_1", "active", nil)) |
| + if _, err := bf.st.OpenBillingProblem(bf.acct.ID, "sub_1", problemSecondSubscription, "", billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + open, _ := bf.st.BillingProblems(false) |
| + id := open[0].ID |
| + op := planOperatorToken(t, bf.consoleFixture, "ops@keymail.dev", "code-billing-close") |
| + note := map[string]any{"note": "refunded and cancelled in the dashboard"} |
| + if status, out := postJSON(t, billingCloseURL(bf.consoleFixture, id), note, op); status != http.StatusConflict || out["error"] != billingCopyStillLive { |
| + t.Fatalf("live: %d %v", status, out) |
| + } |
| + bf.put(bf.personalSub("sub_1", "canceled", nil)) |
| + status, out := postJSON(t, billingCloseURL(bf.consoleFixture, id), note, op) |
| + if status != http.StatusOK || out["closed_by"] != "ops@keymail.dev" || out["note"] != note["note"] || out["closed_at"] == nil { |
| + t.Fatalf("ended: %d %v", status, out) |
| + } |
| + if status, _ := postJSON(t, billingCloseURL(bf.consoleFixture, id), note, op); status != http.StatusConflict { |
| + t.Fatalf("closed twice: %d, want 409", status) |
| + } |
| + if status, _ := postRaw(t, billingCloseURL(bf.consoleFixture, 99999), note, op); status != http.StatusNotFound { |
| + t.Fatalf("unknown: %d, want 404", status) |
| + } |
| + // A subscription the provider does not know any more can be closed. |
| + if _, err := bf.st.OpenBillingProblem(bf.acct.ID, "sub_gone", problemUnrecognised, "", billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + open, _ = bf.st.BillingProblems(false) |
| + if status, out := postJSON(t, billingCloseURL(bf.consoleFixture, open[0].ID), note, op); status != http.StatusOK { |
| + t.Fatalf("not found at the provider: %d %v", status, out) |
| + } |
| + // A transient provider error is 503 and closes nothing. |
| + if _, err := bf.st.OpenBillingProblem(bf.acct.ID, "sub_1", problemUnrecognised, "", billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + open, _ = bf.st.BillingProblems(false) |
| + bf.fake.Err = http.ErrHandlerTimeout |
| + if status, _ := postJSON(t, billingCloseURL(bf.consoleFixture, open[0].ID), note, op); status != http.StatusServiceUnavailable { |
| + t.Fatalf("transient: %d, want 503", status) |
| + } |
| + if p, _ := bf.st.BillingProblem(open[0].ID); !p.ClosedAt.IsZero() { |
| + t.Fatal("closed on a transient error") |
| + } |
| +} |
| + |
| +func TestCloseNeedsANote(t *testing.T) { |
| + bf := newBillingFixture(t) |
| + if _, err := bf.st.OpenBillingProblem(bf.acct.ID, "sub_1", problemUnrecognised, "", billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + open, _ := bf.st.BillingProblems(false) |
| + op := planOperatorToken(t, bf.consoleFixture, "ops@keymail.dev", "code-billing-note") |
| + for _, note := range []string{"", " "} { |
| + if status, _ := postJSON(t, billingCloseURL(bf.consoleFixture, open[0].ID), map[string]any{"note": note}, op); status != http.StatusBadRequest { |
| + t.Errorf("note %q: %d, want 400", note, status) |
| + } |
| + } |
| +} |
diff --git a/internal/console/authcli.go b/internal/console/authcli.go| index 55aa45380..82b01d3dc 100644 |
| --- a/internal/console/authcli.go |
| +++ b/internal/console/authcli.go |
| @@ -954,6 +954,8 @@ func (s *Server) registerCLIRoutes() { |
| s.cliRoute("POST /api/cli/accounts/{account}/store/approve", svcrole.Set{}, s.handleAPIStoreApprove) |
| s.cliRoute("GET /api/cli/accounts/{account}/plan", svcrole.Set{}, s.handleAPIAccountPlanGet) |
| s.cliRoute("POST /api/cli/accounts/{account}/plan", svcrole.Set{}, s.handleAPIAccountPlanSet) |
| + s.cliRoute("GET /api/cli/billing/problems", svcrole.Set{}, s.handleAPIBillingProblems) |
| + s.cliRoute("POST /api/cli/billing/problems/{id}/close", svcrole.Set{}, s.handleAPIBillingProblemClose) |
| s.cliRoute("POST /api/cli/accounts/{account}/store/decline", svcrole.Set{}, s.handleAPIStoreDecline) |
| s.cliRoute("GET /api/cli/store/approvals", svcrole.Set{}, s.handleAPIStoreApprovals) |
| // The scan family (internal/console/apiscan.go). `scan` itself is the |
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go| index 11a85aec0..b84fd6d5b 100644 |
| --- a/internal/console/claim_invariant_fixtures_test.go |
| +++ b/internal/console/claim_invariant_fixtures_test.go |
| @@ -858,6 +858,7 @@ var claimFixtures = map[string]claimFixture{ |
| "route GET /api/cli/status/layout": claimRead("operator layout view"), |
| "route GET /api/cli/store/approvals": claimRead("operator entitlement queue"), |
| "route GET /api/cli/accounts/{account}/plan": claimRead("operator view of an account's plan and limits"), |
| + "route GET /api/cli/billing/problems": claimRead("operator view of billing problems; names no app"), |
| "route GET /api/cli/system/antivirus": claimRead("reads the deployment scanning setting"), |
| "route GET /api/cli/system/geoip": claimRead("operator view of the GeoIP pointer, box heartbeats and feed status (control/geoip/, status/, edge files); writes nothing"), |
| "route GET /api/cli/system/jobs/{id}": claimRead("reads a system update job"), |
| @@ -1258,6 +1259,7 @@ var claimFixtures = map[string]claimFixture{ |
| "route POST /api/cli/accounts/{account}/store/apply": claimNonApp("applies for the account's storage entitlement"), |
| "route POST /api/cli/accounts/{account}/store/approve": claimNonApp("operator approves an account's storage entitlement"), |
| "route POST /api/cli/accounts/{account}/plan": claimNonApp("operator sets an account's plan, packs and sponsored limits; names no app"), |
| + "route POST /api/cli/billing/problems/{id}/close": claimNonApp("operator closes a billing problem with a note after a fresh provider read; names no app"), |
| "route POST /api/cli/accounts/{account}/store/decline": claimNonApp("operator declines an account's storage entitlement"), |
| "route POST /api/cli/fleets/{account}/new": claimNonApp("creates a customer fleet in the registry"), |
| "route POST /api/cli/fleets/{account}/{fleet}/boxes": claimNonApp("enrolls a fleet box"), |
diff --git a/internal/console/claim_invariant_probes_nonapp_test.go b/internal/console/claim_invariant_probes_nonapp_test.go| index 78cddd8cf..7f4d28fee 100644 |
| --- a/internal/console/claim_invariant_probes_nonapp_test.go |
| +++ b/internal/console/claim_invariant_probes_nonapp_test.go |
| @@ -18,6 +18,7 @@ import ( |
| "time" |
| "github.com/carlosframework/platform/internal/billing" |
| + "github.com/carlosframework/platform/internal/billing/billingtest" |
| "github.com/carlosframework/platform/internal/economics" |
| "github.com/carlosframework/platform/internal/geoip" |
| "github.com/carlosframework/platform/internal/infraview" |
| @@ -690,6 +691,23 @@ var claimNonAppProbes = map[string]claimProbe{ |
| return claimBillingPlanIs(t, cx, "personal") |
| }, |
| }, |
| + "route POST /api/cli/billing/problems/{id}/close": { |
| + setup: claimBillingProblemWorld, |
| + do: func(t *testing.T, cx *claimCase) claimReply { |
| + open, err := cx.srv.store.BillingProblems(false) |
| + if err != nil || len(open) != 1 { |
| + t.Fatalf("open problems: %v %v", open, err) |
| + } |
| + return cx.apiReply(t, http.MethodPost, fmt.Sprintf("/api/cli/billing/problems/%d/close", open[0].ID), `{"note":"census"}`) |
| + }, |
| + body: []string{`"note":"census"`}, |
| + effect: func(t *testing.T, cx *claimCase, r claimReply) string { |
| + if open, err := cx.srv.store.BillingProblems(false); err != nil || len(open) != 0 { |
| + return "the billing problem is still open" |
| + } |
| + return "" |
| + }, |
| + }, |
| "route POST /api/cli/accounts/{account}/plan": { |
| setup: func(t *testing.T, cx *claimCase) { cx.srv.cfg.PlanCatalog = examplePlanCatalog(t) }, |
| do: claimAPIReply(http.MethodPost, "/api/cli/accounts/bab/plan", `{"plan":"personal","reason":"census"}`), |
| @@ -1005,3 +1023,19 @@ func claimBillingPlanIs(t *testing.T, cx *claimCase, plan string) string { |
| } |
| return "" |
| } |
| + |
| +// claimBillingProblemWorld is claimBillingWorld with an open problem on a |
| +// subscription the provider says has ended, so it can be closed. |
| +func claimBillingProblemWorld(t *testing.T, cx *claimCase) { |
| + t.Helper() |
| + claimBillingWorld(t, cx) |
| + acct, err := cx.srv.store.AccountBySqid("bab") |
| + if err != nil || acct == nil { |
| + t.Fatalf("bab: %v", err) |
| + } |
| + fake := cx.srv.billing.cfg.Provider.(*billingtest.Fake) |
| + fake.Subs["sub_old"] = testPersonalSub("sub_old", "cus_claim", "bab", "canceled", nil) |
| + if _, err := cx.srv.store.OpenBillingProblem(acct.ID, "sub_old", problemUnrecognised, "census", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
diff --git a/internal/console/claim_invariant_probes_read_test.go b/internal/console/claim_invariant_probes_read_test.go| index e4c317053..f2d94ce63 100644 |
| --- a/internal/console/claim_invariant_probes_read_test.go |
| +++ b/internal/console/claim_invariant_probes_read_test.go |
| @@ -241,6 +241,7 @@ var claimReadProbes = map[string]claimProbe{ |
| "route GET /api/cli/store/approvals": claimAPIRead(claimWorldApply, "/api/cli/store/approvals", `"applications"`, claimFxOwner), |
| "route GET /api/cli/accounts/{account}/plan": claimAPIRead(func(t *testing.T, cx *claimCase) { cx.srv.cfg.PlanCatalog = examplePlanCatalog(t) }, |
| "/api/cli/accounts/bab/plan", `"plan":"free"`), |
| + "route GET /api/cli/billing/problems": claimAPIRead(claimBillingProblemWorld, "/api/cli/billing/problems", `"reason":"unrecognised"`), |
| "route GET /api/cli/system/antivirus": claimAPIRead(nil, "/api/cli/system/antivirus", `"wired":true`), |
| "route GET /api/cli/system/geoip": func() claimProbe { |
| p := claimAPIRead(claimWorldGeoip, "/api/cli/system/geoip", `"pointer"`, "GeoIP2-City") |
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt| index 40f23e091..c5bcb2e42 100644 |
| --- a/internal/console/testdata/claim-routes.txt |
| +++ b/internal/console/testdata/claim-routes.txt |
| @@ -38,6 +38,7 @@ route GET /a/{sqid}/trash |
| route GET /a/{sqid}/{$} |
| route GET /accounts/new |
| route GET /api/cli/accounts/{account}/plan |
| +route GET /api/cli/billing/problems |
| route GET /api/cli/apps |
| route GET /api/cli/apps/{account}/list |
| route GET /api/cli/apps/{account}/{app}/analytics |
| @@ -165,6 +166,7 @@ route POST /a/{sqid}/trash/delete |
| route POST /a/{sqid}/trash/restore |
| route POST /accounts/new |
| route POST /api/cli/accounts/{account}/plan |
| +route POST /api/cli/billing/problems/{id}/close |
| route POST /api/cli/accounts/{account}/store/apply |
| route POST /api/cli/accounts/{account}/store/approve |
| route POST /api/cli/accounts/{account}/store/decline |
diff --git a/main.go b/main.go| index 393054f5b..9fed3be08 100644 |
| --- a/main.go |
| +++ b/main.go |
| @@ -160,6 +160,8 @@ func main() { |
| RunConfig(args) |
| case "accounts": |
| RunAccounts(args) |
| + case "billing": |
| + runBilling(args) |
| case "apps": |
| RunApps(args) |
| case "fleets": |
| @@ -304,6 +306,7 @@ Your apps — ship and run software on a CARLOS deployment |
| Your deployment — stand up and administer boxes, routes and accounts |
| bootstrap prepare a host: units, dirs, user |
| accounts the tenancy primitive: create | list | migrate |
| + billing billing problems the console could not settle: problems | close |
| fleets account-owned groups of remote boxes that dial this |
| console: create | add-box | rotate-token | tag-box | |
| detach-box | ls — box tokens print exactly once, at mint |