All files / src/pages/flowsheet-page/economics/results-panel/charts chartData.ts

93.84% Statements 61/65
59.09% Branches 26/44
100% Functions 10/10
100% Lines 58/58

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 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284                                                                                      50x 50x 50x 50x 50x   13x     50x           4x   46x 55464x   46x                         94x 94x 94x                   55464x 55464x 55464x 55464x                                           50x 50x             5x                 45x                         50x   44x 44x 44x       44x           1238x 1238x 1238x             55464x 55464x 55464x 5469x               5x                                         34x 34x 34x         34x 34x             34x   5x       46x     82x   55320x                     40320x               34x         41x   5x   34x     5x 34x   5x       8x               34x       26x         14x   91x    
import type { EconomicsChartDatasetRead } from "@/api/apiStore.gen";
import { keyFinancialMetricLabelForKey } from "../model/financialMetricCatalog";
import {
  parseWarningRef,
  uniqueWarnings,
  visibleResultWarnings,
} from "../model/resultWarnings";
import type {
  ChartAssumption,
  ChartDatum,
  ChartMetricOption,
  ChartRenderingMetadata,
  ChartSeries,
  ParsedChartDataset,
  SourceRow,
  WarningRef,
} from "../model/types";
import {
  arrayValue,
  isPresent,
  numericField,
  objectValue,
  scalarValue,
  stringField,
} from "../model/valueParsing";
import {
  CHART_CASH_FLOW_NPV,
  CHART_MANUAL_BASELINE_COMPARISON,
} from "./constants";
 
export type ChartDatasetInput = Pick<
  EconomicsChartDatasetRead,
  | "id"
  | "chart_key"
  | "title"
  | "chart_type"
  | "chart_data"
  | "rendering_metadata"
>;
 
export function parseChartDataset(
  dataset: ChartDatasetInput,
): ParsedChartDataset | null {
  const chartData = objectValue(dataset.chart_data);
  const seriesValue = chartData ? arrayValue(chartData.series) : [];
  const series = seriesValue.map(parseSeries).filter(isPresent);
  const renderingMetadata = objectValue(dataset.rendering_metadata);
  const metadataWarnings = renderingMetadata
    ? arrayValue(renderingMetadata.warning_refs)
        .map((warning) => parseWarningRef(warning))
        .filter(isPresent)
    : [];
  const parsedRenderingMetadata = parseRenderingMetadata(
    dataset.chart_key,
    renderingMetadata,
    metadataWarnings,
  );
  if (series.length === 0) {
    return null;
  }
  const pointWarnings = series.flatMap((item) =>
    item.points.flatMap((point) => point.warning_refs),
  );
  return {
    id: dataset.id,
    chart_key: dataset.chart_key,
    title: stringField(dataset.title),
    chart_type: dataset.chart_type,
    series,
    rendering_metadata: parsedRenderingMetadata,
    warning_refs: uniqueWarnings([...metadataWarnings, ...pointWarnings]),
  };
}
 
/** Keep chart rendering tolerant of partially available backend chart series JSON. */
function parseSeries(value: unknown): ChartSeries | null {
  const source = objectValue(value);
  Iif (!source) return null;
  return {
    key: stringField(source.key),
    label: stringField(source.label),
    unit: stringField(source.unit),
    points: arrayValue(source.points).map(parseDatum).filter(isPresent),
  };
}
 
/** Normalize arbitrary chart-data JSON into the narrow datum shape components expect. */
function parseDatum(value: unknown): ChartDatum | null {
  const source = objectValue(value);
  Iif (!source) return null;
  const sourceRow = parseSourceRow(source.source_row);
  return {
    key: stringField(source.key),
    label: stringField(source.label),
    value: numericField(source.value),
    unit: stringField(source.unit),
    source_row: sourceRow,
    assumptions: arrayValue(source.assumptions)
      .map(parseAssumption)
      .filter(isPresent),
    warning_refs: arrayValue(source.warning_refs)
      .map(parseWarningRef)
      .filter(isPresent),
    metadata: objectValue(source.metadata) ?? {},
  };
}
 
/** Preserve chart-family-specific metadata while giving every chart a common warning channel. */
function parseRenderingMetadata(
  chartKey: string,
  metadata: Record<string, unknown> | null,
  warningRefs: WarningRef[],
): ChartRenderingMetadata {
  const chartFamily = stringField(metadata?.chart_family || chartKey);
  const commonMetadata = {
    metric_options: parseMetricOptions(metadata?.metric_options),
    default_metric_keys: arrayValue(metadata?.default_metric_keys)
      .map(stringField)
      .filter(Boolean),
  };
  if (chartKey === CHART_CASH_FLOW_NPV || chartFamily === "cash_flow_npv") {
    return {
      chart_family: "cash_flow_npv",
      payback_years: numericField(metadata?.payback_years),
      npv: numericField(metadata?.npv),
      zero_reference: numericField(metadata?.zero_reference),
      ...commonMetadata,
      warning_refs: warningRefs,
    };
  }
  return {
    chart_family: chartFamily,
    ...commonMetadata,
    point_limit: numericField(metadata?.point_limit),
    estimated_point_count: numericField(metadata?.estimated_point_count),
    coerced_point_count: numericField(metadata?.coerced_point_count),
    downsampled: metadata?.downsampled === true,
    message: stringField(metadata?.message),
    warning_refs: warningRefs,
  };
}
 
