snapshot of https://github.com/RocketChat/Rocket.Chat.git (develop, 2026-09-16; blobs > 131072B omitted)
Some checks failed
Create issues from TODOs / todos (push) Failing after 3s
Close inactive issues / close-issues (push) Has been cancelled
Deploy GitHub Pages / deploy-preview (push) Has been cancelled
CI / ⚙️ Variables Setup (push) Has been cancelled
CI / ⚙️ Test Guard (push) Has been cancelled
CI / 🚀 Notify external services - draft (push) Has been cancelled
CI / 📦 Build Packages (push) Has been cancelled
CI / 📦 Meteor Build (coverage) (push) Has been cancelled
CI / 📦 Meteor Build (production) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], fips) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Publish Docker Images (ghcr.io) (push) Has been cancelled
CI / 📦 Track Image Sizes (push) Has been cancelled
CI / 🔎 Code Check - Action Lint (push) Has been cancelled
CI / 🔎 Code Check (push) Has been cancelled
CI / 🔨 Test Storybook (push) Has been cancelled
CI / 🔨 Test Unit (push) Has been cancelled
CI / 🔨 Test API (CE) (push) Has been cancelled
CI / 🔨 Test API Livechat (CE) (push) Has been cancelled
CI / 🔨 Test UI (CE) (push) Has been cancelled
CI / 🔨 Test API (EE) (push) Has been cancelled
CI / 🔨 Test API Livechat (EE) (push) Has been cancelled
CI / 🔨 Test API Apps (deno-runtime - EE) (push) Has been cancelled
CI / 🔨 Test UI (EE) (push) Has been cancelled
CI / 🔨 Test API (FIPS) (push) Has been cancelled
CI / 🔨 Test API Livechat (FIPS) (push) Has been cancelled
CI / 🔨 Test UI (FIPS) (push) Has been cancelled
CI / 🔨 Test Federation Matrix (push) Has been cancelled
CI / 📊 Report Coverage (push) Has been cancelled
CI / ✅ Tests Done (push) Has been cancelled
CI / 🚀 Publish build assets (push) Has been cancelled
CI / 🚀 Publish Docker Images (DockerHub) (push) Has been cancelled
CI / 🚀 Notify external services (push) Has been cancelled
CI / Update Version Durability (push) Has been cancelled
Release / Release (push) Has been cancelled
Auto-close duplicate issues / auto-close-duplicates (push) Failing after 1s
Code scanning - action / CodeQL-Build (push) Failing after 1s

This commit is contained in:
upstream-mirror
2026-09-16 01:21:02 +05:00
commit 30810eecd7
10161 changed files with 987110 additions and 0 deletions

View File

