Skip to content

CashApplication

The highest-value screen in AR. Every case, not just the happy one.
Implemented
Status
Implemented
Family
10 of 13
Registry
@lopifi/cash-application
npx shadcn@latest add @lopifi/theme @lopifi/cash-application

The component, rendering

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

Preview

The four-layer spec

The highest-value screen in AR, and the one most tools handle worst.

Left: unapplied payments. Right: open invoices for that customer. A running sum against the payment amount as invoices are selected, so the user sees when the selection is exact.

Every case is a first-class path, not just the happy one: exact, partial, overpayment, lump-sum-to-many, short pay, no-invoice, duplicate, bank fee deducted in transit, FX settlement difference.

Rules: unapplied cash is never revenue; it is shown separately within AR, and a customer's net credit balance is flagged for reclassification to a liability · a remaining difference always requires a disposition (write-off with reason and account, leave unapplied, or dispute) · write-off thresholds enforce approval · applying is reversible and audited.

The match uses the reconciliation animation — one of the four sanctioned moments.

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/cash-application.tsx

Lopifi dependencies · 9
buttoncnfiscal-periodformat-moneyiconsmoneymoney.typestooltipuse-media-query
npm packages
@base-ui-components/reactclass-variance-authorityclsxtailwind-merge
Registry entry
/r/cash-application.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/cash-application.tsx
"use client";

import * as React from "react";
import { useReducedMotion } from "@/hooks/ledger/use-media-query";
import { cn } from "@/lib/ledger/cn";
import { formatDate } from "@/lib/ledger/fiscal-period";
import type { MoneyValue } from "@/lib/ledger/money.types";
import { Button } from "@/components/ledger/button";
import { CheckIcon, ExclamationTriangleIcon } from "@/components/ledger/icons";
import { Money } from "@/components/ledger/money";

export type UnappliedPayment = {
  id: string;
  customer: string;
  receivedAt: Date;
  amount: MoneyValue;
  reference: string;
};

export type OpenInvoice = {
  id: string;
  number: string;
  dueDate: Date;
  balance: MoneyValue;
};

export type Disposition =
  | { kind: "write-off"; reason: string; account: string }
  | { kind: "leave-unapplied" }
  | { kind: "dispute"; reason: string };

export interface CashApplicationProps {
  className?: string;
  invoices: OpenInvoice[];
  onApply?: (invoiceIds: string[], disposition: Disposition | null) => void;
  payment: UnappliedPayment;
  /** Write-offs above this need approval. */
  writeOffThreshold: MoneyValue;
}

const WRITE_OFF_REASONS = [
  "Bank fee deducted in transit",
  "FX settlement difference",
  "Short pay — disputed line",
  "Early-payment discount taken",
  "Immaterial residual",
];

/**
 * The highest-value screen in AR, and the one most tools handle worst.
 *
 * Every case is a first-class path, not just the happy one: exact, partial,
 * overpayment, lump-sum-to-many, short pay, bank fee in transit, FX
 * settlement difference.
 *
 * Unapplied cash is never revenue. A remaining difference
 * always requires a disposition.
 */
