diff --git a/src/CONST.ts b/src/CONST.ts
index 864d078ab04b..4cb4509e96a3 100755
--- a/src/CONST.ts
+++ b/src/CONST.ts
@@ -465,6 +465,7 @@ const CONST = {
ACTIONS: {
LIMIT: 50,
TYPE: {
+ APPROVED: 'APPROVED',
ADDCOMMENT: 'ADDCOMMENT',
CLOSED: 'CLOSED',
CREATED: 'CREATED',
diff --git a/src/components/AvatarWithDisplayName.js b/src/components/AvatarWithDisplayName.js
index 2fe1b3b7c57f..cbc34d6f9d47 100644
--- a/src/components/AvatarWithDisplayName.js
+++ b/src/components/AvatarWithDisplayName.js
@@ -26,8 +26,8 @@ const propTypes = {
/** The report currently being looked at */
report: reportPropTypes,
- /** The policies which the user has access to and which the report could be tied to */
- policies: PropTypes.shape({
+ /** The policy which the user has access to and which the report is tied to */
+ policy: PropTypes.shape({
/** Name of the policy */
name: PropTypes.string,
}),
@@ -47,7 +47,7 @@ const propTypes = {
const defaultProps = {
personalDetails: {},
- policies: {},
+ policy: {},
report: {},
isAnonymous: false,
size: CONST.AVATAR_SIZE.DEFAULT,
@@ -72,7 +72,7 @@ function AvatarWithDisplayName(props) {
const subtitle = ReportUtils.getChatRoomSubtitle(props.report);
const parentNavigationSubtitleData = ReportUtils.getParentNavigationSubtitle(props.report);
const isMoneyRequestOrReport = ReportUtils.isMoneyRequestReport(props.report) || ReportUtils.isMoneyRequest(props.report);
- const icons = ReportUtils.getIcons(props.report, props.personalDetails, props.policies, true);
+ const icons = ReportUtils.getIcons(props.report, props.personalDetails, props.policy, true);
const ownerPersonalDetails = OptionsListUtils.getPersonalDetailsForAccountIDs([props.report.ownerAccountID], props.personalDetails);
const displayNamesWithTooltips = ReportUtils.getDisplayNamesWithTooltips(_.values(ownerPersonalDetails), false);
const shouldShowSubscriptAvatar = ReportUtils.shouldReportShowSubscript(props.report);
diff --git a/src/components/HeaderWithBackButton/headerWithBackButtonPropTypes.js b/src/components/HeaderWithBackButton/headerWithBackButtonPropTypes.js
index a5f1c81823b0..d2cdc5b29898 100644
--- a/src/components/HeaderWithBackButton/headerWithBackButtonPropTypes.js
+++ b/src/components/HeaderWithBackButton/headerWithBackButtonPropTypes.js
@@ -73,8 +73,8 @@ const propTypes = {
/** Report, if we're showing the details for one and using AvatarWithDisplay */
report: iouReportPropTypes,
- /** Policies, if we're showing the details for a report and need info about it for AvatarWithDisplay */
- policies: PropTypes.shape({
+ /** The report's policy, if we're showing the details for a report and need info about it for AvatarWithDisplay */
+ policy: PropTypes.shape({
/** Name of the policy */
name: PropTypes.string,
}),
diff --git a/src/components/HeaderWithBackButton/index.js b/src/components/HeaderWithBackButton/index.js
index 6e6164f4c4fc..bbf905cc1ac2 100755
--- a/src/components/HeaderWithBackButton/index.js
+++ b/src/components/HeaderWithBackButton/index.js
@@ -27,7 +27,7 @@ function HeaderWithBackButton({
onDownloadButtonPress = () => {},
onThreeDotsButtonPress = () => {},
report = null,
- policies = {},
+ policy = {},
personalDetails = {},
shouldShowAvatarWithDisplay = false,
shouldShowBackButton = true,
@@ -77,7 +77,7 @@ function HeaderWithBackButton({
{shouldShowAvatarWithDisplay && (
)}
diff --git a/src/components/MoneyReportHeader.js b/src/components/MoneyReportHeader.js
index c4ce8cd173f1..7e6cc78ebd13 100644
--- a/src/components/MoneyReportHeader.js
+++ b/src/components/MoneyReportHeader.js
@@ -1,8 +1,9 @@
-import React from 'react';
+import React, {useMemo} from 'react';
import {withOnyx} from 'react-native-onyx';
import {View} from 'react-native';
import PropTypes from 'prop-types';
import lodashGet from 'lodash/get';
+import useLocalize from '../hooks/useLocalize';
import HeaderWithBackButton from './HeaderWithBackButton';
import iouReportPropTypes from '../pages/iouReportPropTypes';
import * as ReportUtils from '../libs/ReportUtils';
@@ -12,9 +13,10 @@ import withWindowDimensions, {windowDimensionsPropTypes} from './withWindowDimen
import compose from '../libs/compose';
import Navigation from '../libs/Navigation/Navigation';
import ROUTES from '../ROUTES';
-import SettlementButton from './SettlementButton';
-import * as Policy from '../libs/actions/Policy';
import ONYXKEYS from '../ONYXKEYS';
+import CONST from '../CONST';
+import SettlementButton from './SettlementButton';
+import Button from './Button';
import * as IOU from '../libs/actions/IOU';
import * as CurrencyUtils from '../libs/CurrencyUtils';
import reportPropTypes from '../pages/reportPropTypes';
@@ -23,10 +25,16 @@ const propTypes = {
/** The report currently being looked at */
report: iouReportPropTypes.isRequired,
- /** The policies which the user has access to and which the report could be tied to */
- policies: PropTypes.shape({
+ /** The policy tied to the money request report */
+ policy: PropTypes.shape({
/** Name of the policy */
name: PropTypes.string,
+
+ /** Type of the policy */
+ type: PropTypes.string,
+
+ /** The role of the current user in the policy */
+ role: PropTypes.string,
}).isRequired,
/** The chat report this report is linked to */
@@ -51,39 +59,50 @@ const defaultProps = {
},
};
-function MoneyReportHeader(props) {
- const moneyRequestReport = props.report;
+function MoneyReportHeader({session, personalDetails, policy, chatReport, report: moneyRequestReport, isSmallScreenWidth}) {
+ const {translate} = useLocalize();
+ const reportTotal = ReportUtils.getMoneyRequestTotal(moneyRequestReport);
+ const isApproved = ReportUtils.isReportApproved(moneyRequestReport);
const isSettled = ReportUtils.isSettled(moneyRequestReport.reportID);
- const policy = props.policies[`${ONYXKEYS.COLLECTION.POLICY}${props.report.policyID}`];
- const isPayer =
- Policy.isAdminOfFreePolicy([policy]) || (ReportUtils.isMoneyRequestReport(moneyRequestReport) && lodashGet(props.session, 'accountID', null) === moneyRequestReport.managerID);
- const reportTotal = ReportUtils.getMoneyRequestTotal(props.report);
- const shouldShowSettlementButton = !isSettled && isPayer && !moneyRequestReport.isWaitingOnBankAccount && reportTotal !== 0;
- const bankAccountRoute = ReportUtils.getBankAccountRoute(props.chatReport);
- const shouldShowPaypal = Boolean(lodashGet(props.personalDetails, [moneyRequestReport.managerID, 'payPalMeAddress']));
- const formattedAmount = CurrencyUtils.convertToDisplayString(reportTotal, props.report.currency);
+ const policyType = lodashGet(policy, 'type');
+ const isPolicyAdmin = policyType !== CONST.POLICY.TYPE.PERSONAL && lodashGet(policy, 'role') === CONST.POLICY.ROLE.ADMIN;
+ const isManager = ReportUtils.isMoneyRequestReport(moneyRequestReport) && lodashGet(session, 'accountID', null) === moneyRequestReport.managerID;
+ const isPayer = policyType === CONST.POLICY.TYPE.CORPORATE ? isPolicyAdmin && isApproved : isPolicyAdmin || (ReportUtils.isMoneyRequestReport(moneyRequestReport) && isManager);
+ const shouldShowSettlementButton = useMemo(
+ () => isPayer && !isSettled && !moneyRequestReport.isWaitingOnBankAccount && reportTotal !== 0,
+ [isPayer, isSettled, moneyRequestReport, reportTotal],
+ );
+ const shouldShowApproveButton = useMemo(() => {
+ if (policyType !== CONST.POLICY.TYPE.CORPORATE) {
+ return false;
+ }
+ return isManager && !isApproved && !isSettled;
+ }, [policyType, isManager, isApproved, isSettled]);
+ const bankAccountRoute = ReportUtils.getBankAccountRoute(chatReport);
+ const shouldShowPaypal = Boolean(lodashGet(personalDetails, [moneyRequestReport.managerID, 'payPalMeAddress']));
+ const formattedAmount = CurrencyUtils.convertToDisplayString(reportTotal, moneyRequestReport.currency);
return (
Navigation.goBack(ROUTES.HOME, false, true)}
- shouldShowBorderBottom={!shouldShowSettlementButton || !props.isSmallScreenWidth}
+ shouldShowBorderBottom={!shouldShowSettlementButton || !isSmallScreenWidth}
>
- {shouldShowSettlementButton && !props.isSmallScreenWidth && (
+ {shouldShowSettlementButton && !isSmallScreenWidth && (
IOU.payMoneyRequest(paymentType, props.chatReport, props.report)}
+ chatReportID={chatReport.reportID}
+ iouReport={moneyRequestReport}
+ onPress={(paymentType) => IOU.payMoneyRequest(paymentType, chatReport, moneyRequestReport)}
enablePaymentsRoute={ROUTES.BANK_ACCOUNT_NEW}
addBankAccountRoute={bankAccountRoute}
shouldShowPaymentOptions
@@ -92,16 +111,27 @@ function MoneyReportHeader(props) {
/>
)}
+ {shouldShowApproveButton && !isSmallScreenWidth && (
+
+
+ )}
- {shouldShowSettlementButton && props.isSmallScreenWidth && (
-
+ {shouldShowSettlementButton && isSmallScreenWidth && (
+
IOU.payMoneyRequest(paymentType, props.chatReport, props.report)}
+ chatReportID={moneyRequestReport.chatReportID}
+ iouReport={moneyRequestReport}
+ onPress={(paymentType) => IOU.payMoneyRequest(paymentType, chatReport, moneyRequestReport)}
enablePaymentsRoute={ROUTES.BANK_ACCOUNT_NEW}
addBankAccountRoute={bankAccountRoute}
shouldShowPaymentOptions
@@ -109,6 +139,17 @@ function MoneyReportHeader(props) {
/>
)}
+ {shouldShowApproveButton && isSmallScreenWidth && (
+
+
+ )}
);
}
diff --git a/src/components/MoneyRequestHeader.js b/src/components/MoneyRequestHeader.js
index de1a08c8f83c..f04a41ae1153 100644
--- a/src/components/MoneyRequestHeader.js
+++ b/src/components/MoneyRequestHeader.js
@@ -28,8 +28,8 @@ const propTypes = {
/** The expense report or iou report (only will have a value if this is a transaction thread) */
parentReport: iouReportPropTypes,
- /** The policies which the user has access to and which the report could be tied to */
- policies: PropTypes.shape({
+ /** The policy which the report is tied to */
+ policy: PropTypes.shape({
/** Name of the policy */
name: PropTypes.string,
}).isRequired,
@@ -58,6 +58,7 @@ function MoneyRequestHeader(props) {
const [isDeleteModalVisible, setIsDeleteModalVisible] = useState(false);
const moneyRequestReport = props.parentReport;
const isSettled = ReportUtils.isSettled(moneyRequestReport.reportID);
+
const parentReportAction = ReportActionsUtils.getParentReportAction(props.report);
// Only the requestor can take delete the request, admins can only edit it.
@@ -90,7 +91,7 @@ function MoneyRequestHeader(props) {
]}
threeDotsAnchorPosition={styles.threeDotsPopoverOffsetNoCloseButton(props.windowWidth)}
report={report}
- policies={props.policies}
+ policy={props.policy}
personalDetails={props.personalDetails}
shouldShowBackButton={props.isSmallScreenWidth}
onBackButtonPress={() => Navigation.goBack(ROUTES.HOME, false, true)}
@@ -122,7 +123,7 @@ export default compose(
key: ONYXKEYS.SESSION,
},
parentReport: {
- key: (props) => `${ONYXKEYS.COLLECTION.REPORT}${props.report.parentReportID}`,
+ key: ({report}) => `${ONYXKEYS.COLLECTION.REPORT}${report.parentReportID}`,
},
}),
)(MoneyRequestHeader);
diff --git a/src/components/ReportActionItem/MoneyRequestPreview.js b/src/components/ReportActionItem/MoneyRequestPreview.js
index 0112b2cca7f3..5a24c4319878 100644
--- a/src/components/ReportActionItem/MoneyRequestPreview.js
+++ b/src/components/ReportActionItem/MoneyRequestPreview.js
@@ -188,7 +188,9 @@ function MoneyRequestPreview(props) {
}
let message = props.translate('iou.cash');
- if (props.iouReport.isWaitingOnBankAccount) {
+ if (ReportUtils.isControlPolicyExpenseReport(props.iouReport) && ReportUtils.isReportApproved(props.iouReport) && !ReportUtils.isSettled(props.iouReport)) {
+ message += ` • ${props.translate('iou.approved')}`;
+ } else if (props.iouReport.isWaitingOnBankAccount) {
message += ` • ${props.translate('iou.pending')}`;
} else if (ReportUtils.isSettled(props.iouReport.reportID)) {
message += ` • ${props.translate('iou.settledExpensify')}`;
diff --git a/src/components/ReportActionItem/ReportPreview.js b/src/components/ReportActionItem/ReportPreview.js
index 18ca7e7cf2c2..9611ebb30d30 100644
--- a/src/components/ReportActionItem/ReportPreview.js
+++ b/src/components/ReportActionItem/ReportPreview.js
@@ -11,6 +11,7 @@ import styles from '../../styles/styles';
import reportActionPropTypes from '../../pages/home/report/reportActionPropTypes';
import withLocalize, {withLocalizePropTypes} from '../withLocalize';
import compose from '../../libs/compose';
+import CONST from '../../CONST';
import ONYXKEYS from '../../ONYXKEYS';
import ControlSelection from '../../libs/ControlSelection';
import * as DeviceCapabilities from '../../libs/DeviceCapabilities';
@@ -41,6 +42,9 @@ const propTypes = {
// eslint-disable-next-line react/no-unused-prop-types
iouReportID: PropTypes.string.isRequired,
+ /** The report's policyID, used for Onyx subscription */
+ policyID: PropTypes.string.isRequired,
+
/* Onyx Props */
/** chatReport associated with iouReport */
chatReport: reportPropTypes,
@@ -140,15 +144,20 @@ function ReportPreview(props) {
};
const getPreviewMessage = () => {
- const managerName = ReportUtils.isPolicyExpenseChat(props.chatReport) ? ReportUtils.getPolicyName(props.chatReport) : ReportUtils.getDisplayNameForParticipant(managerID, true);
if (isScanning) {
return props.translate('common.receipt');
}
+ if (ReportUtils.isControlPolicyExpenseChat(props.chatReport) && ReportUtils.isReportApproved(props.iouReport)) {
+ return props.translate('iou.managerApproved', {manager: ReportUtils.getDisplayNameForParticipant(managerID, true)});
+ }
+ const managerName = ReportUtils.isPolicyExpenseChat(props.chatReport) ? ReportUtils.getPolicyName(props.chatReport) : ReportUtils.getDisplayNameForParticipant(managerID, true);
return props.translate(iouSettled || props.iouReport.isWaitingOnBankAccount ? 'iou.payerPaid' : 'iou.payerOwes', {payer: managerName});
};
const bankAccountRoute = ReportUtils.getBankAccountRoute(props.chatReport);
- const shouldShowSettlementButton = !_.isEmpty(props.iouReport) && isCurrentUserManager && !iouSettled && !props.iouReport.isWaitingOnBankAccount && reportTotal !== 0;
+ const shouldShowSettlementButton = ReportUtils.isControlPolicyExpenseChat(props.chatReport)
+ ? props.policy.role === CONST.POLICY.ROLE.ADMIN && ReportUtils.isReportApproved(props.iouReport) && !iouSettled
+ : !_.isEmpty(props.iouReport) && isCurrentUserManager && !iouSettled && !props.iouReport.isWaitingOnBankAccount && reportTotal !== 0;
return (
@@ -202,7 +211,7 @@ function ReportPreview(props) {
{shouldShowSettlementButton && (
IOU.payMoneyRequest(paymentType, props.chatReport, props.iouReport)}
@@ -225,6 +234,9 @@ ReportPreview.displayName = 'ReportPreview';
export default compose(
withLocalize,
withOnyx({
+ policy: {
+ key: ({policyID}) => `${ONYXKEYS.COLLECTION.POLICY}${policyID}`,
+ },
chatReport: {
key: ({chatReportID}) => `${ONYXKEYS.COLLECTION.REPORT}${chatReportID}`,
},
diff --git a/src/languages/en.js b/src/languages/en.js
index e2b9fa37e91e..ee17efa37bf8 100755
--- a/src/languages/en.js
+++ b/src/languages/en.js
@@ -396,6 +396,8 @@ export default {
},
iou: {
amount: 'Amount',
+ approve: 'Approve',
+ approved: 'Approved',
cash: 'Cash',
split: 'Split',
request: 'Request',
@@ -426,6 +428,7 @@ export default {
payerOwes: ({payer}) => `${payer} owes: `,
payerPaidAmount: ({payer, amount}) => `${payer} paid ${amount}`,
payerPaid: ({payer}) => `${payer} paid: `,
+ managerApproved: ({manager}) => `${manager} approved:`,
payerSettled: ({amount}) => `paid ${amount}`,
waitingOnBankAccount: ({submitterDisplayName}) => `started settling up, payment is held until ${submitterDisplayName} adds a bank account`,
settledAfterAddedBankAccount: ({submitterDisplayName, amount}) => `${submitterDisplayName} added a bank account. The ${amount} payment has been made.`,
diff --git a/src/languages/es.js b/src/languages/es.js
index 48da21363722..12042f384bc9 100644
--- a/src/languages/es.js
+++ b/src/languages/es.js
@@ -395,6 +395,8 @@ export default {
},
iou: {
amount: 'Importe',
+ approve: 'Aprobar',
+ approved: 'Aprobado',
cash: 'Efectivo',
split: 'Dividir',
request: 'Solicitar',
@@ -425,6 +427,7 @@ export default {
payerOwes: ({payer}) => `${payer} debe: `,
payerPaidAmount: ({payer, amount}) => `${payer} pagó ${amount}`,
payerPaid: ({payer}) => `${payer} pagó: `,
+ managerApproved: ({manager}) => `${manager} aprobó:`,
payerSettled: ({amount}) => `pagó ${amount}`,
waitingOnBankAccount: ({submitterDisplayName}) => `inicio el pago, pero no se procesará hasta que ${submitterDisplayName} añada una cuenta bancaria`,
settledAfterAddedBankAccount: ({submitterDisplayName, amount}) => `${submitterDisplayName} añadió una cuenta bancaria. El pago de ${amount} se ha realizado.`,
diff --git a/src/libs/ReportUtils.js b/src/libs/ReportUtils.js
index 264fefac8753..4734b4f003ec 100644
--- a/src/libs/ReportUtils.js
+++ b/src/libs/ReportUtils.js
@@ -81,6 +81,52 @@ function getChatType(report) {
return report ? report.chatType : '';
}
+/**
+ * @param {String} policyID
+ * @returns {Object}
+ */
+function getPolicy(policyID) {
+ const policy = lodashGet(allPolicies, `${ONYXKEYS.COLLECTION.POLICY}${policyID}`) || {};
+ return policy;
+}
+
+/**
+ * Get the policy type from a given report
+ * @param {Object} report
+ * @param {String} report.policyID
+ * @param {Object} policies must have Onyxkey prefix (i.e 'policy_') for keys
+ * @returns {String}
+ */
+function getPolicyType(report, policies) {
+ return lodashGet(policies, [`${ONYXKEYS.COLLECTION.POLICY}${report.policyID}`, 'type'], '');
+}
+
+/**
+ * Get the policy name from a given report
+ * @param {Object} report
+ * @param {String} report.policyID
+ * @param {String} report.oldPolicyName
+ * @param {String} report.policyName
+ * @param {Boolean} [returnEmptyIfNotFound]
+ * @param {Object} [policy]
+ * @returns {String}
+ */
+function getPolicyName(report, returnEmptyIfNotFound = false, policy = undefined) {
+ const noPolicyFound = returnEmptyIfNotFound ? '' : Localize.translateLocal('workspace.common.unavailable');
+ if (_.isEmpty(report)) {
+ return noPolicyFound;
+ }
+
+ if ((!allPolicies || _.size(allPolicies) === 0) && !report.policyName) {
+ return Localize.translateLocal('workspace.common.unavailable');
+ }
+ const finalPolicy = policy || _.get(allPolicies, `${ONYXKEYS.COLLECTION.POLICY}${report.policyID}`);
+
+ // Public rooms send back the policy name with the reportSummary,
+ // since they can also be accessed by people who aren't in the workspace
+ return lodashGet(finalPolicy, 'name') || report.policyName || report.oldPolicyName || noPolicyFound;
+}
+
/**
* Returns the concatenated title for the PrimaryLogins of a report
*
@@ -168,10 +214,26 @@ function isCompletedTaskReport(report) {
return isTaskReport(report) && report.stateNum === CONST.REPORT.STATE_NUM.SUBMITTED && report.statusNum === CONST.REPORT.STATUS.APPROVED;
}
-function isTaskAssignee(report) {
+/**
+ * Checks if the current user is the manager of the supplied report
+ *
+ * @param {Object} report
+ * @returns {Boolean}
+ */
+function isReportManager(report) {
return lodashGet(report, 'managerID') === currentUserAccountID;
}
+/**
+ * Checks if the supplied report has been approved
+ *
+ * @param {Object} report
+ * @returns {Boolean}
+ */
+function isReportApproved(report) {
+ return lodashGet(report, 'stateNum') === CONST.REPORT.STATE_NUM.SUBMITTED && lodashGet(report, 'statusNum') === CONST.REPORT.STATUS.APPROVED;
+}
+
/**
* Given a collection of reports returns them sorted by last read
*
@@ -194,7 +256,12 @@ function sortReportsByLastRead(reports) {
*/
function isSettled(reportID) {
const report = lodashGet(allReports, `${ONYXKEYS.COLLECTION.REPORT}${reportID}`, {});
- return !_.isEmpty(report) && !report.isWaitingOnBankAccount && report.stateNum > CONST.REPORT.STATE_NUM.PROCESSING;
+
+ if (_.isEmpty(report) || report.isWaitingOnBankAccount) {
+ return false;
+ }
+
+ return report.stateNum === CONST.REPORT.STATE_NUM.SUBMITTED && report.statusNum === CONST.REPORT.STATUS.REIMBURSED;
}
/**
@@ -268,17 +335,6 @@ function isUserCreatedPolicyRoom(report) {
return getChatType(report) === CONST.REPORT.CHAT_TYPE.POLICY_ROOM;
}
-/**
- * Get the policy type from a given report
- * @param {Object} report
- * @param {String} report.policyID
- * @param {Object} policies must have Onyxkey prefix (i.e 'policy_') for keys
- * @returns {String}
- */
-function getPolicyType(report, policies) {
- return lodashGet(policies, [`${ONYXKEYS.COLLECTION.POLICY}${report.policyID}`, 'type'], '');
-}
-
/**
* Whether the provided report is a Policy Expense chat.
* @param {Object} report
@@ -507,42 +563,6 @@ function isArchivedRoom(report) {
return lodashGet(report, ['statusNum']) === CONST.REPORT.STATUS.CLOSED && lodashGet(report, ['stateNum']) === CONST.REPORT.STATE_NUM.SUBMITTED;
}
-/**
- * @param {String} policyID
- * @returns {Object}
- */
-function getPolicy(policyID) {
- const policy = lodashGet(allPolicies, `${ONYXKEYS.COLLECTION.POLICY}${policyID}`) || {};
- return policy;
-}
-
-/**
- * Get the policy name from a given report
- * @param {Object} report
- * @param {String} report.policyID
- * @param {String} report.oldPolicyName
- * @param {String} report.policyName
- * @param {Boolean} [returnEmptyIfNotFound]
- * @param {Object} [policy]
- * @returns {String}
- */
-function getPolicyName(report, returnEmptyIfNotFound = false, policy = undefined) {
- const noPolicyFound = returnEmptyIfNotFound ? '' : Localize.translateLocal('workspace.common.unavailable');
- if (_.isEmpty(report)) {
- return noPolicyFound;
- }
-
- if ((!allPolicies || _.size(allPolicies) === 0) && !report.policyName) {
- return Localize.translateLocal('workspace.common.unavailable');
- }
- const finalPolicy = policy || _.get(allPolicies, `${ONYXKEYS.COLLECTION.POLICY}${report.policyID}`);
-
- // Public rooms send back the policy name with the reportSummary,
- // since they can also be accessed by people who aren't in the workspace
-
- return lodashGet(finalPolicy, 'name') || report.policyName || report.oldPolicyName || noPolicyFound;
-}
-
/**
* Checks if the current user is allowed to comment on the given report.
* @param {Object} report
@@ -1111,6 +1131,22 @@ function isWaitingForIOUActionFromCurrentUser(report) {
return false;
}
+ const policy = getPolicy(report.policyID);
+ if (policy.type === CONST.POLICY.TYPE.CORPORATE) {
+ // If the report is already settled, there's no action required from any user.
+ if (isSettled(report.reportID)) {
+ return false;
+ }
+
+ // Report is pending approval and the current user is the manager
+ if (isReportManager(report) && !isReportApproved(report)) {
+ return true;
+ }
+
+ // Current user is an admin and the report has been approved but not settled yet
+ return policy.role === CONST.POLICY.ROLE.ADMIN && isReportApproved(report);
+ }
+
// Money request waiting for current user to add their credit bank account
if (report.hasOutstandingIOU && report.ownerAccountID === currentUserAccountID && report.isWaitingOnBankAccount) {
return true;
@@ -1125,7 +1161,7 @@ function isWaitingForIOUActionFromCurrentUser(report) {
}
function isWaitingForTaskCompleteFromAssignee(report) {
- return isTaskReport(report) && isTaskAssignee(report) && isOpenTaskReport(report);
+ return isTaskReport(report) && isReportManager(report) && isOpenTaskReport(report);
}
/**
@@ -1378,6 +1414,10 @@ function getReportPreviewMessage(report, reportAction = {}) {
const payerName = isExpenseReport(report) ? getPolicyName(report) : getDisplayNameForParticipant(report.managerID, true);
const formattedAmount = CurrencyUtils.convertToDisplayString(totalAmount, report.currency);
+ if (isReportApproved(report) && getPolicyType(report, allPolicies) === CONST.POLICY.TYPE.CORPORATE) {
+ return `approved ${formattedAmount}`;
+ }
+
if (isSettled(report.reportID)) {
// A settled report preview message can come in three formats "paid ... using Paypal.me", "paid ... elsewhere" or "paid ... using Expensify"
let translatePhraseKey = 'iou.paidElsewhereWithAmount';
@@ -1933,7 +1973,11 @@ function buildOptimisticExpenseReport(chatReportID, policyID, payeeAccountID, to
* @returns {Array}
*/
function getIOUReportActionMessage(iouReportID, type, total, comment, currency, paymentType = '', isSettlingUp = false) {
- let amount = CurrencyUtils.convertToDisplayString(total, currency);
+ const amount =
+ type === CONST.IOU.REPORT_ACTION_TYPE.PAY
+ ? CurrencyUtils.convertToDisplayString(getMoneyRequestTotal(getReport(iouReportID)), currency)
+ : CurrencyUtils.convertToDisplayString(total, currency);
+
let paymentMethodMessage;
switch (paymentType) {
case CONST.IOU.PAYMENT_TYPE.ELSEWHERE:
@@ -1949,6 +1993,9 @@ function getIOUReportActionMessage(iouReportID, type, total, comment, currency,
let iouMessage;
switch (type) {
+ case CONST.REPORT.ACTIONS.TYPE.APPROVED:
+ iouMessage = `approved ${amount}`;
+ break;
case CONST.IOU.REPORT_ACTION_TYPE.CREATE:
iouMessage = `requested ${amount}${comment && ` for ${comment}`}`;
break;
@@ -1959,7 +2006,6 @@ function getIOUReportActionMessage(iouReportID, type, total, comment, currency,
iouMessage = `deleted the ${amount} request${comment && ` for ${comment}`}`;
break;
case CONST.IOU.REPORT_ACTION_TYPE.PAY:
- amount = CurrencyUtils.convertToDisplayString(getMoneyRequestTotal(getReport(iouReportID)), currency);
iouMessage = isSettlingUp ? `paid ${amount}${paymentMethodMessage}` : `sent ${amount}${comment && ` for ${comment}`}${paymentMethodMessage}`;
break;
default:
@@ -2069,6 +2115,43 @@ function buildOptimisticIOUReportAction(
whisperedToAccountIDs: !_.isEmpty(receipt) ? [currentUserAccountID] : [],
};
}
+/**
+ * Builds an optimistic APPROVED report action with a randomly generated reportActionID.
+ *
+ * @param {Number} amount
+ * @param {String} currency
+ * @param {Number} expenseReportID
+ *
+ * @returns {Object}
+ */
+function buildOptimisticApprovedReportAction(amount, currency, expenseReportID) {
+ const originalMessage = {
+ amount,
+ currency,
+ expenseReportID,
+ };
+
+ return {
+ actionName: CONST.REPORT.ACTIONS.TYPE.APPROVED,
+ actorAccountID: currentUserAccountID,
+ automatic: false,
+ avatar: lodashGet(currentUserPersonalDetails, 'avatar', UserUtils.getDefaultAvatar(currentUserAccountID)),
+ isAttachment: false,
+ originalMessage,
+ message: getIOUReportActionMessage(expenseReportID, CONST.REPORT.ACTIONS.TYPE.APPROVED, Math.abs(amount), '', currency),
+ person: [
+ {
+ style: 'strong',
+ text: lodashGet(currentUserPersonalDetails, 'displayName', currentUserEmail),
+ type: 'TEXT',
+ },
+ ],
+ reportActionID: NumberUtils.rand64(),
+ shouldShow: true,
+ created: DateUtils.getDBTime(),
+ pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD,
+ };
+}
/**
* Builds an optimistic report preview action with a randomly generated reportActionID.
@@ -3122,7 +3205,7 @@ function isReportDataReady() {
* @returns {Object}
*/
function getTaskParentReportActionIDInAssigneeReport(taskReport) {
- const assigneeChatReportID = lodashGet(getChatByParticipants(isTaskAssignee(taskReport) ? [taskReport.ownerAccountID] : [taskReport.managerID]), 'reportID');
+ const assigneeChatReportID = lodashGet(getChatByParticipants(isReportManager(taskReport) ? [taskReport.ownerAccountID] : [taskReport.managerID]), 'reportID');
if (!assigneeChatReportID || assigneeChatReportID === taskReport.parentReportID) {
return {};
}
@@ -3426,6 +3509,7 @@ export {
buildOptimisticCreatedReportAction,
buildOptimisticEditedTaskReportAction,
buildOptimisticIOUReport,
+ buildOptimisticApprovedReportAction,
buildOptimisticExpenseReport,
buildOptimisticIOUReportAction,
buildOptimisticReportPreview,
@@ -3455,7 +3539,8 @@ export {
isOpenTaskReport,
isCanceledTaskReport,
isCompletedTaskReport,
- isTaskAssignee,
+ isReportManager,
+ isReportApproved,
isMoneyRequestReport,
isMoneyRequest,
chatIncludesChronos,
diff --git a/src/libs/SidebarUtils.js b/src/libs/SidebarUtils.js
index 7facb155eff0..118035f9f605 100644
--- a/src/libs/SidebarUtils.js
+++ b/src/libs/SidebarUtils.js
@@ -201,6 +201,9 @@ function getOptionData(report, reportActions, personalDetails, preferredLocale,
accountID: null,
managerID: null,
reportID: null,
+ policyID: null,
+ statusNum: null,
+ stateNum: null,
phoneNumber: null,
payPalMeAddress: null,
isUnread: null,
@@ -232,7 +235,7 @@ function getOptionData(report, reportActions, personalDetails, preferredLocale,
result.isTaskReport = ReportUtils.isTaskReport(report);
if (result.isTaskReport) {
result.isCompletedTaskReport = ReportUtils.isCompletedTaskReport(report);
- result.isTaskAssignee = ReportUtils.isTaskAssignee(report);
+ result.isTaskAssignee = ReportUtils.isReportManager(report);
}
result.isArchivedRoom = ReportUtils.isArchivedRoom(report);
result.isPolicyExpenseChat = ReportUtils.isPolicyExpenseChat(report);
@@ -245,6 +248,9 @@ function getOptionData(report, reportActions, personalDetails, preferredLocale,
result.ownerAccountID = report.ownerAccountID;
result.managerID = report.managerID;
result.reportID = report.reportID;
+ result.policyID = report.policyID;
+ result.stateNum = report.stateNum;
+ result.statusNum = report.statusNum;
result.isUnread = ReportUtils.isUnread(report);
result.isUnreadWithMention = ReportUtils.isUnreadWithMention(report);
result.hasDraftComment = report.hasDraft;
diff --git a/src/libs/actions/IOU.js b/src/libs/actions/IOU.js
index 838214bbd98e..3e76035cdcf0 100644
--- a/src/libs/actions/IOU.js
+++ b/src/libs/actions/IOU.js
@@ -650,7 +650,7 @@ function createSplitsAndOnyxData(participants, currentUserLogin, currentUserAcco
splitChatReport.lastMessageText = splitIOUReportAction.message[0].text;
splitChatReport.lastMessageHtml = splitIOUReportAction.message[0].html;
- // If we have an existing groupChatReport use it's pending fields, otherwise indicate that we are adding a chat
+ // If we have an existing splitChatReport (group chat or workspace) use it's pending fields, otherwise indicate that we are adding a chat
if (!existingSplitChatReport) {
splitChatReport.pendingFields = {
createChat: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD,
@@ -753,6 +753,7 @@ function createSplitsAndOnyxData(participants, currentUserLogin, currentUserAcco
const hasMultipleParticipants = participants.length > 1;
_.each(participants, (participant) => {
+ // In case the participant is a worskapce, email & accountID should remain undefined and won't be used in the rest of this code
const email = isOwnPolicyExpenseChat ? '' : OptionsListUtils.addSMSDomainIfPhoneNumber(participant.login).toLowerCase();
const accountID = isOwnPolicyExpenseChat ? 0 : Number(participant.accountID);
if (email === currentUserEmail) {
@@ -767,7 +768,9 @@ function createSplitsAndOnyxData(participants, currentUserLogin, currentUserAcco
// If this is a split between two people only and the function
// wasn't provided with an existing group chat report id
- // or, if this is workspace chat, then the oneOnOneChatReport is the same as the splitChatReport
+ // or, if the split is being made from the workspace chat, then the oneOnOneChatReport is the same as the splitChatReport
+ // in this case existingSplitChatReport will belong to the policy expense chat and we won't be
+ // entering code that creates optimistic personal details
if ((!hasMultipleParticipants && !existingSplitChatReportID) || isOwnPolicyExpenseChat) {
oneOnOneChatReport = splitChatReport;
shouldCreateOptimisticPersonalDetails = !existingSplitChatReport;
@@ -778,19 +781,21 @@ function createSplitsAndOnyxData(participants, currentUserLogin, currentUserAcco
oneOnOneChatReport = existingChatReport || ReportUtils.buildOptimisticChatReport([accountID]);
}
- // STEP 2: Get existing IOU report and update its total OR build a new optimistic one
- const isNewOneOnOneIOUReport = !oneOnOneChatReport.iouReportID;
- let oneOnOneIOUReport;
- if (!isNewOneOnOneIOUReport) {
- oneOnOneIOUReport = allReports[`${ONYXKEYS.COLLECTION.REPORT}${oneOnOneChatReport.iouReportID}`];
- if (isOwnPolicyExpenseChat) {
- // Because of the Expense reports are stored as negative values, we substract the total from the amount
- oneOnOneIOUReport.total -= splitAmount;
- } else {
- oneOnOneIOUReport = IOUUtils.updateIOUOwnerAndTotal(oneOnOneIOUReport, currentUserAccountID, splitAmount, currency);
- }
+ // STEP 2: Get existing IOU/Expense report and update its total OR build a new optimistic one
+ // For Control policy expense chats, if the report is already approved, create a new expense report
+ let oneOnOneIOUReport = lodashGet(allReports, `${ONYXKEYS.COLLECTION.REPORT}${oneOnOneChatReport.iouReportID}`, undefined);
+ const shouldCreateNewOneOnOneIOUReport =
+ _.isUndefined(oneOnOneIOUReport) || (isOwnPolicyExpenseChat && ReportUtils.isControlPolicyExpenseReport(oneOnOneIOUReport) && ReportUtils.isReportApproved(oneOnOneIOUReport));
+
+ if (shouldCreateNewOneOnOneIOUReport) {
+ oneOnOneIOUReport = isOwnPolicyExpenseChat
+ ? ReportUtils.buildOptimisticExpenseReport(oneOnOneChatReport.reportID, oneOnOneChatReport.policyID, currentUserAccountID, splitAmount, currency)
+ : ReportUtils.buildOptimisticIOUReport(currentUserAccountID, accountID, splitAmount, oneOnOneChatReport.reportID, currency);
+ } else if (isOwnPolicyExpenseChat) {
+ // Because of the Expense reports are stored as negative values, we subtract the total from the amount
+ oneOnOneIOUReport.total -= splitAmount;
} else {
- oneOnOneIOUReport = ReportUtils.buildOptimisticIOUReport(currentUserAccountID, accountID, splitAmount, oneOnOneChatReport.reportID, currency);
+ oneOnOneIOUReport = IOUUtils.updateIOUOwnerAndTotal(oneOnOneIOUReport, currentUserAccountID, splitAmount, currency);
}
// STEP 3: Build optimistic transaction
@@ -853,10 +858,10 @@ function createSplitsAndOnyxData(participants, currentUserLogin, currentUserAcco
oneOnOnePersonalDetailListAction,
oneOnOneReportPreviewAction,
isNewOneOnOneChatReport,
- isNewOneOnOneIOUReport,
+ shouldCreateNewOneOnOneIOUReport,
);
- const splitData = {
+ const individualSplit = {
email,
accountID,
amount: splitAmount,
@@ -869,7 +874,7 @@ function createSplitsAndOnyxData(participants, currentUserLogin, currentUserAcco
reportPreviewReportActionID: oneOnOneReportPreviewAction.reportActionID,
};
- splits.push(splitData);
+ splits.push(individualSplit);
optimisticData.push(...oneOnOneOptimisticData);
successData.push(...oneOnOneSuccessData);
failureData.push(...oneOnOneFailureData);
@@ -900,10 +905,10 @@ function createSplitsAndOnyxData(participants, currentUserLogin, currentUserAcco
* @param {Number} amount - always in smallest currency unit
* @param {String} comment
* @param {String} currency
- * @param {String} existingGroupChatReportID
+ * @param {String} existingSplitChatReportID - Either a group DM or a workspace chat
*/
-function splitBill(participants, currentUserLogin, currentUserAccountID, amount, comment, currency, existingGroupChatReportID = '') {
- const {splitData, splits, onyxData} = createSplitsAndOnyxData(participants, currentUserLogin, currentUserAccountID, amount, comment, currency, existingGroupChatReportID);
+function splitBill(participants, currentUserLogin, currentUserAccountID, amount, comment, currency, existingSplitChatReportID = '') {
+ const {splitData, splits, onyxData} = createSplitsAndOnyxData(participants, currentUserLogin, currentUserAccountID, amount, comment, currency, existingSplitChatReportID);
API.write(
'SplitBill',
@@ -1669,6 +1674,59 @@ function sendMoneyViaPaypal(report, amount, currency, comment, managerID, recipi
asyncOpenURL(Promise.resolve(), buildPayPalPaymentUrl(amount, recipient.payPalMeAddress, currency));
}
+function approveMoneyRequest(expenseReport) {
+ const optimisticApprovedReportAction = ReportUtils.buildOptimisticApprovedReportAction(expenseReport.total, expenseReport.currency, expenseReport.reportID);
+
+ const optimisticReportActionsData = {
+ onyxMethod: Onyx.METHOD.MERGE,
+ key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${expenseReport.reportID}`,
+ value: {
+ [optimisticApprovedReportAction.reportActionID]: {
+ ...optimisticApprovedReportAction,
+ pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD,
+ },
+ },
+ };
+ const optimisticIOUReportData = {
+ onyxMethod: Onyx.METHOD.MERGE,
+ key: `${ONYXKEYS.COLLECTION.REPORT}${expenseReport.reportID}`,
+ value: {
+ ...expenseReport,
+ lastMessageText: optimisticApprovedReportAction.message[0].text,
+ lastMessageHtml: optimisticApprovedReportAction.message[0].html,
+ stateNum: CONST.REPORT.STATE_NUM.SUBMITTED,
+ statusNum: CONST.REPORT.STATUS.APPROVED,
+ },
+ };
+ const optimisticData = [optimisticIOUReportData, optimisticReportActionsData];
+
+ const successData = [
+ {
+ onyxMethod: Onyx.METHOD.MERGE,
+ key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${expenseReport.reportID}`,
+ value: {
+ [optimisticApprovedReportAction.reportActionID]: {
+ pendingAction: null,
+ },
+ },
+ },
+ ];
+
+ const failureData = [
+ {
+ onyxMethod: Onyx.METHOD.MERGE,
+ key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${expenseReport.reportID}`,
+ value: {
+ [expenseReport.reportActionID]: {
+ errors: ErrorUtils.getMicroSecondOnyxError('iou.error.other'),
+ },
+ },
+ },
+ ];
+
+ API.write('ApproveMoneyRequest', {reportID: expenseReport.reportID, approvedReportActionID: optimisticApprovedReportAction.reportActionID}, {optimisticData, successData, failureData});
+}
+
/**
* @param {String} paymentType
* @param {Object} chatReport
@@ -1813,6 +1871,7 @@ export {
requestMoney,
sendMoneyElsewhere,
sendMoneyViaPaypal,
+ approveMoneyRequest,
payMoneyRequest,
sendMoneyWithWallet,
startMoneyRequest,
diff --git a/src/pages/home/ReportScreen.js b/src/pages/home/ReportScreen.js
index 62df86a9b014..7ecc8fcefe29 100644
--- a/src/pages/home/ReportScreen.js
+++ b/src/pages/home/ReportScreen.js
@@ -169,7 +169,7 @@ function ReportScreen({
headerView = (