@@ -0,0 +1,280 @@
import { ResponsiveLine } from '@nivo/line';
import { Box, FlexContainer, FlexItem, Skeleton, Tile } from '@rocket.chat/fuselage';
import colors from '@rocket.chat/fuselage-tokens/dist/colors.json';
import { addDays, startOfDay, differenceInDays, endOfDay, subDays, format } from 'date-fns';
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { useActiveUsers } from './useActiveUsers';
import DownloadDataButton from '../../../../components/dashboards/DownloadDataButton';
import CounterSet from '../../../../components/dataView/CounterSet';
import { useFormatDate } from '../../../../hooks/useFormatDate';
import EngagementDashboardCardFilter from '../EngagementDashboardCardFilter';
import LegendSymbol from '../dataView/LegendSymbol';
export type ActiveUsersSectionProps = {
timezone: 'utc' | 'local';
};
const ActiveUsersSection = ({ timezone }: ActiveUsersSectionProps) => {
const utc = timezone === 'utc';
const { data } = useActiveUsers({ utc });
const [
countDailyActiveUsers,
diffDailyActiveUsers,
countWeeklyActiveUsers,
diffWeeklyActiveUsers,
countMonthlyActiveUsers,
diffMonthlyActiveUsers,
dauValues = [],
wauValues = [],
mauValues = [],
] = useMemo(() => {
if (!data) {
return [];
}
const startDate = new Date(data.start);
const createPoint = (i: number): { x: Date; y: number } => ({
x: startOfDay(addDays(startDate, i)),
y: 0,
});
const daysCount = differenceInDays(new Date(data.end), startDate);
const createPoints = (): { x: Date; y: number }[] => Array.from({ length: daysCount }, (_, i) => createPoint(i));
const dauValuesLocal = createPoints();
const prevDauValue = createPoint(-1);
const wauValuesLocal = createPoints();
const prevWauValue = createPoint(-1);
const mauValuesLocal = createPoints();
const prevMauValue = createPoint(-1);
const usersListsMap = data.month.reduce<{ [x: number]: string[] }>((map, dayData) => {
const d = utc
? new Date(Date.UTC(dayData.year, dayData.month - 1, dayData.day))
: new Date(dayData.year, dayData.month - 1, dayData.day);
const date = utc ? new Date(Date.UTC(dayData.year, dayData.month - 1, dayData.day, 23, 59, 59, 999)) : endOfDay(d);
const dateOffset = differenceInDays(date, startDate);
if (dateOffset >= 0 && dauValuesLocal[dateOffset]) {
map[dateOffset] = dayData.usersList;
dauValuesLocal[dateOffset].y = dayData.users;
}
return map;
}, {});
const distributeValueOverPoints = (
usersListsMap: { [x: number]: string[] },
dateOffset: number,
count: number,
array: { x: Date; y: number }[],
): void => {
const usersSet = new Set();
for (let k = dateOffset; count > 0; k--, count--) {
if (usersListsMap[k]) {
usersListsMap[k].map((userId) => usersSet.add(userId));
}
}
array[dateOffset].y = usersSet.size;
};
for (let i = 0; i < dauValuesLocal.length; i++) {
distributeValueOverPoints(usersListsMap, i, 7, wauValuesLocal);
distributeValueOverPoints(usersListsMap, i, 30, mauValuesLocal);
}
prevWauValue.y = wauValuesLocal[dauValuesLocal.length - 2].y;
prevMauValue.y = mauValuesLocal[dauValuesLocal.length - 2].y;
prevDauValue.y = dauValuesLocal[dauValuesLocal.length - 2].y;
return [
dauValuesLocal[dauValuesLocal.length - 1].y,
dauValuesLocal[dauValuesLocal.length - 1].y - prevDauValue.y,
wauValuesLocal[wauValuesLocal.length - 1].y,
wauValuesLocal[wauValuesLocal.length - 1].y - prevWauValue.y,
mauValuesLocal[mauValuesLocal.length - 1].y,
mauValuesLocal[mauValuesLocal.length - 1].y - prevMauValue.y,
dauValuesLocal,
wauValuesLocal,
mauValuesLocal,
];
}, [data, utc]);
const formatDate = useFormatDate();
const { t } = useTranslation();
return (
<>
<EngagementDashboardCardFilter>
<DownloadDataButton
attachmentName={`ActiveUsersSection_start_${data?.start}_end_${data?.end ? subDays(new Date(data.end), 1).toISOString() : ''}`}
headers={['Date', 'DAU', 'WAU', 'MAU']}
dataAvailable={!!data}
dataExtractor={(): unknown[][] | undefined => {
const values = [];
for (let i = 0; i < 30; i++) {
values.push([dauValues[i].x.toISOString(), dauValues[i].y, wauValues[i].y, mauValues[i].y]);
}
return values;
}}
/>
</EngagementDashboardCardFilter>
<CounterSet
counters={[
{
count: countDailyActiveUsers ?? <Skeleton variant='rect' width='3ex' height='1em' />,
variation: diffDailyActiveUsers ?? 0,
description: (
<>
<LegendSymbol color={colors.b200} /> {t('Daily_Active_Users')}
</>
),
},
{
count: countWeeklyActiveUsers ?? <Skeleton variant='rect' width='3ex' height='1em' />,
variation: diffWeeklyActiveUsers ?? 0,
description: (
<>
<LegendSymbol color={colors.b300} /> {t('Weekly_Active_Users')}
</>
),
},
{
count: countMonthlyActiveUsers ?? <Skeleton variant='rect' width='3ex' height='1em' />,
variation: diffMonthlyActiveUsers ?? 0,
description: (
<>
<LegendSymbol color={colors.p500} /> {t('Monthly_Active_Users')}
</>
),
},
]}
/>
<FlexContainer>
{data ? (
<Box style={{ height: 240 }}>
<FlexItem align='stretch' grow={1} shrink={0}>
<Box style={{ position: 'relative' }}>
<Box
style={{
position: 'absolute',
width: '100%',
height: '100%',
}}
>
<ResponsiveLine
data={[
{
id: 'dau',
data: dauValues,
},
{
id: 'wau',
data: wauValues,
},
{
id: 'mau',
data: mauValues,
},
]}
xScale={{
type: 'time',
format: 'native',
precision: 'day',
}}
xFormat='time:%Y-%m-%d'
yScale={{
type: 'linear',
stacked: true,
}}
enableGridX={false}
enableGridY={false}
enablePoints={false}
useMesh
enableArea
areaOpacity={1}
enableCrosshair
crosshairType='bottom'
margin={{
// TODO: Get it from theme
top: 0,
bottom: 20,
right: 0,
left: 40,
}}
colors={[colors.b200, colors.b300, colors.b500]}
axisLeft={{
// TODO: Get it from theme
tickSize: 0,
tickPadding: 4,
tickRotation: 0,
tickValues: 3,
}}
axisBottom={{
// TODO: Get it from theme
tickSize: 0,
tickPadding: 4,
tickRotation: 0,
tickValues: 'every 3 days',
format: (date): string => format(new Date(date), 'dd/MM'),
}}
animate={true}
motionConfig='stiff'
theme={{
// TODO: Get it from theme
axis: {
ticks: {
text: {
fill: '#9EA2A8',
fontFamily:
'Inter, -apple-system, system-ui, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Helvetica Neue", "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Meiryo UI", Arial, sans-serif',
fontSize: '10px',
fontStyle: 'normal',
fontWeight: 600,
letterSpacing: '0.2px',
lineHeight: '12px',
},
},
},
tooltip: {
container: {
backgroundColor: '#1F2329',
boxShadow: '0px 0px 12px rgba(47, 52, 61, 0.12), 0px 0px 2px rgba(47, 52, 61, 0.08)',
borderRadius: 2,
},
},
}}
enableSlices='x'
sliceTooltip={({ slice: { points } }) => (
<Tile elevation='2'>
<Box>
<Box>{formatDate(points[0].data.x)}</Box>
{points.map(({ serieId, data: { y: activeUsers } }) => (
<Box key={serieId} fontScale='p1m'>
<Box>
{(serieId === 'dau' && t('DAU_value', { value: activeUsers })) ||
(serieId === 'wau' && t('WAU_value', { value: activeUsers })) ||
(serieId === 'mau' && t('MAU_value', { value: activeUsers }))}
</Box>
</Box>
))}
</Box>
</Tile>
)}
/>
</Box>
</Box>
</FlexItem>
</Box>
) : (
<Skeleton variant='rect' height={240} />
)}
</FlexContainer>
</>
);
};
export default ActiveUsersSection;

