@baseworks/billing
v1.5.0
Published
Billing capability: typed HTTP client, event catalog, projections, and CLI plugin for billing-service (usage-based billing: metrics, plans, subscriptions, usage). Contract-first, versioned with the service.
Readme
@baseworks/billing
Typed client, event catalog, projections, and CLI plugin for billing-service — the per-org usage-based billing core (metrics, plans, subscriptions). Contract-first, versioned with the service.
pnpm add @baseworks/billingClient
Everything is org-scoped (X-Org-Id + token). Money is integer cents throughout. The wire is snake_case
(0.4.0, workspace ADR 0003): options, inputs and everything the service answers. A service calling this on behalf of a
request passes the request's realm token (c.get('realm_token')), never the raw Authorization header.
import { createBillingClient } from '@baseworks/billing'
const billing = createBillingClient({
base_url: process.env.BILLING_SERVICE_URL!,
token: realmToken,
org_id: activeOrgId,
})
// 1. a billable metric
const apiCalls = await billing.createMetric({
code: 'api_calls', name: 'API calls', aggregation: 'sum', unit: 'request',
})
// 2. a plan — base fee + per-metric usage charges (all integer cents)
const pro = await billing.createPlan({
code: 'pro', name: 'Pro', currency: 'USD',
base_amount_cents: 4900, // $49.00 / month
charges: [{ metric_code: 'api_calls', unit_amount_cents: 2 }], // $0.02 / call
})
// 3. subscribe a customer (customer_id is a customers-service ref — validated,
// name snapshotted). Opens a one-month billing period.
const sub = await billing.createSubscription({ customer_id: 'acct-42', plan_id: 'pro' })
await billing.listSubscriptions({ status: 'active' })
await billing.getSubscription(sub.id)
// 4. meter usage — idempotent by transaction_id (re-sending is a no-op)
await billing.recordUsage({ subscription_id: sub.id, metric_code: 'api_calls', quantity: 100, transaction_id: 'req-1' })
await billing.recordUsage({ subscription_id: sub.id, metric_code: 'api_calls', quantity: 250, transaction_id: 'req-2' })
await billing.listUsage({ subscription_id: sub.id })
// 5. rate the current period — base fee + Σ(aggregated usage × charge). No invoice.
const rating = await billing.rateSubscription(sub.id)
// → { base_amount_cents: 4900, lines: [{ metric_code: 'api_calls', quantity: 350, amount_cents: 700 }], total_cents: 5600 }
// 6. close the period → finalized invoice (idempotent + resumable + locked).
// Re-running is safe: one invoice per subscription-period. `force` closes the
// current period even before it ends (a real cron omits it and closes on due).
const report = await billing.closePeriods({ subscription_id: sub.id, force: true })
// → { locked: true, closed: [{ subscription_short_id, invoice_number, total_cents, status: 'closed' }], skipped: [] }
await billing.cancelSubscription(sub.id, 'downgraded')Errors throw BillingError (.status, .code): 409 code_taken,
400 unknown_metric (charge/usage references a missing metric),
404 customer_not_found, 404 plan_not_found, 404 subscription_not_found,
409 already_canceled, 409 subscription_canceled (usage on a canceled sub),
403 forbidden with permission (the action org-service says the caller lacks: billing.read, .subscribe, .meter, .configure, .close).
Dates (1.5.0)
await billing.recordUsage({ subscription_id: sub.id, metric_code: 'api_calls', quantity: 5, transaction_id: 'req-9',
occurred_at: '2027-01-31T23:50:00Z' }) // or epoch ms; default now. It chooses the period
await billing.listUsage({ subscription_id: sub.id, from: '2027-01-01', to: '2027-01-31' }) // by occurred_at
const r = await billing.closePeriods({ due_date: '2027-02-14' })
// every ended period, oldest first; each entry has display_number, and a refused one reason + message
r.closed.filter((e) => e.date_shifted_from) // dated later than the day it belongs to: the series was already thereA closed period refuses usage (period_closed); more than 5 minutes ahead is occurred_at_in_future. Invoices are dated
the period's last day (a fee in advance: its first; an immediate cancel: that day), or the series' latest date when that is
later (date_shifted_from; a fee's own invoice: fee_date_shifted_from). CLI: billing usage record
--occurred-at <instant>, billing usage ls --from 2027-01-01 --to 2027-01-31, billing close --due-date 2027-02-14.
Needs billing-service 1.5.0 and invoice-service 2.0.0; an older billing-service ignores occurred_at and due_date.
Anchors, included usage, advance fees and cancel (1.4.0)
await billing.createPlan({
code: 'hobby', name: 'Hobby', currency: 'EUR', base_amount_cents: 500,
included_usage_cents: 500, bill_base: 'advance', product_id: 'prod_hobby',
charges: [{ metric_code: 'compute', unit_amount_cents: 1 }, { metric_code: 'ipv4', unit_amount_cents: 300, draws_on_included: false }],
})
const s = await billing.createSubscription({ customer_id: 'acct-42', plan_id: 'hobby', billing_anchor_day: 1 }) // or start_date: '2026-10-15'
s.warning // set when the first advance fee was not invoiced
await billing.cancelSubscription(s.id, 'moving', { at_period_end: true })
await billing.resumeSubscription(s.id) // before the period ends
const due = await billing.listRefunds({ status: 'due' }) // billing.refund.read
await billing.settleRefund(due[0]!.id, 'bank ref 42') // billing moves no moneyAnchors and dates are UTC. Cancelling at once is a member's only in the withdrawal window (14 days from the start by
default, once per customer per year), where no fee is charged and an advance fee becomes a refund due; later it is
403 forbidden without billing.subscription.manage. Cancel-at-period-end changes are limited (429 too_many_changes).
An immediate cancelSubscription invoices the current period up to today (invoice_failed: nothing was canceled). New plan
codes match ^[a-z0-9][a-z0-9_-]{1,39}$ and are not shaped like a short id (bad_code).
A downgrade (changeSubscriptionPlan to a lower base price or another currency) waits for the period to end: the answer has
pending_plan_code and pending_plan_at. { effective: 'now' } (billing subscriptions plan <ref> <plan> --now) applies it
at once and needs billing.subscription.manage.
CLI also: billing subscriptions resume <ref>, billing refunds ls [--status due], billing refunds settle <id> --note <n>.
CLI: billing plans create … --included 5.00 --bill-base advance --product <id> --flat-charge ipv4:3.00 --charge-product
compute=<id>, billing subscriptions create … --anchor-day 1 | --start-date 2026-10-15, billing subscriptions cancel <ref>
--at-period-end.
A subscription's invoices and paging (1.3.0)
await billing.listSubscriptionInvoices(sub.id, { expand: 'invoice' })
await billing.attachSubscriptionInvoice(sub.id, { invoice_id: 'inv_1', period_start: '2026-11-01' }) // billing.invoice.attach
const page = await billing.listPlansPage({ limit: 100 }) // page.next_offset: null on the last pageperiod_start is a period billing closed, the current one, or one of the 60 months before the first period (for invoices from
before the subscription was in billing): its start in epoch ms, or any date inside it (UTC, YYYY-MM-DD).
CLI: billing subscriptions invoices <ref> [--expand], billing subscriptions attach <ref> 2026-11-01=inv_1 2026-12-01=inv_2.
Every billing_list_* MCP tool takes limit (default 100, max 500) and cursor, and returns next.
Archiving and exact prices (1.2.0)
await billing.archivePlan('old') // = deletePlan: hidden from lists and new subscriptions; its subscriptions keep it and are still rated
await billing.archiveMetric('cpu') // = deleteMetric: 409 metric_in_use (BillingError, with the plans in the body) while a live plan charges for it
await billing.listPlans({ include_archived: true }) // also listMetrics({ include_archived: true }); every plan/metric has `archived`
// 1.00 per 21 900 RU-minutes: an exact price per N units. Give unit_amount_cents OR unit_price, never both.
await billing.createPlan({ code: 'ru', name: 'RU', currency: 'USD', charges: [
{ metric_code: 'ru_minutes', unit_price: { amount_cents: 100, per_units: 21_900 } },
{ metric_code: 'api_calls', unit_amount_cents: 2 }, // whole cents per unit, as before
] })
// rating: { metric_code, quantity: 657000, unit_price: { amount_cents: 100, per_units: 21900 },
// unit_price_text: '1.00 USD per 21900 ru_minutes', unit_amount_cents: 0, amount_cents: 3000 }A line is quantity × price computed exactly and rounded half up to whole cents, once; unit_amount_cents on a charge is the price of one unit rounded
for display, never used to rate. The CLI takes --charge metric:price/per_units (ru_minutes:1.00/21900). New types: UnitPrice; archived on Metric and Plan.
See the service README for the rules.
Limits (1.1.0)
Plans carry limits and subscriptions limits + limits_override: Limits = Record<string, number | null> (keys
^[a-z][a-z0-9_]{0,31}$, at most 32; non-negative integers; null = unlimited; an absent key = the product decides). billing
stores and answers, it enforces nothing.
await billing.createPlan({ code: 'team', name: 'Team', currency: 'EUR', limits: { projects: 5, seats: 10 } })
await billing.setPlanLimits('team', { projects: 9, seats: null }) // replaces the whole map; {} clears; needs billing.configure
await billing.updatePlan('team', { limits: { projects: 9 } }) // the same, through updatePlan
await billing.setSubscriptionLimits(sub.id, { seats: 50 }) // one customer's deal; null clears
const s = await billing.getSubscription(sub.id)
// s.limits → the plan's current limits with the override over them, per key
// s.limits_override → { seats: 50 }A bad shape throws BillingError 400 bad_limits and nothing is stored. A plan change reaches its subscriptions at once.
Deprecated names (0.3 → 0.4)
Until 0.4.0 the wire was camelCase. Every camelCase name the client exposed stays, deprecated, so a service that has not
moved still builds and runs; they go when the last caller has moved (stripe-service, apps/cli).
| Where | Old (deprecated) | New |
|---|---|---|
| options | baseUrl, orgId | base_url, org_id |
| inputs (renamed to snake_case before sending; the new name wins when both are given) | customerId, planId, baseAmountCents, metricCode, unitAmountCents (in a plan's charges), subscriptionId, transactionId (recordUsage; subscriptionId also in listUsage), providerRef, planCode, currentPeriodStart, currentPeriodEnd, cancelAtPeriodEnd, endedReason (reconcileProviderSubscription), subscriptionId, asOf, dueAt (closePeriods) | the same in snake_case |
| metric answers | shortId, createdAt, updatedAt | short_id, created_at, updated_at |
| plan answers | shortId, baseAmountCents, createdAt, updatedAt; charges: metricCode, unitAmountCents | snake_case |
| subscription answers | shortId, customerId, customerName, planId, planCode, providerRef, cancelAtPeriodEnd, endedReason, currentPeriodStart, currentPeriodEnd, startedAt, createdAt, updatedAt | snake_case |
| usage answers | subscriptionId, metricCode, transactionId, createdAt | snake_case |
| rating answers | subscriptionId, planCode, periodStart, periodEnd, baseAmountCents, totalCents; lines: metricCode, unitAmountCents, amountCents | snake_case |
| close report entries | subscriptionId, subscriptionShortId, invoiceId, invoiceNumber, totalCents | snake_case |
On answers the old names are non-enumerable getters of the snake_case field: sub.planCode reads, while
JSON.stringify(sub) and toEqual see the snake_case object only. The types carry them @deprecated. Method names are
unchanged. The GraphQL schema stays camelCase (that contract's own), with resolvers over the snake_case data.
A client 0.4.0 needs billing-service 0.4.0 (it sends and reads snake_case). Deploy the service first.
CLI plugin
import { buildBillingCommand } from '@baseworks/billing/cli'
program.addCommand(buildBillingCommand({ http, cliName: 'dtab' }))
// dtab billing | bill
// metrics|metric ls · create · get · update · delete
// plans|plan ls · create (--base, --charge metric:price) · get · update · delete
// subscriptions|subs ls (--status, --customer) · create (--customer <ref> --plan <code> [--collection]) · plan · get · cancel
// usage record (--subscription --metric --quantity --txn) · ls · rate
// close [--subscription <ref>] [--force] [--due-in <days> | --due-date <day>]MCP tools
@baseworks/billing/mcp exports billingTools(), the tools a model would use, for an MCP server built with
@baseworks/mcp (@modelcontextprotocol/sdk is an optional peer dependency):
import { composeTools } from '@baseworks/mcp'
import { billingTools } from '@baseworks/billing/mcp'
composeTools(customersTools(), invoiceTools(), billingTools())
// ctx.clients.billing is a BillingClient built from the realm token| Tool | Access | Permission |
|---|---|---|
| billing_list_metrics, billing_list_plans, billing_get_plan, billing_list_subscriptions, billing_get_subscription, billing_list_usage, billing_list_subscription_invoices, billing_rate_subscription | read | billing.read |
| billing_attach_subscription_invoices | write | billing.invoice.attach |
| billing_create_subscription, billing_change_plan, billing_cancel_subscription | write | billing.subscribe |
| billing_record_usage | write | billing.meter |
| billing_create_metric, billing_create_plan, billing_update_plan, billing_archive_metric, billing_archive_plan, billing_set_plan_limits, billing_set_subscription_limits | write | billing.configure |
| billing_close_periods | write | billing.close |
Each tool is a thin wrapper over the client, so it can never do what the API would refuse; permission is the name the
service registered with org-service, used to hide a tool from somebody who may not use it. What only a payment provider
may report has no tool.
Service integration
import { PROJECTIONS, POLICIES } from '@baseworks/billing/projections'
import { MetricEvents, PlanEvents, SubscriptionEvents, UsageEvents, CloseEvents } from '@baseworks/billing/events'Payload fields are snake_case since 0.4.0; the projections fold the camelCase events written before it (foldbase reads a snake_case path from a
camelCase payload). Projections metrics → read_metrics, plans → read_plans,
subscriptions → read_subscriptions, usage → read_usage,
closes → read_closes. Tenant = org id. Usage streams are keyed by
sha256(subscription_id:transaction_id) and close markers by
sha256(close:subscription_id:period) — the read-model row collapses duplicates, so
dedup (and one-invoice-per-period) holds even if two runs race.
