lodash#isObject JavaScript Examples

The following examples show how to use lodash#isObject. 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: utils.js    From hzero-front with Apache License 2.0 7 votes vote down vote up
export function getQueryFields(dataSet) {
  const {
    props: { queryFields },
  } = dataSet;
  const queryDataSet = dataSet.queryDataSet || dataSet.props.queryDataSet;
  const result = [];
  if (queryDataSet) {
    const fields = queryDataSet.fields || queryDataSet.props.fields;
    return [...fields.entries()].reduce((list, [name, field]) => {
      if (!field.get('bind')) {
        const props = {
          key: name,
          name,
          dataSet: queryDataSet,
        };
        const element = queryFields[name];
        list.push(
          isValidElement(element)
            ? cloneElement(element, props)
            : cloneElement(getEditorByField(field), {
                ...props,
                ...(isObject(element) ? element : {}),
              })
        );
      }
      return list;
    }, result);
  }
  return result;
}
Example #2
Source File: normalizeOrderBy.js    From rate-repository-api with MIT License 6 votes vote down vote up
normalizeOrderByItem = item => {
  if (isString(item)) {
    return { column: item, order: 'asc' };
  }

  if (isObject(item) && isString(item.column)) {
    const { column, order = 'asc' } = item;

    return { column, order: order.toLowerCase() };
  }

  throw new Error('Order by item must be a string or an object');
}
Example #3
Source File: UploadExcel.js    From hzero-front with Apache License 2.0 6 votes vote down vote up
function isJSON(str) {
  let result;
  try {
    result = JSON.parse(str);
  } catch (e) {
    return false;
  }
  return isObject(result) && !isString(result);
}
Example #4
Source File: AvatarUploadModal.js    From hzero-front with Apache License 2.0 6 votes vote down vote up
function isJSON(str) {
  let result;
  try {
    result = JSON.parse(str);
  } catch (e) {
    return false;
  }
  return isObject(result) && !isString(result);
}
Example #5
Source File: index.js    From hzero-front with Apache License 2.0 6 votes vote down vote up
function isJSON(str) {
  let result;
  try {
    result = JSON.parse(str);
  } catch (e) {
    return false;
  }
  return isObject(result) && !isString(result);
}
Example #6
Source File: index.js    From hzero-front with Apache License 2.0 6 votes vote down vote up
function isJSON(str) {
  let result;
  try {
    result = JSON.parse(str);
  } catch (e) {
    return false;
  }
  return isObject(result) && !isString(result);
}
Example #7
Source File: Drawer.js    From hzero-front with Apache License 2.0 6 votes vote down vote up
function isJSON(str) {
  let result;
  try {
    result = JSON.parse(str);
  } catch (e) {
    return false;
  }
  return isObject(result) && !isString(result);
}
Example #8
Source File: UploadButton.js    From hzero-front with Apache License 2.0 6 votes vote down vote up
@Bind()
  uploadData(file) {
    const {
      attachmentUUID,
      bucketName,
      uploadData,
      bucketDirectory,
      docType,
      storageCode, // 存储配置编码
    } = this.props;
    let data = uploadData ? uploadData(file) : {};
    if (!(data instanceof FormData)) {
      const currentData = data;
      data = new FormData();
      if (isObject(data)) {
        Object.keys(currentData).forEach((paramKey) => {
          data.append(paramKey, currentData[paramKey]);
        });
      }
    }
    if (!isUndefined(attachmentUUID)) {
      data.append('attachmentUUID', attachmentUUID);
    }
    if (!isUndefined(bucketName)) {
      data.append('bucketName', bucketName);
    }
    if (!isUndefined(docType)) {
      data.append('docType', docType);
    }
    if (!isUndefined(storageCode)) {
      data.append('storageCode', storageCode);
    }
    if (!isUndefined(bucketDirectory)) {
      data.append('directory', bucketDirectory);
    }
    // data.append('fileName', file.name);
    return data;
  }
Example #9
Source File: ConditionDataSet.js    From hzero-front with Apache License 2.0 6 votes vote down vote up
/**
 * 字段改变事件
 * @param record
 * @param name
 * @param value
 * @param fieldArr
 */
