Skip to content

A local-first personal finance app

54.5 KB
Raw Blame
import { theme } from '@actual-app/components/theme';
import { send } from '@actual-app/core/platform/client/connection';
import * as monthUtils from '@actual-app/core/shared/months';
import { q } from '@actual-app/core/shared/query';
import type {
  CategoryGroupEntity,
  RuleConditionEntity,
} from '@actual-app/core/types/models';
import { t } from 'i18next';

import { getColorScale } from '#components/reports/chart-theme';
import type { useSpreadsheet } from '#hooks/useSpreadsheet';
import { aqlQuery } from '#queries/aqlQuery';

type BudgetMonthCategory = {
  id: string;
  name: string;
  spent?: number;
  budgeted?: number;
  balance?: number;
  received?: number;
};

type BudgetMonthGroup = {
  id: string;
  name: string;
  is_income: boolean;
  categories: BudgetMonthCategory[];
};

type BudgetMonthResponse = {
  categoryGroups: BudgetMonthGroup[];
  totalIncome: number;
  fromLastMonth: number;
  forNextMonth: number;
  lastMonthOverspent: number;
  toBudget: number;
};

type AggregatedBudget = {
  toBudget: number;
  fromPreviousMonth: number;
  lastMonthOverspent: number;
  categoryGroupsMap: Map<string, BudgetMonthGroup>;
  forNextMonth: number;
  startMonth: string;
  endMonth: string;
};

type SankeyNode = {
  name: string;
  percentageLabel?: string;
  key: string;
  color?: string;
};

type SankeyLink = {
  source: number;
  target: number;
  value: number;
  tooltipInfo?: Array<{ name: string; value: number }>;
  color?: string;
};

type SankeyData = {
  nodes: SankeyNode[];
  links: SankeyLink[];
};

type CategoryEntry = {
  categoryGroup: string;
  categoryGroupId: string;
  category: string;
  categoryId: string;
  value: number;
  isIncome: boolean;
  isNegative: boolean;
  accountName?: string;
  accountId?: string;
  payeeName?: string;
  payeeId?: string;
};

type TransferEntry = {
  accountId: string;
  accountName: string;
  amount: number;
  id: string;
  transfer_id: string;
};

type TransferPair = {
  fromAccountId: string;
  fromAccountName: string;
  toAccountId: string;
  toAccountName: string;
  amount: number;
};

type SortMode = 'per-group' | 'global' | 'budget-order';

type NodeKey = string;
export type NodeData = {
  to: Map<NodeKey, number>;
  value?: number;
  type: GraphLayer;
  name?: string;
  labelKey?: string;
  labelParams?: Record<string, string>;
  isNegative?: boolean;
  tooltipInfo?: Array<{ name: string; value: number }>;
  percentageLabel?: string;
  color?: string;
};
export type Graph = Map<NodeKey, NodeData>;
type VisualLayerIndex = number;

type TooltipInfoMap = Map<
  NodeKey,
  Map<NodeKey, Array<{ name: string; value: number }>>
>;

const SpecialNodeKeys = {
  ToBudget: 'to_budget',
  Budgeted: 'budgeted',
  LastMonthOverspent: 'last_month_overspent',
  ForNextMonth: 'for_next_month',
  FromPrevMonth: 'from_previous_month',
  AvailableIncome: 'available_income',
  AllAccounts: 'all_income',
  OtherSuffix: '__OTHER_BUCKET',
  HiddenSuffix: '__HIDDEN',
  NegativeSuffix: '__NEGATIVE',
} as const;
export const GraphLayers = {
  IncomePayee: 'payee',
  IncomeCategory: 'income_category',
  Account: 'account',
  Budget: 'budget',
  CategoryGroup: 'category_group',
  Category: 'category',
} as const;
export type GraphLayer = (typeof GraphLayers)[keyof typeof GraphLayers];

export const GRAPH_LAYER_ORDER = [
  GraphLayers.IncomePayee,
  GraphLayers.IncomeCategory,
  GraphLayers.Account,
  GraphLayers.Budget,
  GraphLayers.CategoryGroup,
  GraphLayers.Category,
] as const;

export function isGraphLayer(value: unknown): value is GraphLayer {
  return (
    typeof value === 'string' &&
    (Object.values(GraphLayers) as string[]).includes(value)
  );
}

export function createBaseGraphSpreadsheet(
  start: string,
  end: string,
  categories: CategoryGroupEntity[],
  conditions: RuleConditionEntity[] = [],
  conditionsOp: 'and' | 'or' = 'and',
  mode: 'budgeted' | 'spent' = 'spent',
  groupAccounts: boolean = false,
  showTransfers: boolean = false,
) {
  return async (
    _spreadsheet: ReturnType<typeof useSpreadsheet>,
    setData: (data: Graph) => void,
  ) => {
    const baseGraph = await createBaseGraph(
      start,
      end,
      categories,
      conditions,
      conditionsOp,
      mode,
      groupAccounts,
      showTransfers,
    );

    setData(baseGraph);
  };
}

async function createBaseGraph(
  start: string,
  end: string,
  categories: CategoryGroupEntity[],
  conditions: RuleConditionEntity[] = [],
  conditionsOp: 'and' | 'or' = 'and',
  mode: 'budgeted' | 'spent' = 'spent',
  groupAccounts: boolean = false,
  showTransfers: boolean = false,
): Promise<Graph> {
  let data: CategoryEntry[] = [];
  let aggregated: AggregatedBudget | undefined;
  let transferData: TransferPair[] | undefined;

  if (mode === 'budgeted') {
    ({ data, aggregated } = await createBudgetSpreadsheet(
      start,
      end,
      conditions,
      conditionsOp,
    )());
  } else if (mode === 'spent') {
    const res = await createTransactionsSpreadsheet(
      start,
      end,
      categories,
      conditions,
      conditionsOp,
      groupAccounts,
      showTransfers,
    )();
    data = res.data;
    transferData = res.transferData;
  }

  return aggregated
    ? createBudgetGraph(data, aggregated)
    : createTransactionsGraph(data, transferData, groupAccounts);
}

export function buildSankeyData(
  baseGraph: Graph,
  topNcategories: number,
  categories: CategoryGroupEntity[],
  categorySort: SortMode,
  layerFrom: GraphLayer,
  layerTo: GraphLayer,
): SankeyData {
  const graph = cloneGraph(baseGraph);

  const toolTipInfoMap = groupOtherCategories(
    graph,
    topNcategories,
    categorySort,
  );
  const sortedGraph = sortGraph(graph, categorySort, categories);
  cleanUpNodes(sortedGraph);
  addHiddenNodes(sortedGraph);
  addPercentageLabels(sortedGraph);
  addColors(sortedGraph);
  filterGraphByLayers(sortedGraph, layerFrom, layerTo);

  return convertToSankeyData(sortedGraph, toolTipInfoMap);
}

