diff --git a/src/CONST/index.ts b/src/CONST/index.ts index bfe437cfd0b4..dfae7df38b4c 100644 --- a/src/CONST/index.ts +++ b/src/CONST/index.ts @@ -10636,6 +10636,7 @@ const CONST = { EFFICIENCY: 'insightsEfficiency', COMPLIANCE: 'insightsCompliance', }, + NO_CHANGE_PLACEHOLDER: '—', GRAPH: { SPEND_OVER_TIME: 'spendOverTime', VIOLATIONS_OVER_TIME: 'violationsOverTime', diff --git a/src/components/Charts/utils/formatChartCount.ts b/src/components/Charts/utils/formatChartCount.ts index f38842c5c0dd..85ae6f11a0c7 100644 --- a/src/components/Charts/utils/formatChartCount.ts +++ b/src/components/Charts/utils/formatChartCount.ts @@ -11,6 +11,12 @@ const COUNT_TRANSLATION_KEYS = { [CONST.SEARCH.CHART_COUNT_DIMENSION.REPORT]: 'iou.reportCount', } as const satisfies Record; +/** Header of a column listing counts, e.g. "Expenses" */ +const COUNT_COLUMN_TITLE_KEYS = { + [CONST.SEARCH.CHART_COUNT_DIMENSION.EXPENSE]: 'common.expenses', + [CONST.SEARCH.CHART_COUNT_DIMENSION.REPORT]: 'common.reports', +} as const satisfies Record; + /** * Names a count of expenses or reports in the viewer's locale, e.g. "1,234.5 expenses". * The number is formatted here and passed to the translation rather than left to it, because locales whose `one` plural category also covers 0 and fractions @@ -22,4 +28,4 @@ function formatChartCount(count: number, countDimension: SearchChartCountDimensi } export default formatChartCount; -export {MAX_COUNT_FRACTION_DIGITS}; +export {COUNT_COLUMN_TITLE_KEYS, MAX_COUNT_FRACTION_DIGITS}; diff --git a/src/components/Charts/utils/formatTooltipComparison.ts b/src/components/Charts/utils/formatTooltipComparison.ts index 2d4172f2c318..daf8d9b1bff8 100644 --- a/src/components/Charts/utils/formatTooltipComparison.ts +++ b/src/components/Charts/utils/formatTooltipComparison.ts @@ -3,6 +3,7 @@ import VictoryTheme from '@components/Charts/VictoryTheme'; import {formatPercentOfTotal} from '@libs/PercentageUtils'; +import CONST from '@src/CONST'; import type Locale from '@src/types/onyx/Locale'; import type {NonEmptyTuple} from 'type-fest'; @@ -44,7 +45,7 @@ type TooltipComparison = { /** Formats how much the primary value rose or fell relative to the compared one, as a percentage */ function formatChangePercentage(primaryValue: number, comparedValue: number, locale: Locale | undefined): string { if (comparedValue === 0) { - return '—'; + return CONST.INSIGHTS.NO_CHANGE_PLACEHOLDER; } const difference = primaryValue - comparedValue; diff --git a/src/components/Search/buildChartSeries.ts b/src/components/Search/buildChartSeries.ts index 229fe3be58d9..efe7c880e08e 100644 --- a/src/components/Search/buildChartSeries.ts +++ b/src/components/Search/buildChartSeries.ts @@ -60,8 +60,14 @@ const AVERAGE_LABEL_KEYS: Partial> = { [CONST.SEARCH.GROUP_BY.FROM]: 'insightsPage.compare.allSpenderAverage', [CONST.SEARCH.GROUP_BY.MERCHANT]: 'insightsPage.compare.allMerchantAverage', [CONST.SEARCH.GROUP_BY.CATEGORY]: 'insightsPage.compare.allCategoryAverage', + [CONST.SEARCH.GROUP_BY.VIOLATION]: 'insightsPage.compare.allViolationAverage', }; +/** Returns the label naming the average a chart grouped by `groupBy` is compared against */ +function getAverageLabelKey(groupBy: SearchGroupBy): TranslationPaths { + return AVERAGE_LABEL_KEYS[groupBy] ?? 'insightsPage.compare.average'; +} + type BuildChartSeriesParams = { /** Grouped search results, in the order the search returned them */ data: GroupedItem[]; @@ -321,7 +327,7 @@ function buildChartSeries({ const primarySeries: ChartSeries = {key: CHART_SERIES_KEY.PRIMARY, label: periods && formatDates(periods.primary, dateFnsLocale)}; const comparisonSeries: ChartSeries | undefined = averageValue !== undefined - ? {key: CHART_SERIES_KEY.COMPARISON, label: translate(AVERAGE_LABEL_KEYS[groupBy] ?? 'insightsPage.compare.average'), isAverage: true} + ? {key: CHART_SERIES_KEY.COMPARISON, label: translate(getAverageLabelKey(groupBy)), isAverage: true} : comparedRows && {key: CHART_SERIES_KEY.COMPARISON, color: comparedRows.color, label: periods && formatDates(periods.comparison, dateFnsLocale)}; return { @@ -344,5 +350,5 @@ function buildChartSeries({ }; } -export {buildChartSeries, getSliceColorsByDataIndex, isChartAverage, CHART_SERIES_KEY}; +export {buildChartSeries, getAverageLabelKey, getSliceColorsByDataIndex, isChartAverage, CHART_SERIES_KEY}; export type {ChartAverage, ChartComparison, SearchChartModel}; diff --git a/src/components/Search/chartGroupByConfig.ts b/src/components/Search/chartGroupByConfig.ts index c591e3d9d61a..1609642ba367 100644 --- a/src/components/Search/chartGroupByConfig.ts +++ b/src/components/Search/chartGroupByConfig.ts @@ -139,8 +139,7 @@ const CHART_GROUP_BY_CONFIG: Record = { [CONST.SEARCH.GROUP_BY.VIOLATION]: { titleIconName: 'Exclamation', getLabel: (item: GroupedItem) => (item.groupedBy === CONST.SEARCH.GROUP_BY.VIOLATION ? item.formattedViolation : ''), - // Search has no violation type filter, so a clicked violation opens the chart's whole query - getFilterQuery: () => '', + getFilterQuery: (item: GroupedItem) => (item.groupedBy === CONST.SEARCH.GROUP_BY.VIOLATION ? `${CONST.SEARCH.SYNTAX_FILTER_KEYS.VIOLATION}:${item.violation}` : ''), }, [CONST.SEARCH.GROUP_BY.PAID_BY]: { titleIconName: 'Users', diff --git a/src/languages/de.ts b/src/languages/de.ts index 585e76be296b..7dc02421a44b 100644 --- a/src/languages/de.ts +++ b/src/languages/de.ts @@ -1248,6 +1248,9 @@ const translations: TranslationDeepObject = { allMerchantAverage: 'Durchschnitt über alle Händler', allCategoryAverage: 'Durchschnitt aller Kategorien', averageValue: (amount: string) => `${amount} durchschnittl.`, + allViolationAverage: 'Durchschnitt aller Verstöße', + noChange: 'Keine Änderung', + percentChange: '% Änderung', }, compliance: 'Compliance', runningTotal: 'Laufende Summe', @@ -1272,6 +1275,7 @@ const translations: TranslationDeepObject = { longestToSubmit: 'Am längsten bis zur Einreichung', slowestToApprove: 'Am langsamsten bei der Genehmigung', mostTimeToPay: 'Längste Zahlungsfrist', + share: 'Anteil', averageDays: 'Durchschnittliche Tage', }, allSettingsScreen: { diff --git a/src/languages/el.ts b/src/languages/el.ts index bcf221cf941a..208b64a1b769 100644 --- a/src/languages/el.ts +++ b/src/languages/el.ts @@ -1294,6 +1294,9 @@ const translations: TranslationDeepObject = { allMerchantAverage: 'Μέσος όρος όλων των εμπόρων', allCategoryAverage: 'Μέσος όρος όλων των κατηγοριών', averageValue: (amount: string) => `${amount} κατά μέσο όρο`, + allViolationAverage: 'Μέσος όρος όλων των παραβάσεων', + noChange: 'Χωρίς αλλαγή', + percentChange: '% μεταβολή', }, compliance: 'Συμμόρφωση', runningTotal: 'Τρέχον σύνολο', @@ -1318,6 +1321,7 @@ const translations: TranslationDeepObject = { longestToSubmit: 'Περισσότερος χρόνος για υποβολή', slowestToApprove: 'Πιο αργοί στην έγκριση', mostTimeToPay: 'Περισσότερος χρόνος για πληρωμή', + share: 'Μερίδιο', averageDays: 'Μέσος όρος ημερών', }, allSettingsScreen: { diff --git a/src/languages/en.ts b/src/languages/en.ts index 281462e07267..26001bee13fa 100644 --- a/src/languages/en.ts +++ b/src/languages/en.ts @@ -1380,6 +1380,8 @@ const translations = { topViolations: 'Top violations', violationsBySubmitter: 'Violations by submitter', violationsByApprover: 'Violations by approver', + // @context Column header for each group's portion of the total, as a percentage. A noun, not the verb "to share". + share: 'Share', efficiency: 'Efficiency', workflowEfficiency: 'Workflow efficiency', averageProcessingTime: 'Average processing time', @@ -1400,12 +1402,15 @@ const translations = { allSpenderAverage: 'All-spender average', allMerchantAverage: 'All-merchant average', allCategoryAverage: 'All-category average', + allViolationAverage: 'All-violation average', averageValue: (amount: string) => `${amount} avg`, dayLabel: (day?: number) => (day === undefined ? 'Day' : `Day ${day}`), weekLabel: (week?: number) => (week === undefined ? 'Week' : `Week ${week}`), monthLabel: (month?: number) => (month === undefined ? 'Month' : `Month ${month}`), quarterLabel: (quarter?: number) => (quarter === undefined ? 'Quarter' : `Quarter ${quarter}`), yearLabel: (year?: number) => (year === undefined ? 'Year' : `Year ${year}`), + noChange: 'No change', + percentChange: '% change', increase: (percentage: string) => `Up ${percentage}`, decrease: (percentage: string) => `Down ${percentage}`, }, diff --git a/src/languages/es.ts b/src/languages/es.ts index 5e4ea5181b01..98d15271cd4a 100644 --- a/src/languages/es.ts +++ b/src/languages/es.ts @@ -1242,6 +1242,9 @@ const translations: TranslationDeepObject = { allMerchantAverage: 'Promedio de todos los comercios', allCategoryAverage: 'Promedio de todas las categorías', averageValue: (amount: string) => `${amount} prom de media`, + allViolationAverage: 'Media de todas las infracciones', + noChange: 'Sin cambios', + percentChange: '% de cambio', }, compliance: 'Cumplimiento', runningTotal: 'Total acumulado', @@ -1266,6 +1269,7 @@ const translations: TranslationDeepObject = { longestToSubmit: 'Más lento en enviar', slowestToApprove: 'Más lento en aprobar', mostTimeToPay: 'Más tiempo para pagar', + share: 'Porcentaje de participación', averageDays: 'Días promedio', }, allSettingsScreen: { diff --git a/src/languages/fr.ts b/src/languages/fr.ts index edaa9039a0f1..5ffd204ba14e 100644 --- a/src/languages/fr.ts +++ b/src/languages/fr.ts @@ -1255,6 +1255,9 @@ const translations: TranslationDeepObject = { allMerchantAverage: 'Moyenne tous marchands', allCategoryAverage: 'Moyenne toutes catégories', averageValue: (amount: string) => `${amount} en moyenne`, + allViolationAverage: 'Moyenne de toutes les infractions', + noChange: 'Aucun changement', + percentChange: '% de changement', }, compliance: 'Conformité', runningTotal: 'Total cumulé', @@ -1279,6 +1282,7 @@ const translations: TranslationDeepObject = { longestToSubmit: 'Le plus long à soumettre', slowestToApprove: 'Plus lent à approuver', mostTimeToPay: 'Délai de paiement le plus long', + share: 'Part de la part totale (%)', averageDays: 'Jours en moyenne', }, allSettingsScreen: { diff --git a/src/languages/it.ts b/src/languages/it.ts index b82fab94497e..5e32e8cfd880 100644 --- a/src/languages/it.ts +++ b/src/languages/it.ts @@ -1251,6 +1251,9 @@ const translations: TranslationDeepObject = { allMerchantAverage: 'Media tutti gli esercenti', allCategoryAverage: 'Media di tutte le categorie', averageValue: (amount: string) => `${amount} in media`, + allViolationAverage: 'Media di tutte le violazioni', + noChange: 'Nessuna modifica', + percentChange: '% variazione', }, compliance: 'Conformità', runningTotal: 'Totale progressivo', @@ -1275,6 +1278,7 @@ const translations: TranslationDeepObject = { longestToSubmit: 'Più lungo per l’invio', slowestToApprove: 'I più lenti ad approvare', mostTimeToPay: 'Tempo massimo per pagare', + share: 'Quota%', averageDays: 'Giorni medi', }, allSettingsScreen: { diff --git a/src/languages/ja.ts b/src/languages/ja.ts index 3c03e32069dd..d44777da6ebb 100644 --- a/src/languages/ja.ts +++ b/src/languages/ja.ts @@ -1236,6 +1236,9 @@ const translations: TranslationDeepObject = { allMerchantAverage: '全加盟店の平均', allCategoryAverage: '全カテゴリ平均', averageValue: (amount: string) => `平均 ${amount}`, + allViolationAverage: 'すべての違反の平均', + noChange: '変更なし', + percentChange: '% 変化', }, compliance: 'コンプライアンス', runningTotal: '累計合計', @@ -1260,6 +1263,7 @@ const translations: TranslationDeepObject = { longestToSubmit: '提出まで最も長い順', slowestToApprove: '承認が最も遅い', mostTimeToPay: '支払いまで最も時間がかかる', + share: 'シェア割合', averageDays: '平均日数', }, allSettingsScreen: { diff --git a/src/languages/nl.ts b/src/languages/nl.ts index bdf3f33a6912..0257381a59d7 100644 --- a/src/languages/nl.ts +++ b/src/languages/nl.ts @@ -1247,6 +1247,9 @@ const translations: TranslationDeepObject = { allMerchantAverage: 'Gemiddelde voor alle handelaren', allCategoryAverage: 'Gemiddelde voor alle categorieën', averageValue: (amount: string) => `${amount} gem.`, + allViolationAverage: 'Gemiddelde over alle overtredingen', + noChange: 'Geen wijziging', + percentChange: '% wijziging', }, compliance: 'Naleving', runningTotal: 'Doorlopend totaal', @@ -1271,6 +1274,7 @@ const translations: TranslationDeepObject = { longestToSubmit: 'Langste om in te dienen', slowestToApprove: 'Traagst om goed te keuren', mostTimeToPay: 'Meeste tijd om te betalen', + share: 'Aandeel', averageDays: 'Gemiddeld aantal dagen', }, allSettingsScreen: { diff --git a/src/languages/pl.ts b/src/languages/pl.ts index ad6f08c909ba..7bc5054c957c 100644 --- a/src/languages/pl.ts +++ b/src/languages/pl.ts @@ -1274,6 +1274,9 @@ const translations: TranslationDeepObject = { allMerchantAverage: 'Średnia dla wszystkich sprzedawców', allCategoryAverage: 'Średnia dla wszystkich kategorii', averageValue: (amount: string) => `średnio ${amount}`, + allViolationAverage: 'Średnia wszystkich naruszeń', + noChange: 'Bez zmian', + percentChange: '% zmiana', }, compliance: 'Zgodność', runningTotal: 'Suma narastająco', @@ -1298,6 +1301,7 @@ const translations: TranslationDeepObject = { longestToSubmit: 'Najdłużej oczekujące na wysłanie', slowestToApprove: 'Najwolniejszy w zatwierdzaniu', mostTimeToPay: 'Najdłuższy czas na zapłatę', + share: 'Udział', averageDays: 'Średnia liczba dni', }, allSettingsScreen: { diff --git a/src/languages/pt-BR.ts b/src/languages/pt-BR.ts index 9a2e58548031..97a89a8a857b 100644 --- a/src/languages/pt-BR.ts +++ b/src/languages/pt-BR.ts @@ -1250,6 +1250,9 @@ const translations: TranslationDeepObject = { allMerchantAverage: 'Média de todos os estabelecimentos', allCategoryAverage: 'Média de todas as categorias', averageValue: (amount: string) => `${amount} média`, + allViolationAverage: 'Média de todas as violações', + noChange: 'Sem alteração', + percentChange: '% de mudança', }, compliance: 'Conformidade', runningTotal: 'Total acumulado', @@ -1274,6 +1277,7 @@ const translations: TranslationDeepObject = { longestToSubmit: 'Mais demorados para enviar', slowestToApprove: 'Mais lento para aprovar', mostTimeToPay: 'Maior prazo para pagar', + share: 'Participação', averageDays: 'Média de dias', }, allSettingsScreen: { diff --git a/src/languages/zh-hans.ts b/src/languages/zh-hans.ts index 6e7f18682e13..bfd627991534 100644 --- a/src/languages/zh-hans.ts +++ b/src/languages/zh-hans.ts @@ -1201,6 +1201,9 @@ const translations: TranslationDeepObject = { allMerchantAverage: '所有商户平均值', allCategoryAverage: '所有类别平均值', averageValue: (amount: string) => `${amount} 平均`, + allViolationAverage: '所有违规平均值', + noChange: '无更改', + percentChange: '百分比变动', }, compliance: '合规', runningTotal: '累计总额', @@ -1221,6 +1224,7 @@ const translations: TranslationDeepObject = { longestToSubmit: '提交所用时间最长', slowestToApprove: '审批最慢', mostTimeToPay: '最长付款时间', + share: '占比', averageDays: '平均天数', }, allSettingsScreen: { diff --git a/src/pages/Insights/InsightsChangeBadge.tsx b/src/pages/Insights/InsightsChangeBadge.tsx new file mode 100644 index 000000000000..49e1f49bd4ef --- /dev/null +++ b/src/pages/Insights/InsightsChangeBadge.tsx @@ -0,0 +1,43 @@ +import Badge from '@components/Badge'; + +import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset'; +import useLocalize from '@hooks/useLocalize'; +import useThemeStyles from '@hooks/useThemeStyles'; + +import type {StyleProp, ViewStyle} from 'react-native'; + +import React from 'react'; +import {View} from 'react-native'; + +type InsightsChangeBadgeProps = { + text: string; + + isIncrease: boolean; + + style?: StyleProp; +}; + +/** Badge showing how a value changed, with an arrow when it went up or down */ +function InsightsChangeBadge({text, isIncrease, style}: InsightsChangeBadgeProps) { + const styles = useThemeStyles(); + const {translate} = useLocalize(); + const icons = useMemoizedLazyExpensifyIcons(['ArrowUpLong', 'ArrowDownLong']); + + return ( + + + + ); +} + +export default InsightsChangeBadge; diff --git a/src/pages/Insights/InsightsDashboard.tsx b/src/pages/Insights/InsightsDashboard.tsx index f78244726ad3..47b2695fc264 100644 --- a/src/pages/Insights/InsightsDashboard.tsx +++ b/src/pages/Insights/InsightsDashboard.tsx @@ -72,7 +72,7 @@ type InsightsDashboardContentProps = { headlineChart: InsightsDashboardChart; - /** Charts in the grid below the headline, left out when no workspace in scope is eligible for them */ + /** Charts below the headline, left out when no workspace in scope is eligible for them */ supportingCharts: InsightsDashboardChart[]; /** Page-level filters every chart on the dashboard is narrowed by */ @@ -94,6 +94,25 @@ type InsightsDashboardContentProps = { children?: React.ReactNode; }; +/** Splits the charts into sections: a full-width chart on its own, or the charts between two full-width ones, which share a two-column grid */ +function getDashboardSections(charts: InsightsDashboardChart[], shouldUseNarrowLayout: boolean): Array { + const isGridChart = (chart: InsightsDashboardChart | undefined) => !!chart && !chart.chart.isFullWidth; + const isAloneInGrid = (index: number) => isGridChart(charts.at(index)) && (index === 0 || !isGridChart(charts.at(index - 1))) && !isGridChart(charts.at(index + 1)); + // A two-column grid with one chart leaves half a row empty, so on wide layouts that chart moves to the bottom, where the gap ends the page + const orderedCharts = shouldUseNarrowLayout ? charts : [...charts.filter((chart, index) => !isAloneInGrid(index)), ...charts.filter((chart, index) => isAloneInGrid(index))]; + + const sections: Array = []; + for (const chart of orderedCharts) { + const lastSection = sections.at(-1); + if (!chart.chart.isFullWidth && Array.isArray(lastSection)) { + lastSection.push(chart); + } else { + sections.push(chart.chart.isFullWidth ? chart : [chart]); + } + } + return sections; +} + function InsightsDashboardContent({ dashboardID, state, @@ -219,8 +238,46 @@ function InsightsDashboardContent({ ); } - // Wide layout stacks the cards in two independent columns, so a short card doesn't leave a gap under it - const columns = shouldUseNarrowLayout ? [supportingCharts] : [supportingCharts.filter((chart, index) => index % 2 === 0), supportingCharts.filter((chart, index) => index % 2 === 1)]; + const renderChart = ({chart, queryJSON, snapshot, previousPeriodQueryJSON, previousPeriodSnapshot, average, isDashboardLoaded}: InsightsDashboardChart, isHeadline = false) => ( + + ); + + const renderGrid = (gridCharts: InsightsDashboardChart[]) => { + // Wide layout stacks the cards in two independent columns, so a short card doesn't leave a gap under it + const columns = shouldUseNarrowLayout ? [gridCharts] : [gridCharts.filter((chart, index) => index % 2 === 0), gridCharts.filter((chart, index) => index % 2 === 1)]; + return ( + + {columns.map((columnCharts, columnIndex) => ( + + {columnCharts.map((chart) => renderChart(chart))} + + ))} + + ); + }; return ( @@ -245,50 +302,8 @@ function InsightsDashboardContent({ hasFailedToLoad={hasFailedToLoad} /> )} - - - {columns.map((columnCharts, columnIndex) => ( - - {columnCharts.map(({chart, queryJSON, snapshot, previousPeriodQueryJSON, previousPeriodSnapshot, average, isDashboardLoaded}) => ( - - ))} - - ))} - + {renderChart(headlineChart, true)} + {getDashboardSections(supportingCharts, shouldUseNarrowLayout).map((section) => (Array.isArray(section) ? renderGrid(section) : renderChart(section)))} diff --git a/src/pages/Insights/ai/InsightsAIChip.tsx b/src/pages/Insights/ai/InsightsAIChip.tsx index 6f0bb9114077..a71a344895b4 100644 --- a/src/pages/Insights/ai/InsightsAIChip.tsx +++ b/src/pages/Insights/ai/InsightsAIChip.tsx @@ -9,11 +9,12 @@ import useThemeStyles from '@hooks/useThemeStyles'; import {convertToShortDisplayString} from '@libs/CurrencyUtils'; import DateUtils from '@libs/DateUtils'; +import InsightsChangeBadge from '@pages/Insights/InsightsChangeBadge'; + import CONST from '@src/CONST'; import type {AIInsightChip} from '@src/types/onyx'; import React from 'react'; -import {View} from 'react-native'; type InsightsAIChipProps = { chip: AIInsightChip; @@ -25,7 +26,7 @@ function InsightsAIChip({chip}: InsightsAIChipProps) { const theme = useTheme(); const StyleUtils = useStyleUtils(); const {translate, numberFormat} = useLocalize(); - const icons = useMemoizedLazyExpensifyIcons(['ArrowUpLong', 'ArrowDownLong', 'Coins', 'Clock', 'Flag']); + const icons = useMemoizedLazyExpensifyIcons(['Coins', 'Clock', 'Flag']); let value: string; let neutralIcon = icons.Coins; @@ -57,22 +58,12 @@ function InsightsAIChip({chip}: InsightsAIChipProps) { ); } - const isIncrease = chip.direction === CONST.INSIGHTS.AI_INSIGHT.CHIP_DIRECTION.INCREASE; - return ( - - - + /> ); } diff --git a/src/pages/Insights/buildInsightsChartCSV.ts b/src/pages/Insights/buildInsightsChartCSV.ts index f47bf7c394b8..4de858827e51 100644 --- a/src/pages/Insights/buildInsightsChartCSV.ts +++ b/src/pages/Insights/buildInsightsChartCSV.ts @@ -1,4 +1,5 @@ /** Builds a CSV from the current period's loaded chart groups, without exporting individual expenses. */ +import {COUNT_COLUMN_TITLE_KEYS} from '@components/Charts/utils/formatChartCount'; import type {LocalizedTranslate} from '@components/LocaleContextProvider'; import CHART_GROUP_BY_CONFIG from '@components/Search/chartGroupByConfig'; import {getAverageDuration} from '@components/Search/chartMetricValue'; @@ -52,7 +53,7 @@ function buildInsightsChartCSV({ }: BuildInsightsChartCSVParams): string { const {getLabel, getDateRange} = CHART_GROUP_BY_CONFIG[groupBy]; const groupHeader = translate(GROUP_HEADER_KEYS[groupBy] ?? 'common.date'); - const countHeader = translate(countDimension === CONST.SEARCH.CHART_COUNT_DIMENSION.REPORT ? 'common.reports' : 'common.expenses'); + const countHeader = translate(COUNT_COLUMN_TITLE_KEYS[countDimension]); const isDurationMetric = metric === CONST.SEARCH.CHART_METRIC.DURATION; const valueHeaders = isDurationMetric ? [translate('insightsPage.averageDays')] : [translate('common.total'), translate('common.currency')]; const header = [groupHeader, countHeader, ...valueHeaders].map(escapeCsvField).join(','); diff --git a/src/pages/Insights/charts/InsightsChartWidget.tsx b/src/pages/Insights/charts/InsightsChartWidget.tsx index 348b397d3eec..965e43c222a0 100644 --- a/src/pages/Insights/charts/InsightsChartWidget.tsx +++ b/src/pages/Insights/charts/InsightsChartWidget.tsx @@ -45,6 +45,7 @@ import {View} from 'react-native'; import Animated, {FadeIn} from 'react-native-reanimated'; import InsightsDataTable from './InsightsDataTable'; +import InsightsRankingTable from './InsightsRankingTable'; type InsightsChartWidgetProps = { dashboardID: InsightsDashboardID; @@ -227,40 +228,53 @@ function InsightsChartWidget({ {state === INSIGHTS_CHART_STATE.OFFLINE && } {state === INSIGHTS_CHART_STATE.ERROR && } {state === INSIGHTS_CHART_STATE.EMPTY && } - {(state === INSIGHTS_CHART_STATE.LOADING || state === INSIGHTS_CHART_STATE.READY) && ( - - {translate('insightsPage.viewDetails')} : undefined} - renderDetails={ - shouldShowTable - ? ({rows, formatValue}) => ( - - ) - : undefined - } + isComparingPreviousPeriod={filters.compare === CONST.SEARCH.COMPARE.PREVIOUS_PERIOD} + queryJSON={queryJSON} + isLoading={isLoading} /> - - )} + ) : ( + + {translate('insightsPage.viewDetails')} : undefined} + renderDetails={ + shouldShowTable + ? ({rows, formatValue}) => ( + + ) + : undefined + } + /> + + ))} ); diff --git a/src/pages/Insights/charts/InsightsDataTableSkeleton.tsx b/src/pages/Insights/charts/InsightsDataTableSkeleton.tsx index 48fe49a1863d..2d24e54bc93b 100644 --- a/src/pages/Insights/charts/InsightsDataTableSkeleton.tsx +++ b/src/pages/Insights/charts/InsightsDataTableSkeleton.tsx @@ -23,42 +23,54 @@ const AMOUNT_WIDTH = 80; type InsightsDataTableSkeletonProps = { /** How many rows to draw. */ fixedNumItems: number; + + /** Whether each row starts with a circle, standing in for the color dot or avatar the table's rows begin with. Defaults to true. */ + shouldShowIndicator?: boolean; + + /** Height of each row, matching the table's own rows so nothing moves when the data lands. The bars are centered in it. Defaults to a chart table's row. */ + rowHeight?: number; + + /** Space above the first row, matching what the table draws there, like its header. Defaults to a chart table's top margin. */ + topOffset?: number; }; -function InsightsDataTableSkeleton({fixedNumItems}: InsightsDataTableSkeletonProps) { +function InsightsDataTableSkeleton({fixedNumItems, shouldShowIndicator = true, rowHeight, topOffset}: InsightsDataTableSkeletonProps) { const styles = useThemeStyles(); const {onLayout, containerWidth} = useContainerWidth(); const {values} = useLayoutSpacing(); const rowPaddingX = values.cardPadding; - const textStartX = rowPaddingX + INDICATOR_SIZE + INDICATOR_GAP_X; + const barOffsetY = rowHeight === undefined ? BAR_OFFSET_Y : (rowHeight - BAR_HEIGHT) / 2; + const textStartX = shouldShowIndicator ? rowPaddingX + INDICATOR_SIZE + INDICATOR_GAP_X : rowPaddingX; const amountX = Math.max(containerWidth - rowPaddingX - AMOUNT_WIDTH, textStartX + LABEL_WIDTH + AMOUNT_GAP_X); return ( ( <> + {shouldShowIndicator && ( + + )} - diff --git a/src/pages/Insights/charts/InsightsRankingTable.tsx b/src/pages/Insights/charts/InsightsRankingTable.tsx new file mode 100644 index 000000000000..b27dff868a9f --- /dev/null +++ b/src/pages/Insights/charts/InsightsRankingTable.tsx @@ -0,0 +1,262 @@ +import formatChartCount, {COUNT_COLUMN_TITLE_KEYS} from '@components/Charts/utils/formatChartCount'; +import type {ChartComparison} from '@components/Search/buildChartSeries'; +import {getAverageLabelKey} from '@components/Search/buildChartSeries'; +import {SortableHeaderLabel} from '@components/Search/SortableHeaderText'; +import type {GroupedItem, SearchChartCountDimension, SearchGroupBy, SearchQueryJSON} from '@components/Search/types'; +import { + getColumnHeaderAccessibilityProps, + getRowAccessibilityProps, + getRowGroupAccessibilityProps, + getTableContainerAccessibilityProps, + shouldUseTableSemantics, +} from '@components/Table/tableAccessibility'; +import Text from '@components/Text'; + +import useLayoutSpacing from '@hooks/useLayoutSpacing'; +import useLocalize from '@hooks/useLocalize'; +import useResponsiveLayout from '@hooks/useResponsiveLayout'; +import useStyleUtils from '@hooks/useStyleUtils'; +import useTheme from '@hooks/useTheme'; +import useThemeStyles from '@hooks/useThemeStyles'; + +import variables from '@styles/variables'; + +import CONST from '@src/CONST'; + +import React from 'react'; +import {StyleSheet, View} from 'react-native'; + +import buildRankingTableRows from './buildRankingTableRows'; +import InsightsDataTableSkeleton from './InsightsDataTableSkeleton'; +import InsightsRankingTableAverageLine from './InsightsRankingTableAverageLine'; +import InsightsRankingTableAverageMarker from './InsightsRankingTableAverageMarker'; +import InsightsRankingTableRow, {RANKING_TABLE_COLUMN} from './InsightsRankingTableRow'; + +const AVERAGE_FRACTION_DIGITS = 1; + +type InsightsRankingTableProps = { + /** Names the table to screen readers */ + title: string; + + /** The listed groups, sorted by count, most first */ + data: GroupedItem[]; + + /** What the rows are grouped by, which names the first column and labels each row */ + groupBy: SearchGroupBy; + + /** What each group's count counts. Defaults to expenses. */ + countDimension?: SearchChartCountDimension; + + /** The most rows the table lists, which the loading skeleton shows */ + rowLimit?: number; + + comparison: ChartComparison | undefined; + + /** Whether the page compares against the previous period, which adds the change column */ + isComparingPreviousPeriod: boolean; + + /** The chart's query, which a pressed row opens on Spend */ + queryJSON: Readonly | undefined; + + isLoading?: boolean; +}; + +/** Table of the groups with the highest count, with each group's share drawn as a bar, its count, its amount and, when comparing, how it changed. */ +function InsightsRankingTable({ + title, + data, + groupBy, + countDimension = CONST.SEARCH.CHART_COUNT_DIMENSION.EXPENSE, + rowLimit, + comparison, + isComparingPreviousPeriod, + queryJSON, + isLoading, +}: InsightsRankingTableProps) { + const theme = useTheme(); + const styles = useThemeStyles(); + const StyleUtils = useStyleUtils(); + const {translate, numberFormat} = useLocalize(); + const {cardPadding, cardPaddingHorizontal, cardPaddingBottom} = useLayoutSpacing(); + const {shouldUseNarrowLayout} = useResponsiveLayout(); + + if (isLoading) { + // The column headers: a label line, its padding and the divider below + const headerHeight = variables.tableHeaderContentHeight + 2 * styles.pv2.paddingVertical + variables.borderTopWidth; + // A narrow row: its padding, the name and count lines with the gap between, the gap above the bar, the bar and the divider + const narrowRowHeight = + 2 * variables.tableRowPaddingVerticalCompact + + variables.fontSizeNormalHeight + + styles.gap1.gap + + variables.lineHeightNormal + + styles.gap3.gap + + variables.insightsRankingTableBarHeight + + variables.borderTopWidth; + + return ( + + + + ); + } + + const {rows, average, averageWidthPercent} = buildRankingTableRows({data, comparison, isComparingPreviousPeriod}); + if (rows.length === 0) { + return null; + } + + const formatCount = (count: number) => formatChartCount(count, countDimension, translate, numberFormat); + + const roundedAverage = average === undefined ? undefined : Math.round(average * 10 ** AVERAGE_FRACTION_DIGITS) / 10 ** AVERAGE_FRACTION_DIGITS; + const formattedAverage = roundedAverage === undefined ? undefined : numberFormat(roundedAverage, {maximumFractionDigits: AVERAGE_FRACTION_DIGITS}); + + if (shouldUseNarrowLayout) { + return ( + + {rows.map((row, index) => ( + + ))} + {!!formattedAverage && ( + + + + {`${translate(getAverageLabelKey(groupBy))}: ${formatCount(roundedAverage ?? 0)}`} + + + )} + + ); + } + + const isTableSemanticsEnabled = shouldUseTableSemantics(shouldUseNarrowLayout); + const headerLabelStyle = [styles.tableHeaderContentHeight, styles.pv2]; + const columnCount = isComparingPreviousPeriod ? RANKING_TABLE_COLUMN.CHANGE : RANKING_TABLE_COLUMN.AMOUNT; + + return ( + + + + + + + + + + + + + + + + + + {isComparingPreviousPeriod && ( + + + + )} + + + {rows.map((row, index) => ( + + ))} + + {!!formattedAverage && averageWidthPercent !== undefined && ( + // Laid out like the rows, so one unbroken line runs over every bar at the average + + + + + + + + {translate('insightsPage.compare.averageValue', formattedAverage)} + + + + + + + + + + )} + + + ); +} + +export default InsightsRankingTable; diff --git a/src/pages/Insights/charts/InsightsRankingTableAverageLine.tsx b/src/pages/Insights/charts/InsightsRankingTableAverageLine.tsx new file mode 100644 index 000000000000..c14cef6021db --- /dev/null +++ b/src/pages/Insights/charts/InsightsRankingTableAverageLine.tsx @@ -0,0 +1,49 @@ +import VictoryTheme, {DASH_INTERVALS} from '@components/Charts/VictoryTheme'; + +import useTheme from '@hooks/useTheme'; +import useThemeStyles from '@hooks/useThemeStyles'; + +import type {StyleProp, ViewStyle} from 'react-native'; + +import React from 'react'; +import {View} from 'react-native'; +import Svg, {Line} from 'react-native-svg'; + +// Snaps the line to whole pixels, since the average rarely falls on one and a 1px line between two pixels is drawn blurred and paler. +// react-native-svg leaves the attribute out of its types but passes it to the DOM on web. +const CRISP_EDGES_PROPS: Record = {shapeRendering: 'crispEdges'}; + +type InsightsRankingTableAverageLineProps = { + style?: StyleProp; +}; + +/** Vertical dashed line marking the average through a ranking table, drawn like the average line in charts */ +function InsightsRankingTableAverageLine({style}: InsightsRankingTableAverageLineProps) { + const theme = useTheme(); + const styles = useThemeStyles(); + const {strokeWidth, opacity} = VictoryTheme.averageLine; + + return ( + + + + + + ); +} + +export default InsightsRankingTableAverageLine; diff --git a/src/pages/Insights/charts/InsightsRankingTableAverageMarker.tsx b/src/pages/Insights/charts/InsightsRankingTableAverageMarker.tsx new file mode 100644 index 000000000000..4dafe58fccb8 --- /dev/null +++ b/src/pages/Insights/charts/InsightsRankingTableAverageMarker.tsx @@ -0,0 +1,43 @@ +import useThemeStyles from '@hooks/useThemeStyles'; + +import colors from '@styles/theme/colors'; +import variables from '@styles/variables'; + +import type {StyleProp, ViewStyle} from 'react-native'; + +import React from 'react'; +import {View} from 'react-native'; +import Svg, {Line} from 'react-native-svg'; + +const DASH_INTERVALS = [4, 4]; + +type InsightsRankingTableAverageMarkerProps = { + style?: StyleProp; +}; + +/** Short vertical dashed mark showing the average across a narrow ranking table row's bar, and in its legend */ +function InsightsRankingTableAverageMarker({style}: InsightsRankingTableAverageMarkerProps) { + const styles = useThemeStyles(); + const width = variables.insightsRankingTableAverageMarkerWidth; + + return ( + + + + + + ); +} + +export default InsightsRankingTableAverageMarker; diff --git a/src/pages/Insights/charts/InsightsRankingTableChange.tsx b/src/pages/Insights/charts/InsightsRankingTableChange.tsx new file mode 100644 index 000000000000..f796b64a489f --- /dev/null +++ b/src/pages/Insights/charts/InsightsRankingTableChange.tsx @@ -0,0 +1,71 @@ +import type {LocaleContextProps} from '@components/LocaleContextProvider'; +import Text from '@components/Text'; + +import useLocalize from '@hooks/useLocalize'; +import useThemeStyles from '@hooks/useThemeStyles'; + +import InsightsChangeBadge from '@pages/Insights/InsightsChangeBadge'; + +import CONST from '@src/CONST'; + +import React from 'react'; + +import type {RankingTableChange} from './buildRankingTableRows'; + +import {RANKING_TABLE_CHANGE} from './buildRankingTableRows'; + +type InsightsRankingTableChangeProps = { + change: RankingTableChange; +}; + +function formatRankingTableChange(change: RankingTableChange, translate: LocaleContextProps['translate'], numberFormat: LocaleContextProps['numberFormat']) { + if (change.type === RANKING_TABLE_CHANGE.NONE) { + return { + text: CONST.INSIGHTS.NO_CHANGE_PLACEHOLDER, + accessibilityLabel: translate('insightsPage.compare.noChange'), + }; + } + if (change.type === RANKING_TABLE_CHANGE.NEW) { + return { + text: CONST.INSIGHTS.NO_CHANGE_PLACEHOLDER, + accessibilityLabel: translate('common.new'), + }; + } + const text = numberFormat(change.percent / 100, { + style: 'percent', + maximumFractionDigits: 0, + }); + return { + text, + accessibilityLabel: translate(change.type === RANKING_TABLE_CHANGE.INCREASE ? 'insightsPage.compare.increase' : 'insightsPage.compare.decrease', text), + }; +} + +/** How a ranking table row's count changed against the previous period */ +function InsightsRankingTableChange({change}: InsightsRankingTableChangeProps) { + const styles = useThemeStyles(); + const {translate, numberFormat} = useLocalize(); + const {text, accessibilityLabel} = formatRankingTableChange(change, translate, numberFormat); + + if (change.type === RANKING_TABLE_CHANGE.NONE || change.type === RANKING_TABLE_CHANGE.NEW) { + return ( + + {text} + + ); + } + + return ( + + ); +} + +export default InsightsRankingTableChange; +export {formatRankingTableChange}; diff --git a/src/pages/Insights/charts/InsightsRankingTableRow.tsx b/src/pages/Insights/charts/InsightsRankingTableRow.tsx new file mode 100644 index 000000000000..5b9d6f039f7a --- /dev/null +++ b/src/pages/Insights/charts/InsightsRankingTableRow.tsx @@ -0,0 +1,177 @@ +import formatChartCount from '@components/Charts/utils/formatChartCount'; +import PressableWithFeedback from '@components/Pressable/PressableWithFeedback'; +import {buildChartDrillDownQuery} from '@components/Search/chartDrillDown'; +import CHART_GROUP_BY_CONFIG from '@components/Search/chartGroupByConfig'; +import type {SearchChartCountDimension, SearchGroupBy, SearchQueryJSON} from '@components/Search/types'; +import {getCellAccessibilityProps, getRowAccessibilityProps, shouldUseTableSemantics} from '@components/Table/tableAccessibility'; +import Text from '@components/Text'; + +import {useCurrencyListActions} from '@hooks/useCurrencyList'; +import useLayoutSpacing from '@hooks/useLayoutSpacing'; +import useLocalize from '@hooks/useLocalize'; +import useResponsiveLayout from '@hooks/useResponsiveLayout'; +import useThemeStyles from '@hooks/useThemeStyles'; + +import Navigation from '@libs/Navigation/Navigation'; + +import variables from '@styles/variables'; + +import CONST from '@src/CONST'; +import ROUTES from '@src/ROUTES'; + +import React from 'react'; +import {View} from 'react-native'; + +import type {RankingTableRow} from './buildRankingTableRows'; + +import InsightsRankingTableAverageMarker from './InsightsRankingTableAverageMarker'; +import InsightsRankingTableChange, {formatRankingTableChange} from './InsightsRankingTableChange'; + +/** Smaller shares would otherwise be displayed as zero. In percentage points. */ +const MIN_WRITTEN_SHARE = 0.1; + +/** Each column's position, as the table's accessibility tree numbers them */ +const RANKING_TABLE_COLUMN = { + GROUP: 1, + SHARE: 2, + COUNT: 3, + AMOUNT: 4, + CHANGE: 5, +} as const; + +type InsightsRankingTableRowProps = { + row: RankingTableRow; + groupBy: SearchGroupBy; + countDimension: SearchChartCountDimension; + queryJSON: Readonly | undefined; + /** Position on the same scale as the bars, omitted outside average comparison mode */ + averageWidthPercent?: number; + /** Zero-based data row position, excluding the header */ + rowIndex: number; +}; + +function InsightsRankingTableRow({row, groupBy, countDimension, queryJSON, averageWidthPercent, rowIndex}: InsightsRankingTableRowProps) { + const {item, share, barWidthPercent, change} = row; + const styles = useThemeStyles(); + const {translate, numberFormat} = useLocalize(); + const {convertToDisplayString} = useCurrencyListActions(); + const {cardPaddingHorizontal} = useLayoutSpacing(); + const {shouldUseNarrowLayout} = useResponsiveLayout(); + const {getLabel, getFilterQuery} = CHART_GROUP_BY_CONFIG[groupBy]; + const isTableSemanticsEnabled = shouldUseTableSemantics(shouldUseNarrowLayout); + const label = getLabel(item); + const formattedCount = formatChartCount(item.count, countDimension, translate, numberFormat); + const formattedAmount = convertToDisplayString(item.total, item.currency); + const percentOptions = { + style: 'percent', + minimumFractionDigits: 1, + maximumFractionDigits: 1, + } as const; + const formattedShare = share > 0 && share < MIN_WRITTEN_SHARE ? `<${numberFormat(MIN_WRITTEN_SHARE / 100, percentOptions)}` : numberFormat(share / 100, percentOptions); + const changeLabel = change ? formatRankingTableChange(change, translate, numberFormat).accessibilityLabel : undefined; + const accessibilityLabel = [label, formattedCount, formattedShare, formattedAmount, changeLabel].filter(Boolean).join(', '); + const cellStyle = [styles.tableRowVerticalPadding, styles.justifyContentCenter]; + + const openOnSpend = () => { + if (!queryJSON) { + return; + } + const query = buildChartDrillDownQuery(queryJSON, getFilterQuery(item)); + if (query) { + Navigation.navigate(ROUTES.SEARCH_ROOT.getRoute({query})); + } + }; + + if (shouldUseNarrowLayout) { + return ( + 0 && styles.borderTop]} + hoverStyle={styles.hoveredComponentBG} + > + + + {label} + + {[formattedCount, formattedShare].join(` ${CONST.DOT_SEPARATOR} `)} + + + + {formattedAmount} + {!!change && } + + + + + {averageWidthPercent !== undefined && ( + + + + )} + + + ); + } + + return ( + 0 && styles.borderTop]} + hoverStyle={styles.hoveredComponentBG} + {...getRowAccessibilityProps(isTableSemanticsEnabled, rowIndex)} + > + + {label} + + + + + + {formattedShare} + + + + + {numberFormat(item.count)} + + + {formattedAmount} + + {!!change && ( + + + + )} + + ); +} + +export default InsightsRankingTableRow; +export {RANKING_TABLE_COLUMN}; diff --git a/src/pages/Insights/charts/buildRankingTableRows.ts b/src/pages/Insights/charts/buildRankingTableRows.ts new file mode 100644 index 000000000000..86da8cc36f67 --- /dev/null +++ b/src/pages/Insights/charts/buildRankingTableRows.ts @@ -0,0 +1,94 @@ +/** Works out what a ranking table shows for each group: its share of every group's count, the length of its bar, and how its count changed. */ +import type {ChartComparison} from '@components/Search/buildChartSeries'; +import {isChartAverage} from '@components/Search/buildChartSeries'; +import type {GroupedItem} from '@components/Search/types'; + +import CONST from '@src/CONST'; + +const RANKING_TABLE_CHANGE = { + NONE: 'none', + NEW: 'new', + INCREASE: 'increase', + DECREASE: 'decrease', +} as const; + +type RankingTableChange = + | {type: typeof RANKING_TABLE_CHANGE.NONE} + | {type: typeof RANKING_TABLE_CHANGE.NEW} + | { + type: typeof RANKING_TABLE_CHANGE.INCREASE | typeof RANKING_TABLE_CHANGE.DECREASE; + percent: number; + }; + +type RankingTableRow = { + item: GroupedItem; + + /** The group's share of every group's count, in percentage points, as the backend works it out */ + share: number; + + /** Bar length as a percentage of the longest bar */ + barWidthPercent: number; + + /** Left out unless the table compares against the previous period */ + change?: RankingTableChange; +}; + +type RankingTable = { + rows: RankingTableRow[]; + + /** Count of the average group, set when the table compares against the average */ + average?: number; + + /** Where the average falls on the bars' scale, as a percentage of the longest bar */ + averageWidthPercent?: number; +}; + +type BuildRankingTableRowsParams = { + /** The listed groups, sorted by count, most first */ + data: GroupedItem[]; + + comparison: ChartComparison | undefined; + + /** Whether the page compares against the previous period. Every row then shows a change, even when there's no previous-period data, e.g. from before violations were tracked. */ + isComparingPreviousPeriod: boolean; +}; + +/** Returns how a group's count changed against the previous period's, rounded to a whole percentage */ +function getRankingTableChange(count: number, previousCount: number | undefined): RankingTableChange { + if (previousCount === undefined) { + return {type: RANKING_TABLE_CHANGE.NONE}; + } + if (previousCount === 0) { + return {type: count > 0 ? RANKING_TABLE_CHANGE.NEW : RANKING_TABLE_CHANGE.NONE}; + } + const percent = Math.round((Math.abs(count - previousCount) / previousCount) * 100); + if (percent === 0) { + return {type: RANKING_TABLE_CHANGE.NONE}; + } + return {type: count > previousCount ? RANKING_TABLE_CHANGE.INCREASE : RANKING_TABLE_CHANGE.DECREASE, percent}; +} + +function buildRankingTableRows({data, comparison, isComparingPreviousPeriod}: BuildRankingTableRowsParams): RankingTable { + const maxCount = Math.max(0, ...data.map((item) => item.count ?? 0)); + const getWidthPercent = (count: number) => (maxCount > 0 ? Math.min((count / maxCount) * 100, 100) : 0); + + const comparedRows = isComparingPreviousPeriod && comparison && !isChartAverage(comparison) ? comparison.data : undefined; + const previousCounts = comparedRows ? new Map(comparedRows.map((item) => [item.keyForList, item.count ?? 0])) : undefined; + + const rows = data.map((item): RankingTableRow => { + const count = item.count ?? 0; + return { + item, + share: item.percentOfTotal ?? 0, + barWidthPercent: getWidthPercent(count), + change: isComparingPreviousPeriod ? getRankingTableChange(count, previousCounts ? (previousCounts.get(item.keyForList) ?? 0) : undefined) : undefined, + }; + }); + + const average = isChartAverage(comparison) ? comparison[CONST.SEARCH.CHART_METRIC.COUNT] : undefined; + return {rows, average, averageWidthPercent: average === undefined ? undefined : getWidthPercent(average)}; +} + +export default buildRankingTableRows; +export {RANKING_TABLE_CHANGE}; +export type {RankingTableChange, RankingTableRow}; diff --git a/src/pages/Insights/dashboardSpecs.ts b/src/pages/Insights/dashboardSpecs.ts index 91ecb65a2143..787d012606b1 100644 --- a/src/pages/Insights/dashboardSpecs.ts +++ b/src/pages/Insights/dashboardSpecs.ts @@ -1,6 +1,6 @@ /** Declares the charts each Insights dashboard renders and how they map to backend graph slots and search views. */ -import type {ChartView, SearchChartCountDimension, SearchChartMetric, SearchGroupBy} from '@components/Search/types'; +import type {SearchChartCountDimension, SearchChartMetric, SearchGroupBy, SearchView} from '@components/Search/types'; import {canEditWorkspaceSettings} from '@libs/PolicyUtils/permissions'; import {isArchivedOrPendingDeletePolicy, isControlPolicy, isGroupPolicy} from '@libs/PolicyUtils/policyType'; @@ -25,7 +25,10 @@ type InsightsChartSpec = { /** Slot the request names the chart's snapshot under, and the response's `graphs` confirms it in */ graphKey: InsightsGraphKey; titleKey: TranslationPaths; - view: ChartView; + view: SearchView; + + /** Whether the chart spans the dashboard's whole width instead of sharing the two-column grid */ + isFullWidth?: boolean; /** What the chart plots for each group, left out by charts plotting the money each group totals */ metric?: SearchChartMetric; @@ -199,17 +202,6 @@ const INSIGHTS_DASHBOARD_SPECS: Record hasMultipleMembers(policy) && areApprovalsEnabled(policy), }, + { + graphKey: CONST.INSIGHTS.GRAPH.TOP_VIOLATIONS, + titleKey: 'insightsPage.topViolations', + has: VIOLATION_HAS_VALUES, + view: CONST.SEARCH.VIEW.TABLE, + isFullWidth: true, + groupBy: CONST.SEARCH.GROUP_BY.VIOLATION, + metric: CONST.SEARCH.CHART_METRIC.COUNT, + sortBy: CONST.SEARCH.TABLE_COLUMNS.GROUP_EXPENSES, + sortOrder: CONST.SEARCH.SORT_ORDER.DESC, + limit: 15, + }, ], }, }; diff --git a/src/styles/index.ts b/src/styles/index.ts index 6a165944c421..1a7c74a6b547 100644 --- a/src/styles/index.ts +++ b/src/styles/index.ts @@ -8173,6 +8173,70 @@ const plainStyles = (theme: ThemeColors) => width: variables.insightsAICardWidth, } satisfies ViewStyle, + insightsDataTableSkeletonTopOffset: (topOffset: number) => + ({ + marginTop: topOffset, + }) satisfies ViewStyle, + + insightsRankingTableShareColumn: { + flex: 1.5, + minWidth: 0, + alignSelf: 'stretch', + paddingRight: variables.insightsRankingTableShareLabelSpace, + } satisfies ViewStyle, + + insightsRankingTableNumberColumn: { + width: variables.w130, + } satisfies ViewStyle, + + insightsRankingTableChangeColumn: { + width: variables.w96, + alignItems: 'flex-end', + } satisfies ViewStyle, + + insightsRankingTableBar: (widthPercent: number) => + ({ + width: `${widthPercent}%`, + minWidth: variables.insightsRankingTableBarMinWidth, + height: variables.insightsRankingTableBarHeight, + borderRadius: variables.insightsRankingTableBarHeight / 2, + backgroundColor: colors.green400, + flexShrink: 0, + }) satisfies ViewStyle, + + insightsRankingTableBarTrack: { + flexDirection: 'row', + height: variables.insightsRankingTableBarHeight, + borderRadius: variables.insightsRankingTableBarHeight / 2, + backgroundColor: theme.border, + } satisfies ViewStyle, + + insightsRankingTableAverageLineAnchor: (leftPercent: number, overhangTop = 0, overhangBottom?: number) => + ({ + position: 'absolute', + top: -overhangTop, + bottom: -(overhangBottom ?? overhangTop), + left: `${leftPercent}%`, + width: 0, + alignItems: 'center', + }) satisfies ViewStyle, + + insightsRankingTableAverageDashedLine: (width: number) => + ({ + width, + }) satisfies ViewStyle, + + insightsRankingTableAverageLegendMark: { + height: variables.insightsRankingTableBarHeight + variables.insightsRankingTableAverageMarkerOverhang * 2, + } satisfies ViewStyle, + + insightsRankingTableAveragePill: { + backgroundColor: theme.heading, + borderRadius: variables.componentBorderRadiusSmall, + paddingHorizontal: VictoryTheme.averageLine.pillPaddingHorizontal, + paddingVertical: VictoryTheme.averageLine.pillPaddingVertical, + } satisfies ViewStyle, + insightsEmptyStateIllustration: { width: variables.insightsEmptyStateIllustrationSize, height: variables.insightsEmptyStateIllustrationSize, diff --git a/src/styles/variables.ts b/src/styles/variables.ts index 440aceca9470..e547325648e2 100644 --- a/src/styles/variables.ts +++ b/src/styles/variables.ts @@ -187,6 +187,11 @@ export default { centeredContentMaxWidth: 1200, insightsEmptyStateIllustrationSize: 136, insightsAICardWidth: 250, + insightsRankingTableBarHeight: 8, + insightsRankingTableBarMinWidth: 4, + insightsRankingTableShareLabelSpace: 56, + insightsRankingTableAverageMarkerWidth: 2, + insightsRankingTableAverageMarkerOverhang: 6, minScanTooltipWidth: 320, chartTooltipMinWidth: 200, uploadViewMargin: 20, diff --git a/tests/ui/InsightsRankingTableTest.tsx b/tests/ui/InsightsRankingTableTest.tsx new file mode 100644 index 000000000000..e7d93fb4cfd3 --- /dev/null +++ b/tests/ui/InsightsRankingTableTest.tsx @@ -0,0 +1,121 @@ +import {cleanup, fireEvent, render, screen, within} from '@testing-library/react-native'; + +import ComposeProviders from '@components/ComposeProviders'; +import {CurrencyListContextProvider} from '@components/CurrencyListContextProvider'; +import {LocaleContextProvider} from '@components/LocaleContextProvider'; +import OnyxListItemProvider from '@components/OnyxListItemProvider'; +import type {GroupedItem} from '@components/Search/types'; + +import useResponsiveLayout from '@hooks/useResponsiveLayout'; + +import Navigation from '@libs/Navigation/Navigation'; +import {buildSearchQueryJSON} from '@libs/SearchQueryUtils'; + +import InsightsRankingTable from '@pages/Insights/charts/InsightsRankingTable'; + +import CONST from '@src/CONST'; +import ONYXKEYS from '@src/ONYXKEYS'; + +import React from 'react'; +import Onyx from 'react-native-onyx'; + +import currencyList from '../unit/currencyList.json'; +import createMock from '../utils/createMock'; +import waitForBatchedUpdatesWithAct from '../utils/waitForBatchedUpdatesWithAct'; + +jest.mock('@hooks/useResponsiveLayout', () => ({__esModule: true, default: jest.fn()})); +jest.mock('@libs/Navigation/Navigation'); +jest.mock('@libs/getPlatform', () => ({__esModule: true, default: () => 'web'})); + +const QUERY = buildSearchQueryJSON('type:expense group-by:violation view:table limit:15 has:submitted-violation date>=2026-01-01 date<=2026-01-31'); +const GROUP: GroupedItem = { + groupedBy: CONST.SEARCH.GROUP_BY.VIOLATION, + violation: 'missingReceipt', + formattedViolation: 'Missing receipt', + keyForList: 'group_missingReceipt', + count: 10, + total: 12345, + currency: CONST.CURRENCY.USD, + percentOfTotal: 25, + transactions: [], +}; + +function renderTable(comparisonCount?: number, isComparingPreviousPeriod = comparisonCount !== undefined) { + return render( + + + , + ); +} + +describe('Insights ranking table', () => { + beforeAll(() => Onyx.init({keys: ONYXKEYS})); + + beforeEach(async () => { + jest.clearAllMocks(); + jest.mocked(useResponsiveLayout).mockReturnValue(createMock>({shouldUseNarrowLayout: false})); + await Onyx.set(ONYXKEYS.CURRENCY_LIST, currencyList); + await waitForBatchedUpdatesWithAct(); + }); + + afterEach(async () => { + cleanup(); + await Onyx.clear(); + }); + + it('exposes desktop data as rows without a conflicting button role', async () => { + // Given a wide web layout with a previous-period comparison + renderTable(5); + await waitForBatchedUpdatesWithAct(); + + // When a screen reader finds the data row + const row = screen.getByRole(CONST.ROLE.ROW, {name: 'Missing receipt, 10 expenses, 25.0%, $123.45, Up 100%'}); + + // Then the web pressable can preserve the row role instead of prioritizing a conflicting button role + expect(row).toHaveProp('role', CONST.ROLE.ROW); + expect(row.props.accessibilityRole).toBeUndefined(); + expect(within(row).getByText('$123.45')).toBeOnTheScreen(); + expect(screen.queryAllByRole(CONST.ROLE.BUTTON)).toHaveLength(0); + }); + + it.each([ + ['more expenses than the previous period', 5, 'Up 100%'], + ['no previous-period data', undefined, 'No change'], + ])('announces all narrow row metrics and the change with %s', async (_description, previousCount, changeLabel) => { + // Given a narrow layout, where each pressed row is a single accessibility element + jest.mocked(useResponsiveLayout).mockReturnValue(createMock>({shouldUseNarrowLayout: true})); + renderTable(previousCount, true); + await waitForBatchedUpdatesWithAct(); + + // When a screen reader focuses the row + const row = screen.getByRole(CONST.ROLE.BUTTON, {name: `Missing receipt, 10 expenses, 25.0%, $123.45, ${changeLabel}`}); + + // Then the label includes every metric rather than just the violation name + expect(row).toBeOnTheScreen(); + }); + + it('opens Spend with the chart filters and without the ranking limit', async () => { + // Given a narrow row whose query can be opened on Spend + jest.mocked(useResponsiveLayout).mockReturnValue(createMock>({shouldUseNarrowLayout: true})); + renderTable(); + await waitForBatchedUpdatesWithAct(); + + // When the user presses the violation + fireEvent.press(screen.getByRole(CONST.ROLE.BUTTON)); + + // Then the destination retains the chart filters without restricting results to the ranking limit + const route = jest.mocked(Navigation.navigate).mock.calls.at(0)?.[0]; + expect(typeof route).toBe('string'); + const decodedRoute = typeof route === 'string' ? decodeURIComponent(route) : ''; + expect(decodedRoute).toContain('has:submitted-violation'); + expect(decodedRoute).toContain('2026-01-01'); + expect(decodedRoute).not.toContain('limit:'); + }); +}); diff --git a/tests/unit/Search/chartGroupByConfigTest.ts b/tests/unit/Search/chartGroupByConfigTest.ts index 799001b15123..72e6c12dc8ea 100644 --- a/tests/unit/Search/chartGroupByConfigTest.ts +++ b/tests/unit/Search/chartGroupByConfigTest.ts @@ -7,6 +7,7 @@ import type { TransactionMonthGroupListItemType, TransactionQuarterGroupListItemType, TransactionTagGroupListItemType, + TransactionViolationGroupListItemType, TransactionWeekGroupListItemType, TransactionWithdrawalIDGroupListItemType, TransactionYearGroupListItemType, @@ -64,6 +65,17 @@ const cases: ChartGroupByCase[] = [ expectedLabel: 'Travel card', expectedFilterQuery: 'cardID:123', }, + { + groupBy: CONST.SEARCH.GROUP_BY.VIOLATION, + item: createMock({ + groupedBy: CONST.SEARCH.GROUP_BY.VIOLATION, + violation: CONST.VIOLATIONS.MISSING_CATEGORY, + formattedViolation: 'Missing category', + }), + expectedIcon: 'Exclamation', + expectedLabel: 'Missing category', + expectedFilterQuery: 'violationName:missingCategory', + }, { groupBy: CONST.SEARCH.GROUP_BY.WITHDRAWAL_ID, item: createMock({ diff --git a/tests/unit/buildRankingTableRowsTest.ts b/tests/unit/buildRankingTableRowsTest.ts new file mode 100644 index 000000000000..20313e9b94b4 --- /dev/null +++ b/tests/unit/buildRankingTableRowsTest.ts @@ -0,0 +1,77 @@ +import type {TransactionViolationGroupListItemType} from '@components/Search/SearchList/ListItem/types'; + +import buildRankingTableRows, {RANKING_TABLE_CHANGE} from '@pages/Insights/charts/buildRankingTableRows'; + +import CONST from '@src/CONST'; + +/** A grouped violation result, carrying the fields the table is built from. */ +function violationGroup(violation: string, count: number, percentOfTotal?: number): TransactionViolationGroupListItemType { + return { + groupedBy: CONST.SEARCH.GROUP_BY.VIOLATION, + violation, + formattedViolation: violation, + keyForList: `group_${violation}`, + count, + total: count * 100, + currency: CONST.CURRENCY.USD, + percentOfTotal, + transactions: [], + }; +} + +describe('buildRankingTableRows', () => { + it('takes each share from the backend and scales the bars by count to the largest row', () => { + // Given two listed violation types, whose shares the backend worked out of every type's expenses + const data = [violationGroup('missingReceipt', 50, 18.8), violationGroup('overLimit', 25, 9.4)]; + + // When the rows are built + const {rows} = buildRankingTableRows({data, comparison: undefined, isComparingPreviousPeriod: false}); + + // Then each row shows the backend's share, since the types past the limit aren't here to share out of + expect(rows.map(({share}) => share)).toEqual([18.8, 9.4]); + // And the bars are scaled by count to the largest row, which fills the bar area + expect(rows.map(({barWidthPercent}) => barWidthPercent)).toEqual([100, 50]); + // And no row shows a change, since the page doesn't compare against the previous period + expect(rows.every(({change}) => change === undefined)).toBe(true); + }); + + it('marks the average on the same scale as the bars', () => { + // Given an average of 20 expenses per violation type, and a top row with 40 + const data = [violationGroup('missingReceipt', 40), violationGroup('overLimit', 10)]; + + // When the rows are built against the average + const table = buildRankingTableRows({data, comparison: {[CONST.SEARCH.CHART_METRIC.COUNT]: 20}, isComparingPreviousPeriod: false}); + + // Then the average line sits halfway along the bar area, where a bar for 20 expenses would end + expect(table.average).toBe(20); + expect(table.averageWidthPercent).toBe(50); + }); + + it('rounds the change from the previous period to a whole percentage, and marks a type without previous expenses as new', () => { + // Given violation types that grew, shrank, stayed the same, and had no expenses in the previous period + const data = [violationGroup('missingReceipt', 33), violationGroup('overLimit', 10), violationGroup('missingCategory', 8), violationGroup('missingTag', 5)]; + const previous = [violationGroup('missingReceipt', 25), violationGroup('overLimit', 20), violationGroup('missingCategory', 8)]; + + // When the rows are built against the previous period + const {rows} = buildRankingTableRows({data, comparison: {data: previous, color: ''}, isComparingPreviousPeriod: true}); + + // Then each row shows how its expenses changed, and a type that went up from zero is new + expect(rows.map(({change}) => change)).toEqual([ + {type: RANKING_TABLE_CHANGE.INCREASE, percent: 32}, + {type: RANKING_TABLE_CHANGE.DECREASE, percent: 50}, + {type: RANKING_TABLE_CHANGE.NONE}, + {type: RANKING_TABLE_CHANGE.NEW}, + ]); + }); + + it('shows no change when the previous period has no data to compare against', () => { + // Given the page compares against the previous period, but there's no previous-period data, e.g. from before violations were tracked + const data = [violationGroup('missingReceipt', 10)]; + + // When the rows are built + const {rows} = buildRankingTableRows({data, comparison: undefined, isComparingPreviousPeriod: true}); + + // Then the row shows no change, since there's nothing to compare it with + expect(rows.at(0)?.change).toEqual({type: RANKING_TABLE_CHANGE.NONE}); + }); +});