Skip to content

add one click enroll functionality to dashboard cards #2319

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

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion frontends/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
"ol-test-utilities": "0.0.0"
},
"dependencies": {
"@mitodl/mitxonline-api-axios": "^2025.6.3",
"@mitodl/mitxonline-api-axios": "^2025.6.23",
"@tanstack/react-query": "^5.66.0",
"axios": "^1.6.3"
}
Expand Down
20 changes: 18 additions & 2 deletions frontends/api/src/mitxonline/hooks/enrollment/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,22 @@
import { enrollmentQueries, enrollmentKeys } from "./queries"
import { useMutation, useQueryClient } from "@tanstack/react-query"
import { enrollmentsApi } from "../../clients"
import { EnrollmentsApiEnrollmentsPartialUpdateRequest } from "@mitodl/mitxonline-api-axios/v1"
import { b2bApi, enrollmentsApi } from "../../clients"
import {
B2bApiB2bEnrollCreateRequest,
EnrollmentsApiEnrollmentsPartialUpdateRequest,
} from "@mitodl/mitxonline-api-axios/v1"

const useCreateEnrollment = (opts: B2bApiB2bEnrollCreateRequest) => {
const queryClient = useQueryClient()
return useMutation({
mutationFn: () => b2bApi.b2bEnrollCreate(opts),
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: enrollmentKeys.enrollmentsList(),
})
},
})
}

