All files / src/pages/flowsheet-page/economics/operating-lines-panel EconomicsOperatingLinesPanel.tsx

73.87% Statements 82/111
60.78% Branches 62/102
33.33% Functions 1/3
84.5% Lines 60/71

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                                                                                              71x             74x 71x   74x   71x   71x   71x 71x 71x   71x 71x 71x 80x 80x 76x   77x   71x     71x   13x 168x   71x 3x 3x 3x 266x   71x 1x 1x 1x 1x                 1x 1x   1x         1x                                             1x 1x 1x       406x   71x 2x       2x 201x   71x     201x       3x               8x                                                   3x         63x     63x     243x 68x 59x     75x                 240x 358x 59x                 63x           535x 303x                 83x    
import { ReceiptText } from "lucide-react";
import { useEffect, useState } from "react";
import { Spinner } from "@/ahuora-design-system/ui/spinner";
import type {
  EconomicsStudyRead,
  OperatingCostLine,
  PatchedOperatingCostLine,
} from "@/api/apiStore.gen";
import {
  BlankEnum,
  OperatingCostLineCategoryEnum,
  OperatingCostLineOutletStreamDispositionEnum as OutletStreamDispositionEnum,
  RateSourceModeEnum,
  useEconomicsDefaultRatesListQuery,
  useEconomicsOperatingLinesCreateMutation,
  useEconomicsOperatingLinesDestroyMutation,
  useEconomicsOperatingLinesPartialUpdateMutation,
  useEconomicsStudiesFullRetrieveQuery,
  useEconomicsStudiesOperatingLinesFromPropertiesCreateMutation,
  useEconomicsStudiesOperatingPropertyOptionsListQuery,
} from "@/api/apiStore.gen";
import {
  rateTypeForCategory,
  selectedOperatingDefaultForCategory,
} from "../default-rates/economicsDefaultRates";
import { LineTypeCreator } from "./creators/LineTypeCreator";
import { OutputPropertyLineCreator } from "./creators/OutputPropertyLineCreator";
import {
  defaultBasisUnit,
  defaultRateForCategory,
  defaultRateUnit,
  mutationErrorMessage,
  type OperatingLineIntent,
  operatingLineTypeForIntent,
  type SaveState,
} from "./model/types";
import { OperatingLinesEditorList } from "./OperatingLinesEditorList";
import { FormState } from "./ui/fields";
 
type EconomicsOperatingLinesPanelProps = {
  study: EconomicsStudyRead;
  canEdit: boolean;
  refreshKey?: number;
  focusedOperatingLineId?: number;
  onConfigurationSaved?: () => void;
};
 
