Skip to content

InvoiceForm

With the revenue-recognition preview per line.
Implemented
Status
Implemented
Family
10 of 13
Registry
@lopifi/invoice-form
npx shadcn@latest add @lopifi/theme @lopifi/invoice-form

The component, rendering

Real data, the shipped component. Switch the theme to check the claims the spec makes below.

Preview

The four-layer spec

Lines with account and dimensions, itemized tax by jurisdiction and rate, terms, PO reference. Shows the revenue recognition preview per line before posting — whether each line credits revenue or deferred revenue, and on what schedule. Invoice number is system-assigned and gapless; the user cannot pick it.

Discount terms render in full: "2% discount if paid within 10 days, otherwise due in 30 days", with both amounts and the discount deadline computed.

Lifted verbatim from Receivables (AR). The doc and this page are the same paragraphs, so they cannot disagree.

What lands in your repository

One component is never one file. Everything below is copied into your project, where you own it.

Files

components/ledger/invoice-form.tsx

Lopifi dependencies · 11
account-pickeraccounting.typesbuttoncnfiscal-periodformat-moneyiconsmoneymoney.typesruletooltip
npm packages
@base-ui-components/reactclass-variance-authorityclsxtailwind-merge
Registry entry
/r/invoice-form.json

The whole component

No compiled bundle, no black box. This is the file the registry copies, and the file you will edit.

components/ledger/invoice-form.tsx
"use client";

import * as React from "react";
import type { Account } from "@/lib/ledger/accounting.types";
import { cn } from "@/lib/ledger/cn";
import { formatDate } from "@/lib/ledger/fiscal-period";
import { formatMoneyInput, parseMoneyInput } from "@/lib/ledger/format-money";
import type { MoneyValue } from "@/lib/ledger/money.types";
import { AccountPicker } from "@/components/ledger/account-picker";
import { Button } from "@/components/ledger/button";
import { InformationCircleIcon, PlusIcon, TrashIcon } from "@/components/ledger/icons";
import { Money } from "@/components/ledger/money";
import { Rule } from "@/components/ledger/rule";

export type InvoiceDraftLine = {
  key: string;
  description: string;
  account: Account | null;
  amount: number | null;
  /** Whether this line credits revenue now or deferred revenue on a schedule. */
  recognition: "immediate" | "ratable";
  ratableMonths?: number;
};

export type TaxLine = {
  jurisdiction: string;
  rate: number;
  amount: MoneyValue;
};

export interface InvoiceFormProps {
  accounts: Account[];
  className?: string;
  currency: string;
  /** System-assigned and gapless. The user cannot pick it. */
  invoiceNumber: string;
  issueDate: Date;
  taxes: TaxLine[];
  /** "2/10 net 30" — rendered in full, with both amounts computed. */
  terms: { discountPercent: number; discountDays: number; netDays: number };
  totals: { subtotal: MoneyValue; tax: MoneyValue; total: MoneyValue; discounted: MoneyValue };
}

/**
 * Shows the revenue-recognition preview per line **before** posting — whether
 * each line credits revenue or deferred revenue, and on what schedule.
 */
