Skip to content

JournalEntryForm

Line grid with live balance check and dimension capture.
Implemented
Status
Implemented
Family
9 of 13
Registry
@lopifi/journal-entry-form
npx shadcn@latest add @lopifi/theme @lopifi/journal-entry-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

Line grid with account, dimensions, debit, credit, memo. Running balance check updates live at the bottom. Tab moves across the row, Enter adds a line, and the amount fields follow AmountInput rules. Reads requiredDimensions from the account the moment it's picked and adds those fields inline. Blocks posting into a closed period with the cutoff explanation, not a bare rejection.

Lifted verbatim from Accounting core (GL). 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/journal-entry-form.tsx

Lopifi dependencies · 13
account-pickeraccounting.typesbuttoncncutoff-warningdimension-pickerfiscal-periodformat-moneyiconsmoneymoney.typesruletooltip
npm packages
@base-ui-components/reactclass-variance-authorityclsxtailwind-merge
Registry entry
/r/journal-entry-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/journal-entry-form.tsx
"use client";

import * as React from "react";
import type { Account, DimensionKey } from "@/lib/ledger/accounting.types";
import { cn } from "@/lib/ledger/cn";
import { formatMoneyInput, parseMoneyInput } from "@/lib/ledger/format-money";
import { AccountPicker } from "@/components/ledger/account-picker";
import { Button } from "@/components/ledger/button";
import { CutoffWarning } from "@/components/ledger/cutoff-warning";
import { DimensionPicker } from "@/components/ledger/dimension-picker";
import { CheckIcon, ExclamationTriangleIcon, PlusIcon, TrashIcon } from "@/components/ledger/icons";
import { Money } from "@/components/ledger/money";
import { Rule } from "@/components/ledger/rule";

type DraftLine = {
  key: string;
  account: Account | null;
  debit: number | null;
  credit: number | null;
  memo: string;
  dimensions: Partial<Record<DimensionKey, string>>;
};

export interface JournalEntryFormProps {
  accounts: Account[];
  className?: string;
  /** Posting into a closed period gets the cutoff explanation, not a bare
      rejection. */
  closedThrough?: Date;
  currency: string;
  onPost?: (lines: DraftLine[], date: string, description: string) => void;
}

const emptyLine = (): DraftLine => ({
  account: null,
  credit: null,
  debit: null,
  dimensions: {},
  key: Math.random().toString(36).slice(2),
  memo: "",
});

/**
 * Tab moves across the row, Enter adds a line, and the amount fields follow
 * the AmountInput rules. `requiredDimensions` is read from the account the
 * moment it is picked, and those fields appear inline.
 */
