feat: add daily monitor data display for public

This commit is contained in:
moonrailgun 2024-10-14 00:24:16 +08:00
parent 1a012bb129
commit 3d2971bce2
7 changed files with 300 additions and 91 deletions

View File

@ -0,0 +1,49 @@
import { useTheme } from '@/hooks/useTheme';
import { get } from 'lodash-es';
import React from 'react';
import { useMemo } from 'react';
import { Rectangle } from 'recharts';
export const CustomizedErrorArea: React.FC = (props) => {
const { colors } = useTheme();
const y = get(props, 'offset.top', 10);
const height = get(props, 'offset.height', 160);
const points = get(props, 'formattedGraphicalItems.0.props.points', []) as {
x: number;
y: number | null;
}[];
const errorArea = useMemo(() => {
const _errorArea: { x: number; width: number }[] = [];
let prevX: number | null = null;
points.forEach((item, i, arr) => {
if (i === 0 && !item.y) {
prevX = 0;
} else if (!item.y && prevX === null && arr[i - 1].y) {
prevX = arr[i - 1].x;
} else if (item.y && prevX !== null) {
_errorArea.push({
x: prevX,
width: item.x - prevX,
});
prevX = null;
}
});
return _errorArea;
}, [points]);
return errorArea.map((area, i) => {
return (
<Rectangle
key={i}
width={area.width}
height={height}
x={area.x}
y={y}
fill={colors.chart.error}
/>
);
});
};
CustomizedErrorArea.displayName = 'CustomizedErrorArea';

View File

@ -195,47 +195,3 @@ export const MonitorDataChart: React.FC<{ monitorId: string }> = React.memo(
} }
); );
MonitorDataChart.displayName = 'MonitorDataChart'; MonitorDataChart.displayName = 'MonitorDataChart';
const CustomizedErrorArea: React.FC = (props) => {
const { colors } = useTheme();
const y = get(props, 'offset.top', 10);
const height = get(props, 'offset.height', 160);
const points = get(props, 'formattedGraphicalItems.0.props.points', []) as {
x: number;
y: number | null;
}[];
const errorArea = useMemo(() => {
const _errorArea: { x: number; width: number }[] = [];
let prevX: number | null = null;
points.forEach((item, i, arr) => {
if (i === 0 && !item.y) {
prevX = 0;
} else if (!item.y && prevX === null && arr[i - 1].y) {
prevX = arr[i - 1].x;
} else if (item.y && prevX !== null) {
_errorArea.push({
x: prevX,
width: item.x - prevX,
});
prevX = null;
}
});
return _errorArea;
}, [points]);
return errorArea.map((area, i) => {
return (
<Rectangle
key={i}
width={area.width}
height={height}
x={area.x}
y={y}
fill={colors.chart.error}
/>
);
});
};
CustomizedErrorArea.displayName = 'CustomizedErrorArea';

View File

