Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,25 @@ import {SELECTION_LIST_POPOVER_HEADER_HEIGHT} from '@components/SelectionListPop
import useLocalize from '@hooks/useLocalize';
import useOnyx from '@hooks/useOnyx';
import useOutstandingReports from '@hooks/useOutstandingReports';
import usePermissions from '@hooks/usePermissions';
import {usePersonalDetail} from '@hooks/usePersonalDetails';
import {useDerivedReportNameByReportID} from '@hooks/useReportAttributes';

import {isMovingTransactionFromTrackExpense} from '@libs/IOUUtils';
import createDynamicRoute from '@libs/Navigation/helpers/dynamicRoutesUtils/createDynamicRoute';
import Navigation from '@libs/Navigation/Navigation';
import Parser from '@libs/Parser';
import {getReportName} from '@libs/ReportNameUtils';
import {
canAddTransaction,
generateReportID,
getNewestOutstandingReportForUser,
getDefaultMoneyRequestReport,
getMoneyRequestReportCandidate,
getOutstandingReportsForUser,
isMoneyRequestReport,
isOpenExpenseReport,
isReportOutstanding,
isSavedThroughMoneyRequestBuilder,
sortOutstandingReportsBySelected,
} from '@libs/ReportUtils';

Expand Down Expand Up @@ -56,6 +61,7 @@ type ReportFieldProps = {
function ReportField({selectedParticipants, iouType, reportID, reportActionID, action, transactionID, isPerDiemRequest, isPolicyExpenseChat}: ReportFieldProps) {
const {shouldUseDropdownRows} = useExpenseFormLayout();
const {translate, localeCompare} = useLocalize();
const {isBetaEnabled} = usePermissions();
const ownerAccountID = selectedParticipants?.at(0)?.ownerAccountID;
const [ownerPersonalDetail] = usePersonalDetail(ownerAccountID);

Expand All @@ -69,6 +75,7 @@ function ReportField({selectedParticipants, iouType, reportID, reportActionID, a
const transactionReportID = transactionState?.reportID;
const participantReportID = transactionState?.participantReportID;
const isFromGlobalCreate = transactionState?.isFromGlobalCreate ?? false;
const isScanRequest = transactionState?.isScanRequest ?? false;

// Per-key report subscriptions instead of full COLLECTION.REPORT
const [transactionReportEntry] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${transactionReportID}`);
Expand All @@ -78,6 +85,7 @@ function ReportField({selectedParticipants, iouType, reportID, reportActionID, a

const isUnreported = transactionReportID === CONST.REPORT.UNREPORTED_REPORT_ID;
const isCreatingExpense = action === CONST.IOU.ACTION.CREATE;
const isMovingTrackedExpense = isMovingTransactionFromTrackExpense(action);

/**
* We need to check if the transaction report exists first in order to prevent the outstanding reports from being used.
Expand All @@ -90,14 +98,15 @@ function ReportField({selectedParticipants, iouType, reportID, reportActionID, a
(report1, report2) => sortOutstandingReportsBySelected(report1, report2, undefined, localeCompare),
);

// Match the builder's automatic destination before checking eligibility, rather than falling back to a report it would not use.
const defaultOutstandingReport = isCreatingExpense
? getNewestOutstandingReportForUser(policyID, ownerAccountID, rules, reportNameValuePairs, outstandingReportsForPolicy ?? {})
: availableOutstandingReports.at(0);
const outstandingReportID = isPolicyExpenseChat ? (iouReportIDFromMain ?? defaultOutstandingReport?.reportID) : reportID;
// Match the save path's automatic destination before checking eligibility, rather than falling back to a report it would not use.
const candidateReport = getMoneyRequestReportCandidate(iouReport, action, policyID, ownerAccountID, rules, reportNameValuePairs, outstandingReportsForPolicy);
const defaultReport = candidateReport ?? (isSavedThroughMoneyRequestBuilder(action) ? undefined : availableOutstandingReports.at(0));
const defaultReportID = getDefaultMoneyRequestReport(defaultReport, mainReport, isScanRequest, isBetaEnabled(CONST.BETAS.ASAP_SUBMIT), rules, action)?.reportID;

const outstandingReportID = isPolicyExpenseChat ? defaultReportID : reportID;
const reportIDToUse = shouldUseTransactionReport ? transactionReportID : outstandingReportID;

const [selectedReportID, selectedReport] = (() => {
const reportIDToUse = shouldUseTransactionReport ? transactionReportID : outstandingReportID;
if (!reportIDToUse) {
// Even if we have no report to use we still need a report id for proper navigation
return [generateReportID(), undefined] as const;
Expand All @@ -110,6 +119,8 @@ function ReportField({selectedParticipants, iouType, reportID, reportActionID, a
reportToUse = mainReport;
} else if (reportIDToUse === iouReportIDFromMain) {
reportToUse = iouReport;
} else if (reportIDToUse === defaultReport?.reportID) {
reportToUse = defaultReport;
} else {
reportToUse = availableOutstandingReports.find((r) => r?.reportID === reportIDToUse);
}
Expand All @@ -129,11 +140,14 @@ function ReportField({selectedParticipants, iouType, reportID, reportActionID, a
return name;
})();

const outstandingReports = useOutstandingReports(undefined, isFromGlobalCreate && !isPerDiemRequest ? undefined : policyID, ownerAccountID, false, ownerPersonalDetail?.login);
const allOutstandingReports = useOutstandingReports(undefined, isFromGlobalCreate && !isPerDiemRequest ? undefined : policyID, ownerAccountID, false, ownerPersonalDetail?.login);
// A tracked expense moved to a workspace can only join an open report, so the picker lists only those. Count the same reports here.
const outstandingReports = isMovingTrackedExpense ? allOutstandingReports.filter(isOpenExpenseReport) : allOutstandingReports;
const eligibleOutstandingReports = isCreatingExpense ? outstandingReports.filter((report) => canAddTransaction(report, rules)) : outstandingReports;
// When creating an expense in an individual report, the report field becomes read-only
// since the destination is already determined and there's no need to show a selectable list.
const shouldReportBeEditable = shouldReportFieldBeEditable(eligibleOutstandingReports, selectedReportID, isUnreported) && !isMoneyRequestReport(reportID);
// Use the default rather than the picked report, so picking the only outstanding report keeps the field editable to switch back.
const shouldReportBeEditable = shouldReportFieldBeEditable(eligibleOutstandingReports, selectedReportID, isUnreported || !outstandingReportID) && !isMoneyRequestReport(reportID);
// Editing a saved expense's report and moving a per diem expense both navigate on from the list (to the report, or to
// the destination step when the workspace changes), so those keep the full page.
const shouldOpenInDropdown = !!transactionID && shouldReportBeEditable && action !== CONST.IOU.ACTION.EDIT && !isPerDiemRequest;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
isCreatedMissing,
isFailedScanAmountPlaceholder,
isMerchantMissing,
isScanRequest,
isScanning,
willFieldBeAutomaticallyFilled,
} from '@libs/TransactionUtils';
Expand Down Expand Up @@ -355,6 +356,7 @@ type ReportFieldTransactionState = {
reportID: Transaction['reportID'];
isFromGlobalCreate: boolean;
participantReportID: string | undefined;
isScanRequest: boolean;
};

const reportFieldTransactionStateSelector = (t: OnyxEntry<Transaction>): ReportFieldTransactionState | undefined => {
Expand All @@ -365,6 +367,7 @@ const reportFieldTransactionStateSelector = (t: OnyxEntry<Transaction>): ReportF
reportID: t.reportID,
isFromGlobalCreate: !!t.isFromGlobalCreate,
participantReportID: t.participants?.at(0)?.reportID,
isScanRequest: isScanRequest(t),
};
};

Expand Down
59 changes: 59 additions & 0 deletions src/libs/ReportUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13674,6 +13674,62 @@ function getNewestOutstandingReportForUser(
return openReports.reduce<OnyxInputValue<Report>>((newest, report) => ((report?.created ?? '') > (newest?.created ?? '') ? (report ?? null) : newest), openReports.at(0) ?? null);
}

/**
* Whether saving the expense for this action goes through the money request builder and its report checks: new expenses and tracked
* expenses moved to a workspace. Other actions, like editing, move the expense to a report without them.
*/
function isSavedThroughMoneyRequestBuilder(action: IOUAction): boolean {
return action === CONST.IOU.ACTION.CREATE || action === CONST.IOU.ACTION.SUBMIT || action === CONST.IOU.ACTION.CATEGORIZE || action === CONST.IOU.ACTION.SHARE;
}

/**
* Returns the report the expense would join before the save path's checks run. The Report field and the report picker both start from
* it, so they show and mark the same report. For actions saved through the money request builder it matches the builder: the report the
* workspace chat points at, or the member's newest open report when the chat's iouReportID was cleared, e.g. after a submit.
*
* @param chatIOUReport - The report the workspace chat's iouReportID points at
* @param policyID - The workspace the expense is created in
* @param reportOwnerAccountID - The member the expense is created for
* @param outstandingReportsForPolicy - The policy's outstanding reports, from the OUTSTANDING_REPORTS_BY_POLICY_ID derived value
*/
function getMoneyRequestReportCandidate(
chatIOUReport: OnyxInputOrEntry<Report>,
action: IOUAction,
policyID: string | undefined,
reportOwnerAccountID: number | undefined,
rules: OnyxCollection<Rule>,
reportNameValuePairs: OnyxCollection<ReportNameValuePairs>,
outstandingReportsForPolicy: OnyxCollection<Report>,
): OnyxInputOrEntry<Report> {
if (chatIOUReport || !isSavedThroughMoneyRequestBuilder(action)) {
return chatIOUReport;
}
return getNewestOutstandingReportForUser(policyID, reportOwnerAccountID, rules, reportNameValuePairs, outstandingReportsForPolicy ?? {});
}

/**
* Returns the report a new expense is added to when the user doesn't pick one, or undefined when saving it starts a new report.
* The Report field and the report picker both read it, so the picker marks the same report the field shows, and picking any
* other report, including the candidate when saving would skip it, writes the choice to the expense.
*
* @param candidateReport - The report the expense would join, from getMoneyRequestReportCandidate
* @param chatReport - The workspace chat the expense is created in
*/
function getDefaultMoneyRequestReport(
candidateReport: OnyxInputOrEntry<Report>,
chatReport: OnyxInputOrEntry<Report>,
isScanRequest: boolean,
isASAPSubmitBetaEnabled: boolean,
rules: OnyxCollection<Rule>,
action: IOUAction,
): OnyxInputOrEntry<Report> {
// Actions that skip the save path's checks keep the report they were given.
if (!isSavedThroughMoneyRequestBuilder(action)) {
return candidateReport;
}
return shouldCreateNewMoneyRequestReport(candidateReport, chatReport, isScanRequest, isASAPSubmitBetaEnabled, rules, action) ? undefined : candidateReport;
}

/**
* Whether the member is the approver of any of the policy's reports that are waiting for their approval.
* An approver assigned through "Change approver" is only stored in the report's `managerID`, so they are not covered by `isPolicyApprover`.
Expand Down Expand Up @@ -16368,6 +16424,9 @@ export {
buildOptimisticMovedTransactionAction,
getOutstandingReportsForUser,
getNewestOutstandingReportForUser,
getDefaultMoneyRequestReport,
getMoneyRequestReportCandidate,
isSavedThroughMoneyRequestBuilder,
isApproverOfOutstandingPolicyReports,
isReportOutstanding,
isReportTotalPending,
Expand Down
8 changes: 7 additions & 1 deletion src/pages/iou/request/step/IOURequestEditReportCommon.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import {fetchOutstandingReports} from '@libs/actions/OutstandingReports';
import canFocusInputOnScreenFocus from '@libs/canFocusInputOnScreenFocus';
import Navigation from '@libs/Navigation/Navigation';
import {canSubmitPerDiemExpenseFromWorkspace, isPerDiemEnabled, isPolicyAdmin, isTimeTrackingEnabled} from '@libs/PolicyUtils';
import {canAddTransaction, getIconsForExpenseReport, isIOUReport, isOpenReport, isReportOwner, isSelfDM, sortOutstandingReportsBySelected} from '@libs/ReportUtils';
import {canAddTransaction, getIconsForExpenseReport, isIOUReport, isOpenExpenseReport, isOpenReport, isReportOwner, isSelfDM, sortOutstandingReportsBySelected} from '@libs/ReportUtils';
import {shouldRestrictUserBillableActions} from '@libs/SubscriptionUtils';
import {isPerDiemRequest as isPerDiemRequestUtil} from '@libs/TransactionUtils';

Expand Down Expand Up @@ -81,6 +81,8 @@ type IOURequestEditReportCommonProps = {
isPerDiemRequest: boolean;
isTimeRequest?: boolean;
isUnreportedManagedCardTransaction?: boolean;
/** Whether only open reports can take the expense, e.g. a tracked expense moved to a workspace, which the server only adds to an open report */
shouldOnlyListOpenReports?: boolean;
/** Whether the expenses being moved belong to more than one submitter */
hasMultipleSubmitters?: boolean;
/** Whether every expense being moved sits on a card this user can resolve, which "Auto report" requires */
Expand Down Expand Up @@ -129,6 +131,7 @@ function IOURequestEditReportCommon({
isPerDiemRequest,
isTimeRequest = false,
isUnreportedManagedCardTransaction = false,
shouldOnlyListOpenReports = false,
hasMultipleSubmitters = false,
areAllManagedCardsResolvable = false,
autoReport,
Expand Down Expand Up @@ -233,6 +236,9 @@ function IOURequestEditReportCommon({
.sort((report1, report2) => sortOutstandingReportsBySelected(report1, report2, selectedReportID, localeCompare))
.filter((report): report is NonNullable<typeof report> => report !== undefined)
.filter((report) => {
if (shouldOnlyListOpenReports && !isOpenExpenseReport(report)) {
return false;
}
const policy = allPolicies?.[`${ONYXKEYS.COLLECTION.POLICY}${report.policyID}`];
if (isTimeRequest && !isTimeTrackingEnabled(policy)) {
return false;
Expand Down
Loading
Loading