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

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.
@@ -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>
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.dev41",
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",