[data-reveal]{opacity:1!important;transform:none!important}
AntelopeJS DMS
DocumentationBilling

Billing

Authorized customer balances and invoice previews, and republishing derived billing state after direct writes.

These functions and types are exported from @antelopejs/interface-dms-saas/billing and from the package root.

Read a customer's balance

The example tells credit from money owed. Its scope holds IDs taken from the authenticated request, never unchecked request fields.

ts
import {
  GetTenantCustomerBalance,
  type TenantCustomerBalanceScope,
} from "@antelopejs/interface-dms-saas/billing";

export async function describeBalance(scope: TenantCustomerBalanceScope): Promise<string> {
  const balance = await GetTenantCustomerBalance(scope);
  if (balance.status === "absent") return `No balance: ${balance.reason}`;
  const amount = balance.balanceMinorUnits;
  if (amount === 0) return "Settled";
  return `${Math.abs(amount)} ${balance.currency} minor units ${amount < 0 ? "in credit" : "owed"}`;
}

For an available EUR balance of -1250, the example returns 1250 EUR minor units in credit. That is €12.50 available for future invoices, not a refund. A provider failure rejects the call, and the example lets it reject instead of reporting a zero balance. The sections below list every absence reason and the separate upcoming invoice estimate.

GetTenantCustomerBalance

GetTenantCustomerBalance(scope: TenantCustomerBalanceScope): Promise<TenantCustomerBalance> takes { tenantId: string, userId: string } from a trusted authentication boundary. The user must be a member of the tenant, or the call rejects with 403 error.tenant_member_required. The DMS tenant access gate (AssertTenantAccess) must then pass. The function does not authenticate the user, so the caller vouches for userId.

ResultFields
AvailableTenantCustomerBalancestatus: "available", balanceMinorUnits: number, currency: string
AbsentTenantCustomerBalancestatus: "absent", reason: TenantCustomerBalanceAbsenceReason, balanceMinorUnits: null, currency: null

Amounts are Stripe minor units. A negative amount is customer credit, a positive amount is money owed, and zero is settled. The currency is uppercase ISO 4217. TenantCustomerBalanceAbsenceReason is customer_not_configured, complimentary, customer_deleted, or currency_unavailable. A Stripe read failure rejects with 502 saas.errors.billing.customer_balance_provider_unavailable and is never an absent balance. The call does not charge or refund the customer.

isComplimentarySubscription(subscription: ComplimentarySubscriptionState | null | undefined): boolean is a synchronous helper. ComplimentarySubscriptionState has isComplimentary?: boolean | null. Only an explicit true returns true. A free plan alone is not the complimentary marker.

GetUpcomingInvoicePreview

GetUpcomingInvoicePreview(scope: UpcomingInvoicePreviewScope): Promise<UpcomingInvoicePreview> takes the same { tenantId, userId } scope (UpcomingInvoicePreviewScope) and runs the same authorization checks. A Stripe failure becomes an unavailable result, never an invented total. An authorization failure, a missing implementation or a local storage failure still rejects.

statusResult type and reason
availableAvailableUpcomingInvoicePreview. Stripe priced the next invoice
absentAbsentUpcomingInvoicePreview, with complimentary, free_plan, customer_not_configured, subscription_not_configured, or no_upcoming_invoice
unavailableUnavailableUpcomingInvoicePreview, with stripe_not_configured, tax_not_configured, tax_location_invalid, tax_location_required, tax_calculation_failed, usage_unavailable, or provider_error

Both other variants have reason and computedAt: string. Their reason unions are exported as UpcomingInvoicePreviewAbsenceReason and UpcomingInvoicePreviewUnavailableReason.

An available preview has the fields below. Every amount is an integer in the minor units of its uppercase currency, and every date is an ISO 8601 string.

FieldsType and meaning
subtotalMinorUnits, totalExcludingTaxMinorUnits, taxMinorUnits, totalMinorUnits, amountDueMinorUnitsnumber. In order, the subtotal before discounts and tax, the total after discounts and before tax, the tax, the total with tax, and the amount due once the customer balance is applied
lines, hasMoreLinesUpcomingInvoiceLine[] and boolean. The first page of lines, and whether Stripe returned more. The totals stay complete
taxes, taxCountry, isReverseChargeUpcomingInvoiceTax[], string | null (uppercase country), boolean
periodStart, periodEnd, billingDate, computedAtstring. The cycle bounds, the issue date and the computation time
usageThroughstring | null. The end of the quoted usage, null without usage lines

UpcomingInvoiceLine has kind: UpcomingInvoiceLineKind (subscription, usage, or invoice_item), description: string | null, amountMinorUnits: number, taxMinorUnits: number, quantity: number | null, periodStart: string, periodEnd: string, isProration: boolean, usageLineKey: string | null, and productId: string | null. A usage line key is <provider id>:<key>. Other line kinds have a null usage key.

UpcomingInvoiceTax has amountMinorUnits: number, taxableAmountMinorUnits: number | null, isInclusive: boolean, ratePercentage: number | null, isReverseCharge: boolean, and nullable string fields country, taxType, displayName, jurisdiction, and taxabilityReason. A reverse charge can produce zero tax with isReverseCharge: true.

The preview calls usage providers with isPreview: true and can store its result in a per-tenant cache in the database, shared by every instance. It never creates an invoice or charges the quoted lines. The usage covers the running cycle so far, not its final total, so a screen shows computedAt next to it. A missing payment method alone does not prevent a preview. The cache lifetime, its invalidation and the Stripe read timeout are runtime configuration.

GetTenantBillingPeriod

GetTenantBillingPeriod(tenantId: string): Promise<TenantBillingPeriod | null> returns the tenant's current Stripe billing period as a TenantBillingPeriod, { start: Date, end: Date }, half-open ([start, end)). The period is clipped to the paid usage the same way renewal invoices clip their usage window. A period opened before the paid usage started starts with it, and a guarded downgrade or a closed paid period ends it early. The result is null for a free or complimentary tenant, and for a tenant whose subscription has no recorded currentPeriodStart and currentPeriodEnd yet.

The read is trusted, with no user scope or membership check. Storage errors propagate. It does not call Stripe. A consumer's usage credits can follow another cycle (Cloud resets its allowance on the UTC calendar month), so this period fits only where the invoice period is meant.

RecomputeTenantBillingState

RecomputeTenantBillingState(tenantId: string): Promise<void> republishes the tenant's billing state and its workspace directory fields (plan, seats, MRR, renewal and owner) from the current records. A seed or import calls it once its direct writes finish. The runtime's own billing operations already call it.

The call is trusted and administrative, with no user scope or membership check, so the caller authorizes the tenant first. It writes derived database state only. It does not change the Stripe subscription, and it does not replace lifecycle delivery or preview cache invalidation. Deleted directory rows and subscriptions whose deletion has started are left alone. Storage errors propagate, and repeated conflicts with a concurrent publication reject after a bounded number of retries. A caller awaits the call and reports a failure instead of showing stale directory state as current.

The example runs after an import has committed every row for tenants the caller already authorized.

ts
import { RecomputeTenantBillingState } from "@antelopejs/interface-dms-saas/billing";

export async function refreshImportedTenants(tenantIds: readonly string[]): Promise<void> {
  for (const tenantId of new Set(tenantIds)) {
    await RecomputeTenantBillingState(tenantId);
  }
}