richie-education 2.25.0-b2.dev35 → 2.25.0-b2.dev42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (21) hide show
  1. package/js/components/Badge/index.tsx +1 -0
  2. package/js/components/PurchaseButton/index.tsx +4 -1
  3. package/js/components/SaleTunnel/index.tsx +7 -1
  4. package/js/components/TeacherDashboardCourseList/index.spec.tsx +1 -1
  5. package/js/hooks/useCourseProductUnion/index.ts +1 -0
  6. package/js/hooks/useQueryKeyInvalidateListener.tsx +16 -0
  7. package/js/hooks/useUnionResource/index.ts +19 -2
  8. package/js/pages/DashboardCourses/useOrdersEnrollments.tsx +1 -0
  9. package/js/utils/CreditCardHelper/index.spec.tsx +4 -7
  10. package/js/widgets/Dashboard/components/DashboardItem/Enrollment/ProductCertificateFooter/index.spec.tsx +89 -2
  11. package/js/widgets/Dashboard/components/DashboardItem/Enrollment/ProductCertificateFooter/index.tsx +12 -1
  12. package/js/widgets/Dashboard/components/DashboardSidebar/components/ContractNavLink/index.spec.tsx +244 -0
  13. package/js/widgets/Dashboard/components/DashboardSidebar/components/ContractNavLink/index.tsx +47 -0
  14. package/js/widgets/Dashboard/components/DashboardSidebar/components/MenuNavLink/index.spec.tsx +40 -0
  15. package/js/widgets/Dashboard/components/DashboardSidebar/components/MenuNavLink/index.tsx +28 -0
  16. package/js/widgets/Dashboard/components/DashboardSidebar/index.stories.tsx +7 -2
  17. package/js/widgets/Dashboard/components/DashboardSidebar/index.tsx +10 -25
  18. package/js/widgets/Dashboard/components/DashboardSidebar/utils.ts +6 -0
  19. package/js/widgets/Dashboard/components/TeacherDashboardOrganizationSidebar/index.spec.tsx +4 -2
  20. package/js/widgets/Dashboard/components/TeacherDashboardOrganizationSidebar/index.tsx +13 -32
  21. package/package.json +15 -15
@@ -6,6 +6,7 @@ type BadgeProps = PropsWithChildren<{
6
6
  }>;
