diff --git a/src/ONYXKEYS.ts b/src/ONYXKEYS.ts index 9abf1a8d2639..f79fdffec872 100755 --- a/src/ONYXKEYS.ts +++ b/src/ONYXKEYS.ts @@ -1,4 +1,3 @@ -import type {OnyxUpdate} from 'react-native-onyx'; import type {ValueOf} from 'type-fest'; import type CONST from './CONST'; import type {OnboardingAccounting} from './CONST'; @@ -9,6 +8,7 @@ import type * as FormTypes from './types/form'; import type * as OnyxTypes from './types/onyx'; import type {Attendee, DistanceExpenseType, Participant} from './types/onyx/IOU'; import type Onboarding from './types/onyx/Onboarding'; +import type {AnyOnyxUpdate} from './types/onyx/Request'; import type AssertTypesEqual from './types/utils/AssertTypesEqual'; import type DeepValueOf from './types/utils/DeepValueOf'; @@ -1267,7 +1267,7 @@ type OnyxValuesMapping = { [ONYXKEYS.NVP_MUTED_PLATFORMS]: Partial>; [ONYXKEYS.NVP_PRIORITY_MODE]: ValueOf; [ONYXKEYS.NVP_BLOCKED_FROM_CONCIERGE]: OnyxTypes.BlockedFromConcierge; - [ONYXKEYS.QUEUE_FLUSHED_DATA]: OnyxUpdate[]; + [ONYXKEYS.QUEUE_FLUSHED_DATA]: AnyOnyxUpdate[]; // The value of this nvp is a string representation of the date when the block expires, or an empty string if the user is not blocked [ONYXKEYS.NVP_BLOCKED_FROM_CHAT]: string; @@ -1333,7 +1333,7 @@ type OnyxValuesMapping = { [ONYXKEYS.VERIFY_3DS_SUBSCRIPTION]: string; [ONYXKEYS.PREFERRED_THEME]: ValueOf; [ONYXKEYS.MAPBOX_ACCESS_TOKEN]: OnyxTypes.MapboxAccessToken; - [ONYXKEYS.ONYX_UPDATES_FROM_SERVER]: OnyxTypes.OnyxUpdatesFromServer; + [ONYXKEYS.ONYX_UPDATES_FROM_SERVER]: OnyxTypes.AnyOnyxUpdatesFromServer; [ONYXKEYS.ONYX_UPDATES_LAST_UPDATE_ID_APPLIED_TO_CLIENT]: number; [ONYXKEYS.MAX_CANVAS_AREA]: number; [ONYXKEYS.MAX_CANVAS_HEIGHT]: number; diff --git a/src/libs/API/index.ts b/src/libs/API/index.ts index eb31018caaa4..d06d92fec5a4 100644 --- a/src/libs/API/index.ts +++ b/src/libs/API/index.ts @@ -143,12 +143,12 @@ function processRequest(request: OnyxRequest, type: * All calls to API.write() will be persisted to disk as JSON with the params, successData, and failureData (or finallyData, if included in place of the former two values). * This is so that if the network is unavailable or the app is closed, we can send the WRITE request later. */ -function write(command: TCommand, apiCommandParameters: ApiRequestCommandParameters[TCommand]): Promise; +function write(command: TCommand, apiCommandParameters: ApiRequestCommandParameters[TCommand]): Promise>; function write( command: TCommand, apiCommandParameters: ApiRequestCommandParameters[TCommand], - onyxData: OnyxData, + onyxData?: OnyxData, conflictResolver?: RequestConflictResolver, ): Promise>; @@ -255,7 +255,7 @@ function paginate, config: PaginationConfig, -): Promise; +): Promise | void>; function paginate, TKey extends OnyxKey>( type: TRequestType, command: TCommand, diff --git a/src/libs/Authentication.ts b/src/libs/Authentication.ts index a33c6a15e1ba..da5b360d5487 100644 --- a/src/libs/Authentication.ts +++ b/src/libs/Authentication.ts @@ -1,6 +1,6 @@ import * as Sentry from '@sentry/react-native'; import Onyx from 'react-native-onyx'; -import type {OnyxEntry} from 'react-native-onyx'; +import type {OnyxEntry, OnyxKey} from 'react-native-onyx'; import CONFIG from '@src/CONFIG'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; @@ -56,7 +56,7 @@ Onyx.connectWithoutView({ }, }); -function Authenticate(parameters: Parameters): Promise { +function Authenticate(parameters: Parameters): Promise | void> { const commandName = 'Authenticate'; try { diff --git a/src/libs/ErrorUtils.ts b/src/libs/ErrorUtils.ts index 85f667446caf..351756738d0e 100644 --- a/src/libs/ErrorUtils.ts +++ b/src/libs/ErrorUtils.ts @@ -1,5 +1,5 @@ import mapValues from 'lodash/mapValues'; -import type {OnyxEntry} from 'react-native-onyx'; +import type {OnyxEntry, OnyxKey} from 'react-native-onyx'; import CONST from '@src/CONST'; import IntlStore from '@src/languages/IntlStore'; import type {TranslationPaths} from '@src/languages/types'; @@ -11,7 +11,7 @@ import DateUtils from './DateUtils'; // eslint-disable-next-line @typescript-eslint/no-deprecated import {translate, translateLocal} from './Localize'; -function getAuthenticateErrorMessage(response: Response): TranslationPaths { +function getAuthenticateErrorMessage(response: Response): TranslationPaths { switch (response.jsonCode) { case CONST.JSON_CODE.UNABLE_TO_RETRY: return 'session.offlineMessageRetry'; diff --git a/src/libs/Network/index.ts b/src/libs/Network/index.ts index e9240e6e4e93..7f54d6aeb645 100644 --- a/src/libs/Network/index.ts +++ b/src/libs/Network/index.ts @@ -1,3 +1,4 @@ +import type {OnyxKey} from 'react-native-onyx'; import * as ActiveClientManager from '@libs/ActiveClientManager'; import CONST from '@src/CONST'; import type {Request} from '@src/types/onyx'; @@ -31,7 +32,7 @@ function clearProcessQueueInterval() { /** * Perform a queued post request */ -function post(command: string, data: Record = {}, type = CONST.NETWORK.METHOD.POST, shouldUseSecure = false): Promise { +function post(command: string, data: Record = {}, type = CONST.NETWORK.METHOD.POST, shouldUseSecure = false): Promise> { return new Promise((resolve, reject) => { const request: Request = { command, diff --git a/src/libs/Notification/PushNotification/NotificationType.ts b/src/libs/Notification/PushNotification/NotificationType.ts index d209d970a53c..db2b10116d66 100644 --- a/src/libs/Notification/PushNotification/NotificationType.ts +++ b/src/libs/Notification/PushNotification/NotificationType.ts @@ -1,5 +1,6 @@ +import type {OnyxKey} from 'react-native-onyx'; import type {ValueOf} from 'type-fest'; -import type {OnyxServerUpdate} from '@src/types/onyx/OnyxUpdatesFromServer'; +import type {AnyOnyxServerUpdate, OnyxServerUpdate} from '@src/types/onyx/OnyxUpdatesFromServer'; const NotificationType = { REPORT_ACTION: 'reportAction', @@ -10,29 +11,35 @@ const NotificationType = { type NotificationTypes = ValueOf; type NotificationDataMap = { - [NotificationType.REPORT_ACTION]: ReportActionPushNotificationData; - [NotificationType.REPORT_COMMENT]: ReportActionPushNotificationData; - [NotificationType.TRANSACTION]: TransactionPushNotificationData; + [NotificationType.REPORT_ACTION]: AnyPushNotificationData; + [NotificationType.REPORT_COMMENT]: AnyPushNotificationData; + [NotificationType.TRANSACTION]: AnyPushNotificationData; }; -type PushNotificationData = ReportActionPushNotificationData | TransactionPushNotificationData; +/** + * This type was created as a solution during the migration away from the large OnyxKey union and is useful for contexts where the specific Onyx keys are not known ahead of time. + * It should only be used in legacy code where providing exact key types would require major restructuring. + */ +type AnyPushNotificationData = ReportActionPushNotificationData | TransactionPushNotificationData; + +type PushNotificationData = ReportActionPushNotificationData> | TransactionPushNotificationData>; -type BasePushNotificationData = { +type BasePushNotificationData = { title: string; subtitle: string; type: ValueOf; - onyxData?: OnyxServerUpdate[]; + onyxData?: TUpdate[]; lastUpdateID?: number; previousUpdateID?: number; hasPendingOnyxUpdates?: boolean; }; -type ReportActionPushNotificationData = BasePushNotificationData & { +type ReportActionPushNotificationData = BasePushNotificationData & { reportID: number; reportActionID: string; }; -type TransactionPushNotificationData = BasePushNotificationData & { +type TransactionPushNotificationData = BasePushNotificationData & { reportID: number; transactionID: number; }; @@ -42,4 +49,4 @@ type TransactionPushNotificationData = BasePushNotificationData & { * types of push notifications sent by our API. */ export default NotificationType; -export type {NotificationTypes, NotificationDataMap, PushNotificationData, ReportActionPushNotificationData, TransactionPushNotificationData}; +export type {NotificationTypes, NotificationDataMap, PushNotificationData, AnyPushNotificationData, ReportActionPushNotificationData, TransactionPushNotificationData}; diff --git a/src/libs/Notification/PushNotification/parsePushNotificationPayload.ts b/src/libs/Notification/PushNotification/parsePushNotificationPayload.ts index 213a2d5f95f2..a5337874ca8a 100644 --- a/src/libs/Notification/PushNotification/parsePushNotificationPayload.ts +++ b/src/libs/Notification/PushNotification/parsePushNotificationPayload.ts @@ -1,21 +1,21 @@ import type {JsonObject, JsonValue} from '@ua/react-native-airship'; import pako from 'pako'; import Log from '@libs/Log'; -import type {PushNotificationData} from './NotificationType'; +import type {AnyPushNotificationData} from './NotificationType'; const GZIP_MAGIC_NUMBER = '\x1f\x8b'; /** * Parse the payload of a push notification. On Android, some notification payloads are sent as a JSON string rather than an object */ -export default function parsePushNotificationPayload(payload: JsonValue | undefined): PushNotificationData | undefined { +export default function parsePushNotificationPayload(payload: JsonValue | undefined): AnyPushNotificationData | undefined { if (payload === undefined) { return undefined; } // No need to parse if it's already an object if (typeof payload !== 'string') { - return payload as PushNotificationData; + return payload as AnyPushNotificationData; } // Gzipped JSON String @@ -27,14 +27,14 @@ export default function parsePushNotificationPayload(payload: JsonValue | undefi const compressed = Uint8Array.from(binaryStringPayload, (x) => x.charCodeAt(0)); const decompressed = pako.inflate(compressed, {to: 'string'}); const jsonObject = JSON.parse(decompressed) as JsonObject; - return jsonObject as PushNotificationData; + return jsonObject as AnyPushNotificationData; } catch { Log.hmmm('[PushNotification] Failed to parse the payload as a Gzipped JSON string', payload); } // JSON String try { - return JSON.parse(payload) as JsonObject as PushNotificationData; + return JSON.parse(payload) as JsonObject as AnyPushNotificationData; } catch { Log.hmmm(`[PushNotification] Failed to parse the payload as a JSON string`, payload); } diff --git a/src/libs/Notification/PushNotification/subscribeToPushNotifications.ts b/src/libs/Notification/PushNotification/subscribeToPushNotifications.ts index bae1548cc5f6..d4fdf36cafbe 100644 --- a/src/libs/Notification/PushNotification/subscribeToPushNotifications.ts +++ b/src/libs/Notification/PushNotification/subscribeToPushNotifications.ts @@ -1,4 +1,5 @@ import {NativeModules} from 'react-native'; +import type {OnyxKey} from 'react-native-onyx'; import Onyx from 'react-native-onyx'; import applyOnyxUpdatesReliably from '@libs/actions/applyOnyxUpdatesReliably'; import Log from '@libs/Log'; @@ -12,7 +13,7 @@ import ONYXKEYS from '@src/ONYXKEYS'; import ROUTES from '@src/ROUTES'; import type {OnyxUpdatesFromServer} from '@src/types/onyx'; import PushNotification from '.'; -import type {PushNotificationData} from './NotificationType'; +import type {AnyPushNotificationData, PushNotificationData} from './NotificationType'; /** * Manage push notification subscriptions on sign-in/sign-out. @@ -53,7 +54,7 @@ Onyx.connectWithoutView({ }, }); -function applyOnyxData({reportID, onyxData, lastUpdateID, previousUpdateID, hasPendingOnyxUpdates = false}: PushNotificationData): Promise { +function applyOnyxData({reportID, onyxData, lastUpdateID, previousUpdateID, hasPendingOnyxUpdates = false}: PushNotificationData): Promise { Log.info(`[PushNotification] Applying onyx data in the ${Visibility.isVisible() ? 'foreground' : 'background'}`, false, {reportID, lastUpdateID}); const logMissingOnyxDataInfo = (isDataMissing: boolean): boolean => { @@ -66,7 +67,7 @@ function applyOnyxData({reportID, onyxData, lastUpdateID, previousUpdateID, hasP return true; }; - let updates: OnyxUpdatesFromServer; + let updates: OnyxUpdatesFromServer; if (hasPendingOnyxUpdates) { const isDataMissing = !lastUpdateID; logMissingOnyxDataInfo(isDataMissing); @@ -110,7 +111,7 @@ function applyOnyxData({reportID, onyxData, lastUpdateID, previousUpdateID, hasP .then(() => NativeModules.PushNotificationBridge?.finishBackgroundProcessing()); } -function navigateToReport({reportID}: PushNotificationData): Promise { +function navigateToReport({reportID}: AnyPushNotificationData): Promise { Log.info('[PushNotification] Navigating to report', false, {reportID}); Navigation.waitForProtectedRoutes().then(() => { diff --git a/src/libs/Pusher/types.ts b/src/libs/Pusher/types.ts index c264464a2dd5..4dc7bd73478c 100644 --- a/src/libs/Pusher/types.ts +++ b/src/libs/Pusher/types.ts @@ -3,7 +3,7 @@ import type PusherClass from 'pusher-js/with-encryption'; import type {Channel, ChannelAuthorizerGenerator} from 'pusher-js/with-encryption'; import type {LiteralUnion, ValueOf} from 'type-fest'; import type CONST from '@src/CONST'; -import type {OnyxUpdatesFromServer, ReportUserIsTyping} from '@src/types/onyx'; +import type {AnyOnyxUpdatesFromServer, ReportUserIsTyping} from '@src/types/onyx'; import type DeepValueOf from '@src/types/utils/DeepValueOf'; import type TYPE from './EventType'; @@ -41,7 +41,7 @@ type PusherEventMap = { type EventData = {chunk?: string; id?: string; index?: number; final?: boolean} & (EventName extends keyof PusherEventMap ? PusherEventMap[EventName] - : OnyxUpdatesFromServer); + : AnyOnyxUpdatesFromServer); type EventCallbackError = {type?: ValueOf; data: {code?: number; message?: string}}; diff --git a/src/libs/PusherUtils.ts b/src/libs/PusherUtils.ts index f6525ce0bd30..98eb4f994df6 100644 --- a/src/libs/PusherUtils.ts +++ b/src/libs/PusherUtils.ts @@ -1,8 +1,7 @@ import type {OnyxKey} from 'react-native-onyx'; import CONFIG from '@src/CONFIG'; import CONST from '@src/CONST'; -import type {OnyxUpdatesFromServer} from '@src/types/onyx'; -import type {OnyxServerUpdate} from '@src/types/onyx/OnyxUpdatesFromServer'; +import type {AnyOnyxUpdatesFromServer, OnyxServerUpdate} from '@src/types/onyx/OnyxUpdatesFromServer'; import Log from './Log'; import NetworkConnection from './NetworkConnection'; import Pusher from './Pusher'; @@ -35,10 +34,10 @@ function triggerMultiEventHandler(eventType: string, data: /** * Abstraction around subscribing to private user channel events. Handles all logs and errors automatically. */ -function subscribeToPrivateUserChannelEvent(eventName: string, accountID: string, onEvent: (pushJSON: OnyxUpdatesFromServer | PingPongEvent) => void) { +function subscribeToPrivateUserChannelEvent(eventName: string, accountID: string, onEvent: (pushJSON: AnyOnyxUpdatesFromServer | PingPongEvent) => void) { const pusherChannelName = getUserChannelName(accountID); - function logPusherEvent(pushJSON: OnyxUpdatesFromServer | PingPongEvent) { + function logPusherEvent(pushJSON: AnyOnyxUpdatesFromServer | PingPongEvent) { Log.info(`[Report] Handled ${eventName} event sent by Pusher`, false, pushJSON); } @@ -46,7 +45,7 @@ function subscribeToPrivateUserChannelEvent(eventName: string, accountID: string NetworkConnection.triggerReconnectionCallbacks('Pusher re-subscribed to private user channel'); } - function onEventPush(pushJSON: OnyxUpdatesFromServer | PingPongEvent) { + function onEventPush(pushJSON: AnyOnyxUpdatesFromServer | PingPongEvent) { logPusherEvent(pushJSON); onEvent(pushJSON); } diff --git a/src/libs/ReportActionsUtils.ts b/src/libs/ReportActionsUtils.ts index 8272da19eddf..89ebcdb3a330 100644 --- a/src/libs/ReportActionsUtils.ts +++ b/src/libs/ReportActionsUtils.ts @@ -3,7 +3,7 @@ import {format} from 'date-fns'; import {fastMerge, Str} from 'expensify-common'; import clone from 'lodash/clone'; import isEmpty from 'lodash/isEmpty'; -import type {NullishDeep, OnyxCollection, OnyxEntry, OnyxUpdate} from 'react-native-onyx'; +import type {NullishDeep, OnyxCollection, OnyxEntry, OnyxKey, OnyxUpdate} from 'react-native-onyx'; import Onyx from 'react-native-onyx'; import type {ValueOf} from 'type-fest'; import type {LocaleContextProps, LocalizedTranslate} from '@components/LocaleContextProvider'; @@ -1396,7 +1396,7 @@ function getFirstVisibleReportActionID(sortedReportActions: ReportAction[] = [], /** * @returns The latest report action in the `onyxData` or `null` if one couldn't be found */ -function getLatestReportActionFromOnyxData(onyxData: OnyxUpdate[] | null): NonNullable> | null { +function getLatestReportActionFromOnyxData(onyxData: Array> | null): NonNullable> | null { const reportActionUpdate = onyxData?.find((onyxUpdate) => onyxUpdate.key.startsWith(ONYXKEYS.COLLECTION.REPORT_ACTIONS)); if (!reportActionUpdate) { diff --git a/src/libs/ReportUtils.ts b/src/libs/ReportUtils.ts index 0b46c07e01e9..1b7aecd4aece 100644 --- a/src/libs/ReportUtils.ts +++ b/src/libs/ReportUtils.ts @@ -10764,7 +10764,11 @@ function getAncestors( * @param lastVisibleActionCreated Last visible action created of the child report * @param type The type of action in the child report */ -function getOptimisticDataForParentReportAction(report: Report | undefined, lastVisibleActionCreated: string, type: string): Array { +function getOptimisticDataForParentReportAction( + report: Report | undefined, + lastVisibleActionCreated: string, + type: string, +): Array | null> { if (!report || isEmptyObject(report)) { return []; } @@ -13256,4 +13260,5 @@ export type { PrepareOnboardingOnyxDataParams, SelfDMParameters, OptimisticReportAction, + OptimisticAnnounceChat, }; diff --git a/src/libs/actions/App.ts b/src/libs/actions/App.ts index 4a0518a18c78..17c0fb1a45f4 100644 --- a/src/libs/actions/App.ts +++ b/src/libs/actions/App.ts @@ -291,6 +291,13 @@ function getPolicyParamsForOpenOrReconnect(): Promise, -): OnyxData< - typeof ONYXKEYS.COLLECTION.REPORT | typeof ONYXKEYS.IS_LOADING_REPORT_DATA | typeof ONYXKEYS.HAS_LOADED_APP | typeof ONYXKEYS.IS_LOADING_APP | typeof ONYXKEYS.LAST_FULL_RECONNECT_TIME -> { +): OnyxData { const result: OnyxData< | typeof ONYXKEYS.IS_LOADING_REPORT_DATA | typeof ONYXKEYS.HAS_LOADED_APP @@ -494,7 +499,7 @@ function reconnectApp(updateIDFrom: OnyxEntry = 0) { * because it will follow patterns that are not recommended so we can be sure we're not putting the app in a unusable * state because of race conditions between reconnectApp and other pusher updates being applied at the same time. */ -function finalReconnectAppAfterActivatingReliableUpdates(): Promise { +function finalReconnectAppAfterActivatingReliableUpdates(): Promise> { console.debug(`[OnyxUpdates] Executing last reconnect app with promise`); return getPolicyParamsForOpenOrReconnect().then((policyParams) => { const params: ReconnectAppParams = {...policyParams}; @@ -513,7 +518,7 @@ function finalReconnectAppAfterActivatingReliableUpdates(): Promise { +function getMissingOnyxUpdates(updateIDFrom = 0, updateIDTo: number | string = 0): Promise> { console.debug(`[OnyxUpdates] Fetching missing updates updateIDFrom: ${updateIDFrom} and updateIDTo: ${updateIDTo}`); const parameters: GetMissingOnyxMessagesParams = { diff --git a/src/libs/actions/Delegate.ts b/src/libs/actions/Delegate.ts index e8126a072c89..8e45d3c29433 100644 --- a/src/libs/actions/Delegate.ts +++ b/src/libs/actions/Delegate.ts @@ -1,6 +1,6 @@ import HybridAppModule from '@expensify/react-native-hybrid-app'; import Onyx from 'react-native-onyx'; -import type {OnyxEntry, OnyxUpdate} from 'react-native-onyx'; +import type {OnyxEntry, OnyxKey, OnyxUpdate} from 'react-native-onyx'; import * as API from '@libs/API'; import type {AddDelegateParams as APIAddDelegateParams, RemoveDelegateParams as APIRemoveDelegateParams, UpdateDelegateRoleParams as APIUpdateDelegateRoleParams} from '@libs/API/parameters'; import {READ_COMMANDS, SIDE_EFFECT_REQUEST_COMMANDS, WRITE_COMMANDS} from '@libs/API/types'; @@ -695,7 +695,7 @@ function clearDelegateRolePendingAction({email, delegatedAccess}: ClearDelegateR Onyx.update(optimisticData); } -function restoreDelegateSession(authenticateResponse: Response) { +function restoreDelegateSession(authenticateResponse: Response) { Onyx.clear(KEYS_TO_PRESERVE_DELEGATE_ACCESS).then(() => { updateSessionAuthTokens(authenticateResponse?.authToken, authenticateResponse?.encryptedAuthToken); updateSessionUser(authenticateResponse?.accountID, authenticateResponse?.email); diff --git a/src/libs/actions/Domain.ts b/src/libs/actions/Domain.ts index 2fa5884f1719..9dd9765109ae 100644 --- a/src/libs/actions/Domain.ts +++ b/src/libs/actions/Domain.ts @@ -660,7 +660,7 @@ function clearAdminError(domainAccountID: number, accountID: number) { * Removes admin access for a domain member */ function revokeDomainAdminAccess(domainAccountID: number, accountID: number) { - const optimisticData: OnyxUpdate[] = [ + const optimisticData: Array> = [ { onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.DOMAIN_PENDING_ACTIONS}${domainAccountID}`, @@ -673,7 +673,7 @@ function revokeDomainAdminAccess(domainAccountID: number, accountID: number) { }, }, ]; - const successData: OnyxUpdate[] = [ + const successData: Array> = [ { onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.DOMAIN_PENDING_ACTIONS}${domainAccountID}`, @@ -686,7 +686,7 @@ function revokeDomainAdminAccess(domainAccountID: number, accountID: number) { }, }, ]; - const failureData: OnyxUpdate[] = [ + const failureData: Array> = [ { onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.DOMAIN_PENDING_ACTIONS}${domainAccountID}`, @@ -721,7 +721,7 @@ function revokeDomainAdminAccess(domainAccountID: number, accountID: number) { * Removes the domain */ function resetDomain(domainAccountID: number, domainName: string, domain: Domain) { - const optimisticData: OnyxUpdate[] = [ + const optimisticData: Array> = [ { onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.DOMAIN_PENDING_ACTIONS}${domainAccountID}`, @@ -735,7 +735,7 @@ function resetDomain(domainAccountID: number, domainName: string, domain: Domain value: null, }, ]; - const successData: OnyxUpdate[] = [ + const successData: Array> = [ { onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.DOMAIN_PENDING_ACTIONS}${domainAccountID}`, @@ -751,7 +751,7 @@ function resetDomain(domainAccountID: number, domainName: string, domain: Domain }, }, ]; - const failureData: OnyxUpdate[] = [ + const failureData: Array> = [ { onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.DOMAIN}${domainAccountID}`, @@ -803,7 +803,9 @@ function addMemberToDomain(domainAccountID: number, email: string, defaultSecuri const DOMAIN_SECURITY_GROUP = `${CONST.DOMAIN.DOMAIN_SECURITY_GROUP_PREFIX}${defaultSecurityGroupID}`; const optimisticAccountID = generateAccountID(email); - const optimisticData: OnyxUpdate[] = [ + const optimisticData: Array< + OnyxUpdate + > = [ { onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.DOMAIN}${domainAccountID}`, @@ -850,7 +852,9 @@ function addMemberToDomain(domainAccountID: number, email: string, defaultSecuri }, ]; - const successData: OnyxUpdate[] = [ + const successData: Array< + OnyxUpdate + > = [ { onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.DOMAIN_PENDING_ACTIONS}${domainAccountID}`, @@ -893,7 +897,7 @@ function addMemberToDomain(domainAccountID: number, email: string, defaultSecuri }, ]; - const failureData: OnyxUpdate[] = [ + const failureData: Array> = [ { onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.DOMAIN_ERRORS}${domainAccountID}`, @@ -966,7 +970,7 @@ function clearDomainMemberError(domainAccountID: number, accountID: number, emai * @param overrideProcessingReports "Force" flag. If true user will be removed regardless of if they have outstanding reports */ function closeUserAccount(domainAccountID: number, domain: string, targetEmail: string, securityGroupsData: UserSecurityGroupData, overrideProcessingReports = false) { - const optimisticData: OnyxUpdate[] = [ + const optimisticData: Array> = [ { onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.DOMAIN_PENDING_ACTIONS}${domainAccountID}`, @@ -985,7 +989,7 @@ function closeUserAccount(domainAccountID: number, domain: string, targetEmail: }, ]; - const successData: OnyxUpdate[] = [ + const successData: Array> = [ { onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.DOMAIN_PENDING_ACTIONS}${domainAccountID}`, @@ -1004,7 +1008,7 @@ function closeUserAccount(domainAccountID: number, domain: string, targetEmail: }, ]; - const failureData: OnyxUpdate[] = [ + const failureData: Array> = [ { onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.DOMAIN_ERRORS}${domainAccountID}`, diff --git a/src/libs/actions/IOU/Duplicate.ts b/src/libs/actions/IOU/Duplicate.ts index b39aa03729d3..da50ad37aa49 100644 --- a/src/libs/actions/IOU/Duplicate.ts +++ b/src/libs/actions/IOU/Duplicate.ts @@ -243,8 +243,12 @@ function mergeDuplicates({transactionThreadReportID: optimisticTransactionThread }, }; - const optimisticData: OnyxUpdate[] = []; - const failureData: OnyxUpdate[] = []; + const optimisticData: Array< + OnyxUpdate + > = []; + const failureData: Array< + OnyxUpdate + > = []; const successData: Array> = []; optimisticData.push( @@ -467,8 +471,8 @@ function resolveDuplicates(params: MergeDuplicatesParams) { }, }; - const optimisticData: OnyxUpdate[] = []; - const failureData: OnyxUpdate[] = []; + const optimisticData: Array> = []; + const failureData: Array> = []; optimisticData.push(optimisticTransactionData, ...optimisticTransactionViolations, ...optimisticHoldActions, ...optimisticHoldTransactionActions, optimisticReportActionData); failureData.push(failureTransactionData, ...failureTransactionViolations, ...failureHoldActions, ...failureHoldTransactionActions, failureReportActionData); diff --git a/src/libs/actions/IOU/Hold.ts b/src/libs/actions/IOU/Hold.ts index 8646c98d8895..e1c1b8e661eb 100644 --- a/src/libs/actions/IOU/Hold.ts +++ b/src/libs/actions/IOU/Hold.ts @@ -62,7 +62,16 @@ function putOnHold(transactionID: string, comment: string, initialReportID: stri const optimisticCreatedAction = buildOptimisticCreatedReportAction(currentUserEmail); - const optimisticData: OnyxUpdate[] = [ + const optimisticData: Array< + OnyxUpdate< + | typeof ONYXKEYS.COLLECTION.REPORT + | typeof ONYXKEYS.COLLECTION.REPORT_ACTIONS + | typeof ONYXKEYS.COLLECTION.REPORT_METADATA + | typeof ONYXKEYS.COLLECTION.TRANSACTION + | typeof ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS + | typeof ONYXKEYS.COLLECTION.NEXT_STEP + > + > = [ { onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`, diff --git a/src/libs/actions/IOU/Split.ts b/src/libs/actions/IOU/Split.ts index 5232242fcccf..8a0460e88099 100644 --- a/src/libs/actions/IOU/Split.ts +++ b/src/libs/actions/IOU/Split.ts @@ -1,6 +1,6 @@ import {eachDayOfInterval, format} from 'date-fns'; import {InteractionManager} from 'react-native'; -import type {OnyxCollection, OnyxEntry, OnyxKey, OnyxUpdate} from 'react-native-onyx'; +import type {OnyxCollection, OnyxEntry, OnyxUpdate} from 'react-native-onyx'; import Onyx from 'react-native-onyx'; import type {ValueOf} from 'type-fest'; import type {SearchContextProps} from '@components/Search/types'; @@ -85,7 +85,7 @@ import { mergePolicyRecentlyUsedCategories, mergePolicyRecentlyUsedCurrencies, } from './index'; -import type {BuildOnyxDataForMoneyRequestKeys, MoneyRequestInformationParams, OneOnOneIOUReport, StartSplitBilActionParams} from './index'; +import type {BuildOnyxDataForMoneyRequestKeys, MoneyRequestInformationParams, OneOnOneIOUReport, StartSplitBilActionParams, UpdateMoneyRequestDataKeys} from './index'; type IOURequestType = ValueOf; @@ -408,7 +408,19 @@ function startSplitBill({ }; } - const optimisticData: OnyxUpdate[] = [ + const optimisticData: Array< + OnyxUpdate< + | typeof ONYXKEYS.COLLECTION.REPORT + | typeof ONYXKEYS.NVP_QUICK_ACTION_GLOBAL_CREATE + | typeof ONYXKEYS.COLLECTION.REPORT_ACTIONS + | typeof ONYXKEYS.COLLECTION.TRANSACTION + | typeof ONYXKEYS.COLLECTION.REPORT_METADATA + | typeof ONYXKEYS.PERSONAL_DETAILS_LIST + | typeof ONYXKEYS.COLLECTION.POLICY_RECENTLY_USED_CATEGORIES + | typeof ONYXKEYS.RECENTLY_USED_CURRENCIES + | typeof ONYXKEYS.COLLECTION.POLICY_RECENTLY_USED_TAGS + > + > = [ { // Use set for new reports because it doesn't exist yet, is faster, // and we need the data to be available when we navigate to the chat page @@ -1089,9 +1101,11 @@ function updateSplitTransactions({ }) ?? []; changesInReportTotal -= splitExpensesTotal; - const successData = [] as OnyxUpdate[]; - const failureData = [] as OnyxUpdate[]; - const optimisticData = [] as OnyxUpdate[]; + const onyxData: OnyxData = { + successData: [], + failureData: [], + optimisticData: [], + }; // The split transactions can be in different reports, so we need to calculate the total for each report. const reportTotals = new Map(); @@ -1190,7 +1204,12 @@ function updateSplitTransactions({ const parsedComment = getParsedComment(Parser.htmlToMarkdown(transactionParams.comment ?? '')); transactionParams.comment = parsedComment; - const {transactionThreadReportID, createdReportActionIDForThread, onyxData, iouAction} = getMoneyRequestInformation({ + const { + transactionThreadReportID, + createdReportActionIDForThread, + onyxData: moneyRequestInformationOnyxData, + iouAction, + } = getMoneyRequestInformation({ participantParams, parentChatReport, policyParams, @@ -1212,7 +1231,7 @@ function updateSplitTransactions({ betas, }); - let updateMoneyRequestParamsOnyxData: OnyxData = {}; + let updateMoneyRequestParamsOnyxData: OnyxData = {}; const currentSplit = splits.at(index); // For existing split transactions, update the field change messages @@ -1278,9 +1297,9 @@ function updateSplitTransactions({ currentSplit.splitReportActionID = iouAction.reportActionID; } - optimisticData.push(...(onyxData.optimisticData ?? []), ...(updateMoneyRequestParamsOnyxData.optimisticData ?? [])); - successData.push(...(onyxData.successData ?? []), ...(updateMoneyRequestParamsOnyxData.successData ?? [])); - failureData.push(...(onyxData.failureData ?? []), ...(updateMoneyRequestParamsOnyxData.failureData ?? [])); + onyxData.optimisticData?.push(...(moneyRequestInformationOnyxData.optimisticData ?? []), ...(updateMoneyRequestParamsOnyxData.optimisticData ?? [])); + onyxData.successData?.push(...(moneyRequestInformationOnyxData.successData ?? []), ...(updateMoneyRequestParamsOnyxData.successData ?? [])); + onyxData.failureData?.push(...(moneyRequestInformationOnyxData.failureData ?? []), ...(updateMoneyRequestParamsOnyxData.failureData ?? [])); } // All transactions that were deleted in the split list will be marked as deleted in onyx @@ -1322,14 +1341,14 @@ function updateSplitTransactions({ isReportArchived || undeletedTransaction?.transactionID === forceDeleteSplitTransactionID, ); - optimisticData.push(...(deleteExpenseOptimisticData ?? [])); - successData.push(...(deleteExpenseSuccessData ?? [])); - failureData.push(...(deleteExpenseFailureData ?? [])); + onyxData.optimisticData?.push(...(deleteExpenseOptimisticData ?? [])); + onyxData.successData?.push(...(deleteExpenseSuccessData ?? [])); + onyxData.failureData?.push(...(deleteExpenseFailureData ?? [])); } if (!isReverseSplitOperation) { // Use SET to update originalTransaction more quickly in Onyx as compared to MERGE to prevent UI inconsistency - optimisticData.push({ + onyxData.optimisticData?.push({ onyxMethod: Onyx.METHOD.SET, key: `${ONYXKEYS.COLLECTION.TRANSACTION}${originalTransactionID}`, value: { @@ -1339,7 +1358,7 @@ function updateSplitTransactions({ }); // @ts-expect-error - will be solved in https://github.com/Expensify/App/issues/73830 - failureData.push({ + onyxData.failureData?.push({ onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.TRANSACTION}${originalTransactionID}`, value: originalTransaction, @@ -1366,18 +1385,18 @@ function updateSplitTransactions({ }, }; const transactionThread = getAllReports()?.[`${ONYXKEYS.COLLECTION.REPORT}${firstIOU.childReportID}`] ?? null; - optimisticData.push({ + onyxData.optimisticData?.push({ onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.REPORT}${firstIOU?.childReportID}`, value: null, }); - optimisticData.push({ + onyxData.optimisticData?.push({ onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${iouReport?.reportID}`, value: updatedReportAction, }); - failureData.push({ + onyxData.failureData?.push({ onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${iouReport?.reportID}`, value: { @@ -1387,14 +1406,14 @@ function updateSplitTransactions({ }, }, }); - failureData.push({ + onyxData.failureData?.push({ onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.REPORT}${firstIOU?.childReportID}`, value: transactionThread ?? null, }); } - optimisticData.push({ + onyxData.optimisticData?.push({ onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.SNAPSHOT}${searchContext?.currentSearchHash}`, value: { @@ -1405,7 +1424,7 @@ function updateSplitTransactions({ }); // @ts-expect-error - will be solved in https://github.com/Expensify/App/issues/73830 - failureData.push({ + onyxData.failureData?.push({ onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.SNAPSHOT}${searchContext?.currentSearchHash}`, value: { @@ -1415,7 +1434,7 @@ function updateSplitTransactions({ }, }); } else { - optimisticData.push({ + onyxData.optimisticData?.push({ onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.TRANSACTION}${originalTransactionID}`, value: { @@ -1429,7 +1448,7 @@ function updateSplitTransactions({ ...splits.at(0), comment: splits.at(0)?.comment?.comment, } as RevertSplitTransactionParams; - API.write(WRITE_COMMANDS.REVERT_SPLIT_TRANSACTION, parameters, {optimisticData, successData, failureData}); + API.write(WRITE_COMMANDS.REVERT_SPLIT_TRANSACTION, parameters, onyxData); } else { // Prepare splitApiParams for the Transaction_Split API call which requires a specific format for the splits // The format is: splits[0][amount], splits[0][category], splits[0][tag] etc. @@ -1489,7 +1508,7 @@ function updateSplitTransactions({ }; // Add to optimisticData for this split's reportActions - optimisticData.push({ + onyxData.optimisticData?.push({ onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${splitReportID}`, value: { @@ -1499,7 +1518,7 @@ function updateSplitTransactions({ }); // Add successData to clear pendingAction after API call succeeds - successData.push({ + onyxData.successData?.push({ onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${splitReportID}`, value: { @@ -1509,7 +1528,7 @@ function updateSplitTransactions({ }); // Add failureData to remove optimistic hold report actions if the request fails - failureData.push({ + onyxData.failureData?.push({ onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${splitReportID}`, value: { @@ -1541,10 +1560,10 @@ function updateSplitTransactions({ if (isCreationOfSplits) { // eslint-disable-next-line rulesdir/no-multiple-api-calls - API.write(WRITE_COMMANDS.SPLIT_TRANSACTION, splitParameters, {optimisticData, successData, failureData}); + API.write(WRITE_COMMANDS.SPLIT_TRANSACTION, splitParameters, onyxData); } else { // eslint-disable-next-line rulesdir/no-multiple-api-calls - API.write(WRITE_COMMANDS.UPDATE_SPLIT_TRANSACTION, splitParameters, {optimisticData, successData, failureData}); + API.write(WRITE_COMMANDS.UPDATE_SPLIT_TRANSACTION, splitParameters, onyxData); } } // eslint-disable-next-line @typescript-eslint/no-deprecated diff --git a/src/libs/actions/IOU/index.ts b/src/libs/actions/IOU/index.ts index 33ecdb4d8063..4263dbce4121 100644 --- a/src/libs/actions/IOU/index.ts +++ b/src/libs/actions/IOU/index.ts @@ -441,9 +441,16 @@ type UpdateMoneyRequestData = { type PayMoneyRequestData = { params: PayMoneyRequestParams & Partial; - optimisticData: OnyxUpdate[]; - successData: OnyxUpdate[]; - failureData: OnyxUpdate[]; + onyxData: OnyxData< + | typeof ONYXKEYS.NVP_ACTIVE_POLICY_ID + | typeof ONYXKEYS.COLLECTION.REPORT + | typeof ONYXKEYS.COLLECTION.REPORT_ACTIONS + | typeof ONYXKEYS.COLLECTION.NEXT_STEP + | typeof ONYXKEYS.NVP_LAST_PAYMENT_METHOD + | typeof ONYXKEYS.COLLECTION.TRANSACTION + | typeof ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS + | BuildPolicyDataKeys + >; }; type GPSPoint = { @@ -9260,7 +9267,7 @@ function deleteMoneyRequest({ const cleanUpTransactionThreadReportOnyxData = getCleanUpTransactionThreadReportOnyxData({shouldDeleteTransactionThread, transactionThreadID, reportAction, isChatIOUReportArchived}); optimisticData.push(...cleanUpTransactionThreadReportOnyxData.optimisticData); - const successData: OnyxUpdate[] = [ + const successData: Array> = [ shouldDeleteIOUReport ? { onyxMethod: Onyx.METHOD.SET, @@ -9605,9 +9612,9 @@ function getReportFromHoldRequestsOnyxData({ optimisticCreatedReportForUnapprovedTransactionsActionID: string | undefined; optimisticHoldReportExpenseActionIDs: OptimisticHoldReportExpenseActionID[]; optimisticReportActionCopyIDs: OptimisticReportActionCopyIDs; - optimisticData: OnyxUpdate[]; - successData: OnyxUpdate[]; - failureData: OnyxUpdate[]; + optimisticData: Array>; + successData: Array>; + failureData: Array>; } { const {holdReportActions, holdTransactions} = getHoldReportActionsAndTransactions(iouReport?.reportID); const firstHoldTransaction = holdTransactions.at(0); @@ -9943,9 +9950,20 @@ function getPayMoneyRequestParams({ let payerPolicyID = activePolicy?.id; let chatReport = initialChatReport; let policyParams = {}; - const optimisticData: OnyxUpdate[] = []; - const successData: OnyxUpdate[] = []; - const failureData: OnyxUpdate[] = []; + const onyxData: OnyxData< + | typeof ONYXKEYS.NVP_ACTIVE_POLICY_ID + | typeof ONYXKEYS.COLLECTION.REPORT + | typeof ONYXKEYS.COLLECTION.REPORT_ACTIONS + | typeof ONYXKEYS.COLLECTION.NEXT_STEP + | typeof ONYXKEYS.NVP_LAST_PAYMENT_METHOD + | typeof ONYXKEYS.COLLECTION.TRANSACTION + | typeof ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS + | BuildPolicyDataKeys + > = { + optimisticData: [], + successData: [], + failureData: [], + }; const shouldCreatePolicy = !activePolicy || !isPolicyAdmin(activePolicy) || !isPaidGroupPolicy(activePolicy); if (isIndividualInvoiceRoom(chatReport) && payAsBusiness && shouldCreatePolicy) { @@ -9979,9 +9997,9 @@ function getPayMoneyRequestParams({ policyName, }; - optimisticData.push(...(policyOptimisticData ?? []), {onyxMethod: Onyx.METHOD.MERGE, key: ONYXKEYS.NVP_ACTIVE_POLICY_ID, value: payerPolicyID}); - successData.push(...(policySuccessData ?? [])); - failureData.push(...(policyFailureData ?? []), {onyxMethod: Onyx.METHOD.MERGE, key: ONYXKEYS.NVP_ACTIVE_POLICY_ID, value: activePolicy?.id ?? null}); + onyxData.optimisticData?.push(...(policyOptimisticData ?? []), {onyxMethod: Onyx.METHOD.MERGE, key: ONYXKEYS.NVP_ACTIVE_POLICY_ID, value: payerPolicyID}); + onyxData.successData?.push(...(policySuccessData ?? [])); + onyxData.failureData?.push(...(policyFailureData ?? []), {onyxMethod: Onyx.METHOD.MERGE, key: ONYXKEYS.NVP_ACTIVE_POLICY_ID, value: activePolicy?.id ?? null}); } if (isIndividualInvoiceRoom(chatReport) && payAsBusiness && existingB2BInvoiceReport) { @@ -10040,7 +10058,7 @@ function getPayMoneyRequestParams({ }; } - optimisticData.push( + onyxData.optimisticData?.push( { onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.REPORT}${chatReport.reportID}`, @@ -10097,14 +10115,14 @@ function getPayMoneyRequestParams({ }, }; - optimisticData.push({ + onyxData.optimisticData?.push({ onyxMethod: Onyx.METHOD.MERGE, key: ONYXKEYS.NVP_LAST_PAYMENT_METHOD, value: optimisticLastPaymentMethod, }); } - successData.push( + onyxData.successData?.push( { onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.REPORT}${iouReport?.reportID}`, @@ -10129,7 +10147,7 @@ function getPayMoneyRequestParams({ }, ); - failureData.push( + onyxData.failureData?.push( { onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${iouReport?.reportID}`, @@ -10160,14 +10178,14 @@ function getPayMoneyRequestParams({ // In case the report preview action is loaded locally, let's update it. if (optimisticReportPreviewAction) { - optimisticData.push({ + onyxData.optimisticData?.push({ onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${chatReport.reportID}`, value: { [optimisticReportPreviewAction.reportActionID]: optimisticReportPreviewAction, }, }); - failureData.push({ + onyxData.failureData?.push({ onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${chatReport.reportID}`, value: { @@ -10182,7 +10200,7 @@ function getPayMoneyRequestParams({ if (full) { const reportTransactions = getReportTransactions(iouReport?.reportID); for (const transaction of reportTransactions) { - optimisticData.push({ + onyxData.optimisticData?.push({ onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.TRANSACTION}${transaction.transactionID}`, value: { @@ -10191,7 +10209,7 @@ function getPayMoneyRequestParams({ }, }, }); - failureData.push({ + onyxData.failureData?.push({ onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.TRANSACTION}${transaction.transactionID}`, value: { @@ -10202,16 +10220,16 @@ function getPayMoneyRequestParams({ }); } - const optimisticTransactionViolations: OnyxUpdate[] = reportTransactions.map(({transactionID}) => { + const optimisticTransactionViolations: Array> = reportTransactions.map(({transactionID}) => { return { onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${transactionID}`, value: null, }; }); - optimisticData.push(...optimisticTransactionViolations); + onyxData.optimisticData?.push(...optimisticTransactionViolations); - const failureTransactionViolations: OnyxUpdate[] = reportTransactions.map(({transactionID}) => { + const failureTransactionViolations: Array> = reportTransactions.map(({transactionID}) => { const violations = allTransactionViolations[`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${transactionID}`] ?? []; return { onyxMethod: Onyx.METHOD.MERGE, @@ -10219,7 +10237,7 @@ function getPayMoneyRequestParams({ value: violations, }; }); - failureData.push(...failureTransactionViolations); + onyxData.failureData?.push(...failureTransactionViolations); } let optimisticHoldReportID; @@ -10228,9 +10246,9 @@ function getPayMoneyRequestParams({ if (!full) { const holdReportOnyxData = getReportFromHoldRequestsOnyxData({chatReport, iouReport, recipient, policy: reportPolicy, betas}); - optimisticData.push(...holdReportOnyxData.optimisticData); - successData.push(...holdReportOnyxData.successData); - failureData.push(...holdReportOnyxData.failureData); + onyxData.optimisticData?.push(...holdReportOnyxData.optimisticData); + onyxData.successData?.push(...holdReportOnyxData.successData); + onyxData.failureData?.push(...holdReportOnyxData.failureData); optimisticHoldReportID = holdReportOnyxData.optimisticHoldReportID; optimisticHoldActionID = holdReportOnyxData.optimisticHoldActionID; optimisticHoldReportExpenseActionIDs = JSON.stringify(holdReportOnyxData.optimisticHoldReportExpenseActionIDs); @@ -10249,9 +10267,7 @@ function getPayMoneyRequestParams({ optimisticHoldReportExpenseActionIDs, ...policyParams, }, - optimisticData, - successData, - failureData, + onyxData, }; } @@ -10505,7 +10521,16 @@ function approveMoneyRequest( }); const chatReport = getReportOrDraftReport(expenseReport.chatReportID); - const optimisticData: OnyxUpdate[] = []; + const optimisticData: Array< + OnyxUpdate< + | typeof ONYXKEYS.COLLECTION.REPORT + | typeof ONYXKEYS.COLLECTION.REPORT_ACTIONS + | typeof ONYXKEYS.COLLECTION.TRANSACTION + | typeof ONYXKEYS.COLLECTION.NEXT_STEP + | typeof ONYXKEYS.COLLECTION.REPORT_METADATA + | typeof ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS + > + > = []; if (shouldAddOptimisticApproveAction) { optimisticData.push({ @@ -10577,7 +10602,7 @@ function approveMoneyRequest( }); } - const successData: OnyxUpdate[] = []; + const successData: Array> = []; if (!isDEWPolicy) { successData.push({ @@ -10614,7 +10639,16 @@ function approveMoneyRequest( }); } - const failureData: OnyxUpdate[] = [ + const failureData: Array< + OnyxUpdate< + | typeof ONYXKEYS.COLLECTION.REPORT + | typeof ONYXKEYS.COLLECTION.REPORT_ACTIONS + | typeof ONYXKEYS.COLLECTION.NEXT_STEP + | typeof ONYXKEYS.COLLECTION.REPORT_METADATA + | typeof ONYXKEYS.COLLECTION.TRANSACTION + | typeof ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS + > + > = [ { onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.REPORT}${expenseReport.chatReportID}`, @@ -10862,7 +10896,11 @@ function reopenReport( value: optimisticNextStepDeprecated, }; - const optimisticData: OnyxUpdate[] = [optimisticIOUReportData, optimisticReportActionsData, optimisticNextStepData]; + const optimisticData: Array> = [ + optimisticIOUReportData, + optimisticReportActionsData, + optimisticNextStepData, + ]; const successData: Array> = [ { @@ -11039,7 +11077,11 @@ function retractReport( value: optimisticNextStepDeprecated, }; - const optimisticData: OnyxUpdate[] = [optimisticIOUReportData, optimisticReportActionsData, optimisticNextStepData]; + const optimisticData: Array> = [ + optimisticIOUReportData, + optimisticReportActionsData, + optimisticNextStepData, + ]; if (chatReport) { optimisticData.push({ @@ -11215,7 +11257,11 @@ function unapproveExpenseReport( value: optimisticNextStepDeprecated, }; - const optimisticData: OnyxUpdate[] = [optimisticIOUReportData, optimisticReportActionData, optimisticNextStepData]; + const optimisticData: Array> = [ + optimisticIOUReportData, + optimisticReportActionData, + optimisticNextStepData, + ]; const successData: Array> = [ { @@ -11361,7 +11407,9 @@ function submitReport( const approvalChain = getApprovalChain(policy, expenseReport); const managerID = getAccountIDsByLogins(approvalChain).at(0); - const optimisticData: OnyxUpdate[] = []; + const optimisticData: Array< + OnyxUpdate + > = []; if (shouldAddOptimisticSubmitAction) { optimisticData.push({ @@ -11849,12 +11897,7 @@ function payMoneyRequest(params: PayMoneyRequestFunctionParams) { completePaymentOnboarding(paymentSelected, introSelected); const recipient = {accountID: iouReport?.ownerAccountID ?? CONST.DEFAULT_NUMBER_ID}; - const { - params: payMoneyRequestParams, - optimisticData, - successData, - failureData, - } = getPayMoneyRequestParams({ + const {params: payMoneyRequestParams, onyxData} = getPayMoneyRequestParams({ initialChatReport: chatReport, iouReport, recipient, @@ -11873,7 +11916,7 @@ function payMoneyRequest(params: PayMoneyRequestFunctionParams) { const apiCommand = paymentType === CONST.IOU.PAYMENT_TYPE.EXPENSIFY ? WRITE_COMMANDS.PAY_MONEY_REQUEST_WITH_WALLET : WRITE_COMMANDS.PAY_MONEY_REQUEST; playSound(SOUNDS.SUCCESS); - API.write(apiCommand, payMoneyRequestParams, {optimisticData, successData, failureData}); + API.write(apiCommand, payMoneyRequestParams, onyxData); notifyNewAction(!full ? (Navigation.getTopmostReportId() ?? iouReport?.reportID) : iouReport?.reportID, undefined, true); return payMoneyRequestParams.optimisticHoldReportID; } @@ -11895,9 +11938,7 @@ function payInvoice({ }: PayInvoiceArgs) { const recipient = {accountID: invoiceReport?.ownerAccountID ?? CONST.DEFAULT_NUMBER_ID}; const { - optimisticData, - successData, - failureData, + onyxData, params: { reportActionID, policyID, @@ -11961,7 +12002,7 @@ function payInvoice({ } playSound(SOUNDS.SUCCESS); - API.write(WRITE_COMMANDS.PAY_INVOICE, params, {optimisticData, successData, failureData}); + API.write(WRITE_COMMANDS.PAY_INVOICE, params, onyxData); } function detachReceipt(transactionID: string | undefined, transactionPolicy: OnyxEntry, transactionPolicyCategories?: OnyxEntry) { @@ -11977,7 +12018,9 @@ function detachReceipt(transactionID: string | undefined, transactionPolicy: Ony } : null; - const optimisticData: OnyxUpdate[] = [ + const optimisticData: Array< + OnyxUpdate + > = [ { onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`, @@ -12104,7 +12147,7 @@ function replaceReceipt({transactionID, file, source, transactionPolicy, transac const retryParams: ReplaceReceipt = {transactionID, file: undefined, source, transactionPolicy, transactionPolicyCategories}; const currentSearchQueryJSON = getCurrentSearchQueryJSON(); - const optimisticData: OnyxUpdate[] = [ + const optimisticData: Array> = [ { onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`, @@ -12166,10 +12209,10 @@ function replaceReceipt({transactionID, file, source, transactionPolicy, transac }); } if (currentSearchQueryJSON?.hash) { - // @ts-expect-error - will be solved in https://github.com/Expensify/App/issues/73830 optimisticData.push({ onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.SNAPSHOT}${currentSearchQueryJSON.hash}`, + // @ts-expect-error - will be solved in https://github.com/Expensify/App/issues/73830 value: { data: { [`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`]: { diff --git a/src/libs/actions/ImportTransactions.ts b/src/libs/actions/ImportTransactions.ts index 5c2a0b65154d..fb5321df0a0b 100644 --- a/src/libs/actions/ImportTransactions.ts +++ b/src/libs/actions/ImportTransactions.ts @@ -284,8 +284,8 @@ function importTransactionsFromCSV(spreadsheet: ImportedSpreadsheet, existingCar reimbursable: isReimbursable, }; - const optimisticData = [] as OnyxUpdate[]; - const failureData = [] as OnyxUpdate[]; + const optimisticData: Array> = []; + const failureData: Array> = []; // Only add card to optimistic data if we're creating a new card if (!isAddingToExistingCard && optimisticCard) { diff --git a/src/libs/actions/MergeTransaction.ts b/src/libs/actions/MergeTransaction.ts index 4ba202268dd4..dbd8a345aa68 100644 --- a/src/libs/actions/MergeTransaction.ts +++ b/src/libs/actions/MergeTransaction.ts @@ -367,9 +367,13 @@ function mergeTransactionRequest({ const isUnreportedSourceTransaction = sourceTransaction.reportID === CONST.REPORT.UNREPORTED_REPORT_ID; const selfDMReportID = selfDMReport?.reportID; - const sourceTransactionOptimisticData: OnyxUpdate[] = []; - const sourceTransactionSuccessData: OnyxUpdate[] = []; - const sourceTransactionFailureData: OnyxUpdate[] = []; + const sourceTransactionOptimisticData: Array< + OnyxUpdate + > = []; + const sourceTransactionSuccessData: Array> = []; + const sourceTransactionFailureData: Array< + OnyxUpdate + > = []; if (!isUnreportedSourceTransaction || !selfDMReportID) { const optimisticSourceTransactionData: OnyxUpdate = { onyxMethod: Onyx.METHOD.SET, @@ -382,7 +386,7 @@ function mergeTransactionRequest({ value: sourceTransaction, }; const transactionsOfSourceReport = getReportTransactions(sourceTransaction.reportID); - const optimisticSourceReportData: OnyxUpdate[] = + const optimisticSourceReportData: Array> = transactionsOfSourceReport.length === 1 ? [ { @@ -394,7 +398,7 @@ function mergeTransactionRequest({ : []; // @ts-expect-error - will be solved in https://github.com/Expensify/App/issues/73830 - const failureSourceReportData: OnyxUpdate[] = + const failureSourceReportData: Array> = transactionsOfSourceReport.length === 1 ? [ { @@ -405,7 +409,7 @@ function mergeTransactionRequest({ ] : []; const iouActionOfSourceTransaction = getIOUActionForReportID(sourceTransaction.reportID, sourceTransaction.transactionID); - const optimisticSourceReportActionData: OnyxUpdate[] = iouActionOfSourceTransaction + const optimisticSourceReportActionData: Array> = iouActionOfSourceTransaction ? [ { onyxMethod: Onyx.METHOD.MERGE, @@ -418,7 +422,7 @@ function mergeTransactionRequest({ }, ] : []; - const successSourceReportActionData: OnyxUpdate[] = iouActionOfSourceTransaction + const successSourceReportActionData: Array> = iouActionOfSourceTransaction ? [ { onyxMethod: Onyx.METHOD.MERGE, @@ -432,7 +436,7 @@ function mergeTransactionRequest({ ] : []; - const failureSourceReportActionData: OnyxUpdate[] = iouActionOfSourceTransaction + const failureSourceReportActionData: Array> = iouActionOfSourceTransaction ? [ { onyxMethod: Onyx.METHOD.MERGE, @@ -520,20 +524,18 @@ function mergeTransactionRequest({ }, ); - // @ts-expect-error - will be solved in https://github.com/Expensify/App/issues/73830 // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment - const optimisticData: OnyxUpdate[] = [ + const optimisticData: Array> = [ ...(onyxTargetTransactionData.optimisticData ?? []), optimisticMergeTransactionData, ...optimisticTransactionViolations, ...sourceTransactionOptimisticData, ]; - // @ts-expect-error - will be solved in https://github.com/Expensify/App/issues/73830 // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment - const failureData: OnyxUpdate[] = [...(onyxTargetTransactionData.failureData ?? []), ...failureTransactionViolations, ...sourceTransactionFailureData]; + const failureData: Array> = [...(onyxTargetTransactionData.failureData ?? []), ...failureTransactionViolations, ...sourceTransactionFailureData]; - const successData: OnyxUpdate[] = []; + const successData: Array> = []; successData.push(...sourceTransactionSuccessData); successData.push(...(onyxTargetTransactionData.successData ?? [])); diff --git a/src/libs/actions/OnyxUpdateManager/index.ts b/src/libs/actions/OnyxUpdateManager/index.ts index 3e485a5bda3b..5561c6e1e175 100644 --- a/src/libs/actions/OnyxUpdateManager/index.ts +++ b/src/libs/actions/OnyxUpdateManager/index.ts @@ -1,4 +1,4 @@ -import type {OnyxEntry, OnyxUpdate} from 'react-native-onyx'; +import type {OnyxEntry, OnyxKey, OnyxUpdate} from 'react-native-onyx'; import Onyx from 'react-native-onyx'; import {isClientTheLeader} from '@libs/ActiveClientManager'; import Log from '@libs/Log'; @@ -84,7 +84,7 @@ function finalizeUpdatesAndResumeQueue() { * * @returns a promise that resolves when all Onyx updates are done being processed */ -function handleMissingOnyxUpdates(onyxUpdatesFromServer: OnyxEntry, clientLastUpdateID?: number): Promise { +function handleMissingOnyxUpdates(onyxUpdatesFromServer: OnyxEntry>, clientLastUpdateID?: number): Promise { // If isLoadingApp is positive it means that OpenApp command hasn't finished yet, and in that case // we don't have base state of the app (reports, policies, etc.) setup. If we apply this update, // we'll only have them overwritten by the openApp response. So let's skip it and return. @@ -201,12 +201,12 @@ function handleMissingOnyxUpdates(onyxUpdatesFromServer: OnyxEntry): void { +function updateAuthTokenIfNecessary(onyxUpdatesFromServer: OnyxEntry>): void { // Consolidate all of the given Onyx updates - const onyxUpdates: OnyxUpdate[] = []; + const onyxUpdates: Array> = []; if (onyxUpdatesFromServer?.updates) { for (const updateEvent of onyxUpdatesFromServer.updates) { - onyxUpdates.push(...updateEvent.data); + onyxUpdates.push(...(updateEvent.data as Array>)); } } onyxUpdates.push(...(onyxUpdatesFromServer?.response?.onyxData ?? [])); diff --git a/src/libs/actions/OnyxUpdateManager/types.ts b/src/libs/actions/OnyxUpdateManager/types.ts index 119dfb82ba1e..105254241687 100644 --- a/src/libs/actions/OnyxUpdateManager/types.ts +++ b/src/libs/actions/OnyxUpdateManager/types.ts @@ -1,6 +1,7 @@ +import type {OnyxKey} from 'react-native-onyx'; import type {OnyxUpdatesFromServer} from '@src/types/onyx'; -type DeferredUpdatesDictionary = Record; +type DeferredUpdatesDictionary = Record>; type DetectGapAndSplitResult = {applicableUpdates: DeferredUpdatesDictionary; updatesAfterGaps: DeferredUpdatesDictionary; latestMissingUpdateID: number | undefined}; diff --git a/src/libs/actions/OnyxUpdateManager/utils/DeferredOnyxUpdates.ts b/src/libs/actions/OnyxUpdateManager/utils/DeferredOnyxUpdates.ts index efcc53d86c6c..ce325d7da37f 100644 --- a/src/libs/actions/OnyxUpdateManager/utils/DeferredOnyxUpdates.ts +++ b/src/libs/actions/OnyxUpdateManager/utils/DeferredOnyxUpdates.ts @@ -1,3 +1,4 @@ +import type {OnyxKey} from 'react-native-onyx'; import Onyx from 'react-native-onyx'; import type {DeferredUpdatesDictionary} from '@libs/actions/OnyxUpdateManager/types'; import Log from '@libs/Log'; @@ -9,7 +10,8 @@ import {isValidOnyxUpdateFromServer} from '@src/types/onyx/OnyxUpdatesFromServer // eslint-disable-next-line import/no-cycle import {validateAndApplyDeferredUpdates} from '.'; -let missingOnyxUpdatesQueryPromise: Promise | undefined; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +let missingOnyxUpdatesQueryPromise: Promise | Array> | void> | undefined; let deferredUpdates: DeferredUpdatesDictionary = {}; /** @@ -23,7 +25,7 @@ function getMissingOnyxUpdatesQueryPromise() { /** * Sets the promise that fetches the missing onyx updates */ -function setMissingOnyxUpdatesQueryPromise(promise: Promise) { +function setMissingOnyxUpdatesQueryPromise(promise: Promise | Array> | void>) { missingOnyxUpdatesQueryPromise = promise; } @@ -77,7 +79,7 @@ type EnqueueDeferredOnyxUpdatesOptions = { * @param updates The updates that should be applied (e.g. updates from push notifications) * @param options additional flags to change the behaviour of this function */ -function enqueue(updates: OnyxUpdatesFromServer | DeferredUpdatesDictionary, options?: EnqueueDeferredOnyxUpdatesOptions) { +function enqueue(updates: OnyxUpdatesFromServer | DeferredUpdatesDictionary, options?: EnqueueDeferredOnyxUpdatesOptions) { if (options?.shouldPauseSequentialQueue ?? true) { Log.info('[DeferredOnyxUpdates] Pausing SequentialQueue'); SequentialQueue.pause(); @@ -100,7 +102,7 @@ function enqueue(updates: OnyxUpdatesFromServer | DeferredUpdatesDictionary, opt continue; } - deferredUpdates[lastUpdateID] = update; + deferredUpdates[lastUpdateID] = update as OnyxUpdatesFromServer; } } } diff --git a/src/libs/actions/OnyxUpdates.ts b/src/libs/actions/OnyxUpdates.ts index 4075431b1899..d128202779a2 100644 --- a/src/libs/actions/OnyxUpdates.ts +++ b/src/libs/actions/OnyxUpdates.ts @@ -7,7 +7,7 @@ import Performance from '@libs/Performance'; import PusherUtils from '@libs/PusherUtils'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; -import type {OnyxUpdateEvent, OnyxUpdatesFromServer, Request} from '@src/types/onyx'; +import type {AnyOnyxUpdatesFromServer, OnyxUpdateEvent, OnyxUpdatesFromServer, Request} from '@src/types/onyx'; import type Response from '@src/types/onyx/Response'; import {isEmptyObject} from '@src/types/utils/EmptyObject'; import {queueOnyxUpdates} from './QueuedOnyxUpdates'; @@ -124,7 +124,7 @@ function apply({ request, response, updates, -}: Merge, {request: Request; response: Response; type: 'https'}>): Promise; +}: Merge, {request: Request; response: Response; type: 'https'}>): Promise>; function apply({lastUpdateID, type, request, response, updates}: OnyxUpdatesFromServer): Promise>; function apply({lastUpdateID, type, request, response, updates}: OnyxUpdatesFromServer): Promise> | undefined { Log.info(`[OnyxUpdateManager] Applying update type: ${type} with lastUpdateID: ${lastUpdateID}`, false, {command: request?.command}); @@ -175,7 +175,7 @@ function apply({lastUpdateID, type, request, response, upd * @param [updateParams.response] Exists if updateParams.type === 'https' * @param [updateParams.updates] Exists if updateParams.type === 'pusher' */ -function saveUpdateInformation(updateParams: OnyxUpdatesFromServer) { +function saveUpdateInformation(updateParams: OnyxUpdatesFromServer) { let modifiedUpdateParams = updateParams; // We don't want to store the data in the updateParams if it's a HTTPS update since it is useless anyways // and it causes serialization issues when storing in Onyx @@ -183,7 +183,8 @@ function saveUpdateInformation(updateParams: Ony modifiedUpdateParams = {...modifiedUpdateParams, request: {...updateParams.request, data: {apiRequestType: updateParams.request?.data?.apiRequestType}}}; } // Always use set() here so that the updateParams are never merged and always unique to the request that came in - Onyx.set(ONYXKEYS.ONYX_UPDATES_FROM_SERVER, modifiedUpdateParams as OnyxUpdatesFromServer); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + Onyx.set(ONYXKEYS.ONYX_UPDATES_FROM_SERVER, modifiedUpdateParams as AnyOnyxUpdatesFromServer); } type DoesClientNeedToBeUpdatedParams = { diff --git a/src/libs/actions/PaymentMethods.ts b/src/libs/actions/PaymentMethods.ts index dfe5e90879e8..117edc0e6a9b 100644 --- a/src/libs/actions/PaymentMethods.ts +++ b/src/libs/actions/PaymentMethods.ts @@ -82,8 +82,8 @@ function getMakeDefaultPaymentOnyxData( previousPaymentMethod?: PaymentMethod, currentPaymentMethod?: PaymentMethod, isOptimisticData = true, -): OnyxUpdate[] { - const onyxData: OnyxUpdate[] = [ +): Array> { + const onyxData: Array> = [ isOptimisticData ? { onyxMethod: Onyx.METHOD.MERGE, diff --git a/src/libs/actions/Policy/Member.ts b/src/libs/actions/Policy/Member.ts index 51cd06172972..56e52fb8e334 100644 --- a/src/libs/actions/Policy/Member.ts +++ b/src/libs/actions/Policy/Member.ts @@ -894,7 +894,17 @@ function buildAddMembersToWorkspaceOnyxData( }; } - const optimisticData: OnyxUpdate[] = [ + const optimisticData: Array< + OnyxUpdate< + | typeof ONYXKEYS.COLLECTION.POLICY + | typeof ONYXKEYS.PERSONAL_DETAILS_LIST + | typeof ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS + | typeof ONYXKEYS.COLLECTION.REPORT_ACTIONS + | typeof ONYXKEYS.COLLECTION.REPORT_METADATA + | typeof ONYXKEYS.COLLECTION.REPORT + | typeof ONYXKEYS.COLLECTION.REPORT_DRAFT + > + > = [ { onyxMethod: Onyx.METHOD.MERGE, key: policyKey, @@ -913,7 +923,15 @@ function buildAddMembersToWorkspaceOnyxData( ...(adminRoomMembers.optimisticData ?? []), ); - const successData: OnyxUpdate[] = [ + const successData: Array< + OnyxUpdate< + | typeof ONYXKEYS.COLLECTION.POLICY + | typeof ONYXKEYS.PERSONAL_DETAILS_LIST + | typeof ONYXKEYS.COLLECTION.REPORT_ACTIONS + | typeof ONYXKEYS.COLLECTION.REPORT_METADATA + | typeof ONYXKEYS.COLLECTION.REPORT + > + > = [ { onyxMethod: Onyx.METHOD.MERGE, key: policyKey, @@ -930,7 +948,16 @@ function buildAddMembersToWorkspaceOnyxData( ...(adminRoomMembers.successData ?? []), ); - const failureData: OnyxUpdate[] = [ + const failureData: Array< + OnyxUpdate< + | typeof ONYXKEYS.COLLECTION.POLICY + | typeof ONYXKEYS.PERSONAL_DETAILS_LIST + | typeof ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS + | typeof ONYXKEYS.COLLECTION.REPORT_ACTIONS + | typeof ONYXKEYS.COLLECTION.REPORT_METADATA + | typeof ONYXKEYS.COLLECTION.REPORT + > + > = [ { onyxMethod: Onyx.METHOD.MERGE, key: policyKey, @@ -1032,7 +1059,7 @@ function inviteMemberToWorkspace(policyID: string, inviterEmail?: string) { const optimisticMembersState = {policyID, inviterEmail}; const failureMembersState = {policyID, inviterEmail}; - const optimisticData: OnyxUpdate[] = [ + const optimisticData: Array> = [ { onyxMethod: Onyx.METHOD.MERGE, key: memberJoinKey, @@ -1040,7 +1067,7 @@ function inviteMemberToWorkspace(policyID: string, inviterEmail?: string) { }, ]; - const failureData: OnyxUpdate[] = [ + const failureData: Array> = [ { onyxMethod: Onyx.METHOD.MERGE, key: memberJoinKey, @@ -1059,7 +1086,7 @@ function inviteMemberToWorkspace(policyID: string, inviterEmail?: string) { function joinAccessiblePolicy(policyID: string) { const memberJoinKey = `${ONYXKEYS.COLLECTION.POLICY_JOIN_MEMBER}${policyID}` as const; - const optimisticData: OnyxUpdate[] = [ + const optimisticData: Array> = [ { onyxMethod: Onyx.METHOD.MERGE, key: memberJoinKey, @@ -1067,7 +1094,7 @@ function joinAccessiblePolicy(policyID: string) { }, ]; - const failureData: OnyxUpdate[] = [ + const failureData: Array> = [ { onyxMethod: Onyx.METHOD.MERGE, key: memberJoinKey, @@ -1084,7 +1111,7 @@ function joinAccessiblePolicy(policyID: string) { function askToJoinPolicy(policyID: string) { const memberJoinKey = `${ONYXKEYS.COLLECTION.POLICY_JOIN_MEMBER}${policyID}` as const; - const optimisticData: OnyxUpdate[] = [ + const optimisticData: Array> = [ { onyxMethod: Onyx.METHOD.MERGE, key: memberJoinKey, @@ -1092,7 +1119,7 @@ function askToJoinPolicy(policyID: string) { }, ]; - const failureData: OnyxUpdate[] = [ + const failureData: Array> = [ { onyxMethod: Onyx.METHOD.MERGE, key: memberJoinKey, diff --git a/src/libs/actions/Policy/Policy.ts b/src/libs/actions/Policy/Policy.ts index 8700b14f346f..1cfb025924ad 100644 --- a/src/libs/actions/Policy/Policy.ts +++ b/src/libs/actions/Policy/Policy.ts @@ -509,7 +509,7 @@ function deleteWorkspace(params: DeleteWorkspaceActionParams) { }); } - const finallyData: OnyxUpdate[] = []; + const finallyData: Array> = []; const currentTime = DateUtils.getDBTime(); const reportIDToOptimisticCloseReportActionID: Record = {}; for (const report of reportsToArchive) { @@ -831,8 +831,8 @@ function setWorkspaceApprovalMode(policyID: string, approver: string, approvalMo const currentUserAccountID = deprecatedSessionAccountID ?? CONST.DEFAULT_NUMBER_ID; const currentUserEmail = deprecatedSessionEmail ?? ''; - const nextStepOptimisticData: OnyxUpdate[] = []; - const nextStepFailureData: OnyxUpdate[] = []; + const nextStepOptimisticData: Array> = []; + const nextStepFailureData: Array> = []; const shouldUpdateNextSteps = additionalData?.reportNextSteps != null && additionalData?.transactionViolations != null && additionalData?.betas != null; if (shouldUpdateNextSteps) { const {reportNextSteps, transactionViolations, betas} = additionalData; @@ -879,7 +879,7 @@ function setWorkspaceApprovalMode(policyID: string, approver: string, approvalMo } } - const optimisticData: OnyxUpdate[] = [ + const optimisticData: Array> = [ { onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.POLICY}${policyID}`, @@ -893,7 +893,7 @@ function setWorkspaceApprovalMode(policyID: string, approver: string, approvalMo optimisticData.push(...nextStepOptimisticData); } - const failureData: OnyxUpdate[] = [ + const failureData: Array> = [ { onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.POLICY}${policyID}`, @@ -2892,7 +2892,18 @@ function buildDuplicatePolicyData(policy: Policy, options: DuplicatePolicyDataOp // WARNING: The data below should be kept in sync with the API so we create the policy with the correct configuration. // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment - const optimisticData: OnyxUpdate[] = [ + const optimisticData: Array< + OnyxUpdate< + | typeof ONYXKEYS.COLLECTION.POLICY + | typeof ONYXKEYS.COLLECTION.REPORT_METADATA + | typeof ONYXKEYS.COLLECTION.REPORT + | typeof ONYXKEYS.COLLECTION.REPORT_ACTIONS + | typeof ONYXKEYS.COLLECTION.POLICY_DRAFTS + | typeof ONYXKEYS.COLLECTION.REPORT_DRAFT + | typeof ONYXKEYS.COLLECTION.POLICY_CATEGORIES + | typeof ONYXKEYS.COLLECTION.POLICY_CATEGORIES_DRAFT + > + > = [ { onyxMethod: Onyx.METHOD.SET, key: `${ONYXKEYS.COLLECTION.POLICY}${targetPolicyID}`, @@ -2998,7 +3009,16 @@ function buildDuplicatePolicyData(policy: Policy, options: DuplicatePolicyDataOp ...announceRoomChat.onyxOptimisticData, ]; - const successData: OnyxUpdate[] = [ + const successData: Array< + OnyxUpdate< + | typeof ONYXKEYS.COLLECTION.POLICY + | typeof ONYXKEYS.COLLECTION.REPORT_METADATA + | typeof ONYXKEYS.COLLECTION.REPORT + | typeof ONYXKEYS.COLLECTION.REPORT_ACTIONS + | typeof ONYXKEYS.COLLECTION.POLICY_CATEGORIES + | typeof ONYXKEYS.COLLECTION.POLICY_CATEGORIES_DRAFT + > + > = [ { onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.POLICY}${targetPolicyID}`, @@ -3073,7 +3093,16 @@ function buildDuplicatePolicyData(policy: Policy, options: DuplicatePolicyDataOp ...announceRoomChat.onyxSuccessData, ]; - const failureData: OnyxUpdate[] = [ + const failureData: Array< + OnyxUpdate< + | typeof ONYXKEYS.COLLECTION.POLICY + | typeof ONYXKEYS.COLLECTION.REPORT_METADATA + | typeof ONYXKEYS.COLLECTION.REPORT + | typeof ONYXKEYS.COLLECTION.REPORT_ACTIONS + | typeof ONYXKEYS.COLLECTION.POLICY_CATEGORIES + | typeof ONYXKEYS.COLLECTION.POLICY_CATEGORIES_DRAFT + > + > = [ { onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.POLICY}${targetPolicyID}`, @@ -3750,7 +3779,18 @@ function createWorkspaceFromIOUPayment( defaultReimbursable: true, }; - const optimisticData: OnyxUpdate[] = [ + const optimisticData: Array< + OnyxUpdate< + | typeof ONYXKEYS.COLLECTION.POLICY + | typeof ONYXKEYS.COLLECTION.POLICY_DRAFTS + | typeof ONYXKEYS.COLLECTION.REPORT + | typeof ONYXKEYS.COLLECTION.REPORT_METADATA + | typeof ONYXKEYS.COLLECTION.REPORT_ACTIONS + | typeof ONYXKEYS.COLLECTION.TRANSACTION + | typeof ONYXKEYS.REIMBURSEMENT_ACCOUNT + | WorkspaceMembersChats['onyxOptimisticData'][number]['key'] + > + > = [ { onyxMethod: Onyx.METHOD.SET, key: `${ONYXKEYS.COLLECTION.POLICY}${policyID}`, @@ -3806,7 +3846,15 @@ function createWorkspaceFromIOUPayment( ]; optimisticData.push(...employeeWorkspaceChat.onyxOptimisticData); - const successData: OnyxUpdate[] = [ + const successData: Array< + OnyxUpdate< + | typeof ONYXKEYS.COLLECTION.POLICY + | typeof ONYXKEYS.COLLECTION.REPORT + | typeof ONYXKEYS.COLLECTION.REPORT_METADATA + | typeof ONYXKEYS.COLLECTION.REPORT_ACTIONS + | WorkspaceMembersChats['onyxSuccessData'][number]['key'] + > + > = [ { onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.POLICY}${policyID}`, @@ -5080,10 +5128,10 @@ function upgradeToCorporate(policyID: string, featureName?: string) { // This will be fixed as part of https://github.com/Expensify/Expensify/issues/507850 // eslint-disable-next-line @typescript-eslint/no-deprecated const policy = getPolicy(policyID); - const optimisticData: OnyxUpdate[] = [ + const optimisticData: Array> = [ { onyxMethod: Onyx.METHOD.MERGE, - key: `policy_${policyID}`, + key: `${ONYXKEYS.COLLECTION.POLICY}${policyID}`, value: { isPendingUpgrade: true, type: CONST.POLICY.TYPE.CORPORATE, @@ -5101,20 +5149,20 @@ function upgradeToCorporate(policyID: string, featureName?: string) { }, ]; - const successData: OnyxUpdate[] = [ + const successData: Array> = [ { onyxMethod: Onyx.METHOD.MERGE, - key: `policy_${policyID}`, + key: `${ONYXKEYS.COLLECTION.POLICY}${policyID}`, value: { isPendingUpgrade: false, }, }, ]; - const failureData: OnyxUpdate[] = [ + const failureData: Array> = [ { onyxMethod: Onyx.METHOD.MERGE, - key: `policy_${policyID}`, + key: `${ONYXKEYS.COLLECTION.POLICY}${policyID}`, value: { isPendingUpgrade: false, type: policy?.type, @@ -5139,10 +5187,10 @@ function downgradeToTeam(policyID: string) { // This will be fixed as part of https://github.com/Expensify/Expensify/issues/507850 // eslint-disable-next-line @typescript-eslint/no-deprecated const policy = getPolicy(policyID); - const optimisticData: OnyxUpdate[] = [ + const optimisticData: Array> = [ { onyxMethod: Onyx.METHOD.MERGE, - key: `policy_${policyID}`, + key: `${ONYXKEYS.COLLECTION.POLICY}${policyID}`, value: { isPendingDowngrade: true, type: CONST.POLICY.TYPE.TEAM, @@ -5151,20 +5199,20 @@ function downgradeToTeam(policyID: string) { }, ]; - const successData: OnyxUpdate[] = [ + const successData: Array> = [ { onyxMethod: Onyx.METHOD.MERGE, - key: `policy_${policyID}`, + key: `${ONYXKEYS.COLLECTION.POLICY}${policyID}`, value: { isPendingDowngrade: false, }, }, ]; - const failureData: OnyxUpdate[] = [ + const failureData: Array> = [ { onyxMethod: Onyx.METHOD.MERGE, - key: `policy_${policyID}`, + key: `${ONYXKEYS.COLLECTION.POLICY}${policyID}`, value: { isPendingDowngrade: false, type: policy?.type, @@ -5188,11 +5236,11 @@ function setWorkspaceDefaultSpendCategory(policyID: string, groupID: string, cat const {mccGroup} = policy; - const optimisticData: OnyxUpdate[] = mccGroup + const optimisticData: Array> = mccGroup ? [ { onyxMethod: Onyx.METHOD.MERGE, - key: `policy_${policyID}`, + key: `${ONYXKEYS.COLLECTION.POLICY}${policyID}`, value: { mccGroup: { ...mccGroup, @@ -5207,11 +5255,11 @@ function setWorkspaceDefaultSpendCategory(policyID: string, groupID: string, cat ] : []; - const failureData: OnyxUpdate[] = mccGroup + const failureData: Array> = mccGroup ? [ { onyxMethod: Onyx.METHOD.MERGE, - key: `policy_${policyID}`, + key: `${ONYXKEYS.COLLECTION.POLICY}${policyID}`, value: { mccGroup: { ...mccGroup, @@ -5225,11 +5273,11 @@ function setWorkspaceDefaultSpendCategory(policyID: string, groupID: string, cat ] : []; - const successData: OnyxUpdate[] = mccGroup + const successData: Array> = mccGroup ? [ { onyxMethod: Onyx.METHOD.MERGE, - key: `policy_${policyID}`, + key: `${ONYXKEYS.COLLECTION.POLICY}${policyID}`, value: { mccGroup: { [groupID]: { @@ -6975,4 +7023,4 @@ export { setPolicyRequireCompanyCardsEnabled, setPolicyTimeTrackingDefaultRate, }; -export type {BuildPolicyDataKeys}; +export type {BuildPolicyDataKeys, WorkspaceMembersChats}; diff --git a/src/libs/actions/PolicyConnections.ts b/src/libs/actions/PolicyConnections.ts index 27df8f792cb3..65ee68af10c9 100644 --- a/src/libs/actions/PolicyConnections.ts +++ b/src/libs/actions/PolicyConnections.ts @@ -8,14 +8,14 @@ import ONYXKEYS from '@src/ONYXKEYS'; function openPolicyAccountingPage(policyID: string) { const hasConnectionsDataBeenFetchedKey = `${ONYXKEYS.COLLECTION.POLICY_HAS_CONNECTIONS_DATA_BEEN_FETCHED}${policyID}` as const; - const successData: OnyxUpdate[] = [ + const successData: Array> = [ { onyxMethod: Onyx.METHOD.MERGE, key: hasConnectionsDataBeenFetchedKey, value: true, }, ]; - const failureData: OnyxUpdate[] = [ + const failureData: Array> = [ { onyxMethod: Onyx.METHOD.MERGE, key: hasConnectionsDataBeenFetchedKey, diff --git a/src/libs/actions/Report/index.ts b/src/libs/actions/Report/index.ts index 569edf4e1d3d..a6772e9d9e5c 100644 --- a/src/libs/actions/Report/index.ts +++ b/src/libs/actions/Report/index.ts @@ -5921,21 +5921,39 @@ function updatePolicyIdForReportAndThreads( currentReportID: string, policyID: string, reportIDToThreadsReportIDsMap: Record, - optimisticData: OnyxUpdate[], - failureData: OnyxUpdate[], + optimisticData: Array< + OnyxUpdate< + | typeof ONYXKEYS.COLLECTION.REPORT + | typeof ONYXKEYS.COLLECTION.SNAPSHOT + | typeof ONYXKEYS.COLLECTION.REPORT_ACTIONS + | typeof ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS + | typeof ONYXKEYS.COLLECTION.NEXT_STEP + | typeof ONYXKEYS.COLLECTION.TRANSACTION + > + >, + failureData: Array< + OnyxUpdate< + | typeof ONYXKEYS.COLLECTION.REPORT + | typeof ONYXKEYS.COLLECTION.NEXT_STEP + | typeof ONYXKEYS.COLLECTION.REPORT_ACTIONS + | typeof ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS + | typeof ONYXKEYS.COLLECTION.TRANSACTION + > + >, ) { - const currentReport = allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${currentReportID}`]; + const reportKey = `${ONYXKEYS.COLLECTION.REPORT}${currentReportID}` as const; + const currentReport = allReports?.[reportKey]; const originalPolicyID = currentReport?.policyID; if (originalPolicyID) { optimisticData.push({ onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT}${currentReportID}`, + key: reportKey, value: {policyID}, }); failureData.push({ onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT}${currentReportID}`, + key: reportKey, value: {policyID: originalPolicyID}, }); } @@ -6498,7 +6516,12 @@ function changeReportPolicyAndInviteSubmitter({ return; } const policyMemberAccountIDs = Object.values(getMemberAccountIDsForWorkspace(employeeList, false, false)); - const {optimisticData, successData, failureData, membersChats} = buildAddMembersToWorkspaceOnyxData( + const { + optimisticData: optimisticAddMembersData, + successData: successAddMembersData, + failureData: failureAddMembersData, + membersChats, + } = buildAddMembersToWorkspaceOnyxData( {[submitterEmail]: report.ownerAccountID}, policy, policyMemberAccountIDs, @@ -6531,9 +6554,10 @@ function changeReportPolicyAndInviteSubmitter({ undefined, membersChats.reportCreationData[submitterEmail], ); - optimisticData.push(...optimisticChangePolicyData); - successData.push(...successChangePolicyData); - failureData.push(...failureChangePolicyData); + + const optimisticData = [...optimisticAddMembersData, ...optimisticChangePolicyData]; + const successData = [...successAddMembersData, ...successChangePolicyData]; + const failureData = [...failureAddMembersData, ...failureChangePolicyData]; const params = { reportID: report.reportID, diff --git a/src/libs/actions/Session/index.ts b/src/libs/actions/Session/index.ts index cdc3424460f8..ad549cb99a65 100644 --- a/src/libs/actions/Session/index.ts +++ b/src/libs/actions/Session/index.ts @@ -232,7 +232,7 @@ function signInWithSupportAuthToken(authToken: string) { /** * Clears the Onyx store and redirects user to the sign in page */ -function signOut(): Promise { +function signOut(): Promise> { Log.info('Flushing logs before signing out', true, {}, true); const shouldUseNewPartnerName = checkIfShouldUseNewPartnerName(credentials?.autoGeneratedLogin); @@ -324,7 +324,7 @@ function signOutAndRedirectToSignIn(shouldResetToHome?: boolean, shouldStashSess // We'll only call signOut if we're not stashing the session and not restoring a stashed session, // otherwise we'll call the API to invalidate the autogenerated credentials used for infinite // session. - const signOutPromise: Promise = !shouldRestoreStashedSession && !shouldStashSession ? signOut() : Promise.resolve(); + const signOutPromise: Promise> = !shouldRestoreStashedSession && !shouldStashSession ? signOut() : Promise.resolve(); // The function redirectToSignIn will clear the whole storage, so let's create our onyx params // updates for the credentials before we call it diff --git a/src/libs/actions/User.ts b/src/libs/actions/User.ts index 01ad77264e62..d2bc1bbf7b7a 100644 --- a/src/libs/actions/User.ts +++ b/src/libs/actions/User.ts @@ -52,7 +52,7 @@ import type {ExpenseRuleForm, MerchantRuleForm} from '@src/types/form'; import type {AppReview, BlockedFromConcierge, CustomStatusDraft, ExpenseRule, LoginList, Policy} from '@src/types/onyx'; import type Login from '@src/types/onyx/Login'; import type {Errors} from '@src/types/onyx/OnyxCommon'; -import type {OnyxServerUpdate, OnyxUpdatesFromServer} from '@src/types/onyx/OnyxUpdatesFromServer'; +import type {AnyOnyxServerUpdate, OnyxServerUpdate, OnyxUpdateEvent} from '@src/types/onyx/OnyxUpdatesFromServer'; import type OnyxPersonalDetails from '@src/types/onyx/PersonalDetails'; import type {Status} from '@src/types/onyx/PersonalDetails'; import type ReportAction from '@src/types/onyx/ReportAction'; @@ -685,7 +685,7 @@ function isBlockedFromConcierge(blockedFromConciergeNVP: OnyxEntry(onyxUpdates: Array>, currentUserAccountIDParam: number) { for (const update of onyxUpdates) { if (!update.shouldNotify && !update.shouldShowPushNotification) { continue; @@ -716,7 +716,7 @@ const isChannelMuted = (reportId: string) => }); }); -function playSoundForMessageType(pushJSON: OnyxServerUpdate[]) { +function playSoundForMessageType(pushJSON: Array>) { const reportActionsOnly = pushJSON.filter((update) => update.key?.includes('reportActions_')); // "reportActions_5134363522480668" -> "5134363522480668" const reportID = reportActionsOnly @@ -932,7 +932,7 @@ function subscribeToUserEvents(currentUserAccountIDParam: number) { // Handles the mega multipleEvents from Pusher which contains an array of single events. // Each single event is passed to PusherUtils in order to trigger the callbacks for that event PusherUtils.subscribeToPrivateUserChannelEvent(Pusher.TYPE.MULTIPLE_EVENTS, currentUserAccountIDParam.toString(), (pushJSON) => { - const pushEventData = pushJSON as OnyxUpdatesFromServer; + const pushEventData = pushJSON; // If this is not the main client, we shouldn't process any data received from pusher. if (!ActiveClientManager.isClientTheLeader()) { Log.info('[Pusher] Received updates, but ignoring it since this is not the active client'); @@ -943,7 +943,7 @@ function subscribeToUserEvents(currentUserAccountIDParam: number) { const updates = { type: CONST.ONYX_UPDATE_TYPES.PUSHER, lastUpdateID: Number(pushEventData.lastUpdateID ?? CONST.DEFAULT_NUMBER_ID), - updates: pushEventData.updates ?? [], + updates: (pushEventData.updates as OnyxUpdateEvent[]) ?? [], previousUpdateID: Number(pushJSON.previousUpdateID ?? CONST.DEFAULT_NUMBER_ID), }; Log.info('[subscribeToUserEvents] Applying Onyx updates'); @@ -953,7 +953,7 @@ function subscribeToUserEvents(currentUserAccountIDParam: number) { // Debounce the playSoundForMessageType function to avoid playing sounds too often, for example when a user comeback after offline and a lot of messages come in // See https://github.com/Expensify/App/issues/57961 for more details const debouncedPlaySoundForMessageType = debounce( - (pushJSONMessage: OnyxServerUpdate[]) => { + (pushJSONMessage: AnyOnyxServerUpdate[]) => { playSoundForMessageType(pushJSONMessage); }, CONST.TIMING.PLAY_SOUND_MESSAGE_DEBOUNCE_TIME, @@ -961,7 +961,7 @@ function subscribeToUserEvents(currentUserAccountIDParam: number) { ); // Handles Onyx updates coming from Pusher through the mega multipleEvents. - PusherUtils.subscribeToMultiEvent(Pusher.TYPE.MULTIPLE_EVENT_TYPE.ONYX_API_UPDATE, (pushJSON: OnyxServerUpdate[]) => { + PusherUtils.subscribeToMultiEvent(Pusher.TYPE.MULTIPLE_EVENT_TYPE.ONYX_API_UPDATE, (pushJSON: AnyOnyxServerUpdate[]) => { debouncedPlaySoundForMessageType(pushJSON); return SequentialQueue.getCurrentRequest().then(() => { @@ -1699,7 +1699,7 @@ function deleteExpenseRules(expenseRules: ExpenseRule[], selectedRuleKeys: strin value: JSON.stringify(rulesForAPI), }; - const optimisticData: OnyxUpdate[] = [ + const optimisticData: Array> = [ { onyxMethod: Onyx.METHOD.SET, key: ONYXKEYS.NVP_EXPENSE_RULES, @@ -1707,7 +1707,7 @@ function deleteExpenseRules(expenseRules: ExpenseRule[], selectedRuleKeys: strin }, ]; - const successData: OnyxUpdate[] = [ + const successData: Array> = [ { onyxMethod: Onyx.METHOD.SET, key: ONYXKEYS.NVP_EXPENSE_RULES, @@ -1715,7 +1715,7 @@ function deleteExpenseRules(expenseRules: ExpenseRule[], selectedRuleKeys: strin }, ]; - const failureData: OnyxUpdate[] = [ + const failureData: Array> = [ { onyxMethod: Onyx.METHOD.SET, key: ONYXKEYS.NVP_EXPENSE_RULES, @@ -1789,7 +1789,7 @@ function saveExpenseRule(expenseRules: ExpenseRule[], newRule: ExpenseRule, exis value: JSON.stringify(rulesForAPI), }; - const optimisticData: OnyxUpdate[] = [ + const optimisticData: Array> = [ { onyxMethod: Onyx.METHOD.SET, key: ONYXKEYS.NVP_EXPENSE_RULES, @@ -1797,7 +1797,7 @@ function saveExpenseRule(expenseRules: ExpenseRule[], newRule: ExpenseRule, exis }, ]; - const successData: OnyxUpdate[] = [ + const successData: Array> = [ { onyxMethod: Onyx.METHOD.SET, key: ONYXKEYS.NVP_EXPENSE_RULES, @@ -1805,7 +1805,7 @@ function saveExpenseRule(expenseRules: ExpenseRule[], newRule: ExpenseRule, exis }, ]; - const failureData: OnyxUpdate[] = [ + const failureData: Array> = [ { onyxMethod: Onyx.METHOD.SET, key: ONYXKEYS.NVP_EXPENSE_RULES, diff --git a/src/libs/actions/__mocks__/App.ts b/src/libs/actions/__mocks__/App.ts index e8ac362a679c..a604f78b882f 100644 --- a/src/libs/actions/__mocks__/App.ts +++ b/src/libs/actions/__mocks__/App.ts @@ -1,3 +1,4 @@ +import type {OnyxKey} from 'react-native-onyx'; import type * as AppImport from '@libs/actions/App'; import * as OnyxUpdates from '@userActions/OnyxUpdates'; import type {OnyxUpdatesFromServer} from '@src/types/onyx'; @@ -22,13 +23,13 @@ const { KEYS_TO_PRESERVE, } = AppImplementation; -type AppMockValues = { - missingOnyxUpdatesToBeApplied: OnyxUpdatesFromServer[] | undefined; +type AppMockValues = { + missingOnyxUpdatesToBeApplied: Array> | undefined; }; -type AppActionsMock = typeof AppImport & { +type AppActionsMock = typeof AppImport & { getMissingOnyxUpdates: jest.Mock>; - mockValues: AppMockValues; + mockValues: AppMockValues; }; const mockValues: AppMockValues = { @@ -43,7 +44,7 @@ const getMissingOnyxUpdates = jest.fn((updateIDFrom: number, updateIDTo: number) updates.push({ lastUpdateID: i, previousUpdateID: i - 1, - } as OnyxUpdatesFromServer); + } as OnyxUpdatesFromServer); } } diff --git a/src/libs/actions/__mocks__/OnyxUpdates.ts b/src/libs/actions/__mocks__/OnyxUpdates.ts index e54b423259f1..d43d457dfcc2 100644 --- a/src/libs/actions/__mocks__/OnyxUpdates.ts +++ b/src/libs/actions/__mocks__/OnyxUpdates.ts @@ -1,3 +1,4 @@ +import type {OnyxKey} from 'react-native-onyx'; import Onyx from 'react-native-onyx'; import type * as OnyxUpdatesImport from '@userActions/OnyxUpdates'; import ONYXKEYS from '@src/ONYXKEYS'; @@ -8,8 +9,8 @@ jest.mock('@libs/actions/OnyxUpdateManager/utils/applyUpdates'); const OnyxUpdatesImplementation = jest.requireActual('@libs/actions/OnyxUpdates'); const {doesClientNeedToBeUpdated, saveUpdateInformation, INTERNAL_DO_NOT_USE_applyHTTPSOnyxUpdates: applyHTTPSOnyxUpdates} = OnyxUpdatesImplementation; -type OnyxUpdatesMock = typeof OnyxUpdatesImport & { - apply: jest.Mock, [OnyxUpdatesFromServer]>; +type OnyxUpdatesMock = typeof OnyxUpdatesImport & { + apply: jest.Mock | void>, [OnyxUpdatesFromServer]>; }; let lastUpdateIDAppliedToClient: number | undefined = 0; @@ -19,7 +20,7 @@ Onyx.connectWithoutView({ callback: (val) => (lastUpdateIDAppliedToClient = val), }); -const apply = jest.fn(({lastUpdateID, request, response}: OnyxUpdatesFromServer): Promise | undefined => { +const apply = jest.fn(({lastUpdateID, request, response}: OnyxUpdatesFromServer): Promise> | undefined => { if (lastUpdateID && (lastUpdateIDAppliedToClient === undefined || Number(lastUpdateID) > lastUpdateIDAppliedToClient)) { Onyx.merge(ONYXKEYS.ONYX_UPDATES_LAST_UPDATE_ID_APPLIED_TO_CLIENT, Number(lastUpdateID)); } diff --git a/src/libs/actions/applyOnyxUpdatesReliably.ts b/src/libs/actions/applyOnyxUpdatesReliably.ts index 6c3fe709aadf..81e029ec340e 100644 --- a/src/libs/actions/applyOnyxUpdatesReliably.ts +++ b/src/libs/actions/applyOnyxUpdatesReliably.ts @@ -1,3 +1,4 @@ +import type {OnyxKey} from 'react-native-onyx'; import Log from '@libs/Log'; import * as SequentialQueue from '@libs/Network/SequentialQueue'; import CONST from '@src/CONST'; @@ -19,7 +20,10 @@ type ApplyOnyxUpdatesReliablyOptions = { * @param shouldRunSync * @returns */ -export default function applyOnyxUpdatesReliably(updates: OnyxUpdatesFromServer, {shouldRunSync = false, clientLastUpdateID}: ApplyOnyxUpdatesReliablyOptions = {}): Promise { +export default function applyOnyxUpdatesReliably( + updates: OnyxUpdatesFromServer, + {shouldRunSync = false, clientLastUpdateID}: ApplyOnyxUpdatesReliablyOptions = {}, +): Promise { const fetchMissingUpdates = () => { Log.info('[applyOnyxUpdatesReliably] Fetching missing updates'); // If we got here, that means we are missing some updates on our local storage. To diff --git a/src/types/onyx/OnyxUpdatesFromServer.ts b/src/types/onyx/OnyxUpdatesFromServer.ts index a0a83b51a26a..0b03fe598554 100644 --- a/src/types/onyx/OnyxUpdatesFromServer.ts +++ b/src/types/onyx/OnyxUpdatesFromServer.ts @@ -1,10 +1,25 @@ import type {OnyxKey, OnyxUpdate} from 'react-native-onyx'; import CONST from '@src/CONST'; import type Request from './Request'; +import type {AnyOnyxUpdate, AnyRequest} from './Request'; import type Response from './Response'; +/** + * Model of a onyx server update + * + * This type was created as a solution during the migration away from the large OnyxKey union and is useful for contexts where the specific Onyx keys are not known ahead of time. + * It should only be used in legacy code where providing exact key types would require major restructuring. + */ +type AnyOnyxServerUpdate = AnyOnyxUpdate & { + /** Whether the update should notify UI */ + shouldNotify?: boolean; + + /** Whether the update should be shown as a push notification */ + shouldShowPushNotification?: boolean; +}; + /** Model of a onyx server update */ -type OnyxServerUpdate = OnyxUpdate & { +type OnyxServerUpdate = OnyxUpdate & { /** Whether the update should notify UI */ shouldNotify?: boolean; @@ -21,8 +36,8 @@ type OnyxUpdateEvent = { data: Array>; }; -/** Model of onyx server updates */ -type OnyxUpdatesFromServer = { +/** Generic base for types of onyx server updates */ +type OnyxUpdatesFromServerBase = { /** Delivery method of onyx updates */ type: 'https' | 'pusher' | 'airship'; @@ -36,7 +51,7 @@ type OnyxUpdatesFromServer = { shouldFetchPendingUpdates?: boolean; /** Request data sent to the server */ - request?: Request; + request?: TRequest; /** Response data from server */ response?: Response; @@ -45,13 +60,26 @@ type OnyxUpdatesFromServer = { updates?: Array>; }; +/** + * Model of onyx server updates + * + * This type was created as a solution during the migration away from the large OnyxKey union and is useful for contexts where the specific Onyx keys are not known ahead of time. + * It should only be used in legacy code where providing exact key types would require major restructuring. + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +type AnyOnyxUpdatesFromServer = OnyxUpdatesFromServerBase; + +/** Model of onyx server updates */ +type OnyxUpdatesFromServer = OnyxUpdatesFromServerBase>; + /** * Helper function to determine if onyx update received from server is valid * * @param value - represent the onyx update received from the server * @returns boolean indicating if the onyx update received from the server is valid */ -function isValidOnyxUpdateFromServer(value: unknown): value is OnyxUpdatesFromServer { +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function isValidOnyxUpdateFromServer(value: unknown): value is AnyOnyxUpdatesFromServer { if (!value || typeof value !== 'object') { return false; } @@ -78,4 +106,4 @@ function isValidOnyxUpdateFromServer(value: unknown): value is OnyxUpdatesFromSe export {isValidOnyxUpdateFromServer}; -export type {OnyxUpdatesFromServer, OnyxUpdateEvent, OnyxServerUpdate}; +export type {OnyxUpdatesFromServer, AnyOnyxUpdatesFromServer, OnyxUpdateEvent, OnyxServerUpdate, AnyOnyxServerUpdate}; diff --git a/src/types/onyx/Response.ts b/src/types/onyx/Response.ts index 2af7d651a519..9c2daf41c755 100644 --- a/src/types/onyx/Response.ts +++ b/src/types/onyx/Response.ts @@ -11,7 +11,7 @@ type Data = { }; /** Model of server response */ -type Response = { +type Response = { /** ID of the next update that needs to be fetched from the server */ previousUpdateID?: number | string; diff --git a/src/types/onyx/index.ts b/src/types/onyx/index.ts index 109146c91748..0e7e3fe14bb9 100644 --- a/src/types/onyx/index.ts +++ b/src/types/onyx/index.ts @@ -91,7 +91,7 @@ import type NewGroupChatDraft from './NewGroupChatDraft'; import type Onboarding from './Onboarding'; import type OnboardingRHPVariant from './OnboardingRHPVariant'; import type OnyxInputOrEntry from './OnyxInputOrEntry'; -import type {OnyxUpdateEvent, OnyxUpdatesFromServer} from './OnyxUpdatesFromServer'; +import type {AnyOnyxUpdatesFromServer, OnyxUpdateEvent, OnyxUpdatesFromServer} from './OnyxUpdatesFromServer'; import type {DecisionName, OriginalMessageIOU} from './OriginalMessage'; import type Pages from './Pages'; import type {PendingContactAction} from './PendingContactAction'; @@ -229,6 +229,7 @@ export type { OnyxInputOrEntry, OnyxUpdateEvent, OnyxUpdatesFromServer, + AnyOnyxUpdatesFromServer, Pages, PersonalBankAccount, PersonalDetails, diff --git a/tests/actions/OnyxUpdateManagerTest.ts b/tests/actions/OnyxUpdateManagerTest.ts index 73ef3b799b84..c17eecfd0e5e 100644 --- a/tests/actions/OnyxUpdateManagerTest.ts +++ b/tests/actions/OnyxUpdateManagerTest.ts @@ -42,14 +42,14 @@ jest.mock('@src/libs/SearchUIUtils', () => ({ getSuggestedSearches: jest.fn().mockReturnValue({}), })); -const App = AppImport as AppActionsMock; -const ApplyUpdates = ApplyUpdatesImport as ApplyUpdatesMock; -const OnyxUpdateManagerUtils = OnyxUpdateManagerUtilsImport as OnyxUpdateManagerUtilsMock; - const TEST_USER_ACCOUNT_ID = 1; const REPORT_ID = 'testReport1'; const ONYX_KEY = `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${REPORT_ID}` as const; +const App = AppImport as AppActionsMock; +const ApplyUpdates = ApplyUpdatesImport as ApplyUpdatesMock; +const OnyxUpdateManagerUtils = OnyxUpdateManagerUtilsImport as OnyxUpdateManagerUtilsMock; + const exampleReportAction = { actionName: CONST.REPORT.ACTIONS.TYPE.ADD_COMMENT, actorAccountID: TEST_USER_ACCOUNT_ID, diff --git a/tests/actions/connections/QuickbooksOnline.ts b/tests/actions/connections/QuickbooksOnline.ts index c4bda725bbfb..d8c1b9f91506 100644 --- a/tests/actions/connections/QuickbooksOnline.ts +++ b/tests/actions/connections/QuickbooksOnline.ts @@ -23,7 +23,7 @@ const MOCK_ACCOUNT_ID = 'account-123'; const MOCK_OLD_ACCOUNT_ID = 'account-456'; const MOCK_ONYX_ERROR = {key: 'error'}; -function getQuickBooksConfig(update?: OnyxUpdate): QBOConnectionConfig | undefined { +function getQuickBooksConfig(update?: OnyxUpdate): QBOConnectionConfig | undefined { if (!update || typeof update.value !== 'object' || update.value === null) { return undefined; } @@ -33,7 +33,7 @@ function getQuickBooksConfig(update?: OnyxUpdate): QBOConnectionConfig | undefin return connection?.config; } -function getRequiredQuickBooksConfig(update?: OnyxUpdate): QBOConnectionConfig { +function getRequiredQuickBooksConfig(update?: OnyxUpdate): QBOConnectionConfig { const config = getQuickBooksConfig(update); if (!config) { throw new Error('QuickBooks config is missing from the provided Onyx update'); diff --git a/tests/ui/UnreadIndicatorsTest.tsx b/tests/ui/UnreadIndicatorsTest.tsx index 3618310c55bc..2c94d78eb0e6 100644 --- a/tests/ui/UnreadIndicatorsTest.tsx +++ b/tests/ui/UnreadIndicatorsTest.tsx @@ -337,7 +337,7 @@ describe('Unread Indicators', () => { const NEW_REPORT_FIST_MESSAGE_CREATED_DATE = addSeconds(NEW_REPORT_CREATED_DATE, 1); const createdReportActionIDLocal = rand64(); const commentReportActionID = rand64(); - PusherHelper.emitOnyxUpdate([ + PusherHelper.emitOnyxUpdate([ { onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.REPORT}${NEW_REPORT_ID}`, diff --git a/tests/ui/WorkEmailOnboarding.tsx b/tests/ui/WorkEmailOnboarding.tsx index 65e39f4985a8..996675136344 100644 --- a/tests/ui/WorkEmailOnboarding.tsx +++ b/tests/ui/WorkEmailOnboarding.tsx @@ -97,7 +97,7 @@ const navigate = jest.spyOn(Navigation, 'navigate'); function MergeIntoAccountAndLoginBlockMerge() { const originalXhr = HttpUtils.xhr; HttpUtils.xhr = jest.fn().mockImplementation(() => { - const mockedResponse: OnyxResponse = { + const mockedResponse: OnyxResponse = { jsonCode: 501, onyxData: [ { @@ -122,7 +122,7 @@ function MergeIntoAccountAndLoginBlockMerge() { function MergeIntoAccountAndLoginSuccessful() { const originalXhr = HttpUtils.xhr; HttpUtils.xhr = jest.fn().mockImplementation(() => { - const mockedResponse: OnyxResponse = { + const mockedResponse: OnyxResponse = { jsonCode: 401, onyxData: [ { @@ -145,7 +145,7 @@ function MergeIntoAccountAndLoginSuccessful() { function MergeIntoAccountAndLoginRedirectToClassic() { const originalXhr = HttpUtils.xhr; HttpUtils.xhr = jest.fn().mockImplementation(() => { - const mockedResponse: OnyxResponse = { + const mockedResponse: OnyxResponse = { jsonCode: 200, onyxData: [ { @@ -169,7 +169,7 @@ function MergeIntoAccountAndLoginRedirectToClassic() { function AddWorkEmailShouldValidateFailure() { const originalXhr = HttpUtils.xhr; HttpUtils.xhr = jest.fn().mockImplementation(() => { - const mockedResponse: OnyxResponse = { + const mockedResponse: OnyxResponse = { jsonCode: 200, onyxData: [ { @@ -192,7 +192,7 @@ function AddWorkEmailShouldValidateFailure() { function AddWorkEmailShouldValidate() { const originalXhr = HttpUtils.xhr; HttpUtils.xhr = jest.fn().mockImplementation(() => { - const mockedResponse: OnyxResponse = { + const mockedResponse: OnyxResponse = { jsonCode: 200, onyxData: [ { diff --git a/tests/unit/OnyxUpdateManagerTest.ts b/tests/unit/OnyxUpdateManagerTest.ts index a5b620b62ce7..7ae70275bd81 100644 --- a/tests/unit/OnyxUpdateManagerTest.ts +++ b/tests/unit/OnyxUpdateManagerTest.ts @@ -14,6 +14,7 @@ import * as ApplyUpdatesImport from '@userActions/OnyxUpdateManager/utils/applyU // eslint-disable-next-line no-restricted-syntax -- this is required to allow mocking import * as OnyxUpdatesImport from '@userActions/OnyxUpdates'; import ONYXKEYS from '@src/ONYXKEYS'; +import type {OnyxUpdatesFromServer} from '@src/types/onyx'; import OnyxUpdateMockUtils from '../utils/OnyxUpdateMockUtils'; jest.mock('@userActions/OnyxUpdates'); @@ -31,15 +32,16 @@ jest.mock('@src/libs/SearchUIUtils', () => ({ getSuggestedSearches: jest.fn().mockReturnValue({}), })); -const OnyxUpdates = OnyxUpdatesImport as OnyxUpdatesMock; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +const OnyxUpdates = OnyxUpdatesImport as OnyxUpdatesMock; const App = AppImport as AppActionsMock; const ApplyUpdates = ApplyUpdatesImport as ApplyUpdatesMock; const OnyxUpdateManagerUtils = OnyxUpdateManagerUtilsImport as OnyxUpdateManagerUtilsMock; -const update2 = OnyxUpdateMockUtils.createUpdate(2); +const update2: OnyxUpdatesFromServer = OnyxUpdateMockUtils.createUpdate(2); const pendingUpdateUpTo2 = OnyxUpdateMockUtils.createPendingUpdate(2); -const update3 = OnyxUpdateMockUtils.createUpdate(3); +const update3: OnyxUpdatesFromServer = OnyxUpdateMockUtils.createUpdate(3); const pendingUpdateUpTo3 = OnyxUpdateMockUtils.createPendingUpdate(3); const offsetUpdate3 = OnyxUpdateMockUtils.createUpdate(3, undefined, 1); diff --git a/tests/unit/OnyxUpdatesTest.ts b/tests/unit/OnyxUpdatesTest.ts index 563acb6ee909..f5f01942bbf8 100644 --- a/tests/unit/OnyxUpdatesTest.ts +++ b/tests/unit/OnyxUpdatesTest.ts @@ -33,7 +33,7 @@ describe('OnyxUpdatesTest', () => { }; // Given an onyx update from an Airship push notification - const airshipUpdates: OnyxUpdatesFromServer = { + const airshipUpdates: OnyxUpdatesFromServer = { type: CONST.ONYX_UPDATE_TYPES.AIRSHIP, previousUpdateID: 0, lastUpdateID: 1, @@ -74,7 +74,7 @@ describe('OnyxUpdatesTest', () => { // And we received onyx updates from a full ReconnectApp request with the same lastUpdateID const reportID = NumberUtils.rand64(); const reportValue = {reportID}; - const fullReconnectUpdates: OnyxUpdatesFromServer = { + const fullReconnectUpdates: OnyxUpdatesFromServer = { type: CONST.ONYX_UPDATE_TYPES.HTTPS, request: { command: SIDE_EFFECT_REQUEST_COMMANDS.RECONNECT_APP, diff --git a/tests/utils/OnyxUpdateMockUtils.ts b/tests/utils/OnyxUpdateMockUtils.ts index c9c289c11a7f..04fd4155297a 100644 --- a/tests/utils/OnyxUpdateMockUtils.ts +++ b/tests/utils/OnyxUpdateMockUtils.ts @@ -1,9 +1,8 @@ -import type {OnyxUpdate} from 'react-native-onyx'; +import type {OnyxKey, OnyxUpdate} from 'react-native-onyx'; import CONST from '@src/CONST'; -import type ONYXKEYS from '@src/ONYXKEYS'; import type {OnyxUpdatesFromServer} from '@src/types/onyx'; -const createUpdate = (lastUpdateID: number, successData: Array> = [], previousUpdateID?: number): OnyxUpdatesFromServer => ({ +const createUpdate = (lastUpdateID: number, successData: Array> = [], previousUpdateID?: number): OnyxUpdatesFromServer => ({ type: CONST.ONYX_UPDATE_TYPES.HTTPS, lastUpdateID, previousUpdateID: previousUpdateID ?? lastUpdateID - 1, @@ -23,7 +22,7 @@ const createUpdate = (lastUpdateID: number, successData: Array ({ +const createPendingUpdate = (lastUpdateID: number): OnyxUpdatesFromServer => ({ type: CONST.ONYX_UPDATE_TYPES.AIRSHIP, lastUpdateID, shouldFetchPendingUpdates: true, diff --git a/tests/utils/PusherHelper.ts b/tests/utils/PusherHelper.ts index fe84cc9344de..495612b85e0c 100644 --- a/tests/utils/PusherHelper.ts +++ b/tests/utils/PusherHelper.ts @@ -1,8 +1,9 @@ +import type {OnyxKey} from 'react-native-onyx'; import Pusher from '@libs/Pusher'; import CONFIG from '@src/CONFIG'; import CONST from '@src/CONST'; import PusherConnectionManager from '@src/libs/PusherConnectionManager'; -import type {OnyxServerUpdate} from '@src/types/onyx/OnyxUpdatesFromServer'; +import type {AnyOnyxServerUpdate, OnyxServerUpdate} from '@src/types/onyx/OnyxUpdatesFromServer'; const CHANNEL_NAME = `${CONST.PUSHER.PRIVATE_USER_CHANNEL_PREFIX}1${CONFIG.PUSHER.SUFFIX}`; @@ -28,7 +29,7 @@ function setup() { } } -function emitOnyxUpdate(args: OnyxServerUpdate[]) { +function emitOnyxUpdate(args: Array>) { Pusher.sendEvent(CHANNEL_NAME, Pusher.TYPE.MULTIPLE_EVENTS, { type: 'pusher', lastUpdateID: 0, @@ -36,7 +37,8 @@ function emitOnyxUpdate(args: OnyxServerUpdate[]) { updates: [ { eventType: Pusher.TYPE.MULTIPLE_EVENT_TYPE.ONYX_API_UPDATE, - data: args, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + data: args as AnyOnyxServerUpdate[], }, ], }); diff --git a/tests/utils/TestHelper.ts b/tests/utils/TestHelper.ts index 09515f43e709..22ee3be842bc 100644 --- a/tests/utils/TestHelper.ts +++ b/tests/utils/TestHelper.ts @@ -27,7 +27,7 @@ type MockFetch = jest.MockedFn & { fail: () => void; succeed: () => void; resume: () => Promise; - mockAPICommand: (command: TCommand, responseHandler: (params: ApiRequestCommandParameters[TCommand]) => OnyxResponse) => void; + mockAPICommand: (command: TCommand, responseHandler: (params: ApiRequestCommandParameters[TCommand]) => OnyxResponse) => void; }; type ConnectionCallback = NonNullable['callback']>; @@ -159,7 +159,7 @@ function signInWithTestUser(accountID = 1, login = 'test@user.com', password = ' const originalXhr = HttpUtils.xhr; HttpUtils.xhr = jest.fn().mockImplementation(() => { - const mockedResponse: OnyxResponse = { + const mockedResponse: OnyxResponse = { onyxData: [ { onyxMethod: Onyx.METHOD.MERGE, @@ -195,7 +195,9 @@ function signInWithTestUser(accountID = 1, login = 'test@user.com', password = ' return waitForBatchedUpdates() .then(() => { HttpUtils.xhr = jest.fn().mockImplementation(() => { - const mockedResponse: OnyxResponse = { + const mockedResponse: OnyxResponse< + typeof ONYXKEYS.SESSION | typeof ONYXKEYS.CREDENTIALS | typeof ONYXKEYS.ACCOUNT | typeof ONYXKEYS.BETAS | typeof ONYXKEYS.NVP_PRIVATE_PUSH_NOTIFICATION_ID + > = { onyxData: [ { onyxMethod: Onyx.METHOD.MERGE, @@ -250,7 +252,7 @@ function signInWithTestUser(accountID = 1, login = 'test@user.com', password = ' function signOutTestUser() { const originalXhr = HttpUtils.xhr; HttpUtils.xhr = jest.fn().mockImplementation(() => { - const mockedResponse: OnyxResponse = { + const mockedResponse: OnyxResponse = { jsonCode: 200, }; @@ -272,7 +274,7 @@ function signOutTestUser() { function getGlobalFetchMock(): typeof fetch { let queue: QueueItem[] = []; // eslint-disable-next-line @typescript-eslint/no-explicit-any - let responses = new Map OnyxResponse>(); + let responses = new Map OnyxResponse>(); let isPaused = false; let shouldFail = false; @@ -327,7 +329,8 @@ function getGlobalFetchMock(): typeof fetch { }; mockFetch.fail = () => (shouldFail = true); mockFetch.succeed = () => (shouldFail = false); - mockFetch.mockAPICommand = (command: TCommand, responseHandler: (params: ApiRequestCommandParameters[TCommand]) => OnyxResponse): void => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + mockFetch.mockAPICommand = (command: TCommand, responseHandler: (params: ApiRequestCommandParameters[TCommand]) => OnyxResponse): void => { responses.set(command, responseHandler); }; return mockFetch as typeof fetch;