export function createBudgetSpreadsheet(
  start: string,
  end: string,
  conditions: RuleConditionEntity[] = [],
  conditionsOp: 'and' | 'or' = 'and',
) {
  return async () => {
    const months =
      end && end !== start ? monthUtils.rangeInclusive(start, end) : [start];

    const monthResponses = await Promise.all(
      months.map(
        m =>
          send('api/budget-month', {
            month: m,
          }) as unknown as Promise<BudgetMonthResponse>,
      ),
    );

    const accumulate_months = monthResponses.reduce(
      (acc, response, index) => {
        if (index === monthResponses.length - 1) {
          acc.toBudget = response.toBudget;
        }
        if (index === 0) {
          acc.fromPreviousMonth = response.fromLastMonth;
        }
        acc.lastMonthOverspent += response.lastMonthOverspent;

        for (const group of response.categoryGroups) {
          const existingGroup = acc.categoryGroupsMap.get(group.id);
          if (!existingGroup) {
            acc.categoryGroupsMap.set(group.id, {
              ...group,
              categories: group.categories.map(cat => ({ ...cat })),
            });
            continue;
          }

          for (const cat of group.categories) {
            const existingCat = existingGroup.categories.find(
              c => c.id === cat.id,
            );
            if (!existingCat) {
              existingGroup.categories.push({ ...cat });
              continue;
            }
            existingCat.budgeted =
              (existingCat.budgeted ?? 0) + (cat.budgeted ?? 0);
            existingCat.spent = (existingCat.spent ?? 0) + (cat.spent ?? 0);
            existingCat.balance =
              (existingCat.balance ?? 0) + (cat.balance ?? 0);
            existingCat.received =
              (existingCat.received ?? 0) + (cat.received ?? 0);
          }
        }

        return acc;
      },
      {
        toBudget: 0,
        fromPreviousMonth: 0,
        lastMonthOverspent: 0,
        categoryGroupsMap: new Map<string, BudgetMonthGroup>(),
      },
    );

    const categoryGroups = Array.from(
      accumulate_months.categoryGroupsMap.values(),
    );

    const filteredCategoryGroups = filterCategoryGroups(
      categoryGroups,
      conditions,
      conditionsOp,
    );

    const categoryData: CategoryEntry[] = filteredCategoryGroups
      .flatMap(group =>
        group.categories.map(cat => {
          const rawValue = group.is_income
            ? (cat.received ?? 0)
            : (cat.budgeted ?? 0);
          return {
            categoryGroup: group.name,
            categoryGroupId: group.id,
            category: cat.name,
            categoryId: cat.id,
            isIncome: group.is_income,
            isNegative: rawValue < 0,
            value: rawValue,
          };
        }),
      )
      .filter(entry => entry.value !== 0);

    const nextMonthResponse = (await send('api/budget-month', {
      month: monthUtils.nextMonth(end),
    })) as unknown as BudgetMonthResponse;

    const aggregated: AggregatedBudget = {
      toBudget: accumulate_months.toBudget,
      forNextMonth:
        (nextMonthResponse.fromLastMonth ?? 0) - accumulate_months.toBudget,
      fromPreviousMonth: accumulate_months.fromPreviousMonth,
      lastMonthOverspent: accumulate_months.lastMonthOverspent,
      categoryGroupsMap: accumulate_months.categoryGroupsMap,
      startMonth: start,
      endMonth: end,
    };

    return { data: categoryData, aggregated };
  };
}

export function createTransactionsSpreadsheet(
  start: string,
  end: string,
  categories: CategoryGroupEntity[],
  conditions: RuleConditionEntity[] = [],
  conditionsOp: 'and' | 'or' = 'and',
  groupAccounts: boolean,
  showTransfers: boolean,
) {
  return async () => {
    // gather filters user has set
    const { filters } = await send('make-filters-from-conditions', {
      conditions: conditions.filter(cond => !cond.customName),
    });
    const conditionsOpKey = conditionsOp === 'or' ? '$or' : '$and';

    const categoryData = await fetchCategoryData(
      categories,
      conditionsOpKey,
      filters,
      start,
      end,
      groupAccounts,
    );

    let transferData: TransferPair[] = [];
    if (showTransfers) {
      transferData = await fetchTransferData(
        conditionsOpKey,
        filters,
        start,
        end,
      );
    }

    return { data: categoryData, transferData };
  };
}

function cloneGraph(graph: Graph): Graph {
  const clonedGraph: Graph = new Map();

  for (const [key, node] of graph) {
    clonedGraph.set(key, {
      ...node,
      to: new Map(node.to),
      tooltipInfo: node.tooltipInfo?.map(info => ({ ...info })),
    });
  }

  return clonedGraph;
}

// Filter budget category groups to only those matching the user's conditions.
// Budget data is fetched unconditionally from api/budget-month, so we must
// apply category conditions manually in JS (unlike the transaction path which
// passes conditions directly into the AQL query).
export function filterCategoryGroups(
  categoryGroups: BudgetMonthGroup[],
  conditions: RuleConditionEntity[],
  conditionsOp: 'and' | 'or',
): BudgetMonthGroup[] {
  const categoryConditions = conditions.filter(
    cond => cond.field === GraphLayers.Category,
  );
  const categoryGroupConditions = conditions.filter(
    cond => cond.field === GraphLayers.CategoryGroup,
  );

  if (categoryConditions.length === 0 && categoryGroupConditions.length === 0) {
    return categoryGroups;
  }

  const matchesStringCondition = (
    id: string,
    name: string,
    cond: RuleConditionEntity,
  ): boolean => {
    const value = cond.value;
    if (typeof cond.op !== 'string') {
      throw new Error('Invalid op');
    }
    const op = cond.op;
    if (op === 'is') return id === value;
    if (op === 'isNot') return id !== value;
    if (op === 'oneOf') return Array.isArray(value) && value.includes(id);
    if (op === 'notOneOf') return !Array.isArray(value) || !value.includes(id);
    if (op === 'contains') {
      return (
        typeof value === 'string' &&
        name.toLowerCase().includes(value.toLowerCase())
      );
    }
    if (op === 'doesNotContain') {
      return (
        typeof value === 'string' &&
        !name.toLowerCase().includes(value.toLowerCase())
      );
    }
    if (op === 'matches') {
      if (typeof value !== 'string') return false;
      if (value.length > 256) return false;
      try {
        const regex =
          value.startsWith('/') && value.lastIndexOf('/') > 0
            ? new RegExp(value.slice(1, value.lastIndexOf('/')), 'i')
            : new RegExp(value, 'i');
        return regex.test(name);
      } catch {
        return false;
      }
    }
    return false;
  };

  const categoryMatchesConditions = (
    catId: string,
    catName: string,
    groupId: string,
    groupName: string,
  ): boolean => {
    const matchesCat = (cond: RuleConditionEntity) =>
      matchesStringCondition(catId, catName, cond);
    const matchesGroup = (cond: RuleConditionEntity) =>
      matchesStringCondition(groupId, groupName, cond);

    if (conditionsOp === 'or') {
      return (
        categoryConditions.some(matchesCat) ||
        categoryGroupConditions.some(matchesGroup)
      );
    }
    // 'and': all category conditions AND all category_group conditions must match
    const catMatch =
      categoryConditions.length === 0 || categoryConditions.every(matchesCat);
    const groupMatch =
      categoryGroupConditions.length === 0 ||
      categoryGroupConditions.every(matchesGroup);
    return catMatch && groupMatch;
  };

  return categoryGroups
    .map(group => ({
      ...group,
      categories: group.categories.filter(cat =>
        categoryMatchesConditions(cat.id, cat.name, group.id, group.name),
      ),
    }))
    .filter(group => group.categories.length > 0);
}