export function JournalEntryForm({
  accounts,
  currency,
  closedThrough,
  onPost,
  className,
}: JournalEntryFormProps) {
  const [lines, setLines] = React.useState<DraftLine[]>([emptyLine(), emptyLine()]);
  const [date, setDate] = React.useState(() => new Date().toISOString().slice(0, 10));
  const [description, setDescription] = React.useState("");

  const totalDebit = lines.reduce((s, l) => s + (l.debit ?? 0), 0);
  const totalCredit = lines.reduce((s, l) => s + (l.credit ?? 0), 0);
  const balanced = totalDebit === totalCredit && totalDebit > 0;

  const entryDate = new Date(`${date}T00:00:00`);
  const inClosedPeriod = closedThrough != null && entryDate <= closedThrough;

  const missingDimensions = lines.some(
    (l) => l.account?.requiredDimensions.some((d) => !l.dimensions[d]) ?? false,
  );

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

  return (
    <div className={cn("space-y-4", className)}>
      <div className="grid gap-3 sm:grid-cols-[160px_1fr]">
        <label className="block">
          <span className="mb-2 block text-label font-medium text-text-secondary">Date</span>
          <input
            className="numeric h-10 w-full rounded-sm border border-border bg-surface px-3 text-body outline-none focus-visible:border-accent"
            onChange={(e) => setDate(e.target.value)}
            type="date"
            value={date}
          />
        </label>
        <label className="block">
          <span className="mb-2 block text-label font-medium text-text-secondary">Description</span>
          <input
            className="h-10 w-full rounded-sm border border-border bg-surface px-3 text-body outline-none focus-visible:border-accent"
            onChange={(e) => setDescription(e.target.value)}
            placeholder="Accrue September professional fees"
            value={description}
          />
        </label>
      </div>

      {inClosedPeriod && closedThrough ? (
        <CutoffWarning closedThrough={closedThrough} entryDate={entryDate} />
      ) : null}

      <div className="overflow-x-auto rounded-xl border border-border bg-surface">
        <table className="w-full min-w-[820px]">
          <caption className="sr-only">Journal entry lines</caption>
          <thead>
            <tr className="border-b border-border-subtle">
              <th className="px-4 py-2 text-left text-label font-medium text-text-secondary" scope="col">
                Account
              </th>
              <th className="px-3 py-2 text-left text-label font-medium text-text-secondary" scope="col">
                Dimensions
              </th>
              <th className="px-3 py-2 text-right text-label font-medium text-text-secondary" scope="col">
                Debit
              </th>
              <th className="px-3 py-2 text-right text-label font-medium text-text-secondary" scope="col">
                Credit
              </th>
              <th className="w-10 px-3 py-2" scope="col">
                <span className="sr-only">Remove</span>
              </th>
            </tr>
          </thead>
          <tbody>
            {lines.map((line) => (
              <tr className="border-b border-border-subtle align-top" key={line.key}>
                <td className="w-[280px] px-4 py-2">
                  <AccountPicker
                    accounts={accounts}
                    onValueChange={(account) => update(line.key, { account })}
                    value={line.account?.id ?? null}
                  />
                  <input
                    aria-label="Line memo"
                    className="mt-1 h-8 w-full rounded-sm border border-border bg-surface px-2 text-caption outline-none focus-visible:border-accent"
                    onChange={(e) => update(line.key, { memo: e.target.value })}
                    placeholder="Line memo"
                    value={line.memo}
                  />
                </td>
                <td className="px-3 py-2">
                  <DimensionPicker
                    onValueChange={(dimensions) => update(line.key, { dimensions })}
                    required={line.account?.requiredDimensions ?? ["entityId"]}
                    value={line.dimensions}
                  />
                </td>
                <AmountCell
                  currency={currency}
                  label="Debit"
                  onChange={(v) => update(line.key, { credit: v == null ? line.credit : null, debit: v })}
                  value={line.debit}
                />
                <AmountCell
                  currency={currency}
                  label="Credit"
                  onChange={(v) => update(line.key, { credit: v, debit: v == null ? line.debit : null })}
                  value={line.credit}
                />
                <td className="px-3 py-2">
                  <button
                    aria-label="Remove line"
                    className="press grid size-8 place-items-center rounded-sm text-text-tertiary hover:bg-surface-hover disabled:opacity-30"
                    disabled={lines.length <= 2}
                    onClick={() => setLines((prev) => prev.filter((l) => l.key !== line.key))}
                    type="button"
                  >
                    <TrashIcon aria-hidden="true" className="size-4" />
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
          <tfoot>
            <tr>
              <td colSpan={2} />
              <td className="px-3">
                <Rule variant="subtotal" />
              </td>
              <td className="px-3">
                <Rule variant="subtotal" />
              </td>
              <td />
            </tr>
            <tr>
              <th className="px-4 py-3 text-left text-label font-medium" colSpan={2} scope="row">
                Totals
              </th>
              <td className="px-3 py-3 text-right">
                <Money accounting size="md" value={{ amount: totalDebit, currency }} />
              </td>
              <td className="px-3 py-3 text-right">
                <Money accounting size="md" value={{ amount: totalCredit, currency }} />
              </td>
              <td />
            </tr>
          </tfoot>
        </table>
      </div>

      <div className="flex flex-wrap items-center gap-3">
        <Button onClick={() => setLines((prev) => [...prev, emptyLine()])} size="sm" variant="secondary">
          <PlusIcon aria-hidden="true" className="size-3.5" />
          Add line
        </Button>

        <p
          className={cn(
            "flex items-center gap-2 rounded-sm px-3 py-2 text-body",
            balanced ? "bg-positive-subtle text-positive" : "bg-surface-sunken text-text-secondary",
          )}
          role={balanced ? undefined : "status"}
        >
          {balanced ? (
            <CheckIcon aria-hidden="true" className="size-4" />
          ) : (
            <ExclamationTriangleIcon aria-hidden="true" className="size-4" />
          )}
          {balanced ? (
            "Balanced."
          ) : (
            <>
              Out of balance by{" "}
              <Money tone="inherit" value={{ amount: Math.abs(totalDebit - totalCredit), currency }} />
            </>
          )}
        </p>

        <Button
          className="ml-auto"
          disabled={!balanced || missingDimensions || !description.trim()}
          onClick={() => onPost?.(lines, date, description)}
          variant="primary"
        >
          Post entry
        </Button>
      </div>

      {missingDimensions ? (
        <p className="text-caption text-negative" role="alert">
          One or more lines are missing a dimension their account requires.
        </p>
      ) : null}
    </div>
  );
}

function AmountCell({
  value,
  currency,
  label,
  onChange,
}: {
  value: number | null;
  currency: string;
  label: 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 || value === 0 ? "" : formatMoneyInput(value, currency));
  }, [value, currency, focused]);

  return (
    <td className="px-3 py-2">
      <input
        aria-label={label}
        className="numeric h-10 w-full 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>
  );
}

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 Accounting core (GL)

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 JournalEntryForm 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 Accounting core (GL) 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.