View File

@@ -0,0 +1,64 @@
import { Select } from '@rocket.chat/fuselage';
import { useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import EngagementDashboardCardFilter from '../EngagementDashboardCardFilter';
import ContentForDays from './ContentForDays';
import ContentForHours from './ContentForHours';
type TimeUnit = 'hours' | 'days';
export type BusiestChatTimesSectionProps = {
timezone: 'utc' | 'local';
};
const BusiestChatTimesSection = ({ timezone }: BusiestChatTimesSectionProps) => {
const { t } = useTranslation();
const [timeUnit, setTimeUnit] = useState<TimeUnit>('hours');
const timeUnitOptions = useMemo<[timeUnit: TimeUnit, label: string][]>(
() => [
['hours', t('Hours')],
['days', t('Days')],
],
[t],
);
const [displacement, setDisplacement] = useState(0);
const handleTimeUnitChange = (timeUnit: string): void => {
setTimeUnit(timeUnit as TimeUnit);
setDisplacement(0);
};
const handlePreviousDateClick = (): void => setDisplacement((displacement) => displacement + 1);
const handleNextDateClick = (): void => setDisplacement((displacement) => displacement - 1);
const Content = (
{
hours: ContentForHours,
days: ContentForDays,
} as const
)[timeUnit];
return (
<>
<EngagementDashboardCardFilter>
<Select
options={timeUnitOptions}
value={timeUnit}
onChange={(value) => handleTimeUnitChange(String(value))}
aria-label={t('Select_period')}
/>
</EngagementDashboardCardFilter>
<Content
displacement={displacement}
onPreviousDateClick={handlePreviousDateClick}
onNextDateClick={handleNextDateClick}
timezone={timezone}
/>
</>
);
};
export default BusiestChatTimesSection;

View File

@@ -0,0 +1,119 @@
import { ResponsiveBar } from '@nivo/bar';
import { Box, FlexContainer, FlexItem, IconButton, Margins, Skeleton } from '@rocket.chat/fuselage';
import colors from '@rocket.chat/fuselage-tokens/dist/colors.json';
import { format, subDays } from 'date-fns';
import { useMemo } from 'react';
import { useWeeklyChatActivity } from './useWeeklyChatActivity';
import { formatDate } from '../../../../lib/utils/dateFormat';
export type ContentForDaysProps = {
displacement: number;
onPreviousDateClick: () => void;
onNextDateClick: () => void;
timezone: 'utc' | 'local';
};
const ContentForDays = ({ displacement, onPreviousDateClick, onNextDateClick, timezone }: ContentForDaysProps) => {
const utc = timezone === 'utc';
const { data } = useWeeklyChatActivity({ displacement, utc });
const formattedCurrentDate = useMemo(() => {
if (!data) {
return null;
}
const dayDate = new Date(data.day);
const endOfWeek = dayDate;
const startOfWeek = subDays(dayDate, 6);
return `${format(startOfWeek, 'P')} - ${format(endOfWeek, 'P')}`;
}, [data]);
const values = useMemo(
() =>
data?.month
?.map(({ users, day, month, year }) => ({
users,
day: new Date(year, month - 1, day).getTime(),
}))
?.sort((a, b) => a.day - b.day)
?.map(({ users, day }) => ({ users, day: String(day) })) ?? [],
[data],
);
return (
<>
<FlexContainer alignItems='center' justifyContent='center'>
<Box>
<IconButton icon='chevron-down' verticalAlign='middle' small onClick={onPreviousDateClick} />
<FlexItem basis='50%'>
<Margins inline={8}>
<Box is='span' textAlign='center'>
{formattedCurrentDate}
</Box>
</Margins>
</FlexItem>
<IconButton icon='chevron-down' small disabled={displacement === 0} onClick={onNextDateClick} />
</Box>
</FlexContainer>
<FlexContainer>
{data ? (
<Box height={196}>
<FlexItem align='stretch' grow={1} shrink={0}>
<Box position='relative'>
<Box position='absolute' width='full' height='full'>
<ResponsiveBar
data={values}
indexBy='day'
keys={['users']}
groupMode='grouped'
padding={0.25}
margin={{
// TODO: Get it from theme
bottom: 20,
}}
colors={[
// TODO: Get it from theme
colors.p500,
]}
enableLabel={false}
enableGridY={false}
axisTop={null}
axisRight={null}
axisBottom={{
tickSize: 0,
// TODO: Get it from theme
tickPadding: 4,
tickRotation: 0,
tickValues: 'every 3 days',
format: (timestamp): string => formatDate(parseInt(timestamp, 10), 'L'),
}}
axisLeft={null}
animate={true}
motionConfig='stiff'
theme={{
// TODO: Get it from theme
axis: {
ticks: {
text: {
fill: colors.n600,
fontFamily:
'Inter, -apple-system, system-ui, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Helvetica Neue", "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Meiryo UI", Arial, sans-serif',
},
},
},
}}
/>
</Box>
</Box>
</FlexItem>
</Box>
) : (
<Skeleton variant='rect' height={196} />
)}
</FlexContainer>
</>
);
};
export default ContentForDays;

View File

@@ -0,0 +1,121 @@
import { ResponsiveBar } from '@nivo/bar';
import { Box, Button, Chevron, Skeleton, Tooltip } from '@rocket.chat/fuselage';
import { useBreakpoints } from '@rocket.chat/fuselage-hooks';
import colors from '@rocket.chat/fuselage-tokens/dist/colors.json';
import { format } from 'date-fns';
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { useHourlyChatActivity } from './useHourlyChatActivity';
export type ContentForHoursProps = {
displacement: number;
onPreviousDateClick: () => void;
onNextDateClick: () => void;
timezone: 'utc' | 'local';
};
const ContentForHours = ({ displacement, onPreviousDateClick, onNextDateClick, timezone }: ContentForHoursProps) => {
const utc = timezone === 'utc';
const { data } = useHourlyChatActivity({ displacement, utc });
const { t } = useTranslation();
const isLgScreen = useBreakpoints().includes('lg');
const values = useMemo(() => {
if (!data) {
return [];
}
const divider = 2;
const values = Array.from({ length: 24 / divider }, (_, i) => ({
hour: String(divider * i),
users: 0,
}));
for (const { hour, users } of data?.hours ?? []) {
const i = Math.floor(hour / divider);
values[i] = values[i] || { hour: String(divider * i), users: 0 };
values[i].users += users;
}
return values;
}, [data]);
return (
<>
<Box display='flex' alignItems='center' justifyContent='center'>
<Button square small onClick={onPreviousDateClick}>
<Chevron left size='x20' style={{ verticalAlign: 'middle' }} />
</Button>
<Box marginInline={8} flexBasis='25%' is='span' style={{ textAlign: 'center' }}>
{data ? format(new Date(data.day), displacement < 7 ? 'EEEE' : 'P') : null}
</Box>
<Button square small disabled={displacement === 0} onClick={onNextDateClick}>
<Chevron right size='x20' style={{ verticalAlign: 'middle' }} />
</Button>
</Box>
{data ? (
<Box display='flex' height='196px'>
<Box alignSelf='stretch' flexGrow={1} flexShrink={0} position='relative'>
<Box position='absolute' width='100%' height='100%'>
<ResponsiveBar
data={values}
indexBy='hour'
keys={['users']}
groupMode='grouped'
padding={0.25}
margin={{
// TODO: Get it from theme
bottom: 30,
right: 5,
}}
colors={[
// TODO: Get it from theme
colors.p500,
]}
enableLabel={false}
enableGridY={false}
axisTop={null}
axisRight={null}
axisBottom={{
tickSize: 0,
// TODO: Get it from theme
tickPadding: 4,
tickRotation: isLgScreen ? 0 : 25,
tickValues: 'every 2 hours',
format: (hour): string => format(new Date(2000, 0, 1, Number(hour), 0, 0), 'p'),
}}
axisLeft={null}
animate={true}
motionConfig='stiff'
theme={{
// TODO: Get it from theme
axis: {
ticks: {
text: {
fill: colors.n600,
fontFamily:
'Inter, -apple-system, system-ui, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Helvetica Neue", "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Meiryo UI", Arial, sans-serif',
fontSize: '10px',
fontStyle: 'normal',
fontWeight: 600,
letterSpacing: '0.2px',
lineHeight: '12px',
},
},
},
}}
tooltip={({ value }) => <Tooltip>{t('Value_users', { value })}</Tooltip>}
/>
</Box>
</Box>
</Box>
) : (
<Skeleton variant='rect' height={196} />
)}
</>
);
};
export default ContentForHours;

View File

@@ -0,0 +1,165 @@
import { ResponsiveBar } from '@nivo/bar';
import { Box, FlexContainer, FlexItem, Skeleton, Tooltip } from '@rocket.chat/fuselage';
import colors from '@rocket.chat/fuselage-tokens/dist/colors.json';
import { differenceInDays, addDays, format } from 'date-fns';
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import DownloadDataButton from '../../../../components/dashboards/DownloadDataButton';
import PeriodSelector from '../../../../components/dashboards/PeriodSelector';
import { usePeriodLabel } from '../../../../components/dashboards/usePeriodLabel';
import { usePeriodSelectorState } from '../../../../components/dashboards/usePeriodSelectorState';
import CounterSet from '../../../../components/dataView/CounterSet';
import { useFormatDate } from '../../../../hooks/useFormatDate';
import EngagementDashboardCardFilter from '../EngagementDashboardCardFilter';
import { useNewUsers } from './useNewUsers';
export type NewUsersSectionProps = {
timezone: 'utc' | 'local';
};
const NewUsersSection = ({ timezone }: NewUsersSectionProps) => {
const [period, periodSelectorProps] = usePeriodSelectorState('last 7 days', 'last 30 days', 'last 90 days');
const periodLabel = usePeriodLabel(period);
const utc = timezone === 'utc';
const { data } = useNewUsers({ period, utc });
const { t } = useTranslation();
const formatDate = useFormatDate();
const [countFromPeriod, variatonFromPeriod, countFromYesterday, variationFromYesterday, values] = useMemo(() => {
if (!data) {
return [];
}
const startDate = new Date(data.start);
const endDate = new Date(data.end);
const daysCount = differenceInDays(endDate, startDate) + 1;
const values = Array.from({ length: daysCount }, (_, i) => ({
date: addDays(startDate, i).toISOString(),
newUsers: 0,
}));
for (const { day, users } of data.days) {
const dayDate = new Date(day);
const i = differenceInDays(dayDate, startDate);
if (i >= 0) {
values[i].newUsers += users;
}
}
return [data.period.count, data.period.variation, data.yesterday.count, data.yesterday.variation, values];
}, [data, utc]);
return (
<>
<EngagementDashboardCardFilter>
<PeriodSelector {...periodSelectorProps} />
<DownloadDataButton
attachmentName={`NewUsersSection_start_${data?.start}_end_${data?.end}`}
headers={['Date', 'New Users']}
dataAvailable={!!data}
dataExtractor={(): unknown[][] | undefined => values?.map(({ date, newUsers }) => [date, newUsers])}
/>
</EngagementDashboardCardFilter>
<CounterSet
counters={[
{
count: countFromPeriod ?? <Skeleton variant='rect' width='3ex' height='1em' />,
variation: variatonFromPeriod ?? 0,
description: periodLabel,
},
{
count: countFromYesterday ?? <Skeleton variant='rect' width='3ex' height='1em' />,
variation: variationFromYesterday ?? 0,
description: t('Yesterday'),
},
]}
/>
<FlexContainer>
{values ? (
<Box style={{ height: 300 }}>
<FlexItem align='stretch' grow={1} shrink={0}>
<Box style={{ position: 'relative' }}>
<Box
style={{
position: 'absolute',
width: '100%',
height: '100%',
}}
>
<ResponsiveBar
data={values}
indexBy='date'
keys={['newUsers']}
groupMode='grouped'
padding={0.25}
margin={{
// TODO: Get it from theme
bottom: 50,
left: 20,
top: 20,
}}
colors={[
// TODO: Get it from theme
colors.p500,
]}
enableLabel={false}
enableGridY={false}
axisTop={null}
axisRight={null}
axisBottom={{
tickSize: values.length > 31 ? 4 : 0,
// TODO: Get it from theme
tickPadding: 8,
tickRotation: values.length > 31 ? 90 : 0,
truncateTickAt: 0,
format: (date): string => format(new Date(date), 'dd/MM'),
}}
axisLeft={{
tickSize: 0,
// TODO: Get it from theme
tickPadding: 4,
tickRotation: 0,
}}
animate={true}
motionConfig='stiff'
theme={{
// TODO: Get it from theme
axis: {
ticks: {
text: {
fill: colors.n600,
fontFamily:
'Inter, -apple-system, system-ui, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Helvetica Neue", "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Meiryo UI", Arial, sans-serif',
fontSize: '10px',
fontStyle: 'normal',
fontWeight: 600,
letterSpacing: '0.2px',
lineHeight: '12px',
},
},
},
}}
tooltip={({ value, indexValue }) => (
<Tooltip>
{t('Value_users', { value })}, {formatDate(indexValue)}
</Tooltip>
)}
/>
</Box>
</Box>
</FlexItem>
</Box>
) : (
<Box>
<Skeleton variant='rect' height={240} />
</Box>
)}
</FlexContainer>
</>
);
};
export default NewUsersSection;

View File

@@ -0,0 +1,202 @@
import type { ComputedCell, DefaultHeatMapDatum } from '@nivo/heatmap';
import { ResponsiveHeatMapCanvas } from '@nivo/heatmap';
import { Box, FlexItem, Skeleton, Tooltip } from '@rocket.chat/fuselage';
import colors from '@rocket.chat/fuselage-tokens/dist/colors.json';
import { differenceInDays, addDays, endOfDay, format, isSameDay } from 'date-fns';
import { useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { useUsersByTimeOfTheDay } from './useUsersByTimeOfTheDay';
import DownloadDataButton from '../../../../components/dashboards/DownloadDataButton';
import PeriodSelector from '../../../../components/dashboards/PeriodSelector';
import { usePeriodSelectorState } from '../../../../components/dashboards/usePeriodSelectorState';
import EngagementDashboardCardFilter from '../EngagementDashboardCardFilter';
export type UsersByTimeOfTheDaySectionProps = {
timezone: 'utc' | 'local';
};
function endOfDayUTC(d: Date): Date {
return new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), 23, 59, 59, 999));
}
const UsersByTimeOfTheDaySection = ({ timezone }: UsersByTimeOfTheDaySectionProps) => {
const [period, periodSelectorProps] = usePeriodSelectorState('last 7 days', 'last 30 days', 'last 90 days');
const utc = timezone === 'utc';
const { data, isPending } = useUsersByTimeOfTheDay({ period, utc });
const { t } = useTranslation();
const [dates, values] = useMemo(() => {
if (!data || isPending) {
return [];
}
const startDate = new Date(data.start);
const endDate = new Date(data.end);
const length = utc ? differenceInDays(endDate, startDate) + 1 : differenceInDays(endDate, startDate) - 1;
const start = utc ? endOfDayUTC(startDate) : addDays(endOfDay(startDate), 1);
const datesArray = new Array(length);
for (let i = 0; i < length; i++) {
datesArray[i] = addDays(start, i).toISOString();
}
const valuesArray = new Array(24);
for (let hour = 0; hour < 24; hour++) {
valuesArray[hour] = {
id: hour.toString(),
data: datesArray.map((x) => ({ x, y: 0 })),
};
}
const timezoneOffsetMinutes = -new Date().getTimezoneOffset();
for (const { users, hour, day, month, year } of data.week) {
const d = utc ? new Date(Date.UTC(year, month - 1, day, hour, 0, 0, 0)) : new Date(year, month - 1, day, hour, 0, 0, 0);
if (!utc) {
d.setMinutes(d.getMinutes() + timezoneOffsetMinutes);
}
const include = utc || (!isSameDay(d, endDate) && !isSameDay(new Date(d.getFullYear(), d.getMonth(), d.getDate()), startDate));
if (include) {
const dateEnd = endOfDay(d);
const dateKey = dateEnd.toISOString();
const hourIdx = d.getHours();
const dataPoint = valuesArray[hourIdx].data.find((point: { x: string }) => point.x === dateKey);
if (dataPoint) {
dataPoint.y += users;
}
}
}
return [datesArray, valuesArray];
}, [data, isPending, utc]);
const tooltip = useCallback(
({ cell }: { cell: ComputedCell<DefaultHeatMapDatum> }) => {
return (
<Tooltip>
{format(new Date(cell.data.x), 'EEE')} {format(new Date(2000, 0, 1, parseInt(cell.serieId, 10), 0, 0), 'p')}
<br />
{t('Value_users', { value: cell.data.y })}
</Tooltip>
);
},
[t],
);
return (
<>
<EngagementDashboardCardFilter>
<PeriodSelector {...periodSelectorProps} />
<DownloadDataButton
attachmentName={`UsersByTimeOfTheDaySection_start_${data?.start}_end_${data?.end}`}
headers={['Date', 'Users']}
dataAvailable={!!data}
dataExtractor={(): unknown[][] | undefined =>
data?.week
?.map(({ users, hour, day, month, year }) => ({
date: new Date(year, month - 1, day, hour, 0, 0, 0),
users,
}))
?.sort((a, b) => a.date.getTime() - b.date.getTime())
?.map(({ date, users }) => [date.toISOString(), users])
}
/>
</EngagementDashboardCardFilter>
{!isPending && values && dates ? (
<Box display='flex' style={{ height: 696 }}>
<FlexItem align='stretch' grow={1} shrink={0}>
<Box style={{ position: 'relative' }}>
<Box
style={{
position: 'absolute',
width: '100%',
height: '100%',
}}
>
<ResponsiveHeatMapCanvas
data={values}
xInnerPadding={0.1}
yInnerPadding={0.25}
margin={{
// TODO: Get it from theme
left: 60,
bottom: 20,
}}
colors={{
type: 'quantize',
colors: [
// TODO: Get it from theme
colors.b100,
colors.b200,
colors.b300,
colors.b400,
colors.b500,
colors.b600,
colors.b700,
],
}}
emptyColor='transparent'
enableLabels={false}
axisTop={null}
axisRight={null}
axisBottom={{
// TODO: Get it from theme
tickSize: 0,
tickPadding: 8,
tickRotation: 0,
format: (isoString): string => (dates?.length === 8 ? format(new Date(isoString), 'EEE') : ''),
}}
axisLeft={{
// TODO: Get it from theme
tickSize: 0,
tickPadding: 8,
tickRotation: 0,
format: (hour): string => format(new Date(2000, 0, 1, parseInt(hour, 10), 0, 0), 'p'),
}}
hoverTarget='cell'
animate={dates && dates.length <= 7}
motionConfig='stiff'
theme={{
// TODO: Get it from theme
axis: {
ticks: {
text: {
fill: colors.n600,
fontFamily:
'Inter, -apple-system, system-ui, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Helvetica Neue", "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Meiryo UI", Arial, sans-serif',
fontSize: 10,
fontStyle: 'normal',
fontWeight: 600,
letterSpacing: '0.2px',
lineHeight: '12px',
},
},
},
tooltip: {
container: {
backgroundColor: colors.n900,
boxShadow: '0px 0px 12px rgba(47, 52, 61, 0.12), 0px 0px 2px rgba(47, 52, 61, 0.08)',
borderRadius: 2,
},
},
}}
tooltip={tooltip}
/>
</Box>
</Box>
</FlexItem>
</Box>
) : (
<Skeleton variant='rect' height={696} />
)}
</>
);
};
export default UsersByTimeOfTheDaySection;

