Example #1
0
import { createAction, createThunkAction } from 'redux-tools';
import isEmpty from 'lodash/isEmpty';

const { fetch } = window;

export const setGlobalSection = createAction('setGlobalSection');
export const setGlobalSectionThunk = createThunkAction(
  'setGlobalSectionThunk',
  type => (dispatch, getState) => {
    const { section } = getState().section;
    dispatch(setGlobalSection({ type, section }));
  }
);
export const setWhereToProtectData = createAction('setWhereToProtectData');

export const selectGlobalSelector = createAction(
  'selectGlobalSelector',
  null,
  ({ selection }) => ({
    analytics: ['global', 'Change species on map', `Change to ${selection}`]
  })
);
export const toggleGlobalLayer = createAction(
  'toggleGlobalLayer',
  null,
  ({ name }) => ({
    analytics: ['global', 'Change Map Layer', name]
  })
);

export const setCanonicalData = createAction('setCanonicalData');
Example #2
0
export const getHeaderData = createThunkAction(
  'getHeaderData',
  params => dispatch => {
    dispatch(setHeaderLoading({ loading: true, error: false }));
    axios
      .all([
        getExtent(params),
        getExtent({ ...params, forestType: 'plantations' }),
        getLoss(params),
        getLoss({ ...params, forestType: 'plantations' }),
        getLoss({ ...params, forestType: 'primary_forest' })
      ])
      .then(
        axios.spread(
          (
            totalExtent,
            totalPlantationsExtent,
            totalLoss,
            totalPlantationsLoss,
            totalPrimaryLoss
          ) => {
            const extent = totalExtent.data.data;
            const loss = totalLoss.data.data;
            const plantationsLoss = totalPlantationsLoss.data.data;
            const plantationsExtent = totalPlantationsExtent.data.data;

            // group over years
            const groupedLoss = plantationsLoss && groupBy(loss, 'year');
            const groupedPlantationsLoss =
              plantationsLoss && groupBy(plantationsLoss, 'year');

            const primaryLoss = totalPrimaryLoss.data.data;
            const latestYear = max(Object.keys(groupedLoss));

            const latestPlantationLoss =
              groupedPlantationsLoss[latestYear] || null;
            const latestLoss = groupedLoss[latestYear] || null;

            // sum over different bound1 within year
            const summedPlantationsLoss =
              latestPlantationLoss &&
              latestPlantationLoss.length &&
              latestPlantationLoss[0].area
                ? sumBy(latestPlantationLoss, 'area')
                : 0;
            const summedPlantationsEmissions =
              latestPlantationLoss &&
              latestPlantationLoss.length &&
              latestPlantationLoss[0].emissions
                ? sumBy(latestPlantationLoss, 'emissions')
                : 0;
            const summedLoss =
              latestLoss && latestLoss.length && latestLoss[0].area
                ? sumBy(latestLoss, 'area')
                : 0;
            const summedEmissions =
              latestLoss && latestLoss.length && latestLoss[0].emissions
                ? sumBy(latestLoss, 'emissions')
                : 0;

            const data = {
              totalArea: (extent[0] && extent[0].total_area) || 0,
              extent: (extent[0] && extent[0].value) || 0,
              plantationsExtent:
                plantationsExtent && plantationsExtent.length
                  ? plantationsExtent[0].value
                  : 0,
              totalLoss: {
                area: summedLoss || 0,
                year: latestYear || 0,
                emissions: summedEmissions || 0
              },
              plantationsLoss: {
                area: summedPlantationsLoss || 0,
                emissions: summedPlantationsEmissions || 0
              },
              primaryLoss:
                primaryLoss && primaryLoss.length
                  ? reverse(sortBy(primaryLoss, 'year'))[0]
                  : {}
            };
            dispatch(setHeaderData(data));
          }
        )
      )
      .catch(error => {
        dispatch(setHeaderLoading({ loading: false, error: true }));
        console.info(error);
      });
  }
);
Example #3
0
import { track } from 'app/analytics';

import { fetchUmdLossGain } from 'services/analysis';
import { uploadShapeFile } from 'services/shape';
import { getGeostoreKey } from 'services/geostore';
import { setComponentStateToUrl } from 'utils/stateToUrl';

import uploadFileConfig from './upload-config.json';

// url action
export const setAnalysisSettings = createThunkAction(
  'setAnalysisSettings',
  change => (dispatch, state) => {
    dispatch(
      setComponentStateToUrl({
        key: 'analysis',
        change,
        state
      })
    );
  }
);

// store actions
export const setAnalysisData = createAction('setAnalysisData');
export const setAnalysisLoading = createAction('setAnalysisLoading');
export const clearAnalysisError = createAction('clearAnalysisError');
export const clearAnalysisData = createAction('clearAnalysisData');

