All files / src/pages/flowsheet-page/economics/results-panel/charts CashFlowChart.tsx

84.61% Statements 55/65
33.96% Branches 18/53
42.85% Functions 3/7
87.5% Lines 42/48

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162                                                  2x             2x 2x 2x     2x   13x                                   2x 14x     2x       2x 2x 6x 2x   2x 2x   4x 2x     4x       2x   4x 2x               2x       2x 4x 2x                     4x 2x 2x           4x 2x 2x         4x 2x             2x 12x 6x 2x 8x       2x   2x           4x                   2x      
import {
  Bar,
  CartesianGrid,
  ComposedChart,
  Line,
  ReferenceLine,
  XAxis,
  YAxis,
} from "recharts";
import { ChartContainer, ChartTooltip } from "@/ahuora-design-system/ui/chart";
import type { DrillbackHandler, ParsedChartDataset } from "../model/types";
import { numberValue } from "../model/valueParsing";
import { chartTitle } from "./chartData";
import {
  cashFlowAxisUnit,
  cashFlowLegendLabel,
  cashFlowRenderingMetadata,
  cashFlowXDomain,
  formatCompactAxisTick,
  formatYearAxisTick,
  mergeAssumptions,
} from "./chartFormatters";
import { cashFlowChartConfig } from "./constants";
import { EconomicsChartTooltip } from "./EconomicsChartTooltip";
 
export function CashFlowChart({
  dataset,
  onDrillback,
}: {
  dataset: ParsedChartDataset;
  onDrillback: DrillbackHandler;
}) {
  const annualSeries = dataset.series[0];
  const cumulativeSeries = dataset.series[1];
  const paybackYears =
    cashFlowRenderingMetadata(dataset.rendering_metadata)?.payback_years ??
    null;
  const rows =
    annualSeries?.points.map((annualPoint, index) => {
      const cumulativePoint = cumulativeSeries?.points[index];
      return {
        year: numberValue(annualPoint.metadata.year) ?? index,
        annualNetCashFlow: annualPoint.value,
        cumulativeDiscountedCashFlow: cumulativePoint?.value ?? null,
        sourceRowId: annualPoint.source_row?.id,
        sourceRowKey: annualPoint.source_row?.row_key,
        unit: annualPoint.unit || cumulativePoint?.unit || "",
        assumptions: mergeAssumptions([
          ...annualPoint.assumptions,
          ...(cumulativePoint?.assumptions ?? []),
        ]),
        warningRefs: [
          ...annualPoint.warning_refs,
          ...(cumulativePoint?.warning_refs ?? []),
        ],
      };
    }) ?? [];
  const xDomain = cashFlowXDomain(rows, paybackYears);
  const yAxisLabel = `Cash flow (${cashFlowAxisUnit(rows)})`;
  return (
    <div className="flex h-full flex-col">
      <div
        className="sr-only"
        aria-label="Cash-flow numeric x-axis configuration"
        data-axis-type="number"
        data-domain={`${xDomain[0]},${xDomain[1]}`}
        data-payback-x={paybackYears ?? ""}
      />
      <div className="sr-only" aria-label="Cash-flow x-axis label">
        Year
      </div>
      <div className="sr-only" aria-label="Cash-flow y-axis label">
        {yAxisLabel}
      </div>
      <ChartContainer
        config={cashFlowChartConfig}
        className="min-h-0 w-full flex-1"
        aria-label={`Graph ${chartTitle(dataset)}`}
      >
        <ComposedChart
          data={rows}
          margin={{ left: 12, right: 28, top: 16, bottom: 18 }}
        >
          <CartesianGrid vertical={false} strokeOpacity={0.35} />
          <XAxis
            dataKey="year"
            type="number"
            domain={xDomain}
            allowDecimals={false}
            tickFormatter={formatYearAxisTick}
            tickLine={false}
            axisLine={false}
            label={{
              value: "Year",
              position: "insideBottom",
              offset: -4,
            }}
          />
          <YAxis
            width={72}
            tickFormatter={formatCompactAxisTick}
            tickLine={false}
            axisLine={false}
            label={{
              value: yAxisLabel,
              angle: -90,
              position: "insideLeft",
              offset: 4,
            }}
          />
          <ReferenceLine y={0} stroke="hsl(var(--muted-foreground))" />
          {paybackYears != null && (
            <ReferenceLine
              x={paybackYears}
              stroke="hsl(var(--primary))"
              strokeDasharray="4 4"
            />
          )}
          <ChartTooltip content={<EconomicsChartTooltip />} />
          <Bar
            dataKey="annualNetCashFlow"
            name="Annual net cash flow"
            fill="var(--color-annualNetCashFlow)"
            onClick={(data) => onDrillback(data?.sourceRowId)}
          />
          <Line
            type="monotone"
            dataKey="cumulativeDiscountedCashFlow"
            name="Cumulative discounted cash flow"
            stroke="var(--color-cumulativeDiscountedCashFlow)"
            strokeWidth={2}
            dot={{ r: 3 }}
          />
        </ComposedChart>
      </ChartContainer>
      <CashFlowLegend />
    </div>
  );
}
 
function CashFlowLegend() {
  return (
    <div className="mt-3 flex flex-wrap items-center justify-center gap-x-4 gap-y-1 text-sm text-muted-foreground">
      {(
        [
          ["annualNetCashFlow", "hsl(var(--chart-1))"],
          ["cumulativeDiscountedCashFlow", "hsl(var(--chart-2))"],
        ] as const
      ).map(([seriesKey, color]) => (
        <div key={seriesKey} className="flex items-center gap-1.5">
          <span
            className="size-3 rounded-full"
            style={{ backgroundColor: color }}
            aria-hidden="true"
          />
          <span>{cashFlowLegendLabel(seriesKey)}</span>
        </div>
      ))}
    </div>
  );
}