From 5c3dc45505a498b54a1b5b392595d08de17791ff Mon Sep 17 00:00:00 2001 From: Rutika Pawar <183392827+twilight2294@users.noreply.github.com> Date: Sat, 8 Mar 2025 15:24:03 +0000 Subject: [PATCH 01/43] Fix: Category and Tag "Required" switch is enabled and locked evenif all tags are disable --- src/languages/en.ts | 9 +++ src/languages/es.ts | 4 ++ src/libs/OptionsListUtils.ts | 5 +- src/libs/PolicyUtils.ts | 5 +- src/libs/actions/Policy/Category.ts | 69 +------------------ src/libs/actions/Policy/Tag.ts | 5 -- .../categories/CategorySettingsPage.tsx | 15 ++++ .../categories/WorkspaceCategoriesPage.tsx | 28 +++++++- src/pages/workspace/tags/TagSettingsPage.tsx | 19 ++++- .../workspace/tags/WorkspaceTagsPage.tsx | 28 +++++++- 10 files changed, 108 insertions(+), 79 deletions(-) diff --git a/src/languages/en.ts b/src/languages/en.ts index 8016342f090b..b4148fe9910e 100755 --- a/src/languages/en.ts +++ b/src/languages/en.ts @@ -1,5 +1,6 @@ import {CONST as COMMON_CONST} from 'expensify-common'; import startCase from 'lodash/startCase'; +import {title} from 'process'; import CONST from '@src/CONST'; import type {Country} from '@src/CONST'; import type { @@ -3731,6 +3732,10 @@ const translations = { glCode: 'GL code', updateGLCodeFailureMessage: 'An error occurred while updating the GL code, please try again.', importCategories: 'Import categories', + cannotDisableAllCategories: { + title: 'Cannot disable all categories', + description: `You can't disable all categories when categories are requied on the workspace.`, + }, }, moreFeatures: { subtitle: 'Use the toggles below to enable more features as you grow. Each feature will appear in the navigation menu for further customization.', @@ -3966,6 +3971,10 @@ const translations = { importTags: 'Import tags', importedTagsMessage: ({columnCounts}: ImportedTagsMessageParams) => `We found *${columnCounts} columns* in your spreadsheet. Select *Name* next to the column that contains tags names. You can also select *Enabled* next to the column that sets tags status.`, + cannotDisableAllTags: { + title: 'Cannot disable all tags', + description: `You can't disable all tags when tags are requied on the workspace.`, + }, }, taxes: { subtitle: 'Add tax names, rates, and set defaults.', diff --git a/src/languages/es.ts b/src/languages/es.ts index 0d82fb9fe399..592f1e1885e2 100644 --- a/src/languages/es.ts +++ b/src/languages/es.ts @@ -3774,6 +3774,10 @@ const translations = { glCode: 'Código de Libro Mayor', updateGLCodeFailureMessage: 'Se produjo un error al actualizar el código de Libro Mayor. Inténtelo nuevamente.', importCategories: 'Importar categorías', + cannotDisableAllCategories: { + title: 'No se pueden deshabilitar todas las categorías', + description: `No puedes deshabilitar todas las categorías cuando se requieren en el espacio de trabajo.`, + }, }, moreFeatures: { subtitle: 'Utiliza los botones de abajo para activar más funciones a medida que creces. Cada función aparecerá en el menú de navegación para una mayor personalización.', diff --git a/src/libs/OptionsListUtils.ts b/src/libs/OptionsListUtils.ts index 90a161ef22cf..1d5bedda1913 100644 --- a/src/libs/OptionsListUtils.ts +++ b/src/libs/OptionsListUtils.ts @@ -984,7 +984,10 @@ function isCurrentUser(userDetails: PersonalDetails): boolean { /** * Calculates count of all enabled options */ -function getEnabledCategoriesCount(options: PolicyCategories): number { +function getEnabledCategoriesCount(options: PolicyCategories | undefined): number { + if (options === undefined) { + return 0; + } return Object.values(options).filter((option) => option.enabled).length; } diff --git a/src/libs/PolicyUtils.ts b/src/libs/PolicyUtils.ts index 92f47b91e8ee..004d4822cb25 100644 --- a/src/libs/PolicyUtils.ts +++ b/src/libs/PolicyUtils.ts @@ -407,7 +407,10 @@ function escapeTagName(tag: string) { /** * Gets a count of enabled tags of a policy */ -function getCountOfEnabledTagsOfList(policyTags: PolicyTags) { +function getCountOfEnabledTagsOfList(policyTags: PolicyTags | undefined): number { + if (!policyTags) { + return 0; + } return Object.values(policyTags).filter((policyTag) => policyTag.enabled).length; } diff --git a/src/libs/actions/Policy/Category.ts b/src/libs/actions/Policy/Category.ts index 5613209b9a0d..ee6312d8c52d 100644 --- a/src/libs/actions/Policy/Category.ts +++ b/src/libs/actions/Policy/Category.ts @@ -295,7 +295,6 @@ function buildOptimisticPolicyRecentlyUsedCategories(policyID?: string, category function setWorkspaceCategoryEnabled(policyID: string, categoriesToUpdate: Record) { const policyCategories = allPolicyCategories?.[`${ONYXKEYS.COLLECTION.POLICY_CATEGORIES}${policyID}`] ?? {}; - const policy = allPolicies?.[`${ONYXKEYS.COLLECTION.POLICY}${policyID}`]; const optimisticPolicyCategoriesData = { ...Object.keys(categoriesToUpdate).reduce((acc, key) => { acc[key] = { @@ -310,7 +309,7 @@ function setWorkspaceCategoryEnabled(policyID: string, categoriesToUpdate: Recor return acc; }, {}), }; - const shouldDisableRequiresCategory = !hasEnabledOptions({...policyCategories, ...optimisticPolicyCategoriesData}); + const onyxData: OnyxData = { optimisticData: [ { @@ -359,37 +358,6 @@ function setWorkspaceCategoryEnabled(policyID: string, categoriesToUpdate: Recor }, ], }; - if (shouldDisableRequiresCategory) { - onyxData.optimisticData?.push({ - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.POLICY}${policyID}`, - value: { - requiresCategory: false, - pendingFields: { - requiresCategory: CONST.RED_BRICK_ROAD_PENDING_ACTION.UPDATE, - }, - }, - }); - onyxData.successData?.push({ - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.POLICY}${policyID}`, - value: { - pendingFields: { - requiresCategory: null, - }, - }, - }); - onyxData.failureData?.push({ - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.POLICY}${policyID}`, - value: { - requiresCategory: policy?.requiresCategory, - pendingFields: { - requiresCategory: null, - }, - }, - }); - } const parameters = { policyID, @@ -962,9 +930,7 @@ function deleteWorkspaceCategories(policyID: string, categoryNamesToDelete: stri acc[categoryName] = {pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE, enabled: false}; return acc; }, {}); - const shouldDisableRequiresCategory = !hasEnabledOptions( - Object.values(policyCategories).filter((category) => !categoryNamesToDelete.includes(category.name) && category.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE), - ); + const onyxData: OnyxData = { optimisticData: [ { @@ -998,37 +964,6 @@ function deleteWorkspaceCategories(policyID: string, categoryNamesToDelete: stri }, ], }; - if (shouldDisableRequiresCategory) { - onyxData.optimisticData?.push({ - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.POLICY}${policyID}`, - value: { - requiresCategory: false, - pendingFields: { - requiresCategory: CONST.RED_BRICK_ROAD_PENDING_ACTION.UPDATE, - }, - }, - }); - onyxData.successData?.push({ - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.POLICY}${policyID}`, - value: { - pendingFields: { - requiresCategory: null, - }, - }, - }); - onyxData.failureData?.push({ - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.POLICY}${policyID}`, - value: { - requiresCategory: policy?.requiresCategory, - pendingFields: { - requiresCategory: null, - }, - }, - }); - } const parameters = { policyID, diff --git a/src/libs/actions/Policy/Tag.ts b/src/libs/actions/Policy/Tag.ts index c22a5922d0dd..e697c7721f60 100644 --- a/src/libs/actions/Policy/Tag.ts +++ b/src/libs/actions/Policy/Tag.ts @@ -260,8 +260,6 @@ function setWorkspaceTagEnabled(policyID: string, tagsToUpdate: Record((acc, key) => { acc[key] = { @@ -308,7 +304,6 @@ function setWorkspaceTagEnabled(policyID: string, tagsToUpdate: Record((acc, key) => { acc[key] = { diff --git a/src/pages/workspace/categories/CategorySettingsPage.tsx b/src/pages/workspace/categories/CategorySettingsPage.tsx index 983795fd3e7c..88cfad62d43e 100644 --- a/src/pages/workspace/categories/CategorySettingsPage.tsx +++ b/src/pages/workspace/categories/CategorySettingsPage.tsx @@ -20,6 +20,7 @@ import {convertToDisplayString} from '@libs/CurrencyUtils'; import {getLatestErrorMessageField} from '@libs/ErrorUtils'; import Navigation from '@libs/Navigation/Navigation'; import type {PlatformStackScreenProps} from '@libs/Navigation/PlatformStackNavigation/types'; +import {getEnabledCategoriesCount} from '@libs/OptionsListUtils'; import {getPersonalDetailByEmail} from '@libs/PersonalDetailsUtils'; import {getWorkflowApprovalsUnavailable, isControlPolicy} from '@libs/PolicyUtils'; import type {SettingsNavigatorParamList} from '@navigation/types'; @@ -55,6 +56,7 @@ function CategorySettingsPage({ const policyCurrency = policy?.outputCurrency ?? CONST.CURRENCY.USD; const policyCategoryExpenseLimitType = policyCategory?.expenseLimitType ?? CONST.POLICY.EXPENSE_LIMIT_TYPES.EXPENSE; + const [showCannotDisableLastCategoryModal, setShowCannotDisableLastCategoryModal] = useState(false); const areCommentsRequired = policyCategory?.areCommentsRequired ?? false; const isQuickSettingsFlow = !!backTo; @@ -113,6 +115,10 @@ function CategorySettingsPage({ } const updateWorkspaceRequiresCategory = (value: boolean) => { + if (policy?.requiresCategory && getEnabledCategoriesCount(policyCategories) === 1 && !value) { + setShowCannotDisableLastCategoryModal(true); + return; + } setWorkspaceCategoryEnabled(policyID, {[policyCategory.name]: {name: policyCategory.name, enabled: value}}); }; @@ -159,6 +165,14 @@ function CategorySettingsPage({ cancelText={translate('common.cancel')} danger /> + setShowCannotDisableLastCategoryModal(false)} + title={translate('workspace.categories.cannotDisableAllCategories.title')} + prompt={translate('workspace.categories.cannotDisableAllCategories.description')} + confirmText={translate('common.buttonConfirm')} + shouldShowCancelButton={false} + /> diff --git a/src/pages/workspace/categories/WorkspaceCategoriesPage.tsx b/src/pages/workspace/categories/WorkspaceCategoriesPage.tsx index 9b9c056e0242..eda82d649867 100644 --- a/src/pages/workspace/categories/WorkspaceCategoriesPage.tsx +++ b/src/pages/workspace/categories/WorkspaceCategoriesPage.tsx @@ -40,6 +40,7 @@ import localeCompare from '@libs/LocaleCompare'; import Navigation from '@libs/Navigation/Navigation'; import type {PlatformStackScreenProps} from '@libs/Navigation/PlatformStackNavigation/types'; import type {WorkspaceSplitNavigatorParamList} from '@libs/Navigation/types'; +import {getEnabledCategoriesCount} from '@libs/OptionsListUtils'; import {getCurrentConnectionName, hasAccountingConnections, shouldShowSyncError} from '@libs/PolicyUtils'; import AccessOrNotFoundWrapper from '@pages/workspace/AccessOrNotFoundWrapper'; import {close} from '@userActions/Modal'; @@ -70,6 +71,7 @@ function WorkspaceCategoriesPage({route}: WorkspaceCategoriesPageProps) { const [selectedCategories, setSelectedCategories] = useState>({}); const [isDownloadFailureModalVisible, setIsDownloadFailureModalVisible] = useState(false); const [deleteCategoriesConfirmModalVisible, setDeleteCategoriesConfirmModalVisible] = useState(false); + const [showCannotDisableLastCategoryModal, setShowCannotDisableLastCategoryModal] = useState(false); const {environmentURL} = useEnvironment(); const policyId = route.params.policyID; const backTo = route.params?.backTo; @@ -133,14 +135,21 @@ function WorkspaceCategoriesPage({route}: WorkspaceCategoriesPageProps) { isOn={value.enabled} disabled={isDisabled} accessibilityLabel={translate('workspace.categories.enableCategory')} - onToggle={(newValue: boolean) => updateWorkspaceRequiresCategory(newValue, value.name)} + onToggle={(newValue: boolean) => { + if (policy?.requiresCategory && getEnabledCategoriesCount(policyCategories) === 1 && !newValue) { + setShowCannotDisableLastCategoryModal(true); + return; + } + updateWorkspaceRequiresCategory(newValue, value.name); + }} + showLockIcon={getEnabledCategoriesCount(policyCategories) === 1 && policy?.requiresCategory && value.enabled} /> ), }); return acc; }, []); - }, [policyCategories, isOffline, selectedCategories, canSelectMultiple, translate, updateWorkspaceRequiresCategory]); + }, [policyCategories, isOffline, selectedCategories, canSelectMultiple, translate, updateWorkspaceRequiresCategory, policy?.requiresCategory]); useAutoTurnSelectionModeOffWhenHasNoActiveOption(categoryList); @@ -228,11 +237,17 @@ function WorkspaceCategoriesPage({route}: WorkspaceCategoriesPageProps) { return acc; }, {}); + const categoriesToDisableCount = Object.keys(categoriesToDisable).length; + const enabledCategoriesCount = getEnabledCategoriesCount(policyCategories); options.push({ icon: Expensicons.Close, text: translate(enabledCategories.length === 1 ? 'workspace.categories.disableCategory' : 'workspace.categories.disableCategories'), value: CONST.POLICY.BULK_ACTION_TYPES.DISABLE, onSelected: () => { + if (categoriesToDisableCount === enabledCategoriesCount && policy?.requiresCategory) { + setShowCannotDisableLastCategoryModal(true); + return; + } setSelectedCategories({}); setWorkspaceCategoryEnabled(policyId, categoriesToDisable); }, @@ -455,6 +470,15 @@ function WorkspaceCategoriesPage({route}: WorkspaceCategoriesPageProps) { /> )} + setShowCannotDisableLastCategoryModal(false)} + title={translate('workspace.categories.cannotDisableAllCategories.title')} + prompt={translate('workspace.categories.cannotDisableAllCategories.description')} + confirmText={translate('common.buttonConfirm')} + shouldShowCancelButton={false} + /> + setIsOfflineModalVisible(false)} diff --git a/src/pages/workspace/tags/TagSettingsPage.tsx b/src/pages/workspace/tags/TagSettingsPage.tsx index e312e82bd8c4..238dd2f77891 100644 --- a/src/pages/workspace/tags/TagSettingsPage.tsx +++ b/src/pages/workspace/tags/TagSettingsPage.tsx @@ -1,4 +1,4 @@ -import React, {useEffect, useMemo} from 'react'; +import React, {useEffect, useMemo, useState} from 'react'; import {View} from 'react-native'; import {useOnyx} from 'react-native-onyx'; import ConfirmModal from '@components/ConfirmModal'; @@ -20,8 +20,10 @@ import type {PlatformStackScreenProps} from '@libs/Navigation/PlatformStackNavig import {getPersonalDetailByEmail} from '@libs/PersonalDetailsUtils'; import { getCleanedTagName, + getCountOfEnabledTagsOfList, getTagApproverRule, getTagList, + getTagLists, getWorkflowApprovalsUnavailable, hasAccountingConnections as hasAccountingConnectionsPolicyUtils, isControlPolicy, @@ -40,6 +42,7 @@ type TagSettingsPageProps = PlatformStackScreenProps [getTagLists(policyTags)], [policyTags]); const {orderWeight, policyID, tagName, backTo} = route.params; const styles = useThemeStyles(); const {translate} = useLocalize(); @@ -47,6 +50,7 @@ function TagSettingsPage({route, navigation}: TagSettingsPageProps) { const policy = usePolicy(policyID); const hasAccountingConnections = hasAccountingConnectionsPolicyUtils(policy); const [isDeleteTagModalOpen, setIsDeleteTagModalOpen] = React.useState(false); + const [showCannotDisableLastTagModal, setShowCannotDisableLastTagModal] = useState(false); const isQuickSettingsFlow = !!backTo; const tagApprover = getTagApproverRule(policyID, route.params?.tagName)?.approver ?? ''; const approver = getPersonalDetailByEmail(tagApprover); @@ -71,6 +75,10 @@ function TagSettingsPage({route, navigation}: TagSettingsPageProps) { }; const updateWorkspaceTagEnabled = (value: boolean) => { + if (policy?.requiresTag && getCountOfEnabledTagsOfList(policyTagLists.at(0)?.tags) === 1 && !value) { + setShowCannotDisableLastTagModal(true); + return; + } setWorkspaceTagEnabled(policyID, {[currentPolicyTag.name]: {name: currentPolicyTag.name, enabled: value}}, policyTag.orderWeight); }; @@ -144,6 +152,14 @@ function TagSettingsPage({route, navigation}: TagSettingsPageProps) { cancelText={translate('common.cancel')} danger /> + setShowCannotDisableLastTagModal(false)} + title={translate('workspace.tags.cannotDisableAllTags.title')} + prompt={translate('workspace.tags.cannotDisableAllTags.description')} + confirmText={translate('common.buttonConfirm')} + shouldShowCancelButton={false} + /> diff --git a/src/pages/workspace/tags/WorkspaceTagsPage.tsx b/src/pages/workspace/tags/WorkspaceTagsPage.tsx index 0fd66ee2ebe8..2568d620a0da 100644 --- a/src/pages/workspace/tags/WorkspaceTagsPage.tsx +++ b/src/pages/workspace/tags/WorkspaceTagsPage.tsx @@ -42,6 +42,7 @@ import type {PlatformStackScreenProps} from '@libs/Navigation/PlatformStackNavig import type {WorkspaceSplitNavigatorParamList} from '@libs/Navigation/types'; import { getCleanedTagName, + getCountOfEnabledTagsOfList, getCurrentConnectionName, getTagLists, hasAccountingConnections as hasAccountingConnectionsPolicyUtils, @@ -72,6 +73,7 @@ function WorkspaceTagsPage({route}: WorkspaceTagsPageProps) { const [isDownloadFailureModalVisible, setIsDownloadFailureModalVisible] = useState(false); const [isDeleteTagsConfirmModalVisible, setIsDeleteTagsConfirmModalVisible] = useState(false); const [isOfflineModalVisible, setIsOfflineModalVisible] = useState(false); + const [showCannotDisableLastTagModal, setShowCannotDisableLastTagModal] = useState(false); const policyID = route.params.policyID; const backTo = route.params.backTo; const policy = usePolicy(policyID); @@ -176,11 +178,18 @@ function WorkspaceTagsPage({route}: WorkspaceTagsPageProps) { isOn={tag.enabled} disabled={tag.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE} accessibilityLabel={translate('workspace.tags.enableTag')} - onToggle={(newValue: boolean) => updateWorkspaceTagEnabled(newValue, tag.name)} + onToggle={(newValue: boolean) => { + if (policy?.requiresTag && getCountOfEnabledTagsOfList(policyTagLists.at(0)?.tags) === 1 && !newValue) { + setShowCannotDisableLastTagModal(true); + return; + } + updateWorkspaceTagEnabled(newValue, tag.name); + }} + showLockIcon={getCountOfEnabledTagsOfList(policyTagLists.at(0)?.tags) === 1 && policy?.requiresTag && tag.enabled} /> ), })); - }, [isMultiLevelTags, policyTagLists, selectedTags, canSelectMultiple, translate, updateWorkspaceRequiresTag, updateWorkspaceTagEnabled]); + }, [isMultiLevelTags, policyTagLists, selectedTags, canSelectMultiple, translate, updateWorkspaceRequiresTag, updateWorkspaceTagEnabled, policy?.requiresTag]); const tagListKeyedByName = useMemo( () => @@ -303,11 +312,17 @@ function WorkspaceTagsPage({route}: WorkspaceTagsPageProps) { } if (enabledTagCount > 0) { + const tagsToDisableCount = Object.keys(tagsToDisable).length; + const enabledTagsCount = getCountOfEnabledTagsOfList(policyTagLists.at(0)?.tags); options.push({ icon: Expensicons.Close, text: translate(enabledTagCount === 1 ? 'workspace.tags.disableTag' : 'workspace.tags.disableTags'), value: CONST.POLICY.BULK_ACTION_TYPES.DISABLE, onSelected: () => { + if (tagsToDisableCount === enabledTagsCount && policy?.requiresTag) { + setShowCannotDisableLastTagModal(true); + return; + } setSelectedTags({}); setWorkspaceTagEnabled(policyID, tagsToDisable, 0); }, @@ -488,6 +503,15 @@ function WorkspaceTagsPage({route}: WorkspaceTagsPageProps) { /> )} + setShowCannotDisableLastTagModal(false)} + title={translate('workspace.tags.cannotDisableAllTags.title')} + prompt={translate('workspace.tags.cannotDisableAllTags.description')} + confirmText={translate('common.buttonConfirm')} + shouldShowCancelButton={false} + /> + setIsOfflineModalVisible(false)} From af6af0c2e18e56e4c25b7e61f08c2c72beac63e7 Mon Sep 17 00:00:00 2001 From: Rutika Pawar <183392827+twilight2294@users.noreply.github.com> Date: Sat, 8 Mar 2025 15:36:00 +0000 Subject: [PATCH 02/43] fix lint issues --- src/languages/en.ts | 1 - src/libs/actions/Policy/Category.ts | 2 -- src/libs/actions/Policy/Tag.ts | 1 - src/pages/workspace/tags/WorkspaceTagsPage.tsx | 1 + 4 files changed, 1 insertion(+), 4 deletions(-) diff --git a/src/languages/en.ts b/src/languages/en.ts index b4148fe9910e..0c8ce489718c 100755 --- a/src/languages/en.ts +++ b/src/languages/en.ts @@ -1,6 +1,5 @@ import {CONST as COMMON_CONST} from 'expensify-common'; import startCase from 'lodash/startCase'; -import {title} from 'process'; import CONST from '@src/CONST'; import type {Country} from '@src/CONST'; import type { diff --git a/src/libs/actions/Policy/Category.ts b/src/libs/actions/Policy/Category.ts index ee6312d8c52d..4ef1189fd01a 100644 --- a/src/libs/actions/Policy/Category.ts +++ b/src/libs/actions/Policy/Category.ts @@ -27,7 +27,6 @@ import getIsNarrowLayout from '@libs/getIsNarrowLayout'; import {translateLocal} from '@libs/Localize'; import Log from '@libs/Log'; import enhanceParameters from '@libs/Network/enhanceParameters'; -import {hasEnabledOptions} from '@libs/OptionsListUtils'; import {getPolicy, goBackWhenEnableFeature} from '@libs/PolicyUtils'; import {getAllPolicyReports} from '@libs/ReportUtils'; import CONST from '@src/CONST'; @@ -924,7 +923,6 @@ function clearCategoryErrors(policyID: string, categoryName: string) { } function deleteWorkspaceCategories(policyID: string, categoryNamesToDelete: string[]) { - const policy = allPolicies?.[`${ONYXKEYS.COLLECTION.POLICY}${policyID}`]; const policyCategories = allPolicyCategories?.[`${ONYXKEYS.COLLECTION.POLICY_CATEGORIES}${policyID}`] ?? {}; const optimisticPolicyCategoriesData = categoryNamesToDelete.reduce>>((acc, categoryName) => { acc[categoryName] = {pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE, enabled: false}; diff --git a/src/libs/actions/Policy/Tag.ts b/src/libs/actions/Policy/Tag.ts index e697c7721f60..6b1490050069 100644 --- a/src/libs/actions/Policy/Tag.ts +++ b/src/libs/actions/Policy/Tag.ts @@ -20,7 +20,6 @@ import getIsNarrowLayout from '@libs/getIsNarrowLayout'; import {translateLocal} from '@libs/Localize'; import Log from '@libs/Log'; import enhanceParameters from '@libs/Network/enhanceParameters'; -import * as OptionsListUtils from '@libs/OptionsListUtils'; import * as PolicyUtils from '@libs/PolicyUtils'; import {goBackWhenEnableFeature} from '@libs/PolicyUtils'; import * as ReportUtils from '@libs/ReportUtils'; diff --git a/src/pages/workspace/tags/WorkspaceTagsPage.tsx b/src/pages/workspace/tags/WorkspaceTagsPage.tsx index 2568d620a0da..510aae625d9c 100644 --- a/src/pages/workspace/tags/WorkspaceTagsPage.tsx +++ b/src/pages/workspace/tags/WorkspaceTagsPage.tsx @@ -158,6 +158,7 @@ function WorkspaceTagsPage({route}: WorkspaceTagsPageProps) { accessibilityLabel={translate('workspace.tags.requiresTag')} onToggle={(newValue: boolean) => updateWorkspaceRequiresTag(newValue, policyTagList.orderWeight)} disabled={isSwitchDisabled} + showLockIcon={getCountOfEnabledTagsOfList(policyTagLists.at(0)?.tags) === 1 && policy?.requiresTag && isSwitchEnabled} /> ), }; From 8d4944ae7b4945eb89eb4a8cec0a8071692aa7a4 Mon Sep 17 00:00:00 2001 From: Rutika Pawar <183392827+twilight2294@users.noreply.github.com> Date: Sat, 8 Mar 2025 21:12:04 +0530 Subject: [PATCH 03/43] add missing translation --- src/languages/es.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/languages/es.ts b/src/languages/es.ts index 592f1e1885e2..e1d0d71f165a 100644 --- a/src/languages/es.ts +++ b/src/languages/es.ts @@ -4016,6 +4016,10 @@ const translations = { importTags: 'Importar categorías', importedTagsMessage: ({columnCounts}: ImportedTagsMessageParams) => `Hemos encontrado *${columnCounts} columnas* en su hoja de cálculo. Seleccione *Nombre* junto a la columna que contiene los nombres de las etiquetas. También puede seleccionar *Habilitado* junto a la columna que establece el estado de la etiqueta.`, + cannotDisableAllTags: { + title: 'No se pueden desactivar todas las etiquetas', + description: `No puedes desactivar todas las etiquetas cuando se requieren en el espacio de trabajo.`, + }, }, taxes: { subtitle: 'Añade nombres, tasas y establezca valores por defecto para los impuestos.', From 60949cc62e7eec5cb49533d2b9c15d6382a0b97d Mon Sep 17 00:00:00 2001 From: Rutika Pawar <183392827+twilight2294@users.noreply.github.com> Date: Sat, 8 Mar 2025 17:52:14 +0000 Subject: [PATCH 04/43] add UI tests --- .../categories/CategorySettingsPage.tsx | 1 + .../categories/WorkspaceCategoriesPage.tsx | 1 + src/pages/workspace/tags/TagSettingsPage.tsx | 1 + .../workspace/tags/WorkspaceTagsPage.tsx | 12 +- t.patch | 172 ++++++++++++++++++ tests/ui/WorkspaceCategoriesTest.tsx | 86 +++++++++ tests/ui/WorkspaceTagsTest.tsx | 153 ++++++++++++++++ 7 files changed, 422 insertions(+), 4 deletions(-) create mode 100644 t.patch create mode 100644 tests/ui/WorkspaceTagsTest.tsx diff --git a/src/pages/workspace/categories/CategorySettingsPage.tsx b/src/pages/workspace/categories/CategorySettingsPage.tsx index 88cfad62d43e..bc6ff733d38f 100644 --- a/src/pages/workspace/categories/CategorySettingsPage.tsx +++ b/src/pages/workspace/categories/CategorySettingsPage.tsx @@ -168,6 +168,7 @@ function CategorySettingsPage({ setShowCannotDisableLastCategoryModal(false)} + onCancel={() => setShowCannotDisableLastCategoryModal(false)} title={translate('workspace.categories.cannotDisableAllCategories.title')} prompt={translate('workspace.categories.cannotDisableAllCategories.description')} confirmText={translate('common.buttonConfirm')} diff --git a/src/pages/workspace/categories/WorkspaceCategoriesPage.tsx b/src/pages/workspace/categories/WorkspaceCategoriesPage.tsx index eda82d649867..ad576bc4462c 100644 --- a/src/pages/workspace/categories/WorkspaceCategoriesPage.tsx +++ b/src/pages/workspace/categories/WorkspaceCategoriesPage.tsx @@ -473,6 +473,7 @@ function WorkspaceCategoriesPage({route}: WorkspaceCategoriesPageProps) { setShowCannotDisableLastCategoryModal(false)} + onCancel={() => setShowCannotDisableLastCategoryModal(false)} title={translate('workspace.categories.cannotDisableAllCategories.title')} prompt={translate('workspace.categories.cannotDisableAllCategories.description')} confirmText={translate('common.buttonConfirm')} diff --git a/src/pages/workspace/tags/TagSettingsPage.tsx b/src/pages/workspace/tags/TagSettingsPage.tsx index 238dd2f77891..9328600dff57 100644 --- a/src/pages/workspace/tags/TagSettingsPage.tsx +++ b/src/pages/workspace/tags/TagSettingsPage.tsx @@ -155,6 +155,7 @@ function TagSettingsPage({route, navigation}: TagSettingsPageProps) { setShowCannotDisableLastTagModal(false)} + onCancel={() => setShowCannotDisableLastTagModal(false)} title={translate('workspace.tags.cannotDisableAllTags.title')} prompt={translate('workspace.tags.cannotDisableAllTags.description')} confirmText={translate('common.buttonConfirm')} diff --git a/src/pages/workspace/tags/WorkspaceTagsPage.tsx b/src/pages/workspace/tags/WorkspaceTagsPage.tsx index 510aae625d9c..77cd72ad52d3 100644 --- a/src/pages/workspace/tags/WorkspaceTagsPage.tsx +++ b/src/pages/workspace/tags/WorkspaceTagsPage.tsx @@ -111,12 +111,14 @@ function WorkspaceTagsPage({route}: WorkspaceTagsPageProps) { }); const getPendingAction = (policyTagList: PolicyTagList): PendingAction | undefined => { - if (!policyTagList) { + if (!policyTagList || !policyTagList.tags) { return undefined; } - return (policyTagList.pendingAction as PendingAction) ?? Object.values(policyTagList.tags).some((tag: PolicyTag) => tag.pendingAction) - ? CONST.RED_BRICK_ROAD_PENDING_ACTION.UPDATE - : undefined; + + return ( + (policyTagList.pendingAction as PendingAction) ?? + (Object.values(policyTagList.tags).some((tag: PolicyTag) => tag.pendingAction) ? CONST.RED_BRICK_ROAD_PENDING_ACTION.UPDATE : undefined) + ); }; const updateWorkspaceTagEnabled = useCallback( @@ -353,6 +355,7 @@ function WorkspaceTagsPage({route}: WorkspaceTagsPageProps) { options={options} style={[shouldUseNarrowLayout && styles.flexGrow1, shouldUseNarrowLayout && styles.mb3]} isDisabled={!selectedTagsArray.length} + testID={`${WorkspaceTagsPage.displayName}-header-dropdown-menu-button`} /> ); }; @@ -507,6 +510,7 @@ function WorkspaceTagsPage({route}: WorkspaceTagsPageProps) { setShowCannotDisableLastTagModal(false)} + onCancel={() => setShowCannotDisableLastTagModal(false)} title={translate('workspace.tags.cannotDisableAllTags.title')} prompt={translate('workspace.tags.cannotDisableAllTags.description')} confirmText={translate('common.buttonConfirm')} diff --git a/t.patch b/t.patch new file mode 100644 index 000000000000..a08d6d1c5b69 --- /dev/null +++ b/t.patch @@ -0,0 +1,172 @@ +diff --git a/src/pages/workspace/categories/CategorySettingsPage.tsx b/src/pages/workspace/categories/CategorySettingsPage.tsx +index 88cfad62d43..bc6ff733d38 100644 +--- a/src/pages/workspace/categories/CategorySettingsPage.tsx ++++ b/src/pages/workspace/categories/CategorySettingsPage.tsx +@@ -168,6 +168,7 @@ function CategorySettingsPage({ + setShowCannotDisableLastCategoryModal(false)} ++ onCancel={() => setShowCannotDisableLastCategoryModal(false)} + title={translate('workspace.categories.cannotDisableAllCategories.title')} + prompt={translate('workspace.categories.cannotDisableAllCategories.description')} + confirmText={translate('common.buttonConfirm')} +diff --git a/src/pages/workspace/categories/WorkspaceCategoriesPage.tsx b/src/pages/workspace/categories/WorkspaceCategoriesPage.tsx +index eda82d64986..ad576bc4462 100644 +--- a/src/pages/workspace/categories/WorkspaceCategoriesPage.tsx ++++ b/src/pages/workspace/categories/WorkspaceCategoriesPage.tsx +@@ -473,6 +473,7 @@ function WorkspaceCategoriesPage({route}: WorkspaceCategoriesPageProps) { + setShowCannotDisableLastCategoryModal(false)} ++ onCancel={() => setShowCannotDisableLastCategoryModal(false)} + title={translate('workspace.categories.cannotDisableAllCategories.title')} + prompt={translate('workspace.categories.cannotDisableAllCategories.description')} + confirmText={translate('common.buttonConfirm')} +diff --git a/src/pages/workspace/tags/TagSettingsPage.tsx b/src/pages/workspace/tags/TagSettingsPage.tsx +index 238dd2f7789..9328600dff5 100644 +--- a/src/pages/workspace/tags/TagSettingsPage.tsx ++++ b/src/pages/workspace/tags/TagSettingsPage.tsx +@@ -155,6 +155,7 @@ function TagSettingsPage({route, navigation}: TagSettingsPageProps) { + setShowCannotDisableLastTagModal(false)} ++ onCancel={() => setShowCannotDisableLastTagModal(false)} + title={translate('workspace.tags.cannotDisableAllTags.title')} + prompt={translate('workspace.tags.cannotDisableAllTags.description')} + confirmText={translate('common.buttonConfirm')} +diff --git a/src/pages/workspace/tags/WorkspaceTagsPage.tsx b/src/pages/workspace/tags/WorkspaceTagsPage.tsx +index 510aae625d9..77cd72ad52d 100644 +--- a/src/pages/workspace/tags/WorkspaceTagsPage.tsx ++++ b/src/pages/workspace/tags/WorkspaceTagsPage.tsx +@@ -111,12 +111,14 @@ function WorkspaceTagsPage({route}: WorkspaceTagsPageProps) { + }); + + const getPendingAction = (policyTagList: PolicyTagList): PendingAction | undefined => { +- if (!policyTagList) { ++ if (!policyTagList || !policyTagList.tags) { + return undefined; + } +- return (policyTagList.pendingAction as PendingAction) ?? Object.values(policyTagList.tags).some((tag: PolicyTag) => tag.pendingAction) +- ? CONST.RED_BRICK_ROAD_PENDING_ACTION.UPDATE +- : undefined; ++ ++ return ( ++ (policyTagList.pendingAction as PendingAction) ?? ++ (Object.values(policyTagList.tags).some((tag: PolicyTag) => tag.pendingAction) ? CONST.RED_BRICK_ROAD_PENDING_ACTION.UPDATE : undefined) ++ ); + }; + + const updateWorkspaceTagEnabled = useCallback( +@@ -353,6 +355,7 @@ function WorkspaceTagsPage({route}: WorkspaceTagsPageProps) { + options={options} + style={[shouldUseNarrowLayout && styles.flexGrow1, shouldUseNarrowLayout && styles.mb3]} + isDisabled={!selectedTagsArray.length} ++ testID={`${WorkspaceTagsPage.displayName}-header-dropdown-menu-button`} + /> + ); + }; +@@ -507,6 +510,7 @@ function WorkspaceTagsPage({route}: WorkspaceTagsPageProps) { + setShowCannotDisableLastTagModal(false)} ++ onCancel={() => setShowCannotDisableLastTagModal(false)} + title={translate('workspace.tags.cannotDisableAllTags.title')} + prompt={translate('workspace.tags.cannotDisableAllTags.description')} + confirmText={translate('common.buttonConfirm')} +diff --git a/tests/ui/WorkspaceCategoriesTest.tsx b/tests/ui/WorkspaceCategoriesTest.tsx +index cdcba7295c0..267807f22a4 100644 +--- a/tests/ui/WorkspaceCategoriesTest.tsx ++++ b/tests/ui/WorkspaceCategoriesTest.tsx +@@ -168,6 +168,92 @@ describe('WorkspaceCategories', () => { + expect(screen.queryByText(SECOND_CATEGORY)).not.toBeOnTheScreen(); + }); + ++ unmount(); ++ await waitForBatchedUpdatesWithAct(); ++ }); ++ it('should show a blocking modal when trying to disable the only enabled category when policy has requiresCategory set to true', async () => { ++ await TestHelper.signInWithTestUser(); ++ ++ const policy = { ++ ...LHNTestUtils.getFakePolicy(), ++ role: CONST.POLICY.ROLE.ADMIN, ++ areCategoriesEnabled: true, ++ requiresCategory: true, ++ }; ++ ++ const categories = { ++ [FIRST_CATEGORY]: { ++ name: FIRST_CATEGORY, ++ enabled: true, ++ }, ++ [SECOND_CATEGORY]: { ++ name: SECOND_CATEGORY, ++ enabled: true, ++ }, ++ }; ++ ++ // Initialize categories ++ await act(async () => { ++ await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${policy.id}`, policy); ++ await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY_CATEGORIES}${policy.id}`, categories); ++ }); ++ ++ const {unmount} = renderPage(SCREENS.WORKSPACE.CATEGORIES, {policyID: policy.id}); ++ ++ await waitForBatchedUpdatesWithAct(); ++ ++ // Wait for initial render and verify categories are visible ++ await waitFor(() => { ++ expect(screen.getByText(FIRST_CATEGORY)).toBeOnTheScreen(); ++ }); ++ await waitFor(() => { ++ expect(screen.getByText(SECOND_CATEGORY)).toBeOnTheScreen(); ++ }); ++ ++ // Select categories to delete by clicking their checkboxes ++ fireEvent.press(screen.getByTestId(`TableListItemCheckbox-${FIRST_CATEGORY}`)); ++ fireEvent.press(screen.getByTestId(`TableListItemCheckbox-${SECOND_CATEGORY}`)); ++ ++ const dropdownMenuButtonTestID = `${WorkspaceCategoriesPage.displayName}-header-dropdown-menu-button`; ++ ++ // Wait for selection mode to be active and click the dropdown menu button ++ await waitFor(() => { ++ expect(screen.getByTestId(dropdownMenuButtonTestID)).toBeOnTheScreen(); ++ }); ++ ++ // Click the "2 selected" button to open the menu ++ const dropdownButton = screen.getByTestId(dropdownMenuButtonTestID); ++ fireEvent.press(dropdownButton); ++ ++ await waitForBatchedUpdatesWithAct(); ++ ++ // Wait for menu items to be visible ++ await waitFor(() => { ++ const disableText = Localize.translateLocal('workspace.categories.disableCategories'); ++ expect(screen.getByText(disableText)).toBeOnTheScreen(); ++ }); ++ ++ // Find and verify "Disable categories" dropdown menu item ++ const disableMenuItem = screen.getByTestId('PopoverMenuItem-Disable categories'); ++ expect(disableMenuItem).toBeOnTheScreen(); ++ ++ // Create a mock event object that matches GestureResponderEvent. Needed for onPress in MenuItem to be called ++ const mockEvent = { ++ nativeEvent: {}, ++ type: 'press', ++ target: disableMenuItem, ++ currentTarget: disableMenuItem, ++ }; ++ fireEvent.press(disableMenuItem, mockEvent); ++ ++ await waitForBatchedUpdatesWithAct(); ++ ++ // After clicking disable categories dropdown menu item, verify the blocking modal appears ++ await waitFor(() => { ++ const blockingPrompt = Localize.translateLocal('workspace.categories.cannotDisableAllCategories.title'); ++ expect(screen.getByText(blockingPrompt)).toBeOnTheScreen(); ++ }); ++ + unmount(); + await waitForBatchedUpdatesWithAct(); + }); diff --git a/tests/ui/WorkspaceCategoriesTest.tsx b/tests/ui/WorkspaceCategoriesTest.tsx index cdcba7295c0e..267807f22a4a 100644 --- a/tests/ui/WorkspaceCategoriesTest.tsx +++ b/tests/ui/WorkspaceCategoriesTest.tsx @@ -168,6 +168,92 @@ describe('WorkspaceCategories', () => { expect(screen.queryByText(SECOND_CATEGORY)).not.toBeOnTheScreen(); }); + unmount(); + await waitForBatchedUpdatesWithAct(); + }); + it('should show a blocking modal when trying to disable the only enabled category when policy has requiresCategory set to true', async () => { + await TestHelper.signInWithTestUser(); + + const policy = { + ...LHNTestUtils.getFakePolicy(), + role: CONST.POLICY.ROLE.ADMIN, + areCategoriesEnabled: true, + requiresCategory: true, + }; + + const categories = { + [FIRST_CATEGORY]: { + name: FIRST_CATEGORY, + enabled: true, + }, + [SECOND_CATEGORY]: { + name: SECOND_CATEGORY, + enabled: true, + }, + }; + + // Initialize categories + await act(async () => { + await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${policy.id}`, policy); + await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY_CATEGORIES}${policy.id}`, categories); + }); + + const {unmount} = renderPage(SCREENS.WORKSPACE.CATEGORIES, {policyID: policy.id}); + + await waitForBatchedUpdatesWithAct(); + + // Wait for initial render and verify categories are visible + await waitFor(() => { + expect(screen.getByText(FIRST_CATEGORY)).toBeOnTheScreen(); + }); + await waitFor(() => { + expect(screen.getByText(SECOND_CATEGORY)).toBeOnTheScreen(); + }); + + // Select categories to delete by clicking their checkboxes + fireEvent.press(screen.getByTestId(`TableListItemCheckbox-${FIRST_CATEGORY}`)); + fireEvent.press(screen.getByTestId(`TableListItemCheckbox-${SECOND_CATEGORY}`)); + + const dropdownMenuButtonTestID = `${WorkspaceCategoriesPage.displayName}-header-dropdown-menu-button`; + + // Wait for selection mode to be active and click the dropdown menu button + await waitFor(() => { + expect(screen.getByTestId(dropdownMenuButtonTestID)).toBeOnTheScreen(); + }); + + // Click the "2 selected" button to open the menu + const dropdownButton = screen.getByTestId(dropdownMenuButtonTestID); + fireEvent.press(dropdownButton); + + await waitForBatchedUpdatesWithAct(); + + // Wait for menu items to be visible + await waitFor(() => { + const disableText = Localize.translateLocal('workspace.categories.disableCategories'); + expect(screen.getByText(disableText)).toBeOnTheScreen(); + }); + + // Find and verify "Disable categories" dropdown menu item + const disableMenuItem = screen.getByTestId('PopoverMenuItem-Disable categories'); + expect(disableMenuItem).toBeOnTheScreen(); + + // Create a mock event object that matches GestureResponderEvent. Needed for onPress in MenuItem to be called + const mockEvent = { + nativeEvent: {}, + type: 'press', + target: disableMenuItem, + currentTarget: disableMenuItem, + }; + fireEvent.press(disableMenuItem, mockEvent); + + await waitForBatchedUpdatesWithAct(); + + // After clicking disable categories dropdown menu item, verify the blocking modal appears + await waitFor(() => { + const blockingPrompt = Localize.translateLocal('workspace.categories.cannotDisableAllCategories.title'); + expect(screen.getByText(blockingPrompt)).toBeOnTheScreen(); + }); + unmount(); await waitForBatchedUpdatesWithAct(); }); diff --git a/tests/ui/WorkspaceTagsTest.tsx b/tests/ui/WorkspaceTagsTest.tsx new file mode 100644 index 000000000000..c410929550cd --- /dev/null +++ b/tests/ui/WorkspaceTagsTest.tsx @@ -0,0 +1,153 @@ +import {PortalProvider} from '@gorhom/portal'; +import {NavigationContainer} from '@react-navigation/native'; +import {act, fireEvent, render, screen, waitFor} from '@testing-library/react-native'; +import React from 'react'; +import Onyx from 'react-native-onyx'; +import ComposeProviders from '@components/ComposeProviders'; +import {LocaleContextProvider} from '@components/LocaleContextProvider'; +import OnyxProvider from '@components/OnyxProvider'; +import {CurrentReportIDContextProvider} from '@hooks/useCurrentReportID'; +import * as useResponsiveLayoutModule from '@hooks/useResponsiveLayout'; +import type ResponsiveLayoutResult from '@hooks/useResponsiveLayout/types'; +import * as Localize from '@libs/Localize'; +import createPlatformStackNavigator from '@libs/Navigation/PlatformStackNavigation/createPlatformStackNavigator'; +import type {WorkspaceSplitNavigatorParamList} from '@navigation/types'; +import WorkspaceTagsPage from '@pages/workspace/tags/WorkspaceTagsPage'; +import CONST from '@src/CONST'; +import ONYXKEYS from '@src/ONYXKEYS'; +import SCREENS from '@src/SCREENS'; +import * as LHNTestUtils from '../utils/LHNTestUtils'; +import * as TestHelper from '../utils/TestHelper'; +import waitForBatchedUpdatesWithAct from '../utils/waitForBatchedUpdatesWithAct'; + +TestHelper.setupGlobalFetchMock(); + +const Stack = createPlatformStackNavigator(); + +const renderPage = (initialRouteName: typeof SCREENS.WORKSPACE.TAGS, initialParams: WorkspaceSplitNavigatorParamList[typeof SCREENS.WORKSPACE.TAGS]) => { + return render( + + + + + + + + + , + ); +}; + +describe('WorkspaceTags', () => { + const FIRST_TAG = 'tagOne'; + const SECOND_TAG = 'tagTwo'; + + beforeAll(() => { + Onyx.init({ + keys: ONYXKEYS, + }); + }); + + beforeEach(() => { + jest.spyOn(useResponsiveLayoutModule, 'default').mockReturnValue({ + isSmallScreenWidth: false, + shouldUseNarrowLayout: false, + } as ResponsiveLayoutResult); + }); + + afterEach(async () => { + await act(async () => { + await Onyx.clear(); + }); + jest.clearAllMocks(); + }); + + it('should show a blocking modal when trying to disable the only enabled tag when policy has requiresTag set to true', async () => { + await TestHelper.signInWithTestUser(); + + const policy = { + ...LHNTestUtils.getFakePolicy(), + role: CONST.POLICY.ROLE.ADMIN, + areTagsEnabled: true, + requiresTag: true, + }; + + const tags = { + TagListOne: { + name: 'TagListOne', + required: true, + orderWeight: 1, + tags: { + [FIRST_TAG]: { + name: FIRST_TAG, + enabled: true, + }, + [SECOND_TAG]: { + name: SECOND_TAG, + enabled: true, + }, + }, + }, + }; + + await act(async () => { + await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${policy.id}`, policy); + await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY_TAGS}${policy.id}`, tags); + }); + + const {unmount} = renderPage(SCREENS.WORKSPACE.TAGS, {policyID: policy.id}); + + await waitForBatchedUpdatesWithAct(); + + await waitFor(() => { + expect(screen.getByText(FIRST_TAG)).toBeOnTheScreen(); + }); + await waitFor(() => { + expect(screen.getByText(SECOND_TAG)).toBeOnTheScreen(); + }); + + fireEvent.press(screen.getByTestId(`TableListItemCheckbox-${FIRST_TAG}`)); + fireEvent.press(screen.getByTestId(`TableListItemCheckbox-${SECOND_TAG}`)); + + const dropdownMenuButtonTestID = `${WorkspaceTagsPage.displayName}-header-dropdown-menu-button`; + + await waitFor(() => { + expect(screen.getByTestId(dropdownMenuButtonTestID)).toBeOnTheScreen(); + }); + + const dropdownButton = screen.getByTestId(dropdownMenuButtonTestID); + fireEvent.press(dropdownButton); + + await waitForBatchedUpdatesWithAct(); + + await waitFor(() => { + const disableText = Localize.translateLocal('workspace.tags.disableTags'); + expect(screen.getByText(disableText)).toBeOnTheScreen(); + }); + + const disableMenuItem = screen.getByTestId('PopoverMenuItem-Disable tags'); + expect(disableMenuItem).toBeOnTheScreen(); + + const mockEvent = { + nativeEvent: {}, + type: 'press', + target: disableMenuItem, + currentTarget: disableMenuItem, + }; + fireEvent.press(disableMenuItem, mockEvent); + + await waitForBatchedUpdatesWithAct(); + + await waitFor(() => { + const blockingPrompt = Localize.translateLocal('workspace.tags.cannotDisableAllTags.title'); + expect(screen.getByText(blockingPrompt)).toBeOnTheScreen(); + }); + + unmount(); + await waitForBatchedUpdatesWithAct(); + }); +}); From bba68c88dc3c14157c5cde4108fefc6e4e124c5b Mon Sep 17 00:00:00 2001 From: Rutika Pawar <183392827+twilight2294@users.noreply.github.com> Date: Sat, 8 Mar 2025 23:23:09 +0530 Subject: [PATCH 05/43] remove patch file --- t.patch | 172 -------------------------------------------------------- 1 file changed, 172 deletions(-) delete mode 100644 t.patch diff --git a/t.patch b/t.patch deleted file mode 100644 index a08d6d1c5b69..000000000000 --- a/t.patch +++ /dev/null @@ -1,172 +0,0 @@ -diff --git a/src/pages/workspace/categories/CategorySettingsPage.tsx b/src/pages/workspace/categories/CategorySettingsPage.tsx -index 88cfad62d43..bc6ff733d38 100644 ---- a/src/pages/workspace/categories/CategorySettingsPage.tsx -+++ b/src/pages/workspace/categories/CategorySettingsPage.tsx -@@ -168,6 +168,7 @@ function CategorySettingsPage({ - setShowCannotDisableLastCategoryModal(false)} -+ onCancel={() => setShowCannotDisableLastCategoryModal(false)} - title={translate('workspace.categories.cannotDisableAllCategories.title')} - prompt={translate('workspace.categories.cannotDisableAllCategories.description')} - confirmText={translate('common.buttonConfirm')} -diff --git a/src/pages/workspace/categories/WorkspaceCategoriesPage.tsx b/src/pages/workspace/categories/WorkspaceCategoriesPage.tsx -index eda82d64986..ad576bc4462 100644 ---- a/src/pages/workspace/categories/WorkspaceCategoriesPage.tsx -+++ b/src/pages/workspace/categories/WorkspaceCategoriesPage.tsx -@@ -473,6 +473,7 @@ function WorkspaceCategoriesPage({route}: WorkspaceCategoriesPageProps) { - setShowCannotDisableLastCategoryModal(false)} -+ onCancel={() => setShowCannotDisableLastCategoryModal(false)} - title={translate('workspace.categories.cannotDisableAllCategories.title')} - prompt={translate('workspace.categories.cannotDisableAllCategories.description')} - confirmText={translate('common.buttonConfirm')} -diff --git a/src/pages/workspace/tags/TagSettingsPage.tsx b/src/pages/workspace/tags/TagSettingsPage.tsx -index 238dd2f7789..9328600dff5 100644 ---- a/src/pages/workspace/tags/TagSettingsPage.tsx -+++ b/src/pages/workspace/tags/TagSettingsPage.tsx -@@ -155,6 +155,7 @@ function TagSettingsPage({route, navigation}: TagSettingsPageProps) { - setShowCannotDisableLastTagModal(false)} -+ onCancel={() => setShowCannotDisableLastTagModal(false)} - title={translate('workspace.tags.cannotDisableAllTags.title')} - prompt={translate('workspace.tags.cannotDisableAllTags.description')} - confirmText={translate('common.buttonConfirm')} -diff --git a/src/pages/workspace/tags/WorkspaceTagsPage.tsx b/src/pages/workspace/tags/WorkspaceTagsPage.tsx -index 510aae625d9..77cd72ad52d 100644 ---- a/src/pages/workspace/tags/WorkspaceTagsPage.tsx -+++ b/src/pages/workspace/tags/WorkspaceTagsPage.tsx -@@ -111,12 +111,14 @@ function WorkspaceTagsPage({route}: WorkspaceTagsPageProps) { - }); - - const getPendingAction = (policyTagList: PolicyTagList): PendingAction | undefined => { -- if (!policyTagList) { -+ if (!policyTagList || !policyTagList.tags) { - return undefined; - } -- return (policyTagList.pendingAction as PendingAction) ?? Object.values(policyTagList.tags).some((tag: PolicyTag) => tag.pendingAction) -- ? CONST.RED_BRICK_ROAD_PENDING_ACTION.UPDATE -- : undefined; -+ -+ return ( -+ (policyTagList.pendingAction as PendingAction) ?? -+ (Object.values(policyTagList.tags).some((tag: PolicyTag) => tag.pendingAction) ? CONST.RED_BRICK_ROAD_PENDING_ACTION.UPDATE : undefined) -+ ); - }; - - const updateWorkspaceTagEnabled = useCallback( -@@ -353,6 +355,7 @@ function WorkspaceTagsPage({route}: WorkspaceTagsPageProps) { - options={options} - style={[shouldUseNarrowLayout && styles.flexGrow1, shouldUseNarrowLayout && styles.mb3]} - isDisabled={!selectedTagsArray.length} -+ testID={`${WorkspaceTagsPage.displayName}-header-dropdown-menu-button`} - /> - ); - }; -@@ -507,6 +510,7 @@ function WorkspaceTagsPage({route}: WorkspaceTagsPageProps) { - setShowCannotDisableLastTagModal(false)} -+ onCancel={() => setShowCannotDisableLastTagModal(false)} - title={translate('workspace.tags.cannotDisableAllTags.title')} - prompt={translate('workspace.tags.cannotDisableAllTags.description')} - confirmText={translate('common.buttonConfirm')} -diff --git a/tests/ui/WorkspaceCategoriesTest.tsx b/tests/ui/WorkspaceCategoriesTest.tsx -index cdcba7295c0..267807f22a4 100644 ---- a/tests/ui/WorkspaceCategoriesTest.tsx -+++ b/tests/ui/WorkspaceCategoriesTest.tsx -@@ -168,6 +168,92 @@ describe('WorkspaceCategories', () => { - expect(screen.queryByText(SECOND_CATEGORY)).not.toBeOnTheScreen(); - }); - -+ unmount(); -+ await waitForBatchedUpdatesWithAct(); -+ }); -+ it('should show a blocking modal when trying to disable the only enabled category when policy has requiresCategory set to true', async () => { -+ await TestHelper.signInWithTestUser(); -+ -+ const policy = { -+ ...LHNTestUtils.getFakePolicy(), -+ role: CONST.POLICY.ROLE.ADMIN, -+ areCategoriesEnabled: true, -+ requiresCategory: true, -+ }; -+ -+ const categories = { -+ [FIRST_CATEGORY]: { -+ name: FIRST_CATEGORY, -+ enabled: true, -+ }, -+ [SECOND_CATEGORY]: { -+ name: SECOND_CATEGORY, -+ enabled: true, -+ }, -+ }; -+ -+ // Initialize categories -+ await act(async () => { -+ await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${policy.id}`, policy); -+ await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY_CATEGORIES}${policy.id}`, categories); -+ }); -+ -+ const {unmount} = renderPage(SCREENS.WORKSPACE.CATEGORIES, {policyID: policy.id}); -+ -+ await waitForBatchedUpdatesWithAct(); -+ -+ // Wait for initial render and verify categories are visible -+ await waitFor(() => { -+ expect(screen.getByText(FIRST_CATEGORY)).toBeOnTheScreen(); -+ }); -+ await waitFor(() => { -+ expect(screen.getByText(SECOND_CATEGORY)).toBeOnTheScreen(); -+ }); -+ -+ // Select categories to delete by clicking their checkboxes -+ fireEvent.press(screen.getByTestId(`TableListItemCheckbox-${FIRST_CATEGORY}`)); -+ fireEvent.press(screen.getByTestId(`TableListItemCheckbox-${SECOND_CATEGORY}`)); -+ -+ const dropdownMenuButtonTestID = `${WorkspaceCategoriesPage.displayName}-header-dropdown-menu-button`; -+ -+ // Wait for selection mode to be active and click the dropdown menu button -+ await waitFor(() => { -+ expect(screen.getByTestId(dropdownMenuButtonTestID)).toBeOnTheScreen(); -+ }); -+ -+ // Click the "2 selected" button to open the menu -+ const dropdownButton = screen.getByTestId(dropdownMenuButtonTestID); -+ fireEvent.press(dropdownButton); -+ -+ await waitForBatchedUpdatesWithAct(); -+ -+ // Wait for menu items to be visible -+ await waitFor(() => { -+ const disableText = Localize.translateLocal('workspace.categories.disableCategories'); -+ expect(screen.getByText(disableText)).toBeOnTheScreen(); -+ }); -+ -+ // Find and verify "Disable categories" dropdown menu item -+ const disableMenuItem = screen.getByTestId('PopoverMenuItem-Disable categories'); -+ expect(disableMenuItem).toBeOnTheScreen(); -+ -+ // Create a mock event object that matches GestureResponderEvent. Needed for onPress in MenuItem to be called -+ const mockEvent = { -+ nativeEvent: {}, -+ type: 'press', -+ target: disableMenuItem, -+ currentTarget: disableMenuItem, -+ }; -+ fireEvent.press(disableMenuItem, mockEvent); -+ -+ await waitForBatchedUpdatesWithAct(); -+ -+ // After clicking disable categories dropdown menu item, verify the blocking modal appears -+ await waitFor(() => { -+ const blockingPrompt = Localize.translateLocal('workspace.categories.cannotDisableAllCategories.title'); -+ expect(screen.getByText(blockingPrompt)).toBeOnTheScreen(); -+ }); -+ - unmount(); - await waitForBatchedUpdatesWithAct(); - }); From bdc97056cdf3a13399c1ac9098f9523e006eb54f Mon Sep 17 00:00:00 2001 From: Rutika Pawar <183392827+twilight2294@users.noreply.github.com> Date: Sat, 8 Mar 2025 18:00:56 +0000 Subject: [PATCH 06/43] fix named imports --- src/pages/workspace/tags/WorkspaceTagsPage.tsx | 2 +- tests/ui/WorkspaceCategoriesTest.tsx | 14 +++++++------- tests/ui/WorkspaceTagsTest.tsx | 6 +++--- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/pages/workspace/tags/WorkspaceTagsPage.tsx b/src/pages/workspace/tags/WorkspaceTagsPage.tsx index 77cd72ad52d3..be44fcfd15a8 100644 --- a/src/pages/workspace/tags/WorkspaceTagsPage.tsx +++ b/src/pages/workspace/tags/WorkspaceTagsPage.tsx @@ -111,7 +111,7 @@ function WorkspaceTagsPage({route}: WorkspaceTagsPageProps) { }); const getPendingAction = (policyTagList: PolicyTagList): PendingAction | undefined => { - if (!policyTagList || !policyTagList.tags) { + if (!policyTagList ?? !policyTagList.tags) { return undefined; } diff --git a/tests/ui/WorkspaceCategoriesTest.tsx b/tests/ui/WorkspaceCategoriesTest.tsx index 267807f22a4a..11f3d799a900 100644 --- a/tests/ui/WorkspaceCategoriesTest.tsx +++ b/tests/ui/WorkspaceCategoriesTest.tsx @@ -9,7 +9,7 @@ import OnyxProvider from '@components/OnyxProvider'; import {CurrentReportIDContextProvider} from '@hooks/useCurrentReportID'; import * as useResponsiveLayoutModule from '@hooks/useResponsiveLayout'; import type ResponsiveLayoutResult from '@hooks/useResponsiveLayout/types'; -import * as Localize from '@libs/Localize'; +import {translateLocal} from '@libs/Localize'; import createPlatformStackNavigator from '@libs/Navigation/PlatformStackNavigation/createPlatformStackNavigator'; import type {WorkspaceSplitNavigatorParamList} from '@navigation/types'; import WorkspaceCategoriesPage from '@pages/workspace/categories/WorkspaceCategoriesPage'; @@ -123,7 +123,7 @@ describe('WorkspaceCategories', () => { // Wait for menu items to be visible await waitFor(() => { - const deleteText = Localize.translateLocal('workspace.categories.deleteCategories'); + const deleteText = translateLocal('workspace.categories.deleteCategories'); expect(screen.getByText(deleteText)).toBeOnTheScreen(); }); @@ -144,18 +144,18 @@ describe('WorkspaceCategories', () => { // After clicking delete categories dropdown menu item, verify the confirmation modal appears await waitFor(() => { - const confirmModalPrompt = Localize.translateLocal('workspace.categories.deleteCategoriesPrompt'); + const confirmModalPrompt = translateLocal('workspace.categories.deleteCategoriesPrompt'); expect(screen.getByText(confirmModalPrompt)).toBeOnTheScreen(); }); // Verify the delete button in the modal is visible await waitFor(() => { - const deleteConfirmButton = screen.getByLabelText(Localize.translateLocal('common.delete')); + const deleteConfirmButton = screen.getByLabelText(translateLocal('common.delete')); expect(deleteConfirmButton).toBeOnTheScreen(); }); // Click the delete button in the confirmation modal - const deleteConfirmButton = screen.getByLabelText(Localize.translateLocal('common.delete')); + const deleteConfirmButton = screen.getByLabelText(translateLocal('common.delete')); fireEvent.press(deleteConfirmButton); await waitForBatchedUpdatesWithAct(); @@ -229,7 +229,7 @@ describe('WorkspaceCategories', () => { // Wait for menu items to be visible await waitFor(() => { - const disableText = Localize.translateLocal('workspace.categories.disableCategories'); + const disableText = translateLocal('workspace.categories.disableCategories'); expect(screen.getByText(disableText)).toBeOnTheScreen(); }); @@ -250,7 +250,7 @@ describe('WorkspaceCategories', () => { // After clicking disable categories dropdown menu item, verify the blocking modal appears await waitFor(() => { - const blockingPrompt = Localize.translateLocal('workspace.categories.cannotDisableAllCategories.title'); + const blockingPrompt = translateLocal('workspace.categories.cannotDisableAllCategories.title'); expect(screen.getByText(blockingPrompt)).toBeOnTheScreen(); }); diff --git a/tests/ui/WorkspaceTagsTest.tsx b/tests/ui/WorkspaceTagsTest.tsx index c410929550cd..8fd3780fb066 100644 --- a/tests/ui/WorkspaceTagsTest.tsx +++ b/tests/ui/WorkspaceTagsTest.tsx @@ -9,7 +9,7 @@ import OnyxProvider from '@components/OnyxProvider'; import {CurrentReportIDContextProvider} from '@hooks/useCurrentReportID'; import * as useResponsiveLayoutModule from '@hooks/useResponsiveLayout'; import type ResponsiveLayoutResult from '@hooks/useResponsiveLayout/types'; -import * as Localize from '@libs/Localize'; +import {translateLocal} from '@libs/Localize'; import createPlatformStackNavigator from '@libs/Navigation/PlatformStackNavigation/createPlatformStackNavigator'; import type {WorkspaceSplitNavigatorParamList} from '@navigation/types'; import WorkspaceTagsPage from '@pages/workspace/tags/WorkspaceTagsPage'; @@ -125,7 +125,7 @@ describe('WorkspaceTags', () => { await waitForBatchedUpdatesWithAct(); await waitFor(() => { - const disableText = Localize.translateLocal('workspace.tags.disableTags'); + const disableText = translateLocal('workspace.tags.disableTags'); expect(screen.getByText(disableText)).toBeOnTheScreen(); }); @@ -143,7 +143,7 @@ describe('WorkspaceTags', () => { await waitForBatchedUpdatesWithAct(); await waitFor(() => { - const blockingPrompt = Localize.translateLocal('workspace.tags.cannotDisableAllTags.title'); + const blockingPrompt = translateLocal('workspace.tags.cannotDisableAllTags.title'); expect(screen.getByText(blockingPrompt)).toBeOnTheScreen(); }); From 49551236f7507386d1e4b40f8786811c39fe2b18 Mon Sep 17 00:00:00 2001 From: Rutika Pawar <183392827+twilight2294@users.noreply.github.com> Date: Thu, 20 Mar 2025 14:10:20 +0000 Subject: [PATCH 07/43] update categories page after review comments --- .../categories/CategorySettingsPage.tsx | 19 ++++++++++--------- .../categories/WorkspaceCategoriesPage.tsx | 10 +++++----- 2 files changed, 15 insertions(+), 14 deletions(-) diff --git a/src/pages/workspace/categories/CategorySettingsPage.tsx b/src/pages/workspace/categories/CategorySettingsPage.tsx index bc6ff733d38f..9847b2287705 100644 --- a/src/pages/workspace/categories/CategorySettingsPage.tsx +++ b/src/pages/workspace/categories/CategorySettingsPage.tsx @@ -56,9 +56,10 @@ function CategorySettingsPage({ const policyCurrency = policy?.outputCurrency ?? CONST.CURRENCY.USD; const policyCategoryExpenseLimitType = policyCategory?.expenseLimitType ?? CONST.POLICY.EXPENSE_LIMIT_TYPES.EXPENSE; - const [showCannotDisableLastCategoryModal, setShowCannotDisableLastCategoryModal] = useState(false); + const [isCannotDisableLastCategoryModalVisible, setIsCannotDisableLastCategoryModalVisible] = useState(false); const areCommentsRequired = policyCategory?.areCommentsRequired ?? false; const isQuickSettingsFlow = !!backTo; + const shouldPreventDisable = policyCategory?.enabled && policy?.requiresCategory && getEnabledCategoriesCount(policyCategories) === 1; const navigateBack = () => { Navigation.goBack(isQuickSettingsFlow ? ROUTES.SETTINGS_CATEGORIES_ROOT.getRoute(policyID, backTo) : undefined); @@ -114,9 +115,9 @@ function CategorySettingsPage({ return ; } - const updateWorkspaceRequiresCategory = (value: boolean) => { - if (policy?.requiresCategory && getEnabledCategoriesCount(policyCategories) === 1 && !value) { - setShowCannotDisableLastCategoryModal(true); + const updateWorkspaceCategoryEnabled = (value: boolean) => { + if (shouldPreventDisable && !value) { + setIsCannotDisableLastCategoryModalVisible(true); return; } setWorkspaceCategoryEnabled(policyID, {[policyCategory.name]: {name: policyCategory.name, enabled: value}}); @@ -166,9 +167,9 @@ function CategorySettingsPage({ danger /> setShowCannotDisableLastCategoryModal(false)} - onCancel={() => setShowCannotDisableLastCategoryModal(false)} + isVisible={isCannotDisableLastCategoryModalVisible} + onConfirm={() => setIsCannotDisableLastCategoryModalVisible(false)} + onCancel={() => setIsCannotDisableLastCategoryModalVisible(false)} title={translate('workspace.categories.cannotDisableAllCategories.title')} prompt={translate('workspace.categories.cannotDisableAllCategories.description')} confirmText={translate('common.buttonConfirm')} @@ -187,8 +188,8 @@ function CategorySettingsPage({ diff --git a/src/pages/workspace/categories/WorkspaceCategoriesPage.tsx b/src/pages/workspace/categories/WorkspaceCategoriesPage.tsx index ad576bc4462c..e5afaaed8e70 100644 --- a/src/pages/workspace/categories/WorkspaceCategoriesPage.tsx +++ b/src/pages/workspace/categories/WorkspaceCategoriesPage.tsx @@ -84,7 +84,7 @@ function WorkspaceCategoriesPage({route}: WorkspaceCategoriesPageProps) { const isConnectedToAccounting = Object.keys(policy?.connections ?? {}).length > 0; const currentConnectionName = getCurrentConnectionName(policy); const isQuickSettingsFlow = !!backTo; - + const shouldPreventDisable = getEnabledCategoriesCount(policyCategories) === 1 && policy?.requiresCategory; const canSelectMultiple = isSmallScreenWidth ? selectionMode?.isEnabled : true; const fetchCategories = useCallback(() => { @@ -107,7 +107,7 @@ function WorkspaceCategoriesPage({route}: WorkspaceCategoriesPageProps) { onNavigationCallBack: () => Navigation.goBack(backTo), }); - const updateWorkspaceRequiresCategory = useCallback( + const updateWorkspaceCategoryEnabled = useCallback( (value: boolean, categoryName: string) => { setWorkspaceCategoryEnabled(policyId, {[categoryName]: {name: categoryName, enabled: value}}); }, @@ -140,16 +140,16 @@ function WorkspaceCategoriesPage({route}: WorkspaceCategoriesPageProps) { setShowCannotDisableLastCategoryModal(true); return; } - updateWorkspaceRequiresCategory(newValue, value.name); + updateWorkspaceCategoryEnabled(newValue, value.name); }} - showLockIcon={getEnabledCategoriesCount(policyCategories) === 1 && policy?.requiresCategory && value.enabled} + showLockIcon={shouldPreventDisable && value.enabled} /> ), }); return acc; }, []); - }, [policyCategories, isOffline, selectedCategories, canSelectMultiple, translate, updateWorkspaceRequiresCategory, policy?.requiresCategory]); + }, [policyCategories, isOffline, selectedCategories, canSelectMultiple, translate, updateWorkspaceCategoryEnabled, policy?.requiresCategory]); useAutoTurnSelectionModeOffWhenHasNoActiveOption(categoryList); From 53f129e5a0b2e8c1aa351590ab0a0d3ed303f758 Mon Sep 17 00:00:00 2001 From: Rutika Pawar <183392827+twilight2294@users.noreply.github.com> Date: Tue, 8 Apr 2025 07:28:45 +0000 Subject: [PATCH 08/43] fix test and lint --- .../categories/WorkspaceCategoriesPage.tsx | 2 +- tests/ui/WorkspaceTagsTest.tsx | 91 +++++++++---------- 2 files changed, 42 insertions(+), 51 deletions(-) diff --git a/src/pages/workspace/categories/WorkspaceCategoriesPage.tsx b/src/pages/workspace/categories/WorkspaceCategoriesPage.tsx index 772dcb90bc94..326d14f8b0fc 100644 --- a/src/pages/workspace/categories/WorkspaceCategoriesPage.tsx +++ b/src/pages/workspace/categories/WorkspaceCategoriesPage.tsx @@ -171,7 +171,7 @@ function WorkspaceCategoriesPage({route}: WorkspaceCategoriesPageProps) { return acc; }, []); - }, [policyCategories, isOffline, selectedCategories, canSelectMultiple, translate, updateWorkspaceCategoryEnabled, policy?.requiresCategory]); + }, [policyCategories, isOffline, selectedCategories, canSelectMultiple, translate, updateWorkspaceCategoryEnabled, policy?.requiresCategory, shouldPreventDisable]); useAutoTurnSelectionModeOffWhenHasNoActiveOption(categoryList); diff --git a/tests/ui/WorkspaceTagsTest.tsx b/tests/ui/WorkspaceTagsTest.tsx index f0a777edd350..8d4256845432 100644 --- a/tests/ui/WorkspaceTagsTest.tsx +++ b/tests/ui/WorkspaceTagsTest.tsx @@ -42,23 +42,34 @@ const renderPage = (initialRouteName: typeof SCREENS.WORKSPACE.TAGS, initialPara ); }; -describe('WorkspaceTags', () => { - const FIRST_TAG = 'Tag One'; - const SECOND_TAG = 'Tag Two'; +const FIRST_TAG = 'Tag One'; +const SECOND_TAG = 'Tag Two'; + +const tags = { + TagListOne: { + name: 'TagListOne', + required: true, + orderWeight: 1, + tags: { + [FIRST_TAG]: { + name: FIRST_TAG, + enabled: true, + }, + [SECOND_TAG]: { + name: SECOND_TAG, + enabled: true, + }, + }, + }, +}; +describe('WorkspaceTags', () => { beforeAll(() => { Onyx.init({ keys: ONYXKEYS, }); }); - beforeEach(() => { - jest.spyOn(useResponsiveLayoutModule, 'default').mockReturnValue({ - isSmallScreenWidth: true, - shouldUseNarrowLayout: true, - } as ResponsiveLayoutResult); - }); - afterEach(async () => { await act(async () => { await Onyx.clear(); @@ -67,6 +78,11 @@ describe('WorkspaceTags', () => { }); it('should show select option when the item is not selected and deselect option when the item is selected', async () => { + jest.spyOn(useResponsiveLayoutModule, 'default').mockReturnValue({ + isSmallScreenWidth: true, + shouldUseNarrowLayout: true, + } as ResponsiveLayoutResult); + await TestHelper.signInWithTestUser(); const policy = { @@ -76,24 +92,6 @@ describe('WorkspaceTags', () => { requiresTag: true, }; - const tags = { - TagListOne: { - name: 'TagListOne', - required: true, - orderWeight: 1, - tags: { - [FIRST_TAG]: { - name: FIRST_TAG, - enabled: true, - }, - [SECOND_TAG]: { - name: SECOND_TAG, - enabled: true, - }, - }, - }, - }; - await act(async () => { await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${policy.id}`, policy); await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY_TAGS}${policy.id}`, tags); @@ -105,6 +103,9 @@ describe('WorkspaceTags', () => { await waitFor(() => { expect(screen.getByText(FIRST_TAG)).toBeOnTheScreen(); + }); + + await waitFor(() => { expect(screen.getByText(SECOND_TAG)).toBeOnTheScreen(); }); @@ -130,6 +131,11 @@ describe('WorkspaceTags', () => { // 👇 This is your new test case from the feature branch it('should show a blocking modal when trying to disable the only enabled tag when policy has requiresTag set to true', async () => { + jest.spyOn(useResponsiveLayoutModule, 'default').mockReturnValue({ + isSmallScreenWidth: false, + shouldUseNarrowLayout: false, + } as ResponsiveLayoutResult); + await TestHelper.signInWithTestUser(); const policy = { @@ -139,24 +145,6 @@ describe('WorkspaceTags', () => { requiresTag: true, }; - const tags = { - TagListOne: { - name: 'TagListOne', - required: true, - orderWeight: 1, - tags: { - ['tagOne']: { - name: 'tagOne', - enabled: true, - }, - ['tagTwo']: { - name: 'tagTwo', - enabled: true, - }, - }, - }, - }; - await act(async () => { await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${policy.id}`, policy); await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY_TAGS}${policy.id}`, tags); @@ -166,12 +154,15 @@ describe('WorkspaceTags', () => { await waitForBatchedUpdatesWithAct(); await waitFor(() => { - expect(screen.getByText('tagOne')).toBeOnTheScreen(); - expect(screen.getByText('tagTwo')).toBeOnTheScreen(); + expect(screen.getByText(FIRST_TAG)).toBeOnTheScreen(); + }); + + await waitFor(() => { + expect(screen.getByText(SECOND_TAG)).toBeOnTheScreen(); }); - fireEvent.press(screen.getByTestId(`TableListItemCheckbox-tagOne`)); - fireEvent.press(screen.getByTestId(`TableListItemCheckbox-tagTwo`)); + fireEvent.press(screen.getByTestId(`TableListItemCheckbox-${FIRST_TAG}`)); + fireEvent.press(screen.getByTestId(`TableListItemCheckbox-${SECOND_TAG}`)); const dropdownMenuButtonTestID = `${WorkspaceTagsPage.displayName}-header-dropdown-menu-button`; From 590d1c8e878afbd1ada00939e2b5a892277c09d7 Mon Sep 17 00:00:00 2001 From: Rutika Pawar <183392827+twilight2294@users.noreply.github.com> Date: Tue, 8 Apr 2025 09:59:23 +0000 Subject: [PATCH 09/43] add blocking modal for multi-level tags --- src/libs/PolicyUtils.ts | 14 ++++++ .../workspace/tags/WorkspaceTagsPage.tsx | 14 ++++-- .../workspace/tags/WorkspaceViewTagsPage.tsx | 43 +++++++++++++++++-- 3 files changed, 65 insertions(+), 6 deletions(-) diff --git a/src/libs/PolicyUtils.ts b/src/libs/PolicyUtils.ts index 5337272e946d..19340de70269 100644 --- a/src/libs/PolicyUtils.ts +++ b/src/libs/PolicyUtils.ts @@ -424,6 +424,19 @@ function getCountOfEnabledTagsOfList(policyTags: PolicyTags | undefined): number } return Object.values(policyTags).filter((policyTag) => policyTag.enabled).length; } +/** + * Gets count of multi-level required tags of a policy + */ +function getCountOfMultiLevelRequired(policyTagList: OnyxEntry): number { + if (!policyTagList || typeof policyTagList !== 'object') { + return 0; + } + + return Object.keys(policyTagList).filter((tagList) => { + const tagListValue = policyTagList[tagList]; + return tagListValue && tagListValue.required && getCountOfEnabledTagsOfList(tagListValue.tags) > 0; + }).length; +} /** * Whether the policy has multi-level tags @@ -1541,6 +1554,7 @@ export { isPrefferedExporter, isAutoSyncEnabled, areAllGroupPoliciesExpenseChatDisabled, + getCountOfMultiLevelRequired, }; export type {MemberEmailsToAccountIDs}; diff --git a/src/pages/workspace/tags/WorkspaceTagsPage.tsx b/src/pages/workspace/tags/WorkspaceTagsPage.tsx index 11f928423827..9bc1bcd6105c 100644 --- a/src/pages/workspace/tags/WorkspaceTagsPage.tsx +++ b/src/pages/workspace/tags/WorkspaceTagsPage.tsx @@ -44,6 +44,7 @@ import type {WorkspaceSplitNavigatorParamList} from '@libs/Navigation/types'; import { getCleanedTagName, getCountOfEnabledTagsOfList, + getCountOfMultiLevelRequired, getCurrentConnectionName, getTagLists, hasAccountingConnections as hasAccountingConnectionsPolicyUtils, @@ -167,7 +168,7 @@ function WorkspaceTagsPage({route}: WorkspaceTagsPageProps) { if (policyTagList.required && !areTagsEnabled) { updateWorkspaceRequiresTag(false, policyTagList.orderWeight); } - + console.log('getCountOfMultiLevelRequired(policyTags) ', getCountOfMultiLevelRequired(policyTags)); return { value: policyTagList.name, orderWeight: policyTagList.orderWeight, @@ -181,9 +182,16 @@ function WorkspaceTagsPage({route}: WorkspaceTagsPageProps) { updateWorkspaceRequiresTag(newValue, policyTagList.orderWeight)} + onToggle={(newValue: boolean) => { + if (getCountOfMultiLevelRequired(policyTags) === 1 && policy?.requiresTag && isSwitchEnabled) { + setShowCannotDisableLastTagModal(true); + return; + } + + updateWorkspaceRequiresTag(newValue, policyTagList.orderWeight); + }} disabled={isSwitchDisabled} - showLockIcon={getCountOfEnabledTagsOfList(policyTagLists.at(0)?.tags) === 1 && policy?.requiresTag && isSwitchEnabled} + showLockIcon={getCountOfMultiLevelRequired(policyTags) === 1 && policy?.requiresTag && isSwitchEnabled} /> ), }; diff --git a/src/pages/workspace/tags/WorkspaceViewTagsPage.tsx b/src/pages/workspace/tags/WorkspaceViewTagsPage.tsx index 51162184b594..eb43486a602a 100644 --- a/src/pages/workspace/tags/WorkspaceViewTagsPage.tsx +++ b/src/pages/workspace/tags/WorkspaceViewTagsPage.tsx @@ -36,7 +36,14 @@ import {canUseTouchScreen} from '@libs/DeviceCapabilities'; import localeCompare from '@libs/LocaleCompare'; import Navigation from '@libs/Navigation/Navigation'; import type {PlatformStackScreenProps} from '@libs/Navigation/PlatformStackNavigation/types'; -import {getCleanedTagName, getTagListName, hasDependentTags as hasDependentTagsPolicyUtils, isMultiLevelTags as isMultiLevelTagsPolicyUtils} from '@libs/PolicyUtils'; +import { + getCleanedTagName, + getCountOfEnabledTagsOfList, + getCountOfMultiLevelRequired, + getTagListName, + hasDependentTags as hasDependentTagsPolicyUtils, + isMultiLevelTags as isMultiLevelTagsPolicyUtils, +} from '@libs/PolicyUtils'; import type {SettingsNavigatorParamList} from '@navigation/types'; import NotFoundPage from '@pages/ErrorPage/NotFoundPage'; import AccessOrNotFoundWrapper from '@pages/workspace/AccessOrNotFoundWrapper'; @@ -69,6 +76,7 @@ function WorkspaceViewTagsPage({route}: WorkspaceViewTagsProps) { const currentTagListName = useMemo(() => getTagListName(policyTags, route.params.orderWeight), [policyTags, route.params.orderWeight]); const currentPolicyTag = policyTags?.[currentTagListName]; const isQuickSettingsFlow = !!backTo; + const [showCannotDisableLastTagModal, setShowCannotDisableLastTagModal] = useState(false); const fetchTags = useCallback(() => { openPolicyTagsPage(policyID); @@ -121,7 +129,14 @@ function WorkspaceViewTagsPage({route}: WorkspaceViewTagsProps) { isOn={tag.enabled} disabled={tag.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE} accessibilityLabel={translate('workspace.tags.enableTag')} - onToggle={(newValue: boolean) => updateWorkspaceTagEnabled(newValue, tag.name)} + onToggle={(newValue: boolean) => { + if (getCountOfMultiLevelRequired(policyTags) === 1 && getCountOfEnabledTagsOfList(currentPolicyTag?.tags) === 1 && policy?.requiresTag && tag.enabled) { + setShowCannotDisableLastTagModal(true); + return; + } + updateWorkspaceTagEnabled(newValue, tag.name); + }} + showLockIcon={getCountOfMultiLevelRequired(policyTags) === 1 && getCountOfEnabledTagsOfList(currentPolicyTag?.tags) === 1 && policy?.requiresTag && tag.enabled} /> ), })), @@ -222,11 +237,16 @@ function WorkspaceViewTagsPage({route}: WorkspaceViewTagsProps) { } if (enabledTagCount > 0) { + const tagsToDisableCount = Object.keys(tagsToDisable).length; options.push({ icon: Expensicons.Close, text: translate(enabledTagCount === 1 ? 'workspace.tags.disableTag' : 'workspace.tags.disableTags'), value: CONST.POLICY.BULK_ACTION_TYPES.DISABLE, onSelected: () => { + if (tagsToDisableCount === enabledTagCount && policy?.requiresTag) { + setShowCannotDisableLastTagModal(true); + return; + } setSelectedTags({}); setWorkspaceTagEnabled(policyID, tagsToDisable, route.params.orderWeight); }, @@ -316,11 +336,19 @@ function WorkspaceViewTagsPage({route}: WorkspaceViewTagsProps) { title={translate('common.required')} switchAccessibilityLabel={translate('common.required')} isActive={!!currentPolicyTag?.required} - onToggle={(on) => setPolicyTagsRequired(policyID, on, route.params.orderWeight)} + onToggle={(on) => { + if (getCountOfMultiLevelRequired(policyTags) === 1 && policy?.requiresTag && currentPolicyTag?.required) { + setShowCannotDisableLastTagModal(true); + return; + } + + setPolicyTagsRequired(policyID, on, route.params.orderWeight); + }} pendingAction={currentPolicyTag.pendingFields?.required} errors={currentPolicyTag?.errorFields?.required ?? undefined} onCloseError={() => clearPolicyTagListErrorField(policyID, route.params.orderWeight, 'required')} disabled={!currentPolicyTag?.required && !Object.values(currentPolicyTag?.tags ?? {}).some((tag) => tag.enabled)} + showLockIcon={getCountOfMultiLevelRequired(policyTags) === 1 && policy?.requiresTag && currentPolicyTag?.required} /> )} @@ -363,6 +391,15 @@ function WorkspaceViewTagsPage({route}: WorkspaceViewTagsProps) { }} /> )} + setShowCannotDisableLastTagModal(false)} + onCancel={() => setShowCannotDisableLastTagModal(false)} + title={translate('workspace.tags.cannotDisableAllTags.title')} + prompt={translate('workspace.tags.cannotDisableAllTags.description')} + confirmText={translate('common.buttonConfirm')} + shouldShowCancelButton={false} + /> ); From 0d20f204a7008615b52c36ee64bfa67355a673f8 Mon Sep 17 00:00:00 2001 From: Rutika Pawar <183392827+twilight2294@users.noreply.github.com> Date: Tue, 8 Apr 2025 10:08:05 +0000 Subject: [PATCH 10/43] remove console log and add dependencies --- src/pages/workspace/tags/WorkspaceTagsPage.tsx | 3 +-- src/pages/workspace/tags/WorkspaceViewTagsPage.tsx | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/pages/workspace/tags/WorkspaceTagsPage.tsx b/src/pages/workspace/tags/WorkspaceTagsPage.tsx index 9bc1bcd6105c..0e890d887f09 100644 --- a/src/pages/workspace/tags/WorkspaceTagsPage.tsx +++ b/src/pages/workspace/tags/WorkspaceTagsPage.tsx @@ -168,7 +168,6 @@ function WorkspaceTagsPage({route}: WorkspaceTagsPageProps) { if (policyTagList.required && !areTagsEnabled) { updateWorkspaceRequiresTag(false, policyTagList.orderWeight); } - console.log('getCountOfMultiLevelRequired(policyTags) ', getCountOfMultiLevelRequired(policyTags)); return { value: policyTagList.name, orderWeight: policyTagList.orderWeight, @@ -223,7 +222,7 @@ function WorkspaceTagsPage({route}: WorkspaceTagsPageProps) { /> ), })); - }, [isMultiLevelTags, policyTagLists, selectedTags, canSelectMultiple, translate, updateWorkspaceRequiresTag, updateWorkspaceTagEnabled, policy?.requiresTag]); + }, [isMultiLevelTags, policyTagLists, selectedTags, canSelectMultiple, translate, updateWorkspaceRequiresTag, updateWorkspaceTagEnabled, policy?.requiresTag, policyTags]); const tagListKeyedByName = useMemo( () => diff --git a/src/pages/workspace/tags/WorkspaceViewTagsPage.tsx b/src/pages/workspace/tags/WorkspaceViewTagsPage.tsx index eb43486a602a..0c742542bc0c 100644 --- a/src/pages/workspace/tags/WorkspaceViewTagsPage.tsx +++ b/src/pages/workspace/tags/WorkspaceViewTagsPage.tsx @@ -140,7 +140,7 @@ function WorkspaceViewTagsPage({route}: WorkspaceViewTagsProps) { /> ), })), - [currentPolicyTag?.tags, selectedTags, canSelectMultiple, translate, updateWorkspaceTagEnabled], + [currentPolicyTag?.tags, selectedTags, canSelectMultiple, translate, updateWorkspaceTagEnabled, policy?.requiresTag, policyTags], ); const hasDependentTags = useMemo(() => hasDependentTagsPolicyUtils(policy, policyTags), [policy, policyTags]); From 4325980b2a0d70b73efee8515da849947be82592 Mon Sep 17 00:00:00 2001 From: Rutika Pawar <183392827+twilight2294@users.noreply.github.com> Date: Tue, 8 Apr 2025 15:44:01 +0530 Subject: [PATCH 11/43] Update src/pages/workspace/categories/CategorySettingsPage.tsx Co-authored-by: Abdelhafidh Belalia <16493223+s77rt@users.noreply.github.com> --- src/pages/workspace/categories/CategorySettingsPage.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pages/workspace/categories/CategorySettingsPage.tsx b/src/pages/workspace/categories/CategorySettingsPage.tsx index 9847b2287705..a2d60bce41b8 100644 --- a/src/pages/workspace/categories/CategorySettingsPage.tsx +++ b/src/pages/workspace/categories/CategorySettingsPage.tsx @@ -59,7 +59,7 @@ function CategorySettingsPage({ const [isCannotDisableLastCategoryModalVisible, setIsCannotDisableLastCategoryModalVisible] = useState(false); const areCommentsRequired = policyCategory?.areCommentsRequired ?? false; const isQuickSettingsFlow = !!backTo; - const shouldPreventDisable = policyCategory?.enabled && policy?.requiresCategory && getEnabledCategoriesCount(policyCategories) === 1; + const shouldPreventDisable = policy?.requiresCategory && getEnabledCategoriesCount(policyCategories) === 1; const navigateBack = () => { Navigation.goBack(isQuickSettingsFlow ? ROUTES.SETTINGS_CATEGORIES_ROOT.getRoute(policyID, backTo) : undefined); From 32e71b42a925cc9b86e765db5ad310c5b176add5 Mon Sep 17 00:00:00 2001 From: Rutika Pawar <183392827+twilight2294@users.noreply.github.com> Date: Tue, 8 Apr 2025 15:45:31 +0530 Subject: [PATCH 12/43] Update src/pages/workspace/categories/CategorySettingsPage.tsx --- src/pages/workspace/categories/CategorySettingsPage.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pages/workspace/categories/CategorySettingsPage.tsx b/src/pages/workspace/categories/CategorySettingsPage.tsx index a2d60bce41b8..9847b2287705 100644 --- a/src/pages/workspace/categories/CategorySettingsPage.tsx +++ b/src/pages/workspace/categories/CategorySettingsPage.tsx @@ -59,7 +59,7 @@ function CategorySettingsPage({ const [isCannotDisableLastCategoryModalVisible, setIsCannotDisableLastCategoryModalVisible] = useState(false); const areCommentsRequired = policyCategory?.areCommentsRequired ?? false; const isQuickSettingsFlow = !!backTo; - const shouldPreventDisable = policy?.requiresCategory && getEnabledCategoriesCount(policyCategories) === 1; + const shouldPreventDisable = policyCategory?.enabled && policy?.requiresCategory && getEnabledCategoriesCount(policyCategories) === 1; const navigateBack = () => { Navigation.goBack(isQuickSettingsFlow ? ROUTES.SETTINGS_CATEGORIES_ROOT.getRoute(policyID, backTo) : undefined); From 4d8e7de0a74a572911a1bf6fb75775f26343cf98 Mon Sep 17 00:00:00 2001 From: Rutika Pawar <183392827+twilight2294@users.noreply.github.com> Date: Tue, 8 Apr 2025 15:49:56 +0530 Subject: [PATCH 13/43] fix unintended commit --- .../categories/CategorySettingsPage.tsx | 800 +++++++++++------- 1 file changed, 506 insertions(+), 294 deletions(-) diff --git a/src/pages/workspace/categories/CategorySettingsPage.tsx b/src/pages/workspace/categories/CategorySettingsPage.tsx index 9847b2287705..e66880d1e488 100644 --- a/src/pages/workspace/categories/CategorySettingsPage.tsx +++ b/src/pages/workspace/categories/CategorySettingsPage.tsx @@ -1,362 +1,574 @@ -import React, {useEffect, useMemo, useState} from 'react'; -import {View} from 'react-native'; +import lodashSortBy from 'lodash/sortBy'; +import React, {useCallback, useEffect, useMemo, useState} from 'react'; +import {ActivityIndicator, View} from 'react-native'; import {useOnyx} from 'react-native-onyx'; +import Button from '@components/Button'; +import ButtonWithDropdownMenu from '@components/ButtonWithDropdownMenu'; +import type {DropdownOption} from '@components/ButtonWithDropdownMenu/types'; import ConfirmModal from '@components/ConfirmModal'; +import DecisionModal from '@components/DecisionModal'; +import EmptyStateComponent from '@components/EmptyStateComponent'; import HeaderWithBackButton from '@components/HeaderWithBackButton'; -import {Trashcan} from '@components/Icon/Expensicons'; -import MenuItem from '@components/MenuItem'; -import MenuItemWithTopDescription from '@components/MenuItemWithTopDescription'; -import OfflineWithFeedback from '@components/OfflineWithFeedback'; +import * as Expensicons from '@components/Icon/Expensicons'; +import * as Illustrations from '@components/Icon/Illustrations'; +import LottieAnimations from '@components/LottieAnimations'; +import type {PopoverMenuItem} from '@components/PopoverMenu'; import ScreenWrapper from '@components/ScreenWrapper'; import ScrollView from '@components/ScrollView'; +import TableListItem from '@components/SelectionList/TableListItem'; +import SelectionListWithModal from '@components/SelectionListWithModal'; +import CustomListHeader from '@components/SelectionListWithModal/CustomListHeader'; +import TableListItemSkeleton from '@components/Skeletons/TableRowSkeleton'; import Switch from '@components/Switch'; import Text from '@components/Text'; import TextLink from '@components/TextLink'; +import useCleanupSelectedOptions from '@hooks/useCleanupSelectedOptions'; +import useEnvironment from '@hooks/useEnvironment'; import useLocalize from '@hooks/useLocalize'; +import useMobileSelectionMode from '@hooks/useMobileSelectionMode'; +import useNetwork from '@hooks/useNetwork'; import usePolicy from '@hooks/usePolicy'; +import useResponsiveLayout from '@hooks/useResponsiveLayout'; +import useSearchBackPress from '@hooks/useSearchBackPress'; +import useTheme from '@hooks/useTheme'; import useThemeStyles from '@hooks/useThemeStyles'; -import {formatDefaultTaxRateText, formatRequireReceiptsOverText, getCategoryApproverRule, getCategoryDefaultTaxRate} from '@libs/CategoryUtils'; -import {convertToDisplayString} from '@libs/CurrencyUtils'; -import {getLatestErrorMessageField} from '@libs/ErrorUtils'; +import useThreeDotsAnchorPosition from '@hooks/useThreeDotsAnchorPosition'; +import {isConnectionInProgress} from '@libs/actions/connections'; +import {turnOffMobileSelectionMode} from '@libs/actions/MobileSelectionMode'; +import {clearPolicyTagErrors, deletePolicyTags, downloadTagsCSV, openPolicyTagsPage, setPolicyTagsRequired, setWorkspaceTagEnabled} from '@libs/actions/Policy/Tag'; +import {canUseTouchScreen} from '@libs/DeviceCapabilities'; +import localeCompare from '@libs/LocaleCompare'; import Navigation from '@libs/Navigation/Navigation'; import type {PlatformStackScreenProps} from '@libs/Navigation/PlatformStackNavigation/types'; -import {getEnabledCategoriesCount} from '@libs/OptionsListUtils'; -import {getPersonalDetailByEmail} from '@libs/PersonalDetailsUtils'; -import {getWorkflowApprovalsUnavailable, isControlPolicy} from '@libs/PolicyUtils'; -import type {SettingsNavigatorParamList} from '@navigation/types'; -import NotFoundPage from '@pages/ErrorPage/NotFoundPage'; -import AccessOrNotFoundWrapper from '@pages/workspace/AccessOrNotFoundWrapper'; +import type {WorkspaceSplitNavigatorParamList} from '@libs/Navigation/types'; import { - clearCategoryErrors, - deleteWorkspaceCategories, - setPolicyCategoryDescriptionRequired, - setWorkspaceCategoryDescriptionHint, - setWorkspaceCategoryEnabled, -} from '@userActions/Policy/Category'; + getCleanedTagName, + getCountOfEnabledTagsOfList, + getCountOfMultiLevelRequired, + getCurrentConnectionName, + getTagLists, + hasAccountingConnections as hasAccountingConnectionsPolicyUtils, + isMultiLevelTags as isMultiLevelTagsPolicyUtils, + shouldShowSyncError, +} from '@libs/PolicyUtils'; +import AccessOrNotFoundWrapper from '@pages/workspace/AccessOrNotFoundWrapper'; +import {close} from '@userActions/Modal'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import ROUTES from '@src/ROUTES'; import type SCREENS from '@src/SCREENS'; +import type {PendingAction} from '@src/types/onyx/OnyxCommon'; +import type DeepValueOf from '@src/types/utils/DeepValueOf'; +import {isEmptyObject} from '@src/types/utils/EmptyObject'; +import type {PolicyTag, PolicyTagList, TagListItem} from './types'; -type CategorySettingsPageProps = PlatformStackScreenProps; +type WorkspaceTagsPageProps = PlatformStackScreenProps; -function CategorySettingsPage({ - route: { - params: {backTo, policyID, categoryName}, - }, - navigation, -}: CategorySettingsPageProps) { - const [policyCategories] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY_CATEGORIES}${policyID}`); +function WorkspaceTagsPage({route}: WorkspaceTagsPageProps) { + // We need to use isSmallScreenWidth instead of shouldUseNarrowLayout to use the correct modal type for the decision modal + // eslint-disable-next-line rulesdir/prefer-shouldUseNarrowLayout-instead-of-isSmallScreenWidth + const {shouldUseNarrowLayout, isSmallScreenWidth} = useResponsiveLayout(); const styles = useThemeStyles(); + const theme = useTheme(); const {translate} = useLocalize(); - const [deleteCategoryConfirmModalVisible, setDeleteCategoryConfirmModalVisible] = useState(false); + const threeDotsAnchorPosition = useThreeDotsAnchorPosition(styles.threeDotsPopoverOffsetNoCloseButton); + const [selectedTags, setSelectedTags] = useState>({}); + const [isDownloadFailureModalVisible, setIsDownloadFailureModalVisible] = useState(false); + const [isDeleteTagsConfirmModalVisible, setIsDeleteTagsConfirmModalVisible] = useState(false); + const [isOfflineModalVisible, setIsOfflineModalVisible] = useState(false); + const [showCannotDisableLastTagModal, setShowCannotDisableLastTagModal] = useState(false); + const policyID = route.params.policyID; + const backTo = route.params.backTo; const policy = usePolicy(policyID); + const [policyTags] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY_TAGS}${policyID}`); + const {selectionMode} = useMobileSelectionMode(); + const {environmentURL} = useEnvironment(); + const [connectionSyncProgress] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY_CONNECTION_SYNC_PROGRESS}${policy?.id}`); + const isSyncInProgress = isConnectionInProgress(connectionSyncProgress, policy); + const hasSyncError = shouldShowSyncError(policy, isSyncInProgress); + const isConnectedToAccounting = Object.keys(policy?.connections ?? {}).length > 0; + const currentConnectionName = getCurrentConnectionName(policy); + const [policyTagLists, isMultiLevelTags] = useMemo(() => [getTagLists(policyTags), isMultiLevelTagsPolicyUtils(policyTags)], [policyTags]); + const canSelectMultiple = !isMultiLevelTags && (shouldUseNarrowLayout ? selectionMode?.isEnabled : true); + const fetchTags = useCallback(() => { + openPolicyTagsPage(policyID); + }, [policyID]); + const isQuickSettingsFlow = !!backTo; - const policyCategory = policyCategories?.[categoryName] ?? Object.values(policyCategories ?? {}).find((category) => category.previousCategoryName === categoryName); - const policyCurrency = policy?.outputCurrency ?? CONST.CURRENCY.USD; - const policyCategoryExpenseLimitType = policyCategory?.expenseLimitType ?? CONST.POLICY.EXPENSE_LIMIT_TYPES.EXPENSE; + const {isOffline} = useNetwork({onReconnect: fetchTags}); - const [isCannotDisableLastCategoryModalVisible, setIsCannotDisableLastCategoryModalVisible] = useState(false); - const areCommentsRequired = policyCategory?.areCommentsRequired ?? false; - const isQuickSettingsFlow = !!backTo; - const shouldPreventDisable = policyCategory?.enabled && policy?.requiresCategory && getEnabledCategoriesCount(policyCategories) === 1; + useEffect(() => { + fetchTags(); + // eslint-disable-next-line react-compiler/react-compiler + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); - const navigateBack = () => { - Navigation.goBack(isQuickSettingsFlow ? ROUTES.SETTINGS_CATEGORIES_ROOT.getRoute(policyID, backTo) : undefined); - }; + const cleanupSelectedOption = useCallback(() => setSelectedTags({}), []); + useCleanupSelectedOptions(cleanupSelectedOption); useEffect(() => { - if (policyCategory?.name === categoryName || !policyCategory) { + if (isEmptyObject(selectedTags) || !canSelectMultiple) { return; } - navigation.setParams({categoryName: policyCategory?.name}); - }, [categoryName, navigation, policyCategory]); - const flagAmountsOverText = useMemo(() => { - if (policyCategory?.maxExpenseAmount === CONST.DISABLED_MAX_EXPENSE_VALUE || !policyCategory?.maxExpenseAmount) { - return ''; - } + setSelectedTags((prevSelectedTags) => { + const keys = Object.keys(prevSelectedTags); + const newSelectedTags: Record = {}; + const policyTagList = policyTagLists.at(0); - return `${convertToDisplayString(policyCategory?.maxExpenseAmount, policyCurrency)} ${CONST.DOT_SEPARATOR} ${translate( - `workspace.rules.categoryRules.expenseLimitTypes.${policyCategoryExpenseLimitType}`, - )}`; - }, [policyCategory?.maxExpenseAmount, policyCategoryExpenseLimitType, policyCurrency, translate]); + for (const key of keys) { + if (policyTagList?.tags?.[key] && policyTagList?.tags?.[key].pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE) { + newSelectedTags[key] = prevSelectedTags[key]; + } + } - const approverText = useMemo(() => { - const categoryApprover = getCategoryApproverRule(policy?.rules?.approvalRules ?? [], categoryName)?.approver ?? ''; - const approver = getPersonalDetailByEmail(categoryApprover); - return approver?.displayName ?? categoryApprover; - }, [categoryName, policy?.rules?.approvalRules]); + return newSelectedTags; + }); + // eslint-disable-next-line react-compiler/react-compiler, react-hooks/exhaustive-deps + }, [policyTagLists]); - const defaultTaxRateText = useMemo(() => { - const taxID = getCategoryDefaultTaxRate(policy?.rules?.expenseRules ?? [], categoryName, policy?.taxRates?.defaultExternalID); + useSearchBackPress({ + onClearSelection: () => { + setSelectedTags({}); + }, + onNavigationCallBack: () => Navigation.goBack(backTo), + }); - if (!taxID) { - return ''; + const getPendingAction = (policyTagList: PolicyTagList): PendingAction | undefined => { + if (!policyTagList) { + return undefined; } + return (policyTagList.pendingAction as PendingAction) ?? Object.values(policyTagList.tags).some((tag: PolicyTag) => tag.pendingAction) + ? CONST.RED_BRICK_ROAD_PENDING_ACTION.UPDATE + : undefined; + }; - const taxRate = policy?.taxRates?.taxes[taxID]; + const updateWorkspaceTagEnabled = useCallback( + (value: boolean, tagName: string) => { + setWorkspaceTagEnabled(policyID, {[tagName]: {name: tagName, enabled: value}}, 0); + }, + [policyID], + ); - if (!taxRate) { - return ''; - } + const updateWorkspaceRequiresTag = useCallback( + (value: boolean, orderWeight: number) => { + setPolicyTagsRequired(policyID, value, orderWeight); + }, + [policyID], + ); + const tagList = useMemo(() => { + if (isMultiLevelTags) { + return policyTagLists.map((policyTagList) => { + const areTagsEnabled = !!Object.values(policyTagList?.tags ?? {}).some((tag) => tag.enabled); + const isSwitchDisabled = !policyTagList.required && !areTagsEnabled; + const isSwitchEnabled = policyTagList.required && areTagsEnabled; - return formatDefaultTaxRateText(translate, taxID, taxRate, policy?.taxRates); - }, [categoryName, policy?.rules?.expenseRules, policy?.taxRates, translate]); + if (policyTagList.required && !areTagsEnabled) { + updateWorkspaceRequiresTag(false, policyTagList.orderWeight); + } + return { + value: policyTagList.name, + orderWeight: policyTagList.orderWeight, + text: getCleanedTagName(policyTagList.name), + keyForList: String(policyTagList.orderWeight), + isSelected: selectedTags[policyTagList.name] && canSelectMultiple, + pendingAction: getPendingAction(policyTagList), + enabled: true, + required: policyTagList.required, + rightElement: ( + { + if (getCountOfMultiLevelRequired(policyTags) === 1 && policy?.requiresTag && isSwitchEnabled) { + setShowCannotDisableLastTagModal(true); + return; + } - const requireReceiptsOverText = useMemo(() => { - if (!policy) { - return ''; + updateWorkspaceRequiresTag(newValue, policyTagList.orderWeight); + }} + disabled={isSwitchDisabled} + showLockIcon={getCountOfMultiLevelRequired(policyTags) === 1 && policy?.requiresTag && isSwitchEnabled} + /> + ), + }; + }); } - return formatRequireReceiptsOverText(translate, policy, policyCategory?.maxAmountNoReceipt); - }, [policy, policyCategory?.maxAmountNoReceipt, translate]); + const sortedTags = lodashSortBy(Object.values(policyTagLists.at(0)?.tags ?? {}), 'name', localeCompare) as PolicyTag[]; + return sortedTags.map((tag) => ({ + value: tag.name, + text: getCleanedTagName(tag.name), + keyForList: tag.name, + isSelected: selectedTags[tag.name] && canSelectMultiple, + pendingAction: tag.pendingAction, + errors: tag.errors ?? undefined, + enabled: tag.enabled, + isDisabled: tag.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE, + rightElement: ( + { + if (policy?.requiresTag && getCountOfEnabledTagsOfList(policyTagLists.at(0)?.tags) === 1 && !newValue) { + setShowCannotDisableLastTagModal(true); + return; + } + updateWorkspaceTagEnabled(newValue, tag.name); + }} + showLockIcon={getCountOfEnabledTagsOfList(policyTagLists.at(0)?.tags) === 1 && policy?.requiresTag && tag.enabled} + /> + ), + })); + }, [isMultiLevelTags, policyTagLists, selectedTags, canSelectMultiple, translate, updateWorkspaceRequiresTag, updateWorkspaceTagEnabled, policy?.requiresTag, policyTags]); - if (!policyCategory) { - return ; - } + const tagListKeyedByName = useMemo( + () => + tagList.reduce>((acc, tag) => { + acc[tag.value] = tag; + return acc; + }, {}), + [tagList], + ); + + const toggleTag = (tag: TagListItem) => { + setSelectedTags((prev) => ({ + ...prev, + [tag.value]: !prev[tag.value], + })); + }; - const updateWorkspaceCategoryEnabled = (value: boolean) => { - if (shouldPreventDisable && !value) { - setIsCannotDisableLastCategoryModalVisible(true); + const toggleAllTags = () => { + const availableTags = tagList.filter((tag) => tag.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE); + const isAllSelected = availableTags.length === Object.keys(selectedTags).length; + setSelectedTags(isAllSelected ? {} : Object.fromEntries(availableTags.map((item) => [item.value, true]))); + }; + + const getCustomListHeader = () => { + return ( + + ); + }; + + const navigateToTagsSettings = () => { + Navigation.navigate(isQuickSettingsFlow ? ROUTES.SETTINGS_TAGS_SETTINGS.getRoute(policyID, backTo) : ROUTES.WORKSPACE_TAGS_SETTINGS.getRoute(policyID)); + }; + + const navigateToCreateTagPage = () => { + Navigation.navigate(isQuickSettingsFlow ? ROUTES.SETTINGS_TAG_CREATE.getRoute(policyID, backTo) : ROUTES.WORKSPACE_TAG_CREATE.getRoute(policyID)); + }; + + const navigateToTagSettings = (tag: TagListItem) => { + if (isSmallScreenWidth && selectionMode?.isEnabled) { + toggleTag(tag); return; } - setWorkspaceCategoryEnabled(policyID, {[policyCategory.name]: {name: policyCategory.name, enabled: value}}); + if (tag.orderWeight !== undefined) { + Navigation.navigate( + isQuickSettingsFlow ? ROUTES.SETTINGS_TAG_LIST_VIEW.getRoute(policyID, tag.orderWeight, backTo) : ROUTES.WORKSPACE_TAG_LIST_VIEW.getRoute(policyID, tag.orderWeight), + ); + } else { + Navigation.navigate(isQuickSettingsFlow ? ROUTES.SETTINGS_TAG_SETTINGS.getRoute(policyID, 0, tag.value, backTo) : ROUTES.WORKSPACE_TAG_SETTINGS.getRoute(policyID, 0, tag.value)); + } }; - const navigateToEditCategory = () => { - Navigation.navigate( - isQuickSettingsFlow ? ROUTES.SETTINGS_CATEGORY_EDIT.getRoute(policyID, policyCategory.name, backTo) : ROUTES.WORKSPACE_CATEGORY_EDIT.getRoute(policyID, policyCategory.name), - ); + const selectedTagsArray = Object.keys(selectedTags).filter((key) => selectedTags[key]); + + const deleteTags = () => { + setSelectedTags({}); + deletePolicyTags(policyID, selectedTagsArray); + setIsDeleteTagsConfirmModalVisible(false); }; - const deleteCategory = () => { - deleteWorkspaceCategories(policyID, [categoryName]); - setDeleteCategoryConfirmModalVisible(false); - navigateBack(); + const isLoading = !isOffline && policyTags === undefined; + + const getHeaderButtons = () => { + const hasAccountingConnections = hasAccountingConnectionsPolicyUtils(policy); + + if (shouldUseNarrowLayout ? !selectionMode?.isEnabled : selectedTagsArray.length === 0) { + return ( + + {!hasAccountingConnections && !isMultiLevelTags && ( +