View File

@@ -0,0 +1,14 @@
import { Margins } from '@rocket.chat/fuselage';
import type { StoryObj, Meta } from '@storybook/react';
import UsersTab from './UsersTab';
export default {
component: UsersTab,
decorators: [(fn) => <Margins all='x24'>{fn()}</Margins>],
} satisfies Meta<typeof UsersTab>;
export const Default: StoryObj<typeof UsersTab> = {
render: () => <UsersTab timezone='utc' />,
name: 'UsersTab',
};

View File

@@ -0,0 +1,44 @@
import { Box, FlexItem } from '@rocket.chat/fuselage';
import { useBreakpoints } from '@rocket.chat/fuselage-hooks';
import { useTranslation } from 'react-i18next';
import EngagementDashboardCard from '../EngagementDashboardCard';
import ActiveUsersSection from './ActiveUsersSection';
import BusiestChatTimesSection from './BusiestChatTimesSection';
import NewUsersSection from './NewUsersSection';
import UsersByTimeOfTheDaySection from './UsersByTimeOfTheDaySection';
export type UsersTabProps = {
timezone: 'utc' | 'local';
};
const UsersTab = ({ timezone }: UsersTabProps) => {
const { t } = useTranslation();
const isXxlScreen = useBreakpoints().includes('xxl');
return (
<>
<EngagementDashboardCard title={t('New_users')}>
<NewUsersSection timezone={timezone} />
</EngagementDashboardCard>
<EngagementDashboardCard title={t('Active_users')}>
<ActiveUsersSection timezone={timezone} />
</EngagementDashboardCard>
<Box display='flex' flexWrap='wrap' style={{ columnGap: '16px' }}>
<FlexItem grow={1} shrink={0} basis={isXxlScreen ? '0' : '100%'}>
<EngagementDashboardCard title={t('Users_by_time_of_day')}>
<UsersByTimeOfTheDaySection timezone={timezone} />
</EngagementDashboardCard>
</FlexItem>
<Box flexGrow={1} flexShrink={0} flexBasis={isXxlScreen ? '0' : '100%'}>
<EngagementDashboardCard title={t('When_is_the_chat_busier?')}>
<BusiestChatTimesSection timezone={timezone} />
</EngagementDashboardCard>
</Box>
</Box>
</>
);
};
export default UsersTab;

