diff --git a/src/app/(main)/console/TestConsole.tsx b/src/app/(main)/console/TestConsole.tsx index 8e7169d4..d33f95e9 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.tsx index 253f3adf..f231ce06 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() { - + item.currency)}> {item => {item}} diff --git a/src/app/(main)/reports/revenue/RevenueView.module.css b/src/app/(main)/reports/revenue/RevenueView.module.css index d9b10548..9b35260e 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.tsx index fa62778e..89247b6a 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 }) => ( + + + {countryNames[code]} + + ), + [countryNames, locale], + ); + const chartData = useMemo(() => { if (!data) return []; @@ -119,7 +132,7 @@ export function RevenueView({ isLoading }: RevenueViewProps) { isLoading={isLoading} /> {data && ( - + ({ @@ -127,6 +140,7 @@ export function RevenueView({ isLoading }: RevenueViewProps) { y: value, z: (value / data?.total.sum) * 100, }))} + renderLabel={renderCountryName} /> diff --git a/src/components/hooks/queries/useRevenueValues.ts b/src/components/hooks/queries/useRevenueValues.ts new file mode 100644 index 00000000..cb7bd283 --- /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.ts index ba3243f7..71e4916d 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.ts index 39014d25..d23ce55a 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.ts new file mode 100644 index 00000000..e20672b4 --- /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, + }, + ); +}