Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Completed sessions count #1986

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import React, {useEffect, useState} from 'react';
import {useTranslation} from 'react-i18next';
import styled from 'styled-components/native';
import {COLORS} from '../../../../../shared/src/constants/colors';
import {Collection} from '../../../../../shared/src/types/generated/Collection';
import {HKGroteskBold, HKGroteskRegular} from '../../constants/fonts';
import useCompletedSessionsCount from '../../sessions/hooks/useCompletedSessionsCount';
import {Spacer4} from '../Spacers/Spacer';
import {Body12} from '../Typography/Body/Body';

const Footer = styled.View({
flexDirection: 'row',
justifyContent: 'flex-start',
alignItems: 'baseline',
});

const NumberText = styled(Body12)({
fontFamily: HKGroteskBold,
});

const FooterText = styled.Text.attrs({allowFontScaling: false})({
color: COLORS.BLACK,
fontSize: 10,
lineHeight: 14,
fontFamily: HKGroteskRegular,
});

type CompletedSessionsCountProps = {
collection: Collection | null;
emptyComponent?: React.ReactNode;
};

export const CompletedSessionsCount: React.FC<CompletedSessionsCountProps> = ({
collection,
emptyComponent,
}) => {
const {t} = useTranslation('Component.CompletedSessionsCount');
const {getCompletedSessionsCountByCollection} = useCompletedSessionsCount();
const [completedSessionsCount, setCompletedSessionsCount] = useState(0); // TODO: get this from some storage

useEffect(() => {
if (collection) {
setCompletedSessionsCount(
getCompletedSessionsCountByCollection(collection),
);
}
}, [
collection,
setCompletedSessionsCount,
getCompletedSessionsCountByCollection,
]);

if (!completedSessionsCount) {
if (emptyComponent) {
return <>{emptyComponent}</>;
}
return null;
}

return (
<Footer>
<NumberText>{completedSessionsCount}</NumberText>
<Spacer4 />
<FooterText>{t('text')}</FooterText>
</Footer>
);
};

export default React.memo(CompletedSessionsCount);
21 changes: 21 additions & 0 deletions client/src/lib/sessions/api/sessionsCount.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import {CompletedSessionsCount} from '../../../../../shared/src/types/CompletedSessions';
import apiClient from '../../apiClient/apiClient';

const SESSIONS_COUNT_ENDPOINT = '/sessionsCount';

export const fetchCompletedSessionsCount = async (): Promise<
Array<CompletedSessionsCount>
> => {
try {
const response = await apiClient(SESSIONS_COUNT_ENDPOINT);
if (!response.ok) {
throw new Error(await response.text());
}

return response.json();
} catch (cause) {
console.log(cause);

throw new Error('Could not fetch completed sessions count', {cause});
}
};
106 changes: 106 additions & 0 deletions client/src/lib/sessions/hooks/useCompletedSessionsCount.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import {act, renderHook} from '@testing-library/react-hooks';
import fetchMock, {enableFetchMocks} from 'jest-fetch-mock';
import {Collection} from '../../../../../shared/src/types/generated/Collection';
import useSessionsState from '../state/state';
import useCompletedSessionsCount from './useCompletedSessionsCount';

enableFetchMocks();

afterEach(() => {
fetchMock.resetMocks();
jest.clearAllMocks();
});

describe('useCompletedSessionsCount', () => {
const useTestHook = () => {
const {
getCompletedSessionsCountByCollection,
getCompletedSessionsCountByExerciseId,
} = useCompletedSessionsCount();

return {
getCompletedSessionsCountByCollection,
getCompletedSessionsCountByExerciseId,
};
};

it('should load completed sessions count', async () => {
useSessionsState.setState({
completedSessionsCount: null,
});
fetchMock.mockResponseOnce(
JSON.stringify([{exerciseId: 'some-exercise-id', publicCount: 1}]),
{status: 200},
);

await act(async () => {
renderHook(() => useTestHook());
});

expect(fetchMock).toHaveBeenCalledTimes(1);
});

describe('getCompletedSessionsCountByExerciseId', () => {
it('should sum the counts for an exercise', async () => {
useSessionsState.setState({
completedSessionsCount: [
{
exerciseId: 'some-exercise-id',
asyncCount: 0,
privateCount: 1,
publicCount: 2,
},
{
exerciseId: 'some-other-exercise-id',
asyncCount: 0,
privateCount: 1,
publicCount: 2,
},
],
});

const {result} = renderHook(() => useTestHook());

expect(
result.current.getCompletedSessionsCountByExerciseId(
'some-exercise-id',
),
).toEqual(3);
});
});

describe('getCompletedSessionsCountByCollection', () => {
it('should sum the counts for a collection', async () => {
useSessionsState.setState({
completedSessionsCount: [
{
exerciseId: 'some-exercise-id',
asyncCount: 0,
privateCount: 1,
publicCount: 2,
},
{
exerciseId: 'some-other-exercise-id',
asyncCount: 0,
privateCount: 1,
publicCount: 2,
},
{
exerciseId: 'some-third-exercise-id',
asyncCount: 0,
privateCount: 1,
publicCount: 2,
},
],
});

const {result} = renderHook(() => useTestHook());

expect(
result.current.getCompletedSessionsCountByCollection({
exercises: ['some-exercise-id', 'some-other-exercise-id'],
} as Collection),
).toEqual(6);
});
});
});
56 changes: 56 additions & 0 deletions client/src/lib/sessions/hooks/useCompletedSessionsCount.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import {useCallback, useEffect} from 'react';
import {Collection} from '../../../../../shared/src/types/generated/Collection';
import * as sessionsCountApi from '../api/sessionsCount';
import useSessionsState from '../state/state';