export function InvoiceForm({
  accounts,
  currency,
  invoiceNumber,
  issueDate,
  terms,
  taxes,
  totals,
  className,
}: InvoiceFormProps) {
  const [lines, setLines] = React.useState<InvoiceDraftLine[]>([
    {
      account: null,
      amount: 1_200_000,
      description: "Platform subscription, annual",
      key: "1",
      ratableMonths: 12,
      recognition: "ratable",
    },
    {
      account: null,
      amount: 350_000,
      description: "Implementation services",
      key: "2",
      recognition: "immediate",
    },
  ]);

  const discountDeadline = new Date(
    issueDate.getFullYear(),
    issueDate.getMonth(),
    issueDate.getDate() + terms.discountDays,
  );
  const dueDate = new Date(
    issueDate.getFullYear(),
    issueDate.getMonth(),
    issueDate.getDate() + terms.netDays,
  );

  const update = (key: string, patch: Partial<InvoiceDraftLine>) =>
    setLines((prev) => prev.map((l) => (l.key === key ? { ...l, ...patch } : l)));

  return (
    <div className={cn("space-y-4", className)}>
      <div className="flex flex-wrap items-center gap-4 rounded-md bg-surface-sunken px-4 py-3">
        <span className="text-caption text-text-secondary">
          Invoice number
          <span className="reference-numeric ml-2 text-body font-medium text-text-primary">
            {invoiceNumber}
          </span>
        </span>
        <span className="flex items-center gap-1 text-caption text-text-tertiary">
          <InformationCircleIcon aria-hidden="true" className="size-3.5" />
          System-assigned and gapless — many VAT regimes require a sequence.
        </span>
      </div>

      <div className="overflow-x-auto rounded-xl border border-border bg-surface">
        <table className="w-full min-w-[860px]">
          <caption className="sr-only">Invoice lines</caption>
          <thead>
            <tr className="border-b border-border-subtle">
              {["Description", "Account", "Recognition", "Amount", ""].map((h, i) => (
                <th
                  className={cn(
                    "px-3 py-3 text-label font-medium text-text-secondary",
                    i === 3 ? "text-right" : "text-left",
                    i === 0 && "pl-6",
                  )}
                  key={h || i}
                  scope="col"
                >
                  {h || <span className="sr-only">Remove</span>}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {lines.map((l) => (
              <tr className="border-b border-border-subtle align-top" key={l.key}>
                <td className="py-3 pl-6 pr-3">
                  <input
                    aria-label="Line description"
                    className="h-10 w-full rounded-sm border border-border bg-surface px-3 text-body outline-none focus-visible:border-accent"
                    onChange={(e) => update(l.key, { description: e.target.value })}
                    value={l.description}
                  />
                </td>
                <td className="w-[240px] px-3 py-3">
                  <AccountPicker
                    accounts={accounts}
                    onValueChange={(account) => update(l.key, { account })}
                    value={l.account?.id ?? null}
                  />
                </td>
                <td className="px-3 py-3">
                  <select
                    aria-label="Revenue recognition"
                    className="h-10 rounded-sm border border-border bg-surface px-2 text-body outline-none focus-visible:border-accent focus-visible:ring-2 focus-visible:ring-accent-subtle"
                    onChange={(e) =>
                      update(l.key, {
                        recognition: e.target.value as InvoiceDraftLine["recognition"],
                      })
                    }
                    value={l.recognition}
                  >
                    <option value="immediate">Recognize now</option>
                    <option value="ratable">Ratable</option>
                  </select>
                  {/* The recognition preview, before posting. */}
                  <p className="mt-1 max-w-[220px] text-caption text-text-secondary">
                    {l.recognition === "immediate"
                      ? "Credits revenue on issue."
                      : `Credits deferred revenue, recognized over ${l.ratableMonths ?? 12} months from ${formatDate(issueDate)}.`}
                  </p>
                </td>
                <AmountCell
                  currency={currency}
                  onChange={(v) => update(l.key, { amount: v })}
                  value={l.amount}
                />
                <td className="px-3 py-3">
                  <button
                    aria-label="Remove line"
                    className="press grid size-8 place-items-center rounded-sm text-text-tertiary hover:bg-surface-hover"
                    onClick={() => setLines((prev) => prev.filter((x) => x.key !== l.key))}
                    type="button"
                  >
                    <TrashIcon aria-hidden="true" className="size-4" />
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <Button
        onClick={() =>
          setLines((prev) => [
            ...prev,
            {
              account: null,
              amount: null,
              description: "",
              key: Math.random().toString(36).slice(2),
              recognition: "immediate",
            },
          ])
        }
        size="sm"
        variant="secondary"
      >
        <PlusIcon aria-hidden="true" className="size-3.5" />
        Add line
      </Button>

      <div className="grid gap-4 lg:grid-cols-2">
        <section className="rounded-xl border border-border bg-surface p-6">
          <h3 className="text-title-sm font-medium">Terms</h3>
          <p className="mt-2 text-body">
            <span className="numeric">{terms.discountPercent}%</span> discount if paid within{" "}
            <span className="numeric">{terms.discountDays}</span> days, otherwise due in{" "}
            <span className="numeric">{terms.netDays}</span> days.
          </p>
          <dl className="mt-3 space-y-1">
            <Row label={`Pay by ${formatDate(discountDeadline)}`} value={totals.discounted} />
            <Row label={`Pay by ${formatDate(dueDate)}`} value={totals.total} />
          </dl>
        </section>

        <section className="rounded-xl border border-border bg-surface p-6">
          <h3 className="text-title-sm font-medium">Totals</h3>
          <table className="mt-2 w-full">
            <tbody>
              <TotalRow label="Subtotal" value={totals.subtotal} />
              {taxes.map((t) => (
                <TotalRow key={t.jurisdiction} label={`${t.jurisdiction} @ ${t.rate}%`} value={t.amount} />
              ))}
              <tr>
                <td />
                <td>
                  <Rule variant="subtotal" />
                </td>
              </tr>
              <TotalRow emphasis label="Total" value={totals.total} />
              <tr>
                <td />
                <td>
                  <Rule variant="total" />
                </td>
              </tr>
            </tbody>
          </table>
        </section>
      </div>
    </div>
  );
}

function AmountCell({
  value,
  currency,
  onChange,
}: {
  value: number | null;
  currency: string;
  onChange: (v: number | null) => void;
}) {
  const [draft, setDraft] = React.useState("");
  const [focused, setFocused] = React.useState(false);
  React.useEffect(() => {
    if (focused) return;
    setDraft(value == null ? "" : formatMoneyInput(value, currency));
  }, [value, currency, focused]);
  return (
    <td className="px-3 py-3">
      <input
        aria-label="Line amount"
        className="numeric h-10 w-32 rounded-sm border border-border bg-surface px-2 text-right text-body outline-none focus-visible:border-accent"
        inputMode="decimal"
        onBlur={() => {
          setFocused(false);
          onChange(parseMoneyInput(draft, currency));
        }}
        onChange={(e) => {
          setDraft(e.target.value);
          onChange(parseMoneyInput(e.target.value, currency));
        }}
        onFocus={() => setFocused(true)}
        type="text"
        value={draft}
      />
    </td>
  );
}

function Row({ label, value }: { label: string; value: MoneyValue }) {
  return (
    <div className="flex items-baseline justify-between gap-4">
      <dt className="text-body text-text-secondary">{label}</dt>
      <dd>
        <Money accounting value={value} />
      </dd>
    </div>
  );
}

function TotalRow({ label, value, emphasis }: { label: string; value: MoneyValue; emphasis?: boolean }) {
  return (
    <tr>
      <th
        className={cn(
          "py-1 pr-6 text-left text-body font-normal",
          emphasis ? "font-medium text-text-primary" : "text-text-secondary",
        )}
        scope="row"
      >
        {label}
      </th>
      <td className="py-1 text-right">
        <Money accounting size={emphasis ? "md" : "sm"} value={value} />
      </td>
    </tr>
  );
}

The accounting it encodes

Concepts this component renders. Each one is defined once, in the lexicon, and used identically in the code and the copy.

Also in Receivables (AR)

See also

A component is specified in one place, defined in another, and running in a third. All three, from here.

Elsewhere in the system

Where InvoiceForm sits in the rest of the system — the live section it renders in, the calculators that compute what it displays, and the ledger payloads it is fed from.

Components are copied into your repository and meant to be edited — rounding policy, fiscal calendar and compliance copy differ per company.

Told when Receivables (AR) changes

Components are copied into your repo, so a fix here does not reach you on its own. One email when a component in this family changes in a way that needs a migration — and nothing when it does not.

One address, no list rental, unsubscribe in one click.

Works in your QuickBooks Online or Xero file

Get your books closed every month

Lopifi is building AI bookkeeping that keeps your books closed on US GAAP as transactions happen, with a CPA review every quarter, for $200 a month. We’re not open yet.

$200/month when we open. No card now.