Skip to content

billing-foundation

Plugin host for subscription billing. Manages the read_subscriptions projection table and exposes 5 domain events (subscription created/updated/canceled, invoice paid/failed) appended by the foundation’s own billing-foundation:write:process-event write-handler after provider plugins verify and normalize each webhook. Also manages a separate read_payments projection table (one row per one-off-payment) fed by its own payment-received event and billing-foundation:write:process-payment-event write-handler. Also ships billing-foundation:write:create-checkout-session and billing-foundation:write:create-portal-session write-handlers, a billing-foundation:query:subscription:list query handler, and a createSubscriptionWebhookRoute factory for the /api/subscription/webhook/:providerName extraRoute. createBillingFoundationFeature({ baseUrl, catalog }) additionally derives a billing-foundation:query:billing-plans query, start-plan-checkout/switch-plan write-handlers, a plan-switch-preview query and a dormant billing-plans dashboard screen/panel from the catalog. Several providers can be mounted at once: new checkouts are offered by every enabled provider (enabled means keys set and billingLive on, or simply mounted for plugins without isBillingEnabled), the customer picks one in the plan panel and start-plan-checkout takes a providerName. An existing subscription stays with the provider that stored it, so the plan list and every switch follow that provider. A plan switch is either hosted (createPlanSwitchSession answers a url) or in-app (previewPlanSwitch shows the proration, applyPlanSwitch runs after the customer confirms; switch-plan then answers { applied: true } and records the consent). consumerProtection.providerTexts overrides the checkout note and the VAT note per provider. Also ships billing-foundation:write:sync-subscription (pulls a provider plugin’s live subscription state via retrieveSubscription and appends drift as a subscription.updated event, which catches changes made on the provider’s own dashboard that never reached us as a webhook) and the sync-subscriptions job (daily in the maintenance window, perTenant) that dispatches it. Low-level building block: use subscription-stripe, subscription-mollie or subscription-paddle unless you are writing a new payment provider.

From apps-cap-billing-demo — the smallest working mount:

