diff --git a/.eslintrc.changed.js b/.eslintrc.changed.js index 55472b10ea86..16c414ee6767 100644 --- a/.eslintrc.changed.js +++ b/.eslintrc.changed.js @@ -11,7 +11,6 @@ module.exports = { overrides: [ { files: [ - 'src/libs/actions/IOU.ts', 'src/libs/actions/Report.ts', 'src/libs/actions/Task.ts', 'src/libs/OptionsListUtils.ts', diff --git a/src/ROUTES.ts b/src/ROUTES.ts index 7f8b75f353e1..a907c511615e 100644 --- a/src/ROUTES.ts +++ b/src/ROUTES.ts @@ -423,7 +423,10 @@ const ROUTES = { }, ROOM_INVITE: { route: 'r/:reportID/invite/:role?', - getRoute: (reportID: string, role?: string, backTo?: string) => { + getRoute: (reportID: string | undefined, role?: string, backTo?: string) => { + if (!reportID) { + Log.warn('Invalid reportID is used to build the ROOM_INVITE route'); + } const route = role ? (`r/${reportID}/invite/${role}` as const) : (`r/${reportID}/invite` as const); return getUrlWithBackToParam(route, backTo); }, @@ -748,7 +751,12 @@ const ROUTES = { }, WORKSPACE_PROFILE_ADDRESS: { route: 'settings/workspaces/:policyID/profile/address', - getRoute: (policyID: string, backTo?: string) => getUrlWithBackToParam(`settings/workspaces/${policyID}/profile/address` as const, backTo), + getRoute: (policyID: string | undefined, backTo?: string) => { + if (!policyID) { + Log.warn('Invalid policyID is used to build the WORKSPACE_PROFILE_ADDRESS route'); + } + return getUrlWithBackToParam(`settings/workspaces/${policyID}/profile/address` as const, backTo); + }, }, WORKSPACE_PROFILE_PLAN: { route: 'settings/workspaces/:policyID/profile/plan', diff --git a/src/libs/API/parameters/CategorizeTrackedExpenseParams.ts b/src/libs/API/parameters/CategorizeTrackedExpenseParams.ts index 78eb0adecc5e..7186ae131b83 100644 --- a/src/libs/API/parameters/CategorizeTrackedExpenseParams.ts +++ b/src/libs/API/parameters/CategorizeTrackedExpenseParams.ts @@ -6,14 +6,14 @@ type CategorizeTrackedExpenseParams = { comment: string; created: string; merchant: string; - policyID: string; - transactionID: string; - moneyRequestPreviewReportActionID: string; - moneyRequestReportID: string; - moneyRequestCreatedReportActionID: string; + policyID: string | undefined; + transactionID: string | undefined; + moneyRequestPreviewReportActionID: string | undefined; + moneyRequestReportID: string | undefined; + moneyRequestCreatedReportActionID: string | undefined; actionableWhisperReportActionID: string; modifiedExpenseReportActionID: string; - reportPreviewReportActionID: string; + reportPreviewReportActionID: string | undefined; category?: string; tag?: string; receipt?: Receipt; diff --git a/src/libs/API/parameters/CompleteSplitBillParams.ts b/src/libs/API/parameters/CompleteSplitBillParams.ts index 67ca011b70d9..123ee7b05257 100644 --- a/src/libs/API/parameters/CompleteSplitBillParams.ts +++ b/src/libs/API/parameters/CompleteSplitBillParams.ts @@ -1,5 +1,5 @@ type CompleteSplitBillParams = { - transactionID: string; + transactionID: string | undefined; amount?: number; currency?: string; created?: string; diff --git a/src/libs/API/parameters/ConvertTrackedExpenseToRequestParams.ts b/src/libs/API/parameters/ConvertTrackedExpenseToRequestParams.ts index 2942923f6b37..a6e643e851cb 100644 --- a/src/libs/API/parameters/ConvertTrackedExpenseToRequestParams.ts +++ b/src/libs/API/parameters/ConvertTrackedExpenseToRequestParams.ts @@ -8,9 +8,9 @@ type ConvertTrackedExpenseToRequestParams = { chatReportID: string; transactionID: string; actionableWhisperReportActionID: string; - createdChatReportActionID: string; + createdChatReportActionID: string | undefined; moneyRequestReportID: string; - moneyRequestCreatedReportActionID: string; + moneyRequestCreatedReportActionID: string | undefined; moneyRequestPreviewReportActionID: string; reportPreviewReportActionID: string; }; diff --git a/src/libs/API/parameters/CreateDistanceRequestParams.ts b/src/libs/API/parameters/CreateDistanceRequestParams.ts index 07dd594d7356..108707b71dff 100644 --- a/src/libs/API/parameters/CreateDistanceRequestParams.ts +++ b/src/libs/API/parameters/CreateDistanceRequestParams.ts @@ -1,7 +1,7 @@ type CreateDistanceRequestParams = { transactionID: string; chatReportID: string; - createdChatReportActionID: string; + createdChatReportActionID: string | undefined; reportActionID: string; waypoints: string; customUnitRateID: string; diff --git a/src/libs/API/parameters/DeleteMoneyRequestParams.ts b/src/libs/API/parameters/DeleteMoneyRequestParams.ts index 6e7fe30811c4..b44223905e8c 100644 --- a/src/libs/API/parameters/DeleteMoneyRequestParams.ts +++ b/src/libs/API/parameters/DeleteMoneyRequestParams.ts @@ -1,5 +1,5 @@ type DeleteMoneyRequestParams = { - transactionID: string; + transactionID: string | undefined; reportActionID: string; }; diff --git a/src/libs/API/parameters/PayInvoiceParams.ts b/src/libs/API/parameters/PayInvoiceParams.ts index 7f80e5d20c4c..aaf1d906d143 100644 --- a/src/libs/API/parameters/PayInvoiceParams.ts +++ b/src/libs/API/parameters/PayInvoiceParams.ts @@ -2,7 +2,7 @@ import type {PaymentMethodType} from '@src/types/onyx/OriginalMessage'; import type CreateWorkspaceParams from './CreateWorkspaceParams'; type PayInvoiceParams = Partial & { - reportID: string; + reportID: string | undefined; reportActionID: string; paymentMethodType: PaymentMethodType; payAsBusiness: boolean; diff --git a/src/libs/API/parameters/PayMoneyRequestParams.ts b/src/libs/API/parameters/PayMoneyRequestParams.ts index 3ad98429b75c..337c38d7164e 100644 --- a/src/libs/API/parameters/PayMoneyRequestParams.ts +++ b/src/libs/API/parameters/PayMoneyRequestParams.ts @@ -1,7 +1,7 @@ import type {PaymentMethodType} from '@src/types/onyx/OriginalMessage'; type PayMoneyRequestParams = { - iouReportID: string; + iouReportID: string | undefined; chatReportID: string; reportActionID: string; paymentMethodType: PaymentMethodType; diff --git a/src/libs/API/parameters/RequestMoneyParams.ts b/src/libs/API/parameters/RequestMoneyParams.ts index e3e600a4e367..8ce1aaa97cc0 100644 --- a/src/libs/API/parameters/RequestMoneyParams.ts +++ b/src/libs/API/parameters/RequestMoneyParams.ts @@ -14,8 +14,8 @@ type RequestMoneyParams = { chatReportID: string; transactionID: string; reportActionID: string; - createdChatReportActionID: string; - createdIOUReportActionID: string; + createdChatReportActionID: string | undefined; + createdIOUReportActionID: string | undefined; reportPreviewReportActionID: string; receipt?: Receipt; receiptState?: ValueOf; @@ -26,7 +26,7 @@ type RequestMoneyParams = { billable?: boolean; receiptGpsPoints?: string; transactionThreadReportID: string; - createdReportActionIDForThread: string; + createdReportActionIDForThread: string | undefined; reimbursible?: boolean; }; diff --git a/src/libs/API/parameters/SendInvoiceParams.ts b/src/libs/API/parameters/SendInvoiceParams.ts index e2cac84e0d12..2b172ee6ce6d 100644 --- a/src/libs/API/parameters/SendInvoiceParams.ts +++ b/src/libs/API/parameters/SendInvoiceParams.ts @@ -2,7 +2,7 @@ import type {RequireAtLeastOne} from 'type-fest'; type SendInvoiceParams = RequireAtLeastOne< { - senderWorkspaceID: string; + senderWorkspaceID: string | undefined; accountID: number; receiverEmail?: string; receiverInvoiceRoomID?: string; @@ -21,7 +21,7 @@ type SendInvoiceParams = RequireAtLeastOne< companyName?: string; companyWebsite?: string; createdIOUReportActionID: string; - createdReportActionIDForThread: string; + createdReportActionIDForThread: string | undefined; reportActionID: string; }, 'receiverEmail' | 'receiverInvoiceRoomID' diff --git a/src/libs/API/parameters/SendMoneyParams.ts b/src/libs/API/parameters/SendMoneyParams.ts index 449a87fb5313..1e9a58ab74a5 100644 --- a/src/libs/API/parameters/SendMoneyParams.ts +++ b/src/libs/API/parameters/SendMoneyParams.ts @@ -7,11 +7,11 @@ type SendMoneyParams = { paymentMethodType: PaymentMethodType; transactionID: string; newIOUReportDetails: string; - createdReportActionID: string; + createdReportActionID: string | undefined; reportPreviewReportActionID: string; createdIOUReportActionID: string; transactionThreadReportID: string; - createdReportActionIDForThread: string; + createdReportActionIDForThread: string | undefined; }; export default SendMoneyParams; diff --git a/src/libs/API/parameters/ShareTrackedExpenseParams.ts b/src/libs/API/parameters/ShareTrackedExpenseParams.ts index cee4bc40d9ac..ba69b5410968 100644 --- a/src/libs/API/parameters/ShareTrackedExpenseParams.ts +++ b/src/libs/API/parameters/ShareTrackedExpenseParams.ts @@ -6,14 +6,14 @@ type ShareTrackedExpenseParams = { comment: string; created: string; merchant: string; - policyID: string; - transactionID: string; - moneyRequestPreviewReportActionID: string; - moneyRequestReportID: string; - moneyRequestCreatedReportActionID: string; + policyID: string | undefined; + transactionID: string | undefined; + moneyRequestPreviewReportActionID: string | undefined; + moneyRequestReportID: string | undefined; + moneyRequestCreatedReportActionID: string | undefined; actionableWhisperReportActionID: string; modifiedExpenseReportActionID: string; - reportPreviewReportActionID: string; + reportPreviewReportActionID: string | undefined; category?: string; tag?: string; receipt?: Receipt; diff --git a/src/libs/API/parameters/TrackExpenseParams.ts b/src/libs/API/parameters/TrackExpenseParams.ts index 3a7d0df6736c..f3f2cc539967 100644 --- a/src/libs/API/parameters/TrackExpenseParams.ts +++ b/src/libs/API/parameters/TrackExpenseParams.ts @@ -9,10 +9,10 @@ type TrackExpenseParams = { created: string; merchant: string; iouReportID?: string; - chatReportID: string; - transactionID: string; - reportActionID: string; - createdChatReportActionID: string; + chatReportID: string | undefined; + transactionID: string | undefined; + reportActionID: string | undefined; + createdChatReportActionID: string | undefined; createdIOUReportActionID?: string; reportPreviewReportActionID?: string; receipt?: Receipt; @@ -23,8 +23,8 @@ type TrackExpenseParams = { taxAmount: number; billable?: boolean; receiptGpsPoints?: string; - transactionThreadReportID: string; - createdReportActionIDForThread: string; + transactionThreadReportID: string | undefined; + createdReportActionIDForThread: string | undefined; waypoints?: string; actionableWhisperReportActionID?: string; customUnitRateID?: string; diff --git a/src/libs/ReportUtils.ts b/src/libs/ReportUtils.ts index 67e0828f5c61..df817d145de7 100644 --- a/src/libs/ReportUtils.ts +++ b/src/libs/ReportUtils.ts @@ -677,7 +677,7 @@ Onyx.connect({ reportsTransactions = Object.values(value).reduce>((all, transaction) => { const reportsMap = all; - if (!transaction) { + if (!transaction?.reportID) { return reportsMap; } @@ -3074,6 +3074,10 @@ function getReportFieldKey(reportFieldId: string | undefined) { * Get the report fields attached to the policy given policyID */ function getReportFieldsByPolicyID(policyID: string | undefined): Record { + if (!policyID) { + return {}; + } + const policyReportFields = Object.entries(allPolicies ?? {}).find(([key]) => key.replace(ONYXKEYS.COLLECTION.POLICY, '') === policyID); const fieldList = policyReportFields?.[1]?.fieldList; @@ -4673,7 +4677,7 @@ function buildOptimisticIOUReport( payeeAccountID: number, payerAccountID: number, total: number, - chatReportID: string, + chatReportID: string | undefined, currency: string, isSendingMoney = false, parentReportActionID?: string, @@ -4745,7 +4749,14 @@ function populateOptimisticReportFormula(formula: string, report: OptimisticExpe } /** Builds an optimistic invoice report with a randomly generated reportID */ -function buildOptimisticInvoiceReport(chatReportID: string, policyID: string, receiverAccountID: number, receiverName: string, total: number, currency: string): OptimisticExpenseReport { +function buildOptimisticInvoiceReport( + chatReportID: string, + policyID: string | undefined, + receiverAccountID: number, + receiverName: string, + total: number, + currency: string, +): OptimisticExpenseReport { const formattedTotal = CurrencyUtils.convertToDisplayString(total, currency); const invoiceReport = { reportID: generateReportID(), @@ -4817,8 +4828,8 @@ function getExpenseReportStateAndStatus(policy: OnyxEntry) { * @param parentReportActionID – The parent ReportActionID of the PolicyExpenseChat */ function buildOptimisticExpenseReport( - chatReportID: string, - policyID: string, + chatReportID: string | undefined, + policyID: string | undefined, payeeAccountID: number, total: number, currency: string, @@ -5411,7 +5422,7 @@ function buildOptimisticModifiedExpenseReportAction( * @param transactionThreadID - The reportID of the transaction thread * @param movedToReportID - The reportID of the report the transaction is moved to */ -function buildOptimisticMovedTrackedExpenseModifiedReportAction(transactionThreadID: string, movedToReportID: string): OptimisticModifiedExpenseReportAction { +function buildOptimisticMovedTrackedExpenseModifiedReportAction(transactionThreadID: string | undefined, movedToReportID: string | undefined): OptimisticModifiedExpenseReportAction { const delegateAccountDetails = PersonalDetailsUtils.getPersonalDetailByEmail(delegateEmail); return { @@ -8440,10 +8451,6 @@ function canReportBeMentionedWithinPolicy(report: OnyxEntry, policyID: s return isChatRoom(report) && !isInvoiceRoom(report) && !isThread(report); } -function shouldShowMerchantColumn(transactions: Transaction[]) { - return transactions.some((transaction) => isExpenseReport(allReports?.[transaction.reportID] ?? null)); -} - /** * Whether a given report is used for onboarding tasks. In the past, it could be either the Concierge chat or the system * DM, and we saved the report ID in the user's `onboarding` NVP. As a fallback for users who don't have the NVP, we now @@ -8972,7 +8979,6 @@ export { getTripIDFromTransactionParentReportID, buildOptimisticInvoiceReport, getInvoiceChatByParticipants, - shouldShowMerchantColumn, isCurrentUserInvoiceReceiver, isDraftReport, changeMoneyRequestHoldStatus, diff --git a/src/libs/TransactionUtils/index.ts b/src/libs/TransactionUtils/index.ts index 528481dae237..e95a0228ebcc 100644 --- a/src/libs/TransactionUtils/index.ts +++ b/src/libs/TransactionUtils/index.ts @@ -36,7 +36,7 @@ import getDistanceInMeters from './getDistanceInMeters'; type TransactionParams = { amount: number; currency: string; - reportID: string; + reportID: string | undefined; comment?: string; attendees?: Attendee[]; created?: string; diff --git a/src/libs/TripReservationUtils.ts b/src/libs/TripReservationUtils.ts index 2c774637b4a0..8604a5c38dff 100644 --- a/src/libs/TripReservationUtils.ts +++ b/src/libs/TripReservationUtils.ts @@ -65,7 +65,7 @@ function getTripReservationIcon(reservationType?: ReservationType): IconAsset { } } -type ReservationData = {reservation: Reservation; transactionID: string; reportID: string; reservationIndex: number}; +type ReservationData = {reservation: Reservation; transactionID: string; reportID: string | undefined; reservationIndex: number}; function getReservationsFromTripTransactions(transactions: Transaction[]): ReservationData[] { return transactions @@ -102,7 +102,7 @@ function bookATrip(translate: LocaleContextProps['translate'], setCtaErrorMessag } const policy = PolicyUtils.getPolicy(activePolicyID); if (isEmptyObject(policy?.address)) { - Navigation.navigate(ROUTES.WORKSPACE_PROFILE_ADDRESS.getRoute(activePolicyID ?? '-1', Navigation.getActiveRoute())); + Navigation.navigate(ROUTES.WORKSPACE_PROFILE_ADDRESS.getRoute(activePolicyID, Navigation.getActiveRoute())); return; } if (!travelSettings?.hasAcceptedTerms) { diff --git a/src/libs/actions/IOU.ts b/src/libs/actions/IOU.ts index 684d3fb23e5e..522bd5bae0be 100644 --- a/src/libs/actions/IOU.ts +++ b/src/libs/actions/IOU.ts @@ -92,11 +92,11 @@ type MoneyRequestInformation = { chatReport: OnyxTypes.Report; transaction: OnyxTypes.Transaction; iouAction: OptimisticIOUReportAction; - createdChatReportActionID: string; - createdIOUReportActionID: string; + createdChatReportActionID: string | undefined; + createdIOUReportActionID: string | undefined; reportPreviewAction: OnyxTypes.ReportAction; transactionThreadReportID: string; - createdReportActionIDForThread: string; + createdReportActionIDForThread: string | undefined; onyxData: OnyxData; }; @@ -106,16 +106,16 @@ type TrackExpenseInformation = { chatReport: OnyxTypes.Report; transaction: OnyxTypes.Transaction; iouAction: OptimisticIOUReportAction; - createdChatReportActionID: string; + createdChatReportActionID?: string; createdIOUReportActionID?: string; reportPreviewAction?: OnyxTypes.ReportAction; transactionThreadReportID: string; - createdReportActionIDForThread: string; + createdReportActionIDForThread: string | undefined; actionableWhisperReportActionIDParam?: string; onyxData: OnyxData; }; type CategorizeTrackedExpenseTransactionParams = { - transactionID: string; + transactionID: string | undefined; amount: number; currency: string; comment: string; @@ -129,18 +129,18 @@ type CategorizeTrackedExpenseTransactionParams = { receipt?: Receipt; }; type CategorizeTrackedExpensePolicyParams = { - policyID: string; + policyID: string | undefined; isDraftPolicy: boolean; }; type CategorizeTrackedExpenseReportInformation = { - moneyRequestPreviewReportActionID: string; - moneyRequestReportID: string; - moneyRequestCreatedReportActionID: string; + moneyRequestPreviewReportActionID: string | undefined; + moneyRequestReportID: string | undefined; + moneyRequestCreatedReportActionID: string | undefined; actionableWhisperReportActionID: string; linkedTrackedExpenseReportAction: OnyxTypes.ReportAction; linkedTrackedExpenseReportID: string; - transactionThreadReportID: string; - reportPreviewReportActionID: string; + transactionThreadReportID: string | undefined; + reportPreviewReportActionID: string | undefined; }; type CategorizeTrackedExpenseParams = { onyxData: OnyxData | undefined; @@ -150,7 +150,7 @@ type CategorizeTrackedExpenseParams = { createdWorkspaceParams?: CreateWorkspaceParams; }; type SendInvoiceInformation = { - senderWorkspaceID: string; + senderWorkspaceID: string | undefined; receiver: Partial; invoiceRoom: OnyxTypes.Report; createdChatReportActionID: string; @@ -159,7 +159,7 @@ type SendInvoiceInformation = { transactionID: string; transactionThreadReportID: string; createdIOUReportActionID: string; - createdReportActionIDForThread: string; + createdReportActionIDForThread: string | undefined; reportActionID: string; onyxData: OnyxData; }; @@ -391,7 +391,7 @@ Onyx.connect({ key: ONYXKEYS.SESSION, callback: (value) => { currentUserEmail = value?.email ?? ''; - userAccountID = value?.accountID ?? -1; + userAccountID = value?.accountID ?? CONST.DEFAULT_NUMBER_ID; }, }); @@ -452,7 +452,7 @@ Onyx.connect({ /** * Find the report preview action from given chat report and iou report */ -function getReportPreviewAction(chatReportID: string, iouReportID: string): OnyxInputValue> { +function getReportPreviewAction(chatReportID: string | undefined, iouReportID: string | undefined): OnyxInputValue> { const reportActions = allReportActions?.[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${chatReportID}`] ?? {}; // Find the report preview action from the chat report @@ -1300,14 +1300,18 @@ function buildOnyxDataForInvoice( key: `${ONYXKEYS.COLLECTION.REPORT}${transactionThreadReport.reportID}`, value: transactionThreadReport, }, - { + ]; + + if (transactionThreadCreatedReportAction?.reportActionID) { + optimisticData.push({ onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${transactionThreadReport.reportID}`, value: { - [transactionThreadCreatedReportAction?.reportActionID ?? '-1']: transactionThreadCreatedReportAction, + [transactionThreadCreatedReportAction.reportActionID]: transactionThreadCreatedReportAction, }, - }, - ]; + }); + } + const successData: OnyxUpdate[] = []; if (chatReport) { @@ -1443,17 +1447,20 @@ function buildOnyxDataForInvoice( }, }, }, - { + ); + + if (transactionThreadCreatedReportAction?.reportActionID) { + successData.push({ onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${transactionThreadReport.reportID}`, value: { - [transactionThreadCreatedReportAction?.reportActionID ?? '-1']: { + [transactionThreadCreatedReportAction.reportActionID]: { pendingAction: null, errors: null, }, }, - }, - ); + }); + } if (isNewChatReport) { successData.push( @@ -1537,16 +1544,19 @@ function buildOnyxDataForInvoice( }, }, }, - { + ]; + + if (transactionThreadCreatedReportAction?.reportActionID) { + failureData.push({ onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${transactionThreadReport.reportID}`, value: { - [transactionThreadCreatedReportAction?.reportActionID ?? '-1']: { + [transactionThreadCreatedReportAction.reportActionID]: { errors: ErrorUtils.getMicroSecondOnyxErrorWithTranslationKey('iou.error.genericCreateInvoiceFailureMessage', errorKey), }, }, - }, - ]; + }); + } if (companyName && companyWebsite) { optimisticData.push({ @@ -1957,16 +1967,19 @@ function buildOnyxDataForTrackExpense( pendingFields: clearedPendingFields, }, }, - { + ); + + if (transactionThreadCreatedReportAction?.reportActionID) { + failureData.push({ onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${transactionThreadReport?.reportID}`, value: { - [transactionThreadCreatedReportAction?.reportActionID ?? '-1']: { + [transactionThreadCreatedReportAction?.reportActionID]: { errors: ErrorUtils.getMicroSecondOnyxErrorWithTranslationKey('iou.error.genericCreateFailureMessage'), }, }, - }, - ); + }); + } // We don't need to compute violations unless we're on a paid policy if (!policy || !PolicyUtils.isPaidGroupPolicy(policy)) { @@ -2003,7 +2016,7 @@ function buildOnyxDataForTrackExpense( function getDeleteTrackExpenseInformation( chatReportID: string, - transactionID: string, + transactionID: string | undefined, reportAction: OnyxTypes.ReportAction, shouldDeleteTransactionFromOnyx = true, isMovingTransactionFromTrackExpense = false, @@ -2052,8 +2065,8 @@ function getDeleteTrackExpenseInformation( if (chatReport) { canUserPerformWriteAction = !!ReportUtils.canUserPerformWriteAction(chatReport); } - const lastVisibleAction = ReportActionsUtils.getLastVisibleAction(chatReport?.reportID ?? '-1', canUserPerformWriteAction, updatedReportAction); - const {lastMessageText = '', lastMessageHtml = ''} = ReportActionsUtils.getLastVisibleMessage(chatReport?.reportID ?? '-1', canUserPerformWriteAction, updatedReportAction); + const lastVisibleAction = ReportActionsUtils.getLastVisibleAction(chatReportID, canUserPerformWriteAction, updatedReportAction); + const {lastMessageText = '', lastMessageHtml = ''} = ReportActionsUtils.getLastVisibleMessage(chatReportID, canUserPerformWriteAction, updatedReportAction); // STEP 4: Build Onyx data const optimisticData: OnyxUpdate[] = []; @@ -2238,9 +2251,9 @@ function getSendInvoiceInformation( ): SendInvoiceInformation { const {amount = 0, currency = '', created = '', merchant = '', category = '', tag = '', taxCode = '', taxAmount = 0, billable, comment, participants} = transaction ?? {}; const trimmedComment = (comment?.comment ?? '').trim(); - const senderWorkspaceID = participants?.find((participant) => participant?.isSender)?.policyID ?? '-1'; + const senderWorkspaceID = participants?.find((participant) => participant?.isSender)?.policyID; const receiverParticipant: Participant | InvoiceReceiver | undefined = participants?.find((participant) => participant?.accountID) ?? invoiceChatReport?.invoiceReceiver; - const receiverAccountID = receiverParticipant && 'accountID' in receiverParticipant && receiverParticipant.accountID ? receiverParticipant.accountID : -1; + const receiverAccountID = receiverParticipant && 'accountID' in receiverParticipant && receiverParticipant.accountID ? receiverParticipant.accountID : CONST.DEFAULT_NUMBER_ID; let receiver = ReportUtils.getPersonalDetailsForAccountID(receiverAccountID); let optimisticPersonalDetailListAction = {}; const receiverType = getReceiverType(receiverParticipant); @@ -2357,7 +2370,7 @@ function getSendInvoiceInformation( return { createdIOUReportActionID: optimisticCreatedActionForIOUReport.reportActionID, - createdReportActionIDForThread: optimisticCreatedActionForTransactionThread?.reportActionID ?? '-1', + createdReportActionIDForThread: optimisticCreatedActionForTransactionThread?.reportActionID, reportActionID: iouAction.reportActionID, senderWorkspaceID, receiver, @@ -2422,7 +2435,7 @@ function getMoneyRequestInformation(moneyRequestInformation: MoneyRequestInforma if (!iouReport || shouldCreateNewMoneyRequestReport) { iouReport = isPolicyExpenseChat - ? ReportUtils.buildOptimisticExpenseReport(chatReport.reportID, chatReport.policyID ?? '-1', payeeAccountID, amount, currency) + ? ReportUtils.buildOptimisticExpenseReport(chatReport.reportID, chatReport.policyID, payeeAccountID, amount, currency) : ReportUtils.buildOptimisticIOUReport(payeeAccountID, payerAccountID, amount, chatReport.reportID, currency); } else if (isPolicyExpenseChat) { iouReport = {...iouReport}; @@ -2576,11 +2589,11 @@ function getMoneyRequestInformation(moneyRequestInformation: MoneyRequestInforma chatReport, transaction: optimisticTransaction, iouAction, - createdChatReportActionID: isNewChatReport ? optimisticCreatedActionForChat.reportActionID : '-1', - createdIOUReportActionID: shouldCreateNewMoneyRequestReport ? optimisticCreatedActionForIOUReport.reportActionID : '-1', + createdChatReportActionID: isNewChatReport ? optimisticCreatedActionForChat.reportActionID : undefined, + createdIOUReportActionID: shouldCreateNewMoneyRequestReport ? optimisticCreatedActionForIOUReport.reportActionID : undefined, reportPreviewAction, - transactionThreadReportID: optimisticTransactionThread?.reportID ?? '-1', - createdReportActionIDForThread: optimisticCreatedActionForTransactionThread?.reportActionID ?? '-1', + transactionThreadReportID: optimisticTransactionThread?.reportID, + createdReportActionIDForThread: optimisticCreatedActionForTransactionThread?.reportActionID, onyxData: { optimisticData, successData, @@ -2665,7 +2678,7 @@ function getTrackExpenseInformation( shouldCreateNewMoneyRequestReport = ReportUtils.shouldCreateNewMoneyRequestReport(iouReport, chatReport); if (!iouReport || shouldCreateNewMoneyRequestReport) { - iouReport = ReportUtils.buildOptimisticExpenseReport(chatReport.reportID, chatReport.policyID ?? '-1', payeeAccountID, amount, currency, amount); + iouReport = ReportUtils.buildOptimisticExpenseReport(chatReport.reportID, chatReport.policyID, payeeAccountID, amount, currency, amount); } else { iouReport = {...iouReport}; // Because of the Expense reports are stored as negative values, we subtract the total from the amount @@ -2706,7 +2719,7 @@ function getTrackExpenseInformation( transactionParams: { amount: ReportUtils.isExpenseReport(iouReport) ? -amount : amount, currency, - reportID: shouldUseMoneyReport && iouReport ? iouReport.reportID : '-1', + reportID: shouldUseMoneyReport && iouReport ? iouReport.reportID : undefined, comment, created, merchant, @@ -2797,12 +2810,11 @@ function getTrackExpenseInformation( iouReport: iouReport ?? undefined, transaction: optimisticTransaction, iouAction, - createdChatReportActionID: '-1', - createdIOUReportActionID: shouldCreateNewMoneyRequestReport ? optimisticCreatedActionForIOUReport.reportActionID : '-1', + createdIOUReportActionID: shouldCreateNewMoneyRequestReport ? optimisticCreatedActionForIOUReport.reportActionID : undefined, reportPreviewAction: reportPreviewAction ?? undefined, transactionThreadReportID: optimisticTransactionThread.reportID, - createdReportActionIDForThread: optimisticCreatedActionForTransactionThread?.reportActionID ?? '-1', - actionableWhisperReportActionIDParam: actionableTrackExpenseWhisper?.reportActionID ?? '', + createdReportActionIDForThread: optimisticCreatedActionForTransactionThread?.reportActionID, + actionableWhisperReportActionIDParam: actionableTrackExpenseWhisper?.reportActionID, onyxData: { optimisticData: optimisticData.concat(trackExpenseOnyxData[0]), successData: successData.concat(trackExpenseOnyxData[1]), @@ -3001,7 +3013,7 @@ function getUpdateMoneyRequestParams( } else { updatedMoneyRequestReport = IOUUtils.updateIOUOwnerAndTotal( iouReport, - updatedReportAction.actorAccountID ?? -1, + updatedReportAction.actorAccountID ?? CONST.DEFAULT_NUMBER_ID, diff, TransactionUtils.getCurrency(transaction), false, @@ -3048,30 +3060,33 @@ function getUpdateMoneyRequestParams( }); if (isScanning && ('amount' in transactionChanges || 'currency' in transactionChanges)) { - optimisticData.push( - { + if (transactionThread?.parentReportActionID) { + optimisticData.push({ onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${iouReport?.reportID}`, value: { - [transactionThread?.parentReportActionID ?? '-1']: { + [transactionThread?.parentReportActionID]: { originalMessage: { whisperedTo: [], }, }, }, - }, - { + }); + } + + if (iouReport?.parentReportActionID) { + optimisticData.push({ onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${iouReport?.parentReportID}`, value: { - [iouReport?.parentReportActionID ?? '-1']: { + [iouReport.parentReportActionID]: { originalMessage: { whisperedTo: [], }, }, }, - }, - ); + }); + } } // Update recently used categories if the category is changed @@ -3322,13 +3337,7 @@ function getUpdateTrackExpenseParams( optimisticData.push({ onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${chatReport?.reportID}`, - value: { - [transactionThread?.parentReportActionID ?? '-1']: { - originalMessage: { - whisperedTo: [], - }, - }, - }, + value: transactionThread?.parentReportActionID ? {[transactionThread.parentReportActionID]: {originalMessage: {whisperedTo: []}}} : {}, }); } @@ -3665,12 +3674,12 @@ function updateMoneyRequestDistanceRate( } const getConvertTrackedExpenseInformation = ( - transactionID: string, + transactionID: string | undefined, actionableWhisperReportActionID: string, - moneyRequestReportID: string, + moneyRequestReportID: string | undefined, linkedTrackedExpenseReportAction: OnyxTypes.ReportAction, linkedTrackedExpenseReportID: string, - transactionThreadReportID: string, + transactionThreadReportID: string | undefined, resolution: IOUAction, ) => { const optimisticData: OnyxUpdate[] = []; @@ -3725,9 +3734,9 @@ function convertTrackedExpenseToRequest( chatReportID: string, transactionID: string, actionableWhisperReportActionID: string, - createdChatReportActionID: string, + createdChatReportActionID: string | undefined, moneyRequestReportID: string, - moneyRequestCreatedReportActionID: string, + moneyRequestCreatedReportActionID: string | undefined, moneyRequestPreviewReportActionID: string, linkedTrackedExpenseReportAction: OnyxTypes.ReportAction, linkedTrackedExpenseReportID: string, @@ -3831,16 +3840,16 @@ function categorizeTrackedExpense(trackedExpenseParams: CategorizeTrackedExpense } function shareTrackedExpense( - policyID: string, - transactionID: string, - moneyRequestPreviewReportActionID: string, - moneyRequestReportID: string, - moneyRequestCreatedReportActionID: string, + policyID: string | undefined, + transactionID: string | undefined, + moneyRequestPreviewReportActionID: string | undefined, + moneyRequestReportID: string | undefined, + moneyRequestCreatedReportActionID: string | undefined, actionableWhisperReportActionID: string, linkedTrackedExpenseReportAction: OnyxTypes.ReportAction, linkedTrackedExpenseReportID: string, - transactionThreadReportID: string, - reportPreviewReportActionID: string, + transactionThreadReportID: string | undefined, + reportPreviewReportActionID: string | undefined, onyxData: OnyxData | undefined, amount: number, currency: string, @@ -4187,7 +4196,7 @@ function trackExpense( return; } const transactionParams: CategorizeTrackedExpenseTransactionParams = { - transactionID: transaction?.transactionID ?? '-1', + transactionID: transaction?.transactionID, amount, currency, comment, @@ -4201,18 +4210,18 @@ function trackExpense( receipt: trackedReceipt instanceof Blob ? trackedReceipt : undefined, }; const policyParams: CategorizeTrackedExpensePolicyParams = { - policyID: chatReport?.policyID ?? '-1', + policyID: chatReport?.policyID, isDraftPolicy, }; const reportInformation: CategorizeTrackedExpenseReportInformation = { - moneyRequestPreviewReportActionID: iouAction?.reportActionID ?? '-1', - moneyRequestReportID: iouReport?.reportID ?? '-1', - moneyRequestCreatedReportActionID: createdIOUReportActionID ?? '-1', + moneyRequestPreviewReportActionID: iouAction?.reportActionID, + moneyRequestReportID: iouReport?.reportID, + moneyRequestCreatedReportActionID: createdIOUReportActionID, actionableWhisperReportActionID, linkedTrackedExpenseReportAction, linkedTrackedExpenseReportID, - transactionThreadReportID: transactionThreadReportID ?? '-1', - reportPreviewReportActionID: reportPreviewAction?.reportActionID ?? '-1', + transactionThreadReportID, + reportPreviewReportActionID: reportPreviewAction?.reportActionID, }; const trackedExpenseParams: CategorizeTrackedExpenseParams = { onyxData, @@ -4230,16 +4239,16 @@ function trackExpense( return; } shareTrackedExpense( - chatReport?.policyID ?? '-1', - transaction?.transactionID ?? '-1', - iouAction?.reportActionID ?? '-1', - iouReport?.reportID ?? '-1', - createdIOUReportActionID ?? '-1', + chatReport?.policyID, + transaction?.transactionID, + iouAction?.reportActionID, + iouReport?.reportID, + createdIOUReportActionID, actionableWhisperReportActionID, linkedTrackedExpenseReportAction, linkedTrackedExpenseReportID, - transactionThreadReportID ?? '-1', - reportPreviewAction?.reportActionID ?? '-1', + transactionThreadReportID, + reportPreviewAction?.reportActionID, onyxData, amount, currency, @@ -4264,10 +4273,10 @@ function trackExpense( created, merchant, iouReportID: iouReport?.reportID, - chatReportID: chatReport?.reportID ?? '-1', - transactionID: transaction?.transactionID ?? '-1', - reportActionID: iouAction?.reportActionID ?? '-1', - createdChatReportActionID: createdChatReportActionID ?? '-1', + chatReportID: chatReport?.reportID, + transactionID: transaction?.transactionID, + reportActionID: iouAction?.reportActionID, + createdChatReportActionID, createdIOUReportActionID, reportPreviewReportActionID: reportPreviewAction?.reportActionID, receipt: trackedReceipt instanceof Blob ? trackedReceipt : undefined, @@ -4279,8 +4288,8 @@ function trackExpense( billable, // This needs to be a string of JSON because of limitations with the fetch() API and nested objects receiptGpsPoints: gpsPoints ? JSON.stringify(gpsPoints) : undefined, - transactionThreadReportID: transactionThreadReportID ?? '-1', - createdReportActionIDForThread: createdReportActionIDForThread ?? '-1', + transactionThreadReportID, + createdReportActionIDForThread, waypoints: validWaypoints ? JSON.stringify(sanitizeRecentWaypoints(validWaypoints)) : undefined, customUnitRateID, }; @@ -4298,15 +4307,15 @@ function trackExpense( Navigation.goBack(); Navigation.navigate(ROUTES.REPORT_WITH_ID.getRoute(activeReportID)); } - Navigation.setNavigationActionToMicrotaskQueue(() => Navigation.navigate(ROUTES.ROOM_INVITE.getRoute(activeReportID ?? '-1', CONST.IOU.SHARE.ROLE.ACCOUNTANT))); + Navigation.setNavigationActionToMicrotaskQueue(() => Navigation.navigate(ROUTES.ROOM_INVITE.getRoute(activeReportID, CONST.IOU.SHARE.ROLE.ACCOUNTANT))); } - Report.notifyNewAction(activeReportID ?? '', payeeAccountID); + Report.notifyNewAction(activeReportID, payeeAccountID); } function getOrCreateOptimisticSplitChatReport(existingSplitChatReportID: string, participants: Participant[], participantAccountIDs: number[], currentUserAccountID: number) { // The existing chat report could be passed as reportID or exist on the sole "participant" (in this case a report option) - const existingChatReportID = existingSplitChatReportID || (participants.at(0)?.reportID ?? '-1'); + const existingChatReportID = existingSplitChatReportID || participants.at(0)?.reportID; // Check if the report is available locally if we do have one let existingSplitChatReport = existingChatReportID ? allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${existingChatReportID}`] : null; @@ -4564,7 +4573,7 @@ function createSplitsAndOnyxData( participants.forEach((participant) => { // In a case when a participant is a workspace, even when a current user is not an owner of the workspace const isPolicyExpenseChat = ReportUtils.isPolicyExpenseChat(participant); - const splitAmount = splitShares?.[participant.accountID ?? -1]?.amount ?? IOUUtils.calculateAmount(participants.length, amount, currency, false); + const splitAmount = splitShares?.[participant.accountID ?? CONST.DEFAULT_NUMBER_ID]?.amount ?? IOUUtils.calculateAmount(participants.length, amount, currency, false); const splitTaxAmount = IOUUtils.calculateAmount(participants.length, taxAmount, currency, false); // To exclude someone from a split, the amount can be 0. The scenario for this is when creating a split from a group chat, we have remove the option to deselect users to exclude them. @@ -4609,7 +4618,7 @@ function createSplitsAndOnyxData( if (!oneOnOneIOUReport || shouldCreateNewOneOnOneIOUReport) { oneOnOneIOUReport = isOwnPolicyExpenseChat - ? ReportUtils.buildOptimisticExpenseReport(oneOnOneChatReport.reportID, oneOnOneChatReport.policyID ?? '-1', currentUserAccountID, splitAmount, currency) + ? 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 @@ -5160,7 +5169,7 @@ function startSplitBill({ return; } - const participantPersonalDetails = allPersonalDetails[participant?.accountID ?? -1]; + const participantPersonalDetails = allPersonalDetails[participant?.accountID ?? CONST.DEFAULT_NUMBER_ID]; if (!participantPersonalDetails) { optimisticData.push({ onyxMethod: Onyx.METHOD.MERGE, @@ -5255,7 +5264,7 @@ function startSplitBill({ API.write(WRITE_COMMANDS.START_SPLIT_BILL, parameters, {optimisticData, successData, failureData}); Navigation.dismissModalWithReport(splitChatReport); - Report.notifyNewAction(splitChatReport.reportID ?? '-1', currentUserAccountID); + Report.notifyNewAction(splitChatReport.reportID, currentUserAccountID); } /** Used for editing a split expense while it's still scanning or when SmartScan fails, it completes a split expense started by startSplitBill above. @@ -5268,7 +5277,7 @@ function startSplitBill({ */ function completeSplitBill(chatReportID: string, reportAction: OnyxTypes.ReportAction, updatedTransaction: OnyxEntry, sessionAccountID: number, sessionEmail: string) { const currentUserEmailForIOUSplit = PhoneNumber.addSMSDomainIfPhoneNumber(sessionEmail); - const transactionID = updatedTransaction?.transactionID ?? '-1'; + const transactionID = updatedTransaction?.transactionID; const unmodifiedTransaction = allTransactions[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`]; // Save optimistic updated transaction and action @@ -5351,7 +5360,7 @@ function completeSplitBill(chatReportID: string, reportAction: OnyxTypes.ReportA // In case this is still the optimistic accountID saved in the splits array, return early as we cannot know // if there is an existing chat between the split creator and this participant // Instead, we will rely on Auth generating the report IDs and the user won't see any optimistic chats or reports created - const participantPersonalDetails: OnyxTypes.PersonalDetails | null = allPersonalDetails[participant?.accountID ?? -1]; + const participantPersonalDetails: OnyxTypes.PersonalDetails | null = allPersonalDetails[participant?.accountID ?? CONST.DEFAULT_NUMBER_ID]; if (!participantPersonalDetails || participantPersonalDetails.isOptimisticPersonalDetail) { splits.push({ email: participant.email, @@ -5377,8 +5386,8 @@ function completeSplitBill(chatReportID: string, reportAction: OnyxTypes.ReportA if (!oneOnOneIOUReport || shouldCreateNewOneOnOneIOUReport) { oneOnOneIOUReport = isPolicyExpenseChat - ? ReportUtils.buildOptimisticExpenseReport(oneOnOneChatReport?.reportID ?? '-1', participant.policyID ?? '-1', sessionAccountID, splitAmount, currency ?? '') - : ReportUtils.buildOptimisticIOUReport(sessionAccountID, participant.accountID ?? -1, splitAmount, oneOnOneChatReport?.reportID ?? '-1', currency ?? ''); + ? ReportUtils.buildOptimisticExpenseReport(oneOnOneChatReport?.reportID, participant.policyID, sessionAccountID, splitAmount, currency ?? '') + : ReportUtils.buildOptimisticIOUReport(sessionAccountID, participant.accountID ?? CONST.DEFAULT_NUMBER_ID, splitAmount, oneOnOneChatReport?.reportID, currency ?? ''); } else if (isPolicyExpenseChat) { if (typeof oneOnOneIOUReport?.total === 'number') { // Because of the Expense reports are stored as negative values, we subtract the total from the amount @@ -5393,7 +5402,7 @@ function completeSplitBill(chatReportID: string, reportAction: OnyxTypes.ReportA transactionParams: { amount: isPolicyExpenseChat ? -splitAmount : splitAmount, currency: currency ?? '', - reportID: oneOnOneIOUReport?.reportID ?? '-1', + reportID: oneOnOneIOUReport?.reportID, comment: updatedTransaction?.comment?.comment, created: updatedTransaction?.modifiedCreated, merchant: updatedTransaction?.modifiedMerchant, @@ -5421,7 +5430,7 @@ function completeSplitBill(chatReportID: string, reportAction: OnyxTypes.ReportA undefined, ); - let oneOnOneReportPreviewAction = getReportPreviewAction(oneOnOneChatReport?.reportID ?? '-1', oneOnOneIOUReport?.reportID ?? '-1'); + let oneOnOneReportPreviewAction = getReportPreviewAction(oneOnOneChatReport?.reportID, oneOnOneIOUReport?.reportID); if (oneOnOneReportPreviewAction) { oneOnOneReportPreviewAction = ReportUtils.updateReportPreview(oneOnOneIOUReport, oneOnOneReportPreviewAction); } else { @@ -5571,7 +5580,7 @@ function createDistanceRequest(distanceRequestInformation: CreateDistanceRequest category ?? '', tag ?? '', splitShares, - report?.reportID ?? '', + report?.reportID, billable, CONST.IOU.REQUEST_TYPE.DISTANCE, taxCode, @@ -5584,7 +5593,7 @@ function createDistanceRequest(distanceRequestInformation: CreateDistanceRequest parameters = { transactionID: splitData.transactionID, chatReportID: splitData.chatReportID, - createdChatReportActionID: splitData.createdReportActionID ?? '', + createdChatReportActionID: splitData.createdReportActionID, reportActionID: splitData.reportActionID, waypoints: JSON.stringify(sanitizedWaypoints), customUnitRateID, @@ -5675,7 +5684,7 @@ function createDistanceRequest(distanceRequestInformation: CreateDistanceRequest API.write(WRITE_COMMANDS.CREATE_DISTANCE_REQUEST, parameters, onyxData); InteractionManager.runAfterInteractions(() => TransactionEdit.removeDraftTransaction(CONST.IOU.OPTIMISTIC_TRANSACTION_ID)); - const activeReportID = isMoneyRequestReport ? report?.reportID ?? '-1' : parameters.chatReportID; + const activeReportID = isMoneyRequestReport && report?.reportID ? report.reportID : parameters.chatReportID; Navigation.dismissModal(isSearchTopmostCentralPane() ? undefined : activeReportID); Report.notifyNewAction(activeReportID, userAccountID); } @@ -5730,11 +5739,10 @@ function updateMoneyRequestAmountAndCurrency({ */ function prepareToCleanUpMoneyRequest(transactionID: string, reportAction: OnyxTypes.ReportAction) { // STEP 1: Get all collections we're updating - const iouReportID = ReportActionsUtils.isMoneyRequestAction(reportAction) ? ReportActionsUtils.getOriginalMessage(reportAction)?.IOUReportID : '-1'; + const iouReportID = ReportActionsUtils.isMoneyRequestAction(reportAction) ? ReportActionsUtils.getOriginalMessage(reportAction)?.IOUReportID : undefined; const iouReport = allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${iouReportID}`] ?? null; const chatReport = allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${iouReport?.chatReportID}`]; - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - const reportPreviewAction = getReportPreviewAction(iouReport?.chatReportID ?? '-1', iouReport?.reportID ?? '-1')!; + const reportPreviewAction = getReportPreviewAction(iouReport?.chatReportID, iouReport?.reportID); const transaction = allTransactions[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`]; const isTransactionOnHold = TransactionUtils.isOnHold(transaction); const transactionViolations = allTransactionViolations[`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${transactionID}`]; @@ -5775,15 +5783,15 @@ function prepareToCleanUpMoneyRequest(transactionID: string, reportAction: OnyxT if (chatReport) { canUserPerformWriteAction = !!ReportUtils.canUserPerformWriteAction(chatReport); } - const lastVisibleAction = ReportActionsUtils.getLastVisibleAction(iouReport?.reportID ?? '-1', canUserPerformWriteAction, updatedReportAction); - const iouReportLastMessageText = ReportActionsUtils.getLastVisibleMessage(iouReport?.reportID ?? '-1', canUserPerformWriteAction, updatedReportAction).lastMessageText; + const lastVisibleAction = ReportActionsUtils.getLastVisibleAction(iouReport?.reportID, canUserPerformWriteAction, updatedReportAction); + const iouReportLastMessageText = ReportActionsUtils.getLastVisibleMessage(iouReport?.reportID, canUserPerformWriteAction, updatedReportAction).lastMessageText; const shouldDeleteIOUReport = iouReportLastMessageText.length === 0 && !ReportActionsUtils.isDeletedParentAction(lastVisibleAction) && (!transactionThreadID || shouldDeleteTransactionThread); // STEP 4: Update the iouReport and reportPreview with new totals and messages if it wasn't deleted let updatedIOUReport: OnyxInputValue; const currency = TransactionUtils.getCurrency(transaction); - const updatedReportPreviewAction: OnyxTypes.ReportAction = {...reportPreviewAction}; + const updatedReportPreviewAction: Partial> = {...reportPreviewAction}; updatedReportPreviewAction.pendingAction = shouldDeleteIOUReport ? CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE : CONST.RED_BRICK_ROAD_PENDING_ACTION.UPDATE; if (iouReport && ReportUtils.isExpenseReport(iouReport)) { updatedIOUReport = {...iouReport}; @@ -5810,7 +5818,7 @@ function prepareToCleanUpMoneyRequest(transactionID: string, reportAction: OnyxT } else { updatedIOUReport = IOUUtils.updateIOUOwnerAndTotal( iouReport, - reportAction.actorAccountID ?? -1, + reportAction.actorAccountID ?? CONST.DEFAULT_NUMBER_ID, TransactionUtils.getAmount(transaction, false), currency, true, @@ -5826,7 +5834,7 @@ function prepareToCleanUpMoneyRequest(transactionID: string, reportAction: OnyxT const hasNonReimbursableTransactions = ReportUtils.hasNonReimbursableTransactions(iouReport?.reportID); const messageText = Localize.translateLocal(hasNonReimbursableTransactions ? 'iou.payerSpentAmount' : 'iou.payerOwesAmount', { - payer: ReportUtils.getPersonalDetailsForAccountID(updatedIOUReport?.managerID ?? -1).login ?? '', + payer: ReportUtils.getPersonalDetailsForAccountID(updatedIOUReport?.managerID ?? CONST.DEFAULT_NUMBER_ID).login ?? '', amount: CurrencyUtils.convertToDisplayString(updatedIOUReport?.total, updatedIOUReport?.currency), }); @@ -6048,12 +6056,16 @@ function cleanUpMoneyRequest(transactionID: string, reportAction: OnyxTypes.Repo value: { hasOutstandingChildRequest: false, iouReportID: null, - lastMessageText: ReportActionsUtils.getLastVisibleMessage(iouReport?.chatReportID ?? '-1', canUserPerformWriteAction, { - [reportPreviewAction?.reportActionID ?? '-1']: null, - })?.lastMessageText, - lastVisibleActionCreated: ReportActionsUtils.getLastVisibleAction(iouReport?.chatReportID ?? '-1', canUserPerformWriteAction, { - [reportPreviewAction?.reportActionID ?? '-1']: null, - })?.created, + lastMessageText: ReportActionsUtils.getLastVisibleMessage( + iouReport?.chatReportID, + canUserPerformWriteAction, + reportPreviewAction?.reportActionID ? {[reportPreviewAction.reportActionID]: null} : {}, + )?.lastMessageText, + lastVisibleActionCreated: ReportActionsUtils.getLastVisibleAction( + iouReport?.chatReportID, + canUserPerformWriteAction, + reportPreviewAction?.reportActionID ? {[reportPreviewAction.reportActionID]: null} : {}, + )?.created, }, }, { @@ -6160,9 +6172,7 @@ function deleteMoneyRequest(transactionID: string | undefined, reportAction: Ony { onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${chatReport?.reportID}`, - value: { - [reportPreviewAction?.reportActionID ?? '-1']: updatedReportPreviewAction, - }, + value: reportPreviewAction?.reportActionID ? {[reportPreviewAction.reportActionID]: updatedReportPreviewAction} : {}, }, { onyxMethod: Onyx.METHOD.MERGE, @@ -6192,11 +6202,16 @@ function deleteMoneyRequest(transactionID: string | undefined, reportAction: Ony value: { hasOutstandingChildRequest: false, iouReportID: null, - lastMessageText: ReportActionsUtils.getLastVisibleMessage(iouReport?.chatReportID ?? '-1', canUserPerformWriteAction, {[reportPreviewAction?.reportActionID ?? '-1']: null}) - ?.lastMessageText, - lastVisibleActionCreated: ReportActionsUtils.getLastVisibleAction(iouReport?.chatReportID ?? '-1', canUserPerformWriteAction, { - [reportPreviewAction?.reportActionID ?? '-1']: null, - })?.created, + lastMessageText: ReportActionsUtils.getLastVisibleMessage( + iouReport?.chatReportID, + canUserPerformWriteAction, + reportPreviewAction?.reportActionID ? {[reportPreviewAction.reportActionID]: null} : {}, + )?.lastMessageText, + lastVisibleActionCreated: ReportActionsUtils.getLastVisibleAction( + iouReport?.chatReportID, + canUserPerformWriteAction, + reportPreviewAction?.reportActionID ? {[reportPreviewAction.reportActionID]: null} : {}, + )?.created, }, }); optimisticData.push({ @@ -6225,12 +6240,14 @@ function deleteMoneyRequest(transactionID: string | undefined, reportAction: Ony { onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${chatReport?.reportID}`, - value: { - [reportPreviewAction?.reportActionID ?? '-1']: { - pendingAction: null, - errors: null, - }, - }, + value: reportPreviewAction?.reportActionID + ? { + [reportPreviewAction.reportActionID]: { + pendingAction: null, + errors: null, + }, + } + : {}, }, ]; @@ -6304,15 +6321,17 @@ function deleteMoneyRequest(transactionID: string | undefined, reportAction: Ony { onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${chatReport?.reportID}`, - value: { - [reportPreviewAction?.reportActionID ?? '-1']: { - ...reportPreviewAction, - pendingAction: null, - errors: { - [errorKey]: Localize.translateLocal('iou.error.genericDeleteFailureMessage'), - }, - }, - }, + value: reportPreviewAction?.reportActionID + ? { + [reportPreviewAction.reportActionID]: { + ...reportPreviewAction, + pendingAction: null, + errors: { + [errorKey]: Localize.translateLocal('iou.error.genericDeleteFailureMessage'), + }, + }, + } + : {}, }, ); @@ -6510,9 +6529,7 @@ function getSendMoneyParams( const optimisticTransactionThreadReportActionsData: OnyxUpdate = { onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${optimisticTransactionThread.reportID}`, - value: { - [optimisticCreatedActionForTransactionThread?.reportActionID ?? '-1']: optimisticCreatedActionForTransactionThread, - }, + value: optimisticCreatedActionForTransactionThread ? {[optimisticCreatedActionForTransactionThread?.reportActionID]: optimisticCreatedActionForTransactionThread} : {}, }; const successData: OnyxUpdate[] = []; @@ -6609,11 +6626,7 @@ function getSendMoneyParams( { onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${optimisticTransactionThread.reportID}`, - value: { - [optimisticCreatedActionForTransactionThread?.reportActionID ?? '-1']: { - pendingAction: null, - }, - }, + value: optimisticCreatedActionForTransactionThread ? {[optimisticCreatedActionForTransactionThread?.reportActionID]: {pendingAction: null}} : {}, }, ); @@ -6637,11 +6650,9 @@ function getSendMoneyParams( { onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${optimisticTransactionThread.reportID}`, - value: { - [optimisticCreatedActionForTransactionThread?.reportActionID ?? '-1']: { - errors: ErrorUtils.getMicroSecondOnyxErrorWithTranslationKey('iou.error.genericCreateFailureMessage'), - }, - }, + value: optimisticCreatedActionForTransactionThread?.reportActionID + ? {[optimisticCreatedActionForTransactionThread?.reportActionID]: {errors: ErrorUtils.getMicroSecondOnyxErrorWithTranslationKey('iou.error.genericCreateFailureMessage')}} + : {}, }, { onyxMethod: Onyx.METHOD.SET, @@ -6719,11 +6730,11 @@ function getSendMoneyParams( paymentMethodType, transactionID: optimisticTransaction.transactionID, newIOUReportDetails, - createdReportActionID: isNewChat ? optimisticCreatedActionForChat.reportActionID : '-1', + createdReportActionID: isNewChat ? optimisticCreatedActionForChat.reportActionID : undefined, reportPreviewReportActionID: reportPreviewAction.reportActionID, createdIOUReportActionID: optimisticCreatedActionForIOUReport.reportActionID, transactionThreadReportID: optimisticTransactionThread.reportID, - createdReportActionIDForThread: optimisticCreatedActionForTransactionThread?.reportActionID ?? '-1', + createdReportActionIDForThread: optimisticCreatedActionForTransactionThread?.reportActionID, }, optimisticData, successData, @@ -6736,14 +6747,14 @@ type OptimisticHoldReportExpenseActionID = { oldReportActionID: string; }; -function getHoldReportActionsAndTransactions(reportID: string) { +function getHoldReportActionsAndTransactions(reportID: string | undefined) { const iouReportActions = ReportActionsUtils.getAllReportActions(reportID); const holdReportActions: Array> = []; const holdTransactions: OnyxTypes.Transaction[] = []; Object.values(iouReportActions).forEach((action) => { - const transactionID = ReportActionsUtils.isMoneyRequestAction(action) ? ReportActionsUtils.getOriginalMessage(action)?.IOUTransactionID ?? null : null; - const transaction = getTransaction(transactionID ?? '-1'); + const transactionID = ReportActionsUtils.isMoneyRequestAction(action) ? ReportActionsUtils.getOriginalMessage(action)?.IOUTransactionID : undefined; + const transaction = getTransaction(transactionID); if (transaction?.comment?.hold) { holdReportActions.push(action as OnyxTypes.ReportAction); @@ -6766,7 +6777,7 @@ function getReportFromHoldRequestsOnyxData( successData: OnyxUpdate[]; failureData: OnyxUpdate[]; } { - const {holdReportActions, holdTransactions} = getHoldReportActionsAndTransactions(iouReport?.reportID ?? ''); + const {holdReportActions, holdTransactions} = getHoldReportActionsAndTransactions(iouReport?.reportID); const firstHoldTransaction = holdTransactions.at(0); const newParentReportActionID = rand64(); @@ -6777,7 +6788,7 @@ function getReportFromHoldRequestsOnyxData( const optimisticExpenseReport = isPolicyExpenseChat ? ReportUtils.buildOptimisticExpenseReport( chatReport.reportID, - chatReport.policyID ?? iouReport?.policyID ?? '', + chatReport.policyID ?? iouReport?.policyID, recipient.accountID ?? 1, holdAmount, iouReport?.currency ?? '', @@ -6785,8 +6796,8 @@ function getReportFromHoldRequestsOnyxData( newParentReportActionID, ) : ReportUtils.buildOptimisticIOUReport( - iouReport?.ownerAccountID ?? -1, - iouReport?.managerID ?? -1, + iouReport?.ownerAccountID ?? CONST.DEFAULT_NUMBER_ID, + iouReport?.managerID ?? CONST.DEFAULT_NUMBER_ID, holdAmount, chatReport.reportID, iouReport?.currency ?? '', @@ -6884,7 +6895,7 @@ function getReportFromHoldRequestsOnyxData( // remove hold report actions from old iou report { onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${iouReport?.reportID ?? ''}`, + key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${iouReport?.reportID}`, value: deleteHoldReportActions, }, // add hold report actions to new iou report @@ -6952,7 +6963,7 @@ function getReportFromHoldRequestsOnyxData( // add hold report actions back to old iou report { onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${iouReport?.reportID ?? ''}`, + key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${iouReport?.reportID}`, value: bringReportActionsBack, }, // remove hold report actions from the new iou report @@ -7032,7 +7043,7 @@ function getPayMoneyRequestParams( } let total = (iouReport?.total ?? 0) - (iouReport?.nonReimbursableTotal ?? 0); - if (ReportUtils.hasHeldExpenses(iouReport?.reportID ?? '') && !full && !!iouReport?.unheldTotal) { + if (ReportUtils.hasHeldExpenses(iouReport?.reportID) && !full && !!iouReport?.unheldTotal) { total = iouReport.unheldTotal - (iouReport?.unheldNonReimbursableTotal ?? 0); } @@ -7051,14 +7062,14 @@ function getPayMoneyRequestParams( // In some instances, the report preview action might not be available to the payer (only whispered to the requestor) // hence we need to make the updates to the action safely. let optimisticReportPreviewAction = null; - const reportPreviewAction = getReportPreviewAction(chatReport.reportID, iouReport?.reportID ?? ''); + const reportPreviewAction = getReportPreviewAction(chatReport.reportID, iouReport?.reportID); if (reportPreviewAction) { optimisticReportPreviewAction = ReportUtils.updateReportPreview(iouReport, reportPreviewAction, true); } let currentNextStep = null; let optimisticNextStep = null; if (!isInvoiceReport) { - currentNextStep = allNextSteps[`${ONYXKEYS.COLLECTION.NEXT_STEP}${iouReport?.reportID ?? ''}`] ?? null; + currentNextStep = allNextSteps[`${ONYXKEYS.COLLECTION.NEXT_STEP}${iouReport?.reportID}`] ?? null; optimisticNextStep = NextStepUtils.buildNextStep(iouReport, CONST.REPORT.STATUS_NUM.REIMBURSED); } @@ -7085,7 +7096,7 @@ function getPayMoneyRequestParams( }, { onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${iouReport?.reportID ?? ''}`, + key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${iouReport?.reportID}`, value: { [optimisticIOUReportAction.reportActionID]: { ...(optimisticIOUReportAction as OnyxTypes.ReportAction), @@ -7095,7 +7106,7 @@ function getPayMoneyRequestParams( }, { onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT}${iouReport?.reportID ?? ''}`, + key: `${ONYXKEYS.COLLECTION.REPORT}${iouReport?.reportID}`, value: { ...iouReport, lastMessageText: ReportActionsUtils.getReportActionText(optimisticIOUReportAction), @@ -7113,19 +7124,24 @@ function getPayMoneyRequestParams( }, { onyxMethod: Onyx.METHOD.MERGE, - key: ONYXKEYS.NVP_LAST_PAYMENT_METHOD, - value: {[iouReport?.policyID ?? '-1']: paymentMethodType}, - }, - { - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.NEXT_STEP}${iouReport?.reportID ?? ''}`, + key: `${ONYXKEYS.COLLECTION.NEXT_STEP}${iouReport?.reportID}`, value: optimisticNextStep, }, ); + if (iouReport?.policyID) { + optimisticData.push({ + onyxMethod: Onyx.METHOD.MERGE, + key: ONYXKEYS.NVP_LAST_PAYMENT_METHOD, + value: { + [iouReport.policyID]: paymentMethodType, + }, + }); + } + successData.push({ onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT}${iouReport?.reportID ?? ''}`, + key: `${ONYXKEYS.COLLECTION.REPORT}${iouReport?.reportID}`, value: { pendingFields: { preview: null, @@ -7139,7 +7155,7 @@ function getPayMoneyRequestParams( failureData.push( { onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${iouReport?.reportID ?? ''}`, + key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${iouReport?.reportID}`, value: { [optimisticIOUReportAction.reportActionID]: { errors: ErrorUtils.getMicroSecondOnyxErrorWithTranslationKey('iou.error.other'), @@ -7148,7 +7164,7 @@ function getPayMoneyRequestParams( }, { onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT}${iouReport?.reportID ?? ''}`, + key: `${ONYXKEYS.COLLECTION.REPORT}${iouReport?.reportID}`, value: { ...iouReport, }, @@ -7160,7 +7176,7 @@ function getPayMoneyRequestParams( }, { onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.NEXT_STEP}${iouReport?.reportID ?? ''}`, + key: `${ONYXKEYS.COLLECTION.NEXT_STEP}${iouReport?.reportID}`, value: currentNextStep, }, ); @@ -7245,7 +7261,7 @@ function getPayMoneyRequestParams( return { params: { - iouReportID: iouReport?.reportID ?? '', + iouReportID: iouReport?.reportID, chatReportID: chatReport.reportID, reportActionID: optimisticIOUReportAction.reportActionID, paymentMethodType, @@ -7304,7 +7320,7 @@ function canApproveIOU( return false; } - const managerID = iouReport?.managerID ?? -1; + const managerID = iouReport?.managerID ?? CONST.DEFAULT_NUMBER_ID; const isCurrentUserManager = managerID === userAccountID; const isOpenExpenseReport = ReportUtils.isOpenExpenseReport(iouReport); const isApproved = ReportUtils.isReportApproved(iouReport); @@ -7405,18 +7421,18 @@ function canSubmitReport(report: OnyxEntry | SearchReport, pol return isOpenExpenseReport && reimbursableSpend !== 0 && (report?.ownerAccountID === currentUserAccountID || isAdmin || report?.managerID === currentUserAccountID); } -function getIOUReportActionToApproveOrPay(chatReport: OnyxEntry, excludedIOUReportID: string): OnyxEntry { +function getIOUReportActionToApproveOrPay(chatReport: OnyxEntry, excludedIOUReportID: string | undefined): OnyxEntry { const chatReportActions = allReportActions?.[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${chatReport?.reportID}`] ?? {}; return Object.values(chatReportActions).find((action) => { - const iouReport = ReportUtils.getReportOrDraftReport(action.childReportID ?? '-1'); + const iouReport = ReportUtils.getReportOrDraftReport(action.childReportID); const policy = PolicyUtils.getPolicy(iouReport?.policyID); const shouldShowSettlementButton = canIOUBePaid(iouReport, chatReport, policy) || canApproveIOU(iouReport, policy); return action.childReportID?.toString() !== excludedIOUReportID && action.actionName === CONST.REPORT.ACTIONS.TYPE.REPORT_PREVIEW && shouldShowSettlementButton; }); } -function hasIOUToApproveOrPay(chatReport: OnyxEntry, excludedIOUReportID: string): boolean { +function hasIOUToApproveOrPay(chatReport: OnyxEntry, excludedIOUReportID: string | undefined): boolean { return !!getIOUReportActionToApproveOrPay(chatReport, excludedIOUReportID); } @@ -7445,31 +7461,35 @@ function getNextApproverAccountID(report: OnyxEntry) { } function approveMoneyRequest(expenseReport: OnyxEntry, full?: boolean) { - if (expenseReport?.policyID && SubscriptionUtils.shouldRestrictUserBillableActions(expenseReport.policyID)) { + if (!expenseReport) { + return; + } + + if (expenseReport.policyID && SubscriptionUtils.shouldRestrictUserBillableActions(expenseReport.policyID)) { Navigation.navigate(ROUTES.RESTRICTED_ACTION.getRoute(expenseReport.policyID)); return; } - const currentNextStep = allNextSteps[`${ONYXKEYS.COLLECTION.NEXT_STEP}${expenseReport?.reportID}`] ?? null; - let total = expenseReport?.total ?? 0; - const hasHeldExpenses = ReportUtils.hasHeldExpenses(expenseReport?.reportID); - if (hasHeldExpenses && !full && !!expenseReport?.unheldTotal) { - total = expenseReport?.unheldTotal; + const currentNextStep = allNextSteps[`${ONYXKEYS.COLLECTION.NEXT_STEP}${expenseReport.reportID}`] ?? null; + let total = expenseReport.total ?? 0; + const hasHeldExpenses = ReportUtils.hasHeldExpenses(expenseReport.reportID); + if (hasHeldExpenses && !full && !!expenseReport.unheldTotal) { + total = expenseReport.unheldTotal; } - const optimisticApprovedReportAction = ReportUtils.buildOptimisticApprovedReportAction(total, expenseReport?.currency ?? '', expenseReport?.reportID ?? '-1'); + const optimisticApprovedReportAction = ReportUtils.buildOptimisticApprovedReportAction(total, expenseReport.currency ?? '', expenseReport.reportID); - const approvalChain = ReportUtils.getApprovalChain(PolicyUtils.getPolicy(expenseReport?.policyID), expenseReport); + const approvalChain = ReportUtils.getApprovalChain(PolicyUtils.getPolicy(expenseReport.policyID), expenseReport); const predictedNextStatus = isLastApprover(approvalChain) ? CONST.REPORT.STATUS_NUM.APPROVED : CONST.REPORT.STATUS_NUM.SUBMITTED; const predictedNextState = isLastApprover(approvalChain) ? CONST.REPORT.STATE_NUM.APPROVED : CONST.REPORT.STATE_NUM.SUBMITTED; - const managerID = isLastApprover(approvalChain) ? expenseReport?.managerID : getNextApproverAccountID(expenseReport); + const managerID = isLastApprover(approvalChain) ? expenseReport.managerID : getNextApproverAccountID(expenseReport); const optimisticNextStep = NextStepUtils.buildNextStep(expenseReport, predictedNextStatus); - const chatReport = ReportUtils.getReportOrDraftReport(expenseReport?.chatReportID); + const chatReport = ReportUtils.getReportOrDraftReport(expenseReport.chatReportID); const optimisticReportActionsData: OnyxUpdate = { onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${expenseReport?.reportID}`, + key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${expenseReport.reportID}`, value: { [optimisticApprovedReportAction.reportActionID]: { ...(optimisticApprovedReportAction as OnyxTypes.ReportAction), @@ -7479,7 +7499,7 @@ function approveMoneyRequest(expenseReport: OnyxEntry, full?: }; const optimisticIOUReportData: OnyxUpdate = { onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT}${expenseReport?.reportID}`, + key: `${ONYXKEYS.COLLECTION.REPORT}${expenseReport.reportID}`, value: { ...expenseReport, lastMessageText: ReportActionsUtils.getReportActionText(optimisticApprovedReportAction), @@ -7495,15 +7515,15 @@ function approveMoneyRequest(expenseReport: OnyxEntry, full?: const optimisticChatReportData: OnyxUpdate = { onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT}${expenseReport?.chatReportID}`, + key: `${ONYXKEYS.COLLECTION.REPORT}${expenseReport.chatReportID}`, value: { - hasOutstandingChildRequest: hasIOUToApproveOrPay(chatReport, expenseReport?.reportID ?? '-1'), + hasOutstandingChildRequest: hasIOUToApproveOrPay(chatReport, expenseReport.reportID), }, }; const optimisticNextStepData: OnyxUpdate = { onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.NEXT_STEP}${expenseReport?.reportID}`, + key: `${ONYXKEYS.COLLECTION.NEXT_STEP}${expenseReport.reportID}`, value: optimisticNextStep, }; const optimisticData: OnyxUpdate[] = [optimisticIOUReportData, optimisticReportActionsData, optimisticNextStepData, optimisticChatReportData]; @@ -7511,7 +7531,7 @@ function approveMoneyRequest(expenseReport: OnyxEntry, full?: const successData: OnyxUpdate[] = [ { onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${expenseReport?.reportID}`, + key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${expenseReport.reportID}`, value: { [optimisticApprovedReportAction.reportActionID]: { pendingAction: null, @@ -7520,7 +7540,7 @@ function approveMoneyRequest(expenseReport: OnyxEntry, full?: }, { onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT}${expenseReport?.reportID}`, + key: `${ONYXKEYS.COLLECTION.REPORT}${expenseReport.reportID}`, value: { pendingFields: { partial: null, @@ -7532,7 +7552,7 @@ function approveMoneyRequest(expenseReport: OnyxEntry, full?: const failureData: OnyxUpdate[] = [ { onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${expenseReport?.reportID}`, + key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${expenseReport.reportID}`, value: { [optimisticApprovedReportAction.reportActionID]: { errors: ErrorUtils.getMicroSecondOnyxErrorWithTranslationKey('iou.error.other'), @@ -7541,7 +7561,7 @@ function approveMoneyRequest(expenseReport: OnyxEntry, full?: }, { onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT}${expenseReport?.chatReportID}`, + key: `${ONYXKEYS.COLLECTION.REPORT}${expenseReport.chatReportID}`, value: { hasOutstandingChildRequest: chatReport?.hasOutstandingChildRequest, pendingFields: { @@ -7551,14 +7571,14 @@ function approveMoneyRequest(expenseReport: OnyxEntry, full?: }, { onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.NEXT_STEP}${expenseReport?.reportID}`, + key: `${ONYXKEYS.COLLECTION.NEXT_STEP}${expenseReport.reportID}`, value: currentNextStep, }, ]; // Clear hold reason of all transactions if we approve all requests if (full && hasHeldExpenses) { - const heldTransactions = ReportUtils.getAllHeldTransactions(expenseReport?.reportID); + const heldTransactions = ReportUtils.getAllHeldTransactions(expenseReport.reportID); heldTransactions.forEach((heldTransaction) => { optimisticData.push({ onyxMethod: Onyx.METHOD.MERGE, @@ -7596,7 +7616,7 @@ function approveMoneyRequest(expenseReport: OnyxEntry, full?: } const parameters: ApproveMoneyRequestParams = { - reportID: expenseReport?.reportID ?? '-1', + reportID: expenseReport.reportID, approvedReportActionID: optimisticApprovedReportAction.reportActionID, full, optimisticHoldReportID, @@ -7864,8 +7884,8 @@ function cancelPayment(expenseReport: OnyxEntry, chatReport: O const stateNum: ValueOf = approvalMode === CONST.POLICY.APPROVAL_MODE.OPTIONAL ? CONST.REPORT.STATE_NUM.SUBMITTED : CONST.REPORT.STATE_NUM.APPROVED; const statusNum: ValueOf = approvalMode === CONST.POLICY.APPROVAL_MODE.OPTIONAL ? CONST.REPORT.STATUS_NUM.CLOSED : CONST.REPORT.STATUS_NUM.APPROVED; const optimisticNextStep = NextStepUtils.buildNextStep(expenseReport, statusNum); - const iouReportActions = ReportActionsUtils.getAllReportActions(chatReport.iouReportID ?? '-1'); - const expenseReportActions = ReportActionsUtils.getAllReportActions(expenseReport.reportID ?? '-1'); + const iouReportActions = ReportActionsUtils.getAllReportActions(chatReport.iouReportID); + const expenseReportActions = ReportActionsUtils.getAllReportActions(expenseReport.reportID); const iouCreatedAction = Object.values(iouReportActions).find((action) => ReportActionsUtils.isCreatedAction(action)); const expenseCreatedAction = Object.values(expenseReportActions).find((action) => ReportActionsUtils.isCreatedAction(action)); const optimisticData: OnyxUpdate[] = [ @@ -7924,7 +7944,7 @@ function cancelPayment(expenseReport: OnyxEntry, chatReport: O onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${expenseReport.reportID}`, value: { - [optimisticReportAction.reportActionID ?? '-1']: { + [optimisticReportAction.reportActionID]: { errors: ErrorUtils.getMicroSecondOnyxErrorWithTranslationKey('iou.error.other'), }, }, @@ -7991,7 +8011,7 @@ function cancelPayment(expenseReport: OnyxEntry, chatReport: O { iouReportID: expenseReport.reportID, chatReportID: chatReport.reportID, - managerAccountID: expenseReport.managerID ?? -1, + managerAccountID: expenseReport.managerID ?? CONST.DEFAULT_NUMBER_ID, reportActionID: optimisticReportAction.reportActionID, }, {optimisticData, successData, failureData}, @@ -8048,7 +8068,7 @@ function payMoneyRequest(paymentType: PaymentMethodType, chatReport: OnyxTypes.R const paymentSelected = paymentType === CONST.IOU.PAYMENT_TYPE.VBBA ? CONST.IOU.PAYMENT_SELECTED.BBA : CONST.IOU.PAYMENT_SELECTED.PBA; completePaymentOnboarding(paymentSelected); - const recipient = {accountID: iouReport?.ownerAccountID ?? -1}; + const recipient = {accountID: iouReport?.ownerAccountID ?? CONST.DEFAULT_NUMBER_ID}; const {params, optimisticData, successData, failureData} = getPayMoneyRequestParams(chatReport, iouReport, recipient, paymentType, full); // For now, we need to call the PayMoneyRequestWithWallet API since PayMoneyRequest was not updated to work with @@ -8057,11 +8077,11 @@ function payMoneyRequest(paymentType: PaymentMethodType, chatReport: OnyxTypes.R playSound(SOUNDS.SUCCESS); API.write(apiCommand, params, {optimisticData, successData, failureData}); - Report.notifyNewAction(iouReport?.reportID ?? '', userAccountID); + Report.notifyNewAction(iouReport?.reportID, userAccountID); } function payInvoice(paymentMethodType: PaymentMethodType, chatReport: OnyxTypes.Report, invoiceReport: OnyxEntry, payAsBusiness = false) { - const recipient = {accountID: invoiceReport?.ownerAccountID ?? -1}; + const recipient = {accountID: invoiceReport?.ownerAccountID ?? CONST.DEFAULT_NUMBER_ID}; const { optimisticData, successData, @@ -8084,7 +8104,7 @@ function payInvoice(paymentMethodType: PaymentMethodType, chatReport: OnyxTypes. completePaymentOnboarding(paymentSelected); let params: PayInvoiceParams = { - reportID: invoiceReport?.reportID ?? '', + reportID: invoiceReport?.reportID, reportActionID, paymentMethodType, payAsBusiness, @@ -8699,10 +8719,10 @@ function savePreferredPaymentMethod(policyID: string, paymentMethod: PaymentMeth } /** Get report policy id of IOU request */ -function getIOURequestPolicyID(transaction: OnyxEntry, report: OnyxEntry): string { +function getIOURequestPolicyID(transaction: OnyxEntry, report: OnyxEntry): string | undefined { // Workspace sender will exist for invoices const workspaceSender = transaction?.participants?.find((participant) => participant.isSender); - return workspaceSender?.policyID ?? report?.policyID ?? '-1'; + return workspaceSender?.policyID ?? report?.policyID; } function getIOUActionForTransactions(transactionIDList: string[], iouReportID: string): Array> { @@ -8923,10 +8943,12 @@ function resolveDuplicates(params: TransactionMergeParams) { }); const iouActionList = params.reportID ? getIOUActionForTransactions(params.transactionIDList, params.reportID) : []; - const orderedTransactionIDList = iouActionList.map((action) => { - const message = ReportActionsUtils.getOriginalMessage(action); - return message?.IOUTransactionID ?? ''; - }); + const orderedTransactionIDList = iouActionList + .map((action) => { + const message = ReportActionsUtils.getOriginalMessage(action); + return message?.IOUTransactionID; + }) + .filter((id): id is string => !!id); const optimisticHoldActions: OnyxUpdate[] = []; const failureHoldActions: OnyxUpdate[] = []; diff --git a/src/libs/actions/Report.ts b/src/libs/actions/Report.ts index 1e157b983483..3fb6edf8e7f1 100644 --- a/src/libs/actions/Report.ts +++ b/src/libs/actions/Report.ts @@ -485,7 +485,7 @@ function subscribeToNewActionEvent(reportID: string, callback: SubscriberCallbac } /** Notify the ReportActionsView that a new comment has arrived */ -function notifyNewAction(reportID: string, accountID?: number, reportActionID?: string) { +function notifyNewAction(reportID: string | undefined, accountID?: number, reportActionID?: string) { const actionSubscriber = newActionSubscribers.find((subscriber) => subscriber.reportID === reportID); if (!actionSubscriber) { return; diff --git a/src/types/onyx/Transaction.ts b/src/types/onyx/Transaction.ts index b183cbb06831..a4e6d4a4afab 100644 --- a/src/types/onyx/Transaction.ts +++ b/src/types/onyx/Transaction.ts @@ -452,7 +452,7 @@ type Transaction = OnyxCommon.OnyxValueWithOfflineFeedback< receipt?: Receipt; /** The iouReportID associated with the transaction */ - reportID: string; + reportID: string | undefined; /** Existing routes */ routes?: Routes;