async function handleFieldChange({ record, name, value }, fieldArr) {
  const { defaultValue, lovCode } =
    fieldArr.find(field => field.value === record.get('fieldName')) || {};

  if (name === 'fieldName') {
    record.set('comparator', '');
    record.set('value', undefined);
    map(fieldArr, field => {
      if (value === field.value) {
        record.getField('comparator').set(
          'options',
          new DataSet({
            selection: 'single',
            data: OPERATOR_TYPE[field.type.toUpperCase()],
          })
        );
      }
    });
  }
  if (name === 'comparator') {
    if (value && value.indexOf('NULL') !== -1) {
      record.set('value', undefined);
    } else if (defaultValue) {
      record.set('value', defaultValue);
    }
  }
  if (name === 'value' && isObject(value) && lovCode) {
    const lovValue = await findLovParam(fieldArr, record.get('fieldName'), value);
    record.set('value', lovValue);
  }
}
Example #10
Source File: difference.js    From iceberg-editor with GNU General Public License v2.0 6 votes vote down vote up
difference = ( object, base ) => {
	/* eslint-disable no-shadow */
	function changes( object, base ) {
		return transform( object, function( result, value, key ) {
			if ( ! isEqual( value, base[ key ] ) ) {
				result[ key ] =
					isObject( value ) && isObject( base[ key ] )
						? changes( value, base[ key ] )
						: value;
			}
		} );
	}
	return changes( object, base );
}
Example #11
Source File: checkStore.js    From hackchat-client with Do What The F*ck You Want To Public License 6 votes vote down vote up
/**
 * Check store object integrity and emit error if invalid
 * @param store Redux store instance
 */
export default function checkStore(store) {
  const shape = {
    dispatch: isFunction,
    subscribe: isFunction,
    getState: isFunction,
    replaceReducer: isFunction,
    runSaga: isFunction,
    injectedReducers: isObject,
    injectedSagas: isObject,
  };

  invariant(
    conformsTo(store, shape),
    '(app/utils...) injectors: Expected a valid redux store',
  );
}
Example #12
Source File: checkStore.js    From QiskitFlow with Apache License 2.0 6 votes vote down vote up
/**
 * Validate the shape of redux store
 */
export default function checkStore(store) {
  const shape = {
    dispatch: isFunction,
    subscribe: isFunction,
    getState: isFunction,
    replaceReducer: isFunction,
    runSaga: isFunction,
    injectedReducers: isObject,
    injectedSagas: isObject,
  };
  invariant(
    conformsTo(store, shape),
    '(app/utils...) injectors: Expected a valid redux store',
  );
}
Example #13
Source File: index.js    From datapass with GNU Affero General Public License v3.0 6 votes vote down vote up
getStateFromUrlParams = (defaultState = {}) => {
  const urlParams = new URLSearchParams(window.location.search);

  return mapValues(defaultState, (value, key) => {
    if (!urlParams.has(key)) {
      return value;
    }

    const param = urlParams.getAll(key);

    if (isObject(value)) {
      return JSON.parse(param[0]);
    }

    if (isInteger(value)) {
      return parseInt(param[0]) || value;
    }

    if (isBoolean(value)) {
      return param[0] === 'true';
    }

    return param[0];
  });
}
Example #14
Source File: index.js    From datapass with GNU Affero General Public License v3.0 6 votes vote down vote up
flattenDiffTransformerV2Factory =
  (keyPrefix = null) =>
  (accumulatorObject, objectValue, objectKey) => {
    const key = [keyPrefix, objectKey].filter((e) => e).join('.');

    if (isArray(objectValue)) {
      accumulatorObject[key] = objectValue;
    }

    // { scope: { nom: [false, true] } }
    if (isObject(objectValue)) {
      transform(
        objectValue,
        flattenDiffTransformerV2Factory(key),
        accumulatorObject
      );
    }

    return accumulatorObject;
  }
