All files / src/pages/flowsheet-page/economics/comparison-panel ComparisonMetricsTable.tsx

80.13% Statements 117/146
49.42% Branches 43/87
52.38% Functions 11/21
83.9% Lines 73/87

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 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333                                                          103x 103x 103x   7x         14x   14x           7x           14x 28x 7x             14x 21x       105x             14x                     28x       14x 14x                             14x 14x 30x                       225x           225x       225x                     28x   42x             14x             28x   14x       28x       84x   42x 70x         14x       30x                   14x           225x                                   84x   84x   252x   168x     141x   423x 282x       282x 141x         423x 423x 141x   564x 423x       84x     84x 168x 168x       28x             28x 28x   28x           56x 56x 84x       8x 3x       4x       4x                                         8x 8x       30x             90x   30x   60x           3x     5x        
import { type ReactNode, useMemo } from "react";
import { ScrollArea } from "@/ahuora-design-system/ui/scroll-area";
import {
  type ComparisonPayload,
  type MetricComparisonDirection,
} from "@/api/apiStore.gen";
import { cn } from "@/lib/utils";
import { KeyFinancialMetricsFrame } from "../results-panel/tables/KeyFinancialMetricsTable";
import { ResultDataTable } from "../results-panel/tables/resultTable";
import { resultColumn } from "../results-panel/tables/resultTableColumns";
import { formatAmount, formatUnit } from "../shared/model/economicsFormatters";
import { formatPercentageDifference } from "./comparisonFormatters";
import {
  compactComparisonStatusLabel,
  deltaToneForDirection,
} from "./model/comparisonStatusPresentation";
import {
  type ComparisonRow,
  type ComparisonStudy,
  type ComparisonSummaryItem,
  comparisonFinancialRows,
  comparisonStudiesWithBaselineFirst,
  comparisonSummaryItems,
  comparisonValueForStudy,
  studyHeaderMeta,
  studyHeaderTitle,
} from "./model/comparisonTableModel";
 
const BEST_COMPARISON_CELL_CLASS =
  "bg-emerald-500/10 text-emerald-950 dark:bg-emerald-400/10 dark:text-emerald-100";
const COMPARISON_METRIC_COLUMN_WIDTH_REM = 10;
const COMPARISON_STUDY_COLUMN_WIDTH_REM = 16;
 
export function ComparisonMetricsTable({
  comparison,
}: {
  comparison: ComparisonPayload;
}) {
  const rows = useMemo(() => comparisonFinancialRows(comparison), [comparison]);
  const summaryItems = useMemo(
    () => comparisonSummaryItems(comparison),
    [comparison],
  );
 
  return (
    <div className="space-y-3">
      <ComparisonMetricSection
        ariaLabel="Comparison key financial metrics"
        tableAriaLabel="Comparison key financial metric rows"
        title="Key financial metrics"
        comparison={comparison}
        rows={rows}
        summary={<ComparisonSummary items={summaryItems} />}
      />
      <ComparisonMetricSection
        ariaLabel="Comparison key resource metrics"
        tableAriaLabel="Comparison key resource metric rows"
        title="Key resource metrics"
        comparison={comparison}
        rows={comparison.resource_rows}
        emptyMessage="No resource rows"
      />
    </div>
  );
}
 
function ComparisonMetricSection({
  ariaLabel,
  tableAriaLabel,
  title,
  comparison,
  rows,
  summary,
  emptyMessage = "No comparison rows",
}: {
  ariaLabel: string;
  tableAriaLabel: string;
  title: string;
  comparison: ComparisonPayload;
  rows: ComparisonRow[];
  summary?: ReactNode;
  emptyMessage?: string;
}) {
  const orderedStudies = useMemo(
    () => comparisonStudiesWithBaselineFirst(comparison),
    [comparison],
  );
  const columns = useMemo(
    () => [
      resultColumn<ComparisonRow>({
        key: "metric",
        header: (
          <div className="grid min-w-0 gap-0.5 text-left">
            <div className="truncate text-sm font-medium leading-tight text-foreground">
              Metric
            </div>
            <div className="min-h-4 text-xs font-normal text-muted-foreground" />
          </div>
        ),
        headClassName:
          "sticky left-0 z-30 min-w-40 border-r bg-muted py-2 align-top text-foreground",
        cellClassName:
          "sticky left-0 z-10 min-w-40 border-r bg-background py-3 font-medium text-foreground",
        render: (row) => row.label,
      }),
      ...orderedStudies.map((study) =>
        resultColumn<ComparisonRow>({
          key: `study-${study.id ?? study.name}`,
          header: (
            <div className="grid min-w-0 justify-items-end gap-0.5 text-right">
              <div className="truncate text-sm font-medium leading-tight text-foreground">
                {studyHeaderTitle(study, comparison)}
              </div>
              <StudyHeaderMeta study={study} comparison={comparison} />
            </div>
          ),
          headClassName: "min-w-44 border-l py-2 text-right align-top",
          cellClassName: (row) =>
            cn(
              "min-w-44 border-l py-3 text-right tabular-nums",
              comparisonValueForStudy(row, study.id)?.is_best &&
                BEST_COMPARISON_CELL_CLASS,
            ),
          getCellDataState: (row) =>
            comparisonValueForStudy(row, study.id)?.is_best
              ? "best-value"
              : undefined,
          render: (row) => {
            const value = comparisonValueForStudy(row, study.id);
            return (
              <ComparisonValueCell
                value={value}
                comparisonDirection={row.comparison_direction}
                resultCurrency={study.result_currency}
                isBaseline={study.id === comparison.baseline_study_id}
                maximumFractionDigits={row.maximum_fraction_digits}
              />
            );
          },
        }),
      ),
    ],
    [comparison, orderedStudies],
  );
 
  return (
    <KeyFinancialMetricsFrame ariaLabel={ariaLabel} title={title}>
      {summary}
      <ScrollArea
        type="always"
        horizontalScrollbar
        className="w-full rounded-sm"
      >
        <div
          className="min-w-full pb-3"
          style={{ minWidth: comparisonTableMinWidth(orderedStudies.length) }}
        >
          <ResultDataTable
            ariaLabel={tableAriaLabel}
            columns={columns}
            rows={rows}
            colgroup={comparisonTableColgroup(orderedStudies.length)}
            getRowKey={(row) => row.row_key}
            emptyMessage={emptyMessage}
            tableClassName="table-fixed"
          />
        </div>
      </ScrollArea>
    </KeyFinancialMetricsFrame>
  );
}
 
