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

89.33% Statements 67/75
39.02% Branches 16/41
63.63% Functions 7/11
92.45% Lines 49/53

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 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212                                                                          16x           32x 32x 16x 32x       16x   16x 16x   32x 16x     32x       16x             32x 16x                     16x 16x                       32x 16x 16x 33x                     48x 64x 64x 32x 64x         16x       54996x   54996x             54996x 54996x         54996x       54996x     16x 26648x         16x 33x                   33x   16x 16x                 32x 32x         99x       16x   33x 16x             400x 400x 400x             54996x                  
import { CartesianGrid, Line, LineChart, XAxis, YAxis } from "recharts";
import type { ChartConfig } from "@/ahuora-design-system/ui/chart";
import { ChartContainer, ChartTooltip } from "@/ahuora-design-system/ui/chart";
import type {
  ChartAssumption,
  DrillbackHandler,
  ParsedChartDataset,
  WarningRef,
} from "../model/types";
import { numberValue } from "../model/valueParsing";
import { chartTitle } from "./chartData";
import { formatCompactAxisTick, mergeAssumptions } from "./chartFormatters";
import {
  operatingTimelineColors,
  RESULT_CHART_BOTTOM_MARGIN,
  RESULT_CHART_X_AXIS_LABEL_OFFSET,
  RESULT_CHART_Y_AXIS_LABEL_DY,
  RESULT_CHART_Y_AXIS_LABEL_OFFSET,
  RESULT_CHART_Y_AXIS_WIDTH,
} from "./constants";
import { EconomicsChartTooltip } from "./EconomicsChartTooltip";
 
type TimelineRow = {
  elapsedHours: number;
  unit: string;
  sourceRows: Record<
    string,
    {
      unit?: string;
      assumptions?: ChartAssumption[];
      warningRefs?: WarningRef[];
    }
  >;
  warningRefs: WarningRef[];
  [seriesKey: string]: unknown;
};
 
export function OperatingCostTimelineChart({
  dataset,
}: {
  dataset: ParsedChartDataset;
  onDrillback: DrillbackHandler;
}) {
  const rows = timelineRows(dataset);
  const config = timelineChartConfig(dataset);
  const showDots = rows.length <= 40;
  const yAxisLabel = `Operating cost (${timelineUnit(dataset)})`;
 
  return (
    <div className="flex h-full flex-col">
      <div className="sr-only" aria-label="Operating cost x-axis label">
        Operating hours
      </div>
      <div className="sr-only" aria-label="Operating cost y-axis label">
        {yAxisLabel}
      </div>
      <ChartContainer
        config={config}
        className="min-h-0 w-full flex-1"
        aria-label={`Graph ${chartTitle(dataset)}`}
      >
        <LineChart
          data={rows}
          margin={{
            left: 0,
            right: 28,
            top: 16,
            bottom: RESULT_CHART_BOTTOM_MARGIN,
          }}
        >
          <CartesianGrid vertical={false} strokeOpacity={0.35} />
          <XAxis
            dataKey="elapsedHours"
            type="number"
            tickFormatter={formatOperatingHourTick}
            tickLine={false}
            axisLine={false}
            label={{
              value: "Operating hours",
              position: "insideBottom",
              offset: RESULT_CHART_X_AXIS_LABEL_OFFSET,
            }}
          />
          <YAxis
            width={RESULT_CHART_Y_AXIS_WIDTH}
            tickFormatter={formatCompactAxisTick}
            tickLine={false}
            axisLine={false}
            label={{
              value: yAxisLabel,
              angle: -90,
              position: "insideLeft",
              offset: RESULT_CHART_Y_AXIS_LABEL_OFFSET,
              dy: RESULT_CHART_Y_AXIS_LABEL_DY,
            }}
          />
          <ChartTooltip content={<EconomicsChartTooltip />} />
          {dataset.series.map((series, index) => (
            <Line
              key={series.key}
              type="monotone"
              dataKey={series.key}
              name={series.label}
              stroke={timelineColor(index)}
              strokeWidth={series.key === "total" ? 2.5 : 1.75}
              dot={showDots ? { r: series.key === "total" ? 3 : 2 } : false}
              activeDot={{ r: 4 }}
              connectNulls
            />
          ))}
        </LineChart>
      </ChartContainer>
      <OperatingTimelineLegend dataset={dataset} />
    </div>
  );
}
 
function timelineRows(dataset: ParsedChartDataset): TimelineRow[] {
  const rowsByElapsed = new Map<number, TimelineRow>();
  for (const series of dataset.series) {
    for (const point of series.points) {
      const elapsedHours =
        numberValue(point.metadata.elapsed_hours) ?? rowsByElapsed.size;
      const row =
        rowsByElapsed.get(elapsedHours) ??
        ({
          elapsedHours,
          unit: point.unit || series.unit,
          sourceRows: {},
          warningRefs: [],
        } as TimelineRow);
      row[series.key] = point.value;
      row.sourceRows[series.key] = {
        unit: point.unit || series.unit,
        assumptions: mergeAssumptions(point.assumptions),
        warningRefs: point.warning_refs,
      };
      row.warningRefs = mergeWarnings([
        ...row.warningRefs,
        ...point.warning_refs,
      ]);
      rowsByElapsed.set(elapsedHours, row);
    }
  }
  return Array.from(rowsByElapsed.values()).sort(
    (left, right) => left.elapsedHours - right.elapsedHours,
  );
}
 
function timelineChartConfig(dataset: ParsedChartDataset): ChartConfig {
  return Object.fromEntries(
    dataset.series.map((series, index) => [
      series.key,
      {
        label: series.label,
        color: timelineColor(index),
      },
    ]),
  ) as ChartConfig;
}
 
function OperatingTimelineLegend({ dataset }: { dataset: ParsedChartDataset }) {
  return (
    <div className="mt-3 flex flex-wrap items-center justify-start gap-x-4 gap-y-1.5 pl-[84px] pr-2 text-xs leading-5 text-muted-foreground">
      {dataset.series.map((series, index) => (
        <div key={series.key} className="flex min-w-0 items-center gap-1.5">
          <span
            className="size-3 rounded-full"
            style={{ backgroundColor: timelineColor(index) }}
            aria-hidden="true"
          />
          <span className="truncate">{series.label}</span>
        </div>
      ))}
    </div>
  );
}
 
function timelineColor(index: number) {
  return operatingTimelineColors[index % operatingTimelineColors.length];
}
 
function timelineUnit(dataset: ParsedChartDataset) {
  return (
    dataset.series
      .flatMap((series) => series.points)
      .find((point) => point.unit)?.unit ||
    dataset.series.find((series) => series.unit)?.unit ||
    "currency"
  );
}
 
function formatOperatingHourTick(value: string | number) {
  const parsed = Number(value);
  Iif (!Number.isFinite(parsed)) return String(value);
  return new Intl.NumberFormat("en-NZ", {
    maximumFractionDigits: 1,
    notation: Math.abs(parsed) >= 10000 ? "compact" : "standard",
  }).format(parsed);
}
 
function mergeWarnings(warnings: WarningRef[]) {
  return Array.from(
    new Map(
      warnings.map((warning) => [
        `${warning.code}-${warning.message}-${warning.source_row_key ?? ""}`,
        warning,
      ]),
    ).values(),
  );
}