lodash#includes JavaScript Examples

The following examples show how to use lodash#includes. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: metric-utils.js    From ThreatMapper with Apache License 2.0 7 votes vote down vote up
export function getMetricValue(metric) {
  if (!metric) {
    return { formattedValue: 'n/a', height: 0, value: null };
  }
  const m = metric.toJS();
  const { value } = m;

  let valuePercentage = value === 0 ? 0 : value / m.max;
  let { max } = m;
  if (includes(['load1', 'load5', 'load15'], m.id)) {
    valuePercentage = loadScale(value);
    max = null;
  }

  let displayedValue = Number(value);
  if (displayedValue > 0 && (!max || displayedValue < max)) {
    const baseline = 0.1;
    displayedValue = (valuePercentage * (1 - (baseline * 2))) + baseline;
  } else if (displayedValue >= m.max && displayedValue > 0) {
    displayedValue = 1;
  }

  return {
    formattedValue: formatMetricSvg(value, m),
    hasMetric: value !== null,
    height: displayedValue
  };
}
Example #2
Source File: index.js    From hzero-front with Apache License 2.0 6 votes vote down vote up
/**
   * 移除已分配的用户
   */
  @Bind()
  handleDeleteUser() {
    const { selectedUserKeys } = this.state;
    if (selectedUserKeys.length !== 0) {
      const {
        dispatch,
        tenantId,
        match,
        employee: { userList = [] },
      } = this.props;
      dispatch({
        type: 'employee/deleteUser',
        payload: {
          tenantId,
          data: userList.filter((item) => includes(selectedUserKeys, item.employeeUserId)),
        },
      }).then((res) => {
        if (res) {
          notification.success();
          this.setState({ selectedUserKeys: [] });
          dispatch({
            type: 'employee/fetchUser',
            payload: {
              tenantId,
              customizeUnitCode: 'HPFM.EMPLOYEE_DETAIL.USER_LINE',
              employeeId: match.params.employeeId,
            },
          });
        }
      });
    }
  }
Example #3
Source File: app.js    From Lambda with MIT License 6 votes vote down vote up
onSelect(node) {
    const { cursor, data } = this.state;

    if (cursor) {
      this.setState(() => ({ cursor, active: false }));
      if (!includes(cursor.children, node)) {
        cursor.toggled = false;
        cursor.selected = false;
      }
    }

    node.selected = true;

    this.setState(() => ({ cursor: node, data: Object.assign({}, data) }));
  }
Example #4
Source File: index.js    From hzero-front with Apache License 2.0 6 votes vote down vote up
/**
   * 批量删除公休假期
   */
  @Bind()
  handleDeleteOption() {
    const {
      dispatch,
      match,
      calendar: { holidays },
      tenantId,
    } = this.props;
    const { selectedRowKeys } = this.state;
    const selectedRows = holidays.content.filter(item => includes(selectedRowKeys, item.holidayId));
    dispatch({
      type: 'calendar/deleteHolidays',
      payload: {
        tenantId,
        calendarId: match.params.calendarId,
        data: selectedRows,
      },
    }).then(res => {
      if (res) {
        notification.success();
        this.handleSearchHoliday();
        // 重置选中数据
        this.setState({
          selectedRowKeys: [],
        });
      }
    });
  }