// retrieve sum of group expenses
async function fetchCategoryData(
  categoryGroups: CategoryGroupEntity[],
  conditionsOpKey: string = '$and',
  filters: unknown[] = [],
  start: string,
  end: string,
  groupAccounts: boolean,
): Promise<CategoryEntry[]> {
  const nested = await Promise.all(
    categoryGroups.map(async (categoryGroup: CategoryGroupEntity) => {
      const entries = await Promise.all(
        (categoryGroup.categories || []).map(async category => {
          const results = await aqlQuery(
            q('transactions')
              .filter({ [conditionsOpKey]: filters })
              .filter({
                $and: [
                  { date: { $gte: monthUtils.firstDayOfMonth(start) } },
                  { date: { $lte: monthUtils.lastDayOfMonth(end) } },
                ],
              })
              .filter({ category: category.id })
              .groupBy(
                categoryGroup.is_income
                  ? [
                      { $id: '$category' },
                      { $id: '$account' },
                      { $id: '$payee' },
                    ]
                  : [{ $id: '$category' }, { $id: '$account' }],
              )
              .select([
                { accountId: { $id: '$account.id' } },
                { accountName: { $id: '$account.name' } },
                { amount: { $sum: '$amount' } },
                { payeeId: { $id: '$payee.id' } },
                { payeeName: { $id: '$payee.name' } },
              ]),
          );
          return results.data.map(
            (row: {
              amount?: number;
              accountName?: string;
              accountId?: string;
              payeeName?: string;
              payeeId?: string;
            }) =>
              ({
                categoryGroup: categoryGroup.name,
                categoryGroupId: categoryGroup.id,
                category: category.name,
                categoryId: category.id,
                value: Math.abs(row.amount ?? 0),
                isIncome: categoryGroup.is_income ?? false,
                isNegative: row.amount !== undefined && row.amount < 0,
                accountName: row.accountName ?? '',
                accountId: row.accountId ?? '',
                payeeName: row.payeeName ?? '',
                payeeId: row.payeeId ?? '',
              }) satisfies CategoryEntry,
          );
        }),
      );
      return entries.flat();
    }),
  );
  const allCategoryData = nested.flat();

  if (groupAccounts) {
    allCategoryData.forEach(entry => {
      if (entry.accountName && entry.accountId) {
        entry.accountName = SpecialNodeKeys.AllAccounts;
        entry.accountId = SpecialNodeKeys.AllAccounts;
      }
    });
  }

  return allCategoryData;
}

// Fetch transactions that are transfers within the provided month range
async function fetchTransferData(
  conditionsOpKey: string = '$and',
  filters: unknown[] = [],
  start: string,
  end: string,
): Promise<TransferPair[]> {
  const results = await aqlQuery(
    q('transactions')
      .filter({ [conditionsOpKey]: filters })
      .filter({
        $and: [
          { date: { $gte: monthUtils.firstDayOfMonth(start) } },
          { date: { $lte: monthUtils.lastDayOfMonth(end) } },
        ],
      })
      .filter({ transfer_id: { $ne: null }, 'account.offbudget': false })
      .select([
        { id: 'id' },
        { amount: 'amount' },
        { accountId: { $id: '$account.id' } },
        { accountName: { $id: '$account.name' } },
        { transfer_id: 'transfer_id' },
      ]),
  );

  const raw_results: TransferEntry[] = results.data.map(
    (row: {
      id?: string;
      amount?: number;
      accountId?: string;
      accountName?: string;
      transfer_id?: string;
    }) =>
      ({
        id: row.id ?? '',
        amount: row.amount ?? 0,
        accountId: row.accountId ?? '',
        accountName: row.accountName ?? '',
        transfer_id: row.transfer_id ?? '',
      }) satisfies TransferEntry,
  );

  return aggregateTransferPairs(raw_results);
}

export function aggregateTransferPairs(
  rawResults: TransferEntry[],
): TransferPair[] {
  const byId = new Map<string, TransferEntry>();
  const byAccountId = new Map<string, string>();

  rawResults.forEach((transfer: TransferEntry) => {
    byId.set(String(transfer.id), transfer);
    byAccountId.set(String(transfer.accountId), transfer.accountName);
  });

  const resultPairs = new Map<string, number>();

  rawResults.forEach((from: TransferEntry) => {
    const to = byId.get(String(from.transfer_id));
    if (!to) return;

    if (from.accountId > to.accountId) return;

    const [accountId1, accountId2] = [from.accountId, to.accountId].sort();
    const pairKey = `${accountId1}|${accountId2}`;
    const sourceAccountId = from.amount < 0 ? from.accountId : to.accountId;
    const sign = sourceAccountId === accountId1 ? 1 : -1;
    const existingValue = resultPairs.get(pairKey) ?? 0;

    resultPairs.set(pairKey, existingValue + sign * Math.abs(from.amount));
  });

  return Array.from(resultPairs.entries())
    .filter(([, value]) => value !== 0)
    .map(([key, value]) => {
      const [accountId1, accountId2] = key.split('|');
      const fromAccountId = value > 0 ? accountId1 : accountId2;
      const toAccountId = value > 0 ? accountId2 : accountId1;

      return {
        fromAccountId,
        fromAccountName: byAccountId.get(fromAccountId) || '',
        toAccountId,
        toAccountName: byAccountId.get(toAccountId) || '',
        amount: Math.abs(value),
      };
    }) satisfies TransferPair[];
}

export function createBudgetGraph(
  categoryData: CategoryEntry[],
  aggregated: AggregatedBudget,
): Graph {
  const graph: Graph = new Map();

  // Add initial budget nodes with no links
  addNode(graph, SpecialNodeKeys.Budgeted, GraphLayers.Budget, 'Budgeted');
  addNode(
    graph,
    SpecialNodeKeys.AvailableIncome,
    GraphLayers.Account,
    'Available funds',
  );

  categoryData.forEach(entry => {
    if (entry.isIncome) {
      // Income category > Available income
      addNode(
        graph,
        entry.categoryId,
        GraphLayers.IncomeCategory,
        entry.category,
      );
      addValueToLink(
        graph,
        entry.categoryId,
        SpecialNodeKeys.AvailableIncome,
        entry.value,
      );
    } else {
      if (entry.value >= 0) {
        // Budgeted > Category group > Category
        addNode(
          graph,
          entry.categoryGroupId,
          GraphLayers.CategoryGroup,
          entry.categoryGroup,
        );
        addNode(graph, entry.categoryId, GraphLayers.Category, entry.category);
        addValueToLink(
          graph,
          entry.categoryGroupId,
          entry.categoryId,
          entry.value,
        );
        addValueToLink(
          graph,
          SpecialNodeKeys.Budgeted,
          entry.categoryGroupId,
          entry.value,
        );
        addValueToLink(
          graph,
          SpecialNodeKeys.AvailableIncome,
          SpecialNodeKeys.Budgeted,
          entry.value,
        );
      } else {
        addNodeWithLabel(
          graph,
          entry.categoryId,
          GraphLayers.Account,
          'From {{category}}',
          { category: entry.category },
          true,
        );
        addValueToLink(
          graph,
          entry.categoryId,
          SpecialNodeKeys.Budgeted,
          Math.abs(entry.value),
        );
        addValueToLink(
          graph,
          SpecialNodeKeys.AvailableIncome,
          SpecialNodeKeys.Budgeted,
          entry.value,
        );
      }
    }
  });

  if (aggregated.toBudget > 0) {
    addNodeWithLabel(
      graph,
      SpecialNodeKeys.ToBudget,
      GraphLayers.CategoryGroup,
      'To budget',
      undefined,
      false,
    );
    addValueToLink(
      graph,
      SpecialNodeKeys.AvailableIncome,
      SpecialNodeKeys.ToBudget,
      aggregated.toBudget,
    );
  } else {
    addNodeWithLabel(
      graph,
      SpecialNodeKeys.ToBudget,
      GraphLayers.Account,
      'Overbudgeted',
      undefined,
      true,
    );
    addValueToLink(
      graph,
      SpecialNodeKeys.ToBudget,
      SpecialNodeKeys.Budgeted,
      Math.abs(aggregated.toBudget),
    );
    addValueToLink(
      graph,
      SpecialNodeKeys.AvailableIncome,
      SpecialNodeKeys.Budgeted,
      -Math.abs(aggregated.toBudget),
    );
  }

  addNodeWithLabel(
    graph,
    SpecialNodeKeys.FromPrevMonth,
    GraphLayers.IncomeCategory,
    'From {{month}}',
    { month: monthUtils.prevMonth(aggregated.startMonth) },
  );
  addValueToLink(
    graph,
    SpecialNodeKeys.FromPrevMonth,
    SpecialNodeKeys.AvailableIncome,
    aggregated.fromPreviousMonth,
  );
  addNodeWithLabel(
    graph,
    SpecialNodeKeys.ForNextMonth,
    GraphLayers.Budget,
    'For {{month}}',
    { month: monthUtils.nextMonth(aggregated.endMonth) },
  );
  addValueToLink(
    graph,
    SpecialNodeKeys.AvailableIncome,
    SpecialNodeKeys.ForNextMonth,
    aggregated.forNextMonth,
  );
  addNode(
    graph,
    SpecialNodeKeys.LastMonthOverspent,
    GraphLayers.Budget,
    'Overspent',
  );
  addValueToLink(
    graph,
    SpecialNodeKeys.AvailableIncome,
    SpecialNodeKeys.LastMonthOverspent,
    Math.abs(aggregated.lastMonthOverspent),
  );

  return graph;
}

