From cdca3921eac756e6ad9bcf18997afed980b31114 Mon Sep 17 00:00:00 2001 From: ejanusevicius Date: Fri, 20 Nov 2026 13:18:00 +0000 Subject: [PATCH 1/2] feat(cli): add account spending-limit commands Show, set and remove the overage spending limit from the CLI (`checkly account spending-limit [set | remove]`). Co-Authored-By: Claude Opus 5.5 --- packages/cli/package.json | 3 + packages/cli/src/ai-context/context.ts | 6 +- .../references/manage-spending-limit.md | 38 ++++++ .../cli/src/ai-context/references/manage.md | 2 +- .../__tests__/account-spending-limit.spec.ts | 119 ++++++++++++++++++ .../__tests__/command-metadata.spec.ts | 6 + .../src/commands/account/spending-limit.ts | 36 ++++++ .../commands/account/spending-limit/remove.ts | 57 +++++++++ .../commands/account/spending-limit/set.ts | 73 +++++++++++ .../__tests__/spending-limit.spec.ts | 62 +++++++++ packages/cli/src/formatters/spending-limit.ts | 65 ++++++++++ .../helpers/__tests__/spending-limit.spec.ts | 63 ++++++++++ packages/cli/src/helpers/spending-limit.ts | 58 +++++++++ packages/cli/src/rest/api.ts | 2 + packages/cli/src/rest/spending-limit.ts | 39 ++++++ skills/checkly/SKILL.md | 2 +- 16 files changed, 628 insertions(+), 3 deletions(-) create mode 100644 packages/cli/src/ai-context/references/manage-spending-limit.md create mode 100644 packages/cli/src/commands/__tests__/account-spending-limit.spec.ts create mode 100644 packages/cli/src/commands/account/spending-limit.ts create mode 100644 packages/cli/src/commands/account/spending-limit/remove.ts create mode 100644 packages/cli/src/commands/account/spending-limit/set.ts create mode 100644 packages/cli/src/formatters/__tests__/spending-limit.spec.ts create mode 100644 packages/cli/src/formatters/spending-limit.ts create mode 100644 packages/cli/src/helpers/__tests__/spending-limit.spec.ts create mode 100644 packages/cli/src/helpers/spending-limit.ts create mode 100644 packages/cli/src/rest/spending-limit.ts diff --git a/packages/cli/package.json b/packages/cli/package.json index 2329c0bea..7c970df9b 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -80,6 +80,9 @@ "account:usage": { "description": "Report organization contract usage, credits, and projections." }, + "account:spending-limit": { + "description": "Show and manage the overage spending limit." + }, "alert-channels": { "description": "List and inspect alert channels in your Checkly account." }, diff --git a/packages/cli/src/ai-context/context.ts b/packages/cli/src/ai-context/context.ts index 198d59328..30e2df07f 100644 --- a/packages/cli/src/ai-context/context.ts +++ b/packages/cli/src/ai-context/context.ts @@ -96,6 +96,10 @@ export const MANAGE_REFERENCES = [ id: 'manage-account-members', description: 'List account members and pending invites (`members`), update member roles, and delete members', }, + { + id: 'manage-spending-limit', + description: 'Show, set, and remove the overage spending limit (`account spending-limit`)', + }, ] as const export const SKILL = { @@ -125,7 +129,7 @@ export const ACTIONS = [ }, { id: 'manage', - description: 'Understand your account plan, entitlements, feature limits, members, and pending invites.', + description: 'Understand your account plan, entitlements, feature limits, members, pending invites, and spending limit.', references: MANAGE_REFERENCES, }, ] as const diff --git a/packages/cli/src/ai-context/references/manage-spending-limit.md b/packages/cli/src/ai-context/references/manage-spending-limit.md new file mode 100644 index 000000000..4ad2b05b8 --- /dev/null +++ b/packages/cli/src/ai-context/references/manage-spending-limit.md @@ -0,0 +1,38 @@ +# Spending Limit + +Show and manage the account's overage spending limit: the most the account may spend on runs beyond what the plan includes. When overage reaches the limit, checks stop running. + +## Usage + +```bash +npx checkly account spending-limit # Limit, overage so far, whether checks are stopped +npx checkly account spending-limit --output json # Raw API response (recommended for agents) +npx checkly account spending-limit set 50 # Set or change the limit, in US dollars +npx checkly account spending-limit set 12.50 --dry-run # Preview the change without applying it +npx checkly account spending-limit remove --force # Remove the limit (overage is no longer capped) +``` + +- `set ` takes 0 to 10000 with at most 2 decimals. `0` allows no overage at all. +- `set` and `remove` require confirmation. In non-interactive mode, review the confirmation preview and rerun with `--force`. Do not change the limit unless the user asked for it: lowering it to or below the overage so far stops checks at once. +- Plans that cannot hold a limit (e.g. prepaid or contract plans) are rejected. + +## JSON response shape + +```json +{ + "spendingCapCents": 3000, + "standing": { + "measuredAt": "2026-11-15T00:00:00.000Z", + "pools": { + "API": { "used": 17230, "included": 100000, "overageRuns": 0, "overageCents": 0 }, + "BROWSER": { "used": 14890, "included": 12000, "overageRuns": 2890, "overageCents": 1806.25 } + }, + "overageCents": 1806.25, + "limit": { "capCents": 3000, "state": "CLOSE", "closeAtCents": 2400 } + } +} +``` + +- Amounts are in US cents. `spendingCapCents: null` means no limit. +- `standing: null` means overage is not measured (runs not measured yet, or the plan has no overage). It does not mean $0 overage. +- Checks are stopped when `standing.limit.state` is `REACHED`. diff --git a/packages/cli/src/ai-context/references/manage.md b/packages/cli/src/ai-context/references/manage.md index fc1371b5a..5ba5ff863 100644 --- a/packages/cli/src/ai-context/references/manage.md +++ b/packages/cli/src/ai-context/references/manage.md @@ -1,6 +1,6 @@ # Account Management -Understand your account's plan, entitlements, limits, members, and pending invites. +Understand your account's plan, entitlements, limits, members, pending invites, and overage spending limit. ## Plan-aware workflow diff --git a/packages/cli/src/commands/__tests__/account-spending-limit.spec.ts b/packages/cli/src/commands/__tests__/account-spending-limit.spec.ts new file mode 100644 index 000000000..2de433f03 --- /dev/null +++ b/packages/cli/src/commands/__tests__/account-spending-limit.spec.ts @@ -0,0 +1,119 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('../../helpers/cli-mode', () => ({ + detectCliMode: vi.fn(() => 'agent'), +})) + +vi.mock('../../rest/api', () => ({ + spendingLimit: { get: vi.fn(), update: vi.fn() }, +})) + +import * as api from '../../rest/api.js' +import { ConflictError } from '../../rest/errors.js' +import { InvalidInputError } from '../../helpers/invalid-input-error.js' +import { stripAnsi } from '../../formatters/render.js' +import type { SpendingLimit } from '../../rest/spending-limit.js' +import AccountSpendingLimit from '../account/spending-limit.js' +import AccountSpendingLimitSet from '../account/spending-limit/set.js' +import AccountSpendingLimitRemove from '../account/spending-limit/remove.js' +import { createCommandContext } from './helpers/command-context.js' + +const current: SpendingLimit = { + spendingCapCents: 5000, + standing: { + measuredAt: '2099-11-15T00:00:00.000Z', + pools: { BROWSER: { used: 14890, included: 12000, overageRuns: 2890, overageCents: 1806.25 } }, + overageCents: 1806.25, + limit: { capCents: 5000, state: 'UNDER', closeAtCents: 4000 }, + }, +} + +const mutationFlags = { 'output': 'detail', 'force': false, 'dry-run': false } + +function context (Command: any, parsed: Record) { + return createCommandContext({ command: Command, parsed }) +} + +beforeEach(() => { + vi.clearAllMocks() + process.exitCode = undefined + vi.mocked(api.spendingLimit.get).mockResolvedValue({ data: current } as any) + vi.mocked(api.spendingLimit.update).mockImplementation(cap => + Promise.resolve({ data: { spendingCapCents: cap } } as any)) +}) + +describe('account spending-limit', () => { + it('prints the API response as is for --output json', async () => { + const ctx = context(AccountSpendingLimit, { flags: { output: 'json' } }) + await AccountSpendingLimit.prototype.run.call(ctx as any) + expect(JSON.parse(ctx.logged[0])).toEqual(current) + }) + + it('renders the terminal view', async () => { + const ctx = context(AccountSpendingLimit, { flags: { output: 'detail' } }) + await AccountSpendingLimit.prototype.run.call(ctx as any) + expect(stripAnsi(ctx.logged[0])).toMatch(/Spending limit:\s+\$50\.00/) + }) + + it('maps a 409 to a clear error and exits 1', async () => { + vi.mocked(api.spendingLimit.get).mockRejectedValue( + new ConflictError({ statusCode: 409, error: 'Conflict', message: 'PREPAID' })) + const ctx = context(AccountSpendingLimit, { flags: { output: 'detail' } }) + await AccountSpendingLimit.prototype.run.call(ctx as any) + expect(ctx.style.longError).toHaveBeenCalledWith('Failed to load the spending limit.', + expect.stringMatching(/plan cannot have a spending limit/)) + expect(process.exitCode).toBe(1) + }) +}) + +describe('account spending-limit set', () => { + it('rejects invalid amounts before calling the API', async () => { + const ctx = context(AccountSpendingLimitSet, { args: { dollars: '10000.01' }, flags: mutationFlags }) + await expect(AccountSpendingLimitSet.prototype.run.call(ctx as any)).rejects.toThrow(InvalidInputError) + expect(api.spendingLimit.get).not.toHaveBeenCalled() + }) + + it('asks for confirmation in agent mode, previewing the change and the warning', async () => { + const ctx = context(AccountSpendingLimitSet, { args: { dollars: '12.50' }, flags: mutationFlags }) + await expect(AccountSpendingLimitSet.prototype.run.call(ctx as any)).rejects.toThrow('EXIT_3') + const preview = JSON.parse(ctx.logged[0]) + expect(preview).toMatchObject({ status: 'confirmation_required', command: 'account spending-limit set' }) + expect(preview.changes[0]).toBe('Change the spending limit from $50.00 to $12.50') + expect(preview.changes[1]).toMatch(/stop running at once/) + expect(preview.confirmCommand).toBe('npx checkly account spending-limit set 12.50 --force') + expect(api.spendingLimit.update).not.toHaveBeenCalled() + }) + + it('--dry-run previews and exits 0', async () => { + const ctx = context(AccountSpendingLimitSet, { + args: { dollars: '20' }, flags: { ...mutationFlags, 'dry-run': true }, + }) + await expect(AccountSpendingLimitSet.prototype.run.call(ctx as any)).rejects.toThrow('EXIT_0') + expect(JSON.parse(ctx.logged[0]).status).toBe('dry_run') + expect(api.spendingLimit.update).not.toHaveBeenCalled() + }) + + it('sends integer cents with --force and prints the response for --output json', async () => { + const ctx = context(AccountSpendingLimitSet, { + args: { dollars: '0.29' }, flags: { ...mutationFlags, output: 'json', force: true }, + }) + await AccountSpendingLimitSet.prototype.run.call(ctx as any) + expect(api.spendingLimit.update).toHaveBeenCalledExactlyOnceWith(29) + expect(JSON.parse(ctx.logged[0])).toEqual({ spendingCapCents: 29 }) + }) +}) + +describe('account spending-limit remove', () => { + it('sends null with --force', async () => { + const ctx = context(AccountSpendingLimitRemove, { flags: { ...mutationFlags, force: true } }) + await AccountSpendingLimitRemove.prototype.run.call(ctx as any) + expect(api.spendingLimit.update).toHaveBeenCalledExactlyOnceWith(null) + expect(ctx.style.shortSuccess).toHaveBeenCalledWith('Spending limit removed. Overage is no longer capped.') + }) + + it('previews removing the current limit', async () => { + const ctx = context(AccountSpendingLimitRemove, { flags: mutationFlags }) + await expect(AccountSpendingLimitRemove.prototype.run.call(ctx as any)).rejects.toThrow('EXIT_3') + expect(JSON.parse(ctx.logged[0]).changes).toEqual(['Remove the spending limit of $50.00']) + }) +}) diff --git a/packages/cli/src/commands/__tests__/command-metadata.spec.ts b/packages/cli/src/commands/__tests__/command-metadata.spec.ts index 821974f62..19b130866 100644 --- a/packages/cli/src/commands/__tests__/command-metadata.spec.ts +++ b/packages/cli/src/commands/__tests__/command-metadata.spec.ts @@ -52,6 +52,9 @@ import UsageTermCommand from '../account/usage/term.js' import UsageProjectionsCommand from '../account/usage/projections.js' import UsageSummaryCommand from '../account/usage/summary.js' import UsageSeriesCommand from '../account/usage/series.js' +import AccountSpendingLimit from '../account/spending-limit.js' +import AccountSpendingLimitSet from '../account/spending-limit/set.js' +import AccountSpendingLimitRemove from '../account/spending-limit/remove.js' const commands: Array<[string, typeof BaseCommand]> = [ ['api', Api], @@ -77,6 +80,9 @@ const commands: Array<[string, typeof BaseCommand]> = [ ['account usage projections', UsageProjectionsCommand], ['account usage summary', UsageSummaryCommand], ['account usage series', UsageSeriesCommand], + ['account spending-limit', AccountSpendingLimit], + ['account spending-limit set', AccountSpendingLimitSet], + ['account spending-limit remove', AccountSpendingLimitRemove], ['incidents list', IncidentsList], ['incidents create', IncidentsCreate], ['incidents update', IncidentsUpdate], diff --git a/packages/cli/src/commands/account/spending-limit.ts b/packages/cli/src/commands/account/spending-limit.ts new file mode 100644 index 000000000..cd9af1d1d --- /dev/null +++ b/packages/cli/src/commands/account/spending-limit.ts @@ -0,0 +1,36 @@ +import { AuthCommand } from '../authCommand.js' +import { outputFlag } from '../../helpers/flags.js' +import { exitCodeFor } from '../../helpers/invalid-input-error.js' +import { describeSpendingLimitError } from '../../helpers/spending-limit.js' +import * as api from '../../rest/api.js' +import type { OutputFormat } from '../../formatters/render.js' +import { formatSpendingLimit } from '../../formatters/spending-limit.js' + +export default class AccountSpendingLimit extends AuthCommand { + static hidden = false + static readOnly = true + static destructive = false + static idempotent = true + static description = 'Show the overage spending limit, the overage spent so far, and whether checks are stopped.' + + static flags = { + output: outputFlag({ default: 'detail' }), + } + + async run (): Promise { + const { flags } = await this.parse(AccountSpendingLimit) + this.style.outputFormat = flags.output + try { + const { data } = await api.spendingLimit.get() + if (flags.output === 'json') { + this.log(JSON.stringify(data, null, 2)) + return + } + const fmt: OutputFormat = flags.output === 'md' ? 'md' : 'terminal' + this.log(formatSpendingLimit(data, fmt)) + } catch (err: unknown) { + this.style.longError('Failed to load the spending limit.', describeSpendingLimitError(err, 'billing:read')) + process.exitCode = exitCodeFor(err) + } + } +} diff --git a/packages/cli/src/commands/account/spending-limit/remove.ts b/packages/cli/src/commands/account/spending-limit/remove.ts new file mode 100644 index 000000000..4fd4454c6 --- /dev/null +++ b/packages/cli/src/commands/account/spending-limit/remove.ts @@ -0,0 +1,57 @@ +import { AuthCommand } from '../../authCommand.js' +import { dryRunFlag, forceFlag, outputFlag } from '../../../helpers/flags.js' +import { exitCodeFor } from '../../../helpers/invalid-input-error.js' +import { describeSpendingLimitError, spendingLimitChanges } from '../../../helpers/spending-limit.js' +import * as api from '../../../rest/api.js' + +export default class AccountSpendingLimitRemove extends AuthCommand { + static hidden = false + static readOnly = false + static destructive = true + static idempotent = true + static description = 'Remove the overage spending limit, so overage is no longer capped.' + + static flags = { + 'output': outputFlag({ default: 'detail' }), + 'force': forceFlag(), + 'dry-run': dryRunFlag(), + } + + async run (): Promise { + const { flags } = await this.parse(AccountSpendingLimitRemove) + this.style.outputFormat = flags.output + + let current + try { + ({ data: current } = await api.spendingLimit.get()) + } catch (err: unknown) { + this.style.longError('Failed to load the spending limit.', describeSpendingLimitError(err, 'billing:read')) + process.exitCode = exitCodeFor(err) + return + } + + await this.confirmOrAbort({ + command: 'account spending-limit remove', + description: 'Remove the spending limit', + changes: spendingLimitChanges(current, null), + flags, + classification: { + readOnly: AccountSpendingLimitRemove.readOnly, + destructive: AccountSpendingLimitRemove.destructive, + idempotent: AccountSpendingLimitRemove.idempotent, + }, + }, { force: flags.force, dryRun: flags['dry-run'] }) + + try { + const { data } = await api.spendingLimit.update(null) + if (flags.output === 'json') { + this.log(JSON.stringify(data, null, 2)) + return + } + this.style.shortSuccess('Spending limit removed. Overage is no longer capped.') + } catch (err: unknown) { + this.style.longError('Failed to remove the spending limit.', describeSpendingLimitError(err, 'billing:update')) + process.exitCode = exitCodeFor(err) + } + } +} diff --git a/packages/cli/src/commands/account/spending-limit/set.ts b/packages/cli/src/commands/account/spending-limit/set.ts new file mode 100644 index 000000000..e7f6462f8 --- /dev/null +++ b/packages/cli/src/commands/account/spending-limit/set.ts @@ -0,0 +1,73 @@ +import { Args } from '@oclif/core' +import { AuthCommand } from '../../authCommand.js' +import { dryRunFlag, forceFlag, outputFlag } from '../../../helpers/flags.js' +import { exitCodeFor } from '../../../helpers/invalid-input-error.js' +import { + describeSpendingLimitError, + MAX_SPENDING_LIMIT_DOLLARS, + parseDollarsToCents, + spendingLimitChanges, +} from '../../../helpers/spending-limit.js' +import * as api from '../../../rest/api.js' +import { formatDollars } from '../../../formatters/spending-limit.js' + +export default class AccountSpendingLimitSet extends AuthCommand { + static hidden = false + static readOnly = false + static destructive = false + static idempotent = true + static description = 'Set or change the overage spending limit. Checks stop running once overage reaches it.' + + static args = { + dollars: Args.string({ + required: true, + description: `The limit in US dollars, e.g. 50 or 12.50 (0 to ${MAX_SPENDING_LIMIT_DOLLARS}).`, + }), + } + + static flags = { + 'output': outputFlag({ default: 'detail' }), + 'force': forceFlag(), + 'dry-run': dryRunFlag(), + } + + async run (): Promise { + const { args, flags } = await this.parse(AccountSpendingLimitSet) + this.style.outputFormat = flags.output + const capCents = parseDollarsToCents(args.dollars) + + let current + try { + ({ data: current } = await api.spendingLimit.get()) + } catch (err: unknown) { + this.style.longError('Failed to load the spending limit.', describeSpendingLimitError(err, 'billing:read')) + process.exitCode = exitCodeFor(err) + return + } + + await this.confirmOrAbort({ + command: 'account spending-limit set', + description: 'Set the spending limit', + changes: spendingLimitChanges(current, capCents), + flags, + args: { dollars: args.dollars }, + classification: { + readOnly: AccountSpendingLimitSet.readOnly, + destructive: AccountSpendingLimitSet.destructive, + idempotent: AccountSpendingLimitSet.idempotent, + }, + }, { force: flags.force, dryRun: flags['dry-run'] }) + + try { + const { data } = await api.spendingLimit.update(capCents) + if (flags.output === 'json') { + this.log(JSON.stringify(data, null, 2)) + return + } + this.style.shortSuccess(`Spending limit set to ${formatDollars(data.spendingCapCents ?? capCents)}.`) + } catch (err: unknown) { + this.style.longError('Failed to set the spending limit.', describeSpendingLimitError(err, 'billing:update')) + process.exitCode = exitCodeFor(err) + } + } +} diff --git a/packages/cli/src/formatters/__tests__/spending-limit.spec.ts b/packages/cli/src/formatters/__tests__/spending-limit.spec.ts new file mode 100644 index 000000000..688c3cf4e --- /dev/null +++ b/packages/cli/src/formatters/__tests__/spending-limit.spec.ts @@ -0,0 +1,62 @@ +import { describe, expect, it } from 'vitest' +import { stripAnsi } from '../render.js' +import { formatDollars, formatSpendingLimit } from '../spending-limit.js' +import type { SpendingLimit } from '../../rest/spending-limit.js' + +const closeToLimit: SpendingLimit = { + spendingCapCents: 3000, + standing: { + measuredAt: '2099-11-15T00:00:00.000Z', + pools: { + API: { used: 17230, included: 100000, overageRuns: 0, overageCents: 0 }, + BROWSER: { used: 14890, included: 12000, overageRuns: 2890, overageCents: 1806.25 }, + }, + overageCents: 1806.25, + limit: { capCents: 3000, state: 'CLOSE', closeAtCents: 2400 }, + }, +} + +describe('formatDollars', () => { + it('formats cents as dollars, rounding fractional cents', () => { + expect(formatDollars(1806.25)).toBe('$18.06') + expect(formatDollars(0)).toBe('$0.00') + expect(formatDollars(1000000)).toBe('$10,000.00') + }) +}) + +describe('formatSpendingLimit', () => { + it('shows the limit, overage, status and measurement time', () => { + const out = stripAnsi(formatSpendingLimit(closeToLimit, 'terminal')) + expect(out).toMatch(/Spending limit:\s+\$30\.00/) + expect(out).toMatch(/Overage so far:\s+\$18\.06/) + expect(out).toMatch(/Status:\s+Close to the limit \(from \$24\.00\)/) + expect(out).toMatch(/Checks stopped:\s+No/) + expect(out).toMatch(/Measured at:\s+2099-11-15 00:00:00 UTC/) + }) + + it('says checks are stopped when the limit is reached', () => { + const reached: SpendingLimit = { + ...closeToLimit, + standing: { ...closeToLimit.standing!, limit: { capCents: 3000, state: 'REACHED', closeAtCents: 2400 } }, + } + expect(stripAnsi(formatSpendingLimit(reached, 'terminal'))).toMatch(/Checks stopped:\s+Yes/) + }) + + it('never shows $0 overage when nothing is measured', () => { + const out = formatSpendingLimit({ spendingCapCents: null, standing: null }, 'md') + expect(out).toContain('| Spending limit | No limit |') + expect(out).toContain('| Overage so far | Not measured') + expect(out).not.toContain('$0') + expect(out).not.toContain('Checks stopped') + }) + + it('labels a $0 limit and omits the status without a limit', () => { + const out = formatSpendingLimit({ + spendingCapCents: 0, + standing: { ...closeToLimit.standing!, overageCents: 0, limit: null }, + }, 'md') + expect(out).toContain('| Spending limit | $0.00 (no overage allowed) |') + expect(out).toContain('| Overage so far | $0.00 |') + expect(out).not.toContain('| Status |') + }) +}) diff --git a/packages/cli/src/formatters/spending-limit.ts b/packages/cli/src/formatters/spending-limit.ts new file mode 100644 index 000000000..92f545d0c --- /dev/null +++ b/packages/cli/src/formatters/spending-limit.ts @@ -0,0 +1,65 @@ +import chalk from 'chalk' +import type { SpendingLimit, SpendingLimitState } from '../rest/spending-limit.js' +import { type DetailField, type OutputFormat, formatDate, renderDetailFields } from './render.js' + +const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }) + +/** Cents (possibly fractional, e.g. overage) as dollars: `1806.25` → `$18.06`. */ +export function formatDollars (cents: number): string { + return usd.format(cents / 100) +} + +const STATE_LABELS: Record = { + UNDER: 'Under the limit', + CLOSE: 'Close to the limit', + REACHED: 'Limit reached', +} + +function color (format: OutputFormat, paint: (s: string) => string, value: string) { + return format === 'terminal' ? paint(value) : value +} + +const fields: DetailField[] = [ + { + label: 'Spending limit', + value: ({ spendingCapCents: cap }) => { + if (cap === null) return 'No limit' + return cap === 0 ? `${formatDollars(0)} (no overage allowed)` : formatDollars(cap) + }, + }, + { + label: 'Overage so far', + value: ({ standing }) => standing + ? formatDollars(standing.overageCents) + : 'Not measured (runs not measured yet, or no overage on this plan)', + }, + { + label: 'Status', + value: ({ standing }, format) => { + const limit = standing?.limit + if (!limit) return null + const label = STATE_LABELS[limit.state] ?? limit.state + if (limit.state === 'CLOSE') { + return color(format, chalk.yellow, `${label} (from ${formatDollars(limit.closeAtCents)})`) + } + return limit.state === 'REACHED' ? color(format, chalk.red, label) : label + }, + }, + { + label: 'Checks stopped', + value: ({ standing }, format) => { + if (!standing) return null + return standing.limit?.state === 'REACHED' + ? color(format, chalk.red, 'Yes, the spending limit is reached') + : 'No' + }, + }, + { + label: 'Measured at', + value: ({ standing }, format) => standing ? formatDate(standing.measuredAt, format) : null, + }, +] + +export function formatSpendingLimit (data: SpendingLimit, format: OutputFormat): string { + return renderDetailFields('Spending limit', fields, data, format) +} diff --git a/packages/cli/src/helpers/__tests__/spending-limit.spec.ts b/packages/cli/src/helpers/__tests__/spending-limit.spec.ts new file mode 100644 index 000000000..45bd44fd3 --- /dev/null +++ b/packages/cli/src/helpers/__tests__/spending-limit.spec.ts @@ -0,0 +1,63 @@ +import { describe, expect, it } from 'vitest' +import { InvalidInputError } from '../invalid-input-error.js' +import { describeSpendingLimitError, parseDollarsToCents, spendingLimitChanges } from '../spending-limit.js' +import { ConflictError, ForbiddenError, ACCOUNT_NOT_ACCESSIBLE } from '../../rest/errors.js' +import type { SpendingLimit } from '../../rest/spending-limit.js' + +describe('parseDollarsToCents', () => { + it.each([ + ['50', 5000], ['12.5', 1250], ['12.50', 1250], ['0', 0], ['0.01', 1], + ['0.29', 29], ['1.15', 115], ['10000', 1000000], ['10000.00', 1000000], [' 7 ', 700], + ])('%s → %i cents', (input, cents) => { + expect(parseDollarsToCents(input)).toBe(cents) + }) + + it.each(['-5', '10000.01', '20000', '1.234', 'abc', '', '1e3', '$5', '.5', '5.', 'NaN', 'Infinity'])( + 'rejects %j as invalid input', input => { + expect(() => parseDollarsToCents(input)).toThrow(InvalidInputError) + }) +}) + +const standing = (overageCents: number): SpendingLimit['standing'] => ({ + measuredAt: '2099-11-15T00:00:00.000Z', pools: {}, overageCents, limit: null, +}) + +describe('spendingLimitChanges', () => { + it('describes setting, changing and removing', () => { + expect(spendingLimitChanges({ spendingCapCents: null, standing: null }, 2000)) + .toEqual(['Set the spending limit to $20.00']) + expect(spendingLimitChanges({ spendingCapCents: 5000, standing: standing(0) }, 2000)) + .toEqual(['Change the spending limit from $50.00 to $20.00']) + expect(spendingLimitChanges({ spendingCapCents: 5000, standing: null }, null)) + .toEqual(['Remove the spending limit of $50.00']) + expect(spendingLimitChanges({ spendingCapCents: null, standing: null }, null)) + .toEqual(['Remove the spending limit (none is set)']) + }) + + it('warns when the new limit is at or below the overage so far', () => { + const changes = spendingLimitChanges({ spendingCapCents: 5000, standing: standing(1806.25) }, 1800) + expect(changes[1]).toMatch(/overage so far \(\$18\.06\) is at or above the new limit.*stop running at once/) + expect(spendingLimitChanges({ spendingCapCents: 5000, standing: standing(1806.25) }, 1807)).toHaveLength(1) + }) + + it('warns about a $0 limit', () => { + expect(spendingLimitChanges({ spendingCapCents: 5000, standing: null }, 0)[1]) + .toMatch(/\$0\.00 limit allows no overage/) + }) +}) + +describe('describeSpendingLimitError', () => { + it('maps 409 and 403 to clear messages', () => { + expect(describeSpendingLimitError(new ConflictError({ statusCode: 409, error: 'Conflict', message: 'x' }), 'billing:update')) + .toMatch(/plan cannot have a spending limit/) + expect(describeSpendingLimitError(new ForbiddenError({ statusCode: 403, error: 'Forbidden', message: 'x' }), 'billing:update')) + .toMatch(/billing:update permission/) + }) + + it('passes other errors through', () => { + const notAccessible = new ForbiddenError({ + statusCode: 403, error: 'Forbidden', message: 'x', errorCode: ACCOUNT_NOT_ACCESSIBLE, + }) + expect(describeSpendingLimitError(notAccessible, 'billing:read')).toBe(notAccessible) + }) +}) diff --git a/packages/cli/src/helpers/spending-limit.ts b/packages/cli/src/helpers/spending-limit.ts new file mode 100644 index 000000000..756d6574a --- /dev/null +++ b/packages/cli/src/helpers/spending-limit.ts @@ -0,0 +1,58 @@ +import { InvalidInputError } from './invalid-input-error.js' +import { ConflictError, ForbiddenError, isAccountNotAccessible } from '../rest/errors.js' +import { formatDollars } from '../formatters/spending-limit.js' +import type { SpendingLimit } from '../rest/spending-limit.js' + +export const MAX_SPENDING_LIMIT_DOLLARS = 10000 + +/** + * A dollar amount (`50`, `12.5`, `12.50`) as integer cents, from the digits so + * no float rounding creeps in. At most 2 decimals, from 0 to 10000. + */ +export function parseDollarsToCents (input: string): number { + const match = /^(\d+)(?:\.(\d{1,2}))?$/.exec(input.trim()) + if (!match) { + throw new InvalidInputError( + `Invalid amount "${input}". Use a non-negative dollar amount with at most 2 decimals, e.g. 50 or 12.50.`) + } + const cents = Number(match[1]) * 100 + Number((match[2] ?? '').padEnd(2, '0')) + if (cents > MAX_SPENDING_LIMIT_DOLLARS * 100) { + throw new InvalidInputError( + `Invalid amount "${input}". The spending limit can be at most ${formatDollars(MAX_SPENDING_LIMIT_DOLLARS * 100)}.`) + } + return cents +} + +/** The preview lines for changing the limit from `current` to `capCents` (`null` removes it). */ +export function spendingLimitChanges (current: SpendingLimit, capCents: number | null): string[] { + const from = current.spendingCapCents + const changes = [ + capCents === null + ? from === null ? 'Remove the spending limit (none is set)' : `Remove the spending limit of ${formatDollars(from)}` + : from === null + ? `Set the spending limit to ${formatDollars(capCents)}` + : `Change the spending limit from ${formatDollars(from)} to ${formatDollars(capCents)}`, + ] + const overage = current.standing?.overageCents ?? 0 + if (capCents !== null && overage > 0 && capCents <= overage) { + changes.push(`Warning: overage so far (${formatDollars(overage)}) is at or above the new limit, ` + + 'so checks stop running at once') + } else if (capCents === 0) { + changes.push('Warning: a $0.00 limit allows no overage, so checks stop running as soon as ' + + 'the included runs are used up') + } + return changes +} + +/** Clear messages for the API's 403 and 409; anything else as it came. */ +export function describeSpendingLimitError (err: unknown, permission: 'billing:read' | 'billing:update'): string | Error { + if (err instanceof ConflictError) { + return 'This account\'s plan cannot have a spending limit (for example prepaid or contract plans). ' + + `(${err.message})` + } + if (err instanceof ForbiddenError && !isAccountNotAccessible(err)) { + return `Not allowed: your role needs the ${permission} permission, and the account must manage its plan ` + + `in Checkly (self-serve billing). Ask an account owner or admin. (${err.message})` + } + return err instanceof Error ? err : String(err) +} diff --git a/packages/cli/src/rest/api.ts b/packages/cli/src/rest/api.ts index 740cb05a4..c2f518b5d 100644 --- a/packages/cli/src/rest/api.ts +++ b/packages/cli/src/rest/api.ts @@ -32,6 +32,7 @@ import AlertNotifications from './alert-notifications.js' import Rca from './rca.js' import Cancel from './cancel.js' import Usage from './usage.js' +import SpendingLimits from './spending-limit.js' import { ForbiddenError, handleErrorResponse, NotFoundError, UnauthorizedError } from './errors.js' import { createRetryInterceptor } from './retry.js' import { detectCliMode, detectOperator } from '../helpers/cli-mode.js' @@ -199,3 +200,4 @@ export const alertNotifications = new AlertNotifications(getApi) export const rca = new Rca(getApi) export const cancel = new Cancel(getApi) export const usage = new Usage(getApi) +export const spendingLimit = new SpendingLimits(getApi) diff --git a/packages/cli/src/rest/spending-limit.ts b/packages/cli/src/rest/spending-limit.ts new file mode 100644 index 000000000..90340d55e --- /dev/null +++ b/packages/cli/src/rest/spending-limit.ts @@ -0,0 +1,39 @@ +import { RestResource } from './rest-resource.js' + +export type SpendingLimitState = 'UNDER' | 'CLOSE' | 'REACHED' + +export interface SpendingPool { + used: number + included: number + overageRuns: number + overageCents: number +} + +export interface SpendingStanding { + measuredAt: string + pools: Record + /** Not rounded to whole cents. */ + overageCents: number + /** `null` when the account has no limit. */ + limit: { capCents: number, state: SpendingLimitState, closeAtCents: number } | null +} + +export interface SpendingLimit { + /** `null` = no limit; `0` = no overage allowed. */ + spendingCapCents: number | null + /** `null` when nothing is judged (plan without overage, or runs not measured yet). Not $0 overage. */ + standing: SpendingStanding | null +} + +class SpendingLimits extends RestResource { + get () { + return this.api.get('/v1/billing/spending-limit') + } + + /** `null` removes the limit. */ + update (spendingCapCents: number | null) { + return this.api.put>('/v1/billing/spending-limit', { spendingCapCents }) + } +} + +export default SpendingLimits diff --git a/skills/checkly/SKILL.md b/skills/checkly/SKILL.md index 93dde83d6..f6fdbdc83 100644 --- a/skills/checkly/SKILL.md +++ b/skills/checkly/SKILL.md @@ -160,4 +160,4 @@ Access check and test-session status, analyze failures, inspect attempts/assets, Open incidents and lead customer communications via status pages. ### `npx checkly skills manage` -Understand your account plan, entitlements, feature limits, members, and pending invites. +Understand your account plan, entitlements, feature limits, members, pending invites, and spending limit. From 4c62d696d271c646e77459203c3f12d4981bb9df Mon Sep 17 00:00:00 2001 From: ejanusevicius Date: Fri, 20 Nov 2026 14:18:29 +0000 Subject: [PATCH 2/2] refactor(cli): rename spending-limit to spending-cap Match the API: `/v1/billing/spending-cap`, `checkly account spending-cap`, "spending cap" in user-facing text. Explain the 401 legacy account API keys get. Co-Authored-By: Claude Opus 5.5 --- packages/cli/package.json | 4 +- packages/cli/src/ai-context/context.ts | 6 +- .../references/manage-spending-cap.md | 39 ++++++ .../references/manage-spending-limit.md | 38 ------ .../cli/src/ai-context/references/manage.md | 2 +- .../__tests__/account-spending-cap.spec.ts | 119 ++++++++++++++++++ .../__tests__/account-spending-limit.spec.ts | 119 ------------------ .../__tests__/command-metadata.spec.ts | 12 +- .../{spending-limit.ts => spending-cap.ts} | 16 +-- .../commands/account/spending-cap/remove.ts | 57 +++++++++ .../src/commands/account/spending-cap/set.ts | 73 +++++++++++ .../commands/account/spending-limit/remove.ts | 57 --------- .../commands/account/spending-limit/set.ts | 73 ----------- ...ing-limit.spec.ts => spending-cap.spec.ts} | 32 ++--- .../{spending-limit.ts => spending-cap.ts} | 22 ++-- .../helpers/__tests__/spending-cap.spec.ts | 65 ++++++++++ .../helpers/__tests__/spending-limit.spec.ts | 63 ---------- packages/cli/src/helpers/spending-cap.ts | 61 +++++++++ packages/cli/src/helpers/spending-limit.ts | 58 --------- packages/cli/src/rest/api.ts | 4 +- packages/cli/src/rest/spending-cap.ts | 39 ++++++ packages/cli/src/rest/spending-limit.ts | 39 ------ skills/checkly/SKILL.md | 2 +- 23 files changed, 503 insertions(+), 497 deletions(-) create mode 100644 packages/cli/src/ai-context/references/manage-spending-cap.md delete mode 100644 packages/cli/src/ai-context/references/manage-spending-limit.md create mode 100644 packages/cli/src/commands/__tests__/account-spending-cap.spec.ts delete mode 100644 packages/cli/src/commands/__tests__/account-spending-limit.spec.ts rename packages/cli/src/commands/account/{spending-limit.ts => spending-cap.ts} (56%) create mode 100644 packages/cli/src/commands/account/spending-cap/remove.ts create mode 100644 packages/cli/src/commands/account/spending-cap/set.ts delete mode 100644 packages/cli/src/commands/account/spending-limit/remove.ts delete mode 100644 packages/cli/src/commands/account/spending-limit/set.ts rename packages/cli/src/formatters/__tests__/{spending-limit.spec.ts => spending-cap.spec.ts} (59%) rename packages/cli/src/formatters/{spending-limit.ts => spending-cap.ts} (73%) create mode 100644 packages/cli/src/helpers/__tests__/spending-cap.spec.ts delete mode 100644 packages/cli/src/helpers/__tests__/spending-limit.spec.ts create mode 100644 packages/cli/src/helpers/spending-cap.ts delete mode 100644 packages/cli/src/helpers/spending-limit.ts create mode 100644 packages/cli/src/rest/spending-cap.ts delete mode 100644 packages/cli/src/rest/spending-limit.ts diff --git a/packages/cli/package.json b/packages/cli/package.json index 7c970df9b..131960b9e 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -80,8 +80,8 @@ "account:usage": { "description": "Report organization contract usage, credits, and projections." }, - "account:spending-limit": { - "description": "Show and manage the overage spending limit." + "account:spending-cap": { + "description": "Show and manage the overage spending cap." }, "alert-channels": { "description": "List and inspect alert channels in your Checkly account." diff --git a/packages/cli/src/ai-context/context.ts b/packages/cli/src/ai-context/context.ts index 30e2df07f..6e0e42885 100644 --- a/packages/cli/src/ai-context/context.ts +++ b/packages/cli/src/ai-context/context.ts @@ -97,8 +97,8 @@ export const MANAGE_REFERENCES = [ description: 'List account members and pending invites (`members`), update member roles, and delete members', }, { - id: 'manage-spending-limit', - description: 'Show, set, and remove the overage spending limit (`account spending-limit`)', + id: 'manage-spending-cap', + description: 'Show, set, and remove the overage spending cap (`account spending-cap`)', }, ] as const @@ -129,7 +129,7 @@ export const ACTIONS = [ }, { id: 'manage', - description: 'Understand your account plan, entitlements, feature limits, members, pending invites, and spending limit.', + description: 'Understand your account plan, entitlements, feature limits, members, pending invites, and spending cap.', references: MANAGE_REFERENCES, }, ] as const diff --git a/packages/cli/src/ai-context/references/manage-spending-cap.md b/packages/cli/src/ai-context/references/manage-spending-cap.md new file mode 100644 index 000000000..77e68e476 --- /dev/null +++ b/packages/cli/src/ai-context/references/manage-spending-cap.md @@ -0,0 +1,39 @@ +# Spending Cap + +Show and manage the account's overage spending cap: the most the account may spend on runs beyond what the plan includes. When overage reaches the cap, checks stop running. + +## Usage + +```bash +npx checkly account spending-cap # Cap, overage so far, whether checks are stopped +npx checkly account spending-cap --output json # Raw API response (recommended for agents) +npx checkly account spending-cap set 50 # Set or change the cap, in US dollars +npx checkly account spending-cap set 12.50 --dry-run # Preview the change without applying it +npx checkly account spending-cap remove --force # Remove the cap (overage is no longer capped) +``` + +- `set ` takes 0 to 10000 with at most 2 decimals. `0` allows no overage at all. +- `set` and `remove` require confirmation. In non-interactive mode, review the confirmation preview and rerun with `--force`. Do not change the cap unless the user asked for it: lowering it to or below the overage so far stops checks at once. +- Plans that cannot hold a cap (e.g. prepaid or contract plans) are rejected. +- Needs a user or service API key; legacy account API keys are rejected (401). + +## JSON response shape + +```json +{ + "spendingCapCents": 3000, + "standing": { + "measuredAt": "2026-11-15T00:00:00.000Z", + "pools": { + "API": { "used": 17230, "included": 100000, "overageRuns": 0, "overageCents": 0 }, + "BROWSER": { "used": 14890, "included": 12000, "overageRuns": 2890, "overageCents": 1806.25 } + }, + "overageCents": 1806.25, + "limit": { "capCents": 3000, "state": "CLOSE", "closeAtCents": 2400 } + } +} +``` + +- Amounts are in US cents. `spendingCapCents: null` means no cap. +- `standing: null` means overage is not measured (runs not measured yet, or the plan has no overage). It does not mean $0 overage. +- Checks are stopped when `standing.limit.state` is `REACHED`. diff --git a/packages/cli/src/ai-context/references/manage-spending-limit.md b/packages/cli/src/ai-context/references/manage-spending-limit.md deleted file mode 100644 index 4ad2b05b8..000000000 --- a/packages/cli/src/ai-context/references/manage-spending-limit.md +++ /dev/null @@ -1,38 +0,0 @@ -# Spending Limit - -Show and manage the account's overage spending limit: the most the account may spend on runs beyond what the plan includes. When overage reaches the limit, checks stop running. - -## Usage - -```bash -npx checkly account spending-limit # Limit, overage so far, whether checks are stopped -npx checkly account spending-limit --output json # Raw API response (recommended for agents) -npx checkly account spending-limit set 50 # Set or change the limit, in US dollars -npx checkly account spending-limit set 12.50 --dry-run # Preview the change without applying it -npx checkly account spending-limit remove --force # Remove the limit (overage is no longer capped) -``` - -- `set ` takes 0 to 10000 with at most 2 decimals. `0` allows no overage at all. -- `set` and `remove` require confirmation. In non-interactive mode, review the confirmation preview and rerun with `--force`. Do not change the limit unless the user asked for it: lowering it to or below the overage so far stops checks at once. -- Plans that cannot hold a limit (e.g. prepaid or contract plans) are rejected. - -## JSON response shape - -```json -{ - "spendingCapCents": 3000, - "standing": { - "measuredAt": "2026-11-15T00:00:00.000Z", - "pools": { - "API": { "used": 17230, "included": 100000, "overageRuns": 0, "overageCents": 0 }, - "BROWSER": { "used": 14890, "included": 12000, "overageRuns": 2890, "overageCents": 1806.25 } - }, - "overageCents": 1806.25, - "limit": { "capCents": 3000, "state": "CLOSE", "closeAtCents": 2400 } - } -} -``` - -- Amounts are in US cents. `spendingCapCents: null` means no limit. -- `standing: null` means overage is not measured (runs not measured yet, or the plan has no overage). It does not mean $0 overage. -- Checks are stopped when `standing.limit.state` is `REACHED`. diff --git a/packages/cli/src/ai-context/references/manage.md b/packages/cli/src/ai-context/references/manage.md index 5ba5ff863..b544ca6c7 100644 --- a/packages/cli/src/ai-context/references/manage.md +++ b/packages/cli/src/ai-context/references/manage.md @@ -1,6 +1,6 @@ # Account Management -Understand your account's plan, entitlements, limits, members, pending invites, and overage spending limit. +Understand your account's plan, entitlements, limits, members, pending invites, and overage spending cap. ## Plan-aware workflow diff --git a/packages/cli/src/commands/__tests__/account-spending-cap.spec.ts b/packages/cli/src/commands/__tests__/account-spending-cap.spec.ts new file mode 100644 index 000000000..59eee6ce9 --- /dev/null +++ b/packages/cli/src/commands/__tests__/account-spending-cap.spec.ts @@ -0,0 +1,119 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('../../helpers/cli-mode', () => ({ + detectCliMode: vi.fn(() => 'agent'), +})) + +vi.mock('../../rest/api', () => ({ + spendingCap: { get: vi.fn(), update: vi.fn() }, +})) + +import * as api from '../../rest/api.js' +import { ConflictError } from '../../rest/errors.js' +import { InvalidInputError } from '../../helpers/invalid-input-error.js' +import { stripAnsi } from '../../formatters/render.js' +import type { SpendingCap } from '../../rest/spending-cap.js' +import AccountSpendingCap from '../account/spending-cap.js' +import AccountSpendingCapSet from '../account/spending-cap/set.js' +import AccountSpendingCapRemove from '../account/spending-cap/remove.js' +import { createCommandContext } from './helpers/command-context.js' + +const current: SpendingCap = { + spendingCapCents: 5000, + standing: { + measuredAt: '2099-11-15T00:00:00.000Z', + pools: { BROWSER: { used: 14890, included: 12000, overageRuns: 2890, overageCents: 1806.25 } }, + overageCents: 1806.25, + limit: { capCents: 5000, state: 'UNDER', closeAtCents: 4000 }, + }, +} + +const mutationFlags = { 'output': 'detail', 'force': false, 'dry-run': false } + +function context (Command: any, parsed: Record) { + return createCommandContext({ command: Command, parsed }) +} + +beforeEach(() => { + vi.clearAllMocks() + process.exitCode = undefined + vi.mocked(api.spendingCap.get).mockResolvedValue({ data: current } as any) + vi.mocked(api.spendingCap.update).mockImplementation(cap => + Promise.resolve({ data: { spendingCapCents: cap } } as any)) +}) + +describe('account spending-cap', () => { + it('prints the API response as is for --output json', async () => { + const ctx = context(AccountSpendingCap, { flags: { output: 'json' } }) + await AccountSpendingCap.prototype.run.call(ctx as any) + expect(JSON.parse(ctx.logged[0])).toEqual(current) + }) + + it('renders the terminal view', async () => { + const ctx = context(AccountSpendingCap, { flags: { output: 'detail' } }) + await AccountSpendingCap.prototype.run.call(ctx as any) + expect(stripAnsi(ctx.logged[0])).toMatch(/Spending cap:\s+\$50\.00/) + }) + + it('maps a 409 to a clear error and exits 1', async () => { + vi.mocked(api.spendingCap.get).mockRejectedValue( + new ConflictError({ statusCode: 409, error: 'Conflict', message: 'PREPAID' })) + const ctx = context(AccountSpendingCap, { flags: { output: 'detail' } }) + await AccountSpendingCap.prototype.run.call(ctx as any) + expect(ctx.style.longError).toHaveBeenCalledWith('Failed to load the spending cap.', + expect.stringMatching(/plan cannot have a spending cap/)) + expect(process.exitCode).toBe(1) + }) +}) + +describe('account spending-cap set', () => { + it('rejects invalid amounts before calling the API', async () => { + const ctx = context(AccountSpendingCapSet, { args: { dollars: '10000.01' }, flags: mutationFlags }) + await expect(AccountSpendingCapSet.prototype.run.call(ctx as any)).rejects.toThrow(InvalidInputError) + expect(api.spendingCap.get).not.toHaveBeenCalled() + }) + + it('asks for confirmation in agent mode, previewing the change and the warning', async () => { + const ctx = context(AccountSpendingCapSet, { args: { dollars: '12.50' }, flags: mutationFlags }) + await expect(AccountSpendingCapSet.prototype.run.call(ctx as any)).rejects.toThrow('EXIT_3') + const preview = JSON.parse(ctx.logged[0]) + expect(preview).toMatchObject({ status: 'confirmation_required', command: 'account spending-cap set' }) + expect(preview.changes[0]).toBe('Change the spending cap from $50.00 to $12.50') + expect(preview.changes[1]).toMatch(/stop running at once/) + expect(preview.confirmCommand).toBe('npx checkly account spending-cap set 12.50 --force') + expect(api.spendingCap.update).not.toHaveBeenCalled() + }) + + it('--dry-run previews and exits 0', async () => { + const ctx = context(AccountSpendingCapSet, { + args: { dollars: '20' }, flags: { ...mutationFlags, 'dry-run': true }, + }) + await expect(AccountSpendingCapSet.prototype.run.call(ctx as any)).rejects.toThrow('EXIT_0') + expect(JSON.parse(ctx.logged[0]).status).toBe('dry_run') + expect(api.spendingCap.update).not.toHaveBeenCalled() + }) + + it('sends integer cents with --force and prints the response for --output json', async () => { + const ctx = context(AccountSpendingCapSet, { + args: { dollars: '0.29' }, flags: { ...mutationFlags, output: 'json', force: true }, + }) + await AccountSpendingCapSet.prototype.run.call(ctx as any) + expect(api.spendingCap.update).toHaveBeenCalledExactlyOnceWith(29) + expect(JSON.parse(ctx.logged[0])).toEqual({ spendingCapCents: 29 }) + }) +}) + +describe('account spending-cap remove', () => { + it('sends null with --force', async () => { + const ctx = context(AccountSpendingCapRemove, { flags: { ...mutationFlags, force: true } }) + await AccountSpendingCapRemove.prototype.run.call(ctx as any) + expect(api.spendingCap.update).toHaveBeenCalledExactlyOnceWith(null) + expect(ctx.style.shortSuccess).toHaveBeenCalledWith('Spending cap removed. Overage is no longer capped.') + }) + + it('previews removing the current cap', async () => { + const ctx = context(AccountSpendingCapRemove, { flags: mutationFlags }) + await expect(AccountSpendingCapRemove.prototype.run.call(ctx as any)).rejects.toThrow('EXIT_3') + expect(JSON.parse(ctx.logged[0]).changes).toEqual(['Remove the spending cap of $50.00']) + }) +}) diff --git a/packages/cli/src/commands/__tests__/account-spending-limit.spec.ts b/packages/cli/src/commands/__tests__/account-spending-limit.spec.ts deleted file mode 100644 index 2de433f03..000000000 --- a/packages/cli/src/commands/__tests__/account-spending-limit.spec.ts +++ /dev/null @@ -1,119 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -vi.mock('../../helpers/cli-mode', () => ({ - detectCliMode: vi.fn(() => 'agent'), -})) - -vi.mock('../../rest/api', () => ({ - spendingLimit: { get: vi.fn(), update: vi.fn() }, -})) - -import * as api from '../../rest/api.js' -import { ConflictError } from '../../rest/errors.js' -import { InvalidInputError } from '../../helpers/invalid-input-error.js' -import { stripAnsi } from '../../formatters/render.js' -import type { SpendingLimit } from '../../rest/spending-limit.js' -import AccountSpendingLimit from '../account/spending-limit.js' -import AccountSpendingLimitSet from '../account/spending-limit/set.js' -import AccountSpendingLimitRemove from '../account/spending-limit/remove.js' -import { createCommandContext } from './helpers/command-context.js' - -const current: SpendingLimit = { - spendingCapCents: 5000, - standing: { - measuredAt: '2099-11-15T00:00:00.000Z', - pools: { BROWSER: { used: 14890, included: 12000, overageRuns: 2890, overageCents: 1806.25 } }, - overageCents: 1806.25, - limit: { capCents: 5000, state: 'UNDER', closeAtCents: 4000 }, - }, -} - -const mutationFlags = { 'output': 'detail', 'force': false, 'dry-run': false } - -function context (Command: any, parsed: Record) { - return createCommandContext({ command: Command, parsed }) -} - -beforeEach(() => { - vi.clearAllMocks() - process.exitCode = undefined - vi.mocked(api.spendingLimit.get).mockResolvedValue({ data: current } as any) - vi.mocked(api.spendingLimit.update).mockImplementation(cap => - Promise.resolve({ data: { spendingCapCents: cap } } as any)) -}) - -describe('account spending-limit', () => { - it('prints the API response as is for --output json', async () => { - const ctx = context(AccountSpendingLimit, { flags: { output: 'json' } }) - await AccountSpendingLimit.prototype.run.call(ctx as any) - expect(JSON.parse(ctx.logged[0])).toEqual(current) - }) - - it('renders the terminal view', async () => { - const ctx = context(AccountSpendingLimit, { flags: { output: 'detail' } }) - await AccountSpendingLimit.prototype.run.call(ctx as any) - expect(stripAnsi(ctx.logged[0])).toMatch(/Spending limit:\s+\$50\.00/) - }) - - it('maps a 409 to a clear error and exits 1', async () => { - vi.mocked(api.spendingLimit.get).mockRejectedValue( - new ConflictError({ statusCode: 409, error: 'Conflict', message: 'PREPAID' })) - const ctx = context(AccountSpendingLimit, { flags: { output: 'detail' } }) - await AccountSpendingLimit.prototype.run.call(ctx as any) - expect(ctx.style.longError).toHaveBeenCalledWith('Failed to load the spending limit.', - expect.stringMatching(/plan cannot have a spending limit/)) - expect(process.exitCode).toBe(1) - }) -}) - -describe('account spending-limit set', () => { - it('rejects invalid amounts before calling the API', async () => { - const ctx = context(AccountSpendingLimitSet, { args: { dollars: '10000.01' }, flags: mutationFlags }) - await expect(AccountSpendingLimitSet.prototype.run.call(ctx as any)).rejects.toThrow(InvalidInputError) - expect(api.spendingLimit.get).not.toHaveBeenCalled() - }) - - it('asks for confirmation in agent mode, previewing the change and the warning', async () => { - const ctx = context(AccountSpendingLimitSet, { args: { dollars: '12.50' }, flags: mutationFlags }) - await expect(AccountSpendingLimitSet.prototype.run.call(ctx as any)).rejects.toThrow('EXIT_3') - const preview = JSON.parse(ctx.logged[0]) - expect(preview).toMatchObject({ status: 'confirmation_required', command: 'account spending-limit set' }) - expect(preview.changes[0]).toBe('Change the spending limit from $50.00 to $12.50') - expect(preview.changes[1]).toMatch(/stop running at once/) - expect(preview.confirmCommand).toBe('npx checkly account spending-limit set 12.50 --force') - expect(api.spendingLimit.update).not.toHaveBeenCalled() - }) - - it('--dry-run previews and exits 0', async () => { - const ctx = context(AccountSpendingLimitSet, { - args: { dollars: '20' }, flags: { ...mutationFlags, 'dry-run': true }, - }) - await expect(AccountSpendingLimitSet.prototype.run.call(ctx as any)).rejects.toThrow('EXIT_0') - expect(JSON.parse(ctx.logged[0]).status).toBe('dry_run') - expect(api.spendingLimit.update).not.toHaveBeenCalled() - }) - - it('sends integer cents with --force and prints the response for --output json', async () => { - const ctx = context(AccountSpendingLimitSet, { - args: { dollars: '0.29' }, flags: { ...mutationFlags, output: 'json', force: true }, - }) - await AccountSpendingLimitSet.prototype.run.call(ctx as any) - expect(api.spendingLimit.update).toHaveBeenCalledExactlyOnceWith(29) - expect(JSON.parse(ctx.logged[0])).toEqual({ spendingCapCents: 29 }) - }) -}) - -describe('account spending-limit remove', () => { - it('sends null with --force', async () => { - const ctx = context(AccountSpendingLimitRemove, { flags: { ...mutationFlags, force: true } }) - await AccountSpendingLimitRemove.prototype.run.call(ctx as any) - expect(api.spendingLimit.update).toHaveBeenCalledExactlyOnceWith(null) - expect(ctx.style.shortSuccess).toHaveBeenCalledWith('Spending limit removed. Overage is no longer capped.') - }) - - it('previews removing the current limit', async () => { - const ctx = context(AccountSpendingLimitRemove, { flags: mutationFlags }) - await expect(AccountSpendingLimitRemove.prototype.run.call(ctx as any)).rejects.toThrow('EXIT_3') - expect(JSON.parse(ctx.logged[0]).changes).toEqual(['Remove the spending limit of $50.00']) - }) -}) diff --git a/packages/cli/src/commands/__tests__/command-metadata.spec.ts b/packages/cli/src/commands/__tests__/command-metadata.spec.ts index 19b130866..4bc5348aa 100644 --- a/packages/cli/src/commands/__tests__/command-metadata.spec.ts +++ b/packages/cli/src/commands/__tests__/command-metadata.spec.ts @@ -52,9 +52,9 @@ import UsageTermCommand from '../account/usage/term.js' import UsageProjectionsCommand from '../account/usage/projections.js' import UsageSummaryCommand from '../account/usage/summary.js' import UsageSeriesCommand from '../account/usage/series.js' -import AccountSpendingLimit from '../account/spending-limit.js' -import AccountSpendingLimitSet from '../account/spending-limit/set.js' -import AccountSpendingLimitRemove from '../account/spending-limit/remove.js' +import AccountSpendingCap from '../account/spending-cap.js' +import AccountSpendingCapSet from '../account/spending-cap/set.js' +import AccountSpendingCapRemove from '../account/spending-cap/remove.js' const commands: Array<[string, typeof BaseCommand]> = [ ['api', Api], @@ -80,9 +80,9 @@ const commands: Array<[string, typeof BaseCommand]> = [ ['account usage projections', UsageProjectionsCommand], ['account usage summary', UsageSummaryCommand], ['account usage series', UsageSeriesCommand], - ['account spending-limit', AccountSpendingLimit], - ['account spending-limit set', AccountSpendingLimitSet], - ['account spending-limit remove', AccountSpendingLimitRemove], + ['account spending-cap', AccountSpendingCap], + ['account spending-cap set', AccountSpendingCapSet], + ['account spending-cap remove', AccountSpendingCapRemove], ['incidents list', IncidentsList], ['incidents create', IncidentsCreate], ['incidents update', IncidentsUpdate], diff --git a/packages/cli/src/commands/account/spending-limit.ts b/packages/cli/src/commands/account/spending-cap.ts similarity index 56% rename from packages/cli/src/commands/account/spending-limit.ts rename to packages/cli/src/commands/account/spending-cap.ts index cd9af1d1d..f39e59881 100644 --- a/packages/cli/src/commands/account/spending-limit.ts +++ b/packages/cli/src/commands/account/spending-cap.ts @@ -1,35 +1,35 @@ import { AuthCommand } from '../authCommand.js' import { outputFlag } from '../../helpers/flags.js' import { exitCodeFor } from '../../helpers/invalid-input-error.js' -import { describeSpendingLimitError } from '../../helpers/spending-limit.js' +import { describeSpendingCapError } from '../../helpers/spending-cap.js' import * as api from '../../rest/api.js' import type { OutputFormat } from '../../formatters/render.js' -import { formatSpendingLimit } from '../../formatters/spending-limit.js' +import { formatSpendingCap } from '../../formatters/spending-cap.js' -export default class AccountSpendingLimit extends AuthCommand { +export default class AccountSpendingCap extends AuthCommand { static hidden = false static readOnly = true static destructive = false static idempotent = true - static description = 'Show the overage spending limit, the overage spent so far, and whether checks are stopped.' + static description = 'Show the overage spending cap, the overage spent so far, and whether checks are stopped.' static flags = { output: outputFlag({ default: 'detail' }), } async run (): Promise { - const { flags } = await this.parse(AccountSpendingLimit) + const { flags } = await this.parse(AccountSpendingCap) this.style.outputFormat = flags.output try { - const { data } = await api.spendingLimit.get() + const { data } = await api.spendingCap.get() if (flags.output === 'json') { this.log(JSON.stringify(data, null, 2)) return } const fmt: OutputFormat = flags.output === 'md' ? 'md' : 'terminal' - this.log(formatSpendingLimit(data, fmt)) + this.log(formatSpendingCap(data, fmt)) } catch (err: unknown) { - this.style.longError('Failed to load the spending limit.', describeSpendingLimitError(err, 'billing:read')) + this.style.longError('Failed to load the spending cap.', describeSpendingCapError(err, 'billing:read')) process.exitCode = exitCodeFor(err) } } diff --git a/packages/cli/src/commands/account/spending-cap/remove.ts b/packages/cli/src/commands/account/spending-cap/remove.ts new file mode 100644 index 000000000..1252d1fe0 --- /dev/null +++ b/packages/cli/src/commands/account/spending-cap/remove.ts @@ -0,0 +1,57 @@ +import { AuthCommand } from '../../authCommand.js' +import { dryRunFlag, forceFlag, outputFlag } from '../../../helpers/flags.js' +import { exitCodeFor } from '../../../helpers/invalid-input-error.js' +import { describeSpendingCapError, spendingCapChanges } from '../../../helpers/spending-cap.js' +import * as api from '../../../rest/api.js' + +export default class AccountSpendingCapRemove extends AuthCommand { + static hidden = false + static readOnly = false + static destructive = true + static idempotent = true + static description = 'Remove the overage spending cap, so overage is no longer capped.' + + static flags = { + 'output': outputFlag({ default: 'detail' }), + 'force': forceFlag(), + 'dry-run': dryRunFlag(), + } + + async run (): Promise { + const { flags } = await this.parse(AccountSpendingCapRemove) + this.style.outputFormat = flags.output + + let current + try { + ({ data: current } = await api.spendingCap.get()) + } catch (err: unknown) { + this.style.longError('Failed to load the spending cap.', describeSpendingCapError(err, 'billing:read')) + process.exitCode = exitCodeFor(err) + return + } + + await this.confirmOrAbort({ + command: 'account spending-cap remove', + description: 'Remove the spending cap', + changes: spendingCapChanges(current, null), + flags, + classification: { + readOnly: AccountSpendingCapRemove.readOnly, + destructive: AccountSpendingCapRemove.destructive, + idempotent: AccountSpendingCapRemove.idempotent, + }, + }, { force: flags.force, dryRun: flags['dry-run'] }) + + try { + const { data } = await api.spendingCap.update(null) + if (flags.output === 'json') { + this.log(JSON.stringify(data, null, 2)) + return + } + this.style.shortSuccess('Spending cap removed. Overage is no longer capped.') + } catch (err: unknown) { + this.style.longError('Failed to remove the spending cap.', describeSpendingCapError(err, 'billing:update')) + process.exitCode = exitCodeFor(err) + } + } +} diff --git a/packages/cli/src/commands/account/spending-cap/set.ts b/packages/cli/src/commands/account/spending-cap/set.ts new file mode 100644 index 000000000..0a72fc4a3 --- /dev/null +++ b/packages/cli/src/commands/account/spending-cap/set.ts @@ -0,0 +1,73 @@ +import { Args } from '@oclif/core' +import { AuthCommand } from '../../authCommand.js' +import { dryRunFlag, forceFlag, outputFlag } from '../../../helpers/flags.js' +import { exitCodeFor } from '../../../helpers/invalid-input-error.js' +import { + describeSpendingCapError, + MAX_SPENDING_CAP_DOLLARS, + parseDollarsToCents, + spendingCapChanges, +} from '../../../helpers/spending-cap.js' +import * as api from '../../../rest/api.js' +import { formatDollars } from '../../../formatters/spending-cap.js' + +export default class AccountSpendingCapSet extends AuthCommand { + static hidden = false + static readOnly = false + static destructive = false + static idempotent = true + static description = 'Set or change the overage spending cap. Checks stop running once overage reaches it.' + + static args = { + dollars: Args.string({ + required: true, + description: `The cap in US dollars, e.g. 50 or 12.50 (0 to ${MAX_SPENDING_CAP_DOLLARS}).`, + }), + } + + static flags = { + 'output': outputFlag({ default: 'detail' }), + 'force': forceFlag(), + 'dry-run': dryRunFlag(), + } + + async run (): Promise { + const { args, flags } = await this.parse(AccountSpendingCapSet) + this.style.outputFormat = flags.output + const capCents = parseDollarsToCents(args.dollars) + + let current + try { + ({ data: current } = await api.spendingCap.get()) + } catch (err: unknown) { + this.style.longError('Failed to load the spending cap.', describeSpendingCapError(err, 'billing:read')) + process.exitCode = exitCodeFor(err) + return + } + + await this.confirmOrAbort({ + command: 'account spending-cap set', + description: 'Set the spending cap', + changes: spendingCapChanges(current, capCents), + flags, + args: { dollars: args.dollars }, + classification: { + readOnly: AccountSpendingCapSet.readOnly, + destructive: AccountSpendingCapSet.destructive, + idempotent: AccountSpendingCapSet.idempotent, + }, + }, { force: flags.force, dryRun: flags['dry-run'] }) + + try { + const { data } = await api.spendingCap.update(capCents) + if (flags.output === 'json') { + this.log(JSON.stringify(data, null, 2)) + return + } + this.style.shortSuccess(`Spending cap set to ${formatDollars(data.spendingCapCents ?? capCents)}.`) + } catch (err: unknown) { + this.style.longError('Failed to set the spending cap.', describeSpendingCapError(err, 'billing:update')) + process.exitCode = exitCodeFor(err) + } + } +} diff --git a/packages/cli/src/commands/account/spending-limit/remove.ts b/packages/cli/src/commands/account/spending-limit/remove.ts deleted file mode 100644 index 4fd4454c6..000000000 --- a/packages/cli/src/commands/account/spending-limit/remove.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { AuthCommand } from '../../authCommand.js' -import { dryRunFlag, forceFlag, outputFlag } from '../../../helpers/flags.js' -import { exitCodeFor } from '../../../helpers/invalid-input-error.js' -import { describeSpendingLimitError, spendingLimitChanges } from '../../../helpers/spending-limit.js' -import * as api from '../../../rest/api.js' - -export default class AccountSpendingLimitRemove extends AuthCommand { - static hidden = false - static readOnly = false - static destructive = true - static idempotent = true - static description = 'Remove the overage spending limit, so overage is no longer capped.' - - static flags = { - 'output': outputFlag({ default: 'detail' }), - 'force': forceFlag(), - 'dry-run': dryRunFlag(), - } - - async run (): Promise { - const { flags } = await this.parse(AccountSpendingLimitRemove) - this.style.outputFormat = flags.output - - let current - try { - ({ data: current } = await api.spendingLimit.get()) - } catch (err: unknown) { - this.style.longError('Failed to load the spending limit.', describeSpendingLimitError(err, 'billing:read')) - process.exitCode = exitCodeFor(err) - return - } - - await this.confirmOrAbort({ - command: 'account spending-limit remove', - description: 'Remove the spending limit', - changes: spendingLimitChanges(current, null), - flags, - classification: { - readOnly: AccountSpendingLimitRemove.readOnly, - destructive: AccountSpendingLimitRemove.destructive, - idempotent: AccountSpendingLimitRemove.idempotent, - }, - }, { force: flags.force, dryRun: flags['dry-run'] }) - - try { - const { data } = await api.spendingLimit.update(null) - if (flags.output === 'json') { - this.log(JSON.stringify(data, null, 2)) - return - } - this.style.shortSuccess('Spending limit removed. Overage is no longer capped.') - } catch (err: unknown) { - this.style.longError('Failed to remove the spending limit.', describeSpendingLimitError(err, 'billing:update')) - process.exitCode = exitCodeFor(err) - } - } -} diff --git a/packages/cli/src/commands/account/spending-limit/set.ts b/packages/cli/src/commands/account/spending-limit/set.ts deleted file mode 100644 index e7f6462f8..000000000 --- a/packages/cli/src/commands/account/spending-limit/set.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { Args } from '@oclif/core' -import { AuthCommand } from '../../authCommand.js' -import { dryRunFlag, forceFlag, outputFlag } from '../../../helpers/flags.js' -import { exitCodeFor } from '../../../helpers/invalid-input-error.js' -import { - describeSpendingLimitError, - MAX_SPENDING_LIMIT_DOLLARS, - parseDollarsToCents, - spendingLimitChanges, -} from '../../../helpers/spending-limit.js' -import * as api from '../../../rest/api.js' -import { formatDollars } from '../../../formatters/spending-limit.js' - -export default class AccountSpendingLimitSet extends AuthCommand { - static hidden = false - static readOnly = false - static destructive = false - static idempotent = true - static description = 'Set or change the overage spending limit. Checks stop running once overage reaches it.' - - static args = { - dollars: Args.string({ - required: true, - description: `The limit in US dollars, e.g. 50 or 12.50 (0 to ${MAX_SPENDING_LIMIT_DOLLARS}).`, - }), - } - - static flags = { - 'output': outputFlag({ default: 'detail' }), - 'force': forceFlag(), - 'dry-run': dryRunFlag(), - } - - async run (): Promise { - const { args, flags } = await this.parse(AccountSpendingLimitSet) - this.style.outputFormat = flags.output - const capCents = parseDollarsToCents(args.dollars) - - let current - try { - ({ data: current } = await api.spendingLimit.get()) - } catch (err: unknown) { - this.style.longError('Failed to load the spending limit.', describeSpendingLimitError(err, 'billing:read')) - process.exitCode = exitCodeFor(err) - return - } - - await this.confirmOrAbort({ - command: 'account spending-limit set', - description: 'Set the spending limit', - changes: spendingLimitChanges(current, capCents), - flags, - args: { dollars: args.dollars }, - classification: { - readOnly: AccountSpendingLimitSet.readOnly, - destructive: AccountSpendingLimitSet.destructive, - idempotent: AccountSpendingLimitSet.idempotent, - }, - }, { force: flags.force, dryRun: flags['dry-run'] }) - - try { - const { data } = await api.spendingLimit.update(capCents) - if (flags.output === 'json') { - this.log(JSON.stringify(data, null, 2)) - return - } - this.style.shortSuccess(`Spending limit set to ${formatDollars(data.spendingCapCents ?? capCents)}.`) - } catch (err: unknown) { - this.style.longError('Failed to set the spending limit.', describeSpendingLimitError(err, 'billing:update')) - process.exitCode = exitCodeFor(err) - } - } -} diff --git a/packages/cli/src/formatters/__tests__/spending-limit.spec.ts b/packages/cli/src/formatters/__tests__/spending-cap.spec.ts similarity index 59% rename from packages/cli/src/formatters/__tests__/spending-limit.spec.ts rename to packages/cli/src/formatters/__tests__/spending-cap.spec.ts index 688c3cf4e..ff7f876b8 100644 --- a/packages/cli/src/formatters/__tests__/spending-limit.spec.ts +++ b/packages/cli/src/formatters/__tests__/spending-cap.spec.ts @@ -1,9 +1,9 @@ import { describe, expect, it } from 'vitest' import { stripAnsi } from '../render.js' -import { formatDollars, formatSpendingLimit } from '../spending-limit.js' -import type { SpendingLimit } from '../../rest/spending-limit.js' +import { formatDollars, formatSpendingCap } from '../spending-cap.js' +import type { SpendingCap } from '../../rest/spending-cap.js' -const closeToLimit: SpendingLimit = { +const closeToLimit: SpendingCap = { spendingCapCents: 3000, standing: { measuredAt: '2099-11-15T00:00:00.000Z', @@ -24,38 +24,38 @@ describe('formatDollars', () => { }) }) -describe('formatSpendingLimit', () => { - it('shows the limit, overage, status and measurement time', () => { - const out = stripAnsi(formatSpendingLimit(closeToLimit, 'terminal')) - expect(out).toMatch(/Spending limit:\s+\$30\.00/) +describe('formatSpendingCap', () => { + it('shows the cap, overage, status and measurement time', () => { + const out = stripAnsi(formatSpendingCap(closeToLimit, 'terminal')) + expect(out).toMatch(/Spending cap:\s+\$30\.00/) expect(out).toMatch(/Overage so far:\s+\$18\.06/) - expect(out).toMatch(/Status:\s+Close to the limit \(from \$24\.00\)/) + expect(out).toMatch(/Status:\s+Close to the cap \(from \$24\.00\)/) expect(out).toMatch(/Checks stopped:\s+No/) expect(out).toMatch(/Measured at:\s+2099-11-15 00:00:00 UTC/) }) - it('says checks are stopped when the limit is reached', () => { - const reached: SpendingLimit = { + it('says checks are stopped when the cap is reached', () => { + const reached: SpendingCap = { ...closeToLimit, standing: { ...closeToLimit.standing!, limit: { capCents: 3000, state: 'REACHED', closeAtCents: 2400 } }, } - expect(stripAnsi(formatSpendingLimit(reached, 'terminal'))).toMatch(/Checks stopped:\s+Yes/) + expect(stripAnsi(formatSpendingCap(reached, 'terminal'))).toMatch(/Checks stopped:\s+Yes/) }) it('never shows $0 overage when nothing is measured', () => { - const out = formatSpendingLimit({ spendingCapCents: null, standing: null }, 'md') - expect(out).toContain('| Spending limit | No limit |') + const out = formatSpendingCap({ spendingCapCents: null, standing: null }, 'md') + expect(out).toContain('| Spending cap | No cap |') expect(out).toContain('| Overage so far | Not measured') expect(out).not.toContain('$0') expect(out).not.toContain('Checks stopped') }) - it('labels a $0 limit and omits the status without a limit', () => { - const out = formatSpendingLimit({ + it('labels a $0 cap and omits the status without a cap', () => { + const out = formatSpendingCap({ spendingCapCents: 0, standing: { ...closeToLimit.standing!, overageCents: 0, limit: null }, }, 'md') - expect(out).toContain('| Spending limit | $0.00 (no overage allowed) |') + expect(out).toContain('| Spending cap | $0.00 (no overage allowed) |') expect(out).toContain('| Overage so far | $0.00 |') expect(out).not.toContain('| Status |') }) diff --git a/packages/cli/src/formatters/spending-limit.ts b/packages/cli/src/formatters/spending-cap.ts similarity index 73% rename from packages/cli/src/formatters/spending-limit.ts rename to packages/cli/src/formatters/spending-cap.ts index 92f545d0c..2e732eabf 100644 --- a/packages/cli/src/formatters/spending-limit.ts +++ b/packages/cli/src/formatters/spending-cap.ts @@ -1,5 +1,5 @@ import chalk from 'chalk' -import type { SpendingLimit, SpendingLimitState } from '../rest/spending-limit.js' +import type { SpendingCap, SpendingCapState } from '../rest/spending-cap.js' import { type DetailField, type OutputFormat, formatDate, renderDetailFields } from './render.js' const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }) @@ -9,21 +9,21 @@ export function formatDollars (cents: number): string { return usd.format(cents / 100) } -const STATE_LABELS: Record = { - UNDER: 'Under the limit', - CLOSE: 'Close to the limit', - REACHED: 'Limit reached', +const STATE_LABELS: Record = { + UNDER: 'Under the cap', + CLOSE: 'Close to the cap', + REACHED: 'Cap reached', } function color (format: OutputFormat, paint: (s: string) => string, value: string) { return format === 'terminal' ? paint(value) : value } -const fields: DetailField[] = [ +const fields: DetailField[] = [ { - label: 'Spending limit', + label: 'Spending cap', value: ({ spendingCapCents: cap }) => { - if (cap === null) return 'No limit' + if (cap === null) return 'No cap' return cap === 0 ? `${formatDollars(0)} (no overage allowed)` : formatDollars(cap) }, }, @@ -50,7 +50,7 @@ const fields: DetailField[] = [ value: ({ standing }, format) => { if (!standing) return null return standing.limit?.state === 'REACHED' - ? color(format, chalk.red, 'Yes, the spending limit is reached') + ? color(format, chalk.red, 'Yes, the spending cap is reached') : 'No' }, }, @@ -60,6 +60,6 @@ const fields: DetailField[] = [ }, ] -export function formatSpendingLimit (data: SpendingLimit, format: OutputFormat): string { - return renderDetailFields('Spending limit', fields, data, format) +export function formatSpendingCap (data: SpendingCap, format: OutputFormat): string { + return renderDetailFields('Spending cap', fields, data, format) } diff --git a/packages/cli/src/helpers/__tests__/spending-cap.spec.ts b/packages/cli/src/helpers/__tests__/spending-cap.spec.ts new file mode 100644 index 000000000..5c538b469 --- /dev/null +++ b/packages/cli/src/helpers/__tests__/spending-cap.spec.ts @@ -0,0 +1,65 @@ +import { describe, expect, it } from 'vitest' +import { InvalidInputError } from '../invalid-input-error.js' +import { describeSpendingCapError, parseDollarsToCents, spendingCapChanges } from '../spending-cap.js' +import { ConflictError, ForbiddenError, ACCOUNT_NOT_ACCESSIBLE, UnauthorizedError } from '../../rest/errors.js' +import type { SpendingCap } from '../../rest/spending-cap.js' + +describe('parseDollarsToCents', () => { + it.each([ + ['50', 5000], ['12.5', 1250], ['12.50', 1250], ['0', 0], ['0.01', 1], + ['0.29', 29], ['1.15', 115], ['10000', 1000000], ['10000.00', 1000000], [' 7 ', 700], + ])('%s → %i cents', (input, cents) => { + expect(parseDollarsToCents(input)).toBe(cents) + }) + + it.each(['-5', '10000.01', '20000', '1.234', 'abc', '', '1e3', '$5', '.5', '5.', 'NaN', 'Infinity'])( + 'rejects %j as invalid input', input => { + expect(() => parseDollarsToCents(input)).toThrow(InvalidInputError) + }) +}) + +const standing = (overageCents: number): SpendingCap['standing'] => ({ + measuredAt: '2099-11-15T00:00:00.000Z', pools: {}, overageCents, limit: null, +}) + +describe('spendingCapChanges', () => { + it('describes setting, changing and removing', () => { + expect(spendingCapChanges({ spendingCapCents: null, standing: null }, 2000)) + .toEqual(['Set the spending cap to $20.00']) + expect(spendingCapChanges({ spendingCapCents: 5000, standing: standing(0) }, 2000)) + .toEqual(['Change the spending cap from $50.00 to $20.00']) + expect(spendingCapChanges({ spendingCapCents: 5000, standing: null }, null)) + .toEqual(['Remove the spending cap of $50.00']) + expect(spendingCapChanges({ spendingCapCents: null, standing: null }, null)) + .toEqual(['Remove the spending cap (none is set)']) + }) + + it('warns when the new cap is at or below the overage so far', () => { + const changes = spendingCapChanges({ spendingCapCents: 5000, standing: standing(1806.25) }, 1800) + expect(changes[1]).toMatch(/overage so far \(\$18\.06\) is at or above the new cap.*stop running at once/) + expect(spendingCapChanges({ spendingCapCents: 5000, standing: standing(1806.25) }, 1807)).toHaveLength(1) + }) + + it('warns about a $0 cap', () => { + expect(spendingCapChanges({ spendingCapCents: 5000, standing: null }, 0)[1]) + .toMatch(/\$0\.00 cap allows no overage/) + }) +}) + +describe('describeSpendingCapError', () => { + it('maps 409, 403 and 401 to clear messages', () => { + expect(describeSpendingCapError(new UnauthorizedError({ statusCode: 401, error: 'Unauthorized', message: 'x' }), 'billing:read')) + .toMatch(/legacy account API keys are not accepted/) + expect(describeSpendingCapError(new ConflictError({ statusCode: 409, error: 'Conflict', message: 'x' }), 'billing:update')) + .toMatch(/plan cannot have a spending cap/) + expect(describeSpendingCapError(new ForbiddenError({ statusCode: 403, error: 'Forbidden', message: 'x' }), 'billing:update')) + .toMatch(/billing:update permission/) + }) + + it('passes other errors through', () => { + const notAccessible = new ForbiddenError({ + statusCode: 403, error: 'Forbidden', message: 'x', errorCode: ACCOUNT_NOT_ACCESSIBLE, + }) + expect(describeSpendingCapError(notAccessible, 'billing:read')).toBe(notAccessible) + }) +}) diff --git a/packages/cli/src/helpers/__tests__/spending-limit.spec.ts b/packages/cli/src/helpers/__tests__/spending-limit.spec.ts deleted file mode 100644 index 45bd44fd3..000000000 --- a/packages/cli/src/helpers/__tests__/spending-limit.spec.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { InvalidInputError } from '../invalid-input-error.js' -import { describeSpendingLimitError, parseDollarsToCents, spendingLimitChanges } from '../spending-limit.js' -import { ConflictError, ForbiddenError, ACCOUNT_NOT_ACCESSIBLE } from '../../rest/errors.js' -import type { SpendingLimit } from '../../rest/spending-limit.js' - -describe('parseDollarsToCents', () => { - it.each([ - ['50', 5000], ['12.5', 1250], ['12.50', 1250], ['0', 0], ['0.01', 1], - ['0.29', 29], ['1.15', 115], ['10000', 1000000], ['10000.00', 1000000], [' 7 ', 700], - ])('%s → %i cents', (input, cents) => { - expect(parseDollarsToCents(input)).toBe(cents) - }) - - it.each(['-5', '10000.01', '20000', '1.234', 'abc', '', '1e3', '$5', '.5', '5.', 'NaN', 'Infinity'])( - 'rejects %j as invalid input', input => { - expect(() => parseDollarsToCents(input)).toThrow(InvalidInputError) - }) -}) - -const standing = (overageCents: number): SpendingLimit['standing'] => ({ - measuredAt: '2099-11-15T00:00:00.000Z', pools: {}, overageCents, limit: null, -}) - -describe('spendingLimitChanges', () => { - it('describes setting, changing and removing', () => { - expect(spendingLimitChanges({ spendingCapCents: null, standing: null }, 2000)) - .toEqual(['Set the spending limit to $20.00']) - expect(spendingLimitChanges({ spendingCapCents: 5000, standing: standing(0) }, 2000)) - .toEqual(['Change the spending limit from $50.00 to $20.00']) - expect(spendingLimitChanges({ spendingCapCents: 5000, standing: null }, null)) - .toEqual(['Remove the spending limit of $50.00']) - expect(spendingLimitChanges({ spendingCapCents: null, standing: null }, null)) - .toEqual(['Remove the spending limit (none is set)']) - }) - - it('warns when the new limit is at or below the overage so far', () => { - const changes = spendingLimitChanges({ spendingCapCents: 5000, standing: standing(1806.25) }, 1800) - expect(changes[1]).toMatch(/overage so far \(\$18\.06\) is at or above the new limit.*stop running at once/) - expect(spendingLimitChanges({ spendingCapCents: 5000, standing: standing(1806.25) }, 1807)).toHaveLength(1) - }) - - it('warns about a $0 limit', () => { - expect(spendingLimitChanges({ spendingCapCents: 5000, standing: null }, 0)[1]) - .toMatch(/\$0\.00 limit allows no overage/) - }) -}) - -describe('describeSpendingLimitError', () => { - it('maps 409 and 403 to clear messages', () => { - expect(describeSpendingLimitError(new ConflictError({ statusCode: 409, error: 'Conflict', message: 'x' }), 'billing:update')) - .toMatch(/plan cannot have a spending limit/) - expect(describeSpendingLimitError(new ForbiddenError({ statusCode: 403, error: 'Forbidden', message: 'x' }), 'billing:update')) - .toMatch(/billing:update permission/) - }) - - it('passes other errors through', () => { - const notAccessible = new ForbiddenError({ - statusCode: 403, error: 'Forbidden', message: 'x', errorCode: ACCOUNT_NOT_ACCESSIBLE, - }) - expect(describeSpendingLimitError(notAccessible, 'billing:read')).toBe(notAccessible) - }) -}) diff --git a/packages/cli/src/helpers/spending-cap.ts b/packages/cli/src/helpers/spending-cap.ts new file mode 100644 index 000000000..87f97a544 --- /dev/null +++ b/packages/cli/src/helpers/spending-cap.ts @@ -0,0 +1,61 @@ +import { InvalidInputError } from './invalid-input-error.js' +import { ConflictError, ForbiddenError, isAccountNotAccessible, UnauthorizedError } from '../rest/errors.js' +import { formatDollars } from '../formatters/spending-cap.js' +import type { SpendingCap } from '../rest/spending-cap.js' + +export const MAX_SPENDING_CAP_DOLLARS = 10000 + +/** + * A dollar amount (`50`, `12.5`, `12.50`) as integer cents, from the digits so + * no float rounding creeps in. At most 2 decimals, from 0 to 10000. + */ +export function parseDollarsToCents (input: string): number { + const match = /^(\d+)(?:\.(\d{1,2}))?$/.exec(input.trim()) + if (!match) { + throw new InvalidInputError( + `Invalid amount "${input}". Use a non-negative dollar amount with at most 2 decimals, e.g. 50 or 12.50.`) + } + const cents = Number(match[1]) * 100 + Number((match[2] ?? '').padEnd(2, '0')) + if (cents > MAX_SPENDING_CAP_DOLLARS * 100) { + throw new InvalidInputError( + `Invalid amount "${input}". The spending cap can be at most ${formatDollars(MAX_SPENDING_CAP_DOLLARS * 100)}.`) + } + return cents +} + +/** The preview lines for changing the cap from `current` to `capCents` (`null` removes it). */ +export function spendingCapChanges (current: SpendingCap, capCents: number | null): string[] { + const from = current.spendingCapCents + const changes = [ + capCents === null + ? from === null ? 'Remove the spending cap (none is set)' : `Remove the spending cap of ${formatDollars(from)}` + : from === null + ? `Set the spending cap to ${formatDollars(capCents)}` + : `Change the spending cap from ${formatDollars(from)} to ${formatDollars(capCents)}`, + ] + const overage = current.standing?.overageCents ?? 0 + if (capCents !== null && overage > 0 && capCents <= overage) { + changes.push(`Warning: overage so far (${formatDollars(overage)}) is at or above the new cap, ` + + 'so checks stop running at once') + } else if (capCents === 0) { + changes.push('Warning: a $0.00 cap allows no overage, so checks stop running as soon as ' + + 'the included runs are used up') + } + return changes +} + +/** Clear messages for the API's 401, 403 and 409; anything else as it came. */ +export function describeSpendingCapError (err: unknown, permission: 'billing:read' | 'billing:update'): string | Error { + if (err instanceof ConflictError) { + return 'This account\'s plan cannot have a spending cap (for example prepaid or contract plans). ' + + `(${err.message})` + } + if (err instanceof UnauthorizedError) { + return 'The spending cap requires a user or service API key; legacy account API keys are not accepted.' + } + if (err instanceof ForbiddenError && !isAccountNotAccessible(err)) { + return `Not allowed: your role needs the ${permission} permission, and the account must manage its plan ` + + `in Checkly (self-serve billing). Ask an account owner or admin. (${err.message})` + } + return err instanceof Error ? err : String(err) +} diff --git a/packages/cli/src/helpers/spending-limit.ts b/packages/cli/src/helpers/spending-limit.ts deleted file mode 100644 index 756d6574a..000000000 --- a/packages/cli/src/helpers/spending-limit.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { InvalidInputError } from './invalid-input-error.js' -import { ConflictError, ForbiddenError, isAccountNotAccessible } from '../rest/errors.js' -import { formatDollars } from '../formatters/spending-limit.js' -import type { SpendingLimit } from '../rest/spending-limit.js' - -export const MAX_SPENDING_LIMIT_DOLLARS = 10000 - -/** - * A dollar amount (`50`, `12.5`, `12.50`) as integer cents, from the digits so - * no float rounding creeps in. At most 2 decimals, from 0 to 10000. - */ -export function parseDollarsToCents (input: string): number { - const match = /^(\d+)(?:\.(\d{1,2}))?$/.exec(input.trim()) - if (!match) { - throw new InvalidInputError( - `Invalid amount "${input}". Use a non-negative dollar amount with at most 2 decimals, e.g. 50 or 12.50.`) - } - const cents = Number(match[1]) * 100 + Number((match[2] ?? '').padEnd(2, '0')) - if (cents > MAX_SPENDING_LIMIT_DOLLARS * 100) { - throw new InvalidInputError( - `Invalid amount "${input}". The spending limit can be at most ${formatDollars(MAX_SPENDING_LIMIT_DOLLARS * 100)}.`) - } - return cents -} - -/** The preview lines for changing the limit from `current` to `capCents` (`null` removes it). */ -export function spendingLimitChanges (current: SpendingLimit, capCents: number | null): string[] { - const from = current.spendingCapCents - const changes = [ - capCents === null - ? from === null ? 'Remove the spending limit (none is set)' : `Remove the spending limit of ${formatDollars(from)}` - : from === null - ? `Set the spending limit to ${formatDollars(capCents)}` - : `Change the spending limit from ${formatDollars(from)} to ${formatDollars(capCents)}`, - ] - const overage = current.standing?.overageCents ?? 0 - if (capCents !== null && overage > 0 && capCents <= overage) { - changes.push(`Warning: overage so far (${formatDollars(overage)}) is at or above the new limit, ` - + 'so checks stop running at once') - } else if (capCents === 0) { - changes.push('Warning: a $0.00 limit allows no overage, so checks stop running as soon as ' - + 'the included runs are used up') - } - return changes -} - -/** Clear messages for the API's 403 and 409; anything else as it came. */ -export function describeSpendingLimitError (err: unknown, permission: 'billing:read' | 'billing:update'): string | Error { - if (err instanceof ConflictError) { - return 'This account\'s plan cannot have a spending limit (for example prepaid or contract plans). ' - + `(${err.message})` - } - if (err instanceof ForbiddenError && !isAccountNotAccessible(err)) { - return `Not allowed: your role needs the ${permission} permission, and the account must manage its plan ` - + `in Checkly (self-serve billing). Ask an account owner or admin. (${err.message})` - } - return err instanceof Error ? err : String(err) -} diff --git a/packages/cli/src/rest/api.ts b/packages/cli/src/rest/api.ts index c2f518b5d..06e5a4854 100644 --- a/packages/cli/src/rest/api.ts +++ b/packages/cli/src/rest/api.ts @@ -32,7 +32,7 @@ import AlertNotifications from './alert-notifications.js' import Rca from './rca.js' import Cancel from './cancel.js' import Usage from './usage.js' -import SpendingLimits from './spending-limit.js' +import SpendingCaps from './spending-cap.js' import { ForbiddenError, handleErrorResponse, NotFoundError, UnauthorizedError } from './errors.js' import { createRetryInterceptor } from './retry.js' import { detectCliMode, detectOperator } from '../helpers/cli-mode.js' @@ -200,4 +200,4 @@ export const alertNotifications = new AlertNotifications(getApi) export const rca = new Rca(getApi) export const cancel = new Cancel(getApi) export const usage = new Usage(getApi) -export const spendingLimit = new SpendingLimits(getApi) +export const spendingCap = new SpendingCaps(getApi) diff --git a/packages/cli/src/rest/spending-cap.ts b/packages/cli/src/rest/spending-cap.ts new file mode 100644 index 000000000..db34adcb1 --- /dev/null +++ b/packages/cli/src/rest/spending-cap.ts @@ -0,0 +1,39 @@ +import { RestResource } from './rest-resource.js' + +export type SpendingCapState = 'UNDER' | 'CLOSE' | 'REACHED' + +export interface SpendingPool { + used: number + included: number + overageRuns: number + overageCents: number +} + +export interface SpendingStanding { + measuredAt: string + pools: Record + /** Not rounded to whole cents. */ + overageCents: number + /** `null` when the account has no cap. */ + limit: { capCents: number, state: SpendingCapState, closeAtCents: number } | null +} + +export interface SpendingCap { + /** `null` = no cap; `0` = no overage allowed. */ + spendingCapCents: number | null + /** `null` when nothing is judged (plan without overage, or runs not measured yet). Not $0 overage. */ + standing: SpendingStanding | null +} + +class SpendingCaps extends RestResource { + get () { + return this.api.get('/v1/billing/spending-cap') + } + + /** `null` removes the cap. */ + update (spendingCapCents: number | null) { + return this.api.put>('/v1/billing/spending-cap', { spendingCapCents }) + } +} + +export default SpendingCaps diff --git a/packages/cli/src/rest/spending-limit.ts b/packages/cli/src/rest/spending-limit.ts deleted file mode 100644 index 90340d55e..000000000 --- a/packages/cli/src/rest/spending-limit.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { RestResource } from './rest-resource.js' - -export type SpendingLimitState = 'UNDER' | 'CLOSE' | 'REACHED' - -export interface SpendingPool { - used: number - included: number - overageRuns: number - overageCents: number -} - -export interface SpendingStanding { - measuredAt: string - pools: Record - /** Not rounded to whole cents. */ - overageCents: number - /** `null` when the account has no limit. */ - limit: { capCents: number, state: SpendingLimitState, closeAtCents: number } | null -} - -export interface SpendingLimit { - /** `null` = no limit; `0` = no overage allowed. */ - spendingCapCents: number | null - /** `null` when nothing is judged (plan without overage, or runs not measured yet). Not $0 overage. */ - standing: SpendingStanding | null -} - -class SpendingLimits extends RestResource { - get () { - return this.api.get('/v1/billing/spending-limit') - } - - /** `null` removes the limit. */ - update (spendingCapCents: number | null) { - return this.api.put>('/v1/billing/spending-limit', { spendingCapCents }) - } -} - -export default SpendingLimits diff --git a/skills/checkly/SKILL.md b/skills/checkly/SKILL.md index f6fdbdc83..cf96fa540 100644 --- a/skills/checkly/SKILL.md +++ b/skills/checkly/SKILL.md @@ -160,4 +160,4 @@ Access check and test-session status, analyze failures, inspect attempts/assets, Open incidents and lead customer communications via status pages. ### `npx checkly skills manage` -Understand your account plan, entitlements, feature limits, members, pending invites, and spending limit. +Understand your account plan, entitlements, feature limits, members, pending invites, and spending cap.