Example #15
Source File: index.js    From datapass with GNU Affero General Public License v3.0 6 votes vote down vote up
export function hashToQueryParams(hash, initialSearchParams) {
  const urlParams = new URLSearchParams(initialSearchParams);

  forOwn(hash, (value, key) =>
    urlParams.set(key, isObject(value) ? JSON.stringify(value) : value)
  );

  forOwn(hash, (value, key) => {
    if (isObject(value) ? isEmpty(value) : !value) {
      urlParams.delete(key);
    }
  });

  return isEmpty(urlParams.toString()) ? '' : `?${urlParams.toString()}`;
}
Example #16
Source File: index.js    From datapass with GNU Affero General Public License v3.0 6 votes vote down vote up
function flattenDiffTransformer(accumulatorObject, fullObjectDiff, objectKey) {
  if (!isObject(fullObjectDiff[0])) {
    accumulatorObject[objectKey] = fullObjectDiff;

    return accumulatorObject;
  }
  // {contacts: [[{'name': 'c', email: 'd', work_email: 'a'}], [{'name': 'e', email: 'd'}]]}
  const objectBefore = flatten(fullObjectDiff[0], objectKey);
  const objectAfter = flatten(fullObjectDiff[1], objectKey);
  const objectDiff = mergeWith(
    objectBefore,
    objectAfter,
    (valueBefore, valueAfter) => [valueBefore, valueAfter]
  );
  // {0.name: ['c', 'e'], 0.email: ['d', 'd'], 0.work_email: 'a'}
  const objectDiffNoUnchangedNoDeprecated = omitBy(
    objectDiff,
    (value) => !isArray(value) || value[0] === value[1]
  );
  // {0.name: ['c', 'e']}
  const objectDiffPrefixedKey = mapKeys(
    objectDiffNoUnchangedNoDeprecated,
    (value, flatKey) => `${objectKey}.${flatKey}`
  );
  // {contacts.0.name: ['c', 'e']}
  Object.assign(accumulatorObject, objectDiffPrefixedKey);

  return accumulatorObject;
}
Example #17
Source File: index.js    From datapass with GNU Affero General Public License v3.0 6 votes vote down vote up
export function getErrorMessages(error) {
  if (!isEmpty(error.response) && isObject(error.response.data)) {
    return chain(error.response.data).values().flatten().value();
  }

  const errorMessageEnd =
    'Merci de réessayer ultérieurement. ' +
    'Vous pouvez également nous signaler cette erreur par mail à [email protected].';

  if (!isEmpty(error.response) && error.message !== 'Network Error') {
    return [
      `Une erreur est survenue. Le code de l’erreur est ${error.response.status} (${error.response.statusText}). ${errorMessageEnd}`,
    ];
  }

  if (error.message === 'Network Error') {
    return [
      'Une erreur de connexion au serveur est survenue. ' +
        'Merci de vérifier que vous êtes bien connecté à internet. ' +
        'Si vous utilisez un réseau d’entreprise, merci de signaler cette erreur à ' +
        'l’administrateur de votre réseau informatique. ' +
        'Si le problème persiste, vous pouvez nous contacter par mail à ' +
        '[email protected].',
    ];
  }

  console.error(error);
  return [`Une erreur inconnue est survenue. ${errorMessageEnd}`];
}
Example #18
Source File: enrollmentReducer.js    From datapass with GNU Affero General Public License v3.0 6 votes vote down vote up
enrollmentReducerFactory =
  (demarches = null) =>
  (previousEnrollment, eventOrFutureEnrollment) => {
    if (!isObject(eventOrFutureEnrollment)) {
      return previousEnrollment;
    }

    // if no eventOrFutureEnrollment.target, this is a direct state update (network for instance)
    // a direct state update DOES NOT trigger a pre-filled demarche update
    if (!eventOrFutureEnrollment.target) {
      const futureEnrollment = eventOrFutureEnrollment;

      return globalUpdate({ previousEnrollment, futureEnrollment });
    }

    // if eventOrFutureEnrollment.target, it means reducer was trigger by an html element (input, select etc.)
    const event = eventOrFutureEnrollment;
    return eventUpdateFactory(demarches)({
      previousEnrollment,
      event,
    });
  }
Example #19
Source File: Mappers.js    From sampo-ui with MIT License 6 votes vote down vote up
merger = (a, b) => {
  if (isEqual(a, b)) {
    return a
  }
  if (a && !b) {
    return a
  }
  if (b && !a) {
    return b
  }
  if (isArray(a)) {
    if (isArray(b)) {
      b.forEach(function (bVal) {
        return mergeValueToList(a, bVal)
      })
      return a
    }
    return mergeValueToList(a, b)
  }
  if (isArray(b)) {
    return mergeValueToList(b, a)
  }
  if (!(isObject(a) && isObject(b) && a.id === b.id)) {
    return [a, b]
  }
  return mergeObjects(a, b)
}
Example #20
Source File: Mappers.js    From sampo-ui with MIT License 6 votes vote down vote up
mergeValueToList = (valueList, value) => {
  let old
  if (isObject(value) && value.id) {
    // Check if this object has been constructed earlier
    old = findLast(valueList, function (e) {
      return e.id === value.id
    })
    if (old) {
      // Merge this object to the object constructed earlier
      mergeObjects(old, value)
    }
  } else {
    // Check if this value is present in the list
    old = findLast(valueList, function (e) {
      return isEqual(e, value)
    })
  }
  if (!old) {
    // This is a distinct value
    valueList.push(value)
  }
  return valueList
}
Example #21
Source File: Item.jsx    From kube-design with MIT License 5 votes vote down vote up
render() {
    const { children, error, className, desc, label, rules = [] } = this.props;
    const { validateResults } = this.context;
    const name = children.props.name;

    const childNode = React.cloneElement(children, {
      ...children.props,
      id: name,
      onChange: this.handleValueChange.bind(
        this,
        name,
        children.props.onChange
      ),
      onError: this.handleError.bind(this, name, children.props.onError),
      value: this.getValue(name, children.props),
    });

    const lastError =
      error ||
      this.state.componentError ||
      this.state.error ||
      (validateResults && validateResults.find((item) => item.field === name));

    const classNames = classnames(
      "form-item",
      { "error-item": !isEmpty(lastError) },
      className
    );

    const isRequired = rules.some((rule) => rule.required);

    return (
      <div className={classNames}>
        {label && (
          <label className="form-item-label" htmlFor={name}>
            {label}
            {isRequired ? <span className="form-item-required">*</span> : null}
          </label>
        )}
        <div className="form-item-control">
          {childNode}
          {!isEmpty(lastError) && (
            <div className="form-item-error">
              {isObject(lastError.message)
                ? lastError.message.message
                : lastError.message}
            </div>
          )}
          {isEmpty(lastError) && desc && (
            <div className="form-item-desc">{desc}</div>
          )}
        </div>
      </div>
    );
  }
