All files / src/pages/flowsheet-page/flowsheet/LeftSideBar/Scenarios ScenarioDetails.tsx

70% Statements 28/40
70.58% Branches 24/34
47.05% Functions 8/17
73.68% Lines 28/38

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                                                                        33x                     246x 1x                       82x   82x         82x 82x 82x 82x   82x 82x   82x 4x           82x 1x               82x             82x 2x               82x                   82x   82x 8x 4x       4x 4x                       82x   82x                                                                                                                                                                                                                                                                       54x                                    
import { Checkbox } from "@/ahuora-design-system/ui/checkbox";
import { Label } from "@/ahuora-design-system/ui/label";
import { ScrollArea, ScrollBar } from "@/ahuora-design-system/ui/scroll-area";
import React, { useRef, useState } from "react";
import {
  ScenarioRead,
  useCoreExpressionListQuery,
  useCoreScenarioPartialUpdateMutation,
  StateNameEnum,
  useMssUploadCreateMutation,
  useMssDeleteCreateMutation
} from "@/api/apiStore.gen";
import ExpressionViewer from "@/pages/flowsheet-page/multi-steady-state/ExpressionViewer";
import { ArrowLeft, FileText, Plus } from "lucide-react";
import { OptimisationCheck } from "./OptimisationCheck";
import { ScenarioNameBadge } from "./ScenarioNameBadge";
import { TabListComponent } from "@/ahuora-design-system/ui/tabs-content";
import { Tabs, TabsContent } from "@/ahuora-design-system/ui/tabs";
import { FileUpload } from "./FileUpload";
import { DynamicCheck } from "./DynamicCheck";
import { LiveSolarData } from "./LiveSolarData";
import { Button } from "../../../../../ahuora-design-system/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/ahuora-design-system/ui/dropdown-menu";
import { PreviewData } from "./PreviewData";
import { useProjectId } from "@/hooks/project";
import { useFileUpload } from "./useFileUpload";
import { ToolTipCover } from "./tooltip";
import { CSVUploaderButton, CSVUploaderFile } from "@/pages/flowsheet-page/multi-steady-state/CSVUploader";
import MyDataPanel from "./MyDataPanel";
import SelectInput from "@/ahuora-design-system/inputs/SelectInput";
 
const ToggleCheckbox = ({
  id,
  label,
  checked,
  onChange,
}: {
  id: string;
  label: string;
  checked: boolean;
  onChange: (checked: boolean) => void;
}) => (
  <div className="flex flex-row gap-2 py-2 items-center">
    <Checkbox id={id} checked={checked} onCheckedChange={(checked) => onChange(checked as boolean)} />
    <Label htmlFor={id} className="text-sm">{label}</Label>
  </div>
);
 
