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,24 @@
import { Box, Card, CardTitle, CardBody } from '@rocket.chat/fuselage';
import type { ReactNode } from 'react';
import EngagementDashboardCardErrorBoundary from './EngagementDashboardCardErrorBoundary';
export type EngagementDashboardCardProps = {
children?: ReactNode;
title?: string;
};
const EngagementDashboardCard = ({ children, title = undefined }: EngagementDashboardCardProps) => (
<Box marginBlock={16}>
<Card>
{title && <CardTitle>{title}</CardTitle>}
<CardBody>
<EngagementDashboardCardErrorBoundary>
<Box width='full'>{children}</Box>
</EngagementDashboardCardErrorBoundary>
</CardBody>
</Card>
</Box>
);
export default EngagementDashboardCard;

View File

@@ -0,0 +1,47 @@
import { States, StatesAction, StatesActions, StatesIcon, StatesSubtitle, StatesTitle } from '@rocket.chat/fuselage';
import { QueryErrorResetBoundary } from '@tanstack/react-query';
import type { ReactNode } from 'react';
import { useState } from 'react';
import { ErrorBoundary } from 'react-error-boundary';
import { useTranslation } from 'react-i18next';
export type EngagementDashboardCardErrorBoundaryProps = {
children?: ReactNode;
};
const EngagementDashboardCardErrorBoundary = ({ children }: EngagementDashboardCardErrorBoundaryProps) => {
const { t } = useTranslation();
const [error, setError] = useState<unknown>(null);
const isError = (error: unknown): error is Error => error instanceof Error;
const errorHandler = (error: unknown, info: { componentStack?: string | null }): void => {
setError(error);
console.error('Uncaught Error:', error, info);
};
return (
<QueryErrorResetBoundary>
{({ reset }) => (
<ErrorBoundary
onError={errorHandler}
onReset={reset}
fallbackRender={({ resetErrorBoundary }) => (
<States>
<StatesIcon name='circle-exclamation' />
<StatesTitle>{t('Something_went_wrong')}</StatesTitle>
<StatesSubtitle>{isError(error) && error?.message}</StatesSubtitle>
<StatesActions>
<StatesAction onClick={(): void => resetErrorBoundary()}>{t('Retry')}</StatesAction>
</StatesActions>
</States>
)}
>
{children}
</ErrorBoundary>
)}
</QueryErrorResetBoundary>
);
};
export default EngagementDashboardCardErrorBoundary;

View File

@@ -0,0 +1,14 @@
import { Box, FlexItem, InputBoxSkeleton } from '@rocket.chat/fuselage';
import type { ReactNode } from 'react';
export type EngagementDashboardCardFilterProps = {
children?: ReactNode;
};
const EngagementDashboardCardFilter = ({ children = <InputBoxSkeleton /> }: EngagementDashboardCardFilterProps) => (
<Box rcx-card__row display='flex' justifyContent='flex-end' alignItems='center' wrap='no-wrap' paddingBlockEnd={8}>
{children && <FlexItem grow={0}>{children}</FlexItem>}
</Box>
);
export default EngagementDashboardCardFilter;

View File

@@ -0,0 +1,13 @@
import type { StoryObj, Meta } from '@storybook/react';
import EngagementDashboardPage from './EngagementDashboardPage';
export default {
component: EngagementDashboardPage,
decorators: [(fn) => <div style={{ height: '100vh' }}>{fn()}</div>],
} satisfies Meta<typeof EngagementDashboardPage>;
export const Default: StoryObj<typeof EngagementDashboardPage> = {
render: () => <EngagementDashboardPage tab='users' />,
name: 'EngagementDashboardPage',
};

View File