Example #22
Source File: index.js    From hzero-front with Apache License 2.0 5 votes vote down vote up
export default function cacheComponent({ cacheKey, cachePreKey = getActiveTabKey() } = {}) {
  return (Component) =>
    class CacheComponent extends React.Component {
      loadCache(component, callback) {
        if (cacheKey) {
          const { form } = component.props;
          const cache = getCache(cacheKey);
          if (form && cache && cache.form) {
            if (isObject(cache.form)) {
              Object.keys(cache.form).forEach((item) => form.registerField(item));
            }
            form.setFieldsValue(cache.form);
          }

          if (cache && cache.state) {
            component.setState(cache.state, () => {
              if (callback) callback();
            });
          } else if (callback) {
            callback();
          }
        }
      }

      componentWillUnmount() {
        // if(CLEAR_MAP[cacheKey]){
        //   delete CLEAR_MAP[cacheKey];
        // }else{
        if (cacheKey && this.pageComponent) {
          const { form } = this.pageComponent.props;
          const cache = {};
          if (form) {
            const { getFieldsValue } = form;
            cache.form = getFieldsValue();
          }

          if (this.pageComponent.state) {
            cache.state = this.pageComponent.state;
          }
          // setCache(cacheKey,cache);
          emitter.emit('save', cacheKey, cache, cachePreKey);
        }
        // }
      }

      setComponent = (component) => {
        this.pageComponent = component;
      };

      fakeComponentDidMount(Comp) {
        if (Comp._isFakeComponentDidMount !== true) {
          const { componentDidMount } = Comp.prototype;
          const { loadCache } = this;
          Comp.prototype.componentDidMount = function newComponentDidMount() {
            emitter.emit('willCache', cachePreKey);
            loadCache(this, () => {
              if (typeof componentDidMount === 'function') {
                componentDidMount.call(this);
              }
            });
          };
          Comp._isFakeComponentDidMount = true;
        }
      }

      render() {
        this.fakeComponentDidMount(Component);
        return <Component ref={this.setComponent} {...this.props} />;
      }
    };
}
Example #23
Source File: menuTab.js    From hzero-front with Apache License 2.0 5 votes vote down vote up
function searchFormat(search) {
  if (isObject(search)) {
    return search;
  }
  return qs.parse(search);
}
Example #24
Source File: index.js    From hzero-front with Apache License 2.0 4 votes vote down vote up
// 生成报表
  @Bind()
  buildReport(pageParams = {}) {
    const { reportDataId } = this.state;
    const {
      form,
      dispatch,
      dateFormat,
      dateTimeFormat,
      reportQuery: { detail = {} },
    } = this.props;
    const { paramsData = {} } = detail[reportDataId] || {};
    const { reportUuid, formElements, reportTypeCode } = paramsData;
    this.form.validateFields((err1) => {
      if (!err1) {
        const fieldValues = isUndefined(this.form)
          ? {}
          : filterNullValueObject(this.form.getFieldsValue());

        form.validateFields((err, values) => {
          const { fCodeTenant, ...othersData } = values;
          const valueData = { ...othersData, 'f-templateCode': fCodeTenant };
          const newValues = filter(valueData, (item) => !isUndefined(item));
          let strParam = '';
          map(fieldValues, (value, key) => {
            if (isArray(value) && value.length > 0) {
              const separator = `&${key}=`;
              if (strParam) {
                strParam = `${separator}${join(value, separator)}&${strParam}`;
              } else {
                strParam = `${separator}${join(value, separator)}`;
              }
              if (isEmpty(newValues)) {
                strParam = strParam.substring(1);
              }
              // eslint-disable-next-line no-param-reassign
              delete fieldValues[key];
            } else if (isArray(value) && value.length === 0) {
              // eslint-disable-next-line no-param-reassign
              delete fieldValues[key];
            }
          });
          const formatFieldValues = { ...fieldValues };
          for (const key of Object.keys(fieldValues)) {
            if (isObject(fieldValues[key]) && moment(fieldValues[key]).isValid()) {
              // TODO: 处理日期时间的格式化
              formElements.forEach((n) => {
                if (n.name === key) {
                  if (n.type === 'DatePicker') {
                    formatFieldValues[key] = moment(fieldValues[key]).format(dateFormat);
                  } else if (n.type === 'DatetimePicker') {
                    formatFieldValues[key] = moment(fieldValues[key]).format(dateTimeFormat);
                  }
                }
              });
            }
          }
          if (!err) {
            if (reportTypeCode !== 'C') {
              dispatch({
                type: 'reportQuery/buildReport',
                payload: {
                  // type: reportTypeCode,
                  strParam,
                  reportUuid,
                  ...formatFieldValues,
                  ...values,
                  ...pageParams,
                },
              }).then((res) => {
                if (res) {
                  this.setState({ reportData: res }, () => {
                    if (reportTypeCode === 'ST') {
                      this.handleScrollDom();
                    }
                  });
                }
              });
            } else if (reportTypeCode === 'C') {
              const params = { strParam, ...formatFieldValues, ...values, ...pageParams };
              this.setState({
                EChartsVisible: true,
                uuidKey: uuid(),
                chartParams: params,
              });
            }
          }
        });
      }
    });
  }
