{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "invoice-table",
  "title": "Invoice Table",
  "description": "Invoice line items table with optional quantity, unit price and tax columns, prorated lines, grouped plan changes, a totals footer, and an optional per-line allocation column for credit notes and part payments.",
  "dependencies": [
    "lucide-react"
  ],
  "registryDependencies": [
    "table",
    "https://dentil.dev/r/currency-input.json?via=invoice-table"
  ],
  "files": [
    {
      "path": "components/dentil/invoice-table/invoice-table.tsx",
      "content": "'use client';\n\nimport type { ComponentProps, ReactNode } from 'react';\nimport { Loader2 } from 'lucide-react';\n\nimport { Table, TableBody, TableCell, TableFooter, TableHead, TableHeader, TableRow } from '@/components/ui/table';\nimport { cn } from '@/lib/utils';\n\nimport { CurrencyInput, getCurrencyFormat } from '../currency-input/currency-input';\n\n/** Unix seconds, unix milliseconds, an ISO string or a `Date`. */\nexport type InvoiceDate = number | string | Date;\n\n/** The service period a line covers, shown under its description. */\nexport type InvoicePeriod = { start: InvoiceDate; end: InvoiceDate };\n\n/** How a prorated line relates to its full price, shown under its description. */\nexport type InvoiceProration = {\n  /** The line's price for a whole billing period, in minor units. */\n  fullAmount: number;\n  /** Shown as \"17 of 31 days of $20.00\". Without it the detail reads \"Prorated from $20.00\". */\n  days?: { used: number; total: number };\n  /** Replaces the generated text, e.g. to translate it. */\n  label?: ReactNode;\n};\n\n/** One row of the invoice. Amounts are in minor units (pence, cents). */\nexport type InvoiceLine = {\n  id: string;\n  description: ReactNode;\n  /** Beside the description: badges, a link, a note. */\n  meta?: ReactNode;\n  period?: InvoicePeriod;\n  proration?: InvoiceProration;\n  quantity?: number;\n  /**\n   * A decimal string such as `'0.05'` keeps fractions of a minor unit\n   * below one cent.\n   */\n  unitAmount?: number | string;\n  /** Percent, e.g. `20` for 20%. */\n  taxRate?: number;\n  tax?: number;\n  amount: number;\n  /** Struck through before `amount`, e.g. the price before a discount. For proration, use `proration`. */\n  originalAmount?: number;\n};\n\n/** Lines shown as one block under a heading row, such as the credit and charge of a plan change. */\nexport type InvoiceLineGroup<TLine extends InvoiceLine = InvoiceLine> = {\n  id: string;\n  description: ReactNode;\n  meta?: ReactNode;\n  /** Muted line under the description, e.g. \"Upgraded Dec 15, 2026\". */\n  detail?: ReactNode;\n  lines: readonly TLine[];\n  /** Net of the lines, shown on the group row. Omit to leave it blank. */\n  amount?: number;\n};\n\nexport function isInvoiceLineGroup<TLine extends InvoiceLine>(\n  item: TLine | InvoiceLineGroup<TLine>\n): item is InvoiceLineGroup<TLine> {\n  return 'lines' in item && Array.isArray(item.lines);\n}\n\n/** One row of the totals footer. `amount` is in minor units. */\nexport type InvoiceTotal = {\n  id?: string;\n  label: ReactNode;\n  amount: number;\n  /** `muted` for most rows, `strong` for the final amount due, `entry` for a left-aligned line such as a credit note. */\n  variant?: 'muted' | 'strong' | 'entry';\n  /** Adds space above, to start a group such as adjustments. */\n  gap?: boolean;\n  className?: string;\n};\n\n/** An editable amount per line, such as how much of each line a credit note covers. */\nexport type InvoiceAllocation<TLine extends InvoiceLine = InvoiceLine> = {\n  /** Header of the input column. */\n  label?: string;\n  /** Allocated amount per line, in minor units, keyed by line id. */\n  values: Record<string, number | undefined>;\n  onChange: (values: Record<string, number | undefined>) => void;\n  /** Largest amount a line can take, in minor units. Lines at 0 or below get a disabled input. */\n  max: (line: TLine) => number;\n  /** Shows each line's `max` in a Remaining column before the input. */\n  showRemaining?: boolean;\n  disabled?: boolean;\n  /** Marks every enabled input invalid, e.g. when the allocated sum is over a cap. */\n  invalid?: boolean;\n};\n\nexport type InvoiceTableColumn = 'quantity' | 'unitAmount' | 'taxRate' | 'tax';\n\nexport type InvoiceTableProps<TLine extends InvoiceLine = InvoiceLine> = Omit<ComponentProps<'table'>, 'children'> & {\n  /** Extra fields on a line are ignored by the table and passed back to `allocation.max`. */\n  lines: readonly (TLine | InvoiceLineGroup<TLine>)[];\n  /** ISO 4217 code, e.g. `'USD'`. */\n  currency: string;\n  /** Defaults to `'en-US'` rather than the browser's, so server and client render the same text. */\n  locale?: string;\n  /** IANA time zone for line periods. Defaults to `'UTC'` rather than the browser's, for the same reason. */\n  timezone?: string;\n  /** Optional columns, in display order. Defaults to the ones any line has a value for. Amount always shows. */\n  columns?: readonly InvoiceTableColumn[];\n  totals?: readonly InvoiceTotal[];\n  allocation?: InvoiceAllocation<TLine>;\n  /** Where cells sit in a line taller than one row of text. With `allocation`, `top` lines the first row of text up with the input. */\n  verticalAlign?: 'top' | 'middle';\n  loading?: boolean;\n  /** Shown in place of the rows when `lines` is empty. */\n  empty?: ReactNode;\n};\n\nconst columnOrder: readonly InvoiceTableColumn[] = ['quantity', 'unitAmount', 'taxRate', 'tax'];\n\nconst columnLabels: Record<InvoiceTableColumn, string> = {\n  quantity: 'Qty',\n  unitAmount: 'Unit price',\n  taxRate: 'Tax rate',\n  tax: 'Tax',\n};\n\n/**\n * Formats an amount in minor units (`1050` is $10.50) with the currency's symbol and decimal places. A decimal string\n * (`'0.05'`) shows every fraction digit it has beyond the currency's own, so `'0.05'` USD is $0.0005.\n */\nexport function formatInvoiceAmount(amount: number | string, currency: string, locale = 'en-US') {\n  const { digits } = getCurrencyFormat(currency, locale);\n  const minor = typeof amount === 'string' ? Number(amount.trim()) : amount;\n  if (!Number.isFinite(minor)) return String(amount);\n\n  const extra = typeof amount === 'string' ? (amount.split('.')[1] ?? '').replace(/0+$/, '').length : 0;\n  const fractionDigits = Math.min(digits + extra, 20);\n  const major = minor / 10 ** digits;\n  try {\n    return new Intl.NumberFormat(locale, {\n      style: 'currency',\n      currency,\n      currencyDisplay: 'narrowSymbol',\n      minimumFractionDigits: digits,\n      maximumFractionDigits: fractionDigits,\n    }).format(major);\n  } catch {\n    return `${major.toFixed(fractionDigits)} ${currency.toUpperCase()}`;\n  }\n}\n\nfunction toDate(value: InvoiceDate) {\n  const date =\n    value instanceof Date ? value : new Date(typeof value === 'number' && value < 1e11 ? value * 1000 : value);\n  return Number.isNaN(date.getTime()) ? null : date;\n}\n\n/**\n * Formats a period with the parts the two dates share written once: \"Dec 1 – 31, 2026\", or\n * \"Dec 15, 2026 – Jan 14, 2027\". Returns `null` when either date is invalid.\n */\nexport function formatInvoicePeriod(period: InvoicePeriod, locale = 'en-US', timezone = 'UTC') {\n  const start = toDate(period.start);\n  const end = toDate(period.end);\n  if (!start || !end) return null;\n\n  const options: Intl.DateTimeFormatOptions = { month: 'short', day: 'numeric', year: 'numeric' };\n  let text: string;\n  try {\n    text = new Intl.DateTimeFormat(locale, { ...options, timeZone: timezone }).formatRange(start, end);\n  } catch {\n    text = new Intl.DateTimeFormat(locale, { ...options, timeZone: 'UTC' }).formatRange(start, end);\n  }\n  // ICU versions disagree on thin or regular spaces around the dash, which breaks hydration between Node and browsers.\n  return text.replace(/[\\u2009\\u202f]/g, ' ');\n}\n\nexport function InvoiceTable<TLine extends InvoiceLine>({\n  lines,\n  currency,\n  locale = 'en-US',\n  timezone = 'UTC',\n  columns,\n  totals,\n  allocation,\n  verticalAlign = 'top',\n  loading = false,\n  empty = 'No items',\n  className,\n  ...props\n}: InvoiceTableProps<TLine>) {\n  const flat = lines.flatMap((item) => (isInvoiceLineGroup(item) ? item.lines : [item]));\n  const visible = columns\n    ? columnOrder.filter((column) => columns.includes(column))\n    : columnOrder.filter((column) => flat.some((line) => line[column] !== undefined));\n  const showRemaining = allocation ? (allocation.showRemaining ?? true) : false;\n  const columnCount = 2 + visible.length + (allocation ? 1 : 0) + (showRemaining ? 1 : 0);\n\n  // With allocation, text cells start lower so their first line centres on the 36px input (py-1.5 + h-9).\n  const lineCell = verticalAlign === 'middle' ? 'align-middle' : cn('align-top', allocation && 'pt-3.5');\n\n  const money = (amount: number | string) => formatInvoiceAmount(amount, currency, locale);\n  const percent = new Intl.NumberFormat(locale, { style: 'percent', maximumFractionDigits: 2 });\n  const number = new Intl.NumberFormat(locale);\n\n  const cellValue = (line: TLine, column: InvoiceTableColumn) => {\n    if (column === 'quantity') return line.quantity === undefined ? null : number.format(line.quantity);\n    if (column === 'taxRate') return line.taxRate === undefined ? null : percent.format(line.taxRate / 100);\n    const value = line[column];\n    return value === undefined ? null : money(value);\n  };\n\n  const prorationText = ({ fullAmount, days, label }: InvoiceProration) => {\n    if (label !== undefined) return label;\n    if (!days) return `Prorated from ${money(fullAmount)}`;\n    return `${number.format(days.used)} of ${number.format(days.total)} days of ${money(fullAmount)}`;\n  };\n\n  const renderLine = (line: TLine, index: number, group?: { id: string; last: boolean }) => {\n    const max = allocation ? allocation.max(line) : 0;\n    const inputDisabled = !allocation || allocation.disabled || max <= 0;\n    const struck = line.originalAmount !== undefined && line.originalAmount !== line.amount;\n    const period = line.period ? formatInvoicePeriod(line.period, locale, timezone) : null;\n\n    return (\n      <TableRow\n        key={line.id}\n        data-slot=\"invoice-table-line\"\n        data-group={group?.id}\n        className={cn(group && !group.last && 'border-0')}>\n        <TableCell className={cn(lineCell, 'w-full min-w-48 whitespace-normal', group && 'pl-6')}>\n          <div className=\"flex flex-wrap items-center gap-x-2 gap-y-1\">\n            <span>{line.description}</span>\n            {line.meta}\n          </div>\n          {period || line.proration ? (\n            <div data-slot=\"invoice-table-detail\" className=\"text-muted-foreground mt-0.5 text-xs\">\n              {period ? <span data-slot=\"invoice-table-period\">{period}</span> : null}\n              {period && line.proration ? ' · ' : null}\n              {line.proration ? <span data-slot=\"invoice-table-proration\">{prorationText(line.proration)}</span> : null}\n            </div>\n          ) : null}\n        </TableCell>\n        {visible.map((column) => (\n          <TableCell key={column} className={cn(lineCell, 'text-right tabular-nums')}>\n            {cellValue(line, column)}\n          </TableCell>\n        ))}\n        <TableCell className={cn(lineCell, 'text-right tabular-nums')}>\n          {struck ? (\n            <span className=\"text-muted-foreground mr-2 line-through\">{money(line.originalAmount ?? 0)}</span>\n          ) : null}\n          {money(line.amount)}\n        </TableCell>\n        {showRemaining ? (\n          <TableCell className={cn(lineCell, 'text-muted-foreground text-right tabular-nums')}>\n            {money(Math.max(max, 0))}\n          </TableCell>\n        ) : null}\n        {allocation ? (\n          <TableCell\n            data-slot=\"invoice-table-allocation\"\n            className={cn('py-1.5', verticalAlign === 'middle' ? 'align-middle' : 'align-top')}>\n            <CurrencyInput\n              className=\"ml-auto w-44\"\n              inputClassName=\"text-right\"\n              currency={currency}\n              locale={locale}\n              value={allocation.values[line.id] ?? null}\n              maxAmount={Math.max(max, 0)}\n              disabled={inputDisabled}\n              aria-invalid={(allocation.invalid && !inputDisabled) || undefined}\n              aria-label={\n                typeof line.description === 'string'\n                  ? `${allocation.label ?? 'Amount'} for ${line.description}`\n                  : `${allocation.label ?? 'Amount'}, line ${index + 1}`\n              }\n              onChange={(value) => allocation.onChange({ ...allocation.values, [line.id]: value })}\n            />\n          </TableCell>\n        ) : null}\n      </TableRow>\n    );\n  };\n\n  const renderGroup = (group: InvoiceLineGroup<TLine>) => (\n    <TableRow\n      key={`group:${group.id}`}\n      data-slot=\"invoice-table-group\"\n      className={cn('hover:bg-transparent', group.lines.length > 0 && 'border-0')}>\n      <TableCell className={cn(lineCell, 'w-full min-w-48 whitespace-normal')}>\n        <div className=\"flex flex-wrap items-center gap-x-2 gap-y-1\">\n          <span className=\"font-medium\">{group.description}</span>\n          {group.meta}\n        </div>\n        {group.detail ? <div className=\"text-muted-foreground mt-0.5 text-xs\">{group.detail}</div> : null}\n      </TableCell>\n      {visible.map((column) => (\n        <TableCell key={column} className={lineCell} />\n      ))}\n      <TableCell className={cn(lineCell, 'text-right font-medium tabular-nums')}>\n        {group.amount === undefined ? null : money(group.amount)}\n      </TableCell>\n      {showRemaining ? <TableCell className={lineCell} /> : null}\n      {allocation ? <TableCell className={lineCell} /> : null}\n    </TableRow>\n  );\n\n  let lineIndex = 0;\n  const rows = lines.flatMap((item) => {\n    if (!isInvoiceLineGroup(item)) return [renderLine(item, lineIndex++)];\n    return [\n      renderGroup(item),\n      ...item.lines.map((line, i) => renderLine(line, lineIndex++, { id: item.id, last: i === item.lines.length - 1 })),\n    ];\n  });\n\n  return (\n    <Table data-slot=\"invoice-table\" className={className} {...props}>\n      <TableHeader>\n        <TableRow className=\"hover:bg-transparent\">\n          <TableHead className=\"text-muted-foreground\">Description</TableHead>\n          {visible.map((column) => (\n            <TableHead key={column} className=\"text-muted-foreground text-right\">\n              {columnLabels[column]}\n            </TableHead>\n          ))}\n          <TableHead className=\"text-muted-foreground text-right\">Amount</TableHead>\n          {showRemaining ? <TableHead className=\"text-muted-foreground text-right\">Remaining</TableHead> : null}\n          {allocation ? (\n            <TableHead className=\"text-muted-foreground text-right\">{allocation.label ?? 'Amount'}</TableHead>\n          ) : null}\n        </TableRow>\n      </TableHeader>\n      <TableBody>\n        {loading ? (\n          <TableRow className=\"hover:bg-transparent\">\n            <TableCell colSpan={columnCount} className=\"h-24\">\n              <Loader2 className=\"text-muted-foreground mx-auto size-5 animate-spin\" />\n            </TableCell>\n          </TableRow>\n        ) : lines.length === 0 ? (\n          <TableRow className=\"hover:bg-transparent\">\n            <TableCell colSpan={columnCount} className=\"text-muted-foreground h-24 text-center\">\n              {empty}\n            </TableCell>\n          </TableRow>\n        ) : (\n          rows\n        )}\n      </TableBody>\n      {!loading && lines.length > 0 && totals?.length ? (\n        <TableFooter className=\"bg-background font-normal\">\n          {totals.map((total, index) => {\n            const variant = total.variant ?? 'muted';\n            const spacing = cn('py-1', (index === 0 || total.gap) && 'pt-3', index === totals.length - 1 && 'pb-3');\n            const tone = variant === 'strong' ? 'text-foreground font-medium' : 'text-muted-foreground';\n\n            return (\n              <TableRow\n                key={total.id ?? index}\n                data-slot=\"invoice-table-total\"\n                data-variant={variant}\n                className=\"border-0 hover:bg-transparent\">\n                {variant === 'entry' ? (\n                  <>\n                    <TableCell className={cn(spacing, 'whitespace-normal')}>{total.label}</TableCell>\n                    {columnCount > 2 ? <TableCell colSpan={columnCount - 2} className={spacing} /> : null}\n                  </>\n                ) : (\n                  <TableCell colSpan={columnCount - 1} className={cn(spacing, tone, 'text-right')}>\n                    {total.label}\n                  </TableCell>\n                )}\n                <TableCell className={cn(spacing, tone, 'text-right tabular-nums', total.className)}>\n                  {money(total.amount)}\n                </TableCell>\n              </TableRow>\n            );\n          })}\n        </TableFooter>\n      ) : null}\n    </Table>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/dentil/invoice-table/invoice-table.tsx"
    }
  ],
  "type": "registry:component"
}
