diff --git a/.eslintrc.changed.js b/.eslintrc.changed.js index ae82e38070e7..1f17c73f5813 100644 --- a/.eslintrc.changed.js +++ b/.eslintrc.changed.js @@ -21,7 +21,7 @@ module.exports = { }, overrides: [ { - files: ['src/pages/workspace/WorkspaceInitialPage.tsx', 'src/pages/home/report/PureReportActionItem.tsx', 'src/libs/SidebarUtils.ts'], + files: ['src/pages/workspace/WorkspaceInitialPage.tsx', 'src/libs/SidebarUtils.ts'], rules: { 'rulesdir/no-default-id-values': 'off', }, diff --git a/src/ROUTES.ts b/src/ROUTES.ts index b150e6841ec6..f8496c3ac062 100644 --- a/src/ROUTES.ts +++ b/src/ROUTES.ts @@ -322,8 +322,12 @@ const ROUTES = { }, EDIT_REPORT_FIELD_REQUEST: { route: 'r/:reportID/edit/policyField/:policyID/:fieldID', - getRoute: (reportID: string, policyID: string, fieldID: string, backTo?: string) => - getUrlWithBackToParam(`r/${reportID}/edit/policyField/${policyID}/${encodeURIComponent(fieldID)}` as const, backTo), + getRoute: (reportID: string | undefined, policyID: string | undefined, fieldID: string, backTo?: string) => { + if (!policyID || !reportID) { + Log.warn('Invalid policyID or reportID is used to build the EDIT_REPORT_FIELD_REQUEST route', {policyID, reportID}); + } + return getUrlWithBackToParam(`r/${reportID}/edit/policyField/${policyID}/${encodeURIComponent(fieldID)}` as const, backTo); + }, }, REPORT_WITH_ID_DETAILS_SHARE_CODE: { route: 'r/:reportID/details/shareCode', @@ -400,11 +404,21 @@ const ROUTES = { }, SPLIT_BILL_DETAILS: { route: 'r/:reportID/split/:reportActionID', - getRoute: (reportID: string, reportActionID: string, backTo?: string) => getUrlWithBackToParam(`r/${reportID}/split/${reportActionID}` as const, backTo), + getRoute: (reportID: string | undefined, reportActionID: string, backTo?: string) => { + if (!reportID) { + Log.warn('Invalid reportID is used to build the SPLIT_BILL_DETAILS route'); + } + return getUrlWithBackToParam(`r/${reportID}/split/${reportActionID}` as const, backTo); + }, }, TASK_TITLE: { route: 'r/:reportID/title', - getRoute: (reportID: string, backTo?: string) => getUrlWithBackToParam(`r/${reportID}/title` as const, backTo), + getRoute: (reportID: string | undefined, backTo?: string) => { + if (!reportID) { + Log.warn('Invalid reportID is used to build the TASK_TITLE route'); + } + return getUrlWithBackToParam(`r/${reportID}/title` as const, backTo); + }, }, REPORT_DESCRIPTION: { route: 'r/:reportID/description', @@ -417,7 +431,12 @@ const ROUTES = { }, TASK_ASSIGNEE: { route: 'r/:reportID/assignee', - getRoute: (reportID: string, backTo?: string) => getUrlWithBackToParam(`r/${reportID}/assignee` as const, backTo), + getRoute: (reportID: string | undefined, backTo?: string) => { + if (!reportID) { + Log.warn('Invalid reportID is used to build the TASK_ASSIGNEE route'); + } + return getUrlWithBackToParam(`r/${reportID}/assignee` as const, backTo); + }, }, PRIVATE_NOTES_LIST: { route: 'r/:reportID/notes', @@ -1917,7 +1936,7 @@ const ROUTES = { }, DEBUG_REPORT: { route: 'debug/report/:reportID', - getRoute: (reportID: string) => `debug/report/${reportID}` as const, + getRoute: (reportID: string | undefined) => `debug/report/${reportID}` as const, }, DEBUG_REPORT_TAB_DETAILS: { route: 'debug/report/:reportID/details', diff --git a/src/components/HTMLEngineProvider/HTMLRenderers/MentionReportRenderer/MentionReportContext.tsx b/src/components/HTMLEngineProvider/HTMLRenderers/MentionReportRenderer/MentionReportContext.tsx index e44d3ef97df6..ddaab1a55994 100644 --- a/src/components/HTMLEngineProvider/HTMLRenderers/MentionReportRenderer/MentionReportContext.tsx +++ b/src/components/HTMLEngineProvider/HTMLRenderers/MentionReportRenderer/MentionReportContext.tsx @@ -1,12 +1,12 @@ import {createContext} from 'react'; type MentionReportContextProps = { - currentReportID: string; + currentReportID: string | undefined; exactlyMatch?: boolean; }; const MentionReportContext = createContext({ - currentReportID: '', + currentReportID: undefined, }); export default MentionReportContext; diff --git a/src/components/HTMLEngineProvider/HTMLRenderers/MentionReportRenderer/index.tsx b/src/components/HTMLEngineProvider/HTMLRenderers/MentionReportRenderer/index.tsx index 89a9fb21d48f..fcae31dd7d2f 100644 --- a/src/components/HTMLEngineProvider/HTMLRenderers/MentionReportRenderer/index.tsx +++ b/src/components/HTMLEngineProvider/HTMLRenderers/MentionReportRenderer/index.tsx @@ -60,9 +60,9 @@ function MentionReportRenderer({style, tnode, TDefaultRenderer, ...defaultRender const [reports] = useOnyx(ONYXKEYS.COLLECTION.REPORT); const currentReportID = useCurrentReportID(); - const currentReportIDValue = currentReportIDContext || currentReportID?.currentReportID; // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing - const [currentReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${currentReportIDValue || -1}`); + const currentReportIDValue = currentReportIDContext || currentReportID?.currentReportID; + const [currentReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${currentReportIDValue}`); // When we invite someone to a room they don't have the policy object, but we still want them to be able to see and click on report mentions, so we only check if the policyID in the report is from a workspace const isGroupPolicyReport = useMemo(() => currentReport && !isEmptyObject(currentReport) && !!currentReport.policyID && currentReport.policyID !== CONST.POLICY.ID_FAKE, [currentReport]); diff --git a/src/components/LHNOptionsList/OptionRowLHN.tsx b/src/components/LHNOptionsList/OptionRowLHN.tsx index 3bf8e11d4ad6..604e2b3065fd 100644 --- a/src/components/LHNOptionsList/OptionRowLHN.tsx +++ b/src/components/LHNOptionsList/OptionRowLHN.tsx @@ -55,7 +55,6 @@ function OptionRowLHN({reportID, isFocused = false, onSelectRow = () => {}, opti const [isScreenFocused, setIsScreenFocused] = useState(false); const {shouldUseNarrowLayout} = useResponsiveLayout(); - // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing const [report] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${optionItem?.reportID}`); const [activePolicyID] = useOnyx(ONYXKEYS.NVP_ACTIVE_POLICY_ID); const [introSelected] = useOnyx(ONYXKEYS.NVP_INTRO_SELECTED); diff --git a/src/components/ReportActionItem/ChronosOOOListActions.tsx b/src/components/ReportActionItem/ChronosOOOListActions.tsx index 460104a71d68..365b22a49c2c 100644 --- a/src/components/ReportActionItem/ChronosOOOListActions.tsx +++ b/src/components/ReportActionItem/ChronosOOOListActions.tsx @@ -6,14 +6,14 @@ import Text from '@components/Text'; import useLocalize from '@hooks/useLocalize'; import useThemeStyles from '@hooks/useThemeStyles'; import DateUtils from '@libs/DateUtils'; -import * as ReportActionsUtils from '@libs/ReportActionsUtils'; -import * as Chronos from '@userActions/Chronos'; +import {getOriginalMessage} from '@libs/ReportActionsUtils'; +import {removeEvent} from '@userActions/Chronos'; import type CONST from '@src/CONST'; import type ReportAction from '@src/types/onyx/ReportAction'; type ChronosOOOListActionsProps = { /** The ID of the report */ - reportID: string; + reportID: string | undefined; /** All the data of the action */ action: ReportAction; @@ -24,7 +24,7 @@ function ChronosOOOListActions({reportID, action}: ChronosOOOListActionsProps) { const {translate, preferredLocale} = useLocalize(); - const events = ReportActionsUtils.getOriginalMessage(action)?.events ?? []; + const events = getOriginalMessage(action)?.events ?? []; if (!events.length) { return ( @@ -61,7 +61,7 @@ function ChronosOOOListActions({reportID, action}: ChronosOOOListActionsProps) { diff --git a/src/components/ReportActionItem/MoneyReportView.tsx b/src/components/ReportActionItem/MoneyReportView.tsx index d1dcdb2f57f5..6354b69bc58e 100644 --- a/src/components/ReportActionItem/MoneyReportView.tsx +++ b/src/components/ReportActionItem/MoneyReportView.tsx @@ -16,12 +16,25 @@ import useNetwork from '@hooks/useNetwork'; import useStyleUtils from '@hooks/useStyleUtils'; import useTheme from '@hooks/useTheme'; import useThemeStyles from '@hooks/useThemeStyles'; -import * as CurrencyUtils from '@libs/CurrencyUtils'; +import {convertToDisplayString} from '@libs/CurrencyUtils'; import Navigation from '@libs/Navigation/Navigation'; -import * as ReportUtils from '@libs/ReportUtils'; +import { + getAvailableReportFields, + getFieldViolation, + getFieldViolationTranslation, + getMoneyRequestSpendBreakdown, + getReportFieldKey, + hasUpdatedTotal, + isClosedExpenseReportWithNoExpenses as isClosedExpenseReportWithNoExpensesReportUtils, + isInvoiceReport as isInvoiceReportUtils, + isPaidGroupPolicyExpenseReport as isPaidGroupPolicyExpenseReportUtils, + isReportFieldDisabled, + isReportFieldOfTypeTitle, + isSettled as isSettledReportUtils, +} from '@libs/ReportUtils'; import AnimatedEmptyStateBackground from '@pages/home/report/AnimatedEmptyStateBackground'; import variables from '@styles/variables'; -import * as reportActions from '@src/libs/actions/Report'; +import {clearReportFieldKeyErrors} from '@src/libs/actions/Report'; import ONYXKEYS from '@src/ONYXKEYS'; import ROUTES from '@src/ROUTES'; import type {Policy, PolicyReportField, Report} from '@src/types/onyx'; @@ -29,7 +42,7 @@ import type {PendingAction} from '@src/types/onyx/OnyxCommon'; type MoneyReportViewProps = { /** The report currently being looked at */ - report: Report; + report: OnyxEntry; /** Policy that the report belongs to */ policy: OnyxEntry; @@ -52,15 +65,15 @@ function MoneyReportView({report, policy, isCombinedReport = false, shouldShowTo const StyleUtils = useStyleUtils(); const {translate} = useLocalize(); const {isOffline} = useNetwork(); - const isSettled = ReportUtils.isSettled(report.reportID); - const isTotalUpdated = ReportUtils.hasUpdatedTotal(report, policy); + const isSettled = isSettledReportUtils(report?.reportID); + const isTotalUpdated = hasUpdatedTotal(report, policy); - const {totalDisplaySpend, nonReimbursableSpend, reimbursableSpend} = ReportUtils.getMoneyRequestSpendBreakdown(report); + const {totalDisplaySpend, nonReimbursableSpend, reimbursableSpend} = getMoneyRequestSpendBreakdown(report); const shouldShowBreakdown = nonReimbursableSpend && reimbursableSpend && shouldShowTotal; - const formattedTotalAmount = CurrencyUtils.convertToDisplayString(totalDisplaySpend, report.currency); - const formattedOutOfPocketAmount = CurrencyUtils.convertToDisplayString(reimbursableSpend, report.currency); - const formattedCompanySpendAmount = CurrencyUtils.convertToDisplayString(nonReimbursableSpend, report.currency); + const formattedTotalAmount = convertToDisplayString(totalDisplaySpend, report?.currency); + const formattedOutOfPocketAmount = convertToDisplayString(reimbursableSpend, report?.currency); + const formattedCompanySpendAmount = convertToDisplayString(nonReimbursableSpend, report?.currency); const isPartiallyPaid = !!report?.pendingFields?.partial; const subAmountTextStyles: StyleProp = [ @@ -70,25 +83,25 @@ function MoneyReportView({report, policy, isCombinedReport = false, shouldShowTo StyleUtils.getColorStyle(theme.textSupporting), ]; - const [violations] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_VIOLATIONS}${report.reportID}`); + const [violations] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_VIOLATIONS}${report?.reportID}`); const sortedPolicyReportFields = useMemo((): PolicyReportField[] => { - const fields = ReportUtils.getAvailableReportFields(report, Object.values(policy?.fieldList ?? {})); - return fields.filter((field) => field.target === report.type).sort(({orderWeight: firstOrderWeight}, {orderWeight: secondOrderWeight}) => firstOrderWeight - secondOrderWeight); + const fields = getAvailableReportFields(report, Object.values(policy?.fieldList ?? {})); + return fields.filter((field) => field.target === report?.type).sort(({orderWeight: firstOrderWeight}, {orderWeight: secondOrderWeight}) => firstOrderWeight - secondOrderWeight); }, [policy, report]); - const enabledReportFields = sortedPolicyReportFields.filter((reportField) => !ReportUtils.isReportFieldDisabled(report, reportField, policy)); - const isOnlyTitleFieldEnabled = enabledReportFields.length === 1 && ReportUtils.isReportFieldOfTypeTitle(enabledReportFields.at(0)); - const isClosedExpenseReportWithNoExpenses = ReportUtils.isClosedExpenseReportWithNoExpenses(report); - const isPaidGroupPolicyExpenseReport = ReportUtils.isPaidGroupPolicyExpenseReport(report); - const isInvoiceReport = ReportUtils.isInvoiceReport(report); + const enabledReportFields = sortedPolicyReportFields.filter((reportField) => !isReportFieldDisabled(report, reportField, policy)); + const isOnlyTitleFieldEnabled = enabledReportFields.length === 1 && isReportFieldOfTypeTitle(enabledReportFields.at(0)); + const isClosedExpenseReportWithNoExpenses = isClosedExpenseReportWithNoExpensesReportUtils(report); + const isPaidGroupPolicyExpenseReport = isPaidGroupPolicyExpenseReportUtils(report); + const isInvoiceReport = isInvoiceReportUtils(report); const shouldShowReportField = !isClosedExpenseReportWithNoExpenses && (isPaidGroupPolicyExpenseReport || isInvoiceReport) && (!isCombinedReport || !isOnlyTitleFieldEnabled); const renderThreadDivider = useMemo( () => shouldHideThreadDividerLine && !isCombinedReport ? ( ) : ( @@ -97,7 +110,7 @@ function MoneyReportView({report, policy, isCombinedReport = false, shouldShowTo style={[!shouldHideThreadDividerLine ? styles.reportHorizontalRule : {}]} /> ), - [shouldHideThreadDividerLine, report.reportID, styles.reportHorizontalRule, isCombinedReport], + [shouldHideThreadDividerLine, report?.reportID, styles.reportHorizontalRule, isCombinedReport], ); return ( @@ -110,39 +123,34 @@ function MoneyReportView({report, policy, isCombinedReport = false, shouldShowTo policy?.areReportFieldsEnabled && (!isCombinedReport || !isOnlyTitleFieldEnabled) && sortedPolicyReportFields.map((reportField) => { - if (ReportUtils.isReportFieldOfTypeTitle(reportField)) { + if (isReportFieldOfTypeTitle(reportField)) { return null; } const fieldValue = reportField.value ?? reportField.defaultValue; - const isFieldDisabled = ReportUtils.isReportFieldDisabled(report, reportField, policy); - const fieldKey = ReportUtils.getReportFieldKey(reportField.fieldID); + const isFieldDisabled = isReportFieldDisabled(report, reportField, policy); + const fieldKey = getReportFieldKey(reportField.fieldID); - const violation = ReportUtils.getFieldViolation(violations, reportField); - const violationTranslation = ReportUtils.getFieldViolationTranslation(reportField, violation); + const violation = getFieldViolation(violations, reportField); + const violationTranslation = getFieldViolationTranslation(reportField, violation); return ( reportActions.clearReportFieldKeyErrors(report.reportID, fieldKey)} + onClose={() => clearReportFieldKeyErrors(report?.reportID, fieldKey)} > + onPress={() => { Navigation.navigate( - ROUTES.EDIT_REPORT_FIELD_REQUEST.getRoute( - report.reportID, - report.policyID ?? '-1', - reportField.fieldID, - Navigation.getReportRHPActiveRoute(), - ), - ) - } + ROUTES.EDIT_REPORT_FIELD_REQUEST.getRoute(report?.reportID, report?.policyID, reportField.fieldID, Navigation.getReportRHPActiveRoute()), + ); + }} shouldShowRightIcon disabled={isFieldDisabled} wrapperStyle={[styles.pv2, styles.taskDescriptionMenuItem]} diff --git a/src/components/ReportActionItem/MoneyRequestAction.tsx b/src/components/ReportActionItem/MoneyRequestAction.tsx index cc64fed1d3e6..2936fddd0376 100644 --- a/src/components/ReportActionItem/MoneyRequestAction.tsx +++ b/src/components/ReportActionItem/MoneyRequestAction.tsx @@ -7,7 +7,12 @@ import useNetwork from '@hooks/useNetwork'; import useThemeStyles from '@hooks/useThemeStyles'; import {isIOUReportPendingCurrencyConversion} from '@libs/IOUUtils'; import Navigation from '@libs/Navigation/Navigation'; -import {isDeletedParentAction, isReversedTransaction, isSplitBillAction, isTrackExpenseAction} from '@libs/ReportActionsUtils'; +import { + isDeletedParentAction as isDeletedParentActionReportActionsUtils, + isReversedTransaction as isReversedTransactionReportActionsUtils, + isSplitBillAction as isSplitBillActionReportActionsUtils, + isTrackExpenseAction as isTrackExpenseActionReportActionsUtils, +} from '@libs/ReportActionsUtils'; import type {ContextMenuAnchor} from '@pages/home/report/ContextMenu/ReportActionContextMenu'; import CONST from '@src/CONST'; import type {TranslationPaths} from '@src/languages/types'; @@ -22,13 +27,13 @@ type MoneyRequestActionProps = { action: OnyxTypes.ReportAction; /** The ID of the associated chatReport */ - chatReportID: string; + chatReportID: string | undefined; /** The ID of the associated expense report */ - requestReportID: string; + requestReportID: string | undefined; /** The ID of the current report */ - reportID: string; + reportID: string | undefined; /** Is this IOUACTION the most recent? */ isMostRecentIOUReportAction: boolean; @@ -65,32 +70,28 @@ function MoneyRequestAction({ isWhisper = false, shouldDisplayContextMenu = true, }: MoneyRequestActionProps) { + const [chatReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${chatReportID}`); + const [iouReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${requestReportID}`); + const [reportActions] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${chatReportID}`, {canEvict: false}); + const styles = useThemeStyles(); const {translate} = useLocalize(); const {isOffline} = useNetwork(); - const isActionSplitBill = isSplitBillAction(action); - const isActionTrackExpense = isTrackExpenseAction(action); - const [reportActions] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${chatReportID || CONST.DEFAULT_NUMBER_ID}`, {canEvict: false}); - const [chatReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${chatReportID || CONST.DEFAULT_NUMBER_ID}`); - const [iouReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${requestReportID}`); + const isSplitBillAction = isSplitBillActionReportActionsUtils(action); + const isTrackExpenseAction = isTrackExpenseActionReportActionsUtils(action); const onMoneyRequestPreviewPressed = () => { - if (isActionSplitBill) { - const reportActionID = action.reportActionID; - Navigation.navigate(ROUTES.SPLIT_BILL_DETAILS.getRoute(chatReportID, reportActionID, Navigation.getReportRHPActiveRoute())); + if (isSplitBillAction) { + Navigation.navigate(ROUTES.SPLIT_BILL_DETAILS.getRoute(chatReportID, action.reportActionID, Navigation.getReportRHPActiveRoute())); return; } - const childReportID = action?.childReportID; - if (!childReportID) { - return; - } - Navigation.navigate(ROUTES.REPORT_WITH_ID.getRoute(childReportID)); + Navigation.navigate(ROUTES.REPORT_WITH_ID.getRoute(action?.childReportID)); }; let shouldShowPendingConversionMessage = false; - const isParentActionDeleted = isDeletedParentAction(action); - const isTransactionReveresed = isReversedTransaction(action); + const isDeletedParentAction = isDeletedParentActionReportActionsUtils(action); + const isReversedTransaction = isReversedTransactionReportActionsUtils(action); if ( !isEmptyObject(iouReport) && !isEmptyObject(reportActions) && @@ -102,22 +103,22 @@ function MoneyRequestAction({ shouldShowPendingConversionMessage = isIOUReportPendingCurrencyConversion(iouReport); } - if (isParentActionDeleted || isTransactionReveresed) { + if (isDeletedParentAction || isReversedTransaction) { let message: TranslationPaths; - if (isTransactionReveresed) { + if (isReversedTransaction) { message = 'parentReportAction.reversedTransaction'; } else { message = 'parentReportAction.deletedExpense'; } - return ${translate(message)}`} />; + return ${translate(message)}`} />; } return ( >(); const {shouldUseNarrowLayout} = useResponsiveLayout(); const [personalDetails] = useOnyx(ONYXKEYS.PERSONAL_DETAILS_LIST); - const [chatReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${chatReportID || CONST.DEFAULT_NUMBER_ID}`); + const [chatReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${chatReportID}`); const [session] = useOnyx(ONYXKEYS.SESSION); - const [iouReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${iouReportID || CONST.DEFAULT_NUMBER_ID}`); + const [iouReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${iouReportID}`); const policy = usePolicy(iouReport?.policyID); const isMoneyRequestAction = isMoneyRequestActionReportActionsUtils(action); diff --git a/src/components/ReportActionItem/MoneyRequestPreview/index.tsx b/src/components/ReportActionItem/MoneyRequestPreview/index.tsx index f902948b2cb5..0b9d4e5f5629 100644 --- a/src/components/ReportActionItem/MoneyRequestPreview/index.tsx +++ b/src/components/ReportActionItem/MoneyRequestPreview/index.tsx @@ -6,7 +6,7 @@ import MoneyRequestPreviewContent from './MoneyRequestPreviewContent'; import type {MoneyRequestPreviewProps} from './types'; function MoneyRequestPreview(props: MoneyRequestPreviewProps) { - const [iouReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${props.iouReportID || '-1'}`); + const [iouReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${props.iouReportID}`); // We should not render the component if there is no iouReport and it's not a split or track expense. // Moved outside of the component scope to allow for easier use of hooks in the main component. // eslint-disable-next-line react/jsx-props-no-spreading diff --git a/src/components/ReportActionItem/MoneyRequestPreview/types.ts b/src/components/ReportActionItem/MoneyRequestPreview/types.ts index c40b45c6d2bd..186c81a8c866 100644 --- a/src/components/ReportActionItem/MoneyRequestPreview/types.ts +++ b/src/components/ReportActionItem/MoneyRequestPreview/types.ts @@ -7,13 +7,13 @@ type MoneyRequestPreviewProps = { /** The active IOUReport, used for Onyx subscription */ // The iouReportID is used inside withOnyx HOC // eslint-disable-next-line react/no-unused-prop-types - iouReportID: string; + iouReportID: string | undefined; /** The associated chatReport */ - chatReportID: string; + chatReportID: string | undefined; /** The ID of the current report */ - reportID: string; + reportID: string | undefined; /** Callback for the preview pressed */ onPreviewPressed: (event?: GestureResponderEvent | KeyboardEvent) => void; diff --git a/src/components/ReportActionItem/ReportPreview.tsx b/src/components/ReportActionItem/ReportPreview.tsx index ae40e8ceed79..4616feeffbca 100644 --- a/src/components/ReportActionItem/ReportPreview.tsx +++ b/src/components/ReportActionItem/ReportPreview.tsx @@ -96,13 +96,13 @@ type ReportPreviewProps = { action: ReportAction; /** The associated chatReport */ - chatReportID: string; + chatReportID: string | undefined; /** The active IOUReport, used for Onyx subscription */ iouReportID: string | undefined; /** The report's policyID, used for Onyx subscription */ - policyID: string; + policyID: string | undefined; /** Extra styles to pass to View wrapper */ containerStyles?: StyleProp; diff --git a/src/components/ReportActionItem/TaskPreview.tsx b/src/components/ReportActionItem/TaskPreview.tsx index 91e9cdbbc9c1..3eca7561eb04 100644 --- a/src/components/ReportActionItem/TaskPreview.tsx +++ b/src/components/ReportActionItem/TaskPreview.tsx @@ -38,9 +38,9 @@ import {isEmptyObject} from '@src/types/utils/EmptyObject'; type TaskPreviewProps = WithCurrentUserPersonalDetailsProps & { /** The ID of the associated policy */ // eslint-disable-next-line react/no-unused-prop-types - policyID: string; + policyID: string | undefined; /** The ID of the associated taskReport */ - taskReportID: string; + taskReportID: string | undefined; /** Whether the task preview is hovered so we can modify its style */ isHovered: boolean; @@ -49,7 +49,7 @@ type TaskPreviewProps = WithCurrentUserPersonalDetailsProps & { action: OnyxEntry; /** The chat report associated with taskReport */ - chatReportID: string; + chatReportID: string | undefined; /** Popover context menu anchor, used for showing context menu */ contextMenuAnchor: ContextMenuAnchor; diff --git a/src/components/ReportActionItem/TaskView.tsx b/src/components/ReportActionItem/TaskView.tsx index 7901426b33e0..3e077c2bda4a 100644 --- a/src/components/ReportActionItem/TaskView.tsx +++ b/src/components/ReportActionItem/TaskView.tsx @@ -1,5 +1,6 @@ import React, {useEffect} from 'react'; import {View} from 'react-native'; +import type {OnyxEntry} from 'react-native-onyx'; import Checkbox from '@components/Checkbox'; import Hoverable from '@components/Hoverable'; import Icon from '@components/Icon'; @@ -17,18 +18,18 @@ import useThemeStyles from '@hooks/useThemeStyles'; import convertToLTR from '@libs/convertToLTR'; import getButtonState from '@libs/getButtonState'; import Navigation from '@libs/Navigation/Navigation'; -import * as OptionsListUtils from '@libs/OptionsListUtils'; -import * as ReportUtils from '@libs/ReportUtils'; -import * as TaskUtils from '@libs/TaskUtils'; -import * as Session from '@userActions/Session'; -import * as Task from '@userActions/Task'; +import {getAvatarsForAccountIDs, getPersonalDetailsForAccountIDs} from '@libs/OptionsListUtils'; +import {getDisplayNameForParticipant, getDisplayNamesWithTooltips, isCompletedTaskReport, isOpenTaskReport} from '@libs/ReportUtils'; +import {isActiveTaskEditRoute} from '@libs/TaskUtils'; +import {checkIfActionIsAllowed} from '@userActions/Session'; +import {canActionTask as canActionTaskUtil, canModifyTask as canModifyTaskUtil, clearTaskErrors, completeTask, reopenTask, setTaskReport} from '@userActions/Task'; import CONST from '@src/CONST'; import ROUTES from '@src/ROUTES'; import type {Report} from '@src/types/onyx'; type TaskViewProps = { /** The report currently being looked at */ - report: Report; + report: OnyxEntry; }; function TaskView({report}: TaskViewProps) { @@ -37,17 +38,14 @@ function TaskView({report}: TaskViewProps) { const currentUserPersonalDetails = useCurrentUserPersonalDetails(); const personalDetails = usePersonalDetails(); useEffect(() => { - Task.setTaskReport(report); + setTaskReport(report); }, [report]); - const taskTitle = convertToLTR(report.reportName ?? ''); - const assigneeTooltipDetails = ReportUtils.getDisplayNamesWithTooltips( - OptionsListUtils.getPersonalDetailsForAccountIDs(report.managerID ? [report.managerID] : [], personalDetails), - false, - ); - const isOpen = ReportUtils.isOpenTaskReport(report); - const isCompleted = ReportUtils.isCompletedTaskReport(report); - const canModifyTask = Task.canModifyTask(report, currentUserPersonalDetails.accountID); - const canActionTask = Task.canActionTask(report, currentUserPersonalDetails.accountID); + const taskTitle = convertToLTR(report?.reportName ?? ''); + const assigneeTooltipDetails = getDisplayNamesWithTooltips(getPersonalDetailsForAccountIDs(report?.managerID ? [report?.managerID] : [], personalDetails), false); + const isOpen = isOpenTaskReport(report); + const isCompleted = isCompletedTaskReport(report); + const canModifyTask = canModifyTaskUtil(report, currentUserPersonalDetails.accountID); + const canActionTask = canActionTaskUtil(report, currentUserPersonalDetails.accountID); const disableState = !canModifyTask; const isDisableInteractive = !canModifyTask || !isOpen; const {translate} = useLocalize(); @@ -56,14 +54,14 @@ function TaskView({report}: TaskViewProps) { Task.clearTaskErrors(report.reportID)} + errors={report?.errorFields?.editTask ?? report?.errorFields?.createTask} + onClose={() => clearTaskErrors(report?.reportID)} errorRowStyles={styles.ph5} > {(hovered) => ( { + onPress={checkIfActionIsAllowed((e) => { if (isDisableInteractive) { return; } @@ -71,7 +69,7 @@ function TaskView({report}: TaskViewProps) { (e.currentTarget as HTMLElement).blur(); } - Navigation.navigate(ROUTES.TASK_TITLE.getRoute(report.reportID, Navigation.getReportRHPActiveRoute())); + Navigation.navigate(ROUTES.TASK_TITLE.getRoute(report?.reportID, Navigation.getReportRHPActiveRoute())); })} style={({pressed}) => [ styles.ph5, @@ -83,19 +81,19 @@ function TaskView({report}: TaskViewProps) { disabled={isDisableInteractive} > {({pressed}) => ( - + {translate('task.title')} { + onPress={checkIfActionIsAllowed(() => { // If we're already navigating to these task editing pages, early return not to mark as completed, otherwise we would have not found page. - if (TaskUtils.isActiveTaskEditRoute(report.reportID)) { + if (isActiveTaskEditRoute(report?.reportID)) { return; } if (isCompleted) { - Task.reopenTask(report); + reopenTask(report); } else { - Task.completeTask(report); + completeTask(report); } })} isChecked={isCompleted} @@ -129,12 +127,12 @@ function TaskView({report}: TaskViewProps) { )} - + Navigation.navigate(ROUTES.REPORT_DESCRIPTION.getRoute(report.reportID, Navigation.getReportRHPActiveRoute()))} + title={report?.description ?? ''} + onPress={() => Navigation.navigate(ROUTES.REPORT_DESCRIPTION.getRoute(report?.reportID, Navigation.getReportRHPActiveRoute()))} shouldShowRightIcon={!isDisableInteractive} disabled={disableState} wrapperStyle={[styles.pv2, styles.taskDescriptionMenuItem]} @@ -144,16 +142,16 @@ function TaskView({report}: TaskViewProps) { shouldUseDefaultCursorWhenDisabled /> - - {report.managerID ? ( + + {report?.managerID ? ( Navigation.navigate(ROUTES.TASK_ASSIGNEE.getRoute(report.reportID, Navigation.getReportRHPActiveRoute()))} + onPress={() => Navigation.navigate(ROUTES.TASK_ASSIGNEE.getRoute(report?.reportID, Navigation.getReportRHPActiveRoute()))} shouldShowRightIcon={!isDisableInteractive} disabled={disableState} wrapperStyle={[styles.pv2]} @@ -166,7 +164,7 @@ function TaskView({report}: TaskViewProps) { ) : ( Navigation.navigate(ROUTES.TASK_ASSIGNEE.getRoute(report.reportID, Navigation.getReportRHPActiveRoute()))} + onPress={() => Navigation.navigate(ROUTES.TASK_ASSIGNEE.getRoute(report?.reportID, Navigation.getReportRHPActiveRoute()))} shouldShowRightIcon={!isDisableInteractive} disabled={disableState} wrapperStyle={[styles.pv2]} diff --git a/src/components/ReportActionItem/TripRoomPreview.tsx b/src/components/ReportActionItem/TripRoomPreview.tsx index 8c275464804c..d85c19d21ee0 100644 --- a/src/components/ReportActionItem/TripRoomPreview.tsx +++ b/src/components/ReportActionItem/TripRoomPreview.tsx @@ -1,5 +1,5 @@ import React, {useMemo} from 'react'; -import type {StyleProp, ViewStyle} from 'react-native'; +import type {ListRenderItemInfo, StyleProp, ViewStyle} from 'react-native'; import {FlatList, View} from 'react-native'; import {useOnyx} from 'react-native-onyx'; import Button from '@components/Button'; @@ -36,7 +36,7 @@ type TripRoomPreviewProps = { action: ReportAction; /** The associated chatReport */ - chatReportID: string; + chatReportID: string | undefined; /** Extra styles to pass to View wrapper */ containerStyles?: StyleProp; @@ -111,7 +111,7 @@ function ReservationView({reservation}: ReservationViewProps) { ); } -const renderItem = ({item}: {item: ReservationData}) => ; +const renderItem = ({item}: ListRenderItemInfo) => ; function TripRoomPreview({action, chatReportID, containerStyles, contextMenuAnchor, isHovered = false, checkIfContextMenuActive = () => {}}: TripRoomPreviewProps) { const styles = useThemeStyles(); diff --git a/src/components/UnreadActionIndicator.tsx b/src/components/UnreadActionIndicator.tsx index c63079e69853..f99efda0c2b6 100755 --- a/src/components/UnreadActionIndicator.tsx +++ b/src/components/UnreadActionIndicator.tsx @@ -7,7 +7,7 @@ import Text from './Text'; type UnreadActionIndicatorProps = { /** The ID of the report action */ - reportActionID: string; + reportActionID: string | undefined; /** Whether we should hide thread divider line */ shouldHideThreadDividerLine?: boolean; diff --git a/src/libs/ReportUtils.ts b/src/libs/ReportUtils.ts index 1015d0b5fec6..c615b58f2587 100644 --- a/src/libs/ReportUtils.ts +++ b/src/libs/ReportUtils.ts @@ -3233,10 +3233,10 @@ function getReportFieldsByPolicyID(policyID: string | undefined): Record, policyReportFields: PolicyReportField[]): PolicyReportField[] { // Get the report fields that are attached to a report. These will persist even if a field is deleted from the policy. - const reportFields = Object.values(report.fieldList ?? {}); - const reportIsSettled = isSettled(report.reportID); + const reportFields = Object.values(report?.fieldList ?? {}); + const reportIsSettled = isSettled(report?.reportID); // If the report is settled, we don't want to show any new field that gets added to the policy. if (reportIsSettled) { diff --git a/src/libs/TaskUtils.ts b/src/libs/TaskUtils.ts index 975c3e617ce5..ac66bdebd42c 100644 --- a/src/libs/TaskUtils.ts +++ b/src/libs/TaskUtils.ts @@ -6,7 +6,7 @@ import ROUTES from '@src/ROUTES'; import type {Report} from '@src/types/onyx'; import type {Message} from '@src/types/onyx/ReportAction'; import type ReportAction from '@src/types/onyx/ReportAction'; -import * as Localize from './Localize'; +import {translateLocal} from './Localize'; import Navigation from './Navigation/Navigation'; import {getReportActionHtml, getReportActionText} from './ReportActionsUtils'; @@ -22,7 +22,11 @@ Onyx.connect({ /** * Check if the active route belongs to task edit flow. */ -function isActiveTaskEditRoute(reportID: string): boolean { +function isActiveTaskEditRoute(reportID: string | undefined): boolean { + if (!reportID) { + return false; + } + return [ROUTES.TASK_TITLE, ROUTES.TASK_ASSIGNEE, ROUTES.REPORT_DESCRIPTION].map((route) => route.getRoute(reportID)).some(Navigation.isActiveRoute); } @@ -32,18 +36,18 @@ function isActiveTaskEditRoute(reportID: string): boolean { function getTaskReportActionMessage(action: OnyxEntry): Pick { switch (action?.actionName) { case CONST.REPORT.ACTIONS.TYPE.TASK_COMPLETED: - return {text: Localize.translateLocal('task.messages.completed')}; + return {text: translateLocal('task.messages.completed')}; case CONST.REPORT.ACTIONS.TYPE.TASK_CANCELLED: - return {text: Localize.translateLocal('task.messages.canceled')}; + return {text: translateLocal('task.messages.canceled')}; case CONST.REPORT.ACTIONS.TYPE.TASK_REOPENED: - return {text: Localize.translateLocal('task.messages.reopened')}; + return {text: translateLocal('task.messages.reopened')}; case CONST.REPORT.ACTIONS.TYPE.TASK_EDITED: return { text: getReportActionText(action), html: getReportActionHtml(action), }; default: - return {text: Localize.translateLocal('task.task')}; + return {text: translateLocal('task.task')}; } } @@ -54,15 +58,15 @@ function getTaskTitleFromReport(taskReport: OnyxEntry, fallbackTitle = ' return taskReport?.reportID && taskReport.reportName ? taskReport.reportName : fallbackTitle; } -function getTaskTitle(taskReportID: string, fallbackTitle = ''): string { +function getTaskTitle(taskReportID: string | undefined, fallbackTitle = ''): string { const taskReport = allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${taskReportID}`]; return getTaskTitleFromReport(taskReport, fallbackTitle); } function getTaskCreatedMessage(reportAction: OnyxEntry) { - const taskReportID = reportAction?.childReportID ?? '-1'; + const taskReportID = reportAction?.childReportID; const taskTitle = getTaskTitle(taskReportID, reportAction?.childReportName); - return taskTitle ? Localize.translateLocal('task.messages.created', {title: taskTitle}) : ''; + return taskTitle ? translateLocal('task.messages.created', {title: taskTitle}) : ''; } export {isActiveTaskEditRoute, getTaskReportActionMessage, getTaskTitle, getTaskTitleFromReport, getTaskCreatedMessage}; diff --git a/src/libs/actions/Chronos.ts b/src/libs/actions/Chronos.ts index 548b8398beec..5a54c2ee9368 100644 --- a/src/libs/actions/Chronos.ts +++ b/src/libs/actions/Chronos.ts @@ -7,7 +7,7 @@ import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import type {ChronosOOOEvent} from '@src/types/onyx/OriginalMessage'; -const removeEvent = (reportID: string, reportActionID: string, eventID: string, events: ChronosOOOEvent[]) => { +const removeEvent = (reportID: string | undefined, reportActionID: string, eventID: string, events: ChronosOOOEvent[]) => { const optimisticData: OnyxUpdate[] = [ { onyxMethod: Onyx.METHOD.MERGE, diff --git a/src/libs/actions/Policy/Member.ts b/src/libs/actions/Policy/Member.ts index 44b0a71dc72c..834812013b5c 100644 --- a/src/libs/actions/Policy/Member.ts +++ b/src/libs/actions/Policy/Member.ts @@ -874,11 +874,12 @@ function setWorkspaceInviteMembersDraft(policyID: string, invitedEmailsToAccount /** * Accept user join request to a workspace */ -function acceptJoinRequest(reportID: string, reportAction: OnyxEntry) { - const choice = CONST.REPORT.ACTIONABLE_MENTION_JOIN_WORKSPACE_RESOLUTION.ACCEPT; - if (!reportAction) { +function acceptJoinRequest(reportID: string | undefined, reportAction: OnyxEntry) { + if (!reportAction || !reportID) { + Log.warn('acceptJoinRequest missing reportID or reportAction', {reportAction, reportID}); return; } + const choice = CONST.REPORT.ACTIONABLE_MENTION_JOIN_WORKSPACE_RESOLUTION.ACCEPT; const optimisticData: OnyxUpdate[] = [ { @@ -933,8 +934,9 @@ function acceptJoinRequest(reportID: string, reportAction: OnyxEntry) { - if (!reportAction) { +function declineJoinRequest(reportID: string | undefined, reportAction: OnyxEntry) { + if (!reportAction || !reportID) { + Log.warn('declineJoinRequest missing reportID or reportAction', {reportAction, reportID}); return; } const choice = CONST.REPORT.ACTIONABLE_MENTION_JOIN_WORKSPACE_RESOLUTION.DECLINE; diff --git a/src/libs/actions/Report.ts b/src/libs/actions/Report.ts index ea8aa5414c7b..fa6046c6baa4 100644 --- a/src/libs/actions/Report.ts +++ b/src/libs/actions/Report.ts @@ -1361,7 +1361,11 @@ function getNewerActions(reportID: string | undefined, reportActionID: string | /** * Gets metadata info about links in the provided report action */ -function expandURLPreview(reportID: string, reportActionID: string) { +function expandURLPreview(reportID: string | undefined, reportActionID: string) { + if (!reportID) { + return; + } + const parameters: ExpandURLPreviewParams = { reportID, reportActionID, @@ -1455,7 +1459,11 @@ function markCommentAsUnread(reportID: string | undefined, reportActionCreated: } /** Toggles the pinned state of the report. */ -function togglePinnedState(reportID: string, isPinnedChat: boolean) { +function togglePinnedState(reportID: string | undefined, isPinnedChat: boolean) { + if (!reportID) { + return; + } + const pinnedValue = !isPinnedChat; // Optimistically pin/unpin the report before we send out the command @@ -1743,14 +1751,13 @@ function handleUserDeletedLinksInHtml(newCommentText: string, originalCommentMar } /** Saves a new message for a comment. Marks the comment as edited, which will be reflected in the UI. */ -function editReportComment(reportID: string, originalReportAction: OnyxEntry, textForNewComment: string, videoAttributeCache?: Record) { +function editReportComment(reportID: string | undefined, originalReportAction: OnyxEntry, textForNewComment: string, videoAttributeCache?: Record) { const originalReportID = getOriginalReportID(reportID, originalReportAction); - const report = allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${originalReportID}`]; - const canUserPerformWriteAction = canUserPerformWriteActionReportUtils(report); - if (!originalReportID || !originalReportAction) { return; } + const report = allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${originalReportID}`]; + const canUserPerformWriteAction = canUserPerformWriteActionReportUtils(report); // Do not autolink if someone explicitly tries to remove a link from message. // https://github.com/Expensify/App/issues/9090 @@ -1873,13 +1880,13 @@ function editReportComment(reportID: string, originalReportAction: OnyxEntry = { [`${ONYXKEYS.COLLECTION.REPORT}${reportID}`]: null, @@ -2523,7 +2534,7 @@ function deleteReport(reportID: string, shouldDeleteChildReports = false) { /** * @param reportID The reportID of the policy report (workspace room) */ -function navigateToConciergeChatAndDeleteReport(reportID: string, shouldPopToTop = false, shouldDeleteChildReports = false) { +function navigateToConciergeChatAndDeleteReport(reportID: string | undefined, shouldPopToTop = false, shouldDeleteChildReports = false) { // Dismiss the current report screen and replace it with Concierge Chat if (shouldPopToTop) { Navigation.setShouldPopAllStateOnUP(true); @@ -2730,7 +2741,7 @@ function showReportActionNotification(reportID: string, reportAction: ReportActi } /** Clear the errors associated with the IOUs of a given report. */ -function clearIOUError(reportID: string) { +function clearIOUError(reportID: string | undefined) { Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, {errorFields: {iou: null}}); } @@ -2832,7 +2843,7 @@ function removeEmojiReaction(reportID: string, reportActionID: string, emoji: Em * Uses the NEW FORMAT for "emojiReactions" */ function toggleEmojiReaction( - reportID: string, + reportID: string | undefined, reportAction: ReportAction, reactionObject: Emoji, existingReactions: OnyxEntry, @@ -4318,9 +4329,13 @@ function clearNewRoomFormError() { }); } -function resolveActionableMentionWhisper(reportId: string, reportAction: OnyxEntry, resolution: ValueOf) { +function resolveActionableMentionWhisper( + reportID: string | undefined, + reportAction: OnyxEntry, + resolution: ValueOf, +) { const message = ReportActionsUtils.getReportActionMessage(reportAction); - if (!message || !reportAction) { + if (!message || !reportAction || !reportID) { return; } @@ -4337,8 +4352,8 @@ function resolveActionableMentionWhisper(reportId: string, reportAction: OnyxEnt }, }; - const report = allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${reportId}`]; - const reportUpdateDataWithPreviousLastMessage = getReportLastMessage(reportId, optimisticReportActions as ReportActions); + const report = allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${reportID}`]; + const reportUpdateDataWithPreviousLastMessage = getReportLastMessage(reportID, optimisticReportActions as ReportActions); const reportUpdateDataWithCurrentLastMessage = { lastMessageText: report?.lastMessageText, @@ -4349,7 +4364,7 @@ function resolveActionableMentionWhisper(reportId: string, reportAction: OnyxEnt const optimisticData: OnyxUpdate[] = [ { onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportId}`, + key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`, value: { [reportAction.reportActionID]: { message: [updatedMessage], @@ -4361,7 +4376,7 @@ function resolveActionableMentionWhisper(reportId: string, reportAction: OnyxEnt }, { onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT}${reportId}`, + key: `${ONYXKEYS.COLLECTION.REPORT}${reportID}`, value: reportUpdateDataWithPreviousLastMessage, }, ]; @@ -4369,7 +4384,7 @@ function resolveActionableMentionWhisper(reportId: string, reportAction: OnyxEnt const failureData: OnyxUpdate[] = [ { onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportId}`, + key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`, value: { [reportAction.reportActionID]: { message: [message], @@ -4381,7 +4396,7 @@ function resolveActionableMentionWhisper(reportId: string, reportAction: OnyxEnt }, { onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT}${reportId}`, + key: `${ONYXKEYS.COLLECTION.REPORT}${reportID}`, value: reportUpdateDataWithCurrentLastMessage, // revert back to the current report last message data in case of failure }, ]; @@ -4395,11 +4410,11 @@ function resolveActionableMentionWhisper(reportId: string, reportAction: OnyxEnt } function resolveActionableReportMentionWhisper( - reportId: string, + reportId: string | undefined, reportAction: OnyxEntry, resolution: ValueOf, ) { - if (!reportAction) { + if (!reportAction || !reportId) { return; } @@ -4466,10 +4481,10 @@ function resolveActionableReportMentionWhisper( API.write(WRITE_COMMANDS.RESOLVE_ACTIONABLE_REPORT_MENTION_WHISPER, parameters, {optimisticData, failureData}); } -function dismissTrackExpenseActionableWhisper(reportID: string, reportAction: OnyxEntry): void { +function dismissTrackExpenseActionableWhisper(reportID: string | undefined, reportAction: OnyxEntry): void { const isArrayMessage = Array.isArray(reportAction?.message); const message = ReportActionsUtils.getReportActionMessage(reportAction); - if (!message || !reportAction) { + if (!message || !reportAction || !reportID) { return; } diff --git a/src/libs/actions/ReportActions.ts b/src/libs/actions/ReportActions.ts index 89517a753c26..e8d7949464d8 100644 --- a/src/libs/actions/ReportActions.ts +++ b/src/libs/actions/ReportActions.ts @@ -1,12 +1,12 @@ import type {OnyxCollection} from 'react-native-onyx'; import Onyx from 'react-native-onyx'; -import * as ReportActionUtils from '@libs/ReportActionsUtils'; -import * as ReportUtils from '@libs/ReportUtils'; +import {getLinkedTransactionID, getReportAction, getReportActionMessage, isCreatedTaskReportAction} from '@libs/ReportActionsUtils'; +import {getOriginalReportID} from '@libs/ReportUtils'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import type * as OnyxTypes from '@src/types/onyx'; import type ReportAction from '@src/types/onyx/ReportAction'; -import * as Report from './Report'; +import {deleteReport} from './Report'; type IgnoreDirection = 'parent' | 'child'; @@ -27,7 +27,7 @@ Onyx.connect({ }); function clearReportActionErrors(reportID: string, reportAction: ReportAction, keys?: string[]) { - const originalReportID = ReportUtils.getOriginalReportID(reportID, reportAction); + const originalReportID = getOriginalReportID(reportID, reportAction); if (!reportAction?.reportActionID) { return; @@ -41,16 +41,16 @@ function clearReportActionErrors(reportID: string, reportAction: ReportAction, k // If there's a linked transaction, delete that too // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing - const linkedTransactionID = ReportActionUtils.getLinkedTransactionID(reportAction.reportActionID, originalReportID || '-1'); + const linkedTransactionID = getLinkedTransactionID(reportAction.reportActionID, originalReportID); if (linkedTransactionID) { Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${linkedTransactionID}`, null); Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${reportAction.childReportID}`, null); } // Delete the failed task report too - const taskReportID = ReportActionUtils.getReportActionMessage(reportAction)?.taskReportID; - if (taskReportID && ReportActionUtils.isCreatedTaskReportAction(reportAction)) { - Report.deleteReport(taskReportID); + const taskReportID = getReportActionMessage(reportAction)?.taskReportID; + if (taskReportID && isCreatedTaskReportAction(reportAction)) { + deleteReport(taskReportID); } return; } @@ -81,9 +81,9 @@ function clearReportActionErrors(reportID: string, reportAction: ReportAction, k ignore: `undefined` means we want to check both parent and children report actions ignore: `parent` or `child` means we want to ignore checking parent or child report actions because they've been previously checked */ -function clearAllRelatedReportActionErrors(reportID: string, reportAction: ReportAction | null | undefined, ignore?: IgnoreDirection, keys?: string[]) { +function clearAllRelatedReportActionErrors(reportID: string | undefined, reportAction: ReportAction | null | undefined, ignore?: IgnoreDirection, keys?: string[]) { const errorKeys = keys ?? Object.keys(reportAction?.errors ?? {}); - if (!reportAction || errorKeys.length === 0) { + if (!reportAction || errorKeys.length === 0 || !reportID) { return; } @@ -91,7 +91,7 @@ function clearAllRelatedReportActionErrors(reportID: string, reportAction: Repor const report = allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${reportID}`]; if (report?.parentReportID && report?.parentReportActionID && ignore !== 'parent') { - const parentReportAction = ReportActionUtils.getReportAction(report.parentReportID, report.parentReportActionID); + const parentReportAction = getReportAction(report.parentReportID, report.parentReportActionID); const parentErrorKeys = Object.keys(parentReportAction?.errors ?? {}).filter((err) => errorKeys.includes(err)); clearAllRelatedReportActionErrors(report.parentReportID, parentReportAction, 'child', parentErrorKeys); @@ -101,7 +101,7 @@ function clearAllRelatedReportActionErrors(reportID: string, reportAction: Repor const childActions = allReportActions?.[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportAction.childReportID}`] ?? {}; Object.values(childActions).forEach((action) => { const childErrorKeys = Object.keys(action.errors ?? {}).filter((err) => errorKeys.includes(err)); - clearAllRelatedReportActionErrors(reportAction.childReportID ?? '-1', action, 'parent', childErrorKeys); + clearAllRelatedReportActionErrors(reportAction.childReportID, action, 'parent', childErrorKeys); }); } } diff --git a/src/libs/actions/Task.ts b/src/libs/actions/Task.ts index fa14e6fef7a8..2864b989ed3d 100644 --- a/src/libs/actions/Task.ts +++ b/src/libs/actions/Task.ts @@ -1251,7 +1251,11 @@ function canActionTask(taskReport: OnyxEntry, sessionAccountID return sessionAccountID === ownerAccountID || sessionAccountID === assigneeAccountID; } -function clearTaskErrors(reportID: string) { +function clearTaskErrors(reportID: string | undefined) { + if (!reportID) { + return; + } + const report = allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${reportID}`]; // Delete the task preview in the parent report diff --git a/src/pages/home/report/ContextMenu/BaseReportActionContextMenu.tsx b/src/pages/home/report/ContextMenu/BaseReportActionContextMenu.tsx index b97e7f2c3dd7..663b83c619e1 100755 --- a/src/pages/home/report/ContextMenu/BaseReportActionContextMenu.tsx +++ b/src/pages/home/report/ContextMenu/BaseReportActionContextMenu.tsx @@ -42,7 +42,7 @@ import {hideContextMenu, showContextMenu} from './ReportActionContextMenu'; type BaseReportActionContextMenuProps = { /** The ID of the report this report action is attached to. */ - reportID: string; + reportID: string | undefined; /** The ID of the report action this context menu is attached to. */ reportActionID: string; @@ -204,6 +204,7 @@ function BaseReportActionContextMenu({ let filteredContextMenuActions = ContextMenuActions.filter( (contextAction) => !disabledActions.includes(contextAction) && + reportID && contextAction.shouldShow({ type, reportAction, diff --git a/src/pages/home/report/ContextMenu/ContextMenuActions.tsx b/src/pages/home/report/ContextMenu/ContextMenuActions.tsx index 91481cd30754..3c9952063a00 100644 --- a/src/pages/home/report/ContextMenu/ContextMenuActions.tsx +++ b/src/pages/home/report/ContextMenu/ContextMenuActions.tsx @@ -147,7 +147,7 @@ type ShouldShow = (args: { type ContextMenuActionPayload = { reportAction: ReportAction; transaction?: OnyxEntry; - reportID: string; + reportID: string | undefined; report: OnyxEntry; draftMessage: string; selection: string; @@ -630,6 +630,10 @@ const ContextMenuActions: ContextMenuAction[] = [ !isChronosReport && reportAction?.actorAccountID !== CONST.ACCOUNT_ID.CONCIERGE, onPress: (closePopover, {reportID, reportAction}) => { + if (!reportID) { + return; + } + const activeRoute = Navigation.getActiveRoute(); if (closePopover) { hideContextMenu(false, () => Navigation.navigate(ROUTES.FLAG_COMMENT.getRoute(reportID, reportAction?.reportActionID, activeRoute))); diff --git a/src/pages/home/report/ContextMenu/ReportActionContextMenu.ts b/src/pages/home/report/ContextMenu/ReportActionContextMenu.ts index 14ce17798e51..a9c2d7c83225 100644 --- a/src/pages/home/report/ContextMenu/ReportActionContextMenu.ts +++ b/src/pages/home/report/ContextMenu/ReportActionContextMenu.ts @@ -105,9 +105,9 @@ function showContextMenu( event: GestureResponderEvent | MouseEvent, selection: string, contextMenuAnchor: ContextMenuAnchor, - reportID = '-1', - reportActionID = '-1', - originalReportID = '-1', + reportID: string | undefined = undefined, + reportActionID: string | undefined = undefined, + originalReportID: string | undefined = undefined, draftMessage: string | undefined = undefined, onShow = () => {}, onHide = () => {}, @@ -171,8 +171,8 @@ function hideDeleteModal() { /** * Opens the Confirm delete action modal */ -function showDeleteModal(reportID: string, reportAction: OnyxEntry, shouldSetModalVisibility?: boolean, onConfirm?: OnConfirm, onCancel?: OnCancel) { - if (!contextMenuRef.current) { +function showDeleteModal(reportID: string | undefined, reportAction: OnyxEntry, shouldSetModalVisibility?: boolean, onConfirm?: OnConfirm, onCancel?: OnCancel) { + if (!contextMenuRef.current || !reportID) { return; } contextMenuRef.current.showDeleteModal(reportID, reportAction, shouldSetModalVisibility, onConfirm, onCancel); diff --git a/src/pages/home/report/PureReportActionItem.tsx b/src/pages/home/report/PureReportActionItem.tsx index c74531acf317..aebf631257ce 100644 --- a/src/pages/home/report/PureReportActionItem.tsx +++ b/src/pages/home/report/PureReportActionItem.tsx @@ -68,7 +68,6 @@ import { isActionableReportMentionWhisper, isActionableTrackExpense, isActionOfType, - isAddCommentAction, isChronosOOOListAction, isCreatedTaskReportAction, isDeletedAction, @@ -231,7 +230,7 @@ type PureReportActionItemProps = { originalReportID?: string; /** Function to deletes the draft for a comment report action. */ - deleteReportActionDraft?: (reportID: string, action: OnyxTypes.ReportAction) => void; + deleteReportActionDraft?: (reportID: string | undefined, action: OnyxTypes.ReportAction) => void; /** Whether the room is archived */ isArchivedRoom?: boolean; @@ -241,7 +240,7 @@ type PureReportActionItemProps = { /** Function to toggle emoji reaction */ toggleEmojiReaction?: ( - reportID: string, + reportID: string | undefined, reportAction: OnyxTypes.ReportAction, reactionObject: Emoji, existingReactions: OnyxEntry, @@ -250,18 +249,18 @@ type PureReportActionItemProps = { ) => void; /** Function to create a draft transaction and navigate to participant selector */ - createDraftTransactionAndNavigateToParticipantSelector?: (transactionID: string, reportID: string, actionName: IOUAction, reportActionID: string) => void; + createDraftTransactionAndNavigateToParticipantSelector?: (transactionID: string | undefined, reportID: string | undefined, actionName: IOUAction, reportActionID: string) => void; /** Function to resolve actionable report mention whisper */ resolveActionableReportMentionWhisper?: ( - reportId: string, + reportId: string | undefined, reportAction: OnyxEntry, resolution: ValueOf, ) => void; /** Function to resolve actionable mention whisper */ resolveActionableMentionWhisper?: ( - reportId: string, + reportId: string | undefined, reportAction: OnyxEntry, resolution: ValueOf, ) => void; @@ -288,10 +287,10 @@ type PureReportActionItemProps = { clearError?: (transactionID: string) => void; /** Function to clear all errors from a report action */ - clearAllRelatedReportActionErrors?: (reportID: string, reportAction: OnyxTypes.ReportAction | null | undefined, ignore?: IgnoreDirection, keys?: string[]) => void; + clearAllRelatedReportActionErrors?: (reportID: string | undefined, reportAction: OnyxTypes.ReportAction | null | undefined, ignore?: IgnoreDirection, keys?: string[]) => void; /** Function to dismiss the actionable whisper for tracking expenses */ - dismissTrackExpenseActionableWhisper?: (reportID: string, reportAction: OnyxEntry) => void; + dismissTrackExpenseActionableWhisper?: (reportID: string | undefined, reportAction: OnyxEntry) => void; /** User payment card ID */ userBillingFundID?: number; @@ -354,7 +353,7 @@ function PureReportActionItem({ }: PureReportActionItemProps) { const {translate} = useLocalize(); const {shouldUseNarrowLayout} = useResponsiveLayout(); - const reportID = report?.reportID ?? ''; + const reportID = report?.reportID; const theme = useTheme(); const styles = useThemeStyles(); const StyleUtils = useStyleUtils(); @@ -556,7 +555,7 @@ function PureReportActionItem({ const contextValue = useMemo( () => ({ anchor: popoverAnchorRef.current, - report: {...report, reportID: report?.reportID ?? ''}, + report, reportNameValuePairs, action, transactionThreadReport, @@ -568,8 +567,7 @@ function PureReportActionItem({ const attachmentContextValue = useMemo(() => ({reportID, type: CONST.ATTACHMENT_TYPE.REPORT}), [reportID]); - const mentionReportContextValue = useMemo(() => ({currentReportID: report?.reportID ?? '-1'}), [report?.reportID]); - + const mentionReportContextValue = useMemo(() => ({currentReportID: report?.reportID}), [report?.reportID]); const actionableItemButtons: ActionableItem[] = useMemo(() => { if (isActionableAddPaymentCard(action) && userBillingFundID === undefined && shouldRenderAddPaymentCard()) { return [ @@ -596,7 +594,7 @@ function PureReportActionItem({ text: 'actionableMentionTrackExpense.submit', key: `${action.reportActionID}-actionableMentionTrackExpense-submit`, onPress: () => { - createDraftTransactionAndNavigateToParticipantSelector(transactionID ?? '0', reportID, CONST.IOU.ACTION.SUBMIT, action.reportActionID); + createDraftTransactionAndNavigateToParticipantSelector(transactionID, reportID, CONST.IOU.ACTION.SUBMIT, action.reportActionID); }, isMediumSized: true, }, @@ -604,7 +602,7 @@ function PureReportActionItem({ text: 'actionableMentionTrackExpense.categorize', key: `${action.reportActionID}-actionableMentionTrackExpense-categorize`, onPress: () => { - createDraftTransactionAndNavigateToParticipantSelector(transactionID ?? '0', reportID, CONST.IOU.ACTION.CATEGORIZE, action.reportActionID); + createDraftTransactionAndNavigateToParticipantSelector(transactionID, reportID, CONST.IOU.ACTION.CATEGORIZE, action.reportActionID); }, isMediumSized: true, }, @@ -612,7 +610,7 @@ function PureReportActionItem({ text: 'actionableMentionTrackExpense.share', key: `${action.reportActionID}-actionableMentionTrackExpense-share`, onPress: () => { - createDraftTransactionAndNavigateToParticipantSelector(transactionID ?? '0', reportID, CONST.IOU.ACTION.SHARE, action.reportActionID); + createDraftTransactionAndNavigateToParticipantSelector(transactionID, reportID, CONST.IOU.ACTION.SHARE, action.reportActionID); }, isMediumSized: true, }, @@ -703,11 +701,11 @@ function PureReportActionItem({ getOriginalMessage(action)?.type === CONST.IOU.REPORT_ACTION_TYPE.TRACK) ) { // There is no single iouReport for bill splits, so only 1:1 requests require an iouReportID - const iouReportID = getOriginalMessage(action)?.IOUReportID ? getOriginalMessage(action)?.IOUReportID?.toString() ?? '-1' : '-1'; + const iouReportID = getOriginalMessage(action)?.IOUReportID?.toString(); children = ( ); } else if (isReimbursementQueuedAction(action)) { const linkedReport = isChatThread(report) ? parentReport : report; - const submitterDisplayName = formatPhoneNumber(getDisplayNameOrDefault(personalDetails?.[linkedReport?.ownerAccountID ?? -1])); + const submitterDisplayName = formatPhoneNumber(getDisplayNameOrDefault(personalDetails?.[linkedReport?.ownerAccountID ?? CONST.DEFAULT_NUMBER_ID])); const paymentType = getOriginalMessage(action)?.paymentType ?? ''; children = ( @@ -1057,7 +1055,7 @@ function PureReportActionItem({ }; if (action.actionName === CONST.REPORT.ACTIONS.TYPE.CREATED) { - const transactionID = isMoneyRequestAction(parentReportActionForTransactionThread) ? getOriginalMessage(parentReportActionForTransactionThread)?.IOUTransactionID : '-1'; + const transactionID = isMoneyRequestAction(parentReportActionForTransactionThread) ? getOriginalMessage(parentReportActionForTransactionThread)?.IOUTransactionID : undefined; return ( 1; - const iouReportID = isMoneyRequestAction(action) && getOriginalMessage(action)?.IOUReportID ? (getOriginalMessage(action)?.IOUReportID ?? '').toString() : '-1'; + const iouReportID = isMoneyRequestAction(action) && getOriginalMessage(action)?.IOUReportID ? getOriginalMessage(action)?.IOUReportID?.toString() : undefined; const transactionsWithReceipts = getTransactionsWithReceipts(iouReportID); const isWhisper = whisperedTo.length > 0 && transactionsWithReceipts.length === 0; const whisperedToPersonalDetails = isWhisper - ? (Object.values(personalDetails ?? {}).filter((details) => whisperedTo.includes(details?.accountID ?? -1)) as OnyxTypes.PersonalDetails[]) + ? (Object.values(personalDetails ?? {}).filter((details) => whisperedTo.includes(details?.accountID ?? CONST.DEFAULT_NUMBER_ID)) as OnyxTypes.PersonalDetails[]) : []; const isWhisperOnlyVisibleByUser = isWhisper && isCurrentUserTheOnlyParticipant(whisperedTo); const displayNamesWithTooltips = isWhisper ? getDisplayNamesWithTooltips(whisperedToPersonalDetails, isMultipleParticipant) : []; diff --git a/src/pages/home/report/ReportActionItemContentCreated.tsx b/src/pages/home/report/ReportActionItemContentCreated.tsx index 80867a9be95b..7c0016b56338 100644 --- a/src/pages/home/report/ReportActionItemContentCreated.tsx +++ b/src/pages/home/report/ReportActionItemContentCreated.tsx @@ -15,7 +15,7 @@ import UnreadActionIndicator from '@components/UnreadActionIndicator'; import useLocalize from '@hooks/useLocalize'; import usePolicy from '@hooks/usePolicy'; import useThemeStyles from '@hooks/useThemeStyles'; -import {isMessageDeleted, isReversedTransaction, isTransactionThread} from '@libs/ReportActionsUtils'; +import {isMessageDeleted, isReversedTransaction as isReversedTransactionReportActionsUtils, isTransactionThread} from '@libs/ReportActionsUtils'; import {isCanceledTaskReport, isExpenseReport, isInvoiceReport, isIOUReport, isTaskReport} from '@libs/ReportUtils'; import {getCurrency} from '@libs/TransactionUtils'; import CONST from '@src/CONST'; @@ -29,10 +29,7 @@ import ReportActionItemSingle from './ReportActionItemSingle'; type ReportActionItemContentCreatedProps = { /** The context value containing the report and action data, along with the show context menu props */ - contextValue: ShowContextMenuContextProps & { - report: OnyxTypes.Report; - action: OnyxTypes.ReportAction; - }; + contextValue: ShowContextMenuContextProps; /** Report action belonging to the report's parent */ parentReportAction: OnyxEntry; @@ -52,8 +49,8 @@ function ReportActionItemContentCreated({contextValue, parentReportAction, trans const {translate} = useLocalize(); const {report, action, transactionThreadReport} = contextValue; - const policy = usePolicy(report.policyID === CONST.POLICY.OWNER_EMAIL_FAKE ? undefined : report.policyID); - const [transaction] = useOnyx(`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID ?? CONST.DEFAULT_NUMBER_ID}`); + const policy = usePolicy(report?.policyID === CONST.POLICY.OWNER_EMAIL_FAKE ? undefined : report?.policyID); + const [transaction] = useOnyx(`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`); const transactionCurrency = getCurrency(transaction); @@ -61,7 +58,7 @@ function ReportActionItemContentCreated({contextValue, parentReportAction, trans () => shouldHideThreadDividerLine ? ( ) : ( @@ -70,18 +67,18 @@ function ReportActionItemContentCreated({contextValue, parentReportAction, trans style={[!shouldHideThreadDividerLine ? styles.reportHorizontalRule : {}]} /> ), - [shouldHideThreadDividerLine, report.reportID, styles.reportHorizontalRule], + [shouldHideThreadDividerLine, report?.reportID, styles.reportHorizontalRule], ); const contextMenuValue = useMemo(() => ({...contextValue, isDisabled: true}), [contextValue]); if (isTransactionThread(parentReportAction)) { - const isTransactionReversed = isReversedTransaction(parentReportAction); + const isReversedTransaction = isReversedTransactionReportActionsUtils(parentReportAction); - if (isMessageDeleted(parentReportAction) || isTransactionReversed) { + if (isMessageDeleted(parentReportAction) || isReversedTransaction) { let message: TranslationPaths; - if (isTransactionReversed) { + if (isReversedTransaction) { message = 'parentReportAction.reversedTransaction'; } else { message = 'parentReportAction.deletedExpense'; @@ -96,7 +93,7 @@ function ReportActionItemContentCreated({contextValue, parentReportAction, trans showHeader report={report} > - ${translate(message)}`} /> + ${translate(message)}`} /> @@ -105,7 +102,7 @@ function ReportActionItemContentCreated({contextValue, parentReportAction, trans } return ( - + + {!isEmptyObject(transactionThreadReport?.reportID) ? ( <> @@ -176,7 +173,7 @@ function ReportActionItemContentCreated({contextValue, parentReportAction, trans )} @@ -186,8 +183,8 @@ function ReportActionItemContentCreated({contextValue, parentReportAction, trans return ( ); } diff --git a/src/pages/home/report/ReportActionItemCreated.tsx b/src/pages/home/report/ReportActionItemCreated.tsx index 1adb24fa23a7..b5584c00087b 100644 --- a/src/pages/home/report/ReportActionItemCreated.tsx +++ b/src/pages/home/report/ReportActionItemCreated.tsx @@ -9,7 +9,7 @@ import useLocalize from '@hooks/useLocalize'; import useResponsiveLayout from '@hooks/useResponsiveLayout'; import useThemeStyles from '@hooks/useThemeStyles'; import Navigation from '@libs/Navigation/Navigation'; -import * as ReportUtils from '@libs/ReportUtils'; +import {getIcons, isChatReport, isCurrentUserInvoiceReceiver, isInvoiceRoom, navigateToDetailsPage, shouldDisableDetailPage as shouldDisableDetailPageReportUtils} from '@libs/ReportUtils'; import {navigateToConciergeChatAndDeleteReport} from '@userActions/Report'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; @@ -17,7 +17,7 @@ import AnimatedEmptyStateBackground from './AnimatedEmptyStateBackground'; type ReportActionItemCreatedProps = { /** The id of the report */ - reportID: string; + reportID: string | undefined; /** The id of the policy */ // eslint-disable-next-line react/no-unused-prop-types @@ -31,16 +31,16 @@ function ReportActionItemCreated({reportID, policyID}: ReportActionItemCreatedPr const [personalDetails] = useOnyx(ONYXKEYS.PERSONAL_DETAILS_LIST); const [report] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`); const [policy] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY}${policyID}`); - const [invoiceReceiverPolicy] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY}${report?.invoiceReceiver && 'policyID' in report.invoiceReceiver ? report.invoiceReceiver.policyID : -1}`); + const [invoiceReceiverPolicy] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY}${report?.invoiceReceiver && 'policyID' in report.invoiceReceiver ? report.invoiceReceiver.policyID : undefined}`); - if (!ReportUtils.isChatReport(report)) { + if (!isChatReport(report)) { return null; } - let icons = ReportUtils.getIcons(report, personalDetails, null, '', -1, policy, invoiceReceiverPolicy); - const shouldDisableDetailPage = ReportUtils.shouldDisableDetailPage(report); + let icons = getIcons(report, personalDetails, null, '', -1, policy, invoiceReceiverPolicy); + const shouldDisableDetailPage = shouldDisableDetailPageReportUtils(report); - if (ReportUtils.isInvoiceRoom(report) && ReportUtils.isCurrentUserInvoiceReceiver(report)) { + if (isInvoiceRoom(report) && isCurrentUserInvoiceReceiver(report)) { icons = [...icons].reverse(); } @@ -59,7 +59,7 @@ function ReportActionItemCreated({reportID, policyID}: ReportActionItemCreatedPr > ReportUtils.navigateToDetailsPage(report, Navigation.getReportRHPActiveRoute())} + onPress={() => navigateToDetailsPage(report, Navigation.getReportRHPActiveRoute())} style={[styles.mh5, styles.mb3, styles.alignSelfStart, shouldDisableDetailPage && styles.cursorDefault]} accessibilityLabel={translate('common.details')} role={CONST.ROLE.BUTTON} diff --git a/src/pages/home/report/ReportActionItemMessage.tsx b/src/pages/home/report/ReportActionItemMessage.tsx index 647c17f70d88..550f7d81cdf3 100644 --- a/src/pages/home/report/ReportActionItemMessage.tsx +++ b/src/pages/home/report/ReportActionItemMessage.tsx @@ -8,8 +8,20 @@ import Text from '@components/Text'; import useLocalize from '@hooks/useLocalize'; import useThemeStyles from '@hooks/useThemeStyles'; import Navigation from '@libs/Navigation/Navigation'; -import * as ReportActionsUtils from '@libs/ReportActionsUtils'; -import * as ReportUtils from '@libs/ReportUtils'; +import { + getLinkedTransactionID, + getMemberChangeMessageFragment, + getOriginalMessage, + getReportActionMessage, + getReportActionMessageFragments, + getUpdateRoomDescriptionFragment, + isAddCommentAction, + isApprovedOrSubmittedReportAction as isApprovedOrSubmittedReportActionUtils, + isMemberChangeAction, + isMoneyRequestAction, + isThreadParentMessage, +} from '@libs/ReportActionsUtils'; +import {getIOUReportActionDisplayMessage, hasMissingInvoiceBankAccount, isSettled} from '@libs/ReportUtils'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import ROUTES from '@src/ROUTES'; @@ -31,20 +43,20 @@ type ReportActionItemMessageProps = { isHidden?: boolean; /** The ID of the report */ - reportID: string; + reportID: string | undefined; }; function ReportActionItemMessage({action, displayAsGroup, reportID, style, isHidden = false}: ReportActionItemMessageProps) { const styles = useThemeStyles(); const {translate} = useLocalize(); const [report] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`); - const [transaction] = useOnyx(`${ONYXKEYS.COLLECTION.TRANSACTION}${ReportActionsUtils.getLinkedTransactionID(action) ?? -1}`); + const [transaction] = useOnyx(`${ONYXKEYS.COLLECTION.TRANSACTION}${getLinkedTransactionID(action)}`); - const fragments = ReportActionsUtils.getReportActionMessageFragments(action); - const isIOUReport = ReportActionsUtils.isMoneyRequestAction(action); + const fragments = getReportActionMessageFragments(action); + const isIOUReport = isMoneyRequestAction(action); - if (ReportActionsUtils.isMemberChangeAction(action)) { - const fragment = ReportActionsUtils.getMemberChangeMessageFragment(action); + if (isMemberChangeAction(action)) { + const fragment = getMemberChangeMessageFragment(action); return ( @@ -60,7 +72,7 @@ function ReportActionItemMessage({action, displayAsGroup, reportID, style, isHid } if (action.actionName === CONST.REPORT.ACTIONS.TYPE.ROOM_CHANGE_LOG.UPDATE_ROOM_DESCRIPTION) { - const fragment = ReportActionsUtils.getUpdateRoomDescriptionFragment(action); + const fragment = getUpdateRoomDescriptionFragment(action); return ( type === action.actionName); @@ -99,11 +111,11 @@ function ReportActionItemMessage({action, displayAsGroup, reportID, style, isHid key={`actionFragment-${action.reportActionID}-${index}`} fragment={fragment} iouMessage={iouMessage} - isThreadParentMessage={ReportActionsUtils.isThreadParentMessage(action, reportID)} + isThreadParentMessage={isThreadParentMessage(action, reportID)} pendingAction={action.pendingAction} actionName={action.actionName} - source={ReportActionsUtils.isAddCommentAction(action) ? ReportActionsUtils.getOriginalMessage(action)?.source : ''} - accountID={action.actorAccountID ?? -1} + source={isAddCommentAction(action) ? getOriginalMessage(action)?.source : ''} + accountID={action.actorAccountID ?? CONST.DEFAULT_NUMBER_ID} style={style} displayAsGroup={displayAsGroup} isApprovedOrSubmittedReportAction={isApprovedOrSubmittedReportAction} @@ -113,7 +125,7 @@ function ReportActionItemMessage({action, displayAsGroup, reportID, style, isHid // to decide if the fragment should be from left to right for RTL display names e.g. Arabic for proper // formatting. isFragmentContainingDisplayName={index === 0} - moderationDecision={ReportActionsUtils.getReportActionMessage(action)?.moderationDecision?.decision} + moderationDecision={getReportActionMessage(action)?.moderationDecision?.decision} /> )); @@ -132,7 +144,7 @@ function ReportActionItemMessage({action, displayAsGroup, reportID, style, isHid Navigation.navigate(ROUTES.WORKSPACE_INVOICES.getRoute(policyID)); }; - const shouldShowAddBankAccountButton = action.actionName === CONST.REPORT.ACTIONS.TYPE.IOU && ReportUtils.hasMissingInvoiceBankAccount(reportID) && !ReportUtils.isSettled(reportID); + const shouldShowAddBankAccountButton = action.actionName === CONST.REPORT.ACTIONS.TYPE.IOU && hasMissingInvoiceBankAccount(reportID) && !isSettled(reportID); return ( diff --git a/src/pages/home/report/ReportActionItemMessageEdit.tsx b/src/pages/home/report/ReportActionItemMessageEdit.tsx index 1862e2b96596..628c50a8a5a5 100644 --- a/src/pages/home/report/ReportActionItemMessageEdit.tsx +++ b/src/pages/home/report/ReportActionItemMessageEdit.tsx @@ -60,7 +60,7 @@ type ReportActionItemMessageEditProps = { draftMessage: string; /** ReportID that holds the comment we're editing */ - reportID: string; + reportID: string | undefined; /** PolicyID of the policy the report belongs to */ policyID?: string;