All files / src/pages/flowsheet-page/export ExportToIDAESCommand.tsx

23.33% Statements 7/30
9.09% Branches 1/11
100% Functions 0/0
25% Lines 7/28

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                          62x     9027x 9027x 9027x 9027x 9027x                                                                               9027x                                                                                                                              
import { defineCommand } from "just-search-it";
import { BookDown, ExternalLink, ExternalLinkIcon } from "lucide-react";
import { useState } from "react";
import { Button } from "@/ahuora-design-system/ui/button";
import {
  Dialog,
  DialogContent,
  DialogTrigger,
} from "@/ahuora-design-system/ui/dialog";
import { useIdaesGeneratePythonCodeCreateMutation } from "@/api/apiStore.gen";
import { RegisterCommand } from "@/commands/CommandProvider";
import { useProject, useProjectId } from "@/hooks/project";
 
export const ExportToIDAES = defineCommand<[], void>("exportToIdaes");
 
export function ExportToIDAESCommand() {
  const [requestGenerate] = useIdaesGeneratePythonCodeCreateMutation();
  const projectName = useProject()?.name;
  const flowsheet_id = useProjectId();
  const [showDialog, setShowDialog] = useState(false);
  const [statusMessage, setStatusMessage] = useState<string | null>(null);
 
  async function doExport() {
    Iif (!flowsheet_id) return;
    setStatusMessage("Generating model...");
    try {
      const response = await requestGenerate({
        generateIdaesPythonRequest: { flowsheet_id },
      }).unwrap();
 
      const text =
        typeof response === "string"
          ? response
          : JSON.stringify(response, null, 2);
      const element = document.createElement("a");
      const file = new Blob([text], { type: "application/json" });
      element.href = URL.createObjectURL(file);
      const name = (projectName || "project") + "_idaes_model.json";
      element.download = name;
      document.body.appendChild(element);
      element.click();
      document.body.removeChild(element);
      setStatusMessage("Download started");
    } catch (e) {
      // Try to extract useful message information from the error object
      // (RTK Query errors often have a `data.message` field)
      let msg = String(e);
      try {
        const maybe = e as unknown as {
          data?: { message?: string };
          message?: string;
        };
        msg = maybe?.data?.message || maybe?.message || String(e);
      } catch {
        /* fallback to String(e) */
      }
      setStatusMessage("An error occurred: " + msg);
    }
  }
 
  return (
    <>
      <RegisterCommand
        command={ExportToIDAES}
        args={[]}
        name="Export to IDAES"
        description="Export the flowsheet to an IDAES JSON model and download it"
        group="Export"
        icon={<BookDown />}
        action={async () => {
          Iif (!flowsheet_id) return;
          await doExport();
          setShowDialog(true);
        }}
      />
 
      <Dialog open={showDialog} onOpenChange={setShowDialog}>
        <DialogContent className="max-w-[1200px] min-w-[800px]">
          <div>
            <p className="text-lg font-semibold">Export to IDAES</p>
            <p>
              This allows you to use your ahuora flowsheet as part of a more
              complex IDAES model using our IDAES integration package.
            </p>
            <p className="my-2">
              For more information on how to use idaes, visit{" "}
              <a
                href="https://idaes-pse.readthedocs.io/en/stable/"
                className="text-sm underline"
                target="_blank"
                rel="noopener noreferrer"
              >
                idaes-pse.readthedocs.io{" "}
                <ExternalLinkIcon size={16} className="inline-block" />
              </a>
            </p>
            {statusMessage && <p className="mt-2 text-sm">{statusMessage}</p>}
 
            <div className="mt-4">
              <Button variant="outline" onClick={doExport}>
                Download again
              </Button>
            </div>
 
            <p className="text-lg font-semibold my-2">Usage Example</p>
 
            <pre className="text-sm border rounded-md p-2">
              from ahuora_builder.flowsheet_manager import FlowsheetManager{" "}
              <br />
              from ahuora_builder_types.flowsheet_schema import FlowsheetSchema{" "}
              <br />
              data = json.load("model.json") <br />
              flowsheet_schema = FlowsheetSchema.model_validate(data) <br />
              flowsheet = FlowsheetManager(flowsheet_schema) <br />
            </pre>
          </div>
        </DialogContent>
      </Dialog>
    </>
  );
}
 
export default ExportToIDAESCommand;