All files / src/pages/flowsheet-page/pinch-analysis UtilityInput.tsx

59.57% Statements 28/47
51.85% Branches 14/27
41.66% Functions 5/12
59.57% Lines 28/47

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                                                7x 7x 7x 7x   7x 7x 7x 7x 7x   7x 3x             4x       4x                                                                 4x             4x           4x       4x             4x                                   4x 1x 1x         1x 1x             1x   3x   2x                         1x                         4x                                      
import {
  api,
  PinchUtility,
  PinchUtilityRead,
  PinchUtilityTypeEnum,
  usePinchPinchutilityCreateMutation,
  usePinchPinchutilityDeleteAllCreateMutation,
  usePinchPinchutilityDestroyMutation,
  usePinchPinchutilityPartialUpdateMutation,
  usePinchPinchutilityBulkCreateCreateMutation,
} from "@/api/apiStore.gen";
import { EditableTable } from "./EditableTable";
import { PinchUtilityColumns } from "./TableColumns/UtilityInputColumns";
import { useAppDispatch } from "@/store/hooks";
import { Spinner } from "@/ahuora-design-system/ui/spinner";
import Papa from "papaparse";
import CSVUploader from "../multi-steady-state/CSVUploader";
import {
  useCurrentPinchInputs,
  useCurrentStreamDataProjectID,
  useCurrentPinchUtilities,
} from "@/hooks/PinchHooks";
 
function UtilityInput({ handleEdit }) {
  const dispatch = useAppDispatch();
  const project = useCurrentStreamDataProjectID();
  const { utilities, isLoading, isError } = useCurrentPinchUtilities();
  const { inputs } = useCurrentPinchInputs();
 
  const [updateUtility] = usePinchPinchutilityPartialUpdateMutation();
  const [createUtility] = usePinchPinchutilityCreateMutation();
  const [deleteUtility] = usePinchPinchutilityDestroyMutation();
  const [bulkCreateUtilities] = usePinchPinchutilityBulkCreateCreateMutation();
  const [deleteAll] = usePinchPinchutilityDeleteAllCreateMutation();
 
  if (isLoading) {
    return (
      <div className="flex justify-center items-center h-screen">
        <Spinner />
      </div>
    );
  }
 
  Iif (isError || !utilities) {
    return <div>Error loading input data.</div>;
  }
 
  const handleUpdateutilities = (
    updatedValue: PinchUtilityRead,
    columnId: string,
    value: PinchUtilityRead[keyof PinchUtilityRead],
  ) => {
    const newValue = { ...updatedValue, [columnId]: value };
 
    // Optimistic Update
    Iif (project) {
      dispatch(
        api.util.updateQueryData(
          "pinchPinchutilityList",
          { projectOwner: +project },
          (utilities) => {
            const index = utilities.findIndex(
              (prop) => prop.id === newValue.id,
            );
            utilities[index] = newValue;
          },
        ),
      );
    }
 
    // Update On Backend
    updateUtility({
      id: newValue.id,
      patchedPinchUtility: newValue,
    });
 
    // Set editing to make button go yellow
    handleEdit();
  };
 
  const handleAddUtility = (newRow: PinchUtilityRead) => {
    newRow["input_owner"] = inputs![0].id;
    createUtility({
      pinchUtility: newRow,
    });
  };
 
  const handleDeleteUtility = (deletedRow: PinchUtilityRead) => {
    deleteUtility({
      id: deletedRow.id,
    });
  };
 
  const handleDeleteAll = () => {
    deleteAll({ deleteAllUtilities: { projectID: +project! } });
  };
 
  const validateData = (newRow: PinchUtilityRead): boolean => {
    Iif (newRow.name && newRow.t_supply && newRow.t_target) {
      return true;
    }
    return false;
  };
 
  const defaultValues: Partial<PinchUtilityRead> = {
    dt_cont: 5,
    htc: 1,
    price: 30,
    type: PinchUtilityTypeEnum.Both,
  };
 
  interface UtilityCSVRow {
    name: string;
    t_supply: string;
    t_target: string;
    heat_flow?: string;
    dt_cont?: string;
    htc?: string;
    price?: string;
    type: string;
  }
 
  const handleUpload = (file: File) => {
    if (file.type === "text/csv") {
      Papa.parse(file, {
        worker: true,
        delimiter: ";",
        header: true,
        complete: (result) => {
          const data = result.data;
          Iif (!Array.isArray(data) || data.length === 0) {
            console.error("No data found in the CSV.");
            return;
          }
 
          // Create PinchUtility objects from CSV data
          const parsedUtilities: Partial<PinchUtility>[] = (
            data as UtilityCSVRow[]
          )
            .filter((row) => row.name && row.t_supply && row.t_target)
            .map((row) => {
              return {
                name: row.name,
                t_supply: +row.t_supply,
                t_target: parseFloat(row.t_target),
                heat_flow: row.heat_flow ? parseFloat(row.heat_flow) : null,
                dt_cont: row.dt_cont ? parseFloat(row.dt_cont) : null,
                htc: row.htc ? parseFloat(row.htc) : null,
                price: row.price ? parseFloat(row.price) : null,
                type: row.type as PinchUtilityTypeEnum,
              };
            });
 
          // Create utilities in the backend
          bulkCreateUtilities({
            bulkCreateUtilities: {
              projectID: +project,
              utilities: parsedUtilities,
            },
          });
        },
      });
    } else E{
      console.log("other file types not supported yet");
    }
  };
 
  return (
    <div className="flex flex-col h-full pb-8 mx-4">
      <h4 className="my-4 font-semibold">Input Utility Data</h4>
      <EditableTable
        data={utilities || []}
        addRow={handleAddUtility}
        updateRow={handleUpdateutilities}
        deleteRow={handleDeleteUtility}
        deleteAll={handleDeleteAll}
        validateData={validateData}
        columns={PinchUtilityColumns}
        defaultValues={defaultValues}
      />
      <CSVUploader onUpload={handleUpload} className="my-4 mx-0 p-4 w-full" />
    </div>
  );
}
 
export default UtilityInput;