export const getAnalysis = createThunkAction(
  'getAnalysis',
  location => dispatch => {
Example #4
0
export const setMapPromptsSettings = createThunkAction(
  'setMapPromptsSettings',
  change => (dispatch, state) => {
    const { mapPrompts } = state() || {};
    const { promptsViewed, showPrompts } = mapPrompts || {};
    const { stepsKey, force, stepIndex } = change || {};

    if (
      force ||
      (showPrompts && (!promptsViewed || !promptsViewed.includes(stepsKey)))
    ) {
      dispatch(
        setComponentStateToUrl({
          key: 'mapPrompts',
          change,
          state
        })
      );
      if (stepsKey) {
        track('userPrompt', {
          label: `${stepsKey}: ${stepIndex + 1}`
        });
      }
    }

    if (stepsKey && showPrompts) {
      dispatch(setShowPromptsViewed(stepsKey));
    }
  }
);
export const getLatest = createThunkAction(
  'getLatest',
  latestEndpoints => (dispatch, getState) => {
    const { latest } = getState();
    const currentLatestDates = latest && Object.keys(latest.data);
    const newEndpoints = latestEndpoints.filter(
      l => !currentLatestDates.includes(l.id)
    );
    if (newEndpoints && newEndpoints.length) {
      dispatch(setLatestLoading({ loading: true, error: false }));
      axios
        .all(newEndpoints.map(n => fetchLatestDate(n.latestUrl)))
        .then(
          axios.spread((...responses) => {
            const latestDates =
              responses &&
              responses.reduce((obj, response, index) => {
                const latestResponse = response.data.data || response.data;
                let date = latestResponse.date;
                if (!date) {
                  const data = Array.isArray(latestResponse)
                    ? latestResponse[0].attributes
                    : latestResponse.attributes;
                  date = data.date || data.latestResponse;
                }
                return {
                  ...obj,
                  [newEndpoints[index].id]: moment(date).format('YYYY-MM-DD')
                };
              }, {});
            dispatch(setLatestDates(latestDates));
          })
        )
        .catch(error => {
          console.error('Error in latest request:', error);
        });
    }
  }
);
// Async actions
export const fetchTools = createThunkAction('TOOL_BLOCK_EDITION_FETCH_DATA', (payload = {}) => (dispatch) => {
  dispatch(setLoading(true));
  dispatch(setError(null));

  const qParams = queryString.stringify({
    sort: 'name',
    published: 'all',
    'page[number]': 1,
    'page[size]': 9,
    ...payload.filters
  });

  fetch(`${process.env.API_URL}/tools?${qParams}`)
    .then((response) => {
      if (response.ok) return response.json();
      throw new Error(response.statusText);
    })
    .then((data) => {
      dispatch(setLoading(false));
      dispatch(setError(null));
      dispatch(setTools(sortBy(data, 'title')));
      // dispatch(setTotal(meta['total-items']));
    })
    .catch((err) => {
      dispatch(setLoading(false));
      dispatch(setError(err));
    });
});
Example #7
0
import { createThunkAction } from 'redux-tools';

export const handleCategoryChange = createThunkAction(
  'handleCategoryChange',
  category => (dispatch, getState) => {
    const { query, type, payload } = getState().location || {};
    dispatch({
      type,
      payload,
      query: {
        ...query,
        category,
        widget: undefined
      }
    });
  }
);
import 'isomorphic-fetch';
import { createAction, createThunkAction } from 'redux-tools';

// Actions
export const setDashboard = createAction('DASHBOARD_PREVIEW_GET_DASHBOARD');
export const setLoading = createAction('DASHBOARD_PREVIEW_LOADING');
export const setError = createAction('DASHBOARD_PREVIEW_ERROR');

// Async actions
export const fetchDashboard = createThunkAction('DASHBOARD_PREVIEW_FETCH_DATA', (payload = {}) => (dispatch) => {
  dispatch(setLoading(true));
  dispatch(setError(null));

  return fetch(new Request(`${process.env.API_URL}/dashboards/${payload.id}?env=${process.env.API_ENV}`))
    .then((response) => {
      if (response.ok) return response.json();
      throw new Error(response.statusText);
    })
    .then((data) => {
      dispatch(setLoading(false));
      dispatch(setError(null));
      dispatch(setDashboard(data));
    })
    .catch((err) => {
      dispatch(setLoading(false));
      dispatch(setError(err));
    });
});
import { createAction, createThunkAction } from 'redux-tools';
import CARTO from 'app/services/carto';

export const fetchCellDetailFail = createAction('cellsDetail/FETCH_DATA_FAIL');
export const fetchCellDetailReady = createAction('cellsDetail/FETCH_DATA_READY');

export const fetchCellDetail = createThunkAction('cellsDetail/FETCH_DATA', id => async dispatch => {
  try {
    const response = await CARTO.getDetail(id);
    const data = response.reduce(
      (acc, next) => ({ ...acc, [next.taxa]: { ...next, species: next.species ? next.species.split(',') : [] } }),
      {}
    );
    dispatch(fetchCellDetailReady({ id, data }));
  } catch (e) {
    console.warn(e);
    dispatch(fetchCellDetailFail(e));
  }
});
Example #10
0
      })
      .catch((err) => {
        dispatch({ type: GET_DATASETS_ERROR, payload: err.message });
      });
  };
}

