diff --git a/src/components/AvatarWithIndicator.js b/src/components/AvatarWithIndicator.js index 2de828d4ef2e..9bd87453bde4 100644 --- a/src/components/AvatarWithIndicator.js +++ b/src/components/AvatarWithIndicator.js @@ -27,6 +27,12 @@ const propTypes = { /** The employee list of all policies (coming from Onyx) */ policiesMemberList: PropTypes.objectOf(policyMemberPropType), + /** The list of this user's policies (coming from Onyx) */ + policies: PropTypes.objectOf(PropTypes.shape({ + /** The ID of the policy */ + id: PropTypes.string, + })), + /** List of bank accounts */ bankAccountList: PropTypes.objectOf(bankAccountPropTypes), @@ -41,6 +47,7 @@ const defaultProps = { size: 'default', tooltipText: '', policiesMemberList: {}, + policies: {}, bankAccountList: {}, cardList: {}, userWallet: {}, @@ -55,8 +62,11 @@ const AvatarWithIndicator = (props) => { ]; const hasPolicyMemberError = _.some(props.policiesMemberList, policyMembers => Policy.hasPolicyMemberError(policyMembers)); + const hasCustomUnitsError = _.some(props.policies, policy => Policy.hasCustomUnitsError(policy)); const hasPaymentMethodError = PaymentMethods.hasPaymentMethodError(props.bankAccountList, props.cardList); const hasWalletError = !_.isEmpty(props.userWallet.errors); + const shouldShowIndicator = hasPolicyMemberError || hasPaymentMethodError || hasWalletError || hasCustomUnitsError; + return ( @@ -65,7 +75,7 @@ const AvatarWithIndicator = (props) => { source={props.source} size={props.size} /> - {(hasPolicyMemberError || hasPaymentMethodError || hasWalletError) && ( + {shouldShowIndicator && ( )} @@ -81,6 +91,9 @@ export default withOnyx({ policiesMemberList: { key: ONYXKEYS.COLLECTION.POLICY_MEMBER_LIST, }, + policies: { + key: ONYXKEYS.COLLECTION.POLICY, + }, bankAccountList: { key: ONYXKEYS.BANK_ACCOUNT_LIST, }, diff --git a/src/languages/en.js b/src/languages/en.js index df85199e1c15..8ff452062147 100755 --- a/src/languages/en.js +++ b/src/languages/en.js @@ -830,6 +830,7 @@ export default { captureNoVBACopyAfterEmail: ' and download the Expensify App to track cash expenses on the go.', unlockNoVBACopy: 'Connect a bank account to reimburse your workspace members online.', fastReimbursementsVBACopy: 'You\'re all set to reimburse receipts from your bank account!', + updateCustomUnitError: "Your changes couldn't be saved. The workspace was modified while you were offline, please try again.", }, bills: { manageYourBills: 'Manage your bills', diff --git a/src/languages/es.js b/src/languages/es.js index 9bd3a33f6b58..2e202a3ef66c 100644 --- a/src/languages/es.js +++ b/src/languages/es.js @@ -832,6 +832,7 @@ export default { captureNoVBACopyAfterEmail: ' y descarga la App de Expensify para controlar tus gastos en efectivo sobre la marcha.', unlockNoVBACopy: 'Conecta una cuenta bancaria para reembolsar online a los miembros de tu espacio de trabajo.', fastReimbursementsVBACopy: '¡Todo listo para reembolsar recibos desde tu cuenta bancaria!', + updateCustomUnitError: 'Los cambios no han podido ser guardados. El espacio de trabajo ha sido modificado mientras estabas desconectado, por favor inténtalo de nuevo.', }, bills: { manageYourBills: 'Gestiona tus facturas', diff --git a/src/libs/actions/Policy.js b/src/libs/actions/Policy.js index 8205538189f3..984e50f3f3f2 100644 --- a/src/libs/actions/Policy.js +++ b/src/libs/actions/Policy.js @@ -2,6 +2,7 @@ import _ from 'underscore'; import Onyx from 'react-native-onyx'; import lodashGet from 'lodash/get'; import * as DeprecatedAPI from '../deprecatedAPI'; +import * as API from '../API'; import ONYXKEYS from '../../ONYXKEYS'; import * as PersonalDetails from './PersonalDetails'; import Growl from '../Growl'; @@ -13,6 +14,7 @@ import ROUTES from '../../ROUTES'; import * as OptionsListUtils from '../OptionsListUtils'; import * as Report from './Report'; import * as Pusher from '../Pusher/pusher'; +import DateUtils from '../DateUtils'; const allPolicies = {}; Onyx.connect({ @@ -66,19 +68,6 @@ function getSimplifiedEmployeeList(employeeList) { * @returns {Object} */ function getSimplifiedPolicyObject(fullPolicyOrPolicySummary, isFromFullPolicy) { - const customUnit = lodashGet(fullPolicyOrPolicySummary, 'value.customUnits[0]', undefined); - const customUnitValue = lodashGet(customUnit, 'attributes.unit', 'mi'); - const customUnitRate = lodashGet(customUnit, 'rates[0]', {}); - const customUnitSimplified = customUnit && { - id: customUnit.customUnitID, - name: customUnit.name, - value: customUnitValue, - rate: { - id: customUnitRate.customUnitRateID, - name: customUnitRate.name, - value: Number(customUnitRate.rate), - }, - }; return { isFromFullPolicy, id: fullPolicyOrPolicySummary.id, @@ -91,7 +80,7 @@ function getSimplifiedPolicyObject(fullPolicyOrPolicySummary, isFromFullPolicy) // "GetFullPolicy" and "GetPolicySummaryList" returns different policy objects. If policy is retrieved by "GetFullPolicy", // avatarUrl will be nested within the key "value" avatarURL: fullPolicyOrPolicySummary.avatarURL || lodashGet(fullPolicyOrPolicySummary, 'value.avatarURL', ''), - customUnit: customUnitSimplified, + customUnits: lodashGet(fullPolicyOrPolicySummary, 'value.customUnits', {}), }; } @@ -430,6 +419,31 @@ function setWorkspaceErrors(policyID, errors) { Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${policyID}`, {errors}); } +/** + * @param {String} policyID + * @param {Number} customUnitID + */ +function removeUnitError(policyID, customUnitID) { + Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${policyID}`, { + customUnits: { + [customUnitID]: { + errors: null, + pendingAction: null, + }, + }, + }); +} + +/** + * Checks if we have any errors stored within the policy custom units. + * @param {Object} policy + * @returns {Boolean} + */ +function hasCustomUnitsError(policy) { + const unitsWithErrors = _.filter(lodashGet(policy, 'customUnits', {}), customUnit => (lodashGet(customUnit, 'errors', null))); + return !_.isEmpty(unitsWithErrors); +} + /** * @param {String} policyID */ @@ -439,30 +453,63 @@ function hideWorkspaceAlertMessage(policyID) { /** * @param {String} policyID - * @param {Object} values + * @param {Object} currentCustomUnit + * @param {Object} values The new custom unit values */ -function setCustomUnit(policyID, values) { - DeprecatedAPI.Policy_CustomUnit_Update({ - policyID: policyID.toString(), - customUnit: JSON.stringify(values), - lastModified: null, - }) - .then((response) => { - if (response.jsonCode !== 200) { - throw new Error(); - } - - updateLocalPolicyValues(policyID, { - customUnit: { - id: values.customUnitID, - name: values.name, - value: values.attributes.unit, +function updateWorkspaceCustomUnit(policyID, currentCustomUnit, values) { + const optimisticData = [ + { + onyxMethod: 'merge', + key: `${ONYXKEYS.COLLECTION.POLICY}${policyID}`, + value: { + customUnits: { + [values.customUnitID]: { + ...values, + pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.UPDATE, + }, }, - }); - }).catch(() => { - // Show the user feedback - Growl.error(Localize.translateLocal('workspace.editor.genericFailureMessage'), 5000); - }); + }, + }, + ]; + + const successData = [ + { + onyxMethod: 'merge', + key: `${ONYXKEYS.COLLECTION.POLICY}${policyID}`, + value: { + customUnits: { + [values.customUnitID]: { + pendingAction: null, + errors: null, + }, + }, + }, + }, + ]; + + const failureData = [ + { + onyxMethod: 'merge', + key: `${ONYXKEYS.COLLECTION.POLICY}${policyID}`, + value: { + customUnits: { + [currentCustomUnit.customUnitID]: { + customUnitID: currentCustomUnit.customUnitID, + name: currentCustomUnit.name, + attributes: currentCustomUnit.attributes, + errors: { + [DateUtils.getMicroseconds()]: Localize.translateLocal('workspace.reimburse.updateCustomUnitError'), + }, + }, + }, + }, + }, + ]; + + API.write('UpdateWorkspaceCustomUnit', { + policyID, + customUnit: JSON.stringify(values), + }, {optimisticData, successData, failureData}); } /** @@ -577,11 +624,13 @@ export { uploadAvatar, update, setWorkspaceErrors, + removeUnitError, + hasCustomUnitsError, hideWorkspaceAlertMessage, deletePolicy, createAndNavigate, createAndGetPolicyList, - setCustomUnit, + updateWorkspaceCustomUnit, setCustomUnitRate, updateLastAccessedWorkspace, subscribeToPolicyEvents, diff --git a/src/pages/settings/InitialSettingsPage.js b/src/pages/settings/InitialSettingsPage.js index 672419a5d61c..64b27a355fa8 100755 --- a/src/pages/settings/InitialSettingsPage.js +++ b/src/pages/settings/InitialSettingsPage.js @@ -160,16 +160,21 @@ class InitialSettingsPage extends React.Component { getMenuItems() { const menuItems = _.chain(this.props.policies) .filter(policy => policy && policy.type === CONST.POLICY.TYPE.FREE && policy.role === CONST.POLICY.ROLE.ADMIN) - .map(policy => ({ - title: policy.name, - icon: policy.avatarURL ? policy.avatarURL : Expensicons.Building, - iconType: policy.avatarURL ? CONST.ICON_TYPE_AVATAR : CONST.ICON_TYPE_ICON, - action: () => Navigation.navigate(ROUTES.getWorkspaceInitialRoute(policy.id)), - iconStyles: policy.avatarURL ? [] : [styles.popoverMenuIconEmphasized], - iconFill: themeColors.iconReversed, - fallbackIcon: Expensicons.FallbackWorkspaceAvatar, - brickRoadIndicator: Policy.hasPolicyMemberError(lodashGet(this.props.policyMembers, `${ONYXKEYS.COLLECTION.POLICY_MEMBER_LIST}${policy.id}`, {})) ? 'error' : null, - })) + .map((policy) => { + const shouldShowErrorIndicator = Policy.hasCustomUnitsError(policy) + || Policy.hasPolicyMemberError(lodashGet(this.props.policyMembers, `${ONYXKEYS.COLLECTION.POLICY_MEMBER_LIST}${policy.id}`, {})); + + return { + title: policy.name, + icon: policy.avatarURL ? policy.avatarURL : Expensicons.Building, + iconType: policy.avatarURL ? CONST.ICON_TYPE_AVATAR : CONST.ICON_TYPE_ICON, + action: () => Navigation.navigate(ROUTES.getWorkspaceInitialRoute(policy.id)), + iconStyles: policy.avatarURL ? [] : [styles.popoverMenuIconEmphasized], + iconFill: themeColors.iconReversed, + fallbackIcon: Expensicons.FallbackWorkspaceAvatar, + brickRoadIndicator: shouldShowErrorIndicator ? 'error' : null, + }; + }) .value(); menuItems.push(...this.getDefaultMenuItems()); diff --git a/src/pages/workspace/WorkspaceInitialPage.js b/src/pages/workspace/WorkspaceInitialPage.js index a4b086c31962..d2c4695f4977 100644 --- a/src/pages/workspace/WorkspaceInitialPage.js +++ b/src/pages/workspace/WorkspaceInitialPage.js @@ -77,6 +77,7 @@ class WorkspaceInitialPage extends React.Component { render() { const policy = this.props.policy; const hasMembersError = PolicyActions.hasPolicyMemberError(this.props.policyMemberList); + const hasCustomUnitsError = PolicyActions.hasCustomUnitsError(this.props.policy); const menuItems = [ { translationKey: 'workspace.common.settings', @@ -92,6 +93,7 @@ class WorkspaceInitialPage extends React.Component { translationKey: 'workspace.common.reimburse', icon: Expensicons.Receipt, action: () => Navigation.navigate(ROUTES.getWorkspaceReimburseRoute(policy.id)), + error: hasCustomUnitsError, }, { translationKey: 'workspace.common.bills', diff --git a/src/pages/workspace/reimburse/WorkspaceReimburseView.js b/src/pages/workspace/reimburse/WorkspaceReimburseView.js index 9ae0b280e24f..e1a18be5d6ff 100644 --- a/src/pages/workspace/reimburse/WorkspaceReimburseView.js +++ b/src/pages/workspace/reimburse/WorkspaceReimburseView.js @@ -22,6 +22,7 @@ import * as Policy from '../../../libs/actions/Policy'; import withFullPolicy from '../withFullPolicy'; import CONST from '../../../CONST'; import Button from '../../../components/Button'; +import OfflineWithFeedback from '../../../components/OfflineWithFeedback'; const propTypes = { /** The policy ID currently being configured */ @@ -32,16 +33,22 @@ const propTypes = { /** Policy values needed in the component */ policy: PropTypes.shape({ - customUnit: PropTypes.shape({ - id: PropTypes.string, - name: PropTypes.string, - value: PropTypes.string, - rate: PropTypes.shape({ - id: PropTypes.string, + customUnits: PropTypes.objectOf( + PropTypes.shape({ + customUnitID: PropTypes.string, name: PropTypes.string, - value: PropTypes.number, + attributes: PropTypes.shape({ + unit: PropTypes.string, + }), + rates: PropTypes.arrayOf( + PropTypes.shape({ + customUnitRateID: PropTypes.string, + name: PropTypes.string, + rate: PropTypes.number, + }), + ), }), - }), + ), outputCurrency: PropTypes.string, }).isRequired, @@ -51,13 +58,15 @@ const propTypes = { class WorkspaceReimburseView extends React.Component { constructor(props) { super(props); + const distanceCustomUnit = _.find(lodashGet(props, 'policy.customUnits', {}), unit => unit.name === 'Distance'); + this.state = { - unitID: lodashGet(props, 'policy.customUnit.id', ''), - unitName: lodashGet(props, 'policy.customUnit.name', ''), - unitValue: lodashGet(props, 'policy.customUnit.value', 'mi'), - rateID: lodashGet(props, 'policy.customUnit.rate.id', ''), - rateName: lodashGet(props, 'policy.customUnit.rate.name', ''), - rateValue: this.getRateDisplayValue(lodashGet(props, 'policy.customUnit.rate.value', 0) / 100), + unitID: lodashGet(distanceCustomUnit, 'customUnitID', ''), + unitName: lodashGet(distanceCustomUnit, 'name', ''), + unitValue: lodashGet(distanceCustomUnit, 'attributes.unit', 'mi'), + rateID: lodashGet(distanceCustomUnit, 'rates[0].customUnitRateID', ''), + rateName: lodashGet(distanceCustomUnit, 'rates[0].name', ''), + rateValue: this.getRateDisplayValue(lodashGet(distanceCustomUnit, 'rates[0].rate', 0) / 100), outputCurrency: lodashGet(props, 'policy.outputCurrency', ''), }; @@ -96,14 +105,31 @@ class WorkspaceReimburseView extends React.Component { }); } + static getDerivedStateFromProps(props, state) { + const distanceCustomUnit = _.find(lodashGet(props, 'policy.customUnits', {}), unit => unit.name === 'Distance'); + const unitValue = lodashGet(distanceCustomUnit, 'attributes.unit', 'mi'); + + if (!state.unitValue || (unitValue !== state.unitValue)) { + return { + unitValue, + }; + } + + return null; + } + setUnit(value) { - this.setState({unitValue: value}); + if (value === this.state.unitValue) { + return; + } - Policy.setCustomUnit(this.props.policyID, { + const distanceCustomUnit = _.find(lodashGet(this.props, 'policy.customUnits', {}), unit => unit.name === 'Distance'); + + Policy.updateWorkspaceCustomUnit(this.props.policyID, distanceCustomUnit, { customUnitID: this.state.unitID, - customUnitName: this.state.unitName, + name: this.state.unitName, attributes: {unit: value}, - }, null); + }); } debounceUpdateOnCursorMove(event) { @@ -167,28 +193,34 @@ class WorkspaceReimburseView extends React.Component { {this.props.translate('workspace.reimburse.trackDistanceCopy')} - - - this.setRate(value)} - value={this.state.rateValue} - autoCompleteType="off" - autoCorrect={false} - keyboardType={CONST.KEYBOARD_TYPE.DECIMAL_PAD} - onKeyPress={this.debounceUpdateOnCursorMove} - /> - - - this.setUnit(value)} - /> + Policy.removeUnitError(this.props.policyID, this.state.unitID)} + > + + + this.setRate(value)} + value={this.state.rateValue} + autoCompleteType="off" + autoCorrect={false} + keyboardType={CONST.KEYBOARD_TYPE.DECIMAL_PAD} + onKeyPress={this.debounceUpdateOnCursorMove} + /> + + + this.setUnit(value)} + /> + - + {!this.props.hasVBA && (