Example #25
Source File: index.js    From hzero-front with Apache License 2.0 4 votes vote down vote up
/**
   * @function handleAdd - 新增或编辑可执行数据
   * @param {Object} fieldsValue - 编辑的数据
   * @param {Object} others - 其他参数(fix bug 新增)
   */
  @Bind()
  handleAdd(fieldsValue, others = {}) {
    const {
      dispatch,
      concRequest: { pagination, paramList = [] },
      currentTenantId,
    } = this.props;
    const {
      startDate,
      endDate,
      concurrentId,
      cycleFlag,
      intervalType,
      intervalNumber,
      intervalHour,
      intervalMinute,
      intervalSecond,
      tenantId,
    } = fieldsValue;
    const newFields = cloneDeep(fieldsValue);
    if (paramList.length > 0) {
      const { requestParamNameMap = new Map() } = others;
      [
        'concurrentId',
        'cycleFlag',
        'startDate',
        'endDate',
        'intervalType',
        'intervalNumber',
        'intervalHour',
        'intervalMinute',
        'intervalSecond',
        'tenantId',
      ].forEach((paramCode) => {
        if (!requestParamNameMap.has(paramCode)) {
          delete newFields[paramCode];
        }
      });
    }
    if (!newFields) {
      return null;
    }
    forEach(newFields, (value, key) => {
      // 值 只有可能是 数组/moment对象/字符串/数字
      if (isArray(value)) {
        newFields[key] = JSON.stringify(value);
      } else if (isObject(value)) {
        //  eslint-disable-next-line
        if (moment(value).isValid()) {
          //  eslint-disable-next-line
          newFields[key] = moment(value).format(getDateTimeFormat());
        }
      }
    });
    dispatch({
      type: 'concRequest/createRequest',
      payload: {
        startDate: startDate ? moment(startDate).format(DEFAULT_DATETIME_FORMAT) : null,
        endDate: endDate ? moment(endDate).format(DEFAULT_DATETIME_FORMAT) : null,
        requestParam: paramList.length > 0 ? JSON.stringify(newFields) : null,
        concurrentId,
        cycleFlag,
        intervalType,
        intervalNumber,
        intervalHour,
        intervalMinute,
        intervalSecond,
        tenantId: !isUndefined(tenantId) ? tenantId : currentTenantId,
      },
    }).then((res) => {
      if (res) {
        notification.success();
        this.handleModalVisible(false);
        this.handleSearch(pagination);
      }
    });
  }