export function createTransactionsGraph(
  categoryData: CategoryEntry[],
  transferData?: TransferPair[],
  groupAccounts?: boolean,
): Graph {
  function addAccountNode(accountId: string, accountName: string): void {
    if (accountId === SpecialNodeKeys.AllAccounts) {
      addNodeWithLabel(
        graph,
        accountId,
        GraphLayers.Account,
        'Income',
        undefined,
      );
    } else {
      addNode(graph, accountId, GraphLayers.Account, accountName);
    }
  }

  const graph: Graph = new Map();

  categoryData.forEach(entry => {
    if (entry.accountId && entry.accountName && entry.categoryId) {
      if (entry.isIncome) {
        if (entry.isNegative) {
          // Account > Income category
          addAccountNode(entry.accountId, entry.accountName);
          addNodeWithLabel(
            graph,
            entry.categoryId + SpecialNodeKeys.NegativeSuffix,
            GraphLayers.CategoryGroup,
            entry.payeeName || entry.category,
            undefined,
            true,
          );
          addValueToLink(
            graph,
            entry.accountId,
            entry.categoryId + SpecialNodeKeys.NegativeSuffix,
            entry.value,
          );
        } else {
          // Payee > Income category > Account
          addNode(
            graph,
            entry.categoryId,
            GraphLayers.IncomeCategory,
            entry.category,
          );
          addAccountNode(entry.accountId, entry.accountName);
          addValueToLink(graph, entry.categoryId, entry.accountId, entry.value);
          if (entry.payeeId) {
            addNode(
              graph,
              entry.payeeId,
              GraphLayers.IncomePayee,
              entry.payeeName,
            );
            addValueToLink(graph, entry.payeeId, entry.categoryId, entry.value);
          }
        }
      } else {
        if (entry.isNegative) {
          // Account > Category group > Category
          addAccountNode(entry.accountId, entry.accountName);
          addNode(
            graph,
            entry.categoryGroupId,
            GraphLayers.CategoryGroup,
            entry.categoryGroup,
          );
          addNode(
            graph,
            entry.categoryId,
            GraphLayers.Category,
            entry.category,
          );
          addValueToLink(
            graph,
            entry.accountId,
            entry.categoryGroupId,
            entry.value,
          );
          addValueToLink(
            graph,
            entry.categoryGroupId,
            entry.categoryId,
            entry.value,
          );
        } else {
          // Category > Account
          addNode(
            graph,
            entry.categoryId + SpecialNodeKeys.NegativeSuffix,
            GraphLayers.IncomeCategory,
            entry.payeeName || entry.category,
          );
          addAccountNode(entry.accountId, entry.accountName);
          addValueToLink(
            graph,
            entry.categoryId + SpecialNodeKeys.NegativeSuffix,
            entry.accountId,
            entry.value,
          );
        }
      }
    }
  });

  // If transfer data is provided, add links between accounts representing transfers.
  // Pair transactions strictly by transfer_id === id.
  if (transferData && transferData.length > 0 && !groupAccounts) {
    transferData.forEach((pair: TransferPair) => {
      addAccountNode(pair.fromAccountId, pair.fromAccountName);
      addAccountNode(pair.toAccountId, pair.toAccountName);
      addValueToLink(graph, pair.fromAccountId, pair.toAccountId, pair.amount);
    });
  }

  return graph;
}

export function addNode(
  graph: Graph,
  key: NodeKey,
  type: GraphLayer,
  name?: string,
) {
  if (!graph.has(key)) {
    graph.set(key, {
      to: new Map(),
      type,
      name,
    });
  }
}

export function addNodeWithLabel(
  graph: Graph,
  key: NodeKey,
  type: GraphLayer,
  labelKey: string,
  labelParams?: Record<string, string>,
  isNegative?: boolean,
) {
  if (!graph.has(key)) {
    graph.set(key, {
      to: new Map(),
      type,
      labelKey,
      labelParams,
      isNegative,
    });
  }
}

export function addValueToLink(
  graph: Graph,
  from: NodeKey,
  to: NodeKey,
  value: number,
) {
  const fromNode = graph.get(from);
  if (fromNode) {
    fromNode.to.set(to, (fromNode.to.get(to) ?? 0) + value);
  }
}

export function getLayer(
  graph: Graph,
  key: NodeKey,
  layerCache?: Map<NodeKey, VisualLayerIndex>,
): number {
  const resolvedLayerCache = layerCache ?? new Map<NodeKey, VisualLayerIndex>();

  const cachedLayer = resolvedLayerCache.get(key);
  if (cachedLayer !== undefined) {
    return cachedLayer;
  }

  if (!graph.has(key)) {
    resolvedLayerCache.set(key, 0);
    return 0;
  }

  const computedLayers = getLayersByStronglyConnectedComponents(graph);
  computedLayers.forEach((layer, nodeKey) => {
    resolvedLayerCache.set(nodeKey, layer);
  });

  return resolvedLayerCache.get(key) ?? 0;
}

