Skip to content
Merged
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
1 change: 1 addition & 0 deletions public/locales/en/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,7 @@
"routine": "Routine",
"routines": "Routines",
"workoutSession": "Workout session",
"deleteSessionInfo": "This will delete the session as well as all the sets logged in it",
"rir": "RiR",
"restDay": "Rest day",
"confirmRestDay": "Confirm rest day change",
Expand Down
56 changes: 52 additions & 4 deletions src/components/Calendar/Components/CalendarComponent.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ import {
getMeasurementCategories
} from "@/components/Measurements/api/measurements";
import { getNutritionalDiaryEntries } from "@/components/Nutrition/api/nutritionalDiary";
import { getSessions } from "@/components/Routines/api/session";
import { deleteSession, getSessions } from "@/components/Routines/api/session";
import { WorkoutSession } from "@/components/Routines/models/WorkoutSession";
import { getBodyWeightCategory, getWeights } from "@/components/Measurements/api/bodyWeight";
import { TEST_DIARY_ENTRY_1, TEST_DIARY_ENTRY_2 } from "@/tests/nutritionDiaryTestdata";
import { testQueryClient } from "@/tests/queryClient";
Expand All @@ -14,9 +15,9 @@ import {
testBodyWeightCategory
} from "@/tests/weight/testData";
import { testWorkoutSession } from "@/tests/workoutLogsRoutinesTestData";
import { dateToYYYYMMDD } from "@/core/lib/date";
import { dateToLocale, dateToYYYYMMDD } from "@/core/lib/date";
import { QueryClientProvider } from "@tanstack/react-query";
import { fireEvent, render, screen } from "@testing-library/react";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import i18n from "i18next";
import React from "react";
Expand Down Expand Up @@ -250,4 +251,51 @@ describe('CalendarComponent', () => {
filtersetQuery: { "datetime__gte": start, "datetime__lt": end },
});
});
});

test('removes a deleted session from the selected day', async () => {
const session = new WorkoutSession({
...testWorkoutSession,
notes: 'leg day',
datetimeStart: new Date(currentYear, currentMonth, 3, 10, 30),
datetimeEnd: new Date(currentYear, currentMonth, 3, 12, 0),
});
(getSessions as Mock).mockImplementation(() => Promise.resolve([session]));
(deleteSession as Mock).mockImplementation(() => {
(getSessions as Mock).mockImplementation(() => Promise.resolve([]));
return Promise.resolve(204);
});

renderComponent();
const day = await screen.findByTestId(`day-${dateToYYYYMMDD(new Date(currentYear, currentMonth, 3))}`);
await user.click(day);
expect(await screen.findByText(/leg day/)).toBeInTheDocument();

await user.click(screen.getByRole('button', { name: 'delete' }));
await user.click(screen.getByRole('button', { name: 'delete' }));

expect(deleteSession).toHaveBeenCalledWith(session.id);
await waitFor(() => expect(screen.queryByText(/leg day/)).not.toBeInTheDocument());
// The selection stays on the day the session was deleted from
expect(screen.getByText(dateToLocale(new Date(currentYear, currentMonth, 3)), { exact: false })).toBeInTheDocument();
});

test('changing the month moves the selection along', async () => {
(getWeights as Mock).mockImplementation(() => Promise.resolve([
makeWeightEntry(new Date(currentYear, currentMonth, 15, 12, 0), 70),
]));

renderComponent();
expect(await screen.findByText('70.0 server.kg')).toBeInTheDocument();

// Another month shows its first day, not today without its entries
await user.click(screen.getByText('<'));
expect(await screen.findByText(dateToLocale(new Date(currentYear, currentMonth - 1, 1)), { exact: false })).toBeInTheDocument();
expect(screen.queryByText('70.0 server.kg')).not.toBeInTheDocument();

// Back in the current month, today is selected again
await user.click(screen.getByText('>'));
expect(await screen.findByText(dateToLocale(today), { exact: false })).toBeInTheDocument();
expect(await screen.findByText('70.0 server.kg')).toBeInTheDocument();
});
});