Example #26
Source File: index.js    From hzero-front with Apache License 2.0 4 votes vote down vote up
// 生成报表
  @Bind()
  buildReport(pageParams = {}) {
    const { reportDataId } = this.state;
    const {
      form,
      dispatch,
      dateFormat,
      dateTimeFormat,
      reportQuery: { detail = {} },
    } = this.props;
    const { paramsData = {} } = detail[reportDataId] || {};
    const { reportUuid, formElements, reportTypeCode } = paramsData;
    this.form.validateFields((err1) => {
      if (!err1) {
        const fieldValues = isUndefined(this.form)
          ? {}
          : filterNullValueObject(this.form.getFieldsValue());

        form.validateFields((err, values) => {
          const { fCodeTenant, ...others } = values;
          const valueData = { ...others, 'f-templateCode': fCodeTenant };
          const newValues = filter(valueData, (item) => !isUndefined(item));
          let strParam = '';
          map(fieldValues, (value, key) => {
            if (isArray(value) && value.length > 0) {
              const separator = `&${key}=`;
              if (strParam) {
                strParam = `${separator}${join(value, separator)}&${strParam}`;
              } else {
                strParam = `${separator}${join(value, separator)}`;
              }
              if (isEmpty(newValues)) {
                strParam = strParam.substring(1);
              }
              // eslint-disable-next-line no-param-reassign
              delete fieldValues[key];
            } else if (isArray(value) && value.length === 0) {
              // eslint-disable-next-line no-param-reassign
              delete fieldValues[key];
            }
          });
          const formatFieldValues = { ...fieldValues };
          for (const key of Object.keys(fieldValues)) {
            if (isObject(fieldValues[key]) && moment(fieldValues[key]).isValid()) {
              // TODO: 处理日期时间的格式化
              formElements.forEach((n) => {
                if (n.name === key) {
                  if (n.type === 'DatePicker') {
                    formatFieldValues[key] = moment(fieldValues[key]).format(dateFormat);
                  } else if (n.type === 'DatetimePicker') {
                    formatFieldValues[key] = moment(fieldValues[key]).format(dateTimeFormat);
                  }
                }
              });
            }
          }
          if (!err) {
            if (reportTypeCode !== 'C') {
              dispatch({
                type: 'reportQuery/buildReport',
                payload: {
                  // type: reportTypeCode,
                  strParam,
                  reportUuid,
                  ...formatFieldValues,
                  ...valueData,
                  ...pageParams,
                },
              }).then((res) => {
                if (res) {
                  this.setState({ reportData: res }, () => {
                    if (reportTypeCode === 'ST') {
                      this.handleScrollDom();
                    }
                  });
                }
              });
            } else if (reportTypeCode === 'C') {
              const params = { strParam, ...formatFieldValues, ...valueData, ...pageParams };
              this.setState({
                EChartsVisible: true,
                uuidKey: uuid(),
                chartParams: params,
              });
            }
          }
        });
      }
    });
  }