export function EconomicsOperatingLinesPanel({
  study,
  canEdit,
  refreshKey,
  focusedOperatingLineId,
  onConfigurationSaved,
}: EconomicsOperatingLinesPanelProps) {
  const fullStudyQuery = useEconomicsStudiesFullRetrieveQuery({ id: study.id });
  const defaultRatesQuery = useEconomicsDefaultRatesListQuery({});
  const operatingPropertyOptionsQuery =
    useEconomicsStudiesOperatingPropertyOptionsListQuery({ id: study.id });
  const [createOperatingLine, createState] =
    useEconomicsOperatingLinesCreateMutation();
  const [createOperatingLinesFromProperties] =
    useEconomicsStudiesOperatingLinesFromPropertiesCreateMutation();
  const [patchOperatingLine] =
    useEconomicsOperatingLinesPartialUpdateMutation();
  const [deleteOperatingLine] = useEconomicsOperatingLinesDestroyMutation();
  const [createStatus, setCreateStatus] = useState<SaveState>({
    kind: "idle",
  });
  const fullStudy = fullStudyQuery.currentData;
  const refetchFullStudy = fullStudyQuery.refetch;
  const operatingLines = fullStudy?.operating_lines ?? [];
  const projectLines = operatingLines.filter((line) => !line.costable_item);
  const defaultRates = defaultRatesQuery.data ?? [];
  const operatingPropertyOptions =
    operatingPropertyOptionsQuery.currentData ?? [];
  const annualOperatingHours =
    fullStudy?.assumptions?.annual_operating_hours ??
    "annual operating hours not set";
 
  useEffect(() => {
    Iif (refreshKey === undefined) return;
    refetchFullStudy();
  }, [refetchFullStudy, refreshKey]);
 
  const refreshAfterSave = () => {
    fullStudyQuery.refetch();
    operatingPropertyOptionsQuery.refetch();
    onConfigurationSaved?.();
  };
 
  const createLine = async (intent: OperatingLineIntent) => {
    const type = operatingLineTypeForIntent(intent);
    const category = type.category;
    setCreateStatus({ kind: "saving", message: "Creating operating line" });
    const selectedDefault = selectedOperatingDefaultForCategory(
      category,
      fullStudy?.assumptions,
      defaultRates,
    ) ?? {
      sourceDefaultRate: defaultRateForCategory(category, defaultRates),
      rateAmount: "",
      rateUnit: "",
    };
    const sourceDefaultRate = selectedDefault.sourceDefaultRate ?? undefined;
    const rateType = rateTypeForCategory(category);
    const disposition =
      category === OperatingCostLineCategoryEnum.OutputRevenue
        ? OutletStreamDispositionEnum.Sold
        : category === OperatingCostLineCategoryEnum.Disposal
          ? OutletStreamDispositionEnum.Disposed
          : BlankEnum.$;
    const payload: OperatingCostLine = {
      study: study.id,
      label: `New ${type.label} line`,
      line_type: category,
      category,
      economic_effect: type.economicEffect,
      currency: fullStudy?.assumptions?.currency ?? "NZD",
      included: false,
      manual: true,
      source: "manual_project_operating_line",
      calculation_method: "rate_times_quantity",
      basis_unit: defaultBasisUnit(category),
      rate_amount: selectedDefault.rateAmount || undefined,
      rate_unit: selectedDefault.rateUnit || defaultRateUnit(category),
      rate_type: rateType ?? BlankEnum.$,
      rate_source_mode: rateType
        ? RateSourceModeEnum.ProjectDefault
        : RateSourceModeEnum.Custom,
      source_default_rate: sourceDefaultRate?.id ?? null,
      outlet_stream_disposition: disposition,
      warning_payload: {},
    };
    try {
      await createOperatingLine({ operatingCostLine: payload }).unwrap();
      refreshAfterSave();
      setCreateStatus({ kind: "saved", message: "Operating line created" });
    } catch (error) {
      setCreateStatus({ kind: "error", message: mutationErrorMessage(error) });
    }
  };
 
  const patchLine = async (lineId: number, patch: PatchedOperatingCostLine) => {
    await patchOperatingLine({
      id: lineId,
      patchedOperatingCostLine: patch,
    }).unwrap();
    refreshAfterSave();
  };
 
  const deleteLine = async (lineId: number) => {
    await deleteOperatingLine({ id: lineId }).unwrap();
    refreshAfterSave();
  };
 
  if (activeQueryLoading(fullStudyQuery)) {
    return (
      <section
        className="rounded-md border bg-card p-4"
        aria-label="Operating lines configuration"
      >
        <div className="flex items-center gap-2 text-sm text-muted-foreground">
          <Spinner size="small" />
          Loading operating lines
        </div>
      </section>
    );
  }
 
  if (fullStudyQuery.isError) {
    return (
      <section
        className="rounded-md border bg-card p-4"
        aria-label="Operating lines configuration"
      >
        <div
          className="rounded-md border border-destructive/30 bg-destructive/5 p-3 text-sm text-destructive"
          role="alert"
        >
          Could not load operating lines.
        </div>
      </section>
    );
  }
 
  return (
    <section
      className="rounded-md border bg-card p-4"
      aria-label="Operating lines configuration"
    >
      <div className="mb-4 flex flex-wrap items-start justify-between gap-3">
        <div>
          <div className="flex items-center gap-2">
            <ReceiptText className="size-4 text-primary" />
            <h3 className="text-sm font-semibold">Operating lines</h3>
          </div>
        </div>
        <LineTypeCreator
          canEdit={canEdit}
          saving={createState.isLoading || createStatus.kind === "saving"}
          onCreate={createLine}
        />
      </div>
      <FormState state={createStatus} />
      <OutputPropertyLineCreator
        canEdit={canEdit}
        options={operatingPropertyOptions}
        loading={activeQueryLoading(operatingPropertyOptionsQuery)}
        error={operatingPropertyOptionsQuery.isError}
        saving={false}
        onCreate={async (payload) => {
          await createOperatingLinesFromProperties({
            id: study.id,
            operatingLinesFromPropertiesRequest: payload,
          }).unwrap();
          refreshAfterSave();
        }}
      />
      <div className="mt-4 space-y-3">
        <OperatingLinesEditorList
          ariaLabel="Project operating lines"
          title="Project operating lines"
          help="Project lines can remain excluded while you collect quantity, unit, rate, source, and inclusion details."
          emptyText="No project operating lines yet. Add one with the type picker."
          lines={projectLines}
          canEdit={canEdit}
          defaultRates={defaultRates}
          assumptions={fullStudy?.assumptions}
          annualOperatingHours={annualOperatingHours}
          focusedOperatingLineId={focusedOperatingLineId}
          onPatchLine={patchLine}
          onDeleteLine={deleteLine}
        />
      </div>
    </section>
  );
}
 
function activeQueryLoading(query: {
  currentData?: unknown;
  isLoading: boolean;
  isFetching: boolean;
}) {
  return query.isLoading || (query.isFetching && query.currentData == null);
}