All files / src/pages/flowsheet-page/economics/page/actions CreateEconomicsStudyButton.tsx

91.66% Statements 22/24
87.09% Branches 27/31
100% Functions 6/6
95.65% Lines 22/23

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                                                                        226x 226x 226x 226x 226x 226x 226x       226x   241x     226x   226x 237x     233x       226x             9x 9x   9x               9x 9x                                                                       1x                         241x                               9x                                                
import { useState } from "react";
import { Button } from "@/ahuora-design-system/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/ahuora-design-system/ui/dialog";
import { Input } from "@/ahuora-design-system/ui/input";
import { Label } from "@/ahuora-design-system/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/ahuora-design-system/ui/select";
import {
  type EconomicsStudyRead,
  FlowsheetTemplateTypeEnum,
  useEconomicsStudiesCreateMutation,
} from "@/api/apiStore.gen";
import { useCurrentProject, useFlowsheetId } from "@/hooks/project";
 
export function CreateEconomicsStudyButton({
  compact = false,
  canEdit = true,
  onCreated,
}: {
  compact?: boolean;
  canEdit?: boolean;
  onCreated?: (study: EconomicsStudyRead) => void;
}) {
  const flowsheetId = useFlowsheetId();
  const projectQuery = useCurrentProject();
  const [createStudy, createStudyState] = useEconomicsStudiesCreateMutation();
  const [error, setError] = useState<string | null>(null);
  const [open, setOpen] = useState(false);
  const [studyName, setStudyName] = useState("Economics study");
  const [selectedFlowsheetId, setSelectedFlowsheetId] = useState<number | null>(
    null,
  );
  const candidateFlowsheets =
    projectQuery.data?.configurations.filter(
      (configuration) =>
        configuration.flowsheet_template_type ===
        FlowsheetTemplateTypeEnum.NotTemplate,
    ) ?? [];
  const defaultFlowsheetId = projectQuery.data?.active_flowsheet ?? flowsheetId;
  const targetFlowsheet =
    candidateFlowsheets.find(
      (configuration) => configuration.id === selectedFlowsheetId,
    ) ??
    candidateFlowsheets.find(
      (configuration) => configuration.id === defaultFlowsheetId,
    ) ??
    candidateFlowsheets[0];
  const disabled =
    createStudyState.isLoading ||
    projectQuery.isLoading ||
    !canEdit ||
    !flowsheetId ||
    !targetFlowsheet;
 
  const handleCreate = async () => {
    Iif (!flowsheetId || !targetFlowsheet) return;
    setError(null);
    try {
      const study = await createStudy({
        flowsheet: flowsheetId,
        economicsStudy: {
          name: studyName.trim() || "Economics study",
          description: "Created from the economics workspace.",
          target_flowsheet: targetFlowsheet.id,
        },
      }).unwrap();
      setOpen(false);
      onCreated?.(study);
    } catch {
      setError("Could not create the economics study.");
    }
  };
 
  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button
          type="button"
          size="sm"
          variant={compact ? "default" : "outline"}
          aria-label="Create economics study"
          disabled={disabled}
        >
          Create study
        </Button>
      </DialogTrigger>
      <DialogContent
        className="sm:max-w-md"
        aria-label="Create economics study dialog"
      >
        <DialogHeader>
          <DialogTitle>Create economics study</DialogTitle>
          <DialogDescription>
            {targetFlowsheet
              ? `Creates a study for ${targetFlowsheet.name}.`
              : "Select a flowsheet before creating an economics study."}
          </DialogDescription>
        </DialogHeader>
        <div className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="economics-study-flowsheet">Flowsheet</Label>
            <Select
              value={targetFlowsheet ? String(targetFlowsheet.id) : ""}
              onValueChange={(value) => setSelectedFlowsheetId(Number(value))}
              disabled={
                projectQuery.isLoading || candidateFlowsheets.length === 0
              }
            >
              <SelectTrigger
                id="economics-study-flowsheet"
                aria-label="Flowsheet"
              >
                <SelectValue placeholder="Select flowsheet" />
              </SelectTrigger>
              <SelectContent>
                {candidateFlowsheets.map((configuration) => (
                  <SelectItem
                    key={configuration.id}
                    value={String(configuration.id)}
                  >
                    {configuration.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-2">
            <Label htmlFor="economics-study-name">Study name</Label>
            <Input
              id="economics-study-name"
              aria-label="Economics study name"
              value={studyName}
              onChange={(event) => setStudyName(event.target.value)}
            />
          </div>
          {error && (
            <p className="text-xs text-destructive" role="alert">
              {error}
            </p>
          )}
        </div>
        <DialogFooter>
          <Button
            type="button"
            size="sm"
            onClick={handleCreate}
            disabled={disabled}
            aria-label="Save economics study"
          >
            {createStudyState.isLoading ? "Creating study" : "Save study"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}