Skip to content

Commit

Permalink
add dropdown logic for revenue report, defaults to USD for unknown cu…
Browse files Browse the repository at this point in the history
…rrency code
  • Loading branch information
franciscao633 committed Sep 27, 2024
1 parent 214396f commit be50e8a
Show file tree
Hide file tree
Showing 8 changed files with 155 additions and 12 deletions.
4 changes: 2 additions & 2 deletions src/app/(main)/console/TestConsole.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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)),
Expand Down
4 changes: 3 additions & 1 deletion src/app/(main)/reports/revenue/RevenueParameters.tsx
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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();
Expand All @@ -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>
Expand Down
6 changes: 6 additions & 0 deletions src/app/(main)/reports/revenue/RevenueView.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,9 @@
gap: 20px;
margin-bottom: 40px;
}

.row {
display: flex;
align-items: center;
gap: 10px;
}
20 changes: 17 additions & 3 deletions src/app/(main)/reports/revenue/RevenueView.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
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';
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';
Expand All @@ -21,13 +23,24 @@ 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,
parameters: { dateRange, currency },
} = 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 [];

Expand Down Expand Up @@ -119,14 +132,15 @@ export function RevenueView({ isLoading }: RevenueViewProps) {
isLoading={isLoading}
/>
{data && (
<GridRow columns="one-two">
<GridRow columns="two">
<ListTable
metric={formatMessage(labels.country)}
data={data?.country.map(({ name, value }) => ({
x: name,
y: value,
z: (value / data?.total.sum) * 100,
}))}
renderLabel={renderCountryName}
/>
<PieChart type="doughnut" data={countryData} />
</GridRow>
Expand Down
18 changes: 18 additions & 0 deletions src/components/hooks/queries/useRevenueValues.ts
Original file line number Diff line number Diff line change
@@ -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;
20 changes: 16 additions & 4 deletions src/lib/format.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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') {
Expand Down
20 changes: 18 additions & 2 deletions src/pages/api/reports/revenue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
}

Expand All @@ -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,
Expand Down
75 changes: 75 additions & 0 deletions src/queries/analytics/reports/getRevenueValues.ts
Original file line number Diff line number Diff line change
@@ -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,
},
);
}

0 comments on commit be50e8a

Please sign in to comment.