// kumiko-feature-version: 1
//
// newsletter — demo feature that brings together tier-engine + cap-counter + the
// mail-foundation plugin API.
//
// **What happens in the send handler:**
// 1. Pre-call (via the withCapEnforcement wrapper):
// a) Read the tenant tier from ctx.config
// b) Map tier → cap limit from DEMO_TIER_MAP
// c) enforceCapAndMaybeNotify calls enforceCap → on a
// soft-hit crossing the notifier (sends a warning mail via
// the same mail-foundation, to the admin) AND dispatches
// mark-soft-warned
// 2. Inner handler: createTransportForTenant → transport.send
// 3. Post-success: increment the cap counter by 1
//
// **Observable in the in-memory inbox** (mail-transport-inmemory):
// - The "real" newsletter mails (to event.payload.to)
// - The soft-hit warning mails (to admin@tenant.demo, on the first
// crossing)
//
// **Tier switching:** the primary source is the `subscription` row from
// billing-foundation (= productive path: a Stripe/Mollie webhook
// writes → the tier changes). The fallback is the config key
// "newsletter:config:tier" — the demo README uses it for manual
// switching without a provider, and tier-engine-only tests keep their
// existing flow.
import {
BILLING_FOUNDATION_FEATURE,
getSubscriptionForTenant,
SubscriptionStatuses,
} from "@cosmicdrift/kumiko-bundled-features/billing-foundation";
import {
currentCalendarMonthStartIso,
type SoftHitNotifier,
withCapEnforcement,
} from "@cosmicdrift/kumiko-bundled-features/cap-counter";
import type { EmailMessage } from "@cosmicdrift/kumiko-bundled-features/channel-email";
import {
createMailFoundationFeature,
createTransportForTenant,
type MailTransportContext,
} from "@cosmicdrift/kumiko-bundled-features/mail-foundation";
import {
access,
createTenantConfig,
defineFeature,
defineWriteHandler,
type ReservationContext,
} from "@cosmicdrift/kumiko-framework/engine";
import { z } from "zod";
import { DEMO_TIER_MAP, TIER_NAMES, type TierName } from "./tier-map";
const FEATURE_NAME = "newsletter";
// The transport factory takes a narrow context (it also runs in the worker), so the handler's
// secrets live under services and are handed over explicitly.
function mailContextOf(
ctx: Pick<ReservationContext, "config" | "registry" | "services" | "user">,
): MailTransportContext {
return {
config: ctx.config,
registry: ctx.registry,
secrets: ctx.services.secrets,
auditUserId: ctx.user.id,
};
}
const NEWSLETTER_CAP = "newsletters-per-month";
// =============================================================================
// Inner send-handler
// =============================================================================
const sendSchema = z.object({
to: z.string().email(),
subject: z.string().min(1),
html: z.string().min(1),
});
const innerSendHandler = defineWriteHandler({
name: "send",
schema: sendSchema,
access: { roles: ["TenantAdmin", "SystemAdmin"] },
handler: async (event, ctx) => {
const payload = event.payload;
const transport = await createTransportForTenant(
mailContextOf(ctx),
event.user.tenantId,
"newsletter:write:send",
);
await transport.send({
to: payload.to,
subject: payload.subject,
html: payload.html,
});
return { isSuccess: true as const, data: { sent: true } };
},
});
// =============================================================================
// Tier-Lookup + Cap-Resolver
// =============================================================================
/**
* Resolve the tenant tier.
*
* **Order:**
* 1. subscription row from billing-foundation (= productive
* path). If the row exists, it beats the config fallback —
* even in canceled status (= the tenant falls back to free, NOT
* to an orphaned config="pro" override).
* 2. config key "newsletter:config:tier" (= demo README path without
* a provider; the tier-engine-only path of the original
* tests stays green too).
* 3. Default "free".
*
* The whitelist filter via TIER_NAMES prevents typos ("Pro" / "Premium")
* that would otherwise silently fall back to free.
*/
function isValidTierName(value: string): value is TierName {
return (TIER_NAMES as readonly string[]).includes(value);
}
async function resolveTier(ctx: ReservationContext): Promise<TierName> {
const tenantId = ctx.user?.tenantId;
if (tenantId) {
const sub = await getSubscriptionForTenant(ctx, tenantId);
if (sub) {
// Subscription existiert → trumpft config. Bei active+valid-tier
// → der subscription-tier; sonst free (canceled/past_due/etc).
if (sub.status === SubscriptionStatuses.active && isValidTierName(sub.tier)) {
return sub.tier;
}
return "free";
}
}
const raw = (await ctx.config?.("newsletter:config:tier")) as string | undefined;
if (raw && isValidTierName(raw)) {
return raw;
}
return "free";
}
/** Notifier factory: builds a SoftHitNotifier that sends the warning via
* the same mail-foundation to the tenant admin. */
function buildSoftHitNotifier(ctx: ReservationContext): SoftHitNotifier {
return async (info) => {
const transport = await createTransportForTenant(
mailContextOf(ctx),
info.tenantId,
"newsletter:soft-hit-notifier",
);
const message: EmailMessage = {
to: `admin@tenant-${info.tenantId.slice(-4)}.demo`,
subject: `[Cap Warning] '${info.capName}' bei ${info.value}/${info.limit}`,
html:
`<p>Hallo Admin,</p>` +
`<p>der Cap <strong>${info.capName}</strong> für deinen Tenant ist bei <strong>${info.value}</strong> von ${info.limit} angekommen.</p>` +
`<p>Du bist im soft-Bereich (110% des Limits). Hard-Block kommt bei 120%. Upgrade auf einen höheren Tier oder warte auf den nächsten Monatsreset.</p>`,
};
await transport.send(message);
};
}
// =============================================================================
// Wrapped send-handler (cap-aware)
// =============================================================================
const wrappedSendHandler = withCapEnforcement(innerSendHandler, async (_event, ctx) => {
const tier = await resolveTier(ctx);
// resolveTier returns one of TIER_NAMES; DEMO_TIER_MAP has an entry
// for each. tsc's `noUncheckedIndexedAccess` doesn't carry that
// narrowing through a Record-lookup — extract via const + non-null
// assert (= contract: tier is always a valid key here, see TIER_NAMES
// whitelist in resolveTier).
const tierEntry = DEMO_TIER_MAP[tier];
if (!tierEntry) {
throw new Error(`newsletter: tier "${tier}" not in DEMO_TIER_MAP — TIER_NAMES drift?`);
}
const limit = tierEntry.caps.newslettersPerMonth;
return {
capName: NEWSLETTER_CAP,
periodStartIso: currentCalendarMonthStartIso(),
limit,
profile: "burstable",
notify: buildSoftHitNotifier(ctx),
};
});
// =============================================================================
// Feature-definition
// =============================================================================
export const newsletterFeature = defineFeature(FEATURE_NAME, (r) => {
// Hard deps: mail-foundation for the plugin API + config for the tier choice +
// cap-counter (transitive via withCapEnforcement, but explicit is
// clearer for boot-validator errors).
r.requires({ features: ["config"] });
r.requires({ features: ["cap-counter"] });
r.requires({ features: [createMailFoundationFeature().name] });
r.requires({ features: [BILLING_FOUNDATION_FEATURE] });
// Tier-config-key. Tenant-Admin setzt's; default "free".
r.config({
keys: {
tier: createTenantConfig("select", {
default: "free",
options: TIER_NAMES,
write: access.roles("TenantAdmin", "SystemAdmin"),
read: access.roles("TenantAdmin", "SystemAdmin", "User"),
}),
},
}).tier;
r.writeHandler(wrappedSendHandler);
});
/** QN for the send handler — exported so tests + clients can access it
* without deriving it by hand. */
export const NEWSLETTER_SEND_QN = "newsletter:write:send";
export const NEWSLETTER_TIER_CONFIG_KEY = "newsletter:config:tier";