function comparisonTableColgroup(studyCount: number) {
  return (
    <colgroup>
      <col style={{ width: `${COMPARISON_METRIC_COLUMN_WIDTH_REM}rem` }} />
      {Array.from({ length: studyCount }).map((_, index) => (
        <col
          key={index}
          style={{ width: `${COMPARISON_STUDY_COLUMN_WIDTH_REM}rem` }}
        />
      ))}
    </colgroup>
  );
}
 
function comparisonTableMinWidth(studyCount: number) {
  return `${
    COMPARISON_METRIC_COLUMN_WIDTH_REM +
    studyCount * COMPARISON_STUDY_COLUMN_WIDTH_REM
  }rem`;
}
 
function ComparisonValueCell({
  value,
  comparisonDirection,
  resultCurrency,
  isBaseline,
  maximumFractionDigits,
}: {
  value: ComparisonRow["values"][number] | undefined;
  comparisonDirection: MetricComparisonDirection;
  resultCurrency: string;
  isBaseline: boolean;
  maximumFractionDigits: number;
}) {
  if (!value) {
    return <UnavailableComparisonValue label="No result" />;
  }
  if (value.amount == null) {
    return (
      <UnavailableComparisonValue
        label={
          isBaseline
            ? undefined
            : compactComparisonStatusLabel(value.comparison_status)
        }
      />
    );
  }
  const amount = `${formatAmount(value.amount, {
    maximumFractionDigits,
  })} ${formatUnit(value.unit, resultCurrency)}`;
  const statusLabel = compactComparisonStatusLabel(value.comparison_status);
  return (
    <div className="grid justify-items-end gap-1 leading-tight">
      <div className="flex flex-wrap items-baseline justify-end gap-x-2 gap-y-1">
        <span className="font-medium text-foreground">{amount}</span>
        {value.percentage_difference != null && (
          <ComparisonDelta
            value={value.percentage_difference}
            comparisonDirection={comparisonDirection}
          />
        )}
      </div>
      {value.percentage_difference == null && !isBaseline && statusLabel && (
        <span className="text-xs text-muted-foreground">{statusLabel}</span>
      )}
    </div>
  );
}
 
function UnavailableComparisonValue({ label }: { label?: string }) {
  return (
    <div className="grid gap-1 leading-tight text-muted-foreground">
      <span className="font-medium">-</span>
      {label && <span className="text-xs">{label}</span>}
    </div>
  );
}
 
function ComparisonDelta({
  value,
  comparisonDirection,
}: {
  value: string;
  comparisonDirection: MetricComparisonDirection;
}) {
  const parsed = Number(value);
  const deltaTone = deltaToneForDirection(comparisonDirection, parsed);
  const tone =
    deltaTone === "negative"
      ? "text-rose-700 dark:text-rose-300"
      : deltaTone === "positive"
        ? "text-emerald-700 dark:text-emerald-300"
        : "text-muted-foreground";
  return (
    <span className={cn("shrink-0 text-xs font-semibold tabular-nums", tone)}>
      {formatPercentageDifference(value)}
    </span>
  );
}
 
function ComparisonSummary({ items }: { items: ComparisonSummaryItem[] }) {
  if (items.length === 0) {
    return null;
  }
  return (
    <div
      className="mb-3 grid gap-x-8 gap-y-3 border-b pb-3 sm:grid-cols-3"
      aria-label="Comparison summary"
    >
      {items.map((item) => (
        <div key={item.key} className="min-w-0">
          <div className="truncate text-xs text-muted-foreground">
            {item.label}
          </div>
          <div className="mt-1 flex min-w-0 flex-wrap items-baseline gap-x-2 gap-y-1">
            <span
              className={cn(
                "shrink-0 text-sm font-semibold tabular-nums",
                summaryValueToneClass(item.tone),
              )}
            >
              {item.value}
            </span>
            {item.status && (
              <span className="shrink-0 text-xs text-muted-foreground">
                {item.status}
              </span>
            )}
          </div>
        </div>
      ))}
    </div>
  );
}
 
function StudyHeaderMeta({
  study,
  comparison,
}: {
  study: ComparisonStudy;
  comparison: ComparisonPayload;
}) {
  const meta = studyHeaderMeta(study, comparison);
  return (
    <div className="min-h-4 truncate text-xs font-normal text-muted-foreground">
      {meta}
    </div>
  );
}
 
function summaryValueToneClass(tone: ComparisonSummaryItem["tone"]) {
  if (tone === "positive") {
    return "text-emerald-700 dark:text-emerald-300";
  }
  if (tone === "negative") {
    return "text-rose-700 dark:text-rose-300";
  }
  return "text-foreground";
}