cli: carlos billing revenue and payments
Two operator doors on the console, GET /api/cli/billing/revenue and GET
/api/cli/billing/payments (billingDoor: 404 for a member, 409 with billing
off), and the two verbs in runBillingWithSession that print them.
revenueFigures puts every revenue figure through moneyReady with the
inputs it declares: arr and mrr the facts, payments, amounts and the
rates of ARR's currencies; paying, attention and groups the facts and
payments; accounts nothing. A refused figure is {"available":false,
"why":...} with no number. The payments door lists up to 500 recorded
payments, newest first, by month (UTC) and kind; a bad month or kind is
400 with the approved text.
Copy from the approved record BDC-1 to BDC-38, gated by
approved_billing_dashboard_copy_test.go. Docs in cli.md and plans.md; the
setup script's webhook line now says nine events. Claim fixtures and the
route census carry the two new doors.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
14 files changed,
+947
−4
approved_billing_dashboard_copy_test.go+95 −0billing_cli.go+231 −2billing_cli_copy.go+43 −1billing_cli_test.go+145 −0docs/site/cli.md+7 −0docs/site/plans.md+2 −0internal/console/apibilling.go+193 −0internal/console/apibilling_copy.go+8 −0internal/console/apibilling_test.go+214 −0internal/console/authcli.go+2 −0internal/console/claim_invariant_fixtures_test.go+2 −0internal/console/claim_invariant_probes_read_test.go+2 −0internal/console/testdata/claim-routes.txt+2 −0scripts/stripe-setup.sh+1 −1
diff --git a/approved_billing_dashboard_copy_test.go b/approved_billing_dashboard_copy_test.go| new file mode 100644 |
| index 000000000..f5565e60e |
| --- /dev/null |
| +++ b/approved_billing_dashboard_copy_test.go |
| @@ -0,0 +1,95 @@ |
| +// approved_billing_dashboard_copy_test.go |
| +package main |
| + |
| +import ( |
| + "os" |
| + "regexp" |
| + "strconv" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +// The copy gate of the billing dashboard plan 1 (spec 2026-11-09). The record |
| +// is docs/superpowers/plans/2026-11-09-billing-dashboard-1-copy.md. It reuses |
| +// the asset cache gate's entryBuiltRows, the operator pages gate's |
| +// checkShortGoText and the moves gate's helpers, so the parser, the em dash |
| +// rule and the "text is in the file" match are the record formats' already. |
| +// |
| +// - TestBillingDashboardCopyInventory: the record names exactly |
| +// billingDashboardCopyIDs, and no row holds an em dash; |
| +// - TestApprovedBillingDashboardCopy: an id in billingDashboardCopyBuilt |
| +// is an approved row, and its text is in the file it names. No pending |
| +// string reaches code, docs or the script. |
| +const billingDashboardCopyRecordPath = "docs/superpowers/plans/2026-11-09-billing-dashboard-1-copy.md" |
| + |
| +var billingDashboardCopyIDPattern = regexp.MustCompile(`^BDC-[0-9]+$`) |
| + |
| +// billingDashboardCopyIDs is the record's inventory, pinned: BDC-1 to BDC-38. |
| +var billingDashboardCopyIDs = func() []string { |
| + ids := make([]string, 0, 38) |
| + for i := 1; i <= 38; i++ { |
| + ids = append(ids, "BDC-"+strconv.Itoa(i)) |
| + } |
| + return ids |
| +}() |
| + |
| +// billingDashboardCopyBuilt is every row whose text the code, docs or script |
| +// carry. The task that writes a row's text adds its entry here in the same |
| +// commit. |
| +var billingDashboardCopyBuilt = []string{ |
| + // Task 9: carlos billing revenue and payments (billing_cli_copy.go). |
| + "BDC-1", "BDC-2", "BDC-3", "BDC-4", "BDC-5", "BDC-6", "BDC-7", "BDC-8", |
| + "BDC-9", "BDC-10", "BDC-11", "BDC-12", "BDC-13", "BDC-14", "BDC-15", "BDC-16", |
| + "BDC-17", "BDC-18", "BDC-19", "BDC-20", |
| + "BDC-21", "BDC-22", "BDC-23", "BDC-24", "BDC-25", "BDC-26", "BDC-27", "BDC-28", "BDC-29", |
| + // Task 9: the payments door (internal/console/apibilling_copy.go). |
| + "BDC-30", "BDC-31", |
| + // Task 9: the docs and the setup script. |
| + "BDC-32", "BDC-33", "BDC-34", "BDC-35", "BDC-36", "BDC-37", "BDC-38", |
| +} |
| + |
| +// billingDashboardShortGoText is the built rows of one short word, each |
| +// the whole value of a string literal in its Go file (checkShortGoText), so |
| +// a word is never matched as a fragment of a longer one. |
| +var billingDashboardShortGoText = map[string]bool{ |
| + "BDC-4": true, "BDC-7": true, "BDC-9": true, "BDC-14": true, |
| + "BDC-23": true, "BDC-24": true, "BDC-25": true, "BDC-26": true, "BDC-27": true, |
| +} |
| + |
| +func mustParseBillingDashboardCopyRecord(t *testing.T) []copyRow { |
| + t.Helper() |
| + raw, err := os.ReadFile(billingDashboardCopyRecordPath) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + rows, err := parseCopyTable(string(raw), billingDashboardCopyRecordPath, billingDashboardCopyIDPattern, "a BDC-<n>") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return rows |
| +} |
| + |
| +func TestBillingDashboardCopyInventory(t *testing.T) { |
| + rows := mustParseBillingDashboardCopyRecord(t) |
| + reportAll(t, checkMovesInventory(rows, billingDashboardCopyIDs)) |
| + reportAll(t, checkMovesNoEmDash(rows)) |
| +} |
| + |
| +func TestApprovedBillingDashboardCopy(t *testing.T) { |
| + built, problems := entryBuiltRows(mustParseBillingDashboardCopyRecord(t), billingDashboardCopyBuilt, "billingDashboardCopyBuilt") |
| + // The record is a markdown table, where a literal pipe in a cell is |
| + // written \|; the code carries the plain pipe. |
| + var whole []copyRow |
| + for _, r := range built { |
| + r.Text = strings.ReplaceAll(r.Text, `\|`, "|") |
| + if billingDashboardShortGoText[r.ID] { |
| + problems = append(problems, checkShortGoText(r, ".")...) |
| + continue |
| + } |
| + whole = append(whole, r) |
| + } |
| + if len(built) != len(billingDashboardCopyIDs) { |
| + problems = append(problems, "every row of the record is built by Task 9, but billingDashboardCopyBuilt names "+strconv.Itoa(len(built))) |
| + } |
| + reportAll(t, append(problems, checkMovesApplied(whole, ".")...)) |
| +} |
diff --git a/billing_cli.go b/billing_cli.go| index 4a9275556..08c58cfa7 100644 |
| --- a/billing_cli.go |
| +++ b/billing_cli.go |
| @@ -2,8 +2,9 @@ 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), and marks or clears |
| -// an account as a house account, whose checkout is free (plans 6b). |
| +// provider (internal/console/apibilling.go; plans 6a), marks or clears |
| +// an account as a house account, whose checkout is free (plans 6b), and |
| +// reads the revenue and the recorded payments (billing dashboard plan 1). |
| import ( |
| "context" |
| @@ -13,7 +14,10 @@ import ( |
| "fmt" |
| "io" |
| "log" |
| + "maps" |
| "net/http" |
| + "net/url" |
| + "slices" |
| "strconv" |
| "strings" |
| "time" |
| @@ -80,6 +84,74 @@ func runBillingWithSession(ctx context.Context, sess *apiSession, args []string, |
| } |
| printBillingProblems(out, list) |
| return nil |
| + case "revenue": |
| + 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) |
| + } |
| + status, body, err := sess.getJSON(ctx, "/api/cli/billing/revenue") |
| + if err != nil { |
| + return err |
| + } |
| + if status != http.StatusOK { |
| + return apiErrorFromBody(status, body) |
| + } |
| + var rev billingRevenueReply |
| + if err := json.Unmarshal(body, &rev); err != nil { |
| + return fmt.Errorf("billing revenue: unreadable response: %w", err) |
| + } |
| + printBillingRevenue(out, rev) |
| + return nil |
| + case "payments": |
| + month := fs.String("month", "", cliBillingCopyFlagMonth) |
| + kind := fs.String("kind", "", cliBillingCopyFlagKind) |
| + if err := fs.Parse(rest); err != nil { |
| + return err |
| + } |
| + if fs.NArg() != 0 { |
| + return fmt.Errorf("unexpected argument %q", fs.Arg(0)) |
| + } |
| + q := url.Values{} |
| + if *month != "" { |
| + if _, err := time.Parse("2006-01", *month); err != nil || len(*month) != len("2006-01") { |
| + return errors.New(cliBillingCopyMonthFormat) |
| + } |
| + q.Set("month", *month) |
| + } |
| + if *kind != "" { |
| + k, ok := billingPaymentKindFlags[*kind] |
| + if !ok { |
| + return errors.New(cliBillingCopyKindFormat) |
| + } |
| + q.Set("kind", k) |
| + } |
| + if sess == nil { |
| + sess = requireBillingAPISession(*consoleFlag) |
| + printUsing(out, sess) |
| + } |
| + path := "/api/cli/billing/payments" |
| + if len(q) > 0 { |
| + path += "?" + q.Encode() |
| + } |
| + status, body, err := sess.getJSON(ctx, path) |
| + if err != nil { |
| + return err |
| + } |
| + if status != http.StatusOK { |
| + return apiErrorFromBody(status, body) |
| + } |
| + var list []billingPaymentReply |
| + if err := json.Unmarshal(body, &list); err != nil { |
| + return fmt.Errorf("billing payments: unreadable response: %w", err) |
| + } |
| + printBillingPayments(out, list) |
| + return nil |
| case "close": |
| id := fs.Int64("id", 0, cliBillingCopyFlagID) |
| note := fs.String("note", "", cliBillingCopyFlagNote) |
| @@ -184,3 +256,160 @@ func requireBillingAPISession(consoleFlag string) *apiSession { |
| } |
| return sess |
| } |
| + |
| +// billingFigure is one revenue figure on the wire: refused figures carry |
| +// only Why, the door's reason code. |
| +type billingFigure struct { |
| + Available bool `json:"available"` |
| + Why string `json:"why"` |
| + ByCurrency map[string]int64 `json:"by_currency"` |
| + EUR int64 `json:"eur"` |
| + RateDay string `json:"rate_day"` |
| + Count int `json:"count"` |
| + Counts map[string]int `json:"counts"` |
| +} |
| + |
| +// billingRevenueReply mirrors the console's revenue door. |
| +type billingRevenueReply struct { |
| + ARR billingFigure `json:"arr"` |
| + MRR billingFigure `json:"mrr"` |
| + Paying billingFigure `json:"paying"` |
| + Attention billingFigure `json:"attention"` |
| + Groups billingFigure `json:"groups"` |
| + Accounts int `json:"accounts"` |
| + TestMode bool `json:"test_mode"` |
| +} |
| + |
| +// billingWhyText is the text of each of the door's reason codes; a code |
| +// with none prints as itself. |
| +var billingWhyText = map[string]string{ |
| + "facts": cliBillingCopyWhyFacts, |
| + "payments": cliBillingCopyWhyPayments, |
| + "rates": cliBillingCopyWhyRates, |
| + "amounts": cliBillingCopyWhyAmounts, |
| +} |
| + |
| +// printBillingRevenue prints the test mode line when it applies, then one |
| +// line per figure: its label, two spaces and its value, or the reason it is |
| +// not available yet. |
| +func printBillingRevenue(w io.Writer, rev billingRevenueReply) { |
| + if rev.TestMode { |
| + fmt.Fprintln(w, cliBillingCopyTestMode) |
| + } |
| + line := func(label string, f billingFigure, value func() string) { |
| + v := "" |
| + if f.Available { |
| + v = value() |
| + } else { |
| + why, ok := billingWhyText[f.Why] |
| + if !ok { |
| + why = f.Why |
| + } |
| + v = fmt.Sprintf(cliBillingCopyNotAvailable, why) |
| + } |
| + fmt.Fprintln(w, label+" "+v) |
| + } |
| + line(cliBillingCopyLabelARR, rev.ARR, func() string { |
| + var parts []string |
| + for _, c := range slices.Sorted(maps.Keys(rev.ARR.ByCurrency)) { |
| + parts = append(parts, formatMinor(rev.ARR.ByCurrency[c], c)) |
| + } |
| + v := fmt.Sprintf(cliBillingCopyARR, formatMinor(rev.ARR.EUR, "eur"), strings.Join(parts, " + ")) |
| + if rev.ARR.RateDay != "" { |
| + v += fmt.Sprintf(cliBillingCopyRateDay, rev.ARR.RateDay) |
| + } |
| + return v |
| + }) |
| + line(cliBillingCopyLabelMRR, rev.MRR, func() string { return fmt.Sprintf(cliBillingCopyMRR, formatMinor(rev.MRR.EUR, "eur")) }) |
| + line(cliBillingCopyLabelPaying, rev.Paying, func() string { return fmt.Sprintf(cliBillingCopyPaying, rev.Paying.Count, rev.Accounts) }) |
| + line(cliBillingCopyLabelAttention, rev.Attention, func() string { return fmt.Sprintf(cliBillingCopyAttention, rev.Attention.Count) }) |
| + line(cliBillingCopyLabelGroups, rev.Groups, func() string { |
| + c := rev.Groups.Counts |
| + return fmt.Sprintf(cliBillingCopyGroups, c["paying"], c["free"], c["sponsored"], c["house"], c["ours"]) |
| + }) |
| +} |
| + |
| +// billingPaymentReply mirrors the console's payments door. |
| +type billingPaymentReply struct { |
| + Movement string `json:"movement"` |
| + Source string `json:"source"` |
| + At time.Time `json:"at"` |
| + Account string `json:"account"` |
| + Kind string `json:"kind"` |
| + Reason string `json:"reason"` |
| + Detail string `json:"detail"` |
| + Amount int64 `json:"amount"` |
| + Tax int64 `json:"tax"` |
| + Currency string `json:"currency"` |
| + Settled int64 `json:"settled"` |
| + Fee int64 `json:"fee"` |
| + SettledCurrency string `json:"settled_currency"` |
| +} |
| + |
| +// billingPaymentKindFlags maps -kind's words to the door's kinds. |
| +var billingPaymentKindFlags = map[string]string{ |
| + "subscription": "subscription", "once-off": "once_off", "refund": "refund", "fee": "fee", "unmatched": "unmatched", |
| +} |
| + |
| +// billingPaymentKindWords is the kind column's word for each of the door's |
| +// kinds; a kind with none prints as itself. |
| +var billingPaymentKindWords = map[string]string{ |
| + "subscription": cliBillingCopyKindSubscription, "once_off": cliBillingCopyKindOnceOff, |
| + "refund": cliBillingCopyKindRefund, "fee": cliBillingCopyKindFee, |
| +} |
| + |
| +// printBillingPayments prints the header and one line per payment: when |
| +// (UTC), the account (or unmatched), the kind, the reason, what was charged |
| +// and its tax in the charge's currency, what settled and the fee in the |
| +// settlement currency, and the detail. |
| +func printBillingPayments(w io.Writer, list []billingPaymentReply) { |
| + if len(list) == 0 { |
| + fmt.Fprintln(w, cliBillingCopyNoPayments) |
| + return |
| + } |
| + fmt.Fprintln(w, cliBillingCopyPaymentsHeader) |
| + for _, p := range list { |
| + account := p.Account |
| + if account == "" { |
| + account = cliBillingCopyUnmatched |
| + } |
| + kind, ok := billingPaymentKindWords[p.Kind] |
| + if !ok { |
| + kind = p.Kind |
| + } |
| + fields := []string{p.At.UTC().Format("2006-01-02 15:04"), account, kind, p.Reason, |
| + formatMinor(p.Amount, p.Currency), formatMinor(p.Tax, p.Currency), |
| + formatMinor(p.Settled, p.SettledCurrency), formatMinor(p.Fee, p.SettledCurrency)} |
| + if p.Detail != "" { |
| + fields = append(fields, p.Detail) |
| + } |
| + fmt.Fprintln(w, strings.Join(fields, " ")) |
| + } |
| +} |
| + |
| +// currencySymbols is the sign printed before an amount in each selling |
| +// currency; any other prints its code in capitals and a space. |
| +var currencySymbols = map[string]string{"eur": "€", "usd": "$", "gbp": "£"} |
| + |
| +// formatMinor formats minor units of a two-decimal currency, with a comma |
| +// between thousands: €2,400.00, -$12.00. |
| +func formatMinor(minor int64, currency string) string { |
| + sign := "" |
| + u := uint64(minor) |
| + if minor < 0 { |
| + sign, u = "-", uint64(-(minor+1))+1 |
| + } |
| + whole := strconv.FormatUint(u/100, 10) |
| + var b strings.Builder |
| + for i, d := range whole { |
| + if i > 0 && (len(whole)-i)%3 == 0 { |
| + b.WriteByte(',') |
| + } |
| + b.WriteRune(d) |
| + } |
| + symbol, ok := currencySymbols[strings.ToLower(currency)] |
| + if !ok { |
| + symbol = strings.ToUpper(currency) + " " |
| + } |
| + return fmt.Sprintf("%s%s%s.%02d", sign, symbol, b.String(), u%100) |
| +} |
diff --git a/billing_cli_copy.go b/billing_cli_copy.go| index 08a88359b..43df3ec61 100644 |
| --- a/billing_cli_copy.go |
| +++ b/billing_cli_copy.go |
| @@ -4,7 +4,8 @@ package main |
| // 2026-10-25: docs/superpowers/specs/LUNA-COPY-RESULT-PLANS-6A.md. Apply |
| // later edits through a copy pass, not by hand. |
| const ( |
| - cliBillingCopyUsage = "usage: carlos billing problems [-all] | close -id N -note \"...\" | house -account A -on|-off -note \"...\"" |
| + // Billing dashboard plan 1 (BDC-1) replaced the plans 6a usage. |
| + cliBillingCopyUsage = "usage: carlos billing problems [-all] | revenue | payments [-month YYYY-MM] [-kind K] | close -id N -note \"...\" | house -account A -on|-off -note \"...\"" |
| cliBillingCopyFlagAll = "include closed problems" |
| cliBillingCopyFlagID = "problem number from carlos billing problems" |
| cliBillingCopyFlagNote = "what you did in stripe. this note is kept with the problem" |
| @@ -25,3 +26,44 @@ const ( |
| cliBillingCopyFlagHouseNote = "why. this note is kept in the console log" |
| cliBillingCopyNeedsConsole = "billing works through a console, but 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>" |
| ) |
| + |
| +// `carlos billing revenue` and `carlos billing payments` strings. Approved by |
| +// Paul, 2026-11-09: docs/superpowers/plans/2026-11-09-billing-dashboard-1-copy.md |
| +// (BDC-2 to BDC-29). Apply later edits through a copy pass, not by hand. A |
| +// revenue line is its label, two spaces and its value, or the label, two |
| +// spaces and cliBillingCopyNotAvailable with the reason's text. |
| +const ( |
| + cliBillingCopyFlagMonth = "only payments in this month (UTC), as YYYY-MM" |
| + cliBillingCopyFlagKind = "only this kind: subscription, once-off, refund, fee or unmatched" |
| + |
| + cliBillingCopyLabelARR = "arr" |
| + cliBillingCopyARR = "%s a year before tax (%s)" |
| + cliBillingCopyRateDay = ", at ecb rates of %s" |
| + cliBillingCopyLabelMRR = "mrr" |
| + cliBillingCopyMRR = "%s a month before tax" |
| + cliBillingCopyLabelPaying = "paying" |
| + cliBillingCopyPaying = "%d of %d accounts" |
| + cliBillingCopyLabelAttention = "needs attention" |
| + cliBillingCopyAttention = "%d paying accounts with a failing renewal or a cancellation" |
| + cliBillingCopyNotAvailable = "not available yet: %s" |
| + cliBillingCopyLabelGroups = "groups" |
| + cliBillingCopyGroups = "%d paying, %d free, %d sponsored, %d house, %d ours" |
| + cliBillingCopyTestMode = "test mode: these come from stripe test payments, not real money" |
| + |
| + // The reasons, for the door's why codes facts, payments, rates and |
| + // amounts. |
| + cliBillingCopyWhyFacts = "the hourly read of subscriptions from stripe is more than two hours old" |
| + cliBillingCopyWhyPayments = "the payment record has not caught up with stripe in the last two hours" |
| + cliBillingCopyWhyRates = "there is no current ecb rate for one of the currencies" |
| + cliBillingCopyWhyAmounts = "a paying account's yearly amount is not known yet" |
| + |
| + cliBillingCopyPaymentsHeader = "when (utc) account kind reason charged tax settled fee detail" |
| + cliBillingCopyNoPayments = "no payments to show" |
| + cliBillingCopyUnmatched = "unmatched" |
| + cliBillingCopyKindSubscription = "subscription" |
| + cliBillingCopyKindOnceOff = "once-off" |
| + cliBillingCopyKindRefund = "refund" |
| + cliBillingCopyKindFee = "fee" |
| + cliBillingCopyMonthFormat = "give -month as YYYY-MM, for example 2026-11" |
| + cliBillingCopyKindFormat = "give -kind as subscription, once-off, refund, fee or unmatched" |
| +) |
diff --git a/billing_cli_test.go b/billing_cli_test.go| index af37b6be0..3fd3938ba 100644 |
| --- a/billing_cli_test.go |
| +++ b/billing_cli_test.go |
| @@ -131,3 +131,148 @@ func TestBillingCLIHouse(t *testing.T) { |
| t.Fatal("a refused command reached the console") |
| } |
| } |
| + |
| +func TestBillingRevenueCLI(t *testing.T) { |
| + var paths []string |
| + reply := `{"arr":{"available":true,"by_currency":{"eur":240000,"usd":280000},"eur":490000,"rate_day":"2026-11-06"},` + |
| + `"mrr":{"available":true,"eur":40833},"paying":{"available":true,"count":2},"attention":{"available":true,"count":1},` + |
| + `"groups":{"available":true,"counts":{"free":30,"house":2,"ours":1,"paying":2,"sponsored":3}},"accounts":38,"test_mode":false}` |
| + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + paths = append(paths, r.Method+" "+r.URL.RequestURI()) |
| + io.WriteString(w, reply) |
| + })) |
| + defer ts.Close() |
| + s := newTestSession(ts.URL) |
| + |
| + var out bytes.Buffer |
| + if err := runBillingWithSession(context.Background(), s, []string{"revenue"}, &out); err != nil { |
| + t.Fatal(err) |
| + } |
| + want := []string{ |
| + "arr " + fmt.Sprintf(cliBillingCopyARR, "€4,900.00", "€2,400.00 + $2,800.00") + fmt.Sprintf(cliBillingCopyRateDay, "2026-11-06"), |
| + "mrr " + fmt.Sprintf(cliBillingCopyMRR, "€408.33"), |
| + "paying " + fmt.Sprintf(cliBillingCopyPaying, 2, 38), |
| + "needs attention " + fmt.Sprintf(cliBillingCopyAttention, 1), |
| + "groups " + fmt.Sprintf(cliBillingCopyGroups, 2, 30, 3, 2, 1), |
| + } |
| + if got := strings.Split(strings.TrimRight(out.String(), "\n"), "\n"); strings.Join(got, "\n") != strings.Join(want, "\n") { |
| + t.Fatalf("revenue:\n%s\nwant\n%s", out.String(), strings.Join(want, "\n")) |
| + } |
| + if strings.Join(paths, "|") != "GET /api/cli/billing/revenue" { |
| + t.Fatalf("paths %v", paths) |
| + } |
| + |
| + // Every figure refused, one per reason, in test mode. |
| + reply = `{"arr":{"available":false,"why":"facts"},"mrr":{"available":false,"why":"payments"},` + |
| + `"paying":{"available":false,"why":"rates"},"attention":{"available":false,"why":"amounts"},` + |
| + `"groups":{"available":false,"why":"facts"},"accounts":38,"test_mode":true}` |
| + out.Reset() |
| + if err := runBillingWithSession(context.Background(), s, []string{"revenue"}, &out); err != nil { |
| + t.Fatal(err) |
| + } |
| + na := func(why string) string { return fmt.Sprintf(cliBillingCopyNotAvailable, why) } |
| + want = []string{ |
| + cliBillingCopyTestMode, |
| + "arr " + na(cliBillingCopyWhyFacts), |
| + "mrr " + na(cliBillingCopyWhyPayments), |
| + "paying " + na(cliBillingCopyWhyRates), |
| + "needs attention " + na(cliBillingCopyWhyAmounts), |
| + "groups " + na(cliBillingCopyWhyFacts), |
| + } |
| + if got := strings.TrimRight(out.String(), "\n"); got != strings.Join(want, "\n") { |
| + t.Fatalf("refused:\n%s\nwant\n%s", got, strings.Join(want, "\n")) |
| + } |
| + if err := runBillingWithSession(context.Background(), s, []string{"revenue", "extra"}, io.Discard); err == nil { |
| + t.Fatal("an extra argument was accepted") |
| + } |
| +} |
| + |
| +func TestBillingPaymentsCLI(t *testing.T) { |
| + var paths []string |
| + reply := `[{"movement":"mv_2","source":"re_1","at":"2026-11-06T09:30:00Z","account":"bab","kind":"refund","reason":"renewal","detail":"","amount":-1200,"tax":-200,"currency":"usd","settled":-1071,"fee":0,"settled_currency":"eur"},` + |
| + `{"movement":"mv_1","source":"ch_1","at":"2026-11-02T08:00:00Z","account":"","kind":"once_off","reason":"domain","detail":"shop.example.com","amount":240000,"tax":0,"currency":"eur","settled":240000,"fee":3500,"settled_currency":"eur"},` + |
| + `{"movement":"mv_0","source":"","at":"2026-11-01T00:00:00Z","account":"","kind":"fee","reason":"other","detail":"","amount":-500,"tax":0,"currency":"eur","settled":-500,"fee":0,"settled_currency":"eur"},` + |
| + `{"movement":"mv_s","source":"ch_s","at":"2026-11-01T00:00:00Z","account":"shop","kind":"subscription","reason":"first","detail":"","amount":1200,"tax":200,"currency":"gbp","settled":1150,"fee":40,"settled_currency":"eur"}]` |
| + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + paths = append(paths, r.Method+" "+r.URL.RequestURI()) |
| + io.WriteString(w, reply) |
| + })) |
| + defer ts.Close() |
| + s := newTestSession(ts.URL) |
| + |
| + var out bytes.Buffer |
| + if err := runBillingWithSession(context.Background(), s, []string{"payments"}, &out); err != nil { |
| + t.Fatal(err) |
| + } |
| + want := []string{ |
| + cliBillingCopyPaymentsHeader, |
| + "2026-11-06 09:30 bab " + cliBillingCopyKindRefund + " renewal -$12.00 -$2.00 -€10.71 €0.00", |
| + "2026-11-02 08:00 " + cliBillingCopyUnmatched + " " + cliBillingCopyKindOnceOff + " domain €2,400.00 €0.00 €2,400.00 €35.00 shop.example.com", |
| + "2026-11-01 00:00 " + cliBillingCopyUnmatched + " " + cliBillingCopyKindFee + " other -€5.00 €0.00 -€5.00 €0.00", |
| + "2026-11-01 00:00 shop " + cliBillingCopyKindSubscription + " first £12.00 £2.00 €11.50 €0.40", |
| + } |
| + if got := strings.TrimRight(out.String(), "\n"); got != strings.Join(want, "\n") { |
| + t.Fatalf("payments:\n%s\nwant\n%s", got, strings.Join(want, "\n")) |
| + } |
| + |
| + if err := runBillingWithSession(context.Background(), s, []string{"payments", "-month", "2026-11", "-kind", "once-off"}, io.Discard); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := runBillingWithSession(context.Background(), s, []string{"payments", "-kind", "unmatched"}, io.Discard); err != nil { |
| + t.Fatal(err) |
| + } |
| + wantPaths := []string{"GET /api/cli/billing/payments", "GET /api/cli/billing/payments?kind=once_off&month=2026-11", |
| + "GET /api/cli/billing/payments?kind=unmatched"} |
| + if strings.Join(paths, "|") != strings.Join(wantPaths, "|") { |
| + t.Fatalf("paths %v, want %v", paths, wantPaths) |
| + } |
| + |
| + reply = `[]` |
| + out.Reset() |
| + if err := runBillingWithSession(context.Background(), s, []string{"payments"}, &out); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := strings.TrimRight(out.String(), "\n"); got != cliBillingCopyNoPayments { |
| + t.Fatalf("empty: %q, want %q", got, cliBillingCopyNoPayments) |
| + } |
| + |
| + // A bad -month or -kind never reaches the console. |
| + hits := len(paths) |
| + for _, c := range []struct { |
| + args []string |
| + want string |
| + }{ |
| + {[]string{"payments", "-month", "2026-13"}, cliBillingCopyMonthFormat}, |
| + {[]string{"payments", "-month", "2026-1"}, cliBillingCopyMonthFormat}, |
| + {[]string{"payments", "-kind", "once_off"}, cliBillingCopyKindFormat}, |
| + {[]string{"payments", "-kind", "all"}, cliBillingCopyKindFormat}, |
| + } { |
| + err := runBillingWithSession(context.Background(), s, c.args, io.Discard) |
| + if err == nil || err.Error() != c.want { |
| + t.Errorf("%v: %v, want %q", c.args, err, c.want) |
| + } |
| + } |
| + if len(paths) != hits { |
| + t.Fatal("a refused command reached the console") |
| + } |
| +} |
| + |
| +func TestFormatMinor(t *testing.T) { |
| + for _, c := range []struct { |
| + minor int64 |
| + currency string |
| + want string |
| + }{ |
| + {0, "eur", "€0.00"}, |
| + {5, "eur", "€0.05"}, |
| + {240000, "eur", "€2,400.00"}, |
| + {123456789, "usd", "$1,234,567.89"}, |
| + {-1071, "eur", "-€10.71"}, |
| + {1200, "gbp", "£12.00"}, |
| + {1200, "chf", "CHF 12.00"}, |
| + } { |
| + if got := formatMinor(c.minor, c.currency); got != c.want { |
| + t.Errorf("formatMinor(%d, %s) = %q, want %q", c.minor, c.currency, got, c.want) |
| + } |
| + } |
| +} |
diff --git a/docs/site/cli.md b/docs/site/cli.md| index 47bb82809..57fb71ad0 100644 |
| --- a/docs/site/cli.md |
| +++ b/docs/site/cli.md |
| @@ -2309,6 +2309,9 @@ Lists the billing problems the console could not settle on its own, and closes o |
| ```sh |
| carlos billing problems |
| carlos billing problems -all |
| +carlos billing revenue |
| +carlos billing payments -month 2026-11 |
| +carlos billing payments -kind unmatched |
| carlos billing close -id 12 -note "refunded and cancelled in the dashboard" |
| carlos billing house -account bac -on -note "our own shop" |
| carlos billing house -account bac -off -note "now a customer" |
| @@ -2316,6 +2319,10 @@ carlos billing house -account bac -off -note "now a customer" |
| `problems` prints one line per open problem: its number, the account, the reason, the subscription, when it opened (UTC) and what the console saw. `-all` adds closed problems. `close` needs `-note`. The console refuses to close most problems while Stripe still shows the subscription as live. |
| +`revenue` prints what the paying accounts bring in, before tax: ARR and MRR in euros at the ECB rates of the day it names, with each currency's own total beside ARR, for example `arr €2,400.00 a year before tax (€2,400.00), at ecb rates of 2026-11-06`. Then it prints how many accounts pay, how many of those have a failing renewal or are cancelling, and how many accounts are paying, free, sponsored, house and ours. A figure the console can't stand behind yet, because a read from Stripe is behind or a rate is missing, says `not available yet` and why, instead of a wrong number. In test mode it says so. |
| + |
| +`payments` lists the money Stripe has taken and paid back, newest first, up to 500 lines: when it happened (UTC), the account, the kind, the amount charged, the tax, what settled in euros and Stripe's fee. `-month 2026-11` keeps one month. `-kind` keeps one of `subscription`, `once-off`, `refund`, `fee` or `unmatched`, a payment from a Stripe customer the console can't match to an account. |
| + |
| `house` marks an account as a house account, whose checkout carries the house coupon and so pays nothing, or clears the mark. It needs `-account` (the account's sqid), exactly one of `-on` and `-off`, and `-note` saying why. The mark applies when the account starts a checkout, and does not change a subscription it already has. It works only against a console. See [Plans](plans#house-accounts). |
| ### carlos fleets |
diff --git a/docs/site/plans.md b/docs/site/plans.md| index c2c0a3ae5..60a1d4cc2 100644 |
| --- a/docs/site/plans.md |
| +++ b/docs/site/plans.md |
| @@ -155,6 +155,8 @@ Every billing setting lives in the console's EnvironmentFile. None of them is a |
| | `CARLOS_STRIPE_PORTAL_CONFIGURATION` | Required with billing on. The id (`bpc_`) of a Stripe customer portal configuration that allows cards and invoice history and nothing else. | |
| | `CARLOS_STRIPE_HOUSE_COUPON` | Optional. The id of the coupon that makes a house account's checkout free. | |
| +The restricted key also needs read access to Balance, Charges and Refunds, and the webhook also needs `charge.succeeded`, `charge.captured` and `charge.refunded`, so the console can record the money it receives. |
| + |
| If any of them is wrong, the console refuses to start and names the variable, never its value. |
| Point Stripe's webhook at `https://<console>/billing/webhook`. When the console starts, it checks the account, every price in the book, the portal configuration and the house coupon (if you set one) against Stripe before it accepts a webhook. Until that check passes, the webhook answers 503 and Stripe tries again later, so a console that starts while Stripe is unreachable catches up by itself. |
diff --git a/internal/console/apibilling.go b/internal/console/apibilling.go| index 532a24246..45a7c8114 100644 |
| --- a/internal/console/apibilling.go |
| +++ b/internal/console/apibilling.go |
| @@ -4,7 +4,9 @@ import ( |
| "context" |
| "errors" |
| "log" |
| + "maps" |
| "net/http" |
| + "slices" |
| "strconv" |
| "strings" |
| "time" |
| @@ -355,3 +357,194 @@ func (s *Server) closeUnresolvedOpLocked(h billingHold, acct *Account, subscript |
| } |
| return http.StatusConflict, billingCopyOpEvidence |
| } |
| + |
| +// The operator's money doors (billing dashboard plan 1): the revenue as of |
| +// now, every figure through the money gate, and the recorded payments. |
| +// Both read the console DB only. |
| + |
| +// revenueARR is ARR on the wire: by currency and in euros at RateDay's |
| +// rates, minor units. A refused figure carries no number, only Why. |
| +type revenueARR struct { |
| + Available bool `json:"available"` |
| + Why string `json:"why,omitempty"` |
| + ByCurrency map[string]int64 `json:"by_currency,omitzero"` |
| + EUR *int64 `json:"eur,omitempty"` |
| + RateDay *string `json:"rate_day,omitempty"` |
| +} |
| + |
| +// revenueMRR is MRR on the wire: ARR in euros over twelve, rounded. |
| +type revenueMRR struct { |
| + Available bool `json:"available"` |
| + Why string `json:"why,omitempty"` |
| + EUR *int64 `json:"eur,omitempty"` |
| +} |
| + |
| +// revenueCount is a count figure on the wire. |
| +type revenueCount struct { |
| + Available bool `json:"available"` |
| + Why string `json:"why,omitempty"` |
| + Count *int `json:"count,omitempty"` |
| +} |
| + |
| +// revenueGroups is the group counts on the wire, every group named. |
| +type revenueGroups struct { |
| + Available bool `json:"available"` |
| + Why string `json:"why,omitempty"` |
| + Counts map[string]int `json:"counts,omitzero"` |
| +} |
| + |
| +// revenueReply is GET /api/cli/billing/revenue's answer. |
| +type revenueReply struct { |
| + ARR revenueARR `json:"arr"` |
| + MRR revenueMRR `json:"mrr"` |
| + Paying revenueCount `json:"paying"` |
| + Attention revenueCount `json:"attention"` |
| + Groups revenueGroups `json:"groups"` |
| + Accounts int `json:"accounts"` |
| + TestMode bool `json:"test_mode"` |
| +} |
| + |
| +// revenueFigures puts each figure of rev through the money gate with the |
| +// inputs it declares and builds the reply from the ones shown: ARR and MRR |
| +// use the facts, the payments, the amounts and the rates of ARR's |
| +// currencies; the paying, attention and group counts the facts and the |
| +// payments; the account count nothing. Pure. |
| +func revenueFigures(rev billingRevenue, in moneyInputs) ([]moneyFigure, revenueReply) { |
| + currencies := slices.Sorted(maps.Keys(rev.ByCurrency)) |
| + money := moneyUse{Inputs: inFacts | inPayments | inAmounts | ratesUse(currencies...), Currencies: currencies} |
| + counts := moneyUse{Inputs: inFacts | inPayments} |
| + var figs []moneyFigure |
| + gate := func(name string, u moneyUse) (bool, string) { |
| + ok, why := moneyReady(in, u) |
| + figs = append(figs, moneyFigure{Name: name, Use: u, Shown: ok, Why: why}) |
| + return ok, why |
| + } |
| + reply := revenueReply{Accounts: rev.Accounts, TestMode: rev.TestMode} |
| + if ok, why := gate("arr", money); ok { |
| + eur, day := rev.EUR, rev.RateDay |
| + by := maps.Clone(rev.ByCurrency) |
| + if by == nil { |
| + by = map[string]int64{} |
| + } |
| + reply.ARR = revenueARR{Available: true, ByCurrency: by, EUR: &eur, RateDay: &day} |
| + } else { |
| + reply.ARR = revenueARR{Why: why} |
| + } |
| + if ok, why := gate("mrr", money); ok { |
| + mrr := (rev.EUR + 6) / 12 |
| + reply.MRR = revenueMRR{Available: true, EUR: &mrr} |
| + } else { |
| + reply.MRR = revenueMRR{Why: why} |
| + } |
| + count := func(name string, n int) revenueCount { |
| + if ok, why := gate(name, counts); !ok { |
| + return revenueCount{Why: why} |
| + } |
| + return revenueCount{Available: true, Count: &n} |
| + } |
| + reply.Paying = count("paying", rev.Paying) |
| + reply.Attention = count("attention", rev.Attention) |
| + if ok, why := gate("groups", counts); ok { |
| + c := map[string]int{} |
| + for _, g := range billingGroupOrder { |
| + c[string(g)] = rev.Groups[g] |
| + } |
| + reply.Groups = revenueGroups{Available: true, Counts: c} |
| + } else { |
| + reply.Groups = revenueGroups{Why: why} |
| + } |
| + gate("accounts", moneyUse{}) |
| + return figs, reply |
| +} |
| + |
| +// handleAPIBillingRevenue is GET /api/cli/billing/revenue: the revenue as |
| +// of now, a figure whose inputs are not complete refused with the reason. |
| +func (s *Server) handleAPIBillingRevenue(w http.ResponseWriter, r *http.Request) { |
| + if _, ok := s.billingDoor(w, r); !ok { |
| + return |
| + } |
| + rev, _, err := s.billingRevenueNow(time.Now()) |
| + if err != nil { |
| + log.Printf("console: api billing revenue: %v", err) |
| + jsonError(w, http.StatusInternalServerError, "internal error") |
| + return |
| + } |
| + _, reply := revenueFigures(rev, rev.Inputs) |
| + writeJSON(w, http.StatusOK, reply) |
| +} |
| + |
| +// billingPaymentReply is one recorded payment on the wire: Account is the |
| +// account's sqid, "" when unmatched or deleted. |
| +type billingPaymentReply struct { |
| + Movement string `json:"movement"` |
| + Source string `json:"source"` |
| + At time.Time `json:"at"` |
| + Account string `json:"account"` |
| + Kind string `json:"kind"` |
| + Reason string `json:"reason"` |
| + Detail string `json:"detail"` |
| + Amount int64 `json:"amount"` |
| + Tax int64 `json:"tax"` |
| + Currency string `json:"currency"` |
| + Settled int64 `json:"settled"` |
| + Fee int64 `json:"fee"` |
| + SettledCurrency string `json:"settled_currency"` |
| +} |
| + |
| +// billingPaymentsLimit is how many payments the door lists. |
| +const billingPaymentsLimit = 500 |
| + |
| +// billingPaymentKinds is what the door's kind may be: "" (every kind but |
| +// fees) or one kind of paymentFilter. |
| +var billingPaymentKinds = map[string]bool{"": true, string(billing.PaymentSubscription): true, |
| + string(billing.PaymentOnceOff): true, string(billing.PaymentRefund): true, string(billing.PaymentFee): true, "unmatched": true} |
| + |
| +// handleAPIBillingPayments is GET /api/cli/billing/payments?month=YYYY-MM&kind=K: |
| +// the recorded payments, newest first, up to billingPaymentsLimit; month |
| +// (UTC) and kind narrow them. |
| +func (s *Server) handleAPIBillingPayments(w http.ResponseWriter, r *http.Request) { |
| + if _, ok := s.billingDoor(w, r); !ok { |
| + return |
| + } |
| + q := r.URL.Query() |
| + f := paymentFilter{Kind: q.Get("kind"), Limit: billingPaymentsLimit} |
| + if !billingPaymentKinds[f.Kind] { |
| + jsonError(w, http.StatusBadRequest, billingCopyKind) |
| + return |
| + } |
| + if m := q.Get("month"); m != "" { |
| + start, err := time.Parse("2006-01", m) |
| + if err != nil || len(m) != len("2006-01") { |
| + jsonError(w, http.StatusBadRequest, billingCopyMonth) |
| + return |
| + } |
| + f.From, f.To = start, start.AddDate(0, 1, 0) |
| + } |
| + rows, _, err := s.store.Payments(f) |
| + if err != nil { |
| + log.Printf("console: api billing payments: %v", err) |
| + jsonError(w, http.StatusInternalServerError, "internal error") |
| + return |
| + } |
| + sqids := map[int64]string{} |
| + out := make([]billingPaymentReply, 0, len(rows)) |
| + for _, p := range rows { |
| + sqid, seen := sqids[p.AccountID] |
| + if !seen && p.AccountID != 0 { |
| + a, err := s.store.AccountByID(p.AccountID) |
| + if err != nil { |
| + log.Printf("console: api billing payments: account %d: %v", p.AccountID, err) |
| + jsonError(w, http.StatusInternalServerError, "internal error") |
| + return |
| + } |
| + if a != nil { |
| + sqid = a.Sqid |
| + } |
| + sqids[p.AccountID] = sqid |
| + } |
| + out = append(out, billingPaymentReply{Movement: p.Movement, Source: p.Source, At: p.At.UTC(), Account: sqid, |
| + Kind: string(p.Kind), Reason: p.Reason, Detail: p.Detail, Amount: p.Amount, Tax: p.Tax, Currency: p.Currency, |
| + Settled: p.Settled, Fee: p.Fee, SettledCurrency: p.SettledCurrency}) |
| + } |
| + writeJSON(w, http.StatusOK, out) |
| +} |
diff --git a/internal/console/apibilling_copy.go b/internal/console/apibilling_copy.go| index 5df01d639..2635e3a5f 100644 |
| --- a/internal/console/apibilling_copy.go |
| +++ b/internal/console/apibilling_copy.go |
| @@ -19,3 +19,11 @@ const ( |
| // Plans 6b draft (Task 14), for the house door. |
| billingCopyHouseNote = "say why with -note" |
| ) |
| + |
| +// Door errors for the payments door (apibilling.go). Approved by Paul, |
| +// 2026-11-09: docs/superpowers/plans/2026-11-09-billing-dashboard-1-copy.md |
| +// (BDC-30, BDC-31). Apply later edits through a copy pass, not by hand. |
| +const ( |
| + billingCopyMonth = "month must be YYYY-MM, for example 2026-11" |
| + billingCopyKind = "kind must be subscription, once_off, refund, fee or unmatched" |
| +) |
diff --git a/internal/console/apibilling_test.go b/internal/console/apibilling_test.go| index 94d1487aa..fbe00617e 100644 |
| --- a/internal/console/apibilling_test.go |
| +++ b/internal/console/apibilling_test.go |
| @@ -3,9 +3,16 @@ package console |
| import ( |
| "context" |
| "encoding/json" |
| + "fmt" |
| "net/http" |
| + "slices" |
| "strconv" |
| + "strings" |
| "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/billing" |
| + "github.com/carlosframework/platform/internal/fxrate" |
| ) |
| func billingProblemsURL(fx *consoleFixture) string { return fx.ts.URL + "/api/cli/billing/problems" } |
| @@ -124,3 +131,210 @@ func TestCloseRefusedWhileUnpaid(t *testing.T) { |
| t.Fatalf("unpaid: %d %v, want 409", status, out) |
| } |
| } |
| + |
| +// TestRevenueFiguresGateInvariant: every figure of the revenue door goes |
| +// through the money gate with the inputs it declares, over a usd and an |
| +// eur paying account. |
| +func TestRevenueFiguresGateInvariant(t *testing.T) { |
| + now := time.Date(2026, 11, 9, 12, 0, 0, 0, time.UTC) |
| + good := goodMoneyInputs(now) |
| + facts := []billingFact{payingFact(2, "eur", 2400), payingFact(3, "usd", 2800)} |
| + checkGateInvariant(t, good, func(in moneyInputs) []moneyFigure { |
| + rev := billingRevenue{arrTotals: arrOf(facts, OpsAccountID, in.Rates), Groups: map[billingGroup]int{groupPaying: 2}, |
| + Accounts: 2, Inputs: in} |
| + figs, _ := revenueFigures(rev, in) |
| + return figs |
| + }) |
| + figs, reply := revenueFigures(billingRevenue{arrTotals: arrOf(facts, OpsAccountID, good.Rates), |
| + Groups: map[billingGroup]int{groupPaying: 2}, Accounts: 2, Inputs: good}, good) |
| + var names []string |
| + for _, f := range figs { |
| + names = append(names, f.Name) |
| + } |
| + if want := []string{"arr", "mrr", "paying", "attention", "groups", "accounts"}; !slices.Equal(names, want) { |
| + t.Fatalf("figures %v, want %v", names, want) |
| + } |
| + if !slices.Equal(figs[0].Use.Currencies, []string{"eur", "usd"}) { |
| + t.Fatalf("arr converts %v, want eur and usd", figs[0].Use.Currencies) |
| + } |
| + if reply.ARR.EUR == nil || *reply.ARR.EUR != 4900 || reply.MRR.EUR == nil || *reply.MRR.EUR != 408 { |
| + t.Fatalf("reply = %+v; want arr 4900 and mrr 408 (4900 / 12, rounded)", reply) |
| + } |
| +} |
| + |
| +// revenueWorld puts acct on a paying eur subscription read at now, its |
| +// first payment recorded, the payments reconciled at now and a rate day |
| +// stored at now. |
| +func revenueWorld(t *testing.T, st *Store, acct *Account, customer, sub string, annual int64, now time.Time) { |
| + t.Helper() |
| + if err := st.SetBillingCustomer(acct.ID, customer, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + b, err := st.BillingAccount(acct.ID) |
| + if err != nil || b == nil { |
| + t.Fatalf("billing row %d: %+v, %v", acct.ID, b, err) |
| + } |
| + b.Subscription, b.ProviderStatus, b.State, b.Currency = sub, "active", billing.StatePaid, "eur" |
| + b.Billable, b.Live, b.Annual, b.FactsReadAt = true, true, annual, now |
| + if err := st.PutBillingState(*b); err != nil { |
| + t.Fatal(err) |
| + } |
| + p := testCharge("mv_"+sub, "ch_"+sub) |
| + p.Customer, p.Subscription, p.At = customer, sub, now.Add(-time.Hour) |
| + recordPayment(t, st, p) |
| + if err := st.SetPaymentsReconciled(now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := st.PutEURRates(fxrate.Rates{Day: "2026-11-06", PerEUR: map[string]float64{"usd": 1.12}}, now); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func billingRevenueURL(fx *consoleFixture) string { return fx.ts.URL + "/api/cli/billing/revenue" } |
| + |
| +func TestAPIBillingRevenue(t *testing.T) { |
| + bf := newBillingFixture(t) |
| + now := time.Now() |
| + revenueWorld(t, bf.st, bf.acct, "cus_1", "sub_1", 2400, now) |
| + op := planOperatorToken(t, bf.consoleFixture, "ops@keymail.dev", "code-billing-revenue") |
| + status, body := getRaw(t, billingRevenueURL(bf.consoleFixture), op) |
| + if status != http.StatusOK { |
| + t.Fatalf("operator: %d %s", status, body) |
| + } |
| + facts, err := bf.st.BillingFacts() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + free := 0 |
| + for _, f := range facts { |
| + if billingGroupOf(f, bf.st.planExemptID) == groupFree { |
| + free++ |
| + } |
| + } |
| + ours := len(facts) - 1 - free |
| + want := fmt.Sprintf(`{"arr":{"available":true,"by_currency":{"eur":2400},"eur":2400,"rate_day":"2026-11-06"},`+ |
| + `"mrr":{"available":true,"eur":200},"paying":{"available":true,"count":1},"attention":{"available":true,"count":0},`+ |
| + `"groups":{"available":true,"counts":{"free":%d,"house":0,"ours":%d,"paying":1,"sponsored":0}},"accounts":%d,"test_mode":%t}`, |
| + free, ours, len(facts), !bf.srv.billing.cfg.LiveMode) |
| + if strings.TrimSpace(body) != want { |
| + t.Fatalf("revenue:\n%s\nwant\n%s", strings.TrimSpace(body), want) |
| + } |
| + |
| + // A second paying account whose yearly amount is unknown: ARR and MRR |
| + // are refused, the counts still shown. |
| + second := planAccount(t, bf.consoleFixture, 502) |
| + revenueWorld(t, bf.st, second, "cus_2", "sub_2", -1, now) |
| + status, body = getRaw(t, billingRevenueURL(bf.consoleFixture), op) |
| + if status != http.StatusOK { |
| + t.Fatalf("unknown amount: %d %s", status, body) |
| + } |
| + var got map[string]json.RawMessage |
| + if err := json.Unmarshal([]byte(body), &got); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, k := range []string{"arr", "mrr"} { |
| + if string(got[k]) != `{"available":false,"why":"amounts"}` { |
| + t.Errorf("%s = %s, want refused for amounts with no number", k, got[k]) |
| + } |
| + } |
| + if string(got["paying"]) != `{"available":true,"count":2}` { |
| + t.Errorf("paying = %s, want shown", got["paying"]) |
| + } |
| + |
| + member := cliToken(t, bf.consoleFixture, "owner"+bf.acct.Sqid+"@example.com", "code-billing-revenue-owner") |
| + if status, body := getRaw(t, billingRevenueURL(bf.consoleFixture), member); status != http.StatusNotFound || body != "404 page not found\n" { |
| + t.Fatalf("member: %d %q, want the stdlib 404", status, body) |
| + } |
| + off := newConsoleFixture(t) |
| + opOff := planOperatorToken(t, off, "ops@keymail.dev", "code-billing-revenue-off") |
| + if status, out := getJSON(t, billingRevenueURL(off), opOff); status != http.StatusConflict || out["error"] != billingCopyOff { |
| + t.Fatalf("billing off: %d %v, want 409 %q", status, out, billingCopyOff) |
| + } |
| +} |
| + |
| +func TestAPIBillingPayments(t *testing.T) { |
| + bf := newBillingFixture(t) |
| + oct := time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC) |
| + nov := time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC) |
| + mk := func(mv string, kind billing.PaymentKind, customer string, at time.Time) billing.Payment { |
| + return billing.Payment{Movement: mv, Source: "src_" + mv, Kind: kind, Reason: billing.ReasonOther, Customer: customer, |
| + Amount: 1200, Tax: 200, Currency: "eur", Settled: 1200, Fee: 40, SettledCurrency: "eur", At: at} |
| + } |
| + for _, p := range []billing.Payment{ |
| + mk("mv_sep", billing.PaymentSubscription, "cus_1", oct.Add(-time.Hour)), |
| + mk("mv_a", billing.PaymentSubscription, "cus_1", oct.Add(time.Hour)), |
| + mk("mv_b", billing.PaymentOnceOff, "cus_nobody", oct.Add(48*time.Hour)), |
| + mk("mv_c", billing.PaymentFee, "", oct.Add(72*time.Hour)), |
| + mk("mv_nov", billing.PaymentRefund, "cus_1", nov), |
| + } { |
| + recordPayment(t, bf.st, p) |
| + } |
| + op := planOperatorToken(t, bf.consoleFixture, "ops@keymail.dev", "code-billing-payments") |
| + list := func(query string) []billingPaymentReply { |
| + t.Helper() |
| + status, body := getRaw(t, bf.ts.URL+"/api/cli/billing/payments"+query, op) |
| + if status != http.StatusOK { |
| + t.Fatalf("%s: %d %s", query, status, body) |
| + } |
| + var out []billingPaymentReply |
| + if err := json.Unmarshal([]byte(body), &out); err != nil { |
| + t.Fatalf("%s: decode %q: %v", query, body, err) |
| + } |
| + return out |
| + } |
| + movements := func(rows []billingPaymentReply) []string { |
| + var out []string |
| + for _, r := range rows { |
| + out = append(out, r.Movement) |
| + } |
| + return out |
| + } |
| + for _, c := range []struct { |
| + query string |
| + want []string |
| + }{ |
| + {"", []string{"mv_nov", "mv_b", "mv_a", "mv_sep"}}, |
| + {"?month=2026-10", []string{"mv_b", "mv_a"}}, |
| + {"?month=2026-10&kind=fee", []string{"mv_c"}}, |
| + {"?kind=once_off", []string{"mv_b"}}, |
| + {"?kind=refund", []string{"mv_nov"}}, |
| + {"?kind=subscription&month=2026-09", []string{"mv_sep"}}, |
| + {"?kind=unmatched", []string{"mv_b"}}, |
| + } { |
| + if got := movements(list(c.query)); !slices.Equal(got, c.want) { |
| + t.Errorf("%q: %v, want %v", c.query, got, c.want) |
| + } |
| + } |
| + rows := list("?month=2026-10") |
| + wantA := billingPaymentReply{Movement: "mv_a", Source: "src_mv_a", At: oct.Add(time.Hour), Account: bf.acct.Sqid, |
| + Kind: "subscription", Reason: billing.ReasonOther, Amount: 1200, Tax: 200, Currency: "eur", Settled: 1200, |
| + Fee: 40, SettledCurrency: "eur"} |
| + if rows[1] != wantA { |
| + t.Errorf("mv_a = %+v\nwant %+v", rows[1], wantA) |
| + } |
| + if rows[0].Account != "" { |
| + t.Errorf("unmatched account = %q, want empty", rows[0].Account) |
| + } |
| + for _, c := range []struct{ query, want string }{ |
| + {"?month=2026-13", billingCopyMonth}, |
| + {"?month=2026-1", billingCopyMonth}, |
| + {"?month=october", billingCopyMonth}, |
| + {"?kind=x", billingCopyKind}, |
| + {"?kind=all", billingCopyKind}, |
| + {"?kind=once-off", billingCopyKind}, |
| + } { |
| + if status, out := getJSON(t, bf.ts.URL+"/api/cli/billing/payments"+c.query, op); status != http.StatusBadRequest || out["error"] != c.want { |
| + t.Errorf("%q: %d %v, want 400 %q", c.query, status, out, c.want) |
| + } |
| + } |
| + |
| + member := cliToken(t, bf.consoleFixture, "owner"+bf.acct.Sqid+"@example.com", "code-billing-payments-owner") |
| + if status, body := getRaw(t, bf.ts.URL+"/api/cli/billing/payments", member); status != http.StatusNotFound || body != "404 page not found\n" { |
| + t.Fatalf("member: %d %q, want the stdlib 404", status, body) |
| + } |
| + off := newConsoleFixture(t) |
| + opOff := planOperatorToken(t, off, "ops@keymail.dev", "code-billing-payments-off") |
| + if status, out := getJSON(t, off.ts.URL+"/api/cli/billing/payments", opOff); status != http.StatusConflict || out["error"] != billingCopyOff { |
| + t.Fatalf("billing off: %d %v, want 409 %q", status, out, billingCopyOff) |
| + } |
| +} |
diff --git a/internal/console/authcli.go b/internal/console/authcli.go| index 6de2f2688..966e91e56 100644 |
| --- a/internal/console/authcli.go |
| +++ b/internal/console/authcli.go |
| @@ -1083,6 +1083,8 @@ func (s *Server) registerCLIRoutes() { |
| 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("GET /api/cli/billing/revenue", svcrole.Set{}, s.handleAPIBillingRevenue) |
| + s.cliRoute("GET /api/cli/billing/payments", svcrole.Set{}, s.handleAPIBillingPayments) |
| s.cliRoute("POST /api/cli/billing/problems/{id}/close", svcrole.Set{}, s.handleAPIBillingProblemClose) |
| // Plans 6b (Task 14): an operator marks an account as a house account. |
| s.cliRoute("POST /api/cli/billing/house", svcrole.Set{}, s.handleAPIBillingHouse) |
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go| index 3ab1594ff..85a21f5bb 100644 |
| --- a/internal/console/claim_invariant_fixtures_test.go |
| +++ b/internal/console/claim_invariant_fixtures_test.go |
| @@ -898,6 +898,8 @@ var claimFixtures = map[string]claimFixture{ |
| "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/billing/revenue": claimRead("operator view of billing revenue; names no app"), |
| + "route GET /api/cli/billing/payments": claimRead("operator view of billing payments; names no app"), |
| "route GET /api/cli/fleets/{account}/{fleet}": claimRead("reads the owned fleet and its boxes; writes nothing"), |
| "route GET /api/cli/system/managed-fleets": claimRead("reads operator managed fleet configuration; writes nothing"), |
| "route PUT /api/cli/system/managed-fleets": claimNonApp("operator configuration at system/managed-fleets.json; no app record write"), |
diff --git a/internal/console/claim_invariant_probes_read_test.go b/internal/console/claim_invariant_probes_read_test.go| index c0ffa21ab..0755683c1 100644 |
| --- a/internal/console/claim_invariant_probes_read_test.go |
| +++ b/internal/console/claim_invariant_probes_read_test.go |
| @@ -357,6 +357,8 @@ var claimReadProbes = map[string]claimProbe{ |
| "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/billing/revenue": claimAPIRead(claimBillingWorld, "/api/cli/billing/revenue", `"accounts":`, `"arr":`), |
| + "route GET /api/cli/billing/payments": claimAPIRead(claimBillingWorld, "/api/cli/billing/payments", `[]`), |
| "route GET /api/cli/fleets/{account}/{fleet}": claimAPIRead(claimWorldFleet, "/api/cli/fleets/bab/pi", `"name":"pi"`), |
| "route GET /api/cli/system/managed-fleets": claimAPIRead(nil, "/api/cli/system/managed-fleets", `"enabled":false`), |
| "route GET /api/cli/system/antivirus": claimAPIRead(nil, "/api/cli/system/antivirus", `"wired":true`), |
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt| index 7f884a328..810a77601 100644 |
| --- a/internal/console/testdata/claim-routes.txt |
| +++ b/internal/console/testdata/claim-routes.txt |
| @@ -118,7 +118,9 @@ route GET /api/cli/apps/{account}/{app}/tags |
| route GET /api/cli/apps/{account}/{app}/tags/{version} |
| route GET /api/cli/apps/{account}/{app}/telemetry |
| route GET /api/cli/apps/{account}/{app}/version-target |
| +route GET /api/cli/billing/payments |
| route GET /api/cli/billing/problems |
| +route GET /api/cli/billing/revenue |
| route GET /api/cli/fleets/{account} |
| route GET /api/cli/fleets/{account}/{fleet} |
| route GET /api/cli/services/{account} |
diff --git a/scripts/stripe-setup.sh b/scripts/stripe-setup.sh| index 09cf2ab41..5d7dbe4f9 100755 |
| --- a/scripts/stripe-setup.sh |
| +++ b/scripts/stripe-setup.sh |
| @@ -411,7 +411,7 @@ readonly WEBHOOK_PROBLEM=' |
| elif .livemode != '"$live"' then "not in '"$mode_word"' mode" |
| elif .status != "enabled" then "not enabled" |
| elif .api_version != $version then "its API version is not \($version)" |
| - elif (.enabled_events | sort) != ($events | sort) then "its events are not the six the console reads" |
| + elif (.enabled_events | sort) != ($events | sort) then "its events are not the nine the console reads" |
| else "" end' |
| # --------------------------------------------------------------------------- |