lodash#pickBy JavaScript Examples

The following examples show how to use lodash#pickBy. 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: Enrollment.js    From SaraAlert with Apache License 2.0 6 votes vote down vote up
constructor(props) {
    super(props);
    this.state = {
      index: this.props.editMode ? 6 : 0,
      direction: null,
      enrollmentState: {
        patient: pickBy(this.props.patient, identity),
        propagatedFields: {},
      },
    };
    this.setEnrollmentState = debounce(this.setEnrollmentState.bind(this), 1000);
    this.submit = this.submit.bind(this);
    this.next = this.next.bind(this);
    this.previous = this.previous.bind(this);
    this.handleConfirmDuplicate = this.handleConfirmDuplicate.bind(this);
    this.goto = this.goto.bind(this);
  }
Example #2
Source File: index.js    From HexactaLabs-NetCore_React-Initial with Apache License 2.0 6 votes vote down vote up
export function fetchByFilters(filters) {
  return function(dispatch) {
    return api
      .post("/provider/search", pickBy(filters))
      .then(response => {
        dispatch(setProviders(response.data));
      })
      .catch(error => {
        apiErrorToast(error);
      });
  };
}
Example #3
Source File: index.js    From HexactaLabs-NetCore_React-Initial with Apache License 2.0 6 votes vote down vote up
export function fetchByFilters(filters) {
  return function(dispatch) {
    return api
      .post("/store/search", pickBy(filters))
      .then(response => {
        dispatch(setStores(response.data));
      })
      .catch(error => {
        apiErrorToast(error);
      });
  };
}
Example #4
Source File: index.js    From HexactaLabs-NetCore_React-Final with Apache License 2.0 6 votes vote down vote up
export function fetchByFilters(filters) {
  return function (dispatch) {
    return api
      .post("/product/search", pickBy(filters))
      .then(response => {
        const products = response.data.map(product => ({
          ...product,
          productTypeId: product.productType.id,
          productTypeDesc: product.productType.description
        }));
        dispatch(setProducts(products));
      })
      .catch(error => {
        apiErrorToast(error);
      });
  };
}
Example #5
Source File: index.js    From HexactaLabs-NetCore_React-Level1 with Apache License 2.0 6 votes vote down vote up
export function fetchByFilters(filters) {
  return function (dispatch) {
    return api
      .post("/producttype/search", pickBy(filters))
      .then((response) => {
        dispatch(setProductTypes(response.data));
      })
      .catch((error) => {
        apiErrorToast(error);
      });
  };
}
Example #6
Source File: networkService.js    From web-wallet with Apache License 2.0 6 votes vote down vote up
// run on poll to check status of any 'pending' deposits
  async checkPendingDepositStatus () {
    try {
      const state = store.getState();
      const { eth: ethDeposits, erc20: erc20Deposits } = state.deposit;

      const pendingEthDeposits = pickBy(ethDeposits, (deposit, transactionHash) => {
        return deposit.status === 'Pending';
      });
      const pendingErc20Deposits = pickBy(erc20Deposits, (deposit, transactionHash) => {
        return deposit.status === 'Pending';
      });

      const updatedEthDeposits = await Promise.all(Object.values(pendingEthDeposits).map(this.getDepositStatus));
      const updatedErc20Deposits = await Promise.all(Object.values(pendingErc20Deposits).map(this.getDepositStatus));
      return { eth: updatedEthDeposits, erc20: updatedErc20Deposits };
    } catch (error) {
      throw new WebWalletError({
        originalError: error,
        reportToSentry: false,
        reportToUi: false
      });
    }
  }