const useUpdateEnrollment = (
opts: EnrollmentsApiEnrollmentsPartialUpdateRequest,
Expand Down Expand Up @@ -32,6 +47,7 @@ const useDestroyEnrollment = (enrollmentId: number) => {
export {
enrollmentQueries,
enrollmentKeys,
useCreateEnrollment,
useUpdateEnrollment,
useDestroyEnrollment,
}
7 changes: 6 additions & 1 deletion frontends/api/src/mitxonline/test-utils/urls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ const enrollment = {
`${API_BASE_URL}/api/v1/enrollments/${id ? `${id}/` : ""}`,
}

const b2b = {
courseEnrollment: (readableId?: string) =>
`${API_BASE_URL}/api/v0/b2b/enroll/${readableId}/`,
}

const programs = {
programsList: (opts?: ProgramsApiProgramsListV2Request) =>
`${API_BASE_URL}/api/v2/programs/${queryify(opts)}`,
Expand All @@ -32,4 +37,4 @@ const organization = {
`${API_BASE_URL}/api/v0/b2b/organizations/${organizationSlug}/`,
}

export { currentUser, enrollment, programs, courses, organization }
export { b2b, currentUser, enrollment, programs, courses, organization }
2 changes: 1 addition & 1 deletion frontends/main/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
"@emotion/cache": "^11.13.1",
"@emotion/styled": "^11.11.0",
"@mitodl/course-search-utils": "3.3.2",
"@mitodl/mitxonline-api-axios": "^2025.6.3",
"@mitodl/mitxonline-api-axios": "^2025.6.23",
"@mitodl/smoot-design": "^6.10.0",
"@next/bundle-analyzer": "^14.2.15",
"@remixicon/react": "^4.2.0",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
import React from "react"
import { renderWithProviders, screen, user, within } from "@/test-utils"
import {
renderWithProviders,
screen,
setMockResponse,
user,
within,
} from "@/test-utils"
import * as mitxonline from "api/mitxonline-test-utils"
import { DashboardCard, getDefaultContextMenuItems } from "./DashboardCard"
import { dashboardCourse } from "./test-utils"
import { faker } from "@faker-js/faker/locale/en"
import moment from "moment"
import { EnrollmentMode, EnrollmentStatus } from "./types"
import { mockAxiosInstance } from "api/test-utils"

const pastDashboardCourse: typeof dashboardCourse = (...overrides) => {
return dashboardCourse(
Expand Down Expand Up @@ -135,16 +143,32 @@ describe.each([
const card = getCard()
const coursewareCTA = within(card).getByTestId("courseware-button")

expect(coursewareCTA).toHaveTextContent(`${expected.labelPrefix} Course`)
if (
course.enrollment?.status === EnrollmentStatus.NotEnrolled ||
!course.enrollment
) {
expect(coursewareCTA).toHaveTextContent("Enroll")
} else {
expect(coursewareCTA).toHaveTextContent(
`${expected.labelPrefix} Course`,
)
}

const courseNoun = faker.word.noun()
view.rerender(
<DashboardCard courseNoun={courseNoun} dashboardResource={course} />,
)

expect(coursewareCTA).toHaveTextContent(
`${expected.labelPrefix} ${courseNoun}`,
)
if (
course.enrollment?.status === EnrollmentStatus.NotEnrolled ||
!course.enrollment
) {
expect(coursewareCTA).toHaveTextContent("Enroll")
} else {
expect(coursewareCTA).toHaveTextContent(
`${expected.labelPrefix} ${courseNoun}`,
)
}
},
)

Expand Down Expand Up @@ -408,4 +432,61 @@ describe.each([
}
},
)

test.each([
{ status: EnrollmentStatus.Completed },
{ status: EnrollmentStatus.Enrolled },
{ status: EnrollmentStatus.NotEnrolled },
])(
"CoursewareButton switches to Enroll functionality when enrollment status is not enrolled or undefined",
({ status }) => {
const course = dashboardCourse()
course.enrollment = {
id: faker.number.int(),
status: status,
mode: EnrollmentMode.Audit,
}
renderWithProviders(<DashboardCard dashboardResource={course} />)
const card = getCard()
const coursewareButton = within(card).getByTestId("courseware-button")

if (
status === EnrollmentStatus.NotEnrolled ||
status === undefined ||
!course.enrollment
) {
expect(coursewareButton).toHaveTextContent("Enroll")
} else {
expect(coursewareButton).toHaveTextContent("Continue Course")
}
},
)

test("CoursewareButton hits enroll endpoint appropriately", async () => {
const course = dashboardCourse({
coursewareId: faker.string.uuid(),
enrollment: {
id: faker.number.int(),
status: EnrollmentStatus.NotEnrolled,
},
})
setMockResponse.post(
mitxonline.urls.b2b.courseEnrollment(course.coursewareId ?? undefined),
{ result: "b2b-enroll-success", order: 1 },
)
renderWithProviders(<DashboardCard dashboardResource={course} />)
const card = getCard()
const coursewareButton = within(card).getByTestId("courseware-button")

await user.click(coursewareButton)

expect(mockAxiosInstance.request).toHaveBeenCalledWith(
expect.objectContaining({
method: "POST",
url: mitxonline.urls.b2b.courseEnrollment(
course.coursewareId ?? undefined,
),
}),
)
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
SimpleMenuItem,
Stack,
Skeleton,
LoadingSpinner,
} from "ol-components"
import NextLink from "next/link"
import { EnrollmentStatus, EnrollmentMode } from "./types"
Expand All @@ -22,6 +23,7 @@ import { calendarDaysUntil, isInPast, NoSSR } from "ol-utilities"
import { EnrollmentStatusIndicator } from "./EnrollmentStatusIndicator"
import { EmailSettingsDialog, UnenrollDialog } from "./DashboardDialogs"
import NiceModal from "@ebay/nice-modal-react"
import { useCreateEnrollment } from "api/mitxonline-hooks/enrollment"

const CardRoot = styled.div<{
screenSize: "desktop" | "mobile"
Expand Down Expand Up @@ -55,6 +57,10 @@ const CardRoot = styled.div<{
},
])

const SpinnerContainer = styled.div({
marginLeft: "8px",
})

const TitleLink = styled(Link)(({ theme }) => ({
[theme.breakpoints.down("md")]: {
maxWidth: "calc(100% - 16px)",
Expand Down Expand Up @@ -103,14 +109,27 @@ const getDefaultContextMenuItems = (
}

type CoursewareButtonProps = {
coursewareId?: string | null
startDate?: string | null
endDate?: string | null
enrollmentStatus?: EnrollmentStatus | null
href?: string | null
className?: string
courseNoun: string
"data-testid"?: string
}
const getCoursewareText = ({ endDate, courseNoun }: CoursewareButtonProps) => {
const getCoursewareText = ({
endDate,
enrollmentStatus,
courseNoun,
}: {
endDate?: string | null
enrollmentStatus?: EnrollmentStatus | null
courseNoun: string
}) => {
if (enrollmentStatus === EnrollmentStatus.NotEnrolled || !enrollmentStatus) {
return "Enroll"
}
if (!endDate) return `Continue ${courseNoun}`
if (isInPast(endDate)) {
return `View ${courseNoun}`
Expand All @@ -119,26 +138,57 @@ const getCoursewareText = ({ endDate, courseNoun }: CoursewareButtonProps) => {
}
const CoursewareButton = styled(
({
coursewareId,
startDate,
endDate,
enrollmentStatus,
href,
className,
courseNoun,
...others
}: CoursewareButtonProps) => {
const children = getCoursewareText({ endDate, courseNoun })
const children = getCoursewareText({
endDate,
courseNoun,
enrollmentStatus,
})
const hasStarted = startDate && isInPast(startDate)
const notEnrolled =
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Small request for

const hasEnrolled = enrollmentStatus &&
      enrollmentStatus !== EnrollmentStatus.NotEnrolled

enrollmentStatus === EnrollmentStatus.NotEnrolled || !enrollmentStatus
const createEnrollment = useCreateEnrollment({
readable_id: coursewareId ?? "",
})
return hasStarted && href ? (
<ButtonLink
size="small"
variant="primary"
endIcon={<RiArrowRightLine />}
href={href}
className={className}
{...others}
>
{children}
</ButtonLink>
!notEnrolled ? (
<ButtonLink
size="small"
variant="primary"
endIcon={<RiArrowRightLine />}
href={href}
className={className}
{...others}
>
{children}
</ButtonLink>
) : (
<Button
size="small"
variant="primary"
className={className}
disabled={createEnrollment.isPending || !coursewareId}
onClick={async () => {
await createEnrollment.mutateAsync()
}}
{...others}
>
{children}
{createEnrollment.isPending && (
<SpinnerContainer>
<LoadingSpinner loading={createEnrollment.isPending} size={16} />
</SpinnerContainer>
)}
</Button>
)
) : (
<Button
size="small"
Expand Down Expand Up @@ -323,7 +373,9 @@ const DashboardCard: React.FC<DashboardCardProps> = ({
/>
<CoursewareButton
data-testid="courseware-button"
coursewareId={dashboardResource.coursewareId}
startDate={run.startDate}
enrollmentStatus={enrollment?.status}
href={buttonHref ? buttonHref : run.coursewareUrl}
endDate={run.endDate}
courseNoun={courseNoun}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ const dashboardCourse: PartialFactory<DashboardCourse> = (...overrides) => {
return mergeOverrides<DashboardCourse>(
{
id: faker.string.uuid(),
coursewareId: faker.string.uuid(),
type: DashboardResourceType.Course,
title: faker.commerce.productName(),
marketingUrl: faker.internet.url(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ describe("Transforming mitxonline enrollment data to DashboardResource", () => {
expect(transformed).toHaveLength(1)
expect(transformed[0]).toEqual({
id: `mitxonline-course-${apiData.run.course.id}`,
coursewareId: apiData.run.courseware_id ?? null,
type: DashboardResourceType.Course,
title: apiData.run.title,
marketingUrl: apiData.run.course.page.page_url,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ const mitxonlineEnrollment = (raw: CourseRunEnrollment): DashboardCourse => {
const course = raw.run.course
return {
id: getId(sources.mitxonline, DashboardResourceType.Course, course.id),
coursewareId: raw.run.courseware_id ?? null,
type: DashboardResourceType.Course,
title: course.title,
marketingUrl: course.page.page_url,
Expand Down Expand Up @@ -57,6 +58,7 @@ const mitxonlineUnenrolledCourse = (
const run = course.courseruns.find((run) => run.id === course.next_run_id)
return {
id: getId(sources.mitxonline, DashboardResourceType.Course, course.id),
coursewareId: run?.courseware_id ?? null,
type: DashboardResourceType.Course,
title: course.title,
marketingUrl: course.page.page_url,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ type EnrollmentMode = (typeof EnrollmentMode)[keyof typeof EnrollmentMode]

type DashboardCourse = {
id: string
coursewareId: string | null
title: string
type: typeof DashboardResourceType.Course
run: {
Expand Down
6 changes: 3 additions & 3 deletions yarn.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading