Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

10.1 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.

import { cn, ScrollArea } from "@carbon/react";
import { Trans, useLingui } from "@lingui/react/macro";
import { memo, useMemo, useRef } from "react";
import {
  LuChevronDown,
  LuChevronRight,
  LuFolder,
  LuFolderOpen
} from "react-icons/lu";
import { useNavigate } from "react-router";
import { LevelLine, TreeView, useTree } from "~/components/TreeView";
import { useRealtime, useUrlParams } from "~/hooks";
import type { Chart } from "../../types";
import { reportFrameClassName, useReportColumnStep } from "./ColumnStepper";
import {
  accountsToFlatTree,
  filterAccounts,
  getDebitCredit
} from "./reportTree";

type TrialBalanceChart = Chart & {
  translatedBalance?: number;
  exchangeRate?: number;
};

type TrialBalanceTreeProps = {
  data: TrialBalanceChart[];
  showTranslated?: boolean;
  parentCurrency?: string | null;
  search: string;
  /** When provided, clicking a leaf account opens its ledger drill-down */
  ledgerPath?: (accountId: string) => string;
};

function formatCurrency(value: number): string {
  if (value === 0) return "-";
  return value.toLocaleString(undefined, {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  });
}

function formatPercent(value: number): string {
  if (!Number.isFinite(value)) return "-";
  return `${value.toLocaleString(undefined, {
    minimumFractionDigits: 1,
    maximumFractionDigits: 2
  })}%`;
}

