{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "billing",
  "title": "Billing",
  "description": "Primitives for subscription billing: billing dates, MRR movement from starting to ending MRR, net revenue retention, a waterfall chart of the movement and an invoice status label.",
  "dependencies": [
    "recharts"
  ],
  "registryDependencies": [
    "https://www.dashboardblocks.com/r/radix/chart.json",
    "https://www.dashboardblocks.com/r/radix/chart-panel.json",
    "https://www.dashboardblocks.com/r/radix/format.json",
    "https://www.dashboardblocks.com/r/radix/status-label.json"
  ],
  "files": [
    {
      "path": "registry/components/dashboardblocks/billing.tsx",
      "content": "'use client'\n\nimport {\n  ChartTooltipFrame,\n  ChartTooltipItem,\n  type ChartValueFormatter,\n  chartAxisProps,\n  chartBarCursor,\n  chartReferenceLabel,\n  chartReferenceProps,\n} from '@/registry/components/dashboardblocks/chart'\nimport { ChartPanelFigure } from '@/registry/components/dashboardblocks/chart-panel'\nimport {\n  StatusLabel,\n  type StatusLabelProps,\n  type StatusTone,\n} from '@/registry/components/dashboardblocks/status-label'\nimport {\n  formatCurrency,\n  formatDate,\n  formatSigned,\n} from '@/registry/lib/dashboardblocks/format'\nimport {\n  Bar,\n  BarChart,\n  Cell,\n  LabelList,\n  ReferenceLine,\n  ResponsiveContainer,\n  Tooltip,\n  type TooltipContentProps,\n  XAxis,\n  YAxis,\n} from 'recharts'\nimport type { NameType, ValueType } from 'recharts/types/component/DefaultTooltipContent'\n\nfunction formatBillingDate(date: Date) {\n  return formatDate(date, 'date')\n}\n\nfunction getDaysUntil(date: Date, now: Date) {\n  return Math.ceil((date.getTime() - now.getTime()) / 86_400_000)\n}\n\nfunction formatDaysUntil(days: number) {\n  if (days > 1) return `in ${days} days`\n  if (days === 1) return 'tomorrow'\n  return 'today'\n}\n\ninterface MrrMovementInput {\n  contraction: number\n  churn: number\n  expansion: number\n  newBusiness: number\n  starting: number\n}\n\ntype MrrStepName = 'starting' | 'new' | 'expansion' | 'contraction' | 'churn' | 'ending'\n\ninterface MrrStep {\n  from: number\n  key: MrrStepName\n  kind: 'total' | 'increase' | 'decrease'\n  label: string\n  to: number\n  /** Signed: negative for contraction and churn. */\n  value: number\n}\n\nfunction getMrrMovement(input: MrrMovementInput) {\n  const { churn, contraction, expansion, newBusiness, starting } = input\n  const changes: [MrrStepName, string, number, MrrStep['kind']][] = [\n    ['new', 'New', newBusiness, 'increase'],\n    ['expansion', 'Expansion', expansion, 'increase'],\n    ['contraction', 'Contraction', -Math.abs(contraction), 'decrease'],\n    ['churn', 'Churn', -Math.abs(churn), 'decrease'],\n  ]\n  const steps: MrrStep[] = [\n    {\n      from: 0,\n      key: 'starting',\n      kind: 'total',\n      label: 'Starting MRR',\n      to: starting,\n      value: starting,\n    },\n  ]\n  let running = starting\n  for (const [key, label, value, kind] of changes) {\n    steps.push({\n      from: running,\n      key,\n      kind,\n      label,\n      to: running + value,\n      value,\n    })\n    running += value\n  }\n  steps.push({\n    from: 0,\n    key: 'ending',\n    kind: 'total',\n    label: 'Ending MRR',\n    to: running,\n    value: running,\n  })\n  return { ending: running, net: running - starting, steps }\n}\n\nfunction getNetRevenueRetention(\n  input: Pick<MrrMovementInput, 'churn' | 'contraction' | 'expansion' | 'starting'>,\n) {\n  const { churn, contraction, expansion, starting } = input\n  if (starting <= 0) return 0\n  return (starting + expansion - Math.abs(contraction) - Math.abs(churn)) / starting\n}\n\nfunction getRevenueMetrics({ customers, mrr }: { customers: number; mrr: number }) {\n  return { arpu: customers > 0 ? mrr / customers : 0, arr: mrr * 12 }\n}\n\nconst MAX_WATERFALL_TICKS = 5\n\nfunction getWaterfallScale(steps: MrrStep[]) {\n  const levels = steps.flatMap((step) =>\n    step.kind === 'total' ? [step.to] : [step.from, step.to],\n  )\n  const lowest = Math.min(...levels, Infinity)\n  const highest = Math.max(...levels, 0)\n  const span = highest - lowest || highest || 1\n  let unit = 10 ** Math.floor(Math.log10(span))\n  const floorFor = (step: number) =>\n    Math.max(0, Math.floor((lowest - span * 0.75) / step) * step)\n  while ((highest - floorFor(unit)) / unit > MAX_WATERFALL_TICKS) unit *= 2\n  const floor = floorFor(unit)\n  const ceiling = floor + Math.ceil((highest - floor) / unit) * unit\n  const ticks: number[] = []\n  for (let tick = floor; tick <= ceiling; tick += unit) ticks.push(tick)\n  return { ceiling, floor, ticks }\n}\n\nconst mrrStepColors: Record<MrrStep['kind'], string> = {\n  decrease: 'var(--color-red-500)',\n  increase: 'var(--color-emerald-500)',\n  total: 'var(--color-chart-2)',\n}\n\ninterface MrrWaterfallRow extends MrrStep {\n  display: string\n  range: [number, number]\n}\n\ntype MrrWaterfallTooltipProps = Partial<\n  Pick<TooltipContentProps<ValueType, NameType>, 'active' | 'payload'>\n> & {\n  formatter: ChartValueFormatter\n}\n\nfunction MrrWaterfallTooltip({ active, formatter, payload }: MrrWaterfallTooltipProps) {\n  const step = payload?.[0]?.payload as MrrWaterfallRow | undefined\n  if (!active || !step) return null\n  return (\n    <ChartTooltipFrame>\n      <span className='font-medium'>{step.label}</span>\n      {step.kind !== 'total' && (\n        <ChartTooltipItem\n          color={mrrStepColors[step.kind]}\n          name='Change'\n          value={formatSigned(step.value, formatter)}\n        />\n      )}\n      <ChartTooltipItem\n        color={step.kind === 'total' ? mrrStepColors.total : undefined}\n        name='MRR'\n        value={formatter(step.to)}\n      />\n    </ChartTooltipFrame>\n  )\n}\n\ninterface MrrWaterfallProps {\n  /** @default true */\n  animated?: boolean\n  className?: string\n  /** Formats the axis and the labels beside each bar. */\n  formatter?: ChartValueFormatter\n  label: string\n  steps: MrrStep[]\n  /** Formats the values in the tooltip. */\n  tooltipFormatter?: ChartValueFormatter\n}\n\nfunction MrrWaterfall({\n  animated = true,\n  className,\n  formatter = (value) => formatCurrency(value, { compact: true }),\n  label,\n  steps,\n  tooltipFormatter = (value) => formatCurrency(value),\n}: MrrWaterfallProps) {\n  const { ceiling, floor, ticks } = getWaterfallScale(steps)\n  const starting = steps.find((step) => step.key === 'starting')\n  const rows: MrrWaterfallRow[] = steps.map((step) => ({\n    ...step,\n    display:\n      step.kind === 'total' ? formatter(step.to) : formatSigned(step.value, formatter),\n    range:\n      step.kind === 'total'\n        ? [floor, step.to]\n        : [Math.min(step.from, step.to), Math.max(step.from, step.to)],\n  }))\n\n  return (\n    <ChartPanelFigure className={className}>\n      <ResponsiveContainer width='100%' height='100%'>\n        <BarChart\n          accessibilityLayer\n          aria-label={label}\n          data={rows}\n          layout='vertical'\n          margin={{ top: 20, right: 56, bottom: 0, left: 0 }}\n          barCategoryGap='30%'\n        >\n          <XAxis\n            {...chartAxisProps}\n            allowDataOverflow\n            domain={[floor, ceiling]}\n            tickFormatter={formatter}\n            ticks={ticks}\n            type='number'\n          />\n          <YAxis {...chartAxisProps} dataKey='label' type='category' width={104} />\n          <Tooltip\n            content={(tooltipProps) => (\n              <MrrWaterfallTooltip {...tooltipProps} formatter={tooltipFormatter} />\n            )}\n            cursor={chartBarCursor}\n          />\n          {starting && (\n            <ReferenceLine\n              {...chartReferenceProps}\n              x={starting.to}\n              label={{ ...chartReferenceLabel, position: 'top', value: 'Start' }}\n            />\n          )}\n          <Bar dataKey='range' isAnimationActive={animated} name='MRR' radius={3}>\n            {rows.map((row) => (\n              <Cell key={row.key} fill={mrrStepColors[row.kind]} />\n            ))}\n            <LabelList\n              dataKey='display'\n              position='right'\n              fill='var(--color-muted-foreground)'\n              fontSize={12}\n            />\n          </Bar>\n        </BarChart>\n      </ResponsiveContainer>\n    </ChartPanelFigure>\n  )\n}\n\ntype InvoiceStatus =\n  | 'draft'\n  | 'due'\n  | 'failed'\n  | 'granted'\n  | 'overdue'\n  | 'paid'\n  | 'partly-paid'\n  | 'scheduled'\n  | 'sent'\n  | 'uncollectible'\n  | 'viewed'\n  | 'void'\n\nconst invoiceStatusConfig: Record<InvoiceStatus, { label: string; tone: StatusTone }> = {\n  draft: { label: 'Draft', tone: 'neutral' },\n  due: { label: 'Due', tone: 'neutral' },\n  failed: { label: 'Failed', tone: 'bad' },\n  granted: { label: 'Granted', tone: 'info' },\n  overdue: { label: 'Overdue', tone: 'bad' },\n  paid: { label: 'Paid', tone: 'good' },\n  'partly-paid': { label: 'Partly paid', tone: 'info' },\n  scheduled: { label: 'Scheduled', tone: 'neutral' },\n  sent: { label: 'Sent', tone: 'neutral' },\n  uncollectible: { label: 'Uncollectible', tone: 'bad' },\n  viewed: { label: 'Viewed', tone: 'info' },\n  void: { label: 'Void', tone: 'neutral' },\n}\n\n/** Statuses that leave nothing to pay: not sent yet, paid, granted for free, or voided. */\nconst settledInvoiceStatuses: InvoiceStatus[] = [\n  'draft',\n  'granted',\n  'paid',\n  'scheduled',\n  'void',\n]\n\n/** What's left to pay, and how many invoices and the oldest of them it's across. */\nfunction getOutstandingInvoices<\n  Invoice extends { amount: number; date: Date; status: InvoiceStatus },\n>(invoices: Invoice[]) {\n  const unpaid = invoices.filter(\n    (invoice) => !settledInvoiceStatuses.includes(invoice.status),\n  )\n  return {\n    amount: unpaid.reduce((sum, invoice) => sum + invoice.amount, 0),\n    count: unpaid.length,\n    oldest: unpaid.reduce<Invoice | undefined>(\n      (first, invoice) => (!first || invoice.date < first.date ? invoice : first),\n      undefined,\n    ),\n  }\n}\n\ninterface InvoiceStatusLabelProps extends Omit<StatusLabelProps, 'children' | 'tone'> {\n  status: InvoiceStatus\n}\n\nfunction InvoiceStatusLabel({ status, ...props }: InvoiceStatusLabelProps) {\n  const config = invoiceStatusConfig[status]\n  return (\n    <StatusLabel tone={config.tone} {...props}>\n      {config.label}\n    </StatusLabel>\n  )\n}\n\nexport {\n  InvoiceStatusLabel,\n  MrrWaterfall,\n  formatBillingDate,\n  formatDaysUntil,\n  getDaysUntil,\n  getMrrMovement,\n  getNetRevenueRetention,\n  getOutstandingInvoices,\n  getRevenueMetrics,\n  getWaterfallScale,\n  invoiceStatusConfig,\n  mrrStepColors,\n}\n\nexport type {\n  InvoiceStatus,\n  InvoiceStatusLabelProps,\n  MrrMovementInput,\n  MrrStep,\n  MrrStepName,\n  MrrWaterfallProps,\n}\n",
      "type": "registry:component",
      "target": "@components/dashboardblocks/billing.tsx"
    }
  ],
  "type": "registry:component"
}
