RendyUI 中文

Blocks / Profit and loss

Profit and loss

Finance · React / TypeScript Free

Recorded demo

Profit and loss preview

Source

pnl-overview.tsx
/* Profit and loss — free block published by UI Stacks (public page source).
   Kept verbatim: the author publishes this block free, in full, at https://uistacks.dev/blocks/pnl-overview
   See replica/README.md for provenance. */
"use client";

import { useEffect, useId, useRef, useState } from "react";
import { motion, useReducedMotion } from "motion/react";
import { StatCard } from "../components/stat-card";
import { GroupedBar } from "../components/grouped-bar";
import { Tabs } from "../components/tabs";

/* ── Sample data: replace with your own ─────────────────────── */

const SCOPE = { workspace: "UI Stacks", stores: "All 6 stores", month: "October 2026", previous: "September" };

/** Net sales and total costs (cost of goods + operating costs) per month, Nov 2025 to Oct 2026. */
const MONTHS = [
  { label: "Nov", year: 2025, revenue: 101_600, costs: 88_700 },
  { label: "Dec", year: 2025, revenue: 118_900, costs: 99_800 },
  { label: "Jan", year: 2026, revenue: 92_400, costs: 84_100 },
  { label: "Feb", year: 2026, revenue: 94_800, costs: 84_600 },
  { label: "Mar", year: 2026, revenue: 99_300, costs: 87_100 },
  { label: "Apr", year: 2026, revenue: 101_900, costs: 88_900 },
  { label: "May", year: 2026, revenue: 104_200, costs: 91_000 },
  { label: "Jun", year: 2026, revenue: 108_900, costs: 94_100 },
  { label: "Jul", year: 2026, revenue: 112_400, costs: 96_000 },
  { label: "Aug", year: 2026, revenue: 115_100, costs: 98_300 },
  { label: "Sep", year: 2026, revenue: 120_200, costs: 102_600 },
  { label: "Oct", year: 2026, revenue: 128_400, costs: 107_837 },
];

/** October in detail. Gross margin is net sales less cost of goods; net profit is what is left after operating costs. */
const OCTOBER = { netSales: 128_400, grossMargin: 64.2, marginWas: 63.1, operating: 61_870, operatingWas: 60_420 };

/** Where October's $107,837 of costs went. */
const COSTS = [
  { id: "goods", label: "Coffee, milk and bakery", note: "Cost of goods", amount: 45_967 },
  { id: "payroll", label: "Payroll", note: "48 people", amount: 36_480 },
  { id: "rent", label: "Rent and utilities", note: "6 stores", amount: 14_760 },
  { id: "fees", label: "Card fees and software", note: "Stripe, Shopify, Notion", amount: 4310 },
  { id: "repairs", label: "Equipment and repairs", note: "2 espresso machines", amount: 4180 },
  { id: "marketing", label: "Marketing", note: "Holiday menu launch", amount: 2140 },
];

/** Seeded random numbers, so the server and the browser draw the same lines. */
function seeded(seed: number) {
  let s = seed >>> 0;
  return () => {
    s = (s + 0x6d2b79f5) >>> 0;
    let t = s;
    t = Math.imul(t ^ (t >>> 15), t | 1);
    t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

const OCT_DAYS = Array.from({ length: 31 }, (_, i) => `Oct ${i + 1}`);
/** 31 daily values with a weekly rhythm and a slow climb that add up to `sum` (or average to it with `mean`). */
function month(seed: number, sum: number, wobble = 0.05, mean = false) {
  const r = seeded(seed);
  const raw = OCT_DAYS.map((_, i) => (1 + 0.004 * i) * (1 + wobble * Math.sin(((i + 3) / 7) * 2 * Math.PI)) * (1 - wobble / 2 + wobble * r()));
  const total = raw.reduce((a, b) => a + b, 0);
  return raw.map((v) => (mean ? (v * sum * raw.length) / total : Math.round((v * sum) / total)));
}

const NET_SALES = month(11, OCTOBER.netSales);
const OPEX = month(12, OCTOBER.operating, 0.03);
const MARGIN = month(13, OCTOBER.grossMargin, 0.012, true).map((v) => Math.round(v * 10) / 10);
const PROFIT_DAILY = NET_SALES.map((s, i) => Math.round(s * (MARGIN[i] / 100) - OPEX[i]));

/* ── Helpers ────────────────────────────────────────────────── */

const money = (v: number) => v.toLocaleString("en-US", { style: "currency", currency: "USD", maximumFractionDigits: 0 });
const k = (v: number) => `$${Math.round(v / 1000)}k`;
const pct = (v: number) => `${v.toFixed(1)}%`;
const spring = { type: "spring", stiffness: 420, damping: 34 } as const;

type Span = "6" | "12";

/** The block's own width, for the chart height (CSS container queries handle the layout). */
function useWidth<T extends HTMLElement>() {
  const ref = useRef<T>(null);
  const [width, setWidth] = useState(0);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const ro = new ResizeObserver(([e]) => setWidth(e.contentRect.width));
    ro.observe(el);
    return () => ro.disconnect();
  }, []);
  return [ref, width] as const;
}