const TrialBalanceTree = memo(
  ({
    data,
    showTranslated = false,
    parentCurrency,
    search,
    ledgerPath
  }: TrialBalanceTreeProps) => {
    const { t } = useLingui();
    const columnLabels = [
      t`Beginning`,
      t`Debits`,
      t`Credits`,
      t`Ending`,
      ...(showTranslated
        ? [t`Ending (${parentCurrency ?? "Translated"})`]
        : []),
      t`Ratio`
    ];
    // Phones: one value column at a time, starting on Ending.
    const {
      isPhone,
      index: columnIndex,
      estimatedRowHeight,
      stepper
    } = useReportColumnStep({
      count: columnLabels.length,
      initial: 3,
      label: (index) => columnLabels[index]
    });
    useRealtime("journal");
    const navigate = useNavigate();
    const [params] = useUrlParams();
    const parentRef = useRef<HTMLDivElement>(null);

    const openLedger = (accountId: string) => {
      if (!ledgerPath) return;
      const qs = params.toString();
      navigate(qs ? `${ledgerPath(accountId)}?${qs}` : ledgerPath(accountId));
    };

    const filtered = useMemo(
      () => filterAccounts(data, search),
      [data, search]
    );
    const tree = useMemo(() => accountsToFlatTree(filtered), [filtered]);

    // Build a lookup of balanceAtDate by account id for ratio calculation
    const balanceById = useMemo(() => {
      const map = new Map<string, number>();
      for (const account of data) {
        map.set(account.id, account.balanceAtDate ?? 0);
      }
      return map;
    }, [data]);

    const {
      nodes,
      getTreeProps,
      getNodeProps,
      selectNode,
      toggleExpandNode,
      virtualizer
    } = useTree<TrialBalanceChart, undefined>({
      tree,
      parentRef,
      estimatedRowHeight,
      isEager: true
    });

    return (
      <ScrollArea className={reportFrameClassName}>
        {isPhone ? (
          <div className="sticky top-0 z-10">{stepper}</div>
        ) : (
          <div className="sticky top-0 z-10 flex h-11 items-center pr-4 text-sm font-medium text-foreground/80 border-b border-border bg-card">
            <div className="flex-1 px-4">
              <Trans>Account</Trans>
            </div>
            {columnLabels.map((label, index) => (
              <span
                key={label}
                className={cn(
                  index === columnLabels.length - 1 ? "w-20" : "w-28",
                  "text-right px-2"
                )}
              >
                {label}
              </span>
            ))}
          </div>
        )}
        <TreeView<TrialBalanceChart>
          tree={tree}
          nodes={nodes}
          getTreeProps={getTreeProps}
          getNodeProps={getNodeProps}
          virtualizer={virtualizer}
          parentRef={parentRef}
          parentClassName="h-full"
          renderNode={({ node, state }) => {
            const account = node.data;
            const isGroup = account.isGroup;
            const isExpanded = state.expanded;

            const endingBalance = account.balanceAtDate ?? 0;
            const netChange = account.netChange ?? 0;
            const beginningBalance = endingBalance - netChange;
            const { debit, credit } = getDebitCredit(netChange, account.class);

            // Ratio: percentage of parent's ending balance
            const parentBalance = node.parentId
              ? (balanceById.get(node.parentId) ?? 0)
              : 0;
            const ratio =
              parentBalance !== 0
                ? (Math.abs(endingBalance) / Math.abs(parentBalance)) * 100
                : 0;

            const isDrillable = !isGroup && !!ledgerPath;

            // Indentation + folder + number + name.
            const accountCell = (
              <>
                {/* Indentation lines */}
                <div className="flex h-9 items-center">
                  {Array.from({ length: node.level }).map((_, index) => (
                    <LevelLine key={index} isSelected={state.selected} />
                  ))}

                  <div
                    className={cn(
                      "flex h-9 w-5 items-center justify-center",
                      node.hasChildren && "hover:bg-accent"
                    )}
                    onClick={(e) => {
                      e.stopPropagation();
                      toggleExpandNode(node.id);
                    }}
                  >
                    {node.hasChildren ? (
                      isExpanded ? (
                        <LuChevronDown className="h-4 w-4 text-muted-foreground flex-shrink-0" />
                      ) : (
                        <LuChevronRight className="h-4 w-4 text-muted-foreground flex-shrink-0" />
                      )
                    ) : (
                      <div className="h-9 w-5" />
                    )}
                  </div>
                </div>

                {/* Folder icon */}
                <div
                  className={cn(
                    "w-5 h-5 flex items-center justify-center mr-2 shrink-0",
                    !isGroup && "max-md:hidden"
                  )}
                >
                  {isGroup &&
                    (isExpanded ? (
                      <LuFolderOpen className="h-4 w-4 text-muted-foreground" />
                    ) : (
                      <LuFolder className="h-4 w-4 text-muted-foreground" />
                    ))}
                </div>

                {/* Account number + name */}
                <div className="flex flex-1 items-center gap-2 overflow-hidden">
                  {!isGroup && account.number && (
                    <span className="text-muted-foreground shrink-0">
                      {account.number}
                    </span>
                  )}
                  <span className="truncate">{account.name}</span>
                </div>
              </>
            );

            // Same order as the header; the translated cell only when shown.
            const cellClass =
              "w-28 text-right tabular-nums shrink-0 px-2 text-muted-foreground";
            const valueCells = [
              <span key="beginning" className={cellClass}>
                {formatCurrency(beginningBalance)}
              </span>,
              <span key="debit" className={cellClass}>
                {formatCurrency(debit)}
              </span>,
              <span key="credit" className={cellClass}>
                {formatCurrency(credit)}
              </span>,
              <span
                key="ending"
                className={cn(
                  cellClass,
                  isDrillable &&
                    "group-hover/row:text-foreground group-hover/row:underline underline-offset-2 decoration-border"
                )}
              >
                {formatCurrency(endingBalance)}
              </span>,
              ...(showTranslated
                ? [
                    <span key="translated" className={cellClass}>
                      {account.translatedBalance != null
                        ? formatCurrency(account.translatedBalance)
                        : "-"}
                    </span>
                  ]
                : []),
              <span
                key="ratio"
                className="w-20 text-right tabular-nums shrink-0 px-2 text-muted-foreground"
              >
                {node.parentId ? formatPercent(ratio) : ""}
              </span>
            ];

            return (
              <div
                className={cn(
                  "flex h-8 cursor-pointer items-center overflow-hidden pr-4 text-sm group/row max-md:h-11",
                  state.selected
                    ? "bg-muted hover:bg-accent"
                    : "bg-transparent hover:bg-accent",
                  isGroup && "font-semibold"
                )}
                onClick={() => {
                  selectNode(node.id, false);
                  if (isGroup) {
                    toggleExpandNode(node.id);
                  } else if (isDrillable) {
                    openLedger(account.id);
                  }
                }}
              >
                {/* Phones: the name takes the width; one value shows. */}
                {isPhone ? (
                  <div className="flex h-full min-w-0 flex-1 items-center overflow-hidden">
                    {accountCell}
                  </div>
                ) : (
                  accountCell
                )}

                {isPhone ? valueCells[columnIndex] : valueCells}
              </div>
            );
          }}
        />
      </ScrollArea>
    );
  }
);

TrialBalanceTree.displayName = "TrialBalanceTree";
export default TrialBalanceTree;