From f69cfe89680e5a2c9731e245e762cb80319bdd76 Mon Sep 17 00:00:00 2001 From: "Kevin Brian Bader (via MelvinBot)" Date: Thu, 19 Nov 2026 04:33:19 +0000 Subject: [PATCH 1/3] Fix: consolidate unsent receipt replacements without losing audit history Co-authored-by: Kevin Brian Bader --- src/libs/Network/SequentialQueue.ts | 8 +- src/libs/actions/IOU/Receipt.ts | 151 +++++++++++-- src/libs/actions/RequestConflictUtils.ts | 32 +++ src/libs/telemetry/ReceiptObservability.ts | 11 + tests/actions/IOUTest/ReceiptTest.ts | 240 ++++++++++++++++++++- tests/unit/RequestConflictUtilsTest.ts | 39 ++++ tests/unit/SequentialQueueTest.ts | 54 ++++- 7 files changed, 514 insertions(+), 21 deletions(-) diff --git a/src/libs/Network/SequentialQueue.ts b/src/libs/Network/SequentialQueue.ts index aae36752426d..edae38c193bb 100644 --- a/src/libs/Network/SequentialQueue.ts +++ b/src/libs/Network/SequentialQueue.ts @@ -830,12 +830,16 @@ async function handleConflictActions(conflictAction: Confl willPushNewRequest: conflictAction.pushNewRequest ?? false, hasNextAction: !!conflictAction.nextAction, }); - await deletePersistedRequestsByIndices(conflictAction.indices); + const deletion = deletePersistedRequestsByIndices(conflictAction.indices); if (conflictAction.pushNewRequest) { Log.info('[SequentialQueue] Pushing new request after delete', false, { command: newRequest.command, }); - await savePersistedRequest(newRequest); + // Both calls update the queue in memory before returning. Append before awaiting persistence so a request + // queued in the meantime cannot be saved and sent ahead of this one. + await Promise.all([deletion, savePersistedRequest(newRequest)]); + } else { + await deletion; } if (conflictAction.nextAction) { Log.info('[SequentialQueue] Processing next conflict action', false, { diff --git a/src/libs/actions/IOU/Receipt.ts b/src/libs/actions/IOU/Receipt.ts index ecc92d2f2e20..bf9801a212e9 100644 --- a/src/libs/actions/IOU/Receipt.ts +++ b/src/libs/actions/IOU/Receipt.ts @@ -8,20 +8,25 @@ import {navigateToStartMoneyRequestStep} from '@libs/IOUUtils'; import createDynamicRoute from '@libs/Navigation/helpers/dynamicRoutesUtils/createDynamicRoute'; import Navigation from '@libs/Navigation/Navigation'; import {rand64} from '@libs/NumberUtils'; +import {isRecord} from '@libs/ObjectUtils'; import {hasDependentTags, isGroupPolicy} from '@libs/PolicyUtils'; import ReceiptStorage from '@libs/ReceiptStorage'; import {buildOptimisticReceiptAddedAction, buildOptimisticReceiptRemovedAction, isInvoiceReport as isInvoiceReportReportUtils} from '@libs/ReportUtils'; import {getCurrentSearchQueryJSON} from '@libs/SearchQueryUtils'; -import {logReceiptCaptured, mintAndStampReceiptTraceId} from '@libs/telemetry/ReceiptObservability'; +import {logReceiptCaptured, logReceiptSuperseded, mintAndStampReceiptTraceId} from '@libs/telemetry/ReceiptObservability'; import {hasReceiptSource, hasUploadedReceipt, isFailedScanAmountPlaceholder} from '@libs/TransactionUtils'; import ViolationsUtils from '@libs/Violations/ViolationsUtils'; +import {getAll as getAllPersistedRequests} from '@userActions/PersistedRequests'; +import {getSupersededReplaceReceiptIndices, resolveReplaceReceiptConflicts} from '@userActions/RequestConflictUtils'; + import type {IOURequestType, IOUType} from '@src/CONST'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import ROUTES, {DYNAMIC_ROUTES} from '@src/ROUTES'; import type * as OnyxTypes from '@src/types/onyx'; import type {CurrentUserPersonalDetails} from '@src/types/onyx/PersonalDetails'; +import type {AnyOnyxUpdate, AnyRequest} from '@src/types/onyx/Request'; import type {SearchResultDataType} from '@src/types/onyx/SearchResults'; import type {Receipt, ReceiptSource} from '@src/types/onyx/Transaction'; import {isEmptyObject} from '@src/types/utils/EmptyObject'; @@ -226,6 +231,88 @@ function detachReceipt({ API.write(WRITE_COMMANDS.DETACH_RECEIPT, parameters, {optimisticData, successData, failureData}); } +type ReplaceReceiptOnyxKey = + | typeof ONYXKEYS.COLLECTION.TRANSACTION + | typeof ONYXKEYS.COLLECTION.SNAPSHOT + | typeof ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS + | typeof ONYXKEYS.COLLECTION.REPORT_ACTIONS + | typeof ONYXKEYS.COLLECTION.REPORT; + +/** Keep the oldest rollback per key, but never restore audit actions belonging to uploads that will not be sent. */ +function getOriginalRollbackUpdates(supersededRequests: AnyRequest[]): Map { + const originalUpdates = new Map(); + for (const request of supersededRequests) { + for (const update of request.failureData ?? []) { + const key: unknown = update.key; + if (typeof key !== 'string' || key.startsWith(ONYXKEYS.COLLECTION.REPORT_ACTIONS) || originalUpdates.has(key)) { + continue; + } + originalUpdates.set(key, update); + } + } + return originalUpdates; +} + +/** Restore the state before the unsent replacements, while retaining the latest upload's errors and retry data. */ +function inheritOriginalRollback( + failureData: Array>, + originalUpdates: Map, + transactionKey: string, +): Array> { + if (originalUpdates.size === 0) { + return failureData; + } + const originalTransactionValue: unknown = originalUpdates.get(transactionKey)?.value; + const inheritedFailureData = failureData.map((update): OnyxUpdate => { + const originalUpdate = originalUpdates.get(update.key); + const snapshotValue: unknown = (originalUpdate ?? update).value; + // A search first opened during these replacements also contains an unsent file, not the server's receipt. + if ( + update.key.startsWith(ONYXKEYS.COLLECTION.SNAPSHOT) && + isRecord(originalTransactionValue) && + 'receipt' in originalTransactionValue && + isRecord(snapshotValue) && + isRecord(snapshotValue.data) && + isRecord(snapshotValue.data[transactionKey]) + ) { + const snapshotUpdate: AnyOnyxUpdate = { + ...(originalUpdate ?? update), + value: { + ...snapshotValue, + data: {...snapshotValue.data, [transactionKey]: {...snapshotValue.data[transactionKey], receipt: originalTransactionValue.receipt}}, + }, + }; + return snapshotUpdate; + } + if (!originalUpdate) { + return update; + } + if (update.key !== transactionKey) { + return originalUpdate; + } + const originalValue: unknown = originalUpdate.value; + if (!isRecord(originalValue) || !('receipt' in originalValue) || !isRecord(update.value)) { + return update; + } + const transactionUpdate: AnyOnyxUpdate = {...update, value: {...update.value, receipt: originalValue.receipt}}; + return transactionUpdate; + }); + + // A snapshot from a search that is no longer open still needs its rollback even if the latest upload did not touch it. + const ownKeys = new Set(failureData.map((update) => update.key)); + for (const [key, originalUpdate] of originalUpdates) { + if (!ownKeys.has(key)) { + inheritedFailureData.push(originalUpdate); + } + } + return inheritedFailureData; +} + +function getStringField(request: AnyRequest, field: string): string | undefined { + const value = request.data?.[field]; + return typeof value === 'string' ? value : undefined; +} + function replaceReceipt({ transaction, file, @@ -253,6 +340,26 @@ function replaceReceipt({ const receiptTraceId = mintAndStampReceiptTraceId(file); logReceiptCaptured({file, captureSource: 'replace', receiptTraceId}); + // Read the waiting queue in the same tick as API.write so cleanup and rollback cover exactly the dropped uploads. + const persistedRequests = getAllPersistedRequests(); + const supersededRequests = getSupersededReplaceReceiptIndices(persistedRequests, transactionID).flatMap((index) => persistedRequests.at(index) ?? []); + for (const request of supersededRequests) { + const queuedReceipt = request.data?.receipt; + logReceiptSuperseded({ + receiptTraceId: isRecord(queuedReceipt) && typeof queuedReceipt.receiptTraceId === 'string' ? queuedReceipt.receiptTraceId : undefined, + transactionID, + command: request.command, + }); + } + const transactionKey = `${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`; + const originalRollbackUpdates = getOriginalRollbackUpdates(supersededRequests); + const originalTransactionRollback: unknown = originalRollbackUpdates.get(transactionKey)?.value; + const hasOriginalReceiptRollback = isRecord(originalTransactionRollback) && 'receipt' in originalTransactionRollback; + const originalReceipt = hasOriginalReceiptRollback ? originalTransactionRollback.receipt : undefined; + + // A crop of an unsent replacement is still a new receipt to the server and must retain replacement auditing. + const isSameReceiptOnServer = !!isSameReceipt && !supersededRequests.some((request) => !request.data?.isSameReceipt); + const oldReceipt = transaction?.receipt ?? {}; // Replacing a failed-scan receipt whose amount was never filled in: upgrade to SCAN_READY so the UI shows "Scanning" instead of 0.00, mirroring the backend. // If the user already entered an amount, keep it OPEN so re-scanning does not overwrite that amount. @@ -267,23 +374,26 @@ function replaceReceipt({ pageCount: null, // A new receipt must not keep the old one's reservation dates, or the per-night limit check would use them. // A crop or rotate keeps the same receipt, so its dates stay. - ...(isSameReceipt ? {} : {hotelReservationStartDate: null, hotelReservationEndDate: null}), + ...(isSameReceiptOnServer ? {} : {hotelReservationStartDate: null, hotelReservationEndDate: null}), }; const newTransaction = transaction && {...transaction, receipt: receiptOptimistic}; // The audit action IDs are chosen before the optimistic data is built. A retry passes the same IDs back // so it updates the failed actions. Nothing is posted for a crop or rotate, or when the thread does not exist yet. const transactionThreadReportID = transactionThreadReport?.reportID; - const optimisticReceiptAddedActionID = !isSameReceipt && transactionThreadReportID ? (receiptAddedReportActionID ?? rand64()) : undefined; + const optimisticReceiptAddedActionID = !isSameReceiptOnServer && transactionThreadReportID ? (receiptAddedReportActionID ?? rand64()) : undefined; // A receipt added offline has a file but no receipt ID yet, and that still counts as one being replaced. - const isReplacingReceipt = !!transaction && (hasReceiptSource(transaction) || hasUploadedReceipt(transaction)); + // An expense that had no receipt before these uploads must not report a removal of an unsent local file. + const isReplacingReceipt = hasOriginalReceiptRollback + ? isRecord(originalReceipt) && (!!originalReceipt.source || !!originalReceipt.receiptID) + : !!transaction && (hasReceiptSource(transaction) || hasUploadedReceipt(transaction)); const optimisticReceiptRemovedActionID = optimisticReceiptAddedActionID && isReplacingReceipt ? (receiptRemovedReportActionID ?? rand64()) : undefined; const retryParams: ReplaceReceiptRetryParams = { transactionID: transaction.transactionID, file: undefined, source, state, - isSameReceipt, + isSameReceipt: isSameReceiptOnServer, transactionPolicy, transactionPolicyCategories, transactionPolicyTagList, @@ -328,15 +438,7 @@ function replaceReceipt({ }, ]; - const failureData: Array< - OnyxUpdate< - | typeof ONYXKEYS.COLLECTION.TRANSACTION - | typeof ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS - | typeof ONYXKEYS.COLLECTION.SNAPSHOT - | typeof ONYXKEYS.COLLECTION.REPORT_ACTIONS - | typeof ONYXKEYS.COLLECTION.REPORT - > - > = [ + const failureData: Array> = [ { onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`, @@ -431,6 +533,18 @@ function replaceReceipt({ const optimisticAuditActions = [optimisticReceiptRemovedAction, optimisticReceiptAddedAction].filter((action) => !!action); + // Dropped uploads cannot clear their pending audit actions. Keep IDs reused by this upload's retry intact. + const supersededAuditActionIDs = supersededRequests + .flatMap((request) => [getStringField(request, 'reportActionID'), getStringField(request, 'receiptRemovedReportActionID')]) + .filter((reportActionID): reportActionID is string => !!reportActionID && reportActionID !== optimisticReceiptAddedActionID && reportActionID !== optimisticReceiptRemovedActionID); + if (supersededAuditActionIDs.length > 0 && transactionThreadReportID) { + optimisticData.push({ + onyxMethod: Onyx.METHOD.MERGE, + key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${transactionThreadReportID}`, + value: Object.fromEntries(supersededAuditActionIDs.map((reportActionID) => [reportActionID, null])), + }); + } + if (optimisticAuditActions.length > 0 && transactionThreadReportID) { const lastAuditAction = optimisticAuditActions.at(-1); optimisticData.push( @@ -485,12 +599,17 @@ function replaceReceipt({ transactionID, receipt, receiptState: state, - isSameReceipt, + isSameReceipt: isSameReceiptOnServer, reportActionID: optimisticReceiptAddedAction?.reportActionID, receiptRemovedReportActionID: optimisticReceiptRemovedAction?.reportActionID, }; - API.write(WRITE_COMMANDS.REPLACE_RECEIPT, parameters, {optimisticData, successData, failureData}); + API.write( + WRITE_COMMANDS.REPLACE_RECEIPT, + parameters, + {optimisticData, successData, failureData: inheritOriginalRollback(failureData, originalRollbackUpdates, transactionKey)}, + {checkAndFixConflictingRequest: (requests) => resolveReplaceReceiptConflicts(requests, transactionID)}, + ); } function setMoneyRequestReceipt( diff --git a/src/libs/actions/RequestConflictUtils.ts b/src/libs/actions/RequestConflictUtils.ts index 358d5d9847eb..cd3cba28ff7e 100644 --- a/src/libs/actions/RequestConflictUtils.ts +++ b/src/libs/actions/RequestConflictUtils.ts @@ -431,7 +431,39 @@ function resolveVacationDelegateDeletionConflicts(persiste }; } +/** + * Replacements before a detach belong to the receipt history. An upload already attempted may also be stored on the + * server, so only later unsent replacements can be dropped. Return their indices oldest first for rollback inheritance. + */ +function getSupersededReplaceReceiptIndices(persistedRequests: AnyRequest[], transactionID: string): number[] { + const indices: number[] = []; + for (let index = persistedRequests.length - 1; index >= 0; index--) { + const request = persistedRequests.at(index); + if (request?.data?.transactionID !== transactionID) { + continue; + } + if (request.command === WRITE_COMMANDS.DETACH_RECEIPT || (request.command === WRITE_COMMANDS.REPLACE_RECEIPT && request.isRollback)) { + break; + } + if (request.command === WRITE_COMMANDS.REPLACE_RECEIPT) { + indices.unshift(index); + } + } + return indices; +} + +/** Append the latest upload after dependencies queued since the superseded uploads, such as the thread's OpenReport. */ +function resolveReplaceReceiptConflicts(persistedRequests: AnyRequest[], transactionID: string): ConflictActionData { + const indices = getSupersededReplaceReceiptIndices(persistedRequests, transactionID); + if (indices.length === 0) { + return {conflictAction: {type: 'push'}}; + } + return {conflictAction: {type: 'delete', indices, pushNewRequest: true}}; +} + export { + getSupersededReplaceReceiptIndices, + resolveReplaceReceiptConflicts, resolveDuplicationConflictAction, resolveOpenAppDuplicationConflictAction, resolveOpenReportDuplicationConflictAction, diff --git a/src/libs/telemetry/ReceiptObservability.ts b/src/libs/telemetry/ReceiptObservability.ts index 67670cf03d01..1d168cd8459a 100644 --- a/src/libs/telemetry/ReceiptObservability.ts +++ b/src/libs/telemetry/ReceiptObservability.ts @@ -240,6 +240,16 @@ function logReceiptGaveUp({ }); } +/** A superseded upload is intentionally never sent, rather than stuck in the queue. */ +function logReceiptSuperseded({receiptTraceId, transactionID, command}: {receiptTraceId: string | undefined; transactionID: string | undefined; command: string}) { + Log.info(`${RECEIPT_LOG_PREFIX} superseded`, true, { + event: 'superseded', + receiptTraceId, + transactionID, + command, + }); +} + function logReceiptStatFailed(code: string | undefined) { Log.info(`${RECEIPT_LOG_PREFIX} stat failed`, false, { event: 'statFailed', @@ -395,6 +405,7 @@ export { logReceiptEnqueued, logReceiptDropped, logReceiptGaveUp, + logReceiptSuperseded, logReceiptStatFailed, logReceiptAdoptFailed, logCameraCaptureFailed, diff --git a/tests/actions/IOUTest/ReceiptTest.ts b/tests/actions/IOUTest/ReceiptTest.ts index b6b6fdf60f91..a7ca116be314 100644 --- a/tests/actions/IOUTest/ReceiptTest.ts +++ b/tests/actions/IOUTest/ReceiptTest.ts @@ -6,8 +6,11 @@ import type {SearchQueryJSON} from '@components/Search/types'; import {detachReceipt, replaceReceipt, setMoneyRequestReceipt} from '@libs/actions/IOU/Receipt'; import initOnyxDerivedValues from '@libs/actions/OnyxDerived'; import {WRITE_COMMANDS} from '@libs/API/types'; +import {flush as flushSequentialQueue, waitForIdle} from '@libs/Network/SequentialQueue'; import type * as PolicyUtils from '@libs/PolicyUtils'; +import {clear as clearPersistedRequests, getAll as getAllPersistedRequests} from '@userActions/PersistedRequests'; + import CONST from '@src/CONST'; import OnyxUpdateManager from '@src/libs/actions/OnyxUpdateManager'; import * as API from '@src/libs/API'; @@ -21,13 +24,15 @@ import type {OnyxEntry} from 'react-native-onyx'; import Onyx from 'react-native-onyx'; +import type {MockFetch} from '../../utils/TestHelper'; + import createRandomPolicy from '../../utils/collections/policies'; import createRandomPolicyTags from '../../utils/collections/policyTags'; import {createRandomReport} from '../../utils/collections/reports'; import createRandomTransaction from '../../utils/collections/transaction'; import createMock from '../../utils/createMock'; import getOnyxValue from '../../utils/getOnyxValue'; -import {getGlobalFetchMock, getRequiredOnyxUpdate, getRequiredOnyxUpdates, getRequiredWriteCall} from '../../utils/TestHelper'; +import {expectAPICommandToHaveBeenCalled, getGlobalFetchMock, getRequiredOnyxUpdate, getRequiredOnyxUpdates, getRequiredWriteCall} from '../../utils/TestHelper'; import waitForBatchedUpdates from '../../utils/waitForBatchedUpdates'; jest.mock('@src/libs/Navigation/Navigation', () => ({ @@ -441,7 +446,12 @@ describe('actions/IOU/Receipt', () => { await waitForBatchedUpdates(); // Then API.write is invoked with the REPLACE_RECEIPT command and the correct transactionID - expect(writeSpy).toHaveBeenCalledWith(WRITE_COMMANDS.REPLACE_RECEIPT, expect.objectContaining({transactionID}), expect.anything()); + expect(writeSpy).toHaveBeenCalledWith( + WRITE_COMMANDS.REPLACE_RECEIPT, + expect.objectContaining({transactionID}), + expect.anything(), + expect.objectContaining({checkAndFixConflictingRequest: expect.any(Function)}), + ); } finally { writeSpy.mockRestore(); } @@ -702,6 +712,7 @@ describe('actions/IOU/Receipt', () => { receipt: expect.any(Object), }), expect.anything(), + expect.objectContaining({checkAndFixConflictingRequest: expect.any(Function)}), ); } finally { writeSpy.mockRestore(); @@ -1044,6 +1055,231 @@ describe('actions/IOU/Receipt', () => { }); }); + describe('offline receipt replacements', () => { + const transactionID = '107135'; + const threadReportID = '107136'; + const snapshotHash = 918273645; + const originalReceipt = {source: 'original.jpg', filename: 'original.jpg', state: CONST.IOU.RECEIPT_STATE.OPEN}; + const originalTimestamp = '2026-01-01 00:00:00.000'; + const currentUserPersonalDetails = {accountID: RORY_ACCOUNT_ID, email: RORY_EMAIL}; + let mockFetch: MockFetch; + + const getTransaction = () => getOnyxValue(`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`); + const getThread = () => getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT}${threadReportID}`); + const getActions = () => getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${threadReportID}`); + const getQueuedReplacement = () => getAllPersistedRequests().find((request) => request.command === WRITE_COMMANDS.REPLACE_RECEIPT); + const getAuditActionIDs = (request: ReturnType) => + [request?.data?.reportActionID, request?.data?.receiptRemovedReportActionID].filter((id): id is string => typeof id === 'string' && id !== '0'); + + const replaceWithLatestState = async (source: string, isSameReceipt?: boolean) => { + replaceReceipt({ + transaction: await getTransaction(), + file: new File([new Blob(['test'])], source, {type: 'image/jpeg'}), + source, + isSameReceipt, + transactionPolicy: undefined, + transactionReport: undefined, + isVendorMatchingBetaEnabled: false, + delegateAccountID: undefined, + currentUserPersonalDetails, + transactionThreadReport: await getThread(), + }); + await waitForBatchedUpdates(); + }; + + const detachLatestState = async () => { + detachReceipt({ + transaction: await getTransaction(), + transactionPolicy: undefined, + transactionPolicyTagList: undefined, + transactionViolations: undefined, + transactionReport: undefined, + isVendorMatchingBetaEnabled: false, + transactionThreadReport: await getThread(), + delegateAccountID: undefined, + currentUserPersonalDetails, + }); + await waitForBatchedUpdates(); + }; + + const reconnect = async () => { + await Onyx.set(ONYXKEYS.NETWORK, {shouldForceOffline: false}); + flushSequentialQueue(); + await waitForIdle(); + await waitForBatchedUpdates(); + }; + + beforeEach(async () => { + mockFetch = getGlobalFetchMock(); + global.fetch = mockFetch; + clearPersistedRequests(); + await Onyx.set(ONYXKEYS.NETWORK, {shouldForceOffline: true}); + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${threadReportID}`, { + ...createRandomReport(2, undefined), + reportID: threadReportID, + lastVisibleActionCreated: originalTimestamp, + lastReadTime: originalTimestamp, + }); + const transaction = {...createRandomTransaction(Number(transactionID)), receipt: originalReceipt}; + await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`, transaction); + await Onyx.set(`${ONYXKEYS.COLLECTION.SNAPSHOT}${snapshotHash}`, { + // @ts-expect-error: Only the transaction data is needed in this snapshot fixture + data: {[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`]: transaction}, + }); + jest.spyOn(SearchQueryUtils, 'getCurrentSearchQueryJSON').mockReturnValue(createMock({hash: snapshotHash})); + }); + + afterEach(async () => { + jest.restoreAllMocks(); + clearPersistedRequests(); + await Onyx.set(ONYXKEYS.NETWORK, {shouldForceOffline: false}); + }); + + it('sends only the latest replacement followed by detach without leaving superseded audit actions', async () => { + // Given three offline uploads, whose discarded audit actions must not remain pending + await replaceWithLatestState('first.jpg'); + const supersededIDs = getAuditActionIDs(getQueuedReplacement()); + await replaceWithLatestState('second.jpg'); + supersededIDs.push(...getAuditActionIDs(getQueuedReplacement())); + await replaceWithLatestState('third.jpg'); + const keptIDs = getAuditActionIDs(getQueuedReplacement()); + await detachLatestState(); + + // When all changes are still offline, only the final upload and detach remain + expect(getAllPersistedRequests()).toEqual([ + expect.objectContaining({command: WRITE_COMMANDS.REPLACE_RECEIPT, data: expect.objectContaining({receipt: expect.objectContaining({source: 'third.jpg'})})}), + expect.objectContaining({command: WRITE_COMMANDS.DETACH_RECEIPT}), + ]); + const actions = await getActions(); + for (const id of supersededIDs) { + expect(actions?.[id]).toBeUndefined(); + } + for (const id of keptIDs) { + expect(actions?.[id]).toBeDefined(); + } + await reconnect(); + + // Then reconnect sends one upload followed by detach, and discarded audit actions never return + expectAPICommandToHaveBeenCalled(WRITE_COMMANDS.REPLACE_RECEIPT, 1); + expectAPICommandToHaveBeenCalled(WRITE_COMMANDS.DETACH_RECEIPT, 1); + const syncedActions = await getActions(); + for (const id of supersededIDs) { + expect(syncedActions?.[id]).toBeUndefined(); + } + }); + + it('restores the original receipt, snapshot and timestamps but keeps the latest error on upload failure', async () => { + // Given several unsent uploads whose intermediate files never reached the server + await replaceWithLatestState('first.jpg'); + const supersededIDs = getAuditActionIDs(getQueuedReplacement()); + await replaceWithLatestState('second.jpg'); + await replaceWithLatestState('third.jpg'); + + // When the surviving upload fails + mockFetch.fail(); + await reconnect(); + + // Then rollback restores the original state without resurrecting the discarded uploads' audit actions + const transaction = await getTransaction(); + expect(transaction?.receipt?.source).toBe(originalReceipt.source); + const snapshot = await getOnyxValue(`${ONYXKEYS.COLLECTION.SNAPSHOT}${snapshotHash}`); + expect(snapshot?.data?.[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`]?.receipt?.source).toBe(originalReceipt.source); + expect(Object.values(transaction?.errors ?? {}).at(0)).toEqual(expect.objectContaining({source: 'third.jpg'})); + expect((await getThread())?.lastVisibleActionCreated).toBe(originalTimestamp); + expect((await getThread())?.lastReadTime).toBe(originalTimestamp); + const actions = await getActions(); + for (const id of supersededIDs) { + expect(actions?.[id]).toBeUndefined(); + } + }); + + it('sends a crop of an unsent replacement with replacement audit actions', async () => { + // Given a new receipt the server has not seen + await replaceWithLatestState('first.jpg'); + + // When it is cropped offline + await replaceWithLatestState('cropped.jpg', true); + + // Then the single surviving upload is a replacement, not a crop of the server's old file + expect(getAllPersistedRequests()).toHaveLength(1); + expect(getQueuedReplacement()?.data?.isSameReceipt).toBe(false); + expect(getAuditActionIDs(getQueuedReplacement())).toHaveLength(2); + }); + + it.each([true, false])('restores earlier snapshots when search changes between uploads (another search: %s)', async (opensAnotherSearch) => { + // Given an unsent replacement made in one search + await replaceWithLatestState('first.jpg'); + const secondSnapshotHash = snapshotHash + 1; + if (opensAnotherSearch) { + const transaction = await getTransaction(); + await Onyx.set(`${ONYXKEYS.COLLECTION.SNAPSHOT}${secondSnapshotHash}`, { + // @ts-expect-error: Only transaction data is needed in this search fixture + data: {[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`]: transaction}, + }); + } + + // When the user switches searches or leaves search, replaces again, and the surviving upload fails + jest.mocked(SearchQueryUtils.getCurrentSearchQueryJSON).mockReturnValue(opensAnotherSearch ? createMock({hash: secondSnapshotHash}) : undefined); + await replaceWithLatestState('second.jpg'); + mockFetch.fail(); + await reconnect(); + + // Then no touched snapshot rolls back to the first file, whose upload was discarded + expect((await getTransaction())?.receipt?.source).toBe(originalReceipt.source); + for (const hash of opensAnotherSearch ? [snapshotHash, secondSnapshotHash] : [snapshotHash]) { + const snapshot = await getOnyxValue(`${ONYXKEYS.COLLECTION.SNAPSHOT}${hash}`); + expect(snapshot?.data?.[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`]?.receipt?.source).toBe(originalReceipt.source); + } + }); + + it('does not report a receipt removal when the expense originally had none', async () => { + // Given an expense without a server receipt + await Onyx.merge(`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`, {receipt: null}); + + // When an unsent receipt is replaced again + await replaceWithLatestState('first.jpg'); + await replaceWithLatestState('second.jpg'); + + // Then only an addition is sent, because the server never stored a receipt to remove + expect(getAllPersistedRequests()).toHaveLength(1); + expect(getQueuedReplacement()?.data?.reportActionID).toEqual(expect.any(String)); + expect(getQueuedReplacement()?.data?.receiptRemovedReportActionID).toBeUndefined(); + }); + + it('preserves additions and removals across detach boundaries from the earlier audit-trail fix', async () => { + // Given an expense without a receipt, matching the historical missing-audit regression + await Onyx.merge(`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`, {receipt: null}); + + // When receipts are added and deleted twice offline, with redundant replacements within each segment + await replaceWithLatestState('first-discarded.jpg'); + await replaceWithLatestState('first-kept.jpg'); + await detachLatestState(); + await replaceWithLatestState('second-discarded.jpg'); + await replaceWithLatestState('second-kept.jpg'); + await detachLatestState(); + const queued = [...getAllPersistedRequests()]; + const actionIDs = queued.flatMap((request) => getAuditActionIDs(request)); + + // Then each addition preceding a deletion survives with its audit action, in its original history order + expect(queued.map((request) => request.command)).toEqual([ + WRITE_COMMANDS.REPLACE_RECEIPT, + WRITE_COMMANDS.DETACH_RECEIPT, + WRITE_COMMANDS.REPLACE_RECEIPT, + WRITE_COMMANDS.DETACH_RECEIPT, + ]); + expect(actionIDs).toHaveLength(4); + await reconnect(); + expectAPICommandToHaveBeenCalled(WRITE_COMMANDS.REPLACE_RECEIPT, 2); + expectAPICommandToHaveBeenCalled(WRITE_COMMANDS.DETACH_RECEIPT, 2); + const actions = await getActions(); + for (const id of actionIDs) { + expect(actions?.[id]).toBeDefined(); + expect(actions?.[id]?.pendingAction).toBeFalsy(); + expect(actions?.[id]?.errors).toBeFalsy(); + } + }); + }); + describe('detachReceipt', () => { const transactionID = '1'; const reportID = '2'; diff --git a/tests/unit/RequestConflictUtilsTest.ts b/tests/unit/RequestConflictUtilsTest.ts index 1e8daea67244..5a2730d82e94 100644 --- a/tests/unit/RequestConflictUtilsTest.ts +++ b/tests/unit/RequestConflictUtilsTest.ts @@ -7,6 +7,7 @@ import { resolveOpenAppDuplicationConflictAction, resolveOpenReportDuplicationConflictAction, resolveReconnectDuplicationConflictAction, + resolveReplaceReceiptConflicts, resolveVacationDelegateDeletionConflicts, } from '@libs/actions/RequestConflictUtils'; import {WRITE_COMMANDS} from '@libs/API/types'; @@ -18,6 +19,44 @@ import type {OnyxKey} from 'react-native-onyx'; import Onyx from 'react-native-onyx'; describe('RequestConflictUtils', () => { + describe('resolveReplaceReceiptConflicts', () => { + const replace = (transactionID: string, isRollback?: boolean): AnyRequest => ({command: WRITE_COMMANDS.REPLACE_RECEIPT, data: {transactionID}, isRollback}); + const detach = (transactionID: string): AnyRequest => ({command: WRITE_COMMANDS.DETACH_RECEIPT, data: {transactionID}}); + + it.each<[string, AnyRequest[], ReturnType]>([ + ['empty queue', [], {conflictAction: {type: 'push'}}], + ['another transaction', [replace('2')], {conflictAction: {type: 'push'}}], + [ + 'multiple replacements with dependencies', + [replace('1'), {command: WRITE_COMMANDS.OPEN_REPORT, data: {reportID: '3'}}, replace('2'), replace('1')], + {conflictAction: {type: 'delete', indices: [0, 3], pushNewRequest: true}}, + ], + ['same transaction detach', [replace('1'), detach('1'), replace('1')], {conflictAction: {type: 'delete', indices: [2], pushNewRequest: true}}], + ['another transaction detach', [replace('1'), detach('2'), replace('1')], {conflictAction: {type: 'delete', indices: [0, 2], pushNewRequest: true}}], + ['previously attempted replacement', [replace('1'), replace('1', true), replace('1')], {conflictAction: {type: 'delete', indices: [2], pushNewRequest: true}}], + ])('preserves receipt history and unrelated requests with %s', (_case, persistedRequests, expected) => { + // Given waiting requests that may include a receipt history boundary or another transaction + // When a new replacement for transaction 1 is prepared + const result = resolveReplaceReceiptConflicts(persistedRequests, '1'); + + // Then only eligible unsent uploads are removed and the new upload is appended after its dependencies + expect(result).toEqual(expected); + }); + + it('returns the same result without mutating requests when evaluated twice', () => { + // Given frozen requests, since preparation and insertion both evaluate the resolver + const persistedRequests = Object.freeze([Object.freeze(replace('1')), Object.freeze(replace('1'))]); + + // When both phases resolve the same requests + const first = resolveReplaceReceiptConflicts([...persistedRequests], '1'); + const second = resolveReplaceReceiptConflicts([...persistedRequests], '1'); + + // Then both phases agree without changing the queue or performing optimistic cleanup + expect(first).toEqual(second); + expect(first).toEqual({conflictAction: {type: 'delete', indices: [0, 1], pushNewRequest: true}}); + }); + }); + it.each([['OpenApp'], ['ReconnectApp']])('resolveDuplicationConflictAction when %s do not exist in the queue should push %i', (command) => { const persistedRequests = [{command: 'OpenReport'}, {command: 'AddComment'}, {command: 'CloseAccount'}]; const result = resolveDuplicationConflictAction(persistedRequests, (request) => request.command === command); diff --git a/tests/unit/SequentialQueueTest.ts b/tests/unit/SequentialQueueTest.ts index 7e5abb8ae082..10b58c70bc2d 100644 --- a/tests/unit/SequentialQueueTest.ts +++ b/tests/unit/SequentialQueueTest.ts @@ -1,4 +1,4 @@ -import {resolveOpenAppDuplicationConflictAction, resolveReconnectDuplicationConflictAction} from '@libs/actions/RequestConflictUtils'; +import {resolveOpenAppDuplicationConflictAction, resolveReconnectDuplicationConflictAction, resolveReplaceReceiptConflicts} from '@libs/actions/RequestConflictUtils'; import {isClientTheLeader} from '@libs/ActiveClientManager'; import type {WriteCommand} from '@libs/API/types'; import {WRITE_COMMANDS} from '@libs/API/types'; @@ -163,6 +163,33 @@ describe('SequentialQueue', () => { } }); + it('should keep the latest replacement after its dependencies and before an immediately queued detach', async () => { + SequentialQueue.pause(); + try { + // Given an upload followed by the request that opens its transaction thread + await SequentialQueue.push({command: WRITE_COMMANDS.REPLACE_RECEIPT, data: {transactionID: '1', receiptState: 'first'}}); + await SequentialQueue.push({command: WRITE_COMMANDS.OPEN_REPORT, data: {reportID: '2'}}); + + // When a new upload supersedes it and a detach is queued without waiting for persistence + const replacementPush = SequentialQueue.push({ + command: WRITE_COMMANDS.REPLACE_RECEIPT, + data: {transactionID: '1', receiptState: 'latest'}, + checkAndFixConflictingRequest: (persistedRequests) => resolveReplaceReceiptConflicts(persistedRequests, '1'), + }); + const detachPush = SequentialQueue.push({command: WRITE_COMMANDS.DETACH_RECEIPT, data: {transactionID: '1'}}); + await Promise.all([replacementPush, detachPush]); + + // Then the dependency precedes the surviving upload, and the final detach cannot be overtaken + expect(getAll().map((queuedRequest) => [queuedRequest.command, queuedRequest.data?.receiptState])).toEqual([ + [WRITE_COMMANDS.OPEN_REPORT, undefined], + [WRITE_COMMANDS.REPLACE_RECEIPT, 'latest'], + [WRITE_COMMANDS.DETACH_RECEIPT, undefined], + ]); + } finally { + SequentialQueue.unpause(); + } + }); + it('should push two requests with conflict resolution and push', () => { SequentialQueue.push(request); const requestWithConflictResolution: Request = { @@ -221,6 +248,31 @@ describe('SequentialQueue', () => { } }); + it('keeps an ongoing receipt upload while collapsing only waiting replacements', async () => { + // Given an upload that may already have reached the server + mockFetch.pause(); + try { + await SequentialQueue.push({command: WRITE_COMMANDS.REPLACE_RECEIPT, data: {transactionID: '1', receiptState: 'ongoing'}}); + await waitForBatchedUpdates(); + expect(getOngoingRequest()?.data?.receiptState).toBe('ongoing'); + + // When two newer receipt uploads are queued while it is in flight + for (const receiptState of ['waiting', 'latest']) { + await SequentialQueue.push({ + command: WRITE_COMMANDS.REPLACE_RECEIPT, + data: {transactionID: '1', receiptState}, + checkAndFixConflictingRequest: (persistedRequests) => resolveReplaceReceiptConflicts(persistedRequests, '1'), + }); + } + + // Then the ongoing request survives and only the latest waiting file remains + expect(getOngoingRequest()?.data?.receiptState).toBe('ongoing'); + expect(getAll()).toEqual([expect.objectContaining({data: expect.objectContaining({receiptState: 'latest'})})]); + } finally { + await mockFetch.resume(); + } + }); + it('should replace request in queue while a similar one is ongoing', async () => { mockFetch.pause(); try { From d2001c1c67fe73a3f78d8520adb79a38a848dc05 Mon Sep 17 00:00:00 2001 From: "Kevin Brian Bader (via MelvinBot)" Date: Fri, 20 Nov 2026 00:42:11 +0000 Subject: [PATCH 2/3] Normalize inherited receipt snapshots on both rollback paths Co-authored-by: Kevin Brian Bader --- src/libs/actions/IOU/Receipt.ts | 46 +++++++++++++++----------- tests/actions/IOUTest/ReceiptTest.ts | 20 +++++------ tests/unit/RequestConflictUtilsTest.ts | 4 +-- 3 files changed, 39 insertions(+), 31 deletions(-) diff --git a/src/libs/actions/IOU/Receipt.ts b/src/libs/actions/IOU/Receipt.ts index bf9801a212e9..603733aad83a 100644 --- a/src/libs/actions/IOU/Receipt.ts +++ b/src/libs/actions/IOU/Receipt.ts @@ -253,6 +253,30 @@ function getOriginalRollbackUpdates(supersededRequests: AnyRequest[]): Map>, @@ -265,24 +289,8 @@ function inheritOriginalRollback( const originalTransactionValue: unknown = originalUpdates.get(transactionKey)?.value; const inheritedFailureData = failureData.map((update): OnyxUpdate => { const originalUpdate = originalUpdates.get(update.key); - const snapshotValue: unknown = (originalUpdate ?? update).value; - // A search first opened during these replacements also contains an unsent file, not the server's receipt. - if ( - update.key.startsWith(ONYXKEYS.COLLECTION.SNAPSHOT) && - isRecord(originalTransactionValue) && - 'receipt' in originalTransactionValue && - isRecord(snapshotValue) && - isRecord(snapshotValue.data) && - isRecord(snapshotValue.data[transactionKey]) - ) { - const snapshotUpdate: AnyOnyxUpdate = { - ...(originalUpdate ?? update), - value: { - ...snapshotValue, - data: {...snapshotValue.data, [transactionKey]: {...snapshotValue.data[transactionKey], receipt: originalTransactionValue.receipt}}, - }, - }; - return snapshotUpdate; + if (update.key.startsWith(ONYXKEYS.COLLECTION.SNAPSHOT)) { + return withOriginalSnapshotReceipt(originalUpdate ?? update, originalTransactionValue, transactionKey); } if (!originalUpdate) { return update; @@ -302,7 +310,7 @@ function inheritOriginalRollback( const ownKeys = new Set(failureData.map((update) => update.key)); for (const [key, originalUpdate] of originalUpdates) { if (!ownKeys.has(key)) { - inheritedFailureData.push(originalUpdate); + inheritedFailureData.push(withOriginalSnapshotReceipt(originalUpdate, originalTransactionValue, transactionKey)); } } return inheritedFailureData; diff --git a/tests/actions/IOUTest/ReceiptTest.ts b/tests/actions/IOUTest/ReceiptTest.ts index a7ca116be314..f6f264920a56 100644 --- a/tests/actions/IOUTest/ReceiptTest.ts +++ b/tests/actions/IOUTest/ReceiptTest.ts @@ -17,6 +17,7 @@ import * as API from '@src/libs/API'; import * as SearchQueryUtils from '@src/libs/SearchQueryUtils'; import ONYXKEYS from '@src/ONYXKEYS'; import type {Policy, SearchResults} from '@src/types/onyx'; +import type {AnyRequest} from '@src/types/onyx/Request'; import type Transaction from '@src/types/onyx/Transaction'; import type {ReceiptError} from '@src/types/onyx/Transaction'; @@ -1057,6 +1058,7 @@ describe('actions/IOU/Receipt', () => { describe('offline receipt replacements', () => { const transactionID = '107135'; + const transactionKey = `${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}` as const; const threadReportID = '107136'; const snapshotHash = 918273645; const originalReceipt = {source: 'original.jpg', filename: 'original.jpg', state: CONST.IOU.RECEIPT_STATE.OPEN}; @@ -1068,7 +1070,7 @@ describe('actions/IOU/Receipt', () => { const getThread = () => getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT}${threadReportID}`); const getActions = () => getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${threadReportID}`); const getQueuedReplacement = () => getAllPersistedRequests().find((request) => request.command === WRITE_COMMANDS.REPLACE_RECEIPT); - const getAuditActionIDs = (request: ReturnType) => + const getAuditActionIDs = (request: AnyRequest | undefined) => [request?.data?.reportActionID, request?.data?.receiptRemovedReportActionID].filter((id): id is string => typeof id === 'string' && id !== '0'); const replaceWithLatestState = async (source: string, isSameReceipt?: boolean) => { @@ -1122,10 +1124,7 @@ describe('actions/IOU/Receipt', () => { }); const transaction = {...createRandomTransaction(Number(transactionID)), receipt: originalReceipt}; await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`, transaction); - await Onyx.set(`${ONYXKEYS.COLLECTION.SNAPSHOT}${snapshotHash}`, { - // @ts-expect-error: Only the transaction data is needed in this snapshot fixture - data: {[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`]: transaction}, - }); + await Onyx.set(`${ONYXKEYS.COLLECTION.SNAPSHOT}${snapshotHash}`, createMock({data: {[transactionKey]: {receipt: originalReceipt}}})); jest.spyOn(SearchQueryUtils, 'getCurrentSearchQueryJSON').mockReturnValue(createMock({hash: snapshotHash})); }); @@ -1212,15 +1211,16 @@ describe('actions/IOU/Receipt', () => { const secondSnapshotHash = snapshotHash + 1; if (opensAnotherSearch) { const transaction = await getTransaction(); - await Onyx.set(`${ONYXKEYS.COLLECTION.SNAPSHOT}${secondSnapshotHash}`, { - // @ts-expect-error: Only transaction data is needed in this search fixture - data: {[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`]: transaction}, - }); + await Onyx.set(`${ONYXKEYS.COLLECTION.SNAPSHOT}${secondSnapshotHash}`, createMock({data: {[transactionKey]: {receipt: transaction?.receipt}}})); } - // When the user switches searches or leaves search, replaces again, and the surviving upload fails + // When the user replaces in another search or outside search, then replaces once more outside search jest.mocked(SearchQueryUtils.getCurrentSearchQueryJSON).mockReturnValue(opensAnotherSearch ? createMock({hash: secondSnapshotHash}) : undefined); await replaceWithLatestState('second.jpg'); + jest.mocked(SearchQueryUtils.getCurrentSearchQueryJSON).mockReturnValue(undefined); + await replaceWithLatestState('third.jpg'); + + // Then a failed upload restores even snapshots absent from its own failure data mockFetch.fail(); await reconnect(); diff --git a/tests/unit/RequestConflictUtilsTest.ts b/tests/unit/RequestConflictUtilsTest.ts index 5a2730d82e94..5604fb18675f 100644 --- a/tests/unit/RequestConflictUtilsTest.ts +++ b/tests/unit/RequestConflictUtilsTest.ts @@ -12,7 +12,7 @@ import { } from '@libs/actions/RequestConflictUtils'; import {WRITE_COMMANDS} from '@libs/API/types'; -import type {AnyRequest} from '@src/types/onyx/Request'; +import type {AnyRequest, ConflictActionData} from '@src/types/onyx/Request'; import type {OnyxKey} from 'react-native-onyx'; @@ -23,7 +23,7 @@ describe('RequestConflictUtils', () => { const replace = (transactionID: string, isRollback?: boolean): AnyRequest => ({command: WRITE_COMMANDS.REPLACE_RECEIPT, data: {transactionID}, isRollback}); const detach = (transactionID: string): AnyRequest => ({command: WRITE_COMMANDS.DETACH_RECEIPT, data: {transactionID}}); - it.each<[string, AnyRequest[], ReturnType]>([ + it.each<[string, AnyRequest[], ConflictActionData]>([ ['empty queue', [], {conflictAction: {type: 'push'}}], ['another transaction', [replace('2')], {conflictAction: {type: 'push'}}], [ From 863b61386aac97f71a19f7066b225aaf27883490 Mon Sep 17 00:00:00 2001 From: "Kevin Brian Bader (via MelvinBot)" Date: Fri, 20 Nov 2026 02:29:30 +0000 Subject: [PATCH 3/3] Preserve intervening thread activity when receipt uploads fail Co-authored-by: Kevin Brian Bader --- src/libs/actions/IOU/Receipt.ts | 33 ++++++++++- tests/actions/IOUTest/ReceiptTest.ts | 83 ++++++++++++++++++++++++++-- 2 files changed, 110 insertions(+), 6 deletions(-) diff --git a/src/libs/actions/IOU/Receipt.ts b/src/libs/actions/IOU/Receipt.ts index 603733aad83a..4c34a73ce195 100644 --- a/src/libs/actions/IOU/Receipt.ts +++ b/src/libs/actions/IOU/Receipt.ts @@ -277,11 +277,39 @@ function withOriginalSnapshotReceipt(update: AnyOnyxUpdate, originalTransactionV }; } +/** Undo receipt timestamps without rewinding activity that happened between the discarded uploads. */ +function inheritReportTimestamps(update: AnyOnyxUpdate, supersededRequests: AnyRequest[]): AnyOnyxUpdate { + const key: unknown = update.key; + if (typeof key !== 'string' || !isRecord(update.value)) { + return update; + } + const value = {...update.value}; + const actionsKey = `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${key.slice(ONYXKEYS.COLLECTION.REPORT.length)}`; + // A newer discarded upload may itself have inherited a rollback that preserves an intervening comment. + for (const request of supersededRequests.toReversed()) { + // Optimistic updates are not persisted, but the failed receipt-added action retains the timestamp they wrote. + const addedActionID = getStringField(request, 'reportActionID'); + const actionsValue: unknown = request.failureData?.find((entry) => entry.key === actionsKey)?.value; + const addedAction = addedActionID && isRecord(actionsValue) ? actionsValue[addedActionID] : undefined; + const failureValue: unknown = request.failureData?.find((entry) => entry.key === update.key)?.value; + if (!isRecord(addedAction) || typeof addedAction.created !== 'string' || !isRecord(failureValue)) { + continue; + } + for (const field of ['lastVisibleActionCreated', 'lastReadTime'] as const) { + if (field in failureValue && value[field] === addedAction.created) { + value[field] = failureValue[field]; + } + } + } + return {...update, value}; +} + /** Restore the state before the unsent replacements, while retaining the latest upload's errors and retry data. */ function inheritOriginalRollback( failureData: Array>, originalUpdates: Map, transactionKey: string, + supersededRequests: AnyRequest[], ): Array> { if (originalUpdates.size === 0) { return failureData; @@ -292,6 +320,9 @@ function inheritOriginalRollback( if (update.key.startsWith(ONYXKEYS.COLLECTION.SNAPSHOT)) { return withOriginalSnapshotReceipt(originalUpdate ?? update, originalTransactionValue, transactionKey); } + if (update.key.startsWith(ONYXKEYS.COLLECTION.REPORT)) { + return inheritReportTimestamps(update, supersededRequests); + } if (!originalUpdate) { return update; } @@ -615,7 +646,7 @@ function replaceReceipt({ API.write( WRITE_COMMANDS.REPLACE_RECEIPT, parameters, - {optimisticData, successData, failureData: inheritOriginalRollback(failureData, originalRollbackUpdates, transactionKey)}, + {optimisticData, successData, failureData: inheritOriginalRollback(failureData, originalRollbackUpdates, transactionKey, supersededRequests)}, {checkAndFixConflictingRequest: (requests) => resolveReplaceReceiptConflicts(requests, transactionID)}, ); } diff --git a/tests/actions/IOUTest/ReceiptTest.ts b/tests/actions/IOUTest/ReceiptTest.ts index f6f264920a56..906f5b5ff4e6 100644 --- a/tests/actions/IOUTest/ReceiptTest.ts +++ b/tests/actions/IOUTest/ReceiptTest.ts @@ -5,7 +5,9 @@ import type {SearchQueryJSON} from '@components/Search/types'; import {detachReceipt, replaceReceipt, setMoneyRequestReceipt} from '@libs/actions/IOU/Receipt'; import initOnyxDerivedValues from '@libs/actions/OnyxDerived'; +import {addComment} from '@libs/actions/Report'; import {WRITE_COMMANDS} from '@libs/API/types'; +import DateUtils from '@libs/DateUtils'; import {flush as flushSequentialQueue, waitForIdle} from '@libs/Network/SequentialQueue'; import type * as PolicyUtils from '@libs/PolicyUtils'; @@ -1066,7 +1068,7 @@ describe('actions/IOU/Receipt', () => { const currentUserPersonalDetails = {accountID: RORY_ACCOUNT_ID, email: RORY_EMAIL}; let mockFetch: MockFetch; - const getTransaction = () => getOnyxValue(`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`); + const getTransaction = () => getOnyxValue(transactionKey); const getThread = () => getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT}${threadReportID}`); const getActions = () => getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${threadReportID}`); const getQueuedReplacement = () => getAllPersistedRequests().find((request) => request.command === WRITE_COMMANDS.REPLACE_RECEIPT); @@ -1182,7 +1184,7 @@ describe('actions/IOU/Receipt', () => { const transaction = await getTransaction(); expect(transaction?.receipt?.source).toBe(originalReceipt.source); const snapshot = await getOnyxValue(`${ONYXKEYS.COLLECTION.SNAPSHOT}${snapshotHash}`); - expect(snapshot?.data?.[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`]?.receipt?.source).toBe(originalReceipt.source); + expect(snapshot?.data?.[transactionKey]?.receipt?.source).toBe(originalReceipt.source); expect(Object.values(transaction?.errors ?? {}).at(0)).toEqual(expect.objectContaining({source: 'third.jpg'})); expect((await getThread())?.lastVisibleActionCreated).toBe(originalTimestamp); expect((await getThread())?.lastReadTime).toBe(originalTimestamp); @@ -1192,6 +1194,77 @@ describe('actions/IOU/Receipt', () => { } }); + it('preserves a successful intervening comment when the surviving receipt upload fails', async () => { + // Given a comment queued between receipt replacements, with distinct timestamps for each activity + const timeSpy = jest.spyOn(DateUtils, 'getDBTime').mockReturnValue('2026-01-01 00:00:01.000'); + await replaceWithLatestState('first.jpg'); + const supersededIDs = getAuditActionIDs(getQueuedReplacement()); + timeSpy.mockReturnValue('2026-01-01 00:00:02.000'); + addComment({ + report: await getThread(), + notifyReportID: threadReportID, + ancestors: [], + text: 'Keep this comment after the receipt upload fails', + timezoneParam: CONST.DEFAULT_TIME_ZONE, + currentUserAccountID: RORY_ACCOUNT_ID, + delegateAccountID: undefined, + conciergeReportID: undefined, + }); + await waitForBatchedUpdates(); + const commentThread = await getThread(); + const commentRequest = getAllPersistedRequests().find((request) => request.command === WRITE_COMMANDS.ADD_COMMENT); + const commentID = String(commentRequest?.data?.reportActionID); + + // When further replacements discard both earlier uploads, only the comment and latest upload are sent + timeSpy.mockReturnValue('2026-01-01 00:00:03.000'); + await replaceWithLatestState('second.jpg'); + supersededIDs.push(...getAuditActionIDs(getQueuedReplacement())); + timeSpy.mockReturnValue('2026-01-01 00:00:04.000'); + await replaceWithLatestState('third.jpg'); + expect(getAllPersistedRequests().map((request) => request.command)).toEqual([WRITE_COMMANDS.ADD_COMMENT, WRITE_COMMANDS.REPLACE_RECEIPT]); + mockFetch.mockAPICommand(WRITE_COMMANDS.REPLACE_RECEIPT, () => ({jsonCode: 400})); + await reconnect(); + + // Then comment success survives upload rollback, including its activity and read timestamps + expectAPICommandToHaveBeenCalled(WRITE_COMMANDS.ADD_COMMENT, 1); + expectAPICommandToHaveBeenCalled(WRITE_COMMANDS.REPLACE_RECEIPT, 1); + const thread = await getThread(); + expect(thread?.lastVisibleActionCreated).toBe(commentThread?.lastVisibleActionCreated); + expect(thread?.lastReadTime).toBe(commentThread?.lastReadTime); + expect(thread?.lastVisibleActionCreated).not.toBe(originalTimestamp); + expect(thread?.lastReadTime).not.toBe(originalTimestamp); + const actions = await getActions(); + expect(actions?.[commentID]).toBeDefined(); + expect(actions?.[commentID]?.pendingAction).toBeFalsy(); + expect(actions?.[commentID]?.isOptimisticAction).toBeFalsy(); + expect(actions?.[commentID]?.errors).toBeFalsy(); + for (const id of supersededIDs) { + expect(actions?.[id]).toBeUndefined(); + } + const transaction = await getTransaction(); + expect(transaction?.receipt?.source).toBe(originalReceipt.source); + expect(Object.values(transaction?.errors ?? {}).at(0)).toEqual(expect.objectContaining({source: 'third.jpg'})); + }); + + it.each(['lastVisibleActionCreated', 'lastReadTime'] as const)('preserves independently advanced %s on upload failure', async (timestampField) => { + // Given activity that advances only one timestamp after an unsent receipt replacement + jest.spyOn(DateUtils, 'getDBTime').mockReturnValue('2026-01-01 00:00:01.000'); + await replaceWithLatestState('first.jpg'); + const activityTimestamp = '2026-01-01 00:00:02.000'; + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${threadReportID}`, {[timestampField]: activityTimestamp}); + + // When the next replacement fails, only timestamps written by the discarded upload should be undone + jest.mocked(DateUtils.getDBTime).mockReturnValue('2026-01-01 00:00:03.000'); + await replaceWithLatestState('second.jpg'); + mockFetch.fail(); + await reconnect(); + + // Then the activity timestamp survives while the other timestamp returns to its original baseline + const thread = await getThread(); + expect(thread?.lastVisibleActionCreated).toBe(timestampField === 'lastVisibleActionCreated' ? activityTimestamp : originalTimestamp); + expect(thread?.lastReadTime).toBe(timestampField === 'lastReadTime' ? activityTimestamp : originalTimestamp); + }); + it('sends a crop of an unsent replacement with replacement audit actions', async () => { // Given a new receipt the server has not seen await replaceWithLatestState('first.jpg'); @@ -1220,15 +1293,15 @@ describe('actions/IOU/Receipt', () => { jest.mocked(SearchQueryUtils.getCurrentSearchQueryJSON).mockReturnValue(undefined); await replaceWithLatestState('third.jpg'); - // Then a failed upload restores even snapshots absent from its own failure data + // And when the surviving upload fails mockFetch.fail(); await reconnect(); - // Then no touched snapshot rolls back to the first file, whose upload was discarded + // Then no touched snapshot rolls back to the first file, including snapshots absent from the latest failure data expect((await getTransaction())?.receipt?.source).toBe(originalReceipt.source); for (const hash of opensAnotherSearch ? [snapshotHash, secondSnapshotHash] : [snapshotHash]) { const snapshot = await getOnyxValue(`${ONYXKEYS.COLLECTION.SNAPSHOT}${hash}`); - expect(snapshot?.data?.[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`]?.receipt?.source).toBe(originalReceipt.source); + expect(snapshot?.data?.[transactionKey]?.receipt?.source).toBe(originalReceipt.source); } });