View File

@@ -0,0 +1,34 @@
import { useEndpoint } from '@rocket.chat/ui-contexts';
import { useQuery } from '@tanstack/react-query';
import { getPeriodRange } from '../../../../components/dashboards/periods';
type UseActiveUsersOptions = { utc: boolean };
export const useActiveUsers = ({ utc }: UseActiveUsersOptions) => {
const getActiveUsers = useEndpoint('GET', '/v1/engagement-dashboard/users/active-users');
return useQuery({
queryKey: ['admin/engagement-dashboard/users/active', { utc }],
queryFn: async () => {
const { start, end } = getPeriodRange('last 30 days', utc);
const response = await getActiveUsers({
start: start.toISOString(),
end: end.toISOString(),
});
return response
? {
...response,
start,
end,
}
: undefined;
},
refetchInterval: 5 * 60 * 1000,
throwOnError: true,
});
};

View File

@@ -0,0 +1,89 @@
import { mockAppRoot } from '@rocket.chat/mock-providers';
import { renderHook, waitFor } from '@testing-library/react';
import { useHourlyChatActivity } from './useHourlyChatActivity';
it('should return utc time', async () => {
const expectedResult = {
hours: [
{ hour: 0, users: 0 },
{ hour: 2, users: 0 },
{ hour: 4, users: 0 },
{ hour: 6, users: 0 },
{ hour: 8, users: 0 },
{ hour: 10, users: 0 },
{ hour: 12, users: 5 },
{ hour: 14, users: 0 },
{ hour: 16, users: 0 },
{ hour: 18, users: 0 },
{ hour: 20, users: 0 },
{ hour: 22, users: 0 },
],
success: true,
};
const { result } = renderHook(() => useHourlyChatActivity({ displacement: 0, utc: true }), {
wrapper: mockAppRoot()
.withEndpoint('GET', '/v1/engagement-dashboard/users/chat-busier/hourly-data', () => expectedResult)
.build(),
});
await waitFor(() => expect(result.current.isSuccess).toBe(true));
if (!result.current.data) {
throw new Error('Data is undefined');
}
expect(result.current.data?.hours).toEqual(expectedResult.hours);
});
// CI is currently running in UTC, so no local time is returned
// TODO: find a way to simulate local time properly in tests
it.skip('should return local time', async () => {
const receivedData = {
hours: [
{ hour: 0, users: 0 },
{ hour: 2, users: 0 },
{ hour: 4, users: 0 },
{ hour: 6, users: 0 },
{ hour: 8, users: 0 },
{ hour: 10, users: 0 },
{ hour: 12, users: 5 },
{ hour: 14, users: 0 },
{ hour: 16, users: 0 },
{ hour: 18, users: 0 },
{ hour: 20, users: 0 },
{ hour: 22, users: 0 },
],
success: true,
};
const expectedResult = {
hours: [
{ hour: 0, users: 0 },
{ hour: 2, users: 0 },
{ hour: 4, users: 5 },
{ hour: 6, users: 0 },
{ hour: 8, users: 0 },
{ hour: 10, users: 0 },
{ hour: 12, users: 0 },
{ hour: 14, users: 0 },
{ hour: 16, users: 0 },
{ hour: 18, users: 0 },
{ hour: 20, users: 0 },
{ hour: 22, users: 0 },
],
};
const { result } = renderHook(() => useHourlyChatActivity({ displacement: 0, utc: false }), {
wrapper: mockAppRoot()
.withEndpoint('GET', '/v1/engagement-dashboard/users/chat-busier/hourly-data', () => receivedData)
.build(),
});
await waitFor(() => expect(result.current.isSuccess).toBe(true));
if (!result.current.data) {
throw new Error('Data is undefined');
}
expect(result.current.data.hours.sort((a, b) => a.hour - b.hour)).toEqual(expectedResult.hours);
});

