Open source, privacy-first web analytics. Lightweight, cookie-free Google Analytics alternative. Self-hosted or cloud.
TypeScript analyticsanalytics-dashboardclickhouseelixirgoogle-analyticsmarketingopen-source-analyticsphoenixplausible-analyticspostgresqlprivacyprivacy-friendlyself-hostedsimple-analyticsstatisticstailwindcssweb-analyticswebsite-analyticswebsite-statswebsite-tracking
Migrate Locations to POST /query API (#6415)
Artur Pata6933a3e5f6d2
diff --git a/.github/workflows/elixir.yml b/.github/workflows/elixir.ymlindex 48af9e9f2a..2ebb5fe018 100644--- a/.github/workflows/elixir.yml+++ b/.github/workflows/elixir.yml@@ -293,5 +293,6 @@ jobs:- run: mix compile --warnings-as-errors --all-warnings- run: mix format --check-formatted- run: mix deps.unlock --check-unused+ - run: mix generate_countries_meta && git diff --exit-code -- assets/data/countries_meta.json- run: mix credo diff --from-git-merge-base origin/master- run: mix dialyzerdiff --git a/assets/data/countries_meta.json b/assets/data/countries_meta.jsonnew file mode 100644index 0000000000..4dd242e0ca--- /dev/null+++ b/assets/data/countries_meta.json@@ -0,0 +1,1006 @@+{+ "YE": [+ "YEM",+ "๐พ๐ช"+ ],+ "QA": [+ "QAT",+ "๐ถ๐ฆ"+ ],+ "MR": [+ "MRT",+ "๐ฒ๐ท"+ ],+ "CH": [+ "CHE",+ "๐จ๐ญ"+ ],+ "AF": [+ "AFG",+ "๐ฆ๐ซ"+ ],+ "AO": [+ "AGO",+ "๐ฆ๐ด"+ ],+ "BT": [+ "BTN",+ "๐ง๐น"+ ],+ "HK": [+ "HKG",+ "๐ญ๐ฐ"+ ],+ "CU": [+ "CUB",+ "๐จ๐บ"+ ],+ "HU": [+ "HUN",+ "๐ญ๐บ"+ ],+ "AZ": [+ "AZE",+ "๐ฆ๐ฟ"+ ],+ "SS": [+ "SSD",+ "๐ธ๐ธ"+ ],+ "BY": [+ "BLR",+ "๐ง๐พ"+ ],+ "MA": [+ "MAR",+ "๐ฒ๐ฆ"+ ],+ "MZ": [+ "MOZ",+ "๐ฒ๐ฟ"+ ],+ "TR": [+ "TUR",+ "๐น๐ท"+ ],+ "PL": [+ "POL",+ "๐ต๐ฑ"+ ],+ "US": [+ "USA",+ "๐บ๐ธ"+ ],+ "SR": [+ "SUR",+ "๐ธ๐ท"+ ],+ "LR": [+ "LBR",+ "๐ฑ๐ท"+ ],+ "OM": [+ "OMN",+ "๐ด๐ฒ"+ ],+ "MH": [+ "MHL",+ "๐ฒ๐ญ"+ ],+ "TG": [+ "TGO",+ "๐น๐ฌ"+ ],+ "CW": [+ "CUW",+ "๐จ๐ผ"+ ],+ "AT": [+ "AUT",+ "๐ฆ๐น"+ ],+ "CO": [+ "COL",+ "๐จ๐ด"+ ],+ "SV": [+ "SLV",+ "๐ธ๐ป"+ ],+ "RE": [+ "REU",+ "๐ท๐ช"+ ],+ "LI": [+ "LIE",+ "๐ฑ๐ฎ"+ ],+ "PR": [+ "PRI",+ "๐ต๐ท"+ ],+ "GI": [+ "GIB",+ "๐ฌ๐ฎ"+ ],+ "CV": [+ "CPV",+ "๐จ๐ป"+ ],+ "KG": [+ "KGZ",+ "๐ฐ๐ฌ"+ ],+ "SK": [+ "SVK",+ "๐ธ๐ฐ"+ ],+ "LT": [+ "LTU",+ "๐ฑ๐น"+ ],+ "AL": [+ "ALB",+ "๐ฆ๐ฑ"+ ],+ "BL": [+ "BLM",+ "๐ง๐ฑ"+ ],+ "FK": [+ "FLK",+ "๐ซ๐ฐ"+ ],+ "TV": [+ "TUV",+ "๐น๐ป"+ ],+ "SJ": [+ "SJM",+ "๐ธ๐ฏ"+ ],+ "CX": [+ "CXR",+ "๐จ๐ฝ"+ ],+ "VG": [+ "VGB",+ "๐ป๐ฌ"+ ],+ "VI": [+ "VIR",+ "๐ป๐ฎ"+ ],+ "TT": [+ "TTO",+ "๐น๐น"+ ],+ "AI": [+ "AIA",+ "๐ฆ๐ฎ"+ ],+ "GE": [+ "GEO",+ "๐ฌ๐ช"+ ],+ "GB": [+ "GBR",+ "๐ฌ๐ง"+ ],+ "TW": [+ "TWN",+ "๐น๐ผ"+ ],+ "BV": [+ "BVT",+ "๐ง๐ป"+ ],+ "AU": [+ "AUS",+ "๐ฆ๐บ"+ ],+ "CD": [+ "COD",+ "๐จ๐ฉ"+ ],+ "IL": [+ "ISR",+ "๐ฎ๐ฑ"+ ],+ "FJ": [+ "FJI",+ "๐ซ๐ฏ"+ ],+ "HM": [+ "HMD",+ "๐ญ๐ฒ"+ ],+ "MO": [+ "MAC",+ "๐ฒ๐ด"+ ],+ "LU": [+ "LUX",+ "๐ฑ๐บ"+ ],+ "TH": [+ "THA",+ "๐น๐ญ"+ ],+ "TZ": [+ "TZA",+ "๐น๐ฟ"+ ],+ "MC": [+ "MCO",+ "๐ฒ๐จ"+ ],+ "AD": [+ "AND",+ "๐ฆ๐ฉ"+ ],+ "IQ": [+ "IRQ",+ "๐ฎ๐ถ"+ ],+ "NI": [+ "NIC",+ "๐ณ๐ฎ"+ ],+ "KW": [+ "KWT",+ "๐ฐ๐ผ"+ ],+ "MW": [+ "MWI",+ "๐ฒ๐ผ"+ ],+ "GH": [+ "GHA",+ "๐ฌ๐ญ"+ ],+ "DM": [+ "DMA",+ "๐ฉ๐ฒ"+ ],+ "EE": [+ "EST",+ "๐ช๐ช"+ ],+ "IS": [+ "ISL",+ "๐ฎ๐ธ"+ ],+ "BM": [+ "BMU",+ "๐ง๐ฒ"+ ],+ "EC": [+ "ECU",+ "๐ช๐จ"+ ],+ "KM": [+ "COM",+ "๐ฐ๐ฒ"+ ],+ "SB": [+ "SLB",+ "๐ธ๐ง"+ ],+ "AE": [+ "ARE",+ "๐ฆ๐ช"+ ],+ "CM": [+ "CMR",+ "๐จ๐ฒ"+ ],+ "EH": [+ "ESH",+ "๐ช๐ญ"+ ],+ "CC": [+ "CCK",+ "๐จ๐จ"+ ],+ "AS": [+ "ASM",+ "๐ฆ๐ธ"+ ],+ "KH": [+ "KHM",+ "๐ฐ๐ญ"+ ],+ "MD": [+ "MDA",+ "๐ฒ๐ฉ"+ ],+ "NA": [+ "NAM",+ "๐ณ๐ฆ"+ ],+ "SA": [+ "SAU",+ "๐ธ๐ฆ"+ ],+ "HN": [+ "HND",+ "๐ญ๐ณ"+ ],+ "MK": [+ "MKD",+ "๐ฒ๐ฐ"+ ],+ "LC": [+ "LCA",+ "๐ฑ๐จ"+ ],+ "PA": [+ "PAN",+ "๐ต๐ฆ"+ ],+ "VC": [+ "VCT",+ "๐ป๐จ"+ ],+ "TM": [+ "TKM",+ "๐น๐ฒ"+ ],+ "SI": [+ "SVN",+ "๐ธ๐ฎ"+ ],+ "GQ": [+ "GNQ",+ "๐ฌ๐ถ"+ ],+ "PH": [+ "PHL",+ "๐ต๐ญ"+ ],+ "CZ": [+ "CZE",+ "๐จ๐ฟ"+ ],+ "BO": [+ "BOL",+ "๐ง๐ด"+ ],+ "SY": [+ "SYR",+ "๐ธ๐พ"+ ],+ "NO": [+ "NOR",+ "๐ณ๐ด"+ ],+ "IM": [+ "IMN",+ "๐ฎ๐ฒ"+ ],+ "SX": [+ "SXM",+ "๐ธ๐ฝ"+ ],+ "GG": [+ "GGY",+ "๐ฌ๐ฌ"+ ],+ "GW": [+ "GNB",+ "๐ฌ๐ผ"+ ],+ "SH": [+ "SHN",+ "๐ธ๐ญ"+ ],+ "NC": [+ "NCL",+ "๐ณ๐จ"+ ],+ "BE": [+ "BEL",+ "๐ง๐ช"+ ],+ "JP": [+ "JPN",+ "๐ฏ๐ต"+ ],+ "LV": [+ "LVA",+ "๐ฑ๐ป"+ ],+ "AM": [+ "ARM",+ "๐ฆ๐ฒ"+ ],+ "SD": [+ "SDN",+ "๐ธ๐ฉ"+ ],+ "GT": [+ "GTM",+ "๐ฌ๐น"+ ],+ "PY": [+ "PRY",+ "๐ต๐พ"+ ],+ "MN": [+ "MNG",+ "๐ฒ๐ณ"+ ],+ "TK": [+ "TKL",+ "๐น๐ฐ"+ ],+ "DZ": [+ "DZA",+ "๐ฉ๐ฟ"+ ],+ "KZ": [+ "KAZ",+ "๐ฐ๐ฟ"+ ],+ "LY": [+ "LBY",+ "๐ฑ๐พ"+ ],+ "AW": [+ "ABW",+ "๐ฆ๐ผ"+ ],+ "UY": [+ "URY",+ "๐บ๐พ"+ ],+ "GL": [+ "GRL",+ "๐ฌ๐ฑ"+ ],+ "SN": [+ "SEN",+ "๐ธ๐ณ"+ ],+ "UM": [+ "UMI",+ "๐บ๐ฒ"+ ],+ "JO": [+ "JOR",+ "๐ฏ๐ด"+ ],+ "MT": [+ "MLT",+ "๐ฒ๐น"+ ],+ "BS": [+ "BHS",+ "๐ง๐ธ"+ ],+ "BI": [+ "BDI",+ "๐ง๐ฎ"+ ],+ "BA": [+ "BIH",+ "๐ง๐ฆ"+ ],+ "MQ": [+ "MTQ",+ "๐ฒ๐ถ"+ ],+ "MU": [+ "MUS",+ "๐ฒ๐บ"+ ],+ "MS": [+ "MSR",+ "๐ฒ๐ธ"+ ],+ "BW": [+ "BWA",+ "๐ง๐ผ"+ ],+ "YT": [+ "MYT",+ "๐พ๐น"+ ],+ "PN": [+ "PCN",+ "๐ต๐ณ"+ ],+ "MP": [+ "MNP",+ "๐ฒ๐ต"+ ],+ "ML": [+ "MLI",+ "๐ฒ๐ฑ"+ ],+ "BH": [+ "BHR",+ "๐ง๐ญ"+ ],+ "LB": [+ "LBN",+ "๐ฑ๐ง"+ ],+ "AR": [+ "ARG",+ "๐ฆ๐ท"+ ],+ "PG": [+ "PNG",+ "๐ต๐ฌ"+ ],+ "GR": [+ "GRC",+ "๐ฌ๐ท"+ ],+ "HT": [+ "HTI",+ "๐ญ๐น"+ ],+ "WS": [+ "WSM",+ "๐ผ๐ธ"+ ],+ "SG": [+ "SGP",+ "๐ธ๐ฌ"+ ],+ "GP": [+ "GLP",+ "๐ฌ๐ต"+ ],+ "BF": [+ "BFA",+ "๐ง๐ซ"+ ],+ "ME": [+ "MNE",+ "๐ฒ๐ช"+ ],+ "AQ": [+ "ATA",+ "๐ฆ๐ถ"+ ],+ "PK": [+ "PAK",+ "๐ต๐ฐ"+ ],+ "FM": [+ "FSM",+ "๐ซ๐ฒ"+ ],+ "MV": [+ "MDV",+ "๐ฒ๐ป"+ ],+ "GS": [+ "SGS",+ "๐ฌ๐ธ"+ ],+ "BN": [+ "BRN",+ "๐ง๐ณ"+ ],+ "CK": [+ "COK",+ "๐จ๐ฐ"+ ],+ "IO": [+ "IOT",+ "๐ฎ๐ด"+ ],+ "SE": [+ "SWE",+ "๐ธ๐ช"+ ],+ "SC": [+ "SYC",+ "๐ธ๐จ"+ ],+ "ZW": [+ "ZWE",+ "๐ฟ๐ผ"+ ],+ "SL": [+ "SLE",+ "๐ธ๐ฑ"+ ],+ "AG": [+ "ATG",+ "๐ฆ๐ฌ"+ ],+ "PF": [+ "PYF",+ "๐ต๐ซ"+ ],+ "CF": [+ "CAF",+ "๐จ๐ซ"+ ],+ "BD": [+ "BGD",+ "๐ง๐ฉ"+ ],+ "AX": [+ "ALA",+ "๐ฆ๐ฝ"+ ],+ "SZ": [+ "SWZ",+ "๐ธ๐ฟ"+ ],+ "HR": [+ "HRV",+ "๐ญ๐ท"+ ],+ "RS": [+ "SRB",+ "๐ท๐ธ"+ ],+ "NF": [+ "NFK",+ "๐ณ๐ซ"+ ],+ "IE": [+ "IRL",+ "๐ฎ๐ช"+ ],+ "NR": [+ "NRU",+ "๐ณ๐ท"+ ],+ "ZA": [+ "ZAF",+ "๐ฟ๐ฆ"+ ],+ "CA": [+ "CAN",+ "๐จ๐ฆ"+ ],+ "KR": [+ "KOR",+ "๐ฐ๐ท"+ ],+ "A1": [+ null,+ "๐ณ๏ธ"+ ],+ "VA": [+ "VAT",+ "๐ป๐ฆ"+ ],+ "NU": [+ "NIU",+ "๐ณ๐บ"+ ],+ "JE": [+ "JEY",+ "๐ฏ๐ช"+ ],+ "TD": [+ "TCD",+ "๐น๐ฉ"+ ],+ "IR": [+ "IRN",+ "๐ฎ๐ท"+ ],+ "NL": [+ "NLD",+ "๐ณ๐ฑ"+ ],+ "BB": [+ "BRB",+ "๐ง๐ง"+ ],+ "FI": [+ "FIN",+ "๐ซ๐ฎ"+ ],+ "UA": [+ "UKR",+ "๐บ๐ฆ"+ ],+ "ID": [+ "IDN",+ "๐ฎ๐ฉ"+ ],+ "ST": [+ "STP",+ "๐ธ๐น"+ ],+ "VU": [+ "VUT",+ "๐ป๐บ"+ ],+ "RU": [+ "RUS",+ "๐ท๐บ"+ ],+ "NE": [+ "NER",+ "๐ณ๐ช"+ ],+ "TO": [+ "TON",+ "๐น๐ด"+ ],+ "UZ": [+ "UZB",+ "๐บ๐ฟ"+ ],+ "GN": [+ "GIN",+ "๐ฌ๐ณ"+ ],+ "JM": [+ "JAM",+ "๐ฏ๐ฒ"+ ],+ "FR": [+ "FRA",+ "๐ซ๐ท"+ ],+ "TL": [+ "TLS",+ "๐น๐ฑ"+ ],+ "ET": [+ "ETH",+ "๐ช๐น"+ ],+ "KI": [+ "KIR",+ "๐ฐ๐ฎ"+ ],+ "CG": [+ "COG",+ "๐จ๐ฌ"+ ],+ "DE": [+ "DEU",+ "๐ฉ๐ช"+ ],+ "RW": [+ "RWA",+ "๐ท๐ผ"+ ],+ "DO": [+ "DOM",+ "๐ฉ๐ด"+ ],+ "VE": [+ "VEN",+ "๐ป๐ช"+ ],+ "PW": [+ "PLW",+ "๐ต๐ผ"+ ],+ "TC": [+ "TCA",+ "๐น๐จ"+ ],+ "ZM": [+ "ZMB",+ "๐ฟ๐ฒ"+ ],+ "NG": [+ "NGA",+ "๐ณ๐ฌ"+ ],+ "WF": [+ "WLF",+ "๐ผ๐ซ"+ ],+ "GF": [+ "GUF",+ "๐ฌ๐ซ"+ ],+ "KN": [+ "KNA",+ "๐ฐ๐ณ"+ ],+ "ES": [+ "ESP",+ "๐ช๐ธ"+ ],+ "GM": [+ "GMB",+ "๐ฌ๐ฒ"+ ],+ "KP": [+ "PRK",+ "๐ฐ๐ต"+ ],+ "GY": [+ "GUY",+ "๐ฌ๐พ"+ ],+ "MX": [+ "MEX",+ "๐ฒ๐ฝ"+ ],+ "IN": [+ "IND",+ "๐ฎ๐ณ"+ ],+ "SM": [+ "SMR",+ "๐ธ๐ฒ"+ ],+ "BG": [+ "BGR",+ "๐ง๐ฌ"+ ],+ "MF": [+ "MAF",+ "๐ฒ๐ซ"+ ],+ "CL": [+ "CHL",+ "๐จ๐ฑ"+ ],+ "VN": [+ "VNM",+ "๐ป๐ณ"+ ],+ "NP": [+ "NPL",+ "๐ณ๐ต"+ ],+ "CR": [+ "CRI",+ "๐จ๐ท"+ ],+ "ER": [+ "ERI",+ "๐ช๐ท"+ ],+ "LK": [+ "LKA",+ "๐ฑ๐ฐ"+ ],+ "CI": [+ "CIV",+ "๐จ๐ฎ"+ ],+ "PT": [+ "PRT",+ "๐ต๐น"+ ],+ "TJ": [+ "TJK",+ "๐น๐ฏ"+ ],+ "MY": [+ "MYS",+ "๐ฒ๐พ"+ ],+ "PS": [+ "PSE",+ "๐ต๐ธ"+ ],+ "PE": [+ "PER",+ "๐ต๐ช"+ ],+ "LS": [+ "LSO",+ "๐ฑ๐ธ"+ ],+ "CY": [+ "CYP",+ "๐จ๐พ"+ ],+ "TN": [+ "TUN",+ "๐น๐ณ"+ ],+ "XK": [+ "XKX",+ "๐ฝ๐ฐ"+ ],+ "KY": [+ "CYM",+ "๐ฐ๐พ"+ ],+ "DK": [+ "DNK",+ "๐ฉ๐ฐ"+ ],+ "BZ": [+ "BLZ",+ "๐ง๐ฟ"+ ],+ "FO": [+ "FRO",+ "๐ซ๐ด"+ ],+ "LA": [+ "LAO",+ "๐ฑ๐ฆ"+ ],+ "RO": [+ "ROU",+ "๐ท๐ด"+ ],+ "DJ": [+ "DJI",+ "๐ฉ๐ฏ"+ ],+ "EG": [+ "EGY",+ "๐ช๐ฌ"+ ],+ "KE": [+ "KEN",+ "๐ฐ๐ช"+ ],+ "UG": [+ "UGA",+ "๐บ๐ฌ"+ ],+ "MM": [+ "MMR",+ "๐ฒ๐ฒ"+ ],+ "BQ": [+ "BES",+ "๐ง๐ถ"+ ],+ "PM": [+ "SPM",+ "๐ต๐ฒ"+ ],+ "GD": [+ "GRD",+ "๐ฌ๐ฉ"+ ],+ "GU": [+ "GUM",+ "๐ฌ๐บ"+ ],+ "CN": [+ "CHN",+ "๐จ๐ณ"+ ],+ "SO": [+ "SOM",+ "๐ธ๐ด"+ ],+ "BJ": [+ "BEN",+ "๐ง๐ฏ"+ ],+ "BR": [+ "BRA",+ "๐ง๐ท"+ ],+ "GA": [+ "GAB",+ "๐ฌ๐ฆ"+ ],+ "NZ": [+ "NZL",+ "๐ณ๐ฟ"+ ],+ "MG": [+ "MDG",+ "๐ฒ๐ฌ"+ ],+ "IT": [+ "ITA",+ "๐ฎ๐น"+ ],+ "TF": [+ "ATF",+ "๐น๐ซ"+ ]+}\ No newline at end of filediff --git a/assets/js/dashboard/components/drilldown-link.tsx b/assets/js/dashboard/components/drilldown-link.tsxindex e9f20483a1..43171ea0c1 100644--- a/assets/js/dashboard/components/drilldown-link.tsx+++ b/assets/js/dashboard/components/drilldown-link.tsx@@ -1,4 +1,4 @@-import React from 'react'+import React, { ReactNode } from 'react'import {AppNavigationLink,AppNavigationLinkProps@@ -20,15 +20,16 @@ export function DrilldownLink({filterInfo,onClick,children,- extraClass+ icon,+ className,+ textClassName}: Pick<AppNavigationLinkProps, 'path' | 'onClick' | 'children'> & {- extraClass?: string+ className?: string+ textClassName?: string+ icon?: ReactNodefilterInfo: FilterInfo | null}) {const { dashboardState } = useDashboardStateContext()- const className = classNames(`${extraClass}`, {- 'hover:underline': !!filterInfo- })if (filterInfo) {const { prefix, filter, labels } = filterInfo@@ -43,7 +44,7 @@ export function DrilldownLink({return (<AppNavigationLinktitle={`Add filter: ${plainFilterText({ ...dashboardState, labels: newLabels }, filter)}`}- className={className}+ className={classNames(className, 'group')}path={path}onClick={onClick}search={(search) => ({@@ -52,10 +53,18 @@ export function DrilldownLink({labels: newLabels})}>- {children}+ {icon}+ <span className={classNames(textClassName, 'group-hover:underline')}>+ {children}+ </span></AppNavigationLink>)} else {- return <span className={className}>{children}</span>+ return (+ <span className={className}>+ {icon}+ <span className={textClassName}>{children}</span>+ </span>+ )}}diff --git a/assets/js/dashboard/router.tsx b/assets/js/dashboard/router.tsxindex b19c9a2aff..1e8a1f10d0 100644--- a/assets/js/dashboard/router.tsx+++ b/assets/js/dashboard/router.tsx@@ -15,7 +15,7 @@ import {BREAKDOWN_REPORTS,BreakdownReportKey} from './stats/reports/reports-config'-import LocationsModal from './stats/modals/locations-modal'+import { LocationsDetails } from './stats/locations/details'import PropsModal from './stats/modals/props'import ConversionsModal from './stats/modals/conversions'import FilterModal from './stats/modals/filter-modal'@@ -113,18 +113,18 @@ export const exitPagesRoute = {}export const countriesRoute = {- path: 'countries',- element: <LocationsModal currentView="countries" />+ path: BREAKDOWN_REPORTS.countries.detailsPath,+ element: <LocationsDetails reportKey={BreakdownReportKey.countries} />}export const regionsRoute = {- path: 'regions',- element: <LocationsModal currentView="regions" />+ path: BREAKDOWN_REPORTS.regions.detailsPath,+ element: <LocationsDetails reportKey={BreakdownReportKey.regions} />}export const citiesRoute = {- path: 'cities',- element: <LocationsModal currentView="cities" />+ path: BREAKDOWN_REPORTS.cities.detailsPath,+ element: <LocationsDetails reportKey={BreakdownReportKey.cities} />}export const browsersRoute = {diff --git a/assets/js/dashboard/stats-query.ts b/assets/js/dashboard/stats-query.tsindex 1a0592bda5..2e49f3b1f7 100644--- a/assets/js/dashboard/stats-query.ts+++ b/assets/js/dashboard/stats-query.ts@@ -55,6 +55,7 @@ export type ReportParams = {include?: Partial<QueryInclude>order_by?: OrderBypagination?: Pagination+ alwaysOnFilters?: ApiFilter[]}export type StatsQuery = {@@ -84,7 +85,10 @@ export function createStatsQuery(relative_date: dashboardState.date ? formatISO(dashboardState.date) : null,dimensions: reportParams.dimensions || [],metrics: reportParams.metrics,- filters: remapToApiFilters(dashboardState.filters),+ filters: [+ ...remapToApiFilters(dashboardState.filters),+ ...(reportParams.alwaysOnFilters ?? [])+ ],order_by: reportParams.order_by || null,pagination: reportParams.pagination || null,include: {diff --git a/assets/js/dashboard/stats/breakdowns.tsx b/assets/js/dashboard/stats/breakdowns.tsxindex d8128121b0..249d7785f7 100644--- a/assets/js/dashboard/stats/breakdowns.tsx+++ b/assets/js/dashboard/stats/breakdowns.tsx@@ -14,10 +14,6 @@ import {} from '../stats-query'import { Filter } from '../dashboard-state'import { MetricsByContext } from './reports/reports-config'-import {- defaultGetStatsQuery,- StatsReportQueryKey-} from '../hooks/use-query-api'import classNames from 'classnames'import { DIRECT_NONE } from './sources'@@ -25,6 +21,7 @@ export type SharedBreakdownReportProps = {dimensionLabel: stringdimensions: NonTimeDimension[]metrics: Metric[]+ alwaysOnFilters?: ApiFilter[]}export type ColumnConfiguration<T> = {@@ -43,37 +40,6 @@ export type ColumnConfiguration<T> = {align?: 'left' | 'right'}-const FILTER_DIMENSIONS_NOT = {- 'visit:city': [0],- 'visit:country': ['\0\0', 'ZZ'],- 'visit:region': [''],- 'visit:utm_medium': [''],- 'visit:utm_source': [''],- 'visit:utm_campaign': [''],- 'visit:utm_content': [''],- 'visit:utm_term': [''],- 'visit:entry_page': [''],- 'visit:exit_page': ['']-}--export function getStatsQueryWithImplicitNotEmptyFilter(- queryKey: StatsReportQueryKey-) {- let statsQuery = defaultGetStatsQuery(queryKey)-- const dimension = queryKey[1].reportParams.dimensions[0]-- if (Object.keys(FILTER_DIMENSIONS_NOT).includes(dimension)) {- statsQuery = addFilter(statsQuery, [- 'is_not',- dimension,- FILTER_DIMENSIONS_NOT[dimension as keyof typeof FILTER_DIMENSIONS_NOT]- ])- }-- return statsQuery-}-export type GetFilterInfo = (dimension: NonTimeDimension,row: QueryResultRowdiff --git a/assets/js/dashboard/stats/devices/details.tsx b/assets/js/dashboard/stats/devices/details.tsxindex 6eb91a21e4..6dbd7c739f 100644--- a/assets/js/dashboard/stats/devices/details.tsx+++ b/assets/js/dashboard/stats/devices/details.tsx@@ -64,6 +64,7 @@ export function DevicesDetails({dimensionLabel={reportConfig.dimensionLabel}dimensions={reportConfig.dimensions}metrics={metrics}+ alwaysOnFilters={reportConfig.alwaysOnFilters}defaultOrderBy={[['visitors', 'desc']]}searchEnabled={searchEnabled}DimensionElement={DimensionElement}diff --git a/assets/js/dashboard/stats/devices/index.tsx b/assets/js/dashboard/stats/devices/index.tsxindex 876c460ad5..7cc262c174 100644--- a/assets/js/dashboard/stats/devices/index.tsx+++ b/assets/js/dashboard/stats/devices/index.tsx@@ -112,6 +112,7 @@ export function Devices() {metrics={metrics}dimensions={reportConfig.dimensions}dimensionLabel={reportConfig.dimensionLabel}+ alwaysOnFilters={reportConfig.alwaysOnFilters}DimensionElement={DimensionElement}onDataReady={setCurrentData}/>diff --git a/assets/js/dashboard/stats/locations/countries.ts b/assets/js/dashboard/stats/locations/countries.tsnew file mode 100644index 0000000000..37757b8ca3--- /dev/null+++ b/assets/js/dashboard/stats/locations/countries.ts@@ -0,0 +1,37 @@+import worldJson from 'visionscarto-world-atlas/world/110m.json'+import countriesMeta from '../../../../data/countries_meta.json'+import * as topojson from 'topojson-client'++// The actual type is more extensive, this is only the part that we care about+export type WorldJsonCountryData = { properties: { a3: string } }++export function parseWorldTopoJsonToGeoJsonFeatures(): Array<WorldJsonCountryData> {+ const collection = topojson.feature(+ // @ts-expect-error strings in worldJson not recongizable as the enum values declared in library+ worldJson,+ worldJson.objects.countries+ )+ // @ts-expect-error topojson.feature return type incorrectly inferred as not a collection+ return collection.features+}++export type CountryEntry = {+ // alpha_3 is null for non-country override entries like "A1" (Anonymous VPN)+ alpha_3: string | null+ flag: string+}++type CountryTwoLetterCode = string++export type CountriesLookup = Record<CountryTwoLetterCode, CountryEntry>++const remapCountriesMeta = () => {+ const result: CountriesLookup = {}+ for (const [alpha_2, [alpha_3, flag]] of Object.entries(countriesMeta)) {+ // flag is definitely defined in the source file+ const entry: CountryEntry = { alpha_3, flag: flag! }+ Object.assign(result, { [alpha_2]: entry })+ }+ return result+}+export const COUNTRIES_BY_TWO_LETTER_CODE = remapCountriesMeta()diff --git a/assets/js/dashboard/stats/locations/details.tsx b/assets/js/dashboard/stats/locations/details.tsxnew file mode 100644index 0000000000..7d2353bf71--- /dev/null+++ b/assets/js/dashboard/stats/locations/details.tsx@@ -0,0 +1,111 @@+import React, { ReactNode } from 'react'+import { revenueAvailable } from '../../dashboard-state'+import { useDashboardStateContext } from '../../dashboard-state-context'+import { useSiteContext } from '../../site-context'+import {+ hasConversionGoalFilter,+ isRealTimeDashboard+} from '../../util/filters'+import { chooseBreakdownMetricsByContext } from '../breakdowns'+import {+ BREAKDOWN_REPORTS,+ BreakdownReportKey+} from '../reports/reports-config'+import {+ DetailsBreakdown,+ DimensionCell,+ DimensionCellProps+} from '../modals/details-breakdown'+import Modal from '../modals/modal'+import {+ getCitiesFilterInfo,+ getCountriesFilterInfo,+ getRegionsFilterInfo,+ LocationsReportKey+} from '.'+import { FlagEmoji } from './flag-emoji'++export function LocationsDetails({+ reportKey+}: {+ reportKey: LocationsReportKey+}) {+ const { dashboardState } = useDashboardStateContext()+ const site = useSiteContext()+ const reportConfig = BREAKDOWN_REPORTS[reportKey]++ /*global BUILD_EXTRA*/+ const isRevenueAvailable =+ BUILD_EXTRA && revenueAvailable(dashboardState, site)++ const metrics = chooseBreakdownMetricsByContext(+ reportConfig.metricsByContext,+ {+ hasConversionGoalFilter: hasConversionGoalFilter(dashboardState),+ isRealtime: isRealTimeDashboard(dashboardState),+ isDetailed: true,+ isRevenueAvailable: isRevenueAvailable+ }+ )++ const DimensionElement = DIMENSION_ELEMENTS[reportKey]++ return (+ <Modal>+ <DetailsBreakdown+ title={reportConfig.detailsTitle}+ dimensionLabel={reportConfig.dimensionLabel}+ dimensions={reportConfig.dimensions}+ metrics={metrics}+ alwaysOnFilters={reportConfig.alwaysOnFilters}+ defaultOrderBy={[['visitors', 'desc']]}+ DimensionElement={DimensionElement}+ />+ </Modal>+ )+}++const CountryDimensionCell = (props: DimensionCellProps) => {+ const [countryName, countryCode] = props.row.dimensions+ return (+ <DimensionCell+ {...props}+ text={countryName}+ icon={<FlagEmoji countryCode={countryCode} />}+ getFilterInfo={getCountriesFilterInfo}+ />+ )+}++const RegionsDimensionCell = (props: DimensionCellProps) => {+ const [regionName, _regionCode, countryCode] = props.row.dimensions+ return (+ <DimensionCell+ {...props}+ text={regionName}+ icon={<FlagEmoji countryCode={countryCode} />}+ getFilterInfo={getRegionsFilterInfo}+ />+ )+}++const CitiesDimensionCell = (props: DimensionCellProps) => {+ const [cityName, _cityCode, countryCode] = props.row.dimensions+ return (+ <DimensionCell+ {...props}+ text={cityName}+ icon={<FlagEmoji countryCode={countryCode} />}+ getFilterInfo={getCitiesFilterInfo}+ />+ )+}++const DIMENSION_ELEMENTS: Record<+ LocationsReportKey,+ (props: DimensionCellProps) => ReactNode+> = {+ [BreakdownReportKey.countries]: CountryDimensionCell,+ [BreakdownReportKey.regions]: RegionsDimensionCell,+ [BreakdownReportKey.cities]: CitiesDimensionCell+}diff --git a/assets/js/dashboard/stats/locations/flag-emoji.tsx b/assets/js/dashboard/stats/locations/flag-emoji.tsxnew file mode 100644index 0000000000..314d725337--- /dev/null+++ b/assets/js/dashboard/stats/locations/flag-emoji.tsx@@ -0,0 +1,13 @@+import React from 'react'+import { COUNTRIES_BY_TWO_LETTER_CODE } from './countries'++export const FlagEmoji = ({ countryCode }: { countryCode: string | null }) => {+ if (!countryCode) {+ return null+ }+ const entry = COUNTRIES_BY_TWO_LETTER_CODE[countryCode]+ if (!entry?.flag) {+ return null+ }+ return <span className="mr-1.5">{entry.flag}</span>+}diff --git a/assets/js/dashboard/stats/locations/index.js b/assets/js/dashboard/stats/locations/index.jsdeleted file mode 100644index b083a2da16..0000000000--- a/assets/js/dashboard/stats/locations/index.js+++ /dev/null@@ -1,315 +0,0 @@-import React from 'react'--import * as storage from '../../util/storage'-import CountriesMap from './map'--import * as api from '../../api'-import { apiPath } from '../../util/url'-import ListReport from '../reports/list-legacy'-import * as metrics from '../reports/metrics'-import {- hasConversionGoalFilter,- getFiltersByKeyPrefix-} from '../../util/filters'-import ImportedQueryUnsupportedWarning from '../imported-query-unsupported-warning'-import { citiesRoute, countriesRoute, regionsRoute } from '../../router'-import { useDashboardStateContext } from '../../dashboard-state-context'-import { useSiteContext } from '../../site-context'-import { ReportLayout } from '../reports/report-layout'-import { ReportHeader } from '../reports/report-header'-import { TabButton, TabWrapper } from '../../components/tabs'-import MoreLink from '../more-link'-import { MoreLinkState } from '../more-link-state'--function Countries({ dashboardState, site, onClick, afterFetchData }) {- function fetchData() {- return api.get(apiPath(site, '/countries'), dashboardState, { limit: 9 })- }-- function renderIcon(country) {- return <span className="mr-2">{country.flag}</span>- }-- function getFilterInfo(listItem) {- return {- prefix: 'country',- filter: ['is', 'country', [listItem['code']]],- labels: { [listItem['code']]: listItem['name'] }- }- }-- function chooseMetrics() {- return [- metrics.createVisitors({ meta: { plot: true } }),- !hasConversionGoalFilter(dashboardState) &&- metrics.createPercentage({ meta: { showOnHover: true } }),- hasConversionGoalFilter(dashboardState) && metrics.createConversionRate()- ].filter((metric) => !!metric)- }-- return (- <ListReport- fetchData={fetchData}- afterFetchData={afterFetchData}- getFilterInfo={getFilterInfo}- onClick={onClick}- keyLabel="Country"- metrics={chooseMetrics()}- renderIcon={renderIcon}- color="bg-orange-50 group-hover/row:bg-orange-100"- />- )-}--function Regions({ dashboardState, site, onClick, afterFetchData }) {- function fetchData() {- return api.get(apiPath(site, '/regions'), dashboardState, { limit: 9 })- }-- function renderIcon(region) {- return <span className="mr-2">{region.country_flag}</span>- }-- function getFilterInfo(listItem) {- return {- prefix: 'region',- filter: ['is', 'region', [listItem['code']]],- labels: { [listItem['code']]: listItem['name'] }- }- }-- function chooseMetrics() {- return [- metrics.createVisitors({ meta: { plot: true } }),- !hasConversionGoalFilter(dashboardState) &&- metrics.createPercentage({ meta: { showOnHover: true } }),- hasConversionGoalFilter(dashboardState) && metrics.createConversionRate()- ].filter((metric) => !!metric)- }-- return (- <ListReport- fetchData={fetchData}- afterFetchData={afterFetchData}- getFilterInfo={getFilterInfo}- onClick={onClick}- keyLabel="Region"- metrics={chooseMetrics()}- renderIcon={renderIcon}- color="bg-orange-50 group-hover/row:bg-orange-100"- />- )-}--function Cities({ dashboardState, site, afterFetchData }) {- function fetchData() {- return api.get(apiPath(site, '/cities'), dashboardState, { limit: 9 })- }-- function renderIcon(city) {- return <span className="mr-2">{city.country_flag}</span>- }-- function getFilterInfo(listItem) {- return {- prefix: 'city',- filter: ['is', 'city', [listItem['code']]],- labels: { [listItem['code']]: listItem['name'] }- }- }-- function chooseMetrics() {- return [- metrics.createVisitors({ meta: { plot: true } }),- !hasConversionGoalFilter(dashboardState) &&- metrics.createPercentage({ meta: { showOnHover: true } }),- hasConversionGoalFilter(dashboardState) && metrics.createConversionRate()- ].filter((metric) => !!metric)- }-- return (- <ListReport- fetchData={fetchData}- afterFetchData={afterFetchData}- getFilterInfo={getFilterInfo}- keyLabel="City"- metrics={chooseMetrics()}- renderIcon={renderIcon}- color="bg-orange-50 group-hover/row:bg-orange-100"- />- )-}--class Locations extends React.Component {- constructor(props) {- super(props)- this.onCountryFilter = this.onCountryFilter.bind(this)- this.onRegionFilter = this.onRegionFilter.bind(this)- this.afterFetchData = this.afterFetchData.bind(this)- this.tabKey = `geoTab__${props.site.domain}`- const storedTab = storage.getItem(this.tabKey)- this.state = {- mode: storedTab || 'map',- loading: true,- skipImportedReason: null,- moreLinkState: MoreLinkState.LOADING- }- }-- componentDidUpdate(prevProps, prevState) {- const isRemovingFilter = (filterName) => {- return (- getFiltersByKeyPrefix(prevProps.dashboardState, filterName).length >- 0 &&- getFiltersByKeyPrefix(this.props.dashboardState, filterName).length == 0- )- }-- if (this.state.mode === 'cities' && isRemovingFilter('region')) {- this.setMode('regions')()- }-- if (this.state.mode === 'regions' && isRemovingFilter('country')) {- this.setMode(this.countriesRestoreMode || 'countries')()- }-- if (- this.props.dashboardState !== prevProps.dashboardState ||- this.state.mode !== prevState.mode- ) {- this.setState({ loading: true, moreLinkState: MoreLinkState.LOADING })- }- }-- setMode(mode) {- return () => {- storage.setItem(this.tabKey, mode)- this.setState({ mode })- }- }-- onCountryFilter(mode) {- return () => {- this.countriesRestoreMode = mode- this.setMode('regions')()- }- }-- onRegionFilter() {- this.setMode('cities')()- }-- afterFetchData(apiResponse) {- let newMoreLinkState-- if (apiResponse.results && apiResponse.results.length > 0) {- newMoreLinkState = MoreLinkState.READY- } else {- newMoreLinkState = MoreLinkState.HIDDEN- }- this.setState({- loading: false,- moreLinkState: newMoreLinkState,- skipImportedReason: apiResponse.skip_imported_reason- })- }-- renderContent() {- switch (this.state.mode) {- case 'cities':- return (- <Cities- site={this.props.site}- dashboardState={this.props.dashboardState}- afterFetchData={this.afterFetchData}- />- )- case 'regions':- return (- <Regions- onClick={this.onRegionFilter}- site={this.props.site}- dashboardState={this.props.dashboardState}- afterFetchData={this.afterFetchData}- />- )- case 'countries':- return (- <Countries- onClick={this.onCountryFilter('countries')}- site={this.props.site}- dashboardState={this.props.dashboardState}- afterFetchData={this.afterFetchData}- />- )- case 'map':- default:- return (- <CountriesMap- onCountrySelect={this.onCountryFilter('map')}- afterFetchData={this.afterFetchData}- />- )- }- }-- getMoreLinkProps() {- let path-- if (this.state.mode === 'regions') {- path = regionsRoute.path- } else if (this.state.mode === 'cities') {- path = citiesRoute.path- } else {- path = countriesRoute.path- }-- return { path: path, search: (search) => search }- }-- render() {- return (- <ReportLayout- testId="report-locations"- className={this.state.mode === 'map' ? '' : 'overflow-x-hidden'}- >- <ReportHeader>- <div className="flex gap-x-3">- <TabWrapper>- {[- { label: 'Map', value: 'map' },- { label: 'Countries', value: 'countries' },- { label: 'Regions', value: 'regions' },- { label: 'Cities', value: 'cities' }- ].map(({ value, label }) => (- <TabButton- key={value}- onClick={this.setMode(value)}- active={this.state.mode === value}- >- {label}- </TabButton>- ))}- </TabWrapper>- <ImportedQueryUnsupportedWarning- loading={this.state.loading}- skipImportedReason={this.state.skipImportedReason}- />- </div>- <MoreLink- linkProps={this.getMoreLinkProps()}- state={this.state.moreLinkState}- />- </ReportHeader>- {this.renderContent()}- </ReportLayout>- )- }-}--function LocationsWithContext() {- const { dashboardState } = useDashboardStateContext()- const site = useSiteContext()- return <Locations site={site} dashboardState={dashboardState} />-}-export default LocationsWithContextdiff --git a/assets/js/dashboard/stats/locations/index.tsx b/assets/js/dashboard/stats/locations/index.tsxnew file mode 100644index 0000000000..a899dcf7cd--- /dev/null+++ b/assets/js/dashboard/stats/locations/index.tsx@@ -0,0 +1,316 @@+import React, { useCallback, useEffect, useRef, useState } from 'react'++import * as storage from '../../util/storage'+import CountriesMap from './map'++import {+ hasConversionGoalFilter,+ isRealTimeDashboard,+ getFiltersByKeyPrefix+} from '../../util/filters'+import { useDashboardStateContext } from '../../dashboard-state-context'+import { useSiteContext } from '../../site-context'+import { ReportLayout } from '../reports/report-layout'+import { ReportHeader } from '../reports/report-header'+import { TabButton, TabWrapper } from '../../components/tabs'+import MoreLink from '../more-link'+import { MoreLinkState } from '../more-link-state'+import { QueryApiResponse, QueryResultRow } from '../../api'+import ImportedWarningBubble from '../imported-warning-bubble'+import {+ BREAKDOWN_REPORTS,+ BreakdownReportKey+} from '../reports/reports-config'+import {+ DimensionCellWithBar,+ DimensionCellWithBarProps,+ IndexBreakdown+} from '../reports/index-breakdown'+import { chooseBreakdownMetricsByContext } from '../breakdowns'+import { FilterInfo } from '../../components/drilldown-link'+import { NonTimeDimension } from '../../stats-query'+import { FlagEmoji } from './flag-emoji'+import { DashboardState } from '../../dashboard-state'++type MapTabKey = 'map'+type TabKey =+ | MapTabKey+ | BreakdownReportKey.countries+ | BreakdownReportKey.regions+ | BreakdownReportKey.cities++export type LocationsReportKey =+ | BreakdownReportKey.countries+ | BreakdownReportKey.regions+ | BreakdownReportKey.cities++const BAR_COLOR = 'bg-orange-50 group-hover/row:bg-orange-100'++const initTab = (storedTab: string | null): TabKey => {+ switch (storedTab) {+ case BreakdownReportKey.countries:+ return BreakdownReportKey.countries+ case BreakdownReportKey.regions:+ return BreakdownReportKey.regions+ case BreakdownReportKey.cities:+ return BreakdownReportKey.cities+ case 'map':+ default:+ return 'map'+ }+}++const getAppliedLocationsFilters = (dashboardState: DashboardState) => ({+ countryFiltersApplied:+ getFiltersByKeyPrefix(dashboardState, 'country').length > 0,+ regionFiltersApplied:+ getFiltersByKeyPrefix(dashboardState, 'region').length > 0+})++export function Locations() {+ const { dashboardState } = useDashboardStateContext()+ const site = useSiteContext()++ const tabKey = `geoTab__${site.domain}`+ const [tab, setTab] = useState<TabKey>(initTab(storage.getItem(tabKey)))+ // determines whether to show list or map (the default) when zooming out of Regions tab+ const [prefersCountriesList, setPrefersCountriesList] =+ useState<boolean>(false)+ const [currentData, setCurrentData] = useState<QueryApiResponse | null>(null)++ useEffect(() => {+ storage.setItem(tabKey, tab)+ }, [tabKey, tab])++ const prevFilters = useRef<{+ countryFiltersApplied: boolean+ regionFiltersApplied: boolean+ }>(getAppliedLocationsFilters(dashboardState))++ /**+ * Clicking on a country applies "Country is ..." filter and zooms to Regions tab,+ * clicking on a region applies "Region is ..." filter and zooms to Cities tab (see onClick handlers below).+ * This effect handles zooming out of Regions tab on dismissing the countries filter,+ * and zooming out of Cities tab on dismissing the regions filter.+ */+ useEffect(() => {+ setTab((currentTab) => {+ const { countryFiltersApplied, regionFiltersApplied } =+ getAppliedLocationsFilters(dashboardState)+ const prev = { ...prevFilters.current }+ prevFilters.current = { countryFiltersApplied, regionFiltersApplied }++ if (+ currentTab === BreakdownReportKey.regions &&+ prev.countryFiltersApplied &&+ !countryFiltersApplied+ ) {+ return prefersCountriesList ? BreakdownReportKey.countries : 'map'+ }++ if (+ currentTab === BreakdownReportKey.cities &&+ prev.regionFiltersApplied &&+ !regionFiltersApplied+ ) {+ return BreakdownReportKey.regions+ }++ return currentTab+ })+ }, [prefersCountriesList, dashboardState])++ const selectedListKey: LocationsReportKey =+ tab === 'map' ? BreakdownReportKey.countries : tab+ const reportConfig = BREAKDOWN_REPORTS[selectedListKey]++ const metrics = chooseBreakdownMetricsByContext(+ reportConfig.metricsByContext,+ {+ isRealtime: isRealTimeDashboard(dashboardState),+ isDetailed: false,+ hasConversionGoalFilter: hasConversionGoalFilter(dashboardState),+ isRevenueAvailable: false+ }+ )++ const moreLinkState = currentData+ ? currentData.results.length > 0+ ? MoreLinkState.READY+ : MoreLinkState.HIDDEN+ : MoreLinkState.LOADING++ const moreLinkPath = reportConfig.detailsPath++ const CountriesDimensionElement = useCallback(+ (props: DimensionCellWithBarProps) => (+ <CountriesDimensionCell+ {...props}+ onClick={() => {+ setPrefersCountriesList(true)+ setTab(BreakdownReportKey.regions)+ }}+ />+ ),+ []+ )++ const RegionsDimensionElement = useCallback(+ (props: DimensionCellWithBarProps) => (+ <RegionsDimensionCell+ {...props}+ onClick={() => setTab(BreakdownReportKey.cities)}+ />+ ),+ []+ )++ const DimensionElement = {+ [BreakdownReportKey.countries]: CountriesDimensionElement,+ [BreakdownReportKey.regions]: RegionsDimensionElement,+ [BreakdownReportKey.cities]: CitiesDimensionCell+ }[selectedListKey]++ return (+ <ReportLayout+ testId="report-locations"+ className={tab === 'map' ? '' : 'overflow-x-hidden'}+ >+ <ReportHeader>+ <div className="flex gap-x-3">+ <TabWrapper>+ {(+ [+ { label: 'Map', value: 'map' },+ {+ label: 'Countries',+ value: BreakdownReportKey.countries+ },+ { label: 'Regions', value: BreakdownReportKey.regions },+ { label: 'Cities', value: BreakdownReportKey.cities }+ ] as const+ ).map(({ label, value }) => (+ <TabButton+ key={value}+ active={tab === value}+ onClick={() => setTab(value)}+ >+ {label}+ </TabButton>+ ))}+ </TabWrapper>+ <ImportedWarningBubble queryApiResponse={currentData} />+ </div>+ <MoreLink+ state={moreLinkState}+ linkProps={{+ path: moreLinkPath,+ search: (search: string) => search+ }}+ />+ </ReportHeader>+ {tab === 'map' ? (+ <CountriesMap+ onCountrySelect={() => {+ setPrefersCountriesList(false)+ setTab(BreakdownReportKey.regions)+ }}+ onDataReady={setCurrentData}+ />+ ) : (+ <IndexBreakdown+ metrics={metrics}+ dimensions={reportConfig.dimensions}+ dimensionLabel={reportConfig.dimensionLabel}+ alwaysOnFilters={reportConfig.alwaysOnFilters}+ DimensionElement={DimensionElement}+ onDataReady={setCurrentData}+ />+ )}+ </ReportLayout>+ )+}++const CountriesDimensionCell = (+ props: DimensionCellWithBarProps & { onClick: () => void }+) => {+ const [countryName, countryCode] = props.row.dimensions+ return (+ <DimensionCellWithBar+ {...props}+ barClassName={BAR_COLOR}+ text={countryName}+ icon={<FlagEmoji countryCode={countryCode} />}+ getFilterInfo={getCountriesFilterInfo}+ />+ )+}++const RegionsDimensionCell = (+ props: DimensionCellWithBarProps & { onClick: () => void }+) => {+ const [regionName, _regionCode, countryCode] = props.row.dimensions+ return (+ <DimensionCellWithBar+ {...props}+ barClassName={BAR_COLOR}+ text={regionName}+ icon={<FlagEmoji countryCode={countryCode} />}+ getFilterInfo={getRegionsFilterInfo}+ />+ )+}++const CitiesDimensionCell = (props: DimensionCellWithBarProps) => {+ const [cityName, _cityCode, countryCode] = props.row.dimensions+ return (+ <DimensionCellWithBar+ {...props}+ barClassName={BAR_COLOR}+ text={cityName}+ icon={<FlagEmoji countryCode={countryCode} />}+ getFilterInfo={getCitiesFilterInfo}+ />+ )+}++export const getCountriesFilterInfo = (+ _dimension: NonTimeDimension,+ row: QueryResultRow+): FilterInfo => {+ const [countryName, countryCode] = row.dimensions++ return {+ prefix: 'country',+ filter: ['is', 'country', [countryCode]],+ labels: { [countryCode]: countryName }+ }+}++export const getRegionsFilterInfo = (+ _dimension: NonTimeDimension,+ row: QueryResultRow+): FilterInfo => {+ const [regionName, regionCode, _countryCode] = row.dimensions++ return {+ prefix: 'region',+ filter: ['is', 'region', [regionCode]],+ labels: { [regionCode]: regionName }+ }+}++export const getCitiesFilterInfo = (+ _dimension: NonTimeDimension,+ row: QueryResultRow+): FilterInfo => {+ const [cityName, cityCode, _countryCode] = row.dimensions++ return {+ prefix: 'city',+ filter: ['is', 'city', [cityCode]],+ labels: { [cityCode]: cityName }+ }+}++export default Locationsdiff --git a/assets/js/dashboard/stats/locations/map.tsx b/assets/js/dashboard/stats/locations/map.tsxindex 60b0bdfdda..f773bfbd78 100644--- a/assets/js/dashboard/stats/locations/map.tsx+++ b/assets/js/dashboard/stats/locations/map.tsx@@ -1,7 +1,6 @@import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'import * as d3 from 'd3'import classNames from 'classnames'-import * as api from '../../api'import {replaceFilterByPrefix,cleanLabels,@@ -10,17 +9,24 @@ import {} from '../../util/filters'import { useAppNavigate } from '../../navigation/use-app-navigate'import { numberShortFormatter } from '../../util/number-formatter'-import * as topojson from 'topojson-client'-import { useQuery } from '@tanstack/react-query'import { useSiteContext } from '../../site-context'import { useDashboardStateContext } from '../../dashboard-state-context'-import worldJson from 'visionscarto-world-atlas/world/110m.json'import { UIMode, useTheme } from '../../theme-context'-import { apiPath } from '../../util/url'import { MIN_HEIGHT } from '../reports/list-legacy'import { MapTooltip } from './map-tooltip'import { GeolocationNotice } from './geolocation-notice'import { DashboardState } from '../../dashboard-state'+import { useQueryApi } from '../../hooks/use-query-api'+import { QueryApiResponse } from '../../api'+import {+ COUNTRIES_BY_TWO_LETTER_CODE,+ parseWorldTopoJsonToGeoJsonFeatures,+ WorldJsonCountryData+} from './countries'+import {+ BREAKDOWN_REPORTS,+ BreakdownReportKey+} from '../reports/reports-config'const width = 475const height = 335@@ -31,7 +37,6 @@ type CountryData = {visitors: numbercode: string}-type WorldJsonCountryData = { properties: { name: string; a3: string } }function getMetricLabel(dashboardState: DashboardState) {if (hasConversionGoalFilter(dashboardState)) {@@ -45,10 +50,10 @@ function getMetricLabel(dashboardState: DashboardState) {const WorldMap = ({onCountrySelect,- afterFetchData+ onDataReady}: {onCountrySelect: () => void- afterFetchData: (response: unknown) => void+ onDataReady: (response: QueryApiResponse) => void}) => {const navigate = useAppNavigate()const { mode } = useTheme()@@ -66,49 +71,52 @@ const WorldMap = ({[dashboardState])- const { data, refetch, isFetching, isError } = useQuery({- queryKey: ['countries', 'map', dashboardState],- placeholderData: (previousData) => previousData,- queryFn: async (): Promise<{- results: CountryData[]- }> => {- return await api.get(apiPath(site, '/countries'), dashboardState, {- limit: 300- })- }- })-- useEffect(() => {- const onTickRefetchData = () => {- if (dashboardState.period === 'realtime') {- refetch()+ const { apiState } = useQueryApi(site, [+ 'visit:country',+ {+ dashboardState,+ reportParams: {+ metrics: ['visitors'],+ dimensions: BREAKDOWN_REPORTS[BreakdownReportKey.countries].dimensions,+ alwaysOnFilters:+ BREAKDOWN_REPORTS[BreakdownReportKey.countries].alwaysOnFilters,+ order_by: [['visitors', 'desc']],+ pagination: { limit: 300, offset: 0 }}}- document.addEventListener('tick', onTickRefetchData)- return () => document.removeEventListener('tick', onTickRefetchData)- }, [dashboardState.period, refetch])+ ])+ const { data, isFetching, isError } = apiStateuseEffect(() => {if (data) {- afterFetchData(data)+ onDataReady(data)}- }, [afterFetchData, data, isFetching])+ }, [onDataReady, data])- const { maxValue, dataByCountryCode } = useMemo(() => {- const dataByCountryCode: Map<string, CountryData> = new Map()+ const { maxValue, dataByAlpha3Code } = useMemo(() => {+ const dataByAlpha3Code: Map<string, CountryData> = new Map()let maxValue = 0- for (const { alpha_3, visitors, name, code } of data?.results || []) {+ for (const row of data?.results ?? []) {+ const [countryName, countryCode] = row.dimensions+ const [visitors] = row.metrics as [number]+ const entry = COUNTRIES_BY_TWO_LETTER_CODE[countryCode]+ if (!entry || !entry.alpha_3) continueif (visitors > maxValue) {maxValue = visitors}- dataByCountryCode.set(alpha_3, { alpha_3, visitors, name, code })+ dataByAlpha3Code.set(entry.alpha_3, {+ alpha_3: entry.alpha_3,+ visitors,+ name: countryName,+ code: countryCode+ })}- return { maxValue, dataByCountryCode }+ return { maxValue, dataByAlpha3Code }}, [data])const onCountryClick = useCallback((d: WorldJsonCountryData) => {- const country = dataByCountryCode.get(d.properties.a3)+ const country = dataByAlpha3Code.get(d.properties.a3)const clickable = country && country.visitorsif (clickable) {const filters = replaceFilterByPrefix(dashboardState, 'country', [@@ -125,7 +133,7 @@ const WorldMap = ({})}},- [navigate, dashboardState, dataByCountryCode, onCountrySelect]+ [navigate, dashboardState, dataByAlpha3Code, onCountrySelect])useEffect(() => {@@ -173,15 +181,15 @@ const WorldMap = ({colorInCountriesWithValues(svgRef.current,getColorForValue,- dataByCountryCode+ dataByAlpha3Code).on('click', (_event, countryPath) => {onCountryClick(countryPath as unknown as WorldJsonCountryData)})}- }, [mode, maxValue, dataByCountryCode, onCountryClick])+ }, [mode, maxValue, dataByAlpha3Code, onCountryClick])const hoveredCountryData = tooltip.hoveredCountryAlpha3Code- ? dataByCountryCode.get(tooltip.hoveredCountryAlpha3Code)+ ? dataByAlpha3Code.get(tooltip.hoveredCountryAlpha3Code): undefinedreturn (@@ -274,25 +282,19 @@ function colorInCountriesWithValues(getColorForValue: d3.ScaleLinear<string, string, never>,dataByCountryCode: Map<string, CountryData>) {- function getCountryByCountryPath(countryPath: unknown) {- return dataByCountryCode.get(- (countryPath as unknown as WorldJsonCountryData).properties.a3- )- }-const svg = d3.select(element)return svg- .selectAll(countrySelector)+ .selectAll<SVGPathElement, WorldJsonCountryData>(countrySelector).style('fill', (countryPath) => {- const country = getCountryByCountryPath(countryPath)+ const country = dataByCountryCode.get(countryPath.properties.a3)if (!country?.visitors) {return null}return getColorForValue(country.visitors)}).style('cursor', (countryPath) => {- const country = getCountryByCountryPath(countryPath)+ const country = dataByCountryCode.get(countryPath.properties.a3)if (!country?.visitors) {return null}@@ -304,7 +306,6 @@ function drawHighlightedCountryOutline(element: SVGSVGElement) {return d3.select(element).append('path').attr('class', initialOutlineClass)}-/** @returns the d3 selected svg element */function drawInteractiveCountries(element: SVGSVGElement) {const path = setupProjetionPath()const data = parseWorldTopoJsonToGeoJsonFeatures()@@ -331,14 +332,4 @@ function setupProjetionPath() {return path}-function parseWorldTopoJsonToGeoJsonFeatures(): Array<WorldJsonCountryData> {- const collection = topojson.feature(- // @ts-expect-error strings in worldJson not recongizable as the enum values declared in library- worldJson,- worldJson.objects.countries- )- // @ts-expect-error topojson.feature return type incorrectly inferred as not a collection- return collection.features-}-export default WorldMapdiff --git a/assets/js/dashboard/stats/modals/breakdown-modal-legacy.tsx b/assets/js/dashboard/stats/modals/breakdown-modal-legacy.tsxindex 7189784fc3..30a71007e2 100644--- a/assets/js/dashboard/stats/modals/breakdown-modal-legacy.tsx+++ b/assets/js/dashboard/stats/modals/breakdown-modal-legacy.tsx@@ -224,7 +224,7 @@ const NameCell = <TListItem extends { name: string }>({path={rootRoute.path}filterInfo={getFilterInfo(item)}onClick={undefined}- extraClass={undefined}+ className={undefined}>{item.name}</DrilldownLink>diff --git a/assets/js/dashboard/stats/modals/details-breakdown.tsx b/assets/js/dashboard/stats/modals/details-breakdown.tsxindex 2a3e8f2955..b0da564665 100644--- a/assets/js/dashboard/stats/modals/details-breakdown.tsx+++ b/assets/js/dashboard/stats/modals/details-breakdown.tsx@@ -30,7 +30,6 @@ import {formatDateRangeLabel,useBodyPortalRef,extractMetricValue,- getStatsQueryWithImplicitNotEmptyFilter,GetFilterInfo} from '../breakdowns'import {@@ -87,6 +86,7 @@ export function DetailsBreakdown({dimensionLabel,dimensions,metrics,+ alwaysOnFilters,defaultOrderBy = [] as MetricOrderBy,DimensionElement,searchEnabled = true,@@ -124,15 +124,14 @@ export function DetailsBreakdown({order_by: [...(orderBy.length ? orderBy : storedOrderBy),...dimensions.map((dim): OrderByEntry => [dim, 'asc'])- ]+ ],+ alwaysOnFilters},search}]- const apiState = useSearchAndPaginateQueryAPI(site, statsReportQueryKey, {- getStatsQuery: getStatsQueryWithImplicitNotEmptyFilter- })+ const apiState = useSearchAndPaginateQueryAPI(site, statsReportQueryKey)useEffect(() => {const pages = apiState.data?.pages@@ -491,8 +490,8 @@ export const DimensionCell = ({<DrilldownLinkpath={rootRoute.path}filterInfo={getFilterInfo(filterDimension, row)}+ icon={icon}>- {icon}{text}</DrilldownLink>{externalLink}diff --git a/assets/js/dashboard/stats/modals/locations-modal.js b/assets/js/dashboard/stats/modals/locations-modal.jsdeleted file mode 100644index 739a0cd084..0000000000--- a/assets/js/dashboard/stats/modals/locations-modal.js+++ /dev/null@@ -1,127 +0,0 @@-import React, { useCallback } from 'react'--import Modal from './modal'-import {- hasConversionGoalFilter,- isRealTimeDashboard-} from '../../util/filters'-import BreakdownModal from './breakdown-modal-legacy'-import * as metrics from '../reports/metrics'-import * as url from '../../util/url'-import { useDashboardStateContext } from '../../dashboard-state-context'-import { useSiteContext } from '../../site-context'-import { addFilter, revenueAvailable } from '../../dashboard-state'--const VIEWS = {- countries: {- title: 'Top countries',- dimension: 'country',- endpoint: '/countries',- dimensionLabel: 'Country',- defaultOrder: ['visitors', 'desc']- },- regions: {- title: 'Top regions',- dimension: 'region',- endpoint: '/regions',- dimensionLabel: 'Region',- defaultOrder: ['visitors', 'desc']- },- cities: {- title: 'Top cities',- dimension: 'city',- endpoint: '/cities',- dimensionLabel: 'City',- defaultOrder: ['visitors', 'desc']- }-}--function LocationsModal({ currentView }) {- const { dashboardState } = useDashboardStateContext()- const site = useSiteContext()-- /*global BUILD_EXTRA*/- const showRevenueMetrics =- BUILD_EXTRA && revenueAvailable(dashboardState, site)-- let reportInfo = VIEWS[currentView]- reportInfo = {- ...reportInfo,- endpoint: url.apiPath(site, reportInfo.endpoint)- }-- const getFilterInfo = useCallback(- (listItem) => {- return {- prefix: reportInfo.dimension,- filter: ['is', reportInfo.dimension, [listItem.code]],- labels: { [listItem.code]: listItem.name }- }- },- [reportInfo.dimension]- )-- const addSearchFilter = useCallback(- (dashboardState, searchString) => {- return addFilter(dashboardState, [- 'contains',- `${reportInfo.dimension}_name`,- [searchString],- { case_sensitive: false }- ])- },- [reportInfo.dimension]- )-- function chooseMetrics() {- if (hasConversionGoalFilter(dashboardState)) {- return [- metrics.createTotalVisitors(),- metrics.createVisitors({- renderLabel: (_dashboardState) => 'Conversions',- width: 'w-28'- }),- metrics.createConversionRate(),- showRevenueMetrics && metrics.createTotalRevenue(),- showRevenueMetrics && metrics.createAverageRevenue()- ].filter((metric) => !!metric)- }-- if (- isRealTimeDashboard(dashboardState) &&- !hasConversionGoalFilter(dashboardState)- ) {- return [- metrics.createVisitors({- renderLabel: (_dashboardState) => 'Current visitors',- width: 'w-32'- })- ]- }-- return [- metrics.createVisitors({ renderLabel: (_dashboardState) => 'Visitors' }),- currentView === 'countries' && metrics.createPercentage()- ].filter((metric) => !!metric)- }-- const renderIcon = useCallback((listItem) => {- return (- <span className="mr-1">{listItem.country_flag || listItem.flag}</span>- )- }, [])-- return (- <Modal>- <BreakdownModal- reportInfo={reportInfo}- metrics={chooseMetrics()}- getFilterInfo={getFilterInfo}- renderIcon={renderIcon}- addSearchFilter={addSearchFilter}- />- </Modal>- )-}--export default LocationsModaldiff --git a/assets/js/dashboard/stats/pages/details.tsx b/assets/js/dashboard/stats/pages/details.tsxindex d68d562c09..0616043edf 100644--- a/assets/js/dashboard/stats/pages/details.tsx+++ b/assets/js/dashboard/stats/pages/details.tsx@@ -56,6 +56,7 @@ export function PagesDetails({dimensionLabel={reportConfig.dimensionLabel}dimensions={reportConfig.dimensions}metrics={metrics}+ alwaysOnFilters={reportConfig.alwaysOnFilters}defaultOrderBy={[['visitors', 'desc']]}DimensionElement={PagesDimensionElement}/>diff --git a/assets/js/dashboard/stats/pages/index.tsx b/assets/js/dashboard/stats/pages/index.tsxindex 04b78e6d5b..980a2f3949 100644--- a/assets/js/dashboard/stats/pages/index.tsx+++ b/assets/js/dashboard/stats/pages/index.tsx@@ -72,6 +72,7 @@ export default function Pages() {metrics={metrics}dimensions={reportConfig.dimensions}dimensionLabel={reportConfig.dimensionLabel}+ alwaysOnFilters={reportConfig.alwaysOnFilters}DimensionElement={PagesDimensionCell}onDataReady={setCurrentData}/>diff --git a/assets/js/dashboard/stats/reports/index-breakdown.tsx b/assets/js/dashboard/stats/reports/index-breakdown.tsxindex ffc2881ed6..0d5700becc 100644--- a/assets/js/dashboard/stats/reports/index-breakdown.tsx+++ b/assets/js/dashboard/stats/reports/index-breakdown.tsx@@ -18,7 +18,6 @@ import {formatDateRangeLabel,useBodyPortalRef,extractMetricValue,- getStatsQueryWithImplicitNotEmptyFilter,MetricValueWrapper,GetFilterInfo} from '../breakdowns'@@ -61,6 +60,7 @@ export function IndexBreakdown({dimensions,DimensionElement,dimensionLabel,+ alwaysOnFilters,onDataReady,metricColumnWidth = DEFAULT_METRIC_COLUMN_WIDTH}: IndexBreakdownProps) {@@ -79,6 +79,7 @@ export function IndexBreakdown({['visitors', 'desc'],...dimensions.map((dim): OrderByEntry => [dim, 'asc'])],+ alwaysOnFilters,pagination: { limit: MAX_ITEMS, offset: 0 }}}@@ -87,7 +88,7 @@ export function IndexBreakdown({const { apiState, isRealtimeSilentUpdate } = useQueryApi(site,statsReportQueryKey,- { enabled: visible, getStatsQuery: getStatsQueryWithImplicitNotEmptyFilter }+ { enabled: visible })useEffect(() => {@@ -234,10 +235,11 @@ export const DimensionCellWithBar = ({<DrilldownLinkonClick={onClick}filterInfo={getFilterInfo(filterDimension, row)}- extraClass="max-w-max w-full flex items-center md:overflow-hidden"+ className="max-w-max w-full flex items-center md:overflow-hidden"+ icon={icon}+ textClassName="w-full md:truncate">- {icon}- <span className="w-full md:truncate">{text}</span>+ {text}</DrilldownLink>{externalLink}</div>diff --git a/assets/js/dashboard/stats/reports/list-legacy.tsx b/assets/js/dashboard/stats/reports/list-legacy.tsxindex 43810bbdf4..3b913d84bc 100644--- a/assets/js/dashboard/stats/reports/list-legacy.tsx+++ b/assets/js/dashboard/stats/reports/list-legacy.tsx@@ -312,13 +312,11 @@ export default function ListReport<<DrilldownLinkfilterInfo={getFilterInfo(listItem)}onClick={onClick}- extraClass="max-w-max w-full flex items-center md:overflow-hidden"+ className="max-w-max w-full flex items-center md:overflow-hidden"+ icon={maybeRenderIconFor(listItem)}+ textClassName="w-full md:truncate">- {maybeRenderIconFor(listItem)}-- <span className="w-full md:truncate">- {trimURL(listItem.name, colMinWidth)}- </span>+ {trimURL(listItem.name, colMinWidth)}</DrilldownLink><ExternalLinkitem={listItem}diff --git a/assets/js/dashboard/stats/reports/reports-config.ts b/assets/js/dashboard/stats/reports/reports-config.tsindex e0d6433a11..3d37e6ad3b 100644--- a/assets/js/dashboard/stats/reports/reports-config.ts+++ b/assets/js/dashboard/stats/reports/reports-config.ts@@ -1,4 +1,4 @@-import { NonTimeDimension } from '../../stats-query'+import { ApiFilter, NonTimeDimension } from '../../stats-query'import { Metric } from '../metrics'export type MetricsByContext = {@@ -10,11 +10,12 @@ export type MetricsByContext = {}export type BreakdownReportConfig = {- dimensions: [NonTimeDimension] | [NonTimeDimension, NonTimeDimension]+ dimensions: [NonTimeDimension, ...NonTimeDimension[]]metricsByContext: MetricsByContextdetailsTitle: stringdetailsPath: stringdimensionLabel: string+ alwaysOnFilters?: ApiFilter[]}const COMMON_METRICS_BY_CONTEXT: MetricsByContext = {@@ -50,7 +51,10 @@ export enum BreakdownReportKey {'utmSources' = 'utmSources','utmCampaigns' = 'utmCampaigns','utmContents' = 'utmContents',- 'utmTerms' = 'utmTerms'+ 'utmTerms' = 'utmTerms',+ 'countries' = 'countries',+ 'regions' = 'regions',+ 'cities' = 'cities'}export const BREAKDOWN_REPORTS: Record<@@ -88,7 +92,8 @@ export const BREAKDOWN_REPORTS: Record<},detailsTitle: 'Entry pages',detailsPath: 'entry-pages',- dimensionLabel: 'Entry page'+ dimensionLabel: 'Entry page',+ alwaysOnFilters: [['is_not', 'visit:entry_page', ['']]]},[BreakdownReportKey.exitPages]: {dimensions: ['visit:exit_page'],@@ -98,7 +103,8 @@ export const BREAKDOWN_REPORTS: Record<},detailsTitle: 'Exit pages',detailsPath: 'exit-pages',- dimensionLabel: 'Exit page'+ dimensionLabel: 'Exit page',+ alwaysOnFilters: [['is_not', 'visit:exit_page', ['']]]},[BreakdownReportKey.browsers]: {dimensions: ['visit:browser'],@@ -161,34 +167,74 @@ export const BREAKDOWN_REPORTS: Record<metricsByContext: COMMON_METRICS_BY_CONTEXT,detailsTitle: 'UTM mediums',detailsPath: 'utm_mediums',- dimensionLabel: 'UTM medium'+ dimensionLabel: 'UTM medium',+ alwaysOnFilters: [['is_not', 'visit:utm_medium', ['']]]},[BreakdownReportKey.utmSources]: {dimensions: ['visit:utm_source'],metricsByContext: COMMON_METRICS_BY_CONTEXT,detailsTitle: 'UTM sources',detailsPath: 'utm_sources',- dimensionLabel: 'UTM source'+ dimensionLabel: 'UTM source',+ alwaysOnFilters: [['is_not', 'visit:utm_source', ['']]]},[BreakdownReportKey.utmCampaigns]: {dimensions: ['visit:utm_campaign'],metricsByContext: COMMON_METRICS_BY_CONTEXT,detailsTitle: 'UTM campaigns',detailsPath: 'utm_campaigns',- dimensionLabel: 'UTM campaign'+ dimensionLabel: 'UTM campaign',+ alwaysOnFilters: [['is_not', 'visit:utm_campaign', ['']]]},[BreakdownReportKey.utmContents]: {dimensions: ['visit:utm_content'],metricsByContext: COMMON_METRICS_BY_CONTEXT,detailsTitle: 'UTM contents',detailsPath: 'utm_contents',- dimensionLabel: 'UTM content'+ dimensionLabel: 'UTM content',+ alwaysOnFilters: [['is_not', 'visit:utm_content', ['']]]},[BreakdownReportKey.utmTerms]: {dimensions: ['visit:utm_term'],metricsByContext: COMMON_METRICS_BY_CONTEXT,detailsTitle: 'UTM terms',detailsPath: 'utm_terms',- dimensionLabel: 'UTM term'+ dimensionLabel: 'UTM term',+ alwaysOnFilters: [['is_not', 'visit:utm_term', ['']]]+ },+ [BreakdownReportKey.countries]: {+ dimensions: ['visit:country_name', 'visit:country'],+ metricsByContext: {+ ...COMMON_METRICS_BY_CONTEXT,+ defaultDetailedMetrics: ['visitors', 'percentage']+ },+ detailsTitle: 'Top countries',+ detailsPath: 'countries',+ dimensionLabel: 'Country',+ alwaysOnFilters: [['is_not', 'visit:country', ['\0\0', 'ZZ']]]+ },+ [BreakdownReportKey.regions]: {+ // the 3rd dimension "visit:country" is needed to render the country flag+ dimensions: ['visit:region_name', 'visit:region', 'visit:country'],+ metricsByContext: {+ ...COMMON_METRICS_BY_CONTEXT,+ defaultDetailedMetrics: ['visitors', 'percentage']+ },+ detailsTitle: 'Top regions',+ detailsPath: 'regions',+ dimensionLabel: 'Region',+ alwaysOnFilters: [['is_not', 'visit:region', ['']]]+ },+ [BreakdownReportKey.cities]: {+ // the 3rd dimension "visit:country" is needed to render the country flag+ dimensions: ['visit:city_name', 'visit:city', 'visit:country'],+ metricsByContext: {+ ...COMMON_METRICS_BY_CONTEXT,+ defaultDetailedMetrics: ['visitors', 'percentage']+ },+ detailsTitle: 'Top cities',+ detailsPath: 'cities',+ dimensionLabel: 'City',+ alwaysOnFilters: [['is_not', 'visit:city', [0]]]}}diff --git a/assets/js/dashboard/stats/sources/details.tsx b/assets/js/dashboard/stats/sources/details.tsxindex 7b1217e808..25447b485e 100644--- a/assets/js/dashboard/stats/sources/details.tsx+++ b/assets/js/dashboard/stats/sources/details.tsx@@ -69,6 +69,7 @@ export function SourcesDetails({ reportKey }: { reportKey: SourcesReportKey }) {dimensionLabel={reportConfig.dimensionLabel}dimensions={reportConfig.dimensions}metrics={metrics}+ alwaysOnFilters={reportConfig.alwaysOnFilters}defaultOrderBy={[['visitors', 'desc']]}DimensionElement={DimensionElement}/>diff --git a/assets/js/dashboard/stats/sources/index.tsx b/assets/js/dashboard/stats/sources/index.tsxindex 5f08011001..b50c34baf3 100644--- a/assets/js/dashboard/stats/sources/index.tsx+++ b/assets/js/dashboard/stats/sources/index.tsx@@ -219,6 +219,7 @@ export default function Sources() {metrics={metrics}dimensions={reportConfig.dimensions}dimensionLabel={reportConfig.dimensionLabel}+ alwaysOnFilters={reportConfig.alwaysOnFilters}DimensionElement={DimensionElement}onDataReady={setCurrentQueryApiData}/>diff --git a/e2e/tests/dashboard/breakdowns.spec.ts b/e2e/tests/dashboard/breakdowns.spec.tsindex cf13664d60..491fb28b6b 100644--- a/e2e/tests/dashboard/breakdowns.spec.ts+++ b/e2e/tests/dashboard/breakdowns.spec.ts@@ -925,6 +925,10 @@ test('locations breakdown', async ({ page, request }) => {country_code: 'PL',subdivision1_code: 'PL-14',city_geoname_id: 756_135+ },+ {+ name: 'pageview',+ country_code: ''}]})@@ -968,6 +972,14 @@ test('locations breakdown', async ({ page, request }) => {await expectMetricValues(modal(page), 'Estonia', ['2'])+ await expect(searchInput(modal(page))).toBeVisible()++ await searchInput(modal(page)).fill('Esto')+ await expectRows(modal(page), [/Estonia/])++ await searchInput(modal(page)).fill('')+ await expectRows(modal(page), [/Estonia/, /Poland/])+await closeModalButton(page).click()})@@ -990,7 +1002,7 @@ test('locations breakdown', async ({ page, request }) => {await expectHeaders(report, ['Region', 'Visitors'])- await expectRows(report, [/Harjumaa/, /Tartumaa/, /Mazovia/])+ await expectRows(report, [/Harjumaa/, /Mazovia/, /Tartumaa/])await expectMetricValues(report, 'Harjumaa', ['1', '33.3%'])await expectMetricValues(report, 'Tartumaa', ['1', '33.3%'])@@ -1006,10 +1018,18 @@ test('locations breakdown', async ({ page, request }) => {await expectHeaders(modal(page), ['Region', /Visitors/])- await expectRows(modal(page), [/Harjumaa/, /Tartumaa/, /Mazovia/])+ await expectRows(modal(page), [/Harjumaa/, /Mazovia/, /Tartumaa/])await expectMetricValues(modal(page), 'Harjumaa', ['1'])+ await expect(searchInput(modal(page))).toBeVisible()++ await searchInput(modal(page)).fill('Harju')+ await expectRows(modal(page), [/Harjumaa/])++ await searchInput(modal(page)).fill('')+ await expectRows(modal(page), [/Harjumaa/, /Mazovia/, /Tartumaa/])+await closeModalButton(page).click()})@@ -1032,7 +1052,7 @@ test('locations breakdown', async ({ page, request }) => {await expectHeaders(report, ['City', 'Visitors'])- await expectRows(report, [/Tartu/, /Tallinn/, /Warsaw/])+ await expectRows(report, [/Tallinn/, /Tartu/, /Warsaw/])await expectMetricValues(report, 'Tartu', ['1', '33.3%'])await expectMetricValues(report, 'Tallinn', ['1', '33.3%'])@@ -1048,10 +1068,205 @@ test('locations breakdown', async ({ page, request }) => {await expectHeaders(modal(page), ['City', /Visitors/])- await expectRows(modal(page), [/Tartu/, /Tallinn/, /Warsaw/])+ await expectRows(modal(page), [/Tallinn/, /Tartu/, /Warsaw/])await expectMetricValues(modal(page), 'Tartu', ['1'])+ await expect(searchInput(modal(page))).toBeVisible()++ await searchInput(modal(page)).fill('Tallinn')+ await expectRows(modal(page), [/Tallinn/])++ await searchInput(modal(page)).fill('')+ await expectRows(modal(page), [/Tallinn/, /Tartu/, /Warsaw/])++ await closeModalButton(page).click()+ })+})++test('locations breakdown with a revenue goal filter applied', async ({+ page,+ request+}) => {+ const { domain } = await setupSite({ page, request })++ await populateStats({+ request,+ domain,+ events: [+ {+ user_id: 1,+ name: 'pageview',+ country_code: 'A1'+ },+ {+ user_id: 2,+ name: 'pageview',+ country_code: 'A1'+ },+ {+ user_id: 2,+ name: 'purchase',+ revenue_reporting_amount: '23',+ revenue_reporting_currency: 'EUR',+ country_code: 'A1'+ },+ {+ user_id: 3,+ name: 'pageview',+ country_code: 'PL',+ subdivision1_code: 'PL-14',+ city_geoname_id: 756_135+ },+ {+ user_id: 4,+ name: 'pageview',+ country_code: 'EE',+ subdivision1_code: 'EE-37',+ city_geoname_id: 588_409+ },+ {+ user_id: 4,+ name: 'purchase',+ revenue_reporting_amount: '12345.67',+ revenue_reporting_currency: 'EUR',+ country_code: 'EE',+ subdivision1_code: 'EE-37',+ city_geoname_id: 588_409+ }+ ]+ })++ await addCustomGoal({ page, domain, name: 'purchase', currency: 'EUR' })++ await page.goto('/' + domain + '?f=is,goal,purchase', {+ waitUntil: 'commit'+ })++ const report = page.getByTestId('report-locations')++ await test.step('countries report shows conversions for revenue goal', async () => {+ await tabButton(report, 'Countries').click()++ await expectHeaders(report, ['Country', 'Conversions', 'CR'])++ await expectRows(report, [/Anonymous VPN Service/, /Estonia/])++ await expectMetricValues(report, 'Anonymous VPN Service', ['1', '50%'])+ await expectMetricValues(report, 'Estonia', ['1', '100%'])+ })++ await test.step('countries details modal includes revenue columns', async () => {+ await detailsLink(report).click()++ await expect(+ modal(page).getByRole('heading', { name: 'Top countries' })+ ).toBeVisible()++ await expectHeaders(modal(page), [+ 'Country',+ /Total visitors/,+ /Conversions/,+ /CR/,+ /Revenue/,+ /Average/+ ])++ await expectRows(modal(page), [/Anonymous VPN Service/, /Estonia/])++ await expectMetricValues(modal(page), 'Anonymous VPN Service', [+ '2',+ '1',+ '50%',+ 'โฌ23.0',+ 'โฌ23.0'+ ])+ await expectMetricValues(modal(page), 'Estonia', [+ '1',+ '1',+ '100%',+ 'โฌ12.3K',+ 'โฌ12.3K'+ ])++ await closeModalButton(page).click()+ })++ await test.step('regions report shows conversions for revenue goal', async () => {+ await tabButton(report, 'Regions').click()++ await expectHeaders(report, ['Region', 'Conversions', 'CR'])++ await expectRows(report, [/Harjumaa/])++ await expectMetricValues(report, 'Harjumaa', ['1', '100%'])+ })++ await test.step('regions details modal includes revenue columns', async () => {+ await detailsLink(report).click()++ await expect(+ modal(page).getByRole('heading', { name: 'Top regions' })+ ).toBeVisible()++ await expectHeaders(modal(page), [+ 'Region',+ /Total visitors/,+ /Conversions/,+ /CR/,+ /Revenue/,+ /Average/+ ])++ await expectRows(modal(page), [/Harjumaa/])++ await expectMetricValues(modal(page), 'Harjumaa', [+ '1',+ '1',+ '100%',+ 'โฌ12.3K',+ 'โฌ12.3K'+ ])++ await closeModalButton(page).click()+ })++ await test.step('cities report shows conversions for revenue goal', async () => {+ await tabButton(report, 'Cities').click()++ await expectHeaders(report, ['City', 'Conversions', 'CR'])++ await expectRows(report, [/Tallinn/])++ await expectMetricValues(report, 'Tallinn', ['1', '100%'])+ })++ await test.step('cities details modal includes revenue columns', async () => {+ await detailsLink(report).click()++ await expect(+ modal(page).getByRole('heading', { name: 'Top cities' })+ ).toBeVisible()++ await expectHeaders(modal(page), [+ 'City',+ /Total visitors/,+ /Conversions/,+ /CR/,+ /Revenue/,+ /Average/+ ])++ await expectRows(modal(page), [/Tallinn/])++ await expectMetricValues(modal(page), 'Tallinn', [+ '1',+ '1',+ '100%',+ 'โฌ12.3K',+ 'โฌ12.3K'+ ])+await closeModalButton(page).click()})})diff --git a/lib/mix/tasks/generate_countries_meta.ex b/lib/mix/tasks/generate_countries_meta.exnew file mode 100644index 0000000000..0805b9c01a--- /dev/null+++ b/lib/mix/tasks/generate_countries_meta.ex@@ -0,0 +1,41 @@+defmodule Mix.Tasks.GenerateCountriesMeta do+ @moduledoc """+ Regenerates `countries_meta.json`, an `alpha_2 -> [alpha_3, flag]` dictionary.+ The dashboard uses it for two things.+ First, to render country flags the same way as the BE does.+ Secondly, to map visitors by country to the country shapes in the world map. This is needed+ because country shapes are identified in the geography dataset only with their alpha3 code.++ The source of truth is `Location.Country.all/0` from the `:location`+ dependency. We materialize it to a checked-in JSON file in `assets/` folder.++ The checked-in file is protected from drifting off from the dependency by a CI job.++ Run `mix generate_countries_meta` locally whenever the `:location` dependency is bumped,+ or any time you want to refresh the committed file.+ """++ use Mix.Task++ @output_path "assets/data/countries_meta.json"++ @impl Mix.Task+ def run(_args) do+ Application.ensure_all_started(:jason)+ Location.Country.load()++ json =+ Location.Country.all()+ |> Map.new(fn %Location.Country{+ alpha_2: code,+ alpha_3: alpha_3,+ flag: flag+ } ->+ {code, [alpha_3, flag]}+ end)+ |> Jason.encode!(pretty: true)++ File.write!(@output_path, json)+ Mix.shell().info("Wrote #{byte_size(json)} bytes to #{@output_path}")+ end+enddiff --git a/lib/plausible/stats/imported/sql/expression.ex b/lib/plausible/stats/imported/sql/expression.exindex a69825fe87..f96cdbbb83 100644--- a/lib/plausible/stats/imported/sql/expression.ex+++ b/lib/plausible/stats/imported/sql/expression.ex@@ -276,6 +276,20 @@ defmodule Plausible.Stats.Imported.SQL.Expression do})end+ # Rows imported from Plausible store `imported_locations.region` as ISO 3166-2 code.+ # Rows imported from GA4 have `imported_locations.region` set to region name+ # (e.g. "California").+ #+ # imported_locations.region_name is an alias column that looks up the name by the ISO code.+ # Lookup by values imported from GA4 (e.g. "California"), will yield an empty string.+ #+ # This function ensures that in those scenarios, the region name is set to the region code.+ defp select_group_fields(q, "visit:region_name", key, _query) do+ select_merge_as(q, [i], %{+ key => fragment("if(empty(?), ?, ?)", i.region_name, i.region, i.region_name)+ })+ end+defp select_group_fields(q, dimension, key, _query) doselect_merge_as(q, [i], %{key => field(i, ^dim(dimension))})end@@ -298,7 +312,7 @@ defmodule Plausible.Stats.Imported.SQL.Expression dodefp filter_group_values(q, "visit:city"), do: where(q, [i], i.city != 0 and not is_nil(i.city))defp filter_group_values(q, "visit:country_name"), do: where(q, [i], i.country_name != "ZZ")- defp filter_group_values(q, "visit:region_name"), do: where(q, [i], i.region_name != "")+ defp filter_group_values(q, "visit:region_name"), do: where(q, [i], i.region != "")defp filter_group_values(q, "visit:city_name"), do: where(q, [i], i.city_name != "")defp filter_group_values(q, _dimension), do: qdiff --git a/test/plausible_web/controllers/api/external_stats_controller/query_imported_test.exs b/test/plausible_web/controllers/api/external_stats_controller/query_imported_test.exsindex d3317f8740..9ed544765c 100644--- a/test/plausible_web/controllers/api/external_stats_controller/query_imported_test.exs+++ b/test/plausible_web/controllers/api/external_stats_controller/query_imported_test.exs@@ -1152,6 +1152,58 @@ defmodule PlausibleWeb.Api.ExternalStatsController.QueryImportedTest doendend+ test "imported non-empty region IDs that don't have a corresponding name in our locations dictionary have region_name set to the ID itself, empty region IDs are excluded",+ %{conn: conn, site: site} do+ site_import = insert(:site_import, site: site)++ populate_stats(site, site_import.id, [+ # GA4 import: `region` is the name of the `region`+ build(:imported_locations, country: "US", region: "California", visitors: 10),+ # Plausible import: `region` is the region ID+ build(:imported_locations, country: "EE", region: "EE-37", visitors: 5),+ # Plausible import: `region` is the region ID, but the ID is stale+ build(:imported_locations, country: "NO", region: "NO-99", visitors: 50),+ # Plausible / GA4 import when the region is unknown+ build(:imported_locations, country: "US", region: "", visitors: 99)+ ])++ for {dimensions, expected_dimension_values} <- [+ {["visit:region_name", "visit:region"],+ [+ NO: ["NO-99", "NO-99"],+ US: ["California", "California"],+ EE: ["Harjumaa", "EE-37"]+ ]},+ {["visit:region"],+ [+ NO: ["NO-99"],+ US: ["California"],+ EE: ["EE-37"]+ ]},+ {["visit:region_name"],+ [+ NO: ["NO-99"],+ US: ["California"],+ EE: ["Harjumaa"]+ ]}+ ] do+ conn =+ post(conn, "/api/v2/query", %{+ "site_id" => site.domain,+ "metrics" => ["visitors"],+ "date_range" => "all",+ "dimensions" => dimensions,+ "include" => %{"imports" => true}+ })++ assert json_response(conn, 200)["results"] == [+ %{"dimensions" => expected_dimension_values[:NO], "metrics" => [50]},+ %{"dimensions" => expected_dimension_values[:US], "metrics" => [10]},+ %{"dimensions" => expected_dimension_values[:EE], "metrics" => [5]}+ ]+ end+ end+test "imported country and city names", %{site: site,conn: conn