All files / src/pages/flowsheet-page/economics/results-panel/model formulaBreakdownModel.ts

0% Statements 0/49
0% Branches 0/36
0% Functions 0/12
0% Lines 0/41

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                                                                                                                                                                                                                                                                                                                                                                                             
import type { EconomicsResultLineRead } from "@/api/apiStore.gen";
import { EconomicsResultLineKindEnum } from "@/api/apiStore.gen";
import { formatAmountWithUnit } from "../../capital/economicsCapitalFactors";
import { formatUnit } from "../../shared/model/economicsFormatters";
import {
  arrayValue,
  isPresent,
  numberLikeValue,
  objectValue,
  stringField,
} from "./valueParsing";
 
export type MetricFormulaBreakdown = {
  ariaLabel: string;
  formula: string;
  rows: {
    label: string;
    value: string;
  }[];
};
 
export function metricBreakdownFromPayload(
  line: EconomicsResultLineRead,
  resultCurrency: string,
): MetricFormulaBreakdown | null {
  const formulaPayload = objectValue(line.formula_audit);
  const unit = formatUnit(line.unit, resultCurrency);
  return metricFormulaBreakdown(line, formulaPayload, unit, resultCurrency);
}
 
export function depreciationBreakdownFromPayload(
  line: EconomicsResultLineRead,
  resultCurrency: string,
): MetricFormulaBreakdown | null {
  Iif (line.kind !== EconomicsResultLineKindEnum.Depreciation) return null;
  const payload = objectValue(line.warning_payload);
  const depreciableBasis = numberLikeValue(payload?.depreciable_basis);
  const lifeYears = numberLikeValue(payload?.life_years);
  const salvagePercent = numberLikeValue(payload?.salvage_percent);
  const unit = formatUnit(line.unit, resultCurrency);
  Iif (depreciableBasis == null || lifeYears == null) return null;
  return {
    ariaLabel: `straight-line depreciation calculation for ${line.label}`,
    formula: "Straight-line depreciation = depreciable basis / equipment life",
    rows: [
      {
        label: "Depreciable basis",
        value: formatAmountWithUnit(depreciableBasis, resultCurrency),
      },
      {
        label: "Equipment life",
        value: formatAmountWithUnit(lifeYears, "years"),
      },
      {
        label: "Residual value",
        value:
          salvagePercent == null
            ? "-"
            : formatAmountWithUnit(salvagePercent, "%"),
      },
      {
        label: "Annual depreciation",
        value: formatAmountWithUnit(line.amount, unit),
      },
    ],
  };
}
 
function metricFormulaBreakdown(
  line: EconomicsResultLineRead,
  formulaPayload: Record<string, unknown> | null,
  unit: string,
  resultCurrency: string,
): MetricFormulaBreakdown | null {
  const rawFormula = stringField(formulaPayload?.formula);
  const formulaInputs = arrayValue(formulaPayload?.inputs)
    .map(objectValue)
    .filter(isPresent)
    .map((input) => ({
      key: stringField(input.key),
      label: stringField(input.label || input.key),
      value: numberLikeValue(input.value),
      unit: formatUnit(stringField(input.unit) || unit, resultCurrency),
    }));
  const formula = renderFormulaDisplayText({
    formula: rawFormula,
    inputs: formulaInputs,
    lineLabel: line.label,
  });
  const inputs = formulaInputs.filter((input) => {
    Iif (!input.label || input.value == null) return false;
    return !isIdentityFormulaInput({
      formula: rawFormula,
      inputKey: input.key,
    });
  });
  const steps = arrayValue(formulaPayload?.steps)
    .map(objectValue)
    .filter(isPresent)
    .map((step) => ({
      label: stringField(step.label || step.kind),
      value: numberLikeValue(step.amount),
      unit: formatUnit(stringField(step.unit) || unit, resultCurrency),
    }))
    .filter((step) => step.label && step.value != null);
  Iif (!rawFormula) return null;
  if (
    isIdentityFormula({ formula: rawFormula, inputs: formulaInputs }) &&
    inputs.length === 0 &&
    steps.length === 0
  ) {
    return null;
  }
  return {
    ariaLabel:
      line.row_key === "metric.annual_savings"
        ? `annual savings calculation for ${line.label}`
        : `${line.label} calculation`,
    formula,
    rows: [
      ...inputs.map((input) => ({
        label: input.label,
        value: formatAmountWithUnit(input.value, input.unit),
      })),
      ...steps.map((step) => ({
        label: step.label,
        value: formatAmountWithUnit(step.value, step.unit),
      })),
      {
        label: line.label,
        value: formatAmountWithUnit(line.amount, unit),
      },
    ],
  };
}
 
function isIdentityFormulaInput({
  formula,
  inputKey,
}: {
  formula: string;
  inputKey: string;
}) {
  return formula === inputKey;
}
 
function renderFormulaDisplayText({
  formula,
  inputs,
  lineLabel,
}: {
  formula: string;
  inputs: { key: string; label: string }[];
  lineLabel: string;
}) {
  Iif (!formula) return "";
  const identityInput = inputs.find(
    (input) => input.key && formula === input.key,
  );
  Iif (identityInput) return lineLabel;
  const labelByKey = new Map(
    inputs
      .filter((input) => input.key && input.label)
      .map((input) => [input.key, input.label]),
  );
  Iif (labelByKey.size === 0) return formula;
  const inputPattern = Array.from(labelByKey.keys())
    .sort((left, right) => right.length - left.length)
    .map(escapeRegExp)
    .join("|");
  return formula.replace(
    new RegExp(`(^|[^A-Za-z0-9_])(${inputPattern})(?=$|[^A-Za-z0-9_])`, "g"),
    (_, prefix: string, key: string) =>
      `${prefix}${labelByKey.get(key) ?? key}`,
  );
}
 
function isIdentityFormula({
  formula,
  inputs,
}: {
  formula: string;
  inputs: { key: string }[];
}) {
  return inputs.some((input) => input.key && formula === input.key);
}
 
function escapeRegExp(value: string) {
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}