View File

@@ -0,0 +1,51 @@
import { useEndpoint } from '@rocket.chat/ui-contexts';
import { useQuery } from '@tanstack/react-query';
import { endOfDay, subDays } from 'date-fns';
type UseHourlyChatActivityOptions = {
displacement: number;
utc: boolean;
};
function endOfDayUTC(d: Date): Date {
return new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), 23, 59, 59, 999));
}
export const useHourlyChatActivity = ({ displacement, utc }: UseHourlyChatActivityOptions) => {
const getHourlyChatActivity = useEndpoint('GET', '/v1/engagement-dashboard/users/chat-busier/hourly-data');
return useQuery({
queryKey: ['admin/engagement-dashboard/users/hourly-chat-activity', { displacement, utc }],
queryFn: async () => {
const end = utc ? endOfDayUTC(new Date()) : endOfDay(new Date());
const day = subDays(end, displacement);
const response = await getHourlyChatActivity({
start: day.toISOString(),
});
if (!utc && response) {
const dayStart = new Date(day);
dayStart.setHours(0, 0, 0, 0);
response.hours = response.hours.map((hours) => {
const utcDate = new Date(Date.UTC(dayStart.getUTCFullYear(), dayStart.getUTCMonth(), dayStart.getUTCDate(), hours.hour, 0, 0, 0));
return {
hour: utcDate.getHours(),
users: hours.users,
};
});
}
return response
? {
...response,
day,
}
: undefined;
},
refetchInterval: 5 * 60 * 1000,
throwOnError: true,
});
};

