diff --git a/packages/cli/package.json b/packages/cli/package.json index 2329c0be..131960b9 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-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 198d5932..6e0e4288 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-cap', + description: 'Show, set, and remove the overage spending cap (`account spending-cap`)', + }, ] 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 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 00000000..77e68e47 --- /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.md b/packages/cli/src/ai-context/references/manage.md index fc1371b5..b544ca6c 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 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 00000000..59eee6ce --- /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__/command-metadata.spec.ts b/packages/cli/src/commands/__tests__/command-metadata.spec.ts index 821974f6..4bc5348a 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 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], @@ -77,6 +80,9 @@ const commands: Array<[string, typeof BaseCommand]> = [ ['account usage projections', UsageProjectionsCommand], ['account usage summary', UsageSummaryCommand], ['account usage series', UsageSeriesCommand], + ['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-cap.ts b/packages/cli/src/commands/account/spending-cap.ts new file mode 100644 index 00000000..f39e5988 --- /dev/null +++ b/packages/cli/src/commands/account/spending-cap.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 { describeSpendingCapError } from '../../helpers/spending-cap.js' +import * as api from '../../rest/api.js' +import type { OutputFormat } from '../../formatters/render.js' +import { formatSpendingCap } from '../../formatters/spending-cap.js' + +export default class AccountSpendingCap extends AuthCommand { + static hidden = false + static readOnly = true + static destructive = false + static idempotent = true + 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(AccountSpendingCap) + this.style.outputFormat = flags.output + try { + 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(formatSpendingCap(data, fmt)) + } catch (err: unknown) { + 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 00000000..1252d1fe --- /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 00000000..0a72fc4a --- /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/formatters/__tests__/spending-cap.spec.ts b/packages/cli/src/formatters/__tests__/spending-cap.spec.ts new file mode 100644 index 00000000..ff7f876b --- /dev/null +++ b/packages/cli/src/formatters/__tests__/spending-cap.spec.ts @@ -0,0 +1,62 @@ +import { describe, expect, it } from 'vitest' +import { stripAnsi } from '../render.js' +import { formatDollars, formatSpendingCap } from '../spending-cap.js' +import type { SpendingCap } from '../../rest/spending-cap.js' + +const closeToLimit: SpendingCap = { + 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('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 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 cap is reached', () => { + const reached: SpendingCap = { + ...closeToLimit, + standing: { ...closeToLimit.standing!, limit: { capCents: 3000, state: 'REACHED', closeAtCents: 2400 } }, + } + expect(stripAnsi(formatSpendingCap(reached, 'terminal'))).toMatch(/Checks stopped:\s+Yes/) + }) + + it('never shows $0 overage when nothing is measured', () => { + 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 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 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-cap.ts b/packages/cli/src/formatters/spending-cap.ts new file mode 100644 index 00000000..2e732eab --- /dev/null +++ b/packages/cli/src/formatters/spending-cap.ts @@ -0,0 +1,65 @@ +import chalk from 'chalk' +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' }) + +/** 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 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[] = [ + { + label: 'Spending cap', + value: ({ spendingCapCents: cap }) => { + if (cap === null) return 'No cap' + 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 cap is reached') + : 'No' + }, + }, + { + label: 'Measured at', + value: ({ standing }, format) => standing ? formatDate(standing.measuredAt, format) : null, + }, +] + +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 00000000..5c538b46 --- /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/spending-cap.ts b/packages/cli/src/helpers/spending-cap.ts new file mode 100644 index 00000000..87f97a54 --- /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/rest/api.ts b/packages/cli/src/rest/api.ts index 740cb05a..06e5a485 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 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' @@ -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 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 00000000..db34adcb --- /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/skills/checkly/SKILL.md b/skills/checkly/SKILL.md index 93dde83d..cf96fa54 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 cap.