From 7d513a89e6592d4ab4ac4d3682fc723bdcd9a2b5 Mon Sep 17 00:00:00 2001 From: Brijesh Date: Wed, 21 Aug 2024 12:32:56 -0700 Subject: [PATCH 1/2] refactor search agreements --- src/actionCreators/index.js | 96 ++---- src/actions/updateActions.js | 5 - .../pageForStaff/UpdateZoneModal.js | 157 --------- .../rangeUsePlanPage/pageForStaff/index.js | 14 +- .../SortableAgreementTable.js | 151 +++----- .../selectRangeUsePlanPage/ZoneSelect.js | 71 ++-- .../selectRangeUsePlanPage/index.js | 322 +++++++----------- src/components/theme.js | 4 +- src/constants/actionTypes.js | 1 - src/reducers/commonStoreReducer.js | 13 - 10 files changed, 255 insertions(+), 579 deletions(-) delete mode 100644 src/components/rangeUsePlanPage/pageForStaff/UpdateZoneModal.js diff --git a/src/actionCreators/index.js b/src/actionCreators/index.js index f782cd49..a9d9db62 100644 --- a/src/actionCreators/index.js +++ b/src/actionCreators/index.js @@ -1,32 +1,9 @@ -// -// MyRangeBC -// -// Copyright © 2018 Province of British Columbia -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Created by Kyubin Han. -// import { normalize } from 'normalizr'; import * as schema from './schema'; import * as actions from '../actions'; import * as reducerTypes from '../constants/reducerTypes'; import * as API from '../constants/api'; -import { - getIsFetchingAgreements, - getAuthTimeout, - getUser, -} from '../reducers/rootReducer'; +import { getAuthTimeout, getUser } from '../reducers/rootReducer'; import { axios, saveUserProfileInLocal, @@ -38,7 +15,6 @@ import { ASSIGN_STAFF_TO_ZONE_SUCCESS, UPDATE_USER_PROFILE_SUCCESS, } from '../constants/strings'; -import { DEFAULT_SEARCH_LIMIT } from '../constants/variables'; export * from './planActionCreator'; export * from './toastActionCreator'; @@ -178,38 +154,38 @@ export const updateUser = (data) => (dispatch, getState) => { ); }; -export const searchAgreements = (params) => (dispatch, getState) => { - const { page = 1, limit = DEFAULT_SEARCH_LIMIT } = params; - - if (getIsFetchingAgreements(getState())) { - return Promise.resolve(); - } - dispatch(actions.request(reducerTypes.SEARCH_AGREEMENTS)); - - const config = { - ...createConfigWithHeader(getState), - params: { - page: Number(page), - limit: Number(limit), - }, - }; - - return axios.get(API.SEARCH_AGREEMENTS, config).then( - (response) => { - dispatch( - actions.successPagenated(reducerTypes.SEARCH_AGREEMENTS, response.data), - ); - const payload = { - ...normalize(response.data.agreements, schema.arrayOfAgreements), - params, - }; - - dispatch(actions.storeAgreements(payload)); - return response.data; - }, - (err) => { - dispatch(actions.error(reducerTypes.SEARCH_AGREEMENTS, err)); - throw err; - }, - ); -}; +// export const searchAgreements = (params) => (dispatch, getState) => { +// const { page = 1, limit = DEFAULT_SEARCH_LIMIT } = params; +// +// if (getIsFetchingAgreements(getState())) { +// return Promise.resolve(); +// } +// dispatch(actions.request(reducerTypes.SEARCH_AGREEMENTS)); +// +// const config = { +// ...createConfigWithHeader(getState), +// params: { +// page: Number(page), +// limit: Number(limit), +// }, +// }; +// +// return axios.get(API.SEARCH_AGREEMENTS, config).then( +// (response) => { +// dispatch( +// actions.successPagenated(reducerTypes.SEARCH_AGREEMENTS, response.data), +// ); +// const payload = { +// ...normalize(response.data.agreements, schema.arrayOfAgreements), +// params, +// }; +// +// dispatch(actions.storeAgreements(payload)); +// return response.data; +// }, +// (err) => { +// dispatch(actions.error(reducerTypes.SEARCH_AGREEMENTS, err)); +// throw err; +// }, +// ); +// }; diff --git a/src/actions/updateActions.js b/src/actions/updateActions.js index 4ee086f5..be1f768e 100644 --- a/src/actions/updateActions.js +++ b/src/actions/updateActions.js @@ -5,11 +5,6 @@ export const agreementSearchChanged = (payload) => ({ payload, }); -export const zoneUpdated = (payload) => ({ - type: actionTypes.ZONE_UPDATED, - payload, -}); - export const userUpdated = (payload) => ({ type: actionTypes.USER_UPDATED, payload, diff --git a/src/components/rangeUsePlanPage/pageForStaff/UpdateZoneModal.js b/src/components/rangeUsePlanPage/pageForStaff/UpdateZoneModal.js deleted file mode 100644 index 41b81ceb..00000000 --- a/src/components/rangeUsePlanPage/pageForStaff/UpdateZoneModal.js +++ /dev/null @@ -1,157 +0,0 @@ -import React, { Component } from 'react'; -import { connect } from 'react-redux'; -import PropTypes from 'prop-types'; -import { Header, Dropdown, Modal, Icon } from 'semantic-ui-react'; -import { updateAgreementZone } from '../../../actionCreators'; -import { ELEMENT_ID } from '../../../constants/variables'; -import { - getZones, - getIsUpdatingAgreementZone, -} from '../../../reducers/rootReducer'; -import { planUpdated } from '../../../actions'; -import { NOT_ASSIGNED, NO_DESCRIPTION } from '../../../constants/strings'; -import { getUserFullName } from '../../../utils'; -import { PrimaryButton } from '../../common'; - -// the componenet is no longer needed since the database is periodically updated by FTA apis -export class UpdateZoneModal extends Component { - static propTypes = { - agreement: PropTypes.shape({ zone: PropTypes.object }).isRequired, - plan: PropTypes.shape({}).isRequired, - isUpdateZoneModalOpen: PropTypes.bool.isRequired, - closeUpdateZoneModal: PropTypes.func.isRequired, - updateAgreementZone: PropTypes.func.isRequired, - zones: PropTypes.arrayOf(PropTypes.object).isRequired, - isUpdatingAgreementZone: PropTypes.bool.isRequired, - planUpdated: PropTypes.func.isRequired, - }; - - state = { - newZoneId: null, - }; - - onZoneChanged = (e, { value }) => { - this.setState({ newZoneId: value }); - }; - - onUpdateZoneClicked = () => { - const { agreement, updateAgreementZone, planUpdated, plan } = this.props; - const requestData = { - agreementId: agreement.id, - zoneId: this.state.newZoneId, - }; - const onZoneUpdated = (newZone) => { - const newAgreement = { ...plan.agreement, zone: newZone }; - const newPlan = { - ...plan, - agreement: newAgreement, - }; - planUpdated({ plan: newPlan }); - }; - updateAgreementZone(requestData).then((newZone) => { - onZoneUpdated(newZone); - this.closeUpdateZoneModal(); - }); - }; - - closeUpdateZoneModal = () => { - this.setState({ newZoneId: null }); - this.props.closeUpdateZoneModal(); - }; - - render() { - const { isUpdateZoneModalOpen, zones, isUpdatingAgreementZone, agreement } = - this.props; - const { newZoneId } = this.state; - - const currZone = agreement && agreement.zone; - const currDistrictId = currZone.district && currZone.district.id; - const currZoneCode = currZone.code; - const zoneOptions = zones - .filter( - (zone) => - zone.districtId === currDistrictId && zone.code !== currZoneCode, - ) - .map((z) => { - const { - id: zoneId, - code: zoneCode, - user: staff, - description: zoneDescription, - } = z; - const option = { - value: zoneId, - text: zoneCode, - description: NOT_ASSIGNED, - }; - let description = zoneDescription; - if ( - zoneDescription === 'Please update contact and description' || - zoneDescription === 'Please update contact' - ) { - description = NO_DESCRIPTION; - } - option.text += ` (${description})`; - if (staff) { - option.description = getUserFullName(staff); - } - - return option; - }); - - return ( - } - > - Update Zone - -
Pick a new zone within the district
- -
- - -
-
-
- ); - } -} - -const mapStateToProps = (state) => ({ - isUpdatingAgreementZone: getIsUpdatingAgreementZone(state), - zones: getZones(state), -}); - -export default connect(mapStateToProps, { - updateAgreementZone, - planUpdated, -})(UpdateZoneModal); diff --git a/src/components/rangeUsePlanPage/pageForStaff/index.js b/src/components/rangeUsePlanPage/pageForStaff/index.js index 7b3d23ab..734a87a3 100644 --- a/src/components/rangeUsePlanPage/pageForStaff/index.js +++ b/src/components/rangeUsePlanPage/pageForStaff/index.js @@ -1,5 +1,4 @@ import React, { Component } from 'react'; -import UpdateZoneModal from './UpdateZoneModal'; import { REFERENCE_KEY, PLAN_STATUS, @@ -32,7 +31,6 @@ class PageForStaff extends Component { static defaultProps = defaultProps; state = { - isUpdateZoneModalOpen: false, isPlanSubmissionModalOpen: false, isSavingAsDraft: false, isCreatingAmendment: false, @@ -141,8 +139,6 @@ class PageForStaff extends Component { } }; - openUpdateZoneModal = () => this.setState({ isUpdateZoneModalOpen: true }); - closeUpdateZoneModal = () => this.setState({ isUpdateZoneModalOpen: false }); openPlanSubmissionModal = () => { const error = this.validateRup(this.props.plan); if (!error) { @@ -212,7 +208,6 @@ class PageForStaff extends Component { render() { const { - agreement, user, clientAgreements, references, @@ -221,7 +216,7 @@ class PageForStaff extends Component { fetchPlan, updateRUPStatus, } = this.props; - const { isUpdateZoneModalOpen, isPlanSubmissionModalOpen } = this.state; + const { isPlanSubmissionModalOpen } = this.state; const { agreementId, status, rangeName } = plan; @@ -235,13 +230,6 @@ class PageForStaff extends Component { return (
- - (event) => { - onRequestSort(event, property); - }; - const filterHandler = (event, property) => { - onRequestFilter(event, property); - }; - return ( @@ -106,14 +98,16 @@ function EnhancedTableHead(props) { { + headCell.sortable && onRequestSort(event, headCell.id); + }} hideSortIcon={!headCell.sortable} disabled={!headCell.sortable} > @@ -127,16 +121,24 @@ function EnhancedTableHead(props) { {headCell.filterable && ( filterHandler(e, headCell.id)} + onChange={(e) => onColumnFilterChange(e, headCell.id)} value={ - Object.hasOwn(filters, headCell.id) - ? props.filters[headCell.id] + Object.hasOwn(columnFilters, headCell.id) + ? columnFilters[headCell.id] : '' } /> )} - {headCell.multiSelectable && ( - + {headCell.id == 'plan.status_id' && ( + + onColumnFilterChange( + { target: { value: newStatusCodes } }, + headCell.id, + ) + } + selectedStatusCodes={columnFilters[headCell.id] || []} + /> )} ))} @@ -145,8 +147,7 @@ function EnhancedTableHead(props) { ); } -const StatusCodesMultiSelect = (props) => { - const { onStatusCodeChange } = props; +const StatusMultiSelect = ({ onStatusCodeChange, selectedStatusCodes }) => { const ITEM_HEIGHT = 48; const ITEM_PADDING_TOP = 8; const references = useReferences(); @@ -167,18 +168,25 @@ const StatusCodesMultiSelect = (props) => { return statusObject; }) .sort((a, b) => a.name.localeCompare(b.name)); - const [selectedStatusName, setSelectedStatusName] = React.useState([]); + const handleChange = (event) => { setSelectedStatusName(event.target.value); - }; - useEffect(() => { - const selectedStatusCodes = selectedStatusName.map((statusName) => { + const selectedStatusCodes = event.target.value.map((statusName) => { const match = statusObjects.find((st) => st.name === statusName); return match.code; }); onStatusCodeChange(selectedStatusCodes); - }, [selectedStatusName]); + }; + + useEffect(() => { + setSelectedStatusName( + selectedStatusCodes.map((code) => { + const match = statusObjects.find((st) => st.code === code); + return match.name; + }), + ); + }, [selectedStatusCodes]); return ( @@ -192,11 +200,7 @@ const StatusCodesMultiSelect = (props) => { {statusObjects.map((statusObject) => ( statusName === statusObject.name, - ) !== -1 - } + checked={selectedStatusName.indexOf(statusObject.name) !== -1} /> @@ -269,11 +273,10 @@ export default function SortableAgreementTable({ totalAgreements, perPage, onOrderChange, - onFilterChange, + onColumnFilterChange, orderBy, order, - filters, - onStatusCodeChange, + columnFilters, }) { const classes = useStyles(); const user = useUser(); @@ -285,35 +288,14 @@ export default function SortableAgreementTable({ onOrderChange(property, isAsc ? 'desc' : 'asc'); }; - const handleFilterChange = (event, property) => { - onFilterChange(property, event.target.value); + const handleColumnFilterChange = (event, property) => { + onColumnFilterChange(property, event.target.value); }; - const handleStatusFilterChange = (selectedStatusCodes) => { - onStatusCodeChange('plan.status_id', selectedStatusCodes); - }; - - const handleChangePage = (event, newPage) => { - onPageChange(newPage); - }; - - const handleChangeRowsPerPage = (event) => { - onLimitChange(parseInt(event.target.value, 10)); - onPageChange(0); - }; - - const getNumberOfRows = () => { - let rowCount = 0; - agreements.forEach((agreement) => { - rowCount = rowCount + agreement.plans?.length; - }); - return rowCount; - }; - const emptyRows = Math.abs(getNumberOfRows() - perPage); - return (
+ {loading && } - {agreements.length === 0 && - loading && - Array.from({ length: perPage }).map((_, i) => ( - - - - - - - - - ))} {agreements.length > 0 && + !loading && agreements.map((agreement, index) => { return ( ); })} - {agreements.length > 0 && emptyRows > 0 && ( - - - - )} - {agreements.length === 0 && !loading && ( @@ -383,15 +338,19 @@ export default function SortableAgreementTable({
- + {!loading && ( + onPageChange(event, newPage)} + onRowsPerPageChange={(event) => { + onLimitChange(parseInt(event.target.value, 10)); + }} + /> + )}
); diff --git a/src/components/selectRangeUsePlanPage/ZoneSelect.js b/src/components/selectRangeUsePlanPage/ZoneSelect.js index 46a2fd56..f41a2429 100644 --- a/src/components/selectRangeUsePlanPage/ZoneSelect.js +++ b/src/components/selectRangeUsePlanPage/ZoneSelect.js @@ -7,15 +7,14 @@ import FormControl from '@material-ui/core/FormControl'; import ListItemText from '@material-ui/core/ListItemText'; import Select from '@material-ui/core/Select'; import Checkbox from '@material-ui/core/Checkbox'; -import { - getUserFullName, - axios, - getAuthHeaderConfig, +import { + getUserFullName, + axios, + getAuthHeaderConfig, getDataFromLocalStorage, - saveDataInLocalStorage + saveDataInLocalStorage, } from '../../utils'; import * as API from '../../constants/api'; -import { useQueryParam, DelimitedNumericArrayParam } from 'use-query-params'; import { FormControlLabel } from '@material-ui/core'; const useStyles = makeStyles((theme) => ({ @@ -71,26 +70,23 @@ const MenuProps = { // Persisting zone information in localstorage const setSaveZoneInfo = (allSelected, allDeselected, zones) => { - const currZoneInfo = getDataFromLocalStorage("zone-info"); + const currZoneInfo = getDataFromLocalStorage('zone-info'); const zoneInfo = { ...currZoneInfo, allSelected: allSelected, allDeselected: allDeselected, - zones: zones - } - saveDataInLocalStorage("zone-info", zoneInfo); -} + zones: zones, + }; + saveDataInLocalStorage('zone-info', zoneInfo); +}; export function ZoneSelectAll({ zones, setSearchSelectedZones }) { const classes = useStyles(); - const [selectedZones = [], setSelectedZones] = useQueryParam( - 'selectedZones', - DelimitedNumericArrayParam, - ); + const [selectedZones, setSelectedZones] = useState([]); const [zoneMap, setZoneMap] = useState(); const [selectAllZones, setSelectAllZones] = useState(true); const [deselectAllZones, setDeselectAllZones] = useState(false); - const zoneInfo = getDataFromLocalStorage("zone-info"); + const zoneInfo = getDataFromLocalStorage('zone-info'); const { data: users, @@ -104,7 +100,6 @@ export function ZoneSelectAll({ zones, setSearchSelectedZones }) { const setAllZonesSelected = () => { const initialSelectedZones = zones.map((zone) => zone.id); setSelectedZones(initialSelectedZones); - setSearchSelectedZones(initialSelectedZones); }; useEffect(() => { @@ -116,7 +111,6 @@ export function ZoneSelectAll({ zones, setSearchSelectedZones }) { setSelectAllZones(false); } if (zoneInfo?.allDeselected) { - setSearchSelectedZones([]); setSelectedZones([]); setSelectAllZones(false); setDeselectAllZones(true); @@ -124,19 +118,21 @@ export function ZoneSelectAll({ zones, setSearchSelectedZones }) { if (zoneInfo?.zones) { setSelectedZones(zoneInfo.zones); - setSearchSelectedZones(zoneInfo.zones); } else if (selectedZones.length === 0) { setAllZonesSelected(); + setSelectAllZones(true); } else { if (!selectedZones.length) { setAllZonesSelected(); } else { setSelectedZones(selectedZones); - setSearchSelectedZones(selectedZones); } } }, []); + useEffect(() => { + setSearchSelectedZones(selectedZones); + }, [selectedZones]); useEffect(() => { if (zones) { const zoneMap = zones.reduce( @@ -156,7 +152,6 @@ export function ZoneSelectAll({ zones, setSearchSelectedZones }) { }; const handleClose = () => { - setSearchSelectedZones(selectedZones); if (zones?.length === selectedZones?.length) { setSelectAllZones(true); } else { @@ -186,7 +181,11 @@ export function ZoneSelectAll({ zones, setSearchSelectedZones }) { if (event.target.checked) { setAllZonesSelected(); setDeselectAllZones(!event.target.checked); - setSaveZoneInfo(true, false, zones.map((zone) => zone.id)); + setSaveZoneInfo( + true, + false, + zones.map((zone) => zone.id), + ); } }} name="selectAllZones" @@ -202,7 +201,6 @@ export function ZoneSelectAll({ zones, setSearchSelectedZones }) { onChange={(event) => { setDeselectAllZones(event.target.checked); if (event.target.checked) { - setSearchSelectedZones([]); setSelectedZones([]); setSelectAllZones(!event.target.checked); setSaveZoneInfo(false, true, []); @@ -276,14 +274,11 @@ export default function ZoneSelect({ setSearchSelectedZones, }) { const classes = useStyles(); - const [selectedZones = [], setSelectedZones] = useQueryParam( - 'selectedZones', - DelimitedNumericArrayParam, - ); + const [selectedZones, setSelectedZones] = useState([]); const [zoneMap, setZoneMap] = useState(); const [selectAllZones, setSelectAllZones] = useState(true); const [deselectAllZones, setDeselectAllZones] = useState(false); - const zoneInfo = getDataFromLocalStorage("zone-info"); + const zoneInfo = getDataFromLocalStorage('zone-info'); const { data: users, @@ -294,16 +289,19 @@ export default function ZoneSelect({ (key) => axios.get(key, getAuthHeaderConfig()).then((res) => res.data), ); + useEffect(() => { + setSearchSelectedZones(selectedZones); + }, [selectedZones]); + useEffect(() => { if (zoneInfo?.allSelected) { setAllZonesSelected(); setSelectAllZones(true); setDeselectAllZones(false); - } else if(zoneInfo) { + } else if (zoneInfo) { setSelectAllZones(false); } if (zoneInfo?.allDeselected) { - setSearchSelectedZones([]); setSelectedZones([]); setSelectAllZones(false); setDeselectAllZones(true); @@ -311,7 +309,6 @@ export default function ZoneSelect({ if (zoneInfo?.zones) { setSelectedZones(zoneInfo.zones); - setSearchSelectedZones(zoneInfo.zones); } else if (userZones && userZones.length > 0) { if (selectedZones.length === 0) { setAllZonesSelected(); @@ -329,11 +326,8 @@ export default function ZoneSelect({ setAllZonesSelected(); } else { setSelectedZones(filteredSelectedZones); - setSearchSelectedZones(filteredSelectedZones); } } - } else { - setSearchSelectedZones(selectedZones); } }, []); @@ -356,7 +350,6 @@ export default function ZoneSelect({ }; const handleClose = () => { - setSearchSelectedZones(selectedZones); if (userZones.concat(unassignedZones)?.length === selectedZones?.length) { setSelectAllZones(true); setSaveZoneInfo(true, false, selectedZones); @@ -373,7 +366,6 @@ export default function ZoneSelect({ .concat(unassignedZones) .map((zone) => zone.id); setSelectedZones(initialSelectedZones); - setSearchSelectedZones(initialSelectedZones); }; if ((isValidating && !users) || !zoneMap) { @@ -395,7 +387,11 @@ export default function ZoneSelect({ if (event.target.checked) { setAllZonesSelected(); setDeselectAllZones(!event.target.checked); - setSaveZoneInfo(true, false, zones.map((zone) => zone.id)); + setSaveZoneInfo( + true, + false, + zones.map((zone) => zone.id), + ); } }} name="selectAllZones" @@ -411,7 +407,6 @@ export default function ZoneSelect({ onChange={(event) => { setDeselectAllZones(event.target.checked); if (event.target.checked) { - setSearchSelectedZones([]); setSelectedZones([]); setSelectAllZones(!event.target.checked); setSaveZoneInfo(false, true, []); diff --git a/src/components/selectRangeUsePlanPage/index.js b/src/components/selectRangeUsePlanPage/index.js index 2a7f80c1..946a847a 100644 --- a/src/components/selectRangeUsePlanPage/index.js +++ b/src/components/selectRangeUsePlanPage/index.js @@ -1,14 +1,7 @@ +import React, { useEffect, useState, useCallback } from 'react'; +import debounce from 'lodash.debounce'; import { Checkbox, FormControlLabel, Tooltip } from '@material-ui/core'; import { makeStyles, withStyles } from '@material-ui/core/styles'; -import React, { useEffect, useState } from 'react'; -import useSWR from 'swr'; -import { - BooleanParam, - StringParam, - decodeObject, - encodeObject, - useQueryParam, -} from 'use-query-params'; import * as API from '../../constants/api'; import { SELECT_RUP_BANNER_CONTENT, @@ -19,30 +12,18 @@ import { TOOLTIP_TEXT_RUP_CREATED, } from '../../constants/strings'; import { useReferences } from '../../providers/ReferencesProvider'; -import { useToast } from '../../providers/ToastProvider'; import { useUser } from '../../providers/UserProvider'; import { axios, getAuthHeaderConfig, - getDataFromLocalStorage, isUserAdmin, isUserAgrologist, + getDataFromLocalStorage, saveDataInLocalStorage, } from '../../utils'; -import useDebounce from '../../utils/hooks/useDebounce'; import { Banner } from '../common'; -import Error from './Error'; -import ZoneSelect, { ZoneSelectAll } from './ZoneSelect'; - import SortableAgreementTable from './SortableAgreementTable'; - -const keyValueSeparator = '-'; // default is "-" -const entrySeparator = '~'; // default is "_" -const NewObjectParam = { - encode: (obj) => encodeObject(obj, keyValueSeparator, entrySeparator), - - decode: (str) => decodeObject(str, keyValueSeparator, entrySeparator), -}; +import ZoneSelect, { ZoneSelectAll } from './ZoneSelect'; const useStyles = makeStyles(() => ({ searchFilterContainer: { @@ -58,146 +39,131 @@ const useStyles = makeStyles(() => ({ margin: '0 1rem', }, })); + const StyledTooltip = withStyles((theme) => ({ tooltip: { fontSize: theme.typography.pxToRem(14), }, }))(Tooltip); -const SelectRangeUsePlanPage = ({ match, history }) => { - const { page = 1 } = match.params; - const debouncedPage = useDebounce(page, 500); - const [toastId, setToastId] = useState(); - const [limit = 10, setLimit] = useQueryParam('limit', StringParam); - const debouncedLimit = useDebounce(limit, 500); - const [searchSelectedZones, setSearchSelectedZones] = useState([]); - const debouncedZones = useDebounce(searchSelectedZones, 500); - const [orderBy = 'agreement.forest_file_id', setOrderBy] = useQueryParam( - 'orderBy', - StringParam, - ); - const debouncedOrderBy = useDebounce(orderBy, 500); - const [order = 'asc', setOrder] = useQueryParam('order', StringParam); - const debouncedOrder = useDebounce(order, 500); - const filterInfo = getDataFromLocalStorage('filter-info'); - const [ - filters = { agreementCheck: 'true', showReplacedPlans: 'false' }, - setFilters, - ] = useQueryParam('filters', NewObjectParam); - const debouncedFilters = useDebounce(filters, 500); - const [filtersInitialized, setFiltersInitialized] = useState(false); - // startup - useEffect(() => { - // Set initial page info from localstorage - const pageInfo = getDataFromLocalStorage('page-info'); - if (pageInfo) { - if (pageInfo.pageNumber) setPage(pageInfo.pageNumber); - if (pageInfo.pageLimit) setLimit(pageInfo.pageLimit); - } - setFiltersInitialized(true); // Workaround flag for checkbox racing the filter initialization - }, []); - const [planCheck = filterInfo?.planCheck || false, setPlanCheck] = - useQueryParam('planCheck', BooleanParam); - const [ - agreementCheck = filterInfo?.agreementCheck !== undefined - ? filterInfo.agreementCheck - : true, - setAgreementCheck, - ] = useQueryParam('agreementCheck', BooleanParam); - const [activeCheck = filterInfo?.activeCheck || false, setActiveCheck] = - useQueryParam('activeCheck', BooleanParam); - const [ - showReplacedPlans = filterInfo?.showReplacedPlans || false, - setShowReplacedPlans, - ] = useQueryParam('showReplacedPlans', BooleanParam); - useEffect(() => { - if (filtersInitialized) addToFilters('planCheck', planCheck); - }, [planCheck]); - useEffect(() => { - if (filtersInitialized) addToFilters('agreementCheck', agreementCheck); - }, [agreementCheck]); - useEffect(() => { - if (filtersInitialized) addToFilters('activeCheck', activeCheck); - }, [activeCheck]); - useEffect(() => { - if (filtersInitialized) - addToFilters('showReplacedPlans', showReplacedPlans); - }, [showReplacedPlans]); - const { warningToast, removeToast, errorToast } = useToast(); +const SelectRangeUsePlanPage = () => { + const [filterSettings, setFilterSettings] = useState({ + page: 1, + limit: 10, + orderBy: 'agreement.forest_file_id', + order: 'asc', + agreementCheck: true, + showReplacedPlans: false, + planCheck: false, + activeCheck: false, + statusCodes: '', + columnFilters: {}, + }); + + const [loading, setLoading] = useState(false); + const [data, setData] = useState(null); const references = useReferences(); const user = useUser(); const zones = references.ZONES || []; const userZones = zones.filter((zone) => user.id === zone.userId); - const districtIds = userZones.map((userZone) => { - return userZone.districtId; - }); + const districtIds = userZones.map((userZone) => userZone.districtId); + + const fetchAgreements = useCallback( + debounce(async (settings) => { + setLoading(true); + saveDataInLocalStorage('filterSettings', settings); + try { + const response = await axios.get(API.SEARCH_AGREEMENTS, { + ...getAuthHeaderConfig(), + params: { filterSettings: settings }, + }); + setData(response.data); + } catch (error) { + console.error('Error fetching agreements:', error); + } finally { + setLoading(false); + } + }, 300), // 300ms delay + [], + ); + + useEffect(() => { + const storedFilterSettings = getDataFromLocalStorage('filterSettings'); + if (storedFilterSettings) { + setFilterSettings((prevSettings) => ({ + ...prevSettings, + ...storedFilterSettings, + page: storedFilterSettings.page || 1, + limit: storedFilterSettings.limit || 10, + })); + } + }, []); + + useEffect(() => { + fetchAgreements(filterSettings); + }, [filterSettings, fetchAgreements]); + const unassignedZones = zones.filter( (zone) => - user.id !== zone.userId && districtIds.indexOf(zone.districtId) != -1, + user.id !== zone.userId && districtIds.indexOf(zone.districtId) !== -1, ); - const zoneUsers = references.USERS; - const { data, error, revalidate, isValidating } = useSWR( - `${API.SEARCH_AGREEMENTS}?page=${debouncedPage}&selectedZones=${debouncedZones}&limit=${debouncedLimit}&orderBy=${debouncedOrderBy}&order=${debouncedOrder}&filterString=${JSON.stringify(debouncedFilters)}`, - (key) => axios.get(key, getAuthHeaderConfig()).then((res) => res.data), - { - onLoadingSlow: () => { - setToastId(warningToast('Agreements are taking a while to load', -1)); - }, - onError: () => { - if (references?.ZONES?.length > 0) - errorToast('Could not load agreements'); - }, - onSuccess: () => removeToast(toastId), - }, - ); + const zoneUsers = references.USERS; + const { agreements, totalPages, totalItems } = data || {}; + const classes = useStyles(); - const addToFilters = (filterCol, filterVal) => { - let newFilter = { - ...filters, - }; - newFilter[filterCol] = filterVal; - setFilters(newFilter); + const handleFilterChange = (field) => (event) => { + setFilterSettings((prevSettings) => ({ + ...prevSettings, + [field]: event.target.checked, + })); }; - const setPage = (page) => { - history.replace(`/home/${page}/${history.location.search}`); + const handlePageChange = (event, page) => { + setFilterSettings((prevSettings) => ({ + ...prevSettings, + page: page + 1, + })); }; - const setPageAndSave = (page) => { - history.replace(`/home/${page}/${history.location.search}`); - const currPageInfo = getDataFromLocalStorage('page-info'); - const pageInfo = { - ...currPageInfo, - pageNumber: page, - }; - saveDataInLocalStorage('page-info', pageInfo); + const handleLimitChange = (limit) => { + setFilterSettings((prevSettings) => ({ + ...prevSettings, + limit, + page: 1, // Reset to first page when limit changes + })); }; - const setPageLimitAndSave = (limit) => { - const currPageInfo = getDataFromLocalStorage('page-info'); - const pageInfo = { - ...currPageInfo, - pageLimit: limit, - }; - saveDataInLocalStorage('page-info', pageInfo); - setLimit(limit); + const handleOrderChange = (orderBy, order) => { + setFilterSettings((prevSettings) => ({ + ...prevSettings, + orderBy, + order, + })); }; - const setSaveFilterInfo = (filterCol, value) => { - if (!filtersInitialized) return; // Avoid empty update + const handleColumnFilterChange = (column, value) => { + setFilterSettings((prevSettings) => { + const columnFilters = { ...prevSettings.columnFilters }; + if (value === '') { + delete columnFilters[column]; + } else { + columnFilters[column] = value; + } + return { ...prevSettings, columnFilters, page: 1 }; + }); + }; - const currFilterInfo = getDataFromLocalStorage('filter-info'); - const filterInfo = { - ...currFilterInfo, - }; - filterInfo[filterCol] = value; - saveDataInLocalStorage('filter-info', filterInfo); + const handleSelectedZonesChange = (selectedZones) => { + setFilterSettings((prevSettings) => { + return { + ...prevSettings, + selectedZones, + }; + }); }; - const { agreements, totalPages, currentPage = page, totalItems } = data || {}; - const classes = useStyles(); return (
{ { - setPlanCheck(!planCheck); - setSaveFilterInfo('planCheck', !planCheck); - }} + checked={filterSettings.planCheck} + onChange={handleFilterChange('planCheck')} name="planCheck" color="primary" /> @@ -226,11 +189,8 @@ const SelectRangeUsePlanPage = ({ match, history }) => { { - setAgreementCheck(!agreementCheck); - setSaveFilterInfo('agreementCheck', !agreementCheck); - }} + checked={filterSettings.agreementCheck} + onChange={handleFilterChange('agreementCheck')} name="agreementCheck" color="primary" /> @@ -242,11 +202,8 @@ const SelectRangeUsePlanPage = ({ match, history }) => { { - setActiveCheck(!activeCheck); - setSaveFilterInfo('activeCheck', !activeCheck); - }} + checked={filterSettings.activeCheck} + onChange={handleFilterChange('activeCheck')} name="activeCheck" color="primary" /> @@ -258,12 +215,9 @@ const SelectRangeUsePlanPage = ({ match, history }) => { { - setShowReplacedPlans(!showReplacedPlans); - setSaveFilterInfo('showReplacedPlans', !showReplacedPlans); - }} - name="shwoReplacedPlans" + checked={filterSettings.showReplacedPlans} + onChange={handleFilterChange('showReplacedPlans')} + name="showReplacedPlans" color="primary" /> } @@ -277,51 +231,31 @@ const SelectRangeUsePlanPage = ({ match, history }) => { userZones={userZones} unassignedZones={unassignedZones} zoneUsers={zoneUsers} - setSearchSelectedZones={setSearchSelectedZones} + setSearchSelectedZones={handleSelectedZonesChange} /> )} {isUserAdmin(user) && ( )} - - {error ? ( - - ) : ( - <> - setPageAndSave(page + 1)} - onLimitChange={setPageLimitAndSave} - loading={isValidating} - onOrderChange={(orderBy, order) => { - setOrder(order); - setOrderBy(orderBy); - }} - onFilterChange={(filterCol, filterVal) => { - addToFilters(filterCol, filterVal); - setSaveFilterInfo(filterCol, filterVal); - setPage(1); - }} - orderBy={orderBy} - order={order} - filters={filters} - onStatusCodeChange={(filterCol, filterVal) => { - addToFilters(filterCol, filterVal); - setSaveFilterInfo(filterCol, filterVal); - setPage(1); - }} - /> - - )} +
); }; diff --git a/src/components/theme.js b/src/components/theme.js index e9f42ffc..69065c6a 100644 --- a/src/components/theme.js +++ b/src/components/theme.js @@ -1,6 +1,6 @@ -import { createMuiTheme } from '@material-ui/core'; +import { createTheme } from '@material-ui/core'; -const theme = createMuiTheme({ +const theme = createTheme({ typography: { fontFamily: 'Lato, sans-serif', fontSize: 16, diff --git a/src/constants/actionTypes.js b/src/constants/actionTypes.js index a62cc64e..5b3601b5 100644 --- a/src/constants/actionTypes.js +++ b/src/constants/actionTypes.js @@ -46,7 +46,6 @@ export const PLANT_COMMUNITY_UPDATED = 'PLANT_COMMUNITY_UPDATED'; export const STORE_REFERENCES = 'STORE_REFERENCES'; export const STORE_ZONES = 'STORE_ZONES'; -export const ZONE_UPDATED = 'ZONE_UPDATED'; export const STORE_USERS = 'STORE_USERS'; export const USER_UPDATED = 'USER_UPDATED'; export const STORE_CLIENTS = 'STORE_CLIENTS'; diff --git a/src/reducers/commonStoreReducer.js b/src/reducers/commonStoreReducer.js index b7ea6f75..682ebe09 100644 --- a/src/reducers/commonStoreReducer.js +++ b/src/reducers/commonStoreReducer.js @@ -21,17 +21,6 @@ const initialState = { userIds: [], }; -const updateZone = (state, action) => { - const zone = { ...action.payload }; - return { - ...state, - zones: { - ...state.zones, - [zone.id]: zone, - }, - }; -}; - const storeZones = (state, action) => { const { entities, result } = action.payload; const { zones } = entities; @@ -78,8 +67,6 @@ const commonStoreReducer = (state = initialState, action) => { }; case actionTypes.STORE_ZONES: return storeZones(state, action); - case actionTypes.ZONE_UPDATED: - return updateZone(state, action); case actionTypes.STORE_USERS: return storeUsers(state, action); case actionTypes.USER_UPDATED: From b587ebeab1b19b031ff0f3ddf7435f52eb3bd851 Mon Sep 17 00:00:00 2001 From: Brijesh Date: Thu, 22 Aug 2024 07:25:25 -0700 Subject: [PATCH 2/2] prettier --- .prettierrc | 2 +- src/actionCreators/commonActionCreator.js | 19 +- .../grazingScheduleActionCreator.js | 225 +- src/actionCreators/index.js | 121 +- .../ministerIssueActionCreator.js | 270 +- src/actionCreators/pastureActionCreator.js | 197 +- src/actionCreators/planActionCreator.js | 245 +- ...equirementAndConsiderationActionCreator.js | 104 +- src/actionCreators/schema.js | 8 +- src/api/delete.js | 104 +- src/api/emailtemplate.js | 8 +- src/api/index.js | 160 +- src/api/plan.js | 66 +- src/api/user.js | 41 +- src/components/PageNotFound.js | 11 +- src/components/ReturnPage.js | 11 +- .../assignRolesAndDistrictsPage/index.js | 212 +- src/components/common/Avatar.story.js | 4 +- src/components/common/Banner.js | 9 +- src/components/common/Banner.story.js | 11 +- src/components/common/CollapsibleBox.js | 14 +- src/components/common/ErrorMessage.story.js | 4 +- src/components/common/ErrorPage.js | 5 +- src/components/common/InfoTip.story.js | 9 +- src/components/common/InputModal.js | 14 +- src/components/common/InputModal.story.js | 7 +- src/components/common/ListModal.js | 15 +- src/components/common/Loading.js | 9 +- src/components/common/NetworkStatus.js | 9 +- src/components/common/PermissionsField.js | 16 +- src/components/common/PrimaryButton.story.js | 24 +- src/components/common/Select.js | 9 +- .../common/SortableTableHeaderCell.js | 21 +- src/components/common/Status.js | 31 +- src/components/common/Status.story.js | 11 +- src/components/common/TextField.js | 15 +- .../common/footer/PrivacyInfoModal.js | 46 +- src/components/common/footer/index.js | 30 +- src/components/common/form/DateInputField.js | 9 +- src/components/common/form/DayMonthPicker.js | 268 +- .../common/form/DayMonthPicker.story.js | 4 +- src/components/common/form/DecimalField.js | 16 +- src/components/common/form/ErrorMessage.js | 4 +- src/components/common/form/HelpfulDropdown.js | 11 +- .../common/form/HelpfulDropdown.story.js | 7 +- src/components/common/form/InputRef.js | 6 +- .../common/form/OnSubmitValidationError.js | 7 +- src/components/common/form/PercentField.js | 15 +- src/components/decorators/marginDecorator.js | 4 +- .../decorators/providerDecorator.js | 4 +- src/components/emailTemplatePage/index.js | 39 +- .../loginPage/BrowserWarningHeader.js | 31 +- .../loginPage/BrowserWarningHeader.story.js | 4 +- src/components/loginPage/SignInBox.js | 27 +- src/components/loginPage/SignInButtons.js | 31 +- .../loginPage/SignInErrorMessage.js | 6 +- .../loginPage/SignInErrorMessage.story.js | 4 +- src/components/loginPage/index.js | 75 +- src/components/mainPage/ConfirmModals.js | 28 +- src/components/mainPage/InputModal.js | 15 +- src/components/mainPage/Navbar.js | 41 +- src/components/mainPage/SignInModal.js | 13 +- src/components/mainPage/UsernameInputModal.js | 21 +- src/components/mainPage/index.js | 12 +- .../manageClientPage/ClientDropdown.js | 16 +- .../manageClientPage/ClientLinkList.js | 67 +- src/components/manageClientPage/index.js | 46 +- src/components/mergeAccountPage/index.js | 52 +- src/components/rangeUsePlanPage/ActionBtns.js | 20 +- .../rangeUsePlanPage/AmendFromLegalButton.js | 9 +- src/components/rangeUsePlanPage/BackBtn.js | 4 +- .../rangeUsePlanPage/ImportPastureModal.js | 80 +- .../rangeUsePlanPage/PDFViewFromServer.js | 30 +- src/components/rangeUsePlanPage/PlanForm.js | 61 +- .../rangeUsePlanPage/StickyHeader.js | 5 +- .../SubmitAsMandatoryButton.js | 23 +- .../AdditionalRequirementRow.js | 14 +- .../additionalRequirements/index.js | 29 +- .../additionalRequirements/index.story.js | 35 +- .../attachments/AttachmentRow.js | 40 +- .../rangeUsePlanPage/attachments/index.js | 35 +- .../basicInformation/ManualConfirmation.js | 51 +- .../basicInformation/index.js | 50 +- .../rangeUsePlanPage/conditions/index.js | 21 +- .../AddableMinisterIssueActionList.js | 37 +- .../EditableMinisterIssueActionBox.js | 28 +- .../MinisterIssueBox.js | 20 +- .../editableMinisterIssues/index.js | 12 +- .../grazingSchedules/GrazingScheduleBox.js | 191 +- .../GrazingScheduleBox.test.js | 152 - .../GrazingScheduleEntryRow.js | 45 +- .../GrazingScheduleEntryRow.test.js | 187 -- .../grazingSchedules/RowMenu.js | 7 +- .../GrazingScheduleEntryRow.test.js.snap | 284 -- .../__snapshots__/index.test.js.snap | 876 ------ .../grazingSchedules/index.js | 48 +- .../grazingSchedules/index.story.js | 13 - .../grazingSchedules/index.test.js | 143 - src/components/rangeUsePlanPage/index.js | 60 +- .../invasivePlantChecklist/index.js | 25 +- .../manageAgentsPage/index.js | 38 +- .../ManagementConsiderationRow.js | 9 +- .../managementConsiderations/index.js | 45 +- .../AddMinisterIssueActionButton.js | 4 +- .../ministerIssues/AddMinisterIssueButton.js | 7 +- .../ministerIssues/MinisterIssueAction.js | 17 +- .../ministerIssues/MinisterIssueBox.js | 49 +- .../rangeUsePlanPage/ministerIssues/index.js | 22 +- .../ministerIssues/index.story.js | 15 +- .../notifications/AHSignaturesStatusModal.js | 36 +- .../notifications/StatusHistory.js | 47 +- .../rangeUsePlanPage/notifications/index.js | 14 +- .../pageForAH/AHSignatureModal.js | 34 +- .../pageForAH/AmendmentSubmissionModal.js | 91 +- .../pageForAH/SubmissionModal.js | 53 +- .../confirmationTabs/AHConfirmationList.js | 19 +- .../confirmationTabs/ConfirmChoiceTab.js | 11 +- .../pageForAH/confirmationTabs/LastTab.js | 13 +- .../RequestClarificationTab.js | 4 +- .../rangeUsePlanPage/pageForAH/index.js | 90 +- .../submissionTabs/AddDescriptionTab.js | 14 +- .../submissionTabs/ChooseAmendmentTypeTab.js | 25 +- .../submissionTabs/ChooseSubmissionTypeTab.js | 18 +- .../pageForAH/submissionTabs/LastTab.js | 7 +- .../submissionTabs/RequestSignaturesTab.js | 17 +- .../submissionTabs/SubmitForFeedbackTab.js | 6 +- .../SubmitForFinalDecisionTab.js | 14 +- .../rangeUsePlanPage/pageForAH/tab/LeftBtn.js | 9 +- .../pageForAH/tabs/ConfirmationTabs.js | 12 +- .../tabs/MandatoryTabsForMultipleAH.js | 11 +- .../tabs/MandatoryTabsForSingleAH.js | 8 +- .../pageForAH/tabs/MinorTabsForMultipleAH.js | 6 +- .../pageForAH/tabs/TabsForMultipleAH.js | 8 +- .../pageForAH/tabs/TabsForSingleAH.js | 5 +- .../pageForStaff/UpdateStatusDropdown.js | 46 +- .../pageForStaff/UpdateStatusModal.js | 20 +- .../rangeUsePlanPage/pageForStaff/index.js | 58 +- .../rangeUsePlanPage/pastures/PastureBox.js | 26 +- .../rangeUsePlanPage/pastures/index.js | 16 +- src/components/rangeUsePlanPage/pdf/helper.js | 77 +- .../AddPlantCommunityButton.js | 6 +- .../plantCommunities/IndicatorPlant.js | 7 +- .../plantCommunities/IndicatorPlantsForm.js | 19 +- .../IndicatorPlantsForm.story.js | 57 +- .../plantCommunities/PlantCommunityAction.js | 37 +- .../PlantCommunityActionsBox.js | 19 +- .../PlantCommunityActionsBox.story.js | 10 +- .../plantCommunities/PlantCommunityBox.js | 82 +- .../PlantCommunityBox.story.js | 35 +- .../plantCommunities/criteria/Import.js | 23 +- .../criteria/RangeReadinessBox.js | 18 +- .../plantCommunities/criteria/ShrubUseBox.js | 5 +- .../plantCommunities/index.js | 17 +- .../plantCommunities/index.story.js | 5 +- .../monitoringArea/AddMonitoringAreaButton.js | 7 +- .../monitoringArea/MonitoringAreaBox.js | 34 +- .../monitoringArea/MonitoringAreaBox.story.js | 5 +- .../plantCommunities/monitoringArea/index.js | 15 +- src/components/rangeUsePlanPage/schema.js | 64 +- .../rangeUsePlanPage/usage/UsageTable.js | 19 +- .../rangeUsePlanPage/usage/UsageTableRow.js | 8 +- .../versionsList/AttachmentsList.js | 17 +- .../versionsList/VersionsDropdown.js | 4 +- .../versionsList/VersionsDropdownList.js | 47 +- src/components/router/ProtectedRoute.js | 10 +- src/components/router/index.js | 74 +- .../selectRangeUsePlanPage/AHWarning.js | 8 +- .../selectRangeUsePlanPage/AgreementTable.js | 30 +- .../AgreementTableRow.js | 27 +- .../DatePickerDialog.js | 6 +- .../selectRangeUsePlanPage/ExtensionColumn.js | 99 +- .../selectRangeUsePlanPage/NewPlanButton.js | 7 +- .../PastePlanMenuItem.js | 6 +- .../selectRangeUsePlanPage/PlanActions.js | 31 +- .../selectRangeUsePlanPage/PlanRow.js | 54 +- .../selectRangeUsePlanPage/PlanTable.js | 26 +- .../selectRangeUsePlanPage/PlanTableRow.js | 20 +- .../SortableAgreementTable.js | 35 +- .../selectRangeUsePlanPage/ZoneSelect.js | 77 +- .../selectRangeUsePlanPage/index.js | 15 +- src/configureStore.js | 5 +- src/constants/actionTypes.js | 12 +- src/constants/api.js | 174 +- src/constants/reducerTypes.js | 15 +- src/constants/strings.js | 156 +- src/constants/variables.js | 26 +- src/providers/ConfrimationModalProvider.js | 24 +- src/providers/EditableProvider.js | 6 +- src/providers/PlanProvider.js | 7 +- src/providers/ReferencesProvider.js | 6 +- src/providers/ToastProvider.js | 26 +- src/reducers/agreementReducer.js | 8 +- src/reducers/agreementWithALLPlansReducer.js | 3 +- src/reducers/authReducer.js | 7 +- src/reducers/clientReducer.js | 3 +- src/reducers/confirmModalReducer.js | 5 +- src/reducers/networkReducer.js | 7 +- src/reducers/planReducer/index.js | 6 +- .../planReducer/ministerIssuesReducer.js | 5 +- .../planReducer/planStatusHistoryReducer.js | 5 +- src/reducers/planReducer/plansReducer.js | 9 +- .../planReducer/plantCommunitiesReducer.js | 6 +- src/reducers/rootReducer.js | 222 +- src/tests/helpers/setupBrowser.js | 13 - src/tests/helpers/setupTests.js | 8 - src/tests/helpers/test-utils.js | 49 - src/tests/helpers/utils.js | 15 - src/tests/intergration/AHRupPage.test.js | 67 - src/tests/intergration/AdminRupPage.test.js | 66 - src/tests/intergration/LoginPage.test.js | 33 - .../intergration/ManageClientPage.test.js | 217 -- src/tests/intergration/ManageZonePage.test.js | 106 - src/tests/intergration/OfficerRupPage.test.js | 65 - .../SelectRangeUsePlanPage.test.js | 99 - .../intergration/__mocks__/lodash.debounce.js | 3 - src/tests/intergration/mockData/index.js | 36 - .../intergration/mockData/mockAgreements.js | 2801 ----------------- .../intergration/mockData/mockClients.js | 84 - src/tests/intergration/mockData/mockPlan.js | 692 ---- .../intergration/mockData/mockReference.js | 1406 --------- src/tests/intergration/mockData/mockUsers.js | 631 ---- src/tests/intergration/mockData/mockZones.js | 1482 --------- src/tests/reducers/planReducer.test.js | 174 - src/tests/reducers/plansReducer.test.js | 106 - src/tests/utils/localStorage.test.js | 36 - src/utils/authentication.js | 33 +- src/utils/calculation/grazingSchedule.js | 16 +- src/utils/calculation/index.js | 4 +- src/utils/format/date.js | 13 +- src/utils/format/queryString.js | 6 +- src/utils/helper/amendment.js | 64 +- src/utils/helper/client.js | 36 +- src/utils/helper/grazingSchedule.js | 56 +- src/utils/helper/manageZoneAndClient.js | 13 +- src/utils/helper/pasture.js | 4 +- src/utils/helper/plan.js | 149 +- src/utils/helper/plantCommunity.js | 12 +- src/utils/helper/user.js | 56 +- src/utils/hooks/useDebounce.js | 2 +- src/utils/index.js | 24 +- src/utils/localStorage.js | 3 +- src/utils/validation/grazingSchedule.js | 14 +- src/utils/validation/plan.js | 24 +- 243 files changed, 2000 insertions(+), 15202 deletions(-) delete mode 100644 src/components/rangeUsePlanPage/grazingSchedules/GrazingScheduleBox.test.js delete mode 100644 src/components/rangeUsePlanPage/grazingSchedules/GrazingScheduleEntryRow.test.js delete mode 100644 src/components/rangeUsePlanPage/grazingSchedules/__snapshots__/GrazingScheduleEntryRow.test.js.snap delete mode 100644 src/components/rangeUsePlanPage/grazingSchedules/__snapshots__/index.test.js.snap delete mode 100644 src/components/rangeUsePlanPage/grazingSchedules/index.story.js delete mode 100644 src/components/rangeUsePlanPage/grazingSchedules/index.test.js delete mode 100644 src/tests/helpers/setupBrowser.js delete mode 100644 src/tests/helpers/setupTests.js delete mode 100644 src/tests/helpers/test-utils.js delete mode 100644 src/tests/helpers/utils.js delete mode 100644 src/tests/intergration/AHRupPage.test.js delete mode 100644 src/tests/intergration/AdminRupPage.test.js delete mode 100644 src/tests/intergration/LoginPage.test.js delete mode 100644 src/tests/intergration/ManageClientPage.test.js delete mode 100644 src/tests/intergration/ManageZonePage.test.js delete mode 100644 src/tests/intergration/OfficerRupPage.test.js delete mode 100644 src/tests/intergration/SelectRangeUsePlanPage.test.js delete mode 100644 src/tests/intergration/__mocks__/lodash.debounce.js delete mode 100644 src/tests/intergration/mockData/index.js delete mode 100644 src/tests/intergration/mockData/mockAgreements.js delete mode 100644 src/tests/intergration/mockData/mockClients.js delete mode 100644 src/tests/intergration/mockData/mockPlan.js delete mode 100644 src/tests/intergration/mockData/mockReference.js delete mode 100644 src/tests/intergration/mockData/mockUsers.js delete mode 100644 src/tests/intergration/mockData/mockZones.js delete mode 100644 src/tests/reducers/planReducer.test.js delete mode 100644 src/tests/reducers/plansReducer.test.js delete mode 100644 src/tests/utils/localStorage.test.js diff --git a/.prettierrc b/.prettierrc index d7679edd..34b61644 100644 --- a/.prettierrc +++ b/.prettierrc @@ -13,7 +13,7 @@ "vueIndentScriptAndStyle": false, "proseWrap": "preserve", "insertPragma": false, - "printWidth": 80, + "printWidth": 120, "requirePragma": false, "tabWidth": 2, "useTabs": false, diff --git a/src/actionCreators/commonActionCreator.js b/src/actionCreators/commonActionCreator.js index 65e83e12..c9e990d5 100644 --- a/src/actionCreators/commonActionCreator.js +++ b/src/actionCreators/commonActionCreator.js @@ -1,18 +1,7 @@ import { normalize } from 'normalizr'; -import { - axios, - createConfigWithHeader, - saveReferencesInLocalStorage, -} from '../utils'; +import { axios, createConfigWithHeader, saveReferencesInLocalStorage } from '../utils'; import * as API from '../constants/api'; -import { - storeUsers, - storeReferences, - storeZones, - request, - success, - error, -} from '../actions'; +import { storeUsers, storeReferences, storeZones, request, success, error } from '../actions'; import * as schema from './schema'; import { GET_USERS, GET_ZONES } from '../constants/reducerTypes'; @@ -58,9 +47,7 @@ export const fetchReferences = () => (dispatch, getState) => { if (err?.status === 401) { // Request was unauthorized, user probably hasn't logged in yet. } else { - console.warn( - `Error fetching references, '${err}'. Falling back to locally stored references`, - ); + console.warn(`Error fetching references, '${err}'. Falling back to locally stored references`); } }); }; diff --git a/src/actionCreators/grazingScheduleActionCreator.js b/src/actionCreators/grazingScheduleActionCreator.js index cb2ff6d4..3a567eb0 100644 --- a/src/actionCreators/grazingScheduleActionCreator.js +++ b/src/actionCreators/grazingScheduleActionCreator.js @@ -5,135 +5,124 @@ import * as reducerTypes from '../constants/reducerTypes'; import * as API from '../constants/api'; import { axios, createConfigWithHeader } from '../utils'; -export const createRUPGrazingScheduleEntry = - (planId, grazingScheduleId, entry) => (dispatch, getState) => { - return axios - .post( - API.CREATE_RUP_GRAZING_SCHEDULE_ENTRY(planId, grazingScheduleId), - { ...entry, plan_id: planId }, - createConfigWithHeader(getState), - ) - .then( - (response) => { - const newEntry = response.data; - return newEntry; - }, - (err) => { - throw err; - }, - ); +export const createRUPGrazingScheduleEntry = (planId, grazingScheduleId, entry) => (dispatch, getState) => { + return axios + .post( + API.CREATE_RUP_GRAZING_SCHEDULE_ENTRY(planId, grazingScheduleId), + { ...entry, plan_id: planId }, + createConfigWithHeader(getState), + ) + .then( + (response) => { + const newEntry = response.data; + return newEntry; + }, + (err) => { + throw err; + }, + ); +}; + +export const createRUPGrazingSchedule = (planId, schedule) => (dispatch, getState) => { + const makeRequest = async () => { + const { data: newSchedule } = await axios.post( + API.CREATE_RUP_GRAZING_SCHEDULE(planId), + { ...schedule, plan_id: planId }, + createConfigWithHeader(getState), + ); + // const newGses = await Promise.all(schedule.grazingScheduleEntries + // .map(gse => dispatch(createRUPGrazingScheduleEntry(planId, newSchedule.id, gse)))); + + return { + ...newSchedule, + // grazingScheduleEntries: newGses, + }; }; + return makeRequest(); +}; -export const createRUPGrazingSchedule = - (planId, schedule) => (dispatch, getState) => { - const makeRequest = async () => { - const { data: newSchedule } = await axios.post( +const createRUPGrazingScheduleAndEntries = (planId, schedule) => (dispatch, getState) => { + dispatch(request(reducerTypes.CREATE_GRAZING_SCHEDULE_AND_ENTRIES)); + const makeRequest = async () => { + try { + const { ...grazingSchedule } = schedule; + const { data } = await axios.post( API.CREATE_RUP_GRAZING_SCHEDULE(planId), - { ...schedule, plan_id: planId }, + { ...grazingSchedule, plan_id: planId }, createConfigWithHeader(getState), ); - // const newGses = await Promise.all(schedule.grazingScheduleEntries - // .map(gse => dispatch(createRUPGrazingScheduleEntry(planId, newSchedule.id, gse)))); - - return { - ...newSchedule, - // grazingScheduleEntries: newGses, - }; - }; - return makeRequest(); + dispatch(success(reducerTypes.CREATE_GRAZING_SCHEDULE_AND_ENTRIES, data)); + return data; + } catch (err) { + dispatch(error(reducerTypes.CREATE_GRAZING_SCHEDULE_AND_ENTRIES, err)); + dispatch(toastErrorMessage(err)); + throw err; + } }; + return makeRequest(); +}; -const createRUPGrazingScheduleAndEntries = - (planId, schedule) => (dispatch, getState) => { - dispatch(request(reducerTypes.CREATE_GRAZING_SCHEDULE_AND_ENTRIES)); - const makeRequest = async () => { - try { - const { ...grazingSchedule } = schedule; - const { data } = await axios.post( - API.CREATE_RUP_GRAZING_SCHEDULE(planId), - { ...grazingSchedule, plan_id: planId }, - createConfigWithHeader(getState), - ); - dispatch( - success(reducerTypes.CREATE_GRAZING_SCHEDULE_AND_ENTRIES, data), - ); - return data; - } catch (err) { - dispatch(error(reducerTypes.CREATE_GRAZING_SCHEDULE_AND_ENTRIES, err)); - dispatch(toastErrorMessage(err)); - throw err; - } - }; - return makeRequest(); +const updateRUPGrazingScheduleAndEntries = (planId, schedule) => (dispatch, getState) => { + dispatch(request(reducerTypes.UPDATE_GRAZING_SCHEDULE_AND_ENTRIES)); + const makeRequest = async () => { + try { + const { data } = await axios.put( + API.UPDATE_RUP_GRAZING_SCHEDULE(planId, schedule.id), + { ...schedule }, + createConfigWithHeader(getState), + ); + dispatch(success(reducerTypes.UPDATE_GRAZING_SCHEDULE_AND_ENTRIES, data)); + return data; + } catch (err) { + dispatch(error(reducerTypes.UPDATE_GRAZING_SCHEDULE_AND_ENTRIES, err)); + dispatch(toastErrorMessage(err)); + throw err; + } }; + return makeRequest(); +}; -const updateRUPGrazingScheduleAndEntries = - (planId, schedule) => (dispatch, getState) => { - dispatch(request(reducerTypes.UPDATE_GRAZING_SCHEDULE_AND_ENTRIES)); - const makeRequest = async () => { - try { - const { data } = await axios.put( - API.UPDATE_RUP_GRAZING_SCHEDULE(planId, schedule.id), - { ...schedule }, - createConfigWithHeader(getState), - ); - dispatch( - success(reducerTypes.UPDATE_GRAZING_SCHEDULE_AND_ENTRIES, data), - ); - return data; - } catch (err) { - dispatch(error(reducerTypes.UPDATE_GRAZING_SCHEDULE_AND_ENTRIES, err)); - dispatch(toastErrorMessage(err)); - throw err; - } - }; - return makeRequest(); - }; +export const createOrUpdateRUPGrazingSchedule = (planId, schedule) => (dispatch) => { + if (uuid.isUUID(schedule.id)) { + return dispatch(createRUPGrazingScheduleAndEntries(planId, schedule)); + } + return dispatch(updateRUPGrazingScheduleAndEntries(planId, schedule)); +}; -export const createOrUpdateRUPGrazingSchedule = - (planId, schedule) => (dispatch) => { - if (uuid.isUUID(schedule.id)) { - return dispatch(createRUPGrazingScheduleAndEntries(planId, schedule)); +export const deleteRUPGrazingSchedule = (planId, scheduleId) => (dispatch, getState) => { + dispatch(request(reducerTypes.DELETE_GRAZING_SCHEUDLE)); + const makeRequest = async () => { + try { + const { data } = await axios.delete( + API.DELETE_RUP_GRAZING_SCHEDULE(planId, scheduleId), + createConfigWithHeader(getState), + ); + dispatch(success(reducerTypes.DELETE_GRAZING_SCHEUDLE, data)); + return data; + } catch (err) { + dispatch(error(reducerTypes.DELETE_GRAZING_SCHEUDLE, err)); + dispatch(toastErrorMessage(err)); + throw err; } - return dispatch(updateRUPGrazingScheduleAndEntries(planId, schedule)); - }; - -export const deleteRUPGrazingSchedule = - (planId, scheduleId) => (dispatch, getState) => { - dispatch(request(reducerTypes.DELETE_GRAZING_SCHEUDLE)); - const makeRequest = async () => { - try { - const { data } = await axios.delete( - API.DELETE_RUP_GRAZING_SCHEDULE(planId, scheduleId), - createConfigWithHeader(getState), - ); - dispatch(success(reducerTypes.DELETE_GRAZING_SCHEUDLE, data)); - return data; - } catch (err) { - dispatch(error(reducerTypes.DELETE_GRAZING_SCHEUDLE, err)); - dispatch(toastErrorMessage(err)); - throw err; - } - }; - return makeRequest(); }; + return makeRequest(); +}; -export const deleteRUPGrazingScheduleEntry = - (planId, scheduleId, entryId) => (dispatch, getState) => { - dispatch(request(reducerTypes.DELETE_GRAZING_SCHEUDLE_ENTRY)); - const makeRequest = async () => { - try { - const { data } = await axios.delete( - API.DELETE_RUP_GRAZING_SCHEDULE_ENTRY(planId, scheduleId, entryId), - createConfigWithHeader(getState), - ); - dispatch(success(reducerTypes.DELETE_GRAZING_SCHEUDLE_ENTRY, data)); - return data; - } catch (err) { - dispatch(error(reducerTypes.DELETE_GRAZING_SCHEUDLE_ENTRY, err)); - dispatch(toastErrorMessage(err)); - throw err; - } - }; - return makeRequest(); +export const deleteRUPGrazingScheduleEntry = (planId, scheduleId, entryId) => (dispatch, getState) => { + dispatch(request(reducerTypes.DELETE_GRAZING_SCHEUDLE_ENTRY)); + const makeRequest = async () => { + try { + const { data } = await axios.delete( + API.DELETE_RUP_GRAZING_SCHEDULE_ENTRY(planId, scheduleId, entryId), + createConfigWithHeader(getState), + ); + dispatch(success(reducerTypes.DELETE_GRAZING_SCHEUDLE_ENTRY, data)); + return data; + } catch (err) { + dispatch(error(reducerTypes.DELETE_GRAZING_SCHEUDLE_ENTRY, err)); + dispatch(toastErrorMessage(err)); + throw err; + } }; + return makeRequest(); +}; diff --git a/src/actionCreators/index.js b/src/actionCreators/index.js index a9d9db62..e945a575 100644 --- a/src/actionCreators/index.js +++ b/src/actionCreators/index.js @@ -4,17 +4,9 @@ import * as actions from '../actions'; import * as reducerTypes from '../constants/reducerTypes'; import * as API from '../constants/api'; import { getAuthTimeout, getUser } from '../reducers/rootReducer'; -import { - axios, - saveUserProfileInLocal, - createConfigWithHeader, - setTimeoutForReAuth, -} from '../utils'; +import { axios, saveUserProfileInLocal, createConfigWithHeader, setTimeoutForReAuth } from '../utils'; import { toastSuccessMessage, toastErrorMessage } from './toastActionCreator'; -import { - ASSIGN_STAFF_TO_ZONE_SUCCESS, - UPDATE_USER_PROFILE_SUCCESS, -} from '../constants/strings'; +import { ASSIGN_STAFF_TO_ZONE_SUCCESS, UPDATE_USER_PROFILE_SUCCESS } from '../constants/strings'; export * from './planActionCreator'; export * from './toastActionCreator'; @@ -26,25 +18,19 @@ export * from './requirementAndConsiderationActionCreator'; export const fetchAgreement = (agreementId) => (dispatch, getState) => { dispatch(actions.request(reducerTypes.GET_AGREEMENT)); - return axios - .get(API.GET_AGREEMENT(agreementId), createConfigWithHeader(getState)) - .then( - (response) => { - const agreement = response.data; - dispatch(actions.success(reducerTypes.GET_AGREEMENT, agreement)); - dispatch( - actions.storeAgreementWithAllPlans( - normalize(agreement, schema.agreement), - ), - ); + return axios.get(API.GET_AGREEMENT(agreementId), createConfigWithHeader(getState)).then( + (response) => { + const agreement = response.data; + dispatch(actions.success(reducerTypes.GET_AGREEMENT, agreement)); + dispatch(actions.storeAgreementWithAllPlans(normalize(agreement, schema.agreement))); - return agreement; - }, - (err) => { - dispatch(actions.error(reducerTypes.GET_AGREEMENT, err)); - throw err; - }, - ); + return agreement; + }, + (err) => { + dispatch(actions.error(reducerTypes.GET_AGREEMENT, err)); + throw err; + }, + ); }; export const searchClients = (term) => (dispatch, getState) => { @@ -76,33 +62,26 @@ export const searchClients = (term) => (dispatch, getState) => { export const updateUserIdOfZone = (zoneId, userId) => (dispatch, getState) => { dispatch(actions.request(reducerTypes.UPDATE_USER_ID_OF_ZONE)); - return axios - .put( - API.UPDATE_USER_ID_OF_ZONE(zoneId), - { userId }, - createConfigWithHeader(getState), - ) - .then( - (response) => { - dispatch(actions.success(reducerTypes.UPDATE_USER_ID_OF_ZONE)); - dispatch(toastSuccessMessage(ASSIGN_STAFF_TO_ZONE_SUCCESS)); - return response.data; - }, - (err) => { - dispatch(actions.error(reducerTypes.UPDATE_USER_ID_OF_ZONE, err)); - dispatch(toastErrorMessage(err)); - throw err; - }, - ); + return axios.put(API.UPDATE_USER_ID_OF_ZONE(zoneId), { userId }, createConfigWithHeader(getState)).then( + (response) => { + dispatch(actions.success(reducerTypes.UPDATE_USER_ID_OF_ZONE)); + dispatch(toastSuccessMessage(ASSIGN_STAFF_TO_ZONE_SUCCESS)); + return response.data; + }, + (err) => { + dispatch(actions.error(reducerTypes.UPDATE_USER_ID_OF_ZONE, err)); + dispatch(toastErrorMessage(err)); + throw err; + }, + ); }; -export const resetTimeoutForReAuth = - (reauthenticate) => (dispatch, getState) => { - clearTimeout(getAuthTimeout(getState())); +export const resetTimeoutForReAuth = (reauthenticate) => (dispatch, getState) => { + clearTimeout(getAuthTimeout(getState())); - const timeoutId = setTimeoutForReAuth(reauthenticate); - dispatch(actions.setTimeoutForAuthentication(timeoutId)); - }; + const timeoutId = setTimeoutForReAuth(reauthenticate); + dispatch(actions.setTimeoutForAuthentication(timeoutId)); +}; export const signOut = () => (dispatch) => { // clear the local storage in the browser @@ -131,27 +110,25 @@ export const fetchUser = () => (dispatch, getState) => { export const updateUser = (data) => (dispatch, getState) => { dispatch(actions.request(reducerTypes.UPDATE_USER)); - return axios - .put(API.UPDATE_USER_PROFILE, data, createConfigWithHeader(getState)) - .then( - (response) => { - const currUser = getUser(getState()); - const updatedUser = { - ...currUser, - ...response.data, - }; - dispatch(actions.success(reducerTypes.UPDATE_USER, updatedUser)); - dispatch(actions.storeUser(updatedUser)); - dispatch(toastSuccessMessage(UPDATE_USER_PROFILE_SUCCESS)); - saveUserProfileInLocal(updatedUser); + return axios.put(API.UPDATE_USER_PROFILE, data, createConfigWithHeader(getState)).then( + (response) => { + const currUser = getUser(getState()); + const updatedUser = { + ...currUser, + ...response.data, + }; + dispatch(actions.success(reducerTypes.UPDATE_USER, updatedUser)); + dispatch(actions.storeUser(updatedUser)); + dispatch(toastSuccessMessage(UPDATE_USER_PROFILE_SUCCESS)); + saveUserProfileInLocal(updatedUser); - return updatedUser; - }, - (err) => { - dispatch(actions.error(reducerTypes.UPDATE_USER, err)); - throw err; - }, - ); + return updatedUser; + }, + (err) => { + dispatch(actions.error(reducerTypes.UPDATE_USER, err)); + throw err; + }, + ); }; // export const searchAgreements = (params) => (dispatch, getState) => { diff --git a/src/actionCreators/ministerIssueActionCreator.js b/src/actionCreators/ministerIssueActionCreator.js index 763e5c05..890ade98 100644 --- a/src/actionCreators/ministerIssueActionCreator.js +++ b/src/actionCreators/ministerIssueActionCreator.js @@ -4,180 +4,134 @@ import { success, request, error } from '../actions'; import { axios, createConfigWithHeader } from '../utils'; import * as reducerTypes from '../constants/reducerTypes'; -export const createRUPMinisterIssueAction = - (planId, issueId, action) => (dispatch, getState) => { - return axios - .post( - API.CREATE_RUP_MINISTER_ISSUE_ACTION(planId, issueId), - action, +export const createRUPMinisterIssueAction = (planId, issueId, action) => (dispatch, getState) => { + return axios + .post(API.CREATE_RUP_MINISTER_ISSUE_ACTION(planId, issueId), action, createConfigWithHeader(getState)) + .then( + (response) => { + return response.data; + }, + (err) => { + throw err; + }, + ); +}; + +export const createRUPMinisterIssueAndActions = (planId, issue) => (dispatch, getState) => { + dispatch(request(reducerTypes.CREATE_MINISTER_ISSUE_AND_ACTIONS)); + const makeRequest = async () => { + try { + const { data: newIssue } = await axios.post( + API.CREATE_RUP_MINISTER_ISSUE(planId), + issue, createConfigWithHeader(getState), - ) - .then( - (response) => { - return response.data; - }, - (err) => { - throw err; - }, ); + const newActions = await Promise.all( + issue.ministerIssueActions.map((mia) => dispatch(createRUPMinisterIssueAction(planId, newIssue.id, mia))), + ); + const newIssueWithNewActions = { + ...newIssue, + ministerIssueActions: newActions, + }; + dispatch(success(reducerTypes.CREATE_MINISTER_ISSUE_AND_ACTIONS, newIssueWithNewActions)); + + return newIssueWithNewActions; + } catch (err) { + dispatch(error(reducerTypes.CREATE_MINISTER_ISSUE_AND_ACTIONS)); + throw err; + } }; -export const createRUPMinisterIssueAndActions = - (planId, issue) => (dispatch, getState) => { - dispatch(request(reducerTypes.CREATE_MINISTER_ISSUE_AND_ACTIONS)); - const makeRequest = async () => { - try { - const { data: newIssue } = await axios.post( - API.CREATE_RUP_MINISTER_ISSUE(planId), - issue, - createConfigWithHeader(getState), - ); - const newActions = await Promise.all( - issue.ministerIssueActions.map((mia) => - dispatch(createRUPMinisterIssueAction(planId, newIssue.id, mia)), - ), - ); - const newIssueWithNewActions = { - ...newIssue, - ministerIssueActions: newActions, - }; - dispatch( - success( - reducerTypes.CREATE_MINISTER_ISSUE_AND_ACTIONS, - newIssueWithNewActions, - ), - ); + return makeRequest(); +}; - return newIssueWithNewActions; - } catch (err) { - dispatch(error(reducerTypes.CREATE_MINISTER_ISSUE_AND_ACTIONS)); +export const updateRUPMinisterIssueAction = (planId, issueId, action) => (dispatch, getState) => { + return axios + .put(API.UPDATE_RUP_MINISTER_ISSUE_ACTION(planId, issueId, action.id), action, createConfigWithHeader(getState)) + .then( + (response) => { + return response.data; + }, + (err) => { throw err; - } - }; + }, + ); +}; - return makeRequest(); +export const createOrUpdateRUPMinisterIssueActions = (planId, issueId, actions) => (dispatch) => { + const makeRequest = async () => { + return await Promise.all( + actions.map((action) => { + if (uuid.isUUID(action.id)) { + return dispatch(createRUPMinisterIssueAction(planId, issueId, action)); + } + return dispatch(updateRUPMinisterIssueAction(planId, issueId, action)); + }), + ); }; -export const updateRUPMinisterIssueAction = - (planId, issueId, action) => (dispatch, getState) => { - return axios - .put( - API.UPDATE_RUP_MINISTER_ISSUE_ACTION(planId, issueId, action.id), - action, + return makeRequest(); +}; + +export const updateRUPMinisterIssueAndActions = (planId, issue) => (dispatch, getState) => { + dispatch(request(reducerTypes.UPDATE_MINISTER_ISSUE_AND_ACTIONS)); + const makeRequest = async () => { + try { + const { data: updatedIssue } = await axios.put( + API.UPDATE_RUP_MINISTER_ISSUE(planId, issue.id), + issue, createConfigWithHeader(getState), - ) - .then( - (response) => { - return response.data; - }, - (err) => { - throw err; - }, ); - }; - -export const createOrUpdateRUPMinisterIssueActions = - (planId, issueId, actions) => (dispatch) => { - const makeRequest = async () => { - return await Promise.all( - actions.map((action) => { - if (uuid.isUUID(action.id)) { - return dispatch( - createRUPMinisterIssueAction(planId, issueId, action), - ); - } - return dispatch( - updateRUPMinisterIssueAction(planId, issueId, action), - ); - }), + const createdOrUpdatedActions = await dispatch( + createOrUpdateRUPMinisterIssueActions(planId, issue.id, issue.ministerIssueActions), ); - }; + const updatedIssueWithCreatedOrUpdatedActions = { + ...updatedIssue, + ministerIssueActions: createdOrUpdatedActions, + }; + dispatch(success(reducerTypes.UPDATE_MINISTER_ISSUE_AND_ACTIONS, updatedIssueWithCreatedOrUpdatedActions)); - return makeRequest(); + return updatedIssueWithCreatedOrUpdatedActions; + } catch (err) { + dispatch(error(reducerTypes.UPDATE_MINISTER_ISSUE_AND_ACTIONS)); + throw err; + } }; -export const updateRUPMinisterIssueAndActions = - (planId, issue) => (dispatch, getState) => { - dispatch(request(reducerTypes.UPDATE_MINISTER_ISSUE_AND_ACTIONS)); - const makeRequest = async () => { - try { - const { data: updatedIssue } = await axios.put( - API.UPDATE_RUP_MINISTER_ISSUE(planId, issue.id), - issue, - createConfigWithHeader(getState), - ); - const createdOrUpdatedActions = await dispatch( - createOrUpdateRUPMinisterIssueActions( - planId, - issue.id, - issue.ministerIssueActions, - ), - ); - const updatedIssueWithCreatedOrUpdatedActions = { - ...updatedIssue, - ministerIssueActions: createdOrUpdatedActions, - }; - dispatch( - success( - reducerTypes.UPDATE_MINISTER_ISSUE_AND_ACTIONS, - updatedIssueWithCreatedOrUpdatedActions, - ), - ); - - return updatedIssueWithCreatedOrUpdatedActions; - } catch (err) { - dispatch(error(reducerTypes.UPDATE_MINISTER_ISSUE_AND_ACTIONS)); - throw err; - } - }; - - return makeRequest(); - }; + return makeRequest(); +}; -export const createOrUpdateRUPMinisterIssueAndActions = - (planId, issue) => (dispatch) => { - if (uuid.isUUID(issue.id)) { - return dispatch(createRUPMinisterIssueAndActions(planId, issue)); - } +export const createOrUpdateRUPMinisterIssueAndActions = (planId, issue) => (dispatch) => { + if (uuid.isUUID(issue.id)) { + return dispatch(createRUPMinisterIssueAndActions(planId, issue)); + } - return dispatch(updateRUPMinisterIssueAndActions(planId, issue)); - }; + return dispatch(updateRUPMinisterIssueAndActions(planId, issue)); +}; -export const deleteRUPMinisterIssue = - (planId, issueId) => (dispatch, getState) => { - return axios - .delete( - API.DELETE_RUP_MINISTER_ISSUE(planId, issueId), - createConfigWithHeader(getState), - ) - .then( - (response) => { - return response.data; - }, - (err) => { - throw err; - }, - ); - }; +export const deleteRUPMinisterIssue = (planId, issueId) => (dispatch, getState) => { + return axios.delete(API.DELETE_RUP_MINISTER_ISSUE(planId, issueId), createConfigWithHeader(getState)).then( + (response) => { + return response.data; + }, + (err) => { + throw err; + }, + ); +}; -export const deleteRUPMinisterIssueAction = - (planId, issueId, actionId) => (dispatch, getState) => { - dispatch(request(reducerTypes.DELETE_MINISTER_ISSUE_ACTION)); - return axios - .delete( - API.DELETE_RUP_MINISTER_ISSUE_ACTION(planId, issueId, actionId), - createConfigWithHeader(getState), - ) - .then( - (response) => { - dispatch( - success(reducerTypes.DELETE_MINISTER_ISSUE_ACTION, response.data), - ); - return response.data; - }, - (err) => { - dispatch(error(reducerTypes.DELETE_MINISTER_ISSUE_ACTION, err)); - throw err; - }, - ); - }; +export const deleteRUPMinisterIssueAction = (planId, issueId, actionId) => (dispatch, getState) => { + dispatch(request(reducerTypes.DELETE_MINISTER_ISSUE_ACTION)); + return axios + .delete(API.DELETE_RUP_MINISTER_ISSUE_ACTION(planId, issueId, actionId), createConfigWithHeader(getState)) + .then( + (response) => { + dispatch(success(reducerTypes.DELETE_MINISTER_ISSUE_ACTION, response.data)); + return response.data; + }, + (err) => { + dispatch(error(reducerTypes.DELETE_MINISTER_ISSUE_ACTION, err)); + throw err; + }, + ); +}; diff --git a/src/actionCreators/pastureActionCreator.js b/src/actionCreators/pastureActionCreator.js index 1ab3b0f3..7d3d26c4 100644 --- a/src/actionCreators/pastureActionCreator.js +++ b/src/actionCreators/pastureActionCreator.js @@ -1,12 +1,6 @@ import * as API from '../constants/api'; import { axios, createConfigWithHeader } from '../utils'; -import { - request, - success, - error, - pastureUpdated, - pastureSubmitted, -} from '../actions'; +import { request, success, error, pastureUpdated, pastureSubmitted } from '../actions'; import { toastErrorMessage } from './toastActionCreator'; import { CREATE_PASTURE, UPDATE_PASTURE } from '../constants/reducerTypes'; @@ -17,11 +11,7 @@ export const createRUPPasture = (planId, pasture) => (dispatch, getState) => { const makeRequest = async () => { try { - const { data } = await axios.post( - API.CREATE_RUP_PASTURE(planId), - values, - createConfigWithHeader(getState), - ); + const { data } = await axios.post(API.CREATE_RUP_PASTURE(planId), values, createConfigWithHeader(getState)); dispatch(success(CREATE_PASTURE, data)); dispatch(pastureSubmitted({ id, pasture: data })); return data; @@ -67,118 +57,91 @@ export const createOrUpdateRUPPasture = (planId, pasture) => (dispatch) => { } }; -export const createRUPPlantCommunityAction = - (planId, pastureId, communityId, action) => (dispatch, getState) => { - const { ...data } = action; - - return axios - .post( - API.CREATE_RUP_PLANT_COMMUNITY_ACTION(planId, pastureId, communityId), - data, - createConfigWithHeader(getState), - ) - .then( - (response) => { - return response.data; - }, - (err) => { - throw err; - }, - ); - }; +export const createRUPPlantCommunityAction = (planId, pastureId, communityId, action) => (dispatch, getState) => { + const { ...data } = action; + + return axios + .post(API.CREATE_RUP_PLANT_COMMUNITY_ACTION(planId, pastureId, communityId), data, createConfigWithHeader(getState)) + .then( + (response) => { + return response.data; + }, + (err) => { + throw err; + }, + ); +}; -export const createRUPIndicatorPlant = - (planId, pastureId, communityId, plant) => (dispatch, getState) => { - const { ...data } = plant; +export const createRUPIndicatorPlant = (planId, pastureId, communityId, plant) => (dispatch, getState) => { + const { ...data } = plant; + + return axios + .post(API.CREATE_RUP_INDICATOR_PLANT(planId, pastureId, communityId), data, createConfigWithHeader(getState)) + .then( + (response) => { + return response.data; + }, + (err) => { + throw err; + }, + ); +}; - return axios - .post( - API.CREATE_RUP_INDICATOR_PLANT(planId, pastureId, communityId), - data, - createConfigWithHeader(getState), - ) - .then( - (response) => { - return response.data; - }, - (err) => { - throw err; - }, - ); - }; +export const createRUPMonitoringArea = (planId, pastureId, communityId, area) => (dispatch, getState) => { + const { ...data } = area; + + return axios + .post(API.CREATE_RUP_MONITERING_AREA(planId, pastureId, communityId), data, createConfigWithHeader(getState)) + .then( + (response) => { + return response.data; + }, + (err) => { + throw err; + }, + ); +}; -export const createRUPMonitoringArea = - (planId, pastureId, communityId, area) => (dispatch, getState) => { - const { ...data } = area; +export const createRUPPlantCommunityAndOthers = (planId, pastureId, community) => (dispatch, getState) => { + const makeRequest = async () => { + const { id, ...data } = community; + let plantCommunity = community; - return axios - .post( - API.CREATE_RUP_MONITERING_AREA(planId, pastureId, communityId), + if (!Number(id)) { + const { data: newPlantCommunity } = await axios.post( + API.CREATE_RUP_PLANT_COMMUNITY(planId, pastureId), data, createConfigWithHeader(getState), - ) - .then( - (response) => { - return response.data; - }, - (err) => { - throw err; - }, - ); - }; - -export const createRUPPlantCommunityAndOthers = - (planId, pastureId, community) => (dispatch, getState) => { - const makeRequest = async () => { - const { id, ...data } = community; - let plantCommunity = community; - - if (!Number(id)) { - const { data: newPlantCommunity } = await axios.post( - API.CREATE_RUP_PLANT_COMMUNITY(planId, pastureId), - data, - createConfigWithHeader(getState), - ); - plantCommunity = newPlantCommunity; - } - - const newPcas = await Promise.all( - community.plantCommunityActions.map((pca) => - dispatch( - createRUPPlantCommunityAction( - planId, - pastureId, - plantCommunity.id, - pca, - ), - ), - ), - ); - const newIps = await Promise.all( - community.indicatorPlants.map((ip) => { - if (!ip.id) { - return dispatch( - createRUPIndicatorPlant(planId, pastureId, plantCommunity.id, ip), - ); - } - return Promise.resolve(); - }), - ); - const newMas = await Promise.all( - community.monitoringAreas.map((ma) => - dispatch( - createRUPMonitoringArea(planId, pastureId, plantCommunity.id, ma), - ), - ), ); + plantCommunity = newPlantCommunity; + } - return { - ...plantCommunity, - plantCommunityActions: newPcas, - indicatorPlants: newIps, - monitoringAreas: newMas, - }; + const newPcas = await Promise.all( + community.plantCommunityActions.map((pca) => + dispatch(createRUPPlantCommunityAction(planId, pastureId, plantCommunity.id, pca)), + ), + ); + const newIps = await Promise.all( + community.indicatorPlants.map((ip) => { + if (!ip.id) { + return dispatch(createRUPIndicatorPlant(planId, pastureId, plantCommunity.id, ip)); + } + return Promise.resolve(); + }), + ); + const newMas = await Promise.all( + community.monitoringAreas.map((ma) => + dispatch(createRUPMonitoringArea(planId, pastureId, plantCommunity.id, ma)), + ), + ); + + return { + ...plantCommunity, + plantCommunityActions: newPcas, + indicatorPlants: newIps, + monitoringAreas: newMas, }; - - return makeRequest(); }; + + return makeRequest(); +}; diff --git a/src/actionCreators/planActionCreator.js b/src/actionCreators/planActionCreator.js index bc47f7d7..9bf5e64d 100644 --- a/src/actionCreators/planActionCreator.js +++ b/src/actionCreators/planActionCreator.js @@ -1,9 +1,6 @@ import { normalize } from 'normalizr'; import { success, request, error, storePlan } from '../actions'; -import { - UPDATE_PLAN_STATUS_SUCCESS, - UPDATE_AGREEMENT_ZONE_SUCCESS, -} from '../constants/strings'; +import { UPDATE_PLAN_STATUS_SUCCESS, UPDATE_AGREEMENT_ZONE_SUCCESS } from '../constants/strings'; import { toastSuccessMessage, toastErrorMessage } from './toastActionCreator'; import * as reducerTypes from '../constants/reducerTypes'; import * as API from '../constants/api'; @@ -17,11 +14,7 @@ import { getManagementConsiderationsMap, getPlantCommunitiesMap, } from '../reducers/rootReducer'; -import { - REFERENCE_KEY, - PLAN_STATUS, - AMENDMENT_TYPE, -} from '../constants/variables'; +import { REFERENCE_KEY, PLAN_STATUS, AMENDMENT_TYPE } from '../constants/variables'; import { axios, createConfigWithHeader, @@ -37,33 +30,25 @@ import { findStatusWithCode, } from '../utils'; import { createRUPGrazingSchedule } from './grazingScheduleActionCreator'; -import { - createRUPPasture, - createRUPPlantCommunityAndOthers, -} from './pastureActionCreator'; +import { createRUPPasture, createRUPPlantCommunityAndOthers } from './pastureActionCreator'; import { createRUPMinisterIssueAndActions } from './ministerIssueActionCreator'; import { createRUPManagementConsideration, createRUPAdditionalRequirement, } from './requirementAndConsiderationActionCreator'; -export const createRUPInvasivePlantChecklist = - (planId, invasivePlantChecklist) => (dispatch, getState) => { - return axios - .post( - API.CREATE_RUP_INVASIVE_PLANT_CHECKLIST(planId), - invasivePlantChecklist, - createConfigWithHeader(getState), - ) - .then( - (response) => { - return response.data; - }, - (err) => { - throw err; - }, - ); - }; +export const createRUPInvasivePlantChecklist = (planId, invasivePlantChecklist) => (dispatch, getState) => { + return axios + .post(API.CREATE_RUP_INVASIVE_PLANT_CHECKLIST(planId), invasivePlantChecklist, createConfigWithHeader(getState)) + .then( + (response) => { + return response.data; + }, + (err) => { + throw err; + }, + ); +}; export const updateRUPInvasivePlantChecklist = (planId, { id: checklistId, ...invasivePlantChecklist }) => @@ -84,49 +69,39 @@ export const updateRUPInvasivePlantChecklist = ); }; -export const createOrUpdateRUPInvasivePlantChecklist = - (planId, checklist) => (dispatch) => { - if (checklist && checklist.id) { - return dispatch(updateRUPInvasivePlantChecklist(planId, checklist)); - } - return dispatch(createRUPInvasivePlantChecklist(planId, checklist)); - }; +export const createOrUpdateRUPInvasivePlantChecklist = (planId, checklist) => (dispatch) => { + if (checklist && checklist.id) { + return dispatch(updateRUPInvasivePlantChecklist(planId, checklist)); + } + return dispatch(createRUPInvasivePlantChecklist(planId, checklist)); +}; -export const createRUPStatusRecord = - (plan, newStatus, note) => (dispatch, getState) => { - const { id: planId, statusId: fromPlanStatusId } = plan; +export const createRUPStatusRecord = (plan, newStatus, note) => (dispatch, getState) => { + const { id: planId, statusId: fromPlanStatusId } = plan; - return axios - .post( - API.CREATE_RUP_STATUS_RECORD(planId), - { - fromPlanStatusId, - toPlanStatusId: newStatus.id, - note, - }, - createConfigWithHeader(getState), - ) - .then( - (response) => { - return response.data; - }, - (err) => { - dispatch(toastErrorMessage(err)); - throw err; - }, - ); - }; + return axios + .post( + API.CREATE_RUP_STATUS_RECORD(planId), + { + fromPlanStatusId, + toPlanStatusId: newStatus.id, + note, + }, + createConfigWithHeader(getState), + ) + .then( + (response) => { + return response.data; + }, + (err) => { + dispatch(toastErrorMessage(err)); + throw err; + }, + ); +}; export const updateRUPConfirmation = - ( - plan, - user, - confirmationId, - confirmed, - isMinorAmendment, - isOwnSignature = true, - isManualConfirmation = false, - ) => + (plan, user, confirmationId, confirmed, isMinorAmendment, isOwnSignature = true, isManualConfirmation = false) => (dispatch, getState) => { const { id: planId } = plan; const config = { @@ -152,32 +127,28 @@ export const updateRUPConfirmation = }; export const updateRUP = (planId, body) => (dispatch, getState) => { - return axios - .put(API.UPDATE_RUP(planId), body, createConfigWithHeader(getState)) - .then( - (response) => { - const updatedPlan = response.data; - dispatch(storePlan(normalize(updatedPlan, schema.plan))); - return updatedPlan; - }, - (err) => { - throw err; - }, - ); + return axios.put(API.UPDATE_RUP(planId), body, createConfigWithHeader(getState)).then( + (response) => { + const updatedPlan = response.data; + dispatch(storePlan(normalize(updatedPlan, schema.plan))); + return updatedPlan; + }, + (err) => { + throw err; + }, + ); }; export const createRUP = (plan) => (dispatch, getState) => { - return axios - .post(API.CREATE_RUP, plan, createConfigWithHeader(getState)) - .then( - (response) => { - const newPlan = response.data; - return newPlan; - }, - (err) => { - throw err; - }, - ); + return axios.post(API.CREATE_RUP, plan, createConfigWithHeader(getState)).then( + (response) => { + const newPlan = response.data; + return newPlan; + }, + (err) => { + throw err; + }, + ); }; export const createAmendment = (plan) => (dispatch, getState) => { @@ -190,100 +161,51 @@ export const createAmendment = (plan) => (dispatch, getState) => { const plantCommunitiesMap = getPlantCommunitiesMap(getState()); const grazingSchedulesMap = getGrazingSchedulesMap(getState()); const ministerIssuesMap = getMinisterIssuesMap(getState()); - const additionalRequirementsMap = - getAdditionalRequirementsMap(getState()); - const managementConsiderationsMap = - getManagementConsiderationsMap(getState()); + const additionalRequirementsMap = getAdditionalRequirementsMap(getState()); + const managementConsiderationsMap = getManagementConsiderationsMap(getState()); const amendmentTypes = references[REFERENCE_KEY.AMENDMENT_TYPE]; const createdStatus = findStatusWithCode(references, PLAN_STATUS.CREATED); - const initialAmendment = amendmentTypes.find( - (at) => at.code === AMENDMENT_TYPE.INITIAL, - ); + const initialAmendment = amendmentTypes.find((at) => at.code === AMENDMENT_TYPE.INITIAL); - const newPlan = copyPlanToCreateAmendment( - plan, - createdStatus.id, - initialAmendment.id, - ); + const newPlan = copyPlanToCreateAmendment(plan, createdStatus.id, initialAmendment.id); const amendment = await dispatch(createRUP(newPlan)); const { id: amendmentId } = amendment; - const { pastures, plantCommunities: pcs } = copyPasturesToCreateAmendment( - plan, - pasturesMap, - ); - const newPastures = await Promise.all( - pastures.map((p) => dispatch(createRUPPasture(amendmentId, p))), - ); + const { pastures, plantCommunities: pcs } = copyPasturesToCreateAmendment(plan, pasturesMap); + const newPastures = await Promise.all(pastures.map((p) => dispatch(createRUPPasture(amendmentId, p)))); // create a normalized pasture ids map with the old pasture id as a key - const newPastureIdsMap = normalizePasturesWithOldId( - pastures, - newPastures, - ); + const newPastureIdsMap = normalizePasturesWithOldId(pastures, newPastures); - const plantCommunities = copyPlantCommunitiesToCreateAmendment( - pcs, - plantCommunitiesMap, - newPastureIdsMap, - ); + const plantCommunities = copyPlantCommunitiesToCreateAmendment(pcs, plantCommunitiesMap, newPastureIdsMap); const newPlantCommunities = await Promise.all( - plantCommunities.map((pc) => - dispatch( - createRUPPlantCommunityAndOthers(amendmentId, pc.pastureId, pc), - ), - ), + plantCommunities.map((pc) => dispatch(createRUPPlantCommunityAndOthers(amendmentId, pc.pastureId, pc))), ); - const grazingSchedules = copyGrazingSchedulesToCreateAmendment( - plan, - grazingSchedulesMap, - newPastureIdsMap, - ); + const grazingSchedules = copyGrazingSchedulesToCreateAmendment(plan, grazingSchedulesMap, newPastureIdsMap); const newGrazingSchedules = await Promise.all( - grazingSchedules.map((gs) => - dispatch(createRUPGrazingSchedule(amendmentId, gs)), - ), + grazingSchedules.map((gs) => dispatch(createRUPGrazingSchedule(amendmentId, gs))), ); - const ministerIssues = copyMinisterIssuesToCreateAmendment( - plan, - ministerIssuesMap, - newPastureIdsMap, - ); + const ministerIssues = copyMinisterIssuesToCreateAmendment(plan, ministerIssuesMap, newPastureIdsMap); const newMinisterIssues = await Promise.all( - ministerIssues.map((mi) => - dispatch(createRUPMinisterIssueAndActions(amendmentId, mi)), - ), + ministerIssues.map((mi) => dispatch(createRUPMinisterIssueAndActions(amendmentId, mi))), ); - const invasivePlantChecklist = - copyInvasivePlantChecklistToCreateAmendment(plan); + const invasivePlantChecklist = copyInvasivePlantChecklistToCreateAmendment(plan); const newInvasivePlantCheckList = await dispatch( createRUPInvasivePlantChecklist(amendmentId, invasivePlantChecklist), ); - const managementConsiderations = - copyManagementConsiderationsToCreateAmendment( - plan, - managementConsiderationsMap, - ); + const managementConsiderations = copyManagementConsiderationsToCreateAmendment(plan, managementConsiderationsMap); const newManagementConsiderations = await Promise.all( - managementConsiderations.map((mc) => - dispatch(createRUPManagementConsideration(amendmentId, mc)), - ), + managementConsiderations.map((mc) => dispatch(createRUPManagementConsideration(amendmentId, mc))), ); - const additionalRequirements = - copyAdditionalRequirementsToCreateAmendment( - plan, - additionalRequirementsMap, - ); + const additionalRequirements = copyAdditionalRequirementsToCreateAmendment(plan, additionalRequirementsMap); const newAdditionalRequirements = await Promise.all( - additionalRequirements.map((ar) => - dispatch(createRUPAdditionalRequirement(amendmentId, ar)), - ), + additionalRequirements.map((ar) => dispatch(createRUPAdditionalRequirement(amendmentId, ar))), ); // successfully finish uploading so make this amendment visible! @@ -316,10 +238,7 @@ export const fetchRUP = (planId) => (dispatch, getState) => { dispatch(request(reducerTypes.GET_PLAN)); const makeRequest = async () => { try { - const response = await axios.get( - API.GET_RUP(planId), - createConfigWithHeader(getState), - ); + const response = await axios.get(API.GET_RUP(planId), createConfigWithHeader(getState)); const planWithAgreement = response.data; dispatch(success(reducerTypes.GET_PLAN, planWithAgreement)); diff --git a/src/actionCreators/requirementAndConsiderationActionCreator.js b/src/actionCreators/requirementAndConsiderationActionCreator.js index 87b46eb9..052c936b 100644 --- a/src/actionCreators/requirementAndConsiderationActionCreator.js +++ b/src/actionCreators/requirementAndConsiderationActionCreator.js @@ -12,31 +12,21 @@ import { DELETE_MANAGEMENT_CONSIDERATION } from '../constants/reducerTypes'; export const createRUPAdditionalRequirement = (planId, { ...requirement }) => (dispatch, getState) => { - return axios - .post( - CREATE_RUP_ADDITIONAL_REQUIREMENT(planId), - requirement, - createConfigWithHeader(getState), - ) - .then( - (response) => { - return response.data; - }, - (err) => { - throw err; - }, - ); + return axios.post(CREATE_RUP_ADDITIONAL_REQUIREMENT(planId), requirement, createConfigWithHeader(getState)).then( + (response) => { + return response.data; + }, + (err) => { + throw err; + }, + ); }; export const createRUPManagementConsideration = (planId, { ...consideration }) => (dispatch, getState) => { return axios - .post( - CREATE_RUP_MANAGEMENT_CONSIDERATION(planId), - consideration, - createConfigWithHeader(getState), - ) + .post(CREATE_RUP_MANAGEMENT_CONSIDERATION(planId), consideration, createConfigWithHeader(getState)) .then( (response) => { return response.data; @@ -47,49 +37,39 @@ export const createRUPManagementConsideration = ); }; -export const updateRUPManagementConsideration = - (planId, consideration) => (dispatch, getState) => { - return axios - .put( - UPDATE_RUP_MANAGEMENT_CONSIDERATION(planId, consideration.id), - consideration, - createConfigWithHeader(getState), - ) - .then( - (response) => { - return response.data; - }, - (err) => { - throw err; - }, - ); - }; +export const updateRUPManagementConsideration = (planId, consideration) => (dispatch, getState) => { + return axios + .put(UPDATE_RUP_MANAGEMENT_CONSIDERATION(planId, consideration.id), consideration, createConfigWithHeader(getState)) + .then( + (response) => { + return response.data; + }, + (err) => { + throw err; + }, + ); +}; -export const createOrUpdateRUPManagementConsideration = - (planId, consideration) => (dispatch) => { - if (uuid.isUUID(consideration.id)) { - return dispatch(createRUPManagementConsideration(planId, consideration)); - } +export const createOrUpdateRUPManagementConsideration = (planId, consideration) => (dispatch) => { + if (uuid.isUUID(consideration.id)) { + return dispatch(createRUPManagementConsideration(planId, consideration)); + } - return dispatch(updateRUPManagementConsideration(planId, consideration)); - }; + return dispatch(updateRUPManagementConsideration(planId, consideration)); +}; -export const deleteRUPManagementConsideration = - (planId, considerationId) => (dispatch, getState) => { - dispatch(request(DELETE_MANAGEMENT_CONSIDERATION)); - return axios - .delete( - DELETE_RUP_MANAGEMENT_CONSIDERATION(planId, considerationId), - createConfigWithHeader(getState), - ) - .then( - (response) => { - dispatch(success(DELETE_MANAGEMENT_CONSIDERATION, response)); - return response.data; - }, - (err) => { - dispatch(error(DELETE_MANAGEMENT_CONSIDERATION, err)); - throw err; - }, - ); - }; +export const deleteRUPManagementConsideration = (planId, considerationId) => (dispatch, getState) => { + dispatch(request(DELETE_MANAGEMENT_CONSIDERATION)); + return axios + .delete(DELETE_RUP_MANAGEMENT_CONSIDERATION(planId, considerationId), createConfigWithHeader(getState)) + .then( + (response) => { + dispatch(success(DELETE_MANAGEMENT_CONSIDERATION, response)); + return response.data; + }, + (err) => { + dispatch(error(DELETE_MANAGEMENT_CONSIDERATION, err)); + throw err; + }, + ); +}; diff --git a/src/actionCreators/schema.js b/src/actionCreators/schema.js index 53e638f1..a73b5f30 100644 --- a/src/actionCreators/schema.js +++ b/src/actionCreators/schema.js @@ -37,12 +37,8 @@ export const plantCommunity = new schema.Entity('plantCommunities'); export const grazingSchedule = new schema.Entity('grazingSchedules'); export const ministerIssue = new schema.Entity('ministerIssues'); // export const ministerIssueAction = new schema.Entity('ministerIssueActions'); -export const additionalRequirements = new schema.Entity( - 'additionalRequirements', -); -export const managementConsiderations = new schema.Entity( - 'managementConsiderations', -); +export const additionalRequirements = new schema.Entity('additionalRequirements'); +export const managementConsiderations = new schema.Entity('managementConsiderations'); export const confirmation = new schema.Entity('confirmations'); export const planStatusHistory = new schema.Entity('planStatusHistory'); // export const grazingScheduleEntry = new schema.Entity('grazingScheduleEntries'); diff --git a/src/api/delete.js b/src/api/delete.js index eefde9a4..95ecf7d8 100644 --- a/src/api/delete.js +++ b/src/api/delete.js @@ -27,13 +27,11 @@ const addDeleteHandler = (key, handler) => { export const deleteFromQueue = async () => { const deleteQueue = loadOrInitDeleteQueue(); - const deletePromises = Object.entries(deleteQueue).map( - async ([key, queue]) => { - const handler = deleteHandlers[key]; + const deletePromises = Object.entries(deleteQueue).map(async ([key, queue]) => { + const handler = deleteHandlers[key]; - return Promise.all(queue.map((args) => handler(...args))); - }, - ); + return Promise.all(queue.map((args) => handler(...args))); + }); await deletePromises; }; @@ -46,9 +44,7 @@ export const createDeleteHandler = (key, cb) => { deleteQueue[key] = []; } - deleteQueue[key] = deleteQueue[key].filter( - (queuedArgs) => queuedArgs !== args, - ); + deleteQueue[key] = deleteQueue[key].filter((queuedArgs) => queuedArgs !== args); try { await cb(...args); @@ -67,50 +63,26 @@ export const createDeleteHandler = (key, cb) => { export const deleteMinisterIssueAction = createDeleteHandler( 'ministerIssueAction', async (planId, issueId, actionId) => { - await axios.delete( - API.DELETE_RUP_MINISTER_ISSUE_ACTION(planId, issueId, actionId), - getAuthHeaderConfig(), - ); + await axios.delete(API.DELETE_RUP_MINISTER_ISSUE_ACTION(planId, issueId, actionId), getAuthHeaderConfig()); }, ); -export const deletePasture = createDeleteHandler( - 'pasture', - async (planId, pastureId) => { - await axios.delete( - API.DELETE_RUP_PASTURE(planId, pastureId), - getAuthHeaderConfig(), - ); - }, -); +export const deletePasture = createDeleteHandler('pasture', async (planId, pastureId) => { + await axios.delete(API.DELETE_RUP_PASTURE(planId, pastureId), getAuthHeaderConfig()); +}); -export const deletePlantCommunity = createDeleteHandler( - 'plantCommunity', - async (planId, pastureId, communityId) => { - await axios.delete( - API.DELETE_RUP_PLANT_COMMUNITY(planId, pastureId, communityId), - getAuthHeaderConfig(), - ); - }, -); +export const deletePlantCommunity = createDeleteHandler('plantCommunity', async (planId, pastureId, communityId) => { + await axios.delete(API.DELETE_RUP_PLANT_COMMUNITY(planId, pastureId, communityId), getAuthHeaderConfig()); +}); -export const deleteMinisterIssue = createDeleteHandler( - 'ministerIssue', - async (planId, issueId) => { - await axios.delete( - API.DELETE_RUP_MINISTER_ISSUE(planId, issueId), - getAuthHeaderConfig(), - ); - }, -); +export const deleteMinisterIssue = createDeleteHandler('ministerIssue', async (planId, issueId) => { + await axios.delete(API.DELETE_RUP_MINISTER_ISSUE(planId, issueId), getAuthHeaderConfig()); +}); export const deleteMonitoringArea = createDeleteHandler( 'monitoringArea', async (planId, pastureId, communityId, areaId) => { - await axios.delete( - API.DELETE_RUP_MONITORING_AREA(planId, pastureId, communityId, areaId), - getAuthHeaderConfig(), - ); + await axios.delete(API.DELETE_RUP_MONITORING_AREA(planId, pastureId, communityId, areaId), getAuthHeaderConfig()); }, ); @@ -118,12 +90,7 @@ export const deletePlantCommunityAction = createDeleteHandler( 'plantCommunityAction', async (planId, pastureId, communityId, actionId) => { await axios.delete( - API.DELETE_RUP_PLANT_COMMUNITY_ACTION( - planId, - pastureId, - communityId, - actionId, - ), + API.DELETE_RUP_PLANT_COMMUNITY_ACTION(planId, pastureId, communityId, actionId), getAuthHeaderConfig(), ); }, @@ -132,56 +99,35 @@ export const deletePlantCommunityAction = createDeleteHandler( export const deleteAdditionalRequirement = createDeleteHandler( 'additionalRequirement', async (planId, requirementId) => { - await axios.delete( - API.DELETE_RUP_ADDITIONAL_REQUIREMENT(planId, requirementId), - getAuthHeaderConfig(), - ); + await axios.delete(API.DELETE_RUP_ADDITIONAL_REQUIREMENT(planId, requirementId), getAuthHeaderConfig()); }, ); export const deleteManagementConsideration = createDeleteHandler( 'managementConsideration', async (planId, considerationId) => { - await axios.delete( - API.DELETE_RUP_MANAGEMENT_CONSIDERATION(planId, considerationId), - getAuthHeaderConfig(), - ); + await axios.delete(API.DELETE_RUP_MANAGEMENT_CONSIDERATION(planId, considerationId), getAuthHeaderConfig()); }, ); -export const deleteGrazingSchedule = createDeleteHandler( - 'grazingSchedule', - async (planId, scheduleId) => { - await axios.delete( - API.DELETE_RUP_GRAZING_SCHEDULE(planId, scheduleId), - getAuthHeaderConfig(), - ); - }, -); +export const deleteGrazingSchedule = createDeleteHandler('grazingSchedule', async (planId, scheduleId) => { + await axios.delete(API.DELETE_RUP_GRAZING_SCHEDULE(planId, scheduleId), getAuthHeaderConfig()); +}); export const deleteGrazingScheduleEntry = createDeleteHandler( 'grazingScheduleEntry', async (planId, scheduleId, entryId) => { - await axios.delete( - API.DELETE_RUP_GRAZING_SCHEDULE_ENTRY(planId, scheduleId, entryId), - getAuthHeaderConfig(), - ); + await axios.delete(API.DELETE_RUP_GRAZING_SCHEDULE_ENTRY(planId, scheduleId, entryId), getAuthHeaderConfig()); }, ); export const deleteIndicatorPlant = createDeleteHandler( 'indicatorPlant', async (planId, pastureId, communityId, plantId) => { - await axios.delete( - API.DELETE_RUP_INDICATOR_PLANT(planId, pastureId, communityId, plantId), - getAuthHeaderConfig(), - ); + await axios.delete(API.DELETE_RUP_INDICATOR_PLANT(planId, pastureId, communityId, plantId), getAuthHeaderConfig()); }, ); export const deleteAttachment = async (planId, attachmentId) => { - await axios.delete( - API.DELETE_RUP_ATTACHMENT(planId, attachmentId), - getAuthHeaderConfig(), - ); + await axios.delete(API.DELETE_RUP_ATTACHMENT(planId, attachmentId), getAuthHeaderConfig()); }; diff --git a/src/api/emailtemplate.js b/src/api/emailtemplate.js index 44d8bac6..dc8a5625 100644 --- a/src/api/emailtemplate.js +++ b/src/api/emailtemplate.js @@ -1,13 +1,7 @@ import * as API from '../constants/api'; import { getAuthHeaderConfig, axios } from '../utils'; -export const updateEmailTemplate = async ( - templateId, - name, - fromEmail, - subject, - body, -) => { +export const updateEmailTemplate = async (templateId, name, fromEmail, subject, body) => { return axios.put( API.UPDATE_EMAIL_TEMPLATE(templateId), { diff --git a/src/api/index.js b/src/api/index.js index 53e7eca5..44cba23d 100644 --- a/src/api/index.js +++ b/src/api/index.js @@ -10,13 +10,11 @@ export const createVersion = async (planId) => { export const saveGrazingSchedules = (planId, grazingSchedules, newPastures) => { return sequentialAsyncMap(grazingSchedules, async (schedule) => { - const grazingScheduleEntries = schedule.grazingScheduleEntries.map( - ({ id: entryId, ...entry }) => ({ - ...entry, - ...(!uuid.isUUID(entryId) && { id: entryId }), - pastureId: newPastures.find((p) => p.oldId === entry.pastureId).id, - }), - ); + const grazingScheduleEntries = schedule.grazingScheduleEntries.map(({ id: entryId, ...entry }) => ({ + ...entry, + ...(!uuid.isUUID(entryId) && { id: entryId }), + pastureId: newPastures.find((p) => p.oldId === entry.pastureId).id, + })); const { id, ...grazingSchedule } = schedule; if (uuid.isUUID(schedule.id)) { @@ -42,16 +40,10 @@ export const saveGrazingSchedules = (planId, grazingSchedules, newPastures) => { }); }; -export const saveInvasivePlantChecklist = async ( - planId, - invasivePlantChecklist, -) => { +export const saveInvasivePlantChecklist = async (planId, invasivePlantChecklist) => { if (invasivePlantChecklist && invasivePlantChecklist.id) { await axios.put( - API.UPDATE_RUP_INVASIVE_PLANT_CHECKLIST( - planId, - invasivePlantChecklist.id, - ), + API.UPDATE_RUP_INVASIVE_PLANT_CHECKLIST(planId, invasivePlantChecklist.id), invasivePlantChecklist, getAuthHeaderConfig(), ); @@ -59,11 +51,7 @@ export const saveInvasivePlantChecklist = async ( return invasivePlantChecklist; } else { const { id, ...values } = invasivePlantChecklist; - const { data } = await axios.post( - API.CREATE_RUP_INVASIVE_PLANT_CHECKLIST(planId), - values, - getAuthHeaderConfig(), - ); + const { data } = await axios.post(API.CREATE_RUP_INVASIVE_PLANT_CHECKLIST(planId), values, getAuthHeaderConfig()); return { ...invasivePlantChecklist, @@ -76,40 +64,25 @@ export const saveAttachments = async (planId, attachments) => { return sequentialAsyncMap(attachments, async (attachment) => { if (uuid.isUUID(attachment.id)) { const { id, ...values } = attachment; - const { data } = await axios.post( - API.CREATE_RUP_ATTACHMENT(planId), - values, - getAuthHeaderConfig(), - ); + const { data } = await axios.post(API.CREATE_RUP_ATTACHMENT(planId), values, getAuthHeaderConfig()); return { ...attachment, id: data.id, }; } else { - await axios.put( - API.UPDATE_RUP_ATTACHMENT(planId, attachment.id), - attachment, - getAuthHeaderConfig(), - ); + await axios.put(API.UPDATE_RUP_ATTACHMENT(planId, attachment.id), attachment, getAuthHeaderConfig()); return attachment; } }); }; -export const saveManagementConsiderations = ( - planId, - managementConsiderations, -) => { +export const saveManagementConsiderations = (planId, managementConsiderations) => { return sequentialAsyncMap(managementConsiderations, async (consideration) => { if (uuid.isUUID(consideration.id)) { const { id, ...values } = consideration; - const { data } = await axios.post( - API.CREATE_RUP_MANAGEMENT_CONSIDERATION(planId), - values, - getAuthHeaderConfig(), - ); + const { data } = await axios.post(API.CREATE_RUP_MANAGEMENT_CONSIDERATION(planId), values, getAuthHeaderConfig()); return { ...consideration, @@ -131,11 +104,7 @@ export const saveAdditionalRequirements = (planId, additionalRequirements) => { return sequentialAsyncMap(additionalRequirements, async (requirement) => { if (uuid.isUUID(requirement.id)) { const { id, ...values } = requirement; - const { data } = await axios.post( - API.CREATE_RUP_ADDITIONAL_REQUIREMENT(planId), - values, - getAuthHeaderConfig(), - ); + const { data } = await axios.post(API.CREATE_RUP_ADDITIONAL_REQUIREMENT(planId), values, getAuthHeaderConfig()); return { ...requirement, @@ -175,11 +144,7 @@ export const saveMinisterIssues = (planId, ministerIssues, newPastures) => { getAuthHeaderConfig(), ); - const newActions = await saveMinisterIssueActions( - planId, - newIssue.id, - issue.ministerIssueActions, - ); + const newActions = await saveMinisterIssueActions(planId, newIssue.id, issue.ministerIssueActions); return { ...issue, @@ -196,11 +161,7 @@ export const saveMinisterIssues = (planId, ministerIssues, newPastures) => { getAuthHeaderConfig(), ); - const newActions = await saveMinisterIssueActions( - planId, - issue.id, - issue.ministerIssueActions, - ); + const newActions = await saveMinisterIssueActions(planId, issue.id, issue.ministerIssueActions); return { ...issue, @@ -240,20 +201,12 @@ export const savePastures = async (planId, pastures) => { // Sequentially save pastures to keep order return sequentialAsyncMap(pastures, async (pasture) => { if (Number(pasture.id)) { - await axios.put( - API.UPDATE_RUP_PASTURE(planId, pasture.id), - pasture, - getAuthHeaderConfig(), - ); + await axios.put(API.UPDATE_RUP_PASTURE(planId, pasture.id), pasture, getAuthHeaderConfig()); return { ...pasture, oldId: pasture.id }; } else { const { id, ...values } = pasture; - const { data } = await axios.post( - API.CREATE_RUP_PASTURE(planId), - values, - getAuthHeaderConfig(), - ); + const { data } = await axios.post(API.CREATE_RUP_PASTURE(planId), values, getAuthHeaderConfig()); return { ...pasture, @@ -264,11 +217,7 @@ export const savePastures = async (planId, pastures) => { }); }; -export const savePlantCommunities = async ( - planId, - pastureId, - plantCommunities, -) => { +export const savePlantCommunities = async (planId, pastureId, plantCommunities) => { // Sequentially save plant communities (to keep order) return sequentialAsyncMap( plantCommunities, @@ -276,49 +225,21 @@ export const savePlantCommunities = async ( let { id: communityId, ...values } = plantCommunity; if (uuid.isUUID(communityId)) { communityId = ( - await axios.post( - API.CREATE_RUP_PLANT_COMMUNITY(planId, pastureId), - values, - getAuthHeaderConfig(), - ) + await axios.post(API.CREATE_RUP_PLANT_COMMUNITY(planId, pastureId), values, getAuthHeaderConfig()) ).data.id; } else { - await axios.put( - API.UPDATE_RUP_PLANT_COMMUNITY(planId, pastureId, communityId), - values, - getAuthHeaderConfig(), - ); + await axios.put(API.UPDATE_RUP_PLANT_COMMUNITY(planId, pastureId, communityId), values, getAuthHeaderConfig()); } - await savePlantCommunityActions( - planId, - pastureId, - communityId, - plantCommunity.plantCommunityActions, - ); - await saveIndicatorPlants( - planId, - pastureId, - communityId, - plantCommunity.indicatorPlants, - ); - await saveMonitoringAreas( - planId, - pastureId, - communityId, - plantCommunity.monitoringAreas, - ); + await savePlantCommunityActions(planId, pastureId, communityId, plantCommunity.plantCommunityActions); + await saveIndicatorPlants(planId, pastureId, communityId, plantCommunity.indicatorPlants); + await saveMonitoringAreas(planId, pastureId, communityId, plantCommunity.monitoringAreas); }, Promise.resolve(), ); }; -const savePlantCommunityActions = ( - planId, - pastureId, - communityId, - plantCommunityActions, -) => { +const savePlantCommunityActions = (planId, pastureId, communityId, plantCommunityActions) => { return sequentialAsyncMap(plantCommunityActions, (action) => { let { id: actionId, ...values } = action; if (uuid.isUUID(actionId)) { @@ -329,12 +250,7 @@ const savePlantCommunityActions = ( ); } else { return axios.put( - API.UPDATE_RUP_PLANT_COMMUNITY_ACTION( - planId, - pastureId, - communityId, - actionId, - ), + API.UPDATE_RUP_PLANT_COMMUNITY_ACTION(planId, pastureId, communityId, actionId), values, getAuthHeaderConfig(), ); @@ -342,20 +258,11 @@ const savePlantCommunityActions = ( }); }; -const saveIndicatorPlants = ( - planId, - pastureId, - communityId, - indicatorPlants, -) => { +const saveIndicatorPlants = (planId, pastureId, communityId, indicatorPlants) => { return sequentialAsyncMap(indicatorPlants, (plant) => { let { id: plantId, ...values } = plant; if (uuid.isUUID(plantId)) { - return axios.post( - API.CREATE_RUP_INDICATOR_PLANT(planId, pastureId, communityId), - values, - getAuthHeaderConfig(), - ); + return axios.post(API.CREATE_RUP_INDICATOR_PLANT(planId, pastureId, communityId), values, getAuthHeaderConfig()); } else { return axios.put( API.UPDATE_RUP_INDICATOR_PLANT(planId, pastureId, communityId, plantId), @@ -366,20 +273,11 @@ const saveIndicatorPlants = ( }); }; -const saveMonitoringAreas = ( - planId, - pastureId, - communityId, - monitoringAreas, -) => { +const saveMonitoringAreas = (planId, pastureId, communityId, monitoringAreas) => { return sequentialAsyncMap(monitoringAreas, (area) => { let { id: areaId, ...values } = area; if (uuid.isUUID(areaId)) { - return axios.post( - API.CREATE_RUP_MONITERING_AREA(planId, pastureId, communityId), - values, - getAuthHeaderConfig(), - ); + return axios.post(API.CREATE_RUP_MONITERING_AREA(planId, pastureId, communityId), values, getAuthHeaderConfig()); } else { return axios.put( API.UPDATE_RUP_MONITORING_AREA(planId, pastureId, communityId, areaId), diff --git a/src/api/plan.js b/src/api/plan.js index d5fac2fa..22abfc19 100644 --- a/src/api/plan.js +++ b/src/api/plan.js @@ -1,11 +1,5 @@ import uuid from 'uuid-v4'; -import { - axios, - getAuthHeaderConfig, - findStatusWithCode, - isUserAgrologist, - canUserAddAttachments, -} from '../utils'; +import { axios, getAuthHeaderConfig, findStatusWithCode, isUserAgrologist, canUserAddAttachments } from '../utils'; import * as API from '../constants/api'; import RUPSchema from '../components/rangeUsePlanPage/schema'; import { getNetworkStatus } from '../utils/helper/network'; @@ -20,11 +14,7 @@ import { savePastures, saveAttachments, } from '.'; -import { - REFERENCE_KEY, - AMENDMENT_TYPE, - PLAN_STATUS, -} from '../constants/variables'; +import { REFERENCE_KEY, AMENDMENT_TYPE, PLAN_STATUS } from '../constants/variables'; /** * Syncs plan and then returns locally stored record @@ -55,10 +45,7 @@ const syncPlan = async (planId, user) => { await savePlan(localPlan, user); } - const { data: serverPlan } = await axios.get( - API.GET_RUP(planId), - getAuthHeaderConfig(), - ); + const { data: serverPlan } = await axios.get(API.GET_RUP(planId), getAuthHeaderConfig()); savePlanToLocalStorage(serverPlan, true); } }; @@ -202,23 +189,11 @@ export const updatePlan = async (planId, data) => { return await axios.put(API.UPDATE_RUP(planId), data, getAuthHeaderConfig()); }; -export const createAmendment = async ( - plan, - references, - staffInitiated = false, -) => { +export const createAmendment = async (plan, references, staffInitiated = false) => { const amendmentTypes = references[REFERENCE_KEY.AMENDMENT_TYPE]; - const initialAmendment = amendmentTypes.find( - (at) => at.code === AMENDMENT_TYPE.INITIAL, - ); - const ahAmendmentStatus = findStatusWithCode( - references, - PLAN_STATUS.AMENDMENT_AH, - ); - const staffAmendmentStatus = findStatusWithCode( - references, - PLAN_STATUS.MANDATORY_AMENDMENT_STAFF, - ); + const initialAmendment = amendmentTypes.find((at) => at.code === AMENDMENT_TYPE.INITIAL); + const ahAmendmentStatus = findStatusWithCode(references, PLAN_STATUS.AMENDMENT_AH); + const staffAmendmentStatus = findStatusWithCode(references, PLAN_STATUS.MANDATORY_AMENDMENT_STAFF); await axios.put( API.UPDATE_RUP(plan.id), @@ -240,16 +215,11 @@ export const createAmendment = async ( }; export const updateStatus = async ({ planId, note, statusId }) => { - await axios.put( - API.UPDATE_PLAN_STATUS(planId), - { note, statusId }, - getAuthHeaderConfig(), - ); + await axios.put(API.UPDATE_PLAN_STATUS(planId), { note, statusId }, getAuthHeaderConfig()); }; export const createReplacementPlan = async (planId) => { - return (await axios.put(API.REPLACEMENT_PLAN(planId), getAuthHeaderConfig())) - .data.replacementPlan; + return (await axios.put(API.REPLACEMENT_PLAN(planId), getAuthHeaderConfig())).data.replacementPlan; }; export const updateConfirmation = async ({ @@ -283,10 +253,7 @@ export const getMostRecentLegalPlan = async (planId) => { throw new Error('Could not find legal version'); } - const { data } = await axios.get( - API.GET_RUP_VERSION(planId, legalVersion.version), - getAuthHeaderConfig(), - ); + const { data } = await axios.get(API.GET_RUP_VERSION(planId, legalVersion.version), getAuthHeaderConfig()); return data; }; @@ -298,11 +265,7 @@ export const discardAmendment = async (planId) => { export const amendFromLegal = async (plan, references, staffInitiated) => { const { version } = await getMostRecentLegalPlan(plan.id); - await axios.post( - API.RESTORE_RUP_VERSION(plan.id, version), - {}, - getAuthHeaderConfig(), - ); + await axios.post(API.RESTORE_RUP_VERSION(plan.id, version), {}, getAuthHeaderConfig()); await createAmendment(plan, references, staffInitiated); }; @@ -310,12 +273,7 @@ export const generatePDF = async (planId) => { return await axios.get(API.GET_RUP_PDF(planId), getAuthHeaderConfig()); }; -export const updateSortOrder = async ( - planId, - scheduleId, - sortBy, - sortOrder, -) => { +export const updateSortOrder = async (planId, scheduleId, sortBy, sortOrder) => { return axios.put( API.UPDATE_SCHEDULE_SORT_ORDER(planId, scheduleId), { diff --git a/src/api/user.js b/src/api/user.js index c73aea52..eb32f387 100644 --- a/src/api/user.js +++ b/src/api/user.js @@ -2,48 +2,25 @@ import * as API from '../constants/api'; import { getAuthHeaderConfig, axios } from '../utils'; export const createClientLink = async (userId, clientNumber) => { - return axios.post( - API.CREATE_USER_CLIENT_LINK(userId), - { clientId: clientNumber }, - getAuthHeaderConfig(), - ); + return axios.post(API.CREATE_USER_CLIENT_LINK(userId), { clientId: clientNumber }, getAuthHeaderConfig()); }; export const deleteClientLink = async (userId, clientNumber) => { - return axios.delete( - API.DELETE_USER_CLIENT_LINK(userId, clientNumber), - getAuthHeaderConfig(), - ); + return axios.delete(API.DELETE_USER_CLIENT_LINK(userId, clientNumber), getAuthHeaderConfig()); }; export const mergeAccounts = async (sourceAccountIds, destinationAccountId) => { - return axios.post( - API.MERGE_ACCOUNTS(destinationAccountId), - { accountIds: sourceAccountIds }, - getAuthHeaderConfig(), - ); + return axios.post(API.MERGE_ACCOUNTS(destinationAccountId), { accountIds: sourceAccountIds }, getAuthHeaderConfig()); }; export const assignRole = async (userId, roleId) => { - return axios.post( - API.ASSIGN_ROLE(userId), - { roleId: roleId }, - getAuthHeaderConfig(), - ) -} + return axios.post(API.ASSIGN_ROLE(userId), { roleId: roleId }, getAuthHeaderConfig()); +}; export const assignDistrict = async (userId, districtId) => { - return axios.post( - API.ASSIGN_DISTRICT(userId), - { districtId: districtId }, - getAuthHeaderConfig(), - ) -} + return axios.post(API.ASSIGN_DISTRICT(userId), { districtId: districtId }, getAuthHeaderConfig()); +}; export const assignDistricts = async (userId, districts) => { - return axios.post( - API.ASSIGN_DISTRICTS(userId), - { districts: districts }, - getAuthHeaderConfig(), - ) -} \ No newline at end of file + return axios.post(API.ASSIGN_DISTRICTS(userId), { districts: districts }, getAuthHeaderConfig()); +}; diff --git a/src/components/PageNotFound.js b/src/components/PageNotFound.js index b968b301..6945c780 100644 --- a/src/components/PageNotFound.js +++ b/src/components/PageNotFound.js @@ -31,18 +31,11 @@ class PageNotFound extends Component { return (
- cow-img + cow-img
Page Not Found

This is not the web page you are looking for.

-

- You will be redirected to the {APP_NAME} home page within 10 - seconds. -

+

You will be redirected to the {APP_NAME} home page within 10 seconds.

Go to home diff --git a/src/components/ReturnPage.js b/src/components/ReturnPage.js index ee02e818..5c3e6af5 100644 --- a/src/components/ReturnPage.js +++ b/src/components/ReturnPage.js @@ -1,11 +1,6 @@ import React, { Component } from 'react'; import PropTypes from 'prop-types'; -import { - parseQuery, - getTokenFromSSO, - saveAuthDataInLocal, - getDataFromLocalStorage, -} from '../utils'; +import { parseQuery, getTokenFromSSO, saveAuthDataInLocal, getDataFromLocalStorage } from '../utils'; import { SSO_LOGOUT_ENDPOINT } from '../constants/api'; import { REDIRECTING } from '../constants/strings'; import { LOCAL_STORAGE_KEY, RETURN_PAGE_TYPE } from '../constants/variables'; @@ -23,9 +18,7 @@ class ReturnPage extends Component { switch (type) { case RETURN_PAGE_TYPE.LOGIN: if (code) { - const { codeVerifier, codeVerifierHash } = getDataFromLocalStorage( - LOCAL_STORAGE_KEY.AUTH_PKCE_CODE, - ); + const { codeVerifier, codeVerifierHash } = getDataFromLocalStorage(LOCAL_STORAGE_KEY.AUTH_PKCE_CODE); if (!codeVerifier || !codeVerifierHash) { // we cannot proceed without the pkce challenge code window.close(); diff --git a/src/components/assignRolesAndDistrictsPage/index.js b/src/components/assignRolesAndDistrictsPage/index.js index 27e52ff2..035488fb 100644 --- a/src/components/assignRolesAndDistrictsPage/index.js +++ b/src/components/assignRolesAndDistrictsPage/index.js @@ -1,26 +1,11 @@ import React, { useState } from 'react'; import useSWR from 'swr'; -import { - CircularProgress, - TextField, - Grid, - Typography, - makeStyles, - Button, - Fade, -} from '@material-ui/core'; +import { CircularProgress, TextField, Grid, Typography, makeStyles, Button, Fade } from '@material-ui/core'; import { Autocomplete } from '@material-ui/lab'; import PersonIcon from '@material-ui/icons/Person'; import * as strings from '../../constants/strings'; import * as API from '../../constants/api'; -import { - axios, - formatDateToNow, - getAuthHeaderConfig, - getUserFullName, - getUserRole, - getUserRoleObj, -} from '../../utils'; +import { axios, formatDateToNow, getAuthHeaderConfig, getUserFullName, getUserRole, getUserRoleObj } from '../../utils'; import { Banner } from '../common'; import { assignRole, assignDistricts } from '../../api'; @@ -44,21 +29,18 @@ const AssignRolesAndDistrictsPage = () => { data: usersFromData, error, isValidating, - } = useSWR( - `${API.GET_USERS}/?orderCId=desc`, - (key) => axios.get(key, getAuthHeaderConfig()).then((res) => { + } = useSWR(`${API.GET_USERS}/?orderCId=desc`, (key) => + axios.get(key, getAuthHeaderConfig()).then((res) => { setUsers(res.data); - return res.data + return res.data; }), ); - const { data: roles } = useSWR( - `${API.GET_ROLES}`, (key) => + const { data: roles } = useSWR(`${API.GET_ROLES}`, (key) => axios.get(key, getAuthHeaderConfig()).then((res) => { return res.data; }), ); - const { data: districtsFromData } = useSWR( - `${API.GET_DISTRICTS}`, (key) => + const { data: districtsFromData } = useSWR(`${API.GET_DISTRICTS}`, (key) => axios.get(key, getAuthHeaderConfig()).then((res) => { setDistricts(res.data); return res.data; @@ -71,7 +53,7 @@ const AssignRolesAndDistrictsPage = () => { setAssigningSuccess(null); try { if (role.id === -1) { - setAssigningError("No role has been selected"); + setAssigningError('No role has been selected'); return; } await assignRole(user.id, role.id); @@ -79,7 +61,7 @@ const AssignRolesAndDistrictsPage = () => { setAssigningSuccess('Role and Districts assigned to account successfully'); axios.get(`${API.GET_USERS}/?orderCId=desc`, getAuthHeaderConfig()).then((res) => { setUsers([...res.data]); - return res.data + return res.data; }); axios.get(`${API.GET_DISTRICTS}`, getAuthHeaderConfig()).then((res) => { setDistricts([...res.data]); @@ -90,7 +72,7 @@ const AssignRolesAndDistrictsPage = () => { } finally { setAssigning(false); } - } + }; const pullRoleAndDistrict = (user) => { // Role @@ -99,9 +81,9 @@ const AssignRolesAndDistrictsPage = () => { // District axios.get(`${API.GET_DISTRICTS}/${user.id}`, getAuthHeaderConfig()).then((res) => { setSelectedDistricts([...res.data]); - return res.data - }) - } + return res.data; + }); + }; const [users, setUsers] = useState([]); const [districts, setDistricts] = useState([]); @@ -112,23 +94,15 @@ const AssignRolesAndDistrictsPage = () => { const [assigningError, setAssigningError] = useState(null); const [assigningSuccess, setAssigningSuccess] = useState(null); - return (
- +
- -

- Select the user who you'd like to edit: -

+

Select the user who you'd like to edit:

{error && ( - index.js Error occurred fetching user:{' '} - {error?.message ?? error?.data?.error ?? JSON.stringify(error)} + index.js Error occurred fetching user: {error?.message ?? error?.data?.error ?? JSON.stringify(error)} )} {isValidating && !usersFromData && } @@ -146,23 +120,15 @@ const AssignRolesAndDistrictsPage = () => { getOptionLabel={(option) => getUserFullName(option)} getOptionSelected={(option) => option.id === user.id} style={{ width: 400 }} - renderInput={(params) => ( - - )} + renderInput={(params) => } renderOption={(option) => ( - {option.id} - {getUserFullName(option)} - - {getUserRole(option)} - + {option.id} - {getUserFullName(option)} + {getUserRole(option)} {formatDateToNow(option.lastLoginAt)} @@ -178,77 +144,60 @@ const AssignRolesAndDistrictsPage = () => {

- {user && selectedDistricts && <> - {/* Roles */} - { - setRole(role); - }} - getOptionLabel={(option) => option.description} - style={{ width: 400 }} - renderInput={(params) => ( - - )} - renderOption={(option) => ( - - - {option.description} + {user && selectedDistricts && ( + <> + {/* Roles */} + { + setRole(role); + }} + getOptionLabel={(option) => option.description} + style={{ width: 400 }} + renderInput={(params) => } + renderOption={(option) => ( + + + {option.description} + - - )} - /> + )} + /> -

+

- {/* Districts */} - 0 ? districts : districtsFromData} - value={selectedDistricts} - openOnFocus - onChange={(e, districts) => { - setSelectedDistricts(districts); - }} - getOptionLabel={(option) => `${option.code}`} - style={{ width: 400 }} - renderInput={(params) => ( - - )} - renderOption={(option) => ( - - - - {option.code} - - - ID: {option.id} - - - {option.description} - + {/* Districts */} + 0 ? districts : districtsFromData} + value={selectedDistricts} + openOnFocus + onChange={(e, districts) => { + setSelectedDistricts(districts); + }} + getOptionLabel={(option) => `${option.code}`} + style={{ width: 400 }} + renderInput={(params) => } + renderOption={(option) => ( + + + + {option.code} + + + ID: {option.id} + + {option.description} + - - )} - /> - } + )} + /> + + )} {role && selectedDistricts && user && ( <> @@ -261,10 +210,7 @@ const AssignRolesAndDistrictsPage = () => { user === null || selectedDistricts === null || role === null || - ( - role?.id === 4 && - selectedDistricts?.length > 0 - ) + (role?.id === 4 && selectedDistricts?.length > 0) } variant="contained" color="primary" @@ -278,29 +224,19 @@ const AssignRolesAndDistrictsPage = () => { }} unmountOnExit > - + )} - ) - } + )} {assigningError && {assigningError}} - { - (role?.id === 4 && selectedDistricts?.length > 0)&& + {role?.id === 4 && selectedDistricts?.length > 0 && ( Range Agreement Holders cannot be assigned districts. - } - - {assigningSuccess && ( - - {assigningSuccess} - )} + {assigningSuccess && {assigningSuccess}}
diff --git a/src/components/common/Avatar.story.js b/src/components/common/Avatar.story.js index 31e98454..c65aafe3 100644 --- a/src/components/common/Avatar.story.js +++ b/src/components/common/Avatar.story.js @@ -6,6 +6,4 @@ import Avatar from './Avatar'; storiesOf('Avatar', module) .add('Default', () => ) - .add('with user prop', () => ( - - )); + .add('with user prop', () => ); diff --git a/src/components/common/Banner.js b/src/components/common/Banner.js index e158bf3d..71ec12dc 100644 --- a/src/components/common/Banner.js +++ b/src/components/common/Banner.js @@ -14,14 +14,7 @@ const defaultProps = { noDefaultHeight: false, }; -const Banner = ({ - header, - content, - style, - noDefaultHeight, - contentLine2, - isReplacementPlan, -}) => ( +const Banner = ({ header, content, style, noDefaultHeight, contentLine2, isReplacementPlan }) => (
); -stories.add('with props', () => ( - -)); +stories.add('with props', () => ); stories.add('with long content', () => { const content = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus vel venenatis purus, vitae viverra ex. Nulla ac nisl aliquam, eleifend neque vitae, feugiat magna. Nunc venenatis dui et odio pulvinar tincidunt. Nunc in maximus est, at faucibus elit. Fusce auctor aliquet orci eu viverra. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean cursus condimentum viverra. Nullam tempus sapien vulputate faucibus malesuada. Fusce aliquet purus nulla, a hendrerit arcu tristique a. Donec massa erat, commodo quis leo non, blandit egestas turpis. Proin tempor rhoncus orci, ac euismod lectus vulputate et. Suspendisse nisi nibh, tincidunt aliquam aliquet at, pellentesque et enim. Maecenas laoreet est eu urna volutpat, vitae cursus justo dignissim. Maecenas venenatis condimentum nunc a cursus.'; return ; }); -stories.add('with knobs', () => ( - -)); +stories.add('with knobs', () => ); diff --git a/src/components/common/CollapsibleBox.js b/src/components/common/CollapsibleBox.js index 8d7bf415..5ffd111c 100644 --- a/src/components/common/CollapsibleBox.js +++ b/src/components/common/CollapsibleBox.js @@ -52,23 +52,15 @@ class CollapsibleBox extends Component { 'collaspible-box__header__title--active': isActive, 'collaspible-box__header__title--error': error, })} - onClick={ - onContentClick ? onContentClick : onContentClicked(contentIndex) - } + onClick={onContentClick ? onContentClick : onContentClicked(contentIndex)} > {header}
{additionalHeaderRight} {isActive ? ( - + ) : ( - + )}
diff --git a/src/components/common/ErrorMessage.story.js b/src/components/common/ErrorMessage.story.js index cf52088c..2ced6a1d 100644 --- a/src/components/common/ErrorMessage.story.js +++ b/src/components/common/ErrorMessage.story.js @@ -7,6 +7,4 @@ import ErrorMessage from './ErrorMessage'; storiesOf('Error Message', module) .add('Message', () => ) - .add('With warning', () => ( - - )); + .add('With warning', () => ); diff --git a/src/components/common/ErrorPage.js b/src/components/common/ErrorPage.js index a7dcc283..f1a7f5dc 100644 --- a/src/components/common/ErrorPage.js +++ b/src/components/common/ErrorPage.js @@ -15,10 +15,7 @@ const ErrorPage = ({ message }) => { {message}
- window.location.reload(true)} - content="Reload" - /> + window.location.reload(true)} content="Reload" />
); diff --git a/src/components/common/InfoTip.story.js b/src/components/common/InfoTip.story.js index 2112cedc..7f1387f9 100644 --- a/src/components/common/InfoTip.story.js +++ b/src/components/common/InfoTip.story.js @@ -6,12 +6,7 @@ import InfoTip from './InfoTip'; const stories = storiesOf('InfoTip', module); stories.addDecorator(withKnobs); -stories.add('default', () => ( - -)); +stories.add('default', () => ); stories.add('with knobs', () => ( - + )); diff --git a/src/components/common/InputModal.js b/src/components/common/InputModal.js index 83e7ded5..555a43e5 100644 --- a/src/components/common/InputModal.js +++ b/src/components/common/InputModal.js @@ -26,13 +26,7 @@ const InputModal = ({ onSubmit(input); }} render={({ resetForm, handleSubmit }) => ( - + {title} @@ -43,11 +37,7 @@ const InputModal = ({ handleSubmit(); }} > - + diff --git a/src/components/common/InputModal.story.js b/src/components/common/InputModal.story.js index 5d2d49d5..330cec83 100644 --- a/src/components/common/InputModal.story.js +++ b/src/components/common/InputModal.story.js @@ -5,10 +5,5 @@ import { action } from '@storybook/addon-actions'; import InputModal from './InputModal'; storiesOf('InputModal', module).add('default', () => ( - + )); diff --git a/src/components/common/ListModal.js b/src/components/common/ListModal.js index 599f6e6b..60f8333b 100644 --- a/src/components/common/ListModal.js +++ b/src/components/common/ListModal.js @@ -15,20 +15,9 @@ const ListModal = ({ const [selected, setSelected] = useState([]); return ( - + {title} - + {options.map((option) => ( { +const Loading = ({ size, active, inverted, message, onlySpinner, containerProps }) => { if (onlySpinner) { return (
diff --git a/src/components/common/NetworkStatus.js b/src/components/common/NetworkStatus.js index 08a474ad..94e41389 100644 --- a/src/components/common/NetworkStatus.js +++ b/src/components/common/NetworkStatus.js @@ -1,8 +1,5 @@ import React from 'react'; -import { - useNetworkStatus, - usePlanSyncedStatus, -} from '../../utils/hooks/network'; +import { useNetworkStatus, usePlanSyncedStatus } from '../../utils/hooks/network'; const NetworkStatus = ({ planId }) => { const online = useNetworkStatus(); @@ -10,9 +7,7 @@ const NetworkStatus = ({ planId }) => { return (
- + {online ? 'Online' : 'Offline'} ({synced ? 'Synced' : 'Not synced'}) diff --git a/src/components/common/PermissionsField.js b/src/components/common/PermissionsField.js index e2ca490f..991e4a1e 100644 --- a/src/components/common/PermissionsField.js +++ b/src/components/common/PermissionsField.js @@ -10,8 +10,7 @@ import { handleNullValue } from '../../utils'; import { useEditable } from '../../providers/EditableProvider'; import MultiParagraphDisplay from './MultiParagraphDisplay'; -export const canUserEdit = (field, user) => - permissions[user.roleId]?.includes(field); +export const canUserEdit = (field, user) => permissions[user.roleId]?.includes(field); const PermissionsField = ({ permission, @@ -44,10 +43,7 @@ const PermissionsField = ({
)} { const arrayFn = any ? some : every; const canEdit = - (Array.isArray(permission) - ? arrayFn(permission, (p) => canUserEdit(p, user)) - : canUserEdit(permission, user)) && globalIsEditable; + (Array.isArray(permission) ? arrayFn(permission, (p) => canUserEdit(p, user)) : canUserEdit(permission, user)) && + globalIsEditable; if (!invert && canEdit) return children; if (invert && !canEdit) return children; @@ -83,8 +78,7 @@ export const IfEditable = ({ children, permission, invert, any = false }) => { IfEditable.propTypes = { children: PropTypes.node, - permission: PropTypes.oneOfType([PropTypes.string, PropTypes.array]) - .isRequired, + permission: PropTypes.oneOfType([PropTypes.string, PropTypes.array]).isRequired, invert: PropTypes.bool, }; diff --git a/src/components/common/PrimaryButton.story.js b/src/components/common/PrimaryButton.story.js index 69d8cde8..436ad86e 100644 --- a/src/components/common/PrimaryButton.story.js +++ b/src/components/common/PrimaryButton.story.js @@ -8,24 +8,18 @@ storiesOf('Priamry Button', module) .add('Inverted', () => ) - .add('Inverted with children', () => ( - Button - )) + .add('Inverted with children', () => Button) .add('With children', () => Button) .add('With long children', () => ( - Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus vel - venenatis purus, vitae viverra ex. Nulla ac nisl aliquam, eleifend neque - vitae, feugiat magna. Nunc venenatis dui et odio pulvinar tincidunt. Nunc - in maximus est, at faucibus elit. Fusce auctor aliquet orci eu viverra. - Orci varius natoque penatibus et magnis dis parturient montes, nascetur - ridiculus mus. Aenean cursus condimentum viverra. Nullam tempus sapien - vulputate faucibus malesuada. Fusce aliquet purus nulla, a hendrerit arcu - tristique a. Donec massa erat, commodo quis leo non, blandit egestas - turpis. Proin tempor rhoncus orci, ac euismod lectus vulputate et. - Suspendisse nisi nibh, tincidunt aliquam aliquet at, pellentesque et enim. - Maecenas laoreet est eu urna volutpat, vitae cursus justo dignissim. - Maecenas venenatis condimentum nunc a cursus. + Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus vel venenatis purus, vitae viverra ex. Nulla ac + nisl aliquam, eleifend neque vitae, feugiat magna. Nunc venenatis dui et odio pulvinar tincidunt. Nunc in maximus + est, at faucibus elit. Fusce auctor aliquet orci eu viverra. Orci varius natoque penatibus et magnis dis + parturient montes, nascetur ridiculus mus. Aenean cursus condimentum viverra. Nullam tempus sapien vulputate + faucibus malesuada. Fusce aliquet purus nulla, a hendrerit arcu tristique a. Donec massa erat, commodo quis leo + non, blandit egestas turpis. Proin tempor rhoncus orci, ac euismod lectus vulputate et. Suspendisse nisi nibh, + tincidunt aliquam aliquet at, pellentesque et enim. Maecenas laoreet est eu urna volutpat, vitae cursus justo + dignissim. Maecenas venenatis condimentum nunc a cursus. )); diff --git a/src/components/common/Select.js b/src/components/common/Select.js index 708808f8..02216020 100644 --- a/src/components/common/Select.js +++ b/src/components/common/Select.js @@ -2,14 +2,7 @@ import React from 'react'; import ReactSelect from 'react-select'; import { connect, getIn } from 'formik'; -const Select = ({ - name, - formik, - onChange, - options = [], - inputProps, - ...props -}) => { +const Select = ({ name, formik, onChange, options = [], inputProps, ...props }) => { const currentValue = getIn(formik.values, name); const selectedOption = options.find((f) => f.value === currentValue); diff --git a/src/components/common/SortableTableHeaderCell.js b/src/components/common/SortableTableHeaderCell.js index 827b5f54..56d4e79c 100644 --- a/src/components/common/SortableTableHeaderCell.js +++ b/src/components/common/SortableTableHeaderCell.js @@ -1,25 +1,10 @@ import React from 'react'; import { TableHeaderCell } from 'semantic-ui-react'; -const SortableTableHeaderCell = ({ - column, - children, - currentSortBy, - currentSortOrder, - onClick, - noSort = false, -}) => { - if (noSort) - return ( - - {children} - - ); +const SortableTableHeaderCell = ({ column, children, currentSortBy, currentSortOrder, onClick, noSort = false }) => { + if (noSort) return {children}; return ( - onClick(column)} - > + onClick(column)}> {children} ); diff --git a/src/components/common/Status.js b/src/components/common/Status.js index bd08ddee..206f57aa 100644 --- a/src/components/common/Status.js +++ b/src/components/common/Status.js @@ -3,11 +3,7 @@ import PropTypes from 'prop-types'; import classnames from 'classnames'; import { PLAN_STATUS } from '../../constants/variables'; import { NO_PLAN } from '../../constants/strings'; -import { - isUserAgreementHolder, - isUserAgrologist, - isUserDecisionMaker, -} from '../../utils'; +import { isUserAgreementHolder, isUserAgrologist, isUserDecisionMaker } from '../../utils'; const propTypes = { user: PropTypes.shape({}).isRequired, @@ -28,11 +24,7 @@ const defaultProps = { style: {}, }; -export const translateStatusBasedOnUser = ( - status, - user, - isForVersionsList = false, -) => { +export const translateStatusBasedOnUser = (status, user, isForVersionsList = false) => { let modifier = 'status__icon'; let statusName = status.code ? 'Unknown_status' : NO_PLAN; switch (status.code) { @@ -215,27 +207,14 @@ export const translateStatusBasedOnUser = ( return { modifier, statusName }; }; -const Status = ({ - status, - className, - style, - user, - isAmendment = false, - isForVersionsList = false, -}) => { - const { modifier, statusName } = translateStatusBasedOnUser( - status, - user, - isForVersionsList, - ); +const Status = ({ status, className, style, user, isAmendment = false, isForVersionsList = false }) => { + const { modifier, statusName } = translateStatusBasedOnUser(status, user, isForVersionsList); return (
{statusName} - {isAmendment && ( - Amendment - )} + {isAmendment && Amendment}
); }; diff --git a/src/components/common/Status.story.js b/src/components/common/Status.story.js index 7f7b648b..f85b456e 100644 --- a/src/components/common/Status.story.js +++ b/src/components/common/Status.story.js @@ -11,20 +11,13 @@ const userPropOptions = { 'Not Agreement Holder': { roles: [] }, }; -const statusPropOptions = Object.fromEntries( - Object.entries(PLAN_STATUS).map(([status, code]) => [status, { code }]), -); +const statusPropOptions = Object.fromEntries(Object.entries(PLAN_STATUS).map(([status, code]) => [status, { code }])); storiesOf('Status', module) .addDecorator(withKnobs) .add('With Knobs', () => ( )); diff --git a/src/components/common/TextField.js b/src/components/common/TextField.js index 6d11a61f..92f8a04c 100644 --- a/src/components/common/TextField.js +++ b/src/components/common/TextField.js @@ -7,11 +7,7 @@ import { handleNullValue } from '../../utils'; const propTypes = { className: PropTypes.string, label: PropTypes.string.isRequired, - text: PropTypes.oneOfType([ - PropTypes.object, - PropTypes.string, - PropTypes.number, - ]), + text: PropTypes.oneOfType([PropTypes.object, PropTypes.string, PropTypes.number]), isLabelHidden: PropTypes.bool, isEditable: PropTypes.bool, onClick: PropTypes.func, @@ -25,14 +21,7 @@ const defaultProps = { onClick: () => {}, }; -const TextField = ({ - className, - label, - text: rawText, - isLabelHidden, - isEditable, - onClick, -}) => { +const TextField = ({ className, label, text: rawText, isLabelHidden, isEditable, onClick }) => { const text = handleNullValue(rawText); return ( diff --git a/src/components/common/footer/PrivacyInfoModal.js b/src/components/common/footer/PrivacyInfoModal.js index 5e975d83..4622b642 100644 --- a/src/components/common/footer/PrivacyInfoModal.js +++ b/src/components/common/footer/PrivacyInfoModal.js @@ -17,39 +17,25 @@ class PrivacyInfoModal extends Component { const { closePiaModal, isModalOpen } = this.props; return ( - +
Privacy Information
-
- Please review to return to {APP_NAME} -
+
Please review to return to {APP_NAME}
- Personal information is collected under the legal authority of - section 26 (c) and 27 (1)(a)(i) of the Freedom of Information - and Protection of Privacy Act (the Act). The collection, use, - and disclosure of personal information is subject to the - provisions of the Act. The personal information collected will - be used to process your submission(s). It may also be shared - when strictly necessary with partner agencies that are also - subject to the provisions of the Act. The personal information - supplied in the submission may be used for referrals, - consultation, or notifications as required. Staff may use your - personal information to contact you regarding your submission or - for survey purposes. + Personal information is collected under the legal authority of section 26 (c) and 27 (1)(a)(i) of the + Freedom of Information and Protection of Privacy Act (the Act). The collection, use, and disclosure of + personal information is subject to the provisions of the Act. The personal information collected will be + used to process your submission(s). It may also be shared when strictly necessary with partner agencies + that are also subject to the provisions of the Act. The personal information supplied in the submission + may be used for referrals, consultation, or notifications as required. Staff may use your personal + information to contact you regarding your submission or for survey purposes.
- For more information regarding the collection, use, and/or - disclosure of your personal information, please contact - MyRangeBC Administrator at: + For more information regarding the collection, use, and/or disclosure of your personal information, + please contact MyRangeBC Administrator at:
Email: myrangebc@gov.bc.ca
@@ -58,10 +44,7 @@ class PrivacyInfoModal extends Component {
Mailing Address:
- - Ministry of Forests, Lands, Natural Resource Operations and - Rural Development - + Ministry of Forests, Lands, Natural Resource Operations and Rural Development
Range Branch - Kamloops
Attn: MyRangeBC
@@ -79,10 +62,7 @@ class PrivacyInfoModal extends Component {
- +
diff --git a/src/components/common/footer/index.js b/src/components/common/footer/index.js index 7bf2093d..3a0ad921 100644 --- a/src/components/common/footer/index.js +++ b/src/components/common/footer/index.js @@ -26,27 +26,15 @@ class Footer extends Component {