function getLayersByStronglyConnectedComponents(
  graph: Graph,
): Map<NodeKey, VisualLayerIndex> {
  const visitedIndex = new Map<NodeKey, number>();
  const lowlink = new Map<NodeKey, number>();
  const stack: NodeKey[] = [];
  const activeStack = new Set<NodeKey>();
  const componentByNode = new Map<NodeKey, number>();
  const components: NodeKey[][] = [];
  let index = 0;

  function strongConnect(nodeKey: NodeKey) {
    visitedIndex.set(nodeKey, index);
    lowlink.set(nodeKey, index);
    index += 1;
    stack.push(nodeKey);
    activeStack.add(nodeKey);

    const node = graph.get(nodeKey);
    if (node) {
      for (const childKey of node.to.keys()) {
        if (!graph.has(childKey)) {
          continue;
        }

        if (!visitedIndex.has(childKey)) {
          strongConnect(childKey);
          lowlink.set(
            nodeKey,
            Math.min(lowlink.get(nodeKey) ?? 0, lowlink.get(childKey) ?? 0),
          );
        } else if (activeStack.has(childKey)) {
          lowlink.set(
            nodeKey,
            Math.min(
              lowlink.get(nodeKey) ?? 0,
              visitedIndex.get(childKey) ?? 0,
            ),
          );
        }
      }
    }

    if (lowlink.get(nodeKey) === visitedIndex.get(nodeKey)) {
      const componentIndex = components.length;
      const componentNodes: NodeKey[] = [];

      let poppedNode: NodeKey | undefined;
      do {
        poppedNode = stack.pop();
        if (!poppedNode) {
          break;
        }

        activeStack.delete(poppedNode);
        componentByNode.set(poppedNode, componentIndex);
        componentNodes.push(poppedNode);
      } while (poppedNode !== nodeKey);

      components.push(componentNodes);
    }
  }

  for (const nodeKey of graph.keys()) {
    if (!visitedIndex.has(nodeKey)) {
      strongConnect(nodeKey);
    }
  }

  const parentsByComponent = new Map<number, Set<number>>();
  for (
    let componentIndex = 0;
    componentIndex < components.length;
    componentIndex += 1
  ) {
    parentsByComponent.set(componentIndex, new Set());
  }

  for (const [sourceKey, sourceNode] of graph) {
    const sourceComponent = componentByNode.get(sourceKey);
    if (sourceComponent === undefined) {
      continue;
    }

    for (const targetKey of sourceNode.to.keys()) {
      const targetComponent = componentByNode.get(targetKey);
      if (
        targetComponent === undefined ||
        targetComponent === sourceComponent
      ) {
        continue;
      }

      parentsByComponent.get(targetComponent)?.add(sourceComponent);
    }
  }

  const layerByComponent = new Map<number, VisualLayerIndex>();
  function resolveComponentLayer(componentIndex: number): VisualLayerIndex {
    const cachedComponentLayer = layerByComponent.get(componentIndex);
    if (cachedComponentLayer !== undefined) {
      return cachedComponentLayer;
    }

    const parents = parentsByComponent.get(componentIndex);
    if (!parents || parents.size === 0) {
      layerByComponent.set(componentIndex, 0);
      return 0;
    }

    const layer =
      1 + Math.max(...Array.from(parents).map(resolveComponentLayer));
    layerByComponent.set(componentIndex, layer);
    return layer;
  }

  const layerByNode = new Map<NodeKey, VisualLayerIndex>();
  for (const [nodeKey, componentIndex] of componentByNode) {
    layerByNode.set(nodeKey, resolveComponentLayer(componentIndex));
  }

  return layerByNode;
}

function getComputedNodeLayers(graph: Graph): Map<NodeKey, VisualLayerIndex> {
  const layerCache = new Map<NodeKey, VisualLayerIndex>();

  for (const key of graph.keys()) {
    getLayer(graph, key, layerCache);
  }

  return layerCache;
}

function isHiddenNodeKey(key: NodeKey): boolean {
  return key.endsWith(SpecialNodeKeys.HiddenSuffix);
}

function groupOtherCategories(
  graph: Graph,
  topN: number,
  categorySort: SortMode = 'per-group',
): TooltipInfoMap {
  const toolTipInfoMap: TooltipInfoMap = new Map();
  const structuralKeys = new Set<string>(Object.values(SpecialNodeKeys));

  function isGroupableNode(key: NodeKey): boolean {
    const node = graph.get(key);
    return Boolean(
      node &&
      !key.endsWith(SpecialNodeKeys.OtherSuffix) &&
      !structuralKeys.has(key) &&
      !node.isNegative,
    );
  }

  Object.values(GraphLayers).forEach(layer => {
    let ordinaryNodes = nodesInLayer(graph, layer).filter(isGroupableNode);
    let otherNodes = nodesInLayer(graph, layer).filter(s =>
      s.endsWith(SpecialNodeKeys.OtherSuffix),
    );

    while (ordinaryNodes.length + otherNodes.length > topN) {
      let minValue = Infinity;
      let nodeToDelete: NodeKey | undefined;
      for (const nodeKey of ordinaryNodes) {
        const nodeValue = getNodeValue(graph, nodeKey);
        if (nodeValue < minValue) {
          minValue = nodeValue;
          nodeToDelete = nodeKey;
        }
      }

      if (nodeToDelete === undefined) break; // safety

      moveToOther(
        graph,
        nodeToDelete,
        toolTipInfoMap,
        categorySort === 'global',
      );

      ordinaryNodes = nodesInLayer(graph, layer).filter(isGroupableNode);
      otherNodes = nodesInLayer(graph, layer).filter(s =>
        s.endsWith(SpecialNodeKeys.OtherSuffix),
      );
    }
  });

  return toolTipInfoMap;
}

export function nodesInLayer(graph: Graph, layer: GraphLayer): NodeKey[] {
  return Array.from(graph)
    .filter(([, data]) => data.type === layer)
    .map(([key]) => key);
}

function moveToOther(
  graph: Graph,
  key: NodeKey,
  toolTipInfoMap: TooltipInfoMap,
  globalOther: boolean = false,
) {
  const nodeData = graph.get(key);
  if (!nodeData) {
    return;
  }

  // Get nodes connected to this node
  const toNodes = Array.from(graph.get(key)?.to.keys() ?? []);
  const fromNodes = Array.from(graph).filter(([, data]) => data.to.has(key));

  let otherKey: NodeKey;
  if (globalOther) {
    otherKey = nodeData.type + SpecialNodeKeys.OtherSuffix;
  } else {
    otherKey = nodeData.type + SpecialNodeKeys.OtherSuffix;

    if (nodeData.type === GraphLayers.Category) {
      const categoryGroupResult = getCategoryGroup(graph, key);
      if (categoryGroupResult) {
        const categoryGroupKey = categoryGroupResult[0];
        otherKey = categoryGroupKey + SpecialNodeKeys.OtherSuffix;
      }
    } else if (nodeData.type === GraphLayers.IncomePayee) {
      const incomeCategoryKey = Array.from(
        graph.get(key)?.to.keys() ?? [],
      ).find(k => graph.get(k)?.type === GraphLayers.IncomeCategory);
      if (incomeCategoryKey) {
        otherKey = incomeCategoryKey + SpecialNodeKeys.OtherSuffix;
      }
    }
  }

  // Make sure the Other node exists
  addNode(graph, otherKey, nodeData.type, 'Other');

  fromNodes.forEach(([fromKey, fromData]) => {
    const linkValue = fromData.to.get(key);
    if (linkValue !== undefined) {
      // Avoid creating self-links (otherKey -> otherKey) which produce
      // immediate cycles and can break recursive layer computation.
      if (fromKey !== otherKey) {
        addValueToLink(graph, fromKey, otherKey, linkValue);
        newAddTooltipInfo(
          toolTipInfoMap,
          fromKey,
          otherKey,
          graph.get(key)?.name ?? key,
          linkValue,
        );
      }
    }
  });
  toNodes.forEach(toKey => {
    const fromData = graph.get(key);
    const linkValue = fromData?.to.get(toKey);
    if (linkValue !== undefined) {
      // Avoid creating self-links (otherKey -> otherKey)
      if (otherKey !== toKey) {
        addValueToLink(graph, otherKey, toKey, linkValue);
        newAddTooltipInfo(
          toolTipInfoMap,
          otherKey,
          toKey,
          graph.get(key)?.name ?? key,
          linkValue,
        );
      }
    }
  });

  toNodes.forEach(toKey => {
    deleteLink(graph, key, toKey);
  });
  fromNodes.forEach(([fromKey]) => {
    deleteLink(graph, fromKey, key);
  });

  graph.delete(key);
}

