Skip to content

ThreeWayMatch

Line-level variances, not header totals.
Implemented
Status
Implemented
Family
11 of 13
Registry
@lopifi/three-way-match
npx shadcn@latest add @lopifi/theme @lopifi/three-way-match

The component, rendering

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

Preview

The four-layer spec

PO, goods receipt, and invoice side by side, line by line, with differences highlighted at the line level. A header total that matches while lines don't is how overbilling hides. Tolerances displayed. A variance requires a disposition — accept with reason, request a vendor credit, partial-pay, or reject — never a silent pass.

Lifted verbatim from Payables (AP). 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/three-way-match.tsx

Lopifi dependencies · 8
buttoncnformat-moneyiconsmoneymoney.typestooltipuse-scroll-edges
npm packages
@base-ui-components/reactclass-variance-authorityclsxtailwind-merge
Registry entry
/r/three-way-match.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/three-way-match.tsx
"use client";

import * as React from "react";
import { useScrollEdges } from "@/hooks/ledger/use-scroll-edges";
import { cn } from "@/lib/ledger/cn";
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 MatchLine = {
  id: string;
  description: string;
  po: { quantity: number; unitPrice: MoneyValue; total: MoneyValue };
  receipt: { quantity: number } | null;
  invoice: { quantity: number; unitPrice: MoneyValue; total: MoneyValue };
};

export type Tolerance = { quantityPercent: number; pricePercent: number };

export type MatchDisposition = "accept-with-reason" | "request-credit" | "partial-pay" | "reject";

export interface ThreeWayMatchProps {
  className?: string;
  lines: MatchLine[];
  /** Caps the scroller so the grouped header and the line column can freeze. */
  maxHeight?: number;
  onDisposition?: (lineId: string, disposition: MatchDisposition, reason: string) => void;
  tolerance: Tolerance;
}

/**
 * PO, goods receipt and invoice side by side, **line by line**. A header
 * total that matches while the lines don't is how overbilling hides.
 *
 * A variance requires a disposition — never a silent pass.
 */