Example #27
Source File: index.js    From strapi-plugin-elastic with MIT License 4 votes vote down vote up
DataView = ({
  data = [],
  activeModel = '',
  loading,
  page,
  limit,
  totalCount,
  onChangeParams,
  isMigrateActive,
  isDeleted,
  isCreated,
  refreshData,
}) => {
  const history = useHistory();
  const tableHeaders = useMemo(
    () =>
      data && data.length
        ? Object.keys(data[0]).map((d) => ({ name: d, value: d }))
        : [],
    [data]
  );

  const tableData = useMemo(
    () =>
      data && data.length
        ? data.map((dataObject) => {
            let newObj = {};
            if (!dataObject) return newObj;

            for (let key in dataObject) {
              if (isObject(dataObject[key])) {
                newObj[key] = JSON.stringify(dataObject[key], null, 2);
              } else {
                newObj[key] = dataObject[key];
              }
            }

            return newObj;
          })
        : [],
    [data]
  );

  const [isMigrating, setIsMigrating] = useState(false);
  const [isCreating, setIsCreating] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);

  const migrate = (model) => {
    setIsMigrating(true);
    request(`/elastic/migrate-model`, {
      method: 'POST',
      body: { model },
    })
      .then((res) => {
        if (res.success) {
          strapi.notification.success(`${model} model migrated successfully`);
          refreshData();
        } else strapi.notification.error(`migration failed`);
      })
      .catch(() => strapi.notification.error(`migration failed`))
      .finally(() => setIsMigrating(false));
  };

  const deleteIndex = (model) => {
    setIsDeleting(true);
    request(`/elastic/delete-index`, {
      method: 'POST',
      body: { model },
    })
      .then((res) => {
        if (res.success) {
          refreshData();
          strapi.notification.success(`${model} index deleted`);
        } else {
          strapi.notification.error(`cannot delete ${model} index`);
        }
      })
      .catch(() => {
        strapi.notification.error(`cannot delete ${model} index`);
      })
      .finally(() => setIsDeleting(false));
  };

  const createIndex = (model) => {
    setIsCreating(true);
    request(`/elastic/create-index`, {
      method: 'POST',
      body: { model },
    })
      .then((res) => {
        refreshData();
        if (res.success) {
          strapi.notification.success(`${model} index created`);
        } else {
          strapi.notification.error(`cannot create ${model} index`);
        }
      })
      .catch(() => strapi.notification.error(`cannot create ${model} index`))
      .finally(() => setIsCreating(false));
  };

  return (
    <Wrapper>
      <div className="row px-4">
        <h2>{activeModel?.index?.toUpperCase()}</h2>
        <Button
          color="success"
          isLoading={isMigrating}
          onClick={() => {
            migrate(activeModel.model);
          }}
          className="ml-auto"
          disabled={!isMigrateActive}
        >
          migrate
        </Button>
        <Button
          color="primary"
          isLoading={isCreating}
          disabled={isCreated}
          onClick={() => {
            createIndex(activeModel.model);
          }}
          className="ml-2"
        >
          create
        </Button>
        <Button
          color="delete"
          isLoading={isDeleting}
          disabled={isDeleted}
          onClick={() => {
            deleteIndex(activeModel.model);
          }}
          className="ml-2"
        >
          delete
        </Button>
      </div>
      <hr />
      {loading ? (
        new Array(10).fill(0).map(() => (
          <>
            <LoadingBar />
            <div className="mt-3" />
          </>
        ))
      ) : (
        <>
          <Table
            headers={tableHeaders}
            rows={tableData}
            onClickRow={(e, data) =>
              history.push(
                `/plugins/content-manager/collectionType/${
                  activeModel?.plugin
                    ? `plugins::${activeModel?.plugin}.${activeModel?.model}`
                    : `application::${activeModel?.model}.${activeModel?.model}`
                }/${data.id}`
              )
            }
          />
          <div className="mt-5 row align-items-center px-2">
            <Select
              name="params._limit"
              onChange={onChangeParams}
              options={LIMIT_OPTIONS}
              value={limit}
              className="col-2"
            />
            <div className="col-8 ml-auto">
              <GlobalPagination
                count={totalCount}
                onChangeParams={onChangeParams}
                params={{
                  _limit: parseInt(limit || 10, 10),
                  _page: page,
                }}
              />
            </div>
          </div>
        </>
      )}
    </Wrapper>
  );
}
Example #28
Source File: cadastrapp.js    From mapstore2-cadastrapp with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Holds the state of cadastrapp.
 * The shape of the state is the following:
 * ```
 * {
 *     loading: true | false // general loading flag
 *     loadingFlags: {} // object that contain loading flag, for various parts of the application.
 *     searchType: undefined // one of constant.SEARCH_TOOLS
 *     selectionType: undefined // one of constant.SELECTION_TYPE
 *     plots: [{  // an entry for each tab of the plot selection
 *          data: [{parcelle: "12345", ...}] // data of the tab
 *          selected: [parcelle1, parcelle2]
 *     }],
 *     configuration: { // the configuration from server. e.g.
 *        cadastreLayerIdParcelle: "geo_parcelle"
 *        cadastreWFSLayerName: "qgis:cadastrapp_parcelle"
 *        cadastreWFSURL: "https://domain.org/geoserver/wfs"
 *        cadastreWMSLayerName: "qgis:cadastrapp_parcelle"
 *        cadastreWMSURL: "https://domain.org/geoserver/wms"
 *        cnil1RoleName: "ROLE_EL_APPLIS_CAD_CNIL1"
 *        cnil2RoleName: "ROLE_EL_APPLIS_CAD_CNIL2"
 *        dateValiditeEDIGEO: "01/01/2018"
 *        dateValiditeMajic: "01/01/2018"
 *        maxRequest: "8"
 *        minNbCharForSearch: "3"
 *        minParacelleIdLength: "14"
 *        organisme: "Un service fourni par "
 *        pdfbasemapthumbnails: [{,…}, {,…}]
 *        pdfbasemaptitles: [{value: "Cadastre", key: "pdf.baseMap.0.title"},…]
 *        uFWFSLayerName: "qgis:cadastrapp_unite_fonciere"
 *        uFWFSURL: "https://domain.org/geoserver/wfs"
 *     }
 * }
 * ```
 *
 * @param {object} state the application state
 * @param {object} action a redux action
 */