function newAddTooltipInfo(
  toolTipInfoMap: TooltipInfoMap,
  from: NodeKey,
  to: NodeKey,
  name: string,
  value: number,
) {
  if (!toolTipInfoMap.has(from)) {
    toolTipInfoMap.set(from, new Map());
  }
  const innerMap = toolTipInfoMap.get(from)!;
  const existingInfo = innerMap.get(to) ?? [];
  if (!existingInfo.find(info => info.name === name)) {
    innerMap.set(to, [...existingInfo, { name, value }]);
  }
}

export function getCategoryGroup(graph: Graph, key: NodeKey) {
  return Array.from(graph).filter(
    ([, data]) => data.to.has(key) && data.type === GraphLayers.CategoryGroup,
  )[0];
}

export function deleteLink(graph: Graph, from: NodeKey, to: NodeKey) {
  const fromNode = graph.get(from);
  if (fromNode) {
    fromNode.to.delete(to);
  }
}

export function sortGraph(
  graph: Graph,
  categorySort: SortMode = 'per-group',
  categories: CategoryGroupEntity[],
): Graph {
  function sortRelatedNodesAroundAnchors(
    entries: Array<[string, NodeData]>,
    anchorLayer: GraphLayer,
    relatedLayer: GraphLayer,
    placement: 'before' | 'after',
  ) {
    const anchorKeys = nodesInLayer(graph, anchorLayer);

    anchorKeys.forEach(anchorKey => {
      const anchor = graph.get(anchorKey);
      if (!anchor) return;

      const relatedKeys =
        placement === 'after'
          ? Array.from(anchor.to.keys()).filter(
              key => graph.get(key)?.type === relatedLayer,
            )
          : Array.from(graph)
              .filter(
                ([, data]) =>
                  data.type === relatedLayer && data.to.has(anchorKey),
              )
              .map(([key]) => key);

      const otherKey = `${anchorKey}${SpecialNodeKeys.OtherSuffix}`;
      const relatedOtherKey =
        graph.get(otherKey)?.type === relatedLayer ? otherKey : undefined;
      const orderedRelatedKeys = relatedKeys.filter(key => key !== otherKey);

      const relatedEntries = orderedRelatedKeys
        .map(key => entries.find(([entryKey]) => entryKey === key))
        .filter((entry): entry is [string, NodeData] => entry !== undefined);
      relatedEntries.sort(
        ([keyA], [keyB]) =>
          getNodeValue(graph, keyB) - getNodeValue(graph, keyA),
      );

      const otherEntry = relatedOtherKey
        ? entries.find(([entryKey]) => entryKey === relatedOtherKey)
        : undefined;

      const relatedKeysToMove = new Set(orderedRelatedKeys);
      if (relatedOtherKey) {
        relatedKeysToMove.add(relatedOtherKey);
      }
      const entriesWithoutRelated = entries.filter(
        ([entryKey]) => !relatedKeysToMove.has(entryKey),
      );
      const anchorIndex = entriesWithoutRelated.findIndex(
        ([entryKey]) => entryKey === anchorKey,
      );
      if (anchorIndex === -1) {
        return;
      }

      const insertionIndex =
        placement === 'before' ? anchorIndex : anchorIndex + 1;
      const nodesToInsert = otherEntry
        ? [...relatedEntries, otherEntry]
        : relatedEntries;

      entriesWithoutRelated.splice(insertionIndex, 0, ...nodesToInsert);
      entries.length = 0;
      entries.push(...entriesWithoutRelated);
    });
  }

  let sortedEntries: Array<[string, NodeData]>;
  if (categorySort === 'global') {
    sortedEntries = Array.from(graph.entries()).sort(
      ([keyA], [keyB]) => getNodeValue(graph, keyB) - getNodeValue(graph, keyA),
    );
    sortedEntries.forEach(([key]) => {
      if (key.endsWith(SpecialNodeKeys.OtherSuffix)) {
        moveNodeToEnd(sortedEntries, key);
      }
    });
  } else if (categorySort === 'per-group') {
    sortedEntries = Array.from(graph.entries()).sort(
      ([keyA], [keyB]) => getNodeValue(graph, keyB) - getNodeValue(graph, keyA),
    );

    sortRelatedNodesAroundAnchors(
      sortedEntries,
      GraphLayers.CategoryGroup,
      GraphLayers.Category,
      'after',
    );
    sortRelatedNodesAroundAnchors(
      sortedEntries,
      GraphLayers.IncomeCategory,
      GraphLayers.IncomePayee,
      'before',
    );
  } else {
    const used = new Set<NodeKey>();
    sortedEntries = [];

    // 1. Add entries by category group and subcategory order
    categories.forEach(group => {
      const groupNode = graph.get(group.id);
      if (groupNode) {
        sortedEntries.push([group.id, groupNode]);
        used.add(group.id);
      }

      if (group.categories && group.categories.length) {
        group.categories.forEach(cat => {
          const categoryNode = graph.get(cat.id);
          if (categoryNode) {
            sortedEntries.push([cat.id, categoryNode]);
            used.add(cat.id);
          }
        });
      }

      const otherKey = `${group.id}${SpecialNodeKeys.OtherSuffix}`;
      const otherNode = graph.get(otherKey);
      if (otherNode) {
        sortedEntries.push([otherKey, otherNode]);
        used.add(otherKey);
      }
    });

    // 2. Add all remaining entries that weren't used (preserving graph order)
    for (const [key, data] of graph) {
      if (!used.has(key)) {
        sortedEntries.push([key, data]);
      }
    }
  }

  // We always want certain nodes to be shown at the start/end of their layers
  sortedEntries
    .filter(([, nodeData]) => nodeData.isNegative)
    .forEach(([key]) => {
      moveNodeToStart(sortedEntries, key);
    });
  const toBudgetNode = graph.get(SpecialNodeKeys.ToBudget);
  if (toBudgetNode) {
    if (toBudgetNode.isNegative) {
      moveNodeToStart(sortedEntries, SpecialNodeKeys.ToBudget);
    } else {
      moveNodeToEnd(sortedEntries, SpecialNodeKeys.ToBudget);
    }
  }
  moveNodeToEnd(sortedEntries, SpecialNodeKeys.LastMonthOverspent);
  moveNodeToEnd(sortedEntries, SpecialNodeKeys.ForNextMonth);
  moveNodeToEnd(sortedEntries, SpecialNodeKeys.FromPrevMonth);
  return new Map(sortedEntries);
}

export function moveNodeToEnd(
  entries: Array<[string, NodeData]>,
  key: NodeKey,
) {
  const nodeIndex = entries.findIndex(([nodekey]) => nodekey === key);
  if (nodeIndex !== -1) {
    const [entry] = entries.splice(nodeIndex, 1);
    entries.push(entry);
  }
}

export function moveNodeToStart(
  entries: Array<[string, NodeData]>,
  key: NodeKey,
) {
  const nodeIndex = entries.findIndex(([nodekey]) => nodekey === key);
  if (nodeIndex !== -1) {
    const [entry] = entries.splice(nodeIndex, 1);
    entries.unshift(entry);
  }
}