@@ -0,0 +1,66 @@
import { Box, Select, Tabs, TabsItem } from '@rocket.chat/fuselage';
import { PageScrollableContent, Page, PageHeader } from '@rocket.chat/ui-client';
import { useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import ChannelsTab from './channels/ChannelsTab';
import MessagesTab from './messages/MessagesTab';
import UsersTab from './users/UsersTab';
export type EngagementDashboardPageProps = {
tab: 'users' | 'messages' | 'channels';
onSelectTab?: (tab: 'users' | 'messages' | 'channels') => void;
};
const EngagementDashboardPage = ({ tab = 'users', onSelectTab }: EngagementDashboardPageProps) => {
const { t } = useTranslation();
const timezoneOptions = useMemo<[timezone: 'utc' | 'local', label: string][]>(
() => [
['utc', t('UTC_Timezone')],
['local', t('Local_Timezone')],
],
[t],
);
const [timezoneId, setTimezoneId] = useState<'utc' | 'local'>('utc');
const handleTimezoneChange = (timezoneId: string): void => setTimezoneId(timezoneId as 'utc' | 'local');
const handleTabClick = useCallback(
(tab: 'users' | 'messages' | 'channels'): undefined | (() => void) => (onSelectTab ? (): void => onSelectTab(tab) : undefined),
[onSelectTab],
);
return (
<Page background='tint'>
<PageHeader title={t('Engagement')}>
<Select
options={timezoneOptions}
value={timezoneId}
onChange={(value) => handleTimezoneChange(String(value))}
aria-label={t('Default_Timezone_For_Reporting')}
/>
</PageHeader>
<Tabs>
<TabsItem selected={tab === 'users'} onClick={handleTabClick('users')}>
{t('Users')}
</TabsItem>
<TabsItem selected={tab === 'messages'} onClick={handleTabClick('messages')}>
{t('Messages')}
</TabsItem>
<TabsItem selected={tab === 'channels'} onClick={handleTabClick('channels')}>
{t('Channels')}
</TabsItem>
</Tabs>
<PageScrollableContent padding={0}>
<Box margin={24}>
{(tab === 'users' && <UsersTab timezone={timezoneId} />) ||
(tab === 'messages' && <MessagesTab timezone={timezoneId} />) ||
(tab === 'channels' && <ChannelsTab />)}
</Box>
</PageScrollableContent>
</Page>
);
};
export default EngagementDashboardPage;

View File

@@ -0,0 +1,137 @@
import { mockAppRoot } from '@rocket.chat/mock-providers';
import type { RouterContextValue } from '@rocket.chat/ui-contexts';
import { render } from '@testing-library/react';
import EngagementDashboardRoute from './EngagementDashboardRoute';
import { useUpsellActions } from '../../../components/GenericUpsellModal/hooks';
import { useHasLicenseModule } from '../../../hooks/useHasLicenseModule';
jest.mock('../../../hooks/useHasLicenseModule', () => ({ useHasLicenseModule: jest.fn() }));
jest.mock('../../../components/GenericUpsellModal/hooks', () => ({ useUpsellActions: jest.fn() }));
jest.mock('./EngagementDashboardPage', () => () => null);
jest.mock('../../../components/PageSkeleton', () => () => null);
jest.mock('../../notAuthorized/NotAuthorizedPage', () => () => null);
jest.mock('../../../../client/lib/getURL', () => ({ getURL: (path: string) => path }));
const buildWrapper = (router: Partial<RouterContextValue>, tab?: string) => {
const builder = mockAppRoot()
.withPermission('view-engagement-dashboard')
.withEndpoint('POST', '/v1/statistics.telemetry', () => ({}))
.withRouter(router);
if (tab) {
builder.withRouteParameter('tab', tab);
}
return builder.build();
};
const createSubscribeTracker = () => {
const unsubscribes: jest.Mock[] = [];
const subscribeToRouteChange = jest.fn((_cb: () => void) => {
const unsub = jest.fn();
unsubscribes.push(unsub);
return unsub;
});
const allUnsubscribed = () => unsubscribes.length > 0 && unsubscribes.every((u) => u.mock.calls.length > 0);
const noneUnsubscribed = () => unsubscribes.every((u) => u.mock.calls.length === 0);
const getLastRouteChangeCallback = () => {
const callback = subscribeToRouteChange.mock.calls.at(-1)?.[0];
expect(callback).toBeDefined();
return callback as () => void;
};
return { subscribeToRouteChange, allUnsubscribed, noneUnsubscribed, getLastRouteChangeCallback };
};
beforeEach(() => {
jest.clearAllMocks();
jest.mocked(useHasLicenseModule).mockReturnValue({
isPending: false,
data: true,
} as unknown as ReturnType<typeof useHasLicenseModule>);
jest.mocked(useUpsellActions).mockReturnValue({
shouldShowUpsell: false,
cloudWorkspaceHadTrial: false,
handleManageSubscription: jest.fn(),
handleTalkToSales: jest.fn(),
});
});
describe('EngagementDashboardRoute', () => {
it('subscribes to route changes on mount', () => {
const { subscribeToRouteChange } = createSubscribeTracker();
render(<EngagementDashboardRoute />, {
wrapper: buildWrapper({ subscribeToRouteChange }, 'users'),
});
expect(subscribeToRouteChange).toHaveBeenCalled();
});
it('unsubscribes all listeners on unmount', () => {
const { subscribeToRouteChange, allUnsubscribed } = createSubscribeTracker();
const { unmount } = render(<EngagementDashboardRoute />, {
wrapper: buildWrapper({ subscribeToRouteChange }, 'users'),
});
unmount();
expect(allUnsubscribed()).toBe(true);
});
it('does not redirect when the tab is valid', () => {
const navigate = jest.fn();
const { subscribeToRouteChange, getLastRouteChangeCallback } = createSubscribeTracker();
render(<EngagementDashboardRoute />, {
wrapper: buildWrapper({ subscribeToRouteChange, navigate }, 'users'),
});
const routeChangeCallback = getLastRouteChangeCallback();
routeChangeCallback();
expect(navigate).not.toHaveBeenCalled();
});
it('redirects to the users tab when the tab is invalid', () => {
const navigate = jest.fn();
const { subscribeToRouteChange, getLastRouteChangeCallback } = createSubscribeTracker();
render(<EngagementDashboardRoute />, {
wrapper: buildWrapper({ subscribeToRouteChange, navigate }),
});
const routeChangeCallback = getLastRouteChangeCallback();
routeChangeCallback();
expect(navigate).toHaveBeenCalledWith({ pattern: '/admin/engagement/:tab?', params: { tab: 'users' } }, { replace: true });
});
it('cleans up all subscriptions on unmount and resubscribes on remount', () => {
const first = createSubscribeTracker();
const { unmount } = render(<EngagementDashboardRoute />, {
wrapper: buildWrapper({ subscribeToRouteChange: first.subscribeToRouteChange }, 'users'),
});
expect(first.subscribeToRouteChange).toHaveBeenCalled();
unmount();
expect(first.allUnsubscribed()).toBe(true);
const second = createSubscribeTracker();
render(<EngagementDashboardRoute />, {
wrapper: buildWrapper({ subscribeToRouteChange: second.subscribeToRouteChange }, 'messages'),
});
expect(second.subscribeToRouteChange).toHaveBeenCalled();
expect(second.noneUnsubscribed()).toBe(true);
});
});

View File

@@ -0,0 +1,93 @@
import {
usePermission,
useRouter,
useSetModal,
useCurrentModal,
useTranslation,
useRouteParameter,
useEndpoint,
} from '@rocket.chat/ui-contexts';
import { useEffect } from 'react';
import EngagementDashboardPage from './EngagementDashboardPage';
import GenericUpsellModal from '../../../components/GenericUpsellModal';
import { useUpsellActions } from '../../../components/GenericUpsellModal/hooks';
import PageSkeleton from '../../../components/PageSkeleton';
import { useHasLicenseModule } from '../../../hooks/useHasLicenseModule';
import { getURL } from '../../../lib/getURL';
import NotAuthorizedPage from '../../notAuthorized/NotAuthorizedPage';
const isValidTab = (tab: string | undefined): tab is 'users' | 'messages' | 'channels' =>
typeof tab === 'string' && ['users', 'messages', 'channels'].includes(tab);
const EngagementDashboardRoute = () => {
const t = useTranslation();
const canViewEngagementDashboard = usePermission('view-engagement-dashboard');
const setModal = useSetModal();
const isModalOpen = !!useCurrentModal();
const router = useRouter();
const tab = useRouteParameter('tab');
const eventStats = useEndpoint('POST', '/v1/statistics.telemetry');
const { isPending, data: hasEngagementDashboard = false } = useHasLicenseModule('engagement-dashboard');
const { shouldShowUpsell, handleManageSubscription } = useUpsellActions(hasEngagementDashboard);
useEffect(() => {
if (shouldShowUpsell) {
setModal(
<GenericUpsellModal
aria-label={t('Engagement_Dashboard')}
title={t('Engagement_Dashboard')}
img={getURL('images/engagement.png')}
subtitle={t('Analyze_practical_usage')}
description={t('Enrich_your_workspace')}
onClose={() => setModal(null)}
onConfirm={handleManageSubscription}
onCancel={() => setModal(null)}
/>,
);
}
}, [shouldShowUpsell, setModal, t, handleManageSubscription]);
useEffect(() => {
return router.subscribeToRouteChange(() => {
if (!isValidTab(tab)) {
router.navigate(
{
pattern: '/admin/engagement/:tab?',
params: { tab: 'users' },
},
{ replace: true },
);
}
});
}, [router, tab]);
if (isModalOpen || isPending) {
return <PageSkeleton />;
}
if (!canViewEngagementDashboard || !hasEngagementDashboard) {
return <NotAuthorizedPage />;
}
eventStats({
params: [{ eventName: 'updateCounter', settingsId: 'Engagement_Dashboard_Load_Count' }],
});
return (
<EngagementDashboardPage
tab={tab as 'users' | 'messages' | 'channels'}
onSelectTab={(tab) =>
router.navigate({
pattern: '/admin/engagement/:tab?',
params: { tab },
})
}
/>
);
};
export default EngagementDashboardRoute;

View File

@@ -0,0 +1,134 @@
import { Icon, Margins, Pagination, Skeleton, Table, TableBody, TableCell, TableHead, TableRow, Tile } from '@rocket.chat/fuselage';
import { format } from 'date-fns';
import { useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useChannelsList } from './useChannelsList';
import DownloadDataButton from '../../../../components/dashboards/DownloadDataButton';
import PeriodSelector from '../../../../components/dashboards/PeriodSelector';
import { usePeriodSelectorState } from '../../../../components/dashboards/usePeriodSelectorState';
import Growth from '../../../../components/dataView/Growth';
import EngagementDashboardCardFilter from '../EngagementDashboardCardFilter';
const ChannelsOverview = () => {
const [period, periodSelectorProps] = usePeriodSelectorState('last 7 days', 'last 30 days', 'last 90 days');
const { t } = useTranslation();
const [current, setCurrent] = useState(0);
const [itemsPerPage, setItemsPerPage] = useState<25 | 50 | 100>(25);
const { data } = useChannelsList({
period,
offset: current,
count: itemsPerPage,
});
const channels = useMemo(() => {
if (!data) {
return;
}
return data?.channels?.map(({ room: { t, name, usernames, ts, _updatedAt }, messages, diffFromLastWeek }) => ({
t,
name: name || usernames?.join(' × '),
createdAt: ts,
updatedAt: _updatedAt,
messagesCount: messages,
messagesVariation: diffFromLastWeek,
}));
}, [data]);
return (
<>
<EngagementDashboardCardFilter>
<PeriodSelector {...periodSelectorProps} />
<DownloadDataButton
attachmentName={`Channels_start_${data?.start}_end_${data?.end}`}
headers={['Room type', 'Name', 'Messages', 'Last Update Date', 'Creation Date']}
dataAvailable={!!data}
dataExtractor={(): unknown[][] | undefined =>
data?.channels?.map(({ room: { t, name, usernames, ts, _updatedAt }, messages }) => [
t,
name || usernames?.join(' × '),
messages,
_updatedAt,
ts,
])
}
/>
</EngagementDashboardCardFilter>
<div>
{channels && !channels.length && (
<Tile fontScale='p1' color='hint' style={{ textAlign: 'center' }}>
{t('No_data_found')}
</Tile>
)}
{(!channels || channels.length) && (
<Table>
<TableHead>
<TableRow>
<TableCell>#</TableCell>
<TableCell>{t('Channel')}</TableCell>
<TableCell>{t('Created')}</TableCell>
<TableCell>{t('Last_active')}</TableCell>
<TableCell>{t('Messages_sent')}</TableCell>
</TableRow>
</TableHead>
<TableBody>
{channels?.map(({ t, name, createdAt, updatedAt, messagesCount, messagesVariation }, i) => (
<TableRow key={i}>
<TableCell>{i + 1}.</TableCell>
<TableCell>
<Margins inlineEnd={4}>
{(t === 'd' && <Icon name='at' />) || (t === 'p' && <Icon name='lock' />) || (t === 'c' && <Icon name='hashtag' />)}
</Margins>
{name}
</TableCell>
<TableCell>{format(new Date(createdAt ?? new Date()), 'P')}</TableCell>
<TableCell>{format(new Date(updatedAt ?? new Date()), 'P')}</TableCell>
<TableCell>
{messagesCount} <Growth>{messagesVariation}</Growth>
</TableCell>
</TableRow>
))}
{!channels &&
Array.from({ length: 5 }, (_, i) => (
<TableRow key={i}>
<TableCell>
<Skeleton width='100%' />
</TableCell>
<TableCell>
<Skeleton width='100%' />
</TableCell>
<TableCell>
<Skeleton width='100%' />
</TableCell>
<TableCell>
<Skeleton width='100%' />
</TableCell>
<TableCell>
<Skeleton width='100%' />
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
<Pagination
current={current}
itemsPerPage={itemsPerPage}
itemsPerPageLabel={(): string => t('Items_per_page:')}
showingResultsLabel={({ count, current, itemsPerPage }): string =>
t('Showing_results_of', { from: current + 1, to: Math.min(current + itemsPerPage, count), total: count })
}
count={data?.total || 0}
onSetItemsPerPage={setItemsPerPage}
onSetCurrent={setCurrent}
/>
</div>
</>
);
};
export default ChannelsOverview;

View File

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

View File

@@ -0,0 +1,10 @@
import EngagementDashboardCard from '../EngagementDashboardCard';
import ChannelsOverview from './ChannelsOverview';
const ChannelsTab = () => (
<EngagementDashboardCard>
<ChannelsOverview />
</EngagementDashboardCard>
);
export default ChannelsTab;

View File

@@ -0,0 +1,42 @@
import { useEndpoint } from '@rocket.chat/ui-contexts';
import { keepPreviousData, useQuery } from '@tanstack/react-query';
import type { Period } from '../../../../components/dashboards/periods';
import { getPeriodRange } from '../../../../components/dashboards/periods';
type UseChannelsListOptions = {
period: Period['key'];
offset: number;
count: number;
};
export const useChannelsList = ({ period, offset, count }: UseChannelsListOptions) => {
const getChannelsList = useEndpoint('GET', '/v1/engagement-dashboard/channels/list');
return useQuery({
queryKey: ['admin/engagement-dashboard/channels/list', { period, offset, count }],
queryFn: async () => {
const { start, end } = getPeriodRange(period);
const response = await getChannelsList({
start: start.toISOString(),
end: end.toISOString(),
offset,
count,
});
return response
? {
...response,
start,
end,
}
: undefined;
},
placeholderData: keepPreviousData,
refetchInterval: 5 * 60 * 1000,
throwOnError: true,
});
};

View File

@@ -0,0 +1,32 @@
import { Box, Margins } from '@rocket.chat/fuselage';
import type { Meta, StoryFn } from '@storybook/react';
import LegendSymbol from './LegendSymbol';
import { monochromaticColors, polychromaticColors } from './colors';
export default {
component: LegendSymbol,
decorators: [(fn) => <Margins all='x16'>{fn()}</Margins>],
} satisfies Meta<typeof LegendSymbol>;
export const WithoutColor: StoryFn<typeof LegendSymbol> = () => (
<Box>
<LegendSymbol />
Legend text
</Box>
);
export const WithColor: StoryFn<typeof LegendSymbol> = () => (
<>
{monochromaticColors.map((color) => (
<Box key={color}>
<LegendSymbol color={color} /> {color}
</Box>
))}
{polychromaticColors.map((color) => (
<Box key={color}>
<LegendSymbol color={color} /> {color}
</Box>
))}
</>
);

View File

@@ -0,0 +1,25 @@
import { Box, Margins } from '@rocket.chat/fuselage';
import type { CSSProperties } from 'react';
export type LegendSymbolProps = {
color?: CSSProperties['backgroundColor'];
};
const LegendSymbol = ({ color = 'currentColor' }: LegendSymbolProps) => (
<Margins inlineEnd={8}>
<Box
is='span'
aria-hidden='true'
style={{
display: 'inline-block',
width: 12,
height: 12,
borderRadius: 2,
backgroundColor: color,
verticalAlign: 'baseline',
}}
/>
</Margins>
);
export default LegendSymbol;

View File

@@ -0,0 +1,14 @@
import colors from '@rocket.chat/fuselage-tokens/dist/colors.json';
export const monochromaticColors = [
colors.b100,
colors.b200,
colors.b300,
colors.b400,
colors.b500,
colors.b600,
colors.b700,
colors.b800,
colors.b900,
];
export const polychromaticColors = [colors.y500, colors.g500, colors.b500];

View File

@@ -0,0 +1,232 @@
import { ResponsivePie } from '@nivo/pie';
import {
Box,
FlexContainer,
FlexItem,
Icon,
Margins,
Skeleton,
Table,
Tile,
Palette,
Tooltip,
TableHead,
TableRow,
TableBody,
TableCell,
} from '@rocket.chat/fuselage';
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { useMessageOrigins } from './useMessageOrigins';
import { useTopFivePopularChannels } from './useTopFivePopularChannels';
import DownloadDataButton from '../../../../components/dashboards/DownloadDataButton';
import PeriodSelector from '../../../../components/dashboards/PeriodSelector';
import { usePeriodSelectorState } from '../../../../components/dashboards/usePeriodSelectorState';
import EngagementDashboardCardFilter from '../EngagementDashboardCardFilter';
import LegendSymbol from '../dataView/LegendSymbol';
const colors = {
warning: Palette.statusColor['status-font-on-warning'].toString(),
success: Palette.statusColor['status-font-on-success'].toString(),
info: Palette.statusColor['status-font-on-info'].toString(),
};
const MessagesPerChannelSection = () => {
const [period, periodSelectorProps] = usePeriodSelectorState('last 7 days', 'last 30 days', 'last 90 days');
const { t } = useTranslation();
const { data: messageOriginsData } = useMessageOrigins({ period });
const { data: topFivePopularChannelsData } = useTopFivePopularChannels({ period });
const pie = useMemo(
() => messageOriginsData?.origins?.reduce<{ [roomType: string]: number }>((obj, { messages, t }) => ({ ...obj, [t]: messages }), {}),
[messageOriginsData],
);
const table = useMemo(
() =>
topFivePopularChannelsData?.channels?.reduce<
{
i: number;
t: string;
name?: string;
messages: number;
}[]
>((entries, { t, messages, name, usernames }, i) => [...entries, { i, t, name: name || usernames?.join(' × '), messages }], []),
[topFivePopularChannelsData],
);
return (
<>
<EngagementDashboardCardFilter>
<PeriodSelector {...periodSelectorProps} />
<DownloadDataButton
attachmentName={`MessagesPerChannelSection_start_${messageOriginsData?.start}_end_${messageOriginsData?.end}`}
headers={['Room Type', 'Messages']}
dataAvailable={!!messageOriginsData}
dataExtractor={(): unknown[][] | undefined => messageOriginsData?.origins.map(({ t, messages }) => [t, messages])}
/>
</EngagementDashboardCardFilter>
<FlexContainer>
<Margins inline='neg-x12'>
<Box>
<Margins inline={12}>
<FlexItem grow={1} shrink={0} basis='0'>
<Box>
<FlexContainer alignItems='center' wrap='no-wrap'>
{pie ? (
<Box>
<FlexItem grow={1} shrink={1}>
<Margins inline={24}>
<Box
style={{
position: 'relative',
height: 300,
}}
>
<Box
style={{
position: 'absolute',
width: '100%',
height: '100%',
}}
>
<ResponsivePie
data={[
{
id: 'd',
label: t('Direct_Messages'),
value: pie.d,
color: colors.warning,
},
{
id: 'p',
label: t('Private_Channels'),
value: pie.p,
color: colors.success,
},
{
id: 'c',
label: t('Public_Channels'),
value: pie.c,
color: colors.info,
},
]}
innerRadius={0.6}
colors={[colors.warning, colors.success, colors.info]}
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: 10,
fontStyle: 'normal',
fontWeight: 600,
letterSpacing: '0.2px',
lineHeight: '12px',
},
},
},
}}
tooltip={({ datum }) => <Tooltip>{t('Value_messages', { value: datum.value })}</Tooltip>}
/>
</Box>
</Box>
</Margins>
</FlexItem>
<FlexItem basis='auto'>
<Margins block='neg-x4'>
<Box>
<Margins block={4}>
<Box color='hint' fontScale='p1'>
<LegendSymbol color={colors.warning} />
{t('Private_Chats')}
</Box>
<Box color='hint' fontScale='p1'>
<LegendSymbol color={colors.success} />
{t('Private_Channels')}
</Box>
<Box color='hint' fontScale='p1'>
<LegendSymbol color={colors.info} />
{t('Public_Channels')}
</Box>
</Margins>
</Box>
</Margins>
</FlexItem>
</Box>
) : (
<Skeleton variant='rect' height={300} />
)}
</FlexContainer>
</Box>
</FlexItem>
<FlexItem grow={1} shrink={0} basis='0'>
<Box>
<Margins blockEnd={16}>
{table ? <Box fontScale='p1'>{t('Most_popular_channels_top_5')}</Box> : <Skeleton width='50%' />}
</Margins>
{table && !table.length && (
<Tile fontScale='p1' color='hint' style={{ textAlign: 'center' }}>
{t('Not_enough_data')}
</Tile>
)}
{(!table || !!table.length) && (
<Table>
<TableHead>
<TableRow>
<TableCell>#</TableCell>
<TableCell>{t('Channel')}</TableCell>
<TableCell align='end'>{t('Number_of_messages')}</TableCell>
</TableRow>
</TableHead>
<TableBody>
{table?.map(({ i, t, name, messages }) => (
<TableRow key={i}>
<TableCell>{i + 1}.</TableCell>
<TableCell>
<Margins inlineEnd={4}>
{(t === 'd' && <Icon name='at' />) ||
(t === 'p' && <Icon name='lock' />) ||
(t === 'c' && <Icon name='hashtag' />)}
</Margins>
{name}
</TableCell>
<TableCell align='end'>{messages}</TableCell>
</TableRow>
))}
{!table &&
Array.from({ length: 5 }, (_, i) => (
<TableRow key={i}>
<TableCell>
<Skeleton width='100%' />
</TableCell>
<TableCell>
<Skeleton width='100%' />
</TableCell>
<TableCell align='end'>
<Skeleton width='100%' />
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</Box>
</FlexItem>
</Margins>
</Box>
</Margins>
</FlexContainer>
</>
);
};
export default MessagesPerChannelSection;

View File

@@ -0,0 +1,166 @@
import { ResponsiveBar } from '@nivo/bar';
import { Box, FlexContainer, FlexItem, Skeleton, Palette, 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 EngagementDashboardCardFilter from '../EngagementDashboardCardFilter';
import { useMessagesSent } from './useMessagesSent';
import { useFormatDate } from '../../../../hooks/useFormatDate';
export type MessagesSentSectionProps = {
timezone: 'utc' | 'local';
};
const MessagesSentSection = ({ timezone }: MessagesSentSectionProps) => {
const [period, periodSelectorProps] = usePeriodSelectorState('last 7 days', 'last 30 days', 'last 90 days');
const periodLabel = usePeriodLabel(period);
const { t } = useTranslation();
const utc = timezone === 'utc';
const { data } = useMessagesSent({ period, utc });
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(),
newMessages: 0,
}));
for (const { day, messages } of data.days ?? []) {
const i = differenceInDays(new Date(day), startDate);
if (i >= 0) {
values[i].newMessages += messages;
}
}
return [data.period?.count, data.period?.variation, data.yesterday?.count, data.yesterday?.variation, values];
}, [data]);
return (
<>
<EngagementDashboardCardFilter>
<PeriodSelector {...periodSelectorProps} />
<DownloadDataButton
attachmentName={`MessagesSentSection_start_${data?.start}_end_${data?.end}`}
headers={['Date', 'Messages']}
dataAvailable={!!data}
dataExtractor={(): unknown[][] | undefined => values?.map(({ date, newMessages }) => [date, newMessages])}
/>
</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={['newMessages']}
groupMode='grouped'
padding={0.25}
margin={{
// TODO: Get it from theme
bottom: 50,
left: 20,
top: 20,
}}
colors={[
// TODO: Get it from theme
Palette.statusColor['status-font-on-info'].toString(),
]}
enableLabel={false}
enableGridY={false}
axisTop={null}
axisRight={null}
valueScale={{ type: 'linear' }}
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_messages', { value })}, {formatDate(indexValue)}
</Tooltip>
)}
/>
</Box>
</Box>
</FlexItem>
</Box>
) : (
<Box>
<Skeleton variant='rect' height={240} />
</Box>
)}
</FlexContainer>
</>
);
};
export default MessagesSentSection;