const useCompletedSessionsCount = () => {
const setCompletedSessionsCount = useSessionsState(
state => state.setCompletedSessionsCount,
);
const completedSessionsCount = useSessionsState(
state => state.completedSessionsCount,
);

const fetchCompletedSessionsCount = useCallback(async () => {
setCompletedSessionsCount(
await sessionsCountApi.fetchCompletedSessionsCount(),
);
}, [setCompletedSessionsCount]);

useEffect(() => {
if (completedSessionsCount === null) {
fetchCompletedSessionsCount();
}
}, [completedSessionsCount, fetchCompletedSessionsCount]);

const getCompletedSessionsCountByExerciseId = useCallback(
(exerciseId: string) => {
return completedSessionsCount
?.filter(cs => cs.exerciseId === exerciseId)
.reduce(
(sum, count) =>
sum + count.asyncCount + count.privateCount + count.publicCount,
0,
);
},
[completedSessionsCount],
);

const getCompletedSessionsCountByCollection = useCallback(
(collection: Collection) => {
return collection.exercises.reduce(
(sum, exerciseId) =>
sum + getCompletedSessionsCountByExerciseId(exerciseId),
0,
);
},
[getCompletedSessionsCountByExerciseId],
);

return {
getCompletedSessionsCountByExerciseId,
getCompletedSessionsCountByCollection,
};
};

export default useCompletedSessionsCount;
8 changes: 8 additions & 0 deletions client/src/lib/sessions/state/state.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,34 @@
import {LiveSession} from '../../../../../shared/src/types/Session';
import {create} from 'zustand';
import {CompletedSessionsCount} from '../../../../../shared/src/types/CompletedSessions';

type State = {
isLoading: boolean;
sessions: LiveSession[] | null;
completedSessionsCount: CompletedSessionsCount[] | null;
};

type Actions = {
setIsLoading: (isLoading: State['isLoading']) => void;
setSessions: (sessions: State['sessions']) => void;
setCompletedSessionsCount: (
completedSessionsCount: State['completedSessionsCount'],
) => void;
reset: () => void;
};

const initialState: State = {
isLoading: false,
sessions: null,
completedSessionsCount: null,
};

const useSessionsState = create<State & Actions>()(set => ({
...initialState,
setIsLoading: isLoading => set({isLoading}),
setSessions: sessions => set({sessions}),
setCompletedSessionsCount: completedSessionsCount =>
set({completedSessionsCount}),
reset: () => set(initialState),
}));

Expand Down
8 changes: 8 additions & 0 deletions content/src/ui/Component.CompletedSessionsCount.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"en": {
"text": "maningful sessions this month"
},
"pt": {},
"sv": {},
"es": {}
}
2 changes: 2 additions & 0 deletions functions/src/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import Koa from 'koa';

import {killSwitchRouter} from './killswitch';
import {sessionsRouter} from './sessions';
import {sessionsCountRouter} from './sessionsCount';
import {userRouter} from './user';
import {postsRouter} from './posts';
import sentryErrorHandler from '../lib/sentry';
Expand All @@ -20,6 +21,7 @@ app.on('error', localErrorHandler);
const rootRouter = createApiRouter();
rootRouter
.use('/sessions', sessionsRouter.routes())
.use('/sessionsCount', sessionsCountRouter.routes())
.use('/killSwitch', killSwitchRouter.routes())
.use('/user', userRouter.routes())
.use('/posts', postsRouter.routes());
Expand Down
60 changes: 60 additions & 0 deletions functions/src/api/sessionsCount/index.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import request from 'supertest';
import Koa from 'koa';

import {sessionsCountRouter} from '.';
import {createApiRouter} from '../../lib/routers';
import createMockServer from '../lib/createMockServer';
import * as sessionsController from '../../controllers/sessions';
import {CompletedSessionsCount} from '../../../../shared/src/types/CompletedSessions';

jest.mock('../../controllers/sessions');

const mockGetCompletedSessionsCount = jest.mocked(
sessionsController.getCompletedSessionsCount,
);

const getMockCustomClaims = jest.fn();
const router = createApiRouter();
router.use('/completedSessionsCount', sessionsCountRouter.routes());
const mockServer = createMockServer(
async (ctx: Koa.Context, next: Koa.Next) => {
ctx.user = {
id: 'some-user-id',
customClaims: getMockCustomClaims(),
};
await next();
},
router.routes(),
router.allowedMethods(),
);

beforeEach(async () => {
jest.clearAllMocks();
});

afterAll(() => {
mockServer.close();
});

describe('/completedSessionsCount', () => {
it('should return completed sessions count', async () => {
mockGetCompletedSessionsCount.mockResolvedValueOnce([
{
exerciseId: 'some-exercise-id',
publicCount: 1,
} as CompletedSessionsCount,
]);

const response = await request(mockServer).get('/completedSessionsCount');

expect(mockGetCompletedSessionsCount).toHaveBeenCalledTimes(1);
expect(response.status).toEqual(200);
expect(response.headers).toMatchObject({'cache-control': 'max-age=1800'});
expect(response.body).toEqual([
{
exerciseId: 'some-exercise-id',
publicCount: 1,
},
]);
});
});
15 changes: 15 additions & 0 deletions functions/src/api/sessionsCount/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import {createApiRouter} from '../../lib/routers';
import * as sessionsController from '../../controllers/sessions';

const sessionsCountRouter = createApiRouter();

sessionsCountRouter.get('/', async ctx => {
const completedSessionsCount =
await sessionsController.getCompletedSessionsCount();

ctx.set('Cache-Control', 'max-age=1800');
ctx.status = 200;
ctx.body = completedSessionsCount;
});

export {sessionsCountRouter};
Loading