export default function cadastrapp(state = DEFAULT_STATE, action) {
    const type = action.type;
    switch (type) {
    case SETUP:
        return set('pluginCfg', action.cfg, state);
    case SET_CONFIGURATION:
        return set('configuration', action.configuration, state);
    case LOADING: {
        let newValue = action.value;
        if (action.mode === 'count') {
            const oldValue = get(state, `loadFlags.${action.name}`) ?? 0;
            newValue = isNumber(newValue)
                ? newValue // set with passed value if number
                : newValue
                    ? oldValue + 1 // increment if true
                    : Math.max(oldValue - 1, 0); // decrement if false
        }
        // anyway sets loading to true
        return set(action.name === "loading" ? "loading" : `loadFlags.${action.name}`, newValue, state);
    }
    case TOGGLE_SELECTION: {
        const {selectionType} = action;
        // if the current selection button is clicked, it turns off selection
        return set("selectionType", selectionType, state);
    }
    case TOGGLE_SEARCH: {
        const { searchType } = action;
        // if the current search button is clicked, it closes the search section
        return set("searchType", searchType, state);
    }
    case ADD_PLOTS: {
        const { plots, target, activate = true } = action;
        const {activePlotSelection = 0 } = state;
        let targetPlotSelection = activePlotSelection;
        let newState = state;
        if (!isNil(target)) {
            const targetIndex = isObject(target) ? findIndex(state.plots, {id: target.id}) : target;
            // create
            if (targetIndex < 0) {
                newState = set(`plots`, [...state.plots, { ...EMPTY_PLOT_SELECTION, ...target }], state);
                targetPlotSelection = newState.plots.length - 1;
            } else {
                newState = set(`plots[${targetIndex}]`, {...state.plots[targetIndex], ...target});
                targetPlotSelection = targetIndex;
            }
        }
        if (activate) {
            newState = set(`activePlotSelection`, targetPlotSelection, newState);
        }
        // get the current selection or create a new one if it not exists.
        let currentSelection = newState?.plots?.[targetPlotSelection] ?? EMPTY_PLOT_SELECTION;
        // add every plot received and toggle selection if exist
        plots.map(({ parcelle, ...other}) => {
            // if exists, toggle selection
            currentSelection = toggleSelection(currentSelection, parcelle);
            // update/insert the value at the en
            currentSelection = arrayUpsert(`data`, { parcelle, ...other }, {parcelle}, currentSelection);
        });
        // update with new values the state
        return set(`plots[${targetPlotSelection}]`, currentSelection, newState);
    }
    case REMOVE_PLOTS: {
        const { parcelles = []} = action;
        const {activePlotSelection = 0 } = state;
        // get the current selection or create a new one if it not exists.
        let currentSelection = state?.plots?.[activePlotSelection] ?? EMPTY_PLOT_SELECTION;
        currentSelection = {
            ...currentSelection,
            data: currentSelection.data.filter(({ parcelle }) => !parcelles.includes(parcelle)),
            selected: currentSelection.selected.filter(parcelle => !parcelles.includes(parcelle))
        };
        // update with new values the state
        return set(`plots[${activePlotSelection}]`, currentSelection, state);
    }
    case SELECT_PLOTS:
    case DESELECT_PLOTS: {
        const { activePlotSelection = 0 } = state;
        let currentSelection = state?.plots?.[activePlotSelection] ?? EMPTY_PLOT_SELECTION;
        const {plots = []} = action;
        const parcelles = plots.map(({ parcelle }) => parcelle);
        const selected = action.type === SELECT_PLOTS
            ? uniq([...(currentSelection.selected || []), ...parcelles])
            : (currentSelection.selected || []).filter(id => !parcelles.includes(id));
        currentSelection = {
            ...currentSelection,
            selected
        };
        return set(`plots[${activePlotSelection}]`, currentSelection, state);
    }
    case ADD_PLOT_SELECTION: {
        const {plot = {}} = action;
        const currentPlots = state?.plots ?? [];
        return compose(
            set(`plots`, [...currentPlots, { ...EMPTY_PLOT_SELECTION, ...plot}]),
            set(`activePlotSelection`, state?.plots?.length ?? 0) // select the new tab
        )(state);
    }
    case REMOVE_PLOT_SELECTION: {
        const active = action.active ?? state.activePlotSelection;
        const newPlots = [...state.plots.filter((_, i) => i !== active)];
        return compose(
            set(`plots`, newPlots),
            set(`activePlotSelection`, Math.max(state.activePlotSelection - 1, 0))
        )(state);
    }
    case SET_ACTIVE_PLOT_SELECTION: {
        return set('activePlotSelection', action.active, state);
    }
    case SET_LAYER_STYLE: {
        return set(`styles.${action.styleType}`, action.value, state);
    }
    case UPDATE_LAYER_STYLE: {
        return set(`styles.${action.styleType}`, {...(state?.styles?.[action.styleType] ?? {}), ...action.values}, state);
    }
    case SET_STYLES: {
        return set('styles', action.styles, state);
    }
    case SHOW_OWNERS: {
        return compose(
            set('owners.data', action.owners),
            set('owners.show', true)
        )(state);
    }
    case CLEAR_OWNERS: {
        return set('owners', undefined, state);
    }
    case SHOW_LANDED_PROPERTIES_INFORMATION: {
        return set('landedProperty.parcelle', action.parcelle, state);
    }
    case INFORMATION_UPDATE: {
        return set(
            `informationData["${action.parcelle}"]${action.path ? '.' + action.path : ''}`, action.data, state
        );
    }
    case INFORMATION_CLEAR: {
        return set(
            `informationData`, undefined, state
        );
    }
    case SAVE_BUBBLE_INFO: {
        return set('infoBulle', action.data, state);
    }
    case PRINT_RESPONSE: {
        return {...state, requestFormData: {...state.requestFormData, allowDocument: action.allowDocument, requestId: action.requestId}};
    }

    default:
        return state;
    }
}