View File

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

View File

@@ -0,0 +1,26 @@
import { useTranslation } from 'react-i18next';
import EngagementDashboardCard from '../EngagementDashboardCard';
import MessagesPerChannelSection from './MessagesPerChannelSection';
import MessagesSentSection from './MessagesSentSection';
export type MessagesTabProps = {
timezone: 'utc' | 'local';
};
const MessagesTab = ({ timezone }: MessagesTabProps) => {
const { t } = useTranslation();
return (
<>
<EngagementDashboardCard title={t('Messages_sent')}>
<MessagesSentSection timezone={timezone} />
</EngagementDashboardCard>
<EngagementDashboardCard title={t('Where_are_the_messages_being_sent?')}>
<MessagesPerChannelSection />
</EngagementDashboardCard>
</>
);
};
export default MessagesTab;

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 UseMessageOriginsOptions = { period: Period['key'] };
export const useMessageOrigins = ({ period }: UseMessageOriginsOptions) => {
const getMessageOrigins = useEndpoint('GET', '/v1/engagement-dashboard/messages/origin');
return useQuery({
queryKey: ['admin/engagement-dashboard/messages/origins', { period }],
queryFn: async () => {
const { start, end } = getPeriodRange(period);
const response = await getMessageOrigins({
start: start.toISOString(),
end: end.toISOString(),
});
return response
? {
...response,
start,
end,
}
: 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 { useMessagesSent } from './useMessagesSent';
beforeAll(() => {
jest.useFakeTimers().setSystemTime(new Date(2025, 4, 13));
});
afterAll(() => {
jest.useRealTimers();
});
it('should return utc time', async () => {
const expectedResult = {
days: [
{
day: 'Monday',
messages: 15,
},
{
day: 'Tuesday',
messages: 10,
},
{
day: 'Wednesday',
messages: 5,
},
{
day: 'Thursday',
messages: 0,
},
{
day: 'Friday',
messages: 0,
},
{
day: 'Saturday',
messages: 0,
},
{
day: 'Sunday',
messages: 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(() => useMessagesSent({ period: 'this week', utc: true }), {
wrapper: mockAppRoot()
.withEndpoint('GET', '/v1/engagement-dashboard/messages/messages-sent', () => 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',
messages: 15,
},
{
day: 'Tuesday',
messages: 10,
},
{
day: 'Wednesday',
messages: 5,
},
{
day: 'Thursday',
messages: 0,
},
{
day: 'Friday',
messages: 0,
},
{
day: 'Saturday',
messages: 0,
},
{
day: 'Sunday',
messages: 0,
},
],
end: new Date('2025-05-14T02:59:59.000Z'),
period: {
count: 15,
variation: 2,
},
start: new Date('2025-05-11T03:00:00.000Z'),
success: true,
yesterday: {
count: 15,
variation: 3,
},
};
const { result } = renderHook(() => useMessagesSent({ period: 'this week', utc: false }), {
wrapper: mockAppRoot()
.withEndpoint('GET', '/v1/engagement-dashboard/messages/messages-sent', () => 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,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 UseMessagesSentOptions = { period: Period['key']; utc: boolean };
export const useMessagesSent = ({ period, utc }: UseMessagesSentOptions) => {
const getMessagesSent = useEndpoint('GET', '/v1/engagement-dashboard/messages/messages-sent');
return useQuery({
queryKey: ['admin/engagement-dashboard/messages/messages-sent', { period, utc }],
queryFn: async () => {
const { start, end } = getPeriodRange(period, utc);
const response = await getMessagesSent({
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 UseTopFivePopularChannelsOptions = { period: Period['key'] };
export const useTopFivePopularChannels = ({ period }: UseTopFivePopularChannelsOptions) => {
const getTopFivePopularChannels = useEndpoint('GET', '/v1/engagement-dashboard/messages/top-five-popular-channels');
return useQuery({
queryKey: ['admin/engagement-dashboard/messages/top-five-popular-channels', { period }],
queryFn: async () => {
const { start, end } = getPeriodRange(period);
const response = await getTopFivePopularChannels({
start: start.toISOString(),
end: end.toISOString(),
});
return response
? {
...response,
start,
end,
}
: undefined;
},
refetchInterval: 5 * 60 * 1000,
throwOnError: true,
});
};

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,
});
};