export function getNodeValue(
  graph: Graph,
  key: NodeKey,
  computedLayersByNode?: Map<NodeKey, VisualLayerIndex>,
): number {
  const resolvedLayersByNode =
    computedLayersByNode ?? getComputedNodeLayers(graph);
  let nodeValue: number = 0;

  if ((resolvedLayersByNode.get(key) ?? 0) === 0) {
    // Look at outgoing links for root nodes
    const node = graph.get(key);
    if (node) {
      node.to.forEach((value, targetKey) => {
        if (isHiddenNodeKey(targetKey)) {
          return;
        }
        nodeValue += value ?? 0;
      });
    }
  } else {
    graph.forEach((data, sourceKey) => {
      if (isHiddenNodeKey(sourceKey)) {
        return;
      }
      nodeValue += data.to.get(key) ?? 0;
    });

    // If node is in reality a root node, masked behind hidden nodes
    if (nodeValue < 0) {
      nodeValue = 0;
      const node = graph.get(key);
      if (node) {
        node.to.forEach((value, targetKey) => {
          if (isHiddenNodeKey(targetKey)) {
            return;
          }
          nodeValue += value;
        });
      }
    }
  }
  return nodeValue;
}

export function addPercentageLabels(graph: Graph): void {
  const layerSums = new Map<VisualLayerIndex, number>();
  const computedLayersByNode = getComputedNodeLayers(graph);

  // First pass: calculate visual-layer sums
  graph.forEach((_: NodeData, key: NodeKey) => {
    if (isHiddenNodeKey(key)) {
      return;
    }

    const layer = computedLayersByNode.get(key);
    if (layer === undefined) {
      return;
    }

    const nodeValue = getNodeValue(graph, key, computedLayersByNode);
    layerSums.set(layer, (layerSums.get(layer) ?? 0) + nodeValue);
  });

  // Second pass: assign percentage label to each node
  graph.forEach((data: NodeData, key: NodeKey) => {
    if (isHiddenNodeKey(key)) {
      data.percentageLabel = undefined;
      return;
    }

    const layer = computedLayersByNode.get(key);
    if (layer === undefined) {
      data.percentageLabel = undefined;
      return;
    }

    const nodeValue = getNodeValue(graph, key, computedLayersByNode);
    const layerTotal = layerSums.get(layer) ?? 1;
    const percentage = layerTotal ? (nodeValue / layerTotal) * 100 : 0;
    data.percentageLabel = `${percentage.toFixed(1)}%`;
  });
}

function addColors(graph: Graph) {
  const colors = getColorScale('qualitative');

  for (const key of graph.keys()) {
    const node = graph.get(key);
    if (node) {
      node.color = colors[colorIndexFromKey(key, colors.length)];
    }
  }

  setColor(graph, SpecialNodeKeys.ToBudget, theme.toBudgetPositive);
  graph.forEach((node, key) => {
    if (node.isNegative) {
      setColor(graph, key, theme.toBudgetNegative);
    }
  });
  setColor(graph, SpecialNodeKeys.LastMonthOverspent, theme.toBudgetNegative);
  setColor(graph, SpecialNodeKeys.FromPrevMonth, theme.reportsGray);
  setColor(graph, SpecialNodeKeys.ForNextMonth, theme.reportsGray);
  setColor(graph, SpecialNodeKeys.Budgeted, theme.reportsBlue);
  setColor(graph, SpecialNodeKeys.AvailableIncome, theme.reportsBlue);
  setColor(graph, SpecialNodeKeys.AllAccounts, theme.reportsBlue);
}

function colorIndexFromKey(key: string, colorCount: number): number {
  // Use the first three chars of the key (UUID) as a stable random value
  const hex = key.replace(/[^0-9a-f]/gi, '').slice(0, 3);
  const val = parseInt(hex || '0', 16);
  return val % colorCount;
}

function setColor(graph: Graph, key: NodeKey, color: string) {
  const node = graph.get(key);
  if (node) {
    node.color = color;
  }
}

export function addHiddenNodes(graph: Graph) {
  // Nodes with parents/children different than other nodes in the same layer might end up
  // in the wrong place in the graph. This fixes that, by adding extra, hidden nodes.

  // Group nodes by type
  const nodesByType: Partial<Record<GraphLayer, Array<[NodeKey, NodeData]>>> =
    {};

  for (const [key, node] of graph) {
    if (!nodesByType[node.type]) nodesByType[node.type] = [];
    nodesByType[node.type]!.push([key, node]);
  }

  const { typeHasParent, typeHasChild } = buildTypeConnectivity(
    graph,
    nodesByType,
  );

  const activeLayerOrder = GRAPH_LAYER_ORDER.filter(
    layer => (nodesByType[layer]?.length ?? 0) > 0,
  );
  const layerIndex = new Map<GraphLayer, number>();
  activeLayerOrder.forEach((layer, index) => {
    layerIndex.set(layer, index);
  });

  function addHiddenParentChain(key: NodeKey, type: GraphLayer) {
    const typeIndex = layerIndex.get(type);
    if (typeIndex === undefined || typeIndex <= 0) {
      return;
    }

    let childKey = key;
    for (let i = typeIndex - 1; i >= 0; i--) {
      const parentType = activeLayerOrder[i];
      if (!parentType) {
        continue;
      }
      const parentKey = `${key}_${parentType}${SpecialNodeKeys.HiddenSuffix}`;
      addNode(graph, parentKey, parentType, '');
      addValueToLink(graph, parentKey, childKey, -1);
      childKey = parentKey;
    }
  }

  function addHiddenChildChain(key: NodeKey, type: GraphLayer) {
    const typeIndex = layerIndex.get(type);
    if (
      typeIndex === undefined ||
      typeIndex < 0 ||
      typeIndex >= activeLayerOrder.length - 1
    ) {
      return;
    }

    let parentKey = key;
    for (let i = typeIndex + 1; i < activeLayerOrder.length; i++) {
      const childType = activeLayerOrder[i];
      if (!childType) {
        continue;
      }
      const childKey = `${key}_${childType}${SpecialNodeKeys.HiddenSuffix}`;
      addNode(graph, childKey, childType, '');
      addValueToLink(graph, parentKey, childKey, -1);
      parentKey = childKey;
    }
  }

  // Now: find and fix "problematic" nodes
  for (const typeStr in nodesByType) {
    if (!isGraphLayer(typeStr)) continue;
    const type = typeStr;
    const nodes = nodesByType[type];
    if (!nodes) continue;
    for (const [key, node] of nodes) {
      const nodeHasParent = hasParent(graph, key);
      const nodeHasChild = hasChild(node);
      if (!nodeHasParent && typeHasParent[type]) {
        // This node is at the wrong layer and needs hidden parents.
        addHiddenParentChain(key, type);
      }
      if (!nodeHasChild && typeHasChild[type]) {
        // This node is at the wrong layer and needs hidden children.
        addHiddenChildChain(key, type);
      }
    }
  }

  ensureCategoryGroupsFollowAccountLayers(graph);
}