export function ThreeWayMatch({
  lines,
  tolerance,
  onDisposition,
  maxHeight = 520,
  className,
}: ThreeWayMatchProps) {
  const scroller = useScrollEdges<HTMLDivElement>();
  return (
    <div className={cn("space-y-3", className)}>
      <p className="text-caption text-text-secondary">
        Tolerances in force: quantity ±<span className="numeric">{tolerance.quantityPercent}%</span>, price ±
        <span className="numeric">{tolerance.pricePercent}%</span>. Matching is line by line, not on header
        totals.
      </p>

      <div
        className="ledger-frozen scrollbar-thin rounded-xl border border-border bg-surface"
        ref={scroller}
        style={{ maxHeight }}
      >
        <table className="w-full min-w-[900px]">
          <caption className="sr-only">Three-way match by line</caption>
          <thead>
            <tr className="border-b border-border-subtle">
              <th
                className="py-3 pl-6 pr-3 text-left text-label font-medium text-text-secondary"
                rowSpan={2}
                scope="col"
              >
                Line
              </th>
              <th
                className="border-l border-border-subtle px-3 py-2 text-center text-label font-medium text-text-secondary"
                colSpan={2}
                scope="col"
              >
                Purchase order
              </th>
              <th
                className="border-l border-border-subtle px-3 py-2 text-center text-label font-medium text-text-secondary"
                scope="col"
              >
                Receipt
              </th>
              <th
                className="border-l border-border-subtle px-3 py-2 text-center text-label font-medium text-text-secondary"
                colSpan={2}
                scope="col"
              >
                Invoice
              </th>
              <th
                className="border-l border-border-subtle py-3 pl-3 pr-6 text-left text-label font-medium text-text-secondary"
                rowSpan={2}
                scope="col"
              >
                Variance
              </th>
            </tr>
            <tr className="border-b border-border-subtle">
              {[
                { key: "po-qty", label: "Qty" },
                { key: "po-price", label: "Unit price" },
                { key: "received-qty", label: "Qty received" },
                { key: "invoice-qty", label: "Qty" },
                { key: "invoice-price", label: "Unit price" },
              ].map(({ key, label }, i) => (
                <th
                  className={cn(
                    "px-3 py-2 text-right text-caption text-text-secondary",
                    (i === 0 || i === 2 || i === 3) && "border-l border-border-subtle",
                  )}
                  key={key}
                  scope="col"
                >
                  {label}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {lines.map((l) => {
              const receivedQty = l.receipt?.quantity ?? 0;
              const qtyVariance = l.invoice.quantity - receivedQty;
              const qtyOut =
                Math.abs(qtyVariance) / Math.max(1, receivedQty) > tolerance.quantityPercent / 100;
              const priceDelta = Number(l.invoice.unitPrice.amount) - Number(l.po.unitPrice.amount);
              const priceOut =
                Math.abs(priceDelta) / Math.max(1, Number(l.po.unitPrice.amount)) >
                tolerance.pricePercent / 100;
              const clean = !qtyOut && !priceOut && l.receipt !== null;

              return (
                <React.Fragment key={l.id}>
                  <tr className={cn("border-b border-border-subtle", !clean && "bg-negative-subtle")}>
                    <th className="py-3 pl-6 pr-3 text-left text-body font-normal" scope="row">
                      {l.description}
                    </th>
                    <td className="numeric border-l border-border-subtle px-3 py-3 text-right text-figure-sm">
                      {l.po.quantity}
                    </td>
                    <td className="px-3 py-3 text-right">
                      <Money accounting value={l.po.unitPrice} />
                    </td>
                    <td className="numeric border-l border-border-subtle px-3 py-3 text-right text-figure-sm">
                      {l.receipt ? receivedQty : <span className="text-warning">not received</span>}
                    </td>
                    <td className="numeric border-l border-border-subtle px-3 py-3 text-right text-figure-sm">
                      {l.invoice.quantity}
                    </td>
                    <td className="px-3 py-3 text-right">
                      <Money accounting value={l.invoice.unitPrice} />
                    </td>
                    <td className="border-l border-border-subtle py-3 pl-3 pr-6 text-left">
                      {clean ? (
                        <span className="inline-flex items-center gap-1 text-caption text-positive">
                          <CheckIcon aria-hidden="true" className="size-3.5" />
                          Within tolerance
                        </span>
                      ) : (
                        <span className="inline-flex items-start gap-1 text-caption text-negative">
                          <ExclamationTriangleIcon aria-hidden="true" className="mt-0.5 size-3.5 shrink-0" />
                          <span>
                            {qtyOut ? (
                              <span className="block">
                                Quantity out by <span className="numeric">{qtyVariance}</span>
                              </span>
                            ) : null}
                            {priceOut ? (
                              <span className="block">
                                Unit price out by{" "}
                                <Money
                                  accounting
                                  size="xs"
                                  tone="inherit"
                                  value={{
                                    amount: priceDelta,
                                    currency: l.po.unitPrice.currency,
                                  }}
                                />
                              </span>
                            ) : null}
                            {!l.receipt ? <span className="block">No goods receipt</span> : null}
                          </span>
                        </span>
                      )}
                    </td>
                  </tr>
                  {!clean ? (
                    <tr className="border-b border-border-subtle bg-negative-subtle">
                      <td className="py-2 pl-6 pr-6" colSpan={7}>
                        <DispositionRow lineId={l.id} onDisposition={onDisposition} />
                      </td>
                    </tr>
                  ) : null}
                </React.Fragment>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function DispositionRow({
  lineId,
  onDisposition,
}: {
  lineId: string;
  onDisposition?: (id: string, d: MatchDisposition, reason: string) => void;
}) {
  const [disposition, setDisposition] = React.useState<MatchDisposition | "">("");
  const [reason, setReason] = React.useState("");

  return (
    <div className="flex flex-wrap items-center gap-2">
      <span className="text-caption font-medium">This variance needs a disposition:</span>
      <select
        aria-label="Variance 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) => setDisposition(e.target.value as MatchDisposition)}
        value={disposition}
      >
        <option value="">Choose…</option>
        <option value="accept-with-reason">Accept with a reason</option>
        <option value="request-credit">Request a vendor credit</option>
        <option value="partial-pay">Partial-pay the matched portion</option>
        <option value="reject">Reject the invoice</option>
      </select>
      <input
        aria-label="Disposition reason"
        className="h-8 flex-1 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)}
        placeholder="Reason"
        value={reason}
      />
      <Button
        disabled={!disposition || reason.trim().length < 3}
        onClick={() => onDisposition?.(lineId, disposition as MatchDisposition, reason)}
        size="sm"
        variant="primary"
      >
        Record
      </Button>
    </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 Payables (AP)

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 ThreeWayMatch 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 Payables (AP) 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.