/** A box's height, so the chart can fill the card when the cost list beside it is taller. */
function useHeight<T extends HTMLElement>() {
  const ref = useRef<T>(null);
  const [height, setHeight] = useState(0);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const ro = new ResizeObserver(([e]) => setHeight(e.contentRect.height));
    ro.observe(el);
    return () => ro.disconnect();
  }, []);
  return [ref, height] as const;
}

/** GroupedBar draws its legend (24 + 16 gap) and 48 px of axes around the plot. */
const CHART_CHROME = 88;

/* ── The block ──────────────────────────────────────────────── */

/** October's profit and loss: four headline numbers, revenue against costs by month, and where the costs went. */
export default function PnlOverviewBlock({ className = "" }: { className?: string }) {
  const reduce = useReducedMotion();
  const titleId = useId();
  const [span, setSpan] = useState<Span>("6");
  const [said, setSaid] = useState("");
  const [rootRef, width] = useWidth<HTMLElement>();
  const [plotRef, plotBox] = useHeight<HTMLDivElement>();
  const basePlot = width && width < 480 ? 200 : 280;

  const shown = MONTHS.slice(-Number(span));
  const oct = MONTHS[MONTHS.length - 1];
  const sep = MONTHS[MONTHS.length - 2];
  const profit = oct.revenue - oct.costs;
  const profitWas = sep.revenue - sep.costs;
  const costTotal = COSTS.reduce((a, c) => a + c.amount, 0);
  const top = Math.max(...COSTS.map((c) => c.amount));
  const first = shown[0];
  const range = `${first.label}${first.year !== oct.year ? ` ${first.year}` : ""} – ${oct.label} ${oct.year}`;
  const shownProfit = shown.reduce((a, m) => a + m.revenue - m.costs, 0);

  return (
    <section ref={rootRef} aria-labelledby={titleId} className={"@container w-full min-w-0 " + className}>
      <div className="flex flex-col gap-4">
        <header className="px-1">
          <h2 id={titleId} className="text-[15px] font-medium leading-5 text-fg">
            Profit and loss
          </h2>
          <p className="mt-0.5 truncate text-[13px] leading-5 text-fg-muted">
            {SCOPE.workspace} · {SCOPE.stores} · {SCOPE.month}
          </p>
        </header>

        <div className="grid grid-cols-1 gap-4 @min-[480px]:grid-cols-2 @min-[1024px]:grid-cols-4">
          <StatCard label="Net sales" value={OCTOBER.netSales} format={money} delta={(oct.revenue / sep.revenue - 1) * 100} comparison={`vs ${SCOPE.previous}`} data={NET_SALES} labels={OCT_DAYS} />
          <StatCard
            label="Gross margin"
            value={OCTOBER.grossMargin}
            format={pct}
            delta={OCTOBER.grossMargin - OCTOBER.marginWas}
            deltaLabel={`${(OCTOBER.grossMargin - OCTOBER.marginWas).toFixed(1)} pts`}
            comparison={`vs ${SCOPE.previous}`}
            data={MARGIN}
            labels={OCT_DAYS}
          />
          <StatCard
            label="Operating costs"
            value={OCTOBER.operating}
            format={money}
            delta={(OCTOBER.operating / OCTOBER.operatingWas - 1) * 100}
            goodDirection="down"
            comparison={`vs ${SCOPE.previous}`}
            data={OPEX}
            labels={OCT_DAYS}
          />
          <StatCard label="Net profit" value={profit} format={money} delta={(profit / profitWas - 1) * 100} comparison={`vs ${SCOPE.previous}`} data={PROFIT_DAILY} labels={OCT_DAYS} />
        </div>

        <div className="grid grid-cols-1 gap-4 @min-[1024px]:grid-cols-[minmax(0,1fr)_360px]">
          <section aria-label="Revenue and costs by month" className="flex min-w-0 flex-col rounded-[20px] bg-surface p-5 shadow-[var(--shadow-card)]">
            <div className="mb-4 flex flex-col gap-3 @min-[480px]:flex-row @min-[480px]:items-start">
              <div className="min-w-0 flex-1">
                <h3 className="text-[15px] font-medium leading-5 text-fg">Revenue and costs</h3>
                <p className="mt-0.5 truncate text-[13px] leading-5 text-fg-muted tabular-nums">
                  {range} · {money(shownProfit)} profit
                </p>
              </div>
              <Tabs
                variant="pill"
                size="sm"
                label="Months shown"
                value={span}
                onValueChange={(v) => {
                  setSpan(v as Span);
                  setSaid(`Showing the last ${v} months`);
                }}
                items={[
                  { value: "6", label: "6 months" },
                  { value: "12", label: "12 months" },
                ]}
                className="self-start"
              />
            </div>
            {/* The plot grows into any room the taller card beside it leaves; the chart sits out of flow so it never props the row open. */}
            <div ref={plotRef} className="relative flex-1" style={{ minHeight: basePlot + CHART_CHROME }}>
              <div className="absolute inset-0">
                <GroupedBar
                  key={span}
                  categories={shown.map((m) => m.label)}
                  series={[
                    { name: "Revenue", values: shown.map((m) => m.revenue) },
                    { name: "Costs", values: shown.map((m) => m.costs) },
                  ]}
                  format={money}
                  formatAxis={k}
                  groupLabel={(c, i) => `${c} ${shown[i].year}`}
                  max={150_000}
                  height={Math.max(basePlot, Math.floor(plotBox) - CHART_CHROME)}
                  label={`Revenue and costs by month, ${range}`}
                />
              </div>
            </div>
          </section>

          <section aria-label="October costs" className="flex min-w-0 flex-col rounded-[20px] bg-surface p-5 shadow-[var(--shadow-card)]">
            <h3 className="text-[15px] font-medium leading-5 text-fg">Where the money went</h3>
            <p className="mt-0.5 truncate text-[13px] leading-5 text-fg-muted tabular-nums">
              {money(costTotal)} of costs in October
            </p>
            <ul className="mt-4 flex flex-col gap-3.5">
              {COSTS.map((c, i) => (
                <li key={c.id} className="flex flex-col gap-1.5">
                  <div className="flex items-start gap-2">
                    <span className="min-w-0 flex-1">
                      <span className="block truncate text-[14px] leading-5 text-fg">{c.label}</span>
                      <span className="block truncate text-[12px] leading-4 text-fg-muted">{c.note}</span>
                    </span>
                    <span className="shrink-0 text-right">
                      <span className="block text-[14px] font-medium leading-5 text-fg tabular-nums">{money(c.amount)}</span>
                      <span className="block text-[12px] leading-4 text-fg-muted tabular-nums">
                        {Math.round((c.amount / costTotal) * 100)}%<span className="sr-only"> of costs</span>
                      </span>
                    </span>
                  </div>
                  <span aria-hidden className="block h-1.5 w-full overflow-hidden rounded-full bg-[color-mix(in_srgb,var(--fg)_6%,transparent)]">
                    <motion.span
                      className={`block h-full rounded-full ${i === 0 ? "bg-[var(--series-1)]" : "bg-[color-mix(in_srgb,var(--fg)_22%,transparent)]"}`}
                      initial={reduce ? false : { width: 0 }}
                      animate={{ width: `${(c.amount / top) * 100}%` }}
                      transition={reduce ? { duration: 0 } : { ...spring, delay: i * 0.04 }}
                    />
                  </span>
                </li>
              ))}
            </ul>
            <div aria-hidden className="min-h-4 flex-1" />
            <div className="flex items-start gap-2 border-t border-border pt-4">
              <span className="min-w-0 flex-1">
                <span className="block truncate text-[14px] font-medium leading-5 text-fg">Net profit</span>
                <span className="block truncate text-[12px] leading-4 text-fg-muted">Net sales less every cost</span>
              </span>
              <span className="shrink-0 text-right">
                <span className="block text-[14px] font-medium leading-5 text-fg tabular-nums">{money(OCTOBER.netSales - costTotal)}</span>
                <span className="block text-[12px] leading-4 text-fg-muted tabular-nums">
                  {(((OCTOBER.netSales - costTotal) / OCTOBER.netSales) * 100).toFixed(1)}%<span className="sr-only"> of net sales</span>
                </span>
              </span>
            </div>
          </section>
        </div>
      </div>
      <span role="status" aria-live="polite" className="sr-only">
        {said}
      </span>
    </section>
  );
}

Usage

Add the TSX to your React project and install the required dependencies. Styles use Tailwind CSS and theme tokens。

Package dependencies · motion、react

Shared source · grouped-bar.tsx、stat-card.tsx、tabs.tsx