feat: org and course student analytics page (#509)

* UI initialization

* feat: structure API

* feat: audience & people analytics

* feat: quick changes

* feat: add comments

* redesign course student page

* chore: make requests to db more efficient

* clean up analytics page for course

* feat: finish up audience analytics page

* chore: minor UI tweaks

* translate all

* replace inserts of log in events to update

* catch error if last_login isn't inserted

---------

Co-authored-by: Rotimi Best <best@classroomio.com>
This commit is contained in:
Adeyemi Adetunji
2024-12-30 02:59:10 +01:00
committed by GitHub
co-authored by Rotimi Best
parent 381776f388
commit f69bf920a9
46 changed files with 1916 additions and 437 deletions
@@ -0,0 +1,52 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { page } from '$app/stores';
import CourseContainer from '$lib/components/CourseContainer/index.svelte';
import IconButton from '$lib/components/IconButton/index.svelte';
import PageBody from '$lib/components/PageBody/index.svelte';
import PageNav from '$lib/components/PageNav/index.svelte';
import PrimaryButton from '$lib/components/PrimaryButton/index.svelte';
import RoleBasedSecurity from '$lib/components/RoleBasedSecurity/index.svelte';
import { t } from '$lib/utils/functions/translations';
import ArrowLeft from 'carbon-icons-svelte/lib/ArrowLeft.svelte';
export let data;
const handleClick = () => {
const url = $page.url.href + '?add=true';
goto(url);
};
</script>
<CourseContainer bind:courseId={data.courseId}>
<PageNav title={$t('course.navItem.people.title')} disableSticky={true}>
<slot:fragment slot="image">
{#if data.personId}
<RoleBasedSecurity allowedRoles={[1, 2]}>
<IconButton
size="large"
onClick={() => {
goto(`/courses/${data.courseId}/people`);
}}
>
<ArrowLeft size={16} class="carbon-icon dark:text-white " />
</IconButton>
</RoleBasedSecurity>
{/if}
</slot:fragment>
<slot:fragment slot="widget">
{#if !data.personId}
<RoleBasedSecurity allowedRoles={[1, 2]}>
<PrimaryButton
className="mr-2"
label={$t('course.navItem.people.add')}
onClick={handleClick}
/>
</RoleBasedSecurity>
{/if}
</slot:fragment>
</PageNav>
<PageBody width="w-full max-w-6xl md:w-11/12">
<slot />
</PageBody>
</CourseContainer>
@@ -0,0 +1,6 @@
export const load = ({ params = { id: '', personId: '' } }) => {
return {
courseId: params.id,
personId: params.personId
};
};
@@ -1,5 +1,25 @@
<script lang="ts">
import copy from 'copy-to-clipboard';
import { goto } from '$app/navigation';
import { page } from '$app/stores';
import Avatar from '$lib/components/Avatar/index.svelte';
import TextChip from '$lib/components/Chip/Text.svelte';
import ComingSoon from '$lib/components/ComingSoon/index.svelte';
import DeleteConfirmation from '$lib/components/Course/components/People/DeleteConfirmation.svelte';
import InvitationModal from '$lib/components/Course/components/People/InvitationModal.svelte';
import { deleteMemberModal } from '$lib/components/Course/components/People/store';
import type { Person, ProfileRole } from '$lib/components/Course/components/People/types';
import { group } from '$lib/components/Course/store';
import Select from '$lib/components/Form/Select.svelte';
import IconButton from '$lib/components/IconButton/index.svelte';
import { VARIANTS } from '$lib/components/PrimaryButton/constants';
import PrimaryButton from '$lib/components/PrimaryButton/index.svelte';
import RoleBasedSecurity from '$lib/components/RoleBasedSecurity/index.svelte';
import { snackbar } from '$lib/components/Snackbar/store';
import { ROLE_LABEL, ROLES } from '$lib/utils/constants/roles';
import { t } from '$lib/utils/functions/translations';
import { deleteGroupMember, updatedGroupMember } from '$lib/utils/services/courses';
import { profile } from '$lib/utils/store/user';
import type { GroupPerson } from '$lib/utils/types';
import {
CopyButton,
Search,
@@ -9,34 +29,10 @@
StructuredListHead,
StructuredListRow
} from 'carbon-components-svelte';
import TextChip from '$lib/components/Chip/Text.svelte';
import ComingSoon from '$lib/components/ComingSoon/index.svelte';
import CourseContainer from '$lib/components/CourseContainer/index.svelte';
import { deleteGroupMember, updatedGroupMember } from '$lib/utils/services/courses';
import TrashCanIcon from 'carbon-icons-svelte/lib/TrashCan.svelte';
import PageNav from '$lib/components/PageNav/index.svelte';
import PageBody from '$lib/components/PageBody/index.svelte';
import PrimaryButton from '$lib/components/PrimaryButton/index.svelte';
import Select from '$lib/components/Form/Select.svelte';
import IconButton from '$lib/components/IconButton/index.svelte';
import RoleBasedSecurity from '$lib/components/RoleBasedSecurity/index.svelte';
import { group } from '$lib/components/Course/store';
import InvitationModal from '$lib/components/Course/components/People/InvitationModal.svelte';
import DeleteConfirmation from '$lib/components/Course/components/People/DeleteConfirmation.svelte';
import { deleteMemberModal } from '$lib/components/Course/components/People/store';
import type { Person, ProfileRole } from '$lib/components/Course/components/People/types';
import { ROLE_LABEL, ROLES } from '$lib/utils/constants/roles';
import { profile } from '$lib/utils/store/user';
import { snackbar } from '$lib/components/Snackbar/store';
import Avatar from '$lib/components/Avatar/index.svelte';
import type { GroupPerson } from '$lib/utils/types';
import { t } from '$lib/utils/functions/translations';
import { page } from '$app/stores';
import { goto } from '$app/navigation';
import copy from 'copy-to-clipboard';
export let data;
let people: Array<Person> = [];
let people: Array<GroupPerson> = [];
let member: { id?: string; email?: string; profile?: { email: string } } = {};
let shouldEditMemberId: string | null = null;
let filterBy: ProfileRole = ROLES[0];
@@ -59,6 +55,7 @@
}
async function deletePerson() {
if (!member.id) return;
$group.people = $group.people.filter((person: { id: string }) => person.id !== member.id);
$group.tutors = $group.tutors.filter((person: GroupPerson) => person.memberId !== member.id);
@@ -73,15 +70,18 @@
shouldEditMemberId = null;
}
function sortAndFilterPeople(_people: Array<Person>, filterBy: ProfileRole) {
function sortAndFilterPeople(_people: Array<GroupPerson>, filterBy: ProfileRole) {
people = (_people || [])
.filter((person) => {
if (filterBy.value === 'all') return true;
return person.role_id === filterBy.value;
})
.sort((a: Person, b: Person) => new Date(a.created_at) - new Date(b.created_at))
.sort((a: Person, b: Person) => a.role_id - b.role_id);
.sort(
(a: GroupPerson, b: GroupPerson) =>
new Date(a.created_at).getTime() - new Date(b.created_at).getTime()
)
.sort((a: GroupPerson, b: GroupPerson) => a.role_id - b.role_id);
}
function getEmail(person) {
@@ -115,6 +115,10 @@
goto(url);
};
function gotoPerson(person) {
goto(`${$page.url.href}/${person.profile_id}`);
}
$: sortAndFilterPeople($group.people, filterBy);
</script>
@@ -125,163 +129,156 @@
{deletePerson}
/>
<CourseContainer bind:courseId={data.courseId}>
<PageNav title={$t('course.navItem.people.title')} disableSticky={true}>
<slot:fragment slot="widget">
<RoleBasedSecurity allowedRoles={[1, 2]}>
<PrimaryButton
className="mr-2"
label={$t('course.navItem.people.add')}
onClick={handleClick}
/>
</RoleBasedSecurity>
</slot:fragment>
</PageNav>
<PageBody width="w-full max-w-6xl md:w-11/12">
<section class="my-5 mx-2 md:mx-9">
<div
class="flex flex-col md:flex-row flex-end gap-2 justify-end items-start md:items-center mb-7"
>
<div class="max-w-[320px]">
<Search
class="dark:text-slate-950 border-0 bg-zinc-100 w-full"
placeholder={$t('course.navItem.people.search')}
bind:value={searchValue}
/>
</div>
<div class="mb-3">
<Select
bind:value={filterBy}
options={ROLES.map((role) => ({ label: $t(role.label), value: role.value }))}
className="dark:text-black mt-3 max-w-[80px]"
/>
<!-- <select bind:value={filterBy} class="mt-3">
{#each ROLES as option}
<option value={option.value}>{option.label}</option>
{/each}
</select> -->
</div>
<RoleBasedSecurity allowedRoles={[1, 2]}>
<p class="dark:text-white hidden lg:block text-lg w-20" />
</RoleBasedSecurity>
</div>
<section class="mx-2 my-5 md:mx-9">
<div
class="flex-end mb-7 flex flex-col items-start justify-end gap-2 md:flex-row md:items-center"
>
<div class="max-w-[320px]">
<Search
class="w-full border-0 bg-zinc-100 dark:text-slate-950"
placeholder={$t('course.navItem.people.search')}
bind:value={searchValue}
/>
</div>
<div class="mb-3">
<Select
bind:value={filterBy}
options={ROLES.map((role) => ({ label: $t(role.label), value: role.value }))}
className="dark:text-black mt-3 max-w-[80px]"
/>
<!-- <select bind:value={filterBy} class="mt-3">
{#each ROLES as option}
<option value={option.value}>{option.label}</option>
{/each}
</select> -->
</div>
<RoleBasedSecurity allowedRoles={[1, 2]}>
<p class="hidden w-20 text-lg dark:text-white lg:block" />
</RoleBasedSecurity>
</div>
<StructuredList class="m-0">
<StructuredListHead
class="bg-slate-100 dark:bg-neutral-800 dark:border-2 dark:border-neutral-800"
<StructuredList class="m-0">
<StructuredListHead
class="bg-slate-100 dark:border-2 dark:border-neutral-800 dark:bg-neutral-800"
>
<StructuredListRow head class="mx-7">
<StructuredListCell head class="text-primary-700 py-3 dark:text-white"
>{$t('course.navItem.people.name')}</StructuredListCell
>
<StructuredListRow head class="mx-7">
<StructuredListCell head class="text-primary-700 py-3 dark:text-white"
>{$t('course.navItem.people.name')}</StructuredListCell
>
<StructuredListCell head class="text-primary-700 py-3 dark:text-white"
>{$t('course.navItem.people.role')}</StructuredListCell
>
<StructuredListCell head class="text-primary-700 py-3 dark:text-white"
>{$t('course.navItem.people.action')}</StructuredListCell
>
<RoleBasedSecurity allowedRoles={[1, 2]}>
<p class="dark:text-white hidden lg:block text-lg w-20" />
</RoleBasedSecurity>
</StructuredListRow>
</StructuredListHead>
<StructuredListCell head class="text-primary-700 py-3 dark:text-white"
>{$t('course.navItem.people.role')}</StructuredListCell
>
<StructuredListCell head class="text-primary-700 py-3 dark:text-white"
>{$t('course.navItem.people.action')}</StructuredListCell
>
<RoleBasedSecurity allowedRoles={[1, 2]}>
<p class="hidden w-20 text-lg dark:text-white lg:block" />
</RoleBasedSecurity>
</StructuredListRow>
</StructuredListHead>
{#each filterPeople(searchValue, people) as person}
<StructuredListBody>
<StructuredListRow class="relative">
<!-- first column -->
<StructuredListCell class="w-4/6 md:w-3/6">
{#if person.profile}
<div class="flex items-start lg:items-center">
<Avatar
src={person.profile.avatar_url}
name={person.profile.fullname}
width="w-8"
height="h-8"
className="mr-3"
/>
<div class="flex flex-col lg:flex-row items-start lg:items-center">
<div class="mr-2">
<p class="dark:text-white text-base font-normal">
{person.profile.fullname}
</p>
<p class="text-xs text-primary-600 line-clamp-1">
{obscureEmail(getEmail(person))}
</p>
</div>
<div class="flex items-center">
<RoleBasedSecurity allowedRoles={[1, 2]}>
<CopyButton
text={getEmail(person)}
feedback="Copied Email to clipboard"
/>
</RoleBasedSecurity>
{#if person.profile_id == $profile.id}
<ComingSoon label={$t('course.navItem.people.you')} />
{/if}
</div>
</div>
{#each filterPeople(searchValue, people) as person}
<StructuredListBody>
<StructuredListRow class="relative">
<!-- first column -->
<StructuredListCell class="w-4/6 md:w-3/6">
{#if person.profile}
<div class="flex items-start lg:items-center">
<Avatar
src={person.profile.avatar_url}
name={person.profile.fullname}
width="w-8"
height="h-8"
className="mr-3"
/>
<div class="flex flex-col items-start lg:flex-row lg:items-center">
<div class="mr-2">
<p class="text-base font-normal dark:text-white">
{person.profile.fullname}
</p>
<p class="text-primary-600 line-clamp-1 text-xs">
{obscureEmail(getEmail(person))}
</p>
</div>
{:else}
<div class="flex items-start lg:items-center w-2/4">
<TextChip
value={person.email.substring(0, 2).toUpperCase()}
className="bg-primary-200 text-black font-semibold text-xs mr-3"
shape="rounded-full"
/>
<a
href="mailto:{person.email}"
class="text-md text-primary-600 mr-2 dark:text-white"
>
{person.email}
</a>
<div class="flex items-center justify-between">
<RoleBasedSecurity allowedRoles={[1, 2]}>
<CopyButton
text={getEmail(person)}
feedback={$t('course.navItem.people.feedback')}
/>
</RoleBasedSecurity>
<TextChip
value={$t('course.navItem.people.pending')}
className="text-xs bg-yellow-200 text-yellow-700 h-fit"
size="sm"
/>
</div>
</div>
{/if}
</StructuredListCell>
<!-- second column -->
<StructuredListCell class="w-1/4 px-3">
<p class=" dark:text-white font-normal text-center text-base w-1/4">
{$t(ROLE_LABEL[person.role_id])}
</p>
</StructuredListCell>
<!-- third column -->
<StructuredListCell class="p-0 w-1/4">
<RoleBasedSecurity allowedRoles={[1, 2]}>
<div class="hidden sm:flex sm:justify-between sm:items-center w-20">
{#if person.profile_id !== $profile.id}
<IconButton
onClick={() => {
member = person;
$deleteMemberModal.open = true;
}}
>
<TrashCanIcon size={16} class="carbon-icon dark:text-white" />
</IconButton>
<div class="flex items-center">
<RoleBasedSecurity allowedRoles={[1, 2]}>
<CopyButton text={getEmail(person)} feedback="Copied Email to clipboard" />
</RoleBasedSecurity>
{#if person.profile_id == $profile.id}
<ComingSoon label={$t('course.navItem.people.you')} />
{/if}
</div>
</RoleBasedSecurity>
</StructuredListCell>
</StructuredListRow>
</StructuredListBody>
{/each}
</StructuredList>
<!-- <Pagination totalItems={10} pageSizes={[10, 15, 20]} /> -->
</section>
</PageBody>
</CourseContainer>
</div>
</div>
{:else}
<div class="flex w-2/4 items-start lg:items-center">
<TextChip
value={person.email.substring(0, 2).toUpperCase()}
className="bg-primary-200 text-black font-semibold text-xs mr-3"
shape="rounded-full"
/>
<a
href="mailto:{person.email}"
class="text-md text-primary-600 mr-2 dark:text-white"
>
{person.email}
</a>
<div class="flex items-center justify-between">
<RoleBasedSecurity allowedRoles={[1, 2]}>
<CopyButton
text={getEmail(person)}
feedback={$t('course.navItem.people.feedback')}
/>
</RoleBasedSecurity>
<TextChip
value={$t('course.navItem.people.pending')}
className="text-xs bg-yellow-200 text-yellow-700 h-fit"
size="sm"
/>
</div>
</div>
{/if}
</StructuredListCell>
<!-- second column -->
<StructuredListCell class="w-1/4">
<p class=" w-1/4 text-center text-base font-normal dark:text-white">
{$t(ROLE_LABEL[person.role_id])}
</p>
</StructuredListCell>
<!-- third column -->
<StructuredListCell class="w-1/4 p-0">
<RoleBasedSecurity allowedRoles={[1, 2]}>
<div class="hidden space-x-2 sm:flex sm:items-center">
{#if person.profile_id !== $profile.id}
<IconButton
onClick={() => {
member = person;
$deleteMemberModal.open = true;
}}
>
<TrashCanIcon size={16} class="carbon-icon dark:text-white" />
</IconButton>
<!-- <IconButton
onClick={() => gotoPerson(person)}
>
<TrashCanIcon size={16} class="carbon-icon dark:text-white" />
</IconButton> -->
<PrimaryButton
variant={VARIANTS.OUTLINED}
label={$t('course.navItem.people.view')}
onClick={() => gotoPerson(person)}
/>
{/if}
</div>
</RoleBasedSecurity>
</StructuredListCell>
</StructuredListRow>
</StructuredListBody>
{/each}
</StructuredList>
<!-- <Pagination totalItems={10} pageSizes={[10, 15, 20]} /> -->
</section>
@@ -0,0 +1,208 @@
<script lang="ts">
import { ActivityCard, HeroProfileCard, LoadingPage } from '$lib/components/Analytics';
import Progress from '$lib/components/Progress/index.svelte';
import { snackbar } from '$lib/components/Snackbar/store';
import { getAccessToken } from '$lib/utils/functions/supabase';
import { t } from '$lib/utils/functions/translations';
import type { UserCourseAnalytics } from '$lib/utils/types/analytics';
import { Grid, Tag } from 'carbon-components-svelte';
import Notebook from 'carbon-icons-svelte/lib/Notebook.svelte';
import Report from 'carbon-icons-svelte/lib/Report.svelte';
import RowExpand from 'carbon-icons-svelte/lib/RowExpand.svelte';
import { onMount } from 'svelte';
import { fade } from 'svelte/transition';
export let data;
let userCourseAnalytics: UserCourseAnalytics;
function getPercentage(a: number, b: number): number {
if (b === 0) {
return 0;
}
return Math.round((a / b) * 100);
}
let exerciseFilter: 'all' | 'completed' | 'incomplete' = 'all';
function toggleExerciseFilter(filter: 'completed' | 'incomplete') {
if (exerciseFilter === filter) {
exerciseFilter = 'all';
} else {
exerciseFilter = filter;
}
}
async function fetchUserCourseAnalytics() {
const accessToken = await getAccessToken();
const response = await fetch('/api/analytics/user', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: accessToken
},
body: JSON.stringify(data)
});
if (response.ok) {
userCourseAnalytics = (await response.json()) as UserCourseAnalytics;
} else {
console.error(response);
snackbar.error('Failed to fetch analytics data');
}
}
onMount(() => {
fetchUserCourseAnalytics();
});
$: learningActivities = [
{
description: $t('analytics.overall_course_progress_user_description'),
icon: Notebook,
percentage: userCourseAnalytics?.progressPercentage,
title: $t('analytics.overall_course_progress')
},
{
description: $t('analytics.assignment_completion_description'),
icon: Report,
percentage: getPercentage(
userCourseAnalytics?.userExercisesStats?.filter((exercise) => exercise.isCompleted)?.length,
userCourseAnalytics?.userExercisesStats?.length
),
title: $t('analytics.assignment_completion')
},
{
description: $t('analytics.average_grade_description'),
icon: RowExpand,
percentage: userCourseAnalytics?.averageGrade,
title: $t('analytics.average_grade')
}
];
$: filteredExercises = userCourseAnalytics?.userExercisesStats?.filter((exercise) => {
if (exerciseFilter === 'all') {
return true;
}
return exercise.isCompleted === (exerciseFilter === 'completed');
});
$: completedExercises = userCourseAnalytics?.userExercisesStats?.filter(
(exercise) => exercise.isCompleted
)?.length;
$: incompleteExercises = userCourseAnalytics?.userExercisesStats?.filter(
(exercise) => !exercise.isCompleted
)?.length;
</script>
{#if userCourseAnalytics}
<section class="px-1">
<HeroProfileCard user={userCourseAnalytics.user} />
<Grid class="mt-5 px-0" fullWidth>
<div class="mt-8 grid grid-cols-1 gap-6 md:grid-cols-2 lg:grid-cols-3">
{#each learningActivities as activity}
<ActivityCard {activity} />
{/each}
</div>
</Grid>
<div class="mt-5 rounded-md border p-3 dark:border-neutral-600 md:p-5">
<h3 class="text-2xl font-bold">
{$t('analytics.exercises')}
</h3>
<div class="flex flex-col gap-2">
<div class="flex items-center justify-between">
<p class="text-sm font-medium text-gray-600 dark:text-gray-200">
{$t('analytics.exercises')}
</p>
<p class="text-sm font-medium text-gray-600 dark:text-gray-200">
{$t('analytics.progress_description', {
value: completedExercises,
total: userCourseAnalytics?.userExercisesStats?.length
})}
</p>
</div>
<Progress
value={getPercentage(completedExercises, userCourseAnalytics?.userExercisesStats?.length)}
/>
<div class="flex items-center justify-between">
<Tag
interactive
filter={exerciseFilter === 'incomplete'}
type={exerciseFilter === 'incomplete' ? 'gray' : 'outline'}
class="text-yellow-700 dark:text-yellow-500"
on:click={() => toggleExerciseFilter('incomplete')}
>
{incompleteExercises}
{$t('analytics.incomplete')}
</Tag>
<Tag
interactive
filter={exerciseFilter === 'completed'}
type={exerciseFilter === 'completed' ? 'gray' : 'outline'}
class="text-green-700 dark:text-green-500"
on:click={() => toggleExerciseFilter('completed')}
>
{completedExercises}
{$t('analytics.complete')}
</Tag>
</div>
</div>
{#each filteredExercises as exercise, index}
{#key index}
<div
class={`mt-5 flex items-center justify-between gap-4 rounded-md border p-5 ${
exercise.isCompleted
? 'border-green-200 bg-green-50 dark:bg-green-100'
: 'border-yellow-200 bg-yellow-50 dark:bg-yellow-100'
}`}
transition:fade={{ duration: 300 }}
>
<div class="flex w-2/3 items-center gap-4">
<Notebook size={24} class="text-black" />
<div>
<div class="mb-2">
<a
href={`/courses/${data.courseId}/lessons/${exercise.lessonId}/exercises/${exercise.id}?tabIndex=1`}
>
<p class="text-lg font-semibold text-gray-600">
{exercise.title}
</p>
</a>
<a href={`/courses/${data.courseId}/lessons/${exercise.lessonId}`}>
<p class="text-sm text-gray-500">
#{exercise.lessonTitle}
</p>
</a>
</div>
<p class="text-sm text-gray-500">
Score: {exercise.score}/{exercise.totalPoints}
{#if exercise.isCompleted}
<Tag type={exercise.status === 3 ? 'high-contrast' : 'outline'} size="sm">
{exercise.status === 3 ? $t('analytics.graded') : $t('analytics.not_graded')}
</Tag>
{/if}
</p>
</div>
</div>
<Tag
class={`${
exercise.isCompleted
? 'bg-green-200 text-green-700'
: 'bg-yellow-200 text-yellow-700'
}`}
>
{exercise.isCompleted ? $t('analytics.complete') : $t('analytics.incomplete')}
</Tag>
</div>
{/key}
{/each}
</div>
</section>
{:else}
<LoadingPage />
{/if}
@@ -0,0 +1,8 @@
export const load = async ({ params }) => {
const { id, personId } = params;
return {
userId: personId,
courseId: id
};
};