export function ScenarioDetails({
  scenario,
  onClose,
}: {
  scenario: ScenarioRead;
  onClose?: () => void;
}) {
  const [uploadSource, setUploadSource] = useState<"file" | "solar" | null>(null);
 
  const { data: expressions } = useCoreExpressionListQuery(
    { scenario: scenario?.id },
    { skip: !scenario }
  );
 
  const [updateOptimization] = useCoreScenarioPartialUpdateMutation();
  const [uploadMSS] = useMssUploadCreateMutation();
  const [deleteMSS] = useMssDeleteCreateMutation();
  const id = useProjectId();
 
  const data = useCoreExpressionListQuery({ scenario: scenario.id })?.data || [];
  const ratingMode = scenario.enable_rating || false;
 
  const updateUploadedFileName = (name: string) => {
    updateOptimization({
      id: scenario.id,
      patchedScenario: { Uploaded_fileName: name },
    });
  };
 
  const handleEnableOptimization = () => {
    updateOptimization({
      id: scenario.id,
      patchedScenario: {
        enable_optimization: !scenario.enable_optimization,
      },
    });
  };
 
  const setRatingMode = (value: boolean) => {
    updateOptimization({
      id: scenario.id,
      patchedScenario: { enable_rating: value },
    });
  };
 
  const handleFileUpload = useFileUpload({
    onSuccess: (name) => updateUploadedFileName(name),
    onError: (err) => { },
    uploadMSS,
    updateUploadedFileName,
    flowsheetId: id,
    scenarioId: scenario.id,
  });
 
  const clearFile = () => {
    deleteMSS({
      deleteData: { flowsheet: id, scenario: scenario.id },
    });
    updateOptimization({
      id: scenario.id,
      patchedScenario: { Uploaded_fileName: "" },
    });
  };
 
  const hasFile = !!scenario.Uploaded_fileName && data && data.length > 0;
 
  const handleTabChange = (value) => {
    if (value === StateNameEnum.Dynamic) {
      updateOptimization({
        id: scenario.id,
        patchedScenario: { enable_dynamics: true, state_name: StateNameEnum.Dynamic },
      });
    } else if (value === StateNameEnum.Mss) {
      updateOptimization({
        id: scenario.id,
        patchedScenario: { enable_dynamics: false, state_name: StateNameEnum.Mss },
      });
    IE} else if (value === StateNameEnum.SteadyState) {
      updateOptimization({
        id: scenario.id,
        patchedScenario: { enable_dynamics: false, state_name: StateNameEnum.SteadyState },
      });
    }
  };
 
  const csvUploaderRef = useRef<{ openFileDialog: () => void }>(null);
 
  return (
    <div className="flex flex-col bg pb-1 w-full h-full">
      {/* Header */}
      <div className="flex flex-row gap-5 justify-between items-center bg-accent p-2" aria-label="scenario-header">
        <ScenarioNameBadge scenario={scenario} />
        <div className="flex flex-row text-sm font-light items-center cursor-pointer" onClick={onClose} aria-label="scenario-back-btn">
          <ArrowLeft size={24} />
        </div>
      </div>
 
      <ScrollArea className="flex-1 p-2 gap-2 text-sm">
        <Tabs value={scenario.state_name} onValueChange={handleTabChange}>
          <p className="text-sm">General Setting:</p>
 
          {/* Optimisation Toggle */}
          <div className="border p-2 rounded-lg my-2 bg-muted">
            <ToggleCheckbox id="enable_optimization" label="Enable Optimisation" checked={scenario.enable_optimization ?? false} onChange={handleEnableOptimization} />
            {scenario.enable_optimization && <OptimisationCheck optimization={scenario} />}
          </div>
 
          {/* Initialization Toggle */}
          <div className="border p-2 rounded-lg my-2 bg-muted">
            <ToggleCheckbox
              id="disable_initialization"
              label="Skip Initialisation"
              checked={scenario.disable_initialization ?? false}
              onChange={(checked) => {
                updateOptimization({ id: scenario.id, patchedScenario: { disable_initialization: checked } });
              }}
            />
            {scenario.disable_initialization && <p className="text-xs">No initialization will be performed. This may speed up solving if you have initialized previously.</p>}
          </div>
 
          {/* Rating Mode */}
          <div className="border p-2 rounded-lg my-2 bg-muted">
            <ToggleCheckbox id="rating-mode" label="Rating Mode" checked={ratingMode} onChange={setRatingMode} />
            {ratingMode && <p className="text-xs">Rating mode is enabled. You cannot replace which properties are used for calculation.</p>}
          </div>
 
          {/* Solver Selection, combobox */}
          <div className="border p-2 rounded-lg my-2 bg-muted">
            <div className="flex items-center gap-2">
              <Label htmlFor="solver-select" className="text-sm">
                Solver
              </Label>
 
              <div className="lg:w-44 md:w-40 sm:w-full">
                <SelectInput
                  ariaLabel="solver-select"
                  // If SelectInput supports id/aria-labelledby, this ties it to the Label above
                  // id="solver-select"
                  title={undefined}                 // keep label on same row (avoid duplicated title inside)
                  disabled={false}
                  value={scenario.solver_option ?? ""}
                  data={[
                    { label: "ipopt",  value: "ipopt"  },
                    { label: "ipopt_v2", value: "ipopt_v2" },
                    { label: "conopt", value: "conopt" },
                    { label: "bonmin", value: "bonmin" },
                  ]}
                  handleChange={(val: string) =>
                    updateOptimization({
                      id: scenario.id,
                      patchedScenario: { solver_option: val },
                    })
                  }
                />
              </div>
            </div>
          </div>
 
          <p className="text-sm pb-2">Simulation Specific Setting:</p>
 
          <TabListComponent
            tabValues={[
              { value: StateNameEnum.SteadyState, label: "Steady" },
              { value: StateNameEnum.Mss, label: "Multiple" },
              { value: StateNameEnum.Dynamic, label: "Dynamics" },
            ]}
            className="flex flex-row bg-muted text-secondary-foreground rounded-t-lg shadow-sm"
          />
 
          {/* Steady State */}
          <TabsContent value={StateNameEnum.SteadyState}>
            <p className="text-sm my-2">Solve the flowsheet based on the conditions set in the flowsheet. No additional settings are required.</p>
          </TabsContent>
 
          {/* Multiple Steady State */}
          <TabsContent value={StateNameEnum.Mss}>
            <p className="text-sm my-2">Solve the flowsheet multiple times, based on the conditions in the uploaded data.</p>
            <MyDataPanel handleFileUpload={handleFileUpload} hasFile={hasFile} clearFile={clearFile} scenario={scenario} expressions={expressions} />
          </TabsContent>
 
          {/* Dynamics Tab */}
          <TabsContent value={StateNameEnum.Dynamic}>
            <p className="text-xs my-2">Solve the flowsheet dynamically, incorporating time-based changes such as tank levels and battery charge levels.</p>
            <div className="border rounded-lg p-2 bg-muted" aria-label="scn-dynamic-container">
              {/* Add Data Dropdown */}
              <div className="flex flex-row items-center border border-input rounded-md p-1 w-full gap-1">
                <DropdownMenu>
                  <DropdownMenuTrigger asChild>
                    <Button variant="outline"><Plus /> Add Data</Button>
                  </DropdownMenuTrigger>
                  <DropdownMenuContent className="w-full p-0">
                    <DropdownMenuItem onClick={() => { setUploadSource("file"); setTimeout(() => csvUploaderRef.current?.openFileDialog(), 0); }}>
                      Choose from File
                    </DropdownMenuItem>
                    <DropdownMenuItem onClick={() => setUploadSource("solar")}>
                      Add live data
                    </DropdownMenuItem>
                  </DropdownMenuContent>
                </DropdownMenu>
 
                {uploadSource === "file" && <CSVUploaderFile ref={csvUploaderRef} onUpload={handleFileUpload} />}
 
                <PreviewData hasFile={hasFile} onRemove={clearFile} fileName={scenario.Uploaded_fileName ? "View Data" : "No Data Added"} optimization={scenario} />
              </div>
 
              {/* LiveSolarData stays mounted until upload is successful */}
              <div className="mt-2">
                {uploadSource === "solar" && (
                  <LiveSolarData
                    optimization={scenario}
                    onAdded={() => setUploadSource(null)} // 
                  />
                )}
              </div>
 
              {/* Expressions Display */}
              {hasFile && (
                <div className="border mt-2">
                  {expressions?.map((expression) => (
                    <div key={expression.id} className="rounded-lg bg-muted shadow-sm p-2 my-1">
                      <ExpressionViewer expression={expression} />
                    </div>
                  ))}
                </div>
              )}
 
              {/* Dynamic Check */}
              {scenario.enable_dynamics && <DynamicCheck optimization={scenario} />}
            </div>
          </TabsContent>
        </Tabs>
 
        <ScrollBar orientation="vertical" />
      </ScrollArea>
    </div>
  );
}