All files / src/form/wizard WizardStepComponent.tsx

72.09% Statements 31/43
59.52% Branches 25/42
60% Functions 6/10
72.09% Lines 31/43

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                                                                                                  21x 20x 20x   20x 20x 20x 20x 20x   20x   20x 5x 5x 5x   5x 5x 4x   5x 5x 5x 5x 5x             5x         5x               20x 5x     20x 20x   20x     15x 15x                 20x                                                                                                                                                                      
import React, { ReactElement, useCallback, useEffect, useState } from 'react';
import { Alert, Button, FormInstance, Result, Space } from 'antd';
import {
  PlusCircleOutlined, CloseCircleOutlined, RightCircleOutlined, HomeOutlined,
  ReloadOutlined
} from "@ant-design/icons";
import { useTranslation } from 'react-i18next';
 
import {
  MapOfEnumMetaProps,
  RecordProps,
  SaveRecordProps,
  Store,
  TableMetaProps,
  WizardMetaStepProps
} from "@props/RecordProps";
import { fetchCanCreate, getWizardStepMeta } from '@utils/FetchUtils';
import { LargeSpin } from '../../components';
import { DataCollectForm } from '../../form';
import { wrapAsHtml } from '@utils/ComponentUtils';
import { emptyMethod } from '@utils/Constants';
import { RedirectComponent } from "../../components/redirect";
import { transformRecord } from "@kernel/DisplayComponentsMapping";
 
export interface WizardStepComponentProps {
  wizardId: number;
  direction: 'vertical' | 'horizontal';
  wizardStep: WizardMetaStepProps;
  form: FormInstance;
  errorMessage?: string;
  warningMessage?: string;
  infoMessage?: string;
  finalSubmitted: boolean;
  redirect?: string
  initialValues?: Store;
  onClose?: () => void;
  onWizardRerun?: () => void;
  zIndex: number;
  options?: Array<MapOfEnumMetaProps>;
  dynamicMetas?: Array<TableMetaProps>;
}
 
export default function WizardStepComponent(
  props: WizardStepComponentProps
): ReactElement {
  const {
    wizardStep, form, errorMessage, warningMessage, infoMessage,
    finalSubmitted, redirect, initialValues, zIndex, onClose, onWizardRerun,
    options, dynamicMetas, direction
  } = props;
  const { t } = useTranslation();
  const { id: stepId, description } = wizardStep;
 
  const [loading, setLoading] = useState<boolean>(true);
  const [fieldsMeta, setFieldsMeta] = useState<Array<TableMetaProps>>([]);
  const [hasField, setHasField] = useState<boolean>();
  const [canCreateField, setCanCreateField] = useState<boolean>();
  const [convertedInitialValues, setConvertedInitialValues] = useState<SaveRecordProps | undefined>(initialValues);
 
  const isHorizontal = direction === 'horizontal';
 
  const refreshStepMeta = useCallback(() => {
    setLoading(true);
    if (stepId != null) {
      getWizardStepMeta(stepId)
        .then((meta) => {
          const lcFieldsMeta = (meta == null) ? [] : meta;
          if (dynamicMetas) {
            lcFieldsMeta.push(...dynamicMetas);
          }
          console.log("getWizardStepMeta: ", lcFieldsMeta, dynamicMetas);
          setFieldsMeta(lcFieldsMeta);
          const lcHasField = lcFieldsMeta.length > 0;
          setHasField(lcHasField);
          Iif (lcHasField === false) {
            fetchCanCreate("DynamicFieldInstance")
              .then(json => setCanCreateField(json.create))
              .catch(e => {
                console.error(`Failed to get canCreate of domain DynamicFieldInstance: ${e}`);
              });
          }
          Iif (initialValues) {
            const transformedRecord = transformRecord(lcFieldsMeta, initialValues as RecordProps);
            form.setFieldsValue(transformedRecord);
            setConvertedInitialValues(transformedRecord);
          }
        }).finally(() => setLoading(false));
    } else E{
      setFieldsMeta([]);
      setHasField(false);
      setLoading(false);
    }
  }, [dynamicMetas, form, initialValues, stepId]);
 
  useEffect(() => {
    refreshStepMeta();
  }, [refreshStepMeta]);
 
  const redirectIsEmpty = (redirect == null || redirect === '');
  const needDisplayRedirect = !redirectIsEmpty && finalSubmitted;
 
  const showMsg = (
    msg: string | undefined, level: "info" | "error" | "warning"
  ): ReactElement => {
    const msgIsEmpty = (msg == null || msg === '');
    return msgIsEmpty ?
      (<></>) : <Alert
        message={<>{wrapAsHtml(msg)}</>}
        type={level}
        className={`wizard-message wizard-message-${level}`}
        showIcon
      />;
  };
 
  return loading ? (<LargeSpin />) : ((hasField === false) ? (<>
    {canCreateField && <Result
      extra={canCreateField &&
        <Space>
          <Button
            type="primary"
          >
            <a href="/DynamicFieldInstance/create" target="_blank">
              <PlusCircleOutlined /> {t('Add new step field')}
            </a>
          </Button>
          <Button
            type="primary"
            onClick={() => refreshStepMeta()}
          >
            <ReloadOutlined /> {t('Refresh wizard step')}
          </Button>
        </Space>
      }
      title={t("No step field defined")}
    />}
  </>) : (
      <div>
        {isHorizontal && <Alert message={description} type="info" showIcon className="wizard-light-info" />}
        <div>
          {showMsg(errorMessage, "error")}
          {showMsg(warningMessage, "warning")}
          {showMsg(infoMessage, "info")}
          <div style={direction === 'horizontal' ? { marginTop: "24px" } : undefined}>
            {!finalSubmitted &&
              <DataCollectForm
                key={wizardStep.id}
                onChange={emptyMethod}
                onFinishFailed={emptyMethod}
                onFinish={emptyMethod}
                operation="create"
                columns={fieldsMeta}
                domainName={""}
                hideDetailPanel={isHorizontal}
                groups={[]}
                form={form}
                readonly={false}
                hideFields={[]}
                record={convertedInitialValues == null ? undefined : convertedInitialValues}
                zIndex={zIndex}
                formType={isHorizontal ? "Wizard" : "Create"}
                defaultColumnOptions={options}
                page={isHorizontal ? "wizard" : "create"}
              />
            }
            {finalSubmitted && <div className="wizard-final-step-actions">
              {needDisplayRedirect && (
                <div style={{ padding: "30px" }}>
                  <RedirectComponent
                    forMultiple={false}
                    fetchDataCallback={emptyMethod}
                    redirect={redirect}
                    zIndex={zIndex + 1}
                  />
                </div>
              )}
              <br />
              <Space size="large">
                <span onClick={() => {
                  window.location.assign("/");
                  onClose?.();
                }} className="link-span">
                  <HomeOutlined /> {t("Return to homepage")}
                </span>
                <span onClick={onClose} className="link-span">
                  <CloseCircleOutlined /> {t("Close window")}
                </span>
                <span onClick={onWizardRerun} className="link-span">
                  <RightCircleOutlined /> {t("Rerun wizard")}
                </span>
              </Space>
            </div>}
          </div>
        </div>
      </div>
    ));
}