The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
import { afterEach, describe, expect, it } from 'vitest'
import axios from 'axios'
import { BillingApiClient } from './billingApiClient'
// The api/apiClient.test.ts trick: a custom adapter settles every request
// locally, so the wire mapping is exercised without a server. Each test sets
// the JSON the "server" returns and reads back what URL was requested.
let requestedUrl = ''
let requestedUrls: string[] = []
let requestedMethod = ''
let requestedData: unknown
let requestedTimeout: number | undefined
function serve(data: unknown | ((url: string) => unknown)): BillingApiClient {
requestedUrls = []
axios.defaults.adapter = (async (cfg: {
url?: string
baseURL?: string
method?: string
data?: unknown
timeout?: number
}) => {
requestedUrl = `${cfg.baseURL ?? ''}${cfg.url ?? ''}`
requestedUrls.push(requestedUrl)
requestedMethod = cfg.method ?? ''
requestedData = cfg.data
requestedTimeout = cfg.timeout
const responseData = typeof data === 'function' ? data(requestedUrl) : data
return { data: responseData, status: 200, statusText: 'OK', headers: {}, config: cfg }
}) as never
return new BillingApiClient('http://billing.test/api/billing', 'tok')
}
afterEach(() => {
axios.defaults.adapter = undefined as never
})
describe('redeemCoupon', () => {
it.each(['BoXlite20', 'TEAM#2026', 'TEAM?2026', 'TEAM/2026', 'TEAM%2026'])(
'preserves %s as one coupon path segment',
async (couponCode) => {
const api = serve({ message: 'Promotion accepted.' })
expect(await api.redeemCoupon('org-1', couponCode)).toBe('Promotion accepted.')
const request = new URL(requestedUrl)
expect(requestedMethod).toBe('post')
expect(request.search).toBe('')
expect(request.hash).toBe('')
expect(request.pathname.split('/').slice(0, -1).join('/')).toBe('/api/billing/organization/org-1/redeem-coupon')
expect(decodeURIComponent(request.pathname.split('/').at(-1)!)).toBe(couponCode)
},
)
})
describe('getOrganizationPlan', () => {
it('unwraps the plan envelope and turns the cycle bounds into Dates', async () => {
const api = serve({
plan: {
planId: 'pro',
planName: 'Pro',
status: 'active',
cycleFrom: '2026-08-05T00:00:00.000Z',
cycleTo: '2026-09-05T00:00:00.000Z',
includedQuotaCents: 25000,
quotaConsumedCents: 6250,
quotaRemainingCents: 18750,
trial: {
startedAt: '2026-08-05T00:00:00.000Z',
endsAt: '2026-08-12T00:00:00.000Z',
conversionAmountCents: 14900,
currency: 'USD',
conversionState: 'not_attempted',
},
},
})
const plan = await api.getOrganizationPlan('org-1')
expect(plan?.cycleFrom).toEqual(new Date('2026-08-05T00:00:00.000Z'))
expect(plan?.cycleTo).toEqual(new Date('2026-09-05T00:00:00.000Z'))
expect(plan).toMatchObject({
planId: 'pro',
includedQuotaCents: 25000,
quotaConsumedCents: 6250,
quotaRemainingCents: 18750,
})
expect(plan?.trial).toEqual({
startedAt: new Date('2026-08-05T00:00:00.000Z'),
endsAt: new Date('2026-08-12T00:00:00.000Z'),
conversionAmountCents: 14900,
currency: 'USD',
conversionState: 'not_attempted',
})
})
it('hydrates dueAt when the plan is past due', async () => {
const api = serve({
plan: {
planId: 'pro',
planName: 'Pro',
status: 'past_due',
cycleFrom: '2026-08-05T00:00:00.000Z',
cycleTo: '2026-09-05T00:00:00.000Z',
includedQuotaCents: 25000,
quotaConsumedCents: 6250,
quotaRemainingCents: 18750,
dueAt: '2026-08-20T00:00:00.000Z',
amountDueCents: 14900,
},
})
const plan = await api.getOrganizationPlan('org-1')
expect(plan?.dueAt).toEqual(new Date('2026-08-20T00:00:00.000Z'))
})
it('returns null for an organization with no live plan (the {} envelope, not a bare null)', async () => {
const api = serve({})
const plan = await api.getOrganizationPlan('org-1')
expect(plan).toBeNull()
})
})
describe('plan trial eligibility', () => {
it.each([
{ plans: [] },
{
plans: [
{ name: 'Go', eligible: true, durationSeconds: 5400 },
{ name: 'Team', eligible: false, durationSeconds: 0 },
],
},
])('reads the organization offer list in one GET', async ({ plans }) => {
const api = serve({ plans })
expect(await api.getPlanTrialEligibility('org-1')).toEqual(plans)
expect(requestedUrls).toEqual(['http://billing.test/api/billing/organization/org-1/plan/trial-eligibility'])
expect(requestedMethod).toBe('get')
expect(requestedData).toBeUndefined()
})
})
describe('upgradePlan', () => {
it('returns the checkout URL when a first subscribe needs one', async () => {
const api = serve({ url: 'https://checkout.stripe.com/pay/cs_test_123' })
const url = await api.upgradePlan('org-1', 'pro')
expect(url).toBe('https://checkout.stripe.com/pay/cs_test_123')
})
it('returns undefined when an in-place change applies with no redirect', async () => {
const api = serve(undefined)
const url = await api.upgradePlan('org-1', 'max')
expect(url).toBeUndefined()
})
})
describe('withdrawPendingPlan', () => {
it('deletes the queued plan without resubmitting the effective plan', async () => {
const api = serve(undefined)
await api.withdrawPendingPlan('org-1')
expect(requestedMethod).toBe('delete')
expect(requestedUrl).toBe('http://billing.test/api/billing/organization/org-1/plan/pending')
expect(requestedData).toBeUndefined()
})
})
describe('listAllPaymentMethods', () => {
it('walks every page and returns every stored method', async () => {
const firstPageMethod = {
id: 'card-1',
isDefault: true,
paymentProviderType: 'stripe',
providerMethodId: 'pm_1',
details: { brand: 'visa', last4: '4242', expMonth: 8, expYear: 2027 },
}
const secondPageMethod = {
id: 'card-2',
isDefault: false,
paymentProviderType: 'stripe',
providerMethodId: 'pm_2',
details: { brand: 'mastercard', last4: '4444', expMonth: 12, expYear: 2029 },
}
const api = serve((url) =>
url.endsWith('?page=1&perPage=100')
? {
paymentMethods: [firstPageMethod],
meta: { currentPage: 1, totalPages: 2, totalCount: 2, nextPage: 2, prevPage: null },
}
: {
paymentMethods: [secondPageMethod],
meta: { currentPage: 2, totalPages: 2, totalCount: 2, nextPage: null, prevPage: 1 },
},
)
await expect(api.listAllPaymentMethods('org-1')).resolves.toEqual([firstPageMethod, secondPageMethod])
expect(requestedUrls).toEqual([
'http://billing.test/api/billing/organization/org-1/payment-methods?page=1&perPage=100',
'http://billing.test/api/billing/organization/org-1/payment-methods?page=2&perPage=100',
])
})
})
describe('topUpWallet', () => {
it('posts the amount and returns the hosted payment URL', async () => {
const payment = { url: 'https://checkout.stripe.com/pay/cs_top_up' }
const api = serve(payment)
await expect(api.topUpWallet('org-without-card', 10_000)).resolves.toEqual(payment)
expect(requestedMethod).toBe('post')
expect(requestedUrl).toBe('http://billing.test/api/billing/organization/org-without-card/wallet/top-up')
expect(JSON.parse(String(requestedData))).toEqual({ amountCents: 10_000 })
})
})
describe('getUsageFundingSeries', () => {
it('sends granularity and ISO bounds, and maps bucket bounds to Dates', async () => {
const api = serve([
{
from: '2026-08-13T00:00:00.000Z',
to: '2026-08-14T00:00:00.000Z',
quotaCoveredCents: 2985,
fromWalletCents: 15,
},
])
const from = new Date('2026-07-15T00:00:00.000Z')
const to = new Date('2026-08-14T00:00:00.000Z')
const buckets = await api.getUsageFundingSeries('org-1', 'day', from, to)
expect(requestedUrl).toBe(
'http://billing.test/api/billing/organization/org-1/usage/series' +
'?granularity=day&from=2026-07-15T00%3A00%3A00.000Z&to=2026-08-14T00%3A00%3A00.000Z',
)
expect(buckets).toEqual([
{
from: new Date('2026-08-13T00:00:00.000Z'),
to: new Date('2026-08-14T00:00:00.000Z'),
quotaCoveredCents: 2985,
fromWalletCents: 15,
},
])
})
})
describe('PR 829 real-data parity: settlement invoices', () => {
it('keeps only the read surface that current Commerce supports', async () => {
const response = {
items: [
{
id: 'invoice-1',
number: 'INV-000001',
sequentialId: 1,
chargedAt: '2026-08-18T12:00:00.000Z',
totalAmountCents: 1_250,
quotaCoveredCents: 1_000,
voided: false,
},
],
totalItems: 1,
totalPages: 1,
}
const api = serve(response)
// The three fields the billing history needs are absent here on purpose:
// this is the payload a Commerce predating that change still returns, and
// either side may deploy first. The client fills them rather than letting
// the page throw on undefined.toLowerCase() and print NaN.
await expect(api.listInvoices('org-1', 2, 25)).resolves.toEqual({
...response,
items: [{ ...response.items[0], type: 'advance_charges', paymentStatus: 'succeeded', totalPaidCents: 250 }],
})
expect(requestedUrl).toBe('http://billing.test/api/billing/organization/org-1/invoices?page=2&perPage=25')
expect(api).not.toHaveProperty('createInvoicePaymentUrl')
expect(api).not.toHaveProperty('voidInvoice')
})
it('leaves the fields alone once Commerce sends them', async () => {
const api = serve({
items: [
{
id: 'invoice-2',
number: 'BOX-2026-0002',
sequentialId: 2,
type: 'credit',
chargedAt: '2026-09-04T00:00:00.000Z',
totalAmountCents: 5_000,
totalPaidCents: 5_000,
quotaCoveredCents: 0,
paymentStatus: 'pending',
voided: false,
},
],
totalItems: 1,
totalPages: 1,
})
const page = await api.listInvoices('org-1', 1, 25, 'all')
expect(page.items[0].type).toBe('credit')
expect(page.items[0].paymentStatus).toBe('pending')
expect(page.items[0].totalPaidCents).toBe(5_000)
})
it('never defaults a paid amount below zero', async () => {
// Quota covering more than the total should not turn into a negative charge.
const api = serve({
items: [
{
id: 'invoice-3',
number: 'INV-000003',
sequentialId: 3,
chargedAt: '2026-08-18T12:00:00.000Z',
totalAmountCents: 1_000,
quotaCoveredCents: 4_000,
voided: false,
},
],
totalItems: 1,
totalPages: 1,
})
const page = await api.listInvoices('org-1')
expect(page.items[0].totalPaidCents).toBe(0)
})
})
describe('listInvoices type filter', () => {
const creditInvoice = {
id: 'invoice-1',
number: 'BOX-2026-0001',
sequentialId: 1,
type: 'credit',
chargedAt: '2026-09-04T00:00:00.000Z',
totalAmountCents: 5_000,
totalPaidCents: 5_000,
quotaCoveredCents: 0,
paymentStatus: 'succeeded',
voided: false,
}
it('omits the parameter entirely when no filter is given', async () => {
const api = serve({ items: [], totalItems: 0, totalPages: 0 })
await api.listInvoices('org-1')
// Commerce then serves settlement invoices only, which is what every
// caller predating the billing history already expects.
expect(requestedUrl).toBe('http://billing.test/api/billing/organization/org-1/invoices')
})
it("asks for every kind on 'all' so a later one is not silently dropped", async () => {
const api = serve({ items: [creditInvoice], totalItems: 1, totalPages: 1 })
const page = await api.listInvoices('org-1', 1, 50, 'all')
expect(requestedUrl).toBe('http://billing.test/api/billing/organization/org-1/invoices?page=1&perPage=50&type=all')
expect(page.items[0].type).toBe('credit')
expect(page.items[0].paymentStatus).toBe('succeeded')
expect(page.items[0].totalPaidCents).toBe(5_000)
})
it('comma-joins an explicit subset', async () => {
const api = serve({ items: [], totalItems: 0, totalPages: 0 })
await api.listInvoices('org-1', undefined, undefined, ['credit', 'one_off'])
expect(requestedUrl).toBe('http://billing.test/api/billing/organization/org-1/invoices?type=credit%2Cone_off')
})
})
describe('PR 829 real-data parity: wallet transactions', () => {
it('requests a paginated ledger with every transaction axis intact', async () => {
const response = {
items: [
{
id: 'transaction-1',
direction: 'inbound',
kind: 'granted',
status: 'settled',
source: 'interval',
amountCents: 25_000,
name: 'Pro monthly quota',
subscriptionCreditKind: 'cycle',
createdAt: '2026-08-30T00:00:00.000Z',
settledAt: '2026-08-30T00:00:00.000Z',
},
],
totalItems: 1,
totalPages: 1,
}
const api = serve(response)
await expect(api.listWalletTransactions('org-1', 2, 25)).resolves.toEqual(response)
expect(requestedUrl).toBe(
'http://billing.test/api/billing/organization/org-1/wallet/transactions?page=2&perPage=25',
)
})
})
describe('saved card actions', () => {
it('sets the default card through its own path', async () => {
const api = serve(undefined)
await expect(api.setDefaultPaymentMethod('org-1', 'card-2')).resolves.toBeUndefined()
expect(requestedMethod).toBe('post')
expect(requestedUrl).toBe('http://billing.test/api/billing/organization/org-1/payment-methods/card-2/default')
expect(requestedData).toBeUndefined()
})
it('removes a card with DELETE on the card path', async () => {
const api = serve(undefined)
await expect(api.removePaymentMethod('org-1', 'card-2')).resolves.toBeUndefined()
expect(requestedMethod).toBe('delete')
expect(requestedUrl).toBe('http://billing.test/api/billing/organization/org-1/payment-methods/card-2')
})
})
describe('subscription cancellation API', () => {
it.each([undefined, 10_000])('preserves plan reads with timeout %s', async (timeout) => {
const api = serve({})
expect(await api.getOrganizationPlan('org-1', timeout)).toBeNull()
expect(requestedMethod).toBe('get')
expect(requestedUrl).toBe('http://billing.test/api/billing/organization/org-1/plan')
expect(requestedTimeout).toBe(timeout ?? 0)
})
it('preserves the existing downgrade request when no timeout is supplied', async () => {
const api = serve(undefined)
await api.downgradePlan('org-1', 'go')
expect(requestedMethod).toBe('post')
expect(JSON.parse(requestedData as string)).toEqual({ planId: 'go' })
expect(requestedTimeout).toBe(0)
})
it('reuses downgrade with a null plan and bounds the cancellation request', async () => {
const api = serve(undefined)
await api.downgradePlan('org-1', null, 15_000)
expect(requestedUrl).toBe('http://billing.test/api/billing/organization/org-1/plan/downgrade')
expect(requestedMethod).toBe('post')
expect(JSON.parse(requestedData as string)).toEqual({ planId: null })
expect(requestedTimeout).toBe(15_000)
})
})