function ensureCategoryGroupsFollowAccountLayers(graph: Graph) {
  let computedLayersByNode = getComputedNodeLayers(graph);

  let maxVisibleAccountLayer = -1;
  for (const [key, node] of graph) {
    if (node.type !== GraphLayers.Account || isHiddenNodeKey(key)) {
      continue;
    }

    const nodeLayer = computedLayersByNode.get(key);
    if (nodeLayer !== undefined && nodeLayer > maxVisibleAccountLayer) {
      maxVisibleAccountLayer = nodeLayer;
    }
  }

  if (maxVisibleAccountLayer < 0) {
    return;
  }

  const categoryGroupsToPush: NodeKey[] = [];
  for (const [key, node] of graph) {
    if (node.type !== GraphLayers.CategoryGroup) {
      continue;
    }

    const nodeLayer = computedLayersByNode.get(key);
    if (nodeLayer !== undefined && nodeLayer <= maxVisibleAccountLayer) {
      categoryGroupsToPush.push(key);
    }
  }

  for (const key of categoryGroupsToPush) {
    let currentLayer = computedLayersByNode.get(key);
    while (
      currentLayer !== undefined &&
      currentLayer <= maxVisibleAccountLayer
    ) {
      const deepestParent = getDeepestParentKey(
        graph,
        key,
        computedLayersByNode,
      );
      if (!deepestParent) {
        break;
      }

      const hiddenParentKey = `${key}_${GraphLayers.Account}_${currentLayer}${SpecialNodeKeys.HiddenSuffix}`;
      addNode(graph, hiddenParentKey, GraphLayers.Account, '');
      addValueToLink(graph, deepestParent, hiddenParentKey, -1);
      addValueToLink(graph, hiddenParentKey, key, -1);

      computedLayersByNode = getComputedNodeLayers(graph);
      currentLayer = computedLayersByNode.get(key);
    }
  }
}

function getDeepestParentKey(
  graph: Graph,
  nodeKey: NodeKey,
  computedLayersByNode: Map<NodeKey, VisualLayerIndex>,
): NodeKey | undefined {
  let deepestParent: NodeKey | undefined;
  let deepestLayer = -Infinity;

  for (const [parentKey, data] of graph) {
    if (!data.to.has(nodeKey)) {
      continue;
    }

    const parentLayer = computedLayersByNode.get(parentKey);
    if (parentLayer !== undefined && parentLayer > deepestLayer) {
      deepestLayer = parentLayer;
      deepestParent = parentKey;
    }
  }

  return deepestParent;
}

function buildTypeConnectivity(
  graph: Map<NodeKey, NodeData>,
  nodesByType: Partial<Record<GraphLayer, Array<[NodeKey, NodeData]>>>,
) {
  const typeHasParent = {} as Record<GraphLayer, boolean>;
  const typeHasChild = {} as Record<GraphLayer, boolean>;

  for (const typeStr in nodesByType) {
    if (!isGraphLayer(typeStr)) continue;
    const type = typeStr;
    const nodes = nodesByType[type];
    if (!nodes) continue;
    typeHasParent[type] = false;
    typeHasChild[type] = false;
    for (const [key, node] of nodes) {
      if (hasParent(graph, key)) typeHasParent[type] = true;
      if (hasChild(node)) typeHasChild[type] = true;
    }
  }
  return { typeHasParent, typeHasChild };
}

export function hasParent(
  graph: Map<NodeKey, NodeData>,
  key: NodeKey,
): boolean {
  for (const [_, data] of graph) {
    if (data.to.has(key)) return true;
  }
  return false;
}

export function hasChild(node: NodeData): boolean {
  return node.to.size > 0;
}

export function filterGraphByLayers(
  graph: Graph,
  layerFrom: GraphLayer,
  layerTo: GraphLayer,
): void {
  const layerIndices = new Map<string, number>();
  GRAPH_LAYER_ORDER.forEach((layer, index) => {
    layerIndices.set(layer, index);
  });

  const fromIndex = layerIndices.get(layerFrom);
  const toIndex = layerIndices.get(layerTo);

  if (fromIndex !== undefined && toIndex !== undefined) {
    const keysToDelete: NodeKey[] = [];
    graph.forEach((data, key) => {
      const nodeLayerIndex = layerIndices.get(data.type);
      if (nodeLayerIndex !== undefined) {
        if (nodeLayerIndex < fromIndex || nodeLayerIndex > toIndex) {
          keysToDelete.push(key);
        }
      }
    });

    keysToDelete.forEach(key => graph.delete(key));
  }
}

export function cleanUpNodes(graph: Graph) {
  // 1. Remove all `.to` links with value ===0
  for (const [, node] of graph) {
    for (const [target, value] of node.to) {
      if (value === 0) {
        node.to.delete(target);
      }
    }
  }

  // 2. Find all nodes that are targets of remaining links ("has incoming link")
  const hasIncoming = new Set<NodeKey>();
  for (const [, node] of graph) {
    for (const target of node.to.keys()) {
      hasIncoming.add(target);
    }
  }

  // 3. Collect keys to remove (no incoming links and no outgoing links)
  const toDelete: NodeKey[] = [];
  for (const [key, node] of graph) {
    const hasOutgoing = node.to.size > 0;
    const incoming = hasIncoming.has(key);
    if (!hasOutgoing && !incoming) {
      toDelete.push(key);
    }
  }

  // 4. Remove these nodes from the graph
  for (const key of toDelete) {
    graph.delete(key);
  }
}

export function convertToSankeyData(
  graph: Graph,
  toolTipInfoMap: TooltipInfoMap,
): SankeyData {
  const nodes = Array.from(graph, ([key, data]) => ({
    key,
    name: data.labelKey
      ? t(data.labelKey, data.labelParams)
      : (data.name ?? key),
    percentageLabel: data.percentageLabel ?? '',
    color: data.color ?? undefined,
  }));
  const links = Array.from(graph).flatMap(([key, data]) =>
    Array.from(data.to, ([targetKey, value]) => {
      const tooltipInfo = toolTipInfoMap.get(key)?.get(targetKey) ?? [];

      tooltipInfo.sort((a, b) => b.value - a.value);

      let color: string | undefined;
      const sourceLayersWithOwnColor: readonly GraphLayer[] = [
        GraphLayers.IncomePayee,
        GraphLayers.IncomeCategory,
        GraphLayers.Account,
        GraphLayers.CategoryGroup,
      ];
      const targetLayersWithTargetColor: readonly GraphLayer[] = [
        GraphLayers.Category,
        GraphLayers.Budget,
      ];

      if (
        isGraphLayer(data.type) &&
        sourceLayersWithOwnColor.includes(data.type)
      ) {
        color = data.color;
      } else if (
        isGraphLayer(data.type) &&
        targetLayersWithTargetColor.includes(data.type)
      ) {
        const targetNode = graph.get(targetKey);
        color = targetNode ? targetNode.color : undefined;
      }

      // Specific color overrides
      if (targetKey === SpecialNodeKeys.LastMonthOverspent) {
        color = graph.get(SpecialNodeKeys.LastMonthOverspent)?.color;
      }
      if (targetKey.endsWith(SpecialNodeKeys.NegativeSuffix)) {
        color = graph.get(targetKey)?.color;
      }
      if (targetKey === SpecialNodeKeys.ToBudget) {
        color = graph.get(SpecialNodeKeys.ToBudget)?.color;
      }
      if (targetKey === SpecialNodeKeys.ForNextMonth) {
        color = graph.get(SpecialNodeKeys.ForNextMonth)?.color;
      }
      if (data.isNegative) {
        color = data.color;
      }

      return {
        source: nodes.findIndex(n => n.key === key) ?? -1,
        target: nodes.findIndex(n => n.key === targetKey) ?? -1,
        value,
        tooltipInfo,
        color: color ?? undefined,
      };
    }),
  );

  return {
    nodes,
    links,
  };
}