@ -0,0 +1,149 @@
import dayjs from 'dayjs';
import { get } from 'lodash-es';
import React, { useMemo } from 'react';
import { trpc } from '../../api/trpc';
import { getMonitorProvider, getProviderDisplay } from './provider';
import { useTranslation } from '@i18next-toolkit/react';
import {
ChartConfig,
ChartContainer,
ChartTooltip,
ChartTooltipContent,
} from '../ui/chart';
import {
Area,
AreaChart,
CartesianGrid,
Customized,
XAxis,
YAxis,
} from 'recharts';
import { useTheme } from '@/hooks/useTheme';
import { CustomizedErrorArea } from './CustomizedErrorArea';
const chartConfig = {
value: {
label: <span className="text-sm font-bold">Result</span>,
},
} satisfies ChartConfig;
interface MonitorPublicDataChartProps {
workspaceId: string;
monitorId: string;
className?: string;
}
export const MonitorPublicDataChart: React.FC<MonitorPublicDataChartProps> =
React.memo((props) => {
const { t } = useTranslation();
const { workspaceId, monitorId } = props;
const { colors } = useTheme();
const { data: monitorInfo } = trpc.monitor.getPublicInfo.useQuery(
{
monitorIds: [monitorId],
},
{
select(data) {
return data[0];
},
}
);
const { data: _data = [] } = trpc.monitor.publicData.useQuery({
workspaceId,
monitorId,
});
const providerInfo = getMonitorProvider(monitorInfo?.type ?? '');
const { data } = useMemo(() => {
const data = _data.map((d, i, arr) => {
const value = d.value > 0 ? d.value : null;
const time = dayjs(d.createdAt).valueOf();
return {
value,
time,
};
});
return { data };
}, [_data]);
const isTrendingMode = monitorInfo?.trendingMode ?? false; // if true, y axis not start from 0
return (
<div>
<ChartContainer className="h-[120px] w-full" config={chartConfig}>
<AreaChart
data={data}
margin={{ top: 10, right: 0, left: 0, bottom: 0 }}
>
<defs>
<linearGradient id="color" x1="0" y1="0" x2="0" y2="1">
<stop
offset="5%"
stopColor={colors.chart.monitor}
stopOpacity={0.3}
/>
<stop
offset="95%"
stopColor={colors.chart.monitor}
stopOpacity={0}
/>
</linearGradient>
</defs>
<XAxis
dataKey="time"
type="number"
domain={['dataMin', 'dataMax']}
tickFormatter={(date) => dayjs(date).format('HH:mm')}
/>
<YAxis
mirror
domain={[isTrendingMode ? 'dataMin' : 0, 'dataMax']}
/>
<CartesianGrid vertical={false} />
<ChartTooltip
labelFormatter={(label, payload) =>
dayjs(get(payload, [0, 'payload', 'time'])).format(
'YYYY-MM-DD HH:mm:ss'
)
}
formatter={(value, defaultText, item, index, payload) => {
if (typeof value !== 'number') {
return defaultText;
}
const { name, text } = getProviderDisplay(
Number(value),
providerInfo
);
return (
<div>
<span className="mr-2">{name}:</span>
<span>{text}</span>
</div>
);
}}
content={<ChartTooltipContent />}
/>
<Customized component={CustomizedErrorArea} />
<Area
type="monotone"
dataKey="value"
stroke={colors.chart.monitor}
fillOpacity={1}
fill="url(#color)"
strokeWidth={2}
isAnimationActive={false}
/>
</AreaChart>
</ChartContainer>
</div>
);
});
MonitorPublicDataChart.displayName = 'MonitorPublicDataChart';

View File

