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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions src/libs/Network/SequentialQueue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -830,12 +830,16 @@ async function handleConflictActions<TKey extends OnyxKey>(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, {
Expand Down
190 changes: 174 additions & 16 deletions src/libs/actions/IOU/Receipt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -226,6 +231,127 @@ 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<string, AnyOnyxUpdate> {
const originalUpdates = new Map<string, AnyOnyxUpdate>();
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;
}

/** A search first opened during these replacements must not restore a file that was never uploaded. */
function withOriginalSnapshotReceipt(update: AnyOnyxUpdate, originalTransactionValue: unknown, transactionKey: string): AnyOnyxUpdate {
const key: unknown = update.key;
const snapshotValue: unknown = update.value;
if (
typeof key !== 'string' ||
!key.startsWith(ONYXKEYS.COLLECTION.SNAPSHOT) ||
!isRecord(originalTransactionValue) ||
!('receipt' in originalTransactionValue) ||
!isRecord(snapshotValue) ||
!isRecord(snapshotValue.data) ||
!isRecord(snapshotValue.data[transactionKey])
) {
return update;
}
return {
...update,
value: {
...snapshotValue,
data: {...snapshotValue.data, [transactionKey]: {...snapshotValue.data[transactionKey], receipt: originalTransactionValue.receipt}},
},
};
}

/** 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<OnyxUpdate<ReplaceReceiptOnyxKey>>,
originalUpdates: Map<string, AnyOnyxUpdate>,
transactionKey: string,
supersededRequests: AnyRequest[],
): Array<OnyxUpdate<ReplaceReceiptOnyxKey>> {
if (originalUpdates.size === 0) {
return failureData;
}
const originalTransactionValue: unknown = originalUpdates.get(transactionKey)?.value;
const inheritedFailureData = failureData.map((update): OnyxUpdate<ReplaceReceiptOnyxKey> => {
const originalUpdate = originalUpdates.get(update.key);
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;
}
if (update.key !== transactionKey) {
return originalUpdate;
Comment on lines +329 to +330

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve intervening thread activity when inheriting rollback

If a user replaces a receipt offline, posts a comment in the expense thread, and then replaces the receipt again, this branch replaces the latest request's report rollback with the timestamps from before the first replacement. Posting the comment updates both lastVisibleActionCreated and lastReadTime in src/libs/actions/Report/index.ts, and the conflict resolver preserves that comment request ahead of the surviving upload. If the comment succeeds but the upload fails, its inherited rollback therefore rewinds the thread timestamps past a successfully posted comment, leaving incorrect activity ordering and read state. Preserve intervening non-superseded activity when calculating the report rollback instead of unconditionally taking the oldest report update.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed by source inspection: Report/index.ts:1034–1040 advances both timestamps for a comment, but Receipt.ts:298–299 still unconditionally inherits the older report rollback. If the retained comment succeeds and the surviving upload fails, the rollback can rewind past the comment.

Simply keeping the newest report rollback would instead retain timestamps from discarded receipt actions. The targeted fix should preserve each timestamp belonging to intervening activity and inherit the original baseline only for timestamps attributable to superseded receipt actions, with a regression covering comment success followed by upload failure.

The snapshot update does not change this behavior, so this finding remains open. ikevin127, should I implement this timestamp change as well?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rechecked: this P2 is valid and remains open. Report/index.ts:1034–1040 advances both timestamps for a comment, but Receipt.ts:298–299 inherits the oldest report rollback. A successful intervening comment followed by upload failure can therefore rewind activity/read timestamps.

The snapshot fix does not address this. A timestamp fix needs to preserve intervening comment activity without retaining timestamps belonging only to discarded receipt actions, with a regression covering comment success followed by upload failure. The current request asks for a reply to this finding; no timestamp change was made.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Implemented in 863b6138. Receipt.ts:280–307 now handles each timestamp independently: it unwinds a superseded receipt action's timestamp through that request's rollback, but preserves intervening activity. It uses the persisted receipt-added action timestamp, since queued requests do not retain optimistic updates.

Added the queued comment-success/upload-failure regression and independent-field cases. All three new cases failed before the fix; 195 focused tests pass afterward. Full lint, changed-file lint/spelling, typecheck, and Storybook smoke pass. Browser verification remains blocked by unavailable usable UI/failure injection; details are in AI Tests.

}
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<string>(failureData.map((update) => update.key));
for (const [key, originalUpdate] of originalUpdates) {
if (!ownKeys.has(key)) {
inheritedFailureData.push(withOriginalSnapshotReceipt(originalUpdate, originalTransactionValue, transactionKey));
}
}
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,
Expand Down Expand Up @@ -253,6 +379,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.
Expand All @@ -267,23 +413,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,
Expand Down Expand Up @@ -328,15 +477,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<OnyxUpdate<ReplaceReceiptOnyxKey>> = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`,
Expand Down Expand Up @@ -431,6 +572,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(
Expand Down Expand Up @@ -485,12 +638,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, supersededRequests)},
{checkAndFixConflictingRequest: (requests) => resolveReplaceReceiptConflicts(requests, transactionID)},
);
}

function setMoneyRequestReceipt(
Expand Down
32 changes: 32 additions & 0 deletions src/libs/actions/RequestConflictUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -431,7 +431,39 @@ function resolveVacationDelegateDeletionConflicts<TKey extends OnyxKey>(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,
Expand Down
11 changes: 11 additions & 0 deletions src/libs/telemetry/ReceiptObservability.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down Expand Up @@ -395,6 +405,7 @@ export {
logReceiptEnqueued,
logReceiptDropped,
logReceiptGaveUp,
logReceiptSuperseded,
logReceiptStatFailed,
logReceiptAdoptFailed,
logCameraCaptureFailed,
Expand Down
Loading
Loading