function parseMetricOptions(value: unknown): ChartMetricOption[] {
  return arrayValue(value)
    .map((item) => {
      const source = objectValue(item);
      Iif (!source) return null;
      const option = {
        value: stringField(source.value),
        label: stringField(source.label),
      };
      return option.value && option.label ? option : null;
    })
    .filter(isPresent);
}
 
function parseAssumption(value: unknown): ChartAssumption | null {
  const source = objectValue(value);
  Iif (!source) return null;
  return {
    key: stringField(source.key),
    value: scalarValue(source.value),
  };
}
 
function parseSourceRow(value: unknown): SourceRow | null {
  const source = objectValue(value);
  const id = numericField(source?.id);
  if (!source || id == null) return null;
  return {
    id,
    row_key: stringField(source.row_key),
    label: stringField(source.label),
  };
}
 
export function comparisonRows(dataset: ParsedChartDataset) {
  const byCategory = new Map<
    string,
    {
      category: string;
      categoryLabel: string;
      target?: number | null;
      baseline?: number | null;
      result?: number | null;
      sourceRows: Record<
        string,
        {
          sourceRowId?: number;
          sourceRowKey?: string;
          unit: string;
          assumptions: ChartAssumption[];
          warningRefs: WarningRef[];
        }
      >;
    }
  >();
  for (const point of dataset.series[0]?.points ?? []) {
    const category = stringField(point.metadata.category || point.key);
    const seriesKey = stringField(point.metadata.series_key || "result");
    const row = byCategory.get(category) ?? {
      category,
      categoryLabel: comparisonCategoryLabel(category),
      sourceRows: {},
    };
    row[seriesKey as "target" | "baseline" | "result"] = point.value;
    row.sourceRows[seriesKey] = {
      sourceRowId: point.source_row?.id,
      sourceRowKey: point.source_row?.row_key,
      unit: point.unit,
      assumptions: point.assumptions,
      warningRefs: point.warning_refs,
    };
    byCategory.set(category, row);
  }
  return Array.from(byCategory.values());
}
 
export function displayedChartDataLabels(dataset: ParsedChartDataset) {
  return Array.from(
    new Set(
      dataset.series.flatMap((series) =>
        series.points.map(
          (point) =>
            stringField(point.metadata.category_label) ||
            stringField(point.metadata.metric_label) ||
            point.label ||
            series.label,
        ),
      ),
    ),
  ).filter(Boolean);
}
 
export function metricKeyForChartPoint(point: ChartDatum, seriesKey: string) {
  return (
    stringField(point.metadata.metric_key) ||
    stringField(point.metadata.category) ||
    seriesKey
  );
}
 
export function manualBaselineMetricKey(point: ChartDatum, seriesKey: string) {
  return stringField(point.metadata.category || point.key) || seriesKey;
}
 
export function visibleChartWarnings(dataset: ParsedChartDataset) {
  if (dataset.chart_key !== CHART_MANUAL_BASELINE_COMPARISON) {
    return visibleResultWarnings(dataset.warning_refs);
  }
  const visibleSourceRows = new Set(
    chartSourcePoints(dataset)
      .map((point) => point.source_row?.row_key)
      .filter(isPresent),
  );
  const visiblePointWarnings = chartSourcePoints(dataset).flatMap(
    (point) => point.warning_refs,
  );
  return visibleResultWarnings(
    uniqueWarnings(
      [...dataset.warning_refs, ...visiblePointWarnings].filter(
        (warning) =>
          !warning.source_row_key ||
          visibleSourceRows.has(warning.source_row_key),
      ),
    ),
  );
}
 
export function chartSourcePoints(dataset: ParsedChartDataset) {
  return dataset.series.flatMap((series) => series.points);
}
 
export function comparisonCategoryLabel(category: string) {
  return keyFinancialMetricLabelForKey(category) ?? category.replace(/_/g, " ");
}
 
export function chartTitle(dataset: ParsedChartDataset) {
  if (dataset.chart_key === CHART_MANUAL_BASELINE_COMPARISON) {
    return "Baseline Comparison";
  }
  return dataset.title;
}