View File

@@ -0,0 +1,130 @@
import { mockAppRoot } from '@rocket.chat/mock-providers';
import { renderHook, waitFor } from '@testing-library/react';
import { useNewUsers } from './useNewUsers';
beforeAll(() => {
jest.useFakeTimers().setSystemTime(new Date(2025, 4, 13));
});
afterAll(() => {
jest.useRealTimers();
});
it('should return utc time', async () => {
const expectedResult = {
days: [
{
day: 'Monday',
users: 15,
},
{
day: 'Tuesday',
users: 10,
},
{
day: 'Wednesday',
users: 5,
},
{
day: 'Thursday',
users: 0,
},
{
day: 'Friday',
users: 0,
},
{
day: 'Saturday',
users: 0,
},
{
day: 'Sunday',
users: 0,
},
],
end: new Date('2025-05-13T23:59:59.999Z'),
period: {
count: 15,
variation: 2,
},
start: new Date('2025-05-11T00:00:00.000Z'),
success: true,
yesterday: {
count: 15,
variation: 3,
},
};
const { result } = renderHook(() => useNewUsers({ period: 'this week', utc: true }), {
wrapper: mockAppRoot()
.withEndpoint('GET', '/v1/engagement-dashboard/users/new-users', () => expectedResult)
.build(),
});
await waitFor(() => expect(result.current.isSuccess).toBe(true));
if (!result.current.data) {
throw new Error('Data is undefined');
}
expect(result.current.data).toEqual(expectedResult);
});
// CI is currently running in UTC, so no local time is returned
// TODO: find a way to simulate local time properly in tests
it.skip('should return local time', async () => {
const expectedResult = {
days: [
{
day: 'Monday',
users: 15,
},
{
day: 'Tuesday',
users: 10,
},
{
day: 'Wednesday',
users: 5,
},
{
day: 'Thursday',
users: 0,
},
{
day: 'Friday',
users: 0,
},
{
day: 'Saturday',
users: 0,
},
{
day: 'Sunday',
users: 0,
},
],
end: new Date('2025-05-13T23:59:59.999Z'),
period: {
count: 15,
variation: 2,
},
start: new Date('2025-05-11T00:00:00.000Z'),
success: true,
yesterday: {
count: 15,
variation: 3,
},
};
const { result } = renderHook(() => useNewUsers({ period: 'this week', utc: false }), {
wrapper: mockAppRoot()
.withEndpoint('GET', '/v1/engagement-dashboard/users/new-users', () => expectedResult)
.build(),
});
await waitFor(() => expect(result.current.isSuccess).toBe(true));
if (!result.current.data) {
throw new Error('Data is undefined');
}
expect(result.current.data).toEqual(expectedResult);
});