📄 On GitHub: samples/apps/cap-billing-demo/src/feature.ts

What this feature needs to run (Requires, top) and the write commands this feature provides (Provides, bottom).

flowchart TB
  n_billing_foundation["billing-foundation"]
  subgraph how_reqs["Requires"]
    n_tenant_lifecycle["tenant-lifecycle"]
    n_compliance_profiles["compliance-profiles"]
  end
  subgraph how_provides["Provides"]
    n_cmd_billing_foundation_write_apply_subscription_snapshot(["apply-subscription-snapshot"])
    n_cmd_billing_foundation_write_create_checkout_session(["create-checkout-session"])
    n_cmd_billing_foundation_write_create_portal_session(["create-portal-session"])
    n_cmd_billing_foundation_write_process_event(["process-event"])
    n_cmd_billing_foundation_write_process_payment_event(["process-payment-event"])
    n_cmd_billing_foundation_write_record_checkout_opened(["record-checkout-opened"])
    n_cmd_more(["+1 more"])
  end
  n_tenant_lifecycle --> n_billing_foundation
  n_compliance_profiles --> n_billing_foundation
  n_billing_foundation --> n_cmd_billing_foundation_write_apply_subscription_snapshot
  n_billing_foundation --> n_cmd_billing_foundation_write_create_checkout_session
  n_billing_foundation --> n_cmd_billing_foundation_write_create_portal_session
  n_billing_foundation --> n_cmd_billing_foundation_write_process_event
  n_billing_foundation --> n_cmd_billing_foundation_write_process_payment_event
  n_billing_foundation --> n_cmd_billing_foundation_write_record_checkout_opened
  n_billing_foundation --> n_cmd_more

Provides — write commands this feature registers (dispatch them through the command bus):

Start with apps-cap-billing-demo for a step-by-step walkthrough with runnable code and integration tests.

  • Registers extension: tenantData → subscription, tenantData → payment