Example #7
Source File: index.js    From HexactaLabs-NetCore_React-Level1 with Apache License 2.0 6 votes vote down vote up
export function fetchByFilters(filters) {
  return function(dispatch) {
    return api
      .post("/producttype/search", pickBy(filters))
      .then(response => {
        dispatch(setProductTypes(response.data));
      })
      .catch(error => {
        apiErrorToast(error);
      });
  };
}
Example #8
Source File: pendingIssue.js    From bonded-stablecoin-ui with MIT License 5 votes vote down vote up
pendingIssue = (params) => ({
  type: PENDING_ISSUE_STABLECOIN,
  payload: pickBy(params, (p) => p !== undefined),
})
Example #9
Source File: DemarcheSectionSelect.js    From datapass with GNU Affero General Public License v3.0 4 votes vote down vote up
DemarcheSectionSelect = ({ body, scrollableId }) => {
  const { disabled, onChange, enrollment, demarches } = useContext(FormContext);
  const { demarche: selectedDemarcheId } = enrollment;

  const [isLoading, setIsLoading] = useState(false);
  const [confirmNewDemarcheId, setConfirmNewDemarcheId] = useState(false);

  // reducer expects onChange events from HTML Element
  const selectNewDemarche = useCallback(
    (newDemarcheId) => {
      onChange({ target: { value: newDemarcheId, name: 'demarche' } });
    },
    [onChange]
  );

  const filteredDemarches = useMemo(
    () =>
      pickBy(demarches, function (value, key) {
        return (
          !value.state?.technical_team_value ||
          !enrollment.technical_team_value ||
          value.state.technical_team_value ===
            enrollment.technical_team_value ||
          key === selectedDemarcheId
        );
      }),
    [demarches, enrollment.technical_team_value, selectedDemarcheId]
  );

  const onSelectDemarche = (event) => {
    let newDemarcheId = event.target.value || 'default';

    const preFilledEnrollment = merge(
      {},
      get(demarches, 'default', {}).state,
      get(demarches, selectedDemarcheId, {}).state
    );

    // we compare current enrollment with prefilled associated with selectedDemarcheId
    // if modifications, it means any change to selectedDemarcheId could overwrite the user's changes.
    const modifications = findModifiedFields(preFilledEnrollment, enrollment);

    if (!isEmpty(modifications)) {
      // trigger confirmation modal before updating Enrollment
      setConfirmNewDemarcheId(newDemarcheId);
    } else {
      // update Enrollment Context with new demarche
      selectNewDemarche(newDemarcheId);
    }
  };

  useEffect(() => {
    if (selectedDemarcheId !== 'default') {
      setIsLoading(true);
      const timer = setTimeout(() => setIsLoading(false), 900);
      return () => clearTimeout(timer);
    }
  }, [selectedDemarcheId]);

  const displayNotification = useMemo(
    () =>
      has(demarches, selectedDemarcheId) && selectedDemarcheId !== 'default',
    [demarches, selectedDemarcheId]
  );

  return (
    <>
      <ScrollablePanel scrollableId={scrollableId}>
        <h2>Les modèles pré-remplis</h2>
        {body || (
          <p>
            Nous avons identifié plusieurs cas d’usage de cette API. Si votre
            demande d’habilitation s’inscrit dans un des cas ci-dessous,
            sélectionnez-le pour gagner du temps.
          </p>
        )}
        <SelectInput
          label="Sélectionnez le modèle correspondant à votre projet"
          name="demarche"
          options={Object.keys(filteredDemarches).map((demarcheId) => ({
            id: demarcheId,
            label: get(demarches, demarcheId, {}).label,
          }))}
          value={selectedDemarcheId}
          disabled={disabled}
          onChange={onSelectDemarche}
        />
        {confirmNewDemarcheId && (
          <ConfirmationModal
            title="Attention, vous allez écraser certains de vos changements"
            handleCancel={() => setConfirmNewDemarcheId(false)}
            handleConfirm={() => {
              setConfirmNewDemarcheId(false);
              selectNewDemarche(confirmNewDemarcheId);
            }}
            confirmLabel="Changer tout de même"
          >
            <p>
              En changeant de cas d’usage, certains des champs que vous avez
              édités vont être écrasés.
            </p>
          </ConfirmationModal>
        )}
        {displayNotification && (
          <DemarcheSectionSelectNotification
            isLoading={isLoading}
            selectedDemarcheId={selectedDemarcheId}
            demarches={demarches}
          />
        )}
      </ScrollablePanel>
    </>
  );
}
Example #10
Source File: Stats.js    From datapass with GNU Affero General Public License v3.0 4 votes vote down vote up
Stats = () => {
  const [stats, setStats] = useState(null);
  const { targetApi } = useParams();

  const dataProviderKeyList = useMemo(
    () =>
      Object.keys(DATA_PROVIDER_PARAMETERS).filter(
        (dataProviderKey) =>
          !HIDDEN_DATA_PROVIDER_KEYS.includes(dataProviderKey)
      ),
    []
  );

  async function getTargetAPIList(targetApi) {
    let targetApiList;

    switch (targetApi) {
      case 'allApi':
        const ApiTargetConfiguration = pickBy(
          DATA_PROVIDER_PARAMETERS,
          (dataProviderConfig) => dataProviderConfig.type === 'api'
        );
        targetApiList = Object.keys(ApiTargetConfiguration);
        break;
      case 'allServices':
        const serviceTargetConfiguration = pickBy(
          DATA_PROVIDER_PARAMETERS,
          (dataProviderConfig) => dataProviderConfig.type === 'service'
        );
        targetApiList = Object.keys(serviceTargetConfiguration);
        break;
      case undefined:
        targetApiList = [];
        break;
      default:
        targetApiList = [targetApi];
    }
    return getAPIStats(targetApiList);
  }

  useEffect(() => {
    async function fetchStats() {
      const result = await getTargetAPIList(targetApi);

      setStats({
        ...result.data,
        enrollment_by_target_api: stackLowUseAndUnpublishedApi(
          dataProviderKeyList,
          result.data.enrollment_by_target_api,
          10
        ),
      });
    }

    fetchStats();
  }, [targetApi, dataProviderKeyList]);

  if (!stats) {
    return (
      <section className="full-page">
        <Loader />
      </section>
    );
  }

  return (
    <main>
      <ListHeader title="Statistiques d’utilisation">
        <TagContainer>
          <NavLink end to="/stats">
            {({ isActive }) => (
              <Tag type={isActive ? 'info' : ''}>Toutes les habilitations</Tag>
            )}
          </NavLink>
          <NavLink end to={`/stats/allApi`}>
            {({ isActive }) => (
              <Tag type={isActive ? 'info' : ''}>Toutes les API</Tag>
            )}
          </NavLink>
          <NavLink end to={`/stats/allServices`}>
            {({ isActive }) => (
              <Tag type={isActive ? 'info' : ''}>Tous les services</Tag>
            )}
          </NavLink>
          {dataProviderKeyList.map((targetApi) => (
            <NavLink key={targetApi} end to={`/stats/${targetApi}`}>
              {({ isActive }) => (
                <Tag type={isActive ? 'info' : ''}>
                  {DATA_PROVIDER_PARAMETERS[targetApi]?.label}
                </Tag>
              )}
            </NavLink>
          ))}
        </TagContainer>
      </ListHeader>
      <div className="table-container">
        <CardContainer>
          <Card className="stat_card">
            <div className="stat_card_head">
              <h3>Habilitations déposées</h3>
            </div>
            <div className="stat_card_number">{stats.enrollment_count}</div>
          </Card>
          <Card className="stat_card">
            <div className="stat_card_head">
              <h3>Habilitations validées</h3>
              <div className="card__meta">
                <Link
                  inline
                  href={`/public${targetApi ? `/${targetApi}` : ''}`}
                >
                  voir la liste détaillée
                </Link>
              </div>
            </div>
            <div className="stat_card_number">
              <div>{stats.validated_enrollment_count}</div>
            </div>
          </Card>
        </CardContainer>
        <CardContainer>
          <Card className="stat_card">
            <div className="stat_card_head">
              <h3>
                Temps moyen de traitement des demandes d’habilitation
                <Helper title="temps moyen entre la première soumission d’une demande d’habilitation jusqu’à la première réponse d'un instructeur sur les 6 derniers mois" />
              </h3>
              <div className="card__meta">(en jours)</div>
            </div>
            <div className="stat_card_number">
              {stats.average_processing_time_in_days}
            </div>
          </Card>
          <Card className="stat_card">
            <div className="stat_card_head">
              <h3>
                Pourcentage des habilitations nécessitant un aller retour
                <Helper title="sur les 6 derniers mois" />
              </h3>
              <div className="card__meta">(en % des habilitations totales)</div>
            </div>
            <div className="stat_card_number">{stats.go_back_ratio}</div>
          </Card>
        </CardContainer>
        <CardContainer>
          <Card className="stat_card">
            <div className="stat_card_head">
              <h3>Habilitations déposées</h3>
            </div>
            <div className="stat_card_graph">
              <ResponsiveContainer width={'100%'} height={250}>
                <BarChart data={stats.monthly_enrollment_count}>
                  <XAxis
                    dataKey="month"
                    tickFormatter={(value) => moment(value).format('MMM YY')}
                  />
                  <YAxis />
                  <Tooltip
                    formatter={(value, name, props) => [
                      value,
                      USER_STATUS_LABELS[name],
                      props,
                    ]}
                    labelFormatter={(value) => moment(value).format('MMM YYYY')}
                  />
                  <Legend formatter={(value) => USER_STATUS_LABELS[value]} />
                  <CartesianGrid vertical={false} />
                  {Object.keys(EnrollmentStatus).map((status, index, array) => (
                    <Bar
                      key={status}
                      stackId="count"
                      dataKey={status}
                      fill={USER_STATUS_COLORS[status]}
                    >
                      {index === array.length - 1 && (
                        <LabelList dataKey="total" position="top" />
                      )}
                    </Bar>
                  ))}
                </BarChart>
              </ResponsiveContainer>
            </div>
          </Card>
        </CardContainer>
        <CardContainer>
          <Card className="stat_card">
            <div className="stat_card_head">
              <h3>Répartition des habilitations par statut</h3>
            </div>
            <div className="stat_card_graph">
              <ResponsiveContainer width={'100%'} height={250}>
                <PieChart>
                  <Pie data={stats.enrollment_by_status} dataKey="count" label>
                    {stats.enrollment_by_status.map((entry, index) => (
                      <Cell key={index} fill={USER_STATUS_COLORS[entry.name]} />
                    ))}
                  </Pie>
                  <Legend
                    layout={'vertical'}
                    align={'right'}
                    verticalAlign={'middle'}
                    formatter={(value) => USER_STATUS_LABELS[value]}
                  />
                  <Tooltip
                    formatter={(value, name, props) => [
                      value,
                      USER_STATUS_LABELS[name],
                      props,
                    ]}
                  />
                </PieChart>
              </ResponsiveContainer>
            </div>
          </Card>
        </CardContainer>
        <CardContainer>
          <Card className="stat_card">
            <div className="stat_card_head">
              <h3>Répartition des habilitations par API</h3>
            </div>
            <div className="stat_card_graph">
              <ResponsiveContainer width={'100%'} height={450}>
                <PieChart>
                  <Pie
                    data={stats.enrollment_by_target_api}
                    dataKey="count"
                    label
                  >
                    {stats.enrollment_by_target_api.map((entry, index) => (
                      <Cell key={index} fill={COLORS[index % COLORS.length]} />
                    ))}
                  </Pie>
                  <Tooltip
                    formatter={(value, name, props) => [
                      value,
                      name === 'others'
                        ? 'Autres'
                        : DATA_PROVIDER_PARAMETERS[name]?.label,
                      props,
                    ]}
                  />
                  <Legend
                    layout={'vertical'}
                    align={'right'}
                    verticalAlign={'middle'}
                    formatter={(value) =>
                      (value === 'others'
                        ? 'Autres'
                        : DATA_PROVIDER_PARAMETERS[value]?.label
                      ).substring(0, 32)
                    }
                  />
                </PieChart>
              </ResponsiveContainer>
            </div>
          </Card>
        </CardContainer>
      </div>
    </main>
  );
}