All files / src/components TemplateMenu.tsx

83.87% Statements 52/62
82.6% Branches 19/23
85.71% Functions 6/7
83.33% Lines 50/60

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        4x 4x 4x   4x 4x   4x 4x                             4x     34x   34x 34x 34x           34x   34x 34x   34x 17x 17x   17x 4x 4x 4x 3x   4x 4x 4x         4x   4x 4x   13x   13x     13x 3x 3x 3x 2x   3x                     17x     34x 2x 2x 2x 1x 1x 1x 1x 1x       1x 1x                         34x                                        
/*---------------------------------------------------------------------------------------------
 * Copyright (c) Bentley Systems, Incorporated. All rights reserved.
 * See LICENSE.md in the project root for license terms and full copyright notice.
 *--------------------------------------------------------------------------------------------*/
import React from "react";
import { useEffect, useState } from "react";
import { Stepper, toaster } from "@itwin/itwinui-react";
import type { Configuration } from "./EC3/Template";
import { useApiContext } from "./context/APIContext";
import { TemplateModificationStepRenderer } from "./TemplateModificationStepRenderer";
import type { EC3ReportConfigurationLabel, Report } from "@itwin/insights-client";
import "./TemplateMenu.scss";
import { EC3Widget } from "../EC3Widget";
/**
 * Props for {@link TemplateMenu}
 * @beta
 */
export interface TemplateMenuProps {
  template?: Configuration;
  onSaveSuccess: () => void;
  onClickCancel: () => void;
}
 
/**
 * EC3 Template menu
 * @beta
 */
export const TemplateMenu = (props: TemplateMenuProps) => {
  const {
    config: { getAccessToken, iTwinId: projectId, defaultReport },
  } = useApiContext();
 
  const [currentStep, setCurrentStep] = useState<number>(0);
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [childTemplate, setChildTemplate] = useState<Configuration>({
    reportId: undefined,
    description: "",
    displayName: "",
    labels: [],
  });
  const [fetchedReports, setFetchedReports] = useState<Report[]>();
 
  const configurationsClient = useApiContext().ec3ConfigurationsClient;
  const reportsClient = useApiContext().reportsClient;
 
  useEffect(() => {
    const fetchReports = async () => {
      const token = await getAccessToken();
 
      if (props.template && !childTemplate.reportId) {
        setIsLoading(true);
        const data = await reportsClient.getReports(token, projectId);
        if (data && data.length > 0) {
          setFetchedReports(data);
        }
        const configuration = await configurationsClient.getConfiguration(token, props.template.id!);
        const reportId = configuration._links.report?.href.split("/reports/")[1];
        const childConfig: Configuration = {
          displayName: configuration.displayName,
          description: configuration.description ?? "",
          reportId,
          id: configuration.id,
          labels: configuration.labels.filter(l => !!l.reportTable).map(l => l as EC3ReportConfigurationLabel),
        };
        setChildTemplate(childConfig);
        setIsLoading(false);
      } else {
        try {
          // check if defaultReport exists (set by the consuming application), else fetch all reports and allow user to select
          Iif (defaultReport && childTemplate.reportId === undefined) {
            setChildTemplate({ ...childTemplate, reportId: defaultReport.id });
          } else {
            if (!fetchedReports) {
              setIsLoading(true);
              const data = await reportsClient.getReports(token, projectId);
              if (data && data.length > 0) {
                setFetchedReports(data);
              }
              setIsLoading(false);
            }
          }
        } catch (err) {
          toaster.negative(EC3Widget.translate("unauthorisedUserMsg"));
          /* eslint-disable no-console */
          console.error(err);
          setIsLoading(false);
        }
      }
    };
    void fetchReports();
  }, [childTemplate, configurationsClient, defaultReport, fetchedReports, getAccessToken, projectId, props.template, reportsClient]);
 
  const saveConfiguration = async () => {
    try {
      const token = await getAccessToken();
      if (childTemplate.id) {
        await configurationsClient.updateConfiguration(token, childTemplate.id, childTemplate);
        props.onSaveSuccess();
        return;
      } else if (childTemplate.reportId) {
        await configurationsClient.createConfiguration(token, {
          ...childTemplate,
          reportId: childTemplate.reportId,
        });
        props.onSaveSuccess();
        return;
      } else E{
        props.onSaveSuccess();
        return undefined;
      }
    } catch (e) {
      toaster.negative(EC3Widget.translate("savingFailedToasterMsg"));
      // eslint-disable-next-line no-console
      console.error(e);
      return undefined;
    }
  };
 
  return (
    <div className="ec3w-template-creation-stepper" data-testid="ec3w-template-creation-stepper">
      <Stepper
        steps={[{ name: EC3Widget.translate("stepOneTitle") }, { name: EC3Widget.translate("stepTwoTitle") }, { name: EC3Widget.translate("stepThreeTitle") }]}
        currentStep={currentStep}
        onStepClick={(index: number) => setCurrentStep(index)}
      />
      <TemplateModificationStepRenderer
        childTemplate={childTemplate}
        isLoading={isLoading}
        currentStep={currentStep}
        onCancelClick={props.onClickCancel}
        onSaveClick={saveConfiguration}
        updateChildTemplate={setChildTemplate}
        updateCurrentStep={setCurrentStep}
        fetchedReports={fetchedReports ?? []}
      />
    </div>
  );
};