export function CashApplication({
  payment,
  invoices,
  writeOffThreshold,
  onApply,
  className,
}: CashApplicationProps) {
  const [selected, setSelected] = React.useState<string[]>([]);
  const [dispositionKind, setDispositionKind] = React.useState<Disposition["kind"] | "">("");
  const [reason, setReason] = React.useState(WRITE_OFF_REASONS[0]);
  const [matching, setMatching] = React.useState(false);
  const reduced = useReducedMotion();

  const currency = payment.amount.currency;
  const applied = invoices
    .filter((i) => selected.includes(i.id))
    .reduce((s, i) => s + Number(i.balance.amount), 0);
  const paymentAmount = Number(payment.amount.amount);
  const remaining = paymentAmount - applied;

  const exact = remaining === 0;
  const overpayment = remaining > 0 && selected.length > 0;
  const shortfall = remaining < 0;
  const needsDisposition = !exact && selected.length > 0;
  const exceedsThreshold =
    Math.abs(remaining) > Number(writeOffThreshold.amount) && dispositionKind === "write-off";

  const caseLabel = exact
    ? "Exact application"
    : shortfall
      ? "Payment does not cover the selected invoices"
      : selected.length > 1
        ? "Lump sum applied to several invoices, with a residual"
        : selected.length === 1
          ? "Partial payment or short pay"
          : "No invoices selected";

  const apply = () => {
    if (reduced) {
      onApply?.(selected, buildDisposition());
      return;
    }
    setMatching(true);
    setTimeout(() => {
      setMatching(false);
      onApply?.(selected, buildDisposition());
    }, 520);
  };

  const buildDisposition = (): Disposition | null => {
    if (exact) return null;
    if (dispositionKind === "write-off")
      return { account: "6900 · Bad debt expense", kind: "write-off", reason };
    if (dispositionKind === "dispute") return { kind: "dispute", reason };
    if (dispositionKind === "leave-unapplied") return { kind: "leave-unapplied" };
    return null;
  };

  return (
    <div className={cn("space-y-4", className)}>
      <div
        className={cn(
          "sticky top-0 z-sticky flex flex-wrap items-center justify-between gap-4 rounded-md border px-4 py-3",
          exact ? "border-positive bg-positive-subtle" : "border-border bg-surface",
        )}
      >
        <span className="flex flex-wrap items-baseline gap-3">
          <span className="text-caption text-text-secondary">
            Payment <Money size="xs" tone="inherit" value={payment.amount} />
          </span>
          <span className="text-caption text-text-secondary">
            Applied <Money size="xs" tone="inherit" value={{ amount: applied, currency }} />
          </span>
        </span>
        <span className="flex items-baseline gap-2">
          <span className="text-label font-medium">Remaining</span>
          <Money
            accounting
            className={exact ? "text-positive" : "text-negative"}
            size="md"
            value={{ amount: remaining, currency }}
          />
        </span>
      </div>

      <p className="text-caption text-text-secondary">{caseLabel}</p>

      <div className="grid gap-4 lg:grid-cols-2">
        <section className="overflow-hidden rounded-xl border border-border bg-surface">
          <h3 className="border-b border-border-subtle px-4 py-3 text-label font-medium text-text-secondary">
            Unapplied payment
          </h3>
          <div className="px-4 py-3">
            <p className="text-body font-medium">{payment.customer}</p>
            <p className="text-caption text-text-secondary">
              Received {formatDate(payment.receivedAt)} · ref{" "}
              <span className="reference-numeric">{payment.reference}</span>
            </p>
            <Money className="mt-2" size="lg" value={payment.amount} />
            <p className="mt-2 rounded-sm bg-surface-sunken px-2 py-1 text-caption text-text-secondary">
              Held as a liability until applied. It does not reduce accounts receivable.
            </p>
          </div>
        </section>

        <section className="overflow-hidden rounded-xl border border-border bg-surface">
          <h3 className="border-b border-border-subtle px-4 py-3 text-label font-medium text-text-secondary">
            Open invoices — {payment.customer}
          </h3>
          <ul>
            {invoices.map((i, idx) => (
              <li
                className={cn(
                  "flex items-center gap-3 border-b border-border-subtle px-4 py-3 last:border-b-0",
                  selected.includes(i.id) && "bg-surface-selected",
                )}
                key={i.id}
                style={
                  matching && selected.includes(i.id)
                    ? {
                        animation: `ledger-match 320ms var(--ease-out) ${Math.min(idx * 40, 240)}ms both`,
                      }
                    : undefined
                }
              >
                <input
                  aria-label={`Apply to invoice ${i.number}`}
                  checked={selected.includes(i.id)}
                  className="size-4 accent-[var(--accent)]"
                  onChange={() =>
                    setSelected((s) => (s.includes(i.id) ? s.filter((x) => x !== i.id) : [...s, i.id]))
                  }
                  type="checkbox"
                />
                <span className="min-w-0 flex-1">
                  <span className="reference-numeric block text-body">{i.number}</span>
                  <span className="block text-caption text-text-secondary">
                    Due <span className="numeric">{formatDate(i.dueDate)}</span>
                  </span>
                </span>
                <Money accounting value={i.balance} />
              </li>
            ))}
          </ul>
        </section>
      </div>

      {needsDisposition ? (
        <div className="rounded-md border border-[var(--warning)] bg-warning-subtle p-4">
          <p className="flex items-center gap-2 text-body">
            <ExclamationTriangleIcon aria-hidden="true" className="size-4 shrink-0 text-warning" />A
            difference of <Money accounting tone="inherit" value={{ amount: remaining, currency }} /> remains.
            It needs a disposition before this can be applied.
          </p>
          <div className="mt-3 flex flex-wrap items-center gap-3">
            <select
              aria-label="Disposition"
              className="h-8 rounded-sm border border-border bg-surface px-2 text-label outline-none focus-visible:border-accent focus-visible:ring-2 focus-visible:ring-accent-subtle"
              onChange={(e) => setDispositionKind(e.target.value as Disposition["kind"] | "")}
              value={dispositionKind}
            >
              <option value="">Choose a disposition…</option>
              <option value="write-off">Write off</option>
              <option value="leave-unapplied">Leave unapplied</option>
              <option value="dispute">Raise a dispute</option>
            </select>
            {dispositionKind === "write-off" || dispositionKind === "dispute" ? (
              <select
                aria-label="Reason"
                className="h-8 rounded-sm border border-border bg-surface px-2 text-label outline-none focus-visible:border-accent focus-visible:ring-2 focus-visible:ring-accent-subtle"
                onChange={(e) => setReason(e.target.value)}
                value={reason}
              >
                {WRITE_OFF_REASONS.map((r) => (
                  <option key={r}>{r}</option>
                ))}
              </select>
            ) : null}
          </div>
          {exceedsThreshold ? (
            <p className="mt-2 text-caption text-negative">
              This write-off exceeds the <Money size="xs" tone="inherit" value={writeOffThreshold} />{" "}
              threshold and needs approval.
            </p>
          ) : null}
          {overpayment && dispositionKind === "leave-unapplied" ? (
            <p className="mt-2 text-caption text-text-secondary">
              The residual stays as unapplied cash — a liability, not a reduction of AR.
            </p>
          ) : null}
        </div>
      ) : null}

      <div className="flex flex-wrap items-center gap-3">
        <Button
          disabled={selected.length === 0 || (needsDisposition && !dispositionKind)}
          onClick={apply}
          variant="primary"
        >
          {exact ? (
            <>
              <CheckIcon aria-hidden="true" className="size-4" />
              Apply exactly
            </>
          ) : (
            `Apply to ${selected.length} invoice${selected.length === 1 ? "" : "s"}`
          )}
        </Button>
        <p className="text-caption text-text-tertiary">Applying is reversible and audited.</p>
      </div>
    </div>
  );
}

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 CashApplication 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.