All files / src/pages/flowsheet-page/flowsheet SolveButton.tsx

65.71% Statements 23/35
58.33% Branches 7/12
50% Functions 4/8
65.62% Lines 21/32

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                                        49x     8171x 8171x 8171x 8171x   8171x 62x   62x 6x       8171x                         8171x 8171x 8171x 8171x       8171x 468x 419x 2830x                                                           8171x 53x                       8171x                                                                  
import { defineCommand, useRegisterCommand } from "just-search-it";
import { ChevronDown, Play } from "lucide-react";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import { useLocalStorage } from "usehooks-ts";
import { Button } from "@/ahuora-design-system/ui/button";
import { Spinner } from "@/ahuora-design-system/ui/spinner";
import { ToolTipCover } from "@/ahuora-design-system/ui/tooltip";
import { useFlowsheetUnitOps } from "@/hooks/flowsheetObjects";
import { useProjectId } from "@/hooks/project";
import {
  DropdownMenu,
  DropdownMenuTrigger,
} from "../../../ahuora-design-system/ui/dropdown-menu";
import { baseUrl } from "../../../api/emptyApi";
import { cn } from "../../../lib/utils";
import { ScenarioDropdown } from "./LeftSideBar/Scenarios/ScenarioDropdown";
import { useCurrentScenario } from "./LeftSideBar/Scenarios/useCurrentScenario";
import { useSolve } from "./Solving/useSolve";
 
const solveCommand = defineCommand<[], void>("solve");
 
export default function SolveButton({ className }: { className?: string }) {
  const [solve, solveRunning] = useSolve();
  const scenario = useCurrentScenario();
  const scenarioNumber = scenario?.id;
  const [, setScenarioOpen] = useLocalStorage("scenario-result-open", false);
 
  const handleClick = () => {
    solve(scenarioNumber);
 
    if (scenario) {
      setScenarioOpen(true);
    }
  };
 
  useRegisterCommand(
    solveCommand,
    {
      name: "Solve",
      description:
        "Solve the flowsheet in steady-state with the current parameters.",
      group: "Solving",
      icon: <Play className="icon-ls" />,
    },
    () => solve(undefined),
  );
 
  //Declaring variables for use:
  const [capValue, setCapValue] = useState<number | null>(null);
  const [powerValue, setPowerValue] = useState<number | null>(null);
  const unitops = useFlowsheetUnitOps();
  const flowsheetId = useProjectId();
 
  //Getting the power value and capacity values from the Grid unitOp:
  // TODO: This needs to be refactored to use lazy queries, and move elsewhere (doesn't belong in the SolveButton component)
  useEffect(() => {
    if (!unitops) return;
    for (let i = 0; i < unitops.length; i++) {
      Iif (unitops[i].componentName?.includes("Grid")) {
        const id = unitops[i].id;
        fetch(
          `${baseUrl}/api/unitops/simulationobjects/${id}/?flowsheet=${flowsheetId}`,
        )
          .then((res) => {
            Iif (!res.ok) throw new Error("Failed to fetch data");
            return res.json();
          })
          .then((data) => {
            const props = data;
            //Retrieving variables and setting cap value and power value:
            setCapValue(
              props.properties.ContainedProperties[0].values.displayValue,
            );
            setPowerValue(
              props.initial_values[`${unitops[i].componentName}_${id}`].data
                .None.__pyomo_components__.properties_in.data["0.0"]
                .__pyomo_components__.power.data.None.value / 1000,
            );
          })
          .catch((err) => {
            console.error("Error fetching unit op data:", err);
          });
 
        break; // prevents overwriting if multiple "Grid" matches
      }
    }
  }, [flowsheetId, unitops]);
  //Generating the warning if capacity is exceeded by the power-in:
  useEffect(() => {
    Iif (
      capValue !== null &&
      powerValue !== null &&
      Number(powerValue) > Number(capValue)
    ) {
      toast.warning("Power exceeds capacity", {
        description: `Grid power in/out is higher than Grid N-Capacity.`,
        duration: 7000,
      });
    }
  }, [capValue, powerValue]);
 
  return (
    <div className="h-full">
      <ToolTipCover content={"Click to solve flowsheet."} asChild side="bottom">
        <Button
          size="sm"
          className={cn(className, "rounded-r-none")}
          onClick={handleClick}
          disabled={solveRunning}
        >
          {solveRunning ? (
            <Spinner size="small" color="white" />
          ) : (
            <Play size={20} />
          )}
          Run {scenario && ` ${scenario.displayName}`}
        </Button>
      </ToolTipCover>
      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <Button
            size="sm"
            aria-label="Select Scenario"
            className={cn(className, "rounded-l-none")}
            disabled={solveRunning}
          >
            <ChevronDown />
          </Button>
        </DropdownMenuTrigger>
        <ScenarioDropdown />
      </DropdownMenu>
    </div>
  );
}