feature(dashboard,api): add timezone support

* feat(dashboard): add support for today, yesterday etc (timezones)

* fix(db): escape js dates

* fix(dashboard): ensure we support default timezone

* final fixes

* remove complete series and add sql with fill instead
This commit is contained in:
Carl-Gerhard Lindesvärd
2025-05-23 11:26:44 +02:00
committed by GitHub
parent 46bfeee131
commit 680727355b
48 changed files with 1817 additions and 758 deletions

View File

@@ -34,10 +34,7 @@ export function SignInEmailForm() {
};
return (
<form
onSubmit={form.handleSubmit(onSubmit, (err) => console.log(err))}
className="col gap-6"
>
<form onSubmit={form.handleSubmit(onSubmit)} className="col gap-6">
<h3 className="text-2xl font-medium text-left">Sign in with email</h3>
<InputWithLabel
{...form.register('email')}

View File

@@ -7,7 +7,6 @@ import type {
IChartType,
IInterval,
} from '@openpanel/validation';
import { endOfDay, startOfDay } from 'date-fns';
import { SaveIcon } from 'lucide-react';
import { useState } from 'react';
import { ReportChart } from '../report-chart';
@@ -50,10 +49,8 @@ export function ChatReport({
className="min-w-0"
onChange={setRange}
value={report.range}
onStartDateChange={(date) =>
setStartDate(startOfDay(date).toISOString())
}
onEndDateChange={(date) => setEndDate(endOfDay(date).toISOString())}
onStartDateChange={setStartDate}
onEndDateChange={setEndDate}
endDate={report.endDate}
startDate={report.startDate}
/>

View File

@@ -173,7 +173,9 @@ export function OverviewMetricCardNumber({
<div className={cn('flex min-w-0 flex-col gap-2', className)}>
<div className="flex items-center justify-between gap-2">
<div className="flex min-w-0 items-center gap-2 text-left">
<span className="truncate text-muted-foreground">{label}</span>
<span className="truncate text-sm font-medium text-muted-foreground">
{label}
</span>
</div>
</div>
{isLoading ? (

View File

@@ -4,15 +4,19 @@ import { useOverviewOptions } from '@/components/overview/useOverviewOptions';
import { useEventQueryFilters } from '@/hooks/useEventQueryFilters';
import { cn } from '@/utils/cn';
import { useDashedStroke } from '@/hooks/use-dashed-stroke';
import { useFormatDateInterval } from '@/hooks/useFormatDateInterval';
import { useNumber } from '@/hooks/useNumerFormatter';
import { type RouterOutputs, api } from '@/trpc/client';
import { getChartColor } from '@/utils/theme';
import { getPreviousMetric } from '@openpanel/common';
import type { IInterval } from '@openpanel/validation';
import { isSameDay, isSameHour, isSameMonth, isSameWeek } from 'date-fns';
import { last } from 'ramda';
import React from 'react';
import {
CartesianGrid,
Customized,
Line,
LineChart,
ResponsiveContainer,
@@ -93,6 +97,44 @@ export default function OverviewMetrics({ projectId }: OverviewMetricsProps) {
const xAxisProps = useXAxisProps({ interval });
const yAxisProps = useYAxisProps();
let dotIndex = undefined;
if (range === 'today') {
// Find closest index based on times
dotIndex = data.findIndex((item) => {
return isSameHour(item.date, new Date());
});
}
const { calcStrokeDasharray, handleAnimationEnd, getStrokeDasharray } =
useDashedStroke({
dotIndex,
});
const lastSerieDataItem = last(data)?.date || new Date();
const useDashedLastLine = (() => {
if (range === 'today') {
return true;
}
if (interval === 'hour') {
return isSameHour(lastSerieDataItem, new Date());
}
if (interval === 'day') {
return isSameDay(lastSerieDataItem, new Date());
}
if (interval === 'month') {
return isSameMonth(lastSerieDataItem, new Date());
}
if (interval === 'week') {
return isSameWeek(lastSerieDataItem, new Date());
}
return false;
})();
return (
<>
<div className="relative -top-0.5 col-span-6 -m-4 mb-0 mt-0 md:m-0">
@@ -127,7 +169,7 @@ export default function OverviewMetrics({ projectId }: OverviewMetricsProps) {
</div>
<div className="card p-4">
<div className="text-center text-muted-foreground mb-2">
<div className="text-center mb-3 -mt-1 text-sm font-medium text-muted-foreground">
{activeMetric.title}
</div>
<div className="w-full h-[150px]">
@@ -135,6 +177,13 @@ export default function OverviewMetrics({ projectId }: OverviewMetricsProps) {
<TooltipProvider metric={activeMetric} interval={interval}>
<ResponsiveContainer width="100%" height="100%">
<LineChart data={data}>
<Customized component={calcStrokeDasharray} />
<Line
dataKey="calcStrokeDasharray"
legendType="none"
animationDuration={0}
onAnimationEnd={handleAnimationEnd}
/>
<Tooltip />
<YAxis
{...yAxisProps}
@@ -184,6 +233,11 @@ export default function OverviewMetrics({ projectId }: OverviewMetricsProps) {
dataKey={activeMetric.key}
stroke={getChartColor(0)}
strokeWidth={2}
strokeDasharray={
useDashedLastLine
? getStrokeDasharray(activeMetric.key)
: undefined
}
isAnimationActive={false}
dot={
data.length > 90

View File

@@ -2,7 +2,6 @@
import { useOverviewOptions } from '@/components/overview/useOverviewOptions';
import { TimeWindowPicker } from '@/components/time-window-picker';
import { endOfDay, formatISO, startOfDay } from 'date-fns';
export function OverviewRange() {
const { range, setRange, setStartDate, setEndDate, endDate, startDate } =
@@ -12,14 +11,8 @@ export function OverviewRange() {
<TimeWindowPicker
onChange={setRange}
value={range}
onStartDateChange={(date) => {
const d = formatISO(startOfDay(new Date(date)));
setStartDate(d);
}}
onEndDateChange={(date) => {
const d = formatISO(endOfDay(new Date(date)));
setEndDate(d);
}}
onStartDateChange={setStartDate}
onEndDateChange={setEndDate}
endDate={endDate}
startDate={startDate}
/>

View File

@@ -6,13 +6,20 @@ import { api } from '@/trpc/client';
import type { IChartData } from '@/trpc/client';
import { cn } from '@/utils/cn';
import { getChartColor } from '@/utils/theme';
import { isSameDay, isSameHour, isSameMonth } from 'date-fns';
import {
isFuture,
isSameDay,
isSameHour,
isSameMonth,
isSameWeek,
} from 'date-fns';
import { last } from 'ramda';
import React, { useCallback } from 'react';
import React, { useCallback, useState } from 'react';
import {
Area,
CartesianGrid,
ComposedChart,
Customized,
Legend,
Line,
ReferenceLine,
@@ -22,6 +29,7 @@ import {
YAxis,
} from 'recharts';
import { useDashedStroke, useStrokeDasharray } from '@/hooks/use-dashed-stroke';
import { useXAxisProps, useYAxisProps } from '../common/axis';
import { SolidToDashedGradient } from '../common/linear-gradient';
import { ReportChartTooltip } from '../common/report-chart-tooltip';
@@ -63,15 +71,20 @@ export function Chart({ data }: Props) {
const { series, setVisibleSeries } = useVisibleSeries(data);
const rechartData = useRechartDataModel(series);
// great care should be taken when computing lastIntervalPercent
// the expression below works for data.length - 1 equal intervals
// but if there are numeric x values in a "linear" axis, the formula
// should be updated to use those values
const lastIntervalPercent =
((rechartData.length - 2) * 100) / (rechartData.length - 1);
let dotIndex = undefined;
if (range === 'today') {
// Find closest index based on times
dotIndex = rechartData.findIndex((item) => {
return isSameHour(item.date, new Date());
});
}
const lastSerieDataItem = last(series[0]?.data || [])?.date || new Date();
const useDashedLastLine = (() => {
if (range === 'today') {
return true;
}
if (interval === 'hour') {
return isSameHour(lastSerieDataItem, new Date());
}
@@ -84,9 +97,18 @@ export function Chart({ data }: Props) {
return isSameMonth(lastSerieDataItem, new Date());
}
if (interval === 'week') {
return isSameWeek(lastSerieDataItem, new Date());
}
return false;
})();
const { getStrokeDasharray, calcStrokeDasharray, handleAnimationEnd } =
useDashedStroke({
dotIndex,
});
const CustomLegend = useCallback(() => {
return (
<div className="flex flex-wrap justify-center gap-x-4 gap-y-1 text-xs mt-4 -mb-2">
@@ -117,6 +139,13 @@ export function Chart({ data }: Props) {
<div className={cn('h-full w-full', isEditMode && 'card p-4')}>
<ResponsiveContainer>
<ComposedChart data={rechartData}>
<Customized component={calcStrokeDasharray} />
<Line
dataKey="calcStrokeDasharray"
legendType="none"
animationDuration={0}
onAnimationEnd={handleAnimationEnd}
/>
<CartesianGrid
strokeDasharray="3 3"
horizontal={true}
@@ -166,13 +195,6 @@ export function Chart({ data }: Props) {
/>
</linearGradient>
)}
{useDashedLastLine && (
<SolidToDashedGradient
percentage={lastIntervalPercent}
baseColor={color}
id={`stroke${color}`}
/>
)}
</defs>
<Line
dot={isAreaStyle && dataLength <= 8}
@@ -181,7 +203,12 @@ export function Chart({ data }: Props) {
isAnimationActive={false}
strokeWidth={2}
dataKey={`${serie.id}:count`}
stroke={useDashedLastLine ? `url(#stroke${color})` : color}
stroke={color}
strokeDasharray={
useDashedLastLine
? getStrokeDasharray(`${serie.id}:count`)
: undefined
}
// Use for legend
fill={color}
/>

View File

@@ -1,16 +1,9 @@
import { createSlice } from '@reduxjs/toolkit';
import type { PayloadAction } from '@reduxjs/toolkit';
import {
endOfDay,
formatISO,
isSameDay,
isSameMonth,
startOfDay,
} from 'date-fns';
import { createSlice } from '@reduxjs/toolkit';
import { endOfDay, format, isSameDay, isSameMonth, startOfDay } from 'date-fns';
import { shortId } from '@openpanel/common';
import {
alphabetIds,
getDefaultIntervalByDates,
getDefaultIntervalByRange,
isHourIntervalEnabledByRange,
@@ -192,31 +185,10 @@ export const reportSlice = createSlice({
state.lineType = action.payload;
},
// Custom start and end date
changeDates: (
state,
action: PayloadAction<{
startDate: string;
endDate: string;
}>,
) => {
state.dirty = true;
state.startDate = formatISO(startOfDay(action.payload.startDate));
state.endDate = formatISO(endOfDay(action.payload.endDate));
if (isSameDay(state.startDate, state.endDate)) {
state.interval = 'hour';
} else if (isSameMonth(state.startDate, state.endDate)) {
state.interval = 'day';
} else {
state.interval = 'month';
}
},
// Date range
changeStartDate: (state, action: PayloadAction<string>) => {
state.dirty = true;
state.startDate = formatISO(startOfDay(action.payload));
state.startDate = action.payload;
const interval = getDefaultIntervalByDates(
state.startDate,
@@ -230,7 +202,7 @@ export const reportSlice = createSlice({
// Date range
changeEndDate: (state, action: PayloadAction<string>) => {
state.dirty = true;
state.endDate = formatISO(endOfDay(action.payload));
state.endDate = action.payload;
const interval = getDefaultIntervalByDates(
state.startDate,
@@ -263,8 +235,6 @@ export const reportSlice = createSlice({
},
changeUnit(state, action: PayloadAction<string | undefined>) {
console.log('here?!?!', action.payload);
state.dirty = true;
state.unit = action.payload || undefined;
},
@@ -305,7 +275,6 @@ export const {
removeBreakdown,
changeBreakdown,
changeInterval,
changeDates,
changeStartDate,
changeEndDate,
changeDateRanges,

View File

@@ -18,6 +18,7 @@ import { useCallback, useEffect, useRef } from 'react';
import { shouldIgnoreKeypress } from '@/utils/should-ignore-keypress';
import { timeWindows } from '@openpanel/constants';
import type { IChartRange } from '@openpanel/validation';
import { endOfDay, format, startOfDay } from 'date-fns';
type Props = {
value: IChartRange;
@@ -46,8 +47,8 @@ export function TimeWindowPicker({
const handleCustom = useCallback(() => {
pushModal('DateRangerPicker', {
onChange: ({ startDate, endDate }) => {
onStartDateChange(startDate.toISOString());
onEndDateChange(endDate.toISOString());
onStartDateChange(format(startOfDay(startDate), 'yyyy-MM-dd HH:mm:ss'));
onEndDateChange(format(endOfDay(endDate), 'yyyy-MM-dd HH:mm:ss'));
onChange('custom');
},
startDate: startDate ? new Date(startDate) : undefined,
@@ -113,6 +114,12 @@ export function TimeWindowPicker({
{timeWindows.today.shortcut}
</DropdownMenuShortcut>
</DropdownMenuItem>
<DropdownMenuItem onClick={() => onChange(timeWindows.yesterday.key)}>
{timeWindows.yesterday.label}
<DropdownMenuShortcut>
{timeWindows.yesterday.shortcut}
</DropdownMenuShortcut>
</DropdownMenuItem>
</DropdownMenuGroup>
<DropdownMenuSeparator />
@@ -130,6 +137,18 @@ export function TimeWindowPicker({
{timeWindows['30d'].shortcut}
</DropdownMenuShortcut>
</DropdownMenuItem>
<DropdownMenuItem onClick={() => onChange(timeWindows['6m'].key)}>
{timeWindows['6m'].label}
<DropdownMenuShortcut>
{timeWindows['6m'].shortcut}
</DropdownMenuShortcut>
</DropdownMenuItem>
<DropdownMenuItem onClick={() => onChange(timeWindows['12m'].key)}>
{timeWindows['12m'].label}
<DropdownMenuShortcut>
{timeWindows['12m'].shortcut}
</DropdownMenuShortcut>
</DropdownMenuItem>
</DropdownMenuGroup>
<DropdownMenuSeparator />

View File

@@ -18,8 +18,6 @@ export function InputEnter({
useEffect(() => {
if (value !== internalValue) {
console.log(value, internalValue);
setInternalValue(value ?? '');
}
}, [value]);