diff --git a/src/components/GpsDraftDetailsRefSync.tsx b/src/components/GpsDraftDetailsRefSync.tsx new file mode 100644 index 000000000000..f24d1c68cfd8 --- /dev/null +++ b/src/components/GpsDraftDetailsRefSync.tsx @@ -0,0 +1,29 @@ +import useOnyx from '@hooks/useOnyx'; + +import ONYXKEYS from '@src/ONYXKEYS'; +import type GpsDraftDetails from '@src/types/onyx/GpsDraftDetails'; + +import type {RefObject} from 'react'; + +import {useEffect} from 'react'; + +type GpsDraftDetailsRefSyncProps = { + gpsDraftDetailsRef: RefObject; +}; + +/** + * Keeps the latest GPS draft details in a ref without re-rendering the parent. + * Mount only while copilot leave + active GPS trip (e.g. require-2FA overlay). + */ +function GpsDraftDetailsRefSync({gpsDraftDetailsRef}: GpsDraftDetailsRefSyncProps) { + const [gpsDraftDetails] = useOnyx(ONYXKEYS.GPS_DRAFT_DETAILS); + + useEffect(() => { + // eslint-disable-next-line no-param-reassign -- ref sync intentionally mutates .current for the parent overlay + gpsDraftDetailsRef.current = gpsDraftDetails; + }, [gpsDraftDetails, gpsDraftDetailsRef]); + + return null; +} + +export default GpsDraftDetailsRefSync; diff --git a/src/hooks/useSignOut.ts b/src/hooks/useSignOut.ts new file mode 100644 index 000000000000..4a3b8e4cef8b --- /dev/null +++ b/src/hooks/useSignOut.ts @@ -0,0 +1,216 @@ +import {ModalActions} from '@components/Modal/Global/ModalContext'; + +import {disconnect} from '@libs/actions/Delegate'; +import {showPermissionErrorAlert} from '@libs/fileDownload/FileUtils'; +import {getGpsPoints, stopGpsTrip} from '@libs/GPSDraftDetailsUtils'; +import Log from '@libs/Log'; +import {getSaveablePendingReceiptRequests, saveReceiptsToGallery} from '@libs/savePendingReceiptsToGallery'; + +import {BACKGROUND_LOCATION_TRACKING_TASK_NAME} from '@pages/iou/request/step/IOURequestStepDistanceGPS/const'; +import {stopGpsTripNotification} from '@pages/iou/request/step/IOURequestStepDistanceGPS/GPSNotifications'; + +import {signOutAndRedirectToSignIn} from '@userActions/Session'; + +import CONST from '@src/CONST'; +import ONYXKEYS from '@src/ONYXKEYS'; +import {isActingAsDelegateSelector} from '@src/selectors/Account'; +import {isTrackingSelector} from '@src/selectors/GPSDraftDetails'; +import type GpsDraftDetails from '@src/types/onyx/GpsDraftDetails'; + +import type {RefObject} from 'react'; + +import {stopLocationUpdatesAsync} from 'expo-location'; + +import useConfirmModal from './useConfirmModal'; +import useLocalize from './useLocalize'; +import useNetwork from './useNetwork'; +import useOnyx from './useOnyx'; + +type SignOutOptions = { + /** When true, always show the generic sign-out confirm (e.g. from the require-2FA overlay). GPS and receipt prompts still run when applicable. */ + shouldAlwaysConfirm?: boolean; +}; + +type LeaveDelegateAccountOptions = { + /** Ref kept current by GpsDraftDetailsRefSync. Read only after the user confirms, so points stay fresh while the modal is open. */ + gpsDraftDetailsRef?: RefObject; +}; + +/** Stops a second Sign out or Leave press from stacking another confirm modal. */ +let isSignOutFlowInFlight = false; + +function useSignOut() { + const {translate} = useLocalize(); + const {isOffline} = useNetwork(); + const {showConfirmModal} = useConfirmModal(); + const [isTrackingGPS = false] = useOnyx(ONYXKEYS.GPS_DRAFT_DETAILS, { + selector: isTrackingSelector, + }); + const [isActingAsDelegate = false] = useOnyx(ONYXKEYS.ACCOUNT, { + selector: isActingAsDelegateSelector, + }); + const [stashedCredentials = CONST.EMPTY_OBJECT] = useOnyx(ONYXKEYS.STASHED_CREDENTIALS); + const [stashedSession] = useOnyx(ONYXKEYS.STASHED_SESSION); + + const showOfflineModal = () => { + showConfirmModal({ + title: translate('common.youAppearToBeOffline'), + prompt: translate('common.offlinePrompt'), + confirmText: translate('common.buttonConfirm'), + shouldShowCancelButton: false, + }); + }; + + const signOutImmediately = () => { + signOutAndRedirectToSignIn(); + }; + + const runSignOut = async ({shouldAlwaysConfirm = false}: SignOutOptions = {}) => { + const saveableReceipts = getSaveablePendingReceiptRequests(); + const shouldWarnBeforeSignOut = isOffline || isTrackingGPS; + const isOfflineReceiptsCase = isOffline && !isTrackingGPS && saveableReceipts.length > 0; + + if (!shouldAlwaysConfirm && !shouldWarnBeforeSignOut && saveableReceipts.length === 0) { + return signOutAndRedirectToSignIn(); + } + + const confirmModalTitle = isTrackingGPS ? translate('gps.signOutWarningTripInProgress.title') : translate('common.areYouSure'); + const confirmModalPrompt = isTrackingGPS ? translate('gps.signOutWarningTripInProgress.prompt') : translate('initialSettingsPage.signOutConfirmationText'); + const confirmModalConfirmText = isTrackingGPS ? translate('gps.signOutWarningTripInProgress.confirm') : translate('initialSettingsPage.signOut'); + + const saveReceipts = async () => { + try { + const {savedCount, failedCount, permissionDenied} = await saveReceiptsToGallery(saveableReceipts); + Log.info('[Receipt] Saved pending receipts to gallery before sign-out', false, {savedCount, failedCount, permissionDenied}); + if (permissionDenied) { + showPermissionErrorAlert(translate); + } + } catch (error) { + Log.alert('[Receipt] Unexpected rejection from saveReceiptsToGallery; sign-out continued', {error}); + } + }; + + if (isOfflineReceiptsCase) { + const result = await showConfirmModal({ + title: translate('initialSettingsPage.saveReceiptsAndSignOutConfirmation.title'), + prompt: translate('initialSettingsPage.saveReceiptsAndSignOutConfirmation.prompt', { + count: saveableReceipts.length, + }), + confirmText: translate('initialSettingsPage.saveReceiptsAndSignOutConfirmation.confirm'), + cancelText: translate('common.cancel'), + shouldShowCancelButton: true, + buttonVariant: CONST.BUTTON_VARIANT.DANGER, + }); + if (result.action !== ModalActions.CONFIRM) { + return; + } + await saveReceipts(); + } else { + const shouldShowOfflineOrGpsWarning = shouldWarnBeforeSignOut || shouldAlwaysConfirm; + if (shouldShowOfflineOrGpsWarning) { + const result = await showConfirmModal({ + title: confirmModalTitle, + prompt: confirmModalPrompt, + confirmText: confirmModalConfirmText, + cancelText: translate('common.cancel'), + shouldShowCancelButton: true, + buttonVariant: CONST.BUTTON_VARIANT.DANGER, + }); + if (result.action !== ModalActions.CONFIRM) { + return; + } + } + + if (saveableReceipts.length > 0) { + const result = await showConfirmModal({ + title: translate('initialSettingsPage.saveReceiptsConfirmation.title'), + prompt: translate('initialSettingsPage.saveReceiptsConfirmation.prompt', { + count: saveableReceipts.length, + }), + confirmText: translate('initialSettingsPage.saveReceiptsConfirmation.confirm'), + cancelText: translate('common.cancel'), + shouldShowCancelButton: true, + }); + if (result.action !== ModalActions.CONFIRM) { + return; + } + await saveReceipts(); + } + } + + if (isTrackingGPS) { + stopGpsTripNotification(); + stopLocationUpdatesAsync(BACKGROUND_LOCATION_TRACKING_TASK_NAME).catch((error) => console.error('[GPS distance request] Failed to stop location tracking', error)); + } + + return signOutAndRedirectToSignIn(); + }; + + const signOut = async ({shouldAlwaysConfirm = false}: SignOutOptions = {}) => { + if (isSignOutFlowInFlight) { + return; + } + isSignOutFlowInFlight = true; + + return runSignOut({shouldAlwaysConfirm}).finally(() => { + isSignOutFlowInFlight = false; + }); + }; + + const runLeaveDelegateAccount = async (gpsDraftDetailsRef?: RefObject) => { + if (isOffline) { + showOfflineModal(); + return; + } + + const result = await showConfirmModal({ + title: translate('common.areYouSure'), + prompt: translate('delegate.leaveAccountConfirmationText'), + confirmText: translate('delegate.leaveAccount'), + cancelText: translate('common.cancel'), + shouldShowCancelButton: true, + buttonVariant: CONST.BUTTON_VARIANT.DANGER, + }); + if (result.action !== ModalActions.CONFIRM) { + return; + } + + const leaveAction = () => disconnect({stashedCredentials, stashedSession}); + + if (isTrackingGPS) { + const gpsResult = await showConfirmModal({ + title: translate('gps.switchAccountWarningTripInProgress.title'), + prompt: translate('gps.switchAccountWarningTripInProgress.prompt'), + confirmText: translate('gps.switchAccountWarningTripInProgress.confirm'), + cancelText: translate('common.cancel'), + }); + if (gpsResult.action !== ModalActions.CONFIRM) { + return; + } + await stopGpsTrip(false, getGpsPoints(gpsDraftDetailsRef?.current), true); + } + + leaveAction(); + }; + + const leaveDelegateAccount = async ({gpsDraftDetailsRef}: LeaveDelegateAccountOptions = {}) => { + if (isSignOutFlowInFlight) { + return; + } + isSignOutFlowInFlight = true; + + return runLeaveDelegateAccount(gpsDraftDetailsRef).finally(() => { + isSignOutFlowInFlight = false; + }); + }; + + return { + signOut, + signOutImmediately, + leaveDelegateAccount, + isActingAsDelegate, + isTrackingGPS, + }; +} + +export default useSignOut; diff --git a/src/languages/de.ts b/src/languages/de.ts index 4517412af1ca..964138a31cbf 100644 --- a/src/languages/de.ts +++ b/src/languages/de.ts @@ -2554,7 +2554,7 @@ const translations: TranslationDeepObject = { twoFactorAuthIsRequiredForAdminsHeader: 'Zwei-Faktor-Authentifizierung erforderlich', twoFactorAuthIsRequiredForAdminsTitle: 'Bitte aktiviere die Zwei-Faktor-Authentifizierung', twoFactorAuthIsRequiredXero: 'Ihre Xero-Buchhaltungsverbindung erfordert eine Zwei-Faktor-Authentifizierung.', - twoFactorAuthIsRequiredCompany: 'Ihr Unternehmen verlangt eine Zwei-Faktor-Authentifizierung.', + twoFactorAuthIsRequiredCompany: 'Ihr Unternehmen erfordert eine Zwei-Faktor-Authentifizierung (2FA).', twoFactorAuthCannotDisable: '2FA kann nicht deaktiviert werden', twoFactorAuthRequired: 'Die Zwei-Faktor-Authentifizierung (2FA) ist für Ihre Xero-Verbindung erforderlich und kann nicht deaktiviert werden.', replaceDevice: 'Gerät ersetzen', @@ -2566,6 +2566,7 @@ const translations: TranslationDeepObject = { verifyNewDeviceDescription: 'Scannen Sie den QR-Code mit Ihrem neuen Gerät und geben Sie dann den Code ein, um die Einrichtung abzuschließen.', downloadCodes: 'Codes herunterladen', copyCodes: 'Codes kopieren', + enable2FA: 'Aktivieren', }, recoveryCodeForm: { error: { @@ -11106,6 +11107,8 @@ Fügen Sie weitere Ausgabelimits hinzu, um den Cashflow Ihres Unternehmens zu sc `Sind Sie sicher, dass Sie Ihren Copilot-Zugriff auf das Expensify-Konto von ${delegatorName} entfernen möchten? Diese Aktion kann nicht rückgängig gemacht werden.`, removeCopilotAccessConfirm: 'Zugriff entfernen', copilotAccess: 'Copilot-Zugriff', + leaveAccount: 'Konto verlassen', + leaveAccountConfirmationText: 'Sie kehren zu Ihrem eigenen Konto zurück. Sie werden nicht vollständig abgemeldet.', }, debug: { debug: 'Debug', diff --git a/src/languages/el.ts b/src/languages/el.ts index 5c5dcd4bf8d2..f51a097a3340 100644 --- a/src/languages/el.ts +++ b/src/languages/el.ts @@ -2608,7 +2608,7 @@ const translations: TranslationDeepObject = { twoFactorAuthIsRequiredForAdminsHeader: 'Απαιτείται έλεγχος ταυτότητας δύο παραγόντων', twoFactorAuthIsRequiredForAdminsTitle: 'Παρακαλούμε ενεργοποιήστε τον έλεγχο ταυτότητας δύο παραγόντων', twoFactorAuthIsRequiredXero: 'Η σύνδεσή σας με το λογιστικό σύστημα Xero απαιτεί έλεγχο ταυτότητας δύο παραγόντων.', - twoFactorAuthIsRequiredCompany: 'Η εταιρεία σας απαιτεί έλεγχο ταυτότητας δύο παραγόντων.', + twoFactorAuthIsRequiredCompany: 'Η εταιρεία σας απαιτεί έλεγχο ταυτότητας δύο παραγόντων (2FA).', twoFactorAuthCannotDisable: 'Δεν είναι δυνατή η απενεργοποίηση του 2FA', twoFactorAuthRequired: 'Η επαλήθευση δύο παραγόντων (2FA) είναι υποχρεωτική για τη σύνδεσή σας με το Xero και δεν μπορεί να απενεργοποιηθεί.', replaceDevice: 'Αντικατάσταση συσκευής', @@ -2618,6 +2618,7 @@ const translations: TranslationDeepObject = { verifyOldDeviceDescriptionWithRecovery: 'Εισαγάγετε έναν έγκυρο κωδικό ανάκτησης για να επιβεβαιώσετε ότι έχετε πρόσβαση στον λογαριασμό σας.', verifyNewDeviceTitle: 'Ρύθμιση νέας συσκευής', verifyNewDeviceDescription: 'Σαρώστε τον κωδικό QR με τη νέα σας συσκευή και κατόπιν εισαγάγετε τον κωδικό για να ολοκληρώσετε τη ρύθμιση.', + enable2FA: 'Ενεργοποίηση', }, recoveryCodeForm: { error: { @@ -11323,6 +11324,8 @@ ${reportName}`, notAllowedMessage: (accountOwnerEmail: string) => `Ως συνοδοιπόρος για τον/την ${accountOwnerEmail}, δεν έχετε δικαίωμα να εκτελέσετε αυτήν την ενέργεια. Συγγνώμη!`, copilotAccess: 'Πρόσβαση στο Copilot', + leaveAccount: 'Αποχώρηση από τον λογαριασμό', + leaveAccountConfirmationText: 'Θα επιστρέψετε στον δικό σας λογαριασμό. Δεν θα αποσυνδεθείτε πλήρως.', }, debug: { debug: 'Εντοπισμός σφαλμάτων', diff --git a/src/languages/en.ts b/src/languages/en.ts index d36fd9ffa7c6..d7454ed72e25 100644 --- a/src/languages/en.ts +++ b/src/languages/en.ts @@ -2660,12 +2660,13 @@ const translations = { copyCodes: 'Copy codes', disable: 'Disable', enableTwoFactorAuth: 'Enable two-factor authentication', + enable2FA: 'Enable', pleaseEnableTwoFactorAuth: 'Please enable two-factor authentication.', twoFactorAuthIsRequiredDescription: 'For security purposes, Xero requires two-factor authentication to connect the integration.', twoFactorAuthIsRequiredForAdminsHeader: 'Two-factor authentication required', twoFactorAuthIsRequiredForAdminsTitle: 'Please enable two-factor authentication', twoFactorAuthIsRequiredXero: 'Your Xero accounting connection requires two-factor authentication.', - twoFactorAuthIsRequiredCompany: 'Your company requires two-factor authentication.', + twoFactorAuthIsRequiredCompany: 'Your company requires two-factor authentication (2FA).', twoFactorAuthCannotDisable: 'Cannot disable 2FA', twoFactorAuthRequired: 'Two-factor authentication (2FA) is required for your Xero connection and cannot be disabled.', replaceDevice: 'Replace device', @@ -11246,6 +11247,8 @@ const translations = { removedRoomAvatar: 'removed the room avatar', }, delegate: { + leaveAccount: 'Leave account', + leaveAccountConfirmationText: "You'll return to your own account. You won't be fully signed out.", switchAccount: 'Switch accounts:', switch: 'Switch', copilot: 'Copilot', diff --git a/src/languages/es.ts b/src/languages/es.ts index 701340175a96..a369d224df29 100644 --- a/src/languages/es.ts +++ b/src/languages/es.ts @@ -2470,7 +2470,7 @@ const translations: TranslationDeepObject = { twoFactorAuthIsRequiredForAdminsHeader: 'Autenticación de dos factores requerida', twoFactorAuthIsRequiredForAdminsTitle: 'Por favor, habilita la autenticación de dos factores', twoFactorAuthIsRequiredXero: 'Tu conexión de contabilidad con Xero requiere el uso de autenticación de dos factores. Por favor, habilítala para seguir usando Expensify.', - twoFactorAuthIsRequiredCompany: 'Tu empresa requiere el uso de autenticación de dos factores. Por favor, habilítala para seguir usando Expensify.', + twoFactorAuthIsRequiredCompany: 'Tu empresa requiere autenticación de dos factores (2FA).', twoFactorAuthCannotDisable: 'No se puede desactivar la autenticación de dos factores (2FA)', twoFactorAuthRequired: 'La autenticación de dos factores (2FA) es obligatoria para tu conexión a Xero y no se puede desactivar.', replaceDevice: 'Reemplazar dispositivo', @@ -2482,6 +2482,7 @@ const translations: TranslationDeepObject = { verifyNewDeviceDescription: 'Escanea el código QR con tu nuevo dispositivo y luego introduce el código para completar la configuración.', downloadCodes: 'Descargar códigos', copyCodes: 'Copiar códigos', + enable2FA: 'Habilitar', }, recoveryCodeForm: { error: { @@ -11298,6 +11299,8 @@ ${reportName}`, notAllowedMessage: (accountOwnerEmail) => `Como copiloto de ${accountOwnerEmail}, no tienes permiso para realizar esta acción. ¡Lo siento!`, copilotAccess: 'Acceso a Copilot', + leaveAccount: 'Abandonar cuenta', + leaveAccountConfirmationText: 'Volverás a tu propia cuenta. No cerrarás sesión por completo.', }, debug: { debug: 'Depuración', diff --git a/src/languages/fr.ts b/src/languages/fr.ts index 0f489efc702d..d3abe7343025 100644 --- a/src/languages/fr.ts +++ b/src/languages/fr.ts @@ -2560,7 +2560,7 @@ const translations: TranslationDeepObject = { twoFactorAuthIsRequiredForAdminsHeader: 'Authentification à deux facteurs requise', twoFactorAuthIsRequiredForAdminsTitle: 'Veuillez activer l’authentification à deux facteurs', twoFactorAuthIsRequiredXero: 'Votre connexion comptable Xero nécessite une authentification à deux facteurs.', - twoFactorAuthIsRequiredCompany: 'Votre entreprise exige l’authentification à deux facteurs.', + twoFactorAuthIsRequiredCompany: 'Votre entreprise exige l’authentification à deux facteurs (2FA).', twoFactorAuthCannotDisable: 'Impossible de désactiver la 2FA', twoFactorAuthRequired: 'L’authentification à deux facteurs (2FA) est requise pour votre connexion Xero et ne peut pas être désactivée.', replaceDevice: 'Remplacer l’appareil', @@ -2572,6 +2572,7 @@ const translations: TranslationDeepObject = { verifyNewDeviceDescription: 'Scannez le code QR avec votre nouvel appareil, puis saisissez le code pour terminer la configuration.', downloadCodes: 'Télécharger les codes', copyCodes: 'Copier les codes', + enable2FA: 'Activer', }, recoveryCodeForm: { error: { @@ -11128,6 +11129,8 @@ Ajoutez davantage de règles de dépenses pour protéger la trésorerie de l’e `Êtes-vous sûr de vouloir supprimer votre accès copilote au compte Expensify de ${delegatorName} ? Cette action est irréversible.`, removeCopilotAccessConfirm: "Supprimer l'accès", copilotAccess: 'Accès Copilot', + leaveAccount: 'Quitter le compte', + leaveAccountConfirmationText: 'Vous reviendrez à votre propre compte. Vous ne serez pas complètement déconnecté.', }, debug: { debug: 'Déboguer', diff --git a/src/languages/it.ts b/src/languages/it.ts index 24fbf6be7e49..0034cc8c7eac 100644 --- a/src/languages/it.ts +++ b/src/languages/it.ts @@ -2545,7 +2545,7 @@ const translations: TranslationDeepObject = { twoFactorAuthIsRequiredForAdminsHeader: 'Autenticazione a due fattori richiesta', twoFactorAuthIsRequiredForAdminsTitle: 'Abilita l’autenticazione a due fattori', twoFactorAuthIsRequiredXero: 'La tua connessione contabile Xero richiede l’autenticazione a due fattori.', - twoFactorAuthIsRequiredCompany: 'La tua azienda richiede l’autenticazione a due fattori.', + twoFactorAuthIsRequiredCompany: 'La tua azienda richiede l’autenticazione a due fattori (2FA).', twoFactorAuthCannotDisable: "Impossibile disabilitare l'autenticazione a due fattori", twoFactorAuthRequired: 'Per la connessione a Xero è richiesta l’autenticazione a due fattori (2FA) e non può essere disattivata.', replaceDevice: 'Sostituisci dispositivo', @@ -2557,6 +2557,7 @@ const translations: TranslationDeepObject = { verifyNewDeviceDescription: 'Scansiona il codice QR con il tuo nuovo dispositivo, poi inserisci il codice per completare la configurazione.', downloadCodes: 'Scarica codici', copyCodes: 'Copia codici', + enable2FA: 'Abilita', }, recoveryCodeForm: { error: { @@ -11055,6 +11056,8 @@ Aggiungi altre regole di spesa per proteggere il flusso di cassa aziendale.`, `Sei sicuro di voler rimuovere il tuo accesso copilota all'account Expensify di ${delegatorName}? Questa azione non può essere annullata.`, removeCopilotAccessConfirm: 'Rimuovi accesso', copilotAccess: 'Accesso a Copilot', + leaveAccount: 'Abbandona account', + leaveAccountConfirmationText: 'Verrai reindirizzato al tuo account. Non verrai disconnesso completamente.', }, debug: { debug: 'Debug', diff --git a/src/languages/ja.ts b/src/languages/ja.ts index b40e4e0fcfab..b93e2c36e82e 100644 --- a/src/languages/ja.ts +++ b/src/languages/ja.ts @@ -2527,7 +2527,7 @@ const translations: TranslationDeepObject = { twoFactorAuthIsRequiredForAdminsHeader: '2要素認証が必要です', twoFactorAuthIsRequiredForAdminsTitle: '2要素認証を有効にしてください', twoFactorAuthIsRequiredXero: 'Xero 会計連携には二要素認証が必要です。', - twoFactorAuthIsRequiredCompany: 'あなたの会社では、2 要素認証が必須です。', + twoFactorAuthIsRequiredCompany: 'お客様の会社では、2 要素認証(2FA)が必須です。', twoFactorAuthCannotDisable: '2要素認証を無効にできません', twoFactorAuthRequired: 'Xero 連携には二要素認証(2FA)が必須で、無効にすることはできません。', replaceDevice: 'デバイスを交換', @@ -2539,6 +2539,7 @@ const translations: TranslationDeepObject = { verifyNewDeviceDescription: '新しいデバイスでQRコードをスキャンし、表示されたコードを入力して設定を完了してください。', downloadCodes: 'コードをダウンロード', copyCodes: 'コードをコピー', + enable2FA: '有効にする', }, recoveryCodeForm: { error: { @@ -10892,6 +10893,8 @@ ${reportName}`, removeCopilotAccessConfirmation: (delegatorName: string) => `${delegatorName}のExpensifyアカウントへのコパイロットアクセスを削除してもよろしいですか?この操作は元に戻せません。`, removeCopilotAccessConfirm: 'アクセスを削除', copilotAccess: 'Copilot へのアクセス', + leaveAccount: 'アカウントを退出', + leaveAccountConfirmationText: 'ご自身のアカウントに戻りますが、完全にはサインアウトされません。', }, debug: { debug: 'デバッグ', diff --git a/src/languages/nl.ts b/src/languages/nl.ts index 9e8906537865..634ce8c3a6a3 100644 --- a/src/languages/nl.ts +++ b/src/languages/nl.ts @@ -2546,7 +2546,7 @@ const translations: TranslationDeepObject = { twoFactorAuthIsRequiredForAdminsHeader: 'Tweefactorauthenticatie vereist', twoFactorAuthIsRequiredForAdminsTitle: 'Schakel tweestapsverificatie in', twoFactorAuthIsRequiredXero: 'Je Xero-boekhoudkoppeling vereist tweefactorauthenticatie.', - twoFactorAuthIsRequiredCompany: 'Je bedrijf vereist tweefactorauthenticatie.', + twoFactorAuthIsRequiredCompany: 'Je bedrijf vereist tweefactorauthenticatie (2FA).', twoFactorAuthCannotDisable: 'Kan 2FA niet uitschakelen', twoFactorAuthRequired: 'Tweestapsverificatie (2FA) is vereist voor je Xero-verbinding en kan niet worden uitgeschakeld.', replaceDevice: 'Apparaat vervangen', @@ -2558,6 +2558,7 @@ const translations: TranslationDeepObject = { verifyNewDeviceDescription: 'Scan de QR-code met je nieuwe apparaat en voer daarna de code in om de installatie te voltooien.', downloadCodes: 'Codes downloaden', copyCodes: 'Codes kopiëren', + enable2FA: 'Inschakelen', }, recoveryCodeForm: { error: { @@ -11020,6 +11021,8 @@ er bestedingsregels toe om de kasstroom van het bedrijf te beschermen.`, `Weet je zeker dat je je copilot-toegang tot het Expensify-account van ${delegatorName} wilt verwijderen? Deze actie kan niet ongedaan worden gemaakt.`, removeCopilotAccessConfirm: 'Toegang verwijderen', copilotAccess: 'Copilot-toegang', + leaveAccount: 'Account verlaten', + leaveAccountConfirmationText: 'Je gaat terug naar je eigen account. Je wordt niet volledig uitgelogd.', }, debug: { debug: 'Debug', diff --git a/src/languages/pl.ts b/src/languages/pl.ts index ddb65185b174..783f84156342 100644 --- a/src/languages/pl.ts +++ b/src/languages/pl.ts @@ -2585,7 +2585,7 @@ const translations: TranslationDeepObject = { twoFactorAuthIsRequiredForAdminsHeader: 'Wymagane uwierzytelnianie dwuskładnikowe', twoFactorAuthIsRequiredForAdminsTitle: 'Włącz uwierzytelnianie dwuskładnikowe', twoFactorAuthIsRequiredXero: 'Twoje połączenie księgowe z Xero wymaga uwierzytelniania dwuskładnikowego.', - twoFactorAuthIsRequiredCompany: 'Twoetapowe uwierzytelnianie jest wymagane przez Twoją firmę.', + twoFactorAuthIsRequiredCompany: 'Twoja firma wymaga uwierzytelniania dwuskładnikowego (2FA).', twoFactorAuthCannotDisable: 'Nie można wyłączyć 2FA', twoFactorAuthRequired: 'Dla połączenia z Xero wymagana jest weryfikacja dwuetapowa (2FA) i nie można jej wyłączyć.', replaceDevice: 'Zastąp urządzenie', @@ -2597,6 +2597,7 @@ const translations: TranslationDeepObject = { verifyNewDeviceDescription: 'Zeskanuj kod QR nowym urządzeniem, a następnie wpisz ten kod, aby zakończyć konfigurację.', downloadCodes: 'Pobierz kody', copyCodes: 'Skopiuj kody', + enable2FA: 'Włącz', }, recoveryCodeForm: { error: { @@ -11039,6 +11040,8 @@ Dodaj więcej zasad wydatków, żeby chronić płynność finansową firmy.`, `Czy na pewno chcesz usunąć swój dostęp kopilota do konta Expensify użytkownika ${delegatorName}? Tej czynności nie można cofnąć.`, removeCopilotAccessConfirm: 'Usuń dostęp', copilotAccess: 'Dostęp do Copilota', + leaveAccount: 'Opuść konto', + leaveAccountConfirmationText: 'Wrócisz do swojego konta. Nie zostaniesz całkowicie wylogowany.', }, debug: { debug: 'Debug', diff --git a/src/languages/pt-BR.ts b/src/languages/pt-BR.ts index 879520917003..a26742157367 100644 --- a/src/languages/pt-BR.ts +++ b/src/languages/pt-BR.ts @@ -2539,7 +2539,7 @@ const translations: TranslationDeepObject = { twoFactorAuthIsRequiredForAdminsHeader: 'Autenticação em duas etapas obrigatória', twoFactorAuthIsRequiredForAdminsTitle: 'Ative a autenticação em duas etapas', twoFactorAuthIsRequiredXero: 'Sua conexão contábil com o Xero exige autenticação em duas etapas.', - twoFactorAuthIsRequiredCompany: 'Sua empresa exige autenticação em duas etapas.', + twoFactorAuthIsRequiredCompany: 'Sua empresa exige autenticação de dois fatores (2FA).', twoFactorAuthCannotDisable: 'Não é possível desativar a 2FA', twoFactorAuthRequired: 'A autenticação em duas etapas (2FA) é obrigatória para sua conexão com o Xero e não pode ser desativada.', replaceDevice: 'Substituir dispositivo', @@ -2551,6 +2551,7 @@ const translations: TranslationDeepObject = { verifyNewDeviceDescription: 'Escaneie o código QR com seu novo dispositivo e depois insira o código para concluir a configuração.', downloadCodes: 'Baixar códigos', copyCodes: 'Copiar códigos', + enable2FA: 'Ativar', }, recoveryCodeForm: { error: { @@ -11013,6 +11014,8 @@ Adicione mais regras de gasto para proteger o fluxo de caixa da empresa.`, `Tem certeza de que deseja remover seu acesso de copiloto à conta Expensify de ${delegatorName}? Esta ação não pode ser desfeita.`, removeCopilotAccessConfirm: 'Remover acesso', copilotAccess: 'Acesso ao Copilot', + leaveAccount: 'Sair da conta', + leaveAccountConfirmationText: 'Você voltará para a sua própria conta. Você não será totalmente desconectado.', }, debug: { debug: 'Depurar', diff --git a/src/languages/zh-hans.ts b/src/languages/zh-hans.ts index 01c55acafcdc..a7689b55e94f 100644 --- a/src/languages/zh-hans.ts +++ b/src/languages/zh-hans.ts @@ -2462,7 +2462,7 @@ const translations: TranslationDeepObject = { twoFactorAuthIsRequiredForAdminsHeader: '需要启用双重身份验证', twoFactorAuthIsRequiredForAdminsTitle: '请启用双重身份验证', twoFactorAuthIsRequiredXero: '您的 Xero 会计连接需要启用双重身份验证。', - twoFactorAuthIsRequiredCompany: '您的公司要求使用双重身份验证。', + twoFactorAuthIsRequiredCompany: '您的公司要求使用双重身份验证(2FA)。', twoFactorAuthCannotDisable: '无法禁用双重验证', twoFactorAuthRequired: '您的 Xero 连接需要启用双重身份验证(2FA),且无法将其禁用。', replaceDevice: '更换设备', @@ -2474,6 +2474,7 @@ const translations: TranslationDeepObject = { verifyNewDeviceDescription: '使用新设备扫描二维码,然后输入代码完成设置。', downloadCodes: '下载代码', copyCodes: '复制代码', + enable2FA: '启用', }, recoveryCodeForm: { error: { @@ -10609,6 +10610,8 @@ ${reportName}`, removeCopilotAccessConfirmation: (delegatorName: string) => `您确定要移除对${delegatorName}的 Expensify 账户的副驾驶访问权限吗?此操作无法撤销。`, removeCopilotAccessConfirm: '移除访问权限', copilotAccess: 'Copilot 访问', + leaveAccount: '退出账户', + leaveAccountConfirmationText: '您将返回到您自己的账户。您不会完全登出。', }, debug: { debug: '调试', diff --git a/src/libs/migrations/ReplaceShouldUseStagingServerWithActiveServer.ts b/src/libs/migrations/ReplaceShouldUseStagingServerWithActiveServer.ts index 6b1f04eafa74..91e7cdbb57b4 100644 --- a/src/libs/migrations/ReplaceShouldUseStagingServerWithActiveServer.ts +++ b/src/libs/migrations/ReplaceShouldUseStagingServerWithActiveServer.ts @@ -1,38 +1,26 @@ /* eslint-disable @typescript-eslint/no-deprecated -- draining SHOULD_USE_STAGING_SERVER is this file's entire purpose */ import Log from '@libs/Log'; +import readOnceOnyxValue from '@libs/readOnceOnyxValue'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; -import type {OnyxKey, OnyxMultiSetInput, OnyxValue} from 'react-native-onyx'; +import type {OnyxMultiSetInput} from 'react-native-onyx'; import Onyx from 'react-native-onyx'; -/** Onyx has no promise-based read. */ -function readOnce(key: TKey): Promise> { - return new Promise((resolve) => { - const connection = Onyx.connectWithoutView({ - key, - callback: (value) => { - Onyx.disconnect(connection); - resolve(value); - }, - }); - }); -} - /** * A missing legacy key must write NOTHING: `resolveActiveServer` derives the environment default from * `value === undefined`, so seeding 'production' would pin every staging and adhoc build to production. */ export default async function ReplaceShouldUseStagingServerWithActiveServer(): Promise { - const shouldUseStagingServer = await readOnce(ONYXKEYS.SHOULD_USE_STAGING_SERVER); + const shouldUseStagingServer = await readOnceOnyxValue(ONYXKEYS.SHOULD_USE_STAGING_SERVER); if (shouldUseStagingServer === undefined) { return; } const updates: OnyxMultiSetInput = {[ONYXKEYS.SHOULD_USE_STAGING_SERVER]: null}; - if ((await readOnce(ONYXKEYS.ACTIVE_SERVER)) === undefined) { + if ((await readOnceOnyxValue(ONYXKEYS.ACTIVE_SERVER)) === undefined) { updates[ONYXKEYS.ACTIVE_SERVER] = shouldUseStagingServer ? CONST.SERVER.STAGING : CONST.SERVER.PRODUCTION; } diff --git a/src/libs/readOnceOnyxValue.ts b/src/libs/readOnceOnyxValue.ts new file mode 100644 index 000000000000..794048e6d59f --- /dev/null +++ b/src/libs/readOnceOnyxValue.ts @@ -0,0 +1,18 @@ +import type {OnyxKey, OnyxValue} from 'react-native-onyx'; + +import Onyx from 'react-native-onyx'; + +/** Onyx has no promise-based read. */ +function readOnceOnyxValue(key: TKey): Promise> { + return new Promise((resolve) => { + const connection = Onyx.connectWithoutView({ + key, + callback: (value) => { + Onyx.disconnect(connection); + resolve(value); + }, + }); + }); +} + +export default readOnceOnyxValue; diff --git a/src/pages/RequireTwoFactorAuthenticationOverlay.tsx b/src/pages/RequireTwoFactorAuthenticationOverlay.tsx index 60015feb132d..2b7f7061b380 100644 --- a/src/pages/RequireTwoFactorAuthenticationOverlay.tsx +++ b/src/pages/RequireTwoFactorAuthenticationOverlay.tsx @@ -1,5 +1,6 @@ import Button from '@components/Button'; import FocusTrapForModal from '@components/FocusTrap/FocusTrapForModal'; +import GpsDraftDetailsRefSync from '@components/GpsDraftDetailsRefSync'; import Icon from '@components/Icon'; import Text from '@components/Text'; @@ -8,6 +9,7 @@ import useLocalize from '@hooks/useLocalize'; import useOnyx from '@hooks/useOnyx'; import useRootNavigationState from '@hooks/useRootNavigationState'; import useShouldShowRequire2FAPage from '@hooks/useShouldShowRequire2FAPage'; +import useSignOut from '@hooks/useSignOut'; import useThemeStyles from '@hooks/useThemeStyles'; import useTwoFactorAuthRoute from '@hooks/useTwoFactorAuthRoute'; @@ -23,11 +25,12 @@ import ONYXKEYS from '@src/ONYXKEYS'; import ROUTES from '@src/ROUTES'; import {emailSelector} from '@src/selectors/Session'; import type {Policy} from '@src/types/onyx'; +import type GpsDraftDetails from '@src/types/onyx/GpsDraftDetails'; import type {OnyxCollection} from 'react-native-onyx'; import {useNavigation} from '@react-navigation/core'; -import React, {useCallback, useEffect} from 'react'; +import React, {useCallback, useEffect, useRef, useState} from 'react'; import {StyleSheet, View} from 'react-native'; /** @@ -58,6 +61,9 @@ function RequireTwoFactorAuthenticationOverlay() { const styles = useThemeStyles(); const {translate} = useLocalize(); const {getTwoFactorAuthRoute} = useTwoFactorAuthRoute(); + const {signOut, leaveDelegateAccount, isActingAsDelegate, isTrackingGPS} = useSignOut(); + const gpsDraftDetailsRef = useRef(undefined); + const [isEscapeInFlight, setIsEscapeInFlight] = useState(false); const [onboardingInitialPath] = useOnyx(ONYXKEYS.ONBOARDING_LAST_VISITED_PATH); const [account] = useOnyx(ONYXKEYS.ACCOUNT); const [onboardingValues] = useOnyx(ONYXKEYS.NVP_ONBOARDING); @@ -90,7 +96,18 @@ function RequireTwoFactorAuthenticationOverlay() { snapshotOnboardingResumePathIfNeeded(); }, [shouldShowRequire2FAPage, isIn2FASetupFlow, snapshotOnboardingResumePathIfNeeded]); - const handleOnPress = () => { + const onEscapePress = () => { + if (isEscapeInFlight) { + return; + } + setIsEscapeInFlight(true); + const escapeAction = isActingAsDelegate ? leaveDelegateAccount({gpsDraftDetailsRef}) : signOut(); + escapeAction.finally(() => { + setIsEscapeInFlight(false); + }); + }; + + const enableTwoFactorAuth = () => { snapshotOnboardingResumePathIfNeeded(); Navigation.navigate(getTwoFactorAuthRoute(ROUTES.SETTINGS_SECURITY, {forceSetup: true})); }; @@ -100,40 +117,52 @@ function RequireTwoFactorAuthenticationOverlay() { } return ( - - - - - - - - - - {translate('twoFactorAuth.twoFactorAuthIsRequiredForAdminsHeader')} - - {translate(is2FARequiredBecauseOfXero ? 'twoFactorAuth.twoFactorAuthIsRequiredXero' : 'twoFactorAuth.twoFactorAuthIsRequiredCompany')} - + <> + {isActingAsDelegate && isTrackingGPS && } + + + + + + + + + + {translate('twoFactorAuth.twoFactorAuthIsRequiredForAdminsHeader')} + + {translate(is2FARequiredBecauseOfXero ? 'twoFactorAuth.twoFactorAuthIsRequiredXero' : 'twoFactorAuth.twoFactorAuthIsRequiredCompany')} + + + + + + - - - + + ); } diff --git a/src/pages/settings/useInitialSettingsPageMenuData.ts b/src/pages/settings/useInitialSettingsPageMenuData.ts index 29db52e6d7f2..920b39b5b7f5 100644 --- a/src/pages/settings/useInitialSettingsPageMenuData.ts +++ b/src/pages/settings/useInitialSettingsPageMenuData.ts @@ -1,38 +1,30 @@ /** * Builds the Account and General menu section data shown on the Initial Settings page. */ -import {ModalActions} from '@components/Modal/Global/ModalContext'; - import useCardFeedErrors from '@hooks/useCardFeedErrors'; -import useConfirmModal from '@hooks/useConfirmModal'; import {useCurrencyListActions} from '@hooks/useCurrencyList'; import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset'; import useLocalize from '@hooks/useLocalize'; -import useNetwork from '@hooks/useNetwork'; import useNonPersonalCardList from '@hooks/useNonPersonalCardList'; import useOnyx from '@hooks/useOnyx'; import usePrivateSubscription from '@hooks/usePrivateSubscription'; +import useSignOut from '@hooks/useSignOut'; import {resetExitSurveyForm} from '@libs/actions/ExitSurvey'; import {closeReactNativeApp} from '@libs/actions/HybridApp'; import {hasPartiallySetupBankAccount, hasPersonalBankAccountMissingInfo} from '@libs/BankAccountUtils'; import {hasCardPendingDigitalWalletApproval, hasPendingExpensifyCardAction, hasVirtualExpensifyCardMissingPersonalDetails} from '@libs/CardUtils'; -import {showPermissionErrorAlert} from '@libs/fileDownload/FileUtils'; -import Log from '@libs/Log'; import createDynamicRoute from '@libs/Navigation/helpers/dynamicRoutesUtils/createDynamicRoute'; import Navigation from '@libs/Navigation/Navigation'; -import {getSaveablePendingReceiptRequests, saveReceiptsToGallery} from '@libs/savePendingReceiptsToGallery'; import {getFreeTrialText, hasSubscriptionRedDotError, shouldShowSubscriptionExpiringSoonUI} from '@libs/SubscriptionUtils'; import {shouldHideOldAppRedirect} from '@libs/TryNewDotUtils'; import {expensifyLoginsSelector, getProfilePageBrickRoadIndicator, hasDeviceManagementError} from '@libs/UserUtils'; import useTimeSensitiveHomeAddress from '@pages/home/TimeSensitiveSection/hooks/useTimeSensitiveHomeAddress'; -import {BACKGROUND_LOCATION_TRACKING_TASK_NAME} from '@pages/iou/request/step/IOURequestStepDistanceGPS/const'; -import {stopGpsTripNotification} from '@pages/iou/request/step/IOURequestStepDistanceGPS/GPSNotifications'; import {openExternalLink, openOldDotLink} from '@userActions/Link'; import {hasPaymentMethodError} from '@userActions/PaymentMethods'; -import {hasStashedSession, isSupportAuthToken, signOutAndRedirectToSignIn} from '@userActions/Session'; +import {hasStashedSession, isSupportAuthToken} from '@userActions/Session'; import CONFIG from '@src/CONFIG'; import CONST from '@src/CONST'; @@ -48,7 +40,6 @@ import isLoadingOnyxValue from '@src/types/utils/isLoadingOnyxValue'; import type {ValueOf} from 'type-fest'; import {differenceInDays} from 'date-fns'; -import {stopLocationUpdatesAsync} from 'expo-location'; import type {MenuData, MenuSection} from './useSettingsNavigationMenuData'; @@ -82,8 +73,8 @@ function useInitialSettingsPageMenuData(currentUserPersonalDetails: CurrentUserP const [amountOwed = 0] = useOnyx(ONYXKEYS.NVP_PRIVATE_AMOUNT_OWED); const [ownerBillingGracePeriodEnd] = useOnyx(ONYXKEYS.NVP_PRIVATE_OWNER_BILLING_GRACE_PERIOD_END); const [ownerTravelBillingGracePeriodEnd] = useOnyx(ONYXKEYS.NVP_PRIVATE_OWNER_TRAVEL_BILLING_GRACE_PERIOD_END); - const network = useNetwork(); const {translate} = useLocalize(); + const {signOut: signOutInteractively, signOutImmediately} = useSignOut(); const hasActivatedWallet = ([CONST.WALLET.TIER_NAME.GOLD, CONST.WALLET.TIER_NAME.PLATINUM] as string[]).includes(userWallet?.tierName ?? ''); const hasLockedBankAccount = bankAccountList ? Object.values(bankAccountList).some((bankAccount) => bankAccount.accountData?.state === CONST.BANK_ACCOUNT.STATE.LOCKED) : false; const {shouldShowAddHomeAddress} = useTimeSensitiveHomeAddress(); @@ -132,106 +123,12 @@ function useInitialSettingsPageMenuData(currentUserPersonalDetails: CurrentUserP walletBrickRoadIndicator = CONST.BRICK_ROAD_INDICATOR_STATUS.INFO; } - const {showConfirmModal} = useConfirmModal(); - const confirmModalTitle = isTrackingGPS ? translate('gps.signOutWarningTripInProgress.title') : translate('common.areYouSure'); - const confirmModalPrompt = isTrackingGPS ? translate('gps.signOutWarningTripInProgress.prompt') : translate('initialSettingsPage.signOutConfirmationText'); - const confirmModalConfirmText = isTrackingGPS ? translate('gps.signOutWarningTripInProgress.confirm') : translate('initialSettingsPage.signOut'); - - const showSignOutModal = () => { - return showConfirmModal({ - title: confirmModalTitle, - prompt: confirmModalPrompt, - confirmText: confirmModalConfirmText, - cancelText: translate('common.cancel'), - shouldShowCancelButton: true, - buttonVariant: CONST.BUTTON_VARIANT.DANGER, - }); - }; - - const showSaveReceiptsModal = (pendingReceiptCount: number) => { - return showConfirmModal({ - title: translate('initialSettingsPage.saveReceiptsConfirmation.title'), - prompt: translate('initialSettingsPage.saveReceiptsConfirmation.prompt', { - count: pendingReceiptCount, - }), - confirmText: translate('initialSettingsPage.saveReceiptsConfirmation.confirm'), - cancelText: translate('common.cancel'), - shouldShowCancelButton: true, - }); - }; - - // Combined modal for the offline case: warns about losing offline changes and offers to save the pending receipts, so the user is not shown two back-to-back prompts. - const showSaveReceiptsAndSignOutModal = (pendingReceiptCount: number) => { - return showConfirmModal({ - title: translate('initialSettingsPage.saveReceiptsAndSignOutConfirmation.title'), - prompt: translate('initialSettingsPage.saveReceiptsAndSignOutConfirmation.prompt', { - count: pendingReceiptCount, - }), - confirmText: translate('initialSettingsPage.saveReceiptsAndSignOutConfirmation.confirm'), - cancelText: translate('common.cancel'), - shouldShowCancelButton: true, - buttonVariant: CONST.BUTTON_VARIANT.DANGER, - }); - }; - - // Save must complete before the forced-signout branch dispatches `Onyx.clear`, which wipes the persisted queue that holds these local file paths. - const saveReceipts = async (saveableReceipts: ReturnType) => { - try { - const {savedCount, failedCount, permissionDenied} = await saveReceiptsToGallery(saveableReceipts); - Log.info('[Receipt] Saved pending receipts to gallery before sign-out', false, {savedCount, failedCount, permissionDenied}); - // When the OS denied gallery access the receipts could not be saved. Point the user to Settings with the same alert the manual download flow uses, then let sign-out proceed. - if (permissionDenied) { - showPermissionErrorAlert(translate); - } - } catch (error) { - Log.alert('[Receipt] Unexpected rejection from saveReceiptsToGallery; sign-out continued', {error}); - } - }; - const signOut = async (shouldForceSignout = false) => { - // Forced sign-out (expired session, SAML re-auth) must be non-interactive: it must not touch the gallery flow, which can trigger OS permission prompts and delay the redirect. if (shouldForceSignout) { - return signOutAndRedirectToSignIn(); - } - - // `getSaveablePendingReceiptRequests` is platform-split (web returns `[]`) and image-filtered so we do not promise a save the native gallery API can not deliver. - const saveableReceipts = getSaveablePendingReceiptRequests(); - const shouldWarnBeforeSignOut = network.isOffline || isTrackingGPS; - // Offline + receipts is the common case; merge the offline warning and the save-receipts prompt into a single modal. GPS keeps its own warning, so it falls through to the two-step path below. - const isOfflineReceiptsCase = network.isOffline && !isTrackingGPS && saveableReceipts.length > 0; - - if (!shouldWarnBeforeSignOut && saveableReceipts.length === 0) { - return signOutAndRedirectToSignIn(); + return signOutImmediately(); } - if (isOfflineReceiptsCase) { - const result = await showSaveReceiptsAndSignOutModal(saveableReceipts.length); - if (result.action !== ModalActions.CONFIRM) { - return; - } - await saveReceipts(saveableReceipts); - } else { - if (shouldWarnBeforeSignOut) { - const result = await showSignOutModal(); - if (result.action !== ModalActions.CONFIRM) { - return; - } - } - - if (saveableReceipts.length > 0) { - const result = await showSaveReceiptsModal(saveableReceipts.length); - if (result.action !== ModalActions.CONFIRM) { - return; - } - await saveReceipts(saveableReceipts); - } - } - - if (isTrackingGPS) { - stopGpsTripNotification(); - stopLocationUpdatesAsync(BACKGROUND_LOCATION_TRACKING_TASK_NAME).catch((error) => console.error('[GPS distance request] Failed to stop location tracking', error)); - } - signOut(true); + return signOutInteractively(); }; const surveyThresholdInDays = 30; diff --git a/tests/unit/hooks/useSignOutTest.ts b/tests/unit/hooks/useSignOutTest.ts new file mode 100644 index 000000000000..7584e40ac539 --- /dev/null +++ b/tests/unit/hooks/useSignOutTest.ts @@ -0,0 +1,352 @@ +import {act, renderHook} from '@testing-library/react-native'; + +import {ModalActions} from '@components/Modal/Global/ModalContext'; + +import useOnyx from '@hooks/useOnyx'; +import useSignOut from '@hooks/useSignOut'; + +import {disconnect} from '@libs/actions/Delegate'; +import {getGpsPoints, stopGpsTrip} from '@libs/GPSDraftDetailsUtils'; +import {getSaveablePendingReceiptRequests, saveReceiptsToGallery} from '@libs/savePendingReceiptsToGallery'; + +import {signOutAndRedirectToSignIn} from '@userActions/Session'; + +import ONYXKEYS from '@src/ONYXKEYS'; +import {isActingAsDelegateSelector} from '@src/selectors/Account'; +import {isTrackingSelector} from '@src/selectors/GPSDraftDetails'; +import type GpsDraftDetails from '@src/types/onyx/GpsDraftDetails'; + +const mockShowConfirmModal = jest.fn(); +const mockTranslate = jest.fn((key: string) => key); + +let mockIsOffline = false; + +jest.mock('@hooks/useLocalize', () => ({ + __esModule: true, + default: () => ({translate: mockTranslate}), +})); + +jest.mock('@hooks/useNetwork', () => ({ + __esModule: true, + default: () => ({isOffline: mockIsOffline}), +})); + +jest.mock('@hooks/useConfirmModal', () => ({ + __esModule: true, + default: () => ({showConfirmModal: mockShowConfirmModal}), +})); + +jest.mock('@hooks/useOnyx', () => ({ + __esModule: true, + default: jest.fn(), +})); + +jest.mock('@userActions/Session', () => ({ + signOutAndRedirectToSignIn: jest.fn(), +})); + +jest.mock('@libs/actions/Delegate', () => ({ + disconnect: jest.fn(), +})); + +jest.mock('@libs/savePendingReceiptsToGallery', () => ({ + getSaveablePendingReceiptRequests: jest.fn(() => []), + saveReceiptsToGallery: jest.fn(() => Promise.resolve({savedCount: 0, failedCount: 0, permissionDenied: false})), +})); + +jest.mock('@libs/GPSDraftDetailsUtils', () => ({ + getGpsPoints: jest.fn(() => []), + stopGpsTrip: jest.fn(() => Promise.resolve()), +})); + +jest.mock('@pages/iou/request/step/IOURequestStepDistanceGPS/GPSNotifications', () => ({ + stopGpsTripNotification: jest.fn(), +})); + +jest.mock('expo-location', () => ({ + Accuracy: {Highest: 6}, + stopLocationUpdatesAsync: jest.fn(() => Promise.resolve()), +})); + +jest.mock('@pages/iou/request/step/IOURequestStepDistanceGPS/const', () => ({ + BACKGROUND_LOCATION_TRACKING_TASK_NAME: 'background-location-tracking', +})); + +const mockUseOnyx = jest.mocked(useOnyx); +const mockSignOutAndRedirectToSignIn = jest.mocked(signOutAndRedirectToSignIn); +const mockDelegateDisconnect = jest.mocked(disconnect); +const mockGetSaveablePendingReceiptRequests = jest.mocked(getSaveablePendingReceiptRequests); +const mockSaveReceiptsToGallery = jest.mocked(saveReceiptsToGallery); +const mockStopGpsTrip = jest.mocked(stopGpsTrip); +const mockGetGpsPoints = jest.mocked(getGpsPoints); + +type MockOnyxState = { + isTrackingGPS?: boolean; + isActingAsDelegate?: boolean; + stashedCredentials?: Record; + stashedSession?: {email?: string}; +}; + +const loadedOnyxMetadata = {status: 'loaded'} as const; + +const mockGpsDraftDetails: GpsDraftDetails = { + gpsPoints: [[{lat: 1, long: 2}]], + distanceInMeters: 0, + isTracking: true, + reportID: '1', + unit: 'mi', +}; + +function mockOnyxState({isTrackingGPS = false, isActingAsDelegate = false, stashedCredentials = {}, stashedSession = {email: 'copilot@expensify.com'}}: MockOnyxState = {}) { + mockUseOnyx.mockImplementation((key, options) => { + if (key === ONYXKEYS.GPS_DRAFT_DETAILS) { + if (options?.selector === isTrackingSelector) { + return [isTrackingGPS, loadedOnyxMetadata]; + } + return [undefined, loadedOnyxMetadata]; + } + if (key === ONYXKEYS.ACCOUNT) { + const account = isActingAsDelegate ? {delegatedAccess: {delegate: 'delegate@expensify.com'}} : {}; + if (options?.selector === isActingAsDelegateSelector) { + return [isActingAsDelegateSelector(account), loadedOnyxMetadata]; + } + return [account, loadedOnyxMetadata]; + } + if (key === ONYXKEYS.STASHED_CREDENTIALS) { + return [stashedCredentials, loadedOnyxMetadata]; + } + if (key === ONYXKEYS.STASHED_SESSION) { + return [stashedSession, loadedOnyxMetadata]; + } + return [undefined, loadedOnyxMetadata]; + }); +} + +describe('useSignOut', () => { + beforeEach(() => { + jest.clearAllMocks(); + mockIsOffline = false; + mockOnyxState(); + mockShowConfirmModal.mockResolvedValue({action: ModalActions.CONFIRM}); + }); + + it('should sign out immediately when online with no GPS tracking or pending receipts', async () => { + // Given the user is online with no active GPS trip and no pending receipts + const {result} = renderHook(() => useSignOut()); + + // When they sign out from settings + await act(async () => { + await result.current.signOut(); + }); + + // Then sign-out proceeds without an extra confirm modal + expect(mockSignOutAndRedirectToSignIn).toHaveBeenCalledTimes(1); + expect(mockShowConfirmModal).not.toHaveBeenCalled(); + }); + + it('should show generic confirm when shouldAlwaysConfirm is true before signing out', async () => { + // Given the require-2FA overlay asks the hook to always confirm sign-out + const {result} = renderHook(() => useSignOut()); + + // When signOut is called with shouldAlwaysConfirm + await act(async () => { + await result.current.signOut({shouldAlwaysConfirm: true}); + }); + + // Then the generic sign-out confirm appears before redirecting + expect(mockShowConfirmModal).toHaveBeenCalledWith( + expect.objectContaining({ + prompt: 'initialSettingsPage.signOutConfirmationText', + confirmText: 'initialSettingsPage.signOut', + }), + ); + expect(mockSignOutAndRedirectToSignIn).toHaveBeenCalledTimes(1); + }); + + it('should stay in flight until sign-out finishes and ignore a second press', async () => { + // Given sign-out has started but the redirect has not finished + let resolveSignOut: () => void = () => {}; + mockSignOutAndRedirectToSignIn.mockImplementationOnce( + () => + new Promise((resolve) => { + resolveSignOut = () => { + resolve(undefined); + }; + }), + ); + const {result} = renderHook(() => useSignOut()); + + let firstSignOut: Promise | undefined; + act(() => { + firstSignOut = result.current.signOut(); + }); + + // When they press Sign out again before the first one finishes + await act(async () => { + await result.current.signOut(); + }); + + // Then the second press is ignored and the first call is still waiting + expect(mockSignOutAndRedirectToSignIn).toHaveBeenCalledTimes(1); + expect(mockShowConfirmModal).not.toHaveBeenCalled(); + + let didSettle = false; + const trackedSignOut = firstSignOut?.finally(() => { + didSettle = true; + }); + await act(async () => { + await Promise.resolve(); + }); + expect(didSettle).toBe(false); + + await act(async () => { + resolveSignOut(); + await trackedSignOut; + }); + expect(didSettle).toBe(true); + }); + + it('should ignore a second sign-out while the first confirm is still open', async () => { + // Given the first sign-out confirm is still waiting for the user + let resolveModal: (value: {action: string}) => void = () => {}; + mockShowConfirmModal.mockImplementation( + () => + new Promise((resolve) => { + resolveModal = resolve; + }), + ); + const {result} = renderHook(() => useSignOut()); + + let firstSignOut: Promise | undefined; + act(() => { + firstSignOut = result.current.signOut({shouldAlwaysConfirm: true}); + }); + + // When they press Sign out again before the first modal closes + await act(async () => { + await result.current.signOut({shouldAlwaysConfirm: true}); + }); + + // Then only one confirm modal is opened + expect(mockShowConfirmModal).toHaveBeenCalledTimes(1); + + await act(async () => { + resolveModal({action: ModalActions.CLOSE}); + await firstSignOut; + }); + }); + + it('should show merged save-and-sign-out confirm when offline with pending receipts', async () => { + // Given the user is offline and has pending receipts to save + mockIsOffline = true; + mockGetSaveablePendingReceiptRequests.mockReturnValue([{localPath: 'file:///receipt.jpg', filename: 'receipt.jpg', type: 'image/jpeg'}]); + + const {result} = renderHook(() => useSignOut()); + + // When they attempt to sign out + await act(async () => { + await result.current.signOut(); + }); + + // Then the merged save-and-sign-out modal runs before redirecting + expect(mockShowConfirmModal).toHaveBeenCalledWith( + expect.objectContaining({ + title: 'initialSettingsPage.saveReceiptsAndSignOutConfirmation.title', + }), + ); + expect(mockSaveReceiptsToGallery).toHaveBeenCalledTimes(1); + expect(mockSignOutAndRedirectToSignIn).toHaveBeenCalledTimes(1); + }); + + it('should call signOutImmediately without showing confirm modals', () => { + // Given the settings page uses the immediate sign-out escape hatch + const {result} = renderHook(() => useSignOut()); + + // When signOutImmediately is invoked + act(() => { + result.current.signOutImmediately(); + }); + + // Then redirect happens with no confirm modals + expect(mockSignOutAndRedirectToSignIn).toHaveBeenCalledTimes(1); + expect(mockShowConfirmModal).not.toHaveBeenCalled(); + }); + + it('should disconnect instead of signing out when leaving a delegated account', async () => { + // Given the user is acting as a copilot delegate while online + mockOnyxState({isActingAsDelegate: true}); + + const {result} = renderHook(() => useSignOut()); + + // When they choose to leave the delegated account + await act(async () => { + await result.current.leaveDelegateAccount(); + }); + + // Then the leave confirm appears and disconnect runs instead of sign-out + expect(mockShowConfirmModal).toHaveBeenCalledWith( + expect.objectContaining({ + prompt: 'delegate.leaveAccountConfirmationText', + confirmText: 'delegate.leaveAccount', + }), + ); + expect(mockDelegateDisconnect).toHaveBeenCalledTimes(1); + expect(mockSignOutAndRedirectToSignIn).not.toHaveBeenCalled(); + }); + + it('should show GPS switch-account warning before disconnecting from a delegated account', async () => { + // Given a copilot is leaving while a GPS trip is in progress + mockOnyxState({isActingAsDelegate: true, isTrackingGPS: true}); + + const {result} = renderHook(() => useSignOut()); + + // When they confirm leaving after the ref has the latest GPS draft + await act(async () => { + await result.current.leaveDelegateAccount({gpsDraftDetailsRef: {current: mockGpsDraftDetails}}); + }); + + // Then points are read from the ref after confirm, and the trip is stopped before disconnect + expect(mockGetGpsPoints).toHaveBeenCalledWith(mockGpsDraftDetails); + expect(mockShowConfirmModal).toHaveBeenCalledWith( + expect.objectContaining({ + title: 'gps.switchAccountWarningTripInProgress.title', + }), + ); + expect(mockStopGpsTrip).toHaveBeenCalledTimes(1); + expect(mockDelegateDisconnect).toHaveBeenCalledTimes(1); + expect(mockSignOutAndRedirectToSignIn).not.toHaveBeenCalled(); + }); + + it('should block leaving a delegated account while offline', async () => { + // Given a copilot is offline and tries to leave the delegated account + mockIsOffline = true; + mockOnyxState({isActingAsDelegate: true}); + + const {result} = renderHook(() => useSignOut()); + + // When leaveDelegateAccount is invoked + await act(async () => { + await result.current.leaveDelegateAccount(); + }); + + // Then the offline modal appears first and disconnect never runs + expect(mockShowConfirmModal).toHaveBeenCalledWith( + expect.objectContaining({ + title: 'common.youAppearToBeOffline', + }), + ); + expect(mockDelegateDisconnect).not.toHaveBeenCalled(); + expect(mockSignOutAndRedirectToSignIn).not.toHaveBeenCalled(); + }); + + it('should expose isActingAsDelegate from account state', () => { + // Given the account is in delegate mode + mockOnyxState({isActingAsDelegate: true}); + + const {result} = renderHook(() => useSignOut()); + + // When the hook is rendered + // Then callers can branch on isActingAsDelegate + expect(result.current.isActingAsDelegate).toBe(true); + }); +});