Example #5
Source File: root.js    From ThreatMapper with Apache License 2.0 6 votes vote down vote up
// TODO: These state changes should probably be calculated from selectors.
function updateStateFromNodes(state) {
  // Apply pinned searches, filters nodes that dont match.
  state = applyPinnedSearches(state);

  // In case node or edge disappears before mouseleave event.
  const nodesIds = state.get('nodes').keySeq();
  if (!nodesIds.contains(state.get('mouseOverNodeId'))) {
    state = state.set('mouseOverNodeId', null);
  }
  if (!nodesIds.some(nodeId => includes(state.get('mouseOverEdgeId'), nodeId))) {
    state = state.set('mouseOverEdgeId', null);
  }

  // Update the nodes cache only if we're not in the resource view mode, as we
  // intentionally want to keep it static before we figure how to keep it up-to-date.
  if (!isResourceViewModeSelector(state)) {
    const nodesForCurrentTopologyKey = ['nodesByTopology', state.get('currentTopologyId')];
    state = state.setIn(nodesForCurrentTopologyKey, state.get('nodes'));
  }

  // Clear the error.
  state = state.set('errorUrl', null);

  return state;
}
Example #6
Source File: layout.js    From ThreatMapper with Apache License 2.0 6 votes vote down vote up
focusedNodesIdsSelector = createSelector(
  [
    selectedNodeIdSelector,
    state => state.get('nodes'),
  ],
  (selectedNodeId, nodes) => {
    if (!selectedNodeId || nodes.isEmpty()) {
      return [];
    }

    // The selected node always goes in focus.
    let focusedNodes = makeSet([selectedNodeId]);

    // Add all the nodes the selected node is connected to...
    focusedNodes = focusedNodes.merge(nodes.getIn([selectedNodeId, 'adjacency']) || makeList());

    // ... and also all the nodes that connect to the selected one.
    nodes.forEach((node, nodeId) => {
      const adjacency = node.get('adjacency') || makeList();
      if (adjacency.includes(selectedNodeId)) {
        focusedNodes = focusedNodes.add(nodeId);
      }
    });

    return focusedNodes.toArray();
  }
)
Example #7
Source File: layout.js    From ThreatMapper with Apache License 2.0 6 votes vote down vote up
layoutEdgesSelector = createSelector(
  [
    graphEdgesSelector,
    layoutNodesSelector,
    focusedNodesIdsSelector,
  ],
  (graphEdges, layoutNodes, focusedNodesIds) => (
    // Update the edges in the circular layout to link the nodes in a straight line.
    graphEdges.map((edge) => {
      const source = edge.get('source');
      const target = edge.get('target');
      if (includes(focusedNodesIds, source) || includes(focusedNodesIds, target)) {
        return edge.set('points', fromJS([
          pick(layoutNodes.get(source).toJS(), ['x', 'y']),
          pick(layoutNodes.get(target).toJS(), ['x', 'y']),
        ]));
      }
      return edge;
    })
  )
)
Example #8
Source File: ValidateInput.js    From SESTA-FMS with GNU Affero General Public License v3.0 5 votes vote down vote up
validateInput = (value, inputValidations = {}, type = "text") => {
  let errors = [];

  const emailRegex = new RegExp(
    /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
  );
  const phoneRegex = new RegExp(
    /^\s*(?:\+?(\d{1,3}))?[- (]*(\d{3})[- )]*(\d{3})[- ]*(\d{4})(?: *[x/#]{1}(\d+))?\s*$/
  );
  const passRegx = new RegExp("^(?=.*[a-zA-Z])(?=.*[0-9])(?=.{8,})");

  // handle i18n
  const requiredError = { id: "components.Input.error.validation.required" };
  mapKeys(inputValidations, (validationValue, validationKey) => {
    switch (validationKey) {
      case "max":
        if (parseInt(value, 10) > validationValue.value) {
          errors.push(validationValue.message);
        }
        break;
      case "maxLength":
        if (value.length > validationValue.value) {
          errors.push(validationValue.message);
        }
        break;
      case "min":
        if (parseInt(value, 10) < validationValue.value) {
          errors.push(validationValue.message);
        }
        break;
      case "minLength":
        if (value.length < validationValue.value) {
          errors.push(validationValue.message);
        }
        break;
      case "required":
        if (value.length === 0) {
          errors.push(validationValue.message);
        }
        break;
      case "regex":
        if (!new RegExp(validationValue.value).test(value)) {
          errors.push(validationValue.message);
        }
        break;
      case "validatePasswordRegex":
        if (value.length !== 0 && !passRegx.test(value)) {
          errors.push(validationValue.message);
        }
        break;
      case "email":
        if (value.length !== 0 && !emailRegex.test(value)) {
          errors.push(validationValue.message);
        }
        break;
      case "phone":
        if (value.length !== 0 && !phoneRegex.test(value)) {
          errors.push(validationValue.message);
        }
        break;
      default:
        errors = [];
    }
  });

  if (type === "email" && !emailRegex.test(value)) {
    errors.push("Not an email");
  }

  if (includes(errors, requiredError)) {
    errors = reject(errors, (error) => error !== requiredError);
  }

  return errors;
}
Example #9
Source File: index.js    From hzero-front with Apache License 2.0 5 votes vote down vote up
/**
   * 确认按钮-用户分配Modal
   * @prop {List<Object>} userList - 用户信息类表
   */
  @Bind()
  handleUserModalOk() {
    const { availableUserKeys } = this.state;
    if (availableUserKeys.length !== 0) {
      const {
        dispatch,
        tenantId,
        match,
        employee: { users },
      } = this.props;
      const userData = users.content
        .filter((i) => includes(availableUserKeys, i.id))
        .map((item) => ({
          ...item,
          tenantId,
          userId: item.id,
          employeeId: match.params.employeeId,
        }));
      dispatch({
        type: 'employee/updateUser',
        payload: {
          tenantId,
          data: userData,
        },
      }).then((res) => {
        if (res) {
          notification.success();
          dispatch({
            type: 'employee/fetchUser',
            payload: {
              tenantId,
              customizeUnitCode: 'HPFM.EMPLOYEE_DETAIL.USER_LINE',
              employeeId: match.params.employeeId,
            },
          });
          this.setState({ userVisible: false, availableUserKeys: [] });
        }
      });
    }
  }
Example #10
Source File: index.js    From hzero-front with Apache License 2.0 5 votes vote down vote up
/**
   * 移除已维护岗位
   */
  @Bind()
  handleDeletePosition() {
    const { selectedPositionKeys } = this.state;
    if (selectedPositionKeys.length !== 0) {
      const {
        dispatch,
        tenantId,
        match,
        employee: { positionList = [] },
      } = this.props;
      // 移除岗位,不做是否存在主岗校验
      const newPositions = positionList.filter((i) => !selectedPositionKeys.includes(i.positionId));
      dispatch({
        type: 'employee/updatePosition',
        payload: {
          tenantId,
          employeeId: match.params.employeeId,
          positionList: newPositions,
        },
      }).then((res) => {
        if (res) {
          notification.success();
          this.setState({ selectedPositionKeys: [] });
          dispatch({
            type: 'employee/fetchPosition',
            payload: {
              tenantId,
              customizeUnitCode: 'HPFM.EMPLOYEE_DETAIL.POST_LINE',
              employeeId: match.params.employeeId,
              positions: [],
              expandedRowKeys: [],
            },
          });
        }
      });
    }
  }
Example #11
Source File: Notify.jsx    From kube-design with MIT License 5 votes vote down vote up
open = (args) => {
  const defaultOptions = {
    duration: 4500,
    closable: true,
    placement: "topRight",
    type: "info",
  };

  const options = { ...defaultOptions, ...args };

  let position;
  if (!includes(PLACEMENT, options.placement)) {
    position = defaultOptions.placement;
  } else {
    position = options.placement;
  }

  const { title, content, type, btns, key } = options;

  const cacheKey = `${prefixCls}-${position}`;

  const newOptions = omit(options, [
    "title",
    "content",
    "placement",
    "icon",
    "btns",
  ]);

  const target = key || generateUUID("notify");
  const createNotice = (notify) => {
    notify.createNotice({
      key: target,
      content: (
        <div className={`${prefixCls}-with-icon`}>
          <div className={`${prefixCls}-icon`}>
            <Icon name={IconMap[type] || "check"} type="light" size={20} />
          </div>
          <div className={`${prefixCls}-text`}>
            {title && <div className={`${prefixCls}-title`}>{title}</div>}
            {content && <div className={`${prefixCls}-content`}>{content}</div>}
          </div>
          {btns ? <div className={`${prefixCls}-btns`}>{btns}</div> : null}
        </div>
      ),
      ...newOptions,
    });
  };

  if (notifyInstance[cacheKey]) {
    createNotice(notifyInstance[cacheKey]);
  } else {
    NotifyManager.newInstance(
      {
        prefixCls,
        animation: "drop",
        className: cacheKey,
        style: getPlacementStyle(position),
      },
      (notify) => {
        notifyInstance[cacheKey] = notify;
        createNotice(notify);
      }
    );
  }
  return { ...notifyInstance[cacheKey], key: target };
}
Example #12
Source File: Integrations.js    From gutenberg-forms with GNU General Public License v2.0 5 votes vote down vote up
function Integrations(props) {
	const integrations = get(window, "cwpGlobal.settings.integrations");
	const savedIntegrations = props.data.attributes.integrations;
	const { actions } = props.data.attributes;

	// responsible for keeping the form actions and integrations synchronized
	useEffect(() => {
		each(savedIntegrations, (integration, name) => {
			const title = get(integrations[name], "title");
			const hasActionOfCurrentIntegration = includes(actions, title); // checking if the action has current integration

			if (!hasActionOfCurrentIntegration) {
				const newIntegrations = clone(savedIntegrations);
				const withoutCurrentIntegrations = omit(newIntegrations, [name]); // deleting the current integration from the list

				props.data.setAttributes({ integrations: withoutCurrentIntegrations });
			}
		});
	}, [actions]);

	useEffect(() => {
		each(integrations, (integration, name) => {
			const title = get(integration, "title");
			const hasActionOfCurrentIntegration = includes(actions, title); // checking if the action has current integration
			const isAllFieldIntegration = get(integration, "include_all_fields");

			if (isAllFieldIntegration && hasActionOfCurrentIntegration === true) {
				// if this integration support all field then the field plotter will be hidden
				// therefore updating the integration attribute manually

				const newIntegrations = clone(savedIntegrations);
				set(newIntegrations, name, new Object());
				props.data.setAttributes({ integrations: newIntegrations });
			}
		});
	}, [actions]);

	return (
		<Fragment>
			{map(integrations, (integration, name) => {
				const api_fields = get(integration, "api_fields"),
					query_fields = get(integration, "query_fields"),
					title = get(integration, "title"),
					enable = get(integration, "enable"),
					fields = get(integration, "fields"),
					type = get(integration, "type"),
					include_all_fields = get(integration, "include_all_fields");
				if (
					enable &&
					actions.includes(title) &&
					isEqual(type, "autoResponder") &&
					!include_all_fields
				) {
					return (
						<PanelBody title={__(title, "cwp-gutenberg-forms")}>
							<FieldPlotter
								fields={fields}
								title={title}
								name={name}
								data={props.data}
								clientId={props.clientId}
								api_fields={api_fields}
								query_fields={query_fields}
							/>
						</PanelBody>
					);
				}
			})}
		</Fragment>
	);
}
Example #13
Source File: RelatedNews.js    From ecomloop.github.io with MIT License 5 votes vote down vote up
getRelatedNews = (currentNews, allNews) => {

    const maxPosts = 3;
    const currentCategories = (currentNews.extractedkeywords + "," + currentNews.keywords).split(",") || [];
    const currentTags = currentNews.tags.split(",") || [];

    // console.log("******** in related news")
    // console.log(allNews)
    // console.log(currentNews)
    // console.log(currentCategories)
    // console.log(currentTags)
    
    // Don't include the current post in posts list
    allNews = allNews.filter((post) => post.node.id !== currentNews.id);

    const identityMap = {};

    //Map over all posts, add to map and add points
    for (let post of allNews) {

        const id = post.node.id;
        if (!identityMap.hasOwnProperty(id)) {
            identityMap[id] = {
                news: post,
                points: 0
            }
        }

        // For category matches, we add 2 points
        const categoryPoints = 2;
        const categories = (post.node.extractedkeywords + "," + post.node.keywords).split(",") || [];
        categories.forEach((category) => {
            if (includes(...currentCategories, category)) {
                identityMap[id].points += categoryPoints;
            }
        })

        // For tags matches, we add 1 point
        const tagPoint = 1;
        const tags = post.node.tags.split(",") || [];
        tags.forEach((aTag) => {
            if (includes(currentTags, aTag)) {
                identityMap[id].points += tagPoint;
            }
        })

    }

    // Convert the identity map to an array
    const arrayIdentityMap = Object.keys(identityMap).map((id) => identityMap[id]);

    // Use a lodash utility function to sort them 
    // by points, from greatest to least
    const similarPosts = orderBy(
        arrayIdentityMap, ['points'], ['desc']
    )

    //console.log("***** relatedNews Output ",similarPosts.splice(0, maxPosts))
    // return the max number posts requested
    return similarPosts.splice(0, maxPosts);

}
Example #14
Source File: RelatedShops.jsx    From emprezzo with MIT License 5 votes vote down vote up
getRelatedShops = (currentShop, allshops) => {

    const maxPosts = 4;
    const currentCategories = currentShop.category?currentShop.category.split(","):[];
    const currentTags = currentShop.tags?currentShop.tags.split(","):[];

    // console.log("******** in related shops")
    // console.log(allshops)
    // console.log(currentShop)
    // console.log(currentCategories)
    // console.log(currentTags)

    // Don't include the current post in posts list
    allshops = allshops.filter((post) => post.id !== currentShop.id);

    const identityMap = {};

    //Map over all posts, add to map and add points
    for (let post of allshops) {
        const id = post.id;
        if (!identityMap.hasOwnProperty(id)) {
            identityMap[id] = {
                shop: post,
                points: 0
            }
        }

        // For category matches, we add 2 points
        const categoryPoints = 2;
        const categories = post.category?post.category.split(","):[];
        categories.forEach((category) => {
            if (includes(...currentCategories, category)) {
                identityMap[id].points += categoryPoints;
            }
        })

        // For tags matches, we add 1 point
        const tagPoint = 1;
        const tags = post.tags?post.tags.split(","):[];
        tags.forEach((aTag) => {
            if (includes(currentTags, aTag)) {
                identityMap[id].points += tagPoint;
            }
        })

    }

    // Convert the identity map to an array
    const arrayIdentityMap = Object.keys(identityMap).map((id) => identityMap[id]);

    // Use a lodash utility function to sort them
    // by points, from greatest to least
    const similarPosts = orderBy(
        arrayIdentityMap, ['points'], ['desc']
    )

    //console.log("***** relatedShops Output ",similarPosts.splice(0, maxPosts))
    // return the max number posts requested
    return similarPosts.splice(0, maxPosts);

}
Example #15
Source File: RelatedPosts.js    From ecomloop.github.io with MIT License 5 votes vote down vote up
getRelatedPosts = (currentPost, allPosts) => {

    const maxPosts = 3;
    const currentCatetory = currentPost.node.frontmatter.categories || "";
    const currentTags = currentPost.node.frontmatter.tags || [];

    // console.log("******** in related post")
    // console.log(allPosts)
    // console.log(currentPost)
    // console.log(currentCatetory)
    // console.log(currentTags)

    // Don't include the current post in posts list
    allPosts = allPosts.filter((post) => post.node.id !== currentPost.node.id);

    const identityMap = {};

    //Map over all posts, add to map and add points
    for (let post of allPosts) {

        const id = post.node.id;
        if (!identityMap.hasOwnProperty(id)) {
            identityMap[id] = {
                post: post,
                points: 0
            }
        }

        // For category matches, we add 2 points
        const categoryPoints = 2;
        //if (post.node.frontmatter.categories.category === currentCatetory) {
            //identityMap[id].points += categoryPoints;
        //}
        post.node.frontmatter.categories.forEach(({category}) => {
            if (includes(...currentCatetory, category)) {
                identityMap[id].points += categoryPoints;
            }
        })

        // For tags matches, we add 1 point
        const tagPoint = 1;
        post.node.frontmatter.tags.forEach((aTag) => {
            if (includes(currentTags, aTag)) {
                identityMap[id].points += tagPoint;
            }
        })

    }

    // Convert the identity map to an array
    const arrayIdentityMap = Object.keys(identityMap).map((id) => identityMap[id]);

    // Use a lodash utility function to sort them 
    // by points, from greatest to least
    const similarPosts = orderBy(
        arrayIdentityMap, ['points'], ['desc']
    )

    //console.log(similarPosts.splice(0, maxPosts))
    // return the max number posts requested
    return similarPosts.splice(0, maxPosts);

}
Example #16
Source File: RouteWithTabLayout.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
RouteWithTabLayout = props => {
  const { layout: Layout, component: Component, title, ...rest } = props;
  let history = useHistory();
  const classes = useStyles();

  const menu = get(MenuItems(), roleConstants.STUDENT, []);

  /**
   * Get tabs for only sub menu items from menu only for profile
   */
  const tabs = menu ? menu[0].tabItems : menu;

  const getSelectedTab = () => {
    const tab = tabs.find(tab => {
      if (includes(tab.availableRoutes, props.path)) {
        return tab;
      }
    });

    if (tab) {
      return tab.link;
    } else {
      return "/view-profile";
    }
  };

  // Default selected tab view-profile
  const [selectedTab, setSelectedTab] = useState(null);

  useEffect(() => {
    if (props.path) {
      setSelectedTab(getSelectedTab);
    }
  }, [props.path]);

  const NavBar = () => {
    const handleTabChange = val => {
      setSelectedTab(val);
      history.push(val);
    };

    return (
      <div className={classes.root} id="handletabchange">
        <Typography className={classes.marginY} variant="h4">
          {title || ""}
        </Typography>
        <StyledTabs
          value={selectedTab}
          variant={window.screen.width > 420 ? "fullWidth" : "scrollable"}
          scrollButtons="on"
          onChange={(event, value) => handleTabChange(value)}
        >
          {tabs.map((tab, index) => {
            return <StyledTab label={tab.name} value={tab.link} key={index} />;
          })}
        </StyledTabs>
      </div>
    );
  };

  if (auth.getToken() !== null) {
    if (props.location["collegeAdminRoute"]) {
      return (
        <Route
          {...rest}
          render={matchProps => (
            <Layout>
              <NavBar />
              <AddEditStudentForCollegeAdmin {...matchProps} />
            </Layout>
          )}
        />
      );
    } else {
      return (
        <Route
          {...rest}
          render={matchProps => (
            <Layout>
              <NavBar />
              <Component {...matchProps} />
            </Layout>
          )}
        />
      );
    }
  } else {
    return (
      <Redirect
        to={{
          pathname: routeConstants.SIGN_IN_URL,
          state: { from: props.location }
        }}
      />
    );
  }
}
Example #17
Source File: AddEditActivity.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
AddEditActivity = props => {
  let history = useHistory();
  const dateFrom = "dateFrom";
  const dateTo = "dateTo";

  const [editorState, setEditorState] = useState(EditorState.createEmpty());
  const [backDrop, setBackDrop] = useState(false);

  const [formState, setFormState] = useState({
    isValid: false,
    values: {
      dateFrom: moment(),
      dateTo: moment()
    },
    touched: {},
    errors: {},
    isSuccess: false,
    showPassword: false,
    editActivity: props.location.editActivity
      ? props.location.editActivity
      : false,
    dataForEdit: props.location.dataForEdit
      ? props.location.dataForEdit
      : false,
    counter: 0,
    testCounter: 0,
    stream: [],
    files: null,
    descriptionError: false,
    discriptionMinLengthError: false,
    previewFile: {},
    showPreview: false,
    showEditPreview: props.location.editActivity
      ? props.location.dataForEdit.upload_logo
        ? true
        : false
      : false,
    showNoImage: props.location.editActivity
      ? false
      : props.location.editActivity
  });

  if (formState.dataForEdit && !formState.counter) {
    if (props.location["dataForEdit"]) {
      if (props.location["dataForEdit"]["title"]) {
        formState.values["activityname"] =
          props.location["dataForEdit"]["title"];
      }
      if (props.location["dataForEdit"]["activitytype"]) {
        formState.values["activitytype"] =
          props.location["dataForEdit"]["activitytype"]["id"];
      }
      if (
        props.location["dataForEdit"]["academic_year"] &&
        props.location["dataForEdit"]["academic_year"]["id"]
      ) {
        formState.values["academicyear"] =
          props.location["dataForEdit"]["academic_year"]["id"];
      }
      if (props.location["dataForEdit"]["streams"]) {
        formState.values["stream"] = props.location["dataForEdit"]["streams"];
      }
      if (props.location["dataForEdit"]["address"]) {
        formState.values["address"] = props.location["dataForEdit"]["address"];
      }
      if (props.location["dataForEdit"]["education_year"]) {
        formState.values["educationyear"] =
          props.location["dataForEdit"]["education_year"];
      }
      if (props.location["dataForEdit"]["activity_status"]) {
        formState.values["activitystatus"] =
          props.location["dataForEdit"]["activity_status"];
      }
      if (
        props.location["dataForEdit"]["question_set"] &&
        props.location["dataForEdit"]["question_set"]
      ) {
        formState.values["questionSet"] =
          props.location["dataForEdit"]["question_set"]["id"];
      }
      if (props.location["dataForEdit"]["description"]) {
        // formState.values["description"] = props["dataForEdit"]["description"];
        const blocksFromHtml = htmlToDraft(
          props.location["dataForEdit"]["description"]
        );
        const { contentBlocks, entityMap } = blocksFromHtml;
        const contentState = ContentState.createFromBlockArray(
          contentBlocks,
          entityMap
        );
        const editorState = EditorState.createWithContent(contentState);
        setEditorState(editorState);
      }
      if (props.location["dataForEdit"]["trainer_name"]) {
        formState.values["trainer"] =
          props.location["dataForEdit"]["trainer_name"];
      }

      if (
        props.location["dataForEdit"]["contact"] &&
        props.location["dataForEdit"]["contact"]["id"]
      ) {
        formState.values["college"] =
          props.location["dataForEdit"]["contact"]["id"];
      }
      if (props.location["dataForEdit"]["start_date_time"]) {
        formState.values[dateFrom] = moment(
          props.location["dataForEdit"]["start_date_time"]
        );
      }
      if (props.location["dataForEdit"]["end_date_time"]) {
        formState.values[dateTo] = moment(
          props.location["dataForEdit"]["end_date_time"]
        );
      }
      if (
        props.location["dataForEdit"]["upload_logo"] &&
        props.location["dataForEdit"]["upload_logo"]["id"]
      ) {
        formState.files = props.location["dataForEdit"]["upload_logo"];
        //      formState.values["files"] =
        //        props.location["dataForEdit"]["upload_logo"]["name"];
      }
    }
    formState.counter += 1;
  }

  if (props.location.state && !formState.counter) {
    if (props.location.state.contactNumber && props.location.state.otp) {
      formState.values["contact"] = props.location.state.contactNumber;
      formState.values["otp"] = props.location.state.otp;
    }
    formState.counter += 1;
  }

  // const [selectedDateFrom, setSelectedDateFrom] = React.useState(new Date());
  // const [selectedDateTo, setSelectedDateTo] = React.useState(new Date());
  const { setLoaderStatus } = useContext(LoaderContext);

  const educationyearlist = [
    { name: "First", id: "First" },
    { name: "Second", id: "Second" },
    { name: "Third", id: "Third" }
  ];

  const activityNameList = [
    { name: "Soft Skills 1", id: "Soft Skills 1" },
    { name: "Soft Skills 2", id: "Soft Skills 2" },
    { name: "Career Awareness 1", id: "Career Awareness 1" },
    { name: "Career Awareness 2", id: "Career Awareness 2" },
    { name: "Job Preparation 1", id: "Job Preparation 1" },
    { name: "Job Preparation 2", id: "Job Preparation 2" },
    { name: "Job Preparation 3", id: "Job Preparation 3" },
    { name: "Industrial Visit", id: "Industrial Visit" },
    { name: "Industry Talk", id: "Industry Talk" }
  ];

  const activityStatus = [
    { name: "Scheduled", id: "scheduled" },
    { name: "Completed", id: "completed" },
    { name: "Cancelled", id: "cancelled" }
  ];

  const [stream, setStream] = useState([]);
  const [isFailed, setIsFailed] = useState(false);

  const classes = useStyles();

  const [collegelist, setcollegelist] = useState(
    props.collegeListForTest ? props.collegeListForTest : []
  );
  const [streamlist, setstreamlist] = useState(
    props.streamListForTest ? props.streamListForTest : []
  );
  const [collegeStreamList, setCollegeStreamList] = useState(
    props.collegeStreamListForTest ? props.collegeStreamListForTest : []
  );
  const [activityType, setActivityType] = useState(
    props.activityTypeListForTest ? props.activityTypeListForTest : []
  );
  const [questionSetData, setQuestionSetData] = useState(
    props.questionSetListForTest ? props.questionSetListForTest : []
  );

  if (
    !formState.dataForEdit &&
    props.isDataForTesting &&
    !formState.testCounter
  ) {
    const html = "<p>Test Data</p>";
    const contentBlock = htmlToDraft(html);
    if (contentBlock) {
      const contentState = ContentState.createFromBlockArray(
        contentBlock.contentBlocks
      );
      const editorState = EditorState.createWithContent(contentState);
      setEditorState(editorState);
      formState.testCounter += 1;
    }
  }

  useEffect(() => {
    serviceProvider
      .serviceProviderForGetRequest(QUESTION_SET)
      .then(res => {
        setQuestionSetData(res.data);
      })
      .catch(error => {});
    getColleges();
    getStreams();
    getActivityTypes();
  }, []);

  const getActivityTypes = async () => {
    const activityTypeUrl =
      strapiApiConstants.STRAPI_DB_URL +
      strapiApiConstants.STRAPI_ACTIVITY_TYPE;
    await serviceProvider
      .serviceProviderForGetRequest(activityTypeUrl)
      .then(res => {
        setActivityType(res.data);
      })
      .catch(error => {});
  };

  const getStreams = () => {
    axios
      .get(strapiApiConstants.STRAPI_DB_URL + strapiApiConstants.STRAPI_STREAMS)
      .then(res => {
        const list = res.data.map(({ id, name }) => ({
          id,
          name
        }));
        setstreamlist(list);

        if (formState.dataForEdit) {
          const streamIds = props.location["dataForEdit"]["streams"].map(
            stream => stream.id
          );
          const selectedStream = list.filter(stream => {
            if (includes(streamIds, stream.id)) {
              return stream;
            }
          });

          setStream(selectedStream);
        }
      });
  };

  useEffect(() => {
    setLoaderStatus(true);
    if (
      formState.values.hasOwnProperty("college") &&
      formState.values["college"] &&
      collegelist.length > 0
    ) {
      const college = collegelist.find(
        college => college.contact.id == formState.values["college"]
      );

      const collegeStreamIds = college.stream_strength.map(s => s.stream.id);
      const list = streamlist.filter(stream => {
        if (includes(collegeStreamIds, stream.id)) {
          return stream;
        }
      });

      setCollegeStreamList(list);
    }

    setLoaderStatus(false);
  }, [formState.values["college"], collegelist, streamlist]);

  const handleSubmit = event => {
    event.preventDefault();
    setBackDrop(true);

    let isValid = false;
    let checkAllFieldsValid = formUtilities.checkAllKeysPresent(
      formState.values,
      ActivityFormSchema
    );
    if (checkAllFieldsValid) {
      /** Evaluated only if all keys are valid inside formstate */
      formState.errors = formUtilities.setErrors(
        formState.values,
        ActivityFormSchema,
        true,
        dateFrom,
        dateTo
      );
      if (formUtilities.checkEmpty(formState.errors)) {
        isValid = true;
      }
    } else {
      /** This is used to find out which all required fields are not filled */
      formState.values = formUtilities.getListOfKeysNotPresent(
        formState.values,
        ActivityFormSchema
      );
      formState.errors = formUtilities.setErrors(
        formState.values,
        ActivityFormSchema,
        true,
        dateFrom,
        dateTo
      );
    }
    formState.descriptionError = false;

    if (
      convertToRaw(editorState.getCurrentContent()).blocks &&
      convertToRaw(editorState.getCurrentContent()).blocks.length
    ) {
      let arrayToCheckIn = convertToRaw(editorState.getCurrentContent()).blocks;
      let validationCounter = 0;
      let validationMinCounter = 0;
      for (let i in arrayToCheckIn) {
        if (
          arrayToCheckIn[i]["text"] &&
          arrayToCheckIn[i]["text"].trim().length !== 0
        ) {
          validationCounter += 1;
          break;
        }
      }
      if (validationCounter === 0) {
        formState.descriptionError = true;
      }
      for (let i in arrayToCheckIn) {
        if (
          arrayToCheckIn[i]["text"] &&
          arrayToCheckIn[i]["text"].trim().length > 320
        ) {
          validationMinCounter += 1;
          break;
        }
      }

      if (validationMinCounter !== 0) {
        formState.discriptionMinLengthError = true;
      }
    }
    if (
      isValid &&
      !formState.descriptionError &&
      !formState.discriptionMinLengthError
    ) {
      /** CALL POST FUNCTION */
      postActivityData();

      /** Call axios from here */
      setFormState(formState => ({
        ...formState,
        isValid: true
      }));
    } else {
      setBackDrop(false);
      setFormState(formState => ({
        ...formState,
        isValid: false
      }));
    }
  };

  const postActivityData = () => {
    let postData;
    if (formState.editActivity) {
      postData = databaseUtilities.editActivity(
        formState.showPreview,
        formState.values["activityname"],
        formState.values["activitytype"],
        formState.values["college"],
        formState.values[dateFrom],
        formState.values[dateTo],
        formState.values["educationyear"],
        formState.values["address"],
        draftToHtml(convertToRaw(editorState.getCurrentContent())),
        formState.values["trainer"],
        stream.map(stream => stream.id),
        formState["dataForEdit"]["id"],
        formState.files,
        formState.values["questionSet"],
        formState.values["activitystatus"]
      );
      serviceProvider
        .serviceProviderForPutRequest(
          strapiApiConstants.STRAPI_DB_URL + strapiApiConstants.STRAPI_ACTIVITY,
          formState.dataForEdit.id,
          postData
        )
        .then(response => {
          setFormState({ ...formState, isSuccess: true });
          history.push({
            pathname: routeConstants.MANAGE_ACTIVITY,
            isDataEdited: true,
            editedData: response.data,
            fromEditActivity: true
          });
          setBackDrop(false);
        })
        .catch(err => {
          setIsFailed(true);
          setBackDrop(false);
        });
    } else {
      postData = databaseUtilities.addActivity(
        formState.values["activityname"],
        formState.values["activitytype"],
        formState.values["college"],
        formState.values[dateFrom],
        formState.values[dateTo],
        formState.values["educationyear"],
        formState.values["address"],
        draftToHtml(convertToRaw(editorState.getCurrentContent())),
        formState.values["trainer"],
        stream.map(stream => stream.id),
        formState.files,
        formState.values["questionSet"]
      );
      serviceProvider
        .serviceProviderForPostRequest(
          strapiApiConstants.STRAPI_DB_URL + strapiApiConstants.STRAPI_ACTIVITY,
          postData
        )
        .then(({ data }) => {
          history.push({
            pathname: routeConstants.MANAGE_ACTIVITY,
            isDataAdded: true,
            addedData: data,
            fromAddActivity: true
          });
          setBackDrop(false);
        })
        .catch(err => {
          setIsFailed(true);
          setBackDrop(false);
        });
    }
  };

  const getColleges = async () => {
    await serviceProvider
      .serviceProviderForGetRequest(
        strapiApiConstants.STRAPI_DB_URL + strapiApiConstants.STRAPI_COLLEGES,
        { pageSize: -1 }
      )
      .then(res => {
        setcollegelist(
          res.data.result.map(({ id, name, contact, stream_strength }) => ({
            id,
            name,
            contact,
            stream_strength
          }))
        );
      });
  };

  const handleChangefile = e => {
    e.persist();
    setFormState(formState => ({
      ...formState,

      values: {
        ...formState.values,
        [e.target.name]: e.target.files[0].name
      },
      touched: {
        ...formState.touched,
        [e.target.name]: true
      },
      files: e.target.files[0],
      previewFile: URL.createObjectURL(e.target.files[0]),
      showPreview: true,
      showEditPreview: false,
      showNoImage: false
    }));
    if (formState.errors.hasOwnProperty(e.target.name)) {
      delete formState.errors[e.target.name];
    }
  };
  const handleChange = e => {
    /** TO SET VALUES IN FORMSTATE */
    e.persist();
    setFormState(formState => ({
      ...formState,

      values: {
        ...formState.values,
        [e.target.name]:
          e.target.type === "checkbox" ? e.target.checked : e.target.value
      },
      touched: {
        ...formState.touched,
        [e.target.name]: true
      }
    }));
    if (formState.errors.hasOwnProperty(e.target.name)) {
      delete formState.errors[e.target.name];
    }
  };

  const handleChangeAutoComplete = (eventName, event, value) => {
    /**TO SET VALUES OF AUTOCOMPLETE */
    if (value !== null) {
      if (eventName === "college") {
        setFormState(formState => ({
          ...formState,
          values: {
            ...formState.values,
            [eventName]: value.contact.id
          },
          touched: {
            ...formState.touched,
            [eventName]: true
          }
        }));
      } else {
        setFormState(formState => ({
          ...formState,
          values: {
            ...formState.values,
            [eventName]: value.id
          },
          touched: {
            ...formState.touched,
            [eventName]: true
          }
        }));
      }
      if (formState.errors.hasOwnProperty(eventName)) {
        delete formState.errors[eventName];
      }
    } else {
      if (eventName === "college") {
        delete formState.values["stream"];
        formState.stream = [];
        setCollegeStreamList([]);
        setStream([]);
      }
      delete formState.values[eventName];
    }
  };

  const handleStreamChange = (eventName, event, value) => {
    /**TO SET VALUES OF AUTOCOMPLETE */
    if (value !== null) {
      setFormState(formState => ({
        ...formState,
        values: {
          ...formState.values,
          [eventName]: value
        },
        touched: {
          ...formState.touched,
          [eventName]: true
        }
      }));
      if (formState.errors.hasOwnProperty(eventName)) {
        delete formState.errors[eventName];
      }
      setStream(value);
    }
  };

  const handleDateChange = (dateObject, event) => {
    if (formState.errors.hasOwnProperty(dateObject)) {
      delete formState.errors[dateObject];
    }
    setFormState(formState => ({
      ...formState,
      values: {
        ...formState.values,
        [dateObject]: event
      },
      touched: {
        ...formState.touched,
        [dateObject]: true
      },
      isStateClearFilter: false
    }));
  };

  const hasError = field => (formState.errors[field] ? true : false);
  return (
    <Grid>
      <Grid item xs={12} className={classes.title}>
        <Typography variant="h4" gutterBottom>
          {formState.editActivity
            ? genericConstants.EDIT_ACTIVITY_TEXT
            : genericConstants.ADD_ACTIVITY_TEXT}
        </Typography>
        {isFailed && formState.editActivity ? (
          <Collapse in={isFailed}>
            <Alert
              severity="error"
              action={
                <IconButton
                  aria-label="close"
                  color="inherit"
                  size="small"
                  onClick={() => {
                    setIsFailed(false);
                  }}
                >
                  <CloseIcon fontSize="inherit" />
                </IconButton>
              }
            >
              {genericConstants.ALERT_ERROR_DATA_EDITED_MESSAGE}
            </Alert>
          </Collapse>
        ) : null}
        {isFailed && !formState.editActivity ? (
          <Collapse in={isFailed}>
            <Alert
              severity="error"
              action={
                <IconButton
                  aria-label="close"
                  color="inherit"
                  size="small"
                  onClick={() => {
                    setIsFailed(false);
                  }}
                >
                  <CloseIcon fontSize="inherit" />
                </IconButton>
              }
            >
              {genericConstants.ALERT_ERROR_DATA_ADDED_MESSAGE}
            </Alert>
          </Collapse>
        ) : null}
      </Grid>
      <Grid spacing={3}>
        <Card>
          <form autoComplete="off" noValidate>
            <CardContent>
              <Grid item xs={12} md={6} xl={3}>
                <Grid container className={classes.formgridInputFile}>
                  <Grid item md={10} xs={12}>
                    <div className={classes.imageDiv}>
                      {formState.showPreview ? (
                        <Img
                          alt="abc"
                          loader={<Spinner />}
                          className={classes.UploadImage}
                          src={formState.previewFile}
                        />
                      ) : null}
                      {!formState.showPreview && !formState.showEditPreview ? (
                        <div className={classes.DefaultNoImage}></div>
                      ) : null}
                      {/* {formState.showEditPreview&&formState.dataForEdit.upload_logo===null? <div class={classes.DefaultNoImage}></div>:null} */}
                      {formState.showEditPreview &&
                      formState.dataForEdit["upload_logo"] !== null &&
                      formState.dataForEdit["upload_logo"] !== undefined &&
                      formState.dataForEdit["upload_logo"] !== {} ? (
                        <Img
                          src={
                            strapiApiConstants.STRAPI_DB_URL_WITHOUT_HASH +
                            formState.dataForEdit["upload_logo"]["url"]
                          }
                          loader={<Spinner />}
                          className={classes.UploadImage}
                        />
                      ) : null}
                      {formState.showNoImage ? (
                        <Img
                          src="/images/noImage.png"
                          loader={<Spinner />}
                          className={classes.UploadImage}
                        />
                      ) : null}
                    </div>
                  </Grid>
                </Grid>
                <Grid container className={classes.MarginBottom}>
                  <Grid item md={10} xs={12}>
                    <TextField
                      fullWidth
                      id="files"
                      margin="normal"
                      name="files"
                      placeholder="Upload Logo"
                      onChange={handleChangefile}
                      required
                      type="file"
                      inputProps={{ accept: "image/*" }}
                      //value={formState.values["files"] || ""}
                      error={hasError("files")}
                      helperText={
                        hasError("files")
                          ? formState.errors["files"].map(error => {
                              return error + " ";
                            })
                          : null
                      }
                      variant="outlined"
                      className={classes.inputFile}
                    />
                    <label htmlFor={get(ActivityFormSchema["files"], "id")}>
                      <Button
                        variant="contained"
                        color="primary"
                        component="span"
                        fullWidth
                        className={classes.InputFileButton}
                        startIcon={<AddOutlinedIcon />}
                      >
                        ADD NEW FILE
                      </Button>
                    </label>
                  </Grid>
                </Grid>
              </Grid>
              <Divider className={classes.divider} />
              <Grid item xs={12} md={6} xl={3}>
                <Grid container spacing={3} className={classes.formgrid}>
                  <Grid item md={12} xs={12}>
                    <Autocomplete
                      id="activitytype"
                      className={classes.root}
                      options={activityType}
                      getOptionLabel={option => option.name}
                      onChange={(event, value) => {
                        handleChangeAutoComplete("activitytype", event, value);
                      }}
                      value={
                        activityType[
                          activityType.findIndex(function (item, i) {
                            return item.id === formState.values.activitytype;
                          })
                        ] || null
                      }
                      renderInput={params => (
                        <TextField
                          {...params}
                          error={hasError("activitytype")}
                          label="Activity Type"
                          variant="outlined"
                          name="tester"
                          helperText={
                            hasError("activitytype")
                              ? formState.errors["activitytype"].map(error => {
                                  return error + " ";
                                })
                              : null
                          }
                        />
                      )}
                    />
                  </Grid>
                </Grid>
                <Grid container spacing={3} className={classes.formgrid}>
                  <Grid item md={12} xs={12}>
                    <Autocomplete
                      id="activityname"
                      className={classes.root}
                      options={activityNameList}
                      getOptionLabel={option => option.name}
                      onChange={(event, value) => {
                        handleChangeAutoComplete("activityname", event, value);
                      }}
                      value={
                        activityNameList[
                          activityNameList.findIndex(function (item, i) {
                            return item.id === formState.values["activityname"];
                          })
                        ] || null
                      }
                      renderInput={params => (
                        <TextField
                          {...params}
                          error={hasError("activityname")}
                          label="Activity Name"
                          variant="outlined"
                          required
                          name="activityname"
                          helperText={
                            hasError("activityname")
                              ? formState.errors["activityname"].map(error => {
                                  return error + " ";
                                })
                              : null
                          }
                        />
                      )}
                    />
                  </Grid>
                </Grid>
                <Grid container spacing={3} className={classes.MarginBottom}>
                  <Grid item md={12} xs={12} className={"descriptionBox"}>
                    <Grid
                      className={
                        formState.descriptionError ||
                        formState.discriptionMinLengthError
                          ? classes.descriptionBoxError
                          : classes.descriptionBox
                      }
                    >
                      <Card className={classes.streamoffer}>
                        <InputLabel
                          htmlFor="outlined-stream-card"
                          fullwidth={true.toString()}
                          error={
                            formState.descriptionError ||
                            formState.discriptionMinLengthError
                          }
                        >
                          {genericConstants.DESCRIPTION}
                        </InputLabel>
                        <div className="rdw-root">
                          <Editor
                            id="description-editor"
                            editorState={editorState}
                            toolbarClassName="rdw-toolbar"
                            wrapperClassName="rdw-wrapper"
                            editorClassName="rdw-editor"
                            value={editorState}
                            onEditorStateChange={data => {
                              formState.descriptionError = false;
                              formState.discriptionMinLengthError = false;
                              setEditorState(data);
                            }}
                          />
                        </div>
                        {formState.descriptionError ? (
                          <FormHelperText error={true}>
                            Description is required
                          </FormHelperText>
                        ) : null}
                        {formState.discriptionMinLengthError ? (
                          <FormHelperText error={true}>
                            Description length should be less than 320
                            characters
                          </FormHelperText>
                        ) : null}
                      </Card>
                    </Grid>
                  </Grid>
                </Grid>

                <Grid container spacing={3} className={classes.MarginBottom}>
                  <Grid item md={6} xs={12}>
                    <CustomDateTimePicker
                      onChange={event => {
                        handleDateChange(dateFrom, event);
                      }}
                      value={formState.values[dateFrom] || null}
                      name={dateFrom}
                      label={get(ActivityFormSchema[dateFrom], "label")}
                      placeholder={get(
                        ActivityFormSchema[dateFrom],
                        "placeholder"
                      )}
                      fullWidth
                      error={hasError(dateFrom)}
                      helperText={
                        hasError(dateFrom)
                          ? formState.errors[dateFrom].map(error => {
                              return error + " ";
                            })
                          : null
                      }
                    />
                  </Grid>
                  <Grid item md={6} xs={12}>
                    <CustomDateTimePicker
                      onChange={event => {
                        handleDateChange(dateTo, event);
                      }}
                      value={formState.values[dateTo] || null}
                      name={dateTo}
                      label={get(ActivityFormSchema[dateTo], "label")}
                      placeholder={get(
                        ActivityFormSchema[dateTo],
                        "placeholder"
                      )}
                      fullWidth
                      error={hasError(dateTo)}
                      helperText={
                        hasError(dateTo)
                          ? formState.errors[dateTo].map(error => {
                              return error + " ";
                            })
                          : null
                      }
                    />
                  </Grid>
                </Grid>

                <Grid container spacing={3} className={classes.MarginBottom}>
                  <Grid item md={12} xs={12}>
                    <TextField
                      label="Address"
                      name="address"
                      value={formState.values["address"] || ""}
                      variant="outlined"
                      required
                      fullWidth
                      id="addressId"
                      onChange={handleChange}
                      error={hasError("address")}
                      helperText={
                        hasError("address")
                          ? formState.errors["address"].map(error => {
                              return error + " ";
                            })
                          : null
                      }
                    />
                  </Grid>
                </Grid>

                <Grid container spacing={3} className={classes.MarginBottom}>
                  <Grid item md={12} xs={12}>
                    <Autocomplete
                      id="collegeId"
                      className={classes.root}
                      options={collegelist}
                      getOptionLabel={option => option.name}
                      onChange={(event, value) => {
                        handleChangeAutoComplete("college", event, value);
                      }}
                      value={
                        collegelist[
                          collegelist.findIndex(function (item, i) {
                            return item.contact.id === formState.values.college;
                          })
                        ] || null
                      }
                      renderInput={params => (
                        <TextField
                          {...params}
                          error={hasError("college")}
                          label="College"
                          variant="outlined"
                          required
                          name="tester"
                          helperText={
                            hasError("college")
                              ? formState.errors["college"].map(error => {
                                  return error + " ";
                                })
                              : null
                          }
                        />
                      )}
                    />
                  </Grid>
                </Grid>
                <Grid container spacing={3} className={classes.MarginBottom}>
                  <Grid item md={12} xs={12} className={classes.root}>
                    <Autocomplete
                      multiple={true}
                      id="collegeStreamID"
                      required
                      options={collegeStreamList}
                      getOptionLabel={option => option.name}
                      onChange={(event, value) => {
                        handleStreamChange("stream", event, value);
                      }}
                      value={stream}
                      filterSelectedOptions
                      renderInput={params => (
                        <TextField
                          {...params}
                          error={hasError("stream")}
                          label="Stream"
                          variant="outlined"
                          required
                          name="tester"
                          helperText={
                            hasError("stream")
                              ? formState.errors["stream"].map(error => {
                                  return error + " ";
                                })
                              : null
                          }
                        />
                      )}
                    />
                  </Grid>
                </Grid>
              </Grid>
              <Divider className={classes.divider} />
              <Grid item xs={12} md={6} xl={3}>
                <Grid container spacing={3} className={classes.formgrid}>
                  <Grid item md={6} xs={12}>
                    <Autocomplete
                      id="educationYearId"
                      className={classes.root}
                      options={educationyearlist}
                      getOptionLabel={option => option.name}
                      onChange={(event, value) => {
                        handleChangeAutoComplete("educationyear", event, value);
                      }}
                      value={
                        educationyearlist[
                          educationyearlist.findIndex(function (item, i) {
                            return item.id === formState.values.educationyear;
                          })
                        ] || null
                      }
                      renderInput={params => (
                        <TextField
                          {...params}
                          error={hasError("educationyear")}
                          label="Education Year"
                          variant="outlined"
                          name="tester"
                          helperText={
                            hasError("educationyear")
                              ? formState.errors["educationyear"].map(error => {
                                  return error + " ";
                                })
                              : null
                          }
                        />
                      )}
                    />
                  </Grid>
                  {formState.editActivity ? (
                    <Grid item md={6} xs={12}>
                      <Autocomplete
                        id="combo-box-demo"
                        className={classes.root}
                        options={activityStatus}
                        getOptionLabel={option => option.name}
                        onChange={(event, value) => {
                          handleChangeAutoComplete(
                            "activitystatus",
                            event,
                            value
                          );
                        }}
                        value={
                          activityStatus[
                            activityStatus.findIndex(function (item, i) {
                              return (
                                item.id === formState.values.activitystatus
                              );
                            })
                          ] || null
                        }
                        renderInput={params => (
                          <TextField
                            {...params}
                            error={hasError("activitystatus")}
                            label="Activity Status"
                            variant="outlined"
                            name="tester"
                            helperText={
                              hasError("activitystatus")
                                ? formState.errors["activitystatus"].map(
                                    error => {
                                      return error + " ";
                                    }
                                  )
                                : null
                            }
                          />
                        )}
                      />
                    </Grid>
                  ) : null}
                </Grid>
                <Grid container spacing={3} className={classes.formgrid}>
                  <Grid item md={6} xs={12}>
                    <TextField
                      label="Trainer Name"
                      name="trainer"
                      id="trainerId"
                      value={formState.values["trainer"] || ""}
                      variant="outlined"
                      required
                      fullWidth
                      onChange={handleChange}
                      error={hasError("trainer")}
                      helperText={
                        hasError("trainer")
                          ? formState.errors["trainer"].map(error => {
                              return error + " ";
                            })
                          : null
                      }
                    />
                  </Grid>
                  <Grid item md={6} xs={12}>
                    <Autocomplete
                      id="question_set"
                      className={classes.root}
                      options={questionSetData}
                      placeholder={"Select Question Set"}
                      getOptionLabel={option => option.name}
                      onChange={(event, value) => {
                        handleChangeAutoComplete("questionSet", event, value);
                      }}
                      required
                      value={
                        questionSetData[
                          questionSetData.findIndex(function (item, i) {
                            return item.id === formState.values["questionSet"];
                          })
                        ] || null
                      }
                      renderInput={params => (
                        <TextField
                          {...params}
                          label={"Question-Set"}
                          variant="outlined"
                          required
                          placeholder={"Select Question Set"}
                          error={hasError("questionSet")}
                          helperText={
                            hasError("questionSet")
                              ? formState.errors["questionSet"].map(error => {
                                  return error + " ";
                                })
                              : null
                          }
                        />
                      )}
                    />
                  </Grid>
                </Grid>
              </Grid>
            </CardContent>
            <Grid item xs={12} className={classes.CardActionGrid}>
              <CardActions className={classes.btnspace}>
                <Grid item xs={12}>
                  <Grid item xs={12} md={6} xl={3}>
                    {formState.editActivity ? (
                      <Grid container spacing={3}>
                        <Grid item md={2} xs={12}>
                          <YellowButton
                            color="primary"
                            type="submit"
                            mfullWidth
                            variant="contained"
                            style={{ marginRight: "18px" }}
                            onClick={handleSubmit}
                          >
                            <span>{genericConstants.SAVE_BUTTON_TEXT}</span>
                          </YellowButton>
                        </Grid>
                        <Grid item md={2} xs={12}>
                          <GrayButton
                            color="primary"
                            type="submit"
                            mfullWidth
                            variant="contained"
                            onClick={() => {
                              history.push(routeConstants.MANAGE_ACTIVITY);
                            }}
                          >
                            <span>{genericConstants.CANCEL_BUTTON_TEXT}</span>
                          </GrayButton>
                        </Grid>
                      </Grid>
                    ) : (
                      <Grid container spacing={3}>
                        <Grid item md={2} xs={12}>
                          <YellowButton
                            id="submitActivity"
                            color="primary"
                            type="submit"
                            mfullWidth
                            variant="contained"
                            style={{ marginRight: "18px" }}
                            onClick={handleSubmit}
                          >
                            <span>{genericConstants.SAVE_BUTTON_TEXT}</span>
                          </YellowButton>
                        </Grid>
                        <Grid item md={2} xs={12}>
                          <GrayButton
                            color="primary"
                            type="submit"
                            mfullWidth
                            variant="contained"
                            onClick={() => {
                              history.push(routeConstants.MANAGE_ACTIVITY);
                            }}
                          >
                            <span>{genericConstants.CANCEL_BUTTON_TEXT}</span>
                          </GrayButton>
                        </Grid>
                      </Grid>
                    )}
                  </Grid>
                </Grid>
              </CardActions>
            </Grid>
          </form>
        </Card>
      </Grid>
      <Backdrop className={classes.backDrop} open={backDrop}>
        <CircularProgress color="inherit" />
      </Backdrop>
    </Grid>
  );
}
Example #18
Source File: AddEditStudent.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
AddEditStudent = props => {
  let history = useHistory();
  const [user, setUser] = useState({
    firstName: "",
    middleName: "",
    lastName: "",
    fatherFulltName: "",
    motherFullName: "",
    address: "",
    district: null,
    state: null,
    email: "",
    contactNumber: "",
    userName: "",
    password: "",
    gender: "",
    physicallyHandicapped: null,
    college: null,
    stream: null,
    currentAcademicYear: null,
    collegeRollNumber: null,
    otp: "",
    futureAspirations: null
  });

  const [formState, setFormState] = useState({
    isValid: false,
    values: {},
    touched: {},
    errors: {},
    isDateOfBirthPresent: true,
    isdateOfBirthValid: true,
    isSuccess: false,
    showPassword: false,
    editStudent: props.location.editStudent
      ? props.location.editStudent
      : false,
    dataForEdit: props.location.dataForEdit
      ? props.location.dataForEdit
      : false,
    counter: 0,
    flag: 0,
    files: null,
    previewFile: {},
    showPreview: false,
    showEditPreview: props.location.editStudent
      ? props.location.dataForEdit.profile_photo
        ? true
        : false
      : false,
    showNoImage: props.location.editStudent
      ? false
      : props.location.editStudent,
    addressSameAsLocal: false,
    addresses: genericConstants.ADDRESSES
  });

  const [selectedDate, setSelectedDate] = useState(
    props.forTesting ? new Date("1999-03-25") : null
  );

  const genderlist = [
    { name: "Male", id: "male" },
    { name: "Female", id: "female" },
    { name: "Other", id: "other" }
  ];
  const [futureAspirationsList, setFutureAspirationsList] = useState(
    props.mockFutureAspiration ? props.mockFutureAspiration : []
  );
  const physicallyHandicappedlist = [
    { name: "Yes", id: true },
    { name: "No", id: false }
  ];
  const [isFailed, setIsFailed] = useState(false);
  const [backDrop, setBackDrop] = useState(false);

  const classes = useStyles();
  const [statelist, setstatelist] = useState(
    props.mockStateList ? props.mockStateList : []
  );
  const [districtlist, setdistrictlist] = useState(
    props.mockdistrictList ? props.mockdistrictList : []
  );
  const [collegelist, setcollegelist] = useState(
    props.mockCollegeData ? props.mockCollegeData : []
  );
  const [streamlist, setstreamlist] = useState(
    props.streamsList ? props.streamsList : []
  );
  const [collegeStreamList, setCollegeStreamList] = useState(
    props.mockCollegeStreamList ? props.mockCollegeStreamList : []
  );
  const [stream, setStream] = useState(null);

  const [validateAddress, setValidateAddress] = useState([]);

  useEffect(() => {
    if (
      props.location.pathname !== "/registration" &&
      props.location &&
      !props.location.dataForEdit
    ) {
      history.push({
        pathname: routeConstants.VIEW_PROFILE
      });
    }
    getStates();
    getFutureAspirations();
    getDistrict();
    getColleges();
    getStreams();
    // setLabelWidth(inputLabel.current.offsetWidth);
  }, []);

  useEffect(() => {
    if (
      formState.values.hasOwnProperty("college") &&
      formState.values["college"] &&
      collegelist.length > 0
    ) {
      const college = collegelist.find(
        college => college.id == formState.values["college"]
      );

      const collegeStreamIds = college.stream_strength.map(s => s.stream.id);
      const list = streamlist.filter(stream => {
        if (_.includes(collegeStreamIds, stream.id)) {
          return stream;
        }
      });

      setCollegeStreamList(list);
    }
  }, [formState.values["college"]]);

  useEffect(() => {
    if (!formState.editStudent) {
      if (formState.addressSameAsLocal) {
        const address = formState.addresses.find(
          addr => addr.address_type == "Temporary"
        );
        const copyAddresses = formState.addresses.map(addr => {
          if (addr.address_type == "Permanent") {
            return { ...address, address_type: "Permanent" };
          } else {
            return addr;
          }
        });

        setFormState(formState => ({
          ...formState,
          addresses: copyAddresses
        }));
      } else {
        const address = genericConstants.ADDRESSES.find(
          addr => addr.address_type == "Permanent"
        );

        const resetPermanentAddress = formState.addresses.map(addr => {
          if (addr.address_type == "Permanent") {
            return address;
          } else {
            return addr;
          }
        });
        setFormState(formState => ({
          ...formState,
          addresses: resetPermanentAddress
        }));
      }
    }
  }, [formState.addressSameAsLocal]);

  if (formState.dataForEdit && !formState.counter) {
    if (props.location["dataForEdit"]) {
      if (props.location["dataForEdit"]["first_name"]) {
        formState.values["firstname"] =
          props.location["dataForEdit"]["first_name"];
      }
      if (props.location["dataForEdit"]["middle_name"]) {
        formState.values["middlename"] =
          props.location["dataForEdit"]["middle_name"];
      }
      if (props.location["dataForEdit"]["last_name"]) {
        formState.values["lastname"] =
          props.location["dataForEdit"]["last_name"];
      }
      if (
        props.location["dataForEdit"]["contact"] &&
        props.location["dataForEdit"]["contact"]["user"] &&
        props.location["dataForEdit"]["contact"]["user"]["email"]
      ) {
        formState.values["email"] =
          props.location["dataForEdit"]["contact"]["user"]["email"];
      }
      if (
        props.location["dataForEdit"]["contact"] &&
        props.location["dataForEdit"]["contact"]["phone"]
      ) {
        formState.values["contact"] =
          props.location["dataForEdit"]["contact"]["phone"];
      }
      if (
        props.location["dataForEdit"]["contact"] &&
        props.location["dataForEdit"]["contact"]["user"] &&
        props.location["dataForEdit"]["contact"]["user"]["username"]
      ) {
        formState.values["username"] =
          props.location["dataForEdit"]["contact"]["user"]["username"];
      }
      if (
        props.location["dataForEdit"]["organization"] &&
        props.location["dataForEdit"]["organization"]["id"]
      ) {
        formState.values["college"] =
          props.location["dataForEdit"]["organization"]["id"];
      }
      // if (
      //   props.location["dataForEdit"]["contact"] &&
      //   props.location["dataForEdit"]["contact"]["state"]
      // ) {
      //   formState.values["state"] =
      //     props.location["dataForEdit"]["contact"]["state"]["id"];
      // }
      if (
        props.location["dataForEdit"]["stream"] &&
        props.location["dataForEdit"]["stream"]["id"]
      ) {
        formState.values["stream"] = props.location["dataForEdit"]["stream"];
      }

      // if (
      //   props.location["dataForEdit"]["contact"]["district"] &&
      //   props.location["dataForEdit"]["contact"]["district"]["id"]
      // ) {
      //   formState.values["district"] =
      //     props.location["dataForEdit"]["contact"]["district"]["id"];
      // }

      if (props.location["dataForEdit"]["father_full_name"]) {
        formState.values["fatherFullName"] =
          props.location["dataForEdit"]["father_full_name"];
      }
      if (props.location["dataForEdit"]["mother_full_name"]) {
        formState.values["motherFullName"] =
          props.location["dataForEdit"]["mother_full_name"];
      }
      // if (props.location["dataForEdit"]["contact"]["address_1"]) {
      //   formState.values["address"] =
      //     props.location["dataForEdit"]["contact"]["address_1"];
      // }
      if (props.location["dataForEdit"]["gender"]) {
        formState.values["gender"] = props.location["dataForEdit"]["gender"];
      }

      if (props.location["dataForEdit"]["roll_number"]) {
        formState.values["rollnumber"] =
          props.location["dataForEdit"]["roll_number"];
      }
      if (props.location["dataForEdit"]["future_aspirations"]) {
        formState.values["futureAspirations"] =
          props.location["dataForEdit"]["future_aspirations"];
        formState["futureAspirations"] = props.location["dataForEdit"][
          "future_aspirations"
        ].map(value => value.id);
      }

      if (props.location["dataForEdit"]) {
        formState.values["physicallyHandicapped"] =
          props.location["dataForEdit"]["is_physically_challenged"];
      }
      if (
        props.location["dataForEdit"]["organization"] &&
        props.location["dataForEdit"]["organization"]["id"]
      ) {
        formState.values["college"] =
          props.location["dataForEdit"]["organization"]["id"];
      }
      if (props.location["dataForEdit"]["date_of_birth"]) {
        setSelectedDate(
          new Date(props.location["dataForEdit"]["date_of_birth"])
        );
      }
      if (
        props.location["dataForEdit"]["profile_photo"] &&
        props.location["dataForEdit"]["profile_photo"]["id"]
      ) {
        formState.previewFile = props.location["dataForEdit"]["profile_photo"];
        //      formState.values["files"] =
        //        props.location["dataForEdit"]["upload_logo"]["name"];
      }

      if (
        props.location["dataForEdit"]["contact"] &&
        props.location["dataForEdit"]["contact"]["addresses"] &&
        props.location["dataForEdit"]["contact"]["addresses"].length > 0
      ) {
        formState.addresses =
          props.location["dataForEdit"]["contact"]["addresses"];
      } else {
        formState.addresses = genericConstants.ADDRESSES;
      }
    }
    formState.counter += 1;
  }

  if (props.location.state && !formState.counter) {
    if (props.location.state.contactNumber && props.location.state.otp) {
      formState.values["contact"] = props.location.state.contactNumber;
      formState.values["otp"] = props.location.state.otp;
      formState.values["username"] = props.location.state.contactNumber;
    }
    formState.counter += 1;
  }

  const handleSubmit = event => {
    event.preventDefault();
    const isValidAddress = validateAddresses();
    setBackDrop(true);
    let schema;
    if (formState.editStudent) {
      schema = Object.assign(
        {},
        _.omit(registrationSchema, ["password", "otp"])
      );
    } else {
      schema = registrationSchema;
    }
    let isValid = false;
    let checkAllFieldsValid = formUtilities.checkAllKeysPresent(
      formState.values,
      schema
    );
    if (checkAllFieldsValid) {
      /** Evaluated only if all keys are valid inside formstate */
      formState.errors = formUtilities.setErrors(formState.values, schema);

      if (formUtilities.checkEmpty(formState.errors)) {
        isValid = true;
      }
    } else {
      /** This is used to find out which all required fields are not filled */
      formState.values = formUtilities.getListOfKeysNotPresent(
        formState.values,
        schema
      );
      formState.errors = formUtilities.setErrors(formState.values, schema);
    }

    if (selectedDate === null) {
      formState.isDateOfBirthPresent = false;
    } else {
      formState.isDateOfBirthPresent = true;
      if (props.forTesting) {
        formState.isdateOfBirthValid = true;
      } else {
        formState.isdateOfBirthValid = formUtilities.validateDateOfBirth(
          selectedDate
        );
      }
    }

    console.log(formState);
    if (
      isValid &&
      formState.isDateOfBirthPresent &&
      formState.isdateOfBirthValid &&
      isValidAddress
    ) {
      /** CALL POST FUNCTION */
      postStudentData();

      /** Call axios from here */
      setFormState(formState => ({
        ...formState,
        isValid: true
      }));
    } else {
      setFormState(formState => ({
        ...formState,
        isValid: false
      }));
      setBackDrop(false);
    }
  };

  const saveAndNext = event => {
    event.preventDefault();
    formState["flag"] = 1;
    handleSubmit(event);
  };

  const postStudentData = () => {
    let postData;
    const addresses = formState.addresses;
    if (formState.editStudent) {
      postData = databaseUtilities.editStudent(
        formState.values["firstname"],
        formState.values["middlename"],
        formState.values["lastname"],
        formState.values["fatherFullName"],
        formState.values["motherFullName"],
        formState.values["email"],
        formState.values["contact"],
        formState.values["contact"],
        formState.values["gender"],
        selectedDate.getFullYear() +
          "-" +
          (selectedDate.getMonth() + 1) +
          "-" +
          selectedDate.getDate(),
        formState.values["physicallyHandicapped"] !== undefined
          ? formState.values["physicallyHandicapped"]
          : null,
        formState.values["college"],
        formState.values["stream"].id,
        formState.values["rollnumber"],
        formState.dataForEdit.id,
        formState.values["futureAspirations"]
          ? formState["futureAspirations"]
          : null,
        formState.files,
        null,
        addresses
      );
      let EDIT_STUDENT_URL =
        strapiApiConstants.STRAPI_DB_URL +
        strapiApiConstants.STRAPI_CONTACT_URL;
      let EDIT_URL = strapiApiConstants.STRAPI_EDIT_STUDENT;
      serviceProvider
        .serviceProviderForPutRequest(
          EDIT_STUDENT_URL,
          formState.dataForEdit.contact.id,
          postData,
          EDIT_URL
        )
        .then(response => {
          if (auth.getUserInfo().role.name === roleConstants.STUDENT) {
            commonUtilities.updateUser();
          }
          let studentName =
            props.location["dataForEdit"]["first_name"] +
            " " +
            props.location["dataForEdit"]["middlename"] +
            " " +
            props.location["dataForEdit"]["last_name"];
          if (
            auth.getUserInfo().role.name === roleConstants.MEDHAADMIN ||
            auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN
          ) {
            history.push({
              pathname: routeConstants.MANAGE_STUDENT,
              fromeditStudent: true,
              isDataEdited: true,
              editedStudentName: studentName
            });
          } else {
            if (formState.flag === 1) {
              history.push({
                pathname: routeConstants.VIEW_EDUCATION
              });
            } else {
              history.push({
                pathname: routeConstants.VIEW_PROFILE,
                success: true
              });
            }
          }

          setBackDrop(false);
        })
        .catch(err => {
          setIsFailed(true);
          let studentName =
            props.location["dataForEdit"]["first_name"] +
            " " +
            props.location["dataForEdit"]["middlename"] +
            " " +
            props.location["dataForEdit"]["last_name"];
          if (
            auth.getUserInfo().role.name === roleConstants.MEDHAADMIN ||
            auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN
          ) {
            history.push({
              pathname: routeConstants.MANAGE_STUDENT,
              fromeditStudent: true,
              isDataEdited: true,
              editedStudentName: studentName
            });
          } else {
            history.push({
              pathname: routeConstants.VIEW_PROFILE,
              success: false
            });
          }
          setBackDrop(false);
        });
    } else {
      postData = databaseUtilities.addStudent(
        formState.values["firstname"],
        formState.values["middlename"],
        formState.values["lastname"],
        formState.values["fatherFullName"],
        formState.values["motherFullName"],
        formState.values["email"],
        formState.values["contact"],
        formState.values["contact"],
        formState.values["password"],
        formState.values["gender"],
        selectedDate.getFullYear() +
          "-" +
          (selectedDate.getMonth() + 1) +
          "-" +
          selectedDate.getDate(),
        formState.values["physicallyHandicapped"],
        formState.values["college"],
        formState.values["stream"].id,
        formState.values["rollnumber"],
        formState.values.otp,
        formState.files,
        formState.values["futureAspirations"]
          ? formState["futureAspirations"]
          : null,
        true,
        addresses
      );

      axios
        .post(
          strapiApiConstants.STRAPI_DB_URL +
            strapiApiConstants.STRAPI_CREATE_USERS,
          postData
        )
        .then(response => {
          if (auth.getToken() === null || auth.getUserInfo() === null) {
            history.push(routeConstants.REGISTERED);
          } else {
            if (
              auth.getUserInfo().role.name === roleConstants.MEDHAADMIN ||
              auth.getUserInfo().role.name === roleConstants.COLLEGEADMIN
            ) {
              history.push(routeConstants.MANAGE_STUDENT);
            }
          }
          setBackDrop(false);
        })
        .catch(err => {
          console.log(err);
          setBackDrop(false);
        });
    }
  };

  const getFutureAspirations = () => {
    axios
      .get(
        strapiApiConstants.STRAPI_DB_URL +
          strapiApiConstants.STRAPI_FUTURE_ASPIRATIONS +
          "?pageSize=-1"
      )
      .then(res => {
        const list = res.data.result.map(({ id, name }) => ({ id, name }));
        setFutureAspirationsList(list);
        if (formState.dataForEdit) {
          const id = props.location["dataForEdit"]["future_aspirations"].map(
            value => value.id
          );
          const ids = list.filter(value => {
            if (includes(id, value.id)) {
              return value;
            }
          });
          formState.values["futureAspirations"] = ids;
        }
      });
  };
  const getColleges = () => {
    axios
      .get(
        strapiApiConstants.STRAPI_DB_URL +
          strapiApiConstants.STRAPI_COLLEGES +
          "?pageSize=-1"
      )
      .then(res => {
        setcollegelist(
          res.data.result.map(({ id, name, stream_strength }) => ({
            id,
            name,
            stream_strength
          }))
        );
      });
  };

  const getStreams = () => {
    axios
      .get(
        strapiApiConstants.STRAPI_DB_URL +
          strapiApiConstants.STRAPI_STREAMS +
          "?pageSize=-1"
      )
      .then(res => {
        const list = res.data.map(({ id, name }) => ({
          id,
          name
        }));
        setstreamlist(list);

        if (formState.dataForEdit && props.location["dataForEdit"]["stream"]) {
          const selectedStream = list.find(
            stream => stream.id == props.location["dataForEdit"]["stream"]["id"]
          );

          setStream(selectedStream);
        }
      });
  };

  const getStates = () => {
    axios
      .get(
        strapiApiConstants.STRAPI_DB_URL +
          strapiApiConstants.STRAPI_STATES +
          "?pageSize=-1"
      )
      .then(res => {
        setstatelist(res.data.result.map(({ id, name }) => ({ id, name })));
      });
  };

  const getDistrict = () => {
    axios
      .get(
        strapiApiConstants.STRAPI_DB_URL +
          strapiApiConstants.STRAPI_DISTRICTS +
          "?pageSize=-1"
      )
      .then(res => {
        setdistrictlist(
          res.data.result.map(({ id, name, state }) => ({
            id,
            name,
            state: state.id
          }))
        );
      });
  };

  const handleChange = e => {
    /** TO SET VALUES IN FORMSTATE */
    e.persist();
    setFormState(formState => ({
      ...formState,

      values: {
        ...formState.values,
        [e.target.name]:
          e.target.type === "checkbox" ? e.target.checked : e.target.value
      },
      touched: {
        ...formState.touched,
        [e.target.name]: true
      }
    }));
    if (formState.errors.hasOwnProperty(e.target.name)) {
      delete formState.errors[e.target.name];
    }
  };

  const handleChangeAutoComplete = (eventName, event, value) => {
    /**TO SET VALUES OF AUTOCOMPLETE */
    if (value !== null) {
      setFormState(formState => ({
        ...formState,
        values: {
          ...formState.values,
          [eventName]: value.id
        },
        touched: {
          ...formState.touched,
          [eventName]: true
        }
      }));
      if (formState.errors.hasOwnProperty(eventName)) {
        delete formState.errors[eventName];
      }
    } else {
      if (eventName === "state") {
        delete formState.values["district"];
      }
      delete formState.values[eventName];
      setFormState(formState => ({
        ...formState
      }));
    }
  };

  const handleStreamChange = (eventName, event, value) => {
    /**TO SET VALUES OF AUTOCOMPLETE */
    if (value !== null) {
      setFormState(formState => ({
        ...formState,
        values: {
          ...formState.values,
          [eventName]: value
        },
        touched: {
          ...formState.touched,
          [eventName]: true
        }
      }));
      if (formState.errors.hasOwnProperty(eventName)) {
        delete formState.errors[eventName];
      }
      setStream(value);
    } else {
      if (eventName === "state") {
        delete formState.values["district"];
      }
      delete formState.values[eventName];
      setFormState(formState => ({
        ...formState
      }));
    }
  };

  const handleClickShowPassword = () => {
    setFormState({
      ...formState,
      showPassword: !formState.showPassword
    });
  };

  const handleFutureAspirationChange = (eventName, event, value) => {
    /**TO SET VALUES OF AUTOCOMPLETE */
    if (value !== null) {
      const id = value.map(value => value.id).filter(c => c);
      setFormState(formState => ({
        ...formState,
        values: {
          ...formState.values,
          [eventName]: value
        },
        touched: {
          ...formState.touched,
          [eventName]: true
        },
        futureAspirations: id
      }));
      if (formState.errors.hasOwnProperty(eventName)) {
        delete formState.errors[eventName];
      }
    }
  };

  const handleChangefile = e => {
    e.persist();
    setFormState(formState => ({
      ...formState,

      values: {
        ...formState.values,
        [e.target.name]: e.target.files[0].name
      },
      touched: {
        ...formState.touched,
        [e.target.name]: true
      },
      files: e.target.files[0],
      previewFile: URL.createObjectURL(e.target.files[0]),
      showPreview: true,
      showEditPreview: false,
      showNoImage: false
    }));
    if (formState.errors.hasOwnProperty(e.target.name)) {
      delete formState.errors[e.target.name];
    }
  };

  const hasError = field => (formState.errors[field] ? true : false);

  const changeContactNumber = () => {
    history.push(routeConstants.CHANGE_CONTACT_NUMBER, {
      contactNumber: formState.values["contact"]
    });
  };

  const handleStateAndDistrictChange = (type, value, idx) => {
    formState.addresses[idx][type] = value && value.id;
    if (type == "state") {
      formState.addresses[idx]["district"] = null;
    }
    validateAddresses();
    setFormState(formState => ({
      ...formState
    }));
  };

  const handleAddressChange = (idx, e, type) => {
    e.persist();
    console.log(e.target.value);

    const addresses = formState.addresses.map((addr, index) => {
      if (index == idx) {
        return { ...addr, [type]: e.target.value };
      } else {
        return addr;
      }
    });
    validateAddresses();
    setFormState(formState => ({
      ...formState,
      addresses
    }));
  };

  const validateAddresses = () => {
    const addresses = formState.addresses;
    let errors = [];
    let isError = false;
    addresses.forEach(addr => {
      let errorObject = {};
      if (!(addr.address_line_1 && addr.address_line_1.length > 0)) {
        isError = true;
        errorObject["address_line_1"] = {
          error: true,
          message: "Address is required"
        };
      } else {
        errorObject["address_line_1"] = {
          error: false,
          message: null
        };
      }

      if (!addr.state) {
        isError = true;
        errorObject["state"] = {
          error: true,
          message: "State is required"
        };
      } else {
        errorObject["state"] = {
          error: false,
          message: null
        };
      }

      if (!addr.district) {
        isError = true;
        errorObject["district"] = {
          error: true,
          message: "District is required"
        };
      } else {
        errorObject["district"] = {
          error: false,
          message: null
        };
      }

      if (!addr.city) {
        isError = true;
        errorObject["city"] = {
          error: true,
          message: "City is required"
        };
      } else {
        errorObject["city"] = {
          error: false,
          message: null
        };
      }

      if (!addr.pincode) {
        isError = true;
        errorObject["pincode"] = {
          error: true,
          message: "Pincode is required"
        };
      } else {
        errorObject["pincode"] = {
          error: false,
          message: null
        };
      }

      errors.push(errorObject);
    });

    setValidateAddress(errors);
    return !isError;
  };

  console.log(formState.addresses);
  console.log(validateAddress);
  return (
    // <Layout>
    <Grid>
      <Grid item xs={12} className={classes.title}>
        {formState.editStudent ? null : (
          <Typography variant="h4" gutterBottom>
            {genericConstants.STUDENT_REGISTRATION}
          </Typography>
        )}

        {isFailed && formState.editStudent ? (
          <Collapse in={isFailed}>
            <Alert
              severity="error"
              action={
                <IconButton
                  aria-label="close"
                  color="inherit"
                  size="small"
                  onClick={() => {
                    setIsFailed(false);
                  }}
                >
                  <CloseIcon fontSize="inherit" />
                </IconButton>
              }
            >
              {genericConstants.ALERT_ERROR_DATA_EDITED_MESSAGE}
            </Alert>
          </Collapse>
        ) : null}
        {isFailed && !formState.editStudent ? (
          <Collapse in={isFailed}>
            <Alert
              severity="error"
              action={
                <IconButton
                  aria-label="close"
                  color="inherit"
                  size="small"
                  onClick={() => {
                    setIsFailed(false);
                  }}
                >
                  <CloseIcon fontSize="inherit" />
                </IconButton>
              }
            >
              {genericConstants.ALERT_ERROR_DATA_ADDED_MESSAGE}
            </Alert>
          </Collapse>
        ) : null}
      </Grid>
      <Card>
        <form autoComplete="off" noValidate>
          <CardContent>
            <Grid item xs={12} md={6} xl={3}>
              <Grid container className={classes.formgridInputFile}>
                <Grid item md={10} xs={12}>
                  <div className={classes.imageDiv}>
                    {formState.showPreview ? (
                      <Img
                        alt="abc"
                        loader={<Spinner />}
                        className={classes.UploadImage}
                        src={formState.previewFile}
                      />
                    ) : null}
                    {!formState.showPreview && !formState.showEditPreview ? (
                      <div className={classes.DefaultNoImage}></div>
                    ) : null}
                    {/* {formState.showEditPreview&&formState.dataForEdit.upload_logo===null? <div class={classes.DefaultNoImage}></div>:null} */}
                    {formState.showEditPreview &&
                    formState.dataForEdit["profile_photo"] !== null &&
                    formState.dataForEdit["profile_photo"] !== undefined &&
                    formState.dataForEdit["profile_photo"] !== {} ? (
                      <Img
                        src={
                          strapiApiConstants.STRAPI_DB_URL_WITHOUT_HASH +
                          formState.dataForEdit["profile_photo"]["url"]
                        }
                        loader={<Spinner />}
                        className={classes.UploadImage}
                      />
                    ) : null}
                    {formState.showNoImage ? (
                      <Img
                        src="/images/noImage.png"
                        loader={<Spinner />}
                        className={classes.UploadImage}
                      />
                    ) : null}
                  </div>
                </Grid>
              </Grid>
              <Grid container className={classes.MarginBottom}>
                <Grid item md={10} xs={12}>
                  <TextField
                    fullWidth
                    id="files"
                    margin="normal"
                    name="files"
                    placeholder="Upload Logo"
                    onChange={handleChangefile}
                    required
                    type="file"
                    inputProps={{ accept: "image/*" }}
                    //value={formState.values["files"] || ""}
                    error={hasError("files")}
                    helperText={
                      hasError("files")
                        ? formState.errors["files"].map(error => {
                            return error + " ";
                          })
                        : null
                    }
                    variant="outlined"
                    className={classes.inputFile}
                  />
                  <label htmlFor={get(registrationSchema["files"], "id")}>
                    <Button
                      variant="contained"
                      color="primary"
                      component="span"
                      fullWidth
                      className={classes.InputFileButton}
                      startIcon={<AddOutlinedIcon />}
                    >
                      ADD PROFILE PHOTO
                    </Button>
                  </label>
                </Grid>
              </Grid>
            </Grid>
            <Divider className={classes.divider} />

            <Grid item xs={12} md={6} xl={3}>
              <Grid container spacing={3} className={classes.formgrid}>
                <Grid item md={12} xs={12}>
                  <TextField
                    id="firstName"
                    label="First Name"
                    name="firstname"
                    value={formState.values["firstname"] || ""}
                    variant="outlined"
                    required
                    fullWidth
                    onChange={handleChange}
                    error={hasError("firstname")}
                    helperText={
                      hasError("firstname")
                        ? formState.errors["firstname"].map(error => {
                            return error + " ";
                          })
                        : null
                    }
                  />
                </Grid>
              </Grid>
              <Grid container spacing={3} className={classes.MarginBottom}>
                <Grid item md={6} xs={12}>
                  <TextField
                    id="middlename"
                    label="Middle Name"
                    name="middlename"
                    value={formState.values["middlename"]}
                    variant="outlined"
                    error={hasError("middlename")}
                    fullWidth
                    onChange={handleChange}
                    helperText={
                      hasError("middlename")
                        ? formState.errors["middlename"].map(error => {
                            return error + " ";
                          })
                        : null
                    }
                  />
                </Grid>
                <Grid item md={6} xs={12}>
                  <TextField
                    id="lastname"
                    label="Last Name"
                    name="lastname"
                    value={formState.values["lastname"]}
                    variant="outlined"
                    required
                    fullWidth
                    error={hasError("lastname")}
                    onChange={handleChange}
                    helperText={
                      hasError("lastname")
                        ? formState.errors["lastname"].map(error => {
                            return error + " ";
                          })
                        : null
                    }
                  />
                </Grid>
              </Grid>
              <Grid container spacing={3} className={classes.MarginBottom}>
                <Grid item md={6} xs={12}>
                  <TextField
                    id="fatherFullName"
                    label="Father's Full Name"
                    name="fatherFullName"
                    value={formState.values["fatherFullName"] || ""}
                    variant="outlined"
                    required
                    fullWidth
                    onChange={handleChange}
                    error={hasError("fatherFullName")}
                    helperText={
                      hasError("fatherFullName")
                        ? formState.errors["fatherFullName"].map(error => {
                            return error + " ";
                          })
                        : null
                    }
                  />
                </Grid>
                <Grid item md={6} xs={12}>
                  <TextField
                    id="motherFullName"
                    label="Mother's Full Name"
                    name="motherFullName"
                    value={formState.values["motherFullName"] || ""}
                    variant="outlined"
                    required
                    fullWidth
                    onChange={handleChange}
                    error={hasError("motherFullName")}
                    helperText={
                      hasError("motherFullName")
                        ? formState.errors["motherFullName"].map(error => {
                            return error + " ";
                          })
                        : null
                    }
                  />
                </Grid>
              </Grid>
              <Divider className={classes.divider} />
              <Grid container spacing={3} className={classes.MarginBottom}>
                {formState.addresses.map((addr, idx) => {
                  return (
                    <Grid item md={12} xs={12}>
                      <Grid item md={12} xs={12} className={classes.streamcard}>
                        <Card className={classes.streamoffer}>
                          <InputLabel
                            htmlFor="outlined-address-card"
                            fullwidth={true.toString()}
                          >
                            {addr.address_type == "Temporary"
                              ? "Local Address"
                              : "Permanent Address"}
                          </InputLabel>
                          <Grid
                            container
                            spacing={3}
                            className={classes.MarginBottom}
                          >
                            <Grid
                              item
                              md={12}
                              xs={12}
                              style={{ marginTop: "8px" }}
                            >
                              <TextField
                                label="Address"
                                name="address"
                                value={
                                  formState.addresses[idx].address_line_1 || ""
                                }
                                variant="outlined"
                                required
                                fullWidth
                                onChange={event =>
                                  handleAddressChange(
                                    idx,
                                    event,
                                    "address_line_1"
                                  )
                                }
                                error={
                                  (validateAddress[idx] &&
                                    validateAddress[idx]["address_line_1"][
                                      "error"
                                    ]) ||
                                  false
                                }
                                helperText={
                                  (validateAddress[idx] &&
                                    validateAddress[idx]["address_line_1"][
                                      "message"
                                    ]) ||
                                  null
                                }
                              />
                            </Grid>
                          </Grid>
                          <Grid
                            container
                            spacing={3}
                            className={classes.MarginBottom}
                          >
                            <Grid item md={6} xs={12}>
                              <Autocomplete
                                id="combo-box-demo"
                                className={classes.root}
                                options={statelist}
                                getOptionLabel={option => option.name}
                                onChange={(event, value) => {
                                  handleStateAndDistrictChange(
                                    "state",
                                    value,
                                    idx
                                  );
                                }}
                                value={
                                  statelist[
                                    statelist.findIndex(function (item, i) {
                                      return (
                                        item.id ===
                                        formState.addresses[idx].state
                                      );
                                    })
                                  ] || null
                                }
                                renderInput={params => (
                                  <TextField
                                    {...params}
                                    label="State"
                                    variant="outlined"
                                    name="tester"
                                    error={
                                      (validateAddress[idx] &&
                                        validateAddress[idx]["state"][
                                          "error"
                                        ]) ||
                                      false
                                    }
                                    helperText={
                                      (validateAddress[idx] &&
                                        validateAddress[idx]["state"][
                                          "message"
                                        ]) ||
                                      null
                                    }
                                  />
                                )}
                              />
                            </Grid>
                            <Grid item md={6} xs={12}>
                              <Autocomplete
                                id="combo-box-demo"
                                className={classes.root}
                                options={districtlist.filter(
                                  district =>
                                    district.state ===
                                    formState.addresses[idx].state
                                )}
                                getOptionLabel={option => option.name}
                                onChange={(event, value) => {
                                  handleStateAndDistrictChange(
                                    "district",
                                    value,
                                    idx
                                  );
                                }}
                                value={
                                  districtlist[
                                    districtlist.findIndex(function (item, i) {
                                      return (
                                        item.id ===
                                        formState.addresses[idx].district
                                      );
                                    })
                                  ] || null
                                }
                                renderInput={params => (
                                  <TextField
                                    {...params}
                                    label="District"
                                    variant="outlined"
                                    name="tester"
                                    error={
                                      (validateAddress[idx] &&
                                        validateAddress[idx]["district"][
                                          "error"
                                        ]) ||
                                      false
                                    }
                                    helperText={
                                      (validateAddress[idx] &&
                                        validateAddress[idx]["district"][
                                          "message"
                                        ]) ||
                                      null
                                    }
                                  />
                                )}
                              />
                            </Grid>
                            <Grid item md={6} xs={12}>
                              <TextField
                                label="City"
                                name="city"
                                value={formState.addresses[idx].city || ""}
                                variant="outlined"
                                required
                                fullWidth
                                onChange={event =>
                                  handleAddressChange(idx, event, "city")
                                }
                                error={
                                  (validateAddress[idx] &&
                                    validateAddress[idx]["city"]["error"]) ||
                                  false
                                }
                                helperText={
                                  (validateAddress[idx] &&
                                    validateAddress[idx]["city"]["message"]) ||
                                  null
                                }
                              />
                            </Grid>
                            <Grid item md={6} xs={12}>
                              <TextField
                                label="Pincode"
                                name="pincode"
                                value={formState.addresses[idx].pincode || ""}
                                variant="outlined"
                                required
                                fullWidth
                                onChange={event =>
                                  handleAddressChange(idx, event, "pincode")
                                }
                                error={
                                  (validateAddress[idx] &&
                                    validateAddress[idx]["pincode"]["error"]) ||
                                  false
                                }
                                helperText={
                                  (validateAddress[idx] &&
                                    validateAddress[idx]["pincode"][
                                      "message"
                                    ]) ||
                                  null
                                }
                              />
                            </Grid>
                          </Grid>
                          <Grid item md={12} xs={12}>
                            {!formState.editStudent &&
                            addr.address_type == "Temporary" ? (
                              <FormControlLabel
                                control={
                                  <Checkbox
                                    checked={formState.addressSameAsLocal}
                                    onChange={event => {
                                      setFormState(formState => ({
                                        ...formState,
                                        addressSameAsLocal: event.target.checked
                                      }));
                                    }}
                                    name="addressSameAsLocal"
                                    color="primary"
                                  />
                                }
                                label="Permanent Address same as local Address?"
                              />
                            ) : null}
                          </Grid>
                        </Card>
                      </Grid>
                    </Grid>
                  );
                })}
              </Grid>
            </Grid>
            <Divider className={classes.divider} />
            <Grid item xs={12} md={6} xl={3}>
              <Grid container spacing={3} className={classes.formgrid}>
                <Grid item md={6} xs={12}>
                  <TextField
                    id="contact"
                    label="Contact Number"
                    name="contact"
                    value={formState.values["contact"] || ""}
                    variant="outlined"
                    required
                    fullWidth
                    readOnly
                    disabled
                    error={hasError("contact")}
                    helperText={
                      hasError("contact")
                        ? formState.errors["contact"].map(error => {
                            return error + " ";
                          })
                        : null
                    }
                  />
                  {formState.editStudent ? (
                    <Link
                      href="javascript:void(0);"
                      variant="body2"
                      className={classes.linkColor}
                      onClick={changeContactNumber}
                    >
                      {authPageConstants.CHANGE_CONTACT_NUMBER}
                    </Link>
                  ) : null}
                </Grid>

                <Grid
                  item
                  md={6}
                  xs={12}
                  style={formState.editStudent ? { marginTop: "-22px" } : null}
                >
                  <InlineDatePicker
                    // variant="inline"
                    format="dd/MM/yyyy"
                    margin="normal"
                    id="date-picker-inline"
                    label="Date of Birth"
                    value={selectedDate}
                    className={classes.date}
                    onChange={date => {
                      formState.isDateOfBirthPresent = true;
                      formState.isdateOfBirthValid = true;
                      setSelectedDate(date);
                    }}
                    error={
                      !formState.isDateOfBirthPresent ||
                      !formState.isdateOfBirthValid
                    }
                    helperText={
                      !formState.isDateOfBirthPresent
                        ? "Date of Birth is required"
                        : !formState.isdateOfBirthValid
                        ? "Date of birth cannot be greater than current date"
                        : null
                    }
                    KeyboardButtonProps={{
                      "aria-label": "change date"
                    }}
                  />
                </Grid>
              </Grid>
              <Grid container spacing={3} className={classes.formgrid}>
                <Grid item md={6} xs={12}>
                  <Autocomplete
                    id="gender-filter"
                    className={classes.root}
                    options={genderlist}
                    getOptionLabel={option => option.name}
                    onChange={(event, value) => {
                      handleChangeAutoComplete("gender", event, value);
                    }}
                    value={
                      genderlist[
                        genderlist.findIndex(function (item, i) {
                          return item.id === formState.values.gender;
                        })
                      ] || null
                    }
                    renderInput={params => (
                      <TextField
                        {...params}
                        error={hasError("gender")}
                        label="Gender"
                        required
                        variant="outlined"
                        name="tester"
                        helperText={
                          hasError("gender")
                            ? formState.errors["gender"].map(error => {
                                return error + " ";
                              })
                            : null
                        }
                      />
                    )}
                  />
                </Grid>
                <Grid item md={6} xs={12}>
                  <TextField
                    id="email"
                    label="Email-Id"
                    name="email"
                    value={formState.values["email"] || ""}
                    variant="outlined"
                    required
                    fullWidth
                    onChange={handleChange}
                    error={hasError("email")}
                    helperText={
                      hasError("email")
                        ? formState.errors["email"].map(error => {
                            return error + " ";
                          })
                        : null
                    }
                  />
                </Grid>
              </Grid>
            </Grid>
            <Divider className={classes.divider} />
            <Grid item xs={12} md={6} xl={3}>
              <Grid container spacing={3} className={classes.formgrid}>
                <Grid item md={6} xs={12}>
                  <Autocomplete
                    id="college-filter"
                    className={classes.root}
                    options={collegelist}
                    disabled={formState.editStudent ? true : false}
                    getOptionLabel={option => option.name}
                    onChange={(event, value) => {
                      handleChangeAutoComplete("college", event, value);
                    }}
                    value={
                      collegelist[
                        collegelist.findIndex(function (item, i) {
                          return item.id === formState.values.college;
                        })
                      ] || null
                    }
                    renderInput={params => (
                      <TextField
                        {...params}
                        error={hasError("college")}
                        label="College"
                        variant="outlined"
                        required
                        name="tester"
                        helperText={
                          hasError("college")
                            ? formState.errors["college"].map(error => {
                                return error + " ";
                              })
                            : null
                        }
                      />
                    )}
                  />
                </Grid>
                <Grid item md={6} xs={12}>
                  <Autocomplete
                    id="stream-filter"
                    className={classes.root}
                    options={collegeStreamList || []}
                    disabled={formState.editStudent ? true : false}
                    getOptionLabel={option => option.name}
                    onChange={(event, value) => {
                      handleStreamChange("stream", event, value);
                    }}
                    value={stream || null}
                    renderInput={params => (
                      <TextField
                        {...params}
                        error={hasError("stream")}
                        label="Stream"
                        variant="outlined"
                        name="tester"
                        helperText={
                          hasError("stream")
                            ? formState.errors["stream"].map(error => {
                                return error + " ";
                              })
                            : null
                        }
                      />
                    )}
                  />
                </Grid>
              </Grid>
              <Grid container spacing={3} className={classes.formgrid}>
                <Grid item md={6} xs={12}>
                  <TextField
                    id="rollnumber"
                    label="Enrollment Number "
                    name="rollnumber"
                    value={formState.values["rollnumber"] || ""}
                    variant="outlined"
                    fullWidth
                    required
                    onChange={handleChange}
                    error={hasError("rollnumber")}
                    helperText={
                      hasError("rollnumber")
                        ? formState.errors["rollnumber"].map(error => {
                            return error + " ";
                          })
                        : null
                    }
                  />
                </Grid>
                <Grid item md={6} xs={12}>
                  <Autocomplete
                    id="physically-handicapped-id"
                    className={classes.root}
                    options={physicallyHandicappedlist}
                    getOptionLabel={option => option.name}
                    onChange={(event, value) => {
                      handleChangeAutoComplete(
                        "physicallyHandicapped",
                        event,
                        value
                      );
                    }}
                    value={
                      physicallyHandicappedlist[
                        physicallyHandicappedlist.findIndex(function (item, i) {
                          return (
                            item.id === formState.values.physicallyHandicapped
                          );
                        })
                      ] || null
                    }
                    renderInput={params => (
                      <TextField
                        {...params}
                        error={hasError("physicallyHandicapped")}
                        label="Physically Handicapped"
                        variant="outlined"
                        name="tester"
                        helperText={
                          hasError("physicallyHandicapped")
                            ? formState.errors["physicallyHandicapped"].map(
                                error => {
                                  return error + " ";
                                }
                              )
                            : null
                        }
                      />
                    )}
                  />
                </Grid>
              </Grid>
            </Grid>
            <Divider className={classes.divider} />
            <Grid item xs={12} md={6} xl={3}>
              <Grid container spacing={3} className={classes.MarginBottom}>
                <Grid item md={12} xs={12}>
                  <Autocomplete
                    multiple={true}
                    id="futureAspirations"
                    className={classes.root}
                    options={futureAspirationsList}
                    getOptionLabel={option => option.name}
                    onChange={(event, value) => {
                      handleFutureAspirationChange(
                        "futureAspirations",
                        event,
                        value
                      );
                    }}
                    value={formState.values.futureAspirations}
                    filterSelectedOptions={true}
                    renderInput={params => (
                      <TextField
                        {...params}
                        error={hasError("futureAspirations")}
                        label="Future Aspirations"
                        variant="outlined"
                        name="tester"
                        helperText={
                          hasError("futureAspirations")
                            ? formState.errors["futureAspirations"].map(
                                error => {
                                  return error + " ";
                                }
                              )
                            : null
                        }
                      />
                    )}
                  />
                </Grid>
              </Grid>
            </Grid>
            <Divider className={classes.divider} />
            <Grid item xs={12} md={6} xl={3}>
              <Grid container spacing={3} className={classes.formgrid}>
                <Grid item md={6} xs={12}>
                  <TextField
                    id="username"
                    label="Username"
                    name="username"
                    value={formState.values["username"] || ""}
                    variant="outlined"
                    required
                    fullWidth
                    disabled
                    readOnly
                    error={hasError("username")}
                    helperText={
                      hasError("username")
                        ? formState.errors["username"].map(error => {
                            return error + " ";
                          })
                        : null
                    }
                  />
                </Grid>

                {formState.editStudent ? null : (
                  <Grid item md={6} xs={12}>
                    <FormControl fullWidth variant="outlined">
                      <InputLabel
                        htmlFor="outlined-adornment-password"
                        fullWidth
                        error={hasError("password")}
                      >
                        Password
                      </InputLabel>
                      <OutlinedInput
                        id="password"
                        label="Password"
                        name="password"
                        type={formState.showPassword ? "text" : "password"}
                        value={formState.values["password"]}
                        required
                        fullWidth
                        onChange={handleChange}
                        error={hasError("password")}
                        helpertext={
                          hasError("password")
                            ? formState.errors["password"].map(error => {
                                return error + " ";
                              })
                            : null
                        }
                        endAdornment={
                          <InputAdornment
                            position="end"
                            error={hasError("password")}
                          >
                            <IconButton
                              aria-label="toggle password visibility"
                              onClick={handleClickShowPassword}
                              edge="end"
                            >
                              {formState.showPassword ? (
                                <Visibility />
                              ) : (
                                <VisibilityOff />
                              )}
                            </IconButton>
                          </InputAdornment>
                        }
                      />
                      <FormHelperText error={hasError("password")}>
                        {hasError("password")
                          ? formState.errors["password"].map(error => {
                              return error + " ";
                            })
                          : null}
                      </FormHelperText>
                    </FormControl>
                  </Grid>
                )}
              </Grid>
            </Grid>
            {formState.editStudent ? (
              <Grid item xs={12} className={classes.CardActionGrid}>
                <CardActions className={classes.btnspace}>
                  <Grid item xs={12}>
                    <Grid item xs={12} md={6} xl={3}>
                      <Grid container spacing={3}>
                        <Grid item md={2} xs={12}>
                          <YellowButton
                            color="primary"
                            type="submit"
                            id="submit"
                            mfullWidth
                            variant="contained"
                            style={{ marginRight: "18px" }}
                            onClick={handleSubmit}
                          >
                            <span>{genericConstants.SAVE_BUTTON_TEXT}</span>
                          </YellowButton>
                        </Grid>
                        <Grid item md={3} xs={12}>
                          <YellowButton
                            id="submitandnext"
                            color="primary"
                            type="submit"
                            mfullWidth
                            variant="contained"
                            style={{ marginRight: "18px" }}
                            onClick={saveAndNext}
                          >
                            <span>
                              {genericConstants.SAVE_AND_NEXT_BUTTON_TEXT}
                            </span>
                          </YellowButton>
                        </Grid>
                        <Grid item md={2} xs={12}>
                          <GrayButton
                            id="cancel"
                            color="primary"
                            type="submit"
                            mfullWidth
                            variant="contained"
                            onClick={() => {
                              auth.getUserInfo().role.name ===
                              roleConstants.COLLEGEADMIN
                                ? history.push(routeConstants.MANAGE_STUDENT)
                                : history.push(routeConstants.VIEW_PROFILE);
                            }}
                          >
                            <span>{genericConstants.CANCEL_BUTTON_TEXT}</span>
                          </GrayButton>
                        </Grid>
                      </Grid>
                    </Grid>
                  </Grid>
                </CardActions>
              </Grid>
            ) : (
              <Grid item md={12} xs={12} className={classes.CardActionGrid}>
                <CardActions className={classes.btnspace}>
                  <Grid item xs={12}>
                    <Grid item xs={12} md={6} xl={3}>
                      <Grid container spacing={3}>
                        <Grid item md={2} xs={12}>
                          <YellowButton
                            id="submit"
                            color="primary"
                            type="submit"
                            mfullWidth
                            variant="contained"
                            onClick={handleSubmit}
                          >
                            <span>{authPageConstants.REGISTER}</span>
                          </YellowButton>
                        </Grid>

                        <Grid item md={2} xs={12}>
                          <GrayButton
                            id="cancel"
                            color="primary"
                            type="submit"
                            mfullWidth
                            variant="contained"
                            onClick={() => {
                              history.push(routeConstants.SIGN_IN_URL);
                            }}
                          >
                            <span>{genericConstants.CANCEL_BUTTON_TEXT}</span>
                          </GrayButton>
                        </Grid>
                      </Grid>
                    </Grid>
                  </Grid>
                </CardActions>
              </Grid>
            )}
          </CardContent>
        </form>
      </Card>
      <Backdrop className={classes.backDrop} open={backDrop}>
        <CircularProgress color="inherit" />
      </Backdrop>
    </Grid>
    // </Layout>
  );
}
Example #19
Source File: RequestObjectItem.jsx    From mapstore2-cadastrapp with GNU General Public License v3.0 4 votes vote down vote up
/**
 * RequestObjectItem component
 * @param {object} props Component props
 * @param {function} props.setRequestFormData triggered when adding or updating request object's data
 * @param {object} props.requestFormData contains request form data
 * @param {id} props.dataId key/index of the request object
 * @param {string} props.value contains current request option value
 * @param {function} props.onDelete triggered when adding or deleting a request object
 * @param {function} props.onChange triggered when changing a request object
 * @param {function} props.setInValidField triggered when changing mandatory fields values
 * @param {bool} props.allow boolean variable to show restricted options
 */
export default function RequestObjectItem({
    setRequestFormData = () => {},
    requestFormData = {},
    dataId,
    value,
    onDelete = () => {},
    onChange = () => {},
    setInValidField = () => {},
    allow = false
}) {
    const requestOptions = [
        { value: 'owner-id', label: 'cadastrapp.demandeinformation.object.type.1' },
        { value: 'plot', label: 'cadastrapp.demandeinformation.object.type.2' },
        { value: 'co-owners', label: 'cadastrapp.demandeinformation.object.type.3' },
        { value: 'plot-id', label: 'cadastrapp.demandeinformation.object.type.5' },
        { value: 'owner', label: 'cadastrapp.demandeinformation.object.type.4', style: {display: allow ? 'block' : 'none'} },
        { value: 'owner-birth-name', label: 'cadastrapp.demandeinformation.object.type.7', style: {display: allow ? 'block' : 'none'} },
        { value: 'lot-co-owners', label: 'cadastrapp.demandeinformation.object.type.6', style: {display: allow ? 'block' : 'none'} }
    ];

    const [fieldName, setFieldName] = useState('');
    const [mandatoryFields, setMandatoryFields] = useState(0);

    const handleOnChange = ({target}) => {
        const {name, value: data} = target || {};
        setRequestFormData({...requestFormData, [fieldName]: {
            ...requestFormData[fieldName],
            [dataId]: {
                ...requestFormData[fieldName][dataId],
                ...(includes(['propStatement', 'parcelSlip'], name)
                    ? {[name]: target.checked}
                    : {[name]: data})
            }}
        });
    };

    const handleSelectChange = (name, v) => {
        let result;
        if (name === "commune" && isEmpty(v)) {
            result = { [dataId]: {} };
            setRequestFormData({...requestFormData,
                [fieldName]: { ...requestFormData[fieldName] }});
        } else {
            result = {
                [dataId]: {
                    ...requestFormData[fieldName][dataId],
                    [name]: {...v}
                }
            };
        }
        setRequestFormData({...requestFormData,
            [fieldName]: { ...requestFormData[fieldName], ...result}});
    };

    useEffect(()=>{
        const data = requestFormData?.[fieldName]?.[dataId] || [];
        const fieldEquality = Object.keys(data).filter(k => !isEmpty(data[k]) && !includes(['propStatement', 'parcelSlip'], k));
        const booleanFields = Object.keys(data).filter(k => data[k] === true);
        // Mandatory field validation
        let inValid = true;
        if (!isEmpty(data) && !isEmpty(mandatoryFields)) {
            if (isEqual(fieldEquality.sort(), mandatoryFields.sort())) {
                if (booleanFields.length > 0) {
                    inValid = false;
                }
            }
        }
        setInValidField(inValid);
    }, [requestFormData]);

    function ownerId() {
        return (
            <div>
                <FormControl
                    className="pull-left"
                    placeholder={"cadastrapp.demandeinformation.idCompteCom"}
                    name="accountId"
                    value={requestFormData?.[fieldName]?.[dataId]?.accountId || ''}
                    style={{ height: 34, width: 248, margin: 4 }}
                    onChange={handleOnChange}
                />
            </div>
        );
    }

    const plot = () => {
        return (
            <div>
                <div style={{display: 'flex', "float": "left", margin: 4}}>
                    <MunicipalityCombo
                        dropUp
                        placeholder={'cadastrapp.commune'}
                        additionalStyle={{width: 300, marginRight: 4}} value={requestFormData?.[fieldName]?.[dataId]?.commune?.label}
                        onSelect={v =>handleSelectChange("commune", v)}
                    />
                    <SectionCombo
                        cgocommune={requestFormData?.[fieldName]?.[dataId]?.commune?.cgocommune}
                        value={{section: requestFormData?.[fieldName]?.[dataId]?.section,
                            plot: isEmpty(requestFormData?.[fieldName]?.[dataId]?.plot) ? null : requestFormData?.[fieldName]?.[dataId]?.plot}}
                        onSelect={(c, v) =>handleSelectChange(c, v)}
                    />
                </div>
            </div>
        );
    };

    const coOwners = () => {
        return (
            <div style={{ width: "300" }}>
                <FormControl
                    placeholder={'cadastrapp.demandeinformation.idCompteCom'}
                    name="accountId"
                    value={requestFormData?.[fieldName]?.[dataId]?.accountId || ''}
                    className={cs("pull-left", "request-obj-double")}
                    onChange={handleOnChange}
                />
                <FormControl
                    placeholder={'cadastrapp.demandeinformation.idParcelle'}
                    name={"plotId"}
                    value={requestFormData?.[fieldName]?.[dataId]?.plotId || ''}
                    className={cs("pull-left", "request-obj-double")}
                    onChange={handleOnChange}
                />
            </div>
        );
    };

    const plotId = () => {
        return (
            <div>
                <FormControl
                    placeholder={'cadastrapp.demandeinformation.idCompteCom'}
                    name="accountId"
                    value={requestFormData?.[fieldName]?.[dataId]?.accountId || ''}
                    className={cs("pull-left", "request-obj-double")}
                    onChange={handleOnChange}
                />
            </div>
        );
    };

    const owner = () => {
        return (
            <div key="owner">
                <div style={{display: 'flex', "float": "left", margin: 4}}>
                    <MunicipalityCombo
                        dropUp
                        placeholder={'cadastrapp.commune'}
                        additionalStyle={{width: 300, marginRight: 4}}
                        value={requestFormData?.[fieldName]?.[dataId]?.commune?.label}
                        onSelect={v =>handleSelectChange("commune", v)}
                    />
                    <ProprietaireCombo
                        dropUp
                        placeholder={'cadastrapp.demandeinformation.proprietaire'}
                        disabled={isEmpty(requestFormData?.[fieldName]?.[dataId]?.commune)}
                        birthsearch={false}
                        cgocommune={requestFormData?.[fieldName]?.[dataId]?.commune?.cgocommune}
                        additionalStyle={{width: 300, marginRight: 4}}
                        value={requestFormData?.[fieldName]?.[dataId]?.proprietaire?.value}
                        onSelect={v =>handleSelectChange("proprietaire", v)}
                    />
                </div>
            </div>
        );
    };

    const cadastrappDemandei = () => {
        return (
            <div>
                <div style={{display: 'flex', "float": "left", margin: 4}}>
                    <MunicipalityCombo
                        dropUp
                        placeholder={'cadastrapp.commune'}
                        additionalStyle={{width: 300, marginRight: 4}}
                        value={requestFormData?.[fieldName]?.[dataId]?.commune?.label}
                        onSelect={v =>handleSelectChange("commune", v)}
                    />
                    <ProprietaireCombo
                        dropUp
                        placeholder={'cadastrapp.demandeinformation.proprietaire'}
                        disabled={isEmpty(requestFormData?.[fieldName]?.[dataId]?.commune)}
                        birthsearch
                        cgocommune={requestFormData?.[fieldName]?.[dataId]?.commune?.cgocommune}
                        additionalStyle={{width: 300, marginRight: 4}}
                        value={requestFormData?.[fieldName]?.[dataId]?.proprietaire?.value }
                        onSelect={v =>handleSelectChange("proprietaire", v)}
                    />
                </div>
            </div>
        );
    };

    const lotCoOwners = () => {
        return (
            <div>
                <div style={{display: 'flex', margin: 4}}>
                    <MunicipalityCombo
                        dropUp
                        placeholder={'cadastrapp.commune'}
                        additionalStyle={{marginRight: 4}}
                        value={requestFormData?.[fieldName]?.[dataId]?.commune?.label}
                        onSelect={v =>handleSelectChange("commune", v)}
                    />
                    <SectionCombo
                        cgocommune={requestFormData?.[fieldName]?.[dataId]?.commune?.cgocommune}
                        value={{section: requestFormData?.[fieldName]?.[dataId]?.section,
                            plot: isEmpty(requestFormData?.[fieldName]?.[dataId]?.plot) ? null : requestFormData?.[fieldName]?.[dataId]?.plot}}
                        onSelect={(c, v) =>handleSelectChange(c, v)}/>

                    <ProprietaireComboList
                        placeholder={'cadastrapp.demandeinformation.proprietaire'}
                        disabled={isEmpty(requestFormData?.[fieldName]?.[dataId]?.plot)}
                        section={requestFormData?.[fieldName]?.[dataId]?.section?.ccosec}
                        numero={requestFormData?.[fieldName]?.[dataId]?.section?.plot?.dnupla}
                        commune={requestFormData?.[fieldName]?.[dataId]?.commune?.cgocommune}
                        onSelect={v =>handleSelectChange("proprietaire", v)}
                    />
                </div>
            </div>
        );
    };

    const inputTemplate = () => <div/>;
    const [compRender, setCompRender] = useState(inputTemplate);

    useEffect(()=>{
        switch (value) {
        case "owner-id":
            setFieldName("comptecommunaux");
            setMandatoryFields(["accountId"]);
            setCompRender(ownerId);
            break;
        case "plot":
            setFieldName("parcelles");
            setMandatoryFields(["commune", "section", "plot"]);
            setCompRender(plot);
            break;
        case "co-owners":
            setFieldName("coproprietes");
            setMandatoryFields(["accountId", "plotId"]);
            setCompRender(coOwners);
            break;
        case "plot-id":
            setFieldName("parcelleIds");
            setMandatoryFields(["accountId"]);
            setCompRender(plotId);
            break;
        case "owner":
            setFieldName("proprietaires");
            setMandatoryFields(["commune", "proprietaire"]);
            setCompRender(owner);
            break;
        case "owner-birth-name":
            setFieldName("proprietaires");
            setMandatoryFields(["commune", "proprietaire"]);
            setCompRender(cadastrappDemandei);
            break;
        case "lot-co-owners":
            setFieldName("proprietaireLots");
            setMandatoryFields(["commune", "section", "numero", "proprietaire"]);
            setCompRender(lotCoOwners);
            break;
        default: break;
        }
    }, [value, requestFormData, fieldName, allow, dataId]);

    let handleDelete = () => {
        onDelete(dataId);
        delete requestFormData?.[fieldName]?.[dataId];
        setRequestFormData({...requestFormData});
    };

    const handleChange = (item) => {
        onChange(dataId, item.value);
    };

    return (
        <div className="pull-left" style={{ width: "100%" }}>
            <div className={"request-obj-triple"}>
                <RequestSelect
                    className={"drop-up"}
                    options={requestOptions}
                    value={value}
                    onChange={handleChange}
                />
            </div>
            {compRender}
            <Button className="pull-right" onClick={handleDelete} style={{ margin: 4 }}>
                <Glyphicon glyph="trash"/>
            </Button>
            {!isEmpty(fieldName) && <RequestItemsCheckboxes
                handleOnChange={handleOnChange}
                requestFormData={requestFormData?.[fieldName]?.[dataId] || {}}
            />}
        </div>
    );
}
Example #20
Source File: Request.jsx    From mapstore2-cadastrapp with GNU General Public License v3.0 4 votes vote down vote up
export default function RequestFormModal({
    onClose = () => {},
    isShown = false,
    authLevel = {},
    maxRequest = DEFAULT_MAX_REQUEST,
    ...props
}) {

    // Auth level of the user
    const isCNIL = authLevel.isCNIL2 || authLevel.isCNIL1;

    const USER_TYPE_OPTIONS = [
        { value: 'A', label: 'cadastrapp.demandeinformation.type.A'},
        { value: 'P1', label: 'cadastrapp.demandeinformation.type.P1' },
        { value: 'P2', label: 'cadastrapp.demandeinformation.type.P2' },
        { value: 'P3', label: 'cadastrapp.demandeinformation.type.P3' }
    ];

    const [showReqByFields, setShowReqByFields] = useState(false);
    const [showRequestObj, setShowRequestObj] = useState(false);
    const [requestFormData, setRequestFormData] = useState(DEFAULT_REQUEST_OBJ);
    const [inValidField, setInValidField] = useState(true);
    const [availableRequest, setAvailableRequest] = useState(+maxRequest);
    const [checkingLimit, setCheckingLimit] = useState(false);

    useEffect(()=>{
        const {type, lastname, cni} = requestFormData;
        const isNotNormalUser = !isEmpty(type) && type !== "P3";  // P3 is normal user
        const isValidNormalUser = !isEmpty(cni) && type === "P3";

        setShowReqByFields(isNotNormalUser || isValidNormalUser); // Show/hide requestBy fields
        setShowRequestObj((isNotNormalUser && !!lastname.length) || isValidNormalUser); // Show/hide request object fields
    }, [requestFormData.cni, requestFormData.type, requestFormData.lastname]);

    // Check request limit based cni and type and set available request
    const checkRequestLimit = ({cni, type}) => {
        setCheckingLimit(true);
        checkRequestLimitation({cni, type}).then((data)=> {
            if (data.user) {
                // Use the fetched user data to populate the request form field
                setRequestFormData({
                    ...requestFormData, ...data.user,
                    firstname: data.user?.firstName || '',
                    lastname: data.user?.lastName || '',
                    codepostal: data.user?.codePostal || ''
                });
            }
            // Set available requests from the response, else set max request from configuration
            data.requestAvailable || data.requestAvailable === 0 ? setAvailableRequest(+data.requestAvailable) : setAvailableRequest(+maxRequest);
            setCheckingLimit(false);
        }).catch(()=>{
            setAvailableRequest(0);
            props.onError({
                title: "Error",
                message: "cadastrapp.demandeinformation.availableReqError"
            });
            setCheckingLimit(false);
        });
    };

    const [printRequest, setPrintRequest] = useState({});

    useEffect(() => {
        // Generate print params from form data
        setPrintRequest(formulatePrintParams(requestFormData));
    }, [requestFormData]);

    const onChange = (item) => {
        let formObj;
        if (item.value) {
            formObj = {...DEFAULT_REQUEST_OBJ, type: item.value};
        } else {
            const {name = '', value = ''} = item?.target || {};
            formObj = {...requestFormData, [name]: includes(['askby', 'responseby'], name) ? +value : value};
            name === "cni" && setCheckingLimit(true); // Set flag when checking for request limit
        }
        setRequestFormData(formObj);
    };

    const onBlur = ({target}) => {
        const {name = '', value = ''} = target || {};
        const trimmedValue = value.trim();
        setRequestFormData({...requestFormData, [name]: trimmedValue});

        // Trigger check request limit call
        if (name === "cni" && !isEmpty(requestFormData.type) && !isEmpty(trimmedValue) && trimmedValue.length > 2) {
            checkRequestLimit(requestFormData);
        }
    };

    const onCloseForm = () => { onClose(); setRequestFormData(DEFAULT_REQUEST_OBJ); setAvailableRequest(DEFAULT_MAX_REQUEST);};

    const formFields = [
        {
            value: requestFormData.cni,
            name: 'cni',
            label: <Message msgId={"cadastrapp.demandeinformation.cni"}/>,
            validation: requestFormData.type === 'P3' && isEmpty(requestFormData.cni) && "error"
        },
        {
            value: requestFormData.lastname,
            name: 'lastname',
            label: <Message msgId={"cadastrapp.demandeinformation.nom"}/>,
            validation: !isEmpty(requestFormData.type) && requestFormData.type !== 'P3' && isEmpty(requestFormData.lastname) && "error"
        },
        {
            value: requestFormData.firstname,
            name: 'firstname',
            label: <Message msgId={"cadastrapp.demandeinformation.prenom"}/>
        },
        {
            value: requestFormData.adress,
            name: 'adress',
            label: <Message msgId={"cadastrapp.demandeinformation.num_rue"}/>
        },
        {
            value: requestFormData.codepostal,
            name: 'codepostal',
            label: <Message msgId={"cadastrapp.demandeinformation.code_postal"}/>
        },
        {
            value: requestFormData.commune,
            name: 'commune',
            label: <Message msgId={"cadastrapp.demandeinformation.commune"}/>
        },
        {
            value: requestFormData.mail,
            name: 'mail',
            type: 'email',
            label: <Message msgId={"cadastrapp.demandeinformation.mail"}/>,
            validation: !isEmpty(requestFormData.mail) && !isValidEmail(requestFormData.mail) && "error"
        }
    ];

    const radioButtonGroup = {
        groupLabel: [
            {label: <Message msgId={"cadastrapp.demandeinformation.realise"}/>, name: 'askby' },
            {label: <Message msgId={"cadastrapp.demandeinformation.transmission"}/>, name: 'responseby'}
        ],
        groupField: [
            <Message msgId={"cadastrapp.demandeinformation.counter"}/>,
            <Message msgId={"cadastrapp.demandeinformation.mail"}/>,
            <Message msgId={"cadastrapp.demandeinformation.email"}/>
        ]
    };

    return (
        <Modal
            dialogClassName="cadastrapp-modal"
            show={isShown} onHide={onCloseForm}>
            <Modal.Header closeButton>
                <Modal.Title><Message msgId={'cadastrapp.demandeinformation.title'}/></Modal.Title>
            </Modal.Header>
            <Modal.Body className="request-modal-body">
                <div className="item-row">
                    <div className="label-col">
                        <ControlLabel><Message msgId={'cadastrapp.demandeinformation.type.demandeur'}/></ControlLabel>
                    </div>
                    <div className="form-col">
                        <Select name="type" value={requestFormData.type} onChange={onChange} options={USER_TYPE_OPTIONS}/>
                    </div>
                </div>
                {
                    formFields.map(({label, name, value, type = "text", validation = null}, index)=> (
                        <div className="item-row" key={index}>
                            <FormGroup validationState={validation}>
                                <div className="label-col">
                                    <ControlLabel>{label}</ControlLabel>
                                </div>
                                <div className="form-col">
                                    <FormControl
                                        disabled={isEmpty(requestFormData.type) || (name !== "cni" && requestFormData.type === 'P3' && isEmpty(requestFormData.cni))}
                                        value={value} name={name} onBlur={onBlur} onChange={onChange} type={type}
                                        bsSize="sm"
                                    />
                                </div>
                            </FormGroup>
                        </div>
                    ))
                }
                {
                    showReqByFields && radioButtonGroup.groupLabel.map(({label, name})=> (
                        <div className={"item-row"}>
                            <div className="label-col">
                                <ControlLabel>{label}</ControlLabel>
                            </div>
                            <div className="form-col">
                                <FormGroup>
                                    {radioButtonGroup.groupField.map((fieldLabel, index)=>
                                        <Radio onChange={onChange} checked={requestFormData[name] === index + 1} value={index + 1}  name={name} inline>
                                            {fieldLabel}
                                        </Radio>)}
                                </FormGroup>
                            </div>
                        </div>
                    ))
                }
                <hr/>
                {showRequestObj && !checkingLimit && <div className={"item-row"}>
                    <div className="request-obj-label">
                        <ControlLabel><Message msgId={"cadastrapp.demandeinformation.titre2"}/></ControlLabel>
                    </div>
                    <RequestObject
                        allow={isCNIL}
                        requestFormData={requestFormData}
                        setInValidField={setInValidField}
                        setRequestFormData={setRequestFormData}
                        setAvailableRequest={setAvailableRequest}
                        availableRequest={availableRequest}
                    />
                </div>
                }
            </Modal.Body>
            <Modal.Footer>
                <Button onClick={onCloseForm}><Message msgId={'cadastrapp.demandeinformation.annuler'}/></Button>
                <Button
                    disabled={!showRequestObj || checkingLimit || inValidField || props.loading}
                    onClick={()=>props.onPrintPDF(printRequest)}
                    className="print"
                >
                    {!props.allowDocument && props.loading ? (
                        <Spinner
                            spinnerName="circle"
                            noFadeIn
                            overrideSpinnerClassName="spinner"
                        />
                    ) : null}
                    <Message msgId={'cadastrapp.demandeinformation.imprimer'}/>
                </Button>
                <Button
                    disabled={isCNIL ? !props.allowDocument : true}
                    onClick={()=>props.onPrintPDF(null, 'Document')}
                    className="print"
                >
                    {props.allowDocument && props.loading ? (
                        <Spinner
                            spinnerName="circle"
                            noFadeIn
                            overrideSpinnerClassName="spinner"
                        />
                    ) : null}
                    <Message msgId={'cadastrapp.demandeinformation.generate.document'}/>
                </Button>
            </Modal.Footer>
        </Modal>);
}
Example #21
Source File: Inspector.js    From gutenberg-forms with GNU General Public License v2.0 4 votes vote down vote up
function Inspector(prop) {
	const props = prop.data;

	const {
		buttonSetting,
		email,
		successURL,
		successType,
		messages,
		successMessage,
		templateBuilder,
		theme,
		formType,
		hideFormOnSuccess,
		formLabel,
		cpt,
		saveToEntries,
		sendEmail,
		actions,
		spamProtections,
		buttonStyling,
		spamMessage,
		errorMessage,
		customAction
	} = props.attributes;

	const handleAlignment = (aln) => {
		props.setAttributes({
			buttonSetting: {
				...buttonSetting,
				alignment: aln,
			},
		});
	};

	const getAlignmentProps = (aln) => {
		if (buttonSetting.alignment === aln)
			return {
				isPrimary: true,
			};

		return {
			isDefault: true,
		};
	};

	const handleButtonSetting = (t, v) => {
		props.setAttributes({
			buttonSetting: {
				...buttonSetting,
				[t]: v,
			},
		});
	};

	const getSuccess = (t) => {
		return successType === t
			? {
					isPrimary: true,
			  }
			: {
					isDefault: true,
			  };
	};

	const handleMessagesChange = (t, v, i, fieldName) => {
		let newMessages = clone(messages);

		newMessages[i] = {
			...newMessages[i],
			[t]: v,
		};
		props.setAttributes({ messages: newMessages });
		changeChildValue(fieldName, props.clientId, newMessages[i], t, messages);
	};

	const handleStyling = (style, key) => {
		const themeStyling = clone(theme);

		set(themeStyling, key, style); //changing the color;

		props.setAttributes({ theme: themeStyling });
	};

	const handleProtection = (protection) => {
		const enabled = hasObject(spamProtections, protection);

		if (enabled === false) {
			const newProtections = clone(spamProtections);
			newProtections.push(protection);
			props.setAttributes({ spamProtections: newProtections });
		} else {
			const newProtections = clone(spamProtections);
			let disabled = newProtections.filter((p) => !isEqual(p, protection));

			props.setAttributes({ spamProtections: disabled });
		}
	};

	const handleButtonStyling = (v, t) => {
		const newStyling = clone(buttonStyling);

		set(newStyling, t, v);

		props.setAttributes({ buttonStyling: newStyling });
	};

	const handleActions = (actions) => {
		// only update actions of integrations that are available
		const globalIntegrations = get(window, "cwpGlobal.settings.integrations");
		const integrations_titles = map(globalIntegrations, "title");
		let isCurrentActionSupported = true;

		actions.forEach((action) => {
			const exceptionalCases = ["Record Entries", "Email Notification"];

			if (
				!includes(integrations_titles, action) &&
				!includes(exceptionalCases, action)
			) {
				isCurrentActionSupported = false;
			}
		});

		if (isCurrentActionSupported) {
			props.setAttributes({ actions });
		}
	};

	return (
		<InspectorControls>
			<PanelBody initialOpen={false} title={__("Form Design", "cwp-gutenberg-forms")}>
				<div className="cwp-option">
					<h3 className="cwp-heading">{__("Accent Color", "cwp-gutenberg-forms")}</h3>
					<ColorPalette
						colors={basicColorScheme}
						value={theme.accentColor}
						onChange={(color) => handleStyling(color, "accentColor")}
					/>
				</div>
				<div className="cwp-option">
					<h3 className="cwp-heading">{__("Text Color", "cwp-gutenberg-forms")}</h3>
					<ColorPalette
						colors={basicColorScheme}
						value={theme.textColor}
						onChange={(color) => handleStyling(color, "textColor")}
					/>
				</div>
				<div className="cwp-option">
					<h3 className="cwp-heading">
						{__("Field Background Color", "cwp-gutenberg-forms")}
					</h3>
					<ColorPalette
						colors={basicColorScheme}
						value={theme.fieldBackgroundColor}
						onChange={(color) => handleStyling(color, "fieldBackgroundColor")}
					/>
				</div>
				<div className="cwp-option">
					<h3 className="cwp-heading">
						{__("Button Background Color", "cwp-gutenberg-forms")}
					</h3>
					<ColorPalette
						value={buttonStyling.backgroundColor}
						onChange={(newbg) => handleButtonStyling(newbg, "backgroundColor")}
						colors={basicColorScheme}
					/>
				</div>
			</PanelBody>

			<PanelBody initialOpen={true} title={__("General", "cwp-gutenberg-forms")}>
				<TextControl
					disabled
					label={__("Form Label", "cwp-gutenberg-forms")}
					value={formLabel}
					onChange={(formLabel) => props.setAttributes({ formLabel })}
				/>

				{formType !== "multiStep" && (
					<div className="cwp-option">
						<PanelRow>
							<h3>{__("Disable Submit Button", "cwp-gutenberg-forms")}</h3>
							<FormToggle
								checked={buttonSetting.disable}
								onChange={() =>
									handleButtonSetting("disable", !buttonSetting.disable)
								}
							/>
						</PanelRow>
					</div>
				)}
				{!buttonSetting.disable && (
					<Fragment>
						<div className="cwp-option column">
							<h3 className="cwp-heading">
								{__("Button Alignment", "cwp-gutenberg-forms")}
							</h3>
							<div className="cwp-column">
								<ButtonGroup>
									<Button
										{...getAlignmentProps("justify-start")}
										onClick={() => handleAlignment("justify-start")}
									>
										<Icon icon="editor-alignleft" />
									</Button>
									<Button
										{...getAlignmentProps("justify-center")}
										onClick={() => handleAlignment("justify-center")}
									>
										<Icon icon="editor-aligncenter" />
									</Button>
									<Button
										{...getAlignmentProps("justify-end")}
										onClick={() => handleAlignment("justify-end")}
									>
										<Icon icon="editor-alignright" />
									</Button>
								</ButtonGroup>
							</div>
						</div>
					</Fragment>
				)}
				<div className="cwp-option column">
					<h3>{__("Confirmation Type", "cwp-gutenberg-forms")}</h3>
					<div className="cwp-column">
						<ButtonGroup>
							<Button
								{...getSuccess("url")}
								onClick={() => props.setAttributes({ successType: "url" })}
							>
								{__("URL", "cwp-gutenberg-forms")}
							</Button>
							<Button
								{...getSuccess("message")}
								onClick={() => props.setAttributes({ successType: "message" })}
							>
								{__("Message", "cwp-gutenberg-forms")}
							</Button>
						</ButtonGroup>
					</div>
				</div>
				<div className="cwp-option">
					{successType === "url" ? (
						<TextControl
							label={__("Success Url (Redirect)", "cwp-gutenberg-forms")}
							value={successURL}
							onChange={(successURL) => props.setAttributes({ successURL })}
						/>
					) : (
						<Fragment>
							<TextareaControl
								label={__("Success Message", "cwp-gutenberg-forms")}
								value={successMessage}
								onChange={(successMessage) =>
									props.setAttributes({ successMessage })
								}
							/>
							<TextareaControl
								label={__("Spam Message", "cwp-gutenberg-forms")}
								value={spamMessage}
								onChange={(spamMessage) => props.setAttributes({ spamMessage })}
							/>
							<TextareaControl
								label={__("Error Message", "cwp-gutenberg-forms")}
								value={errorMessage}
								onChange={(errorMessage) =>
									props.setAttributes({ errorMessage })
								}
							/>
						</Fragment>
					)}
				</div>
				{successType === "message" && (
					<div className="cwp-option">
						<PanelRow>
							<h3>{__("Hide Form On Success", "cwp-gutenberg-forms")}</h3>
							<FormToggle
								checked={hideFormOnSuccess}
								onChange={() =>
									props.setAttributes({ hideFormOnSuccess: !hideFormOnSuccess })
								}
							/>
						</PanelRow>
					</div>
				)}
			</PanelBody>

			{actions.includes("Email Notification") && (
				<PanelBody title={__("Email Notification", "cwp-gutenberg-forms")}>
					<TemplateBuilder clientId={props.clientId} data={props} />
				</PanelBody>
			)}

			<PanelBody title={__("Form Action", "cwp-gutenberg-forms")}>
				<FormTokenField
					value={actions}
					onChange={handleActions}
					suggestions={get_form_actions()}
				/>
				<TextControl
					label={__("Custom Form Action Name", "cwp-gutenberg-forms")}
					value={customAction}
					onChange={(customAction) => props.setAttributes({ customAction })}
				/>
			</PanelBody>

			{!isEmpty(get_spam_protectors()) && (
				<PanelBody title={__("Spam Protection", "cwp-gutenberg-forms")}>
					{get_spam_protectors().map((protection) => {
						const isEnabled = hasObject(spamProtections, protection);

						return (
							<div className="cwp-option">
								<PanelRow>
									<h3>{protection.title}</h3>
									<FormToggle
										value={isEnabled}
										checked={isEnabled}
										onChange={() => handleProtection(protection)}
									/>
								</PanelRow>
							</div>
						);
					})}
				</PanelBody>
			)}

			<PanelBody initialOpen={false} title={__("Messages", "cwp-gutenberg-forms")}>
				<div className="cwp-option">
					<p>
						<Icon icon="info" />{" "}
						{__(
							"You can edit validations messages used for various field types here. Use {{ value }} to insert field value.",
							"cwp-gutenberg-forms"
						)}
					</p>
				</div>
				<MappedMessages val={messages} onChange={handleMessagesChange} />
			</PanelBody>
			<Integrations data={props} clientId={props.clientId} />
		</InspectorControls>
	);
}