7
7
  const Badge = ({ children, color }: BadgeProps) => (
8
8
  <div
9
+ data-testid="badge"
9
10
  className={classNames('category-badge', {
10
11
  [`category-badge--${color}`]: Boolean(color),
11
12
  })}
@@ -4,7 +4,7 @@ import { useMemo, useState } from 'react';
4
4
  import { Button, ButtonProps } from '@openfun/cunningham-react';
5
5
  import { useSession } from 'contexts/SessionContext';
6
6
  import * as Joanie from 'types/Joanie';
7
- import SaleTunnel from 'components/SaleTunnel';
7
+ import SaleTunnel, { SaleTunnelProps } from 'components/SaleTunnel';
8
8
  import { isOpenedCourseRunCertificate, isOpenedCourseRunCredential } from 'utils/CourseRuns';
9
9
 
10
10
  const messages = defineMessages({
@@ -45,6 +45,7 @@ interface PurchaseButtonPropsBase {
45
45
  disabled?: boolean;
46
46
  className?: string;
47
47
  buttonProps?: ButtonProps;
48
+ onFinish?: SaleTunnelProps['onFinish'];
48
49
  }
49
50
 
50
51
  interface CredentialPurchaseButtonProps extends PurchaseButtonPropsBase {
@@ -67,6 +68,7 @@ const PurchaseButton = ({
67
68
  disabled = false,
68
69
  className,
69
70
  buttonProps,
71
+ onFinish,
70
72
  }: CredentialPurchaseButtonProps | CertificatePurchaseButtonProps) => {
71
73
  const intl = useIntl();
72
74
  const { user, login } = useSession();
@@ -147,6 +149,7 @@ const PurchaseButton = ({
147
149
  enrollment={enrollment}
148
150
  orderGroup={orderGroup}
149
151
  course={course}
152
+ onFinish={onFinish}
150
153
  />
151
154
  </>
152
155
  );
@@ -1,5 +1,6 @@
1
1
  import { useEffect, useMemo, useRef, useState } from 'react';
2
2
  import { defineMessages, useIntl } from 'react-intl';
3
+ import { useQueryClient } from '@tanstack/react-query';
3
4
  import { Modal } from 'components/Modal';
4
5
  import {
5
6
  CourseLight,
@@ -49,13 +50,14 @@ const focusCurrentStep = (container: HTMLElement) => {
49
50
  }
50
51
  };
51
52
 
52
- interface SaleTunnelProps {
53
+ export interface SaleTunnelProps {
53
54
  isOpen: boolean;
54
55
  onClose: () => void;
55
56
  course?: CourseLight;
56
57
  enrollment?: Enrollment;
57
58
  product: CredentialProduct | CertificateProduct;
58
59
  orderGroup?: OrderGroup;
60
+ onFinish?: (order: Order) => void;
59
61
  }
60
62
 
61
63
  const SaleTunnel = ({
@@ -65,6 +67,7 @@ const SaleTunnel = ({
65
67
  onClose,
66
68
  enrollment,
67
69
  orderGroup,
70
+ onFinish,
68
71
  }: SaleTunnelProps) => {
69
72
  const intl = useIntl();
70
73
  const {
@@ -76,6 +79,7 @@ const SaleTunnel = ({
76
79
  const key = `${product.type === ProductType.CREDENTIAL ? course!.code : enrollment!.id}+${
77
80
  product.id
78
81
  }`;
82
+ const queryClient = useQueryClient();
79
83
 
80
84
  const [order, setOrder] = useState<Maybe<Order>>();
81
85
 
@@ -108,6 +112,8 @@ const SaleTunnel = ({
108
112
  // to update the ordersQuery cache
109
113
  invalidateOrders();
110
114
  refetchOmniscientOrders();
115
+ queryClient.invalidateQueries({ queryKey: ['user', 'enrollments'] });
116
+ onFinish?.(order!);
111
117
  },
112
118
  onExit: () => {
113
119
  handleModalClose();
@@ -102,7 +102,7 @@ describe('components/TeacherDashboardCourseList', () => {
102
102
  );
103
103
 
104
104
  expect(
105
- screen.getByRole('heading', { name: /One lesson about: How to cook birds/ }),
105
+ await screen.findByRole('heading', { name: /One lesson about: How to cook birds/ }),
106
106
  ).toBeInTheDocument();
107
107
  expect(
108
108
  screen.getByRole('heading', { name: /One lesson about: Let's dance, the online lesson/ }),
@@ -51,5 +51,6 @@ export const useCourseProductUnion = ({
51
51
  },
52
52
  perPage,
53
53
  errorGetMessage: messages.errorGet,
54
+ refetchOnInvalidation: false,
54
55
  });
55
56
  };
@@ -0,0 +1,16 @@
1
+ import { useQuery } from '@tanstack/react-query';
2
+ import { useEffect } from 'react';
3
+ import usePrevious from 'hooks/usePrevious';
4
+
5
+ export const useQueryKeyInvalidateListener = (queryKey: string[], callback: Function) => {
6
+ const { data: refreshFlag } = useQuery({
7
+ queryKey: [...queryKey, 'refresh-flag'],
8
+ queryFn: () => Math.random(),
9
+ });
10
+ const previousRefreshFlag = usePrevious(refreshFlag);
11
+ useEffect(() => {
12
+ if (previousRefreshFlag) {
13
+ callback();
14
+ }
15
+ }, [refreshFlag]);
16
+ };
@@ -4,6 +4,7 @@ import { MessageDescriptor, defineMessages, useIntl } from 'react-intl';
4
4
  import { Maybe } from 'yup';
5
5
  import { PaginatedResourceQuery, PaginatedResponse } from 'types/Joanie';
6
6
  import { PER_PAGE } from 'settings';
7
+ import { useQueryKeyInvalidateListener } from 'hooks/useQueryKeyInvalidateListener';
7
8
  import { syncIntegrityCount } from './utils/syncIntegrityCount';
8
9
  import { FetchEntityData } from './utils/fetchEntities';
9
10
  import { QueryConfig } from './utils/fetchEntity';
@@ -39,6 +40,7 @@ interface UseUnionResourceProps<DataA, DataB, FiltersA, FiltersB>
39
40
  queryAConfig: QueryConfig<DataA, FiltersA>;
40
41
  queryBConfig: QueryConfig<DataB, FiltersB>;
41
42
  errorGetMessage?: MessageDescriptor;
43
+ refetchOnInvalidation?: boolean;
42
44
  }
43
45
 
44
46
  /**
@@ -58,6 +60,7 @@ const useUnionResource = <
58
60
  queryBConfig,
59
61
  perPage = PER_PAGE.useUnionResources,
60
62
  errorGetMessage = messages.errorGet,
63
+ refetchOnInvalidation = true,
61
64
  }: UseUnionResourceProps<DataA, DataB, FiltersA, FiltersB>): UseUnionResourceReturns<
62
65
  DataA,
63
66
  DataB
@@ -69,7 +72,7 @@ const useUnionResource = <
69
72
  const [totalCount, setTotalCount] = useState<number | undefined>();
70
73
  const [error, setError] = useState<Maybe<string>>();
71
74
 
72
- // cursor is the total amount of entities what we whant to display.
75
+ // cursor is the total amount of entities what we want to display.
73
76
  const [cursor, setCursor] = useState(perPage);
74
77
 
75
78
  // integrityCount is the number of fetched entities A and B that are correctly ordered.
@@ -87,6 +90,20 @@ const useUnionResource = <
87
90
  const eofRef = useRef<Record<string, number>>(queryClient.getQueryData(eofQueryKey) ?? {});
88
91
  log('eof', eofRef.current);
89
92
 
93
+ const reset = () => {
94
+ setStack([]);
95
+ setPage(0);
96
+ setTotalCount(undefined);
97
+ setError(undefined);
98
+ setCursor(perPage);
99
+ setIntegrityCount(0);
100
+ };
101
+
102
+ if (refetchOnInvalidation) {
103
+ useQueryKeyInvalidateListener(queryAConfig.queryKey, reset);
104
+ useQueryKeyInvalidateListener(queryBConfig.queryKey, reset);
105
+ }
106
+
90
107
  useEffect(() => {
91
108
  async function fetchNewPage() {
92
109
  const {
@@ -132,7 +149,7 @@ const useUnionResource = <
132
149
  setIsSyncing(true);
133
150
  fetchNewPage();
134
151
  }
135
- }, [cursor]);
152
+ }, [cursor, stack.length]); // stack.length is added in the dependency array to force a new fetch on reset.
136
153
 
137
154
  const cursorToUse = Math.min(cursor, integrityCount);
138
155
  const next = () => {
@@ -68,5 +68,6 @@ export const useOrdersEnrollments = ({
68
68
  },
69
69
  perPage,
70
70
  errorGetMessage: messages.errorGet,
71
+ refetchOnInvalidation: false,
71
72
  });
72
73
  };
@@ -27,19 +27,16 @@ describe('CreditCardHelper', () => {
27
27
  });
28
28
 
29
29
  it('is soon expired', () => {
30
- const refDate = new Date();
31
- refDate.setMonth(refDate.getMonth() + 1);
32
- refDate.setDate(1);
33
- const futureLessThan3Months = faker.date.future({
30
+ const expirationDate = faker.date.future({
31
+ refDate: new Date(),
34
32
  years: 2.99 / 12,
35
- refDate,
36
33
  });
37
34
 
38
35
  expect(
39
36
  CreditCardHelper.getExpirationState(
40
37
  CreditCardFactory({
41
- expiration_month: futureLessThan3Months.getMonth() + 1,
42
- expiration_year: futureLessThan3Months.getFullYear(),
38
+ expiration_month: expirationDate.getMonth() + 1,
39
+ expiration_year: expirationDate.getFullYear(),
43
40
  }).one(),
44
41
  ),
45
42
  ).toBe(CreditCardExpirationStatus.SOON);
@@ -1,7 +1,8 @@
1
1
  import { IntlProvider } from 'react-intl';
2
- import { render, screen } from '@testing-library/react';
3
- import { QueryClientProvider } from '@tanstack/react-query';
2
+ import { render, screen, waitForElementToBeRemoved } from '@testing-library/react';
3
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
4
4
  import fetchMock from 'fetch-mock';
5
+ import userEvent from '@testing-library/user-event';
5
6
  import { CertificateProduct, CourseLight, OrderState, ProductType } from 'types/Joanie';
6
7
  import {
7
8
  CourseStateFactory,
@@ -19,6 +20,12 @@ import {
19
20
  import { Priority } from 'types';
20
21
  import { createTestQueryClient } from 'utils/test/createTestQueryClient';
21
22
  import JoanieSessionProvider from 'contexts/SessionContext/JoanieSessionProvider';
23
+ import { SessionProvider } from 'contexts/SessionContext';
24
+ import { DashboardTest } from 'widgets/Dashboard/components/DashboardTest';
25
+ import { LearnerDashboardPaths } from 'widgets/Dashboard/utils/learnerRouteMessages';
26
+ import { expectNoSpinner } from 'utils/test/expectSpinner';
27
+ import { PER_PAGE } from 'settings';
28
+ import { SaleTunnelProps } from 'components/SaleTunnel';
22
29
  import ProductCertificateFooter, { ProductCertificateFooterProps } from '.';
23
30
 
24
31
  jest.mock('utils/context', () => ({
@@ -28,6 +35,24 @@ jest.mock('utils/context', () => ({
28
35
  joanie_backend: { endpoint: 'https://joanie.endpoint.test' },
29
36
  }).one(),
30
37
  }));
38
+ jest.mock('components/SaleTunnel', () => ({
39
+ __esModule: true,
40
+ default: ({ isOpen, onFinish }: SaleTunnelProps) => {
41
+ const React = require('react');
42
+ const Factories = require('utils/test/factories/joanie');
43
+ // Automatically call onFinish() callback after 100ms when the SaleTunnel is opened to simulate a payment.
44
+ React.useEffect(() => {
45
+ if (!isOpen) {
46
+ return;
47
+ }
48
+ setTimeout(() => {
49
+ const order = Factories.CertificateOrderWithOneClickPaymentFactory().one();
50
+ onFinish?.(order);
51
+ }, 100);
52
+ }, [isOpen]);
53
+ return <div data-testid="SaleTunnelMock" />;
54
+ },
55
+ }));
31
56
 
32
57
  describe('<ProductCertificateFooter/>', () => {
33
58
  const Wrapper = ({ product, enrollment }: ProductCertificateFooterProps) => (
@@ -165,4 +190,66 @@ describe('<ProductCertificateFooter/>', () => {
165
190
  expect(await screen.queryByRole('button', { name: 'Download' })).not.toBeInTheDocument();
166
191
  expect(screen.queryByTestId('PurchaseButton__cta')).not.toBeInTheDocument();
167
192
  });
193
+
194
+ // From https://github.com/openfun/richie/issues/2237
195
+ it('should hide purchase button after payment', async () => {
196
+ const TestWrapper = ({ client }: { client?: QueryClient }) => {
197
+ const user = UserFactory().one();
198
+ return (
199
+ <QueryClientProvider client={client ?? createTestQueryClient({ user })}>
200
+ <IntlProvider locale="en">
201
+ {/* <HistoryContext.Provider value={makeHistoryOf({})}> */}
202
+ <SessionProvider>
203
+ <DashboardTest initialRoute={LearnerDashboardPaths.COURSES} />
204
+ </SessionProvider>
205
+ {/* </HistoryContext.Provider> */}
206
+ </IntlProvider>
207
+ </QueryClientProvider>
208
+ );
209
+ };
210
+
211
+ const client = createTestQueryClient({ user: true });
212
+ fetchMock.get(
213
+ `https://joanie.endpoint.test/api/v1.0/orders/?product_type=credential&state_exclude=canceled&page=1&page_size=${PER_PAGE.useOrdersEnrollments}`,
214
+ {
215
+ results: [],
216
+ next: null,
217
+ previous: null,
218
+ count: 0,
219
+ },
220
+ );
221
+
222
+ const enrollment = EnrollmentFactory({
223
+ course_run: CourseRunFactory({
224
+ state: CourseStateFactory({ priority: Priority.ONGOING_OPEN }).one(),
225
+ course,
226
+ }).one(),
227
+ }).one();
228
+ enrollment.product_relations[0].product = CertificateProductFactory().one();
229
+
230
+ fetchMock.get(
231
+ `https://joanie.endpoint.test/api/v1.0/enrollments/?was_created_by_order=false&page=1&page_size=${PER_PAGE.useOrdersEnrollments}`,
232
+ {
233
+ results: [enrollment],
234
+ next: null,
235
+ previous: null,
236
+ count: 1,
237
+ },
238
+ );
239
+
240
+ render(<TestWrapper client={client} />);
241
+ const user = userEvent.setup();
242
+ await expectNoSpinner('Loading orders and enrollments...');
243
+ await screen.findByRole('heading', {
244
+ name: enrollment.course_run.course.title,
245
+ level: 5,
246
+ });
247
+
248
+ // Click on the purchase button, memo: the SaleTunnel is mocked at the top of this file.
249
+ const purchaseButton = screen.getByTestId('PurchaseButton__cta');
250
+ await user.click(purchaseButton);
251
+
252
+ // Then the onFinish() callback of the SaleTunnel is automatically called via the mock.
253
+ await waitForElementToBeRemoved(screen.queryByTestId('PurchaseButton__cta'));
254
+ });
168
255
  });
@@ -1,4 +1,5 @@
1
1
  import { FormattedMessage, defineMessages } from 'react-intl';
2
+ import { useState } from 'react';
2
3
  import PurchaseButton from 'components/PurchaseButton';
3
4
  import { Icon, IconTypeEnum } from 'components/Icon';
4
5
  import { CertificateProduct, Enrollment, ProductType } from 'types/Joanie';
@@ -35,7 +36,9 @@ const ProductCertificateFooter = ({ product, enrollment }: ProductCertificateFoo
35
36
  if (product.type !== ProductType.CERTIFICATE) {
36
37
  return null;
37
38
  }
38
- const activeOrder = getActiveEnrollmentOrder(enrollment.orders || [], product.id);
39
+ const [activeOrder, setActiveOrder] = useState(
40
+ getActiveEnrollmentOrder(enrollment.orders || [], product.id),
41
+ );
39
42
  const { item: certificate } = useCertificate(activeOrder?.certificate_id);
40
43
 
41
44
  // The course run is no longer available
@@ -69,6 +72,14 @@ const ProductCertificateFooter = ({ product, enrollment }: ProductCertificateFoo
69
72
  className="dashboard-item__button"
70
73
  product={product}
71
74
  enrollment={enrollment}
75
+ onFinish={(order) => {
76
+ /**
77
+ * As we do not refetch enrollments in DashboardCourses after SaleTunnel cache invalidation ( to avoid
78
+ * scroll reset - and SaleTunnel modal unmounting too early caused by list reset ) we need to manually
79
+ * update the active order in the enrollment in order to hide the buy button and display the download button.
80
+ */
81
+ setActiveOrder(order);
82
+ }}
72
83
  />
73
84
  )}
74
85
  </div>
@@ -0,0 +1,244 @@
1
+ import { render, screen } from '@testing-library/react';
2
+ import { PropsWithChildren } from 'react';
3
+ import { MemoryRouter } from 'react-router-dom';
4
+ import { QueryClientProvider } from '@tanstack/react-query';
5
+ import { IntlProvider } from 'react-intl';
6
+ import fetchMock from 'fetch-mock';
7
+ import { faker } from '@faker-js/faker';
8
+ import queryString from 'query-string';
9
+ import { RichieContextFactory as mockRichieContextFactory } from 'utils/test/factories/richie';
10
+ import JoanieSessionProvider from 'contexts/SessionContext/JoanieSessionProvider';
11
+ import { createTestQueryClient } from 'utils/test/createTestQueryClient';
12
+ import { PER_PAGE } from 'settings';
13
+ import { ContractResourceQuery, ContractState } from 'types/Joanie';
14
+ import { ContractFactory } from 'utils/test/factories/joanie';
15
+ import { ContractActions } from 'utils/AbilitiesHelper/types';
16
+ import { MenuLink } from '../..';
17
+ import ContractNavLink from '.';
18
+
19
+ jest.mock('utils/context', () => ({
20
+ __esModule: true,
21
+ default: mockRichieContextFactory({
22
+ authentication: { backend: 'fonzie', endpoint: 'https://demo.endpoint' },
23
+ joanie_backend: { endpoint: 'https://joanie.endpoint' },
24
+ }).one(),
25
+ }));
26
+
27
+ describe('<ContractNavLink />', () => {
28
+ const Wrapper = ({ children }: PropsWithChildren) => (
29
+ <QueryClientProvider client={createTestQueryClient({ user: true })}>
30
+ <IntlProvider locale="en">
31
+ <JoanieSessionProvider>
32
+ <MemoryRouter>{children}</MemoryRouter>
33
+ </JoanieSessionProvider>
34
+ </IntlProvider>
35
+ </QueryClientProvider>
36
+ );
37
+
38
+ beforeEach(() => {
39
+ // JoanieSessionProvider queries
40
+ fetchMock.get('https://joanie.endpoint/api/v1.0/addresses/', []);
41
+ fetchMock.get('https://joanie.endpoint/api/v1.0/orders/', []);
42
+ fetchMock.get('https://joanie.endpoint/api/v1.0/credit-cards/', []);
43
+ });
44
+
45
+ afterEach(() => {
46
+ fetchMock.restore();
47
+ });
48
+
49
+ it('should render a ContractNavLink with route and label when neither organizationId and courseProductRelationId are given', () => {
50
+ const link: MenuLink = {
51
+ to: '/dummy/url/',
52
+ label: 'My contract navigation link',
53
+ };
54
+
55
+ render(
56
+ <Wrapper>
57
+ <ContractNavLink link={link} />
58
+ </Wrapper>,
59
+ );
60
+
61
+ expect(screen.getByRole('link', { name: 'My contract navigation link' })).toBeInTheDocument();
62
+ expect(screen.queryByTestId('badge')).not.toBeInTheDocument();
63
+ });
64
+
65
+ describe('without sign ability', () => {
66
+ const contractAbilities = { [ContractActions.SIGN]: false };
67
+ it.each([
68
+ {
69
+ organizationId: faker.string.uuid(),
70
+ courseProductRelationId: undefined,
71
+ },
72
+ {
73
+ organizationId: faker.string.uuid(),
74
+ courseProductRelationId: faker.string.uuid(),
75
+ },
76
+ {
77
+ organizationId: undefined,
78
+ courseProductRelationId: faker.string.uuid(),
79
+ },
80
+ {
81
+ organizationId: undefined,
82
+ courseProductRelationId: undefined,
83
+ },
84
+ ])(
85
+ 'should never render Badge for organizationId: $organizationId and courseProductId: $courseProductRelationId',
86
+ async ({ organizationId, courseProductRelationId }) => {
87
+ let contractQueryParams: ContractResourceQuery = {
88
+ signature_state: ContractState.LEARNER_SIGNED,
89
+ page: 1,
90
+ page_size: PER_PAGE.teacherContractList,
91
+ };
92
+ if (courseProductRelationId) {
93
+ contractQueryParams = {
94
+ course_product_relation_id: courseProductRelationId,
95
+ ...contractQueryParams,
96
+ };
97
+ }
98
+
99
+ fetchMock.get(
100
+ `https://joanie.endpoint/api/v1.0/organizations/${organizationId}/contracts/?${queryString.stringify(
101
+ contractQueryParams,
102
+ { sort: false },
103
+ )}`,
104
+ {
105
+ count: 1,
106
+ next: null,
107
+ previous: null,
108
+ results: [ContractFactory({ abilities: contractAbilities }).one()],
109
+ },
110
+ );
111
+ render(
112
+ <Wrapper>
113
+ <ContractNavLink
114
+ link={{
115
+ to: '/dummy/url/',
116
+ label: 'My contract navigation link',
117
+ }}
118
+ organizationId={organizationId}
119
+ courseProductRelationId={courseProductRelationId}
120
+ />
121
+ </Wrapper>,
122
+ );
123
+
124
+ expect(
125
+ screen.getByRole('link', { name: 'My contract navigation link' }),
126
+ ).toBeInTheDocument();
127
+ expect(screen.queryByTestId('badge')).not.toBeInTheDocument();
128
+ },
129
+ );
130
+ });
131
+
132
+ describe('with sign ability', () => {
133
+ const contractAbilities = { [ContractActions.SIGN]: true };
134
+ it.each([
135
+ // with 1 contracts to sign
136
+ {
137
+ organizationId: faker.string.uuid(),
138
+ courseProductRelationId: undefined,
139
+ nbContractsToSign: 1,
140
+ expectedBadgeCount: 1,
141
+ },
142
+ {
143
+ organizationId: faker.string.uuid(),
144
+ courseProductRelationId: faker.string.uuid(),
145
+ nbContractsToSign: 1,
146
+ expectedBadgeCount: 1,
147
+ },
148
+ {
149
+ organizationId: undefined,
150
+ courseProductRelationId: faker.string.uuid(),
151
+ nbContractsToSign: 1,
152
+ expectedBadgeCount: undefined,
153
+ },
154
+ {
155
+ organizationId: undefined,
156
+ courseProductRelationId: undefined,
157
+ nbContractsToSign: 1,
158
+ expectedBadgeCount: undefined,
159
+ },
160
+
161
+ // with 0 contracts to sign
162
+ {
163
+ organizationId: faker.string.uuid(),
164
+ courseProductRelationId: undefined,
165
+ nbContractsToSign: 0,
166
+ expectedBadgeCount: undefined,
167
+ },
168
+ {
169
+ organizationId: faker.string.uuid(),
170
+ courseProductRelationId: faker.string.uuid(),
171
+ nbContractsToSign: 0,
172
+ expectedBadgeCount: undefined,
173
+ },
174
+ {
175
+ organizationId: undefined,
176
+ courseProductRelationId: faker.string.uuid(),
177
+ nbContractsToSign: 0,
178
+ expectedBadgeCount: undefined,
179
+ },
180
+ {
181
+ organizationId: undefined,
182
+ courseProductRelationId: undefined,
183
+ nbContractsToSign: 0,
184
+ expectedBadgeCount: undefined,
185
+ },
186
+ ])(
187
+ 'should render Badge (count: $expectedBadgeCount) for nb contracts to sign: $nbContractsToSign, organizationId: $organizationId and courseProductId: $courseProductRelationId',
188
+ async ({
189
+ nbContractsToSign,
190
+ organizationId,
191
+ courseProductRelationId,
192
+ expectedBadgeCount,
193
+ }) => {
194
+ let contractQueryParams: ContractResourceQuery = {
195
+ signature_state: ContractState.LEARNER_SIGNED,
196
+ page: 1,
197
+ page_size: PER_PAGE.teacherContractList,
198
+ };
199
+ if (courseProductRelationId) {
200
+ contractQueryParams = {
201
+ course_product_relation_id: courseProductRelationId,
202
+ ...contractQueryParams,
203
+ };
204
+ }
205
+
206
+ fetchMock.get(
207
+ `https://joanie.endpoint/api/v1.0/organizations/${organizationId}/contracts/?${queryString.stringify(
208
+ contractQueryParams,
209
+ { sort: false },
210
+ )}`,
211
+ {
212
+ count: nbContractsToSign,
213
+ next: null,
214
+ previous: null,
215
+ results: [ContractFactory({ abilities: contractAbilities }).one()],
216
+ },
217
+ );
218
+ render(
219
+ <Wrapper>
220
+ <ContractNavLink
221
+ link={{
222
+ to: '/dummy/url/',
223
+ label: 'My contract navigation link',
224
+ }}
225
+ organizationId={organizationId}
226
+ courseProductRelationId={courseProductRelationId}
227
+ />
228
+ </Wrapper>,
229
+ );
230
+
231
+ expect(
232
+ screen.getByRole('link', { name: 'My contract navigation link' }),
233
+ ).toBeInTheDocument();
234
+ if (expectedBadgeCount === undefined) {
235
+ expect(screen.queryByTestId('badge')).not.toBeInTheDocument();
236
+ } else {
237
+ const $badge = await screen.findByTestId('badge');
238
+ expect($badge).toBeInTheDocument();
239
+ expect($badge).toHaveTextContent(`${expectedBadgeCount}`);
240
+ }
241
+ },
242
+ );
243
+ });
244
+ });
@@ -0,0 +1,47 @@
1
+ import { createSearchParams } from 'react-router-dom';
2
+ import { useMemo } from 'react';
3
+ import { MenuLink } from 'widgets/Dashboard/components/DashboardSidebar';
4
+ import { ContractState, CourseProductRelation, Organization } from 'types/Joanie';
5
+ import useTeacherPendingContractsCount from 'hooks/useTeacherPendingContractsCount';
6
+ import { ContractActions } from 'utils/AbilitiesHelper/types';
7
+ import useContractAbilities from 'hooks/useContractAbilities';
8
+ import MenuNavLink from '../MenuNavLink';
9
+
10
+ interface ContractNavLinkProps {
11
+ link: MenuLink;
12
+ organizationId?: Organization['id'];
13
+ courseProductRelationId?: CourseProductRelation['id'];
14
+ }
15
+
16
+ const ContractNavLink = ({
17
+ link,
18
+ organizationId,
19
+ courseProductRelationId,
20
+ }: ContractNavLinkProps) => {
21
+ const { contracts: pendingContracts, pendingContractCount } = useTeacherPendingContractsCount({
22
+ organizationId,
23
+ courseProductRelationId,
24
+ });
25
+ const contractAbilities = useContractAbilities(pendingContracts);
26
+ const canSignContracts = contractAbilities.can(ContractActions.SIGN);
27
+ const hasContractsToSign = useMemo(
28
+ () => canSignContracts && pendingContractCount > 0,
29
+ [canSignContracts, pendingContractCount],
30
+ );
31
+ const searchParams = useMemo(() => {
32
+ if (hasContractsToSign) {
33
+ return createSearchParams({ signature_state: ContractState.LEARNER_SIGNED });
34
+ }
35
+
36
+ return createSearchParams({ signature_state: ContractState.SIGNED });
37
+ }, [hasContractsToSign]);
38
+
39
+ return (
40
+ <MenuNavLink
41
+ link={{ ...link, to: `${link.to}?${searchParams.toString()}` }}
42
+ badgeCount={hasContractsToSign ? pendingContractCount : undefined}
43
+ />
44
+ );
45
+ };
46
+
47
+ export default ContractNavLink;
@@ -0,0 +1,40 @@
1
+ import { render, screen } from '@testing-library/react';
2
+ import { PropsWithChildren } from 'react';
3
+ import { MemoryRouter } from 'react-router-dom';
4
+ import { MenuLink } from '../..';
5
+ import MenuNavLink from '.';
6
+
7
+ describe('<MenuNavLink />', () => {
8
+ const Wrapper = ({ children }: PropsWithChildren) => <MemoryRouter>{children} </MemoryRouter>;
9
+ it('should render a MenuNavLink with route and label', () => {
10
+ const link: MenuLink = {
11
+ to: '/dummy/url/',
12
+ label: 'My navigation link',
13
+ };
14
+
15
+ render(
16
+ <Wrapper>
17
+ <MenuNavLink link={link} />
18
+ </Wrapper>,
19
+ );
20
+
21
+ expect(screen.getByRole('link', { name: 'My navigation link' })).toBeInTheDocument();
22
+ expect(screen.queryByTestId('badge')).not.toBeInTheDocument();
23
+ });
24
+
25
+ it('should render a MenuNavLink with a badge', () => {
26
+ const link: MenuLink = {
27
+ to: '/dummy/url/',
28
+ label: 'My navigation link',
29
+ };
30
+
31
+ render(
32
+ <Wrapper>
33
+ <MenuNavLink link={link} badgeCount={999} />
34
+ </Wrapper>,
35
+ );
36
+
37
+ expect(screen.getByRole('link', { name: 'My navigation link' })).toBeInTheDocument();
38
+ expect(screen.getByText('999')).toBeInTheDocument();
39
+ });
40
+ });
@@ -0,0 +1,28 @@
1
+ import classNames from 'classnames';
2
+ import { NavLink, useLocation } from 'react-router-dom';
3
+ import Badge from 'components/Badge';
4
+ import { MenuLink } from '../..';
5
+ import { isMenuLinkActive } from '../../utils';
6
+
7
+ interface MenuNavLinkProps {
8
+ link: MenuLink;
9
+ badgeCount?: number;
10
+ }
11
+
12
+ const MenuNavLink = ({ link, badgeCount }: MenuNavLinkProps) => {
13
+ const location = useLocation();
14
+ return (
15
+ <li
16
+ className={classNames('dashboard-sidebar__container__nav__item', {
17
+ active: isMenuLinkActive(link.to, location),
18
+ })}
19
+ >
20
+ <NavLink to={link.to} end>
21
+ {link.label}
22
+ </NavLink>
23
+ {badgeCount && <Badge color="primary">{badgeCount}</Badge>}
24
+ </li>
25
+ );
26
+ };
27
+
28
+ export default MenuNavLink;
@@ -2,7 +2,7 @@ import { Meta, StoryObj } from '@storybook/react';
2
2
  import { createMemoryRouter, RouterProvider } from 'react-router-dom';
3
3
  import { UserFactory } from 'utils/test/factories/richie';
4
4
  import { StorybookHelper } from 'utils/StorybookHelper';
5
- import Badge from 'components/Badge';
5
+ import MenuNavLink from './components/MenuNavLink';
6
6
  import { DashboardSidebar } from '.';
7
7
 
8
8
  export default {
@@ -19,7 +19,12 @@ export default {
19
19
  {
20
20
  to: '/test/again',
21
21
  label: 'An other menu link',
22
- badge: <Badge color="primary">999</Badge>,
22
+ component: (
23
+ <MenuNavLink
24
+ link={{ to: '/test/again', label: 'An other menu link' }}
25
+ badgeCount={999}
26
+ />
27
+ ),
23
28
  },
24
29
  ]}
25
30
  header="Dashboard story header"
@@ -1,14 +1,13 @@
1
- import { matchPath, NavLink, resolvePath, useLocation } from 'react-router-dom';
2
- import { PropsWithChildren, ReactNode, useCallback } from 'react';
3
- import classNames from 'classnames';
1
+ import { Fragment, PropsWithChildren, ReactNode } from 'react';
4
2
  import { useSession } from 'contexts/SessionContext';
5
3
  import { DashboardAvatar } from 'widgets/Dashboard/components/DashboardAvatar';
6
4
  import NavigationSelect from './components/NavigationSelect';
5
+ import MenuNavLink from './components/MenuNavLink';
7
6
 
8
7
  export interface MenuLink {
9
8
  to: string;
10
9
  label: string;
11
- badge?: ReactNode;
10
+ component?: ReactNode;
12
11
  }
13
12
 
14
13
  export interface DashboardSidebarProps extends PropsWithChildren {
@@ -28,15 +27,7 @@ export const DashboardSidebar = ({
28
27
  avatar,
29
28
  }: DashboardSidebarProps) => {
30
29
  const { user } = useSession();
31
- const location = useLocation();
32
30
  const classes = ['dashboard-sidebar'];
33
- const isActive = useCallback(
34
- (to: string) => {
35
- const path = resolvePath(to).pathname;
36
- return !!matchPath({ path, end: true }, location.pathname);
37
- },
38
- [location],
39
- );
40
31
 
41
32
  return (
42
33
  <aside className={classes.join(' ')} data-testid="dashboard__sidebar">
@@ -54,19 +45,13 @@ export const DashboardSidebar = ({
54
45
  </div>
55
46
 
56
47
  <ul className="dashboard-sidebar__container__nav">
57
- {menuLinks.map((link) => (
58
- <li
59
- key={link.to}
60
- className={classNames('dashboard-sidebar__container__nav__item', {
61
- active: isActive(link.to),
62
- })}
63
- >
64
- <NavLink to={link.to} end>
65
- {link.label}
66
- </NavLink>
67
- {link.badge}
68
- </li>
69
- ))}
48
+ {menuLinks.map((link) =>
49
+ link.component ? (
50
+ <Fragment key={link.to}>{link.component}</Fragment>
51
+ ) : (
52
+ <MenuNavLink link={link} key={link.to} />
53
+ ),
54
+ )}
70
55
  </ul>
71
56
  </div>
72
57
  {children}
@@ -0,0 +1,6 @@
1
+ import { Location, matchPath, resolvePath } from 'react-router-dom';
2
+
3
+ export const isMenuLinkActive = (to: string, location: Location) => {
4
+ const path = resolvePath(to).pathname;
5
+ return !!matchPath({ path, end: true }, location.pathname);
6
+ };
@@ -1,7 +1,7 @@
1
1
  import { faker } from '@faker-js/faker';
2
2
  import { CunninghamProvider } from '@openfun/cunningham-react';
3
3
  import { QueryClientProvider } from '@tanstack/react-query';
4
- import { render, screen } from '@testing-library/react';
4
+ import { render, screen, waitFor } from '@testing-library/react';
5
5
  import fetchMock from 'fetch-mock';
6
6
  import { IntlProvider } from 'react-intl';
7
7
  import { MemoryRouter, Route, Routes } from 'react-router-dom';
@@ -111,7 +111,9 @@ describe('<TeacherDashboardOrganizationSidebar />', () => {
111
111
 
112
112
  // It should display contract link with badge next to it displaying the number of contracts to sign
113
113
  const contractLink = screen.getByRole('link', { name: 'Contracts' });
114
- expect(contractLink!.nextSibling).toHaveTextContent(contractToSignCount.toString());
114
+ await waitFor(() => {
115
+ expect(contractLink!.nextSibling).toHaveTextContent(contractToSignCount.toString());
116
+ });
115
117
  expect(contractLink).toHaveAttribute(
116
118
  'href',
117
119
  '/teacher/organizations/' + organization.id + '/contracts?signature_state=half_signed',
@@ -1,20 +1,15 @@
1
- import { useMemo } from 'react';
2
1
  import { defineMessages, FormattedMessage, useIntl } from 'react-intl';
3
- import { createSearchParams, useParams } from 'react-router-dom';
4
- import Badge from 'components/Badge';
2
+ import { useParams } from 'react-router-dom';
5
3
  import { Spinner } from 'components/Spinner';
6
4
  import { useOrganization } from 'hooks/useOrganizations';
7
- import { ContractState } from 'types/Joanie';
8
5
  import { DashboardSidebar, MenuLink } from 'widgets/Dashboard/components/DashboardSidebar';
9
6
  import {
10
7
  getDashboardRouteLabel,
11
8
  getDashboardRoutePath,
12
9
  } from 'widgets/Dashboard/utils/dashboardRoutes';
13
10
  import { TeacherDashboardPaths } from 'widgets/Dashboard/utils/teacherRouteMessages';
14
- import useTeacherPendingContractsCount from 'hooks/useTeacherPendingContractsCount';
15
- import useContractAbilities from 'hooks/useContractAbilities';
16
- import { ContractActions } from 'utils/AbilitiesHelper/types';
17
11
  import { DashboardAvatar, DashboardAvatarVariantEnum } from '../DashboardAvatar';
12
+ import ContractNavLink from '../DashboardSidebar/components/ContractNavLink';
18
13
 
19
14
  const messages = defineMessages({
20
15
  subHeader: {
@@ -42,13 +37,6 @@ export const TeacherDashboardOrganizationSidebar = () => {
42
37
  states: { fetching },
43
38
  } = useOrganization(organizationId);
44
39
 
45
- const { contracts: pendingContracts, pendingContractCount } = useTeacherPendingContractsCount({
46
- organizationId,
47
- courseProductRelationId,
48
- });
49
- const contractAbilities = useContractAbilities(pendingContracts);
50
- const canSignContracts = contractAbilities.can(ContractActions.SIGN);
51
-
52
40
  const getMenuLinkFromPath = (basePath: TeacherDashboardPaths) => {
53
41
  const path = getRoutePath(basePath, { organizationId });
54
42
 
@@ -57,30 +45,23 @@ export const TeacherDashboardOrganizationSidebar = () => {
57
45
  label: getRouteLabel(basePath),
58
46
  };
59
47
 
60
- // For the contracts link, we want to display the number of contracts if needed and set
61
- // the correct filter depending on the user's abilities
62
48
  if (basePath === TeacherDashboardPaths.ORGANIZATION_CONTRACTS) {
63
- if (canSignContracts && pendingContractCount > 0) {
64
- const searchParams = createSearchParams({ signature_state: ContractState.LEARNER_SIGNED });
65
- menuLink.badge = <Badge color="primary">{pendingContractCount}</Badge>;
66
- menuLink.to = `${path}?${searchParams.toString()}`;
67
- } else {
68
- const searchParams = createSearchParams({ signature_state: ContractState.SIGNED });
69
- menuLink.to = `${path}?${searchParams.toString()}`;
70
- }
49
+ menuLink.component = (
50
+ <ContractNavLink
51
+ link={menuLink}
52
+ organizationId={organizationId}
53
+ courseProductRelationId={courseProductRelationId}
54
+ />
55
+ );
71
56
  }
72
57
 
73
58
  return menuLink;
74
59
  };
75
60
 
76
- const links = useMemo(
77
- () =>
78
- [
79
- TeacherDashboardPaths.ORGANIZATION_COURSES,
80
- TeacherDashboardPaths.ORGANIZATION_CONTRACTS,
81
- ].map(getMenuLinkFromPath),
82
- [pendingContractCount, canSignContracts],
83
- );
61
+ const links = [
62
+ TeacherDashboardPaths.ORGANIZATION_COURSES,
63
+ TeacherDashboardPaths.ORGANIZATION_CONTRACTS,
64
+ ].map(getMenuLinkFromPath);
84
65
 
85
66
  if (fetching) {
86
67
  return (
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "richie-education",
3
- "version": "2.25.0-b2.dev35",
3
+ "version": "2.25.0-b2.dev42",
4
4
  "description": "A CMS to build learning portals for Open Education",
5
5
  "main": "sandbox/manage.py",
6
6
  "scripts": {
@@ -38,20 +38,20 @@
38
38
  "not dead"
39
39
  ],
40
40
  "dependencies": {
41
- "@babel/core": "7.23.7",
41
+ "@babel/core": "7.23.9",
42
42
  "@babel/plugin-syntax-dynamic-import": "7.8.3",
43
43
  "@babel/plugin-transform-modules-commonjs": "7.23.3",
44
- "@babel/preset-env": "7.23.8",
44
+ "@babel/preset-env": "7.23.9",
45
45
  "@babel/preset-react": "7.23.3",
46
46
  "@babel/preset-typescript": "7.23.3",
47
- "@faker-js/faker": "8.3.1",
48
- "@formatjs/cli": "6.2.6",
47
+ "@faker-js/faker": "8.4.0",
48
+ "@formatjs/cli": "6.2.7",
49
49
  "@formatjs/intl-relativetimeformat": "11.2.12",
50
50
  "@hookform/resolvers": "3.3.4",
51
51
  "@openfun/cunningham-react": "2.4.0",
52
52
  "@openfun/cunningham-tokens": "2.1.0",
53
- "@sentry/browser": "7.94.1",
54
- "@sentry/types": "7.94.1",
53
+ "@sentry/browser": "7.98.0",
54
+ "@sentry/types": "7.98.0",
55
55
  "@storybook/addon-actions": "7.6.10",
56
56
  "@storybook/addon-essentials": "7.6.10",
57
57
  "@storybook/addon-interactions": "7.6.10",
@@ -64,7 +64,7 @@
64
64
  "@tanstack/react-query": "5.17.19",
65
65
  "@tanstack/react-query-persist-client": "5.17.19",
66
66
  "@testing-library/dom": "9.3.4",
67
- "@testing-library/jest-dom": "6.2.1",
67
+ "@testing-library/jest-dom": "6.4.0",
68
68
  "@testing-library/react": "14.1.2",
69
69
  "@testing-library/user-event": "14.5.2",
70
70
  "@types/fetch-mock": "7.3.8",
@@ -78,9 +78,9 @@
78
78
  "@types/react-autosuggest": "10.1.11",
79
79
  "@types/react-dom": "18.2.18",
80
80
  "@types/react-modal": "3.16.3",
81
- "@types/uuid": "9.0.7",
82
- "@typescript-eslint/eslint-plugin": "6.19.1",
83
- "@typescript-eslint/parser": "6.19.1",
81
+ "@types/uuid": "9.0.8",
82
+ "@typescript-eslint/eslint-plugin": "6.20.0",
83
+ "@typescript-eslint/parser": "6.20.0",
84
84
  "babel-jest": "29.7.0",
85
85
  "babel-loader": "9.1.3",
86
86
  "babel-plugin-react-intl": "8.2.25",
@@ -95,7 +95,7 @@
95
95
  "eslint-config-prettier": "9.1.0",
96
96
  "eslint-import-resolver-webpack": "0.13.8",
97
97
  "eslint-plugin-compat": "4.2.0",
98
- "eslint-plugin-formatjs": "4.12.1",
98
+ "eslint-plugin-formatjs": "4.12.2",
99
99
  "eslint-plugin-import": "2.29.1",
100
100
  "eslint-plugin-jsx-a11y": "6.8.0",
101
101
  "eslint-plugin-prettier": "5.1.3",
@@ -113,7 +113,7 @@
113
113
  "js-cookie": "3.0.5",
114
114
  "lodash-es": "4.17.21",
115
115
  "mdn-polyfills": "5.20.0",
116
- "msw": "2.1.4",
116
+ "msw": "2.1.5",
117
117
  "node-fetch": ">2.6.6 <3",
118
118
  "nodemon": "3.0.3",
119
119
  "prettier": "3.2.4",
@@ -122,7 +122,7 @@
122
122
  "react-autosuggest": "10.1.0",
123
123
  "react-dom": "18.2.0",
124
124
  "react-hook-form": "7.49.3",
125
- "react-intl": "6.6.1",
125
+ "react-intl": "6.6.2",
126
126
  "react-modal": "3.16.1",
127
127
  "react-router-dom": "6.21.3",
128
128
  "sass": "1.70.0",
@@ -131,7 +131,7 @@
131
131
  "tsconfig-paths-webpack-plugin": "4.1.0",
132
132
  "typescript": "5.3.3",
133
133
  "uuid": "9.0.1",
134
- "webpack": "5.89.0",
134
+ "webpack": "5.90.0",
135
135
  "webpack-cli": "5.1.4",
136
136
  "whatwg-fetch": "3.6.20",
137
137
  "xhr-mock": "2.5.1",