View File

@@ -0,0 +1,33 @@
import { useEndpoint } from '@rocket.chat/ui-contexts';
import { useQuery } from '@tanstack/react-query';
import type { Period } from '../../../../components/dashboards/periods';
import { getPeriodRange } from '../../../../components/dashboards/periods';
export const useNewUsers = ({ period, utc }: { period: Period['key']; utc: boolean }) => {
const getNewUsers = useEndpoint('GET', '/v1/engagement-dashboard/users/new-users');
return useQuery({
queryKey: ['admin/engagement-dashboard/users/new', { period, utc }],
queryFn: async () => {
const { start, end } = getPeriodRange(period, utc);
const response = await getNewUsers({
start: start.toISOString(),
end: end.toISOString(),
});
return response
? {
...response,
start,
end,
}
: undefined;
},
refetchInterval: 5 * 60 * 1000,
throwOnError: true,
});
};

View File

@@ -0,0 +1,35 @@
import { useEndpoint } from '@rocket.chat/ui-contexts';
import { useQuery } from '@tanstack/react-query';
import type { Period } from '../../../../components/dashboards/periods';
import { getPeriodRange } from '../../../../components/dashboards/periods';
type UseUsersByTimeOfTheDayOptions = { period: Period['key']; utc: boolean };
export const useUsersByTimeOfTheDay = ({ period, utc }: UseUsersByTimeOfTheDayOptions) => {
const getUsersByTimeOfTheDay = useEndpoint('GET', '/v1/engagement-dashboard/users/users-by-time-of-the-day-in-a-week');
return useQuery({
queryKey: ['admin/engagement-dashboard/users/users-by-time-of-the-day', { period, utc }],
queryFn: async () => {
const { start, end } = getPeriodRange(period, utc);
const response = await getUsersByTimeOfTheDay({
start: start.toISOString(),
end: end.toISOString(),
});
return response
? {
...response,
start,
end,
}
: undefined;
},
refetchInterval: 5 * 60 * 1000,
throwOnError: true,
});
};

View File

@@ -0,0 +1,39 @@
import { useEndpoint } from '@rocket.chat/ui-contexts';
import { useQuery } from '@tanstack/react-query';
import { endOfDay, subWeeks } from 'date-fns';
type UseWeeklyChatActivityOptions = {
displacement: number;
utc: boolean;
};
function endOfDayUTC(d: Date): Date {
return new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), 23, 59, 59, 999));
}
export const useWeeklyChatActivity = ({ displacement, utc }: UseWeeklyChatActivityOptions) => {
const getWeeklyChatActivity = useEndpoint('GET', '/v1/engagement-dashboard/users/chat-busier/weekly-data');
return useQuery({
queryKey: ['admin/engagement-dashboard/users/weekly-chat-activity', { displacement, utc }],
queryFn: async () => {
const end = utc ? endOfDayUTC(new Date()) : endOfDay(new Date());
const day = subWeeks(end, displacement);
const response = await getWeeklyChatActivity({
start: day.toISOString(),
});
return response
? {
...response,
day,
}
: undefined;
},
refetchInterval: 5 * 60 * 1000,
throwOnError: true,
});
};