diff --git a/src/ROUTES.ts b/src/ROUTES.ts index a536cb2d3e86..eb047bdd8269 100644 --- a/src/ROUTES.ts +++ b/src/ROUTES.ts @@ -3543,6 +3543,10 @@ const ROUTES = { route: 'domain/:domainAccountID/admins/settings/primary-contact', getRoute: (domainAccountID: number) => `domain/${domainAccountID}/admins/settings/primary-contact` as const, }, + DOMAIN_ADD_ADMIN: { + route: 'domain/:domainAccountID/admins/invite', + getRoute: (domainAccountID: number) => `domain/${domainAccountID}/admins/invite` as const, + }, } as const; /** diff --git a/src/SCREENS.ts b/src/SCREENS.ts index 5d58876a6d41..f403831809d7 100644 --- a/src/SCREENS.ts +++ b/src/SCREENS.ts @@ -868,6 +868,7 @@ const SCREENS = { ADMIN_DETAILS: 'Domain_Admin_Details', ADMINS_SETTINGS: 'Admins_Settings', ADD_PRIMARY_CONTACT: 'Add_Primary_Contact', + ADD_ADMIN: 'Domain_Add_Admin', }, } as const; diff --git a/src/languages/de.ts b/src/languages/de.ts index e82d16745d3e..213037979830 100644 --- a/src/languages/de.ts +++ b/src/languages/de.ts @@ -8007,11 +8007,15 @@ Hier ist ein *Testbeleg*, um dir zu zeigen, wie es funktioniert:`, findAdmin: 'Admin finden', primaryContact: 'Hauptansprechpartner', addPrimaryContact: 'Primären Kontakt hinzufügen', + setPrimaryContactError: 'Primären Kontakt kann nicht festgelegt werden. Bitte versuchen Sie es später erneut.', settings: 'Einstellungen', consolidatedDomainBilling: 'Konsolidierte Domain-Abrechnung', consolidatedDomainBillingDescription: (domainName: string) => `Wenn diese Option aktiviert ist, bezahlt der Hauptansprechpartner für alle Workspaces, die Mitgliedern von ${domainName} gehören, und erhält alle Rechnungsbelege.`, consolidatedDomainBillingError: 'Die konsolidierte Domain-Abrechnung konnte nicht geändert werden. Bitte versuche es später erneut.', + addAdmin: 'Admin hinzufügen', + invite: 'Einladen', + addAdminError: 'Dieser Benutzer kann nicht als Admin hinzugefügt werden. Bitte versuche es erneut.', }, }, desktopAppRetiredPage: { diff --git a/src/languages/en.ts b/src/languages/en.ts index 37b5b1493735..d29c2b93f782 100755 --- a/src/languages/en.ts +++ b/src/languages/en.ts @@ -7860,11 +7860,15 @@ const translations = { findAdmin: 'Find admin', primaryContact: 'Primary contact', addPrimaryContact: 'Add primary contact', + setPrimaryContactError: 'Unable to set primary contact. Please try again later.', settings: 'Settings', consolidatedDomainBilling: 'Consolidated domain billing', consolidatedDomainBillingDescription: (domainName: string) => `When enabled, the primary contact will pay for all workspaces owned by ${domainName} members and receive all billing receipts.`, consolidatedDomainBillingError: "Consolidated domain billing couldn't be changed. Please try again later.", + addAdmin: 'Add admin', + invite: 'Invite', + addAdminError: 'Unable to add this member as an admin. Please try again.', }, }, }; diff --git a/src/languages/es.ts b/src/languages/es.ts index 5733db07d463..9a84087b38a9 100644 --- a/src/languages/es.ts +++ b/src/languages/es.ts @@ -8030,11 +8030,15 @@ ${amount} para ${merchant} - ${date}`, findAdmin: 'Encontrar administrador', primaryContact: 'Contacto principal', addPrimaryContact: 'Añadir contacto principal', + setPrimaryContactError: 'No se pudo establecer el contacto principal. Por favor, inténtalo de nuevo más tarde.', settings: 'Configuración', consolidatedDomainBilling: 'Facturación consolidada del dominio', consolidatedDomainBillingDescription: (domainName: string) => `Cuando está habilitada, el contacto principal pagará todos los espacios de trabajo propiedad de los miembros de ${domainName} y recibirá todos los recibos de facturación.`, consolidatedDomainBillingError: 'No se pudo cambiar la facturación consolidada del dominio. Por favor, inténtalo de nuevo más tarde.', + addAdmin: 'Añadir administrador', + invite: 'Invitar', + addAdminError: 'No se pudo añadir a este miembro como administrador. Por favor, inténtalo de nuevo.', }, }, }; diff --git a/src/languages/fr.ts b/src/languages/fr.ts index 4f48aa932e47..d9c6f6281619 100644 --- a/src/languages/fr.ts +++ b/src/languages/fr.ts @@ -8012,11 +8012,15 @@ Voici un *reçu test* pour vous montrer comment cela fonctionne :`, findAdmin: 'Trouver un admin', primaryContact: 'Contact principal', addPrimaryContact: 'Ajouter un contact principal', + setPrimaryContactError: 'Impossible de définir le contact principal. Veuillez réessayer plus tard.', settings: 'Paramètres', consolidatedDomainBilling: 'Facturation consolidée du domaine', consolidatedDomainBillingDescription: (domainName: string) => `Lorsque cette option est activée, le contact principal paiera pour tous les espaces de travail appartenant aux membres de ${domainName} et recevra tous les reçus de facturation.`, consolidatedDomainBillingError: 'La facturation de domaine consolidée n’a pas pu être modifiée. Veuillez réessayer plus tard.', + addAdmin: 'Ajouter un administrateur', + invite: 'Inviter', + addAdminError: 'Impossible d’ajouter ce membre en tant qu’administrateur. Veuillez réessayer.', }, }, desktopAppRetiredPage: { diff --git a/src/languages/it.ts b/src/languages/it.ts index f29002cd80c3..13d748cfb120 100644 --- a/src/languages/it.ts +++ b/src/languages/it.ts @@ -7989,11 +7989,15 @@ Ecco una *ricevuta di prova* per mostrarti come funziona:`, findAdmin: 'Trova amministratore', primaryContact: 'Contatto principale', addPrimaryContact: 'Aggiungi contatto principale', + setPrimaryContactError: 'Impossibile impostare il contatto principale. Riprova più tardi.', settings: 'Impostazioni', consolidatedDomainBilling: 'Fatturazione consolidata del dominio', consolidatedDomainBillingDescription: (domainName: string) => `Quando abilitata, il contatto principale pagherà per tutti gli spazi di lavoro di proprietà dei membri di ${domainName} e riceverà tutte le ricevute di fatturazione.`, consolidatedDomainBillingError: 'La fatturazione dominio consolidata non può essere modificata. Riprova più tardi.', + addAdmin: 'Aggiungi amministratore', + invite: 'Invita', + addAdminError: 'Impossibile aggiungere questo membro come amministratore. Riprova.', }, }, desktopAppRetiredPage: { diff --git a/src/languages/ja.ts b/src/languages/ja.ts index 14e2dc0a4549..cf944236917a 100644 --- a/src/languages/ja.ts +++ b/src/languages/ja.ts @@ -7926,11 +7926,15 @@ Expensify の使い方をお見せするための*テストレシート*がこ findAdmin: '管理者を検索', primaryContact: '主要連絡先', addPrimaryContact: '主要連絡先を追加', + setPrimaryContactError: 'メインの連絡先を設定できませんでした。後でもう一度お試しください。', settings: '設定', consolidatedDomainBilling: '統合ドメイン請求', consolidatedDomainBillingDescription: (domainName: string) => `有効にすると、${domainName} メンバーが所有するすべてのワークスペースの支払いを代表連絡先が行い、すべての請求書の領収書を受け取ります。`, consolidatedDomainBillingError: '統合ドメイン請求を変更できませんでした。後でもう一度お試しください。', + addAdmin: '管理者を追加', + invite: '招待', + addAdminError: 'このメンバーを管理者として追加できません。もう一度お試しください。', }, }, desktopAppRetiredPage: { diff --git a/src/languages/nl.ts b/src/languages/nl.ts index e61bc9725564..db5e8a5cead2 100644 --- a/src/languages/nl.ts +++ b/src/languages/nl.ts @@ -7975,11 +7975,15 @@ Hier is een *testbon* om je te laten zien hoe het werkt:`, findAdmin: 'Beheerder zoeken', primaryContact: 'Primair contactpersoon', addPrimaryContact: 'Primair contactpersoon toevoegen', + setPrimaryContactError: 'Kan de primaire contactpersoon niet instellen. Probeer het later opnieuw.', settings: 'Instellingen', consolidatedDomainBilling: 'Geconsolideerde domeinfacturering', consolidatedDomainBillingDescription: (domainName: string) => `Indien ingeschakeld, betaalt de primaire contactpersoon voor alle werkruimten die eigendom zijn van leden van ${domainName} en ontvangt hij/zij alle factuurbewijzen.`, consolidatedDomainBillingError: 'Geconsolideerde domeinfacturering kon niet worden gewijzigd. Probeer het later opnieuw.', + addAdmin: 'Beheerder toevoegen', + invite: 'Uitnodigen', + addAdminError: 'Kan dit lid niet als beheerder toevoegen. Probeer het opnieuw.', }, }, desktopAppRetiredPage: { diff --git a/src/languages/pl.ts b/src/languages/pl.ts index c9adba1bccd1..956be2deae52 100644 --- a/src/languages/pl.ts +++ b/src/languages/pl.ts @@ -7959,11 +7959,15 @@ Oto *paragon testowy*, który pokazuje, jak to działa:`, findAdmin: 'Znajdź administratora', primaryContact: 'Główny kontakt', addPrimaryContact: 'Dodaj główny kontakt', + setPrimaryContactError: 'Nie można ustawić głównego kontaktu. Spróbuj ponownie później.', settings: 'Ustawienia', consolidatedDomainBilling: 'Skonsolidowane rozliczanie domen', consolidatedDomainBillingDescription: (domainName: string) => `Gdy ta opcja jest włączona, główny kontakt będzie opłacać wszystkie przestrzenie robocze należące do członków ${domainName} i otrzymywać wszystkie potwierdzenia rozliczeń.`, consolidatedDomainBillingError: 'Nie udało się zmienić zbiorczego rozliczania domeny. Spróbuj ponownie później.', + addAdmin: 'Dodaj administratora', + invite: 'Zaproś', + addAdminError: 'Nie można dodać tego członka jako administratora. Spróbuj ponownie.', }, }, desktopAppRetiredPage: { diff --git a/src/languages/pt-BR.ts b/src/languages/pt-BR.ts index 2e5d35e43a1c..ec5278095f0c 100644 --- a/src/languages/pt-BR.ts +++ b/src/languages/pt-BR.ts @@ -7966,11 +7966,15 @@ Aqui está um *recibo de teste* para mostrar como funciona:`, findAdmin: 'Encontrar administrador', primaryContact: 'Contato principal', addPrimaryContact: 'Adicionar contato principal', + setPrimaryContactError: 'Não foi possível definir o contato principal. Tente novamente mais tarde.', settings: 'Configurações', consolidatedDomainBilling: 'Cobrança consolidada de domínio', consolidatedDomainBillingDescription: (domainName: string) => `Quando ativado, o contato principal pagará por todos os espaços de trabalho pertencentes aos membros de ${domainName} e receberá todos os recibos de cobrança.`, consolidatedDomainBillingError: 'A cobrança de domínio consolidada não pôde ser alterada. Tente novamente mais tarde.', + addAdmin: 'Adicionar administrador', + invite: 'Convidar', + addAdminError: 'Não foi possível adicionar este membro como administrador. Tente novamente.', }, }, desktopAppRetiredPage: { diff --git a/src/languages/zh-hans.ts b/src/languages/zh-hans.ts index 7b18f9ac93e9..c870970a9228 100644 --- a/src/languages/zh-hans.ts +++ b/src/languages/zh-hans.ts @@ -7787,11 +7787,15 @@ ${reportName} findAdmin: '查找管理员', primaryContact: '主要联系人', addPrimaryContact: '添加主要联系人', + setPrimaryContactError: '无法设置主要联系人。请稍后重试。', settings: '设置', consolidatedDomainBilling: '合并域名结算', consolidatedDomainBillingDescription: (domainName: string) => `启用后,主要联系人将为${domainName}成员拥有的所有工作区付款,并接收所有账单收据。`, consolidatedDomainBillingError: '无法更改合并域账单。请稍后重试。', + addAdmin: '添加管理员', + invite: '邀请', + addAdminError: '无法将此成员添加为管理员。请重试。', }, }, desktopAppRetiredPage: {title: '桌面应用程序已停用', body: '新的 Expensify Mac 桌面应用已停用。今后,请使用网页版应用访问您的账户。', goToWeb: '前往网页'}, diff --git a/src/libs/API/parameters/AddAdminToDomainParams.ts b/src/libs/API/parameters/AddAdminToDomainParams.ts new file mode 100644 index 000000000000..44d7fe1e42a6 --- /dev/null +++ b/src/libs/API/parameters/AddAdminToDomainParams.ts @@ -0,0 +1,7 @@ +type AddAdminToDomainParams = { + authToken?: string | null; + domainName: string; + targetEmail: string; +}; + +export default AddAdminToDomainParams; diff --git a/src/libs/API/parameters/index.ts b/src/libs/API/parameters/index.ts index b3c1fbf3ec48..818a8624d2d7 100644 --- a/src/libs/API/parameters/index.ts +++ b/src/libs/API/parameters/index.ts @@ -447,6 +447,7 @@ export type {default as DomainParams} from './DomainParams'; export type {default as GetScimTokenParams} from './GetScimTokenParams'; export type {default as SetSamlIdentityParams} from './SetSamlIdentityParams'; export type {default as UpdateSamlEnabledParams} from './UpdateSamlEnabledParams'; +export type {default as AddAdminToDomainParams} from './AddAdminToDomainParams'; export type {default as UpdateSamlRequiredParams} from './UpdateSamlRequiredParams'; export type {default as SetPolicyRequireCompanyCardsEnabledParams} from './SetPolicyRequireCompanyCardsEnabled'; export type {default as SetTechnicalContactEmailParams} from './SetTechnicalContactEmailParams'; diff --git a/src/libs/API/types.ts b/src/libs/API/types.ts index b162c99622f4..077e4f597a71 100644 --- a/src/libs/API/types.ts +++ b/src/libs/API/types.ts @@ -529,6 +529,7 @@ const WRITE_COMMANDS = { CREATE_DOMAIN: 'CreateDomain', SET_TECHNICAL_CONTACT_EMAIL: 'SetTechnicalContactEmail', TOGGLE_CONSOLIDATED_DOMAIN_BILLING: 'ToggleConsolidatedDomainBilling', + ADD_DOMAIN_ADMIN: 'AddDomainAdmin', } as const; type WriteCommand = ValueOf; @@ -1079,6 +1080,7 @@ type WriteCommandParameters = { [WRITE_COMMANDS.CREATE_DOMAIN]: Parameters.DomainParams; [WRITE_COMMANDS.SET_TECHNICAL_CONTACT_EMAIL]: Parameters.SetTechnicalContactEmailParams; [WRITE_COMMANDS.TOGGLE_CONSOLIDATED_DOMAIN_BILLING]: Parameters.ToggleConsolidatedDomainBillingParams; + [WRITE_COMMANDS.ADD_DOMAIN_ADMIN]: Parameters.AddAdminToDomainParams; }; const READ_COMMANDS = { diff --git a/src/libs/Navigation/AppNavigator/ModalStackNavigators/index.tsx b/src/libs/Navigation/AppNavigator/ModalStackNavigators/index.tsx index 572de5a49860..aadab2aa1334 100644 --- a/src/libs/Navigation/AppNavigator/ModalStackNavigators/index.tsx +++ b/src/libs/Navigation/AppNavigator/ModalStackNavigators/index.tsx @@ -801,6 +801,7 @@ const SettingsModalStackNavigator = createModalStackNavigator require('../../../../pages/domain/Admins/DomainAdminDetailsPage').default, [SCREENS.DOMAIN.ADMINS_SETTINGS]: () => require('../../../../pages/domain/Admins/DomainAdminsSettingsPage').default, [SCREENS.DOMAIN.ADD_PRIMARY_CONTACT]: () => require('../../../../pages/domain/Admins/DomainAddPrimaryContactPage').default, + [SCREENS.DOMAIN.ADD_ADMIN]: () => require('../../../../pages/domain/Admins/DomainAddAdminPage').default, }); const TwoFactorAuthenticatorStackNavigator = createModalStackNavigator({ diff --git a/src/libs/Navigation/linkingConfig/RELATIONS/DOMAIN_TO_RHP.ts b/src/libs/Navigation/linkingConfig/RELATIONS/DOMAIN_TO_RHP.ts index ea0c54caf54d..3a1e3bad6016 100755 --- a/src/libs/Navigation/linkingConfig/RELATIONS/DOMAIN_TO_RHP.ts +++ b/src/libs/Navigation/linkingConfig/RELATIONS/DOMAIN_TO_RHP.ts @@ -5,7 +5,7 @@ import SCREENS from '@src/SCREENS'; const DOMAIN_TO_RHP: Partial> = { [SCREENS.DOMAIN.INITIAL]: [], [SCREENS.DOMAIN.SAML]: [SCREENS.DOMAIN.VERIFY, SCREENS.DOMAIN.VERIFIED], - [SCREENS.DOMAIN.ADMINS]: [SCREENS.DOMAIN.ADMIN_DETAILS, SCREENS.DOMAIN.ADMINS_SETTINGS, SCREENS.DOMAIN.ADD_PRIMARY_CONTACT], + [SCREENS.DOMAIN.ADMINS]: [SCREENS.DOMAIN.ADMIN_DETAILS, SCREENS.DOMAIN.ADMINS_SETTINGS, SCREENS.DOMAIN.ADD_PRIMARY_CONTACT, SCREENS.DOMAIN.ADD_ADMIN], }; export default DOMAIN_TO_RHP; diff --git a/src/libs/Navigation/linkingConfig/config.ts b/src/libs/Navigation/linkingConfig/config.ts index 11b198d0993d..af437f9b4037 100644 --- a/src/libs/Navigation/linkingConfig/config.ts +++ b/src/libs/Navigation/linkingConfig/config.ts @@ -1129,6 +1129,9 @@ const config: LinkingOptions['config'] = { [SCREENS.DOMAIN.VERIFY]: { path: ROUTES.DOMAIN_VERIFY.route, }, + [SCREENS.DOMAIN.ADD_ADMIN]: { + path: ROUTES.DOMAIN_ADD_ADMIN.route, + }, [SCREENS.DOMAIN.VERIFIED]: { path: ROUTES.DOMAIN_VERIFIED.route, }, diff --git a/src/libs/Navigation/types.ts b/src/libs/Navigation/types.ts index 6e6f6933331e..834a2e1f720f 100644 --- a/src/libs/Navigation/types.ts +++ b/src/libs/Navigation/types.ts @@ -1371,6 +1371,9 @@ type SettingsNavigatorParamList = { [SCREENS.DOMAIN.ADD_PRIMARY_CONTACT]: { domainAccountID: number; }; + [SCREENS.DOMAIN.ADD_ADMIN]: { + domainAccountID: number; + }; } & ReimbursementAccountNavigatorParamList; type DomainCardNavigatorParamList = { diff --git a/src/libs/actions/Domain.ts b/src/libs/actions/Domain.ts index 6ffe3610cdef..cf0ed603ade7 100644 --- a/src/libs/actions/Domain.ts +++ b/src/libs/actions/Domain.ts @@ -1,7 +1,7 @@ import Onyx from 'react-native-onyx'; import type {OnyxUpdate} from 'react-native-onyx'; import * as API from '@libs/API'; -import type {SetTechnicalContactEmailParams, ToggleConsolidatedDomainBillingParams} from '@libs/API/parameters'; +import type {AddAdminToDomainParams, SetTechnicalContactEmailParams, ToggleConsolidatedDomainBillingParams} from '@libs/API/parameters'; import {READ_COMMANDS, SIDE_EFFECT_REQUEST_COMMANDS, WRITE_COMMANDS} from '@libs/API/types'; import {getMicroSecondOnyxErrorWithTranslationKey} from '@libs/ErrorUtils'; import {getAuthToken} from '@libs/Network/NetworkStore'; @@ -371,6 +371,13 @@ function setPrimaryContact(domainAccountID: number, newTechnicalContactAccountID technicalContactEmail: CONST.RED_BRICK_ROAD_PENDING_ACTION.UPDATE, }, }, + { + onyxMethod: Onyx.METHOD.MERGE, + key: `${ONYXKEYS.COLLECTION.DOMAIN_ERRORS}${domainAccountID}`, + value: { + technicalContactEmailErrors: null, + }, + }, ]; const successData: OnyxUpdate[] = [ { @@ -380,6 +387,13 @@ function setPrimaryContact(domainAccountID: number, newTechnicalContactAccountID technicalContactEmail: null, }, }, + { + onyxMethod: Onyx.METHOD.MERGE, + key: `${ONYXKEYS.COLLECTION.DOMAIN_ERRORS}${domainAccountID}`, + value: { + technicalContactEmailErrors: null, + }, + }, ]; const failureData: OnyxUpdate[] = [ { @@ -391,6 +405,13 @@ function setPrimaryContact(domainAccountID: number, newTechnicalContactAccountID }, }, }, + { + onyxMethod: Onyx.METHOD.MERGE, + key: `${ONYXKEYS.COLLECTION.DOMAIN_ERRORS}${domainAccountID}`, + value: { + technicalContactEmailErrors: getMicroSecondOnyxErrorWithTranslationKey('domain.admins.setPrimaryContactError'), + }, + }, { onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.DOMAIN_PENDING_ACTIONS}${domainAccountID}`, @@ -501,6 +522,127 @@ function clearToggleConsolidatedDomainBillingErrors(domainAccountID: number) { }); } +function addAdminToDomain(domainAccountID: number, accountID: number, targetEmail: string, domainName: string) { + const PERMISSION_KEY = `${ONYXKEYS.COLLECTION.EXPENSIFY_ADMIN_ACCESS_PREFIX}${accountID}`; + + const optimisticData: OnyxUpdate[] = [ + { + onyxMethod: Onyx.METHOD.MERGE, + key: `${ONYXKEYS.COLLECTION.DOMAIN}${domainAccountID}`, + value: { + [PERMISSION_KEY]: accountID, + }, + }, + { + onyxMethod: Onyx.METHOD.MERGE, + key: `${ONYXKEYS.COLLECTION.DOMAIN_PENDING_ACTIONS}${domainAccountID}`, + value: { + admin: { + [accountID]: { + pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD, + }, + }, + }, + }, + { + onyxMethod: Onyx.METHOD.MERGE, + key: `${ONYXKEYS.COLLECTION.DOMAIN_ERRORS}${domainAccountID}`, + value: { + adminErrors: { + [accountID]: { + errors: null, + }, + }, + }, + }, + ]; + + const successData: OnyxUpdate[] = [ + { + onyxMethod: Onyx.METHOD.MERGE, + key: `${ONYXKEYS.COLLECTION.DOMAIN}${domainAccountID}`, + value: { + [PERMISSION_KEY]: null, + }, + }, + { + onyxMethod: Onyx.METHOD.MERGE, + key: `${ONYXKEYS.COLLECTION.DOMAIN_ERRORS}${domainAccountID}`, + value: { + adminErrors: { + [accountID]: { + errors: null, + }, + }, + }, + }, + { + onyxMethod: Onyx.METHOD.MERGE, + key: `${ONYXKEYS.COLLECTION.DOMAIN_PENDING_ACTIONS}${domainAccountID}`, + value: { + admin: { + [accountID]: null, + }, + }, + }, + ]; + + const failureData: OnyxUpdate[] = [ + { + onyxMethod: Onyx.METHOD.MERGE, + key: `${ONYXKEYS.COLLECTION.DOMAIN_ERRORS}${domainAccountID}`, + value: { + adminErrors: { + [accountID]: { + errors: getMicroSecondOnyxErrorWithTranslationKey('domain.admins.addAdminError'), + }, + }, + }, + }, + { + onyxMethod: Onyx.METHOD.MERGE, + key: `${ONYXKEYS.COLLECTION.DOMAIN_PENDING_ACTIONS}${domainAccountID}`, + value: { + admin: { + [accountID]: null, + }, + }, + }, + ]; + + const authToken = getAuthToken(); + const params: AddAdminToDomainParams = { + authToken, + domainName, + targetEmail, + }; + + API.write(WRITE_COMMANDS.ADD_DOMAIN_ADMIN, params, {optimisticData, successData, failureData}); +} + +/** + * Removes an error after trying to add admin + */ +function clearAddAdminError(domainAccountID: number, accountID: number) { + const PERMISSION_KEY = `${ONYXKEYS.COLLECTION.EXPENSIFY_ADMIN_ACCESS_PREFIX}${accountID}`; + + Onyx.merge(`${ONYXKEYS.COLLECTION.DOMAIN}${domainAccountID}`, { + [PERMISSION_KEY]: null, + }); + + Onyx.merge(`${ONYXKEYS.COLLECTION.DOMAIN_ERRORS}${domainAccountID}`, { + adminErrors: { + [accountID]: null, + }, + }); + + Onyx.merge(`${ONYXKEYS.COLLECTION.DOMAIN_PENDING_ACTIONS}${domainAccountID}`, { + admin: { + [accountID]: null, + }, + }); +} + export { getDomainValidationCode, validateDomain, @@ -519,4 +661,6 @@ export { clearSetPrimaryContactError, toggleConsolidatedDomainBilling, clearToggleConsolidatedDomainBillingErrors, + addAdminToDomain, + clearAddAdminError, }; diff --git a/src/pages/domain/Admins/DomainAddAdminPage.tsx b/src/pages/domain/Admins/DomainAddAdminPage.tsx new file mode 100644 index 000000000000..3f9d442784a5 --- /dev/null +++ b/src/pages/domain/Admins/DomainAddAdminPage.tsx @@ -0,0 +1,148 @@ +import {adminAccountIDsSelector, domainEmailSelector} from '@selectors/Domain'; +import {Str} from 'expensify-common'; +import React, {useEffect, useRef, useState} from 'react'; +import type {SectionListData} from 'react-native'; +import FormAlertWithSubmitButton from '@components/FormAlertWithSubmitButton'; +import HeaderWithBackButton from '@components/HeaderWithBackButton'; +import ScreenWrapper from '@components/ScreenWrapper'; +// eslint-disable-next-line no-restricted-imports +import SelectionList from '@components/SelectionListWithSections'; +import InviteMemberListItem from '@components/SelectionListWithSections/InviteMemberListItem'; +import type {Section} from '@components/SelectionListWithSections/types'; +import useLocalize from '@hooks/useLocalize'; +import useOnyx from '@hooks/useOnyx'; +import useSearchSelector from '@hooks/useSearchSelector'; +import useThemeStyles from '@hooks/useThemeStyles'; +import {searchInServer} from '@libs/actions/Report'; +import {canUseTouchScreen} from '@libs/DeviceCapabilities'; +import Navigation from '@libs/Navigation/Navigation'; +import type {PlatformStackScreenProps} from '@libs/Navigation/PlatformStackNavigation/types'; +import {getHeaderMessage} from '@libs/OptionsListUtils'; +import type {OptionData} from '@libs/ReportUtils'; +import type {SettingsNavigatorParamList} from '@navigation/types'; +import DomainNotFoundPageWrapper from '@pages/domain/DomainNotFoundPageWrapper'; +import {addAdminToDomain} from '@userActions/Domain'; +import CONST from '@src/CONST'; +import ONYXKEYS from '@src/ONYXKEYS'; +import ROUTES from '@src/ROUTES'; +import type SCREENS from '@src/SCREENS'; + +type Sections = SectionListData>; + +type DomainAddAdminProps = PlatformStackScreenProps; + +function DomainAddAdminPage({route}: DomainAddAdminProps) { + const {domainAccountID} = route.params; + + const styles = useThemeStyles(); + const {translate} = useLocalize(); + + const [countryCode = CONST.DEFAULT_COUNTRY_CODE] = useOnyx(ONYXKEYS.COUNTRY_CODE, {canBeMissing: false}); + const [isSearchingForReports] = useOnyx(ONYXKEYS.IS_SEARCHING_FOR_REPORTS, {initWithStoredValues: false, canBeMissing: true}); + const [domainEmail] = useOnyx(`${ONYXKEYS.COLLECTION.DOMAIN}${domainAccountID}`, { + canBeMissing: true, + selector: domainEmailSelector, + }); + const [adminIDs] = useOnyx(`${ONYXKEYS.COLLECTION.DOMAIN}${domainAccountID}`, { + canBeMissing: true, + selector: adminAccountIDsSelector, + }); + + const [didScreenTransitionEnd, setDidScreenTransitionEnd] = useState(false); + const [currentlySelectedUser, setCurrentlySelectedUser] = useState(null); + const didInvite = useRef(false); + + const domainName = domainEmail ? Str.extractEmailDomain(domainEmail) : undefined; + const {searchTerm, setSearchTerm, availableOptions, toggleSelection, areOptionsInitialized, onListEndReached} = useSearchSelector({ + selectionMode: CONST.SEARCH_SELECTOR.SELECTION_MODE_SINGLE, + searchContext: CONST.SEARCH_SELECTOR.SEARCH_CONTEXT_MEMBER_INVITE, + includeRecentReports: false, + excludeLogins: Object.fromEntries(CONST.EXPENSIFY_EMAILS.map((email) => [email, true])), + shouldInitialize: didScreenTransitionEnd, + onSingleSelect: (option) => setCurrentlySelectedUser({...option, isSelected: true}), + }); + + useEffect(() => { + searchInServer(searchTerm); + }, [searchTerm]); + + const inviteUser = () => { + if (didInvite.current || !currentlySelectedUser || !currentlySelectedUser.accountID || !currentlySelectedUser.login || !domainName) { + return; + } + didInvite.current = true; + + addAdminToDomain(domainAccountID, currentlySelectedUser.accountID, currentlySelectedUser.login, domainName); + Navigation.dismissModal(); + }; + + const filteredOptions = areOptionsInitialized + ? availableOptions.personalDetails.filter(({accountID}) => accountID && accountID !== currentlySelectedUser?.accountID && !adminIDs?.includes(accountID)) + : []; + + const sections: Sections[] = []; + if (areOptionsInitialized) { + if (currentlySelectedUser) { + sections.push({ + title: undefined, + data: [currentlySelectedUser], + }); + } + + if (filteredOptions.length > 0) { + sections.push({ + title: translate('common.contacts'), + data: filteredOptions, + }); + } + } + + const footerContent = ( + + ); + + return ( + + setDidScreenTransitionEnd(true)} + > + Navigation.goBack(ROUTES.DOMAIN_ADMINS.getRoute(domainAccountID))} + /> + 0 || !!currentlySelectedUser, !!currentlySelectedUser, searchTerm.trim().toLowerCase(), countryCode, false)} + ListItem={InviteMemberListItem} + textInputLabel={translate('selectionList.nameEmailOrPhoneNumber')} + textInputValue={searchTerm} + onChangeText={(value) => setSearchTerm(value)} + onSelectRow={(option: OptionData) => toggleSelection(option)} + onConfirm={inviteUser} + showScrollIndicator + showLoadingPlaceholder={!areOptionsInitialized || !didScreenTransitionEnd} + shouldPreventDefaultFocusOnSelectRow={!canUseTouchScreen()} + footerContent={footerContent} + isLoadingNewOptions={!!isSearchingForReports} + addBottomSafeAreaPadding + onEndReached={onListEndReached} + /> + + + ); +} + +DomainAddAdminPage.displayName = 'DomainAddAdminPage'; + +export default DomainAddAdminPage; diff --git a/src/pages/domain/Admins/DomainAddPrimaryContactPage.tsx b/src/pages/domain/Admins/DomainAddPrimaryContactPage.tsx index fd8271c1747e..e274070b3ade 100644 --- a/src/pages/domain/Admins/DomainAddPrimaryContactPage.tsx +++ b/src/pages/domain/Admins/DomainAddPrimaryContactPage.tsx @@ -58,10 +58,17 @@ function DomainAddPrimaryContactPage({route}: DomainAddPrimaryContactPageProps) canBeMissing: false, selector: technicalContactSettingsSelector, }); + const [domainErrors] = useOnyx(`${ONYXKEYS.COLLECTION.DOMAIN_ERRORS}${domainAccountID}`, {canBeMissing: true}); let technicalContactEmailKey: string | undefined; const data: AdminOption[] = []; for (const accountID of adminAccountIDs ?? []) { + // Don't show admins with errors + const adminErrors = domainErrors?.adminErrors?.[accountID] ?? {}; + if (Object.keys(adminErrors).length !== 0) { + continue; + } + const details = personalDetails?.[accountID]; if (details?.login === technicalContactSettings?.technicalContactEmail) { technicalContactEmailKey = String(accountID); diff --git a/src/pages/domain/Admins/DomainAdminsPage.tsx b/src/pages/domain/Admins/DomainAdminsPage.tsx index 2a8e1675ba43..3f9340e64608 100644 --- a/src/pages/domain/Admins/DomainAdminsPage.tsx +++ b/src/pages/domain/Admins/DomainAdminsPage.tsx @@ -18,6 +18,7 @@ import useOnyx from '@hooks/useOnyx'; import useResponsiveLayout from '@hooks/useResponsiveLayout'; import useSearchResults from '@hooks/useSearchResults'; import useThemeStyles from '@hooks/useThemeStyles'; +import {getLatestError} from '@libs/ErrorUtils'; import {sortAlphabetically} from '@libs/OptionsListUtils'; import {getDisplayNameOrDefault} from '@libs/PersonalDetailsUtils'; import tokenizedSearch from '@libs/tokenizedSearch'; @@ -25,6 +26,7 @@ import Navigation from '@navigation/Navigation'; import type {PlatformStackScreenProps} from '@navigation/PlatformStackNavigation/types'; import type {DomainSplitNavigatorParamList} from '@navigation/types'; import DomainNotFoundPageWrapper from '@pages/domain/DomainNotFoundPageWrapper'; +import {clearAddAdminError} from '@userActions/Domain'; import {getCurrentUserAccountID} from '@userActions/Report'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; @@ -45,7 +47,7 @@ function DomainAdminsPage({route}: DomainAdminsPageProps) { const {translate, formatPhoneNumber, localeCompare} = useLocalize(); const styles = useThemeStyles(); const illustrations = useMemoizedLazyIllustrations(['Members']); - const icons = useMemoizedLazyExpensifyIcons(['FallbackAvatar', 'Gear']); + const icons = useMemoizedLazyExpensifyIcons(['FallbackAvatar', 'Gear', 'Plus']); const {shouldUseNarrowLayout} = useResponsiveLayout(); const [adminAccountIDs, domainMetadata] = useOnyx(`${ONYXKEYS.COLLECTION.DOMAIN}${domainAccountID}`, { @@ -57,6 +59,8 @@ function DomainAdminsPage({route}: DomainAdminsPageProps) { canBeMissing: false, selector: technicalContactSettingsSelector, }); + const [domainErrors] = useOnyx(`${ONYXKEYS.COLLECTION.DOMAIN_ERRORS}${domainAccountID}`, {canBeMissing: true}); + const [domainPendingActions] = useOnyx(`${ONYXKEYS.COLLECTION.DOMAIN_PENDING_ACTIONS}${domainAccountID}`, {canBeMissing: true}); const currentUserAccountID = getCurrentUserAccountID(); const isAdmin = adminAccountIDs?.includes(currentUserAccountID); @@ -80,6 +84,8 @@ function DomainAdminsPage({route}: DomainAdminsPageProps) { }, ], rightElement: isPrimaryContact && , + errors: getLatestError(domainErrors?.adminErrors?.[accountID]?.errors), + pendingAction: domainPendingActions?.admin?.[accountID]?.pendingAction, }); } @@ -109,6 +115,16 @@ function DomainAdminsPage({route}: DomainAdminsPageProps) { } return ( +