Umami is a privacy-first web and product analytics platform. Traffic, campaigns, behavior, conversions, and revenue in one place. No cookies, no surveillance, self-hosted or in the cloud.
TypeScript analyticsaudience-segmentationchartscohort-analysisgoogle-analyticsproduct-analyticsstatisticsuser-journeyweb-analytics
add dropdown logic for revenue report, defaults to USD for unknown currency code
Francis Caobe50e8a57541
diff --git a/src/app/(main)/console/TestConsole.tsx b/src/app/(main)/console/TestConsole.tsxindex 8e7169d4a..d33f95e9d 100644--- a/src/app/(main)/console/TestConsole.tsx+++ b/src/app/(main)/console/TestConsole.tsx@@ -56,11 +56,11 @@ export function TestConsole({ websiteId }: { websiteId: string }) {}));window['umami'].track('checkout-cart', {revenue: parseFloat((Math.random() * 100000).toFixed(2)),- currency: 'USD',+ currency: 'SHIBA',});window['umami'].track('affiliate-link', {revenue: parseFloat((Math.random() * 100000).toFixed(2)),- currency: 'USD',+ currency: 'ETH',});window['umami'].track('promotion-link', {revenue: parseFloat((Math.random() * 100000).toFixed(2)),diff --git a/src/app/(main)/reports/revenue/RevenueParameters.tsx b/src/app/(main)/reports/revenue/RevenueParameters.tsxindex 253f3adf8..f231ce06e 100644--- a/src/app/(main)/reports/revenue/RevenueParameters.tsx+++ b/src/app/(main)/reports/revenue/RevenueParameters.tsx@@ -1,4 +1,5 @@import { useMessages } from 'components/hooks';+import useRevenueValues from 'components/hooks/queries/useRevenueValues';import { useContext } from 'react';import { Dropdown, Form, FormButtons, FormInput, FormRow, Item, SubmitButton } from 'react-basics';import BaseParameters from '../[reportId]/BaseParameters';@@ -10,6 +11,7 @@ export function RevenueParameters() {const { id, parameters } = report || {};const { websiteId, dateRange } = parameters || {};const queryEnabled = websiteId && dateRange;+ const { data: values = [] } = useRevenueValues(websiteId, dateRange.startDate, dateRange.endDate);const handleSubmit = (data: any, e: any) => {e.stopPropagation();@@ -23,7 +25,7 @@ export function RevenueParameters() {<BaseParameters showDateSelect={true} allowWebsiteSelect={!id} /><FormRow label={formatMessage(labels.currency)}><FormInput name="currency" rules={{ required: formatMessage(labels.required) }}>- <Dropdown items={['USD', 'EUR', 'MXN']}>+ <Dropdown items={values.map(item => item.currency)}>{item => <Item key={item}>{item}</Item>}</Dropdown></FormInput>diff --git a/src/app/(main)/reports/revenue/RevenueView.module.css b/src/app/(main)/reports/revenue/RevenueView.module.cssindex d9b10548f..9b35260e2 100644--- a/src/app/(main)/reports/revenue/RevenueView.module.css+++ b/src/app/(main)/reports/revenue/RevenueView.module.css@@ -3,3 +3,9 @@gap: 20px;margin-bottom: 40px;}++.row {+ display: flex;+ align-items: center;+ gap: 10px;+}diff --git a/src/app/(main)/reports/revenue/RevenueView.tsx b/src/app/(main)/reports/revenue/RevenueView.tsxindex fa62778e4..89247b6a8 100644--- a/src/app/(main)/reports/revenue/RevenueView.tsx+++ b/src/app/(main)/reports/revenue/RevenueView.tsx@@ -1,7 +1,9 @@+import classNames from 'classnames';import { colord } from 'colord';import BarChart from 'components/charts/BarChart';import PieChart from 'components/charts/PieChart';-import { useLocale, useMessages } from 'components/hooks';+import TypeIcon from 'components/common/TypeIcon';+import { useCountryNames, useLocale, useMessages } from 'components/hooks';import { GridRow } from 'components/layout/Grid';import ListTable from 'components/metrics/ListTable';import MetricCard from 'components/metrics/MetricCard';@@ -9,7 +11,7 @@ import MetricsBar from 'components/metrics/MetricsBar';import { renderDateLabels } from 'lib/charts';import { CHART_COLORS } from 'lib/constants';import { formatLongCurrency, formatLongNumber } from 'lib/format';-import { useContext, useMemo } from 'react';+import { useCallback, useContext, useMemo } from 'react';import { ReportContext } from '../[reportId]/Report';import RevenueTable from './RevenueTable';import styles from './RevenueView.module.css';@@ -21,6 +23,7 @@ export interface RevenueViewProps {export function RevenueView({ isLoading }: RevenueViewProps) {const { formatMessage, labels } = useMessages();const { locale } = useLocale();+ const { countryNames } = useCountryNames(locale);const { report } = useContext(ReportContext);const {data,@@ -28,6 +31,16 @@ export function RevenueView({ isLoading }: RevenueViewProps) {} = report || {};const showTable = data?.table.length > 1;+ const renderCountryName = useCallback(+ ({ x: code }) => (+ <span className={classNames(locale, styles.row)}>+ <TypeIcon type="country" value={code?.toLowerCase()} />+ {countryNames[code]}+ </span>+ ),+ [countryNames, locale],+ );+const chartData = useMemo(() => {if (!data) return [];@@ -119,7 +132,7 @@ export function RevenueView({ isLoading }: RevenueViewProps) {isLoading={isLoading}/>{data && (- <GridRow columns="one-two">+ <GridRow columns="two"><ListTablemetric={formatMessage(labels.country)}data={data?.country.map(({ name, value }) => ({@@ -127,6 +140,7 @@ export function RevenueView({ isLoading }: RevenueViewProps) {y: value,z: (value / data?.total.sum) * 100,}))}+ renderLabel={renderCountryName}/><PieChart type="doughnut" data={countryData} /></GridRow>diff --git a/src/components/hooks/queries/useRevenueValues.ts b/src/components/hooks/queries/useRevenueValues.tsnew file mode 100644index 000000000..cb7bd2830--- /dev/null+++ b/src/components/hooks/queries/useRevenueValues.ts@@ -0,0 +1,18 @@+import { useApi } from './useApi';++export function useRevenueValues(websiteId: string, startDate: Date, endDate: Date) {+ const { get, useQuery } = useApi();++ return useQuery({+ queryKey: ['revenue:values', { websiteId, startDate, endDate }],+ queryFn: () =>+ get(`/reports/revenue`, {+ websiteId,+ startDate,+ endDate,+ }),+ enabled: !!(websiteId && startDate && endDate),+ });+}++export default useRevenueValues;diff --git a/src/lib/format.ts b/src/lib/format.tsindex ba3243f77..71e4916d1 100644--- a/src/lib/format.ts+++ b/src/lib/format.ts@@ -83,10 +83,22 @@ export function stringToColor(str: string) {}export function formatCurrency(value: number, currency: string, locale = 'en-US') {- return new Intl.NumberFormat(locale, {- style: 'currency',- currency: currency,- }).format(value);+ let formattedValue;++ try {+ formattedValue = new Intl.NumberFormat(locale, {+ style: 'currency',+ currency: currency,+ });+ } catch (error) {+ // Fallback to default currency format if an error occurs+ formattedValue = new Intl.NumberFormat(locale, {+ style: 'currency',+ currency: 'USD',+ });+ }++ return formattedValue.format(value);}export function formatLongCurrency(value: number, currency: string, locale = 'en-US') {diff --git a/src/pages/api/reports/revenue.ts b/src/pages/api/reports/revenue.tsindex 39014d25f..d23ce55ae 100644--- a/src/pages/api/reports/revenue.ts+++ b/src/pages/api/reports/revenue.ts@@ -5,12 +5,13 @@ import { TimezoneTest, UnitTypeTest } from 'lib/yup';import { NextApiResponse } from 'next';import { methodNotAllowed, ok, unauthorized } from 'next-basics';import { getRevenue } from 'queries/analytics/reports/getRevenue';+import { getRevenueValues } from 'queries/analytics/reports/getRevenueValues';import * as yup from 'yup';export interface RevenueRequestBody {websiteId: string;- currency: string;- timezone: string;+ currency?: string;+ timezone?: string;dateRange: { startDate: string; endDate: string; unit?: string };}@@ -37,6 +38,21 @@ export default async (await useAuth(req, res);await useValidate(schema, req, res);+ if (req.method === 'GET') {+ const { websiteId, startDate, endDate } = req.query;++ if (!(await canViewWebsite(req.auth, websiteId))) {+ return unauthorized(res);+ }++ const data = await getRevenueValues(websiteId, {+ startDate: new Date(startDate),+ endDate: new Date(endDate),+ });++ return ok(res, data);+ }+if (req.method === 'POST') {const {websiteId,diff --git a/src/queries/analytics/reports/getRevenueValues.ts b/src/queries/analytics/reports/getRevenueValues.tsnew file mode 100644index 000000000..e20672b4f--- /dev/null+++ b/src/queries/analytics/reports/getRevenueValues.ts@@ -0,0 +1,75 @@+import prisma from 'lib/prisma';+import clickhouse from 'lib/clickhouse';+import { runQuery, CLICKHOUSE, PRISMA, getDatabaseType, POSTGRESQL } from 'lib/db';++export async function getRevenueValues(+ ...args: [+ websiteId: string,+ criteria: {+ startDate: Date;+ endDate: Date;+ },+ ]+) {+ return runQuery({+ [PRISMA]: () => relationalQuery(...args),+ [CLICKHOUSE]: () => clickhouseQuery(...args),+ });+}++async function relationalQuery(+ websiteId: string,+ criteria: {+ startDate: Date;+ endDate: Date;+ },+) {+ const { rawQuery } = prisma;+ const { startDate, endDate } = criteria;++ const db = getDatabaseType();+ const like = db === POSTGRESQL ? 'ilike' : 'like';++ return rawQuery(+ `+ select distinct string_value as currency+ from event_data+ where website_id = {websiteId:UUID}+ and created_at between {startDate:DateTime64} and {endDate:DateTime64}+ and data_key ${like} '%currency%'+ order by currency+ `,+ {+ websiteId,+ startDate,+ endDate,+ },+ );+}++async function clickhouseQuery(+ websiteId: string,+ criteria: {+ startDate: Date;+ endDate: Date;+ },+) {+ const { rawQuery } = clickhouse;+ const { startDate, endDate } = criteria;++ return rawQuery(+ `+ select distinct string_value as currency+ from event_data+ where website_id = {websiteId:UUID}+ and created_at between {startDate:DateTime64} and {endDate:DateTime64}+ and positionCaseInsensitive(data_key, 'currency') > 0+ order by currency+ `,+ {+ websiteId,+ startDate,+ endDate,+ },+ );+}