Skip to content
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

feat: Conditionally render expiring learner credit alerts and modals #1081

Merged
merged 6 commits into from
May 22, 2024
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
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ Factory.define('enterpriseCustomer')
.attr('hide_labor_market_data', false)
.attr('enable_learner_portal', true)
.attr('enable_data_sharing_consent', true)
.attr('disable_expiry_messaging_for_learner_credit', false)
.attr('admin_users', [{ email: faker.internet.email() }])
.attr('disable_search', false)
.attr('enable_one_academy', false)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,18 @@ import {
getEnterpriseBudgetExpiringModalCookieName,
} from '../utils';
import useExpirationMetadata from './useExpirationMetadata';
import { useEnterpriseCustomer } from '../../../app/data';

const useExpiry = (enterpriseId, budget, modalOpen, modalClose, alertOpen, alertClose) => {
const [alert, setAlert] = useState(null);
const [expirationThreshold, setExpirationThreshold] = useState(null);
const [modal, setModal] = useState(null);
const { thresholdKey, threshold } = useExpirationMetadata(budget?.end);
const { data: { disableExpiryMessagingForLearnerCredit } } = useEnterpriseCustomer();
const hasExpiryNotificationsDisabled = budget.isNonExpiredBudget && disableExpiryMessagingForLearnerCredit;

useEffect(() => {
if (!budget || thresholdKey === null) {
if (!budget || thresholdKey === null || hasExpiryNotificationsDisabled) {
return;
}

Expand Down Expand Up @@ -45,7 +48,7 @@ const useExpiry = (enterpriseId, budget, modalOpen, modalClose, alertOpen, alert
if (!isAlertDismissed) {
alertOpen();
}
}, [budget, modalOpen, alertOpen, enterpriseId, thresholdKey, threshold]);
}, [budget, modalOpen, alertOpen, enterpriseId, thresholdKey, threshold, hasExpiryNotificationsDisabled]);

const dismissModal = () => {
const seenCurrentExpirationModalCookieName = getEnterpriseBudgetExpiringModalCookieName({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,22 @@ import {
SEEN_ENTERPRISE_EXPIRATION_ALERT_COOKIE_PREFIX,
SEEN_ENTERPRISE_EXPIRATION_MODAL_COOKIE_PREFIX,
} from '../constants';
import { useEnterpriseCustomer } from '../../../app/data';
import { enterpriseCustomerFactory } from '../../../app/data/services/data/__factories__';

dayjs.extend(duration);

const modalOpen = jest.fn();
const modalClose = jest.fn();
const alertOpen = jest.fn();
const alertClose = jest.fn();
const mockEnterpriseCustomer = enterpriseCustomerFactory();

jest.mock('./useExpirationMetadata', () => jest.fn());
jest.mock('../../../app/data', () => ({
...jest.requireActual('../../../app/data'),
useEnterpriseCustomer: jest.fn(),
}));

const enterpriseUUID = 'fake-id';

Expand Down Expand Up @@ -51,6 +58,7 @@ const mock60Threshold = {
describe('useExpiry', () => {
beforeEach(() => {
jest.clearAllMocks();
useEnterpriseCustomer.mockReturnValue({ data: mockEnterpriseCustomer });
useExpirationMetadata.mockReturnValue({
thresholdKey: null,
threshold: null,
Expand All @@ -76,7 +84,7 @@ describe('useExpiry', () => {
isPlanApproachingExpiry: false,
});

const budget = { end: endDate }; // Mock data with an expiring budget
const budget = { end: endDate, isNonExpiredBudget: true }; // Mock data with an expiring budget
const { result } = renderHook(() => (
useExpiry(enterpriseUUID, budget, modalOpen, modalClose, alertOpen, alertClose)
));
Expand All @@ -98,4 +106,37 @@ describe('useExpiry', () => {
expect(alertLocalstorage).toBeTruthy();
expect(modalLocalstorage).toBeTruthy();
});

it.each([
{
thresholdKey: 60,
mock: mock60Threshold,
endDate: dayjs().add(60, 'day'),
},
{
thresholdKey: 30,
endDate: dayjs().add(30, 'day'),
mock: mock30Threshold,
},
])('displays no alert or modal when plan is expiring in %s days and disableExpiryMessagingForLearnerCredit is false', ({ thresholdKey, mock, endDate }) => {
useExpirationMetadata.mockReturnValue({
thresholdKey,
threshold: mock,
isPlanApproachingExpiry: false,
});
useEnterpriseCustomer.mockReturnValue({
data: {
...mockEnterpriseCustomer,
disableExpiryMessagingForLearnerCredit: true,
},
});

const budget = { end: endDate, isNonExpiredBudget: true }; // Mock data with an expiring budget
const { result } = renderHook(() => (
useExpiry(enterpriseUUID, budget, modalOpen, modalClose, alertOpen, alertClose)
));

expect(result.current.alert).toEqual(null);
expect(result.current.modal).toEqual(null);
});
});
7 changes: 6 additions & 1 deletion src/components/budget-expiry-notification/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
} from '@openedx/paragon';

import { sendEnterpriseTrackEvent } from '@edx/frontend-enterprise-utils';
import dayjs from 'dayjs';
import useExpiry from './data/hooks/useExpiry';
import { useEnterpriseCustomer, useHasAvailableSubsidiesOrRequests } from '../app/data';
import { EVENT_NAMES } from './data/constants';
Expand All @@ -17,7 +18,11 @@ const BudgetExpiryNotification = () => {
const [alertIsOpen, alertOpen, alertClose] = useToggle(false);
const { data: enterpriseCustomer } = useEnterpriseCustomer();
const { learnerCreditSummaryCardData } = useHasAvailableSubsidiesOrRequests();
const budget = useMemo(() => ({ end: learnerCreditSummaryCardData?.expirationDate }), [learnerCreditSummaryCardData]);
const budget = useMemo(() => ({
end: learnerCreditSummaryCardData?.expirationDate,
isNonExpiredBudget: dayjs(learnerCreditSummaryCardData?.expirationDate).isAfter(dayjs()),
}), [learnerCreditSummaryCardData]);

const {
alert, modal, dismissModal, dismissAlert,
} = useExpiry(
Expand Down
87 changes: 74 additions & 13 deletions src/components/dashboard/sidebar/LearnerCreditSummaryCard.jsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,71 @@
import React from 'react';
import React, { useMemo } from 'react';
import PropTypes from 'prop-types';
import { Badge } from '@openedx/paragon';
import dayjs from 'dayjs';
import { FormattedDate, FormattedMessage } from '@edx/frontend-platform/i18n';
import {
defineMessages, FormattedDate, FormattedMessage, useIntl,
} from '@edx/frontend-platform/i18n';
import SidebarCard from './SidebarCard';
import { useEnterpriseCustomer } from '../../app/data';
import { BUDGET_STATUSES } from '../data/constants';

const badgeStatusMessages = defineMessages({
active: {
id: 'enterprise.dashboard.sidebar.learner.credit.card.badge.active',
defaultMessage: 'Active',
description: 'Label for the active badge on the learner credit summary card on the enterprise dashboard sidebar.',
},
expired: {
id: 'enterprise.dashboard.sidebar.learner.credit.card.badge.expired',
defaultMessage: 'Expired',
description: 'Label for the expired badge on the learner credit summary card on the enterprise dashboard sidebar.',
},
expiring: {
id: 'enterprise.dashboard.sidebar.learner.credit.card.badge.expiring',
defaultMessage: 'Expiring',
description: 'Label for the expiring badge on the learner credit summary card on the enterprise dashboard sidebar.',
},
scheduled: {
id: 'enterprise.dashboard.sidebar.learner.credit.card.badge.scheduled',
defaultMessage: 'Scheduled',
description: 'Label for the scheduled badge on the learner credit summary card on the enterprise dashboard sidebar.',
},
retired: {
id: 'enterprise.dashboard.sidebar.learner.credit.card.badge.retired',
defaultMessage: 'Retired',
description: 'Label for the active retired on the learner credit summary card on the enterprise dashboard sidebar.',
},
});

/**
* If the disableExpiryMessagingForLearnerCredit configuration is true, we do not show the expiration badge variant,
* otherwise, display all other badge variants
* @param disableExpiryMessagingForLearnerCredit
* @param status
* @param badgeVariant
* @param intl
* @returns {React.JSX.Element|null}
*/
const conditionallyRenderCardBadge = ({
disableExpiryMessagingForLearnerCredit,
status,
badgeVariant,
intl,
}) => {
if (status === BUDGET_STATUSES.expiring && disableExpiryMessagingForLearnerCredit) {
return null;
}

return (
<Badge
variant={badgeVariant}
className="ml-2"
data-testid="learner-credit-status-badge"
>
{intl.formatMessage(badgeStatusMessages[status.toLowerCase()])}
</Badge>
);
};

const LearnerCreditSummaryCard = ({
className,
Expand All @@ -12,6 +74,15 @@ const LearnerCreditSummaryCard = ({
assignmentOnlyLearner,
}) => {
const { status, badgeVariant } = statusMetadata;
const { data: enterpriseCustomer } = useEnterpriseCustomer();
const intl = useIntl();

const cardBadge = useMemo(() => conditionallyRenderCardBadge({
disableExpiryMessagingForLearnerCredit: enterpriseCustomer.disableExpiryMessagingForLearnerCredit,
status,
badgeVariant,
intl,
}), [badgeVariant, enterpriseCustomer.disableExpiryMessagingForLearnerCredit, intl, status]);

return (
<SidebarCard
Expand All @@ -25,17 +96,7 @@ const LearnerCreditSummaryCard = ({
description="Title for the learner credit summary card on the enterprise dashboard sidebar."
/>
</h3>
<Badge
variant={badgeVariant}
className="ml-2"
data-testid="learner-credit-status-badge"
>
<FormattedMessage
id="enterprise.dashboard.sidebar.learner.credit.card.badge.active"
defaultMessage={status}
description="Label for the active badge on the learner credit summary card on the enterprise dashboard sidebar."
/>
</Badge>
{cardBadge}
</div>
)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,30 +2,47 @@ import React from 'react';
import '@testing-library/jest-dom/extend-expect';
import { render, screen } from '@testing-library/react';
import { IntlProvider } from '@edx/frontend-platform/i18n';
import { AppContext } from '@edx/frontend-platform/react';
import dayjs from 'dayjs';
import LearnerCreditSummaryCard from '../LearnerCreditSummaryCard';
import {
LEARNER_CREDIT_ASSIGNMENT_ONLY_SUMMARY,
LEARNER_CREDIT_CARD_SUMMARY,
LEARNER_CREDIT_SUMMARY_CARD_TITLE,
} from '../data/constants';
import { BUDGET_STATUSES } from '../../data';
import { useEnterpriseCustomer } from '../../../app/data';
import { authenticatedUserFactory, enterpriseCustomerFactory } from '../../../app/data/services/data/__factories__';

const TEST_EXPIRATION_DATE = '2022-06-01T00:00:00Z';

const TEST_EXPIRATION_DATE = dayjs().add(10, 'days').toISOString();
const TEST_EXPIRATION_DATE_TEXT = dayjs().add(10, 'days').format('MMM DD, YYYY');
const mockActiveStatusMetadata = {
status: BUDGET_STATUSES.active,
badgeVariant: 'success',
term: 'Expires',
date: TEST_EXPIRATION_DATE,
};
jest.mock('../../../app/data', () => ({
...jest.requireActual('../../../app/data'),
useEnterpriseCustomer: jest.fn(),
}));

const mockEnterpriseCustomer = enterpriseCustomerFactory();
const mockAuthenticatedUser = authenticatedUserFactory();

const LearnerCreditSummaryCardWrapper = (props) => (
<IntlProvider locale="en">
<LearnerCreditSummaryCard {...props} />
<AppContext.Provider value={{ authenticatedUser: mockAuthenticatedUser }}>
<LearnerCreditSummaryCard {...props} />
</AppContext.Provider>
</IntlProvider>
);

describe('<LearnerCreditSummaryCard />', () => {
beforeEach(() => {
jest.clearAllMocks();
useEnterpriseCustomer.mockReturnValue({ data: mockEnterpriseCustomer });
});
it('should render searchCoursesCta', () => {
render(
<LearnerCreditSummaryCardWrapper
Expand All @@ -46,7 +63,7 @@ describe('<LearnerCreditSummaryCard />', () => {
/>,
);
expect(screen.getByTestId('learner-credit-summary-end-date-text')).toBeInTheDocument();
expect(screen.getByText('2022', { exact: false })).toBeInTheDocument();
expect(screen.getByText(TEST_EXPIRATION_DATE_TEXT, { exact: false })).toBeInTheDocument();
});

it.each([{
Expand All @@ -66,4 +83,57 @@ describe('<LearnerCreditSummaryCard />', () => {
);
expect(screen.getByText(summaryText)).toBeInTheDocument();
});

it.each([{
activeStatusMetadata: {
status: BUDGET_STATUSES.expiring,
badgeVariant: 'warning',
},
disableExpiryMessagingForLearnerCredit: false,
},
{
activeStatusMetadata: {
status: BUDGET_STATUSES.expiring,
badgeVariant: 'warning',
},
disableExpiryMessagingForLearnerCredit: true,
},
{
activeStatusMetadata: {
status: BUDGET_STATUSES.expired,
badgeVariant: 'danger',
},
disableExpiryMessagingForLearnerCredit: false,
},
{
activeStatusMetadata: {
status: BUDGET_STATUSES.expired,
badgeVariant: 'danger',
},
disableExpiryMessagingForLearnerCredit: true,
}])('should not display "Expiring" badge if disableExpiryMessagingForLearnerCredit is true', ({
activeStatusMetadata,
disableExpiryMessagingForLearnerCredit,
}) => {
useEnterpriseCustomer.mockReturnValue({
data: {
...mockEnterpriseCustomer,
disableExpiryMessagingForLearnerCredit,
},
});
render(
<LearnerCreditSummaryCardWrapper
expirationDate={TEST_EXPIRATION_DATE}
statusMetadata={activeStatusMetadata}
assignmentOnlyLearner
/>,
);
expect(screen.getByTestId('learner-credit-summary-end-date-text')).toBeInTheDocument();
expect(screen.getByText(TEST_EXPIRATION_DATE_TEXT, { exact: false })).toBeInTheDocument();
if (disableExpiryMessagingForLearnerCredit && activeStatusMetadata.status === BUDGET_STATUSES.expiring) {
expect(screen.queryByText(activeStatusMetadata.status)).not.toBeInTheDocument();
} else {
expect(screen.queryByText(activeStatusMetadata.status)).toBeInTheDocument();
}
});
});
Loading