@ -15,6 +15,7 @@ import {
getStatusBgColorClassName, getStatusBgColorClassName,
parseHealthStatusByPercent, parseHealthStatusByPercent,
} from '@/utils/health'; } from '@/utils/health';
import { MonitorPublicDataChart } from '../MonitorPublicDataChart';
interface StatusPageBodyProps { interface StatusPageBodyProps {
workspaceId: string; workspaceId: string;
@ -51,7 +52,7 @@ export const StatusPageBody: React.FC<StatusPageBodyProps> = React.memo(
<StatusItemMonitor <StatusItemMonitor
key={item.key} key={item.key}
workspaceId={props.workspaceId} workspaceId={props.workspaceId}
id={item.id} monitorId={item.id}
showCurrent={item.showCurrent ?? false} showCurrent={item.showCurrent ?? false}
/> />
); );
@ -69,13 +70,13 @@ export const StatusPageBody: React.FC<StatusPageBodyProps> = React.memo(
StatusPageBody.displayName = 'StatusPageBody'; StatusPageBody.displayName = 'StatusPageBody';
export const StatusItemMonitor: React.FC<{ export const StatusItemMonitor: React.FC<{
id: string; monitorId: string;
showCurrent: boolean; showCurrent: boolean;
workspaceId: string; workspaceId: string;
}> = React.memo((props) => { }> = React.memo((props) => {
const { data: info } = trpc.monitor.getPublicInfo.useQuery( const { data: info } = trpc.monitor.getPublicInfo.useQuery(
{ {
monitorIds: [props.id], monitorIds: [props.monitorId],
}, },
{ {
select: (data) => data[0], select: (data) => data[0],
@ -84,7 +85,7 @@ export const StatusItemMonitor: React.FC<{
const { data: list = [], isLoading } = trpc.monitor.publicSummary.useQuery({ const { data: list = [], isLoading } = trpc.monitor.publicSummary.useQuery({
workspaceId: props.workspaceId, workspaceId: props.workspaceId,
monitorId: props.id, monitorId: props.monitorId,
}); });
const { summaryStatus, summaryPercent } = useMemo(() => { const { summaryStatus, summaryPercent } = useMemo(() => {
@ -108,51 +109,58 @@ export const StatusItemMonitor: React.FC<{
} }
return ( return (
<div <div>
className={cn( <div
'mb-1 flex items-center overflow-hidden rounded-lg bg-green-500 bg-opacity-0 px-4 py-3 hover:bg-opacity-10' className={cn(
)} 'mb-1 flex items-center overflow-hidden rounded-lg bg-green-500 bg-opacity-0 px-4 py-3 hover:bg-opacity-10'
> )}
<div> >
<span <div>
className={cn( <span
'inline-block min-w-[62px] rounded-full p-0.5 text-center text-white', className={cn(
getStatusBgColorClassName(summaryStatus) 'inline-block min-w-[62px] rounded-full p-0.5 text-center text-white',
)} getStatusBgColorClassName(summaryStatus)
> )}
{summaryPercent}% >
</span> {summaryPercent}%
</span>
</div>
<div className="flex-1 pl-2">
<div className="text-nowrap text-base">{info?.name}</div>
</div>
{props.showCurrent && info && (
<MonitorLatestResponse
workspaceId={props.workspaceId}
monitorId={info.id}
monitorType={info.type}
/>
)}
<div className="flex-shrink basis-[250px] items-center overflow-hidden px-1">
<HealthBar
className="justify-end"
size="small"
beats={[...list].reverse().map((item) => {
const status = parseHealthStatusByPercent(
item.upRate,
item.totalCount
);
return {
status,
title: `${item.day} | (${item.upCount}/${item.totalCount}) ${item.upRate}%`,
};
})}
/>
</div>
</div> </div>
<div className="flex-1 pl-2"> <MonitorRecentChart
<div className="text-nowrap text-base">{info?.name}</div> workspaceId={props.workspaceId}
</div> monitorId={props.monitorId}
/>
{props.showCurrent && info && (
<MonitorLatestResponse
workspaceId={props.workspaceId}
monitorId={info.id}
monitorType={info.type}
/>
)}
<div className="flex-shrink basis-[250px] items-center overflow-hidden px-1">
<HealthBar
className="justify-end"
size="small"
beats={[...list].reverse().map((item) => {
const status = parseHealthStatusByPercent(
item.upRate,
item.totalCount
);
return {
status,
title: `${item.day} | (${item.upCount}/${item.totalCount}) ${item.upRate}%`,
};
})}
/>
</div>
</div> </div>
); );
}); });
@ -199,3 +207,16 @@ const MonitorLatestResponse: React.FC<{
); );
}); });
MonitorLatestResponse.displayName = 'MonitorLatestResponse'; MonitorLatestResponse.displayName = 'MonitorLatestResponse';
export const MonitorRecentChart: React.FC<{
workspaceId: string;
monitorId: string;
}> = React.memo((props) => {
return (
<MonitorPublicDataChart
workspaceId={props.workspaceId}
monitorId={props.monitorId}
/>
);
});
MonitorRecentChart.displayName = 'MonitorRecentChart';

View File

@ -13,6 +13,7 @@ module.exports = {
'./components/**/*.{js,jsx,ts,tsx}', './components/**/*.{js,jsx,ts,tsx}',
'./pages/**/*.{js,jsx,ts,tsx}', './pages/**/*.{js,jsx,ts,tsx}',
'./routes/**/*.{js,jsx,ts,tsx}', './routes/**/*.{js,jsx,ts,tsx}',
'./utils/health.ts',
], ],
}, },
theme: { theme: {

View File

@ -9,4 +9,5 @@ export const monitorPublicInfoSchema = MonitorModelSchema.pick({
id: true, id: true,
name: true, name: true,
type: true, type: true,
trendingMode: true,
}); });

View File

@ -361,6 +361,38 @@ export const monitorRouter = router({
return summary; return summary;
}), }),
publicData: publicProcedure
.meta(
buildMonitorOpenapi({
method: 'GET',
protect: false,
path: '/{monitorId}/publicData',
})
)
.input(
z.object({
workspaceId: z.string().cuid2(),
monitorId: z.string().cuid2(),
})
)
.output(
z.array(
z.object({
value: z.number(),
createdAt: z.date(),
})
)
)
.query(async ({ input }) => {
const { workspaceId, monitorId } = input;
return getMonitorData(
workspaceId,
monitorId,
dayjs().subtract(1, 'days').toDate(),
dayjs().toDate()
);
}),
dataMetrics: workspaceProcedure dataMetrics: workspaceProcedure
.meta( .meta(
buildMonitorOpenapi({ buildMonitorOpenapi({