export const getAllDatasets = createThunkAction('datasets/getAllDatasets', options =>
  (dispatch, getState) => {
    dispatch({ type: GET_DATASETS_LOADING });
    const { user } = getState();

    return DatasetsService.getAllDatasets(user.token, { ...options })
      .then(({ data, meta }) => {
        const { 'total-items': totalItems } = meta;
        dispatch({
          type: GET_DATASETS_SUCCESS,
          payload: data.map(d => ({ ...{ id: d.id, type: d.type }, ...d.attributes }))
        });
        dispatch(setPaginationTotal(totalItems));
      })
      .catch((err) => {
        dispatch({ type: GET_DATASETS_ERROR, payload: err.message });
      });
  });

export const getDatasetsByTab = createThunkAction('datasets/getDatasetsByTab', tab =>
  (dispatch, getState) => {
    const { user, datasets } = getState();
    const { id } = user;
    const { orderDirection, pagination, filters } = datasets.datasets;
    const { page, limit } = pagination;
export const setSidebar = createAction('explore/setSidebar');

// Update URL
export const updateURLParams = createThunkAction('updateURLParams', () => (dispatch, getState) => {
  const { explorePage, routing } = getState();
  const { tab, datasets, coreDatasets, datasetFilters, map } = explorePage;
  const { location } = coreDatasets;
  const { filters } = datasetFilters;
  const { filterQuery, activeDatasets } = datasets;
  const activeDatasetsResult = activeDatasets && activeDatasets.length ?
    activeDatasets.map(({ id, opacity, visibility, zIndex }) => `${id}|${opacity}|${visibility}|${zIndex}`) : [];
  const filtersParams = {};

  (Object.keys(filters) || []).forEach((key) => {
    Object.assign(filtersParams, { [key]: filters[key].join(',') });
  });

  const query = {
    ...omit(map, 'bbox'),
    tab,
    filterQuery,
    ...filtersParams,
    location,
    activeDatasets: activeDatasetsResult
  };

  dispatch(replace({ pathname: routing.locationBeforeTransitions.pathname, query }));
});

export const setTab = createThunkAction('setTab', () => (dispatch) => {
  dispatch(updateURLParams());
Example #12
0
import { createAction, createThunkAction } from 'redux-tools';
import { setComponentStateToUrl } from 'utils/stateToUrl';

import { submitContactForm } from 'services/forms';

export const setModalContactUsOpen = createThunkAction(
  'setModalContactUsOpen',
  isOpen => (dispatch, state) => {
    dispatch(
      setComponentStateToUrl({
        key: 'contactUs',
        change: isOpen,
        state
      })
    );
    dispatch(setShowConfirm(false));
  }
);

export const setShowConfirm = createAction('setShowConfirm');
export const setFormSubmitting = createAction('setFormSubmitting');

export const sendContactForm = createThunkAction(
  'sendContactForm',
  data => dispatch => {
    dispatch(setFormSubmitting({ submitting: true, error: false }));
    submitContactForm(data)
      .then(() => {
        dispatch(setShowConfirm(true));
      })
      .catch(error => {
  'setRegionWhitelistLoading'
);

export const setCountryWhitelist = createAction('setCountryWhitelist');
export const setRegionWhitelist = createAction('setRegionWhitelist');

export const getCountryWhitelist = createThunkAction(
  'getCountryWhitelist',
  adm0 => (dispatch, getState) => {
    const { whitelists } = getState();
    if (whitelists && !whitelists.countriesLoading) {
      dispatch(setCountryWhitelistLoading(true));
      getCountryWhitelistProvider(adm0)
        .then(response => {
          const data =
            response.data.data && response.data.data.map(d => d.polyname);
          dispatch(setCountryWhitelist(data));
        })
        .catch(error => {
          dispatch(setCountryWhitelistLoading(false));
          console.info(error);
        });
    }
  }
);

export const getRegionWhitelist = createThunkAction(
  'getRegionWhitelist',
  ({ adm0, adm1, adm2 }) => (dispatch, getState) => {
    const { whitelists } = getState();
    if (whitelists && !whitelists.regionsLoading) {
// Insight actions
export const setInsight = createAction('INSIGHT_BLOCK_GET');
export const setInsightLoading = createAction('INSIGHT_BLOCK_LOADING');
export const setInsightError = createAction('INSIGHT_BLOCK_ERROR');
export const setInsightModal = createAction('INSIGHT_BLOCK_MODAL');
export const removeInsight = createAction('INSIGHT_BLOCK_REMOVE');

// Async actions
export const fetchInsight = createThunkAction('INSIGHT_BLOCK_FETCH_DATA', (payload = {}) => (dispatch) => {
  const id = `${payload.id}/${payload.itemId}`;

  dispatch(setInsightLoading({ id, value: true }));
  dispatch(setInsightError({ id, value: null }));

  fetch(`${process.env.API_URL}/insights/${payload.id}`)
    .then((response) => {
      if (response.ok) return response.json();
      throw new Error(response.statusText);
    })
    .then((data) => {
      dispatch(setInsightLoading({ id, value: false }));
      dispatch(setInsightError({ id, value: null }));
      dispatch(setInsight({ id, value: data }));
    })
    .catch((err) => {
      dispatch(setInsightLoading(false));
      dispatch(setInsightError(err));
    });
});