66 changes: 26 additions & 40 deletions src/components/Calendar/Components/CalendarComponent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { isSameDay } from "@/core/lib/date";
import { LoadingPlaceholder } from "@/core/ui/LoadingWidget/LoadingWidget";
import CalendarMonthIcon from '@mui/icons-material/CalendarMonth';
import { Box, Card, CardContent, CardHeader, useMediaQuery, useTheme } from '@mui/material';
import React, { useEffect, useMemo, useState } from 'react';
import React, { useMemo, useState } from 'react';
import { useTranslation } from "react-i18next";
import Entries from './Entries';

Expand All @@ -31,8 +31,10 @@ const CalendarComponent = (props: { isStandalone?: boolean }) => {
const [t] = useTranslation();

const currentDate = useMemo(() => new Date(), []);
const [currentMonth, setCurrentMonth] = useState(currentDate.getMonth());
const [currentYear, setCurrentYear] = useState(currentDate.getFullYear());
// The calendar always shows the month of the selected day
const [selectedDate, setSelectedDate] = useState(currentDate);
const currentMonth = selectedDate.getMonth();
const currentYear = selectedDate.getFullYear();

const startOfMonth = new Date(currentYear, currentMonth, 1);
const startOfNextMonth = new Date(currentYear, currentMonth + 1, 1);
Expand Down Expand Up @@ -71,14 +73,6 @@ const CalendarComponent = (props: { isStandalone?: boolean }) => {
const isLoading = weightsQuery.isLoading || sessionQuery.isLoading || categoryQuery.isLoading || measurementQuery.isLoading || nutritionDiaryQuery.isLoading;
const isSuccess = weightsQuery.isSuccess && sessionQuery.isSuccess && categoryQuery.isSuccess && measurementQuery.isSuccess && nutritionDiaryQuery.isSuccess;

const defaultDay: DayProps = {
date: currentDate,
weightEntry: undefined,
workoutSessions: [],
measurements: [],
nutritionLogs: []
};

const days = useMemo(() => {
const year = currentYear;
const month = currentMonth;
Expand Down Expand Up @@ -146,47 +140,39 @@ const CalendarComponent = (props: { isStandalone?: boolean }) => {

return result;
}, [currentYear, currentMonth, weightsQuery.data, sessionQuery.data, categoryQuery.data, measurementQuery.data, nutritionDiaryQuery.data, t]);
const [selectedDay, setSelectedDay] = useState<DayProps>(days.find(day => isSameDay(day.date, currentDate)) || defaultDay);
// Read from the current data, so that e.g. a deleted session disappears
// from the entries panel instead of showing a stale copy
const selectedDay: DayProps = days.find(
day => day.date.getMonth() === currentMonth && isSameDay(day.date, selectedDate)
) ?? {
date: selectedDate,
weightEntry: undefined,
workoutSessions: [],
measurements: [],
nutritionLogs: []
};

const theme = useTheme();
const isMobile = useMediaQuery(theme.breakpoints.down('sm'));

useEffect(() => {
if (isSuccess) {
const todayWithData = days.find(day => isSameDay(day.date, currentDate));
if (todayWithData) {
setSelectedDay(todayWithData);
}
}
}, [currentDate, days, isSuccess]);


useEffect(() => {
setCurrentMonth(selectedDay.date.getMonth());
setCurrentYear(selectedDay.date.getFullYear());
}, [selectedDay]);

const handleDayClick = (day: DayProps) => {
setSelectedDay(day);
setSelectedDate(day.date);
};

// Changing the month selects its first day, or today in the current month
const selectMonth = (year: number, month: number) => {
setSelectedDate(year === currentDate.getFullYear() && month === currentDate.getMonth()
? currentDate
: new Date(year, month, 1));
};

const handlePrevMonth = () => {
if (currentMonth === 0) {
setCurrentMonth(11);
setCurrentYear(currentYear - 1);
} else {
setCurrentMonth(currentMonth - 1);
}
selectMonth(currentYear, currentMonth - 1);
};

const handleNextMonth = () => {
if (currentMonth < currentDate.getMonth() || currentYear < currentDate.getFullYear()) {
if (currentMonth === 11) {
setCurrentMonth(0);
setCurrentYear(currentYear + 1);
} else {
setCurrentMonth(currentMonth + 1);
}
selectMonth(currentYear, currentMonth + 1);
}
};

Expand Down
47 changes: 47 additions & 0 deletions src/components/Calendar/Components/Entries.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { QueryClientProvider } from '@tanstack/react-query';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MeasurementEntry } from "@/components/Measurements";
import { deleteSession } from "@/components/Routines/api/session";
import { WorkoutSession } from "@/components/Routines/models/WorkoutSession";
import { testQueryClient } from "@/tests/queryClient";
import { makeWeightEntry } from "@/tests/weight/testData";
Expand All @@ -14,6 +15,7 @@ import { DayProps } from './CalendarComponent';
import Entries from './Entries';

vi.mock("@/components/Measurements/api/bodyWeight");
vi.mock("@/components/Routines/api/session");
vi.mock('@/components/User/queries/profile', () => ({
useProfileQuery: () => ({ isLoading: false, data: { useMetric: true } }),
}));
Expand Down Expand Up @@ -129,6 +131,51 @@ describe('Entries Component', () => {
expect(screen.getByText(/^8 × 82.5/)).toBeInTheDocument();
});

test('Deletes a workout session after confirming', async () => {
const session = new WorkoutSession({ ...testWorkoutSession, logs: testWorkoutLogs });
const propsWithSession = {
...defaultProps,
workoutSessions: [session]
};

render(
<QueryClientProvider client={testQueryClient}>
<Entries selectedDay={propsWithSession} />
</QueryClientProvider>
);

const user = userEvent.setup();
await user.click(screen.getByRole('button', { name: 'delete' }));

// Nothing is deleted until the user confirms
expect(screen.getByText('routines.deleteSessionInfo')).toBeInTheDocument();
expect(deleteSession).not.toHaveBeenCalled();

await user.click(screen.getByRole('button', { name: 'delete' }));

expect(deleteSession).toHaveBeenCalledTimes(1);
expect(deleteSession).toHaveBeenCalledWith(session.id);
});

test('Does not delete a workout session when the dialog is closed', async () => {
const propsWithSession = {
...defaultProps,
workoutSessions: [new WorkoutSession({ ...testWorkoutSession, logs: testWorkoutLogs })]
};

render(
<QueryClientProvider client={testQueryClient}>
<Entries selectedDay={propsWithSession} />
</QueryClientProvider>
);

const user = userEvent.setup();
await user.click(screen.getByRole('button', { name: 'delete' }));
await user.click(screen.getByRole('button', { name: 'close' }));

expect(deleteSession).not.toHaveBeenCalled();
});

test('Shows every session of the day', async () => {
const propsWithSessions = {
...defaultProps,
Expand Down
26 changes: 25 additions & 1 deletion src/components/Calendar/Components/Entries.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
import { useBodyWeightCategoryQuery, useDisplayWeightUnit } from "@/components/Measurements";
import { useDeleteSessionQuery, WorkoutSession } from "@/components/Routines";
import { dateToLocale } from "@/core/lib/date";
import { DeleteConfirmationModal } from "@/core/ui/Modals/DeleteConfirmationModal";
import { ExpandLess, ExpandMore } from '@mui/icons-material';
import DeleteIcon from "@mui/icons-material/DeleteOutlined";
import {
Card,
CardContent,
CardHeader,
Collapse,
IconButton,
List,
ListItem,
ListItemButton,
Expand All @@ -31,6 +35,8 @@ const Entries: React.FC<LogProps> = ({ selectedDay, isStandalone }) => {
// A day can hold several sessions, at most one of them is expanded
const [openSessionId, setOpenSessionId] = React.useState<string | null>(null);
const [openNutritionDiary, setOpenNutritionDiary] = React.useState(false);
const [sessionToDelete, setSessionToDelete] = React.useState<WorkoutSession | null>(null);
const deleteSessionQuery = useDeleteSessionQuery();

isStandalone = isStandalone ?? true;

Expand Down Expand Up @@ -113,7 +119,17 @@ const Entries: React.FC<LogProps> = ({ selectedDay, isStandalone }) => {

{/* Workout sessions */}
{selectedDay.workoutSessions.map((session) => <React.Fragment key={session.id}>
<ListItem>
<ListItem
secondaryAction={
<IconButton
edge="end"
aria-label={t("delete")}
onClick={() => setSessionToDelete(session)}
>
<DeleteIcon />
</IconButton>
}
>
<ListItemButton
onClick={() => setOpenSessionId(openSessionId === session.id ? null : session.id)}
selected={openSessionId === session.id}
Expand Down Expand Up @@ -171,6 +187,14 @@ const Entries: React.FC<LogProps> = ({ selectedDay, isStandalone }) => {
</List>

</CardContent>

<DeleteConfirmationModal
title={t('deleteConfirmation', { name: t("routines.workoutSession") })}
message={t("routines.deleteSessionInfo")}
isOpen={sessionToDelete !== null}
closeFn={() => setSessionToDelete(null)}
deleteFn={() => deleteSessionQuery.mutate(sessionToDelete!)}
/>
</Card>
);
};
Expand Down
15 changes: 13 additions & 2 deletions src/components/Routines/api/session.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as exerciseService from "@/components/Exercises/api/exercise";
import { addSession, editSession, getSessions, searchSessions } from "@/components/Routines/api/session";
import { addSession, deleteSession, editSession, getSessions, searchSessions } from "@/components/Routines/api/session";
import { WorkoutSession } from "@/components/Routines/models/WorkoutSession";
import { testExerciseBenchPress, testExerciseSquats } from "@/tests/exerciseTestdata";
import axios from "axios";
Expand Down Expand Up @@ -265,4 +265,15 @@ describe("Session service tests", () => {
});
expect(result.notes).toBe("edited");
});
});

test('deleteSession DELETEs /workoutsession/<id>/', async () => {
(axios.delete as Mock).mockResolvedValue({ status: 204 });

const result = await deleteSession(SESSION_UUID);

expect(axios.delete).toHaveBeenCalledTimes(1);
const [url] = (axios.delete as Mock).mock.calls[0];
expect(url).toMatch(new RegExp(`/api/v2/workoutsession/${SESSION_UUID}/$`));
expect(result).toBe(204);
});
});
12 changes: 12 additions & 0 deletions src/components/Routines/api/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,18 @@ export const addSession = async (session: WorkoutSession): Promise<WorkoutSessio
return new WorkoutSessionAdapter().fromJson(response.data);
};

/*
* Delete a session. The server deletes the logs that belong to it as well.
*/
export const deleteSession = async (id: string): Promise<number> => {
const response = await axios.delete(
makeUrl(ApiPath.SESSION, { id: id }),
{ headers: makeHeader() }
);

return response.status;
};

export const editSession = async (session: WorkoutSession): Promise<WorkoutSession> => {
const response = await axios.patch(
makeUrl(ApiPath.SESSION, { id: session.id! }),
Expand Down
2 changes: 1 addition & 1 deletion src/components/Routines/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export {
} from "./models/WorkoutSession";

// Query hooks
export { useActiveRoutineQuery, useSessionsQuery } from "./queries";
export { useActiveRoutineQuery, useDeleteSessionQuery, useSessionsQuery } from "./queries";

// Widgets
export { SetConfigDataDetails } from "./widgets/RoutineDetailsCard";
7 changes: 6 additions & 1 deletion src/components/Routines/queries/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,5 +62,10 @@ export {
} from "./slots";

export {
useAddSessionQuery, useEditSessionQuery, useFindSessionsQuery, useSessionOfDay, useSessionsQuery
useAddSessionQuery,
useDeleteSessionQuery,
useEditSessionQuery,
useFindSessionsQuery,
useSessionOfDay,
useSessionsQuery
} from "./sessions";
Loading
Loading