diff --git a/src/CONST/index.ts b/src/CONST/index.ts index 423a5b21e1d0..d8e4c2a038b8 100644 --- a/src/CONST/index.ts +++ b/src/CONST/index.ts @@ -1957,10 +1957,12 @@ const CONST = { DOWNLOAD_CSV: 'downloadCSV', REPORT_LEVEL_EXPORT: 'report_level_export', EXPENSE_LEVEL_EXPORT: 'detailed_export', + MULTIPLE_TAX_EXPORT: 'multiple_tax_export', }, EXPORT_OPTION_LABELS: { REPORT_LEVEL_EXPORT: 'All Data - Report Level Export', EXPENSE_LEVEL_EXPORT: 'All Data - Expense Level Export', + MULTIPLE_TAX_EXPORT: 'Canadian Multiple Tax Export', DEFAULT_CSV: 'Default CSV', }, ROOM_MEMBERS_BULK_ACTION_TYPES: { diff --git a/src/components/Search/FilterComponents/ExportedToSelector.tsx b/src/components/Search/FilterComponents/ExportedToSelector.tsx index d4fb9a46687f..8246cdbe393a 100644 --- a/src/components/Search/FilterComponents/ExportedToSelector.tsx +++ b/src/components/Search/FilterComponents/ExportedToSelector.tsx @@ -9,7 +9,7 @@ import useStyleUtils from '@hooks/useStyleUtils'; import useTheme from '@hooks/useTheme'; import useThemeStyles from '@hooks/useThemeStyles'; -import {getSearchValueForConnection} from '@libs/AccountingUtils'; +import {getSearchValueForConnection, getStandardExportTemplateDisplayName, isStandardExportTemplate} from '@libs/AccountingUtils'; import {getIntegrationIcon} from '@libs/ReportUtils'; import {getAllPolicyValues, getConnectedIntegrationNamesForPolicies} from '@libs/SearchQueryUtils'; @@ -28,11 +28,6 @@ type ExportedToSelectorProps = SearchFilterCommonProps & { policyID: Filter | undefined; }; -const STANDARD_EXPORT_TEMPLATE_ID_TO_DISPLAY_LABEL: Record = { - [CONST.REPORT.EXPORT_OPTIONS.REPORT_LEVEL_EXPORT]: CONST.REPORT.EXPORT_OPTION_LABELS.REPORT_LEVEL_EXPORT, - [CONST.REPORT.EXPORT_OPTIONS.EXPENSE_LEVEL_EXPORT]: CONST.REPORT.EXPORT_OPTION_LABELS.EXPENSE_LEVEL_EXPORT, -}; - function ExportedToSelector({value = [], policyID, selectionListTextInputStyle, selectionListStyle, autoFocus, footer, onChange}: ExportedToSelectorProps) { const styles = useThemeStyles(); const {localeCompare} = useLocalize(); @@ -106,13 +101,15 @@ function ExportedToSelector({value = [], policyID, selectionListTextInputStyle, } const displayName = template.name ?? template.templateName ?? ''; - const filterValue = STANDARD_EXPORT_TEMPLATE_ID_TO_DISPLAY_LABEL[template.templateName] ?? displayName; + + // Standard templates are filtered on by the label the backend records for them, while custom templates are filtered on by their display name + const isStandardTemplate = isStandardExportTemplate(template.templateName); + const filterValue = isStandardTemplate ? getStandardExportTemplateDisplayName(template.templateName) : displayName; if (usedPickerValueKeys.has(filterValue)) { continue; } usedPickerValueKeys.add(filterValue); - const isStandardTemplate = !!STANDARD_EXPORT_TEMPLATE_ID_TO_DISPLAY_LABEL[template.templateName]; standardAndIntegrationCustomTemplatePickerItems.push({ text: displayName, value: filterValue, diff --git a/src/components/Search/SearchList/ListItem/ExportedIconCell.tsx b/src/components/Search/SearchList/ListItem/ExportedIconCell.tsx index ebc6e020c955..9fad6fe70053 100644 --- a/src/components/Search/SearchList/ListItem/ExportedIconCell.tsx +++ b/src/components/Search/SearchList/ListItem/ExportedIconCell.tsx @@ -5,6 +5,7 @@ import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset'; import useTheme from '@hooks/useTheme'; import useThemeStyles from '@hooks/useThemeStyles'; +import {isStandardExportTemplateLabel} from '@libs/AccountingUtils'; import {getOriginalMessage, isExportedToIntegrationAction} from '@libs/ReportActionsUtils'; import CONST from '@src/CONST'; @@ -17,8 +18,6 @@ type ExportedIconCellProps = { reportActions?: ReportAction[]; }; -const STANDARD_EXPORT_TEMPLATE_LABELS = new Set([CONST.REPORT.EXPORT_OPTION_LABELS.EXPENSE_LEVEL_EXPORT, CONST.REPORT.EXPORT_OPTION_LABELS.REPORT_LEVEL_EXPORT]); - function ExportedIconCell({reportActions}: ExportedIconCellProps) { const theme = useTheme(); const styles = useThemeStyles(); @@ -60,7 +59,7 @@ function ExportedIconCell({reportActions}: ExportedIconCellProps) { const message = getOriginalMessage(action); const label = message?.label; const type = message?.type; - const isStandardExportTemplate = !!label && STANDARD_EXPORT_TEMPLATE_LABELS.has(label); + const isStandardExportTemplate = !!label && isStandardExportTemplateLabel(label); if (type === CONST.EXPORT_TEMPLATE && isStandardExportTemplate) { isExportedToStandardTemplate = true; diff --git a/src/hooks/useExportedToFilterOptions.ts b/src/hooks/useExportedToFilterOptions.ts index e770d777c50b..59c862e12752 100644 --- a/src/hooks/useExportedToFilterOptions.ts +++ b/src/hooks/useExportedToFilterOptions.ts @@ -31,7 +31,7 @@ function exportedToPoliciesSelector(policies: OnyxCollection): OnyxColle if (!policy) { continue; } - result[key] = {id: policy.id, name: policy.name, connections: policy.connections, exportLayouts: policy.exportLayouts} as Policy; + result[key] = {id: policy.id, name: policy.name, connections: policy.connections, exportLayouts: policy.exportLayouts, outputCurrency: policy.outputCurrency} as Policy; } return result; } diff --git a/src/hooks/useSearchBulkActions.ts b/src/hooks/useSearchBulkActions.ts index 8ce122c96e2a..87860d454913 100644 --- a/src/hooks/useSearchBulkActions.ts +++ b/src/hooks/useSearchBulkActions.ts @@ -64,7 +64,7 @@ import { isSelfDM, shouldShowMarkAsDone, } from '@libs/ReportUtils'; -import {buildSearchQueryJSON, buildSearchQueryString, isDefaultExpensesQuery, serializeQueryJSONForBackend} from '@libs/SearchQueryUtils'; +import {buildSearchQueryJSON, buildSearchQueryString, getFilterFromQuery, isDefaultExpensesQuery, serializeQueryJSONForBackend} from '@libs/SearchQueryUtils'; import {getColumnsToShow, getSearchColumnTranslationKey, getSelectedGroupFilterEntry, getValidGroupBy, isGroupEntry, navigateToSearchRHP, shouldShowDeleteOption} from '@libs/SearchUIUtils'; import showConfirmModalAfterMoreMenuDismiss from '@libs/showConfirmModalAfterMoreMenuDismiss'; import playSound, {SOUNDS} from '@libs/Sound'; @@ -572,6 +572,27 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) { ], [selectedTransactions], ); + + // A bulk selection can span several workspaces, so the Canadian Multiple Tax Export template is only offered when every selected item belongs to a workspace that outputs in CAD. + // Reports and transactions are both checked because a selection can mix whole reports with individual transactions from other reports, and the export request covers all of them. + const doAllSelectedItemsBelongToCADPolicies = useMemo(() => { + if (areAllMatchingItemsSelected) { + const policyIDFilter = getFilterFromQuery(queryJSON, CONST.SEARCH.SYNTAX_FILTER_KEYS.POLICY_ID); + if (!policyIDFilter.value?.length || policyIDFilter.isNegated) { + return false; + } + + return policyIDFilter.value.every((policyID) => policies?.[`${ONYXKEYS.COLLECTION.POLICY}${policyID}`]?.outputCurrency === CONST.CURRENCY.CAD); + } + + const selectedItems = [...selectedReports, ...Object.values(selectedTransactions)]; + if (selectedItems.length === 0) { + return false; + } + + return selectedItems.every((item) => !!item.policyID && policies?.[`${ONYXKEYS.COLLECTION.POLICY}${item.policyID}`]?.outputCurrency === CONST.CURRENCY.CAD); + }, [areAllMatchingItemsSelected, queryJSON, selectedReports, selectedTransactions, policies]); + const selectedBulkCurrency = selectedReports.at(0)?.currency ?? Object.values(selectedTransactions).at(0)?.currency; const totalFormattedAmount = getTotalFormattedAmount(convertToDisplayString, selectedReports, selectedTransactions, selectedBulkCurrency); @@ -1688,6 +1709,7 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) { policy, includeReportLevelExport, !isGroupedSearch, + doAllSelectedItemsBelongToCADPolicies, ); const shouldHideTemplateExports = isExpenseType && areAllMatchingItemsSelected && Object.keys(excludedTransactions).length > 0; const availableCustomTemplates = shouldHideTemplateExports @@ -2507,6 +2529,7 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) { personalPolicy?.outputCurrency, restrictedActionPolicyID, doSelectedItemsBelongToSubmitPolicy, + doAllSelectedItemsBelongToCADPolicies, openSearchReportSubmitToPopover, deleteTransactionsFromHook, duplicateTransactionViolations, diff --git a/src/languages/de.ts b/src/languages/de.ts index c02737885786..4cf7a5f0d9ac 100644 --- a/src/languages/de.ts +++ b/src/languages/de.ts @@ -10393,6 +10393,7 @@ Hier ist ein *Testbeleg*, um dir zu zeigen, wie es funktioniert:`, basicExport: 'Standardexport', reportLevelExport: 'Alle Daten – Berichtsebene', expenseLevelExport: 'Alle Daten – Ausgabenebene', + multipleTaxExport: 'Kanadischer Export mit mehreren Steuern', exportInProgress: 'Export wird ausgeführt', conciergeWillSend: 'Concierge wird dir die Datei in Kürze senden.', currentView: 'Aktuelle Ansicht', diff --git a/src/languages/el.ts b/src/languages/el.ts index 619da4e10e13..722abfe5cce8 100644 --- a/src/languages/el.ts +++ b/src/languages/el.ts @@ -10610,6 +10610,7 @@ ${reportName}`, currentView: 'Τρέχουσα προβολή', reportLevelExport: 'Όλα τα δεδομένα - σε επίπεδο αναφοράς', expenseLevelExport: 'Όλα τα δεδομένα - επίπεδο δαπάνης', + multipleTaxExport: 'Καναδική εξαγωγή πολλαπλών φόρων', exportInProgress: 'Εξαγωγή σε εξέλιξη', conciergeWillSend: 'Ο Concierge θα σας στείλει το αρχείο σύντομα.', downloadStatementPDF: 'Λήψη κατάστασης', diff --git a/src/languages/en.ts b/src/languages/en.ts index 4257c624f813..167eb7d7aad9 100644 --- a/src/languages/en.ts +++ b/src/languages/en.ts @@ -10548,6 +10548,7 @@ const translations = { currentView: 'Current view', reportLevelExport: 'All Data - report level', expenseLevelExport: 'All Data - expense level', + multipleTaxExport: 'Canadian Multiple Tax Export', exportInProgress: 'Export in progress', conciergeWillSend: 'Concierge will send you the file shortly.', }, diff --git a/src/languages/es.ts b/src/languages/es.ts index c2f33688b721..b902d76f1e87 100644 --- a/src/languages/es.ts +++ b/src/languages/es.ts @@ -10590,6 +10590,7 @@ El plan Controlar empieza en 9 $ por miembro activo al mes.`, basicExport: 'Exportar básico', reportLevelExport: 'Todos los datos - a nivel de informe', expenseLevelExport: 'Todos los datos - a nivel de gasto', + multipleTaxExport: 'Exportación canadiense de impuestos múltiples', exportInProgress: 'Exportación en curso', conciergeWillSend: 'Concierge te enviará el archivo en breve.', currentView: 'Vista actual', diff --git a/src/languages/fr.ts b/src/languages/fr.ts index d73f782c2236..675c7b7c8899 100644 --- a/src/languages/fr.ts +++ b/src/languages/fr.ts @@ -10427,6 +10427,7 @@ Voici un *reçu test* pour vous montrer comment ça fonctionne :`, basicExport: 'Export basique', reportLevelExport: 'Toutes les données - niveau note de frais', expenseLevelExport: 'Toutes les données - niveau dépense', + multipleTaxExport: 'Export canadien à taxes multiples', exportInProgress: 'Export en cours', conciergeWillSend: 'Concierge vous enverra le fichier sous peu.', currentView: 'Vue actuelle', diff --git a/src/languages/it.ts b/src/languages/it.ts index a26fc7d11e55..2ac9015a4611 100644 --- a/src/languages/it.ts +++ b/src/languages/it.ts @@ -10364,6 +10364,7 @@ Ecco una *ricevuta di prova* per mostrarti come funziona:`, basicExport: 'Esportazione di base', reportLevelExport: 'Tutti i dati - livello report', expenseLevelExport: 'Tutti i dati - livello spesa', + multipleTaxExport: 'Esportazione canadese con imposte multiple', exportInProgress: 'Esportazione in corso', conciergeWillSend: 'Concierge ti invierà il file a breve.', currentView: 'Vista corrente', diff --git a/src/languages/ja.ts b/src/languages/ja.ts index 5d2b26e6c14e..82beae5ad72b 100644 --- a/src/languages/ja.ts +++ b/src/languages/ja.ts @@ -10227,6 +10227,7 @@ ${reportName}`, basicExport: '基本エクスポート', reportLevelExport: 'すべてのデータ - レポートレベル', expenseLevelExport: 'すべてのデータ - 経費レベル', + multipleTaxExport: 'カナダの複数税エクスポート', exportInProgress: 'エクスポート処理中', conciergeWillSend: 'Conciergeがまもなくファイルを送信します。', currentView: '現在のビュー', diff --git a/src/languages/nl.ts b/src/languages/nl.ts index 25f00ee82bf0..e1c7b3aa7313 100644 --- a/src/languages/nl.ts +++ b/src/languages/nl.ts @@ -10335,6 +10335,7 @@ Hier is een *proefbon* om je te laten zien hoe het werkt:`, basicExport: 'Standaardexport', reportLevelExport: 'Alle gegevens - rapportniveau', expenseLevelExport: 'Alle gegevens - uitgaveniveau', + multipleTaxExport: 'Canadese export met meerdere belastingen', exportInProgress: 'Export bezig', conciergeWillSend: 'Concierge stuurt je het bestand zo meteen.', currentView: 'Huidige weergave', diff --git a/src/languages/pl.ts b/src/languages/pl.ts index 0d14cbf4d173..3624a38039a7 100644 --- a/src/languages/pl.ts +++ b/src/languages/pl.ts @@ -10304,6 +10304,7 @@ Oto *paragon testowy*, żeby pokazać Ci, jak to działa:`, basicExport: 'Podstawowy eksport', reportLevelExport: 'Wszystkie dane – poziom raportu', expenseLevelExport: 'Wszystkie dane – poziom wydatku', + multipleTaxExport: 'Kanadyjski eksport z wieloma podatkami', exportInProgress: 'Trwa eksport', conciergeWillSend: 'Concierge wkrótce wyśle Ci plik.', currentView: 'Bieżący widok', diff --git a/src/languages/pt-BR.ts b/src/languages/pt-BR.ts index 52690e34b069..257b88b541e3 100644 --- a/src/languages/pt-BR.ts +++ b/src/languages/pt-BR.ts @@ -10328,6 +10328,7 @@ Aqui está um *comprovante de teste* para mostrar como funciona:`, basicExport: 'Exportação básica', reportLevelExport: 'Todos os dados - nível de relatório', expenseLevelExport: 'Todos os dados - nível de despesa', + multipleTaxExport: 'Exportação canadense de múltiplos impostos', exportInProgress: 'Exportação em andamento', conciergeWillSend: 'O Concierge enviará o arquivo para você em breve.', currentView: 'Visualização atual', diff --git a/src/languages/zh-hans.ts b/src/languages/zh-hans.ts index 59339478e05d..b58052d052ac 100644 --- a/src/languages/zh-hans.ts +++ b/src/languages/zh-hans.ts @@ -9979,6 +9979,7 @@ ${reportName}`, basicExport: '基本导出', reportLevelExport: '所有数据 - 报告级别', expenseLevelExport: '所有数据 - 报销级别', + multipleTaxExport: '加拿大多种税导出', exportInProgress: '导出进行中', conciergeWillSend: 'Concierge 将很快把文件发送给你。', currentView: '当前视图', diff --git a/src/libs/AccountingUtils.ts b/src/libs/AccountingUtils.ts index 9d6a519fd2c3..a73f62358e32 100644 --- a/src/libs/AccountingUtils.ts +++ b/src/libs/AccountingUtils.ts @@ -34,8 +34,11 @@ const NAME_ROUTE_MAPPING = { const STANDARD_EXPORT_TEMPLATE_NAME_MAPPING = { [CONST.REPORT.EXPORT_OPTIONS.EXPENSE_LEVEL_EXPORT]: CONST.REPORT.EXPORT_OPTION_LABELS.EXPENSE_LEVEL_EXPORT, [CONST.REPORT.EXPORT_OPTIONS.REPORT_LEVEL_EXPORT]: CONST.REPORT.EXPORT_OPTION_LABELS.REPORT_LEVEL_EXPORT, + [CONST.REPORT.EXPORT_OPTIONS.MULTIPLE_TAX_EXPORT]: CONST.REPORT.EXPORT_OPTION_LABELS.MULTIPLE_TAX_EXPORT, }; +const STANDARD_EXPORT_TEMPLATE_LABELS = new Set(Object.values(STANDARD_EXPORT_TEMPLATE_NAME_MAPPING)); + function getConnectionNameFromRouteParam(routeParam: ValueOf) { return ROUTE_NAME_MAPPING[routeParam]; } @@ -52,4 +55,21 @@ function getStandardExportTemplateDisplayName(templateName: string): string { return STANDARD_EXPORT_TEMPLATE_NAME_MAPPING[templateName as keyof typeof STANDARD_EXPORT_TEMPLATE_NAME_MAPPING] ?? templateName; } -export {getConnectionNameFromRouteParam, getRouteParamForConnection, getSearchValueForConnection, getStandardExportTemplateDisplayName}; +/** Whether the given template ID belongs to one of the standard (i.e. not user-defined) export templates */ +function isStandardExportTemplate(templateName: string): boolean { + return templateName in STANDARD_EXPORT_TEMPLATE_NAME_MAPPING; +} + +/** Whether the given export label, as sent by the backend on an export report action, belongs to one of the standard (i.e. not user-defined) export templates */ +function isStandardExportTemplateLabel(label: string): boolean { + return STANDARD_EXPORT_TEMPLATE_LABELS.has(label); +} + +export { + getConnectionNameFromRouteParam, + getRouteParamForConnection, + getSearchValueForConnection, + getStandardExportTemplateDisplayName, + isStandardExportTemplate, + isStandardExportTemplateLabel, +}; diff --git a/src/libs/SearchQueryUtils.ts b/src/libs/SearchQueryUtils.ts index 4c62643429e6..933eae6b2473 100644 --- a/src/libs/SearchQueryUtils.ts +++ b/src/libs/SearchQueryUtils.ts @@ -56,6 +56,7 @@ import Onyx from 'react-native-onyx'; import type {SearchFullscreenNavigatorParamList} from './Navigation/types'; +import {getStandardExportTemplateDisplayName} from './AccountingUtils'; import {getBankAccountSearchLabel, isBankAccountPartiallySetup} from './BankAccountUtils'; import {getCardFeedsForDisplay} from './CardFeedUtils'; import {getCardDescription} from './CardUtils'; @@ -1756,13 +1757,8 @@ function getFilterDisplayValue({ return getPolicyNameWithFallback(filterValue, policies, reports); } if (filterName === CONST.SEARCH.SYNTAX_FILTER_KEYS.EXPORTED_TO) { - if (filterValue === CONST.REPORT.EXPORT_OPTIONS.REPORT_LEVEL_EXPORT) { - return CONST.REPORT.EXPORT_OPTION_LABELS.REPORT_LEVEL_EXPORT; - } - if (filterValue === CONST.REPORT.EXPORT_OPTIONS.EXPENSE_LEVEL_EXPORT) { - return CONST.REPORT.EXPORT_OPTION_LABELS.EXPENSE_LEVEL_EXPORT; - } - return filterValue; + // A query can carry a standard template's ID, so display the label the backend records for it. Custom template names are returned as-is. + return getStandardExportTemplateDisplayName(filterValue); } return filterValue; } diff --git a/src/libs/actions/Search.ts b/src/libs/actions/Search.ts index 23a4f8e92a9e..eaebf781d93e 100644 --- a/src/libs/actions/Search.ts +++ b/src/libs/actions/Search.ts @@ -1775,6 +1775,8 @@ type ExportTemplateGroups = { * @param policy - The user's policy * @param includeReportLevelExport - Whether to include the report level export template * @param includeBasicExport - Whether to include the basic export (CSV download) template in the default group + * @param includeMultipleTaxExport - Whether to include the Canadian Multiple Tax Export template. Defaults to whether the given policy outputs in CAD, so callers that + * export across several workspaces (e.g. a bulk selection in Search) can instead pass whether every selected workspace outputs in CAD. * @returns The export templates pre-grouped into the custom group and the default group, each sorted alphabetically */ function getExportTemplates( @@ -1785,6 +1787,7 @@ function getExportTemplates( policy?: Policy, includeReportLevelExport = true, includeBasicExport = false, + includeMultipleTaxExport = policy?.outputCurrency === CONST.CURRENCY.CAD, ): ExportTemplateGroups { // Helper function to normalize template data into consistent ExportTemplate format const normalizeTemplate = ( @@ -1811,6 +1814,11 @@ function getExportTemplates( exportTemplates.push(normalizeTemplate(CONST.REPORT.EXPORT_OPTIONS.REPORT_LEVEL_EXPORT, {name: translate('export.reportLevelExport')}, CONST.EXPORT_TEMPLATE_TYPES.INTEGRATIONS)); } + // The Canadian Multiple Tax Export template is only relevant to workspaces that output in CAD, so it's hidden for every other currency + if (includeMultipleTaxExport) { + exportTemplates.push(normalizeTemplate(CONST.REPORT.EXPORT_OPTIONS.MULTIPLE_TAX_EXPORT, {name: translate('export.multipleTaxExport')}, CONST.EXPORT_TEMPLATE_TYPES.INTEGRATIONS)); + } + // Conditionally include the basic export (CSV download) template so it's sorted alphabetically alongside the other default templates if (includeBasicExport) { exportTemplates.push(normalizeTemplate(CONST.REPORT.EXPORT_OPTIONS.DOWNLOAD_CSV, {name: translate('export.basicExport')}, CONST.EXPORT_TEMPLATE_TYPES.INTEGRATIONS)); diff --git a/tests/unit/Search/SearchQueryUtilsTest.ts b/tests/unit/Search/SearchQueryUtilsTest.ts index e5e636cad8ba..3aebe143ba97 100644 --- a/tests/unit/Search/SearchQueryUtilsTest.ts +++ b/tests/unit/Search/SearchQueryUtilsTest.ts @@ -2807,6 +2807,41 @@ describe('SearchQueryUtils', () => { expect(result).toBe(CONST.REPORT.EXPORT_OPTION_LABELS.REPORT_LEVEL_EXPORT); }); + it('should display the label the backend records for the Canadian multiple tax export template', () => { + const result = getFilterDisplayValue({ + filterName: CONST.SEARCH.SYNTAX_FILTER_KEYS.EXPORTED_TO, + filterValue: CONST.REPORT.EXPORT_OPTIONS.MULTIPLE_TAX_EXPORT, + personalDetails: {}, + reports: {}, + cardList: mockCardList, + cardFeeds: mockCardFeeds, + policies: mockPolicies, + currentUserAccountID, + translate: translateLocal, + formatPhoneNumber, + }); + + expect(result).toBe(CONST.REPORT.EXPORT_OPTION_LABELS.MULTIPLE_TAX_EXPORT); + }); + + it('should return a custom export template name as-is', () => { + const customTemplateName = 'Custom Export Layout'; + const result = getFilterDisplayValue({ + filterName: CONST.SEARCH.SYNTAX_FILTER_KEYS.EXPORTED_TO, + filterValue: customTemplateName, + personalDetails: {}, + reports: {}, + cardList: mockCardList, + cardFeeds: mockCardFeeds, + policies: mockPolicies, + currentUserAccountID, + translate: translateLocal, + formatPhoneNumber, + }); + + expect(result).toBe(customTemplateName); + }); + it('should handle policyID filter by looking up policy name', () => { const policies: OnyxCollection = { [`${ONYXKEYS.COLLECTION.POLICY}abc123`]: { diff --git a/tests/unit/SearchActionsTest.ts b/tests/unit/SearchActionsTest.ts index dab410f26160..f41af29953c5 100644 --- a/tests/unit/SearchActionsTest.ts +++ b/tests/unit/SearchActionsTest.ts @@ -10,9 +10,10 @@ import type {SearchKey} from '@libs/SearchUIUtils'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; -import type {ExportTemplate} from '@src/types/onyx'; +import type {ExportTemplate, Policy} from '@src/types/onyx'; import type {AnyOnyxUpdate} from '@src/types/onyx/Request'; +import createRandomPolicy from '../utils/collections/policies'; import {translateLocal} from '../utils/TestHelper'; const translateForTest: LocalizedTranslate = (path, ...parameters) => translate(CONST.LOCALES.EN, path, ...parameters); @@ -280,6 +281,7 @@ describe('getExportTemplates', () => { const translateForTemplates = translateLocal; const localeCompare = (first: string, second: string) => first.localeCompare(second); const makeTemplate = (name: string): ExportTemplate => ({name, templateName: name, type: '', policyID: undefined, description: ''}); + const makePolicyWithOutputCurrency = (outputCurrency: string): Policy => ({...createRandomPolicy(1), outputCurrency}); it('returns the custom templates and the default templates as separate groups, each sorted alphabetically', () => { const integrationsExportTemplates: ExportTemplate[] = [makeTemplate('Zebra integration'), makeTemplate('Apple integration')]; @@ -321,4 +323,28 @@ describe('getExportTemplates', () => { [translateForTemplates('export.expenseLevelExport'), translateForTemplates('export.reportLevelExport'), translateForTemplates('export.basicExport')].sort(localeCompare), ); }); + + it('includes the Canadian Multiple Tax Export template when the policy outputs in CAD', () => { + const {defaultTemplates} = getExportTemplates([], {}, translateForTemplates, localeCompare, makePolicyWithOutputCurrency(CONST.CURRENCY.CAD)); + + expect(defaultTemplates.map((template) => template.templateName)).toContain(CONST.REPORT.EXPORT_OPTIONS.MULTIPLE_TAX_EXPORT); + }); + + it('excludes the Canadian Multiple Tax Export template when the policy outputs in another currency', () => { + const {defaultTemplates} = getExportTemplates([], {}, translateForTemplates, localeCompare, makePolicyWithOutputCurrency(CONST.CURRENCY.USD)); + + expect(defaultTemplates.map((template) => template.templateName)).not.toContain(CONST.REPORT.EXPORT_OPTIONS.MULTIPLE_TAX_EXPORT); + }); + + it('includes the Canadian Multiple Tax Export template when includeMultipleTaxExport is true without a policy', () => { + const {defaultTemplates} = getExportTemplates([], {}, translateForTemplates, localeCompare, undefined, true, false, true); + + expect(defaultTemplates.map((template) => template.templateName)).toContain(CONST.REPORT.EXPORT_OPTIONS.MULTIPLE_TAX_EXPORT); + }); + + it('excludes the Canadian Multiple Tax Export template when includeMultipleTaxExport is false for a CAD policy', () => { + const {defaultTemplates} = getExportTemplates([], {}, translateForTemplates, localeCompare, makePolicyWithOutputCurrency(CONST.CURRENCY.CAD), true, false, false); + + expect(defaultTemplates.map((template) => template.templateName)).not.toContain(CONST.REPORT.EXPORT_OPTIONS.MULTIPLE_TAX_EXPORT); + }); }); diff --git a/tests/unit/SearchAutocompleteUtilsTest.ts b/tests/unit/SearchAutocompleteUtilsTest.ts index 2f32a19b592f..6e4012ed488a 100644 --- a/tests/unit/SearchAutocompleteUtilsTest.ts +++ b/tests/unit/SearchAutocompleteUtilsTest.ts @@ -1,6 +1,6 @@ import type {SubstitutionMap} from '@components/Search/SearchRouter/getQueryWithSubstitutions'; -import {getSearchValueForConnection, getStandardExportTemplateDisplayName} from '@libs/AccountingUtils'; +import {getSearchValueForConnection, getStandardExportTemplateDisplayName, isStandardExportTemplate, isStandardExportTemplateLabel} from '@libs/AccountingUtils'; import {getParsableSearchValue, getTrimmedUserSearchQueryPreservingComma, parseForLiveMarkdown} from '@libs/SearchAutocompleteUtils'; import CONST from '@src/CONST'; @@ -554,11 +554,39 @@ describe('SearchAutocompleteUtils', () => { expect(getStandardExportTemplateDisplayName(CONST.REPORT.EXPORT_OPTIONS.REPORT_LEVEL_EXPORT)).toBe(CONST.REPORT.EXPORT_OPTION_LABELS.REPORT_LEVEL_EXPORT); }); + it('returns display name for the Canadian multiple tax export template', () => { + expect(getStandardExportTemplateDisplayName(CONST.REPORT.EXPORT_OPTIONS.MULTIPLE_TAX_EXPORT)).toBe(CONST.REPORT.EXPORT_OPTION_LABELS.MULTIPLE_TAX_EXPORT); + }); + it('returns template name as-is when no standard mapping', () => { const customName = 'Custom Export Layout'; expect(getStandardExportTemplateDisplayName(customName)).toBe(customName); }); }); + + describe('isStandardExportTemplate', () => { + it('returns true for every standard export template ID', () => { + expect(isStandardExportTemplate(CONST.REPORT.EXPORT_OPTIONS.EXPENSE_LEVEL_EXPORT)).toBe(true); + expect(isStandardExportTemplate(CONST.REPORT.EXPORT_OPTIONS.REPORT_LEVEL_EXPORT)).toBe(true); + expect(isStandardExportTemplate(CONST.REPORT.EXPORT_OPTIONS.MULTIPLE_TAX_EXPORT)).toBe(true); + }); + + it('returns false for a custom template ID', () => { + expect(isStandardExportTemplate('Custom Export Layout')).toBe(false); + }); + }); + + describe('isStandardExportTemplateLabel', () => { + it('returns true for every standard export template label', () => { + expect(isStandardExportTemplateLabel(CONST.REPORT.EXPORT_OPTION_LABELS.EXPENSE_LEVEL_EXPORT)).toBe(true); + expect(isStandardExportTemplateLabel(CONST.REPORT.EXPORT_OPTION_LABELS.REPORT_LEVEL_EXPORT)).toBe(true); + expect(isStandardExportTemplateLabel(CONST.REPORT.EXPORT_OPTION_LABELS.MULTIPLE_TAX_EXPORT)).toBe(true); + }); + + it('returns false for a custom template label', () => { + expect(isStandardExportTemplateLabel('Custom Export Layout')).toBe(false); + }); + }); }); describe('getParsableSearchValue', () => { diff --git a/tests/unit/hooks/useSearchBulkActionsExportTest.ts b/tests/unit/hooks/useSearchBulkActionsExportTest.ts index da40cbeddfbf..610aec26cff0 100644 --- a/tests/unit/hooks/useSearchBulkActionsExportTest.ts +++ b/tests/unit/hooks/useSearchBulkActionsExportTest.ts @@ -5,6 +5,7 @@ import type {SearchQueryJSON, SelectedReports, SelectedTransactions} from '@comp import useSearchBulkActions from '@hooks/useSearchBulkActions'; +import {getExportTemplates} from '@libs/actions/Search'; import type * as ReportSecondaryActionUtilsModule from '@libs/ReportSecondaryActionUtils'; import CONST from '@src/CONST'; @@ -207,12 +208,13 @@ const mockSelectAllMatchingItems = jest.fn(); let mockSelectedTransactions: SelectedTransactions = {}; let mockSelectedReports: SelectedReports[] = []; let mockCurrentSearchResults: SearchResults | undefined; +let mockAreAllMatchingItemsSelected = false; jest.mock('@components/Search/SearchContext', () => ({ useSearchSelectionContext: () => ({ selectedTransactions: mockSelectedTransactions, selectedReports: mockSelectedReports, - areAllMatchingItemsSelected: false, + areAllMatchingItemsSelected: mockAreAllMatchingItemsSelected, }), useSearchResultsContext: () => ({ currentSearchResults: mockCurrentSearchResults, @@ -229,6 +231,8 @@ jest.mock('@components/Search/SearchContext', () => ({ }), })); +const mockGetExportTemplates = jest.mocked(getExportTemplates); + const CURRENT_USER_ACCOUNT_ID = 1; jest.mock('@hooks/useCurrentUserPersonalDetails', () => ({ @@ -366,6 +370,7 @@ describe('useSearchBulkActions - export options', () => { mockSelectedTransactions = {}; mockSelectedReports = []; mockCurrentSearchResults = undefined; + mockAreAllMatchingItemsSelected = false; await Onyx.merge(ONYXKEYS.SESSION, {accountID: CURRENT_USER_ACCOUNT_ID, email: 'test@example.com'}); // A policy connected to NetSuite so the integration export branch is reachable. @@ -486,4 +491,138 @@ describe('useSearchBulkActions - export options', () => { expect(getExportOptionTexts(result.current.headerButtonsOptions)).toEqual(['export.currentView']); }); }); + + describe('Canadian Multiple Tax Export eligibility', () => { + const SECOND_POLICY_ID = 'policy2'; + const SECOND_REPORT_ID = 'report2'; + + /** The includeMultipleTaxExport argument getExportTemplates was last called with */ + function getIncludeMultipleTaxExportArgument() { + return mockGetExportTemplates.mock.calls.at(-1)?.at(7); + } + + beforeEach(async () => { + await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${POLICY_ID}`, {outputCurrency: CONST.CURRENCY.CAD}); + }); + + it('offers the template when every selected workspace outputs in CAD, even across several workspaces', async () => { + await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${SECOND_POLICY_ID}`, {id: SECOND_POLICY_ID, outputCurrency: CONST.CURRENCY.CAD}); + + mockCurrentSearchResults = makeSearchResults([makeSnapshotReport()]); + mockSelectedReports = [makeSelectedReport(), makeSelectedReport({reportID: SECOND_REPORT_ID, policyID: SECOND_POLICY_ID})]; + mockSelectedTransactions = { + tx1: makeSelectedTransaction(), + tx2: makeSelectedTransaction({reportID: SECOND_REPORT_ID, policyID: SECOND_POLICY_ID}), + }; + + renderHook(() => useSearchBulkActions({queryJSON: expenseReportQueryJSON}), {wrapper: OnyxListItemProvider}); + + await waitFor(() => { + expect(getIncludeMultipleTaxExportArgument()).toBe(true); + }); + }); + + it('hides the template when a transaction from a non-CAD workspace is selected alongside a CAD report', async () => { + await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${SECOND_POLICY_ID}`, {id: SECOND_POLICY_ID, outputCurrency: CONST.CURRENCY.USD}); + + mockCurrentSearchResults = makeSearchResults([makeSnapshotReport()]); + // Only the CAD report is fully selected, but an extra transaction from a USD workspace is part of the same export request + mockSelectedReports = [makeSelectedReport()]; + mockSelectedTransactions = { + tx1: makeSelectedTransaction(), + tx2: makeSelectedTransaction({reportID: SECOND_REPORT_ID, policyID: SECOND_POLICY_ID}), + }; + + renderHook(() => useSearchBulkActions({queryJSON: expenseReportQueryJSON}), {wrapper: OnyxListItemProvider}); + + await waitFor(() => { + expect(mockGetExportTemplates).toHaveBeenCalled(); + }); + expect(getIncludeMultipleTaxExportArgument()).toBe(false); + }); + + it('hides the template when a self DM expense is selected alongside a CAD workspace expense', async () => { + const expenseQueryJSON: SearchQueryJSON = { + ...expenseReportQueryJSON, + inputQuery: 'type:expense status:all', + type: CONST.SEARCH.DATA_TYPES.EXPENSE, + }; + + mockCurrentSearchResults = makeSearchResults([makeSnapshotReport()]); + mockSelectedReports = []; + mockSelectedTransactions = { + // A self DM expense sits outside any workspace, so its selection entry carries no policyID + selfDMTx: makeSelectedTransaction({reportID: SECOND_REPORT_ID, policyID: undefined, currency: 'USD'}), + workspaceTx: makeSelectedTransaction(), + }; + + renderHook(() => useSearchBulkActions({queryJSON: expenseQueryJSON}), {wrapper: OnyxListItemProvider}); + + await waitFor(() => { + expect(mockGetExportTemplates).toHaveBeenCalled(); + }); + expect(getIncludeMultipleTaxExportArgument()).toBe(false); + }); + + /** A query scoped to the given workspaces, as "Select all matching" would export it. */ + function policyScopedQueryJSON(policyIDs: string[]): SearchQueryJSON { + return { + ...expenseReportQueryJSON, + flatFilters: [ + { + key: CONST.SEARCH.SYNTAX_FILTER_KEYS.POLICY_ID, + filters: policyIDs.map((policyID) => ({operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, value: policyID})), + }, + ], + } as SearchQueryJSON; + } + + it('offers the template under select all when the query is scoped to CAD workspaces only', async () => { + await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${SECOND_POLICY_ID}`, {id: SECOND_POLICY_ID, outputCurrency: CONST.CURRENCY.CAD}); + mockAreAllMatchingItemsSelected = true; + + mockCurrentSearchResults = makeSearchResults([makeSnapshotReport()]); + mockSelectedReports = [makeSelectedReport()]; + mockSelectedTransactions = {tx1: makeSelectedTransaction()}; + + renderHook(() => useSearchBulkActions({queryJSON: policyScopedQueryJSON([POLICY_ID, SECOND_POLICY_ID])}), {wrapper: OnyxListItemProvider}); + + await waitFor(() => { + expect(getIncludeMultipleTaxExportArgument()).toBe(true); + }); + }); + + it('hides the template under select all when a workspace in the query scope is not CAD', async () => { + await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${SECOND_POLICY_ID}`, {id: SECOND_POLICY_ID, outputCurrency: CONST.CURRENCY.USD}); + mockAreAllMatchingItemsSelected = true; + + mockCurrentSearchResults = makeSearchResults([makeSnapshotReport()]); + // The loaded rows are all CAD, but the query also matches a USD workspace that hasn't been loaded yet + mockSelectedReports = [makeSelectedReport()]; + mockSelectedTransactions = {tx1: makeSelectedTransaction()}; + + renderHook(() => useSearchBulkActions({queryJSON: policyScopedQueryJSON([POLICY_ID, SECOND_POLICY_ID])}), {wrapper: OnyxListItemProvider}); + + await waitFor(() => { + expect(mockGetExportTemplates).toHaveBeenCalled(); + }); + expect(getIncludeMultipleTaxExportArgument()).toBe(false); + }); + + it('hides the template under select all when the query is not scoped to any workspace', async () => { + mockAreAllMatchingItemsSelected = true; + + mockCurrentSearchResults = makeSearchResults([makeSnapshotReport()]); + // Every loaded row is CAD, but an unscoped query can still match a non-CAD workspace further down the results + mockSelectedReports = [makeSelectedReport()]; + mockSelectedTransactions = {tx1: makeSelectedTransaction()}; + + renderHook(() => useSearchBulkActions({queryJSON: expenseReportQueryJSON}), {wrapper: OnyxListItemProvider}); + + await waitFor(() => { + expect(mockGetExportTemplates).toHaveBeenCalled(); + }); + expect(getIncludeMultipleTaxExportArgument()).toBe(false); + }); + }); });